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,6 +1,6 @@
1
1
  import { atMost, n, not, pointWrite } from "../core/machine.js";
2
2
  import { add, k, scale, sub } from "../core/solver.js";
3
- import { countedGoal, countedObligations, countHyps, mcGoal, postName, boundOf, caseGoals, check, checkRecur, checkRecurCases, coverGoal, recurGoal, canon, decided, factorsOf, isCell, isMonomial, columnTerm, stateName, termColumn, truth, historyMachine, sumMachine, sumCovers, sumParts, foldObligations, kInductionStart, kInductionSteps, leafConstraints, loopLiveness, loopMachine, linear, livenessHelpful, livenessParts, livenessLevels, livenessRanks, strongly, loopObligations, trueC, obligations, progressObligations, stepLawObligations, substC, witnessesOf, withProducts } from "../kernel/kernel.js";
3
+ import { countedGoal, countedObligations, countHyps, mcGoal, postName, boundOf, caseGoals, cellParts, check, checkRecur, checkRecurCases, coverGoal, recurGoal, canon, decided, factorsOf, isCell, isMonomial, columnTerm, stateName, termColumn, truth, historyMachine, sumMachine, sumCovers, sumParts, foldObligations, kInductionStart, kInductionSteps, leafConstraints, loopLiveness, loopMachine, linear, livenessHelpful, livenessParts, livenessLevels, livenessRanks, strongly, loopObligations, trueC, obligations, progressObligations, stepLawObligations, substC, witnessesOf, withProducts } from "../kernel/kernel.js";
4
4
  import { chooseLevels, clock, grow, minimal, proveBuilt, proveLaws, proveSetFast, proveStepLaws, withDeadline } from "../kernel/prove.js";
5
5
  import { refinement, refinementSides } from "../core/compose.js";
6
6
  import { exactNat, leanSurface, leanTerms } from "./lean-terms.js";
@@ -11,27 +11,9 @@ import { proveKInduction } from "../core/kind.js";
11
11
  export { leanLibrary };
12
12
  // --- to Lean ------------------------------------------------------------------------------------------------------------
13
13
  const varsOf = (c) => [...JSON.stringify(c).matchAll(/"op":"var","name":"([^"]+)"/g)].map(m => m[1]);
14
- const parseKey = (text) => {
15
- const lin = {};
16
- let depth = 0, start = 0;
17
- for (let i = 0; i <= text.length; i++) {
18
- const ch = text[i];
19
- if (ch === '[')
20
- depth++;
21
- else if (ch === ']')
22
- depth--;
23
- else if ((ch === ',' && depth === 0) || i === text.length) {
24
- if (i > start) {
25
- const part = text.slice(start, i), at = part.lastIndexOf(':');
26
- lin[part.slice(0, at)] = Number(part.slice(at + 1));
27
- }
28
- start = i + 1;
29
- }
30
- }
31
- return lin;
32
- };
33
- const cellKey = (cell) => parseKey(cell.slice(cell.indexOf('[') + 1, -1));
34
- const cellMap = (cell) => cell.slice(0, cell.indexOf('['));
14
+ // A cell's map, and its key rows: a plain key's one (M[k], Lean's cell) or a tuple's parts' (M[⟨k1|…⟩], Lean's cellT).
15
+ const cellMap = (cell) => cellParts(cell).map;
16
+ const cellKeys = (cell) => { const p = cellParts(cell); return p.keys ?? [p.key]; };
35
17
  const decide = (lin, path) => {
36
18
  if (Object.keys(lin).every(key => key === '1'))
37
19
  return (lin['1'] ?? 0) <= 0;
@@ -69,9 +51,11 @@ function reachedChoices(goal, leafList) {
69
51
  case 'get': return walkE(e.key);
70
52
  case 'add':
71
53
  case 'prod':
54
+ case 'tup':
72
55
  walkE(e.a);
73
56
  walkE(e.b);
74
57
  return;
58
+ case 'proj': return walkE(e.a);
75
59
  case 'sub':
76
60
  case 'min':
77
61
  case 'max':
@@ -163,7 +147,7 @@ export function encode(ex, tamper = false, dropStep = true, globalVars, globalMa
163
147
  if (isCell(f))
164
148
  addCell(f); };
165
149
  const addCell = (name) => { if (cells.has(name))
166
- return; cells.add(name); for (const key of Object.keys(cellKey(name)))
150
+ return; cells.add(name); for (const key of cellKeys(name).flatMap(l => Object.keys(l)))
167
151
  if (isMonomial(key))
168
152
  addMono(key);
169
153
  else if (key.includes('['))
@@ -252,7 +236,7 @@ export function encode(ex, tamper = false, dropStep = true, globalVars, globalMa
252
236
  if (placed.has(name))
253
237
  return;
254
238
  placed.add(name);
255
- for (const d of isMonomial(name) ? factorsOf(name) : Object.keys(cellKey(name)))
239
+ for (const d of isMonomial(name) ? factorsOf(name) : cellKeys(name).flatMap(l => Object.keys(l)))
256
240
  if (cells.has(d) || cellMonos.includes(d))
257
241
  place(d);
258
242
  late.push(name);
@@ -283,7 +267,7 @@ export function encode(ex, tamper = false, dropStep = true, globalVars, globalMa
283
267
  const { e, c } = leanTerms(vars, maps, ex.name);
284
268
  const tab = cols.map(name => (isMonomial(name) ? `.mono ${list(factorsOf(name).map(f => { const j = col.get(f); if (j === undefined)
285
269
  throw new Error(`${ex.name}: factor ${f}`); return j; }).sort((a, b) => a - b).map(String))}`
286
- : name.includes('[') ? `.cell ${maps.indexOf(cellMap(name))} ${row(cellKey(name))}`
270
+ : name.includes('[') ? (cellParts(name).keys ? `.cellT ${maps.indexOf(cellMap(name))} ${list(cellKeys(name).map(row))}` : `.cell ${maps.indexOf(cellMap(name))} ${row(cellKeys(name)[0])}`)
287
271
  : name.startsWith('⟦') ? `.term (${e(columnTerm(name))})`
288
272
  : `.var ${vars.indexOf(name)}`));
289
273
  let leafNo = 0, leafAt = 0;
@@ -322,15 +306,17 @@ export function encode(ex, tamper = false, dropStep = true, globalVars, globalMa
322
306
  });
323
307
  if (tamper && dropStep && leafNo++ === 0)
324
308
  steps = steps.slice(0, -1); // the first leaf loses its last step
325
- // Cell pairs the path proves equal (Lean re-checks each).
309
+ // Cell pairs the path proves equal (Lean re-checks each): one map, and the keys' difference decided 0 both ways (a
310
+ // tuple's, part by part, as many parts each; a plain key and a tuple never).
326
311
  const eqs = [], pairs = [];
327
- const cellCols = cols.map((name, j) => ({ name, j })).filter(c2 => isCell(c2.name));
312
+ const cellCols = cols.map((name, j) => ({ name, j, ...cellParts(name) })).filter(c2 => isCell(c2.name));
313
+ const zero = (a, b) => { const d = sub(a, b); return decide(d, path) === true && decide(scale(d, -1), path) === true; };
328
314
  for (const [a, p] of cellCols.entries())
329
315
  for (const q of cellCols.slice(a + 1)) {
330
- if (cellMap(p.name) !== cellMap(q.name))
316
+ if (p.map !== q.map)
331
317
  continue;
332
- const d = sub(cellKey(p.name), cellKey(q.name));
333
- if (decide(d, path) === true && decide(scale(d, -1), path) === true) {
318
+ const same = p.key && q.key ? zero(p.key, q.key) : !!p.keys && !!q.keys && p.keys.length === q.keys.length && p.keys.every((x, i) => zero(x, q.keys[i]));
319
+ if (same) {
334
320
  eqs.push(`(${p.j}, ${q.j})`);
335
321
  pairs.push([p.name, q.name].sort().join('\n'));
336
322
  }
@@ -413,11 +399,11 @@ export function cmachineToLean(id, m, laws, proof, tampers = []) {
413
399
  const allCerts = [proof.certs, ...tampers.map(t => t.certs)];
414
400
  const goals = obl.map(o => { const g = mcGoal(o.goal.hyps, o.decls, proof.certs[o.goal.name]); if (!g)
415
401
  throw new Error(`${id}: ${o.goal.name}: a read of no count`); return g; });
416
- const certVars = allCerts.flatMap(cs => Object.values(cs).flatMap(k => [...k.reads.flatMap(r => [r[0], ...varsOfE(r[2])]), ...k.insts.flatMap(i => [i.wit, ...varsOfE(i.below)])]));
417
- const vars = [...new Set([...named.vars, ...counts.flatMap(([, d]) => [d.j, d.key, ...varsOfE(d.below), ...varsOfE(d.body)]), ...laws.map(l => (l.forall ? `${l.forall}#` : '#')),
402
+ const certVars = allCerts.flatMap(cs => Object.values(cs).flatMap(k => [...k.reads.flatMap(r => [r[0], ...varsOfE(r[2])]), ...k.insts.flatMap(i => [i.wit, ...varsOfE(i.below)]), ...(k.picks ?? []).flatMap(([v2, ks]) => [v2, ...ks.flatMap(varsOfE)])]));
403
+ const vars = [...new Set([...named.vars, ...counts.flatMap(([, d]) => [d.j, d.lo ?? d.j, d.key, ...varsOfE(d.below), ...varsOfE(d.body)]), ...laws.map(l => (l.forall ? `${l.forall}#` : '#')),
418
404
  ...goals.flatMap(g => g.hyps.flatMap(varsOf)), ...certVars])];
419
405
  const maps = [...new Set([...named.maps, ...counts.flatMap(([cn]) => [cn, postName(cn)]), ...goals.flatMap(g => g.hyps.flatMap(mapsOf)),
420
- ...allCerts.flatMap(cs => Object.values(cs).flatMap(k => k.reads.map(r => r[1])))])];
406
+ ...allCerts.flatMap(cs => Object.values(cs).flatMap(k => [...k.reads.map(r => r[1]), ...(k.picks ?? []).flatMap(([, ks]) => ks.flatMap(mapsOf))]))])];
421
407
  const { e, c } = leanTerms(vars, maps, id);
422
408
  const ix = (name) => { const j = vars.indexOf(name); if (j < 0)
423
409
  throw new Error(`${id}: no variable for ${name}`); return j; };
@@ -448,7 +434,8 @@ export function cmachineToLean(id, m, laws, proof, tampers = []) {
448
434
  ${list(k.reads.map(r => `(${ix(r[0])}, ${mx(r[1])}, ${e(r[2])})`))},
449
435
  ${list(k.insts.map(i => `⟨${ix(i.wit)}, ${e(i.below)}, ${list(i.terms.map(([z, v2]) => `(${int(z)}, ${ix(v2)})`))}, ${int(i.unit)}⟩`))},
450
436
  ${tt.tab},
451
- ${tt.tree}⟩`;
437
+ ${tt.tree},
438
+ ${list((k.picks ?? []).map(([v2, ks]) => `(${ix(v2)}, ${list(ks.map(e))})`))}⟩`;
452
439
  };
453
440
  const entries = (certs) => laws.map(law => {
454
441
  const inst = proof.instances[law.name] ?? {};
@@ -460,7 +447,7 @@ export function cmachineToLean(id, m, laws, proof, tampers = []) {
460
447
  return `-- ${m.name}: ${laws.map(l => l.name).join('; ')}, with counts ${counts.map(([cn]) => cn).join(', ')}
461
448
  -- (variables ${vars.map((v2, j) => `${j} ${v2}`).join(', ')}; maps ${maps.map((v2, j) => `${j} ${v2}`).join(', ')})
462
449
  def ${id}_machine : SMachine := ${machineLit(sm, { e, c }, ix, mx)}
463
- def ${id}_decls : List CDecl := ${list(counts.map(([cn, d]) => `⟨${mx(cn)}, ${mx(postName(cn))}, ${ix(d.j)}, ${ix(d.key)}, ${e(d.below)}, ${e(d.body)}⟩`))}
450
+ def ${id}_decls : List CDecl := ${list(counts.map(([cn, d]) => `⟨${mx(cn)}, ${mx(postName(cn))}, ${ix(d.j)}, ${ix(d.key)}, ${e(d.below)}, ${e(d.body)}, ${ix(d.lo ?? d.j)}, ${d.base ?? 0}⟩`))}
464
451
  def ${id}_proof : List CEntry := ${list(entries(proof.certs))}
465
452
  theorem ${id}_check : checkCMachine ${id}_machine ${id}_decls ${id}_proof = true := by ${checkBy}
466
453
  /-- ${laws.map(l => l.name).join('; ')}: each holds in every reachable state, each count map read as the state's count. -/
@@ -530,15 +517,16 @@ export function loopToLean(id, l, laws, rank, tamper) {
530
517
  export function neverEndsToLean(id, l, r, tampered = []) {
531
518
  if (!checkRecur(l, r))
532
519
  throw new Error(`${id}: the certificate does not check`);
533
- const { vars, loop, recur, defs } = recurLean(id, l, r);
520
+ const { vars, loop, recur, defs } = recurLean(id, l, r, true), d = dataDef();
534
521
  return `-- ${l.name}: a run that never ends (variables ${vars.map((v2, j) => `${j} ${v2}`).join(', ')})
535
- ${defs ? `${defs}\n` : ''}def ${id}_loop : Loop := ${loop}
536
- def ${id}_recur : Recur := ${recur(r)}
522
+ ${defs ? `${defs}\n` : ''}${d} ${id}_loop : Loop := ${loop}
523
+ ${d} ${id}_recur : Recur := ${recur(r)}
537
524
  /-- ${l.name} never ends: for some params meeting its precondition, a run of turns from the start goes on forever. -/
538
525
  theorem ${id}_never_ends : NeverEnds ${id}_loop :=
539
- never_ends_of ${id}_loop ${id}_recur (by ${checkBy})${tampered.map((t, j) => `
526
+ never_ends_of ${id}_loop ${id}_recur (by
527
+ ${checkInParts('checkRecur', [])})${tampered.map((t, j) => `
540
528
  -- TAMPERED: ${t.what}. Lean computes the check to false.
541
- def ${id}_tampered${j} : Recur := ${recur(t.recur)}
529
+ ${d} ${id}_tampered${j} : Recur := ${recur(t.recur)}
542
530
  example : checkRecur ${id}_loop ${id}_tampered${j} = false := by ${checkBy}`).join('')}`;
543
531
  }
544
532
  // A loop with a run that never ends, its set closed by cases (NonTerm.lean's never_ends_of_cases): the cover's and each
@@ -546,17 +534,32 @@ example : checkRecur ${id}_loop ${id}_tampered${j} = false := by ${checkBy}`).jo
546
534
  export function neverEndsCasesToLean(id, l, r) {
547
535
  if (!checkRecurCases(l, r))
548
536
  throw new Error(`${id}: the certificate does not check`);
549
- const { vars, loop, recur, defs } = recurCasesLean(id, l);
537
+ const { vars, loop, recur, caseLit, defs } = recurCasesLean(id, l, true), d = dataDef();
538
+ const names = r.cases.map((_, j) => `${id}_case${j}`);
550
539
  return `-- ${l.name}: a run that never ends, closed by ${r.cases.length} cases (variables ${vars.map((v2, j) => `${j} ${v2}`).join(', ')})
551
- ${defs ? `${defs}\n` : ''}def ${id}_loop : Loop := ${loop}
552
- def ${id}_recur : RecurCases := ${recur(r)}
540
+ ${defs ? `${defs}\n` : ''}${d} ${id}_loop : Loop := ${loop}
541
+ ${names.map((n, j) => `${d} ${n} : List (Nat × Nat) × C × Cert := ${caseLit(r, j)}\n`).join('')}${d} ${id}_recur : RecurCases := ${recur(r, names)}
553
542
  /-- ${l.name} never ends: for some params meeting its precondition, a run of turns from the start goes on forever. -/
554
543
  theorem ${id}_never_ends : NeverEnds ${id}_loop :=
555
- never_ends_of_cases ${id}_loop ${id}_recur (by ${checkBy})`;
544
+ never_ends_of_cases ${id}_loop ${id}_recur (by
545
+ ${checkInParts('checkRecurCases', [`show ${id}_recur.cases = ${list(names)} from rfl`])})`;
546
+ }
547
+ // Definitions that are data: no compiled code for Lean to make (a large loop's terms take its compiler past its
548
+ // recursion limit and many GB), unless native_decide runs them.
549
+ const dataDef = () => checkBy === 'native_decide' ? 'def' : 'noncomputable def';
550
+ // A certificate's check, one part at a time: its definition unfolded into its conjuncts (the cases' list into one per
551
+ // case), each conjunct computed by the kernel on its own (an auxiliary lemma each, so the kernel's caches of one part
552
+ // are gone before the next: a large program's stem and each case's goal, not all of them at once). The same check of
553
+ // the same definitions, only its && split; Lean proves the split.
554
+ function checkInParts(check, rws) {
555
+ return ` rw [${[check, ...rws].join(', ')}]
556
+ simp only [List.all_cons, List.all_nil, Bool.and_true, Bool.and_eq_true]
557
+ repeat' apply And.intro
558
+ all_goals ${checkBy}`;
556
559
  }
557
560
  // A certificate by cases as NonTerm.lean's RecurCases (each tree written against the goal it refutes, else none).
558
- export function recurCasesLean(id, l) {
559
- const { vars, loop, defs } = recurLean(id, l, undefined);
561
+ export function recurCasesLean(id, l, share = false) {
562
+ const { vars, loop, defs } = recurLean(id, l, undefined, share);
560
563
  const { e, c } = leanTerms(vars, [], id);
561
564
  const ix = (name) => { const j = vars.indexOf(name); if (j < 0)
562
565
  throw new Error(`${id}: no variable for ${name}`); return j; };
@@ -572,36 +575,154 @@ export function recurCasesLean(id, l) {
572
575
  const coded = fits ? encode({ name: `${id}: ${goal.name}`, goal, tree }, false, true, vars, [], false, true) : { tab: '[]', tree: '.leafAt [] [] [] []' };
573
576
  return `(${coded.tab}, [], ${coded.tree})`;
574
577
  };
575
- const recur = (r) => `⟨${list(vars.map((_, j) => String(j)))},
576
- ${vals(r.start)},
577
- ${list(r.stem.map(vals))},
578
+ const caseLit = (r, j) => { const k2 = r.cases[j]; return `(${list(k2.pins.map(([n2, x]) => `(${ix(n2)}, ${x})`))}, ${c(k2.cond)}, ${cert(goals(r)[j], k2.tree)})`; };
579
+ // (the cases written in place, or as the names given, one per case)
580
+ const recur = (r, names) => `⟨${domOrder(vars, l, r.set, r.start)},
581
+ ${vals(nonzero(r.start))},
582
+ ${list(r.stem.map(t => vals(nonzero(t))))},
578
583
  ${c(r.set)},
579
584
  ${list(Object.entries(r.wit).map(([name, t]) => `(${ix(name)}, ${e(t)})`))},
580
585
  ${cert(coverGoal(r), r.cover)},
581
- ${list(r.cases.map((k2, j) => `(${list(k2.pins.map(([n2, x]) => `(${ix(n2)}, ${x})`))}, ${c(k2.cond)}, ${cert(goals(r)[j], k2.tree)})`))}⟩`;
586
+ ${list(names ?? r.cases.map((_, j) => caseLit(r, j)))}⟩`;
582
587
  const made = new WeakMap(), goals = (r) => { let g = made.get(r); if (!g)
583
588
  made.set(r, (g = caseGoals(l, r, r.cases))); return g; };
584
- return { vars, loop, recur, defs };
589
+ return { vars, loop, recur, caseLit, defs };
590
+ }
591
+ // A stem's domain and values as Lean reads them fastest. Its values are each looked up in a list: a value 0 is left out
592
+ // (valsEnv reads a value not listed as 0), and so is from the domain a variable no turn, the start or an input writes
593
+ // whose start is 0 (a run's state off the domain is 0 there, as it is anyway: Lean's stem reads the same values). Then
594
+ // the domain in the order the run reads it most: every rule's condition reads the location, so the variables the
595
+ // conditions read come first (most read first, the rest in their order). NonTerm.lean's domOk reads the domain as a set.
596
+ const nonzero = (o) => Object.fromEntries(Object.entries(o).filter(([, v]) => v !== 0));
597
+ function domOrder(vars, l, set, start) {
598
+ const reads = new Map();
599
+ const walk = (t, inC) => {
600
+ if (!t || typeof t !== 'object')
601
+ return;
602
+ const o = t;
603
+ if (o.op === 'var' && inC)
604
+ reads.set(o.name, (reads.get(o.name) ?? 0) + 1);
605
+ const c = inC || ['<=', '<', '=', 'and', 'or', 'not'].includes(o.op ?? '');
606
+ for (const v of Object.values(t))
607
+ if (v && typeof v === 'object')
608
+ (Array.isArray(v) ? v : [v]).forEach(x => walk(x, c));
609
+ };
610
+ for (const t of [...Object.values(l.body), l.while, ...(l.assume ? [l.assume] : []), set])
611
+ walk(t, false);
612
+ const written = new Set([...l.inputs, ...Object.keys(l.state), ...Object.keys(l.body), ...Object.keys(nonzero(start))]);
613
+ return list(vars.flatMap((name, j) => (written.has(name) ? [{ j, n: reads.get(name) ?? 0 }] : [])).sort((a, b) => b.n - a.n || a.j - b.j).map(x => String(x.j)));
614
+ }
615
+ // Terms written once each where they recur (recurLean's loops): `count` each term first, then `e` prints a term with
616
+ // each condition or term that has no if in it and recurs (3 uses or more, 24 characters or more) as its name, s<k>,
617
+ // and `defs` gives their definitions (`d`: def or noncomputable def), in the order they were named.
618
+ function sharedTerms(vars, where, plainE) {
619
+ const { c: plainC } = leanTerms(vars, [], where);
620
+ const counts = new Map(), names = new Map(), out = [];
621
+ const ifFree = new WeakMap();
622
+ const free = (t) => {
623
+ const had = ifFree.get(t);
624
+ if (had !== undefined)
625
+ return had;
626
+ const r = t.op === 'if' ? false : Object.values(t).every(v => typeof v !== 'object' || v === null || (Array.isArray(v) ? v.every(x => typeof x !== 'object' || free(x)) : free(v)));
627
+ ifFree.set(t, r);
628
+ return r;
629
+ };
630
+ const isC = (t) => ['<=', '<', '=', 'and', 'or', 'not', 'flag', 'all'].includes(t.op);
631
+ const text = (t) => (isC(t) ? plainC(t) : plainE(t));
632
+ const atomic = (t) => t.op === 'var' || t.op === 'const';
633
+ const count = (t) => {
634
+ if (atomic(t))
635
+ return;
636
+ if (free(t)) {
637
+ const k = text(t);
638
+ counts.set(k, (counts.get(k) ?? 0) + 1);
639
+ return;
640
+ }
641
+ for (const v of Object.values(t))
642
+ if (typeof v === 'object' && v !== null)
643
+ (Array.isArray(v) ? v : [v]).forEach(x => typeof x === 'object' && count(x));
644
+ };
645
+ const named = (t, k) => {
646
+ if (k.length < 24 || (counts.get(k) ?? 0) < 3)
647
+ return undefined;
648
+ let name = names.get(k);
649
+ if (!name) {
650
+ names.set(k, (name = `s${names.size}`));
651
+ out.push(`${isC(t) ? 'C' : 'E'}\u0000${name}\u0000${k}`);
652
+ }
653
+ return name;
654
+ };
655
+ const e = (t) => {
656
+ if (atomic(t))
657
+ return plainE(t);
658
+ if (free(t)) {
659
+ const k = plainE(t);
660
+ return named(t, k) ?? k;
661
+ }
662
+ switch (t.op) {
663
+ case 'mul': return `.mul ${exactNat(t.k)} (${e(t.a)})`;
664
+ case 'add':
665
+ case 'sub':
666
+ case 'min':
667
+ case 'max':
668
+ case 'prod': return `.${t.op} (${e(t.a)}) (${e(t.b)})`;
669
+ case 'if': return `.ite (${c(t.c)}) (${e(t.then)}) (${e(t.else)})`;
670
+ case 'get': return plainE(t);
671
+ case 'tup': return `.tup (${e(t.a)}) (${e(t.b)})`;
672
+ case 'proj': return `.proj ${t.k} (${e(t.a)})`;
673
+ }
674
+ };
675
+ const c = (t) => {
676
+ if (free(t)) {
677
+ const k = plainC(t);
678
+ return named(t, k) ?? k;
679
+ }
680
+ switch (t.op) {
681
+ case '<=': return `.le (${e(t.a)}) (${e(t.b)})`;
682
+ case '<': return `.lt (${e(t.a)}) (${e(t.b)})`;
683
+ case '=': return `.eq (${e(t.a)}) (${e(t.b)})`;
684
+ case 'not': return `.not (${c(t.x)})`;
685
+ case 'and':
686
+ case 'or': return t.xs.length === 0 ? plainC(t) : t.xs.map(c).reduceRight((acc, y) => `.${t.op} (${y}) (${acc})`);
687
+ case 'flag':
688
+ case 'all': return plainC(t);
689
+ }
690
+ };
691
+ const defs = (d) => out.map(x => { const [ty, name, k] = x.split('\u0000'); return `${d} ${name} : ${ty} := ${k}`; });
692
+ return { count, e, c, defs };
585
693
  }
586
- // The loop and a certificate as NonTerm.lean's Loop and Recur (the domain every variable; a certificate whose tree
587
- // doesn't refute its own goal carries `fallback`'s table and tree, which refutes `fallback`'s). lean-kernel/conformance.ts prints its cases with it.
694
+ // The loop and a certificate as NonTerm.lean's Loop and Recur (the domain and the values as domOrder and nonzero give
695
+ // them; a certificate whose tree doesn't refute its own goal carries `fallback`'s table and tree, which refutes
696
+ // `fallback`'s). lean-kernel/conformance.ts prints its cases with it. `share`: the loop's recurring terms named
697
+ // (sharedTerms), for an export that writes `defs` out.
588
698
  // (a loop's start and body past 128 variables as definitions of 128 each, appended: Lean elaborates a list literal of
589
699
  // deep terms one level deeper per entry, and pgarch's 690 body terms, each 228 rules deep, pass its recursion limit)
590
- export function recurLean(id, l, fallback) {
700
+ export function recurLean(id, l, fallback, share = false) {
591
701
  const vars = [...l.params, ...l.inputs, ...Object.keys(l.state)];
592
702
  const { e, c } = leanTerms(vars, [], id);
593
703
  const ix = (name) => { const j = vars.indexOf(name); if (j < 0)
594
704
  throw new Error(`${id}: no variable for ${name}`); return j; };
595
705
  const defs = [];
706
+ // A large program's terms are each variable's rules as one chain of ifs, every chain over the same conditions (the
707
+ // locations) and much the same updates: each such term past a few uses written once, as a definition (s<k>, in the
708
+ // namespace <id>_s, with the chains' pieces), and named where it is used. The same terms, as Lean unfolds them.
709
+ const sh = sharedTerms(vars, id, e), ns = `${id}_s`, entries = (o) => Object.entries(o).map(([name, e2]) => `(${ix(name)}, ${sh.e(e2)})`);
710
+ if (share)
711
+ for (const t of [...Object.values(l.state), ...Object.values(l.body)])
712
+ sh.count(t);
713
+ const init = entries(l.state), body = entries(l.body), shared = sh.defs(dataDef());
596
714
  const pieces = (what, xs) => {
597
- if (xs.length <= 128)
715
+ if (xs.length <= 128 && !shared.length)
598
716
  return list(xs);
599
- const names = Array.from({ length: Math.ceil(xs.length / 128) }, (_, k) => { defs.push(`def ${id}_${what}${k} : List (Nat × E) := ${list(xs.slice(k * 128, k * 128 + 128))}`); return `${id}_${what}${k}`; });
600
- return `(${names.join(' ++ ')})`;
717
+ const names = Array.from({ length: Math.ceil(xs.length / 128) }, (_, k) => { defs.push(`${dataDef()} ${what}${k} : List (Nat × E) := ${list(xs.slice(k * 128, k * 128 + 128))}`); return `${ns}.${what}${k}`; });
718
+ return names.length ? `(${names.join(' ++ ')})` : '[]';
601
719
  };
720
+ const loopInit = pieces('init', init), loopBody = pieces('body', body);
721
+ if (defs.length)
722
+ defs.splice(0, 0, `namespace ${ns}`, ...shared), defs.push(`end ${ns}`);
602
723
  const loop = `⟨${list(l.inputs.map(name => String(ix(name))))},
603
- ${pieces('init', Object.entries(l.state).map(([name, e2]) => `(${ix(name)}, ${e(e2)})`))},
604
- ${pieces('body', Object.entries(l.body).map(([name, e2]) => `(${ix(name)}, ${e(e2)})`))},
724
+ ${loopInit},
725
+ ${loopBody},
605
726
  ${c(l.while)},
606
727
  ${l.pre ? c(l.pre) : TRUE},
607
728
  ${l.assume ? c(l.assume) : TRUE}⟩`;
@@ -620,9 +741,9 @@ export function recurLean(id, l, fallback) {
620
741
  // (neither refuting its goal, as a forged certificate's: a leaf with no step, the tree that refutes nothing)
621
742
  const by = fits(rr) ? rr : fallback && fits(fallback) ? fallback : undefined;
622
743
  const coded = by ? enc(by) : { tab: '[]', tree: '.leafAt [] [] [] []' };
623
- return `⟨${list(vars.map((_, j) => String(j)))},
624
- ${vals(rr.start)},
625
- ${list(rr.stem.map(vals))},
744
+ return `⟨${domOrder(vars, l, rr.set, rr.start)},
745
+ ${vals(nonzero(rr.start))},
746
+ ${list(rr.stem.map(t => vals(nonzero(t))))},
626
747
  ${c(rr.set)},
627
748
  ${list(Object.entries(rr.wit).map(([name, t]) => `(${ix(name)}, ${e(t)})`))},
628
749
  (${coded.tab}, [], ${coded.tree})⟩`;
@@ -699,6 +820,8 @@ export function readable(id, laws, vars, maps, reach) {
699
820
  const a = plain ? arithOf(e.map) : undefined;
700
821
  return a ? `(${t(e.key)} ${a.op} ${a.k})` : `(μ ${q(e.map)} (${t(e.key)}))`;
701
822
  }
823
+ case 'tup': return `(Kern.cpair ${t(e.a)} ${t(e.b)})`;
824
+ case 'proj': return `(Kern.pickP ${e.k} ${t(e.a)})`;
702
825
  }
703
826
  };
704
827
  const p = (c) => {
@@ -804,7 +927,9 @@ ${plain}`;
804
927
  case 'min':
805
928
  case 'max':
806
929
  case 'prod':
807
- case 'if': return undefined;
930
+ case 'if':
931
+ case 'tup':
932
+ case 'proj': return undefined;
808
933
  }
809
934
  };
810
935
  const side = (ts) => (ts.length ? ts.map(([show, c]) => (c === 1 ? show : `${c} * ${show}`)).join(' + ') : '0');
@@ -1233,6 +1358,16 @@ theorem ${id}_some${j} : ∀ ρ M, SReach ${id}_gm.orig ρ M → ∀ v, ∃ val,
1233
1358
  (by ${checkBy}) (by ${checkBy}) (by ${checkBy}) (by ${checkBy})
1234
1359
  have hr : substRC [] (rdW ${mx(fs.map)} ${ix(fs.as)}) ${id}_e${li}.law.holds = ${c(read)} := by ${checkBy}
1235
1360
  rw [hr] at h; exact h`;
1361
+ }).join('')}${(opts.ghostSubst ?? []).map((gs, j) => {
1362
+ const li = laws.findIndex(l => l.name === gs.law), law = laws[li];
1363
+ if (!law)
1364
+ throw new Error(`${id}: ${gs.law}: no such law`);
1365
+ const sigma = list(Object.entries(gs.sub).map(([x, t]) => `(${ix(x)}, ${e(t)})`));
1366
+ return `
1367
+ /-- ${law.name}, read ∃: for every value of its keys, some natural for each of ${Object.keys(gs.sub).join(', ')} (at the ghosts' terms) where its body holds; no ghost read. -/
1368
+ theorem ${id}_ex${j} : ∀ ρ M, SReach ${id}_gm.orig ρ M → ExHolds (${c(gs.body)}) ${id}_e${li}.law.key ${list(Object.keys(gs.sub).map(x => String(ix(x))))} M ${id}_e${li}.keys2 ρ :=
1369
+ forall_some_of_ghostsubst ${id}_gm ${id}_gmOk ${id}_proof ${id}_check ${id}_e${li} (${memOf(li)}) ${sigma} (${c(gs.body)})
1370
+ (by ${checkBy}) (by ${checkBy}) (by ${checkBy})`;
1236
1371
  }).join('')}`;
1237
1372
  } });
1238
1373
  // Ghosts (Ghost.lean's sghost_laws): the laws that read no ghost hold of the machine without its ghosts.
@@ -1267,7 +1402,7 @@ theorem ${id}_orig_laws : ∀ ρ M, SReach ${id}_ghosted.orig ρ M → ∀ e ∈
1267
1402
  }
1268
1403
  else if (x2.op === 'if')
1269
1404
  (inC(x2.c), inE(x2.then), inE(x2.else));
1270
- else if (x2.op === 'mul')
1405
+ else if (x2.op === 'mul' || x2.op === 'proj')
1271
1406
  inE(x2.a);
1272
1407
  else if ('a' in x2)
1273
1408
  (inE(x2.a), inE(x2.b)); };
@@ -2293,8 +2428,7 @@ ${cycProofText(id, p, tampered, vars, maps)}${bridge ? `\n${cycBridgeLean(id, p,
2293
2428
  // node's membership, the check and cyclic_sound's theorem; each tampered proof's check computed to false.
2294
2429
  function cycProofText(id, p, tampered, vars, maps) {
2295
2430
  const { e, c } = leanTerms(vars, maps, id);
2296
- // (data, not code: no compiled code for Lean to make, unless native_decide runs it)
2297
- const d = checkBy === 'native_decide' ? 'def' : 'noncomputable def';
2431
+ const d = dataDef();
2298
2432
  const ix = (name) => vars.indexOf(name);
2299
2433
  const facts = list(p.facts.map(f => `⟨${list(f.keys.map(key => String(ix(key))))}, ${c(f.holds)}⟩`));
2300
2434
  // A tampered proof keeps the proof's tables and trees (made for the proof's own goals) under its changed nodes.
@@ -24,6 +24,8 @@ export function leanTerms(vars, maps, where) {
24
24
  case 'prod': return `.${t.op} (${e(t.a)}) (${e(t.b)})`;
25
25
  case 'if': return `.ite (${c(t.c)}) (${e(t.then)}) (${e(t.else)})`;
26
26
  case 'get': return `.get ${mx(t.map)} (${e(t.key)})`;
27
+ case 'tup': return `.tup (${e(t.a)}) (${e(t.b)})`;
28
+ case 'proj': return `.proj ${t.k} (${e(t.a)})`;
27
29
  default: return unreachable(t);
28
30
  }
29
31
  };
@@ -66,6 +68,9 @@ export function leanSurface(names, where, get) {
66
68
  if (!get)
67
69
  throw new Error(`${where}: reads ${t.map}, a function or a map`);
68
70
  return get(t.map, t.key, e);
71
+ // A tuple is its pairing (Kernel.lean's cpair), a part of one the pair's part (pickP: 0 the first, 1 the second).
72
+ case 'tup': return `(Kern.cpair ${e(t.a)} ${e(t.b)})`;
73
+ case 'proj': return `(Kern.pickP ${t.k} ${e(t.a)})`;
69
74
  default: return unreachable(t);
70
75
  }
71
76
  };