ruby-anything 0.2.0 → 0.2.2
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 +12 -12
- package/.claude-plugin/plugin.json +10 -2
- package/README.md +32 -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/docs/test-results.md +92 -0
- package/package.json +6 -4
- package/src/adapters.js +63 -63
|
@@ -1,430 +1,430 @@
|
|
|
1
|
-
"""Rust support for the polyglot adapter.
|
|
2
|
-
|
|
3
|
-
Analysis: free `fn` items (pub or private); fns inside `impl`/`trait` blocks are listed as kind=method
|
|
4
|
-
(not recordable); fns inside inline `mod` blocks and generic fns are skipped.
|
|
5
|
-
Driver: the target file is mounted as `#[path] mod target` in a generated main.rs (a private target fn is
|
|
6
|
-
made `pub` in the /tmp copy), with a hand-written JSON decoder/encoder (no crates, no serde), compiled
|
|
7
|
-
with plain `rustc`. `Result::Err(e)` -> raise type "Err"; panics -> raise type "panic" with the line.
|
|
8
|
-
"""
|
|
9
|
-
import os
|
|
10
|
-
import re
|
|
11
|
-
import subprocess
|
|
12
|
-
|
|
13
|
-
from harness import unit_record
|
|
14
|
-
|
|
15
|
-
EXTS = {".rs"}
|
|
16
|
-
THROW = r"\bpanic!\(|\bErr\(|\bunreachable!\(|\bassert!\("
|
|
17
|
-
FN_RE = re.compile(r'^[ \t]*((?:pub(?:\([^)]*\))?\s+)?(?:(?:const|async|unsafe|extern\s+"[^"]*")\s+)*fn\s+(\w+)\s*(<[^>]*>)?\s*\()', re.M)
|
|
18
|
-
BLOCK_RE = re.compile(r"^[ \t]*(?:pub(?:\([^)]*\))?\s+)?(?:unsafe\s+)?(impl|trait|mod)\b([^{;]*)\{", re.M)
|
|
19
|
-
CHAR_LIT = re.compile(r"'(?:\\.[^']*|[^\\'])'")
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
def runtime():
|
|
23
|
-
return subprocess.run(["rustc", "--version"], capture_output=True, text=True).stdout.strip()
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
def imports(text):
|
|
27
|
-
skip = {"std", "core", "alloc", "crate", "self", "super"}
|
|
28
|
-
return sorted({m for m in re.findall(r"^\s*(?:pub\s+)?use\s+(\w+)", text, re.M)} - skip)
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
def match_delim(text, i, open_c, close_c):
|
|
32
|
-
"""Index of the delimiter closing the one at i; skips strings, char literals (not lifetimes) and comments."""
|
|
33
|
-
depth, n = 0, len(text)
|
|
34
|
-
while i < n:
|
|
35
|
-
c, two = text[i], text[i:i + 2]
|
|
36
|
-
if two == "//":
|
|
37
|
-
j = text.find("\n", i)
|
|
38
|
-
i = n if j < 0 else j
|
|
39
|
-
continue
|
|
40
|
-
if two == "/*":
|
|
41
|
-
j = text.find("*/", i + 2)
|
|
42
|
-
i = n if j < 0 else j + 2
|
|
43
|
-
continue
|
|
44
|
-
if c == '"':
|
|
45
|
-
i += 1
|
|
46
|
-
while i < n and text[i] != '"':
|
|
47
|
-
i += 2 if text[i] == "\\" else 1
|
|
48
|
-
elif c == "'":
|
|
49
|
-
m = CHAR_LIT.match(text, i)
|
|
50
|
-
if m:
|
|
51
|
-
i = m.end() - 1
|
|
52
|
-
elif c == open_c:
|
|
53
|
-
depth += 1
|
|
54
|
-
elif c == close_c:
|
|
55
|
-
depth -= 1
|
|
56
|
-
if depth == 0:
|
|
57
|
-
return i
|
|
58
|
-
i += 1
|
|
59
|
-
return n - 1
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
def split_top(raw):
|
|
63
|
-
parts, depth, cur = [], 0, ""
|
|
64
|
-
for ch in raw:
|
|
65
|
-
if ch in "<([":
|
|
66
|
-
depth += 1
|
|
67
|
-
elif ch in ">)]":
|
|
68
|
-
depth -= 1
|
|
69
|
-
if ch == "," and depth == 0:
|
|
70
|
-
parts.append(cur)
|
|
71
|
-
cur = ""
|
|
72
|
-
else:
|
|
73
|
-
cur += ch
|
|
74
|
-
return [p.strip() for p in parts + [cur] if p.strip()]
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
def parse_params(raw):
|
|
78
|
-
params = []
|
|
79
|
-
for part in split_top(raw):
|
|
80
|
-
if re.fullmatch(r"&?\s*(mut\s+)?self(\s*:.*)?", part):
|
|
81
|
-
continue
|
|
82
|
-
name, _, typ = part.partition(":")
|
|
83
|
-
params.append({"name": re.sub(r"^mut\s+", "", name.strip()), "annotation": re.sub(r"&\s*'\w+\s+", "&", typ.strip()),
|
|
84
|
-
"default": None, "kind": "positional"})
|
|
85
|
-
return params
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
def analyze_file(rel, text):
|
|
89
|
-
module = os.path.splitext(rel)[0].replace("/", ".")
|
|
90
|
-
blocks = [] # (start, end, kind, owner)
|
|
91
|
-
for m in BLOCK_RE.finditer(text):
|
|
92
|
-
header = m.group(2).split(" where ")[0]
|
|
93
|
-
if m.group(1) == "impl":
|
|
94
|
-
header = header.split(" for ")[-1]
|
|
95
|
-
header = re.sub(r"^\s*<[^>]*>", "", header) # impl<T> generics
|
|
96
|
-
owner = (re.search(r"\w+", header) or [None])[0] if m.group(1) != "mod" else None
|
|
97
|
-
blocks.append((m.start(), match_delim(text, m.end() - 1, "{", "}"), m.group(1), owner))
|
|
98
|
-
units, done_to = [], -1
|
|
99
|
-
for m in FN_RE.finditer(text):
|
|
100
|
-
start, name = m.start(1), m.group(2)
|
|
101
|
-
if start < done_to or (m.group(3) and not re.fullmatch(r"<\s*('\w+\s*,?\s*)+>", m.group(3))):
|
|
102
|
-
continue # nested fn, or generic fn
|
|
103
|
-
inside = [b for b in blocks if b[0] < start < b[1]]
|
|
104
|
-
if any(b[2] == "mod" for b in inside):
|
|
105
|
-
continue
|
|
106
|
-
paren = m.end() - 1
|
|
107
|
-
close = match_delim(text, paren, "(", ")")
|
|
108
|
-
tail = re.match(r"\s*(?:->\s*([^{;]+?))?\s*(?:where[^{;]*)?([{;])", text[close + 1:])
|
|
109
|
-
if not tail or tail.group(2) == ";":
|
|
110
|
-
continue # bodiless trait method
|
|
111
|
-
end = match_delim(text, close + 1 + tail.end() - 1, "{", "}")
|
|
112
|
-
owner = inside[-1][3] if inside else None
|
|
113
|
-
if name == "main" and not owner:
|
|
114
|
-
continue
|
|
115
|
-
units.append(unit_record(rel, module, name, start, end, text, parse_params(text[paren + 1:close]),
|
|
116
|
-
(tail.group(1) or "").strip() or None, THROW, owner=owner))
|
|
117
|
-
done_to = end
|
|
118
|
-
return units
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
DRIVER = r'''#![allow(warnings)]
|
|
122
|
-
use std::fmt::Write as _;
|
|
123
|
-
use std::panic::{self, AssertUnwindSafe};
|
|
124
|
-
use std::sync::Mutex;
|
|
125
|
-
|
|
126
|
-
#[path = "__TARGET__"]
|
|
127
|
-
mod target;
|
|
128
|
-
|
|
129
|
-
#[derive(Clone)]
|
|
130
|
-
enum J { Null, Bool(bool), Num(String), Str(String), Arr(Vec<J>), Obj(Vec<(String, J)>) }
|
|
131
|
-
|
|
132
|
-
struct P<'a> { s: &'a [u8], i: usize }
|
|
133
|
-
|
|
134
|
-
impl<'a> P<'a> {
|
|
135
|
-
fn ws(&mut self) { while self.i < self.s.len() && (self.s[self.i] as char).is_ascii_whitespace() { self.i += 1; } }
|
|
136
|
-
fn val(&mut self) -> Result<J, String> {
|
|
137
|
-
self.ws();
|
|
138
|
-
if self.i >= self.s.len() { return Err("unexpected end of input".into()); }
|
|
139
|
-
match self.s[self.i] {
|
|
140
|
-
b'n' => { self.i += 4; Ok(J::Null) }
|
|
141
|
-
b't' => { self.i += 4; Ok(J::Bool(true)) }
|
|
142
|
-
b'f' => { self.i += 5; Ok(J::Bool(false)) }
|
|
143
|
-
b'"' => Ok(J::Str(self.string()?)),
|
|
144
|
-
b'[' => {
|
|
145
|
-
self.i += 1;
|
|
146
|
-
let mut v = vec![];
|
|
147
|
-
loop {
|
|
148
|
-
self.ws();
|
|
149
|
-
if self.s[self.i] == b']' { self.i += 1; break; }
|
|
150
|
-
v.push(self.val()?);
|
|
151
|
-
self.ws();
|
|
152
|
-
if self.s[self.i] == b',' { self.i += 1; }
|
|
153
|
-
}
|
|
154
|
-
Ok(J::Arr(v))
|
|
155
|
-
}
|
|
156
|
-
b'{' => {
|
|
157
|
-
self.i += 1;
|
|
158
|
-
let mut v = vec![];
|
|
159
|
-
loop {
|
|
160
|
-
self.ws();
|
|
161
|
-
if self.s[self.i] == b'}' { self.i += 1; break; }
|
|
162
|
-
let k = self.string()?;
|
|
163
|
-
self.ws();
|
|
164
|
-
self.i += 1; // ':'
|
|
165
|
-
v.push((k, self.val()?));
|
|
166
|
-
self.ws();
|
|
167
|
-
if self.s[self.i] == b',' { self.i += 1; }
|
|
168
|
-
}
|
|
169
|
-
Ok(J::Obj(v))
|
|
170
|
-
}
|
|
171
|
-
_ => {
|
|
172
|
-
let st = self.i;
|
|
173
|
-
while self.i < self.s.len() && matches!(self.s[self.i], b'-' | b'+' | b'.' | b'e' | b'E' | b'0'..=b'9') { self.i += 1; }
|
|
174
|
-
if st == self.i { return Err(format!("bad json at {}", st)); }
|
|
175
|
-
Ok(J::Num(String::from_utf8_lossy(&self.s[st..self.i]).into_owned()))
|
|
176
|
-
}
|
|
177
|
-
}
|
|
178
|
-
}
|
|
179
|
-
fn hex4(&mut self) -> Result<u32, String> {
|
|
180
|
-
let h = std::str::from_utf8(&self.s[self.i..self.i + 4]).map_err(|e| e.to_string())?;
|
|
181
|
-
self.i += 4;
|
|
182
|
-
u32::from_str_radix(h, 16).map_err(|e| e.to_string())
|
|
183
|
-
}
|
|
184
|
-
fn string(&mut self) -> Result<String, String> {
|
|
185
|
-
self.i += 1;
|
|
186
|
-
let mut out: Vec<u8> = Vec::new();
|
|
187
|
-
loop {
|
|
188
|
-
let c = self.s[self.i];
|
|
189
|
-
self.i += 1;
|
|
190
|
-
match c {
|
|
191
|
-
b'"' => break,
|
|
192
|
-
b'\\' => {
|
|
193
|
-
let e = self.s[self.i];
|
|
194
|
-
self.i += 1;
|
|
195
|
-
match e {
|
|
196
|
-
b'n' => out.push(b'\n'),
|
|
197
|
-
b't' => out.push(b'\t'),
|
|
198
|
-
b'r' => out.push(b'\r'),
|
|
199
|
-
b'b' => out.push(8),
|
|
200
|
-
b'f' => out.push(12),
|
|
201
|
-
b'u' => {
|
|
202
|
-
let mut cp = self.hex4()?;
|
|
203
|
-
if (0xD800..0xDC00).contains(&cp) && self.s[self.i] == b'\\' && self.s[self.i + 1] == b'u' {
|
|
204
|
-
self.i += 2;
|
|
205
|
-
let lo = self.hex4()?;
|
|
206
|
-
cp = 0x10000 + ((cp - 0xD800) << 10) + (lo - 0xDC00);
|
|
207
|
-
}
|
|
208
|
-
let ch = char::from_u32(cp).unwrap_or('\u{FFFD}');
|
|
209
|
-
let mut b = [0u8; 4];
|
|
210
|
-
out.extend_from_slice(ch.encode_utf8(&mut b).as_bytes());
|
|
211
|
-
}
|
|
212
|
-
o => out.push(o),
|
|
213
|
-
}
|
|
214
|
-
}
|
|
215
|
-
_ => out.push(c),
|
|
216
|
-
}
|
|
217
|
-
}
|
|
218
|
-
Ok(String::from_utf8_lossy(&out).into_owned())
|
|
219
|
-
}
|
|
220
|
-
}
|
|
221
|
-
|
|
222
|
-
trait Dec: Sized { fn dec(j: &J) -> Result<Self, String>; }
|
|
223
|
-
|
|
224
|
-
macro_rules! dec_int {
|
|
225
|
-
($($t:ty),*) => {$(
|
|
226
|
-
impl Dec for $t {
|
|
227
|
-
fn dec(j: &J) -> Result<Self, String> {
|
|
228
|
-
match j {
|
|
229
|
-
J::Num(s) => s.parse::<$t>().map_err(|e| format!("{}: {}", s, e)),
|
|
230
|
-
_ => Err(format!("expected integer for {}", stringify!($t))),
|
|
231
|
-
}
|
|
232
|
-
}
|
|
233
|
-
}
|
|
234
|
-
)*};
|
|
235
|
-
}
|
|
236
|
-
dec_int!(i8, i16, i32, i64, u8, u16, u32, u64, usize, isize);
|
|
237
|
-
|
|
238
|
-
fn special(s: &str) -> Result<f64, String> {
|
|
239
|
-
match s {
|
|
240
|
-
"nan" => Ok(f64::NAN),
|
|
241
|
-
"inf" => Ok(f64::INFINITY),
|
|
242
|
-
"-inf" => Ok(f64::NEG_INFINITY),
|
|
243
|
-
"-0.0" => Ok(-0.0f64),
|
|
244
|
-
o => o.parse::<f64>().map_err(|e| e.to_string()),
|
|
245
|
-
}
|
|
246
|
-
}
|
|
247
|
-
|
|
248
|
-
fn dec_f64(j: &J) -> Result<f64, String> {
|
|
249
|
-
match j {
|
|
250
|
-
J::Num(s) => s.parse::<f64>().map_err(|e| e.to_string()),
|
|
251
|
-
J::Obj(kv) => {
|
|
252
|
-
for (k, v) in kv {
|
|
253
|
-
if k == "$float" { if let J::Str(s) = v { return special(s); } }
|
|
254
|
-
}
|
|
255
|
-
Err("bad float tag".into())
|
|
256
|
-
}
|
|
257
|
-
_ => Err("expected float".into()),
|
|
258
|
-
}
|
|
259
|
-
}
|
|
260
|
-
|
|
261
|
-
impl Dec for f64 { fn dec(j: &J) -> Result<Self, String> { dec_f64(j) } }
|
|
262
|
-
impl Dec for f32 { fn dec(j: &J) -> Result<Self, String> { dec_f64(j).map(|x| x as f32) } }
|
|
263
|
-
impl Dec for bool { fn dec(j: &J) -> Result<Self, String> { if let J::Bool(b) = j { Ok(*b) } else { Err("expected bool".into()) } } }
|
|
264
|
-
impl Dec for String { fn dec(j: &J) -> Result<Self, String> { if let J::Str(s) = j { Ok(s.clone()) } else { Err("expected string".into()) } } }
|
|
265
|
-
impl<T: Dec> Dec for Vec<T> {
|
|
266
|
-
fn dec(j: &J) -> Result<Self, String> { if let J::Arr(v) = j { v.iter().map(T::dec).collect() } else { Err("expected array".into()) } }
|
|
267
|
-
}
|
|
268
|
-
impl<T: Dec> Dec for Option<T> {
|
|
269
|
-
fn dec(j: &J) -> Result<Self, String> { if let J::Null = j { Ok(None) } else { T::dec(j).map(Some) } }
|
|
270
|
-
}
|
|
271
|
-
|
|
272
|
-
trait Enc { fn enc(&self, o: &mut String); }
|
|
273
|
-
|
|
274
|
-
macro_rules! enc_int {
|
|
275
|
-
($($t:ty),*) => {$( impl Enc for $t { fn enc(&self, o: &mut String) { let _ = write!(o, "{}", self); } } )*};
|
|
276
|
-
}
|
|
277
|
-
enc_int!(i8, i16, i32, i64, u8, u16, u32, u64, usize, isize, bool);
|
|
278
|
-
|
|
279
|
-
fn enc_f64(x: f64, o: &mut String) {
|
|
280
|
-
if x.is_nan() { o.push_str("{\"$float\":\"nan\"}"); }
|
|
281
|
-
else if x.is_infinite() { o.push_str(if x > 0.0 { "{\"$float\":\"inf\"}" } else { "{\"$float\":\"-inf\"}" }); }
|
|
282
|
-
else if x == 0.0 && x.is_sign_negative() { o.push_str("{\"$float\":\"-0.0\"}"); }
|
|
283
|
-
else if x.abs() >= 1e16 || (x != 0.0 && x.abs() < 1e-4) { let _ = write!(o, "{:e}", x); }
|
|
284
|
-
else if x == x.trunc() { let _ = write!(o, "{:.1}", x); }
|
|
285
|
-
else { let _ = write!(o, "{}", x); }
|
|
286
|
-
}
|
|
287
|
-
|
|
288
|
-
fn esc(s: &str, o: &mut String) {
|
|
289
|
-
o.push('"');
|
|
290
|
-
for c in s.chars() {
|
|
291
|
-
match c {
|
|
292
|
-
'"' => o.push_str("\\\""),
|
|
293
|
-
'\\' => o.push_str("\\\\"),
|
|
294
|
-
'\n' => o.push_str("\\n"),
|
|
295
|
-
'\r' => o.push_str("\\r"),
|
|
296
|
-
'\t' => o.push_str("\\t"),
|
|
297
|
-
c if (c as u32) < 0x20 => { let _ = write!(o, "\\u{:04x}", c as u32); }
|
|
298
|
-
c => o.push(c),
|
|
299
|
-
}
|
|
300
|
-
}
|
|
301
|
-
o.push('"');
|
|
302
|
-
}
|
|
303
|
-
|
|
304
|
-
impl Enc for f64 { fn enc(&self, o: &mut String) { enc_f64(*self, o); } }
|
|
305
|
-
impl Enc for f32 { fn enc(&self, o: &mut String) { enc_f64(format!("{}", self).parse::<f64>().unwrap(), o); } }
|
|
306
|
-
impl Enc for String { fn enc(&self, o: &mut String) { esc(self, o); } }
|
|
307
|
-
impl Enc for str { fn enc(&self, o: &mut String) { esc(self, o); } }
|
|
308
|
-
impl Enc for () { fn enc(&self, o: &mut String) { o.push_str("null"); } }
|
|
309
|
-
impl<T: Enc> Enc for Vec<T> {
|
|
310
|
-
fn enc(&self, o: &mut String) {
|
|
311
|
-
o.push('[');
|
|
312
|
-
for (i, x) in self.iter().enumerate() { if i > 0 { o.push(','); } x.enc(o); }
|
|
313
|
-
o.push(']');
|
|
314
|
-
}
|
|
315
|
-
}
|
|
316
|
-
impl<T: Enc> Enc for Option<T> { fn enc(&self, o: &mut String) { match self { Some(x) => x.enc(o), None => o.push_str("null") } } }
|
|
317
|
-
|
|
318
|
-
static PANIC: Mutex<Option<(String, u32)>> = Mutex::new(None);
|
|
319
|
-
|
|
320
|
-
fn raise(t: &str, m: &str, line: u32) -> String {
|
|
321
|
-
let mut o = String::from("{\"kind\":\"raise\",\"type\":");
|
|
322
|
-
esc(t, &mut o);
|
|
323
|
-
o.push_str(",\"message\":");
|
|
324
|
-
esc(m, &mut o);
|
|
325
|
-
if line > 0 { let _ = write!(o, ",\"raise_line\":{}", line); }
|
|
326
|
-
o.push('}');
|
|
327
|
-
o
|
|
328
|
-
}
|
|
329
|
-
|
|
330
|
-
fn run(f: &dyn Fn() -> Result<String, String>) -> String {
|
|
331
|
-
match panic::catch_unwind(AssertUnwindSafe(|| f())) {
|
|
332
|
-
Ok(Ok(v)) => format!("{{\"kind\":\"return\",\"value\":{}}}", v),
|
|
333
|
-
Ok(Err(m)) => raise("Err", &m, 0),
|
|
334
|
-
Err(_) => {
|
|
335
|
-
let (m, l) = PANIC.lock().unwrap_or_else(|e| e.into_inner()).take().unwrap_or(("panic".to_string(), 0));
|
|
336
|
-
raise("panic", &m, l)
|
|
337
|
-
}
|
|
338
|
-
}
|
|
339
|
-
}
|
|
340
|
-
|
|
341
|
-
fn write_result(body: String) {
|
|
342
|
-
if let Ok(p) = std::env::var("PP_RESULT") { let _ = std::fs::write(p, body); }
|
|
343
|
-
}
|
|
344
|
-
|
|
345
|
-
fn finish(outcome: String) { write_result(format!("{{\"outcome\":{}}}", outcome)); }
|
|
346
|
-
|
|
347
|
-
fn main() {
|
|
348
|
-
panic::set_hook(Box::new(|info| {
|
|
349
|
-
let msg = if let Some(s) = info.payload().downcast_ref::<&str>() { s.to_string() }
|
|
350
|
-
else if let Some(s) = info.payload().downcast_ref::<String>() { s.clone() }
|
|
351
|
-
else { "panic".to_string() };
|
|
352
|
-
let line = info.location().filter(|l| l.file().ends_with("__FILE__")).map(|l| l.line()).unwrap_or(0);
|
|
353
|
-
*PANIC.lock().unwrap_or_else(|e| e.into_inner()) = Some((msg, line));
|
|
354
|
-
}));
|
|
355
|
-
let mut inp = String::new();
|
|
356
|
-
let _ = std::io::Read::read_to_string(&mut std::io::stdin(), &mut inp);
|
|
357
|
-
let req = P { s: inp.as_bytes(), i: 0 }.val().unwrap_or(J::Null);
|
|
358
|
-
let (mut mode, mut args, mut iters) = ("call".to_string(), Vec::<J>::new(), 1usize);
|
|
359
|
-
if let J::Obj(kv) = &req {
|
|
360
|
-
for (k, v) in kv {
|
|
361
|
-
match (k.as_str(), v) {
|
|
362
|
-
("mode", J::Str(s)) => mode = s.clone(),
|
|
363
|
-
("args", J::Arr(a)) => args = a.clone(),
|
|
364
|
-
("iterations", J::Num(n)) => iters = n.parse().unwrap_or(1),
|
|
365
|
-
_ => {}
|
|
366
|
-
}
|
|
367
|
-
}
|
|
368
|
-
}
|
|
369
|
-
__DECODE__
|
|
370
|
-
let call = || -> Result<String, String> {
|
|
371
|
-
__CALL__
|
|
372
|
-
};
|
|
373
|
-
if mode == "bench" {
|
|
374
|
-
let mut samples: Vec<u128> = Vec::new();
|
|
375
|
-
for _ in 0..iters {
|
|
376
|
-
let t = std::time::Instant::now();
|
|
377
|
-
let _ = run(&call);
|
|
378
|
-
samples.push(t.elapsed().as_nanos());
|
|
379
|
-
}
|
|
380
|
-
let list: Vec<String> = samples.iter().map(|s| s.to_string()).collect();
|
|
381
|
-
write_result(format!("{{\"samples_ns\":[{}]}}", list.join(",")));
|
|
382
|
-
return;
|
|
383
|
-
}
|
|
384
|
-
finish(run(&call));
|
|
385
|
-
}
|
|
386
|
-
'''
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
def prepare(src, rel, unit, work):
|
|
390
|
-
if unit["kind"] != "function":
|
|
391
|
-
raise SystemExit("only free Rust functions can be recorded")
|
|
392
|
-
path = os.path.join(src, rel)
|
|
393
|
-
text = open(path, encoding="utf-8").read()
|
|
394
|
-
if not unit["source"].startswith("pub"): # private fns become reachable from the driver
|
|
395
|
-
text = text.replace(unit["source"], "pub " + unit["source"], 1)
|
|
396
|
-
open(path, "w", encoding="utf-8").write(text)
|
|
397
|
-
|
|
398
|
-
decode, args = [], []
|
|
399
|
-
for i, p in enumerate(unit["params"]):
|
|
400
|
-
typ = p["annotation"]
|
|
401
|
-
by_ref = typ.startswith("&")
|
|
402
|
-
inner = typ.lstrip("&").strip()
|
|
403
|
-
owned = {"str": "String"}.get(inner, re.sub(r"^\[(.*)\]$", r"Vec<\1>", inner))
|
|
404
|
-
decode.append(f" let a{i}: {owned} = match args.get({i}).map(|j| <{owned} as Dec>::dec(j)) {{\n"
|
|
405
|
-
f" Some(Ok(v)) => v,\n"
|
|
406
|
-
f" Some(Err(e)) => {{ finish(raise(\"TypeError\", &e, 0)); return; }}\n"
|
|
407
|
-
f" None => {{ finish(raise(\"TypeError\", \"missing argument {i}\", 0)); return; }}\n }};")
|
|
408
|
-
args.append(f"&a{i}" if by_ref else f"a{i}.clone()")
|
|
409
|
-
call = f"target::{unit['name']}({', '.join(args)})"
|
|
410
|
-
ret = unit["returns"] or "()"
|
|
411
|
-
enc = "let mut o = String::new();\n Enc::enc(&v, &mut o);\n Ok(o)"
|
|
412
|
-
if ret.startswith("Result<") or re.match(r"^(\w+::)*Result<", ret):
|
|
413
|
-
err = split_top(ret[ret.index("<") + 1:ret.rindex(">")])
|
|
414
|
-
etype = err[1] if len(err) > 1 else "String"
|
|
415
|
-
shown = etype.split("::")[-1]
|
|
416
|
-
display = shown in ("String", "&str", "str") or etype.startswith("Box<") or len(err) < 2 or \
|
|
417
|
-
re.search(r"impl\s+(?:std::)?(?:fmt::)?Display\s+for\s+(?:\w+::)*" + re.escape(shown) + r"\b", text)
|
|
418
|
-
body = f" match {call} {{\n Ok(v) => {{ {enc} }}\n Err(e) => Err(format!(\"{'{}' if display else '{:?}'}\", e)),\n }}"
|
|
419
|
-
else:
|
|
420
|
-
body = f" let v = {call};\n {enc}"
|
|
421
|
-
driver = DRIVER.replace("__DECODE__", "\n".join(decode)).replace("__CALL__", body) \
|
|
422
|
-
.replace("__FILE__", os.path.basename(rel)).replace("__TARGET__", path)
|
|
423
|
-
drv_dir = os.path.join(work, "drv")
|
|
424
|
-
os.makedirs(drv_dir, exist_ok=True)
|
|
425
|
-
open(os.path.join(drv_dir, "main.rs"), "w", encoding="utf-8").write(driver)
|
|
426
|
-
out = os.path.join(work, "ppdrv")
|
|
427
|
-
subprocess.run(["rustc", "--edition", "2021", "-O", "-C", "debuginfo=0", "-C", "panic=unwind", "-C", "overflow-checks=on",
|
|
428
|
-
"-A", "warnings", "-o", out, os.path.join(drv_dir, "main.rs")],
|
|
429
|
-
cwd=work, env=dict(os.environ, HOME=work), check=True, capture_output=True)
|
|
430
|
-
return [out]
|
|
1
|
+
"""Rust support for the polyglot adapter.
|
|
2
|
+
|
|
3
|
+
Analysis: free `fn` items (pub or private); fns inside `impl`/`trait` blocks are listed as kind=method
|
|
4
|
+
(not recordable); fns inside inline `mod` blocks and generic fns are skipped.
|
|
5
|
+
Driver: the target file is mounted as `#[path] mod target` in a generated main.rs (a private target fn is
|
|
6
|
+
made `pub` in the /tmp copy), with a hand-written JSON decoder/encoder (no crates, no serde), compiled
|
|
7
|
+
with plain `rustc`. `Result::Err(e)` -> raise type "Err"; panics -> raise type "panic" with the line.
|
|
8
|
+
"""
|
|
9
|
+
import os
|
|
10
|
+
import re
|
|
11
|
+
import subprocess
|
|
12
|
+
|
|
13
|
+
from harness import unit_record
|
|
14
|
+
|
|
15
|
+
EXTS = {".rs"}
|
|
16
|
+
THROW = r"\bpanic!\(|\bErr\(|\bunreachable!\(|\bassert!\("
|
|
17
|
+
FN_RE = re.compile(r'^[ \t]*((?:pub(?:\([^)]*\))?\s+)?(?:(?:const|async|unsafe|extern\s+"[^"]*")\s+)*fn\s+(\w+)\s*(<[^>]*>)?\s*\()', re.M)
|
|
18
|
+
BLOCK_RE = re.compile(r"^[ \t]*(?:pub(?:\([^)]*\))?\s+)?(?:unsafe\s+)?(impl|trait|mod)\b([^{;]*)\{", re.M)
|
|
19
|
+
CHAR_LIT = re.compile(r"'(?:\\.[^']*|[^\\'])'")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def runtime():
|
|
23
|
+
return subprocess.run(["rustc", "--version"], capture_output=True, text=True).stdout.strip()
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def imports(text):
|
|
27
|
+
skip = {"std", "core", "alloc", "crate", "self", "super"}
|
|
28
|
+
return sorted({m for m in re.findall(r"^\s*(?:pub\s+)?use\s+(\w+)", text, re.M)} - skip)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def match_delim(text, i, open_c, close_c):
|
|
32
|
+
"""Index of the delimiter closing the one at i; skips strings, char literals (not lifetimes) and comments."""
|
|
33
|
+
depth, n = 0, len(text)
|
|
34
|
+
while i < n:
|
|
35
|
+
c, two = text[i], text[i:i + 2]
|
|
36
|
+
if two == "//":
|
|
37
|
+
j = text.find("\n", i)
|
|
38
|
+
i = n if j < 0 else j
|
|
39
|
+
continue
|
|
40
|
+
if two == "/*":
|
|
41
|
+
j = text.find("*/", i + 2)
|
|
42
|
+
i = n if j < 0 else j + 2
|
|
43
|
+
continue
|
|
44
|
+
if c == '"':
|
|
45
|
+
i += 1
|
|
46
|
+
while i < n and text[i] != '"':
|
|
47
|
+
i += 2 if text[i] == "\\" else 1
|
|
48
|
+
elif c == "'":
|
|
49
|
+
m = CHAR_LIT.match(text, i)
|
|
50
|
+
if m:
|
|
51
|
+
i = m.end() - 1
|
|
52
|
+
elif c == open_c:
|
|
53
|
+
depth += 1
|
|
54
|
+
elif c == close_c:
|
|
55
|
+
depth -= 1
|
|
56
|
+
if depth == 0:
|
|
57
|
+
return i
|
|
58
|
+
i += 1
|
|
59
|
+
return n - 1
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def split_top(raw):
|
|
63
|
+
parts, depth, cur = [], 0, ""
|
|
64
|
+
for ch in raw:
|
|
65
|
+
if ch in "<([":
|
|
66
|
+
depth += 1
|
|
67
|
+
elif ch in ">)]":
|
|
68
|
+
depth -= 1
|
|
69
|
+
if ch == "," and depth == 0:
|
|
70
|
+
parts.append(cur)
|
|
71
|
+
cur = ""
|
|
72
|
+
else:
|
|
73
|
+
cur += ch
|
|
74
|
+
return [p.strip() for p in parts + [cur] if p.strip()]
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def parse_params(raw):
|
|
78
|
+
params = []
|
|
79
|
+
for part in split_top(raw):
|
|
80
|
+
if re.fullmatch(r"&?\s*(mut\s+)?self(\s*:.*)?", part):
|
|
81
|
+
continue
|
|
82
|
+
name, _, typ = part.partition(":")
|
|
83
|
+
params.append({"name": re.sub(r"^mut\s+", "", name.strip()), "annotation": re.sub(r"&\s*'\w+\s+", "&", typ.strip()),
|
|
84
|
+
"default": None, "kind": "positional"})
|
|
85
|
+
return params
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def analyze_file(rel, text):
|
|
89
|
+
module = os.path.splitext(rel)[0].replace("/", ".")
|
|
90
|
+
blocks = [] # (start, end, kind, owner)
|
|
91
|
+
for m in BLOCK_RE.finditer(text):
|
|
92
|
+
header = m.group(2).split(" where ")[0]
|
|
93
|
+
if m.group(1) == "impl":
|
|
94
|
+
header = header.split(" for ")[-1]
|
|
95
|
+
header = re.sub(r"^\s*<[^>]*>", "", header) # impl<T> generics
|
|
96
|
+
owner = (re.search(r"\w+", header) or [None])[0] if m.group(1) != "mod" else None
|
|
97
|
+
blocks.append((m.start(), match_delim(text, m.end() - 1, "{", "}"), m.group(1), owner))
|
|
98
|
+
units, done_to = [], -1
|
|
99
|
+
for m in FN_RE.finditer(text):
|
|
100
|
+
start, name = m.start(1), m.group(2)
|
|
101
|
+
if start < done_to or (m.group(3) and not re.fullmatch(r"<\s*('\w+\s*,?\s*)+>", m.group(3))):
|
|
102
|
+
continue # nested fn, or generic fn
|
|
103
|
+
inside = [b for b in blocks if b[0] < start < b[1]]
|
|
104
|
+
if any(b[2] == "mod" for b in inside):
|
|
105
|
+
continue
|
|
106
|
+
paren = m.end() - 1
|
|
107
|
+
close = match_delim(text, paren, "(", ")")
|
|
108
|
+
tail = re.match(r"\s*(?:->\s*([^{;]+?))?\s*(?:where[^{;]*)?([{;])", text[close + 1:])
|
|
109
|
+
if not tail or tail.group(2) == ";":
|
|
110
|
+
continue # bodiless trait method
|
|
111
|
+
end = match_delim(text, close + 1 + tail.end() - 1, "{", "}")
|
|
112
|
+
owner = inside[-1][3] if inside else None
|
|
113
|
+
if name == "main" and not owner:
|
|
114
|
+
continue
|
|
115
|
+
units.append(unit_record(rel, module, name, start, end, text, parse_params(text[paren + 1:close]),
|
|
116
|
+
(tail.group(1) or "").strip() or None, THROW, owner=owner))
|
|
117
|
+
done_to = end
|
|
118
|
+
return units
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
DRIVER = r'''#![allow(warnings)]
|
|
122
|
+
use std::fmt::Write as _;
|
|
123
|
+
use std::panic::{self, AssertUnwindSafe};
|
|
124
|
+
use std::sync::Mutex;
|
|
125
|
+
|
|
126
|
+
#[path = "__TARGET__"]
|
|
127
|
+
mod target;
|
|
128
|
+
|
|
129
|
+
#[derive(Clone)]
|
|
130
|
+
enum J { Null, Bool(bool), Num(String), Str(String), Arr(Vec<J>), Obj(Vec<(String, J)>) }
|
|
131
|
+
|
|
132
|
+
struct P<'a> { s: &'a [u8], i: usize }
|
|
133
|
+
|
|
134
|
+
impl<'a> P<'a> {
|
|
135
|
+
fn ws(&mut self) { while self.i < self.s.len() && (self.s[self.i] as char).is_ascii_whitespace() { self.i += 1; } }
|
|
136
|
+
fn val(&mut self) -> Result<J, String> {
|
|
137
|
+
self.ws();
|
|
138
|
+
if self.i >= self.s.len() { return Err("unexpected end of input".into()); }
|
|
139
|
+
match self.s[self.i] {
|
|
140
|
+
b'n' => { self.i += 4; Ok(J::Null) }
|
|
141
|
+
b't' => { self.i += 4; Ok(J::Bool(true)) }
|
|
142
|
+
b'f' => { self.i += 5; Ok(J::Bool(false)) }
|
|
143
|
+
b'"' => Ok(J::Str(self.string()?)),
|
|
144
|
+
b'[' => {
|
|
145
|
+
self.i += 1;
|
|
146
|
+
let mut v = vec![];
|
|
147
|
+
loop {
|
|
148
|
+
self.ws();
|
|
149
|
+
if self.s[self.i] == b']' { self.i += 1; break; }
|
|
150
|
+
v.push(self.val()?);
|
|
151
|
+
self.ws();
|
|
152
|
+
if self.s[self.i] == b',' { self.i += 1; }
|
|
153
|
+
}
|
|
154
|
+
Ok(J::Arr(v))
|
|
155
|
+
}
|
|
156
|
+
b'{' => {
|
|
157
|
+
self.i += 1;
|
|
158
|
+
let mut v = vec![];
|
|
159
|
+
loop {
|
|
160
|
+
self.ws();
|
|
161
|
+
if self.s[self.i] == b'}' { self.i += 1; break; }
|
|
162
|
+
let k = self.string()?;
|
|
163
|
+
self.ws();
|
|
164
|
+
self.i += 1; // ':'
|
|
165
|
+
v.push((k, self.val()?));
|
|
166
|
+
self.ws();
|
|
167
|
+
if self.s[self.i] == b',' { self.i += 1; }
|
|
168
|
+
}
|
|
169
|
+
Ok(J::Obj(v))
|
|
170
|
+
}
|
|
171
|
+
_ => {
|
|
172
|
+
let st = self.i;
|
|
173
|
+
while self.i < self.s.len() && matches!(self.s[self.i], b'-' | b'+' | b'.' | b'e' | b'E' | b'0'..=b'9') { self.i += 1; }
|
|
174
|
+
if st == self.i { return Err(format!("bad json at {}", st)); }
|
|
175
|
+
Ok(J::Num(String::from_utf8_lossy(&self.s[st..self.i]).into_owned()))
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
fn hex4(&mut self) -> Result<u32, String> {
|
|
180
|
+
let h = std::str::from_utf8(&self.s[self.i..self.i + 4]).map_err(|e| e.to_string())?;
|
|
181
|
+
self.i += 4;
|
|
182
|
+
u32::from_str_radix(h, 16).map_err(|e| e.to_string())
|
|
183
|
+
}
|
|
184
|
+
fn string(&mut self) -> Result<String, String> {
|
|
185
|
+
self.i += 1;
|
|
186
|
+
let mut out: Vec<u8> = Vec::new();
|
|
187
|
+
loop {
|
|
188
|
+
let c = self.s[self.i];
|
|
189
|
+
self.i += 1;
|
|
190
|
+
match c {
|
|
191
|
+
b'"' => break,
|
|
192
|
+
b'\\' => {
|
|
193
|
+
let e = self.s[self.i];
|
|
194
|
+
self.i += 1;
|
|
195
|
+
match e {
|
|
196
|
+
b'n' => out.push(b'\n'),
|
|
197
|
+
b't' => out.push(b'\t'),
|
|
198
|
+
b'r' => out.push(b'\r'),
|
|
199
|
+
b'b' => out.push(8),
|
|
200
|
+
b'f' => out.push(12),
|
|
201
|
+
b'u' => {
|
|
202
|
+
let mut cp = self.hex4()?;
|
|
203
|
+
if (0xD800..0xDC00).contains(&cp) && self.s[self.i] == b'\\' && self.s[self.i + 1] == b'u' {
|
|
204
|
+
self.i += 2;
|
|
205
|
+
let lo = self.hex4()?;
|
|
206
|
+
cp = 0x10000 + ((cp - 0xD800) << 10) + (lo - 0xDC00);
|
|
207
|
+
}
|
|
208
|
+
let ch = char::from_u32(cp).unwrap_or('\u{FFFD}');
|
|
209
|
+
let mut b = [0u8; 4];
|
|
210
|
+
out.extend_from_slice(ch.encode_utf8(&mut b).as_bytes());
|
|
211
|
+
}
|
|
212
|
+
o => out.push(o),
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
_ => out.push(c),
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
Ok(String::from_utf8_lossy(&out).into_owned())
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
trait Dec: Sized { fn dec(j: &J) -> Result<Self, String>; }
|
|
223
|
+
|
|
224
|
+
macro_rules! dec_int {
|
|
225
|
+
($($t:ty),*) => {$(
|
|
226
|
+
impl Dec for $t {
|
|
227
|
+
fn dec(j: &J) -> Result<Self, String> {
|
|
228
|
+
match j {
|
|
229
|
+
J::Num(s) => s.parse::<$t>().map_err(|e| format!("{}: {}", s, e)),
|
|
230
|
+
_ => Err(format!("expected integer for {}", stringify!($t))),
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
)*};
|
|
235
|
+
}
|
|
236
|
+
dec_int!(i8, i16, i32, i64, u8, u16, u32, u64, usize, isize);
|
|
237
|
+
|
|
238
|
+
fn special(s: &str) -> Result<f64, String> {
|
|
239
|
+
match s {
|
|
240
|
+
"nan" => Ok(f64::NAN),
|
|
241
|
+
"inf" => Ok(f64::INFINITY),
|
|
242
|
+
"-inf" => Ok(f64::NEG_INFINITY),
|
|
243
|
+
"-0.0" => Ok(-0.0f64),
|
|
244
|
+
o => o.parse::<f64>().map_err(|e| e.to_string()),
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
fn dec_f64(j: &J) -> Result<f64, String> {
|
|
249
|
+
match j {
|
|
250
|
+
J::Num(s) => s.parse::<f64>().map_err(|e| e.to_string()),
|
|
251
|
+
J::Obj(kv) => {
|
|
252
|
+
for (k, v) in kv {
|
|
253
|
+
if k == "$float" { if let J::Str(s) = v { return special(s); } }
|
|
254
|
+
}
|
|
255
|
+
Err("bad float tag".into())
|
|
256
|
+
}
|
|
257
|
+
_ => Err("expected float".into()),
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
impl Dec for f64 { fn dec(j: &J) -> Result<Self, String> { dec_f64(j) } }
|
|
262
|
+
impl Dec for f32 { fn dec(j: &J) -> Result<Self, String> { dec_f64(j).map(|x| x as f32) } }
|
|
263
|
+
impl Dec for bool { fn dec(j: &J) -> Result<Self, String> { if let J::Bool(b) = j { Ok(*b) } else { Err("expected bool".into()) } } }
|
|
264
|
+
impl Dec for String { fn dec(j: &J) -> Result<Self, String> { if let J::Str(s) = j { Ok(s.clone()) } else { Err("expected string".into()) } } }
|
|
265
|
+
impl<T: Dec> Dec for Vec<T> {
|
|
266
|
+
fn dec(j: &J) -> Result<Self, String> { if let J::Arr(v) = j { v.iter().map(T::dec).collect() } else { Err("expected array".into()) } }
|
|
267
|
+
}
|
|
268
|
+
impl<T: Dec> Dec for Option<T> {
|
|
269
|
+
fn dec(j: &J) -> Result<Self, String> { if let J::Null = j { Ok(None) } else { T::dec(j).map(Some) } }
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
trait Enc { fn enc(&self, o: &mut String); }
|
|
273
|
+
|
|
274
|
+
macro_rules! enc_int {
|
|
275
|
+
($($t:ty),*) => {$( impl Enc for $t { fn enc(&self, o: &mut String) { let _ = write!(o, "{}", self); } } )*};
|
|
276
|
+
}
|
|
277
|
+
enc_int!(i8, i16, i32, i64, u8, u16, u32, u64, usize, isize, bool);
|
|
278
|
+
|
|
279
|
+
fn enc_f64(x: f64, o: &mut String) {
|
|
280
|
+
if x.is_nan() { o.push_str("{\"$float\":\"nan\"}"); }
|
|
281
|
+
else if x.is_infinite() { o.push_str(if x > 0.0 { "{\"$float\":\"inf\"}" } else { "{\"$float\":\"-inf\"}" }); }
|
|
282
|
+
else if x == 0.0 && x.is_sign_negative() { o.push_str("{\"$float\":\"-0.0\"}"); }
|
|
283
|
+
else if x.abs() >= 1e16 || (x != 0.0 && x.abs() < 1e-4) { let _ = write!(o, "{:e}", x); }
|
|
284
|
+
else if x == x.trunc() { let _ = write!(o, "{:.1}", x); }
|
|
285
|
+
else { let _ = write!(o, "{}", x); }
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
fn esc(s: &str, o: &mut String) {
|
|
289
|
+
o.push('"');
|
|
290
|
+
for c in s.chars() {
|
|
291
|
+
match c {
|
|
292
|
+
'"' => o.push_str("\\\""),
|
|
293
|
+
'\\' => o.push_str("\\\\"),
|
|
294
|
+
'\n' => o.push_str("\\n"),
|
|
295
|
+
'\r' => o.push_str("\\r"),
|
|
296
|
+
'\t' => o.push_str("\\t"),
|
|
297
|
+
c if (c as u32) < 0x20 => { let _ = write!(o, "\\u{:04x}", c as u32); }
|
|
298
|
+
c => o.push(c),
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
o.push('"');
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
impl Enc for f64 { fn enc(&self, o: &mut String) { enc_f64(*self, o); } }
|
|
305
|
+
impl Enc for f32 { fn enc(&self, o: &mut String) { enc_f64(format!("{}", self).parse::<f64>().unwrap(), o); } }
|
|
306
|
+
impl Enc for String { fn enc(&self, o: &mut String) { esc(self, o); } }
|
|
307
|
+
impl Enc for str { fn enc(&self, o: &mut String) { esc(self, o); } }
|
|
308
|
+
impl Enc for () { fn enc(&self, o: &mut String) { o.push_str("null"); } }
|
|
309
|
+
impl<T: Enc> Enc for Vec<T> {
|
|
310
|
+
fn enc(&self, o: &mut String) {
|
|
311
|
+
o.push('[');
|
|
312
|
+
for (i, x) in self.iter().enumerate() { if i > 0 { o.push(','); } x.enc(o); }
|
|
313
|
+
o.push(']');
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
impl<T: Enc> Enc for Option<T> { fn enc(&self, o: &mut String) { match self { Some(x) => x.enc(o), None => o.push_str("null") } } }
|
|
317
|
+
|
|
318
|
+
static PANIC: Mutex<Option<(String, u32)>> = Mutex::new(None);
|
|
319
|
+
|
|
320
|
+
fn raise(t: &str, m: &str, line: u32) -> String {
|
|
321
|
+
let mut o = String::from("{\"kind\":\"raise\",\"type\":");
|
|
322
|
+
esc(t, &mut o);
|
|
323
|
+
o.push_str(",\"message\":");
|
|
324
|
+
esc(m, &mut o);
|
|
325
|
+
if line > 0 { let _ = write!(o, ",\"raise_line\":{}", line); }
|
|
326
|
+
o.push('}');
|
|
327
|
+
o
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
fn run(f: &dyn Fn() -> Result<String, String>) -> String {
|
|
331
|
+
match panic::catch_unwind(AssertUnwindSafe(|| f())) {
|
|
332
|
+
Ok(Ok(v)) => format!("{{\"kind\":\"return\",\"value\":{}}}", v),
|
|
333
|
+
Ok(Err(m)) => raise("Err", &m, 0),
|
|
334
|
+
Err(_) => {
|
|
335
|
+
let (m, l) = PANIC.lock().unwrap_or_else(|e| e.into_inner()).take().unwrap_or(("panic".to_string(), 0));
|
|
336
|
+
raise("panic", &m, l)
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
fn write_result(body: String) {
|
|
342
|
+
if let Ok(p) = std::env::var("PP_RESULT") { let _ = std::fs::write(p, body); }
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
fn finish(outcome: String) { write_result(format!("{{\"outcome\":{}}}", outcome)); }
|
|
346
|
+
|
|
347
|
+
fn main() {
|
|
348
|
+
panic::set_hook(Box::new(|info| {
|
|
349
|
+
let msg = if let Some(s) = info.payload().downcast_ref::<&str>() { s.to_string() }
|
|
350
|
+
else if let Some(s) = info.payload().downcast_ref::<String>() { s.clone() }
|
|
351
|
+
else { "panic".to_string() };
|
|
352
|
+
let line = info.location().filter(|l| l.file().ends_with("__FILE__")).map(|l| l.line()).unwrap_or(0);
|
|
353
|
+
*PANIC.lock().unwrap_or_else(|e| e.into_inner()) = Some((msg, line));
|
|
354
|
+
}));
|
|
355
|
+
let mut inp = String::new();
|
|
356
|
+
let _ = std::io::Read::read_to_string(&mut std::io::stdin(), &mut inp);
|
|
357
|
+
let req = P { s: inp.as_bytes(), i: 0 }.val().unwrap_or(J::Null);
|
|
358
|
+
let (mut mode, mut args, mut iters) = ("call".to_string(), Vec::<J>::new(), 1usize);
|
|
359
|
+
if let J::Obj(kv) = &req {
|
|
360
|
+
for (k, v) in kv {
|
|
361
|
+
match (k.as_str(), v) {
|
|
362
|
+
("mode", J::Str(s)) => mode = s.clone(),
|
|
363
|
+
("args", J::Arr(a)) => args = a.clone(),
|
|
364
|
+
("iterations", J::Num(n)) => iters = n.parse().unwrap_or(1),
|
|
365
|
+
_ => {}
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
__DECODE__
|
|
370
|
+
let call = || -> Result<String, String> {
|
|
371
|
+
__CALL__
|
|
372
|
+
};
|
|
373
|
+
if mode == "bench" {
|
|
374
|
+
let mut samples: Vec<u128> = Vec::new();
|
|
375
|
+
for _ in 0..iters {
|
|
376
|
+
let t = std::time::Instant::now();
|
|
377
|
+
let _ = run(&call);
|
|
378
|
+
samples.push(t.elapsed().as_nanos());
|
|
379
|
+
}
|
|
380
|
+
let list: Vec<String> = samples.iter().map(|s| s.to_string()).collect();
|
|
381
|
+
write_result(format!("{{\"samples_ns\":[{}]}}", list.join(",")));
|
|
382
|
+
return;
|
|
383
|
+
}
|
|
384
|
+
finish(run(&call));
|
|
385
|
+
}
|
|
386
|
+
'''
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
def prepare(src, rel, unit, work):
|
|
390
|
+
if unit["kind"] != "function":
|
|
391
|
+
raise SystemExit("only free Rust functions can be recorded")
|
|
392
|
+
path = os.path.join(src, rel)
|
|
393
|
+
text = open(path, encoding="utf-8").read()
|
|
394
|
+
if not unit["source"].startswith("pub"): # private fns become reachable from the driver
|
|
395
|
+
text = text.replace(unit["source"], "pub " + unit["source"], 1)
|
|
396
|
+
open(path, "w", encoding="utf-8").write(text)
|
|
397
|
+
|
|
398
|
+
decode, args = [], []
|
|
399
|
+
for i, p in enumerate(unit["params"]):
|
|
400
|
+
typ = p["annotation"]
|
|
401
|
+
by_ref = typ.startswith("&")
|
|
402
|
+
inner = typ.lstrip("&").strip()
|
|
403
|
+
owned = {"str": "String"}.get(inner, re.sub(r"^\[(.*)\]$", r"Vec<\1>", inner))
|
|
404
|
+
decode.append(f" let a{i}: {owned} = match args.get({i}).map(|j| <{owned} as Dec>::dec(j)) {{\n"
|
|
405
|
+
f" Some(Ok(v)) => v,\n"
|
|
406
|
+
f" Some(Err(e)) => {{ finish(raise(\"TypeError\", &e, 0)); return; }}\n"
|
|
407
|
+
f" None => {{ finish(raise(\"TypeError\", \"missing argument {i}\", 0)); return; }}\n }};")
|
|
408
|
+
args.append(f"&a{i}" if by_ref else f"a{i}.clone()")
|
|
409
|
+
call = f"target::{unit['name']}({', '.join(args)})"
|
|
410
|
+
ret = unit["returns"] or "()"
|
|
411
|
+
enc = "let mut o = String::new();\n Enc::enc(&v, &mut o);\n Ok(o)"
|
|
412
|
+
if ret.startswith("Result<") or re.match(r"^(\w+::)*Result<", ret):
|
|
413
|
+
err = split_top(ret[ret.index("<") + 1:ret.rindex(">")])
|
|
414
|
+
etype = err[1] if len(err) > 1 else "String"
|
|
415
|
+
shown = etype.split("::")[-1]
|
|
416
|
+
display = shown in ("String", "&str", "str") or etype.startswith("Box<") or len(err) < 2 or \
|
|
417
|
+
re.search(r"impl\s+(?:std::)?(?:fmt::)?Display\s+for\s+(?:\w+::)*" + re.escape(shown) + r"\b", text)
|
|
418
|
+
body = f" match {call} {{\n Ok(v) => {{ {enc} }}\n Err(e) => Err(format!(\"{'{}' if display else '{:?}'}\", e)),\n }}"
|
|
419
|
+
else:
|
|
420
|
+
body = f" let v = {call};\n {enc}"
|
|
421
|
+
driver = DRIVER.replace("__DECODE__", "\n".join(decode)).replace("__CALL__", body) \
|
|
422
|
+
.replace("__FILE__", os.path.basename(rel)).replace("__TARGET__", path)
|
|
423
|
+
drv_dir = os.path.join(work, "drv")
|
|
424
|
+
os.makedirs(drv_dir, exist_ok=True)
|
|
425
|
+
open(os.path.join(drv_dir, "main.rs"), "w", encoding="utf-8").write(driver)
|
|
426
|
+
out = os.path.join(work, "ppdrv")
|
|
427
|
+
subprocess.run(["rustc", "--edition", "2021", "-O", "-C", "debuginfo=0", "-C", "panic=unwind", "-C", "overflow-checks=on",
|
|
428
|
+
"-A", "warnings", "-o", out, os.path.join(drv_dir, "main.rs")],
|
|
429
|
+
cwd=work, env=dict(os.environ, HOME=work), check=True, capture_output=True)
|
|
430
|
+
return [out]
|