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,1721 @@
|
|
|
1
|
+
"""A small regex parser for the five flavors CodeCop reads (Python `re`, JavaScript, Java, Go `regexp`, Rust `regex`), the
|
|
2
|
+
static check for super-linear structure, the strings a pattern matches (shortest sample, random members for the corpus),
|
|
3
|
+
and the rule-made rewrites. Pure Python, no dependency.
|
|
4
|
+
|
|
5
|
+
The parser keeps each node's span in the pattern text, so a rewrite is a text edit of the developer's own pattern (a
|
|
6
|
+
possessive `+` after one quantifier, a lookbehind guard in front, `(?-u:\\b)` for `\\b`), never a re-printed pattern.
|
|
7
|
+
|
|
8
|
+
The static check is a gate, not the verdict: it names the repeats that can backtrack super-linearly and, for each, a
|
|
9
|
+
few attack families (prefix + pump * n + suffix). The engine itself decides (harness.py): a family that does not grow on
|
|
10
|
+
the pattern's own engine is no finding.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import random
|
|
16
|
+
import unicodedata
|
|
17
|
+
from dataclasses import dataclass, field
|
|
18
|
+
|
|
19
|
+
FLAVORS = ("python", "js", "java", "go", "rust")
|
|
20
|
+
INF = None
|
|
21
|
+
|
|
22
|
+
# The characters a char set is evaluated on: ASCII and a few that tell the flavors apart (a letter with an accent, a
|
|
23
|
+
# Greek, Cyrillic and CJK letter, an Arabic digit, a superscript digit, non-breaking and other spaces, a line separator,
|
|
24
|
+
# an emoji). A pattern's own literal characters are added per pattern.
|
|
25
|
+
BASE_UNIVERSE = tuple(chr(i) for i in range(128)) + ("é", "ß", "λ", "Ж", "中", "٣", "²", "\u00a0", "\u2028", "\u3000", "\u0085", "😀")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class Unsupported(ValueError):
|
|
29
|
+
"""The pattern uses syntax this parser does not read (or is not a valid pattern)."""
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
# --- char sets ---------------------------------------------------------------------------------------------------------
|
|
33
|
+
|
|
34
|
+
@dataclass(frozen=True)
|
|
35
|
+
class CharSet:
|
|
36
|
+
"""A set of characters as items (a char, a range, a named class) and a negation; evaluated on a universe."""
|
|
37
|
+
items: tuple = ()
|
|
38
|
+
negated: bool = False
|
|
39
|
+
icase: bool = False
|
|
40
|
+
flavor: str = "python"
|
|
41
|
+
ascii: bool = False # \w \d \s are ASCII-only (Python re.ASCII, Rust (?-u), and JS/Java/Go by default)
|
|
42
|
+
dotall: bool = False
|
|
43
|
+
|
|
44
|
+
def contains(self, c: str) -> bool:
|
|
45
|
+
cands = {x for x in (c, c.lower(), c.upper()) if len(x) == 1} if self.icase else {c}
|
|
46
|
+
hit = any(_item_has(it, x, self) for it in self.items for x in cands)
|
|
47
|
+
return hit != self.negated
|
|
48
|
+
|
|
49
|
+
def chars(self, universe) -> frozenset:
|
|
50
|
+
return frozenset(c for c in universe if self.contains(c))
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _class_has(name: str, c: str, cs: CharSet) -> bool:
|
|
54
|
+
ascii_only = cs.ascii or cs.flavor in ("js", "java", "go")
|
|
55
|
+
if name == "d":
|
|
56
|
+
return "0" <= c <= "9" if ascii_only else c.isdecimal()
|
|
57
|
+
if name == "w":
|
|
58
|
+
if ascii_only:
|
|
59
|
+
return c.isascii() and (c.isalnum() or c == "_")
|
|
60
|
+
return c.isalnum() or c == "_"
|
|
61
|
+
if name == "s":
|
|
62
|
+
if cs.flavor == "java" or (cs.ascii and cs.flavor != "js"):
|
|
63
|
+
return c in " \t\n\x0b\f\r"
|
|
64
|
+
if cs.flavor == "go":
|
|
65
|
+
return c in " \t\n\f\r"
|
|
66
|
+
return c.isspace() or c == "\ufeff" and cs.flavor == "js"
|
|
67
|
+
if name == "any":
|
|
68
|
+
if cs.dotall:
|
|
69
|
+
return True
|
|
70
|
+
if cs.flavor in ("js", "java"):
|
|
71
|
+
return c not in "\n\r\u2028\u2029" + ("\u0085" if cs.flavor == "java" else "")
|
|
72
|
+
return c != "\n"
|
|
73
|
+
if name.startswith("p:"):
|
|
74
|
+
return _prop_has(name[2:], c)
|
|
75
|
+
if name.startswith("posix:"):
|
|
76
|
+
return _posix_has(name[6:], c)
|
|
77
|
+
return False
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _item_has(it, c: str, cs: CharSet) -> bool:
|
|
81
|
+
kind = it[0]
|
|
82
|
+
if kind == "ch":
|
|
83
|
+
return c == it[1]
|
|
84
|
+
if kind == "range":
|
|
85
|
+
return it[1] <= c <= it[2]
|
|
86
|
+
if kind == "cls":
|
|
87
|
+
return _class_has(it[1], c, cs) != it[2]
|
|
88
|
+
if kind == "set": # a nested class (Java/Rust [a[b]], intersections are read as unions: approximate)
|
|
89
|
+
return it[1].contains(c)
|
|
90
|
+
return False
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _prop_has(prop: str, c: str) -> bool:
|
|
94
|
+
p = prop.replace("_", "").replace(" ", "").lower()
|
|
95
|
+
neg = False
|
|
96
|
+
if p.startswith("^"):
|
|
97
|
+
neg, p = True, p[1:]
|
|
98
|
+
for pre in ("is", "in", "general_category=", "gc=", "script=", "sc="):
|
|
99
|
+
if p.startswith(pre) and len(p) > len(pre):
|
|
100
|
+
p = p[len(pre):]
|
|
101
|
+
cat = unicodedata.category(c)
|
|
102
|
+
table = {"l": cat.startswith("L"), "letter": cat.startswith("L"), "alpha": c.isalpha(), "alphabetic": c.isalpha(),
|
|
103
|
+
"lu": cat == "Lu", "upper": c.isupper(), "uppercase": c.isupper(), "uppercaseletter": cat == "Lu",
|
|
104
|
+
"ll": cat == "Ll", "lower": c.islower(), "lowercase": c.islower(), "lowercaseletter": cat == "Ll",
|
|
105
|
+
"n": cat.startswith("N"), "number": cat.startswith("N"), "nd": cat == "Nd", "digit": cat == "Nd",
|
|
106
|
+
"p": cat.startswith("P"), "punct": cat.startswith("P"), "punctuation": cat.startswith("P"),
|
|
107
|
+
"s": cat.startswith("S"), "symbol": cat.startswith("S"), "z": cat.startswith("Z"), "separator": cat.startswith("Z"),
|
|
108
|
+
"space": c.isspace(), "whitespace": c.isspace(), "m": cat.startswith("M"), "mark": cat.startswith("M"),
|
|
109
|
+
"c": cat.startswith("C"), "cc": cat == "Cc", "cntrl": cat == "Cc", "ascii": c.isascii(), "any": True,
|
|
110
|
+
"alnum": c.isalnum(), "word": c.isalnum() or c == "_",
|
|
111
|
+
"latin": c.isalpha() and (c.isascii() or "LATIN" in unicodedata.name(c, "")),
|
|
112
|
+
"greek": "GREEK" in unicodedata.name(c, ""), "cyrillic": "CYRILLIC" in unicodedata.name(c, ""),
|
|
113
|
+
"han": "CJK" in unicodedata.name(c, ""), "arabic": "ARABIC" in unicodedata.name(c, ""),
|
|
114
|
+
"emoji": ord(c) >= 0x1F000, "extendedpictographic": ord(c) >= 0x1F000}
|
|
115
|
+
if p in table:
|
|
116
|
+
return table[p] != neg
|
|
117
|
+
if len(p) <= 2:
|
|
118
|
+
return cat.lower().startswith(p) != neg
|
|
119
|
+
return (not c.isascii() and c.isalpha()) != neg # a script or block this table does not know: non-ASCII letters
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _posix_has(name: str, c: str) -> bool:
|
|
123
|
+
return {"alpha": c.isascii() and c.isalpha(), "digit": "0" <= c <= "9", "alnum": c.isascii() and c.isalnum(),
|
|
124
|
+
"upper": "A" <= c <= "Z", "lower": "a" <= c <= "z", "space": c in " \t\n\r\f\v", "blank": c in " \t",
|
|
125
|
+
"punct": c.isascii() and c.isprintable() and not c.isalnum() and c != " ", "word": c.isascii() and (c.isalnum() or c == "_"),
|
|
126
|
+
"xdigit": c in "0123456789abcdefABCDEF", "cntrl": ord(c) < 32 or ord(c) == 127, "print": c.isascii() and c.isprintable(),
|
|
127
|
+
"graph": c.isascii() and c.isprintable() and c != " ", "ascii": c.isascii()}.get(name, False)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
# --- the tree ----------------------------------------------------------------------------------------------------------
|
|
131
|
+
|
|
132
|
+
@dataclass(eq=False)
|
|
133
|
+
class Node:
|
|
134
|
+
kind: str # char seq alt rep group look anchor backref empty
|
|
135
|
+
span: tuple = (0, 0) # [start, end) in the pattern text
|
|
136
|
+
cs: CharSet | None = None # char
|
|
137
|
+
items: list = field(default_factory=list) # seq, alt
|
|
138
|
+
item: "Node | None" = None # rep, group, look
|
|
139
|
+
lo: int = 0 # rep
|
|
140
|
+
hi: int | None = None # rep: None = unbounded
|
|
141
|
+
greedy: bool = True
|
|
142
|
+
possessive: bool = False
|
|
143
|
+
qspan: tuple = (0, 0) # rep: the quantifier's span (`+`, `{2,}`, `*?`)
|
|
144
|
+
cap: int | None = None # group: its number when capturing
|
|
145
|
+
name: str = "" # group name, anchor name, backref target
|
|
146
|
+
atomic: bool = False
|
|
147
|
+
ahead: bool = True # look
|
|
148
|
+
neg: bool = False # look
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
@dataclass
|
|
152
|
+
class Parsed:
|
|
153
|
+
pattern: str
|
|
154
|
+
flavor: str
|
|
155
|
+
root: Node
|
|
156
|
+
groups: int
|
|
157
|
+
flags: dict
|
|
158
|
+
universe: tuple
|
|
159
|
+
|
|
160
|
+
def walk(self):
|
|
161
|
+
return walk(self.root)
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def walk(n: Node):
|
|
165
|
+
stack = [n]
|
|
166
|
+
while stack:
|
|
167
|
+
x = stack.pop()
|
|
168
|
+
yield x
|
|
169
|
+
if x.item is not None:
|
|
170
|
+
stack.append(x.item)
|
|
171
|
+
stack.extend(reversed(x.items))
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
class _Parser:
|
|
175
|
+
def __init__(self, text: str, flavor: str, flags: dict):
|
|
176
|
+
self.t, self.i, self.flavor = text, 0, flavor
|
|
177
|
+
self.flags = dict(flags)
|
|
178
|
+
self.groups = 0
|
|
179
|
+
self.literals: set[str] = set()
|
|
180
|
+
|
|
181
|
+
# helpers
|
|
182
|
+
def peek(self, k: int = 0) -> str:
|
|
183
|
+
j = self.i + k
|
|
184
|
+
return self.t[j] if j < len(self.t) else ""
|
|
185
|
+
|
|
186
|
+
def eat(self, s: str) -> bool:
|
|
187
|
+
if self.t.startswith(s, self.i):
|
|
188
|
+
self.i += len(s)
|
|
189
|
+
return True
|
|
190
|
+
return False
|
|
191
|
+
|
|
192
|
+
def cset(self, items, negated=False) -> CharSet:
|
|
193
|
+
f = self.flags
|
|
194
|
+
return CharSet(tuple(items), negated, bool(f.get("i")), self.flavor, bool(f.get("a")), bool(f.get("s")))
|
|
195
|
+
|
|
196
|
+
def skip_ws(self):
|
|
197
|
+
if not self.flags.get("x"):
|
|
198
|
+
return
|
|
199
|
+
while self.i < len(self.t):
|
|
200
|
+
c = self.t[self.i]
|
|
201
|
+
if c in " \t\n\r\f\v":
|
|
202
|
+
self.i += 1
|
|
203
|
+
elif c == "#":
|
|
204
|
+
while self.i < len(self.t) and self.t[self.i] != "\n":
|
|
205
|
+
self.i += 1
|
|
206
|
+
else:
|
|
207
|
+
break
|
|
208
|
+
|
|
209
|
+
# grammar
|
|
210
|
+
def parse(self) -> Node:
|
|
211
|
+
n = self.alt()
|
|
212
|
+
if self.i < len(self.t):
|
|
213
|
+
raise Unsupported(f"unbalanced ) at {self.i}")
|
|
214
|
+
return n
|
|
215
|
+
|
|
216
|
+
def alt(self) -> Node:
|
|
217
|
+
start = self.i
|
|
218
|
+
branches = [self.seq()]
|
|
219
|
+
while self.peek() == "|":
|
|
220
|
+
self.i += 1
|
|
221
|
+
branches.append(self.seq())
|
|
222
|
+
if len(branches) == 1:
|
|
223
|
+
return branches[0]
|
|
224
|
+
return Node("alt", (start, self.i), items=branches)
|
|
225
|
+
|
|
226
|
+
def seq(self) -> Node:
|
|
227
|
+
start = self.i
|
|
228
|
+
items = []
|
|
229
|
+
while True:
|
|
230
|
+
self.skip_ws()
|
|
231
|
+
c = self.peek()
|
|
232
|
+
if c == "" or c == "|" or c == ")":
|
|
233
|
+
break
|
|
234
|
+
atom = self.atom()
|
|
235
|
+
if atom is None:
|
|
236
|
+
continue
|
|
237
|
+
atom = self.quant(atom)
|
|
238
|
+
items.append(atom)
|
|
239
|
+
if len(items) == 1:
|
|
240
|
+
return items[0]
|
|
241
|
+
return Node("seq", (start, self.i), items=items)
|
|
242
|
+
|
|
243
|
+
def quant(self, atom: Node) -> Node:
|
|
244
|
+
while True:
|
|
245
|
+
self.skip_ws()
|
|
246
|
+
qs = self.i
|
|
247
|
+
c = self.peek()
|
|
248
|
+
lo, hi = None, None
|
|
249
|
+
if c == "*":
|
|
250
|
+
lo, hi = 0, INF
|
|
251
|
+
self.i += 1
|
|
252
|
+
elif c == "+":
|
|
253
|
+
lo, hi = 1, INF
|
|
254
|
+
self.i += 1
|
|
255
|
+
elif c == "?":
|
|
256
|
+
lo, hi = 0, 1
|
|
257
|
+
self.i += 1
|
|
258
|
+
elif c == "{":
|
|
259
|
+
got = self.brace()
|
|
260
|
+
if got is None:
|
|
261
|
+
return atom
|
|
262
|
+
lo, hi = got
|
|
263
|
+
else:
|
|
264
|
+
return atom
|
|
265
|
+
if atom.kind in ("anchor", "look") and self.flavor in ("go", "rust"):
|
|
266
|
+
raise Unsupported("a quantified assertion")
|
|
267
|
+
greedy, possessive = True, False
|
|
268
|
+
if self.peek() == "?":
|
|
269
|
+
greedy = False
|
|
270
|
+
self.i += 1
|
|
271
|
+
elif self.peek() == "+" and self.flavor in ("python", "java"):
|
|
272
|
+
possessive = True
|
|
273
|
+
self.i += 1
|
|
274
|
+
atom = Node("rep", (atom.span[0], self.i), item=atom, lo=lo, hi=hi, greedy=greedy, possessive=possessive, qspan=(qs, self.i))
|
|
275
|
+
|
|
276
|
+
def brace(self):
|
|
277
|
+
j = self.i + 1
|
|
278
|
+
k = self.t.find("}", j)
|
|
279
|
+
if k < 0:
|
|
280
|
+
return None
|
|
281
|
+
body = self.t[j:k].replace(" ", "") if self.flavor == "rust" else self.t[j:k]
|
|
282
|
+
if "," in body:
|
|
283
|
+
a, b = body.split(",", 1)
|
|
284
|
+
if not (a.isdigit() or (a == "" and self.flavor in ("python", "rust"))) or not (b.isdigit() or b == ""):
|
|
285
|
+
return None
|
|
286
|
+
lo, hi = int(a or 0), (int(b) if b else INF)
|
|
287
|
+
elif body.isdigit():
|
|
288
|
+
lo = hi = int(body)
|
|
289
|
+
else:
|
|
290
|
+
return None
|
|
291
|
+
self.i = k + 1
|
|
292
|
+
return lo, hi
|
|
293
|
+
|
|
294
|
+
def atom(self) -> Node | None:
|
|
295
|
+
start = self.i
|
|
296
|
+
c = self.peek()
|
|
297
|
+
if c == "(":
|
|
298
|
+
return self.group()
|
|
299
|
+
if c == "[":
|
|
300
|
+
cs = self.char_class()
|
|
301
|
+
return Node("char", (start, self.i), cs=cs)
|
|
302
|
+
if c == ".":
|
|
303
|
+
self.i += 1
|
|
304
|
+
return Node("char", (start, self.i), cs=self.cset([("cls", "any", False)]))
|
|
305
|
+
if c == "^":
|
|
306
|
+
self.i += 1
|
|
307
|
+
return Node("anchor", (start, self.i), name="bol" if self.flags.get("m") else "start")
|
|
308
|
+
if c == "$":
|
|
309
|
+
self.i += 1
|
|
310
|
+
return Node("anchor", (start, self.i), name="eol" if self.flags.get("m") else "end")
|
|
311
|
+
if c == "\\":
|
|
312
|
+
return self.escape()
|
|
313
|
+
if c in "*+?" or (c == "{" and self.flavor in ("go", "rust", "java", "python") and self.brace_like()):
|
|
314
|
+
raise Unsupported(f"nothing to repeat at {self.i}")
|
|
315
|
+
self.i += 1
|
|
316
|
+
self.literals.add(c)
|
|
317
|
+
return Node("char", (start, self.i), cs=self.cset([("ch", c)]))
|
|
318
|
+
|
|
319
|
+
def brace_like(self) -> bool:
|
|
320
|
+
save = self.i
|
|
321
|
+
got = self.brace()
|
|
322
|
+
self.i = save
|
|
323
|
+
return got is not None
|
|
324
|
+
|
|
325
|
+
def group(self) -> Node:
|
|
326
|
+
start = self.i
|
|
327
|
+
self.i += 1
|
|
328
|
+
saved = dict(self.flags)
|
|
329
|
+
cap, name, atomic, look = None, "", False, None
|
|
330
|
+
if self.eat("?"):
|
|
331
|
+
c = self.peek()
|
|
332
|
+
if c == ":":
|
|
333
|
+
self.i += 1
|
|
334
|
+
elif c == ">":
|
|
335
|
+
self.i += 1
|
|
336
|
+
atomic = True
|
|
337
|
+
elif c == "#":
|
|
338
|
+
k = self.t.find(")", self.i)
|
|
339
|
+
if k < 0:
|
|
340
|
+
raise Unsupported("unterminated comment")
|
|
341
|
+
self.i = k + 1
|
|
342
|
+
return None
|
|
343
|
+
elif c in "=!":
|
|
344
|
+
self.i += 1
|
|
345
|
+
look = (True, c == "!")
|
|
346
|
+
elif c == "<" and self.peek(1) in "=!":
|
|
347
|
+
look = (False, self.peek(1) == "!")
|
|
348
|
+
self.i += 2
|
|
349
|
+
elif c == "P" and self.peek(1) == "<" or c == "<" or c == "'":
|
|
350
|
+
if c == "P":
|
|
351
|
+
self.i += 1
|
|
352
|
+
close = ">" if self.peek() == "<" else "'"
|
|
353
|
+
self.i += 1
|
|
354
|
+
k = self.t.find(close, self.i)
|
|
355
|
+
if k < 0:
|
|
356
|
+
raise Unsupported("unterminated group name")
|
|
357
|
+
name = self.t[self.i:k]
|
|
358
|
+
self.i = k + 1
|
|
359
|
+
self.groups += 1
|
|
360
|
+
cap = self.groups
|
|
361
|
+
elif c == "P" and self.peek(1) == "=":
|
|
362
|
+
k = self.t.find(")", self.i)
|
|
363
|
+
if k < 0:
|
|
364
|
+
raise Unsupported("unterminated backreference")
|
|
365
|
+
ref = self.t[self.i + 2:k]
|
|
366
|
+
self.i = k + 1
|
|
367
|
+
return Node("backref", (start, self.i), name=ref)
|
|
368
|
+
else:
|
|
369
|
+
# inline flags: (?i) (?i:...) (?-u:...) (?ims-x)
|
|
370
|
+
j = self.i
|
|
371
|
+
on = True
|
|
372
|
+
changes = {}
|
|
373
|
+
while j < len(self.t) and self.t[j] not in ":)":
|
|
374
|
+
ch = self.t[j]
|
|
375
|
+
if ch == "-":
|
|
376
|
+
on = False
|
|
377
|
+
elif ch in "imsxuaULR":
|
|
378
|
+
key = {"u": "U", "U": "ungreedy"}.get(ch, ch)
|
|
379
|
+
if ch == "u":
|
|
380
|
+
changes["a"] = not on
|
|
381
|
+
elif ch in "imsxa":
|
|
382
|
+
changes[ch] = on
|
|
383
|
+
else:
|
|
384
|
+
raise Unsupported(f"group syntax (?{ch}")
|
|
385
|
+
j += 1
|
|
386
|
+
if j >= len(self.t):
|
|
387
|
+
raise Unsupported("unterminated flags")
|
|
388
|
+
if self.t[j] == ")":
|
|
389
|
+
self.flags.update(changes) # applies to the rest of the enclosing group
|
|
390
|
+
self.i = j + 1
|
|
391
|
+
return None
|
|
392
|
+
self.flags.update(changes)
|
|
393
|
+
self.i = j + 1
|
|
394
|
+
body = self.alt()
|
|
395
|
+
if not self.eat(")"):
|
|
396
|
+
raise Unsupported("missing )")
|
|
397
|
+
self.flags = saved
|
|
398
|
+
return Node("group", (start, self.i), item=body)
|
|
399
|
+
else:
|
|
400
|
+
self.groups += 1
|
|
401
|
+
cap = self.groups
|
|
402
|
+
body = self.alt()
|
|
403
|
+
if not self.eat(")"):
|
|
404
|
+
raise Unsupported("missing )")
|
|
405
|
+
self.flags = saved
|
|
406
|
+
if look is not None:
|
|
407
|
+
return Node("look", (start, self.i), item=body, ahead=look[0], neg=look[1])
|
|
408
|
+
return Node("group", (start, self.i), item=body, cap=cap, name=name, atomic=atomic)
|
|
409
|
+
|
|
410
|
+
def escape(self) -> Node:
|
|
411
|
+
start = self.i
|
|
412
|
+
self.i += 1
|
|
413
|
+
c = self.peek()
|
|
414
|
+
if c == "":
|
|
415
|
+
raise Unsupported("trailing backslash")
|
|
416
|
+
self.i += 1
|
|
417
|
+
if c in "dwsDWS":
|
|
418
|
+
return Node("char", (start, self.i), cs=self.cset([("cls", c.lower(), c.isupper())]))
|
|
419
|
+
if c in "bB":
|
|
420
|
+
return Node("anchor", (start, self.i), name="wordb" if c == "b" else "nwordb")
|
|
421
|
+
if c == "A":
|
|
422
|
+
return Node("anchor", (start, self.i), name="start")
|
|
423
|
+
if c in "zZ":
|
|
424
|
+
return Node("anchor", (start, self.i), name="end" if (c == "z" or self.flavor == "python") else "endnl")
|
|
425
|
+
if c == "G":
|
|
426
|
+
return Node("anchor", (start, self.i), name="start")
|
|
427
|
+
if c in "pP" and self.flavor != "python":
|
|
428
|
+
prop = self.prop()
|
|
429
|
+
return Node("char", (start, self.i), cs=self.cset([("cls", "p:" + prop, c == "P")]))
|
|
430
|
+
if c.isdigit() and c != "0":
|
|
431
|
+
j = self.i
|
|
432
|
+
while j < len(self.t) and self.t[j].isdigit():
|
|
433
|
+
j += 1
|
|
434
|
+
ref = self.t[self.i - 1:j]
|
|
435
|
+
self.i = j
|
|
436
|
+
if self.flavor in ("go", "rust"):
|
|
437
|
+
raise Unsupported("backreferences")
|
|
438
|
+
return Node("backref", (start, self.i), name=ref)
|
|
439
|
+
if c == "k" and self.peek() in "<{'":
|
|
440
|
+
close = {"<": ">", "{": "}", "'": "'"}[self.peek()]
|
|
441
|
+
k = self.t.find(close, self.i + 1)
|
|
442
|
+
ref = self.t[self.i + 1:k]
|
|
443
|
+
self.i = k + 1
|
|
444
|
+
return Node("backref", (start, self.i), name=ref)
|
|
445
|
+
ch = self.char_escape(c)
|
|
446
|
+
self.literals.add(ch)
|
|
447
|
+
return Node("char", (start, self.i), cs=self.cset([("ch", ch)]))
|
|
448
|
+
|
|
449
|
+
def prop(self) -> str:
|
|
450
|
+
if self.peek() == "{":
|
|
451
|
+
k = self.t.find("}", self.i)
|
|
452
|
+
if k < 0:
|
|
453
|
+
raise Unsupported("unterminated property")
|
|
454
|
+
p = self.t[self.i + 1:k]
|
|
455
|
+
self.i = k + 1
|
|
456
|
+
return p
|
|
457
|
+
p = self.peek()
|
|
458
|
+
self.i += 1
|
|
459
|
+
return p
|
|
460
|
+
|
|
461
|
+
def char_escape(self, c: str) -> str:
|
|
462
|
+
simple = {"n": "\n", "t": "\t", "r": "\r", "f": "\f", "v": "\v", "a": "\a", "e": "\x1b", "0": "\0"}
|
|
463
|
+
if c in simple and not (c == "0" and self.peek().isdigit() and self.flavor == "python"):
|
|
464
|
+
return simple[c]
|
|
465
|
+
if c == "x":
|
|
466
|
+
if self.peek() == "{":
|
|
467
|
+
k = self.t.find("}", self.i)
|
|
468
|
+
v = self.t[self.i + 1:k]
|
|
469
|
+
self.i = k + 1
|
|
470
|
+
return chr(int(v, 16))
|
|
471
|
+
v = self.t[self.i:self.i + 2]
|
|
472
|
+
self.i += 2
|
|
473
|
+
return chr(int(v, 16))
|
|
474
|
+
if c == "u":
|
|
475
|
+
if self.peek() == "{":
|
|
476
|
+
k = self.t.find("}", self.i)
|
|
477
|
+
v = self.t[self.i + 1:k]
|
|
478
|
+
self.i = k + 1
|
|
479
|
+
return chr(int(v, 16))
|
|
480
|
+
v = self.t[self.i:self.i + 4]
|
|
481
|
+
self.i += 4
|
|
482
|
+
return chr(int(v, 16))
|
|
483
|
+
if c == "U" and self.flavor in ("python", "rust"):
|
|
484
|
+
v = self.t[self.i:self.i + 8]
|
|
485
|
+
self.i += 8
|
|
486
|
+
return chr(int(v, 16))
|
|
487
|
+
if c == "c" and self.flavor in ("js", "java"):
|
|
488
|
+
v = self.peek()
|
|
489
|
+
self.i += 1
|
|
490
|
+
return chr(ord(v.upper()) ^ 64)
|
|
491
|
+
if c == "N" and self.peek() == "{":
|
|
492
|
+
k = self.t.find("}", self.i)
|
|
493
|
+
name = self.t[self.i + 1:k]
|
|
494
|
+
self.i = k + 1
|
|
495
|
+
try:
|
|
496
|
+
return unicodedata.lookup(name)
|
|
497
|
+
except KeyError:
|
|
498
|
+
raise Unsupported(f"unknown character name {name}") from None
|
|
499
|
+
if c == "0":
|
|
500
|
+
j = self.i
|
|
501
|
+
while j < len(self.t) and j < self.i + 2 and self.t[j] in "01234567":
|
|
502
|
+
j += 1
|
|
503
|
+
v = self.t[self.i - 1:j]
|
|
504
|
+
self.i = j
|
|
505
|
+
return chr(int(v, 8))
|
|
506
|
+
if c.isalnum() and c not in "_":
|
|
507
|
+
raise Unsupported(f"escape \\{c}")
|
|
508
|
+
return c
|
|
509
|
+
|
|
510
|
+
def char_class(self) -> CharSet:
|
|
511
|
+
self.i += 1
|
|
512
|
+
negated = self.eat("^")
|
|
513
|
+
items = []
|
|
514
|
+
first = True
|
|
515
|
+
while True:
|
|
516
|
+
c = self.peek()
|
|
517
|
+
if c == "":
|
|
518
|
+
raise Unsupported("unterminated [")
|
|
519
|
+
if c == "]" and not (first and self.flavor in ("python", "go", "rust", "java")):
|
|
520
|
+
self.i += 1
|
|
521
|
+
break
|
|
522
|
+
first = False
|
|
523
|
+
if c == "[" and self.peek(1) == ":":
|
|
524
|
+
k = self.t.find(":]", self.i)
|
|
525
|
+
if k > 0 and self.flavor in ("go", "rust"):
|
|
526
|
+
name = self.t[self.i + 2:k]
|
|
527
|
+
neg = name.startswith("^")
|
|
528
|
+
items.append(("cls", "posix:" + name.lstrip("^"), neg))
|
|
529
|
+
self.i = k + 2
|
|
530
|
+
continue
|
|
531
|
+
if c == "[" and self.flavor in ("java", "rust"):
|
|
532
|
+
sub = self.char_class()
|
|
533
|
+
items.append(("set", sub))
|
|
534
|
+
continue
|
|
535
|
+
if self.t.startswith("&&", self.i) and self.flavor in ("java", "rust"):
|
|
536
|
+
self.i += 2 # intersection: read as union (an over-approximation of the class)
|
|
537
|
+
continue
|
|
538
|
+
if self.t.startswith("--", self.i) and self.flavor == "rust" or self.t.startswith("~~", self.i) and self.flavor == "rust":
|
|
539
|
+
self.i += 2
|
|
540
|
+
continue
|
|
541
|
+
lo = self.class_atom(items)
|
|
542
|
+
if lo is None:
|
|
543
|
+
continue
|
|
544
|
+
if self.peek() == "-" and self.peek(1) not in ("]", ""):
|
|
545
|
+
save = self.i
|
|
546
|
+
self.i += 1
|
|
547
|
+
if self.peek() == "\\" and self.peek(1) in "dwsDWSpP":
|
|
548
|
+
self.i = save
|
|
549
|
+
items.append(("ch", lo))
|
|
550
|
+
continue
|
|
551
|
+
hi = self.class_atom(items, want_char=True)
|
|
552
|
+
if hi is None or hi < lo:
|
|
553
|
+
raise Unsupported("bad range")
|
|
554
|
+
items.append(("range", lo, hi))
|
|
555
|
+
self.literals.update((lo, hi))
|
|
556
|
+
else:
|
|
557
|
+
items.append(("ch", lo))
|
|
558
|
+
self.literals.add(lo)
|
|
559
|
+
return self.cset(items, negated)
|
|
560
|
+
|
|
561
|
+
def class_atom(self, items, want_char=False) -> str | None:
|
|
562
|
+
c = self.peek()
|
|
563
|
+
self.i += 1
|
|
564
|
+
if c != "\\":
|
|
565
|
+
return c
|
|
566
|
+
e = self.peek()
|
|
567
|
+
self.i += 1
|
|
568
|
+
if e in "dwsDWS" and not want_char:
|
|
569
|
+
items.append(("cls", e.lower(), e.isupper()))
|
|
570
|
+
return None
|
|
571
|
+
if e in "pP" and self.flavor != "python" and not want_char:
|
|
572
|
+
items.append(("cls", "p:" + self.prop(), e == "P"))
|
|
573
|
+
return None
|
|
574
|
+
if e == "b":
|
|
575
|
+
return "\b"
|
|
576
|
+
return self.char_escape(e)
|
|
577
|
+
|
|
578
|
+
|
|
579
|
+
DEFAULT_FLAGS = {"i": False, "m": False, "s": False, "x": False, "a": False}
|
|
580
|
+
|
|
581
|
+
|
|
582
|
+
def parse(pattern: str, flavor: str = "python", flags: str | dict = "") -> Parsed:
|
|
583
|
+
"""The tree of a pattern in a flavor. `flags`: letters (`ims x` and `a` for ASCII) or a dict; Raises Unsupported."""
|
|
584
|
+
if flavor not in FLAVORS:
|
|
585
|
+
raise Unsupported(f"flavor {flavor}")
|
|
586
|
+
fl = dict(DEFAULT_FLAGS)
|
|
587
|
+
if isinstance(flags, dict):
|
|
588
|
+
fl.update(flags)
|
|
589
|
+
else:
|
|
590
|
+
for ch in str(flags or ""):
|
|
591
|
+
if ch in fl:
|
|
592
|
+
fl[ch] = True
|
|
593
|
+
if flavor in ("js", "java", "go"):
|
|
594
|
+
fl["a"] = True if flavor != "js" or not fl.get("u_classes") else fl["a"]
|
|
595
|
+
p = _Parser(pattern, flavor, fl)
|
|
596
|
+
root = p.parse()
|
|
597
|
+
# a leading global inline flag group changes the parse of what follows (handled), and the flags a site reports
|
|
598
|
+
universe = tuple(dict.fromkeys(BASE_UNIVERSE + tuple(sorted(c for c in p.literals if len(c) == 1))))
|
|
599
|
+
return Parsed(pattern, flavor, root, p.groups, p.flags, universe)
|
|
600
|
+
|
|
601
|
+
|
|
602
|
+
# --- facts about nodes ---------------------------------------------------------------------------------------------------
|
|
603
|
+
|
|
604
|
+
class Facts:
|
|
605
|
+
"""nullable, first and last char sets, every char that can be in a match, a shortest sample: memoised per node."""
|
|
606
|
+
|
|
607
|
+
def __init__(self, parsed: Parsed):
|
|
608
|
+
self.p = parsed
|
|
609
|
+
self.u = parsed.universe
|
|
610
|
+
self._null: dict[int, bool] = {}
|
|
611
|
+
self._first: dict[int, frozenset] = {}
|
|
612
|
+
self._last: dict[int, frozenset] = {}
|
|
613
|
+
self._chars: dict[int, frozenset] = {}
|
|
614
|
+
self._sample: dict[int, str] = {}
|
|
615
|
+
|
|
616
|
+
def nullable(self, n: Node) -> bool:
|
|
617
|
+
k = id(n)
|
|
618
|
+
if k not in self._null:
|
|
619
|
+
if n.kind == "char":
|
|
620
|
+
v = False
|
|
621
|
+
elif n.kind == "seq":
|
|
622
|
+
v = all(self.nullable(x) for x in n.items)
|
|
623
|
+
elif n.kind == "alt":
|
|
624
|
+
v = any(self.nullable(x) for x in n.items)
|
|
625
|
+
elif n.kind == "rep":
|
|
626
|
+
v = n.lo == 0 or self.nullable(n.item)
|
|
627
|
+
elif n.kind == "group":
|
|
628
|
+
v = self.nullable(n.item)
|
|
629
|
+
else:
|
|
630
|
+
v = True # anchors, lookarounds, backrefs (may be empty), empty
|
|
631
|
+
self._null[k] = v
|
|
632
|
+
return self._null[k]
|
|
633
|
+
|
|
634
|
+
def first(self, n: Node) -> frozenset:
|
|
635
|
+
k = id(n)
|
|
636
|
+
if k not in self._first:
|
|
637
|
+
if n.kind == "char":
|
|
638
|
+
v = n.cs.chars(self.u)
|
|
639
|
+
elif n.kind == "seq":
|
|
640
|
+
acc = set()
|
|
641
|
+
for x in n.items:
|
|
642
|
+
acc |= self.first(x)
|
|
643
|
+
if not self.nullable(x):
|
|
644
|
+
break
|
|
645
|
+
v = frozenset(acc)
|
|
646
|
+
elif n.kind == "alt":
|
|
647
|
+
v = frozenset().union(*(self.first(x) for x in n.items))
|
|
648
|
+
elif n.kind in ("rep", "group"):
|
|
649
|
+
v = self.first(n.item) if not (n.kind == "rep" and n.hi == 0) else frozenset()
|
|
650
|
+
else:
|
|
651
|
+
v = frozenset()
|
|
652
|
+
self._first[k] = v
|
|
653
|
+
return self._first[k]
|
|
654
|
+
|
|
655
|
+
def last(self, n: Node) -> frozenset:
|
|
656
|
+
k = id(n)
|
|
657
|
+
if k not in self._last:
|
|
658
|
+
if n.kind == "char":
|
|
659
|
+
v = n.cs.chars(self.u)
|
|
660
|
+
elif n.kind == "seq":
|
|
661
|
+
acc = set()
|
|
662
|
+
for x in reversed(n.items):
|
|
663
|
+
acc |= self.last(x)
|
|
664
|
+
if not self.nullable(x):
|
|
665
|
+
break
|
|
666
|
+
v = frozenset(acc)
|
|
667
|
+
elif n.kind == "alt":
|
|
668
|
+
v = frozenset().union(*(self.last(x) for x in n.items))
|
|
669
|
+
elif n.kind in ("rep", "group"):
|
|
670
|
+
v = self.last(n.item)
|
|
671
|
+
else:
|
|
672
|
+
v = frozenset()
|
|
673
|
+
self._last[k] = v
|
|
674
|
+
return self._last[k]
|
|
675
|
+
|
|
676
|
+
def chars(self, n: Node) -> frozenset:
|
|
677
|
+
k = id(n)
|
|
678
|
+
if k not in self._chars:
|
|
679
|
+
if n.kind == "char":
|
|
680
|
+
v = n.cs.chars(self.u)
|
|
681
|
+
elif n.kind in ("seq", "alt"):
|
|
682
|
+
v = frozenset().union(*(self.chars(x) for x in n.items)) if n.items else frozenset()
|
|
683
|
+
elif n.kind in ("rep", "group"):
|
|
684
|
+
v = self.chars(n.item)
|
|
685
|
+
else:
|
|
686
|
+
v = frozenset()
|
|
687
|
+
self._chars[k] = v
|
|
688
|
+
return self._chars[k]
|
|
689
|
+
|
|
690
|
+
def sample(self, n: Node) -> str:
|
|
691
|
+
"""A short string the node matches (lookarounds and anchors give ''); for building attack prefixes."""
|
|
692
|
+
k = id(n)
|
|
693
|
+
if k not in self._sample:
|
|
694
|
+
if n.kind == "char":
|
|
695
|
+
v = pick(n.cs.chars(self.u))
|
|
696
|
+
elif n.kind == "seq":
|
|
697
|
+
v = "".join(self.sample(x) for x in n.items)
|
|
698
|
+
elif n.kind == "alt":
|
|
699
|
+
opts = [self.sample(x) for x in n.items]
|
|
700
|
+
v = min(opts, key=len) if opts else ""
|
|
701
|
+
elif n.kind == "rep":
|
|
702
|
+
v = self.sample(n.item) * n.lo if n.lo <= 64 else self.sample(n.item) * 64
|
|
703
|
+
elif n.kind == "group":
|
|
704
|
+
v = self.sample(n.item)
|
|
705
|
+
else:
|
|
706
|
+
v = ""
|
|
707
|
+
self._sample[k] = v
|
|
708
|
+
return self._sample[k]
|
|
709
|
+
|
|
710
|
+
|
|
711
|
+
# printable picks first: a pump of letters is easier to read in a report than a pump of control characters
|
|
712
|
+
_PREFER = "a1 _-.,:;/\\\"'@#()[]{}<>=+*&%$!?|~^`\t\n" + "".join(chr(i) for i in range(32, 127)) + "éλ中"
|
|
713
|
+
|
|
714
|
+
|
|
715
|
+
def pick(chars, avoid: str = "") -> str:
|
|
716
|
+
for c in _PREFER:
|
|
717
|
+
if c in chars and c not in avoid:
|
|
718
|
+
return c
|
|
719
|
+
rest = sorted(c for c in chars if c not in avoid)
|
|
720
|
+
return rest[0] if rest else ""
|
|
721
|
+
|
|
722
|
+
|
|
723
|
+
# --- the static check: super-linear structure -----------------------------------------------------------------------------
|
|
724
|
+
|
|
725
|
+
@dataclass
|
|
726
|
+
class Issue:
|
|
727
|
+
code: str # nested_quantifier, overlapping_alternation, adjacent_overlap, search_restart, unicode_boundary
|
|
728
|
+
growth: str # exponential | polynomial | constant (the expected shape)
|
|
729
|
+
span: tuple # the repeat (or `\b`) in the pattern text
|
|
730
|
+
families: list = field(default_factory=list) # [{name, prefix, pump, suffix}]
|
|
731
|
+
note: str = ""
|
|
732
|
+
|
|
733
|
+
|
|
734
|
+
UNANCHORED_APIS = {"search", "findall", "finditer", "sub", "subn", "split", "find", "find_iter", "replace", "replace_all",
|
|
735
|
+
"replaceAll", "replaceFirst", "test", "exec", "match_all", "matchAll", "is_match", "captures",
|
|
736
|
+
"captures_iter", "FindString", "FindAllString", "FindStringSubmatch", "FindAllStringSubmatch",
|
|
737
|
+
"MatchString", "ReplaceAllString", "Split", "Matcher.find", "literal", "compile", "new", "Pattern.compile"}
|
|
738
|
+
ANCHORED_APIS = {"match"} # Python re.match: anchored at the start, not the end
|
|
739
|
+
FULL_APIS = {"fullmatch", "matches", "String.matches"}
|
|
740
|
+
|
|
741
|
+
|
|
742
|
+
def _fail_chars(avoid: frozenset, universe) -> list[str]:
|
|
743
|
+
out = []
|
|
744
|
+
for c in "!\x00 \n@é#1a_.":
|
|
745
|
+
if c not in avoid and c not in out:
|
|
746
|
+
out.append(c)
|
|
747
|
+
if len(out) >= 3:
|
|
748
|
+
break
|
|
749
|
+
if not out:
|
|
750
|
+
for c in universe:
|
|
751
|
+
if c not in avoid:
|
|
752
|
+
out.append(c)
|
|
753
|
+
break
|
|
754
|
+
return out
|
|
755
|
+
|
|
756
|
+
|
|
757
|
+
def _paths(root: Node):
|
|
758
|
+
"""(node, prefix items, continuation items, inside a repeat) for every node: what must match before it in the
|
|
759
|
+
pattern, and what follows it. Alternation branches are walked one at a time."""
|
|
760
|
+
out = []
|
|
761
|
+
|
|
762
|
+
def go(n: Node, before: list, after: list, in_rep: bool):
|
|
763
|
+
out.append((n, before, after, in_rep))
|
|
764
|
+
if n.kind == "seq":
|
|
765
|
+
for i, x in enumerate(n.items):
|
|
766
|
+
go(x, before + n.items[:i], n.items[i + 1:] + after, in_rep)
|
|
767
|
+
elif n.kind == "alt":
|
|
768
|
+
for x in n.items:
|
|
769
|
+
go(x, before, after, in_rep)
|
|
770
|
+
elif n.kind == "group":
|
|
771
|
+
go(n.item, before, after, in_rep)
|
|
772
|
+
elif n.kind == "rep":
|
|
773
|
+
go(n.item, before, after, True)
|
|
774
|
+
elif n.kind == "look":
|
|
775
|
+
go(n.item, [], [], in_rep)
|
|
776
|
+
go(root, [], [], False)
|
|
777
|
+
return out
|
|
778
|
+
|
|
779
|
+
|
|
780
|
+
def _seq_items(n: Node) -> list:
|
|
781
|
+
while n.kind == "group" and not n.atomic:
|
|
782
|
+
n = n.item
|
|
783
|
+
return n.items if n.kind == "seq" else [n]
|
|
784
|
+
|
|
785
|
+
|
|
786
|
+
def _alt_items(n: Node) -> list:
|
|
787
|
+
while n.kind == "group" and not n.atomic:
|
|
788
|
+
n = n.item
|
|
789
|
+
return n.items if n.kind == "alt" else []
|
|
790
|
+
|
|
791
|
+
|
|
792
|
+
def analyse(parsed: Parsed, api: str = "search", *, max_families: int = 8) -> list[Issue]:
|
|
793
|
+
"""The repeats that can backtrack super-linearly on a backtracking engine (Python, JavaScript, Java), each with
|
|
794
|
+
attack families to measure. On Go and Rust (linear engines) only `unicode_boundary` is reported here; their other
|
|
795
|
+
costs (compile per call, a scan that runs to the end per match) are call-site facts, not pattern facts."""
|
|
796
|
+
f = Facts(parsed)
|
|
797
|
+
U = parsed.universe
|
|
798
|
+
issues: list[Issue] = []
|
|
799
|
+
full = api in FULL_APIS
|
|
800
|
+
anchored_start = api in ANCHORED_APIS or full
|
|
801
|
+
root_items = _seq_items(parsed.root)
|
|
802
|
+
if root_items and root_items[0].kind == "anchor" and root_items[0].name == "start":
|
|
803
|
+
anchored_start = True
|
|
804
|
+
|
|
805
|
+
def seq_sample(items) -> str:
|
|
806
|
+
return "".join(f.sample(x) for x in items)
|
|
807
|
+
|
|
808
|
+
def must_fail(cont: list) -> bool:
|
|
809
|
+
"""Whether what follows can fail (a non-empty requirement, an end anchor, or a full match)."""
|
|
810
|
+
if full:
|
|
811
|
+
return True
|
|
812
|
+
for x in cont:
|
|
813
|
+
if x.kind == "anchor" and x.name in ("end", "endnl", "eol", "wordb", "nwordb"):
|
|
814
|
+
return True
|
|
815
|
+
if x.kind == "look" or x.kind == "backref":
|
|
816
|
+
return True
|
|
817
|
+
if not f.nullable(x):
|
|
818
|
+
return True
|
|
819
|
+
return False
|
|
820
|
+
|
|
821
|
+
def cont_first(cont: list) -> frozenset:
|
|
822
|
+
acc = set()
|
|
823
|
+
for x in cont:
|
|
824
|
+
acc |= f.first(x)
|
|
825
|
+
if not f.nullable(x):
|
|
826
|
+
break
|
|
827
|
+
return frozenset(acc)
|
|
828
|
+
|
|
829
|
+
def families(prefix: str, pumps: list[str], avoid: frozenset, cont: list) -> list[dict]:
|
|
830
|
+
out = []
|
|
831
|
+
fails = _fail_chars(avoid | cont_first(cont), U)
|
|
832
|
+
if not full and not any(not f.nullable(x) for x in cont) and "" not in fails:
|
|
833
|
+
fails = fails[:2]
|
|
834
|
+
for pump in dict.fromkeys(p for p in pumps if p):
|
|
835
|
+
for sfx in fails[:2] + ([""] if not full else []):
|
|
836
|
+
out.append({"prefix": prefix, "pump": pump, "suffix": sfx})
|
|
837
|
+
return out[:max_families]
|
|
838
|
+
|
|
839
|
+
if parsed.flavor in ("python", "js", "java"):
|
|
840
|
+
for n, before, after, in_rep in _paths(parsed.root):
|
|
841
|
+
if n.kind != "rep" or n.possessive or n.hi is not None and n.hi < 16:
|
|
842
|
+
continue
|
|
843
|
+
body = n.item
|
|
844
|
+
if body.kind == "group" and body.atomic:
|
|
845
|
+
continue
|
|
846
|
+
pre = seq_sample(before)
|
|
847
|
+
# 1. ambiguous iterations: the end of one iteration can take the start of the next (nested repeat)
|
|
848
|
+
items = _seq_items(body)
|
|
849
|
+
for idx, s in enumerate(items):
|
|
850
|
+
if s.kind != "rep" or s.hi is not None and s.hi < 16 or s.possessive:
|
|
851
|
+
continue
|
|
852
|
+
head, tail = items[:idx], items[idx + 1:]
|
|
853
|
+
inner = f.chars(s.item)
|
|
854
|
+
shared = set()
|
|
855
|
+
if all(f.nullable(x) for x in tail):
|
|
856
|
+
shared |= f.first(body) & inner
|
|
857
|
+
if all(f.nullable(x) for x in head):
|
|
858
|
+
shared |= f.last(body) & inner
|
|
859
|
+
if shared and must_fail(after):
|
|
860
|
+
c = pick(shared)
|
|
861
|
+
it = seq_sample(items[:idx]) + c + seq_sample(items[idx + 1:])
|
|
862
|
+
issues.append(Issue("nested_quantifier", "exponential", n.span,
|
|
863
|
+
families(pre, [c, it, c * 2], frozenset(inner) | f.chars(body), after),
|
|
864
|
+
f"{parsed.pattern[s.span[0]:s.span[1]]} inside {parsed.pattern[n.qspan[0]:n.qspan[1]]}"))
|
|
865
|
+
break
|
|
866
|
+
# 2. overlapping alternation under the repeat
|
|
867
|
+
alts = _alt_items(body)
|
|
868
|
+
done = False
|
|
869
|
+
for i in range(len(alts)):
|
|
870
|
+
for j in range(i + 1, len(alts)):
|
|
871
|
+
both = f.first(alts[i]) & f.first(alts[j])
|
|
872
|
+
if both and must_fail(after) and not done:
|
|
873
|
+
c = pick(both)
|
|
874
|
+
si, sj = f.sample(alts[i]), f.sample(alts[j])
|
|
875
|
+
pumps = [c, c * 2] + [s for s in (si, sj) if s and s[0] == c] + [si + sj]
|
|
876
|
+
issues.append(Issue("overlapping_alternation", "exponential", n.span,
|
|
877
|
+
families(pre, pumps, f.chars(body), after),
|
|
878
|
+
f"branches {i + 1} and {j + 1} can both start with {c!r}"))
|
|
879
|
+
done = True
|
|
880
|
+
# 3. two repeats side by side inside the body that can trade characters
|
|
881
|
+
for a_i in range(len(items)):
|
|
882
|
+
a = items[a_i]
|
|
883
|
+
if a.kind != "rep" or a.hi is not None and a.hi < 16 or a.possessive:
|
|
884
|
+
continue
|
|
885
|
+
for b_i in range(a_i + 1, len(items)):
|
|
886
|
+
b = items[b_i]
|
|
887
|
+
if b.kind == "rep" and (b.hi is None or b.hi >= 16) and not b.possessive and all(f.nullable(x) for x in items[a_i + 1:b_i]):
|
|
888
|
+
shared = f.chars(a.item) & f.chars(b.item)
|
|
889
|
+
if shared and must_fail(after):
|
|
890
|
+
c = pick(shared)
|
|
891
|
+
issues.append(Issue("nested_quantifier", "exponential", n.span,
|
|
892
|
+
families(pre, [c, c * 2], f.chars(body), after),
|
|
893
|
+
"two repeats side by side inside a repeat"))
|
|
894
|
+
break
|
|
895
|
+
if not f.nullable(b):
|
|
896
|
+
break
|
|
897
|
+
|
|
898
|
+
# 4. adjacent repeats outside a repeat that trade characters: polynomial
|
|
899
|
+
for n, before, after, in_rep in _paths(parsed.root):
|
|
900
|
+
if n.kind != "seq" or in_rep:
|
|
901
|
+
continue
|
|
902
|
+
items = n.items
|
|
903
|
+
for a_i, a in enumerate(items):
|
|
904
|
+
if a.kind != "rep" or a.hi is not None and a.hi < 16 or a.possessive:
|
|
905
|
+
continue
|
|
906
|
+
for b_i in range(a_i + 1, len(items)):
|
|
907
|
+
b = items[b_i]
|
|
908
|
+
if b.kind == "rep" and (b.hi is None or b.hi >= 16) and not b.possessive:
|
|
909
|
+
shared = f.chars(a.item) & f.chars(b.item)
|
|
910
|
+
cont = items[b_i + 1:] + after
|
|
911
|
+
if shared and must_fail(cont):
|
|
912
|
+
c = pick(shared)
|
|
913
|
+
issues.append(Issue("adjacent_overlap", "polynomial", a.span,
|
|
914
|
+
families(seq_sample(before + items[:a_i]), [c], f.chars(a.item) | f.chars(b.item), cont),
|
|
915
|
+
f"{parsed.pattern[a.span[0]:a.span[1]]} then {parsed.pattern[b.span[0]:b.span[1]]}"))
|
|
916
|
+
break
|
|
917
|
+
if not f.nullable(b):
|
|
918
|
+
break
|
|
919
|
+
|
|
920
|
+
# 5. an unanchored search restarts at every position: a repeat reached from the start that runs over the text
|
|
921
|
+
if not anchored_start:
|
|
922
|
+
for idx, r in enumerate(root_items):
|
|
923
|
+
if r.kind == "rep" and (r.hi is None or r.hi >= 16) and not r.possessive:
|
|
924
|
+
cont = root_items[idx + 1:]
|
|
925
|
+
inner = f.chars(r.item)
|
|
926
|
+
pre_items = root_items[:idx]
|
|
927
|
+
pre = seq_sample(pre_items)
|
|
928
|
+
if not inner or not must_fail(cont):
|
|
929
|
+
break
|
|
930
|
+
pumps = []
|
|
931
|
+
if not pre and (f.first(parsed.root) & inner):
|
|
932
|
+
pumps.append(pick(f.first(parsed.root) & inner))
|
|
933
|
+
elif pre and all(ch in inner for ch in pre):
|
|
934
|
+
pumps.append(pre)
|
|
935
|
+
elif pre:
|
|
936
|
+
c = pick(inner)
|
|
937
|
+
if c:
|
|
938
|
+
pumps.append(pre + c)
|
|
939
|
+
if pumps:
|
|
940
|
+
issues.append(Issue("search_restart", "polynomial", r.span,
|
|
941
|
+
families("", pumps, inner, cont),
|
|
942
|
+
"an unanchored search tries every start position and this repeat runs to the end each time"))
|
|
943
|
+
break
|
|
944
|
+
if r.kind != "anchor" and not f.nullable(r) and r.kind != "char":
|
|
945
|
+
break
|
|
946
|
+
if r.kind == "anchor":
|
|
947
|
+
continue
|
|
948
|
+
|
|
949
|
+
if parsed.flavor == "rust" and not parsed.flags.get("a"):
|
|
950
|
+
spans = [n.span for n in parsed.walk() if n.kind == "anchor" and n.name in ("wordb", "nwordb") and not _ascii_at(parsed, n)]
|
|
951
|
+
if spans:
|
|
952
|
+
issues.append(Issue("unicode_boundary", "constant", spans[0], [], f"{len(spans)} Unicode word boundar{'y' if len(spans) == 1 else 'ies'}"))
|
|
953
|
+
return _dedupe(issues)
|
|
954
|
+
|
|
955
|
+
|
|
956
|
+
def _ascii_at(parsed: Parsed, n: Node) -> bool:
|
|
957
|
+
"""Whether a `\\b` sits in an ASCII scope already ((?-u:\\b) or (?-u) before it)."""
|
|
958
|
+
text = parsed.pattern[:n.span[0]]
|
|
959
|
+
return text.endswith("(?-u:") or "(?-u)" in text
|
|
960
|
+
|
|
961
|
+
|
|
962
|
+
def _dedupe(issues: list[Issue]) -> list[Issue]:
|
|
963
|
+
seen, out = set(), []
|
|
964
|
+
for i in issues:
|
|
965
|
+
key = (i.code, i.span)
|
|
966
|
+
if key not in seen:
|
|
967
|
+
seen.add(key)
|
|
968
|
+
out.append(i)
|
|
969
|
+
return out
|
|
970
|
+
|
|
971
|
+
|
|
972
|
+
def attack(fam: dict, n: int) -> str:
|
|
973
|
+
return fam["prefix"] + fam["pump"] * n + fam["suffix"]
|
|
974
|
+
|
|
975
|
+
|
|
976
|
+
# --- strings a pattern matches: the corpus ---------------------------------------------------------------------------------
|
|
977
|
+
|
|
978
|
+
def generate(parsed: Parsed, rng: random.Random, max_rep: int = 4, budget: int = 400) -> str:
|
|
979
|
+
"""One random string the pattern is likely to match (lookarounds and backreferences are not honoured: the corpus
|
|
980
|
+
check does not need every string to match, it needs both patterns to see the same strings)."""
|
|
981
|
+
U = parsed.universe
|
|
982
|
+
groups: dict[str, str] = {}
|
|
983
|
+
|
|
984
|
+
def gen(n: Node, depth: int) -> str:
|
|
985
|
+
if depth > 40:
|
|
986
|
+
return ""
|
|
987
|
+
if n.kind == "char":
|
|
988
|
+
chars = sorted(n.cs.chars(U))
|
|
989
|
+
if not chars:
|
|
990
|
+
return ""
|
|
991
|
+
if rng.random() < 0.7:
|
|
992
|
+
ascii_ = [c for c in chars if c.isascii() and c.isprintable()]
|
|
993
|
+
if ascii_:
|
|
994
|
+
return rng.choice(ascii_)
|
|
995
|
+
return rng.choice(chars)
|
|
996
|
+
if n.kind == "seq":
|
|
997
|
+
return "".join(gen(x, depth + 1) for x in n.items)
|
|
998
|
+
if n.kind == "alt":
|
|
999
|
+
return gen(rng.choice(n.items), depth + 1) if n.items else ""
|
|
1000
|
+
if n.kind == "rep":
|
|
1001
|
+
hi = n.hi if n.hi is not None else n.lo + max_rep
|
|
1002
|
+
k = rng.randint(n.lo, max(n.lo, min(hi, n.lo + max_rep)))
|
|
1003
|
+
return "".join(gen(n.item, depth + 1) for _ in range(k))
|
|
1004
|
+
if n.kind == "group":
|
|
1005
|
+
s = gen(n.item, depth + 1)
|
|
1006
|
+
if n.cap:
|
|
1007
|
+
groups[str(n.cap)] = s
|
|
1008
|
+
if n.name:
|
|
1009
|
+
groups[n.name] = s
|
|
1010
|
+
return s
|
|
1011
|
+
if n.kind == "backref":
|
|
1012
|
+
return groups.get(n.name, "")
|
|
1013
|
+
return ""
|
|
1014
|
+
s = gen(parsed.root, 0)
|
|
1015
|
+
return s[:budget]
|
|
1016
|
+
|
|
1017
|
+
|
|
1018
|
+
def corpus(parsed: Parsed, rng: random.Random, size: int, *, extra: list[str] | None = None, families: list[dict] | None = None,
|
|
1019
|
+
also: Parsed | None = None) -> list[str]:
|
|
1020
|
+
"""Strings to compare two patterns on: members of each pattern, their mutations (one character dropped, inserted,
|
|
1021
|
+
replaced, a sample appended), small attack strings, single characters, the empty string, and `extra` (strings from
|
|
1022
|
+
the repository's tests). Deterministic for a seed."""
|
|
1023
|
+
out: dict[str, None] = {"": None}
|
|
1024
|
+
pos = []
|
|
1025
|
+
for src in [parsed] + ([also] if also else []):
|
|
1026
|
+
for _ in range(max(4, size // 6)):
|
|
1027
|
+
s = generate(src, rng)
|
|
1028
|
+
pos.append(s)
|
|
1029
|
+
out[s] = None
|
|
1030
|
+
for fam in families or []:
|
|
1031
|
+
for n in (0, 1, 2, 3, 5, 8, 13):
|
|
1032
|
+
out[attack(fam, n)[:400]] = None
|
|
1033
|
+
for s in extra or []:
|
|
1034
|
+
if isinstance(s, str) and len(s) <= 400:
|
|
1035
|
+
out[s] = None
|
|
1036
|
+
alpha = sorted(set("".join(pos)) | set(" \t\na0Z_-.:/@#()[]{}\"'<>=,;é\\") | {c for c in parsed.universe if c.isprintable()} & set("abcxyz019"))
|
|
1037
|
+
base = list(out)
|
|
1038
|
+
for c in alpha:
|
|
1039
|
+
out[c] = None
|
|
1040
|
+
while len(out) < size and base:
|
|
1041
|
+
s = list(rng.choice(base))
|
|
1042
|
+
k = rng.randint(0, 4)
|
|
1043
|
+
if k == 0 and s:
|
|
1044
|
+
del s[rng.randrange(len(s))]
|
|
1045
|
+
elif k == 1:
|
|
1046
|
+
s.insert(rng.randint(0, len(s)), rng.choice(alpha))
|
|
1047
|
+
elif k == 2 and s:
|
|
1048
|
+
s[rng.randrange(len(s))] = rng.choice(alpha)
|
|
1049
|
+
elif k == 3:
|
|
1050
|
+
s += list(rng.choice(base))
|
|
1051
|
+
else:
|
|
1052
|
+
s = list(rng.choice(alpha) * rng.randint(1, 6)) + s
|
|
1053
|
+
out["".join(s)[:400]] = None
|
|
1054
|
+
if rng.random() < 0.02:
|
|
1055
|
+
base = list(out)
|
|
1056
|
+
return list(out)[:max(size, len(base))]
|
|
1057
|
+
|
|
1058
|
+
|
|
1059
|
+
# --- rule-made rewrites -------------------------------------------------------------------------------------------------------
|
|
1060
|
+
|
|
1061
|
+
@dataclass
|
|
1062
|
+
class Rewrite:
|
|
1063
|
+
change: str # possessive_quantifier, lookbehind_guard, disjoint_branch, ascii_word_boundary
|
|
1064
|
+
pattern: str
|
|
1065
|
+
note: str = ""
|
|
1066
|
+
|
|
1067
|
+
|
|
1068
|
+
def supports(flavor: str, feature: str, python_version: tuple = (3, 11)) -> bool:
|
|
1069
|
+
if feature == "possessive":
|
|
1070
|
+
return flavor == "java" or flavor == "python" and python_version >= (3, 11)
|
|
1071
|
+
if feature == "lookbehind":
|
|
1072
|
+
return flavor in ("python", "java", "js")
|
|
1073
|
+
return False
|
|
1074
|
+
|
|
1075
|
+
|
|
1076
|
+
def rewrites(parsed: Parsed, issue: Issue, *, python_version: tuple = (3, 11)) -> list[Rewrite]:
|
|
1077
|
+
"""Mechanical rewrites for one issue, most targeted first. Each is a candidate only: it is fixed only after the
|
|
1078
|
+
same-matches check and the growth curve on the engine."""
|
|
1079
|
+
p = parsed.pattern
|
|
1080
|
+
out: list[Rewrite] = []
|
|
1081
|
+
reps = [n for n in parsed.walk() if n.kind == "rep"]
|
|
1082
|
+
target = next((n for n in reps if n.span == issue.span), None)
|
|
1083
|
+
|
|
1084
|
+
def poss(nodes) -> str:
|
|
1085
|
+
s = p
|
|
1086
|
+
for n in sorted(nodes, key=lambda x: -x.qspan[1]):
|
|
1087
|
+
if n.possessive or not n.greedy:
|
|
1088
|
+
continue
|
|
1089
|
+
s = s[:n.qspan[1]] + "+" + s[n.qspan[1]:]
|
|
1090
|
+
return s
|
|
1091
|
+
|
|
1092
|
+
if issue.code == "unicode_boundary":
|
|
1093
|
+
s = p
|
|
1094
|
+
for n in sorted((x for x in parsed.walk() if x.kind == "anchor" and x.name in ("wordb", "nwordb") and not _ascii_at(parsed, x)),
|
|
1095
|
+
key=lambda x: -x.span[0]):
|
|
1096
|
+
s = s[:n.span[0]] + "(?-u:" + p[n.span[0]:n.span[1]] + ")" + s[n.span[1]:]
|
|
1097
|
+
return [Rewrite("ascii_word_boundary", s, "an ASCII word boundary: the fast automaton keeps going past non-ASCII bytes")]
|
|
1098
|
+
|
|
1099
|
+
if supports(parsed.flavor, "possessive", python_version) and target is not None:
|
|
1100
|
+
unbounded = [n for n in walk(target) if n.kind == "rep" and n.greedy and not n.possessive and (n.hi is None or n.hi >= 16)]
|
|
1101
|
+
inner = [n for n in unbounded if n is not target]
|
|
1102
|
+
if target.greedy:
|
|
1103
|
+
out.append(Rewrite("possessive_quantifier", poss([target]), "the repeat gives nothing back"))
|
|
1104
|
+
for n in inner[:4]:
|
|
1105
|
+
out.append(Rewrite("possessive_quantifier", poss([n]), "the inner repeat gives nothing back"))
|
|
1106
|
+
if len(unbounded) > 1:
|
|
1107
|
+
out.append(Rewrite("possessive_quantifier", poss(unbounded), "every repeat here gives nothing back"))
|
|
1108
|
+
allreps = [n for n in reps if n.greedy and not n.possessive and (n.hi is None or n.hi >= 16)]
|
|
1109
|
+
if len(allreps) > len(unbounded):
|
|
1110
|
+
out.append(Rewrite("possessive_quantifier", poss(allreps), "every repeat of the pattern gives nothing back"))
|
|
1111
|
+
|
|
1112
|
+
items0 = _seq_items(parsed.root)
|
|
1113
|
+
if issue.code == "search_restart" and target is not None and supports(parsed.flavor, "lookbehind") and target.item.kind == "char" \
|
|
1114
|
+
and items0 and items0[0] is target:
|
|
1115
|
+
cls = p[target.item.span[0]:target.item.span[1]]
|
|
1116
|
+
out.append(Rewrite("lookbehind_guard", p[:target.span[0]] + f"(?<!{cls})" + p[target.span[0]:],
|
|
1117
|
+
"a match cannot start in the middle of a run"))
|
|
1118
|
+
if supports(parsed.flavor, "possessive", python_version) and target.greedy:
|
|
1119
|
+
out.append(Rewrite("lookbehind_guard", p[:target.span[0]] + f"(?<!{cls})" + poss([target])[target.span[0]:],
|
|
1120
|
+
"a match cannot start in the middle of a run, and the run gives nothing back"))
|
|
1121
|
+
elif issue.code == "search_restart" and target is not None and supports(parsed.flavor, "lookbehind") and len(items0) > 1 \
|
|
1122
|
+
and items0[1] is target and items0[0].kind == "char" and target.item.kind == "char":
|
|
1123
|
+
# X[Y]* with X inside Y: a match starting after an X would have started one earlier
|
|
1124
|
+
f = Facts(parsed)
|
|
1125
|
+
if f.chars(items0[0]) <= f.chars(target.item):
|
|
1126
|
+
cls = p[items0[0].span[0]:items0[0].span[1]]
|
|
1127
|
+
out.append(Rewrite("lookbehind_guard", f"(?<!{cls})" + p, "a match cannot start in the middle of a run"))
|
|
1128
|
+
|
|
1129
|
+
if issue.code == "overlapping_alternation" and target is not None:
|
|
1130
|
+
alts = _alt_items(target.item)
|
|
1131
|
+
f = Facts(parsed)
|
|
1132
|
+
for a in alts:
|
|
1133
|
+
if a.kind == "char" and a.cs.negated and p[a.span[0]:a.span[1]].startswith("[^"):
|
|
1134
|
+
others = frozenset().union(*(f.first(x) for x in alts if x is not a))
|
|
1135
|
+
clash = sorted(others & a.cs.chars(parsed.universe))
|
|
1136
|
+
if clash and len(clash) <= 4:
|
|
1137
|
+
add = "".join("\\" + c if not c.isalnum() else c for c in clash)
|
|
1138
|
+
text = p[a.span[0]:a.span[1]]
|
|
1139
|
+
out.append(Rewrite("disjoint_branch", p[:a.span[0]] + text[:-1] + add + "]" + p[a.span[1]:],
|
|
1140
|
+
"the branches no longer start with the same character"))
|
|
1141
|
+
seen, uniq = {p}, []
|
|
1142
|
+
for r in out:
|
|
1143
|
+
if r.pattern not in seen:
|
|
1144
|
+
seen.add(r.pattern)
|
|
1145
|
+
uniq.append(r)
|
|
1146
|
+
return uniq
|
|
1147
|
+
|
|
1148
|
+
|
|
1149
|
+
def scan_families(parsed: Parsed, max_families: int = 4) -> list[dict]:
|
|
1150
|
+
"""Inputs for a scan that counts every match on a linear engine: lines that open a long branch (a prefix, then a
|
|
1151
|
+
character of its unbounded repeat, never the character that closes it) next to a short match of another branch. Each
|
|
1152
|
+
match then makes the engine look to the end of the text for the long one; a bounded count stops early."""
|
|
1153
|
+
f = Facts(parsed)
|
|
1154
|
+
U = parsed.universe
|
|
1155
|
+
branches = _alt_items(parsed.root) or [parsed.root]
|
|
1156
|
+
shortest = sorted((f.sample(b) for b in branches if f.sample(b)), key=len)
|
|
1157
|
+
out = []
|
|
1158
|
+
for b in branches:
|
|
1159
|
+
items = _seq_items(b)
|
|
1160
|
+
for i, r in enumerate(items):
|
|
1161
|
+
if r.kind == "rep" and r.hi is None:
|
|
1162
|
+
inner = f.chars(r.item)
|
|
1163
|
+
closers = frozenset().union(*(f.first(x) for x in items[i + 1:])) if items[i + 1:] else frozenset()
|
|
1164
|
+
c = pick(inner - closers - {"\n"}) or pick(inner - closers)
|
|
1165
|
+
if not c:
|
|
1166
|
+
continue
|
|
1167
|
+
pre = "".join(f.sample(x) for x in items[:i])
|
|
1168
|
+
other = next((s for s in shortest if s != f.sample(b) and "\n" not in s), "")
|
|
1169
|
+
out.append({"prefix": "", "pump": pre + c + " " + other + "\n", "suffix": ""})
|
|
1170
|
+
break
|
|
1171
|
+
if len(out) >= max_families:
|
|
1172
|
+
break
|
|
1173
|
+
return out
|
|
1174
|
+
|
|
1175
|
+
|
|
1176
|
+
def typical_text(parsed_list: list[Parsed], rng: random.Random, size: int, tail: str = "") -> str:
|
|
1177
|
+
"""Text made of members of the patterns and plain ASCII words, about `size` characters, then `tail`."""
|
|
1178
|
+
words = "the of and to in is for on that with as it at by from this be or are an data value item user name list".split()
|
|
1179
|
+
parts, n = [], 0
|
|
1180
|
+
while n < size:
|
|
1181
|
+
if parsed_list and rng.random() < 0.3:
|
|
1182
|
+
s = generate(rng.choice(parsed_list), rng, max_rep=3, budget=60)
|
|
1183
|
+
s = "".join(ch for ch in s if ch.isascii())
|
|
1184
|
+
else:
|
|
1185
|
+
s = " ".join(rng.choice(words) for _ in range(rng.randint(3, 9)))
|
|
1186
|
+
s += rng.choice([" ", "\n", "; ", ". "])
|
|
1187
|
+
parts.append(s)
|
|
1188
|
+
n += len(s)
|
|
1189
|
+
return "".join(parts)[:size] + tail
|
|
1190
|
+
|
|
1191
|
+
|
|
1192
|
+
PROSE = ("the of and to in is for on that with as it at by from this be or are an was were has have had not but can will would "
|
|
1193
|
+
"should could may use used using data value item user name list file line code text time request response server client "
|
|
1194
|
+
"service error message report result model when then there their which what more some other into over about only also "
|
|
1195
|
+
"after first new work part number people way day year page section table field type default config update").split()
|
|
1196
|
+
CODE = ("def return if else for while import from self None True False { } ( ) [ ] = == : , . -> => # // /* */ \" ' 0 1 2 42 x i "
|
|
1197
|
+
"id url json http api get set let const var func fn int str len map err nil ok args kwargs log debug info").split()
|
|
1198
|
+
|
|
1199
|
+
|
|
1200
|
+
def ordinary_text(parsed_list: list[Parsed], rng: random.Random, size: int, plant_every: int = 4096, words: list[str] | None = None) -> str:
|
|
1201
|
+
"""Text a table of patterns usually runs on: prose and code-like lines (lower and capitalised words, punctuation, a
|
|
1202
|
+
few digits), with one string a pattern matches (or one of `words`) planted every `plant_every` characters, so matches
|
|
1203
|
+
exist without the text being made of them. Generated, never a customer's."""
|
|
1204
|
+
parts, n, nxt = [], 0, plant_every // 2
|
|
1205
|
+
while n < size:
|
|
1206
|
+
if plant_every > 0 and n >= nxt and (parsed_list or words):
|
|
1207
|
+
if words and (not parsed_list or rng.random() < 0.5):
|
|
1208
|
+
s = rng.choice(words)
|
|
1209
|
+
else:
|
|
1210
|
+
s = generate(rng.choice(parsed_list), rng, max_rep=3, budget=80)
|
|
1211
|
+
nxt += max(1, plant_every)
|
|
1212
|
+
elif rng.random() < 0.25:
|
|
1213
|
+
s = " ".join(rng.choice(CODE) for _ in range(rng.randint(3, 10)))
|
|
1214
|
+
else:
|
|
1215
|
+
w = [rng.choice(PROSE) for _ in range(rng.randint(4, 14))]
|
|
1216
|
+
w[0] = w[0].capitalize()
|
|
1217
|
+
s = " ".join(w)
|
|
1218
|
+
s += rng.choice([" ", "\n", ". ", ", ", ".\n"])
|
|
1219
|
+
parts.append(s)
|
|
1220
|
+
n += len(s)
|
|
1221
|
+
return "".join(parts)[:size]
|
|
1222
|
+
|
|
1223
|
+
|
|
1224
|
+
def required_literal(parsed: Parsed, min_len: int = 1) -> str:
|
|
1225
|
+
"""A literal every match must contain (the longest of the top-level sequence's literal runs), or ''."""
|
|
1226
|
+
if parsed.flags.get("i"):
|
|
1227
|
+
return ""
|
|
1228
|
+
best, run = "", ""
|
|
1229
|
+
for x in _seq_items(parsed.root):
|
|
1230
|
+
if x.kind == "char" and len(x.cs.items) == 1 and x.cs.items[0][0] == "ch" and not x.cs.negated and not x.cs.icase:
|
|
1231
|
+
run += x.cs.items[0][1]
|
|
1232
|
+
continue
|
|
1233
|
+
if len(run) > len(best):
|
|
1234
|
+
best = run
|
|
1235
|
+
run = ""
|
|
1236
|
+
if x.kind in ("anchor", "look"):
|
|
1237
|
+
continue
|
|
1238
|
+
if len(run) > len(best):
|
|
1239
|
+
best = run
|
|
1240
|
+
return best if len(best) >= min_len else ""
|
|
1241
|
+
|
|
1242
|
+
|
|
1243
|
+
# --- required literals: what every match must contain ---------------------------------------------------------------------
|
|
1244
|
+
|
|
1245
|
+
MAX_LITERALS = 64
|
|
1246
|
+
# the characters that match an ASCII letter under a case-insensitive flag without lower() giving that letter (asked of
|
|
1247
|
+
# CPython over every code point): fold them first, then lower(), and an `in` test on the folded text is exact
|
|
1248
|
+
FOLD_EXTRA = (("\u0130", "i"), ("\u0131", "i"), ("\u017f", "s"), ("\u212a", "k"))
|
|
1249
|
+
|
|
1250
|
+
|
|
1251
|
+
def fold(text: str) -> str:
|
|
1252
|
+
"""The text a case-insensitive literal is looked for in (only for `in`, never for spans)."""
|
|
1253
|
+
for a, b in FOLD_EXTRA:
|
|
1254
|
+
if a in text:
|
|
1255
|
+
text = text.replace(a, b)
|
|
1256
|
+
return text.lower()
|
|
1257
|
+
|
|
1258
|
+
|
|
1259
|
+
def _lit_char(n: Node) -> str | None:
|
|
1260
|
+
if n.kind == "char" and len(n.cs.items) == 1 and n.cs.items[0][0] == "ch" and not n.cs.negated:
|
|
1261
|
+
return n.cs.items[0][1]
|
|
1262
|
+
return None
|
|
1263
|
+
|
|
1264
|
+
|
|
1265
|
+
def _seq_lits(n: Node) -> str | None:
|
|
1266
|
+
"""The text of a group body that is only plain literal characters (one or a sequence), else None."""
|
|
1267
|
+
out = []
|
|
1268
|
+
for y in _seq_items(n):
|
|
1269
|
+
c = _lit_char(y)
|
|
1270
|
+
if c is None:
|
|
1271
|
+
return None
|
|
1272
|
+
out.append(c)
|
|
1273
|
+
return "".join(out) if out else None
|
|
1274
|
+
|
|
1275
|
+
|
|
1276
|
+
def required_literals(parsed: Parsed, min_len: int = 3) -> tuple:
|
|
1277
|
+
"""(literals, case_insensitive): every match of the pattern contains at least one of the literals (compared on the
|
|
1278
|
+
folded text when case_insensitive), read from the tree by five rules: a literal run gives itself; a sequence takes its
|
|
1279
|
+
best part; an alternation is the union of one set per branch (none if a branch has none); a repeat with minimum >= 1
|
|
1280
|
+
passes its body's set through (minimum 0 gives none); classes, dot, lookarounds and back-references give nothing and
|
|
1281
|
+
end a run (anchors are zero-width and do not). (None, ci) when no set qualifies. Never a guess: a case-insensitive
|
|
1282
|
+
literal character outside ASCII ends the run (its case partners are not all folded by `fold`)."""
|
|
1283
|
+
ci = [False]
|
|
1284
|
+
|
|
1285
|
+
def best(cands):
|
|
1286
|
+
cands = [c for c in cands if c and len(c) <= MAX_LITERALS]
|
|
1287
|
+
return max(cands, key=lambda s: (min(len(x) for x in s), -len(s))) if cands else None
|
|
1288
|
+
|
|
1289
|
+
def lit(x: Node, run: list) -> bool:
|
|
1290
|
+
ch = _lit_char(x)
|
|
1291
|
+
if ch is None:
|
|
1292
|
+
return False
|
|
1293
|
+
if x.cs.icase and ch.lower() != ch.upper():
|
|
1294
|
+
if not ch.isascii():
|
|
1295
|
+
return False
|
|
1296
|
+
ci[0] = True
|
|
1297
|
+
ch = ch.lower()
|
|
1298
|
+
run.append(ch)
|
|
1299
|
+
return True
|
|
1300
|
+
|
|
1301
|
+
def seq(items) -> frozenset | None:
|
|
1302
|
+
cands, run = [], []
|
|
1303
|
+
|
|
1304
|
+
def flush():
|
|
1305
|
+
if run:
|
|
1306
|
+
cands.append(frozenset({"".join(run)}))
|
|
1307
|
+
run.clear()
|
|
1308
|
+
for x in items:
|
|
1309
|
+
if lit(x, run):
|
|
1310
|
+
continue
|
|
1311
|
+
if x.kind == "anchor":
|
|
1312
|
+
continue
|
|
1313
|
+
if x.kind == "group" and not x.atomic and _seq_lits(x.item) is not None:
|
|
1314
|
+
tmp: list = []
|
|
1315
|
+
if all(lit(y, tmp) for y in _seq_items(x.item)):
|
|
1316
|
+
run.extend(tmp)
|
|
1317
|
+
continue
|
|
1318
|
+
flush()
|
|
1319
|
+
if x.kind != "char":
|
|
1320
|
+
cands.append(node(x))
|
|
1321
|
+
flush()
|
|
1322
|
+
return best(cands)
|
|
1323
|
+
|
|
1324
|
+
def node(n: Node) -> frozenset | None:
|
|
1325
|
+
if n.kind == "seq":
|
|
1326
|
+
return seq(n.items)
|
|
1327
|
+
if n.kind == "char":
|
|
1328
|
+
tmp: list = []
|
|
1329
|
+
return frozenset({tmp[0]}) if lit(n, tmp) else None
|
|
1330
|
+
if n.kind == "alt":
|
|
1331
|
+
parts = [node(b) for b in n.items]
|
|
1332
|
+
if parts and all(parts):
|
|
1333
|
+
u = frozenset().union(*parts)
|
|
1334
|
+
return u if len(u) <= MAX_LITERALS else None
|
|
1335
|
+
return None
|
|
1336
|
+
if n.kind == "group" and n.kind != "look":
|
|
1337
|
+
return node(n.item)
|
|
1338
|
+
if n.kind == "rep":
|
|
1339
|
+
return node(n.item) if n.lo >= 1 else None
|
|
1340
|
+
return None
|
|
1341
|
+
got = node(parsed.root)
|
|
1342
|
+
if not got or min(len(x) for x in got) < min_len:
|
|
1343
|
+
return None, ci[0]
|
|
1344
|
+
if ci[0]:
|
|
1345
|
+
got = frozenset(x.lower() for x in got)
|
|
1346
|
+
return got, ci[0]
|
|
1347
|
+
|
|
1348
|
+
|
|
1349
|
+
# --- the restart skip: a quadratic search restart no pattern can remove ------------------------------------------------------
|
|
1350
|
+
|
|
1351
|
+
def _width(n: Node) -> tuple | None:
|
|
1352
|
+
"""(min, max) characters a node matches, None when unbounded or unknown (a back-reference)."""
|
|
1353
|
+
if n.kind == "char":
|
|
1354
|
+
return (1, 1)
|
|
1355
|
+
if n.kind in ("anchor", "look", "empty"):
|
|
1356
|
+
return (0, 0)
|
|
1357
|
+
if n.kind == "seq":
|
|
1358
|
+
lo = hi = 0
|
|
1359
|
+
for x in n.items:
|
|
1360
|
+
w = _width(x)
|
|
1361
|
+
if w is None:
|
|
1362
|
+
return None
|
|
1363
|
+
lo, hi = lo + w[0], hi + w[1]
|
|
1364
|
+
return (lo, hi)
|
|
1365
|
+
if n.kind == "alt":
|
|
1366
|
+
ws = [_width(x) for x in n.items]
|
|
1367
|
+
if not ws or any(w is None for w in ws):
|
|
1368
|
+
return None
|
|
1369
|
+
return (min(w[0] for w in ws), max(w[1] for w in ws))
|
|
1370
|
+
if n.kind == "group":
|
|
1371
|
+
return _width(n.item)
|
|
1372
|
+
if n.kind == "rep":
|
|
1373
|
+
w = _width(n.item)
|
|
1374
|
+
if w is None or n.hi is None:
|
|
1375
|
+
return None
|
|
1376
|
+
return (w[0] * n.lo, w[1] * n.hi)
|
|
1377
|
+
return None
|
|
1378
|
+
|
|
1379
|
+
|
|
1380
|
+
GLOBAL_FLAGS = r"^(?:\(\?[a-zA-Z]+\))+"
|
|
1381
|
+
|
|
1382
|
+
|
|
1383
|
+
def _run_of(x: Node):
|
|
1384
|
+
"""The repeat when an item is an unbounded repeat of one character class (alone in its groups), else None."""
|
|
1385
|
+
r = x
|
|
1386
|
+
while r.kind == "group" and not r.atomic:
|
|
1387
|
+
r = r.item
|
|
1388
|
+
return r if r.kind == "rep" and r.hi is None and r.item.kind == "char" else None
|
|
1389
|
+
|
|
1390
|
+
|
|
1391
|
+
def _stopper(p: str, rep: Node) -> str:
|
|
1392
|
+
cls = p[rep.item.span[0]:rep.item.span[1]]
|
|
1393
|
+
if cls.startswith("[^") and cls.endswith("]") and len(cls) > 3:
|
|
1394
|
+
return "[" + cls[2:]
|
|
1395
|
+
return f"(?:(?!{cls})[\\s\\S])"
|
|
1396
|
+
|
|
1397
|
+
|
|
1398
|
+
def restart_plan(parsed: Parsed) -> dict | None:
|
|
1399
|
+
"""When a search restarts at every opener and re-reads the same run, the starts that must fail can be skipped
|
|
1400
|
+
without changing a single match. The pattern must be OPENER (bounded width, at least one character, no lookbehind) +
|
|
1401
|
+
a run (an unbounded repeat of one character class, alone in its groups) + the rest, with no back-reference anywhere.
|
|
1402
|
+
If a start fails after its opener matched, every later start whose run begins inside the failed start's run, before
|
|
1403
|
+
its stopper, fails too: its run can only stop at places where the earlier run could also stop, and the rest already
|
|
1404
|
+
failed at every one of them (what the rest matches depends on the position only).
|
|
1405
|
+
|
|
1406
|
+
Later runs count too when the way to them is forced: a fixed-width opener, and each run before them followed by
|
|
1407
|
+
something that must start with a character the run cannot take (`[^\\]]*\\]`), so the run ends at its first stopper
|
|
1408
|
+
and every start reaches the next run at one place (`!\\[([^\\]]*)\\]\\([^)]*\\)`: the second run is the slow one).
|
|
1409
|
+
Returns the opener of each run (the pattern's own text up to it, same flags), each run's stopper, the first
|
|
1410
|
+
opener's width, and samples for the input families; or None."""
|
|
1411
|
+
import re as _re
|
|
1412
|
+
if parsed.flavor not in ("python", "js") or any(n.kind == "backref" for n in parsed.walk()):
|
|
1413
|
+
return None
|
|
1414
|
+
root = parsed.root
|
|
1415
|
+
while root.kind == "group" and not root.atomic:
|
|
1416
|
+
root = root.item
|
|
1417
|
+
items = root.items if root.kind == "seq" else [root]
|
|
1418
|
+
first = next((k for k, x in enumerate(items) if _run_of(x) is not None), None)
|
|
1419
|
+
if not first:
|
|
1420
|
+
return None
|
|
1421
|
+
prefix = items[:first]
|
|
1422
|
+
if any(_width(x) is None for x in prefix):
|
|
1423
|
+
return None
|
|
1424
|
+
w = _width(Node("seq", items=prefix))
|
|
1425
|
+
if w is None or w[0] < 1 or any(n.kind == "look" and not n.ahead for x in prefix for n in walk(x)):
|
|
1426
|
+
return None
|
|
1427
|
+
f = Facts(parsed)
|
|
1428
|
+
p = parsed.pattern
|
|
1429
|
+
m = _re.match(GLOBAL_FLAGS, p)
|
|
1430
|
+
flags_text = m.group(0) if m else ""
|
|
1431
|
+
runs = [first]
|
|
1432
|
+
if w[0] == w[1]:
|
|
1433
|
+
# the forced chain: run k ends at its first stopper when what follows must start with a stopper character
|
|
1434
|
+
k = first
|
|
1435
|
+
while True:
|
|
1436
|
+
rep = _run_of(items[k])
|
|
1437
|
+
nxt = k + 1
|
|
1438
|
+
if nxt >= len(items) or f.nullable(items[nxt]) or f.first(items[nxt]) & f.chars(rep.item):
|
|
1439
|
+
break
|
|
1440
|
+
j = nxt
|
|
1441
|
+
while j < len(items) and _run_of(items[j]) is None and _width(items[j]) is not None and _width(items[j])[0] == _width(items[j])[1]:
|
|
1442
|
+
j += 1
|
|
1443
|
+
if j >= len(items) or _run_of(items[j]) is None:
|
|
1444
|
+
break
|
|
1445
|
+
runs.append(j)
|
|
1446
|
+
k = j
|
|
1447
|
+
openers, stoppers = [], []
|
|
1448
|
+
for k in runs:
|
|
1449
|
+
openers.append(flags_text + "".join(p[x.span[0]:x.span[1]] for x in items[:k]))
|
|
1450
|
+
stoppers.append(flags_text + _stopper(p, _run_of(items[k])))
|
|
1451
|
+
if parsed.flavor == "python":
|
|
1452
|
+
try:
|
|
1453
|
+
for t in openers + stoppers:
|
|
1454
|
+
_re.compile(t, _re.I if parsed.flags.get("i") else 0)
|
|
1455
|
+
except _re.error:
|
|
1456
|
+
return None
|
|
1457
|
+
last = runs[-1]
|
|
1458
|
+
rep0 = _run_of(items[first])
|
|
1459
|
+
return {"opener": openers[0], "stopper": stoppers[0], "openers": openers, "stoppers": stoppers, "min_len": w[0], "max_len": w[1],
|
|
1460
|
+
"run": p[rep0.span[0]:rep0.span[1]], "runs": [p[_run_of(items[k]).span[0]:_run_of(items[k]).span[1]] for k in runs],
|
|
1461
|
+
"opener_sample": "".join(f.sample(x) for x in prefix),
|
|
1462
|
+
"chain_sample": "".join(f.sample(x) for x in items[:last]),
|
|
1463
|
+
"rest_sample": "".join(f.sample(x) for x in items[first + 1:]),
|
|
1464
|
+
"run_chars": f.chars(rep0.item)}
|
|
1465
|
+
|
|
1466
|
+
|
|
1467
|
+
def restart_families(parsed: Parsed, plan: dict) -> list[dict]:
|
|
1468
|
+
"""Three input families for a restart skip: openers only; openers then one closing text at the end; openers, a
|
|
1469
|
+
stopper, then a closing text. A fix that handles only the first (cutting the search at the last closer) stays slow on
|
|
1470
|
+
the other two and is not accepted."""
|
|
1471
|
+
op, rest = plan["opener_sample"], plan["rest_sample"] or ""
|
|
1472
|
+
stop = pick(frozenset(parsed.universe) - plan["run_chars"])
|
|
1473
|
+
fams = [{"name": "openers", "prefix": "", "pump": op, "suffix": ""}]
|
|
1474
|
+
if plan.get("chain_sample") and plan["chain_sample"] != op:
|
|
1475
|
+
fams.append({"name": "openers up to the last run", "prefix": "", "pump": plan["chain_sample"], "suffix": " " + rest if rest else ""})
|
|
1476
|
+
if rest:
|
|
1477
|
+
fams.append({"name": "openers, one closer at the end", "prefix": "", "pump": op, "suffix": " " + rest})
|
|
1478
|
+
if stop:
|
|
1479
|
+
fams.append({"name": "openers, a stopper, then a closer", "prefix": "", "pump": op, "suffix": stop + " zz " + rest})
|
|
1480
|
+
return fams
|
|
1481
|
+
|
|
1482
|
+
|
|
1483
|
+
PY_FLAG_NAMES = {"i": "I", "m": "M", "s": "S", "x": "X", "a": "A"}
|
|
1484
|
+
|
|
1485
|
+
|
|
1486
|
+
def restart_helper(plan: dict, pattern: str, flags: str, engine: str, api: str = "") -> tuple[str, str]:
|
|
1487
|
+
"""(code, entry): the helper in the site's language. The harness runs `entry` (a generator of the same match
|
|
1488
|
+
objects as finditer) from this exact text; the hand-off shows the same text, with the wrapper the call needs."""
|
|
1489
|
+
if engine in ("python", "python-regex"):
|
|
1490
|
+
mod = "regex" if engine == "python-regex" else "re"
|
|
1491
|
+
fl = " | ".join(f"{mod}.{PY_FLAG_NAMES[c]}" for c in flags if c in PY_FLAG_NAMES) or "0"
|
|
1492
|
+
wrap = {
|
|
1493
|
+
"sub": ('\n\ndef sub_skip(repl, text, count=0):\n """_PAT.sub(repl, text, count), linear."""\n out, last, n = [], 0, 0\n'
|
|
1494
|
+
" for m in finditer_skip(text):\n out.append(text[last:m.start()])\n"
|
|
1495
|
+
" out.append(repl(m) if callable(repl) else m.expand(repl))\n last, n = m.end(), n + 1\n"
|
|
1496
|
+
" if count and n >= count:\n break\n out.append(text[last:])\n return \"\".join(out)\n"),
|
|
1497
|
+
"findall": ('\n\ndef findall_skip(text):\n """_PAT.findall(text), linear."""\n g = _PAT.groups\n'
|
|
1498
|
+
" return [m.group() if g == 0 else m.group(1) if g == 1 else m.groups() for m in finditer_skip(text)]\n"),
|
|
1499
|
+
"search": '\n\ndef search_skip(text):\n """_PAT.search(text), linear."""\n return next(finditer_skip(text), None)\n',
|
|
1500
|
+
}
|
|
1501
|
+
opens = "".join(f" {mod}.compile({t!r}, {fl}),\n" for t in plan["openers"])
|
|
1502
|
+
stops = "".join(f" {mod}.compile({t!r}, {fl}),\n" for t in plan["stoppers"])
|
|
1503
|
+
code = (f"import {mod}\n\n"
|
|
1504
|
+
f"_PAT = {mod}.compile({pattern!r}, {fl}) # the pattern as it is, unchanged\n"
|
|
1505
|
+
f"_OPEN = [ # the pattern up to each run ({', '.join(plan['runs'])}): the first is where a match can start\n{opens}]\n"
|
|
1506
|
+
f"_STOP = [ # what each run cannot cross\n{stops}]\n"
|
|
1507
|
+
f"_MIN, _MAX = {plan['min_len']}, {plan['max_len']} # the width of the first opener\n\n\n"
|
|
1508
|
+
"def finditer_skip(text):\n"
|
|
1509
|
+
' """The same matches as _PAT.finditer(text), without re-reading a run for every start: when a start fails,\n'
|
|
1510
|
+
" a later start whose run begins inside that start's run, before its stopper, fails the same way.\"\"\"\n"
|
|
1511
|
+
" pos, end, n = 0, len(text), len(_OPEN)\n"
|
|
1512
|
+
" failed = [None] * n # per run: (first, last) run start known to fail\n"
|
|
1513
|
+
" while True:\n"
|
|
1514
|
+
" c = _OPEN[0].search(text, pos)\n"
|
|
1515
|
+
" if c is None:\n"
|
|
1516
|
+
" return\n"
|
|
1517
|
+
" i = c.start()\n"
|
|
1518
|
+
" f = failed[0]\n"
|
|
1519
|
+
" if f and f[0] <= i + _MIN and i + _MAX <= f[1]:\n"
|
|
1520
|
+
" pos = max(i + 1, f[1] - _MAX + 1)\n"
|
|
1521
|
+
" continue\n"
|
|
1522
|
+
" skip = False\n"
|
|
1523
|
+
" for k in range(1, n):\n"
|
|
1524
|
+
" if failed[k]:\n"
|
|
1525
|
+
" o = _OPEN[k].match(text, i)\n"
|
|
1526
|
+
" if o is None or failed[k][0] <= o.end() <= failed[k][1]:\n"
|
|
1527
|
+
" skip = True\n"
|
|
1528
|
+
" break\n"
|
|
1529
|
+
" if skip:\n"
|
|
1530
|
+
" pos = i + 1\n"
|
|
1531
|
+
" continue\n"
|
|
1532
|
+
" m = _PAT.match(text, i)\n"
|
|
1533
|
+
" if m:\n"
|
|
1534
|
+
" yield m\n"
|
|
1535
|
+
" pos = max(m.end(), i + 1)\n"
|
|
1536
|
+
" continue\n"
|
|
1537
|
+
" s = _STOP[0].search(text, i + _MIN)\n"
|
|
1538
|
+
" failed[0] = (i + _MAX, s.start() if s else end)\n"
|
|
1539
|
+
" for k in range(1, n):\n"
|
|
1540
|
+
" o = _OPEN[k].match(text, i)\n"
|
|
1541
|
+
" if o is not None:\n"
|
|
1542
|
+
" s = _STOP[k].search(text, o.end())\n"
|
|
1543
|
+
" failed[k] = (o.end(), s.start() if s else end)\n"
|
|
1544
|
+
" pos = i + 1\n"
|
|
1545
|
+
+ wrap.get("sub" if api in ("sub", "subn") else api, ""))
|
|
1546
|
+
return code, "finditer_skip"
|
|
1547
|
+
if engine == "node":
|
|
1548
|
+
import json as _json
|
|
1549
|
+
fl = "".join(c for c in flags if c in "imsu")
|
|
1550
|
+
opens = ", ".join(f"new RegExp({_json.dumps(t)}, {_json.dumps(fl + ('g' if k == 0 else 'y'))})" for k, t in enumerate(plan["openers"]))
|
|
1551
|
+
stops = ", ".join(f"new RegExp({_json.dumps(t)}, {_json.dumps(fl + 'g')})" for t in plan["stoppers"])
|
|
1552
|
+
code = (f"const PAT = new RegExp({_json.dumps(pattern)}, {_json.dumps(fl + 'y')}); // the pattern as it is (sticky)\n"
|
|
1553
|
+
f"const OPEN = [{opens}]; // the pattern up to each run; the first is where a match can start\n"
|
|
1554
|
+
f"const STOP = [{stops}]; // what each run cannot cross\n"
|
|
1555
|
+
f"const MIN = {plan['min_len']}, MAX = {plan['max_len']}; // the width of the first opener\n\n"
|
|
1556
|
+
"// The same matches as text.matchAll(/…/g), without re-reading a run for every start.\n"
|
|
1557
|
+
"function* matchAllSkip(text) {\n"
|
|
1558
|
+
" let pos = 0; const failed = OPEN.map(() => null);\n"
|
|
1559
|
+
" const at = (re, i) => { re.lastIndex = i; return re.exec(text); };\n"
|
|
1560
|
+
" for (;;) {\n"
|
|
1561
|
+
" const c = at(OPEN[0], pos);\n"
|
|
1562
|
+
" if (!c) return;\n"
|
|
1563
|
+
" const i = c.index; let f = failed[0];\n"
|
|
1564
|
+
" if (f && f[0] <= i + MIN && i + MAX <= f[1]) { pos = Math.max(i + 1, f[1] - MAX + 1); continue; }\n"
|
|
1565
|
+
" let skip = false;\n"
|
|
1566
|
+
" for (let k = 1; k < OPEN.length && !skip; k++) {\n"
|
|
1567
|
+
" if (!failed[k]) continue;\n"
|
|
1568
|
+
" const o = at(OPEN[k], i);\n"
|
|
1569
|
+
" skip = !o || (failed[k][0] <= i + o[0].length && i + o[0].length <= failed[k][1]);\n"
|
|
1570
|
+
" }\n"
|
|
1571
|
+
" if (skip) { pos = i + 1; continue; }\n"
|
|
1572
|
+
" const m = at(PAT, i);\n"
|
|
1573
|
+
" if (m) { yield m; pos = Math.max(i + m[0].length, i + 1); continue; }\n"
|
|
1574
|
+
" let s = at(STOP[0], i + MIN);\n"
|
|
1575
|
+
" failed[0] = [i + MAX, s ? s.index : text.length];\n"
|
|
1576
|
+
" for (let k = 1; k < OPEN.length; k++) {\n"
|
|
1577
|
+
" const o = at(OPEN[k], i);\n"
|
|
1578
|
+
" if (o) { const e = i + o[0].length; s = at(STOP[k], e); failed[k] = [e, s ? s.index : text.length]; }\n"
|
|
1579
|
+
" }\n"
|
|
1580
|
+
" pos = i + 1;\n"
|
|
1581
|
+
" }\n"
|
|
1582
|
+
"}\n")
|
|
1583
|
+
return code, "matchAllSkip"
|
|
1584
|
+
return "", ""
|
|
1585
|
+
|
|
1586
|
+
|
|
1587
|
+
# --- lookahead scans: a lookahead that reads to the end at every start -------------------------------------------------------
|
|
1588
|
+
|
|
1589
|
+
def lookahead_issues(parsed: Parsed, api: str = "search", max_families: int = 6) -> list[Issue]:
|
|
1590
|
+
"""A lookahead whose body starts with an unbounded repeat (`(?=.*?X)`), tried at every start of an unanchored
|
|
1591
|
+
search: each start reads to the end of the run when X is absent, so the search is quadratic. The repeat check does
|
|
1592
|
+
not see it (the repeat is inside the lookahead)."""
|
|
1593
|
+
if parsed.flavor not in ("python", "js", "java") or api in FULL_APIS or api in ANCHORED_APIS:
|
|
1594
|
+
return []
|
|
1595
|
+
f = Facts(parsed)
|
|
1596
|
+
items = _seq_items(parsed.root)
|
|
1597
|
+
if items and items[0].kind == "anchor" and items[0].name == "start":
|
|
1598
|
+
return []
|
|
1599
|
+
out = []
|
|
1600
|
+
for n, before, after, in_rep in _paths(parsed.root):
|
|
1601
|
+
if n.kind != "look" or not n.ahead or in_rep:
|
|
1602
|
+
continue
|
|
1603
|
+
if any(b.kind != "anchor" and (_width(b) is None or _width(b)[1] > 0) for b in before):
|
|
1604
|
+
continue # something is read before the lookahead
|
|
1605
|
+
body = _seq_items(n.item)
|
|
1606
|
+
if not body or body[0].kind != "rep" or body[0].hi is not None or body[0].possessive:
|
|
1607
|
+
continue
|
|
1608
|
+
inner = f.chars(body[0].item)
|
|
1609
|
+
target = f.first(body[1]) if len(body) > 1 else frozenset()
|
|
1610
|
+
pumps = []
|
|
1611
|
+
c = next((x for x in "ab_x" if x in inner and x not in target), "") or pick(inner - target)
|
|
1612
|
+
if c:
|
|
1613
|
+
pumps.append(c)
|
|
1614
|
+
sp = next((x for x in " .-" if x in inner and x not in target), "")
|
|
1615
|
+
if sp:
|
|
1616
|
+
pumps.append(c * 2 + sp)
|
|
1617
|
+
fams = [{"prefix": "", "pump": p, "suffix": ""} for p in pumps][:max_families]
|
|
1618
|
+
if fams:
|
|
1619
|
+
out.append(Issue("lookahead_scan", "polynomial", n.span, fams,
|
|
1620
|
+
f"{parsed.pattern[n.span[0]:n.span[1]][:40]} reads to the end at every start"))
|
|
1621
|
+
return _dedupe(out)
|
|
1622
|
+
|
|
1623
|
+
|
|
1624
|
+
# --- alphabet classes: one character per class the patterns tell apart --------------------------------------------------------
|
|
1625
|
+
|
|
1626
|
+
def alphabet_classes(parsed_list: list[Parsed]) -> list[str]:
|
|
1627
|
+
"""One representative character for each class of characters that every leaf of the patterns (each literal and
|
|
1628
|
+
class, and \\w, \\s, \\d and the dot under the same flags) treats the same way, over the patterns' universe (ASCII,
|
|
1629
|
+
the patterns' own characters, and characters that tell flavors apart, such as a non-ASCII digit)."""
|
|
1630
|
+
if not parsed_list:
|
|
1631
|
+
return []
|
|
1632
|
+
universe = list(dict.fromkeys(c for p in parsed_list for c in p.universe))
|
|
1633
|
+
leaves = []
|
|
1634
|
+
for p in parsed_list:
|
|
1635
|
+
leaves += [n.cs for n in p.walk() if n.kind == "char"]
|
|
1636
|
+
for probe in ("\\w", "\\s", "\\d", "."):
|
|
1637
|
+
try:
|
|
1638
|
+
leaves.append(parse(probe, p.flavor, {k: v for k, v in p.flags.items() if k != "x"}).root.cs)
|
|
1639
|
+
except (Unsupported, ValueError):
|
|
1640
|
+
pass
|
|
1641
|
+
sig: dict[tuple, list[str]] = {}
|
|
1642
|
+
for c in universe:
|
|
1643
|
+
sig.setdefault(tuple(cs.contains(c) for cs in leaves) + (c.isupper(), c.islower()), []).append(c)
|
|
1644
|
+
return [sorted(chars, key=lambda c: (_PREFER.find(c) if c in _PREFER else 999, ord(c)))[0] for chars in sig.values()]
|
|
1645
|
+
|
|
1646
|
+
|
|
1647
|
+
def class_variants(strings: list[str], reps: list[str], budget: int, max_pos: int = 48) -> list[str]:
|
|
1648
|
+
"""Strings with each position replaced by, and preceded by, one representative of every class (shortest strings
|
|
1649
|
+
first, at most `budget` new strings). It closes a hole a generated corpus leaves: a non-ASCII digit
|
|
1650
|
+
next to a lookahead (`(?<=\\d)p(?=\\d)` against `[0-9]`)."""
|
|
1651
|
+
out: dict[str, None] = {}
|
|
1652
|
+
seen = set(strings)
|
|
1653
|
+
base = sorted(seen, key=len)
|
|
1654
|
+
per = max(1, budget // max(1, len(base)))
|
|
1655
|
+
for s in base:
|
|
1656
|
+
k = 0
|
|
1657
|
+
for i in range(min(len(s), max_pos) + 1):
|
|
1658
|
+
for c in reps:
|
|
1659
|
+
for t in ((s[:i] + c + s[i + 1:]) if i < len(s) else None, s[:i] + c + s[i:]):
|
|
1660
|
+
if t is not None and t not in seen and t not in out:
|
|
1661
|
+
out[t] = None
|
|
1662
|
+
k += 1
|
|
1663
|
+
if k > per:
|
|
1664
|
+
break
|
|
1665
|
+
if len(out) >= budget:
|
|
1666
|
+
break
|
|
1667
|
+
return list(out)[:budget]
|
|
1668
|
+
|
|
1669
|
+
|
|
1670
|
+
# --- fold once instead of a case-insensitive flag (CPython) --------------------------------------------------------------------
|
|
1671
|
+
|
|
1672
|
+
def fold_eligible(pattern: str, flavor: str, flags: str) -> bool:
|
|
1673
|
+
"""Whether the pattern compiled WITHOUT the case-insensitive flag, on the text folded once per character (lower(),
|
|
1674
|
+
with U+0130, U+0131, U+017F and U+212A mapped, so every span stays where it was), matches exactly what it matches
|
|
1675
|
+
WITH the flag on the original text. Read from the tree: every character set gives the same answer with and without
|
|
1676
|
+
the flag on every folded character, literals are ASCII, and nothing refers back to a group. The corpus then checks."""
|
|
1677
|
+
import re as _re
|
|
1678
|
+
if flavor != "python" or "i" not in (flags or "") or _re.search(r"\(\?[a-zA-Z]*i", pattern):
|
|
1679
|
+
return False
|
|
1680
|
+
try:
|
|
1681
|
+
with_i = parse(pattern, flavor, flags)
|
|
1682
|
+
without = parse(pattern, flavor, flags.replace("i", ""))
|
|
1683
|
+
except (Unsupported, ValueError, IndexError, OverflowError):
|
|
1684
|
+
return False
|
|
1685
|
+
a, b = list(with_i.walk()), list(without.walk())
|
|
1686
|
+
if len(a) != len(b):
|
|
1687
|
+
return False
|
|
1688
|
+
U = [c for c in with_i.universe if _fold_char(c) == c]
|
|
1689
|
+
for x, y in zip(a, b):
|
|
1690
|
+
if x.kind == "backref":
|
|
1691
|
+
return False
|
|
1692
|
+
if x.kind == "char":
|
|
1693
|
+
for item in x.cs.items:
|
|
1694
|
+
if item[0] == "ch" and not item[1].isascii() or item[0] == "range" and not (item[1].isascii() and item[2].isascii()):
|
|
1695
|
+
return False
|
|
1696
|
+
if any(x.cs.contains(c) != y.cs.contains(c) for c in U):
|
|
1697
|
+
return False
|
|
1698
|
+
return True
|
|
1699
|
+
|
|
1700
|
+
|
|
1701
|
+
def _fold_char(c: str) -> str:
|
|
1702
|
+
for a, b in FOLD_EXTRA:
|
|
1703
|
+
if c == a:
|
|
1704
|
+
return b
|
|
1705
|
+
lo = c.lower()
|
|
1706
|
+
return lo if len(lo) == 1 else c
|
|
1707
|
+
|
|
1708
|
+
|
|
1709
|
+
def keyword_alternation(parsed: Parsed) -> list[str] | None:
|
|
1710
|
+
"""The keywords of a pattern that is only an alternation of plain literals (optionally in one group), else None."""
|
|
1711
|
+
root = parsed.root
|
|
1712
|
+
while root.kind == "group" and not root.atomic:
|
|
1713
|
+
root = root.item
|
|
1714
|
+
branches = root.items if root.kind == "alt" else [root]
|
|
1715
|
+
out = []
|
|
1716
|
+
for b in branches:
|
|
1717
|
+
s = _seq_lits(b)
|
|
1718
|
+
if s is None:
|
|
1719
|
+
return None
|
|
1720
|
+
out.append(s)
|
|
1721
|
+
return out if len(out) >= 2 else None
|