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,295 @@
|
|
|
1
|
+
"""CodeCop's regex harness for CPython `re` (and the `regex` module when the interpreter has it). Reads one JSON request on
|
|
2
|
+
stdin, writes JSON lines on stdout, one per measured input, flushed at once: when the parent kills a run that does not
|
|
3
|
+
finish, the lines already written are kept. Runs only the pattern it is given on the strings it is given; it imports
|
|
4
|
+
nothing from the repository. Ops: version, time, results, compile (see harness.py)."""
|
|
5
|
+
|
|
6
|
+
import json
|
|
7
|
+
import sys
|
|
8
|
+
import time
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def flags_of(mod, text):
|
|
12
|
+
f = 0
|
|
13
|
+
for ch in text or "":
|
|
14
|
+
f |= {"i": mod.IGNORECASE, "m": mod.MULTILINE, "s": mod.DOTALL, "x": mod.VERBOSE, "a": mod.ASCII}.get(ch, 0)
|
|
15
|
+
return f
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def span_list(m, limit):
|
|
19
|
+
if m is None:
|
|
20
|
+
return None
|
|
21
|
+
out = [m.start(), m.end()]
|
|
22
|
+
for g in range(1, min(len(m.groups()), limit) + 1):
|
|
23
|
+
out.append([m.start(g), m.end(g)] if m.start(g) >= 0 else None)
|
|
24
|
+
return out
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def run(rx, mode, s, take=None, limit=50):
|
|
28
|
+
"""The call the site makes, by mode, and a result to compare."""
|
|
29
|
+
if mode == "match":
|
|
30
|
+
return span_list(rx.match(s), 20)
|
|
31
|
+
if mode == "full":
|
|
32
|
+
return span_list(rx.fullmatch(s), 20)
|
|
33
|
+
if mode == "search":
|
|
34
|
+
return span_list(rx.search(s), 20)
|
|
35
|
+
if mode == "bool":
|
|
36
|
+
return rx.search(s) is not None
|
|
37
|
+
if mode == "count":
|
|
38
|
+
n = 0
|
|
39
|
+
for _ in rx.finditer(s):
|
|
40
|
+
n += 1
|
|
41
|
+
if take and n >= take:
|
|
42
|
+
break
|
|
43
|
+
return n
|
|
44
|
+
out = []
|
|
45
|
+
for m in rx.finditer(s):
|
|
46
|
+
if len(out) < limit:
|
|
47
|
+
out.append(span_list(m, 20))
|
|
48
|
+
else:
|
|
49
|
+
break
|
|
50
|
+
return out
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def emit(obj):
|
|
54
|
+
sys.stdout.write(json.dumps(obj) + "\n")
|
|
55
|
+
sys.stdout.flush()
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
SAFE_BUILTINS = ("abs", "all", "any", "bool", "callable", "dict", "enumerate", "filter", "frozenset", "int", "isinstance", "iter",
|
|
59
|
+
"len", "list", "map", "max", "min", "next", "range", "reversed", "set", "sorted", "str", "sum", "tuple", "zip",
|
|
60
|
+
"StopIteration", "ValueError", "IndexError", "KeyError", "Exception", "True", "False", "None", "callable")
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class Fixed:
|
|
64
|
+
"""A fix written as a small function (a CodeCop helper or the agent's code): run from its source text with nothing but
|
|
65
|
+
the regex module and plain builtins, never anything from the repository. `PAT` is the original compiled pattern."""
|
|
66
|
+
|
|
67
|
+
def __init__(self, mod, code, entry, rx):
|
|
68
|
+
import builtins
|
|
69
|
+
allowed = {mod.__name__, "re"}
|
|
70
|
+
|
|
71
|
+
def imp(name, *a, **k):
|
|
72
|
+
if name not in allowed:
|
|
73
|
+
raise ImportError(f"only {sorted(allowed)} may be imported")
|
|
74
|
+
return __import__(name, *a, **k)
|
|
75
|
+
b = {k: getattr(builtins, k) for k in SAFE_BUILTINS if hasattr(builtins, k)}
|
|
76
|
+
b["__import__"] = imp
|
|
77
|
+
ns = {"__builtins__": b, "PAT": rx, mod.__name__: mod, "__name__": "codecop_fix"}
|
|
78
|
+
exec(compile(code, "<fix>", "exec"), ns) # noqa: S102 -- CodeCop's helper or the agent's answer, sandboxed child
|
|
79
|
+
self.fn = ns[entry]
|
|
80
|
+
self.groups = rx.groups
|
|
81
|
+
|
|
82
|
+
def norm(self, m, limit):
|
|
83
|
+
if m is None:
|
|
84
|
+
return None
|
|
85
|
+
out = [m.start(), m.end()]
|
|
86
|
+
for g in range(1, min(self.groups, limit) + 1):
|
|
87
|
+
out.append([m.start(g), m.end(g)] if m.start(g) >= 0 else None)
|
|
88
|
+
return out
|
|
89
|
+
|
|
90
|
+
def run(self, mode, s, take=None, limit=50):
|
|
91
|
+
r = self.fn(s)
|
|
92
|
+
if mode in ("search", "match", "full", "bool"):
|
|
93
|
+
if r is not None and not hasattr(r, "span"):
|
|
94
|
+
r = next(iter(r), None)
|
|
95
|
+
return (r is not None) if mode == "bool" else self.norm(r, 20)
|
|
96
|
+
out, n = [], 0
|
|
97
|
+
for m in r:
|
|
98
|
+
n += 1
|
|
99
|
+
if mode == "count":
|
|
100
|
+
if take and n >= take:
|
|
101
|
+
break
|
|
102
|
+
continue
|
|
103
|
+
if len(out) < limit:
|
|
104
|
+
out.append(self.norm(m, 20))
|
|
105
|
+
else:
|
|
106
|
+
break
|
|
107
|
+
return n if mode == "count" else out
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def fold(text):
|
|
111
|
+
"""Per-character fold that keeps every span: the four characters lower() does not bring to an ASCII letter first."""
|
|
112
|
+
for a, b in (("İ", "i"), ("ı", "i"), ("ſ", "s"), ("K", "k")):
|
|
113
|
+
if a in text:
|
|
114
|
+
text = text.replace(a, b)
|
|
115
|
+
return text.lower()
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def table_runner(mod, req):
|
|
119
|
+
"""A table of patterns over one text, as the code runs it (`variant` plain), with each pattern run only when one of
|
|
120
|
+
its required literals is in the text (prefilter), or on the text folded once without the case flag (fold)."""
|
|
121
|
+
variant, mode = req.get("variant") or "plain", req.get("mode") or "search"
|
|
122
|
+
pats = []
|
|
123
|
+
for p in req["patterns"]:
|
|
124
|
+
fl = p.get("flags") or ""
|
|
125
|
+
if variant == "fold" and p.get("fold"):
|
|
126
|
+
fl = fl.replace("i", "")
|
|
127
|
+
pats.append((mod.compile(p["pattern"], flags_of(mod, fl)), p.get("literals"), bool(p.get("ci")), bool(p.get("fold"))))
|
|
128
|
+
empty = {"search": None, "match": None, "full": None, "bool": False, "count": 0, "all": []}[mode]
|
|
129
|
+
|
|
130
|
+
def go(s):
|
|
131
|
+
out = []
|
|
132
|
+
if variant == "prefilter":
|
|
133
|
+
low = None
|
|
134
|
+
for rx, lits, ci, _ in pats:
|
|
135
|
+
if lits:
|
|
136
|
+
if ci:
|
|
137
|
+
if low is None:
|
|
138
|
+
low = fold(s)
|
|
139
|
+
hay = low
|
|
140
|
+
else:
|
|
141
|
+
hay = s
|
|
142
|
+
if not any(x in hay for x in lits):
|
|
143
|
+
out.append(empty)
|
|
144
|
+
continue
|
|
145
|
+
out.append(run(rx, mode, s))
|
|
146
|
+
elif variant == "fold":
|
|
147
|
+
low = fold(s)
|
|
148
|
+
for rx, _, _, f in pats:
|
|
149
|
+
out.append(run(rx, mode, low if f else s))
|
|
150
|
+
else:
|
|
151
|
+
for rx, _, _, _ in pats:
|
|
152
|
+
out.append(run(rx, mode, s))
|
|
153
|
+
return out
|
|
154
|
+
return go
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def words_runner(mod, req):
|
|
158
|
+
"""One pattern per word in a loop (`variant` plain: re.sub(pre + w + post, repl, s) word by word, or a yes/no search
|
|
159
|
+
per word) against one alternation of all the words, longest first, with a lookup for the replacement."""
|
|
160
|
+
pre, post, F = req.get("pre") or "", req.get("post") or "", flags_of(mod, req.get("flags"))
|
|
161
|
+
words = req["words"] # [[word, replacement or None]]
|
|
162
|
+
kind = req.get("kind") or "sub"
|
|
163
|
+
ci = "i" in (req.get("flags") or "")
|
|
164
|
+
if req.get("variant") == "alternation":
|
|
165
|
+
order = sorted(words, key=lambda w: -len(w[0]))
|
|
166
|
+
rx = mod.compile(pre + "(?:" + "|".join(w[0] for w in order) + ")" + post, F)
|
|
167
|
+
table = {}
|
|
168
|
+
for w, r in words:
|
|
169
|
+
table.setdefault(w.lower() if ci else w, r)
|
|
170
|
+
if kind == "bool":
|
|
171
|
+
return lambda s: rx.search(s) is not None
|
|
172
|
+
return lambda s: rx.sub(lambda m: table[m.group().lower() if ci else m.group()], s)
|
|
173
|
+
if kind == "bool":
|
|
174
|
+
return lambda s: any(mod.search(pre + w + post, s, F) for w, _ in words)
|
|
175
|
+
|
|
176
|
+
def seq(s):
|
|
177
|
+
for w, r in words:
|
|
178
|
+
s = mod.sub(pre + w + post, r, s, flags=F)
|
|
179
|
+
return s
|
|
180
|
+
return seq
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def keywords_runner(mod, req):
|
|
184
|
+
"""A case-insensitive alternation of plain keywords asked yes/no, against `any(k in folded)` on the text folded once."""
|
|
185
|
+
if req.get("variant") == "fold":
|
|
186
|
+
kws = [k.lower() for k in req["keywords"]]
|
|
187
|
+
|
|
188
|
+
def folded(s):
|
|
189
|
+
low = fold(s)
|
|
190
|
+
return any(k in low for k in kws)
|
|
191
|
+
return folded
|
|
192
|
+
rx = mod.compile(req["pattern"], flags_of(mod, req.get("flags")))
|
|
193
|
+
return lambda s: rx.search(s) is not None
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def time_fn(fn, inputs, runs, budget):
|
|
197
|
+
for i, s in enumerate(inputs):
|
|
198
|
+
ms, stop = [], False
|
|
199
|
+
for _ in range(runs):
|
|
200
|
+
t = time.perf_counter()
|
|
201
|
+
fn(s)
|
|
202
|
+
e = (time.perf_counter() - t) * 1e3
|
|
203
|
+
ms.append(e)
|
|
204
|
+
if e > budget:
|
|
205
|
+
stop = True
|
|
206
|
+
break
|
|
207
|
+
emit({"i": i, "len": len(s), "ms": ms})
|
|
208
|
+
if stop:
|
|
209
|
+
emit({"stopped": i})
|
|
210
|
+
return
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def main():
|
|
214
|
+
req = json.loads(sys.stdin.read())
|
|
215
|
+
mod = __import__(req.get("module") or "re")
|
|
216
|
+
op = req["op"]
|
|
217
|
+
if op == "version":
|
|
218
|
+
emit({"engine": "python-" + mod.__name__, "version": sys.version.split()[0]})
|
|
219
|
+
return
|
|
220
|
+
if op in ("table", "words", "keywords"):
|
|
221
|
+
try:
|
|
222
|
+
fn = {"table": table_runner, "words": words_runner, "keywords": keywords_runner}[op](mod, req)
|
|
223
|
+
except Exception as e: # noqa: BLE001
|
|
224
|
+
emit({"error": "compile", "detail": str(e)[:200]})
|
|
225
|
+
return
|
|
226
|
+
if req.get("results"):
|
|
227
|
+
try:
|
|
228
|
+
emit({"results": [fn(s) for s in req["inputs"]]})
|
|
229
|
+
except Exception as e: # noqa: BLE001
|
|
230
|
+
emit({"error": "run", "detail": f"{type(e).__name__}: {e}"[:200]})
|
|
231
|
+
return
|
|
232
|
+
time_fn(fn, req["inputs"], int(req.get("runs") or 3), float(req.get("budget_ms") or 1000))
|
|
233
|
+
return
|
|
234
|
+
try:
|
|
235
|
+
t0 = time.perf_counter()
|
|
236
|
+
rx = mod.compile(req["pattern"], flags_of(mod, req.get("flags")))
|
|
237
|
+
compile_ms = (time.perf_counter() - t0) * 1e3
|
|
238
|
+
except Exception as e: # noqa: BLE001
|
|
239
|
+
emit({"error": "compile", "detail": str(e)[:200]})
|
|
240
|
+
return
|
|
241
|
+
mode, take = req.get("mode") or "search", req.get("take")
|
|
242
|
+
if req.get("code"):
|
|
243
|
+
try:
|
|
244
|
+
fixed = Fixed(mod, req["code"], req.get("entry") or "fixed", rx)
|
|
245
|
+
except Exception as e: # noqa: BLE001
|
|
246
|
+
emit({"error": "code", "detail": f"{type(e).__name__}: {e}"[:200]})
|
|
247
|
+
return
|
|
248
|
+
|
|
249
|
+
def run_fixed(rx_, mode_, s, take_=None, limit=50):
|
|
250
|
+
try:
|
|
251
|
+
return fixed.run(mode_, s, take_, limit)
|
|
252
|
+
except Exception as e: # noqa: BLE001 -- a fix that raises is a different result, not a crash
|
|
253
|
+
return {"raised": type(e).__name__}
|
|
254
|
+
globals()["run"] = run_fixed # the fix's function replaces the pattern in the ops below
|
|
255
|
+
if op == "time":
|
|
256
|
+
runs, budget = int(req.get("runs") or 3), float(req.get("budget_ms") or 1000)
|
|
257
|
+
for i, s in enumerate(req["inputs"]):
|
|
258
|
+
ms, stop = [], False
|
|
259
|
+
for _ in range(runs):
|
|
260
|
+
t = time.perf_counter()
|
|
261
|
+
r = run(rx, mode, s, take)
|
|
262
|
+
e = (time.perf_counter() - t) * 1e3
|
|
263
|
+
ms.append(e)
|
|
264
|
+
if e > budget:
|
|
265
|
+
stop = True
|
|
266
|
+
break
|
|
267
|
+
emit({"i": i, "len": len(s), "ms": ms, "n": r if isinstance(r, (int, bool)) else (len(r) if isinstance(r, list) and mode == "all" else int(r is not None))})
|
|
268
|
+
if stop:
|
|
269
|
+
emit({"stopped": i})
|
|
270
|
+
return
|
|
271
|
+
elif op == "results":
|
|
272
|
+
out = []
|
|
273
|
+
for s in req["inputs"]:
|
|
274
|
+
out.append(run(rx, mode, s, take))
|
|
275
|
+
emit({"results": out})
|
|
276
|
+
elif op == "compile":
|
|
277
|
+
n, runs = int(req.get("n") or 200), int(req.get("runs") or 5)
|
|
278
|
+
s = req["inputs"][0] if req.get("inputs") else ""
|
|
279
|
+
both, only = [], []
|
|
280
|
+
F = flags_of(mod, req.get("flags"))
|
|
281
|
+
for _ in range(runs):
|
|
282
|
+
t = time.perf_counter()
|
|
283
|
+
for _ in range(n):
|
|
284
|
+
mod.purge()
|
|
285
|
+
run(mod.compile(req["pattern"], F), mode, s, take)
|
|
286
|
+
both.append((time.perf_counter() - t) * 1e3 / n)
|
|
287
|
+
t = time.perf_counter()
|
|
288
|
+
for _ in range(n):
|
|
289
|
+
run(rx, mode, s, take)
|
|
290
|
+
only.append((time.perf_counter() - t) * 1e3 / n)
|
|
291
|
+
emit({"compile_ms": compile_ms, "per_call_compiled_each_ms": both, "per_call_precompiled_ms": only})
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
if __name__ == "__main__":
|
|
295
|
+
main()
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
// CodeCop's regex harness for Rust's `regex` crate (and `fancy-regex` when the request names it). One JSON request on
|
|
2
|
+
// stdin, JSON lines on stdout (see run_python.py). Runs only the pattern and strings it is given; it builds nothing
|
|
3
|
+
// from the repository. Built once per toolchain into CodeCop's cache with `cargo build --offline`.
|
|
4
|
+
use serde_json::{json, Value};
|
|
5
|
+
use std::io::{Read, Write};
|
|
6
|
+
use std::time::Instant;
|
|
7
|
+
|
|
8
|
+
enum Rx {
|
|
9
|
+
Std(regex::Regex),
|
|
10
|
+
Fancy(fancy_regex::Regex),
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
fn emit(v: Value) {
|
|
14
|
+
let mut o = std::io::stdout();
|
|
15
|
+
writeln!(o, "{}", v).ok();
|
|
16
|
+
o.flush().ok();
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
fn build(p: &str, flags: &str, mode: &str, engine: &str) -> Result<Rx, String> {
|
|
20
|
+
let mut f = String::new();
|
|
21
|
+
for c in flags.chars() {
|
|
22
|
+
if "imsxU".contains(c) {
|
|
23
|
+
f.push(c);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
let mut pat = if f.is_empty() { p.to_string() } else { format!("(?{}){}", f, p) };
|
|
27
|
+
if mode == "full" {
|
|
28
|
+
pat = format!("^(?:{})$", pat);
|
|
29
|
+
}
|
|
30
|
+
if engine == "fancy" {
|
|
31
|
+
fancy_regex::Regex::new(&pat).map(Rx::Fancy).map_err(|e| e.to_string())
|
|
32
|
+
} else {
|
|
33
|
+
regex::Regex::new(&pat).map(Rx::Std).map_err(|e| e.to_string())
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
fn caps_std(c: ®ex::Captures<'_>) -> Value {
|
|
38
|
+
let m = c.get(0).unwrap();
|
|
39
|
+
let mut o = vec![json!(m.start()), json!(m.end())];
|
|
40
|
+
for g in 1..c.len().min(21) {
|
|
41
|
+
o.push(match c.get(g) { Some(x) => json!([x.start(), x.end()]), None => Value::Null });
|
|
42
|
+
}
|
|
43
|
+
Value::Array(o)
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// fancy-regex changed its Captures type between versions: a macro reads either one
|
|
47
|
+
macro_rules! caps_fancy {
|
|
48
|
+
($c:expr) => {{
|
|
49
|
+
let c = $c;
|
|
50
|
+
let m = c.get(0).unwrap();
|
|
51
|
+
let mut o = vec![json!(m.start()), json!(m.end())];
|
|
52
|
+
for g in 1..c.len().min(21) {
|
|
53
|
+
o.push(match c.get(g) { Some(x) => json!([x.start(), x.end()]), None => Value::Null });
|
|
54
|
+
}
|
|
55
|
+
Value::Array(o)
|
|
56
|
+
}};
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
fn run(rx: &Rx, mode: &str, s: &str, take: usize) -> Value {
|
|
60
|
+
match rx {
|
|
61
|
+
Rx::Std(r) => match mode {
|
|
62
|
+
"bool" => json!(r.is_match(s)),
|
|
63
|
+
"count" => {
|
|
64
|
+
if take > 0 { json!(r.find_iter(s).take(take).count()) } else { json!(r.find_iter(s).count()) }
|
|
65
|
+
}
|
|
66
|
+
"match" => match r.captures(s) { Some(c) if c.get(0).unwrap().start() == 0 => caps_std(&c), _ => Value::Null },
|
|
67
|
+
"full" | "search" => match r.captures(s) { Some(c) => caps_std(&c), None => Value::Null },
|
|
68
|
+
_ => Value::Array(r.captures_iter(s).take(50).map(|c| caps_std(&c)).collect()),
|
|
69
|
+
},
|
|
70
|
+
Rx::Fancy(r) => match mode {
|
|
71
|
+
"bool" => json!(r.is_match(s).unwrap_or(false)),
|
|
72
|
+
"count" => {
|
|
73
|
+
let it = r.find_iter(s).filter_map(|x| x.ok());
|
|
74
|
+
if take > 0 { json!(it.take(take).count()) } else { json!(it.count()) }
|
|
75
|
+
}
|
|
76
|
+
"match" => match r.captures(s) { Ok(Some(c)) if c.get(0).unwrap().start() == 0 => caps_fancy!(&c), _ => Value::Null },
|
|
77
|
+
"full" | "search" => match r.captures(s) { Ok(Some(c)) => caps_fancy!(&c), _ => Value::Null },
|
|
78
|
+
_ => Value::Array(r.captures_iter(s).filter_map(|x| x.ok()).take(50).map(|c| caps_fancy!(&c)).collect()),
|
|
79
|
+
},
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
fn count(v: &Value, mode: &str) -> Value {
|
|
84
|
+
match v {
|
|
85
|
+
Value::Number(_) | Value::Bool(_) => v.clone(),
|
|
86
|
+
Value::Array(a) if mode == "all" => json!(a.len()),
|
|
87
|
+
Value::Null => json!(0),
|
|
88
|
+
_ => json!(1),
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
fn main() {
|
|
93
|
+
let mut buf = String::new();
|
|
94
|
+
std::io::stdin().read_to_string(&mut buf).ok();
|
|
95
|
+
let req: Value = match serde_json::from_str(&buf) { Ok(v) => v, Err(e) => { emit(json!({"error": "request", "detail": e.to_string()})); return; } };
|
|
96
|
+
let op = req["op"].as_str().unwrap_or("");
|
|
97
|
+
if op == "version" {
|
|
98
|
+
emit(json!({"engine": "rust-regex", "version": option_env!("CODECOP_REGEX_VERSIONS").unwrap_or("")}));
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
let pattern = req["pattern"].as_str().unwrap_or("");
|
|
102
|
+
let flags = req["flags"].as_str().unwrap_or("");
|
|
103
|
+
let mode = req["mode"].as_str().unwrap_or("search");
|
|
104
|
+
let engine = req["module"].as_str().unwrap_or("regex");
|
|
105
|
+
let take = req["take"].as_u64().unwrap_or(0) as usize;
|
|
106
|
+
let inputs: Vec<String> = req["inputs"].as_array().map(|a| a.iter().map(|x| x.as_str().unwrap_or("").to_string()).collect()).unwrap_or_default();
|
|
107
|
+
let t0 = Instant::now();
|
|
108
|
+
let rx = match build(pattern, flags, mode, engine) { Ok(r) => r, Err(e) => { emit(json!({"error": "compile", "detail": e.chars().take(200).collect::<String>()})); return; } };
|
|
109
|
+
let compile_ms = t0.elapsed().as_nanos() as f64 / 1e6;
|
|
110
|
+
let runs = req["runs"].as_u64().unwrap_or(3) as usize;
|
|
111
|
+
let budget = req["budget_ms"].as_f64().unwrap_or(1000.0);
|
|
112
|
+
match op {
|
|
113
|
+
"time" => {
|
|
114
|
+
for (i, s) in inputs.iter().enumerate() {
|
|
115
|
+
let mut ms = vec![];
|
|
116
|
+
let mut res = Value::Null;
|
|
117
|
+
let mut stop = false;
|
|
118
|
+
for _ in 0..runs {
|
|
119
|
+
let t = Instant::now();
|
|
120
|
+
res = run(&rx, mode, s, take);
|
|
121
|
+
let e = t.elapsed().as_nanos() as f64 / 1e6;
|
|
122
|
+
ms.push(e);
|
|
123
|
+
if e > budget { stop = true; break; }
|
|
124
|
+
}
|
|
125
|
+
emit(json!({"i": i, "len": s.len(), "ms": ms, "n": count(&res, mode)}));
|
|
126
|
+
if stop { emit(json!({"stopped": i})); return; }
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
"results" => {
|
|
130
|
+
let o: Vec<Value> = inputs.iter().map(|s| run(&rx, mode, s, take)).collect();
|
|
131
|
+
emit(json!({"results": o}));
|
|
132
|
+
}
|
|
133
|
+
"compile" => {
|
|
134
|
+
let n = req["n"].as_u64().unwrap_or(200) as usize;
|
|
135
|
+
let s = inputs.get(0).cloned().unwrap_or_default();
|
|
136
|
+
let (mut both, mut only) = (vec![], vec![]);
|
|
137
|
+
for _ in 0..runs.max(1) {
|
|
138
|
+
let t = Instant::now();
|
|
139
|
+
for _ in 0..n { if let Ok(x) = build(pattern, flags, mode, engine) { run(&x, mode, &s, take); } }
|
|
140
|
+
both.push(t.elapsed().as_nanos() as f64 / 1e6 / n as f64);
|
|
141
|
+
let t = Instant::now();
|
|
142
|
+
for _ in 0..n { run(&rx, mode, &s, take); }
|
|
143
|
+
only.push(t.elapsed().as_nanos() as f64 / 1e6 / n as f64);
|
|
144
|
+
}
|
|
145
|
+
emit(json!({"compile_ms": compile_ms, "per_call_compiled_each_ms": both, "per_call_precompiled_ms": only}));
|
|
146
|
+
}
|
|
147
|
+
_ => emit(json!({"error": "op"})),
|
|
148
|
+
}
|
|
149
|
+
}
|