tslaws 1.1.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.
package/dist/seal.js CHANGED
@@ -30,7 +30,7 @@ import { readResolution, resolutionCompilerOptions } from "./tsconfigResolve.js"
30
30
  const digest = (data) => createHash('sha256').update(data).digest('hex');
31
31
  /** The code as its tokens joined by one space: no comments or layout, every literal exact. */
32
32
  function tokensOf(text, fileName) {
33
- const source = ts.createSourceFile(fileName, text, ts.ScriptTarget.Latest, true);
33
+ const source = ts.createSourceFile(fileName, text, ts.ScriptTarget.Latest, false);
34
34
  const tokens = [];
35
35
  const visit = (node) => {
36
36
  if (node.kind >= ts.SyntaxKind.FirstJSDocNode && node.kind <= ts.SyntaxKind.LastJSDocNode)
@@ -45,14 +45,55 @@ function tokensOf(text, fileName) {
45
45
  return tokens.join(' ');
46
46
  }
47
47
  const scripts = /\.(?:[cm]?[jt]sx?)$/;
48
+ /** Stat-validated cache for file digests and module specifiers so unchanged files aren't re-parsed across checks. */
49
+ const digestCache = new Map();
50
+ const specifierCache = new Map();
48
51
  /** The line endings of a checkout must not matter, so text is read with `\n`. */
49
52
  const readText = (path) => readFileSync(path, 'utf8').replaceAll('\r\n', '\n');
50
53
  /** A file's digest: the tokens of a script, the text of any other text file, the bytes of a binary one. */
51
54
  function digestOf(path) {
55
+ let st;
56
+ try {
57
+ st = statSync(path);
58
+ const cached = digestCache.get(path);
59
+ if (cached !== undefined && cached.size === st.size && cached.mtimeMs === st.mtimeMs)
60
+ return cached.digest;
61
+ }
62
+ catch {
63
+ // Fall through to readFileSync which throws if unreadable.
64
+ }
65
+ let result;
52
66
  if (scripts.test(path))
53
- return digest(tokensOf(readText(path), path));
54
- const bytes = readFileSync(path);
55
- return digest(bytes.includes(0) ? bytes : bytes.toString('utf8').replaceAll('\r\n', '\n'));
67
+ result = digest(tokensOf(readText(path), path));
68
+ else {
69
+ const bytes = readFileSync(path);
70
+ result = digest(bytes.includes(0) ? bytes : bytes.toString('utf8').replaceAll('\r\n', '\n'));
71
+ }
72
+ if (st !== undefined) {
73
+ if (digestCache.size > 4000)
74
+ digestCache.clear();
75
+ digestCache.set(path, { size: st.size, mtimeMs: st.mtimeMs, digest: result });
76
+ }
77
+ return result;
78
+ }
79
+ function cachedSpecifiers(path) {
80
+ let st;
81
+ try {
82
+ st = statSync(path);
83
+ const cached = specifierCache.get(path);
84
+ if (cached !== undefined && cached.size === st.size && cached.mtimeMs === st.mtimeMs)
85
+ return cached.specifiers;
86
+ }
87
+ catch {
88
+ // Fall through.
89
+ }
90
+ const specifiers = moduleSpecifiers(readText(path), path).map((s) => s.value);
91
+ if (st !== undefined) {
92
+ if (specifierCache.size > 4000)
93
+ specifierCache.clear();
94
+ specifierCache.set(path, { size: st.size, mtimeMs: st.mtimeMs, specifiers });
95
+ }
96
+ return specifiers;
56
97
  }
57
98
  const builtins = new Set(builtinModules);
58
99
  const underNodeModules = /(?:^|[\\/])node_modules[\\/]/;
@@ -137,7 +178,7 @@ class Linker {
137
178
  if (installed !== undefined && installed !== 'linked')
138
179
  externals.push(registry(installed, specifier));
139
180
  const found = ts.resolveModuleName(specifier, from, this.options, ts.sys).resolvedModule;
140
- const typesOnly = builtin && found !== undefined && /[\/]node_modules[\/]@types[\/]/.test(realOf(found.resolvedFileName));
181
+ const typesOnly = builtin && found !== undefined && /[/]node_modules[/]@types[/]/.test(realOf(found.resolvedFileName));
141
182
  if (found !== undefined && existsSync(found.resolvedFileName) && !typesOnly) {
142
183
  const real = realOf(found.resolvedFileName);
143
184
  if (underNodeModules.test(real)) {
@@ -299,9 +340,7 @@ class Sealer {
299
340
  try {
300
341
  found = {
301
342
  digest: digestOf(path),
302
- links: scripts.test(path)
303
- ? moduleSpecifiers(readText(path), path).map((s) => this.linker.link(s.value, path))
304
- : [],
343
+ links: scripts.test(path) ? cachedSpecifiers(path).map((s) => this.linker.link(s, path)) : [],
305
344
  };
306
345
  }
307
346
  catch {
package/dist/smt.d.ts CHANGED
@@ -1,9 +1,13 @@
1
1
  import { Worker } from 'node:worker_threads';
2
2
  import { type Certificate, type CertifyMode } from './certificates.ts';
3
+ import { type ProofCache } from './proofCache.ts';
3
4
  import { type SolverName } from './solvers.ts';
4
5
  import type { ManifestLaw } from './types.ts';
5
- export type Shape = 'number' | 'int' | 'bigint' | 'boolean' | 'string' | {
6
+ export type Shape = 'number' | 'int' | 'nat' | 'posInt' | 'nonZeroInt' | {
7
+ intRange: [number, number];
8
+ } | 'bigint' | 'boolean' | 'string' | 'asciiString' | 'nonEmptyString' | {
6
9
  array: Shape;
10
+ minLength?: number;
7
11
  } | {
8
12
  fields: Record<string, Shape>;
9
13
  } | undefined;
@@ -51,6 +55,8 @@ export interface ProveInput {
51
55
  dir: string;
52
56
  root: string;
53
57
  };
58
+ /** Optional proof & certificate result cache keyed by exact SMT-LIB problem hash. */
59
+ cache?: ProofCache;
54
60
  }
55
61
  /**
56
62
  * Starts the Z3 workers with `start` from now on and ends the idle ones, which were started the old way; the returned
package/dist/smt.js CHANGED
@@ -12,7 +12,7 @@
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';
@@ -20,8 +20,10 @@ import ts from 'typescript';
20
20
  import { certificateName, certify, certifyHorn, problemText, } from "./certificates.js";
21
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;
@@ -260,17 +316,23 @@ export function startSolverWorkersWith(start) {
260
316
  * never `Unsupported`, so a proof cannot take it for a solver that gave up.
261
317
  */
262
318
  export async function solve(query, values, timeoutMs) {
319
+ const native = spawnWorker === startWorker ? nativeZ3Path() : undefined;
263
320
  for (let attempt = 0;; attempt += 1) {
264
321
  try {
265
322
  // A solve is a slot of the budget (the law's own, when it runs under one).
266
- 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));
267
326
  }
268
327
  catch (error) {
269
328
  if (!(error instanceof SolverCrash))
270
329
  throw error;
271
330
  if (attempt >= crashRetries)
272
331
  throw new SolverCrash(`${error.message} (the query was tried on ${plural(attempt + 1, 'fresh worker')})`);
273
- solvers.close();
332
+ if (native !== undefined)
333
+ closeNativeZ3();
334
+ else
335
+ solvers.close();
274
336
  await new Promise((done) => setTimeout(done, 400 * (attempt + 1)));
275
337
  }
276
338
  }
@@ -330,7 +392,7 @@ function resultOf(value) {
330
392
  return value.k === 'bool' ? value.t : 'true';
331
393
  }
332
394
  function containsArray(shape) {
333
- if (shape === undefined || typeof shape === 'string')
395
+ if (shape === undefined || typeof shape === 'string' || 'intRange' in shape)
334
396
  return false;
335
397
  if ('array' in shape)
336
398
  return true;
@@ -353,13 +415,13 @@ export function assumptionsFor(shapes, intLimit) {
353
415
  const visit = (shape) => {
354
416
  if (shape === 'number')
355
417
  found.add(numberAssumption);
356
- else if (shape === 'int') {
418
+ else if (shape === 'int' || shape === 'nat' || shape === 'posInt' || shape === 'nonZeroInt') {
357
419
  if (intLimit === undefined)
358
420
  found.add(intAssumption);
359
421
  }
360
- else if (shape === 'string')
422
+ else if (shape === 'string' || shape === 'asciiString' || shape === 'nonEmptyString')
361
423
  found.add(stringAssumption);
362
- else if (shape === undefined || typeof shape === 'string')
424
+ else if (shape === undefined || typeof shape === 'string' || 'intRange' in shape)
363
425
  return;
364
426
  else if ('array' in shape)
365
427
  visit(shape.array);
@@ -399,9 +461,9 @@ export async function proveLaw(input) {
399
461
  }
400
462
  }
401
463
  function containsInt(shape) {
402
- if (shape === 'int')
464
+ if (shape === 'int' || shape === 'nat' || shape === 'posInt' || shape === 'nonZeroInt')
403
465
  return true;
404
- if (shape === undefined || typeof shape === 'string')
466
+ if (shape === undefined || typeof shape === 'string' || 'intRange' in shape)
405
467
  return false;
406
468
  if ('array' in shape)
407
469
  return containsInt(shape.array);
@@ -412,7 +474,7 @@ function keepOf(input, certify) {
412
474
  return { dir: certify.dir, root: certify.root, name: certificateName(lawKey(input.law.file, input.law.name)) };
413
475
  }
414
476
  function buildProblem(input, intLimit, theory) {
415
- const source = ts.createSourceFile(input.jsFile, readFileSync(input.jsFile, 'utf8'), ts.ScriptTarget.ES2022, true, ts.ScriptKind.JS);
477
+ const source = readParsedJs(input.jsFile);
416
478
  const fn = source.statements.find((s) => ts.isFunctionDeclaration(s) && s.name?.text === (input.law.symbol ?? input.law.name));
417
479
  if (fn === undefined || fn.body === undefined)
418
480
  throw new Unsupported('law function not found in the compiled output');
@@ -531,7 +593,23 @@ async function attemptWith(input, intLimit, theory) {
531
593
  // Cvc5 does not solve Horn clauses, so a proof it must confirm is left to the bounded way.
532
594
  if (input.solvers?.includes('cvc5'))
533
595
  return undefined;
534
- 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);
535
613
  if (verdict.kind === 'disagree')
536
614
  return { kind: 'unsupported', reason: verdict.reason };
537
615
  if (verdict.kind === 'crash')
@@ -540,11 +618,71 @@ async function attemptWith(input, intLimit, theory) {
540
618
  return undefined;
541
619
  const assumptions = [...assumptionsFor(input.shapes, intLimit), ...verdict.invariants, ...verdict.notes];
542
620
  const certificate = await hornCertificate(input, verdict.certification);
543
- return executor.bounded.length > 0
621
+ const result = executor.bounded.length > 0
544
622
  ? { kind: 'bounded', limits: executor.bounded, assumptions, ...certificate }
545
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
+ }
546
668
  }
547
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
+ }
548
686
  const watch = decl.constants.map((c) => {
549
687
  const term = c.term ?? c.name;
550
688
  return c.sort === 'fp' ? `(fp.to_real ${term})` : term;
@@ -553,22 +691,57 @@ async function attemptWith(input, intLimit, theory) {
553
691
  if (process.env.TSLAWS_DEBUG !== undefined) {
554
692
  const dir = join(dirname(input.jsFile), '..', 'smt');
555
693
  mkdirSync(dir, { recursive: true });
556
- 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`);
557
695
  }
558
696
  const valueQuery = watch.length === 0 ? '' : `(get-value (${watch.join(' ')}))`;
559
- const { out, vals } = await solve(query.join('\n'), valueQuery, input.timeoutMs);
697
+ const { out, vals } = await solve(queryText, valueQuery, input.timeoutMs);
560
698
  const check = out;
561
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
+ }
562
716
  const assumptions = assumptionsFor(input.shapes, intLimit);
563
- const text = query.join('\n');
564
- const certifyQuery = async () => input.certify === undefined || input.certify.mode === false
565
- ? {}
566
- : { certificate: await certify(text, { timeoutMs: input.timeoutMs, keep: keepOf(input, input.certify) }) };
567
- if (executor.bounded.length > 0)
568
- 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
+ }
569
742
  // Only a proof that would stand is sent to the second solver.
570
743
  const unconfirmed = await secondOpinion(input.solvers ?? [], text, input.timeoutMs);
571
- return unconfirmed === undefined
744
+ const result = unconfirmed === undefined
572
745
  ? { kind: 'proved', assumptions, ...(await certifyQuery()) }
573
746
  : {
574
747
  kind: 'bounded',
@@ -579,6 +752,9 @@ async function attemptWith(input, intLimit, theory) {
579
752
  ? {}
580
753
  : { certificate: { status: 'uncertified', reason: unconfirmed } }),
581
754
  };
755
+ if (cacheKey !== undefined && unconfirmed === undefined)
756
+ input.cache.set(cacheKey, result);
757
+ return result;
582
758
  }
583
759
  if (check.startsWith('unknown'))
584
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;