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
|
@@ -0,0 +1,437 @@
|
|
|
1
|
+
import { parseExpression } from "@babel/parser";
|
|
2
|
+
import type { Node } from "@babel/types";
|
|
3
|
+
import { Unsupported, type ClaimProgress, type NativeProofTerm, type ProofAssistant, type ProofCall, type ProofClaim, type ProofComparison, type ProofConstraint, type ProofErrorKind, type ProofExpression, type ProofModule, type ProofOutcome, type ProofPredicate, type ProofType, type SubjectSource } from "../assistant.ts";
|
|
4
|
+
import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
|
5
|
+
import { tmpdir } from "node:os";
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
import { native } from "../suite-authoring.ts";
|
|
8
|
+
import { runProver } from "../prover-process.ts";
|
|
9
|
+
import { leanCommand, type LeanOptions } from "./command.ts";
|
|
10
|
+
import { numberBinary, numberSemantics } from "./number.ts";
|
|
11
|
+
import { definitions, lowerProgram } from "./program.ts";
|
|
12
|
+
import { replayClaim } from "./replay.ts";
|
|
13
|
+
import { iterationSemantics, scalarCall, scalarSemantics, scalarValue } from "./scalar.ts";
|
|
14
|
+
import { asOutcome, errorKinds, invoke, isScalar, leanTypes, ofSort, readProposition, readValue, type Sort, type Value } from "./syntax.ts";
|
|
15
|
+
|
|
16
|
+
export type { LeanOptions } from "./command.ts";
|
|
17
|
+
export const lean = native("lean");
|
|
18
|
+
|
|
19
|
+
const trustedAxioms = new Set(["propext", "Quot.sound", "Classical.choice"]);
|
|
20
|
+
const operators: Record<ProofComparison, string> = { eq: "=", gt: ">", gte: "≥", lt: "<", lte: "≤" };
|
|
21
|
+
const jsOperators: Record<ProofComparison, string> = { eq: "===", gt: ">", gte: ">=", lt: "<", lte: "<=" };
|
|
22
|
+
const modeledErrors = Object.keys(errorKinds) as ProofErrorKind[];
|
|
23
|
+
const errors = `inductive ErrorKind where
|
|
24
|
+
${Object.values(errorKinds).map(kind => ` | ${kind}`).join("\n")}
|
|
25
|
+
deriving DecidableEq, Repr`;
|
|
26
|
+
const autoProof = (unfold: string, recursive: readonly string[], numbers: boolean, fallible: boolean) => `by
|
|
27
|
+
simp only [claim]
|
|
28
|
+
intros
|
|
29
|
+
first
|
|
30
|
+
| rfl${fallible ? `
|
|
31
|
+
| solve | simp (disch := omega) [${unfold}, pure, Except.pure, bind, Except.bind, if_neg, if_pos]` : ""}${numbers ? `
|
|
32
|
+
| solve | simp (disch := assumption) only [${unfold}, pure, JSNumber.round_integer, JSNumber.floor_integer,
|
|
33
|
+
JSNumber.ceil_integer, JSNumber.trunc_integer, JSNumber.round_eq_zero, JSNumber.mul_comm,
|
|
34
|
+
JSNumber.nearestInteger_round, JSNumber.nearestInteger_round_down]
|
|
35
|
+
| solve
|
|
36
|
+
| simp (disch := decide) only [${unfold}, JSNumber.mul_neg, JSNumber.div_neg, JSNumber.mul_comm,
|
|
37
|
+
JSNumber.round_eq_zero, JSNumber.eq_self, JSNumber.isNaN_neg, JSNumber.isNaN_mul_right,
|
|
38
|
+
JSNumber.isNaN_mul_left, JSNumber.isNaN_div_right, Bool.not_eq_true'] at * <;> assumption
|
|
39
|
+
| simp only [${unfold}] at *
|
|
40
|
+
try apply JSNumber.nonnegative_round
|
|
41
|
+
first | apply JSNumber.nonnegative_mul <;> first | assumption | decide
|
|
42
|
+
| apply JSNumber.negative_div <;> first | assumption | decide
|
|
43
|
+
| simp only [${unfold}] at *
|
|
44
|
+
try simp (disch := decide) only [JSNumber.eq_regular] at *
|
|
45
|
+
subst_vars
|
|
46
|
+
decide +kernel` : ""}
|
|
47
|
+
| try simp_all [${unfold}, Int.add_nonneg, Int.tmod_eq_emod_of_nonneg, Int.tdiv_eq_ediv_of_nonneg]
|
|
48
|
+
all_goals (repeat' (split <;> try simp_all))
|
|
49
|
+
all_goals ((try simp (disch := omega) [Int.tmod_eq_emod_of_nonneg, Int.tdiv_eq_ediv_of_nonneg] at *) <;> (first | rfl | omega))${recursive.length ? `
|
|
50
|
+
| solve | simp_all (config := { maxSteps := 500 }) [${unfold}, ${recursive.join(", ")}]` : ""}
|
|
51
|
+
| try simp_all [${unfold}]
|
|
52
|
+
all_goals (repeat' (first | split | constructor))
|
|
53
|
+
all_goals ((try simp_all) <;> omega)`;
|
|
54
|
+
|
|
55
|
+
function proofType(sort: Sort, itemType: string | undefined): ProofType {
|
|
56
|
+
switch (sort) {
|
|
57
|
+
case "integer":
|
|
58
|
+
case "number":
|
|
59
|
+
case "boolean": return { kind: sort };
|
|
60
|
+
case "integers": return { kind: "array", item: { kind: "integer" } };
|
|
61
|
+
case "items": return { kind: "array", item: { kind: "opaque", name: itemType! } };
|
|
62
|
+
case "textOrItems": return { kind: "textOrArray", item: { kind: "opaque", name: itemType! } };
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
type Scope = ReadonlyMap<string, Value>;
|
|
67
|
+
const emptyScope: Scope = new Map();
|
|
68
|
+
const logicalOperators = { and: "∧", or: "∨", implies: "→", iff: "↔" } as const;
|
|
69
|
+
|
|
70
|
+
function readOperand<T>(
|
|
71
|
+
expression: ProofExpression, parameters: Scope, locals: Scope,
|
|
72
|
+
read: (file: string, node: Node, scope: Scope, helpers?: ReadonlySet<string>, numberGlobal?: boolean) => T,
|
|
73
|
+
): T {
|
|
74
|
+
const { file, source, line, column, offset, bindings, schemaBindings } = expression;
|
|
75
|
+
const scope = new Map([...bindings].map(([name, parameter]) => [name, parameters.get(parameter)!]));
|
|
76
|
+
for (const [name, value] of locals) scope.set(name, value);
|
|
77
|
+
try {
|
|
78
|
+
const node = parseExpression(source, { plugins: ["typescript"], startLine: line, startColumn: column, startIndex: offset });
|
|
79
|
+
return read(file, node, scope, schemaBindings, expression.numberGlobal);
|
|
80
|
+
} catch (error) {
|
|
81
|
+
if (error instanceof Unsupported) throw error;
|
|
82
|
+
throw new Unsupported(`${file}:${line}:${column + 1}: ${(error as Error).message}`);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function indent(code: string) { return code.split("\n").map(line => ` ${line}`).join("\n"); }
|
|
87
|
+
|
|
88
|
+
type Program = ReturnType<typeof lowerProgram>;
|
|
89
|
+
|
|
90
|
+
function observe(program: Program, observation?: ProofCall) {
|
|
91
|
+
const { root } = program;
|
|
92
|
+
const roots = new Set([root]);
|
|
93
|
+
const parameters = new Map(root.params.map(param => [param.name, param]));
|
|
94
|
+
let next = 0;
|
|
95
|
+
const fresh = () => `callArg${next++}`;
|
|
96
|
+
type Observation = { value: Value; source?: ReturnType<typeof scalarValue> };
|
|
97
|
+
function call(node: ProofCall): Observation {
|
|
98
|
+
const subject = node.callee === "subject" ? root : program.resolve(node.callee.file, node.callee.name);
|
|
99
|
+
if (subject.itemType || subject.params.length !== node.args.length) {
|
|
100
|
+
throw new Unsupported("Pass the full signature of each function in a composed call.");
|
|
101
|
+
}
|
|
102
|
+
roots.add(subject);
|
|
103
|
+
const args = node.args.map((arg, index) => {
|
|
104
|
+
const param = arg.kind === "parameter" ? parameters.get(arg.name) : undefined;
|
|
105
|
+
const operand = arg.kind === "call" ? call(arg) : param && { value: param, source: scalarValue(param.sort, param.code) };
|
|
106
|
+
if (operand?.value.sort !== subject.params[index]!.sort) {
|
|
107
|
+
throw new Unsupported("Each argument in a composed call must match the callee's declared type.");
|
|
108
|
+
}
|
|
109
|
+
return operand;
|
|
110
|
+
});
|
|
111
|
+
return { value: invoke(subject, args.map(arg => arg.value), fresh), source: scalarCall(subject, args.map(arg => arg.source), fresh) };
|
|
112
|
+
}
|
|
113
|
+
const args = [root.itemType && "(Item := Item)", ...root.params.map(param => param.code)].filter(Boolean);
|
|
114
|
+
const observed: Observation = observation ? call(observation) : {
|
|
115
|
+
value: { sort: root.result, code: [root.code, ...args].join(" "), fallible: root.fallible },
|
|
116
|
+
source: root.sourceExpression && (root.result === "integer" || root.result === "boolean")
|
|
117
|
+
? { sort: root.result, code: `(${[`${root.code}Source`, ...args].join(" ")})` } : undefined,
|
|
118
|
+
};
|
|
119
|
+
return { ...observed, linked: definitions([...roots]) };
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function loweringProof(observed: ReturnType<typeof observe>, binders: string) {
|
|
123
|
+
if (!observed.source) return;
|
|
124
|
+
const proved = observed.linked.filter(subject => subject.sourceExpression);
|
|
125
|
+
function normalize(rewrite: readonly string[]) {
|
|
126
|
+
const rules = [...rewrite, "Scalar.lower", "Scalar.Binary.lower", "Scalar.Unary.apply", "Id.run", "bind", "pure", "Except.pure"];
|
|
127
|
+
return `first
|
|
128
|
+
| rfl
|
|
129
|
+
| simp [${rules.join(", ")}]
|
|
130
|
+
all_goals (repeat' (split <;> try simp_all))
|
|
131
|
+
all_goals (first | rfl | simp_all | omega)`;
|
|
132
|
+
}
|
|
133
|
+
const sourceDefinitions = proved.map(subject => {
|
|
134
|
+
const source = subject.code + "Source";
|
|
135
|
+
const params = subject.params.map(p => ` (${p.code} : ${leanTypes[p.sort]})`).join("");
|
|
136
|
+
const args = subject.params.map(p => " " + p.code).join("");
|
|
137
|
+
const invocation: Value = { sort: subject.result, code: subject.code + args, fallible: subject.fallible };
|
|
138
|
+
return `def ${source}${params} : Scalar.Expr ErrorKind .${subject.result} :=
|
|
139
|
+
${subject.sourceExpression}
|
|
140
|
+
|
|
141
|
+
theorem ${subject.code}Lowering${params} :
|
|
142
|
+
Scalar.lower (${source}${args}) = ${asOutcome(invocation)} := by
|
|
143
|
+
${indent(normalize([source, subject.code, ...[...subject.callees].map(callee => callee.code + "Lowering")]))}`;
|
|
144
|
+
});
|
|
145
|
+
return [...sourceDefinitions, `def loweringClaim : Prop :=
|
|
146
|
+
${binders ? `∀ ${binders},\n ` : ""}Scalar.evaluate ${observed.source.code} = ${asOutcome(observed.value)}
|
|
147
|
+
|
|
148
|
+
theorem loweringCertificate : loweringClaim := by
|
|
149
|
+
simp only [loweringClaim]
|
|
150
|
+
intros
|
|
151
|
+
rw [Scalar.preservation]
|
|
152
|
+
${indent(normalize(proved.map(subject => subject.code + "Lowering")))}`].join("\n\n");
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** Direct adapter callers can also supply a claim created before the kind field was introduced. */
|
|
156
|
+
function checkedClaim(input: Omit<ProofClaim, "kind"> & { kind?: ProofClaim["kind"] }): ProofClaim {
|
|
157
|
+
const { kind: tag, assertions, exactResult, expectedError, reference, ...common } = input;
|
|
158
|
+
const kind = tag ?? (expectedError !== undefined ? "throw" : reference !== undefined ? "equal" : "return");
|
|
159
|
+
const returns = Boolean(assertions.length || exactResult);
|
|
160
|
+
if (kind === "return" && returns && reference === undefined && expectedError === undefined) {
|
|
161
|
+
return { ...common, kind, assertions, exactResult };
|
|
162
|
+
}
|
|
163
|
+
if (kind === "equal" && reference && !returns && expectedError === undefined) {
|
|
164
|
+
return { ...common, kind, reference, assertions: [] };
|
|
165
|
+
}
|
|
166
|
+
if (kind === "throw" && expectedError && Object.hasOwn(errorKinds, expectedError) && !returns && reference === undefined) {
|
|
167
|
+
return { ...common, kind, expectedError, assertions: [] };
|
|
168
|
+
}
|
|
169
|
+
throw new Unsupported("State a return predicate, equality between calls, or one modeled exception.");
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function generate(program: Program, input: ProofClaim, imports: readonly string[]) {
|
|
173
|
+
const claim = checkedClaim(input);
|
|
174
|
+
const { params, itemType } = program.root;
|
|
175
|
+
const observed = observe(program, claim.observation);
|
|
176
|
+
const execution = observed.value;
|
|
177
|
+
if (claim.exactResult && !isScalar(execution.sort)) {
|
|
178
|
+
throw new Unsupported("Use an exact result schema for a scalar return value.");
|
|
179
|
+
}
|
|
180
|
+
const reference = claim.kind === "equal" ? observe(program, claim.reference) : undefined;
|
|
181
|
+
if (reference && (!isScalar(execution.sort) || reference.value.sort !== execution.sort || reference.value.fallible || execution.fallible)) {
|
|
182
|
+
throw new Unsupported("Use toEqual() with two nonthrowing calls returning the same scalar type.");
|
|
183
|
+
}
|
|
184
|
+
const linked = reference ? definitions([...observed.linked, ...reference.linked]) : observed.linked;
|
|
185
|
+
const parameters = new Map(params.map(p => [p.name, p]));
|
|
186
|
+
const result: Value = { sort: execution.sort, code: "result" };
|
|
187
|
+
let nextBinder = 0;
|
|
188
|
+
|
|
189
|
+
function operand(expression: ProofExpression, locals: Scope, expected?: Sort) {
|
|
190
|
+
return readOperand(expression, parameters, locals, (file, node, scope, helpers, numberGlobal) => {
|
|
191
|
+
const value = readValue(file, node, scope, helpers, undefined, numberGlobal);
|
|
192
|
+
return expected ? ofSort(file, node, value, expected) : value.code;
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
function term(proof: NativeProofTerm, locals: Scope) {
|
|
197
|
+
if (proof.assistant !== "lean") throw new Unsupported(`This proof term requires ${proof.assistant}.`);
|
|
198
|
+
const args = proof.args.map(arg => operand(arg, locals));
|
|
199
|
+
if (proof.kind === "reference") return [proof.name, ...args].join(" ");
|
|
200
|
+
return `(${proof.parts.map((part, i) => i ? `(${args[i - 1]})${part}` : part).join("")})`;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function predicate(spec: ProofPredicate, locals: Scope): string {
|
|
204
|
+
switch (spec.kind) {
|
|
205
|
+
case "boolean": return readOperand(spec.expression, parameters, locals, readProposition);
|
|
206
|
+
case "not": return `(¬ ${predicate(spec.operand, locals)})`;
|
|
207
|
+
case "binary": return `(${predicate(spec.left, locals)} ${logicalOperators[spec.operator]} ${predicate(spec.right, locals)})`;
|
|
208
|
+
case "quantifier": {
|
|
209
|
+
const { domain } = spec;
|
|
210
|
+
const value: Value = { sort: domain.kind === "schema" ? domain.type : "integer", code: `q${nextBinder++}` };
|
|
211
|
+
// The domain is outside the scope of the new binder, even when callback names repeat.
|
|
212
|
+
const restrictions = domain.kind === "schema"
|
|
213
|
+
? domain.constraints.map(clause => renderConstraint(clause, locals, value))
|
|
214
|
+
: [`(${value.code} ∈ ${operand(domain.expression, locals, "integers")})`];
|
|
215
|
+
const body = predicate(spec.predicate, new Map([...locals, [spec.variable, value]]));
|
|
216
|
+
const binder = `(${value.code} : ${leanTypes[value.sort]})`;
|
|
217
|
+
const connective = spec.quantifier === "forall" ? "→" : "∧";
|
|
218
|
+
const symbol = spec.quantifier === "forall" ? "∀" : "∃";
|
|
219
|
+
const guarded = restrictions.length ? `(${restrictions.join(" ∧ ")}) ${connective} ${body}` : body;
|
|
220
|
+
return `(${symbol} ${binder}, ${guarded})`;
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
function renderConstraint(constraint: ProofConstraint, locals: Scope, quantified?: Value): string {
|
|
226
|
+
if (constraint.kind === "condition") return `(${operand(constraint.expression, locals, "boolean")} = true)`;
|
|
227
|
+
if (constraint.kind === "proposition") return predicate(constraint.predicate, locals);
|
|
228
|
+
const target = constraint.target;
|
|
229
|
+
const value = target.kind === "result" ? result : target.kind === "quantified" ? quantified : parameters.get(target.name);
|
|
230
|
+
if (!value) throw new Unsupported("The property constraint has no corresponding value.");
|
|
231
|
+
if (constraint.kind === "refinement") return predicate(constraint.predicate, new Map([...locals, [constraint.variable, value]]));
|
|
232
|
+
if (constraint.kind === "native") return `((${term(constraint.term, locals)} ${value.code}) : Prop)`;
|
|
233
|
+
const rhs = operand(constraint.value, locals, value.sort);
|
|
234
|
+
if (constraint.kind === "sameValue") {
|
|
235
|
+
if (value.sort !== "number") throw new Unsupported("Use sameValue() with a JavaScript number.");
|
|
236
|
+
return `(${value.code} = ${rhs})`;
|
|
237
|
+
}
|
|
238
|
+
if (constraint.kind === "nearestInteger") {
|
|
239
|
+
if (value.sort !== "number") throw new Unsupported("Use nearestIntegerTo() with a JavaScript number.");
|
|
240
|
+
return `(${value.code} = JSNumber.nearestInteger (${rhs}) ${constraint.ties === "up"})`;
|
|
241
|
+
}
|
|
242
|
+
if (value.sort === "number") return `(${numberBinary(jsOperators[constraint.operator], value.code, rhs)!.code} = true)`;
|
|
243
|
+
return `(${value.code} ${operators[constraint.operator]} ${rhs})`;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
const render = (constraint: ProofConstraint) => renderConstraint(constraint, emptyScope);
|
|
247
|
+
const binders = [itemType && "(Item : Type)", ...params.map(param => `(${param.code} : ${leanTypes[param.sort]})`)].filter(Boolean).join(" ");
|
|
248
|
+
const premises = claim.premises.map(p => `${render(p)} →`);
|
|
249
|
+
const assertions = claim.assertions.map(render).join(" ∧\n") || "True";
|
|
250
|
+
const binding = claim.exactResult ? "actual" : "result";
|
|
251
|
+
const postcondition = claim.exactResult
|
|
252
|
+
? `∀ (result : ${leanTypes[execution.sort]}), (${assertions}) ↔ result = actual` : assertions;
|
|
253
|
+
function goal(outcome: Value) {
|
|
254
|
+
if (claim.kind === "throw") return outcome.fallible ? `(${outcome.code}) = .error ErrorKind.${errorKinds[claim.expectedError]}` : "False";
|
|
255
|
+
if (reference) return outcome.sort === "number"
|
|
256
|
+
? `JSNumber.eq (${outcome.code}) (${reference.value.code}) = true` : `(${outcome.code}) = (${reference.value.code})`;
|
|
257
|
+
return outcome.fallible
|
|
258
|
+
? `match (${outcome.code}) with\n| .ok ${binding} =>\n${indent(postcondition)}\n| .error _ => False`
|
|
259
|
+
: `let ${binding} := ${outcome.code}\n${postcondition}`;
|
|
260
|
+
}
|
|
261
|
+
function proposition(outcome: Value) {
|
|
262
|
+
return [binders && `∀ ${binders},`, ...premises, goal(outcome)].filter(Boolean).join("\n");
|
|
263
|
+
}
|
|
264
|
+
const simplify = [...linked.filter(subject => !subject.recursive).map(subject => subject.code), "Id.run"].join(", ");
|
|
265
|
+
const recursive = linked.filter(subject => subject.recursive).map(subject => subject.code);
|
|
266
|
+
const countdown = linked.some(subject => subject.countdown);
|
|
267
|
+
const fold = linked.some(subject => subject.fold);
|
|
268
|
+
const loopConformance = linked.flatMap(subject => subject.loopConformance);
|
|
269
|
+
if (countdown) recursive.push("countdownWhile");
|
|
270
|
+
const certificate = reference ? undefined : loweringProof(observed, binders);
|
|
271
|
+
const sourceClaim = certificate && observed.source && proposition({
|
|
272
|
+
sort: observed.source.sort, code: `Scalar.evaluate ${observed.source.code}`, fallible: true,
|
|
273
|
+
});
|
|
274
|
+
const claimText = proposition(execution);
|
|
275
|
+
const usesNumbers = linked.some(subject => subject.definition.includes("JSNumber")) || claimText.includes("JSNumber");
|
|
276
|
+
let proof = claim.proof ? term(claim.proof, emptyScope) : autoProof(simplify, recursive, usesNumbers, !!execution.fallible);
|
|
277
|
+
if (claim.proof?.kind === "reference" && loopConformance.length) {
|
|
278
|
+
const rewrites = loopConformance.map(({ name }) => name).join(", ");
|
|
279
|
+
proof = `by
|
|
280
|
+
first
|
|
281
|
+
| exact (${proof})
|
|
282
|
+
| simpa only [claim, ${simplify}, bind, pure, ${rewrites}] using (${proof})`;
|
|
283
|
+
}
|
|
284
|
+
const unit = [
|
|
285
|
+
"import Std", ...imports.map(module => `import ${module}`), "", ...(usesNumbers ? [numberSemantics, ""] : []), ...(certificate ? [scalarSemantics, ""] : []),
|
|
286
|
+
...(countdown || fold || loopConformance.length ? [iterationSemantics, ""] : []),
|
|
287
|
+
"namespace Pud", "", "set_option autoImplicit false", "",
|
|
288
|
+
errors, "",
|
|
289
|
+
linked.map(subject => subject.definition).join("\n\n"), "",
|
|
290
|
+
...loopConformance.flatMap(({ definition }) => [definition, ""]),
|
|
291
|
+
...(certificate ? [certificate, ""] : []),
|
|
292
|
+
"def claim : Prop :=", indent(claimText), "",
|
|
293
|
+
...(sourceClaim ? ["def sourceClaim : Prop :=", indent(sourceClaim), ""] : []),
|
|
294
|
+
"theorem checked : claim :=", indent(proof), "",
|
|
295
|
+
...(sourceClaim ? [`theorem sourceChecked : sourceClaim := by
|
|
296
|
+
have preservation := loweringCertificate
|
|
297
|
+
unfold loweringClaim at preservation
|
|
298
|
+
simpa [sourceClaim, claim, preservation] using checked`, ""] : []),
|
|
299
|
+
"end Pud", "",
|
|
300
|
+
].join("\n");
|
|
301
|
+
const iterationTheorems = [
|
|
302
|
+
...(countdown ? ["Pud.countdownWhile_except_correct", "Pud.countdownWhile_pure_correct"] : []),
|
|
303
|
+
...(fold ? ["Pud.denseForOf_correct"] : []),
|
|
304
|
+
...loopConformance.map(({ name }) => `Pud.${name}`),
|
|
305
|
+
];
|
|
306
|
+
return { unit, claim, certifiedLowering: !!certificate, iterationTheorems };
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
class RejectedProof extends Error {}
|
|
310
|
+
|
|
311
|
+
function leanAt(dir: string, command: ReturnType<typeof leanCommand>) {
|
|
312
|
+
return async (module: string, source: string, compile = false) => {
|
|
313
|
+
const file = `${module}.lean`;
|
|
314
|
+
const artifact = `${module}.olean`;
|
|
315
|
+
writeFileSync(join(dir, file), source);
|
|
316
|
+
const run = await runProver(command.binary, compile ? ["-o", artifact, file] : [file], {
|
|
317
|
+
cwd: dir, env: { ...command.env, LEAN_PATH: dir }, timeout: 30_000, maxBuffer: 1024 * 1024,
|
|
318
|
+
}).catch(error => {
|
|
319
|
+
if (error.code === "ENOENT") throw new Error("Install Lean with Elan or set PUD_LEAN to a working Lean executable.");
|
|
320
|
+
if (error.signal) throw new Error(`Lean was interrupted by ${error.signal} while checking ${file}.`);
|
|
321
|
+
throw error;
|
|
322
|
+
});
|
|
323
|
+
if (run.status !== 0) throw new RejectedProof([run.stdout, run.stderr].filter(Boolean).join("\n").trim() || `Lean rejected ${file}.`);
|
|
324
|
+
if (compile && !existsSync(join(dir, artifact))) throw new Error(`Lean did not produce ${artifact}.`);
|
|
325
|
+
return run.stdout.trim();
|
|
326
|
+
};
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
async function audit(module: string, run: ReturnType<typeof leanAt>, certificate: ReturnType<typeof generate>) {
|
|
330
|
+
const { certifiedLowering, iterationTheorems } = certificate;
|
|
331
|
+
const certificates = ["pudAuditCertificate",
|
|
332
|
+
...(certifiedLowering ? ["pudLoweringAuditCertificate", "pudSourceAuditCertificate"] : []), ...iterationTheorems];
|
|
333
|
+
const report = await run("PudAudit", [
|
|
334
|
+
`import ${module}`, "set_option autoImplicit false",
|
|
335
|
+
"theorem pudAuditCertificate : Pud.claim := Pud.checked",
|
|
336
|
+
...(certifiedLowering ? [
|
|
337
|
+
"theorem pudLoweringAuditCertificate : Pud.loweringClaim := Pud.loweringCertificate",
|
|
338
|
+
"theorem pudSourceAuditCertificate : Pud.sourceClaim := Pud.sourceChecked",
|
|
339
|
+
] : []),
|
|
340
|
+
...certificates.map(name => `#print axioms ${name}`), "",
|
|
341
|
+
].join("\n"));
|
|
342
|
+
const lines = report.split("\n");
|
|
343
|
+
const approved = certificates.every((name, index) => {
|
|
344
|
+
const line = lines[index];
|
|
345
|
+
if (line === `'${name}' does not depend on any axioms`) return true;
|
|
346
|
+
const prefix = `'${name}' depends on axioms: [`;
|
|
347
|
+
return line?.startsWith(prefix) && line.endsWith("]") &&
|
|
348
|
+
line.slice(prefix.length, -1).split(",").every(axiom => trustedAxioms.has(axiom.trim()));
|
|
349
|
+
});
|
|
350
|
+
if (lines.length !== certificates.length || !approved) {
|
|
351
|
+
throw new RejectedProof(`Lean did not certify the expected claim with approved axioms.\n${report}`);
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
function moduleNames(modules: readonly ProofModule[]) {
|
|
356
|
+
return modules.map(({ file }, i) => {
|
|
357
|
+
if (!file.endsWith(".lean")) throw new Unsupported(`Expected a .lean support module. Received ${file}.`);
|
|
358
|
+
return `PudSupport${i}`;
|
|
359
|
+
});
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
async function verify(
|
|
363
|
+
program: Program, source: SubjectSource, options: LeanOptions, claims: readonly ProofClaim[],
|
|
364
|
+
modules: readonly ProofModule[], onClaim?: ClaimProgress,
|
|
365
|
+
): Promise<ProofOutcome[]> {
|
|
366
|
+
const imports = moduleNames(modules);
|
|
367
|
+
const units = claims.map(claim => {
|
|
368
|
+
try { return generate(program, claim, imports); }
|
|
369
|
+
catch (error) {
|
|
370
|
+
if (!(error instanceof Unsupported)) throw error;
|
|
371
|
+
return { outcome: { status: "unsupported", detail: error.message } as const };
|
|
372
|
+
}
|
|
373
|
+
});
|
|
374
|
+
if (units.every(entry => "outcome" in entry)) return units.map(entry => entry.outcome!);
|
|
375
|
+
const dir = mkdtempSync(join(tmpdir(), "pud-lean-"));
|
|
376
|
+
try {
|
|
377
|
+
const run = leanAt(dir, leanCommand(source, options));
|
|
378
|
+
for (const [i, module] of modules.entries()) {
|
|
379
|
+
try { await run(imports[i]!, module.source, true); }
|
|
380
|
+
catch (error) { throw new Error(`${module.file}\n${(error as Error).message}`); }
|
|
381
|
+
}
|
|
382
|
+
const outcomes: ProofOutcome[] = [];
|
|
383
|
+
for (const [i, entry] of units.entries()) {
|
|
384
|
+
if ("outcome" in entry) {
|
|
385
|
+
outcomes.push(entry.outcome);
|
|
386
|
+
onClaim?.(i, "finished", entry.outcome.status);
|
|
387
|
+
continue;
|
|
388
|
+
}
|
|
389
|
+
onClaim?.(i, "running");
|
|
390
|
+
let outcome: ProofOutcome;
|
|
391
|
+
try {
|
|
392
|
+
const module = `PudClaim${i}`;
|
|
393
|
+
await run(module, entry.unit, true);
|
|
394
|
+
await audit(module, run, entry);
|
|
395
|
+
outcome = { status: "proved" };
|
|
396
|
+
} catch (error) {
|
|
397
|
+
const detail = (error as Error).message;
|
|
398
|
+
outcome = error instanceof RejectedProof && entry.claim.exactResult
|
|
399
|
+
? { status: "unproved", detail: "Lean could not prove that the rule accepts exactly the returned value for each admitted input.", diagnostic: detail }
|
|
400
|
+
: { status: error instanceof RejectedProof ? "unproved" : "error", detail };
|
|
401
|
+
if (error instanceof RejectedProof && options.replay) {
|
|
402
|
+
try {
|
|
403
|
+
const counterexample = await replayClaim(program, entry.claim, join(dir, `replay-${i}`));
|
|
404
|
+
if (counterexample) outcome = { status: "disproved", counterexample };
|
|
405
|
+
} catch (replayError) {
|
|
406
|
+
outcome = { status: "error", detail: `Bun replay failed. ${(replayError as Error).message}`, diagnostic: detail };
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
outcomes.push(outcome);
|
|
411
|
+
onClaim?.(i, "finished", outcome.status);
|
|
412
|
+
}
|
|
413
|
+
return outcomes;
|
|
414
|
+
} finally {
|
|
415
|
+
rmSync(dir, { recursive: true, force: true });
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
export function leanAdapter(options: LeanOptions = {}): ProofAssistant<"lean"> {
|
|
420
|
+
return {
|
|
421
|
+
id: "lean",
|
|
422
|
+
prepare(source) {
|
|
423
|
+
const program = lowerProgram(source);
|
|
424
|
+
const subject = program.root;
|
|
425
|
+
return {
|
|
426
|
+
parameters: subject.params.map(p => ({ name: p.name, type: proofType(p.sort, subject.itemType) })),
|
|
427
|
+
result: proofType(subject.result, subject.itemType),
|
|
428
|
+
inspectCall(call) { return proofType(observe(program, call).value.sort, undefined); },
|
|
429
|
+
callEquality: true,
|
|
430
|
+
exactResults: true,
|
|
431
|
+
errors: modeledErrors,
|
|
432
|
+
emit(claim, modules) { return generate(program, claim, moduleNames(modules)).unit; },
|
|
433
|
+
verify(claims, modules, onClaim) { return verify(program, source, options, claims, modules, onClaim); },
|
|
434
|
+
};
|
|
435
|
+
},
|
|
436
|
+
};
|
|
437
|
+
}
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import Std
|
|
2
|
+
|
|
3
|
+
namespace Pud
|
|
4
|
+
|
|
5
|
+
set_option autoImplicit false
|
|
6
|
+
|
|
7
|
+
def countdownWhile {m : Type → Type} [Monad m] {σ : Type}
|
|
8
|
+
(counter limit decrement : Int) (positive : 0 < decrement)
|
|
9
|
+
(step : Int → σ → m σ) (state : σ) : m (Int × σ) :=
|
|
10
|
+
if _above : counter > limit then do
|
|
11
|
+
let next ← step counter state
|
|
12
|
+
countdownWhile (counter - decrement) limit decrement positive step next
|
|
13
|
+
else pure (counter, state)
|
|
14
|
+
termination_by (counter - limit).toNat
|
|
15
|
+
decreasing_by omega
|
|
16
|
+
|
|
17
|
+
@[simp] theorem countdownWhile_stop {m : Type → Type} [Monad m] {σ : Type}
|
|
18
|
+
(counter limit decrement : Int) (positive : 0 < decrement)
|
|
19
|
+
(step : Int → σ → m σ) (state : σ) (stopped : counter ≤ limit) :
|
|
20
|
+
countdownWhile counter limit decrement positive step state = pure (counter, state) := by
|
|
21
|
+
rw [countdownWhile]
|
|
22
|
+
simp [Int.not_lt.mpr stopped]
|
|
23
|
+
|
|
24
|
+
-- A false guard finishes with the current state. A throw finishes before the
|
|
25
|
+
-- counter update. A successful body updates the counter and runs the next step.
|
|
26
|
+
inductive CountdownRuns {ε σ : Type} (limit decrement : Int)
|
|
27
|
+
(step : Int → σ → Except ε σ) : Int → σ → Except ε (Int × σ) → Prop where
|
|
28
|
+
| stopped {counter state} : counter ≤ limit →
|
|
29
|
+
CountdownRuns limit decrement step counter state (.ok (counter, state))
|
|
30
|
+
| thrown {counter state error} : counter > limit → step counter state = .error error →
|
|
31
|
+
CountdownRuns limit decrement step counter state (.error error)
|
|
32
|
+
| continued {counter state next outcome} : counter > limit → step counter state = .ok next →
|
|
33
|
+
CountdownRuns limit decrement step (counter - decrement) next outcome →
|
|
34
|
+
CountdownRuns limit decrement step counter state outcome
|
|
35
|
+
|
|
36
|
+
theorem countdownWhile_except_runs {ε σ : Type}
|
|
37
|
+
(counter limit decrement : Int) (positive : 0 < decrement)
|
|
38
|
+
(step : Int → σ → Except ε σ) (state : σ) :
|
|
39
|
+
CountdownRuns limit decrement step counter state (countdownWhile counter limit decrement positive step state) := by
|
|
40
|
+
by_cases above : counter > limit
|
|
41
|
+
· rw [countdownWhile]
|
|
42
|
+
simp only [dif_pos above]
|
|
43
|
+
cases currentStep : step counter state with
|
|
44
|
+
| error error => exact .thrown above currentStep
|
|
45
|
+
| ok next =>
|
|
46
|
+
exact .continued above currentStep
|
|
47
|
+
(countdownWhile_except_runs (counter - decrement) limit decrement positive step next)
|
|
48
|
+
· rw [countdownWhile_stop _ _ _ _ _ _ (Int.le_of_not_gt above)]
|
|
49
|
+
exact .stopped (Int.le_of_not_gt above)
|
|
50
|
+
termination_by (counter - limit).toNat
|
|
51
|
+
decreasing_by omega
|
|
52
|
+
|
|
53
|
+
theorem countdownWhile_pure_runs {σ : Type}
|
|
54
|
+
(counter limit decrement : Int) (positive : 0 < decrement)
|
|
55
|
+
(step : Int → σ → σ) (state : σ) :
|
|
56
|
+
CountdownRuns (ε := Unit) limit decrement (fun n s => .ok (step n s)) counter state
|
|
57
|
+
(.ok (countdownWhile (m := Id) counter limit decrement positive step state)) := by
|
|
58
|
+
by_cases above : counter > limit
|
|
59
|
+
· rw [countdownWhile]
|
|
60
|
+
simp only [dif_pos above]
|
|
61
|
+
exact .continued above rfl (countdownWhile_pure_runs (counter - decrement) limit decrement positive step (step counter state))
|
|
62
|
+
· rw [countdownWhile_stop _ _ _ _ _ _ (Int.le_of_not_gt above)]
|
|
63
|
+
exact .stopped (Int.le_of_not_gt above)
|
|
64
|
+
termination_by (counter - limit).toNat
|
|
65
|
+
decreasing_by omega
|
|
66
|
+
|
|
67
|
+
theorem CountdownRuns.deterministic {ε σ : Type} {limit decrement : Int}
|
|
68
|
+
{step : Int → σ → Except ε σ} {counter : Int} {state : σ} {first second : Except ε (Int × σ)}
|
|
69
|
+
(h₁ : CountdownRuns limit decrement step counter state first)
|
|
70
|
+
(h₂ : CountdownRuns limit decrement step counter state second) : first = second := by
|
|
71
|
+
induction h₁ generalizing second with
|
|
72
|
+
| stopped below => cases h₂ <;> first | rfl | omega
|
|
73
|
+
| thrown above error => cases h₂ <;> first | (simp_all; done) | omega
|
|
74
|
+
| continued above ok _ ih =>
|
|
75
|
+
cases h₂ with
|
|
76
|
+
| stopped _ => omega
|
|
77
|
+
| thrown _ error => rw [ok] at error; contradiction
|
|
78
|
+
| continued _ other rest =>
|
|
79
|
+
have same := Except.ok.inj (ok.symm.trans other)
|
|
80
|
+
cases same
|
|
81
|
+
exact ih rest
|
|
82
|
+
|
|
83
|
+
theorem countdownWhile_except_correct {ε σ : Type} (counter limit decrement : Int)
|
|
84
|
+
(positive : 0 < decrement) (step : Int → σ → Except ε σ) (state : σ) (outcome : Except ε (Int × σ)) :
|
|
85
|
+
CountdownRuns limit decrement step counter state outcome ↔
|
|
86
|
+
countdownWhile counter limit decrement positive step state = outcome := by
|
|
87
|
+
have run := countdownWhile_except_runs counter limit decrement positive step state
|
|
88
|
+
constructor
|
|
89
|
+
· exact run.deterministic
|
|
90
|
+
· intro equal
|
|
91
|
+
rw [← equal]
|
|
92
|
+
exact run
|
|
93
|
+
|
|
94
|
+
theorem countdownWhile_pure_correct {σ : Type} (counter limit decrement : Int)
|
|
95
|
+
(positive : 0 < decrement) (step : Int → σ → σ) (state : σ) (outcome : Int × σ) :
|
|
96
|
+
CountdownRuns (ε := Unit) limit decrement (fun n s => .ok (step n s)) counter state (.ok outcome) ↔
|
|
97
|
+
countdownWhile (m := Id) counter limit decrement positive step state = outcome := by
|
|
98
|
+
have run := countdownWhile_pure_runs counter limit decrement positive step state
|
|
99
|
+
constructor
|
|
100
|
+
· intro other
|
|
101
|
+
exact Except.ok.inj (run.deterministic other)
|
|
102
|
+
· intro equal
|
|
103
|
+
rw [← equal]
|
|
104
|
+
exact run
|
|
105
|
+
|
|
106
|
+
-- The scalar-accumulator optimization consumes the dense array in order,
|
|
107
|
+
-- committing exactly one state update before proceeding to the tail.
|
|
108
|
+
inductive DenseForOfRuns {α σ : Type} (step : σ → α → σ) : List α → σ → σ → Prop where
|
|
109
|
+
| done (state) : DenseForOfRuns step [] state state
|
|
110
|
+
| next (value : α) {rest state final} : DenseForOfRuns step rest (step state value) final →
|
|
111
|
+
DenseForOfRuns step (value :: rest) state final
|
|
112
|
+
|
|
113
|
+
theorem denseForOf_foldl {α σ : Type} (step : σ → α → σ) (values : List α) (state : σ) :
|
|
114
|
+
DenseForOfRuns step values state (values.foldl step state) := by
|
|
115
|
+
induction values generalizing state with
|
|
116
|
+
| nil => exact .done state
|
|
117
|
+
| cons head rest ih => exact .next head (ih (step state head))
|
|
118
|
+
|
|
119
|
+
theorem DenseForOfRuns.deterministic {α σ : Type} {step : σ → α → σ} {values : List α}
|
|
120
|
+
{state first second : σ} (h₁ : DenseForOfRuns step values state first)
|
|
121
|
+
(h₂ : DenseForOfRuns step values state second) : first = second := by
|
|
122
|
+
induction h₁ generalizing second with
|
|
123
|
+
| done => cases h₂; rfl
|
|
124
|
+
| next _ _ ih => cases h₂; apply ih; assumption
|
|
125
|
+
|
|
126
|
+
theorem denseForOf_correct {α σ : Type} (step : σ → α → σ) (values : List α) (state outcome : σ) :
|
|
127
|
+
DenseForOfRuns step values state outcome ↔ values.foldl step state = outcome := by
|
|
128
|
+
have run := denseForOf_foldl step values state
|
|
129
|
+
constructor
|
|
130
|
+
· exact run.deterministic
|
|
131
|
+
· intro equal
|
|
132
|
+
rw [← equal]
|
|
133
|
+
exact run
|
|
134
|
+
|
|
135
|
+
theorem forIn_foldl_of_step_eq {α σ : Type} (values : List α) (initial : σ)
|
|
136
|
+
(body : α → σ → Id (ForInStep σ)) (step : σ → α → σ)
|
|
137
|
+
(agrees : ∀ item state, body item state = .yield (step state item)) :
|
|
138
|
+
forIn (m := Id) values initial body = values.foldl step initial := by
|
|
139
|
+
induction values generalizing initial with
|
|
140
|
+
| nil => rfl
|
|
141
|
+
| cons head tail ih =>
|
|
142
|
+
rw [List.forIn_cons, List.foldl_cons, agrees]
|
|
143
|
+
exact ih (step initial head)
|
|
144
|
+
|
|
145
|
+
end Pud
|