gdp-wired 0.45.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 (120) 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 +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 +3 -0
  10. package/dist/core/cli.js +204 -38
  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.d.ts +1 -4
  27. package/dist/core/effect.js +1 -15
  28. package/dist/core/exists.d.ts +1 -0
  29. package/dist/core/exists.js +191 -16
  30. package/dist/core/extract-c.d.ts +2 -0
  31. package/dist/core/extract-c.js +169 -22
  32. package/dist/core/extract-check.d.ts +1 -0
  33. package/dist/core/extract-check.js +66 -0
  34. package/dist/core/extract-go-check.d.ts +1 -1
  35. package/dist/core/extract-go-check.js +2 -1
  36. package/dist/core/extract-go.d.ts +1 -0
  37. package/dist/core/extract-go.js +38 -4
  38. package/dist/core/extract-ir.d.ts +1 -0
  39. package/dist/core/extract-ir.js +15 -0
  40. package/dist/core/extract-jvm.d.ts +1 -1
  41. package/dist/core/extract-jvm.js +2 -0
  42. package/dist/core/extract-orm.d.ts +12 -0
  43. package/dist/core/extract-orm.js +244 -0
  44. package/dist/core/extract-print.js +20 -1
  45. package/dist/core/extract-py.d.ts +1 -0
  46. package/dist/core/extract-py.js +1 -1
  47. package/dist/core/extract-read.d.ts +17 -0
  48. package/dist/core/extract-read.js +5 -5
  49. package/dist/core/extract-rs.js +5 -1
  50. package/dist/core/extract-shapes.js +2 -0
  51. package/dist/core/extract-sol.d.ts +10 -1
  52. package/dist/core/extract-sol.js +70 -22
  53. package/dist/core/extract-step.d.ts +151 -1
  54. package/dist/core/extract-step.js +1232 -60
  55. package/dist/core/extract-swift.js +6 -2
  56. package/dist/core/extract.d.ts +8 -0
  57. package/dist/core/extract.js +61 -5
  58. package/dist/core/fiber-run.d.ts +5 -0
  59. package/dist/core/fiber-run.js +18 -0
  60. package/dist/core/infer.d.ts +4 -1
  61. package/dist/core/infer.js +918 -217
  62. package/dist/core/jvm/JavaReader.java +23 -6
  63. package/dist/core/jvm/Jvm.java +3 -0
  64. package/dist/core/jvm/KtReader.java +6 -5
  65. package/dist/core/laws.d.ts +10 -3
  66. package/dist/core/laws.js +193 -14
  67. package/dist/core/machine.d.ts +15 -1
  68. package/dist/core/machine.js +187 -15
  69. package/dist/core/nonterm.js +14 -1
  70. package/dist/core/orm/harness.js +61 -0
  71. package/dist/core/orm-fixtures/schema.prisma +5 -0
  72. package/dist/core/py/harness.py +183 -10
  73. package/dist/core/py/reader.py +234 -40
  74. package/dist/core/reader-fixtures/README.md +28 -0
  75. package/dist/core/reader-fixtures/c-693042.cpp +8 -0
  76. package/dist/core/reader-fixtures/go-685506.go +14 -0
  77. package/dist/core/reader-fixtures/jvm-724362.kt +8 -0
  78. package/dist/core/reader-fixtures/jvm-737430.kt +7 -0
  79. package/dist/core/reader-fixtures/jvm-765282.kt +3 -0
  80. package/dist/core/reader-fixtures/swift-735726.swift +15 -0
  81. package/dist/core/reader-fixtures/swift-735990.swift +15 -0
  82. package/dist/core/reader-fixtures/swift-739158.swift +4 -0
  83. package/dist/core/reader-fixtures/swift-744834.swift +15 -0
  84. package/dist/core/reader-fixtures/swift-746946.swift +31 -0
  85. package/dist/core/reader-fixtures/typescript-673062.ts.txt +2 -0
  86. package/dist/core/relation.d.ts +1 -1
  87. package/dist/core/relation.js +29 -2
  88. package/dist/core/relational.js +4 -2
  89. package/dist/core/rs/src/main.rs +8 -2
  90. package/dist/core/sample-cache.d.ts +8 -0
  91. package/dist/core/sample-cache.js +46 -0
  92. package/dist/core/security.d.ts +38 -0
  93. package/dist/core/security.js +88 -0
  94. package/dist/core/sol/harness.py +57 -4
  95. package/dist/core/sol-concrete.d.ts +23 -0
  96. package/dist/core/sol-concrete.js +195 -0
  97. package/dist/core/solver.js +3 -1
  98. package/dist/core/swift/Sources/gdp-swiftreader/main.swift +50 -7
  99. package/dist/core/system.js +1 -1
  100. package/dist/core/transfer.js +22 -9
  101. package/dist/core/translate.js +39 -10
  102. package/dist/core/watch.js +50 -5
  103. package/dist/interchange/format.js +11 -1
  104. package/dist/kernel/cdcl.d.ts +5 -0
  105. package/dist/kernel/cdcl.js +56 -9
  106. package/dist/kernel/epr.js +108 -26
  107. package/dist/kernel/kernel.d.ts +29 -1
  108. package/dist/kernel/kernel.js +325 -62
  109. package/dist/kernel/model-sequence.d.ts +3 -0
  110. package/dist/kernel/model-sequence.js +34 -0
  111. package/dist/kernel/prove.d.ts +10 -3
  112. package/dist/kernel/prove.js +332 -71
  113. package/dist/kernel/reader.d.ts +3 -0
  114. package/dist/kernel/reader.js +101 -14
  115. package/dist/kernel/share.d.ts +1 -0
  116. package/dist/kernel/share.js +27 -0
  117. package/dist/lean-kernel/emit.js +30 -37
  118. package/dist/lean-kernel/lean-terms.js +5 -0
  119. package/dist/lean-kernel/library.js +10 -10
  120. package/package.json +6 -1
@@ -5,7 +5,7 @@
5
5
  // Arithmetic is linear: +, −, × by a constant, min, max, if. Maps are naturals indexed by naturals, every cell starting
6
6
  // at the same value; a law about a map holds for every key x, and is proven at one arbitrary x (with the law assumed at
7
7
  // every other key the step reads).
8
- import { boundOf, crossFree, historyMachine, keyTerm, plainKey, scope, sumRuntime } from "../kernel/kernel.js";
8
+ import { boundOf, crossFree, eachParts, historyMachine, tuple, keyTerm, mapArities, plainKey, scope, sumRuntime, tupleParts } from "../kernel/kernel.js";
9
9
  import { add, env, eq, k, le, lt, nat, scale, show, solve, sub, v } from "./solver.js";
10
10
  // The one generator of the repo's random draws: x' = (1103515245 x + 12345) mod 2^31, exact (Math.imul). In doubles
11
11
  // the product passes 2^53 and rounds, which folds every seed into one of six short cycles (61 to 10,466 steps; 98.8% of
@@ -47,7 +47,7 @@ export const pointWrite = (w, where) => { if ('each' in w)
47
47
  throw new Error(`${where} takes no write at every key`); return w; };
48
48
  // The same for a quantified flag.
49
49
  export const noQuantifier = (where) => { throw new Error(`${where} takes no quantified flag`); };
50
- export { unreachable } from "../kernel/kernel.js";
50
+ export { unreachable, tuple, tupleParts, part } from "../kernel/kernel.js";
51
51
  // Builders.
52
52
  export const x = (name) => ({ op: 'var', name });
53
53
  export const n = (value) => ({ op: 'const', value });
@@ -59,6 +59,20 @@ export const max = (a, b) => ({ op: 'max', a, b });
59
59
  export const prod = (a, b) => ({ op: 'prod', a, b });
60
60
  export const ite = (c, then, otherwise) => ({ op: 'if', c, then, else: otherwise });
61
61
  export const get = (map, key) => ({ op: 'get', map, key });
62
+ // The pairing and its inverse as the runtimes compute them, exactly (Lean's cpair and cun): tri(a + b) + b, and back.
63
+ export const cpair = (a, b) => { const s = a + b; return exactPair(s % 2 === 0 ? (s / 2) * (s + 1) + b : s * ((s + 1) / 2) + b); };
64
+ const exactPair = (v) => { if (!Number.isSafeInteger(v))
65
+ throw new RangeError('a tuple key passed 2^53 - 1, past which the proofs over the naturals no longer describe the run'); return v; };
66
+ export const cunpair = (z) => {
67
+ let s = Math.floor((Math.sqrt(8 * z + 1) - 1) / 2);
68
+ while (s > 0 && tri(s) > z)
69
+ s--;
70
+ while (tri(s + 1) <= z)
71
+ s++;
72
+ const b = z - tri(s);
73
+ return [s - b, b];
74
+ };
75
+ const tri = (s) => (s % 2 === 0 ? (s / 2) * (s + 1) : s * ((s + 1) / 2));
62
76
  export const less = (a, b) => ({ op: '<', a, b });
63
77
  export const atMost = (a, b) => ({ op: '<=', a, b });
64
78
  export const same = (a, b) => ({ op: '=', a, b });
@@ -132,17 +146,39 @@ function breaksOf(t, key) {
132
146
  return hit;
133
147
  const out = { reads: [], cmps: [] };
134
148
  const termOf = (e) => (e.op === 'var' ? { minus: false } : e.op === 'add' ? { off: e.a.op === 'var' && e.a.name === key ? e.b : e.a, minus: false } : { off: e.b, minus: true });
149
+ const cmp = (a, b) => {
150
+ if (!keyTerm(a, key) && !keyTerm(b, key))
151
+ return false;
152
+ const [kt, other] = keyTerm(a, key) ? [a, b] : [b, a];
153
+ out.cmps.push({ value: other, ...termOf(kt) });
154
+ walk(other);
155
+ return true;
156
+ };
135
157
  const walk = (u) => {
136
158
  if (u.op === 'get' && keyTerm(u.key, key)) {
137
159
  out.reads.push({ map: u.map, ...termOf(u.key) });
138
160
  return;
139
161
  }
140
- if ((u.op === '<' || u.op === '<=' || u.op === '=') && (keyTerm(u.a, key) || keyTerm(u.b, key))) {
141
- const [kt, other] = keyTerm(u.a, key) ? [u.a, u.b] : [u.b, u.a];
142
- out.cmps.push({ value: other, ...termOf(kt) });
143
- walk(other);
162
+ if (u.op === 'get' && u.key.op === 'tup') {
163
+ const parts = tupleParts(u.key);
164
+ parts.forEach((p, i) => { if (keyTerm(p, key))
165
+ out.reads.push({ map: u.map, ...termOf(p), part: [i, parts.length] });
166
+ else
167
+ walk(p); });
144
168
  return;
145
169
  }
170
+ if (u.op === '=' && u.a.op === 'tup' && u.b.op === 'tup') {
171
+ const as = tupleParts(u.a), bs = tupleParts(u.b);
172
+ if (as.length === bs.length) {
173
+ as.forEach((a, i) => { if (!cmp(a, bs[i])) {
174
+ walk(a);
175
+ walk(bs[i]);
176
+ } });
177
+ return;
178
+ }
179
+ }
180
+ if ((u.op === '<' || u.op === '<=' || u.op === '=') && cmp(u.a, u.b))
181
+ return;
146
182
  for (const v of Object.values(u))
147
183
  if (v && typeof v === 'object')
148
184
  (Array.isArray(v) ? v : [v]).forEach(y => walk(y));
@@ -157,7 +193,8 @@ function breakKeys(b, env, st, m) {
157
193
  const points = new Set([0]);
158
194
  for (const r of b.reads) {
159
195
  const d = r.off ? evalE(r.off, env, st, m) : 0;
160
- for (const s of st.maps[r.map]?.keys() ?? []) {
196
+ for (const s0 of st.maps[r.map]?.keys() ?? []) {
197
+ const s = r.part ? partsOf(s0, r.part[1])[r.part[0]] : s0;
161
198
  if (r.minus)
162
199
  points.add(s + d);
163
200
  else if (s >= d)
@@ -201,6 +238,17 @@ function tupleKeys(c, env, st, m) {
201
238
  const parts = names.map(n => breaksOf(body, n));
202
239
  return spread(breakKeys({ reads: parts.flatMap(b => b.reads), cmps: parts.flatMap(b => b.cmps) }, env, st, m), names.length);
203
240
  }
241
+ // A natural's n parts, read as an n-tuple (the inverse of cpair nested to the right).
242
+ export const partsOf = (z, n) => {
243
+ const out = [];
244
+ for (let i = 0; i + 1 < n; i++) {
245
+ const [a, b] = cunpair(z);
246
+ out.push(a);
247
+ z = b;
248
+ }
249
+ out.push(z);
250
+ return out;
251
+ };
204
252
  const spread = (keys, n) => [...new Set(keys.flatMap(k => Array.from({ length: n }, (_, i) => k + i)))].sort((a, b) => a - b);
205
253
  export const naturalIn = (v, what) => {
206
254
  if (typeof v !== 'number' || !Number.isSafeInteger(v) || v < 0)
@@ -230,6 +278,8 @@ export function evalE(e, env, st, m) {
230
278
  case 'min': return Math.min(evalE(e.a, env, st, m), evalE(e.b, env, st, m));
231
279
  case 'max': return Math.max(evalE(e.a, env, st, m), evalE(e.b, env, st, m));
232
280
  case 'if': return evalC(e.c, env, st, m) ? evalE(e.then, env, st, m) : evalE(e.else, env, st, m);
281
+ case 'tup': return cpair(evalE(e.a, env, st, m), evalE(e.b, env, st, m));
282
+ case 'proj': return cunpair(evalE(e.a, env, st, m))[e.k];
233
283
  case 'get': {
234
284
  const fn = m.fns && Object.hasOwn(m.fns, e.map) ? m.fns[e.map] : undefined, args = fn?.call ? pairedArgs(e.key, fn.arity) : undefined;
235
285
  if (args) {
@@ -342,6 +392,14 @@ export function compileE(e, m) {
342
392
  const c = compileC(e.c, m), t = compileE(e.then, m), f = compileE(e.else, m);
343
393
  return (env, st) => (c(env, st) ? t(env, st) : f(env, st));
344
394
  }
395
+ case 'tup': {
396
+ const a = compileE(e.a, m), b = compileE(e.b, m);
397
+ return (env, st) => cpair(a(env, st), b(env, st));
398
+ }
399
+ case 'proj': {
400
+ const a = compileE(e.a, m), k = e.k;
401
+ return (env, st) => cunpair(a(env, st))[k];
402
+ }
345
403
  case 'get': {
346
404
  const map = e.map, key = compileE(e.key, m);
347
405
  return (env, st) => {
@@ -390,7 +448,11 @@ export function compileC(c, m) {
390
448
  // A write at every key: its value at each key the maps it reads hold a cell at, and its new default past them.
391
449
  // With the key in key terms, every key up to the last breakpoint is computed (the stretches between breakpoints hold the
392
450
  // same value, which need not be the default), and past it the value is the new default.
393
- function writeEvery(w, env, st, m) {
451
+ function writeEvery(w, env, st, m, parts = 1, map) {
452
+ if (parts > 1) {
453
+ const t = eachParts(w, parts), same = map !== undefined && unchanged(t, map, env, st, m);
454
+ return same ? { cells: new Map(st.maps[map]), default: st.defaults && Object.hasOwn(st.defaults, map) ? st.defaults[map] : m.maps[map] } : writeEveryTuple(t, env, st, m);
455
+ }
394
456
  if (!plainKey(w.value, w.each)) {
395
457
  const ks = breakKeys(breaksOf(w.value, w.each), env, st, m), top = ks.at(-1);
396
458
  // (each breakpoint on its own, and each stretch between two at one key of it: no read moves and no comparison turns
@@ -422,6 +484,99 @@ function writeEvery(w, env, st, m) {
422
484
  }
423
485
  return { cells, default: fallback };
424
486
  }
487
+ // A write at every tuple of a map of n parts, read at its parts (kernel.ts's eachParts): each part's breakpoints together
488
+ // (as a condition at every tuple of keys reads them), every tuple of them, and each stretch between two breakpoints at
489
+ // one key of it. Past the last breakpoint in any part the value must be the new default (a value other than it along an
490
+ // unbounded stretch is cells without end), and a stretch filled in two parts or more at once must read no comparison
491
+ // between the parts (the value along it then depends on more than the stretch).
492
+ function writeEveryTuple(t, env, st, m) {
493
+ const n = t.names.length, body = { op: '=', a: t.value, b: { op: 'const', value: 0 } }, free = crossFree(body, t.names);
494
+ const bs = t.names.map(name => breaksOf(free, name));
495
+ const crossed = JSON.stringify(free) !== JSON.stringify(body);
496
+ // (parts compared with no other part: each on its own breakpoints; else all of them together, n keys after each)
497
+ const merged = crossed ? spread(breakKeys({ reads: bs.flatMap(b => b.reads), cmps: bs.flatMap(b => b.cmps) }, env, st, m), n) : undefined;
498
+ const kss = bs.map(b => merged ?? breakKeys(b, env, st, m));
499
+ const at = (xs) => evalE(t.value, { ...env, ...Object.fromEntries(t.names.map((name, i) => [name, xs[i]])) }, st, m);
500
+ const fallback = at(kss.map(ks => ks.at(-1))), cells = new Map();
501
+ // (each key of a part's keys, and after each the stretch up to the next, at its first key: [key, end) with end the
502
+ // next; the last key stands for every key past it)
503
+ const segss = kss.map(ks => {
504
+ const segs = [];
505
+ for (let i = 0; i < ks.length; i++) {
506
+ segs.push([ks[i], i + 1 < ks.length ? ks[i] + 1 : Infinity]);
507
+ if (i + 1 < ks.length && ks[i + 1] > ks[i] + 1)
508
+ segs.push([ks[i] + 1, ks[i + 1]]);
509
+ }
510
+ return segs;
511
+ });
512
+ const go = (i, picked) => {
513
+ if (i < n) {
514
+ for (const g of segss[i])
515
+ go(i + 1, [...picked, g]);
516
+ return;
517
+ }
518
+ const v = at(picked.map(g => g[0]));
519
+ if (v === fallback)
520
+ return;
521
+ if (picked.some(g => g[1] === Infinity))
522
+ throw new RangeError('a write at every tuple holds other than its default at tuples without end');
523
+ const wide = picked.filter(g => g[1] - g[0] > 1).length;
524
+ if (wide > 1 && crossed)
525
+ throw new RangeError('a write at every tuple compares its parts along stretches of keys: its cells there are not one value');
526
+ let size = 1;
527
+ for (const g of picked)
528
+ size *= g[1] - g[0];
529
+ if (size > 1_000_000)
530
+ throw new RangeError('a write at every tuple fills more than a million tuples at once');
531
+ const fill = (j, xs) => {
532
+ if (j === n) {
533
+ cells.set(tupleKey(xs), v);
534
+ return;
535
+ }
536
+ for (let x = picked[j][0]; x < picked[j][1]; x++)
537
+ fill(j + 1, [...xs, x]);
538
+ };
539
+ fill(0, []);
540
+ };
541
+ go(0, []);
542
+ return { cells, default: fallback };
543
+ }
544
+ const tupleKey = (xs) => xs.slice(0, -1).reduceRight((b, a) => cpair(a, b), xs.at(-1));
545
+ // Whether a write at every tuple leaves the map as it is at this step: its value, with every condition that reads no part
546
+ // decided at the request (the flags, the inputs, the state), is the map's own cell at the tuple of the parts, as read
547
+ // (M[k]) or as a member (if(1 <= M[k], 1, 0) where every cell is 0 or 1 already). Then no tuple need be visited.
548
+ function unchanged(t, map, env, st, m) {
549
+ const names = new Set(t.names), reads = (u) => JSON.stringify(u).match(/"name":"([^"]+)"/g)?.some(x => names.has(x.slice(8, -1))) ?? false;
550
+ const cond = (c) => {
551
+ if (!reads(c)) {
552
+ try {
553
+ return evalC(c, env, st, m);
554
+ }
555
+ catch {
556
+ return c;
557
+ }
558
+ }
559
+ if (c.op === 'and' || c.op === 'or') {
560
+ const xs = [];
561
+ for (const y of c.xs) {
562
+ const v = cond(y);
563
+ if (v === (c.op === 'or'))
564
+ return v;
565
+ if (typeof v !== 'boolean')
566
+ xs.push(v);
567
+ }
568
+ return xs.length === 0 ? c.op === 'and' : xs.length === 1 ? xs[0] : { op: c.op, xs };
569
+ }
570
+ return c;
571
+ };
572
+ const term = (e) => { if (e.op !== 'if')
573
+ return e; const c = cond(e.c); return c === true ? term(e.then) : c === false ? term(e.else) : { ...e, c: c }; };
574
+ const v = term(t.value), own = (e) => e.op === 'get' && e.map === map && JSON.stringify(e.key) === JSON.stringify(tuple(t.names.map((name) => ({ op: 'var', name }))));
575
+ if (own(v))
576
+ return true;
577
+ const zeroOne = () => [...(st.maps[map]?.values() ?? [])].every(x => x === 0 || x === 1) && (st.defaults?.[map] ?? m.maps[map]) <= 1;
578
+ return v.op === 'if' && v.then.op === 'const' && v.then.value === 1 && v.else.op === 'const' && v.else.value === 0 && v.c.op === '<=' && v.c.a.op === 'const' && v.c.a.value === 1 && own(v.c.b) && zeroOne();
579
+ }
425
580
  // The machine a runtime steps (with a history, kernel.ts's plain machine), its queries, and the inputs a request carries.
426
581
  function runnable(m) {
427
582
  const h = m.history;
@@ -492,7 +647,7 @@ export function carriedView(m, st, input, rename = map => map, params) {
492
647
  const view = { ...st, maps, defaults }, env0 = { ...params, ...numbersOf(input) };
493
648
  for (const [c, d] of counts) {
494
649
  maps[rename(c)] = new CountCells(x => {
495
- const e1 = { ...env0, [d.j]: x }, n = evalE(d.below, e1, view, m);
650
+ const e1 = d.base ? { ...env0, [d.j]: Math.floor(x / d.base), [d.lo]: x % d.base } : { ...env0, [d.j]: x }, n = evalE(d.below, e1, view, m);
496
651
  let sum = 0;
497
652
  for (let k = 0; k < n; k++)
498
653
  sum = exact(sum + evalE(d.body, { ...e1, [d.key]: k }, view, m));
@@ -510,7 +665,7 @@ export const numbersOf = (input) => Object.fromEntries(Object.entries(input).fil
510
665
  const refused = (m) => `${m.name}: the request fails the rule's assumption, so no proof covers the step it would take`;
511
666
  // The interpreter: persistent (a step leaves the state it was given as it was), so searches can branch from any state.
512
667
  export function interpret(m) {
513
- const { h, plain, carried } = runnable(m);
668
+ const { h, plain, carried } = runnable(m), arity = mapArities(plain);
514
669
  const args = (params, input) => {
515
670
  const env = {};
516
671
  for (const p of m.params)
@@ -584,7 +739,7 @@ export function interpret(m) {
584
739
  const scalars = { ...st.scalars };
585
740
  for (const [name, e] of Object.entries(plain.step.state ?? {}))
586
741
  scalars[name] = evalE(e, env, st, plain);
587
- const writes = Object.entries(plain.step.maps ?? {}).map(([name, w]) => [name, 'each' in w ? writeEvery(w, env, st, plain) : { key: evalE(w.key, env, st, plain), value: evalE(w.value, env, st, plain) }]);
742
+ const writes = Object.entries(plain.step.maps ?? {}).map(([name, w]) => [name, 'each' in w ? writeEvery(w, env, st, plain, arity[name] ?? 1, name) : { key: evalE(w.key, env, st, plain), value: evalE(w.value, env, st, plain) }]);
588
743
  const maps = Object.fromEntries(Object.entries(given.maps).map(([name, cells]) => [name, new Map(cells)]));
589
744
  const defaults = { ...given.defaults };
590
745
  for (const [name, w] of writes)
@@ -609,6 +764,8 @@ export function interpret(m) {
609
764
  const RUNTIME = [
610
765
  ['$n', `function $n(v, what) { if (typeof v !== 'number' || !Number.isSafeInteger(v) || v < 0) throw new RangeError(what + ' must be a natural below 2^53, not ' + v); return v; }`],
611
766
  ['$x', `function $x(v) { if (v > 9007199254740991) throw new RangeError('a value passed 2^53 - 1, past which the proofs over the naturals no longer describe the run'); return v; }`],
767
+ ['$p', `function $p(a, b) { const s = a + b, v = (s % 2 === 0 ? (s / 2) * (s + 1) : s * ((s + 1) / 2)) + b; if (!Number.isSafeInteger(v)) throw new RangeError('a tuple key passed 2^53 - 1, past which the proofs over the naturals no longer describe the run'); return v; }`],
768
+ ['$u', `function $u(z) { const tri = t => (t % 2 === 0 ? (t / 2) * (t + 1) : t * ((t + 1) / 2)); let s = Math.floor((Math.sqrt(8 * z + 1) - 1) / 2); while (s > 0 && tri(s) > z) s--; while (tri(s + 1) <= z) s++; const b = z - tri(s); return [s - b, b]; }`],
612
769
  ['$m', `function $m(v, what) { if (!(v instanceof Map)) throw new RangeError(what + ' must be a Map of naturals'); for (const [key, x] of v) { $n(key, 'a key of ' + what); $n(x, 'a cell of ' + what); } return v; }`],
613
770
  ['$keys', `function $keys(maps, names) { const keys = new Set(); let past = 0; for (const c of Object.values(maps)) for (const key of c.keys()) past = Math.max(past, key + 1); for (const n of names) for (const key of maps[n].keys()) keys.add(key); return [...keys, past]; }`],
614
771
  ['$breaks', `function $breaks(maps, reads, cmps) { const p = new Set([0]); for (const [n, d, minus] of reads) { for (const s of maps[n].keys()) { if (minus) p.add(s + d); else if (s >= d) p.add(s - d); } if (minus) p.add(d); } for (const [v, d, minus] of cmps) { if (minus) { p.add(v + d); p.add(d); } else if (v >= d) p.add(v - d); } const keys = new Set(); for (const q of p) for (let i = -1; i <= 2; i++) if (q + i >= 0) keys.add(q + i); const sorted = [...keys].sort((a, b) => a - b); sorted.push(sorted[sorted.length - 1] + 1); return sorted; }`],
@@ -649,8 +806,16 @@ function joinOf(c, k, k1) {
649
806
  }
650
807
  return undefined;
651
808
  }
652
- export function compileJs(m) {
809
+ export function compileJs(m) { return compileJsMode(m, false); }
810
+ // fastStep keeps the input state persistent. Its fork can wait until every
811
+ // precondition and right-hand side has been evaluated, just before the writes.
812
+ function compileJsMode(m, persistent) {
653
813
  const { h, plain, queries, carried } = runnable(m);
814
+ // (a condition or a write at every key over a tuple key: the interpreter decides those, part by part)
815
+ const atEvery = [...Object.values(plain.step.flags ?? {}).filter(c => c.op === 'all'), ...Object.values(plain.step.maps ?? {}).filter(w => 'each' in w)];
816
+ const arity = mapArities(plain);
817
+ if (JSON.stringify(atEvery).includes('"op":"tup"') || Object.entries(plain.step.maps ?? {}).some(([map, w]) => 'each' in w && (arity[map] ?? 1) > 1))
818
+ throw new Error(`${m.name}: compileJs takes no tuple key at every key (interpret runs it)`);
654
819
  const id = (name) => JSON.stringify(name);
655
820
  const flags = Object.keys(plain.step.flags ?? {}), carriedMaps = m.inputMaps ?? [], fns = Object.keys(m.fns ?? {});
656
821
  // A key bound by a quantified flag or a write at every key is the JS parameter k (k1, k2 for a flag's further keys).
@@ -666,6 +831,8 @@ export function compileJs(m) {
666
831
  case 'min': return `Math.min(${ex(e.a)}, ${ex(e.b)})`;
667
832
  case 'max': return `Math.max(${ex(e.a)}, ${ex(e.b)})`;
668
833
  case 'if': return `(${cx(e.c)} ? ${ex(e.then)} : ${ex(e.else)})`;
834
+ case 'tup': return `$p(${ex(e.a)}, ${ex(e.b)})`;
835
+ case 'proj': return `$u(${ex(e.a)})[${e.k}]`;
669
836
  case 'get': {
670
837
  const fn = m.fns && Object.hasOwn(m.fns, e.map) ? m.fns[e.map] : undefined, args = fn?.call ? pairedArgs(e.key, fn.arity) : undefined;
671
838
  if (args)
@@ -750,6 +917,8 @@ export function compileJs(m) {
750
917
  ...(m.assume ? [`if (!${cx(m.assume)}) throw new RangeError(${id(refused(m))});`] : []), `const scalars = {...s, ${Object.entries(plain.step.state ?? {}).map(([name, e]) => `${id(name)}: ${ex(e)}`).join(', ')}};`, ...writes.map(([, w], i) => ('each' in w ? `const write${i} = ${every(w)};` : `const key${i} = ${ex(w.key)}, value${i} = ${ex(w.value)};`)));
751
918
  if (h)
752
919
  lines.push(`const keep = ${cx(h.keep)};`);
920
+ if (persistent)
921
+ lines.push('state = fork(state);');
753
922
  lines.push(...writes.map(([name, w], i) => ('each' in w ? `state.maps[${id(name)}] = write${i}.cells; dft[${id(name)}] = write${i}.d;` : `state.maps[${id(name)}].set(key${i}, value${i});`)));
754
923
  if (h)
755
924
  lines.push(`if (keep) records.push({${h.record.map(f => `${id(f)}: env[${id(f)}]`).join(', ')}});`,
@@ -779,7 +948,8 @@ export function compileFunction(params, body) {
779
948
  // oxlint-disable-next-line typescript/no-implied-eval
780
949
  return new Function(...params, body);
781
950
  }
782
- export const loadJs = (m) => compileFunction([], `${compileJs(m).replace(/^export function/gm, 'function')}\nreturn {init, fork, step}`)();
951
+ export const loadJs = (m) => loadJsMode(m, false);
952
+ const loadJsMode = (m, persistent) => compileFunction([], `${compileJsMode(m, persistent).replace(/^export function/gm, 'function')}\nreturn {init, fork, step}`)();
783
953
  // The interpreter's step (persistent: a copy of the state each) through loadJs's, several times faster, a request's counts
784
954
  // given to it as maps the request carries (carriedView's, each cell its sum when read); none with a history, or where the
785
955
  // generator refuses the machine.
@@ -789,14 +959,14 @@ export function fastStep(m) {
789
959
  try {
790
960
  if (m.history)
791
961
  return undefined;
792
- js = loadJs({ ...m, counts: undefined, inputMaps: [...m.inputMaps ?? [], ...cs] });
962
+ js = loadJsMode({ ...m, counts: undefined, inputMaps: [...m.inputMaps ?? [], ...cs] }, true);
793
963
  }
794
964
  catch {
795
965
  return undefined;
796
966
  }
797
967
  return (params, st, input) => {
798
968
  const view = cs.length ? carriedView(m, st, input, undefined, params).maps : {};
799
- return js.step(params, js.fork(st), cs.length ? { ...input, ...Object.fromEntries(cs.map(c => [c, view[c]])) } : input);
969
+ return js.step(params, st, cs.length ? { ...input, ...Object.fromEntries(cs.map(c => [c, view[c]])) } : input);
800
970
  };
801
971
  }
802
972
  const cross = (as, f) => as.flatMap(a => f(a.value).map(b => ({ path: [...a.path, ...b.path], value: b.value })));
@@ -809,6 +979,8 @@ function symE(e, s) {
809
979
  case 'add': return cross(symE(e.a, s), a => symE(e.b, s).map(b => ({ path: b.path, value: add(a, b.value) })));
810
980
  case 'mul': return symE(e.a, s).map(a => ({ path: a.path, value: scale(a.value, e.k) }));
811
981
  case 'prod': throw new Error('a product of two terms: kernel/prove.ts proves with products, this prover does not');
982
+ case 'tup':
983
+ case 'proj': throw new Error('a tuple key: kernel/prove.ts proves with tuples, this prover does not');
812
984
  case 'sub': // truncated at 0, as on naturals
813
985
  return cross(symE(e.a, s), a => symE(e.b, s).flatMap(b => [
814
986
  { path: [...b.path, ...le(b.value, a)], value: sub(a, b.value) },
@@ -23,7 +23,7 @@
23
23
  // run with its loops accelerated, checked as the rest are. A large closure goal (a program of many locations, whose
24
24
  // body reads every rule) is closed by the set's parts (`cases`): each part's goal at its location, the location
25
25
  // substituted and the constants folded, which leaves only that location's rules (kernel.ts's checkRecurCases).
26
- import { n as K, same as eq, seeded, walkOnce, x as V } from "./machine.js";
26
+ import { cpair, cunpair, n as K, same as eq, seeded, walkOnce, x as V } from "./machine.js";
27
27
  import { caseGoals, checkRecur, checkRecurCases, coverGoal, loopMachine, recurGoal, substC, trueC } from "../kernel/kernel.js";
28
28
  import { clock, counted, grow, realModels } from "../kernel/prove.js";
29
29
  import { work } from "./solver.js";
@@ -64,6 +64,8 @@ function simpE0(e) {
64
64
  }
65
65
  case 'if': return ite(simpC(e.c), simpE(e.then), simpE(e.else));
66
66
  case 'get': return { op: 'get', map: e.map, key: simpE(e.key) };
67
+ case 'tup': return { op: 'tup', a: simpE(e.a), b: simpE(e.b) };
68
+ case 'proj': return { op: 'proj', k: e.k, a: simpE(e.a) };
67
69
  }
68
70
  }
69
71
  // An and's (an or's) parts simplified, its nested and-s (or-s) walked in place, each part once (x ∧ x is x): the parts
@@ -146,6 +148,9 @@ class Overflow extends Error {
146
148
  const BIG = 2 ** 48;
147
149
  const big = (x) => { if (x > BIG)
148
150
  throw new Overflow(); return x; };
151
+ // (two parts summing below 2^24 pair below BIG)
152
+ const bigPair = (x, y) => { if (x + y >= 2 ** 24)
153
+ throw new Overflow(); return cpair(x, y); };
149
154
  function cE(e) {
150
155
  switch (e.op) {
151
156
  case 'var': {
@@ -185,6 +190,14 @@ function cE(e) {
185
190
  return env => (c(env) ? a(env) : b(env));
186
191
  }
187
192
  case 'get': return () => 0;
193
+ case 'tup': {
194
+ const a = cE(e.a), b = cE(e.b);
195
+ return env => bigPair(a(env), b(env));
196
+ }
197
+ case 'proj': {
198
+ const a = cE(e.a), k = e.k;
199
+ return env => cunpair(a(env))[k];
200
+ }
188
201
  }
189
202
  }
190
203
  function cC(c) {
@@ -0,0 +1,61 @@
1
+ // The checker imports the original module; only its injected database client is replaced.
2
+ import {openSync, readSync, writeSync} from 'node:fs'
3
+ import {pathToFileURL} from 'node:url'
4
+ const input = openSync(process.argv[2], 'r'), output = openSync(process.argv[3], 'w')
5
+ let pending = '', config, mod, next = 0
6
+ const objects = new Map()
7
+ function line() { for (;;) { const i = pending.indexOf('\n'); if (i >= 0) { const s = pending.slice(0, i); pending = pending.slice(i + 1); return s } const b = Buffer.alloc(65536), n = readSync(input, b, 0, b.length, null); if (!n) return; pending += b.subarray(0, n).toString() } }
8
+ const decode = x => x && 'in' in x ? x.in : x && x.none ? null : undefined
9
+ const tag = x => typeof x === 'number' ? {n: String(x)} : typeof x === 'string' ? {s: x} : x === undefined ? null : x
10
+ async function run(q) {
11
+ if (q.op === 'hello') { config = q; mod = await import(pathToFileURL(q.path).href); return {ok: true} }
12
+ const leaf = config.leaves.find(l => l.orm), meta = leaf?.orm
13
+ if (!leaf) throw Error('ORM table missing')
14
+ if (q.op === 'new' || q.op === 'at') {
15
+ const rows = new Map()
16
+ const state = q.state ?? {}
17
+ if (Object.keys(state).some(k => k !== leaf.name)) throw Error('unexpected state field')
18
+ const cells = state[leaf.name] ?? {}
19
+ if (!cells || typeof cells !== 'object' || Array.isArray(cells)) throw Error('invalid ORM table')
20
+ const fields = meta.fields.filter(f => f.name !== meta.key)
21
+ for (const [k, cell] of Object.entries(cells)) {
22
+ if (!cell || typeof cell !== 'object' || Array.isArray(cell) || Object.keys(cell).length !== fields.length || fields.some(f => !Object.hasOwn(cell, f.name))) throw Error('invalid ORM cell fields')
23
+ const row = Object.create(null)
24
+ row[meta.key] = leaf.key === 'num' ? Number(k) : k
25
+ for (const f of fields) row[f.name] = f.t.k === 'int' ? Number(cell[f.name]) : cell[f.name]
26
+ rows.set(k, row)
27
+ }
28
+ const id = ++next; objects.set(id, {rows, services: new Map()}); return {id}
29
+ }
30
+ if (q.op === 'coverage') return {hit: []}
31
+ const obj = objects.get(q.id); if (!obj) throw Error('unknown object')
32
+ const {rows, services} = obj
33
+ if (q.op === 'get') {
34
+ const cells = Object.create(null)
35
+ for (const [k, row] of rows) { const c = Object.create(null); for (const f of meta.fields) if (f.name !== meta.key) c[f.name] = f.t.k === 'int' ? String(row[f.name]) : row[f.name]; cells[k] = c }
36
+ return {state: {[leaf.name]: cells}}
37
+ }
38
+ if (q.op === 'call') {
39
+ const lookup = where => rows.get(String(where[meta.key]))
40
+ const repo = {
41
+ async findUnique({where}) { const row = lookup(where); return row ? {...row} : null },
42
+ async findOneBy(where) { const row = lookup(where); return row ? {...row} : null },
43
+ async create({data}) { const k = String(data[meta.key]); if (rows.has(k)) throw Error('duplicate key'); rows.set(k, {...data}); return {...data} },
44
+ async update({where, data}) { const row = lookup(where); if (!row) throw Error('missing row'); Object.assign(row, data); return {...row} },
45
+ async save(data) { const k = String(data[meta.key]); rows.set(k, {...data}); return {...data} },
46
+ }
47
+ const db = config.kind === 'prisma' ? {[config.model[0].toLowerCase() + config.model.slice(1)]: repo} : repo
48
+ try {
49
+ const parts = q.m.split('.')
50
+ let receiver, fn
51
+ if (parts.length === 1) fn = mod[parts[0]]
52
+ else if (parts.length === 2) {
53
+ if (!services.has(parts[0])) services.set(parts[0], new mod[parts[0]]())
54
+ receiver = services.get(parts[0]); fn = receiver[parts[1]]
55
+ } else throw Error('invalid entry')
56
+ return {out: tag(await fn.call(receiver, db, ...q.a.map(a => decode(a[1]))))}
57
+ } catch (e) { return {err: String(e)} }
58
+ }
59
+ throw Error(`unknown operation ${q.op}`)
60
+ }
61
+ for (;;) { const l = line(); if (l === undefined) break; let out; try { out = await run(JSON.parse(l)) } catch (e) { out = {error: String(e)} } writeSync(output, JSON.stringify(out) + '\n') }
@@ -0,0 +1,5 @@
1
+ model Account {
2
+ id String @id
3
+ amount Int
4
+ active Boolean
5
+ }