ruby-anything 0.2.0 → 0.2.1
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 +9 -2
- package/README.md +15 -1
- package/adapters/node/harness.mjs +3 -1
- 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_java.py +510 -510
- package/adapters/polyglot/lang_rust.py +430 -430
- package/adapters/polyglot/lang_swift.py +337 -337
- package/adapters/ruby/harness.rb +134 -0
- package/package.json +3 -3
- package/src/adapters.js +60 -63
|
@@ -1,222 +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]
|
|
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]
|