ruby-anything 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/.claude-plugin/marketplace.json +12 -0
  2. package/.claude-plugin/plugin.json +7 -0
  3. package/.mcp.json +8 -0
  4. package/LICENSE +21 -0
  5. package/README.md +82 -2
  6. package/adapters/node/harness.mjs +324 -0
  7. package/adapters/node/package-lock.json +26 -0
  8. package/adapters/node/package.json +7 -0
  9. package/adapters/polyglot/harness.py +350 -0
  10. package/adapters/polyglot/lang_csharp.py +222 -0
  11. package/adapters/polyglot/lang_go.py +283 -0
  12. package/adapters/polyglot/lang_java.py +510 -0
  13. package/adapters/polyglot/lang_kotlin.py +133 -0
  14. package/adapters/polyglot/lang_php.py +156 -0
  15. package/adapters/polyglot/lang_ruby.py +148 -0
  16. package/adapters/polyglot/lang_rust.py +430 -0
  17. package/adapters/polyglot/lang_swift.py +337 -0
  18. package/adapters/python/harness.py +417 -0
  19. package/bin/ruby-anything.js +10 -0
  20. package/docs/assets/how-it-works-dark.svg +51 -0
  21. package/docs/assets/how-it-works-light.svg +51 -0
  22. package/harness/ruby_replay.rb +144 -0
  23. package/package.json +51 -4
  24. package/skills/ruby-anything/SKILL.md +130 -0
  25. package/skills/ruby-anything/frontend.md +64 -0
  26. package/skills/ruby-anything/languages/csharp.md +43 -0
  27. package/skills/ruby-anything/languages/go.md +36 -0
  28. package/skills/ruby-anything/languages/java.md +54 -0
  29. package/skills/ruby-anything/languages/javascript.md +50 -0
  30. package/skills/ruby-anything/languages/kotlin.md +27 -0
  31. package/skills/ruby-anything/languages/php.md +47 -0
  32. package/skills/ruby-anything/languages/python.md +49 -0
  33. package/skills/ruby-anything/languages/rust.md +31 -0
  34. package/skills/ruby-anything/languages/swift.md +27 -0
  35. package/skills/ruby-anything/whole-app.md +168 -0
  36. package/src/adapters.js +60 -0
  37. package/src/analyze.js +183 -0
  38. package/src/app.js +697 -0
  39. package/src/cli.js +75 -0
  40. package/src/detect.js +266 -0
  41. package/src/go.js +139 -0
  42. package/src/mcp.js +89 -0
  43. package/src/setup.js +106 -0
  44. package/src/units.js +444 -0
  45. package/src/util.js +312 -0
@@ -0,0 +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()
@@ -0,0 +1,222 @@
1
+ """C# support for the polyglot adapter.
2
+
3
+ Analysis: `public|internal static` methods of classes (regex, nothing executed).
4
+ Driver: all .cs files of the source tree plus a generated PpDriver.cs are compiled OFFLINE by
5
+ calling the SDK's Roslyn (`csc.dll`) directly against the reference pack, with a portable PDB so
6
+ exception stack frames carry line numbers. No NuGet restore / `dotnet build` is involved.
7
+ The driver decodes JSON args into the declared parameter types (System.Text.Json), calls the
8
+ method and maps exceptions to outcomes (type = exception class name, message as-is).
9
+ """
10
+ import glob
11
+ import json
12
+ import os
13
+ import re
14
+ import subprocess
15
+
16
+ from harness import match_brace, unit_record
17
+
18
+ EXTS = {".cs"}
19
+ THROW = r"\bthrow\b"
20
+ DOTNET = "/usr/lib/dotnet"
21
+ HEAP = "0x30000000" # 768MB GC cap: stops the runtime reserving hundreds of GB of address space (fits --as 8GB); W^X off: its memfd double-mapping hits RLIMIT_FSIZE (--fsize 16MB)
22
+ METHOD_RE = re.compile(
23
+ r"^[ \t]*(?:public|internal)\s+(?:(?:unsafe|new)\s+)*static\s+(?:(?:unsafe|extern)\s+)*([\w<>\[\],.?() ]+?)\s+(\w+)\s*(<[^>(]*>)?\s*\(([^)]*)\)\s*(?:where [^{=]*)?(\{|=>)",
24
+ re.M)
25
+ CLASS_RE = re.compile(r"\b(?:class|struct|record)\s+(\w+)")
26
+ NS_RE = re.compile(r"^\s*namespace\s+([\w.]+)", re.M)
27
+
28
+
29
+ def runtime():
30
+ vers = sorted(os.path.basename(p) for p in glob.glob(f"{DOTNET}/shared/Microsoft.NETCore.App/*"))
31
+ return ".NET " + (vers[-1] if vers else "?")
32
+
33
+
34
+ def imports(text):
35
+ return sorted(set(re.findall(r"^\s*using\s+(?:static\s+)?([\w.]+)\s*;", text, re.M)))
36
+
37
+
38
+ def split_top(raw):
39
+ parts, depth, cur = [], 0, ""
40
+ for c in raw:
41
+ if c in "<([":
42
+ depth += 1
43
+ elif c in ">)]":
44
+ depth -= 1
45
+ if c == "," and depth == 0:
46
+ parts.append(cur)
47
+ cur = ""
48
+ else:
49
+ cur += c
50
+ return parts + [cur]
51
+
52
+
53
+ def parse_params(raw):
54
+ params = []
55
+ for part in split_top(raw):
56
+ part = re.sub(r"\[[A-Za-z]\w*(\([^)]*\))?\]", "", part.split("=")[0]).strip() # attributes, default values
57
+ part = re.sub(r"^(this|params|in|ref|out)\s+", "", part)
58
+ if not part:
59
+ continue
60
+ typ, _, name = part.rpartition(" ")
61
+ params.append({"name": name, "annotation": typ.strip(), "default": None, "kind": "positional"})
62
+ return params
63
+
64
+
65
+ def analyze_file(rel, text):
66
+ ns = (NS_RE.search(text) or [None, "global"])[1]
67
+ classes = [(m.start(), m.group(1)) for m in CLASS_RE.finditer(text)]
68
+ units = []
69
+ for m in METHOD_RE.finditer(text):
70
+ if m.group(3) or m.group(2) == "Main": # generic methods and entrypoints are not recordable
71
+ continue
72
+ owner = next((n for pos, n in reversed(classes) if pos < m.start()), None)
73
+ if m.group(5) == "{":
74
+ end = match_brace(text, m.end() - 1)
75
+ else:
76
+ end = text.find(";", m.end())
77
+ unit = unit_record(rel, ns, m.group(2), m.start(), end, text, parse_params(m.group(4)),
78
+ m.group(1).strip(), THROW, owner=owner)
79
+ unit["kind"] = "function" # static methods are plain functions for recording purposes
80
+ units.append(unit)
81
+ return units
82
+
83
+
84
+ DRIVER = r'''using System;
85
+ using System.Collections.Generic;
86
+ using System.Diagnostics;
87
+ using System.Globalization;
88
+ using System.IO;
89
+ using System.Text.Json;
90
+ using System.Text.Json.Serialization;
91
+
92
+ static class PpDriver
93
+ {
94
+ sealed class DblConv : JsonConverter<double>
95
+ {
96
+ public override double Read(ref Utf8JsonReader r, Type t, JsonSerializerOptions o)
97
+ {
98
+ if (r.TokenType == JsonTokenType.StartObject)
99
+ {
100
+ using var d = JsonDocument.ParseValue(ref r);
101
+ string s = d.RootElement.GetProperty("$float").GetString();
102
+ switch (s)
103
+ {
104
+ case "nan": return double.NaN;
105
+ case "inf": return double.PositiveInfinity;
106
+ case "-inf": return double.NegativeInfinity;
107
+ case "-0.0": return -0.0;
108
+ }
109
+ return double.Parse(s, CultureInfo.InvariantCulture);
110
+ }
111
+ return r.GetDouble();
112
+ }
113
+
114
+ public override void Write(Utf8JsonWriter w, double v, JsonSerializerOptions o)
115
+ {
116
+ string tag = double.IsNaN(v) ? "nan" : double.IsPositiveInfinity(v) ? "inf" : double.IsNegativeInfinity(v) ? "-inf"
117
+ : (v == 0 && double.IsNegative(v)) ? "-0.0" : null;
118
+ if (tag != null) { w.WriteStartObject(); w.WriteString("$float", tag); w.WriteEndObject(); return; }
119
+ string txt = v.ToString("R", CultureInfo.InvariantCulture);
120
+ if (v == Math.Truncate(v) && Math.Abs(v) > 9007199254740992.0) { w.WriteStartObject(); w.WriteString("$float", txt); w.WriteEndObject(); return; }
121
+ if (txt.IndexOfAny(new[] { '.', 'E', 'e' }) < 0) txt += ".0";
122
+ w.WriteRawValue(txt);
123
+ }
124
+ }
125
+
126
+ static readonly JsonSerializerOptions Opt = new JsonSerializerOptions { Converters = { new DblConv() } };
127
+
128
+ static void Write(string json) => File.WriteAllText(Environment.GetEnvironmentVariable("PP_RESULT"), json);
129
+
130
+ static string Raise(string type, string msg, int line)
131
+ {
132
+ var o = new System.Collections.Generic.Dictionary<string, object> { ["kind"] = "raise", ["type"] = type, ["message"] = msg };
133
+ if (line > 0) o["raise_line"] = line;
134
+ return JsonSerializer.Serialize(o, Opt);
135
+ }
136
+
137
+ static string Outcome(Func<string> call)
138
+ {
139
+ try { return "{\"kind\":\"return\",\"value\":" + call() + "}"; }
140
+ catch (Exception ex)
141
+ {
142
+ int line = 0;
143
+ foreach (var f in new StackTrace(ex, true).GetFrames())
144
+ if (f.GetFileName() != null && Path.GetFileName(f.GetFileName()) == "__FILE__" && f.GetFileLineNumber() > 0) { line = f.GetFileLineNumber(); break; }
145
+ return Raise(ex.GetType().Name, ex.Message, line);
146
+ }
147
+ }
148
+
149
+ static int Main()
150
+ {
151
+ using var doc = JsonDocument.Parse(Console.In.ReadToEnd());
152
+ var root = doc.RootElement;
153
+ var args = root.GetProperty("args");
154
+ string mode = root.GetProperty("mode").GetString();
155
+ __DECODE__
156
+ Func<string> call = __CALL__;
157
+ if (mode == "bench")
158
+ {
159
+ int n = root.GetProperty("iterations").GetInt32();
160
+ var samples = new long[n];
161
+ for (int i = 0; i < n; i++)
162
+ {
163
+ long t0 = Stopwatch.GetTimestamp();
164
+ Outcome(call);
165
+ samples[i] = (Stopwatch.GetTimestamp() - t0) * 1000000000L / Stopwatch.Frequency;
166
+ }
167
+ Write("{\"samples_ns\":[" + string.Join(",", samples) + "]}");
168
+ return 0;
169
+ }
170
+ Write("{\"outcome\":" + Outcome(call) + "}");
171
+ return 0;
172
+ }
173
+ }
174
+ '''
175
+
176
+
177
+ def prepare(src, rel, unit, work):
178
+ if not unit["owner"]:
179
+ raise SystemExit("only static methods can be recorded")
180
+ ns = unit["module"]
181
+ qual = (f"{ns}." if ns != "global" else "") + f"{unit['owner']}.{unit['name']}"
182
+ decode, args = [], []
183
+ for i, p in enumerate(unit["params"]):
184
+ decode.append(f" {p['annotation']} a{i};\n"
185
+ f" try {{ a{i} = JsonSerializer.Deserialize<{p['annotation']}>(args[{i}].GetRawText(), Opt); }}\n"
186
+ f" catch (Exception e) {{ Write(\"{{\\\"outcome\\\":\" + Raise(\"TypeError\", e.Message, 0) + \"}}\"); return 0; }}")
187
+ args.append(f"a{i}")
188
+ call = f"{qual}({', '.join(args)})"
189
+ ret = unit["returns"]
190
+ if ret == "void":
191
+ lam = f"() => {{ {call}; return \"null\"; }}"
192
+ else:
193
+ lam = f"() => JsonSerializer.Serialize<{ret}>({call}, Opt)"
194
+ code = DRIVER.replace("__DECODE__", "\n".join(decode)).replace("__FILE__", os.path.basename(rel)).replace("__CALL__", lam)
195
+ open(os.path.join(work, "PpDriver.cs"), "w", encoding="utf-8").write(code)
196
+
197
+ csc = sorted(glob.glob(f"{DOTNET}/sdk/*/Roslyn/bincore/csc.dll"))[-1]
198
+ refdir = sorted(glob.glob(f"{DOTNET}/packs/Microsoft.NETCore.App.Ref/*/ref/net*"))[-1]
199
+ ver = os.path.basename(os.path.dirname(os.path.dirname(refdir)))
200
+ sources = [os.path.join(work, "PpDriver.cs")]
201
+ for root, dirs, names in os.walk(src):
202
+ dirs[:] = [d for d in dirs if d not in ("bin", "obj", ".git")]
203
+ sources += [os.path.join(root, n) for n in names if n.endswith(".cs")]
204
+ dll = os.path.join(work, "PpDriver.dll")
205
+ env = dict(os.environ, HOME=work, DOTNET_CLI_HOME=work, DOTNET_NOLOGO="1", DOTNET_CLI_TELEMETRY_OPTOUT="1",
206
+ DOTNET_SKIP_FIRST_TIME_EXPERIENCE="1", DOTNET_GCHeapHardLimit=HEAP, DOTNET_EnableWriteXorExecute="0", DOTNET_gcConcurrent="0", DOTNET_TieredCompilation="0")
207
+ cmd = ["dotnet", csc, "-nologo", "-noconfig", "-nostdlib+", "-target:exe", "-debug:portable", "-optimize+",
208
+ "-main:PpDriver", "-nullable-", "-parallel-", f"-out:{dll}"]
209
+ cmd += [f"-reference:{p}" for p in sorted(glob.glob(os.path.join(refdir, "*.dll")))] + sources
210
+ for _ in range(3): # thread creation can fail under a busy per-user RLIMIT_NPROC; Roslyn then crashes: retry
211
+ proc = subprocess.run(cmd, cwd=work, env=env, capture_output=True)
212
+ if proc.returncode == 0:
213
+ break
214
+ if proc.returncode != 0:
215
+ raise subprocess.CalledProcessError(proc.returncode, cmd, proc.stdout, proc.stderr)
216
+ rc = os.path.join(work, "PpDriver.runtimeconfig.json")
217
+ with open(rc, "w") as fh:
218
+ json.dump({"runtimeOptions": {"tfm": "net" + re.match(r"\d+\.\d+", ver).group(0), "rollForward": "LatestMajor",
219
+ "framework": {"name": "Microsoft.NETCore.App", "version": ver},
220
+ "configProperties": {"System.GC.Concurrent": False}}}, fh)
221
+ return ["env", "DOTNET_TieredCompilation=0", "DOTNET_gcConcurrent=0", "DOTNET_gcServer=0", f"DOTNET_GCHeapHardLimit={HEAP}", "DOTNET_EnableWriteXorExecute=0", "DOTNET_CLI_TELEMETRY_OPTOUT=1",
222
+ "DOTNET_NOLOGO=1", f"DOTNET_CLI_HOME={work}", "dotnet", "exec", "--runtimeconfig", rc, dll]