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/compiler.py ADDED
@@ -0,0 +1,253 @@
1
+ """Normalize if/elif chains and compile them to match statements."""
2
+
3
+ from collections.abc import Sequence
4
+ from typing import NamedTuple
5
+
6
+ import libcst as cst
7
+
8
+ from .access_path import MatchSubjectPlan
9
+ from .assumptions import PURE_SUBJECTS, Assumptions
10
+ from .capture_patterns import (
11
+ detect_captures,
12
+ normalize_duplicate_captures,
13
+ prepend_aliases,
14
+ remove_statements,
15
+ )
16
+ from .conditions import (
17
+ BoolExpr,
18
+ parse_condition,
19
+ select_assumed_pure_subject_paths,
20
+ )
21
+ from .facts import BranchFacts
22
+ from .pattern_builder import normalize_condition
23
+ from .patterns import build_wildcard_pattern
24
+ from .safety import is_safe_condition
25
+
26
+
27
+ class IfBranch(NamedTuple):
28
+ """One if/elif branch in a convertible chain."""
29
+
30
+ body: cst.IndentedBlock
31
+ leading_lines: tuple[cst.EmptyLine, ...]
32
+ facts: BranchFacts
33
+
34
+ @property
35
+ def is_wildcard_case(self) -> bool:
36
+ """Whether this branch compiles to `case _`."""
37
+ return self.facts.pattern is None
38
+
39
+
40
+ class IfChain(NamedTuple):
41
+ """A normalized if/elif/else chain, independent from LibCST navigation quirks."""
42
+
43
+ subject: MatchSubjectPlan
44
+ branches: tuple[IfBranch, ...]
45
+ else_body: cst.IndentedBlock | None
46
+ else_leading_lines: tuple[cst.EmptyLine, ...]
47
+
48
+
49
+ class ParsedBranch(NamedTuple):
50
+ """One branch before its access paths are bound to a match subject."""
51
+
52
+ test: cst.BaseExpression
53
+ condition: BoolExpr
54
+ body: cst.IndentedBlock
55
+ leading_lines: tuple[cst.EmptyLine, ...]
56
+
57
+
58
+ class IfChainCompiler:
59
+ """Analyze an if-chain once, then compile it to a match statement.
60
+
61
+ The compiler is deliberately guard-first:
62
+ every branch starts as `case _ if <original condition>`, and optimizers may
63
+ move proven-safe pieces into the pattern. That makes unsupported constructs
64
+ fail closed instead of silently dropping conditions.
65
+ """
66
+
67
+ def __init__(
68
+ self,
69
+ ignore_types_pattern: str | None = r".*_TYPES$",
70
+ *,
71
+ assumptions: Assumptions | None = None,
72
+ assume_pure_subjects: bool = False,
73
+ ) -> None:
74
+ self.ignore_types_pattern = ignore_types_pattern
75
+ self.assumptions = assumptions or Assumptions.from_names()
76
+ if assume_pure_subjects:
77
+ self.assumptions = Assumptions.from_names(
78
+ (*self.assumptions.names, PURE_SUBJECTS)
79
+ )
80
+
81
+ def extract_chain(self, node: cst.If) -> IfChain | None:
82
+ if not isinstance(node.orelse, cst.If):
83
+ return None
84
+
85
+ parsed_branches: list[ParsedBranch] = []
86
+ current = node
87
+ while True:
88
+ leading_lines = () if current is node else current.leading_lines
89
+ parsed_branches.append(
90
+ ParsedBranch(
91
+ current.test,
92
+ parse_condition(current.test, self.ignore_types_pattern),
93
+ current.body,
94
+ leading_lines,
95
+ )
96
+ )
97
+
98
+ if isinstance(current.orelse, cst.If):
99
+ current = current.orelse
100
+ continue
101
+ if isinstance(current.orelse, cst.Else):
102
+ else_body = current.orelse.body
103
+ else_leading_lines = current.orelse.leading_lines
104
+ else:
105
+ else_body = None
106
+ else_leading_lines = ()
107
+ break
108
+
109
+ subject = self._select_chain_subject(parsed_branches)
110
+ if subject is None:
111
+ return None
112
+
113
+ branches = self._analyze_branches(parsed_branches, subject)
114
+ if branches is None:
115
+ return None
116
+
117
+ if not any(not branch.is_wildcard_case for branch in branches):
118
+ return None
119
+ wildcard_case_count = sum(branch.is_wildcard_case for branch in branches)
120
+ if wildcard_case_count + int(else_body is not None) > 1:
121
+ return None
122
+ return IfChain(
123
+ subject=subject,
124
+ branches=tuple(branches),
125
+ else_body=else_body,
126
+ else_leading_lines=else_leading_lines,
127
+ )
128
+
129
+ def _select_chain_subject(
130
+ self, branches: list[ParsedBranch]
131
+ ) -> MatchSubjectPlan | None:
132
+ """Build a subject from the common prefix of all branch candidates."""
133
+ candidates = tuple(
134
+ select_assumed_pure_subject_paths(branch.condition) for branch in branches
135
+ )
136
+ if any(paths is None for paths in candidates):
137
+ return None
138
+ concrete_candidates = tuple(paths for paths in candidates if paths is not None)
139
+ if self.assumptions.assume_pure_subjects:
140
+ return MatchSubjectPlan.from_shared_candidates(concrete_candidates)
141
+
142
+ if self.assumptions.use_object:
143
+ subject = MatchSubjectPlan.from_shared_candidates(concrete_candidates)
144
+ if subject is not None and not subject.is_composite:
145
+ return subject
146
+
147
+ return MatchSubjectPlan.from_aligned_candidates(
148
+ tuple((paths[0],) for paths in concrete_candidates)
149
+ )
150
+
151
+ def _analyze_branches(
152
+ self, branches: Sequence[ParsedBranch], subject: MatchSubjectPlan
153
+ ) -> tuple[IfBranch, ...] | None:
154
+ analyzed: list[IfBranch] = []
155
+ for branch in branches:
156
+ analyzed_branch = self._analyze_branch(branch, subject)
157
+ if analyzed_branch is None:
158
+ return None
159
+ analyzed.append(analyzed_branch)
160
+ return tuple(analyzed)
161
+
162
+ def _analyze_branch(
163
+ self, branch: ParsedBranch, subject: MatchSubjectPlan
164
+ ) -> IfBranch | None:
165
+ if not is_safe_condition(
166
+ branch.test,
167
+ subject,
168
+ ignore_types_pattern=self.ignore_types_pattern,
169
+ ):
170
+ return None
171
+ facts = normalize_condition(
172
+ branch.condition,
173
+ subject,
174
+ allow_object_anchors=self.assumptions.use_object,
175
+ )
176
+ return IfBranch(branch.body, branch.leading_lines, facts)
177
+
178
+ def compile(
179
+ self, chain: IfChain, leading_lines: tuple[cst.EmptyLine, ...]
180
+ ) -> cst.Match:
181
+ cases = [
182
+ self._compile_branch(branch, chain.subject) for branch in chain.branches
183
+ ]
184
+
185
+ if chain.else_body is not None:
186
+ cases.append(
187
+ cst.MatchCase(
188
+ pattern=build_wildcard_pattern(),
189
+ body=chain.else_body,
190
+ leading_lines=chain.else_leading_lines,
191
+ )
192
+ )
193
+
194
+ return cst.Match(
195
+ subject=chain.subject.to_expression(),
196
+ cases=cases,
197
+ leading_lines=leading_lines,
198
+ )
199
+
200
+ def _compile_branch(
201
+ self, branch: IfBranch, subject: MatchSubjectPlan
202
+ ) -> cst.MatchCase:
203
+ facts = branch.facts
204
+ body = branch.body
205
+
206
+ if facts.pattern is not None:
207
+ captures = detect_captures(body, subject)
208
+ if captures:
209
+ captures, aliases = normalize_duplicate_captures(captures)
210
+ capture_pattern = facts.pattern
211
+ for capture in captures:
212
+ next_pattern = capture_pattern.with_capture(capture)
213
+ if next_pattern is None:
214
+ break
215
+ capture_pattern = next_pattern
216
+ else:
217
+ facts = BranchFacts(pattern=capture_pattern, guard=facts.guard)
218
+ body = remove_statements(body, len(captures) + len(aliases))
219
+ if aliases:
220
+ body = prepend_aliases(body, aliases)
221
+
222
+ pattern = (
223
+ build_wildcard_pattern()
224
+ if branch.is_wildcard_case
225
+ else facts.pattern.render()
226
+ )
227
+ guard = parenthesize_multiline_guard(facts.guard)
228
+
229
+ return cst.MatchCase(
230
+ pattern=pattern,
231
+ guard=guard,
232
+ body=body,
233
+ leading_lines=branch.leading_lines,
234
+ whitespace_before_if=(
235
+ cst.SimpleWhitespace("") if guard is None else cst.SimpleWhitespace(" ")
236
+ ),
237
+ whitespace_after_if=(
238
+ cst.SimpleWhitespace("") if guard is None else cst.SimpleWhitespace(" ")
239
+ ),
240
+ )
241
+
242
+
243
+ def parenthesize_multiline_guard(
244
+ guard: cst.BaseExpression | None,
245
+ ) -> cst.BaseExpression | None:
246
+ if guard is None:
247
+ return None
248
+ if "\n" not in cst.Module([]).code_for_node(guard):
249
+ return guard
250
+ return guard.with_changes(
251
+ lpar=(cst.LeftParen(), *guard.lpar),
252
+ rpar=(*guard.rpar, cst.RightParen()),
253
+ )