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.
- codecop/__init__.py +7 -0
- codecop/access.py +140 -0
- codecop/access_postgres.py +284 -0
- codecop/advisor.py +1512 -0
- codecop/advisor_bench.py +493 -0
- codecop/advisor_ch.py +2080 -0
- codecop/advisor_view.py +381 -0
- codecop/advisors.py +184 -0
- codecop/agent.py +221 -0
- codecop/agentfacts.py +745 -0
- codecop/apply/__init__.py +327 -0
- codecop/apply/check.py +344 -0
- codecop/apply/cli.py +162 -0
- codecop/apply/clickhouse.py +379 -0
- codecop/apply/common.py +238 -0
- codecop/apply/html.py +264 -0
- codecop/apply/patch.py +213 -0
- codecop/apply/postgres.py +102 -0
- codecop/apply/trial.py +166 -0
- codecop/assemble.py +104 -0
- codecop/baseline.py +1043 -0
- codecop/bench.py +2464 -0
- codecop/blockers.py +935 -0
- codecop/budget.py +980 -0
- codecop/catalog_profile.py +525 -0
- codecop/changed.py +261 -0
- codecop/cicmd.py +1002 -0
- codecop/cli.py +5421 -0
- codecop/client.py +729 -0
- codecop/coverage.py +1067 -0
- codecop/coverage_reasons.py +116 -0
- codecop/crashlog.py +70 -0
- codecop/datagen.py +766 -0
- codecop/datagen_postgres.py +630 -0
- codecop/datagen_sqlite.py +323 -0
- codecop/dbcli.py +885 -0
- codecop/definitions.py +457 -0
- codecop/discover/__init__.py +702 -0
- codecop/discover/arms.py +160 -0
- codecop/discover/base.py +234 -0
- codecop/discover/dialect.py +296 -0
- codecop/discover/elixir.py +64 -0
- codecop/discover/engine_go.py +320 -0
- codecop/discover/go.py +1947 -0
- codecop/discover/java.py +1528 -0
- codecop/discover/loops.py +1671 -0
- codecop/discover/named_go.py +258 -0
- codecop/discover/origins.py +4565 -0
- codecop/discover/origins_ts.py +1584 -0
- codecop/discover/orm_django.py +2772 -0
- codecop/discover/orm_django_models.py +814 -0
- codecop/discover/orm_django_sql.py +662 -0
- codecop/discover/orm_ent.py +565 -0
- codecop/discover/orm_ex_ecto.py +2138 -0
- codecop/discover/orm_go.py +2134 -0
- codecop/discover/orm_go_bun.py +602 -0
- codecop/discover/orm_go_run.py +636 -0
- codecop/discover/orm_go_types.py +1082 -0
- codecop/discover/orm_java.py +1450 -0
- codecop/discover/orm_jdbi.py +743 -0
- codecop/discover/orm_jooq.py +806 -0
- codecop/discover/orm_jpa.py +1307 -0
- codecop/discover/orm_mybatis.py +730 -0
- codecop/discover/orm_py.py +557 -0
- codecop/discover/orm_py_peewee.py +1266 -0
- codecop/discover/orm_py_prisma.py +298 -0
- codecop/discover/orm_rb_activerecord.py +1906 -0
- codecop/discover/orm_rust.py +1248 -0
- codecop/discover/orm_rust_seaorm.py +734 -0
- codecop/discover/orm_sqlalchemy.py +2475 -0
- codecop/discover/orm_stats.py +307 -0
- codecop/discover/orm_tables.py +29 -0
- codecop/discover/orm_ts.py +503 -0
- codecop/discover/orm_ts_drizzle.py +697 -0
- codecop/discover/orm_ts_knex.py +1117 -0
- codecop/discover/orm_ts_kysely.py +861 -0
- codecop/discover/orm_ts_prisma.py +1045 -0
- codecop/discover/orm_ts_schema.py +169 -0
- codecop/discover/orm_ts_sequelize.py +1401 -0
- codecop/discover/orm_ts_typeorm.py +1067 -0
- codecop/discover/probes.py +323 -0
- codecop/discover/python.py +595 -0
- codecop/discover/ruby.py +793 -0
- codecop/discover/rust.py +2378 -0
- codecop/discover/schema.py +520 -0
- codecop/discover/schema_ent.py +145 -0
- codecop/discover/schema_ts.py +420 -0
- codecop/discover/tsresolve.py +257 -0
- codecop/discover/typescript.py +1728 -0
- codecop/discover/xml_mapper.py +526 -0
- codecop/engines/__init__.py +515 -0
- codecop/engines/base.py +498 -0
- codecop/engines/clickhouse.py +1558 -0
- codecop/engines/pg_ddl.py +444 -0
- codecop/engines/pg_hints.py +137 -0
- codecop/engines/postgres.py +1060 -0
- codecop/engines/sqlite.py +742 -0
- codecop/families/__init__.py +3 -0
- codecop/families/build.py +280 -0
- codecop/families/cli.py +177 -0
- codecop/families/coverage_hook.py +62 -0
- codecop/families/driver.py +221 -0
- codecop/families/goslice.py +229 -0
- codecop/families/goslice_tool/go.mod +3 -0
- codecop/families/goslice_tool/main.go +403 -0
- codecop/families/holes.py +451 -0
- codecop/families/images/Dockerfile.go +5 -0
- codecop/families/images/Dockerfile.python +4 -0
- codecop/families/images/Dockerfile.rust +4 -0
- codecop/families/isolate.py +171 -0
- codecop/families/locate.py +270 -0
- codecop/families/model.py +301 -0
- codecop/families/plangate.py +271 -0
- codecop/families/tagpatch.py +174 -0
- codecop/fidelity.py +671 -0
- codecop/fixgroups.py +130 -0
- codecop/formerly.py +91 -0
- codecop/grantscript.py +254 -0
- codecop/groupbench.py +1375 -0
- codecop/groups.py +594 -0
- codecop/groups_view.py +186 -0
- codecop/heat.py +1405 -0
- codecop/heatcli.py +219 -0
- codecop/joins.py +1749 -0
- codecop/joins_view.py +127 -0
- codecop/kinds/__init__.py +507 -0
- codecop/kinds/calls/__init__.py +501 -0
- codecop/kinds/calls/extract.py +1097 -0
- codecop/kinds/calls/harness.py +408 -0
- codecop/kinds/calls/measure.py +342 -0
- codecop/kinds/calls/rules.py +139 -0
- codecop/kinds/calls/runners/RunCalls.java +167 -0
- codecop/kinds/calls/runners/run_go.go +141 -0
- codecop/kinds/calls/runners/run_node.js +186 -0
- codecop/kinds/calls/runners/run_python.py +319 -0
- codecop/kinds/calls/runners/run_rust.rs +200 -0
- codecop/kinds/calls/standin.py +340 -0
- codecop/kinds/pipeline.py +288 -0
- codecop/kinds/regex/__init__.py +1167 -0
- codecop/kinds/regex/engines/RegexHarness.java +129 -0
- codecop/kinds/regex/engines/run_go.go +294 -0
- codecop/kinds/regex/engines/run_node.js +99 -0
- codecop/kinds/regex/engines/run_python.py +295 -0
- codecop/kinds/regex/engines/run_rust.rs +149 -0
- codecop/kinds/regex/extract.py +1438 -0
- codecop/kinds/regex/harness.py +235 -0
- codecop/kinds/regex/measure.py +270 -0
- codecop/kinds/regex/shapes.py +418 -0
- codecop/kinds/regex/syntax.py +1721 -0
- codecop/kinds/testkind.py +107 -0
- codecop/kinds/transaction/__init__.py +228 -0
- codecop/kinds/transaction/bind.py +355 -0
- codecop/kinds/transaction/measure.py +264 -0
- codecop/kinds/transaction/plan.py +462 -0
- codecop/kinds/transaction/rules.py +540 -0
- codecop/kinds/transaction/sandbox.py +94 -0
- codecop/kinds/transaction/scenarios.py +520 -0
- codecop/kinds/transaction/schedule.py +483 -0
- codecop/kinds/transaction/shapes.py +418 -0
- codecop/kinds/transaction/verify.py +293 -0
- codecop/live.py +237 -0
- codecop/loopbench.py +2071 -0
- codecop/loopschema.py +591 -0
- codecop/mcpserver.py +120 -0
- codecop/mechanism.py +214 -0
- codecop/members.py +200 -0
- codecop/multi.py +443 -0
- codecop/observed.py +1868 -0
- codecop/parts.py +102 -0
- codecop/patterns.py +830 -0
- codecop/patterns_view.py +559 -0
- codecop/plangate.py +242 -0
- codecop/profile.py +439 -0
- codecop/prompts/areas.md +19 -0
- codecop/prompts/observed_variants.md +20 -0
- codecop/prompts/profile.md +60 -0
- codecop/prompts/profile_postgres.md +68 -0
- codecop/prompts/profile_sizes.md +26 -0
- codecop/prompts/profile_sqlite.md +69 -0
- codecop/prompts/rank.md +84 -0
- codecop/prompts/rank_postgres.md +96 -0
- codecop/prompts/rank_sqlite.md +94 -0
- codecop/prompts/scenario_variants.md +20 -0
- codecop/rank.py +1473 -0
- codecop/realdb/__init__.py +688 -0
- codecop/realdb/clickhouse.py +1223 -0
- codecop/realdb/facts.py +815 -0
- codecop/realdb/locality.py +964 -0
- codecop/realdb/locks.py +355 -0
- codecop/realdb/match.py +531 -0
- codecop/realdb/postgres.py +643 -0
- codecop/realdb/ratios.py +77 -0
- codecop/realdb/sample.py +126 -0
- codecop/relations.py +227 -0
- codecop/report.py +1854 -0
- codecop/resources.py +332 -0
- codecop/resources_view.py +266 -0
- codecop/rules/entry_points.toml +1013 -0
- codecop/rules/sinks.toml +362 -0
- codecop/runsonce.py +8 -0
- codecop/sandboxschema.py +555 -0
- codecop/scenario_agent.py +172 -0
- codecop/scenario_bind.py +507 -0
- codecop/scenario_sql.py +971 -0
- codecop/scenarios.py +675 -0
- codecop/scenarios_view.py +274 -0
- codecop/schemacli.py +67 -0
- codecop/schemas/areas_output.schema.json +21 -0
- codecop/schemas/profile_output.schema.json +362 -0
- codecop/schemas/rank_output.schema.json +385 -0
- codecop/sizes.py +200 -0
- codecop/sqlinfo.py +558 -0
- codecop/typedparams.py +576 -0
- codecop/verdicts.py +212 -0
- codecop/writebench.py +720 -0
- codecop/writecost.py +440 -0
- codecop/writes.py +1208 -0
- codecop-0.1.0.dist-info/METADATA +42 -0
- codecop-0.1.0.dist-info/RECORD +222 -0
- codecop-0.1.0.dist-info/WHEEL +4 -0
- codecop-0.1.0.dist-info/entry_points.txt +2 -0
- codecop-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,1438 @@
|
|
|
1
|
+
"""Regex call sites, per language CodeCop reads: Python (ast), TypeScript/JavaScript, Go, Java and Rust (tree-sitter).
|
|
2
|
+
|
|
3
|
+
A site is where a pattern is used on a string (the call the trace can place on a request path), with the pattern itself
|
|
4
|
+
(a literal, a constant, or built from literals and constants, resolved like SQL templates), its flags, the engine that
|
|
5
|
+
runs it, the API (match, search, find all, replace, split), how it is compiled (`once`: module level, a static, a lazy
|
|
6
|
+
global, `sync.Once`; `function`: on every call; `loop`: inside a loop), what flows in when that is cheap to tell, and a
|
|
7
|
+
length bound seen on the input before the call. A compiled pattern with no use in the repository is a site at its
|
|
8
|
+
definition. A table of patterns (a list or array compiled in one place) gives one site per pattern at its own line.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import ast
|
|
14
|
+
import json
|
|
15
|
+
import os
|
|
16
|
+
import re
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
|
|
19
|
+
from ...discover.base import read_text
|
|
20
|
+
|
|
21
|
+
# api -> the harness mode (what the call computes): match (anchored at the start), full, search (first match), all
|
|
22
|
+
# (every match), count (how many), bool (is there one)
|
|
23
|
+
PY_MODES = {"match": "match", "fullmatch": "full", "search": "search", "findall": "all", "finditer": "all", "sub": "all",
|
|
24
|
+
"subn": "all", "split": "all", "compile": "search", "escape": None, "purge": None}
|
|
25
|
+
JS_MODES = {"test": "bool", "exec": "search", "match": "search", "matchAll": "all", "replace": "all", "replaceAll": "all",
|
|
26
|
+
"split": "all", "search": "search", "literal": "search", "new": "search"}
|
|
27
|
+
GO_MODES = {"MatchString": "bool", "Match": "bool", "MatchReader": "bool", "FindString": "search", "Find": "search",
|
|
28
|
+
"FindStringIndex": "search", "FindIndex": "search", "FindStringSubmatch": "search", "FindSubmatch": "search",
|
|
29
|
+
"FindStringSubmatchIndex": "search", "FindAllString": "all", "FindAll": "all", "FindAllStringIndex": "all",
|
|
30
|
+
"FindAllStringSubmatch": "all", "FindAllStringSubmatchIndex": "all", "FindAllSubmatch": "all", "ReplaceAllString": "all",
|
|
31
|
+
"ReplaceAll": "all", "ReplaceAllStringFunc": "all", "ReplaceAllLiteralString": "all", "ReplaceAllFunc": "all", "Split": "all",
|
|
32
|
+
"MustCompile": "search", "Compile": "search", "MustCompilePOSIX": "search", "CompilePOSIX": "search"}
|
|
33
|
+
JAVA_MODES = {"matches": "full", "find": "search", "lookingAt": "match", "replaceAll": "all", "replaceFirst": "search",
|
|
34
|
+
"split": "all", "compile": "search", "results": "all", "matcher": "search"}
|
|
35
|
+
RUST_MODES = {"is_match": "bool", "find": "search", "find_iter": "all", "captures": "search", "captures_iter": "all",
|
|
36
|
+
"replace": "search", "replace_all": "all", "replacen": "all", "split": "all", "splitn": "all", "shortest_match": "bool",
|
|
37
|
+
"new": "search", "find_at": "search", "is_match_at": "bool", "captures_at": "search", "count": "count"}
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def mode_of(language: str, api: str) -> str | None:
|
|
41
|
+
table = {"python": PY_MODES, "typescript": JS_MODES, "go": GO_MODES, "java": JAVA_MODES, "rust": RUST_MODES}.get(language, {})
|
|
42
|
+
return table.get(api, "search")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def trim(text: str, n: int = 100) -> str:
|
|
46
|
+
text = " ".join(str(text or "").split())
|
|
47
|
+
return text if len(text) <= n else text[: n - 1] + "…"
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _no_surrogates(text: str) -> str:
|
|
51
|
+
"""A lone surrogate (a `\\ud800` escape decoded) written back as its escape: the same pattern, and valid UTF-8."""
|
|
52
|
+
if not text or not any(0xD800 <= ord(c) <= 0xDFFF for c in text):
|
|
53
|
+
return text
|
|
54
|
+
return "".join(f"\\u{ord(c):04x}" if 0xD800 <= ord(c) <= 0xDFFF else c for c in text)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def make(file: str, line: int, language: str, engine: str, pattern: str | None, flags: str, api: str, *, symbol: str = "",
|
|
58
|
+
compiled: str = "once", in_loop: bool = False, source: str = "literal", def_line: int | None = None, def_file: str = "",
|
|
59
|
+
arg: str = "", bound: dict | None = None, take: int | None = None, table: str = "", flows: str = "", name: str = "",
|
|
60
|
+
end_line: int | None = None, use: str = "") -> dict:
|
|
61
|
+
if pattern is not None:
|
|
62
|
+
pattern = _no_surrogates(pattern)
|
|
63
|
+
arg, use = _no_surrogates(arg), _no_surrogates(use)
|
|
64
|
+
s = {"file": file, "line": int(line), "end_line": int(end_line or line), "language": language, "engine": engine,
|
|
65
|
+
"pattern": pattern, "flags": flags, "api": api, "mode": mode_of(language, api), "symbol": symbol, "compiled": compiled,
|
|
66
|
+
"in_loop": bool(in_loop), "source": source if pattern is not None else "built", "def_file": def_file or file,
|
|
67
|
+
"def_line": int(def_line or line), "arg": trim(arg, 80), "name": name}
|
|
68
|
+
if bound:
|
|
69
|
+
s["bound"] = bound
|
|
70
|
+
if take:
|
|
71
|
+
s["take"] = int(take)
|
|
72
|
+
if table:
|
|
73
|
+
s["table"] = table
|
|
74
|
+
if flows:
|
|
75
|
+
s["flows"] = flows
|
|
76
|
+
if use:
|
|
77
|
+
s["use"] = trim(use, 160)
|
|
78
|
+
# the id's text: the pattern and the call, so the same call keeps its id when lines move
|
|
79
|
+
s["text"] = f"{engine}|{pattern if pattern is not None else '?'}|{flags}|{api}|{name}|{use and trim(use, 80)}"
|
|
80
|
+
return s
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
# --- Python ---------------------------------------------------------------------------------------------------------------
|
|
84
|
+
|
|
85
|
+
PY_FLAG = {"I": "i", "IGNORECASE": "i", "M": "m", "MULTILINE": "m", "S": "s", "DOTALL": "s", "X": "x", "VERBOSE": "x",
|
|
86
|
+
"A": "a", "ASCII": "a", "U": "", "UNICODE": ""}
|
|
87
|
+
RE_FUNCS = {"compile", "match", "fullmatch", "search", "findall", "finditer", "sub", "subn", "split"}
|
|
88
|
+
REQUEST_WORDS = re.compile(r"\b(request|req|body|payload|params|query|form|json|headers|prompt|message|messages|text|content|input|user_input)\b", re.I)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
class _PyConsts:
|
|
92
|
+
"""Module-level names of one Python file: strings, lists of strings, ints, and compiled patterns."""
|
|
93
|
+
|
|
94
|
+
def __init__(self):
|
|
95
|
+
self.strings: dict[str, str] = {}
|
|
96
|
+
self.lists: dict[str, list[tuple[str, int]]] = {}
|
|
97
|
+
self.ints: dict[str, int] = {}
|
|
98
|
+
self.compiled: dict[str, dict] = {} # name -> {pattern, flags, line, engine}
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _py_flags(node, aliases) -> str:
|
|
102
|
+
out = ""
|
|
103
|
+
if node is None:
|
|
104
|
+
return out
|
|
105
|
+
for x in ast.walk(node):
|
|
106
|
+
if isinstance(x, ast.Attribute) and isinstance(x.value, ast.Name) and x.value.id in aliases:
|
|
107
|
+
out += PY_FLAG.get(x.attr, "")
|
|
108
|
+
elif isinstance(x, ast.Name) and x.id in PY_FLAG and len(x.id) > 1:
|
|
109
|
+
out += PY_FLAG.get(x.id, "")
|
|
110
|
+
return "".join(sorted(set(out)))
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _py_str(node, consts: _PyConsts, depth: int = 0):
|
|
114
|
+
"""The string a node evaluates to when it is built from literals and module constants; None otherwise."""
|
|
115
|
+
if depth > 8 or node is None:
|
|
116
|
+
return None
|
|
117
|
+
if isinstance(node, ast.Constant):
|
|
118
|
+
if isinstance(node.value, str):
|
|
119
|
+
return node.value
|
|
120
|
+
if isinstance(node.value, bytes):
|
|
121
|
+
return node.value.decode("latin-1")
|
|
122
|
+
return None
|
|
123
|
+
if isinstance(node, ast.Name):
|
|
124
|
+
return consts.strings.get(node.id)
|
|
125
|
+
if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add):
|
|
126
|
+
a, b = _py_str(node.left, consts, depth + 1), _py_str(node.right, consts, depth + 1)
|
|
127
|
+
return a + b if a is not None and b is not None else None
|
|
128
|
+
if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Mod):
|
|
129
|
+
return None
|
|
130
|
+
if isinstance(node, ast.JoinedStr):
|
|
131
|
+
parts = []
|
|
132
|
+
for v in node.values:
|
|
133
|
+
if isinstance(v, ast.Constant):
|
|
134
|
+
parts.append(str(v.value))
|
|
135
|
+
elif isinstance(v, ast.FormattedValue) and v.format_spec is None:
|
|
136
|
+
s = _py_str(v.value, consts, depth + 1)
|
|
137
|
+
if s is None:
|
|
138
|
+
return None
|
|
139
|
+
parts.append(s)
|
|
140
|
+
else:
|
|
141
|
+
return None
|
|
142
|
+
return "".join(parts)
|
|
143
|
+
if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute):
|
|
144
|
+
f = node.func
|
|
145
|
+
if f.attr == "join" and len(node.args) == 1:
|
|
146
|
+
sep = _py_str(f.value, consts, depth + 1)
|
|
147
|
+
items = _py_list(node.args[0], consts, depth + 1)
|
|
148
|
+
if sep is not None and items is not None:
|
|
149
|
+
return sep.join(items)
|
|
150
|
+
if f.attr == "escape" and isinstance(f.value, ast.Name) and f.value.id in ("re", "regex") and node.args:
|
|
151
|
+
s = _py_str(node.args[0], consts, depth + 1)
|
|
152
|
+
return re.escape(s) if s is not None else None
|
|
153
|
+
if f.attr in ("strip", "lower", "upper") and not node.args:
|
|
154
|
+
s = _py_str(f.value, consts, depth + 1)
|
|
155
|
+
return getattr(s, f.attr)() if s is not None else None
|
|
156
|
+
return None
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _py_list(node, consts: _PyConsts, depth: int = 0):
|
|
160
|
+
if isinstance(node, (ast.List, ast.Tuple, ast.Set)):
|
|
161
|
+
out = [_py_str(e, consts, depth + 1) for e in node.elts]
|
|
162
|
+
return out if all(x is not None for x in out) else None
|
|
163
|
+
if isinstance(node, ast.Name) and node.id in consts.lists:
|
|
164
|
+
return [s for s, _ in consts.lists[node.id]]
|
|
165
|
+
if isinstance(node, (ast.GeneratorExp, ast.ListComp)) and len(node.generators) == 1:
|
|
166
|
+
g = node.generators[0]
|
|
167
|
+
src = _py_list(g.iter, consts, depth + 1)
|
|
168
|
+
if src is not None and isinstance(node.elt, ast.Call) and isinstance(node.elt.func, ast.Attribute) \
|
|
169
|
+
and node.elt.func.attr == "escape" and isinstance(g.target, ast.Name):
|
|
170
|
+
return [re.escape(s) for s in src]
|
|
171
|
+
if src is not None and isinstance(node.elt, ast.Name) and isinstance(g.target, ast.Name) and node.elt.id == g.target.id:
|
|
172
|
+
return src
|
|
173
|
+
return None
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def _re_aliases(tree) -> tuple[set, dict]:
|
|
177
|
+
"""Names the `re` (or `regex`) module goes by in a file, and functions imported from it (`from re import search`)."""
|
|
178
|
+
mods, funcs = set(), {}
|
|
179
|
+
for n in ast.walk(tree):
|
|
180
|
+
if isinstance(n, ast.Import):
|
|
181
|
+
for a in n.names:
|
|
182
|
+
if a.name in ("re", "regex"):
|
|
183
|
+
mods.add(a.asname or a.name)
|
|
184
|
+
elif isinstance(n, ast.ImportFrom) and n.module in ("re", "regex") and n.level == 0:
|
|
185
|
+
for a in n.names:
|
|
186
|
+
if a.name in RE_FUNCS:
|
|
187
|
+
funcs[a.asname or a.name] = (a.name, n.module)
|
|
188
|
+
return mods, funcs
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def _compile_call(node, mods, funcs):
|
|
192
|
+
"""(engine, args) when node is re.compile(...)/regex.compile(...)."""
|
|
193
|
+
if not isinstance(node, ast.Call):
|
|
194
|
+
return None
|
|
195
|
+
f = node.func
|
|
196
|
+
if isinstance(f, ast.Attribute) and isinstance(f.value, ast.Name) and f.value.id in mods and f.attr == "compile":
|
|
197
|
+
return ("python-regex" if f.value.id == "regex" else "python"), node
|
|
198
|
+
if isinstance(f, ast.Name) and funcs.get(f.id, ("", ""))[0] == "compile":
|
|
199
|
+
return ("python-regex" if funcs[f.id][1] == "regex" else "python"), node
|
|
200
|
+
return None
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def _py_module_consts(tree, mods, funcs) -> _PyConsts:
|
|
204
|
+
c = _PyConsts()
|
|
205
|
+
body = list(tree.body)
|
|
206
|
+
for stmt in body:
|
|
207
|
+
targets, value = [], None
|
|
208
|
+
if isinstance(stmt, ast.Assign):
|
|
209
|
+
targets, value = [t for t in stmt.targets if isinstance(t, ast.Name)], stmt.value
|
|
210
|
+
elif isinstance(stmt, ast.AnnAssign) and isinstance(stmt.target, ast.Name) and stmt.value is not None:
|
|
211
|
+
targets, value = [stmt.target], stmt.value
|
|
212
|
+
if not targets or value is None:
|
|
213
|
+
continue
|
|
214
|
+
for t in targets:
|
|
215
|
+
s = _py_str(value, c)
|
|
216
|
+
if s is not None:
|
|
217
|
+
c.strings[t.id] = s
|
|
218
|
+
continue
|
|
219
|
+
if isinstance(value, ast.Constant) and isinstance(value.value, int) and not isinstance(value.value, bool):
|
|
220
|
+
c.ints[t.id] = value.value
|
|
221
|
+
continue
|
|
222
|
+
if isinstance(value, (ast.List, ast.Tuple)):
|
|
223
|
+
items = [(_py_str(e, c), getattr(e, "lineno", stmt.lineno)) for e in value.elts]
|
|
224
|
+
if items and all(s is not None for s, _ in items):
|
|
225
|
+
c.lists[t.id] = items
|
|
226
|
+
continue
|
|
227
|
+
cc = _compile_call(value, mods, funcs)
|
|
228
|
+
if cc and cc[1].args:
|
|
229
|
+
pat = _py_str(cc[1].args[0], c)
|
|
230
|
+
fl = _py_flags(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), mods)
|
|
231
|
+
c.compiled[t.id] = {"pattern": pat, "flags": fl, "line": stmt.lineno, "engine": cc[0]}
|
|
232
|
+
return c
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def _bound_py(fn, call_line: int, arg, consts: _PyConsts) -> dict | None:
|
|
236
|
+
"""A length bound on the input seen before the call: `text[:N]` as the argument, `text = text[:N]`, or `if
|
|
237
|
+
len(text) > N: return/raise` in the same function. N may be a module constant."""
|
|
238
|
+
def num(n):
|
|
239
|
+
if isinstance(n, ast.Constant) and isinstance(n.value, int) and not isinstance(n.value, bool):
|
|
240
|
+
return n.value
|
|
241
|
+
if isinstance(n, ast.Name) and n.id in consts.ints:
|
|
242
|
+
return consts.ints[n.id]
|
|
243
|
+
return None
|
|
244
|
+
|
|
245
|
+
def sliced(n):
|
|
246
|
+
if isinstance(n, ast.Subscript) and isinstance(n.slice, ast.Slice) and n.slice.lower is None and n.slice.step is None:
|
|
247
|
+
return num(n.slice.upper)
|
|
248
|
+
if isinstance(n, ast.Subscript) and isinstance(n.slice, ast.Slice) and n.slice.upper is None and n.slice.step is None \
|
|
249
|
+
and isinstance(n.slice.lower, ast.UnaryOp) and isinstance(n.slice.lower.op, ast.USub):
|
|
250
|
+
return num(n.slice.lower.operand)
|
|
251
|
+
return None
|
|
252
|
+
if arg is not None:
|
|
253
|
+
k = sliced(arg)
|
|
254
|
+
if k is not None:
|
|
255
|
+
return {"n": k, "line": call_line, "text": trim(ast.unparse(arg), 80)}
|
|
256
|
+
name = arg.id if isinstance(arg, ast.Name) else None
|
|
257
|
+
if not name or fn is None:
|
|
258
|
+
return None
|
|
259
|
+
best = None
|
|
260
|
+
for st in ast.walk(fn):
|
|
261
|
+
line = getattr(st, "lineno", 0)
|
|
262
|
+
if not line or line >= call_line:
|
|
263
|
+
continue
|
|
264
|
+
if isinstance(st, ast.Assign) and any(isinstance(t, ast.Name) and t.id == name for t in st.targets):
|
|
265
|
+
k = sliced(st.value)
|
|
266
|
+
if k is not None:
|
|
267
|
+
best = {"n": k, "line": line, "text": trim(ast.unparse(st), 80)}
|
|
268
|
+
elif isinstance(st, ast.If) and isinstance(st.test, ast.Compare) and len(st.test.ops) == 1:
|
|
269
|
+
t = st.test
|
|
270
|
+
left = t.left
|
|
271
|
+
if isinstance(left, ast.Call) and isinstance(left.func, ast.Name) and left.func.id == "len" and left.args \
|
|
272
|
+
and isinstance(left.args[0], ast.Name) and left.args[0].id == name and isinstance(t.ops[0], (ast.Gt, ast.GtE)):
|
|
273
|
+
k = num(t.comparators[0])
|
|
274
|
+
exits = any(isinstance(b, (ast.Return, ast.Raise)) for b in st.body)
|
|
275
|
+
cuts = any(isinstance(b, ast.Assign) and sliced(b.value) is not None for b in st.body)
|
|
276
|
+
if k is not None and (exits or cuts):
|
|
277
|
+
best = {"n": k, "line": line, "text": trim(ast.unparse(st.test), 80)}
|
|
278
|
+
return best
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def python_sites(root: Path, files: list[str]) -> list[dict]:
|
|
282
|
+
trees: dict[str, tuple] = {}
|
|
283
|
+
global_compiled: dict[str, list[tuple[str, dict]]] = {}
|
|
284
|
+
for rel in files:
|
|
285
|
+
text = read_text(root / rel)
|
|
286
|
+
if not text or "import" not in text:
|
|
287
|
+
continue
|
|
288
|
+
try:
|
|
289
|
+
tree = ast.parse(text)
|
|
290
|
+
except (SyntaxError, ValueError, RecursionError):
|
|
291
|
+
continue
|
|
292
|
+
mods, funcs = _re_aliases(tree)
|
|
293
|
+
consts = _py_module_consts(tree, mods, funcs)
|
|
294
|
+
trees[rel] = (tree, mods, funcs, consts)
|
|
295
|
+
for name, d in consts.compiled.items():
|
|
296
|
+
global_compiled.setdefault(name, []).append((rel, d))
|
|
297
|
+
out: list[dict] = []
|
|
298
|
+
used_defs: set = set()
|
|
299
|
+
for rel, (tree, mods, funcs, consts) in trees.items():
|
|
300
|
+
imported = {}
|
|
301
|
+
for n in ast.walk(tree):
|
|
302
|
+
if isinstance(n, ast.ImportFrom):
|
|
303
|
+
for a in n.names:
|
|
304
|
+
defs = global_compiled.get(a.name) or []
|
|
305
|
+
if len(defs) == 1 and defs[0][0] != rel:
|
|
306
|
+
imported[a.asname or a.name] = defs[0]
|
|
307
|
+
for parent in ast.walk(tree):
|
|
308
|
+
for child in ast.iter_child_nodes(parent):
|
|
309
|
+
child._codecop_parent = parent # noqa: SLF001 -- what a compile call sits in
|
|
310
|
+
_PyWalk(rel, mods, funcs, consts, imported, out, used_defs).visit(tree)
|
|
311
|
+
# compiled patterns nothing in the repository uses (exported, or used dynamically): a site at the definition
|
|
312
|
+
for name, defs in global_compiled.items():
|
|
313
|
+
for rel, d in defs:
|
|
314
|
+
if (rel, name) not in used_defs:
|
|
315
|
+
out.append(make(rel, d["line"], "python", d["engine"], d["pattern"], d["flags"], "compile", compiled="once",
|
|
316
|
+
source="constant", name=name))
|
|
317
|
+
return out
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
class _PyWalk(ast.NodeVisitor):
|
|
321
|
+
def __init__(self, rel, mods, funcs, consts, imported, out, used_defs):
|
|
322
|
+
self.rel, self.mods, self.funcs, self.consts, self.imported = rel, mods, funcs, consts, imported
|
|
323
|
+
self.out, self.used_defs = out, used_defs
|
|
324
|
+
self.stack: list[str] = []
|
|
325
|
+
self.fns: list = []
|
|
326
|
+
self.loop = 0
|
|
327
|
+
self.locals: list[dict] = [{}]
|
|
328
|
+
self.cls_attrs: list[dict] = [{}]
|
|
329
|
+
|
|
330
|
+
def symbol(self) -> str:
|
|
331
|
+
return ".".join(self.stack)
|
|
332
|
+
|
|
333
|
+
def visit_ClassDef(self, node):
|
|
334
|
+
self.stack.append(node.name)
|
|
335
|
+
attrs = {}
|
|
336
|
+
for st in node.body:
|
|
337
|
+
if isinstance(st, ast.Assign) and len(st.targets) == 1 and isinstance(st.targets[0], ast.Name):
|
|
338
|
+
cc = _compile_call(st.value, self.mods, self.funcs)
|
|
339
|
+
if cc and cc[1].args:
|
|
340
|
+
attrs[st.targets[0].id] = {"pattern": _py_str(cc[1].args[0], self.consts), "line": st.lineno, "engine": cc[0],
|
|
341
|
+
"flags": _py_flags(cc[1].args[1] if len(cc[1].args) > 1 else None, self.mods)}
|
|
342
|
+
# self.X = re.compile(...) in any method
|
|
343
|
+
for n in ast.walk(node):
|
|
344
|
+
if isinstance(n, ast.Assign) and len(n.targets) == 1 and isinstance(n.targets[0], ast.Attribute) \
|
|
345
|
+
and isinstance(n.targets[0].value, ast.Name) and n.targets[0].value.id == "self":
|
|
346
|
+
cc = _compile_call(n.value, self.mods, self.funcs)
|
|
347
|
+
if cc and cc[1].args:
|
|
348
|
+
attrs[n.targets[0].attr] = {"pattern": _py_str(cc[1].args[0], self.consts), "line": n.lineno, "engine": cc[0],
|
|
349
|
+
"flags": _py_flags(cc[1].args[1] if len(cc[1].args) > 1 else None, self.mods)}
|
|
350
|
+
self.cls_attrs.append(attrs)
|
|
351
|
+
self.generic_visit(node)
|
|
352
|
+
self.cls_attrs.pop()
|
|
353
|
+
self.stack.pop()
|
|
354
|
+
|
|
355
|
+
def visit_FunctionDef(self, node):
|
|
356
|
+
for d in node.decorator_list:
|
|
357
|
+
self.visit(d)
|
|
358
|
+
self.stack.append(node.name)
|
|
359
|
+
self.fns.append(node)
|
|
360
|
+
saved, self.loop = self.loop, 0
|
|
361
|
+
self.locals.append({})
|
|
362
|
+
for st in node.body:
|
|
363
|
+
self.visit(st)
|
|
364
|
+
self.locals.pop()
|
|
365
|
+
self.loop = saved
|
|
366
|
+
self.fns.pop()
|
|
367
|
+
self.stack.pop()
|
|
368
|
+
|
|
369
|
+
visit_AsyncFunctionDef = visit_FunctionDef
|
|
370
|
+
|
|
371
|
+
def _loop(self, node):
|
|
372
|
+
self.loop += 1
|
|
373
|
+
self.generic_visit(node)
|
|
374
|
+
self.loop -= 1
|
|
375
|
+
|
|
376
|
+
visit_For = visit_While = visit_AsyncFor = _loop
|
|
377
|
+
|
|
378
|
+
def _comp(self, node):
|
|
379
|
+
# [re.compile(p) for p in TABLE]: one site per pattern of the table, at its own line
|
|
380
|
+
g = node.generators[0] if len(node.generators) == 1 else None
|
|
381
|
+
elt = node.elt if not isinstance(node, ast.DictComp) else node.value
|
|
382
|
+
if g is not None and isinstance(g.iter, ast.Name) and g.iter.id in self.consts.lists:
|
|
383
|
+
target_names = {x.id for x in ast.walk(g.target) if isinstance(x, ast.Name)}
|
|
384
|
+
for x in ast.walk(elt):
|
|
385
|
+
cc = _compile_call(x, self.mods, self.funcs)
|
|
386
|
+
if cc and cc[1].args and isinstance(cc[1].args[0], ast.Name) and cc[1].args[0].id in target_names:
|
|
387
|
+
fl = _py_flags(cc[1].args[1] if len(cc[1].args) > 1 else None, self.mods)
|
|
388
|
+
for pat, line in self.consts.lists[g.iter.id]:
|
|
389
|
+
self.out.append(make(self.rel, line, "python", cc[0], pat, fl, "compile", symbol=self.symbol(),
|
|
390
|
+
compiled="once" if not self.fns else "function", source="table", def_line=line,
|
|
391
|
+
table=f"{self.rel}:{g.iter.id}", name=g.iter.id))
|
|
392
|
+
self.used_defs.add((self.rel, "__table__" + g.iter.id))
|
|
393
|
+
break
|
|
394
|
+
self.loop += 1
|
|
395
|
+
self.generic_visit(node)
|
|
396
|
+
self.loop -= 1
|
|
397
|
+
|
|
398
|
+
visit_ListComp = visit_SetComp = visit_DictComp = visit_GeneratorExp = _comp
|
|
399
|
+
|
|
400
|
+
def visit_Assign(self, node):
|
|
401
|
+
if self.fns and len(node.targets) == 1 and isinstance(node.targets[0], ast.Name):
|
|
402
|
+
cc = _compile_call(node.value, self.mods, self.funcs)
|
|
403
|
+
if cc and cc[1].args:
|
|
404
|
+
self.locals[-1][node.targets[0].id] = {"pattern": _py_str(cc[1].args[0], self.consts), "line": node.lineno,
|
|
405
|
+
"engine": cc[0], "loop": self.loop > 0,
|
|
406
|
+
"flags": _py_flags(cc[1].args[1] if len(cc[1].args) > 1 else None, self.mods)}
|
|
407
|
+
self.generic_visit(node)
|
|
408
|
+
|
|
409
|
+
def visit_Call(self, node):
|
|
410
|
+
f = node.func
|
|
411
|
+
fn = self.fns[-1] if self.fns else None
|
|
412
|
+
# re.compile(...) kept in a list, tuple, dict or passed on (`self.patterns = [re.compile(...), ...]`): it runs
|
|
413
|
+
# wherever the collection is iterated, which is not traced here; the site is the compile itself
|
|
414
|
+
cc = _compile_call(node, self.mods, self.funcs)
|
|
415
|
+
par = getattr(node, "_codecop_parent", None)
|
|
416
|
+
if cc and node.args and isinstance(par, (ast.List, ast.Tuple, ast.Set, ast.Dict, ast.keyword, ast.Call)) \
|
|
417
|
+
and not isinstance(getattr(par, "_codecop_parent", None), (ast.ListComp, ast.SetComp, ast.DictComp, ast.GeneratorExp)):
|
|
418
|
+
pat = _py_str(node.args[0], self.consts)
|
|
419
|
+
if pat is not None:
|
|
420
|
+
fl = _py_flags(node.args[1] if len(node.args) > 1 else next((k.value for k in node.keywords if k.arg == "flags"), None), self.mods)
|
|
421
|
+
self.out.append(make(self.rel, node.lineno, "python", cc[0], pat, fl, "compile", symbol=self.symbol(),
|
|
422
|
+
compiled="function" if self.fns and self.stack[-1:] != ["__init__"] else "once",
|
|
423
|
+
in_loop=self.loop > 0, source="table", use=ast.unparse(node), name="(collection)"))
|
|
424
|
+
api, d, engine, arg, flags, how = None, None, "python", None, "", "once"
|
|
425
|
+
# re.search(p, s, flags) / search(p, s)
|
|
426
|
+
if isinstance(f, ast.Attribute) and isinstance(f.value, ast.Name) and f.value.id in self.mods and f.attr in RE_FUNCS - {"compile"}:
|
|
427
|
+
api, engine = f.attr, ("python-regex" if f.value.id == "regex" else "python")
|
|
428
|
+
elif isinstance(f, ast.Name) and f.id in self.funcs and self.funcs[f.id][0] != "compile":
|
|
429
|
+
api, engine = self.funcs[f.id][0], ("python-regex" if self.funcs[f.id][1] == "regex" else "python")
|
|
430
|
+
if api and node.args:
|
|
431
|
+
pat = _py_str(node.args[0], self.consts)
|
|
432
|
+
fl_node = node.args[3 if api in ("sub", "subn") else 2] if len(node.args) > (3 if api in ("sub", "subn") else 2) else \
|
|
433
|
+
next((k.value for k in node.keywords if k.arg == "flags"), None)
|
|
434
|
+
arg = node.args[2 if api in ("sub", "subn") else 1] if len(node.args) > (2 if api in ("sub", "subn") else 1) else None
|
|
435
|
+
self._site(node, engine, pat, _py_flags(fl_node, self.mods), api, arg, compiled="function" if self.fns else "once",
|
|
436
|
+
source="literal" if isinstance(node.args[0], ast.Constant) else "constant", fn=fn)
|
|
437
|
+
elif isinstance(f, ast.Attribute) and f.attr in RE_FUNCS - {"compile"}:
|
|
438
|
+
v = f.value
|
|
439
|
+
name, d = "", None
|
|
440
|
+
if isinstance(v, ast.Name):
|
|
441
|
+
name = v.id
|
|
442
|
+
d = self.locals[-1].get(v.id) or self.consts.compiled.get(v.id)
|
|
443
|
+
if d is None and v.id in self.imported:
|
|
444
|
+
d = self.imported[v.id][1]
|
|
445
|
+
self.used_defs.add((self.imported[v.id][0], v.id))
|
|
446
|
+
elif d is not None and v.id in self.consts.compiled and v.id not in self.locals[-1]:
|
|
447
|
+
self.used_defs.add((self.rel, v.id))
|
|
448
|
+
how = "loop" if d is not None and d.get("loop") else ("function" if d is not None and v.id in self.locals[-1] else "once")
|
|
449
|
+
elif isinstance(v, ast.Attribute) and isinstance(v.value, ast.Name) and v.value.id in ("self", "cls"):
|
|
450
|
+
name = v.attr
|
|
451
|
+
d = self.cls_attrs[-1].get(v.attr)
|
|
452
|
+
if d is not None and node.args:
|
|
453
|
+
arg = node.args[1] if f.attr in ("sub", "subn") and len(node.args) > 1 else node.args[0]
|
|
454
|
+
self._site(node, d.get("engine", "python"), d.get("pattern"), d.get("flags", ""), f.attr, arg, compiled=how,
|
|
455
|
+
source="constant", def_line=d.get("line"), fn=fn, name=name)
|
|
456
|
+
self.generic_visit(node)
|
|
457
|
+
|
|
458
|
+
def _site(self, node, engine, pat, flags, api, arg, *, compiled, source, fn, def_line=None, name=""):
|
|
459
|
+
bound = _bound_py(fn, node.lineno, arg, self.consts) if arg is not None else None
|
|
460
|
+
arg_text = ast.unparse(arg) if arg is not None else ""
|
|
461
|
+
flows = ""
|
|
462
|
+
if arg is not None and REQUEST_WORDS.search(arg_text):
|
|
463
|
+
flows = "request"
|
|
464
|
+
if fn is not None and arg is not None and isinstance(arg, ast.Name) and arg.id in {a.arg for a in fn.args.args}:
|
|
465
|
+
flows = flows or "parameter"
|
|
466
|
+
take, use = (_py_count_use(node) if api == "findall" else (None, None))
|
|
467
|
+
self.out.append(make(self.rel, node.lineno, "python", engine, pat, flags, api, symbol=self.symbol(), compiled=compiled,
|
|
468
|
+
in_loop=self.loop > 0, source=source, def_line=def_line, arg=arg_text, bound=bound, flows=flows,
|
|
469
|
+
name=name, end_line=getattr(node, "end_lineno", node.lineno), use=use or ast.unparse(node), take=take))
|
|
470
|
+
|
|
471
|
+
|
|
472
|
+
_CMP_NEED = {ast.Gt: 1, ast.GtE: 0, ast.Eq: 1, ast.NotEq: 1, ast.Lt: 0, ast.LtE: 1}
|
|
473
|
+
|
|
474
|
+
|
|
475
|
+
def _py_count_use(call) -> tuple:
|
|
476
|
+
"""(N, the expression) when a findall's list is only counted against a constant (`len(x.findall(s)) > 3`: the first 4
|
|
477
|
+
matches decide) or only tested for being non-empty (`if x.findall(s):`: the first match decides)."""
|
|
478
|
+
par = getattr(call, "_codecop_parent", None)
|
|
479
|
+
if isinstance(par, ast.Call) and isinstance(par.func, ast.Name) and par.func.id == "len" and len(par.args) == 1:
|
|
480
|
+
cmp_ = getattr(par, "_codecop_parent", None)
|
|
481
|
+
if isinstance(cmp_, ast.Compare) and len(cmp_.ops) == 1 and type(cmp_.ops[0]) in _CMP_NEED:
|
|
482
|
+
other = cmp_.comparators[0] if cmp_.left is par else cmp_.left
|
|
483
|
+
if isinstance(other, ast.Constant) and isinstance(other.value, int) and not isinstance(other.value, bool) and other.value >= 0:
|
|
484
|
+
op = type(cmp_.ops[0])
|
|
485
|
+
if cmp_.left is not par: # 3 < len(...): mirror the operator
|
|
486
|
+
op = {ast.Gt: ast.Lt, ast.GtE: ast.LtE, ast.Lt: ast.Gt, ast.LtE: ast.GtE}.get(op, op)
|
|
487
|
+
n = other.value + _CMP_NEED[op]
|
|
488
|
+
return (n, ast.unparse(cmp_)) if n >= 1 else (None, None)
|
|
489
|
+
return None, None
|
|
490
|
+
truth = par
|
|
491
|
+
if isinstance(par, ast.BoolOp): # `if a and x.findall(s):` -- only when the whole is itself a test
|
|
492
|
+
truth = getattr(par, "_codecop_parent", None)
|
|
493
|
+
if not (isinstance(truth, (ast.If, ast.While, ast.IfExp)) and truth.test is par):
|
|
494
|
+
return None, None
|
|
495
|
+
return 1, ast.unparse(call)
|
|
496
|
+
if isinstance(par, (ast.If, ast.While, ast.IfExp)) and par.test is call \
|
|
497
|
+
or isinstance(par, ast.UnaryOp) and isinstance(par.op, ast.Not) \
|
|
498
|
+
or isinstance(par, ast.Call) and isinstance(par.func, ast.Name) and par.func.id == "bool":
|
|
499
|
+
return 1, ast.unparse(par if not isinstance(par, (ast.If, ast.While, ast.IfExp)) else call)
|
|
500
|
+
return None, None
|
|
501
|
+
|
|
502
|
+
|
|
503
|
+
# --- tree-sitter helpers ----------------------------------------------------------------------------------------------------
|
|
504
|
+
|
|
505
|
+
def _ts(lang: str):
|
|
506
|
+
from tree_sitter import Language, Parser
|
|
507
|
+
if lang == "go":
|
|
508
|
+
import tree_sitter_go as m
|
|
509
|
+
L = Language(m.language())
|
|
510
|
+
elif lang == "java":
|
|
511
|
+
import tree_sitter_java as m
|
|
512
|
+
L = Language(m.language())
|
|
513
|
+
elif lang == "rust":
|
|
514
|
+
import tree_sitter_rust as m
|
|
515
|
+
L = Language(m.language())
|
|
516
|
+
elif lang == "tsx":
|
|
517
|
+
import tree_sitter_typescript as m
|
|
518
|
+
L = Language(m.language_tsx())
|
|
519
|
+
else:
|
|
520
|
+
import tree_sitter_typescript as m
|
|
521
|
+
L = Language(m.language_typescript())
|
|
522
|
+
return Parser(L)
|
|
523
|
+
|
|
524
|
+
|
|
525
|
+
_PARSERS: dict = {}
|
|
526
|
+
|
|
527
|
+
|
|
528
|
+
def parser(lang: str):
|
|
529
|
+
if lang not in _PARSERS:
|
|
530
|
+
_PARSERS[lang] = _ts(lang)
|
|
531
|
+
return _PARSERS[lang]
|
|
532
|
+
|
|
533
|
+
|
|
534
|
+
def _t(n) -> str:
|
|
535
|
+
return n.text.decode("utf-8", "replace") if n is not None else ""
|
|
536
|
+
|
|
537
|
+
|
|
538
|
+
def _walk(node):
|
|
539
|
+
stack = [node]
|
|
540
|
+
while stack:
|
|
541
|
+
n = stack.pop()
|
|
542
|
+
yield n
|
|
543
|
+
stack.extend(reversed(n.children))
|
|
544
|
+
|
|
545
|
+
|
|
546
|
+
def _ancestors(n):
|
|
547
|
+
p = n.parent
|
|
548
|
+
while p is not None:
|
|
549
|
+
yield p
|
|
550
|
+
p = p.parent
|
|
551
|
+
|
|
552
|
+
|
|
553
|
+
def _line(n) -> int:
|
|
554
|
+
return n.start_point[0] + 1
|
|
555
|
+
|
|
556
|
+
|
|
557
|
+
# --- Go --------------------------------------------------------------------------------------------------------------------
|
|
558
|
+
|
|
559
|
+
GO_COMPILE = {"MustCompile", "Compile", "MustCompilePOSIX", "CompilePOSIX"}
|
|
560
|
+
GO_ONESHOT = {"MatchString", "Match", "MatchReader"}
|
|
561
|
+
|
|
562
|
+
|
|
563
|
+
def _go_str(n, consts: dict) -> str | None:
|
|
564
|
+
if n is None:
|
|
565
|
+
return None
|
|
566
|
+
t = n.type
|
|
567
|
+
if t == "raw_string_literal":
|
|
568
|
+
return _t(n)[1:-1]
|
|
569
|
+
if t == "interpreted_string_literal":
|
|
570
|
+
try:
|
|
571
|
+
return json.loads(_t(n))
|
|
572
|
+
except ValueError:
|
|
573
|
+
try:
|
|
574
|
+
return ast.literal_eval(_t(n))
|
|
575
|
+
except (ValueError, SyntaxError):
|
|
576
|
+
return None
|
|
577
|
+
if t == "identifier":
|
|
578
|
+
return consts.get(_t(n))
|
|
579
|
+
if t == "binary_expression" and n.child_by_field_name("operator") is not None and _t(n.child_by_field_name("operator")) == "+":
|
|
580
|
+
a, b = _go_str(n.child_by_field_name("left"), consts), _go_str(n.child_by_field_name("right"), consts)
|
|
581
|
+
return a + b if a is not None and b is not None else None
|
|
582
|
+
if t == "parenthesized_expression" and n.named_children:
|
|
583
|
+
return _go_str(n.named_children[0], consts)
|
|
584
|
+
return None
|
|
585
|
+
|
|
586
|
+
|
|
587
|
+
def _go_fn(n):
|
|
588
|
+
for a in _ancestors(n):
|
|
589
|
+
if a.type in ("function_declaration", "method_declaration"):
|
|
590
|
+
nm = a.child_by_field_name("name")
|
|
591
|
+
if a.type == "method_declaration":
|
|
592
|
+
recv = a.child_by_field_name("receiver")
|
|
593
|
+
rt = re.sub(r"[\s*()]", "", _t(recv).split()[-1]) if recv is not None and _t(recv).split() else ""
|
|
594
|
+
return a, (rt + "." if rt else "") + _t(nm)
|
|
595
|
+
return a, _t(nm)
|
|
596
|
+
return None, ""
|
|
597
|
+
|
|
598
|
+
|
|
599
|
+
def _go_once(n, fn) -> bool:
|
|
600
|
+
"""Compiled once: at package level, in init(), or inside sync.Once / sync.OnceValue(s) / a lazy getter."""
|
|
601
|
+
if fn is None:
|
|
602
|
+
return True
|
|
603
|
+
if _t(fn.child_by_field_name("name")) == "init":
|
|
604
|
+
return True
|
|
605
|
+
for a in _ancestors(n):
|
|
606
|
+
if a == fn:
|
|
607
|
+
break
|
|
608
|
+
if a.type == "call_expression":
|
|
609
|
+
callee = _t(a.child_by_field_name("function"))
|
|
610
|
+
if re.search(r"(?:sync\.Once(?:Value|Values|Func)?|\.Do)$", callee):
|
|
611
|
+
return True
|
|
612
|
+
return False
|
|
613
|
+
|
|
614
|
+
|
|
615
|
+
def _go_loop(n, fn) -> bool:
|
|
616
|
+
for a in _ancestors(n):
|
|
617
|
+
if a == fn:
|
|
618
|
+
return False
|
|
619
|
+
if a.type == "for_statement":
|
|
620
|
+
return True
|
|
621
|
+
return False
|
|
622
|
+
|
|
623
|
+
|
|
624
|
+
def go_sites(root: Path, files: list[str]) -> list[dict]:
|
|
625
|
+
parsed = []
|
|
626
|
+
consts: dict[str, str] = {}
|
|
627
|
+
compiled: dict[str, dict] = {}
|
|
628
|
+
for rel in files:
|
|
629
|
+
src = read_text(root / rel)
|
|
630
|
+
if not src or "regexp" not in src:
|
|
631
|
+
continue
|
|
632
|
+
tree = parser("go").parse(src.encode())
|
|
633
|
+
parsed.append((rel, tree))
|
|
634
|
+
for n in _walk(tree.root_node):
|
|
635
|
+
if n.type in ("const_spec", "var_spec") and n.parent is not None and n.parent.parent is not None \
|
|
636
|
+
and n.parent.parent.type == "source_file" or n.type in ("const_spec", "var_spec") and n.parent is not None and n.parent.type == "source_file":
|
|
637
|
+
names = [c for c in n.children_by_field_name("name")]
|
|
638
|
+
vals = n.child_by_field_name("value")
|
|
639
|
+
if vals is None or not names:
|
|
640
|
+
continue
|
|
641
|
+
for nm, v in zip(names, vals.named_children):
|
|
642
|
+
s = _go_str(v, consts)
|
|
643
|
+
if s is not None:
|
|
644
|
+
consts[_t(nm)] = s
|
|
645
|
+
out = []
|
|
646
|
+
used: set = set()
|
|
647
|
+
for rel, tree in parsed:
|
|
648
|
+
for n in _walk(tree.root_node):
|
|
649
|
+
if n.type != "call_expression":
|
|
650
|
+
continue
|
|
651
|
+
f = n.child_by_field_name("function")
|
|
652
|
+
ft = _t(f)
|
|
653
|
+
if not ft.startswith("regexp."):
|
|
654
|
+
continue
|
|
655
|
+
what = ft.split(".", 1)[1]
|
|
656
|
+
if what not in GO_COMPILE and what not in GO_ONESHOT:
|
|
657
|
+
continue
|
|
658
|
+
args = n.child_by_field_name("arguments")
|
|
659
|
+
first = args.named_children[0] if args is not None and args.named_children else None
|
|
660
|
+
pat = _go_str(first, consts)
|
|
661
|
+
fn, sym = _go_fn(n)
|
|
662
|
+
once = _go_once(n, fn)
|
|
663
|
+
loop = _go_loop(n, fn)
|
|
664
|
+
compiled_how = "once" if once else ("loop" if loop else "function")
|
|
665
|
+
if what in GO_ONESHOT:
|
|
666
|
+
arg = args.named_children[1] if len(args.named_children) > 1 else None
|
|
667
|
+
out.append(make(rel, _line(n), "go", "go", pat, "", what, symbol=sym, compiled="loop" if loop else "function",
|
|
668
|
+
in_loop=loop, source="literal" if first is not None and "string" in first.type else "constant",
|
|
669
|
+
arg=_t(arg), use=_t(n)))
|
|
670
|
+
continue
|
|
671
|
+
# the variable it is assigned to: package-level (once) or local
|
|
672
|
+
var = ""
|
|
673
|
+
for a in _ancestors(n):
|
|
674
|
+
if a.type in ("var_spec", "short_var_declaration", "assignment_statement"):
|
|
675
|
+
left = a.child_by_field_name("name") or a.child_by_field_name("left")
|
|
676
|
+
var = _t(left).split(",")[0].strip()
|
|
677
|
+
break
|
|
678
|
+
if a.type in ("block", "function_declaration", "source_file"):
|
|
679
|
+
break
|
|
680
|
+
d = {"pattern": pat, "line": _line(n), "file": rel, "how": compiled_how, "sym": sym, "loop": loop}
|
|
681
|
+
if fn is None and var:
|
|
682
|
+
compiled[var] = d
|
|
683
|
+
else:
|
|
684
|
+
# compiled inside a function: the uses in the same function are where it runs
|
|
685
|
+
body = fn.child_by_field_name("body") if fn is not None else None
|
|
686
|
+
uses = []
|
|
687
|
+
if var and body is not None:
|
|
688
|
+
for u in _walk(body):
|
|
689
|
+
if u.type == "call_expression":
|
|
690
|
+
uf = u.child_by_field_name("function")
|
|
691
|
+
if uf is not None and uf.type == "selector_expression" and _t(uf.child_by_field_name("operand")) == var:
|
|
692
|
+
uses.append(u)
|
|
693
|
+
api = _t(uses[0].child_by_field_name("function").child_by_field_name("field")) if uses else what
|
|
694
|
+
out.append(make(rel, _line(n), "go", "go", pat, "", api if api in GO_MODES else what, symbol=sym,
|
|
695
|
+
compiled=compiled_how, in_loop=loop, source="literal" if first is not None and "string" in first.type else "constant",
|
|
696
|
+
name=var, use=_t(uses[0]) if uses else _t(n)))
|
|
697
|
+
# uses of package-level compiled patterns
|
|
698
|
+
for rel, tree in parsed:
|
|
699
|
+
for n in _walk(tree.root_node):
|
|
700
|
+
if n.type != "call_expression":
|
|
701
|
+
continue
|
|
702
|
+
f = n.child_by_field_name("function")
|
|
703
|
+
if f is None or f.type != "selector_expression":
|
|
704
|
+
continue
|
|
705
|
+
op, field = _t(f.child_by_field_name("operand")), _t(f.child_by_field_name("field"))
|
|
706
|
+
if op in compiled and field in GO_MODES:
|
|
707
|
+
d = compiled[op]
|
|
708
|
+
used.add(op)
|
|
709
|
+
fn, sym = _go_fn(n)
|
|
710
|
+
args = n.child_by_field_name("arguments")
|
|
711
|
+
arg = args.named_children[0] if args is not None and args.named_children else None
|
|
712
|
+
out.append(make(rel, _line(n), "go", "go", d["pattern"], "", field, symbol=sym, compiled="once", in_loop=_go_loop(n, fn),
|
|
713
|
+
source="constant", def_line=d["line"], def_file=d["file"], arg=_t(arg), name=op, use=_t(n)))
|
|
714
|
+
for name, d in compiled.items():
|
|
715
|
+
if name not in used:
|
|
716
|
+
out.append(make(d["file"], d["line"], "go", "go", d["pattern"], "", "MustCompile", compiled="once", source="constant", name=name))
|
|
717
|
+
return out
|
|
718
|
+
|
|
719
|
+
|
|
720
|
+
# --- Java ------------------------------------------------------------------------------------------------------------------
|
|
721
|
+
|
|
722
|
+
JAVA_FLAGS = {"CASE_INSENSITIVE": "i", "MULTILINE": "m", "DOTALL": "s", "COMMENTS": "x", "UNICODE_CHARACTER_CLASS": "u"}
|
|
723
|
+
SPLIT_FAST = ".$|()[{^?*+\\"
|
|
724
|
+
|
|
725
|
+
|
|
726
|
+
def _java_str(n, consts: dict) -> str | None:
|
|
727
|
+
if n is None:
|
|
728
|
+
return None
|
|
729
|
+
if n.type == "string_literal":
|
|
730
|
+
t = _t(n)
|
|
731
|
+
if t.startswith('"""'):
|
|
732
|
+
return None
|
|
733
|
+
try:
|
|
734
|
+
return json.loads(t)
|
|
735
|
+
except ValueError:
|
|
736
|
+
return None
|
|
737
|
+
if n.type == "identifier":
|
|
738
|
+
return consts.get(_t(n))
|
|
739
|
+
if n.type == "field_access":
|
|
740
|
+
return consts.get(_t(n.child_by_field_name("field")))
|
|
741
|
+
if n.type == "binary_expression" and _t(n.child_by_field_name("operator")) == "+":
|
|
742
|
+
a, b = _java_str(n.child_by_field_name("left"), consts), _java_str(n.child_by_field_name("right"), consts)
|
|
743
|
+
return a + b if a is not None and b is not None else None
|
|
744
|
+
if n.type == "parenthesized_expression" and n.named_children:
|
|
745
|
+
return _java_str(n.named_children[0], consts)
|
|
746
|
+
return None
|
|
747
|
+
|
|
748
|
+
|
|
749
|
+
def _java_fn(n):
|
|
750
|
+
cls, meth = "", None
|
|
751
|
+
for a in _ancestors(n):
|
|
752
|
+
if a.type in ("method_declaration", "constructor_declaration", "lambda_expression") and meth is None:
|
|
753
|
+
meth = a
|
|
754
|
+
if a.type in ("class_declaration", "enum_declaration", "record_declaration", "interface_declaration") and not cls:
|
|
755
|
+
cls = _t(a.child_by_field_name("name"))
|
|
756
|
+
name = _t(meth.child_by_field_name("name")) if meth is not None and meth.type != "lambda_expression" else ""
|
|
757
|
+
return meth, (f"{cls}.{name}" if cls and name else cls or name)
|
|
758
|
+
|
|
759
|
+
|
|
760
|
+
def _java_loop(n, fn) -> bool:
|
|
761
|
+
for a in _ancestors(n):
|
|
762
|
+
if a == fn:
|
|
763
|
+
return False
|
|
764
|
+
if a.type in ("for_statement", "enhanced_for_statement", "while_statement", "do_statement"):
|
|
765
|
+
return True
|
|
766
|
+
return False
|
|
767
|
+
|
|
768
|
+
|
|
769
|
+
def java_sites(root: Path, files: list[str]) -> list[dict]:
|
|
770
|
+
parsed, consts, fields = [], {}, {}
|
|
771
|
+
for rel in files:
|
|
772
|
+
src = read_text(root / rel)
|
|
773
|
+
if not src or not any(k in src for k in ("Pattern", ".matches(", ".replaceAll(", ".split(", ".replaceFirst(")):
|
|
774
|
+
continue
|
|
775
|
+
tree = parser("java").parse(src.encode())
|
|
776
|
+
parsed.append((rel, tree))
|
|
777
|
+
for n in _walk(tree.root_node):
|
|
778
|
+
if n.type == "field_declaration":
|
|
779
|
+
for d in n.children_by_field_name("declarator"):
|
|
780
|
+
v = d.child_by_field_name("value")
|
|
781
|
+
s = _java_str(v, consts)
|
|
782
|
+
if s is not None:
|
|
783
|
+
consts[_t(d.child_by_field_name("name"))] = s
|
|
784
|
+
out = []
|
|
785
|
+
used = set()
|
|
786
|
+
for rel, tree in parsed:
|
|
787
|
+
for n in _walk(tree.root_node):
|
|
788
|
+
if n.type != "method_invocation":
|
|
789
|
+
continue
|
|
790
|
+
name = _t(n.child_by_field_name("name"))
|
|
791
|
+
obj = n.child_by_field_name("object")
|
|
792
|
+
args = n.child_by_field_name("arguments")
|
|
793
|
+
a = args.named_children if args is not None else []
|
|
794
|
+
meth, sym = _java_fn(n)
|
|
795
|
+
loop = _java_loop(n, meth)
|
|
796
|
+
if name == "compile" and obj is not None and _t(obj).endswith("Pattern") and a:
|
|
797
|
+
pat = _java_str(a[0], consts)
|
|
798
|
+
fl = "".join(sorted({JAVA_FLAGS[k] for k in JAVA_FLAGS if len(a) > 1 and k in _t(a[1])}))
|
|
799
|
+
field = None
|
|
800
|
+
for an in _ancestors(n):
|
|
801
|
+
if an.type == "field_declaration":
|
|
802
|
+
field = an
|
|
803
|
+
break
|
|
804
|
+
if an.type in ("method_declaration", "constructor_declaration", "block"):
|
|
805
|
+
break
|
|
806
|
+
if field is not None:
|
|
807
|
+
static = "static" in _t(field).split("=")[0]
|
|
808
|
+
for d in field.children_by_field_name("declarator"):
|
|
809
|
+
fields[_t(d.child_by_field_name("name"))] = {"pattern": pat, "flags": fl, "line": _line(n), "file": rel,
|
|
810
|
+
"how": "once" if static else "instance"}
|
|
811
|
+
continue
|
|
812
|
+
out.append(make(rel, _line(n), "java", "java", pat, fl, "compile", symbol=sym, compiled="loop" if loop else "function",
|
|
813
|
+
in_loop=loop, source="literal" if a[0].type == "string_literal" else "constant", use=_t(n)))
|
|
814
|
+
continue
|
|
815
|
+
if name in ("matches", "replaceAll", "replaceFirst", "split") and obj is not None and a:
|
|
816
|
+
if _t(obj) == "Pattern" and name == "matches":
|
|
817
|
+
pat = _java_str(a[0], consts)
|
|
818
|
+
out.append(make(rel, _line(n), "java", "java", pat, "", "matches", symbol=sym, compiled="loop" if loop else "function",
|
|
819
|
+
in_loop=loop, arg=_t(a[1]) if len(a) > 1 else "", use=_t(n)))
|
|
820
|
+
continue
|
|
821
|
+
pat = _java_str(a[0], consts)
|
|
822
|
+
if pat is None and a[0].type != "string_literal" and _t(a[0]) not in consts:
|
|
823
|
+
continue # not a String method on a regex we can read (Matcher.replaceAll(String), list.split(...))
|
|
824
|
+
if name == "split" and pat is not None and (len(pat) == 1 and pat not in SPLIT_FAST
|
|
825
|
+
or len(pat) == 2 and pat[0] == "\\" and not pat[1].isalnum()):
|
|
826
|
+
continue # String.split's fast path: no regex is compiled
|
|
827
|
+
out.append(make(rel, _line(n), "java", "java", pat, "", name, symbol=sym, compiled="loop" if loop else "function",
|
|
828
|
+
in_loop=loop, arg=_t(obj), use=_t(n)))
|
|
829
|
+
continue
|
|
830
|
+
if name == "matcher" and obj is not None and _t(obj).split(".")[-1] in fields:
|
|
831
|
+
fname = _t(obj).split(".")[-1]
|
|
832
|
+
d = fields[fname]
|
|
833
|
+
used.add(fname)
|
|
834
|
+
api = "find"
|
|
835
|
+
par = n.parent
|
|
836
|
+
if par is not None and par.type == "method_invocation":
|
|
837
|
+
api = _t(par.child_by_field_name("name"))
|
|
838
|
+
out.append(make(rel, _line(n), "java", "java", d["pattern"], d["flags"], api if api in JAVA_MODES else "find", symbol=sym,
|
|
839
|
+
compiled=d["how"], in_loop=loop, source="constant", def_line=d["line"], def_file=d["file"],
|
|
840
|
+
arg=_t(a[0]) if a else "", name=fname, use=_t(par if par is not None and par.type == "method_invocation" else n)))
|
|
841
|
+
for fname, d in fields.items():
|
|
842
|
+
if fname not in used:
|
|
843
|
+
out.append(make(d["file"], d["line"], "java", "java", d["pattern"], d["flags"], "compile", compiled=d["how"], source="constant",
|
|
844
|
+
name=fname))
|
|
845
|
+
return out
|
|
846
|
+
|
|
847
|
+
|
|
848
|
+
# --- TypeScript / JavaScript ------------------------------------------------------------------------------------------------
|
|
849
|
+
|
|
850
|
+
BROWSER_DIRS = {"frontend", "client", "web", "webapp", "ui", "components", "pages", "public", "static", "browser", "extension",
|
|
851
|
+
"app-ui", "views", "hooks", "widgets", "renderer", "src-ui", "dashboard", "console", "site", "www", "assets", "js"}
|
|
852
|
+
SERVER_DIRS = {"server", "api", "backend", "worker", "workers", "lambda", "functions", "routes", "services", "service", "cmd", "jobs",
|
|
853
|
+
"handlers", "middleware", "cron", "gateway", "edge", "node", "plugins-server", "trpc", "router", "routers"}
|
|
854
|
+
|
|
855
|
+
|
|
856
|
+
VENDORED_NAME = re.compile(r"(^|/)(vendor|vendors|third[_-]?party|bower_components)/|[.-](bundle|min|umd|esm|prod|production)\.[cm]?js$|"
|
|
857
|
+
r"[-.]v?\d+\.\d+\.\d+[^/]*\.[cm]?js$|(^|/)(chunks?|dist|build|_next|static/js)/", re.I)
|
|
858
|
+
|
|
859
|
+
|
|
860
|
+
def vendored(rel: str, src: str) -> bool:
|
|
861
|
+
"""A third-party or built bundle checked into the repository (swagger-ui-bundle.js, scalar-1.81.0.js, a minified
|
|
862
|
+
file): its patterns are not the project's code."""
|
|
863
|
+
if VENDORED_NAME.search(rel):
|
|
864
|
+
return True
|
|
865
|
+
lines = src.count("\n") + 1
|
|
866
|
+
return len(src) > 20_000 and len(src) / lines > 400
|
|
867
|
+
|
|
868
|
+
|
|
869
|
+
def browser_path(rel: str) -> bool:
|
|
870
|
+
parts = [p.lower() for p in rel.split("/")]
|
|
871
|
+
if any(p in SERVER_DIRS for p in parts[:-1]) or re.search(r"\.(server|api)\.[tj]sx?$", rel):
|
|
872
|
+
return False
|
|
873
|
+
if rel.endswith((".tsx", ".jsx", ".vue", ".svelte")):
|
|
874
|
+
return True
|
|
875
|
+
return any(p in BROWSER_DIRS for p in parts[:-1])
|
|
876
|
+
|
|
877
|
+
|
|
878
|
+
def _js_str(n, consts: dict) -> str | None:
|
|
879
|
+
if n is None:
|
|
880
|
+
return None
|
|
881
|
+
if n.type == "string":
|
|
882
|
+
t = _t(n)
|
|
883
|
+
q = t[0]
|
|
884
|
+
body = t[1:-1]
|
|
885
|
+
try:
|
|
886
|
+
return ast.literal_eval(t) if q in "'\"" else None
|
|
887
|
+
except (ValueError, SyntaxError):
|
|
888
|
+
return body
|
|
889
|
+
if n.type == "template_string":
|
|
890
|
+
if any(c.type == "template_substitution" for c in n.children):
|
|
891
|
+
return None
|
|
892
|
+
return _t(n)[1:-1]
|
|
893
|
+
if n.type == "identifier":
|
|
894
|
+
return consts.get(_t(n))
|
|
895
|
+
if n.type == "binary_expression" and _t(n.child_by_field_name("operator")) == "+":
|
|
896
|
+
a, b = _js_str(n.child_by_field_name("left"), consts), _js_str(n.child_by_field_name("right"), consts)
|
|
897
|
+
return a + b if a is not None and b is not None else None
|
|
898
|
+
return None
|
|
899
|
+
|
|
900
|
+
|
|
901
|
+
def _js_fn(n):
|
|
902
|
+
names = []
|
|
903
|
+
fn = None
|
|
904
|
+
for a in _ancestors(n):
|
|
905
|
+
if a.type in ("function_declaration", "method_definition", "function_expression", "arrow_function", "function",
|
|
906
|
+
"generator_function_declaration"):
|
|
907
|
+
if fn is None:
|
|
908
|
+
fn = a
|
|
909
|
+
nm = a.child_by_field_name("name")
|
|
910
|
+
if nm is not None:
|
|
911
|
+
names.append(_t(nm))
|
|
912
|
+
elif a.parent is not None and a.parent.type == "variable_declarator":
|
|
913
|
+
names.append(_t(a.parent.child_by_field_name("name")))
|
|
914
|
+
if a.type in ("class_declaration", "class"):
|
|
915
|
+
nm = a.child_by_field_name("name")
|
|
916
|
+
if nm is not None:
|
|
917
|
+
names.append(_t(nm))
|
|
918
|
+
return fn, ".".join(reversed(names[:2]))
|
|
919
|
+
|
|
920
|
+
|
|
921
|
+
def _js_loop(n, fn) -> bool:
|
|
922
|
+
for a in _ancestors(n):
|
|
923
|
+
if a == fn:
|
|
924
|
+
return False
|
|
925
|
+
if a.type in ("for_statement", "for_in_statement", "while_statement", "do_statement"):
|
|
926
|
+
return True
|
|
927
|
+
if a.type == "call_expression":
|
|
928
|
+
callee = a.child_by_field_name("function")
|
|
929
|
+
if callee is not None and callee.type == "member_expression" and _t(callee.child_by_field_name("property")) in (
|
|
930
|
+
"map", "forEach", "filter", "reduce", "some", "every", "flatMap", "find"):
|
|
931
|
+
if any(x == a for x in _ancestors(n)) and fn is not None and any(x == fn for x in _ancestors(n)) and \
|
|
932
|
+
any(x == a for x in _ancestors(fn)):
|
|
933
|
+
return True
|
|
934
|
+
return False
|
|
935
|
+
|
|
936
|
+
|
|
937
|
+
def _js_use(node):
|
|
938
|
+
"""The call a regex (literal or identifier) takes part in: (api, the call node, the input expression)."""
|
|
939
|
+
p = node.parent
|
|
940
|
+
if p is None:
|
|
941
|
+
return "literal", node, None
|
|
942
|
+
if p.type == "member_expression" and p.child_by_field_name("object") == node:
|
|
943
|
+
prop = _t(p.child_by_field_name("property"))
|
|
944
|
+
call = p.parent
|
|
945
|
+
if call is not None and call.type == "call_expression" and prop in ("test", "exec"):
|
|
946
|
+
args = call.child_by_field_name("arguments")
|
|
947
|
+
return prop, call, (args.named_children[0] if args is not None and args.named_children else None)
|
|
948
|
+
if p.type == "arguments" and p.parent is not None and p.parent.type == "call_expression":
|
|
949
|
+
callee = p.parent.child_by_field_name("function")
|
|
950
|
+
if callee is not None and callee.type == "member_expression":
|
|
951
|
+
prop = _t(callee.child_by_field_name("property"))
|
|
952
|
+
if prop in ("match", "matchAll", "replace", "replaceAll", "split", "search"):
|
|
953
|
+
return prop, p.parent, callee.child_by_field_name("object")
|
|
954
|
+
return "literal", node, None
|
|
955
|
+
|
|
956
|
+
|
|
957
|
+
_JS_NEED = {">": 1, ">=": 0, "===": 1, "==": 1, "!==": 1, "!=": 1, "<": 0, "<=": 1}
|
|
958
|
+
|
|
959
|
+
|
|
960
|
+
def _js_count_use(call) -> tuple:
|
|
961
|
+
"""(N, the expression) when `s.match(/x/g)` is only counted against a number: `(s.match(/x/g) || []).length > 3`,
|
|
962
|
+
`s.match(/x/g)?.length >= 2`. The first N matches decide."""
|
|
963
|
+
n = call.parent
|
|
964
|
+
for _ in range(4):
|
|
965
|
+
if n is None:
|
|
966
|
+
return None, None
|
|
967
|
+
if n.type == "member_expression" and _t(n.child_by_field_name("property")) == "length":
|
|
968
|
+
break
|
|
969
|
+
if n.type not in ("parenthesized_expression", "binary_expression") or n.type == "binary_expression" and "||" not in _t(n) and "??" not in _t(n):
|
|
970
|
+
return None, None
|
|
971
|
+
n = n.parent
|
|
972
|
+
else:
|
|
973
|
+
return None, None
|
|
974
|
+
cmp_ = n.parent
|
|
975
|
+
if cmp_ is None or cmp_.type != "binary_expression":
|
|
976
|
+
return None, None
|
|
977
|
+
op = _t(cmp_.child_by_field_name("operator"))
|
|
978
|
+
left, right = cmp_.child_by_field_name("left"), cmp_.child_by_field_name("right")
|
|
979
|
+
num = right if left == n else left
|
|
980
|
+
if op not in _JS_NEED or num is None or num.type != "number" or not _INT.match(_t(num)):
|
|
981
|
+
return None, None
|
|
982
|
+
if left != n:
|
|
983
|
+
op = {">": "<", ">=": "<=", "<": ">", "<=": ">="}.get(op, op)
|
|
984
|
+
k = int(_t(num)) + _JS_NEED[op]
|
|
985
|
+
return (k, _t(cmp_)) if k >= 1 else (None, None)
|
|
986
|
+
|
|
987
|
+
|
|
988
|
+
def ts_sites(root: Path, files: list[str]) -> list[dict]:
|
|
989
|
+
out = []
|
|
990
|
+
for rel in files:
|
|
991
|
+
if rel.endswith(".d.ts") or ".min." in rel:
|
|
992
|
+
continue
|
|
993
|
+
src = read_text(root / rel)
|
|
994
|
+
if not src or ("/" not in src):
|
|
995
|
+
continue
|
|
996
|
+
tree = parser("tsx" if rel.endswith((".tsx", ".jsx", ".js", ".mjs", ".cjs")) else "ts").parse(src.encode())
|
|
997
|
+
consts, defs = {}, {}
|
|
998
|
+
for n in _walk(tree.root_node):
|
|
999
|
+
if n.type == "variable_declarator" and n.parent is not None and n.parent.parent is not None \
|
|
1000
|
+
and n.parent.parent.type in ("program", "export_statement"):
|
|
1001
|
+
v = n.child_by_field_name("value")
|
|
1002
|
+
s = _js_str(v, consts)
|
|
1003
|
+
if s is not None:
|
|
1004
|
+
consts[_t(n.child_by_field_name("name"))] = s
|
|
1005
|
+
elif v is not None and v.type == "regex":
|
|
1006
|
+
defs[_t(n.child_by_field_name("name"))] = v
|
|
1007
|
+
browser = browser_path(rel)
|
|
1008
|
+
flows = "vendored" if vendored(rel, src) else "browser" if browser else ""
|
|
1009
|
+
used = set()
|
|
1010
|
+
for n in _walk(tree.root_node):
|
|
1011
|
+
if n.type == "regex":
|
|
1012
|
+
pat = _t(n.child_by_field_name("pattern"))
|
|
1013
|
+
fl = _t(n.child_by_field_name("flags"))
|
|
1014
|
+
fn, sym = _js_fn(n)
|
|
1015
|
+
decl = n.parent if n.parent is not None and n.parent.type == "variable_declarator" else None
|
|
1016
|
+
if decl is not None and _t(decl.child_by_field_name("name")) in defs and fn is None:
|
|
1017
|
+
continue # a module-level constant: its uses are the sites
|
|
1018
|
+
api, call, arg = _js_use(n)
|
|
1019
|
+
loop = _js_loop(n, fn)
|
|
1020
|
+
take, cuse = _js_count_use(call) if api == "match" and "g" in fl else (None, None)
|
|
1021
|
+
out.append(make(rel, _line(call), "typescript", "node", pat, fl, api, symbol=sym, compiled="once", in_loop=loop,
|
|
1022
|
+
arg=_t(arg), flows=flows, use=(cuse or _t(call))[:200], def_line=_line(n), take=take))
|
|
1023
|
+
elif n.type == "identifier" and _t(n) in defs and n.parent is not None and n.parent.type != "variable_declarator":
|
|
1024
|
+
api, call, arg = _js_use(n)
|
|
1025
|
+
if call == n:
|
|
1026
|
+
continue
|
|
1027
|
+
name = _t(n)
|
|
1028
|
+
used.add(name)
|
|
1029
|
+
d = defs[name]
|
|
1030
|
+
fn, sym = _js_fn(n)
|
|
1031
|
+
dfl = _t(d.child_by_field_name("flags"))
|
|
1032
|
+
take, cuse = _js_count_use(call) if api == "match" and "g" in dfl else (None, None)
|
|
1033
|
+
out.append(make(rel, _line(call), "typescript", "node", _t(d.child_by_field_name("pattern")), dfl,
|
|
1034
|
+
api, symbol=sym, compiled="once", in_loop=_js_loop(n, fn), source="constant", def_line=_line(d), arg=_t(arg),
|
|
1035
|
+
flows=flows, name=name, use=(cuse or _t(call))[:200], take=take))
|
|
1036
|
+
elif n.type in ("new_expression", "call_expression"):
|
|
1037
|
+
ctor = n.child_by_field_name("constructor") or n.child_by_field_name("function")
|
|
1038
|
+
if _t(ctor) != "RegExp":
|
|
1039
|
+
continue
|
|
1040
|
+
args = n.child_by_field_name("arguments")
|
|
1041
|
+
a = args.named_children if args is not None else []
|
|
1042
|
+
if not a:
|
|
1043
|
+
continue
|
|
1044
|
+
pat = _js_str(a[0], consts)
|
|
1045
|
+
fl = _js_str(a[1], consts) if len(a) > 1 else ""
|
|
1046
|
+
fn, sym = _js_fn(n)
|
|
1047
|
+
loop = _js_loop(n, fn)
|
|
1048
|
+
api, call, arg = _js_use(n) if n.parent is not None and n.parent.type != "variable_declarator" else ("new", n, None)
|
|
1049
|
+
api = "new" if api == "literal" else api
|
|
1050
|
+
out.append(make(rel, _line(n), "typescript", "node", pat, fl or "", api, symbol=sym,
|
|
1051
|
+
compiled="once" if fn is None else ("loop" if loop else "function"), in_loop=loop,
|
|
1052
|
+
source="literal" if a[0].type in ("string", "template_string") else "constant", arg=_t(arg), flows=flows,
|
|
1053
|
+
use=_t(call)[:200]))
|
|
1054
|
+
for name, d in defs.items():
|
|
1055
|
+
if name not in used:
|
|
1056
|
+
out.append(make(rel, _line(d), "typescript", "node", _t(d.child_by_field_name("pattern")), _t(d.child_by_field_name("flags")),
|
|
1057
|
+
"literal", compiled="once", source="constant", name=name, flows=flows))
|
|
1058
|
+
return out
|
|
1059
|
+
|
|
1060
|
+
|
|
1061
|
+
# --- Rust ------------------------------------------------------------------------------------------------------------------
|
|
1062
|
+
|
|
1063
|
+
RUST_NEW = re.compile(r"(?:^|::)(Regex|RegexBuilder|RegexSet|RegexSetBuilder)::new$")
|
|
1064
|
+
LAZY_STATIC = re.compile(r"static\s+ref\s+([A-Z_][A-Z0-9_]*)\s*:\s*[^=]*=\s*(?:[\w:]*Regex(?:Set)?::new|[\w:]*RegexBuilder::new)\s*\(\s*"
|
|
1065
|
+
r"(r(#*)\"(.*?)\"\3|\"((?:[^\"\\]|\\.)*)\")", re.S)
|
|
1066
|
+
|
|
1067
|
+
|
|
1068
|
+
def _rust_str(n, consts: dict) -> str | None:
|
|
1069
|
+
if n is None:
|
|
1070
|
+
return None
|
|
1071
|
+
if n.type == "raw_string_literal":
|
|
1072
|
+
t = _t(n)
|
|
1073
|
+
m = re.match(r'^(?:b?r)(#*)"(.*)"\1$', t, re.S)
|
|
1074
|
+
return m.group(2) if m else None
|
|
1075
|
+
if n.type == "string_literal":
|
|
1076
|
+
t = _t(n)
|
|
1077
|
+
if t.startswith("b"):
|
|
1078
|
+
t = t[1:]
|
|
1079
|
+
body = t[1:-1]
|
|
1080
|
+
return _rust_unescape(body)
|
|
1081
|
+
if n.type == "identifier":
|
|
1082
|
+
return consts.get(_t(n))
|
|
1083
|
+
if n.type == "reference_expression" and n.named_children:
|
|
1084
|
+
return _rust_str(n.named_children[-1], consts)
|
|
1085
|
+
if n.type == "macro_invocation" and _t(n.child_by_field_name("macro")) == "concat":
|
|
1086
|
+
tt = n.named_children[-1] if n.named_children else None
|
|
1087
|
+
parts = [c for c in (tt.named_children if tt is not None else [])]
|
|
1088
|
+
vals = [_rust_str(c, consts) for c in parts if c.type in ("string_literal", "raw_string_literal")]
|
|
1089
|
+
return "".join(v for v in vals if v is not None) if vals and all(v is not None for v in vals) else None
|
|
1090
|
+
if n.type == "call_expression":
|
|
1091
|
+
f = _t(n.child_by_field_name("function"))
|
|
1092
|
+
if f.endswith("format") or f.endswith("format!"):
|
|
1093
|
+
return None
|
|
1094
|
+
return None
|
|
1095
|
+
|
|
1096
|
+
|
|
1097
|
+
def _rust_unescape(body: str) -> str | None:
|
|
1098
|
+
out, i = [], 0
|
|
1099
|
+
while i < len(body):
|
|
1100
|
+
c = body[i]
|
|
1101
|
+
if c != "\\":
|
|
1102
|
+
out.append(c)
|
|
1103
|
+
i += 1
|
|
1104
|
+
continue
|
|
1105
|
+
nxt = body[i + 1:i + 2]
|
|
1106
|
+
simple = {"n": "\n", "t": "\t", "r": "\r", "0": "\0", "\\": "\\", '"': '"', "'": "'"}
|
|
1107
|
+
if nxt in simple:
|
|
1108
|
+
out.append(simple[nxt])
|
|
1109
|
+
i += 2
|
|
1110
|
+
elif nxt == "x":
|
|
1111
|
+
out.append(chr(int(body[i + 2:i + 4], 16)))
|
|
1112
|
+
i += 4
|
|
1113
|
+
elif nxt == "u":
|
|
1114
|
+
j = body.find("}", i)
|
|
1115
|
+
out.append(chr(int(body[i + 3:j], 16)))
|
|
1116
|
+
i = j + 1
|
|
1117
|
+
elif nxt == "\n":
|
|
1118
|
+
i += 2
|
|
1119
|
+
while i < len(body) and body[i] in " \t\n":
|
|
1120
|
+
i += 1
|
|
1121
|
+
else:
|
|
1122
|
+
return None
|
|
1123
|
+
return "".join(out)
|
|
1124
|
+
|
|
1125
|
+
|
|
1126
|
+
def _rust_fn(n):
|
|
1127
|
+
names, fn = [], None
|
|
1128
|
+
for a in _ancestors(n):
|
|
1129
|
+
if a.type == "function_item":
|
|
1130
|
+
if fn is None:
|
|
1131
|
+
fn = a
|
|
1132
|
+
names.append(_t(a.child_by_field_name("name")))
|
|
1133
|
+
if a.type == "impl_item":
|
|
1134
|
+
ty = a.child_by_field_name("type")
|
|
1135
|
+
names.append(re.sub(r"<.*", "", _t(ty)))
|
|
1136
|
+
return fn, ".".join(reversed(names[:2]))
|
|
1137
|
+
|
|
1138
|
+
|
|
1139
|
+
RUST_ONCE_CALL = re.compile(r"(?:^|::|\.)(get_or_init|get_or_try_init|call_once|call_once_force|get_or_insert_with)$|"
|
|
1140
|
+
r"(?:^|::)(?:Lazy|LazyLock|LazyCell|OnceCell|OnceLock|SyncLazy)(?:::<[^>]*>)?::new$")
|
|
1141
|
+
|
|
1142
|
+
|
|
1143
|
+
def _rust_static(n):
|
|
1144
|
+
"""The static (LazyLock, Lazy, OnceLock, once_cell) a Regex::new sits in, or None."""
|
|
1145
|
+
for a in _ancestors(n):
|
|
1146
|
+
if a.type in ("static_item", "const_item"):
|
|
1147
|
+
return _t(a.child_by_field_name("name"))
|
|
1148
|
+
if a.type == "function_item":
|
|
1149
|
+
return None
|
|
1150
|
+
return None
|
|
1151
|
+
|
|
1152
|
+
|
|
1153
|
+
def _rust_lazy(n) -> bool:
|
|
1154
|
+
"""Whether a Regex::new runs inside a lazy initialiser's closure (`RE.get_or_init(|| Regex::new(..))`,
|
|
1155
|
+
`Lazy::new(|| ..)`, `thread_local!`): compiled once, not on every call."""
|
|
1156
|
+
for a in _ancestors(n):
|
|
1157
|
+
if a.type == "function_item":
|
|
1158
|
+
return False
|
|
1159
|
+
if a.type == "macro_invocation" and _t(a.child_by_field_name("macro")) in ("thread_local", "lazy_static", "once_cell"):
|
|
1160
|
+
return True
|
|
1161
|
+
if a.type == "call_expression":
|
|
1162
|
+
f = a.child_by_field_name("function")
|
|
1163
|
+
if f is not None and RUST_ONCE_CALL.search(_t(f).replace(" ", "")):
|
|
1164
|
+
return True
|
|
1165
|
+
return False
|
|
1166
|
+
|
|
1167
|
+
|
|
1168
|
+
def _rust_loop(n, fn) -> bool:
|
|
1169
|
+
for a in _ancestors(n):
|
|
1170
|
+
if a == fn:
|
|
1171
|
+
return False
|
|
1172
|
+
if a.type in ("for_expression", "while_expression", "loop_expression"):
|
|
1173
|
+
return True
|
|
1174
|
+
return False
|
|
1175
|
+
|
|
1176
|
+
|
|
1177
|
+
_INT = re.compile(r"^\d+$")
|
|
1178
|
+
|
|
1179
|
+
|
|
1180
|
+
def _take_bound(count_call, fn) -> int | None:
|
|
1181
|
+
"""`X.find_iter(s).count()` used only to compare with a constant, or capped with min(N, ...): the matches it needs."""
|
|
1182
|
+
p = count_call.parent
|
|
1183
|
+
while p is not None and p.type == "parenthesized_expression":
|
|
1184
|
+
p = p.parent
|
|
1185
|
+
|
|
1186
|
+
def need(op: str, k: int, count_left: bool) -> int | None:
|
|
1187
|
+
if not count_left:
|
|
1188
|
+
op = {">": "<", "<": ">", ">=": "<=", "<=": ">="}.get(op, op)
|
|
1189
|
+
if op in (">=", "<"):
|
|
1190
|
+
return k
|
|
1191
|
+
if op in (">", "<="):
|
|
1192
|
+
return k + 1
|
|
1193
|
+
if op in ("==", "!=") and k == 0:
|
|
1194
|
+
return 1
|
|
1195
|
+
return None
|
|
1196
|
+
if p is not None and p.type == "binary_expression":
|
|
1197
|
+
op = _t(p.child_by_field_name("operator"))
|
|
1198
|
+
left, right = p.child_by_field_name("left"), p.child_by_field_name("right")
|
|
1199
|
+
other = right if left == count_call or (left is not None and left.start_byte == count_call.start_byte) else left
|
|
1200
|
+
if other is not None and _INT.match(_t(other)):
|
|
1201
|
+
return need(op, int(_t(other)), other == right)
|
|
1202
|
+
return None
|
|
1203
|
+
if p is not None and p.type == "arguments" and p.parent is not None and p.parent.type == "call_expression":
|
|
1204
|
+
callee = _t(p.parent.child_by_field_name("function"))
|
|
1205
|
+
if callee.endswith("min"):
|
|
1206
|
+
others = [c for c in p.named_children if c.start_byte != count_call.start_byte]
|
|
1207
|
+
if len(others) == 1 and _INT.match(_t(others[0])):
|
|
1208
|
+
return int(_t(others[0]))
|
|
1209
|
+
return None
|
|
1210
|
+
if p is not None and p.type == "let_declaration" and fn is not None:
|
|
1211
|
+
var = _t(p.child_by_field_name("pattern"))
|
|
1212
|
+
if not re.fullmatch(r"[a-z_][a-z0-9_]*", var):
|
|
1213
|
+
return None
|
|
1214
|
+
body = fn.child_by_field_name("body")
|
|
1215
|
+
needs = []
|
|
1216
|
+
for u in _walk(body):
|
|
1217
|
+
if u.type == "identifier" and _t(u) == var and u.start_byte > p.end_byte:
|
|
1218
|
+
q = u.parent
|
|
1219
|
+
if q is None or q.type != "binary_expression":
|
|
1220
|
+
return None
|
|
1221
|
+
op = _t(q.child_by_field_name("operator"))
|
|
1222
|
+
left, right = q.child_by_field_name("left"), q.child_by_field_name("right")
|
|
1223
|
+
other = right if left == u else left
|
|
1224
|
+
if other is None or not _INT.match(_t(other)):
|
|
1225
|
+
return None
|
|
1226
|
+
k = need(op, int(_t(other)), other == right)
|
|
1227
|
+
if k is None:
|
|
1228
|
+
return None
|
|
1229
|
+
needs.append(k)
|
|
1230
|
+
return max(needs) if needs else None
|
|
1231
|
+
return None
|
|
1232
|
+
|
|
1233
|
+
|
|
1234
|
+
_CRATES: dict = {}
|
|
1235
|
+
|
|
1236
|
+
|
|
1237
|
+
def _crate_of(root: Path, rel: str) -> str:
|
|
1238
|
+
"""The directory of the nearest Cargo.toml above a file (its crate), '' when there is none."""
|
|
1239
|
+
d = os.path.dirname(rel)
|
|
1240
|
+
key = (str(root), d)
|
|
1241
|
+
if key not in _CRATES:
|
|
1242
|
+
p = d
|
|
1243
|
+
while True:
|
|
1244
|
+
if (Path(root) / p / "Cargo.toml").exists():
|
|
1245
|
+
_CRATES[key] = p
|
|
1246
|
+
break
|
|
1247
|
+
if not p:
|
|
1248
|
+
_CRATES[key] = ""
|
|
1249
|
+
break
|
|
1250
|
+
p = os.path.dirname(p)
|
|
1251
|
+
return _CRATES[key]
|
|
1252
|
+
|
|
1253
|
+
|
|
1254
|
+
def rust_sites(root: Path, files: list[str]) -> list[dict]:
|
|
1255
|
+
parsed, consts, statics = [], {}, {}
|
|
1256
|
+
for rel in files:
|
|
1257
|
+
src = read_text(root / rel)
|
|
1258
|
+
if not src or "Regex" not in src and "regex!" not in src:
|
|
1259
|
+
continue
|
|
1260
|
+
tree = parser("rust").parse(src.encode())
|
|
1261
|
+
fancy = "fancy_regex" in src
|
|
1262
|
+
parsed.append((rel, tree, src, fancy))
|
|
1263
|
+
for n in _walk(tree.root_node):
|
|
1264
|
+
if n.type == "const_item" or n.type == "static_item":
|
|
1265
|
+
v = n.child_by_field_name("value")
|
|
1266
|
+
s = _rust_str(v, consts)
|
|
1267
|
+
if s is not None:
|
|
1268
|
+
consts[_t(n.child_by_field_name("name"))] = s
|
|
1269
|
+
out = []
|
|
1270
|
+
used = set()
|
|
1271
|
+
for rel, tree, src, fancy in parsed:
|
|
1272
|
+
for n in _walk(tree.root_node):
|
|
1273
|
+
if n.type == "call_expression":
|
|
1274
|
+
f = n.child_by_field_name("function")
|
|
1275
|
+
ft = _t(f)
|
|
1276
|
+
m = RUST_NEW.search(ft)
|
|
1277
|
+
if not m:
|
|
1278
|
+
continue
|
|
1279
|
+
engine = "rust-fancy" if (fancy and "regex::" not in ft) or "fancy_regex" in ft else "rust"
|
|
1280
|
+
args = n.child_by_field_name("arguments")
|
|
1281
|
+
a = args.named_children[0] if args is not None and args.named_children else None
|
|
1282
|
+
fn, sym = _rust_fn(n)
|
|
1283
|
+
static = _rust_static(n)
|
|
1284
|
+
loop = _rust_loop(n, fn)
|
|
1285
|
+
flags = ""
|
|
1286
|
+
chain = n.parent
|
|
1287
|
+
while chain is not None and chain.type in ("field_expression", "call_expression", "arguments"):
|
|
1288
|
+
t = _t(chain)
|
|
1289
|
+
if ".case_insensitive(true)" in t:
|
|
1290
|
+
flags += "i"
|
|
1291
|
+
if ".multi_line(true)" in t:
|
|
1292
|
+
flags += "m"
|
|
1293
|
+
if ".dot_matches_new_line(true)" in t:
|
|
1294
|
+
flags += "s"
|
|
1295
|
+
if ".unicode(false)" in t:
|
|
1296
|
+
flags += "a"
|
|
1297
|
+
chain = chain.parent
|
|
1298
|
+
flags = "".join(sorted(set(flags))) # each enclosing call repeats the builder chain's text
|
|
1299
|
+
if m.group(1).startswith("RegexSet") and a is not None and a.type in ("array_expression", "reference_expression"):
|
|
1300
|
+
arr = a if a.type == "array_expression" else (a.named_children[-1] if a.named_children else None)
|
|
1301
|
+
for el in (arr.named_children if arr is not None else []):
|
|
1302
|
+
pat = _rust_str(el, consts)
|
|
1303
|
+
out.append(make(rel, _line(el), "rust", engine, pat, flags, "is_match", symbol=sym,
|
|
1304
|
+
compiled="once" if static else ("loop" if loop else "function"), source="table",
|
|
1305
|
+
table=f"{rel}:{static or sym}", name=static or ""))
|
|
1306
|
+
continue
|
|
1307
|
+
pat = _rust_str(a, consts)
|
|
1308
|
+
if static:
|
|
1309
|
+
statics.setdefault(static, []).append({"pattern": pat, "flags": flags, "file": rel, "line": _line(n), "engine": engine})
|
|
1310
|
+
continue
|
|
1311
|
+
out.append(make(rel, _line(n), "rust", engine, pat, flags, "new", symbol=sym,
|
|
1312
|
+
compiled="once" if _rust_lazy(n) else ("loop" if loop else "function"),
|
|
1313
|
+
in_loop=loop, source="literal" if a is not None and "string" in a.type else "constant", use=_t(n)))
|
|
1314
|
+
elif n.type == "macro_invocation" and _t(n.child_by_field_name("macro")) == "lazy_static":
|
|
1315
|
+
for mm in LAZY_STATIC.finditer(_t(n)):
|
|
1316
|
+
raw = mm.group(5) if mm.group(5) is not None else _rust_unescape(mm.group(6) or "")
|
|
1317
|
+
statics.setdefault(mm.group(1), []).append({"pattern": raw, "flags": "", "file": rel,
|
|
1318
|
+
"line": _line(n) + _t(n)[:mm.start()].count("\n"), "engine": "rust"})
|
|
1319
|
+
# uses of the statics, by name (a static is used across modules: `use super::patterns::*`), in any Rust file that
|
|
1320
|
+
# names one, whether or not it mentions Regex itself
|
|
1321
|
+
seen = {rel for rel, *_ in parsed}
|
|
1322
|
+
names_re = re.compile(r"\b(?:" + "|".join(re.escape(k) for k in statics) + r")\b") if statics else None
|
|
1323
|
+
users = list(parsed)
|
|
1324
|
+
if names_re is not None:
|
|
1325
|
+
for rel in files:
|
|
1326
|
+
if rel in seen:
|
|
1327
|
+
continue
|
|
1328
|
+
src = read_text(root / rel)
|
|
1329
|
+
if src and names_re.search(src):
|
|
1330
|
+
users.append((rel, parser("rust").parse(src.encode()), src, "fancy_regex" in src))
|
|
1331
|
+
for rel, tree, src, fancy in users:
|
|
1332
|
+
for n in _walk(tree.root_node):
|
|
1333
|
+
if n.type != "call_expression":
|
|
1334
|
+
continue
|
|
1335
|
+
f = n.child_by_field_name("function")
|
|
1336
|
+
if f is None or f.type != "field_expression":
|
|
1337
|
+
continue
|
|
1338
|
+
recv = f.child_by_field_name("value")
|
|
1339
|
+
field = _t(f.child_by_field_name("field"))
|
|
1340
|
+
rname = _t(recv).split("::")[-1]
|
|
1341
|
+
if field not in RUST_MODES or rname not in statics:
|
|
1342
|
+
continue
|
|
1343
|
+
# a static belongs to its crate: the definition is the one in the same crate as the use, when it is one
|
|
1344
|
+
mine = [d for d in statics[rname] if _crate_of(root, d["file"]) == _crate_of(root, rel)]
|
|
1345
|
+
if len(mine) != 1:
|
|
1346
|
+
continue
|
|
1347
|
+
d = mine[0]
|
|
1348
|
+
used.add((rname, d["file"], d["line"]))
|
|
1349
|
+
fn, sym = _rust_fn(n)
|
|
1350
|
+
args = n.child_by_field_name("arguments")
|
|
1351
|
+
arg = args.named_children[0] if args is not None and args.named_children else None
|
|
1352
|
+
api, take, use = field, None, n
|
|
1353
|
+
par = n.parent
|
|
1354
|
+
if field == "find_iter" and par is not None and par.type == "field_expression" and _t(par.child_by_field_name("field")) == "count" \
|
|
1355
|
+
and par.parent is not None and par.parent.type == "call_expression":
|
|
1356
|
+
api, use = "count", par.parent
|
|
1357
|
+
take = _take_bound(par.parent, fn)
|
|
1358
|
+
out.append(make(rel, _line(n), "rust", d["engine"], d["pattern"], d["flags"], api, symbol=sym, compiled="once",
|
|
1359
|
+
in_loop=_rust_loop(n, fn), source="constant", def_line=d["line"], def_file=d["file"], arg=_t(arg),
|
|
1360
|
+
take=take, name=rname, use=_t(use)))
|
|
1361
|
+
for name, defs in statics.items():
|
|
1362
|
+
for d in defs:
|
|
1363
|
+
if (name, d["file"], d["line"]) in used:
|
|
1364
|
+
continue
|
|
1365
|
+
out.append(make(d["file"], d["line"], "rust", d["engine"], d["pattern"], d["flags"], "new", compiled="once",
|
|
1366
|
+
source="constant", name=name))
|
|
1367
|
+
return out
|
|
1368
|
+
|
|
1369
|
+
|
|
1370
|
+
EXTRACTORS = {"python": python_sites, "go": go_sites, "java": java_sites, "typescript": ts_sites, "rust": rust_sites}
|
|
1371
|
+
|
|
1372
|
+
|
|
1373
|
+
def sites(root: Path, by_lang: dict, languages: list[str] | None = None, log=None) -> list[dict]:
|
|
1374
|
+
out = []
|
|
1375
|
+
for lang, files in sorted((by_lang or {}).items()):
|
|
1376
|
+
fx = EXTRACTORS.get(lang)
|
|
1377
|
+
if fx is None or (languages and lang not in languages):
|
|
1378
|
+
continue
|
|
1379
|
+
try:
|
|
1380
|
+
got = fx(root, list(files))
|
|
1381
|
+
except Exception as e: # noqa: BLE001 -- one language must not lose the others
|
|
1382
|
+
if log:
|
|
1383
|
+
log(f"regex: {lang} extraction stopped ({type(e).__name__}: {e})")
|
|
1384
|
+
got = []
|
|
1385
|
+
out.extend(got)
|
|
1386
|
+
return out
|
|
1387
|
+
|
|
1388
|
+
|
|
1389
|
+
# a file named like an example, a fixture or a sample is not the table a service loads
|
|
1390
|
+
NOT_CONFIG = re.compile(r"(^|[/_.-])(examples?|samples?|fixtures?|mocks?|demo|testdata|tests?|package(-lock)?|tsconfig|"
|
|
1391
|
+
r"manifest|schema|openapi|swagger|contract|conformance)([/_.-]|$)", re.I)
|
|
1392
|
+
|
|
1393
|
+
|
|
1394
|
+
def config_tables(root: Path, by_lang: dict, max_bytes: int = 2_000_000) -> list[dict]:
|
|
1395
|
+
"""Pattern tables in JSON or YAML files that the code names (`rules.yaml` read by a Python loader): one site per
|
|
1396
|
+
pattern, at its line, with the engine of the language that names the file."""
|
|
1397
|
+
from ...discover.base import is_test_path
|
|
1398
|
+
names: dict[str, str] = {}
|
|
1399
|
+
for lang, files in (by_lang or {}).items():
|
|
1400
|
+
for rel in files:
|
|
1401
|
+
if is_test_path(rel) or NOT_CONFIG.search(rel):
|
|
1402
|
+
continue
|
|
1403
|
+
text = read_text(root / rel) or ""
|
|
1404
|
+
for m in re.finditer(r"[\"']([\w./-]+\.(?:json|ya?ml))[\"']", text):
|
|
1405
|
+
names.setdefault(os.path.basename(m.group(1)), lang)
|
|
1406
|
+
if not names:
|
|
1407
|
+
return []
|
|
1408
|
+
engine_of = {"python": "python", "typescript": "node", "go": "go", "java": "java", "rust": "rust"}
|
|
1409
|
+
out = []
|
|
1410
|
+
key_re = re.compile(r"""^\s*-?\s*["']?(regex|pattern|patterns|regexes|regexp|match_regex|re)["']?\s*:\s*(.+?)\s*,?\s*$""")
|
|
1411
|
+
for dirpath, dirnames, filenames in os.walk(root):
|
|
1412
|
+
dirnames[:] = [d for d in dirnames if not d.startswith(".") and d not in ("node_modules", "vendor", "target", "dist", "build")]
|
|
1413
|
+
for fname in filenames:
|
|
1414
|
+
if fname not in names or NOT_CONFIG.search(fname):
|
|
1415
|
+
continue
|
|
1416
|
+
p = Path(dirpath) / fname
|
|
1417
|
+
try:
|
|
1418
|
+
if p.stat().st_size > max_bytes:
|
|
1419
|
+
continue
|
|
1420
|
+
lines = p.read_text(errors="replace").splitlines()
|
|
1421
|
+
except OSError:
|
|
1422
|
+
continue
|
|
1423
|
+
rel = str(p.relative_to(root))
|
|
1424
|
+
lang = names[fname]
|
|
1425
|
+
for i, ln in enumerate(lines, 1):
|
|
1426
|
+
m = key_re.match(ln)
|
|
1427
|
+
if not m:
|
|
1428
|
+
continue
|
|
1429
|
+
v = m.group(2).strip()
|
|
1430
|
+
if v.startswith(("'", '"')):
|
|
1431
|
+
try:
|
|
1432
|
+
s = json.loads(v) if v.startswith('"') else v[1:-1].replace("''", "'")
|
|
1433
|
+
except ValueError:
|
|
1434
|
+
continue
|
|
1435
|
+
if isinstance(s, str) and len(s) >= 3:
|
|
1436
|
+
out.append(make(rel, i, lang, engine_of.get(lang, "python"), s, "", "search", compiled="once", source="table",
|
|
1437
|
+
table=rel, name=m.group(1)))
|
|
1438
|
+
return out
|