gdp-wired 0.44.0 → 0.45.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 (66) hide show
  1. package/dist/core/c/reader.js +22 -7
  2. package/dist/core/check.js +3 -2
  3. package/dist/core/cli.d.ts +1 -0
  4. package/dist/core/cli.js +136 -6
  5. package/dist/core/counts.d.ts +1 -1
  6. package/dist/core/counts.js +30 -12
  7. package/dist/core/data.d.ts +6 -1
  8. package/dist/core/data.js +894 -152
  9. package/dist/core/dsl.d.ts +2 -0
  10. package/dist/core/dsl.js +88 -10
  11. package/dist/core/effect-prims.js +2 -2
  12. package/dist/core/ex/reader.exs +17 -1
  13. package/dist/core/exists.d.ts +15 -1
  14. package/dist/core/exists.js +263 -41
  15. package/dist/core/extract-c.js +19 -12
  16. package/dist/core/extract-check.d.ts +6 -0
  17. package/dist/core/extract-check.js +49 -3
  18. package/dist/core/extract-ex.js +3 -3
  19. package/dist/core/extract-go-check.js +19 -12
  20. package/dist/core/extract-go.js +20 -5
  21. package/dist/core/extract-jvm.js +63 -14
  22. package/dist/core/extract-print.js +3 -0
  23. package/dist/core/extract-py.js +3 -3
  24. package/dist/core/extract-rb.js +3 -3
  25. package/dist/core/extract-read.d.ts +8 -0
  26. package/dist/core/extract-read.js +55 -0
  27. package/dist/core/extract-rs.js +17 -19
  28. package/dist/core/extract-shapes.js +20 -0
  29. package/dist/core/extract-sol.js +19 -8
  30. package/dist/core/extract-step.d.ts +50 -3
  31. package/dist/core/extract-step.js +289 -58
  32. package/dist/core/extract-swift.js +20 -13
  33. package/dist/core/extract.d.ts +1 -0
  34. package/dist/core/extract.js +27 -2
  35. package/dist/core/fresh.d.ts +2 -2
  36. package/dist/core/fresh.js +7 -3
  37. package/dist/core/go/reader.go +7 -1
  38. package/dist/core/infer.js +115 -42
  39. package/dist/core/jvm/JavaReader.java +10 -2
  40. package/dist/core/jvm/Jvm.java +17 -1
  41. package/dist/core/jvm/KtReader.java +57 -5
  42. package/dist/core/machine.d.ts +1 -2
  43. package/dist/core/machine.js +27 -15
  44. package/dist/core/py/harness.py +77 -11
  45. package/dist/core/py/reader.py +50 -5
  46. package/dist/core/rb/reader.rb +52 -5
  47. package/dist/core/rs/src/main.rs +10 -0
  48. package/dist/core/sol/harness.py +6 -3
  49. package/dist/core/solver.js +5 -4
  50. package/dist/core/system.d.ts +62 -1
  51. package/dist/core/system.js +262 -3
  52. package/dist/core/transfer.js +17 -0
  53. package/dist/core/watch.js +1 -1
  54. package/dist/interchange/check.js +10 -10
  55. package/dist/interchange/format.d.ts +4 -0
  56. package/dist/interchange/format.js +13 -5
  57. package/dist/kernel/cdcl.js +33 -2
  58. package/dist/kernel/epr.js +35 -5
  59. package/dist/kernel/kernel.d.ts +2 -0
  60. package/dist/kernel/kernel.js +67 -40
  61. package/dist/kernel/prove.d.ts +22 -0
  62. package/dist/kernel/prove.js +156 -7
  63. package/dist/lean-kernel/emit.d.ts +9 -3
  64. package/dist/lean-kernel/emit.js +170 -29
  65. package/dist/lean-kernel/library.js +1 -1
  66. package/package.json +2 -2
@@ -1,4 +1,4 @@
1
- import { Refusal } from "../extract-read.js";
1
+ import { Refusal, readerRun, statedRefusal } from "../extract-read.js";
2
2
  // (consecutive JSON values in one string, each with where it ends)
3
3
  class JSONDecoder {
4
4
  decode(s, i) {
@@ -31,10 +31,13 @@ export function clangDump(file, flags, clang = 'clang', cpp = false, filter) {
31
31
  const cp = node('node:child_process'), lang = cpp ? ['-x', 'c++'] : ['-x', 'c'];
32
32
  const run = (args) => {
33
33
  try {
34
- return cp.execFileSync(clang, args, { encoding: 'utf8', maxBuffer: 1 << 30, stdio: ['ignore', 'pipe', 'pipe'] });
34
+ return cp.execFileSync(clang, args, { encoding: 'utf8', maxBuffer: 1 << 30, stdio: ['ignore', 'pipe', 'pipe'], ...readerRun() });
35
35
  }
36
36
  catch (e) {
37
37
  const x = e;
38
+ const stated = statedRefusal(e);
39
+ if (stated)
40
+ throw new Refusal(file, stated);
38
41
  throw new Refusal(file, x.code === 'ENOENT' ? `no ${clang} to run: clang is needed to extract ${cpp ? 'C++' : 'C'}` : `clang doesn't compile it (${String(x.stderr ?? x.message).split('\n').filter(l => /error/.test(l)).slice(0, 3).join(' | ')})`);
39
42
  }
40
43
  };
@@ -198,11 +201,17 @@ export function readC(file, entry, tu, target, cpp = false, root, picks = {}) {
198
201
  cxx.push(n);
199
202
  }
200
203
  };
204
+ // A literal's value exactly, through parentheses.
205
+ const exact = (n) => n.kind === 'IntegerLiteral' ? BigInt(String(n.value)) : n.kind === 'ParenExpr' ? exact(n.inner[0]) : undefined;
201
206
  // A constant's value, where the node is one (literals, enum constants, a const global's, folded).
202
207
  const fold = (n) => {
203
208
  switch (n.kind) {
209
+ // (a literal a double can't hold exactly: NaN, past 2^53, unless a cast takes it exactly)
204
210
  case 'IntegerLiteral':
205
- case 'CharacterLiteral': return Number(n.value);
211
+ case 'CharacterLiteral': {
212
+ const v = Number(n.value);
213
+ return Number.isSafeInteger(v) ? v : NaN;
214
+ }
206
215
  case 'CXXBoolLiteralExpr': return n.value ? 1 : 0;
207
216
  case 'CallExpr': {
208
217
  const m = /numeric_limits<\s*(.+?)\s*>::(max|min|lowest)\)?\s*\(\s*\)$/.exec(text(n)), it = m ? T(parseT(m[1])) : undefined;
@@ -217,11 +226,13 @@ export function readC(file, entry, tu, target, cpp = false, root, picks = {}) {
217
226
  case 'CStyleCastExpr':
218
227
  case 'CXXStaticCastExpr':
219
228
  case 'CXXFunctionalCastExpr': {
220
- const v = fold(n.inner[0]), t = n.type ? T(tyOf(n.type)) : undefined;
229
+ const b = exact(n.inner[0]), v = b !== undefined ? Number(b) : fold(n.inner[0]), t = n.type ? T(tyOf(n.type)) : undefined;
221
230
  if (v === undefined || t?.k !== 'int')
222
231
  return n.castKind === 'IntegralToBoolean' && v !== undefined ? +(v !== 0) : undefined;
232
+ if (b === undefined && !Number.isFinite(v))
233
+ return NaN;
223
234
  // (exactly: at 64 bits 2^64 + 1 is 2^64 in a double)
224
- const m = 1n << BigInt(t.bits), w = ((BigInt(Math.trunc(v)) % m) + m) % m;
235
+ const m = 1n << BigInt(t.bits), w = (((b ?? BigInt(Math.trunc(v))) % m) + m) % m;
225
236
  return Number(t.signed && w >= m / 2n ? w - m : w);
226
237
  }
227
238
  case 'UnaryOperator': {
@@ -367,9 +378,13 @@ export function readC(file, entry, tu, target, cpp = false, root, picks = {}) {
367
378
  for (const m of cxx) {
368
379
  if (m.$rec !== entryRec)
369
380
  continue;
381
+ // (a constructor the check can't call, private or protected: refused, the object is made with it)
370
382
  if (m.kind === 'CXXConstructorDecl') {
371
- if (!/\((const )?\w+ &&?\)/.test(m.type.qualType) || params(m).length !== 1)
383
+ if (!/\((const )?\w+ &&?\)/.test(m.type.qualType) || params(m).length !== 1) {
384
+ if (m.$access !== 'public')
385
+ refuse(m, `${entry}: its constructor is ${String(m.$access)} (the check makes the object with it)`);
372
386
  ctors.push(m);
387
+ }
373
388
  continue;
374
389
  }
375
390
  if (m.kind !== 'CXXMethodDecl' || /^operator/.test(m.name))
@@ -761,7 +776,7 @@ export function readC(file, entry, tu, target, cpp = false, root, picks = {}) {
761
776
  if (c.inner.length > 2)
762
777
  return void cases.push({ p: pos(c), b: sno(c, 'a case range (a GNU extension)') });
763
778
  const v = fold(c.inner[0]);
764
- cases.push({ p: pos(c), list: [v === undefined ? no(c, 'a case that isn\'t a constant') : lit(c, v, tt)], b: [] });
779
+ cases.push({ p: pos(c), list: [v === undefined ? no(c, 'a case that isn\'t a constant') : !Number.isSafeInteger(v) ? no(c, 'a case past 2^53 (the rule\'s numbers stop there)') : lit(c, v, tt)], b: [] });
765
780
  return c.inner[1];
766
781
  }
767
782
  if (c.kind === 'DefaultStmt') {
@@ -17,7 +17,8 @@ export function checkRefutation(constraints, steps, integral = true) {
17
17
  return false;
18
18
  if (!integral && !(Number.isInteger(s.a) && Number.isInteger(s.b) && s.a >= 0 && s.b >= 0))
19
19
  return false;
20
- const out = {};
20
+ // (on no prototype: a row's variable named __proto__ is summed like any other, never dropped)
21
+ const out = Object.create(null);
21
22
  // Each product safe too: a rounded one is past 2^53, but the other row's could bring the sum back under it.
22
23
  for (const [lin, m] of [[rows[s.a], s.ma], [rows[s.b], s.mb]])
23
24
  for (const [key, c] of Object.entries(lin)) {
@@ -48,7 +49,7 @@ export function checkWitness(constraints, witness) {
48
49
  return constraints.every(c => {
49
50
  let sum = 0;
50
51
  for (const [key, a] of Object.entries(c.lin)) {
51
- const value = key === '1' ? 1 : witness[key], term = a * value;
52
+ const value = key === '1' ? 1 : Object.hasOwn(witness, key) ? witness[key] : undefined, term = a * value;
52
53
  if (!(Number.isSafeInteger(a) && Number.isSafeInteger(value) && Number.isSafeInteger(term) && Number.isSafeInteger(sum + term)))
53
54
  return false;
54
55
  sum += term;
@@ -60,6 +60,7 @@ export type RuleOut = {
60
60
  notes: string[];
61
61
  names: Name[];
62
62
  checked?: string;
63
+ env?: string[];
63
64
  laws: LawOut[];
64
65
  proposed: LawOut[];
65
66
  brokenProposed?: number;
package/dist/core/cli.js CHANGED
@@ -10,6 +10,7 @@ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExte
10
10
  import { proveLeadsTo, proveRule, proveSteps } from "./dsl.js";
11
11
  import { LawError, buildLaw, buildLeadsTo, buildTwoRuns, citesIn, isLeadsTo, isTwoRuns, lawsIn, namesWithClock } from "./laws.js";
12
12
  import { certify, proveTwoRuns } from "./relational.js";
13
+ import { contend, envOf, inEnv, shrinkRun } from "./system.js";
13
14
  const proc = globalThis.process;
14
15
  const fs = proc.getBuiltinModule('node:fs'), path = proc.getBuiltinModule('node:path');
15
16
  const out = (s = '') => proc.stdout.write(`${s}\n`);
@@ -264,7 +265,7 @@ async function rulesOf(t, o, laws) {
264
265
  const more = [...new Set(laws.map(l => l.cls ?? l.fn).filter((n) => !!n && !have.has(n)))];
265
266
  if (!more.length)
266
267
  return got;
267
- const { json: _j, ms: _m, propose: _p, clock: _c, cert: _t, from: _fr, ...flags } = o;
268
+ const { json: _j, ms: _m, propose: _p, clock: _c, cert: _t, from: _fr, env: _e, ...flags } = o;
268
269
  void _j;
269
270
  void _m;
270
271
  void _p;
@@ -272,7 +273,7 @@ async function rulesOf(t, o, laws) {
272
273
  void _t;
273
274
  void _fr;
274
275
  const cfg = configFor(t.lang === 'go' || t.lang === 'rust' || fs.statSync(t.at).isDirectory() ? t.at : path.dirname(t.at));
275
- const { clock: _k, from: _f, ...shared } = cfg.all;
276
+ const { clock: _k, from: _f, env: _v, ...shared } = cfg.all;
276
277
  void _k;
277
278
  void _f;
278
279
  const keep = [...new Set(laws.flatMap(l => l.expr.match(/[A-Za-z_]\w*/g) ?? []))];
@@ -281,7 +282,7 @@ async function rulesOf(t, o, laws) {
281
282
  return [...got.filter(r => r.x.ok || r.entry || !extra.length), ...extra];
282
283
  }
283
284
  async function rulesOf0(t, o, laws) {
284
- const { json: _j, ms: _m, propose: _p, clock: _c, cert: _t, from: _fr, ...flags } = o;
285
+ const { json: _j, ms: _m, propose: _p, clock: _c, cert: _t, from: _fr, env: _e, ...flags } = o;
285
286
  void _j;
286
287
  void _m;
287
288
  void _p;
@@ -291,7 +292,7 @@ async function rulesOf0(t, o, laws) {
291
292
  // (the options: gdp.toml's for every rule, then the rule's own, then the flags; a rule found with no entry named is
292
293
  // read again where gdp.toml has options of its own for it)
293
294
  const cfg = configFor(t.lang === 'go' || t.lang === 'rust' || fs.statSync(t.at).isDirectory() ? t.at : path.dirname(t.at));
294
- const { clock: _k, from: _f, ...shared } = cfg.all;
295
+ const { clock: _k, from: _f, env: _v, ...shared } = cfg.all;
295
296
  void _f;
296
297
  void _k;
297
298
  // (the names the laws read, so an argument a law reads stays in the rule though the code ignores it)
@@ -463,6 +464,32 @@ export async function checkTarget(t, o) {
463
464
  const methods = new Set([...(x.names ?? []).filter(n => n.method).map(n => n.method), ...(evSort?.k === 'choice' ? evSort.values : [])]);
464
465
  const stated = mine.map(l => ({ ...l, ...(l.fn && methods.has(l.fn) ? { method: l.fn } : {}) }));
465
466
  const proven = [];
467
+ // (the environment the code runs in: --env, gdp.toml's env for the rule or every rule, or a `gdp: env` comment in
468
+ // its class: every call at once at its isolation level, keys that expire, retries; its laws lifted to it)
469
+ const words = o.env ?? (name ? cfg.rules[name]?.env : undefined) ?? envTags(t.files, name) ?? cfg.all.env;
470
+ let sys;
471
+ if (words) {
472
+ try {
473
+ const m = x.rule.machine, stores = [...new Set((x.names ?? []).filter(n => n.map?.store && n.rule).map(n => n.rule))].map(b => Object.keys(m.maps ?? {}).filter(k => k === b || k.startsWith(`${b}.`))).filter(c => c.length);
474
+ const own = Object.keys(m.state).filter(k => (x.names ?? []).some(n => (n.role === 'failed' || n.role === 'result') && ((n.rule && (k === n.rule || k.startsWith(`${n.rule}$`))) || k === n.none)));
475
+ const ev = (x.names ?? []).find(n => n.role === 'method'), evSort = x.model?.inputs.find(v => v.name === x.model?.event)?.sort;
476
+ const failedVar = (x.names ?? []).find(n => n.role === 'failed')?.rule;
477
+ // (a flow the laws state where the env doesn't: at most one call between a and b is the flow a then b, a and a a
478
+ // call of a alone, holding once it did its work)
479
+ const env = envOf(words), bw = mine.map(l => /^at\s+most\s+one\s+call\s+between\s+([\w.]+)\s+and\s+([\w.]+)$/i.exec(l.expr.trim())).find(Boolean);
480
+ if (!env.flow && bw)
481
+ env.flow = bw[1] === bw[2] ? [bw[1]] : [bw[1], bw[2]];
482
+ sys = inEnv(x.rule, env, { stores, own, ...(ev && evSort?.k === 'choice' ? { method: { name: ev.rule, values: evSort.values } } : {}), ...(failedVar ? { failed: failedVar } : {}), args: (x.names ?? []).filter(n => n.role === 'input' && n.method && n.rule).map(n => ({ method: n.method, code: n.code, rule: n.rule })),
483
+ oks: [...(x.names ?? []).filter(n => n.role === 'result' && n.method && x.model?.state.find(v => v.name === n.rule)?.sort.k === 'bool').map(n => ({ method: n.method, rule: n.rule })),
484
+ // (a method that makes an effect did its work where it made it: a charge, a handled message)
485
+ ...Object.entries(x.read?.effectsOf ?? {}).flatMap(([method, vs]) => vs.map(rule => ({ method, rule })))] });
486
+ r.env = sys.models.map(md => `${md.name}: ${md.assumes}`);
487
+ }
488
+ catch (e) {
489
+ r.laws = mine.map(l => ({ name: l.name, expr: l.expr, where: l.where, verdict: 'not read', why: `the environment: ${e.message}`, ms: 0 }));
490
+ continue;
491
+ }
492
+ }
466
493
  // (a law is known by its name: a name stated twice in one rule is refused, both times)
467
494
  const twice = (l) => stated.filter(m => m.name === l.name).map(m => m.where);
468
495
  // (from = "any": every law proven from every state the laws allow, not only those a run from the start reaches, for
@@ -482,12 +509,12 @@ export async function checkTarget(t, o) {
482
509
  const order = [...stated.keys()].sort((a, b) => rank(stated[a]) - rank(stated[b]));
483
510
  // (from any state, the laws about states as one inductive set: the largest the stated ones make, each law the
484
511
  // kernel's step breaks taken out in turn (Houdini), the others proven together; one taken out is judged alone)
485
- const inductive = from && x.rule ? houdini(x, stated.filter(m => twice(m).length === 1 && kindOf(m) === 'law'), o.ms, ctx.clock) : undefined;
512
+ const inductive = from && x.rule && !sys ? houdini(x, stated.filter(m => twice(m).length === 1 && kindOf(m) === 'law'), o.ms, ctx.clock) : undefined;
486
513
  const outsOf = [];
487
514
  for (const i of order) {
488
515
  const l = stated[i];
489
516
  outsOf[i] = twice(l).length > 1 ? { name: l.name, expr: l.expr, where: l.where, verdict: 'not read', why: `a law of this name is stated twice (${twice(l).join(', ')}): a law is known by its name`, ms: 0 }
490
- : prove(x, l, o.ms, proven, { ...ctx, entry: name, ...(from ? { from, inductive, together: stated.filter(m => twice(m).length === 1 && kindOf(m) === 'law' && inductive.has(m.name)) } : {}) });
517
+ : sys ? proveInEnv(x, l, o.ms, proven, { ...ctx, sys, entry: name }) : prove(x, l, o.ms, proven, { ...ctx, entry: name, ...(from ? { from, inductive, together: stated.filter(m => twice(m).length === 1 && kindOf(m) === 'law' && inductive.has(m.name)) } : {}) });
491
518
  }
492
519
  r.laws = outsOf;
493
520
  if (o.propose && x.model) {
@@ -665,6 +692,104 @@ function prove(x0, l, ms, proven, ctx) {
665
692
  return { ...base, kind, verdict, ...(ctx?.from && verdict === 'proven' ? { from: 'any' } : {}), ...(replayed ? { replayed } : {}), ...(v.run && verdict === 'broken' ? { run: two ? pairRunOf(x, v.run, two) : runOf(x, v.run) } : {}), ...(verdict === 'unknown' || (verdict === 'broken' && !v.run) ? { why: [v.why ?? v.stuck ?? 'not proven', ...(at.length ? [`a state the laws allow where a step breaks it, no run from the start found reaching it: ${at.join(', ')}`] : [])].join('; ') } : {}),
666
693
  ...(v.run && !two ? { assumes: assumedOf(x, v.run) } : {}), ...(found?.length ? { found } : {}), ...(cert ? { cert } : {}), ms: Date.now() - t0 };
667
694
  }
695
+ // A law of a rule in its environment (core/system.ts's inEnv): built on the rule as the code's names read it, then
696
+ // lifted to every call at once; proven of the system, a run shown as the calls' steps.
697
+ function proveInEnv(x, l, ms, proven, ctx) {
698
+ const t0 = Date.now(), sys = ctx.sys, base = { name: l.name, expr: l.expr, ...(l.where ? { where: l.where } : {}) };
699
+ if (isLeadsTo(l.expr) || isTwoRuns(l.expr))
700
+ return { ...base, verdict: 'not read', why: `a ${isLeadsTo(l.expr) ? 'leads-to' : 'two-run'} law is not lifted to the environment (state it of the rule with no env)`, ms: 0 };
701
+ // (at most one call between a and b: a flow's mutual exclusion, its leases running out where their keys expire)
702
+ const bw = /^at\s+most\s+one\s+call\s+between\s+([\w.]+)\s+and\s+([\w.]+)$/i.exec(l.expr.trim());
703
+ let b;
704
+ try {
705
+ b = bw ? { kind: 'law', law: sys.between(l.name, bw[1], bw[2]) } : buildLaw(x, l, { clock: ctx.clock });
706
+ }
707
+ catch (e) {
708
+ return { ...base, verdict: 'not read', why: e.message, ms: 0 };
709
+ }
710
+ const inv = (x.invariants ?? []).map(sys.law);
711
+ let v, law;
712
+ try {
713
+ if (b.kind === 'law') {
714
+ law = bw ? b.law : sys.law(b.law);
715
+ v = proveRule(sys.rule, [...inv, law], { search: { ms } });
716
+ }
717
+ else {
718
+ law = sys.step(b.law);
719
+ v = proveSteps(sys.rule, [...inv, ...proven], [law], { search: { ms } });
720
+ }
721
+ }
722
+ catch (e) {
723
+ return { ...base, kind: b.kind, verdict: 'unknown', why: e.message, ms: Date.now() - t0 };
724
+ }
725
+ // (not proven and no run: calls contending with one request, a run the search's own draws seldom make)
726
+ if (!(v.proven && v.checked) && !v.run) {
727
+ const run = contend(sys, law, { ms: Math.min(ms, 10_000) });
728
+ if (run)
729
+ v = { ...v, run: run };
730
+ }
731
+ const verdict = v.proven && v.checked ? 'proven' : v.run ? 'broken' : 'unknown';
732
+ if (verdict === 'proven' && b.kind === 'law')
733
+ proven.push(law);
734
+ const found = v.found?.laws?.map(f => f.text);
735
+ return { ...base, kind: b.kind, verdict, ...(v.run && verdict === 'broken' ? { run: sysRunOf(x, sys, shrinkRun(sys.rule, law, v.run)) } : {}), ...(verdict === 'unknown' ? { why: v.why ?? v.stuck ?? 'not proven' } : {}), ...(found?.length ? { found } : {}), ms: Date.now() - t0 };
736
+ }
737
+ // A run of the system as each call's steps: a call begins with its request, reads, commits; a store's key expires.
738
+ function sysRunOf(x, sys, run) {
739
+ const pcs = new Map(), done = (sys.commit ?? 0) + 1, out = [];
740
+ const params = Object.keys(run.params).length ? runOf(x, { params: run.params, trace: [] }) : [];
741
+ // (calls numbered in the order they begin; a store by the code's name)
742
+ const ids = new Map(), n = (p) => { if (!ids.has(p))
743
+ ids.set(p, ids.size + 1); return ids.get(p); };
744
+ const store = (map) => (x.names ?? []).find(m => m.rule === map)?.code ?? map;
745
+ for (const q of run.trace) {
746
+ const a = q[sys.act];
747
+ if (!(a === 0 || a === sys.part)) {
748
+ out.push(`a key of the store expires (key #${String(q['key$'])})`);
749
+ continue;
750
+ }
751
+ const call = runOf(x, { params: {}, trace: [q] }).at(-1);
752
+ if (!sys.id) {
753
+ out.push(call);
754
+ continue;
755
+ }
756
+ const p = q[sys.id], pc = pcs.get(p) ?? 0;
757
+ if (!sys.commit) {
758
+ out.push(`call ${n(p)}: ${call}`);
759
+ continue;
760
+ }
761
+ if (pc >= done)
762
+ continue;
763
+ pcs.set(p, pc === 0 ? (sys.level === 'snapshot' || sys.commit === 1 ? sys.commit : 1) : pc === sys.commit && sys.flow ? 0 : pc + 1);
764
+ out.push(pc === 0 ? `call ${n(p)} begins ${call}` : pc === sys.commit ? `call ${n(p)} commits` : `call ${n(p)} reads ${store(sys.reads[pc - 1])}`);
765
+ }
766
+ return [...params, ...out];
767
+ }
768
+ // The environment a `gdp: env <words>` comment states: one in the rule's class (or naming none, the file's).
769
+ const ENV = /(?:#|\/\/|--|%|\/\*|^\s*\*)\s*gdp:\s*env\s+(.+?)\s*(?:\*\/)?\s*$/;
770
+ function envTags(files, name) {
771
+ for (const f of files) {
772
+ const lines = fs.readFileSync(f, 'utf8').split('\n');
773
+ for (const [i, l] of lines.entries()) {
774
+ const m = ENV.exec(l);
775
+ if (!m)
776
+ continue;
777
+ // (a tag right above a class statement is that class's, else the class it is in)
778
+ let cls;
779
+ for (let j = i + 1; j < lines.length; j++) {
780
+ if (/^\s*(\/\/|\/?\*|#|@|$)/.test(lines[j]))
781
+ continue;
782
+ cls = classAt(lines[j]);
783
+ break;
784
+ }
785
+ for (let j = i; j >= 0 && !cls; j--)
786
+ cls = classAt(lines[j]);
787
+ if (!cls || !name || cls === name)
788
+ return m[1];
789
+ }
790
+ }
791
+ return undefined;
792
+ }
668
793
  // Two runs as calls of the code: each request once, the values the two runs take apart as `a | b`, and the run b leaves
669
794
  // out (isolation's: the others' calls) marked.
670
795
  function pairRunOf(x, run, two) {
@@ -804,6 +929,11 @@ function printRule(r, o) {
804
929
  else {
805
930
  if (r.checked)
806
931
  out(` ${paint('dim', r.checked)}`);
932
+ if (r.env) {
933
+ out(' in its environment (every call at once; the laws below are about these runs):');
934
+ for (const e of r.env)
935
+ out(` ${e}`);
936
+ }
807
937
  const inferred = r.notes.filter(n => /inferred|tagged|left out|answered|injected|the entry/.test(n));
808
938
  for (const n of inferred.slice(0, 12))
809
939
  out(` ${n}`);
@@ -27,7 +27,7 @@ export type Tried<P> = {
27
27
  } | {
28
28
  stuck: string;
29
29
  };
30
- export declare function cone<P>(m: Machine, set: Law[], attempt: (law: Law, ls: Law[], ms: number) => Tried<P>, until: number): Map<string, P>;
30
+ export declare function cone<P>(m: Machine, set: Law[], attempt: (law: Law, ls: Law[], ms: number) => Tried<P>, until: number, houdini?: boolean): Map<string, P>;
31
31
  export type Counted = {
32
32
  proven: boolean;
33
33
  laws: Law[];
@@ -221,8 +221,8 @@ export function candidates(src, m, caller, shapes, guarded, ms, until) {
221
221
  console.error(`counts: ${kinds.length + guarded.length + rowLaws.length + cubes.length - out.length} candidates said before or false on the small instances`);
222
222
  return out;
223
223
  }
224
- export function cone(m, set, attempt, until) {
225
- const kept = new Map(), inCone = (l) => kept.has(l.name), tried = new Map(), times = new Map(), asked = new Set();
224
+ export function cone(m, set, attempt, until, houdini = false) {
225
+ const kept = new Map(), inCone = (l) => kept.has(l.name), tried = new Map(), times = new Map(), asked = new Set(), slow = new Set();
226
226
  const stopAt = until - (until - clock()) / 3, brief = (stopAt - clock()) / Math.max(1, set.length);
227
227
  // (the maps a law reads, a count's through its body)
228
228
  const mapsOf = (l) => new Set([...reads(l.holds, () => true).values()].flatMap(([mp]) => [mp, ...(m.counts?.[mp] ? [...reads(m.counts[mp].body, () => true).values()].map(([q]) => q) : [])]));
@@ -233,7 +233,7 @@ export function cone(m, set, attempt, until) {
233
233
  grew = false;
234
234
  for (const law of set) {
235
235
  const id = `${t} ${law.name}`;
236
- if (kept.has(law.name) || tried.get(id) === kept.size || (t === 0 && tried.has(id)) || (t === 2 && (times.get(law.name) ?? 0) >= 2) || clock() > stopAt)
236
+ if (kept.has(law.name) || tried.get(id) === kept.size || (t === 0 && tried.has(id)) || (t === 2 && ((times.get(law.name) ?? 0) >= 2 || slow.has(law.name))) || clock() > stopAt)
237
237
  continue;
238
238
  tried.set(id, kept.size);
239
239
  if (t === 2)
@@ -248,6 +248,10 @@ export function cone(m, set, attempt, until) {
248
248
  continue;
249
249
  asked.add(same);
250
250
  const r = attempt(law, ls, brief);
251
+ // (a law out of time over every kept law: tried again over more, its goals only grow; where Houdini follows, its
252
+ // share is larger)
253
+ if (houdini && t === 2 && 'stuck' in r && r.stuck !== 'sat')
254
+ slow.add(law.name);
251
255
  if ('proof' in r) {
252
256
  kept.set(law.name, r.proof);
253
257
  grew = any = true;
@@ -268,9 +272,14 @@ export function cone(m, set, attempt, until) {
268
272
  }
269
273
  // On the counted clock (kernel/prove.ts's `counted`, the cost model's work at fullRate a millisecond), as the engine's
270
274
  // search is: what a budget lets it try, and so its verdict, is the same on a slow or shared machine as on a fast one; the
271
- // wall a stop only at twice the budget.
275
+ // wall a stop only at twice the budget. The small instances (exists.ts's smallOf) are read before the wall starts: their
276
+ // search is bounded by its own count of steps, on neither clock, and took 3.6 to 5.2 s of an 8 s budget's 16 s wall on
277
+ // a boat VM (exists.test.ts's two counts), so a shared VM crossed the wall before the search began and left every goal
278
+ // unknown (2 runs in 4 on main; 4 in 4 beside three busy loops).
272
279
  export function searchCounted(m0, caller, ms = 60_000) {
273
- const run = () => withWall(performance.now() + 2 * ms, () => counted(fullRate, () => searchCounted0(m0, caller, ms), true));
280
+ const g = guardLaws(m0), m = { ...m0, counts: { ...m0.counts, ...g.counts } };
281
+ ptime('small', () => smallOf(m));
282
+ const run = () => withWall(performance.now() + 2 * ms, () => counted(fullRate, () => searchCounted0(m0, g, m, caller, ms), true));
274
283
  if (!env.GDP_COUNTS_PROF)
275
284
  return run();
276
285
  cdclStats.on = true;
@@ -278,8 +287,8 @@ export function searchCounted(m0, caller, ms = 60_000) {
278
287
  console.error(`counts: prof total ${Math.round(performance.now() - t)} ms; ${Object.entries(cprof).map(([k2, x]) => `${k2} ${Math.round(x)}`).join(', ')}; cdcl runs ${cdclStats.runs} conflicts ${cdclStats.conflicts} decisions ${cdclStats.decisions} solveMs ${Math.round(cdclStats.solveMs)} rowsMs ${Math.round(cdclStats.rowsMs)} coreMs ${Math.round(cdclStats.coreMs)} unfoldMs ${Math.round(cdclStats.unfoldMs)} lpMs ${Math.round(cdclStats.lpMs)} boundMs ${Math.round(cdclStats.boundMs)} orderMs ${Math.round(cdclStats.orderMs)}`);
279
288
  return out;
280
289
  }
281
- function searchCounted0(m0, caller, ms = 60_000) {
282
- const until = clock() + ms, g = guardLaws(m0), m = { ...m0, counts: { ...m0.counts, ...g.counts } };
290
+ function searchCounted0(m0, g, m, caller, ms) {
291
+ const until = clock() + ms;
283
292
  if (!caller.every(l => clock() < until && trueSmall(m, [l])))
284
293
  return { proven: false, laws: caller, m, why: clock() < until ? 'a law fails on the small instances' : 'time' };
285
294
  const t1 = clock();
@@ -302,13 +311,16 @@ function searchCounted0(m0, caller, ms = 60_000) {
302
311
  const models = new Map(), isCount = (mp) => !!m.counts?.[mp];
303
312
  const attempt = (law, ls, pass, ms) => {
304
313
  const ts = terms(law), id = `${pass} ${law.name}`, cti = models.get(id);
314
+ // (the model broken: the attempt starts at the instances it asks for, its last attempt's and the tuples the new laws
315
+ // break it at, where the rounds of models would lead it again)
316
+ let seed;
305
317
  if (cti && !ls.some(l => !cti.ls.has(l.name) && reads(l.holds, isCount).size)) {
306
318
  const at0 = Object.fromEntries(Object.entries(cti.at).filter(([n]) => n.startsWith('?') || ls.some(l => l.name === n)));
307
- if (!ptime('mbqi', () => modelInstances(m, ls, at0, cti.gg, cti.w)))
319
+ if (!(seed = ptime('mbqi', () => modelInstances(m, ls, at0, cti.gg, cti.w))))
308
320
  return { stuck: 'sat' };
309
321
  }
310
322
  const refuted = (gg, w) => { models.set(id, { gg, w, at, ls: new Set(ls.map(l => l.name)) }); return { stuck: 'sat' }; };
311
- let at = Object.fromEntries(Object.entries(m.step.flags ?? {}).flatMap(([f, q]) => (q.op === 'all' && !q.keys?.length ? [[`?${f}`, ts]] : [])));
323
+ let at = seed ?? Object.fromEntries(Object.entries(m.step.flags ?? {}).flatMap(([f, q]) => (q.op === 'all' && !q.keys?.length ? [[`?${f}`, ts]] : [])));
312
324
  const obligations = (i) => ptime('encode', () => countedObligations(m, ls, { [law.name]: i }, ls.indexOf(law)));
313
325
  const build = () => obligations(at).map(({ goal, decls }) => { const c = pass ? certFor(goal, decls) : none; return { goal, decls, c, gg: ptime('encode', () => mcGoal(goal.hyps, decls, c)) }; });
314
326
  let built = build();
@@ -400,7 +412,7 @@ function searchCounted0(m0, caller, ms = 60_000) {
400
412
  };
401
413
  // The cone (a law about no key is assumed in every goal, so with one in the set nothing is kept); with every caller
402
414
  // kept, the kept laws are the proof; else Houdini over the whole set, the kept laws' proofs reused.
403
- const kept = set.every(l => l.forall) ? cone(m, set, (law, ls, ms2) => traced(law, ls, 1, ms2), until) : new Map();
415
+ const kept = set.every(l => l.forall) ? cone(m, set, (law, ls, ms2) => traced(law, ls, 1, ms2), until, true) : new Map();
404
416
  if (env.GDP_COUNTS_TRACE)
405
417
  console.error(`counts: kept ${kept.size} of ${set.length} in ${Math.round(clock() - t1)} ms`);
406
418
  const finish = (ls, proof) => (ptime('kernel', () => checkCountedLaws(m, ls, proof)) ? { proven: true, laws: ls, m, proof } : { proven: false, laws: ls, m, why: 'the kernel refused the set' });
@@ -408,21 +420,24 @@ function searchCounted0(m0, caller, ms = 60_000) {
408
420
  if (caller.every(l => kept.has(l.name)))
409
421
  return finish(set.filter(l => kept.has(l.name)), keptProof());
410
422
  // (each law not kept an even share of what is left a round)
423
+ let carried = new Map();
411
424
  for (let round = 0; clock() < until; round++) {
412
- const { instances, certs } = keptProof(), failed = new Set(), share = (until - clock()) / Math.max(1, set.filter(l => !kept.has(l.name)).length);
425
+ const { instances, certs } = keptProof(), failed = new Set(), proofs = new Map(), share = (until - clock()) / Math.max(1, set.filter(l => !kept.has(l.name) && !carried.has(l.name)).length);
413
426
  // (the callers last, so they meet every support kept so far)
414
427
  for (const law of [...set.filter(l => !caller.includes(l)), ...set.filter(l => caller.includes(l))]) {
415
428
  if (clock() > until)
416
429
  return { proven: false, laws: set, m, why: 'time' };
417
430
  if (kept.has(law.name))
418
431
  continue;
419
- let r = traced(law, set, 0, share);
432
+ const was = carried.get(law.name);
433
+ let r = was ? { proof: was } : traced(law, set, 0, share);
420
434
  if (!('proof' in r) && counted)
421
435
  r = traced(law, set, 1, share);
422
436
  if (!('proof' in r)) {
423
437
  failed.add(law.name);
424
438
  continue;
425
439
  }
440
+ proofs.set(law.name, r.proof);
426
441
  instances[law.name] = r.proof.instances;
427
442
  Object.assign(certs, r.proof.certs);
428
443
  }
@@ -434,6 +449,9 @@ function searchCounted0(m0, caller, ms = 60_000) {
434
449
  // (only callers fail: drop nothing more, give up)
435
450
  if (next.length === set.length)
436
451
  return { proven: false, laws: set, m, why: `not proven: ${[...failed].join(', ')}` };
452
+ // (a proof that assumes no law dropped at any key is one over the rest: its goals are the same; the kernel checks all)
453
+ const dropped = set.filter(l => !next.includes(l));
454
+ carried = new Map([...proofs].filter(([, pr]) => dropped.every(d => d.forall && !pr.instances[d.name]?.length)));
437
455
  set = next;
438
456
  }
439
457
  return { proven: false, laws: set, m, why: 'time' };
@@ -262,6 +262,7 @@ export type Measure = {
262
262
  export type Termination = {
263
263
  measure: Measure;
264
264
  text: string;
265
+ invariant?: Y;
265
266
  obligations: {
266
267
  law: DataLaw;
267
268
  proof?: CyclicVerdict;
@@ -273,10 +274,14 @@ export type Termination = {
273
274
  };
274
275
  export declare const terminationMs: {
275
276
  ms: number;
277
+ }, guardedMs: {
278
+ ms: number;
276
279
  };
277
280
  export declare const showMeasure: (f: Pick<Fn, "params">, m: Measure) => string;
278
281
  export declare function measureX(f: Pick<Fn, 'params'>, c: Measure['comps'][number], args: X[]): X;
279
- export declare function checkMeasures(fns: Fn[], ms: Measure[], budget?: number): {
282
+ export type Inv = (Y | undefined)[];
283
+ export declare const valueVar: (f: Pick<Fn, "name">) => string;
284
+ export declare function checkMeasures(fns: Fn[], ms: Measure[], budget?: number, inv?: Inv): {
280
285
  proven: true;
281
286
  obligations: Termination['obligations'][];
282
287
  } | {