eutaxy 0.5.1 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +96 -12
- package/dist/aws.mjs +5 -5
- package/dist/bin.mjs +2 -2
- package/dist/{checksum-DhS6ofSm.mjs → checksum-DHr5qb3Y.mjs} +2 -2
- package/dist/{checksum-DhS6ofSm.mjs.map → checksum-DHr5qb3Y.mjs.map} +1 -1
- package/dist/cli-CsiVEsS-.mjs +2 -0
- package/dist/cli.d.mts.map +1 -1
- package/dist/cli.mjs +2 -2
- package/dist/cloudflare.d.mts +2 -4
- package/dist/cloudflare.d.mts.map +1 -1
- package/dist/cloudflare.mjs +2 -2
- package/dist/{delivery-invariants-Cuxdna28.mjs → delivery-invariants-hmhwh_qD.mjs} +2 -2
- package/dist/{delivery-invariants-Cuxdna28.mjs.map → delivery-invariants-hmhwh_qD.mjs.map} +1 -1
- package/dist/{event-streams-BANyO9xt.mjs → event-streams-i8OGzuFN.mjs} +2 -2
- package/dist/{event-streams-BANyO9xt.mjs.map → event-streams-i8OGzuFN.mjs.map} +1 -1
- package/dist/{checked-CGpA2-F0.d.mts → explore-CDpJA9zX.d.mts} +118 -61
- package/dist/explore-CDpJA9zX.d.mts.map +1 -0
- package/dist/index.d.mts +76 -20
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +19 -20
- package/dist/index.mjs.map +1 -1
- package/dist/{src-Bqc9Eyb1.mjs → src-BO7I3f-1.mjs} +2 -2
- package/dist/{src-Bqc9Eyb1.mjs.map → src-BO7I3f-1.mjs.map} +1 -1
- package/dist/{src-DKb-fkdb.mjs → src-C43iUZgr.mjs} +1650 -10
- package/dist/src-C43iUZgr.mjs.map +1 -0
- package/dist/{src-Dxl9ZlKn.mjs → src-Cs4Mg55e.mjs} +957 -37
- package/dist/src-Cs4Mg55e.mjs.map +1 -0
- package/package.json +16 -1
- package/dist/checked-CGpA2-F0.d.mts.map +0 -1
- package/dist/cli-IJrKkeYS.mjs +0 -2
- package/dist/src-DKb-fkdb.mjs.map +0 -1
- package/dist/src-Dxl9ZlKn.mjs.map +0 -1
|
@@ -1,10 +1,11 @@
|
|
|
1
|
-
import { a as
|
|
2
|
-
import {
|
|
3
|
-
import { n as
|
|
1
|
+
import { E as canonicalJson, T as getPath, _ as defaultBounds, a as explore, c as CrashSignal, d as withoutNetwork, f as patchGlobals, g as toJson, i as proxiedSide, l as InjectedEffectError, m as settleOn, n as DifferentialStuck, r as compareSides, t as observeCore, u as installScriptedFetch, v as validateScenario } from "./src-BO7I3f-1.mjs";
|
|
2
|
+
import { n as atLeastOncePerMessage$1 } from "./delivery-invariants-hmhwh_qD.mjs";
|
|
3
|
+
import { _ as TokenizeError, a as emitRegressionTest, b as describeVerdict, d as lemmaBool, f as lemmaUnresolved, m as extractSpecs, n as renderSpecs, o as aggregate, p as predicateSource, r as renderText, s as checkSpecModule, t as renderJson, v as templateSubstitutions, y as tokenize } from "./src-Cs4Mg55e.mjs";
|
|
4
4
|
import { createRequire } from "node:module";
|
|
5
5
|
import { spawn } from "node:child_process";
|
|
6
|
-
import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
|
|
6
|
+
import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
|
|
7
7
|
import { basename, dirname, join, relative, resolve } from "node:path";
|
|
8
|
+
import { homedir, tmpdir } from "node:os";
|
|
8
9
|
// packages/cli/src/args.ts
|
|
9
10
|
function parseArgs(argv, booleans = []) {
|
|
10
11
|
const positionals = [];
|
|
@@ -33,6 +34,1599 @@ function parseArgs(argv, booleans = []) {
|
|
|
33
34
|
flags
|
|
34
35
|
};
|
|
35
36
|
}
|
|
37
|
+
// packages/prover-lean/src/subset.ts
|
|
38
|
+
/**
|
|
39
|
+
* The pure TypeScript subset the first-party engine accepts, read into a
|
|
40
|
+
* small tree: exported functions over `number` (as unbounded integers),
|
|
41
|
+
* `boolean` and `string`, returning those or a record type declared in the
|
|
42
|
+
* same module;
|
|
43
|
+
* bodies made of `const` bindings, `if` with early returns, `return`, and
|
|
44
|
+
* expressions from integer arithmetic (`+ - *`), comparisons, `&& || !`,
|
|
45
|
+
* the conditional operator, record literals and field reads, and calls to
|
|
46
|
+
* the module's own functions. Anything else is `OutsideSubset`, with the
|
|
47
|
+
* construct named: the subset is specified by the contract corpus and
|
|
48
|
+
* widens one characterised class at a time.
|
|
49
|
+
*/
|
|
50
|
+
var OutsideSubset = class extends Error {
|
|
51
|
+
line;
|
|
52
|
+
constructor(message, line) {
|
|
53
|
+
super(message);
|
|
54
|
+
this.line = line;
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
/** Binary operators by precedence, loosest first; all left-associative here. */
|
|
58
|
+
const levels = [
|
|
59
|
+
["||"],
|
|
60
|
+
["&&"],
|
|
61
|
+
["===", "!=="],
|
|
62
|
+
[
|
|
63
|
+
"<",
|
|
64
|
+
"<=",
|
|
65
|
+
">",
|
|
66
|
+
">="
|
|
67
|
+
],
|
|
68
|
+
["+", "-"],
|
|
69
|
+
["*"]
|
|
70
|
+
];
|
|
71
|
+
var Reader = class {
|
|
72
|
+
at = 0;
|
|
73
|
+
tokens;
|
|
74
|
+
lineOf;
|
|
75
|
+
constructor(tokens, lineOf) {
|
|
76
|
+
this.tokens = tokens;
|
|
77
|
+
this.lineOf = lineOf;
|
|
78
|
+
}
|
|
79
|
+
peek(n = 0) {
|
|
80
|
+
return this.tokens[this.at + n];
|
|
81
|
+
}
|
|
82
|
+
line(t = this.peek()) {
|
|
83
|
+
return t ? this.lineOf(t.start) : this.lineOf(this.tokens.at(-1)?.end ?? 0);
|
|
84
|
+
}
|
|
85
|
+
fail(what, t = this.peek()) {
|
|
86
|
+
throw new OutsideSubset(what, this.line(t));
|
|
87
|
+
}
|
|
88
|
+
isPunct(text, n = 0) {
|
|
89
|
+
const t = this.peek(n);
|
|
90
|
+
return t?.kind === "punct" && t.text === text;
|
|
91
|
+
}
|
|
92
|
+
isWord(text, n = 0) {
|
|
93
|
+
const t = this.peek(n);
|
|
94
|
+
return t?.kind === "ident" && t.text === text;
|
|
95
|
+
}
|
|
96
|
+
take() {
|
|
97
|
+
const t = this.peek();
|
|
98
|
+
if (!t) this.fail("the module ends early");
|
|
99
|
+
this.at++;
|
|
100
|
+
return t;
|
|
101
|
+
}
|
|
102
|
+
expectPunct(text) {
|
|
103
|
+
if (!this.isPunct(text)) this.fail(`expected ${text}, found ${this.peek()?.text ?? "the end"}`);
|
|
104
|
+
this.at++;
|
|
105
|
+
}
|
|
106
|
+
ident() {
|
|
107
|
+
const t = this.peek();
|
|
108
|
+
if (t?.kind !== "ident") this.fail(`expected a name, found ${t?.text ?? "the end"}`);
|
|
109
|
+
this.at++;
|
|
110
|
+
return t.text;
|
|
111
|
+
}
|
|
112
|
+
};
|
|
113
|
+
/** Whether a string holds a surrogate code unit without its pair: no Lean character corresponds to it. */
|
|
114
|
+
function hasLoneSurrogate(s) {
|
|
115
|
+
return /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/.test(s);
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* The value of a string literal token. Simple escapes and `\xHH`, `\uHHHH`,
|
|
119
|
+
* `\u{H…}` are decoded; a line continuation, an octal escape or a lone
|
|
120
|
+
* surrogate (which Lean's strings cannot hold) is outside the subset.
|
|
121
|
+
*/
|
|
122
|
+
function stringLiteralValue(text, r, t) {
|
|
123
|
+
const body = text.slice(1, -1);
|
|
124
|
+
let out = "";
|
|
125
|
+
for (let i = 0; i < body.length; i++) {
|
|
126
|
+
const c = body[i];
|
|
127
|
+
if (c !== "\\") {
|
|
128
|
+
out += c;
|
|
129
|
+
continue;
|
|
130
|
+
}
|
|
131
|
+
const e = body[++i];
|
|
132
|
+
const simple = {
|
|
133
|
+
n: "\n",
|
|
134
|
+
t: " ",
|
|
135
|
+
r: "\r",
|
|
136
|
+
b: "\b",
|
|
137
|
+
f: "\f",
|
|
138
|
+
v: "\v",
|
|
139
|
+
"0": "\0",
|
|
140
|
+
"\\": "\\",
|
|
141
|
+
"\"": "\"",
|
|
142
|
+
"'": "'"
|
|
143
|
+
};
|
|
144
|
+
if (e !== void 0 && e in simple && !(e === "0" && /[0-9]/.test(body[i + 1] ?? ""))) {
|
|
145
|
+
out += simple[e];
|
|
146
|
+
continue;
|
|
147
|
+
}
|
|
148
|
+
if (e === "x" && /^[0-9a-fA-F]{2}$/.test(body.slice(i + 1, i + 3))) {
|
|
149
|
+
out += String.fromCharCode(Number.parseInt(body.slice(i + 1, i + 3), 16));
|
|
150
|
+
i += 2;
|
|
151
|
+
continue;
|
|
152
|
+
}
|
|
153
|
+
if (e === "u") {
|
|
154
|
+
const m = /^\{([0-9a-fA-F]{1,6})\}|^([0-9a-fA-F]{4})/.exec(body.slice(i + 1));
|
|
155
|
+
if (m) {
|
|
156
|
+
const code = Number.parseInt(m[1] ?? m[2], 16);
|
|
157
|
+
if (code > 1114111) r.fail(`a code point escape beyond U+10FFFF in a string literal`, t);
|
|
158
|
+
out += String.fromCodePoint(code);
|
|
159
|
+
i += m[0].length;
|
|
160
|
+
continue;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
r.fail(`an escape sequence \\${e ?? ""} in a string literal`, t);
|
|
164
|
+
}
|
|
165
|
+
if (hasLoneSurrogate(out)) r.fail("a string literal with a lone surrogate, which Lean's strings cannot hold", t);
|
|
166
|
+
return out;
|
|
167
|
+
}
|
|
168
|
+
function typeAnnotation(r, records, bad = /* @__PURE__ */ new Map()) {
|
|
169
|
+
const t = r.take();
|
|
170
|
+
if (t.kind === "string") {
|
|
171
|
+
while (r.isPunct("|")) {
|
|
172
|
+
r.at++;
|
|
173
|
+
const next = r.take();
|
|
174
|
+
if (next.kind !== "string") r.fail(`a union mixing string literals with ${next.text} (only string literals are read, as string)`, next);
|
|
175
|
+
}
|
|
176
|
+
return { kind: "string" };
|
|
177
|
+
}
|
|
178
|
+
if (t.kind !== "ident") r.fail(`a type that is not a name: ${t.text}`, t);
|
|
179
|
+
const why = bad.get(t.text);
|
|
180
|
+
if (why !== void 0) r.fail(`record type ${t.text} is outside the subset: ${why}`, t);
|
|
181
|
+
if (r.isPunct("[") || r.isPunct("<") || r.isPunct("|") || r.isPunct("&")) r.fail(`type ${t.text}${r.peek()?.text}… (arrays, generics, unions and intersections are outside the subset)`, t);
|
|
182
|
+
if (t.text === "number") return { kind: "int" };
|
|
183
|
+
if (t.text === "boolean") return { kind: "bool" };
|
|
184
|
+
if (t.text === "string") return { kind: "string" };
|
|
185
|
+
if (records.has(t.text)) return {
|
|
186
|
+
kind: "record",
|
|
187
|
+
name: t.text
|
|
188
|
+
};
|
|
189
|
+
r.fail(`type ${t.text} (the subset has number, boolean, string and the module's own record types)`, t);
|
|
190
|
+
}
|
|
191
|
+
/** Names a Lean structure declaration generates itself, which a field cannot take. */
|
|
192
|
+
const structureNames = /* @__PURE__ */ new Set([
|
|
193
|
+
"mk",
|
|
194
|
+
"rec",
|
|
195
|
+
"recOn",
|
|
196
|
+
"casesOn",
|
|
197
|
+
"noConfusion",
|
|
198
|
+
"noConfusionType",
|
|
199
|
+
"injEq"
|
|
200
|
+
]);
|
|
201
|
+
/** `interface Name { a: T; b: U }` or `type Name = { ... }` at the reader, after any `export`. */
|
|
202
|
+
function recordAt(r, records) {
|
|
203
|
+
const start = r.at;
|
|
204
|
+
if (r.isWord("export")) r.at++;
|
|
205
|
+
const alias = r.isWord("type");
|
|
206
|
+
if (!r.isWord("interface") && !alias) {
|
|
207
|
+
r.at = start;
|
|
208
|
+
return;
|
|
209
|
+
}
|
|
210
|
+
r.at++;
|
|
211
|
+
const name = r.ident();
|
|
212
|
+
if (alias) r.expectPunct("=");
|
|
213
|
+
if (r.isWord("extends")) r.fail("interface inheritance", r.peek());
|
|
214
|
+
r.expectPunct("{");
|
|
215
|
+
const fields = [];
|
|
216
|
+
while (!r.isPunct("}")) {
|
|
217
|
+
if (r.isWord("readonly")) r.at++;
|
|
218
|
+
const fname = r.ident();
|
|
219
|
+
if (r.isPunct("?")) r.fail(`optional field ${fname}`);
|
|
220
|
+
if (structureNames.has(fname)) r.fail(`field ${fname} takes a name Lean's structures reserve`);
|
|
221
|
+
if (fname === "__proto__") r.fail("a field named __proto__, which JavaScript treats specially");
|
|
222
|
+
r.expectPunct(":");
|
|
223
|
+
fields.push({
|
|
224
|
+
name: fname,
|
|
225
|
+
type: typeAnnotation(r, records)
|
|
226
|
+
});
|
|
227
|
+
if (r.isPunct(";") || r.isPunct(",")) r.at++;
|
|
228
|
+
}
|
|
229
|
+
r.expectPunct("}");
|
|
230
|
+
if (r.isPunct(";")) r.at++;
|
|
231
|
+
return {
|
|
232
|
+
name,
|
|
233
|
+
fields
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
/** Skip a balanced bracket group starting at the reader. */
|
|
237
|
+
function skipGroup(r) {
|
|
238
|
+
const open = r.take();
|
|
239
|
+
const close = {
|
|
240
|
+
"(": ")",
|
|
241
|
+
"[": "]",
|
|
242
|
+
"{": "}"
|
|
243
|
+
}[open.text];
|
|
244
|
+
let depth = 1;
|
|
245
|
+
while (depth > 0) {
|
|
246
|
+
const t = r.take();
|
|
247
|
+
if (t.kind !== "punct") continue;
|
|
248
|
+
if (t.text === open.text) depth++;
|
|
249
|
+
else if (t.text === close) depth--;
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
/**
|
|
253
|
+
* Whether the `function` token at `i` starts a declaration: at the start of
|
|
254
|
+
* the module or after a statement end, with `export` and `async` allowed in
|
|
255
|
+
* front. A `function` after `=`, `(`, `,`, `return` or `:` is an
|
|
256
|
+
* expression, whose name is its own, not the module's.
|
|
257
|
+
*/
|
|
258
|
+
function isDeclaration(tokens, i, lineOf) {
|
|
259
|
+
let k = i - 1;
|
|
260
|
+
while (tokens[k]?.kind === "ident" && [
|
|
261
|
+
"async",
|
|
262
|
+
"export",
|
|
263
|
+
"default"
|
|
264
|
+
].includes(tokens[k]?.text ?? "")) k--;
|
|
265
|
+
const before = tokens[k];
|
|
266
|
+
if (before === void 0) return true;
|
|
267
|
+
if (before.kind === "punct" && (before.text === ";" || before.text === "}")) return true;
|
|
268
|
+
if (lineOf(before.end) === lineOf(tokens[i]?.start ?? 0)) return false;
|
|
269
|
+
if (before.kind === "punct") return [
|
|
270
|
+
")",
|
|
271
|
+
"]",
|
|
272
|
+
"++",
|
|
273
|
+
"--"
|
|
274
|
+
].includes(before.text);
|
|
275
|
+
if (before.kind === "ident") return !"return typeof void new else case in of do yield await delete instanceof throw export default async".split(" ").includes(before.text);
|
|
276
|
+
return true;
|
|
277
|
+
}
|
|
278
|
+
/**
|
|
279
|
+
* Names used as values anywhere in the token stream, with the line of the
|
|
280
|
+
* first use: a bare identifier that is not being called (`f(`), not a
|
|
281
|
+
* property (`o.f`), not an object key (`{ f: … }`) and not the name in its
|
|
282
|
+
* own declaration (`function f`, `const f`). A function used that way may
|
|
283
|
+
* be reassigned, wrapped, aliased or passed on, so what runs under its name
|
|
284
|
+
* is not what its declaration says; one rule covers every assignment form
|
|
285
|
+
* (`f = …`, `f! = …`, `f as T = …`, `[f] = …`, `for (f of …)`) and the
|
|
286
|
+
* aliases besides. Template substitutions are code too and are scanned.
|
|
287
|
+
*/
|
|
288
|
+
function valueUses(tokens, lineOf) {
|
|
289
|
+
const out = /* @__PURE__ */ new Map();
|
|
290
|
+
const isPunct = (t, text) => t?.kind === "punct" && t.text === text;
|
|
291
|
+
tokens.forEach((t, i) => {
|
|
292
|
+
if (t.kind === "template") {
|
|
293
|
+
for (const sub of templateSubstitutions(t.text)) for (const [name, line] of valueUses(tokenize(sub), () => lineOf(t.start))) if (!out.has(name)) out.set(name, line);
|
|
294
|
+
return;
|
|
295
|
+
}
|
|
296
|
+
if (t.kind !== "ident") return;
|
|
297
|
+
const before = tokens[i - 1];
|
|
298
|
+
const after = tokens[i + 1];
|
|
299
|
+
if (isPunct(after, "(")) return;
|
|
300
|
+
if (isPunct(before, ".") || isPunct(before, "?.")) return;
|
|
301
|
+
if (isPunct(after, ":") && (isPunct(before, "{") || isPunct(before, ","))) return;
|
|
302
|
+
if (before?.kind === "ident" && [
|
|
303
|
+
"function",
|
|
304
|
+
"const",
|
|
305
|
+
"let",
|
|
306
|
+
"var"
|
|
307
|
+
].includes(before.text)) return;
|
|
308
|
+
if (!out.has(t.text)) out.set(t.text, lineOf(t.start));
|
|
309
|
+
});
|
|
310
|
+
return out;
|
|
311
|
+
}
|
|
312
|
+
/** The line of the first token matching, template substitutions included (recursively). */
|
|
313
|
+
function firstLine(tokens, lineOf, matches) {
|
|
314
|
+
for (let i = 0; i < tokens.length; i++) {
|
|
315
|
+
const t = tokens[i];
|
|
316
|
+
if (t.kind === "template") {
|
|
317
|
+
for (const sub of templateSubstitutions(t.text)) {
|
|
318
|
+
let inner;
|
|
319
|
+
try {
|
|
320
|
+
inner = tokenize(sub);
|
|
321
|
+
} catch (err) {
|
|
322
|
+
if (!(err instanceof TokenizeError)) throw err;
|
|
323
|
+
return lineOf(t.start);
|
|
324
|
+
}
|
|
325
|
+
if (firstLine(inner, () => lineOf(t.start), matches) !== void 0) return lineOf(t.start);
|
|
326
|
+
}
|
|
327
|
+
continue;
|
|
328
|
+
}
|
|
329
|
+
if (matches(t, tokens[i - 1])) return lineOf(t.start);
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
/** The line of the first `eval` that is not a property of something else, template substitutions included. */
|
|
333
|
+
function mentionsEval(tokens, lineOf) {
|
|
334
|
+
return firstLine(tokens, lineOf, (t, before) => t.kind === "ident" && t.text === "eval" && !(before?.kind === "punct" && (before.text === "." || before.text === "?.")));
|
|
335
|
+
}
|
|
336
|
+
/** Words that start a declaration at module level, where a declaration the reader skips must stop. */
|
|
337
|
+
const declarationStarts = new Set("export import function interface type const let var class enum declare async".split(" "));
|
|
338
|
+
/** Skip the rest of a declaration the subset does not take: to its `;`, or to the next declaration. */
|
|
339
|
+
function skipDeclaration(r) {
|
|
340
|
+
while (r.at < r.tokens.length) {
|
|
341
|
+
const t = r.peek();
|
|
342
|
+
if (t.kind === "punct" && t.text === ";") {
|
|
343
|
+
r.at++;
|
|
344
|
+
return;
|
|
345
|
+
}
|
|
346
|
+
if (t.kind === "punct" && [
|
|
347
|
+
"(",
|
|
348
|
+
"[",
|
|
349
|
+
"{"
|
|
350
|
+
].includes(t.text)) {
|
|
351
|
+
skipGroup(r);
|
|
352
|
+
continue;
|
|
353
|
+
}
|
|
354
|
+
if (t.kind === "ident" && declarationStarts.has(t.text)) return;
|
|
355
|
+
r.at++;
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
var FunctionParser = class {
|
|
359
|
+
r;
|
|
360
|
+
records;
|
|
361
|
+
functions;
|
|
362
|
+
/** Every function the module declares, in the subset or not, for messages. */
|
|
363
|
+
declared;
|
|
364
|
+
badRecords;
|
|
365
|
+
signatures = /* @__PURE__ */ new Map();
|
|
366
|
+
constructor(r, records, functions, badRecords = /* @__PURE__ */ new Map(), declared = functions) {
|
|
367
|
+
this.r = r;
|
|
368
|
+
this.records = records;
|
|
369
|
+
this.functions = functions;
|
|
370
|
+
this.badRecords = badRecords;
|
|
371
|
+
this.declared = declared;
|
|
372
|
+
}
|
|
373
|
+
/** `export function name(params): Type` at the reader, up to and including the body's `{`. */
|
|
374
|
+
signature() {
|
|
375
|
+
const r = this.r;
|
|
376
|
+
const line = r.line();
|
|
377
|
+
if (r.isWord("export")) r.at++;
|
|
378
|
+
if (r.isWord("async")) r.fail("an async function (core functions are synchronous)");
|
|
379
|
+
if (!r.isWord("function")) r.fail(`a declaration that is not a function: ${r.peek()?.text}`);
|
|
380
|
+
r.at++;
|
|
381
|
+
if (r.isPunct("*")) r.fail("a generator function");
|
|
382
|
+
const name = r.ident();
|
|
383
|
+
if (r.isPunct("<")) r.fail("type parameters");
|
|
384
|
+
const offset = r.peek()?.start ?? -1;
|
|
385
|
+
r.expectPunct("(");
|
|
386
|
+
const params = [];
|
|
387
|
+
while (!r.isPunct(")")) {
|
|
388
|
+
if (r.isPunct("{") || r.isPunct("[")) r.fail("a destructured parameter");
|
|
389
|
+
if (r.isPunct("...")) r.fail("a rest parameter");
|
|
390
|
+
const pname = r.ident();
|
|
391
|
+
if (pname === "this") r.fail("a this parameter (the receiver is not modelled)");
|
|
392
|
+
if (r.isPunct("?")) r.fail(`optional parameter ${pname}`);
|
|
393
|
+
if (!r.isPunct(":")) r.fail(`parameter ${pname} without a type`);
|
|
394
|
+
r.at++;
|
|
395
|
+
const type = typeAnnotation(r, new Set(this.records.keys()), this.badRecords);
|
|
396
|
+
if (r.isPunct("=")) r.fail(`a default value for ${pname}`);
|
|
397
|
+
params.push({
|
|
398
|
+
name: pname,
|
|
399
|
+
type
|
|
400
|
+
});
|
|
401
|
+
if (r.isPunct(",")) r.at++;
|
|
402
|
+
}
|
|
403
|
+
r.expectPunct(")");
|
|
404
|
+
if (!r.isPunct(":")) r.fail(`${name} without a return type (the subset needs it to name the record returned)`);
|
|
405
|
+
r.at++;
|
|
406
|
+
const returns = typeAnnotation(r, new Set(this.records.keys()), this.badRecords);
|
|
407
|
+
r.expectPunct("{");
|
|
408
|
+
return {
|
|
409
|
+
name,
|
|
410
|
+
params,
|
|
411
|
+
returns,
|
|
412
|
+
line,
|
|
413
|
+
offset,
|
|
414
|
+
body: r.at
|
|
415
|
+
};
|
|
416
|
+
}
|
|
417
|
+
/** The function, its body read from where the signature stopped. */
|
|
418
|
+
declaration(sig) {
|
|
419
|
+
this.r.at = sig.body;
|
|
420
|
+
const scope = new Map(sig.params.map((p) => [p.name, p.type]));
|
|
421
|
+
const body = this.block(scope, sig.returns);
|
|
422
|
+
const actual = this.typeOfExpr(body, scope);
|
|
423
|
+
if (JSON.stringify(actual) !== JSON.stringify(sig.returns)) this.r.fail(`${sig.name} returns a ${actual.kind === "record" ? actual.name : actual.kind} but declares ${sig.returns.kind === "record" ? sig.returns.name : sig.returns.kind}`);
|
|
424
|
+
return {
|
|
425
|
+
name: sig.name,
|
|
426
|
+
params: sig.params,
|
|
427
|
+
returns: sig.returns,
|
|
428
|
+
body,
|
|
429
|
+
line: sig.line,
|
|
430
|
+
offset: sig.offset
|
|
431
|
+
};
|
|
432
|
+
}
|
|
433
|
+
/**
|
|
434
|
+
* The statements up to the closing `}` as one expression: `const` becomes
|
|
435
|
+
* `let`, `if (c) return a; rest` becomes a conditional, and the last
|
|
436
|
+
* statement must return. Every path ends in a `return`.
|
|
437
|
+
*/
|
|
438
|
+
block(scope, returns) {
|
|
439
|
+
const r = this.r;
|
|
440
|
+
if (r.isWord("const")) {
|
|
441
|
+
r.at++;
|
|
442
|
+
const name = r.ident();
|
|
443
|
+
if (this.declared.has(name)) r.fail(`const ${name} shadows the module's function ${name} in its block`);
|
|
444
|
+
if (scope.has(name)) r.fail(`const ${name} redeclares a name already bound here`);
|
|
445
|
+
let annotated;
|
|
446
|
+
if (r.isPunct(":")) {
|
|
447
|
+
r.at++;
|
|
448
|
+
annotated = typeAnnotation(r, new Set(this.records.keys()), this.badRecords);
|
|
449
|
+
}
|
|
450
|
+
r.expectPunct("=");
|
|
451
|
+
const value = this.expression(scope);
|
|
452
|
+
if (r.isPunct(";")) r.at++;
|
|
453
|
+
const inner = new Map(scope);
|
|
454
|
+
const inferred = this.typeOfExpr(value, scope);
|
|
455
|
+
if (annotated && JSON.stringify(annotated) !== JSON.stringify(inferred)) r.fail(`const ${name} is annotated ${describe(annotated)} but holds a ${describe(inferred)}`);
|
|
456
|
+
inner.set(name, inferred);
|
|
457
|
+
return {
|
|
458
|
+
kind: "let",
|
|
459
|
+
name,
|
|
460
|
+
value,
|
|
461
|
+
body: this.block(inner, returns)
|
|
462
|
+
};
|
|
463
|
+
}
|
|
464
|
+
if (r.isWord("if")) {
|
|
465
|
+
r.at++;
|
|
466
|
+
r.expectPunct("(");
|
|
467
|
+
const test = this.expression(scope);
|
|
468
|
+
r.expectPunct(")");
|
|
469
|
+
const then = this.branch(scope, returns);
|
|
470
|
+
let otherwise;
|
|
471
|
+
if (r.isWord("else")) {
|
|
472
|
+
r.at++;
|
|
473
|
+
otherwise = this.branch(scope, returns);
|
|
474
|
+
if (!r.isPunct("}")) r.fail("statements after an if/else that both return");
|
|
475
|
+
r.at++;
|
|
476
|
+
} else otherwise = this.block(scope, returns);
|
|
477
|
+
return {
|
|
478
|
+
kind: "cond",
|
|
479
|
+
test,
|
|
480
|
+
ifTrue: then,
|
|
481
|
+
ifFalse: otherwise
|
|
482
|
+
};
|
|
483
|
+
}
|
|
484
|
+
if (r.isWord("return")) {
|
|
485
|
+
const value = this.returned(scope);
|
|
486
|
+
if (!r.isPunct("}")) r.fail("statements after a return");
|
|
487
|
+
r.at++;
|
|
488
|
+
return value;
|
|
489
|
+
}
|
|
490
|
+
if (r.isWord("let") || r.isWord("var")) r.fail("a mutable binding (use const)");
|
|
491
|
+
if (r.isWord("for") || r.isWord("while") || r.isWord("do")) r.fail("a loop");
|
|
492
|
+
if (r.isWord("throw")) r.fail("throw");
|
|
493
|
+
if (r.isWord("switch")) r.fail("switch");
|
|
494
|
+
if (r.isWord("try")) r.fail("try");
|
|
495
|
+
if (r.isPunct("}")) r.fail("a path that does not return");
|
|
496
|
+
r.fail(`statement starting with ${r.peek()?.text}`);
|
|
497
|
+
}
|
|
498
|
+
/** An `if` branch: `return e;` or `{ ...statements ending in return }`. */
|
|
499
|
+
branch(scope, returns) {
|
|
500
|
+
const r = this.r;
|
|
501
|
+
if (r.isPunct("{")) {
|
|
502
|
+
r.at++;
|
|
503
|
+
return this.block(scope, returns);
|
|
504
|
+
}
|
|
505
|
+
if (!r.isWord("return")) r.fail("an if branch that does not return");
|
|
506
|
+
return this.returned(scope);
|
|
507
|
+
}
|
|
508
|
+
/** `return e;` at the reader. A line break after `return` makes JavaScript return undefined, so it is refused. */
|
|
509
|
+
returned(scope) {
|
|
510
|
+
const r = this.r;
|
|
511
|
+
const keyword = r.take();
|
|
512
|
+
if (r.isPunct(";") || r.isPunct("}")) r.fail("a return without a value", keyword);
|
|
513
|
+
if (r.line() !== r.line(keyword)) r.fail("a line break after return (JavaScript inserts a semicolon and returns undefined)", keyword);
|
|
514
|
+
const value = this.expression(scope);
|
|
515
|
+
if (r.isPunct(";")) r.at++;
|
|
516
|
+
return value;
|
|
517
|
+
}
|
|
518
|
+
expression(scope) {
|
|
519
|
+
const r = this.r;
|
|
520
|
+
const left = this.binary(scope, 0);
|
|
521
|
+
if (r.isPunct("?")) {
|
|
522
|
+
r.at++;
|
|
523
|
+
const then = this.expression(scope);
|
|
524
|
+
r.expectPunct(":");
|
|
525
|
+
return {
|
|
526
|
+
kind: "cond",
|
|
527
|
+
test: left,
|
|
528
|
+
ifTrue: then,
|
|
529
|
+
ifFalse: this.expression(scope)
|
|
530
|
+
};
|
|
531
|
+
}
|
|
532
|
+
return left;
|
|
533
|
+
}
|
|
534
|
+
binary(scope, level) {
|
|
535
|
+
if (level >= levels.length) return this.unary(scope);
|
|
536
|
+
let left = this.binary(scope, level + 1);
|
|
537
|
+
const ops = levels[level];
|
|
538
|
+
for (;;) {
|
|
539
|
+
const t = this.r.peek();
|
|
540
|
+
if (t?.kind !== "punct" || !ops.includes(t.text)) {
|
|
541
|
+
if (t?.kind === "punct" && [
|
|
542
|
+
"==",
|
|
543
|
+
"!=",
|
|
544
|
+
"/",
|
|
545
|
+
"%",
|
|
546
|
+
"**",
|
|
547
|
+
"??",
|
|
548
|
+
"<<",
|
|
549
|
+
">>",
|
|
550
|
+
"&",
|
|
551
|
+
"|",
|
|
552
|
+
"^"
|
|
553
|
+
].includes(t.text)) this.r.fail(`the ${t.text} operator`, t);
|
|
554
|
+
return left;
|
|
555
|
+
}
|
|
556
|
+
this.r.at++;
|
|
557
|
+
const right = this.binary(scope, level + 1);
|
|
558
|
+
left = {
|
|
559
|
+
kind: "binary",
|
|
560
|
+
op: t.text,
|
|
561
|
+
left,
|
|
562
|
+
right
|
|
563
|
+
};
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
unary(scope) {
|
|
567
|
+
const r = this.r;
|
|
568
|
+
if (r.isPunct("!")) {
|
|
569
|
+
r.at++;
|
|
570
|
+
return {
|
|
571
|
+
kind: "not",
|
|
572
|
+
operand: this.unary(scope)
|
|
573
|
+
};
|
|
574
|
+
}
|
|
575
|
+
if (r.isPunct("-")) {
|
|
576
|
+
r.at++;
|
|
577
|
+
const operand = this.unary(scope);
|
|
578
|
+
return operand.kind === "int" ? {
|
|
579
|
+
kind: "int",
|
|
580
|
+
value: operand.value.startsWith("-") ? operand.value.slice(1) : `-${operand.value}`
|
|
581
|
+
} : {
|
|
582
|
+
kind: "neg",
|
|
583
|
+
operand
|
|
584
|
+
};
|
|
585
|
+
}
|
|
586
|
+
if (r.isPunct("+")) r.fail("unary plus");
|
|
587
|
+
if (r.isWord("typeof") || r.isWord("void") || r.isWord("await") || r.isWord("new")) r.fail(`the ${r.peek()?.text} operator`);
|
|
588
|
+
return this.postfix(scope, this.primary(scope));
|
|
589
|
+
}
|
|
590
|
+
postfix(scope, base) {
|
|
591
|
+
const r = this.r;
|
|
592
|
+
let e = base;
|
|
593
|
+
for (;;) {
|
|
594
|
+
if (r.isPunct(".")) {
|
|
595
|
+
r.at++;
|
|
596
|
+
const field = r.ident();
|
|
597
|
+
e = {
|
|
598
|
+
kind: "field",
|
|
599
|
+
object: e,
|
|
600
|
+
field
|
|
601
|
+
};
|
|
602
|
+
continue;
|
|
603
|
+
}
|
|
604
|
+
if (r.isPunct("?.")) r.fail("optional chaining");
|
|
605
|
+
if (r.isPunct("[")) r.fail("index access");
|
|
606
|
+
if (r.isPunct("(")) {
|
|
607
|
+
if (e.kind === "var" && scope.has(e.name)) r.fail(`a call to ${e.name}, which names a value here, not the module's function`);
|
|
608
|
+
if (e.kind !== "var" || !this.functions.has(e.name)) r.fail(e.kind !== "var" ? "a call to a computed callee" : this.declared.has(e.name) ? `a call to ${e.name}, which is outside the subset` : `a call to ${e.name}, which this module does not declare`);
|
|
609
|
+
r.at++;
|
|
610
|
+
const args = [];
|
|
611
|
+
while (!r.isPunct(")")) {
|
|
612
|
+
args.push(this.expression(scope));
|
|
613
|
+
if (r.isPunct(",")) r.at++;
|
|
614
|
+
}
|
|
615
|
+
r.at++;
|
|
616
|
+
e = {
|
|
617
|
+
kind: "call",
|
|
618
|
+
callee: e.name,
|
|
619
|
+
args
|
|
620
|
+
};
|
|
621
|
+
continue;
|
|
622
|
+
}
|
|
623
|
+
if (r.isWord("as") || r.isWord("satisfies")) r.fail(`the ${r.peek()?.text} operator`);
|
|
624
|
+
return e;
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
primary(scope) {
|
|
628
|
+
const r = this.r;
|
|
629
|
+
const t = r.take();
|
|
630
|
+
switch (t.kind) {
|
|
631
|
+
case "number":
|
|
632
|
+
if (!/^[0-9](_?[0-9])*$/.test(t.text)) r.fail(`the numeric literal ${t.text} (integers in decimal only)`, t);
|
|
633
|
+
return {
|
|
634
|
+
kind: "int",
|
|
635
|
+
value: t.text.replace(/_/g, "")
|
|
636
|
+
};
|
|
637
|
+
case "string": return {
|
|
638
|
+
kind: "string",
|
|
639
|
+
value: stringLiteralValue(t.text, r, t)
|
|
640
|
+
};
|
|
641
|
+
case "template":
|
|
642
|
+
r.fail("a template literal", t);
|
|
643
|
+
break;
|
|
644
|
+
case "regex":
|
|
645
|
+
r.fail("a regular expression", t);
|
|
646
|
+
break;
|
|
647
|
+
case "ident":
|
|
648
|
+
if (t.text === "true" || t.text === "false") return {
|
|
649
|
+
kind: "bool",
|
|
650
|
+
value: t.text === "true"
|
|
651
|
+
};
|
|
652
|
+
if (t.text === "null" || t.text === "undefined") r.fail(`${t.text}`, t);
|
|
653
|
+
if (scope.has(t.text) || this.declared.has(t.text)) return {
|
|
654
|
+
kind: "var",
|
|
655
|
+
name: t.text
|
|
656
|
+
};
|
|
657
|
+
r.fail(`${t.text}, which is neither a parameter, a const nor a function of this module`, t);
|
|
658
|
+
break;
|
|
659
|
+
case "punct":
|
|
660
|
+
if (t.text === "(") {
|
|
661
|
+
const e = this.expression(scope);
|
|
662
|
+
r.expectPunct(")");
|
|
663
|
+
return e;
|
|
664
|
+
}
|
|
665
|
+
if (t.text === "{") return this.record(scope);
|
|
666
|
+
if (t.text === "[") r.fail("an array literal", t);
|
|
667
|
+
r.fail(`unexpected ${t.text}`, t);
|
|
668
|
+
break;
|
|
669
|
+
default: r.fail(`unexpected ${t.text}`, t);
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
record(scope) {
|
|
673
|
+
const r = this.r;
|
|
674
|
+
const fields = [];
|
|
675
|
+
while (!r.isPunct("}")) {
|
|
676
|
+
if (r.isPunct("...")) r.fail("spread in a record literal");
|
|
677
|
+
if (r.isPunct("[")) r.fail("a computed key");
|
|
678
|
+
const t = r.take();
|
|
679
|
+
if (t.kind !== "ident") r.fail(`a key that is not a name: ${t.text}`, t);
|
|
680
|
+
if (t.text === "__proto__") r.fail("a __proto__ key, which sets the prototype, not a field", t);
|
|
681
|
+
if (r.isPunct("(")) r.fail(`a method ${t.text}`, t);
|
|
682
|
+
if (r.isPunct(":")) {
|
|
683
|
+
r.at++;
|
|
684
|
+
fields.push({
|
|
685
|
+
name: t.text,
|
|
686
|
+
value: this.expression(scope)
|
|
687
|
+
});
|
|
688
|
+
} else {
|
|
689
|
+
if (!scope.has(t.text)) r.fail(`shorthand ${t.text} names nothing in scope`, t);
|
|
690
|
+
fields.push({
|
|
691
|
+
name: t.text,
|
|
692
|
+
value: {
|
|
693
|
+
kind: "var",
|
|
694
|
+
name: t.text
|
|
695
|
+
}
|
|
696
|
+
});
|
|
697
|
+
}
|
|
698
|
+
if (r.isPunct(",")) r.at++;
|
|
699
|
+
}
|
|
700
|
+
r.at++;
|
|
701
|
+
return {
|
|
702
|
+
kind: "record",
|
|
703
|
+
fields
|
|
704
|
+
};
|
|
705
|
+
}
|
|
706
|
+
typeOfExpr(e, scope) {
|
|
707
|
+
return typeOf(e, scope, {
|
|
708
|
+
records: this.records,
|
|
709
|
+
signatures: this.signatures
|
|
710
|
+
}, (m) => this.r.fail(m));
|
|
711
|
+
}
|
|
712
|
+
};
|
|
713
|
+
/** A type, for messages. */
|
|
714
|
+
function describe(t) {
|
|
715
|
+
return t.kind === "record" ? t.name : t.kind;
|
|
716
|
+
}
|
|
717
|
+
/** The type of an expression in a scope; records are matched by their fields' names. */
|
|
718
|
+
function typeOf(e, scope, ctx, fail) {
|
|
719
|
+
switch (e.kind) {
|
|
720
|
+
case "int": return { kind: "int" };
|
|
721
|
+
case "bool": return { kind: "bool" };
|
|
722
|
+
case "string": return { kind: "string" };
|
|
723
|
+
case "var": {
|
|
724
|
+
const t = scope.get(e.name);
|
|
725
|
+
if (!t) fail(`${e.name} is not in scope`);
|
|
726
|
+
return t;
|
|
727
|
+
}
|
|
728
|
+
case "binary": {
|
|
729
|
+
const l = typeOf(e.left, scope, ctx, fail);
|
|
730
|
+
const r = typeOf(e.right, scope, ctx, fail);
|
|
731
|
+
if (e.op === "+" && l.kind === "string" && r.kind === "string") return { kind: "string" };
|
|
732
|
+
if ([
|
|
733
|
+
"+",
|
|
734
|
+
"-",
|
|
735
|
+
"*",
|
|
736
|
+
"<",
|
|
737
|
+
"<=",
|
|
738
|
+
">",
|
|
739
|
+
">="
|
|
740
|
+
].includes(e.op) && (l.kind !== "int" || r.kind !== "int")) fail(`${e.op} on a ${l.kind} and a ${r.kind} (the subset has it on integers${e.op === "+" ? ", and + on two strings" : ""})`);
|
|
741
|
+
if ((e.op === "&&" || e.op === "||") && (l.kind !== "bool" || r.kind !== "bool")) fail(`${e.op} on a ${l.kind} and a ${r.kind} (the subset has it on booleans)`);
|
|
742
|
+
if ((e.op === "===" || e.op === "!==") && JSON.stringify(l) !== JSON.stringify(r)) fail(`${e.op} between a ${l.kind} and a ${r.kind}`);
|
|
743
|
+
if ((e.op === "===" || e.op === "!==") && l.kind === "record") fail(`${e.op} on records compares references in JavaScript; compare their fields instead`);
|
|
744
|
+
return [
|
|
745
|
+
"+",
|
|
746
|
+
"-",
|
|
747
|
+
"*"
|
|
748
|
+
].includes(e.op) ? { kind: "int" } : { kind: "bool" };
|
|
749
|
+
}
|
|
750
|
+
case "neg": {
|
|
751
|
+
const t = typeOf(e.operand, scope, ctx, fail);
|
|
752
|
+
if (t.kind !== "int") fail(`unary minus on a ${t.kind}`);
|
|
753
|
+
return { kind: "int" };
|
|
754
|
+
}
|
|
755
|
+
case "not": {
|
|
756
|
+
const t = typeOf(e.operand, scope, ctx, fail);
|
|
757
|
+
if (t.kind !== "bool") fail(`! on a ${t.kind}`);
|
|
758
|
+
return { kind: "bool" };
|
|
759
|
+
}
|
|
760
|
+
case "cond": {
|
|
761
|
+
const test = typeOf(e.test, scope, ctx, fail);
|
|
762
|
+
if (test.kind !== "bool") fail(`a condition that is a ${describe(test)} (truthiness is not in the subset; compare it)`);
|
|
763
|
+
const a = typeOf(e.ifTrue, scope, ctx, fail);
|
|
764
|
+
const b = typeOf(e.ifFalse, scope, ctx, fail);
|
|
765
|
+
if (JSON.stringify(a) !== JSON.stringify(b)) fail("the branches of a conditional have different types");
|
|
766
|
+
return a;
|
|
767
|
+
}
|
|
768
|
+
case "let": return typeOf(e.body, new Map([...scope, [e.name, typeOf(e.value, scope, ctx, fail)]]), ctx, fail);
|
|
769
|
+
case "call": {
|
|
770
|
+
const sig = ctx.signatures.get(e.callee);
|
|
771
|
+
if (!sig) fail(`the signature of ${e.callee} is not known`);
|
|
772
|
+
if (sig.params.length !== e.args.length) fail(`${e.callee} takes ${sig.params.length} argument(s), called with ${e.args.length}`);
|
|
773
|
+
e.args.forEach((a, i) => {
|
|
774
|
+
const want = sig.params[i]?.type;
|
|
775
|
+
const got = typeOf(a, scope, ctx, fail);
|
|
776
|
+
if (JSON.stringify(want) !== JSON.stringify(got)) fail(`argument ${i + 1} of ${e.callee} is a ${got.kind}, not the ${want.kind} it takes`);
|
|
777
|
+
});
|
|
778
|
+
return sig.returns;
|
|
779
|
+
}
|
|
780
|
+
case "field": {
|
|
781
|
+
const o = typeOf(e.object, scope, ctx, fail);
|
|
782
|
+
if (o.kind !== "record") fail(`field ${e.field} read from a ${o.kind}`);
|
|
783
|
+
const f = ctx.records.get(o.name)?.fields.find((x) => x.name === e.field);
|
|
784
|
+
if (!f) fail(`${o.name} has no field ${e.field}`);
|
|
785
|
+
return f.type;
|
|
786
|
+
}
|
|
787
|
+
case "record": {
|
|
788
|
+
const names = e.fields.map((f) => f.name).sort().join(",");
|
|
789
|
+
const byNames = [...ctx.records.values()].filter((rec) => rec.fields.map((f) => f.name).sort().join(",") === names);
|
|
790
|
+
if (byNames.length === 0) fail(`a record literal with fields ${names} matches no declared record type`);
|
|
791
|
+
const types = new Map(e.fields.map((f) => [f.name, typeOf(f.value, scope, ctx, fail)]));
|
|
792
|
+
const fits = byNames.filter((rec) => rec.fields.every((f) => JSON.stringify(types.get(f.name)) === JSON.stringify(f.type)));
|
|
793
|
+
if (fits.length === 0) {
|
|
794
|
+
const rec = byNames[0];
|
|
795
|
+
const off = rec.fields.find((f) => JSON.stringify(types.get(f.name)) !== JSON.stringify(f.type));
|
|
796
|
+
fail(`field ${off.name} of a ${rec.name} literal holds a ${describe(types.get(off.name))}, not a ${describe(off.type)}`);
|
|
797
|
+
}
|
|
798
|
+
if (fits.length > 1) fail(`a record literal with fields ${names} matches ${fits.map((r) => r.name).join(" and ")} alike`);
|
|
799
|
+
return {
|
|
800
|
+
kind: "record",
|
|
801
|
+
name: fits[0].name
|
|
802
|
+
};
|
|
803
|
+
}
|
|
804
|
+
}
|
|
805
|
+
}
|
|
806
|
+
/**
|
|
807
|
+
* One TypeScript expression (a Lemma atom or equation side, say) in a
|
|
808
|
+
* scope of typed names, over a module already read. The whole text must
|
|
809
|
+
* be the expression.
|
|
810
|
+
*/
|
|
811
|
+
function readExpression(text, scope, module) {
|
|
812
|
+
const r = new Reader(tokenize(text), () => 0);
|
|
813
|
+
const records = new Map(module.records.map((rec) => [rec.name, rec]));
|
|
814
|
+
const inSubset = new Set(module.functions.map((f) => f.name));
|
|
815
|
+
const declared = /* @__PURE__ */ new Set([...inSubset, ...module.outside.map((o) => o.name)]);
|
|
816
|
+
const parser = new FunctionParser(r, records, inSubset, /* @__PURE__ */ new Map(), declared);
|
|
817
|
+
for (const f of module.functions) parser.signatures.set(f.name, {
|
|
818
|
+
params: f.params,
|
|
819
|
+
returns: f.returns
|
|
820
|
+
});
|
|
821
|
+
const e = parser.expression(scope);
|
|
822
|
+
if (r.at < r.tokens.length) r.fail(`unexpected ${r.peek()?.text} after the expression`);
|
|
823
|
+
return e;
|
|
824
|
+
}
|
|
825
|
+
/** The functions an expression calls. */
|
|
826
|
+
function callees(e, out = /* @__PURE__ */ new Set()) {
|
|
827
|
+
switch (e.kind) {
|
|
828
|
+
case "int":
|
|
829
|
+
case "bool":
|
|
830
|
+
case "string":
|
|
831
|
+
case "var": return out;
|
|
832
|
+
case "neg":
|
|
833
|
+
case "not": return callees(e.operand, out);
|
|
834
|
+
case "binary":
|
|
835
|
+
callees(e.left, out);
|
|
836
|
+
return callees(e.right, out);
|
|
837
|
+
case "cond":
|
|
838
|
+
callees(e.test, out);
|
|
839
|
+
callees(e.ifTrue, out);
|
|
840
|
+
return callees(e.ifFalse, out);
|
|
841
|
+
case "call":
|
|
842
|
+
out.add(e.callee);
|
|
843
|
+
for (const a of e.args) callees(a, out);
|
|
844
|
+
return out;
|
|
845
|
+
case "field": return callees(e.object, out);
|
|
846
|
+
case "record":
|
|
847
|
+
for (const f of e.fields) callees(f.value, out);
|
|
848
|
+
return out;
|
|
849
|
+
case "let":
|
|
850
|
+
callees(e.value, out);
|
|
851
|
+
return callees(e.body, out);
|
|
852
|
+
}
|
|
853
|
+
}
|
|
854
|
+
/**
|
|
855
|
+
* Read a module: its record types, every function the subset takes (in
|
|
856
|
+
* source order, so callees come before callers) and, for the others, why
|
|
857
|
+
* not. A function calling one outside the subset is outside it too. The
|
|
858
|
+
* names given are what the caller cares about; one the module does not
|
|
859
|
+
* declare at its top level is reported among the others, not thrown.
|
|
860
|
+
*/
|
|
861
|
+
function readSubset(source, functions) {
|
|
862
|
+
const lineOf = (offset) => {
|
|
863
|
+
let line = 1;
|
|
864
|
+
for (let i = 0; i < offset && i < source.length; i++) {
|
|
865
|
+
const c = source[i];
|
|
866
|
+
if (c === "\r") {
|
|
867
|
+
line++;
|
|
868
|
+
if (source[i + 1] === "\n") i++;
|
|
869
|
+
} else if (c === "\n" || c === "\u2028" || c === "\u2029") line++;
|
|
870
|
+
}
|
|
871
|
+
return line;
|
|
872
|
+
};
|
|
873
|
+
let tokens;
|
|
874
|
+
try {
|
|
875
|
+
tokens = tokenize(source);
|
|
876
|
+
} catch (err) {
|
|
877
|
+
if (!(err instanceof TokenizeError)) throw err;
|
|
878
|
+
return {
|
|
879
|
+
records: [],
|
|
880
|
+
functions: [],
|
|
881
|
+
outside: (functions ?? []).map((name) => ({
|
|
882
|
+
name,
|
|
883
|
+
line: 0,
|
|
884
|
+
message: `the module could not be tokenized: ${err.message}`
|
|
885
|
+
}))
|
|
886
|
+
};
|
|
887
|
+
}
|
|
888
|
+
const r = new Reader(tokens, lineOf);
|
|
889
|
+
const records = /* @__PURE__ */ new Map();
|
|
890
|
+
const badRecords = /* @__PURE__ */ new Map();
|
|
891
|
+
const declared = /* @__PURE__ */ new Set();
|
|
892
|
+
const assigned = /* @__PURE__ */ new Map();
|
|
893
|
+
const starts = [];
|
|
894
|
+
while (r.at < tokens.length) {
|
|
895
|
+
const t = r.peek();
|
|
896
|
+
if (t.kind === "ident" && t.text === "import") {
|
|
897
|
+
r.at++;
|
|
898
|
+
skipDeclaration(r);
|
|
899
|
+
continue;
|
|
900
|
+
}
|
|
901
|
+
if (t.kind === "ident" && (t.text === "interface" || t.text === "type" || t.text === "export")) {
|
|
902
|
+
const save = r.at;
|
|
903
|
+
try {
|
|
904
|
+
const rec = recordAt(r, new Set(records.keys()));
|
|
905
|
+
if (rec) {
|
|
906
|
+
records.set(rec.name, rec);
|
|
907
|
+
continue;
|
|
908
|
+
}
|
|
909
|
+
} catch (err) {
|
|
910
|
+
if (!(err instanceof OutsideSubset)) throw err;
|
|
911
|
+
r.at = save;
|
|
912
|
+
if (r.isWord("export")) r.at++;
|
|
913
|
+
r.at++;
|
|
914
|
+
if (r.peek()?.kind === "ident") badRecords.set(r.ident(), err.message);
|
|
915
|
+
skipDeclaration(r);
|
|
916
|
+
continue;
|
|
917
|
+
}
|
|
918
|
+
r.at = save;
|
|
919
|
+
}
|
|
920
|
+
if (t.kind === "ident" && t.text === "function" && isDeclaration(tokens, r.at, lineOf)) {
|
|
921
|
+
const name = r.isPunct("*", 1) ? r.peek(2) : r.peek(1);
|
|
922
|
+
if (name?.kind === "ident") declared.add(name.text);
|
|
923
|
+
let start = r.at;
|
|
924
|
+
if (r.isWord("async", start - r.at - 1)) start--;
|
|
925
|
+
if (r.isWord("export", start - r.at - 1)) start--;
|
|
926
|
+
starts.push(start);
|
|
927
|
+
r.at++;
|
|
928
|
+
continue;
|
|
929
|
+
}
|
|
930
|
+
if (t.kind === "punct" && [
|
|
931
|
+
"(",
|
|
932
|
+
"[",
|
|
933
|
+
"{"
|
|
934
|
+
].includes(t.text)) {
|
|
935
|
+
skipGroup(r);
|
|
936
|
+
continue;
|
|
937
|
+
}
|
|
938
|
+
r.at++;
|
|
939
|
+
}
|
|
940
|
+
for (const [name, line] of valueUses(tokens, lineOf)) assigned.set(name, line);
|
|
941
|
+
const outside = /* @__PURE__ */ new Map();
|
|
942
|
+
for (const name of functions ?? []) if (!declared.has(name)) outside.set(name, {
|
|
943
|
+
name,
|
|
944
|
+
line: 0,
|
|
945
|
+
message: `the module declares no function ${name} at its top level`
|
|
946
|
+
});
|
|
947
|
+
const evalLine = mentionsEval(tokens, lineOf);
|
|
948
|
+
if (evalLine !== void 0) for (const name of declared) outside.set(name, {
|
|
949
|
+
name,
|
|
950
|
+
line: evalLine,
|
|
951
|
+
message: "the module mentions eval directly, which can rebind any of its declarations"
|
|
952
|
+
});
|
|
953
|
+
const escapeLine = firstLine(tokens, lineOf, (t) => t.kind === "punct" && t.text === "\\");
|
|
954
|
+
if (escapeLine !== void 0) {
|
|
955
|
+
for (const name of declared) if (!outside.has(name)) outside.set(name, {
|
|
956
|
+
name,
|
|
957
|
+
line: escapeLine,
|
|
958
|
+
message: "the module uses an identifier escape sequence (\\u…), so its names cannot be matched by spelling"
|
|
959
|
+
});
|
|
960
|
+
}
|
|
961
|
+
for (const [name, line] of assigned) if (declared.has(name) && !outside.has(name)) outside.set(name, {
|
|
962
|
+
name,
|
|
963
|
+
line,
|
|
964
|
+
message: `${name} is used as a value in the module (not only called), so what runs under its name may not be its declaration`
|
|
965
|
+
});
|
|
966
|
+
const parser = new FunctionParser(r, records, declared, badRecords);
|
|
967
|
+
const signatures = [];
|
|
968
|
+
for (const start of starts) {
|
|
969
|
+
r.at = start;
|
|
970
|
+
try {
|
|
971
|
+
const sig = parser.signature();
|
|
972
|
+
parser.signatures.set(sig.name, {
|
|
973
|
+
params: sig.params,
|
|
974
|
+
returns: sig.returns
|
|
975
|
+
});
|
|
976
|
+
if (!outside.has(sig.name)) signatures.push(sig);
|
|
977
|
+
} catch (err) {
|
|
978
|
+
if (!(err instanceof OutsideSubset)) throw err;
|
|
979
|
+
const head = tokens.slice(start, start + 5);
|
|
980
|
+
const fnAt = head.findIndex((t) => t.kind === "ident" && t.text === "function");
|
|
981
|
+
const after = head[fnAt + 1]?.text === "*" ? head[fnAt + 2] : head[fnAt + 1];
|
|
982
|
+
const name = after?.kind === "ident" ? after.text : void 0;
|
|
983
|
+
if (name) outside.set(name, {
|
|
984
|
+
name,
|
|
985
|
+
line: err.line,
|
|
986
|
+
message: err.message
|
|
987
|
+
});
|
|
988
|
+
}
|
|
989
|
+
}
|
|
990
|
+
const read = /* @__PURE__ */ new Map();
|
|
991
|
+
for (const sig of signatures) try {
|
|
992
|
+
read.set(sig.name, parser.declaration(sig));
|
|
993
|
+
} catch (err) {
|
|
994
|
+
if (!(err instanceof OutsideSubset)) throw err;
|
|
995
|
+
outside.set(sig.name, {
|
|
996
|
+
name: sig.name,
|
|
997
|
+
line: err.line,
|
|
998
|
+
message: err.message
|
|
999
|
+
});
|
|
1000
|
+
}
|
|
1001
|
+
for (let changed = true; changed;) {
|
|
1002
|
+
changed = false;
|
|
1003
|
+
for (const [name, fn] of read) {
|
|
1004
|
+
const bad = [...callees(fn.body)].find((c) => outside.has(c));
|
|
1005
|
+
if (bad === void 0) continue;
|
|
1006
|
+
read.delete(name);
|
|
1007
|
+
outside.set(name, {
|
|
1008
|
+
name,
|
|
1009
|
+
line: fn.line,
|
|
1010
|
+
message: `calls ${bad}, which is outside the subset: ${outside.get(bad)?.message}`
|
|
1011
|
+
});
|
|
1012
|
+
changed = true;
|
|
1013
|
+
}
|
|
1014
|
+
}
|
|
1015
|
+
const reaches = (from, target, seen = /* @__PURE__ */ new Set()) => {
|
|
1016
|
+
const fn = read.get(from);
|
|
1017
|
+
if (!fn) return false;
|
|
1018
|
+
for (const c of callees(fn.body)) {
|
|
1019
|
+
if (c === target) return true;
|
|
1020
|
+
if (!seen.has(c)) {
|
|
1021
|
+
seen.add(c);
|
|
1022
|
+
if (reaches(c, target, seen)) return true;
|
|
1023
|
+
}
|
|
1024
|
+
}
|
|
1025
|
+
return false;
|
|
1026
|
+
};
|
|
1027
|
+
for (const [name, fn] of [...read]) if (reaches(name, name)) {
|
|
1028
|
+
read.delete(name);
|
|
1029
|
+
outside.set(name, {
|
|
1030
|
+
name,
|
|
1031
|
+
line: fn.line,
|
|
1032
|
+
message: `${name} is recursive (it reaches itself through its calls); recursion is not in the subset yet`
|
|
1033
|
+
});
|
|
1034
|
+
}
|
|
1035
|
+
for (let changed = true; changed;) {
|
|
1036
|
+
changed = false;
|
|
1037
|
+
for (const [name, fn] of read) {
|
|
1038
|
+
const bad = [...callees(fn.body)].find((c) => outside.has(c));
|
|
1039
|
+
if (bad === void 0) continue;
|
|
1040
|
+
read.delete(name);
|
|
1041
|
+
outside.set(name, {
|
|
1042
|
+
name,
|
|
1043
|
+
line: fn.line,
|
|
1044
|
+
message: `calls ${bad}, which is outside the subset: ${outside.get(bad)?.message}`
|
|
1045
|
+
});
|
|
1046
|
+
changed = true;
|
|
1047
|
+
}
|
|
1048
|
+
}
|
|
1049
|
+
const ordered = [];
|
|
1050
|
+
const placed = /* @__PURE__ */ new Set();
|
|
1051
|
+
while (ordered.length < read.size) for (const [name, fn] of read) if (!placed.has(name) && [...callees(fn.body)].every((c) => placed.has(c))) {
|
|
1052
|
+
ordered.push(fn);
|
|
1053
|
+
placed.add(name);
|
|
1054
|
+
}
|
|
1055
|
+
return {
|
|
1056
|
+
records: [...records.values()],
|
|
1057
|
+
functions: ordered,
|
|
1058
|
+
outside: [...outside.values()]
|
|
1059
|
+
};
|
|
1060
|
+
}
|
|
1061
|
+
// packages/prover-lean/src/emit.ts
|
|
1062
|
+
/**
|
|
1063
|
+
* TypeScript names as Lean identifiers that can clash with nothing Lean
|
|
1064
|
+
* defines and not with each other: functions get `f_`, record types `R_`,
|
|
1065
|
+
* variables `v_`, theorems `t_`. The schemes differ in their first letter,
|
|
1066
|
+
* so no two names from different kinds coincide whatever the author
|
|
1067
|
+
* wrote (`ts_f` and `f_` would, under suffixing), and Lean's prelude has
|
|
1068
|
+
* no names of these shapes, so a function called `decide` or a parameter
|
|
1069
|
+
* called `max` stays what the author meant.
|
|
1070
|
+
*/
|
|
1071
|
+
const ident = {
|
|
1072
|
+
fn: (name) => quote(`f_${name}`),
|
|
1073
|
+
record: (name) => quote(`R_${name}`),
|
|
1074
|
+
variable: (name) => quote(`v_${name}`),
|
|
1075
|
+
field: (name) => leanKeywords.has(name) ? `«${name}»` : quote(name)
|
|
1076
|
+
};
|
|
1077
|
+
/** Lean's keywords, which a field name may coincide with. */
|
|
1078
|
+
const leanKeywords = new Set("at by calc def deriving do else end example export extends from fun have if import in inductive instance lemma let macro match mutual namespace open private protected return section set_option show structure syntax termination_by then theorem universe variable where with abbrev axiom class opaque partial noncomputable unsafe nomatch nofun omit include local scoped attribute initialize builtin_initialize elab notation infix infixl infixr prefix postfix declare_syntax_cat macro_rules elab_rules syntax_rules suffices obtain exists forall Type Prop Sort true false fun".split(" "));
|
|
1079
|
+
function quote(name) {
|
|
1080
|
+
return /^[A-Za-z_][A-Za-z0-9_]*$/.test(name) ? name : `«${name}»`;
|
|
1081
|
+
}
|
|
1082
|
+
function leanType(t) {
|
|
1083
|
+
switch (t.kind) {
|
|
1084
|
+
case "int": return "Int";
|
|
1085
|
+
case "bool": return "Bool";
|
|
1086
|
+
case "string": return "String";
|
|
1087
|
+
case "record": return ident.record(t.name);
|
|
1088
|
+
}
|
|
1089
|
+
}
|
|
1090
|
+
function emitRecord(r) {
|
|
1091
|
+
return [
|
|
1092
|
+
`structure ${ident.record(r.name)} where`,
|
|
1093
|
+
...r.fields.map((f) => ` ${ident.field(f.name)} : ${leanType(f.type)}`),
|
|
1094
|
+
" deriving Repr, DecidableEq"
|
|
1095
|
+
].join("\n");
|
|
1096
|
+
}
|
|
1097
|
+
function env(module) {
|
|
1098
|
+
return {
|
|
1099
|
+
module,
|
|
1100
|
+
ctx: {
|
|
1101
|
+
records: new Map(module.records.map((r) => [r.name, r])),
|
|
1102
|
+
signatures: new Map(module.functions.map((f) => [f.name, {
|
|
1103
|
+
params: f.params,
|
|
1104
|
+
returns: f.returns
|
|
1105
|
+
}]))
|
|
1106
|
+
}
|
|
1107
|
+
};
|
|
1108
|
+
}
|
|
1109
|
+
const fail = (message) => {
|
|
1110
|
+
throw new OutsideSubset(message, 0);
|
|
1111
|
+
};
|
|
1112
|
+
/** A term of the expression's TypeScript type: `Int`, `Bool` or a structure. */
|
|
1113
|
+
function term(e, scope, env) {
|
|
1114
|
+
const t = (x) => term(x, scope, env);
|
|
1115
|
+
switch (e.kind) {
|
|
1116
|
+
case "int": return `(${e.value} : Int)`;
|
|
1117
|
+
case "bool": return e.value ? "true" : "false";
|
|
1118
|
+
case "string": return leanString(e.value);
|
|
1119
|
+
case "var": return ident.variable(e.name);
|
|
1120
|
+
case "neg": return `(-${t(e.operand)})`;
|
|
1121
|
+
case "not": return `(!${t(e.operand)})`;
|
|
1122
|
+
case "binary":
|
|
1123
|
+
switch (e.op) {
|
|
1124
|
+
case "+": {
|
|
1125
|
+
const lt = typeOf(e.left, scope, env.ctx, fail);
|
|
1126
|
+
return `(${t(e.left)} ${lt.kind === "string" ? "++" : "+"} ${t(e.right)})`;
|
|
1127
|
+
}
|
|
1128
|
+
case "-":
|
|
1129
|
+
case "*": return `(${t(e.left)} ${e.op} ${t(e.right)})`;
|
|
1130
|
+
case "<":
|
|
1131
|
+
case ">": return `(decide (${t(e.left)} ${e.op} ${t(e.right)}))`;
|
|
1132
|
+
case "<=": return `(decide (${t(e.left)} ≤ ${t(e.right)}))`;
|
|
1133
|
+
case ">=": return `(decide (${t(e.left)} ≥ ${t(e.right)}))`;
|
|
1134
|
+
case "===":
|
|
1135
|
+
case "!==":
|
|
1136
|
+
if (typeOf(e.left, scope, env.ctx, fail).kind === "record") fail(`${e.op} on records compares references in JavaScript; compare their fields instead`);
|
|
1137
|
+
return `(decide (${t(e.left)} ${e.op === "===" ? "=" : "≠"} ${t(e.right)}))`;
|
|
1138
|
+
case "&&": return `(${t(e.left)} && ${t(e.right)})`;
|
|
1139
|
+
case "||": return `(${t(e.left)} || ${t(e.right)})`;
|
|
1140
|
+
}
|
|
1141
|
+
break;
|
|
1142
|
+
case "cond": return `(if ${t(e.test)} = true then ${t(e.ifTrue)} else ${t(e.ifFalse)})`;
|
|
1143
|
+
case "call": return `(${ident.fn(e.callee)}${e.args.map((a) => ` ${t(a)}`).join("")})`;
|
|
1144
|
+
case "field": return `${t(e.object)}.${ident.field(e.field)}`;
|
|
1145
|
+
case "record": {
|
|
1146
|
+
const type = typeOf(e, scope, env.ctx, fail);
|
|
1147
|
+
const name = type.kind === "record" ? ident.record(type.name) : fail("a record literal of no record type");
|
|
1148
|
+
return `({ ${e.fields.map((f) => `${ident.field(f.name)} := ${t(f.value)}`).join(", ")} } : ${name})`;
|
|
1149
|
+
}
|
|
1150
|
+
case "let": {
|
|
1151
|
+
const inner = new Map(scope);
|
|
1152
|
+
inner.set(e.name, typeOf(e.value, scope, env.ctx, fail));
|
|
1153
|
+
return `(let ${ident.variable(e.name)} := ${t(e.value)}; ${term(e.body, inner, env)})`;
|
|
1154
|
+
}
|
|
1155
|
+
}
|
|
1156
|
+
}
|
|
1157
|
+
function emitFunction(f, module) {
|
|
1158
|
+
const e = env(module);
|
|
1159
|
+
const scope = new Map(f.params.map((p) => [p.name, p.type]));
|
|
1160
|
+
const params = f.params.map((p) => `(${ident.variable(p.name)} : ${leanType(p.type)})`).join(" ");
|
|
1161
|
+
return `def ${ident.fn(f.name)} ${params} : ${leanType(f.returns)} :=\n ${term(f.body, scope, e)}`;
|
|
1162
|
+
}
|
|
1163
|
+
/** The Lean type a binder ranges over, or `OutsideSubset`. */
|
|
1164
|
+
function binderType(b) {
|
|
1165
|
+
switch (b.domain) {
|
|
1166
|
+
case "int":
|
|
1167
|
+
case "nat": return { kind: "int" };
|
|
1168
|
+
case "boolean": return { kind: "bool" };
|
|
1169
|
+
case "bigint":
|
|
1170
|
+
fail(`binder ${b.name} over bigint: the subset has no bigint, and a bigint argument to a number function throws`);
|
|
1171
|
+
break;
|
|
1172
|
+
case "number":
|
|
1173
|
+
fail(`binder ${b.name} over number: the engine models integers, not doubles`);
|
|
1174
|
+
break;
|
|
1175
|
+
case "string": return { kind: "string" };
|
|
1176
|
+
}
|
|
1177
|
+
}
|
|
1178
|
+
/** The hypotheses a binder's domain and guard add. */
|
|
1179
|
+
function binderHypotheses(b) {
|
|
1180
|
+
const out = [];
|
|
1181
|
+
const x = ident.variable(b.name);
|
|
1182
|
+
if (b.domain === "nat") out.push(`0 ≤ ${x}`);
|
|
1183
|
+
const g = b.guard;
|
|
1184
|
+
if (!g) return out;
|
|
1185
|
+
if (g.kind === "regex") fail(`a regex guard on ${b.name}: the engine does not model regular expressions`);
|
|
1186
|
+
const literal = (v) => v.replace(/_/g, "").replace(/n$/, "");
|
|
1187
|
+
if (!g.lower.value.endsWith("∞")) out.push(`(${literal(g.lower.value)} : Int) ${g.lower.inclusive ? "≤" : "<"} ${x}`);
|
|
1188
|
+
if (!g.upper.value.endsWith("∞")) out.push(`${x} ${g.upper.inclusive ? "≤" : "<"} (${literal(g.upper.value)} : Int)`);
|
|
1189
|
+
return out;
|
|
1190
|
+
}
|
|
1191
|
+
/** A formula as a proposition. */
|
|
1192
|
+
function prop(f, scope, e) {
|
|
1193
|
+
const p = (x) => prop(x, scope, e);
|
|
1194
|
+
const expr = (text) => readExpression(text, scope, e.module);
|
|
1195
|
+
switch (f.kind) {
|
|
1196
|
+
case "atom": {
|
|
1197
|
+
const x = expr(f.text);
|
|
1198
|
+
if (typeOf(x, scope, e.ctx, fail).kind !== "bool") fail(`atom ${f.text.trim()} is not boolean`);
|
|
1199
|
+
return `(${term(x, scope, e)} = true)`;
|
|
1200
|
+
}
|
|
1201
|
+
case "equation": {
|
|
1202
|
+
const l = expr(f.left);
|
|
1203
|
+
const r = expr(f.right);
|
|
1204
|
+
const lt = typeOf(l, scope, e.ctx, fail);
|
|
1205
|
+
const rt = typeOf(r, scope, e.ctx, fail);
|
|
1206
|
+
if (leanType(lt) !== leanType(rt)) fail(`${f.left.trim()} and ${f.right.trim()} have different types`);
|
|
1207
|
+
if (lt.kind === "record") fail(`${f.left.trim()} ≡ ${f.right.trim()} compares records: SameValue on objects is reference identity in JavaScript; compare their fields instead`);
|
|
1208
|
+
if (lt.kind === "int") fail(`${f.left.trim()} ≡ ${f.right.trim()} compares numbers by SameValue, which tells -0 from 0; the integer model does not, so use === for numeric equality`);
|
|
1209
|
+
return `(${term(l, scope, e)} ${f.negated ? "≠" : "="} ${term(r, scope, e)})`;
|
|
1210
|
+
}
|
|
1211
|
+
case "not": return `(¬ ${p(f.operand)})`;
|
|
1212
|
+
case "and": return `(${f.operands.map(p).join(" ∧ ")})`;
|
|
1213
|
+
case "or": return `(${f.operands.map(p).join(" ∨ ")})`;
|
|
1214
|
+
case "implies": return `(${[...f.antecedents, f.consequent].map(p).join(" → ")})`;
|
|
1215
|
+
case "iff": return `(${p(f.left)} ↔ ${p(f.right)})`;
|
|
1216
|
+
}
|
|
1217
|
+
}
|
|
1218
|
+
/** The statement and how many hypotheses stand before the claim (the tactic script introduces them by name). */
|
|
1219
|
+
function stated(property, module) {
|
|
1220
|
+
const e = env(module);
|
|
1221
|
+
const scope = new Map(property.binders.map((b) => [b.name, binderType(b)]));
|
|
1222
|
+
const binders = property.binders.map((b) => `(${ident.variable(b.name)} : ${leanType(binderType(b))})`).join(" ");
|
|
1223
|
+
const hyps = [...property.binders.flatMap(binderHypotheses), ...property.requires.map((r) => prop(r, scope, e))];
|
|
1224
|
+
const claim = prop(property.claim, scope, e);
|
|
1225
|
+
return {
|
|
1226
|
+
text: `∀ ${binders},\n ${[...hyps, claim].join(" →\n ")}`,
|
|
1227
|
+
hypotheses: hyps.length
|
|
1228
|
+
};
|
|
1229
|
+
}
|
|
1230
|
+
/**
|
|
1231
|
+
* The tactic script every theorem is closed by. Booleans become
|
|
1232
|
+
* propositions first, while the `Decidable` instances in the statement
|
|
1233
|
+
* still match their propositions (unfolding under `decide` first leaves
|
|
1234
|
+
* them stale and stops `simp`); Bool binders are cased, so boolean claims
|
|
1235
|
+
* are decided by enumeration; then the module's definitions unfold, each
|
|
1236
|
+
* conditional splits, and linear integer arithmetic (`omega`) closes what
|
|
1237
|
+
* remains. Nothing here is specific to a property; what Lean checks is
|
|
1238
|
+
* the statement.
|
|
1239
|
+
*/
|
|
1240
|
+
function tactics(module, property, hypotheses) {
|
|
1241
|
+
const defs = module.functions.map((f) => ident.fn(f.name)).join(", ");
|
|
1242
|
+
const names = property.binders.map((b) => ident.variable(b.name));
|
|
1243
|
+
const hyps = Array.from({ length: hypotheses }, (_, i) => `h${i}_`);
|
|
1244
|
+
const bools = property.binders.filter((b) => b.domain === "boolean").map((b) => ident.variable(b.name));
|
|
1245
|
+
return [
|
|
1246
|
+
` intro ${[...names, ...hyps].join(" ")}`,
|
|
1247
|
+
...bools.length > 0 ? [` ${bools.map((b) => `cases ${b}`).join(" <;> ")}`] : [],
|
|
1248
|
+
" all_goals (try simp_all)",
|
|
1249
|
+
` all_goals (try simp only [${defs}] at *)`,
|
|
1250
|
+
" all_goals (repeat' (split <;> simp_all))",
|
|
1251
|
+
" all_goals (try simp_all)",
|
|
1252
|
+
" all_goals (first | decide | trivial | omega)"
|
|
1253
|
+
].join("\n");
|
|
1254
|
+
}
|
|
1255
|
+
/** A Lean-safe theorem name: unique by position, readable by the function's and property's names. */
|
|
1256
|
+
function theoremName(index, fn, property) {
|
|
1257
|
+
return `t${index}_${fn}_${property}`.replace(/[^A-Za-z0-9_]/g, "_");
|
|
1258
|
+
}
|
|
1259
|
+
/** The whole file: structures, definitions, one theorem per property, then any extra lines (translation checks). */
|
|
1260
|
+
function emitModule(module, properties, extra = []) {
|
|
1261
|
+
const parts = [
|
|
1262
|
+
"-- Generated by Eutaxy's first-party engine from the annotated module; the theorems are its properties.",
|
|
1263
|
+
"set_option linter.unusedSimpArgs false",
|
|
1264
|
+
...module.records.map(emitRecord),
|
|
1265
|
+
...module.functions.map((f) => emitFunction(f, module))
|
|
1266
|
+
];
|
|
1267
|
+
const theorems = [];
|
|
1268
|
+
const skipped = [];
|
|
1269
|
+
for (const { function: fn, property } of properties) {
|
|
1270
|
+
let body;
|
|
1271
|
+
try {
|
|
1272
|
+
body = stated(property.property, module);
|
|
1273
|
+
} catch (err) {
|
|
1274
|
+
if (!(err instanceof OutsideSubset)) throw err;
|
|
1275
|
+
skipped.push({
|
|
1276
|
+
function: fn,
|
|
1277
|
+
property: property.name,
|
|
1278
|
+
reason: err.message
|
|
1279
|
+
});
|
|
1280
|
+
continue;
|
|
1281
|
+
}
|
|
1282
|
+
const name = theoremName(theorems.length + skipped.length, fn, property.name);
|
|
1283
|
+
const text = `theorem ${name} :\n ${body.text} := by\n${tactics(module, property.property, body.hypotheses)}`;
|
|
1284
|
+
const from = parts.join("\n\n").split("\n").length + 2;
|
|
1285
|
+
parts.push(text);
|
|
1286
|
+
theorems.push({
|
|
1287
|
+
function: fn,
|
|
1288
|
+
property: property.name,
|
|
1289
|
+
name,
|
|
1290
|
+
from,
|
|
1291
|
+
to: from + text.split("\n").length - 1
|
|
1292
|
+
});
|
|
1293
|
+
}
|
|
1294
|
+
parts.push(...extra);
|
|
1295
|
+
return {
|
|
1296
|
+
source: `${parts.join("\n\n")}\n`,
|
|
1297
|
+
theorems,
|
|
1298
|
+
skipped
|
|
1299
|
+
};
|
|
1300
|
+
}
|
|
1301
|
+
/**
|
|
1302
|
+
* A JavaScript string as a Lean string literal: `"` and `\` escaped, control
|
|
1303
|
+
* characters as `\xHH`, everything else written as it is (Lean source is
|
|
1304
|
+
* UTF-8). A lone surrogate has no Lean character and is refused.
|
|
1305
|
+
*/
|
|
1306
|
+
function leanString(value) {
|
|
1307
|
+
if (hasLoneSurrogate(value)) fail("a string with a lone surrogate, which Lean's strings cannot hold");
|
|
1308
|
+
let out = "\"";
|
|
1309
|
+
for (const c of value) {
|
|
1310
|
+
const code = c.codePointAt(0);
|
|
1311
|
+
if (c === "\"") out += "\\\"";
|
|
1312
|
+
else if (c === "\\") out += "\\\\";
|
|
1313
|
+
else if (code < 32 || code === 127) out += `\\x${code.toString(16).padStart(2, "0")}`;
|
|
1314
|
+
else out += c;
|
|
1315
|
+
}
|
|
1316
|
+
return `${out}"`;
|
|
1317
|
+
}
|
|
1318
|
+
// packages/prover-lean/src/lean.ts
|
|
1319
|
+
/**
|
|
1320
|
+
* Running Lean over a process boundary. The engine is pinned to one Lean
|
|
1321
|
+
* release: `elan` (Lean's toolchain manager) is asked for it by name, and a
|
|
1322
|
+
* `lean` found without `elan` must report that version. Nothing is ever
|
|
1323
|
+
* downloaded during a check; a missing toolchain is `unavailable`, with the
|
|
1324
|
+
* command that installs it. Diagnostics come back as `file:line:col:
|
|
1325
|
+
* severity: message` lines, which the engine maps to theorems.
|
|
1326
|
+
*/
|
|
1327
|
+
/** The Lean release the engine's contract corpus is checked against. */
|
|
1328
|
+
const leanToolchain = "leanprover/lean4:v4.35.0";
|
|
1329
|
+
const leanVersion = "4.35.0";
|
|
1330
|
+
/** How to put the pinned toolchain on this machine. */
|
|
1331
|
+
const installHint = `install elan (https://elan.lean-lang.org) and run: elan toolchain install ${leanToolchain}`;
|
|
1332
|
+
function run(command, args, options) {
|
|
1333
|
+
return new Promise((resolve) => {
|
|
1334
|
+
let child;
|
|
1335
|
+
try {
|
|
1336
|
+
child = spawn(command, args, {
|
|
1337
|
+
cwd: options.cwd,
|
|
1338
|
+
stdio: [
|
|
1339
|
+
"ignore",
|
|
1340
|
+
"pipe",
|
|
1341
|
+
"pipe"
|
|
1342
|
+
],
|
|
1343
|
+
detached: process.platform !== "win32"
|
|
1344
|
+
});
|
|
1345
|
+
} catch (err) {
|
|
1346
|
+
resolve({
|
|
1347
|
+
code: null,
|
|
1348
|
+
stdout: "",
|
|
1349
|
+
stderr: String(err),
|
|
1350
|
+
timedOut: false
|
|
1351
|
+
});
|
|
1352
|
+
return;
|
|
1353
|
+
}
|
|
1354
|
+
let stdout = "";
|
|
1355
|
+
let stderr = "";
|
|
1356
|
+
let timedOut = false;
|
|
1357
|
+
const timer = setTimeout(() => {
|
|
1358
|
+
timedOut = true;
|
|
1359
|
+
try {
|
|
1360
|
+
if (process.platform !== "win32" && child.pid !== void 0) process.kill(-child.pid, "SIGKILL");
|
|
1361
|
+
else child.kill("SIGKILL");
|
|
1362
|
+
} catch {
|
|
1363
|
+
child.kill("SIGKILL");
|
|
1364
|
+
}
|
|
1365
|
+
}, options.timeoutMs);
|
|
1366
|
+
child.stdout?.on("data", (d) => {
|
|
1367
|
+
stdout += d.toString();
|
|
1368
|
+
});
|
|
1369
|
+
child.stderr?.on("data", (d) => {
|
|
1370
|
+
stderr += d.toString();
|
|
1371
|
+
});
|
|
1372
|
+
child.on("error", (err) => {
|
|
1373
|
+
clearTimeout(timer);
|
|
1374
|
+
resolve({
|
|
1375
|
+
code: null,
|
|
1376
|
+
stdout,
|
|
1377
|
+
stderr: `${stderr}${String(err)}`,
|
|
1378
|
+
timedOut
|
|
1379
|
+
});
|
|
1380
|
+
});
|
|
1381
|
+
child.on("close", (code) => {
|
|
1382
|
+
clearTimeout(timer);
|
|
1383
|
+
resolve({
|
|
1384
|
+
code,
|
|
1385
|
+
stdout,
|
|
1386
|
+
stderr,
|
|
1387
|
+
timedOut
|
|
1388
|
+
});
|
|
1389
|
+
});
|
|
1390
|
+
});
|
|
1391
|
+
}
|
|
1392
|
+
/** Candidates for the `elan` and `lean` executables: the PATH, then elan's default home. */
|
|
1393
|
+
function candidates(name) {
|
|
1394
|
+
const home = process.env["ELAN_HOME"] ?? join(homedir(), ".elan");
|
|
1395
|
+
return [name, join(home, "bin", name)];
|
|
1396
|
+
}
|
|
1397
|
+
/**
|
|
1398
|
+
* The pinned toolchain if it is installed: through `elan run <toolchain>`
|
|
1399
|
+
* when elan is present (and only when it already has the toolchain, so
|
|
1400
|
+
* nothing is downloaded), else a bare `lean` of exactly that version.
|
|
1401
|
+
*/
|
|
1402
|
+
async function findLean() {
|
|
1403
|
+
for (const elan of candidates("elan")) {
|
|
1404
|
+
const list = await run(elan, ["toolchain", "list"], { timeoutMs: 2e4 });
|
|
1405
|
+
if (list.code !== 0) continue;
|
|
1406
|
+
if (!list.stdout.split("\n").some((l) => l.trim().split(" ")[0] === "leanprover/lean4:v4.35.0")) return { unavailable: `elan has no ${leanToolchain}; run: elan toolchain install ${leanToolchain}` };
|
|
1407
|
+
return {
|
|
1408
|
+
command: elan,
|
|
1409
|
+
args: [
|
|
1410
|
+
"run",
|
|
1411
|
+
leanToolchain,
|
|
1412
|
+
"lean"
|
|
1413
|
+
],
|
|
1414
|
+
version: leanVersion
|
|
1415
|
+
};
|
|
1416
|
+
}
|
|
1417
|
+
for (const lean of candidates("lean")) {
|
|
1418
|
+
const v = await run(lean, ["--version"], { timeoutMs: 2e4 });
|
|
1419
|
+
if (v.code !== 0) continue;
|
|
1420
|
+
const m = /Lean \(version ([^,]+),/.exec(v.stdout);
|
|
1421
|
+
if (m?.[1] === "4.35.0") return {
|
|
1422
|
+
command: lean,
|
|
1423
|
+
args: [],
|
|
1424
|
+
version: leanVersion
|
|
1425
|
+
};
|
|
1426
|
+
return { unavailable: `lean ${m?.[1] ?? "of unknown version"} found, but the engine is pinned to ${leanVersion}; ${installHint}` };
|
|
1427
|
+
}
|
|
1428
|
+
return { unavailable: `no Lean toolchain found; ${installHint}` };
|
|
1429
|
+
}
|
|
1430
|
+
/** Parse Lean's diagnostics for the one file it was given. */
|
|
1431
|
+
function diagnostics(output) {
|
|
1432
|
+
const out = [];
|
|
1433
|
+
const re = /^(?:.*?):(\d+):(\d+): (error|warning|info): (.*)$/;
|
|
1434
|
+
let current;
|
|
1435
|
+
const flush = (c) => out.push({
|
|
1436
|
+
line: c.line,
|
|
1437
|
+
column: c.column,
|
|
1438
|
+
severity: c.severity,
|
|
1439
|
+
message: c.lines.join("\n").trimEnd()
|
|
1440
|
+
});
|
|
1441
|
+
for (const raw of output.split("\n")) {
|
|
1442
|
+
const m = re.exec(raw);
|
|
1443
|
+
if (m) {
|
|
1444
|
+
if (current) flush(current);
|
|
1445
|
+
current = {
|
|
1446
|
+
line: Number(m[1]),
|
|
1447
|
+
column: Number(m[2]),
|
|
1448
|
+
severity: m[3],
|
|
1449
|
+
lines: [m[4]]
|
|
1450
|
+
};
|
|
1451
|
+
} else if (current) current.lines.push(raw);
|
|
1452
|
+
}
|
|
1453
|
+
if (current) flush(current);
|
|
1454
|
+
return out;
|
|
1455
|
+
}
|
|
1456
|
+
/** Write the source to a scratch directory pinned to the toolchain and check it. */
|
|
1457
|
+
async function checkLean(toolchain, source, options = {}) {
|
|
1458
|
+
const dir = mkdtempSync(join(tmpdir(), "eutaxy-lean-"));
|
|
1459
|
+
try {
|
|
1460
|
+
writeFileSync(join(dir, "lean-toolchain"), `${leanToolchain}\n`);
|
|
1461
|
+
writeFileSync(join(dir, "Eutaxy.lean"), source);
|
|
1462
|
+
const result = await run(toolchain.command, [...toolchain.args, "Eutaxy.lean"], {
|
|
1463
|
+
cwd: dir,
|
|
1464
|
+
timeoutMs: options.timeoutMs ?? 12e4
|
|
1465
|
+
});
|
|
1466
|
+
return {
|
|
1467
|
+
run: result,
|
|
1468
|
+
diagnostics: diagnostics(`${result.stdout}\n${result.stderr}`)
|
|
1469
|
+
};
|
|
1470
|
+
} finally {
|
|
1471
|
+
if (!options.keep) rmSync(dir, {
|
|
1472
|
+
recursive: true,
|
|
1473
|
+
force: true
|
|
1474
|
+
});
|
|
1475
|
+
}
|
|
1476
|
+
}
|
|
1477
|
+
// packages/prover-lean/src/prove.ts
|
|
1478
|
+
const engineName = "lean";
|
|
1479
|
+
/** What every PROVEN verdict of this engine rests on. */
|
|
1480
|
+
const engineAssumptions = [
|
|
1481
|
+
"number is modelled as the unbounded integers: no overflow, no fractions, no NaN",
|
|
1482
|
+
"string is modelled as Lean's String, a sequence of Unicode characters: a lone surrogate, which a JavaScript string can hold, is outside every string binder's domain",
|
|
1483
|
+
"the function and its callees are the module's own, pure and total; nothing outside the module is modelled",
|
|
1484
|
+
`the proof was checked by the Lean ${leanVersion} kernel on the emitted statement, not by Eutaxy`
|
|
1485
|
+
];
|
|
1486
|
+
const proven = {
|
|
1487
|
+
kind: "PROVEN",
|
|
1488
|
+
engine: {
|
|
1489
|
+
name: engineName,
|
|
1490
|
+
version: leanVersion
|
|
1491
|
+
},
|
|
1492
|
+
assumptions: engineAssumptions
|
|
1493
|
+
};
|
|
1494
|
+
const unknown = (cause, reason) => ({
|
|
1495
|
+
kind: "UNKNOWN",
|
|
1496
|
+
cause,
|
|
1497
|
+
reason
|
|
1498
|
+
});
|
|
1499
|
+
function propertiesOf(fn) {
|
|
1500
|
+
return [...fn.ensures.map((p) => p.name), ...fn.total ? ["@total"] : []];
|
|
1501
|
+
}
|
|
1502
|
+
/** Every property of the functions, with one outcome. */
|
|
1503
|
+
function allWith(fns, outcome) {
|
|
1504
|
+
return fns.flatMap((fn) => propertiesOf(fn).map((property) => ({
|
|
1505
|
+
function: fn.name,
|
|
1506
|
+
property,
|
|
1507
|
+
outcome
|
|
1508
|
+
})));
|
|
1509
|
+
}
|
|
1510
|
+
/**
|
|
1511
|
+
* Read and emit. Every function the subset takes is emitted (callees
|
|
1512
|
+
* included); properties are stated for the annotated ones among them.
|
|
1513
|
+
*/
|
|
1514
|
+
function prepare(input) {
|
|
1515
|
+
const specs = input.specs ?? extractSpecs(input.source);
|
|
1516
|
+
const wanted = input.functions ? new Set(input.functions) : void 0;
|
|
1517
|
+
const fns = specs.functions.filter((f) => !wanted || wanted.has(f.name));
|
|
1518
|
+
const module = readSubset(input.source, fns.map((f) => f.name));
|
|
1519
|
+
const outside = /* @__PURE__ */ new Map();
|
|
1520
|
+
for (const o of module.outside) if (fns.some((f) => f.name === o.name)) outside.set(o.name, `outside the engine's subset${o.line > 0 ? ` (line ${o.line})` : ""}: ${o.message}`);
|
|
1521
|
+
for (const fn of fns) {
|
|
1522
|
+
const read = module.functions.find((f) => f.name === fn.name);
|
|
1523
|
+
if (read && read.offset !== fn.offset) outside.set(fn.name, `outside the engine's subset (line ${fn.line}): the annotated ${fn.name} is not the module's top-level declaration of that name (line ${read.line})`);
|
|
1524
|
+
}
|
|
1525
|
+
const properties = fns.filter((fn) => !outside.has(fn.name)).flatMap((fn) => fn.ensures.map((property) => ({
|
|
1526
|
+
function: fn.name,
|
|
1527
|
+
property
|
|
1528
|
+
})));
|
|
1529
|
+
const specErrors = specs.errors;
|
|
1530
|
+
try {
|
|
1531
|
+
return {
|
|
1532
|
+
module,
|
|
1533
|
+
emitted: emitModule(module, properties, input.extra),
|
|
1534
|
+
fns,
|
|
1535
|
+
outside,
|
|
1536
|
+
specErrors
|
|
1537
|
+
};
|
|
1538
|
+
} catch (err) {
|
|
1539
|
+
if (!(err instanceof OutsideSubset)) throw err;
|
|
1540
|
+
for (const fn of fns) outside.set(fn.name, `outside the engine's subset: ${err.message}`);
|
|
1541
|
+
return {
|
|
1542
|
+
module,
|
|
1543
|
+
emitted: {
|
|
1544
|
+
source: "",
|
|
1545
|
+
theorems: [],
|
|
1546
|
+
skipped: []
|
|
1547
|
+
},
|
|
1548
|
+
fns,
|
|
1549
|
+
outside,
|
|
1550
|
+
specErrors
|
|
1551
|
+
};
|
|
1552
|
+
}
|
|
1553
|
+
}
|
|
1554
|
+
/** Prove a module's properties with the pinned Lean. */
|
|
1555
|
+
async function proveModule(input) {
|
|
1556
|
+
const { emitted, fns, outside, specErrors } = prepare(input);
|
|
1557
|
+
const inSubset = fns.filter((f) => !outside.has(f.name));
|
|
1558
|
+
const unsupported = fns.filter((f) => outside.has(f.name)).flatMap((f) => propertiesOf(f).map((property) => ({
|
|
1559
|
+
function: f.name,
|
|
1560
|
+
property,
|
|
1561
|
+
outcome: unknown("unsupported", outside.get(f.name))
|
|
1562
|
+
})));
|
|
1563
|
+
if (inSubset.length === 0) return {
|
|
1564
|
+
results: unsupported,
|
|
1565
|
+
specErrors
|
|
1566
|
+
};
|
|
1567
|
+
const lean = emitted.source;
|
|
1568
|
+
const rest = (outcome) => ({
|
|
1569
|
+
results: [...unsupported, ...allWith(inSubset, outcome)],
|
|
1570
|
+
lean,
|
|
1571
|
+
specErrors
|
|
1572
|
+
});
|
|
1573
|
+
const toolchain = await findLean();
|
|
1574
|
+
if ("unavailable" in toolchain) return rest(unknown("unavailable", toolchain.unavailable));
|
|
1575
|
+
const timeoutMs = input.timeoutMs ?? 12e4;
|
|
1576
|
+
const checked = await checkLean(toolchain, lean, { timeoutMs });
|
|
1577
|
+
if (checked.run.timedOut) return rest(unknown("gave_up", `Lean did not finish within ${timeoutMs} ms`));
|
|
1578
|
+
const errors = checked.diagnostics.filter((d) => d.severity === "error");
|
|
1579
|
+
const inTheorem = (d) => emitted.theorems.find((t) => d.line >= t.from && d.line <= t.to);
|
|
1580
|
+
if (checked.run.code === null || checked.run.code !== 0 && errors.length === 0) return rest(unknown("unavailable", `Lean could not be run: ${checked.run.stderr.trim() || `exit ${checked.run.code}`}`));
|
|
1581
|
+
const elsewhere = errors.filter((d) => !inTheorem(d));
|
|
1582
|
+
if (elsewhere.length > 0) {
|
|
1583
|
+
const where = elsewhere.map((d) => `line ${d.line}: ${d.message.split("\n")[0]}`).join("; ");
|
|
1584
|
+
return rest(unknown("unsupported", `the emitted Lean did not compile: ${where}`));
|
|
1585
|
+
}
|
|
1586
|
+
const results = [...unsupported];
|
|
1587
|
+
for (const fn of inSubset) {
|
|
1588
|
+
for (const property of fn.ensures) {
|
|
1589
|
+
const skipped = emitted.skipped.find((s) => s.function === fn.name && s.property === property.name);
|
|
1590
|
+
if (skipped) {
|
|
1591
|
+
results.push({
|
|
1592
|
+
function: fn.name,
|
|
1593
|
+
property: property.name,
|
|
1594
|
+
outcome: unknown("unsupported", skipped.reason)
|
|
1595
|
+
});
|
|
1596
|
+
continue;
|
|
1597
|
+
}
|
|
1598
|
+
const theorem = emitted.theorems.find((t) => t.function === fn.name && t.property === property.name);
|
|
1599
|
+
const failed = theorem ? errors.filter((d) => d.line >= theorem.from && d.line <= theorem.to) : [];
|
|
1600
|
+
results.push({
|
|
1601
|
+
function: fn.name,
|
|
1602
|
+
property: property.name,
|
|
1603
|
+
outcome: failed.length === 0 ? proven : unknown("gave_up", `Lean could not close the proof: ${failed[0].message.split("\n")[0]}`)
|
|
1604
|
+
});
|
|
1605
|
+
}
|
|
1606
|
+
if (fn.total) results.push({
|
|
1607
|
+
function: fn.name,
|
|
1608
|
+
property: "@total",
|
|
1609
|
+
outcome: {
|
|
1610
|
+
...proven,
|
|
1611
|
+
assumptions: [...engineAssumptions, "Lean accepted the definition, so it terminates on every input"]
|
|
1612
|
+
}
|
|
1613
|
+
});
|
|
1614
|
+
}
|
|
1615
|
+
return {
|
|
1616
|
+
results,
|
|
1617
|
+
lean,
|
|
1618
|
+
specErrors
|
|
1619
|
+
};
|
|
1620
|
+
}
|
|
1621
|
+
/** The engine as a `Prover`: available when the pinned toolchain is installed. */
|
|
1622
|
+
const leanProver = {
|
|
1623
|
+
name: engineName,
|
|
1624
|
+
async available() {
|
|
1625
|
+
const toolchain = await findLean();
|
|
1626
|
+
return "unavailable" in toolchain ? toolchain : { version: toolchain.version };
|
|
1627
|
+
},
|
|
1628
|
+
prove: (input) => proveModule(input)
|
|
1629
|
+
};
|
|
36
1630
|
// packages/cli/src/generate.ts
|
|
37
1631
|
/**
|
|
38
1632
|
* The files `eutaxy check` writes into `<scenario dir>/.eutaxy/` before
|
|
@@ -226,6 +1820,32 @@ const exitCodes = {
|
|
|
226
1820
|
UNSUPPORTED: 2,
|
|
227
1821
|
error: 3
|
|
228
1822
|
};
|
|
1823
|
+
/** The engines `--prover` can name. */
|
|
1824
|
+
const provers = { lean: leanProver };
|
|
1825
|
+
/**
|
|
1826
|
+
* The PROVEN rung, on the Node side: each engine on each observed spec
|
|
1827
|
+
* module's source, the outcomes folded into the simulator's verdicts.
|
|
1828
|
+
* An engine that is not installed proves nothing and says so.
|
|
1829
|
+
*/
|
|
1830
|
+
async function proveSpecs(dir, observed, specs, engines) {
|
|
1831
|
+
let out = specs;
|
|
1832
|
+
for (const m of observed) {
|
|
1833
|
+
const key = specKey(m.module);
|
|
1834
|
+
const source = readFileSync(resolve(dir, key), "utf8");
|
|
1835
|
+
const annotated = m.functions.filter((f) => specs.some((v) => v.module === key && v.function === f));
|
|
1836
|
+
if (annotated.length === 0) continue;
|
|
1837
|
+
const reports = [];
|
|
1838
|
+
for (const engine of engines) reports.push({
|
|
1839
|
+
engine: engine.name,
|
|
1840
|
+
proofs: await engine.prove({
|
|
1841
|
+
source,
|
|
1842
|
+
functions: annotated
|
|
1843
|
+
})
|
|
1844
|
+
});
|
|
1845
|
+
out = aggregate(key, out, reports);
|
|
1846
|
+
}
|
|
1847
|
+
return out;
|
|
1848
|
+
}
|
|
229
1849
|
function findWrangler(dir, explicit, cwd) {
|
|
230
1850
|
if (explicit) return resolve(cwd, explicit);
|
|
231
1851
|
for (const name of [
|
|
@@ -333,8 +1953,24 @@ async function runCheck(o) {
|
|
|
333
1953
|
}
|
|
334
1954
|
const report = transport.report;
|
|
335
1955
|
const verdict = report.verdict;
|
|
336
|
-
|
|
337
|
-
if (o.
|
|
1956
|
+
let specs = report.specs ?? [];
|
|
1957
|
+
if (o.provers && o.provers.length > 0) {
|
|
1958
|
+
const engines = [];
|
|
1959
|
+
for (const name of o.provers) {
|
|
1960
|
+
const engine = provers[name];
|
|
1961
|
+
if (!engine) {
|
|
1962
|
+
o.stderr(`unknown prover ${name}; known: ${Object.keys(provers).join(", ")}\n`);
|
|
1963
|
+
return exitCodes.error;
|
|
1964
|
+
}
|
|
1965
|
+
engines.push(engine);
|
|
1966
|
+
}
|
|
1967
|
+
specs = await proveSpecs(dir, transport.observed ?? [], specs, engines);
|
|
1968
|
+
}
|
|
1969
|
+
const printed = o.provers && o.provers.length > 0 ? {
|
|
1970
|
+
...transport.report,
|
|
1971
|
+
specs
|
|
1972
|
+
} : transport.report;
|
|
1973
|
+
if (o.json) o.stdout(`${canonicalJson(printed)}\n`);
|
|
338
1974
|
else o.stdout(`${renderText(verdict)}\n${specs.length > 0 ? `\n${renderSpecs(specs)}\n` : ""}`);
|
|
339
1975
|
if (verdict.kind === "VIOLATED" && !o.noRegression) {
|
|
340
1976
|
const outPath = o.out ? resolve(o.cwd, o.out) : join(dir, `${name}.regression.test.ts`);
|
|
@@ -358,7 +1994,7 @@ async function runCheck(o) {
|
|
|
358
1994
|
writeFileSync(outPath, source);
|
|
359
1995
|
if (!o.json) o.stdout(`\nRegression test written to ${relative(o.cwd, outPath) || outPath}\n`);
|
|
360
1996
|
}
|
|
361
|
-
if (verdict.kind !== "VIOLATED" && specs.some((v) => v.kind === "REFUTED")) return exitCodes.VIOLATED;
|
|
1997
|
+
if (verdict.kind !== "VIOLATED" && specs.some((v) => v.kind === "REFUTED" || v.kind === "CONFLICT")) return exitCodes.VIOLATED;
|
|
362
1998
|
return exitCodes[verdict.kind];
|
|
363
1999
|
} finally {
|
|
364
2000
|
if (!o.keep) rmSync(workDir, {
|
|
@@ -379,13 +2015,15 @@ Options:
|
|
|
379
2015
|
--max-runs <n> cap on exploration runs in addition to the scenario's time budget
|
|
380
2016
|
--budget-ms <n> replace the scenario's time budget (with --max-runs, the run cap decides)
|
|
381
2017
|
--exhaustive run every schedule within the bounds once (with partial-order reduction)
|
|
2018
|
+
--prover <names> also run the PROVEN rung with these engines on the scenario's specs
|
|
2019
|
+
(comma-separated; known: lean)
|
|
382
2020
|
--json print the versioned JSON report instead of text
|
|
383
2021
|
--out <path> where to write the regression test on a violation
|
|
384
2022
|
--no-regression do not write a regression test
|
|
385
2023
|
--expect-violation write a regression test that asserts the violation (for corpora)
|
|
386
2024
|
--keep keep the generated .eutaxy/ files
|
|
387
2025
|
|
|
388
|
-
Exit codes: 0 BOUNDED, 1 VIOLATED or a REFUTED spec, 2 UNSUPPORTED, 3 error.
|
|
2026
|
+
Exit codes: 0 BOUNDED, 1 VIOLATED or a REFUTED or CONFLICT spec, 2 UNSUPPORTED, 3 error.
|
|
389
2027
|
`;
|
|
390
2028
|
async function main(argv, io) {
|
|
391
2029
|
const { positionals, flags } = parseArgs(argv, [
|
|
@@ -423,9 +2061,11 @@ async function main(argv, io) {
|
|
|
423
2061
|
io.stderr(`--budget-ms must be a positive integer, got ${JSON.stringify(budgetText)}\n`);
|
|
424
2062
|
return exitCodes.error;
|
|
425
2063
|
}
|
|
2064
|
+
const provers = (str("prover") ?? "").split(",").map((n) => n.trim()).filter((n) => n.length > 0);
|
|
426
2065
|
return runCheck({
|
|
427
2066
|
scenario,
|
|
428
2067
|
cwd: io.cwd,
|
|
2068
|
+
...provers.length > 0 ? { provers } : {},
|
|
429
2069
|
...str("wrangler") ? { wrangler: str("wrangler") } : {},
|
|
430
2070
|
...str("seed") ? { seed: str("seed") } : {},
|
|
431
2071
|
...maxRuns === void 0 ? {} : { maxRuns },
|
|
@@ -3384,7 +5024,7 @@ async function checkInWorkerd(input) {
|
|
|
3384
5024
|
} finally {
|
|
3385
5025
|
for (const o of observers) o.restore();
|
|
3386
5026
|
}
|
|
3387
|
-
const specs = selected.flatMap((m, i) => checkSpecModule(m.key, m.specs, m.predicates, observers[i]));
|
|
5027
|
+
const specs = selected.flatMap((m, i) => checkSpecModule(m.key, m.specs, m.predicates, observers[i], { tested: { seed: input.seed } }));
|
|
3388
5028
|
return {
|
|
3389
5029
|
report: JSON.parse(renderJson(verdict, specs)),
|
|
3390
5030
|
...transportBase,
|
|
@@ -3396,4 +5036,4 @@ async function checkInWorkerd(input) {
|
|
|
3396
5036
|
}
|
|
3397
5037
|
export { snapshotD1 as A, r2Rows as C, workflow as D, unique as E, expectHolds as M, main as N, workflowRows as O, cloudflareRegressionTest as P, r2Op as S, refines as T, httpResponse as _, d1Param as a, queueAck as b, d1Schema as c, durableObject as d, durableObjectRows as f, http as g, fetchCall as h, atLeastOncePerMessage as i, check as j, workflowStep as k, d1Write as l, external as m, runDifferential as n, d1Read as o, everyRow as p, createCloudflarePlatform as r, d1Rows as s, checkInWorkerd as t, defineScenario as u, implies as v, references as w, r2Bucket as x, queue as y };
|
|
3398
5038
|
|
|
3399
|
-
//# sourceMappingURL=src-
|
|
5039
|
+
//# sourceMappingURL=src-C43iUZgr.mjs.map
|