gdp-wired 0.44.0 → 0.46.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. package/README.md +58 -7
  2. package/dist/core/bitsets.d.ts +2 -0
  3. package/dist/core/bitsets.js +23 -0
  4. package/dist/core/bmc.js +6 -2
  5. package/dist/core/c/reader.d.ts +9 -1
  6. package/dist/core/c/reader.js +445 -38
  7. package/dist/core/calendar.d.ts +29 -0
  8. package/dist/core/calendar.js +82 -0
  9. package/dist/core/check.js +3 -2
  10. package/dist/core/cli.d.ts +4 -0
  11. package/dist/core/cli.js +335 -39
  12. package/dist/core/compose.js +3 -1
  13. package/dist/core/counts.d.ts +5 -2
  14. package/dist/core/counts.js +335 -88
  15. package/dist/core/cycles.js +8 -1
  16. package/dist/core/cyclic.d.ts +1 -0
  17. package/dist/core/cyclic.js +13 -7
  18. package/dist/core/data-synth.d.ts +3 -0
  19. package/dist/core/data-synth.js +252 -0
  20. package/dist/core/data.d.ts +8 -2
  21. package/dist/core/data.js +1113 -172
  22. package/dist/core/discover.js +3 -1
  23. package/dist/core/draft.d.ts +19 -0
  24. package/dist/core/draft.js +53 -0
  25. package/dist/core/dsl.d.ts +39 -3
  26. package/dist/core/dsl.js +250 -31
  27. package/dist/core/effect-prims.js +2 -2
  28. package/dist/core/effect.d.ts +1 -4
  29. package/dist/core/effect.js +1 -15
  30. package/dist/core/ex/reader.exs +17 -1
  31. package/dist/core/exists.d.ts +16 -1
  32. package/dist/core/exists.js +447 -50
  33. package/dist/core/extract-c.d.ts +2 -0
  34. package/dist/core/extract-c.js +185 -31
  35. package/dist/core/extract-check.d.ts +7 -0
  36. package/dist/core/extract-check.js +115 -3
  37. package/dist/core/extract-ex.js +3 -3
  38. package/dist/core/extract-go-check.d.ts +1 -1
  39. package/dist/core/extract-go-check.js +21 -13
  40. package/dist/core/extract-go.d.ts +1 -0
  41. package/dist/core/extract-go.js +58 -9
  42. package/dist/core/extract-ir.d.ts +1 -0
  43. package/dist/core/extract-ir.js +15 -0
  44. package/dist/core/extract-jvm.d.ts +1 -1
  45. package/dist/core/extract-jvm.js +65 -14
  46. package/dist/core/extract-orm.d.ts +12 -0
  47. package/dist/core/extract-orm.js +244 -0
  48. package/dist/core/extract-print.js +23 -1
  49. package/dist/core/extract-py.d.ts +1 -0
  50. package/dist/core/extract-py.js +4 -4
  51. package/dist/core/extract-rb.js +3 -3
  52. package/dist/core/extract-read.d.ts +25 -0
  53. package/dist/core/extract-read.js +60 -5
  54. package/dist/core/extract-rs.js +22 -20
  55. package/dist/core/extract-shapes.js +22 -0
  56. package/dist/core/extract-sol.d.ts +10 -1
  57. package/dist/core/extract-sol.js +89 -30
  58. package/dist/core/extract-step.d.ts +201 -4
  59. package/dist/core/extract-step.js +1514 -111
  60. package/dist/core/extract-swift.js +24 -13
  61. package/dist/core/extract.d.ts +9 -0
  62. package/dist/core/extract.js +88 -7
  63. package/dist/core/fiber-run.d.ts +5 -0
  64. package/dist/core/fiber-run.js +18 -0
  65. package/dist/core/fresh.d.ts +2 -2
  66. package/dist/core/fresh.js +7 -3
  67. package/dist/core/go/reader.go +7 -1
  68. package/dist/core/infer.d.ts +4 -1
  69. package/dist/core/infer.js +1020 -246
  70. package/dist/core/jvm/JavaReader.java +33 -8
  71. package/dist/core/jvm/Jvm.java +20 -1
  72. package/dist/core/jvm/KtReader.java +59 -6
  73. package/dist/core/laws.d.ts +10 -3
  74. package/dist/core/laws.js +193 -14
  75. package/dist/core/machine.d.ts +16 -3
  76. package/dist/core/machine.js +212 -28
  77. package/dist/core/nonterm.js +14 -1
  78. package/dist/core/orm/harness.js +61 -0
  79. package/dist/core/orm-fixtures/schema.prisma +5 -0
  80. package/dist/core/py/harness.py +260 -21
  81. package/dist/core/py/reader.py +278 -39
  82. package/dist/core/rb/reader.rb +52 -5
  83. package/dist/core/reader-fixtures/README.md +28 -0
  84. package/dist/core/reader-fixtures/c-693042.cpp +8 -0
  85. package/dist/core/reader-fixtures/go-685506.go +14 -0
  86. package/dist/core/reader-fixtures/jvm-724362.kt +8 -0
  87. package/dist/core/reader-fixtures/jvm-737430.kt +7 -0
  88. package/dist/core/reader-fixtures/jvm-765282.kt +3 -0
  89. package/dist/core/reader-fixtures/swift-735726.swift +15 -0
  90. package/dist/core/reader-fixtures/swift-735990.swift +15 -0
  91. package/dist/core/reader-fixtures/swift-739158.swift +4 -0
  92. package/dist/core/reader-fixtures/swift-744834.swift +15 -0
  93. package/dist/core/reader-fixtures/swift-746946.swift +31 -0
  94. package/dist/core/reader-fixtures/typescript-673062.ts.txt +2 -0
  95. package/dist/core/relation.d.ts +1 -1
  96. package/dist/core/relation.js +29 -2
  97. package/dist/core/relational.js +4 -2
  98. package/dist/core/rs/src/main.rs +18 -2
  99. package/dist/core/sample-cache.d.ts +8 -0
  100. package/dist/core/sample-cache.js +46 -0
  101. package/dist/core/security.d.ts +38 -0
  102. package/dist/core/security.js +88 -0
  103. package/dist/core/sol/harness.py +63 -7
  104. package/dist/core/sol-concrete.d.ts +23 -0
  105. package/dist/core/sol-concrete.js +195 -0
  106. package/dist/core/solver.js +8 -5
  107. package/dist/core/swift/Sources/gdp-swiftreader/main.swift +50 -7
  108. package/dist/core/system.d.ts +62 -1
  109. package/dist/core/system.js +263 -4
  110. package/dist/core/transfer.js +39 -9
  111. package/dist/core/translate.js +39 -10
  112. package/dist/core/watch.js +51 -6
  113. package/dist/interchange/check.js +10 -10
  114. package/dist/interchange/format.d.ts +4 -0
  115. package/dist/interchange/format.js +24 -6
  116. package/dist/kernel/cdcl.d.ts +5 -0
  117. package/dist/kernel/cdcl.js +88 -10
  118. package/dist/kernel/epr.js +141 -29
  119. package/dist/kernel/kernel.d.ts +31 -1
  120. package/dist/kernel/kernel.js +391 -101
  121. package/dist/kernel/model-sequence.d.ts +3 -0
  122. package/dist/kernel/model-sequence.js +34 -0
  123. package/dist/kernel/prove.d.ts +30 -1
  124. package/dist/kernel/prove.js +481 -71
  125. package/dist/kernel/reader.d.ts +3 -0
  126. package/dist/kernel/reader.js +101 -14
  127. package/dist/kernel/share.d.ts +1 -0
  128. package/dist/kernel/share.js +27 -0
  129. package/dist/lean-kernel/emit.d.ts +9 -3
  130. package/dist/lean-kernel/emit.js +200 -66
  131. package/dist/lean-kernel/lean-terms.js +5 -0
  132. package/dist/lean-kernel/library.js +10 -10
  133. package/package.json +7 -2
@@ -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 { Outside, constantsOf, draw, drive } 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)
@@ -62,12 +79,13 @@ function sortOfText(s, at) {
62
79
  const t = one();
63
80
  return { t: none ? { k: 'opt', of: t } : t };
64
81
  }
65
- const TAG_DECO = /(?:^|\.)gdp[._]?(skip|answer|strict)$/i;
82
+ const TAG_DECO = /(?:^|\.)gdp[._]?(skip|answer|strict|effect)$/i;
66
83
  // A type an answer takes: a scalar, or one with None.
67
84
  const answerable = (t) => { const i = t.k === 'opt' ? t.of : t; return i.k === 'int' || i.k === 'float' || i.k === 'bool' || i.k === 'str' || i.k === 'choice'; };
68
85
  const typeText = (t) => (t.k === 'opt' ? `${typeText(t.of)} | None` : t.k === 'choice' ? t.values.map(v => JSON.stringify(v)).join(' | ') : t.k);
69
- // A store's method by its name: one that reads, writes or deletes a key (async_, _cache and camel case aside).
70
86
  const KEYED = Object.fromEntries([
87
+ ...['add', 'setnx', 'putifempty', 'putifabsent', 'addifabsent'].map(n => [n, 'add']),
88
+ ...['incr', 'incrby', 'increment', 'incrementby'].map(n => [n, 'incr']),
71
89
  ...['get', 'getcache', 'find', 'findbyid', 'fetch', 'load', 'lookup', 'read'].map(n => [n, 'get']),
72
90
  ...['set', 'setcache', 'put', 'save', 'store', 'write', 'upsert'].map(n => [n, 'set']),
73
91
  ...['delete', 'deletecache', 'remove', 'deletebyid', 'del', 'evict', 'invalidate'].map(n => [n, 'delete'])
@@ -97,6 +115,11 @@ export class Stepper {
97
115
  // (inside a fold's pass: the tries outside it, hidden, and how deep)
98
116
  hidden = 0;
99
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;
100
123
  initHeap = new Map();
101
124
  storeMaps = new Map();
102
125
  // The least keys the step reads (an ordered collection's first or last item, its min or max by a key), each once.
@@ -164,11 +187,15 @@ export class Stepper {
164
187
  }
165
188
  // An input of a type: its variables, the value, and how the harness makes it.
166
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
+ }
167
194
  const s = this.scalar(t);
168
195
  if (s) {
169
196
  const v = this.newVar(name, s, role);
170
197
  this.typed(v, t, role);
171
- 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 } : {}) }];
172
199
  }
173
200
  if (t.k === 'opt') {
174
201
  if (t.of.k === 'rec') {
@@ -180,8 +207,8 @@ export class Stepper {
180
207
  if (!inner)
181
208
  return refuse(at, `${name}: an optional ${this.why(t.of)}`);
182
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`);
183
- this.typed(v, t.of, role);
184
- 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 } : {}) } }];
185
212
  }
186
213
  if (t.k === 'none')
187
214
  return [{ t: 'none' }, { k: 'dflt' }];
@@ -216,6 +243,13 @@ export class Stepper {
216
243
  // (the request's arguments kept though no term reads them: opts.keep)
217
244
  kept = new Set();
218
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
+ }
219
253
  if ('k' in t && t.k === 'str' && t.bytes)
220
254
  this.bytesVars.add(v.name);
221
255
  const ty = 'k' in t ? this.intTy(t) : t;
@@ -537,6 +571,512 @@ export class Stepper {
537
571
  q = this.assume(q, I.not(end('__returned').e));
538
572
  return { live: q, rets: [[{ ...ret, pc: [...q0.pc, end('__returned').e] }, end('__ret')]] };
539
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
+ }
540
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:
541
1081
  // false at the first that isn't; sum: each added), the fold above.
542
1082
  foldExpr(x, p) {
@@ -624,7 +1164,8 @@ export class Stepper {
624
1164
  const i = this.initHeap.get(id);
625
1165
  if (!i || ('origin' in o && o.origin !== 'state'))
626
1166
  continue;
627
- if (o.k === 'map' ? !!o.w || (!!o.nil && I.keyOf(o.nil) !== I.keyOf(i.nil)) : o.k === 'list' ? o.ops.length > 0 : keyV(o) !== keyV(i))
1167
+ // (a write a condition makes, nx's, on a path where that condition is false: none)
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))
628
1169
  return true;
629
1170
  }
630
1171
  return false;
@@ -641,7 +1182,10 @@ export class Stepper {
641
1182
  let k = 0;
642
1183
  while (k < a.pc.length && k < b.pc.length && I.same(a.pc[k], b.pc[k]))
643
1184
  k++;
644
- 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)])];
645
1189
  if (c.op === 'const')
646
1190
  return c.v ? { ...a, pc } : { ...b, pc };
647
1191
  if (a.locks.join() !== b.locks.join())
@@ -671,7 +1215,9 @@ export class Stepper {
671
1215
  const x = this.initHeap.get(id);
672
1216
  heap.set(id, x ? this.mergeObj(c, x, y, at) : y);
673
1217
  }
674
- return { pc, locals, heap, called: [...new Set([...a.called, ...b.called])], locks: a.locks, defers: [...new Set([...a.defers, ...b.defers])] };
1218
+ const effs = new Set([...(a.eff?.keys() ?? []), ...(b.eff?.keys() ?? [])]);
1219
+ const eff = effs.size ? new Map([...effs].map(e => [e, I.bite(c, a.eff?.get(e) ?? I.F, b.eff?.get(e) ?? I.F)])) : undefined;
1220
+ return { pc, locals, heap, called: [...new Set([...a.called, ...b.called])], locks: a.locks, defers: [...new Set([...a.defers, ...b.defers])], ...(eff ? { eff } : {}) };
675
1221
  }
676
1222
  mergeObj(c, a, b, at) {
677
1223
  if (a === b)
@@ -691,6 +1237,17 @@ export class Stepper {
691
1237
  }
692
1238
  if (a.k === 'map' && b.k === 'map') {
693
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
+ }
694
1251
  // (several keys written: both paths' writes padded to one length, each place by the condition)
695
1252
  const [la, lb] = padWrites([[...(a.pre ?? []), ...(a.w ? [a.w] : [])], [...(b.pre ?? []), ...(b.w ? [b.w] : [])]], base);
696
1253
  if (la.length > 1) {
@@ -943,6 +1500,14 @@ export class Stepper {
943
1500
  return refuse(at, `${f.name}: *args or **kwargs given`);
944
1501
  return refuse(at, `${f.name}: more arguments than it takes`);
945
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
+ }
946
1511
  const saved = q.locals;
947
1512
  this.frames.push(f.id);
948
1513
  this.frameLocals.push(saved);
@@ -1180,6 +1745,7 @@ export class Stepper {
1180
1745
  case 'break': return { rets: [], brk: [p] };
1181
1746
  case 'continue': return { rets: [], brk: [{ ...p, cont: true }] };
1182
1747
  case 'for': return this.forStmt(s, p);
1748
+ case 'while': return this.whileStmt(s, p);
1183
1749
  case 'defer': {
1184
1750
  const key = this.lockKey(s.pl, p);
1185
1751
  if (!p.locks.includes(key))
@@ -1260,6 +1826,8 @@ export class Stepper {
1260
1826
  return refuse(at, `${at.text}: writes an object already put in a map (one object in two places)`);
1261
1827
  if (obj.origin === 'state' && !this.init && !obj.f.has(f))
1262
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);
1263
1831
  const old = obj.f.get(f);
1264
1832
  if (old?.t === 'opaque' && obj.origin === 'state' && !this.init)
1265
1833
  return refuse(at, `${at.text}: writes ${old.why}`);
@@ -1311,7 +1879,24 @@ export class Stepper {
1311
1879
  return [m.id, o];
1312
1880
  }
1313
1881
  cellOf(o, key, _p, _at) {
1882
+ keyKind(o.decl, key, _at);
1314
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
+ }
1315
1900
  for (const w of [...(o.pre ?? []), ...(o.w ? [o.w] : [])]) {
1316
1901
  const same = I.keq(key, w.key), a = acc;
1317
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)])) };
@@ -1321,6 +1906,7 @@ export class Stepper {
1321
1906
  // A cell written: a second key of a scalar map keyed by numbers (a transfer's two accounts) after the first, any
1322
1907
  // earlier write of the same key dropped (this one is read through it).
1323
1908
  writeCell(id, o, key, has, vals, at, p) {
1909
+ keyKind(o.decl, key, at);
1324
1910
  if (o.w && !I.same(o.w.key, key)) {
1325
1911
  if (!o.decl.scalar || o.decl.key !== 'num')
1326
1912
  return refuse(at, `${at.text}: a second key of one map written in one step (the subset writes one a step, or several of a map of numbers or booleans keyed by numbers)`);
@@ -1366,13 +1952,13 @@ export class Stepper {
1366
1952
  const [id, o] = this.mapObj(m, at, p), c = this.cellOf(o, k, p, at);
1367
1953
  if (strict)
1368
1954
  this.fail(p, I.not(c.has), at, `${at.text}: a key the dict doesn't hold deleted (a KeyError)`);
1369
- return this.writeCell(id, o, k, I.F, new Map([...c.vals].map(([f, v]) => [f, (v.t === 'num' ? { t: 'num', e: I.num(0) } : v.t === 'bool' ? { t: 'bool', e: I.F } : v.t === 'choice' ? { t: 'choice', e: I.llit(lvalues(v.e)[0], lvalues(v.e)) } : v)])), at, strict ? this.assume(p, c.has) : p);
1955
+ return this.writeCell(id, o, k, I.F, new Map([...c.vals].map(([f, v]) => [f, (v.t === 'num' ? { t: 'num', e: I.num(0) } : v.t === 'bool' ? { t: 'bool', e: I.F } : v.t === 'choice' ? { t: 'choice', e: I.llit(lvalues(v.e)[0], lvalues(v.e)) } : o.decl.fields.find(x => x.name === f)?.sort.k === 'str' ? { t: 'str', e: { op: 'slit', value: '' } } : v)])), at, strict ? this.assume(p, c.has) : p);
1370
1956
  }
1371
1957
  mapDeclOf(name, t, at) {
1372
1958
  if (t.k !== 'map')
1373
1959
  return refuse(at, `${name}: ${this.why(t)}`);
1374
1960
  const key = t.key.k === 'int' ? 'num' : t.key.k === 'str' ? 'str' : refuse(at, `${name}: a dict keyed by ${this.why(t.key)} (keys are integers or strings)`);
1375
- const cell = (n, ft) => { const s = this.scalar(ft); if (!s || s.k === 'str')
1961
+ const cell = (n, ft) => { const s = this.scalar(ft); if (!s || (s.k === 'str' && !t.sv))
1376
1962
  return refuse(at, `${name}: a dict of ${s?.k === 'str' ? 'strings' : this.why(ft)} (a cell holds integers, booleans and literals)`); return { name: n, sort: s, role: 'state' }; };
1377
1963
  let fields, scalar = true;
1378
1964
  // (a record's string field the module only ever sets to literals: a choice of them, said in the notes)
@@ -1436,7 +2022,10 @@ export class Stepper {
1436
2022
  // before the step, so one read after the step wrote the map is refused. Each least read once, however often.
1437
2023
  // (`held`: whether there is one, with `where` at its key, which it implies: what a path that takes it knows)
1438
2024
  least(o, at, where, by) {
1439
- 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)
1440
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)`);
1441
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 });
1442
2031
  let l = this.leasts.find(x => I.keyOf({ map: x.map, w: x.where, b: x.by }) === sig);
@@ -1485,6 +2074,21 @@ export class Stepper {
1485
2074
  o = q.heap.get(id);
1486
2075
  if (kw.length)
1487
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
+ }
1488
2092
  if (name === 'append' && args.length === 1) {
1489
2093
  const last = this.least(o, x, k => this.baseCell(o.decl, k).has, k => [{ e: k.e, desc: true }]);
1490
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)];
@@ -1589,6 +2193,196 @@ export class Stepper {
1589
2193
  this.fail(p, I.not(l.some), x, `${x.text}: ${n}() of an empty collection (a ValueError)`);
1590
2194
  return [v, this.assume(p, l.held)];
1591
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
+ }
1592
2386
  // --- stores ---------------------------------------------------------------------------------------------------------
1593
2387
  storeMap(store, tpl, kn, at, p) {
1594
2388
  const key = `${store}\u0000${tpl}`;
@@ -1602,7 +2396,7 @@ export class Stepper {
1602
2396
  if (!disjoint(other.tpl, tpl))
1603
2397
  refuse(at, `${store}: the key templates ${JSON.stringify(other.tpl)} and ${JSON.stringify(tpl)} may name one key`);
1604
2398
  const sv = decl.values?.[tpl];
1605
- const val = Array.isArray(sv) ? { k: 'choice', values: sv } : sv === 'int' || (!sv && decl.value === 'int') ? { k: 'int' } : !sv && decl.value === 'str' ? { k: 'str' } : { k: 'float' };
2399
+ const val = Array.isArray(sv) ? { k: 'choice', values: sv } : sv === 'int' || (!sv && decl.value === 'int') ? { k: 'int' } : sv === 'str' || (!sv && decl.value === 'str') ? { k: 'str' } : { k: 'float' };
1606
2400
  const name = `${store}_${tpl.replace(/\{\}/g, '').replace(/[^A-Za-z0-9]+/g, '_').replace(/^_|_$/g, '')}`;
1607
2401
  let d, json;
1608
2402
  if (sv && typeof sv === 'object' && !Array.isArray(sv)) {
@@ -1614,7 +2408,7 @@ export class Stepper {
1614
2408
  json.push({ name: f, out: true });
1615
2409
  continue;
1616
2410
  }
1617
- 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;
1618
2412
  fields.push({ name: f, sort: this.scalar(inner), role: 'state' });
1619
2413
  if (opt)
1620
2414
  fields.push({ name: `${f}_has`, sort: { k: 'bool' }, role: 'state' });
@@ -1626,7 +2420,7 @@ export class Stepper {
1626
2420
  this.notes.add(`${store}: ${JSON.stringify(tpl)} keys hold JSON records (stated): ${json.map(f => `${f.name}${f.out ? ' (a string, left out)' : f.opt ? ' (maybe absent)' : ''}`).join(', ')}`);
1627
2421
  }
1628
2422
  else
1629
- d = this.mapDeclOf(name, { k: 'map', key: { k: kn ? 'int' : 'str' }, val }, at);
2423
+ d = this.mapDeclOf(name, { k: 'map', key: { k: kn ? 'int' : 'str' }, val, ...(val.k === 'str' ? { sv: true } : {}) }, at);
1630
2424
  const id = `store:${key}`;
1631
2425
  sm = { store, tpl, id, decl: d, ...(json ? { json } : {}), ...(Array.isArray(sv) ? { choice: true } : {}) };
1632
2426
  this.storeMaps.set(key, sm);
@@ -1652,6 +2446,8 @@ export class Stepper {
1652
2446
  // (the stores whose keys the rule holds: stated, or an injected dependency the class calls a key's method on)
1653
2447
  storeKeyed = new Set();
1654
2448
  injectedFields = [];
2449
+ globalStores = [];
2450
+ inertAttrs = [];
1655
2451
  // (the injected dependencies and stores: their type, whether the rule holds keys of theirs, whether the caller stated them)
1656
2452
  deps = [];
1657
2453
  // A constructor argument held as an injected dependency (a store): one its reader marks so, or one of no scalar type
@@ -1707,11 +2503,11 @@ export class Stepper {
1707
2503
  refuse(at, `${at.text}: ${store}.${m} is given the rule's state, which other code may change (if it doesn't, a \`gdp: skip\` comment on its line says so)`); };
1708
2504
  const arg = (n, i) => kw.find(([k]) => k === n || (n === 'key' && k === 'name'))?.[1] ?? args[i] ?? refuse(at, `${at.text}: the store's ${n} not given`);
1709
2505
  const has = (n, i) => kw.some(([k]) => k === n) || args.length > i;
1710
- let kind = (d.get ?? ['get', 'async_get_cache', 'get_cache']).includes(m) ? 'get' : (d.set ?? ['set', 'async_set_cache', 'set_cache']).includes(m) ? 'set' : (d.delete ?? ['delete', 'delete_cache', 'async_delete_cache']).includes(m) ? 'delete' : undefined;
2506
+ let kind = (d.get ?? ['get', 'async_get_cache', 'get_cache']).includes(m) ? 'get' : (d.set ?? ['set', 'async_set_cache', 'set_cache']).includes(m) ? 'set' : (d.delete ?? ['delete', 'delete_cache', 'async_delete_cache']).includes(m) ? 'delete' : d.add?.includes(m) ? 'add' : d.incr?.includes(m) ? 'incr' : undefined;
1711
2507
  if (!kind && this.inf) {
1712
2508
  // (inferred: a method named as a key's get, set or delete, given a key that is a string or a format)
1713
2509
  const k = keyShape(m), key = kw.find(([n]) => n === 'key' || n === 'name')?.[1] ?? args[0];
1714
- if (k && key && (key.t === 'str' || key.t === 'fmt') && (k !== 'set' || has('value', 1))) {
2510
+ if (k && key && (key.t === 'str' || key.t === 'fmt') && ((k !== 'set' && k !== 'add') || has('value', 1))) {
1715
2511
  kind = k;
1716
2512
  (d[k] ??= []).push(m);
1717
2513
  this.notes.add(`${store}.${m}: read as the store's ${k} by a key (inferred from its name)`);
@@ -1741,15 +2537,15 @@ export class Stepper {
1741
2537
  return refuse(at, `${at.text}: the store's ${m} awaited at one call and not at another`);
1742
2538
  this.storeAsync[store][m] = awaited;
1743
2539
  // (a key's operation takes its key, and a set its value: any other argument given the rule's state is refused)
1744
- const keyV = arg('key', 0), valV = kind === 'set' ? arg('value', 1) : undefined;
2540
+ const sets = kind === 'set' || kind === 'add', keyV = arg('key', 0), valV = sets ? arg('value', 1) : kind === 'incr' && has('amount', 1) ? arg('amount', 1) : undefined;
1745
2541
  // (a set's options: nx and xx make it conditional, its result whether it set (True, else None, as redis-py's); its
1746
2542
  // expiry is left out, as every store's is; any other option is refused)
1747
2543
  const TTL = ['ex', 'px', 'exat', 'pxat', 'ttl', 'timeout', 'expire', 'expiry'];
1748
2544
  let only;
1749
2545
  for (const [n, v] of kw) {
1750
- if (n === 'key' || n === 'name' || n === 'value')
2546
+ if (n === 'key' || n === 'name' || n === 'value' || (kind === 'incr' && n === 'amount'))
1751
2547
  continue;
1752
- if (kind === 'set' && TTL.includes(n)) {
2548
+ if (sets && TTL.includes(n)) {
1753
2549
  this.notes.add(`${store}.${m}: its ${n} (the key's expiry) left out, as the store's expiry is`);
1754
2550
  continue;
1755
2551
  }
@@ -1771,10 +2567,19 @@ export class Stepper {
1771
2567
  }
1772
2568
  return refuse(at, `${at.text}: the store's ${m} given ${n}, a value the request decides (the subset reads a key, a value, nx, xx, the expiry and options given a constant)`);
1773
2569
  }
1774
- given(all.filter(v => v !== keyV && v !== valV));
1775
- if (args.length > (kind === 'set' ? 2 : 1))
1776
- return refuse(at, `${at.text}: the store's ${m} given more than its key${kind === 'set' ? ' and value' : ''}`);
2570
+ // (a set's third argument, set(key, value, ttl) as most caches take it: the key's expiry, left out)
2571
+ const ttl = sets && args.length === 3 ? args[2] : undefined;
2572
+ if (ttl)
2573
+ this.notes.add(`${store}.${m}: its third argument (the key's expiry) left out, as the store's expiry is`);
2574
+ given(all.filter(v => v !== keyV && v !== valV && v !== ttl));
2575
+ if (args.length > (sets ? 3 : kind === 'incr' ? 2 : 1))
2576
+ return refuse(at, `${at.text}: the store's ${m} given more than its key${sets ? ', value and expiry' : kind === 'incr' ? ' and amount' : ''}`);
1777
2577
  const { tpl, k, kn } = this.storeKey(keyV, at);
2578
+ // (what a template's keys hold, where nothing states it: strings where the first write sets one)
2579
+ if (sets && valV?.t === 'str' && !d.value && !d.values?.[tpl] && !this.storeMaps.has(`${store}\u0000${tpl}`)) {
2580
+ (d.values ??= {})[tpl] = 'str';
2581
+ this.notes.add(`${store}: ${JSON.stringify(tpl)} keys hold strings (inferred: a string set)`);
2582
+ }
1778
2583
  const [id, o] = this.storeMap(store, tpl, kn, at, p), sm = [...this.storeMaps.values()].find(x => x.id === id);
1779
2584
  // (inside a try that may catch it: the store's operation may raise, as other code's may, before it acts)
1780
2585
  if (this.tries.length && !d.nothrow)
@@ -1795,6 +2600,15 @@ export class Stepper {
1795
2600
  }
1796
2601
  if (kind === 'delete')
1797
2602
  return [{ t: 'none' }, this.mapDel({ t: 'ref', id }, k, at, p, false)];
2603
+ if (kind === 'incr') {
2604
+ if (sm.json || sm.choice || o.val.k === 'str')
2605
+ return refuse(at, `${at.text}: ${m} on a store that holds no numbers`);
2606
+ const by = valV ? this.numOf(valV, at, p) : I.num(1), c = this.cellOf(o, k, p, at);
2607
+ const now = { t: 'num', e: I.add(this.numOf(this.ite(c.has, c.vals.get('value'), { t: 'num', e: I.num(0) }, at), at, p), by) };
2608
+ return [now, this.writeCell(id, o, k, I.T, new Map([['value', now]]), at, p)];
2609
+ }
2610
+ if (kind === 'add')
2611
+ only = 'nx';
1798
2612
  const v = arg('value', 1);
1799
2613
  let vals;
1800
2614
  if (sm.json) {
@@ -1819,11 +2633,10 @@ export class Stepper {
1819
2633
  }
1820
2634
  }
1821
2635
  else {
1822
- const v2 = sm.choice ? this.fit(v, o.decl.fields[0], at) : v;
1823
- if (sm.choice ? v2.t !== 'choice' : o.val.k === 'str' ? v.t !== 'str' : v.t !== 'num')
2636
+ // (a bool set where numbers are held: 1 or 0, as Python's True is)
2637
+ const v2 = sm.choice ? this.fit(v, o.decl.fields[0], at) : v.t === 'bool' && o.val.k !== 'str' ? { t: 'num', e: I.nite(v.e, I.num(1), I.num(0)) } : v;
2638
+ if (sm.choice ? v2.t !== 'choice' : o.val.k === 'str' ? v.t !== 'str' : v2.t !== 'num')
1824
2639
  return refuse(at, `${at.text}: a ${v.t === 'opaque' ? v.why : v.t} set in a store of ${o.val.k === 'float' ? 'numbers' : o.val.k}`);
1825
- if (!sm.choice && o.val.k === 'str')
1826
- return refuse(at, `${at.text}: a store of strings (its cells hold numbers)`);
1827
2640
  vals = new Map([['value', v2]]);
1828
2641
  }
1829
2642
  if (!only)
@@ -1831,7 +2644,9 @@ export class Stepper {
1831
2644
  // (nx: where the key holds nothing; xx: where it holds a value)
1832
2645
  const c = this.cellOf(o, k, p, at), when = only === 'nx' ? I.not(c.has) : c.has;
1833
2646
  const merged = new Map([...vals].map(([n, x]) => [n, this.ite(when, x, c.vals.get(n), at)]));
1834
- return [{ t: 'opt', has: when, v: { t: 'bool', e: I.T } }, this.writeCell(id, o, k, I.bite(when, I.T, c.has), merged, at, p)];
2647
+ const w = this.writeCell(id, o, k, I.bite(when, I.T, c.has), merged, at, p), wo = w.heap.get(id);
2648
+ w.heap.set(id, { ...wo, w: { ...wo.w, on: when } });
2649
+ return [kind === 'add' ? { t: 'bool', e: when } : { t: 'opt', has: when, v: { t: 'bool', e: I.T } }, w];
1835
2650
  }
1836
2651
  // --- context managers of the module's, made by @contextmanager ---------------------------------------------------------
1837
2652
  // with self.cm(...): body, where cm is a generator the module reads, decorated @contextmanager: the generator run,
@@ -1900,6 +2715,21 @@ export class Stepper {
1900
2715
  return [v, p];
1901
2716
  }
1902
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
+ }
1903
2733
  if (o.ty === '$dt' && m === 'timestamp' && !args.length && !kw.length)
1904
2734
  return [{ t: 'val', ty: '$ts', f: o.f }, p];
1905
2735
  if (o.ty === '$dict' && m === 'get' && !kw.length && args.length >= 1 && args.length <= 2) {
@@ -1949,7 +2779,8 @@ export class Stepper {
1949
2779
  const mk = (t, e) => {
1950
2780
  if (t === '$dt')
1951
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)`);
1952
- 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 }]] : [])]) };
1953
2784
  };
1954
2785
  if (op === '+' && ty(a) === '$dt' && ty(b) === '$td')
1955
2786
  return mk('$dt', I.add(ms(a), ms(b)));
@@ -1957,8 +2788,11 @@ export class Stepper {
1957
2788
  return mk('$dt', I.add(ms(a), ms(b)));
1958
2789
  if (op === '-' && ty(a) === '$dt' && ty(b) === '$td')
1959
2790
  return mk('$dt', I.sub(ms(a), ms(b)));
1960
- 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');
1961
2794
  return mk('$td', I.sub(ms(a), ms(b)));
2795
+ }
1962
2796
  if ((op === '+' || op === '-') && ty(a) === '$td' && ty(b) === '$td')
1963
2797
  return mk('$td', op === '+' ? I.add(ms(a), ms(b)) : I.sub(ms(a), ms(b)));
1964
2798
  if (op === '*' && ty(a) === '$ts' && constOf(b) === 1000)
@@ -2002,15 +2836,14 @@ export class Stepper {
2002
2836
  let a = this.answers.get(key);
2003
2837
  const short = key.split(/\.|::/).pop();
2004
2838
  if (!a) {
2005
- 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);
2006
2840
  const inner = t.k === 'opt' ? t.of : t, s = this.scalar(inner);
2007
2841
  const v = this.newVar(short, s, 'input', how === 'stated' ? `what ${names[0]} returns (stated: answers)` : `what ${names[0]} returns (${how}: any ${text})`);
2008
2842
  const none = t.k === 'opt' ? this.newVar(`${short}_none`, { k: 'bool' }, 'input', `whether ${names[0]} returns None`).name : undefined;
2009
2843
  // (a result of a fixed width: within it, the claim is for the values its type holds)
2010
2844
  const fit = !!this.intTy(inner);
2011
- if (fit)
2012
- this.typed(v, inner, 'input');
2013
- 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 } : {}) };
2014
2847
  this.answers.set(key, a);
2015
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`);
2016
2849
  }
@@ -2021,7 +2854,7 @@ export class Stepper {
2021
2854
  this.typed(this.vars.get(a.inputs.name), at.ity, 'input', I.and(this.sel, this.cond(p)));
2022
2855
  if (!a.at.some(x => x.p === site.p))
2023
2856
  a.at.push(site);
2024
- 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);
2025
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)];
2026
2859
  }
2027
2860
  // A call left out inside a try (its value unread): stubbed only to raise where the request says, else run as it is.
@@ -2072,6 +2905,10 @@ export class Stepper {
2072
2905
  if (t)
2073
2906
  return this.answer(b.key, [b.name], b.patch, x, q, awaited, t, tag ? 'tagged' : 'inferred');
2074
2907
  const why = `${x.text ?? b.name}: the value of ${b.name}, other code left out`;
2908
+ // (a call on an attribute of a store the rule doesn't state, a registry its constructor adds to: inert in the check)
2909
+ const ra = b.recv?.t === 'opaque' ? b.recv.sattr : b.recv?.t === 'sattr' ? { store: b.recv.store, path: b.recv.path } : undefined;
2910
+ if (ra && !this.inertAttrs.some(i => i.store === ra.store && i.path === ra.path))
2911
+ this.inertAttrs.push(ra);
2075
2912
  this.pend.set(why, { ...b, why, at: x.p, ...(x.end ? { end: x.end } : {}) });
2076
2913
  this.leftOut.add(b.name).add(b.key);
2077
2914
  this.notes.add(`${b.name} (${x.p}): left out (${tag ? 'tagged: gdp: skip' : 'inferred: nothing the rule keeps reads its value'}), run as it is by the check`);
@@ -2194,7 +3031,7 @@ export class Stepper {
2194
3031
  if (!lines) {
2195
3032
  lines = new Map();
2196
3033
  const src = sourceOf(this.mod, m[1]) ?? '';
2197
- src.split('\n').forEach((l, i) => { const t = /(?:#|\/\/|--|%)\s*gdp:\s*(skip|answer|strict)\b[ \t]*([^#\n]*)$/.exec(l); if (t)
3034
+ src.split('\n').forEach((l, i) => { const t = /(?:#|\/\/|--|%)\s*gdp:\s*(skip|answer|strict|effect)\b[ \t]*([^#\n]*)$/.exec(l); if (t)
2198
3035
  lines.set(i + 1, { k: t[1], arg: t[2].trim() }); });
2199
3036
  this.tagLines.set(m[1], lines);
2200
3037
  }
@@ -2275,7 +3112,7 @@ export class Stepper {
2275
3112
  return [{ t: 'num', e: I.num(Number(x.v)), ...(ty ? { ty } : {}) }, p];
2276
3113
  }
2277
3114
  case 'unit': return [{ t: 'none' }, p];
2278
- 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];
2279
3116
  case 'ref':
2280
3117
  case 'lock': return this.ev(x.x, p);
2281
3118
  case 'copy': {
@@ -2304,7 +3141,7 @@ export class Stepper {
2304
3141
  case 'expect': {
2305
3142
  const [v, q] = this.ev(x.x, p);
2306
3143
  const good = this.isOf(v, 'good', x);
2307
- this.fail(q, I.not(good), x, `${x.text}: unwrap of ${v.t === 'res' ? 'an Err' : 'None'} (a panic)`);
3144
+ this.fail(q, I.not(good), x, x.npe ? `${x.text}: null unboxed (a NullPointerException)` : `${x.text}: unwrap of ${v.t === 'res' ? 'an Err' : 'None'} (a panic)`);
2308
3145
  return [this.inner(v, 'good', x), this.assume(q, good)];
2309
3146
  }
2310
3147
  case 'opt_or': {
@@ -2359,6 +3196,12 @@ export class Stepper {
2359
3196
  case 'upd': {
2360
3197
  const [o, q] = this.ev(x.x, p);
2361
3198
  let [c, q2] = this.copy(o, q, x);
3199
+ // (Elixir's %{m | k: v}, strict: a key the map doesn't hold is a KeyError)
3200
+ const r = c.t === 'ref' && x.strict ? this.mod.recs[q2.heap.get(c.id)?.ty ?? ''] : undefined, gone = x.fields.find(([f]) => r && !r.fields.some(y => y.name === f));
3201
+ if (gone) {
3202
+ this.fail(q2, I.T, x, `${x.text}: ${gone[0]}, a key the map doesn't hold (a KeyError)`);
3203
+ return [{ t: 'opaque', why: 'unreachable' }, { ...q2, pc: [...q2.pc, I.F] }];
3204
+ }
2362
3205
  for (const [f, y] of x.fields) {
2363
3206
  const [v, q3] = this.ev(y, q2);
2364
3207
  q2 = this.setField(c, f, v, x, q3);
@@ -2373,6 +3216,9 @@ export class Stepper {
2373
3216
  const v = p.locals.get(String(x.n));
2374
3217
  // (Python's local read on a path that never set it, past a raise caught before its assignment: an
2375
3218
  // UnboundLocalError on that path)
3219
+ // (Ruby's local read before it is set: nil)
3220
+ if (!v && !x.why && this.mod.lang === 'ruby')
3221
+ return [{ t: 'none' }, p];
2376
3222
  if (!v && !x.why && this.mod.lang === 'python') {
2377
3223
  this.fail(p, I.T, x, `${String(x.n)}: a local read before it is set (an UnboundLocalError)`);
2378
3224
  return [{ t: 'opaque', why: 'unreachable' }, { ...p, pc: [...p.pc, I.F] }];
@@ -2385,11 +3231,38 @@ export class Stepper {
2385
3231
  case 'cls': return [{ t: 'cls', rec: String(x.rec), ...(x.patch ? { patch: x.patch } : {}) }, p];
2386
3232
  case 'builtin': return [{ t: 'builtin', n: String(x.n) }, p];
2387
3233
  case 'lib': return [{ t: 'lib', q: String(x.q) }, p];
2388
- case 'ext': return [{ t: 'ext', q: String(x.q), text: String(x.text), ...(x.patch ? { patch: x.patch } : {}), ...(x.ret ? { ret: x.ret } : {}), ...(x.nothrow ? { nothrow: true } : {}) }, p];
3234
+ case 'ext': {
3235
+ // (a module's object a stated store names, Django's `cache`, a client made at import: the store, the check
3236
+ // giving one in its place)
3237
+ const pt = x.patch;
3238
+ if (this.opts.stores?.[String(x.text)] && pt?.mod && pt.path?.length === 1) {
3239
+ const name = String(x.text), id = `store:${name}`;
3240
+ if (!this.initHeap.has(id)) {
3241
+ this.initHeap.set(id, { k: 'store', name });
3242
+ this.storeKeyed.add(name);
3243
+ this.globalStores.push({ name, mod: pt.mod });
3244
+ this.notes.add(`${name}: a store (stated), the module's object, the check giving one in its place`);
3245
+ }
3246
+ if (!p.heap.has(id))
3247
+ p.heap.set(id, this.initHeap.get(id));
3248
+ return [{ t: 'ref', id }, p];
3249
+ }
3250
+ return [{ t: 'ext', q: String(x.q), text: String(x.text), ...(x.patch ? { patch: x.patch } : {}), ...(x.ret ? { ret: x.ret } : {}), ...(x.nothrow ? { nothrow: true } : {}) }, p];
3251
+ }
2389
3252
  case 'no': {
2390
3253
  // (a call of other code a reader doesn't lower, `ext` its name: at the boundary, where it is inferred)
2391
3254
  if (x.ext && !x.pre && !x.prepl) {
2392
3255
  const names = [x.ext], ans = this.match(Object.keys(this.opts.answers ?? {}), names), patch = x.patch;
3256
+ // (a stub stated: nothing run, None returned, its arguments not read)
3257
+ const st = this.match(this.opts.stubs, names);
3258
+ if (st && patch) {
3259
+ const key = st.split('.').pop();
3260
+ if (!this.answers.has(key)) {
3261
+ this.answers.set(key, { key, patch, async: false, inputs: { name: '' }, sort: '', pass: true, effect: true, quiet: true, at: [] });
3262
+ this.notes.add(`${key} (${x.p}): stubbed (stated): it does nothing and returns None in the check`);
3263
+ }
3264
+ return [{ t: 'none' }, p];
3265
+ }
2393
3266
  if (ans)
2394
3267
  return this.answer(ans, names, patch, x, x.args ? this.argsRead(x, p) : p, false);
2395
3268
  if (this.skipped(names)) {
@@ -2454,6 +3327,11 @@ export class Stepper {
2454
3327
  }
2455
3328
  case 'conv': {
2456
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
+ }
2457
3335
  if (ty && v.t === 'num')
2458
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];
2459
3337
  return refuse(x, v.t === 'opaque' && v.ask ? `${String(x.why)}: of ${v.why}` : String(x.why));
@@ -2479,6 +3357,9 @@ export class Stepper {
2479
3357
  }
2480
3358
  if (op === '+')
2481
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];
2482
3363
  return refuse(x, String(x.why));
2483
3364
  }
2484
3365
  case 'addr': {
@@ -2595,8 +3476,11 @@ export class Stepper {
2595
3476
  case 'get': return this.get(x, p);
2596
3477
  case 'idx': {
2597
3478
  const [m, q] = this.ev(x.x, p), [k, q2] = this.ev(x.i, q);
2598
- if (m.t === 'opaque')
3479
+ // (an item of a value outside the subset: whether it holds one, and what, is that value's)
3480
+ if (m.t === 'opaque' && m.why === 'unreachable')
2599
3481
  return [m, q2];
3482
+ if (m.t === 'opaque')
3483
+ return refuse(x, `${x.text}: an item of ${m.why} (whether it holds one is that value's)`);
2600
3484
  if (m.t === 'val')
2601
3485
  return this.valItem(m, k, x, q2);
2602
3486
  const ord = this.orderedObj(m, q2);
@@ -2613,6 +3497,8 @@ export class Stepper {
2613
3497
  }
2614
3498
  case 'neg': {
2615
3499
  const [v, q] = this.ev(x.x, p);
3500
+ if (v.t === 'opaque' && v.ask)
3501
+ return refuse(x, `${x.text ?? '-'}: arithmetic on ${v.why} (what it does depends on that value)`);
2616
3502
  if (v.t === 'opaque')
2617
3503
  return [v, q];
2618
3504
  return [{ t: 'num', e: I.neg(this.numOf(v, x, q)) }, q];
@@ -2671,6 +3557,23 @@ export class Stepper {
2671
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)`);
2672
3558
  case 'call': return this.call(x, p, awaited);
2673
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
+ }
2674
3577
  }
2675
3578
  return refuse(x, `${x.text ?? x.e}: an expression the subset doesn't read`);
2676
3579
  }
@@ -2757,6 +3660,19 @@ export class Stepper {
2757
3660
  }
2758
3661
  return refuse(x, `${x.text}: an atomic's ${op}`);
2759
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
+ }
2760
3676
  get(x, p) {
2761
3677
  const [o, q] = this.ev(x.x, p), f = String(x.f);
2762
3678
  switch (o.t) {
@@ -2781,8 +3697,15 @@ export class Stepper {
2781
3697
  }
2782
3698
  case 'cls': {
2783
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];
2784
3702
  if (mid)
2785
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];
2786
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];
2787
3710
  }
2788
3711
  case 'bool':
@@ -2814,12 +3737,38 @@ export class Stepper {
2814
3737
  if (obj?.k !== 'rec')
2815
3738
  return refuse(x, `${x.text}: a field of other than an object`);
2816
3739
  const r = this.rec(obj.ty, x);
2817
- // (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)
2818
3767
  if (typeof x.sup === 'string')
2819
3768
  return [{ t: 'fn', id: x.sup, self: o }, q];
2820
3769
  const v = obj.f.get(f);
2821
3770
  if (v)
2822
- return [v, q];
3771
+ return [this.timeField(v, r.fields.find(fd => fd.name === f)?.t, true, x), q];
2823
3772
  const mid = r.methods[f];
2824
3773
  if (mid !== undefined) {
2825
3774
  if (mid === null)
@@ -2831,6 +3780,12 @@ export class Stepper {
2831
3780
  }
2832
3781
  if (obj.lazy)
2833
3782
  return this.lazyField(o.id, obj, f, x, q);
3783
+ // (a class attribute set to a constant, which no method sets on the object: that constant)
3784
+ const ca = r.cattrs?.[f];
3785
+ if (ca !== undefined)
3786
+ return [this.classConstant(ca, x), q];
3787
+ if (r.classCollections?.[f])
3788
+ return [this.classCollection(r.classCollections[f], f), q];
2834
3789
  return refuse(x, `${x.text}: no field ${f} (the object's fields are those its constructor sets)`);
2835
3790
  }
2836
3791
  // A field of an object the caller gives, made an input where it is first read.
@@ -2870,6 +3825,9 @@ export class Stepper {
2870
3825
  return [this.valBin(op, a, b, x, q2), q2];
2871
3826
  // A true division: a float, kept only where nothing the rule keeps reads it (refused there); its divisor 0 fails.
2872
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];
2873
3831
  if (b.t === 'num' || b.t === 'bool') {
2874
3832
  const nb = this.numOf(b, x, q2);
2875
3833
  this.fail(q2, I.cmp('=', nb, I.num(0)), x, `${x.text}: a division by zero (a ZeroDivisionError)`);
@@ -2877,12 +3835,22 @@ export class Stepper {
2877
3835
  }
2878
3836
  return [{ t: 'opaque', why: `${x.text}: a true division (a float; the subset reads math.floor or math.ceil of x / k, int(x / k), or x // k)` }, q2];
2879
3837
  }
3838
+ // (other code's value left out, computed with: whether that raises is that value's, so it is read)
3839
+ const asked = [a, b].find(v => v.t === 'opaque' && v.ask);
3840
+ if (asked)
3841
+ return refuse(x, `${x.text}: arithmetic on ${asked.why} (what it does depends on that value)`);
2880
3842
  if (a.t === 'opaque' || b.t === 'opaque')
2881
3843
  return [a.t === 'opaque' ? a : b, q2];
2882
3844
  if ((a.t === 'str' || a.t === 'fmt') && op === '+')
2883
3845
  return [{ t: 'opaque', why: `${x.text}: strings joined` }, q2];
2884
- if (a.t === 'str' && op === '%')
2885
- return [{ t: 'opaque', why: `${x.text}: a string formatted` }, q2];
3846
+ if (a.t === 'str' && op === '%') {
3847
+ // ('...%s...' % x or % (x, y): %s and %d holes, %% a percent sign)
3848
+ const f = a.e.op === 'slit' ? a.e.value.split(/(%[sd%])/) : undefined, xs = b.t === 'tuple' ? b.xs : [b];
3849
+ if (!f || f.filter(t => t === '%s' || t === '%d').length !== xs.length)
3850
+ return [{ t: 'opaque', why: `${x.text}: a string formatted` }, q2];
3851
+ let i = 0;
3852
+ return this.fstr(x, q2, f.flatMap((t) => (t === '%%' ? ['%'] : t === '%s' || t === '%d' ? [xs[i++]] : t ? [t] : [])));
3853
+ }
2886
3854
  const na = this.numOf(a, x, q2), nb = this.numOf(b, x, q2);
2887
3855
  switch (op) {
2888
3856
  case '+': return [{ t: 'num', e: I.add(na, nb) }, q2];
@@ -3020,6 +3988,20 @@ export class Stepper {
3020
3988
  }
3021
3989
  return out(op === 'in' ? e : I.not(e));
3022
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
+ }
3023
4005
  if (op === '==' || op === '!=') {
3024
4006
  const e = this.equal(a, b, x, q2);
3025
4007
  return out(op === '==' ? e : I.not(e));
@@ -3034,6 +4016,13 @@ export class Stepper {
3034
4016
  const o = a.t === 'none' ? b : a;
3035
4017
  return o.t === 'none' ? I.T : o.t === 'opt' ? I.not(o.has) : I.F;
3036
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
+ }
3037
4026
  if (a.t === 'opt')
3038
4027
  return I.and(a.has, this.equal(a.v, b, at, p));
3039
4028
  if (b.t === 'opt')
@@ -3106,20 +4095,42 @@ export class Stepper {
3106
4095
  }
3107
4096
  // An f-string: with one hole between literal text, a key a store reads by (its template); else a value kept only
3108
4097
  // where nothing reads it.
3109
- fstr(x, p) {
3110
- const parts = x.parts;
4098
+ // A constant string in a hole (a literal, a stated attribute: a store's name) is literal text of the template; a
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
+ }
4108
+ fstr(x, p, given) {
4109
+ const parts = given ?? x.parts;
3111
4110
  let q = p, tpl = '', hole, n = 0, opaque = false, ask;
3112
4111
  for (const part of parts) {
3113
4112
  if (typeof part === 'string') {
3114
4113
  tpl += part.replace(/\{\}/g, '{ }');
3115
4114
  continue;
3116
4115
  }
3117
- const [v, q2] = this.ev(part.x, q);
3118
- q = q2;
4116
+ let v;
4117
+ const plain = 't' in part || part.plain;
4118
+ if ('t' in part)
4119
+ v = part;
4120
+ else {
4121
+ const [v1, q2] = this.ev(part.x, q);
4122
+ v = v1;
4123
+ q = q2;
4124
+ }
4125
+ this.checkOrmDisplay(v, x);
4126
+ if (v.t === 'str' && v.e.op === 'slit' && plain) {
4127
+ tpl += v.e.value.replace(/\{\}/g, '{ }');
4128
+ continue;
4129
+ }
3119
4130
  n++;
3120
4131
  if (v.t === 'opaque' && v.ask)
3121
4132
  ask ??= v;
3122
- if (!part.plain || n > 1 || !(v.t === 'str' || (v.t === 'num' && part.plain))) {
4133
+ if (!plain || n > 1 || !(v.t === 'str' || v.t === 'num')) {
3123
4134
  opaque = true;
3124
4135
  continue;
3125
4136
  }
@@ -3136,11 +4147,12 @@ export class Stepper {
3136
4147
  if (dead(p))
3137
4148
  return [{ t: 'opaque', why: 'unreachable' }, p];
3138
4149
  const fx = x.f, names = this.calleeNames(x), args0 = x.args, kw0 = x.kw;
3139
- // The boundary first: an answered call, then a skipped one (neither's arguments read).
3140
- const ans = this.match(Object.keys(this.opts.answers ?? {}), names), skip = !ans && this.skipped(names);
3141
- if (ans || skip) {
4150
+ // The boundary first: an effect, an answered call, then a skipped one (none's arguments read but an effect's).
4151
+ const quiet = this.match(this.opts.stubs, names), eff = quiet ?? this.match(this.opts.effects, names) ?? (this.tagAt(x.p)?.k === 'effect' ? names[0] : undefined);
4152
+ const ans = !eff ? this.match(Object.keys(this.opts.answers ?? {}), names) : undefined, skip = !eff && !ans && this.skipped(names);
4153
+ if (ans || skip || eff) {
3142
4154
  let patch;
3143
- if (!ans && !this.tries.length) { } // (left out outside a try: run as it is, no stub)
4155
+ if (!ans && !eff && !this.tries.length) { } // (left out outside a try: run as it is, no stub)
3144
4156
  else if (fx.e === 'fn')
3145
4157
  patch = { mod: this.mod.module, path: [String(fx.id)] };
3146
4158
  else if (fx.e === 'get' && fx.x.e === 'var' && fx.x.n === 'self')
@@ -3148,7 +4160,10 @@ export class Stepper {
3148
4160
  else if (fx.e === 'get') {
3149
4161
  // A method of an object the caller gives, of another module's class: the class's method stubbed.
3150
4162
  const [o] = this.ev(fx.x, p), obj = o.t === 'ref' ? p.heap.get(o.id) : undefined;
3151
- if (obj?.k === 'rec') {
4163
+ // (a class's method, Redis.from_url: stubbed on the class where the module reads it)
4164
+ if (o.t === 'cls' && o.patch?.path && (eff || ans))
4165
+ patch = { ...o.patch, path: [...o.patch.path, String(fx.f)] };
4166
+ else if (obj?.k === 'rec') {
3152
4167
  const r = this.rec(obj.ty, x);
3153
4168
  patch = { mod: r.module, path: [r.short, String(fx.f)] };
3154
4169
  }
@@ -3168,6 +4183,22 @@ export class Stepper {
3168
4183
  }
3169
4184
  if (ans)
3170
4185
  return this.answer(ans, names, patch, x, this.argsRead(x, p), awaited);
4186
+ if (eff) {
4187
+ if (!patch)
4188
+ return refuse(x, `${x.text}: an effect the check can't stub (a function of the module, a method of the object, a store or another module's)`);
4189
+ const key = eff.split('.').pop();
4190
+ const a = this.answers.get(key);
4191
+ if (a && !a.effect)
4192
+ return refuse(x, `${x.text}: ${key} an effect at one call and not at another`);
4193
+ if (!a) {
4194
+ this.answers.set(key, { key, patch, async: awaited, inputs: { name: '' }, sort: '', pass: true, effect: true, ...(quiet ? { quiet: true } : {}), at: [] });
4195
+ this.notes.add(quiet ? `${key} (${x.p}): stubbed (stated): it does nothing and returns None in the check` : `${key}: an effect (${this.opts.effects?.length ? 'stated' : 'tagged'}): each step says whether it called it (${key}.called), the check stubbing it`);
4196
+ }
4197
+ if (quiet)
4198
+ return [{ t: 'none' }, p];
4199
+ const q = this.argsRead(x, p);
4200
+ return [{ t: 'none' }, { ...q, eff: new Map(q.eff).set(key, I.T) }];
4201
+ }
3171
4202
  for (const n of names)
3172
4203
  this.leftOut.add(n);
3173
4204
  this.notes.add(`${names[0]} (${x.p}): left out (stated: skip), run as it is by the check`);
@@ -3178,6 +4209,15 @@ export class Stepper {
3178
4209
  if (fx.e === 'get') {
3179
4210
  const [o, q1] = this.ev(fx.x, q);
3180
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
+ }
3181
4221
  if (o.t === 'val')
3182
4222
  return this.evArgs(x, q, (args, kw, q2) => this.valCall(o, String(fx.f), args, kw, x, q2));
3183
4223
  const ord = this.orderedObj(o, q);
@@ -3191,7 +4231,7 @@ export class Stepper {
3191
4231
  return refuse(x, `${x.text}: a method of the store's ${o.path} (not stated)`);
3192
4232
  [f, q] = this.get(fx, q);
3193
4233
  if (o.t === 'opaque' && f.t === 'opaque')
3194
- return this.inf ? this.boundary(x, { key: names[0] ?? String(x.text), name: names[0] ?? String(x.text), refusal: `${x.text}: a call on ${o.why}` }, q, awaited) : refuse(x, `${x.text}: a call on ${o.why}`);
4234
+ return this.inf ? this.boundary(x, { key: names[0] ?? String(x.text), name: names[0] ?? String(x.text), refusal: `${x.text}: a call on ${o.why}`, ...(o.sattr ? { recv: o } : {}) }, q, awaited) : refuse(x, `${x.text}: a call on ${o.why}`);
3195
4235
  }
3196
4236
  else
3197
4237
  [f, q] = this.ev(fx, q);
@@ -3214,6 +4254,8 @@ export class Stepper {
3214
4254
  }
3215
4255
  }
3216
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));
3217
4259
  // (another module's class made: other code, at the boundary)
3218
4260
  const r = this.inf ? this.mod.recs[f.rec] : undefined;
3219
4261
  if (r && !r.own && !madeByInit(r))
@@ -3321,13 +4363,68 @@ export class Stepper {
3321
4363
  return refuse(x, `${x.text}: set.${name} (the subset reads add, discard, remove and in)`);
3322
4364
  });
3323
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
+ }
3324
4420
  construct(rec, args, kw, x, p) {
3325
4421
  const r = this.rec(rec, x);
4422
+ const initId = this.initMethod(r, x);
3326
4423
  // (a plain class of the repository whose __init__ the reader read: made by running it on a fresh object)
3327
4424
  if (madeByInit(r)) {
3328
4425
  const id = `fresh:${this.fresh++}`, q1 = { ...p, heap: new Map(p.heap).set(id, { k: 'rec', ty: rec, f: new Map(), origin: 'fresh' }) };
3329
4426
  this.notes.add(`${r.short}(...) (${x.p}): made by its __init__, read`);
3330
- 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]];
3331
4428
  }
3332
4429
  if (!r.kinds.includes('dataclass') || !r.own)
3333
4430
  return refuse(x, `${x.text}: ${r.short} made (the subset makes the module's own dataclasses)`);
@@ -3374,6 +4471,9 @@ export class Stepper {
3374
4471
  return this.evArgs(x, p, (args, kw, q) => {
3375
4472
  if (kw.length)
3376
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);
3377
4477
  // (int of a timestamp: its whole seconds)
3378
4478
  if (n === 'int' && args[0]?.t === 'val')
3379
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)}`);
@@ -3387,6 +4487,16 @@ export class Stepper {
3387
4487
  if (n === 'len' && cl)
3388
4488
  return [{ t: 'num', e: cl.len }, q];
3389
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`);
3390
4500
  case 'min':
3391
4501
  case 'max': {
3392
4502
  if (args.length < 2)
@@ -3421,24 +4531,40 @@ export class Stepper {
3421
4531
  return refuse(x, `${x.text}: ${n}() (a builtin outside the subset)`);
3422
4532
  });
3423
4533
  }
3424
- // (even: Python's round(a / k), the nearest whole number, a half to the even one: exact for |a| below 2^53, where the
3425
- // 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.
3426
4540
  quotient(d, p, round) {
3427
4541
  const [a, q] = this.ev(d.x, p), [b, q2] = this.ev(d.y, q), k = constOf(b);
3428
4542
  if (k === undefined)
3429
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)`);
3430
4546
  if (k === 0) {
3431
4547
  this.fail(q2, I.T, d, `${d.text}: a division by zero (a ZeroDivisionError)`);
3432
4548
  return [{ t: 'num', e: I.num(0) }, { ...q2, pc: [...q2.pc, I.F] }];
3433
4549
  }
4550
+ if (!Number.isSafeInteger(k))
4551
+ return refuse(d, `${d.text}: a division by a constant that isn't whole`);
3434
4552
  const n = this.numOf(a, d, q2), fl = this.floorDiv(n, k), ce = I.neg(this.floorDiv(I.neg(n), k));
3435
4553
  const lt = k > 0 ? I.cmp('<', n, I.num(0)) : I.cmp('<', I.num(0), n);
3436
- if (round === 'even') {
3437
- // (r = a − k·⌊a/k⌋: below half of k the floor, past it one more, at it the even of the two)
3438
- 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);
3439
- 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];
3440
- }
3441
- 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];
3442
4568
  }
3443
4569
  lib(q0, x, p) {
3444
4570
  const a0 = x.args[0];
@@ -3452,15 +4578,24 @@ export class Stepper {
3452
4578
  return [{ t: 'lock' }, p];
3453
4579
  // A datetime: the request's time (in whole seconds, as time.time()), in milliseconds; a timedelta by its parts.
3454
4580
  if (q0 === 'datetime.datetime.now') {
3455
- if (x.args.length || x.kw.length)
3456
- 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`);
3457
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
+ }
3458
4591
  const [t, q] = this.clock(x, p);
3459
- 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];
3460
4593
  }
3461
- if (q0 === 'datetime.timedelta')
4594
+ if (q0 === 'datetime.timedelta' || q0 === 'dateutil.relativedelta.relativedelta')
3462
4595
  return this.evArgs(x, p, (args, kw, q) => {
3463
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`);
3464
4599
  if (args.length > 1)
3465
4600
  return refuse(x, `${x.text}: a timedelta of positional parts past its days`);
3466
4601
  const parts = [...(args.length ? [['days', args[0]]] : []), ...kw];
@@ -3552,6 +4687,10 @@ export class Stepper {
3552
4687
  const seg = segs[0], rest = segs.slice(1), out = new Map(fs);
3553
4688
  if (!rest.length) {
3554
4689
  const old = fs.get(seg);
4690
+ if (old?.t === 'opaque' && old.sink) {
4691
+ out.set(seg, old);
4692
+ return out;
4693
+ }
3555
4694
  if (old?.t === 'opaque')
3556
4695
  refuse(at, `writes ${old.why}`);
3557
4696
  out.set(seg, x);
@@ -3704,13 +4843,13 @@ export class Stepper {
3704
4843
  }
3705
4844
  numv(v, at) {
3706
4845
  if (v.t !== 'num')
3707
- 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`);
3708
4847
  if (v.slen)
3709
4848
  return refuse(at, 'len of a string read other than against 0 (strings are set and compared in the subset)');
3710
4849
  return v.e;
3711
4850
  }
3712
4851
  boolv(v, at) { if (v.t !== 'bool')
3713
- 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; }
3714
4853
  // A binary operation of the reader's language with fixed-width integers (Go's): comparisons, arithmetic wrapped.
3715
4854
  binop(op, a, b, x, p) {
3716
4855
  if (op === '==' || op === '!=') {
@@ -3748,8 +4887,97 @@ export class Stepper {
3748
4887
  return refuse(x, 'strings joined (strings are set and compared in the subset)');
3749
4888
  return this.arith(op, a, b, x, p);
3750
4889
  }
4890
+ if (['&', '|', '^', '&^'].includes(op) && a.t === 'num' && b.t === 'num')
4891
+ return this.bitop(op, a, b, x);
3751
4892
  return refuse(x, `${op}: a bit operation (outside the subset)`);
3752
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
+ }
3753
4981
  eq(a, b, x, p) {
3754
4982
  if (a.t === 'map' && b.t === 'nil' && p)
3755
4983
  return this.mapAt(a, x, p).nil;
@@ -3780,12 +5008,15 @@ export class Stepper {
3780
5008
  }
3781
5009
  if ((a.t === 'list' || a.t === 'map') && b.t === 'nil')
3782
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)`);
3783
- 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}`}`);
3784
5012
  }
3785
5013
  // Integer arithmetic at the type's width: the exact result, wrapped as the type wraps it (or refused, at 64 bits).
3786
5014
  arith(op, a, b, x, p) {
3787
- if (a.t !== 'num' || b.t !== 'num')
3788
- 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
+ }
3789
5020
  this.numv(a, x);
3790
5021
  this.numv(b, x);
3791
5022
  const ty = a.ty?.name !== undefined ? a.ty : b.ty;
@@ -3848,7 +5079,10 @@ export class Stepper {
3848
5079
  const a = this.bounds(e.a), b = this.bounds(e.b);
3849
5080
  return [a[0] + b[0], a[1] + b[1]];
3850
5081
  }
5082
+ // (x − k·(x div k): x's floor remainder by k, a conversion's wrap)
3851
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];
3852
5086
  const a = this.bounds(e.a), b = this.bounds(e.b);
3853
5087
  return [a[0] - b[1], a[1] - b[0]];
3854
5088
  }
@@ -4343,6 +5577,11 @@ const cellV = (map, i, f, s, ty) => {
4343
5577
  const c = { op: 'cell', map, key: { op: 'num', e: i }, field: f };
4344
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 : [] } };
4345
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);
4346
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);
4347
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`));
4348
5587
  // The locals a body sets (each statement's targets), by name.
@@ -4371,8 +5610,17 @@ const firm = (v) => ['ptr', 'struct', 'err', 'nil', 'map', 'list', 'push', 'pop'
4371
5610
  // Whether some node of an IR tree (an object, depth first) is one f says yes to.
4372
5611
  const deep = (x, f) => !!x && typeof x === 'object' && (!!f(x) || Object.values(x).some(y => deep(y, f)));
4373
5612
  const callFree = (x) => !deep(x, o => o.e === 'call' || o.e === 'await' || o.e === 'no');
4374
- // An expression that reaches none of the module's own code and not `self`.
4375
- const foreign = (x) => !deep(x, o => o.e === 'fn' || (o.e === 'var' && o.n === 'self'));
5613
+ // A key of the other kind than its map's (a string into a map keyed by numbers): never held where keys are compared as
5614
+ // they are (a Map, a dict, a hash), so refused; an object's keys (a record's, JavaScript's) are strings both.
5615
+ const kindOf = (k) => k.op === 'num' ? 'num' : k.op === 'svar' || k.op === 'slit' ? 'str' : k.op === 'kite' && kindOf(k.a) === kindOf(k.b) ? kindOf(k.a) : undefined;
5616
+ function keyKind(d, k, at) {
5617
+ const kk = kindOf(k);
5618
+ if (kk && kk !== d.key && d.js !== 'record' && !d.untyped)
5619
+ refuse(at, `${at.text ?? ''}: a ${kk === 'num' ? 'number' : 'string'} key of a map keyed by ${d.key === 'num' ? 'numbers' : 'strings'} (never one it holds)`);
5620
+ }
5621
+ // An expression that reaches none of the module's own code and not `self`, nor what raises wherever it runs (a reader's
5622
+ // `raises`: a name nothing binds).
5623
+ const foreign = (x) => !deep(x, o => o.e === 'fn' || (o.e === 'var' && o.n === 'self') || !!o.raises);
4376
5624
  // Two key templates name disjoint keys: they differ at some position of their fixed prefixes or of their fixed
4377
5625
  // suffixes (a hole's value can be any string, so only those parts tell keys apart).
4378
5626
  export function disjoint(a, b) {
@@ -4479,6 +5727,13 @@ export function readStep(mod, opts) {
4479
5727
  }
4480
5728
  }
4481
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
+ }
4482
5737
  function readOnce(mod, opts, g) {
4483
5738
  if (mod.error)
4484
5739
  refuse(mod.file ?? mod.root ?? '?', mod.error);
@@ -4518,11 +5773,13 @@ function readOnce(mod, opts, g) {
4518
5773
  g.method = '__init__';
4519
5774
  const r0 = g.refusals.length;
4520
5775
  let made;
4521
- const initId = r.methods.__init__;
5776
+ const initId = g.initMethod(r, at);
4522
5777
  if (initId)
4523
5778
  g.entryIds.add(initId);
4524
5779
  if (r.kinds.some(k => k.startsWith('generic:')))
4525
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);
4526
5783
  const rustNew = mod.lang === 'rust' ? r.methods.new : undefined;
4527
5784
  if (rustNew)
4528
5785
  g.entryIds.add(rustNew);
@@ -4630,13 +5887,15 @@ function readOnce(mod, opts, g) {
4630
5887
  if (ctor.length)
4631
5888
  g.notes.add(`${r.short} made by its constructor: its arguments are the rule's params`);
4632
5889
  }
4633
- 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);
4634
5893
  const f = new Map();
4635
5894
  let p = fresh;
4636
5895
  for (const fd of r.fields) {
4637
5896
  if (fd.dflt) {
4638
5897
  const [d, p2] = g.ev(fd.dflt, p);
4639
- f.set(fd.name, d);
5898
+ f.set(fd.name, g.timeField(d, fd.t, false, { p: r.p }));
4640
5899
  p = p2;
4641
5900
  g.declared.set(`this.${fd.name}`, fd.t);
4642
5901
  continue;
@@ -4644,14 +5903,14 @@ function readOnce(mod, opts, g) {
4644
5903
  const [v, a] = g.input(fd.name, fd.t, { p: r.p }, p, 'param');
4645
5904
  if (a.k === 'inert')
4646
5905
  refuse(r, `${r.short}.${fd.name}: a field of ${g.why(fd.t)}`);
4647
- f.set(fd.name, v);
5906
+ f.set(fd.name, g.timeField(v, fd.t, false, { p: r.p }));
4648
5907
  ctor.push([fd.name, a]);
4649
5908
  g.declared.set(`this.${fd.name}`, fd.t);
4650
5909
  }
4651
5910
  if (r.methods.__post_init__)
4652
5911
  refuse(r, `${r.short}: __post_init__`);
4653
5912
  made = { ...p, heap: new Map(p.heap).set('this', { k: 'rec', ty: cls, f, origin: 'state' }) };
4654
- 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`);
4655
5914
  }
4656
5915
  else
4657
5916
  made = fresh;
@@ -4659,8 +5918,11 @@ function readOnce(mod, opts, g) {
4659
5918
  pre = I.and(I.not(I.or(...g.fails)), I.not(I.or(...g.paramsOut)), I.not(I.or(...g.refusals.splice(r0))));
4660
5919
  g.fails = [];
4661
5920
  g.init = false;
4662
- // (a field a framework injects, @Autowired or @Inject on it: the store the check gives, named by the field)
4663
- for (const fd of g.inf ? r.fields.filter(f => f.inject && !made.heap.get('this').f.has(f.name)) : []) {
5921
+ // (a field a framework injects, @Autowired or @Inject on it, or one a stated store names whatever the constructor
5922
+ // made it (a client made from a URL): the store the check gives, named by the field)
5923
+ const madeAs = (f) => made.heap.get('this').f.get(f), isStore = (v) => v?.t === 'ref' && made.heap.get(v.id)?.k === 'store';
5924
+ const stated = Object.keys(opts.stores ?? {}).filter(f => madeAs(f) && !isStore(madeAs(f)) && !r.fields.some(x => x.name === f)).map(f => ({ name: f, t: { k: 'any' } }));
5925
+ for (const fd of [...r.fields.filter(f => (g.inf && f.inject && !madeAs(f.name)) || (opts.stores?.[f.name] && madeAs(f.name) && !isStore(madeAs(f.name)))), ...stated]) {
4664
5926
  const id = `store:${fd.name}`, o = { k: 'store', name: fd.name };
4665
5927
  made.heap.set(id, o);
4666
5928
  g.initHeap.set(id, o);
@@ -4672,7 +5934,7 @@ function readOnce(mod, opts, g) {
4672
5934
  if (keyed)
4673
5935
  g.storeKeyed.add(fd.name);
4674
5936
  g.deps.push({ name: fd.name, ...(fd.t.k === 'rec' ? { ty: fd.t.name } : {}), keyed, stated: false });
4675
- g.notes.add(`${r.short}.${fd.name}: an injected dependency (marked so), the check giving one`);
5937
+ g.notes.add(`${r.short}.${fd.name}: ${stated.includes(fd) ? 'a store (stated), the check giving one in its place after the constructor' : 'an injected dependency (marked so), the check giving one'}`);
4676
5938
  }
4677
5939
  // (two injected dependencies are taken as two objects: where they are of one type and the rule holds keys of one,
4678
5940
  // the code may be given one object for both, which the rule would take as two; refused unless both are stated)
@@ -4701,7 +5963,7 @@ function readOnce(mod, opts, g) {
4701
5963
  g.notes.add(`${r.short}.${fd.name}: declared on the class but not set by its constructor (left out)`);
4702
5964
  // Each field a leaf: a variable (two for an optional one), a nested object's own, a map, a store, or left out.
4703
5965
  const heap = new Map();
4704
- const fields = new Map();
5966
+ const fields = new Map(), holding = new Set();
4705
5967
  const build = (path, v, t, into, initPath) => {
4706
5968
  const name = path.join('_'), f = path.at(-1), decl = t ?? undefined;
4707
5969
  const scalarT = decl && decl.k !== 'opt' ? decl : undefined;
@@ -4748,9 +6010,14 @@ function readOnce(mod, opts, g) {
4748
6010
  return;
4749
6011
  }
4750
6012
  if (o?.k === 'rec') {
6013
+ // (an object that holds itself, by a field of its own or of one it holds: its leaves would never end)
6014
+ if (holding.has(v.id))
6015
+ refuse(at, `${path.join('.')}: an object that holds itself`);
6016
+ holding.add(v.id);
4751
6017
  const sub = new Map(), id = `state:${path.join('.')}`;
4752
6018
  for (const [ff, vv] of o.f)
4753
6019
  build([...path, ff], vv, g.mod.recs[o.ty]?.fields.find(x => x.name === ff)?.t, sub, initPath);
6020
+ holding.delete(v.id);
4754
6021
  heap.set(id, { k: 'rec', ty: o.ty, f: sub, origin: 'state' });
4755
6022
  leaves.push({ name: '', path, kind: 'frame', cls: o.ty });
4756
6023
  into.set(f, { t: 'ref', id });
@@ -4790,8 +6057,9 @@ function readOnce(mod, opts, g) {
4790
6057
  leaves.push({ name: '', path, kind: 'frame' });
4791
6058
  return;
4792
6059
  }
4793
- // A field the constructor sets to None, of no declared type: a constant (a method setting it is refused).
4794
- if (v.t === 'none') {
6060
+ // A field the constructor sets to None, of no declared type, or to a key's template (a lock's key made of its name):
6061
+ // a constant (a method setting it is refused).
6062
+ if (v.t === 'none' || v.t === 'fmt') {
4795
6063
  into.set(f, v);
4796
6064
  g.frozen.add(path.join('.'));
4797
6065
  leaves.push({ name: '', path, kind: 'frame' });
@@ -4950,18 +6218,18 @@ function readOnce(mod, opts, g) {
4950
6218
  const id = [...g.initHeap].find(([, o]) => o.k === 'map' && o.decl === d)?.[0];
4951
6219
  if (!id)
4952
6220
  continue;
4953
- const cw = (w0) => ({ key: w0.key, has: w0.has, vals: Object.fromEntries([...w0.vals].map(([f2, v]) => [f2, termOf(v, at)])) });
4954
- 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))]; });
4955
6223
  // (a failure kept, the cell as it was there)
4956
6224
  const fix = (i, w2, base) => { if (!kept || carried)
4957
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)])) }; };
4958
6226
  // (several keys written by some method: each method's writes under its own selector, so a key compared is the
4959
6227
  // request's, never one of two by the method)
4960
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)])) }; };
4961
- 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 }))) : [];
4962
6230
  const w = ws.length ? ws.at(-1) : mapWritesOf(g, d, finals.map(f => f.sel), lists.map(l => l[0]), fix);
4963
6231
  if (w)
4964
- 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;
4965
6233
  }
4966
6234
  // What each method returns, and whether it failed: the step's result.
4967
6235
  const results = {}, resultKinds = {};
@@ -4969,6 +6237,8 @@ function readOnce(mod, opts, g) {
4969
6237
  if (kept) {
4970
6238
  failedVar = g.newVar('failed', { k: 'bool' }, 'state', 'whether the step failed (an exception raised): the state is as it was');
4971
6239
  }
6240
+ // (each effect: whether the step called it, on the method's path that did)
6241
+ const effectVars = [...g.answers.values()].filter(a => a.effect && !a.quiet).map(a => ({ key: a.key, v: g.newVar(`${a.key.replace(/\W+/g, '_')}_called`, { k: 'bool' }, 'state', `whether the step called ${a.key}`) }));
4972
6242
  for (const [i, f] of finals.entries()) {
4973
6243
  const fn = chosen[i];
4974
6244
  const out = f.out;
@@ -5026,6 +6296,8 @@ function readOnce(mod, opts, g) {
5026
6296
  state.push(rn);
5027
6297
  init[rn.name] = { s: 'bool', e: I.F };
5028
6298
  }
6299
+ for (const e of effectVars)
6300
+ fields.push([`effect:${e.key}`, e.v.name]);
5029
6301
  if (fields.length === 1 && !failedVar && rv && !rn)
5030
6302
  results[fn.name] = { k: 'scalar', name: rv.name };
5031
6303
  else if (fields.length)
@@ -5052,6 +6324,12 @@ function readOnce(mod, opts, g) {
5052
6324
  writes[o] = acc;
5053
6325
  void v;
5054
6326
  }
6327
+ for (const e of effectVars) {
6328
+ outputs.push(e.v.name);
6329
+ state.push(e.v);
6330
+ init[e.v.name] = { s: 'bool', e: I.F };
6331
+ writes[e.v.name] = { s: 'bool', e: I.or(...finals.map(f => I.and(f.sel, f.path.eff?.get(e.key) ?? I.F))) };
6332
+ }
5055
6333
  if (failedVar) {
5056
6334
  outputs.push(failedVar.name);
5057
6335
  state.push(failedVar);
@@ -5062,8 +6340,14 @@ function readOnce(mod, opts, g) {
5062
6340
  // Inputs no term reads are still the request's (the check builds the arguments from them).
5063
6341
  const maps = g.maps.filter(d => [...g.initHeap.values()].some(o => o.k === 'map' && o.decl === d));
5064
6342
  const stores = Object.fromEntries([...new Set([...Object.keys(opts.stores ?? {}), ...g.storeDecls.keys()])].map(n => [n, { ...g.storeDecl(n), async: g.storeAsync[n] ?? {} }]));
5065
- for (const sm of g.storeMaps.values())
5066
- 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 ? { float: true } : {}), ...(sm.json ? { json: sm.json } : {}), ...(sm.choice ? { choice: true } : {}) });
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
+ }
6347
+ for (const sm of g.storeMaps.values()) {
6348
+ const str = sm.decl.fields[0]?.sort.k === 'str' && !sm.json;
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 } : {}) });
6350
+ }
5067
6351
  const layout = { k: 'rec', fields: state.filter(v => !outputs.includes(v.name)).map(v => [v.name, { k: 'scalar', name: v.name }]) };
5068
6352
  for (const fn of chosen) {
5069
6353
  const used = new Set();
@@ -5098,6 +6382,16 @@ function readOnce(mod, opts, g) {
5098
6382
  if (g.vars.get(base)?.sort.k === 'num')
5099
6383
  laws.push(`r.law(${JSON.stringify(`${base}: a None one holds 0`)}, ({${base}, ${l.name}}) => any(${l.name}.not(), ${base}.eq(0)))`);
5100
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
+ }
5101
6395
  // (a stored JSON record's optional field: absent, its cell holds the default, as the text holds nothing there)
5102
6396
  for (const sm of g.storeMaps.values()) {
5103
6397
  const opts = (sm.json ?? []).filter(f => f.opt), n = sm.decl.name;
@@ -5127,9 +6421,11 @@ function readOnce(mod, opts, g) {
5127
6421
  }
5128
6422
  mention(refuseB);
5129
6423
  mention(pre);
5130
- for (const fd of g.folds)
6424
+ for (const fd of g.folds) {
5131
6425
  for (const t of [...Object.values(fd.init), ...Object.values(fd.step)])
5132
6426
  mention(t.e);
6427
+ mention(fd.len);
6428
+ }
5133
6429
  const unread = g.inputs.filter(v => !read.has(v.name) && v.name !== ev?.name && !g.kept.has(v.name));
5134
6430
  if (unread.length)
5135
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(', ')}`);
@@ -5176,9 +6472,9 @@ function readOnce(mod, opts, g) {
5176
6472
  params: g.params, inputs, state, maps, init, writes, mapWrites, outputs,
5177
6473
  refuse: refuseB, pre, layout, events, notes: [...g.notes], hints: g.hints, ...(ev ? { event: ev.name } : {}), results, laws,
5178
6474
  ...(g.leasts.length ? { leasts: g.leasts } : {}),
5179
- ...(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 } : {}),
5180
6476
  };
5181
- 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 } : {}) };
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)])) } : {}) };
5182
6478
  }
5183
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).
5184
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]);
@@ -5209,7 +6505,7 @@ export function padWrites(lists, base) {
5209
6505
  export function mapWritesOf(g, d, sels, ws, fix = (_, w) => w) {
5210
6506
  if (!ws.some(Boolean))
5211
6507
  return undefined;
5212
- const key0 = ws.find(Boolean).key, base = (k) => { const c = g.baseCell(d, k); return { key: k, has: c.has, vals: Object.fromEntries([...c.vals].map(([f, v]) => [f, { s: v.t === 'num' ? 'num' : v.t === 'choice' ? 'choice' : 'bool', e: v.e }])) }; };
6508
+ const key0 = ws.find(Boolean).key, base = (k) => { const c = g.baseCell(d, k); return { key: k, has: c.has, vals: Object.fromEntries([...c.vals].map(([f, v]) => [f, { s: v.t === 'num' ? 'num' : v.t === 'choice' ? 'choice' : v.t === 'str' ? 'str' : 'bool', e: v.e }])) }; };
5213
6509
  let acc;
5214
6510
  for (let i = sels.length - 1; i >= 0; i--) {
5215
6511
  const w = ws[i] ? fix(i, ws[i], base) : base(acc?.key ?? key0), c = sels[i];
@@ -5254,24 +6550,61 @@ export function asset(rel) {
5254
6550
  }
5255
6551
  // A harness started on the two named pipes in `work` and both opened. It runs under sh, which, if the harness exits
5256
6552
  // before it answered (it couldn't start: a file missing, an interpreter absent, the code not loading), opens the
5257
- // pipes itself and answers the first request with the error, so nothing here waits on a harness that is gone.
5258
- const GUARD = 'i=$1 o=$2; shift 2; trap \'kill $p 2>/dev/null; exit 143\' TERM; "$@" "$i" "$o" & p=$!; wait $p; e=$?; [ "$e" = 0 ] && exit 0; trap - TERM; exec 3<"$i" 4>"$o"; read -r _ <&3; printf \'{"error": "the harness exited (status %s) before it answered"}\\n\' "$e" >&4';
6553
+ // pipes itself and answers the first request with the error, so nothing here waits on a harness that is gone. The
6554
+ // reads here block, so the harness runs within GDP_CHECK_HARNESS_S seconds (120, all its requests): past them sh kills
6555
+ // it and answers `stopped` (a step of the code that doesn't end: a loop a reader read as one that does).
6556
+ export const harnessLimit = () => Number(proc?.env?.GDP_CHECK_HARNESS_S ?? 120);
6557
+ // The check's build of the code (its compiler, the code with the harness): each within GDP_COMPILE_S seconds (900).
6558
+ // The compiler's errors about the code's own files are the source's (a refusal, with its message), about the
6559
+ // harness's the check's own; a compiler that fails saying nothing of the code (killed, crashed, past its time) runs
6560
+ // once more (`first`: a failure already had), then fails the check's harness. Never "the rule and the code differ".
6561
+ export const compileLimit = () => Number(proc?.env?.GDP_COMPILE_S ?? 900) * 1000;
6562
+ export function buildCheck(tool, run, errorsOf, ofSource, first) {
6563
+ let last = first;
6564
+ for (let i = 0; i < 2; i++) {
6565
+ if (i > 0 || last === undefined) {
6566
+ try {
6567
+ return { ok: run() };
6568
+ }
6569
+ catch (e) {
6570
+ last = e;
6571
+ }
6572
+ }
6573
+ const errs = last.signal ? [] : errorsOf(last);
6574
+ if (errs.length) {
6575
+ const src = errs.filter(ofSource);
6576
+ return src.length ? { kind: 'source', why: `the source doesn't compile (${tool}): ${src.slice(0, 3).join(' | ').slice(0, 900)}` } : { kind: 'harness', why: `the check's harness for the code doesn't build (${tool}): ${errs.slice(0, 3).join(' | ').slice(0, 900)}` };
6577
+ }
6578
+ }
6579
+ const said = String(last.stderr || last?.message || last).split('\n').filter(l => l.trim()).slice(-2).join(' | ').slice(0, 300);
6580
+ return { kind: 'harness', why: `${tool} failed twice with nothing to say of the code (${last.signal ? `killed: ${last.signal}, ` : ''}${said})` };
6581
+ }
6582
+ // (a build's outcome as the check's evidence: the source refused, or the harness failed)
6583
+ export const builtEvidence = (b) => (b.kind === 'source' ? { source: b.why } : { harness: b.why });
6584
+ // (the harness past its time, or its transport failing, `transport` set: the check's failure, not the code's)
6585
+ export const stopped = (res) => { if (res.stopped || res.transport)
6586
+ throw new HarnessFailure(String(res.error)); return res; };
6587
+ const GUARD = 'i=$1 o=$2 l=$3; shift 3; trap \'kill $p $w 2>/dev/null; exit 143\' TERM; "$@" "$i" "$o" & p=$!; (trap \'kill $s 2>/dev/null; exit 0\' TERM; sleep "$l" & s=$!; wait $s; kill -9 $p) 2>/dev/null & w=$!; wait $p; e=$?; kill $w 2>/dev/null; [ "$e" = 0 ] && exit 0; trap - TERM; if [ "$e" = 137 ]; then exec 4>"$o"; printf \'{"error": "the code did not answer within %s s (a request that does not end)", "stopped": true}\\n\' "$l" >&4; exit 1; fi; exec 3<"$i" 4>"$o"; read -r _ <&3; printf \'{"error": "the harness exited (status %s) before it answered"}\\n\' "$e" >&4';
5259
6588
  export function openHarness(work, cmd, args, o) {
5260
6589
  const fs = node('node:fs'), cp = node('node:child_process');
5261
6590
  cp.execFileSync('mkfifo', [`${work}/in`, `${work}/out`], {});
5262
- const child = cp.spawn('sh', ['-c', GUARD, 'gdp-harness', `${work}/in`, `${work}/out`, cmd, ...args], o);
6591
+ const child = cp.spawn('sh', ['-c', GUARD, 'gdp-harness', `${work}/in`, `${work}/out`, String(harnessLimit()), cmd, ...args], o);
5263
6592
  const wi = fs.openSync(`${work}/in`, 'w'), ro = fs.openSync(`${work}/out`, 'r');
5264
6593
  return { child, wi, ro };
5265
6594
  }
5266
6595
  export function checkStep(h, read, r, sorts, opts) {
6596
+ return retried(() => checkStepOnce(h, read, r, sorts, opts), () => ({ ...noEvidence(), runMs: 0 }));
6597
+ }
6598
+ function checkStepOnce(h, read, r, sorts, opts) {
5267
6599
  const o = opts.check ?? {}, m = read.model, bound = o.bound ?? 12;
5268
6600
  const fs = node('node:fs'), os = node('node:os');
5269
6601
  const work = fs.mkdtempSync(`${os.tmpdir()}/gdp-stepcheck-`);
5270
6602
  let child, wi = -1, ro = -1;
5271
6603
  const empty = { runs: 0, requests: 0, fromStates: 0, probes: { conditions: 0, witnesses: 0, steps: 0 }, refusedBoth: 0, outside: 0, edge: 0, compiledAgreed: 0, coverage: { arms: 0, hit: 0, missed: [] }, ms: 0, runMs: 0 };
5272
6604
  try {
6605
+ // (no harness: no request ran, so never a difference: the check's own failure, or the code refused with why)
5273
6606
  if (h.error)
5274
- return { ...empty, mismatch: h.error };
6607
+ return h.kind === 'harness' ? { ...empty, harness: h.error } : { ...empty, source: h.error };
5275
6608
  ({ child, wi, ro } = openHarness(work, h.cmd, h.args, { stdio: ['ignore', 'ignore', 'inherit'], env: { ...proc?.env, ...h.env } }));
5276
6609
  const buf = new Uint8Array(1 << 20), dec = new TextDecoder();
5277
6610
  let pend = '';
@@ -5293,10 +6626,10 @@ export function checkStep(h, read, r, sorts, opts) {
5293
6626
  fs.writeSync(wi, `${JSON.stringify(cmd)}\n`);
5294
6627
  const l = line();
5295
6628
  if (l === undefined)
5296
- throw new Error('the harness stopped');
5297
- return JSON.parse(l);
6629
+ throw new HarnessFailure('the harness stopped before it answered');
6630
+ return stopped(JSON.parse(l));
5298
6631
  };
5299
- 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 } : {}) });
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 } : {}) });
5300
6633
  if (hi.error)
5301
6634
  return { ...empty, mismatch: `the code doesn't load with the check's harness: ${JSON.stringify(hi.error)}` };
5302
6635
  const num = (x, at) => { const n = Number(x); if (typeof x === 'string' && Number.isSafeInteger(n) && String(n) === x)
@@ -5312,7 +6645,7 @@ export function checkStep(h, read, r, sorts, opts) {
5312
6645
  };
5313
6646
  const j = (x) => (typeof x === 'number' ? String(x) : x);
5314
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)]))]))])) });
5315
- 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 }
5316
6649
  : a.k === 'list' ? { list: (inputs[a.name] ?? []).map(it => build(a.item, it)) } : { dflt: true });
5317
6650
  const ctorArgs = (params) => read.ctor.map(([n, a]) => [n, build(a, params)]);
5318
6651
  let now = 0, inputsNow = {};
@@ -5324,9 +6657,11 @@ export function checkStep(h, read, r, sorts, opts) {
5324
6657
  if (n < lo || n > hi)
5325
6658
  throw new Outside(`${a.key} answers ${String(v)}, outside its type`);
5326
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`);
5327
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)
5328
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;
5329
- 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] } : {}) }];
5330
6665
  }));
5331
6666
  let coverage;
5332
6667
  const r0 = performance.now();
@@ -5343,6 +6678,9 @@ export function checkStep(h, read, r, sorts, opts) {
5343
6678
  throw new Error(`the code changes ${res.frame}, a field the rule leaves out`);
5344
6679
  if (res.bad !== undefined)
5345
6680
  return { ok: false, error: `the code can't be given it (${res.bad})` };
6681
+ // (the harness failed making the call: no step of the code, neither a refusal nor one taken)
6682
+ if (res.error !== undefined)
6683
+ throw new HarnessFailure(`the harness failed on a call: ${String(res.error)}`);
5346
6684
  const kind = read.results[e.call] ?? 'none', failed = res.err !== undefined;
5347
6685
  if (failed && !read.kept)
5348
6686
  return { ok: false, error: `raised: ${res.err}` };
@@ -5369,6 +6707,8 @@ export function checkStep(h, read, r, sorts, opts) {
5369
6707
  }
5370
6708
  if (f === 'none')
5371
6709
  o.none = !failed && (out === null || out === undefined) && kind === 'maybe';
6710
+ if (f.startsWith('effect:'))
6711
+ o[f] = !!res.effects?.[f.slice(7)];
5372
6712
  }
5373
6713
  return { ok: true, value: o };
5374
6714
  },
@@ -5402,14 +6742,29 @@ export function checkStep(h, read, r, sorts, opts) {
5402
6742
  for (const f of jl ?? [])
5403
6743
  if (f.opt && cells[key][`${f.name}_has`] === false)
5404
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;
5405
6748
  }
5406
6749
  maps[d.name] = cells;
5407
6750
  }
5408
6751
  return { leaves, maps };
5409
6752
  },
5410
- normalize: s => { for (const l of read.leaves)
5411
- if (l.kind === 'none' && s.leaves[l.name] === true)
5412
- 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) } : {}),
5413
6768
  };
5414
6769
  function closeAndCount() {
5415
6770
  const res = ask({ op: 'coverage' });
@@ -5423,6 +6778,8 @@ export function checkStep(h, read, r, sorts, opts) {
5423
6778
  return { ...ev, runMs: Math.round(performance.now() - r0) };
5424
6779
  }
5425
6780
  catch (x) {
6781
+ if (x instanceof HarnessFailure)
6782
+ throw x;
5426
6783
  return { ...empty, mismatch: `the check's harness: ${x.message}` };
5427
6784
  }
5428
6785
  finally {
@@ -5453,11 +6810,55 @@ const g0 = (m, name) => { const v = m.state.find(x => x.name === name); return v
5453
6810
  // A front end's whole run: the module read, the model printed and built, the code run beside it.
5454
6811
  export function extractStep(mod, h, opts) {
5455
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 };
6819
+ // (an argument the code declares no type of, given one: `types`, by its name)
6820
+ for (const f of Object.values(mod.funcs))
6821
+ for (const pa of f.params) {
6822
+ const t = opts.types?.[pa.name];
6823
+ if (t && pa.t.k === 'any') {
6824
+ try {
6825
+ pa.t = sortOfText(t, f.p, mod.lang).t;
6826
+ notes.push(`${f.name}(${pa.name}): a ${t} (stated)`);
6827
+ }
6828
+ catch (e) {
6829
+ if (e instanceof Refusal)
6830
+ return { ok: false, refusals: [{ where: e.where, what: e.what }], notes };
6831
+ throw e;
6832
+ }
6833
+ }
6834
+ }
6835
+ // (and a field the class declares no type of: its declared type, by name)
6836
+ for (const r of Object.values(mod.recs))
6837
+ for (const [f, t] of Object.entries(opts.types ?? {})) {
6838
+ // (only a field its constructor sets: `self.<f> = ...`)
6839
+ const init = r.methods.__init__ ? mod.funcs[r.methods.__init__] : undefined;
6840
+ let sets = false;
6841
+ if (init)
6842
+ deep(init.body, st => { const to = st.to; if (st.s === 'set' && to?.e === 'get' && to.x.e === 'var' && to.x.n === 'self' && to.f === f)
6843
+ sets = true; });
6844
+ if (!r.own || r.fields.some(x => x.name === f) || !sets)
6845
+ continue;
6846
+ try {
6847
+ r.fields.push({ name: f, t: sortOfText(t, r.p, mod.lang).t });
6848
+ }
6849
+ catch (e) {
6850
+ if (e instanceof Refusal)
6851
+ return { ok: false, refusals: [{ where: e.where, what: e.what }], notes };
6852
+ throw e;
6853
+ }
6854
+ }
5456
6855
  let read;
5457
6856
  try {
5458
6857
  read = readStep(mod, opts);
5459
6858
  }
5460
6859
  catch (e) {
6860
+ if (e instanceof InitializerChoice)
6861
+ return { ok: false, refusals: [{ where: e.where, what: e.what }], notes, initializers: e.initializers };
5461
6862
  if (e instanceof Refusal)
5462
6863
  return { ok: false, refusals: [{ where: e.where, what: e.what }], notes };
5463
6864
  throw e;
@@ -5473,7 +6874,7 @@ export function stepNames(read) {
5473
6874
  for (const l of read.leaves) {
5474
6875
  const code = l.path.join('.');
5475
6876
  if (l.kind === 'map')
5476
- 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 } : {}) } });
5477
6878
  else if (l.kind === 'none') {
5478
6879
  const n = at(code);
5479
6880
  if (n)
@@ -5517,6 +6918,8 @@ export function stepNames(read) {
5517
6918
  out.push({ code: 'result', rule: `${method}_result`, role: 'result', method, ...(k === 'maybe' ? { none: `${method}_result_none` } : {}) });
5518
6919
  if (vars.has('failed'))
5519
6920
  out.push({ code: 'failed', rule: 'failed', role: 'failed' });
6921
+ for (const a of read.answers.filter(x => x.effect && !x.quiet))
6922
+ out.push({ code: `${a.key}.called`, rule: `${a.key.replace(/\W+/g, '_')}_called`, role: 'result' });
5520
6923
  if (vars.has('now'))
5521
6924
  out.push({ code: 'now', rule: 'now', role: 'clock' });
5522
6925
  if (m.event)