tslaws 1.0.0 → 1.2.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 (51) hide show
  1. package/README.md +183 -187
  2. package/dist/api.d.ts +86 -0
  3. package/dist/api.js +78 -0
  4. package/dist/badge.d.ts +111 -0
  5. package/dist/badge.js +288 -0
  6. package/dist/browser.d.ts +5 -2
  7. package/dist/browser.js +403 -173
  8. package/dist/browserApi.d.ts +305 -0
  9. package/dist/browserApi.js +456 -0
  10. package/dist/browserServer.d.ts +13 -0
  11. package/dist/browserServer.js +406 -0
  12. package/dist/certificates.js +50 -28
  13. package/dist/chc.d.ts +13 -1
  14. package/dist/chc.js +40 -8
  15. package/dist/check.js +64 -36
  16. package/dist/cli.d.ts +16 -0
  17. package/dist/cli.js +78 -1
  18. package/dist/compile.js +46 -5
  19. package/dist/coverage.d.ts +17 -0
  20. package/dist/coverage.js +297 -24
  21. package/dist/derived.d.ts +2 -0
  22. package/dist/derived.js +9 -4
  23. package/dist/generators.d.ts +5 -1
  24. package/dist/generators.js +50 -4
  25. package/dist/githubCli.js +88 -15
  26. package/dist/isolate.d.ts +5 -0
  27. package/dist/isolate.js +1 -1
  28. package/dist/lawHost.d.ts +2 -0
  29. package/dist/lawHost.js +32 -21
  30. package/dist/lawRuntime.d.ts +6 -0
  31. package/dist/lawRuntime.js +86 -7
  32. package/dist/nativeZ3.d.ts +11 -0
  33. package/dist/nativeZ3.js +162 -0
  34. package/dist/plan.d.ts +7 -0
  35. package/dist/plan.js +11 -0
  36. package/dist/pluginHooks.d.ts +4 -0
  37. package/dist/pluginHooks.js +13 -4
  38. package/dist/proofCache.d.ts +24 -0
  39. package/dist/proofCache.js +135 -0
  40. package/dist/property.d.ts +2 -2
  41. package/dist/property.js +33 -8
  42. package/dist/propertyWorker.js +14 -8
  43. package/dist/sandbox.d.ts +1 -1
  44. package/dist/sandbox.js +48 -8
  45. package/dist/seal.js +47 -8
  46. package/dist/smt.d.ts +16 -2
  47. package/dist/smt.js +241 -31
  48. package/dist/symbolic.d.ts +38 -3
  49. package/dist/symbolic.js +504 -47
  50. package/dist/types.d.ts +9 -0
  51. package/package.json +7 -7
package/dist/smt.js CHANGED
@@ -12,16 +12,18 @@
12
12
  //
13
13
  // Numbers are IEEE doubles; a parameter typed `number` is a finite double (the generators exclude NaN and the
14
14
  // infinities too). A parameter typed `int` (from 'tslaws') or `bigint` is an exact integer.
15
- import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
15
+ import { mkdirSync, writeFileSync } from 'node:fs';
16
16
  import { Worker } from 'node:worker_threads';
17
17
  import { budget, jobs, WorkerPool } from "./pool.js";
18
18
  import { dirname, join } from 'node:path';
19
19
  import ts from 'typescript';
20
20
  import { certificateName, certify, certifyHorn, problemText, } from "./certificates.js";
21
- import { hornText, runExternalSolvers, solveHorn } from "./chc.js";
21
+ import { hornText, runExternalSolvers, SolverCrash, solveHorn, } from "./chc.js";
22
22
  import { lawKey } from "./lock.js";
23
+ import { closeNativeZ3, nativeZ3Path, solveNative } from "./nativeZ3.js";
24
+ import { proofCacheKey } from "./proofCache.js";
23
25
  import { SolverUnavailable, secondOpinion } from "./solvers.js";
24
- import { Executor, SpuriousModel, Unsupported, and, not } from "./symbolic.js";
26
+ import { Executor, readParsedJs, SpuriousModel, Unsupported, and, not, } from "./symbolic.js";
25
27
  import { plural } from "./plural.js";
26
28
  /** How many elements of an array of any length a counterexample can show; a longer one is left to the bounded proof. */
27
29
  const shownElements = 16;
@@ -56,7 +58,17 @@ class Declarations {
56
58
  /** JavaScript strings stop near 2^29 units; a longer one would also push their lengths out of the safe integers. */
57
59
  const maxStringLength = 536870888;
58
60
  function sequenceElement(shape) {
59
- return shape === 'int' ? 'int' : shape === 'bigint' ? 'big' : shape === 'boolean' ? 'bool' : undefined;
61
+ if (shape === 'int' ||
62
+ shape === 'nat' ||
63
+ shape === 'posInt' ||
64
+ shape === 'nonZeroInt' ||
65
+ (typeof shape === 'object' && shape !== undefined && 'intRange' in shape))
66
+ return 'int';
67
+ return shape === 'bigint' ? 'big' : shape === 'boolean' ? 'bool' : undefined;
68
+ }
69
+ function intAtom(n) {
70
+ const b = BigInt(n);
71
+ return b < 0n ? `(- ${-b})` : `${b}`;
60
72
  }
61
73
  function declareParam(name, shape, bound, decl, intLimit, theory) {
62
74
  if (shape === 'number') {
@@ -69,6 +81,30 @@ function declareParam(name, shape, bound, decl, intLimit, theory) {
69
81
  decl.assumptions.push(intLimit === undefined ? safeRange(name) : `(and (<= (- ${intLimit}) ${name}) (<= ${name} ${intLimit}))`);
70
82
  return { k: 'int', t: name };
71
83
  }
84
+ if (shape === 'nat') {
85
+ decl.constant(name, 'int');
86
+ const hi = intLimit ?? 9007199254740991n;
87
+ decl.assumptions.push(`(and (<= 0 ${name}) (<= ${name} ${hi}))`);
88
+ return { k: 'int', t: name };
89
+ }
90
+ if (shape === 'posInt') {
91
+ decl.constant(name, 'int');
92
+ const hi = intLimit ?? 9007199254740991n;
93
+ decl.assumptions.push(`(and (<= 1 ${name}) (<= ${name} ${hi}))`);
94
+ return { k: 'int', t: name };
95
+ }
96
+ if (shape === 'nonZeroInt') {
97
+ decl.constant(name, 'int');
98
+ const range = intLimit === undefined ? safeRange(name) : `(and (<= (- ${intLimit}) ${name}) (<= ${name} ${intLimit}))`;
99
+ decl.assumptions.push(`(and ${range} (not (= ${name} 0)))`);
100
+ return { k: 'int', t: name };
101
+ }
102
+ if (typeof shape === 'object' && shape !== undefined && 'intRange' in shape) {
103
+ decl.constant(name, 'int');
104
+ const [lo, hi] = shape.intRange;
105
+ decl.assumptions.push(`(and (<= ${intAtom(lo)} ${name}) (<= ${name} ${intAtom(hi)}))`);
106
+ return { k: 'int', t: name };
107
+ }
72
108
  if (shape === 'bigint') {
73
109
  decl.constant(name, 'int');
74
110
  return { k: 'big', t: name };
@@ -84,6 +120,18 @@ function declareParam(name, shape, bound, decl, intLimit, theory) {
84
120
  decl.assumptions.push(`(<= (str.len ${name}) ${maxStringLength})`);
85
121
  return { k: 'str', t: name };
86
122
  }
123
+ if (shape === 'asciiString') {
124
+ decl.constant(name, 'str');
125
+ decl.assumptions.push(`(str.in_re ${name} (re.* (re.range "\\u{0}" "\\u{7f}")))`);
126
+ decl.assumptions.push(`(<= (str.len ${name}) ${maxStringLength})`);
127
+ return { k: 'str', t: name };
128
+ }
129
+ if (shape === 'nonEmptyString') {
130
+ decl.constant(name, 'str');
131
+ decl.assumptions.push(`(str.in_re ${name} (re.* (re.range "\\u{0}" "\\u{ffff}")))`);
132
+ decl.assumptions.push(`(and (<= 1 (str.len ${name})) (<= (str.len ${name}) ${maxStringLength}))`);
133
+ return { k: 'str', t: name };
134
+ }
87
135
  if (shape === undefined)
88
136
  throw new Unsupported('a parameter type is not modelled');
89
137
  if ('array' in shape && theory) {
@@ -91,12 +139,15 @@ function declareParam(name, shape, bound, decl, intLimit, theory) {
91
139
  if (elem === undefined)
92
140
  throw new Unsupported('arrays of this element type are proved only within the bound');
93
141
  decl.sequence(name, elem);
142
+ if (shape.minLength !== undefined && shape.minLength > 0)
143
+ decl.assumptions.push(`(<= ${shape.minLength} ${name}__len)`);
94
144
  return { k: 'seq', len: { k: 'int', t: `${name}__len` }, data: `${name}__data`, elem, id: { escaped: true } };
95
145
  }
96
146
  if ('array' in shape) {
97
147
  const len = `${name}__len`;
98
148
  decl.constant(len, 'int');
99
- decl.assumptions.push(`(and (<= 0 ${len}) (<= ${len} ${bound}))`);
149
+ const minLen = shape.minLength ?? 0;
150
+ decl.assumptions.push(`(and (<= ${minLen} ${len}) (<= ${len} ${bound}))`);
100
151
  const slots = [];
101
152
  for (let i = 0; i < bound; i += 1)
102
153
  slots.push(declareParam(`${name}__${i}`, shape.array, bound, decl, intLimit, theory));
@@ -208,13 +259,18 @@ function modelValue(sort, e) {
208
259
  return toDouble([n, d]);
209
260
  }
210
261
  function jsValue(shape, name, model) {
211
- if (shape === 'number' || shape === 'int')
262
+ if (shape === 'number' ||
263
+ shape === 'int' ||
264
+ shape === 'nat' ||
265
+ shape === 'posInt' ||
266
+ shape === 'nonZeroInt' ||
267
+ (typeof shape === 'object' && shape !== undefined && 'intRange' in shape))
212
268
  return Number(model.get(name) ?? 0);
213
269
  if (shape === 'bigint')
214
270
  return BigInt(model.get(name) ?? 0);
215
271
  if (shape === 'boolean')
216
272
  return model.get(name) === true;
217
- if (shape === 'string')
273
+ if (shape === 'string' || shape === 'asciiString' || shape === 'nonEmptyString')
218
274
  return String(model.get(name) ?? '');
219
275
  if (shape === undefined)
220
276
  return undefined;
@@ -238,24 +294,51 @@ function startWorker() {
238
294
  return w;
239
295
  }
240
296
  // Each Z3 instance holds a large WebAssembly heap; more than four at once run out of memory on the bigger queries.
241
- const solvers = new WorkerPool(startWorker, () => Math.min(4, jobs()));
297
+ let spawnWorker = startWorker;
298
+ const solvers = new WorkerPool(() => spawnWorker(), () => Math.min(4, jobs()));
299
+ /**
300
+ * Starts the Z3 workers with `start` from now on and ends the idle ones, which were started the old way; the returned
301
+ * function puts the first way back. For tests that make a worker crash.
302
+ */
303
+ export function startSolverWorkersWith(start) {
304
+ const before = spawnWorker;
305
+ spawnWorker = start;
306
+ solvers.close();
307
+ return () => {
308
+ spawnWorker = before;
309
+ solvers.close();
310
+ };
311
+ }
242
312
  /**
243
313
  * Runs the query, and runs it again in a fresh worker when the solver itself fell over (a WebAssembly allocation that
244
- * fails on a machine short of memory). A query that merely ran too long is not retried: it would only run long again.
314
+ * fails on a machine short of memory). Idle workers are ended first, so the retry has their memory. A query that merely
315
+ * ran too long is not retried: it would only run long again. A crash that outlasts the retries throws `SolverCrash`,
316
+ * never `Unsupported`, so a proof cannot take it for a solver that gave up.
245
317
  */
246
318
  export async function solve(query, values, timeoutMs) {
319
+ const native = spawnWorker === startWorker ? nativeZ3Path() : undefined;
247
320
  for (let attempt = 0;; attempt += 1) {
248
321
  try {
249
322
  // A solve is a slot of the budget (the law's own, when it runs under one).
250
- return await budget.run(() => solveOnce(query, values, timeoutMs));
323
+ return await budget.run(() => native !== undefined
324
+ ? solveNative(native, query, values, timeoutMs, () => new Unsupported(`the solver did not stop within ${timeoutMs} ms and was terminated`))
325
+ : solveOnce(query, values, timeoutMs));
251
326
  }
252
327
  catch (error) {
253
- if (attempt >= 2 || !(error instanceof Unsupported) || !error.message.startsWith('the solver crashed'))
328
+ if (!(error instanceof SolverCrash))
254
329
  throw error;
330
+ if (attempt >= crashRetries)
331
+ throw new SolverCrash(`${error.message} (the query was tried on ${plural(attempt + 1, 'fresh worker')})`);
332
+ if (native !== undefined)
333
+ closeNativeZ3();
334
+ else
335
+ solvers.close();
255
336
  await new Promise((done) => setTimeout(done, 400 * (attempt + 1)));
256
337
  }
257
338
  }
258
339
  }
340
+ /** How many times a query is run again after the solver crashed. */
341
+ const crashRetries = 2;
259
342
  /** One try: gives up on the whole worker after the timeout plus a grace period. */
260
343
  async function solveOnce(query, values, timeoutMs) {
261
344
  const current = await solvers.acquire();
@@ -265,6 +348,7 @@ async function solveOnce(query, values, timeoutMs) {
265
348
  clearTimeout(timer);
266
349
  current.off('message', onMessage);
267
350
  current.off('error', onError);
351
+ current.off('exit', onExit);
268
352
  };
269
353
  const kill = () => {
270
354
  solvers.discard(current);
@@ -280,7 +364,7 @@ async function solveOnce(query, values, timeoutMs) {
280
364
  drop();
281
365
  if (reply.error !== undefined) {
282
366
  kill();
283
- reject(new Unsupported(`the solver crashed: ${reply.error}`));
367
+ reject(new SolverCrash(`the Z3 solver crashed: ${reply.error}`));
284
368
  }
285
369
  else {
286
370
  solvers.release(current);
@@ -290,10 +374,17 @@ async function solveOnce(query, values, timeoutMs) {
290
374
  const onError = (error) => {
291
375
  drop();
292
376
  kill();
293
- reject(new Unsupported(`the solver crashed: ${error.message}`));
377
+ reject(new SolverCrash(`the Z3 solver crashed: ${error.message}`));
378
+ };
379
+ // A worker that ends without a word (an abort inside WebAssembly) would otherwise be waited for until the timeout.
380
+ const onExit = (code) => {
381
+ drop();
382
+ kill();
383
+ reject(new SolverCrash(`the Z3 solver crashed: its worker exited with code ${code}`));
294
384
  };
295
385
  current.on('message', onMessage);
296
386
  current.on('error', onError);
387
+ current.on('exit', onExit);
297
388
  current.postMessage({ id, query, values });
298
389
  });
299
390
  }
@@ -301,7 +392,7 @@ function resultOf(value) {
301
392
  return value.k === 'bool' ? value.t : 'true';
302
393
  }
303
394
  function containsArray(shape) {
304
- if (shape === undefined || typeof shape === 'string')
395
+ if (shape === undefined || typeof shape === 'string' || 'intRange' in shape)
305
396
  return false;
306
397
  if ('array' in shape)
307
398
  return true;
@@ -324,13 +415,13 @@ export function assumptionsFor(shapes, intLimit) {
324
415
  const visit = (shape) => {
325
416
  if (shape === 'number')
326
417
  found.add(numberAssumption);
327
- else if (shape === 'int') {
418
+ else if (shape === 'int' || shape === 'nat' || shape === 'posInt' || shape === 'nonZeroInt') {
328
419
  if (intLimit === undefined)
329
420
  found.add(intAssumption);
330
421
  }
331
- else if (shape === 'string')
422
+ else if (shape === 'string' || shape === 'asciiString' || shape === 'nonEmptyString')
332
423
  found.add(stringAssumption);
333
- else if (shape === undefined || typeof shape === 'string')
424
+ else if (shape === undefined || typeof shape === 'string' || 'intRange' in shape)
334
425
  return;
335
426
  else if ('array' in shape)
336
427
  visit(shape.array);
@@ -361,15 +452,18 @@ export async function proveLaw(input) {
361
452
  catch (error) {
362
453
  if (error instanceof Unsupported)
363
454
  return { kind: 'unsupported', reason: error.message };
455
+ // Not `unsupported`: that would let a law that was merely not proved because Z3 fell over pass as tested.
456
+ if (error instanceof SolverCrash)
457
+ return { kind: 'error', message: error.message };
364
458
  if (error instanceof SolverUnavailable)
365
459
  return { kind: 'error', message: error.message };
366
460
  throw error;
367
461
  }
368
462
  }
369
463
  function containsInt(shape) {
370
- if (shape === 'int')
464
+ if (shape === 'int' || shape === 'nat' || shape === 'posInt' || shape === 'nonZeroInt')
371
465
  return true;
372
- if (shape === undefined || typeof shape === 'string')
466
+ if (shape === undefined || typeof shape === 'string' || 'intRange' in shape)
373
467
  return false;
374
468
  if ('array' in shape)
375
469
  return containsInt(shape.array);
@@ -380,7 +474,7 @@ function keepOf(input, certify) {
380
474
  return { dir: certify.dir, root: certify.root, name: certificateName(lawKey(input.law.file, input.law.name)) };
381
475
  }
382
476
  function buildProblem(input, intLimit, theory) {
383
- const source = ts.createSourceFile(input.jsFile, readFileSync(input.jsFile, 'utf8'), ts.ScriptTarget.ES2022, true, ts.ScriptKind.JS);
477
+ const source = readParsedJs(input.jsFile);
384
478
  const fn = source.statements.find((s) => ts.isFunctionDeclaration(s) && s.name?.text === (input.law.symbol ?? input.law.name));
385
479
  if (fn === undefined || fn.body === undefined)
386
480
  throw new Unsupported('law function not found in the compiled output');
@@ -499,18 +593,96 @@ async function attemptWith(input, intLimit, theory) {
499
593
  // Cvc5 does not solve Horn clauses, so a proof it must confirm is left to the bounded way.
500
594
  if (input.solvers?.includes('cvc5'))
501
595
  return undefined;
502
- const verdict = await solveHorn(hornSystem(executor, decl, facts, holds, safe), { z3: solve, external: runExternalSolvers }, input.timeoutMs);
596
+ const system = hornSystem(executor, decl, facts, holds, safe);
597
+ const keep = input.certify === undefined || input.certify.mode === false ? undefined : keepOf(input, input.certify);
598
+ const cacheKey = input.cache === undefined
599
+ ? undefined
600
+ : proofCacheKey({
601
+ query: hornText(system),
602
+ bounded: executor.bounded,
603
+ assumptions: assumptionsFor(input.shapes, intLimit),
604
+ solvers: input.solvers,
605
+ certify: input.certify?.mode,
606
+ });
607
+ if (cacheKey !== undefined) {
608
+ const hit = input.cache.get(cacheKey, keep);
609
+ if (hit !== undefined)
610
+ return hit;
611
+ }
612
+ const verdict = await solveHorn(system, { z3: solve, external: runExternalSolvers }, input.timeoutMs);
503
613
  if (verdict.kind === 'disagree')
504
614
  return { kind: 'unsupported', reason: verdict.reason };
615
+ if (verdict.kind === 'crash')
616
+ throw new SolverCrash(verdict.reason);
505
617
  if (verdict.kind !== 'safe')
506
618
  return undefined;
507
619
  const assumptions = [...assumptionsFor(input.shapes, intLimit), ...verdict.invariants, ...verdict.notes];
508
620
  const certificate = await hornCertificate(input, verdict.certification);
509
- return executor.bounded.length > 0
621
+ const result = executor.bounded.length > 0
510
622
  ? { kind: 'bounded', limits: executor.bounded, assumptions, ...certificate }
511
623
  : { kind: 'proved', assumptions, ...certificate };
624
+ if (cacheKey !== undefined)
625
+ input.cache.set(cacheKey, result);
626
+ return result;
627
+ }
628
+ // Prove any intermediate `lemma(...)` subgoals first so assuming them in the main query is mathematically sound.
629
+ if (executor.subgoals.length > 0) {
630
+ const baseAssumptions = theory ? [] : decl.assumptions;
631
+ for (const subgoal of executor.subgoals) {
632
+ const subQuery = [
633
+ `(set-option :timeout ${input.timeoutMs})`,
634
+ ...decl.lines,
635
+ ...executor.freshDecls,
636
+ ...executor.defs,
637
+ ...baseAssumptions.map((a) => `(assert ${a})`),
638
+ ...subgoal.assumptions.map((a) => `(assert ${a})`),
639
+ `(assert (not ${subgoal.goal}))`,
640
+ '(check-sat)',
641
+ ].join('\n');
642
+ const watchSub = decl.constants.map((c) => {
643
+ const term = c.term ?? c.name;
644
+ return c.sort === 'fp' ? `(fp.to_real ${term})` : term;
645
+ });
646
+ const subValueQuery = watchSub.length === 0 ? '' : `(get-value (${watchSub.join(' ')}))`;
647
+ const sub = await solve(subQuery, subValueQuery, input.timeoutMs);
648
+ if (sub.out.startsWith('unsat'))
649
+ continue;
650
+ if (sub.out.startsWith('sat')) {
651
+ const values = watchSub.length === 0 ? '()' : sub.vals;
652
+ const pairs = parseSexp(values);
653
+ const model = new Map();
654
+ decl.constants.forEach((c, i) => {
655
+ const pair = pairs[i];
656
+ if (Array.isArray(pair) && pair.length === 2)
657
+ model.set(c.name, modelValue(c.sort, pair[1]));
658
+ });
659
+ if (!decl.lengths.some((len) => Number(model.get(len) ?? 0) > shownElements)) {
660
+ const inputs = names.map((name, i) => jsValue(input.shapes[i], name, model));
661
+ if (!(await input.holds(inputs)))
662
+ return { kind: 'refuted', model: names.map((n, i) => `${n} = ${show(inputs[i])}`).join(', '), inputs };
663
+ }
664
+ throw new Unsupported('a lemma() step could not be proved');
665
+ }
666
+ throw new Unsupported(`a lemma() step was not proved within ${input.timeoutMs} ms`);
667
+ }
512
668
  }
513
669
  const query = queryOf(input, problem);
670
+ const queryText = query.join('\n');
671
+ const keep = input.certify === undefined || input.certify.mode === false ? undefined : keepOf(input, input.certify);
672
+ const cacheKey = input.cache === undefined
673
+ ? undefined
674
+ : proofCacheKey({
675
+ query: problemText(queryText),
676
+ bounded: executor.bounded,
677
+ assumptions: assumptionsFor(input.shapes, intLimit),
678
+ solvers: input.solvers,
679
+ certify: input.certify?.mode,
680
+ });
681
+ if (cacheKey !== undefined) {
682
+ const hit = input.cache.get(cacheKey, keep);
683
+ if (hit !== undefined)
684
+ return hit;
685
+ }
514
686
  const watch = decl.constants.map((c) => {
515
687
  const term = c.term ?? c.name;
516
688
  return c.sort === 'fp' ? `(fp.to_real ${term})` : term;
@@ -519,22 +691,57 @@ async function attemptWith(input, intLimit, theory) {
519
691
  if (process.env.TSLAWS_DEBUG !== undefined) {
520
692
  const dir = join(dirname(input.jsFile), '..', 'smt');
521
693
  mkdirSync(dir, { recursive: true });
522
- writeFileSync(join(dir, `${input.law.name}.smt2`), `${query.join('\n')}\n(get-model)\n`);
694
+ writeFileSync(join(dir, `${input.law.name}.smt2`), `${queryText}\n(get-model)\n`);
523
695
  }
524
696
  const valueQuery = watch.length === 0 ? '' : `(get-value (${watch.join(' ')}))`;
525
- const { out, vals } = await solve(query.join('\n'), valueQuery, input.timeoutMs);
697
+ const { out, vals } = await solve(queryText, valueQuery, input.timeoutMs);
526
698
  const check = out;
527
699
  if (check.startsWith('unsat')) {
700
+ // Vacuity check (like Dafny/Verus/Kani): ensure assume() preconditions are satisfiable so assume(false) can never prove a law.
701
+ const userAssumptions = executor.assumptions.filter((a) => !executor.lemmaAssumptions.has(a));
702
+ if (userAssumptions.length > 0) {
703
+ const vacQuery = [
704
+ '(set-option :produce-models false)',
705
+ ...decl.lines,
706
+ ...executor.freshDecls,
707
+ ...executor.defs,
708
+ ...decl.assumptions.map((a) => `(assert ${a})`),
709
+ ...userAssumptions.map((a) => `(assert ${a})`),
710
+ '(check-sat)',
711
+ ].join('\n');
712
+ const vac = await solve(vacQuery, '', input.timeoutMs);
713
+ if (vac.out.startsWith('unsat'))
714
+ throw new Unsupported('assumptions are unsatisfiable (vacuous law — no input satisfies assume())');
715
+ }
528
716
  const assumptions = assumptionsFor(input.shapes, intLimit);
529
- const text = query.join('\n');
530
- const certifyQuery = async () => input.certify === undefined || input.certify.mode === false
531
- ? {}
532
- : { certificate: await certify(text, { timeoutMs: input.timeoutMs, keep: keepOf(input, input.certify) }) };
533
- if (executor.bounded.length > 0)
534
- return { kind: 'bounded', limits: executor.bounded, assumptions, ...(await certifyQuery()) };
717
+ // For independent certification/second-opinion, omit lemma assumptions so cvc5/Carcara proves the full claim directly.
718
+ const text = executor.lemmaAssumptions.size === 0
719
+ ? queryText
720
+ : queryOf(input, {
721
+ ...problem,
722
+ facts: problem.facts.filter((f) => !executor.lemmaAssumptions.has(f)),
723
+ }).join('\n');
724
+ const certifyQuery = async () => {
725
+ if (input.certify === undefined || input.certify.mode === false)
726
+ return {};
727
+ if (executor.usedInduction)
728
+ return {
729
+ certificate: {
730
+ status: 'uncertified',
731
+ reason: 'induct() subgoals are proved by Z3; standalone Carcara certificate export for induction is not yet emitted',
732
+ },
733
+ };
734
+ return { certificate: await certify(text, { timeoutMs: input.timeoutMs, keep: keepOf(input, input.certify) }) };
735
+ };
736
+ if (executor.bounded.length > 0) {
737
+ const result = { kind: 'bounded', limits: executor.bounded, assumptions, ...(await certifyQuery()) };
738
+ if (cacheKey !== undefined)
739
+ input.cache.set(cacheKey, result);
740
+ return result;
741
+ }
535
742
  // Only a proof that would stand is sent to the second solver.
536
743
  const unconfirmed = await secondOpinion(input.solvers ?? [], text, input.timeoutMs);
537
- return unconfirmed === undefined
744
+ const result = unconfirmed === undefined
538
745
  ? { kind: 'proved', assumptions, ...(await certifyQuery()) }
539
746
  : {
540
747
  kind: 'bounded',
@@ -545,6 +752,9 @@ async function attemptWith(input, intLimit, theory) {
545
752
  ? {}
546
753
  : { certificate: { status: 'uncertified', reason: unconfirmed } }),
547
754
  };
755
+ if (cacheKey !== undefined && unconfirmed === undefined)
756
+ input.cache.set(cacheKey, result);
757
+ return result;
548
758
  }
549
759
  if (check.startsWith('unknown'))
550
760
  throw new Unsupported(`solver gave up within ${input.timeoutMs} ms`);
@@ -65,16 +65,29 @@ interface FileIndex {
65
65
  imports: Map<string, string>;
66
66
  /** Module-level `const NAME = ...` and `exports.NAME = ...` initializers, evaluated on demand. */
67
67
  constants: Map<string, ts.Expression>;
68
+ /** Re-exported bindings (`Object.defineProperty(exports, "X", { get: () => mod_1.Y })` or `exports.X = mod_1.Y`). */
69
+ reexports: Map<string, {
70
+ file: string;
71
+ name: string;
72
+ }>;
73
+ /** Star re-exports (`__exportStar(require("./sub"), exports)`). */
74
+ stars: string[];
68
75
  }
76
+ /** Resolves a relative CommonJS specifier the way Node does: `base.js`, else `base/index.js`. */
77
+ export declare function resolveRelativeJs(fromFile: string, specifier: string): string;
78
+ /** Reads and parses a compiled `.js` file, reusing the AST while its size and modification time are unchanged. */
79
+ export declare function readParsedJs(file: string): ts.SourceFile;
69
80
  declare class Frame {
70
81
  env: Map<string, Value>;
71
82
  done: string;
72
83
  brk: string;
73
84
  cnt: string;
74
85
  ret: Value | undefined;
86
+ fnKey: string | undefined;
87
+ decreases: Int | Big | undefined;
75
88
  readonly file: string;
76
89
  readonly depth: number;
77
- constructor(file: string, depth: number);
90
+ constructor(file: string, depth: number, fnKey?: string);
78
91
  fork(): Frame;
79
92
  }
80
93
  export declare const bool: (t: string) => Bool;
@@ -93,6 +106,17 @@ export declare class Executor {
93
106
  private havocked;
94
107
  readonly assumptions: string[];
95
108
  readonly obligations: string[];
109
+ /** Intermediate proof steps from `lemma(...)` / `calc(...)` / `induct(...)`: each is proved under prior assumptions. */
110
+ readonly subgoals: {
111
+ assumptions: string[];
112
+ goal: string;
113
+ }[];
114
+ /** Assumptions introduced by `lemma(...)` / `calc(...)` (omitted when sending the whole query to an independent certifier). */
115
+ readonly lemmaAssumptions: Set<string>;
116
+ /** True when `induct()` discharged the claim via base + inductive step subgoals. */
117
+ usedInduction: boolean;
118
+ /** Active call frames for checking recursive `decreases(...)` termination measures. */
119
+ private readonly callFrames;
96
120
  readonly bounded: string[];
97
121
  /** Advice for the reader when a proof fails on an obligation (a divisor that may be 0). */
98
122
  readonly hints: string[];
@@ -116,7 +140,7 @@ export declare class Executor {
116
140
  readonly bound: number;
117
141
  constructor(bound: number);
118
142
  index(file: string): FileIndex;
119
- /** `exports.NAME = value` assigned exactly once, at the top level, is a constant; any other assignment spoils it. */
143
+ /** `exports.NAME = value` assigned exactly once, at the top level, is a constant; also records CommonJS re-exports. */
120
144
  private indexExports;
121
145
  private readonly constantValues;
122
146
  private readonly resolving;
@@ -151,7 +175,7 @@ export declare class Executor {
151
175
  private branch;
152
176
  private forStatement;
153
177
  private loop;
154
- /** The `invariant(...)` calls leading a loop body, and the statements after them. */
178
+ /** The `invariant(...)` and `decreases(...)` calls leading a loop body, and the statements after them. */
155
179
  private invariantsOf;
156
180
  private calleeOf;
157
181
  /** The names a piece of code assigns, increments or mutates. */
@@ -246,6 +270,17 @@ export declare class Executor {
246
270
  /** `forall(xs, p)` / `exists(xs, p)` over the slots of the array model, so a claim about them is bounded like the array. */
247
271
  private quantifier;
248
272
  private assumeCall;
273
+ private lemmaCall;
274
+ private requiresCall;
275
+ private impliesCall;
276
+ private iffCall;
277
+ private distinctCall;
278
+ private unreachableCall;
279
+ private calcCall;
280
+ private inductCall;
281
+ private ensuresCall;
282
+ private decreasesCall;
283
+ private resolveFunction;
249
284
  private callProject;
250
285
  private math;
251
286
  private mathRaw;