gdp-wired 0.26.0 → 0.28.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 (44) hide show
  1. package/dist/core/accel.d.ts +24 -0
  2. package/dist/core/accel.js +557 -207
  3. package/dist/core/bmc.d.ts +4 -1
  4. package/dist/core/bmc.js +18 -15
  5. package/dist/core/cycles.d.ts +2 -0
  6. package/dist/core/cycles.js +1 -1
  7. package/dist/core/cyclic.js +17 -10
  8. package/dist/core/data.d.ts +1 -0
  9. package/dist/core/data.js +73 -18
  10. package/dist/core/discover.js +64 -25
  11. package/dist/core/dsl.js +108 -18
  12. package/dist/core/extract-check.d.ts +52 -2
  13. package/dist/core/extract-check.js +155 -104
  14. package/dist/core/extract-read.d.ts +25 -0
  15. package/dist/core/extract-read.js +55 -14
  16. package/dist/core/extract-shapes.js +94 -18
  17. package/dist/core/extract-xstate.js +16 -3
  18. package/dist/core/extract.d.ts +1 -0
  19. package/dist/core/extract.js +16 -8
  20. package/dist/core/fresh.d.ts +9 -0
  21. package/dist/core/fresh.js +91 -0
  22. package/dist/core/infer.d.ts +1 -0
  23. package/dist/core/infer.js +64 -46
  24. package/dist/core/live.d.ts +15 -0
  25. package/dist/core/live.js +317 -0
  26. package/dist/core/machine.js +0 -1
  27. package/dist/core/nonterm.d.ts +3 -1
  28. package/dist/core/nonterm.js +103 -25
  29. package/dist/core/solver.d.ts +21 -0
  30. package/dist/core/solver.js +8 -0
  31. package/dist/core/translate.js +69 -19
  32. package/dist/kernel/cdcl.js +212 -78
  33. package/dist/kernel/kernel.d.ts +17 -1
  34. package/dist/kernel/kernel.js +158 -2
  35. package/dist/kernel/prove.d.ts +30 -4
  36. package/dist/kernel/prove.js +119 -25
  37. package/dist/kernel/reader.d.ts +74 -5
  38. package/dist/kernel/reader.js +531 -75
  39. package/dist/kernel/simplex.d.ts +26 -1
  40. package/dist/kernel/simplex.js +148 -14
  41. package/dist/lean-kernel/emit.d.ts +15 -3
  42. package/dist/lean-kernel/emit.js +144 -12
  43. package/dist/lean-kernel/library.js +1 -1
  44. package/package.json +2 -2
@@ -126,9 +126,9 @@ export function sandbox(code, file, expose, modules = {}, init, files = {}, extr
126
126
  return { ctx, counts, arms, call, setNow: n => { now = n; }, get: name => vm.runInContext(`__gdp[${JSON.stringify(name)}]`, ctx) };
127
127
  }
128
128
  const isMap = (x) => Object.prototype.toString.call(x) === '[object Map]';
129
- class Outside extends Error {
129
+ export class Outside extends Error {
130
130
  }
131
- class Refused extends Error {
131
+ export class Refused extends Error {
132
132
  }
133
133
  // The code's value as a snapshot, by the layout; what the rule has no place for is a difference.
134
134
  function snapOf(v, layout, m, consts, out = { leaves: {}, maps: {} }, path = 'state') {
@@ -160,7 +160,8 @@ function snapOf(v, layout, m, consts, out = { leaves: {}, maps: {} }, path = 'st
160
160
  case 'rec': {
161
161
  if (typeof v !== 'object' || v === null)
162
162
  throw new Error(`${path} is ${JSON.stringify(v)}, not an object`);
163
- const own = Object.keys(v), want = layout.fields.map(([f]) => f).filter(f => !f.endsWith('()'));
163
+ // (a class's fields holding a function are no state: the object's own, left out where they hold one)
164
+ const own = Object.keys(v).filter(k => !(path === 'state' && m.fnFields?.includes(k) && typeof v[k] === 'function')), want = layout.fields.map(([f]) => f).filter(f => !f.endsWith('()'));
164
165
  for (const k of own)
165
166
  if (!want.includes(k))
166
167
  throw new Error(`${path} has a field ${k} the rule doesn't`);
@@ -262,8 +263,8 @@ function valueOf(s, layout, m, consts, ctx) {
262
263
  ctx.__in = JSON.stringify(tree(layout));
263
264
  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 && typeof v === "object" && "$date" in v ? new Date(v.$date) : v)', ctx);
264
265
  }
265
- const showSnap = (s) => JSON.stringify({ ...s.leaves, ...Object.fromEntries(Object.entries(s.maps).map(([k, v]) => [k, v])), ...(s.lists ?? {}) });
266
- const sameSnap = (a, b) => {
266
+ export const showSnap = (s) => JSON.stringify({ ...s.leaves, ...Object.fromEntries(Object.entries(s.maps).map(([k, v]) => [k, v])), ...(s.lists ?? {}) });
267
+ export const sameSnap = (a, b) => {
267
268
  for (const k of new Set([...Object.keys(a.leaves), ...Object.keys(b.leaves)]))
268
269
  if (a.leaves[k] !== b.leaves[k])
269
270
  return `${k} is ${JSON.stringify(a.leaves[k])} in the code, ${JSON.stringify(b.leaves[k])} in the rule`;
@@ -281,7 +282,7 @@ const sameSnap = (a, b) => {
281
282
  // --- the rule's side ------------------------------------------------------------------------------------------------
282
283
  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());
283
284
  const idText = (id) => interned().find(([, n]) => n === id)?.[0];
284
- function ruleSnap(r, m, st, sorts) {
285
+ export function ruleSnap(r, m, st, sorts) {
285
286
  const d = r.decode(st), leaves = {}, maps = {};
286
287
  for (const v of m.state)
287
288
  if (!m.outputs.includes(v.name))
@@ -303,7 +304,7 @@ function ruleSnap(r, m, st, sorts) {
303
304
  return { leaves, maps, ...(m.lists?.length ? { lists } : {}) };
304
305
  }
305
306
  // A snapshot as a state of the rule (each variable and cell by its kind).
306
- function ruleState(base, s, m, sorts) {
307
+ export function ruleState(base, s, m, sorts) {
307
308
  const scalars = { ...base.scalars }, maps = Object.fromEntries(Object.entries(base.maps).map(([k]) => [k, new Map()]));
308
309
  for (const v of m.state)
309
310
  if (v.name in s.leaves)
@@ -331,14 +332,14 @@ import { record } from "./dsl.js";
331
332
  const cellKind = (d, sorts) => record({ has: bool, ...Object.fromEntries(d.fields.map(f => [f.name, kindOfVar(f, sorts, `${d.name}.${f.name}`)])) });
332
333
  // --- values to draw -------------------------------------------------------------------------------------------------
333
334
  const BIG = [Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER - 1, 2 ** 31, 2 ** 32];
334
- function constantsOf(m) {
335
+ export function constantsOf(m) {
335
336
  const out = new Set([0, 1]);
336
337
  walk([m.writes, m.mapWrites, m.refuse, m.pre, m.init], o => { if (o.op === 'const' && typeof o.v === 'number')
337
338
  out.add(o.v); if (typeof o.k === 'number')
338
339
  out.add(o.k); });
339
340
  return [...out];
340
341
  }
341
- function draw(sort, sorts, name, rand, near, bound, strs) {
342
+ export function draw(sort, sorts, name, rand, near, bound, strs) {
342
343
  switch (sort.k) {
343
344
  case 'bool': return rand(2) === 1;
344
345
  case 'choice': return sort.values[rand(sort.values.length)];
@@ -362,37 +363,94 @@ function draw(sort, sorts, name, rand, near, bound, strs) {
362
363
  }
363
364
  }
364
365
  export function check(code, file, m, r, sorts, opts = {}) {
365
- const t0 = performance.now(), rand = seeded((opts.seed ?? 7) >>> 0 || 1), bound = opts.bound ?? 12;
366
366
  const isClass = m.shape === 'class', fns = m.shape === 'class' ? [m.entry] : [...new Set(m.events.map(e => e.call))];
367
367
  const box = sandbox(code, file, fns, opts.modules, m.initSource, opts.files, m.factory ? [[m.factory.at, m.factory.text]] : []);
368
368
  // An object a factory makes: its state is what its functions close over, read and set through the two functions the
369
369
  // check added to it.
370
370
  const stateOf = (self) => (m.factory ? box.call('$get', self, []).value : self);
371
- const interp = r.interpreter(), gen = r.compiled(), machine = r.machine;
372
- 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 };
373
- const consts = constantsOf(m), strs = ['a', 'b', 'c', ''];
374
- const paramKinds = m.params.map(v => [v, kindOfVar(v, sorts)]), inputKinds = m.inputs.map(v => [v, kindOfVar(v, sorts)]);
375
- // A term over the params at their values (a constant field, a start).
376
371
  const evalAt = (env) => (t) => evalTerm(t, env);
377
- const fail = (what) => { ev.mismatch = what; return finish(); };
378
372
  // The arms of the code the step reads (the entry, its methods, the functions it inlines; a class's constructor too).
379
373
  const inSpan = (a) => !m.spans || m.spans.some(([s0, e0]) => a.pos >= s0 && a.pos < e0);
380
374
  const counted = box.arms.map((a, i) => [a, i]).filter(([a]) => inSpan(a));
381
- ev.coverage.arms = counted.length;
375
+ const E = JSON.stringify(m.entry);
376
+ if (isClass && !m.factory)
377
+ vmOf().runInContext(`__gdp.$method = function (name, args) { return this[name](...args) }; __gdp.$new = function (...args) { return new __gdp[${E}](...args) }; __gdp.$at = function (fields) { return Object.assign(Object.create(__gdp[${E}].prototype), fields) }`, box.ctx);
378
+ if (m.factory)
379
+ vmOf().runInContext(`__gdp.$method = function (name, args) { return this[name](...args) }; __gdp.$new = function (...args) { return __gdp[${E}](...args) }; __gdp.$get = function () { return this.__gdpGet() }; __gdp.$at = function (fields, args) { const o = __gdp[${E}](...args); o.__gdpSet(fields); return o }`, box.ctx);
380
+ // A class's fields holding a function: each answers the request's input (set on the object before each call; a
381
+ // function given to the constructor is one such too).
382
+ let answers = {};
383
+ const answering = (f) => () => { const n = Object.keys(m.answers ?? {}).find(k => m.answers[k] === f); return n === undefined ? undefined : answers[n]; };
384
+ const fnArg = () => () => { throw new Error('a function given to the constructor called while the object is made'); };
385
+ const ctorValue = (n, params) => (n === '$fn' ? fnArg() : n.startsWith('$map:') ? vmOf().runInContext(n === '$map:Map' ? 'new Map()' : '({})', box.ctx) : params[n]);
386
+ const ctorValues = (params) => (m.ctorArgs ?? []).filter(n => !m.params.find(v => v.name === n)?.note?.startsWith('Date.now()')).map(n => ctorValue(n, params));
387
+ const side = {
388
+ make: params => {
389
+ const now0 = m.params.find(v => v.note?.startsWith('Date.now()'));
390
+ if (now0)
391
+ box.setNow(params[now0.name]);
392
+ // A Map the constructor is given: an empty one, made in the code's realm.
393
+ return box.call('$new', undefined, (m.ctorArgs ?? []).filter(n => n !== now0?.name).map(n => ctorValue(n, params)));
394
+ },
395
+ at: (snap, params) => (box.call('$at', undefined, [valueOf(snap, m.layout, m, evalAt(params), box.ctx), ctorValues(params)]).ok ? box.ctx.__r.value : (() => { throw new Error(`could not make the object: ${box.ctx.__r.error}`); })()),
396
+ snapOf: (self, params) => snapOf(stateOf(self), m.layout, m, evalAt(params)),
397
+ call: (self, e, args) => {
398
+ for (const f of new Set(Object.values(m.answers ?? {})))
399
+ self[f] = answering(f);
400
+ return box.call('$method', self, [e.call, args]);
401
+ },
402
+ reduce: (snap, e, args, params) => {
403
+ const input = valueOf(snap, m.layout, m, evalAt(params), box.ctx), before = JSON.stringify(input, mapReplacer);
404
+ const res = box.call(e.call, undefined, [input, ...args.slice(1)]);
405
+ if (JSON.stringify(input, mapReplacer) !== before)
406
+ return { problem: `${e.call} changed the state it was given` };
407
+ return res.ok ? { snap: snapOf(res.value, m.layout, m, evalAt(params)) } : { refused: res.error };
408
+ },
409
+ args: (inputs, e) => {
410
+ answers = inputs;
411
+ const dateIn = (n) => { const x = m.inputs.find(v => v.name === n); return x?.sort.k === 'num' && x.sort.date ? vmOf().runInContext(`new Date(${Number(inputs[n])})`, box.ctx) : inputs[n]; };
412
+ const build = (a) => (a.k === 'input' ? dateIn(a.name) : a.k === 'lit' ? a.value : a.k === 'rec' ? Object.fromEntries(a.fields.map(([f, x]) => [f, build(x)])) : a.k === 'lazy'
413
+ ? 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]]))
414
+ : undefined);
415
+ return e.args.map(build);
416
+ },
417
+ setNow: n => box.setNow(n),
418
+ // The code's own initial state (where the code gives it), against the rule's.
419
+ init: (snap, params) => {
420
+ if (!m.initSource)
421
+ return undefined;
422
+ const made = vmOf().runInContext('(() => { try { return {ok: true, value: __gdpInit()} } catch (e) { return {ok: false, error: String(e)} } })()', box.ctx);
423
+ if (!made.ok)
424
+ return `the initial state throws (${made.error})`;
425
+ try {
426
+ const diff = sameSnap(snapOf(made.value, m.layout, m, evalAt(params)), snap);
427
+ if (diff)
428
+ return `the initial state: ${diff}`;
429
+ }
430
+ catch (x) {
431
+ return `the initial state: ${x.message}`;
432
+ }
433
+ return undefined;
434
+ },
435
+ coverage: () => ({ arms: counted.length, hit: counted.filter(([, i]) => box.counts[i] > 0).length, missed: counted.filter(([, i]) => box.counts[i] === 0).map(([a]) => `${a.label} at ${a.where}`) }),
436
+ };
437
+ return drive(m, r, sorts, side, opts);
438
+ }
439
+ // The check: requests from the start, from drawn states and from the prover's witnesses, each made of the code
440
+ // (through its side) and of the rule, and compared.
441
+ export function drive(m, r, sorts, code, opts = {}) {
442
+ const t0 = performance.now(), rand = seeded((opts.seed ?? 7) >>> 0 || 1), bound = opts.bound ?? 12;
443
+ const isClass = m.shape === 'class';
444
+ const interp = r.interpreter(), gen = r.compiled(), machine = r.machine;
445
+ 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: 0, hit: 0, missed: [] }, ms: 0 };
446
+ const consts = constantsOf(m), strs = ['a', 'b', 'c', ''];
447
+ const paramKinds = m.params.map(v => [v, kindOfVar(v, sorts)]), inputKinds = m.inputs.map(v => [v, kindOfVar(v, sorts)]);
448
+ const fail = (what) => { ev.mismatch = what; return finish(); };
382
449
  const finish = () => {
383
- ev.coverage.hit = counted.filter(([, i]) => box.counts[i] > 0).length;
384
- ev.coverage.missed = counted.filter(([, i]) => box.counts[i] === 0).map(([a]) => `${a.label} at ${a.where}`);
450
+ ev.coverage = code.coverage();
385
451
  ev.ms = Math.round(performance.now() - t0);
386
452
  return ev;
387
453
  };
388
- const request = (params, inputs, e) => {
389
- const dateIn = (n) => { const x = m.inputs.find(v => v.name === n); return x?.sort.k === 'num' && x.sort.date ? vmOf().runInContext(`new Date(${Number(inputs[n])})`, box.ctx) : inputs[n]; };
390
- const build = (a) => (a.k === 'input' ? dateIn(a.name) : a.k === 'lit' ? a.value : a.k === 'rec' ? Object.fromEntries(a.fields.map(([f, x]) => [f, build(x)])) : a.k === 'lazy'
391
- ? 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]]))
392
- : undefined);
393
- void params;
394
- return e.args.map(build);
395
- };
396
454
  const draws = (st, params) => [...consts, ...Object.values(st.leaves).filter((x) => typeof x === 'number'), ...Object.values(params).filter((x) => typeof x === 'number')];
397
455
  let lastNow = 1_000;
398
456
  const drawRequest = (st, params) => {
@@ -411,7 +469,7 @@ export function check(code, file, m, r, sorts, opts = {}) {
411
469
  const keys = Object.values(st.maps).flatMap(c => Object.keys(c));
412
470
  // An input given as a natural (domains) is drawn as one: the claim is for those, as the user said.
413
471
  const x = draw(v.sort, sorts, v.name, rand, near, bound, [...strs, ...keys]);
414
- inputs[v.name] = opts.given?.[v.name] === 'nat' && typeof x === 'number' ? Math.abs(x) : x;
472
+ inputs[v.name] = code.input ? code.input(v, x, rand) : opts.given?.[v.name] === 'nat' && typeof x === 'number' ? Math.abs(x) : x;
415
473
  }
416
474
  return { e, inputs };
417
475
  };
@@ -427,7 +485,7 @@ export function check(code, file, m, r, sorts, opts = {}) {
427
485
  used.add(v.name); };
428
486
  e.args.forEach(walk);
429
487
  for (const v of m.inputs)
430
- if (v.note?.startsWith('Date.now()'))
488
+ if (v.note?.startsWith('Date.now()') || m.answers?.[v.name])
431
489
  used.add(v.name);
432
490
  // An input the event doesn't bring: its kind's first value (the rule reads it only under another event).
433
491
  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] : '']));
@@ -435,31 +493,30 @@ export function check(code, file, m, r, sorts, opts = {}) {
435
493
  // Steps the code and the rule from one state; undefined when they agree (the next state on both sides is returned
436
494
  // through `next`), else the difference.
437
495
  const step = (params, ps, side, st, inputs, e, next, where) => {
438
- const args = request(params, inputs, e), raw = ruleInputs(inputs, e);
496
+ const args = code.args(inputs, e), raw = ruleInputs(inputs, e);
439
497
  const nowVar = m.inputs.find(v => v.note?.startsWith('Date.now()'));
440
498
  if (nowVar)
441
- box.setNow(inputs[nowVar.name]);
499
+ code.setNow(inputs[nowVar.name]);
442
500
  // The code.
443
- let code;
501
+ let res;
444
502
  try {
445
503
  if (isClass) {
446
- const self = side.self, res = box.call('$method', self, [e.call, args]);
447
- if (!res.ok)
448
- code = { refused: res.error };
504
+ const self = side.self, c = code.call(self, e, args);
505
+ if (!c.ok)
506
+ res = { refused: c.error };
449
507
  else
450
- code = { snap: snapOf(stateOf(self), m.layout, m, evalAt(params)), out: res.value, self };
508
+ res = { snap: code.snapOf(self, params), out: c.value, self };
451
509
  }
452
510
  else {
453
- const input = valueOf(side.snap, m.layout, m, evalAt(params), box.ctx), before = JSON.stringify(input, mapReplacer);
454
- const res = box.call(e.call, undefined, [input, ...args.slice(1)]);
455
- if (JSON.stringify(input, mapReplacer) !== before)
456
- return `${where}: ${e.call} changed the state it was given`;
457
- code = res.ok ? { snap: snapOf(res.value, m.layout, m, evalAt(params)) } : { refused: res.error };
511
+ const c = code.reduce(side.snap, e, args, params);
512
+ if ('problem' in c)
513
+ return `${where}: ${c.problem}`;
514
+ res = c;
458
515
  }
459
516
  }
460
517
  catch (x) {
461
518
  if (x instanceof Outside)
462
- code = { outside: x.message };
519
+ res = { outside: x.message };
463
520
  else
464
521
  return `${where}: the code's state after the request: ${x.message}`;
465
522
  }
@@ -486,19 +543,22 @@ export function check(code, file, m, r, sorts, opts = {}) {
486
543
  catch (x) {
487
544
  rule = x instanceof Refused ? { refused: x.message } : /2\^53|safe integer/.test(x.message) ? { outside: x.message } : { refused: x.message };
488
545
  }
546
+ // Where Go goes on past a type the rule refuses at (a uint64 below 0): the edge the rule's claim stops at.
547
+ if ('refused' in rule && code.edge?.(side.snap, raw))
548
+ rule = { outside: `${rule.refused}: past the rule's numbers` };
489
549
  }
490
550
  const req = `${e.call}(${JSON.stringify(args).slice(1, -1)})${nowVar ? ` at ${inputs[nowVar.name]}` : ''}`;
491
551
  const from = `from ${showSnap(side.snap)}${m.params.length ? ` with ${JSON.stringify(params)}` : ''}`;
492
- if ('outside' in code || 'outside' in rule) {
552
+ if ('outside' in res || 'outside' in rule) {
493
553
  // The code past the safe integers: the rule's runtime must refuse there too (it never rounds).
494
554
  next.stop = true;
495
- if ('outside' in code) {
555
+ if ('outside' in res) {
496
556
  if ('st' in rule)
497
- return `${where}: ${req} ${from}: the code leaves the safe integers (${code.outside}) where the rule takes the step`;
557
+ return `${where}: ${req} ${from}: the code leaves the safe integers (${res.outside}) where the rule takes the step`;
498
558
  ev.outside++;
499
559
  return undefined;
500
560
  }
501
- if ('refused' in code) {
561
+ if ('refused' in res) {
502
562
  ev.refusedBoth++;
503
563
  return undefined;
504
564
  }
@@ -508,13 +568,13 @@ export function check(code, file, m, r, sorts, opts = {}) {
508
568
  ev.edgeSample ??= `${req} ${from}`;
509
569
  return undefined;
510
570
  }
511
- if ('refused' in code && 'refused' in rule) {
571
+ if ('refused' in res && 'refused' in rule) {
512
572
  // A refusal leaves the state as it was: the object the code threw from must be as it was too.
513
573
  if (isClass) {
514
574
  try {
515
- const after = snapOf(stateOf(side.self), m.layout, m, evalAt(params)), d = sameSnap(after, side.snap);
575
+ const after = code.snapOf(side.self, params), d = sameSnap(after, side.snap);
516
576
  if (d)
517
- return `${where}: ${req} ${from}: the code throws (${code.refused}) after changing the object: ${d}`;
577
+ return `${where}: ${req} ${from}: the code throws (${res.refused}) after changing the object: ${d}`;
518
578
  }
519
579
  catch (x) {
520
580
  return `${where}: ${req} ${from}: the code throws after changing the object (${x.message})`;
@@ -523,47 +583,40 @@ export function check(code, file, m, r, sorts, opts = {}) {
523
583
  ev.refusedBoth++;
524
584
  return undefined;
525
585
  }
526
- if ('refused' in code)
527
- return `${where}: ${req} ${from}: the code throws (${code.refused}), the rule takes the step`;
586
+ if ('refused' in res)
587
+ return `${where}: ${req} ${from}: the code throws (${res.refused}), the rule takes the step`;
528
588
  if ('refused' in rule)
529
589
  return `${where}: ${req} ${from}: the rule refuses it (${rule.refused}), the code doesn't`;
530
- const ruleSide = ruleSnap(r, m, rule.st, sorts), diff = sameSnap(code.snap, ruleSide);
590
+ const ruleSide = ruleSnap(r, m, rule.st, sorts), diff = sameSnap(res.snap, ruleSide);
531
591
  if (diff)
532
592
  return `${where}: ${req} ${from}: ${diff}`;
533
593
  if (isClass) {
534
594
  // The method's result, as the rule keeps it: a value, a record's fields, or a value and whether it is missing.
535
- const res = m.results?.[e.call], d = r.decode(rule.st);
536
- const bad = (what) => `${where}: ${req} ${from}: ${e.call} returns ${JSON.stringify(code.out)}, ${what}`;
537
- if (res?.k === 'scalar' && d[res.name] !== code.out)
538
- return bad(`the rule's ${res.name} is ${JSON.stringify(d[res.name])}`);
539
- if (res?.k === 'rec') {
540
- const o = code.out;
541
- if (typeof o !== 'object' || o === null || Object.keys(o).length !== res.fields.length)
595
+ const rk = m.results?.[e.call], d = r.decode(rule.st);
596
+ const bad = (what) => `${where}: ${req} ${from}: ${e.call} returns ${JSON.stringify(res.out)}, ${what}`;
597
+ if (rk?.k === 'scalar' && d[rk.name] !== res.out)
598
+ return bad(`the rule's ${rk.name} is ${JSON.stringify(d[rk.name])}`);
599
+ if (rk?.k === 'rec') {
600
+ const o = res.out;
601
+ if (typeof o !== 'object' || o === null || Object.keys(o).length !== rk.fields.length)
542
602
  return bad('not a record of the fields the rule keeps');
543
- for (const [f, n] of res.fields)
603
+ for (const [f, n] of rk.fields)
544
604
  if (o[f] !== d[n])
545
605
  return bad(`the rule's ${n} is ${JSON.stringify(d[n])}`);
546
606
  }
547
- if (res?.k === 'maybe') {
548
- const gone = code.out === (res.null ? null : undefined);
549
- if (gone !== d[res.missing])
550
- return bad(`the rule's ${res.missing} is ${JSON.stringify(d[res.missing])}`);
551
- if (!gone && d[res.name] !== code.out)
552
- return bad(`the rule's ${res.name} is ${JSON.stringify(d[res.name])}`);
607
+ if (rk?.k === 'maybe') {
608
+ const gone = res.out === (rk.null ? null : undefined);
609
+ if (gone !== d[rk.missing])
610
+ return bad(`the rule's ${rk.missing} is ${JSON.stringify(d[rk.missing])}`);
611
+ if (!gone && d[rk.name] !== res.out)
612
+ return bad(`the rule's ${rk.name} is ${JSON.stringify(d[rk.name])}`);
553
613
  }
554
614
  }
555
- next.side = { snap: code.snap, ...(code.self ? { self: code.self } : {}) };
615
+ next.side = { snap: res.snap, ...(res.self ? { self: res.self } : {}) };
556
616
  next.st = rule.st;
557
617
  return undefined;
558
618
  };
559
619
  // A class's object: made by its constructor, or set to a snapshot.
560
- const E = JSON.stringify(m.entry);
561
- if (isClass && !m.factory)
562
- vmOf().runInContext(`__gdp.$method = function (name, args) { return this[name](...args) }; __gdp.$new = function (...args) { return new __gdp[${E}](...args) }; __gdp.$at = function (fields) { return Object.assign(Object.create(__gdp[${E}].prototype), fields) }`, box.ctx);
563
- if (m.factory)
564
- vmOf().runInContext(`__gdp.$method = function (name, args) { return this[name](...args) }; __gdp.$new = function (...args) { return __gdp[${E}](...args) }; __gdp.$get = function () { return this.__gdpGet() }; __gdp.$at = function (fields, args) { const o = __gdp[${E}](...args); o.__gdpSet(fields); return o }`, box.ctx);
565
- const ctorValues = (params) => (m.ctorArgs ?? []).filter(n => !m.params.find(v => v.name === n)?.note?.startsWith('Date.now()')).map(n => (n.startsWith('$map:') ? vmOf().runInContext(n === '$map:Map' ? 'new Map()' : '({})', box.ctx) : params[n]));
566
- const objectAt = (snap, params) => box.call('$at', undefined, [valueOf(snap, m.layout, m, evalAt(params), box.ctx), ctorValues(params)]).ok ? box.ctx.__r.value : (() => { throw new Error(`could not make the object: ${box.ctx.__r.error}`); })();
567
620
  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)]));
568
621
  const start = (params) => {
569
622
  const ctorRefuses = (() => { const pre = evalTerm(m.pre, params); return pre !== true; })();
@@ -575,11 +628,7 @@ export function check(code, file, m, r, sorts, opts = {}) {
575
628
  ps = undefined;
576
629
  }
577
630
  if (isClass) {
578
- const now0 = m.params.find(v => v.note?.startsWith('Date.now()'));
579
- if (now0)
580
- box.setNow(params[now0.name]);
581
- // A Map the constructor is given: an empty one, made in the code's realm.
582
- const made = box.call('$new', undefined, (m.ctorArgs ?? []).filter(n => n !== now0?.name).map(n => (n.startsWith('$map:') ? vmOf().runInContext(n === '$map:Map' ? 'new Map()' : '({})', box.ctx) : params[n])));
631
+ const made = code.make(params);
583
632
  const ruleRefuses = ps === undefined || ctorRefuses;
584
633
  if (!made.ok)
585
634
  return ruleRefuses ? {} : { problem: `new ${m.entry}(${JSON.stringify(params)}) throws (${made.error}), the rule's precondition holds` };
@@ -587,7 +636,7 @@ export function check(code, file, m, r, sorts, opts = {}) {
587
636
  return { problem: `new ${m.entry}(${JSON.stringify(params)}) is made, the rule's ${ps === undefined ? 'param kinds refuse' : 'precondition refuses'} it` };
588
637
  const st = interp.init(ps);
589
638
  try {
590
- const snap = snapOf(stateOf(made.value), m.layout, m, evalAt(params));
639
+ const snap = code.snapOf(made.value, params);
591
640
  const diff = sameSnap(snap, ruleSnap(r, m, st, sorts));
592
641
  if (diff)
593
642
  return { problem: `new ${m.entry}(${JSON.stringify(params)}): ${diff}` };
@@ -598,20 +647,9 @@ export function check(code, file, m, r, sorts, opts = {}) {
598
647
  }
599
648
  }
600
649
  const st = interp.init(ps ?? {}), snap = ruleSnap(r, m, st, sorts);
601
- // The code's own initial state (where the code gives it), against the rule's.
602
- if (m.initSource) {
603
- const made = vmOf().runInContext('(() => { try { return {ok: true, value: __gdpInit()} } catch (e) { return {ok: false, error: String(e)} } })()', box.ctx);
604
- if (!made.ok)
605
- return { problem: `the initial state throws (${made.error})` };
606
- try {
607
- const diff = sameSnap(snapOf(made.value, m.layout, m, evalAt(params)), snap);
608
- if (diff)
609
- return { problem: `the initial state: ${diff}` };
610
- }
611
- catch (x) {
612
- return { problem: `the initial state: ${x.message}` };
613
- }
614
- }
650
+ const problem = code.init?.(snap, params);
651
+ if (problem)
652
+ return { problem };
615
653
  return { side: { snap }, st, ps: ps ?? {} };
616
654
  };
617
655
  const runs = opts.runs ?? 200, depth = opts.depth ?? 12;
@@ -640,6 +678,8 @@ export function check(code, file, m, r, sorts, opts = {}) {
640
678
  }
641
679
  // Steps from drawn states.
642
680
  const drawSnap = (params) => {
681
+ if (code.drawSnap)
682
+ return code.drawSnap(rand);
643
683
  const leaves = {}, maps = {};
644
684
  for (const v of m.state)
645
685
  if (!m.outputs.includes(v.name))
@@ -688,7 +728,11 @@ export function check(code, file, m, r, sorts, opts = {}) {
688
728
  if (evalTerm(m.pre, params) !== true)
689
729
  return undefined;
690
730
  const st = ruleState(interp.init(ps), snap, m, sorts);
691
- const side = { snap, ...(isClass ? { self: objectAt(snap, params) } : {}) };
731
+ // A state the code can't hold (a value outside its type, Go's): no state of the code is that one.
732
+ const self = isClass ? code.at(snap, params) : undefined;
733
+ if (isClass && self === undefined)
734
+ return undefined;
735
+ const side = { snap, ...(isClass ? { self: self } : {}) };
692
736
  return step(params, ps, side, st, inputs, e, {}, where);
693
737
  };
694
738
  for (let i = 0; i < (opts.states ?? 400); i++) {
@@ -732,7 +776,8 @@ export function check(code, file, m, r, sorts, opts = {}) {
732
776
  if (!ok)
733
777
  continue;
734
778
  const e = m.events.find(x => Object.entries(x.select).every(([n, val]) => inputs[n] === val)) ?? m.events[0];
735
- const diff = fromState(params, { leaves, maps: Object.fromEntries(m.maps.map(d => [d.name, {}])) }, inputs, e, `the prover's witness for ${showCond(c)}`);
779
+ const snap = { leaves, maps: Object.fromEntries(m.maps.map(d => [d.name, {}])) };
780
+ const diff = fromState(params, code.normalize ? code.normalize(snap) : snap, inputs, e, `the prover's witness for ${showCond(c)}`);
736
781
  ev.probes.steps++;
737
782
  if (diff)
738
783
  return fail(diff);
@@ -742,7 +787,7 @@ export function check(code, file, m, r, sorts, opts = {}) {
742
787
  }
743
788
  const mapReplacer = (_, v) => (isMap(v) ? { $map: [...v.entries()] } : v);
744
789
  // The conditions a step reads (each branch's, each refusal's), as a probe asks the prover to reach.
745
- function conditionsOf(m) {
790
+ export function conditionsOf(m) {
746
791
  const out = [], seen = new Set();
747
792
  const add = (c) => { if (c.op === 'const')
748
793
  return; const k = I.keyOf(c); if (!seen.has(k) && !hasCell(c)) {
@@ -758,7 +803,7 @@ function conditionsOf(m) {
758
803
  const hasCell = (c) => I.varsOf(c).maps.size > 0;
759
804
  const showCond = (c) => JSON.stringify(c).replace(/"op":/g, '').slice(0, 120);
760
805
  // A condition over the rule's env (the step law's `when`): the builders' own values, read from the env by name.
761
- function condAt(c, env) {
806
+ export function condAt(c, env) {
762
807
  const n = (e) => {
763
808
  switch (e.op) {
764
809
  case 'var': return Int.of(env[e.name]);
@@ -823,8 +868,11 @@ function condAt(c, env) {
823
868
  }
824
869
  import { yes as yesC, no as noC, when as whenDsl } from "./dsl.js";
825
870
  const whenInt = (c, a, b) => whenDsl(c, a, b);
826
- // A term at concrete values (a constant field over the params, a start, the precondition).
827
- export function evalTerm(t, env) {
871
+ // A term at concrete values (a constant field over the params, a start, the precondition; with `cell`, a state's
872
+ // map cells and list items too).
873
+ export function evalTerm(t, env, cell) {
874
+ const at = (map, k, field) => (cell ?? (() => { throw new Error('a map cell at the start'); }))(map, key(k), field);
875
+ const key = (k) => (k.op === 'num' ? n(k.e) : k.op === 'svar' ? env[k.name] : k.op === 'slit' ? k.value : b(k.c) ? key(k.a) : key(k.b));
828
876
  const n = (e) => {
829
877
  switch (e.op) {
830
878
  case 'var': return env[e.name];
@@ -839,7 +887,7 @@ export function evalTerm(t, env) {
839
887
  case 'divk': return Math.floor(n(e.a) / e.k);
840
888
  case 'modk': return ((n(e.a) % e.k) + e.k) % e.k;
841
889
  case 'ite': return b(e.c) ? n(e.a) : n(e.b);
842
- case 'cell': throw new Error('a map cell at the start');
890
+ case 'cell': return at(e.map, e.key, e.field);
843
891
  }
844
892
  };
845
893
  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'); })());
@@ -854,8 +902,11 @@ export function evalTerm(t, env) {
854
902
  case 'ite': return b(x.c) ? b(x.a) : b(x.b);
855
903
  case 'is': return l(x.l) === x.value;
856
904
  case 'leq': return l(x.a) === l(x.b);
857
- case 'keq': throw new Error('a key at the start');
858
- case 'cell': throw new Error('a map cell at the start');
905
+ case 'keq':
906
+ if (!cell)
907
+ throw new Error('a key at the start');
908
+ return key(x.a) === key(x.b);
909
+ case 'cell': return at(x.map, x.key, x.field);
859
910
  }
860
911
  };
861
912
  if (t.op === 'var')
@@ -865,7 +916,7 @@ export function evalTerm(t, env) {
865
916
  if (t.op === 'lit')
866
917
  return t.value;
867
918
  if (t.op === 'ite')
868
- return b(t.c) ? evalTerm(t.a, env) : evalTerm(t.b, env);
919
+ return b(t.c) ? evalTerm(t.a, env, cell) : evalTerm(t.b, env, cell);
869
920
  if (['add', 'sub', 'neg', 'mulk', 'mul', 'min', 'max', 'divk', 'modk', 'cell'].includes(t.op))
870
921
  return n(t);
871
922
  return b(t);
@@ -172,6 +172,9 @@ export type Model = {
172
172
  missing: string;
173
173
  null: boolean;
174
174
  }>;
175
+ laws?: string[];
176
+ answers?: Record<string, string>;
177
+ fnFields?: string[];
175
178
  };
176
179
  type V = {
177
180
  t: 'num';
@@ -252,12 +255,14 @@ type Path = {
252
255
  heap: Heap;
253
256
  wrote: string[];
254
257
  nows: number;
258
+ outs?: string[];
255
259
  };
256
260
  type Flow = {
257
261
  live?: Path;
258
262
  rets: [Path, V][];
259
263
  breaks: Path[];
260
264
  };
265
+ export declare const unparen: (x: ts.Expression) => ts.Expression;
261
266
  export declare const normalize: (path: string) => string;
262
267
  export declare const resolveIn: (files: Record<string, string>, from: string, spec: string) => string | undefined;
263
268
  export declare function program(code: string, file: string, extra?: Record<string, string>): {
@@ -298,6 +303,13 @@ export type Setup = {
298
303
  sort: Sort;
299
304
  }>;
300
305
  };
306
+ fnFields?: {
307
+ outside: Map<string, {
308
+ path: string;
309
+ sort: Sort;
310
+ }>;
311
+ names: Set<string>;
312
+ };
301
313
  };
302
314
  export declare class Exec {
303
315
  readonly s: Setup;
@@ -363,6 +375,7 @@ export declare class Exec {
363
375
  resolved(e: ts.Node): ts.Symbol | undefined;
364
376
  private args;
365
377
  private call;
378
+ fnField(x: ts.Expression): boolean;
366
379
  private outside;
367
380
  private listLen;
368
381
  private listOp;
@@ -374,6 +387,18 @@ export declare class Exec {
374
387
  inline(f: Callable, args: V[], at: ts.Node, p: Path): [V, Path];
375
388
  }
376
389
  export declare const isDate: (t: ts.Type) => boolean;
390
+ export declare function mergeWrites<V>(c: B, wa: Write<V> | undefined, wb: Write<V> | undefined, base: (key: K) => {
391
+ has: B;
392
+ vals: Map<string, V>;
393
+ }, scalar: (c: B, a: V, b: V) => V): Write<V> | undefined;
394
+ type Write<V> = {
395
+ key: K;
396
+ has: B;
397
+ vals: Map<string, V>;
398
+ };
399
+ export declare const mergeOps: <O extends {
400
+ when: B;
401
+ }>(c: B, a: O[], b: O[]) => O[];
377
402
  export declare const memberName: (n: ts.PropertyName | ts.MemberName) => string;
378
403
  export declare function impure(e: ts.Node): boolean;
379
404
  export type { V, Path, Rec, MapObj, ListObj, Heap, Flow };