gdp-wired 0.36.0 → 0.38.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.
@@ -13,6 +13,7 @@ export type SType = {
13
13
  atomic?: string;
14
14
  lock?: string;
15
15
  rs?: string;
16
+ mod?: string;
16
17
  } | {
17
18
  k: 'float' | 'bool' | 'str' | 'none' | 'any' | 'lock';
18
19
  atomic?: string;
@@ -184,7 +185,7 @@ export type StepOptions = {
184
185
  states?: number;
185
186
  seed?: number;
186
187
  bound?: number;
187
- probes?: boolean;
188
+ probes?: boolean | 'writes';
188
189
  };
189
190
  };
190
191
  export type IntTy = {
@@ -193,6 +194,7 @@ export type IntTy = {
193
194
  name?: string;
194
195
  t?: number;
195
196
  ub?: boolean;
197
+ mod?: string;
196
198
  };
197
199
  type V = {
198
200
  t: 'num';
@@ -297,6 +299,11 @@ type V = {
297
299
  t: 'pop';
298
300
  id: string;
299
301
  };
302
+ type CellWrite = {
303
+ key: K;
304
+ has: B;
305
+ vals: Map<string, V>;
306
+ };
300
307
  type Ptr = {
301
308
  k: 'nil';
302
309
  } | {
@@ -355,11 +362,8 @@ type Obj = {
355
362
  decl: MapDecl;
356
363
  val?: SType;
357
364
  nil?: B;
358
- w?: {
359
- key: K;
360
- has: B;
361
- vals: Map<string, V>;
362
- };
365
+ w?: CellWrite;
366
+ pre?: CellWrite[];
363
367
  origin: Origin;
364
368
  } | {
365
369
  k: 'store';
@@ -848,6 +852,7 @@ export declare class Stepper {
848
852
  wrap(e: N, ty: IntTy, x: {
849
853
  p: string;
850
854
  }, p: Path): N;
855
+ pastMod(e: N, mod: string): B;
851
856
  past(e: N, lo: number, hi: number, p: Path): [B, B];
852
857
  within(e: N, b: number, side: 'lo' | 'hi', p: Path): boolean;
853
858
  mapAt(m: V, at: SX, p: Path): Extract<Obj, {
@@ -901,6 +906,9 @@ type CellW = {
901
906
  has: B;
902
907
  vals: Record<string, Term>;
903
908
  };
909
+ export declare function padWrites<W extends {
910
+ key: K;
911
+ }>(lists: W[][], base: (k: K) => Omit<W, 'key'>): W[][];
904
912
  export declare function mapWritesOf(g: Stepper, d: MapDecl, sels: B[], ws: (CellW | undefined)[], fix?: (i: number, w: CellW, base: (k: K) => CellW) => CellW): CellW | undefined;
905
913
  export declare const rangeLaws: (state: Var[], ints: Map<string, IntTy>) => string[];
906
914
  export declare const varTerm: (v: Var) => Term;
@@ -203,7 +203,7 @@ export class Stepper {
203
203
  }
204
204
  // A fixed-width integer variable: its type, and (for a request) a value outside it refused: the claim is for the
205
205
  // type's values.
206
- intTy(t) { return t.k === 'int' && t.bits !== undefined ? { bits: t.bits, signed: t.signed ?? true } : undefined; }
206
+ intTy(t) { return t.k === 'int' && t.bits !== undefined ? { bits: t.bits, signed: t.signed ?? true, ...(t.mod ? { mod: t.mod } : {}) } : undefined; }
207
207
  typed(v, t, role, sel = this.sel) {
208
208
  const ty = 'k' in t ? this.intTy(t) : t;
209
209
  if (!ty)
@@ -213,6 +213,15 @@ export class Stepper {
213
213
  if (role === 'state')
214
214
  return;
215
215
  const x = I.nvar(v.name);
216
+ // (a value of a symbolic width: an input at or past it refused, a param's the precondition's)
217
+ if (ty.mod) {
218
+ const out = I.or(I.cmp('<', x, I.num(0)), I.cmp('<=', I.nvar(ty.mod), x));
219
+ if (role === 'param')
220
+ this.paramsOut.push(out);
221
+ else
222
+ this.refusals.push(I.and(sel, out));
223
+ return;
224
+ }
216
225
  // (a constructor's argument outside its type: no object is made with one, the rule's precondition says so)
217
226
  if (role === 'param') {
218
227
  const out = I.or(...(Number.isFinite(lo) ? [I.cmp('<', x, I.num(lo))] : []), ...(Number.isFinite(hi) ? [I.cmp('<', I.num(hi), x)] : []));
@@ -658,7 +667,14 @@ export class Stepper {
658
667
  return { ...a, f, moved: a.moved || b.moved };
659
668
  }
660
669
  if (a.k === 'map' && b.k === 'map') {
661
- const w = mergeWrites(c, a.w, b.w, key => this.baseCell(a.decl, key), (c2, x, y) => this.ite(c2, x, y, at));
670
+ const base = (key) => this.baseCell(a.decl, key), ite = (c2, x, y) => this.ite(c2, x, y, at);
671
+ // (several keys written: both paths' writes padded to one length, each place by the condition)
672
+ const [la, lb] = padWrites([[...(a.pre ?? []), ...(a.w ? [a.w] : [])], [...(b.pre ?? []), ...(b.w ? [b.w] : [])]], base);
673
+ if (la.length > 1) {
674
+ const ws = la.map((x, i) => mergeWrites(c, x, lb[i], base, ite));
675
+ return { ...a, ...(a.nil ? { nil: I.bite(c, a.nil, b.nil) } : {}), w: ws.at(-1), pre: ws.slice(0, -1) };
676
+ }
677
+ const w = mergeWrites(c, a.w, b.w, base, ite);
662
678
  return { ...a, ...(a.nil ? { nil: I.bite(c, a.nil, b.nil) } : {}), ...(w ? { w } : {}) };
663
679
  }
664
680
  if (a.k === 'list' && b.k === 'list')
@@ -1206,15 +1222,21 @@ export class Stepper {
1206
1222
  return [m.id, o];
1207
1223
  }
1208
1224
  cellOf(o, key, _p, _at) {
1209
- const base = this.baseCell(o.decl, key);
1210
- if (!o.w)
1211
- return base;
1212
- const same = I.keq(key, o.w.key);
1213
- return { has: I.bite(same, o.w.has, base.has), vals: new Map([...base.vals].map(([f, v]) => [f, this.ite(same, o.w.vals.get(f), v, _at)])) };
1225
+ let acc = this.baseCell(o.decl, key);
1226
+ for (const w of [...(o.pre ?? []), ...(o.w ? [o.w] : [])]) {
1227
+ const same = I.keq(key, w.key), a = acc;
1228
+ acc = { has: I.bite(same, w.has, a.has), vals: new Map([...a.vals].map(([f, v]) => [f, this.ite(same, w.vals.get(f), v, _at)])) };
1229
+ }
1230
+ return acc;
1214
1231
  }
1232
+ // A cell written: a second key of a scalar map keyed by numbers (a transfer's two accounts) after the first, any
1233
+ // earlier write of the same key dropped (this one is read through it).
1215
1234
  writeCell(id, o, key, has, vals, at, p) {
1216
- if (o.w && !I.same(o.w.key, key))
1217
- return refuse(at, `${at.text}: a second key of one map written in one step (the subset writes one a step)`);
1235
+ if (o.w && !I.same(o.w.key, key)) {
1236
+ if (!o.decl.scalar || o.decl.key !== 'num')
1237
+ return refuse(at, `${at.text}: a second key of one map written in one step (the subset writes one a step, or several of a map of numbers or booleans keyed by numbers)`);
1238
+ return { ...p, heap: new Map(p.heap).set(id, { ...o, pre: [...(o.pre ?? []).filter(x => !I.same(x.key, key)), o.w], w: { key, has, vals } }) };
1239
+ }
1218
1240
  return { ...p, heap: new Map(p.heap).set(id, { ...o, w: { key, has, vals } }) };
1219
1241
  }
1220
1242
  mapGet(m, k, at, p, missing) {
@@ -1232,8 +1254,11 @@ export class Stepper {
1232
1254
  }
1233
1255
  mapSet(m, k, v, at, p) {
1234
1256
  const [id, o] = this.mapObj(m, at, p);
1235
- if (o.decl.scalar)
1236
- return this.writeCell(id, o, k, I.T, new Map([['value', this.fit(v, o.decl.fields[0], at)]]), at, p);
1257
+ // (nz: a cell is held where it isn't zero, Solidity's mapping: a zero written is no cell)
1258
+ if (o.decl.scalar) {
1259
+ const x = this.fit(v, o.decl.fields[0], at);
1260
+ return this.writeCell(id, o, k, !at.nz ? I.T : x.t === 'num' ? I.not(I.cmp('=', x.e, I.num(0))) : x.t === 'bool' ? x.e : refuse(at, `${at.text}: a zero of a ${x.t}`), new Map([['value', x]]), at, p);
1261
+ }
1237
1262
  // A record put in: a fresh one (made here), its fields copied into the cell, the object no longer written apart.
1238
1263
  if (v.t === 'cell' && v.map === id && I.same(v.key, k))
1239
1264
  return p;
@@ -2516,7 +2541,7 @@ export class Stepper {
2516
2541
  if (a.t === 'opaque' || b.t === 'opaque')
2517
2542
  return [a.t === 'opaque' ? a : b, q2];
2518
2543
  const na = this.numOf(a, x, q2), nb = this.numOf(b, x, q2);
2519
- const ty = (a.t === 'num' ? a.ty : undefined) ?? (b.t === 'num' ? b.ty : undefined) ?? (ovf === 'sat0' || ovf === 'checked0' ? { bits: 0, signed: false } : undefined);
2544
+ const ty = x.ity ?? (a.t === 'num' ? a.ty : undefined) ?? (b.t === 'num' ? b.ty : undefined) ?? (ovf === 'sat0' || ovf === 'checked0' ? { bits: 0, signed: false } : undefined);
2520
2545
  let e;
2521
2546
  if (op === '+')
2522
2547
  e = I.add(na, nb);
@@ -2537,7 +2562,12 @@ export class Stepper {
2537
2562
  else
2538
2563
  return refuse(x, `${x.text}: ${op}`);
2539
2564
  const out = (n) => ({ t: 'num', e: n, ...(ty ? { ty } : {}) });
2540
- const [lo, hi] = ty ? rangeOf(ty) : [-Infinity, Infinity], [below, above] = this.past(e, lo, hi, q2);
2565
+ const [lo, hi] = ty ? rangeOf(ty) : [-Infinity, Infinity], [below0, above0] = this.past(e, lo, hi, q2);
2566
+ // (a symbolic width: past it where the result may be at least its 2^bits; of two values below it, a difference is
2567
+ // never at or past it and a sum or a product never below 0)
2568
+ const above = ty?.mod ? (op === '-' ? I.F : this.pastMod(e, ty.mod)) : above0, below = ty?.mod && op !== '-' ? I.F : below0;
2569
+ if (ty?.mod && ovf !== 'trap' && ovf !== 'checked' && ovf !== 'wrap')
2570
+ return refuse(x, `${x.text}: ${ovf} at ${tyName(ty)}`);
2541
2571
  switch (ovf) {
2542
2572
  case 'trap':
2543
2573
  this.fail(q2, I.or(below, above), x, `${x.text}: past ${tyName(ty)}'s range (${typeof x.trap === 'string' ? x.trap : `a panic: attempt to ${op === '+' ? 'add' : op === '-' ? 'subtract' : op === '*' ? 'multiply' : 'divide'} with overflow`})`);
@@ -3392,6 +3422,17 @@ export class Stepper {
3392
3422
  wrap(e, ty, x, p) {
3393
3423
  if (ty.bits === 0)
3394
3424
  return e;
3425
+ if (ty.mod) {
3426
+ // Modulo a symbolic 2^bits: a sum or a difference of two values below it is at most once past it, by cases (a
3427
+ // product may be many times past: refused).
3428
+ if (hasProduct(e))
3429
+ return refuse(x, `${x.text ? `${x.text}: ` : ''}a product wrapped modulo 2^${ty.bits} (the subset wraps sums and differences at that width)`);
3430
+ // (two values below 2^n: a sum is never below 0, a difference never at or past 2^n)
3431
+ const below = e.op === 'add' ? I.F : this.past(e, 0, Infinity, p)[0], above = e.op === 'sub' ? I.F : this.pastMod(e, ty.mod), m = I.nvar(ty.mod);
3432
+ this.notes.add(`${ty.name ?? tyName(ty)}: a result past its range wraps modulo 2^${ty.bits} (${ty.mod}, any width at least 2 in the rule: a law proven is proven at 2^${ty.bits})`);
3433
+ // (a − b below 0 is (2^n − b) + a: each part a natural, b being below 2^n)
3434
+ return I.nite(below, e.op === 'sub' ? I.add(I.sub(m, e.b), e.a) : I.add(e, m), I.nite(above, I.sub(e, m), e));
3435
+ }
3395
3436
  if (ty.ub) {
3396
3437
  const out = I.or(...this.past(e, ...rangeOf(ty), p));
3397
3438
  if (!(out.op === 'const' && !out.v)) {
@@ -3427,6 +3468,8 @@ export class Stepper {
3427
3468
  // Many times over (a conversion from a wider type, a product): e − 2^n·⌊(e − lo)/2^n⌋.
3428
3469
  return I.sub(e, I.mulk(m, I.divk(m, I.add(e, I.num(-lo)))));
3429
3470
  }
3471
+ // Where e may be at or past a symbolic 2^bits (false where e is a constant below 2, the least width).
3472
+ pastMod(e, mod) { return e.op === 'const' && e.v < 2 ? I.F : I.cmp('<=', I.nvar(mod), e); }
3430
3473
  // Where e may be past [lo, hi] on the path: below and above, each false where the term's bounds or the path's facts
3431
3474
  // keep it within.
3432
3475
  past(e, lo, hi, p) {
@@ -4365,12 +4408,18 @@ function readOnce(mod, opts, g) {
4365
4408
  const id = [...g.initHeap].find(([, o]) => o.k === 'map' && o.decl === d)?.[0];
4366
4409
  if (!id)
4367
4410
  continue;
4368
- const ws = finals.map(f => { const w0 = f.path.heap.get(id)?.w; return w0 && { key: w0.key, has: w0.has, vals: Object.fromEntries([...w0.vals].map(([f2, v]) => [f2, termOf(v, at)])) }; });
4411
+ const cw = (w0) => ({ key: w0.key, has: w0.has, vals: Object.fromEntries([...w0.vals].map(([f2, v]) => [f2, termOf(v, at)])) });
4412
+ const lists = finals.map(f => { const o = f.path.heap.get(id); return [...(o?.pre ?? []), ...(o?.w ? [o.w] : [])].map(cw); });
4369
4413
  // (a failure kept, the cell as it was there)
4370
- const w = mapWritesOf(g, d, finals.map(f => f.sel), ws, (i, w2, base) => { if (!kept || carried)
4371
- return w2; const fl = failedOf(finals[i]), b = base(w2.key); return { key: w2.key, has: I.bite(fl, b.has, w2.has), vals: Object.fromEntries(Object.entries(w2.vals).map(([f, t]) => [f, iteTerm(fl, b.vals[f], t)])) }; });
4414
+ const fix = (i, w2, base) => { if (!kept || carried)
4415
+ return w2; const fl = failedOf(finals[i]), b = base(w2.key); return { key: w2.key, has: I.bite(fl, b.has, w2.has), vals: Object.fromEntries(Object.entries(w2.vals).map(([f, t]) => [f, iteTerm(fl, b.vals[f], t)])) }; };
4416
+ // (several keys written by some method: each method's writes under its own selector, so a key compared is the
4417
+ // request's, never one of two by the method)
4418
+ const base = (k) => { const c = g.baseCell(d, k); return { key: k, has: c.has, vals: Object.fromEntries([...c.vals].map(([f2, v]) => [f2, termOf(v, at)])) }; };
4419
+ const ws = lists.some(l => l.length > 1) ? finals.flatMap((f, i) => lists[i].map(w2 => ({ ...fix(i, w2, base), when: f.sel }))) : [];
4420
+ const w = ws.length ? ws.at(-1) : mapWritesOf(g, d, finals.map(f => f.sel), lists.map(l => l[0]), fix);
4372
4421
  if (w)
4373
- mapWrites[d.name] = w;
4422
+ mapWrites[d.name] = ws.length > 1 ? { ...w, pre: ws.slice(0, -1) } : w;
4374
4423
  }
4375
4424
  // What each method returns, and whether it failed: the step's result.
4376
4425
  const results = {}, resultKinds = {};
@@ -4509,9 +4558,11 @@ function readOnce(mod, opts, g) {
4509
4558
  read.add(n); };
4510
4559
  for (const t of [...Object.values(writes), ...Object.values(init)])
4511
4560
  mention(t.e);
4512
- for (const w of Object.values(mapWrites)) {
4561
+ for (const w of Object.values(mapWrites).flatMap(x => [x, ...(x.pre ?? [])])) {
4513
4562
  mention(w.has);
4514
4563
  mention(w.key);
4564
+ if (w.when)
4565
+ mention(w.when);
4515
4566
  for (const t of Object.values(w.vals))
4516
4567
  mention(t.e);
4517
4568
  }
@@ -4590,6 +4641,12 @@ const defaultOf = (t, at) => {
4590
4641
  const lvalues = (e) => (e.op === 'ite' ? lvalues(e.a) : e.values);
4591
4642
  const zeroRaw = (s) => (s.k === 'num' ? 0 : s.k === 'bool' ? false : s.k === 'choice' ? s.values[0] : '');
4592
4643
  const zeroOf = (s) => (s.k === 'num' ? { t: 'num', e: I.num(0) } : s.k === 'bool' ? { t: 'bool', e: I.F } : s.k === 'choice' ? { t: 'choice', e: I.llit(s.values[0], s.values) } : { t: 'str', e: { op: 'slit', value: '' } });
4644
+ // Lists of writes of one map made one length: the shorter ones led by writes that change nothing (a cell as it is,
4645
+ // at the key the longest list writes there), so place by place they merge as one write each.
4646
+ export function padWrites(lists, base) {
4647
+ const n = Math.max(0, ...lists.map(l => l.length)), long = lists.find(l => l.length === n) ?? [];
4648
+ return lists.map(l => [...long.slice(0, n - l.length).map(w => ({ key: w.key, ...base(w.key) })), ...l]);
4649
+ }
4593
4650
  export function mapWritesOf(g, d, sels, ws, fix = (_, w) => w) {
4594
4651
  if (!ws.some(Boolean))
4595
4652
  return undefined;
@@ -4606,9 +4663,13 @@ export const rangeLaws = (state, ints) => state.flatMap(v => {
4606
4663
  const ty = ints.get(v.name), law = (b) => [`r.law(${JSON.stringify(`${v.name} within its type's range`)}, ({${v.name}}) => ${v.name}.${b})`];
4607
4664
  if (!ty || v.sort.k !== 'num')
4608
4665
  return [];
4666
+ if (ty.mod)
4667
+ return [`r.law(${JSON.stringify(`${v.name} within its type's range`)}, ({${v.name}, ${ty.mod}}) => ${v.name}.lt(${ty.mod}))`];
4609
4668
  const [lo, hi] = rangeOf(ty);
4610
4669
  return Number.isFinite(hi) ? law(`atMost(${hi}).and(${v.name}.atLeast(${lo}))`) : lo === 0 ? law('atLeast(0)') : [];
4611
4670
  });
4671
+ // Whether a term multiplies (by a variable, or by a constant other than 0 and ±1): past a width more than once.
4672
+ const hasProduct = (e) => e.op === 'mul' || (e.op === 'mulk' && Math.abs(e.k) > 1) || ((e.op === 'add' || e.op === 'sub' || e.op === 'min' || e.op === 'max' || e.op === 'ite') && (hasProduct(e.a) || hasProduct(e.b))) || ((e.op === 'neg' || e.op === 'mulk') && hasProduct(e.a));
4612
4673
  export const varTerm = (v) => (v.sort.k === 'num' ? { s: 'num', e: I.nvar(v.name) } : v.sort.k === 'bool' ? { s: 'bool', e: I.bvar(v.name) } : v.sort.k === 'choice' ? { s: 'choice', e: { op: 'var', name: v.name, values: v.sort.values } } : { s: 'str', e: { op: 'svar', name: v.name } });
4613
4674
  export function iteTerm(c, a, b) {
4614
4675
  if (a.s === 'num' && b.s === 'num')
@@ -16,6 +16,14 @@ export type ExtractOptions = Omit<ReadOptions, 'entry' | 'functions'> & {
16
16
  };
17
17
  export type Extraction = {
18
18
  ok: boolean;
19
+ quiet?: string;
20
+ replay?: (run: {
21
+ params: Record<string, number>;
22
+ trace: Record<string, unknown>[];
23
+ }, law?: unknown) => {
24
+ ok: boolean;
25
+ what: string;
26
+ };
19
27
  rule?: Rule;
20
28
  invariants?: Law[];
21
29
  source?: string;
@@ -303,7 +303,8 @@ function builderOf(m, sorts) {
303
303
  // The step: a const for each term written more than once (by the code's own local's name where it has one).
304
304
  const outs = [];
305
305
  const writes = Object.entries(m.writes), mw = Object.entries(m.mapWrites);
306
- hoist(m, P, [...writes.map(([, t]) => t.e), ...mw.flatMap(([, w]) => [w.has, ...Object.values(w.vals).map(t => t.e), w.key])]);
306
+ const allW = (w) => [...(w.pre ?? []), w];
307
+ hoist(m, P, [...writes.map(([, t]) => t.e), ...mw.flatMap(([, w0]) => allW(w0).flatMap(w => [w.has, ...Object.values(w.vals).map(t => t.e), w.key, ...(w.when ? [w.when] : [])]))]);
307
308
  const consts = [...P.hoisted.entries()];
308
309
  P.hoisted = new Map();
309
310
  const defs = [];
@@ -316,6 +317,21 @@ function builderOf(m, sorts) {
316
317
  outs.push([n, pterm(t, P, ctx(), n)]);
317
318
  for (const [n, w] of mw) {
318
319
  const d = m.maps.find(x => x.name === n);
320
+ if (w.pre) {
321
+ // Several keys written: every key at once, each cell the last write at it (k$, the key, a natural).
322
+ const k = { op: 'num', e: I.nvar('k$') }, ws = allW(w);
323
+ sorts.set('k$', 'nat');
324
+ const at = (x) => I.and(x.when ?? I.T, I.keq(k, x.key));
325
+ const has = ws.reduce((acc, x) => I.bite(at(x), x.has, acc), { op: 'cell', map: n, key: k, field: 'has' });
326
+ const vals = d.fields.map(f => {
327
+ const base = f.sort.k === 'num' ? { s: 'num', e: { op: 'cell', map: n, key: k, field: f.name } } : f.sort.k === 'choice' ? { s: 'choice', e: { op: 'cell', map: n, key: k, field: f.name, values: f.sort.values } } : { s: 'bool', e: { op: 'cell', map: n, key: k, field: f.name } };
328
+ const t = ws.reduce((acc, x) => { const c = at(x), v = x.vals[f.name]; return acc.s === 'num' && v.s === 'num' ? { s: 'num', e: I.nite(c, v.e, acc.e) } : acc.s === 'bool' && v.s === 'bool' ? { s: 'bool', e: I.bite(c, v.e, acc.e) } : acc.s === 'choice' && v.s === 'choice' ? { s: 'choice', e: I.lite(c, v.e, acc.e) } : acc; }, base);
329
+ return `${f.name}: ${pterm(t, P, ctx(), `${n}.${f.name}`)}`;
330
+ });
331
+ outs.push([n, `${n}.each(k$ => ({${[`has: ${pb(has, P, ctx())}`, ...vals].join(', ')}}))`]);
332
+ sorts.delete('k$');
333
+ continue;
334
+ }
319
335
  const vals = d.fields.map(f => `${f.name}: ${pterm(w.vals[f.name], P, { m, sorts, atoms: [w.has] }, `${n}.${f.name}`)}`);
320
336
  outs.push([n, `${n}.set(${pk(w.key, P, ctx())}, {${[`has: ${pb(w.has, P, ctx())}`, ...vals].join(', ')}})`]);
321
337
  }
@@ -330,7 +346,7 @@ function builderOf(m, sorts) {
330
346
  }
331
347
  const all = [...defs, ...outs.map(([, x]) => x)].join('\n');
332
348
  const lterms = lw.flatMap(([, ops]) => ops.flatMap(o => [o.when, ...(o.op === 'pop' ? [] : [o.x.e]), ...(o.op === 'set' ? [o.i] : [])]));
333
- const env = withChoices(envOf(...writes.map(([, t]) => t.e), ...mw.flatMap(([, w]) => [w.has, w.key, ...Object.values(w.vals).map(t => t.e)]), ...lterms), all, P, [...mw.map(([n]) => n), ...lw.map(([n]) => n)]);
349
+ const env = withChoices(envOf(...writes.map(([, t]) => t.e), ...mw.flatMap(([, w0]) => allW(w0).flatMap(w => [w.has, w.key, ...(w.when ? [w.when] : []), ...Object.values(w.vals).map(t => t.e)])), ...lterms), all, P, [...mw.map(([n]) => n), ...lw.map(([n]) => n)]);
334
350
  const ret = `{${outs.map(([n, x]) => (n.startsWith('...') ? `...${x}` : `${n}: ${x}`)).join(', ')}}`;
335
351
  lines.push(defs.length ? ` .step((${env}) => {\n${defs.map(d => ` ${d}`).join('\n')}\n return ${ret}\n })` : ` .step((${env}) => (${ret}))`);
336
352
  return lines.join('\n');
@@ -15,6 +15,7 @@ export type InferOptions = {
15
15
  minimize?: boolean;
16
16
  remainders?: boolean;
17
17
  join?: number;
18
+ cubes?: number;
18
19
  };
19
20
  export type Found = {
20
21
  law: Law;
@@ -6,8 +6,8 @@
6
6
  // together), up to three terms with small coefficients and the rule's own constants, each d the largest value the
7
7
  // runs reached (and the rule's constants just above it); the same forms where a yes/no, a choice or a small natural
8
8
  // holds one value (locked is 0 → …), and a choice's value no run reached as unreachable; and laws about every key
9
- // of the maps: forms over the cells at one key (and a scalar), at every key or every key but a scalar's (k = owner
10
- // or …), and where a cell holds one value
9
+ // of the maps: forms over the cells at one key (and a scalar, or a scalar and a param: until[k] + E <= now), at every
10
+ // key or every key but a scalar's (k = owner or …), where a cell holds one value, and where it was written (off 0)
11
11
  // - Houdini on the runs' neighbors: a reached state moved a little that every candidate alive and every law allows,
12
12
  // stepped; a candidate its step breaks is in no inductive set of them, so it is dropped
13
13
  // - the join, over the rule's own vocabulary: per control state the samples' affine hull (its equalities, exact) and
@@ -760,7 +760,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
760
760
  return verdictOf(out);
761
761
  };
762
762
  const stats = (samples, candidates, alive) => ({ samples, candidates, alive, proofs, ms: Math.round(performance.now() - t0), stopped: stop() });
763
- const first = opts.first ?? prove(laws);
763
+ const first = opts.first ?? (opts.cubes ? { proven: false, checked: false } : prove(laws));
764
764
  if ((first.proven && first.checked) || first.run)
765
765
  return { ...first, found: [], stats: stats(0, 0, 0) };
766
766
  // --- runs ------------------------------------------------------------------------------------------------------------
@@ -1005,8 +1005,10 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1005
1005
  const all = atoms.flatMap((_, i) => (modeOf(i)?.choice ? [] : [i])), cellOk = (acc) => acc.some(([i]) => atoms[i].cell) && acc.filter(([i]) => !atoms[i].cell).length <= 1 && sortedCells(acc);
1006
1006
  pick(1, [1], cellAtoms, () => true, true);
1007
1007
  pick(2, [1], all, cellOk, true);
1008
+ // (and a cell against a scalar a param apart: a time a key holds and a window against the clock, until[k] + E <= now)
1009
+ const apart = (acc) => { const c = acc.filter(([i]) => atoms[i].cell), p = acc.filter(([i]) => atoms[i].param), s = acc.filter(([i]) => !atoms[i].cell && !atoms[i].param); return c.length === 1 && p.length === 1 && s.length === 1 && c[0][1] === -s[0][1]; };
1008
1010
  if (choose(3, A) * 8 <= maxCandidates / 4)
1009
- pick(3, [1], all, acc => cellOk(acc) && acc.filter(([i]) => atoms[i].cell).length >= 2, true);
1011
+ pick(3, [1], all, acc => sortedCells(acc) && (cellOk(acc) && acc.filter(([i]) => atoms[i].cell).length >= 2 || apart(acc)), true);
1010
1012
  }
1011
1013
  const sizeOf = (coef) => coef.length * 100 + coef.reduce((s, [, c]) => s + Math.abs(c), 0);
1012
1014
  const forms = [];
@@ -1018,7 +1020,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1018
1020
  // guard in one pass over (at most 1,500 of) the rows. Building candidates takes at most a quarter of the time.
1019
1021
  const guards = [...modes].sort((p, q) => Number(!!q.choice) - Number(!!p.choice) || Number(!!q.bool) - Number(!!p.bool)).slice(0, 8);
1020
1022
  const strideS = Math.max(1, Math.ceil(NS / 1500)), strideK = Math.max(1, Math.ceil(NK / 1500));
1021
- const buildUntil = Math.min(until, now() + (until - now()) / 4);
1023
+ const buildUntil = opts.cubes ? 0 : Math.min(until, now() + (until - now()) / 4);
1022
1024
  for (const [n_, { coef, cells }] of shapes.entries()) {
1023
1025
  if (forms.length > maxCandidates || (n_ % 256 === 0 && (now() > buildUntil || stop())))
1024
1026
  break;
@@ -1033,23 +1035,56 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1033
1035
  // The rule's constants just above the largest value reached, a bound a run may not have hit.
1034
1036
  for (const b of bounds.filter(b => b > d).slice(0, 2))
1035
1037
  forms.push({ coef, d: b, cells, size: sizeOf(coef) + 1 + (cells ? 10 : 0) });
1036
- if (coef.length > 2)
1038
+ // (a cell form's one cell, a natural that starts at 0 and takes many values, bounded above: each guard also where it
1039
+ // was written, off 0; a cell of a few values has a guard at each already)
1040
+ const one = cells ? coef.filter(([i]) => atoms[i].cell) : [], c1 = one[0]?.[0] ?? -1;
1041
+ const w = one.length === 1 && one[0][1] > 0 && !atoms[c1].int && !modeOf(c1) && m.maps?.[atoms[c1].parts[0][0]] === 0 ? c1 : -1;
1042
+ if (coef.length > 2 && w < 0)
1037
1043
  continue;
1044
+ used.rows += coef.length > 2 ? Math.ceil(N / strideK) : 0;
1038
1045
  const here = guards.filter(mode => !coef.some(([i]) => i === mode.atom) && (cells ? !atoms[mode.atom].cell || sortedCells([...coef, [mode.atom, 1]]) : !atoms[mode.atom].cell));
1039
1046
  const most = here.map(() => new Map()), away = cells ? keyNots.map(() => -Infinity) : [];
1047
+ const mostW = here.map(() => new Map()), awayW = keyNots.map(() => -Infinity);
1048
+ let written = -Infinity;
1040
1049
  for (let j = 0; j < N; j += cells ? strideK : strideS) {
1041
- const value = at(coef, vals, j);
1042
- here.forEach((mode, g) => { const v = vals[mode.atom][j], b = most[g]; b.set(v, Math.max(b.get(v) ?? -Infinity, value)); });
1050
+ const value = at(coef, vals, j), wj = w >= 0 && vals[w][j] >= 1;
1051
+ if (wj)
1052
+ written = Math.max(written, value);
1053
+ here.forEach((mode, g) => { const v = vals[mode.atom][j]; for (const b of wj ? [most[g], mostW[g]] : [most[g]])
1054
+ b.set(v, Math.max(b.get(v) ?? -Infinity, value)); });
1043
1055
  // At every key but a scalar's: the largest value away from that key.
1044
1056
  if (cells)
1045
- keyNots.forEach((s, g) => { if (rows[j][K] !== valsK[s][j])
1046
- away[g] = Math.max(away[g], value); });
1057
+ keyNots.forEach((s, g) => { if (rows[j][K] !== valsK[s][j]) {
1058
+ away[g] = Math.max(away[g], value);
1059
+ if (wj)
1060
+ awayW[g] = Math.max(awayW[g], value);
1061
+ } });
1047
1062
  }
1048
- here.forEach((mode, g) => { for (const [value, dv] of most[g])
1049
- if (mode.values.includes(value) && dv < d)
1050
- forms.push({ coef, d: dv, cells, guard: { atom: mode.atom, value }, size: sizeOf(coef) + 50 }); });
1051
- keyNots.forEach((s, g) => { if (cells && Number.isFinite(away[g]) && away[g] < d)
1052
- forms.push({ coef, d: away[g], cells, guard: { keyNot: s }, size: sizeOf(coef) + 60 }); });
1063
+ // (a cell a param apart from a scalar: its guards only where it was written, below)
1064
+ if (coef.length <= 2) {
1065
+ here.forEach((mode, g) => { for (const [value, dv] of most[g])
1066
+ if (mode.values.includes(value) && dv < d)
1067
+ forms.push({ coef, d: dv, cells, guard: { atom: mode.atom, value }, size: sizeOf(coef) + 50 }); });
1068
+ keyNots.forEach((s, g) => { if (cells && Number.isFinite(away[g]) && away[g] < d)
1069
+ forms.push({ coef, d: away[g], cells, guard: { keyNot: s }, size: sizeOf(coef) + 60 }); });
1070
+ }
1071
+ // Where the cell was written (a key no step wrote holds its start: until[k] is 0, or ...), alone and beside each
1072
+ // guard, where that bounds it lower; at the largest value there and the constant above it, or, below 0, at 0 (a run
1073
+ // seldom meets a bound between two times: until[k] + E <= now, reached at the instant its lease ends).
1074
+ if (w < 0 || !Number.isFinite(written))
1075
+ continue;
1076
+ const wr = { atom: w, value: 1, hi: Infinity }, near = (dv) => (dv < 0 ? [0] : [dv, ...bounds.filter(b => b > dv).slice(0, 1)]);
1077
+ if (written < d)
1078
+ for (const dv of near(written))
1079
+ if (dv < d)
1080
+ forms.push({ coef, d: dv, cells, guard: wr, size: sizeOf(coef) + 55 });
1081
+ here.forEach((mode, g) => { for (const [value, dv] of mostW[g])
1082
+ if (mode.values.includes(value) && dv < Math.min(written, most[g].get(value)))
1083
+ for (const e of near(dv))
1084
+ forms.push({ coef, d: e, cells, guard: { atom: mode.atom, value }, also: [wr], size: sizeOf(coef) + 65 }); });
1085
+ keyNots.forEach((s, g) => { if (Number.isFinite(awayW[g]) && awayW[g] < Math.min(written, away[g]))
1086
+ for (const e of near(awayW[g]))
1087
+ forms.push({ coef, d: e, cells, guard: { keyNot: s }, also: [wr], size: sizeOf(coef) + 70 }); });
1053
1088
  }
1054
1089
  for (const mode of modes)
1055
1090
  if (!atoms[mode.atom].cell)
@@ -1436,7 +1471,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1436
1471
  return false;
1437
1472
  }
1438
1473
  };
1439
- const houdiniUntil = Math.min(until, now() + Math.max(500, (until - now()) / 4));
1474
+ const houdiniUntil = opts.cubes ? 0 : Math.min(until, now() + Math.max(500, (until - now()) / 4));
1440
1475
  for (let quiet = 0; samples.length && now() < houdiniUntil && !stop() && quiet < 3;) {
1441
1476
  const killed = new Set();
1442
1477
  for (let tries = 0; tries < 400 && now() < houdiniUntil && !stop(); tries++) {
@@ -2173,7 +2208,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
2173
2208
  // (a step law's goal: its step from a state the set allows)
2174
2209
  const stepLawOf = new Map(stepLaws.map(sl => [sl.name, sl]));
2175
2210
  // (the engine runs after a join that finds nothing, on a rule whose scalars the runs held at few values: below)
2176
- let follows;
2211
+ let follows, cubesOut;
2177
2212
  const engineFollows = () => (follows ??= !!sorts && callerLaws.some(l => l.keys?.length) && atoms.every((a, i) => a.cell || a.param || !!a.term || a.view !== undefined || i >= valsS.length || new Set(valsS[i]).size <= 4));
2178
2213
  const stepWith = (name, form, ctx) => {
2179
2214
  const ctxLaws = [...ctx, ...(form ? [form] : [])].map(lawFor), ls = [...given, ...ctxLaws], mm = forLaws(ctxLaws).m, sl = form ? undefined : stepLawOf.get(name);
@@ -2728,10 +2763,10 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
2728
2763
  // few others that keep its facts on the sort's keys (its values reversed, and each turned by one), each run as its
2729
2764
  // own machine; their states' rows read under their table. One table alone is a fact of it, not of the rule: ring's
2730
2765
  // ids, every node past another one's below it)
2731
- const tables = [{ m, run, js: m.history ? undefined : loadJs(m), fns: {} }];
2766
+ const tables = [{ m, run, js: m.history || m.counts ? undefined : loadJs(m), fns: {} }];
2732
2767
  for (const [f, fn] of Object.entries(m.fns ?? {})) {
2733
2768
  const arg = ks.find(`F:${f}`);
2734
- if (fn.call || fn.recur || (fn.arity ?? 1) !== 1 || !ss.includes(arg) || m.history)
2769
+ if (fn.call || fn.recur || (fn.arity ?? 1) !== 1 || !ss.includes(arg) || m.history || m.counts)
2735
2770
  continue;
2736
2771
  const dom = keyDom(arg), vals = dom.map(k => { try {
2737
2772
  return fnValue(fn, k);
@@ -3170,6 +3205,10 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
3170
3205
  const near = (f) => (f.cube.some(l => atomsIn(formOf([l])).some(i => callerMaps.has(atoms[i].parts[0][0].split(AT)[2] ?? ''))) ? 0 : 1);
3171
3206
  // (the rounds over the data-filtered pool cut to its minimal cubes)
3172
3207
  const minPool = env.GDP_POOL !== '0' ? minimal(enumerated()) : { kept: enumerated(), by: new Map() }, made = minPool.kept;
3208
+ if (opts.cubes) {
3209
+ cubesOut = made;
3210
+ return;
3211
+ }
3173
3212
  const tEngine = vnow();
3174
3213
  let cubes = [];
3175
3214
  // (in turn by the maps a cube reads, those reading the caller's first: one of each kind before a second of any; in
@@ -4081,6 +4120,11 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
4081
4120
  });
4082
4121
  }
4083
4122
  };
4123
+ // (the cubes alone: the engine's enumeration on the small instance and the data filter, then out)
4124
+ if (opts.cubes) {
4125
+ engine();
4126
+ return { ...first, proven: false, found: (cubesOut ?? []).filter(f => f.cube.length <= opts.cubes).map(f => ({ law: lawFor(f), text: textOf(f) })), stats: stats(0, 0, 0) };
4127
+ }
4084
4128
  for (;;) {
4085
4129
  if (now() > jUntil || stop()) {
4086
4130
  why = 'time';
package/dist/core/laws.js CHANGED
@@ -13,6 +13,7 @@
13
13
  // known by its name: two of one name in a rule are refused.
14
14
  //
15
15
  // x <= cap and not failed comparisons (< <= > >= == !=), + − and × a constant, // and % by one, and or not
16
+ // sum(balances) == total_supply a map's cells summed over every key
16
17
  // failed implies spend >= budget implies (=>), parentheses, min max abs, true false None (nil, null)
17
18
  // self.tokens <= self.capacity the state by its fields (self., this., @ or a receiver's name, or bare)
18
19
  // result == (n <= old(tokens)) a request's arguments by name, `result`, `failed`, old(x) or before.x the state
@@ -175,7 +176,7 @@ export function parse(s) {
175
176
  eat(')');
176
177
  return { k: 'old', x: e };
177
178
  }
178
- if (['min', 'max', 'abs'].includes(x) && peek() === '(') {
179
+ if (['min', 'max', 'abs', 'sum'].includes(x) && peek() === '(') {
179
180
  eat();
180
181
  const xs = [top()];
181
182
  while (peek() === ',') {
@@ -258,7 +259,7 @@ export function buildLaw(x, l, opts = {}) {
258
259
  const gate = step && method && names.some(n => n.role === 'method') ? method : undefined;
259
260
  const body = (b, a) => read(e, { b, a, step, method, keys: new Map(), roles: new Set(), methods: new Set(), clock: opts.clock }, names, false);
260
261
  if (!step)
261
- return { kind: 'law', law: r.law(l.name, (env) => body(env, env)) };
262
+ return { kind: 'law', law: r.law(l.name, (env) => (x.quiet ? env[x.quiet].eq(0).implies(body(env, env)) : body(env, env))) };
262
263
  const mname = names.find(n => n.role === 'method')?.rule;
263
264
  return { kind: 'step', ...(gate ? { method: gate } : {}), law: r.stepLaw(l.name, (b, a) => body(b, a), gate ? (b) => b[mname].is(gate) : undefined) };
264
265
  }
@@ -342,6 +343,19 @@ function val(e, c, names, dry) {
342
343
  return val(e.x, { ...c, a: c.b }, names, dry);
343
344
  }
344
345
  case 'fn': {
346
+ // sum(m): a map's cells summed over every key (one number a cell; a key it doesn't hold holds 0)
347
+ if (e.f === 'sum') {
348
+ const m = go(e.xs[0]);
349
+ if (m.t !== 'map' || e.xs.length !== 1)
350
+ throw new LawError('sum(m): the sum of a map\'s cells, m a map');
351
+ const fs = m.n.map.fields;
352
+ if (fs.length !== 1)
353
+ throw new LawError(`sum(${m.n.code}): its cells have ${fs.join(', ')} (the sum is of a map of numbers)`);
354
+ if (dry)
355
+ return DRY;
356
+ const map = (c.a[m.n.rule] ?? c.b[m.n.rule]);
357
+ return { t: 'num', v: Int.of(map.sum(cell => cell[fs[0]])) };
358
+ }
345
359
  const xs = e.xs.map(go);
346
360
  if (dry)
347
361
  return DRY;