gdp-wired 0.25.0 → 0.26.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 (50) hide show
  1. package/README.md +14 -9
  2. package/dist/core/accel.d.ts +1 -1
  3. package/dist/core/accel.js +336 -101
  4. package/dist/core/bmc.d.ts +8 -0
  5. package/dist/core/bmc.js +263 -97
  6. package/dist/core/cycles.d.ts +2 -3
  7. package/dist/core/cycles.js +35 -131
  8. package/dist/core/cyclic.d.ts +4 -1
  9. package/dist/core/cyclic.js +86 -64
  10. package/dist/core/data.d.ts +1 -1
  11. package/dist/core/data.js +89 -118
  12. package/dist/core/discover.js +2 -3
  13. package/dist/core/dsl.d.ts +3 -2
  14. package/dist/core/dsl.js +21 -18
  15. package/dist/core/exists.js +7 -14
  16. package/dist/core/extract-check.d.ts +3 -2
  17. package/dist/core/extract-check.js +137 -50
  18. package/dist/core/extract-print.d.ts +1 -0
  19. package/dist/core/extract-print.js +26 -3
  20. package/dist/core/extract-read.d.ts +85 -4
  21. package/dist/core/extract-read.js +295 -34
  22. package/dist/core/extract-shapes.d.ts +14 -0
  23. package/dist/core/extract-shapes.js +608 -78
  24. package/dist/core/extract-xstate.d.ts +5 -1
  25. package/dist/core/extract-xstate.js +618 -184
  26. package/dist/core/extract.js +73 -27
  27. package/dist/core/infer.js +72 -18
  28. package/dist/core/machine.d.ts +6 -0
  29. package/dist/core/machine.js +35 -3
  30. package/dist/core/nonterm.d.ts +5 -1
  31. package/dist/core/nonterm.js +109 -41
  32. package/dist/core/q.d.ts +1 -0
  33. package/dist/core/q.js +2 -2
  34. package/dist/core/relation.d.ts +1 -0
  35. package/dist/core/relation.js +20 -36
  36. package/dist/core/solver.d.ts +12 -0
  37. package/dist/core/solver.js +76 -30
  38. package/dist/core/transfer.js +22 -13
  39. package/dist/core/translate.d.ts +1 -1
  40. package/dist/core/translate.js +22 -49
  41. package/dist/core/xstate.d.ts +6 -1
  42. package/dist/core/xstate.js +336 -55
  43. package/dist/kernel/cdcl.js +1 -2
  44. package/dist/kernel/prove.d.ts +6 -1
  45. package/dist/kernel/prove.js +96 -82
  46. package/dist/kernel/reader.d.ts +1 -0
  47. package/dist/kernel/reader.js +4 -3
  48. package/dist/kernel/simplex.d.ts +1 -1
  49. package/dist/kernel/simplex.js +13 -1
  50. package/package.json +3 -2
@@ -1,5 +1,6 @@
1
- import { type C, type E, type Law, type Recurrence, type Machine, type Request, type State } from './machine.js';
1
+ import { type C, type E, type Law, type Recurrence, type Machine, type Rand, type Request, type State } from './machine.js';
2
2
  import { type Fold, type Goal, type Liveness, type Loop, type Recur, type StepLaw, type Tree } from '../kernel/kernel.js';
3
+ import { type Report } from '../kernel/prove.js';
3
4
  export type TermLike = Term | number;
4
5
  export declare const termOf: (t: TermLike) => E;
5
6
  export declare class Term {
@@ -54,7 +55,6 @@ export declare const choose: (c: Cond, then: Cond, otherwise: Cond) => Cond;
54
55
  export declare function same(a: unknown, b: unknown): Cond;
55
56
  export declare const count: (c: Cond) => Term;
56
57
  export declare const sum: (first: TermLike, ...rest: TermLike[]) => Term;
57
- type Rand = (k: number) => number;
58
58
  export type Raw = number | boolean | string | null | undefined | RawObject | readonly Raw[];
59
59
  export type RawObject = {
60
60
  readonly [field: string]: Raw;
@@ -853,6 +853,7 @@ export declare class Unproven extends Error {
853
853
  readonly verdict: Verdict;
854
854
  constructor(what: string, verdict: Verdict);
855
855
  }
856
+ export declare const verdictOf: (out: Report) => Verdict;
856
857
  export declare function proveRule(r: Rule<Obj, Obj, Obj, Obj, Obj, Obj, Obj, Obj>, laws: Law[], opts?: ProveOptions): Verdict;
857
858
  export declare function proveSteps(r: Rule<Obj, Obj, Obj, Obj, Obj, Obj, Obj, Obj>, laws: Law[], stepLaws: StepLaw[], opts?: ProveOptions): Verdict;
858
859
  export type { StepLaw };
package/dist/core/dsl.js CHANGED
@@ -15,7 +15,7 @@
15
15
  //
16
16
  // A step returns its updates as one object: every right-hand side reads the state before the step, as the kernel and
17
17
  // both runtimes do.
18
- import { carriedView, compileFunction, divName, divisor, divisorsIn, evalC, evalE, interpret, isArithmetic, loadJs, modName, numbersOf, pairedArgs, withArithmetic } from "./machine.js";
18
+ import { argsKey, carriedView, compileFunction, divName, divisor, divisorsIn, evalC, evalE, interpret, isArithmetic, loadJs, modName, numbersOf, pairedArgs, seeded, withArithmetic } from "./machine.js";
19
19
  import { allowed, keysOf, requestEnv, watch } from "./watch.js";
20
20
  import { someHolds, substVars } from "./exists.js";
21
21
  import { check, checkRecur, foldObligations, loopObligations } from "../kernel/kernel.js";
@@ -1588,8 +1588,6 @@ const flatFns = (defs) => defs.flatMap(([n, d]) => {
1588
1588
  const uses = Object.entries(d.uses ?? {}).map(([u, ud]) => [`${n}.${u}`, ud]);
1589
1589
  return [...flatFns(uses), [n, d, Object.fromEntries(uses.map(([un, ud]) => [un.slice(n.length + 1), fnTerm(un, ud)]))]];
1590
1590
  });
1591
- const pairE = (a, b) => { const s = { op: 'add', a, b }; return { op: 'add', a: { op: 'prod', a: s, b: s }, b }; };
1592
- const argsKey = (args) => args.slice(1).reduce(pairE, args[0]);
1593
1591
  // A function's JavaScript as one function of its key: its arguments unpaired (left-nested, as argsKey pairs them).
1594
1592
  const jsOf = (d) => (typeof d.js === 'string' ? d.js : String(d.js));
1595
1593
  const fnSource = (name, d) => {
@@ -2653,14 +2651,18 @@ const withKinds = (r, laws) => [...r.kindLaws().filter(k => !laws.some(l => l.na
2653
2651
  // knows it only by its facts, which may also bound the params (a recurrence's induction machines take f(x) as a param
2654
2652
  // fx), so params are drawn only where every fact holds: a fact about the params alone exactly, one about every key at
2655
2653
  // each key (or tuple of keys) up to twice the bound. A rule whose function breaks its own facts there gets no run.
2656
- const refuteBudget = { trials: 60, depth: 6, bound: 3, ms: 150 };
2654
+ // The budget is counted, in the runs and requests tried (as core/infer.ts counts its runs), never timed, so a run within
2655
+ // it is found on any machine. (A stop at 150 ms of wall time left a false law to the kernel whenever the first run alone
2656
+ // took that long, a pause on a loaded container: core/pairs.test.ts's two groups, whose 944-hypothesis step goal then ran
2657
+ // out its 944 s, in 7 of 130 runs of the suite's pairs job on Modal.)
2658
+ const refuteBudget = { trials: 60, depth: 6, bound: 3 };
2657
2659
  // A request as a run's trace shows it: each map it carries as an object of its cells.
2658
2660
  const shownRequest = (input) => Object.fromEntries(Object.entries(input).map(([n, x]) => [n, typeof x === 'number' ? x : Object.fromEntries(x)]));
2659
2661
  // The search's own runs, before it looks for what the laws need: deeper and wider, from another seed.
2660
- const deeperBudget = { trials: 600, depth: 24, bound: 8, ms: 1500, seed: 29 };
2662
+ const deeperBudget = { trials: 600, depth: 24, bound: 8, seed: 29 };
2661
2663
  function refuteByRuns(r, laws, stepLaws = [], budget = refuteBudget) {
2662
2664
  const m = r.machine;
2663
- const run = interpret(m), rand = seeded(budget.seed ?? 13), until = performance.now() + budget.ms, bound = budget.bound, shown = shownRequest;
2665
+ const run = interpret(m), rand = seeded(budget.seed ?? 13), bound = budget.bound, shown = shownRequest;
2664
2666
  // (Division by a constant is a function too, its facts Euclid's, which its JavaScript meets: not checked.)
2665
2667
  const facts = (m.facts ?? []).filter(f => !isArithmetic(f.name.slice(0, f.name.indexOf(':'))));
2666
2668
  const holds = (f, params) => {
@@ -2680,7 +2682,7 @@ function refuteByRuns(r, laws, stepLaws = [], budget = refuteBudget) {
2680
2682
  const factsHold = (params) => (alone ??= facts.filter(f => !readsParams(f)).every(f => holds(f, params)))
2681
2683
  && facts.filter(readsParams).every(f => holds(f, params));
2682
2684
  try {
2683
- for (let trial = 0; trial < budget.trials && performance.now() < until; trial++) {
2685
+ for (let trial = 0; trial < budget.trials; trial++) {
2684
2686
  const params = r.randomParams(rand, bound);
2685
2687
  if (m.pre && !evalC(m.pre, params, { scalars: {}, maps: {} }, m) || !factsHold(params))
2686
2688
  continue;
@@ -2712,7 +2714,7 @@ function refuteByRuns(r, laws, stepLaws = [], budget = refuteBudget) {
2712
2714
  // variable of a kind is drawn as its kind draws (33 yes/nos drawn from 0..7 almost never make a lawful state).
2713
2715
  const steps1 = stepLaws.filter(sl => (sl.steps ?? 1) === 1), given = withKinds(r, laws);
2714
2716
  const wide = Object.keys(m.state).length + m.inputs.length >= 32, lawsHere = wide ? given : [], kinded = wide ? r.kindsOfState() : [];
2715
- for (let trial = 0; !m.history && (steps1.length || lawsHere.length) && trial < budget.trials * 4 && performance.now() < until; trial++) {
2717
+ for (let trial = 0; !m.history && (steps1.length || lawsHere.length) && trial < budget.trials * 4; trial++) {
2716
2718
  const params = r.randomParams(rand, bound);
2717
2719
  if (m.pre && !evalC(m.pre, params, { scalars: {}, maps: {} }, m) || !factsHold(params))
2718
2720
  continue;
@@ -2739,6 +2741,8 @@ function refuteByRuns(r, laws, stepLaws = [], budget = refuteBudget) {
2739
2741
  }
2740
2742
  return undefined;
2741
2743
  }
2744
+ // The kernel's report as a verdict: its first goal left unproven, with its counterexample and why.
2745
+ export const verdictOf = (out) => ({ proven: out.proven, checked: out.checked, ...(out.failed ? { goal: out.failed.goal, stuck: out.failed.stuck, ...(out.failed.witness ? { witness: out.failed.witness } : {}), ...(out.failed.why ? { why: out.failed.why } : {}) } : {}) });
2742
2746
  const refutedVerdict = (out) => ({ proven: false, checked: false, goal: out.goal, stuck: 'sat', witness: out.witness, ...(out.run ? { run: out.run } : {}) });
2743
2747
  // The divisors some laws read (modBy, divBy), noted on the rule so its machine declares them: a law may come from
2744
2748
  // another instance of the same rule (a factory called twice).
@@ -2753,7 +2757,7 @@ export function proveRule(r, laws, opts = {}) {
2753
2757
  if (refuted)
2754
2758
  return refuted.run ? refutedVerdict(refuted) : searched(r, laws, [], refutedVerdict(refuted), opts);
2755
2759
  const out = proveLaws(r.machine, withKinds(r, laws));
2756
- const v = { proven: out.proven, checked: out.checked, ...(out.failed ? { goal: out.failed.goal, stuck: out.failed.stuck, ...(out.failed.witness ? { witness: out.failed.witness } : {}), ...(out.failed.why ? { why: out.failed.why } : {}) } : {}), ...(out.witnesses && out.proven ? { witnesses: out.witnesses } : {}) };
2760
+ const v = { ...verdictOf(out), ...(out.witnesses && out.proven ? { witnesses: out.witnesses } : {}) };
2757
2761
  return searched(r, laws, [], v, opts);
2758
2762
  }
2759
2763
  export function proveSteps(r, laws, stepLaws, opts = {}) {
@@ -2762,7 +2766,7 @@ export function proveSteps(r, laws, stepLaws, opts = {}) {
2762
2766
  if (refuted)
2763
2767
  return refutedVerdict(refuted);
2764
2768
  const out = proveStepLaws(r.machine, withKinds(r, laws), stepLaws);
2765
- const v = { proven: out.proven, checked: out.checked, ...(out.failed ? { goal: out.failed.goal, stuck: out.failed.stuck, ...(out.failed.witness ? { witness: out.failed.witness } : {}), ...(out.failed.why ? { why: out.failed.why } : {}) } : {}) };
2769
+ const v = verdictOf(out);
2766
2770
  return searched(r, laws, stepLaws, v, opts);
2767
2771
  }
2768
2772
  // The search, where the prover alone didn't prove the laws and nothing refuted them: the lemmas first where the rule has
@@ -2774,12 +2778,12 @@ function searched(r, laws, stepLaws, v, opts) {
2774
2778
  const deeper = refuteByRuns(r, laws, stepLaws, deeperBudget);
2775
2779
  if (deeper?.run)
2776
2780
  return refutedVerdict(deeper);
2777
- const until = performance.now() + (typeof opts.search === 'object' && opts.search.ms !== undefined ? opts.search.ms : 10_000);
2781
+ const until = clock() + (typeof opts.search === 'object' && opts.search.ms !== undefined ? opts.search.ms : 10_000);
2778
2782
  // Bounded runs (core/bmc.ts): a law broken k steps from the start, a model of the kernel's k-step goal, the run taken
2779
2783
  // by the interpreter. The shallow depths first, within a fortieth of the search's budget (at most 250 ms, counted and
2780
2784
  // in wall time); the deeper ones only where the invariant search finds nothing, within the tenth (at most a second)
2781
2785
  // kept from it, so a law the search proves costs no more than the shallow depths.
2782
- const total = until - performance.now(), tail = Math.min(1000, total / 10);
2786
+ const total = until - clock(), tail = Math.min(1000, total / 10);
2783
2787
  let reached = 0;
2784
2788
  const bounded = (ms, from) => findBoundedRun(r.machine, laws, { ms, wall: performance.now() + ms, from, progress: k => { reached = k; } });
2785
2789
  const refutedBy = (b) => refutedVerdict({ goal: `${b.law} @step (a run of ${b.depth} steps from the start)`, witness: b.witness, run: { params: b.params, trace: b.trace.map(shownRequest) } });
@@ -2805,17 +2809,17 @@ function searched(r, laws, stepLaws, v, opts) {
2805
2809
  }
2806
2810
  // Functions known by their facts alone (not a recurrence): lemmas about them, fitted to their values and proven from
2807
2811
  // the facts as cyclic claims, the laws proven with them as facts.
2808
- if ((typeof opts.search !== 'object' || opts.search.cycles !== false) && fns.some(([, d]) => !recurOf(d)) && rule.machine.facts?.length && until - performance.now() > 500) {
2809
- const c = withDeadline(until, () => cycleLemmas(rule.machine, withKinds(rule, laws), stepLaws, { ms: (until - performance.now()) / 2 }));
2812
+ if ((typeof opts.search !== 'object' || opts.search.cycles !== false) && fns.some(([, d]) => !recurOf(d)) && rule.machine.facts?.length && until - clock() > 500) {
2813
+ const c = withDeadline(until, () => cycleLemmas(rule.machine, withKinds(rule, laws), stepLaws, { ms: (until - clock()) / 2 }));
2810
2814
  if (c.proven && c.checked)
2811
2815
  return { proven: true, checked: true, found: { ...(lemmas ? { lemmas } : {}), facts: c.found.map(f => f.text) } };
2812
2816
  }
2813
- const ms = until - performance.now() - tail;
2817
+ const ms = until - clock() - tail;
2814
2818
  if (ms < 500)
2815
2819
  return v;
2816
2820
  const inf = inferLaws(rule, laws, stepLaws, { ms, ...(rule === r ? { first: v } : {}) });
2817
2821
  if (!(inf.proven && inf.checked)) {
2818
- const deep = bounded(Math.max(0, until - performance.now()), Math.max(1, reached));
2822
+ const deep = bounded(Math.max(0, until - clock()), Math.max(1, reached));
2819
2823
  if (deep)
2820
2824
  return refutedBy(deep);
2821
2825
  return { ...v, why: [v.why, `the search found nothing that proves it in ${Math.round(inf.stats.ms)} ms`].filter(Boolean).join('; ') };
@@ -2834,7 +2838,7 @@ export function proveLeadsTo(r, laws, l, opts = {}) {
2834
2838
  ...(f.found ? { found: { rank: f.found.rank, ...(f.laws?.length ? { laws: f.laws.map((law, i) => ({ law, text: f.found.laws[i] ?? law.name })) } : {}) } } : {}) };
2835
2839
  }
2836
2840
  const out = proveLiveness(r.machine, withKinds(r, laws), l);
2837
- return { proven: out.proven, checked: out.checked, ...(out.failed ? { goal: out.failed.goal, stuck: out.failed.stuck, ...(out.failed.witness ? { witness: out.failed.witness } : {}), ...(out.failed.why ? { why: out.failed.why } : {}) } : {}) };
2841
+ return verdictOf(out);
2838
2842
  }
2839
2843
  // `ms`: the budget (the prover's own per goal, 20 s or a second a hypothesis, where none is given), on the clock the
2840
2844
  // prover reads (the counted one inside a counted search): past it the verdict is unknown.
@@ -2842,7 +2846,6 @@ export const proveDecision = (d, opts = {}) => {
2842
2846
  const go = () => (d.steps ? proveSteps(d.steps.rule, [], [d.steps.law], { search: false }) : goalsVerdict([d.goal]));
2843
2847
  return opts.ms === undefined ? go() : withDeadline(clock() + opts.ms, go);
2844
2848
  };
2845
- const seeded = (seed) => { let x = seed; return k => { x = (x * 1103515245 + 12345) % 2 ** 31; return Math.floor(x / 2 ** 31 * k); }; };
2846
2849
  // A decision's callbacks against its condition, on random params and requests: `given` and `then` each run with every
2847
2850
  // value known, against what the interpreter evaluates of the decision built from them.
2848
2851
  export function crossCheckDecision(d, opts = {}) {
@@ -14,10 +14,9 @@
14
14
  // value before, shifts of it, the request's values and the state before; each is chosen to satisfy P at every
15
15
  // counterexample so far, per case of the step (the conditions its updates split on: the request's clause, say).
16
16
  // A law under a `forall` key takes witness terms only (a ghost per key would be a map).
17
- import { evalC, evalE } from "./machine.js";
18
- import { proveLaw, proveLaws, withinDeadline } from "../kernel/prove.js";
19
- const k = (value) => ({ op: 'const', value });
20
- const v = (name) => ({ op: 'var', name });
17
+ import { evalC, evalE, n as k, walk, x as v } from "./machine.js";
18
+ import { clock, proveLaw, proveLaws, withinDeadline } from "../kernel/prove.js";
19
+ import { env } from "./solver.js";
21
20
  const add = (a, b) => (a.op === 'const' && a.value === 0 ? b : b.op === 'const' && b.value === 0 ? a : { op: 'add', a, b });
22
21
  const sum = (es) => es.reduce((acc, e) => add(acc, e), k(0));
23
22
  const sub = (a, b) => (b.op === 'const' && b.value === 0 ? a : { op: 'sub', a, b });
@@ -286,18 +285,12 @@ const caseAt = (cases, env, st, m) => {
286
285
  };
287
286
  function constantsOf(m) {
288
287
  const out = new Set([1, 2]);
289
- const walk = (t) => {
290
- if (!t || typeof t !== 'object')
291
- return;
292
- const o = t;
288
+ walk(m.step, o => {
293
289
  if (o.op === 'const' && typeof o.value === 'number' && o.value > 0 && o.value <= 64)
294
290
  out.add(o.value);
295
291
  if (o.op === 'mul' && typeof o.k === 'number' && o.k > 1 && o.k <= 64)
296
292
  out.add(o.k);
297
- for (const x of Object.values(o))
298
- (Array.isArray(x) ? x : [x]).forEach(walk);
299
- };
300
- walk(m.step);
293
+ });
301
294
  return [...out].sort((a, b) => a - b).slice(0, 6);
302
295
  }
303
296
  const dedupe = (cs) => [...new Map(cs.map(c => [key(c), c])).values()];
@@ -470,7 +463,7 @@ export function proveSome(m, laws, opts = {}) {
470
463
  return { machine: b.machine, laws: out, ghosts: b.ghosts };
471
464
  };
472
465
  const rounds = opts.rounds ?? 24;
473
- const log = globalThis.process?.env?.GDP_EXISTS_LOG === '1';
466
+ const log = env.GDP_EXISTS_LOG === '1';
474
467
  // Each law's witness until its goals are proven with every law assumed (choose); then the whole set, and where a
475
468
  // later choice broke a law proven before (a witness term is a hypothesis of every law), that law's again.
476
469
  const choose = (i, p, pass, first) => {
@@ -484,7 +477,7 @@ export function proveSome(m, laws, opts = {}) {
484
477
  // A witness given: the kernel proves the law with it, or refuses it here, with its counterexample.
485
478
  if (p.given)
486
479
  return { proven: false, nodes: 0, leaves: 0, checked: false, failed: { goal: r.goal, stuck: r.stuck, ...(r.witness ? { witness: r.witness } : {}), why: `the witness given for "${p.law.name}" does not prove it` } };
487
- if (withinDeadline(Infinity) <= performance.now())
480
+ if (withinDeadline(Infinity) <= clock())
488
481
  return fail(`the deadline passed choosing a witness for "${p.law.name}" (${r.stuck})`);
489
482
  if (round >= rounds)
490
483
  return fail(`no witness found for "${p.law.name}" in ${rounds} rounds (${r.stuck}): name one (exists(kind, f, witness))`);
@@ -33,7 +33,7 @@ export type Evidence = {
33
33
  ms: number;
34
34
  mismatch?: string;
35
35
  };
36
- export declare function instrument(code: string, file: string, tail?: string): {
36
+ export declare function instrument(code: string, file: string, tail?: string, extra?: [number, string][]): {
37
37
  js: string;
38
38
  arms: Arm[];
39
39
  };
@@ -50,13 +50,14 @@ export type Sandbox = {
50
50
  setNow: (n: number) => void;
51
51
  get: (name: string) => unknown;
52
52
  };
53
- export declare function sandbox(code: string, file: string, expose: string[], modules?: Record<string, unknown>, init?: string, files?: Record<string, string>): Sandbox & {
53
+ export declare function sandbox(code: string, file: string, expose: string[], modules?: Record<string, unknown>, init?: string, files?: Record<string, string>, extra?: [number, string][]): Sandbox & {
54
54
  arms: Arm[];
55
55
  };
56
56
  type Cells = Record<string, Record<string, Raw>>;
57
57
  export type Snap = {
58
58
  leaves: Record<string, Raw>;
59
59
  maps: Record<string, Cells>;
60
+ lists?: Record<string, Raw[]>;
60
61
  };
61
62
  export declare const kindOfVar: (v: Var, sorts: Sorts, at?: string) => Kind<unknown>;
62
63
  export type CheckOptions = {
@@ -18,11 +18,12 @@ const proc = globalThis.process;
18
18
  const vmOf = () => { const m = proc?.getBuiltinModule?.('node:vm'); if (!m)
19
19
  throw new Error('the check runs the code in node:vm (Node 20.16 or later, or Bun)'); return m; };
20
20
  import { Int, Term, bool, int, intern, interned, nat, no, oneOf, str, proveSteps } from "./dsl.js";
21
+ import { seeded, walk } from "./machine.js";
21
22
  import { allowed } from "./watch.js";
22
23
  import { normalize, resolveIn, scriptKind } from "./extract-read.js";
23
24
  import * as I from "./extract-ir.js";
24
25
  // --- the code, instrumented and loaded ------------------------------------------------------------------------------
25
- export function instrument(code, file, tail = '') {
26
+ export function instrument(code, file, tail = '', extra = []) {
26
27
  const sf = ts.createSourceFile(file, code, ts.ScriptTarget.ES2022, true, scriptKind(file));
27
28
  const arms = [], edits = [];
28
29
  const loc = (n) => { const { line, character } = sf.getLineAndCharacterOfPosition(n.getStart()); return `${file.split('/').pop()}:${line + 1}:${character + 1}`; };
@@ -58,6 +59,7 @@ export function instrument(code, file, tail = '') {
58
59
  ts.forEachChild(n, visit);
59
60
  };
60
61
  visit(sf);
62
+ edits.push(...extra);
61
63
  // Later positions first; at one position, in the order made reversed (a closing paren before the next opening one).
62
64
  const order = edits.map((e, i) => [...e, i]).sort((a, b) => b[0] - a[0] || b[2] - a[2]);
63
65
  let out = code;
@@ -67,22 +69,23 @@ export function instrument(code, file, tail = '') {
67
69
  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
70
  return { js, arms };
69
71
  }
70
- export function sandbox(code, file, expose, modules = {}, init, files = {}) {
72
+ export function sandbox(code, file, expose, modules = {}, init, files = {}, extra = []) {
71
73
  const vm = vmOf();
72
- const { js, arms } = instrument(code, file, init ? `\n;(globalThis as any).__gdpInit = () => (${init});\n` : '');
74
+ const { js, arms } = instrument(code, file, init ? `\n;(globalThis as any).__gdpInit = () => (${init});\n` : '', extra);
73
75
  const counts = arms.map(() => 0);
74
76
  let now = 0;
77
+ const stub = (name) => new Proxy({}, {
78
+ get: (_, k) => { if (k === '__esModule' || typeof k === 'symbol')
79
+ return undefined; throw new Error(`the check loads no module ${name} (its ${String(k)} was read)`); },
80
+ ownKeys: () => [],
81
+ });
75
82
  const module = { exports: {} };
76
83
  const ctx = vm.createContext({
77
84
  __cov: (i) => { counts[i]++; }, __now: () => now, module, exports: module.exports,
78
85
  // A relative import among the files given: loaded in this VM (not counted: the branches are the entry's). A module
79
86
  // the step doesn't name (React, for the component beside a reducer): a stub that throws when read, so a step that
80
87
  // 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
- })),
88
+ require: (name) => (name in modules ? modules[name] : name.startsWith('.') && Object.keys(files).length ? load(ENTRY, name) : stub(name)),
86
89
  console: { log() { }, warn() { }, error() { }, info() { }, debug() { } },
87
90
  });
88
91
  // The files given, by their place beside the entry's; each loaded once.
@@ -96,12 +99,22 @@ export function sandbox(code, file, expose, modules = {}, init, files = {}) {
96
99
  const m = { exports: {} };
97
100
  loaded.set(at, m.exports);
98
101
  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}`); })()));
102
+ // A file that doesn't load here (it reads import.meta, a browser's globals): a stub that throws when read, so a step
103
+ // that reads it fails the check rather than running without it.
104
+ try {
105
+ const f = vm.runInContext(`(function (module, exports, require) {${js}\n})`, ctx);
106
+ f(m, m.exports, (s2) => (s2 in modules ? modules[s2] : s2.startsWith('.') ? load(at, s2) : stub(s2)));
107
+ }
108
+ catch (e) {
109
+ const st = stub(`${spec} (${e.message})`);
110
+ loaded.set(at, st);
111
+ return st;
112
+ }
101
113
  loaded.set(at, m.exports);
102
114
  return m.exports;
103
115
  };
104
- vm.runInContext('Date.now = () => __now(); Math.random = () => { throw new Error("Math.random in a step") }', ctx);
116
+ // The clock is the request's: Date.now() and new Date() read it.
117
+ vm.runInContext('globalThis.Date = new Proxy(Date, {construct: (D, a) => (a.length ? new D(...a) : new D(__now())), get: (D, k) => (k === "now" ? () => __now() : D[k])}); Math.random = () => { throw new Error("Math.random in a step") }', ctx);
105
118
  vm.runInContext(`${js}\n;globalThis.__gdp = {${expose.map(n => { if (n === 'default')
106
119
  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
120
  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)} } })()');
@@ -122,6 +135,14 @@ function snapOf(v, layout, m, consts, out = { leaves: {}, maps: {} }, path = 'st
122
135
  switch (layout.k) {
123
136
  case 'scalar': {
124
137
  const sort = m.state.find(x => x.name === layout.name)?.sort;
138
+ // A Date: its time.
139
+ if (sort?.k === 'num' && sort.date) {
140
+ if (!isDateValue(v))
141
+ throw new Error(`${path} is ${JSON.stringify(v)}, not a Date`);
142
+ v = v.getTime();
143
+ if (Number.isNaN(v))
144
+ throw new Outside(`${path} is an invalid Date (past ±8.64e15 ms)`);
145
+ }
125
146
  if (sort?.k === 'num' && !(typeof v === 'number' && Number.isSafeInteger(v))) {
126
147
  if (typeof v === 'number')
127
148
  throw new Outside(`${path} is ${v}`);
@@ -173,6 +194,16 @@ function snapOf(v, layout, m, consts, out = { leaves: {}, maps: {} }, path = 'st
173
194
  out.maps[d.name] = cells;
174
195
  return out;
175
196
  }
197
+ case 'list': {
198
+ const d = m.lists.find(x => x.name === layout.name);
199
+ if (!Array.isArray(v))
200
+ throw new Error(`${path} is ${JSON.stringify(v)}, not an array`);
201
+ // Every index an item (an array with holes, or more than its own indices, is not a list).
202
+ if (Object.keys(v).length !== v.length)
203
+ throw new Error(`${path} has holes or fields beside its items`);
204
+ (out.lists ??= {})[d.name] = v.map((x, i) => checkCell(x, d.fields[0], `${path}[${i}]`));
205
+ return out;
206
+ }
176
207
  case 'const': {
177
208
  const want = layout.value.s === 'str' ? (layout.value.e.op === 'slit' ? layout.value.e.value : undefined) : consts(layout.value.e);
178
209
  if (v !== want)
@@ -181,7 +212,15 @@ function snapOf(v, layout, m, consts, out = { leaves: {}, maps: {} }, path = 'st
181
212
  }
182
213
  }
183
214
  }
215
+ const isDateValue = (x) => Object.prototype.toString.call(x) === '[object Date]';
184
216
  function checkCell(x, f, path) {
217
+ if (f.sort.k === 'num' && f.sort.date) {
218
+ if (!isDateValue(x))
219
+ throw new Error(`${path} is ${JSON.stringify(x)}, not a Date`);
220
+ x = x.getTime();
221
+ if (Number.isNaN(x))
222
+ throw new Outside(`${path} is an invalid Date (past ±8.64e15 ms)`);
223
+ }
185
224
  if (f.sort.k === 'num') {
186
225
  if (typeof x === 'number' && Number.isSafeInteger(x))
187
226
  return x;
@@ -205,20 +244,25 @@ function checkCell(x, f, path) {
205
244
  function valueOf(s, layout, m, consts, ctx) {
206
245
  const tree = (l) => {
207
246
  switch (l.k) {
208
- case 'scalar': return s.leaves[l.name];
247
+ case 'scalar': {
248
+ const sort = m.state.find(x => x.name === l.name)?.sort;
249
+ return sort?.k === 'num' && sort.date ? { $date: s.leaves[l.name] } : s.leaves[l.name];
250
+ }
209
251
  case 'rec': return Object.fromEntries(l.fields.filter(([f]) => !f.endsWith('()')).map(([f, sub]) => [f, tree(sub)]));
210
252
  case 'map': {
211
253
  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]);
254
+ const dated = (f, x) => (f.sort.k === 'num' && f.sort.date ? { $date: x } : x);
255
+ const entries = Object.entries(s.maps[d.name] ?? {}).map(([k, c]) => [d.key === 'num' ? Number(k) : k, d.scalar ? dated(d.fields[0], c.value) : Object.fromEntries(d.fields.map(f => [f.name, dated(f, c[f.name])]))]);
213
256
  return { $map: d.js, entries };
214
257
  }
258
+ case 'list': return s.lists?.[l.name] ?? [];
215
259
  case 'const': return l.value.s === 'str' ? (l.value.e.op === 'slit' ? l.value.e.value : undefined) : consts(l.value.e);
216
260
  }
217
261
  };
218
262
  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);
263
+ 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);
220
264
  }
221
- const showSnap = (s) => JSON.stringify({ ...s.leaves, ...Object.fromEntries(Object.entries(s.maps).map(([k, v]) => [k, v])) });
265
+ const showSnap = (s) => JSON.stringify({ ...s.leaves, ...Object.fromEntries(Object.entries(s.maps).map(([k, v]) => [k, v])), ...(s.lists ?? {}) });
222
266
  const sameSnap = (a, b) => {
223
267
  for (const k of new Set([...Object.keys(a.leaves), ...Object.keys(b.leaves)]))
224
268
  if (a.leaves[k] !== b.leaves[k])
@@ -229,6 +273,9 @@ const sameSnap = (a, b) => {
229
273
  if (JSON.stringify(x[key]) !== JSON.stringify(y[key]))
230
274
  return `${k}[${key}] is ${JSON.stringify(x[key])} in the code, ${JSON.stringify(y[key])} in the rule`;
231
275
  }
276
+ for (const k of new Set([...Object.keys(a.lists ?? {}), ...Object.keys(b.lists ?? {})]))
277
+ if (JSON.stringify(a.lists?.[k] ?? []) !== JSON.stringify(b.lists?.[k] ?? []))
278
+ return `${k} is ${JSON.stringify(a.lists?.[k] ?? [])} in the code, ${JSON.stringify(b.lists?.[k] ?? [])} in the rule`;
232
279
  return undefined;
233
280
  };
234
281
  // --- the rule's side ------------------------------------------------------------------------------------------------
@@ -249,8 +296,11 @@ function ruleSnap(r, m, st, sorts) {
249
296
  }
250
297
  maps[md.name] = cells;
251
298
  }
299
+ const lists = {};
300
+ for (const ld of m.lists ?? [])
301
+ lists[ld.name] = (d[ld.name] ?? []);
252
302
  void sorts;
253
- return { leaves, maps };
303
+ return { leaves, maps, ...(m.lists?.length ? { lists } : {}) };
254
304
  }
255
305
  // A snapshot as a state of the rule (each variable and cell by its kind).
256
306
  function ruleState(base, s, m, sorts) {
@@ -267,23 +317,25 @@ function ruleState(base, s, m, sorts) {
267
317
  (maps[part] ??= new Map()).set(key, x);
268
318
  }
269
319
  }
320
+ // A list: its items at their indices, its length.
321
+ for (const d of m.lists ?? []) {
322
+ const kind = kindOfVar(d.fields[0], sorts, `${d.name}.$item`), xs = s.lists?.[d.name] ?? [];
323
+ scalars[`${d.name}_len`] = xs.length;
324
+ xs.forEach((x, i) => { for (const [part, y] of Object.entries(kind.encode(d.name, x)))
325
+ if (y !== 0)
326
+ (maps[part] ??= new Map()).set(i, y); });
327
+ }
270
328
  return { ...base, scalars, maps };
271
329
  }
272
330
  import { record } from "./dsl.js";
273
331
  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); }; };
332
+ // --- values to draw -------------------------------------------------------------------------------------------------
275
333
  const BIG = [Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER - 1, 2 ** 31, 2 ** 32];
276
334
  function constantsOf(m) {
277
335
  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]);
336
+ walk([m.writes, m.mapWrites, m.refuse, m.pre, m.init], o => { if (o.op === 'const' && typeof o.v === 'number')
337
+ out.add(o.v); if (typeof o.k === 'number')
338
+ out.add(o.k); });
287
339
  return [...out];
288
340
  }
289
341
  function draw(sort, sorts, name, rand, near, bound, strs) {
@@ -310,9 +362,12 @@ function draw(sort, sorts, name, rand, near, bound, strs) {
310
362
  }
311
363
  }
312
364
  export function check(code, file, m, r, sorts, opts = {}) {
313
- const t0 = performance.now(), rand = seeded(opts.seed ?? 7), bound = opts.bound ?? 12;
365
+ const t0 = performance.now(), rand = seeded((opts.seed ?? 7) >>> 0 || 1), bound = opts.bound ?? 12;
314
366
  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);
367
+ const box = sandbox(code, file, fns, opts.modules, m.initSource, opts.files, m.factory ? [[m.factory.at, m.factory.text]] : []);
368
+ // An object a factory makes: its state is what its functions close over, read and set through the two functions the
369
+ // check added to it.
370
+ const stateOf = (self) => (m.factory ? box.call('$get', self, []).value : self);
316
371
  const interp = r.interpreter(), gen = r.compiled(), machine = r.machine;
317
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 };
318
373
  const consts = constantsOf(m), strs = ['a', 'b', 'c', ''];
@@ -331,7 +386,8 @@ export function check(code, file, m, r, sorts, opts = {}) {
331
386
  return ev;
332
387
  };
333
388
  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'
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'
335
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]]))
336
392
  : undefined);
337
393
  void params;
@@ -391,7 +447,7 @@ export function check(code, file, m, r, sorts, opts = {}) {
391
447
  if (!res.ok)
392
448
  code = { refused: res.error };
393
449
  else
394
- code = { snap: snapOf(self, m.layout, m, evalAt(params)), out: res.value, self };
450
+ code = { snap: snapOf(stateOf(self), m.layout, m, evalAt(params)), out: res.value, self };
395
451
  }
396
452
  else {
397
453
  const input = valueOf(side.snap, m.layout, m, evalAt(params), box.ctx), before = JSON.stringify(input, mapReplacer);
@@ -456,7 +512,7 @@ export function check(code, file, m, r, sorts, opts = {}) {
456
512
  // A refusal leaves the state as it was: the object the code threw from must be as it was too.
457
513
  if (isClass) {
458
514
  try {
459
- const after = snapOf(side.self, m.layout, m, evalAt(params)), d = sameSnap(after, side.snap);
515
+ const after = snapOf(stateOf(side.self), m.layout, m, evalAt(params)), d = sameSnap(after, side.snap);
460
516
  if (d)
461
517
  return `${where}: ${req} ${from}: the code throws (${code.refused}) after changing the object: ${d}`;
462
518
  }
@@ -474,19 +530,40 @@ export function check(code, file, m, r, sorts, opts = {}) {
474
530
  const ruleSide = ruleSnap(r, m, rule.st, sorts), diff = sameSnap(code.snap, ruleSide);
475
531
  if (diff)
476
532
  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])}`;
533
+ if (isClass) {
534
+ // 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)
542
+ return bad('not a record of the fields the rule keeps');
543
+ for (const [f, n] of res.fields)
544
+ if (o[f] !== d[n])
545
+ return bad(`the rule's ${n} is ${JSON.stringify(d[n])}`);
546
+ }
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])}`);
553
+ }
481
554
  }
482
555
  next.side = { snap: code.snap, ...(code.self ? { self: code.self } : {}) };
483
556
  next.st = rule.st;
484
557
  return undefined;
485
558
  };
486
559
  // 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'); })();
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}`); })();
490
567
  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
568
  const start = (params) => {
492
569
  const ctorRefuses = (() => { const pre = evalTerm(m.pre, params); return pre !== true; })();
@@ -501,7 +578,8 @@ export function check(code, file, m, r, sorts, opts = {}) {
501
578
  const now0 = m.params.find(v => v.note?.startsWith('Date.now()'));
502
579
  if (now0)
503
580
  box.setNow(params[now0.name]);
504
- const made = box.call('$new', undefined, (m.ctorArgs ?? []).filter(n => n !== now0?.name).map(n => params[n]));
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])));
505
583
  const ruleRefuses = ps === undefined || ctorRefuses;
506
584
  if (!made.ok)
507
585
  return ruleRefuses ? {} : { problem: `new ${m.entry}(${JSON.stringify(params)}) throws (${made.error}), the rule's precondition holds` };
@@ -509,7 +587,7 @@ export function check(code, file, m, r, sorts, opts = {}) {
509
587
  return { problem: `new ${m.entry}(${JSON.stringify(params)}) is made, the rule's ${ps === undefined ? 'param kinds refuse' : 'precondition refuses'} it` };
510
588
  const st = interp.init(ps);
511
589
  try {
512
- const snap = snapOf(made.value, m.layout, m, evalAt(params));
590
+ const snap = snapOf(stateOf(made.value), m.layout, m, evalAt(params));
513
591
  const diff = sameSnap(snap, ruleSnap(r, m, st, sorts));
514
592
  if (diff)
515
593
  return { problem: `new ${m.entry}(${JSON.stringify(params)}): ${diff}` };
@@ -578,10 +656,26 @@ export function check(code, file, m, r, sorts, opts = {}) {
578
656
  }
579
657
  maps[d.name] = cells;
580
658
  }
659
+ const lists = {};
660
+ for (const d of m.lists ?? []) {
661
+ const f = d.fields[0];
662
+ lists[d.name] = Array.from({ length: rand(4) }, () => { let x = draw(f.sort, sorts, `${d.name}.$item`, rand, consts, bound, strs); if (typeof x === 'number' && sorts.get(`${d.name}.$item`) === 'nat')
663
+ x = Math.abs(x); return x; });
664
+ }
581
665
  for (const v of m.state)
582
666
  if (v.name in leaves && v.sort.k === 'num' && Math.abs(leaves[v.name]) > Number.MAX_SAFE_INTEGER / 4)
583
667
  leaves[v.name] = rand(bound);
584
- return { leaves, maps };
668
+ // A Date's time within its range (a Date past it is invalid in the code: no state of the code holds one).
669
+ for (const v of m.state)
670
+ if (v.name in leaves && v.sort.k === 'num' && v.sort.date && Math.abs(leaves[v.name]) > 8.64e15)
671
+ leaves[v.name] = rand(bound);
672
+ for (const d of m.maps)
673
+ for (const f of d.fields)
674
+ if (f.sort.k === 'num' && f.sort.date)
675
+ for (const c of Object.values(maps[d.name] ?? {}))
676
+ if (Math.abs(c[f.name]) > 8.64e15)
677
+ c[f.name] = rand(bound);
678
+ return { leaves, maps, ...(m.lists?.length ? { lists } : {}) };
585
679
  };
586
680
  const fromState = (params, snap, inputs, e, where) => {
587
681
  let ps;
@@ -655,15 +749,8 @@ function conditionsOf(m) {
655
749
  seen.add(k);
656
750
  out.push(c, I.not(c));
657
751
  } };
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]);
752
+ walk([m.writes, m.mapWrites], o => { if ((o.op === 'ite' || o.op === 'kite') && o.c)
753
+ add(o.c); });
667
754
  for (const d of m.refuse.op === 'or' ? m.refuse.xs : [m.refuse])
668
755
  add(d);
669
756
  return out.slice(0, 48);
@@ -21,6 +21,7 @@ export type Printer = {
21
21
  };
22
22
  export declare const pnum: (e: N, P: Printer, ctx: Ctx, recv?: boolean) => string;
23
23
  export declare function pb(c: B, P: Printer, ctx: Ctx): string;
24
+ export declare const pidx: (i: N, P: Printer, ctx: Ctx) => string;
24
25
  export declare function pl(l: L, P: Printer, ctx: Ctx, bare?: boolean): string;
25
26
  export declare function pk(k: K, P: Printer, ctx: Ctx): string;
26
27
  export declare function pterm(t: Term, P: Printer, ctx: Ctx, target?: string): string;