eutaxy 0.17.2 → 0.19.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.
Files changed (74) hide show
  1. package/README.md +15 -12
  2. package/dist/aws.d.mts +2 -2
  3. package/dist/aws.mjs +3 -2
  4. package/dist/aws.mjs.map +1 -1
  5. package/dist/bin.mjs +1 -1
  6. package/dist/check-zkHLdWyf.mjs +1281 -0
  7. package/dist/check-zkHLdWyf.mjs.map +1 -0
  8. package/dist/cli-CNAKqV9R.mjs +297 -0
  9. package/dist/cli-CNAKqV9R.mjs.map +1 -0
  10. package/dist/cli.d.mts.map +1 -1
  11. package/dist/cli.mjs +1 -1
  12. package/dist/cloudflare.d.mts +56 -5
  13. package/dist/cloudflare.d.mts.map +1 -1
  14. package/dist/cloudflare.mjs +6417 -3
  15. package/dist/cloudflare.mjs.map +1 -0
  16. package/dist/{delivery-invariants-DO3j1mmD.mjs → delivery-invariants-BJDck0K8.mjs} +2 -2
  17. package/dist/{delivery-invariants-DO3j1mmD.mjs.map → delivery-invariants-BJDck0K8.mjs.map} +1 -1
  18. package/dist/{delivery-invariants-D7DI7i8x.d.mts → delivery-invariants-C3GXJIbg.d.mts} +2 -2
  19. package/dist/{delivery-invariants-D7DI7i8x.d.mts.map → delivery-invariants-C3GXJIbg.d.mts.map} +1 -1
  20. package/dist/draft-DEUDffHa.mjs +467 -0
  21. package/dist/draft-DEUDffHa.mjs.map +1 -0
  22. package/dist/{src-fxWc6oGc.mjs → generate-TBJM3-2P.mjs} +3 -574
  23. package/dist/generate-TBJM3-2P.mjs.map +1 -0
  24. package/dist/index.d.mts +45 -37
  25. package/dist/index.d.mts.map +1 -1
  26. package/dist/index.mjs +7 -4
  27. package/dist/index.mjs.map +1 -1
  28. package/dist/install-DkzpGA5D.mjs +611 -0
  29. package/dist/install-DkzpGA5D.mjs.map +1 -0
  30. package/dist/{explore-CkKiOuz6.d.mts → ir-KpC2epGn.d.mts} +88 -53
  31. package/dist/ir-KpC2epGn.d.mts.map +1 -0
  32. package/dist/keys-xtanNmuR.mjs +111 -0
  33. package/dist/keys-xtanNmuR.mjs.map +1 -0
  34. package/dist/mcp-B64Ko6y7.mjs +539 -0
  35. package/dist/mcp-B64Ko6y7.mjs.map +1 -0
  36. package/dist/{platform-D4hlJjm3.d.mts → platform-Cs9V9t2k.d.mts} +92 -11
  37. package/dist/platform-Cs9V9t2k.d.mts.map +1 -0
  38. package/dist/pool-CXN4CwGY.mjs +61 -0
  39. package/dist/pool-CXN4CwGY.mjs.map +1 -0
  40. package/dist/{provers-DS44OeEm.mjs → provers-D8VaY_OM.mjs} +18 -2
  41. package/dist/provers-D8VaY_OM.mjs.map +1 -0
  42. package/dist/reader-B9FSoEYW.mjs +1 -0
  43. package/dist/reader-Cz6_bLf6.mjs +3774 -0
  44. package/dist/reader-Cz6_bLf6.mjs.map +1 -0
  45. package/dist/report-_Vzavqg0.mjs +310 -0
  46. package/dist/report-_Vzavqg0.mjs.map +1 -0
  47. package/dist/src-B2DpVbMN.mjs +2 -0
  48. package/dist/src-BFGTvuA_.mjs +1235 -0
  49. package/dist/src-BFGTvuA_.mjs.map +1 -0
  50. package/dist/src-BtLZPRyG.mjs +120 -0
  51. package/dist/src-BtLZPRyG.mjs.map +1 -0
  52. package/dist/src-CB8DcvsK.mjs +1 -0
  53. package/dist/src-COuquJvI.mjs +269 -0
  54. package/dist/src-COuquJvI.mjs.map +1 -0
  55. package/dist/src-Chn-m_r1.mjs +1082 -0
  56. package/dist/src-Chn-m_r1.mjs.map +1 -0
  57. package/dist/src-DwYD3QQJ.mjs +346 -0
  58. package/dist/src-DwYD3QQJ.mjs.map +1 -0
  59. package/dist/{src-D_hHC_-3.mjs → src-Dx4QvrQb.mjs} +945 -548
  60. package/dist/src-Dx4QvrQb.mjs.map +1 -0
  61. package/dist/toolchain-DWfymxAJ.mjs +80 -0
  62. package/dist/toolchain-DWfymxAJ.mjs.map +1 -0
  63. package/dist/verdict-evEM5Gxx.mjs +12 -0
  64. package/dist/verdict-evEM5Gxx.mjs.map +1 -0
  65. package/package.json +4 -1
  66. package/dist/cli-B0Gs2mhT.mjs +0 -9445
  67. package/dist/cli-B0Gs2mhT.mjs.map +0 -1
  68. package/dist/explore-CkKiOuz6.d.mts.map +0 -1
  69. package/dist/platform-D4hlJjm3.d.mts.map +0 -1
  70. package/dist/provers-DS44OeEm.mjs.map +0 -1
  71. package/dist/src-D_hHC_-3.mjs.map +0 -1
  72. package/dist/src-fxWc6oGc.mjs.map +0 -1
  73. package/dist/workerd-DhrzU6AZ.mjs +0 -6300
  74. package/dist/workerd-DhrzU6AZ.mjs.map +0 -1
@@ -0,0 +1,1235 @@
1
+ import "./src-DwYD3QQJ.mjs";
2
+ import { n as proofsOf, r as unknownOutcome } from "./provers-D8VaY_OM.mjs";
3
+ import { r as host, t as cacheDir } from "./toolchain-DWfymxAJ.mjs";
4
+ import { S as hasLoneSurrogate, a as readForEngine, b as children, h as builtinsAssumption, i as outsideProofs, l as renameVars, m as typeOf, o as readArrowBody, r as engineGap, v as readBinderType, w as listKinds, y as OutsideSubset } from "./reader-Cz6_bLf6.mjs";
5
+ import { createHash } from "node:crypto";
6
+ import { existsSync, mkdtempSync, readFileSync, readdirSync, readlinkSync, rmSync, writeFileSync } from "node:fs";
7
+ import { homedir, tmpdir } from "node:os";
8
+ import { basename, join, relative, sep } from "node:path";
9
+ import { spawn } from "node:child_process";
10
+ // packages/prover-lean/src/elan.ts
11
+ /**
12
+ * Lean's toolchain comes through elan, Lean's own toolchain manager. This
13
+ * file holds what `eutaxy prover install lean` and the engine share about
14
+ * it: the pinned elan installer (`elanDownloads`, fetched only when no elan
15
+ * is on the machine), where Eutaxy keeps an elan of its own (`elanHome`,
16
+ * inside Eutaxy's cache), the elans the engine and the command look for
17
+ * (`elanCandidates`), and the digest of the pinned toolchain's files
18
+ * (`leanDigests`, `toolchainDigest`), which the command checks after elan
19
+ * has installed it, since elan does not check the toolchain it downloads
20
+ * against a pinned checksum.
21
+ */
22
+ /** The elan release whose installer the command fetches when the machine has no elan. */
23
+ const elanVersion = "4.2.4";
24
+ const elanRelease = `https://github.com/leanprover/elan/releases/download/v${elanVersion}`;
25
+ const elanFile = (name, sha256, bytes) => {
26
+ const installer = name.endsWith(".zip") ? "elan-init.exe" : "elan-init";
27
+ return {
28
+ file: name,
29
+ url: `${elanRelease}/${name}`,
30
+ sha256,
31
+ bytes,
32
+ entries: { [installer]: installer }
33
+ };
34
+ };
35
+ /**
36
+ * The upstream elan installer for each platform, as published on elan's
37
+ * GitHub release with the checksums it reports; a test holds the file
38
+ * names to `elanVersion`. The installer links only system libraries.
39
+ */
40
+ const elanDownloads = {
41
+ name: "elan",
42
+ version: elanVersion,
43
+ executable: "elan-init",
44
+ files: {
45
+ "linux-x64": elanFile("elan-x86_64-unknown-linux-gnu.tar.gz", "42b94d4244e8353142c456ec0e4ca6528fd898a6c604d4059f494e706e431f63", 4996571),
46
+ "linux-arm64": elanFile("elan-aarch64-unknown-linux-gnu.tar.gz", "05febd124d84ebf994b2e7479922a5650b1e950c17ae3bd1ddd776b65bb72bf9", 5131114),
47
+ "darwin-x64": elanFile("elan-x86_64-apple-darwin.tar.gz", "8a340b309d8ed2e96f930761fa223b3af57a38f5d253b53ac90293c9516f8cd4", 2330818),
48
+ "darwin-arm64": elanFile("elan-aarch64-apple-darwin.tar.gz", "7ad829861392c718dfebde3a83b5c8508df47be02af68894b094b0b3952616e5", 2190845),
49
+ "win32-x64": elanFile("elan-x86_64-pc-windows-msvc.zip", "fad2e980a191c15884cc1d80d170ffc5fa84f3774541020145b66d1a644c6111", 2508099)
50
+ }
51
+ };
52
+ /** Where Eutaxy's own elan keeps itself and its toolchains: `<cache>/elan`. */
53
+ function elanHome(h) {
54
+ return join(cacheDir(h), "elan");
55
+ }
56
+ /**
57
+ * The elans to try, in order: Eutaxy's own in the cache, then the one on
58
+ * the PATH, then the one in elan's home (`ELAN_HOME`, else `~/.elan`).
59
+ */
60
+ function elanCandidates(h) {
61
+ const exe = h.platform === "win32" ? "elan.exe" : "elan";
62
+ const own = elanHome(h);
63
+ const home = h.env["ELAN_HOME"] || join(h.home || homedir(), ".elan");
64
+ return [
65
+ {
66
+ command: join(own, "bin", exe),
67
+ env: { ELAN_HOME: own }
68
+ },
69
+ { command: "elan" },
70
+ { command: join(home, "bin", exe) }
71
+ ];
72
+ }
73
+ /**
74
+ * The pinned toolchain's `toolchainDigest`, per platform: computed over
75
+ * Lean's GitHub release file for that platform, checked against the
76
+ * checksum the release reports, and unpacked. elan installs exactly that
77
+ * release (on macOS arm64 the digest of an elan-installed toolchain was
78
+ * checked to equal it), so a toolchain elan installed whose digest differs
79
+ * is not the pinned one.
80
+ */
81
+ const leanDigests = {
82
+ "linux-x64": "d6bb6c4de1fce52bc5d88ff52f7fcf7d347ee5b3ba7d187de775ccf915714c35",
83
+ "linux-arm64": "1bcaf2cf93006e3017a07234e3a33ba8bd1dec404e7dc0e4c202111b0bf2be41",
84
+ "darwin-x64": "b817cf3c90432b774405bad998bad5985f0ef9594d1c31aeddb3df6479c1bd0c",
85
+ "darwin-arm64": "2a31778d0185a17655be5f97e6e930dd0ece0d1db9f41a2825f500b3ca8c5c0a",
86
+ "win32-x64": "441877e59afc80b7af1f1b6fc3db64b2c947d581de26a040486387aa4ec7a3cb"
87
+ };
88
+ /**
89
+ * A digest of everything under a toolchain's directory: one line per file
90
+ * (`<sha256> <path>`) and per link (`-> <target> <path>`), paths relative
91
+ * and with `/`, sorted, the whole hashed. Directories count only through
92
+ * what they hold.
93
+ */
94
+ function toolchainDigest(prefix) {
95
+ const lines = [];
96
+ let files = 0;
97
+ let bytes = 0;
98
+ for (const entry of readdirSync(prefix, {
99
+ recursive: true,
100
+ withFileTypes: true
101
+ })) {
102
+ const at = join(entry.parentPath, entry.name);
103
+ const path = relative(prefix, at).split(sep).join("/");
104
+ if (entry.isSymbolicLink()) lines.push([path, `-> ${readlinkSync(at)} ${path}`]);
105
+ else if (entry.isFile()) {
106
+ const data = readFileSync(at);
107
+ files++;
108
+ bytes += data.length;
109
+ lines.push([path, `${createHash("sha256").update(data).digest("hex")} ${path}`]);
110
+ }
111
+ }
112
+ lines.sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
113
+ return {
114
+ digest: createHash("sha256").update(`${lines.map(([, line]) => line).join("\n")}\n`).digest("hex"),
115
+ files,
116
+ bytes
117
+ };
118
+ }
119
+ // packages/prover-lean/src/emit.ts
120
+ /**
121
+ * Lean 4 for a module in the subset and the properties on it. The
122
+ * module's record types become structures, its functions definitions over
123
+ * `Int`, `Bool` and `String`, each property a theorem whose statement is
124
+ * the claim over its binders, with the precondition as a hypothesis.
125
+ * Booleans stay `Bool` in terms, as in TypeScript, and become propositions
126
+ * with `= true` where a statement needs one; comparisons are `decide`d.
127
+ * Every theorem is closed by one tactic script, except where a proof is
128
+ * supplied beside the spec file (`supplied.ts`): then the statement is
129
+ * fixed as a definition first, and the supplied tactics must prove it.
130
+ */
131
+ /**
132
+ * TypeScript names as Lean identifiers that can clash with nothing Lean
133
+ * defines and not with each other: functions get `f_`, record types `R_`,
134
+ * variables `v_`, theorems `t_`. The schemes differ in their first letter,
135
+ * so no two names from different kinds coincide whatever the author
136
+ * wrote (`ts_f` and `f_` would, under suffixing), and Lean's prelude has
137
+ * no names of these shapes, so a function called `decide` or a parameter
138
+ * called `max` stays what the author meant.
139
+ */
140
+ const ident = {
141
+ fn: (name) => quote(`f_${name}`),
142
+ record: (name) => quote(`R_${name}`),
143
+ variable: (name) => quote(`v_${name}`),
144
+ field: (name) => leanKeywords.has(name) ? `«${name}»` : quote(name)
145
+ };
146
+ /** Lean's keywords, which a field name may coincide with. */
147
+ 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(" "));
148
+ function quote(name) {
149
+ const escaped = name.replace(/%/g, "%25").replace(/«/g, "%ab").replace(/»/g, "%bb");
150
+ return /^[A-Za-z_][A-Za-z0-9_]*$/.test(escaped) ? escaped : `«${escaped}»`;
151
+ }
152
+ function leanType(t) {
153
+ switch (t.kind) {
154
+ case "int": return "Int";
155
+ case "bool": return "Bool";
156
+ case "string": return "String";
157
+ case "record": return ident.record(t.name);
158
+ case "list": return `(List ${leanType(t.element)})`;
159
+ case "nothing": return fail("the element type of an empty array, which nothing gives");
160
+ case "nullable":
161
+ case "union":
162
+ case "null": return fail(`a ${t.kind} type, which the Lean engine does not take yet`);
163
+ }
164
+ }
165
+ function emitRecord(r) {
166
+ return [
167
+ `structure ${ident.record(r.name)} where`,
168
+ ...r.fields.map((f) => ` ${ident.field(f.name)} : ${leanType(f.type)}`),
169
+ " deriving Repr, DecidableEq"
170
+ ].join("\n");
171
+ }
172
+ function env(module) {
173
+ return {
174
+ module,
175
+ ctx: {
176
+ records: new Map(module.records.map((r) => [r.name, r])),
177
+ unions: module.unions,
178
+ signatures: new Map(module.functions.map((f) => [f.name, {
179
+ params: f.params,
180
+ returns: f.returns
181
+ }]))
182
+ }
183
+ };
184
+ }
185
+ const divisionOutside = "division other than Math.floor(x / c) with c a positive integer constant: this engine models numbers as integers, which / leaves (the SMT engine takes it)";
186
+ /** Whether an expression divides other than as Math.floor(x / c), c a positive integer constant. */
187
+ function dividesOutside(e) {
188
+ if (e.kind === "floor" && e.operand.kind === "binary" && e.operand.op === "/") {
189
+ const c = integerValue(e.operand.right);
190
+ if (c !== void 0 && c > 0n) return dividesOutside(e.operand.left);
191
+ }
192
+ if (e.kind === "binary" && e.op === "/") return true;
193
+ return children(e).some(dividesOutside);
194
+ }
195
+ /** The value of an integer expression built from literals by + - * and negation, if it is one. */
196
+ function integerValue(e) {
197
+ if (e.kind === "int") return BigInt(e.value);
198
+ if (e.kind === "neg") {
199
+ const v = integerValue(e.operand);
200
+ return v === void 0 ? void 0 : -v;
201
+ }
202
+ if (e.kind !== "binary") return void 0;
203
+ const l = integerValue(e.left);
204
+ const r = integerValue(e.right);
205
+ if (l === void 0 || r === void 0) return void 0;
206
+ if (e.op === "+") return l + r;
207
+ if (e.op === "-") return l - r;
208
+ if (e.op === "*") return l * r;
209
+ }
210
+ const fail = (message) => {
211
+ throw new OutsideSubset(message, 0);
212
+ };
213
+ /** A term of the expression's TypeScript type: `Int`, `Bool`, `String` or a structure. */
214
+ function term(e, scope, env) {
215
+ const t = (x) => term(x, scope, env);
216
+ switch (e.kind) {
217
+ case "int": return `(${e.value} : Int)`;
218
+ case "bool": return e.value ? "true" : "false";
219
+ case "string": return leanString(e.value);
220
+ case "var":
221
+ if (env.cons?.list === e.name) return `(${env.cons.head} :: ${env.cons.tail})`;
222
+ return ident.variable(e.name);
223
+ case "null":
224
+ case "narrow": return fail("null, which the Lean engine does not take yet");
225
+ case "narrowTag": return fail("a union, which the Lean engine does not take yet");
226
+ case "neg": return `(-${t(e.operand)})`;
227
+ case "not": return `(!${t(e.operand)})`;
228
+ case "isInteger":
229
+ typeOf(e.operand, scope, env.ctx, fail);
230
+ t(e.operand);
231
+ return "true";
232
+ case "floor": {
233
+ const o = e.operand;
234
+ if (o.kind !== "binary" || o.op !== "/") return t(o);
235
+ const c = integerValue(o.right);
236
+ if (c === void 0 || c <= 0n) fail(divisionOutside);
237
+ return `(${t(o.left)} / (${c} : Int))`;
238
+ }
239
+ case "binary":
240
+ switch (e.op) {
241
+ case "+": {
242
+ const lt = typeOf(e.left, scope, env.ctx, fail);
243
+ return `(${t(e.left)} ${lt.kind === "string" ? "++" : "+"} ${t(e.right)})`;
244
+ }
245
+ case "-":
246
+ case "*": return `(${t(e.left)} ${e.op} ${t(e.right)})`;
247
+ case "/": return fail(divisionOutside);
248
+ case "<":
249
+ case ">": return `(decide (${t(e.left)} ${e.op} ${t(e.right)}))`;
250
+ case "<=": return `(decide (${t(e.left)} ≤ ${t(e.right)}))`;
251
+ case ">=": return `(decide (${t(e.left)} ≥ ${t(e.right)}))`;
252
+ case "===":
253
+ case "!==":
254
+ if (typeOf(e.left, scope, env.ctx, fail).kind === "record") fail(`${e.op} on records compares references in JavaScript; compare their fields instead`);
255
+ return `(decide (${t(e.left)} ${e.op === "===" ? "=" : "≠"} ${t(e.right)}))`;
256
+ case "&&": return `(${t(e.left)} && ${t(e.right)})`;
257
+ case "||": return `(${t(e.left)} || ${t(e.right)})`;
258
+ }
259
+ break;
260
+ case "cond": return `(if ${t(e.test)} = true then ${t(e.ifTrue)} else ${t(e.ifFalse)})`;
261
+ case "call": return `(${ident.fn(e.callee)}${e.args.map((a) => ` ${t(a)}`).join("")})`;
262
+ case "field":
263
+ if (typeOf(e.object, scope, env.ctx, fail).kind === "list") return `(Int.ofNat (List.length ${t(e.object)}))`;
264
+ return `${t(e.object)}.${ident.field(e.field)}`;
265
+ case "record": {
266
+ const type = typeOf(e, scope, env.ctx, fail);
267
+ const name = type.kind === "record" ? ident.record(type.name) : fail("a record literal of no record type");
268
+ return `({ ${e.fields.map((f) => `${ident.field(f.name)} := ${t(f.value)}`).join(", ")} } : ${name})`;
269
+ }
270
+ case "let": {
271
+ const inner = new Map(scope);
272
+ const bound = e.type ?? typeOf(e.value, scope, env.ctx, fail);
273
+ inner.set(e.name, bound);
274
+ const annotated = e.type ? ` : ${leanType(e.type)}` : "";
275
+ return `(let ${ident.variable(e.name)}${annotated} := ${t(e.value)}; ${term(e.body, inner, env)})`;
276
+ }
277
+ case "list":
278
+ if (e.items.length === 0 && !e.rest) return "[]";
279
+ if (!e.rest) return `[${e.items.map(t).join(", ")}]`;
280
+ return `(${[...e.items.map(t), t(e.rest)].join(" :: ")})`;
281
+ case "tail":
282
+ if (e.list.kind === "var" && env.cons?.list === e.list.name) return env.cons.tail;
283
+ return `(List.tail ${t(e.list)})`;
284
+ case "headOr":
285
+ if (e.list.kind === "var" && env.cons?.list === e.list.name) return env.cons.head;
286
+ return `(List.headD ${t(e.list)} ${t(e.fallback)})`;
287
+ case "iterate": {
288
+ const listType = typeOf(e.list, scope, env.ctx, fail);
289
+ if (listType.kind !== "list") fail(`${e.op} on a ${listType.kind}`);
290
+ const inner = new Map(scope);
291
+ inner.set(e.item, listType.element);
292
+ if (e.index !== void 0) inner.set(e.index, { kind: "int" });
293
+ const body = term(e.body, inner, env);
294
+ const nat = e.index === void 0 ? "" : quote(`nv_${e.index}`);
295
+ const fn = e.index === void 0 ? `(fun ${ident.variable(e.item)} => ${body})` : `(fun (${ident.variable(e.item)}, ${nat}) => let ${ident.variable(e.index)} := Int.ofNat ${nat}; ${body})`;
296
+ const list = e.index === void 0 ? t(e.list) : `(List.zipIdx ${t(e.list)})`;
297
+ if (e.op === "map") return `(List.map ${fn} ${list})`;
298
+ if (e.op === "flatMap") return `(List.flatMap ${fn} ${list})`;
299
+ return `(${e.op === "every" ? "List.all" : "List.any"} ${list} ${fn})`;
300
+ }
301
+ case "fold": {
302
+ const listType = typeOf(e.list, scope, env.ctx, fail);
303
+ if (listType.kind !== "list") fail(`reduce on a ${listType.kind}`);
304
+ const inner = new Map(scope);
305
+ inner.set(e.acc, typeOf(e, scope, env.ctx, fail));
306
+ inner.set(e.item, listType.element);
307
+ return `(List.foldl (fun ${ident.variable(e.acc)} ${ident.variable(e.item)} => ${term(e.body, inner, env)}) ${t(e.init)} ${t(e.list)})`;
308
+ }
309
+ }
310
+ }
311
+ function emitFunction(f, module) {
312
+ const e = env(module);
313
+ const scope = new Map(f.params.map((p) => [p.name, p.type]));
314
+ const params = f.params.map((p) => `(${ident.variable(p.name)} : ${leanType(p.type)})`).join(" ");
315
+ const head = `def ${ident.fn(f.name)} ${params} : ${leanType(f.returns)} :=`;
316
+ if (f.structural === void 0 || f.body.kind !== "cond") return `${head}\n ${term(f.body, scope, e)}`;
317
+ const list = f.params[f.structural].name;
318
+ const cons = {
319
+ list,
320
+ head: quote(`vh_${list}`),
321
+ tail: quote(`vt_${list}`)
322
+ };
323
+ return [
324
+ head,
325
+ ` match ${ident.variable(list)} with`,
326
+ ` | [] => ${term(f.body.ifTrue, scope, e)}`,
327
+ ` | ${cons.head} :: ${cons.tail} => ${term(f.body.ifFalse, scope, {
328
+ ...e,
329
+ cons
330
+ })}`
331
+ ].join("\n");
332
+ }
333
+ /** What this engine does not take of binder types: nullable types and unions, which the SMT engine takes. */
334
+ const binderRule = {
335
+ nullable: "nullable types are not in the engine's subset yet",
336
+ union: "unions are not in the engine's subset yet"
337
+ };
338
+ /**
339
+ * The subset type a binder ranges over, or `OutsideSubset`: `number` is
340
+ * `Int` (the engine's integer model, an assumption every PROVEN carries),
341
+ * a union of string literals is `String` (the proof covers every string,
342
+ * more than the type admits), a record is the module's structure of that
343
+ * name, an array a list. Nullable types, tagged unions, bigint and whatever
344
+ * the reader could not read are outside. Read by the reader's
345
+ * `readBinderType` under `binderRule`.
346
+ */
347
+ function binderType(name, t, module) {
348
+ return readBinderType(name, t, module, binderRule);
349
+ }
350
+ /** An arrow of the spec file as a Bool term over the binders, its own parameter names renamed to theirs. */
351
+ function arrowTerm(arrow, what, property, types, e) {
352
+ try {
353
+ return arrowTermAt(arrow, what, property, types, e);
354
+ } catch (err) {
355
+ if (!(err instanceof OutsideSubset)) throw err;
356
+ throw new OutsideSubset(`${what} (spec file line ${arrow.line}): ${err.message}`, arrow.line);
357
+ }
358
+ }
359
+ function arrowTermAt(arrow, what, property, types, e) {
360
+ const binders = property.binders;
361
+ const scope = /* @__PURE__ */ new Map();
362
+ const names = /* @__PURE__ */ new Map();
363
+ arrow.params.forEach((p, i) => {
364
+ const binder = binders[i];
365
+ const type = types[i];
366
+ if (p === null) fail(`a destructured parameter in ${what}`);
367
+ if (!binder || !type) fail(`${what} takes more parameters than the function has`);
368
+ scope.set(p, type);
369
+ names.set(p, binder.name);
370
+ });
371
+ const aliases = new Map(property.imports.map((i) => [i.local, i.fn]));
372
+ const read = readArrowBody(arrow, scope, e.module, aliases);
373
+ const t = typeOf(read, scope, e.ctx, fail);
374
+ if (t.kind !== "bool") fail(`${what} is not boolean (a ${t.kind === "record" ? t.name : t.kind})`);
375
+ return term(renameVars(read, names), new Map(binders.map((b, i) => [b.name, types[i]])), e);
376
+ }
377
+ /** The statement and how many hypotheses stand before the claim (the tactic script introduces them by name). */
378
+ function stated(property, module) {
379
+ if (property.kind !== "forall" || !property.ensures) fail("not a forall property");
380
+ const e = env(module);
381
+ const types = property.binders.map((b) => binderType(b.name, b.type, module));
382
+ const binders = property.binders.map((b, i) => `(${ident.variable(b.name)} : ${leanType(types[i])})`).join(" ");
383
+ const hyps = property.when ? [`(${arrowTerm(property.when, "when", property, types, e)} = true)`] : [];
384
+ const claim = `(${arrowTerm(property.ensures, "ensures", property, types, e)} = true)`;
385
+ const body = [...hyps, claim].join(" →\n ");
386
+ return {
387
+ text: binders === "" ? body : `∀ ${binders},\n ${body}`,
388
+ hypotheses: hyps.length
389
+ };
390
+ }
391
+ /**
392
+ * The tactic script every theorem is closed by. Booleans become
393
+ * propositions first, while the `Decidable` instances in the statement
394
+ * still match their propositions (unfolding under `decide` first leaves
395
+ * them stale and stops `simp`); Bool binders are cased, so boolean claims
396
+ * are decided by enumeration; then the module's definitions unfold, each
397
+ * conditional splits, and linear integer arithmetic (`omega`) closes what
398
+ * remains. Nothing here is specific to a property; what Lean checks is
399
+ * the statement.
400
+ */
401
+ function tactics(module, property, hypotheses) {
402
+ const defs = module.functions.map((f) => ident.fn(f.name)).join(", ");
403
+ const names = property.binders.map((b) => ident.variable(b.name));
404
+ const hyps = Array.from({ length: hypotheses }, (_, i) => `h${i}_`);
405
+ const bools = property.binders.filter((b) => b.type.kind === "boolean" || b.type.kind === "literal" && typeof b.type.value === "boolean").map((b) => ident.variable(b.name));
406
+ const introduced = [...names, ...hyps];
407
+ return [
408
+ ...introduced.length > 0 ? [` intro ${introduced.join(" ")}`] : [],
409
+ ...bools.length > 0 ? [` ${bools.map((b) => `cases ${b}`).join(" <;> ")}`] : [],
410
+ " all_goals (try simp_all)",
411
+ ` all_goals (try simp only [${defs}] at *)`,
412
+ " all_goals (repeat' (split <;> simp_all))",
413
+ " all_goals (try simp_all)",
414
+ " all_goals (first | decide | trivial | omega)"
415
+ ].join("\n");
416
+ }
417
+ /** A Lean-safe theorem name: unique by position, readable by the function's and property's names. */
418
+ function theoremName(index, fn, property) {
419
+ return `t${index}_${fn}_${property}`.replace(/[^A-Za-z0-9_]/g, "_");
420
+ }
421
+ /** A tactic block at the indentation a `by` takes: its common indentation stripped, two spaces put back. */
422
+ function indented(block) {
423
+ const lines = block.split("\n");
424
+ const widths = lines.filter((l) => l.trim() !== "").map((l) => /^ */.exec(l)?.[0].length ?? 0);
425
+ const common = widths.length > 0 ? Math.min(...widths) : 0;
426
+ return lines.map((l) => l.trim() === "" ? "" : ` ${l.slice(common)}`).join("\n");
427
+ }
428
+ /**
429
+ * The whole file: structures, definitions, one theorem per property, any
430
+ * extra lines (translation checks), then the properties with supplied
431
+ * proofs: each statement fixed as a definition before any supplied text,
432
+ * the supplied lemmas, each theorem proving its definition with the
433
+ * supplied tactics, and `#print axioms` for each.
434
+ */
435
+ function emitModule(module, properties, extra = [], supplied) {
436
+ const parts = [
437
+ "-- Generated by Eutaxy's first-party engine from the module and its spec file; the theorems are its properties.",
438
+ "set_option linter.unusedSimpArgs false",
439
+ "set_option linter.unusedVariables false",
440
+ ...module.records.map(emitRecord),
441
+ ...module.functions.map((f) => emitFunction(f, module))
442
+ ];
443
+ const theorems = [];
444
+ const skipped = [];
445
+ const later = [];
446
+ for (const { function: fn, property } of properties) {
447
+ let body;
448
+ try {
449
+ body = stated(property, module);
450
+ } catch (err) {
451
+ if (!(err instanceof OutsideSubset)) throw err;
452
+ skipped.push({
453
+ function: fn,
454
+ property: property.name,
455
+ reason: err.message
456
+ });
457
+ continue;
458
+ }
459
+ const name = theoremName(theorems.length + skipped.length + later.length, fn, property.name);
460
+ const proof = supplied?.proofs.get(property.name);
461
+ if (proof !== void 0) {
462
+ later.push({
463
+ fn,
464
+ property: property.name,
465
+ name,
466
+ statement: body.text,
467
+ proof
468
+ });
469
+ continue;
470
+ }
471
+ const text = `theorem ${name} :\n ${body.text} := by\n${tactics(module, property, body.hypotheses)}`;
472
+ const from = parts.join("\n\n").split("\n").length + 2;
473
+ parts.push(text);
474
+ theorems.push({
475
+ function: fn,
476
+ property: property.name,
477
+ name,
478
+ from,
479
+ to: from + text.split("\n").length - 1
480
+ });
481
+ }
482
+ parts.push(...extra);
483
+ const lineAfter = () => parts.join("\n\n").split("\n").length + 2;
484
+ let lemmas;
485
+ if (later.length > 0) {
486
+ for (const l of later) parts.push(`def s_${l.name} : Prop :=\n ${l.statement}`);
487
+ if (supplied && supplied.lemmas !== "") {
488
+ const from = lineAfter();
489
+ parts.push(supplied.lemmas);
490
+ lemmas = {
491
+ from,
492
+ to: from + supplied.lemmas.split("\n").length - 1
493
+ };
494
+ }
495
+ const ownProofs = [];
496
+ for (const l of later) {
497
+ const text = `theorem ${l.name} : s_${l.name} := by\n unfold s_${l.name}\n${indented(l.proof)}`;
498
+ const from = lineAfter();
499
+ parts.push(text);
500
+ ownProofs.push({
501
+ function: l.fn,
502
+ property: l.property,
503
+ name: l.name,
504
+ from,
505
+ to: from + text.split("\n").length - 1,
506
+ supplied: true
507
+ });
508
+ }
509
+ for (const t of ownProofs) {
510
+ const typeLine = lineAfter();
511
+ parts.push(`#check @${t.name}`);
512
+ const axiomsLine = lineAfter();
513
+ parts.push(`#print axioms ${t.name}`);
514
+ theorems.push({
515
+ ...t,
516
+ axiomsLine,
517
+ typeLine
518
+ });
519
+ }
520
+ }
521
+ return {
522
+ source: `${parts.join("\n\n")}\n`,
523
+ theorems,
524
+ skipped,
525
+ ...lemmas ? { lemmas } : {}
526
+ };
527
+ }
528
+ /**
529
+ * A JavaScript string as a Lean string literal: `"` and `\` escaped, control
530
+ * characters as `\xHH`, everything else written as it is (Lean source is
531
+ * UTF-8). A lone surrogate has no Lean character and is refused.
532
+ */
533
+ function leanString(value) {
534
+ if (hasLoneSurrogate(value)) fail("a string with a lone surrogate, which Lean's strings cannot hold");
535
+ let out = "\"";
536
+ for (const c of value) {
537
+ const code = c.codePointAt(0);
538
+ if (c === "\"") out += "\\\"";
539
+ else if (c === "\\") out += "\\\\";
540
+ else if (code < 32 || code === 127) out += `\\x${code.toString(16).padStart(2, "0")}`;
541
+ else out += c;
542
+ }
543
+ return `${out}"`;
544
+ }
545
+ // packages/prover-lean/src/lean.ts
546
+ /**
547
+ * Running Lean over a process boundary. The engine is pinned to one Lean
548
+ * release, looked for through elan (Lean's toolchain manager), asked for it
549
+ * by name: Eutaxy's own elan in its cache first (where `eutaxy prover
550
+ * install lean` puts one when the machine has none), then the user's; then
551
+ * as a bare `lean` that must report that version. Nothing is ever downloaded during
552
+ * a check; a missing toolchain is `unavailable`, with the command that
553
+ * installs it. Diagnostics come back as `file:line:col: severity: message`
554
+ * lines, which the engine maps to theorems.
555
+ */
556
+ /**
557
+ * The Lean release the engine's contract corpus is checked against. On a
558
+ * bump: run the corpus and the supplied-proof tests on the new release,
559
+ * and read its release notes for a new command that runs code while a
560
+ * file is checked (a `#` command is already refused; a new word goes into
561
+ * `supplied.ts`'s refused list in the same change). CI caches the
562
+ * toolchain by this file's hash.
563
+ */
564
+ const leanToolchain = "leanprover/lean4:v4.35.0";
565
+ const leanVersion = "4.35.0";
566
+ /** How to put the pinned toolchain on this machine. */
567
+ const installHint = `run: eutaxy prover install lean (or install elan, https://elan.lean-lang.org, and run: elan toolchain install ${leanToolchain})`;
568
+ function run(command, args, options) {
569
+ return new Promise((resolve) => {
570
+ let child;
571
+ try {
572
+ child = spawn(command, args, {
573
+ cwd: options.cwd,
574
+ ...options.env === void 0 ? {} : { env: {
575
+ ...process.env,
576
+ ...options.env
577
+ } },
578
+ stdio: [
579
+ "ignore",
580
+ "pipe",
581
+ "pipe"
582
+ ],
583
+ detached: process.platform !== "win32"
584
+ });
585
+ } catch (err) {
586
+ resolve({
587
+ code: null,
588
+ stdout: "",
589
+ stderr: String(err),
590
+ timedOut: false
591
+ });
592
+ return;
593
+ }
594
+ let stdout = "";
595
+ let stderr = "";
596
+ let timedOut = false;
597
+ const timer = setTimeout(() => {
598
+ timedOut = true;
599
+ try {
600
+ if (process.platform !== "win32" && child.pid !== void 0) process.kill(-child.pid, "SIGKILL");
601
+ else child.kill("SIGKILL");
602
+ } catch {
603
+ child.kill("SIGKILL");
604
+ }
605
+ }, options.timeoutMs);
606
+ child.stdout?.on("data", (d) => {
607
+ stdout += d.toString();
608
+ });
609
+ child.stderr?.on("data", (d) => {
610
+ stderr += d.toString();
611
+ });
612
+ child.on("error", (err) => {
613
+ clearTimeout(timer);
614
+ resolve({
615
+ code: null,
616
+ stdout,
617
+ stderr: `${stderr}${String(err)}`,
618
+ timedOut
619
+ });
620
+ });
621
+ child.on("close", (code) => {
622
+ clearTimeout(timer);
623
+ resolve({
624
+ code,
625
+ stdout,
626
+ stderr,
627
+ timedOut
628
+ });
629
+ });
630
+ });
631
+ }
632
+ /** Candidates for a bare `lean`: the PATH, then elan's default home. */
633
+ function leanCandidates(h) {
634
+ const home = h.env["ELAN_HOME"] || join(h.home || homedir(), ".elan");
635
+ return ["lean", join(home, "bin", "lean")];
636
+ }
637
+ /**
638
+ * The pinned toolchain if it is installed: through `elan run <toolchain>`
639
+ * with the first elan that has it (Eutaxy's own, then the user's), else,
640
+ * only when no elan answered at all, a bare `lean` of exactly that version.
641
+ * Nothing is downloaded: an elan is run only for its toolchain list, and
642
+ * with an elan present a bare `lean` would be its proxy.
643
+ */
644
+ async function findLean(h = host(), elans = elanCandidates(h), leans = leanCandidates(h)) {
645
+ let lacking;
646
+ for (const elan of elans) {
647
+ const list = await run(elan.command, ["toolchain", "list"], {
648
+ timeoutMs: 2e4,
649
+ env: elan.env
650
+ });
651
+ if (list.code !== 0) continue;
652
+ if (list.stdout.split("\n").some((l) => l.trim().split(" ")[0] === "leanprover/lean4:v4.35.0")) return {
653
+ command: elan.command,
654
+ args: [
655
+ "run",
656
+ leanToolchain,
657
+ "lean"
658
+ ],
659
+ version: leanVersion,
660
+ ...elan.env === void 0 ? {} : { env: elan.env }
661
+ };
662
+ lacking ??= `elan (${elan.command}) has no ${leanToolchain}`;
663
+ }
664
+ if (lacking !== void 0) return { unavailable: `${lacking}; ${installHint}` };
665
+ for (const lean of leans) {
666
+ const v = await run(lean, ["--version"], { timeoutMs: 2e4 });
667
+ if (v.code !== 0) continue;
668
+ const m = /Lean \(version ([^,]+),/.exec(v.stdout);
669
+ if (m?.[1] === "4.35.0") return {
670
+ command: lean,
671
+ args: [],
672
+ version: leanVersion
673
+ };
674
+ return { unavailable: `lean ${m?.[1] ?? "of unknown version"} found, but the engine is pinned to ${leanVersion}; ${installHint}` };
675
+ }
676
+ return { unavailable: `no Lean toolchain found; ${installHint}` };
677
+ }
678
+ /** Parse Lean's diagnostics for the one file it was given. */
679
+ /**
680
+ * Lean's messages from `--json` output: one object per line, each with
681
+ * its position. Lines that are not such an object (whatever a program
682
+ * writes to the terminal) are not messages and are skipped, so nothing in
683
+ * the checked file can pose as a message at a position it is not at.
684
+ */
685
+ function jsonDiagnostics(output) {
686
+ const out = [];
687
+ for (const raw of output.split("\n")) {
688
+ if (!raw.startsWith("{")) continue;
689
+ let m;
690
+ try {
691
+ m = JSON.parse(raw);
692
+ } catch {
693
+ continue;
694
+ }
695
+ const severity = m.severity === "error" ? "error" : m.severity === "warning" ? "warning" : m.severity === "information" ? "info" : void 0;
696
+ if (severity === void 0 || typeof m.pos?.line !== "number" || typeof m.data !== "string") continue;
697
+ out.push({
698
+ line: m.pos.line,
699
+ column: typeof m.pos.column === "number" ? m.pos.column : 0,
700
+ severity,
701
+ message: m.data.trimEnd()
702
+ });
703
+ }
704
+ return out;
705
+ }
706
+ /** Write the source to a scratch directory pinned to the toolchain and check it. */
707
+ async function checkLean(toolchain, source, options = {}) {
708
+ const dir = mkdtempSync(join(tmpdir(), "eutaxy-lean-"));
709
+ try {
710
+ writeFileSync(join(dir, "lean-toolchain"), `${leanToolchain}\n`);
711
+ writeFileSync(join(dir, "Eutaxy.lean"), source);
712
+ const result = await run(toolchain.command, [
713
+ ...toolchain.args,
714
+ "--json",
715
+ "Eutaxy.lean"
716
+ ], {
717
+ cwd: dir,
718
+ timeoutMs: options.timeoutMs ?? 12e4,
719
+ env: toolchain.env
720
+ });
721
+ return {
722
+ run: result,
723
+ diagnostics: jsonDiagnostics(`${result.stdout}\n${result.stderr}`)
724
+ };
725
+ } finally {
726
+ if (!options.keep) rmSync(dir, {
727
+ recursive: true,
728
+ force: true
729
+ });
730
+ }
731
+ }
732
+ // packages/prover-lean/src/supplied.ts
733
+ /** The lines a goal file carries, and a proof file copied from one keeps, tying the proofs to the files they were written for. */
734
+ const sourceHashMarker = "-- eutaxy-source-sha256: ";
735
+ const specHashMarker = "-- eutaxy-spec-sha256: ";
736
+ /** The axioms a supplied proof may rest on: Lean's standard ones. */
737
+ const standardAxioms = /* @__PURE__ */ new Set([
738
+ "propext",
739
+ "Classical.choice",
740
+ "Quot.sound"
741
+ ]);
742
+ /**
743
+ * Words a supplied proof may not use, anywhere in the file, comments and
744
+ * strings included: what adds axioms or trusted code (`axiom`, `sorry`,
745
+ * `unsafe`, `implemented_by`, `extern`, `opaque`, `native_decide`),
746
+ * switches checks off (`set_option`), registers code Lean would run while
747
+ * the file is checked (`attribute`, `initialize`, `simproc` and the like)
748
+ * or changes how text reads (`macro`, `syntax`, `notation` and the like),
749
+ * and `import`. The list narrows when a legitimate proof is refused and
750
+ * grows only with a Lean bump that adds such a command (see
751
+ * `leanToolchain`); never because of what a hostile file could do, which
752
+ * the design answers.
753
+ */
754
+ const refusedWords = [
755
+ "sorry",
756
+ "admit",
757
+ "axiom",
758
+ "unsafe",
759
+ "implemented_by",
760
+ "extern",
761
+ "opaque",
762
+ "native_decide",
763
+ "set_option",
764
+ "macro",
765
+ "macro_rules",
766
+ "syntax",
767
+ "notation",
768
+ "infix",
769
+ "infixl",
770
+ "infixr",
771
+ "prefix",
772
+ "postfix",
773
+ "elab",
774
+ "elab_rules",
775
+ "import",
776
+ "attribute",
777
+ "initialize",
778
+ "simproc",
779
+ "dsimproc",
780
+ "simproc_decl",
781
+ "dsimproc_decl",
782
+ "section",
783
+ "namespace",
784
+ "variable",
785
+ "include",
786
+ "omit",
787
+ "universe"
788
+ ];
789
+ /** Command families refused by how a word starts: `run_cmd`, `builtin_initialize`, `register_option`, `declare_syntax_cat`. */
790
+ const refusedStarts = [
791
+ "run_",
792
+ "builtin_",
793
+ "register_",
794
+ "declare_"
795
+ ];
796
+ /**
797
+ * Refused wherever they appear, inside a name too: every command run
798
+ * while the file is checked starts with `#`, and every attribute (which
799
+ * can hand Lean a tactic, an elaborator or a simplification procedure to
800
+ * run) with `@[`.
801
+ */
802
+ const refusedAnywhere = ["#", "@["];
803
+ /** Lean's ASCII identifier characters after the first. */
804
+ const identRest = /[A-Za-z0-9_'!?]/u;
805
+ /**
806
+ * Whether the text just before `at` continues a name, so that a word
807
+ * starting there is part of that name rather than a token of its own.
808
+ * Only a run of identifier characters that starts with an ASCII letter or
809
+ * `_` counts: one that starts with a digit is a numeral, and Lean starts a
810
+ * new token right after a numeral (`0xfsorry` is `0xf`, then `sorry`).
811
+ * Anything else (`.`, `«`, Unicode) counts as a boundary, which refuses
812
+ * more, never less.
813
+ */
814
+ function continuesName(text, at) {
815
+ let i = at;
816
+ while (i > 0 && identRest.test(text[i - 1])) i--;
817
+ return i < at && /[A-Za-z_]/u.test(text[i]);
818
+ }
819
+ /** The first refused word or command the text holds, as a token of its own, or undefined. */
820
+ function refusedIn(text) {
821
+ const anywhere = refusedAnywhere.find((w) => text.includes(w));
822
+ if (anywhere !== void 0) return anywhere;
823
+ for (const [words, whole] of [[refusedWords, true], [refusedStarts, false]]) for (const w of words) for (let at = text.indexOf(w); at >= 0; at = text.indexOf(w, at + 1)) {
824
+ if (continuesName(text, at)) continue;
825
+ if (whole && identRest.test(text[at + w.length] ?? "")) continue;
826
+ return w;
827
+ }
828
+ }
829
+ /** `-- proof: <property>`: any name the spec file can export, Unicode letters included. */
830
+ const marker = /^-- proof: (\S+)\s*$/u;
831
+ /** Read a proof file: its lemmas, its proofs by property, or why it is refused. */
832
+ function readSupplied(file, text) {
833
+ const lemmas = [];
834
+ const proofs = /* @__PURE__ */ new Map();
835
+ let current = lemmas;
836
+ let twice;
837
+ for (const line of text.split("\n")) {
838
+ const m = marker.exec(line);
839
+ if (!m) {
840
+ current.push(line);
841
+ continue;
842
+ }
843
+ const name = m[1];
844
+ twice ??= proofs.has(name) ? name : void 0;
845
+ current = [];
846
+ proofs.set(name, current);
847
+ }
848
+ if (twice !== void 0) return refuse({
849
+ file,
850
+ proofs
851
+ }, `${file} proves ${twice} twice`);
852
+ const word = refusedIn(text);
853
+ if (word !== void 0) return refuse({
854
+ file,
855
+ proofs
856
+ }, `${file} uses ${word}, which a supplied proof may not (it could add an axiom, switch a check off, run code while the file is checked or change how the statement reads)`);
857
+ const hashLine = (marker) => {
858
+ const hex = lemmas.find((l) => l.startsWith(marker))?.slice(marker.length).trim();
859
+ return hex !== void 0 && /^[0-9a-f]{64}$/.test(hex) ? hex : void 0;
860
+ };
861
+ const sourceSha256 = hashLine(sourceHashMarker);
862
+ const specSha256 = hashLine(specHashMarker);
863
+ return {
864
+ file,
865
+ lemmas: lemmas.join("\n").trim(),
866
+ proofs: new Map([...proofs].map(([k, v]) => [k, v.join("\n").replace(/\s+$/, "")])),
867
+ ...sourceSha256 === void 0 ? {} : { sourceSha256 },
868
+ ...specSha256 === void 0 ? {} : { specSha256 }
869
+ };
870
+ }
871
+ /** The file refused: none of its proofs is used, and every property it names says why. */
872
+ function refuse(supplied, reason) {
873
+ return {
874
+ file: supplied.file,
875
+ lemmas: "",
876
+ proofs: new Map([...supplied.proofs.keys()].map((k) => [k, ""])),
877
+ refused: reason
878
+ };
879
+ }
880
+ /** Lean's messages at one line: an audit is read only when Lean's own message is the only one there. */
881
+ function onlyAt(messages, line) {
882
+ const at = messages.filter((m) => m.line === line);
883
+ return at.length === 1 && at[0]?.severity === "info" ? at[0].message : void 0;
884
+ }
885
+ /**
886
+ * The axioms Lean reports a theorem depends on: the message of the
887
+ * `#print axioms` at `line`, Eutaxy's own audit command, and no other.
888
+ * Undefined unless that message is the only one at the line: anything
889
+ * else there (a forged copy, printed by code the file ran) makes the
890
+ * audit unreadable rather than letting either message stand.
891
+ */
892
+ function axiomsOf(messages, line, theorem) {
893
+ const message = onlyAt(messages, line);
894
+ if (message === void 0) return void 0;
895
+ if (message === `'${theorem}' does not depend on any axioms`) return [];
896
+ const prefix = `'${theorem}' depends on axioms: [`;
897
+ if (message.startsWith(prefix) && message.endsWith("]")) return message.slice(prefix.length, -1).split(",").map((x) => x.trim()).filter((x) => x.length > 0);
898
+ }
899
+ /**
900
+ * Whether Lean's message at the `#check` of a supplied theorem shows it
901
+ * proves exactly its fixed statement `s_<name>`: no hypothesis added (a
902
+ * section variable would show as `False → …`).
903
+ */
904
+ function provesExactly(messages, line, theorem) {
905
+ return onlyAt(messages, line) === `${theorem} : s_${theorem}`;
906
+ }
907
+ // packages/prover-lean/src/goals.ts
908
+ /** The proof file's name beside a spec file: `domain.props.lean` for `domain.props.ts`. */
909
+ function proofFileFor(specFile) {
910
+ return specFile.replace(/\.ts$/, ".lean");
911
+ }
912
+ /** The goal file's name beside a spec file: `domain.props.goals.lean` for `domain.props.ts`. */
913
+ function goalFileFor(specFile) {
914
+ return specFile.replace(/\.ts$/, ".goals.lean");
915
+ }
916
+ /** A line of generated commentary: one a proof file may hold, or a note that it was left out. */
917
+ const commentLine = (text) => refusedIn(text) === void 0 ? text : "-- (a line left out: it held a word a proof file may not use)";
918
+ const comment = (text) => text.split("\n").map((l) => commentLine(l.length > 0 ? `-- ${l}` : "--")).join("\n");
919
+ /**
920
+ * Render the goal file: the header with the hashes, each goal described
921
+ * in comments (the proof file's lemma area, where comments cost nothing),
922
+ * then one open `-- proof:` part per goal at the end, since everything
923
+ * after a `-- proof:` line belongs to that proof. The text avoids every
924
+ * word a supplied proof may not use, so the file copied as is reads as a
925
+ * proof file with open proofs: every generated line is checked, and one
926
+ * that would refuse the file (a reason Lean gave, a file or function name
927
+ * that is itself a refused word) is left out, with a note in its place.
928
+ * The function is named by its Lean identifier, as the statement names it.
929
+ */
930
+ function renderGoals(input) {
931
+ const header = [
932
+ `-- Open proof goals for ${input.specFile}, written by Eutaxy's Lean engine (Lean ${leanVersion}).`,
933
+ "-- Each goal below is a property the tactic script could not close, with the statement Eutaxy",
934
+ "-- emits for it. To supply proofs, copy this file to",
935
+ `-- ${proofFileFor(input.specFile)} beside the spec file, put lemmas above the \`-- proof:\` lines and`,
936
+ "-- tactics under each, and run the engine again (eutaxy report --prover lean). The hashes tie the",
937
+ "-- proofs to these versions of the module and the spec: once either changes, the proofs are stale",
938
+ "-- until the goals are written again.",
939
+ `${sourceHashMarker}${input.sourceSha256}`,
940
+ `${specHashMarker}${input.specSha256}`
941
+ ];
942
+ const described = input.goals.map((g) => [
943
+ commentLine(`-- goal: ${g.property}, a property of ${ident.fn(g.function)}`),
944
+ commentLine(`-- Lean said: ${g.reason}`),
945
+ "-- statement:",
946
+ comment(g.statement.replace(/^/gm, " "))
947
+ ].join("\n"));
948
+ const open = input.goals.map((g) => `-- proof: ${g.property}\n -- tactics here`);
949
+ return `${[
950
+ header.map(commentLine).join("\n"),
951
+ ...described,
952
+ ...open
953
+ ].join("\n\n")}\n`;
954
+ }
955
+ // packages/prover-lean/src/prove.ts
956
+ /**
957
+ * The engine: a module's functions through the subset reader, the emitter
958
+ * and Lean, and each property's outcome back. One Lean run per module;
959
+ * errors are mapped to theorems by line, so one failed proof does not hide
960
+ * another. A proof that fails is `gave_up` (the engine is weak or the
961
+ * claim is false; Lean does not say which), a function or property outside
962
+ * the subset is `unsupported`, and no pinned toolchain is `unavailable`.
963
+ * `total` is proved by Lean accepting the definition.
964
+ */
965
+ const engineName = "lean";
966
+ /** The types this engine translates: the integers, Bool, String and records of those. */
967
+ const leanTakes = (t) => t.kind === "int" || t.kind === "bool" || t.kind === "string" || t.kind === "record" || t.kind === "list" && leanTakes(t.element);
968
+ /** What every PROVEN verdict of this engine rests on. */
969
+ const engineAssumptions = [
970
+ "number is modelled as the unbounded integers: no overflow, no fractions, no NaN",
971
+ "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",
972
+ "the function and its callees are pure and total: the module's own, or generic or imported ones read at each call from their own files; nothing else is modelled",
973
+ builtinsAssumption,
974
+ `the proof was checked by the Lean ${leanVersion} kernel on the emitted statement, not by Eutaxy`
975
+ ];
976
+ /** What a PROVEN over arrays rests on besides: the list model. */
977
+ const listAssumption = "an array is modelled as a Lean List, dense: a sparse array, whose holes JavaScript's array methods skip, is outside every array binder's domain";
978
+ /** What a PROVEN that unfolds a recursive function rests on besides: that the JavaScript returns. */
979
+ const recursionAssumption = "a recursive function is modelled as returning on every input: JavaScript's call stack is bounded, so on a long enough list the code throws (RangeError) where the model returns";
980
+ const proven = {
981
+ kind: "PROVEN",
982
+ engine: {
983
+ name: engineName,
984
+ version: leanVersion
985
+ },
986
+ assumptions: engineAssumptions
987
+ };
988
+ const unknown = unknownOutcome;
989
+ /**
990
+ * Read and emit. Every function the subset takes is emitted (callees
991
+ * included); properties are stated for the ones with specs among them.
992
+ */
993
+ function prepare(input) {
994
+ const specs = input.specs;
995
+ const read = readForEngine(input, [{
996
+ takes: leanTakes,
997
+ reason: "nullable types and tagged unions are not in the Lean engine's subset yet"
998
+ }, {
999
+ takes: () => true,
1000
+ reason: divisionOutside,
1001
+ bodies: /* @__PURE__ */ new Set(),
1002
+ refused: dividesOutside
1003
+ }]);
1004
+ const { module, fns, outside } = read;
1005
+ const properties = fns.filter((fn) => !outside.has(fn.name)).flatMap((fn) => fn.properties.filter((p) => p.kind === "forall").map((property) => ({
1006
+ function: fn.name,
1007
+ property
1008
+ })));
1009
+ const specErrors = specs.errors;
1010
+ const proofFile = input.specPath?.replace(/\.ts$/, ".lean");
1011
+ let supplied = proofFile !== void 0 && existsSync(proofFile) ? readSupplied(basename(proofFile), readFileSync(proofFile, "utf8")) : void 0;
1012
+ if (supplied && !supplied.refused) {
1013
+ const stale = staleness(supplied, input);
1014
+ if (stale !== void 0) supplied = refuse(supplied, stale);
1015
+ }
1016
+ try {
1017
+ return {
1018
+ module,
1019
+ ...supplied ? { supplied } : {},
1020
+ emitted: emitModule(module, properties, input.extra, supplied && !supplied.refused ? supplied : void 0),
1021
+ fns,
1022
+ outside,
1023
+ specErrors
1024
+ };
1025
+ } catch (err) {
1026
+ if (!(err instanceof OutsideSubset)) throw err;
1027
+ engineGap(read, err.message);
1028
+ return {
1029
+ module,
1030
+ emitted: {
1031
+ source: "",
1032
+ theorems: [],
1033
+ skipped: []
1034
+ },
1035
+ fns,
1036
+ outside,
1037
+ specErrors
1038
+ };
1039
+ }
1040
+ }
1041
+ const sha256 = (text) => createHash("sha256").update(text).digest("hex");
1042
+ /** Why a proof file is stale, when it names the hashes of the files it was written for and either moved. */
1043
+ function staleness(supplied, input) {
1044
+ const moved = [];
1045
+ if (supplied.sourceSha256 !== void 0 && supplied.sourceSha256 !== sha256(input.source)) moved.push("the module");
1046
+ if (supplied.specSha256 !== void 0 && input.specPath !== void 0 && existsSync(input.specPath)) {
1047
+ if (supplied.specSha256 !== sha256(readFileSync(input.specPath, "utf8"))) moved.push("the spec file");
1048
+ }
1049
+ if (moved.length === 0) return void 0;
1050
+ return `${supplied.file} is stale: ${moved.join(" and ")} changed since its proofs were written (the hashes it names no longer match); write the goals again and bring the proofs over`;
1051
+ }
1052
+ /**
1053
+ * A supplied proof's outcome: given up on when its lemmas or its tactics
1054
+ * do not compile, or when it rests on an axiom beyond Lean's standard
1055
+ * ones (`sorry` is one); PROVEN otherwise, saying it was supplied.
1056
+ */
1057
+ function suppliedOutcome(file, error, axioms, exact, assumptions) {
1058
+ if (error) return unknown("gave_up", `the proof supplied in ${file} does not close: ${error.message.split("\n")[0]}`);
1059
+ if (!exact) return unknown("gave_up", `the proof supplied in ${file} proves more hypotheses than its statement has (a section variable?), or Lean did not report its type`);
1060
+ if (axioms === void 0) return unknown("gave_up", `Lean did not report the axioms of the proof supplied in ${file}`);
1061
+ const beyond = axioms.filter((a) => !standardAxioms.has(a));
1062
+ if (beyond.length > 0) return unknown("gave_up", `the proof supplied in ${file} rests on ${beyond.join(", ")}, beyond Lean's standard axioms`);
1063
+ return {
1064
+ ...proven,
1065
+ assumptions: [...assumptions, `the proof was supplied in ${file}, not found by the engine's tactic script; Lean's kernel checked it against the statement Eutaxy emitted, and it rests on no axioms beyond propext, Classical.choice and Quot.sound`]
1066
+ };
1067
+ }
1068
+ /** Prove a module's properties with the pinned Lean. */
1069
+ async function proveModule(input) {
1070
+ const { module, emitted, fns, outside, specErrors, supplied } = prepare(input);
1071
+ const inSubset = fns.filter((f) => !outside.has(f.name));
1072
+ const unsupported = outsideProofs(fns, outside);
1073
+ if (inSubset.length === 0) return {
1074
+ results: unsupported,
1075
+ specErrors
1076
+ };
1077
+ const lean = emitted.source;
1078
+ const rest = (outcome) => ({
1079
+ results: [...unsupported, ...proofsOf(inSubset, outcome)],
1080
+ lean,
1081
+ specErrors
1082
+ });
1083
+ const toolchain = await findLean();
1084
+ if ("unavailable" in toolchain) return rest(unknown("unavailable", toolchain.unavailable));
1085
+ const timeoutMs = input.timeoutMs ?? 12e4;
1086
+ const checked = await checkLean(toolchain, lean, { timeoutMs });
1087
+ if (checked.run.timedOut) return rest(unknown("gave_up", `Lean did not finish within ${timeoutMs} ms`));
1088
+ const errors = checked.diagnostics.filter((d) => d.severity === "error");
1089
+ const inTheorem = (d) => emitted.theorems.find((t) => d.line >= t.from && d.line <= t.to);
1090
+ 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}`}`));
1091
+ const inLemmas = (d) => emitted.lemmas !== void 0 && d.line >= emitted.lemmas.from && d.line <= emitted.lemmas.to;
1092
+ const lemmaErrors = errors.filter(inLemmas);
1093
+ const elsewhere = errors.filter((d) => !inTheorem(d) && !inLemmas(d));
1094
+ if (elsewhere.length > 0) {
1095
+ const where = elsewhere.map((d) => `line ${d.line}: ${d.message.split("\n")[0]}`).join("; ");
1096
+ return rest(unknown("unsupported", `the emitted Lean did not compile: ${where}`));
1097
+ }
1098
+ const results = [...unsupported];
1099
+ for (const fn of inSubset) for (const property of fn.properties) {
1100
+ if (property.kind === "total") {
1101
+ results.push({
1102
+ function: fn.name,
1103
+ property: property.name,
1104
+ outcome: {
1105
+ ...proven,
1106
+ assumptions: [
1107
+ ...engineAssumptions,
1108
+ ...modelAssumptions(property, fn.name, module),
1109
+ "Lean accepted the definition, so it terminates on every input"
1110
+ ]
1111
+ }
1112
+ });
1113
+ continue;
1114
+ }
1115
+ const skipped = emitted.skipped.find((s) => s.function === fn.name && s.property === property.name);
1116
+ if (skipped) {
1117
+ results.push({
1118
+ function: fn.name,
1119
+ property: property.name,
1120
+ outcome: unknown("unsupported", skipped.reason)
1121
+ });
1122
+ continue;
1123
+ }
1124
+ if (supplied?.refused && supplied.proofs.has(property.name)) {
1125
+ results.push({
1126
+ function: fn.name,
1127
+ property: property.name,
1128
+ outcome: unknown("gave_up", supplied.refused)
1129
+ });
1130
+ continue;
1131
+ }
1132
+ const theorem = emitted.theorems.find((t) => t.function === fn.name && t.property === property.name);
1133
+ const failed = theorem ? errors.filter((d) => d.line >= theorem.from && d.line <= theorem.to) : [];
1134
+ if (theorem?.supplied && supplied) {
1135
+ results.push({
1136
+ function: fn.name,
1137
+ property: property.name,
1138
+ outcome: suppliedOutcome(supplied.file, lemmaErrors[0] ?? failed[0], axiomsOf(checked.diagnostics, theorem.axiomsLine ?? 0, theorem.name), provesExactly(checked.diagnostics, theorem.typeLine ?? 0, theorem.name), [...engineAssumptions, ...modelAssumptions(property, fn.name, module)])
1139
+ });
1140
+ continue;
1141
+ }
1142
+ results.push({
1143
+ function: fn.name,
1144
+ property: property.name,
1145
+ outcome: failed.length === 0 ? {
1146
+ ...proven,
1147
+ assumptions: [...engineAssumptions, ...modelAssumptions(property, fn.name, module)]
1148
+ } : unknown("gave_up", `Lean could not close the proof: ${failed[0].message.split("\n")[0]}`)
1149
+ });
1150
+ }
1151
+ const goals = [];
1152
+ for (const fn of inSubset) for (const property of fn.properties) {
1153
+ if (property.kind !== "forall") continue;
1154
+ const r = results.find((x) => x.function === fn.name && x.property === property.name);
1155
+ if (r?.outcome.kind !== "UNKNOWN" || r.outcome.cause !== "gave_up") continue;
1156
+ goals.push({
1157
+ function: fn.name,
1158
+ property: property.name,
1159
+ statement: stated(property, module).text,
1160
+ reason: r.outcome.reason
1161
+ });
1162
+ }
1163
+ return {
1164
+ results,
1165
+ lean,
1166
+ specErrors,
1167
+ goals
1168
+ };
1169
+ }
1170
+ /** The engine as a `Prover`: available when the pinned toolchain is installed. */
1171
+ const leanProver = {
1172
+ name: engineName,
1173
+ async available() {
1174
+ const toolchain = await findLean();
1175
+ return "unavailable" in toolchain ? toolchain : { version: toolchain.version };
1176
+ },
1177
+ prove: (input) => proveModule(input)
1178
+ };
1179
+ /** The list and recursion models a proof rests on, where its claim may meet them. */
1180
+ function modelAssumptions(property, fn, module) {
1181
+ const arrows = [property.when?.body ?? "", property.ensures?.body ?? ""].join("\n");
1182
+ const roots = [fn, ...property.imports.filter((i) => new RegExp(`(^|[^\\w$])${i.local.replace(/\$/g, "\\$")}($|[^\\w$])`).test(arrows)).map((i) => i.fn)];
1183
+ return [...usesLists(property, roots, module) ? [listAssumption] : [], ...reached(roots, module).some((f) => f.structural !== void 0) ? [recursionAssumption] : []];
1184
+ }
1185
+ /**
1186
+ * The functions a property's claim may unfold: its function, the module
1187
+ * functions its arrows call, and, through their calls, everything they
1188
+ * reach.
1189
+ */
1190
+ function reached(roots, module) {
1191
+ const byName = new Map(module.functions.map((f) => [f.name, f]));
1192
+ const out = /* @__PURE__ */ new Map();
1193
+ const visit = (name) => {
1194
+ const f = byName.get(name);
1195
+ if (!f || out.has(name)) return;
1196
+ out.set(name, f);
1197
+ const walk = (e) => {
1198
+ if (e.kind === "call") visit(e.callee);
1199
+ for (const c of children(e)) walk(c);
1200
+ };
1201
+ walk(f.body);
1202
+ };
1203
+ for (const r of roots) visit(r);
1204
+ return [...out.values()];
1205
+ }
1206
+ /**
1207
+ * Whether a list can be in play in a property: a binder whose type holds
1208
+ * an array at any depth, or a function the claim may unfold that holds a
1209
+ * list in its types (through records too) or builds one.
1210
+ */
1211
+ function usesLists(property, roots, module) {
1212
+ const records = new Map(module.records.map((r) => [r.name, r]));
1213
+ const seen = /* @__PURE__ */ new Set();
1214
+ const hasList = (t) => {
1215
+ if (t.kind === "list") return true;
1216
+ if (t.kind === "nullable") return hasList(t.inner);
1217
+ if (t.kind === "record" && !seen.has(t.name)) {
1218
+ seen.add(t.name);
1219
+ return records.get(t.name)?.fields.some((f) => hasList(f.type)) ?? false;
1220
+ }
1221
+ return false;
1222
+ };
1223
+ const hasArray = (t) => {
1224
+ if (t.kind === "array") return true;
1225
+ if (t.kind === "union") return t.members.some(hasArray);
1226
+ if (t.kind === "record") return t.fields.some((f) => hasArray(f.type));
1227
+ return false;
1228
+ };
1229
+ const builds = (e) => listKinds.has(e.kind) || children(e).some(builds);
1230
+ const arrowLists = [property.when, property.ensures].some((a) => a !== void 0 && /\[|\.(map|flatMap|every|some|reduce|slice|length)\b/.test(a.body));
1231
+ return property.binders.some((b) => hasArray(b.type)) || arrowLists || reached(roots, module).some((f) => hasList(f.returns) || f.params.some((p) => hasList(p.type)) || builds(f.body));
1232
+ }
1233
+ export { elanCandidates as C, leanDigests as D, elanVersion as E, toolchainDigest as O, ident as S, elanHome as T, findLean as _, prepare as a, leanVersion as b, proofFileFor as c, readSupplied as d, refusedIn as f, checkLean as g, standardAxioms as h, leanTakes as i, renderGoals as l, specHashMarker as m, engineName as n, proveModule as o, sourceHashMarker as p, leanProver as r, goalFileFor as s, engineAssumptions as t, axiomsOf as u, installHint as v, elanDownloads as w, emitModule as x, leanToolchain as y };
1234
+
1235
+ //# sourceMappingURL=src-BFGTvuA_.mjs.map