ruby-anything 0.2.1 → 0.2.3
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.
- package/.claude-plugin/marketplace.json +1 -1
- package/.claude-plugin/plugin.json +3 -2
- package/README.md +27 -2
- package/adapters/node/harness.mjs +350 -350
- package/adapters/node/package-lock.json +26 -26
- package/adapters/node/package.json +7 -7
- package/adapters/polyglot/harness.py +350 -350
- package/adapters/polyglot/lang_csharp.py +222 -222
- package/adapters/polyglot/lang_go.py +283 -283
- package/adapters/polyglot/lang_java.py +510 -510
- package/adapters/polyglot/lang_kotlin.py +133 -133
- package/adapters/polyglot/lang_php.py +156 -156
- package/adapters/polyglot/lang_ruby.py +148 -148
- package/adapters/polyglot/lang_rust.py +430 -430
- package/adapters/polyglot/lang_swift.py +337 -337
- package/adapters/python/harness.py +459 -459
- package/docs/assets/logo.png +0 -0
- package/docs/test-results.md +102 -0
- package/package.json +6 -3
- package/skills/ruby-anything/SKILL.md +74 -1
- package/src/adapters.js +63 -60
- package/src/cli.js +3 -0
- package/src/mcp.js +2 -1
- package/src/setup.js +32 -7
- package/src/status.js +77 -0
- package/adapters/ruby/harness.rb +0 -134
|
@@ -1,350 +1,350 @@
|
|
|
1
|
-
"""PortPilot polyglot adapter: one orchestrator for languages that need a generated driver.
|
|
2
|
-
|
|
3
|
-
Runs INSIDE the sandbox only (python3 is always present there). The language comes from the
|
|
4
|
-
PORTPILOT_LANGUAGE environment variable; `lang_<language>.py` next to this file supplies:
|
|
5
|
-
|
|
6
|
-
EXTS file extensions to analyze
|
|
7
|
-
SKIP_DIRS extra folders to skip (optional)
|
|
8
|
-
analyze_file(rel, text) -> list of unit dicts (static analysis; nothing is executed)
|
|
9
|
-
prepare(src, rel, unit, work) -> argv of a driver program, compiled in `work` (a /tmp copy)
|
|
10
|
-
|
|
11
|
-
Driver contract (every language): `argv` is run once per case with cwd = a fresh scratch dir.
|
|
12
|
-
stdin = one JSON object {"mode": "call"|"bench", "args": [...], "iterations": N}.
|
|
13
|
-
The driver writes ONE JSON object to the file named by env PP_RESULT:
|
|
14
|
-
call: {"outcome": {"kind": "return", "value": V} | {"kind": "raise", "type": T, "message": M, "raise_line": L?}}
|
|
15
|
-
bench: {"samples_ns": [...]}
|
|
16
|
-
Anything the user code prints goes to the driver's real stdout/stderr and is captured as the case output.
|
|
17
|
-
Values use the shared tagged encoding ($float for nan/inf/-0.0 and exact doubles).
|
|
18
|
-
"""
|
|
19
|
-
import base64
|
|
20
|
-
import hashlib
|
|
21
|
-
import importlib
|
|
22
|
-
import json
|
|
23
|
-
import math
|
|
24
|
-
import os
|
|
25
|
-
import random
|
|
26
|
-
import re
|
|
27
|
-
import shutil
|
|
28
|
-
import subprocess
|
|
29
|
-
import sys
|
|
30
|
-
import tempfile
|
|
31
|
-
import time
|
|
32
|
-
|
|
33
|
-
SRC = os.environ.get("PORTPILOT_SRC", "/work/src")
|
|
34
|
-
HERE = os.path.dirname(os.path.abspath(__file__))
|
|
35
|
-
LANG_NAME = os.environ.get("PORTPILOT_LANGUAGE", "")
|
|
36
|
-
REAL_STDOUT = sys.stdout
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
def emit(event, **data):
|
|
40
|
-
data["event"] = event
|
|
41
|
-
REAL_STDOUT.write(json.dumps(data, ensure_ascii=False, allow_nan=False) + "\n")
|
|
42
|
-
REAL_STDOUT.flush()
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
def load_lang():
|
|
46
|
-
if not re.fullmatch(r"[a-z]+", LANG_NAME or ""):
|
|
47
|
-
raise SystemExit("PORTPILOT_LANGUAGE missing")
|
|
48
|
-
sys.path.insert(0, HERE)
|
|
49
|
-
return importlib.import_module("lang_" + LANG_NAME)
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
# ------------------------------------------------------------------ shared static-analysis helpers
|
|
53
|
-
def line_of(text, index):
|
|
54
|
-
return text.count("\n", 0, index) + 1
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
def match_brace(text, open_index):
|
|
58
|
-
"""Index of the brace closing the one at open_index (skips strings and // # /* */ comments)."""
|
|
59
|
-
depth, i, n = 0, open_index, len(text)
|
|
60
|
-
while i < n:
|
|
61
|
-
c = text[i]
|
|
62
|
-
two = text[i:i + 2]
|
|
63
|
-
if two == "//" or c == "#" and LANG_NAME in ("php", "ruby"):
|
|
64
|
-
j = text.find("\n", i)
|
|
65
|
-
i = n if j < 0 else j
|
|
66
|
-
continue
|
|
67
|
-
if two == "/*":
|
|
68
|
-
j = text.find("*/", i + 2)
|
|
69
|
-
i = n if j < 0 else j + 2
|
|
70
|
-
continue
|
|
71
|
-
if c in "\"'`":
|
|
72
|
-
q, i = c, i + 1
|
|
73
|
-
while i < n and text[i] != q:
|
|
74
|
-
i += 2 if text[i] == "\\" else 1
|
|
75
|
-
elif c == "{":
|
|
76
|
-
depth += 1
|
|
77
|
-
elif c == "}":
|
|
78
|
-
depth -= 1
|
|
79
|
-
if depth == 0:
|
|
80
|
-
return i
|
|
81
|
-
i += 1
|
|
82
|
-
return n - 1
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
def leading_comment(text, start, prefixes=("//", "///", "*", "/**", "#")):
|
|
86
|
-
lines = text[:start].rstrip().split("\n")
|
|
87
|
-
out = []
|
|
88
|
-
while lines and lines[-1].strip().startswith(prefixes):
|
|
89
|
-
out.append(lines.pop().strip().lstrip("/*# ").rstrip("*/ ").strip())
|
|
90
|
-
return "\n".join(reversed([l for l in out if l])) or None
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
CALL_SKIP = {"if", "for", "while", "switch", "catch", "return", "func", "fn", "match", "new", "throw", "sizeof", "typeof",
|
|
94
|
-
"elif", "foreach", "using", "lock", "when", "guard", "defer", "panic", "print", "println"}
|
|
95
|
-
EFFECT_RULES = [
|
|
96
|
-
("filesystem", r"\b(os\.(Create|WriteFile|Remove|Mkdir)|ioutil\.|File\.(Write|Create|Delete|Open)|Files\.(write|delete|create)|fs::|std::fs|fopen|file_put_contents|unlink|mkdir|FileManager|FileWriter|File\.write|File\.open|Dir\.mkdir)"),
|
|
97
|
-
("network", r"\b(http\.(Get|Post|NewRequest)|net\.Dial|HttpClient|URLSession|reqwest|curl_|file_get_contents\(\s*['\"]https?|Net::HTTP|URL\(|Socket)"),
|
|
98
|
-
("database", r"\b(sql\.Open|gorm|DbContext|JDBC|DriverManager|PDO|mysqli|ActiveRecord|diesel|sqlx)"),
|
|
99
|
-
("process", r"\b(exec\.Command|Process\.Start|ProcessBuilder|Runtime\.getRuntime|std::process|proc_open|shell_exec|system\(|`)"),
|
|
100
|
-
("stdout", r"\b(fmt\.Print|Console\.Write|System\.out|println!|print!|echo |print\(|puts |printf|NSLog)"),
|
|
101
|
-
("nondeterminism", r"\b(time\.Now|rand\.|DateTime\.Now|Random\(|System\.currentTimeMillis|Instant\.now|SystemTime::now|thread_rng|mt_rand|rand\(|Time\.now|Date\(\)|UUID)"),
|
|
102
|
-
("environment", r"\b(os\.Getenv|Environment\.GetEnvironmentVariable|System\.getenv|std::env|getenv|ENV\[|ProcessInfo\.processInfo\.environment)"),
|
|
103
|
-
]
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
def unit_record(rel, module, name, start, end, text, params, returns, throw_words, owner=None):
|
|
107
|
-
body = text[start:end + 1]
|
|
108
|
-
line_start, line_end = line_of(text, start), line_of(text, end)
|
|
109
|
-
calls = sorted({m for m in re.findall(r"([A-Za-z_][\w.:]*)\s*[!]?\(", body) if m.split(".")[-1].split("::")[-1] not in CALL_SKIP and m != name})
|
|
110
|
-
throw_lines = [line_start + i for i, l in enumerate(body.split("\n")) if re.search(throw_words, l)]
|
|
111
|
-
complexity = 1 + len(re.findall(r"\b(if|for|while|case|catch|when|guard|elseif|elif|rescue)\b|&&|\|\||\?\s", body))
|
|
112
|
-
loops = len(re.findall(r"\b(for|while|loop|foreach|each)\b", body))
|
|
113
|
-
hints = ["nested loops: possible O(n^2) path - static hint, not measured"] if re.search(r"\b(for|while|foreach)\b[\s\S]*?\{[\s\S]*?\b(for|while|foreach)\b", body) else []
|
|
114
|
-
return {
|
|
115
|
-
"file": rel, "module": module, "name": name, "owner": owner,
|
|
116
|
-
"qualified_name": f"{module}.{owner + '.' if owner else ''}{name}", "kind": "method" if owner else "function",
|
|
117
|
-
"is_async": bool(re.search(r"\basync\b", body[:200])), "line_start": line_start, "line_end": line_end,
|
|
118
|
-
"params": params, "returns": returns, "docstring": leading_comment(text, start), "source": body,
|
|
119
|
-
"digest": "sha256:" + hashlib.sha256(body.encode()).hexdigest(), "calls": calls, "internal_deps": [],
|
|
120
|
-
"side_effects": sorted(k for k, rx in EFFECT_RULES if re.search(rx, body)), "complexity": complexity,
|
|
121
|
-
"loop_depth": 2 if hints else (1 if loops else 0), "perf_hints": hints, "raise_lines": throw_lines,
|
|
122
|
-
"loc": line_end - line_start + 1,
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
def analyze(lang):
|
|
127
|
-
skip = {".git", "vendor", "node_modules", "target", "bin", "obj", "build", "dist", ".build", ".gradle", "out"} | set(getattr(lang, "SKIP_DIRS", ()))
|
|
128
|
-
files = []
|
|
129
|
-
for root, dirs, names in os.walk(SRC):
|
|
130
|
-
dirs[:] = sorted(d for d in dirs if d not in skip and not d.startswith("."))
|
|
131
|
-
files += [os.path.join(root, n) for n in sorted(names) if os.path.splitext(n)[1] in lang.EXTS]
|
|
132
|
-
emit("log", message=f"found {len(files)} {LANG_NAME} files")
|
|
133
|
-
units = []
|
|
134
|
-
for path in files:
|
|
135
|
-
rel = os.path.relpath(path, SRC).replace(os.sep, "/")
|
|
136
|
-
text = open(path, encoding="utf-8", errors="replace").read()
|
|
137
|
-
imports = getattr(lang, "imports", lambda t: [])(text)
|
|
138
|
-
emit("file", path=rel, module=os.path.splitext(rel)[0].replace("/", "."), loc=text.count("\n") + 1,
|
|
139
|
-
imports=imports, external=[i for i in imports if "." in i or "/" in i], classes=[],
|
|
140
|
-
digest="sha256:" + hashlib.sha256(text.encode()).hexdigest())
|
|
141
|
-
units += lang.analyze_file(rel, text)
|
|
142
|
-
names = {u["name"] for u in units}
|
|
143
|
-
for u in units:
|
|
144
|
-
u["internal_deps"] = sorted({c.split(".")[-1].split("::")[-1] for c in u["calls"]} & names - {u["name"]})
|
|
145
|
-
emit("unit", **u)
|
|
146
|
-
emit("done")
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
# ------------------------------------------------------------------ value codec / input generation
|
|
150
|
-
def encode(v):
|
|
151
|
-
if isinstance(v, float):
|
|
152
|
-
if math.isnan(v):
|
|
153
|
-
return {"$float": "nan"}
|
|
154
|
-
if math.isinf(v):
|
|
155
|
-
return {"$float": "inf" if v > 0 else "-inf"}
|
|
156
|
-
if v == 0 and math.copysign(1, v) < 0:
|
|
157
|
-
return {"$float": "-0.0"}
|
|
158
|
-
if isinstance(v, list):
|
|
159
|
-
return [encode(x) for x in v]
|
|
160
|
-
return v
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
def kind_of(t):
|
|
164
|
-
t = (t or "").replace(" ", "")
|
|
165
|
-
if re.search(r"^(\[\]|Vec<|\w+\[\]$|List<|Array<|\[[A-Za-z]|array$|IEnumerable<|ArrayList<|IList<)", t) or t.endswith("[]"):
|
|
166
|
-
return "list"
|
|
167
|
-
tl = t.lower().lstrip("&").lstrip("?")
|
|
168
|
-
if re.fullmatch(r"(string|str|&str|char\*|charsequence)", tl):
|
|
169
|
-
return "string"
|
|
170
|
-
if re.fullmatch(r"(bool|boolean)", tl):
|
|
171
|
-
return "bool"
|
|
172
|
-
if re.fullmatch(r"(float|double|f32|f64|float32|float64|decimal|cgfloat)", tl):
|
|
173
|
-
return "float"
|
|
174
|
-
if re.fullmatch(r"(int|long|short|byte|i8|i16|i32|i64|isize|u8|u16|u32|u64|usize|int8|int16|int32|int64|uint|uint8|uint16|uint32|uint64|integer|nint)", tl):
|
|
175
|
-
return "int"
|
|
176
|
-
return "any"
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
POOLS = {
|
|
180
|
-
"string": ["", " ", "a", "Hello World", " multiple spaces ", "UPPER lower", "ünïcödé café", "emoji 😀 here", "-0", "1h30m", "x" * 300, "!!!"],
|
|
181
|
-
"int": [0, 1, -1, 2, 7, 255, 1000, 2 ** 31 - 1, -(2 ** 31)],
|
|
182
|
-
"float": [0.0, 1.5, -2.25, 1e-9, 1e9, {"$float": "-0.0"}, {"$float": "nan"}],
|
|
183
|
-
"bool": [True, False],
|
|
184
|
-
"list": [[], [1], [1, 2, 3], [5, -3, 5], [0, 0, 0]],
|
|
185
|
-
"any": ["", "a", 0, 1, -1],
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
def gen_value(rng, kind, mode):
|
|
190
|
-
if mode != "fuzz":
|
|
191
|
-
return rng.choice(POOLS[kind])
|
|
192
|
-
if kind == "string":
|
|
193
|
-
return "".join(rng.choice("abcXYZ019 -_.,!é\t") for _ in range(rng.randint(0, 24)))
|
|
194
|
-
if kind == "int":
|
|
195
|
-
return rng.choice([rng.randint(-10, 10), rng.randint(-10000, 10000)])
|
|
196
|
-
if kind == "float":
|
|
197
|
-
return rng.choice([round(rng.uniform(-1e6, 1e6), 3), float(rng.randint(-5, 5))])
|
|
198
|
-
if kind == "bool":
|
|
199
|
-
return rng.random() < 0.5
|
|
200
|
-
if kind == "list":
|
|
201
|
-
return [rng.randint(-50, 50) for _ in range(rng.randint(0, 6))]
|
|
202
|
-
return rng.choice([0, 1, "s"])
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
def generate(params, count, seed, mode):
|
|
206
|
-
rng, seen, out = random.Random(seed), set(), []
|
|
207
|
-
kinds = [kind_of(p.get("annotation")) for p in params]
|
|
208
|
-
for attempt in range(count * 20):
|
|
209
|
-
if len(out) >= count:
|
|
210
|
-
break
|
|
211
|
-
args = []
|
|
212
|
-
for i, k in enumerate(kinds):
|
|
213
|
-
pool = POOLS[k]
|
|
214
|
-
if mode != "fuzz" and i == 0 and len(out) < len(pool):
|
|
215
|
-
args.append(pool[len(out) % len(pool)])
|
|
216
|
-
else:
|
|
217
|
-
args.append(gen_value(rng, k, mode))
|
|
218
|
-
key = json.dumps(args, sort_keys=True)
|
|
219
|
-
if key not in seen:
|
|
220
|
-
seen.add(key)
|
|
221
|
-
out.append({"args": args, "kwargs": {}, "origin": "fuzz" if mode == "fuzz" else "generated"})
|
|
222
|
-
return out
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
# ------------------------------------------------------------------ running cases
|
|
226
|
-
def snapshot(root):
|
|
227
|
-
effects = []
|
|
228
|
-
for base, _dirs, files in os.walk(root):
|
|
229
|
-
for name in files:
|
|
230
|
-
full = os.path.join(base, name)
|
|
231
|
-
data = open(full, "rb").read()
|
|
232
|
-
effects.append({"path": os.path.relpath(full, root).replace(os.sep, "/"), "size": len(data),
|
|
233
|
-
"sha256": hashlib.sha256(data).hexdigest()})
|
|
234
|
-
return sorted(effects, key=lambda e: e["path"])
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
def run_driver(argv, payload, timeout=5):
|
|
238
|
-
with tempfile.TemporaryDirectory(prefix="pp-case-") as scratch, tempfile.TemporaryDirectory(prefix="pp-res-") as resdir:
|
|
239
|
-
result_file = os.path.join(resdir, "result.json")
|
|
240
|
-
env = dict(os.environ, PP_RESULT=result_file, HOME="/tmp")
|
|
241
|
-
started = time.perf_counter_ns()
|
|
242
|
-
try:
|
|
243
|
-
proc = subprocess.run(argv, input=json.dumps(payload).encode(), cwd=scratch, env=env,
|
|
244
|
-
capture_output=True, timeout=timeout)
|
|
245
|
-
out, err, code = proc.stdout.decode("utf-8", "replace"), proc.stderr.decode("utf-8", "replace"), proc.returncode
|
|
246
|
-
except subprocess.TimeoutExpired:
|
|
247
|
-
out, err, code = "", "", -9
|
|
248
|
-
duration = (time.perf_counter_ns() - started) // 1000
|
|
249
|
-
effects = snapshot(scratch)
|
|
250
|
-
result = None
|
|
251
|
-
if os.path.exists(result_file):
|
|
252
|
-
try:
|
|
253
|
-
result = json.load(open(result_file, encoding="utf-8"))
|
|
254
|
-
except ValueError: # killed mid-write (memory or time limit)
|
|
255
|
-
result = None
|
|
256
|
-
if result is not None:
|
|
257
|
-
pass
|
|
258
|
-
elif code == -9:
|
|
259
|
-
result = {"outcome": {"kind": "raise", "type": "Timeout", "message": f"case exceeded {timeout}s"}}
|
|
260
|
-
else: # crashed before writing a result (abort, segfault, uncaught runtime error)
|
|
261
|
-
result = {"outcome": {"kind": "raise", "type": "Crash", "message": f"exit status {code}: {err.strip()[-300:]}"}}
|
|
262
|
-
err = ""
|
|
263
|
-
return result, out, err, effects, duration
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
def fill_raise_line(outcome, unit_source, line_start, raise_lines):
|
|
267
|
-
"""Languages whose errors carry no line: pick the raise site whose quoted literal starts the message."""
|
|
268
|
-
if outcome.get("kind") != "raise" or outcome.get("raise_line") or not raise_lines:
|
|
269
|
-
return
|
|
270
|
-
msg = outcome.get("message", "")
|
|
271
|
-
lines = unit_source.split("\n")
|
|
272
|
-
for ln in raise_lines:
|
|
273
|
-
text = lines[ln - line_start] if 0 <= ln - line_start < len(lines) else ""
|
|
274
|
-
for lit in re.findall(r"[\"']([^\"'{}$%\\]{3,})", text):
|
|
275
|
-
if lit.strip() and msg.startswith(lit.strip()[:20]):
|
|
276
|
-
outcome["raise_line"] = ln
|
|
277
|
-
return
|
|
278
|
-
if len(raise_lines) == 1:
|
|
279
|
-
outcome["raise_line"] = raise_lines[0]
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
def find_unit(lang, rel, function):
|
|
283
|
-
path = os.path.realpath(os.path.join(SRC, rel))
|
|
284
|
-
if not path.startswith(os.path.realpath(SRC) + os.sep):
|
|
285
|
-
raise SystemExit("module_file escapes the source root")
|
|
286
|
-
text = open(path, encoding="utf-8", errors="replace").read()
|
|
287
|
-
for u in lang.analyze_file(rel, text):
|
|
288
|
-
if u["name"] == function:
|
|
289
|
-
return u
|
|
290
|
-
emit("fatal", message=f"{function} not found in {rel}")
|
|
291
|
-
sys.exit(2)
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
def build(lang, req):
|
|
295
|
-
unit = find_unit(lang, req["module_file"], req["function"])
|
|
296
|
-
work = tempfile.mkdtemp(prefix="pp-build-")
|
|
297
|
-
shutil.copytree(SRC, os.path.join(work, "src"), symlinks=False, dirs_exist_ok=True)
|
|
298
|
-
emit("log", message=f"building {LANG_NAME} driver for {req['function']}")
|
|
299
|
-
try:
|
|
300
|
-
argv = lang.prepare(os.path.join(work, "src"), req["module_file"], unit, work)
|
|
301
|
-
except subprocess.CalledProcessError as exc:
|
|
302
|
-
out = ((exc.stdout or b"") + (exc.stderr or b"")).decode("utf-8", "replace")
|
|
303
|
-
emit("fatal", message=f"driver build failed: {out.strip()[-1200:]}")
|
|
304
|
-
sys.exit(2)
|
|
305
|
-
return unit, argv
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
def record(lang, req):
|
|
309
|
-
unit, argv = build(lang, req)
|
|
310
|
-
cases = list(req.get("cases", []))
|
|
311
|
-
gen = req.get("generate") or {}
|
|
312
|
-
if gen.get("count"):
|
|
313
|
-
cases += generate(unit["params"], int(gen["count"]), int(gen.get("seed", 0)), gen.get("mode", "edge"))
|
|
314
|
-
runtime = getattr(lang, "runtime", lambda: LANG_NAME)()
|
|
315
|
-
emit("plan", total=len(cases), runtime=runtime)
|
|
316
|
-
for index, case in enumerate(cases):
|
|
317
|
-
results = []
|
|
318
|
-
for _ in range(2):
|
|
319
|
-
res, out, err, effects, dur = run_driver(argv, {"mode": "call", "args": case.get("args", []), "iterations": 1})
|
|
320
|
-
outcome = res.get("outcome", {})
|
|
321
|
-
fill_raise_line(outcome, unit["source"], unit["line_start"], unit["raise_lines"])
|
|
322
|
-
results.append({"outcome": outcome, "stdout": out, "stderr": err, "effects": effects, "duration_us": dur})
|
|
323
|
-
stable = json.dumps({k: results[0][k] for k in ("outcome", "stdout", "stderr", "effects")}, sort_keys=True) == \
|
|
324
|
-
json.dumps({k: results[1][k] for k in ("outcome", "stdout", "stderr", "effects")}, sort_keys=True)
|
|
325
|
-
emit("case", index=index, ref=case.get("ref"), origin=case.get("origin", "manual"), args=case.get("args", []),
|
|
326
|
-
kwargs=case.get("kwargs", {}), stable=stable, **results[0])
|
|
327
|
-
emit("done")
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
def bench(lang, req):
|
|
331
|
-
_unit, argv = build(lang, req)
|
|
332
|
-
iterations = max(1, min(int(req.get("iterations", 30)), 10000))
|
|
333
|
-
emit("plan", total=len(req["cases"]), runtime=LANG_NAME)
|
|
334
|
-
for case in req["cases"]:
|
|
335
|
-
res, *_ = run_driver(argv, {"mode": "bench", "args": case.get("args", []), "iterations": iterations}, timeout=120)
|
|
336
|
-
emit("case", ref=case.get("ref"), samples_ns=res.get("samples_ns", []), peak_memory_bytes=None)
|
|
337
|
-
emit("done")
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
def main():
|
|
341
|
-
req = json.loads(sys.stdin.read() or "{}")
|
|
342
|
-
lang = load_lang()
|
|
343
|
-
handlers = {"analyze": lambda: analyze(lang), "record": lambda: record(lang, req), "bench": lambda: bench(lang, req)}
|
|
344
|
-
if req.get("command") not in handlers:
|
|
345
|
-
raise SystemExit(f"unknown command {req.get('command')!r}")
|
|
346
|
-
handlers[req["command"]]()
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
if __name__ == "__main__":
|
|
350
|
-
main()
|
|
1
|
+
"""PortPilot polyglot adapter: one orchestrator for languages that need a generated driver.
|
|
2
|
+
|
|
3
|
+
Runs INSIDE the sandbox only (python3 is always present there). The language comes from the
|
|
4
|
+
PORTPILOT_LANGUAGE environment variable; `lang_<language>.py` next to this file supplies:
|
|
5
|
+
|
|
6
|
+
EXTS file extensions to analyze
|
|
7
|
+
SKIP_DIRS extra folders to skip (optional)
|
|
8
|
+
analyze_file(rel, text) -> list of unit dicts (static analysis; nothing is executed)
|
|
9
|
+
prepare(src, rel, unit, work) -> argv of a driver program, compiled in `work` (a /tmp copy)
|
|
10
|
+
|
|
11
|
+
Driver contract (every language): `argv` is run once per case with cwd = a fresh scratch dir.
|
|
12
|
+
stdin = one JSON object {"mode": "call"|"bench", "args": [...], "iterations": N}.
|
|
13
|
+
The driver writes ONE JSON object to the file named by env PP_RESULT:
|
|
14
|
+
call: {"outcome": {"kind": "return", "value": V} | {"kind": "raise", "type": T, "message": M, "raise_line": L?}}
|
|
15
|
+
bench: {"samples_ns": [...]}
|
|
16
|
+
Anything the user code prints goes to the driver's real stdout/stderr and is captured as the case output.
|
|
17
|
+
Values use the shared tagged encoding ($float for nan/inf/-0.0 and exact doubles).
|
|
18
|
+
"""
|
|
19
|
+
import base64
|
|
20
|
+
import hashlib
|
|
21
|
+
import importlib
|
|
22
|
+
import json
|
|
23
|
+
import math
|
|
24
|
+
import os
|
|
25
|
+
import random
|
|
26
|
+
import re
|
|
27
|
+
import shutil
|
|
28
|
+
import subprocess
|
|
29
|
+
import sys
|
|
30
|
+
import tempfile
|
|
31
|
+
import time
|
|
32
|
+
|
|
33
|
+
SRC = os.environ.get("PORTPILOT_SRC", "/work/src")
|
|
34
|
+
HERE = os.path.dirname(os.path.abspath(__file__))
|
|
35
|
+
LANG_NAME = os.environ.get("PORTPILOT_LANGUAGE", "")
|
|
36
|
+
REAL_STDOUT = sys.stdout
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def emit(event, **data):
|
|
40
|
+
data["event"] = event
|
|
41
|
+
REAL_STDOUT.write(json.dumps(data, ensure_ascii=False, allow_nan=False) + "\n")
|
|
42
|
+
REAL_STDOUT.flush()
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def load_lang():
|
|
46
|
+
if not re.fullmatch(r"[a-z]+", LANG_NAME or ""):
|
|
47
|
+
raise SystemExit("PORTPILOT_LANGUAGE missing")
|
|
48
|
+
sys.path.insert(0, HERE)
|
|
49
|
+
return importlib.import_module("lang_" + LANG_NAME)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
# ------------------------------------------------------------------ shared static-analysis helpers
|
|
53
|
+
def line_of(text, index):
|
|
54
|
+
return text.count("\n", 0, index) + 1
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def match_brace(text, open_index):
|
|
58
|
+
"""Index of the brace closing the one at open_index (skips strings and // # /* */ comments)."""
|
|
59
|
+
depth, i, n = 0, open_index, len(text)
|
|
60
|
+
while i < n:
|
|
61
|
+
c = text[i]
|
|
62
|
+
two = text[i:i + 2]
|
|
63
|
+
if two == "//" or c == "#" and LANG_NAME in ("php", "ruby"):
|
|
64
|
+
j = text.find("\n", i)
|
|
65
|
+
i = n if j < 0 else j
|
|
66
|
+
continue
|
|
67
|
+
if two == "/*":
|
|
68
|
+
j = text.find("*/", i + 2)
|
|
69
|
+
i = n if j < 0 else j + 2
|
|
70
|
+
continue
|
|
71
|
+
if c in "\"'`":
|
|
72
|
+
q, i = c, i + 1
|
|
73
|
+
while i < n and text[i] != q:
|
|
74
|
+
i += 2 if text[i] == "\\" else 1
|
|
75
|
+
elif c == "{":
|
|
76
|
+
depth += 1
|
|
77
|
+
elif c == "}":
|
|
78
|
+
depth -= 1
|
|
79
|
+
if depth == 0:
|
|
80
|
+
return i
|
|
81
|
+
i += 1
|
|
82
|
+
return n - 1
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def leading_comment(text, start, prefixes=("//", "///", "*", "/**", "#")):
|
|
86
|
+
lines = text[:start].rstrip().split("\n")
|
|
87
|
+
out = []
|
|
88
|
+
while lines and lines[-1].strip().startswith(prefixes):
|
|
89
|
+
out.append(lines.pop().strip().lstrip("/*# ").rstrip("*/ ").strip())
|
|
90
|
+
return "\n".join(reversed([l for l in out if l])) or None
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
CALL_SKIP = {"if", "for", "while", "switch", "catch", "return", "func", "fn", "match", "new", "throw", "sizeof", "typeof",
|
|
94
|
+
"elif", "foreach", "using", "lock", "when", "guard", "defer", "panic", "print", "println"}
|
|
95
|
+
EFFECT_RULES = [
|
|
96
|
+
("filesystem", r"\b(os\.(Create|WriteFile|Remove|Mkdir)|ioutil\.|File\.(Write|Create|Delete|Open)|Files\.(write|delete|create)|fs::|std::fs|fopen|file_put_contents|unlink|mkdir|FileManager|FileWriter|File\.write|File\.open|Dir\.mkdir)"),
|
|
97
|
+
("network", r"\b(http\.(Get|Post|NewRequest)|net\.Dial|HttpClient|URLSession|reqwest|curl_|file_get_contents\(\s*['\"]https?|Net::HTTP|URL\(|Socket)"),
|
|
98
|
+
("database", r"\b(sql\.Open|gorm|DbContext|JDBC|DriverManager|PDO|mysqli|ActiveRecord|diesel|sqlx)"),
|
|
99
|
+
("process", r"\b(exec\.Command|Process\.Start|ProcessBuilder|Runtime\.getRuntime|std::process|proc_open|shell_exec|system\(|`)"),
|
|
100
|
+
("stdout", r"\b(fmt\.Print|Console\.Write|System\.out|println!|print!|echo |print\(|puts |printf|NSLog)"),
|
|
101
|
+
("nondeterminism", r"\b(time\.Now|rand\.|DateTime\.Now|Random\(|System\.currentTimeMillis|Instant\.now|SystemTime::now|thread_rng|mt_rand|rand\(|Time\.now|Date\(\)|UUID)"),
|
|
102
|
+
("environment", r"\b(os\.Getenv|Environment\.GetEnvironmentVariable|System\.getenv|std::env|getenv|ENV\[|ProcessInfo\.processInfo\.environment)"),
|
|
103
|
+
]
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def unit_record(rel, module, name, start, end, text, params, returns, throw_words, owner=None):
|
|
107
|
+
body = text[start:end + 1]
|
|
108
|
+
line_start, line_end = line_of(text, start), line_of(text, end)
|
|
109
|
+
calls = sorted({m for m in re.findall(r"([A-Za-z_][\w.:]*)\s*[!]?\(", body) if m.split(".")[-1].split("::")[-1] not in CALL_SKIP and m != name})
|
|
110
|
+
throw_lines = [line_start + i for i, l in enumerate(body.split("\n")) if re.search(throw_words, l)]
|
|
111
|
+
complexity = 1 + len(re.findall(r"\b(if|for|while|case|catch|when|guard|elseif|elif|rescue)\b|&&|\|\||\?\s", body))
|
|
112
|
+
loops = len(re.findall(r"\b(for|while|loop|foreach|each)\b", body))
|
|
113
|
+
hints = ["nested loops: possible O(n^2) path - static hint, not measured"] if re.search(r"\b(for|while|foreach)\b[\s\S]*?\{[\s\S]*?\b(for|while|foreach)\b", body) else []
|
|
114
|
+
return {
|
|
115
|
+
"file": rel, "module": module, "name": name, "owner": owner,
|
|
116
|
+
"qualified_name": f"{module}.{owner + '.' if owner else ''}{name}", "kind": "method" if owner else "function",
|
|
117
|
+
"is_async": bool(re.search(r"\basync\b", body[:200])), "line_start": line_start, "line_end": line_end,
|
|
118
|
+
"params": params, "returns": returns, "docstring": leading_comment(text, start), "source": body,
|
|
119
|
+
"digest": "sha256:" + hashlib.sha256(body.encode()).hexdigest(), "calls": calls, "internal_deps": [],
|
|
120
|
+
"side_effects": sorted(k for k, rx in EFFECT_RULES if re.search(rx, body)), "complexity": complexity,
|
|
121
|
+
"loop_depth": 2 if hints else (1 if loops else 0), "perf_hints": hints, "raise_lines": throw_lines,
|
|
122
|
+
"loc": line_end - line_start + 1,
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def analyze(lang):
|
|
127
|
+
skip = {".git", "vendor", "node_modules", "target", "bin", "obj", "build", "dist", ".build", ".gradle", "out"} | set(getattr(lang, "SKIP_DIRS", ()))
|
|
128
|
+
files = []
|
|
129
|
+
for root, dirs, names in os.walk(SRC):
|
|
130
|
+
dirs[:] = sorted(d for d in dirs if d not in skip and not d.startswith("."))
|
|
131
|
+
files += [os.path.join(root, n) for n in sorted(names) if os.path.splitext(n)[1] in lang.EXTS]
|
|
132
|
+
emit("log", message=f"found {len(files)} {LANG_NAME} files")
|
|
133
|
+
units = []
|
|
134
|
+
for path in files:
|
|
135
|
+
rel = os.path.relpath(path, SRC).replace(os.sep, "/")
|
|
136
|
+
text = open(path, encoding="utf-8", errors="replace").read()
|
|
137
|
+
imports = getattr(lang, "imports", lambda t: [])(text)
|
|
138
|
+
emit("file", path=rel, module=os.path.splitext(rel)[0].replace("/", "."), loc=text.count("\n") + 1,
|
|
139
|
+
imports=imports, external=[i for i in imports if "." in i or "/" in i], classes=[],
|
|
140
|
+
digest="sha256:" + hashlib.sha256(text.encode()).hexdigest())
|
|
141
|
+
units += lang.analyze_file(rel, text)
|
|
142
|
+
names = {u["name"] for u in units}
|
|
143
|
+
for u in units:
|
|
144
|
+
u["internal_deps"] = sorted({c.split(".")[-1].split("::")[-1] for c in u["calls"]} & names - {u["name"]})
|
|
145
|
+
emit("unit", **u)
|
|
146
|
+
emit("done")
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
# ------------------------------------------------------------------ value codec / input generation
|
|
150
|
+
def encode(v):
|
|
151
|
+
if isinstance(v, float):
|
|
152
|
+
if math.isnan(v):
|
|
153
|
+
return {"$float": "nan"}
|
|
154
|
+
if math.isinf(v):
|
|
155
|
+
return {"$float": "inf" if v > 0 else "-inf"}
|
|
156
|
+
if v == 0 and math.copysign(1, v) < 0:
|
|
157
|
+
return {"$float": "-0.0"}
|
|
158
|
+
if isinstance(v, list):
|
|
159
|
+
return [encode(x) for x in v]
|
|
160
|
+
return v
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def kind_of(t):
|
|
164
|
+
t = (t or "").replace(" ", "")
|
|
165
|
+
if re.search(r"^(\[\]|Vec<|\w+\[\]$|List<|Array<|\[[A-Za-z]|array$|IEnumerable<|ArrayList<|IList<)", t) or t.endswith("[]"):
|
|
166
|
+
return "list"
|
|
167
|
+
tl = t.lower().lstrip("&").lstrip("?")
|
|
168
|
+
if re.fullmatch(r"(string|str|&str|char\*|charsequence)", tl):
|
|
169
|
+
return "string"
|
|
170
|
+
if re.fullmatch(r"(bool|boolean)", tl):
|
|
171
|
+
return "bool"
|
|
172
|
+
if re.fullmatch(r"(float|double|f32|f64|float32|float64|decimal|cgfloat)", tl):
|
|
173
|
+
return "float"
|
|
174
|
+
if re.fullmatch(r"(int|long|short|byte|i8|i16|i32|i64|isize|u8|u16|u32|u64|usize|int8|int16|int32|int64|uint|uint8|uint16|uint32|uint64|integer|nint)", tl):
|
|
175
|
+
return "int"
|
|
176
|
+
return "any"
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
POOLS = {
|
|
180
|
+
"string": ["", " ", "a", "Hello World", " multiple spaces ", "UPPER lower", "ünïcödé café", "emoji 😀 here", "-0", "1h30m", "x" * 300, "!!!"],
|
|
181
|
+
"int": [0, 1, -1, 2, 7, 255, 1000, 2 ** 31 - 1, -(2 ** 31)],
|
|
182
|
+
"float": [0.0, 1.5, -2.25, 1e-9, 1e9, {"$float": "-0.0"}, {"$float": "nan"}],
|
|
183
|
+
"bool": [True, False],
|
|
184
|
+
"list": [[], [1], [1, 2, 3], [5, -3, 5], [0, 0, 0]],
|
|
185
|
+
"any": ["", "a", 0, 1, -1],
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def gen_value(rng, kind, mode):
|
|
190
|
+
if mode != "fuzz":
|
|
191
|
+
return rng.choice(POOLS[kind])
|
|
192
|
+
if kind == "string":
|
|
193
|
+
return "".join(rng.choice("abcXYZ019 -_.,!é\t") for _ in range(rng.randint(0, 24)))
|
|
194
|
+
if kind == "int":
|
|
195
|
+
return rng.choice([rng.randint(-10, 10), rng.randint(-10000, 10000)])
|
|
196
|
+
if kind == "float":
|
|
197
|
+
return rng.choice([round(rng.uniform(-1e6, 1e6), 3), float(rng.randint(-5, 5))])
|
|
198
|
+
if kind == "bool":
|
|
199
|
+
return rng.random() < 0.5
|
|
200
|
+
if kind == "list":
|
|
201
|
+
return [rng.randint(-50, 50) for _ in range(rng.randint(0, 6))]
|
|
202
|
+
return rng.choice([0, 1, "s"])
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def generate(params, count, seed, mode):
|
|
206
|
+
rng, seen, out = random.Random(seed), set(), []
|
|
207
|
+
kinds = [kind_of(p.get("annotation")) for p in params]
|
|
208
|
+
for attempt in range(count * 20):
|
|
209
|
+
if len(out) >= count:
|
|
210
|
+
break
|
|
211
|
+
args = []
|
|
212
|
+
for i, k in enumerate(kinds):
|
|
213
|
+
pool = POOLS[k]
|
|
214
|
+
if mode != "fuzz" and i == 0 and len(out) < len(pool):
|
|
215
|
+
args.append(pool[len(out) % len(pool)])
|
|
216
|
+
else:
|
|
217
|
+
args.append(gen_value(rng, k, mode))
|
|
218
|
+
key = json.dumps(args, sort_keys=True)
|
|
219
|
+
if key not in seen:
|
|
220
|
+
seen.add(key)
|
|
221
|
+
out.append({"args": args, "kwargs": {}, "origin": "fuzz" if mode == "fuzz" else "generated"})
|
|
222
|
+
return out
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
# ------------------------------------------------------------------ running cases
|
|
226
|
+
def snapshot(root):
|
|
227
|
+
effects = []
|
|
228
|
+
for base, _dirs, files in os.walk(root):
|
|
229
|
+
for name in files:
|
|
230
|
+
full = os.path.join(base, name)
|
|
231
|
+
data = open(full, "rb").read()
|
|
232
|
+
effects.append({"path": os.path.relpath(full, root).replace(os.sep, "/"), "size": len(data),
|
|
233
|
+
"sha256": hashlib.sha256(data).hexdigest()})
|
|
234
|
+
return sorted(effects, key=lambda e: e["path"])
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def run_driver(argv, payload, timeout=5):
|
|
238
|
+
with tempfile.TemporaryDirectory(prefix="pp-case-") as scratch, tempfile.TemporaryDirectory(prefix="pp-res-") as resdir:
|
|
239
|
+
result_file = os.path.join(resdir, "result.json")
|
|
240
|
+
env = dict(os.environ, PP_RESULT=result_file, HOME="/tmp")
|
|
241
|
+
started = time.perf_counter_ns()
|
|
242
|
+
try:
|
|
243
|
+
proc = subprocess.run(argv, input=json.dumps(payload).encode(), cwd=scratch, env=env,
|
|
244
|
+
capture_output=True, timeout=timeout)
|
|
245
|
+
out, err, code = proc.stdout.decode("utf-8", "replace"), proc.stderr.decode("utf-8", "replace"), proc.returncode
|
|
246
|
+
except subprocess.TimeoutExpired:
|
|
247
|
+
out, err, code = "", "", -9
|
|
248
|
+
duration = (time.perf_counter_ns() - started) // 1000
|
|
249
|
+
effects = snapshot(scratch)
|
|
250
|
+
result = None
|
|
251
|
+
if os.path.exists(result_file):
|
|
252
|
+
try:
|
|
253
|
+
result = json.load(open(result_file, encoding="utf-8"))
|
|
254
|
+
except ValueError: # killed mid-write (memory or time limit)
|
|
255
|
+
result = None
|
|
256
|
+
if result is not None:
|
|
257
|
+
pass
|
|
258
|
+
elif code == -9:
|
|
259
|
+
result = {"outcome": {"kind": "raise", "type": "Timeout", "message": f"case exceeded {timeout}s"}}
|
|
260
|
+
else: # crashed before writing a result (abort, segfault, uncaught runtime error)
|
|
261
|
+
result = {"outcome": {"kind": "raise", "type": "Crash", "message": f"exit status {code}: {err.strip()[-300:]}"}}
|
|
262
|
+
err = ""
|
|
263
|
+
return result, out, err, effects, duration
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def fill_raise_line(outcome, unit_source, line_start, raise_lines):
|
|
267
|
+
"""Languages whose errors carry no line: pick the raise site whose quoted literal starts the message."""
|
|
268
|
+
if outcome.get("kind") != "raise" or outcome.get("raise_line") or not raise_lines:
|
|
269
|
+
return
|
|
270
|
+
msg = outcome.get("message", "")
|
|
271
|
+
lines = unit_source.split("\n")
|
|
272
|
+
for ln in raise_lines:
|
|
273
|
+
text = lines[ln - line_start] if 0 <= ln - line_start < len(lines) else ""
|
|
274
|
+
for lit in re.findall(r"[\"']([^\"'{}$%\\]{3,})", text):
|
|
275
|
+
if lit.strip() and msg.startswith(lit.strip()[:20]):
|
|
276
|
+
outcome["raise_line"] = ln
|
|
277
|
+
return
|
|
278
|
+
if len(raise_lines) == 1:
|
|
279
|
+
outcome["raise_line"] = raise_lines[0]
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def find_unit(lang, rel, function):
|
|
283
|
+
path = os.path.realpath(os.path.join(SRC, rel))
|
|
284
|
+
if not path.startswith(os.path.realpath(SRC) + os.sep):
|
|
285
|
+
raise SystemExit("module_file escapes the source root")
|
|
286
|
+
text = open(path, encoding="utf-8", errors="replace").read()
|
|
287
|
+
for u in lang.analyze_file(rel, text):
|
|
288
|
+
if u["name"] == function:
|
|
289
|
+
return u
|
|
290
|
+
emit("fatal", message=f"{function} not found in {rel}")
|
|
291
|
+
sys.exit(2)
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def build(lang, req):
|
|
295
|
+
unit = find_unit(lang, req["module_file"], req["function"])
|
|
296
|
+
work = tempfile.mkdtemp(prefix="pp-build-")
|
|
297
|
+
shutil.copytree(SRC, os.path.join(work, "src"), symlinks=False, dirs_exist_ok=True)
|
|
298
|
+
emit("log", message=f"building {LANG_NAME} driver for {req['function']}")
|
|
299
|
+
try:
|
|
300
|
+
argv = lang.prepare(os.path.join(work, "src"), req["module_file"], unit, work)
|
|
301
|
+
except subprocess.CalledProcessError as exc:
|
|
302
|
+
out = ((exc.stdout or b"") + (exc.stderr or b"")).decode("utf-8", "replace")
|
|
303
|
+
emit("fatal", message=f"driver build failed: {out.strip()[-1200:]}")
|
|
304
|
+
sys.exit(2)
|
|
305
|
+
return unit, argv
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def record(lang, req):
|
|
309
|
+
unit, argv = build(lang, req)
|
|
310
|
+
cases = list(req.get("cases", []))
|
|
311
|
+
gen = req.get("generate") or {}
|
|
312
|
+
if gen.get("count"):
|
|
313
|
+
cases += generate(unit["params"], int(gen["count"]), int(gen.get("seed", 0)), gen.get("mode", "edge"))
|
|
314
|
+
runtime = getattr(lang, "runtime", lambda: LANG_NAME)()
|
|
315
|
+
emit("plan", total=len(cases), runtime=runtime)
|
|
316
|
+
for index, case in enumerate(cases):
|
|
317
|
+
results = []
|
|
318
|
+
for _ in range(2):
|
|
319
|
+
res, out, err, effects, dur = run_driver(argv, {"mode": "call", "args": case.get("args", []), "iterations": 1})
|
|
320
|
+
outcome = res.get("outcome", {})
|
|
321
|
+
fill_raise_line(outcome, unit["source"], unit["line_start"], unit["raise_lines"])
|
|
322
|
+
results.append({"outcome": outcome, "stdout": out, "stderr": err, "effects": effects, "duration_us": dur})
|
|
323
|
+
stable = json.dumps({k: results[0][k] for k in ("outcome", "stdout", "stderr", "effects")}, sort_keys=True) == \
|
|
324
|
+
json.dumps({k: results[1][k] for k in ("outcome", "stdout", "stderr", "effects")}, sort_keys=True)
|
|
325
|
+
emit("case", index=index, ref=case.get("ref"), origin=case.get("origin", "manual"), args=case.get("args", []),
|
|
326
|
+
kwargs=case.get("kwargs", {}), stable=stable, **results[0])
|
|
327
|
+
emit("done")
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def bench(lang, req):
|
|
331
|
+
_unit, argv = build(lang, req)
|
|
332
|
+
iterations = max(1, min(int(req.get("iterations", 30)), 10000))
|
|
333
|
+
emit("plan", total=len(req["cases"]), runtime=LANG_NAME)
|
|
334
|
+
for case in req["cases"]:
|
|
335
|
+
res, *_ = run_driver(argv, {"mode": "bench", "args": case.get("args", []), "iterations": iterations}, timeout=120)
|
|
336
|
+
emit("case", ref=case.get("ref"), samples_ns=res.get("samples_ns", []), peak_memory_bytes=None)
|
|
337
|
+
emit("done")
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
def main():
|
|
341
|
+
req = json.loads(sys.stdin.read() or "{}")
|
|
342
|
+
lang = load_lang()
|
|
343
|
+
handlers = {"analyze": lambda: analyze(lang), "record": lambda: record(lang, req), "bench": lambda: bench(lang, req)}
|
|
344
|
+
if req.get("command") not in handlers:
|
|
345
|
+
raise SystemExit(f"unknown command {req.get('command')!r}")
|
|
346
|
+
handlers[req["command"]]()
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
if __name__ == "__main__":
|
|
350
|
+
main()
|