gdp-wired 0.44.0 → 0.46.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 (133) hide show
  1. package/README.md +58 -7
  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 +445 -38
  7. package/dist/core/calendar.d.ts +29 -0
  8. package/dist/core/calendar.js +82 -0
  9. package/dist/core/check.js +3 -2
  10. package/dist/core/cli.d.ts +4 -0
  11. package/dist/core/cli.js +335 -39
  12. package/dist/core/compose.js +3 -1
  13. package/dist/core/counts.d.ts +5 -2
  14. package/dist/core/counts.js +335 -88
  15. package/dist/core/cycles.js +8 -1
  16. package/dist/core/cyclic.d.ts +1 -0
  17. package/dist/core/cyclic.js +13 -7
  18. package/dist/core/data-synth.d.ts +3 -0
  19. package/dist/core/data-synth.js +252 -0
  20. package/dist/core/data.d.ts +8 -2
  21. package/dist/core/data.js +1113 -172
  22. package/dist/core/discover.js +3 -1
  23. package/dist/core/draft.d.ts +19 -0
  24. package/dist/core/draft.js +53 -0
  25. package/dist/core/dsl.d.ts +39 -3
  26. package/dist/core/dsl.js +250 -31
  27. package/dist/core/effect-prims.js +2 -2
  28. package/dist/core/effect.d.ts +1 -4
  29. package/dist/core/effect.js +1 -15
  30. package/dist/core/ex/reader.exs +17 -1
  31. package/dist/core/exists.d.ts +16 -1
  32. package/dist/core/exists.js +447 -50
  33. package/dist/core/extract-c.d.ts +2 -0
  34. package/dist/core/extract-c.js +185 -31
  35. package/dist/core/extract-check.d.ts +7 -0
  36. package/dist/core/extract-check.js +115 -3
  37. package/dist/core/extract-ex.js +3 -3
  38. package/dist/core/extract-go-check.d.ts +1 -1
  39. package/dist/core/extract-go-check.js +21 -13
  40. package/dist/core/extract-go.d.ts +1 -0
  41. package/dist/core/extract-go.js +58 -9
  42. package/dist/core/extract-ir.d.ts +1 -0
  43. package/dist/core/extract-ir.js +15 -0
  44. package/dist/core/extract-jvm.d.ts +1 -1
  45. package/dist/core/extract-jvm.js +65 -14
  46. package/dist/core/extract-orm.d.ts +12 -0
  47. package/dist/core/extract-orm.js +244 -0
  48. package/dist/core/extract-print.js +23 -1
  49. package/dist/core/extract-py.d.ts +1 -0
  50. package/dist/core/extract-py.js +4 -4
  51. package/dist/core/extract-rb.js +3 -3
  52. package/dist/core/extract-read.d.ts +25 -0
  53. package/dist/core/extract-read.js +60 -5
  54. package/dist/core/extract-rs.js +22 -20
  55. package/dist/core/extract-shapes.js +22 -0
  56. package/dist/core/extract-sol.d.ts +10 -1
  57. package/dist/core/extract-sol.js +89 -30
  58. package/dist/core/extract-step.d.ts +201 -4
  59. package/dist/core/extract-step.js +1514 -111
  60. package/dist/core/extract-swift.js +24 -13
  61. package/dist/core/extract.d.ts +9 -0
  62. package/dist/core/extract.js +88 -7
  63. package/dist/core/fiber-run.d.ts +5 -0
  64. package/dist/core/fiber-run.js +18 -0
  65. package/dist/core/fresh.d.ts +2 -2
  66. package/dist/core/fresh.js +7 -3
  67. package/dist/core/go/reader.go +7 -1
  68. package/dist/core/infer.d.ts +4 -1
  69. package/dist/core/infer.js +1020 -246
  70. package/dist/core/jvm/JavaReader.java +33 -8
  71. package/dist/core/jvm/Jvm.java +20 -1
  72. package/dist/core/jvm/KtReader.java +59 -6
  73. package/dist/core/laws.d.ts +10 -3
  74. package/dist/core/laws.js +193 -14
  75. package/dist/core/machine.d.ts +16 -3
  76. package/dist/core/machine.js +212 -28
  77. package/dist/core/nonterm.js +14 -1
  78. package/dist/core/orm/harness.js +61 -0
  79. package/dist/core/orm-fixtures/schema.prisma +5 -0
  80. package/dist/core/py/harness.py +260 -21
  81. package/dist/core/py/reader.py +278 -39
  82. package/dist/core/rb/reader.rb +52 -5
  83. package/dist/core/reader-fixtures/README.md +28 -0
  84. package/dist/core/reader-fixtures/c-693042.cpp +8 -0
  85. package/dist/core/reader-fixtures/go-685506.go +14 -0
  86. package/dist/core/reader-fixtures/jvm-724362.kt +8 -0
  87. package/dist/core/reader-fixtures/jvm-737430.kt +7 -0
  88. package/dist/core/reader-fixtures/jvm-765282.kt +3 -0
  89. package/dist/core/reader-fixtures/swift-735726.swift +15 -0
  90. package/dist/core/reader-fixtures/swift-735990.swift +15 -0
  91. package/dist/core/reader-fixtures/swift-739158.swift +4 -0
  92. package/dist/core/reader-fixtures/swift-744834.swift +15 -0
  93. package/dist/core/reader-fixtures/swift-746946.swift +31 -0
  94. package/dist/core/reader-fixtures/typescript-673062.ts.txt +2 -0
  95. package/dist/core/relation.d.ts +1 -1
  96. package/dist/core/relation.js +29 -2
  97. package/dist/core/relational.js +4 -2
  98. package/dist/core/rs/src/main.rs +18 -2
  99. package/dist/core/sample-cache.d.ts +8 -0
  100. package/dist/core/sample-cache.js +46 -0
  101. package/dist/core/security.d.ts +38 -0
  102. package/dist/core/security.js +88 -0
  103. package/dist/core/sol/harness.py +63 -7
  104. package/dist/core/sol-concrete.d.ts +23 -0
  105. package/dist/core/sol-concrete.js +195 -0
  106. package/dist/core/solver.js +8 -5
  107. package/dist/core/swift/Sources/gdp-swiftreader/main.swift +50 -7
  108. package/dist/core/system.d.ts +62 -1
  109. package/dist/core/system.js +263 -4
  110. package/dist/core/transfer.js +39 -9
  111. package/dist/core/translate.js +39 -10
  112. package/dist/core/watch.js +51 -6
  113. package/dist/interchange/check.js +10 -10
  114. package/dist/interchange/format.d.ts +4 -0
  115. package/dist/interchange/format.js +24 -6
  116. package/dist/kernel/cdcl.d.ts +5 -0
  117. package/dist/kernel/cdcl.js +88 -10
  118. package/dist/kernel/epr.js +141 -29
  119. package/dist/kernel/kernel.d.ts +31 -1
  120. package/dist/kernel/kernel.js +391 -101
  121. package/dist/kernel/model-sequence.d.ts +3 -0
  122. package/dist/kernel/model-sequence.js +34 -0
  123. package/dist/kernel/prove.d.ts +30 -1
  124. package/dist/kernel/prove.js +481 -71
  125. package/dist/kernel/reader.d.ts +3 -0
  126. package/dist/kernel/reader.js +101 -14
  127. package/dist/kernel/share.d.ts +1 -0
  128. package/dist/kernel/share.js +27 -0
  129. package/dist/lean-kernel/emit.d.ts +9 -3
  130. package/dist/lean-kernel/emit.js +200 -66
  131. package/dist/lean-kernel/lean-terms.js +5 -0
  132. package/dist/lean-kernel/library.js +10 -10
  133. package/package.json +7 -2
@@ -1,4 +1,4 @@
1
- import { argsKey, atMost as le, compileFunction, evalC as evalMC, evalE as evalME, fnValue, get, interpret, minus as sub, n as k, pairedArgs, plus as add, same as eqC, seeded, walk, x as v } from "./machine.js";
1
+ import { argsKey, atMost as le, compileFunction, cpair, cunpair, evalC as evalMC, evalE as evalME, fnValue, get, interpret, minus as sub, n as k, pairedArgs, plus as add, same as eqC, seeded, tupleParts, walk, x as v } from "./machine.js";
2
2
  import { check, livenessHelpful, livenessParts, loopLiveness, loopMachine, loopObligations, strongly, substC, substE } from "../kernel/kernel.js";
3
3
  import { checkCyclic, factsAvoid, lexLt } from "../kernel/cyclic.js";
4
4
  import { and, proveCyclic, vars as vs } from "./cyclic.js";
@@ -42,6 +42,8 @@ export const showE = (e) => {
42
42
  const as = pairedArgs(e.key, 2), as3 = as && pairedArgs(e.key, 3);
43
43
  return `${e.map}(${(as3 ?? as ?? [e.key]).map(showE).join(', ')})`;
44
44
  }
45
+ case 'tup': return `⟨${tupleParts(e).map(showE).join(', ')}⟩`;
46
+ case 'proj': return `${e.k === 0 ? 'fst' : 'snd'}(${showE(e.a)})`;
45
47
  }
46
48
  };
47
49
  export const showC = (c) => {
@@ -154,6 +156,11 @@ function ev(cx, e, env, rec) {
154
156
  case 'min': return two(e.a, e.b, Math.min);
155
157
  case 'max': return two(e.a, e.b, Math.max);
156
158
  case 'prod': return two(e.a, e.b, (x, y) => x * y);
159
+ case 'tup': return two(e.a, e.b, cpair);
160
+ case 'proj': {
161
+ const x = ev(cx, e.a, env, rec);
162
+ return x === undefined ? undefined : cunpair(x)[e.k];
163
+ }
157
164
  case 'mul': {
158
165
  const x = ev(cx, e.a, env, rec);
159
166
  return x === undefined ? undefined : e.k * x;
@@ -10,6 +10,7 @@ export type NodeSpec = Omit<CNode, 'uses' | 'main'> & {
10
10
  slice?: boolean;
11
11
  main?: Tree;
12
12
  carry?: boolean | 'sliced';
13
+ within?: number;
13
14
  };
14
15
  export type CyclicVerdict = {
15
16
  proven: true;
@@ -56,7 +56,7 @@
56
56
  import { atMost as le, get, n as k, plus as add, same as eq, walk, x as v } from "./machine.js";
57
57
  import { assumed, boundOf, foldObligations, livenessParts, loopLiveness, loopMachine, loopObligations, obligations, stepLawObligations, substC, substE, witnessesOf } from "../kernel/kernel.js";
58
58
  import { baseHyps, descentGoal, instHyps, mainGoal, premiseGoal, refuseCyclic } from "../kernel/cyclic.js";
59
- import { cellProducts, clock, counted, fullRate, grow, profile, usedHyps, widen, withDeadline, withinDeadline } from "../kernel/prove.js";
59
+ import { cellProducts, clock, counted, fullRate, grow, late, profile, usedHyps, widen, withDeadline, withinDeadline } from "../kernel/prove.js";
60
60
  import { carry, decide, readsFirst, renamer, translate, tstats } from "./translate.js";
61
61
  import { env } from "./solver.js";
62
62
  const less1 = (a) => ({ op: 'sub', a, b: k(1) });
@@ -287,7 +287,7 @@ export function proveCyclic(facts, specs, order0, grownBefore = searched, st = t
287
287
  };
288
288
  // A node's goal grown; then the node keeps only the facts and uses its tree reads (the fewer, the fewer hypotheses its
289
289
  // goal has for the kernel to read at every leaf, and the fewer uses to prove below); then each use's goals.
290
- const attempt = ({ opaque, variants: _v, weak: _w, slice: sl, main: given0, carry: made, ...n0 }) => {
290
+ const attempt = ({ opaque, variants: _v, weak: _w, slice: sl, main: given0, carry: made, within: _in, ...n0 }) => {
291
291
  hidden = opaque ?? [];
292
292
  sliceNow = !!sl;
293
293
  // A goal's own hypotheses: the node's, and those after its facts and uses.
@@ -377,13 +377,16 @@ export function proveCyclic(facts, specs, order0, grownBefore = searched, st = t
377
377
  return main3 && !('proven' in uses3) ? { ...n3, uses: uses3, main: main3 } : uses;
378
378
  };
379
379
  for (const i of order) {
380
+ if (late(withinDeadline(Infinity)))
381
+ return { proven: false, checked: false, node: specs[i].name, goal: specs[i].name, stuck: 'unknown' };
380
382
  let failed;
381
383
  for (const [j, spec] of [specs[i], ...(specs[i].variants ?? [])].entries()) {
382
384
  // (a variant after the first within a few seconds a goal, one second once a node is refuted: a variant the first
383
385
  // wasn't proven by is seldom needed, and seldom proves a node where another is refuted)
384
386
  // (a translated node's goals, its uses' among them, within four: past that its translation isn't kept, the usual
385
387
  // trees are)
386
- later = j ? (refuted ? 1_000 : 3_000) : spec.main || spec.carry ? 4_000 : undefined;
388
+ // (`within`: the spec's own, each of its goals: core/data.ts's case nodes, their leaner instances first)
389
+ later = spec.within ?? (j ? (refuted ? 1_000 : 3_000) : spec.main || spec.carry ? 4_000 : undefined);
387
390
  if (spec.uses.some(u => weak.has(u.node)))
388
391
  continue;
389
392
  const r = attempt(spec);
@@ -1386,6 +1389,9 @@ export const translateMs = (usualMs = 0, floor = certMs()) => Math.max(floor, 4
1386
1389
  export const stepCertFloor = () => Number(env.GDP_CERT_STEP_MS ?? 250);
1387
1390
  function cyclicOf(translated, run, st, until, usualMs, floor) {
1388
1391
  let how = 'searched', why;
1392
+ const expired = () => late(withinDeadline(until ?? Infinity));
1393
+ if (expired())
1394
+ return { out: none(), how, why: 'the caller deadline passed' };
1389
1395
  if (translated) {
1390
1396
  const r = withDeadline(clock() + translateMs(usualMs, floor), () => translated(st));
1391
1397
  if (r.verdict?.proven && r.verdict.checked)
@@ -1393,7 +1399,7 @@ function cyclicOf(translated, run, st, until, usualMs, floor) {
1393
1399
  how = 'fallback';
1394
1400
  why = r.why ?? (r.verdict && !r.verdict.proven ? `${r.verdict.goal}: ${r.verdict.stuck}` : r.verdict?.why);
1395
1401
  }
1396
- return { out: until === undefined ? run() : withDeadline(until, run), how, ...(why ? { why } : {}) };
1402
+ return { out: expired() ? none() : until === undefined ? run() : withDeadline(until, run), how, ...(why ? { why } : {}) };
1397
1403
  }
1398
1404
  // GDP_CYCLIC_PROF=1: where the proof's time went, by goal kind, in its line.
1399
1405
  const profLine = () => (profOn() ? { prof: Object.fromEntries(Object.entries(cyclicProf).map(([key, p]) => [key, Object.fromEntries(Object.entries(p).map(([f, x]) => [f, Math.round(x)]))])) } : {});
@@ -1439,12 +1445,12 @@ export const uncovered = (kind, name, why) => cycLog({ kind, name, uncovered: tr
1439
1445
  export function certCyclic(kind, name, translated, run0, usualMs, floor) {
1440
1446
  for (const key of Object.keys(cyclicProf))
1441
1447
  delete cyclicProf[key];
1442
- const st = tstats(), t0 = performance.now(), until = clock() + certMs();
1448
+ const st = tstats(), t0 = performance.now(), until = withinDeadline(clock() + certMs());
1443
1449
  const { out, how, why } = cyclicOf(translated, (translated && !certSearch() ? undefined : run0) ?? none, st, until, usualMs, floor);
1444
1450
  const checked = out.proven && out.checked;
1445
1451
  cycLog({ kind, name, cert: true, usual: true, cyclic: checked, ms: Math.round(performance.now() - t0), ...(usualMs === undefined ? {} : { usualMs: Math.round(usualMs) }), route: how, ...(how !== 'searched' ? st : {}), ...(why ? { fellBack: why } : {}), ...profLine() });
1446
- const late = clock() > until ? ` within ${certMs()} ms` : '';
1447
- return { checked, ...(out.proven ? { proof: out.proof } : {}), why: checked ? '' : `no cyclic proof found${late}${why ? ` (not translated: ${why})` : ''}` };
1452
+ const expired = late(until) ? ' within the caller or certificate budget' : '';
1453
+ return { checked, ...(out.proven ? { proof: out.proof } : {}), why: checked ? '' : `no cyclic proof found${expired}${why ? ` (not translated: ${why})` : ''}` };
1448
1454
  }
1449
1455
  // The step laws' searched nodes after the laws' (stepLawNodes over the sk machine), with the flags' closing facts read
1450
1456
  // where each node reads the run on a machine with flags that hold at every key: what GDP_CERT=cyclic's search and the
@@ -0,0 +1,3 @@
1
+ import { type DataLaw, type Program } from './data.js';
2
+ export declare const synthesizedObserver: (l: DataLaw) => string | undefined;
3
+ export declare function synthesizedLemmas(p: Program): DataLaw[];
@@ -0,0 +1,252 @@
1
+ // Search only: invented folds are ordinary definitions; these equations are conjectures, never facts.
2
+ // The caller proves every one with the cyclic kernel before using it, and exports the folds with its proof.
3
+ import { Data, define, evalY, fnNamed, reduceX, samples, showY, wrap } from "./data.js";
4
+ const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
5
+ const variable = (name) => ({ op: 'var', name });
6
+ const walk = (t, f) => {
7
+ if (!t || typeof t !== 'object')
8
+ return;
9
+ if (Array.isArray(t)) {
10
+ t.forEach(x => walk(x, f));
11
+ return;
12
+ }
13
+ f(t);
14
+ Object.values(t).forEach(x => walk(x, f));
15
+ };
16
+ const replace = (t, f) => {
17
+ const go = (x) => {
18
+ if (!x || typeof x !== 'object')
19
+ return x;
20
+ if (Array.isArray(x))
21
+ return x.map(go);
22
+ const changed = f(x);
23
+ return changed ?? Object.fromEntries(Object.entries(x).map(([k, v]) => [k, go(v)]));
24
+ };
25
+ return go(t);
26
+ };
27
+ const substitute = (t, sub) => replace(t, x => x.op === 'var' ? sub.get(x.name) : undefined);
28
+ const free = (t) => { const out = new Set(); walk(t, x => { if (x.op === 'var')
29
+ out.add(x.name); }); return out; };
30
+ const fieldSort = (p, s) => typeof s === 'string' ? s : p.datas.find(d => d.name === s.data);
31
+ const zero = (f) => f.ret === 'int' ? { op: 'int', value: 0 } : { op: 'nat', value: 0 };
32
+ const plus = (f, a, b) => a.op === zero(f).op && 'value' in a && a.value === 0 ? b : b.op === zero(f).op && 'value' in b && b.value === 0 ? a : { op: f.ret === 'int' ? 'iadd' : 'add', a, b };
33
+ const sum = (f, xs) => xs.reduce((a, b) => plus(f, a, b), zero(f));
34
+ // Recognise an additive list algebra, including a guard around the recursive call (count), not just length.
35
+ // No equation is assumed from this recognition: a wrong guess can only leave its subsequent lemma unproved.
36
+ function algebra(p, f) {
37
+ if ((f.ret !== 'nat' && f.ret !== 'int') || f.params.some(q => q.sort === 'bool'))
38
+ return;
39
+ const body = f.body();
40
+ if (body.op !== 'match' || body.of.op !== 'var')
41
+ return;
42
+ const at = f.params.findIndex(q => `${f.name}.${q.name}` === body.of.name);
43
+ const d = f.params[at]?.sort;
44
+ if (!(d instanceof Data) || d.abstract || d.ctors.length !== 2)
45
+ return;
46
+ const ci = d.ctors.findIndex(c => c.fields.length === 2 && c.fields.filter(q => typeof q.sort === 'object' && q.sort.data === d.name).length === 1);
47
+ if (ci < 0)
48
+ return;
49
+ const ctor = d.ctors[ci], branch = body.cases[ci], ri = ctor.fields.findIndex(q => typeof q.sort === 'object' && q.sort.data === d.name), vi = 1 - ri;
50
+ if (!body.cases.every((c, i) => i === ci || same(reduceX(c.body), zero(f))))
51
+ return;
52
+ const recursive = { op: 'call', fn: f.name, args: f.params.map((q, i) => variable(i === at ? branch.binds[ri] : `${f.name}.${q.name}`)) };
53
+ const weight = (x) => {
54
+ if (same(x, recursive))
55
+ return { n: 1, x: zero(f) };
56
+ let calls = false;
57
+ walk(x, t => { if (t.op === 'call' && t.fn === f.name)
58
+ calls = true; });
59
+ if (!calls)
60
+ return { n: 0, x };
61
+ if (x.op === 'add' || x.op === 'iadd') {
62
+ const a = weight(x.a), b = weight(x.b);
63
+ return a && b ? { n: a.n + b.n, x: plus(f, a.x, b.x) } : undefined;
64
+ }
65
+ if (x.op === 'if') {
66
+ let inGuard = false;
67
+ walk(x.c, t => { if (t.op === 'call' && t.fn === f.name)
68
+ inGuard = true; });
69
+ if (inGuard)
70
+ return;
71
+ const a = weight(x.then), b = weight(x.else);
72
+ return a && b && a.n === b.n ? { n: a.n, x: { ...x, then: a.x, else: b.x } } : undefined;
73
+ }
74
+ return;
75
+ };
76
+ const w = weight(branch.body);
77
+ if (!w || w.n !== 1)
78
+ return;
79
+ const allowed = new Set([branch.binds[vi], ...f.params.filter((_, i) => i !== at).map(q => `${f.name}.${q.name}`)]);
80
+ if ([...free(w.x)].some(v => !allowed.has(v)))
81
+ return;
82
+ return { observer: f, data: d, at, payload: fieldSort(p, ctor.fields[vi].sort), item: branch.binds[vi], weight: w.x };
83
+ }
84
+ let serial = 0;
85
+ const lifted = new WeakMap();
86
+ // Lift the same per-element weight over other container shapes, including a list of containers and mutual groups.
87
+ function lift(p, a) {
88
+ const f = a.observer, out = new Map([[a.data, f]]);
89
+ const cache = lifted.get(f) ?? new Map();
90
+ lifted.set(f, cache);
91
+ const contains = new Set([a.data]);
92
+ for (let changed = true; changed;) {
93
+ changed = false;
94
+ for (const d of p.datas)
95
+ if (!d.abstract && d !== a.payload && !contains.has(d) && d.ctors.some(c => c.fields.some(q => { const s = fieldSort(p, q.sort); return s === a.payload || s instanceof Data && contains.has(s); }))) {
96
+ contains.add(d);
97
+ changed = true;
98
+ }
99
+ }
100
+ for (const d of contains)
101
+ if (d !== a.data) {
102
+ const old = cache.get(d);
103
+ if (old && fnNamed(old.name) === old) {
104
+ out.set(d, old);
105
+ continue;
106
+ }
107
+ let name;
108
+ do {
109
+ name = `observer${++serial}`;
110
+ } while (fnNamed(name));
111
+ const params = f.params.map((q, i) => ({ name: `a${i}`, sort: i === a.at ? d : q.sort }));
112
+ const made = define(name, Object.fromEntries(params.map(q => [q.name, q.sort])), f.ret, args => {
113
+ const input = args[`a${a.at}`];
114
+ const sub = new Map(f.params.map((q, i) => [`${f.name}.${q.name}`, args[`a${i}`].x]));
115
+ const body = { op: 'match', data: d.name, of: input.x, cases: d.ctors.map(c => {
116
+ const binds = c.fields.map((_, i) => `${name}field${i}`);
117
+ const terms = c.fields.flatMap((q, i) => {
118
+ const s = fieldSort(p, q.sort), v = variable(binds[i]);
119
+ if (s === a.payload)
120
+ return [substitute(a.weight, new Map([...sub, [a.item, v]]))];
121
+ const obs = s instanceof Data ? out.get(s) : undefined;
122
+ return obs ? [{ op: 'call', fn: obs.name, args: params.map((_, j) => j === a.at ? v : args[`a${j}`].x) }] : [];
123
+ });
124
+ return { binds, body: sum(f, terms) };
125
+ }) };
126
+ return wrap(f.ret, body);
127
+ }).fn;
128
+ out.set(d, made);
129
+ cache.set(d, made);
130
+ }
131
+ return out;
132
+ }
133
+ // Values filter conjectures, never certify them. Guarded candidates need witnesses on both sides of the guard.
134
+ function keep(l, guard) {
135
+ let yes = 0, no = 0;
136
+ const draws = samples(l.vars, l.params, 80, 19);
137
+ // Independent RNG streams can miss equality guards. Also force scalar coincidences, with the
138
+ // containers unchanged; these are adversarial samples, not assumptions of the proof.
139
+ const scalars = l.vars.filter(v => v.sort === 'nat' || v.sort === 'int');
140
+ const correlated = draws.flatMap(s => [0, 1, 2].map(n => ({ ...s, env: new Map([...s.env, ...scalars.map(v => [v.name, n])]) })));
141
+ for (const s of [...draws, ...correlated]) {
142
+ try {
143
+ if (guard && !evalY(guard, s.env, s.params)) {
144
+ no++;
145
+ continue;
146
+ }
147
+ ;
148
+ yes++;
149
+ if (!evalY(l.holds, s.env, s.params))
150
+ return false;
151
+ }
152
+ catch {
153
+ return false;
154
+ }
155
+ }
156
+ return yes >= 8 && (!guard || no >= 8);
157
+ }
158
+ const families = new WeakMap();
159
+ export const synthesizedObserver = (l) => families.get(l);
160
+ export function synthesizedLemmas(p) {
161
+ const out = [], seen = new Set();
162
+ let family = '';
163
+ const emit = (vars, lhs, rhs, guard) => {
164
+ if (same(lhs, rhs))
165
+ return;
166
+ const eq = { op: '=', a: lhs, b: rhs }, holds = guard ? { op: 'or', xs: [{ op: 'not', x: guard }, eq] } : eq;
167
+ const text = JSON.stringify(holds);
168
+ if (seen.has(text))
169
+ return;
170
+ seen.add(text);
171
+ const names = free(holds), used = vars.filter(v => names.has(v.name));
172
+ // All branch binders have been eliminated; no free symbol is silently omitted.
173
+ if (names.size !== used.length)
174
+ return;
175
+ const l = { name: showY(holds), vars: used, holds, params: [...p.params] };
176
+ if (keep(l, guard)) {
177
+ families.set(l, family);
178
+ out.push(l);
179
+ }
180
+ };
181
+ for (const f of p.fns) {
182
+ const a = algebra(p, f);
183
+ if (!a)
184
+ continue;
185
+ family = f.name;
186
+ const observers = lift(p, a);
187
+ for (const m of p.fns) {
188
+ const observer = m.ret instanceof Data ? observers.get(m.ret) : undefined;
189
+ if (!observer || m === f || (m.decreases === undefined && !m.measure) || m.params.every(q => !(q.sort instanceof Data)))
190
+ continue;
191
+ const vars = [...f.params.flatMap((q, i) => i === a.at ? [] : [{ name: `o${i}`, sort: q.sort }]), ...m.params.map((q, i) => ({ name: `v${i}`, sort: q.sort }))];
192
+ const args = m.params.map((_, i) => variable(`v${i}`));
193
+ const obsArgs = (value) => f.params.map((_, i) => i === a.at ? value : variable(`o${i}`));
194
+ const observe = (of, value) => ({ op: 'call', fn: of.name, args: obsArgs(value) });
195
+ const weights = [], parts = [];
196
+ const sub = new Map(f.params.map((q, i) => [`${f.name}.${q.name}`, variable(`o${i}`)]));
197
+ for (const [i, q] of m.params.entries()) {
198
+ const o = q.sort instanceof Data ? observers.get(q.sort) : undefined;
199
+ if (o)
200
+ parts.push(observe(o, args[i]));
201
+ else if (q.sort === a.payload)
202
+ weights.push(substitute(a.weight, new Map([...sub, [a.item, args[i]]])));
203
+ }
204
+ if (!parts.length)
205
+ continue;
206
+ const lhs = observe(observer, { op: 'call', fn: m.name, args }), rhs = sum(f, parts);
207
+ emit(vars, lhs, sum(f, [...parts, ...weights]));
208
+ if (weights.length)
209
+ emit(vars, lhs, rhs);
210
+ // Removing an element is additive only when its selection guard has a witness in the input.
211
+ // Instantiate the observer's equality parameter with that element, then test its count is positive.
212
+ for (const [wi, q] of m.params.entries())
213
+ if (q.sort === a.payload)
214
+ for (const [pi, pq] of f.params.entries())
215
+ if (pi !== a.at && pq.sort === a.payload)
216
+ for (const [di, dq] of m.params.entries())
217
+ if (dq.sort === a.data) {
218
+ const count = { op: 'call', fn: f.name, args: obsArgs(args[di]).map((v, i) => i === pi ? args[wi] : v) };
219
+ const guard = { op: f.ret === 'int' ? 'i<' : '<', a: zero(f), b: count };
220
+ emit(vars, sum(f, [lhs, ...weights]), rhs, guard);
221
+ emit(vars, lhs, rhs, { op: 'not', x: guard });
222
+ }
223
+ }
224
+ // A selector's result occurs in its input. This is the premise needed by a
225
+ // guarded removal law (minimum-then-rest is one instance, not a named special case).
226
+ const cons = a.data.ctors.findIndex(c => c.fields.length === 2 && c.fields.some(q => fieldSort(p, q.sort) === a.payload) && c.fields.some(q => fieldSort(p, q.sort) === a.data));
227
+ if (cons < 0)
228
+ continue;
229
+ for (const m of p.fns) {
230
+ if (m === f || m.ret !== a.payload || m.decreases === undefined || m.params.filter(q => q.sort === a.data).length !== 1)
231
+ continue;
232
+ const vars = m.params.map((q, i) => ({ name: `s${i}`, sort: q.sort })), args = vars.map(v => variable(v.name));
233
+ const result = { op: 'call', fn: m.name, args };
234
+ let source = args[m.params.findIndex(q => q.sort === a.data)];
235
+ for (const [i, q] of m.params.entries())
236
+ if (q.sort === a.payload)
237
+ source = { op: 'ctor', data: a.data.name, ctor: cons, args: a.data.ctors[cons].fields.map(q => fieldSort(p, q.sort) === a.payload ? args[i] : source) };
238
+ for (const [i, q] of f.params.entries()) {
239
+ if (i === a.at || q.sort !== a.payload || f.params.length !== 2)
240
+ continue;
241
+ const count = { op: 'call', fn: f.name, args: f.params.map((_, j) => j === a.at ? source : result) };
242
+ const holds = { op: f.ret === 'int' ? 'i<' : '<', a: zero(f), b: count };
243
+ const l = { name: showY(holds), vars, holds, params: [...p.params] };
244
+ if (keep(l)) {
245
+ families.set(l, family);
246
+ out.push(l);
247
+ }
248
+ }
249
+ }
250
+ }
251
+ return out;
252
+ }
@@ -262,6 +262,7 @@ export type Measure = {
262
262
  export type Termination = {
263
263
  measure: Measure;
264
264
  text: string;
265
+ invariant?: Y;
265
266
  obligations: {
266
267
  law: DataLaw;
267
268
  proof?: CyclicVerdict;
@@ -273,10 +274,14 @@ export type Termination = {
273
274
  };
274
275
  export declare const terminationMs: {
275
276
  ms: number;
277
+ }, guardedMs: {
278
+ ms: number;
276
279
  };
277
280
  export declare const showMeasure: (f: Pick<Fn, "params">, m: Measure) => string;
278
281
  export declare function measureX(f: Pick<Fn, 'params'>, c: Measure['comps'][number], args: X[]): X;
279
- export declare function checkMeasures(fns: Fn[], ms: Measure[], budget?: number): {
282
+ export type Inv = (Y | undefined)[];
283
+ export declare const valueVar: (f: Pick<Fn, "name">) => string;
284
+ export declare function checkMeasures(fns: Fn[], ms: Measure[], budget?: number, inv?: Inv): {
280
285
  proven: true;
281
286
  obligations: Termination['obligations'][];
282
287
  } | {
@@ -333,7 +338,7 @@ export type Program = {
333
338
  divisors: number[];
334
339
  ints: boolean;
335
340
  };
336
- export declare function programOf(laws: DataLaw[], extra?: Fn[]): Program;
341
+ export declare function programOf(laws: DataLaw[], extra?: Fn[], allowCounters?: boolean): Program;
337
342
  export declare const divMap: (k: number) => string, modMap: (k: number) => string;
338
343
  export declare const zig: (z: number) => number;
339
344
  export declare const unzig: (c: number) => number;
@@ -464,6 +469,7 @@ export type SearchCtx = {
464
469
  export declare function searchIn(l: DataLaw, opts: Options, until: number, ctx?: SearchCtx, phase?: 'all' | 'first' | 'rest'): {
465
470
  verdict: DataVerdict;
466
471
  out?: Proven;
472
+ facts?: Facts;
467
473
  };
468
474
  export declare const proveDataToday: (l: DataLaw) => DataVerdict;
469
475
  export declare function opaque(name: string): Data;