tslaws 0.9.0 → 1.0.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 +8 -2
- package/bin/tslaws.js +8 -2
- package/dist/browser.d.ts +1 -1
- package/dist/browser.js +36 -7
- package/dist/bundled.js +2 -2
- package/dist/bundlerPlugins.d.ts +2 -0
- package/dist/bundlerPlugins.js +7 -0
- package/dist/certificates.d.ts +139 -0
- package/dist/certificates.js +433 -0
- package/dist/chc.d.ts +85 -0
- package/dist/chc.js +298 -0
- package/dist/check.d.ts +13 -1
- package/dist/check.js +215 -28
- package/dist/cli.d.ts +4 -0
- package/dist/cli.js +324 -41
- package/dist/compile.d.ts +17 -1
- package/dist/compile.js +244 -25
- package/dist/coverage.d.ts +55 -3
- package/dist/coverage.js +231 -12
- package/dist/e2eApi.js +3 -1
- package/dist/generators.js +12 -2
- package/dist/github.d.ts +49 -5
- package/dist/github.js +107 -24
- package/dist/githubCli.d.ts +28 -0
- package/dist/githubCli.js +1039 -211
- package/dist/hints.js +2 -1
- package/dist/init.js +42 -0
- package/dist/isolate.d.ts +28 -0
- package/dist/isolate.js +262 -0
- package/dist/isolatedCheck.d.ts +1 -0
- package/dist/isolatedCheck.js +16 -0
- package/dist/lawHost.d.ts +50 -0
- package/dist/lawHost.js +199 -0
- package/dist/lawRuntime.d.ts +39 -0
- package/dist/lawRuntime.js +242 -0
- package/dist/lock.d.ts +49 -9
- package/dist/lock.js +132 -21
- package/dist/mcp.js +28 -7
- package/dist/mutate.d.ts +4 -0
- package/dist/mutate.js +7 -1
- package/dist/plan.d.ts +1 -0
- package/dist/plan.js +4 -0
- package/dist/pluginHooks.d.ts +16 -0
- package/dist/pluginHooks.js +48 -0
- package/dist/pluginHost.d.ts +5 -0
- package/dist/pluginHost.js +43 -0
- package/dist/pluginWorker.d.ts +1 -0
- package/dist/pluginWorker.js +40 -0
- package/dist/plural.d.ts +2 -0
- package/dist/plural.js +4 -0
- package/dist/pool.d.ts +80 -7
- package/dist/pool.js +222 -11
- package/dist/projects.d.ts +70 -0
- package/dist/projects.js +457 -0
- package/dist/promote.d.ts +56 -2
- package/dist/promote.js +429 -13
- package/dist/property.js +13 -2
- package/dist/propertyWorker.js +11 -1
- package/dist/proposals.d.ts +52 -4
- package/dist/proposals.js +484 -21
- package/dist/reporters.js +5 -1
- package/dist/runtimeEnv.d.ts +32 -0
- package/dist/runtimeEnv.js +146 -0
- package/dist/sandbox.d.ts +98 -0
- package/dist/sandbox.js +673 -0
- package/dist/sandboxGuard.d.ts +56 -0
- package/dist/sandboxGuard.js +249 -0
- package/dist/seal.d.ts +9 -0
- package/dist/seal.js +426 -0
- package/dist/security/cli.d.ts +6 -0
- package/dist/security/cli.js +39 -0
- package/dist/security/cwe.d.ts +14 -0
- package/dist/security/cwe.js +40 -0
- package/dist/security/deps/cache.d.ts +28 -0
- package/dist/security/deps/cache.js +107 -0
- package/dist/security/deps/config.d.ts +16 -0
- package/dist/security/deps/config.js +43 -0
- package/dist/security/deps/imports.d.ts +4 -0
- package/dist/security/deps/imports.js +33 -0
- package/dist/security/deps/lockfiles.d.ts +23 -0
- package/dist/security/deps/lockfiles.js +153 -0
- package/dist/security/deps/osv.d.ts +66 -0
- package/dist/security/deps/osv.js +137 -0
- package/dist/security/deps/run.d.ts +54 -0
- package/dist/security/deps/run.js +135 -0
- package/dist/security/deps/severity.d.ts +26 -0
- package/dist/security/deps/severity.js +78 -0
- package/dist/security/generators.d.ts +9 -0
- package/dist/security/generators.js +36 -0
- package/dist/security/index.d.ts +27 -0
- package/dist/security/index.js +18 -0
- package/dist/security/integers.d.ts +31 -0
- package/dist/security/integers.js +105 -0
- package/dist/security/law.d.ts +54 -0
- package/dist/security/law.js +54 -0
- package/dist/security/pathTraversal.d.ts +29 -0
- package/dist/security/pathTraversal.js +146 -0
- package/dist/security/prototypePollution.d.ts +30 -0
- package/dist/security/prototypePollution.js +142 -0
- package/dist/security/redirect.d.ts +21 -0
- package/dist/security/redirect.js +154 -0
- package/dist/security/redos.d.ts +21 -0
- package/dist/security/redos.js +93 -0
- package/dist/security/validation.d.ts +25 -0
- package/dist/security/validation.js +89 -0
- package/dist/security/xss.d.ts +21 -0
- package/dist/security/xss.js +90 -0
- package/dist/settings.d.ts +20 -0
- package/dist/settings.js +32 -0
- package/dist/smt.d.ts +29 -1
- package/dist/smt.js +239 -107
- package/dist/smtWorker.d.ts +1 -0
- package/dist/smtWorker.js +26 -0
- package/dist/solvers.d.ts +9 -0
- package/dist/solvers.js +11 -5
- package/dist/symbolic.d.ts +54 -1
- package/dist/symbolic.js +239 -13
- package/dist/tsconfigResolve.d.ts +28 -0
- package/dist/tsconfigResolve.js +141 -0
- package/dist/types.d.ts +28 -0
- package/env.d.ts +17 -0
- package/hooks/claude-hook.mjs +2 -0
- package/package.json +22 -6
package/dist/settings.d.ts
CHANGED
|
@@ -9,6 +9,26 @@ export interface RunDefaults {
|
|
|
9
9
|
}
|
|
10
10
|
/** What `tslaws check` uses when neither a flag nor tslaws.json says otherwise. */
|
|
11
11
|
export declare const checkDefaults: RunDefaults;
|
|
12
|
+
/**
|
|
13
|
+
* The keys of tslaws.json the lock does not seal, each for a reason. Every other key is sealed, so a key added later is
|
|
14
|
+
* sealed until someone decides it is harmless.
|
|
15
|
+
* - `$schema`: an editor hint.
|
|
16
|
+
* - `github`: who may accept and how a pull request is reviewed (github.ts); it changes no law's run.
|
|
17
|
+
* - `security`: the severity, cache and offline mode of `tslaws security deps`; it reads packages, it runs no law.
|
|
18
|
+
* - `jobs`: how many things run at once on this machine; it changes no law's result.
|
|
19
|
+
* - `levels`: the lock records each laws file's level in its own section and compares it, and a lock that records
|
|
20
|
+
* levels while the project no longer resolves any is tampered (see `compareLock`).
|
|
21
|
+
*/
|
|
22
|
+
export declare const unsealedKeys: readonly string[];
|
|
23
|
+
/**
|
|
24
|
+
* The whole effective tslaws.json (every `extends` followed) except `unsealedKeys`, with defaults filled in so that
|
|
25
|
+
* writing a default down changes nothing. The lock seals it with each law, so weakening any of it (fewer runs, a lower
|
|
26
|
+
* bound, shorter timeouts, fewer solvers, no certificates, looser compiler options, a smaller `cover`, another
|
|
27
|
+
* `e2e` server or `env`) reads as tampered, and so does strengthening it. Command line flags are not part of it: they
|
|
28
|
+
* are one run's choice, not the project's. What the config points at, `bundlerPlugins` and `tsconfig`, is digested
|
|
29
|
+
* by seal.ts.
|
|
30
|
+
*/
|
|
31
|
+
export declare function sealedSettings(config: CoverageConfig): Record<string, unknown>;
|
|
12
32
|
/** `tslaws mutate` runs every law many times over, so it takes fewer runs per mutant. */
|
|
13
33
|
export declare const mutateDefaults: RunDefaults;
|
|
14
34
|
export type ResolvedSettings = RunDefaults & Pick<CheckOptions, 'explicit'>;
|
package/dist/settings.js
CHANGED
|
@@ -1,5 +1,37 @@
|
|
|
1
1
|
/** What `tslaws check` uses when neither a flag nor tslaws.json says otherwise. */
|
|
2
2
|
export const checkDefaults = { runs: 200, bound: 4, proofTimeoutMs: 5000, propertyTimeoutMs: 30000 };
|
|
3
|
+
/**
|
|
4
|
+
* The keys of tslaws.json the lock does not seal, each for a reason. Every other key is sealed, so a key added later is
|
|
5
|
+
* sealed until someone decides it is harmless.
|
|
6
|
+
* - `$schema`: an editor hint.
|
|
7
|
+
* - `github`: who may accept and how a pull request is reviewed (github.ts); it changes no law's run.
|
|
8
|
+
* - `security`: the severity, cache and offline mode of `tslaws security deps`; it reads packages, it runs no law.
|
|
9
|
+
* - `jobs`: how many things run at once on this machine; it changes no law's result.
|
|
10
|
+
* - `levels`: the lock records each laws file's level in its own section and compares it, and a lock that records
|
|
11
|
+
* levels while the project no longer resolves any is tampered (see `compareLock`).
|
|
12
|
+
*/
|
|
13
|
+
export const unsealedKeys = ['$schema', 'github', 'security', 'levels', 'jobs'];
|
|
14
|
+
/**
|
|
15
|
+
* The whole effective tslaws.json (every `extends` followed) except `unsealedKeys`, with defaults filled in so that
|
|
16
|
+
* writing a default down changes nothing. The lock seals it with each law, so weakening any of it (fewer runs, a lower
|
|
17
|
+
* bound, shorter timeouts, fewer solvers, no certificates, looser compiler options, a smaller `cover`, another
|
|
18
|
+
* `e2e` server or `env`) reads as tampered, and so does strengthening it. Command line flags are not part of it: they
|
|
19
|
+
* are one run's choice, not the project's. What the config points at, `bundlerPlugins` and `tsconfig`, is digested
|
|
20
|
+
* by seal.ts.
|
|
21
|
+
*/
|
|
22
|
+
export function sealedSettings(config) {
|
|
23
|
+
const { runs, bound, proofTimeoutMs, propertyTimeoutMs } = resolveSettings(new Map(), config);
|
|
24
|
+
return {
|
|
25
|
+
...Object.fromEntries(Object.entries(config).filter(([key]) => !unsealedKeys.includes(key))),
|
|
26
|
+
runs,
|
|
27
|
+
bound,
|
|
28
|
+
proofTimeoutMs,
|
|
29
|
+
propertyTimeoutMs,
|
|
30
|
+
solvers: config.solvers ?? ['z3'],
|
|
31
|
+
certify: config.certify ?? false,
|
|
32
|
+
compilerOptions: config.compilerOptions ?? {},
|
|
33
|
+
};
|
|
34
|
+
}
|
|
3
35
|
/** `tslaws mutate` runs every law many times over, so it takes fewer runs per mutant. */
|
|
4
36
|
export const mutateDefaults = { ...checkDefaults, runs: 30 };
|
|
5
37
|
/** Resolves runs, bound and the two timeouts: flag, then tslaws.json, then `defaults`. */
|
package/dist/smt.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type Certificate, type CertifyMode } from './certificates.ts';
|
|
1
2
|
import { type SolverName } from './solvers.ts';
|
|
2
3
|
import type { ManifestLaw } from './types.ts';
|
|
3
4
|
export type Shape = 'number' | 'int' | 'bigint' | 'boolean' | 'string' | {
|
|
@@ -8,10 +9,12 @@ export type Shape = 'number' | 'int' | 'bigint' | 'boolean' | 'string' | {
|
|
|
8
9
|
export type ProofResult = {
|
|
9
10
|
kind: 'proved';
|
|
10
11
|
assumptions: string[];
|
|
12
|
+
certificate?: Certificate;
|
|
11
13
|
} | {
|
|
12
14
|
kind: 'bounded';
|
|
13
15
|
limits: string[];
|
|
14
16
|
assumptions: string[];
|
|
17
|
+
certificate?: Certificate;
|
|
15
18
|
} | {
|
|
16
19
|
kind: 'refuted';
|
|
17
20
|
model: string;
|
|
@@ -35,10 +38,27 @@ export interface ProveInput {
|
|
|
35
38
|
/** Longest array, most loop iterations and deepest recursion a proof considers. */
|
|
36
39
|
bound: number;
|
|
37
40
|
/** Runs the compiled law on concrete inputs; true when it holds. */
|
|
38
|
-
holds: (inputs: unknown[]) => boolean
|
|
41
|
+
holds: (inputs: unknown[]) => boolean | Promise<boolean>;
|
|
39
42
|
/** The solvers that must agree on a proof (see solvers.ts); default Z3 alone. */
|
|
40
43
|
solvers?: readonly SolverName[];
|
|
44
|
+
/**
|
|
45
|
+
* Check the `unsat` of an unbounded or bounded proof with cvc5 and Carcara (see certificates.ts). `dir` keeps the
|
|
46
|
+
* proofs of certified laws; `root` is the project they are named relative to.
|
|
47
|
+
*/
|
|
48
|
+
certify?: {
|
|
49
|
+
mode: CertifyMode;
|
|
50
|
+
dir: string;
|
|
51
|
+
root: string;
|
|
52
|
+
};
|
|
41
53
|
}
|
|
54
|
+
/**
|
|
55
|
+
* Runs the query, and runs it again in a fresh worker when the solver itself fell over (a WebAssembly allocation that
|
|
56
|
+
* fails on a machine short of memory). A query that merely ran too long is not retried: it would only run long again.
|
|
57
|
+
*/
|
|
58
|
+
export declare function solve(query: string, values: string, timeoutMs: number): Promise<{
|
|
59
|
+
out: string;
|
|
60
|
+
vals: string;
|
|
61
|
+
}>;
|
|
42
62
|
/**
|
|
43
63
|
* The domain assumptions a proof rests on for parameters of these types, in order of first use and without repeats.
|
|
44
64
|
* Arrays are left out (their length bound is a limit of the proof), as is `int` when `intLimit` narrows it (that range is
|
|
@@ -47,3 +67,11 @@ export interface ProveInput {
|
|
|
47
67
|
export declare function assumptionsFor(shapes: Shape[], intLimit?: bigint): string[];
|
|
48
68
|
/** Tries to prove `input.law` for every input within `input.bound`. */
|
|
49
69
|
export declare function proveLaw(input: ProveInput): Promise<ProofResult>;
|
|
70
|
+
/**
|
|
71
|
+
* The SMT-LIB problems the prover can send for a law (unbounded arrays, then bounded; the full safe range, then the
|
|
72
|
+
* small-int retry), as the checkers read them. `tslaws accept` compares a certificate's problem hash with these, so a
|
|
73
|
+
* certificate counts only for what the law proves now. A law the prover cannot model has none. For a law with loops the
|
|
74
|
+
* text is the Horn system: the invariants that prove it are found by Z3 and can differ, so the certificate binds to the
|
|
75
|
+
* clauses the code yields instead.
|
|
76
|
+
*/
|
|
77
|
+
export declare function problemTexts(input: ProveInput): string[];
|
package/dist/smt.js
CHANGED
|
@@ -6,30 +6,59 @@
|
|
|
6
6
|
// refuted Z3 found an input and the compiled law really fails on it in JavaScript
|
|
7
7
|
// unsupported the code uses something that does not lower, Z3 gave up, or its model did not reproduce
|
|
8
8
|
//
|
|
9
|
+
// Arrays that are parameters, with integer, bigint or boolean elements, are SMT arrays of any length, and a loop
|
|
10
|
+
// becomes constrained Horn clauses for Z3's Spacer to find an invariant (see chc.ts): both are proved without a bound.
|
|
11
|
+
// Anything outside that runs again the old way, with arrays cut at `bound` and loops unrolled that far.
|
|
12
|
+
//
|
|
9
13
|
// Numbers are IEEE doubles; a parameter typed `number` is a finite double (the generators exclude NaN and the
|
|
10
14
|
// infinities too). A parameter typed `int` (from 'tslaws') or `bigint` is an exact integer.
|
|
11
15
|
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
12
|
-
import { createRequire } from 'node:module';
|
|
13
16
|
import { Worker } from 'node:worker_threads';
|
|
14
|
-
import { jobs, WorkerPool } from "./pool.js";
|
|
17
|
+
import { budget, jobs, WorkerPool } from "./pool.js";
|
|
15
18
|
import { dirname, join } from 'node:path';
|
|
16
19
|
import ts from 'typescript';
|
|
20
|
+
import { certificateName, certify, certifyHorn, problemText, } from "./certificates.js";
|
|
21
|
+
import { hornText, runExternalSolvers, solveHorn } from "./chc.js";
|
|
22
|
+
import { lawKey } from "./lock.js";
|
|
17
23
|
import { SolverUnavailable, secondOpinion } from "./solvers.js";
|
|
18
|
-
import { Executor, SpuriousModel, Unsupported, and } from "./symbolic.js";
|
|
24
|
+
import { Executor, SpuriousModel, Unsupported, and, not } from "./symbolic.js";
|
|
25
|
+
import { plural } from "./plural.js";
|
|
26
|
+
/** How many elements of an array of any length a counterexample can show; a longer one is left to the bounded proof. */
|
|
27
|
+
const shownElements = 16;
|
|
19
28
|
const safeRange = (t) => `(and (<= (- 9007199254740991) ${t}) (<= ${t} 9007199254740991))`;
|
|
20
29
|
class Declarations {
|
|
21
30
|
lines = [];
|
|
22
31
|
constants = [];
|
|
32
|
+
/** Every `declare-const`, with its SMT sort, for the Horn clauses that quantify over them. */
|
|
33
|
+
declared = [];
|
|
34
|
+
/** The length constant of each array of any length. */
|
|
35
|
+
lengths = [];
|
|
23
36
|
assumptions = [];
|
|
24
37
|
constant(name, sort) {
|
|
25
38
|
const smt = { fp: '(_ FloatingPoint 11 53)', int: 'Int', bool: 'Bool', str: 'String' }[sort];
|
|
26
39
|
this.lines.push(`(declare-const ${name} ${smt})`);
|
|
40
|
+
this.declared.push({ name, sort: smt });
|
|
27
41
|
this.constants.push({ name, sort });
|
|
28
42
|
}
|
|
43
|
+
/** An array of any length: a length and an SMT array, and the first few elements for a counterexample to show. */
|
|
44
|
+
sequence(name, elem) {
|
|
45
|
+
const sort = elem === 'bool' ? 'bool' : 'int';
|
|
46
|
+
this.constant(`${name}__len`, 'int');
|
|
47
|
+
this.lengths.push(`${name}__len`);
|
|
48
|
+
const smt = `(Array Int ${elem === 'bool' ? 'Bool' : 'Int'})`;
|
|
49
|
+
this.lines.push(`(declare-const ${name}__data ${smt})`);
|
|
50
|
+
this.declared.push({ name: `${name}__data`, sort: smt });
|
|
51
|
+
this.assumptions.push(`(and (<= 0 ${name}__len) (<= ${name}__len 4294967295))`);
|
|
52
|
+
for (let k = 0; k < shownElements; k += 1)
|
|
53
|
+
this.constants.push({ name: `${name}__${k}`, sort, term: `(select ${name}__data ${k})` });
|
|
54
|
+
}
|
|
29
55
|
}
|
|
30
56
|
/** JavaScript strings stop near 2^29 units; a longer one would also push their lengths out of the safe integers. */
|
|
31
57
|
const maxStringLength = 536870888;
|
|
32
|
-
function
|
|
58
|
+
function sequenceElement(shape) {
|
|
59
|
+
return shape === 'int' ? 'int' : shape === 'bigint' ? 'big' : shape === 'boolean' ? 'bool' : undefined;
|
|
60
|
+
}
|
|
61
|
+
function declareParam(name, shape, bound, decl, intLimit, theory) {
|
|
33
62
|
if (shape === 'number') {
|
|
34
63
|
decl.constant(name, 'fp');
|
|
35
64
|
decl.assumptions.push(`(and (not (fp.isNaN ${name})) (not (fp.isInfinite ${name})))`);
|
|
@@ -57,18 +86,25 @@ function declareParam(name, shape, bound, decl, intLimit) {
|
|
|
57
86
|
}
|
|
58
87
|
if (shape === undefined)
|
|
59
88
|
throw new Unsupported('a parameter type is not modelled');
|
|
89
|
+
if ('array' in shape && theory) {
|
|
90
|
+
const elem = sequenceElement(shape.array);
|
|
91
|
+
if (elem === undefined)
|
|
92
|
+
throw new Unsupported('arrays of this element type are proved only within the bound');
|
|
93
|
+
decl.sequence(name, elem);
|
|
94
|
+
return { k: 'seq', len: { k: 'int', t: `${name}__len` }, data: `${name}__data`, elem, id: { escaped: true } };
|
|
95
|
+
}
|
|
60
96
|
if ('array' in shape) {
|
|
61
97
|
const len = `${name}__len`;
|
|
62
98
|
decl.constant(len, 'int');
|
|
63
99
|
decl.assumptions.push(`(and (<= 0 ${len}) (<= ${len} ${bound}))`);
|
|
64
100
|
const slots = [];
|
|
65
101
|
for (let i = 0; i < bound; i += 1)
|
|
66
|
-
slots.push(declareParam(`${name}__${i}`, shape.array, bound, decl, intLimit));
|
|
102
|
+
slots.push(declareParam(`${name}__${i}`, shape.array, bound, decl, intLimit, theory));
|
|
67
103
|
return { k: 'arr', len: { k: 'int', t: len }, slots, id: { escaped: true } };
|
|
68
104
|
}
|
|
69
105
|
const fields = new Map();
|
|
70
106
|
for (const [field, fieldShape] of Object.entries(shape.fields))
|
|
71
|
-
fields.set(field, declareParam(`${name}__${field}`, fieldShape, bound, decl, intLimit));
|
|
107
|
+
fields.set(field, declareParam(`${name}__${field}`, fieldShape, bound, decl, intLimit, theory));
|
|
72
108
|
return { k: 'rec', fields };
|
|
73
109
|
}
|
|
74
110
|
function parseSexp(text) {
|
|
@@ -194,52 +230,24 @@ function jsValue(shape, name, model) {
|
|
|
194
230
|
out[field] = jsValue(fieldShape, `${name}__${field}`, model);
|
|
195
231
|
return out;
|
|
196
232
|
}
|
|
197
|
-
// ---- Z3 ------------------------------------------------------------------------------------------------------
|
|
198
|
-
// Z3 runs in a worker thread: its WebAssembly build blocks the thread and `:timeout` does not always interrupt it,
|
|
199
|
-
// so a query that runs away is stopped by terminating the worker, and the next query starts a fresh one.
|
|
200
|
-
const workerSource = `
|
|
201
|
-
const { parentPort, workerData } = require('node:worker_threads');
|
|
202
|
-
const { init } = require(workerData.z3);
|
|
203
|
-
const ready = init().then((api) => api.Z3);
|
|
204
|
-
parentPort.on('message', async ({ id, query, values }) => {
|
|
205
|
-
try {
|
|
206
|
-
const Z3 = await ready;
|
|
207
|
-
const config = Z3.mk_config();
|
|
208
|
-
const ctx = Z3.mk_context(config);
|
|
209
|
-
let out = '';
|
|
210
|
-
let vals = '';
|
|
211
|
-
try {
|
|
212
|
-
out = (await Z3.eval_smtlib2_string(ctx, query)).trim();
|
|
213
|
-
vals = out.startsWith('sat') && values ? (await Z3.eval_smtlib2_string(ctx, values)).trim() : '';
|
|
214
|
-
} finally {
|
|
215
|
-
Z3.del_context(ctx);
|
|
216
|
-
Z3.del_config(config);
|
|
217
|
-
}
|
|
218
|
-
parentPort.postMessage({ id, out, vals });
|
|
219
|
-
} catch (error) {
|
|
220
|
-
parentPort.postMessage({ id, error: String(error && error.message || error) });
|
|
221
|
-
}
|
|
222
|
-
});
|
|
223
|
-
`;
|
|
224
233
|
let nextId = 0;
|
|
225
234
|
function startWorker() {
|
|
226
|
-
const
|
|
227
|
-
|
|
228
|
-
workerData: { z3: createRequire(import.meta.url).resolve('z3-solver') },
|
|
229
|
-
});
|
|
235
|
+
const ext = import.meta.url.endsWith('.ts') ? '.ts' : '.js';
|
|
236
|
+
const w = new Worker(new URL(`./smtWorker${ext}`, import.meta.url));
|
|
230
237
|
w.unref();
|
|
231
238
|
return w;
|
|
232
239
|
}
|
|
233
240
|
// Each Z3 instance holds a large WebAssembly heap; more than four at once run out of memory on the bigger queries.
|
|
234
|
-
const solvers = new WorkerPool(startWorker, Math.min(4, jobs()));
|
|
241
|
+
const solvers = new WorkerPool(startWorker, () => Math.min(4, jobs()));
|
|
235
242
|
/**
|
|
236
243
|
* Runs the query, and runs it again in a fresh worker when the solver itself fell over (a WebAssembly allocation that
|
|
237
244
|
* fails on a machine short of memory). A query that merely ran too long is not retried: it would only run long again.
|
|
238
245
|
*/
|
|
239
|
-
async function solve(query, values, timeoutMs) {
|
|
246
|
+
export async function solve(query, values, timeoutMs) {
|
|
240
247
|
for (let attempt = 0;; attempt += 1) {
|
|
241
248
|
try {
|
|
242
|
-
|
|
249
|
+
// 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));
|
|
243
251
|
}
|
|
244
252
|
catch (error) {
|
|
245
253
|
if (attempt >= 2 || !(error instanceof Unsupported) || !error.message.startsWith('the solver crashed'))
|
|
@@ -367,73 +375,197 @@ function containsInt(shape) {
|
|
|
367
375
|
return containsInt(shape.array);
|
|
368
376
|
return Object.values(shape.fields).some(containsInt);
|
|
369
377
|
}
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
const
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
378
|
+
/** Where a law's certificate is kept: a file name from the law's name and a hash of its key. */
|
|
379
|
+
function keepOf(input, certify) {
|
|
380
|
+
return { dir: certify.dir, root: certify.root, name: certificateName(lawKey(input.law.file, input.law.name)) };
|
|
381
|
+
}
|
|
382
|
+
function buildProblem(input, intLimit, theory) {
|
|
383
|
+
const source = ts.createSourceFile(input.jsFile, readFileSync(input.jsFile, 'utf8'), ts.ScriptTarget.ES2022, true, ts.ScriptKind.JS);
|
|
384
|
+
const fn = source.statements.find((s) => ts.isFunctionDeclaration(s) && s.name?.text === (input.law.symbol ?? input.law.name));
|
|
385
|
+
if (fn === undefined || fn.body === undefined)
|
|
386
|
+
throw new Unsupported('law function not found in the compiled output');
|
|
387
|
+
if (fn.parameters.length !== input.shapes.length)
|
|
388
|
+
throw new Unsupported('parameter count mismatch');
|
|
389
|
+
const names = fn.parameters.map((p) => (ts.isIdentifier(p.name) ? p.name.text : ''));
|
|
390
|
+
const executor = new Executor(input.bound);
|
|
391
|
+
executor.infer = theory;
|
|
392
|
+
executor.intLimit = intLimit;
|
|
393
|
+
const decl = new Declarations();
|
|
394
|
+
const params = names.map((name, i) => declareParam(name, input.shapes[i], input.bound, decl, intLimit, theory));
|
|
395
|
+
// In the clauses of a loop the parameters' domains are facts like any other, so they go where the executor keeps them.
|
|
396
|
+
if (theory)
|
|
397
|
+
executor.assumptions.push(...decl.assumptions);
|
|
398
|
+
if (intLimit !== undefined)
|
|
399
|
+
executor.bounded.push(`int values stay within ±2^26`);
|
|
400
|
+
if (!theory && input.shapes.some(containsArray))
|
|
401
|
+
executor.bounded.push(`arrays hold at most ${plural(input.bound, 'element')}`);
|
|
402
|
+
const result = executor.runLaw(input.jsFile, fn, params);
|
|
403
|
+
const holds = resultOf(result);
|
|
404
|
+
const safe = and(...executor.obligations);
|
|
405
|
+
const facts = theory ? executor.assumptions : [...decl.assumptions, ...executor.assumptions];
|
|
406
|
+
return { executor, decl, names, holds, safe, facts };
|
|
407
|
+
}
|
|
408
|
+
/** The SMT-LIB query for a problem without loops, as the prover sends it to Z3. */
|
|
409
|
+
function queryOf(input, { decl, executor, facts, holds, safe }) {
|
|
410
|
+
return [
|
|
411
|
+
`(set-option :timeout ${input.timeoutMs})`,
|
|
412
|
+
...decl.lines,
|
|
413
|
+
...executor.freshDecls,
|
|
414
|
+
...executor.defs,
|
|
415
|
+
...facts.map((a) => `(assert ${a})`),
|
|
416
|
+
`(assert (or (not ${holds}) (not ${safe})))`,
|
|
417
|
+
'(check-sat)',
|
|
418
|
+
];
|
|
419
|
+
}
|
|
420
|
+
/**
|
|
421
|
+
* The SMT-LIB problems the prover can send for a law (unbounded arrays, then bounded; the full safe range, then the
|
|
422
|
+
* small-int retry), as the checkers read them. `tslaws accept` compares a certificate's problem hash with these, so a
|
|
423
|
+
* certificate counts only for what the law proves now. A law the prover cannot model has none. For a law with loops the
|
|
424
|
+
* text is the Horn system: the invariants that prove it are found by Z3 and can differ, so the certificate binds to the
|
|
425
|
+
* clauses the code yields instead.
|
|
426
|
+
*/
|
|
427
|
+
export function problemTexts(input) {
|
|
428
|
+
const texts = new Set();
|
|
429
|
+
for (const theory of [true, false]) {
|
|
430
|
+
for (const limit of [undefined, ...(input.shapes.some(containsInt) ? [smallInts] : [])]) {
|
|
431
|
+
try {
|
|
432
|
+
const problem = buildProblem(input, limit, theory);
|
|
433
|
+
if (problem.executor.predicates.length > 0) {
|
|
434
|
+
if (theory)
|
|
435
|
+
texts.add(hornText(hornSystem(problem.executor, problem.decl, problem.facts, problem.holds, problem.safe)));
|
|
436
|
+
continue;
|
|
437
|
+
}
|
|
438
|
+
if (theory && problem.decl.lengths.length === 0)
|
|
439
|
+
continue;
|
|
440
|
+
texts.add(problemText(queryOf(input, problem).join('\n')));
|
|
441
|
+
}
|
|
442
|
+
catch {
|
|
443
|
+
// A limit the law cannot be built under proves nothing.
|
|
444
|
+
}
|
|
436
445
|
}
|
|
437
|
-
return { kind: 'refuted', model: names.map((n, i) => `${n} = ${show(inputs[i])}`).join(', '), inputs };
|
|
438
446
|
}
|
|
447
|
+
return [...texts];
|
|
448
|
+
}
|
|
449
|
+
/**
|
|
450
|
+
* One proof attempt: first with arrays of any length and loop invariants found by a Horn solver, and when that cannot
|
|
451
|
+
* express the law or reach a verdict, the bounded way (arrays and loops cut at `bound`).
|
|
452
|
+
*/
|
|
453
|
+
async function attempt(input, intLimit) {
|
|
454
|
+
try {
|
|
455
|
+
const unbounded = await attemptWith(input, intLimit, true);
|
|
456
|
+
if (unbounded !== undefined)
|
|
457
|
+
return unbounded;
|
|
458
|
+
}
|
|
459
|
+
catch (error) {
|
|
460
|
+
if (!(error instanceof Unsupported))
|
|
461
|
+
throw error;
|
|
462
|
+
}
|
|
463
|
+
return (await attemptWith(input, intLimit, false));
|
|
464
|
+
}
|
|
465
|
+
const declaredConstant = /^\(declare-const (\S+) (.+)\)$/;
|
|
466
|
+
/** The Horn clauses of the loops, closed over every constant, and the query that the law and its obligations hold. */
|
|
467
|
+
function hornSystem(executor, decl, facts, holds, safe) {
|
|
468
|
+
const constants = [...decl.declared];
|
|
469
|
+
for (const line of executor.freshDecls) {
|
|
470
|
+
const m = declaredConstant.exec(line);
|
|
471
|
+
if (m !== null)
|
|
472
|
+
constants.push({ name: m[1], sort: m[2] });
|
|
473
|
+
}
|
|
474
|
+
return {
|
|
475
|
+
predicates: executor.predicates,
|
|
476
|
+
constants,
|
|
477
|
+
clauses: [...executor.clauses, `(=> ${and(...facts, not(and(holds, safe)))} false)`],
|
|
478
|
+
shared: executor.sharedTerms,
|
|
479
|
+
};
|
|
480
|
+
}
|
|
481
|
+
/** The certificate of a proof by loop invariants: cvc5 refutes the problem the invariants make of the clauses, Carcara checks it. */
|
|
482
|
+
async function hornCertificate(input, certification) {
|
|
483
|
+
if (input.certify === undefined || input.certify.mode === false)
|
|
484
|
+
return {};
|
|
485
|
+
return {
|
|
486
|
+
certificate: await certifyHorn(certification, { timeoutMs: input.timeoutMs, keep: keepOf(input, input.certify) }),
|
|
487
|
+
};
|
|
488
|
+
}
|
|
489
|
+
/**
|
|
490
|
+
* `theory`: arrays are of any length and loops get inferred invariants. Undefined when that changes nothing, or no
|
|
491
|
+
* verdict came of it, and the caller runs the bounded proof.
|
|
492
|
+
*/
|
|
493
|
+
async function attemptWith(input, intLimit, theory) {
|
|
494
|
+
const problem = buildProblem(input, intLimit, theory);
|
|
495
|
+
const { executor, decl, names, holds, safe, facts } = problem;
|
|
496
|
+
if (theory && decl.lengths.length === 0 && executor.predicates.length === 0)
|
|
497
|
+
return undefined;
|
|
498
|
+
if (executor.predicates.length > 0) {
|
|
499
|
+
// Cvc5 does not solve Horn clauses, so a proof it must confirm is left to the bounded way.
|
|
500
|
+
if (input.solvers?.includes('cvc5'))
|
|
501
|
+
return undefined;
|
|
502
|
+
const verdict = await solveHorn(hornSystem(executor, decl, facts, holds, safe), { z3: solve, external: runExternalSolvers }, input.timeoutMs);
|
|
503
|
+
if (verdict.kind === 'disagree')
|
|
504
|
+
return { kind: 'unsupported', reason: verdict.reason };
|
|
505
|
+
if (verdict.kind !== 'safe')
|
|
506
|
+
return undefined;
|
|
507
|
+
const assumptions = [...assumptionsFor(input.shapes, intLimit), ...verdict.invariants, ...verdict.notes];
|
|
508
|
+
const certificate = await hornCertificate(input, verdict.certification);
|
|
509
|
+
return executor.bounded.length > 0
|
|
510
|
+
? { kind: 'bounded', limits: executor.bounded, assumptions, ...certificate }
|
|
511
|
+
: { kind: 'proved', assumptions, ...certificate };
|
|
512
|
+
}
|
|
513
|
+
const query = queryOf(input, problem);
|
|
514
|
+
const watch = decl.constants.map((c) => {
|
|
515
|
+
const term = c.term ?? c.name;
|
|
516
|
+
return c.sort === 'fp' ? `(fp.to_real ${term})` : term;
|
|
517
|
+
});
|
|
518
|
+
// TSLAWS_DEBUG=1 keeps each query next to the compiled output, to replay in z3.
|
|
519
|
+
if (process.env.TSLAWS_DEBUG !== undefined) {
|
|
520
|
+
const dir = join(dirname(input.jsFile), '..', 'smt');
|
|
521
|
+
mkdirSync(dir, { recursive: true });
|
|
522
|
+
writeFileSync(join(dir, `${input.law.name}.smt2`), `${query.join('\n')}\n(get-model)\n`);
|
|
523
|
+
}
|
|
524
|
+
const valueQuery = watch.length === 0 ? '' : `(get-value (${watch.join(' ')}))`;
|
|
525
|
+
const { out, vals } = await solve(query.join('\n'), valueQuery, input.timeoutMs);
|
|
526
|
+
const check = out;
|
|
527
|
+
if (check.startsWith('unsat')) {
|
|
528
|
+
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()) };
|
|
535
|
+
// Only a proof that would stand is sent to the second solver.
|
|
536
|
+
const unconfirmed = await secondOpinion(input.solvers ?? [], text, input.timeoutMs);
|
|
537
|
+
return unconfirmed === undefined
|
|
538
|
+
? { kind: 'proved', assumptions, ...(await certifyQuery()) }
|
|
539
|
+
: {
|
|
540
|
+
kind: 'bounded',
|
|
541
|
+
limits: [unconfirmed],
|
|
542
|
+
assumptions,
|
|
543
|
+
// Nothing was proved, so nothing is certified; `require` must not let this pass.
|
|
544
|
+
...(input.certify === undefined || input.certify.mode === false
|
|
545
|
+
? {}
|
|
546
|
+
: { certificate: { status: 'uncertified', reason: unconfirmed } }),
|
|
547
|
+
};
|
|
548
|
+
}
|
|
549
|
+
if (check.startsWith('unknown'))
|
|
550
|
+
throw new Unsupported(`solver gave up within ${input.timeoutMs} ms`);
|
|
551
|
+
if (!check.startsWith('sat'))
|
|
552
|
+
throw new Unsupported(`solver said: ${check.split('\n')[0]}`);
|
|
553
|
+
const values = watch.length === 0 ? '()' : vals;
|
|
554
|
+
const pairs = parseSexp(values);
|
|
555
|
+
const model = new Map();
|
|
556
|
+
decl.constants.forEach((c, i) => {
|
|
557
|
+
const pair = pairs[i];
|
|
558
|
+
if (Array.isArray(pair) && pair.length === 2)
|
|
559
|
+
model.set(c.name, modelValue(c.sort, pair[1]));
|
|
560
|
+
});
|
|
561
|
+
if (decl.lengths.some((len) => Number(model.get(len) ?? 0) > shownElements))
|
|
562
|
+
throw new Unsupported(`the counterexample has more than ${shownElements} elements`);
|
|
563
|
+
const inputs = names.map((name, i) => jsValue(input.shapes[i], name, model));
|
|
564
|
+
// A model may break only an obligation, or rest on float effects the replay does not share.
|
|
565
|
+
if (await input.holds(inputs)) {
|
|
566
|
+
const why = `Z3 model ${show(inputs)} passes in JavaScript (an integer may leave the safe range, an index may leave its array, or the bound cut the code)`;
|
|
567
|
+
const advice = executor.hints.length === 0 ? '' : `; ${executor.hints.join('; ')}`;
|
|
568
|
+
throw intLimit === undefined ? new SpuriousModel(why + advice) : new Unsupported(why + advice);
|
|
569
|
+
}
|
|
570
|
+
return { kind: 'refuted', model: names.map((n, i) => `${n} = ${show(inputs[i])}`).join(', '), inputs };
|
|
439
571
|
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
// The Z3 worker thread (see smt.ts): it holds one Z3 instance and answers one query at a time. Its WebAssembly build
|
|
2
|
+
// blocks the thread, so the owner stops a runaway query by terminating the worker rather than by a solver timeout.
|
|
3
|
+
import { parentPort } from 'node:worker_threads';
|
|
4
|
+
import { init } from 'z3-solver';
|
|
5
|
+
const ready = init().then((api) => api.Z3);
|
|
6
|
+
parentPort.on('message', async ({ id, query, values }) => {
|
|
7
|
+
try {
|
|
8
|
+
const Z3 = await ready;
|
|
9
|
+
const config = Z3.mk_config();
|
|
10
|
+
const ctx = Z3.mk_context(config);
|
|
11
|
+
let out = '';
|
|
12
|
+
let vals = '';
|
|
13
|
+
try {
|
|
14
|
+
out = (await Z3.eval_smtlib2_string(ctx, query)).trim();
|
|
15
|
+
vals = out.startsWith('sat') && values ? (await Z3.eval_smtlib2_string(ctx, values)).trim() : '';
|
|
16
|
+
}
|
|
17
|
+
finally {
|
|
18
|
+
Z3.del_context(ctx);
|
|
19
|
+
Z3.del_config(config);
|
|
20
|
+
}
|
|
21
|
+
parentPort.postMessage({ id, out, vals });
|
|
22
|
+
}
|
|
23
|
+
catch (error) {
|
|
24
|
+
parentPort.postMessage({ id, error: String(error?.message ?? error) });
|
|
25
|
+
}
|
|
26
|
+
});
|
package/dist/solvers.d.ts
CHANGED
|
@@ -20,6 +20,15 @@ export type Cvc5Answer = {
|
|
|
20
20
|
* with `(set-logic ALL)` first when the query names no logic.
|
|
21
21
|
*/
|
|
22
22
|
export declare function cvc5Text(query: string): string;
|
|
23
|
+
/**
|
|
24
|
+
* Where a tool's binary is and how to start it: the path in the environment variable `env`, else `binary` on the PATH. A
|
|
25
|
+
* path ending in .js, .mjs or .cjs is a Node script and runs under the current Node (the tests use one as a fake tool,
|
|
26
|
+
* which a .cmd file could not do on every platform); anything else is run as it is. No shell is involved.
|
|
27
|
+
*/
|
|
28
|
+
export declare function toolCommand(env: string, binary: string): {
|
|
29
|
+
file: string;
|
|
30
|
+
args: string[];
|
|
31
|
+
};
|
|
23
32
|
/** Asks cvc5 for the verdict on the query; a binary that cannot be started throws `SolverUnavailable`. */
|
|
24
33
|
export declare function runCvc5(query: string, timeoutMs: number): Promise<Cvc5Answer>;
|
|
25
34
|
/** The reason cvc5 did not agree, or undefined when it also said `unsat`. */
|
package/dist/solvers.js
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
// they already replay in JavaScript.
|
|
5
5
|
import { spawn } from 'node:child_process';
|
|
6
6
|
import { extname } from 'node:path';
|
|
7
|
+
import { budget, lowerPriority } from "./pool.js";
|
|
7
8
|
export const solverNames = ['z3', 'cvc5'];
|
|
8
9
|
/** The solvers of a project without a `solvers` key: Z3 alone, with no second opinion. */
|
|
9
10
|
export const defaultSolvers = ['z3'];
|
|
@@ -40,25 +41,30 @@ export function cvc5Text(query) {
|
|
|
40
41
|
return `${logic}${text}\n`;
|
|
41
42
|
}
|
|
42
43
|
/**
|
|
43
|
-
* Where
|
|
44
|
-
* a Node script and runs under the current Node (the tests use one as a fake
|
|
45
|
-
* every platform); anything else is run as it is. No shell is involved.
|
|
44
|
+
* Where a tool's binary is and how to start it: the path in the environment variable `env`, else `binary` on the PATH. A
|
|
45
|
+
* path ending in .js, .mjs or .cjs is a Node script and runs under the current Node (the tests use one as a fake tool,
|
|
46
|
+
* which a .cmd file could not do on every platform); anything else is run as it is. No shell is involved.
|
|
46
47
|
*/
|
|
47
|
-
function
|
|
48
|
-
const path = process.env
|
|
48
|
+
export function toolCommand(env, binary) {
|
|
49
|
+
const path = process.env[env] ?? binary;
|
|
49
50
|
return ['.js', '.mjs', '.cjs'].includes(extname(path))
|
|
50
51
|
? { file: process.execPath, args: [path] }
|
|
51
52
|
: { file: path, args: [] };
|
|
52
53
|
}
|
|
54
|
+
const command = () => toolCommand('TSLAWS_CVC5', 'cvc5');
|
|
53
55
|
const missing = () => new SolverUnavailable(`"solvers" includes "cvc5", but the cvc5 binary was not found: install cvc5 (https://cvc5.github.io) so that cvc5 is on the PATH, or set TSLAWS_CVC5 to its path`);
|
|
54
56
|
/** Asks cvc5 for the verdict on the query; a binary that cannot be started throws `SolverUnavailable`. */
|
|
55
57
|
export function runCvc5(query, timeoutMs) {
|
|
58
|
+
return budget.run(() => spawnCvc5(query, timeoutMs));
|
|
59
|
+
}
|
|
60
|
+
function spawnCvc5(query, timeoutMs) {
|
|
56
61
|
const { file, args } = command();
|
|
57
62
|
return new Promise((resolve, reject) => {
|
|
58
63
|
const child = spawn(file, [...args, '--lang', 'smt2', '--tlimit', String(timeoutMs)], {
|
|
59
64
|
stdio: ['pipe', 'pipe', 'pipe'],
|
|
60
65
|
windowsHide: true,
|
|
61
66
|
});
|
|
67
|
+
lowerPriority(child.pid);
|
|
62
68
|
let stdout = '';
|
|
63
69
|
let stderr = '';
|
|
64
70
|
let finished = false;
|