pud.dev 0.0.1 → 0.0.2
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/LICENSE +21 -0
- package/README.md +53 -27
- package/THIRD-PARTY-NOTICES +112 -0
- package/chunk-224av1ab.js +10 -0
- package/chunk-fstxscck.js +3 -0
- package/chunk-h90k6v7w.js +3 -0
- package/chunk-k7a83qqm.js +3 -0
- package/cli.js +37 -0
- package/index.js +2 -0
- package/lean/index.js +880 -0
- package/package.json +28 -19
- package/project-runner.js +2 -0
- package/types/assistant.d.ts +200 -0
- package/types/check.d.ts +55 -0
- package/types/expressions.d.ts +47 -0
- package/types/input-scope.d.ts +4 -0
- package/types/lean/command.d.ts +14 -0
- package/types/lean/index.d.ts +5 -0
- package/types/lean/number.d.ts +4 -0
- package/types/lean/program.d.ts +26 -0
- package/types/lean/replay-predicate.d.ts +5 -0
- package/types/lean/replay.d.ts +6 -0
- package/types/lean/scalar.d.ts +23 -0
- package/types/lean/subject.d.ts +25 -0
- package/types/lean/syntax.d.ts +42 -0
- package/types/module.d.ts +9 -0
- package/types/prover-process.d.ts +7 -0
- package/types/run.d.ts +30 -0
- package/types/source.d.ts +5 -0
- package/types/suite-authoring.d.ts +117 -0
- package/types/suite-check.d.ts +10 -0
- package/types/suite.d.ts +44 -0
- package/CLAUDE.md +0 -106
- package/scripts/pack.ts +0 -67
- package/scripts/setup-lean.ts +0 -88
- package/src/assistant.ts +0 -131
- package/src/check.ts +0 -173
- package/src/cli.ts +0 -70
- package/src/expressions.ts +0 -65
- package/src/input-scope.ts +0 -71
- package/src/lean/command.ts +0 -40
- package/src/lean/index.ts +0 -437
- package/src/lean/iteration.lean +0 -145
- package/src/lean/lean-assets.d.ts +0 -4
- package/src/lean/number.lean +0 -427
- package/src/lean/number.ts +0 -25
- package/src/lean/program.ts +0 -110
- package/src/lean/replay-predicate.ts +0 -95
- package/src/lean/replay.ts +0 -136
- package/src/lean/scalar.lean +0 -183
- package/src/lean/scalar.ts +0 -196
- package/src/lean/subject.ts +0 -443
- package/src/lean/syntax.ts +0 -287
- package/src/module.ts +0 -110
- package/src/project-runner.ts +0 -26
- package/src/prover-process.ts +0 -16
- package/src/reporter.ts +0 -173
- package/src/run.ts +0 -60
- package/src/source.ts +0 -54
- package/src/suite-authoring.ts +0 -135
- package/src/suite-check.ts +0 -157
- package/src/suite.ts +0 -515
- package/src/terminal-progress.ts +0 -145
- package/src/terminal.ts +0 -41
- package/test/authoring.test.ts +0 -151
- package/test/lean.test.ts +0 -394
- package/test/module.test.ts +0 -55
- package/test/number.test.ts +0 -318
- package/test/package.test.ts +0 -170
- package/test/suite.test.ts +0 -257
- package/tsconfig.json +0 -7
- package/tsconfig.pack.json +0 -12
- /package/{src/index.ts → types/index.d.ts} +0 -0
package/src/lean/subject.ts
DELETED
|
@@ -1,443 +0,0 @@
|
|
|
1
|
-
import { getOuterBindingIdentifiers, traverseFast, type ArrowFunctionExpression, type AssignmentExpression, type FunctionDeclaration, type Node, type Program, type Statement } from "@babel/types";
|
|
2
|
-
import { invalid } from "../source.ts";
|
|
3
|
-
import { scalarSource } from "./scalar.ts";
|
|
4
|
-
import { asOutcome, bigintLiteral, errorKinds, invoke, isScalar, leanTypes, nameOf, ofSort, readValue, sequence, truthy, tsSort, type ExecutableExpressions, type Sort, type Value } from "./syntax.ts";
|
|
5
|
-
|
|
6
|
-
type Binding = Value & { mutable?: boolean };
|
|
7
|
-
export type Parameter = Value & { name: string };
|
|
8
|
-
const roundingMethods = new Set(["round", "floor", "ceil", "trunc"]);
|
|
9
|
-
|
|
10
|
-
export interface Subject {
|
|
11
|
-
file: string;
|
|
12
|
-
name: string;
|
|
13
|
-
code: string;
|
|
14
|
-
params: Parameter[];
|
|
15
|
-
result: Sort;
|
|
16
|
-
itemType?: string;
|
|
17
|
-
definition: string;
|
|
18
|
-
fallible: boolean;
|
|
19
|
-
countdown: boolean;
|
|
20
|
-
fold: boolean;
|
|
21
|
-
loopConformance: readonly { name: string; definition: string }[];
|
|
22
|
-
recursive: boolean;
|
|
23
|
-
callees: ReadonlySet<Subject>;
|
|
24
|
-
sourceExpression?: string;
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
function exits(node: Node | undefined): boolean {
|
|
28
|
-
switch (node?.type) {
|
|
29
|
-
case "ReturnStatement":
|
|
30
|
-
case "ThrowStatement": return true;
|
|
31
|
-
case "BlockStatement": return exits(node.body.at(-1));
|
|
32
|
-
case "IfStatement": return exits(node.consequent) && exits(node.alternate ?? undefined);
|
|
33
|
-
case "TryStatement": return !!node.handler && exits(node.block) && exits(node.handler.body);
|
|
34
|
-
default: return false;
|
|
35
|
-
}
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
function tuple(parts: string[]): string {
|
|
39
|
-
return parts.length === 1 ? parts[0]! : `(${parts.join(", ")})`;
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
function singleStatement(node: Statement): Statement {
|
|
43
|
-
return node.type === "BlockStatement" && node.body.length === 1 ? node.body[0]! : node;
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
function localUpdate(node: Statement): AssignmentExpression | undefined {
|
|
47
|
-
const statement = singleStatement(node);
|
|
48
|
-
if (statement.type === "ExpressionStatement" && statement.expression.type === "AssignmentExpression" &&
|
|
49
|
-
statement.expression.left.type === "Identifier") return statement.expression;
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
export function lowerFunction(
|
|
53
|
-
file: string, program: Program, fn: FunctionDeclaration | ArrowFunctionExpression, symbol: string, code: string,
|
|
54
|
-
resolveCall: (name: string, at: Node) => Subject,
|
|
55
|
-
): Subject {
|
|
56
|
-
if (fn.async || fn.generator || fn.typeParameters) invalid(file, fn, "Expected a synchronous, non-generic function.");
|
|
57
|
-
const interfaces = new Set(program.body.flatMap(statement => {
|
|
58
|
-
const node = statement.type === "ExportNamedDeclaration" ? statement.declaration : statement;
|
|
59
|
-
return node?.type === "TSInterfaceDeclaration" && !node.typeParameters ? [node.id.name] : [];
|
|
60
|
-
}));
|
|
61
|
-
let itemType: string | undefined;
|
|
62
|
-
function sort(annotation: Node | null | undefined, at: Node) {
|
|
63
|
-
return tsSort(file, annotation, at, (name, node) => {
|
|
64
|
-
if (!interfaces.has(name) || (itemType && itemType !== name)) {
|
|
65
|
-
invalid(file, node, "Use one locally declared interface as the opaque array element type.");
|
|
66
|
-
}
|
|
67
|
-
itemType = name;
|
|
68
|
-
});
|
|
69
|
-
}
|
|
70
|
-
const inferBody = !fn.returnType && fn.type === "ArrowFunctionExpression" && fn.body.type !== "BlockStatement" ? fn.body : undefined;
|
|
71
|
-
const annotatedResult = inferBody ? undefined : sort(fn.returnType, fn);
|
|
72
|
-
const params = fn.params.map((node, i) => ({
|
|
73
|
-
name: nameOf(file, node),
|
|
74
|
-
sort: sort(node.type === "Identifier" ? node.typeAnnotation : undefined, node),
|
|
75
|
-
code: `p${i}`,
|
|
76
|
-
}));
|
|
77
|
-
const scope = new Map<string, Binding>(params.map(p => [p.name, p]));
|
|
78
|
-
const moduleNames = new Set(program.body.flatMap(node => Object.keys(getOuterBindingIdentifiers(node))));
|
|
79
|
-
const localNames = new Set(scope.keys());
|
|
80
|
-
let recursive = false;
|
|
81
|
-
traverseFast(fn.body, node => {
|
|
82
|
-
if (node.type === "VariableDeclarator") for (const name of Object.keys(getOuterBindingIdentifiers(node.id))) localNames.add(name);
|
|
83
|
-
if (node.type === "CallExpression" && node.callee.type === "Identifier" && node.callee.name === symbol) recursive = true;
|
|
84
|
-
});
|
|
85
|
-
const signature = [itemType && "{Item : Type}", ...params.map(p => `(${p.code} : ${leanTypes[p.sort]})`)].filter(Boolean);
|
|
86
|
-
|
|
87
|
-
let nextLocal = 0;
|
|
88
|
-
const fresh = () => `v${nextLocal++}`;
|
|
89
|
-
const lines: string[] = [];
|
|
90
|
-
let arrayGuard: Node | undefined;
|
|
91
|
-
let fallible = false;
|
|
92
|
-
let countdown = false;
|
|
93
|
-
let fold = false;
|
|
94
|
-
const loopConformance: Subject["loopConformance"][number][] = [];
|
|
95
|
-
const callTargets = new Map<string, Subject>();
|
|
96
|
-
const executable: ExecutableExpressions = {
|
|
97
|
-
fresh, recursive, numberGlobal: !localNames.has("Number") && !moduleNames.has("Number"),
|
|
98
|
-
call(node, read) {
|
|
99
|
-
const member = node.callee;
|
|
100
|
-
if (member.type === "MemberExpression" && !member.computed && member.object.type === "Identifier" &&
|
|
101
|
-
member.object.name === "Math" && member.property.type === "Identifier" && roundingMethods.has(member.property.name)) {
|
|
102
|
-
const method = member.property.name;
|
|
103
|
-
if (localNames.has("Math") || moduleNames.has("Math")) invalid(file, member, `Math.${method} requires the unshadowed Math built-in.`);
|
|
104
|
-
const [arg] = node.arguments;
|
|
105
|
-
if (node.typeArguments || node.arguments.length !== 1 || !arg) invalid(file, node, `Pass one number to Math.${method}.`);
|
|
106
|
-
const value = read(arg);
|
|
107
|
-
ofSort(file, arg, value, "number");
|
|
108
|
-
return sequence([value], fresh, ([x]) => ({ sort: "number", code: `(JSNumber.${method} ${x})` }));
|
|
109
|
-
}
|
|
110
|
-
if (node.typeArguments || node.callee.type !== "Identifier" || localNames.has(node.callee.name)) {
|
|
111
|
-
invalid(file, node, "Call a directly declared function without shadowing its name.");
|
|
112
|
-
}
|
|
113
|
-
const linked = node.callee.name === symbol ? undefined : resolveCall(node.callee.name, node);
|
|
114
|
-
const callee = linked ?? { params, result: annotatedResult ?? invalid(file, node, "Annotate a recursive function's return type."), itemType, code, fallible: false };
|
|
115
|
-
if (callee.itemType || node.arguments.length !== callee.params.length) {
|
|
116
|
-
invalid(file, node, "Call a supported function with its exact argument count and types.");
|
|
117
|
-
}
|
|
118
|
-
if (linked) callTargets.set(node.callee.name, linked);
|
|
119
|
-
const args = node.arguments.map((arg, index) => {
|
|
120
|
-
const value = read(arg);
|
|
121
|
-
ofSort(file, arg, value, callee.params[index]!.sort);
|
|
122
|
-
return value;
|
|
123
|
-
});
|
|
124
|
-
return invoke(callee, args, fresh);
|
|
125
|
-
},
|
|
126
|
-
};
|
|
127
|
-
const read = (node: Node, bindings: ReadonlyMap<string, Binding>) => readValue(file, node, bindings, undefined, executable);
|
|
128
|
-
const inferred = inferBody && read(inferBody, scope);
|
|
129
|
-
const result = annotatedResult ?? inferred!.sort;
|
|
130
|
-
if (result === "textOrItems") invalid(file, fn, "Return a scalar or a supported readonly array.");
|
|
131
|
-
|
|
132
|
-
function returned(node: Node, bindings: ReadonlyMap<string, Binding>): Value {
|
|
133
|
-
if (node.type === "ArrayExpression" && !node.elements.length && !isScalar(result)) return { sort: result, code: "[]" };
|
|
134
|
-
const value = read(node, bindings);
|
|
135
|
-
ofSort(file, node, value, result);
|
|
136
|
-
return value;
|
|
137
|
-
}
|
|
138
|
-
|
|
139
|
-
function assignment(node: AssignmentExpression, bindings: ReadonlyMap<string, Binding>) {
|
|
140
|
-
const name = nameOf(file, node.left);
|
|
141
|
-
const binding = bindings.get(name);
|
|
142
|
-
if (!binding?.mutable || !isScalar(binding.sort)) invalid(file, node.left, "Only scalar let bindings can be assigned.");
|
|
143
|
-
const rhs = read(node.right, bindings);
|
|
144
|
-
ofSort(file, node.right, rhs, binding.sort);
|
|
145
|
-
if (node.operator === "=") return { name, binding, rhs };
|
|
146
|
-
if (binding.sort === "integer" && (node.operator === "+=" || node.operator === "-=")) {
|
|
147
|
-
return { name, binding, rhs: sequence([rhs], fresh, ([value]) => ({
|
|
148
|
-
sort: "integer", code: `(${binding.code} ${node.operator[0]} ${value})`,
|
|
149
|
-
})) };
|
|
150
|
-
}
|
|
151
|
-
return invalid(file, node, `Unsupported assignment '${node.operator}'.`);
|
|
152
|
-
}
|
|
153
|
-
|
|
154
|
-
function line(indent: number, code: string) { lines.push(" ".repeat(indent) + code); }
|
|
155
|
-
|
|
156
|
-
function force(value: Value, indent: number) {
|
|
157
|
-
if (!value.fallible) return value.code;
|
|
158
|
-
fallible = true;
|
|
159
|
-
const name = fresh();
|
|
160
|
-
line(indent, `let ${name} ← ${value.code}`);
|
|
161
|
-
return name;
|
|
162
|
-
}
|
|
163
|
-
|
|
164
|
-
function certifyGuardedUpdate(
|
|
165
|
-
node: Extract<Statement, { type: "IfStatement" }>, bindings: ReadonlyMap<string, Binding>, item: string, itemCode: string,
|
|
166
|
-
) {
|
|
167
|
-
if (recursive || arrayGuard === node.test) return;
|
|
168
|
-
const yes = localUpdate(node.consequent);
|
|
169
|
-
const no = node.alternate && localUpdate(node.alternate);
|
|
170
|
-
if (yes?.left.type !== "Identifier" || (node.alternate && !no)) return;
|
|
171
|
-
const target = yes.left.name;
|
|
172
|
-
const accumulator = bindings.get(target);
|
|
173
|
-
if (!accumulator?.mutable || !isScalar(accumulator.sort) ||
|
|
174
|
-
(no && (no.left.type !== "Identifier" || no.left.name !== target))) return;
|
|
175
|
-
|
|
176
|
-
const state = fresh();
|
|
177
|
-
const scope = new Map(bindings);
|
|
178
|
-
scope.set(target, { ...accumulator, code: state });
|
|
179
|
-
const test = read(node.test, scope);
|
|
180
|
-
const updated = assignment(yes, scope).rhs;
|
|
181
|
-
const otherwise = no ? assignment(no, scope).rhs : { sort: accumulator.sort, code: state };
|
|
182
|
-
if (test.fallible || updated.fallible || otherwise.fallible) return;
|
|
183
|
-
const guard = truthy(test, test.code);
|
|
184
|
-
|
|
185
|
-
function delta(update: AssignmentExpression) {
|
|
186
|
-
if (accumulator?.sort !== "integer") return;
|
|
187
|
-
const { operator, right } = update;
|
|
188
|
-
if (operator === "+=" || operator === "-=") return { operator: operator[0], code: read(right, scope).code };
|
|
189
|
-
if (operator === "=" && right.type === "BinaryExpression" && (right.operator === "+" || right.operator === "-") &&
|
|
190
|
-
right.left.type === "Identifier" && right.left.name === target) {
|
|
191
|
-
return { operator: right.operator, code: read(right.right, scope).code };
|
|
192
|
-
}
|
|
193
|
-
}
|
|
194
|
-
|
|
195
|
-
// Match the fold used by an assignment with a conditional operand. Lean
|
|
196
|
-
// checks the step equality, including the identity update on a skipped arm.
|
|
197
|
-
let step = `(if ${guard} then ${updated.code} else ${otherwise.code})`;
|
|
198
|
-
const taken = delta(yes), skipped = no && delta(no);
|
|
199
|
-
if (taken && (!no || skipped?.operator === taken.operator)) {
|
|
200
|
-
step = `(${state} ${taken.operator} (if ${guard} then ${taken.code} else ${skipped?.code ?? "(0 : Int)"}))`;
|
|
201
|
-
}
|
|
202
|
-
|
|
203
|
-
const used = new Set<string>();
|
|
204
|
-
for (const expression of [node.test, yes.right, no?.right]) {
|
|
205
|
-
if (expression) traverseFast(expression, child => { if (child.type === "Identifier") used.add(child.name); });
|
|
206
|
-
}
|
|
207
|
-
const captured = [...bindings].filter(([name]) => name !== target && name !== item && used.has(name));
|
|
208
|
-
const parameters = captured.map(([, value]) => `(${value.code} : ${leanTypes[value.sort]})`);
|
|
209
|
-
if (captured.some(([, value]) => value.sort === "items" || value.sort === "textOrItems")) parameters.unshift("{Item : Type}");
|
|
210
|
-
const name = `${code}Loop${loopConformance.length}Conforms`;
|
|
211
|
-
loopConformance.push({ name, definition: `theorem ${[name, ...parameters].join(" ")}
|
|
212
|
-
(values : List Int) (initial : ${leanTypes[accumulator.sort]}) :
|
|
213
|
-
forIn (m := Id) values initial (fun ${itemCode} ${state} =>
|
|
214
|
-
if ${guard} then ForInStep.yield (${updated.code}) else ForInStep.yield (${otherwise.code})) =
|
|
215
|
-
values.foldl (fun ${state} ${itemCode} => ${step}) initial := by
|
|
216
|
-
apply forIn_foldl_of_step_eq
|
|
217
|
-
intro ${itemCode} ${state}
|
|
218
|
-
by_cases h : (${guard}) = true <;> simp only [h, Bool.false_eq_true, if_true, if_false, Int.add_zero, Int.sub_zero]` });
|
|
219
|
-
}
|
|
220
|
-
|
|
221
|
-
function emitArrayGuard(node: Extract<Statement, { type: "IfStatement" }>, bindings: Map<string, Binding>, indent: number, inLoop: boolean) {
|
|
222
|
-
const test = node.test;
|
|
223
|
-
if (test.type !== "CallExpression" || test.callee.type !== "MemberExpression" || test.callee.computed ||
|
|
224
|
-
test.callee.object.type !== "Identifier" || test.callee.object.name !== "Array" ||
|
|
225
|
-
test.callee.property.type !== "Identifier" || test.callee.property.name !== "isArray") return false;
|
|
226
|
-
if (test.typeArguments || test.arguments.length !== 1) invalid(file, test, "Pass one named union value to Array.isArray.");
|
|
227
|
-
const name = nameOf(file, test.arguments[0]);
|
|
228
|
-
const value = bindings.get(name);
|
|
229
|
-
if (value?.sort !== "textOrItems") invalid(file, test, "Array.isArray expects a string-or-record-array binding.");
|
|
230
|
-
arrayGuard = test;
|
|
231
|
-
const narrowed = new Map(bindings), code = fresh();
|
|
232
|
-
narrowed.set(name, { sort: "items", code });
|
|
233
|
-
line(indent, `match ${value.code} with`);
|
|
234
|
-
line(indent, `| some ${code} =>`);
|
|
235
|
-
branch(node.consequent, narrowed, indent + 2, inLoop);
|
|
236
|
-
line(indent, "| none =>");
|
|
237
|
-
if (node.alternate) branch(node.alternate, bindings, indent + 2, inLoop);
|
|
238
|
-
else line(indent + 2, "pure ()");
|
|
239
|
-
return true;
|
|
240
|
-
}
|
|
241
|
-
|
|
242
|
-
function emitWhile(node: Extract<Statement, { type: "WhileStatement" }>, bindings: Map<string, Binding>, indent: number) {
|
|
243
|
-
const { test, body } = node;
|
|
244
|
-
const counter = test.type === "BinaryExpression" && (test.operator === ">" || test.operator === ">=") &&
|
|
245
|
-
test.left.type === "Identifier" ? test.left.name : undefined;
|
|
246
|
-
if (!counter || test.type !== "BinaryExpression" || body.type !== "BlockStatement") {
|
|
247
|
-
invalid(file, node, "Use a braced while loop guarded by a decreasing bigint counter and a literal lower bound.");
|
|
248
|
-
}
|
|
249
|
-
const binding = bindings.get(counter);
|
|
250
|
-
const bound = bigintLiteral(test.right);
|
|
251
|
-
const last = body.body.at(-1);
|
|
252
|
-
const assignment = last?.type === "ExpressionStatement" && last.expression.type === "AssignmentExpression" ? last.expression : undefined;
|
|
253
|
-
const amount = assignment?.operator === "-=" && assignment.left.type === "Identifier" && assignment.left.name === counter
|
|
254
|
-
? bigintLiteral(assignment.right) : undefined;
|
|
255
|
-
if (binding?.sort !== "integer" || !binding.mutable || bound === undefined || amount === undefined || amount <= 0n) {
|
|
256
|
-
invalid(file, node, "A while loop needs a mutable bigint counter and a final counter -= positiveLiteral update.");
|
|
257
|
-
}
|
|
258
|
-
const statements = body.body.slice(0, -1);
|
|
259
|
-
for (const child of statements) traverseFast(child, part => {
|
|
260
|
-
if (part.type === "ReturnStatement" || part.type === "BreakStatement" || part.type === "ContinueStatement") {
|
|
261
|
-
invalid(file, part, "Use a while body that reaches its counter update on every continuing path.");
|
|
262
|
-
}
|
|
263
|
-
});
|
|
264
|
-
countdown = true;
|
|
265
|
-
const limit = test.operator === ">=" ? bound - 1n : bound;
|
|
266
|
-
const state = [...bindings].filter(([name, value]) => name !== counter && value.mutable);
|
|
267
|
-
const stateValues = state.map(([, value]) => value.code);
|
|
268
|
-
const nextCounter = fresh();
|
|
269
|
-
const nextState = state.map(fresh);
|
|
270
|
-
const counterArg = fresh(), stateArg = fresh();
|
|
271
|
-
const loopScope = new Map(bindings);
|
|
272
|
-
loopScope.set(counter, { ...binding, code: counterArg, mutable: false });
|
|
273
|
-
line(indent, `let (${nextCounter}, ${state.length ? tuple(nextState) : "_"}) ← countdownWhile ${binding.code} (${limit} : Int) (${amount} : Int) (by decide)`);
|
|
274
|
-
line(indent + 2, `(fun ${counterArg} ${stateArg} => do`);
|
|
275
|
-
const stateInputs = state.map(fresh);
|
|
276
|
-
if (state.length) line(indent + 4, `let ${tuple(stateInputs)} := ${stateArg}`);
|
|
277
|
-
for (const [index, [name, value]] of state.entries()) {
|
|
278
|
-
const code = fresh();
|
|
279
|
-
line(indent + 4, `let mut ${code} := ${stateInputs[index]}`);
|
|
280
|
-
loopScope.set(name, { ...value, code });
|
|
281
|
-
}
|
|
282
|
-
for (const child of statements) statement(child, loopScope, indent + 4, false);
|
|
283
|
-
line(indent + 4, `return ${tuple(state.map(([name]) => loopScope.get(name)!.code))}) ${tuple(stateValues)}`);
|
|
284
|
-
line(indent, `${binding.code} := ${nextCounter}`);
|
|
285
|
-
for (const [index, original] of stateValues.entries()) line(indent, `${original} := ${nextState[index]}`);
|
|
286
|
-
}
|
|
287
|
-
|
|
288
|
-
function statement(node: Statement, bindings: Map<string, Binding>, indent: number, inLoop: boolean): void {
|
|
289
|
-
switch (node.type) {
|
|
290
|
-
case "EmptyStatement": return;
|
|
291
|
-
case "ReturnStatement": {
|
|
292
|
-
if (!node.argument) invalid(file, node, "Return a value.");
|
|
293
|
-
line(indent, `return ${force(returned(node.argument, bindings), indent)}`);
|
|
294
|
-
return;
|
|
295
|
-
}
|
|
296
|
-
case "ThrowStatement": {
|
|
297
|
-
const value = node.argument;
|
|
298
|
-
if (value.type !== "NewExpression" || value.callee.type !== "Identifier" || value.typeArguments ||
|
|
299
|
-
!Object.hasOwn(errorKinds, value.callee.name) || moduleNames.has(value.callee.name) || localNames.has(value.callee.name) ||
|
|
300
|
-
value.arguments.length > 1 || (value.arguments[0] && value.arguments[0].type !== "StringLiteral")) {
|
|
301
|
-
invalid(file, value, "Throw an unshadowed Error, RangeError, or TypeError with an optional string literal.");
|
|
302
|
-
}
|
|
303
|
-
fallible = true;
|
|
304
|
-
line(indent, `throw ErrorKind.${errorKinds[value.callee.name as keyof typeof errorKinds]}`);
|
|
305
|
-
return;
|
|
306
|
-
}
|
|
307
|
-
case "TryStatement": {
|
|
308
|
-
const [attempt] = node.block.body;
|
|
309
|
-
if (!node.handler || node.handler.param || node.finalizer || node.block.body.length !== 1 || attempt?.type !== "ReturnStatement" || !attempt.argument) {
|
|
310
|
-
invalid(file, node, "Use try { return expression } with an unbound catch and no finally.");
|
|
311
|
-
}
|
|
312
|
-
const value = returned(attempt.argument, bindings);
|
|
313
|
-
const success = fresh();
|
|
314
|
-
line(indent, `match (${asOutcome(value)} : Except ErrorKind (${leanTypes[result]})) with`);
|
|
315
|
-
line(indent, `| .ok ${success} => return ${success}`);
|
|
316
|
-
line(indent, "| .error _ =>");
|
|
317
|
-
branch(node.handler.body, bindings, indent + 2, inLoop);
|
|
318
|
-
return;
|
|
319
|
-
}
|
|
320
|
-
case "BreakStatement":
|
|
321
|
-
case "ContinueStatement": {
|
|
322
|
-
if (!inLoop || node.label) invalid(file, node, "Loop control must be unlabelled and inside a for-of loop.");
|
|
323
|
-
line(indent, node.type === "BreakStatement" ? "break" : "continue");
|
|
324
|
-
return;
|
|
325
|
-
}
|
|
326
|
-
case "VariableDeclaration": {
|
|
327
|
-
if (node.kind !== "const" && node.kind !== "let") invalid(file, node, "Expected a const or let declaration.");
|
|
328
|
-
for (const decl of node.declarations) {
|
|
329
|
-
const name = nameOf(file, decl.id);
|
|
330
|
-
if (!decl.init || bindings.has(name)) invalid(file, decl, "Expected a new, initialized binding.");
|
|
331
|
-
const value = read(decl.init, bindings);
|
|
332
|
-
if (!isScalar(value.sort)) invalid(file, decl, "Keep array and union inputs as named parameters.");
|
|
333
|
-
if (decl.id.type === "Identifier" && decl.id.typeAnnotation) {
|
|
334
|
-
ofSort(file, decl, value, tsSort(file, decl.id.typeAnnotation, decl));
|
|
335
|
-
}
|
|
336
|
-
const code = fresh(), mutable = node.kind === "let";
|
|
337
|
-
const rhs = force(value, indent);
|
|
338
|
-
bindings.set(name, { sort: value.sort, code, mutable });
|
|
339
|
-
line(indent, `let ${mutable ? "mut " : ""}${code} := ${rhs}`);
|
|
340
|
-
}
|
|
341
|
-
return;
|
|
342
|
-
}
|
|
343
|
-
case "ExpressionStatement": {
|
|
344
|
-
if (node.expression.type !== "AssignmentExpression") invalid(file, node, "Expected a local assignment.");
|
|
345
|
-
const { binding, rhs } = assignment(node.expression, bindings);
|
|
346
|
-
line(indent, `${binding.code} := ${force(rhs, indent)}`);
|
|
347
|
-
return;
|
|
348
|
-
}
|
|
349
|
-
case "IfStatement": {
|
|
350
|
-
if (emitArrayGuard(node, bindings, indent, inLoop)) return;
|
|
351
|
-
const value = read(node.test, bindings);
|
|
352
|
-
if (value.sort !== "integer" && value.sort !== "number") ofSort(file, node.test, value, "boolean");
|
|
353
|
-
const test = truthy(value, force(value, indent));
|
|
354
|
-
line(indent, `if ${recursive ? `_${fresh()} : ` : ""}${test} then`);
|
|
355
|
-
branch(node.consequent, bindings, indent + 2, inLoop);
|
|
356
|
-
if (node.alternate) {
|
|
357
|
-
line(indent, "else");
|
|
358
|
-
branch(node.alternate, bindings, indent + 2, inLoop);
|
|
359
|
-
}
|
|
360
|
-
return;
|
|
361
|
-
}
|
|
362
|
-
case "WhileStatement": emitWhile(node, bindings, indent); return;
|
|
363
|
-
case "ForOfStatement": {
|
|
364
|
-
const decl = node.left.type === "VariableDeclaration" && node.left.kind === "const" &&
|
|
365
|
-
node.left.declarations.length === 1 ? node.left.declarations[0] : undefined;
|
|
366
|
-
if (node.await || !decl || decl.init) invalid(file, node, "Expected a synchronous for (const item of values) loop.");
|
|
367
|
-
const iterable = read(node.right, bindings);
|
|
368
|
-
ofSort(file, node.right, iterable, "integers");
|
|
369
|
-
const item = nameOf(file, decl.id), values = force(iterable, indent);
|
|
370
|
-
if (bindings.has(item)) invalid(file, decl, "The loop item must have a new name.");
|
|
371
|
-
const loopScope = new Map(bindings), itemCode = fresh();
|
|
372
|
-
loopScope.set(item, { sort: "integer", code: itemCode });
|
|
373
|
-
const update = localUpdate(node.body);
|
|
374
|
-
if (update?.left.type === "Identifier") {
|
|
375
|
-
const target = update.left.name, accumulator = bindings.get(target);
|
|
376
|
-
if (accumulator?.mutable && accumulator.sort === "integer") {
|
|
377
|
-
const stateCode = fresh();
|
|
378
|
-
const { rhs } = assignment(update, new Map([...loopScope, [target, { ...accumulator, code: stateCode }]]));
|
|
379
|
-
if (!rhs.fallible) {
|
|
380
|
-
fold = true;
|
|
381
|
-
const step = `(fun (${stateCode} ${itemCode} : Int) => ${rhs.code})`;
|
|
382
|
-
line(indent, `${accumulator.code} := List.foldl ${step} ${accumulator.code} ${values}`);
|
|
383
|
-
return;
|
|
384
|
-
}
|
|
385
|
-
}
|
|
386
|
-
}
|
|
387
|
-
line(indent, `for ${itemCode} in ${values} do`);
|
|
388
|
-
branch(node.body, loopScope, indent + 2, true);
|
|
389
|
-
const inner = singleStatement(node.body);
|
|
390
|
-
if (inner.type === "IfStatement") certifyGuardedUpdate(inner, loopScope, item, itemCode);
|
|
391
|
-
return;
|
|
392
|
-
}
|
|
393
|
-
default: invalid(file, node, `Unsupported statement '${node.type}' before the final return.`);
|
|
394
|
-
}
|
|
395
|
-
}
|
|
396
|
-
|
|
397
|
-
function branch(node: Statement, bindings: ReadonlyMap<string, Binding>, indent: number, inLoop: boolean) {
|
|
398
|
-
const inner = new Map(bindings);
|
|
399
|
-
const statements = node.type === "BlockStatement" ? node.body : [node];
|
|
400
|
-
emitStatements(statements, inner, indent, inLoop);
|
|
401
|
-
const last = statements.at(-1);
|
|
402
|
-
if (!exits(last) && last?.type !== "BreakStatement" && last?.type !== "ContinueStatement") line(indent, "pure ()");
|
|
403
|
-
}
|
|
404
|
-
|
|
405
|
-
function emitStatements(statements: readonly Statement[], bindings: Map<string, Binding>, indent: number, inLoop: boolean) {
|
|
406
|
-
for (const [i, node] of statements.entries()) {
|
|
407
|
-
// A guarded early return makes the following code the false branch. Expose
|
|
408
|
-
// that fact explicitly so the termination proof sees the guard.
|
|
409
|
-
if (recursive && node.type === "IfStatement" && !node.alternate && exits(node.consequent) && i < statements.length - 1) {
|
|
410
|
-
statement({ ...node, alternate: { type: "BlockStatement", body: statements.slice(i + 1), directives: [] } },
|
|
411
|
-
bindings, indent, inLoop);
|
|
412
|
-
return;
|
|
413
|
-
}
|
|
414
|
-
statement(node, bindings, indent, inLoop);
|
|
415
|
-
}
|
|
416
|
-
}
|
|
417
|
-
|
|
418
|
-
let body: string;
|
|
419
|
-
if (fn.body.type === "BlockStatement") {
|
|
420
|
-
if (!exits(fn.body)) invalid(file, fn.body, "The final statement must return a value or throw on every path.");
|
|
421
|
-
emitStatements(fn.body.body, scope, 2, false);
|
|
422
|
-
body = `${fallible ? " do" : " Id.run do"}\n${lines.join("\n")}`;
|
|
423
|
-
} else {
|
|
424
|
-
const value = inferred ?? returned(fn.body, scope);
|
|
425
|
-
fallible = !!value.fallible;
|
|
426
|
-
body = `\n ${value.code}`;
|
|
427
|
-
}
|
|
428
|
-
if (arrayGuard && (moduleNames.has("Array") || localNames.has("Array"))) {
|
|
429
|
-
invalid(file, arrayGuard, "Array.isArray requires an unshadowed Array built-in.");
|
|
430
|
-
}
|
|
431
|
-
const resultType = fallible ? `Except ErrorKind (${leanTypes[result]})` : leanTypes[result];
|
|
432
|
-
let termination = "";
|
|
433
|
-
if (recursive) {
|
|
434
|
-
const measure = params.find(param => param.sort === "integer");
|
|
435
|
-
if (!measure || fallible || countdown || itemType) {
|
|
436
|
-
invalid(file, fn, "Direct recursion needs a pure body and a decreasing bigint parameter.");
|
|
437
|
-
}
|
|
438
|
-
termination = `\ntermination_by ${measure.code}.toNat\ndecreasing_by all_goals (simp_wf; try simp_all; omega)`;
|
|
439
|
-
}
|
|
440
|
-
const definition = `def ${[code, ...signature].join(" ")} : ${resultType} :=${body}${termination}`;
|
|
441
|
-
return { file, name: symbol, code, params, result, itemType, definition, fallible, countdown, fold, loopConformance: fallible ? [] : loopConformance, recursive,
|
|
442
|
-
callees: new Set(callTargets.values()), sourceExpression: scalarSource(fn.body, params, result, callTargets) };
|
|
443
|
-
}
|