tslaws 1.1.0 → 1.3.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/README.md +177 -187
- package/dist/api.d.ts +86 -0
- package/dist/api.js +78 -0
- package/dist/badge.d.ts +58 -11
- package/dist/badge.js +194 -27
- package/dist/browser.d.ts +5 -2
- package/dist/browser.js +403 -173
- package/dist/browserApi.d.ts +305 -0
- package/dist/browserApi.js +456 -0
- package/dist/browserServer.d.ts +13 -0
- package/dist/browserServer.js +406 -0
- package/dist/certificates.js +50 -28
- package/dist/chc.js +30 -7
- package/dist/check.js +55 -30
- package/dist/cli.js +12 -2
- package/dist/compile.js +41 -4
- package/dist/coverage.d.ts +17 -0
- package/dist/coverage.js +269 -18
- package/dist/derived.d.ts +2 -0
- package/dist/derived.js +9 -4
- package/dist/generators.d.ts +5 -1
- package/dist/generators.js +50 -4
- package/dist/githubCli.js +67 -7
- package/dist/lawHost.d.ts +2 -0
- package/dist/lawHost.js +31 -18
- package/dist/lock.d.ts +1 -0
- package/dist/lock.js +7 -4
- package/dist/nativeZ3.d.ts +11 -0
- package/dist/nativeZ3.js +162 -0
- package/dist/plan.d.ts +7 -0
- package/dist/plan.js +11 -0
- package/dist/proofCache.d.ts +24 -0
- package/dist/proofCache.js +135 -0
- package/dist/property.d.ts +2 -2
- package/dist/property.js +33 -8
- package/dist/propertyWorker.js +13 -5
- package/dist/sandbox.d.ts +1 -1
- package/dist/sandbox.js +48 -8
- package/dist/seal.js +47 -8
- package/dist/smt.d.ts +7 -1
- package/dist/smt.js +202 -26
- package/dist/symbolic.d.ts +38 -3
- package/dist/symbolic.js +504 -47
- package/dist/types.d.ts +4 -0
- package/package.json +6 -6
package/dist/sandbox.js
CHANGED
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
// them (`--allow-e2e`). `--no-sandbox` turns it all off, with a warning.
|
|
13
13
|
import { fork } from 'node:child_process';
|
|
14
14
|
import { createHash, randomBytes } from 'node:crypto';
|
|
15
|
-
import { existsSync, readdirSync, readFileSync, realpathSync } from 'node:fs';
|
|
15
|
+
import { existsSync, readdirSync, readFileSync, realpathSync, statSync } from 'node:fs';
|
|
16
16
|
import { homedir } from 'node:os';
|
|
17
17
|
import { dirname, extname, isAbsolute, join, relative, resolve, sep } from 'node:path';
|
|
18
18
|
import { fileURLToPath } from 'node:url';
|
|
@@ -316,6 +316,35 @@ const namesOf = (manifest, fields) => fields.flatMap((field) => {
|
|
|
316
316
|
const value = manifest?.[field];
|
|
317
317
|
return typeof value === 'object' && value !== null ? Object.keys(value) : [];
|
|
318
318
|
});
|
|
319
|
+
const trustedPackagesCache = new Map();
|
|
320
|
+
function manifestStamp(dir) {
|
|
321
|
+
const out = [];
|
|
322
|
+
for (const name of ['package.json', 'package-lock.json', 'pnpm-lock.yaml']) {
|
|
323
|
+
const p = join(dir, name);
|
|
324
|
+
try {
|
|
325
|
+
const st = statSync(p);
|
|
326
|
+
out.push([p, st.size, st.mtimeMs]);
|
|
327
|
+
}
|
|
328
|
+
catch {
|
|
329
|
+
out.push([p, -1, -1]);
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
return out;
|
|
333
|
+
}
|
|
334
|
+
function stampsMatch(stamps) {
|
|
335
|
+
for (const [p, size, mtimeMs] of stamps) {
|
|
336
|
+
try {
|
|
337
|
+
const st = statSync(p);
|
|
338
|
+
if (st.size !== size || st.mtimeMs !== mtimeMs)
|
|
339
|
+
return false;
|
|
340
|
+
}
|
|
341
|
+
catch {
|
|
342
|
+
if (size !== -1 || mtimeMs !== -1)
|
|
343
|
+
return false;
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
return true;
|
|
347
|
+
}
|
|
319
348
|
/**
|
|
320
349
|
* The packages the code may load: those the manifests declare (the project's `package.json` with its dev dependencies,
|
|
321
350
|
* and tslaws's own) and, from each one's manifest, what it declares in turn. Anything else in a `node_modules` was put
|
|
@@ -324,6 +353,10 @@ const namesOf = (manifest, fields) => fields.flatMap((field) => {
|
|
|
324
353
|
*/
|
|
325
354
|
export function trustedPackages(cwd) {
|
|
326
355
|
const project = realOf(resolve(cwd));
|
|
356
|
+
const cached = trustedPackagesCache.get(project);
|
|
357
|
+
if (cached !== undefined && stampsMatch(cached.stamps))
|
|
358
|
+
return cached.value;
|
|
359
|
+
const stamps = [...manifestStamp(project), ...manifestStamp(tslawsRoot)];
|
|
327
360
|
const modules = new Set();
|
|
328
361
|
const linked = new Set();
|
|
329
362
|
const seen = new Set();
|
|
@@ -358,7 +391,11 @@ export function trustedPackages(cwd) {
|
|
|
358
391
|
for (const [dir, fields] of manifests)
|
|
359
392
|
for (const name of namesOf(readManifest(join(dir, 'package.json')), fields))
|
|
360
393
|
visit(name, dir);
|
|
361
|
-
|
|
394
|
+
const value = { modules: [...modules], linked: [...linked] };
|
|
395
|
+
if (trustedPackagesCache.size > 256)
|
|
396
|
+
trustedPackagesCache.clear();
|
|
397
|
+
trustedPackagesCache.set(project, { stamps, value });
|
|
398
|
+
return value;
|
|
362
399
|
}
|
|
363
400
|
/**
|
|
364
401
|
* The reviewed set of a project after a build: the build's output, the files its laws reach, the packages, and the
|
|
@@ -476,11 +513,11 @@ class LawProcess {
|
|
|
476
513
|
configKey;
|
|
477
514
|
/** Answers only requests that carry it. The process learns it from `configure` and no law can read it. */
|
|
478
515
|
token = randomBytes(24).toString('hex');
|
|
479
|
-
constructor(
|
|
516
|
+
constructor(flags) {
|
|
480
517
|
this.child = fork(hostFile, [], {
|
|
481
518
|
// The allowlisted environment the token-free check process gets (see isolate.ts): no credential, no code loader.
|
|
482
519
|
env: scrubbedEnv(process.env),
|
|
483
|
-
execArgv:
|
|
520
|
+
execArgv: flags,
|
|
484
521
|
serialization: 'advanced',
|
|
485
522
|
stdio: ['ignore', 'inherit', 'inherit', 'ipc'],
|
|
486
523
|
windowsHide: true,
|
|
@@ -551,7 +588,7 @@ export function liveSandboxProcesses() {
|
|
|
551
588
|
* Makes room for a process about to start: the cap is shared by every project, not held by each, so an idle process of
|
|
552
589
|
* another project (or configuration) ends when the budget is already spent. The pool counts the new one before it starts.
|
|
553
590
|
*/
|
|
554
|
-
function startProcess(
|
|
591
|
+
function startProcess(flags) {
|
|
555
592
|
const cap = jobs();
|
|
556
593
|
for (const { pool } of pools.values()) {
|
|
557
594
|
if (liveSandboxProcesses() <= cap)
|
|
@@ -559,15 +596,17 @@ function startProcess(cwd, extra) {
|
|
|
559
596
|
while (liveSandboxProcesses() > cap && pool.evictOne())
|
|
560
597
|
;
|
|
561
598
|
}
|
|
562
|
-
return new LawProcess(
|
|
599
|
+
return new LawProcess(flags);
|
|
563
600
|
}
|
|
564
601
|
function poolFor(cwd, extra) {
|
|
565
602
|
const key = JSON.stringify([resolve(cwd), extra]);
|
|
566
603
|
let entry = pools.get(key);
|
|
567
604
|
if (entry === undefined) {
|
|
605
|
+
// Compute permission flags once per pool instead of re-walking node_modules for every forked process.
|
|
606
|
+
const flags = sandboxFlags(cwd, extra);
|
|
568
607
|
entry = {
|
|
569
608
|
cwd: resolve(cwd),
|
|
570
|
-
pool: new WorkerPool(() => startProcess(
|
|
609
|
+
pool: new WorkerPool(() => startProcess(flags), jobs, idleMs),
|
|
571
610
|
};
|
|
572
611
|
pools.set(key, entry);
|
|
573
612
|
}
|
|
@@ -633,7 +672,7 @@ export class Sandbox {
|
|
|
633
672
|
}
|
|
634
673
|
}
|
|
635
674
|
/** The property test of `law`, `'timeout'` when it does not finish; throws `LawLoadError` when it cannot be loaded. */
|
|
636
|
-
async run(outDir, law, options, plans) {
|
|
675
|
+
async run(outDir, law, options, plans, buildKey) {
|
|
637
676
|
const reply = await this.ask(options.propertyTimeoutMs ?? 30000, (id) => ({
|
|
638
677
|
type: 'run',
|
|
639
678
|
id,
|
|
@@ -643,6 +682,7 @@ export class Sandbox {
|
|
|
643
682
|
// Functions cannot cross to the process; it needs only the numbers.
|
|
644
683
|
options: { ...options, onEvent: undefined },
|
|
645
684
|
env: lawEnv(options.cwd, 'node'),
|
|
685
|
+
buildKey,
|
|
646
686
|
}));
|
|
647
687
|
if (reply === 'timeout')
|
|
648
688
|
return reply;
|
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,
|
|
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
|
-
|
|
54
|
-
|
|
55
|
-
|
|
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 && /[
|
|
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' | '
|
|
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,
|
|
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
|
-
|
|
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
|
-
|
|
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' ||
|
|
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(() =>
|
|
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
|
-
|
|
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 =
|
|
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
|
|
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
|
-
|
|
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`), `${
|
|
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(
|
|
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
|
-
|
|
564
|
-
const
|
|
565
|
-
?
|
|
566
|
-
:
|
|
567
|
-
|
|
568
|
-
|
|
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
|
-
|
|
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`);
|