gdp-wired 0.45.0 → 0.47.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (126) hide show
  1. package/README.md +61 -8
  2. package/dist/core/bitsets.d.ts +2 -0
  3. package/dist/core/bitsets.js +23 -0
  4. package/dist/core/bmc.js +6 -2
  5. package/dist/core/c/reader.d.ts +9 -1
  6. package/dist/core/c/reader.js +423 -31
  7. package/dist/core/calendar.d.ts +29 -0
  8. package/dist/core/calendar.js +82 -0
  9. package/dist/core/cli.d.ts +4 -0
  10. package/dist/core/cli.js +206 -40
  11. package/dist/core/compose.js +3 -1
  12. package/dist/core/counts.d.ts +4 -1
  13. package/dist/core/counts.js +314 -85
  14. package/dist/core/cycles.js +8 -1
  15. package/dist/core/cyclic.d.ts +1 -0
  16. package/dist/core/cyclic.js +13 -7
  17. package/dist/core/data-synth.d.ts +3 -0
  18. package/dist/core/data-synth.js +252 -0
  19. package/dist/core/data.d.ts +2 -1
  20. package/dist/core/data.js +223 -24
  21. package/dist/core/discover.js +3 -1
  22. package/dist/core/draft.d.ts +19 -0
  23. package/dist/core/draft.js +53 -0
  24. package/dist/core/dsl.d.ts +37 -3
  25. package/dist/core/dsl.js +167 -26
  26. package/dist/core/effect-schema.d.ts +90 -0
  27. package/dist/core/effect-schema.js +500 -0
  28. package/dist/core/effect.d.ts +4 -11
  29. package/dist/core/effect.js +3 -79
  30. package/dist/core/exists.d.ts +1 -0
  31. package/dist/core/exists.js +191 -16
  32. package/dist/core/extract-c.d.ts +2 -0
  33. package/dist/core/extract-c.js +169 -22
  34. package/dist/core/extract-check.d.ts +1 -0
  35. package/dist/core/extract-check.js +97 -6
  36. package/dist/core/extract-go-check.d.ts +1 -1
  37. package/dist/core/extract-go-check.js +26 -5
  38. package/dist/core/extract-go.d.ts +8 -0
  39. package/dist/core/extract-go.js +67 -6
  40. package/dist/core/extract-ir.d.ts +1 -0
  41. package/dist/core/extract-ir.js +15 -0
  42. package/dist/core/extract-jvm.d.ts +1 -1
  43. package/dist/core/extract-jvm.js +2 -0
  44. package/dist/core/extract-orm.d.ts +12 -0
  45. package/dist/core/extract-orm.js +244 -0
  46. package/dist/core/extract-print.js +20 -1
  47. package/dist/core/extract-py.d.ts +1 -0
  48. package/dist/core/extract-py.js +1 -1
  49. package/dist/core/extract-read.d.ts +26 -1
  50. package/dist/core/extract-read.js +14 -7
  51. package/dist/core/extract-rs.js +63 -15
  52. package/dist/core/extract-shapes.d.ts +1 -0
  53. package/dist/core/extract-shapes.js +84 -0
  54. package/dist/core/extract-sol.d.ts +10 -1
  55. package/dist/core/extract-sol.js +70 -22
  56. package/dist/core/extract-standalone.d.ts +3 -0
  57. package/dist/core/extract-standalone.js +221 -0
  58. package/dist/core/extract-step.d.ts +151 -1
  59. package/dist/core/extract-step.js +1232 -60
  60. package/dist/core/extract-swift.js +6 -2
  61. package/dist/core/extract.d.ts +9 -0
  62. package/dist/core/extract.js +77 -7
  63. package/dist/core/fiber-run.d.ts +5 -0
  64. package/dist/core/fiber-run.js +18 -0
  65. package/dist/core/infer.d.ts +4 -1
  66. package/dist/core/infer.js +918 -217
  67. package/dist/core/jvm/JavaReader.java +23 -6
  68. package/dist/core/jvm/Jvm.java +3 -0
  69. package/dist/core/jvm/KtReader.java +6 -5
  70. package/dist/core/laws.d.ts +10 -3
  71. package/dist/core/laws.js +226 -23
  72. package/dist/core/machine.d.ts +15 -1
  73. package/dist/core/machine.js +187 -15
  74. package/dist/core/nonterm.js +14 -1
  75. package/dist/core/orm/harness.js +61 -0
  76. package/dist/core/orm-fixtures/schema.prisma +5 -0
  77. package/dist/core/py/harness.py +183 -10
  78. package/dist/core/py/reader.py +234 -40
  79. package/dist/core/reader-fixtures/README.md +28 -0
  80. package/dist/core/reader-fixtures/c-693042.cpp +8 -0
  81. package/dist/core/reader-fixtures/go-685506.go +14 -0
  82. package/dist/core/reader-fixtures/jvm-724362.kt +8 -0
  83. package/dist/core/reader-fixtures/jvm-737430.kt +7 -0
  84. package/dist/core/reader-fixtures/jvm-765282.kt +3 -0
  85. package/dist/core/reader-fixtures/swift-735726.swift +15 -0
  86. package/dist/core/reader-fixtures/swift-735990.swift +15 -0
  87. package/dist/core/reader-fixtures/swift-739158.swift +4 -0
  88. package/dist/core/reader-fixtures/swift-744834.swift +15 -0
  89. package/dist/core/reader-fixtures/swift-746946.swift +31 -0
  90. package/dist/core/reader-fixtures/typescript-673062.ts.txt +2 -0
  91. package/dist/core/relation.d.ts +1 -1
  92. package/dist/core/relation.js +29 -2
  93. package/dist/core/relational.js +4 -2
  94. package/dist/core/rs/Cargo.toml +1 -1
  95. package/dist/core/rs/src/main.rs +466 -11
  96. package/dist/core/sample-cache.d.ts +8 -0
  97. package/dist/core/sample-cache.js +46 -0
  98. package/dist/core/security.d.ts +38 -0
  99. package/dist/core/security.js +88 -0
  100. package/dist/core/sol/harness.py +57 -4
  101. package/dist/core/sol-concrete.d.ts +23 -0
  102. package/dist/core/sol-concrete.js +195 -0
  103. package/dist/core/solver.js +3 -1
  104. package/dist/core/swift/Sources/gdp-swiftreader/main.swift +50 -7
  105. package/dist/core/system.js +1 -1
  106. package/dist/core/transfer.js +22 -9
  107. package/dist/core/translate.js +39 -10
  108. package/dist/core/watch.js +50 -5
  109. package/dist/interchange/format.js +11 -1
  110. package/dist/kernel/cdcl.d.ts +5 -0
  111. package/dist/kernel/cdcl.js +56 -9
  112. package/dist/kernel/epr.js +108 -26
  113. package/dist/kernel/kernel.d.ts +29 -1
  114. package/dist/kernel/kernel.js +325 -62
  115. package/dist/kernel/model-sequence.d.ts +3 -0
  116. package/dist/kernel/model-sequence.js +34 -0
  117. package/dist/kernel/prove.d.ts +10 -3
  118. package/dist/kernel/prove.js +332 -71
  119. package/dist/kernel/reader.d.ts +3 -0
  120. package/dist/kernel/reader.js +101 -14
  121. package/dist/kernel/share.d.ts +1 -0
  122. package/dist/kernel/share.js +27 -0
  123. package/dist/lean-kernel/emit.js +30 -37
  124. package/dist/lean-kernel/lean-terms.js +5 -0
  125. package/dist/lean-kernel/library.js +10 -10
  126. package/package.json +6 -1
@@ -29,8 +29,23 @@ import { Refusal, pathOf } from "./extract-read.js";
29
29
  import { buildCheck, builtEvidence, compileLimit, stubbed } from "./extract-step.js";
30
30
  import { goNames, readGo, unsignedDomains } from "./extract-go.js";
31
31
  import { speak } from "./extract-go-check.js";
32
- import { clangDump, flagsFor, node, readC } from "./c/reader.js";
32
+ import { clangDump, constantsOf, flagsFor, node, readC } from "./c/reader.js";
33
33
  export { proveRule, proveSteps } from "./dsl.js";
34
+ // (C++ that includes little, embedded code's without the standard library: its whole dump is small, read whole; else
35
+ // only the class's, its headers' being hundreds of MB)
36
+ const smallTUs = new Map();
37
+ function smallTU(file, flags, clang) {
38
+ const k = `${clang} ${flags.join(' ')} ${file}`;
39
+ if (!smallTUs.has(k)) {
40
+ try {
41
+ smallTUs.set(k, node('node:child_process').execFileSync(clang, ['-x', 'c++', ...flags, '-E', '-P', file], { encoding: 'utf8', maxBuffer: 1 << 26, stdio: ['ignore', 'pipe', 'ignore'] }).length < 400_000);
42
+ }
43
+ catch {
44
+ smallTUs.set(k, false);
45
+ }
46
+ }
47
+ return smallTUs.get(k);
48
+ }
34
49
  export function readCFile(file, opts, cpp = false) {
35
50
  // (no entry, C++: each class the file declares tried, its dump read for its name only)
36
51
  if (!opts.entry && cpp) {
@@ -58,10 +73,51 @@ export function readCFile(file, opts, cpp = false) {
58
73
  throw new Refusal(file, ok.length ? `several classes write their state (${ok.map(r => r.c.entry).join(', ')}): name one (entry)` : `no class whose methods write its state${why.length ? ` (${why.join('; ')})` : ''}: name the entry`);
59
74
  return ok[0];
60
75
  }
61
- const flags0 = [...flagsFor(file, opts.compileCommands), ...(opts.flags ?? [])], flags = cpp && !flags0.some(f => f.startsWith('-std=')) ? [...flags0, '-std=c++17'] : flags0, { tu, target } = clangDump(file, flags, opts.clang ?? (cpp ? 'clang++' : 'clang'), cpp, cpp ? opts.entry : undefined);
76
+ const flags0 = [...flagsFor(file, opts.compileCommands), ...(opts.flags ?? [])], flags = cpp && !flags0.some(f => f.startsWith('-std=')) ? [...flags0, '-std=c++17'] : flags0, { tu, target } = clangDump(file, flags, opts.clang ?? (cpp ? 'clang++' : 'clang'), cpp, cpp && !smallTU(file, flags, opts.clang ?? 'clang++') ? opts.entry : undefined);
77
+ // (C++, its dump filtered to the class: each variable outside it the class reads, a namespace's constant, dumped too)
78
+ if (cpp && opts.entry && !smallTU(file, flags, opts.clang ?? 'clang++')) {
79
+ const have = new Set(), want = new Map();
80
+ const walk = (n) => { if (n.kind === 'VarDecl' && n.id)
81
+ have.add(n.id); const d = n.referencedDecl; if (n.kind === 'DeclRefExpr' && d?.kind === 'VarDecl')
82
+ want.set(d.id, d.name); for (const c of n.inner ?? [])
83
+ walk(c); };
84
+ walk(tu);
85
+ // (and each struct a method takes by reference or pointer, the caller's object: its fields read as inputs)
86
+ const recs = new Set(), haveRec = new Set();
87
+ const walkP = (n) => { if (/Record/.test(n.kind) && n.name)
88
+ haveRec.add(n.name); if (n.kind === 'ParmVarDecl' && n.type) {
89
+ const b = n.type.qualType.replace(/\b(const|volatile|struct|class)\b|[&*]/g, '').trim();
90
+ if (/^[A-Za-z_]\w*$/.test(b))
91
+ recs.add(b);
92
+ } for (const c of n.inner ?? [])
93
+ walkP(c); };
94
+ walkP(tu);
95
+ for (const name of [...recs].filter(r => !haveRec.has(r))) {
96
+ try {
97
+ const more = clangDump(file, flags, opts.clang ?? 'clang++', cpp, name).tu.inner ?? [];
98
+ tu.inner = [...(tu.inner ?? []), ...more.filter(m => /^(CXX)?RecordDecl$/.test(m.kind) && m.name === name && m.completeDefinition)];
99
+ }
100
+ catch { /* read where it is, as before */ }
101
+ }
102
+ for (const name of new Set([...want].filter(([id]) => !have.has(id)).map(([, n]) => n))) {
103
+ try {
104
+ const more = clangDump(file, flags, opts.clang ?? 'clang++', cpp, name).tu.inner ?? [];
105
+ const ids = [...want].filter(([id, n]) => n === name && !have.has(id)).map(([id]) => id);
106
+ for (const m of more)
107
+ if (m.kind === 'VarDecl' && m.name === name)
108
+ for (const id of ids)
109
+ tu.inner = [...(tu.inner ?? []), { ...m, id }];
110
+ }
111
+ catch { /* read where it is, as before */ }
112
+ }
113
+ }
62
114
  // (no entry: the file's one struct its functions write, each struct of the dump tried)
63
115
  if (!opts.entry) {
64
- const names = [...new Set((tu.inner ?? []).filter(n => n.kind === 'RecordDecl' && n.name && n.completeDefinition).map(n => String(n.name)))];
116
+ // (each struct by its tag or a typedef's name, an unnamed one's typedef too, that a function of the file takes a
117
+ // pointer to first)
118
+ const firsts = new Set((tu.inner ?? []).filter(n => n.kind === 'FunctionDecl' && n.inner?.some(c => c.kind === 'CompoundStmt')).map(n => n.inner.find(c => c.kind === 'ParmVarDecl')?.type?.qualType.replace(/\b(const|volatile|struct)\b|\*/g, '').trim()).filter((t) => !!t));
119
+ const typedefNames = (tu.inner ?? []).filter(n => n.kind === 'TypedefDecl' && (n.inner ?? []).some(c => /Record|Elaborated/.test(c.kind))).map(n => String(n.name));
120
+ const names = [...new Set([...(tu.inner ?? []).filter(n => n.kind === 'RecordDecl' && n.name && n.completeDefinition).map(n => String(n.name)), ...typedefNames])].filter(n => firsts.has(n));
65
121
  const ok = names.filter(n => { try {
66
122
  const c = readC(file, n, tu, target, cpp, opts.root);
67
123
  readGo(c.pkg, { methods: c.methods });
@@ -72,11 +128,27 @@ export function readCFile(file, opts, cpp = false) {
72
128
  return false;
73
129
  throw e;
74
130
  } });
131
+ // (none: the file's globals, where its functions keep the state there)
132
+ if (!ok.length && !cpp) {
133
+ const stem = file.replace(/^.*\//, '').replace(/\.[^.]*$/, '');
134
+ try {
135
+ const r = readCFile(file, { ...opts, entry: stem }, cpp);
136
+ readGo(r.c.pkg, { methods: r.c.methods, ...(opts.onError ? { onError: opts.onError } : {}) });
137
+ return r;
138
+ }
139
+ catch (e) {
140
+ if (!(e instanceof Refusal))
141
+ throw e;
142
+ // (its globals are its state, and something in them is refused: that, not the structs)
143
+ if (!/^no global of /.test(e.what))
144
+ throw new Refusal(e.where, `${e.what} (the file's globals read as its state, ${stem}: no struct its functions write)`);
145
+ }
146
+ }
75
147
  if (ok.length !== 1)
76
148
  throw new Refusal(file, ok.length ? `several structs written by the file's functions (${ok.join(', ')}): name one (entry)` : 'no struct the file\'s functions write: name the entry');
77
149
  return readCFile(file, { ...opts, entry: ok[0] }, cpp);
78
150
  }
79
- return { c: readC(file, opts.entry, tu, target, cpp, opts.root, Object.fromEntries((opts.functions ?? []).filter(f => f.includes('/')).map(f => [f.split('/')[0], Number(f.split('/')[1])]))), flags };
151
+ return { c: readC(file, opts.entry, tu, target, cpp, opts.root, Object.fromEntries((opts.functions ?? []).filter(f => f.includes('/')).map(f => [f.split('/')[0], Number(f.split('/')[1])])), (opts.functions ?? opts.methods ?? []).map(f => f.split('/')[0]), opts.leave ?? [], [...Object.keys(opts.answers ?? {}), ...(opts.cut ?? [])]), flags };
80
152
  }
81
153
  export function extractC(at, given = {}, cpp = false) {
82
154
  const notes = [], file = pathOf(at), fns = given.methods ?? given.functions, opts = { ...given, ...(fns ? { functions: fns } : {}) };
@@ -98,8 +170,12 @@ export function extractC(at, given = {}, cpp = false) {
98
170
  read.model.laws = read.model.laws?.map(l => (l.includes(`"${n} within its type's range"`) ? l.replace(/\.atLeast\(-\d+\)/, '.atLeast(0)') : l));
99
171
  if (!opts.entry)
100
172
  read.model.notes.unshift(`the entry inferred: ${c.entry}, ${cpp ? 'the class whose methods write its state' : 'the struct the file\'s functions write'}`);
173
+ // (the names the laws read that the code defines as constants: its enum constants, else clang's value of each)
174
+ // (a qualified one, C++'s vehicle_status_s::ARMING_STATE_ARMED, by its law's spelling, vehicle_status_s.ARMING_STATE_ARMED)
175
+ const keep = (given.keep ?? []).filter(n => !(n in c.consts)), found = keep.length ? constantsOf(file, flags, opts.clang ?? (cpp ? 'clang++' : 'clang'), cpp, keep) : {};
176
+ const consts = { ...c.consts, ...Object.fromEntries(Object.entries(found).map(([k, v]) => [k.replaceAll('::', '.'), v])) };
101
177
  const x = fromModel(read.model, `${c.entry}.${cpp ? 'cpp' : 'c'}`, { ...unsignedDomains(read), ...signedDomains(c.pkg, read), ...opts.domains }, notes, (rule, sorts) => checkC(file, flags, c, read, rule, sorts, opts, cpp));
102
- return { ...x, leaves: read.leaves, names: goNames(read) };
178
+ return { ...x, leaves: read.leaves, names: goNames(read), ...(Object.keys(consts).length ? { consts } : {}) };
103
179
  }
104
180
  // A signed field (and a signed result) is an integer, never inferred a natural: its range law reads below 0.
105
181
  function signedDomains(pkg, read) {
@@ -127,8 +203,9 @@ export function harnessC(file, c, read, opts, cpp) {
127
203
  const pkg = c.pkg, T = (t) => ty(pkg, t), q = JSON.stringify, robs = [];
128
204
  // A leaf's place: o->a.b in C; in C++ each member through a pointer to it the explicit instantiation of gdp_rob takes
129
205
  // (access isn't checked there), so private members are read and set as the class's own code does.
206
+ const G = c.globals;
130
207
  const acc = (path) => {
131
- if (!cpp)
208
+ if (!cpp || G)
132
209
  return `o->${path.join('.')}`;
133
210
  let e = '(*o)', t = pkg.types[0].t;
134
211
  for (const f of path) {
@@ -158,20 +235,28 @@ export function harnessC(file, c, read, opts, cpp) {
158
235
  }
159
236
  else if (l.kind === 'bool') {
160
237
  get.push(`gdp_putf("%s\\"%s\\":%s", sep, ${k}, ${a} ? "true" : "false"); sep = ",";`);
161
- set.push(`if ((v = gdp_key(st, ${k}))) { if (!strncmp(v, "true", 4)) ${a} = 1; else if (!strncmp(v, "false", 5)) ${a} = 0; else return "${l.name}: not a boolean"; }`);
238
+ set.push(`if ((v = gdp_key(st, ${k}))) { if (!strncmp(v, "true", 4)) ${a} = ${T(l.t).nullflag ? '(void *)1' : '1'}; else if (!strncmp(v, "false", 5)) ${a} = 0; else return "${l.name}: not a boolean"; }`);
162
239
  }
163
240
  }
164
241
  const frames = read.leaves.filter(l => l.kind === 'frame' && !T(l.t).mutex);
242
+ // (a field left out that points to an object other code owns, a buffer: a zeroed one of its own, as the code's setup
243
+ // would give)
244
+ const et = T(pkg.types[0].t), leftPtrs = cpp || G ? [] : (opts.leave ?? []).filter(f => { const fd = et.fields?.find(g => g.name === f); return fd && T(fd.t).k === 'ptr' && ['struct', 'int', 'bool'].includes(T(T(fd.t).elem).k); });
165
245
  // (the longest method name the request names, in UTF-8 bytes, its buffer: a name of any length is called)
166
246
  const M = Math.max(256, ...read.methods.map(x => new TextEncoder().encode(x.name).length + 1));
167
247
  const calls = read.methods.map(meth => {
168
- const lines = [], args = ['o'], outs = [];
248
+ const lines = [], args = ['o'], outs = [], given = [];
169
249
  meth.params.forEach((pa, i) => {
250
+ // (a global the request gives: set before the call, not passed)
251
+ const push = (a) => { if (G?.inputs.includes(pa.name) && i >= meth.params.length - G.inputs.filter(n => meth.params.some(q => q.name === n)).length)
252
+ given.push([pa.name, a]);
253
+ else
254
+ args.push(a); };
170
255
  const t = T(pa.t), raw = `gdp_idx(a, ${i})`;
171
256
  if (pa.arg.k === 'input') {
172
257
  lines.push(`${t.go} a${i}; memset(&a${i}, 0, sizeof a${i}); const char *r${i} = ${raw}; if (!r${i}) return "no argument ${i}";`);
173
258
  lines.push(t.k === 'int' ? intIn(`a${i}`, `r${i}`, pa.t, `return "argument ${i} outside its type"`) : `a${i} = !strncmp(r${i}, "true", 4);`);
174
- args.push(`a${i}`);
259
+ push(`a${i}`);
175
260
  }
176
261
  else if (pa.arg.k === 'rec' && t.k === 'ptr' && T(t.elem).box) {
177
262
  // (an out-parameter: a local of its type, its address given, what is left in it reported)
@@ -187,25 +272,26 @@ export function harnessC(file, c, read, opts, cpp) {
187
272
  const ft = st.fields.find(g => g.name === f).t;
188
273
  lines.push(`if ((v = gdp_key(r${i}, ${q(f)}))) ${T(ft).k === 'int' ? intIn(`a${i}.${f}`, 'v', ft, `return "argument ${i}.${f} outside its type"`) : `a${i}.${f} = !strncmp(v, "true", 4);`}`);
189
274
  }
190
- args.push(byValue ? `a${i}` : `&a${i}`);
275
+ push(byValue || t.go?.trim().endsWith('&') ? `a${i}` : `&a${i}`);
191
276
  }
192
277
  else
193
278
  lines.push(`return "an argument the harness can't make";`);
194
279
  });
195
280
  const rt = meth.results[0], fails = opts.fails?.[meth.name]?.trim();
196
- const callee = cpp ? `o->${meth.name}(${args.slice(1).join(', ')})` : `${meth.name}(${args.join(', ')})`;
281
+ const callee = G ? `${meth.name}(${args.slice(1).join(', ')})` : cpp ? `o->${meth.name}(${args.slice(1).join(', ')})` : `${meth.name}(${args.join(', ')})`;
197
282
  const invoke = rt === undefined ? `${callee};` : `${cpp ? 'auto' : T(rt).go} r0 = ${callee}; gdp_has = 1; ${T(rt).k === 'int' ? `gdp_outv = ${T(rt).signed === false ? '(long long)' : ''}r0; gdp_outu = ${T(rt).signed === false ? 1 : 0};` : 'gdp_outb = r0; gdp_isb = 1;'}`;
198
283
  const failed = fails !== undefined && rt !== undefined ? `if (r0 ${fails.replace(/^(==|!=|<=|>=|<|>)\s*/, '$1 ')}) gdp_err = 1;` : '';
199
284
  // (with out-parameters, the result is a record: the value returned and what each holds)
200
285
  const rec = outs.length ? `gdp_rec = 1; gdp_putf(",\\"out\\":{"); ${[...(rt !== undefined ? [['result', 'r0', rt]] : []), ...outs].map(([n, v, et], j) => `gdp_putf("${j ? ',' : ''}\\"${n}\\":"); ${T(et).k === 'int' ? `gdp_putf(${T(et).signed === false ? '"%llu", (unsigned long long)' : '"%lld", (long long)'}(${v}))` : `gdp_putf("%s", ${v} ? "true" : "false")`};`).join(' ')} gdp_putf("},\\"hasOut\\":true");` : '';
201
- return `if (!strcmp(m, ${q(meth.name)})) {\n ${lines.join('\n ')}\n memcpy(gdp_pre, (void *)o, sizeof(gdp_T));\n int sg = sigsetjmp(gdp_jb, 1);\n if (!sg) { gdp_armed = 1; ${cpp ? 'try { ' : ''}${invoke} ${failed} gdp_armed = 0; ${rec}${cpp ? ' } catch (...) { gdp_armed = 0; gdp_sig = SIGUSR2; }' : ''} } else gdp_sig = sg;\n return gdp_after(o);\n }`;
286
+ const load = G ? `gdp_load(o); ${given.map(([n, a]) => `memcpy((void *)&${n}, (const void *)&${a}, sizeof ${n});`).join(' ')}\n ` : '';
287
+ return `if (!strcmp(m, ${q(meth.name)})) {\n ${lines.join('\n ')}\n memcpy(gdp_pre, (void *)o, sizeof(gdp_T));\n ${load}int sg = sigsetjmp(gdp_jb, 1);\n if (!sg) { gdp_armed = 1; gdp_watch(1); ${cpp ? 'try { ' : ''}${invoke} ${failed} gdp_watch(0); gdp_armed = 0; ${rec}${cpp ? ' } catch (...) { gdp_watch(0); gdp_armed = 0; gdp_sig = SIGUSR2; }' : ''} } else { gdp_watch(0); gdp_sig = sg; }\n ${G ? 'gdp_store(o);\n ' : ''}return gdp_after(o);\n }`;
202
288
  });
203
289
  const frameLines = frames.map(l => { const e = acc(l.path); return `if (memcmp((char *)&${e}, (char *)gdp_pre + ((char *)&${e} - (char *)o), sizeof ${e})) return ${q(l.path.join('.'))};`; });
204
290
  // The object, made as the code makes it: C's zeroed; C++'s constructed (in zeroed memory) with the rule's parameters.
205
291
  const cps = read.ctor ?? [], make = `static gdp_T *gdp_make(const char *line, const char **bad) {
206
292
  const char *a = gdp_key(line, "a"), *v; (void)a; (void)v;
207
- ${cps.map((pa, i) => `${T(pa.t).go} c${i} = 0; if (!(v = a ? gdp_idx(a, ${i}) : 0)) { *bad = "no argument ${i}"; return 0; } ${T(pa.t).k === 'int' ? intIn(`c${i}`, 'v', pa.t, `{ *bad = "argument ${i} outside its type"; return 0; }`) : `c${i} = !strncmp(v, "true", 4);`}`).join('\n ')}
208
- void *mem = calloc(1, sizeof(gdp_T));
293
+ ${cps.map((pa, i) => `${T(pa.t).go} c${i}${cpp ? '{}' : ' = 0'}; if (!(v = a ? gdp_idx(a, ${i}) : 0)) { *bad = "no argument ${i}"; return 0; } ${T(pa.t).k === 'int' ? intIn(`c${i}`, 'v', pa.t, `{ *bad = "argument ${i} outside its type"; return 0; }`) : `c${i} = !strncmp(v, "true", 4);`}`).join('\n ')}
294
+ void *mem = calloc(1, sizeof(gdp_T));${G ? '\n memcpy(mem, &gdp_init, sizeof(gdp_T));' : ''}${leftPtrs.map(f => `\n ((gdp_T *)mem)->${f} = calloc(1, sizeof *((gdp_T *)mem)->${f});`).join('')}
209
295
  return ${cpp ? `new (mem) gdp_T(${cps.map((_, i) => `c${i}`).join(', ')})` : '(gdp_T *)mem'};
210
296
  }`;
211
297
  return `// Generated by gdp-wired's ${cpp ? 'C++' : 'C'} check (core/extract-c.ts): the file's code is called as it is.
@@ -230,8 +316,15 @@ static long long gdp_answer(const char *name) {
230
316
  #include <signal.h>
231
317
  #include <setjmp.h>
232
318
  #include <errno.h>
319
+ #include <sys/time.h>
233
320
  ${cpp ? '#include <new>\n#include <type_traits>\n' : '#include <stdbool.h>\n'}
234
- typedef ${c.cname} gdp_T;
321
+ ${G ? `// The file's globals, the state: an object of them each request loads, and stores back after it.
322
+ ${G.externs.map(n => `__typeof__(${n}) ${n};`).join('\n')}
323
+ typedef struct { ${G.state.map(n => `${cpp ? `std::remove_cv_t<decltype(${n})>` : `__typeof__(${n})`} ${n};`).join(' ')} } gdp_G;
324
+ static void gdp_load(const gdp_G *o) { ${G.state.map(n => `memcpy((void *)&${n}, (const void *)&o->${n}, sizeof ${n});`).join(' ')} }
325
+ static void gdp_store(gdp_G *o) { ${G.state.map(n => `memcpy((void *)&o->${n}, (const void *)&${n}, sizeof ${n});`).join(' ')} }
326
+ static gdp_G gdp_init;
327
+ ` : ''}typedef ${c.cname} gdp_T;
235
328
  static unsigned char gdp_pre[sizeof(gdp_T)];
236
329
  ${robs.length ? `template <typename Tag, auto M> struct gdp_rob { friend auto gdp_ptr(Tag) { return M; } };\n${robs.map((k, i) => `struct gdp_tag${i} { friend auto gdp_ptr(gdp_tag${i}); };\ntemplate struct gdp_rob<gdp_tag${i}, ${k}>;`).join('\n')}` : ''}
237
330
  static char *gdp_buf; static size_t gdp_n, gdp_cap;
@@ -287,6 +380,8 @@ static const char *gdp_set(gdp_T *o, const char *st) {
287
380
  static sigjmp_buf gdp_jb; static volatile sig_atomic_t gdp_armed;
288
381
  static int gdp_sig, gdp_err, gdp_has, gdp_outu, gdp_isb, gdp_rec; static long long gdp_outv; static bool gdp_outb;
289
382
  static void gdp_on(int s) { if (gdp_armed) { gdp_armed = 0; siglongjmp(gdp_jb, s); } signal(s, SIG_DFL); raise(s); }
383
+ // (a call that doesn't return within 2 s, an endless loop: the code's failure, as the rule's)
384
+ static void gdp_watch(int on) { struct itimerval t; memset(&t, 0, sizeof t); t.it_value.tv_sec = on ? 2 : 0; setitimer(ITIMER_REAL, &t, 0); }
290
385
  static const char *gdp_frame(gdp_T *o) {
291
386
  (void)o;
292
387
  ${frameLines.join('\n ')}
@@ -298,7 +393,7 @@ ${cpp ? 'extern "C" ' : ''}void gdp_extern_called(const char *n) { gdp_extern =
298
393
  static const char *gdp_after(gdp_T *o) {
299
394
  const char *f = gdp_frame(o);
300
395
  if (f) { gdp_putf(",\\"frame\\":\\"%s\\"", f); }
301
- if (gdp_sig) gdp_putf(",\\"panic\\":\\"%s\\"", gdp_sig == SIGABRT ? "SIGABRT (abort, or an assertion failing)" : gdp_sig == SIGTRAP || gdp_sig == SIGILL ? "undefined behavior (the sanitizer's trap)" : gdp_sig == SIGUSR1 ? "another file's function called" : gdp_sig == SIGUSR2 ? "an exception thrown" : "a signal");
396
+ if (gdp_sig) gdp_putf(",\\"panic\\":\\"%s\\"", gdp_sig == SIGABRT ? "SIGABRT (abort, or an assertion failing)" : gdp_sig == SIGTRAP || gdp_sig == SIGILL ? "undefined behavior (the sanitizer's trap)" : gdp_sig == SIGUSR1 ? "another file's function called" : gdp_sig == SIGUSR2 ? "an exception thrown" : gdp_sig == SIGALRM ? "the code didn't return (an endless loop)" : "a signal");
302
397
  else if (gdp_err) gdp_putf(",\\"err\\":\\"its result is its failure (%lld)\\"", gdp_outv);
303
398
  if (!gdp_sig && gdp_has && !gdp_rec) { if (gdp_isb) gdp_putf(",\\"out\\":%s,\\"hasOut\\":true", gdp_outb ? "true" : "false"); else if (gdp_outu) gdp_putf(",\\"out\\":\\"%llu\\",\\"hasOut\\":true", (unsigned long long)gdp_outv); else gdp_putf(",\\"out\\":\\"%lld\\",\\"hasOut\\":true", gdp_outv); }
304
399
  if (${opts.onError === 'discard' ? 1 : 0} && (gdp_sig || gdp_err)) memcpy((void *)o, gdp_pre, sizeof(gdp_T));
@@ -313,11 +408,11 @@ static const char *gdp_call(gdp_T *o, const char *m, const char *a) {
313
408
  return "no such function";
314
409
  }
315
410
  int main(int argc, char **argv) {
316
- if (argc == 2 && !strcmp(argv[1], "--probe")) return 0;
411
+ ${G ? 'gdp_store(&gdp_init);\n ' : ''}if (argc == 2 && !strcmp(argv[1], "--probe")) return 0;
317
412
  if (argc < 3) return 2;
318
413
  FILE *in = fopen(argv[1], "r"), *out = fopen(argv[2], "w");
319
414
  if (!in || !out) return 2;
320
- int sigs[] = {SIGABRT, SIGTRAP, SIGILL, SIGFPE, SIGSEGV, SIGBUS};
415
+ int sigs[] = {SIGABRT, SIGTRAP, SIGILL, SIGFPE, SIGSEGV, SIGBUS, SIGALRM};
321
416
  for (unsigned i = 0; i < sizeof sigs / sizeof *sigs; i++) signal(sigs[i], gdp_on);
322
417
  gdp_T **objs = 0; size_t nobj = 0;
323
418
  char *line = 0; size_t lcap = 0;
@@ -367,6 +462,34 @@ function strictFlex(clang) {
367
462
  }
368
463
  return flexOK.get(clang) ? ['-fstrict-flex-arrays=3'] : [];
369
464
  }
465
+ // A demangled C++ function's own name: `void events::send<A, B>(unsigned int, ...)` is send, `A::f(int) const` f.
466
+ function shortName(d) {
467
+ let depth = 0, end = -1;
468
+ for (let i = 0; i < d.length; i++) {
469
+ const ch = d[i];
470
+ if (ch === '<')
471
+ depth++;
472
+ else if (ch === '>')
473
+ depth--;
474
+ else if (ch === '(' && depth === 0) {
475
+ end = i;
476
+ break;
477
+ }
478
+ }
479
+ if (end < 0)
480
+ return undefined;
481
+ let head = d.slice(0, end), out = '', dd = 0;
482
+ for (const ch of head) {
483
+ if (ch === '<')
484
+ dd++;
485
+ else if (ch === '>')
486
+ dd--;
487
+ else if (dd === 0)
488
+ out += ch;
489
+ }
490
+ head = out.trim().split(/\s+/).pop() ?? '';
491
+ return head.split('::').pop() || undefined;
492
+ }
370
493
  // --- the check ------------------------------------------------------------------------------------------------------------
371
494
  export function checkC(file, flags, c, read, r, sorts, opts, cpp) {
372
495
  const fs = node('node:fs'), cp = node('node:child_process'), os = node('node:os'), path = node('node:path');
@@ -391,7 +514,10 @@ export function checkC(file, flags, c, read, r, sorts, opts, cpp) {
391
514
  // code's failure where the rule took the step, a difference), but those left out (skip, stated or inferred: they
392
515
  // change nothing the rule keeps, and nothing reads their value), which do nothing.
393
516
  const clang = opts.clang ?? (cpp ? 'clang++' : 'clang'), stubs = `${work}/gdp_stubs.c`;
394
- const link = (more) => cp.execFileSync(clang, [...(cpp ? ['-x', 'c++'] : []), ...flags, '-w', '-O0', '-fsanitize=undefined', '-fsanitize-trap=undefined', '-fno-sanitize=vptr,function', ...strictFlex(clang), h, ...(more.length ? ['-x', 'c', ...more] : []), '-o', `${work}/harness`,], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 1 << 26, timeout: compileLimit(), killSignal: 'SIGKILL' });
517
+ const run = (cc, args) => cp.execFileSync(cc, args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 1 << 26, timeout: compileLimit(), killSignal: 'SIGKILL' });
518
+ // (the stubs are C, compiled apart: the project's flags, a C++ -std among them, are the harness's)
519
+ const link = (more) => { for (const m of more)
520
+ run(clang.replace(/\+\+$/, ''), ['-w', '-c', '-x', 'c', m, '-o', `${m}.o`]); return run(clang, [...(cpp ? ['-x', 'c++'] : []), ...flags, '-w', '-O0', '-fsanitize=undefined', '-fsanitize-trap=undefined', '-fno-sanitize=vptr,function', ...strictFlex(clang), h, ...(more.length ? ['-x', 'none', ...more.map(m => `${m}.o`)] : []), '-o', `${work}/harness`]); };
395
521
  const why = (x) => String(x.stderr ?? x.message);
396
522
  // (the compiler's errors: where they are in the code's own files, the source's; the linker's alone say nothing of it)
397
523
  const base = path.resolve(file).split('/').pop(), errorsOf = (x) => why(x).split('\n').filter(l => /\berror:/.test(l) && !/linker command failed|ld returned/.test(l));
@@ -400,15 +526,36 @@ export function checkC(file, flags, c, read, r, sorts, opts, cpp) {
400
526
  link([]);
401
527
  }
402
528
  catch (x) {
403
- const names = [...new Set([...why(x).matchAll(/undefined (?:reference to [`']|symbol: )_?([A-Za-z_]\w*)|"_([A-Za-z_]\w*)", referenced from/g)].map(m => m[1] ?? m[2]))];
529
+ // (C's names: a C++ one is demangled, `A::f(int)`, below)
530
+ const names = [...new Set([...why(x).matchAll(/undefined (?:reference to [`']|symbol: )_?([A-Za-z_]\w*)(?=['`]|$)|"_([A-Za-z_]\w*)", referenced from/gm)].map(m => m[1] ?? m[2]))];
531
+ // (C++: the linker names other code's functions demangled, `A::f(int) const`: their own names from the object's
532
+ // undefined symbols, each matched by its demangled form; a stub is named so, `void _ZNK1A1fEi(void)`)
533
+ const demangled = new Set([...why(x).matchAll(/"([^"]+)", referenced from|undefined reference to [`']([^'`]+)'/g)].map(m => m[1] ?? m[2]).filter(d => /[:(]/.test(d)));
534
+ const base = new Map();
535
+ if (cpp && demangled.size) {
536
+ try {
537
+ run(clang, ['-x', 'c++', ...flags, '-w', '-O0', '-fsanitize=undefined', '-fsanitize-trap=undefined', '-fno-sanitize=vptr,function', ...strictFlex(clang), '-c', h, '-o', `${work}/harness.o`]);
538
+ const und = run('nm', ['-u', `${work}/harness.o`]).split('\n').map(l => l.trim().replace(/^U\s+/, '')).filter(Boolean);
539
+ const out = cp.execFileSync('c++filt', [], { input: und.join('\n'), encoding: 'utf8' }).split('\n');
540
+ und.forEach((m, i) => { const d = out[i]?.trim() ?? ''; if (demangled.has(d) || demangled.has(d.replace(/^_/, ''))) {
541
+ const n = m.replace(/^_(?=_Z)/, '');
542
+ if (/^\w+$/.test(n)) {
543
+ names.push(n);
544
+ base.set(n, shortName(d) ?? n);
545
+ }
546
+ } });
547
+ }
548
+ catch { /* the names the linker gave */ }
549
+ }
404
550
  if (!names.length) {
405
551
  const b = buildCheck(clang, () => link([]), errorsOf, ofSource, x);
406
552
  if (!('ok' in b))
407
553
  return { ...empty, ...builtEvidence(b) };
408
554
  }
409
555
  else {
410
- const out = new Set(read.leftOut ?? []);
411
- fs.writeFileSync(stubs, `void gdp_extern_called(const char *);\n${names.map(n => (out.has(n) ? `void ${n}(void) {}` : `void ${n}(void) { gdp_extern_called(${JSON.stringify(n)}); }`)).join('\n')}\n`);
556
+ // (left out by its name, or by its name and constant arguments, CO_error_x_1_27: answered per arguments)
557
+ const left = new Set(read.leftOut ?? []), out = { has: (n) => left.has(n) || [...left].some(k => k.startsWith(`${n}_`) && /^[xm\d_]+$/.test(k.slice(n.length + 1))) };
558
+ fs.writeFileSync(stubs, `void gdp_extern_called(const char *);\n${names.map(n => (out.has(n) || out.has(base.get(n) ?? '') ? `void ${n}(void) {}` : `void ${n}(void) { gdp_extern_called(${JSON.stringify(base.get(n) ?? n)}); }`)).join('\n')}\n`);
412
559
  const b = buildCheck(clang, () => link([stubs]), errorsOf, ofSource);
413
560
  if (!('ok' in b))
414
561
  return { ...empty, ...builtEvidence(b) };
@@ -133,5 +133,6 @@ export declare function drive(m: Model, r: Rule, sorts: Sorts, code: CodeSide, o
133
133
  }): Evidence;
134
134
  export declare function conditionsOf(m: Model, writes?: boolean): B[];
135
135
  export declare function condAt(c: B, env: Record<string, unknown>): ReturnType<Term['lt']>;
136
+ export declare function tiesIn(m: Model, s: Snap, raw: Record<string, Raw>): boolean;
136
137
  export declare function evalTerm(t: N | B | I.L, env: Record<string, Raw>, cell?: (map: string, key: Raw, field: string) => Raw): Raw;
137
138
  export {};
@@ -400,7 +400,7 @@ export function check(code, file, m, r, sorts, opts = {}) {
400
400
  return retried(() => checkOnce(code, file, m, r, sorts, opts), noEvidence);
401
401
  }
402
402
  function checkOnce(code, file, m, r, sorts, opts) {
403
- const isClass = m.shape === 'class', fns = m.shape === 'class' ? [m.entry] : [...new Set(m.events.map(e => e.call))];
403
+ const isClass = m.shape === 'class', standalone = !!m.standalone, fns = m.shape === 'class' ? [m.entry] : [...new Set(m.events.map(e => e.call))];
404
404
  let answers = {};
405
405
  // (the modules whose functions the class calls: each export answers its input, or nothing, by the callee's name)
406
406
  const ans = (path) => () => { const n = Object.keys(m.answers ?? {}).find(k => m.answers[k] === path); return n === undefined ? undefined : answers[n]; };
@@ -444,6 +444,8 @@ function checkOnce(code, file, m, r, sorts, opts) {
444
444
  at: (snap, params) => (box.call('$at', undefined, [valueOf(snap, m.layout, m, evalAt(params), box.ctx), ctorValues(params)]).ok ? box.ctx.__r.value : (() => { throw new Error(`could not make the object: ${box.ctx.__r.error}`); })()),
445
445
  snapOf: (self, params) => snapOf(stateOf(self), m.layout, m, evalAt(params)),
446
446
  call: (self, e, args) => {
447
+ if (standalone)
448
+ return box.call(e.call, undefined, args);
447
449
  for (const f of new Set(Object.values(m.answers ?? {})))
448
450
  if (!f.startsWith('import:'))
449
451
  self[f] = answering(f);
@@ -459,7 +461,7 @@ function checkOnce(code, file, m, r, sorts, opts) {
459
461
  args: (inputs, e) => {
460
462
  answers = inputs;
461
463
  const dateIn = (n) => { const x = m.inputs.find(v => v.name === n); return x?.sort.k === 'num' && x.sort.date ? vmOf().runInContext(`new Date(${Number(inputs[n])})`, box.ctx) : inputs[n]; };
462
- const build = (a) => (a.k === 'input' ? dateIn(a.name) : a.k === 'lit' ? a.value : a.k === 'rec' ? Object.fromEntries(a.fields.map(([f, x]) => [f, build(x)])) : a.k === 'lazy'
464
+ const build = (a) => (a.k === 'input' ? dateIn(a.name) : a.k === 'maybe-bool' ? (inputs[a.missing] ? undefined : inputs[a.name]) : a.k === 'lit' ? a.value : a.k === 'rec' ? Object.fromEntries(a.fields.map(([f, x]) => [f, build(x)])) : a.k === 'lazy'
463
465
  ? Object.fromEntries([...m.inputs].filter(v => m.lazy?.get(v.name)?.prefix === a.prefix).map(v => [m.lazy.get(v.name).field, inputs[v.name]]))
464
466
  : undefined);
465
467
  return e.args.map(build);
@@ -490,7 +492,7 @@ function checkOnce(code, file, m, r, sorts, opts) {
490
492
  // (through its side) and of the rule, and compared.
491
493
  export function drive(m, r, sorts, code, opts = {}) {
492
494
  const t0 = performance.now(), rand = seeded((opts.seed ?? 7) >>> 0 || 1), bound = opts.bound ?? 12;
493
- const isClass = m.shape === 'class';
495
+ const isClass = m.shape === 'class', standalone = !!m.standalone;
494
496
  const interp = r.interpreter(), gen = r.compiled(), machine = r.machine;
495
497
  const ev = { 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 };
496
498
  const consts = constantsOf(m), strs = stringsOf(m);
@@ -518,7 +520,8 @@ export function drive(m, r, sorts, code, opts = {}) {
518
520
  }
519
521
  const keys = Object.values(st.maps).flatMap(c => Object.keys(c));
520
522
  // An input given as a natural (domains) is drawn as one: the claim is for those, as the user said.
521
- const x = draw(v.sort, sorts, v.name, rand, near, bound, [...strs, ...keys]);
523
+ const finite = m.standaloneDomains?.[v.name];
524
+ const x = finite ? finite[rand(finite.length)] : draw(v.sort, sorts, v.name, rand, near, bound, [...strs, ...keys]);
522
525
  inputs[v.name] = code.input ? code.input(v, x, rand) : opts.given?.[v.name] === 'nat' && typeof x === 'number' ? Math.abs(x) : x;
523
526
  }
524
527
  // (a list the request carries: up to 4 items, mostly, each field drawn by its sort)
@@ -530,6 +533,10 @@ export function drive(m, r, sorts, code, opts = {}) {
530
533
  const used = new Set();
531
534
  const walk = (a) => { if (a.k === 'input')
532
535
  used.add(a.name);
536
+ else if (a.k === 'maybe-bool') {
537
+ used.add(a.name);
538
+ used.add(a.missing);
539
+ }
533
540
  else if (a.k === 'rec')
534
541
  a.fields.forEach(([, x]) => walk(x));
535
542
  else if (a.k === 'lazy')
@@ -546,6 +553,13 @@ export function drive(m, r, sorts, code, opts = {}) {
546
553
  // Steps the code and the rule from one state; undefined when they agree (the next state on both sides is returned
547
554
  // through `next`), else the difference.
548
555
  const step = (params, ps, side, st, inputs, e, next, where) => {
556
+ // A source type's finite numeric domain is part of the standalone claim, not
557
+ // behavior the source is alleged to reject. Never execute an out-of-domain probe.
558
+ if (m.standalone && Object.entries(m.standaloneDomains ?? {}).some(([name, values]) => !values.includes(inputs[name]))) {
559
+ ev.outside++;
560
+ next.stop = true;
561
+ return undefined;
562
+ }
549
563
  const args = code.args(inputs, e), raw = ruleInputs(inputs, e);
550
564
  if (m.folds)
551
565
  carry(m, raw, inputs, side.snap, params, r.decode(st));
@@ -555,7 +569,18 @@ export function drive(m, r, sorts, code, opts = {}) {
555
569
  // The code.
556
570
  let res;
557
571
  try {
558
- if (isClass) {
572
+ if (standalone) {
573
+ const c = code.call(undefined, e, args);
574
+ if (!c.ok && c.outside) {
575
+ next.stop = true;
576
+ ev.outside++;
577
+ return undefined;
578
+ }
579
+ // Result fields in a prover witness are not state held by a pure
580
+ // function. Compare the returned value below, never carry those fields.
581
+ res = c.ok ? { snap: { leaves: {}, maps: {} }, out: c.value } : { refused: c.error };
582
+ }
583
+ else if (isClass) {
559
584
  const self = side.self, c = code.call(self, e, args);
560
585
  if (!c.ok && c.outside) {
561
586
  next.stop = true;
@@ -656,7 +681,7 @@ export function drive(m, r, sorts, code, opts = {}) {
656
681
  const ruleSide = ruleSnap(r, m, rule.st, sorts), diff = sameSnap(res.snap, ruleSide);
657
682
  if (diff)
658
683
  return `${where}: ${req} ${from}: ${diff}`;
659
- if (isClass) {
684
+ if (isClass || standalone) {
660
685
  // The method's result, as the rule keeps it: a value, a record's fields, or a value and whether it is missing.
661
686
  const rk = m.results?.[e.call], d = r.decode(rule.st);
662
687
  const bad = (what) => `${where}: ${req} ${from}: ${e.call} returns ${JSON.stringify(res.out)}, ${what}`;
@@ -1005,17 +1030,83 @@ function carry(m, raw, inputs, st, params, dec) {
1005
1030
  const dflt = (map, field) => { const f = m.maps.find(d => d.name === map)?.fields.find(x => x.name === field); return field === 'has' || f?.sort.k === 'bool' ? false : f?.sort.k === 'choice' ? f.sort.values[0] : 0; };
1006
1031
  const cell = (map, key, field) => (lists[map] ? lists[map][key][field] : dec[map]?.[String(key)]?.[field] ?? dflt(map, field));
1007
1032
  for (const d of m.folds ?? []) {
1033
+ if (d.loop?.cond) {
1034
+ carryLoop(d, raw, st, params, lists, dec, cell);
1035
+ continue;
1036
+ }
1008
1037
  // (the passes: a carried list's length, or one past a list of the state's last place)
1009
1038
  const env = { ...params, ...st.leaves, ...raw }, runs = [];
1010
1039
  const n = d.state ? Math.max(-1, ...Object.entries(dec[d.list] ?? {}).filter(([, c]) => c.has).map(([k]) => Number(k))) + 1 : (lists[d.list] ?? []).length;
1011
1040
  const at = (t, i) => evalTerm(t.e, i === undefined ? env : { ...env, [I.PASS]: i }, cell);
1012
1041
  runs.push(Object.fromEntries(d.fields.map(f => [f.name, at(d.init[f.name])])));
1013
1042
  lists[d.run] = runs;
1043
+ // (from the last place down: the start at n, each pass's output at its own place)
1044
+ if (d.back) {
1045
+ const out = Array.from({ length: n + 1 });
1046
+ out[n] = runs[0];
1047
+ lists[d.run] = out;
1048
+ for (let i = n - 1; i >= 0; i--)
1049
+ out[i] = Object.fromEntries(d.fields.map(f => [f.name, at(d.step[f.name], i)]));
1050
+ raw[d.run] = out;
1051
+ continue;
1052
+ }
1014
1053
  for (let i = 0; i < n; i++)
1015
1054
  runs.push(Object.fromEntries(d.fields.map(f => [f.name, at(d.step[f.name], i)])));
1016
1055
  raw[d.run] = runs;
1017
1056
  }
1018
1057
  }
1058
+ // A while loop's run over lists by an order, as its passes compute it: each list's held keys sorted by the order (ties
1059
+ // in place order: the rule refuses there, an edge), then from the start each pass where the condition holds.
1060
+ function carryLoop(d, raw, st, params, lists, dec, cell) {
1061
+ const l = d.loop, env = { ...params, ...st.leaves, ...raw }, runs = [];
1062
+ const places = new Map();
1063
+ for (const g of l.drains ?? []) {
1064
+ const keys = Object.keys(dec[g.map] ?? {}).map(Number).filter(k => evalTerm(g.held, { ...env, kl$: k }, cell) === true).sort((a, b) => a - b);
1065
+ const parts = (k) => g.by.map(b => ({ v: evalTerm(b.e, { ...env, kl$: k }, cell), desc: b.desc }));
1066
+ keys.sort((x, y) => { const a = parts(x), b = parts(y); for (let j = 0; j < a.length; j++) {
1067
+ const c = a[j].v - b[j].v;
1068
+ if (c)
1069
+ return a[j].desc ? -c : c;
1070
+ } return x - y; });
1071
+ lists[g.ord] = keys.map(k => ({ k }));
1072
+ raw[g.ord] = lists[g.ord];
1073
+ raw[`${g.ord}_len`] = keys.length;
1074
+ env[`${g.ord}_len`] = keys.length;
1075
+ places.set(g.rk, new Map(keys.map((k, i) => [k, i])));
1076
+ raw[g.rk] = places.get(g.rk);
1077
+ }
1078
+ const cell2 = (map, key, field) => (places.has(map) ? places.get(map).get(key) ?? 0 : cell(map, key, field));
1079
+ const at = (t, i) => evalTerm(t.e, { ...env, [I.PASS]: i }, cell2);
1080
+ lists[d.run] = runs;
1081
+ runs.push(Object.fromEntries(d.fields.filter(f => d.init[f.name]).map(f => [f.name, at(d.init[f.name], 0)])));
1082
+ for (let i = 0; evalTerm(l.cond, { ...env, [I.PASS]: i }, cell2) === true && i < 100_000; i++)
1083
+ runs.push(Object.fromEntries(d.fields.filter(f => d.step[f.name]).map(f => [f.name, at(d.step[f.name], i)])));
1084
+ raw[d.run] = runs;
1085
+ if (d.len.op === 'var')
1086
+ raw[d.len.name] = runs.length - 1;
1087
+ }
1088
+ // Whether two held items of a list a while loop takes by an order tie under it (the rule's claim stops there).
1089
+ export function tiesIn(m, s, raw) {
1090
+ for (const d of m.folds ?? [])
1091
+ for (const g of d.loop?.drains ?? []) {
1092
+ // (only where the loop runs: the request its method's, on its branch)
1093
+ const cell0 = (map, key, field) => (field === 'has' ? !!s.maps[map]?.[String(key)] : s.maps[map]?.[String(key)]?.[field] ?? 0);
1094
+ if (d.loop.entry && evalTerm(d.loop.entry, { ...s.leaves, ...raw }, cell0) !== true)
1095
+ continue;
1096
+ const cells = s.maps[g.map] ?? {}, cell = (map, key, field) => (field === 'has' ? !!s.maps[map]?.[String(key)] : s.maps[map]?.[String(key)]?.[field] ?? 0);
1097
+ const seen = new Set();
1098
+ for (const k of Object.keys(cells).map(Number)) {
1099
+ const env = { ...s.leaves, ...raw, kl$: k };
1100
+ if (evalTerm(g.held, env, cell) !== true)
1101
+ continue;
1102
+ const key = JSON.stringify(g.by.map(b => evalTerm(b.e, env, cell)));
1103
+ if (seen.has(key))
1104
+ return true;
1105
+ seen.add(key);
1106
+ }
1107
+ }
1108
+ return false;
1109
+ }
1019
1110
  // A term at concrete values (a constant field over the params, a start, the precondition; with `cell`, a state's
1020
1111
  // map cells and list items too).
1021
1112
  export function evalTerm(t, env, cell) {
@@ -5,7 +5,7 @@ import { type GoOptions, type GoPkg, type GoRead } from './extract-go.js';
5
5
  export type GoLeaf = {
6
6
  name: string;
7
7
  path: string[];
8
- kind: 'int' | 'bool' | 'str' | 'big' | 'bignil' | 'map' | 'mapnil' | 'list' | 'frame';
8
+ kind: 'int' | 'bool' | 'str' | 'big' | 'bignil' | 'map' | 'mapnil' | 'list' | 'frame' | 'sink';
9
9
  t: number;
10
10
  go: string;
11
11
  };