gdp-wired 0.23.0 → 0.24.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 (40) hide show
  1. package/README.md +12 -2
  2. package/dist/core/bmc.d.ts +13 -2
  3. package/dist/core/bmc.js +390 -18
  4. package/dist/core/cycles.d.ts +23 -0
  5. package/dist/core/cycles.js +104 -54
  6. package/dist/core/data.d.ts +9 -0
  7. package/dist/core/data.js +352 -121
  8. package/dist/core/discover.js +8 -3
  9. package/dist/core/dsl.d.ts +7 -2
  10. package/dist/core/dsl.js +47 -9
  11. package/dist/core/extract-check.d.ts +77 -0
  12. package/dist/core/extract-check.js +785 -0
  13. package/dist/core/extract-ir.d.ts +139 -0
  14. package/dist/core/extract-ir.js +198 -0
  15. package/dist/core/extract-print.d.ts +30 -0
  16. package/dist/core/extract-print.js +426 -0
  17. package/dist/core/extract-read.d.ts +298 -0
  18. package/dist/core/extract-read.js +1298 -0
  19. package/dist/core/extract-shapes.d.ts +13 -0
  20. package/dist/core/extract-shapes.js +993 -0
  21. package/dist/core/extract-xstate.d.ts +34 -0
  22. package/dist/core/extract-xstate.js +320 -0
  23. package/dist/core/extract.d.ts +31 -0
  24. package/dist/core/extract.js +249 -0
  25. package/dist/core/kind.d.ts +30 -0
  26. package/dist/core/kind.js +81 -0
  27. package/dist/core/relation.js +7 -4
  28. package/dist/core/xstate.d.ts +6 -0
  29. package/dist/core/xstate.js +70 -12
  30. package/dist/kernel/cdcl.d.ts +10 -0
  31. package/dist/kernel/cdcl.js +291 -241
  32. package/dist/kernel/kernel.d.ts +15 -0
  33. package/dist/kernel/kernel.js +32 -0
  34. package/dist/kernel/prove.js +14 -3
  35. package/dist/kernel/reader.d.ts +14 -0
  36. package/dist/kernel/reader.js +102 -14
  37. package/dist/lean-kernel/emit.d.ts +28 -1
  38. package/dist/lean-kernel/emit.js +56 -15
  39. package/dist/lean-kernel/library.js +2 -1
  40. package/package.json +12 -3
@@ -0,0 +1,785 @@
1
+ // The extractor's check (core/extract.ts): the rule an extraction prints is run beside the code it was read from, and
2
+ // any difference refuses the extraction. The code runs as it ships, compiled by TypeScript and loaded into a VM of its
3
+ // own (no require but the modules named, Date.now() the request's time, Math.random refused), with a counter at each
4
+ // branch arm (an if's two arms, a ternary's, each case and the switch's fall-through, the right side of && || ??), so
5
+ // the evidence says which of the code's branches the requests reached. The rule runs through its reference evaluator
6
+ // (`rule.interpreter()`) and the generated JavaScript (`rule.compiled()`), and the two are compared too. Requests:
7
+ // - runs from the start: the params, then requests drawn at random, near the boundaries (0, ±1, the code's constants,
8
+ // the state's own values ±1, the params ±1, the edges of the safe integers) and with the time moving on or back;
9
+ // - single steps from states drawn at random (every value of each field's type, maps with a few keys): a rule's proof
10
+ // is about every state, not only those reached;
11
+ // - single steps from the prover's own counterexamples: for each branch condition the rule reads, proveSteps is asked
12
+ // to refute "the condition never holds", and the state and request it refutes it with are run on both sides.
13
+ // After each request, every state variable, every map cell, the method's result and whether the request was refused
14
+ // are compared. A value outside the safe integers in the code, where the rule's runtime refuses the step (it never
15
+ // rounds), is counted apart: the rule's claim stops at 2^53.
16
+ import ts from 'typescript';
17
+ const proc = globalThis.process;
18
+ const vmOf = () => { const m = proc?.getBuiltinModule?.('node:vm'); if (!m)
19
+ throw new Error('the check runs the code in node:vm (Node 20.16 or later, or Bun)'); return m; };
20
+ import { Int, Term, bool, int, intern, interned, nat, no, oneOf, str, proveSteps } from "./dsl.js";
21
+ import { allowed } from "./watch.js";
22
+ import { normalize, resolveIn, scriptKind } from "./extract-read.js";
23
+ import * as I from "./extract-ir.js";
24
+ // --- the code, instrumented and loaded ------------------------------------------------------------------------------
25
+ export function instrument(code, file, tail = '') {
26
+ const sf = ts.createSourceFile(file, code, ts.ScriptTarget.ES2022, true, scriptKind(file));
27
+ const arms = [], edits = [];
28
+ const loc = (n) => { const { line, character } = sf.getLineAndCharacterOfPosition(n.getStart()); return `${file.split('/').pop()}:${line + 1}:${character + 1}`; };
29
+ const arm = (label, n) => { arms.push({ label, where: loc(n), pos: n.getStart() }); return arms.length - 1; };
30
+ const visit = (n) => {
31
+ if (ts.isIfStatement(n)) {
32
+ const t = arm('if: then', n);
33
+ edits.push([n.thenStatement.getStart(), `{__cov(${t});`], [n.thenStatement.end, '}']);
34
+ const e = arm('if: else', n);
35
+ if (n.elseStatement)
36
+ edits.push([n.elseStatement.getStart(), `{__cov(${e});`], [n.elseStatement.end, '}']);
37
+ else
38
+ edits.push([n.thenStatement.end, ` else {__cov(${e});}`]);
39
+ }
40
+ else if (ts.isConditionalExpression(n)) {
41
+ const t = arm('?: true', n), f = arm('?: false', n);
42
+ edits.push([n.whenTrue.getStart(), `(__cov(${t}), `], [n.whenTrue.end, ')'], [n.whenFalse.getStart(), `(__cov(${f}), `], [n.whenFalse.end, ')']);
43
+ }
44
+ else if (ts.isSwitchStatement(n)) {
45
+ for (const cl of n.caseBlock.clauses) {
46
+ const i = arm(ts.isCaseClause(cl) ? `case ${cl.expression.getText()}` : 'default', cl);
47
+ edits.push([cl.statements.pos, ` __cov(${i});`]);
48
+ }
49
+ if (!n.caseBlock.clauses.some(ts.isDefaultClause)) {
50
+ const i = arm('switch: no case', n);
51
+ edits.push([n.caseBlock.getStart() + 1, ` default: __cov(${i}); break;`]);
52
+ }
53
+ }
54
+ else if (ts.isBinaryExpression(n) && [ts.SyntaxKind.AmpersandAmpersandToken, ts.SyntaxKind.BarBarToken, ts.SyntaxKind.QuestionQuestionToken].includes(n.operatorToken.kind)) {
55
+ const i = arm(`${n.operatorToken.getText()}: right side`, n);
56
+ edits.push([n.right.getStart(), `(__cov(${i}), `], [n.right.end, ')']);
57
+ }
58
+ ts.forEachChild(n, visit);
59
+ };
60
+ visit(sf);
61
+ // Later positions first; at one position, in the order made reversed (a closing paren before the next opening one).
62
+ const order = edits.map((e, i) => [...e, i]).sort((a, b) => b[0] - a[0] || b[2] - a[2]);
63
+ let out = code;
64
+ for (const [pos, txt] of order)
65
+ out = out.slice(0, pos) + txt + out.slice(pos);
66
+ out += tail;
67
+ const js = ts.transpileModule(out, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022, esModuleInterop: true, jsx: ts.JsxEmit.React }, fileName: file.replace(/\.js$/, '.ts').replace(/\.jsx$/, '.tsx') }).outputText;
68
+ return { js, arms };
69
+ }
70
+ export function sandbox(code, file, expose, modules = {}, init, files = {}) {
71
+ const vm = vmOf();
72
+ const { js, arms } = instrument(code, file, init ? `\n;(globalThis as any).__gdpInit = () => (${init});\n` : '');
73
+ const counts = arms.map(() => 0);
74
+ let now = 0;
75
+ const module = { exports: {} };
76
+ const ctx = vm.createContext({
77
+ __cov: (i) => { counts[i]++; }, __now: () => now, module, exports: module.exports,
78
+ // A relative import among the files given: loaded in this VM (not counted: the branches are the entry's). A module
79
+ // the step doesn't name (React, for the component beside a reducer): a stub that throws when read, so a step that
80
+ // reads it fails the check rather than running without it.
81
+ require: (name) => (name in modules ? modules[name] : name.startsWith('.') && Object.keys(files).length ? load(ENTRY, name) : new Proxy({}, {
82
+ get: (_, k) => { if (k === '__esModule' || typeof k === 'symbol')
83
+ return undefined; throw new Error(`the check loads no module ${name} (its ${String(k)} was read)`); },
84
+ ownKeys: () => [],
85
+ })),
86
+ console: { log() { }, warn() { }, error() { }, info() { }, debug() { } },
87
+ });
88
+ // The files given, by their place beside the entry's; each loaded once.
89
+ const ENTRY = `/v/${file.split('/').pop()}`, abs = Object.fromEntries(Object.entries(files).map(([p, c]) => [normalize(`/v/${p}`), c])), loaded = new Map();
90
+ const load = (from, spec) => {
91
+ const at = resolveIn(abs, from, spec);
92
+ if (!at)
93
+ throw new Error(`the check has no file for ${spec}`);
94
+ if (loaded.has(at))
95
+ return loaded.get(at);
96
+ const m = { exports: {} };
97
+ loaded.set(at, m.exports);
98
+ const js = ts.transpileModule(abs[at], { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022, esModuleInterop: true, jsx: ts.JsxEmit.React }, fileName: at.replace(/\.js$/, '.ts').replace(/\.jsx$/, '.tsx') }).outputText;
99
+ const f = vm.runInContext(`(function (module, exports, require) {${js}\n})`, ctx);
100
+ f(m, m.exports, (s2) => (s2 in modules ? modules[s2] : s2.startsWith('.') ? load(at, s2) : (() => { throw new Error(`the check loads no module ${s2}`); })()));
101
+ loaded.set(at, m.exports);
102
+ return m.exports;
103
+ };
104
+ vm.runInContext('Date.now = () => __now(); Math.random = () => { throw new Error("Math.random in a step") }', ctx);
105
+ vm.runInContext(`${js}\n;globalThis.__gdp = {${expose.map(n => { if (n === 'default')
106
+ return 'default: module.exports.default'; const [h, ...rest] = n.split('.'); return `${JSON.stringify(n)}: (typeof ${h} !== 'undefined' ? ${h} : module.exports.${h})${rest.map(x => `.${x}`).join('')}`; }).join(', ')}};`, ctx, { timeout: 2000, filename: file });
107
+ const script = new vm.Script('globalThis.__r = (() => { try { return {ok: true, value: __gdp[__f].apply(__self, __args)} } catch (e) { return {ok: false, error: String(e && e.message || e)} } })()');
108
+ const call = (f, self, args) => {
109
+ Object.assign(ctx, { __f: f, __self: self, __args: args });
110
+ script.runInContext(ctx, { timeout: 1000 });
111
+ return ctx.__r;
112
+ };
113
+ return { ctx, counts, arms, call, setNow: n => { now = n; }, get: name => vm.runInContext(`__gdp[${JSON.stringify(name)}]`, ctx) };
114
+ }
115
+ const isMap = (x) => Object.prototype.toString.call(x) === '[object Map]';
116
+ class Outside extends Error {
117
+ }
118
+ class Refused extends Error {
119
+ }
120
+ // The code's value as a snapshot, by the layout; what the rule has no place for is a difference.
121
+ function snapOf(v, layout, m, consts, out = { leaves: {}, maps: {} }, path = 'state') {
122
+ switch (layout.k) {
123
+ case 'scalar': {
124
+ const sort = m.state.find(x => x.name === layout.name)?.sort;
125
+ if (sort?.k === 'num' && !(typeof v === 'number' && Number.isSafeInteger(v))) {
126
+ if (typeof v === 'number')
127
+ throw new Outside(`${path} is ${v}`);
128
+ throw new Error(`${path} is ${JSON.stringify(v)}, not a number`);
129
+ }
130
+ if (sort?.k === 'bool' && typeof v !== 'boolean')
131
+ throw new Error(`${path} is ${JSON.stringify(v)}, not a boolean`);
132
+ if (sort?.k === 'choice' && !(typeof v === 'string' && sort.values.includes(v)))
133
+ throw new Error(`${path} is ${JSON.stringify(v)}, not one of its literals`);
134
+ if (sort?.k === 'str' && typeof v !== 'string')
135
+ throw new Error(`${path} is ${JSON.stringify(v)}, not a string`);
136
+ out.leaves[layout.name] = v;
137
+ return out;
138
+ }
139
+ case 'rec': {
140
+ if (typeof v !== 'object' || v === null)
141
+ throw new Error(`${path} is ${JSON.stringify(v)}, not an object`);
142
+ const own = Object.keys(v), want = layout.fields.map(([f]) => f).filter(f => !f.endsWith('()'));
143
+ for (const k of own)
144
+ if (!want.includes(k))
145
+ throw new Error(`${path} has a field ${k} the rule doesn't`);
146
+ for (const [f, sub] of layout.fields)
147
+ if (!f.endsWith('()'))
148
+ snapOf(v[f], sub, m, consts, out, `${path}.${f}`);
149
+ return out;
150
+ }
151
+ case 'map': {
152
+ const d = m.maps.find(x => x.name === layout.name), cells = {};
153
+ const entries = isMap(v) ? [...v.entries()] : typeof v === 'object' && v !== null ? Object.entries(v) : (() => { throw new Error(`${path} is not a map`); })();
154
+ for (const [k, x] of entries) {
155
+ if (d.key === 'num' && !(typeof k === 'number' || (typeof k === 'string' && /^\d+$/.test(k))))
156
+ throw new Error(`${path} has a key ${String(k)} that isn't a natural`);
157
+ if (d.key === 'str' && typeof k !== 'string')
158
+ throw new Error(`${path} has a key ${String(k)} that isn't a string`);
159
+ const cell = {};
160
+ if (d.scalar)
161
+ cell.value = checkCell(x, d.fields[0], `${path}[${String(k)}]`);
162
+ else {
163
+ if (typeof x !== 'object' || x === null)
164
+ throw new Error(`${path}[${String(k)}] is ${JSON.stringify(x)}, not an object`);
165
+ for (const kk of Object.keys(x))
166
+ if (!d.fields.some(f => f.name === kk))
167
+ throw new Error(`${path}[${String(k)}] has a field ${kk} the rule doesn't`);
168
+ for (const f of d.fields)
169
+ cell[f.name] = checkCell(x[f.name], f, `${path}[${String(k)}].${f.name}`);
170
+ }
171
+ cells[String(k)] = cell;
172
+ }
173
+ out.maps[d.name] = cells;
174
+ return out;
175
+ }
176
+ case 'const': {
177
+ const want = layout.value.s === 'str' ? (layout.value.e.op === 'slit' ? layout.value.e.value : undefined) : consts(layout.value.e);
178
+ if (v !== want)
179
+ throw new Error(`${path} is ${JSON.stringify(v)}, the constant ${JSON.stringify(want)} the rule takes it for`);
180
+ return out;
181
+ }
182
+ }
183
+ }
184
+ function checkCell(x, f, path) {
185
+ if (f.sort.k === 'num') {
186
+ if (typeof x === 'number' && Number.isSafeInteger(x))
187
+ return x;
188
+ if (typeof x === 'number')
189
+ throw new Outside(`${path} is ${x}`);
190
+ throw new Error(`${path} is ${JSON.stringify(x)}, not a number`);
191
+ }
192
+ if (f.sort.k === 'bool') {
193
+ if (typeof x === 'boolean')
194
+ return x;
195
+ throw new Error(`${path} is ${JSON.stringify(x)}, not a boolean`);
196
+ }
197
+ if (f.sort.k === 'choice') {
198
+ if (typeof x === 'string' && f.sort.values.includes(x))
199
+ return x;
200
+ throw new Error(`${path} is ${JSON.stringify(x)}`);
201
+ }
202
+ throw new Error(`${path}: a string cell`);
203
+ }
204
+ // A snapshot as the code's own value, built inside the sandbox's realm (its Maps are the code's Maps).
205
+ function valueOf(s, layout, m, consts, ctx) {
206
+ const tree = (l) => {
207
+ switch (l.k) {
208
+ case 'scalar': return s.leaves[l.name];
209
+ case 'rec': return Object.fromEntries(l.fields.filter(([f]) => !f.endsWith('()')).map(([f, sub]) => [f, tree(sub)]));
210
+ case 'map': {
211
+ const d = m.maps.find(x => x.name === l.name);
212
+ const entries = Object.entries(s.maps[d.name] ?? {}).map(([k, c]) => [d.key === 'num' ? Number(k) : k, d.scalar ? c.value : c]);
213
+ return { $map: d.js, entries };
214
+ }
215
+ case 'const': return l.value.s === 'str' ? (l.value.e.op === 'slit' ? l.value.e.value : undefined) : consts(l.value.e);
216
+ }
217
+ };
218
+ ctx.__in = JSON.stringify(tree(layout));
219
+ return vmOf().runInContext('JSON.parse(__in, (k, v) => v && typeof v === "object" && v.$map ? (v.$map === "Map" ? new Map(v.entries) : Object.fromEntries(v.entries)) : v)', ctx);
220
+ }
221
+ const showSnap = (s) => JSON.stringify({ ...s.leaves, ...Object.fromEntries(Object.entries(s.maps).map(([k, v]) => [k, v])) });
222
+ const sameSnap = (a, b) => {
223
+ for (const k of new Set([...Object.keys(a.leaves), ...Object.keys(b.leaves)]))
224
+ if (a.leaves[k] !== b.leaves[k])
225
+ return `${k} is ${JSON.stringify(a.leaves[k])} in the code, ${JSON.stringify(b.leaves[k])} in the rule`;
226
+ for (const k of new Set([...Object.keys(a.maps), ...Object.keys(b.maps)])) {
227
+ const x = a.maps[k] ?? {}, y = b.maps[k] ?? {};
228
+ for (const key of new Set([...Object.keys(x), ...Object.keys(y)]))
229
+ if (JSON.stringify(x[key]) !== JSON.stringify(y[key]))
230
+ return `${k}[${key}] is ${JSON.stringify(x[key])} in the code, ${JSON.stringify(y[key])} in the rule`;
231
+ }
232
+ return undefined;
233
+ };
234
+ // --- the rule's side ------------------------------------------------------------------------------------------------
235
+ export const kindOfVar = (v, sorts, at = v.name) => (v.sort.k === 'num' ? (sorts.get(at) === 'nat' ? nat : int) : v.sort.k === 'bool' ? bool : v.sort.k === 'choice' ? oneOf(...v.sort.values) : str());
236
+ const idText = (id) => interned().find(([, n]) => n === id)?.[0];
237
+ function ruleSnap(r, m, st, sorts) {
238
+ const d = r.decode(st), leaves = {}, maps = {};
239
+ for (const v of m.state)
240
+ if (!m.outputs.includes(v.name))
241
+ leaves[v.name] = d[v.name];
242
+ for (const md of m.maps) {
243
+ const cells = {};
244
+ for (const [k, c] of Object.entries((d[md.name] ?? {}))) {
245
+ if (!c.has)
246
+ continue;
247
+ const key = md.key === 'str' ? idText(Number(k)) ?? `#${k}` : k;
248
+ cells[key] = Object.fromEntries(md.fields.map(f => [f.name, c[f.name]]));
249
+ }
250
+ maps[md.name] = cells;
251
+ }
252
+ void sorts;
253
+ return { leaves, maps };
254
+ }
255
+ // A snapshot as a state of the rule (each variable and cell by its kind).
256
+ function ruleState(base, s, m, sorts) {
257
+ const scalars = { ...base.scalars }, maps = Object.fromEntries(Object.entries(base.maps).map(([k]) => [k, new Map()]));
258
+ for (const v of m.state)
259
+ if (v.name in s.leaves)
260
+ Object.assign(scalars, kindOfVar(v, sorts).encode(v.name, s.leaves[v.name]));
261
+ for (const d of m.maps) {
262
+ const kind = cellKind(d, sorts);
263
+ for (const [k, c] of Object.entries(s.maps[d.name] ?? {})) {
264
+ const key = d.key === 'str' ? intern(k) : Number(k);
265
+ for (const [part, x] of Object.entries(kind.encode(d.name, { has: true, ...c })))
266
+ if (x !== 0)
267
+ (maps[part] ??= new Map()).set(key, x);
268
+ }
269
+ }
270
+ return { ...base, scalars, maps };
271
+ }
272
+ import { record } from "./dsl.js";
273
+ const cellKind = (d, sorts) => record({ has: bool, ...Object.fromEntries(d.fields.map(f => [f.name, kindOfVar(f, sorts, `${d.name}.${f.name}`)])) });
274
+ const seeded = (seed) => { let x = seed >>> 0 || 1; return n => { x = (x * 1103515245 + 12345) % 2 ** 31; return Math.floor(x / 2 ** 31 * n); }; };
275
+ const BIG = [Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER - 1, 2 ** 31, 2 ** 32];
276
+ function constantsOf(m) {
277
+ const out = new Set([0, 1]);
278
+ const go = (x) => { if (x && typeof x === 'object') {
279
+ const o = x;
280
+ if (o.op === 'const' && typeof o.v === 'number')
281
+ out.add(o.v);
282
+ if (typeof o.k === 'number')
283
+ out.add(o.k);
284
+ Object.values(o).forEach(go);
285
+ } };
286
+ go([m.writes, m.mapWrites, m.refuse, m.pre, m.init]);
287
+ return [...out];
288
+ }
289
+ function draw(sort, sorts, name, rand, near, bound, strs) {
290
+ switch (sort.k) {
291
+ case 'bool': return rand(2) === 1;
292
+ case 'choice': return sort.values[rand(sort.values.length)];
293
+ case 'str': return strs[rand(strs.length)];
294
+ case 'num': {
295
+ const natural = sorts.get(name) === 'nat', pick = rand(10);
296
+ let x;
297
+ if (pick < 4)
298
+ x = rand(bound + 1) * (natural || rand(2) ? 1 : -1);
299
+ else if (pick < 8 && near.length) {
300
+ const b = near[rand(near.length)];
301
+ x = b + rand(3) - 1;
302
+ }
303
+ else if (pick < 9)
304
+ x = BIG[rand(BIG.length)] * (natural || rand(2) ? 1 : -1);
305
+ else
306
+ x = -1 - rand(bound);
307
+ // The code's domain is every safe integer: a natural input is drawn below 0 too (the code must refuse it).
308
+ return x;
309
+ }
310
+ }
311
+ }
312
+ export function check(code, file, m, r, sorts, opts = {}) {
313
+ const t0 = performance.now(), rand = seeded(opts.seed ?? 7), bound = opts.bound ?? 12;
314
+ const isClass = m.shape === 'class', fns = m.shape === 'class' ? [m.entry] : [...new Set(m.events.map(e => e.call))];
315
+ const box = sandbox(code, file, fns, opts.modules, m.initSource, opts.files);
316
+ const interp = r.interpreter(), gen = r.compiled(), machine = r.machine;
317
+ const ev = { runs: 0, requests: 0, fromStates: 0, probes: { conditions: 0, witnesses: 0, steps: 0 }, refusedBoth: 0, outside: 0, edge: 0, compiledAgreed: 0, coverage: { arms: box.arms.length, hit: 0, missed: [] }, ms: 0 };
318
+ const consts = constantsOf(m), strs = ['a', 'b', 'c', ''];
319
+ const paramKinds = m.params.map(v => [v, kindOfVar(v, sorts)]), inputKinds = m.inputs.map(v => [v, kindOfVar(v, sorts)]);
320
+ // A term over the params at their values (a constant field, a start).
321
+ const evalAt = (env) => (t) => evalTerm(t, env);
322
+ const fail = (what) => { ev.mismatch = what; return finish(); };
323
+ // The arms of the code the step reads (the entry, its methods, the functions it inlines; a class's constructor too).
324
+ const inSpan = (a) => !m.spans || m.spans.some(([s0, e0]) => a.pos >= s0 && a.pos < e0);
325
+ const counted = box.arms.map((a, i) => [a, i]).filter(([a]) => inSpan(a));
326
+ ev.coverage.arms = counted.length;
327
+ const finish = () => {
328
+ ev.coverage.hit = counted.filter(([, i]) => box.counts[i] > 0).length;
329
+ ev.coverage.missed = counted.filter(([, i]) => box.counts[i] === 0).map(([a]) => `${a.label} at ${a.where}`);
330
+ ev.ms = Math.round(performance.now() - t0);
331
+ return ev;
332
+ };
333
+ const request = (params, inputs, e) => {
334
+ const build = (a) => (a.k === 'input' ? inputs[a.name] : a.k === 'lit' ? a.value : a.k === 'rec' ? Object.fromEntries(a.fields.map(([f, x]) => [f, build(x)])) : a.k === 'lazy'
335
+ ? Object.fromEntries([...m.inputs].filter(v => m.lazy?.get(v.name)?.prefix === a.prefix).map(v => [m.lazy.get(v.name).field, inputs[v.name]]))
336
+ : undefined);
337
+ void params;
338
+ return e.args.map(build);
339
+ };
340
+ const draws = (st, params) => [...consts, ...Object.values(st.leaves).filter((x) => typeof x === 'number'), ...Object.values(params).filter((x) => typeof x === 'number')];
341
+ let lastNow = 1_000;
342
+ const drawRequest = (st, params) => {
343
+ const e = m.events[rand(m.events.length)], near = draws(st, params), inputs = {};
344
+ for (const v of m.inputs) {
345
+ if (v.name in e.select) {
346
+ inputs[v.name] = e.select[v.name];
347
+ continue;
348
+ }
349
+ if (v.note?.startsWith('Date.now()')) {
350
+ const d = rand(6);
351
+ lastNow = d === 0 ? Math.max(0, lastNow - rand(50)) : d === 1 ? rand(10_000) : lastNow + rand(d * 40);
352
+ inputs[v.name] = lastNow;
353
+ continue;
354
+ }
355
+ const keys = Object.values(st.maps).flatMap(c => Object.keys(c));
356
+ // An input given as a natural (domains) is drawn as one: the claim is for those, as the user said.
357
+ const x = draw(v.sort, sorts, v.name, rand, near, bound, [...strs, ...keys]);
358
+ inputs[v.name] = opts.given?.[v.name] === 'nat' && typeof x === 'number' ? Math.abs(x) : x;
359
+ }
360
+ return { e, inputs };
361
+ };
362
+ const ruleInputs = (inputs, e) => {
363
+ const used = new Set();
364
+ const walk = (a) => { if (a.k === 'input')
365
+ used.add(a.name);
366
+ else if (a.k === 'rec')
367
+ a.fields.forEach(([, x]) => walk(x));
368
+ else if (a.k === 'lazy')
369
+ for (const v of m.inputs)
370
+ if (m.lazy?.get(v.name)?.prefix === a.prefix)
371
+ used.add(v.name); };
372
+ e.args.forEach(walk);
373
+ for (const v of m.inputs)
374
+ if (v.note?.startsWith('Date.now()'))
375
+ used.add(v.name);
376
+ // An input the event doesn't bring: its kind's first value (the rule reads it only under another event).
377
+ return Object.fromEntries(m.inputs.map(v => [v.name, v.name in e.select ? e.select[v.name] : used.has(v.name) ? inputs[v.name] : v.sort.k === 'num' ? 0 : v.sort.k === 'bool' ? false : v.sort.k === 'choice' ? v.sort.values[0] : '']));
378
+ };
379
+ // Steps the code and the rule from one state; undefined when they agree (the next state on both sides is returned
380
+ // through `next`), else the difference.
381
+ const step = (params, ps, side, st, inputs, e, next, where) => {
382
+ const args = request(params, inputs, e), raw = ruleInputs(inputs, e);
383
+ const nowVar = m.inputs.find(v => v.note?.startsWith('Date.now()'));
384
+ if (nowVar)
385
+ box.setNow(inputs[nowVar.name]);
386
+ // The code.
387
+ let code;
388
+ try {
389
+ if (isClass) {
390
+ const self = side.self, res = box.call('$method', self, [e.call, args]);
391
+ if (!res.ok)
392
+ code = { refused: res.error };
393
+ else
394
+ code = { snap: snapOf(self, m.layout, m, evalAt(params)), out: res.value, self };
395
+ }
396
+ else {
397
+ const input = valueOf(side.snap, m.layout, m, evalAt(params), box.ctx), before = JSON.stringify(input, mapReplacer);
398
+ const res = box.call(e.call, undefined, [input, ...args.slice(1)]);
399
+ if (JSON.stringify(input, mapReplacer) !== before)
400
+ return `${where}: ${e.call} changed the state it was given`;
401
+ code = res.ok ? { snap: snapOf(res.value, m.layout, m, evalAt(params)) } : { refused: res.error };
402
+ }
403
+ }
404
+ catch (x) {
405
+ if (x instanceof Outside)
406
+ code = { outside: x.message };
407
+ else
408
+ return `${where}: the code's state after the request: ${x.message}`;
409
+ }
410
+ // The rule.
411
+ let rule = { refused: 'not run' };
412
+ let enc;
413
+ try {
414
+ enc = r.encodeInput(raw, params);
415
+ }
416
+ catch (x) {
417
+ rule = { refused: `outside the input's kind (${x.message})` };
418
+ }
419
+ if (enc) {
420
+ try {
421
+ if (!allowed(machine, interp, ps, st, enc))
422
+ throw new Refused('the assumption');
423
+ const s1 = interp.step(ps, st, enc);
424
+ rule = { st: s1 };
425
+ const s2 = gen.step(ps, gen.fork(st), enc);
426
+ if (JSON.stringify(r.decode(s2)) !== JSON.stringify(r.decode(s1)))
427
+ return `${where}: the rule's interpreter and its generated JavaScript differ (${JSON.stringify(r.decode(s1))} against ${JSON.stringify(r.decode(s2))})`;
428
+ ev.compiledAgreed++;
429
+ }
430
+ catch (x) {
431
+ rule = x instanceof Refused ? { refused: x.message } : /2\^53|safe integer/.test(x.message) ? { outside: x.message } : { refused: x.message };
432
+ }
433
+ }
434
+ const req = `${e.call}(${JSON.stringify(args).slice(1, -1)})${nowVar ? ` at ${inputs[nowVar.name]}` : ''}`;
435
+ const from = `from ${showSnap(side.snap)}${m.params.length ? ` with ${JSON.stringify(params)}` : ''}`;
436
+ if ('outside' in code || 'outside' in rule) {
437
+ // The code past the safe integers: the rule's runtime must refuse there too (it never rounds).
438
+ next.stop = true;
439
+ if ('outside' in code) {
440
+ if ('st' in rule)
441
+ return `${where}: ${req} ${from}: the code leaves the safe integers (${code.outside}) where the rule takes the step`;
442
+ ev.outside++;
443
+ return undefined;
444
+ }
445
+ if ('refused' in code) {
446
+ ev.refusedBoth++;
447
+ return undefined;
448
+ }
449
+ // The rule's runtime refuses a sum or a comparison past 2^53 where the code's values are still safe: the edge
450
+ // its claim stops at, counted apart (a sample kept), not a difference in what the step computes.
451
+ ev.edge++;
452
+ ev.edgeSample ??= `${req} ${from}`;
453
+ return undefined;
454
+ }
455
+ if ('refused' in code && 'refused' in rule) {
456
+ // A refusal leaves the state as it was: the object the code threw from must be as it was too.
457
+ if (isClass) {
458
+ try {
459
+ const after = snapOf(side.self, m.layout, m, evalAt(params)), d = sameSnap(after, side.snap);
460
+ if (d)
461
+ return `${where}: ${req} ${from}: the code throws (${code.refused}) after changing the object: ${d}`;
462
+ }
463
+ catch (x) {
464
+ return `${where}: ${req} ${from}: the code throws after changing the object (${x.message})`;
465
+ }
466
+ }
467
+ ev.refusedBoth++;
468
+ return undefined;
469
+ }
470
+ if ('refused' in code)
471
+ return `${where}: ${req} ${from}: the code throws (${code.refused}), the rule takes the step`;
472
+ if ('refused' in rule)
473
+ return `${where}: ${req} ${from}: the rule refuses it (${rule.refused}), the code doesn't`;
474
+ const ruleSide = ruleSnap(r, m, rule.st, sorts), diff = sameSnap(code.snap, ruleSide);
475
+ if (diff)
476
+ return `${where}: ${req} ${from}: ${diff}`;
477
+ if (isClass && code.out !== undefined) {
478
+ const o = m.outputs.find(n => n === `${e.call}_result`);
479
+ if (o !== undefined && r.decode(rule.st)[o] !== code.out)
480
+ return `${where}: ${req} ${from}: ${e.call} returns ${JSON.stringify(code.out)}, the rule's ${o} is ${JSON.stringify(r.decode(rule.st)[o])}`;
481
+ }
482
+ next.side = { snap: code.snap, ...(code.self ? { self: code.self } : {}) };
483
+ next.st = rule.st;
484
+ return undefined;
485
+ };
486
+ // A class's object: made by its constructor, or set to a snapshot.
487
+ if (isClass)
488
+ vmOf().runInContext(`__gdp.$method = function (name, args) { return this[name](...args) }; __gdp.$new = function (...args) { return new __gdp[${JSON.stringify(m.entry)}](...args) }; __gdp.$at = function (fields) { return Object.assign(Object.create(__gdp[${JSON.stringify(m.entry)}].prototype), fields) }`, box.ctx);
489
+ const objectAt = (snap, params) => box.call('$at', undefined, [valueOf(snap, m.layout, m, evalAt(params), box.ctx)]).ok ? box.ctx.__r.value : (() => { throw new Error('could not make the object'); })();
490
+ const drawParams = () => Object.fromEntries(m.params.map(v => [v.name, v.note?.startsWith('Date.now()') ? rand(10_000) : draw(v.sort, sorts, v.name, rand, consts, bound, strs)]));
491
+ const start = (params) => {
492
+ const ctorRefuses = (() => { const pre = evalTerm(m.pre, params); return pre !== true; })();
493
+ let ps;
494
+ try {
495
+ ps = r.encodeParams(params);
496
+ }
497
+ catch {
498
+ ps = undefined;
499
+ }
500
+ if (isClass) {
501
+ const now0 = m.params.find(v => v.note?.startsWith('Date.now()'));
502
+ if (now0)
503
+ box.setNow(params[now0.name]);
504
+ const made = box.call('$new', undefined, (m.ctorArgs ?? []).filter(n => n !== now0?.name).map(n => params[n]));
505
+ const ruleRefuses = ps === undefined || ctorRefuses;
506
+ if (!made.ok)
507
+ return ruleRefuses ? {} : { problem: `new ${m.entry}(${JSON.stringify(params)}) throws (${made.error}), the rule's precondition holds` };
508
+ if (ruleRefuses)
509
+ return { problem: `new ${m.entry}(${JSON.stringify(params)}) is made, the rule's ${ps === undefined ? 'param kinds refuse' : 'precondition refuses'} it` };
510
+ const st = interp.init(ps);
511
+ try {
512
+ const snap = snapOf(made.value, m.layout, m, evalAt(params));
513
+ const diff = sameSnap(snap, ruleSnap(r, m, st, sorts));
514
+ if (diff)
515
+ return { problem: `new ${m.entry}(${JSON.stringify(params)}): ${diff}` };
516
+ return { side: { snap, self: made.value }, st, ps: ps };
517
+ }
518
+ catch (x) {
519
+ return { problem: `new ${m.entry}: ${x.message}` };
520
+ }
521
+ }
522
+ const st = interp.init(ps ?? {}), snap = ruleSnap(r, m, st, sorts);
523
+ // The code's own initial state (where the code gives it), against the rule's.
524
+ if (m.initSource) {
525
+ const made = vmOf().runInContext('(() => { try { return {ok: true, value: __gdpInit()} } catch (e) { return {ok: false, error: String(e)} } })()', box.ctx);
526
+ if (!made.ok)
527
+ return { problem: `the initial state throws (${made.error})` };
528
+ try {
529
+ const diff = sameSnap(snapOf(made.value, m.layout, m, evalAt(params)), snap);
530
+ if (diff)
531
+ return { problem: `the initial state: ${diff}` };
532
+ }
533
+ catch (x) {
534
+ return { problem: `the initial state: ${x.message}` };
535
+ }
536
+ }
537
+ return { side: { snap }, st, ps: ps ?? {} };
538
+ };
539
+ const runs = opts.runs ?? 200, depth = opts.depth ?? 12;
540
+ for (let run = 0; run < runs; run++) {
541
+ const params = drawParams(), s0 = start(params);
542
+ if (s0.problem)
543
+ return fail(`at the start: ${s0.problem}`);
544
+ if (!s0.side)
545
+ continue;
546
+ ev.runs++;
547
+ let side = s0.side, st = s0.st;
548
+ for (let d = 0; d < depth; d++) {
549
+ const { e, inputs } = drawRequest(side.snap, params), next = {};
550
+ const diff = step(params, s0.ps, side, st, inputs, e, next, `run ${run + 1}, request ${d + 1}`);
551
+ ev.requests++;
552
+ if (diff)
553
+ return fail(diff);
554
+ // Past the safe integers the two sides part by design: the run ends there.
555
+ if (next.stop)
556
+ break;
557
+ if (next.side) {
558
+ side = next.side;
559
+ st = next.st;
560
+ }
561
+ }
562
+ }
563
+ // Steps from drawn states.
564
+ const drawSnap = (params) => {
565
+ const leaves = {}, maps = {};
566
+ for (const v of m.state)
567
+ if (!m.outputs.includes(v.name))
568
+ leaves[v.name] = draw(v.sort, sorts, v.name, rand, [...consts, ...Object.values(params).filter((x) => typeof x === 'number')], bound, strs);
569
+ for (const v of m.state)
570
+ if (v.name in leaves && v.sort.k === 'num' && sorts.get(v.name) === 'nat' && leaves[v.name] < 0)
571
+ leaves[v.name] = -leaves[v.name];
572
+ for (const d of m.maps) {
573
+ const cells = {};
574
+ for (let i = rand(4); i > 0; i--) {
575
+ const key = d.key === 'str' ? strs[rand(3)] : String(rand(4));
576
+ cells[key] = Object.fromEntries(d.fields.map(f => { let x = draw(f.sort, sorts, `${d.name}.${f.name}`, rand, consts, bound, strs); if (typeof x === 'number' && sorts.get(`${d.name}.${f.name}`) === 'nat')
577
+ x = Math.abs(x); return [f.name, x]; }));
578
+ }
579
+ maps[d.name] = cells;
580
+ }
581
+ for (const v of m.state)
582
+ if (v.name in leaves && v.sort.k === 'num' && Math.abs(leaves[v.name]) > Number.MAX_SAFE_INTEGER / 4)
583
+ leaves[v.name] = rand(bound);
584
+ return { leaves, maps };
585
+ };
586
+ const fromState = (params, snap, inputs, e, where) => {
587
+ let ps;
588
+ try {
589
+ ps = r.encodeParams(params);
590
+ }
591
+ catch {
592
+ return undefined;
593
+ }
594
+ if (evalTerm(m.pre, params) !== true)
595
+ return undefined;
596
+ const st = ruleState(interp.init(ps), snap, m, sorts);
597
+ const side = { snap, ...(isClass ? { self: objectAt(snap, params) } : {}) };
598
+ return step(params, ps, side, st, inputs, e, {}, where);
599
+ };
600
+ for (let i = 0; i < (opts.states ?? 400); i++) {
601
+ const params = drawParams(), snap = drawSnap(params), { e, inputs } = drawRequest(snap, params);
602
+ const diff = fromState(params, snap, inputs, e, `drawn state ${i + 1}`);
603
+ ev.fromStates++;
604
+ if (diff)
605
+ return fail(diff);
606
+ }
607
+ // Steps from the prover's counterexamples: each condition of the step, refuted as "never holds".
608
+ if (opts.probes !== false) {
609
+ const conds = conditionsOf(m);
610
+ for (const [i, c] of conds.entries()) {
611
+ ev.probes.conditions++;
612
+ let law;
613
+ try {
614
+ law = r.stepLaw(`probe ${i + 1}`, () => no, env => condAt(c, env));
615
+ }
616
+ catch {
617
+ continue;
618
+ }
619
+ const v = proveSteps(r, [], [law], { search: false });
620
+ if (v.proven || !v.witness)
621
+ continue;
622
+ ev.probes.witnesses++;
623
+ const w = v.witness, params = {}, inputs = {}, leaves = {};
624
+ let ok = true;
625
+ const dec = (vv, k, at) => { try {
626
+ const x = k.decode(vv.name, Object.fromEntries(k.vars(vv.name).map(part => [part, w[part] ?? 0])));
627
+ at[vv.name] = x;
628
+ }
629
+ catch {
630
+ ok = false;
631
+ } };
632
+ for (const [vv, k] of paramKinds)
633
+ dec(vv, k, params);
634
+ for (const [vv, k] of inputKinds)
635
+ dec(vv, k, inputs);
636
+ for (const vv of m.state)
637
+ dec(vv, kindOfVar(vv, sorts), leaves);
638
+ if (!ok)
639
+ continue;
640
+ const e = m.events.find(x => Object.entries(x.select).every(([n, val]) => inputs[n] === val)) ?? m.events[0];
641
+ const diff = fromState(params, { leaves, maps: Object.fromEntries(m.maps.map(d => [d.name, {}])) }, inputs, e, `the prover's witness for ${showCond(c)}`);
642
+ ev.probes.steps++;
643
+ if (diff)
644
+ return fail(diff);
645
+ }
646
+ }
647
+ return finish();
648
+ }
649
+ const mapReplacer = (_, v) => (isMap(v) ? { $map: [...v.entries()] } : v);
650
+ // The conditions a step reads (each branch's, each refusal's), as a probe asks the prover to reach.
651
+ function conditionsOf(m) {
652
+ const out = [], seen = new Set();
653
+ const add = (c) => { if (c.op === 'const')
654
+ return; const k = I.keyOf(c); if (!seen.has(k) && !hasCell(c)) {
655
+ seen.add(k);
656
+ out.push(c, I.not(c));
657
+ } };
658
+ const go = (x) => {
659
+ if (!x || typeof x !== 'object')
660
+ return;
661
+ const o = x;
662
+ if ((o.op === 'ite' || o.op === 'kite') && o.c)
663
+ add(o.c);
664
+ Object.values(o).forEach(go);
665
+ };
666
+ go([m.writes, m.mapWrites]);
667
+ for (const d of m.refuse.op === 'or' ? m.refuse.xs : [m.refuse])
668
+ add(d);
669
+ return out.slice(0, 48);
670
+ }
671
+ const hasCell = (c) => I.varsOf(c).maps.size > 0;
672
+ const showCond = (c) => JSON.stringify(c).replace(/"op":/g, '').slice(0, 120);
673
+ // A condition over the rule's env (the step law's `when`): the builders' own values, read from the env by name.
674
+ function condAt(c, env) {
675
+ const n = (e) => {
676
+ switch (e.op) {
677
+ case 'var': return Int.of(env[e.name]);
678
+ case 'const': return Int.of(e.v);
679
+ case 'add': return n(e.a).plus(n(e.b));
680
+ case 'sub': return n(e.a).minus(n(e.b));
681
+ case 'neg': return n(e.a).negate();
682
+ case 'mulk': return n(e.a).times(e.k);
683
+ case 'min': return n(e.a).min(n(e.b));
684
+ case 'max': return n(e.a).max(n(e.b));
685
+ case 'divk': return n(e.a).divBy(e.k);
686
+ case 'modk': return Int.of(n(e.a).modBy(e.k));
687
+ case 'ite': return Int.of(whenInt(b(e.c), n(e.a), n(e.b)));
688
+ case 'mul': {
689
+ const a = env[e.a.name ?? ''], bb = env[e.b.name ?? ''];
690
+ if (a instanceof Term && bb instanceof Term)
691
+ return Int.of(a.mul(bb));
692
+ throw new Error('a product in a probe');
693
+ }
694
+ case 'cell': throw new Error('a map cell in a probe');
695
+ }
696
+ };
697
+ const l = (x) => {
698
+ if (x.op === 'var')
699
+ return env[x.name];
700
+ if (x.op === 'lit')
701
+ return { is: (v) => (v === x.value ? yesC : noC) };
702
+ if (x.op === 'ite') {
703
+ const cc = b(x.c), a = l(x.a), bb = l(x.b);
704
+ return { is: (v) => cc.and(a.is(v)).or(cc.not().and(bb.is(v))) };
705
+ }
706
+ throw new Error('a map cell in a probe');
707
+ };
708
+ const b = (x) => {
709
+ switch (x.op) {
710
+ case 'const': return x.v ? yesC : noC;
711
+ case 'var': return env[x.name];
712
+ case 'cmp': return x.rel === '<' ? n(x.a).lt(n(x.b)) : x.rel === '<=' ? n(x.a).atMost(n(x.b)) : n(x.a).eq(n(x.b));
713
+ case 'and': return x.xs.map(b).reduce((p, y) => p.and(y));
714
+ case 'or': return x.xs.map(b).reduce((p, y) => p.or(y));
715
+ case 'not': return b(x.x).not();
716
+ case 'ite': {
717
+ const cc = b(x.c);
718
+ return cc.and(b(x.a)).or(cc.not().and(b(x.b)));
719
+ }
720
+ case 'is': return l(x.l).is(x.value);
721
+ case 'leq': {
722
+ const a = x.a, bb = x.b;
723
+ if (a.op === 'var' && bb.op === 'var')
724
+ return env[a.name].eq(env[bb.name]);
725
+ throw new Error('a choice comparison in a probe');
726
+ }
727
+ case 'keq': {
728
+ const s = (k) => (k.op === 'svar' ? env[k.name] : k.op === 'slit' ? k.value : (() => { throw new Error('a key in a probe'); })());
729
+ const a = s(x.a), bb = s(x.b);
730
+ return (typeof a === 'string' ? bb.eq(a) : a.eq(bb));
731
+ }
732
+ case 'cell': throw new Error('a map cell in a probe');
733
+ }
734
+ };
735
+ return b(c);
736
+ }
737
+ import { yes as yesC, no as noC, when as whenDsl } from "./dsl.js";
738
+ const whenInt = (c, a, b) => whenDsl(c, a, b);
739
+ // A term at concrete values (a constant field over the params, a start, the precondition).
740
+ export function evalTerm(t, env) {
741
+ const n = (e) => {
742
+ switch (e.op) {
743
+ case 'var': return env[e.name];
744
+ case 'const': return e.v;
745
+ case 'add': return n(e.a) + n(e.b);
746
+ case 'sub': return n(e.a) - n(e.b);
747
+ case 'neg': return -n(e.a);
748
+ case 'mulk': return e.k * n(e.a);
749
+ case 'mul': return n(e.a) * n(e.b);
750
+ case 'min': return Math.min(n(e.a), n(e.b));
751
+ case 'max': return Math.max(n(e.a), n(e.b));
752
+ case 'divk': return Math.floor(n(e.a) / e.k);
753
+ case 'modk': return ((n(e.a) % e.k) + e.k) % e.k;
754
+ case 'ite': return b(e.c) ? n(e.a) : n(e.b);
755
+ case 'cell': throw new Error('a map cell at the start');
756
+ }
757
+ };
758
+ const l = (x) => (x.op === 'var' ? env[x.name] : x.op === 'lit' ? x.value : x.op === 'ite' ? (b(x.c) ? l(x.a) : l(x.b)) : (() => { throw new Error('a map cell'); })());
759
+ const b = (x) => {
760
+ switch (x.op) {
761
+ case 'const': return x.v;
762
+ case 'var': return env[x.name];
763
+ case 'cmp': return x.rel === '<' ? n(x.a) < n(x.b) : x.rel === '<=' ? n(x.a) <= n(x.b) : n(x.a) === n(x.b);
764
+ case 'and': return x.xs.every(b);
765
+ case 'or': return x.xs.some(b);
766
+ case 'not': return !b(x.x);
767
+ case 'ite': return b(x.c) ? b(x.a) : b(x.b);
768
+ case 'is': return l(x.l) === x.value;
769
+ case 'leq': return l(x.a) === l(x.b);
770
+ case 'keq': throw new Error('a key at the start');
771
+ case 'cell': throw new Error('a map cell at the start');
772
+ }
773
+ };
774
+ if (t.op === 'var')
775
+ return env[t.name];
776
+ if (t.op === 'const')
777
+ return t.v;
778
+ if (t.op === 'lit')
779
+ return t.value;
780
+ if (t.op === 'ite')
781
+ return b(t.c) ? evalTerm(t.a, env) : evalTerm(t.b, env);
782
+ if (['add', 'sub', 'neg', 'mulk', 'mul', 'min', 'max', 'divk', 'modk', 'cell'].includes(t.op))
783
+ return n(t);
784
+ return b(t);
785
+ }