pud.dev 0.0.0-stage → 0.0.1
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/CLAUDE.md +106 -0
- package/README.md +117 -2
- package/package.json +24 -4
- package/scripts/pack.ts +67 -0
- package/scripts/setup-lean.ts +88 -0
- package/src/assistant.ts +131 -0
- package/src/check.ts +173 -0
- package/src/cli.ts +70 -0
- package/src/expressions.ts +65 -0
- package/src/index.ts +4 -0
- package/src/input-scope.ts +71 -0
- package/src/lean/command.ts +40 -0
- package/src/lean/index.ts +437 -0
- package/src/lean/iteration.lean +145 -0
- package/src/lean/lean-assets.d.ts +4 -0
- package/src/lean/number.lean +427 -0
- package/src/lean/number.ts +25 -0
- package/src/lean/program.ts +110 -0
- package/src/lean/replay-predicate.ts +95 -0
- package/src/lean/replay.ts +136 -0
- package/src/lean/scalar.lean +183 -0
- package/src/lean/scalar.ts +196 -0
- package/src/lean/subject.ts +443 -0
- package/src/lean/syntax.ts +287 -0
- package/src/module.ts +110 -0
- package/src/project-runner.ts +26 -0
- package/src/prover-process.ts +16 -0
- package/src/reporter.ts +173 -0
- package/src/run.ts +60 -0
- package/src/source.ts +54 -0
- package/src/suite-authoring.ts +135 -0
- package/src/suite-check.ts +157 -0
- package/src/suite.ts +515 -0
- package/src/terminal-progress.ts +145 -0
- package/src/terminal.ts +41 -0
- package/test/authoring.test.ts +151 -0
- package/test/lean.test.ts +394 -0
- package/test/module.test.ts +55 -0
- package/test/number.test.ts +318 -0
- package/test/package.test.ts +170 -0
- package/test/suite.test.ts +257 -0
- package/tsconfig.json +7 -0
- package/tsconfig.pack.json +12 -0
package/src/check.ts
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
import { readFileSync, realpathSync } from "node:fs";
|
|
2
|
+
import { resolve } from "node:path";
|
|
3
|
+
import { failure, type Counterexample, type ProofAssistant, type ProofOutcome } from "./assistant.ts";
|
|
4
|
+
import type { ConcreteScope } from "./input-scope.ts";
|
|
5
|
+
import { parseSourceModule } from "./source.ts";
|
|
6
|
+
import { checkSuite, emitSuite, findConfig } from "./suite-check.ts";
|
|
7
|
+
import { readSuite, type Suite } from "./suite.ts";
|
|
8
|
+
|
|
9
|
+
export interface CheckResult {
|
|
10
|
+
status: ProofOutcome["status"] | "todo";
|
|
11
|
+
name?: string;
|
|
12
|
+
subject?: string;
|
|
13
|
+
line?: number;
|
|
14
|
+
detail?: string;
|
|
15
|
+
diagnostic?: string;
|
|
16
|
+
counterexample?: Counterexample;
|
|
17
|
+
concreteScope?: ConcreteScope;
|
|
18
|
+
exactResult?: true;
|
|
19
|
+
assistant?: string;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface CheckReport { file: string; results: CheckResult[] }
|
|
23
|
+
|
|
24
|
+
type ItemEvent =
|
|
25
|
+
| { kind: "running"; indices: readonly number[]; statuses?: never }
|
|
26
|
+
| { kind: "finished"; indices: readonly number[]; statuses: readonly CheckResult["status"][] };
|
|
27
|
+
|
|
28
|
+
/** Each active index finishes once. Its status is provisional until the final report. */
|
|
29
|
+
export type CheckProgress =
|
|
30
|
+
| { kind: "suite"; file: string; index: number; total: number; totalItems: number; items: readonly { name: string; todo?: boolean }[] }
|
|
31
|
+
| (ItemEvent & { file: string })
|
|
32
|
+
| { kind: "validating" };
|
|
33
|
+
|
|
34
|
+
export type ItemProgress = (event: ItemEvent) => void;
|
|
35
|
+
|
|
36
|
+
export interface CheckOptions {
|
|
37
|
+
adapter?: ProofAssistant;
|
|
38
|
+
onProgress?: (event: CheckProgress) => void;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export interface EmitOptions extends Pick<CheckOptions, "adapter"> {
|
|
42
|
+
property?: string;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
type Snapshot = { canonical: string; source: string } | { error: unknown };
|
|
46
|
+
|
|
47
|
+
class SourceSnapshots {
|
|
48
|
+
private inputs = new Map<string, Snapshot>();
|
|
49
|
+
private contents = new Map<string, string>();
|
|
50
|
+
|
|
51
|
+
read(file: string): Snapshot {
|
|
52
|
+
const path = resolve(file);
|
|
53
|
+
const existing = this.inputs.get(path);
|
|
54
|
+
if (existing) return existing;
|
|
55
|
+
let snapshot: Snapshot;
|
|
56
|
+
try {
|
|
57
|
+
const canonical = realpathSync(path);
|
|
58
|
+
let source = this.contents.get(canonical);
|
|
59
|
+
if (source === undefined) {
|
|
60
|
+
source = readFileSync(canonical, "utf8");
|
|
61
|
+
this.contents.set(canonical, source);
|
|
62
|
+
}
|
|
63
|
+
snapshot = { canonical, source };
|
|
64
|
+
} catch (error) { snapshot = { error }; }
|
|
65
|
+
this.inputs.set(path, snapshot);
|
|
66
|
+
return snapshot;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
changes(): Map<string, Error> {
|
|
70
|
+
const current = new SourceSnapshots(), changed = new Map<string, Error>();
|
|
71
|
+
for (const [path, before] of this.inputs) {
|
|
72
|
+
const after = current.read(path);
|
|
73
|
+
if (("error" in before) !== ("error" in after) ||
|
|
74
|
+
("source" in before && "source" in after && (before.canonical !== after.canonical || before.source !== after.source))) {
|
|
75
|
+
changed.set(path, new Error(`${path} changed during verification. Rerun pud check.`));
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
return changed;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function snapshotReader(snapshots: SourceSnapshots, dependencies?: Set<string>) {
|
|
83
|
+
return (file: string) => {
|
|
84
|
+
const path = resolve(file);
|
|
85
|
+
dependencies?.add(path);
|
|
86
|
+
const input = snapshots.read(path);
|
|
87
|
+
if ("error" in input) throw input.error;
|
|
88
|
+
return input;
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function remappedImports(imports: Suite["imports"]) {
|
|
93
|
+
const changed = new Map<string, Error>();
|
|
94
|
+
for (const { path, resolveAgain } of imports) {
|
|
95
|
+
try { if (resolveAgain() === path) continue; } catch { /* the import may now be missing or unsupported */ }
|
|
96
|
+
changed.set(path, new Error(`The import of ${path} changed during verification. Rerun pud check.`));
|
|
97
|
+
}
|
|
98
|
+
return changed;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function parseSuite(file: string, read: ReturnType<typeof snapshotReader>) {
|
|
102
|
+
if (!file.endsWith(".proof.ts")) throw new Error(`Expected a *.proof.ts file: ${file}`);
|
|
103
|
+
const { canonical: origin, source } = read(file);
|
|
104
|
+
const config = findConfig(origin);
|
|
105
|
+
const suite = readSuite(file, origin, source, parseSourceModule(file, source), config);
|
|
106
|
+
return { suite, config, origin };
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
type Plan = { file: string; error: CheckResult }
|
|
110
|
+
| { file: string; origin: string; suite: Suite; config?: string; dependencies: Set<string>; results: CheckResult[] };
|
|
111
|
+
|
|
112
|
+
/** Check a batch against shared snapshots of the sidecars and their proof inputs. */
|
|
113
|
+
export async function checkFiles(files: readonly string[], options: CheckOptions = {}): Promise<CheckReport[]> {
|
|
114
|
+
const snapshots = new SourceSnapshots();
|
|
115
|
+
const read = snapshotReader(snapshots);
|
|
116
|
+
const plans = files.map((file): Plan => {
|
|
117
|
+
try {
|
|
118
|
+
const plan = parseSuite(file, read);
|
|
119
|
+
if (plan.suite.properties.some(property => property.kind === "claim")) {
|
|
120
|
+
// Freeze direct inputs before any adapter starts. Track the files it actually uses below.
|
|
121
|
+
snapshots.read(plan.suite.subject.file);
|
|
122
|
+
if (plan.config && !options.adapter) snapshots.read(plan.config);
|
|
123
|
+
for (const module of plan.suite.modules) snapshots.read(module.file);
|
|
124
|
+
}
|
|
125
|
+
return { file, ...plan, dependencies: new Set(), results: [] };
|
|
126
|
+
} catch (error) {
|
|
127
|
+
return { file, error: failure(error) };
|
|
128
|
+
}
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
const progress = options.onProgress;
|
|
132
|
+
const totalItems = progress ? plans.reduce((count, plan) => count + ("error" in plan
|
|
133
|
+
? 0 : plan.suite.properties.filter(property => property.kind === "claim").length), 0) : 0;
|
|
134
|
+
for (const [index, plan] of plans.entries()) {
|
|
135
|
+
if (progress) {
|
|
136
|
+
const items = "error" in plan ? [] : plan.suite.properties.map(property => ({ name: property.name, todo: property.kind === "todo" }));
|
|
137
|
+
progress({ kind: "suite", file: plan.file, index, total: plans.length, totalItems, items });
|
|
138
|
+
}
|
|
139
|
+
if ("error" in plan) continue;
|
|
140
|
+
const report: ItemProgress | undefined = progress && (event => progress({ ...event, file: plan.file }));
|
|
141
|
+
plan.results = await checkSuite(plan.suite, plan.config, options, snapshotReader(snapshots, plan.dependencies), report);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
if (plans.length && progress) await progress({ kind: "validating" });
|
|
145
|
+
const changed = snapshots.changes();
|
|
146
|
+
return plans.map(plan => {
|
|
147
|
+
const { file } = plan;
|
|
148
|
+
const sidecarChange = changed.get(resolve(file));
|
|
149
|
+
if ("error" in plan) return { file, results: [sidecarChange ? failure(sidecarChange) : plan.error] };
|
|
150
|
+
const dependencyChange = [...plan.dependencies].map(path => changed.get(path)).find(Boolean);
|
|
151
|
+
const hasActive = plan.results.some(result => result.status !== "todo");
|
|
152
|
+
const configChange = hasActive && !options.adapter && findConfig(plan.origin) !== plan.config
|
|
153
|
+
? new Error(`The project configuration for ${file} changed during verification. Rerun pud check.`) : undefined;
|
|
154
|
+
const remapped = hasActive ? remappedImports(plan.suite.imports).values().next().value : undefined;
|
|
155
|
+
const change = configChange ?? remapped ?? dependencyChange;
|
|
156
|
+
return { file, results: plan.results.map(result => {
|
|
157
|
+
const error = sidecarChange ?? (result.status !== "todo" ? change : undefined);
|
|
158
|
+
const { name, line, subject, assistant } = result;
|
|
159
|
+
return error ? { ...failure(error), name, line, subject, assistant } : result;
|
|
160
|
+
}) };
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
export async function emit(file: string, options: EmitOptions): Promise<string> {
|
|
165
|
+
const snapshots = new SourceSnapshots();
|
|
166
|
+
const read = snapshotReader(snapshots);
|
|
167
|
+
const { suite, config, origin } = parseSuite(file, read);
|
|
168
|
+
const unit = await emitSuite(suite, config, options, read);
|
|
169
|
+
const changed = snapshots.changes().values().next().value ?? remappedImports(suite.imports).values().next().value;
|
|
170
|
+
if (changed) throw changed;
|
|
171
|
+
if (!options.adapter && findConfig(origin) !== config) throw new Error(`The project configuration for ${file} changed during emission.`);
|
|
172
|
+
return unit;
|
|
173
|
+
}
|
package/src/cli.ts
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
import { readdirSync, statSync } from "node:fs";
|
|
3
|
+
import { join, resolve } from "node:path";
|
|
4
|
+
import { failure } from "./assistant.ts";
|
|
5
|
+
import { checkFiles, emit } from "./run.ts";
|
|
6
|
+
import { display, proofReporter } from "./reporter.ts";
|
|
7
|
+
|
|
8
|
+
const synopsis = `Usage: pud [check] [DIR | FILE.proof.ts ...] [--verbose | --json] [--deny-cases]
|
|
9
|
+
pud --emit FILE.proof.ts [PROPERTY | SUBJECT[.PROPERTY]]`;
|
|
10
|
+
const usage = `${synopsis}
|
|
11
|
+
|
|
12
|
+
With no paths, Pud discovers *.proof.ts under the current directory.
|
|
13
|
+
The nearest pud.config.ts selects the proof assistant.
|
|
14
|
+
--emit Print the verification unit for one property without running the prover or replay.
|
|
15
|
+
--verbose Show full diagnostics and affected properties.
|
|
16
|
+
--json Print machine-readable results.
|
|
17
|
+
--deny-cases Fail on zero-input claims or explicit literal constraints on every input. Quantified postconditions are allowed.
|
|
18
|
+
Exit: 0 all active properties proved, 1 unproved or disproved, 2 unsupported, invalid input or tool error.`;
|
|
19
|
+
|
|
20
|
+
const skipped = new Set(["node_modules", "dist", "out", "build", "coverage"]);
|
|
21
|
+
function discover(dir: string): string[] {
|
|
22
|
+
return readdirSync(dir, { withFileTypes: true }).flatMap(entry => {
|
|
23
|
+
if (entry.name.startsWith(".") || skipped.has(entry.name)) return [];
|
|
24
|
+
const path = join(dir, entry.name);
|
|
25
|
+
if (entry.isDirectory()) return discover(path);
|
|
26
|
+
return (entry.isFile() || entry.isSymbolicLink()) && entry.name.endsWith(".proof.ts") ? [path] : [];
|
|
27
|
+
}).sort();
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
async function main(args: string[]): Promise<number> {
|
|
31
|
+
if (args[0] === "check") args = args.slice(1);
|
|
32
|
+
if (args.length === 1 && ["--help", "-h"].includes(args[0]!)) { console.log(usage); return 0; }
|
|
33
|
+
if (args[0] === "--emit" && args.length >= 2 && args.length <= 3 && !args.includes("--json")) {
|
|
34
|
+
try { process.stdout.write(await emit(args[1]!, args[2])); return 0; }
|
|
35
|
+
catch (error) {
|
|
36
|
+
display(args[1]!, failure(error), false, process.stderr);
|
|
37
|
+
return 2;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
const started = performance.now();
|
|
41
|
+
const verbose = args.includes("--verbose"), json = args.includes("--json");
|
|
42
|
+
const denyCases = args.includes("--deny-cases");
|
|
43
|
+
const paths = args.filter(a => a !== "--verbose" && a !== "--json" && a !== "--deny-cases");
|
|
44
|
+
const files = new Map<string, string>(), errors: string[] = [];
|
|
45
|
+
if (paths.some(path => path.startsWith("-")) || (json && verbose)) errors.push(synopsis);
|
|
46
|
+
else for (const path of paths.length ? paths : ["."]) {
|
|
47
|
+
try {
|
|
48
|
+
if (statSync(path, { throwIfNoEntry: false })?.isDirectory()) {
|
|
49
|
+
const matches = discover(path);
|
|
50
|
+
if (!matches.length) errors.push(`No *.proof.ts files found in ${path}. Add a proof file beside the function you want to check.`);
|
|
51
|
+
for (const file of matches) files.set(resolve(file), file);
|
|
52
|
+
} else if (path.endsWith(".proof.ts")) files.set(resolve(path), path);
|
|
53
|
+
else errors.push(`Expected a directory or a *.proof.ts file. Received ${path}.`);
|
|
54
|
+
} catch (e) { errors.push((e as Error).message); }
|
|
55
|
+
}
|
|
56
|
+
const selected = [...files.values()];
|
|
57
|
+
const reporter = json ? undefined : proofReporter(selected, started, verbose);
|
|
58
|
+
const reports = await checkFiles(selected, { onProgress: reporter?.update }).finally(reporter?.close);
|
|
59
|
+
if (denyCases) for (const report of reports) for (const result of report.results) {
|
|
60
|
+
if (result.concreteScope) errors.push(`${report.file}:${result.line}: "${result.name}" has ${result.concreteScope === "no-inputs" ? "no inputs" : "a literal constraint on every input"}. State a law over a domain or move the case to a runtime test.`);
|
|
61
|
+
}
|
|
62
|
+
const counts = { proved: 0, disproved: 0, unproved: 0, unsupported: 0, error: errors.length, todo: 0 };
|
|
63
|
+
for (const report of reports) for (const r of report.results) counts[r.status]++;
|
|
64
|
+
const code = counts.error || counts.unsupported ? 2 : counts.disproved || counts.unproved ? 1 : 0;
|
|
65
|
+
if (json) console.log(JSON.stringify({ files: reports, counts, ...(errors.length ? { errors } : {}) }, null, 2));
|
|
66
|
+
else reporter?.report(reports, counts, errors, code ? process.stderr : process.stdout);
|
|
67
|
+
return code;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
if (import.meta.main) process.exitCode = await main(process.argv.slice(2));
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import type { Node } from "@babel/types";
|
|
2
|
+
import { Unsupported } from "./assistant.ts";
|
|
3
|
+
import { invalid } from "./source.ts";
|
|
4
|
+
|
|
5
|
+
/** Typed expressions shared by TypeScript frontends. */
|
|
6
|
+
export type Sort = "integer" | "boolean" | "string";
|
|
7
|
+
export type BinaryOp = "+" | "-" | "*" | "<" | "<=" | ">" | ">=" | "===" | "!==" | "&&" | "||";
|
|
8
|
+
export type Expr =
|
|
9
|
+
| { kind: "integer"; sort: "integer"; value: string }
|
|
10
|
+
| { kind: "boolean"; sort: "boolean"; value: boolean }
|
|
11
|
+
| { kind: "string"; sort: "string"; value: string }
|
|
12
|
+
| { kind: "reference"; sort: Sort; path: string[] }
|
|
13
|
+
| { kind: "unary"; sort: Sort; op: "!" | "-"; arg: Expr }
|
|
14
|
+
| { kind: "binary"; sort: Sort; op: BinaryOp; left: Expr; right: Expr }
|
|
15
|
+
| { kind: "choose"; sort: Sort; test: Expr; yes: Expr; no: Expr };
|
|
16
|
+
|
|
17
|
+
export const integer = (value: bigint): Expr => ({ kind: "integer", sort: "integer", value: value.toString() });
|
|
18
|
+
export const bool = (value: boolean): Expr => ({ kind: "boolean", sort: "boolean", value });
|
|
19
|
+
export const string = (value: string): Expr => ({ kind: "string", sort: "string", value });
|
|
20
|
+
export const ref = (sort: Sort, ...path: string[]): Expr => ({ kind: "reference", sort, path });
|
|
21
|
+
|
|
22
|
+
export function unary(op: "!" | "-", arg: Expr): Expr {
|
|
23
|
+
const sort = op === "!" ? "boolean" : "integer";
|
|
24
|
+
if (arg.sort !== sort) throw new Error(`${op} expects ${sort === "integer" ? "bigint" : sort} operands.`);
|
|
25
|
+
return { kind: "unary", sort, op, arg };
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function binary(op: BinaryOp, left: Expr, right: Expr): Expr {
|
|
29
|
+
const input = op === "===" || op === "!==" ? left.sort : op === "&&" || op === "||" ? "boolean" : "integer";
|
|
30
|
+
if (left.sort !== input || right.sort !== input) throw new Error(`${op} expects ${input === "integer" ? "bigint" : input} operands.`);
|
|
31
|
+
const sort = op === "+" || op === "-" || op === "*" ? "integer" : "boolean";
|
|
32
|
+
return { kind: "binary", sort, op, left, right };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function choose(test: Expr, yes: Expr, no: Expr): Expr {
|
|
36
|
+
if (test.sort !== "boolean" || yes.sort !== no.sort) throw new Error("A conditional needs a boolean test and two branches of the same type.");
|
|
37
|
+
return { kind: "choose", sort: yes.sort, test, yes, no };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const operators = new Set<string>(["+", "-", "*", "<", "<=", ">", ">=", "===", "!==", "&&", "||"]);
|
|
41
|
+
|
|
42
|
+
/** The caller supplies the meanings of names and domain-specific observations. */
|
|
43
|
+
export function readExpression(file: string, node: Node, resolve: (node: Node) => Expr | undefined): Expr {
|
|
44
|
+
const read = (n: Node) => readExpression(file, n, resolve);
|
|
45
|
+
const existing = resolve(node);
|
|
46
|
+
if (existing) return existing;
|
|
47
|
+
try {
|
|
48
|
+
switch (node.type) {
|
|
49
|
+
case "BooleanLiteral": return bool(node.value);
|
|
50
|
+
case "BigIntLiteral": return integer(BigInt(node.value));
|
|
51
|
+
case "UnaryExpression":
|
|
52
|
+
if (node.operator === "-" || node.operator === "!") return unary(node.operator, read(node.argument));
|
|
53
|
+
break;
|
|
54
|
+
case "BinaryExpression":
|
|
55
|
+
case "LogicalExpression":
|
|
56
|
+
if (operators.has(node.operator)) return binary(node.operator as BinaryOp, read(node.left), read(node.right));
|
|
57
|
+
break;
|
|
58
|
+
case "ConditionalExpression": return choose(read(node.test), read(node.consequent), read(node.alternate));
|
|
59
|
+
}
|
|
60
|
+
} catch (error) {
|
|
61
|
+
if (error instanceof Unsupported) throw error;
|
|
62
|
+
return invalid(file, node, (error as Error).message);
|
|
63
|
+
}
|
|
64
|
+
return invalid(file, node, `Unsupported TypeScript: ${node.type}${"operator" in node ? ` (${node.operator})` : ""}.`);
|
|
65
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { check, checkFiles, emit } from "./run.ts";
|
|
2
|
+
export type { CheckOptions, CheckProgress, CheckReport, CheckResult, EmitOptions } from "./check.ts";
|
|
3
|
+
export { defineConfig, describe, expect, given, it, native, pud, type PudConfig, type NativeModule, type NativeSyntax, type NativeTerm, type Proposition, type Schema } from "./suite-authoring.ts";
|
|
4
|
+
export { Unsupported, type ClaimProgress, type Counterexample, type NativeProofTerm, type PreparedProofAssistant, type ProofAssistant, type ProofCall, type ProofClaim, type ProofComparison, type ProofConstraint, type ProofErrorKind, type ProofExpression, type ProofModule, type ProofOutcome, type ProofPredicate, type ProofTarget, type ProofType, type SubjectSource } from "./assistant.ts";
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { parseExpression } from "@babel/parser";
|
|
2
|
+
import type { Node } from "@babel/types";
|
|
3
|
+
import type { PreparedProofAssistant, ProofClaim, ProofExpression, ProofPredicate } from "./assistant.ts";
|
|
4
|
+
|
|
5
|
+
export type ConcreteScope = "literal-inputs" | "no-inputs";
|
|
6
|
+
|
|
7
|
+
const forward = { "===": "eq", "<=": "lte", ">=": "gte" } as const;
|
|
8
|
+
const reversed = { "===": "eq", "<=": "gte", ">=": "lte" } as const;
|
|
9
|
+
|
|
10
|
+
function literal(node: Node): string | undefined {
|
|
11
|
+
if (node.type === "BooleanLiteral") return String(node.value);
|
|
12
|
+
const negative = node.type === "UnaryExpression" && node.operator === "-";
|
|
13
|
+
const value = negative ? node.argument : node;
|
|
14
|
+
if (value.type === "NumericLiteral") return String(negative ? -value.value : value.value);
|
|
15
|
+
if (value.type === "BigIntLiteral") return String(negative ? -BigInt(value.value) : BigInt(value.value)) + "n";
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function quantified(spec: ProofPredicate): boolean {
|
|
19
|
+
if (spec.kind === "quantifier") return true;
|
|
20
|
+
if (spec.kind === "not") return quantified(spec.operand);
|
|
21
|
+
return spec.kind === "binary" && (quantified(spec.left) || quantified(spec.right));
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Recognize explicit literal constraints. An unclassified domain can still be empty or have one member. */
|
|
25
|
+
export function concreteScope(parameters: PreparedProofAssistant["parameters"], claim: ProofClaim): ConcreteScope | undefined {
|
|
26
|
+
if (claim.assertions.some(a => (a.kind === "refinement" || a.kind === "proposition") && quantified(a.predicate))) return;
|
|
27
|
+
if (!parameters.length) return "no-inputs";
|
|
28
|
+
const fixed = new Set<string>();
|
|
29
|
+
const bounds = new Map<string, { lower: Set<string>; upper: Set<string> }>();
|
|
30
|
+
function constrain(name: string, operator: "eq" | "gte" | "lte", node: Node) {
|
|
31
|
+
const value = literal(node);
|
|
32
|
+
if (value === undefined) return;
|
|
33
|
+
if (operator === "eq") { fixed.add(name); return; }
|
|
34
|
+
const range = bounds.get(name) ?? { lower: new Set<string>(), upper: new Set<string>() };
|
|
35
|
+
bounds.set(name, range);
|
|
36
|
+
range[operator === "gte" ? "lower" : "upper"].add(value);
|
|
37
|
+
if (range.lower.has(value) && range.upper.has(value)) fixed.add(name);
|
|
38
|
+
}
|
|
39
|
+
function equalities(expression: ProofExpression, local?: readonly [string, string]) {
|
|
40
|
+
const visit = (node: Node) => {
|
|
41
|
+
if (node.type === "LogicalExpression" && node.operator === "&&") { visit(node.left); visit(node.right); }
|
|
42
|
+
if (node.type !== "BinaryExpression") return;
|
|
43
|
+
const { left, right, operator } = node;
|
|
44
|
+
if (operator !== "===" && operator !== "<=" && operator !== ">=") return;
|
|
45
|
+
const variable = left.type === "Identifier" ? left : right.type === "Identifier" ? right : undefined;
|
|
46
|
+
if (!variable) return;
|
|
47
|
+
const name = local?.[0] === variable.name ? local[1] : expression.bindings.get(variable.name);
|
|
48
|
+
if (!name) return;
|
|
49
|
+
if (variable === left) constrain(name, forward[operator], right);
|
|
50
|
+
else constrain(name, reversed[operator], left);
|
|
51
|
+
};
|
|
52
|
+
visit(parseExpression(expression.source, { plugins: ["typescript"] }));
|
|
53
|
+
}
|
|
54
|
+
function facts(spec: ProofPredicate, local?: readonly [string, string]) {
|
|
55
|
+
if (spec.kind === "boolean") equalities(spec.expression, local);
|
|
56
|
+
if (spec.kind === "binary" && spec.operator === "and") { facts(spec.left, local); facts(spec.right, local); }
|
|
57
|
+
}
|
|
58
|
+
for (const premise of claim.premises) {
|
|
59
|
+
if (premise.kind === "condition") equalities(premise.expression);
|
|
60
|
+
if (premise.kind === "proposition") facts(premise.predicate);
|
|
61
|
+
if (premise.kind === "refinement" && premise.target.kind === "parameter") facts(premise.predicate, [premise.variable, premise.target.name]);
|
|
62
|
+
if ((premise.kind === "sameValue" || premise.kind === "nearestInteger") && premise.target.kind === "parameter") {
|
|
63
|
+
constrain(premise.target.name, "eq", parseExpression(premise.value.source, { plugins: ["typescript"] }));
|
|
64
|
+
}
|
|
65
|
+
if (premise.kind === "comparison" && premise.target.kind === "parameter" &&
|
|
66
|
+
(premise.operator === "eq" || premise.operator === "gte" || premise.operator === "lte")) {
|
|
67
|
+
constrain(premise.target.name, premise.operator, parseExpression(premise.value.source, { plugins: ["typescript"] }));
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
if (parameters.every(p => fixed.has(p.name))) return "literal-inputs";
|
|
71
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { readFileSync, statSync } from "node:fs";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { dirname, join, resolve } from "node:path";
|
|
4
|
+
import type { SubjectSource } from "../assistant.ts";
|
|
5
|
+
|
|
6
|
+
export interface LeanOptions {
|
|
7
|
+
executable?: string;
|
|
8
|
+
toolchain?: string;
|
|
9
|
+
replay?: boolean;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
function ancestors(file: string) {
|
|
13
|
+
const directories: string[] = [];
|
|
14
|
+
for (let dir = dirname(file); ; dir = dirname(dir)) {
|
|
15
|
+
directories.push(dir);
|
|
16
|
+
if (dirname(dir) === dir) return directories;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function leanCommand(subject: SubjectSource, options: LeanOptions) {
|
|
21
|
+
const directories = ancestors(subject.file);
|
|
22
|
+
const executable = process.platform === "win32" ? "lean.exe" : "lean";
|
|
23
|
+
const override = options.executable ?? process.env.PUD_LEAN;
|
|
24
|
+
const local = [...directories, ...ancestors(join(process.cwd(), "pud.config.ts"))]
|
|
25
|
+
.map(dir => join(dir, ".cache", "elan")).find(home => Bun.which(join(home, "bin", executable)));
|
|
26
|
+
const localShim = local && join(local, "bin", executable);
|
|
27
|
+
const userShim = join(process.env.ELAN_HOME ?? join(homedir(), ".elan"), "bin", executable);
|
|
28
|
+
const binary = override
|
|
29
|
+
? /[/\\]/.test(override) ? resolve(override) : Bun.which(override) ?? override
|
|
30
|
+
: localShim ?? Bun.which("lean") ?? Bun.which(userShim) ?? "lean";
|
|
31
|
+
const env = { ...process.env };
|
|
32
|
+
if (local && binary === localShim) env.ELAN_HOME = local;
|
|
33
|
+
let toolchain = options.toolchain ?? env.ELAN_TOOLCHAIN;
|
|
34
|
+
if (!toolchain) {
|
|
35
|
+
const pin = directories.map(dir => join(dir, "lean-toolchain")).find(file => statSync(file, { throwIfNoEntry: false })?.isFile());
|
|
36
|
+
if (pin) toolchain = (subject.readDependency ? subject.readDependency(pin) : readFileSync(pin, "utf8")).trim();
|
|
37
|
+
}
|
|
38
|
+
if (toolchain) env.ELAN_TOOLCHAIN = toolchain;
|
|
39
|
+
return { binary, env };
|
|
40
|
+
}
|