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
@@ -28,14 +28,26 @@ import * as I from "./extract-ir.js";
28
28
  import { Refusal, mergeOps, mergeWrites } from "./extract-read.js";
29
29
  import { fromModel } from "./extract.js";
30
30
  import { nonneg } from "./extract-print.js";
31
- import { HarnessFailure, Outside, constantsOf, draw, drive, noEvidence, retried } from "./extract-check.js";
31
+ import { HarnessFailure, Outside, constantsOf, draw, drive, evalTerm, noEvidence, retried, tiesIn } from "./extract-check.js";
32
+ // Bitwise and, or and xor of two naturals below 2^53 (JavaScript's operators stop at 32 bits).
33
+ const and = (a, b) => { let out = 0; for (let p = 1; a > 0 && b > 0; p *= 2, a = Math.floor(a / 2), b = Math.floor(b / 2))
34
+ if (a % 2 && b % 2)
35
+ out += p; return out; };
36
+ const or = (a, b) => a + b - and(a, b);
37
+ const xor = (a, b) => a + b - 2 * and(a, b);
38
+ // (a while loop whose first item is read from the other end: its passes run back from the last)
39
+ class Backward extends Error {
40
+ }
41
+ // (a while loop whose first item is read by an order other than the collection's places: its passes over that order)
42
+ class Ranked extends Error {
43
+ }
32
44
  // A string that is one of a choice's literals on every path (a literal, or literals by a condition): the choice's.
33
45
  const asChoice = (k, vs) => { if (k.op === 'slit')
34
46
  return vs.includes(k.value) ? I.llit(k.value, vs) : undefined; if (k.op !== 'kite')
35
47
  return undefined; const a = asChoice(k.a, vs), b = asChoice(k.b, vs); return a && b ? I.lite(k.c, a, b) : undefined; };
36
48
  const where = (x) => x.p || '?';
37
49
  const refuse = (x, what) => { throw new Refusal(typeof x === 'string' ? x : where(x), what); };
38
- const RESERVED = new Set(['rule', 'nat', 'int', 'bool', 'when', 'min', 'max', 'all', 'any', 'not', 'yes', 'no', 'lit', 'str', 'record', 'oneOf', 'intern', 'Int', 'forall']);
50
+ const RESERVED = new Set(['rule', 'nat', 'int', 'bool', 'when', 'min', 'max', 'all', 'any', 'not', 'yes', 'no', 'lit', 'str', 'record', 'oneOf', 'intern', 'Int', 'forall', 'everyKey']);
39
51
  const keyV = (v) => JSON.stringify(v, (_, x) => (x instanceof Map ? [...x.entries()] : x));
40
52
  const LANG = { go: 'Go', rust: 'Rust', python: 'Python', c: 'C', cpp: 'C++', ruby: 'Ruby', elixir: 'Elixir', java: 'Java', kotlin: 'Kotlin' };
41
53
  const tyName = (ty) => (ty ? (ty.bits ? `${ty.signed ? 'i' : 'u'}${ty.bits}` : ty.signed ? 'an Instant' : 'a Duration') : 'the number');
@@ -43,7 +55,7 @@ const constOf = (v) => (v.t === 'num' && v.e.op === 'const' ? v.e.v : undefined)
43
55
  // The key a least key's where and by are read at (the printed rule's `.least`'s argument).
44
56
  const LEAST_KEY = 'kl$';
45
57
  // The sorts a type string names (an answer's): int, float, bool, str, a choice of quoted strings, each `| None`.
46
- function sortOfText(s, at) {
58
+ function sortOfText(s, at, lang) {
47
59
  const parts = s.split('|').map(x => x.trim()).filter(Boolean), none = parts.includes('None'), rest = parts.filter(x => x !== 'None');
48
60
  const one = () => {
49
61
  if (rest.length && rest.every(x => /^['"].*['"]$/.test(x)))
@@ -53,6 +65,11 @@ function sortOfText(s, at) {
53
65
  const k = rest[0];
54
66
  if (k === 'int' || k === 'float' || k === 'bool' || k === 'str')
55
67
  return { k };
68
+ if (k === 'datetime' || k === 'datetime-naive' || k === 'datetime-utc') {
69
+ if (lang !== 'python')
70
+ return refuse(at, 'stated datetime values are supported only by the Python harness');
71
+ return { k: 'int', unit: k === 'datetime-utc' ? k : 'datetime-naive' };
72
+ }
56
73
  // (a fixed width, a compiled language's: u32, i64, usize, uint8, int32)
57
74
  const w = /^(u|i|uint|int)(8|16|32|64|128|size)$/.exec(k);
58
75
  if (w)
@@ -98,6 +115,11 @@ export class Stepper {
98
115
  // (inside a fold's pass: the tries outside it, hidden, and how deep)
99
116
  hidden = 0;
100
117
  inFold = 0;
118
+ // (inside a while loop's pass: the collection it takes first items of, from which end; empty: the pass after they ran
119
+ // out; drainSetup: an order read over the state before the step)
120
+ drain;
121
+ drainSetup = 0;
122
+ drainAgain = false;
101
123
  initHeap = new Map();
102
124
  storeMaps = new Map();
103
125
  // The least keys the step reads (an ordered collection's first or last item, its min or max by a key), each once.
@@ -165,11 +187,15 @@ export class Stepper {
165
187
  }
166
188
  // An input of a type: its variables, the value, and how the harness makes it.
167
189
  input(name, t, at, p, role = 'input') {
190
+ if (t.k === 'opaque' && t.why === '$orm-session' && role === 'input') {
191
+ this.storeDecls.set(name, { ormSession: true });
192
+ return [{ t: 'ext', q: `orm-session:${name}`, text: name }, { k: 'store', name }];
193
+ }
168
194
  const s = this.scalar(t);
169
195
  if (s) {
170
196
  const v = this.newVar(name, s, role);
171
197
  this.typed(v, t, role);
172
- return [this.valueOf(v), { k: 'in', name: v.name, z: zeroRaw(s), ...(t.k === 'float' ? { float: true } : {}), ...(t.k === 'choice' && t.sym ? { sym: true } : {}), ...(t.k === 'str' && t.bytes ? { bytes: true } : {}) }];
198
+ return [this.timeField(this.valueOf(v), t, true, at), { k: 'in', name: v.name, z: zeroRaw(s), ...(t.k === 'int' && t.unit?.startsWith('datetime-') ? { time: t.unit } : {}), ...(t.k === 'float' ? { float: true } : {}), ...(t.k === 'choice' && t.sym ? { sym: true } : {}), ...(t.k === 'str' && t.bytes ? { bytes: true } : {}) }];
173
199
  }
174
200
  if (t.k === 'opt') {
175
201
  if (t.of.k === 'rec') {
@@ -181,8 +207,8 @@ export class Stepper {
181
207
  if (!inner)
182
208
  return refuse(at, `${name}: an optional ${this.why(t.of)}`);
183
209
  const v = this.newVar(name, inner, role, `0 where ${name} is None`), none = this.newVar(`${name}_none`, { k: 'bool' }, role, `whether ${name} is None`);
184
- this.typed(v, t.of, role);
185
- return [{ t: 'opt', has: I.not(I.bvar(none.name)), v: this.valueOf(v) }, { k: 'opt', none: none.name, v: { k: 'in', name: v.name, z: zeroRaw(inner), ...(t.of.k === 'float' ? { float: true } : {}), ...(t.of.k === 'str' && t.of.bytes ? { bytes: true } : {}) } }];
210
+ this.typed(v, t.of, role, t.of.k === 'int' && t.of.unit?.startsWith('datetime-') ? I.and(this.sel, I.not(I.bvar(none.name))) : this.sel);
211
+ return [{ t: 'opt', has: I.not(I.bvar(none.name)), v: this.timeField(this.valueOf(v), t.of, true, at) }, { k: 'opt', none: none.name, v: { k: 'in', name: v.name, z: zeroRaw(inner), ...(t.of.k === 'int' && t.of.unit?.startsWith('datetime-') ? { time: t.of.unit } : {}), ...(t.of.k === 'float' ? { float: true } : {}), ...(t.of.k === 'str' && t.of.bytes ? { bytes: true } : {}) } }];
186
212
  }
187
213
  if (t.k === 'none')
188
214
  return [{ t: 'none' }, { k: 'dflt' }];
@@ -217,6 +243,13 @@ export class Stepper {
217
243
  // (the request's arguments kept though no term reads them: opts.keep)
218
244
  kept = new Set();
219
245
  typed(v, t, role, sel = this.sel) {
246
+ if ('k' in t && t.k === 'int' && t.unit?.startsWith('datetime-') && role !== 'state') {
247
+ const out = I.or(I.cmp('<', I.nvar(v.name), I.num(-62_135_596_800_000)), I.cmp('<', I.num(253_402_300_799_999), I.nvar(v.name)));
248
+ if (role === 'param')
249
+ this.paramsOut.push(I.and(sel, out));
250
+ else
251
+ this.refusals.push(I.and(sel, out));
252
+ }
220
253
  if ('k' in t && t.k === 'str' && t.bytes)
221
254
  this.bytesVars.add(v.name);
222
255
  const ty = 'k' in t ? this.intTy(t) : t;
@@ -538,6 +571,512 @@ export class Stepper {
538
571
  q = this.assume(q, I.not(end('__returned').e));
539
572
  return { live: q, rets: [[{ ...ret, pc: [...q0.pc, end('__returned').e] }, end('__ret')]] };
540
573
  }
574
+ // --- while loops over the state's ordered collections, read as folds ------------------------------------------------
575
+ // A while loop whose passes take the first item of one collection of the state in its own order (a list's places:
576
+ // xs[0], pop(0), popleft(); a dict's keys: min(d), or from the other end: xs[-1], pop(), max(d)), each pass that goes
577
+ // on taking it out, the last one (where the loop ends) free to keep it with its fields written. Then its passes are a
578
+ // fold over the collection's keys in that order, as a for loop over the list is (core/extract-step.ts's forStmt): the
579
+ // pass at a key holds its item, each pass where the condition holds runs the body, the first where it doesn't (or a
580
+ // break, a return, a failure) ends the loop, and every request carries the run the passes compute. After the loop
581
+ // each item the passes reached is as its pass left it (one write at every key); where the passes ran out of items
582
+ // the condition is read once more with the collection empty. Exact for every number of items; refused: a pass that
583
+ // keeps its item and goes on (the next would take it again), and any other write of the state in a pass.
584
+ whileStmt(s, p, back = false) {
585
+ if (s.els?.length)
586
+ return refuse(s, 'a loop\'s else');
587
+ if (this.inFold)
588
+ return refuse(s, 'a loop inside a loop\'s pass (one fold at a time)');
589
+ const q0 = p, i = I.nvar(PASS), body = s.body, own = assigned(body);
590
+ const run = this.newVar(`loop$${this.folds.length}`, { k: 'num' }, 'input', undefined, false).name;
591
+ const cin = back ? I.add(i, I.num(1)) : i;
592
+ const fields = [], init = {}, locals = new Map(q0.locals);
593
+ for (const n of [...own].filter(x => q0.locals.has(x))) {
594
+ if (FLAGS.includes(n))
595
+ refuse(s, `${n}: a local the loop carries named as a fold's own values are`);
596
+ const v0 = q0.locals.get(n), srt = sortOfV(v0) ?? refuse(s, `${n}: ${v0.t === 'opaque' ? v0.why : `a ${v0.t}`}, carried by the loop (the subset reads a loop's numbers, booleans and choices)`);
597
+ fields.push({ name: n, sort: srt, role: 'state' });
598
+ init[n] = termOfV(v0, s);
599
+ locals.set(n, cellV(run, cin, n, srt, v0.t === 'num' ? v0.ty : undefined));
600
+ }
601
+ const at = (n, x) => cellV(run, x, n, fields.find(v => v.name === n).sort);
602
+ const saved = { tries: this.tries, fails: this.fails, failPaths: this.failPaths, refusals: this.refusals.length, edges: this.edges.length };
603
+ this.hidden += this.tries.length;
604
+ this.tries = [];
605
+ this.fails = [];
606
+ this.failPaths = [];
607
+ this.inFold++;
608
+ const dr = { i, back, entry: q0 };
609
+ this.drain = dr;
610
+ let f, c, b1;
611
+ try {
612
+ ;
613
+ [c, b1] = this.truth(s.c, { ...q0, pc: [], locals, cont: undefined });
614
+ f = c.op === 'const' && !c.v ? { rets: [] } : this.block(body, this.assume(b1, c));
615
+ }
616
+ catch (e) {
617
+ if (e instanceof Backward || e instanceof Ranked) {
618
+ this.vars.delete(run);
619
+ this.tries = saved.tries;
620
+ this.hidden -= saved.tries.length;
621
+ this.inFold--;
622
+ this.drain = undefined;
623
+ this.fails = saved.fails;
624
+ this.failPaths = saved.failPaths;
625
+ this.refusals.splice(saved.refusals);
626
+ return e instanceof Ranked ? this.whileRank(s, p) : this.whileStmt(s, p, true);
627
+ }
628
+ throw e;
629
+ }
630
+ finally {
631
+ if (this.drain === dr) {
632
+ this.tries = saved.tries;
633
+ this.hidden -= saved.tries.length;
634
+ this.inFold--;
635
+ this.drain = undefined;
636
+ }
637
+ }
638
+ const d = dr.map ?? refuse(s, 'a while loop that takes no item of a collection of the state (the subset reads a loop over a list the request carries, or one whose passes take the first items of the state\'s list or dict)');
639
+ const o0 = q0.heap.get(d.id), held = this.baseCell(o0.decl, { op: 'num', e: i }).has;
640
+ // Each way out of a pass: what it wrote of its item (at the pass's key, nothing else of the state), and whether it
641
+ // took it out; a pass that goes on (to the next) must have.
642
+ const brks = (f.brk ?? []).filter(x => !x.cont), goes = [...(f.brk ?? []).filter(x => x.cont), ...(f.live ? [f.live] : [])];
643
+ const itemOf = (e) => {
644
+ for (const [id, o] of e.heap) {
645
+ const b = q0.heap.get(id);
646
+ if (!b || b === o || !('origin' in o) || o.origin !== 'state' || keyV(o) === keyV(b))
647
+ continue;
648
+ if (id !== d.id)
649
+ refuse(s, 'a loop whose passes write the state other than the items they take (the subset reads a loop over the state as its passes over a collection\'s items, each taking its own)');
650
+ }
651
+ const o = e.heap.get(d.id);
652
+ if (o.pre?.length || (o.w && !I.same(o.w.key, { op: 'num', e: i })))
653
+ refuse(s, `a pass of the loop writes an item of ${d.name} other than the one it takes`);
654
+ const base = this.baseCell(o0.decl, { op: 'num', e: i });
655
+ return o.w ? { w: I.T, has: o.w.has, vals: o.w.vals } : { w: I.F, has: base.has, vals: base.vals };
656
+ };
657
+ // (a pass that keeps its item where the condition holds again: the code's next pass takes the same item, the rule's
658
+ // the next one; the rule refuses there, which the check sees where the code reaches it)
659
+ // (and a pass that keeps its item ends the loop: the code's next condition reads that item again, false or refused)
660
+ let kept = I.F;
661
+ for (const e of goes) {
662
+ const it = itemOf(e);
663
+ if (it.has.op === 'const' && !it.has.v)
664
+ continue;
665
+ kept = I.or(kept, I.and(...e.pc, it.has));
666
+ this.drain = dr;
667
+ this.drainAgain = true;
668
+ try {
669
+ const [again] = this.truth(s.c, e);
670
+ const w = I.and(this.cond(e), it.has, again);
671
+ if (!(w.op === 'const' && !w.v)) {
672
+ this.refusals.push(w);
673
+ this.notes.add(`${s.p}: a pass of the loop over ${d.name} that keeps its item where the condition holds again is refused (the next pass would take it again)`);
674
+ }
675
+ }
676
+ finally {
677
+ this.drain = undefined;
678
+ this.drainAgain = false;
679
+ }
680
+ }
681
+ const F = I.or(...this.fails), Rf = I.or(...this.refusals.splice(saved.refusals));
682
+ this.fails = saved.fails;
683
+ this.failPaths = saved.failPaths;
684
+ if (this.edges.length > saved.edges)
685
+ refuse(s, 'a loop whose passes reach the edge of a fixed-width type');
686
+ const on = this.join(goes, s), brk = this.join(brks, s), retJ = this.join(f.rets.map(r => r[0]), s);
687
+ const pc = (x) => I.and(...x.pc), R = I.or(...f.rets.map(([x]) => pc(x))), Br = I.or(...brks.map(pc));
688
+ const no = (x) => x.op === 'const' && !x.v;
689
+ const flag = (n) => { fields.push({ name: n, sort: { k: 'bool' }, role: 'state' }); init[n] = { s: 'bool', e: I.F }; };
690
+ flag('__done');
691
+ const doneIn = at('__done', cin).e, idle = I.or(doneIn, I.not(held)), runs = I.and(I.not(idle), c);
692
+ const step = {};
693
+ for (const v of fields.filter(x => !FLAGS.includes(x.name))) {
694
+ const val = (x) => x?.locals.get(v.name);
695
+ const nx = brk && on ? this.ite(Br, val(brk), val(on), s) : val(brk) ?? val(on) ?? locals.get(v.name);
696
+ if (sortOfV(nx)?.k !== v.sort.k)
697
+ refuse(s, `${v.name}: ${nx.t === 'opaque' ? nx.why : `a ${nx.t}`} after a pass of the loop`);
698
+ step[v.name] = iteTerm(runs, termOfV(nx, s), termOfV(locals.get(v.name), s));
699
+ }
700
+ step.__done = { s: 'bool', e: I.or(doneIn, I.and(I.not(idle), I.or(I.not(c), R, Br, F, Rf, kept))) };
701
+ // (the item each pass leaves: whether it wrote it, held or taken out, and its fields, at the pass's own place)
702
+ const ways = [...(brk ? [[Br, brk]] : []), ...(retJ ? [[R, retJ]] : [])], lastOn = on ? itemOf(on) : undefined;
703
+ let item = lastOn ?? { w: I.F, has: I.F, vals: this.baseCell(o0.decl, { op: 'num', e: i }).vals };
704
+ for (const [w, e] of ways) {
705
+ const it = itemOf(e);
706
+ item = { w: I.bite(w, it.w, item.w), has: I.bite(w, it.has, item.has), vals: new Map([...item.vals].map(([fn, v]) => [fn, this.ite(w, it.vals.get(fn), v, s)])) };
707
+ }
708
+ const wf = (n, srt, t) => { fields.push({ name: n, sort: srt, role: 'state' }); init[n] = termOfV(zeroOf(srt), s); step[n] = t; };
709
+ wf('__w', { k: 'bool' }, { s: 'bool', e: I.and(runs, item.w) });
710
+ wf('__h', { k: 'bool' }, { s: 'bool', e: item.has });
711
+ const like = [];
712
+ for (const fd of o0.decl.fields) {
713
+ wf(`__f__${fd.name}`, fd.sort, termOfV(item.vals.get(fd.name), s));
714
+ like.push([`__f__${fd.name}`, `${d.name}.${fd.name}`]);
715
+ }
716
+ let retV;
717
+ if (!no(R)) {
718
+ retV = this.join(f.rets.map(([r, v]) => ({ ...r, locals: new Map([['__ret', v]]) })), s).locals.get('__ret');
719
+ const srt = sortOfV(retV) ?? refuse(s, `a loop that returns ${retV.t === 'opaque' ? retV.why : `a ${retV.t}`} (the subset reads a loop's return of a number, a boolean or a choice)`);
720
+ flag('__returned');
721
+ step.__returned = { s: 'bool', e: I.or(at('__returned', cin).e, I.and(runs, R)) };
722
+ fields.push({ name: '__ret', sort: srt, role: 'state' });
723
+ init.__ret = termOfV(zeroOf(srt), s);
724
+ step.__ret = iteTerm(I.and(runs, R), termOfV(retV, s), termOfV(at('__ret', cin), s));
725
+ }
726
+ if (!no(F)) {
727
+ flag('__failed');
728
+ step.__failed = { s: 'bool', e: I.or(at('__failed', cin).e, I.and(runs, F)) };
729
+ }
730
+ if (!no(Rf)) {
731
+ flag('__refused');
732
+ step.__refused = { s: 'bool', e: I.or(at('__refused', cin).e, I.and(runs, Rf)) };
733
+ }
734
+ // (the passes: the collection's places up to its last, as a for loop over it reads them)
735
+ const last = this.least(o0, s, k => this.baseCell(o0.decl, k).has, k => [{ e: k.e, desc: true }]);
736
+ const len = I.nite(last.some, I.add(last.key, I.num(1)), I.num(0)), end = back ? I.num(0) : len;
737
+ this.folds.push({ list: d.name, run, fields, init, step, len, state: true, ...(back ? { back: true } : {}), loop: { like } });
738
+ // After the loop: each running value its cell at the end, the collection as the passes left it.
739
+ let q = { ...q0, locals: new Map(q0.locals), heap: new Map(q0.heap), called: [...new Set([q0.called, ...f.rets.map(r => r[0].called), ...(on ? [on.called] : []), ...(brk ? [brk.called] : [])].flat())] };
740
+ for (const v of fields)
741
+ if (!FLAGS.includes(v.name) && !v.name.startsWith('__'))
742
+ q.locals.set(v.name, at(v.name, end));
743
+ const k = I.nvar('k$'), ko = back ? k : I.add(k, I.num(1)), base = this.baseCell(o0.decl, { op: 'num', e: k });
744
+ const wrote = cellV(run, ko, '__w', { k: 'bool' }).e;
745
+ q.heap.set(d.id, { ...o0, ew: { key: { op: 'num', e: k }, has: I.bite(wrote, cellV(run, ko, '__h', { k: 'bool' }).e, base.has), vals: new Map([...base.vals].map(([fn, v]) => [fn, this.ite(wrote, cellV(run, ko, `__f__${fn}`, o0.decl.fields.find(x => x.name === fn).sort), v, s)])) } });
746
+ const endDone = at('__done', end).e;
747
+ if (!no(F)) {
748
+ if (this.tries.length)
749
+ refuse(s, 'a failure in a loop inside a try');
750
+ this.fail(q, at('__failed', end).e, s, `a failure in a pass of the loop over ${d.name}`, null);
751
+ q = this.assume(q, I.not(at('__failed', end).e));
752
+ }
753
+ if (!no(Rf)) {
754
+ this.refusals.push(I.and(this.cond(q), at('__refused', end).e));
755
+ q = this.assume(q, I.not(at('__refused', end).e));
756
+ }
757
+ const rets = [];
758
+ if (!no(R)) {
759
+ rets.push([{ ...q, pc: [...q0.pc, at('__returned', end).e] }, at('__ret', end)]);
760
+ q = this.assume(q, I.not(at('__returned', end).e));
761
+ }
762
+ // Where the passes ran out of items (none ended the loop): the condition once more, the collection empty.
763
+ const ranOut = this.assume(q, I.not(endDone)), stopped = this.assume(q, endDone);
764
+ this.drain = { i, back, entry: q0, empty: d.name };
765
+ let g, c2, q2;
766
+ try {
767
+ ;
768
+ [c2, q2] = this.truth(s.c, ranOut);
769
+ g = c2.op === 'const' && !c2.v ? { rets: [] } : this.block(body, this.assume(q2, c2));
770
+ }
771
+ finally {
772
+ this.drain = undefined;
773
+ }
774
+ if (g.live || (g.brk ?? []).some(x => x.cont))
775
+ this.refuseWhere(g.live ?? (g.brk ?? []).find(x => x.cont), I.T, s, `the loop over ${d.name} goes on with it empty (it never ends)`);
776
+ const after = this.join([stopped, ...(c2.op === 'const' && c2.v ? [] : [this.assume(q2, I.not(c2))]), ...(g.brk ?? []).filter(x => !x.cont)], s);
777
+ return { ...(after ? { live: after } : {}), rets: [...rets, ...g.rets] };
778
+ }
779
+ // A while loop whose passes take the first items of the state's lists by an order of their own (min or max by a
780
+ // key, a heap's top): its passes are a fold of an unknown length, each one's item the one at its count in the order.
781
+ // Every request carries the run (the locals, and for each list how many of its items the passes took out, whether
782
+ // they hold the next and its fields as they left it), each list's held keys in the order (`ord`: increasing, each
783
+ // held, and every held key at its place `rk`, the place's item tying it by the order), and the run is assumed to be
784
+ // the one the passes compute: each pass's start where the condition holds and none ended the loop, the length the
785
+ // first where not. After the loop, each list's items before the count are out and the one at it has the fields the
786
+ // passes left (one write at every key). Two items that tie under the order are outside the claim (which of them comes
787
+ // first is the code's: Python's list order, a heap's layout), an edge the check counts apart.
788
+ whileRank(s, p) {
789
+ const q0 = p, run = this.newVar(`loop$${this.folds.length}`, { k: 'num' }, 'input', undefined, false).name, i = I.nvar(PASS);
790
+ const body = s.body, own = assigned(body);
791
+ const fields = [], init = {}, locals = new Map(q0.locals);
792
+ for (const n of [...own].filter(x => q0.locals.has(x))) {
793
+ if (FLAGS.includes(n))
794
+ refuse(s, `${n}: a local the loop carries named as a fold's own values are`);
795
+ const v0 = q0.locals.get(n), srt = sortOfV(v0) ?? refuse(s, `${n}: ${v0.t === 'opaque' ? v0.why : `a ${v0.t}`}, carried by the loop (the subset reads a loop's numbers, booleans and choices)`);
796
+ fields.push({ name: n, sort: srt, role: 'state' });
797
+ init[n] = termOfV(v0, s);
798
+ locals.set(n, cellV(run, i, n, srt, v0.t === 'num' ? v0.ty : undefined));
799
+ }
800
+ const at = (n, x = i) => cellV(run, x, n, fields.find(v => v.name === n).sort);
801
+ const saved = { tries: this.tries, fails: this.fails, failPaths: this.failPaths, refusals: this.refusals.length, edges: this.edges.length };
802
+ this.hidden += this.tries.length;
803
+ this.tries = [];
804
+ this.fails = [];
805
+ this.failPaths = [];
806
+ this.inFold++;
807
+ const dr = { i, back: false, entry: q0, rank: new Map(), run };
808
+ this.drain = dr;
809
+ let f, c;
810
+ try {
811
+ const [c0, b1] = this.truth(s.c, { ...q0, pc: [], locals, cont: undefined });
812
+ c = c0;
813
+ f = c.op === 'const' && !c.v ? { rets: [] } : this.block(body, this.assume(b1, c));
814
+ }
815
+ finally {
816
+ this.tries = saved.tries;
817
+ this.hidden -= saved.tries.length;
818
+ this.inFold--;
819
+ this.drain = undefined;
820
+ }
821
+ const rk = dr.rank;
822
+ // What a pass leaves of each list (each way out of it): the item taken out, or held with its fields; one that goes
823
+ // on and keeps it where the condition holds again is refused (the code's next pass takes it again).
824
+ const ends = [...(f.brk ?? []), ...(f.live ? [f.live] : []), ...f.rets.map(r => r[0])], goes = [...(f.brk ?? []).filter(x => x.cont), ...(f.live ? [f.live] : [])];
825
+ for (const e of ends) {
826
+ for (const [id, o] of e.heap) {
827
+ const b = q0.heap.get(id);
828
+ if (!b || b === o || !('origin' in o) || o.origin !== 'state' || keyV(o) === keyV(b))
829
+ continue;
830
+ const d = o.k === 'map' ? rk.get(o.decl.name) : undefined;
831
+ if (!d)
832
+ refuse(s, 'a loop whose passes write the state other than the items they take (the subset reads a loop over the state as its passes over a collection\'s items, each taking its own)');
833
+ if (o.pre?.length)
834
+ refuse(s, `a pass of the loop writes two items of ${d.name}`);
835
+ }
836
+ for (const d of rk.values()) {
837
+ const o = e.heap.get(d.id);
838
+ if (o.w && !I.same(o.w.key, d.K))
839
+ refuse(s, `a pass of the loop writes an item of ${d.name} other than the first it takes`);
840
+ const has = o.w ? o.w.has : d.exists, vals = o.w ? o.w.vals : d.view;
841
+ const out = I.and(d.exists, I.not(has)), held = I.and(d.exists, has), L = e.locals = new Map(e.locals);
842
+ // (an item kept must keep the fields its order reads, or the order the run carries is no longer its: refused
843
+ // where a pass changes one)
844
+ if (o.w && d.order)
845
+ for (const fn of orderFields(d.order.by, d.decl)) {
846
+ const a = vals.get(fn), b = d.view.get(fn);
847
+ if (keyV(a) === keyV(b) || !('e' in a) || !('e' in b))
848
+ continue;
849
+ const w = I.and(this.cond(e), d.exists, I.not(a.t === 'num' && b.t === 'num' ? I.cmp('=', a.e, b.e) : a.t === 'bool' && b.t === 'bool' ? I.bite(a.e, b.e, I.not(b.e)) : I.F));
850
+ if (!(w.op === 'const' && !w.v)) {
851
+ this.refusals.push(w);
852
+ this.notes.add(`${s.p}: a pass of the loop over ${d.name} that changes ${fn} (its order) of its item is refused`);
853
+ }
854
+ }
855
+ L.set(`${d.name}__a`, { t: 'num', e: I.nite(out, I.add(d.a, I.num(1)), d.a) });
856
+ L.set(`${d.name}__ld`, { t: 'bool', e: held });
857
+ for (const fd of d.decl.fields)
858
+ L.set(`${d.name}__f__${fd.name}`, this.ite(held, vals.get(fd.name), d.cur.get(fd.name), s));
859
+ if (goes.includes(e)) {
860
+ this.drain = dr;
861
+ this.drainAgain = true;
862
+ try {
863
+ const [again] = this.truth(s.c, e);
864
+ const w = I.and(this.cond(e), held, again);
865
+ if (!(w.op === 'const' && !w.v)) {
866
+ this.refusals.push(w);
867
+ this.notes.add(`${s.p}: a pass of the loop over ${d.name} that keeps its item where the condition holds again is refused (the next pass would take it again)`);
868
+ }
869
+ }
870
+ finally {
871
+ this.drain = undefined;
872
+ this.drainAgain = false;
873
+ }
874
+ }
875
+ }
876
+ }
877
+ const F = I.or(...this.fails), Rf = I.or(...this.refusals.splice(saved.refusals));
878
+ this.fails = saved.fails;
879
+ this.failPaths = saved.failPaths;
880
+ if (this.edges.length > saved.edges)
881
+ refuse(s, 'a loop whose passes reach the edge of a fixed-width type');
882
+ if (!rk.size)
883
+ refuse(s, 'a while loop that takes no item of a collection of the state');
884
+ const like = [], drains = [], kl = { op: 'num', e: I.nvar(LEAST_KEY) };
885
+ for (const d of rk.values()) {
886
+ const add = (n, srt, t) => { fields.push({ name: n, sort: srt, role: 'state' }); init[n] = t; };
887
+ add(`${d.name}__a`, { k: 'num' }, { s: 'num', e: I.num(0) });
888
+ add(`${d.name}__ld`, { k: 'bool' }, { s: 'bool', e: I.F });
889
+ for (const fd of d.decl.fields) {
890
+ add(`${d.name}__f__${fd.name}`, fd.sort, termOfV(zeroOf(fd.sort), s));
891
+ like.push([`${d.name}__f__${fd.name}`, `${d.name}.${fd.name}`]);
892
+ }
893
+ const by = d.order ? this.rankOrder(d)(kl) : refuse(s, `${d.name}: a loop that reads its first item by no order`);
894
+ drains.push({ map: d.name, ord: d.ord, rk: d.rk, held: this.baseCell(d.decl, kl).has, by });
895
+ }
896
+ const brks = (f.brk ?? []).filter(x => !x.cont), on = this.join(goes, s), brk = this.join(brks, s);
897
+ const pc = (x) => I.and(...x.pc), R = I.or(...f.rets.map(([x]) => pc(x))), Br = I.or(...brks.map(pc));
898
+ const no = (x) => x.op === 'const' && !x.v, stops = !(no(R) && no(Br) && no(F) && no(Rf));
899
+ const flag = (n, x) => { fields.push({ name: n, sort: { k: 'bool' }, role: 'state' }); init[n] = { s: 'bool', e: I.F }; return x; };
900
+ const step = {}, done = stops ? flag('__done', I.or(R, Br, F, Rf)) : I.F;
901
+ const doneAt = (x) => (stops ? at('__done', x).e : I.F);
902
+ const retJ = this.join(f.rets.map(r => r[0]), s);
903
+ for (const v of fields.filter(x => !FLAGS.includes(x.name))) {
904
+ const val = (x) => x?.locals.get(v.name);
905
+ const ways = [...(brk && val(brk) ? [[Br, val(brk)]] : []), ...(v.name.includes('__') && retJ && val(retJ) ? [[R, val(retJ)]] : [])];
906
+ let nx = val(on) ?? locals.get(v.name) ?? cellV(run, i, v.name, v.sort);
907
+ for (const [w, x] of ways)
908
+ nx = this.ite(w, x, nx, s);
909
+ if (sortOfV(nx)?.k !== v.sort.k)
910
+ refuse(s, `${v.name}: ${nx.t === 'opaque' ? nx.why : `a ${nx.t}`} after a pass of the loop`);
911
+ step[v.name] = termOfV(nx, s);
912
+ }
913
+ if (stops)
914
+ step.__done = { s: 'bool', e: done };
915
+ if (!no(R)) {
916
+ const retV = this.join(f.rets.map(([r, v]) => ({ ...r, locals: new Map([['__ret', v]]) })), s).locals.get('__ret');
917
+ const srt = sortOfV(retV) ?? refuse(s, `a loop that returns ${retV.t === 'opaque' ? retV.why : `a ${retV.t}`} (the subset reads a loop's return of a number, a boolean or a choice)`);
918
+ flag('__returned', R);
919
+ step.__returned = { s: 'bool', e: R };
920
+ fields.push({ name: '__ret', sort: srt, role: 'state' });
921
+ init.__ret = termOfV(zeroOf(srt), s);
922
+ step.__ret = termOfV(retV, s);
923
+ }
924
+ if (!no(F)) {
925
+ flag('__failed', F);
926
+ step.__failed = { s: 'bool', e: F };
927
+ }
928
+ if (!no(Rf)) {
929
+ flag('__refused', Rf);
930
+ step.__refused = { s: 'bool', e: Rf };
931
+ }
932
+ const len = I.nvar(this.newVar(`${run}_n`, { k: 'num' }, 'input', 'the passes of a loop (the run carries one more)').name);
933
+ this.folds.push({ list: [...rk.keys()].join(','), run, fields, init, step, len, loop: { like, cond: I.and(c, I.not(doneAt(i))), drains, entry: I.and(this.sel, this.cond(q0)) } });
934
+ // After the loop: each running value its cell at the length; each list written at every key.
935
+ let q = { ...q0, locals: new Map(q0.locals), heap: new Map(q0.heap), called: [...new Set([q0.called, ...f.rets.map(r => r[0].called), ...(on ? [on.called] : []), ...(brk ? [brk.called] : [])].flat())] };
936
+ for (const v of fields)
937
+ if (!FLAGS.includes(v.name) && !v.name.includes('__'))
938
+ q.locals.set(v.name, at(v.name, len));
939
+ for (const d of rk.values()) {
940
+ const k = { op: 'num', e: I.nvar('k$') }, base = this.baseCell(d.decl, k), aN = at(`${d.name}__a`, len).e;
941
+ const place = { op: 'cell', map: d.rk, key: k, field: '$item' };
942
+ const out = I.and(base.has, I.cmp('<', place, aN)), cur = I.and(at(`${d.name}__ld`, len).e, base.has, I.cmp('=', place, aN));
943
+ const vals = new Map([...base.vals].map(([fn, v]) => [fn, this.ite(cur, at(`${d.name}__f__${fn}`, len), v, s)]));
944
+ const o0 = q0.heap.get(d.id);
945
+ q.heap.set(d.id, { ...o0, ew: { key: k, has: I.and(base.has, I.not(out)), vals } });
946
+ }
947
+ if (!no(F)) {
948
+ if (this.tries.length)
949
+ refuse(s, 'a failure in a loop inside a try');
950
+ this.fail(q, at('__failed', len).e, s, 'a failure in a pass of the loop', null);
951
+ q = this.assume(q, I.not(at('__failed', len).e));
952
+ }
953
+ // (a pass the rule refuses: outside the claim (an item it keeps where the condition holds again, an order field it
954
+ // changes), whatever the passes wrote)
955
+ if (!no(Rf)) {
956
+ this.refusals.push(I.and(this.cond(q), at('__refused', len).e));
957
+ q = this.assume(q, I.not(at('__refused', len).e));
958
+ }
959
+ if (no(R))
960
+ return { live: q, rets: [] };
961
+ const ret = q;
962
+ q = this.assume(q, I.not(at('__returned', len).e));
963
+ return { live: q, rets: [[{ ...ret, pc: [...q0.pc, at('__returned', len).e] }, at('__ret', len)]] };
964
+ }
965
+ // The order a list's passes take its items in: the order its first item is read by, part by part over the item's
966
+ // cells at a key (no tie-breaking: two items that tie are an edge).
967
+ rankOrder(d) {
968
+ return k => { this.drainSetup++; try {
969
+ return d.order.by(k);
970
+ }
971
+ finally {
972
+ this.drainSetup--;
973
+ } };
974
+ }
975
+ // A list a pass of a while loop takes items of by an order: its item at the count of those taken out (in the order
976
+ // the request carries its keys in), held where the count is below how many there are.
977
+ rankOf(o, at) {
978
+ const dr = this.drain, name = o.decl.name;
979
+ let d = dr.rank.get(name);
980
+ if (d)
981
+ return d;
982
+ const id = [...this.initHeap].find(([, x]) => x.k === 'map' && x.decl === o.decl)?.[0] ?? refuse(at, `${at.text}: a collection of the state the reader didn't find`);
983
+ const o0 = dr.entry.heap.get(id);
984
+ if (o0?.w || o0?.pre?.length || o0?.ew)
985
+ refuse(at, `${at.text}: a loop over ${name} after the step wrote it (the passes take its items in the state before the step)`);
986
+ const ord = this.newVar(`${name}__ord`, { k: 'num' }, 'input', undefined, false).name, rk = this.newVar(`${name}__rk`, { k: 'num' }, 'input', undefined, false).name;
987
+ const cell = (n) => ({ op: 'cell', map: dr.run, key: { op: 'num', e: dr.i }, field: `${name}__${n}` });
988
+ const a = cell('a'), ld = cell('ld'), K = { op: 'num', e: { op: 'cell', map: ord, key: { op: 'num', e: a }, field: 'k' } };
989
+ const exists = I.cmp('<', a, I.nvar(`${ord}_len`)), base = this.baseCell(o.decl, K);
990
+ const cur = new Map(o.decl.fields.map(fd => [fd.name, cellV(dr.run, dr.i, `${name}__f__${fd.name}`, fd.sort)]));
991
+ const view = new Map(o.decl.fields.map(fd => [fd.name, this.ite(ld, cur.get(fd.name), base.vals.get(fd.name), at)]));
992
+ d = { name, id, decl: o.decl, K, exists, view, cur, a, ld, ord, rk };
993
+ dr.rank.set(name, d);
994
+ return d;
995
+ }
996
+ // A least read of a list a while loop's passes take items of by an order: the pass's item; the order is the one the
997
+ // item's key is first read by (a read of whether it is empty reads only whether there is one).
998
+ rankLeast(o, at, where, by) {
999
+ if (!o.decl.ordered)
1000
+ return refuse(at, `${at.text}: a dict read in a loop that takes the first items of a list by an order`);
1001
+ const d = this.rankOf(o, at), kk = { op: 'num', e: I.nvar(LEAST_KEY) };
1002
+ let w, parts;
1003
+ this.drainSetup++;
1004
+ try {
1005
+ w = where(kk);
1006
+ parts = by(kk);
1007
+ }
1008
+ finally {
1009
+ this.drainSetup--;
1010
+ }
1011
+ const sig = I.keyOf(parts);
1012
+ if (!I.same(w, this.baseCell(o.decl, kk).has))
1013
+ refuse(at, `${at.text}: an item of ${d.name} by a condition, in a loop that takes its first items`);
1014
+ const empty = parts.length === 0;
1015
+ return { get key() {
1016
+ if (empty && !d.order)
1017
+ return refuse(at, `${at.text}: ${d.name}'s first item by its places, in a loop that takes another list's items by an order`);
1018
+ if (!d.order)
1019
+ d.order = { by, sig };
1020
+ else if (d.order.sig !== sig)
1021
+ refuse(at, `${at.text}: ${d.name} read in two orders in a loop that takes its first items`);
1022
+ return d.K.e;
1023
+ }, some: d.exists, held: d.exists, where };
1024
+ }
1025
+ // A least read of a collection a while loop's passes take items of: the pass's own item (its place or key), the
1026
+ // collection's own order only (the first from either end); in the pass after the passes ran out, none.
1027
+ drainLeast(o, at, where, by) {
1028
+ // (the list read again after the pass may have taken its item out: refused, the pass's item is the one it took; the
1029
+ // condition read once more at the pass's end is the next pass's, on the same item)
1030
+ if (!this.drainAgain && (o.pre?.length || (o.w && !(o.w.has.op === 'const' && o.w.has.v))))
1031
+ return refuse(at, `${at.text}: ${o.decl.name} read again in a pass of the loop after the pass took its item out`);
1032
+ if (this.drain.rank)
1033
+ return this.rankLeast(o, at, where, by);
1034
+ // (a dict's keys in order: the passes would run over every number up to the greatest key, refused)
1035
+ if (!o.decl.ordered)
1036
+ return refuse(at, `${at.text}: a dict's keys taken in order in a loop (the subset reads a loop over a list of the state)`);
1037
+ const dr = this.drain, kk = { op: 'num', e: I.nvar(LEAST_KEY) }, name = o.decl.name;
1038
+ let w, parts;
1039
+ this.drainSetup++;
1040
+ try {
1041
+ w = where(kk);
1042
+ parts = by(kk);
1043
+ }
1044
+ finally {
1045
+ this.drainSetup--;
1046
+ }
1047
+ const own = parts.length === 0 || (parts.length === 1 && I.same(parts[0].e, kk.e));
1048
+ const desc = parts.length === 1 && !!parts[0].desc;
1049
+ if (dr.empty === name)
1050
+ return { get key() { return refuse(at, `${at.text}: the first item of ${name}, empty`); }, some: I.F, held: I.F, where };
1051
+ if (dr.empty)
1052
+ return refuse(at, `${at.text}: a collection read after a loop over another ran out of items`);
1053
+ if (!I.same(w, this.baseCell(o.decl, kk).has))
1054
+ refuse(at, `${at.text}: an item of ${name} by a condition, in a loop whose passes take its first items`);
1055
+ if (dr.map && dr.map.name !== name)
1056
+ refuse(at, `${at.text}: a loop whose passes take items of two collections (${dr.map.name} and ${name}): the subset reads one`);
1057
+ if (!dr.map) {
1058
+ const id = [...this.initHeap].find(([, x]) => x.k === 'map' && x.decl === o.decl)?.[0] ?? refuse(at, `${at.text}: a collection of the state the reader didn't find`);
1059
+ const o0 = dr.entry.heap.get(id);
1060
+ if (o0?.w || o0?.pre?.length || o0?.ew)
1061
+ refuse(at, `${at.text}: a loop over ${name} after the step wrote it (the passes take its items in the state before the step)`);
1062
+ dr.map = { name, id };
1063
+ }
1064
+ const key = dr.i;
1065
+ return { get key() {
1066
+ if (!own) {
1067
+ if (o.decl.ordered && !dr.dir)
1068
+ throw new Ranked();
1069
+ return refuse(at, `${at.text}: a loop whose passes take ${name}'s items in an order other than its own (its places or keys) after reading them in it`);
1070
+ }
1071
+ if (desc !== dr.back) {
1072
+ if (dr.dir === undefined)
1073
+ throw new Backward();
1074
+ return refuse(at, `${at.text}: ${name} taken from both ends in one loop`);
1075
+ }
1076
+ dr.dir = desc;
1077
+ return key;
1078
+ }, some: I.T, held: I.T, where };
1079
+ }
541
1080
  // any, all or sum of a generator: the loop it is, its value an accumulator's (any: true at the first that is; all:
542
1081
  // false at the first that isn't; sum: each added), the fold above.
543
1082
  foldExpr(x, p) {
@@ -626,7 +1165,7 @@ export class Stepper {
626
1165
  if (!i || ('origin' in o && o.origin !== 'state'))
627
1166
  continue;
628
1167
  // (a write a condition makes, nx's, on a path where that condition is false: none)
629
- if (o.k === 'map' ? (!!o.w && !(o.w.on && p.pc.some(c => I.same(c, I.not(o.w.on))))) || (!!o.nil && I.keyOf(o.nil) !== I.keyOf(i.nil)) : o.k === 'list' ? o.ops.length > 0 : keyV(o) !== keyV(i))
1168
+ if (o.k === 'map' ? !!o.ew || (!!o.w && !(o.w.on && p.pc.some(c => I.same(c, I.not(o.w.on))))) || (!!o.nil && I.keyOf(o.nil) !== I.keyOf(i.nil)) : o.k === 'list' ? o.ops.length > 0 : keyV(o) !== keyV(i))
630
1169
  return true;
631
1170
  }
632
1171
  return false;
@@ -643,7 +1182,10 @@ export class Stepper {
643
1182
  let k = 0;
644
1183
  while (k < a.pc.length && k < b.pc.length && I.same(a.pc[k], b.pc[k]))
645
1184
  k++;
646
- const c = I.and(...a.pc.slice(k)), pc = a.pc.slice(0, k);
1185
+ const c = I.and(...a.pc.slice(k)), cb = I.and(...b.pc.slice(k));
1186
+ // (the two paths' own conditions: one or the other holds past the merge, which is no longer true where a path of
1187
+ // either left before it, a return or a break in a branch)
1188
+ const pc = [...a.pc.slice(0, k), ...(I.same(cb, I.not(c)) || I.same(c, I.not(cb)) || (c.op === 'const' && c.v) || (cb.op === 'const' && cb.v) ? [] : [I.or(c, cb)])];
647
1189
  if (c.op === 'const')
648
1190
  return c.v ? { ...a, pc } : { ...b, pc };
649
1191
  if (a.locks.join() !== b.locks.join())
@@ -695,6 +1237,17 @@ export class Stepper {
695
1237
  }
696
1238
  if (a.k === 'map' && b.k === 'map') {
697
1239
  const base = (key) => this.baseCell(a.decl, key), ite = (c2, x, y) => this.ite(c2, x, y, at);
1240
+ // (a write at every key on one path or both: each key's cell by the condition, the other path's as it was)
1241
+ if (a.ew || b.ew) {
1242
+ const sig = (w) => (w ? keyV({ h: w.has, v: [...w.vals] }) : '');
1243
+ if ((a.w || a.pre?.length || b.w || b.pre?.length) && sig(a.ew) !== sig(b.ew))
1244
+ return refuse(at, 'a collection a loop wrote at every key on one path and at one key on another');
1245
+ const k = { op: 'num', e: I.nvar('k$') }, ea = a.ew ?? { key: k, ...base(k) }, eb = b.ew ?? { key: k, ...base(k) };
1246
+ if (sig(ea) !== sig(eb))
1247
+ return { ...a, ew: { key: k, has: I.bite(c, ea.has, eb.has), vals: new Map([...ea.vals].map(([f, v]) => [f, ite(c, v, eb.vals.get(f))])) } };
1248
+ if (!a.w && !b.w)
1249
+ return { ...a, ew: ea };
1250
+ }
698
1251
  // (several keys written: both paths' writes padded to one length, each place by the condition)
699
1252
  const [la, lb] = padWrites([[...(a.pre ?? []), ...(a.w ? [a.w] : [])], [...(b.pre ?? []), ...(b.w ? [b.w] : [])]], base);
700
1253
  if (la.length > 1) {
@@ -947,6 +1500,14 @@ export class Stepper {
947
1500
  return refuse(at, `${f.name}: *args or **kwargs given`);
948
1501
  return refuse(at, `${f.name}: more arguments than it takes`);
949
1502
  }
1503
+ // The supported call supplies no variadic arguments (extra ones were
1504
+ // refused above). Python still binds *args and **kwargs to empty values;
1505
+ // leaving them unbound would invent an UnboundLocalError in the body.
1506
+ if (this.mod.lang === 'python')
1507
+ for (const pa of f.params.filter(x => x.star)) {
1508
+ locals.set(pa.name, pa.star === 1 ? { t: 'tuple', xs: [] } : { t: 'val', ty: '$dict', f: new Map() });
1509
+ this.notes.add(`${f.name}: ${pa.star === 1 ? '*' : '**'}${pa.name} is empty (the modeled calls supply only the declared arguments)`);
1510
+ }
950
1511
  const saved = q.locals;
951
1512
  this.frames.push(f.id);
952
1513
  this.frameLocals.push(saved);
@@ -1184,6 +1745,7 @@ export class Stepper {
1184
1745
  case 'break': return { rets: [], brk: [p] };
1185
1746
  case 'continue': return { rets: [], brk: [{ ...p, cont: true }] };
1186
1747
  case 'for': return this.forStmt(s, p);
1748
+ case 'while': return this.whileStmt(s, p);
1187
1749
  case 'defer': {
1188
1750
  const key = this.lockKey(s.pl, p);
1189
1751
  if (!p.locks.includes(key))
@@ -1264,6 +1826,8 @@ export class Stepper {
1264
1826
  return refuse(at, `${at.text}: writes an object already put in a map (one object in two places)`);
1265
1827
  if (obj.origin === 'state' && !this.init && !obj.f.has(f))
1266
1828
  return refuse(at, `${at.text}: a field the constructor doesn't set (the state's fields are the constructor's)`);
1829
+ const fieldType = this.mod.recs[obj.ty]?.fields.find(x => x.name === f)?.t;
1830
+ v = this.timeField(v, fieldType, false, at);
1267
1831
  const old = obj.f.get(f);
1268
1832
  if (old?.t === 'opaque' && obj.origin === 'state' && !this.init)
1269
1833
  return refuse(at, `${at.text}: writes ${old.why}`);
@@ -1317,6 +1881,22 @@ export class Stepper {
1317
1881
  cellOf(o, key, _p, _at) {
1318
1882
  keyKind(o.decl, key, _at);
1319
1883
  let acc = this.baseCell(o.decl, key);
1884
+ // (an order read over the state before the step; in a while loop's pass, the collection only at the pass's key)
1885
+ if (this.drainSetup)
1886
+ return acc;
1887
+ const rd = this.drain?.rank?.get(o.decl.name);
1888
+ if (rd && o.origin === 'state') {
1889
+ if (I.same(key, rd.K))
1890
+ acc = { has: rd.exists, vals: rd.view };
1891
+ else
1892
+ return refuse(_at, `${_at.text}: an item of ${o.decl.name} other than the first a pass of the loop takes (the subset reads a loop over the state as its passes' first items)`);
1893
+ }
1894
+ if (this.drain?.map?.name === o.decl.name && o.origin === 'state' && !this.drain.empty && !I.same(key, { op: 'num', e: this.drain.i }))
1895
+ return refuse(_at, `${_at.text}: an item of ${o.decl.name} other than the one a pass of the loop takes (the subset reads a loop over the state as its passes over a collection's items, each taking its own)`);
1896
+ if (o.ew) {
1897
+ const x = key.e ?? refuse(_at, `${_at.text}: a key of other than a number`), sub = (v) => substV(v, 'k$', x);
1898
+ acc = { has: I.substN(o.ew.has, 'k$', x), vals: new Map([...o.ew.vals].map(([f, v]) => [f, sub(v)])) };
1899
+ }
1320
1900
  for (const w of [...(o.pre ?? []), ...(o.w ? [o.w] : [])]) {
1321
1901
  const same = I.keq(key, w.key), a = acc;
1322
1902
  acc = { has: I.bite(same, w.has, a.has), vals: new Map([...a.vals].map(([f, v]) => [f, this.ite(same, w.vals.get(f), v, _at)])) };
@@ -1442,7 +2022,10 @@ export class Stepper {
1442
2022
  // before the step, so one read after the step wrote the map is refused. Each least read once, however often.
1443
2023
  // (`held`: whether there is one, with `where` at its key, which it implies: what a path that takes it knows)
1444
2024
  least(o, at, where, by) {
1445
- if (o.w)
2025
+ // (in a while loop's pass, a collection of the state it takes first items of: the pass's item)
2026
+ if (this.drain && o.origin === 'state' && (o.decl.ordered || o.decl.key === 'num') && !this.drainSetup)
2027
+ return this.drainLeast(o, at, where, by);
2028
+ if (o.w || o.ew)
1446
2029
  return refuse(at, `${at.text}: the first, last, least or greatest item of a collection the step has written (the rule reads it in the state before the step)`);
1447
2030
  const kk = { op: 'num', e: I.nvar(LEAST_KEY) }, w = where(kk), b = [...by(kk), { e: I.nvar(LEAST_KEY) }], sig = I.keyOf({ map: o.decl.name, w, b });
1448
2031
  let l = this.leasts.find(x => I.keyOf({ map: x.map, w: x.where, b: x.by }) === sig);
@@ -1491,6 +2074,21 @@ export class Stepper {
1491
2074
  o = q.heap.get(id);
1492
2075
  if (kw.length)
1493
2076
  return refuse(x, `${x.text}: a list's method given keywords`);
2077
+ if (this.drain && o.decl.ordered) {
2078
+ // (in a while loop's pass: the collection it takes items of only gives its item up)
2079
+ if (name === 'append')
2080
+ return refuse(x, `${x.text}: an item put in ${o.decl.name} in a pass of a loop`);
2081
+ const rr = o.decl.scalar ? undefined : this.recOf(o.decl, x);
2082
+ if (name === 'remove' && rr && (!rr.kinds.includes('dataclass') || rr.kinds.includes('eq-identity') || rr.methods.__eq__))
2083
+ return refuse(x, `${x.text}: a list's remove of ${rr.short}, whose equality isn't its fields' (a dataclass's)`);
2084
+ const rd = this.drain.rank?.get(o.decl.name);
2085
+ if (name === 'remove' && rd && args.length === 1 && args[0].t === 'cell' && args[0].map === id && I.same(args[0].key, rd.K))
2086
+ return [{ t: 'none' }, this.listDel(id, o, rd.K, x, this.assume(q, rd.exists))];
2087
+ if (name === 'remove' && this.drain.map?.name === o.decl.name && args.length === 1 && args[0].t === 'cell' && args[0].map === id && I.same(args[0].key, { op: 'num', e: this.drain.i }))
2088
+ return [{ t: 'none' }, this.listDel(id, o, args[0].key, x, q)];
2089
+ if (name === 'remove')
2090
+ return refuse(x, `${x.text}: an item of ${o.decl.name} other than the one a pass of a loop takes, taken out`);
2091
+ }
1494
2092
  if (name === 'append' && args.length === 1) {
1495
2093
  const last = this.least(o, x, k => this.baseCell(o.decl, k).has, k => [{ e: k.e, desc: true }]);
1496
2094
  return [{ t: 'none' }, this.mapSet(m, { op: 'num', e: I.nite(last.some, I.add(last.key, I.num(1)), I.num(0)) }, args[0], x, q)];
@@ -1595,6 +2193,196 @@ export class Stepper {
1595
2193
  this.fail(p, I.not(l.some), x, `${x.text}: ${n}() of an empty collection (a ValueError)`);
1596
2194
  return [v, this.assume(p, l.held)];
1597
2195
  }
2196
+ timeField(v, t, read, at) {
2197
+ const inner = t?.k === 'opt' ? t.of : t;
2198
+ if (inner?.k !== 'int' || !inner.unit?.startsWith('datetime-'))
2199
+ return v;
2200
+ if (inner.unit === 'datetime-naive') {
2201
+ this.naiveUtc = true;
2202
+ this.notes.add('naive datetime values require a UTC process timezone');
2203
+ }
2204
+ if (v.t === 'opt')
2205
+ return { ...v, v: this.timeField(v.v, inner, read, at) };
2206
+ if (v.t === 'none')
2207
+ return v;
2208
+ const utc = inner.unit === 'datetime-utc' ? I.T : I.F;
2209
+ if (read && v.t === 'num')
2210
+ return { t: 'val', ty: '$dt', f: new Map([['ms', v], ['utc', { t: 'bool', e: utc }]]) };
2211
+ if (v.t === 'val' && v.ty === '$dt' && I.same(v.f.get('utc')?.e ?? I.F, utc))
2212
+ return read ? v : v.f.get('ms');
2213
+ return refuse(at, `${at.text}: expected ${inner.unit} value`);
2214
+ }
2215
+ // ORM rows are detached copies. Only save/create/delete writes the table; mutating a fetched
2216
+ // object does not. Tables start empty and have the same map semantics used by system.ts.
2217
+ naiveUtc = false;
2218
+ ormTables = new Map();
2219
+ ormTable(rec, at, p) {
2220
+ let table = this.ormTables.get(rec);
2221
+ if (!table) {
2222
+ const r = this.rec(rec, at), meta = r.orm;
2223
+ if (!meta || meta.why)
2224
+ return refuse(at, meta?.why || `${rec}: no ORM schema`);
2225
+ if (r.fields.some(f => ['__proto__', 'prototype', 'constructor'].includes(f.name)))
2226
+ return refuse(at, `${rec}: reserved ORM column name`);
2227
+ if (r.methods.save || r.methods.delete || r.methods.__init__)
2228
+ return refuse(at, `${rec}: custom ORM constructor/save/delete is outside the table boundary`);
2229
+ const kt = r.fields.find(f => f.name === meta.key)?.t;
2230
+ if (kt?.k !== 'int' && kt?.k !== 'str')
2231
+ return refuse(at, `${rec}: primary key must be a non-null integer or string`);
2232
+ const fields = [];
2233
+ for (const f of r.fields) {
2234
+ if (f.name === meta.key)
2235
+ continue;
2236
+ const t = f.t.k === 'opt' ? f.t.of : f.t, sort = this.scalar(t);
2237
+ if (!sort)
2238
+ return refuse(at, `${rec}.${f.name}: ${this.why(t)}`);
2239
+ if (r.fields.some(g => g.name === `${f.name}_has`))
2240
+ return refuse(at, `${rec}: reserved ORM presence column`);
2241
+ fields.push({ name: f.name, sort, role: 'state' });
2242
+ if (f.t.k === 'opt')
2243
+ fields.push({ name: `${f.name}_has`, sort: { k: 'bool' }, role: 'state' });
2244
+ }
2245
+ const v = this.newVar(r.short, { k: 'num' }, 'state'), decl = { name: v.name, key: kt.k === 'int' ? 'num' : 'str', fields, scalar: false, js: 'Map' };
2246
+ table = { id: `orm:${rec}`, decl };
2247
+ this.maps.push(decl);
2248
+ this.ormTables.set(rec, table);
2249
+ this.initHeap.set(table.id, { k: 'map', decl, val: { k: 'rec', name: rec }, origin: 'state' });
2250
+ this.notes.add(`${rec}: ${meta.framework} table keyed by ${meta.key}; explicit keys, detached rows, no database touched by the check. Database constraints, triggers and signals are outside this stated table boundary; use gdp: env for isolation and store failures.`);
2251
+ }
2252
+ if (!p.heap.has(table.id))
2253
+ p.heap.set(table.id, this.initHeap.get(table.id));
2254
+ return table;
2255
+ }
2256
+ ormRow(rec, key, vals, at, p) {
2257
+ const r = this.rec(rec, at), table = this.ormTable(rec, at, p), f = new Map();
2258
+ for (const fd of r.fields) {
2259
+ if (fd.name === r.orm.key) {
2260
+ f.set(fd.name, key.op === 'num' ? { t: 'num', e: key.e } : { t: 'str', e: key });
2261
+ continue;
2262
+ }
2263
+ const v = vals.get(fd.name);
2264
+ f.set(fd.name, fd.t.k === 'opt' ? { t: 'opt', has: this.boolv(vals.get(`${fd.name}_has`), at), v } : v);
2265
+ }
2266
+ const id = `fresh:${this.fresh++}`;
2267
+ return [{ t: 'ref', id }, { ...p, heap: new Map(p.heap).set(id, { k: 'rec', ty: rec, f, origin: 'fresh', orm: { table: table.id, key, loaded: true } }) }];
2268
+ }
2269
+ ormCall(rec, op, args, kw, at, p) {
2270
+ const r = this.rec(rec, at), table = this.ormTable(rec, at, p), meta = r.orm, o = p.heap.get(table.id);
2271
+ if (this.tries.length)
2272
+ return refuse(at, 'ORM operations inside try require modeled database exception classes');
2273
+ if (args.length)
2274
+ return refuse(at, `${at.text}: ORM arguments must be named`);
2275
+ if (op === 'new' || op === 'create') {
2276
+ const f = new Map(kw);
2277
+ for (const fd of r.fields) {
2278
+ const v = f.get(fd.name);
2279
+ if (v)
2280
+ f.set(fd.name, this.timeField(v, fd.t, false, at));
2281
+ }
2282
+ if (f.size !== kw.length || kw.some(([n]) => !r.fields.some(fd => fd.name === n)) || r.fields.some(fd => !f.has(fd.name)))
2283
+ return refuse(at, `${at.text}: give every ORM column explicitly, including the primary key`);
2284
+ const key = this.keyOf(f.get(meta.key), at), id = `fresh:${this.fresh++}`;
2285
+ keyKind(table.decl, key, at);
2286
+ let q = { ...p, heap: new Map(p.heap).set(id, { k: 'rec', ty: rec, f, origin: 'fresh', orm: { table: table.id, key } }) };
2287
+ const row = { t: 'ref', id };
2288
+ if (op === 'create') {
2289
+ const has = this.cellOf(o, key, q, at).has;
2290
+ this.fail(q, has, at, `${at.text}: duplicate primary key (an IntegrityError)`);
2291
+ q = this.assume(q, I.not(has));
2292
+ q = this.ormPersist(row, 'save', [], [], at, q)[1];
2293
+ }
2294
+ return [row, q];
2295
+ }
2296
+ if (kw.length !== 1 || ![meta.key, 'pk'].includes(kw[0][0]))
2297
+ return refuse(at, `${at.text}: ORM queries require exactly the primary key ${JSON.stringify(meta.key)} (or "pk"); received filters: ${kw.map(([n]) => JSON.stringify(n)).join(', ') || '(none)'}; non-key filters need a scan`);
2298
+ const key = this.keyOf(kw[0][1], at), c = this.cellOf(o, key, p, at);
2299
+ if (op === 'filter')
2300
+ return [{ t: 'val', ty: `$orm-query:${rec}`, f: new Map([['key', kw[0][1]]]) }, p];
2301
+ if (op !== 'get')
2302
+ return refuse(at, `${at.text}: unsupported ORM operation ${op}`);
2303
+ this.fail(p, I.not(c.has), at, `${at.text}: row not found (DoesNotExist)`);
2304
+ return this.ormRow(rec, key, c.vals, at, this.assume(p, c.has));
2305
+ }
2306
+ ormSession(name, op, args, kw, at, p) {
2307
+ if (kw.length || this.tries.length || p.called.includes(`session-committed:${name}`))
2308
+ return refuse(at, `${at.text}: session options, exception handling or operations after commit are outside the subset`);
2309
+ if (op === 'get' && args.length === 2 && args[0]?.t === 'cls') {
2310
+ const rec = args[0].rec, r = this.rec(rec, at);
2311
+ if (r.orm?.framework !== 'sqlalchemy')
2312
+ return refuse(at, `${at.text}: Session.get requires a mapped class`);
2313
+ if (p.called.includes(`session-read:${rec}`))
2314
+ return refuse(at, `${at.text}: repeated session reads require an identity map`);
2315
+ const table = this.ormTable(rec, at, p), key = this.keyOf(args[1], at), c = this.cellOf(p.heap.get(table.id), key, p, at);
2316
+ const [v, q] = this.ormRow(rec, key, c.vals, at, p), row = q.heap.get(v.id);
2317
+ row.orm.session = name;
2318
+ return [{ t: 'opt', has: c.has, v }, { ...q, called: [...q.called, `session-read:${rec}`] }];
2319
+ }
2320
+ if ((op === 'add' || op === 'delete') && args.length === 1 && args[0]?.t === 'ref') {
2321
+ const v = args[0], row = p.heap.get(v.id);
2322
+ if (row?.k !== 'rec' || !row.orm || this.rec(row.ty, at).orm?.framework !== 'sqlalchemy')
2323
+ return refuse(at, `${at.text}: session requires a mapped row`);
2324
+ if (row.orm.session && row.orm.session !== name)
2325
+ return refuse(at, `${at.text}: transferring a row between sessions is outside the subset`);
2326
+ if (op === 'delete' && !row.orm.loaded)
2327
+ return refuse(at, `${at.text}: deleting a transient session row is outside the subset`);
2328
+ return [{ t: 'none' }, { ...p, heap: new Map(p.heap).set(v.id, { ...row, orm: { ...row.orm, session: name, deleted: op === 'delete' } }) }];
2329
+ }
2330
+ if (op === 'commit' && !args.length) {
2331
+ let q = p;
2332
+ const pending = [];
2333
+ for (const row of p.heap.values())
2334
+ if (row.k === 'rec' && row.orm?.session === name) {
2335
+ const table = q.heap.get(row.orm.table), exists = this.cellOf(table, row.orm.key, q, at).has;
2336
+ // A missing get returned None, not an object added to the session. Only paths that
2337
+ // established its presence may flush it; otherwise the extraction is refused.
2338
+ if (row.orm.loaded && !this.holds(q, exists))
2339
+ return refuse(at, `${at.text}: committing a session read without establishing row presence`);
2340
+ if (!row.orm.loaded && !row.orm.deleted) {
2341
+ const duplicate = I.or(exists, ...pending.filter(v => v.table === row.orm.table).map(v => I.keq(v.key, row.orm.key)));
2342
+ this.fail(q, duplicate, at, `${at.text}: duplicate primary key (IntegrityError)`);
2343
+ q = this.assume(q, I.not(duplicate));
2344
+ pending.push(row.orm);
2345
+ }
2346
+ }
2347
+ for (const [id, row] of p.heap)
2348
+ if (row.k === 'rec' && row.orm?.session === name)
2349
+ q = this.ormPersist({ t: 'ref', id }, row.orm.deleted ? 'delete' : 'save', [], [], at, q)[1];
2350
+ return [{ t: 'none' }, { ...q, called: [...q.called, `session-committed:${name}`] }];
2351
+ }
2352
+ return refuse(at, `${at.text}: unsupported session operation ${op}`);
2353
+ }
2354
+ ormPersist(v, op, args, kw, at, p) {
2355
+ if (args.length || kw.length || this.tries.length)
2356
+ return refuse(at, `${at.text}: ORM save/delete options or exception handler outside the subset`);
2357
+ const row = v.t === 'ref' ? p.heap.get(v.id) : undefined;
2358
+ if (row?.k !== 'rec' || !row.orm)
2359
+ return refuse(at, `${at.text}: save/delete requires a row fetched or created in this request`);
2360
+ const r = this.rec(row.ty, at), key = this.keyOf(row.f.get(r.orm.key), at);
2361
+ if (!I.same(key, row.orm.key))
2362
+ return refuse(at, `${at.text}: changing an ORM primary key is outside the subset`);
2363
+ const o = p.heap.get(row.orm.table);
2364
+ if (op === 'delete') {
2365
+ const q = this.mapDel({ t: 'ref', id: row.orm.table }, key, at, p, false);
2366
+ if (r.orm.framework === 'django' && v.t === 'ref')
2367
+ q.heap.set(v.id, { ...row, f: new Map(row.f).set(r.orm.key, { t: 'none' }) });
2368
+ return [{ t: 'none' }, q];
2369
+ }
2370
+ const vals = new Map();
2371
+ for (const fd of r.fields) {
2372
+ if (fd.name === r.orm.key)
2373
+ continue;
2374
+ const value = row.f.get(fd.name) ?? refuse(at, `${at.text}: missing column ${fd.name}`), f = o.decl.fields.find(f => f.name === fd.name);
2375
+ if (fd.t.k === 'opt') {
2376
+ const has = value.t === 'none' ? I.F : value.t === 'opt' ? value.has : I.T;
2377
+ const inner = value.t === 'none' ? zeroOf(f.sort) : value.t === 'opt' ? value.v : value;
2378
+ vals.set(fd.name, this.ite(has, this.fit(inner, f, at), zeroOf(f.sort), at));
2379
+ vals.set(`${fd.name}_has`, { t: 'bool', e: has });
2380
+ }
2381
+ else
2382
+ vals.set(fd.name, this.fit(value, f, at));
2383
+ }
2384
+ return [{ t: 'none' }, this.writeCell(row.orm.table, o, key, I.T, vals, at, p)];
2385
+ }
1598
2386
  // --- stores ---------------------------------------------------------------------------------------------------------
1599
2387
  storeMap(store, tpl, kn, at, p) {
1600
2388
  const key = `${store}\u0000${tpl}`;
@@ -1620,7 +2408,7 @@ export class Stepper {
1620
2408
  json.push({ name: f, out: true });
1621
2409
  continue;
1622
2410
  }
1623
- const st = Array.isArray(t) ? { t: { k: 'choice', values: t } } : sortOfText(t, at.p), opt = st.t.k === 'opt', inner = st.t.k === 'opt' ? st.t.of : st.t;
2411
+ const st = Array.isArray(t) ? { t: { k: 'choice', values: t } } : sortOfText(t, at.p, this.mod.lang), opt = st.t.k === 'opt', inner = st.t.k === 'opt' ? st.t.of : st.t;
1624
2412
  fields.push({ name: f, sort: this.scalar(inner), role: 'state' });
1625
2413
  if (opt)
1626
2414
  fields.push({ name: `${f}_has`, sort: { k: 'bool' }, role: 'state' });
@@ -1927,6 +2715,21 @@ export class Stepper {
1927
2715
  return [v, p];
1928
2716
  }
1929
2717
  valCall(o, m, args, kw, x, p) {
2718
+ if (o.ty.startsWith('$orm-query:')) {
2719
+ if (args.length || kw.length || this.tries.length)
2720
+ return refuse(x, `${x.text}: ORM query options or exception handlers outside the subset`);
2721
+ const rec = o.ty.slice(11), table = this.ormTable(rec, x, p), key = this.keyOf(o.f.get('key'), x);
2722
+ const obj = p.heap.get(table.id), c = this.cellOf(obj, key, p, x);
2723
+ if (m === 'exists')
2724
+ return [{ t: 'bool', e: c.has }, p];
2725
+ if (m === 'first') {
2726
+ const [v, q] = this.ormRow(rec, key, c.vals, x, p);
2727
+ return [{ t: 'opt', has: c.has, v }, q];
2728
+ }
2729
+ if (m === 'delete')
2730
+ return [{ t: 'none' }, this.mapDel({ t: 'ref', id: table.id }, key, x, p, false)];
2731
+ return refuse(x, `${x.text}: unsupported ORM query operation ${m}`);
2732
+ }
1930
2733
  if (o.ty === '$dt' && m === 'timestamp' && !args.length && !kw.length)
1931
2734
  return [{ t: 'val', ty: '$ts', f: o.f }, p];
1932
2735
  if (o.ty === '$dict' && m === 'get' && !kw.length && args.length >= 1 && args.length <= 2) {
@@ -1976,7 +2779,8 @@ export class Stepper {
1976
2779
  const mk = (t, e) => {
1977
2780
  if (t === '$dt')
1978
2781
  this.fail(p, I.or(I.cmp('<', e, I.num(-62_135_596_800_000)), I.cmp('<', I.num(253_402_300_799_999), e)), x, `${x.text}: a datetime out of its range (an OverflowError)`);
1979
- return { t: 'val', ty: t, f: new Map([['ms', { t: 'num', e }]]) };
2782
+ const source = a.t === 'val' && a.ty === '$dt' ? a : b.t === 'val' && b.ty === '$dt' ? b : undefined;
2783
+ return { t: 'val', ty: t, f: new Map([['ms', { t: 'num', e }], ...(t === '$dt' ? [['utc', source?.f.get('utc') ?? { t: 'bool', e: I.F }]] : [])]) };
1980
2784
  };
1981
2785
  if (op === '+' && ty(a) === '$dt' && ty(b) === '$td')
1982
2786
  return mk('$dt', I.add(ms(a), ms(b)));
@@ -1984,8 +2788,11 @@ export class Stepper {
1984
2788
  return mk('$dt', I.add(ms(a), ms(b)));
1985
2789
  if (op === '-' && ty(a) === '$dt' && ty(b) === '$td')
1986
2790
  return mk('$dt', I.sub(ms(a), ms(b)));
1987
- if (op === '-' && ty(a) === '$dt' && ty(b) === '$dt')
2791
+ if (op === '-' && a.t === 'val' && a.ty === '$dt' && b.t === 'val' && b.ty === '$dt') {
2792
+ if (!I.same(a.f.get('utc') ?? { t: 'bool', e: I.F }, b.f.get('utc') ?? { t: 'bool', e: I.F }))
2793
+ return refuse(x, 'mixed aware and naive datetimes');
1988
2794
  return mk('$td', I.sub(ms(a), ms(b)));
2795
+ }
1989
2796
  if ((op === '+' || op === '-') && ty(a) === '$td' && ty(b) === '$td')
1990
2797
  return mk('$td', op === '+' ? I.add(ms(a), ms(b)) : I.sub(ms(a), ms(b)));
1991
2798
  if (op === '*' && ty(a) === '$ts' && constOf(b) === 1000)
@@ -2029,15 +2836,14 @@ export class Stepper {
2029
2836
  let a = this.answers.get(key);
2030
2837
  const short = key.split(/\.|::/).pop();
2031
2838
  if (!a) {
2032
- const t = typeof type === 'string' ? sortOfText(type, at.p).t : type, text = typeof type === 'string' ? type : typeText(type);
2839
+ const t = typeof type === 'string' ? sortOfText(type, at.p, this.mod.lang).t : type, text = typeof type === 'string' ? type : typeText(type);
2033
2840
  const inner = t.k === 'opt' ? t.of : t, s = this.scalar(inner);
2034
2841
  const v = this.newVar(short, s, 'input', how === 'stated' ? `what ${names[0]} returns (stated: answers)` : `what ${names[0]} returns (${how}: any ${text})`);
2035
2842
  const none = t.k === 'opt' ? this.newVar(`${short}_none`, { k: 'bool' }, 'input', `whether ${names[0]} returns None`).name : undefined;
2036
2843
  // (a result of a fixed width: within it, the claim is for the values its type holds)
2037
2844
  const fit = !!this.intTy(inner);
2038
- if (fit)
2039
- this.typed(v, inner, 'input');
2040
- a = { key, patch: patch ?? {}, async: awaited, inputs: { name: v.name, ...(none ? { none } : {}), ...(inner.k === 'float' ? { float: true } : {}) }, sort: text, ...(how === 'stated' ? {} : { how }), ...(fit ? { fit } : {}), at: [], ...(at.ty ? { ty: at.ty } : {}) };
2845
+ this.typed(v, inner, 'input', inner.k === 'int' && inner.unit?.startsWith('datetime-') && none ? I.and(this.sel, I.not(I.bvar(none))) : this.sel);
2846
+ a = { key, patch: patch ?? {}, async: awaited, inputs: { name: v.name, ...(none ? { none } : {}), ...(inner.k === 'float' ? { float: true } : {}), ...(inner.k === 'int' && inner.unit?.startsWith('datetime-') ? { time: inner.unit } : {}) }, sort: text, ...(how === 'stated' ? {} : { how }), ...(fit ? { fit } : {}), at: [], ...(at.ty ? { ty: at.ty } : {}) };
2041
2847
  this.answers.set(key, a);
2042
2848
  this.notes.add(how === 'stated' ? `${names[0]} (${at.p}): answered by the request (stated), its arguments not read` : `${names[0]} (${at.p}): answered by the request (${how}: its value is read; assumes ${names[0]} may return any ${text}), its arguments not read`);
2043
2849
  }
@@ -2048,7 +2854,7 @@ export class Stepper {
2048
2854
  this.typed(this.vars.get(a.inputs.name), at.ity, 'input', I.and(this.sel, this.cond(p)));
2049
2855
  if (!a.at.some(x => x.p === site.p))
2050
2856
  a.at.push(site);
2051
- const vv = this.valueOf(this.vars.get(a.inputs.name));
2857
+ const vv = this.timeField(this.valueOf(this.vars.get(a.inputs.name)), a.inputs.time ? { k: 'int', unit: a.inputs.time } : undefined, true, at);
2052
2858
  return [a.inputs.none ? { t: 'opt', has: I.not(I.bvar(a.inputs.none)), v: vv } : vv, this.mayRaise(a, names[0], at, q)];
2053
2859
  }
2054
2860
  // A call left out inside a try (its value unread): stubbed only to raise where the request says, else run as it is.
@@ -2306,7 +3112,7 @@ export class Stepper {
2306
3112
  return [{ t: 'num', e: I.num(Number(x.v)), ...(ty ? { ty } : {}) }, p];
2307
3113
  }
2308
3114
  case 'unit': return [{ t: 'none' }, p];
2309
- case 'opaque': return [{ t: 'opaque', why: String(x.why), ...(x.firm ? { firm: true } : {}) }, p];
3115
+ case 'opaque': return [{ t: 'opaque', why: String(x.why), ...(x.firm ? { firm: true } : {}), ...(x.sink ? { sink: true } : {}) }, p];
2310
3116
  case 'ref':
2311
3117
  case 'lock': return this.ev(x.x, p);
2312
3118
  case 'copy': {
@@ -2521,6 +3327,11 @@ export class Stepper {
2521
3327
  }
2522
3328
  case 'conv': {
2523
3329
  const [v, q] = this.ev(x.x, p), ty = x.ity;
3330
+ // (a bit form to an unsigned type: its bits below the type's width, the same form)
3331
+ if (ty && v.t === 'num' && v.bits && !ty.mod && ty.signed === false && ty.bits > 0 && ty.bits < 53) {
3332
+ const m = 2 ** ty.bits, f = { ...v.bits, A: v.bits.A % m, B: v.bits.B % m };
3333
+ return [{ t: 'num', e: f.A === v.bits.A && f.B === v.bits.B ? v.e : this.ofBits(f, x), ty, bits: f }, q];
3334
+ }
2524
3335
  if (ty && v.t === 'num')
2525
3336
  return [{ t: 'num', e: this.wrap(v.e, ty.ub ? { bits: ty.bits, signed: ty.signed, name: ty.name, t: ty.t } : ty, x, q), ty }, q];
2526
3337
  return refuse(x, v.t === 'opaque' && v.ask ? `${String(x.why)}: of ${v.why}` : String(x.why));
@@ -2546,6 +3357,9 @@ export class Stepper {
2546
3357
  }
2547
3358
  if (op === '+')
2548
3359
  return [a, q];
3360
+ // (~x: −x − 1 in two's complement, at x's width)
3361
+ if (op === '^' && a.t === 'num')
3362
+ return [{ t: 'num', e: this.wrap(I.sub(I.neg(a.e), I.num(1)), a.ty, x, q), ty: a.ty }, q];
2549
3363
  return refuse(x, String(x.why));
2550
3364
  }
2551
3365
  case 'addr': {
@@ -2743,6 +3557,23 @@ export class Stepper {
2743
3557
  case 'lambda': return refuse(x, `${x.text}: a lambda (a closure; read only as min's or max's key over a collection of the state)`);
2744
3558
  case 'call': return this.call(x, p, awaited);
2745
3559
  case 'fold': return this.foldExpr(x, p);
3560
+ // (a / k rounded to a whole number, by a reader's own rounding: Math.round, math.Round, f64::round, floorDiv ...)
3561
+ // (an integer converted to a float of `bits` bits (Java's (float) p): itself below 2^bits, an edge past it)
3562
+ case 'fbits': {
3563
+ const [v, q] = this.ev(x.x, p);
3564
+ if (v.t !== 'num')
3565
+ return [v, q];
3566
+ this.refuseWhere(q, I.or(I.cmp('<=', I.num(2 ** x.bits), v.e), I.cmp('<=', v.e, I.num(-(2 ** x.bits)))), x, `${x.text}: converted to a float at |x| of 2^${x.bits} or more (past its precision)`, false);
3567
+ return [v, q];
3568
+ }
3569
+ // (of a whole number, itself; of another float, a value outside the subset where it is read)
3570
+ case 'rnd': {
3571
+ const d = x.x;
3572
+ if (d.e === 'bin' && d.op === '/' && !d.ovf)
3573
+ return this.quotient(d, p, x.mode);
3574
+ const [v, q] = this.ev(d, p);
3575
+ return v.t === 'num' || v.t === 'opaque' ? [v, q] : refuse(x, `${x.text}: a rounding of a ${v.t}`);
3576
+ }
2746
3577
  }
2747
3578
  return refuse(x, `${x.text ?? x.e}: an expression the subset doesn't read`);
2748
3579
  }
@@ -2829,6 +3660,19 @@ export class Stepper {
2829
3660
  }
2830
3661
  return refuse(x, `${x.text}: an atomic's ${op}`);
2831
3662
  }
3663
+ classConstant(value, at) {
3664
+ if (value === null)
3665
+ return { t: 'none' };
3666
+ if (typeof value === 'boolean')
3667
+ return { t: 'bool', e: value ? I.T : I.F };
3668
+ if (typeof value === 'number')
3669
+ return Number.isInteger(value) ? { t: 'num', e: I.num(value) } : { t: 'opaque', why: `${at.text}: a float` };
3670
+ return { t: 'str', e: { op: 'slit', value } };
3671
+ }
3672
+ classCollection(owner, name) {
3673
+ this.notes.add(`${owner}.${name}: a class collection, preserved by the original code; its contents and shared identity are outside the modeled state, never copied or frozen`);
3674
+ return { t: 'opaque', why: `${owner}.${name}: a shared class collection outside the modeled state` };
3675
+ }
2832
3676
  get(x, p) {
2833
3677
  const [o, q] = this.ev(x.x, p), f = String(x.f);
2834
3678
  switch (o.t) {
@@ -2853,8 +3697,15 @@ export class Stepper {
2853
3697
  }
2854
3698
  case 'cls': {
2855
3699
  const r = this.rec(o.rec, x), mid = r.methods[f];
3700
+ if (r.orm && f === 'objects' && r.orm.framework !== 'sqlalchemy')
3701
+ return [{ t: 'ext', q: `orm:${r.name}`, text: x.text ?? f }, q];
2856
3702
  if (mid)
2857
3703
  return [{ t: 'fn', id: mid }, q];
3704
+ const ca = r.cattrs?.[f];
3705
+ if (ca !== undefined)
3706
+ return [this.classConstant(ca, x), q];
3707
+ if (r.classCollections?.[f])
3708
+ return [this.classCollection(r.classCollections[f], f), q];
2858
3709
  return [{ t: 'ext', q: `${o.rec}.${f}`, text: x.text ?? f, ...(o.patch?.path ? { patch: { ...o.patch, path: [...o.patch.path, f] } } : {}), ...(r.rets?.[f] ? { ret: r.rets[f] } : {}) }, q];
2859
3710
  }
2860
3711
  case 'bool':
@@ -2886,12 +3737,38 @@ export class Stepper {
2886
3737
  if (obj?.k !== 'rec')
2887
3738
  return refuse(x, `${x.text}: a field of other than an object`);
2888
3739
  const r = this.rec(obj.ty, x);
2889
- // (super().f: the base's method the reader resolved, on this object)
3740
+ // Python super starts after the defining owner in the actual receiver's
3741
+ // C3 order. Only an owner's own binding may win, not its flattened methods.
3742
+ if (typeof x.superFrom === 'string') {
3743
+ const index = r.mro?.indexOf(x.superFrom) ?? -1;
3744
+ if (index < 0)
3745
+ return refuse(x, `${x.text}: the receiver's MRO cannot be bound`);
3746
+ const owner = r.mro.slice(index + 1).find(name => this.rec(name, x).declared?.includes(f));
3747
+ if (!owner) {
3748
+ if (f === '__init__')
3749
+ return [{ t: 'builtin', n: '$object_init' }, q];
3750
+ return refuse(x, `${x.text}: no inherited attribute ${f} after ${x.superFrom}`);
3751
+ }
3752
+ const base = this.rec(owner, x), id = base.methods[f];
3753
+ if (id) {
3754
+ const fn = this.func(id, x);
3755
+ if (fn.decorators.some(d => d.name === 'property'))
3756
+ return this.callFunc(fn, o, [], [], x, q, false);
3757
+ return [{ t: 'fn', id, self: fn.static ? undefined : o }, q];
3758
+ }
3759
+ const ca = base.cattrs?.[f];
3760
+ if (ca !== undefined)
3761
+ return [this.classConstant(ca, x), q];
3762
+ if (base.classCollections?.[f])
3763
+ return [this.classCollection(base.classCollections[f], f), q];
3764
+ return refuse(x, `${x.text}: inherited attribute ${owner}.${f} cannot be bound`);
3765
+ }
3766
+ // (a base method already resolved by a reader, on this object)
2890
3767
  if (typeof x.sup === 'string')
2891
3768
  return [{ t: 'fn', id: x.sup, self: o }, q];
2892
3769
  const v = obj.f.get(f);
2893
3770
  if (v)
2894
- return [v, q];
3771
+ return [this.timeField(v, r.fields.find(fd => fd.name === f)?.t, true, x), q];
2895
3772
  const mid = r.methods[f];
2896
3773
  if (mid !== undefined) {
2897
3774
  if (mid === null)
@@ -2906,7 +3783,9 @@ export class Stepper {
2906
3783
  // (a class attribute set to a constant, which no method sets on the object: that constant)
2907
3784
  const ca = r.cattrs?.[f];
2908
3785
  if (ca !== undefined)
2909
- return [ca === null ? { t: 'none' } : typeof ca === 'boolean' ? { t: 'bool', e: ca ? I.T : I.F } : typeof ca === 'number' ? (Number.isInteger(ca) ? { t: 'num', e: I.num(ca) } : { t: 'opaque', why: `${x.text}: a float` }) : { t: 'str', e: { op: 'slit', value: ca } }, q];
3786
+ return [this.classConstant(ca, x), q];
3787
+ if (r.classCollections?.[f])
3788
+ return [this.classCollection(r.classCollections[f], f), q];
2910
3789
  return refuse(x, `${x.text}: no field ${f} (the object's fields are those its constructor sets)`);
2911
3790
  }
2912
3791
  // A field of an object the caller gives, made an input where it is first read.
@@ -2946,6 +3825,9 @@ export class Stepper {
2946
3825
  return [this.valBin(op, a, b, x, q2), q2];
2947
3826
  // A true division: a float, kept only where nothing the rule keeps reads it (refused there); its divisor 0 fails.
2948
3827
  if (op === '/') {
3828
+ // (a float division of a reader's (Java's): no failure at 0, an infinity or NaN)
3829
+ if (x.fdiv)
3830
+ return [{ t: 'opaque', why: `${x.text}: a float division (read where it is rounded to a whole number: Math.round, floor, ceil, rint or a cast)` }, q2];
2949
3831
  if (b.t === 'num' || b.t === 'bool') {
2950
3832
  const nb = this.numOf(b, x, q2);
2951
3833
  this.fail(q2, I.cmp('=', nb, I.num(0)), x, `${x.text}: a division by zero (a ZeroDivisionError)`);
@@ -3106,6 +3988,20 @@ export class Stepper {
3106
3988
  }
3107
3989
  return out(op === 'in' ? e : I.not(e));
3108
3990
  }
3991
+ const da = a.t === 'opt' ? a.v : a, db = b.t === 'opt' ? b.v : b;
3992
+ if (da.t === 'val' && da.ty === '$dt' && db.t === 'val' && db.ty === '$dt') {
3993
+ const ah = a.t === 'opt' ? a.has : I.T, bh = b.t === 'opt' ? b.has : I.T;
3994
+ const sameZone = I.same(da.f.get('utc') ?? { t: 'bool', e: I.F }, db.f.get('utc') ?? { t: 'bool', e: I.F });
3995
+ const na = this.numOf(da.f.get('ms'), x, q2), nb = this.numOf(db.f.get('ms'), x, q2);
3996
+ if (op === '==' || op === '!=') {
3997
+ const eq = this.equal(a, b, x, q2);
3998
+ return out(op === '==' ? eq : I.not(eq));
3999
+ }
4000
+ if (!sameZone)
4001
+ return refuse(x, 'mixed aware and naive datetimes');
4002
+ this.fail(q2, I.not(I.and(ah, bh)), x, `${x.text}: ordering None and a datetime (a TypeError)`);
4003
+ return out(op === '<' ? I.cmp('<', na, nb) : op === '<=' ? I.cmp('<=', na, nb) : op === '>' ? I.cmp('<', nb, na) : I.cmp('<=', nb, na));
4004
+ }
3109
4005
  if (op === '==' || op === '!=') {
3110
4006
  const e = this.equal(a, b, x, q2);
3111
4007
  return out(op === '==' ? e : I.not(e));
@@ -3120,6 +4016,13 @@ export class Stepper {
3120
4016
  const o = a.t === 'none' ? b : a;
3121
4017
  return o.t === 'none' ? I.T : o.t === 'opt' ? I.not(o.has) : I.F;
3122
4018
  }
4019
+ const da = a.t === 'opt' ? a.v : a, db = b.t === 'opt' ? b.v : b;
4020
+ if (da.t === 'val' && da.ty === '$dt' && db.t === 'val' && db.ty === '$dt') {
4021
+ const ah = a.t === 'opt' ? a.has : I.T, bh = b.t === 'opt' ? b.has : I.T;
4022
+ const same = I.same(da.f.get('utc') ?? { t: 'bool', e: I.F }, db.f.get('utc') ?? { t: 'bool', e: I.F });
4023
+ const values = same ? I.cmp('=', this.numOf(da.f.get('ms'), at, p), this.numOf(db.f.get('ms'), at, p)) : I.F;
4024
+ return I.or(I.and(I.not(ah), I.not(bh)), I.and(ah, bh, values));
4025
+ }
3123
4026
  if (a.t === 'opt')
3124
4027
  return I.and(a.has, this.equal(a.v, b, at, p));
3125
4028
  if (b.t === 'opt')
@@ -3194,6 +4097,14 @@ export class Stepper {
3194
4097
  // where nothing reads it.
3195
4098
  // A constant string in a hole (a literal, a stated attribute: a store's name) is literal text of the template; a
3196
4099
  // % format ('%s.lock.%s' % (a, b)) is read as the f-string it spells.
4100
+ checkOrmDisplay(v, at) {
4101
+ // Formatting can call user code even when its result is discarded. Keep
4102
+ // non-scalar conversion outside the boundary if a modeled ORM class has
4103
+ // display hooks; this also covers containers/optionals holding such rows.
4104
+ if (this.mod.lang === 'python' && !['num', 'bool', 'str', 'choice', 'none'].includes(v.t) &&
4105
+ Object.values(this.mod.recs).some(r => r.orm && ('__str__' in r.methods || '__repr__' in r.methods)))
4106
+ refuse(at, `${at.text}: implicit ORM display conversion may execute custom methods`);
4107
+ }
3197
4108
  fstr(x, p, given) {
3198
4109
  const parts = given ?? x.parts;
3199
4110
  let q = p, tpl = '', hole, n = 0, opaque = false, ask;
@@ -3211,6 +4122,7 @@ export class Stepper {
3211
4122
  v = v1;
3212
4123
  q = q2;
3213
4124
  }
4125
+ this.checkOrmDisplay(v, x);
3214
4126
  if (v.t === 'str' && v.e.op === 'slit' && plain) {
3215
4127
  tpl += v.e.value.replace(/\{\}/g, '{ }');
3216
4128
  continue;
@@ -3297,6 +4209,15 @@ export class Stepper {
3297
4209
  if (fx.e === 'get') {
3298
4210
  const [o, q1] = this.ev(fx.x, q);
3299
4211
  q = q1;
4212
+ if (o.t === 'ext' && o.q.startsWith('orm-session:'))
4213
+ return this.evArgs(x, q, (args, kw, q2) => this.ormSession(o.q.slice(12), String(fx.f), args, kw, x, q2));
4214
+ if (o.t === 'ext' && o.q.startsWith('orm:'))
4215
+ return this.evArgs(x, q, (args, kw, q2) => this.ormCall(o.q.slice(4), String(fx.f), args, kw, x, q2));
4216
+ if (o.t === 'ref') {
4217
+ const row = q.heap.get(o.id);
4218
+ if (row?.k === 'rec' && this.mod.recs[row.ty]?.orm && ['save', 'delete'].includes(String(fx.f)))
4219
+ return this.evArgs(x, q, (args, kw, q2) => this.ormPersist(o, String(fx.f), args, kw, x, q2));
4220
+ }
3300
4221
  if (o.t === 'val')
3301
4222
  return this.evArgs(x, q, (args, kw, q2) => this.valCall(o, String(fx.f), args, kw, x, q2));
3302
4223
  const ord = this.orderedObj(o, q);
@@ -3333,6 +4254,8 @@ export class Stepper {
3333
4254
  }
3334
4255
  }
3335
4256
  case 'cls': {
4257
+ if (this.mod.recs[f.rec]?.orm)
4258
+ return this.evArgs(x, q, (args, kw, q2) => this.ormCall(f.rec, 'new', args, kw, x, q2));
3336
4259
  // (another module's class made: other code, at the boundary)
3337
4260
  const r = this.inf ? this.mod.recs[f.rec] : undefined;
3338
4261
  if (r && !r.own && !madeByInit(r))
@@ -3440,13 +4363,68 @@ export class Stepper {
3440
4363
  return refuse(x, `${x.text}: set.${name} (the subset reads add, discard, remove and in)`);
3441
4364
  });
3442
4365
  }
4366
+ // This is a presence check, not a speculative getattr: descriptors and custom
4367
+ // lookup can execute code or raise AttributeError even when a name is declared.
4368
+ hasAttribute(v, name, at, p) {
4369
+ if (v.t !== 'ref')
4370
+ return refuse(at, `${at.text}: hasattr requires a modeled instance`);
4371
+ const obj = p.heap.get(v.id);
4372
+ if (obj?.k !== 'rec')
4373
+ return refuse(at, `${at.text}: hasattr requires a modeled record`);
4374
+ const r = this.rec(obj.ty, at);
4375
+ if (!r.mro)
4376
+ return refuse(at, `${at.text}: hasattr needs a known static MRO`);
4377
+ for (const owner of r.mro) {
4378
+ const base = this.rec(owner, at);
4379
+ if (base.declared?.some(n => ['__getattribute__', '__getattr__'].includes(n)))
4380
+ return refuse(at, `${at.text}: hasattr with custom attribute lookup`);
4381
+ }
4382
+ const owner = r.mro.map(n => this.rec(n, at)).find(b => b.declared?.includes(name));
4383
+ if (owner) {
4384
+ const id = owner.methods[name];
4385
+ if (id) {
4386
+ const fn = this.func(id, at);
4387
+ if (fn.decorators.some(d => !['staticmethod', 'classmethod', 'override', 'typing.override', 'abstractmethod'].includes(d.name)))
4388
+ return refuse(at, `${at.text}: hasattr may invoke a descriptor`);
4389
+ }
4390
+ else if (!Object.hasOwn(owner.cattrs ?? {}, name) && !Object.hasOwn(owner.classCollections ?? {}, name)) {
4391
+ return refuse(at, `${at.text}: hasattr cannot resolve the final class binding`);
4392
+ }
4393
+ return true;
4394
+ }
4395
+ if (obj.f.has(name))
4396
+ return true;
4397
+ // Implicit object/type attributes are outside the reader's explicit MRO.
4398
+ if (name.startsWith('__') && name.endsWith('__'))
4399
+ return refuse(at, `${at.text}: hasattr of an implicit object attribute`);
4400
+ return false;
4401
+ }
4402
+ // Entry and nested construction must agree about the final __init__ binding.
4403
+ initMethod(r, at) {
4404
+ const id = r.methods.__init__;
4405
+ if (this.mod.lang !== 'python')
4406
+ return id;
4407
+ const generated = r.kinds.includes('dataclass') || !!r.orm;
4408
+ if (!r.mro && !generated)
4409
+ return refuse(at, `${r.short}: construction needs a known static MRO`);
4410
+ const order = (r.mro ?? [r.name]).map(n => this.rec(n, at));
4411
+ if (order.some(b => b.declared?.some(n => ['__new__', '__init_subclass__', '__getattribute__', '__getattr__', '__setattr__', '__delattr__'].includes(n))))
4412
+ return refuse(at, `${r.short}: custom allocation or attribute hooks are outside modeled construction`);
4413
+ const owner = order.find(b => b.declared?.includes('__init__'));
4414
+ if (owner && (!id || owner.methods.__init__ !== id))
4415
+ return refuse(at, `${r.short}: final __init__ binding is not a known method`);
4416
+ if (id && this.func(id, at).decorators.some(d => !['override', 'typing.override', 'abstractmethod'].includes(d.name)))
4417
+ return refuse(at, `${r.short}: decorated __init__ is outside modeled construction`);
4418
+ return id;
4419
+ }
3443
4420
  construct(rec, args, kw, x, p) {
3444
4421
  const r = this.rec(rec, x);
4422
+ const initId = this.initMethod(r, x);
3445
4423
  // (a plain class of the repository whose __init__ the reader read: made by running it on a fresh object)
3446
4424
  if (madeByInit(r)) {
3447
4425
  const id = `fresh:${this.fresh++}`, q1 = { ...p, heap: new Map(p.heap).set(id, { k: 'rec', ty: rec, f: new Map(), origin: 'fresh' }) };
3448
4426
  this.notes.add(`${r.short}(...) (${x.p}): made by its __init__, read`);
3449
- return [{ t: 'ref', id }, this.callFunc(this.func(r.methods.__init__, x), { t: 'ref', id }, args, kw, x, q1, false)[1]];
4427
+ return [{ t: 'ref', id }, this.callFunc(this.func(initId, x), { t: 'ref', id }, args, kw, x, q1, false)[1]];
3450
4428
  }
3451
4429
  if (!r.kinds.includes('dataclass') || !r.own)
3452
4430
  return refuse(x, `${x.text}: ${r.short} made (the subset makes the module's own dataclasses)`);
@@ -3493,6 +4471,9 @@ export class Stepper {
3493
4471
  return this.evArgs(x, p, (args, kw, q) => {
3494
4472
  if (kw.length)
3495
4473
  return refuse(x, `${x.text}: ${n} given keywords`);
4474
+ if (n === 'str' || n === 'repr')
4475
+ for (const v of args)
4476
+ this.checkOrmDisplay(v, x);
3496
4477
  // (int of a timestamp: its whole seconds)
3497
4478
  if (n === 'int' && args[0]?.t === 'val')
3498
4479
  return args[0].ty === '$ts' ? [{ t: 'num', e: I.divk(1000, this.numOf(args[0].f.get('ms'), x, q)) }, q] : refuse(x, `${x.text}: int of a ${args[0].ty.slice(1)}`);
@@ -3506,6 +4487,16 @@ export class Stepper {
3506
4487
  if (n === 'len' && cl)
3507
4488
  return [{ t: 'num', e: cl.len }, q];
3508
4489
  switch (n) {
4490
+ case 'hasattr': {
4491
+ const name = args[1];
4492
+ if (args.length !== 2 || name?.t !== 'str' || name.e.op !== 'slit')
4493
+ return refuse(x, `${x.text}: hasattr requires an object and a literal attribute name`);
4494
+ return [{ t: 'bool', e: this.hasAttribute(args[0], name.e.value, x, q) ? I.T : I.F }, q];
4495
+ }
4496
+ case '$object_init':
4497
+ if (!args.length)
4498
+ return [{ t: 'none' }, q];
4499
+ return refuse(x, `${x.text}: object.__init__ takes no arguments`);
3509
4500
  case 'min':
3510
4501
  case 'max': {
3511
4502
  if (args.length < 2)
@@ -3540,24 +4531,40 @@ export class Stepper {
3540
4531
  return refuse(x, `${x.text}: ${n}() (a builtin outside the subset)`);
3541
4532
  });
3542
4533
  }
3543
- // (even: Python's round(a / k), the nearest whole number, a half to the even one: exact for |a| below 2^53, where the
3544
- // float a / k is within half its last place of a / k, so it lands on a half only where a / k is one)
4534
+ // a / k rounded to a whole number, for a constant k: floor, ceil and trunc (toward zero) exact for |a| below 2^53 (the
4535
+ // float a / k is within half its last place of a / k, less than 1/k from it, so it never reaches the next whole
4536
+ // number); to the nearest, a half to the even one (`even`: Python's round, Java's Math.rint), up (`up`: Java's and
4537
+ // JavaScript's Math.round) or away from zero (`away`: Go's math.Round, Rust's round, C's round) exact for |a| below
4538
+ // 2^52 only: a / k not a half is at least 1/(2k) from one, and the float is within |a / k|·2^-53 of it, less than
4539
+ // 1/(2k) only there (3·2^51 + 2 over 3 lands on a half). Past it, an edge: the claim is for |a| below 2^52.
3545
4540
  quotient(d, p, round) {
3546
4541
  const [a, q] = this.ev(d.x, p), [b, q2] = this.ev(d.y, q), k = constOf(b);
3547
4542
  if (k === undefined)
3548
4543
  return refuse(d, `${d.text}: a division by a value that isn't a constant`);
4544
+ if (k === 0 && d.fdiv)
4545
+ return refuse(d, `${d.text}: a float division by 0 rounded (an infinity or NaN)`);
3549
4546
  if (k === 0) {
3550
4547
  this.fail(q2, I.T, d, `${d.text}: a division by zero (a ZeroDivisionError)`);
3551
4548
  return [{ t: 'num', e: I.num(0) }, { ...q2, pc: [...q2.pc, I.F] }];
3552
4549
  }
4550
+ if (!Number.isSafeInteger(k))
4551
+ return refuse(d, `${d.text}: a division by a constant that isn't whole`);
3553
4552
  const n = this.numOf(a, d, q2), fl = this.floorDiv(n, k), ce = I.neg(this.floorDiv(I.neg(n), k));
3554
4553
  const lt = k > 0 ? I.cmp('<', n, I.num(0)) : I.cmp('<', I.num(0), n);
3555
- if (round === 'even') {
3556
- // (r = a − k·⌊a/k⌋: below half of k the floor, past it one more, at it the even of the two)
3557
- const r2 = I.mulk(2, I.sub(n, I.mulk(k, fl))), half = I.num(k), below = k > 0 ? I.cmp('<', r2, half) : I.cmp('<', half, r2), above = k > 0 ? I.cmp('<', half, r2) : I.cmp('<', r2, half);
3558
- return [{ t: 'num', e: I.nite(below, fl, I.nite(above, I.add(fl, I.num(1)), I.add(fl, I.sub(fl, I.mulk(2, I.divk(2, fl)))))) }, q2];
3559
- }
3560
- return [{ t: 'num', e: round === 'floor' ? fl : round === 'ceil' ? ce : I.nite(lt, ce, fl) }, q2];
4554
+ // (a float's precision: a double's 53 bits (Python's and the rule's own bound), a float's 24: past 2^bits, a / k and
4555
+ // its operands aren't exact, an edge)
4556
+ const bits = d.prec ?? 53, edge = (e, why) => { if (Math.abs(k) > 1 || bits < 53)
4557
+ this.refuseWhere(q2, I.or(I.cmp('<=', I.num(2 ** e), n), I.cmp('<=', n, I.num(-(2 ** e)))), d, `${d.text}: ${why}`, false); };
4558
+ if (round === 'floor' || round === 'ceil' || round === 'trunc') {
4559
+ if (bits < 53)
4560
+ edge(bits, `rounded at |a| of 2^${bits} or more (past a float's precision)`);
4561
+ return [{ t: 'num', e: round === 'floor' ? fl : round === 'ceil' ? ce : I.nite(lt, ce, fl) }, q2];
4562
+ }
4563
+ // (a / k as m / j with j = |k| > 0: q = ⌊m/j⌋, r = m − j·q in [0, j); below half of j q, past it q + 1, at it the mode's)
4564
+ const j = Math.abs(k), m = k > 0 ? n : I.neg(n), qq = I.divk(j, m), r2 = I.mulk(2, I.sub(m, I.mulk(j, qq))), half = I.num(j);
4565
+ const tie = round === 'even' ? I.add(qq, I.sub(qq, I.mulk(2, I.divk(2, qq)))) : round === 'up' ? I.add(qq, I.num(1)) : I.nite(I.cmp('<', m, I.num(0)), qq, I.add(qq, I.num(1)));
4566
+ edge(bits - 1, `rounded to the nearest at |a| of 2^${bits - 1} or more (the float a / k may land on a half there)`);
4567
+ return [{ t: 'num', e: I.nite(I.cmp('<', r2, half), qq, I.nite(I.cmp('<', half, r2), I.add(qq, I.num(1)), tie)) }, q2];
3561
4568
  }
3562
4569
  lib(q0, x, p) {
3563
4570
  const a0 = x.args[0];
@@ -3571,15 +4578,24 @@ export class Stepper {
3571
4578
  return [{ t: 'lock' }, p];
3572
4579
  // A datetime: the request's time (in whole seconds, as time.time()), in milliseconds; a timedelta by its parts.
3573
4580
  if (q0 === 'datetime.datetime.now') {
3574
- if (x.args.length || x.kw.length)
3575
- return refuse(x, `${x.text}: now() given a time zone`);
4581
+ const args = x.args, kw = x.kw;
4582
+ const zone = args[0] ?? kw.find(([k]) => k === 'tz')?.[1];
4583
+ const isUTC = (z) => !!z && ((z.e === 'ext' && z.q === 'datetime.timezone.utc') || (z.e === 'get' && z.f === 'utc' && z.x.e === 'ext' && z.x.q === 'datetime.timezone'));
4584
+ if (args.length + kw.length > 1 || (kw.length && kw[0][0] !== 'tz') || (zone && !isUTC(zone)))
4585
+ return refuse(x, `${x.text}: only timezone.utc is supported`);
3576
4586
  this.notes.add(`${q0}() is the request's time (an input, at whole seconds: the claim is for those)`);
4587
+ if (!zone) {
4588
+ this.naiveUtc = true;
4589
+ this.notes.add('naive datetime clocks require a UTC process timezone');
4590
+ }
3577
4591
  const [t, q] = this.clock(x, p);
3578
- return [{ t: 'val', ty: '$dt', f: new Map([['ms', { t: 'num', e: I.mulk(1000, t.e) }]]) }, q];
4592
+ return [{ t: 'val', ty: '$dt', f: new Map([['ms', { t: 'num', e: I.mulk(1000, t.e) }], ['utc', { t: 'bool', e: zone ? I.T : I.F }]]) }, q];
3579
4593
  }
3580
- if (q0 === 'datetime.timedelta')
4594
+ if (q0 === 'datetime.timedelta' || q0 === 'dateutil.relativedelta.relativedelta')
3581
4595
  return this.evArgs(x, p, (args, kw, q) => {
3582
4596
  const unit = { days: 86_400_000, seconds: 1000, milliseconds: 1, minutes: 60_000, hours: 3_600_000, weeks: 604_800_000 };
4597
+ if (q0 === 'dateutil.relativedelta.relativedelta' && args.length)
4598
+ return refuse(x, `${x.text}: relativedelta requires named linear durations`);
3583
4599
  if (args.length > 1)
3584
4600
  return refuse(x, `${x.text}: a timedelta of positional parts past its days`);
3585
4601
  const parts = [...(args.length ? [['days', args[0]]] : []), ...kw];
@@ -3671,6 +4687,10 @@ export class Stepper {
3671
4687
  const seg = segs[0], rest = segs.slice(1), out = new Map(fs);
3672
4688
  if (!rest.length) {
3673
4689
  const old = fs.get(seg);
4690
+ if (old?.t === 'opaque' && old.sink) {
4691
+ out.set(seg, old);
4692
+ return out;
4693
+ }
3674
4694
  if (old?.t === 'opaque')
3675
4695
  refuse(at, `writes ${old.why}`);
3676
4696
  out.set(seg, x);
@@ -3823,13 +4843,13 @@ export class Stepper {
3823
4843
  }
3824
4844
  numv(v, at) {
3825
4845
  if (v.t !== 'num')
3826
- return refuse(at, `${at.text ?? ''}: a ${v.t} where a number is read`);
4846
+ return refuse(at, `${at.text ?? ''}: ${v.t === 'opaque' ? v.why : `a ${v.t}`} where a number is read`);
3827
4847
  if (v.slen)
3828
4848
  return refuse(at, 'len of a string read other than against 0 (strings are set and compared in the subset)');
3829
4849
  return v.e;
3830
4850
  }
3831
4851
  boolv(v, at) { if (v.t !== 'bool')
3832
- return refuse(at, `${at.text ?? ''}: a ${v.t} where a condition is read`); return v.e; }
4852
+ return refuse(at, `${at.text ?? ''}: ${v.t === 'opaque' ? v.why : `a ${v.t}`} where a condition is read`); return v.e; }
3833
4853
  // A binary operation of the reader's language with fixed-width integers (Go's): comparisons, arithmetic wrapped.
3834
4854
  binop(op, a, b, x, p) {
3835
4855
  if (op === '==' || op === '!=') {
@@ -3867,8 +4887,97 @@ export class Stepper {
3867
4887
  return refuse(x, 'strings joined (strings are set and compared in the subset)');
3868
4888
  return this.arith(op, a, b, x, p);
3869
4889
  }
4890
+ if (['&', '|', '^', '&^'].includes(op) && a.t === 'num' && b.t === 'num')
4891
+ return this.bitop(op, a, b, x);
3870
4892
  return refuse(x, `${op}: a bit operation (outside the subset)`);
3871
4893
  }
4894
+ // A bit operation with a constant (a flag set, cleared, tested, toggled; a mask), or with a value that is 0 or 1: exact
4895
+ // in linear terms, in two's complement of any width (floor division and remainder take a negative value's bits):
4896
+ // x & K, K ≥ 0, is the sum over K's runs of ones [lo, lo + n) of ((x div 2^lo) mod 2^n)·2^lo; x & K, K < 0, is
4897
+ // x − (x & ~K); x | K = x + K − (x & K); x ^ K = x + K − 2(x & K); x &^ K = x − (x & K). Of two values neither
4898
+ // constant nor 0 or 1, refused (bit-vectors).
4899
+ bitop(op, a, b, x) {
4900
+ const ty = a.ty?.name !== undefined ? a.ty : b.ty, at = x.text ? `${x.text}: ` : '';
4901
+ const isK = (v) => v.op === 'const', bit01 = (v) => { const [lo, hi] = this.bounds(v); return lo >= 0 && hi <= 1; };
4902
+ // (two values at least 0 of few bits, a byte's flags masked by another's: bit by bit, each bit a case)
4903
+ const width = (v) => { const [lo, hi] = this.bounds(v); if (lo < 0 || !Number.isFinite(hi))
4904
+ return Infinity; let w = 0; while (2 ** w <= hi)
4905
+ w++; return w; };
4906
+ if (!isK(a.e) && !isK(b.e) && !bit01(a.e) && !bit01(b.e) && Math.max(width(a.e), width(b.e)) <= 16) {
4907
+ const w = Math.max(width(a.e), width(b.e)), bit = (v, j) => I.cmp('=', I.modk(2, I.divk(2 ** j, v)), I.num(1));
4908
+ let e = I.num(0);
4909
+ for (let j = 0; j < w; j++) {
4910
+ const x1 = bit(a.e, j), y1 = bit(b.e, j), on = op === '&' ? I.and(x1, y1) : op === '|' ? I.or(x1, y1) : op === '^' ? I.or(I.and(x1, I.not(y1)), I.and(I.not(x1), y1)) : I.and(x1, I.not(y1));
4911
+ e = I.add(e, I.nite(on, I.num(2 ** j), I.num(0)));
4912
+ }
4913
+ return { t: 'num', e, ty };
4914
+ }
4915
+ const [vv, wv] = isK(b.e) ? [a, b] : isK(a.e) ? [b, a] : bit01(b.e) ? [a, b] : bit01(a.e) ? [b, a] : refuse(x, `${at}${op} of two values neither of them a constant nor of 16 bits or fewer (bit-vectors are outside the subset)`);
4916
+ const v = vv.e, w = wv.e, first = vv === a;
4917
+ if (!isK(w)) {
4918
+ // (with a value that is 0 or 1: its low bit, where that value is 1)
4919
+ const k = I.nite(I.cmp('=', w, I.num(1)), I.modk(2, v), I.num(0));
4920
+ return { t: 'num', e: op === '&' ? k : op === '|' ? I.sub(I.add(v, w), k) : op === '^' ? I.sub(I.add(v, w), I.mulk(2, k)) : first ? I.sub(v, k) : I.sub(w, k), ty };
4921
+ }
4922
+ const K = w.v;
4923
+ // (x &^ K, Go's: x & ~K; K &^ x: K & ~x, read as K − (K & x))
4924
+ if (op === '&^' && !first) {
4925
+ const k = this.bitop('&', vv, wv, x);
4926
+ return { t: 'num', e: I.sub(I.num(K), k.e), ty };
4927
+ }
4928
+ // A value at least 0 below 2^w: its form (x & A) ^ B composed with this one (K within its w bits).
4929
+ const form = vv.bits ?? this.bitsOf(v);
4930
+ if (form) {
4931
+ const m = 2 ** form.w, k = ((K % m) + m) % m, f = op === '&' ? { ...form, A: and(form.A, k), B: and(form.B, k) } : op === '|' ? { ...form, A: and(form.A, m - 1 - k), B: or(form.B, k) } : op === '^' ? { ...form, B: xor(form.B, k) } : { ...form, A: and(form.A, m - 1 - k), B: and(form.B, m - 1 - k) };
4932
+ // (K's bits past w: x | K and x ^ K keep them, past every bit x has)
4933
+ const past = op === '|' || op === '^' ? K - k : 0;
4934
+ if (past && (K < 0 || ty.signed !== false))
4935
+ return this.bitGeneric(op, v, w, first, ty, x);
4936
+ const e = this.ofBits(f, x);
4937
+ return { t: 'num', e: past ? I.add(e, I.num(past)) : e, ty, ...(past ? {} : { bits: f }) };
4938
+ }
4939
+ return this.bitGeneric(op, v, w, first, ty, x);
4940
+ }
4941
+ // (x & A) ^ B as a term, a natural by its form: x's bits where A is set and B isn't, plus the complement of x's bits
4942
+ // where both are (AB − (x & AB)), plus B's bits where A isn't; each x & K the sum over K's runs of ones [lo, lo + n) of
4943
+ // ((x div 2^lo) mod 2^n)·2^lo.
4944
+ ofBits(f, at) {
4945
+ const ab = and(f.A, f.B), kept = f.A - ab, set = f.B - ab;
4946
+ let e = kept ? this.andRuns(f.x, kept, at) : I.num(0);
4947
+ if (ab)
4948
+ e = I.add(e, I.sub(I.num(ab), this.andRuns(f.x, ab, at)));
4949
+ return set ? I.add(e, I.num(set)) : e;
4950
+ }
4951
+ andRuns(v, k, at) {
4952
+ const runs = [];
4953
+ for (let i = 0, r = k; r > 0; i++, r = Math.floor(r / 2))
4954
+ if (r % 2) {
4955
+ const last = runs.at(-1);
4956
+ if (last && last[0] + last[1] === i)
4957
+ last[1]++;
4958
+ else
4959
+ runs.push([i, 1]);
4960
+ }
4961
+ if (runs.length > 16)
4962
+ return refuse(at, `${at.text ? `${at.text}: ` : ''}a mask of more than 16 runs of ones`);
4963
+ return runs.reduce((s, [lo, n]) => I.add(s, I.mulk(2 ** lo, I.modk(2 ** n, I.divk(2 ** lo, v)))), I.num(0));
4964
+ }
4965
+ // (a value at least 0 with a finite bound: x itself, every bit of its w kept)
4966
+ bitsOf(v) {
4967
+ const [lo, hi] = this.bounds(v);
4968
+ if (!(lo >= 0 && Number.isFinite(hi) && hi < 2 ** 53))
4969
+ return undefined;
4970
+ let w = 0;
4971
+ while (2 ** w <= hi)
4972
+ w++;
4973
+ return { x: v, A: 2 ** w - 1, B: 0, w };
4974
+ }
4975
+ // In two's complement of any width (floor division and remainder take a negative value's bits): x & K, K < 0, is
4976
+ // x − (x & ~K); x | K = x + K − (x & K); x ^ K = x + K − 2(x & K); x &^ K = x − (x & K).
4977
+ bitGeneric(op, v, w, first, ty, x) {
4978
+ const K = w.v, andK = (kk) => (kk < 0 ? I.sub(v, andK(-kk - 1)) : this.andRuns(v, kk, x)), k = andK(K);
4979
+ return { t: 'num', e: op === '&' ? k : op === '|' ? I.sub(I.add(v, w), k) : op === '^' ? I.sub(I.add(v, w), I.mulk(2, k)) : first ? I.sub(v, k) : I.sub(w, k), ty };
4980
+ }
3872
4981
  eq(a, b, x, p) {
3873
4982
  if (a.t === 'map' && b.t === 'nil' && p)
3874
4983
  return this.mapAt(a, x, p).nil;
@@ -3899,12 +5008,15 @@ export class Stepper {
3899
5008
  }
3900
5009
  if ((a.t === 'list' || a.t === 'map') && b.t === 'nil')
3901
5010
  return refuse(x, `a ${a.t === 'list' ? 'slice' : 'map'} compared with nil (nil and empty are one ${a.t === 'list' ? 'list' : 'map'} in the subset)`);
3902
- return refuse(x, `${a.t === 'opaque' && a.ask ? a.why : `a ${a.t}`} compared with a ${b.t}`);
5011
+ return refuse(x, `${a.t === 'opaque' && a.ask ? a.why : `a ${a.t}`} compared with ${b.t === 'opaque' && b.ask ? b.why : `a ${b.t}`}`);
3903
5012
  }
3904
5013
  // Integer arithmetic at the type's width: the exact result, wrapped as the type wraps it (or refused, at 64 bits).
3905
5014
  arith(op, a, b, x, p) {
3906
- if (a.t !== 'num' || b.t !== 'num')
3907
- return refuse(x, `${op} of a ${a.t} and a ${b.t}`);
5015
+ // (other code's value left out, computed with: named, so the next run answers it)
5016
+ if (a.t !== 'num' || b.t !== 'num') {
5017
+ const o = [a, b].find(v => v.t === 'opaque');
5018
+ return refuse(x, o ? `${x.text ?? op}: arithmetic on ${o.why}` : `${op} of a ${a.t} and a ${b.t}`);
5019
+ }
3908
5020
  this.numv(a, x);
3909
5021
  this.numv(b, x);
3910
5022
  const ty = a.ty?.name !== undefined ? a.ty : b.ty;
@@ -3967,7 +5079,10 @@ export class Stepper {
3967
5079
  const a = this.bounds(e.a), b = this.bounds(e.b);
3968
5080
  return [a[0] + b[0], a[1] + b[1]];
3969
5081
  }
5082
+ // (x − k·(x div k): x's floor remainder by k, a conversion's wrap)
3970
5083
  case 'sub': {
5084
+ if (e.b.op === 'mulk' && e.b.a.op === 'divk' && e.b.a.k === e.b.k && I.same(e.b.a.a, e.a))
5085
+ return [0, e.b.k - 1];
3971
5086
  const a = this.bounds(e.a), b = this.bounds(e.b);
3972
5087
  return [a[0] - b[1], a[1] - b[0]];
3973
5088
  }
@@ -4462,6 +5577,11 @@ const cellV = (map, i, f, s, ty) => {
4462
5577
  const c = { op: 'cell', map, key: { op: 'num', e: i }, field: f };
4463
5578
  return s.k === 'num' ? { t: 'num', e: c, ...(ty ? { ty } : {}) } : s.k === 'bool' ? { t: 'bool', e: c } : s.k === 'str' ? { t: 'str', e: c } : { t: 'choice', e: { ...c, values: s.k === 'choice' ? s.values : [] } };
4464
5579
  };
5580
+ // The fields of a collection's items an order reads (its parts over an item at a key).
5581
+ const orderFields = (by, d) => { const out = new Set(); JSON.stringify(by({ op: 'num', e: I.nvar('kl$') }), (k, v) => { if (k === 'field' && typeof v === 'string' && d.fields.some(f => f.name === v))
5582
+ out.add(v); return v; }); return [...out]; };
5583
+ // A value with a numeric bound name (k$) replaced by a term, in its terms.
5584
+ const substV = (v, name, by) => (v.t === 'num' || v.t === 'bool' || v.t === 'choice' || v.t === 'str' ? { ...v, e: I.substN(v.e, name, by) } : v);
4465
5585
  const sortOfV = (v) => (v.t === 'num' ? { k: 'num' } : v.t === 'bool' ? { k: 'bool' } : v.t === 'choice' ? { k: 'choice', values: lvalues(v.e) } : v.t === 'str' ? { k: 'str' } : undefined);
4466
5586
  const termOfV = (v, at) => (v.t === 'num' ? { s: 'num', e: v.e } : v.t === 'bool' ? { s: 'bool', e: v.e } : v.t === 'choice' ? { s: 'choice', e: v.e } : v.t === 'str' ? { s: 'str', e: v.e } : refuse(at, `a ${v.t} where a fold keeps a number, a boolean, a string or a choice`));
4467
5587
  // The locals a body sets (each statement's targets), by name.
@@ -4607,6 +5727,13 @@ export function readStep(mod, opts) {
4607
5727
  }
4608
5728
  }
4609
5729
  }
5730
+ class InitializerChoice extends Refusal {
5731
+ initializers;
5732
+ constructor(r) {
5733
+ super(r.p, `${r.short}: several constructors (select ctor, or check every initializer with the CLI)`);
5734
+ this.initializers = { entry: r.name, name: r.short, selectors: r.initializers };
5735
+ }
5736
+ }
4610
5737
  function readOnce(mod, opts, g) {
4611
5738
  if (mod.error)
4612
5739
  refuse(mod.file ?? mod.root ?? '?', mod.error);
@@ -4646,11 +5773,13 @@ function readOnce(mod, opts, g) {
4646
5773
  g.method = '__init__';
4647
5774
  const r0 = g.refusals.length;
4648
5775
  let made;
4649
- const initId = r.methods.__init__;
5776
+ const initId = g.initMethod(r, at);
4650
5777
  if (initId)
4651
5778
  g.entryIds.add(initId);
4652
5779
  if (r.kinds.some(k => k.startsWith('generic:')))
4653
5780
  refuse(r, `${r.short}: a generic type (its methods read a type parameter)`);
5781
+ if (r.initializers && r.initializers.length > 1)
5782
+ throw new InitializerChoice(r);
4654
5783
  const rustNew = mod.lang === 'rust' ? r.methods.new : undefined;
4655
5784
  if (rustNew)
4656
5785
  g.entryIds.add(rustNew);
@@ -4758,13 +5887,15 @@ function readOnce(mod, opts, g) {
4758
5887
  if (ctor.length)
4759
5888
  g.notes.add(`${r.short} made by its constructor: its arguments are the rule's params`);
4760
5889
  }
4761
- else if (r.kinds.includes('dataclass')) {
5890
+ else if (r.kinds.includes('dataclass') || r.orm) {
5891
+ if (r.orm?.why)
5892
+ refuse(r, r.orm.why);
4762
5893
  const f = new Map();
4763
5894
  let p = fresh;
4764
5895
  for (const fd of r.fields) {
4765
5896
  if (fd.dflt) {
4766
5897
  const [d, p2] = g.ev(fd.dflt, p);
4767
- f.set(fd.name, d);
5898
+ f.set(fd.name, g.timeField(d, fd.t, false, { p: r.p }));
4768
5899
  p = p2;
4769
5900
  g.declared.set(`this.${fd.name}`, fd.t);
4770
5901
  continue;
@@ -4772,14 +5903,14 @@ function readOnce(mod, opts, g) {
4772
5903
  const [v, a] = g.input(fd.name, fd.t, { p: r.p }, p, 'param');
4773
5904
  if (a.k === 'inert')
4774
5905
  refuse(r, `${r.short}.${fd.name}: a field of ${g.why(fd.t)}`);
4775
- f.set(fd.name, v);
5906
+ f.set(fd.name, g.timeField(v, fd.t, false, { p: r.p }));
4776
5907
  ctor.push([fd.name, a]);
4777
5908
  g.declared.set(`this.${fd.name}`, fd.t);
4778
5909
  }
4779
5910
  if (r.methods.__post_init__)
4780
5911
  refuse(r, `${r.short}: __post_init__`);
4781
5912
  made = { ...p, heap: new Map(p.heap).set('this', { k: 'rec', ty: cls, f, origin: 'state' }) };
4782
- g.notes.add(`${r.short}: a dataclass, made with its fields' defaults (the claim is for objects made so) and the others as params`);
5913
+ g.notes.add(r.orm ? `${r.short}: a ${r.orm.framework} row; every declared column supplied as a parameter, no database read by its constructor` : `${r.short}: a dataclass, made with its fields' defaults (the claim is for objects made so) and the others as params`);
4783
5914
  }
4784
5915
  else
4785
5916
  made = fresh;
@@ -5087,18 +6218,18 @@ function readOnce(mod, opts, g) {
5087
6218
  const id = [...g.initHeap].find(([, o]) => o.k === 'map' && o.decl === d)?.[0];
5088
6219
  if (!id)
5089
6220
  continue;
5090
- const cw = (w0) => ({ key: w0.key, has: w0.has, vals: Object.fromEntries([...w0.vals].map(([f2, v]) => [f2, termOf(v, at)])) });
5091
- const lists = finals.map(f => { const o = f.path.heap.get(id); return [...(o?.pre ?? []), ...(o?.w ? [o.w] : [])].map(cw); });
6221
+ const cw = (w0, each) => ({ key: w0.key, has: w0.has, vals: Object.fromEntries([...w0.vals].map(([f2, v]) => [f2, termOf(v, at)])), ...(each ? { each: true } : {}) });
6222
+ const lists = finals.map(f => { const o = f.path.heap.get(id); return [...(o?.ew ? [cw(o.ew, true)] : []), ...[...(o?.pre ?? []), ...(o?.w ? [o.w] : [])].map(w0 => cw(w0))]; });
5092
6223
  // (a failure kept, the cell as it was there)
5093
6224
  const fix = (i, w2, base) => { if (!kept || carried)
5094
6225
  return w2; const fl = failedOf(finals[i]), b = base(w2.key); return { key: w2.key, has: I.bite(fl, b.has, w2.has), vals: Object.fromEntries(Object.entries(w2.vals).map(([f, t]) => [f, iteTerm(fl, b.vals[f], t)])) }; };
5095
6226
  // (several keys written by some method: each method's writes under its own selector, so a key compared is the
5096
6227
  // request's, never one of two by the method)
5097
6228
  const base = (k) => { const c = g.baseCell(d, k); return { key: k, has: c.has, vals: Object.fromEntries([...c.vals].map(([f2, v]) => [f2, termOf(v, at)])) }; };
5098
- const ws = lists.some(l => l.length > 1) ? finals.flatMap((f, i) => lists[i].map(w2 => ({ ...fix(i, w2, base), when: f.sel }))) : [];
6229
+ const ws = lists.some(l => l.length > 1 || l.some(w0 => w0.each)) ? finals.flatMap((f, i) => lists[i].map(w2 => ({ ...fix(i, w2, base), when: f.sel }))) : [];
5099
6230
  const w = ws.length ? ws.at(-1) : mapWritesOf(g, d, finals.map(f => f.sel), lists.map(l => l[0]), fix);
5100
6231
  if (w)
5101
- mapWrites[d.name] = ws.length > 1 ? { ...w, pre: ws.slice(0, -1) } : w;
6232
+ mapWrites[d.name] = ws.length > 1 ? { ...w, pre: ws.slice(0, -1) } : w.each ? { ...w, pre: [] } : w;
5102
6233
  }
5103
6234
  // What each method returns, and whether it failed: the step's result.
5104
6235
  const results = {}, resultKinds = {};
@@ -5209,6 +6340,10 @@ function readOnce(mod, opts, g) {
5209
6340
  // Inputs no term reads are still the request's (the check builds the arguments from them).
5210
6341
  const maps = g.maps.filter(d => [...g.initHeap.values()].some(o => o.k === 'map' && o.decl === d));
5211
6342
  const stores = Object.fromEntries([...new Set([...Object.keys(opts.stores ?? {}), ...g.storeDecls.keys()])].map(n => [n, { ...g.storeDecl(n), async: g.storeAsync[n] ?? {} }]));
6343
+ for (const [rec, table] of g.ormTables) {
6344
+ const r = g.rec(rec, at);
6345
+ leaves.push({ name: table.decl.name, path: [], kind: 'map', key: table.decl.key, orm: { rec, key: r.orm.key, framework: r.orm.framework, fields: r.fields } });
6346
+ }
5212
6347
  for (const sm of g.storeMaps.values()) {
5213
6348
  const str = sm.decl.fields[0]?.sort.k === 'str' && !sm.json;
5214
6349
  leaves.push({ name: sm.decl.name, path: [], kind: 'map', key: sm.decl.key, store: sm.store, tpl: sm.tpl, ...(stores[sm.store]?.value !== 'int' && stores[sm.store]?.values?.[sm.tpl] !== 'int' && !sm.json && !sm.choice && !str ? { float: true } : {}), ...(sm.json ? { json: sm.json } : {}), ...(sm.choice ? { choice: true } : {}), ...(str ? { str: true } : {}) });
@@ -5247,6 +6382,16 @@ function readOnce(mod, opts, g) {
5247
6382
  if (g.vars.get(base)?.sort.k === 'num')
5248
6383
  laws.push(`r.law(${JSON.stringify(`${base}: a None one holds 0`)}, ({${base}, ${l.name}}) => any(${l.name}.not(), ${base}.eq(0)))`);
5249
6384
  }
6385
+ for (const [rec, table] of g.ormTables) {
6386
+ const nullable = g.rec(rec, at).fields.filter(f => f.t.k === 'opt'), n = table.decl.name;
6387
+ if (nullable.length) {
6388
+ const zero = (f) => {
6389
+ const t = f.t.k === 'opt' ? f.t.of : f.t, cell = `${n}.at(k).${f.name}`;
6390
+ return t.k === 'bool' ? `${cell}.not()` : t.k === 'str' ? `${cell}.eq('')` : `${cell}.eq(0)`;
6391
+ };
6392
+ laws.push(`r.law(${JSON.stringify(`${n}: absent nullable columns hold the default`)}, ({${n}}) => forall(k => all(${nullable.map(f => `any(${n}.at(k).${f.name}_has, ${zero(f)})`).join(', ')})))`);
6393
+ }
6394
+ }
5250
6395
  // (a stored JSON record's optional field: absent, its cell holds the default, as the text holds nothing there)
5251
6396
  for (const sm of g.storeMaps.values()) {
5252
6397
  const opts = (sm.json ?? []).filter(f => f.opt), n = sm.decl.name;
@@ -5276,9 +6421,11 @@ function readOnce(mod, opts, g) {
5276
6421
  }
5277
6422
  mention(refuseB);
5278
6423
  mention(pre);
5279
- for (const fd of g.folds)
6424
+ for (const fd of g.folds) {
5280
6425
  for (const t of [...Object.values(fd.init), ...Object.values(fd.step)])
5281
6426
  mention(t.e);
6427
+ mention(fd.len);
6428
+ }
5282
6429
  const unread = g.inputs.filter(v => !read.has(v.name) && v.name !== ev?.name && !g.kept.has(v.name));
5283
6430
  if (unread.length)
5284
6431
  g.notes.add(`read by the code but by no term of the rule (given their sort's zero, or None, by the check): ${unread.map(v => v.name).join(', ')}`);
@@ -5325,9 +6472,9 @@ function readOnce(mod, opts, g) {
5325
6472
  params: g.params, inputs, state, maps, init, writes, mapWrites, outputs,
5326
6473
  refuse: refuseB, pre, layout, events, notes: [...g.notes], hints: g.hints, ...(ev ? { event: ev.name } : {}), results, laws,
5327
6474
  ...(g.leasts.length ? { leasts: g.leasts } : {}),
5328
- ...(g.used.size ? { seqs: g.seqs.filter(d => g.used.has(d.name)), folds: g.folds } : {}),
6475
+ ...(g.used.size || g.folds.length ? { seqs: g.seqs.filter(d => g.used.has(d.name)), folds: g.folds } : {}),
5329
6476
  };
5330
- return { ints: Object.fromEntries(g.ints), ...(g.madeAt ? { madeAt: g.madeAt.name } : {}), model, leaves, args: argsOf, answers: [...g.answers.values()], ctor, kept, arms: [...g.arms].map(a => { const i = a.lastIndexOf(':'); return [a.slice(0, i), Number(a.slice(i + 1))]; }), ...(cls ? { cls } : {}), stores, results: resultKinds, ...(g.injectedFields.length ? { inject: g.injectedFields } : {}), ...(g.globalStores.length ? { globals: g.globalStores } : {}), ...(g.inertAttrs.length ? { inert: g.inertAttrs } : {}), ...(effectVars.length ? { effectsOf: Object.fromEntries(finals.map((f, i) => [chosen[i].name, effectVars.filter(e => f.path.eff?.has(e.key)).map(e => e.v.name)])) } : {}) };
6477
+ return { ints: Object.fromEntries(g.ints), ...(g.naiveUtc ? { naiveUtc: true } : {}), ...(g.madeAt ? { madeAt: g.madeAt.name } : {}), model, leaves, args: argsOf, answers: [...g.answers.values()], ctor, kept, arms: [...g.arms].map(a => { const i = a.lastIndexOf(':'); return [a.slice(0, i), Number(a.slice(i + 1))]; }), ...(cls ? { cls } : {}), stores, results: resultKinds, ...(g.injectedFields.length ? { inject: g.injectedFields } : {}), ...(g.globalStores.length ? { globals: g.globalStores } : {}), ...(g.inertAttrs.length ? { inert: g.inertAttrs } : {}), ...(g.edges.length ? { edges: g.edges } : {}), ...(effectVars.length ? { effectsOf: Object.fromEntries(finals.map((f, i) => [chosen[i].name, effectVars.filter(e => f.path.eff?.has(e.key)).map(e => e.v.name)])) } : {}) };
5331
6478
  }
5332
6479
  // A type's range (64 bits and wider: the rule's numbers stop at ±2^53 before the type's do, and are refused there).
5333
6480
  export const rangeOf = (ty) => (ty.bits === 0 || ty.bits >= 64 ? (ty.signed ? [-Infinity, Infinity] : [0, Infinity]) : ty.signed ? [-(2 ** (ty.bits - 1)), 2 ** (ty.bits - 1) - 1] : [0, 2 ** ty.bits - 1]);
@@ -5482,7 +6629,7 @@ function checkStepOnce(h, read, r, sorts, opts) {
5482
6629
  throw new HarnessFailure('the harness stopped before it answered');
5483
6630
  return stopped(JSON.parse(l));
5484
6631
  };
5485
- const hi = ask({ op: 'hello', ...h.hello, leaves: read.leaves, ctor: read.ctor, answers: read.answers, kept: read.kept, cls: read.cls ?? null, stores: read.stores, arms: read.arms, discard: opts.onError === 'discard', ...(read.inject ? { inject: read.inject } : {}), ...(read.globals ? { globals: read.globals } : {}), ...(read.inert ? { inert: read.inert } : {}), ...(opts.fields ? { fields: opts.fields } : {}) });
6632
+ const hi = ask({ op: 'hello', ...h.hello, naiveUtc: read.naiveUtc, leaves: read.leaves, ctor: read.ctor, answers: read.answers, kept: read.kept, cls: read.cls ?? null, stores: read.stores, arms: read.arms, discard: opts.onError === 'discard', ...(read.inject ? { inject: read.inject } : {}), ...(read.globals ? { globals: read.globals } : {}), ...(read.inert ? { inert: read.inert } : {}), ...(opts.fields ? { fields: opts.fields } : {}) });
5486
6633
  if (hi.error)
5487
6634
  return { ...empty, mismatch: `the code doesn't load with the check's harness: ${JSON.stringify(hi.error)}` };
5488
6635
  const num = (x, at) => { const n = Number(x); if (typeof x === 'string' && Number.isSafeInteger(n) && String(n) === x)
@@ -5498,7 +6645,7 @@ function checkStepOnce(h, read, r, sorts, opts) {
5498
6645
  };
5499
6646
  const j = (x) => (typeof x === 'number' ? String(x) : x);
5500
6647
  const snapJson = (s) => ({ ...Object.fromEntries(Object.entries(s.leaves).map(([k, v]) => [k, j(v)])), ...Object.fromEntries(Object.entries(s.maps).map(([k, cells]) => [k, Object.fromEntries(Object.entries(cells).map(([key, c]) => [key, Object.fromEntries(Object.entries(c).map(([f, x]) => [f, j(x)]))]))])) });
5501
- const build = (a, inputs) => (a.k === 'in' ? { in: inputs[a.name] ?? a.z ?? 0, ...(a.float ? { float: true } : {}), ...(a.sym ? { sym: true } : {}), ...(a.bytes ? { bytes: true } : {}) } : a.k === 'opt' ? (inputs[a.none] === true ? { none: true } : build(a.v, inputs)) : a.k === 'rec' ? (a.f.length ? { rec: a.cls, f: Object.fromEntries(a.f.map(([f, x]) => [f, build(x, inputs)])) } : { inert: true }) : a.k === 'inert' ? { inert: true, ...(a.dict ? { dict: true } : {}) } : a.k === 'store' ? { store: a.name }
6648
+ const build = (a, inputs) => (a.k === 'in' ? { in: inputs[a.name] ?? a.z ?? 0, ...(a.float ? { float: true } : {}), ...(a.sym ? { sym: true } : {}), ...(a.bytes ? { bytes: true } : {}), ...(a.time ? { time: a.time } : {}) } : a.k === 'opt' ? (inputs[a.none] === true ? { none: true } : build(a.v, inputs)) : a.k === 'rec' ? (a.f.length ? { rec: a.cls, f: Object.fromEntries(a.f.map(([f, x]) => [f, build(x, inputs)])) } : { inert: true }) : a.k === 'inert' ? { inert: true, ...(a.dict ? { dict: true } : {}) } : a.k === 'store' ? { store: a.name }
5502
6649
  : a.k === 'list' ? { list: (inputs[a.name] ?? []).map(it => build(a.item, it)) } : { dflt: true });
5503
6650
  const ctorArgs = (params) => read.ctor.map(([n, a]) => [n, build(a, params)]);
5504
6651
  let now = 0, inputsNow = {};
@@ -5510,9 +6657,11 @@ function checkStepOnce(h, read, r, sorts, opts) {
5510
6657
  if (n < lo || n > hi)
5511
6658
  throw new Outside(`${a.key} answers ${String(v)}, outside its type`);
5512
6659
  }
6660
+ if (a.inputs.time && !(a.inputs.none && inputsNow[a.inputs.none] === true) && (n < -62_135_596_800_000 || n > 253_402_300_799_999))
6661
+ throw new Outside(`${a.key} answers a datetime outside Python's range`);
5513
6662
  // (a call that may raise: the class of the handler the request says, by its index; a call left out runs as it is)
5514
6663
  const rs = a.raises?.find(x => x.m === call), r = rs && inputsNow[rs.name], raise = r === true ? 0 : typeof r === 'string' && r !== 'none' ? rs.cls.findIndex((_, i) => (g0r(read.model, rs.name, i + 1)) === r) : -1;
5515
- return [a.key, { ...(a.pass ? { pass: true } : a.inputs.none && inputsNow[a.inputs.none] === true ? { none: true } : { in: v, ...(a.inputs.float ? { float: true } : {}) }), ...(raise >= 0 ? { raise: rs.cls[raise] } : {}) }];
6664
+ return [a.key, { ...(a.pass ? { pass: true } : a.inputs.none && inputsNow[a.inputs.none] === true ? { none: true } : { in: v, ...(a.inputs.float ? { float: true } : {}), ...(a.inputs.time ? { time: a.inputs.time } : {}) }), ...(raise >= 0 ? { raise: rs.cls[raise] } : {}) }];
5516
6665
  }));
5517
6666
  let coverage;
5518
6667
  const r0 = performance.now();
@@ -5593,14 +6742,29 @@ function checkStepOnce(h, read, r, sorts, opts) {
5593
6742
  for (const f of jl ?? [])
5594
6743
  if (f.opt && cells[key][`${f.name}_has`] === false)
5595
6744
  cells[key][f.name] = f.choice ? f.vals[0] : 0;
6745
+ for (const f of read.leaves.find(l => l.name === d.name)?.orm?.fields ?? [])
6746
+ if (f.t.k === 'opt' && cells[key][`${f.name}_has`] === false)
6747
+ cells[key][f.name] = f.t.of.k === 'str' ? '' : f.t.of.k === 'bool' ? false : 0;
5596
6748
  }
5597
6749
  maps[d.name] = cells;
5598
6750
  }
5599
6751
  return { leaves, maps };
5600
6752
  },
5601
- normalize: s => { for (const l of read.leaves)
5602
- if (l.kind === 'none' && s.leaves[l.name] === true)
5603
- s.leaves[l.name.replace(/_none$/, '')] = g0(m, l.name.replace(/_none$/, '')); return s; },
6753
+ normalize: s => {
6754
+ for (const l of read.leaves) {
6755
+ if (l.kind === 'none' && s.leaves[l.name] === true)
6756
+ s.leaves[l.name.replace(/_none$/, '')] = g0(m, l.name.replace(/_none$/, ''));
6757
+ for (const f of l.orm?.fields ?? [])
6758
+ if (f.t.k === 'opt')
6759
+ for (const c of Object.values(s.maps[l.name] ?? {}))
6760
+ if (c[`${f.name}_has`] === false)
6761
+ c[f.name] = f.t.of.k === 'str' ? '' : f.t.of.k === 'bool' ? false : 0;
6762
+ }
6763
+ return s;
6764
+ },
6765
+ // (where the code goes on past what the rule's claim covers (a rounding past a float's exact range): an edge)
6766
+ // (and where two items of a list a loop takes by an order tie under it)
6767
+ ...(read.edges?.length || m.folds?.some(d => d.loop?.drains) ? { edge: (s, raw) => (read.edges ?? []).some(c => evalTerm(c, { ...s.leaves, ...raw }, (map, key, field) => (field === 'has' ? !!s.maps[map]?.[String(key)] : s.maps[map]?.[String(key)]?.[field] ?? 0)) === true) || tiesIn(m, s, raw) } : {}),
5604
6768
  };
5605
6769
  function closeAndCount() {
5606
6770
  const res = ask({ op: 'coverage' });
@@ -5646,13 +6810,19 @@ const g0 = (m, name) => { const v = m.state.find(x => x.name === name); return v
5646
6810
  // A front end's whole run: the module read, the model printed and built, the code run beside it.
5647
6811
  export function extractStep(mod, h, opts) {
5648
6812
  const notes = [];
6813
+ if (Object.values({ ...opts.types, ...opts.answers }).some(t => /datetime/.test(t)))
6814
+ notes.push('Stated datetime values are millisecond-aligned Python datetimes: datetime/datetime-naive is naive, datetime-utc is UTC-aware. None remains distinct; other precision and timezone semantics are outside this stated boundary.');
6815
+ // (a reader that said why it read nothing, the source not parsing say, or gave no module: refused with why)
6816
+ const said = mod?.error;
6817
+ if (said !== undefined || !mod || typeof mod.funcs !== 'object' || !mod.funcs || typeof mod.recs !== 'object' || !mod.recs)
6818
+ return { ok: false, refusals: [{ where: mod?.path ?? mod?.file ?? 'the reader', what: said !== undefined ? `the reader read nothing: ${typeof said === 'string' ? said : JSON.stringify(said)}` : 'the reader gave no module of the source' }], notes };
5649
6819
  // (an argument the code declares no type of, given one: `types`, by its name)
5650
6820
  for (const f of Object.values(mod.funcs))
5651
6821
  for (const pa of f.params) {
5652
6822
  const t = opts.types?.[pa.name];
5653
6823
  if (t && pa.t.k === 'any') {
5654
6824
  try {
5655
- pa.t = sortOfText(t, f.p).t;
6825
+ pa.t = sortOfText(t, f.p, mod.lang).t;
5656
6826
  notes.push(`${f.name}(${pa.name}): a ${t} (stated)`);
5657
6827
  }
5658
6828
  catch (e) {
@@ -5674,7 +6844,7 @@ export function extractStep(mod, h, opts) {
5674
6844
  if (!r.own || r.fields.some(x => x.name === f) || !sets)
5675
6845
  continue;
5676
6846
  try {
5677
- r.fields.push({ name: f, t: sortOfText(t, r.p).t });
6847
+ r.fields.push({ name: f, t: sortOfText(t, r.p, mod.lang).t });
5678
6848
  }
5679
6849
  catch (e) {
5680
6850
  if (e instanceof Refusal)
@@ -5687,6 +6857,8 @@ export function extractStep(mod, h, opts) {
5687
6857
  read = readStep(mod, opts);
5688
6858
  }
5689
6859
  catch (e) {
6860
+ if (e instanceof InitializerChoice)
6861
+ return { ok: false, refusals: [{ where: e.where, what: e.what }], notes, initializers: e.initializers };
5690
6862
  if (e instanceof Refusal)
5691
6863
  return { ok: false, refusals: [{ where: e.where, what: e.what }], notes };
5692
6864
  throw e;
@@ -5702,7 +6874,7 @@ export function stepNames(read) {
5702
6874
  for (const l of read.leaves) {
5703
6875
  const code = l.path.join('.');
5704
6876
  if (l.kind === 'map')
5705
- out.push({ code: l.store ?? code, rule: l.name, role: 'state', map: { fields: m.maps.find(d => d.name === l.name)?.fields.map(f => f.name) ?? [], ...(l.store ? { store: l.store, tpl: l.tpl ?? '{}' } : {}), ...(l.ordered ? { ordered: true } : {}) } });
6877
+ out.push({ code: l.orm ? l.name : l.store ?? code, rule: l.name, role: 'state', map: { fields: m.maps.find(d => d.name === l.name)?.fields.map(f => f.name) ?? [], ...(l.orm ? { store: l.orm.rec, tpl: '{}' } : l.store ? { store: l.store, tpl: l.tpl ?? '{}' } : {}), ...(l.ordered ? { ordered: true } : {}) } });
5706
6878
  else if (l.kind === 'none') {
5707
6879
  const n = at(code);
5708
6880
  if (n)