gdp-wired 0.46.0 → 0.48.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 +18 -5
- package/dist/core/carry.d.ts +15 -0
- package/dist/core/carry.js +651 -0
- package/dist/core/cli.d.ts +4 -1
- package/dist/core/cli.js +31 -11
- package/dist/core/count-cases.d.ts +24 -0
- package/dist/core/count-cases.js +320 -0
- package/dist/core/count-cert-grow.d.ts +4 -0
- package/dist/core/count-cert-grow.js +37 -0
- package/dist/core/count-cert-transport.d.ts +3 -0
- package/dist/core/count-cert-transport.js +58 -0
- package/dist/core/count-completion.d.ts +9 -0
- package/dist/core/count-completion.js +27 -0
- package/dist/core/count-cubes.d.ts +8 -0
- package/dist/core/count-cubes.js +69 -0
- package/dist/core/count-demand.d.ts +37 -0
- package/dist/core/count-demand.js +361 -0
- package/dist/core/count-facts.d.ts +52 -0
- package/dist/core/count-facts.js +247 -0
- package/dist/core/count-focus-proof.d.ts +8 -0
- package/dist/core/count-focus-proof.js +140 -0
- package/dist/core/count-focused.d.ts +22 -0
- package/dist/core/count-focused.js +676 -0
- package/dist/core/count-ranges.d.ts +5 -0
- package/dist/core/count-ranges.js +65 -0
- package/dist/core/count-recovery/action-guard.d.ts +5 -0
- package/dist/core/count-recovery/action-guard.js +51 -0
- package/dist/core/count-recovery/boolean-core.d.ts +16 -0
- package/dist/core/count-recovery/boolean-core.js +258 -0
- package/dist/core/count-recovery/carried-case.d.ts +2 -0
- package/dist/core/count-recovery/carried-case.js +24 -0
- package/dist/core/count-recovery/conditional-check-cache.d.ts +23 -0
- package/dist/core/count-recovery/conditional-check-cache.js +130 -0
- package/dist/core/count-recovery/conditional-cuts.d.ts +6 -0
- package/dist/core/count-recovery/conditional-cuts.js +318 -0
- package/dist/core/count-recovery/conditional-proof.d.ts +19 -0
- package/dist/core/count-recovery/conditional-proof.js +306 -0
- package/dist/core/count-recovery/derivability-closure.d.ts +14 -0
- package/dist/core/count-recovery/derivability-closure.js +533 -0
- package/dist/core/count-recovery/empty-count-source.d.ts +2 -0
- package/dist/core/count-recovery/empty-count-source.js +40 -0
- package/dist/core/count-recovery/field-bound-lemmas.d.ts +23 -0
- package/dist/core/count-recovery/field-bound-lemmas.js +640 -0
- package/dist/core/count-recovery/field-case.d.ts +5 -0
- package/dist/core/count-recovery/field-case.js +89 -0
- package/dist/core/count-recovery/field-demand.d.ts +46 -0
- package/dist/core/count-recovery/field-demand.js +47 -0
- package/dist/core/count-recovery/field-only.d.ts +3 -0
- package/dist/core/count-recovery/field-only.js +18 -0
- package/dist/core/count-recovery/fold-path.d.ts +6 -0
- package/dist/core/count-recovery/fold-path.js +35 -0
- package/dist/core/count-recovery/frame-lemmas.d.ts +9 -0
- package/dist/core/count-recovery/frame-lemmas.js +120 -0
- package/dist/core/count-recovery/guard-cases.d.ts +12 -0
- package/dist/core/count-recovery/guard-cases.js +138 -0
- package/dist/core/count-recovery/key-closure.d.ts +14 -0
- package/dist/core/count-recovery/key-closure.js +62 -0
- package/dist/core/count-recovery/leaf-allowance.d.ts +4 -0
- package/dist/core/count-recovery/leaf-allowance.js +7 -0
- package/dist/core/count-recovery/lift-count-proxies.d.ts +6 -0
- package/dist/core/count-recovery/lift-count-proxies.js +175 -0
- package/dist/core/count-recovery/live-dependencies.d.ts +6 -0
- package/dist/core/count-recovery/live-dependencies.js +76 -0
- package/dist/core/count-recovery/member-inclusions.d.ts +11 -0
- package/dist/core/count-recovery/member-inclusions.js +168 -0
- package/dist/core/count-recovery/member-premises.d.ts +29 -0
- package/dist/core/count-recovery/member-premises.js +114 -0
- package/dist/core/count-recovery/natural-cases.d.ts +6 -0
- package/dist/core/count-recovery/natural-cases.js +59 -0
- package/dist/core/count-recovery/ops.d.ts +6 -0
- package/dist/core/count-recovery/ops.js +8 -0
- package/dist/core/count-recovery/pre-state-source.d.ts +8 -0
- package/dist/core/count-recovery/pre-state-source.js +18 -0
- package/dist/core/count-recovery/rebase-path.d.ts +9 -0
- package/dist/core/count-recovery/rebase-path.js +70 -0
- package/dist/core/count-recovery/rename-proof.d.ts +2 -0
- package/dist/core/count-recovery/rename-proof.js +102 -0
- package/dist/core/count-recovery/row-cases.d.ts +16 -0
- package/dist/core/count-recovery/row-cases.js +291 -0
- package/dist/core/count-recovery/scalar-guards.d.ts +7 -0
- package/dist/core/count-recovery/scalar-guards.js +291 -0
- package/dist/core/count-recovery/source-memo.d.ts +12 -0
- package/dist/core/count-recovery/source-memo.js +67 -0
- package/dist/core/count-select.d.ts +16 -0
- package/dist/core/count-select.js +24 -0
- package/dist/core/count-support.d.ts +598 -0
- package/dist/core/count-support.js +2080 -0
- package/dist/core/count-unions.d.ts +2 -0
- package/dist/core/count-unions.js +139 -0
- package/dist/core/count-witness-flags.d.ts +9 -0
- package/dist/core/count-witness-flags.js +37 -0
- package/dist/core/count-write-frames.d.ts +12 -0
- package/dist/core/count-write-frames.js +206 -0
- package/dist/core/counts.d.ts +20 -2
- package/dist/core/counts.js +807 -156
- package/dist/core/dsl.d.ts +50 -6
- package/dist/core/dsl.js +307 -65
- package/dist/core/effect-schema.d.ts +90 -0
- package/dist/core/effect-schema.js +500 -0
- package/dist/core/effect.d.ts +3 -7
- package/dist/core/effect.js +10 -65
- package/dist/core/exists.d.ts +1 -1
- package/dist/core/exists.js +80 -15
- package/dist/core/extract-check.d.ts +7 -1
- package/dist/core/extract-check.js +161 -19
- package/dist/core/extract-go-check.js +24 -4
- package/dist/core/extract-go.d.ts +7 -0
- package/dist/core/extract-go.js +29 -2
- package/dist/core/extract-read.d.ts +31 -9
- package/dist/core/extract-read.js +36 -11
- package/dist/core/extract-rs.js +58 -14
- package/dist/core/extract-shapes.d.ts +1 -0
- package/dist/core/extract-shapes.js +190 -27
- package/dist/core/extract-standalone.d.ts +3 -0
- package/dist/core/extract-standalone.js +265 -0
- package/dist/core/extract.d.ts +1 -0
- package/dist/core/extract.js +25 -5
- package/dist/core/field-laws.d.ts +2 -0
- package/dist/core/field-laws.js +100 -0
- package/dist/core/finite-frontiers.d.ts +5 -0
- package/dist/core/finite-frontiers.js +116 -0
- package/dist/core/finite-houdini.d.ts +52 -0
- package/dist/core/finite-houdini.js +460 -0
- package/dist/core/finite-model.d.ts +13 -0
- package/dist/core/finite-model.js +68 -0
- package/dist/core/finite-tiny.d.ts +72 -0
- package/dist/core/finite-tiny.js +1052 -0
- package/dist/core/infer.d.ts +1 -1
- package/dist/core/infer.js +32 -9
- package/dist/core/laws.d.ts +2 -1
- package/dist/core/laws.js +76 -19
- package/dist/core/lemma-cuts.d.ts +38 -0
- package/dist/core/lemma-cuts.js +365 -0
- package/dist/core/machine.d.ts +39 -2
- package/dist/core/machine.js +240 -35
- package/dist/core/mutate.d.ts +55 -0
- package/dist/core/mutate.js +210 -0
- package/dist/core/native-domain.d.ts +6 -0
- package/dist/core/native-domain.js +114 -0
- package/dist/core/native-law.d.ts +3 -0
- package/dist/core/native-law.js +174 -0
- package/dist/core/quorum-laws.d.ts +5 -0
- package/dist/core/quorum-laws.js +239 -0
- package/dist/core/relational.js +10 -2
- package/dist/core/relevance.d.ts +4 -0
- package/dist/core/relevance.js +79 -0
- package/dist/core/rs/Cargo.toml +1 -1
- package/dist/core/rs/src/main.rs +458 -9
- package/dist/core/runtime-wall.d.ts +3 -0
- package/dist/core/runtime-wall.js +4 -0
- package/dist/core/sample-step.d.ts +16 -0
- package/dist/core/sample-step.js +28 -0
- package/dist/core/source-check.d.ts +44 -0
- package/dist/core/source-check.js +126 -0
- package/dist/core/source-diagnostic.d.ts +1 -0
- package/dist/core/source-diagnostic.js +34 -0
- package/dist/core/support-budget.d.ts +2 -0
- package/dist/core/support-budget.js +6 -0
- package/dist/core/system.js +2 -0
- package/dist/core/wall.d.ts +6 -0
- package/dist/core/wall.js +23 -0
- package/dist/core/watch.js +4 -0
- package/dist/kernel/cdcl.d.ts +4 -0
- package/dist/kernel/cdcl.js +20 -5
- package/dist/kernel/kernel.d.ts +10 -0
- package/dist/kernel/kernel.js +56 -3
- package/dist/kernel/model-sequence.d.ts +2 -2
- package/dist/kernel/model-sequence.js +4 -3
- package/dist/kernel/model-values.d.ts +2 -0
- package/dist/kernel/model-values.js +60 -0
- package/dist/kernel/prove.d.ts +10 -0
- package/dist/kernel/prove.js +56 -8
- package/dist/kernel/prover-rows.d.ts +29 -0
- package/dist/kernel/prover-rows.js +114 -0
- package/dist/lean-kernel/emit.d.ts +39 -2
- package/dist/lean-kernel/emit.js +136 -24
- package/dist/lean-kernel/lean-terms.d.ts +1 -0
- package/dist/lean-kernel/lean-terms.js +13 -5
- package/dist/lean-kernel/library.js +4 -0
- package/dist/lean-kernel/qalpha.d.ts +7 -0
- package/dist/lean-kernel/qalpha.js +40 -0
- package/package.json +5 -1
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
const cell = (text) => text.replace(/\|/g, '\\|').replace(/[\r\n]+/g, ' ');
|
|
2
|
+
const sameBytes = (a, b) => a.length === b.length && a.every((v, i) => b[i] === v);
|
|
3
|
+
/** Compare each trusted source edit against each suite, restoring exact original bytes in finally.
|
|
4
|
+
* Infrastructure errors (including timeout/signal/output overflow) never count as a killed mutant.
|
|
5
|
+
* No process can restore after SIGKILL or power loss: use a disposable working tree.
|
|
6
|
+
*/
|
|
7
|
+
export function checkMutations(config) {
|
|
8
|
+
if (!config || !Array.isArray(config.mutants) || !config.mutants.length || !Array.isArray(config.suites) || !config.suites.length)
|
|
9
|
+
throw new Error('mutate needs nonempty mutants and suites');
|
|
10
|
+
const names = config.suites.map(s => s.name);
|
|
11
|
+
if (names.some(n => typeof n !== 'string' || !n.trim()) || new Set(names).size !== names.length || !names.includes(config.lawSuite))
|
|
12
|
+
throw new Error('mutate needs unique suite names and a designated lawSuite');
|
|
13
|
+
for (const suite of config.suites)
|
|
14
|
+
if (!Array.isArray(suite.command) || !suite.command.length || suite.command.some(s => typeof s !== 'string' || !s))
|
|
15
|
+
throw new Error(`suite ${suite.name}: command must be a nonempty argv array`);
|
|
16
|
+
const timeout = config.timeoutMs ?? 120_000;
|
|
17
|
+
if (!Number.isSafeInteger(timeout) || timeout <= 0 || timeout > 2_147_483_647)
|
|
18
|
+
throw new Error('timeoutMs must be a positive safe integer at most 2147483647');
|
|
19
|
+
const proc = globalThis.process;
|
|
20
|
+
if (!proc?.getBuiltinModule)
|
|
21
|
+
throw new Error('mutation checks need Node.js 20.16+ or Bun');
|
|
22
|
+
if (proc.platform === 'win32')
|
|
23
|
+
throw new Error('mutation checks require POSIX process-group supervision');
|
|
24
|
+
const fs = proc.getBuiltinModule('node:fs');
|
|
25
|
+
const path = proc.getBuiltinModule('node:path');
|
|
26
|
+
const { spawnSync } = proc.getBuiltinModule('node:child_process');
|
|
27
|
+
const cwd = path.resolve(config.cwd ?? proc.cwd());
|
|
28
|
+
const snapshots = new Map();
|
|
29
|
+
const edits = config.mutants.map((edit, index) => {
|
|
30
|
+
if (!edit || typeof edit.file !== 'string' || !edit.file || typeof edit.from !== 'string' || !edit.from || typeof edit.to !== 'string' || edit.to === edit.from || typeof edit.bug !== 'string' || !edit.bug.trim())
|
|
31
|
+
throw new Error(`mutant ${index + 1}: file, nonempty from, different to, and bug are required`);
|
|
32
|
+
if (edit.name !== undefined && (typeof edit.name !== 'string' || !edit.name.trim()))
|
|
33
|
+
throw new Error(`mutant ${index + 1}: name must be a nonempty string`);
|
|
34
|
+
const file = path.resolve(cwd, edit.file), stat = fs.lstatSync(file);
|
|
35
|
+
if (!stat.isFile() || stat.isSymbolicLink())
|
|
36
|
+
throw new Error(`mutant ${index + 1}: source must be a regular, non-symlink file`);
|
|
37
|
+
let original = snapshots.get(file);
|
|
38
|
+
if (!original) {
|
|
39
|
+
const bytes = fs.readFileSync(file);
|
|
40
|
+
original = { bytes, text: new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes) };
|
|
41
|
+
snapshots.set(file, original);
|
|
42
|
+
}
|
|
43
|
+
const first = original.text.indexOf(edit.from);
|
|
44
|
+
if (first < 0)
|
|
45
|
+
throw new Error(`mutant ${index + 1}: from text not found in ${edit.file}`);
|
|
46
|
+
if (original.text.indexOf(edit.from, first + 1) >= 0)
|
|
47
|
+
throw new Error(`mutant ${index + 1}: from text is ambiguous in ${edit.file}`);
|
|
48
|
+
return { edit, file, original, mutant: edit.name ?? String(index + 1) };
|
|
49
|
+
});
|
|
50
|
+
// Each suite owns a fresh POSIX process group. After the leader exits (including timeout), enumerate that
|
|
51
|
+
// exact group's remaining PIDs, kill each exact PID, and await quiescence before touching source bytes.
|
|
52
|
+
// A deliberately detached session or external writer is outside this trusted-command boundary.
|
|
53
|
+
const supervise = (group) => {
|
|
54
|
+
if (!group || group <= 0)
|
|
55
|
+
return undefined;
|
|
56
|
+
const until = Date.now() + 3000, pause = new Int32Array(new SharedArrayBuffer(4));
|
|
57
|
+
do {
|
|
58
|
+
const scan = spawnSync('ps', ['-eo', 'pid=,pgid=,stat='], { cwd, encoding: 'utf8', timeout: 2000, maxBuffer: 1024 * 1024, killSignal: 'SIGKILL', windowsHide: true, detached: false });
|
|
59
|
+
if (scan.error || scan.status !== 0)
|
|
60
|
+
return `cannot verify suite descendants: ${scan.error?.message ?? `ps exited ${scan.status}`}`;
|
|
61
|
+
const live = (scan.stdout ?? '').split('\n').map(line => line.trim().split(/\s+/)).filter(parts => Number(parts[1]) === group && !parts[2]?.startsWith('Z')).map(parts => Number(parts[0]));
|
|
62
|
+
if (!live.length)
|
|
63
|
+
return undefined;
|
|
64
|
+
for (const pid of live) {
|
|
65
|
+
try {
|
|
66
|
+
proc.kill(pid, 'SIGKILL');
|
|
67
|
+
}
|
|
68
|
+
catch (error) {
|
|
69
|
+
if (error.code !== 'ESRCH')
|
|
70
|
+
return `cannot stop suite descendant ${pid}: ${String(error)}`;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
Atomics.wait(pause, 0, 0, 10);
|
|
74
|
+
} while (Date.now() < until);
|
|
75
|
+
return 'suite descendants did not stop before the cleanup deadline';
|
|
76
|
+
};
|
|
77
|
+
const run = (suite) => {
|
|
78
|
+
const p = spawnSync(suite.command[0], suite.command.slice(1), { cwd, encoding: 'utf8', timeout, maxBuffer: 1024 * 1024, killSignal: 'SIGKILL', windowsHide: true, detached: true });
|
|
79
|
+
const cleanup = supervise(p.pid);
|
|
80
|
+
const error = cleanup ?? p.error?.message ?? (p.signal ? `terminated by ${p.signal}` : p.status === null ? 'no exit status' : undefined);
|
|
81
|
+
return { status: error ? 'error' : p.status === 0 ? 'missed' : 'caught', exit: p.status, output: `${p.stdout ?? ''}${p.stderr ?? ''}`.slice(-65536), ...(error ? { error } : {}) };
|
|
82
|
+
};
|
|
83
|
+
for (const suite of config.suites) {
|
|
84
|
+
const result = run(suite);
|
|
85
|
+
if (result.status !== 'missed')
|
|
86
|
+
throw new Error(`suite ${suite.name} fails unmutated: ${result.error ?? `exit ${result.exit}`}\n${result.output}`);
|
|
87
|
+
}
|
|
88
|
+
const rows = [];
|
|
89
|
+
for (const { edit, file, original, mutant } of edits) {
|
|
90
|
+
if (!sameBytes(fs.readFileSync(file), original.bytes))
|
|
91
|
+
throw new Error(`mutant ${mutant}: source changed since preflight; refusing to overwrite it`);
|
|
92
|
+
const text = original.text.replace(edit.from, () => edit.to);
|
|
93
|
+
try {
|
|
94
|
+
fs.writeFileSync(file, text);
|
|
95
|
+
const suites = Object.fromEntries(config.suites.map(suite => [suite.name, run(suite)]));
|
|
96
|
+
rows.push({ mutant, bug: edit.bug, suites });
|
|
97
|
+
}
|
|
98
|
+
finally {
|
|
99
|
+
fs.writeFileSync(file, original.bytes);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
const header = ['Mutant', 'Bug', ...names];
|
|
103
|
+
const table = [header, header.map(() => '---'), ...rows.map(row => [row.mutant, row.bug, ...names.map(n => row.suites[n].status)])];
|
|
104
|
+
const markdown = table.map(row => `| ${row.map(cell).join(' | ')} |`).join('\n');
|
|
105
|
+
const passed = rows.every(row => row.suites[config.lawSuite].status === 'caught' && Object.values(row.suites).every(r => r.status !== 'error'));
|
|
106
|
+
return { passed, rows, markdown };
|
|
107
|
+
}
|
|
108
|
+
/** Derive single-occurrence implementation mutations, not weakened laws or assumptions.
|
|
109
|
+
* Pure scalar decisions only. The explicit printer bridges machine terms to the source artifact under test;
|
|
110
|
+
* this does not claim an automatic inverse mapping from terms to arbitrary hand-written TypeScript.
|
|
111
|
+
* Candidates may be equivalent: only the suites determine which laws kill them.
|
|
112
|
+
*/
|
|
113
|
+
export function deriveDecisionMutants(machine, options) {
|
|
114
|
+
const cap = options.maxCandidates ?? 64;
|
|
115
|
+
if (!Number.isSafeInteger(cap) || cap < 1 || cap > 1000)
|
|
116
|
+
throw new Error('maxCandidates must be an integer from 1 to 1000');
|
|
117
|
+
if (typeof options.file !== 'string' || !options.file || typeof options.render !== 'function')
|
|
118
|
+
throw new Error('decision mutations need a file and deterministic render function');
|
|
119
|
+
if (machine.history || [machine.maps, machine.step.maps, machine.fns, machine.sums, machine.counts, machine.leasts, machine.relations].some(x => x && Object.keys(x).length) || machine.inputMaps?.length)
|
|
120
|
+
throw new Error('decision mutations require a pure scalar decision');
|
|
121
|
+
const names = new Set([...machine.inputs, ...machine.params]);
|
|
122
|
+
for (const [name, values] of Object.entries(options.choices ?? {})) {
|
|
123
|
+
if (!names.has(name) || !Array.isArray(values) || values.length < 2 || values.length > 1000 || values.some(x => !Number.isSafeInteger(x) || x < 0) || new Set(values).size !== values.length)
|
|
124
|
+
throw new Error(`invalid choice encodings for ${name}`);
|
|
125
|
+
}
|
|
126
|
+
const baseline = options.render(machine);
|
|
127
|
+
if (typeof baseline !== 'string' || !baseline)
|
|
128
|
+
throw new Error('render must return nonempty source text');
|
|
129
|
+
// JSON terms have no object-identity semantics; break sharing so each path really is one occurrence.
|
|
130
|
+
const serialized = JSON.stringify(machine);
|
|
131
|
+
const result = [], seen = new Set([baseline]);
|
|
132
|
+
let visited = 0;
|
|
133
|
+
const add = (kind, path, replacement) => {
|
|
134
|
+
if (result.length >= cap)
|
|
135
|
+
return;
|
|
136
|
+
const variant = JSON.parse(serialized);
|
|
137
|
+
let parent = variant;
|
|
138
|
+
for (const part of path.slice(0, -1))
|
|
139
|
+
parent = parent[part];
|
|
140
|
+
parent[path[path.length - 1]] = replacement;
|
|
141
|
+
const to = options.render(variant);
|
|
142
|
+
if (typeof to !== 'string' || !to)
|
|
143
|
+
throw new Error('render must return nonempty source text');
|
|
144
|
+
if (seen.has(to))
|
|
145
|
+
return;
|
|
146
|
+
seen.add(to);
|
|
147
|
+
result.push({ file: options.file, from: baseline, to, name: `${kind}-${String(result.length + 1).padStart(3, '0')}`, bug: `${kind} at ${path.join('.')}` });
|
|
148
|
+
};
|
|
149
|
+
const visit = () => { if (++visited > 10000)
|
|
150
|
+
throw new Error('decision has too many term occurrences'); };
|
|
151
|
+
const expr = (e, path) => {
|
|
152
|
+
visit();
|
|
153
|
+
if (e.op === 'var') {
|
|
154
|
+
if (!names.has(e.name))
|
|
155
|
+
throw new Error(`decision reads non-input state ${e.name}`);
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
if (e.op === 'const')
|
|
159
|
+
return;
|
|
160
|
+
if (e.op === 'get')
|
|
161
|
+
throw new Error('decision mutations do not support map or helper reads');
|
|
162
|
+
if (e.op === 'if') {
|
|
163
|
+
add('negate-guard', [...path, 'c'], { op: 'not', x: e.c });
|
|
164
|
+
cond(e.c, [...path, 'c']);
|
|
165
|
+
expr(e.then, [...path, 'then']);
|
|
166
|
+
expr(e.else, [...path, 'else']);
|
|
167
|
+
return;
|
|
168
|
+
}
|
|
169
|
+
expr(e.a, [...path, 'a']);
|
|
170
|
+
if ('b' in e)
|
|
171
|
+
expr(e.b, [...path, 'b']);
|
|
172
|
+
};
|
|
173
|
+
const cond = (c, path) => {
|
|
174
|
+
visit();
|
|
175
|
+
if (c.op === 'all')
|
|
176
|
+
throw new Error('decision mutations do not support quantified guards');
|
|
177
|
+
if (c.op === 'flag') {
|
|
178
|
+
if (!machine.step.flags?.[c.name])
|
|
179
|
+
throw new Error(`unknown decision flag ${c.name}`);
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
if (c.op === 'not') {
|
|
183
|
+
cond(c.x, [...path, 'x']);
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
if (c.op === 'and' || c.op === 'or') {
|
|
187
|
+
if (c.op === 'and')
|
|
188
|
+
c.xs.forEach((_, i) => add('drop-conjunct', path, { ...c, xs: c.xs.filter((_, j) => i !== j) }));
|
|
189
|
+
c.xs.forEach((x, i) => cond(x, [...path, 'xs', i]));
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
192
|
+
add('flip-comparison', path, c.op === '=' ? { op: 'not', x: c } : { ...c, op: c.op === '<' ? '<=' : '<' });
|
|
193
|
+
if (c.op === '=') {
|
|
194
|
+
const pair = c.a.op === 'var' && c.b.op === 'const' ? [c.a, c.b] : c.b.op === 'var' && c.a.op === 'const' ? [c.b, c.a] : undefined;
|
|
195
|
+
if (pair)
|
|
196
|
+
for (const value of options.choices?.[pair[0].name] ?? []) {
|
|
197
|
+
if (value !== pair[1].value)
|
|
198
|
+
add('widen-choice', path, { op: 'or', xs: [c, { op: '=', a: pair[0], b: { op: 'const', value } }] });
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
expr(c.a, [...path, 'a']);
|
|
202
|
+
expr(c.b, [...path, 'b']);
|
|
203
|
+
};
|
|
204
|
+
// Do not mutate preconditions, input-domain assumptions, initial state, or law/fact terms.
|
|
205
|
+
for (const [name, flag] of Object.entries(machine.step.flags ?? {}))
|
|
206
|
+
cond(flag, ['step', 'flags', name]);
|
|
207
|
+
for (const [name, value] of Object.entries(machine.step.state ?? {}))
|
|
208
|
+
expr(value, ['step', 'state', name]);
|
|
209
|
+
return result;
|
|
210
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export type NativeInputs = {
|
|
2
|
+
domains?: unknown[][];
|
|
3
|
+
reason?: string;
|
|
4
|
+
};
|
|
5
|
+
export declare function nativeCaptureEdits(code: string, file: string, methods: string[]): [number, string][];
|
|
6
|
+
export declare function nativeInputs(code: string, file: string, entry: string, files?: Record<string, string>): NativeInputs;
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
// Read native argument domains from TypeScript's types, independently of symbolic
|
|
2
|
+
// input variables/heap identities. Capture the actual parameter bindings at entry,
|
|
3
|
+
// after JS defaults and destructuring, rather than rebuilding them from the model.
|
|
4
|
+
import ts from 'typescript';
|
|
5
|
+
import { normalize, program, scriptKind } from "./extract-read.js";
|
|
6
|
+
const LIMIT = 65536;
|
|
7
|
+
class TooLarge extends Error {
|
|
8
|
+
}
|
|
9
|
+
function named(n) {
|
|
10
|
+
if (ts.isFunctionDeclaration(n) || ts.isMethodDeclaration(n))
|
|
11
|
+
return n.name && (ts.isIdentifier(n.name) || ts.isStringLiteral(n.name)) ? n.name.text : undefined;
|
|
12
|
+
if (ts.isArrowFunction(n) || ts.isFunctionExpression(n)) {
|
|
13
|
+
const p = n.parent;
|
|
14
|
+
if ((ts.isVariableDeclaration(p) || ts.isPropertyAssignment(p)) && (ts.isIdentifier(p.name) || ts.isStringLiteral(p.name)))
|
|
15
|
+
return p.name.text;
|
|
16
|
+
}
|
|
17
|
+
return undefined;
|
|
18
|
+
}
|
|
19
|
+
const callable = (n) => ts.isFunctionDeclaration(n) || ts.isMethodDeclaration(n) || ts.isArrowFunction(n) || ts.isFunctionExpression(n);
|
|
20
|
+
function bindingNames(name) {
|
|
21
|
+
return ts.isIdentifier(name) ? [name.text] : name.elements.flatMap(e => ts.isOmittedExpression(e) ? [] : bindingNames(e.name));
|
|
22
|
+
}
|
|
23
|
+
export function nativeCaptureEdits(code, file, methods) {
|
|
24
|
+
if (!methods.length)
|
|
25
|
+
return [];
|
|
26
|
+
const sf = ts.createSourceFile(file, code, ts.ScriptTarget.ES2022, true, scriptKind(file)), edits = [];
|
|
27
|
+
const visit = (n) => {
|
|
28
|
+
if (callable(n) && n.body && methods.includes(named(n) ?? '')) {
|
|
29
|
+
const names = n.parameters.flatMap(p => bindingNames(p.name)), capture = `__gdp_native_capture(${JSON.stringify(named(n))}, {${names.join(',')}})`;
|
|
30
|
+
if (ts.isBlock(n.body))
|
|
31
|
+
edits.push([n.body.getStart(sf) + 1, `${capture};`]);
|
|
32
|
+
else
|
|
33
|
+
edits.push([n.body.getStart(sf), `(${capture}, (`], [n.body.end, '))']);
|
|
34
|
+
}
|
|
35
|
+
ts.forEachChild(n, visit);
|
|
36
|
+
};
|
|
37
|
+
visit(sf);
|
|
38
|
+
return edits;
|
|
39
|
+
}
|
|
40
|
+
export function nativeInputs(code, file, entry, files = {}) {
|
|
41
|
+
const root = file.slice(0, file.length - (file.split('/').pop().length));
|
|
42
|
+
const extra = Object.fromEntries(Object.entries(files).map(([name, text]) => [normalize(`${root}${name}`), text]));
|
|
43
|
+
const { sf, checker } = program(code, file, extra);
|
|
44
|
+
let target;
|
|
45
|
+
const visit = (n) => { if (callable(n) && named(n) === entry)
|
|
46
|
+
target ??= n; ts.forEachChild(n, visit); };
|
|
47
|
+
visit(sf);
|
|
48
|
+
if (!target)
|
|
49
|
+
return { reason: 'native entry signature could not be read independently' };
|
|
50
|
+
const domain = (t, depth = 0) => {
|
|
51
|
+
if (depth > 12)
|
|
52
|
+
return undefined;
|
|
53
|
+
if (t.isUnion()) {
|
|
54
|
+
const parts = t.types.map(x => domain(x, depth + 1));
|
|
55
|
+
if (parts.some(x => x === undefined))
|
|
56
|
+
return undefined;
|
|
57
|
+
const out = parts.flat();
|
|
58
|
+
if (out.length > LIMIT)
|
|
59
|
+
throw new TooLarge();
|
|
60
|
+
return out;
|
|
61
|
+
}
|
|
62
|
+
if (t.flags & ts.TypeFlags.BooleanLiteral)
|
|
63
|
+
return [t.intrinsicName === 'true'];
|
|
64
|
+
if (t.flags & ts.TypeFlags.Boolean)
|
|
65
|
+
return [false, true];
|
|
66
|
+
if (t.isStringLiteral() || t.isNumberLiteral())
|
|
67
|
+
return [t.value];
|
|
68
|
+
if (t.flags & ts.TypeFlags.Undefined || t.flags & ts.TypeFlags.Void)
|
|
69
|
+
return [undefined];
|
|
70
|
+
if (t.flags & ts.TypeFlags.Null)
|
|
71
|
+
return [null];
|
|
72
|
+
if (t.flags & ts.TypeFlags.Never)
|
|
73
|
+
return [];
|
|
74
|
+
if (!(t.flags & ts.TypeFlags.Object) || checker.getIndexInfosOfType(t).length || t.getCallSignatures().length || t.getConstructSignatures().length)
|
|
75
|
+
return undefined;
|
|
76
|
+
let rows = [{}];
|
|
77
|
+
for (const p of t.getProperties()) {
|
|
78
|
+
const at = p.valueDeclaration ?? p.declarations?.[0];
|
|
79
|
+
if (!at)
|
|
80
|
+
return undefined;
|
|
81
|
+
const values = domain(checker.getTypeOfSymbolAtLocation(p, at), depth + 1);
|
|
82
|
+
if (!values)
|
|
83
|
+
return undefined;
|
|
84
|
+
const optional = !!(p.flags & ts.SymbolFlags.Optional), factor = values.length + Number(optional);
|
|
85
|
+
if (rows.length * factor > LIMIT)
|
|
86
|
+
throw new TooLarge();
|
|
87
|
+
rows = rows.flatMap(row => [...(optional ? [row] : []), ...values.map(value => ({ ...row, [p.name]: value }))]);
|
|
88
|
+
}
|
|
89
|
+
return rows;
|
|
90
|
+
};
|
|
91
|
+
try {
|
|
92
|
+
const domains = [];
|
|
93
|
+
let size = 1;
|
|
94
|
+
for (const p of target.parameters) {
|
|
95
|
+
if (p.dotDotDotToken)
|
|
96
|
+
return { reason: 'native rest-argument domain is not supported' };
|
|
97
|
+
const values = domain(checker.getTypeAtLocation(p));
|
|
98
|
+
if (!values)
|
|
99
|
+
return {};
|
|
100
|
+
if ((p.questionToken || p.initializer) && !values.includes(undefined))
|
|
101
|
+
values.push(undefined);
|
|
102
|
+
size *= values.length;
|
|
103
|
+
if (size > LIMIT)
|
|
104
|
+
throw new TooLarge();
|
|
105
|
+
domains.push(values);
|
|
106
|
+
}
|
|
107
|
+
return { domains };
|
|
108
|
+
}
|
|
109
|
+
catch (e) {
|
|
110
|
+
if (e instanceof TooLarge)
|
|
111
|
+
return { reason: `finite native domain exceeds the exhaustive bound of ${LIMIT}; no sampled proof is substituted` };
|
|
112
|
+
return { reason: `native input domains unavailable: ${e instanceof Error ? e.message : String(e)}` };
|
|
113
|
+
}
|
|
114
|
+
}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import type { X, LawOpts } from './laws.js';
|
|
2
|
+
import { type NativeObservation } from './source-check.js';
|
|
3
|
+
export declare function nativeLaw(expression: X, opts: LawOpts, parse: (text: string) => X, constants?: Record<string, number | string | boolean>, knownNames?: ReadonlySet<string>): (observation: NativeObservation) => boolean;
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
import { nativeSame } from "./source-check.js";
|
|
2
|
+
const NONE = Symbol('language None');
|
|
3
|
+
const truthy = (value) => value !== NONE && Boolean(value);
|
|
4
|
+
const object = (x) => x !== null && (typeof x === 'object' || typeof x === 'function');
|
|
5
|
+
const tag = (x, name) => Object.prototype.toString.call(x) === `[object ${name}]`;
|
|
6
|
+
const unsupported = (what) => { throw new Error(`native law cannot interpret ${what}`); };
|
|
7
|
+
const number = (x) => x; // Type assertion only: JS, including NaN/coercion, does the operation.
|
|
8
|
+
const equal = (a, b) => a === NONE ? b === null || b === undefined || b === NONE : b === NONE ? a === null || a === undefined : nativeSame(a, b);
|
|
9
|
+
const keys = (x) => tag(x, 'Map') || tag(x, 'Set') ? [...x.keys()] : Array.isArray(x) ? x : object(x) ? Object.keys(x) : unsupported('quantification over a non-container');
|
|
10
|
+
const has = (container, key) => tag(container, 'Map') || tag(container, 'Set') ? container.has(key) : Array.isArray(container) ? container.some(value => nativeSame(value, key)) : object(container) ? Object.hasOwn(container, String(key)) : unsupported('membership in a non-container');
|
|
11
|
+
const get = (container, key) => tag(container, 'Map') ? container.get(key) : object(container) || typeof container === 'string' ? container[String(key)] : undefined;
|
|
12
|
+
function businessDays(a, b, opts) {
|
|
13
|
+
if (typeof a !== 'number' || typeof b !== 'number' || !Number.isFinite(a) || !Number.isFinite(b))
|
|
14
|
+
return NaN;
|
|
15
|
+
if (!opts.calendar || !opts.clock)
|
|
16
|
+
return unsupported('business days without a calendar and clock');
|
|
17
|
+
const cal = opts.calendar, match = /^([+-])(\d{2}):(\d{2})$/.exec((cal.utc_offset ?? '+00:00').trim());
|
|
18
|
+
if (!match)
|
|
19
|
+
return unsupported('calendar offset');
|
|
20
|
+
const unit = 86400 * opts.clock, offset = (match[1] === '-' ? -1 : 1) * (Number(match[2]) * 3600 + Number(match[3]) * 60) * opts.clock;
|
|
21
|
+
const start = Math.floor((a + offset) / unit), end = Math.floor((b + offset) / unit);
|
|
22
|
+
const weekend = new Set((cal.weekend ?? ['sat', 'sun']).map(s => s.trim().slice(0, 3).toLowerCase())), names = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];
|
|
23
|
+
const work = (d) => !weekend.has(names[((d + 4) % 7 + 7) % 7]);
|
|
24
|
+
const lo = Math.min(start, end), hi = Math.max(start, end), weeks = Math.floor((hi - lo) / 7);
|
|
25
|
+
let count = weeks * (7 - weekend.size);
|
|
26
|
+
for (let d = lo + weeks * 7 + 1; d <= hi; d++)
|
|
27
|
+
if (work(d))
|
|
28
|
+
count++;
|
|
29
|
+
for (const date of new Set(cal.holidays ?? [])) {
|
|
30
|
+
const d = Date.parse(`${date.trim()}T00:00:00Z`) / 86400000;
|
|
31
|
+
if (d > lo && d <= hi && work(d))
|
|
32
|
+
count--;
|
|
33
|
+
}
|
|
34
|
+
return end >= start ? count : -count;
|
|
35
|
+
}
|
|
36
|
+
export function nativeLaw(expression, opts, parse, constants = {}, knownNames = new Set()) {
|
|
37
|
+
return observation => {
|
|
38
|
+
const locals = new Map();
|
|
39
|
+
const evaluate = (e, old = false) => {
|
|
40
|
+
switch (e.k) {
|
|
41
|
+
case 'num':
|
|
42
|
+
case 'bool': return e.v;
|
|
43
|
+
case 'str': return e.holes ? e.parts.reduce((s, part, i) => s + part + (i < e.holes.length ? String(evaluate(e.holes[i], old)) : ''), '') : e.v;
|
|
44
|
+
case 'null': return e.absence === 'undefined' ? undefined : e.absence === 'null' ? null : NONE;
|
|
45
|
+
case 'dur': return e.v * (opts.clock ?? unsupported('a duration without a clock'));
|
|
46
|
+
case 'bdur': return unsupported('business days outside an elapsed-time comparison');
|
|
47
|
+
case 'old': return evaluate(e.x, true);
|
|
48
|
+
case 'un': return e.op === 'not' ? !truthy(evaluate(e.x, old)) : -number(evaluate(e.x, old));
|
|
49
|
+
case 'forall': {
|
|
50
|
+
const domain = evaluate(e.over, old), previous = locals.get(e.v), existed = locals.has(e.v);
|
|
51
|
+
try {
|
|
52
|
+
return keys(domain).every(k => { locals.set(e.v, k); return truthy(evaluate(e.body, old)); });
|
|
53
|
+
}
|
|
54
|
+
finally {
|
|
55
|
+
if (existed)
|
|
56
|
+
locals.set(e.v, previous);
|
|
57
|
+
else
|
|
58
|
+
locals.delete(e.v);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
case 'fn': {
|
|
62
|
+
const xs = e.xs.map(x => evaluate(x, old));
|
|
63
|
+
if (e.f === 'abs')
|
|
64
|
+
return Math.abs(number(xs[0]));
|
|
65
|
+
if (e.f === 'min')
|
|
66
|
+
return Math.min(...xs.map(number));
|
|
67
|
+
if (e.f === 'max')
|
|
68
|
+
return Math.max(...xs.map(number));
|
|
69
|
+
if (e.f === 'sum') {
|
|
70
|
+
if (xs.length !== 1)
|
|
71
|
+
return unsupported('sum with several arguments');
|
|
72
|
+
const values = tag(xs[0], 'Map') ? [...xs[0].values()] : Array.isArray(xs[0]) ? xs[0] : object(xs[0]) ? Object.values(xs[0]) : unsupported('sum over a non-container');
|
|
73
|
+
return values.reduce((sum, value) => sum + number(value), 0);
|
|
74
|
+
}
|
|
75
|
+
return unsupported(`function ${e.f}`);
|
|
76
|
+
}
|
|
77
|
+
case 'path': {
|
|
78
|
+
const state = old ? observation.before : observation.after;
|
|
79
|
+
let value;
|
|
80
|
+
if (['this', 'self'].includes(e.head))
|
|
81
|
+
value = state;
|
|
82
|
+
else if (e.head === 'before')
|
|
83
|
+
value = observation.before;
|
|
84
|
+
else if (e.head.startsWith('@') && object(state))
|
|
85
|
+
value = state[e.head.slice(1)];
|
|
86
|
+
else if (locals.has(e.head))
|
|
87
|
+
value = locals.get(e.head);
|
|
88
|
+
else if (Object.hasOwn(observation.bindings, e.head))
|
|
89
|
+
value = observation.bindings[e.head];
|
|
90
|
+
else if (e.head === 'result') {
|
|
91
|
+
if (old)
|
|
92
|
+
return unsupported('old(result), which is not native source state');
|
|
93
|
+
value = !e.segs.length && observation.legacyResult ? get(observation.result, 'value') : observation.result;
|
|
94
|
+
}
|
|
95
|
+
else if (e.head === 'failed')
|
|
96
|
+
value = observation.legacyResult ? get(observation.result, 'failed') : observation.failed;
|
|
97
|
+
else if (e.head === 'method')
|
|
98
|
+
value = observation.method;
|
|
99
|
+
else if (object(state) && e.head in state)
|
|
100
|
+
value = state[e.head];
|
|
101
|
+
else if (Object.hasOwn(observation.params, e.head))
|
|
102
|
+
value = observation.params[e.head];
|
|
103
|
+
else if (Object.hasOwn(observation.inputs, e.head))
|
|
104
|
+
value = observation.inputs[e.head];
|
|
105
|
+
else if (e.head === observation.method && 'call' in (e.segs[0] ?? {}))
|
|
106
|
+
value = observation.result;
|
|
107
|
+
else if (Object.hasOwn(constants, e.head))
|
|
108
|
+
value = constants[e.head];
|
|
109
|
+
else if (knownNames.has(e.head))
|
|
110
|
+
return unsupported(`native value of ${e.head} is unavailable`);
|
|
111
|
+
else if (!e.segs.length)
|
|
112
|
+
value = e.head; // A bare enum label; buildLaw already checked its domain.
|
|
113
|
+
else
|
|
114
|
+
return unsupported(`name ${e.head}`);
|
|
115
|
+
for (let i = 0; i < e.segs.length; i++) {
|
|
116
|
+
const s = e.segs[i];
|
|
117
|
+
if ('f' in s) {
|
|
118
|
+
const next = e.segs[i + 1];
|
|
119
|
+
if (next && 'call' in next && ((tag(value, 'Map') && ['get', 'has'].includes(s.f)) || (tag(value, 'Set') && s.f === 'has'))) {
|
|
120
|
+
const key = next.args ? evaluate(parse(next.args), old) : undefined;
|
|
121
|
+
value = s.f === 'get' ? get(value, key) : has(value, key);
|
|
122
|
+
i++;
|
|
123
|
+
}
|
|
124
|
+
else if (s.f === 'size' && (tag(value, 'Map') || tag(value, 'Set')))
|
|
125
|
+
value = value.size;
|
|
126
|
+
else
|
|
127
|
+
value = get(value, s.f);
|
|
128
|
+
}
|
|
129
|
+
else if ('i' in s)
|
|
130
|
+
value = get(value, evaluate(s.i, old));
|
|
131
|
+
else if (i === 0 && e.head === observation.method) {
|
|
132
|
+
const expected = s.args ? s.args.split(',').map(a => evaluate(parse(a), old)) : [];
|
|
133
|
+
if (expected.length && (expected.length !== observation.args.length || expected.some((v, k) => !equal(v, observation.args[k]))))
|
|
134
|
+
return unsupported('a method call with different arguments');
|
|
135
|
+
}
|
|
136
|
+
else
|
|
137
|
+
return unsupported('an unobserved method call');
|
|
138
|
+
}
|
|
139
|
+
return value;
|
|
140
|
+
}
|
|
141
|
+
case 'bin': {
|
|
142
|
+
if (e.op === '&&')
|
|
143
|
+
return truthy(evaluate(e.a, old)) && truthy(evaluate(e.b, old));
|
|
144
|
+
if (e.op === '||')
|
|
145
|
+
return truthy(evaluate(e.a, old)) || truthy(evaluate(e.b, old));
|
|
146
|
+
if (e.op === '=>')
|
|
147
|
+
return !truthy(evaluate(e.a, old)) || truthy(evaluate(e.b, old));
|
|
148
|
+
const calendarOperand = (x) => x.k === 'bdur' ? x.v : x.k === 'bin' && x.op === '-' ? businessDays(evaluate(x.b, old), evaluate(x.a, old), opts) : unsupported('business-day operand');
|
|
149
|
+
const calendar = e.a.k === 'bdur' || e.b.k === 'bdur';
|
|
150
|
+
const a = calendar ? calendarOperand(e.a) : evaluate(e.a, old), b = calendar ? calendarOperand(e.b) : evaluate(e.b, old);
|
|
151
|
+
switch (e.op) {
|
|
152
|
+
case '==': return equal(a, b);
|
|
153
|
+
case '!=': return !equal(a, b);
|
|
154
|
+
case '<': return number(a) < number(b);
|
|
155
|
+
case '<=': return number(a) <= number(b);
|
|
156
|
+
case '>': return number(a) > number(b);
|
|
157
|
+
case '>=': return number(a) >= number(b);
|
|
158
|
+
case '+': return number(a) + number(b);
|
|
159
|
+
case '-': return number(a) - number(b);
|
|
160
|
+
case '*': return number(a) * number(b);
|
|
161
|
+
case '/': return number(a) / number(b);
|
|
162
|
+
case '//': return Math.floor(number(a) / number(b));
|
|
163
|
+
case '%': return number(a) % number(b);
|
|
164
|
+
case '&': return number(a) & number(b);
|
|
165
|
+
case '|': return number(a) | number(b);
|
|
166
|
+
case 'in': return has(b, a);
|
|
167
|
+
default: return unsupported(`operator ${e.op}`);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
};
|
|
172
|
+
return truthy(evaluate(expression));
|
|
173
|
+
};
|
|
174
|
+
}
|