codecop 0.1.0__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.
Files changed (222) hide show
  1. codecop/__init__.py +7 -0
  2. codecop/access.py +140 -0
  3. codecop/access_postgres.py +284 -0
  4. codecop/advisor.py +1512 -0
  5. codecop/advisor_bench.py +493 -0
  6. codecop/advisor_ch.py +2080 -0
  7. codecop/advisor_view.py +381 -0
  8. codecop/advisors.py +184 -0
  9. codecop/agent.py +221 -0
  10. codecop/agentfacts.py +745 -0
  11. codecop/apply/__init__.py +327 -0
  12. codecop/apply/check.py +344 -0
  13. codecop/apply/cli.py +162 -0
  14. codecop/apply/clickhouse.py +379 -0
  15. codecop/apply/common.py +238 -0
  16. codecop/apply/html.py +264 -0
  17. codecop/apply/patch.py +213 -0
  18. codecop/apply/postgres.py +102 -0
  19. codecop/apply/trial.py +166 -0
  20. codecop/assemble.py +104 -0
  21. codecop/baseline.py +1043 -0
  22. codecop/bench.py +2464 -0
  23. codecop/blockers.py +935 -0
  24. codecop/budget.py +980 -0
  25. codecop/catalog_profile.py +525 -0
  26. codecop/changed.py +261 -0
  27. codecop/cicmd.py +1002 -0
  28. codecop/cli.py +5421 -0
  29. codecop/client.py +729 -0
  30. codecop/coverage.py +1067 -0
  31. codecop/coverage_reasons.py +116 -0
  32. codecop/crashlog.py +70 -0
  33. codecop/datagen.py +766 -0
  34. codecop/datagen_postgres.py +630 -0
  35. codecop/datagen_sqlite.py +323 -0
  36. codecop/dbcli.py +885 -0
  37. codecop/definitions.py +457 -0
  38. codecop/discover/__init__.py +702 -0
  39. codecop/discover/arms.py +160 -0
  40. codecop/discover/base.py +234 -0
  41. codecop/discover/dialect.py +296 -0
  42. codecop/discover/elixir.py +64 -0
  43. codecop/discover/engine_go.py +320 -0
  44. codecop/discover/go.py +1947 -0
  45. codecop/discover/java.py +1528 -0
  46. codecop/discover/loops.py +1671 -0
  47. codecop/discover/named_go.py +258 -0
  48. codecop/discover/origins.py +4565 -0
  49. codecop/discover/origins_ts.py +1584 -0
  50. codecop/discover/orm_django.py +2772 -0
  51. codecop/discover/orm_django_models.py +814 -0
  52. codecop/discover/orm_django_sql.py +662 -0
  53. codecop/discover/orm_ent.py +565 -0
  54. codecop/discover/orm_ex_ecto.py +2138 -0
  55. codecop/discover/orm_go.py +2134 -0
  56. codecop/discover/orm_go_bun.py +602 -0
  57. codecop/discover/orm_go_run.py +636 -0
  58. codecop/discover/orm_go_types.py +1082 -0
  59. codecop/discover/orm_java.py +1450 -0
  60. codecop/discover/orm_jdbi.py +743 -0
  61. codecop/discover/orm_jooq.py +806 -0
  62. codecop/discover/orm_jpa.py +1307 -0
  63. codecop/discover/orm_mybatis.py +730 -0
  64. codecop/discover/orm_py.py +557 -0
  65. codecop/discover/orm_py_peewee.py +1266 -0
  66. codecop/discover/orm_py_prisma.py +298 -0
  67. codecop/discover/orm_rb_activerecord.py +1906 -0
  68. codecop/discover/orm_rust.py +1248 -0
  69. codecop/discover/orm_rust_seaorm.py +734 -0
  70. codecop/discover/orm_sqlalchemy.py +2475 -0
  71. codecop/discover/orm_stats.py +307 -0
  72. codecop/discover/orm_tables.py +29 -0
  73. codecop/discover/orm_ts.py +503 -0
  74. codecop/discover/orm_ts_drizzle.py +697 -0
  75. codecop/discover/orm_ts_knex.py +1117 -0
  76. codecop/discover/orm_ts_kysely.py +861 -0
  77. codecop/discover/orm_ts_prisma.py +1045 -0
  78. codecop/discover/orm_ts_schema.py +169 -0
  79. codecop/discover/orm_ts_sequelize.py +1401 -0
  80. codecop/discover/orm_ts_typeorm.py +1067 -0
  81. codecop/discover/probes.py +323 -0
  82. codecop/discover/python.py +595 -0
  83. codecop/discover/ruby.py +793 -0
  84. codecop/discover/rust.py +2378 -0
  85. codecop/discover/schema.py +520 -0
  86. codecop/discover/schema_ent.py +145 -0
  87. codecop/discover/schema_ts.py +420 -0
  88. codecop/discover/tsresolve.py +257 -0
  89. codecop/discover/typescript.py +1728 -0
  90. codecop/discover/xml_mapper.py +526 -0
  91. codecop/engines/__init__.py +515 -0
  92. codecop/engines/base.py +498 -0
  93. codecop/engines/clickhouse.py +1558 -0
  94. codecop/engines/pg_ddl.py +444 -0
  95. codecop/engines/pg_hints.py +137 -0
  96. codecop/engines/postgres.py +1060 -0
  97. codecop/engines/sqlite.py +742 -0
  98. codecop/families/__init__.py +3 -0
  99. codecop/families/build.py +280 -0
  100. codecop/families/cli.py +177 -0
  101. codecop/families/coverage_hook.py +62 -0
  102. codecop/families/driver.py +221 -0
  103. codecop/families/goslice.py +229 -0
  104. codecop/families/goslice_tool/go.mod +3 -0
  105. codecop/families/goslice_tool/main.go +403 -0
  106. codecop/families/holes.py +451 -0
  107. codecop/families/images/Dockerfile.go +5 -0
  108. codecop/families/images/Dockerfile.python +4 -0
  109. codecop/families/images/Dockerfile.rust +4 -0
  110. codecop/families/isolate.py +171 -0
  111. codecop/families/locate.py +270 -0
  112. codecop/families/model.py +301 -0
  113. codecop/families/plangate.py +271 -0
  114. codecop/families/tagpatch.py +174 -0
  115. codecop/fidelity.py +671 -0
  116. codecop/fixgroups.py +130 -0
  117. codecop/formerly.py +91 -0
  118. codecop/grantscript.py +254 -0
  119. codecop/groupbench.py +1375 -0
  120. codecop/groups.py +594 -0
  121. codecop/groups_view.py +186 -0
  122. codecop/heat.py +1405 -0
  123. codecop/heatcli.py +219 -0
  124. codecop/joins.py +1749 -0
  125. codecop/joins_view.py +127 -0
  126. codecop/kinds/__init__.py +507 -0
  127. codecop/kinds/calls/__init__.py +501 -0
  128. codecop/kinds/calls/extract.py +1097 -0
  129. codecop/kinds/calls/harness.py +408 -0
  130. codecop/kinds/calls/measure.py +342 -0
  131. codecop/kinds/calls/rules.py +139 -0
  132. codecop/kinds/calls/runners/RunCalls.java +167 -0
  133. codecop/kinds/calls/runners/run_go.go +141 -0
  134. codecop/kinds/calls/runners/run_node.js +186 -0
  135. codecop/kinds/calls/runners/run_python.py +319 -0
  136. codecop/kinds/calls/runners/run_rust.rs +200 -0
  137. codecop/kinds/calls/standin.py +340 -0
  138. codecop/kinds/pipeline.py +288 -0
  139. codecop/kinds/regex/__init__.py +1167 -0
  140. codecop/kinds/regex/engines/RegexHarness.java +129 -0
  141. codecop/kinds/regex/engines/run_go.go +294 -0
  142. codecop/kinds/regex/engines/run_node.js +99 -0
  143. codecop/kinds/regex/engines/run_python.py +295 -0
  144. codecop/kinds/regex/engines/run_rust.rs +149 -0
  145. codecop/kinds/regex/extract.py +1438 -0
  146. codecop/kinds/regex/harness.py +235 -0
  147. codecop/kinds/regex/measure.py +270 -0
  148. codecop/kinds/regex/shapes.py +418 -0
  149. codecop/kinds/regex/syntax.py +1721 -0
  150. codecop/kinds/testkind.py +107 -0
  151. codecop/kinds/transaction/__init__.py +228 -0
  152. codecop/kinds/transaction/bind.py +355 -0
  153. codecop/kinds/transaction/measure.py +264 -0
  154. codecop/kinds/transaction/plan.py +462 -0
  155. codecop/kinds/transaction/rules.py +540 -0
  156. codecop/kinds/transaction/sandbox.py +94 -0
  157. codecop/kinds/transaction/scenarios.py +520 -0
  158. codecop/kinds/transaction/schedule.py +483 -0
  159. codecop/kinds/transaction/shapes.py +418 -0
  160. codecop/kinds/transaction/verify.py +293 -0
  161. codecop/live.py +237 -0
  162. codecop/loopbench.py +2071 -0
  163. codecop/loopschema.py +591 -0
  164. codecop/mcpserver.py +120 -0
  165. codecop/mechanism.py +214 -0
  166. codecop/members.py +200 -0
  167. codecop/multi.py +443 -0
  168. codecop/observed.py +1868 -0
  169. codecop/parts.py +102 -0
  170. codecop/patterns.py +830 -0
  171. codecop/patterns_view.py +559 -0
  172. codecop/plangate.py +242 -0
  173. codecop/profile.py +439 -0
  174. codecop/prompts/areas.md +19 -0
  175. codecop/prompts/observed_variants.md +20 -0
  176. codecop/prompts/profile.md +60 -0
  177. codecop/prompts/profile_postgres.md +68 -0
  178. codecop/prompts/profile_sizes.md +26 -0
  179. codecop/prompts/profile_sqlite.md +69 -0
  180. codecop/prompts/rank.md +84 -0
  181. codecop/prompts/rank_postgres.md +96 -0
  182. codecop/prompts/rank_sqlite.md +94 -0
  183. codecop/prompts/scenario_variants.md +20 -0
  184. codecop/rank.py +1473 -0
  185. codecop/realdb/__init__.py +688 -0
  186. codecop/realdb/clickhouse.py +1223 -0
  187. codecop/realdb/facts.py +815 -0
  188. codecop/realdb/locality.py +964 -0
  189. codecop/realdb/locks.py +355 -0
  190. codecop/realdb/match.py +531 -0
  191. codecop/realdb/postgres.py +643 -0
  192. codecop/realdb/ratios.py +77 -0
  193. codecop/realdb/sample.py +126 -0
  194. codecop/relations.py +227 -0
  195. codecop/report.py +1854 -0
  196. codecop/resources.py +332 -0
  197. codecop/resources_view.py +266 -0
  198. codecop/rules/entry_points.toml +1013 -0
  199. codecop/rules/sinks.toml +362 -0
  200. codecop/runsonce.py +8 -0
  201. codecop/sandboxschema.py +555 -0
  202. codecop/scenario_agent.py +172 -0
  203. codecop/scenario_bind.py +507 -0
  204. codecop/scenario_sql.py +971 -0
  205. codecop/scenarios.py +675 -0
  206. codecop/scenarios_view.py +274 -0
  207. codecop/schemacli.py +67 -0
  208. codecop/schemas/areas_output.schema.json +21 -0
  209. codecop/schemas/profile_output.schema.json +362 -0
  210. codecop/schemas/rank_output.schema.json +385 -0
  211. codecop/sizes.py +200 -0
  212. codecop/sqlinfo.py +558 -0
  213. codecop/typedparams.py +576 -0
  214. codecop/verdicts.py +212 -0
  215. codecop/writebench.py +720 -0
  216. codecop/writecost.py +440 -0
  217. codecop/writes.py +1208 -0
  218. codecop-0.1.0.dist-info/METADATA +42 -0
  219. codecop-0.1.0.dist-info/RECORD +222 -0
  220. codecop-0.1.0.dist-info/WHEEL +4 -0
  221. codecop-0.1.0.dist-info/entry_points.txt +2 -0
  222. codecop-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,418 @@
1
+ """Call shapes around regexes that cost more than the patterns themselves: a table of patterns run one after another on
2
+ the same text (a required-literal prefilter, or the text folded once instead of a case-insensitive flag on each), and
3
+ one pattern per word built inside a loop (one alternation instead). Read from the code, never run.
4
+
5
+ A shape is a site like any other (discover traces it to its entry points); its `shape` names it and `members` carries
6
+ the patterns or words. Python (ast) and Go (tree-sitter) tables; Python word loops.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import ast
12
+ import re
13
+
14
+ from ...discover.base import read_text
15
+ from .extract import (GO_MODES, PY_MODES, _compile_call, _go_fn, _go_str, _py_flags, _py_list, _py_module_consts, _py_str,
16
+ _re_aliases, _t, _walk, make, parser, trim)
17
+
18
+ TABLE_APIS = {"search", "match", "fullmatch", "finditer", "findall"}
19
+
20
+
21
+ def _site(rel, line, engine, api, members, *, symbol, name, use, shape, flags="", extra=None, language="python"):
22
+ pat = members[0][0] if members else None
23
+ s = make(rel, line, language, engine, pat, flags, api, symbol=symbol, compiled="once", source="table", name=name, use=use)
24
+ s["shape"] = shape
25
+ s["members"] = members
26
+ s["text"] = f"{shape}|{engine}|{name}|{api}|{trim(use, 80)}"
27
+ s.update(extra or {})
28
+ return s
29
+
30
+
31
+ # --- Python ------------------------------------------------------------------------------------------------------------------
32
+
33
+ def _py_table(node, consts, mods, funcs) -> list | None:
34
+ """[(pattern, flags, line, engine)] of a module-level collection of compiled patterns (a list, tuple or dict; an
35
+ element may be a tuple holding one compile), or of pattern strings; None when it is something else."""
36
+ if isinstance(node, ast.Dict):
37
+ elts = list(node.values)
38
+ elif isinstance(node, (ast.List, ast.Tuple, ast.Set)):
39
+ elts = list(node.elts)
40
+ else:
41
+ return None
42
+ out = []
43
+ for e in elts:
44
+ cc = _compile_call(e, mods, funcs)
45
+ if cc is None and isinstance(e, ast.Tuple):
46
+ cs = [x for x in (_compile_call(y, mods, funcs) for y in e.elts) if x]
47
+ cc = cs[0] if len(cs) == 1 else None
48
+ if cc is not None and cc[1].args:
49
+ pat = _py_str(cc[1].args[0], consts)
50
+ fl_node = cc[1].args[1] if len(cc[1].args) > 1 else next((k.value for k in cc[1].keywords if k.arg == "flags"), None)
51
+ if pat is None:
52
+ return None
53
+ out.append((pat, _py_flags(fl_node, mods), getattr(e, "lineno", node.lineno), cc[0]))
54
+ else:
55
+ return None
56
+ return out if len(out) >= 2 else None
57
+
58
+
59
+ class _Tables(ast.NodeVisitor):
60
+ def __init__(self, rel, tree, mods, funcs, consts, out):
61
+ self.rel, self.mods, self.funcs, self.consts, self.out = rel, mods, funcs, consts, out
62
+ self.tables: dict[str, list] = {}
63
+ self.table_line: dict[str, int] = {}
64
+ for st in tree.body:
65
+ if isinstance(st, (ast.Assign, ast.AnnAssign)):
66
+ tg = st.targets if isinstance(st, ast.Assign) else [st.target]
67
+ val = st.value
68
+ if val is None:
69
+ continue
70
+ t = _py_table(val, consts, mods, funcs)
71
+ for x in tg:
72
+ if isinstance(x, ast.Name) and t:
73
+ self.tables[x.id] = t
74
+ self.table_line[x.id] = st.lineno
75
+ self.stack: list[str] = []
76
+
77
+ def visit_ClassDef(self, node):
78
+ self.stack.append(node.name)
79
+ self.generic_visit(node)
80
+ self.stack.pop()
81
+
82
+ def visit_FunctionDef(self, node):
83
+ self.stack.append(node.name)
84
+ self.generic_visit(node)
85
+ self.stack.pop()
86
+
87
+ visit_AsyncFunctionDef = visit_FunctionDef
88
+
89
+ def _iter_table(self, it):
90
+ """The table a loop iterates, and how its element is unpacked: NAME, NAME.items(), NAME.values()."""
91
+ if isinstance(it, ast.Name) and it.id in self.tables:
92
+ return it.id, "elts"
93
+ if isinstance(it, ast.Call) and isinstance(it.func, ast.Attribute) and isinstance(it.func.value, ast.Name) \
94
+ and it.func.value.id in self.tables and it.func.attr in ("items", "values") and not it.args:
95
+ return it.func.value.id, it.func.attr
96
+ return None, None
97
+
98
+ def _uses(self, body_nodes, names: set) -> list:
99
+ """Calls X.search(arg) / re.search(X, arg) on a loop element; [(api, arg node, call)]."""
100
+ got = []
101
+ for b in body_nodes:
102
+ for n in ast.walk(b):
103
+ if not isinstance(n, ast.Call) or not isinstance(n.func, ast.Attribute):
104
+ continue
105
+ f = n.func
106
+ if f.attr in TABLE_APIS and isinstance(f.value, ast.Name) and f.value.id in names and n.args:
107
+ got.append((f.attr, n.args[0], n))
108
+ elif f.attr in TABLE_APIS and isinstance(f.value, ast.Name) and f.value.id in self.mods and len(n.args) >= 2 \
109
+ and isinstance(n.args[0], ast.Name) and n.args[0].id in names:
110
+ got.append((f.attr, n.args[1], n))
111
+ return got
112
+
113
+ def _emit(self, node, target, it, body, kind):
114
+ name, how = self._iter_table(it)
115
+ if name is None:
116
+ return
117
+ names = {x.id for x in ast.walk(target) if isinstance(x, ast.Name)}
118
+ uses = self._uses(body, names)
119
+ if not uses:
120
+ return
121
+ api, arg, call = uses[0]
122
+ if not isinstance(arg, (ast.Name, ast.Attribute, ast.Subscript, ast.Call)):
123
+ return
124
+ arg_text = ast.unparse(arg)
125
+ # the text must be the same for every pattern: not assigned in the loop body
126
+ for b in body:
127
+ for n in ast.walk(b):
128
+ if isinstance(n, (ast.Assign, ast.AugAssign, ast.AnnAssign)):
129
+ tg = n.targets if isinstance(n, ast.Assign) else [n.target]
130
+ if any(ast.unparse(t) == arg_text for t in tg):
131
+ return
132
+ members = [[p, f, line, eng] for p, f, line, eng in self.tables[name]]
133
+ engines = {m[3] for m in members}
134
+ if len(engines) != 1:
135
+ return
136
+ self.out.append(_site(self.rel, node.lineno, engines.pop(), api, members, symbol=".".join(self.stack), name=name,
137
+ use=f"{kind} over {name}: {ast.unparse(call)}", shape="table",
138
+ extra={"arg": trim(arg_text, 80), "def_line": self.table_line.get(name, node.lineno)}))
139
+
140
+ def visit_For(self, node):
141
+ self._emit(node, node.target, node.iter, node.body, "for")
142
+ self.generic_visit(node)
143
+
144
+ visit_AsyncFor = visit_For
145
+
146
+ def _comp(self, node):
147
+ if len(node.generators) == 1:
148
+ g = node.generators[0]
149
+ elt = node.elt if not isinstance(node, ast.DictComp) else node.value
150
+ self._emit(node, g.target, g.iter, [elt] + list(g.ifs), "comprehension")
151
+ self.generic_visit(node)
152
+
153
+ visit_GeneratorExp = visit_ListComp = visit_SetComp = visit_DictComp = _comp
154
+
155
+
156
+ def _word_template(node, var: str, consts) -> tuple | None:
157
+ """(pre, post) when the pattern argument is an f-string or a concatenation with the loop variable exactly once and
158
+ constants around it: rf"\\b{w}\\b", r"\\b" + w + r"\\b"."""
159
+ if isinstance(node, ast.JoinedStr):
160
+ parts, at = [], None
161
+ for v in node.values:
162
+ if isinstance(v, ast.Constant):
163
+ parts.append(str(v.value))
164
+ elif isinstance(v, ast.FormattedValue) and isinstance(v.value, ast.Name) and v.value.id == var and v.format_spec is None \
165
+ and v.conversion == -1 and at is None:
166
+ at = len(parts)
167
+ parts.append(None)
168
+ else:
169
+ s = _py_str(v.value, consts) if isinstance(v, ast.FormattedValue) and v.format_spec is None else None
170
+ if s is None:
171
+ return None
172
+ parts.append(s)
173
+ if at is None:
174
+ return None
175
+ return "".join(parts[:at]), "".join(parts[at + 1:])
176
+ if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add):
177
+ flat = []
178
+
179
+ def go(n):
180
+ if isinstance(n, ast.BinOp) and isinstance(n.op, ast.Add):
181
+ go(n.left)
182
+ go(n.right)
183
+ else:
184
+ flat.append(n)
185
+ go(node)
186
+ at = [i for i, x in enumerate(flat) if isinstance(x, ast.Name) and x.id == var]
187
+ if len(at) != 1:
188
+ return None
189
+ pre = [_py_str(x, consts) for x in flat[:at[0]]]
190
+ post = [_py_str(x, consts) for x in flat[at[0] + 1:]]
191
+ if any(x is None for x in pre + post):
192
+ return None
193
+ return "".join(pre), "".join(post)
194
+ return None
195
+
196
+
197
+ def _word_list(it, consts) -> list | None:
198
+ """[(word, other)] of a loop over constant strings, or over constant pairs (a tuple of tuples, or dict.items())."""
199
+ node = it
200
+ if isinstance(it, ast.Call) and isinstance(it.func, ast.Attribute) and it.func.attr == "items" and not it.args:
201
+ node = it.func.value
202
+ if isinstance(node, ast.Name):
203
+ return None
204
+ if isinstance(node, ast.Dict):
205
+ out = []
206
+ for k, v in zip(node.keys, node.values):
207
+ a, b = _py_str(k, consts), _py_str(v, consts)
208
+ if a is None or b is None:
209
+ return None
210
+ out.append((a, b))
211
+ return out
212
+ return None
213
+ if isinstance(node, (ast.List, ast.Tuple)):
214
+ out = []
215
+ for e in node.elts:
216
+ if isinstance(e, ast.Tuple) and len(e.elts) == 2:
217
+ a, b = _py_str(e.elts[0], consts), _py_str(e.elts[1], consts)
218
+ if a is None or b is None:
219
+ return None
220
+ out.append((a, b))
221
+ else:
222
+ a = _py_str(e, consts)
223
+ if a is None:
224
+ return None
225
+ out.append((a, None))
226
+ return out
227
+ lst = _py_list(node, consts)
228
+ return [(a, None) for a in lst] if lst else None
229
+
230
+
231
+ class _Words(ast.NodeVisitor):
232
+ """for w in WORDS: s = re.sub(rf"\\b{w}\\b", repl, s) / if re.search(rf"\\b{w}\\b", s): ..."""
233
+
234
+ def __init__(self, rel, mods, funcs, consts, out):
235
+ self.rel, self.mods, self.funcs, self.consts, self.out = rel, mods, funcs, consts, out
236
+ self.stack: list[str] = []
237
+
238
+ def visit_ClassDef(self, node):
239
+ self.stack.append(node.name)
240
+ self.generic_visit(node)
241
+ self.stack.pop()
242
+
243
+ def visit_FunctionDef(self, node):
244
+ self.stack.append(node.name)
245
+ self.generic_visit(node)
246
+ self.stack.pop()
247
+
248
+ visit_AsyncFunctionDef = visit_FunctionDef
249
+
250
+ def visit_For(self, node):
251
+ self.generic_visit(node)
252
+ words = _word_list(node.iter, self.consts)
253
+ if not words or len(words) < 2:
254
+ return
255
+ t = node.target
256
+ if isinstance(t, ast.Name):
257
+ wvar, rvar = t.id, None
258
+ elif isinstance(t, ast.Tuple) and len(t.elts) == 2 and all(isinstance(x, ast.Name) for x in t.elts):
259
+ wvar, rvar = t.elts[0].id, t.elts[1].id
260
+ if any(b is None for _, b in words):
261
+ return
262
+ else:
263
+ return
264
+ for st in node.body:
265
+ for n in ast.walk(st):
266
+ if not (isinstance(n, ast.Call) and isinstance(n.func, ast.Attribute) and isinstance(n.func.value, ast.Name)
267
+ and n.func.value.id in self.mods and n.func.attr in ("sub", "search") and n.args):
268
+ continue
269
+ tpl = _word_template(n.args[0], wvar, self.consts)
270
+ if tpl is None:
271
+ continue
272
+ api = n.func.attr
273
+ fl_i = 3 if api == "sub" else 2
274
+ fl_node = n.args[fl_i] if len(n.args) > fl_i else next((k.value for k in n.keywords if k.arg == "flags"), None)
275
+ if any(k.arg == "count" for k in n.keywords) or api == "sub" and len(n.args) > 3 and fl_i != 3:
276
+ continue
277
+ flags = _py_flags(fl_node, self.mods)
278
+ if api == "sub":
279
+ if len(n.args) < 3:
280
+ continue
281
+ repl, text = n.args[1], n.args[2]
282
+ # the result must feed the next word: s = re.sub(..., s)
283
+ par = getattr(n, "_codecop_parent", None)
284
+ if not (isinstance(st, ast.Assign) and st.value is n and len(st.targets) == 1
285
+ and ast.unparse(st.targets[0]) == ast.unparse(text)):
286
+ continue
287
+ if isinstance(repl, ast.Name) and repl.id == rvar:
288
+ pairs = [[w, r] for w, r in words]
289
+ else:
290
+ r = _py_str(repl, self.consts)
291
+ if r is None:
292
+ continue
293
+ pairs = [[w, r] for w, _ in words]
294
+ kind = "sub"
295
+ arg = ast.unparse(text)
296
+ del par
297
+ else:
298
+ if len(n.args) < 2:
299
+ continue
300
+ pairs = [[w, None] for w, _ in words]
301
+ kind = "bool"
302
+ arg = ast.unparse(n.args[1])
303
+ self.out.append(_site(self.rel, node.lineno, "python-regex" if n.func.value.id == "regex" else "python", api,
304
+ [[w, r] for w, r in pairs], symbol=".".join(self.stack), name=wvar,
305
+ use=f"for {wvar} in …: {ast.unparse(n)}", shape="words", flags=flags,
306
+ extra={"pre": tpl[0], "post": tpl[1], "word_kind": kind, "end_line": node.end_lineno or node.lineno,
307
+ "arg": trim(arg, 80)}))
308
+ return
309
+
310
+ visit_AsyncFor = visit_For
311
+
312
+
313
+ def python(root, files: list[str]) -> list[dict]:
314
+ out: list[dict] = []
315
+ for rel in files:
316
+ text = read_text(root / rel)
317
+ if not text or "re" not in text or "import" not in text:
318
+ continue
319
+ try:
320
+ tree = ast.parse(text)
321
+ except (SyntaxError, ValueError, RecursionError):
322
+ continue
323
+ mods, funcs = _re_aliases(tree)
324
+ if not mods and not funcs:
325
+ continue
326
+ consts = _py_module_consts(tree, mods, funcs)
327
+ _Tables(rel, tree, mods, funcs, consts, out).visit(tree)
328
+ _Words(rel, mods, funcs, consts, out).visit(tree)
329
+ return out
330
+
331
+
332
+ # --- Go -------------------------------------------------------------------------------------------------------------------
333
+
334
+ GO_TABLE_USE = re.compile(r"\b(\w+)(?:\.\w+)?\.(MatchString|FindString|FindStringIndex|FindStringSubmatch|FindStringSubmatchIndex|"
335
+ r"FindAllString|FindAllStringIndex|FindAllStringSubmatch|FindAllStringSubmatchIndex|Match|FindAllIndex)\(\s*([\w.\[\]]+)")
336
+
337
+
338
+ def go(root, files: list[str]) -> list[dict]:
339
+ """for _, r := range RULES { r.re.MatchString(text) } over a package-level slice or map literal whose elements hold
340
+ regexp.MustCompile(<constant>) (one per element)."""
341
+ out: list[dict] = []
342
+ for rel in files:
343
+ src = read_text(root / rel)
344
+ if not src or "regexp" not in src or "range" not in src:
345
+ continue
346
+ tree = parser("go").parse(src.encode())
347
+ consts: dict[str, str] = {}
348
+ tables: dict[str, list] = {}
349
+ for n in _walk(tree.root_node):
350
+ if n.type in ("const_spec", "var_spec") and n.parent is not None and (n.parent.type == "source_file" or n.parent.parent is not None
351
+ and n.parent.parent.type == "source_file"):
352
+ names = list(n.children_by_field_name("name"))
353
+ vals = n.child_by_field_name("value")
354
+ if vals is None or not names:
355
+ continue
356
+ for nm, v in zip(names, vals.named_children):
357
+ s = _go_str(v, consts)
358
+ if s is not None:
359
+ consts[_t(nm)] = s
360
+ elif v.type == "composite_literal":
361
+ pats = []
362
+ body = v.child_by_field_name("body")
363
+ for el in (body.named_children if body is not None else []):
364
+ calls = [c for c in _walk(el) if c.type == "call_expression"
365
+ and _t(c.child_by_field_name("function")) in ("regexp.MustCompile", "regexp.MustCompilePOSIX")]
366
+ if len(calls) != 1:
367
+ pats = None
368
+ break
369
+ a = calls[0].child_by_field_name("arguments")
370
+ p = _go_str(a.named_children[0] if a is not None and a.named_children else None, consts)
371
+ if p is None:
372
+ pats = None
373
+ break
374
+ pats.append([p, "", calls[0].start_point[0] + 1, "go"])
375
+ if pats and len(pats) >= 2:
376
+ tables[_t(nm)] = pats
377
+ if not tables:
378
+ continue
379
+ for n in _walk(tree.root_node):
380
+ if n.type != "for_statement":
381
+ continue
382
+ rc = next((c for c in n.named_children if c.type == "range_clause"), None)
383
+ if rc is None:
384
+ continue
385
+ right = rc.child_by_field_name("right")
386
+ left = rc.child_by_field_name("left")
387
+ name = _t(right)
388
+ if name not in tables or left is None:
389
+ continue
390
+ var = _t(left).split(",")[-1].strip()
391
+ body = n.child_by_field_name("body")
392
+ m = None
393
+ for u in GO_TABLE_USE.finditer(_t(body) if body is not None else ""):
394
+ if u.group(1) == var:
395
+ m = u
396
+ break
397
+ if m is None or m.group(2) not in GO_MODES:
398
+ continue
399
+ arg = m.group(3)
400
+ if re.search(r"\b" + re.escape(arg.split(".")[0]) + r"\s*(?:=|:=)", _t(body)):
401
+ continue
402
+ fn, sym = _go_fn(n)
403
+ out.append(_site(rel, n.start_point[0] + 1, "go", m.group(2), tables[name], symbol=sym, name=name,
404
+ use=f"range {name}: {m.group(0)})", shape="table", language="go",
405
+ extra={"arg": arg, "def_line": tables[name][0][2]}))
406
+ return out
407
+
408
+
409
+ def sites(root, by_lang: dict) -> list[dict]:
410
+ out = []
411
+ if by_lang.get("python"):
412
+ out += python(root, by_lang["python"])
413
+ if by_lang.get("go"):
414
+ out += go(root, by_lang["go"])
415
+ return out
416
+
417
+
418
+ __all__ = ["sites", "python", "go", "PY_MODES"]