matchify 0.0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- matchify/__init__.py +11 -0
- matchify/__main__.py +6 -0
- matchify/access_path.py +285 -0
- matchify/assumptions.py +58 -0
- matchify/capture_patterns.py +98 -0
- matchify/cli.py +193 -0
- matchify/compiler.py +253 -0
- matchify/conditions.py +492 -0
- matchify/facts.py +356 -0
- matchify/pattern_builder.py +381 -0
- matchify/patterns.py +164 -0
- matchify/safety.py +69 -0
- matchify/transform.py +138 -0
- matchify-0.0.1.dist-info/METADATA +247 -0
- matchify-0.0.1.dist-info/RECORD +17 -0
- matchify-0.0.1.dist-info/WHEEL +4 -0
- matchify-0.0.1.dist-info/entry_points.txt +2 -0
matchify/__init__.py
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"""Public API for matchify."""
|
|
2
|
+
|
|
3
|
+
from .cli import collect_python_files, convert_file
|
|
4
|
+
from .transform import IfToMatchTransformer, transform_code
|
|
5
|
+
|
|
6
|
+
__all__ = [
|
|
7
|
+
"IfToMatchTransformer",
|
|
8
|
+
"collect_python_files",
|
|
9
|
+
"convert_file",
|
|
10
|
+
"transform_code",
|
|
11
|
+
]
|
matchify/__main__.py
ADDED
matchify/access_path.py
ADDED
|
@@ -0,0 +1,285 @@
|
|
|
1
|
+
"""Absolute and match-subject-bound expression access paths."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
|
|
7
|
+
import libcst as cst
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def extract_integer_subscript_index(subscript: cst.Subscript) -> int | None:
|
|
11
|
+
"""Return the integer index for simple subscripts like `x[0]`."""
|
|
12
|
+
if len(subscript.slice) != 1:
|
|
13
|
+
return None
|
|
14
|
+
slice_elem = subscript.slice[0]
|
|
15
|
+
if not isinstance(slice_elem.slice, cst.Index):
|
|
16
|
+
return None
|
|
17
|
+
index_val = slice_elem.slice.value
|
|
18
|
+
if not isinstance(index_val, cst.Integer):
|
|
19
|
+
return None
|
|
20
|
+
return int(index_val.value)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass(frozen=True)
|
|
24
|
+
class AttributePathPart:
|
|
25
|
+
name: str
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass(frozen=True)
|
|
29
|
+
class SubscriptPathPart:
|
|
30
|
+
index: int | None
|
|
31
|
+
expression_key: str | None = None
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass(frozen=True)
|
|
35
|
+
class NameRoot:
|
|
36
|
+
"""Root of an access path that has not been bound to a match subject."""
|
|
37
|
+
|
|
38
|
+
name: str
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclass(frozen=True)
|
|
42
|
+
class MatchSubjectRoot:
|
|
43
|
+
"""Root of an access path bound to one match subject."""
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@dataclass(frozen=True)
|
|
47
|
+
class ExpressionRoot:
|
|
48
|
+
"""Root expression that is not a plain name, compared by source shape."""
|
|
49
|
+
|
|
50
|
+
code: str
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
PathRoot = NameRoot | ExpressionRoot | MatchSubjectRoot
|
|
54
|
+
AccessPathPart = AttributePathPart | SubscriptPathPart
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@dataclass(frozen=True)
|
|
58
|
+
class AccessPath:
|
|
59
|
+
"""A statically representable expression access path.
|
|
60
|
+
|
|
61
|
+
Examples:
|
|
62
|
+
node -> NameRoot("node"), ()
|
|
63
|
+
node.value -> NameRoot("node"), (AttributePathPart("value"),)
|
|
64
|
+
bound node.value -> MatchSubjectRoot(), (AttributePathPart("value"),)
|
|
65
|
+
"""
|
|
66
|
+
|
|
67
|
+
root: PathRoot
|
|
68
|
+
parts: tuple[AccessPathPart, ...] = ()
|
|
69
|
+
|
|
70
|
+
@classmethod
|
|
71
|
+
def from_expression(cls, node: cst.BaseExpression) -> AccessPath:
|
|
72
|
+
parts: list[AccessPathPart] = []
|
|
73
|
+
current = node
|
|
74
|
+
|
|
75
|
+
while True:
|
|
76
|
+
if isinstance(current, cst.Name):
|
|
77
|
+
return cls(NameRoot(current.value), tuple(reversed(parts)))
|
|
78
|
+
if isinstance(current, cst.Attribute):
|
|
79
|
+
parts.append(AttributePathPart(current.attr.value))
|
|
80
|
+
current = current.value
|
|
81
|
+
continue
|
|
82
|
+
if isinstance(current, cst.Subscript):
|
|
83
|
+
index = extract_integer_subscript_index(current)
|
|
84
|
+
parts.append(
|
|
85
|
+
SubscriptPathPart(
|
|
86
|
+
index,
|
|
87
|
+
expression_key=(
|
|
88
|
+
None
|
|
89
|
+
if index is not None
|
|
90
|
+
else cst.Module([]).code_for_node(current)
|
|
91
|
+
),
|
|
92
|
+
)
|
|
93
|
+
)
|
|
94
|
+
current = current.value
|
|
95
|
+
continue
|
|
96
|
+
return cls(
|
|
97
|
+
ExpressionRoot(cst.Module([]).code_for_node(current)),
|
|
98
|
+
tuple(reversed(parts)),
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
def bind(
|
|
102
|
+
self,
|
|
103
|
+
subject: AccessPath,
|
|
104
|
+
target: tuple[AccessPathPart, ...] = (),
|
|
105
|
+
) -> AccessPath:
|
|
106
|
+
"""Replace a matching subject prefix with a bound target prefix."""
|
|
107
|
+
if not self.starts_with(subject):
|
|
108
|
+
return self
|
|
109
|
+
return AccessPath(
|
|
110
|
+
MatchSubjectRoot(),
|
|
111
|
+
(*target, *self.parts[len(subject.parts) :]),
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
@classmethod
|
|
115
|
+
def common_prefix(cls, paths: tuple[AccessPath, ...]) -> AccessPath | None:
|
|
116
|
+
if not paths or any(path.root != paths[0].root for path in paths[1:]):
|
|
117
|
+
return None
|
|
118
|
+
common_parts = []
|
|
119
|
+
for parts in zip(*(path.parts for path in paths)):
|
|
120
|
+
if any(part != parts[0] for part in parts[1:]):
|
|
121
|
+
break
|
|
122
|
+
common_parts.append(parts[0])
|
|
123
|
+
return cls(paths[0].root, tuple(common_parts))
|
|
124
|
+
|
|
125
|
+
def to_expression(self) -> cst.BaseExpression:
|
|
126
|
+
"""Build fresh CST for an unbound access path."""
|
|
127
|
+
if isinstance(self.root, NameRoot):
|
|
128
|
+
expression: cst.BaseExpression = cst.Name(self.root.name)
|
|
129
|
+
elif isinstance(self.root, ExpressionRoot):
|
|
130
|
+
expression = cst.parse_expression(self.root.code)
|
|
131
|
+
else:
|
|
132
|
+
raise ValueError("A bound access path cannot be rendered as a subject")
|
|
133
|
+
|
|
134
|
+
for part in self.parts:
|
|
135
|
+
if isinstance(part, AttributePathPart):
|
|
136
|
+
expression = cst.Attribute(value=expression, attr=cst.Name(part.name))
|
|
137
|
+
elif part.index is not None:
|
|
138
|
+
expression = cst.Subscript(
|
|
139
|
+
value=expression,
|
|
140
|
+
slice=[
|
|
141
|
+
cst.SubscriptElement(
|
|
142
|
+
slice=cst.Index(cst.Integer(str(part.index)))
|
|
143
|
+
)
|
|
144
|
+
],
|
|
145
|
+
)
|
|
146
|
+
elif part.expression_key is not None:
|
|
147
|
+
expression = cst.parse_expression(part.expression_key)
|
|
148
|
+
else: # pragma: no cover
|
|
149
|
+
raise ValueError("An unknown subscript needs an expression key")
|
|
150
|
+
return expression
|
|
151
|
+
|
|
152
|
+
@property
|
|
153
|
+
def is_bound(self) -> bool:
|
|
154
|
+
return isinstance(self.root, MatchSubjectRoot)
|
|
155
|
+
|
|
156
|
+
@property
|
|
157
|
+
def is_subject(self) -> bool:
|
|
158
|
+
return self.is_bound and not self.parts
|
|
159
|
+
|
|
160
|
+
@property
|
|
161
|
+
def is_patternable(self) -> bool:
|
|
162
|
+
return self.is_bound and all(
|
|
163
|
+
not isinstance(part, SubscriptPathPart) or part.index is not None
|
|
164
|
+
for part in self.parts
|
|
165
|
+
)
|
|
166
|
+
|
|
167
|
+
@property
|
|
168
|
+
def contains_subscript(self) -> bool:
|
|
169
|
+
return any(isinstance(part, SubscriptPathPart) for part in self.parts)
|
|
170
|
+
|
|
171
|
+
@property
|
|
172
|
+
def first_part(self) -> AccessPathPart | None:
|
|
173
|
+
return self.parts[0] if self.parts else None
|
|
174
|
+
|
|
175
|
+
def tail(self) -> AccessPath:
|
|
176
|
+
return AccessPath(self.root, self.parts[1:])
|
|
177
|
+
|
|
178
|
+
def parent(self) -> AccessPath:
|
|
179
|
+
return AccessPath(self.root, self.parts[:-1])
|
|
180
|
+
|
|
181
|
+
def starts_with(self, prefix: AccessPath) -> bool:
|
|
182
|
+
return (
|
|
183
|
+
self.root == prefix.root and self.parts[: len(prefix.parts)] == prefix.parts
|
|
184
|
+
)
|
|
185
|
+
|
|
186
|
+
def strip_prefix(self, prefix: AccessPath) -> AccessPath:
|
|
187
|
+
if not self.starts_with(prefix):
|
|
188
|
+
raise ValueError("Cannot strip a path that is not a prefix")
|
|
189
|
+
return AccessPath(self.root, self.parts[len(prefix.parts) :])
|
|
190
|
+
|
|
191
|
+
def first_part_after(self, prefix: AccessPath) -> AccessPathPart | None:
|
|
192
|
+
if not self.starts_with(prefix):
|
|
193
|
+
return None
|
|
194
|
+
index = len(prefix.parts)
|
|
195
|
+
return self.parts[index] if index < len(self.parts) else None
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
@dataclass(frozen=True)
|
|
199
|
+
class MatchSubjectPlan:
|
|
200
|
+
"""Ordered subjects and their relative locations in one match value."""
|
|
201
|
+
|
|
202
|
+
subjects: tuple[AccessPath, ...]
|
|
203
|
+
|
|
204
|
+
@classmethod
|
|
205
|
+
def from_subjects(cls, subjects: tuple[AccessPath, ...]) -> MatchSubjectPlan:
|
|
206
|
+
if not subjects:
|
|
207
|
+
raise ValueError("A match subject plan needs at least one subject")
|
|
208
|
+
for index, subject in enumerate(subjects):
|
|
209
|
+
if any(
|
|
210
|
+
subject.starts_with(other) or other.starts_with(subject)
|
|
211
|
+
for other in subjects[index + 1 :]
|
|
212
|
+
):
|
|
213
|
+
raise ValueError("Match subjects must not overlap")
|
|
214
|
+
return cls(subjects)
|
|
215
|
+
|
|
216
|
+
@classmethod
|
|
217
|
+
def from_aligned_candidates(
|
|
218
|
+
cls, candidates: tuple[tuple[AccessPath, ...], ...]
|
|
219
|
+
) -> MatchSubjectPlan | None:
|
|
220
|
+
if not candidates or not candidates[0]:
|
|
221
|
+
return None
|
|
222
|
+
size = len(candidates[0])
|
|
223
|
+
if any(len(paths) != size for paths in candidates[1:]):
|
|
224
|
+
return None
|
|
225
|
+
subjects = tuple(
|
|
226
|
+
AccessPath.common_prefix(tuple(paths[index] for paths in candidates))
|
|
227
|
+
for index in range(size)
|
|
228
|
+
)
|
|
229
|
+
if any(subject is None for subject in subjects):
|
|
230
|
+
return None
|
|
231
|
+
return cls._from_optional_subjects(subjects)
|
|
232
|
+
|
|
233
|
+
@classmethod
|
|
234
|
+
def from_shared_candidates(
|
|
235
|
+
cls, candidates: tuple[tuple[AccessPath, ...], ...]
|
|
236
|
+
) -> MatchSubjectPlan | None:
|
|
237
|
+
if not candidates or not candidates[0]:
|
|
238
|
+
return None
|
|
239
|
+
subjects = []
|
|
240
|
+
for first in candidates[0]:
|
|
241
|
+
if any(subject.root == first.root for subject in subjects):
|
|
242
|
+
continue
|
|
243
|
+
matching_groups = tuple(
|
|
244
|
+
tuple(path for path in paths if path.root == first.root)
|
|
245
|
+
for paths in candidates
|
|
246
|
+
)
|
|
247
|
+
if any(not group for group in matching_groups):
|
|
248
|
+
continue
|
|
249
|
+
subject = AccessPath.common_prefix(
|
|
250
|
+
tuple(path for group in matching_groups for path in group)
|
|
251
|
+
)
|
|
252
|
+
if subject is not None:
|
|
253
|
+
subjects.append(subject)
|
|
254
|
+
return cls._from_optional_subjects(tuple(subjects))
|
|
255
|
+
|
|
256
|
+
@classmethod
|
|
257
|
+
def _from_optional_subjects(
|
|
258
|
+
cls, subjects: tuple[AccessPath | None, ...]
|
|
259
|
+
) -> MatchSubjectPlan | None:
|
|
260
|
+
concrete = tuple(subject for subject in subjects if subject is not None)
|
|
261
|
+
if len(concrete) != len(subjects) or not concrete:
|
|
262
|
+
return None
|
|
263
|
+
try:
|
|
264
|
+
return cls.from_subjects(concrete)
|
|
265
|
+
except ValueError:
|
|
266
|
+
return None
|
|
267
|
+
|
|
268
|
+
@property
|
|
269
|
+
def is_composite(self) -> bool:
|
|
270
|
+
return len(self.subjects) > 1
|
|
271
|
+
|
|
272
|
+
def bind(self, path: AccessPath) -> AccessPath:
|
|
273
|
+
for index, subject in enumerate(self.subjects):
|
|
274
|
+
if path.starts_with(subject):
|
|
275
|
+
target = () if not self.is_composite else (SubscriptPathPart(index),)
|
|
276
|
+
return path.bind(subject, target)
|
|
277
|
+
return path
|
|
278
|
+
|
|
279
|
+
def to_expression(self) -> cst.BaseExpression:
|
|
280
|
+
expressions = tuple(subject.to_expression() for subject in self.subjects)
|
|
281
|
+
if len(expressions) == 1:
|
|
282
|
+
return expressions[0]
|
|
283
|
+
return cst.Tuple(
|
|
284
|
+
elements=[cst.Element(expression) for expression in expressions]
|
|
285
|
+
)
|
matchify/assumptions.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"""Risky transformation assumptions."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Iterable
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
|
|
6
|
+
PURE_SUBJECTS = "pure-subjects"
|
|
7
|
+
USE_OBJECT = "use-object"
|
|
8
|
+
|
|
9
|
+
ALL_RISKY_ASSUMPTIONS = frozenset({PURE_SUBJECTS, USE_OBJECT})
|
|
10
|
+
DEFAULT_ASSUMPTIONS = frozenset[str]()
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass(frozen=True)
|
|
14
|
+
class AssumptionDiagnostic:
|
|
15
|
+
"""A skipped conversion that needs risky assumptions."""
|
|
16
|
+
|
|
17
|
+
line: int
|
|
18
|
+
column: int
|
|
19
|
+
assumptions: frozenset[str]
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass(frozen=True)
|
|
23
|
+
class Assumptions:
|
|
24
|
+
"""Enabled risky transformation assumptions."""
|
|
25
|
+
|
|
26
|
+
names: frozenset[str] = DEFAULT_ASSUMPTIONS
|
|
27
|
+
|
|
28
|
+
@classmethod
|
|
29
|
+
def from_names(cls, names: Iterable[str] | None = None) -> "Assumptions":
|
|
30
|
+
resolved = DEFAULT_ASSUMPTIONS if names is None else frozenset(names)
|
|
31
|
+
unknown = resolved - ALL_RISKY_ASSUMPTIONS
|
|
32
|
+
if unknown:
|
|
33
|
+
names_list = ", ".join(sorted(unknown))
|
|
34
|
+
raise ValueError(f"Unknown risky assumption: {names_list}")
|
|
35
|
+
return cls(resolved)
|
|
36
|
+
|
|
37
|
+
@classmethod
|
|
38
|
+
def risky(cls) -> "Assumptions":
|
|
39
|
+
return cls(ALL_RISKY_ASSUMPTIONS)
|
|
40
|
+
|
|
41
|
+
@classmethod
|
|
42
|
+
def safe(cls) -> "Assumptions":
|
|
43
|
+
return cls(frozenset())
|
|
44
|
+
|
|
45
|
+
@property
|
|
46
|
+
def assume_pure_subjects(self) -> bool:
|
|
47
|
+
return PURE_SUBJECTS in self.names
|
|
48
|
+
|
|
49
|
+
@property
|
|
50
|
+
def use_object(self) -> bool:
|
|
51
|
+
return USE_OBJECT in self.names
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def parse_assumption_names(value: str) -> frozenset[str]:
|
|
55
|
+
"""Parse a comma-separated assumption list."""
|
|
56
|
+
names = frozenset(name.strip() for name in value.split(",") if name.strip())
|
|
57
|
+
Assumptions.from_names(names)
|
|
58
|
+
return names
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
"""Capture assignment helpers for compiled match cases."""
|
|
2
|
+
|
|
3
|
+
import libcst as cst
|
|
4
|
+
|
|
5
|
+
from .access_path import AccessPath, MatchSubjectPlan, extract_integer_subscript_index
|
|
6
|
+
from .facts import CaptureFact
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def detect_captures(
|
|
10
|
+
body: cst.IndentedBlock, subject: MatchSubjectPlan
|
|
11
|
+
) -> tuple[CaptureFact, ...]:
|
|
12
|
+
captures = []
|
|
13
|
+
|
|
14
|
+
for stmt in body.body:
|
|
15
|
+
if not isinstance(stmt, cst.SimpleStatementLine):
|
|
16
|
+
break
|
|
17
|
+
if len(stmt.body) != 1 or not isinstance(stmt.body[0], cst.Assign):
|
|
18
|
+
break
|
|
19
|
+
|
|
20
|
+
assign = stmt.body[0]
|
|
21
|
+
if len(assign.targets) != 1:
|
|
22
|
+
break
|
|
23
|
+
|
|
24
|
+
target = assign.targets[0].target
|
|
25
|
+
if not isinstance(target, cst.Name):
|
|
26
|
+
break
|
|
27
|
+
|
|
28
|
+
if not isinstance(assign.value, cst.Subscript):
|
|
29
|
+
break
|
|
30
|
+
|
|
31
|
+
path = AccessPath.from_expression(assign.value.value)
|
|
32
|
+
path = subject.bind(path)
|
|
33
|
+
if not path.is_bound:
|
|
34
|
+
break
|
|
35
|
+
index = extract_integer_subscript_index(assign.value)
|
|
36
|
+
if index is None:
|
|
37
|
+
break
|
|
38
|
+
|
|
39
|
+
captures.append(CaptureFact(name=target.value, path=path, index=index))
|
|
40
|
+
|
|
41
|
+
return tuple(captures)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def normalize_duplicate_captures(
|
|
45
|
+
captures: tuple[CaptureFact, ...],
|
|
46
|
+
) -> tuple[tuple[CaptureFact, ...], tuple[tuple[str, str], ...]]:
|
|
47
|
+
"""Keep one pattern capture per source index and alias later duplicates."""
|
|
48
|
+
seen: dict[tuple[AccessPath, int], str] = {}
|
|
49
|
+
unique_captures = []
|
|
50
|
+
aliases = []
|
|
51
|
+
|
|
52
|
+
for capture in captures:
|
|
53
|
+
key = (capture.path, capture.index)
|
|
54
|
+
if key in seen:
|
|
55
|
+
aliases.append((capture.name, seen[key]))
|
|
56
|
+
continue
|
|
57
|
+
seen[key] = capture.name
|
|
58
|
+
unique_captures.append(capture)
|
|
59
|
+
|
|
60
|
+
return tuple(unique_captures), tuple(aliases)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def remove_statements(body: cst.IndentedBlock, count: int) -> cst.IndentedBlock:
|
|
64
|
+
if len(body.body) <= count:
|
|
65
|
+
return body.with_changes(body=[cst.SimpleStatementLine(body=[cst.Pass()])])
|
|
66
|
+
return body.with_changes(body=body.body[count:])
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def prepend_aliases(
|
|
70
|
+
body: cst.IndentedBlock, aliases: tuple[tuple[str, str], ...]
|
|
71
|
+
) -> cst.IndentedBlock:
|
|
72
|
+
alias_statements = [
|
|
73
|
+
cst.SimpleStatementLine(
|
|
74
|
+
body=[
|
|
75
|
+
cst.Assign(
|
|
76
|
+
targets=[cst.AssignTarget(target=cst.Name(alias_name))],
|
|
77
|
+
value=cst.Name(source_name),
|
|
78
|
+
)
|
|
79
|
+
]
|
|
80
|
+
)
|
|
81
|
+
for alias_name, source_name in aliases
|
|
82
|
+
]
|
|
83
|
+
|
|
84
|
+
if body_is_pass(body):
|
|
85
|
+
return body.with_changes(body=alias_statements)
|
|
86
|
+
|
|
87
|
+
return body.with_changes(body=[*alias_statements, *body.body])
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def body_is_pass(body: cst.IndentedBlock) -> bool:
|
|
91
|
+
if len(body.body) != 1:
|
|
92
|
+
return False
|
|
93
|
+
statement = body.body[0]
|
|
94
|
+
return (
|
|
95
|
+
isinstance(statement, cst.SimpleStatementLine)
|
|
96
|
+
and len(statement.body) == 1
|
|
97
|
+
and isinstance(statement.body[0], cst.Pass)
|
|
98
|
+
)
|
matchify/cli.py
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
"""Command-line and file processing helpers."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import pathlib
|
|
5
|
+
from concurrent.futures import ProcessPoolExecutor
|
|
6
|
+
from functools import partial
|
|
7
|
+
|
|
8
|
+
from .assumptions import (
|
|
9
|
+
ALL_RISKY_ASSUMPTIONS,
|
|
10
|
+
AssumptionDiagnostic,
|
|
11
|
+
Assumptions,
|
|
12
|
+
parse_assumption_names,
|
|
13
|
+
)
|
|
14
|
+
from .transform import transform_code
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def convert_file(
|
|
18
|
+
path: pathlib.Path,
|
|
19
|
+
ignore_types_pattern: str | None = None,
|
|
20
|
+
*,
|
|
21
|
+
assumptions: Assumptions | None = None,
|
|
22
|
+
assume_pure_subjects: bool = False,
|
|
23
|
+
report_assumption_diagnostics: bool = False,
|
|
24
|
+
) -> tuple[pathlib.Path, bool, str | None]:
|
|
25
|
+
"""Convert a single file.
|
|
26
|
+
|
|
27
|
+
Returns:
|
|
28
|
+
Tuple of (path, changed, error_message)
|
|
29
|
+
"""
|
|
30
|
+
try:
|
|
31
|
+
source = path.read_text(encoding="utf-8")
|
|
32
|
+
diagnostics: list[AssumptionDiagnostic] = []
|
|
33
|
+
transformed_code = transform_code(
|
|
34
|
+
source,
|
|
35
|
+
ignore_types_pattern=ignore_types_pattern,
|
|
36
|
+
assumptions=assumptions,
|
|
37
|
+
assume_pure_subjects=assume_pure_subjects,
|
|
38
|
+
diagnostics=diagnostics,
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
if report_assumption_diagnostics:
|
|
42
|
+
report_assumption_requirements(path, diagnostics)
|
|
43
|
+
if transformed_code != source:
|
|
44
|
+
path.write_text(transformed_code, encoding="utf-8")
|
|
45
|
+
return (path, True, None)
|
|
46
|
+
return (path, False, None)
|
|
47
|
+
except Exception as e:
|
|
48
|
+
return (path, False, str(e))
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def collect_python_files(paths: list[pathlib.Path]) -> list[pathlib.Path]:
|
|
52
|
+
"""Collect all Python files from the given paths."""
|
|
53
|
+
python_files = []
|
|
54
|
+
for arg in paths:
|
|
55
|
+
if arg.is_file() and arg.suffix == ".py":
|
|
56
|
+
python_files.append(arg)
|
|
57
|
+
elif arg.is_dir():
|
|
58
|
+
python_files.extend(arg.rglob("*.py"))
|
|
59
|
+
else:
|
|
60
|
+
print(f"Skipping (not a Python file): {arg}")
|
|
61
|
+
return python_files
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def resolve_assumptions(args: argparse.Namespace) -> Assumptions:
|
|
65
|
+
"""Resolve CLI assumption flags into an assumption set."""
|
|
66
|
+
if args.risky:
|
|
67
|
+
return Assumptions.risky()
|
|
68
|
+
if args.safe_assumptions:
|
|
69
|
+
return Assumptions.safe()
|
|
70
|
+
if args.assume is not None:
|
|
71
|
+
return Assumptions.from_names(parse_assumption_names(args.assume))
|
|
72
|
+
return Assumptions.from_names()
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def report_assumption_requirements(
|
|
76
|
+
path: pathlib.Path, diagnostics: list[AssumptionDiagnostic]
|
|
77
|
+
) -> None:
|
|
78
|
+
"""Print skipped conversions that require risky assumptions."""
|
|
79
|
+
for diagnostic in diagnostics:
|
|
80
|
+
assumptions = ",".join(sorted(diagnostic.assumptions))
|
|
81
|
+
print(
|
|
82
|
+
f"Info: {path}:{diagnostic.line}:{diagnostic.column + 1}: "
|
|
83
|
+
f"if/elif chain requires --assume {assumptions}"
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def report_result(
|
|
88
|
+
path: pathlib.Path, changed: bool, error: str | None, verbose: bool
|
|
89
|
+
) -> tuple[int, int, int]:
|
|
90
|
+
if error:
|
|
91
|
+
print(f"Error processing {path}: {error}")
|
|
92
|
+
return (0, 0, 1)
|
|
93
|
+
if changed:
|
|
94
|
+
print(f"Converted: {path}")
|
|
95
|
+
return (1, 0, 0)
|
|
96
|
+
if verbose:
|
|
97
|
+
print(f"No changes: {path}")
|
|
98
|
+
return (0, 1, 0)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def main() -> None:
|
|
102
|
+
parser = argparse.ArgumentParser(
|
|
103
|
+
description="Convert if/elif/else chains to Python 3.10+ match statements"
|
|
104
|
+
)
|
|
105
|
+
parser.add_argument(
|
|
106
|
+
"paths",
|
|
107
|
+
nargs="+",
|
|
108
|
+
type=pathlib.Path,
|
|
109
|
+
help="Python files or directories to process",
|
|
110
|
+
)
|
|
111
|
+
assumption_group = parser.add_mutually_exclusive_group()
|
|
112
|
+
assumption_group.add_argument(
|
|
113
|
+
"--assume",
|
|
114
|
+
metavar="NAMES",
|
|
115
|
+
help=(
|
|
116
|
+
"Comma-separated risky assumptions to enable "
|
|
117
|
+
f"(available: {', '.join(sorted(ALL_RISKY_ASSUMPTIONS))})"
|
|
118
|
+
),
|
|
119
|
+
)
|
|
120
|
+
assumption_group.add_argument(
|
|
121
|
+
"--safe",
|
|
122
|
+
dest="safe_assumptions",
|
|
123
|
+
action="store_true",
|
|
124
|
+
help="Disable all risky assumptions",
|
|
125
|
+
)
|
|
126
|
+
assumption_group.add_argument(
|
|
127
|
+
"--risky",
|
|
128
|
+
action="store_true",
|
|
129
|
+
help="Enable all risky assumptions",
|
|
130
|
+
)
|
|
131
|
+
parser.add_argument(
|
|
132
|
+
"-j",
|
|
133
|
+
"--jobs",
|
|
134
|
+
type=int,
|
|
135
|
+
default=None,
|
|
136
|
+
help="Number of parallel jobs (default: number of CPU cores)",
|
|
137
|
+
)
|
|
138
|
+
parser.add_argument(
|
|
139
|
+
"-v", "--verbose", action="store_true", help="Show files with no changes"
|
|
140
|
+
)
|
|
141
|
+
parser.add_argument(
|
|
142
|
+
"--no-types",
|
|
143
|
+
type=str,
|
|
144
|
+
default=r".*_TYPES$",
|
|
145
|
+
help="Regex pattern for isinstance type variables to ignore (default: .*_TYPES$)",
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
args = parser.parse_args()
|
|
149
|
+
try:
|
|
150
|
+
assumptions = resolve_assumptions(args)
|
|
151
|
+
except ValueError as error:
|
|
152
|
+
parser.error(str(error))
|
|
153
|
+
|
|
154
|
+
python_files = collect_python_files(args.paths)
|
|
155
|
+
|
|
156
|
+
if not python_files:
|
|
157
|
+
print("No Python files found to process")
|
|
158
|
+
return
|
|
159
|
+
|
|
160
|
+
converted_count = 0
|
|
161
|
+
unchanged_count = 0
|
|
162
|
+
error_count = 0
|
|
163
|
+
|
|
164
|
+
if len(python_files) == 1:
|
|
165
|
+
result = convert_file(
|
|
166
|
+
python_files[0],
|
|
167
|
+
ignore_types_pattern=args.no_types,
|
|
168
|
+
assumptions=assumptions,
|
|
169
|
+
report_assumption_diagnostics=True,
|
|
170
|
+
)
|
|
171
|
+
converted, unchanged, errors = report_result(*result, verbose=args.verbose)
|
|
172
|
+
converted_count += converted
|
|
173
|
+
unchanged_count += unchanged
|
|
174
|
+
error_count += errors
|
|
175
|
+
else:
|
|
176
|
+
with ProcessPoolExecutor(max_workers=args.jobs or None) as executor:
|
|
177
|
+
convert = partial(
|
|
178
|
+
convert_file,
|
|
179
|
+
ignore_types_pattern=args.no_types,
|
|
180
|
+
assumptions=assumptions,
|
|
181
|
+
report_assumption_diagnostics=True,
|
|
182
|
+
)
|
|
183
|
+
for result in executor.map(convert, python_files):
|
|
184
|
+
converted, unchanged, errors = report_result(
|
|
185
|
+
*result, verbose=args.verbose
|
|
186
|
+
)
|
|
187
|
+
converted_count += converted
|
|
188
|
+
unchanged_count += unchanged
|
|
189
|
+
error_count += errors
|
|
190
|
+
|
|
191
|
+
print(
|
|
192
|
+
f"\nSummary: {converted_count} converted, {unchanged_count} unchanged, {error_count} errors"
|
|
193
|
+
)
|