gdp-wired 0.45.0 → 0.47.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 (126) hide show
  1. package/README.md +61 -8
  2. package/dist/core/bitsets.d.ts +2 -0
  3. package/dist/core/bitsets.js +23 -0
  4. package/dist/core/bmc.js +6 -2
  5. package/dist/core/c/reader.d.ts +9 -1
  6. package/dist/core/c/reader.js +423 -31
  7. package/dist/core/calendar.d.ts +29 -0
  8. package/dist/core/calendar.js +82 -0
  9. package/dist/core/cli.d.ts +4 -0
  10. package/dist/core/cli.js +206 -40
  11. package/dist/core/compose.js +3 -1
  12. package/dist/core/counts.d.ts +4 -1
  13. package/dist/core/counts.js +314 -85
  14. package/dist/core/cycles.js +8 -1
  15. package/dist/core/cyclic.d.ts +1 -0
  16. package/dist/core/cyclic.js +13 -7
  17. package/dist/core/data-synth.d.ts +3 -0
  18. package/dist/core/data-synth.js +252 -0
  19. package/dist/core/data.d.ts +2 -1
  20. package/dist/core/data.js +223 -24
  21. package/dist/core/discover.js +3 -1
  22. package/dist/core/draft.d.ts +19 -0
  23. package/dist/core/draft.js +53 -0
  24. package/dist/core/dsl.d.ts +37 -3
  25. package/dist/core/dsl.js +167 -26
  26. package/dist/core/effect-schema.d.ts +90 -0
  27. package/dist/core/effect-schema.js +500 -0
  28. package/dist/core/effect.d.ts +4 -11
  29. package/dist/core/effect.js +3 -79
  30. package/dist/core/exists.d.ts +1 -0
  31. package/dist/core/exists.js +191 -16
  32. package/dist/core/extract-c.d.ts +2 -0
  33. package/dist/core/extract-c.js +169 -22
  34. package/dist/core/extract-check.d.ts +1 -0
  35. package/dist/core/extract-check.js +97 -6
  36. package/dist/core/extract-go-check.d.ts +1 -1
  37. package/dist/core/extract-go-check.js +26 -5
  38. package/dist/core/extract-go.d.ts +8 -0
  39. package/dist/core/extract-go.js +67 -6
  40. package/dist/core/extract-ir.d.ts +1 -0
  41. package/dist/core/extract-ir.js +15 -0
  42. package/dist/core/extract-jvm.d.ts +1 -1
  43. package/dist/core/extract-jvm.js +2 -0
  44. package/dist/core/extract-orm.d.ts +12 -0
  45. package/dist/core/extract-orm.js +244 -0
  46. package/dist/core/extract-print.js +20 -1
  47. package/dist/core/extract-py.d.ts +1 -0
  48. package/dist/core/extract-py.js +1 -1
  49. package/dist/core/extract-read.d.ts +26 -1
  50. package/dist/core/extract-read.js +14 -7
  51. package/dist/core/extract-rs.js +63 -15
  52. package/dist/core/extract-shapes.d.ts +1 -0
  53. package/dist/core/extract-shapes.js +84 -0
  54. package/dist/core/extract-sol.d.ts +10 -1
  55. package/dist/core/extract-sol.js +70 -22
  56. package/dist/core/extract-standalone.d.ts +3 -0
  57. package/dist/core/extract-standalone.js +221 -0
  58. package/dist/core/extract-step.d.ts +151 -1
  59. package/dist/core/extract-step.js +1232 -60
  60. package/dist/core/extract-swift.js +6 -2
  61. package/dist/core/extract.d.ts +9 -0
  62. package/dist/core/extract.js +77 -7
  63. package/dist/core/fiber-run.d.ts +5 -0
  64. package/dist/core/fiber-run.js +18 -0
  65. package/dist/core/infer.d.ts +4 -1
  66. package/dist/core/infer.js +918 -217
  67. package/dist/core/jvm/JavaReader.java +23 -6
  68. package/dist/core/jvm/Jvm.java +3 -0
  69. package/dist/core/jvm/KtReader.java +6 -5
  70. package/dist/core/laws.d.ts +10 -3
  71. package/dist/core/laws.js +226 -23
  72. package/dist/core/machine.d.ts +15 -1
  73. package/dist/core/machine.js +187 -15
  74. package/dist/core/nonterm.js +14 -1
  75. package/dist/core/orm/harness.js +61 -0
  76. package/dist/core/orm-fixtures/schema.prisma +5 -0
  77. package/dist/core/py/harness.py +183 -10
  78. package/dist/core/py/reader.py +234 -40
  79. package/dist/core/reader-fixtures/README.md +28 -0
  80. package/dist/core/reader-fixtures/c-693042.cpp +8 -0
  81. package/dist/core/reader-fixtures/go-685506.go +14 -0
  82. package/dist/core/reader-fixtures/jvm-724362.kt +8 -0
  83. package/dist/core/reader-fixtures/jvm-737430.kt +7 -0
  84. package/dist/core/reader-fixtures/jvm-765282.kt +3 -0
  85. package/dist/core/reader-fixtures/swift-735726.swift +15 -0
  86. package/dist/core/reader-fixtures/swift-735990.swift +15 -0
  87. package/dist/core/reader-fixtures/swift-739158.swift +4 -0
  88. package/dist/core/reader-fixtures/swift-744834.swift +15 -0
  89. package/dist/core/reader-fixtures/swift-746946.swift +31 -0
  90. package/dist/core/reader-fixtures/typescript-673062.ts.txt +2 -0
  91. package/dist/core/relation.d.ts +1 -1
  92. package/dist/core/relation.js +29 -2
  93. package/dist/core/relational.js +4 -2
  94. package/dist/core/rs/Cargo.toml +1 -1
  95. package/dist/core/rs/src/main.rs +466 -11
  96. package/dist/core/sample-cache.d.ts +8 -0
  97. package/dist/core/sample-cache.js +46 -0
  98. package/dist/core/security.d.ts +38 -0
  99. package/dist/core/security.js +88 -0
  100. package/dist/core/sol/harness.py +57 -4
  101. package/dist/core/sol-concrete.d.ts +23 -0
  102. package/dist/core/sol-concrete.js +195 -0
  103. package/dist/core/solver.js +3 -1
  104. package/dist/core/swift/Sources/gdp-swiftreader/main.swift +50 -7
  105. package/dist/core/system.js +1 -1
  106. package/dist/core/transfer.js +22 -9
  107. package/dist/core/translate.js +39 -10
  108. package/dist/core/watch.js +50 -5
  109. package/dist/interchange/format.js +11 -1
  110. package/dist/kernel/cdcl.d.ts +5 -0
  111. package/dist/kernel/cdcl.js +56 -9
  112. package/dist/kernel/epr.js +108 -26
  113. package/dist/kernel/kernel.d.ts +29 -1
  114. package/dist/kernel/kernel.js +325 -62
  115. package/dist/kernel/model-sequence.d.ts +3 -0
  116. package/dist/kernel/model-sequence.js +34 -0
  117. package/dist/kernel/prove.d.ts +10 -3
  118. package/dist/kernel/prove.js +332 -71
  119. package/dist/kernel/reader.d.ts +3 -0
  120. package/dist/kernel/reader.js +101 -14
  121. package/dist/kernel/share.d.ts +1 -0
  122. package/dist/kernel/share.js +27 -0
  123. package/dist/lean-kernel/emit.js +30 -37
  124. package/dist/lean-kernel/lean-terms.js +5 -0
  125. package/dist/lean-kernel/library.js +10 -10
  126. package/package.json +6 -1
@@ -211,6 +211,11 @@ export function sortsOf(m, given = {}) {
211
211
  const nums = (vs) => vs.filter(v => v.sort.k === 'num');
212
212
  const ctx0 = () => ({ m, sorts, atoms: [] });
213
213
  for (const v of [...nums(m.params), ...nums(m.inputs)]) {
214
+ // (a while loop's passes: a count)
215
+ if (m.folds?.some(d => d.loop?.cond && d.len.op === 'var' && d.len.name === v.name)) {
216
+ sorts.set(v.name, 'nat');
217
+ continue;
218
+ }
214
219
  if (given[v.name]) {
215
220
  sorts.set(v.name, given[v.name]);
216
221
  notes.push(`${v.name}: ${given[v.name] === 'nat' ? 'a natural' : 'an integer'}, as given`);
@@ -258,13 +263,27 @@ export function sortsOf(m, given = {}) {
258
263
  }
259
264
  if (m.folds?.length)
260
265
  sorts.set(I.PASS, 'nat');
266
+ for (const g of (m.folds ?? []).flatMap(d => d.loop?.drains ?? [])) {
267
+ sorts.set('kl$', 'nat');
268
+ sorts.set('j$', 'nat');
269
+ sorts.set(`${g.ord}_len`, 'nat');
270
+ sorts.set(`${g.ord}.k`, 'nat');
271
+ sorts.set(`${g.rk}.$item`, 'nat');
272
+ }
261
273
  for (let changed = true; changed;) {
262
274
  changed = false;
263
275
  for (const d of m.folds ?? [])
264
276
  for (const f of d.fields) {
265
277
  const n = `${d.run}.${f.name}`, a = d.init[f.name], b = d.step[f.name];
266
- if (f.sort.k === 'num' && sorts.get(n) === 'nat' && ((a.s === 'num' && !natOK(a.e, ctx0())) || (b.s === 'num' && !natOK(b.e, ctx0())))) {
278
+ if (f.sort.k === 'num' && sorts.get(n) === 'nat' && ((a?.s === 'num' && !natOK(a.e, ctx0())) || (b?.s === 'num' && !natOK(b.e, ctx0())))) {
279
+ sorts.set(n, 'int');
280
+ changed = true;
281
+ }
282
+ // (an item's field the run holds: the collection's field's sort, both ways)
283
+ const lk = d.loop?.like.find(x => x[0] === f.name)?.[1];
284
+ if (lk && f.sort.k === 'num' && sorts.get(n) !== sorts.get(lk) && (sorts.get(n) === 'int' || sorts.get(lk) === 'int')) {
267
285
  sorts.set(n, 'int');
286
+ sorts.set(lk, 'int');
268
287
  changed = true;
269
288
  }
270
289
  }
@@ -5,6 +5,7 @@ export { proveRule, proveSteps } from './dsl.js';
5
5
  export type PyOptions = StepOptions & {
6
6
  root?: string;
7
7
  python?: string;
8
+ djangoSettings?: string;
8
9
  };
9
10
  export declare function readPython(file: string, names: string[], opts?: {
10
11
  root?: string;
@@ -26,6 +26,6 @@ export function extractPython(at, opts = {}) {
26
26
  return { ok: false, refusals: [{ where: e.where, what: e.what }], notes: [] };
27
27
  throw e;
28
28
  }
29
- const harness = () => ({ cmd: opts.python ?? 'python3', args: [here('harness.py')], env: { PYTHONDONTWRITEBYTECODE: '1' }, hello: { root: mod.root, path: mod.path, module: mod.module } });
29
+ const harness = () => ({ cmd: opts.python ?? 'python3', args: [here('harness.py')], env: { PYTHONDONTWRITEBYTECODE: '1', ...(opts.djangoSettings ? { DJANGO_SETTINGS_MODULE: opts.djangoSettings } : {}) }, hello: { root: mod.root, path: mod.path, module: mod.module } });
30
30
  return extractStep(mod, harness, opts);
31
31
  }
@@ -93,6 +93,10 @@ export type Term = {
93
93
  export type Arg = {
94
94
  k: 'input';
95
95
  name: string;
96
+ } | {
97
+ k: 'maybe-bool';
98
+ name: string;
99
+ missing: string;
96
100
  } | {
97
101
  k: 'lit';
98
102
  value: string;
@@ -117,6 +121,7 @@ export type MapWrite = {
117
121
  vals: Record<string, Term>;
118
122
  pre?: MapWrite[];
119
123
  when?: B;
124
+ each?: true;
120
125
  };
121
126
  export type ListOp = {
122
127
  op: 'push';
@@ -149,6 +154,9 @@ export type Model = {
149
154
  shape: 'reducer' | 'functions' | 'class';
150
155
  file: string;
151
156
  entry: string;
157
+ standalone?: true;
158
+ standaloneDomains?: Record<string, number[]>;
159
+ standaloneBindings?: string[];
152
160
  params: Var[];
153
161
  inputs: Var[];
154
162
  state: Var[];
@@ -208,6 +216,22 @@ export type Fold = {
208
216
  step: Record<string, Term>;
209
217
  len: N;
210
218
  state?: true;
219
+ back?: true;
220
+ loop?: {
221
+ like: [string, string][];
222
+ cond?: B;
223
+ entry?: B;
224
+ drains?: {
225
+ map: string;
226
+ ord: string;
227
+ rk: string;
228
+ held: B;
229
+ by: {
230
+ e: N;
231
+ desc?: boolean;
232
+ }[];
233
+ }[];
234
+ };
211
235
  };
212
236
  type V = {
213
237
  t: 'num';
@@ -381,12 +405,13 @@ export type Setup = {
381
405
  };
382
406
  export declare class Exec {
383
407
  readonly s: Setup;
408
+ private readonly standalone;
384
409
  throws: {
385
410
  pc: B[];
386
411
  }[];
387
412
  private depth;
388
413
  private ids;
389
- constructor(s: Setup);
414
+ constructor(s: Setup, standalone?: boolean);
390
415
  fresh(base: string): string;
391
416
  newVar(base: string, sort: Sort, role: Var['role'], note?: string): Var;
392
417
  id(prefix: string): string;
@@ -208,11 +208,13 @@ export function shapeOf(t, checker, at, inner) {
208
208
  const keySort = (s, at) => (s.k === 'num' ? 'num' : s.k === 'str' || s.k === 'choice' ? 'str' : refuse(at, 'a map keyed by other than numbers or strings'));
209
209
  export class Exec {
210
210
  s;
211
+ standalone;
211
212
  throws = [];
212
213
  depth = 0;
213
214
  ids = 0;
214
- constructor(s) {
215
+ constructor(s, standalone = false) {
215
216
  this.s = s;
217
+ this.standalone = standalone;
216
218
  }
217
219
  fresh(base) {
218
220
  const clean = base.replace(/^#/, '').replace(/[^A-Za-z0-9_]/g, '_').replace(/^(\d)/, '_$1') || 'x';
@@ -526,13 +528,14 @@ export class Exec {
526
528
  // where it is there.
527
529
  narrow(e, pt, pe) {
528
530
  const strip = (x) => (ts.isParenthesizedExpression(x) ? strip(x.expression) : x);
529
- let x = strip(e), present = true;
531
+ let x = strip(e), present = true, absenceTest = false;
530
532
  if (ts.isPrefixUnaryExpression(x) && x.operator === ts.SyntaxKind.ExclamationToken) {
531
533
  x = strip(x.operand);
532
534
  present = false;
533
535
  }
534
536
  else if (ts.isBinaryExpression(x) && (x.right.kind === ts.SyntaxKind.UndefinedKeyword || (ts.isIdentifier(x.right) && x.right.text === 'undefined') || x.right.kind === ts.SyntaxKind.NullKeyword)) {
535
537
  const op = x.operatorToken.kind;
538
+ absenceTest = true;
536
539
  if (op === ts.SyntaxKind.EqualsEqualsEqualsToken || op === ts.SyntaxKind.EqualsEqualsToken)
537
540
  present = false;
538
541
  else if (op !== ts.SyntaxKind.ExclamationEqualsEqualsToken && op !== ts.SyntaxKind.ExclamationEqualsToken)
@@ -545,6 +548,10 @@ export class Exec {
545
548
  if (v?.t !== 'opt')
546
549
  return [pt, pe];
547
550
  const set = (p, there) => ({ ...p, locals: new Map(p.locals).set(x.text, there ? v.v : { t: 'undef' }) });
551
+ // A falsy optional scalar can be present (false or 0), not just absent.
552
+ // Preserve the opt value on that arm; only an explicit absence comparison narrows both arms.
553
+ if (this.standalone && !absenceTest)
554
+ return present ? [set(pt, true), pe] : [pt, set(pe, true)];
548
555
  return present ? [set(pt, true), set(pe, false)] : [set(pt, false), set(pe, true)];
549
556
  }
550
557
  bind(name, v, p) {
@@ -839,7 +846,7 @@ export class Exec {
839
846
  // A fraction is a binary float in the code: each operation on it rounds (0.1 + 0.2 is not 0.3), so a rule over ℚ
840
847
  // (gdp-wired/rationals) is the code only where nothing rounds, which no check shows; refused, with what is read.
841
848
  if (op === S.SlashToken)
842
- return refuse(e, 'a division whose result may be a fraction (a binary float in the code: each operation on it rounds, where a rule over the rationals would not; Math.floor or Math.ceil of x / k for a constant k is in the subset)');
849
+ return refuse(e, 'a division whose result may be a fraction (a binary float in the code: each operation on it rounds, where a rule over the rationals would not; Math.floor, Math.ceil or Math.trunc of x / k for a constant k is in the subset; Math.round is not: past 2^52 it isn\'t exact and this reader keeps no edge)');
843
850
  if (op === S.AsteriskAsteriskToken)
844
851
  return refuse(e, 'a power');
845
852
  if (op === S.CommaToken)
@@ -1603,7 +1610,7 @@ export class Exec {
1603
1610
  return undefined;
1604
1611
  }
1605
1612
  math(m, e, p) {
1606
- if (m === 'floor' || m === 'ceil') {
1613
+ if (m === 'floor' || m === 'ceil' || m === 'trunc') {
1607
1614
  const a = e.arguments[0];
1608
1615
  const strip = (x) => (ts.isParenthesizedExpression(x) ? strip(x.expression) : x);
1609
1616
  const d = a && strip(a);
@@ -1614,8 +1621,8 @@ export class Exec {
1614
1621
  const kn = this.num(k, d.right, q2);
1615
1622
  if (kn.op !== 'const' || kn.v < 1)
1616
1623
  return refuse(d.right, `Math.${m}(x / k) by other than a positive constant`);
1617
- const xn = this.num(x, d.left, q2);
1618
- return [{ t: 'num', e: m === 'floor' ? I.divk(kn.v, xn) : I.neg(I.divk(kn.v, I.neg(xn))) }, q2];
1624
+ const xn = this.num(x, d.left, q2), kv = kn.v, fl = I.divk(kv, xn), ce = I.neg(I.divk(kv, I.neg(xn)));
1625
+ return [{ t: 'num', e: m === 'floor' ? fl : m === 'ceil' ? ce : I.nite(I.cmp('<', xn, I.num(0)), ce, fl) }, q2];
1619
1626
  }
1620
1627
  // Of an integer, its value.
1621
1628
  const [x, q] = this.ev(d, p);
@@ -1633,7 +1640,7 @@ export class Exec {
1633
1640
  }
1634
1641
  if (m === 'random')
1635
1642
  return refuse(e, 'Math.random (a step the code takes differently each time)');
1636
- return refuse(e, `Math.${m} (Math.min, Math.max, Math.abs, and Math.floor or Math.ceil of x / k are in the subset)`);
1643
+ return refuse(e, `Math.${m} (Math.min, Math.max, Math.abs, and Math.floor, Math.ceil or Math.trunc of x / k are in the subset)`);
1637
1644
  }
1638
1645
  now(e, p) {
1639
1646
  if (p.nows > 0)
@@ -21,7 +21,11 @@ export function readRust(dir, names, cargo) {
21
21
  catch (e) {
22
22
  throw new Refusal(dir, statedRefusal(e) ?? `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
23
  }
24
- return JSON.parse(out);
24
+ const m = JSON.parse(out);
25
+ // (the crate's files not parsing: the reader's error, the source refused with it)
26
+ if (m.error !== undefined)
27
+ throw new Refusal(dir, `the crate doesn't parse: ${typeof m.error === 'string' ? m.error : JSON.stringify(m.error)}`);
28
+ return m;
25
29
  }
26
30
  // `at`: the crate's directory, or a file in it (a path or a URL).
27
31
  export function extractRust(at, opts = {}) {
@@ -125,7 +129,7 @@ function toJson(t, x) {
125
129
  return `json!(match ${x} { ${t.values.map(v => `${t.enum}::${v} => ${JSON.stringify(v)}`).join(', ')} })`;
126
130
  return 'json!(null)';
127
131
  }
128
- function harnessCode(mod, read, cls) {
132
+ function harnessCode(mod, read, cls, name) {
129
133
  const leaves = read.leaves.filter(l => l.kind !== 'frame' && l.kind !== 'map');
130
134
  if (read.leaves.some(l => l.kind === 'map'))
131
135
  throw new Refusal(mod.file, 'a map in the state: the Rust harness reads none yet');
@@ -158,17 +162,15 @@ function harnessCode(mod, read, cls) {
158
162
  const f = cls ? fn(cls.methods[m]) : fn(m);
159
163
  const ps = f.params.filter(p => !p.self);
160
164
  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(', ')})`;
165
+ const target = cls ? `o.${m}(${args.join(', ')})` : `super::${m}(${args.join(', ')})`;
162
166
  const ret = f.ret;
163
167
  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
168
  return `${JSON.stringify(m)} => { let r = ${target}; ${out} }`;
165
169
  });
166
- const clsMod = cls?.module ?? 'crate';
167
- void clsMod;
168
170
  return `
169
171
  #[cfg(test)]
170
172
  #[allow(unused, clippy::all)]
171
- pub(crate) mod __gdp_harness {
173
+ pub(crate) mod ${name} {
172
174
  use super::*;
173
175
  use serde_json::{json, Value};
174
176
  use std::io::{BufRead, Write};
@@ -256,25 +258,59 @@ function harnessFor(dir, mod, read, opts) {
256
258
  if (!/\[dev-dependencies(\.serde_json)?\][^[]*serde_json/s.test(toml))
257
259
  toml += '\n[dev-dependencies.serde_json]\nversion = "1"\n';
258
260
  fs.writeFileSync(`${work}/Cargo.toml`, toml);
259
- const file = cls ? String(cls.file) : String(mod.fmods ? mod.path.slice(mod.root.length + 1) : mod.path.slice(mod.root.length + 1));
261
+ const file = cls ? String(cls.file) : mod.path.slice(mod.root.length + 1);
260
262
  const modPath = cls?.module ?? mod.fmods?.[Object.keys(read.args)[0]] ?? 'crate';
263
+ if (!cls && Object.keys(read.args).some(id => mod.fmods?.[id] !== modPath || mod.funcs[id]?.span?.[0] !== file)) {
264
+ throw new Refusal(mod.file, 'Rust native replay requires function entries in one known file/module');
265
+ }
261
266
  // The clock: Instant::now() read through the harness (the request's time), the code's own calls rewritten first.
262
267
  const lib = fs.existsSync(`${work}/src/lib.rs`) ? 'src/lib.rs' : 'src/main.rs';
263
268
  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}`] : []; });
269
+ // Allocate bridges once on the unmodified Rust copy, before the chosen names
270
+ // become references in rewritten calls. Placement is still queried afterwards.
271
+ const bridges = JSON.parse(cp.execFileSync(rsReader(opts.cargo), [JSON.stringify({ root: work, harness_bridges: { file: lib } })], { encoding: 'utf8', maxBuffer: 1 << 20, stdio: ['ignore', 'pipe', 'pipe'], ...readerRun() }));
272
+ if (bridges.error)
273
+ throw new Refusal(mod.file, bridges.error);
274
+ const { now: nowName, answer: answerName } = bridges;
275
+ if (typeof nowName !== 'string' || !/^__gdp_now(?:_[1-9][0-9]*)?$/.test(nowName) ||
276
+ typeof answerName !== 'string' || !/^__gdp_answer(?:_[1-9][0-9]*)?$/.test(answerName)) {
277
+ throw new Refusal(mod.file, 'Rust native replay has no validated root bridge names');
278
+ }
264
279
  // (each answered call rewritten to the harness's answer, from the crate's own text, before the clock's; the call
265
280
  // kept in a branch never taken, so the answer is of the type the call is, which a binding needn't write)
266
- for (const [f, t] of stubbed(read, f => fs.readFileSync(`${dir}/${f}`, 'utf8'), (a, _, call) => `(if false { ${call} } else { crate::__gdp_answer(${JSON.stringify(a.key)}) })`))
281
+ for (const [f, t] of stubbed(read, f => fs.readFileSync(`${dir}/${f}`, 'utf8'), (a, _, call) => `(if false { ${call} } else { crate::${answerName}(${JSON.stringify(a.key)}) })`))
267
282
  fs.writeFileSync(`${work}/${f}`, t);
268
283
  for (const f of walk(`${work}/src`)) {
269
284
  const s = fs.readFileSync(f, 'utf8');
270
- const t = s.replace(/\b(?:std::time::)?Instant::now\(\)/g, 'crate::__gdp_now()');
285
+ const t = s.replace(/\b(?:std::time::)?Instant::now\(\)/g, `crate::${nowName}()`);
271
286
  if (t !== s)
272
287
  fs.writeFileSync(f, t);
273
288
  }
274
- // (the lines of the code itself in the files the harness is appended to: an error past them is the harness's)
289
+ // Query the parser after rewrites: original offsets are stale after stubs
290
+ // or clock substitutions. Append for file modules; insert before the exact
291
+ // closing brace for inline modules, keeping private-field access in scope.
275
292
  const own = new Map([file, lib].map(f => [f, fs.readFileSync(`${work}/${f}`, 'utf8').split('\n').length]));
276
- fs.writeFileSync(`${work}/${file}`, fs.readFileSync(`${work}/${file}`, 'utf8') + harnessCode(mod, read, cls));
277
- 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`);
293
+ const site = JSON.parse(cp.execFileSync(rsReader(opts.cargo), [JSON.stringify({ root: work, harness_scope: { file, module: modPath } })], { encoding: 'utf8', maxBuffer: 1 << 20, stdio: ['ignore', 'pipe', 'pipe'], ...readerRun() }));
294
+ if (site.error || site.inline_end === undefined)
295
+ throw new Refusal(mod.file, site.error ?? 'Rust native replay has no placement metadata');
296
+ const harnessName = site.harness_name;
297
+ if (typeof harnessName !== 'string' || !/^__gdp_harness(?:_[1-9][0-9]*)?$/.test(harnessName)) {
298
+ throw new Refusal(mod.file, 'Rust native replay has no validated helper module name');
299
+ }
300
+ const source = fs.readFileSync(`${work}/${file}`, 'utf8');
301
+ let prefix = source, suffix = '';
302
+ if (site.inline_end !== null) {
303
+ const bytes = new TextEncoder().encode(source), at = site.inline_end;
304
+ if (!Number.isSafeInteger(at) || at < 0 || at >= bytes.length || bytes[at] !== 125 || source.startsWith('\uFEFF') || /^#![^[]/.test(source)) {
305
+ throw new Refusal(mod.file, 'Rust native replay has an unsupported inline-module byte position');
306
+ }
307
+ const decoder = new TextDecoder('utf-8', { fatal: true });
308
+ prefix = decoder.decode(bytes.slice(0, at));
309
+ suffix = decoder.decode(bytes.slice(at));
310
+ }
311
+ const code = harnessCode(mod, read, cls, harnessName), insertedAt = prefix.split('\n').length, addedLines = code.split('\n').length - 1;
312
+ fs.writeFileSync(`${work}/${file}`, prefix + code + suffix);
313
+ fs.writeFileSync(`${work}/${lib}`, `${fs.readFileSync(`${work}/${lib}`, 'utf8')}\n#[cfg(test)]\n#[allow(unused)]\npub(crate) fn ${nowName}() -> std::time::Instant { ${modPath}::${harnessName}::now() }\n#[cfg(test)]\n#[allow(unused)]\npub(crate) fn ${answerName}<T: ${modPath}::${harnessName}::GdpAns>(k: &str) -> T { ${modPath}::${harnessName}::answer(k) }\n`);
278
314
  const target = `${os.tmpdir()}/gdp-rscheck-target`;
279
315
  const built = buildCheck('cargo', () => 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 }, timeout: compileLimit(), killSignal: 'SIGKILL' }), e => String(e.stdout ?? '').split('\n').flatMap(l => { try {
280
316
  const j = JSON.parse(l);
@@ -282,8 +318,20 @@ function harnessFor(dir, mod, read, opts) {
282
318
  }
283
319
  catch {
284
320
  return [];
285
- } }), l => { const m = /--> ([^\s:]+\.rs):(\d+):\d+/.exec(l); if (!m)
286
- return false; const n = own.get(m[1]); return n === undefined || Number(m[2]) <= n; });
321
+ } }), l => {
322
+ const m = /--> ([^\s:]+\.rs):(\d+):\d+/.exec(l);
323
+ if (!m)
324
+ return false;
325
+ let line = Number(m[2]);
326
+ if (m[1] === file) {
327
+ if (line > insertedAt && line < insertedAt + addedLines)
328
+ return false;
329
+ if (line >= insertedAt + addedLines)
330
+ line -= addedLines;
331
+ }
332
+ const n = own.get(m[1]);
333
+ return n === undefined || line <= n;
334
+ });
287
335
  if (!('ok' in built))
288
336
  return { cmd: 'false', args: [], hello: {}, error: built.why, kind: built.kind };
289
337
  const msgs = built.ok;
@@ -298,7 +346,7 @@ function harnessFor(dir, mod, read, opts) {
298
346
  return { cmd: 'false', args: [], hello: {}, error: 'the test build gave no executable', kind: 'harness' };
299
347
  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)');
300
348
  read.arms.length = 0;
301
- const test = `${modPath === 'crate' ? '' : `${modPath.replace(/^crate::/, '')}::`}__gdp_harness::__gdp_harness_main`;
349
+ const test = `${modPath === 'crate' ? '' : `${modPath.replace(/^crate::/, '')}::`}${harnessName}::__gdp_harness_main`;
302
350
  return { cmd: exe, args: [test, '--exact', '--nocapture', '--test-threads=1'], hello: {} };
303
351
  }
304
352
  catch (e) {
@@ -10,6 +10,7 @@ export type ReadOptions = {
10
10
  init?: unknown;
11
11
  };
12
12
  export declare function setupOf(code: string, file: string, typed?: Record<string, Sort>, files?: Record<string, string>): Setup;
13
+ export declare function readStandalone(code: string, file: string, opts: ReadOptions): Model;
13
14
  export declare function readFunctions(code: string, file: string, opts: ReadOptions): Model;
14
15
  export declare function readClass(code: string, file: string, opts: ReadOptions): Model;
15
16
  export type Result = {
@@ -4,6 +4,7 @@
4
4
  // symbolically (core/extract-read.ts) into a Model: the state's variables, where each sits in the code's own values,
5
5
  // the step's writes, what the code refuses (its throws) and how a request is made of the code.
6
6
  import ts from 'typescript';
7
+ import { standaloneClosure } from "./extract-standalone.js";
7
8
  import * as I from "./extract-ir.js";
8
9
  import { Exec, Retype, memberName, mergeOps, normalize, program, refuse, shapeOf, unparen } from "./extract-read.js";
9
10
  const at0 = (sf) => sf.statements[0] ?? sf;
@@ -432,6 +433,87 @@ function argOf(ex, param, prefix, body) {
432
433
  return { v, events, heap };
433
434
  }
434
435
  const sortOf = (sh, lits) => (sh.k === 'str' && lits.length ? { k: 'choice', values: [...lits, OTHER] } : sh.k === 'num' || sh.k === 'bool' || sh.k === 'choice' || sh.k === 'str' ? sh : (() => { throw new Error('a compound sort'); })());
436
+ // Experimental opt-in: a pure, standalone scalar function. No third-party call or state is synthesized.
437
+ export function readStandalone(code, file, opts) {
438
+ const s = setupOf(code, file, opts.typed, opts.files), fn = findFunction(s.sf, opts.entry);
439
+ if (opts.entry === 'undefined' || opts.entry === '__cov')
440
+ refuse(fn, 'standalone: reserved entry name');
441
+ const bindings = standaloneClosure(s, fn);
442
+ s.spans = [[fn.getStart(), fn.end]];
443
+ const ex = new Exec(s, true), heap = new Map(), args = [];
444
+ const domains = {}, limits = [];
445
+ let p = { pc: [], locals: new Map(), heap, wrote: [], nows: 0 };
446
+ for (const param of fn.parameters) {
447
+ const name = param.name.text, t = s.checker.getTypeAtLocation(param), parts = t.isUnion() ? t.types : [t];
448
+ const missing = parts.filter(x => !!(x.flags & ts.TypeFlags.Undefined)), rest = parts.filter(x => !(x.flags & ts.TypeFlags.Undefined));
449
+ if (parts.some(x => !!(x.flags & ts.TypeFlags.Null)))
450
+ refuse(param, 'standalone: null input is outside the subset');
451
+ const bool = rest.length > 0 && rest.every(x => !!(x.flags & ts.TypeFlags.BooleanLike));
452
+ const num = rest.length > 0 && rest.every(x => !!(x.flags & ts.TypeFlags.NumberLike));
453
+ if ((!bool && !num) || (missing.length && !bool))
454
+ refuse(param, 'standalone: only numeric, boolean, or boolean | undefined inputs');
455
+ const x = ex.newVar(name, { k: bool ? 'bool' : 'num' }, 'input');
456
+ let v = Exec.valueOf(x);
457
+ if (num && rest.every(t => !!(t.flags & ts.TypeFlags.NumberLiteral))) {
458
+ const values = [...new Set(rest.map(t => t.value))].sort((a, b) => a - b);
459
+ if (!values.every(Number.isSafeInteger) || values.length > 64)
460
+ refuse(param, 'standalone: numeric literal domain must contain at most 64 safe integers');
461
+ domains[x.name] = values;
462
+ limits.push(I.or(...values.map(n => I.cmp('=', v.e, I.num(n)))));
463
+ }
464
+ if (missing.length) {
465
+ const m = ex.newVar(`${name}_missing`, { k: 'bool' }, 'input');
466
+ v = { t: 'opt', has: I.not(Exec.valueOf(m).e), v };
467
+ args.push({ k: 'maybe-bool', name: x.name, missing: m.name });
468
+ }
469
+ else
470
+ args.push({ k: 'input', name: x.name });
471
+ p = ex.bind(param.name, v, p);
472
+ }
473
+ const sig = s.checker.getSignatureFromDeclaration(fn), rt = s.checker.getReturnTypeOfSignature(sig), parts = rt.isUnion() ? rt.types : [rt];
474
+ if (parts.some(x => !!(x.flags & ts.TypeFlags.Null)))
475
+ refuse(fn, 'standalone: null result is outside the subset');
476
+ const rest = parts.filter(x => !(x.flags & (ts.TypeFlags.Undefined | ts.TypeFlags.Void)));
477
+ const bool = rest.length > 0 && rest.every(x => !!(x.flags & ts.TypeFlags.BooleanLike));
478
+ const num = rest.length > 0 && rest.every(x => !!(x.flags & ts.TypeFlags.NumberLike));
479
+ if (!bool && !num)
480
+ refuse(fn, 'standalone: result must be numeric or boolean, optionally undefined');
481
+ const val = ex.newVar(`${opts.entry}_result`, { k: bool ? 'bool' : 'num' }, 'state');
482
+ const absent = ex.newVar(`${opts.entry}_result_missing`, { k: 'bool' }, 'state');
483
+ let outs;
484
+ if (ts.isBlock(fn.body)) {
485
+ const flow = ex.block(fn.body.statements, p);
486
+ outs = [...flow.rets, ...(flow.live ? [[flow.live, { t: 'undef' }]] : [])];
487
+ }
488
+ else {
489
+ const [v, q] = ex.ev(fn.body, p);
490
+ outs = [[q, v]];
491
+ }
492
+ outs = outs.filter(([q]) => ex.feasible(q));
493
+ if (!outs.length)
494
+ refuse(fn, 'standalone: no reachable return');
495
+ const final = joinAll(ex, outs.map(([q, v]) => {
496
+ if ((v.t === 'undef' && v.null) || (v.t === 'opt' && v.null))
497
+ refuse(fn, 'standalone: null result');
498
+ const has = v.t === 'undef' ? I.F : v.t === 'opt' ? v.has : I.T;
499
+ const inner = v.t === 'undef' ? undefined : v.t === 'opt' ? v.v : v;
500
+ const there = inner ? outValue(ex, inner, val, { ...q, pc: [...q.pc, has] }, fn) : Exec.defaultOf(val.sort);
501
+ const sv = { leaves: new Map(), maps: new Map() };
502
+ sv.leaves.set(val.name, ex.mergeScalar(has, there, Exec.defaultOf(val.sort), fn));
503
+ sv.leaves.set(absent.name, { t: 'bool', e: I.not(has) });
504
+ return [q, sv];
505
+ }), fn);
506
+ const model = finish(s, { name: opts.entry, shape: 'functions', file, entry: opts.entry,
507
+ layout: { k: 'rec', fields: [] }, init: { [val.name]: termOf(Exec.defaultOf(val.sort)), [absent.name]: termOf(Exec.defaultOf(absent.sort)) },
508
+ final, refuse: I.or(refusalOf(ex), I.not(I.and(...limits))), pre: I.T, events: [{ select: {}, call: opts.entry, args, names: fn.parameters.map(x => x.name.getText()) }], outputs: [val.name, absent.name] });
509
+ model.standalone = true;
510
+ model.kind = 'a standalone scalar function';
511
+ model.standaloneDomains = domains;
512
+ model.standaloneBindings = bindings;
513
+ model.notes.push('standalone scalar function: separate arguments and optional result; numbers are safe integers, not arbitrary JavaScript numbers', `closed reachable bindings: ${bindings.join(', ')}`, ...Object.entries(domains).map(([n, xs]) => `declared numeric input domain ${n}: ${xs.join(', ')}; other values are outside the claim`));
514
+ model.results = { [opts.entry]: { k: 'maybe', name: val.name, missing: absent.name, null: false } };
515
+ return model;
516
+ }
435
517
  export function readFunctions(code, file, opts) {
436
518
  // Read again while an untyped input turns out to be of another sort than a number.
437
519
  for (let typed = { ...opts.typed };;) {
@@ -632,6 +714,8 @@ function chainOf(s, cls) {
632
714
  const h = c.heritageClauses?.find(x => x.token === ts.SyntaxKind.ExtendsKeyword);
633
715
  if (!h)
634
716
  return chain;
717
+ if (h.types.length !== 1)
718
+ return refuse(h, 'extends must name exactly one base class');
635
719
  c = base(h.types[0].expression, h);
636
720
  }
637
721
  }
@@ -1,10 +1,16 @@
1
1
  import { type Extraction } from './extract.js';
2
2
  import { type FileURL } from './extract-read.js';
3
+ import { type SolidityHarness } from './sol-concrete.js';
4
+ export type { SolidityHarness } from './sol-concrete.js';
3
5
  import { type SModule, type SType, type StepOptions, type StepRead } from './extract-step.js';
4
6
  export { proveRule, proveSteps } from './dsl.js';
5
7
  export type SolOptions = StepOptions & {
6
8
  root?: string;
7
9
  remappings?: string[];
10
+ harness?: 'auto' | false | {
11
+ file: string;
12
+ entry?: string;
13
+ };
8
14
  reentrant?: boolean;
9
15
  solc?: string;
10
16
  anvil?: string;
@@ -18,6 +24,8 @@ type Ast = {
18
24
  };
19
25
  export declare const MOD = "W256$";
20
26
  export type Compiled = {
27
+ harness?: SolidityHarness;
28
+ harnessMethods?: string[];
21
29
  main: number;
22
30
  ast: Map<number, Ast>;
23
31
  text: Map<number, string>;
@@ -50,7 +58,7 @@ export type Compiled = {
50
58
  };
51
59
  }>>;
52
60
  };
53
- export declare function compile(file: string, o: SolOptions): Compiled;
61
+ export declare function compile(file: string, o: SolOptions, extra?: Record<string, string>): Compiled;
54
62
  type Field = {
55
63
  name: string;
56
64
  t: SType;
@@ -88,4 +96,5 @@ export declare function readSolidity(file: string, o?: SolOptions, reenter?: boo
88
96
  };
89
97
  export declare function extractSolidity(at: string | FileURL, opts?: SolOptions): Extraction & {
90
98
  read?: StepRead;
99
+ harness?: SolidityHarness;
91
100
  };