tslaws 0.6.4 → 0.8.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 +16 -9
- package/dist/api.d.ts +10 -0
- package/dist/api.js +7 -0
- package/dist/browser.d.ts +2 -2
- package/dist/browser.js +2 -6
- package/dist/check.d.ts +2 -0
- package/dist/check.js +218 -56
- package/dist/cli.d.ts +18 -0
- package/dist/cli.js +189 -56
- package/dist/compile.d.ts +12 -0
- package/dist/compile.js +207 -6
- package/dist/coverage.d.ts +21 -1
- package/dist/coverage.js +33 -23
- package/dist/derived.d.ts +8 -0
- package/dist/derived.js +52 -0
- package/dist/e2e.d.ts +0 -9
- package/dist/e2e.js +0 -20
- package/dist/generators.d.ts +8 -8
- package/dist/generators.js +59 -99
- package/dist/github.d.ts +121 -0
- package/dist/github.js +266 -0
- package/dist/githubCli.d.ts +46 -0
- package/dist/githubCli.js +502 -0
- package/dist/globs.d.ts +3 -0
- package/dist/globs.js +24 -0
- package/dist/init.js +5 -5
- package/dist/lawFiles.d.ts +21 -0
- package/dist/lawFiles.js +95 -0
- package/dist/lawKinds.d.ts +38 -0
- package/dist/lawKinds.js +210 -0
- package/dist/lawNames.d.ts +6 -0
- package/dist/lawNames.js +22 -0
- package/dist/list.d.ts +22 -0
- package/dist/list.js +36 -0
- package/dist/lock.d.ts +39 -3
- package/dist/lock.js +107 -4
- package/dist/lower.d.ts +10 -0
- package/dist/lower.js +178 -0
- package/dist/mcp.d.ts +2 -8
- package/dist/mcp.js +40 -61
- package/dist/migrate/arbitraries.d.ts +23 -0
- package/dist/migrate/arbitraries.js +202 -0
- package/dist/migrate/convert.d.ts +20 -0
- package/dist/migrate/convert.js +915 -0
- package/dist/migrate/framework.d.ts +48 -0
- package/dist/migrate/framework.js +249 -0
- package/dist/migrate/index.d.ts +16 -0
- package/dist/migrate/index.js +155 -0
- package/dist/migrate/report.d.ts +35 -0
- package/dist/migrate/report.js +40 -0
- package/dist/migrate/source.d.ts +42 -0
- package/dist/migrate/source.js +163 -0
- package/dist/migrate/tests.d.ts +44 -0
- package/dist/migrate/tests.js +184 -0
- package/dist/plan.d.ts +50 -0
- package/dist/plan.js +118 -0
- package/dist/pool.d.ts +21 -0
- package/dist/pool.js +54 -0
- package/dist/promote.d.ts +30 -2
- package/dist/promote.js +133 -7
- package/dist/property.d.ts +12 -26
- package/dist/property.js +33 -74
- package/dist/propertyRun.d.ts +35 -0
- package/dist/propertyRun.js +79 -0
- package/dist/propertyWorker.js +7 -9
- package/dist/proposals.d.ts +43 -0
- package/dist/proposals.js +192 -0
- package/dist/regressions.js +23 -2
- package/dist/reporters.d.ts +3 -0
- package/dist/reporters.js +17 -0
- package/dist/smt.d.ts +16 -0
- package/dist/smt.js +52 -9
- package/dist/solvers.d.ts +31 -0
- package/dist/solvers.js +121 -0
- package/dist/symbolic.js +2 -2
- package/dist/types.d.ts +19 -0
- package/hooks/AGENTS.snippet.md +2 -2
- package/package.json +9 -7
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
// Proposals: laws an agent (or a person) suggests, kept in `.tslaws/proposals/` at the project root. The directory is
|
|
2
|
+
// tool-owned and git-ignored, outside the tree the lock covers, so a proposal protects nothing and an edit to the tree
|
|
3
|
+
// can never turn an accepted law into a proposed one. Only this module writes there; it never touches the lock.
|
|
4
|
+
//
|
|
5
|
+
// Imports in a proposal that start with `./` are written relative to the PROJECT ROOT (`./src/cart`), which is what an
|
|
6
|
+
// author at the project root expects. They are stored relative to the file (`../../src/cart`), so the stored file is
|
|
7
|
+
// ordinary TypeScript that resolves, type-checks and runs where it is. `../` and package imports are left alone.
|
|
8
|
+
// `promote` rewrites the stored form again for the directory the law moves to.
|
|
9
|
+
import { constants, existsSync, lstatSync, mkdirSync, openSync, readFileSync, realpathSync, writeSync, closeSync, appendFileSync, writeFileSync, } from 'node:fs';
|
|
10
|
+
import { join, posix } from 'node:path';
|
|
11
|
+
import { moduleSpecifiers } from "./lawKinds.js";
|
|
12
|
+
import { proposalsDir } from "./lawFiles.js";
|
|
13
|
+
import { parseLawFile } from "./promote.js";
|
|
14
|
+
/** A refusal with a message for the person or agent that asked. */
|
|
15
|
+
export class ProposalError extends Error {
|
|
16
|
+
}
|
|
17
|
+
const nameShape = /^[A-Za-z0-9][A-Za-z0-9._-]*\.(?:ts|mts|cts)$/;
|
|
18
|
+
const isLink = (path) => {
|
|
19
|
+
try {
|
|
20
|
+
return lstatSync(path).isSymbolicLink();
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
return false;
|
|
24
|
+
}
|
|
25
|
+
};
|
|
26
|
+
/**
|
|
27
|
+
* The proposals directory, checked on the real file system: neither `.tslaws` nor `proposals` may be a link (or a
|
|
28
|
+
* junction) that leads out of the project. Creates the directory when `create` is set.
|
|
29
|
+
*/
|
|
30
|
+
export function proposalsDirectory(cwd, create) {
|
|
31
|
+
let real = realpathSync(cwd);
|
|
32
|
+
let shown = cwd;
|
|
33
|
+
for (const part of ['.tslaws', 'proposals']) {
|
|
34
|
+
shown = join(shown, part);
|
|
35
|
+
const expected = join(real, part);
|
|
36
|
+
if (existsSync(shown) || isLink(shown)) {
|
|
37
|
+
if (isLink(shown) || realpathSync(shown) !== expected)
|
|
38
|
+
throw new ProposalError(`${posix.join('.tslaws', part)} is a link that leaves the project; proposals are written inside the project only`);
|
|
39
|
+
}
|
|
40
|
+
else if (create)
|
|
41
|
+
mkdirSync(shown);
|
|
42
|
+
else
|
|
43
|
+
return undefined;
|
|
44
|
+
real = expected;
|
|
45
|
+
}
|
|
46
|
+
return shown;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* The project-relative path of a proposal: `name.ts` or `.tslaws/proposals/name.ts`. Anything that names another
|
|
50
|
+
* directory, climbs out, is absolute or is not a plain `.ts` file name is refused.
|
|
51
|
+
*/
|
|
52
|
+
export function proposalName(file) {
|
|
53
|
+
const given = file.replaceAll('\\', '/').replace(/^\.\//, '');
|
|
54
|
+
const bare = given.startsWith(`${proposalsDir}/`) ? given.slice(proposalsDir.length + 1) : given;
|
|
55
|
+
if (!nameShape.test(bare) || /\.d\.(?:ts|mts|cts)$/.test(bare) || bare.includes('..'))
|
|
56
|
+
throw new ProposalError(`'${file}' is not a proposal file: proposals are plain .ts files directly inside ${proposalsDir}/ (for example ${proposalsDir}/cart.ts)`);
|
|
57
|
+
return `${proposalsDir}/${bare}`;
|
|
58
|
+
}
|
|
59
|
+
/** The absolute path a write to a proposal may use, after refusing links. Creates the directory. */
|
|
60
|
+
function writablePath(cwd, file) {
|
|
61
|
+
const rel = proposalName(file);
|
|
62
|
+
const dir = proposalsDirectory(cwd, true);
|
|
63
|
+
const abs = join(dir, rel.slice(proposalsDir.length + 1));
|
|
64
|
+
if (isLink(abs))
|
|
65
|
+
throw new ProposalError(`${rel} is a link; a proposal must be a plain file`);
|
|
66
|
+
if (existsSync(abs) && !lstatSync(abs).isFile())
|
|
67
|
+
throw new ProposalError(`${rel} is not a plain file`);
|
|
68
|
+
return { rel, abs };
|
|
69
|
+
}
|
|
70
|
+
/** The absolute path of an existing proposal for reading or removing; refuses links the same way. */
|
|
71
|
+
export function existingProposal(cwd, file) {
|
|
72
|
+
const rel = proposalName(file);
|
|
73
|
+
const dir = proposalsDirectory(cwd, false);
|
|
74
|
+
const abs = dir === undefined ? undefined : join(dir, rel.slice(proposalsDir.length + 1));
|
|
75
|
+
if (abs === undefined || !existsSync(abs))
|
|
76
|
+
throw new ProposalError(`no proposal ${rel}`);
|
|
77
|
+
if (isLink(abs) || !lstatSync(abs).isFile())
|
|
78
|
+
throw new ProposalError(`${rel} is not a plain file`);
|
|
79
|
+
return { rel, abs };
|
|
80
|
+
}
|
|
81
|
+
function rewrite(text, change) {
|
|
82
|
+
let out = text;
|
|
83
|
+
for (const spec of moduleSpecifiers(text, 'proposal.ts').reverse()) {
|
|
84
|
+
const next = change(spec.value);
|
|
85
|
+
if (next !== undefined && next !== spec.value)
|
|
86
|
+
out = out.slice(0, spec.start) + next + out.slice(spec.end);
|
|
87
|
+
}
|
|
88
|
+
return out;
|
|
89
|
+
}
|
|
90
|
+
const dotted = (path) => (path.startsWith('.') ? path : `./${path}`);
|
|
91
|
+
/** Stores root-relative `./x` imports relative to the proposals directory. Idempotent for stored text. */
|
|
92
|
+
export function toStoredImports(text) {
|
|
93
|
+
return rewrite(text, (specifier) => {
|
|
94
|
+
if (!specifier.startsWith('./'))
|
|
95
|
+
return undefined;
|
|
96
|
+
const fromRoot = posix.normalize(specifier);
|
|
97
|
+
if (fromRoot.startsWith('..'))
|
|
98
|
+
throw new ProposalError(`import '${specifier}' leaves the project; imports starting with ./ are relative to the project root`);
|
|
99
|
+
return dotted(posix.relative(proposalsDir, fromRoot));
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
/** Re-expresses the relative imports of a stored proposal for a file in the project-relative directory `toDir`. */
|
|
103
|
+
export function importsForTarget(text, toDir) {
|
|
104
|
+
return rewrite(text, (specifier) => {
|
|
105
|
+
if (!specifier.startsWith('.'))
|
|
106
|
+
return undefined;
|
|
107
|
+
return dotted(posix.relative(toDir === '' ? '.' : toDir, posix.join(proposalsDir, specifier)));
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
/** The proposal's own text after `parseLawFile`: only imports and law declarations are allowed in one. */
|
|
111
|
+
function parts(source) {
|
|
112
|
+
const parsed = parseLawFile(source);
|
|
113
|
+
let rest = source;
|
|
114
|
+
for (const part of [...parsed.laws, ...parsed.imports.map((text) => ({ text }))])
|
|
115
|
+
rest = rest.replace(part.text, '');
|
|
116
|
+
if (rest.trim() !== '')
|
|
117
|
+
throw new ProposalError('a proposal may contain only imports and law declarations');
|
|
118
|
+
return parsed;
|
|
119
|
+
}
|
|
120
|
+
/** The proposed file with the proposal's laws appended (same-named laws replaced) and its imports added once. */
|
|
121
|
+
export function mergeProposal(current, imports, laws) {
|
|
122
|
+
const parsed = parseLawFile(current);
|
|
123
|
+
let text = current;
|
|
124
|
+
for (const law of [...parsed.laws].reverse()) {
|
|
125
|
+
if (laws.some((l) => l.name === law.name))
|
|
126
|
+
text = text.slice(0, law.start) + text.slice(law.end);
|
|
127
|
+
}
|
|
128
|
+
const have = new Set(parseLawFile(text).imports.map((i) => i.replace(/\s+/g, ' ').trim()));
|
|
129
|
+
const missing = imports.filter((i) => !have.has(i.replace(/\s+/g, ' ').trim()));
|
|
130
|
+
const head = missing.length > 0 ? `${missing.join('\n')}\n` : '';
|
|
131
|
+
const body = `${text.trim() === '' ? '' : `${text.trim()}\n\n`}${laws.map((l) => l.text.trim()).join('\n\n')}\n`;
|
|
132
|
+
return `${head}${head !== '' && !body.startsWith('import') ? '\n' : ''}${body}`;
|
|
133
|
+
}
|
|
134
|
+
function write(abs, text) {
|
|
135
|
+
// No following of a link planted at the last moment, where the platform can say so.
|
|
136
|
+
const fd = openSync(abs, constants.O_WRONLY | constants.O_CREAT | constants.O_TRUNC | (constants.O_NOFOLLOW ?? 0), 0o644);
|
|
137
|
+
try {
|
|
138
|
+
writeSync(fd, text);
|
|
139
|
+
}
|
|
140
|
+
finally {
|
|
141
|
+
closeSync(fd);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* Keeps the proposals directory out of git, on first use: appends `.tslaws/proposals` to an existing .gitignore (or
|
|
146
|
+
* creates one in a git checkout) unless `.tslaws` or the directory is already listed. `tslaws init` leaves this to us.
|
|
147
|
+
*/
|
|
148
|
+
function ignoreProposals(cwd) {
|
|
149
|
+
const ignore = join(cwd, '.gitignore');
|
|
150
|
+
const has = existsSync(ignore);
|
|
151
|
+
if (!has && !existsSync(join(cwd, '.git')))
|
|
152
|
+
return;
|
|
153
|
+
const text = has ? readFileSync(ignore, 'utf8') : '';
|
|
154
|
+
const listed = text.split(/\r?\n/).map((l) => l.trim().replace(/^\//, '').replace(/\/$/, ''));
|
|
155
|
+
if (listed.includes('.tslaws') || listed.includes('.tslaws/proposals'))
|
|
156
|
+
return;
|
|
157
|
+
const lead = text === '' || text.endsWith('\n') ? '' : '\n';
|
|
158
|
+
if (has)
|
|
159
|
+
appendFileSync(ignore, `${lead}.tslaws/proposals\n`);
|
|
160
|
+
else
|
|
161
|
+
writeFileSync(ignore, '.tslaws/proposals\n');
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* Adds laws to a proposal (appended; a law of the same name is replaced). `source` holds only imports and `export law`
|
|
165
|
+
* declarations; with `only`, it must declare that law. Writes inside `.tslaws/proposals/` and nowhere else.
|
|
166
|
+
*/
|
|
167
|
+
export function addProposal(cwd, file, source, only) {
|
|
168
|
+
const { rel, abs } = writablePath(cwd, file);
|
|
169
|
+
const stored = toStoredImports(source);
|
|
170
|
+
const parsed = parts(stored);
|
|
171
|
+
if (parsed.laws.length === 0)
|
|
172
|
+
throw new ProposalError('source must declare at least one law (`export law name(...) ...`)');
|
|
173
|
+
if (only !== undefined && !parsed.laws.some((l) => l.name === only))
|
|
174
|
+
throw new ProposalError(`source must contain \`export law ${only}\`…`);
|
|
175
|
+
const current = existsSync(abs) ? readFileSync(abs, 'utf8') : '';
|
|
176
|
+
write(abs, mergeProposal(current, parsed.imports, parsed.laws));
|
|
177
|
+
ignoreProposals(cwd);
|
|
178
|
+
return { file: rel, laws: parsed.laws.map((l) => l.name) };
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* Stores the root-relative imports of a proposal someone placed in the directory by hand, so it resolves where it is.
|
|
182
|
+
* Returns whether the file changed. Does nothing for a path that is not a plain file in the directory.
|
|
183
|
+
*/
|
|
184
|
+
export function normaliseProposal(cwd, file) {
|
|
185
|
+
const { abs } = existingProposal(cwd, file);
|
|
186
|
+
const text = readFileSync(abs, 'utf8');
|
|
187
|
+
const stored = toStoredImports(text);
|
|
188
|
+
if (stored === text)
|
|
189
|
+
return false;
|
|
190
|
+
write(abs, stored);
|
|
191
|
+
return true;
|
|
192
|
+
}
|
package/dist/regressions.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
// The regression corpus: every counterexample a property test finds is kept under `.tslaws/regressions` and replayed
|
|
2
2
|
// before the random search on later runs, so a bug that was found once cannot silently come back.
|
|
3
|
+
import { createHash } from 'node:crypto';
|
|
3
4
|
import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
4
5
|
import { join } from 'node:path';
|
|
5
6
|
/** The most examples kept per law. */
|
|
@@ -38,7 +39,12 @@ export function encodeValue(value) {
|
|
|
38
39
|
throw new Error('cannot store a non-plain object');
|
|
39
40
|
const fields = {};
|
|
40
41
|
for (const key of Object.keys(value))
|
|
41
|
-
fields
|
|
42
|
+
Object.defineProperty(fields, key, {
|
|
43
|
+
value: encodeValue(value[key]),
|
|
44
|
+
enumerable: true,
|
|
45
|
+
writable: true,
|
|
46
|
+
configurable: true,
|
|
47
|
+
});
|
|
42
48
|
return { $t: 'object', v: fields };
|
|
43
49
|
}
|
|
44
50
|
throw new Error(`cannot store a ${typeof value}`);
|
|
@@ -84,8 +90,21 @@ export function decodeExample(text) {
|
|
|
84
90
|
const root = (cwd) => join(cwd, '.tslaws', 'regressions');
|
|
85
91
|
/** `.tslaws/regressions/<law file with / as __>/<law>.json` */
|
|
86
92
|
export function regressionFile(cwd, file, name) {
|
|
93
|
+
return join(root(cwd), file.replace(/[\\/]/g, '__'), `${safeName(name)}.json`);
|
|
94
|
+
}
|
|
95
|
+
function legacyFile(cwd, file, name) {
|
|
87
96
|
return join(root(cwd), file.replace(/[\\/]/g, '__'), `${name}.json`);
|
|
88
97
|
}
|
|
98
|
+
/** A law name as a file name on every platform: characters Windows refuses become `_`, and a hash keeps two names apart. */
|
|
99
|
+
function safeName(name) {
|
|
100
|
+
const safe = [...name]
|
|
101
|
+
.map((ch) => (ch.charCodeAt(0) < 32 || '<>:"/\\|?*'.includes(ch) ? '_' : ch))
|
|
102
|
+
.join('')
|
|
103
|
+
.replace(/[. ]+$/, '');
|
|
104
|
+
if (safe === name)
|
|
105
|
+
return name;
|
|
106
|
+
return `${safe}-${createHash('sha256').update(name).digest('hex').slice(0, 8)}`;
|
|
107
|
+
}
|
|
89
108
|
function readCorpus(path) {
|
|
90
109
|
try {
|
|
91
110
|
const corpus = JSON.parse(readFileSync(path, 'utf8'));
|
|
@@ -97,7 +116,9 @@ function readCorpus(path) {
|
|
|
97
116
|
}
|
|
98
117
|
/** The stored examples of a law as the texts `encodeExample` makes, newest first. */
|
|
99
118
|
export function loadExamples(cwd, file, name) {
|
|
100
|
-
|
|
119
|
+
// Before names were made safe for Windows the file was named with the law's name as written: read that too, so
|
|
120
|
+
// counterexamples an earlier version stored are still replayed (the next save writes the new name).
|
|
121
|
+
const corpus = readCorpus(regressionFile(cwd, file, name)) ?? readCorpus(legacyFile(cwd, file, name));
|
|
101
122
|
return corpus === undefined ? [] : corpus.examples.map((e) => JSON.stringify(e));
|
|
102
123
|
}
|
|
103
124
|
/** Stores `args` as the newest example; an equal older one moves to the front. Returns false when `args` cannot be stored. */
|
package/dist/reporters.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { CheckReport } from './check.ts';
|
|
2
|
+
import type { LawResult } from './types.ts';
|
|
2
3
|
/** The values of `tslaws check --reporter`. `text`, `json` and `ndjson` are rendered by the CLI itself. */
|
|
3
4
|
export declare const reporterNames: readonly ["text", "json", "junit", "github", "ndjson"];
|
|
4
5
|
export type ReporterName = (typeof reporterNames)[number];
|
|
@@ -10,6 +11,8 @@ export declare function escapeAttr(text: string): string;
|
|
|
10
11
|
export declare function escapeGithubData(text: string): string;
|
|
11
12
|
/** Escape a workflow command property value. */
|
|
12
13
|
export declare function escapeGithubProperty(text: string): string;
|
|
14
|
+
/** For a law not yet in the lock: what it would be if accepted, e.g. `if accepted: failed, counterexample [0]`. */
|
|
15
|
+
export declare function proposalText(result: LawResult): string | undefined;
|
|
13
16
|
/** JUnit XML: one `testsuite` per law file, one `testcase` per law. */
|
|
14
17
|
export declare function junit(report: CheckReport): string;
|
|
15
18
|
/** GitHub Actions workflow commands: an annotation per failing result and a notice for bounded or tested ones. */
|
package/dist/reporters.js
CHANGED
|
@@ -45,14 +45,31 @@ function detail(result) {
|
|
|
45
45
|
parts.push(result.message);
|
|
46
46
|
if (result.counterexample !== undefined)
|
|
47
47
|
parts.push(`counterexample ${result.counterexample}`);
|
|
48
|
+
if (result.assumptions !== undefined && result.assumptions.length > 0)
|
|
49
|
+
parts.push(`assuming ${result.assumptions.join('; ')}`);
|
|
48
50
|
if (result.status === 'failed' && result.seed !== undefined)
|
|
49
51
|
parts.push(`seed ${result.seed}`);
|
|
50
52
|
return parts.join('; ');
|
|
51
53
|
}
|
|
54
|
+
/** For a law not yet in the lock: what it would be if accepted, e.g. `if accepted: failed, counterexample [0]`. */
|
|
55
|
+
export function proposalText(result) {
|
|
56
|
+
const p = result.proposal;
|
|
57
|
+
if (p === undefined)
|
|
58
|
+
return undefined;
|
|
59
|
+
const detail = p.counterexample !== undefined
|
|
60
|
+
? `, counterexample ${p.counterexample}`
|
|
61
|
+
: p.status === 'failed' && p.message !== undefined
|
|
62
|
+
? `, ${p.message.split('\n')[0]}`
|
|
63
|
+
: '';
|
|
64
|
+
return `proposal (${p.reason}); if accepted: ${p.status} [${p.method}]${detail}`;
|
|
65
|
+
}
|
|
52
66
|
function failureText(result) {
|
|
53
67
|
const lines = [`${result.status.toUpperCase()} ${result.name} (${result.file}:${result.line}) [${result.method}]`];
|
|
54
68
|
if (result.message !== undefined)
|
|
55
69
|
lines.push(result.message);
|
|
70
|
+
const proposed = proposalText(result);
|
|
71
|
+
if (proposed !== undefined)
|
|
72
|
+
lines.push(proposed);
|
|
56
73
|
if (result.counterexample !== undefined)
|
|
57
74
|
lines.push(`counterexample: ${result.counterexample}`);
|
|
58
75
|
const hint = hintFor(result);
|
package/dist/smt.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type SolverName } from './solvers.ts';
|
|
1
2
|
import type { ManifestLaw } from './types.ts';
|
|
2
3
|
export type Shape = 'number' | 'int' | 'bigint' | 'boolean' | 'string' | {
|
|
3
4
|
array: Shape;
|
|
@@ -6,9 +7,11 @@ export type Shape = 'number' | 'int' | 'bigint' | 'boolean' | 'string' | {
|
|
|
6
7
|
} | undefined;
|
|
7
8
|
export type ProofResult = {
|
|
8
9
|
kind: 'proved';
|
|
10
|
+
assumptions: string[];
|
|
9
11
|
} | {
|
|
10
12
|
kind: 'bounded';
|
|
11
13
|
limits: string[];
|
|
14
|
+
assumptions: string[];
|
|
12
15
|
} | {
|
|
13
16
|
kind: 'refuted';
|
|
14
17
|
model: string;
|
|
@@ -16,6 +19,11 @@ export type ProofResult = {
|
|
|
16
19
|
} | {
|
|
17
20
|
kind: 'unsupported';
|
|
18
21
|
reason: string;
|
|
22
|
+
}
|
|
23
|
+
/** A configured second solver could not run (the cvc5 binary is missing). */
|
|
24
|
+
| {
|
|
25
|
+
kind: 'error';
|
|
26
|
+
message: string;
|
|
19
27
|
};
|
|
20
28
|
export interface ProveInput {
|
|
21
29
|
law: ManifestLaw;
|
|
@@ -28,6 +36,14 @@ export interface ProveInput {
|
|
|
28
36
|
bound: number;
|
|
29
37
|
/** Runs the compiled law on concrete inputs; true when it holds. */
|
|
30
38
|
holds: (inputs: unknown[]) => boolean;
|
|
39
|
+
/** The solvers that must agree on a proof (see solvers.ts); default Z3 alone. */
|
|
40
|
+
solvers?: readonly SolverName[];
|
|
31
41
|
}
|
|
42
|
+
/**
|
|
43
|
+
* The domain assumptions a proof rests on for parameters of these types, in order of first use and without repeats.
|
|
44
|
+
* Arrays are left out (their length bound is a limit of the proof), as is `int` when `intLimit` narrows it (that range is
|
|
45
|
+
* a limit too). `bigint` and `boolean` take nothing for granted.
|
|
46
|
+
*/
|
|
47
|
+
export declare function assumptionsFor(shapes: Shape[], intLimit?: bigint): string[];
|
|
32
48
|
/** Tries to prove `input.law` for every input within `input.bound`. */
|
|
33
49
|
export declare function proveLaw(input: ProveInput): Promise<ProofResult>;
|
package/dist/smt.js
CHANGED
|
@@ -11,8 +11,10 @@
|
|
|
11
11
|
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
12
12
|
import { createRequire } from 'node:module';
|
|
13
13
|
import { Worker } from 'node:worker_threads';
|
|
14
|
+
import { jobs, WorkerPool } from "./pool.js";
|
|
14
15
|
import { dirname, join } from 'node:path';
|
|
15
16
|
import ts from 'typescript';
|
|
17
|
+
import { SolverUnavailable, secondOpinion } from "./solvers.js";
|
|
16
18
|
import { Executor, SpuriousModel, Unsupported, and } from "./symbolic.js";
|
|
17
19
|
const safeRange = (t) => `(and (<= (- 9007199254740991) ${t}) (<= ${t} 9007199254740991))`;
|
|
18
20
|
class Declarations {
|
|
@@ -219,7 +221,6 @@ parentPort.on('message', async ({ id, query, values }) => {
|
|
|
219
221
|
}
|
|
220
222
|
});
|
|
221
223
|
`;
|
|
222
|
-
let worker;
|
|
223
224
|
let nextId = 0;
|
|
224
225
|
function startWorker() {
|
|
225
226
|
const w = new Worker(workerSource, {
|
|
@@ -229,6 +230,8 @@ function startWorker() {
|
|
|
229
230
|
w.unref();
|
|
230
231
|
return w;
|
|
231
232
|
}
|
|
233
|
+
// 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()));
|
|
232
235
|
/**
|
|
233
236
|
* Runs the query, and runs it again in a fresh worker when the solver itself fell over (a WebAssembly allocation that
|
|
234
237
|
* fails on a machine short of memory). A query that merely ran too long is not retried: it would only run long again.
|
|
@@ -247,8 +250,7 @@ async function solve(query, values, timeoutMs) {
|
|
|
247
250
|
}
|
|
248
251
|
/** One try: gives up on the whole worker after the timeout plus a grace period. */
|
|
249
252
|
async function solveOnce(query, values, timeoutMs) {
|
|
250
|
-
|
|
251
|
-
const current = worker;
|
|
253
|
+
const current = await solvers.acquire();
|
|
252
254
|
const id = (nextId += 1);
|
|
253
255
|
return new Promise((resolve, reject) => {
|
|
254
256
|
const drop = () => {
|
|
@@ -257,9 +259,7 @@ async function solveOnce(query, values, timeoutMs) {
|
|
|
257
259
|
current.off('error', onError);
|
|
258
260
|
};
|
|
259
261
|
const kill = () => {
|
|
260
|
-
|
|
261
|
-
if (worker === current)
|
|
262
|
-
worker = undefined;
|
|
262
|
+
solvers.discard(current);
|
|
263
263
|
};
|
|
264
264
|
const timer = setTimeout(() => {
|
|
265
265
|
drop();
|
|
@@ -274,8 +274,10 @@ async function solveOnce(query, values, timeoutMs) {
|
|
|
274
274
|
kill();
|
|
275
275
|
reject(new Unsupported(`the solver crashed: ${reply.error}`));
|
|
276
276
|
}
|
|
277
|
-
else
|
|
277
|
+
else {
|
|
278
|
+
solvers.release(current);
|
|
278
279
|
resolve({ out: reply.out ?? '', vals: reply.vals ?? '' });
|
|
280
|
+
}
|
|
279
281
|
};
|
|
280
282
|
const onError = (error) => {
|
|
281
283
|
drop();
|
|
@@ -300,6 +302,38 @@ function containsArray(shape) {
|
|
|
300
302
|
function show(value) {
|
|
301
303
|
return JSON.stringify(value, (_, v) => (typeof v === 'bigint' ? `${v}n` : v));
|
|
302
304
|
}
|
|
305
|
+
/** What a proof silently takes for granted about each kind of parameter; shown with a `proved` or `bounded` result. */
|
|
306
|
+
const numberAssumption = 'number parameters exclude NaN and ±Infinity';
|
|
307
|
+
const intAssumption = 'int parameters stay within ±(2^53 - 1)';
|
|
308
|
+
const stringAssumption = `string parameters use only characters up to U+FFFF (no surrogate pairs) and at most ${maxStringLength} UTF-16 units`;
|
|
309
|
+
/**
|
|
310
|
+
* The domain assumptions a proof rests on for parameters of these types, in order of first use and without repeats.
|
|
311
|
+
* Arrays are left out (their length bound is a limit of the proof), as is `int` when `intLimit` narrows it (that range is
|
|
312
|
+
* a limit too). `bigint` and `boolean` take nothing for granted.
|
|
313
|
+
*/
|
|
314
|
+
export function assumptionsFor(shapes, intLimit) {
|
|
315
|
+
const found = new Set();
|
|
316
|
+
const visit = (shape) => {
|
|
317
|
+
if (shape === 'number')
|
|
318
|
+
found.add(numberAssumption);
|
|
319
|
+
else if (shape === 'int') {
|
|
320
|
+
if (intLimit === undefined)
|
|
321
|
+
found.add(intAssumption);
|
|
322
|
+
}
|
|
323
|
+
else if (shape === 'string')
|
|
324
|
+
found.add(stringAssumption);
|
|
325
|
+
else if (shape === undefined || typeof shape === 'string')
|
|
326
|
+
return;
|
|
327
|
+
else if ('array' in shape)
|
|
328
|
+
visit(shape.array);
|
|
329
|
+
else
|
|
330
|
+
for (const field of Object.values(shape.fields))
|
|
331
|
+
visit(field);
|
|
332
|
+
};
|
|
333
|
+
for (const shape of shapes)
|
|
334
|
+
visit(shape);
|
|
335
|
+
return [...found];
|
|
336
|
+
}
|
|
303
337
|
/** Ints stay within this in the second attempt, where products and sums cannot leave the safe range. */
|
|
304
338
|
const smallInts = 2n ** 26n;
|
|
305
339
|
/** Tries to prove `input.law` for every input within `input.bound`. */
|
|
@@ -319,6 +353,8 @@ export async function proveLaw(input) {
|
|
|
319
353
|
catch (error) {
|
|
320
354
|
if (error instanceof Unsupported)
|
|
321
355
|
return { kind: 'unsupported', reason: error.message };
|
|
356
|
+
if (error instanceof SolverUnavailable)
|
|
357
|
+
return { kind: 'error', message: error.message };
|
|
322
358
|
throw error;
|
|
323
359
|
}
|
|
324
360
|
}
|
|
@@ -334,7 +370,7 @@ function containsInt(shape) {
|
|
|
334
370
|
async function attempt(input, intLimit) {
|
|
335
371
|
{
|
|
336
372
|
const source = ts.createSourceFile(input.jsFile, readFileSync(input.jsFile, 'utf8'), ts.ScriptTarget.ES2022, true, ts.ScriptKind.JS);
|
|
337
|
-
const fn = source.statements.find((s) => ts.isFunctionDeclaration(s) && s.name?.text === input.law.name);
|
|
373
|
+
const fn = source.statements.find((s) => ts.isFunctionDeclaration(s) && s.name?.text === (input.law.symbol ?? input.law.name));
|
|
338
374
|
if (fn === undefined || fn.body === undefined)
|
|
339
375
|
throw new Unsupported('law function not found in the compiled output');
|
|
340
376
|
if (fn.parameters.length !== input.shapes.length)
|
|
@@ -370,7 +406,14 @@ async function attempt(input, intLimit) {
|
|
|
370
406
|
const { out, vals } = await solve(query.join('\n'), valueQuery, input.timeoutMs);
|
|
371
407
|
const check = out;
|
|
372
408
|
if (check.startsWith('unsat')) {
|
|
373
|
-
|
|
409
|
+
const assumptions = assumptionsFor(input.shapes, intLimit);
|
|
410
|
+
if (executor.bounded.length > 0)
|
|
411
|
+
return { kind: 'bounded', limits: executor.bounded, assumptions };
|
|
412
|
+
// Only a proof that would stand is sent to the second solver.
|
|
413
|
+
const unconfirmed = await secondOpinion(input.solvers ?? [], query.join('\n'), input.timeoutMs);
|
|
414
|
+
return unconfirmed === undefined
|
|
415
|
+
? { kind: 'proved', assumptions }
|
|
416
|
+
: { kind: 'bounded', limits: [unconfirmed], assumptions };
|
|
374
417
|
}
|
|
375
418
|
if (check.startsWith('unknown'))
|
|
376
419
|
throw new Unsupported(`solver gave up within ${input.timeoutMs} ms`);
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
export type SolverName = 'z3' | 'cvc5';
|
|
2
|
+
export declare const solverNames: readonly SolverName[];
|
|
3
|
+
/** The solvers of a project without a `solvers` key: Z3 alone, with no second opinion. */
|
|
4
|
+
export declare const defaultSolvers: readonly SolverName[];
|
|
5
|
+
/** What is wrong with a `solvers` value from tslaws.json, or undefined when it is valid. */
|
|
6
|
+
export declare function solversProblem(value: unknown): string | undefined;
|
|
7
|
+
/** The cvc5 binary is not there to run. */
|
|
8
|
+
export declare class SolverUnavailable extends Error {
|
|
9
|
+
}
|
|
10
|
+
export type Cvc5Answer = {
|
|
11
|
+
kind: 'unsat' | 'sat' | 'unknown';
|
|
12
|
+
} | {
|
|
13
|
+
kind: 'timeout';
|
|
14
|
+
} | {
|
|
15
|
+
kind: 'error';
|
|
16
|
+
detail: string;
|
|
17
|
+
};
|
|
18
|
+
/**
|
|
19
|
+
* The text cvc5 reads: Z3's query without the Z3-only timeout option (cvc5 takes `--tlimit`) and without `(get-model)`,
|
|
20
|
+
* with `(set-logic ALL)` first when the query names no logic.
|
|
21
|
+
*/
|
|
22
|
+
export declare function cvc5Text(query: string): string;
|
|
23
|
+
/** Asks cvc5 for the verdict on the query; a binary that cannot be started throws `SolverUnavailable`. */
|
|
24
|
+
export declare function runCvc5(query: string, timeoutMs: number): Promise<Cvc5Answer>;
|
|
25
|
+
/** The reason cvc5 did not agree, or undefined when it also said `unsat`. */
|
|
26
|
+
export declare function disagreementOf(answer: Cvc5Answer, timeoutMs: number): string | undefined;
|
|
27
|
+
/**
|
|
28
|
+
* Runs the second solver on a query Z3 answered `unsat`. Returns what stops the proof from standing, or undefined when
|
|
29
|
+
* the solvers agree or no second solver is configured.
|
|
30
|
+
*/
|
|
31
|
+
export declare function secondOpinion(solvers: readonly SolverName[], query: string, timeoutMs: number): Promise<string | undefined>;
|
package/dist/solvers.js
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
// A second opinion on proofs. Z3 always decides; when `"solvers": ["z3", "cvc5"]` is set in tslaws.json, a law Z3 proves
|
|
2
|
+
// (an `unsat` answer) counts as `proved` only if the cvc5 binary also says `unsat` to the same SMT-LIB query. Any other
|
|
3
|
+
// answer from cvc5 leaves the law `bounded`, with a limit that names what cvc5 said. Refutations are never sent to cvc5:
|
|
4
|
+
// they already replay in JavaScript.
|
|
5
|
+
import { spawn } from 'node:child_process';
|
|
6
|
+
import { extname } from 'node:path';
|
|
7
|
+
export const solverNames = ['z3', 'cvc5'];
|
|
8
|
+
/** The solvers of a project without a `solvers` key: Z3 alone, with no second opinion. */
|
|
9
|
+
export const defaultSolvers = ['z3'];
|
|
10
|
+
/** What is wrong with a `solvers` value from tslaws.json, or undefined when it is valid. */
|
|
11
|
+
export function solversProblem(value) {
|
|
12
|
+
const allowed = solverNames.map((name) => `"${name}"`).join(' and ');
|
|
13
|
+
if (!Array.isArray(value) || value.length === 0)
|
|
14
|
+
return `"solvers" must be an array of solver names (${allowed}), got ${JSON.stringify(value)}`;
|
|
15
|
+
for (const entry of value) {
|
|
16
|
+
if (typeof entry !== 'string' || !solverNames.includes(entry))
|
|
17
|
+
return `"solvers" has an unknown solver ${JSON.stringify(entry)}; the supported solvers are ${allowed}`;
|
|
18
|
+
}
|
|
19
|
+
if (!value.includes('z3'))
|
|
20
|
+
return '"solvers" must include "z3": Z3 decides every proof and cvc5 only confirms it';
|
|
21
|
+
const repeated = value.find((entry, index) => value.indexOf(entry) !== index);
|
|
22
|
+
if (repeated !== undefined)
|
|
23
|
+
return `"solvers" lists "${repeated}" more than once`;
|
|
24
|
+
return undefined;
|
|
25
|
+
}
|
|
26
|
+
/** The cvc5 binary is not there to run. */
|
|
27
|
+
export class SolverUnavailable extends Error {
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* The text cvc5 reads: Z3's query without the Z3-only timeout option (cvc5 takes `--tlimit`) and without `(get-model)`,
|
|
31
|
+
* with `(set-logic ALL)` first when the query names no logic.
|
|
32
|
+
*/
|
|
33
|
+
export function cvc5Text(query) {
|
|
34
|
+
const lines = query.split('\n').filter((line) => !/^\s*\(set-option\s+:timeout\s+\d+\)\s*$/.test(line));
|
|
35
|
+
const text = lines
|
|
36
|
+
.filter((line) => line.trim() !== '(get-model)')
|
|
37
|
+
.join('\n')
|
|
38
|
+
.trimEnd();
|
|
39
|
+
const logic = /\(set-logic\s/.test(text) ? '' : '(set-logic ALL)\n';
|
|
40
|
+
return `${logic}${text}\n`;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Where the binary is and how to start it: `TSLAWS_CVC5`, else `cvc5` on the PATH. A path ending in .js, .mjs or .cjs is
|
|
44
|
+
* a Node script and runs under the current Node (the tests use one as a fake solver, which a .cmd file could not do on
|
|
45
|
+
* every platform); anything else is run as it is. No shell is involved.
|
|
46
|
+
*/
|
|
47
|
+
function command() {
|
|
48
|
+
const path = process.env.TSLAWS_CVC5 ?? 'cvc5';
|
|
49
|
+
return ['.js', '.mjs', '.cjs'].includes(extname(path))
|
|
50
|
+
? { file: process.execPath, args: [path] }
|
|
51
|
+
: { file: path, args: [] };
|
|
52
|
+
}
|
|
53
|
+
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
|
+
/** Asks cvc5 for the verdict on the query; a binary that cannot be started throws `SolverUnavailable`. */
|
|
55
|
+
export function runCvc5(query, timeoutMs) {
|
|
56
|
+
const { file, args } = command();
|
|
57
|
+
return new Promise((resolve, reject) => {
|
|
58
|
+
const child = spawn(file, [...args, '--lang', 'smt2', '--tlimit', String(timeoutMs)], {
|
|
59
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
60
|
+
windowsHide: true,
|
|
61
|
+
});
|
|
62
|
+
let stdout = '';
|
|
63
|
+
let stderr = '';
|
|
64
|
+
let finished = false;
|
|
65
|
+
const done = (answer) => {
|
|
66
|
+
if (finished)
|
|
67
|
+
return;
|
|
68
|
+
finished = true;
|
|
69
|
+
clearTimeout(timer);
|
|
70
|
+
resolve(answer);
|
|
71
|
+
};
|
|
72
|
+
// cvc5 stops itself at --tlimit; the grace period only catches a process that does not.
|
|
73
|
+
const timer = setTimeout(() => {
|
|
74
|
+
child.kill();
|
|
75
|
+
done({ kind: 'timeout' });
|
|
76
|
+
}, timeoutMs + 3000);
|
|
77
|
+
child.stdout.setEncoding('utf8').on('data', (chunk) => (stdout += chunk));
|
|
78
|
+
child.stderr.setEncoding('utf8').on('data', (chunk) => (stderr += chunk));
|
|
79
|
+
child.on('error', (error) => {
|
|
80
|
+
if (finished)
|
|
81
|
+
return;
|
|
82
|
+
if (error.code === 'ENOENT' || error.code === 'EACCES') {
|
|
83
|
+
finished = true;
|
|
84
|
+
clearTimeout(timer);
|
|
85
|
+
reject(missing());
|
|
86
|
+
}
|
|
87
|
+
else
|
|
88
|
+
done({ kind: 'error', detail: error.message });
|
|
89
|
+
});
|
|
90
|
+
child.on('close', (code) => {
|
|
91
|
+
const first = stdout.trim().split('\n')[0]?.trim() ?? '';
|
|
92
|
+
if (code === 0 && (first === 'unsat' || first === 'sat' || first === 'unknown'))
|
|
93
|
+
done({ kind: first });
|
|
94
|
+
else {
|
|
95
|
+
const detail = first !== '' ? first : stderr.trim().split('\n')[0]?.trim() || `exited with code ${code}`;
|
|
96
|
+
done({ kind: 'error', detail });
|
|
97
|
+
}
|
|
98
|
+
});
|
|
99
|
+
child.stdin.on('error', () => undefined);
|
|
100
|
+
child.stdin.end(cvc5Text(query));
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
/** The reason cvc5 did not agree, or undefined when it also said `unsat`. */
|
|
104
|
+
export function disagreementOf(answer, timeoutMs) {
|
|
105
|
+
if (answer.kind === 'unsat')
|
|
106
|
+
return undefined;
|
|
107
|
+
if (answer.kind === 'timeout')
|
|
108
|
+
return `cvc5 did not confirm the proof (no answer within ${timeoutMs} ms)`;
|
|
109
|
+
if (answer.kind === 'error')
|
|
110
|
+
return `cvc5 did not confirm the proof (error: ${answer.detail})`;
|
|
111
|
+
return `cvc5 did not confirm the proof (${answer.kind})`;
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Runs the second solver on a query Z3 answered `unsat`. Returns what stops the proof from standing, or undefined when
|
|
115
|
+
* the solvers agree or no second solver is configured.
|
|
116
|
+
*/
|
|
117
|
+
export async function secondOpinion(solvers, query, timeoutMs) {
|
|
118
|
+
if (!solvers.includes('cvc5'))
|
|
119
|
+
return undefined;
|
|
120
|
+
return disagreementOf(await runCvc5(query, timeoutMs), timeoutMs);
|
|
121
|
+
}
|
package/dist/symbolic.js
CHANGED
|
@@ -439,7 +439,7 @@ export class Executor {
|
|
|
439
439
|
block(statements, f, pc) {
|
|
440
440
|
const outer = new Set(f.env.keys());
|
|
441
441
|
this.execList(statements, f, pc);
|
|
442
|
-
for (const name of
|
|
442
|
+
for (const name of f.env.keys())
|
|
443
443
|
if (!outer.has(name))
|
|
444
444
|
f.env.delete(name);
|
|
445
445
|
}
|
|
@@ -493,7 +493,7 @@ export class Executor {
|
|
|
493
493
|
this.ev(node.initializer, f, pc, true);
|
|
494
494
|
}
|
|
495
495
|
this.loop(undefined, node.condition, node.incrementor, node.statement, f, pc);
|
|
496
|
-
for (const name of
|
|
496
|
+
for (const name of f.env.keys())
|
|
497
497
|
if (!outer.has(name))
|
|
498
498
|
f.env.delete(name);
|
|
499
499
|
}
|