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
@@ -49,6 +49,7 @@ export declare class Reader {
49
49
  readonly goal: Goal;
50
50
  readonly trail: Trail;
51
51
  private node;
52
+ private share;
52
53
  private natRows;
53
54
  private atomRows;
54
55
  private leafAtomRows;
@@ -78,6 +79,7 @@ export declare class Reader {
78
79
  };
79
80
  linear(e: E): LV;
80
81
  private linear0;
82
+ private tparts;
81
83
  private atoms;
82
84
  truth(c: C): TV;
83
85
  private truth0;
@@ -144,6 +146,7 @@ export declare class Reader {
144
146
  private trailRow;
145
147
  private segRows;
146
148
  private pair;
149
+ private equal;
147
150
  private mark;
148
151
  private addCopy;
149
152
  private removeCopy;
@@ -1,5 +1,6 @@
1
+ import { shareTerms } from "./share.js";
1
2
  import { add, costs, env, k, scale, sub, v } from "../core/solver.js";
2
- import { atomOf, canon, canonFlip, columnTerm, factorsOf, isCell, termColumn } from "./kernel.js";
3
+ import { atomOf, canon, canonFlip, cellParts, plainMap, columnTerm, factorsOf, isCell, termColumn, tupleAnd } from "./kernel.js";
3
4
  export const none = new Set();
4
5
  export const join = (a, b) => {
5
6
  if (!a.size || a === b)
@@ -66,6 +67,7 @@ export class Reader {
66
67
  goal;
67
68
  trail;
68
69
  node = 0;
70
+ share = shareTerms();
69
71
  natRows = new Map();
70
72
  atomRows = new Map();
71
73
  leafAtomRows = new WeakMap();
@@ -186,6 +188,7 @@ export class Reader {
186
188
  return { t: undefined, w: none, pos: -1, fin: false };
187
189
  }
188
190
  linear(e) {
191
+ e = this.share(e);
189
192
  this.read(e);
190
193
  const had = this.ls.get(e);
191
194
  if (had && this.ok(had, e))
@@ -196,7 +199,7 @@ export class Reader {
196
199
  let lin, r = R0;
197
200
  switch (e.op) {
198
201
  case 'var':
199
- lin = e.name === '1' || /[*[\],:⟦]/.test(e.name) ? undefined : same(0, e, 0, 0, 0, () => v(e.name));
202
+ lin = e.name === '1' || /[*[\],:⟦⟨⟩|]/.test(e.name) ? undefined : same(0, e, 0, 0, 0, () => v(e.name));
200
203
  break;
201
204
  case 'const':
202
205
  lin = same(0, e, 0, 0, 0, () => k(e.value));
@@ -251,11 +254,41 @@ export class Reader {
251
254
  break;
252
255
  }
253
256
  case 'get': {
257
+ if (!plainMap(e.map)) {
258
+ lin = undefined;
259
+ break;
260
+ } // (kernel.ts's: no column a map's name could spell)
261
+ // (a tuple key: its parts' forms, the cell M[⟨k1|k2|…⟩], kernel.ts's keyParts)
262
+ if (e.key.op === 'tup' || e.key.op === 'proj') {
263
+ const ps = this.tparts(e.key);
264
+ // (kept by the cell's name: the read's parts change with the path, Src[p] where a column stood, and a form kept
265
+ // by the read alone named the first path's cell at every later one, a cell kernel.ts doesn't read there)
266
+ if (ps.lins) {
267
+ r = ps.r;
268
+ const name = `${e.map}[⟨${ps.lins.map(canon).join('|')}⟩]`;
269
+ lin = same(0, e, name, 0, 0, () => v(name));
270
+ break;
271
+ }
272
+ if (e.key.op === 'tup') {
273
+ lin = undefined;
274
+ r = ps.r;
275
+ break;
276
+ }
277
+ }
254
278
  const key = this.linear(e.key);
255
279
  lin = key.lin && same(0, e, key.lin, 0, 0, () => v(`${e.map}[${canon(key.lin)}]`));
256
280
  r = key;
257
281
  break;
258
282
  }
283
+ case 'tup':
284
+ lin = undefined;
285
+ break;
286
+ case 'proj': {
287
+ const ps = this.tparts(e.a);
288
+ r = ps.r;
289
+ lin = !ps.lins ? undefined : e.k === 0 ? ps.lins[0] : ps.lins.length === 2 ? ps.lins[1] : undefined;
290
+ break;
291
+ }
259
292
  }
260
293
  // (an open value's reason is what its decided parts need: only the column's own value is open)
261
294
  const out = { lin, w: r.w, fin: r.fin, pos: r.pos, stamp: r.pos < 0 ? 0 : this.trail.stamp(r.pos), node: this.node };
@@ -263,7 +296,29 @@ export class Reader {
263
296
  this.clean.add(e);
264
297
  return out;
265
298
  }
299
+ // kernel.ts's keyParts: a tuple's parts' forms (proj 1 of one its rest, two or more), with their reason.
300
+ tparts(e) {
301
+ if (e.op === 'proj') {
302
+ if (e.k === 0)
303
+ return { r: R0 };
304
+ const ps = this.tparts(e.a);
305
+ return ps.lins && ps.lins.length >= 3 ? { lins: ps.lins.slice(1), r: ps.r } : { r: ps.r };
306
+ }
307
+ if (e.op !== 'tup')
308
+ return { r: R0 };
309
+ const a = this.linear(e.a);
310
+ if (!a.lin)
311
+ return { r: a };
312
+ if (e.b.op !== 'tup') {
313
+ const b = this.linear(e.b);
314
+ return b.lin ? { lins: [a.lin, b.lin], r: both(a, b) } : { r: both(a, b) };
315
+ }
316
+ const rest = this.tparts(e.b);
317
+ return rest.lins ? { lins: [a.lin, ...rest.lins], r: both(a, rest.r) } : { r: both(a, rest.r) };
318
+ }
266
319
  atoms(c) {
320
+ if (c.a.op === 'tup' || c.b.op === 'tup')
321
+ return undefined;
267
322
  const a = this.linear(c.a), b = this.linear(c.b);
268
323
  if (!a.lin || !b.lin)
269
324
  return undefined;
@@ -279,6 +334,7 @@ export class Reader {
279
334
  return { when: atoms.when, unless: atoms.unless, r };
280
335
  }
281
336
  truth(c) {
337
+ c = this.share(c);
282
338
  this.read(c);
283
339
  const had = this.ts.get(c);
284
340
  if (had && this.ok(had, c))
@@ -324,6 +380,13 @@ export class Reader {
324
380
  case '<':
325
381
  case '<=':
326
382
  case '=': {
383
+ const and = tupleAnd(c);
384
+ if (and) {
385
+ const x = this.truth(and);
386
+ t = x.t;
387
+ r = x;
388
+ break;
389
+ }
327
390
  const cmp = this.atoms(c);
328
391
  if (!cmp) {
329
392
  t = undefined;
@@ -396,6 +459,9 @@ export class Reader {
396
459
  case '<':
397
460
  case '<=':
398
461
  case '=': {
462
+ const and = tupleAnd(c);
463
+ if (and)
464
+ return this.factsOf(and, positive, out);
399
465
  const cmp = this.atoms(c);
400
466
  if (!cmp)
401
467
  return R1;
@@ -643,9 +709,8 @@ export class Reader {
643
709
  for (const q of cells.slice(i + 1)) {
644
710
  if (p.map !== q.map)
645
711
  continue;
646
- const f = this.pair(p, q), x = this.dec(f.d), y = this.dec(f.neg);
647
- if (x.t === true && y.t === true) {
648
- const w = join(x.w, y.w);
712
+ const f = this.pair(p, q), w = this.equal(f);
713
+ if (w) {
649
714
  rows.push({ lin: f.pq, w, label: '' }, { lin: f.qp, w, label: '' });
650
715
  src?.push([p.name, q.name], [p.name, q.name]);
651
716
  }
@@ -804,11 +869,9 @@ export class Reader {
804
869
  const rows = this.within(key, () => {
805
870
  if (key.kind === 1)
806
871
  return this.termRows(this.nameText[key.i]);
807
- const p = cellOf(this.nameText[key.i]), q = cellOf(this.nameText[key.j]), f = this.pair(p, q);
808
- const x = this.dec(f.d), y = this.dec(f.neg);
809
- if (x.t !== true || y.t !== true)
872
+ const p = cellOf(this.nameText[key.i]), q = cellOf(this.nameText[key.j]), f = this.pair(p, q), w = this.equal(f);
873
+ if (!w)
810
874
  return [];
811
- const w = join(x.w, y.w);
812
875
  return [{ lin: f.pq, w, label: '' }, { lin: f.qp, w, label: '' }];
813
876
  });
814
877
  this.cached.set(key, rows);
@@ -816,17 +879,31 @@ export class Reader {
816
879
  return rows;
817
880
  }
818
881
  // (each pair's forms made once: the same objects at every node, so what is kept per form is found again)
882
+ // (two tuples: each part's difference; a plain key and a tuple, or tuples of different lengths: none, never equal)
819
883
  pair(p, q) {
820
884
  const key = `${p.name}\u0000${q.name}`;
821
885
  let f = this.pairs.get(key);
822
886
  if (!f) {
823
887
  if (this.pairs.size > 200_000)
824
888
  this.pairs.clear();
825
- const d = sub(p.key, q.key);
826
- this.pairs.set(key, (f = { d, neg: scale(d, -1), pq: sub(v(p.name), v(q.name)), qp: sub(v(q.name), v(p.name)) }));
889
+ const ds = p.key && q.key ? [sub(p.key, q.key)] : p.keys && q.keys && p.keys.length === q.keys.length ? p.keys.map((x, i) => sub(x, q.keys[i])) : undefined;
890
+ this.pairs.set(key, (f = { parts: ds?.map(d => [d, scale(d, -1)]), pq: sub(v(p.name), v(q.name)), qp: sub(v(q.name), v(p.name)) }));
827
891
  }
828
892
  return f;
829
893
  }
894
+ // The reason the trail proves a pair's keys equal (every part's difference 0 both ways), or none.
895
+ equal(f) {
896
+ if (!f.parts)
897
+ return undefined;
898
+ let w = none;
899
+ for (const [d, neg] of f.parts) {
900
+ const x = this.dec(d), y = this.dec(neg);
901
+ if (x.t !== true || y.t !== true)
902
+ return undefined;
903
+ w = join(w, join(x.w, y.w));
904
+ }
905
+ return w;
906
+ }
830
907
  mark(id, live) {
831
908
  if (this.markN[id] === this.syncN)
832
909
  return;
@@ -992,6 +1069,8 @@ export class Reader {
992
1069
  case 'mul': return this.openE(e.a, out);
993
1070
  case 'prod': return (this.openE(e.a, out), this.openE(e.b, out));
994
1071
  case 'get': return this.openE(e.key, out);
1072
+ case 'tup': return (this.openE(e.a, out), this.openE(e.b, out));
1073
+ case 'proj': return this.openE(e.a.op === 'tup' ? (e.k === 0 ? e.a.a : e.a.b) : e.a, out);
995
1074
  case 'if': {
996
1075
  const t = this.truth(e.c);
997
1076
  if (t.t === undefined)
@@ -1023,6 +1102,9 @@ export class Reader {
1023
1102
  return this.openC(c.x, out);
1024
1103
  if (c.op === 'and' || c.op === 'or')
1025
1104
  return c.xs.forEach(y => this.openC(y, out));
1105
+ const and = tupleAnd(c);
1106
+ if (and)
1107
+ return this.openC(and, out);
1026
1108
  const a = this.linear(c.a).lin, b = this.linear(c.b).lin;
1027
1109
  const own = a && b ? same(7, c, a, b, 0, () => { const d = sub(a, b); return c.op === '<=' ? [d] : c.op === '<' ? [add(d, k(1))] : [d, scale(d, -1)]; }) : [];
1028
1110
  this.openE(c.a, out), this.openE(c.b, out);
@@ -1046,6 +1128,9 @@ export class Reader {
1046
1128
  }
1047
1129
  if (c.op === 'flag' || c.op === 'all')
1048
1130
  return;
1131
+ const and = tupleAnd(c);
1132
+ if (and)
1133
+ return this.openH(and, out, positive);
1049
1134
  const before = out.length;
1050
1135
  this.openE(c.a, out), this.openE(c.b, out);
1051
1136
  if (out.length === before && !positive && c.op === '=' && this.truth(c).t === undefined)
@@ -1066,7 +1151,7 @@ const cellOf = (name) => {
1066
1151
  if (!out) {
1067
1152
  if (cellMemo.size > 100_000)
1068
1153
  cellMemo.clear();
1069
- cellMemo.set(name, (out = { name, map: name.slice(0, name.indexOf('[')), key: keyLin(name) }));
1154
+ cellMemo.set(name, (out = { name, ...cellParts(name) }));
1070
1155
  }
1071
1156
  return out;
1072
1157
  };
@@ -1341,7 +1426,7 @@ export class Clausal {
1341
1426
  let out;
1342
1427
  switch (e.op) {
1343
1428
  case 'var':
1344
- if (e.name === '1' || /[*[\],:⟦]/.test(e.name))
1429
+ if (e.name === '1' || /[*[\],:⟦⟨⟩|]/.test(e.name))
1345
1430
  throw new Unread();
1346
1431
  out = [{ g: [], lin: v(e.name) }];
1347
1432
  break;
@@ -1400,7 +1485,9 @@ export class Clausal {
1400
1485
  }
1401
1486
  break;
1402
1487
  }
1403
- case 'prod': throw new Unread();
1488
+ case 'prod':
1489
+ case 'tup':
1490
+ case 'proj': throw new Unread();
1404
1491
  }
1405
1492
  if (out.length > this.maxCases) {
1406
1493
  const col = v(this.fresh('ϰ'));
@@ -0,0 +1 @@
1
+ export declare function shareTerms(): <T extends object>(term: T) => T;
@@ -0,0 +1,27 @@
1
+ // Search-only hash consing. A reader's identity-keyed values and dependency edges
2
+ // should be shared by structurally identical terms, even after substitution made
3
+ // separate objects. No algebraic rewriting, reordering, or kernel acceptance here.
4
+ // The returned function is local to a reader; its AST inputs must remain immutable.
5
+ export function shareTerms() {
6
+ const memo = new WeakMap(), ids = new WeakMap(), table = new Map();
7
+ let next = 0;
8
+ const share = (term) => {
9
+ const had = memo.get(term);
10
+ if (had)
11
+ return had;
12
+ const entries = Object.entries(term).map(([k, value]) => [k, value !== null && typeof value === 'object' ? share(value) : value]);
13
+ const key = JSON.stringify([Array.isArray(term) ? ['array', term.length] : ['object'], entries.map(([k, value]) => [k,
14
+ value !== null && typeof value === 'object' ? ['ref', ids.get(value)] : [typeof value, typeof value === 'number' && Object.is(value, -0) ? '-0' : String(value)]
15
+ ]).sort(([a], [b]) => String(a).localeCompare(String(b)))]);
16
+ let out = table.get(key);
17
+ if (!out) {
18
+ out = entries.every(([k, value]) => term[k] === value) ? term : Object.assign(Array.isArray(term) ? new Array(term.length) : {}, Object.fromEntries(entries));
19
+ table.set(key, out);
20
+ ids.set(out, next++);
21
+ }
22
+ memo.set(term, out);
23
+ memo.set(out, out);
24
+ return out;
25
+ };
26
+ return share;
27
+ }
@@ -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. -/
@@ -681,6 +668,8 @@ function sharedTerms(vars, where, plainE) {
681
668
  case 'prod': return `.${t.op} (${e(t.a)}) (${e(t.b)})`;
682
669
  case 'if': return `.ite (${c(t.c)}) (${e(t.then)}) (${e(t.else)})`;
683
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)})`;
684
673
  }
685
674
  };
686
675
  const c = (t) => {
@@ -831,6 +820,8 @@ export function readable(id, laws, vars, maps, reach) {
831
820
  const a = plain ? arithOf(e.map) : undefined;
832
821
  return a ? `(${t(e.key)} ${a.op} ${a.k})` : `(μ ${q(e.map)} (${t(e.key)}))`;
833
822
  }
823
+ case 'tup': return `(Kern.cpair ${t(e.a)} ${t(e.b)})`;
824
+ case 'proj': return `(Kern.pickP ${e.k} ${t(e.a)})`;
834
825
  }
835
826
  };
836
827
  const p = (c) => {
@@ -936,7 +927,9 @@ ${plain}`;
936
927
  case 'min':
937
928
  case 'max':
938
929
  case 'prod':
939
- case 'if': return undefined;
930
+ case 'if':
931
+ case 'tup':
932
+ case 'proj': return undefined;
940
933
  }
941
934
  };
942
935
  const side = (ts) => (ts.length ? ts.map(([show, c]) => (c === 1 ? show : `${c} * ${show}`)).join(' + ') : '0');
@@ -1409,7 +1402,7 @@ theorem ${id}_orig_laws : ∀ ρ M, SReach ${id}_ghosted.orig ρ M → ∀ e ∈
1409
1402
  }
1410
1403
  else if (x2.op === 'if')
1411
1404
  (inC(x2.c), inE(x2.then), inE(x2.else));
1412
- else if (x2.op === 'mul')
1405
+ else if (x2.op === 'mul' || x2.op === 'proj')
1413
1406
  inE(x2.a);
1414
1407
  else if ('a' in x2)
1415
1408
  (inE(x2.a), inE(x2.b)); };
@@ -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
  };