gdp-wired 0.45.0 → 0.47.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 (126) hide show
  1. package/README.md +61 -8
  2. package/dist/core/bitsets.d.ts +2 -0
  3. package/dist/core/bitsets.js +23 -0
  4. package/dist/core/bmc.js +6 -2
  5. package/dist/core/c/reader.d.ts +9 -1
  6. package/dist/core/c/reader.js +423 -31
  7. package/dist/core/calendar.d.ts +29 -0
  8. package/dist/core/calendar.js +82 -0
  9. package/dist/core/cli.d.ts +4 -0
  10. package/dist/core/cli.js +206 -40
  11. package/dist/core/compose.js +3 -1
  12. package/dist/core/counts.d.ts +4 -1
  13. package/dist/core/counts.js +314 -85
  14. package/dist/core/cycles.js +8 -1
  15. package/dist/core/cyclic.d.ts +1 -0
  16. package/dist/core/cyclic.js +13 -7
  17. package/dist/core/data-synth.d.ts +3 -0
  18. package/dist/core/data-synth.js +252 -0
  19. package/dist/core/data.d.ts +2 -1
  20. package/dist/core/data.js +223 -24
  21. package/dist/core/discover.js +3 -1
  22. package/dist/core/draft.d.ts +19 -0
  23. package/dist/core/draft.js +53 -0
  24. package/dist/core/dsl.d.ts +37 -3
  25. package/dist/core/dsl.js +167 -26
  26. package/dist/core/effect-schema.d.ts +90 -0
  27. package/dist/core/effect-schema.js +500 -0
  28. package/dist/core/effect.d.ts +4 -11
  29. package/dist/core/effect.js +3 -79
  30. package/dist/core/exists.d.ts +1 -0
  31. package/dist/core/exists.js +191 -16
  32. package/dist/core/extract-c.d.ts +2 -0
  33. package/dist/core/extract-c.js +169 -22
  34. package/dist/core/extract-check.d.ts +1 -0
  35. package/dist/core/extract-check.js +97 -6
  36. package/dist/core/extract-go-check.d.ts +1 -1
  37. package/dist/core/extract-go-check.js +26 -5
  38. package/dist/core/extract-go.d.ts +8 -0
  39. package/dist/core/extract-go.js +67 -6
  40. package/dist/core/extract-ir.d.ts +1 -0
  41. package/dist/core/extract-ir.js +15 -0
  42. package/dist/core/extract-jvm.d.ts +1 -1
  43. package/dist/core/extract-jvm.js +2 -0
  44. package/dist/core/extract-orm.d.ts +12 -0
  45. package/dist/core/extract-orm.js +244 -0
  46. package/dist/core/extract-print.js +20 -1
  47. package/dist/core/extract-py.d.ts +1 -0
  48. package/dist/core/extract-py.js +1 -1
  49. package/dist/core/extract-read.d.ts +26 -1
  50. package/dist/core/extract-read.js +14 -7
  51. package/dist/core/extract-rs.js +63 -15
  52. package/dist/core/extract-shapes.d.ts +1 -0
  53. package/dist/core/extract-shapes.js +84 -0
  54. package/dist/core/extract-sol.d.ts +10 -1
  55. package/dist/core/extract-sol.js +70 -22
  56. package/dist/core/extract-standalone.d.ts +3 -0
  57. package/dist/core/extract-standalone.js +221 -0
  58. package/dist/core/extract-step.d.ts +151 -1
  59. package/dist/core/extract-step.js +1232 -60
  60. package/dist/core/extract-swift.js +6 -2
  61. package/dist/core/extract.d.ts +9 -0
  62. package/dist/core/extract.js +77 -7
  63. package/dist/core/fiber-run.d.ts +5 -0
  64. package/dist/core/fiber-run.js +18 -0
  65. package/dist/core/infer.d.ts +4 -1
  66. package/dist/core/infer.js +918 -217
  67. package/dist/core/jvm/JavaReader.java +23 -6
  68. package/dist/core/jvm/Jvm.java +3 -0
  69. package/dist/core/jvm/KtReader.java +6 -5
  70. package/dist/core/laws.d.ts +10 -3
  71. package/dist/core/laws.js +226 -23
  72. package/dist/core/machine.d.ts +15 -1
  73. package/dist/core/machine.js +187 -15
  74. package/dist/core/nonterm.js +14 -1
  75. package/dist/core/orm/harness.js +61 -0
  76. package/dist/core/orm-fixtures/schema.prisma +5 -0
  77. package/dist/core/py/harness.py +183 -10
  78. package/dist/core/py/reader.py +234 -40
  79. package/dist/core/reader-fixtures/README.md +28 -0
  80. package/dist/core/reader-fixtures/c-693042.cpp +8 -0
  81. package/dist/core/reader-fixtures/go-685506.go +14 -0
  82. package/dist/core/reader-fixtures/jvm-724362.kt +8 -0
  83. package/dist/core/reader-fixtures/jvm-737430.kt +7 -0
  84. package/dist/core/reader-fixtures/jvm-765282.kt +3 -0
  85. package/dist/core/reader-fixtures/swift-735726.swift +15 -0
  86. package/dist/core/reader-fixtures/swift-735990.swift +15 -0
  87. package/dist/core/reader-fixtures/swift-739158.swift +4 -0
  88. package/dist/core/reader-fixtures/swift-744834.swift +15 -0
  89. package/dist/core/reader-fixtures/swift-746946.swift +31 -0
  90. package/dist/core/reader-fixtures/typescript-673062.ts.txt +2 -0
  91. package/dist/core/relation.d.ts +1 -1
  92. package/dist/core/relation.js +29 -2
  93. package/dist/core/relational.js +4 -2
  94. package/dist/core/rs/Cargo.toml +1 -1
  95. package/dist/core/rs/src/main.rs +466 -11
  96. package/dist/core/sample-cache.d.ts +8 -0
  97. package/dist/core/sample-cache.js +46 -0
  98. package/dist/core/security.d.ts +38 -0
  99. package/dist/core/security.js +88 -0
  100. package/dist/core/sol/harness.py +57 -4
  101. package/dist/core/sol-concrete.d.ts +23 -0
  102. package/dist/core/sol-concrete.js +195 -0
  103. package/dist/core/solver.js +3 -1
  104. package/dist/core/swift/Sources/gdp-swiftreader/main.swift +50 -7
  105. package/dist/core/system.js +1 -1
  106. package/dist/core/transfer.js +22 -9
  107. package/dist/core/translate.js +39 -10
  108. package/dist/core/watch.js +50 -5
  109. package/dist/interchange/format.js +11 -1
  110. package/dist/kernel/cdcl.d.ts +5 -0
  111. package/dist/kernel/cdcl.js +56 -9
  112. package/dist/kernel/epr.js +108 -26
  113. package/dist/kernel/kernel.d.ts +29 -1
  114. package/dist/kernel/kernel.js +325 -62
  115. package/dist/kernel/model-sequence.d.ts +3 -0
  116. package/dist/kernel/model-sequence.js +34 -0
  117. package/dist/kernel/prove.d.ts +10 -3
  118. package/dist/kernel/prove.js +332 -71
  119. package/dist/kernel/reader.d.ts +3 -0
  120. package/dist/kernel/reader.js +101 -14
  121. package/dist/kernel/share.d.ts +1 -0
  122. package/dist/kernel/share.js +27 -0
  123. package/dist/lean-kernel/emit.js +30 -37
  124. package/dist/lean-kernel/lean-terms.js +5 -0
  125. package/dist/lean-kernel/library.js +10 -10
  126. package/package.json +6 -1
package/dist/core/data.js CHANGED
@@ -33,6 +33,7 @@ import { clock, counted, pairedKeys, withDeadline } from "../kernel/prove.js";
33
33
  import { env, work } from "./solver.js";
34
34
  import { rankOfPaths, ranksOfCalls, showC } from "./cycles.js";
35
35
  import { proveThrough, transferPlan } from "./transfer.js";
36
+ import { synthesizedLemmas, synthesizedObserver } from "./data-synth.js";
36
37
  // --- sorts and the AST ------------------------------------------------------------------------------------------------
37
38
  export const self = { self: true };
38
39
  export const natural = 'nat';
@@ -1377,6 +1378,76 @@ function foldFn(d, fields, ws) {
1377
1378
  madeFolds.set(name, self.fn);
1378
1379
  return name;
1379
1380
  }
1381
+ // A well-founded function's calls, counted: `f_calls`, of f's parameters, f's body with each choice kept and each value
1382
+ // 1 plus f_calls at the arguments of each call of f it makes (quicksort's: 1 + calls(filter≤ xs) + calls(filter> xs)).
1383
+ // It recurs where f does, at the same arguments under the same choices, so f's measure falls at its calls as at f's: its
1384
+ // termination is proven as any function's, f's measure given. Its use: the rank of f's recursion as an induction (below,
1385
+ // `schemes`), each step's descent one unfolding of it at the case, where f's measure falls only by a lemma (a filter's
1386
+ // size law), which a cyclic proof's descents can't read. None for a ring, or a call of f within f's arguments or choices.
1387
+ const madeCalls = new Map();
1388
+ function callsFn(f) {
1389
+ const name = `${f.name}_calls`;
1390
+ if (fns.has(name))
1391
+ return madeCalls.get(name) === fns.get(name) ? name : undefined;
1392
+ if (f.ring.length !== 1 || f.decreases !== undefined || !f.measure)
1393
+ return undefined;
1394
+ const has = (t) => { let yes = false; walk(t, o => { if (o.op === 'call' && o.fn === f.name)
1395
+ yes = true; }); return yes; };
1396
+ let ok = true;
1397
+ const sum = (xs) => { const ys = xs.filter(x => !(x.op === 'nat' && x.value === 0)); return ys.length ? ys.reduce((a, b) => ({ op: 'add', a, b })) : { op: 'nat', value: 0 }; };
1398
+ const count = (t) => {
1399
+ if (!has(t))
1400
+ return { op: 'nat', value: 0 };
1401
+ if (t.op === 'call' && t.fn === f.name) {
1402
+ if (has(t.args))
1403
+ ok = false;
1404
+ return { op: 'call', fn: name, args: t.args };
1405
+ }
1406
+ if (t.op === 'match') {
1407
+ if (has(t.of))
1408
+ ok = false;
1409
+ return { ...t, cases: t.cases.map(c => ({ binds: c.binds, body: count(c.body) })) };
1410
+ }
1411
+ if (t.op === 'natmatch') {
1412
+ if (has(t.of))
1413
+ ok = false;
1414
+ return { ...t, zero: count(t.zero), succ: count(t.succ) };
1415
+ }
1416
+ if (t.op === 'if') {
1417
+ if (has(t.c))
1418
+ ok = false;
1419
+ return { op: 'if', c: t.c, then: count(t.then), else: count(t.else) };
1420
+ }
1421
+ // (any other term: the calls its parts make, a condition's among them)
1422
+ const parts = [], go = (x) => { if (!x || typeof x !== 'object')
1423
+ return; if (Array.isArray(x)) {
1424
+ x.forEach(go);
1425
+ return;
1426
+ } const o = x; if ('op' in o && ['match', 'natmatch', 'if', 'call', 'var', 'nat', 'int', 'add', 'ctor'].includes(o.op)) {
1427
+ parts.push(count(o));
1428
+ return;
1429
+ } for (const v of Object.values(o))
1430
+ go(v); };
1431
+ for (const v of Object.values(t))
1432
+ go(v);
1433
+ return sum(parts);
1434
+ };
1435
+ const pre = `${f.name}.`;
1436
+ const body = JSON.parse(JSON.stringify(sum([{ op: 'nat', value: 1 }, count(f.body())])), (_, v) => (v && typeof v === 'object' && v.op === 'var' && typeof v.name === 'string' && v.name.startsWith(pre) ? { op: 'var', name: `${name}.${v.name.slice(pre.length)}` } : v));
1437
+ if (!ok)
1438
+ return undefined;
1439
+ const self = define(name, Object.fromEntries(f.params.map(q => [q.name, q.sort])), natural, () => new Nat(body));
1440
+ self.fn.stated = f.measure;
1441
+ madeCalls.set(name, self.fn);
1442
+ try {
1443
+ void self.fn.ring;
1444
+ }
1445
+ catch {
1446
+ madeCalls.delete(name);
1447
+ return undefined;
1448
+ }
1449
+ return name;
1450
+ }
1380
1451
  // An obligation as one node of a cyclic proof (no use, no models): its conclusion, each definition it reads unfolded
1381
1452
  // once, the constructors' facts at the values built, the shape at each size it reads and at its variables of a
1382
1453
  // datatype, the congruences 16 random models' explanations use. The kernel checks it as any cyclic proof; undefined where it isn't proven.
@@ -1773,7 +1844,9 @@ export const tagMap = (d) => `${d}.tag`, sizeMap = (d) => `${d}.size`;
1773
1844
  export const fieldMap = (d, j, i) => `${d.name}.${d.ctors[j].name}.${d.ctors[j].fields[i].name}`;
1774
1845
  export const ctorMap = (d, j) => `${d.name}.${d.ctors[j].name}`;
1775
1846
  // Everything a law reads: the datatypes, the functions (with those they call), the function parameters.
1776
- export function programOf(laws, extra = []) {
1847
+ // `allowCounters: false` leaves optional call-count ranks for a later search pass;
1848
+ // the original functions and every definition actually included are still admitted normally.
1849
+ export function programOf(laws, extra = [], allowCounters = true) {
1777
1850
  const fs = new Map(), ds = new Map(), ps = new Set();
1778
1851
  // A datatype with those its fields name (its group, those declared before it).
1779
1852
  const addSort = (s) => { if (s instanceof Data && !ds.has(s.name)) {
@@ -1823,6 +1896,15 @@ export function programOf(laws, extra = []) {
1823
1896
  for (const f of fs.values())
1824
1897
  place(f);
1825
1898
  }
1899
+ // (and outside a termination's proofs, the call count of each well-founded function whose measure falls only by a
1900
+ // lemma: its recursion's rank as an induction, `callsFn`)
1901
+ const counters = !allowCounters || inTermination.on ? [] : order.flatMap(f => (f.decreases === undefined && f.termination?.obligations.some(o => o.lemmas.length) ? [callsFn(f)].filter(n => n !== undefined) : []));
1902
+ if (counters.length) {
1903
+ for (const n of counters)
1904
+ visit({ op: 'call', fn: n, args: [] });
1905
+ for (const f of fs.values())
1906
+ place(f);
1907
+ }
1826
1908
  const divs = new Set();
1827
1909
  let ints = false;
1828
1910
  const scan = (t) => walk(t, o => { if (o.op === 'mod' || o.op === 'div' || o.op === 'imod' || o.op === 'idiv')
@@ -2196,6 +2278,8 @@ export class Model {
2196
2278
  case 'prod': return this.evalE(e.a, env) * this.evalE(e.b, env);
2197
2279
  case 'if': return this.evalC(e.c, env) ? this.evalE(e.then, env) : this.evalE(e.else, env);
2198
2280
  case 'get': return this.read(e.map, this.evalE(e.key, env));
2281
+ case 'tup': return safe(cpair(this.evalE(e.a, env), this.evalE(e.b, env)));
2282
+ case 'proj': return cun(this.evalE(e.a, env))[e.k];
2199
2283
  }
2200
2284
  }
2201
2285
  evalC(c, env) {
@@ -2225,7 +2309,7 @@ export function unkey(key, n) {
2225
2309
  // A sample whose evaluation passes the bounds (EvalLimit, or the stack) is skipped.
2226
2310
  export function refute(l, n = 400, seed = 7) {
2227
2311
  return bounded(() => {
2228
- for (const s of samples(l.vars, programOf([l]).params, n, seed)) {
2312
+ for (const s of samples(l.vars, programOf([l], [], false).params, n, seed)) {
2229
2313
  let ok;
2230
2314
  try {
2231
2315
  ok = evalY(l.holds, s.env, s.params);
@@ -2523,7 +2607,9 @@ function schemes(p, l) {
2523
2607
  }
2524
2608
  // Well-founded: ranked by the measure at the law's arguments; the law's variables it reads named.
2525
2609
  const read = f.params.flatMap((q, i) => (m.comps.some(c => c.coef[i]) && args[i].op === 'var' && l.vars.some(v => v.name === args[i].name) ? [{ i, v: args[i].name }] : []));
2526
- add({ name: `recursion of ${f.name} on ${read.map(r => r.v).join(', ') || 'its arguments'}`, uses, rank: m.comps.map(c => encX(p, measureX(f, c, args), new Map())),
2610
+ // (ranked by its call count where the program has it: each descent one unfolding of it, `callsFn`)
2611
+ const counter = p.fns.find(g => g.name === `${f.name}_calls` && madeCalls.get(g.name) === g);
2612
+ add({ name: `recursion of ${f.name} on ${read.map(r => r.v).join(', ') || 'its arguments'}`, uses, rank: counter ? [encX(p, { op: 'call', fn: counter.name, args }, new Map())] : m.comps.map(c => encX(p, measureX(f, c, args), new Map())),
2527
2613
  shapes: read.filter(r => f.params[r.i].sort instanceof Data).map(r => ev(r.v)) });
2528
2614
  });
2529
2615
  // Structural induction on each variable of a datatype, the others fixed; mutual where its fields reach another of its
@@ -2586,10 +2672,8 @@ function instancesOf(p, fs, w) {
2586
2672
  console.error(`[data] instances: ${what} at ${Math.round(performance.now() - tt)} ms`); };
2587
2673
  const insts = [], seen = new Set();
2588
2674
  const inst = (fact, at) => { const i = fs.at.get(fact); if (i === undefined)
2589
- return; const id = sid([i, at]); if (!seen.has(id)) {
2590
- seen.add(id);
2591
- insts.push({ fact: i, at });
2592
- } };
2675
+ return undefined; const id = sid([i, at]); if (seen.has(id))
2676
+ return undefined; seen.add(id); const q = { fact: i, at }; insts.push(q); return q; };
2593
2677
  const holdsAt = (fact, at) => { const f = fs.facts[fs.at.get(fact)]; return substShared(f.holds, Object.fromEntries(f.keys.map((key, q) => [key, at[q]]))); };
2594
2678
  // (each read once, where walk first reaches it: a read again adds nothing where these are used)
2595
2679
  const reads = (t) => readsOnce(t).map(o => ({ map: o.map, key: o.key }));
@@ -3244,7 +3328,9 @@ function linearForm(e, at, known) {
3244
3328
  case 'if':
3245
3329
  case 'min':
3246
3330
  case 'max':
3247
- case 'prod': return undefined;
3331
+ case 'prod':
3332
+ case 'tup':
3333
+ case 'proj': return undefined;
3248
3334
  }
3249
3335
  };
3250
3336
  const f = go(e);
@@ -3268,6 +3354,7 @@ function substShared(c, vars) {
3268
3354
  out = x;
3269
3355
  break;
3270
3356
  case 'mul':
3357
+ case 'proj':
3271
3358
  out = { ...x, a: e(x.a) };
3272
3359
  break;
3273
3360
  case 'if':
@@ -3281,6 +3368,7 @@ function substShared(c, vars) {
3281
3368
  case 'sub':
3282
3369
  case 'min':
3283
3370
  case 'max':
3371
+ case 'tup':
3284
3372
  out = { ...x, a: e(x.a), b: e(x.b) };
3285
3373
  break;
3286
3374
  default: out = substE(x, { vars, maps: {}, flags: {} });
@@ -3501,6 +3589,7 @@ function attempt(p, fs, l, scheme, depth, lemmas, level, pool) {
3501
3589
  varSorts = new Map(members.flatMap(mb => mb.law.vars.flatMap(v => (v.sort instanceof Data ? [[v.name, v.sort]] : []))));
3502
3590
  const lemmaNodes = lemmas.map(lm => ({ law: lm.law, node: where.get(lm.spec.name), concl: specs[where.get(lm.spec.name)].concl }));
3503
3591
  const useConcl = (u) => substC(u.node < 0 ? concls[-1 - u.node] : specs[u.node].concl, { vars: u.subst, maps: {}, flags: {} });
3592
+ const leaner = new Map();
3504
3593
  const plans = [];
3505
3594
  for (const [mi, mb] of members.entries()) {
3506
3595
  // (an implication's instances from the models where its premise holds first, the node's and each case's, as only they
@@ -3597,7 +3686,19 @@ function attempt(p, fs, l, scheme, depth, lemmas, level, pool) {
3597
3686
  const rest = fit.filter(u => u.node >= 0 && !kept.includes(u)), joins = rest.length && c.models ? caseJoins(fs, [concl, ihConcls], pre, ihConcls, few(c.models)) : undefined;
3598
3687
  const us = [...kept, ...capUses(joins ? rest.filter(u => joins(useConcl(u))) : [], lemmaCaps.joined)];
3599
3688
  const ms = few(first(c.models ?? c.near ?? models));
3600
- plan.push({ name: `${name}, case ${i + 1}`, hyps: c.lits, concl, sub: 0, insts: reached(p, fs, instsFor(ms, us, false, c.lits), [c.lits, concl, us.map(u => [u.guard, useConcl(u)]), shapesAt, rankReads], ms), uses: us });
3689
+ const from = [c.lits, concl, us.map(u => [u.guard, useConcl(u)]), shapesAt, rankReads], insts = reached(p, fs, instsFor(ms, us, false, c.lits), from, ms);
3690
+ // (and leaner: without the shapes and etas at fields' values, and what only they reach)
3691
+ const atField = (q) => /^(shape|eta) /.test(fs.facts[q.fact].name) && fieldValue(q.at[0]);
3692
+ // (and the function reads both the conclusion and a use's conclusion make, which cancel: count(x, xs) in the law and
3693
+ // in its hypothesis at the tail of ys)
3694
+ const fnReads = (t) => new Set(readsOnce(t).filter(r => r.op === 'get' && p.fns.some(f => f.name === r.map)).map(r => sid(r)));
3695
+ const inConcl = fnReads(concl), common = new Set([...fnReads(us.map(useConcl))].filter(x => inConcl.has(x)));
3696
+ const lean = reached(p, fs, insts.filter(q => !atField(q)), from, ms, common);
3697
+ // Structural equalities need their constructor fields; the arithmetic observer
3698
+ // cancellation pass only spends time on scalar laws, never on those equalities.
3699
+ if (insts.some(atField) && !inTermination.on && aboutNaturals(mb.law))
3700
+ leaner.set(`${name}, case ${i + 1}`, lean);
3701
+ plan.push({ name: `${name}, case ${i + 1}`, hyps: c.lits, concl, sub: 0, insts, uses: us });
3601
3702
  }
3602
3703
  plans.push(plan);
3603
3704
  }
@@ -3607,8 +3708,14 @@ function attempt(p, fs, l, scheme, depth, lemmas, level, pool) {
3607
3708
  const mb = members[mi], size = !mb.on ? k(0) : mb.on.d === 'nat' ? ev(mb.on.v) : get(sizeMap(mb.on.d.name), ev(mb.on.v));
3608
3709
  // (level, the measure or the size, 0 or 1), the measure's place padded to the program's widest measure
3609
3710
  const comps = mb.rank ?? [size], mid = [...comps, ...Array.from({ length: rankWidth(p) - comps.length }, () => k(0))];
3610
- for (const { sub, cases, ...n } of plan)
3611
- specs.push({ ...n, rank: [k(level), ...mid, k(sub)], uses: cases ? cases.map((g, i) => ({ node: offsets[mi] + 1 + i, subst: {}, guard: g })) : n.uses.map(u => (u.node < 0 ? { ...u, node: offsets[-1 - u.node] } : u)) });
3711
+ for (const { sub, cases, ...n } of plan) {
3712
+ const spec = { ...n, rank: [k(level), ...mid, k(sub)], uses: cases ? cases.map((g, i) => ({ node: offsets[mi] + 1 + i, subst: {}, guard: g })) : n.uses.map(u => (u.node < 0 ? { ...u, node: offsets[-1 - u.node] } : u)) };
3713
+ // (a case's leaner instances first, within a third of the attempt's time, all of them where those don't prove it:
3714
+ // the kernel's search on each node apart, the other nodes' trees kept. A merge's case node, past 11 s with all of its
3715
+ // 33 instances, is proven in 0.2 s with 8: count x (merge xs ys) = count x xs + count x ys now in 7 s, none in 96)
3716
+ const lean = leaner.get(n.name);
3717
+ specs.push(lean ? { ...spec, insts: lean, within: attemptMs.ms / 3, variants: [{ ...spec, within: attemptMs.ms }] } : spec);
3718
+ }
3612
3719
  }
3613
3720
  const name = title;
3614
3721
  // Each attempt within its own time (a goal past it is left unknown, and the attempt fails).
@@ -3622,8 +3729,8 @@ function attempt(p, fs, l, scheme, depth, lemmas, level, pool) {
3622
3729
  // Within a termination's proof (its obligations and their size laws), first without the shapes at a field's value
3623
3730
  // (a field of a variable, of a field, of a function's value): each is a split on that value's constructor that a
3624
3731
  // size's descent rarely reads, and a node with a few of them grows past its time (hmerge's size law: past 20 s with
3625
- // them, 0.8 s without). Then the nodes as built. (Elsewhere the nodes as built alone: a law's proof often reads them,
3626
- // length of append's at one vCPU past its 5 s with this pass first.)
3732
+ // them, 0.8 s without). Then the nodes as built. (Elsewhere a case's node is tried leaner first on its own, all of
3733
+ // its instances where that fails: `leaner`, above.)
3627
3734
  const lean = !inTermination.on ? specs : specs.map((n, i) => (i < base ? n : { ...n, insts: n.insts.filter(q => !(fs.facts[q.fact].name.startsWith('shape ') && fieldValue(q.at[0]))) }));
3628
3735
  if (lean.some((n, i) => n.insts.length < specs[i].insts.length)) {
3629
3736
  // (nine tenths for a law about naturals alone, a size law's or a decrease's, which reads no value's constructor)
@@ -3662,7 +3769,7 @@ const dataRate = 300;
3662
3769
  // through each instance at a read reached (a function's at its call, a constructor's at its cell, a shape or eta at a
3663
3770
  // value whose tag is read), the reads of what it gives where the models take it (an if's taken branch, an implication's
3664
3771
  // conclusion where its premise holds); a congruence where both its reads are reached.
3665
- function reached(p, fs, insts, from, ms) {
3772
+ function reached(p, fs, insts, from, ms, opaque) {
3666
3773
  const reach = new Set(), id = (t) => sid(t), done = new Map();
3667
3774
  // (an object once a model: what it reaches there is the same each time)
3668
3775
  const active = (t, m, env) => {
@@ -3706,7 +3813,8 @@ function reached(p, fs, insts, from, ms) {
3706
3813
  const each = (t) => { for (const { m, env } of ms)
3707
3814
  active(t, m, env); };
3708
3815
  // The conclusion and the uses' are read whole: the goal is where the law fails, which no model is.
3709
- walkOnce(from, o => { if (o.op === 'get')
3816
+ // (`opaque`: reads none is wanted at, unless another instance's reads reach them)
3817
+ walkOnce(from, o => { if (o.op === 'get' && !opaque?.has(sid(o)))
3710
3818
  reach.add(sid(o)); });
3711
3819
  const anchor = (q) => {
3712
3820
  const name = fs.facts[q.fact].name;
@@ -4181,6 +4289,8 @@ function proveWith(p, fs, l, lemmas, level, opts, until, per, depths, without, m
4181
4289
  // by every random value, smallest first, each named canonically (its variables in order of appearance), none ground,
4182
4290
  // none the law, none that follows by rewriting with smaller ones; and for each predicate the law reads, that a function
4183
4291
  // returning a datatype keeps it (p(x) implies p(f(x, ...)), under a comparison of two naturals where that is needed).
4292
+ // (the observers distributed over a builder, below: proven together before the law is tried again)
4293
+ const distributed = new WeakSet();
4184
4294
  export function conjectures(p, l, max = 24, maxSize = 6) {
4185
4295
  const sortsOf = (s) => (s instanceof Data ? s.name : s);
4186
4296
  const vars = [...p.datas.flatMap(d => [{ name: `${d.name.toLowerCase()}1`, sort: d }, { name: `${d.name.toLowerCase()}2`, sort: d }]), { name: 'n1', sort: 'nat' }, { name: 'n2', sort: 'nat' }];
@@ -4431,6 +4541,54 @@ export function conjectures(p, l, max = 24, maxSize = 6) {
4431
4541
  if (size(big) > size(small))
4432
4542
  rules.push({ l: big, r: small, vs });
4433
4543
  }
4544
+ // An observer distributed over a function that builds its datatype (past the sizes above: count x (merge xs ys) =
4545
+ // count x xs + count x ys is seven symbols a side): for each function to a natural reading a datatype (`o`) and each
4546
+ // function returning that datatype from values of it (`m`), o(m(a, b, ..)) = o(a) + o(b) + ..; and for two such
4547
+ // functions of one signature, o(m1(v̄)) + o(m2(v̄)) = o(a) + .. (take and drop, evens and odds, a filter and its
4548
+ // complement). Each variable of its own (the sort's first, second, third), kept where the values agree.
4549
+ const pool = new Map([...vars, ...thirds].reduce((acc, v) => acc.set(sortsOf(v.sort), [...(acc.get(sortsOf(v.sort)) ?? []), v.name]), new Map()));
4550
+ const homs = [];
4551
+ const fill = (ps, taken) => { const out2 = []; for (const q of ps) {
4552
+ const s2 = sortsOf(q.sort), i = taken.get(s2) ?? 0, name = pool.get(s2)?.[i];
4553
+ if (!name)
4554
+ return undefined;
4555
+ taken.set(s2, i + 1);
4556
+ out2.push({ op: 'var', name });
4557
+ } return out2; };
4558
+ const sumOf = (xs) => xs.reduce((a2, b2) => ({ op: 'add', a: a2, b: b2 }));
4559
+ for (const o of fnsUsed) {
4560
+ if (o.ret !== 'nat')
4561
+ continue;
4562
+ for (const [oi, oq] of o.params.entries()) {
4563
+ if (!(oq.sort instanceof Data))
4564
+ continue;
4565
+ const d = oq.sort, ms = fnsUsed.filter(m => m !== o && m.ret === d && m.params.some(q => q.sort === d));
4566
+ const obs = (x) => ({ op: 'call', fn: o.name, args: fill(o.params, new Map()).map((y, i) => (i === oi ? x : y)) });
4567
+ for (const [mi, m] of ms.entries())
4568
+ for (const m2 of [undefined, ...ms.slice(mi + 1).filter(q => JSON.stringify(q.params.map(r => sortsOf(r.sort))) === JSON.stringify(m.params.map(r => sortsOf(r.sort))))]) {
4569
+ // (the observer's own variables first, the builder's after: count x (take n xs), n the second natural)
4570
+ const taken = new Map();
4571
+ if (!fill(o.params.filter((_, i) => i !== oi), taken))
4572
+ continue;
4573
+ const args = fill(m.params, taken);
4574
+ if (!args)
4575
+ continue;
4576
+ const parts = m.params.flatMap((q, i) => (q.sort === d ? [obs(args[i])] : []));
4577
+ const lhs = m2 ? { op: 'add', a: obs({ op: 'call', fn: m.name, args }), b: obs({ op: 'call', fn: m2.name, args }) } : obs({ op: 'call', fn: m.name, args });
4578
+ const rhs = sumOf(parts), fl = fp(lhs);
4579
+ if (fl === undefined || fl !== fp(rhs))
4580
+ continue;
4581
+ const { t: ct, vs } = canon([lhs, rhs]), [ca, cb] = ct, y = { op: '=', a: ca, b: cb }, text = JSON.stringify(y);
4582
+ if (seen.has(text) || text === lawText || JSON.stringify({ op: '=', a: cb, b: ca }) === lawText)
4583
+ continue;
4584
+ seen.add(text);
4585
+ const h = lawOf(y, vs, `${showX(ca)} = ${showX(cb)}`);
4586
+ distributed.add(h);
4587
+ homs.push(h);
4588
+ }
4589
+ }
4590
+ }
4591
+ out.unshift(...homs);
4434
4592
  // Predicates kept by a function returning a datatype.
4435
4593
  const preds = p.fns.filter(f => f.ret === 'bool' && used.has(f.name)), makers = p.fns.filter(f => f.ret instanceof Data && used.has(f.name));
4436
4594
  const nats = vars.filter(v => v.sort === 'nat').map(v => v.name);
@@ -4979,13 +5137,14 @@ function proveDataCounted(l, opts, until) {
4979
5137
  }
4980
5138
  export function searchIn(l, opts, until, ctx, phase = 'all') {
4981
5139
  const t0 = performance.now(), w0 = work.n;
4982
- const p = ctx?.p ?? programOf([l, ...(Array.isArray(opts.lemmas) ? opts.lemmas : [])]), fs = ctx?.fs ?? factsOf(p);
5140
+ let p = ctx?.p ?? programOf([l, ...(Array.isArray(opts.lemmas) ? opts.lemmas : [])], [], false), fs = ctx?.fs ?? factsOf(p);
4983
5141
  const base = ctx?.base ?? [], lv = ctx?.level ?? 0;
4984
- let out;
5142
+ let out, proofFacts;
5143
+ const contexts = new Map([[p, fs]]);
4985
5144
  const done = (v) => {
4986
5145
  if (dataTrace)
4987
5146
  console.error(`[data] ${l.name}: ${work.n - w0} units of work in ${Math.round(performance.now() - t0)} ms`);
4988
- return { verdict: { law: l.name, ...v, ms: Math.round(performance.now() - t0) }, out };
5147
+ return { verdict: { law: l.name, ...v, ms: Math.round(performance.now() - t0) }, out, facts: proofFacts };
4989
5148
  };
4990
5149
  if (phase !== 'rest') {
4991
5150
  const cex = refute(l, opts.samples ?? 400);
@@ -5008,7 +5167,7 @@ export function searchIn(l, opts, until, ctx, phase = 'all') {
5008
5167
  }
5009
5168
  return lemmas.filter(q => seen.has(nodes.indexOf(nodes.find(n => n.name === q.spec.name)))).map(q => q.law.name);
5010
5169
  };
5011
- const ok = (r, lemmas, prog = p) => (tried += r.tried, r.out ? (out = r.out, done({ proven: true, checked: true, proof: r.verdict, lemmas: used(r.out, lemmas), scheme: r.scheme, tried, program: prog, node: r.out.nodes.indexOf(r.out.spec) })) : undefined);
5170
+ const ok = (r, lemmas, prog = p) => (tried += r.tried, r.out ? (out = r.out, proofFacts = contexts.get(prog), done({ proven: true, checked: true, proof: r.verdict, lemmas: used(r.out, lemmas), scheme: r.scheme, tried, program: prog, node: r.out.nodes.indexOf(r.out.spec) })) : undefined);
5012
5171
  // A law that calls no function (arithmetic alone: an integer's, a remainder's) has nothing to induct on: its cases.
5013
5172
  if (phase !== 'rest' && opts.induction !== false && !JSON.stringify(l.holds).includes('"op":"call"')) {
5014
5173
  const c = ok(proveWith(p, fs, l, base, lv + 1, opts, until, 3000, [1, 2], 'cases'), base);
@@ -5021,6 +5180,18 @@ export function searchIn(l, opts, until, ctx, phase = 'all') {
5021
5180
  return one;
5022
5181
  if (phase === 'first')
5023
5182
  return done({ proven: false, checked: false, lemmas: [], tried, ...stuckOf(first.last) });
5183
+ // Call-count ranks are useful only after the law's light first attempt fails.
5184
+ // Admitting them eagerly made even singleton laws re-prove unused recursive
5185
+ // definitions. Extend the vocabulary here, preserving prior proof fact indices.
5186
+ if (opts.induction !== false && !inTermination.on) {
5187
+ const next = programOf([l, ...(Array.isArray(opts.lemmas) ? opts.lemmas : [])], p.fns);
5188
+ if (next.fns.some(f => !p.fns.includes(f))) {
5189
+ const made = factsOf(next), extra = made.facts.filter(f => !fs.at.has(f.name));
5190
+ fs = { facts: [...fs.facts, ...extra], at: new Map([...fs.at, ...extra.map((f, i) => [f.name, fs.facts.length + i])]), arity: made.arity };
5191
+ p = next;
5192
+ contexts.set(p, fs);
5193
+ }
5194
+ }
5024
5195
  const without = opts.lemmas === false || opts.induction === false;
5025
5196
  if (without)
5026
5197
  return ok(proveWith(p, fs, l, base, lv + 1, opts, until, 20000, [2, 3]), base) ?? (opts.induction === false ? undefined : ok(proveWith(p, fs, l, base, lv + 1, opts, until, 3000, [1, 2], 'cases'), base)) ?? done({ proven: false, checked: false, lemmas: [], tried, ...stuckOf(first?.last) });
@@ -5038,11 +5209,23 @@ export function searchIn(l, opts, until, ctx, phase = 'all') {
5038
5209
  const tc = performance.now(), calc = Array.isArray(opts.lemmas) ? [] : calculated(p, l, 2, 6).filter(c => !lawAgain(l, c));
5039
5210
  if (dataTrace)
5040
5211
  console.error(`[data] ${l.name}: ${calc.length} calculated in ${Math.round(performance.now() - tc)} ms`);
5041
- const cands = Array.isArray(opts.lemmas) ? opts.lemmas : [...calc, ...conjectures(p, l).filter(c => !lawAgain(l, c))];
5212
+ const invented = Array.isArray(opts.lemmas) ? [] : synthesizedLemmas(p).filter(c => !lawAgain(l, c));
5213
+ for (const c of invented)
5214
+ distributed.add(c);
5215
+ const cands = Array.isArray(opts.lemmas) ? opts.lemmas : [...calc, ...invented, ...conjectures(p, l).filter(c => !lawAgain(l, c))];
5042
5216
  if (dataTrace)
5043
5217
  for (const c of calc)
5044
5218
  console.error(`[data] calculated ${c.name.slice(0, 200)}`);
5045
- const p2 = ctx ? p : programOf([l, ...cands]), fs2 = ctx ? fs : factsOf(p2);
5219
+ // A transfer context predates invented observer definitions. Extend its vocabulary, retaining
5220
+ // the old fact indices used by its already-proved nodes; new definitions/congruences append.
5221
+ const p2 = ctx && !invented.length ? p : programOf([l, ...cands], ctx ? p.fns : []);
5222
+ const madeFacts = p2 === p ? fs : factsOf(p2);
5223
+ const extraFacts = ctx ? madeFacts.facts.filter(f => !fs.at.has(f.name)) : [];
5224
+ const fs2 = !ctx ? madeFacts : !extraFacts.length ? fs : {
5225
+ facts: [...fs.facts, ...extraFacts],
5226
+ at: new Map([...fs.at, ...extraFacts.map((f, i) => [f.name, fs.facts.length + i])]), arity: madeFacts.arity,
5227
+ };
5228
+ contexts.set(p2, fs2);
5046
5229
  // Each scheme's goals: the law's, and each companion's (a lemma may be what only a companion's goal reads).
5047
5230
  const goalOf = (law, uses, on, concls, shapes) => {
5048
5231
  const concl = encY(p2, law.holds, new Map()), ihc = uses.map(u => substC(concls[u.member ?? 0] ?? concl, { vars: u.subst, maps: {}, flags: {} }));
@@ -5056,7 +5239,13 @@ export function searchIn(l, opts, until, ctx, phase = 'all') {
5056
5239
  const goalHits = new Set(), others = cands.slice(calc.length);
5057
5240
  for (const g of goals)
5058
5241
  lemmaUsesFor(p2, fs2, others.map((c, i) => ({ law: c, node: i, concl: encY(p2, c.holds, new Map()) })), g.from, g.insts, [], undefined, goalHits);
5059
- const matchesGoal = (c) => goalHits.has(others.indexOf(c));
5242
+ // (an observer distributed over one builder the goal reads, over the others too: count through ++ leaves the counts of
5243
+ // quicksort's two filters, which the filters' complement law then joins)
5244
+ const observer = (c) => { const family = synthesizedObserver(c); if (family)
5245
+ return family; const y = c.holds; let f; walk(y.b, o => { if (!f && o.op === 'call')
5246
+ f = o.fn; }); return f; };
5247
+ const hitObservers = new Set(others.flatMap((c, i) => (goalHits.has(i) && distributed.has(c) ? [observer(c)] : [])));
5248
+ const matchesGoal = (c) => goalHits.has(others.indexOf(c)) || (distributed.has(c) && hitObservers.has(observer(c)));
5060
5249
  // Those the goal matches first, of those the ones of the law's shape (an implication for an implication) first, then
5061
5250
  // the fusions.
5062
5251
  const implication = (y) => y.op === 'or' && y.xs.length === 2 && y.xs[0].op === 'not';
@@ -5073,12 +5262,14 @@ export function searchIn(l, opts, until, ctx, phase = 'all') {
5073
5262
  if (!(fnOf(g).ret instanceof Data))
5074
5263
  observers.add(g);
5075
5264
  const under = (c) => { const fs2 = [...fnsIn(c.holds)], obs = fs2.filter(f => observers.has(f)), makers = fs2.filter(f => fnOf(f).ret instanceof Data); return obs.length > 0 && makers.length > 0 && [...obs, ...makers].some(f => !inLaw.has(f)); };
5076
- const score = (c, hit) => (hit ? 8 : 0) + (under(c) ? 4 : 0) + (implication(c.holds) === implication(l.holds) ? 2 : 0) + (fusion(c.holds) ? 1 : 0);
5265
+ // Targeted observer families include the premises of their guarded equations; keep
5266
+ // those ahead of undirected enumeration so the whole dependency chain gets a turn.
5267
+ const score = (c, hit) => (synthesizedObserver(c) ? 16 : 0) + (hit ? 8 : 0) + (under(c) ? 4 : 0) + (implication(c.holds) === implication(l.holds) ? 2 : 0) + (fusion(c.holds) ? 1 : 0);
5077
5268
  if (dataTrace)
5078
5269
  console.error(`[data] ${l.name}: ${cands.length} conjectures at ${Math.round(clock())} of ${Math.round(until)}${cands.map(c => `\n[data] conjecture ${c.name.slice(0, 160)}`).join('')}`);
5079
5270
  // (the calculated steps first, in their order: each before the one it was calculated from)
5080
5271
  const calcSet = new Set(calc);
5081
- const ranked = [...calc.map(c => ({ c, hit: true })), ...cands.slice(calc.length).map(c => ({ c, hit: matchesGoal(c) })).sort((a, b) => score(b.c, b.hit) - score(a.c, a.hit))];
5272
+ const ranked = [...calc.map(c => ({ c, hit: true })), ...cands.slice(calc.length).map(c => ({ c, hit: matchesGoal(c) })).sort((a, b) => score(b.c, b.hit) - score(a.c, a.hit) || +distributed.has(b.c) - +distributed.has(a.c))];
5082
5273
  if (dataTrace)
5083
5274
  for (const r of ranked)
5084
5275
  console.error(`[data] ranked ${r.hit ? "hit" : " "} ${r.c.name.slice(0, 150)}`);
@@ -5138,8 +5329,16 @@ export function searchIn(l, opts, until, ctx, phase = 'all') {
5138
5329
  }
5139
5330
  // (as before the passes: again after a lemma the goal reads, or one of the law's shape, an implication for one; a
5140
5331
  // calculated step's after the last of them, whose proofs read each other)
5332
+ // (and one of an observer distributed over a builder before the next of them: quicksort's count needs both ++'s and
5333
+ // the filters')
5141
5334
  if (calcSet.has(c) && !retry.length && i < queue.length && calcSet.has(queue[i].c))
5142
5335
  continue;
5336
+ if (distributed.has(c) && i < queue.length && distributed.has(queue[i].c)) {
5337
+ for (const q of retry)
5338
+ retried.delete(q);
5339
+ retry.length = 0;
5340
+ continue;
5341
+ }
5143
5342
  if (which === 'hits' || implication(c.holds) === implication(l.holds)) {
5144
5343
  since = 0;
5145
5344
  const r2 = again('first');
@@ -150,7 +150,9 @@ function powers(e) {
150
150
  case 'min':
151
151
  case 'max':
152
152
  case 'if':
153
- case 'get': return undefined;
153
+ case 'get':
154
+ case 'tup':
155
+ case 'proj': return undefined;
154
156
  }
155
157
  }
156
158
  // The law a goal is of (the kernel names each goal after its law: '<law> @step').
@@ -0,0 +1,19 @@
1
+ import type { Extraction } from './extract.js';
2
+ import { type LawOpts } from './laws.js';
3
+ export type Draft = {
4
+ method?: string;
5
+ name: string;
6
+ expr: string;
7
+ answers: string;
8
+ };
9
+ export declare function draftPrompt(x: Extraction, clause: string, cite: string): string;
10
+ export declare function parseDraft(text: string): Draft[];
11
+ export declare function vetDrafts(x: Extraction, ds: Draft[], opts?: LawOpts): {
12
+ kept: Draft[];
13
+ refused: {
14
+ d: Draft;
15
+ why: string;
16
+ }[];
17
+ };
18
+ export declare const draftComments: (c: string, d: Draft, cite: string, by: string) => string[];
19
+ export declare const reviewOf: (text: string) => "reviewed" | "unreviewed" | "unmarked";
@@ -0,0 +1,53 @@
1
+ import { LawError, buildLaw, buildTwoRuns, isTwoRuns, namesWithClock } from "./laws.js";
2
+ // The question: the clause, the code's names and what a law can say.
3
+ export function draftPrompt(x, clause, cite) {
4
+ const role = { input: 'request', param: 'made with', answer: 'answered call', result: 'result', failed: 'failed', method: 'method', clock: 'clock', state: 'state', const: 'constant' };
5
+ const names = namesWithClock(x).filter(n => n.role !== 'const').map(n => ` ${n.role === 'input' && n.method ? `${n.method}(${n.code})` : n.code} ${role[n.role]}${n.map ? ` (fields: ${n.map.fields.join(', ')})` : ''}`);
6
+ return `You draft machine-checked laws for code that must meet a regulation. A person reviews every law you draft; a prover then checks it against the code.
7
+
8
+ The clause (${cite}):
9
+ ${clause.trim()}
10
+
11
+ The code (${x.model?.name ?? 'its rule'}) has these names (the code's name, then its role: state is a field, request an argument of a method, clock the request's time):
12
+ ${names.join('\n')}
13
+
14
+ A law is one expression over those names: comparisons (< <= > >= == !=), + - and * by a constant, and/or/not/implies, a map at a key (m[k].field, k in m), forall k in m: ..., a choice by its value (status == "open"). On a method (method set below) it is a law of one call of it: fields are the state after the call, old(x) before, the method's arguments by name, now the request's time. Durations: now - t < 30 days, 72 hours, now - t <= 10 business days. The code acts only when it is called, so a deadline is a law of the call that acts: what that call leaves meets the deadline (on the method that grants a request: granted implies now - received <= 30 days; or a call past the deadline doesn't grant). About two runs: "<argument> never reaches <field>, <field>" (that argument never changes those fields), "isolated by <argument>" (one caller's calls never change what another sees).
15
+
16
+ State what the clause requires, not what the code does: a law the code breaks is what the review is for. Draft only laws whose every name is in the list; leave out what the clause asks of something this code doesn't hold. Answer with JSON only, an array (empty if nothing applies):
17
+ [{"method": "<the method it is about, or null for a law of every state>", "name": "<a short sentence>", "expr": "<the expression>", "answers": "<the words of the clause it answers>"}]`;
18
+ }
19
+ // The drafter's answer: the first JSON array in it.
20
+ export function parseDraft(text) {
21
+ const at = text.indexOf('['), end = text.lastIndexOf(']');
22
+ if (at < 0 || end < at)
23
+ throw new Error('the answer holds no JSON array');
24
+ const xs = JSON.parse(text.slice(at, end + 1));
25
+ const str = (v) => (typeof v === 'string' ? v : v === undefined || v === null ? '' : JSON.stringify(v));
26
+ return xs.map(o => ({ ...(typeof o.method === 'string' && o.method ? { method: o.method } : {}), name: str(o.name).replace(/:/g, ' -').trim().replace(/[.\s]+$/, ''), expr: str(o.expr).trim(), answers: str(o.answers).trim() }));
27
+ }
28
+ // Each draft read over the code's names as `check` would read it: kept, or refused with why.
29
+ export function vetDrafts(x, ds, opts = {}) {
30
+ const kept = [], refused = [];
31
+ for (const d of ds) {
32
+ if (!d.name || !d.expr) {
33
+ refused.push({ d, why: 'no name or no expression' });
34
+ continue;
35
+ }
36
+ try {
37
+ const l = { name: d.name, expr: d.expr, ...(d.method ? { method: d.method } : {}) };
38
+ if (isTwoRuns(d.expr))
39
+ buildTwoRuns(x, l);
40
+ else
41
+ buildLaw(x, l, opts);
42
+ kept.push(d);
43
+ }
44
+ catch (e) {
45
+ refused.push({ d, why: e instanceof LawError ? e.message : String(e.message) });
46
+ }
47
+ }
48
+ return { kept, refused };
49
+ }
50
+ // The comments to paste: each law with its citation, marked unreviewed.
51
+ export const draftComments = (c, d, cite, by) => [`${c} gdp: law ${d.name}: ${d.expr}`, `${c} gdp: cite ${d.name}: ${cite}: "${d.answers.replace(/\s+/g, ' ')}" [unreviewed: drafted by ${by}]`];
52
+ // A citation's review: signed off by a person, marked unreviewed, or neither (written by hand, its review the writer's).
53
+ export const reviewOf = (text) => (/\[\s*reviewed-by:\s*[^\]]+\]/i.test(text) ? 'reviewed' : /\[\s*unreviewed\b/i.test(text) ? 'unreviewed' : 'unmarked');
@@ -4,6 +4,7 @@ import { type Report } from '../kernel/prove.js';
4
4
  import { findRing } from './live.js';
5
5
  export type TermLike = Term | number;
6
6
  export declare const termOf: (t: TermLike) => E;
7
+ export type Rounding = 'halfEven' | 'halfUp' | 'halfDown' | 'halfAway';
7
8
  export declare class Term {
8
9
  readonly e: E;
9
10
  readonly val?: number | undefined;
@@ -14,6 +15,10 @@ export declare class Term {
14
15
  mul(b: TermLike): Term;
15
16
  modBy(k: number): Term;
16
17
  divBy(k: number): Term;
18
+ floorTo(k: number): Term;
19
+ ceilTo(k: number): Term;
20
+ roundTo(k: number, mode?: Rounding): Term;
21
+ onTick(k: number): Cond;
17
22
  lt(b: TermLike): Cond;
18
23
  atMost(b: TermLike): Cond;
19
24
  gt(b: TermLike): Cond;
@@ -101,6 +106,10 @@ export declare class Int {
101
106
  get isNegative(): Cond;
102
107
  modBy(k: number): Term;
103
108
  divBy(k: number): Int;
109
+ floorTo(k: number): Int;
110
+ ceilTo(k: number): Int;
111
+ roundTo(k: number, mode?: Rounding): Int;
112
+ onTick(k: number): Cond;
104
113
  get abs(): Term;
105
114
  get clamped(): Term;
106
115
  }
@@ -124,6 +133,11 @@ export declare class Decimal {
124
133
  min(b: DecimalLike): Decimal;
125
134
  max(b: DecimalLike): Decimal;
126
135
  get isNegative(): Cond;
136
+ private tick;
137
+ floorTo(t: number): Decimal;
138
+ ceilTo(t: number): Decimal;
139
+ roundTo(t: number, mode?: Rounding): Decimal;
140
+ onTick(t: number): Cond;
127
141
  }
128
142
  export declare const nat: Kind<Term>;
129
143
  export declare const upTo: (maxValue: number) => Kind<Term>;
@@ -311,6 +325,18 @@ export declare class MapRef {
311
325
  sizeBelow(n: number): Term;
312
326
  sum(of?: (cell: Term) => TermLike): Term;
313
327
  }
328
+ export declare class RelRef {
329
+ readonly name: string;
330
+ readonly sorts: readonly string[];
331
+ constructor(name: string, sorts: readonly string[]);
332
+ private key;
333
+ at(...xs: TermLike[]): Term;
334
+ has(...xs: TermLike[]): Cond;
335
+ each(f: (...xs: Term[]) => Cond): MapWrite;
336
+ union(f: (...xs: Term[]) => Cond): MapWrite;
337
+ add(xs: TermLike[], c?: Cond): MapWrite;
338
+ remove(xs: TermLike[], c?: Cond): MapWrite;
339
+ }
314
340
  export type ListOp = {
315
341
  readonly when: Cond;
316
342
  readonly at: (k: Term) => TermLike;
@@ -523,6 +549,8 @@ type Spec = {
523
549
  inputs: [string, Kind<unknown>][];
524
550
  state: [string, number | ((p: never) => TermLike)][];
525
551
  maps: [string, number][];
552
+ rels?: [string, string[]][];
553
+ sorts?: string[];
526
554
  lists?: string[];
527
555
  cells?: [string, Kind<unknown>][];
528
556
  items?: [string, Kind<unknown>][];
@@ -531,7 +559,8 @@ type Spec = {
531
559
  carried?: string[];
532
560
  counts?: [string, (env: never) => {
533
561
  below: TermLike;
534
- body: (x: Term, k: Term) => Cond | TermLike;
562
+ body: (x: Term, k: Term, y: Term) => Cond | TermLike;
563
+ base?: number;
535
564
  }][];
536
565
  seqs?: string[];
537
566
  seqTables?: string[];
@@ -576,6 +605,11 @@ export declare class Rule<P extends Obj = {}, I extends Obj = {}, S extends Obj
576
605
  maps<T extends Record<string, number | Init<unknown>>>(init: T): Rule<P, I, S, M & {
577
606
  [k in keyof T]: T[k] extends Init<infer V> ? CellsRef<V> : MapRef;
578
607
  }, F, R, Su, Q>;
608
+ sorts(...names: string[]): Rule<P, I, S, M, F, R, Su, Q>;
609
+ relations<T extends Record<string, readonly string[]>>(rels: T): Rule<P, I, S, M & {
610
+ [k in keyof T]: RelRef;
611
+ }, F, R, Su, Q>;
612
+ relations(f: (env: P & I & Su & Q) => Relation[]): Rule<P, I, S, M, F, R, Su, Q>;
579
613
  ints<T extends Record<string, number | ((p: P) => IntLike)>>(init: T): Rule<P, I, S & {
580
614
  [k in keyof T]: Int;
581
615
  }, M, F, R, Su, Q>;
@@ -608,7 +642,8 @@ export declare class Rule<P extends Obj = {}, I extends Obj = {}, S extends Obj
608
642
  }, S, M, F, R, Su, Q>;
609
643
  counts<T extends Record<string, (env: P & I & S & M) => {
610
644
  below: TermLike;
611
- body: (x: Term, k: Term) => Cond | TermLike;
645
+ body: (x: Term, k: Term, y: Term) => Cond | TermLike;
646
+ base?: number;
612
647
  }>>(cs: T): Rule<P, I & {
613
648
  [k in keyof T]: MapRef;
614
649
  }, S, M, F, R, Su, Q>;
@@ -638,7 +673,6 @@ export declare class Rule<P extends Obj = {}, I extends Obj = {}, S extends Obj
638
673
  [k in keyof T]: Maybe<Term>;
639
674
  }>;
640
675
  keep(f: (env: P & I & S & M & F & Su & Q) => Cond): Rule<P, I, S, M, F, R, Su, Q>;
641
- relations(f: (env: P & I & Su & Q) => Relation[]): Rule<P, I, S, M, F, R, Su, Q>;
642
676
  prune(order: keyof R & string, after: (p: P) => TermLike): Rule<P, I, S, M, F, R, Su, Q>;
643
677
  law(name: string, f: (env: P & S & M & Su) => Cond | Forall): Law;
644
678
  private lawOf;