gdp-wired 0.31.1 → 0.33.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 (84) hide show
  1. package/README.md +95 -6
  2. package/dist/core/c/reader.d.ts +86 -0
  3. package/dist/core/c/reader.js +860 -0
  4. package/dist/core/check.js +20 -6
  5. package/dist/core/cli.d.ts +76 -0
  6. package/dist/core/cli.js +636 -0
  7. package/dist/core/dsl.d.ts +6 -4
  8. package/dist/core/dsl.js +30 -16
  9. package/dist/core/effect.d.ts +6 -4
  10. package/dist/core/effect.js +48 -10
  11. package/dist/core/ex/harness.exs +177 -0
  12. package/dist/core/ex/json.exs +46 -0
  13. package/dist/core/ex/reader.exs +462 -0
  14. package/dist/core/exists.d.ts +3 -0
  15. package/dist/core/exists.js +19 -5
  16. package/dist/core/extract-c.d.ts +35 -0
  17. package/dist/core/extract-c.js +424 -0
  18. package/dist/core/extract-check.js +27 -6
  19. package/dist/core/extract-ex.d.ts +16 -0
  20. package/dist/core/extract-ex.js +33 -0
  21. package/dist/core/extract-go-check.d.ts +28 -0
  22. package/dist/core/extract-go-check.js +639 -0
  23. package/dist/core/extract-go.d.ts +231 -0
  24. package/dist/core/extract-go.js +1166 -0
  25. package/dist/core/extract-jvm.d.ts +23 -0
  26. package/dist/core/extract-jvm.js +220 -0
  27. package/dist/core/extract-print.js +17 -7
  28. package/dist/core/extract-py.d.ts +15 -0
  29. package/dist/core/extract-py.js +31 -0
  30. package/dist/core/extract-rb.d.ts +17 -0
  31. package/dist/core/extract-rb.js +31 -0
  32. package/dist/core/extract-read.d.ts +20 -0
  33. package/dist/core/extract-read.js +46 -6
  34. package/dist/core/extract-rs.d.ts +12 -0
  35. package/dist/core/extract-rs.js +306 -0
  36. package/dist/core/extract-shapes.d.ts +2 -0
  37. package/dist/core/extract-shapes.js +6 -5
  38. package/dist/core/extract-step.d.ts +806 -0
  39. package/dist/core/extract-step.js +4141 -0
  40. package/dist/core/extract-swift.d.ts +27 -0
  41. package/dist/core/extract-swift.js +484 -0
  42. package/dist/core/extract-xstate.d.ts +10 -3
  43. package/dist/core/extract-xstate.js +50 -4
  44. package/dist/core/extract.d.ts +22 -3
  45. package/dist/core/extract.js +107 -18
  46. package/dist/core/go/go.mod +3 -0
  47. package/dist/core/go/reader.go +901 -0
  48. package/dist/core/infer.d.ts +4 -0
  49. package/dist/core/infer.js +1838 -69
  50. package/dist/core/jvm/Harness.java +361 -0
  51. package/dist/core/jvm/JavaReader.java +825 -0
  52. package/dist/core/jvm/Jvm.java +332 -0
  53. package/dist/core/jvm/KtReader.java +960 -0
  54. package/dist/core/jvm/Rt.java +10 -0
  55. package/dist/core/laws.d.ts +83 -0
  56. package/dist/core/laws.js +623 -0
  57. package/dist/core/machine.d.ts +2 -0
  58. package/dist/core/machine.js +87 -0
  59. package/dist/core/py/harness.py +328 -0
  60. package/dist/core/py/reader.py +447 -0
  61. package/dist/core/rb/harness.rb +233 -0
  62. package/dist/core/rb/reader.rb +375 -0
  63. package/dist/core/relational.d.ts +49 -0
  64. package/dist/core/relational.js +345 -0
  65. package/dist/core/rs/Cargo.lock +108 -0
  66. package/dist/core/rs/Cargo.toml +14 -0
  67. package/dist/core/rs/src/main.rs +681 -0
  68. package/dist/core/swift/Harness.swift +124 -0
  69. package/dist/core/swift/Main.swift +34 -0
  70. package/dist/core/swift/Package.swift +13 -0
  71. package/dist/core/swift/Sources/gdp-swiftreader/main.swift +1341 -0
  72. package/dist/interchange/check.d.ts +16 -0
  73. package/dist/interchange/check.js +111 -0
  74. package/dist/interchange/format.d.ts +150 -0
  75. package/dist/interchange/format.js +678 -0
  76. package/dist/kernel/epr.d.ts +40 -0
  77. package/dist/kernel/epr.js +1882 -0
  78. package/dist/kernel/kernel.d.ts +45 -1
  79. package/dist/kernel/kernel.js +138 -13
  80. package/dist/kernel/prove.d.ts +45 -0
  81. package/dist/kernel/prove.js +658 -51
  82. package/dist/lean-kernel/emit.d.ts +17 -2
  83. package/dist/lean-kernel/emit.js +87 -7
  84. package/package.json +57 -2
@@ -0,0 +1,306 @@
1
+ import { Refusal, pathOf } from "./extract-read.js";
2
+ import { entryNames, extractStep, node, stubbed } from "./extract-step.js";
3
+ export { proveRule, proveSteps } from "./dsl.js";
4
+ const proc = globalThis.process;
5
+ // The reader, built once per version of its source (into the system's temporary directory).
6
+ export function rsReader(cargo = 'cargo') {
7
+ const fs = node('node:fs'), cp = node('node:child_process'), os = node('node:os'), crypto = node('node:crypto');
8
+ const dir = new URL('./rs/', import.meta.url).pathname;
9
+ const h = crypto.createHash('sha256').update(fs.readFileSync(`${dir}src/main.rs`, 'utf8') + fs.readFileSync(`${dir}Cargo.toml`, 'utf8')).digest('hex').slice(0, 12);
10
+ const target = `${os.tmpdir()}/gdp-rsreader-${h}`, bin = `${target}/release/gdp-rsreader`;
11
+ if (!fs.existsSync(bin))
12
+ cp.execFileSync(cargo, ['build', '--release', '--quiet', '--target-dir', target], { cwd: dir, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], env: { ...proc?.env } });
13
+ return bin;
14
+ }
15
+ export function readRust(dir, names, cargo) {
16
+ const cp = node('node:child_process');
17
+ let out;
18
+ try {
19
+ out = cp.execFileSync(rsReader(cargo), [JSON.stringify({ root: dir, names })], { encoding: 'utf8', maxBuffer: 1 << 29, stdio: ['ignore', 'pipe', 'pipe'] });
20
+ }
21
+ catch (e) {
22
+ throw new Refusal(dir, `the Rust reader didn't run (${String(e.stderr ?? e.message).split('\n').filter(Boolean).slice(-2).join(' | ')}): cargo is needed to extract Rust`);
23
+ }
24
+ return JSON.parse(out);
25
+ }
26
+ // `at`: the crate's directory, or a file in it (a path or a URL).
27
+ export function extractRust(at, opts = {}) {
28
+ const fs = node('node:fs'), path = node('node:path'), p = pathOf(at);
29
+ let dir = p;
30
+ if (/\.rs$/.test(p))
31
+ for (let d = path.dirname(path.resolve(p));; d = path.dirname(d)) {
32
+ if (fs.existsSync(`${d}/Cargo.toml`)) {
33
+ dir = d;
34
+ break;
35
+ }
36
+ if (path.dirname(d) === d)
37
+ break;
38
+ }
39
+ let mod;
40
+ try {
41
+ if (opts.stores && Object.keys(opts.stores).length)
42
+ throw new Refusal(dir, 'stores: not in the Rust front end yet');
43
+ mod = readRust(dir, entryNames(opts), opts.cargo);
44
+ }
45
+ catch (e) {
46
+ if (e instanceof Refusal)
47
+ return { ok: false, refusals: [{ where: e.where, what: e.what }], notes: [] };
48
+ throw e;
49
+ }
50
+ return extractStep(mod, read => harnessFor(dir, mod, read, opts), opts);
51
+ }
52
+ // The expression making a value of type t from the JSON value `v` (a &serde_json::Value), with `?` on errors.
53
+ function fromJson(t, v, mod, depth = 0) {
54
+ if (depth > 6)
55
+ return 'return Err("too deep".into())';
56
+ switch (t.k) {
57
+ case 'int': {
58
+ if (t.unit === 'instant')
59
+ return `inst(int(val(${v}))?)`;
60
+ if (t.unit === 'duration')
61
+ return `std::time::Duration::from_nanos(u64::try_from(int(val(${v}))?).map_err(|_| "a duration below 0".to_string())?)`;
62
+ const ty = t.rs ?? 'i64';
63
+ return `<${ty}>::try_from(int(val(${v}))?).map_err(|_| format!("{} outside ${ty}", val(${v})))?`;
64
+ }
65
+ case 'bool': return `val(${v}).as_bool().ok_or("not a bool")?`;
66
+ case 'str': return `val(${v}).as_str().ok_or("not a string")?.to_string()`;
67
+ case 'choice': return `match val(${v}).as_str().ok_or("not a variant")? { ${t.values.map(x => `${JSON.stringify(x)} => ${t.enum}::${x}`).join(', ')}, x => return Err(format!("no variant {x}")) }`;
68
+ case 'opt': return `if ${v}.get("none").and_then(|x| x.as_bool()) == Some(true) || ${v}.is_null() { None } else { Some(${fromJson(t.of, v, mod, depth + 1)}) }`;
69
+ case 'rec': {
70
+ const r = mod.recs[t.name];
71
+ if (!r)
72
+ return `return Err("no record ${t.name}".into())`;
73
+ return `${t.name} { ${r.fields.map(f => `${f.name}: match ${v}.get("f").and_then(|m| m.get(${JSON.stringify(f.name)})) { Some(x) => ${fromJson(f.t, 'x', mod, depth + 1)}, None => ${zero(f.t, mod, depth + 1)} }`).join(', ')} }`;
74
+ }
75
+ case 'any':
76
+ case 'float':
77
+ case 'list':
78
+ case 'lock':
79
+ case 'map':
80
+ case 'none':
81
+ case 'opaque':
82
+ case 'res': return `return Err("a value of ${t.k}".into())`;
83
+ }
84
+ }
85
+ // A zero of a type (a field the rule doesn't read: the claim is for any value it holds, and the check gives this one).
86
+ function zero(t, mod, depth = 0) {
87
+ if (depth > 6)
88
+ return 'Default::default()';
89
+ if (t.k === 'int')
90
+ return t.unit === 'instant' ? 'inst(0)' : t.unit === 'duration' ? 'std::time::Duration::ZERO' : '0';
91
+ if (t.k === 'bool')
92
+ return 'false';
93
+ if (t.k === 'str')
94
+ return 'String::new()';
95
+ if (t.k === 'opt')
96
+ return 'None';
97
+ if (t.k === 'choice')
98
+ return `${t.enum}::${t.values[0]}`;
99
+ if (t.k === 'rec') {
100
+ const r = mod.recs[t.name];
101
+ return r ? `${t.name} { ${r.fields.map(f => `${f.name}: ${zero(f.t, mod, depth + 1)}`).join(', ')} }` : 'Default::default()';
102
+ }
103
+ return 'Default::default()';
104
+ }
105
+ // A leaf's place in the object, read and written as its type says (an atomic by load and store, a Mutex by its lock).
106
+ function access(path, t) {
107
+ const place = `o.${path.join('.')}`;
108
+ const lk = t?.lock, at = t?.atomic;
109
+ if (at)
110
+ return { read: `${place}.load(std::sync::atomic::Ordering::SeqCst)`, write: v => `${place}.store(${v}, std::sync::atomic::Ordering::SeqCst)` };
111
+ if (lk) {
112
+ const g = lk === 'std' ? `${place}.lock().unwrap()` : `${place}.lock()`;
113
+ return { read: `(*${g})`, write: v => `*${g} = ${v}` };
114
+ }
115
+ return { read: `${place}`, write: v => `${place} = ${v}` };
116
+ }
117
+ function toJson(t, x) {
118
+ if (t.k === 'int')
119
+ return t.unit === 'instant' ? `json!(of_inst(${x}).to_string())` : t.unit === 'duration' ? `json!((${x}).as_nanos().to_string())` : `json!(((${x}) as i128).to_string())`;
120
+ if (t.k === 'bool')
121
+ return `json!(${x})`;
122
+ if (t.k === 'str')
123
+ return `json!(${x}.clone())`;
124
+ if (t.k === 'choice')
125
+ return `json!(match ${x} { ${t.values.map(v => `${t.enum}::${v} => ${JSON.stringify(v)}`).join(', ')} })`;
126
+ return 'json!(null)';
127
+ }
128
+ function harnessCode(mod, read, cls) {
129
+ const leaves = read.leaves.filter(l => l.kind !== 'frame' && l.kind !== 'map');
130
+ if (read.leaves.some(l => l.kind === 'map'))
131
+ throw new Refusal(mod.file, 'a map in the state: the Rust harness reads none yet');
132
+ const byPath = new Map();
133
+ for (const l of leaves) {
134
+ const k = l.path.join('.');
135
+ byPath.set(k, [...(byPath.get(k) ?? []), l]);
136
+ }
137
+ const get = [], set = [];
138
+ for (const [, ls] of byPath) {
139
+ const val = ls.find(l => l.kind !== 'none'), none = ls.find(l => l.kind === 'none');
140
+ if (!val?.t)
141
+ throw new Refusal(mod.file, `${ls[0].path.join('.')}: a leaf of no type the harness reads`);
142
+ const t = val.t.k === 'opt' ? val.t.of : val.t;
143
+ const ac = access(val.path, val.t);
144
+ if (none) {
145
+ get.push(`match ${ac.read} { Some(x) => { s.insert(${JSON.stringify(val.name)}.into(), ${toJson(t, 'x')}); s.insert(${JSON.stringify(none.name)}.into(), json!(false)); } None => { s.insert(${JSON.stringify(val.name)}.into(), ${toJson(t, zero(t, mod))}); s.insert(${JSON.stringify(none.name)}.into(), json!(true)); } }`);
146
+ set.push(`{ let v = &st[${JSON.stringify(val.name)}]; let n = st[${JSON.stringify(none.name)}].as_bool() == Some(true); ${ac.write(`if n { None } else { Some(${fromJson(t, 'v', mod)}) }`)}; }`);
147
+ }
148
+ else {
149
+ get.push(`s.insert(${JSON.stringify(val.name)}.into(), ${toJson(t, ac.read)});`);
150
+ set.push(`{ let v = &st[${JSON.stringify(val.name)}]; ${ac.write(fromJson(t, 'v', mod))}; }`);
151
+ }
152
+ }
153
+ const self = cls?.name ?? '()';
154
+ const fn = (id) => mod.funcs[id];
155
+ const newId = cls?.methods.new ?? undefined;
156
+ const make = cls ? (newId ? `{ let a = &req["a"]; let _ = a; ${self}::new(${fn(newId).params.filter(p => !p.self).map((p, i) => fromJson(p.t, `(&a[${i}][1])`, mod)).join(', ')}) }` : `${self}::default()`) : '()';
157
+ const calls = Object.entries(read.args).map(([m]) => {
158
+ const f = cls ? fn(cls.methods[m]) : fn(m);
159
+ const ps = f.params.filter(p => !p.self);
160
+ const args = ps.map((p, i) => { const rs = p.rs ?? ''; const v = fromJson(p.t, `(&a[${i}][1])`, mod); return /^&\s*mut/.test(rs) ? `&mut ${v}` : rs.startsWith('&') ? `&${v}` : v; });
161
+ const target = cls ? `o.${m}(${args.join(', ')})` : `${m}(${args.join(', ')})`;
162
+ const ret = f.ret;
163
+ const out = ret.k === 'res' ? `match r { Ok(v) => { let _ = &v; Ok(${ret.of.k === 'none' ? 'json!(null)' : tagged(ret.of, 'v')}) } Err(_) => Err("an Err".to_string()) }` : ret.k === 'opt' ? `Ok(match r { Some(v) => ${tagged(ret.of, 'v')}, None => json!(null) })` : ret.k === 'none' ? 'Ok(json!(null))' : `Ok(${tagged(ret, 'r')})`;
164
+ return `${JSON.stringify(m)} => { let r = ${target}; ${out} }`;
165
+ });
166
+ const clsMod = cls?.module ?? 'crate';
167
+ void clsMod;
168
+ return `
169
+ #[cfg(test)]
170
+ #[allow(unused, clippy::all)]
171
+ pub(crate) mod __gdp_harness {
172
+ use super::*;
173
+ use serde_json::{json, Value};
174
+ use std::io::{BufRead, Write};
175
+ static BASE: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
176
+ static NOW: std::sync::atomic::AtomicI64 = std::sync::atomic::AtomicI64::new(0);
177
+ // An answered call's value: the request's input for it (each answered call rewritten to crate::__gdp_answer).
178
+ static ANS: std::sync::Mutex<Option<Value>> = std::sync::Mutex::new(None);
179
+ pub(crate) trait GdpAns { fn of(v: &Value) -> Self; }
180
+ macro_rules! gdp_int { ($($t:ty),*) => { $(impl GdpAns for $t { fn of(v: &Value) -> Self { int(val(v)).ok().and_then(|n| <$t>::try_from(n).ok()).unwrap_or_default() } })* } }
181
+ gdp_int!(i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize);
182
+ impl GdpAns for bool { fn of(v: &Value) -> Self { val(v).as_bool().unwrap_or(false) } }
183
+ impl GdpAns for String { fn of(v: &Value) -> Self { val(v).as_str().unwrap_or("").to_string() } }
184
+ impl<T: GdpAns> GdpAns for Option<T> { fn of(v: &Value) -> Self { if v.get("none").and_then(|x| x.as_bool()) == Some(true) { None } else { Some(T::of(v)) } } }
185
+ pub(crate) fn answer<T: GdpAns>(k: &str) -> T { T::of(ANS.lock().unwrap().as_ref().and_then(|a| a.get(k)).unwrap_or(&Value::Null)) }
186
+ fn base() -> std::time::Instant { *BASE.get_or_init(|| std::time::Instant::now() + std::time::Duration::from_secs(1u64 << 31)) }
187
+ pub(crate) fn now() -> std::time::Instant { inst(NOW.load(std::sync::atomic::Ordering::SeqCst) as i128) }
188
+ fn inst(n: i128) -> std::time::Instant { if n >= 0 { base() + std::time::Duration::from_nanos(n as u64) } else { base() - std::time::Duration::from_nanos((-n) as u64) } }
189
+ fn of_inst(t: std::time::Instant) -> i128 { if t >= base() { t.duration_since(base()).as_nanos() as i128 } else { -(base().duration_since(t).as_nanos() as i128) } }
190
+ fn val(v: &Value) -> &Value { v.get("in").unwrap_or(v) }
191
+ fn int(v: &Value) -> Result<i128, String> { if let Some(s) = v.as_str() { s.parse::<i128>().map_err(|e| e.to_string()) } else if let Some(i) = v.as_i64() { Ok(i as i128) } else if let Some(u) = v.as_u64() { Ok(u as i128) } else { Err(format!("not a number: {v}")) } }
192
+ fn get(o: &${self}) -> Value { let mut s = serde_json::Map::new(); ${get.join(' ')} Value::Object(s) }
193
+ fn set(o: &mut ${self}, st: &Value) -> Result<(), String> { ${set.join(' ')} Ok(()) }
194
+ fn make(req: &Value) -> Result<${self}, String> { NOW.store(int(&req["now"]).unwrap_or(0) as i64, std::sync::atomic::Ordering::SeqCst); Ok(${make}) }
195
+ fn call(o: &mut ${self}, m: &str, a: &Value) -> Result<Result<Value, String>, String> {
196
+ Ok(match m { ${calls.join(', ')}, _ => return Err(format!("no method {m}")) })
197
+ }
198
+ #[test]
199
+ fn __gdp_harness_main() {
200
+ let args: Vec<String> = std::env::args().collect();
201
+ let (fin, fout) = (&args[args.len() - 2], &args[args.len() - 1]);
202
+ std::panic::set_hook(Box::new(|_| {}));
203
+ let input = std::io::BufReader::new(std::fs::File::open(fin).unwrap());
204
+ let mut out = std::fs::OpenOptions::new().write(true).open(fout).unwrap();
205
+ let mut objs: Vec<${self}> = vec![];
206
+ for line in input.lines() {
207
+ let line = line.unwrap();
208
+ let req: Value = serde_json::from_str(&line).unwrap();
209
+ let op = req["op"].as_str().unwrap_or("").to_string();
210
+ let res = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| -> Value {
211
+ match op.as_str() {
212
+ "hello" => json!({"ok": true}),
213
+ "new" => match make(&req) { Ok(o) => { objs.push(o); json!({"id": objs.len()}) } Err(e) => json!({"err": e}) },
214
+ "at" => match make(&req) { Ok(mut o) => match set(&mut o, &req["state"]) { Ok(()) => { objs.push(o); json!({"id": objs.len()}) } Err(e) => json!({"bad": e}) }, Err(e) => json!({"bad": e}) },
215
+ "get" => { let i = req["id"].as_u64().unwrap() as usize - 1; json!({"state": get(&objs[i])}) }
216
+ "call" => {
217
+ let i = req["id"].as_u64().unwrap() as usize - 1;
218
+ NOW.store(int(&req["now"]).unwrap_or(0) as i64, std::sync::atomic::Ordering::SeqCst);
219
+ *ANS.lock().unwrap() = Some(req["answers"].clone());
220
+ let m = req["m"].as_str().unwrap().to_string();
221
+ let a = req["a"].clone();
222
+ let o = &mut objs[i];
223
+ match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| call(o, &m, &a))) {
224
+ Ok(Ok(Ok(v))) => json!({"out": v}),
225
+ Ok(Ok(Err(e))) => json!({"out": null, "err": e}),
226
+ Ok(Err(bad)) => json!({"out": null, "bad": bad}),
227
+ Err(p) => json!({"out": null, "err": format!("panic: {}", p.downcast_ref::<String>().cloned().or_else(|| p.downcast_ref::<&str>().map(|s| s.to_string())).unwrap_or_default())}),
228
+ }
229
+ }
230
+ "coverage" => json!({"hit": []}),
231
+ _ => json!({"error": format!("no op {op}")}),
232
+ }
233
+ })).unwrap_or_else(|_| json!({"error": "the harness panicked"}));
234
+ writeln!(out, "{}", res).unwrap(); out.flush().unwrap();
235
+ }
236
+ }
237
+ }
238
+ `;
239
+ }
240
+ const tagged = (t, x) => (t.k === 'int' ? `json!({"n": ${toJsonNum(t, x)}})` : t.k === 'bool' ? `json!(${x})` : t.k === 'str' ? `json!({"s": ${x}})` : t.k === 'choice' ? `json!({"s": ${toJson(t, x).replace(/^json!\(|\)$/g, '')}})` : `json!({"o": "value"})`);
241
+ const toJsonNum = (t, x) => (t.k === 'int' && t.unit === 'instant' ? `of_inst(${x}).to_string()` : t.k === 'int' && t.unit === 'duration' ? `(${x}).as_nanos().to_string()` : `((${x}) as i128).to_string()`);
242
+ // The crate copied (its target left out), the harness put in the struct's module, the clock read through it, the
243
+ // tests built with serde_json beside the crate's own dependencies: the test binary is the harness.
244
+ function harnessFor(dir, mod, read, opts) {
245
+ const fs = node('node:fs'), cp = node('node:child_process'), os = node('node:os');
246
+ const cls = read.cls ? mod.recs[read.cls] : undefined;
247
+ try {
248
+ const work = fs.mkdtempSync(`${os.tmpdir()}/gdp-rscheck-`);
249
+ fs.cpSync(dir, work, { recursive: true, filter: (p) => !/\/target(\/|$)/.test(p.slice(dir.length)) });
250
+ // serde_json for the harness, as a dev-dependency of the copy.
251
+ let toml = fs.readFileSync(`${work}/Cargo.toml`, 'utf8');
252
+ if (!/\[dev-dependencies(\.serde_json)?\][^[]*serde_json/s.test(toml))
253
+ toml += '\n[dev-dependencies.serde_json]\nversion = "1"\n';
254
+ fs.writeFileSync(`${work}/Cargo.toml`, toml);
255
+ const file = cls ? String(cls.file) : String(mod.fmods ? mod.path.slice(mod.root.length + 1) : mod.path.slice(mod.root.length + 1));
256
+ const modPath = cls?.module ?? mod.fmods?.[Object.keys(read.args)[0]] ?? 'crate';
257
+ // The clock: Instant::now() read through the harness (the request's time), the code's own calls rewritten first.
258
+ const lib = fs.existsSync(`${work}/src/lib.rs`) ? 'src/lib.rs' : 'src/main.rs';
259
+ const walk = (d) => fs.readdirSync(d, { withFileTypes: true }).flatMap((e) => { const x = e; return x.isDirectory() ? walk(`${d}/${x.name}`) : x.name.endsWith('.rs') ? [`${d}/${x.name}`] : []; });
260
+ // (each answered call rewritten to the harness's answer, from the crate's own text, before the clock's)
261
+ for (const [f, t] of stubbed(read, f => fs.readFileSync(`${dir}/${f}`, 'utf8'), a => `crate::__gdp_answer(${JSON.stringify(a.key)})`))
262
+ fs.writeFileSync(`${work}/${f}`, t);
263
+ for (const f of walk(`${work}/src`)) {
264
+ const s = fs.readFileSync(f, 'utf8');
265
+ const t = s.replace(/\b(?:std::time::)?Instant::now\(\)/g, 'crate::__gdp_now()');
266
+ if (t !== s)
267
+ fs.writeFileSync(f, t);
268
+ }
269
+ fs.writeFileSync(`${work}/${file}`, fs.readFileSync(`${work}/${file}`, 'utf8') + harnessCode(mod, read, cls));
270
+ fs.writeFileSync(`${work}/${lib}`, `${fs.readFileSync(`${work}/${lib}`, 'utf8')}\n#[cfg(test)]\n#[allow(unused)]\npub(crate) fn __gdp_now() -> std::time::Instant { ${modPath}::__gdp_harness::now() }\n#[cfg(test)]\n#[allow(unused)]\npub(crate) fn __gdp_answer<T: ${modPath}::__gdp_harness::GdpAns>(k: &str) -> T { ${modPath}::__gdp_harness::answer(k) }\n`);
271
+ const target = `${os.tmpdir()}/gdp-rscheck-target`;
272
+ let msgs;
273
+ try {
274
+ msgs = cp.execFileSync(opts.cargo ?? 'cargo', ['test', '--lib', '--no-run', '--message-format=json', '--target-dir', target], { cwd: work, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 1 << 28, env: { ...proc?.env } });
275
+ }
276
+ catch (e) {
277
+ const out = String(e.stdout ?? '');
278
+ const errs = out.split('\n').flatMap(l => { try {
279
+ const j = JSON.parse(l);
280
+ return j.reason === 'compiler-message' && j.message?.level === 'error' ? [j.message.rendered ?? ''] : [];
281
+ }
282
+ catch {
283
+ return [];
284
+ } });
285
+ return { cmd: 'false', args: [], hello: {}, error: `the crate doesn't build with the check's harness: ${(errs.join(' | ') || String(e.stderr ?? '')).replace(/\s+/g, ' ').slice(0, 600)}` };
286
+ }
287
+ const exe = msgs.split('\n').flatMap(l => { try {
288
+ const j = JSON.parse(l);
289
+ return j.reason === 'compiler-artifact' && j.executable && j.target?.kind?.includes('lib') ? [j.executable] : [];
290
+ }
291
+ catch {
292
+ return [];
293
+ } })[0];
294
+ if (!exe)
295
+ return { cmd: 'false', args: [], hello: {}, error: 'the test build gave no executable' };
296
+ read.model.notes.push('Rust: the code is checked in a debug build (overflow checks on); its branch arms are not counted (no instrumentation yet)');
297
+ read.arms.length = 0;
298
+ const test = `${modPath === 'crate' ? '' : `${modPath.replace(/^crate::/, '')}::`}__gdp_harness::__gdp_harness_main`;
299
+ return { cmd: exe, args: [test, '--exact', '--nocapture', '--test-threads=1'], hello: {} };
300
+ }
301
+ catch (e) {
302
+ if (e instanceof Refusal)
303
+ return { cmd: 'false', args: [], hello: {}, error: e.what };
304
+ throw e;
305
+ }
306
+ }
@@ -2,12 +2,14 @@ import ts from 'typescript';
2
2
  import { Exec, type Heap, type Model, type Path, type Setup, type Shape, type Sort, type V } from './extract-read.js';
3
3
  export type ReadOptions = {
4
4
  entry: string;
5
+ strict?: boolean;
5
6
  files?: Record<string, string>;
6
7
  typed?: Record<string, Sort>;
7
8
  functions?: string[];
8
9
  methods?: string[];
9
10
  init?: unknown;
10
11
  };
12
+ export declare function setupOf(code: string, file: string, typed?: Record<string, Sort>, files?: Record<string, string>): Setup;
11
13
  export declare function readFunctions(code: string, file: string, opts: ReadOptions): Model;
12
14
  export declare function readClass(code: string, file: string, opts: ReadOptions): Model;
13
15
  export type Result = {
@@ -7,7 +7,7 @@ import ts from 'typescript';
7
7
  import * as I from "./extract-ir.js";
8
8
  import { Exec, Retype, memberName, mergeOps, normalize, program, refuse, shapeOf, unparen } from "./extract-read.js";
9
9
  const at0 = (sf) => sf.statements[0] ?? sf;
10
- function setupOf(code, file, typed = {}, files = {}) {
10
+ export function setupOf(code, file, typed = {}, files = {}) {
11
11
  const root = file.slice(0, file.length - (file.split('/').pop().length)), extra = Object.fromEntries(Object.entries(files).map(([p, c]) => [normalize(`${root}${p}`), c]));
12
12
  const { sf, checker } = program(code, file, extra);
13
13
  return { ours: f => f === sf || f.fileName in extra, checker, sf, names: new Set(), vars: new Map(), maps: new Map(), lazySorts: new Map(Object.entries(typed)), nowRole: 'input', hints: new WeakMap(), notes: new Set(), lazy: new Map() };
@@ -539,7 +539,7 @@ function readFunctionsOnce(code, file, opts) {
539
539
  outs.push([rp, materialize(ex, rv, layout, rp, f)]);
540
540
  throws.push(refusalOf(ex));
541
541
  for (const c of combos)
542
- events.push({ select: c.select, call: names[i], args: c.args });
542
+ events.push({ select: c.select, call: names[i], args: c.args, names: f.parameters.map(x => x.name.getText()) });
543
543
  });
544
544
  // An untyped record's discriminant, chosen by name now that the variable is made.
545
545
  for (const e of events)
@@ -573,7 +573,7 @@ function finish(s, m) {
573
573
  return { name: m.name, shape: m.shape, file: m.file, entry: m.entry, params: vars.filter(v => v.role === 'param'), inputs: vars.filter(v => v.role === 'input'), state: vars.filter(v => v.role === 'state'),
574
574
  maps: [...s.maps.values()], ...(s.lists?.size ? { lists: [...s.lists.values()], listWrites } : {}), init: m.init, writes, mapWrites, outputs: m.outputs, refuse: m.refuse, pre: m.pre, layout: m.layout, events: m.events, notes: [...s.notes], hints: s.hints,
575
575
  ...(m.event ? { event: m.event } : {}), ...(m.ctorArgs ? { ctorArgs: m.ctorArgs } : {}), ...(s.lazy.size ? { lazy: s.lazy } : {}), ...(m.initSource ? { initSource: m.initSource } : {}), ...(s.spans ? { spans: s.spans } : {}),
576
- ...(s.fnFields?.names.size ? { fnFields: [...s.fnFields.names] } : {}), ...(s.fnFields?.outside.size ? { answers: Object.fromEntries([...s.fnFields.outside].map(([n, o]) => [n, o.path.replace(/^this\./, '')])) } : {}) };
576
+ ...(s.fnFields?.names.size ? { fnFields: [...s.fnFields.names] } : {}), ...(s.fnFields?.outside.size ? { answers: Object.fromEntries([...s.fnFields.outside].map(([n, o]) => [n, o.path.replace(/^this\./, '')])) } : {}), ...(s.fnFields?.mods?.size ? { imports: [...s.fnFields.mods] } : {}) };
577
577
  }
578
578
  // --- classes --------------------------------------------------------------------------------------------------------
579
579
  function findClass(sf, name) {
@@ -699,6 +699,7 @@ function attempt(code, file, opts, written) {
699
699
  // (core/extract-read.ts's fnFields). Its start is a function written there or the one the constructor is given.
700
700
  const fnType = (t) => !(t.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown)) && s.checker.getSignaturesOfType(s.checker.getNonNullableType(t), ts.SignatureKind.Call).length > 0 && !s.checker.getPropertiesOfType(s.checker.getNonNullableType(t)).length;
701
701
  s.fnFields = { outside: new Map(), names: new Set() };
702
+ s.strict = opts.strict;
702
703
  // A field's type as the entry's object has it: a class it extends with type arguments (`extends Base<Ctx>`) has its
703
704
  // fields of a type parameter at the types given (TypeScript's own instantiation of the chain).
704
705
  const ct = s.checker.getTypeAtLocation(cls), inst = ts.isClassDeclaration(cls) ? ct : ct.getConstructSignatures()[0]?.getReturnType();
@@ -1075,7 +1076,7 @@ function attempt(code, file, opts, written) {
1075
1076
  return [rp, sv];
1076
1077
  });
1077
1078
  perMethod.push({ sel, sv: joinAll(ex, outs, m), refuse: refusalOf(ex) });
1078
- events.push({ select: { [ev.name]: name }, call: name, args });
1079
+ events.push({ select: { [ev.name]: name }, call: name, args, names: m.parameters.map(x => x.name.getText()) });
1079
1080
  }
1080
1081
  // The methods together: each variable by the method called.
1081
1082
  let final = perMethod.at(-1).sv;
@@ -1366,7 +1367,7 @@ function factoryAttempt(code, file, opts, written, fxOf) {
1366
1367
  return [rp, sv];
1367
1368
  });
1368
1369
  perMethod.push({ sel, sv: joinAll(ex, outs, f.decl), refuse: refusalOf(ex) });
1369
- events.push({ select: { [ev.name]: f.name }, call: f.name, args });
1370
+ events.push({ select: { [ev.name]: f.name }, call: f.name, args, names: f.decl.parameters.map(x => x.name.getText()) });
1370
1371
  }
1371
1372
  let final = perMethod.at(-1).sv;
1372
1373
  for (let i = perMethod.length - 2; i >= 0; i--)