gdp-wired 0.25.0 → 0.27.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 (52) hide show
  1. package/README.md +14 -9
  2. package/dist/core/accel.d.ts +20 -1
  3. package/dist/core/accel.js +797 -220
  4. package/dist/core/bmc.d.ts +12 -1
  5. package/dist/core/bmc.js +275 -106
  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 +103 -74
  10. package/dist/core/data.d.ts +1 -1
  11. package/dist/core/data.js +89 -118
  12. package/dist/core/discover.js +65 -27
  13. package/dist/core/dsl.d.ts +3 -2
  14. package/dist/core/dsl.js +29 -25
  15. package/dist/core/exists.js +7 -14
  16. package/dist/core/extract-check.d.ts +55 -4
  17. package/dist/core/extract-check.js +248 -122
  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 +98 -4
  21. package/dist/core/extract-read.js +306 -43
  22. package/dist/core/extract-shapes.d.ts +14 -0
  23. package/dist/core/extract-shapes.js +609 -79
  24. package/dist/core/extract-xstate.d.ts +5 -1
  25. package/dist/core/extract-xstate.js +618 -184
  26. package/dist/core/extract.d.ts +1 -0
  27. package/dist/core/extract.js +81 -30
  28. package/dist/core/infer.d.ts +1 -0
  29. package/dist/core/infer.js +126 -64
  30. package/dist/core/machine.d.ts +6 -0
  31. package/dist/core/machine.js +35 -4
  32. package/dist/core/nonterm.d.ts +5 -1
  33. package/dist/core/nonterm.js +133 -45
  34. package/dist/core/q.d.ts +1 -0
  35. package/dist/core/q.js +2 -2
  36. package/dist/core/relation.d.ts +1 -0
  37. package/dist/core/relation.js +20 -36
  38. package/dist/core/solver.d.ts +33 -0
  39. package/dist/core/solver.js +84 -30
  40. package/dist/core/transfer.js +22 -13
  41. package/dist/core/translate.d.ts +1 -1
  42. package/dist/core/translate.js +88 -65
  43. package/dist/core/xstate.d.ts +6 -1
  44. package/dist/core/xstate.js +336 -55
  45. package/dist/kernel/cdcl.js +212 -79
  46. package/dist/kernel/prove.d.ts +36 -5
  47. package/dist/kernel/prove.js +212 -104
  48. package/dist/kernel/reader.d.ts +75 -5
  49. package/dist/kernel/reader.js +533 -76
  50. package/dist/kernel/simplex.d.ts +27 -2
  51. package/dist/kernel/simplex.js +160 -14
  52. package/package.json +3 -2
@@ -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)} } })()');
@@ -113,15 +126,23 @@ export function sandbox(code, file, expose, modules = {}, init, files = {}) {
113
126
  return { ctx, counts, arms, call, setNow: n => { now = n; }, get: name => vm.runInContext(`__gdp[${JSON.stringify(name)}]`, ctx) };
114
127
  }
115
128
  const isMap = (x) => Object.prototype.toString.call(x) === '[object Map]';
116
- class Outside extends Error {
129
+ export class Outside extends Error {
117
130
  }
118
- class Refused extends Error {
131
+ export class Refused extends Error {
119
132
  }
120
133
  // The code's value as a snapshot, by the layout; what the rule has no place for is a difference.
121
134
  function snapOf(v, layout, m, consts, out = { leaves: {}, maps: {} }, path = 'state') {
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,21 +244,26 @@ 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])) });
222
- const sameSnap = (a, b) => {
265
+ export const showSnap = (s) => JSON.stringify({ ...s.leaves, ...Object.fromEntries(Object.entries(s.maps).map(([k, v]) => [k, v])), ...(s.lists ?? {}) });
266
+ export 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])
225
269
  return `${k} is ${JSON.stringify(a.leaves[k])} in the code, ${JSON.stringify(b.leaves[k])} in the rule`;
@@ -229,12 +273,15 @@ 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 ------------------------------------------------------------------------------------------------
235
282
  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
283
  const idText = (id) => interned().find(([, n]) => n === id)?.[0];
237
- function ruleSnap(r, m, st, sorts) {
284
+ export function ruleSnap(r, m, st, sorts) {
238
285
  const d = r.decode(st), leaves = {}, maps = {};
239
286
  for (const v of m.state)
240
287
  if (!m.outputs.includes(v.name))
@@ -249,11 +296,14 @@ 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
- function ruleState(base, s, m, sorts) {
306
+ export function ruleState(base, s, m, sorts) {
257
307
  const scalars = { ...base.scalars }, maps = Object.fromEntries(Object.entries(base.maps).map(([k]) => [k, new Map()]));
258
308
  for (const v of m.state)
259
309
  if (v.name in s.leaves)
@@ -267,26 +317,28 @@ 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
- function constantsOf(m) {
334
+ export 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
- function draw(sort, sorts, name, rand, near, bound, strs) {
341
+ export function draw(sort, sorts, name, rand, near, bound, strs) {
290
342
  switch (sort.k) {
291
343
  case 'bool': return rand(2) === 1;
292
344
  case 'choice': return sort.values[rand(sort.values.length)];
@@ -310,33 +362,83 @@ 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;
314
365
  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).
366
+ const box = sandbox(code, file, fns, opts.modules, m.initSource, opts.files, m.factory ? [[m.factory.at, m.factory.text]] : []);
367
+ // An object a factory makes: its state is what its functions close over, read and set through the two functions the
368
+ // check added to it.
369
+ const stateOf = (self) => (m.factory ? box.call('$get', self, []).value : self);
321
370
  const evalAt = (env) => (t) => evalTerm(t, env);
322
- const fail = (what) => { ev.mismatch = what; return finish(); };
323
371
  // The arms of the code the step reads (the entry, its methods, the functions it inlines; a class's constructor too).
324
372
  const inSpan = (a) => !m.spans || m.spans.some(([s0, e0]) => a.pos >= s0 && a.pos < e0);
325
373
  const counted = box.arms.map((a, i) => [a, i]).filter(([a]) => inSpan(a));
326
- ev.coverage.arms = counted.length;
374
+ const E = JSON.stringify(m.entry);
375
+ if (isClass && !m.factory)
376
+ 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);
377
+ if (m.factory)
378
+ 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);
379
+ 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]));
380
+ const side = {
381
+ make: params => {
382
+ const now0 = m.params.find(v => v.note?.startsWith('Date.now()'));
383
+ if (now0)
384
+ box.setNow(params[now0.name]);
385
+ // A Map the constructor is given: an empty one, made in the code's realm.
386
+ return 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])));
387
+ },
388
+ 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}`); })()),
389
+ snapOf: (self, params) => snapOf(stateOf(self), m.layout, m, evalAt(params)),
390
+ call: (self, e, args) => box.call('$method', self, [e.call, args]),
391
+ reduce: (snap, e, args, params) => {
392
+ const input = valueOf(snap, m.layout, m, evalAt(params), box.ctx), before = JSON.stringify(input, mapReplacer);
393
+ const res = box.call(e.call, undefined, [input, ...args.slice(1)]);
394
+ if (JSON.stringify(input, mapReplacer) !== before)
395
+ return { problem: `${e.call} changed the state it was given` };
396
+ return res.ok ? { snap: snapOf(res.value, m.layout, m, evalAt(params)) } : { refused: res.error };
397
+ },
398
+ args: (inputs, e) => {
399
+ 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]; };
400
+ 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'
401
+ ? 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]]))
402
+ : undefined);
403
+ return e.args.map(build);
404
+ },
405
+ setNow: n => box.setNow(n),
406
+ // The code's own initial state (where the code gives it), against the rule's.
407
+ init: (snap, params) => {
408
+ if (!m.initSource)
409
+ return undefined;
410
+ const made = vmOf().runInContext('(() => { try { return {ok: true, value: __gdpInit()} } catch (e) { return {ok: false, error: String(e)} } })()', box.ctx);
411
+ if (!made.ok)
412
+ return `the initial state throws (${made.error})`;
413
+ try {
414
+ const diff = sameSnap(snapOf(made.value, m.layout, m, evalAt(params)), snap);
415
+ if (diff)
416
+ return `the initial state: ${diff}`;
417
+ }
418
+ catch (x) {
419
+ return `the initial state: ${x.message}`;
420
+ }
421
+ return undefined;
422
+ },
423
+ 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}`) }),
424
+ };
425
+ return drive(m, r, sorts, side, opts);
426
+ }
427
+ // The check: requests from the start, from drawn states and from the prover's witnesses, each made of the code
428
+ // (through its side) and of the rule, and compared.
429
+ export function drive(m, r, sorts, code, opts = {}) {
430
+ const t0 = performance.now(), rand = seeded((opts.seed ?? 7) >>> 0 || 1), bound = opts.bound ?? 12;
431
+ const isClass = m.shape === 'class';
432
+ const interp = r.interpreter(), gen = r.compiled(), machine = r.machine;
433
+ 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 };
434
+ const consts = constantsOf(m), strs = ['a', 'b', 'c', ''];
435
+ const paramKinds = m.params.map(v => [v, kindOfVar(v, sorts)]), inputKinds = m.inputs.map(v => [v, kindOfVar(v, sorts)]);
436
+ const fail = (what) => { ev.mismatch = what; return finish(); };
327
437
  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}`);
438
+ ev.coverage = code.coverage();
330
439
  ev.ms = Math.round(performance.now() - t0);
331
440
  return ev;
332
441
  };
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
442
  const draws = (st, params) => [...consts, ...Object.values(st.leaves).filter((x) => typeof x === 'number'), ...Object.values(params).filter((x) => typeof x === 'number')];
341
443
  let lastNow = 1_000;
342
444
  const drawRequest = (st, params) => {
@@ -355,7 +457,7 @@ export function check(code, file, m, r, sorts, opts = {}) {
355
457
  const keys = Object.values(st.maps).flatMap(c => Object.keys(c));
356
458
  // An input given as a natural (domains) is drawn as one: the claim is for those, as the user said.
357
459
  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;
460
+ inputs[v.name] = code.input ? code.input(v, x, rand) : opts.given?.[v.name] === 'nat' && typeof x === 'number' ? Math.abs(x) : x;
359
461
  }
360
462
  return { e, inputs };
361
463
  };
@@ -379,31 +481,30 @@ export function check(code, file, m, r, sorts, opts = {}) {
379
481
  // Steps the code and the rule from one state; undefined when they agree (the next state on both sides is returned
380
482
  // through `next`), else the difference.
381
483
  const step = (params, ps, side, st, inputs, e, next, where) => {
382
- const args = request(params, inputs, e), raw = ruleInputs(inputs, e);
484
+ const args = code.args(inputs, e), raw = ruleInputs(inputs, e);
383
485
  const nowVar = m.inputs.find(v => v.note?.startsWith('Date.now()'));
384
486
  if (nowVar)
385
- box.setNow(inputs[nowVar.name]);
487
+ code.setNow(inputs[nowVar.name]);
386
488
  // The code.
387
- let code;
489
+ let res;
388
490
  try {
389
491
  if (isClass) {
390
- const self = side.self, res = box.call('$method', self, [e.call, args]);
391
- if (!res.ok)
392
- code = { refused: res.error };
492
+ const self = side.self, c = code.call(self, e, args);
493
+ if (!c.ok)
494
+ res = { refused: c.error };
393
495
  else
394
- code = { snap: snapOf(self, m.layout, m, evalAt(params)), out: res.value, self };
496
+ res = { snap: code.snapOf(self, params), out: c.value, self };
395
497
  }
396
498
  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 };
499
+ const c = code.reduce(side.snap, e, args, params);
500
+ if ('problem' in c)
501
+ return `${where}: ${c.problem}`;
502
+ res = c;
402
503
  }
403
504
  }
404
505
  catch (x) {
405
506
  if (x instanceof Outside)
406
- code = { outside: x.message };
507
+ res = { outside: x.message };
407
508
  else
408
509
  return `${where}: the code's state after the request: ${x.message}`;
409
510
  }
@@ -430,19 +531,22 @@ export function check(code, file, m, r, sorts, opts = {}) {
430
531
  catch (x) {
431
532
  rule = x instanceof Refused ? { refused: x.message } : /2\^53|safe integer/.test(x.message) ? { outside: x.message } : { refused: x.message };
432
533
  }
534
+ // Where Go goes on past a type the rule refuses at (a uint64 below 0): the edge the rule's claim stops at.
535
+ if ('refused' in rule && code.edge?.(side.snap, raw))
536
+ rule = { outside: `${rule.refused}: past the rule's numbers` };
433
537
  }
434
538
  const req = `${e.call}(${JSON.stringify(args).slice(1, -1)})${nowVar ? ` at ${inputs[nowVar.name]}` : ''}`;
435
539
  const from = `from ${showSnap(side.snap)}${m.params.length ? ` with ${JSON.stringify(params)}` : ''}`;
436
- if ('outside' in code || 'outside' in rule) {
540
+ if ('outside' in res || 'outside' in rule) {
437
541
  // The code past the safe integers: the rule's runtime must refuse there too (it never rounds).
438
542
  next.stop = true;
439
- if ('outside' in code) {
543
+ if ('outside' in res) {
440
544
  if ('st' in rule)
441
- return `${where}: ${req} ${from}: the code leaves the safe integers (${code.outside}) where the rule takes the step`;
545
+ return `${where}: ${req} ${from}: the code leaves the safe integers (${res.outside}) where the rule takes the step`;
442
546
  ev.outside++;
443
547
  return undefined;
444
548
  }
445
- if ('refused' in code) {
549
+ if ('refused' in res) {
446
550
  ev.refusedBoth++;
447
551
  return undefined;
448
552
  }
@@ -452,13 +556,13 @@ export function check(code, file, m, r, sorts, opts = {}) {
452
556
  ev.edgeSample ??= `${req} ${from}`;
453
557
  return undefined;
454
558
  }
455
- if ('refused' in code && 'refused' in rule) {
559
+ if ('refused' in res && 'refused' in rule) {
456
560
  // A refusal leaves the state as it was: the object the code threw from must be as it was too.
457
561
  if (isClass) {
458
562
  try {
459
- const after = snapOf(side.self, m.layout, m, evalAt(params)), d = sameSnap(after, side.snap);
563
+ const after = code.snapOf(side.self, params), d = sameSnap(after, side.snap);
460
564
  if (d)
461
- return `${where}: ${req} ${from}: the code throws (${code.refused}) after changing the object: ${d}`;
565
+ return `${where}: ${req} ${from}: the code throws (${res.refused}) after changing the object: ${d}`;
462
566
  }
463
567
  catch (x) {
464
568
  return `${where}: ${req} ${from}: the code throws after changing the object (${x.message})`;
@@ -467,26 +571,40 @@ export function check(code, file, m, r, sorts, opts = {}) {
467
571
  ev.refusedBoth++;
468
572
  return undefined;
469
573
  }
470
- if ('refused' in code)
471
- return `${where}: ${req} ${from}: the code throws (${code.refused}), the rule takes the step`;
574
+ if ('refused' in res)
575
+ return `${where}: ${req} ${from}: the code throws (${res.refused}), the rule takes the step`;
472
576
  if ('refused' in rule)
473
577
  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);
578
+ const ruleSide = ruleSnap(r, m, rule.st, sorts), diff = sameSnap(res.snap, ruleSide);
475
579
  if (diff)
476
580
  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])}`;
581
+ if (isClass) {
582
+ // The method's result, as the rule keeps it: a value, a record's fields, or a value and whether it is missing.
583
+ const rk = m.results?.[e.call], d = r.decode(rule.st);
584
+ const bad = (what) => `${where}: ${req} ${from}: ${e.call} returns ${JSON.stringify(res.out)}, ${what}`;
585
+ if (rk?.k === 'scalar' && d[rk.name] !== res.out)
586
+ return bad(`the rule's ${rk.name} is ${JSON.stringify(d[rk.name])}`);
587
+ if (rk?.k === 'rec') {
588
+ const o = res.out;
589
+ if (typeof o !== 'object' || o === null || Object.keys(o).length !== rk.fields.length)
590
+ return bad('not a record of the fields the rule keeps');
591
+ for (const [f, n] of rk.fields)
592
+ if (o[f] !== d[n])
593
+ return bad(`the rule's ${n} is ${JSON.stringify(d[n])}`);
594
+ }
595
+ if (rk?.k === 'maybe') {
596
+ const gone = res.out === (rk.null ? null : undefined);
597
+ if (gone !== d[rk.missing])
598
+ return bad(`the rule's ${rk.missing} is ${JSON.stringify(d[rk.missing])}`);
599
+ if (!gone && d[rk.name] !== res.out)
600
+ return bad(`the rule's ${rk.name} is ${JSON.stringify(d[rk.name])}`);
601
+ }
481
602
  }
482
- next.side = { snap: code.snap, ...(code.self ? { self: code.self } : {}) };
603
+ next.side = { snap: res.snap, ...(res.self ? { self: res.self } : {}) };
483
604
  next.st = rule.st;
484
605
  return undefined;
485
606
  };
486
607
  // 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
608
  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
609
  const start = (params) => {
492
610
  const ctorRefuses = (() => { const pre = evalTerm(m.pre, params); return pre !== true; })();
@@ -498,10 +616,7 @@ export function check(code, file, m, r, sorts, opts = {}) {
498
616
  ps = undefined;
499
617
  }
500
618
  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]));
619
+ const made = code.make(params);
505
620
  const ruleRefuses = ps === undefined || ctorRefuses;
506
621
  if (!made.ok)
507
622
  return ruleRefuses ? {} : { problem: `new ${m.entry}(${JSON.stringify(params)}) throws (${made.error}), the rule's precondition holds` };
@@ -509,7 +624,7 @@ export function check(code, file, m, r, sorts, opts = {}) {
509
624
  return { problem: `new ${m.entry}(${JSON.stringify(params)}) is made, the rule's ${ps === undefined ? 'param kinds refuse' : 'precondition refuses'} it` };
510
625
  const st = interp.init(ps);
511
626
  try {
512
- const snap = snapOf(made.value, m.layout, m, evalAt(params));
627
+ const snap = code.snapOf(made.value, params);
513
628
  const diff = sameSnap(snap, ruleSnap(r, m, st, sorts));
514
629
  if (diff)
515
630
  return { problem: `new ${m.entry}(${JSON.stringify(params)}): ${diff}` };
@@ -520,20 +635,9 @@ export function check(code, file, m, r, sorts, opts = {}) {
520
635
  }
521
636
  }
522
637
  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
- }
638
+ const problem = code.init?.(snap, params);
639
+ if (problem)
640
+ return { problem };
537
641
  return { side: { snap }, st, ps: ps ?? {} };
538
642
  };
539
643
  const runs = opts.runs ?? 200, depth = opts.depth ?? 12;
@@ -562,6 +666,8 @@ export function check(code, file, m, r, sorts, opts = {}) {
562
666
  }
563
667
  // Steps from drawn states.
564
668
  const drawSnap = (params) => {
669
+ if (code.drawSnap)
670
+ return code.drawSnap(rand);
565
671
  const leaves = {}, maps = {};
566
672
  for (const v of m.state)
567
673
  if (!m.outputs.includes(v.name))
@@ -578,10 +684,26 @@ export function check(code, file, m, r, sorts, opts = {}) {
578
684
  }
579
685
  maps[d.name] = cells;
580
686
  }
687
+ const lists = {};
688
+ for (const d of m.lists ?? []) {
689
+ const f = d.fields[0];
690
+ 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')
691
+ x = Math.abs(x); return x; });
692
+ }
581
693
  for (const v of m.state)
582
694
  if (v.name in leaves && v.sort.k === 'num' && Math.abs(leaves[v.name]) > Number.MAX_SAFE_INTEGER / 4)
583
695
  leaves[v.name] = rand(bound);
584
- return { leaves, maps };
696
+ // A Date's time within its range (a Date past it is invalid in the code: no state of the code holds one).
697
+ for (const v of m.state)
698
+ if (v.name in leaves && v.sort.k === 'num' && v.sort.date && Math.abs(leaves[v.name]) > 8.64e15)
699
+ leaves[v.name] = rand(bound);
700
+ for (const d of m.maps)
701
+ for (const f of d.fields)
702
+ if (f.sort.k === 'num' && f.sort.date)
703
+ for (const c of Object.values(maps[d.name] ?? {}))
704
+ if (Math.abs(c[f.name]) > 8.64e15)
705
+ c[f.name] = rand(bound);
706
+ return { leaves, maps, ...(m.lists?.length ? { lists } : {}) };
585
707
  };
586
708
  const fromState = (params, snap, inputs, e, where) => {
587
709
  let ps;
@@ -594,7 +716,11 @@ export function check(code, file, m, r, sorts, opts = {}) {
594
716
  if (evalTerm(m.pre, params) !== true)
595
717
  return undefined;
596
718
  const st = ruleState(interp.init(ps), snap, m, sorts);
597
- const side = { snap, ...(isClass ? { self: objectAt(snap, params) } : {}) };
719
+ // A state the code can't hold (a value outside its type, Go's): no state of the code is that one.
720
+ const self = isClass ? code.at(snap, params) : undefined;
721
+ if (isClass && self === undefined)
722
+ return undefined;
723
+ const side = { snap, ...(isClass ? { self: self } : {}) };
598
724
  return step(params, ps, side, st, inputs, e, {}, where);
599
725
  };
600
726
  for (let i = 0; i < (opts.states ?? 400); i++) {
@@ -638,7 +764,8 @@ export function check(code, file, m, r, sorts, opts = {}) {
638
764
  if (!ok)
639
765
  continue;
640
766
  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)}`);
767
+ const snap = { leaves, maps: Object.fromEntries(m.maps.map(d => [d.name, {}])) };
768
+ const diff = fromState(params, code.normalize ? code.normalize(snap) : snap, inputs, e, `the prover's witness for ${showCond(c)}`);
642
769
  ev.probes.steps++;
643
770
  if (diff)
644
771
  return fail(diff);
@@ -648,22 +775,15 @@ export function check(code, file, m, r, sorts, opts = {}) {
648
775
  }
649
776
  const mapReplacer = (_, v) => (isMap(v) ? { $map: [...v.entries()] } : v);
650
777
  // The conditions a step reads (each branch's, each refusal's), as a probe asks the prover to reach.
651
- function conditionsOf(m) {
778
+ export function conditionsOf(m) {
652
779
  const out = [], seen = new Set();
653
780
  const add = (c) => { if (c.op === 'const')
654
781
  return; const k = I.keyOf(c); if (!seen.has(k) && !hasCell(c)) {
655
782
  seen.add(k);
656
783
  out.push(c, I.not(c));
657
784
  } };
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]);
785
+ walk([m.writes, m.mapWrites], o => { if ((o.op === 'ite' || o.op === 'kite') && o.c)
786
+ add(o.c); });
667
787
  for (const d of m.refuse.op === 'or' ? m.refuse.xs : [m.refuse])
668
788
  add(d);
669
789
  return out.slice(0, 48);
@@ -671,7 +791,7 @@ function conditionsOf(m) {
671
791
  const hasCell = (c) => I.varsOf(c).maps.size > 0;
672
792
  const showCond = (c) => JSON.stringify(c).replace(/"op":/g, '').slice(0, 120);
673
793
  // 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) {
794
+ export function condAt(c, env) {
675
795
  const n = (e) => {
676
796
  switch (e.op) {
677
797
  case 'var': return Int.of(env[e.name]);
@@ -736,8 +856,11 @@ function condAt(c, env) {
736
856
  }
737
857
  import { yes as yesC, no as noC, when as whenDsl } from "./dsl.js";
738
858
  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) {
859
+ // A term at concrete values (a constant field over the params, a start, the precondition; with `cell`, a state's
860
+ // map cells and list items too).
861
+ export function evalTerm(t, env, cell) {
862
+ const at = (map, k, field) => (cell ?? (() => { throw new Error('a map cell at the start'); }))(map, key(k), field);
863
+ 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));
741
864
  const n = (e) => {
742
865
  switch (e.op) {
743
866
  case 'var': return env[e.name];
@@ -752,7 +875,7 @@ export function evalTerm(t, env) {
752
875
  case 'divk': return Math.floor(n(e.a) / e.k);
753
876
  case 'modk': return ((n(e.a) % e.k) + e.k) % e.k;
754
877
  case 'ite': return b(e.c) ? n(e.a) : n(e.b);
755
- case 'cell': throw new Error('a map cell at the start');
878
+ case 'cell': return at(e.map, e.key, e.field);
756
879
  }
757
880
  };
758
881
  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'); })());
@@ -767,8 +890,11 @@ export function evalTerm(t, env) {
767
890
  case 'ite': return b(x.c) ? b(x.a) : b(x.b);
768
891
  case 'is': return l(x.l) === x.value;
769
892
  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');
893
+ case 'keq':
894
+ if (!cell)
895
+ throw new Error('a key at the start');
896
+ return key(x.a) === key(x.b);
897
+ case 'cell': return at(x.map, x.key, x.field);
772
898
  }
773
899
  };
774
900
  if (t.op === 'var')
@@ -778,7 +904,7 @@ export function evalTerm(t, env) {
778
904
  if (t.op === 'lit')
779
905
  return t.value;
780
906
  if (t.op === 'ite')
781
- return b(t.c) ? evalTerm(t.a, env) : evalTerm(t.b, env);
907
+ return b(t.c) ? evalTerm(t.a, env, cell) : evalTerm(t.b, env, cell);
782
908
  if (['add', 'sub', 'neg', 'mulk', 'mul', 'min', 'max', 'divk', 'modk', 'cell'].includes(t.op))
783
909
  return n(t);
784
910
  return b(t);