eutaxy 0.18.0 → 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.
- package/README.md +15 -12
- package/dist/aws.d.mts +2 -2
- package/dist/aws.mjs +3 -2
- package/dist/aws.mjs.map +1 -1
- package/dist/bin.mjs +1 -1
- package/dist/check-zkHLdWyf.mjs +1281 -0
- package/dist/check-zkHLdWyf.mjs.map +1 -0
- package/dist/cli-CNAKqV9R.mjs +297 -0
- package/dist/cli-CNAKqV9R.mjs.map +1 -0
- package/dist/cli.d.mts.map +1 -1
- package/dist/cli.mjs +1 -1
- package/dist/cloudflare.d.mts +37 -5
- package/dist/cloudflare.d.mts.map +1 -1
- package/dist/cloudflare.mjs +6417 -3
- package/dist/cloudflare.mjs.map +1 -0
- package/dist/{delivery-invariants-BRwfZJrs.mjs → delivery-invariants-BJDck0K8.mjs} +2 -2
- package/dist/{delivery-invariants-BRwfZJrs.mjs.map → delivery-invariants-BJDck0K8.mjs.map} +1 -1
- package/dist/{delivery-invariants-D-_GPOqE.d.mts → delivery-invariants-C3GXJIbg.d.mts} +2 -2
- package/dist/{delivery-invariants-D-_GPOqE.d.mts.map → delivery-invariants-C3GXJIbg.d.mts.map} +1 -1
- package/dist/draft-DEUDffHa.mjs +467 -0
- package/dist/draft-DEUDffHa.mjs.map +1 -0
- package/dist/{src-H1Q8ytEx.mjs → generate-TBJM3-2P.mjs} +3 -618
- package/dist/generate-TBJM3-2P.mjs.map +1 -0
- package/dist/index.d.mts +36 -36
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +6 -3
- package/dist/index.mjs.map +1 -1
- package/dist/install-DkzpGA5D.mjs +611 -0
- package/dist/install-DkzpGA5D.mjs.map +1 -0
- package/dist/{explore-D33RP9hF.d.mts → ir-KpC2epGn.d.mts} +70 -70
- package/dist/ir-KpC2epGn.d.mts.map +1 -0
- package/dist/keys-xtanNmuR.mjs +111 -0
- package/dist/keys-xtanNmuR.mjs.map +1 -0
- package/dist/mcp-B64Ko6y7.mjs +539 -0
- package/dist/mcp-B64Ko6y7.mjs.map +1 -0
- package/dist/{platform-CawKCUru.d.mts → platform-Cs9V9t2k.d.mts} +25 -11
- package/dist/platform-Cs9V9t2k.d.mts.map +1 -0
- package/dist/pool-CXN4CwGY.mjs +61 -0
- package/dist/pool-CXN4CwGY.mjs.map +1 -0
- package/dist/{provers-DS44OeEm.mjs → provers-D8VaY_OM.mjs} +18 -2
- package/dist/provers-D8VaY_OM.mjs.map +1 -0
- package/dist/reader-B9FSoEYW.mjs +1 -0
- package/dist/reader-Cz6_bLf6.mjs +3774 -0
- package/dist/reader-Cz6_bLf6.mjs.map +1 -0
- package/dist/report-_Vzavqg0.mjs +310 -0
- package/dist/report-_Vzavqg0.mjs.map +1 -0
- package/dist/src-B2DpVbMN.mjs +2 -0
- package/dist/src-BFGTvuA_.mjs +1235 -0
- package/dist/src-BFGTvuA_.mjs.map +1 -0
- package/dist/src-BtLZPRyG.mjs +120 -0
- package/dist/src-BtLZPRyG.mjs.map +1 -0
- package/dist/src-CB8DcvsK.mjs +1 -0
- package/dist/src-COuquJvI.mjs +269 -0
- package/dist/src-COuquJvI.mjs.map +1 -0
- package/dist/src-Chn-m_r1.mjs +1082 -0
- package/dist/src-Chn-m_r1.mjs.map +1 -0
- package/dist/src-DwYD3QQJ.mjs +346 -0
- package/dist/src-DwYD3QQJ.mjs.map +1 -0
- package/dist/{src-Whn0RMSh.mjs → src-Dx4QvrQb.mjs} +559 -517
- package/dist/src-Dx4QvrQb.mjs.map +1 -0
- package/dist/toolchain-DWfymxAJ.mjs +80 -0
- package/dist/toolchain-DWfymxAJ.mjs.map +1 -0
- package/dist/verdict-evEM5Gxx.mjs +12 -0
- package/dist/verdict-evEM5Gxx.mjs.map +1 -0
- package/package.json +4 -1
- package/dist/cli-DyA7uTBg.mjs +0 -9447
- package/dist/cli-DyA7uTBg.mjs.map +0 -1
- package/dist/explore-D33RP9hF.d.mts.map +0 -1
- package/dist/platform-CawKCUru.d.mts.map +0 -1
- package/dist/provers-DS44OeEm.mjs.map +0 -1
- package/dist/src-H1Q8ytEx.mjs.map +0 -1
- package/dist/src-Whn0RMSh.mjs.map +0 -1
- package/dist/workerd-tI8INa6v.mjs +0 -6334
- package/dist/workerd-tI8INa6v.mjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"src-BFGTvuA_.mjs","names":[],"sources":["../../prover-lean/src/elan.ts","../../prover-lean/src/emit.ts","../../prover-lean/src/lean.ts","../../prover-lean/src/supplied.ts","../../prover-lean/src/goals.ts","../../prover-lean/src/prove.ts"],"sourcesContent":["/**\n * Lean's toolchain comes through elan, Lean's own toolchain manager. This\n * file holds what `eutaxy prover install lean` and the engine share about\n * it: the pinned elan installer (`elanDownloads`, fetched only when no elan\n * is on the machine), where Eutaxy keeps an elan of its own (`elanHome`,\n * inside Eutaxy's cache), the elans the engine and the command look for\n * (`elanCandidates`), and the digest of the pinned toolchain's files\n * (`leanDigests`, `toolchainDigest`), which the command checks after elan\n * has installed it, since elan does not check the toolchain it downloads\n * against a pinned checksum.\n */\n\nimport { createHash } from \"node:crypto\";\nimport { readdirSync, readFileSync, readlinkSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join, relative, sep } from \"node:path\";\nimport { cacheDir, type Host, type Platform, type Toolchain } from \"@eutaxy/prover/toolchain\";\n\n/** The elan release whose installer the command fetches when the machine has no elan. */\nexport const elanVersion = \"4.2.4\";\n\nconst elanRelease = `https://github.com/leanprover/elan/releases/download/v${elanVersion}`;\nconst elanFile = (name: string, sha256: string, bytes: number) => {\n // Each archive holds the one installer, at its root.\n const installer = name.endsWith(\".zip\") ? \"elan-init.exe\" : \"elan-init\";\n return {\n file: name,\n url: `${elanRelease}/${name}`,\n sha256,\n bytes,\n entries: { [installer]: installer },\n };\n};\n/**\n * The upstream elan installer for each platform, as published on elan's\n * GitHub release with the checksums it reports; a test holds the file\n * names to `elanVersion`. The installer links only system libraries.\n */\nexport const elanDownloads: Toolchain = {\n name: \"elan\",\n version: elanVersion,\n executable: \"elan-init\",\n files: {\n \"linux-x64\": elanFile(\n \"elan-x86_64-unknown-linux-gnu.tar.gz\",\n \"42b94d4244e8353142c456ec0e4ca6528fd898a6c604d4059f494e706e431f63\",\n 4996571,\n ),\n \"linux-arm64\": elanFile(\n \"elan-aarch64-unknown-linux-gnu.tar.gz\",\n \"05febd124d84ebf994b2e7479922a5650b1e950c17ae3bd1ddd776b65bb72bf9\",\n 5131114,\n ),\n \"darwin-x64\": elanFile(\n \"elan-x86_64-apple-darwin.tar.gz\",\n \"8a340b309d8ed2e96f930761fa223b3af57a38f5d253b53ac90293c9516f8cd4\",\n 2330818,\n ),\n \"darwin-arm64\": elanFile(\n \"elan-aarch64-apple-darwin.tar.gz\",\n \"7ad829861392c718dfebde3a83b5c8508df47be02af68894b094b0b3952616e5\",\n 2190845,\n ),\n \"win32-x64\": elanFile(\n \"elan-x86_64-pc-windows-msvc.zip\",\n \"fad2e980a191c15884cc1d80d170ffc5fa84f3774541020145b66d1a644c6111\",\n 2508099,\n ),\n },\n};\n\n/** Where Eutaxy's own elan keeps itself and its toolchains: `<cache>/elan`. */\nexport function elanHome(h: Host): string {\n return join(cacheDir(h), \"elan\");\n}\n\n/** An elan to run, with the environment it needs (`ELAN_HOME` for Eutaxy's own). */\nexport interface Elan {\n readonly command: string;\n readonly env?: Readonly<Record<string, string>>;\n}\n\n/**\n * The elans to try, in order: Eutaxy's own in the cache, then the one on\n * the PATH, then the one in elan's home (`ELAN_HOME`, else `~/.elan`).\n */\nexport function elanCandidates(h: Host): Elan[] {\n const exe = h.platform === \"win32\" ? \"elan.exe\" : \"elan\";\n const own = elanHome(h);\n const home = h.env[\"ELAN_HOME\"] || join(h.home || homedir(), \".elan\");\n return [\n { command: join(own, \"bin\", exe), env: { ELAN_HOME: own } },\n { command: \"elan\" },\n { command: join(home, \"bin\", exe) },\n ];\n}\n\n/**\n * The pinned toolchain's `toolchainDigest`, per platform: computed over\n * Lean's GitHub release file for that platform, checked against the\n * checksum the release reports, and unpacked. elan installs exactly that\n * release (on macOS arm64 the digest of an elan-installed toolchain was\n * checked to equal it), so a toolchain elan installed whose digest differs\n * is not the pinned one.\n */\nexport const leanDigests: Readonly<Record<Platform, string>> = {\n \"linux-x64\": \"d6bb6c4de1fce52bc5d88ff52f7fcf7d347ee5b3ba7d187de775ccf915714c35\",\n \"linux-arm64\": \"1bcaf2cf93006e3017a07234e3a33ba8bd1dec404e7dc0e4c202111b0bf2be41\",\n \"darwin-x64\": \"b817cf3c90432b774405bad998bad5985f0ef9594d1c31aeddb3df6479c1bd0c\",\n \"darwin-arm64\": \"2a31778d0185a17655be5f97e6e930dd0ece0d1db9f41a2825f500b3ca8c5c0a\",\n \"win32-x64\": \"441877e59afc80b7af1f1b6fc3db64b2c947d581de26a040486387aa4ec7a3cb\",\n};\n\nexport interface ToolchainDigest {\n readonly digest: string;\n readonly files: number;\n readonly bytes: number;\n}\n\n/**\n * A digest of everything under a toolchain's directory: one line per file\n * (`<sha256> <path>`) and per link (`-> <target> <path>`), paths relative\n * and with `/`, sorted, the whole hashed. Directories count only through\n * what they hold.\n */\nexport function toolchainDigest(prefix: string): ToolchainDigest {\n const lines: (readonly [string, string])[] = [];\n let files = 0;\n let bytes = 0;\n for (const entry of readdirSync(prefix, { recursive: true, withFileTypes: true })) {\n const at = join(entry.parentPath, entry.name);\n const path = relative(prefix, at).split(sep).join(\"/\");\n if (entry.isSymbolicLink()) lines.push([path, `-> ${readlinkSync(at)} ${path}`]);\n else if (entry.isFile()) {\n const data = readFileSync(at);\n files++;\n bytes += data.length;\n lines.push([path, `${createHash(\"sha256\").update(data).digest(\"hex\")} ${path}`]);\n }\n }\n lines.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));\n return {\n digest: createHash(\"sha256\")\n .update(`${lines.map(([, line]) => line).join(\"\\n\")}\\n`)\n .digest(\"hex\"),\n files,\n bytes,\n };\n}\n","/**\n * Lean 4 for a module in the subset and the properties on it. The\n * module's record types become structures, its functions definitions over\n * `Int`, `Bool` and `String`, each property a theorem whose statement is\n * the claim over its binders, with the precondition as a hypothesis.\n * Booleans stay `Bool` in terms, as in TypeScript, and become propositions\n * with `= true` where a statement needs one; comparisons are `decide`d.\n * Every theorem is closed by one tactic script, except where a proof is\n * supplied beside the spec file (`supplied.ts`): then the statement is\n * fixed as a definition first, and the supplied tactics must prove it.\n */\n\nimport {\n type BinderRule,\n children,\n type Expr,\n hasLoneSurrogate,\n OutsideSubset,\n type RecordType,\n readArrowBody,\n readBinderType,\n renameVars,\n type SubsetFunction,\n type SubsetModule,\n type SubsetType,\n type TypeContext,\n typeOf,\n} from \"@eutaxy/prover/reader\";\nimport type { Arrow, Property, SpecType } from \"@eutaxy/spec\";\n\n/**\n * TypeScript names as Lean identifiers that can clash with nothing Lean\n * defines and not with each other: functions get `f_`, record types `R_`,\n * variables `v_`, theorems `t_`. The schemes differ in their first letter,\n * so no two names from different kinds coincide whatever the author\n * wrote (`ts_f` and `f_` would, under suffixing), and Lean's prelude has\n * no names of these shapes, so a function called `decide` or a parameter\n * called `max` stays what the author meant.\n */\nexport const ident = {\n fn: (name: string) => quote(`f_${name}`),\n record: (name: string) => quote(`R_${name}`),\n variable: (name: string) => quote(`v_${name}`),\n // Fields keep their names, which may be Lean keywords: those are quoted.\n field: (name: string) => (leanKeywords.has(name) ? `«${name}»` : quote(name)),\n};\n\n/** Lean's keywords, which a field name may coincide with. */\nconst leanKeywords = new Set(\n \"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(\n \" \",\n ),\n);\n\nfunction quote(name: string): string {\n // Guillemets hold anything but guillemets: those are escaped as `%ab` and `%bb`, with `%` itself\n // as `%25` first, in every name, so two names never meet in one identifier.\n const escaped = name.replace(/%/g, \"%25\").replace(/«/g, \"%ab\").replace(/»/g, \"%bb\");\n return /^[A-Za-z_][A-Za-z0-9_]*$/.test(escaped) ? escaped : `«${escaped}»`;\n}\n\nfunction leanType(t: SubsetType): string {\n switch (t.kind) {\n case \"int\":\n return \"Int\";\n case \"bool\":\n return \"Bool\";\n case \"string\":\n return \"String\";\n case \"record\":\n return ident.record(t.name);\n case \"list\":\n return `(List ${leanType(t.element)})`;\n case \"nothing\":\n return fail(\"the element type of an empty array, which nothing gives\");\n case \"nullable\":\n case \"union\":\n case \"null\":\n return fail(`a ${t.kind} type, which the Lean engine does not take yet`);\n }\n}\n\nexport function emitRecord(r: RecordType): string {\n return [\n `structure ${ident.record(r.name)} where`,\n ...r.fields.map((f) => ` ${ident.field(f.name)} : ${leanType(f.type)}`),\n \" deriving Repr, DecidableEq\",\n ].join(\"\\n\");\n}\n\ninterface Env {\n readonly module: SubsetModule;\n readonly ctx: TypeContext;\n /**\n * In the non-empty branch of a structurally recursive function: the list\n * parameter is `head :: tail` there, so `xs[0] ?? d` is the head,\n * `xs.slice(1)` the tail (what the recursive call must be given for Lean\n * to see the recursion is structural), and `xs` itself `head :: tail`.\n */\n readonly cons?: { readonly list: string; readonly head: string; readonly tail: string };\n}\n\nfunction env(module: SubsetModule): Env {\n return {\n module,\n ctx: {\n records: new Map(module.records.map((r) => [r.name, r])),\n unions: module.unions,\n signatures: new Map(\n module.functions.map((f) => [f.name, { params: f.params, returns: f.returns }]),\n ),\n },\n };\n}\n\nexport const divisionOutside =\n \"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)\";\n\n/** Whether an expression divides other than as Math.floor(x / c), c a positive integer constant. */\nexport function dividesOutside(e: Expr): boolean {\n if (e.kind === \"floor\" && e.operand.kind === \"binary\" && e.operand.op === \"/\") {\n const c = integerValue(e.operand.right);\n if (c !== undefined && c > 0n) return dividesOutside(e.operand.left);\n }\n if (e.kind === \"binary\" && e.op === \"/\") return true;\n return children(e).some(dividesOutside);\n}\n\n/** The value of an integer expression built from literals by + - * and negation, if it is one. */\nfunction integerValue(e: Expr): bigint | undefined {\n if (e.kind === \"int\") return BigInt(e.value);\n if (e.kind === \"neg\") {\n const v = integerValue(e.operand);\n return v === undefined ? undefined : -v;\n }\n if (e.kind !== \"binary\") return undefined;\n const l = integerValue(e.left);\n const r = integerValue(e.right);\n if (l === undefined || r === undefined) return undefined;\n if (e.op === \"+\") return l + r;\n if (e.op === \"-\") return l - r;\n if (e.op === \"*\") return l * r;\n return undefined;\n}\n\nconst fail: (message: string) => never = (message) => {\n throw new OutsideSubset(message, 0);\n};\n\n/** A term of the expression's TypeScript type: `Int`, `Bool`, `String` or a structure. */\nexport function term(e: Expr, scope: ReadonlyMap<string, SubsetType>, env: Env): string {\n const t = (x: Expr) => term(x, scope, env);\n switch (e.kind) {\n case \"int\":\n return `(${e.value} : Int)`;\n case \"bool\":\n return e.value ? \"true\" : \"false\";\n case \"string\":\n return leanString(e.value);\n case \"var\":\n if (env.cons?.list === e.name) return `(${env.cons.head} :: ${env.cons.tail})`;\n return ident.variable(e.name);\n case \"null\":\n case \"narrow\":\n return fail(\"null, which the Lean engine does not take yet\");\n case \"narrowTag\":\n return fail(\"a union, which the Lean engine does not take yet\");\n case \"neg\":\n return `(-${t(e.operand)})`;\n case \"not\":\n return `(!${t(e.operand)})`;\n case \"isInteger\":\n // Every number is an integer in this engine's model. The operand is still emitted, so what\n // this engine refuses in it (a division) is refused here too, not dropped with it.\n typeOf(e.operand, scope, env.ctx, fail);\n t(e.operand);\n return \"true\";\n case \"floor\": {\n // Of an integer, Math.floor is the integer; of x / c, with c a positive integer constant, it is\n // Lean's Int division, which rounds toward negative infinity as Math.floor does.\n const o = e.operand;\n if (o.kind !== \"binary\" || o.op !== \"/\") return t(o);\n const c = integerValue(o.right);\n if (c === undefined || c <= 0n) fail(divisionOutside);\n return `(${t(o.left)} / (${c} : Int))`;\n }\n case \"binary\":\n switch (e.op) {\n case \"+\": {\n const lt = typeOf(e.left, scope, env.ctx, fail);\n return `(${t(e.left)} ${lt.kind === \"string\" ? \"++\" : \"+\"} ${t(e.right)})`;\n }\n case \"-\":\n case \"*\":\n return `(${t(e.left)} ${e.op} ${t(e.right)})`;\n case \"/\":\n return fail(divisionOutside);\n case \"<\":\n case \">\":\n return `(decide (${t(e.left)} ${e.op} ${t(e.right)}))`;\n case \"<=\":\n return `(decide (${t(e.left)} ≤ ${t(e.right)}))`;\n case \">=\":\n return `(decide (${t(e.left)} ≥ ${t(e.right)}))`;\n case \"===\":\n case \"!==\": {\n // === on objects compares references in JavaScript; Lean's = would compare the fields.\n const lt = typeOf(e.left, scope, env.ctx, fail);\n if (lt.kind === \"record\")\n fail(\n `${e.op} on records compares references in JavaScript; compare their fields instead`,\n );\n return `(decide (${t(e.left)} ${e.op === \"===\" ? \"=\" : \"≠\"} ${t(e.right)}))`;\n }\n case \"&&\":\n return `(${t(e.left)} && ${t(e.right)})`;\n case \"||\":\n return `(${t(e.left)} || ${t(e.right)})`;\n }\n break;\n case \"cond\":\n return `(if ${t(e.test)} = true then ${t(e.ifTrue)} else ${t(e.ifFalse)})`;\n case \"call\":\n return `(${ident.fn(e.callee)}${e.args.map((a) => ` ${t(a)}`).join(\"\")})`;\n case \"field\":\n // A list's length is a natural number in Lean; the subset counts in Int.\n if (typeOf(e.object, scope, env.ctx, fail).kind === \"list\")\n return `(Int.ofNat (List.length ${t(e.object)}))`;\n return `${t(e.object)}.${ident.field(e.field)}`;\n case \"record\": {\n const type = typeOf(e, scope, env.ctx, fail);\n const name =\n type.kind === \"record\"\n ? ident.record(type.name)\n : fail(\"a record literal of no record type\");\n return `({ ${e.fields.map((f) => `${ident.field(f.name)} := ${t(f.value)}`).join(\", \")} } : ${name})`;\n }\n case \"let\": {\n const inner = new Map(scope);\n const bound = e.type ?? typeOf(e.value, scope, env.ctx, fail);\n inner.set(e.name, bound);\n // The annotation, when there is one, types the binding in Lean too (`const xs: number[] = []`).\n const annotated = e.type ? ` : ${leanType(e.type)}` : \"\";\n return `(let ${ident.variable(e.name)}${annotated} := ${t(e.value)}; ${term(e.body, inner, env)})`;\n }\n case \"list\": {\n if (e.items.length === 0 && !e.rest) return \"[]\";\n if (!e.rest) return `[${e.items.map(t).join(\", \")}]`;\n return `(${[...e.items.map(t), t(e.rest)].join(\" :: \")})`;\n }\n case \"tail\":\n if (e.list.kind === \"var\" && env.cons?.list === e.list.name) return env.cons.tail;\n return `(List.tail ${t(e.list)})`;\n case \"headOr\":\n if (e.list.kind === \"var\" && env.cons?.list === e.list.name) return env.cons.head;\n return `(List.headD ${t(e.list)} ${t(e.fallback)})`;\n case \"iterate\": {\n const listType = typeOf(e.list, scope, env.ctx, fail);\n if (listType.kind !== \"list\") fail(`${e.op} on a ${listType.kind}`);\n const inner = new Map(scope);\n inner.set(e.item, listType.element);\n if (e.index !== undefined) inner.set(e.index, { kind: \"int\" });\n const body = term(e.body, inner, env);\n // The index counts from 0 as a natural number; the subset's is an Int.\n const nat = e.index === undefined ? \"\" : quote(`nv_${e.index}`);\n const fn =\n e.index === undefined\n ? `(fun ${ident.variable(e.item)} => ${body})`\n : `(fun (${ident.variable(e.item)}, ${nat}) => let ${ident.variable(e.index)} := Int.ofNat ${nat}; ${body})`;\n const list = e.index === undefined ? t(e.list) : `(List.zipIdx ${t(e.list)})`;\n // map and flatMap take the function first; all and any take the list first.\n if (e.op === \"map\") return `(List.map ${fn} ${list})`;\n if (e.op === \"flatMap\") return `(List.flatMap ${fn} ${list})`;\n return `(${e.op === \"every\" ? \"List.all\" : \"List.any\"} ${list} ${fn})`;\n }\n case \"fold\": {\n const listType = typeOf(e.list, scope, env.ctx, fail);\n if (listType.kind !== \"list\") fail(`reduce on a ${listType.kind}`);\n const inner = new Map(scope);\n inner.set(e.acc, typeOf(e, scope, env.ctx, fail));\n inner.set(e.item, listType.element);\n return `(List.foldl (fun ${ident.variable(e.acc)} ${ident.variable(e.item)} => ${term(e.body, inner, env)}) ${t(e.init)} ${t(e.list)})`;\n }\n }\n}\n\nexport function emitFunction(f: SubsetFunction, module: SubsetModule): string {\n const e = env(module);\n const scope = new Map(f.params.map((p) => [p.name, p.type]));\n const params = f.params.map((p) => `(${ident.variable(p.name)} : ${leanType(p.type)})`).join(\" \");\n const head = `def ${ident.fn(f.name)} ${params} : ${leanType(f.returns)} :=`;\n if (f.structural === undefined || f.body.kind !== \"cond\")\n return `${head}\\n ${term(f.body, scope, e)}`;\n // Structural recursion: a match on the list the body tests against 0, recursing on its tail.\n // `vh_`/`vt_` names cannot meet a variable, whose names all start `v_`.\n const list = (f.params[f.structural] as { name: string }).name;\n const cons = { list, head: quote(`vh_${list}`), tail: quote(`vt_${list}`) };\n return [\n head,\n ` match ${ident.variable(list)} with`,\n ` | [] => ${term(f.body.ifTrue, scope, e)}`,\n ` | ${cons.head} :: ${cons.tail} => ${term(f.body.ifFalse, scope, { ...e, cons })}`,\n ].join(\"\\n\");\n}\n\n/** What this engine does not take of binder types: nullable types and unions, which the SMT engine takes. */\nexport const binderRule: BinderRule = {\n nullable: \"nullable types are not in the engine's subset yet\",\n union: \"unions are not in the engine's subset yet\",\n};\n\n/**\n * The subset type a binder ranges over, or `OutsideSubset`: `number` is\n * `Int` (the engine's integer model, an assumption every PROVEN carries),\n * a union of string literals is `String` (the proof covers every string,\n * more than the type admits), a record is the module's structure of that\n * name, an array a list. Nullable types, tagged unions, bigint and whatever\n * the reader could not read are outside. Read by the reader's\n * `readBinderType` under `binderRule`.\n */\nexport function binderType(name: string, t: SpecType, module: SubsetModule): SubsetType {\n return readBinderType(name, t, module, binderRule);\n}\n\n/** An arrow of the spec file as a Bool term over the binders, its own parameter names renamed to theirs. */\nfunction arrowTerm(\n arrow: Arrow,\n what: \"when\" | \"ensures\",\n property: Property,\n types: readonly SubsetType[],\n e: Env,\n): string {\n try {\n return arrowTermAt(arrow, what, property, types, e);\n } catch (err) {\n // What the subset refused, located in the spec file.\n if (!(err instanceof OutsideSubset)) throw err;\n throw new OutsideSubset(`${what} (spec file line ${arrow.line}): ${err.message}`, arrow.line);\n }\n}\n\nfunction arrowTermAt(\n arrow: Arrow,\n what: \"when\" | \"ensures\",\n property: Property,\n types: readonly SubsetType[],\n e: Env,\n): string {\n const binders = property.binders;\n const scope = new Map<string, SubsetType>();\n const names = new Map<string, string>();\n arrow.params.forEach((p, i) => {\n const binder = binders[i];\n const type = types[i];\n if (p === null) fail(`a destructured parameter in ${what}`);\n if (!binder || !type) fail(`${what} takes more parameters than the function has`);\n scope.set(p, type);\n names.set(p, binder.name);\n });\n const aliases = new Map(property.imports.map((i) => [i.local, i.fn]));\n const read = readArrowBody(arrow, scope, e.module, aliases);\n const t = typeOf(read, scope, e.ctx, fail);\n if (t.kind !== \"bool\")\n fail(`${what} is not boolean (a ${t.kind === \"record\" ? t.name : t.kind})`);\n const renamed = renameVars(read, names);\n const binderScope = new Map(binders.map((b, i) => [b.name, types[i] as SubsetType]));\n return term(renamed, binderScope, e);\n}\n\n/** The proposition a property claims: binders universally quantified, the precondition in front. */\nexport function statement(property: Property, module: SubsetModule): string {\n return stated(property, module).text;\n}\n\n/** The statement and how many hypotheses stand before the claim (the tactic script introduces them by name). */\nexport function stated(\n property: Property,\n module: SubsetModule,\n): { readonly text: string; readonly hypotheses: number } {\n if (property.kind !== \"forall\" || !property.ensures) fail(\"not a forall property\");\n const e = env(module);\n const types = property.binders.map((b) => binderType(b.name, b.type, module));\n const binders = property.binders\n .map((b, i) => `(${ident.variable(b.name)} : ${leanType(types[i] as SubsetType)})`)\n .join(\" \");\n const hyps = property.when\n ? [`(${arrowTerm(property.when, \"when\", property, types, e)} = true)`]\n : [];\n const claim = `(${arrowTerm(property.ensures, \"ensures\", property, types, e)} = true)`;\n const body = [...hyps, claim].join(\" →\\n \");\n return {\n // A function of no parameters has nothing to quantify over: the proposition stands alone.\n text: binders === \"\" ? body : `∀ ${binders},\\n ${body}`,\n hypotheses: hyps.length,\n };\n}\n\n/**\n * The tactic script every theorem is closed by. Booleans become\n * propositions first, while the `Decidable` instances in the statement\n * still match their propositions (unfolding under `decide` first leaves\n * them stale and stops `simp`); Bool binders are cased, so boolean claims\n * are decided by enumeration; then the module's definitions unfold, each\n * conditional splits, and linear integer arithmetic (`omega`) closes what\n * remains. Nothing here is specific to a property; what Lean checks is\n * the statement.\n */\nexport function tactics(module: SubsetModule, property: Property, hypotheses: number): string {\n const defs = module.functions.map((f) => ident.fn(f.name)).join(\", \");\n const names = property.binders.map((b) => ident.variable(b.name));\n const hyps = Array.from({ length: hypotheses }, (_, i) => `h${i}_`);\n const bools = property.binders\n .filter(\n (b) =>\n b.type.kind === \"boolean\" ||\n (b.type.kind === \"literal\" && typeof b.type.value === \"boolean\"),\n )\n .map((b) => ident.variable(b.name));\n const introduced = [...names, ...hyps];\n return [\n ...(introduced.length > 0 ? [` intro ${introduced.join(\" \")}`] : []),\n ...(bools.length > 0 ? [` ${bools.map((b) => `cases ${b}`).join(\" <;> \")}`] : []),\n \" all_goals (try simp_all)\",\n ` all_goals (try simp only [${defs}] at *)`,\n \" all_goals (repeat' (split <;> simp_all))\",\n \" all_goals (try simp_all)\",\n \" all_goals (first | decide | trivial | omega)\",\n ].join(\"\\n\");\n}\n\n/** A Lean-safe theorem name: unique by position, readable by the function's and property's names. */\nexport function theoremName(index: number, fn: string, property: string): string {\n return `t${index}_${fn}_${property}`.replace(/[^A-Za-z0-9_]/g, \"_\");\n}\n\nexport interface EmittedTheorem {\n readonly function: string;\n readonly property: string;\n readonly name: string;\n /** 1-based lines of the theorem in the emitted file, inclusive. */\n readonly from: number;\n readonly to: number;\n /** Closed by a supplied proof, not the tactic script. */\n readonly supplied?: true;\n /** For a supplied proof: the 1-based line of the `#print axioms` that audits it. */\n readonly axiomsLine?: number;\n /** For a supplied proof: the 1-based line of the `#check` that shows its type, which must be the statement alone. */\n readonly typeLine?: number;\n}\n\nexport interface Emitted {\n readonly source: string;\n readonly theorems: readonly EmittedTheorem[];\n /** Properties the emitter could not state, with why. */\n readonly skipped: readonly {\n readonly function: string;\n readonly property: string;\n readonly reason: string;\n }[];\n /** 1-based lines of the supplied lemmas in the emitted file, inclusive, when there are any. */\n readonly lemmas?: { readonly from: number; readonly to: number };\n}\n\n/** The supplied proofs to use: lemmas, and each property's tactic proof by name. */\nexport interface SuppliedText {\n readonly lemmas: string;\n readonly proofs: ReadonlyMap<string, string>;\n}\n\n/** A tactic block at the indentation a `by` takes: its common indentation stripped, two spaces put back. */\nfunction indented(block: string): string {\n const lines = block.split(\"\\n\");\n const widths = lines.filter((l) => l.trim() !== \"\").map((l) => /^ */.exec(l)?.[0].length ?? 0);\n const common = widths.length > 0 ? Math.min(...widths) : 0;\n return lines.map((l) => (l.trim() === \"\" ? \"\" : ` ${l.slice(common)}`)).join(\"\\n\");\n}\n\n/**\n * The whole file: structures, definitions, one theorem per property, any\n * extra lines (translation checks), then the properties with supplied\n * proofs: each statement fixed as a definition before any supplied text,\n * the supplied lemmas, each theorem proving its definition with the\n * supplied tactics, and `#print axioms` for each.\n */\nexport function emitModule(\n module: SubsetModule,\n properties: readonly { readonly function: string; readonly property: Property }[],\n extra: readonly string[] = [],\n supplied?: SuppliedText,\n): Emitted {\n const parts: string[] = [\n \"-- Generated by Eutaxy's first-party engine from the module and its spec file; the theorems are its properties.\",\n \"set_option linter.unusedSimpArgs false\",\n \"set_option linter.unusedVariables false\",\n ...module.records.map(emitRecord),\n ...module.functions.map((f) => emitFunction(f, module)),\n ];\n const theorems: EmittedTheorem[] = [];\n const skipped: Emitted[\"skipped\"][number][] = [];\n const later: { fn: string; property: string; name: string; statement: string; proof: string }[] =\n [];\n for (const { function: fn, property } of properties) {\n let body: { text: string; hypotheses: number };\n try {\n body = stated(property, module);\n } catch (err) {\n if (!(err instanceof OutsideSubset)) throw err;\n skipped.push({ function: fn, property: property.name, reason: err.message });\n continue;\n }\n const name = theoremName(theorems.length + skipped.length + later.length, fn, property.name);\n const proof = supplied?.proofs.get(property.name);\n if (proof !== undefined) {\n later.push({ fn, property: property.name, name, statement: body.text, proof });\n continue;\n }\n const text = `theorem ${name} :\\n ${body.text} := by\\n${tactics(module, property, body.hypotheses)}`;\n const from = parts.join(\"\\n\\n\").split(\"\\n\").length + 2;\n parts.push(text);\n theorems.push({\n function: fn,\n property: property.name,\n name,\n from,\n to: from + text.split(\"\\n\").length - 1,\n });\n }\n parts.push(...extra);\n const lineAfter = () => parts.join(\"\\n\\n\").split(\"\\n\").length + 2;\n let lemmas: Emitted[\"lemmas\"];\n if (later.length > 0) {\n for (const l of later) parts.push(`def s_${l.name} : Prop :=\\n ${l.statement}`);\n if (supplied && supplied.lemmas !== \"\") {\n const from = lineAfter();\n parts.push(supplied.lemmas);\n lemmas = { from, to: from + supplied.lemmas.split(\"\\n\").length - 1 };\n }\n const ownProofs: EmittedTheorem[] = [];\n for (const l of later) {\n const text = `theorem ${l.name} : s_${l.name} := by\\n unfold s_${l.name}\\n${indented(l.proof)}`;\n const from = lineAfter();\n parts.push(text);\n ownProofs.push({\n function: l.fn,\n property: l.property,\n name: l.name,\n from,\n to: from + text.split(\"\\n\").length - 1,\n supplied: true,\n });\n }\n // Each audit's line is recorded: only Lean's message at that line counts as the audit.\n for (const t of ownProofs) {\n // Its type, as Lean has it: a hypothesis the supplied text slipped in (a section variable) shows here.\n const typeLine = lineAfter();\n parts.push(`#check @${t.name}`);\n const axiomsLine = lineAfter();\n parts.push(`#print axioms ${t.name}`);\n theorems.push({ ...t, axiomsLine, typeLine });\n }\n }\n return { source: `${parts.join(\"\\n\\n\")}\\n`, theorems, skipped, ...(lemmas ? { lemmas } : {}) };\n}\n\n/**\n * A JavaScript string as a Lean string literal: `\"` and `\\` escaped, control\n * characters as `\\xHH`, everything else written as it is (Lean source is\n * UTF-8). A lone surrogate has no Lean character and is refused.\n */\nexport function leanString(value: string): string {\n if (hasLoneSurrogate(value))\n fail(\"a string with a lone surrogate, which Lean's strings cannot hold\");\n let out = '\"';\n for (const c of value) {\n const code = c.codePointAt(0) as number;\n if (c === '\"') out += '\\\\\"';\n else if (c === \"\\\\\") out += \"\\\\\\\\\";\n else if (code < 0x20 || code === 0x7f) out += `\\\\x${code.toString(16).padStart(2, \"0\")}`;\n else out += c;\n }\n return `${out}\"`;\n}\n\n/** A TypeScript value of a subset type as a Lean term, for translation checks. */\nexport function value(v: unknown, t: SubsetType, module: SubsetModule): string {\n switch (t.kind) {\n case \"int\":\n if (typeof v !== \"number\" || !Number.isInteger(v)) fail(`${String(v)} is not an integer`);\n return `(${v} : Int)`;\n case \"bool\":\n if (typeof v !== \"boolean\") fail(`${String(v)} is not a boolean`);\n return v ? \"true\" : \"false\";\n case \"string\":\n if (typeof v !== \"string\") fail(`${String(v)} is not a string`);\n return leanString(v);\n case \"record\": {\n const rec = module.records.find((r) => r.name === t.name) ?? fail(`no record ${t.name}`);\n if (typeof v !== \"object\" || v === null) fail(`${String(v)} is not a record`);\n const o = v as Record<string, unknown>;\n const extra = Object.keys(o).filter((k) => !rec.fields.some((f) => f.name === k));\n if (extra.length > 0) fail(`${t.name} value has unexpected fields ${extra.join(\", \")}`);\n return `({ ${rec.fields.map((f) => `${ident.field(f.name)} := ${value(o[f.name], f.type, module)}`).join(\", \")} } : ${ident.record(t.name)})`;\n }\n case \"list\":\n if (!Array.isArray(v)) fail(`${String(v)} is not an array`);\n return `([${v.map((x) => value(x, t.element, module)).join(\", \")}] : ${leanType(t)})`;\n case \"nothing\":\n return fail(\"a value of no type\");\n case \"nullable\":\n case \"union\":\n case \"null\":\n return fail(`a ${t.kind} type, which the Lean engine does not take yet`);\n }\n}\n","/**\n * Running Lean over a process boundary. The engine is pinned to one Lean\n * release, looked for through elan (Lean's toolchain manager), asked for it\n * by name: Eutaxy's own elan in its cache first (where `eutaxy prover\n * install lean` puts one when the machine has none), then the user's; then\n * as a bare `lean` that must report that version. Nothing is ever downloaded during\n * a check; a missing toolchain is `unavailable`, with the command that\n * installs it. Diagnostics come back as `file:line:col: severity: message`\n * lines, which the engine maps to theorems.\n */\n\nimport { spawn } from \"node:child_process\";\nimport { mkdtempSync, rmSync, writeFileSync } from \"node:fs\";\nimport { homedir, tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { type Host, host } from \"@eutaxy/prover/toolchain\";\nimport { type Elan, elanCandidates } from \"./elan.ts\";\n\n/**\n * The Lean release the engine's contract corpus is checked against. On a\n * bump: run the corpus and the supplied-proof tests on the new release,\n * and read its release notes for a new command that runs code while a\n * file is checked (a `#` command is already refused; a new word goes into\n * `supplied.ts`'s refused list in the same change). CI caches the\n * toolchain by this file's hash.\n */\nexport const leanToolchain = \"leanprover/lean4:v4.35.0\";\nexport const leanVersion = \"4.35.0\";\n/** How to put the pinned toolchain on this machine. */\nexport const installHint = `run: eutaxy prover install lean (or install elan, https://elan.lean-lang.org, and run: elan toolchain install ${leanToolchain})`;\n\nexport interface LeanRun {\n readonly code: number | null;\n readonly stdout: string;\n readonly stderr: string;\n readonly timedOut: boolean;\n}\n\nexport interface LeanDiagnostic {\n readonly line: number;\n readonly column: number;\n readonly severity: \"error\" | \"warning\" | \"info\";\n readonly message: string;\n}\n\nexport interface LeanToolchain {\n /** The `lean` executable to run, with the arguments that select the pinned toolchain. */\n readonly command: string;\n readonly args: readonly string[];\n readonly version: string;\n /** Environment to add when running it (`ELAN_HOME` for Eutaxy's own elan). */\n readonly env?: Readonly<Record<string, string>>;\n}\n\nfunction run(\n command: string,\n args: readonly string[],\n options: {\n readonly cwd?: string;\n readonly timeoutMs: number;\n readonly env?: Readonly<Record<string, string>> | undefined;\n },\n): Promise<LeanRun> {\n return new Promise((resolve) => {\n let child: ReturnType<typeof spawn>;\n try {\n // Its own process group, so a timeout kills `lean` under `elan run`, not just elan.\n child = spawn(command, args, {\n cwd: options.cwd,\n ...(options.env === undefined ? {} : { env: { ...process.env, ...options.env } }),\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n detached: process.platform !== \"win32\",\n });\n } catch (err) {\n resolve({ code: null, stdout: \"\", stderr: String(err), timedOut: false });\n return;\n }\n let stdout = \"\";\n let stderr = \"\";\n let timedOut = false;\n const timer = setTimeout(() => {\n timedOut = true;\n try {\n if (process.platform !== \"win32\" && child.pid !== undefined)\n process.kill(-child.pid, \"SIGKILL\");\n else child.kill(\"SIGKILL\");\n } catch {\n child.kill(\"SIGKILL\");\n }\n }, options.timeoutMs);\n child.stdout?.on(\"data\", (d: Buffer) => {\n stdout += d.toString();\n });\n child.stderr?.on(\"data\", (d: Buffer) => {\n stderr += d.toString();\n });\n child.on(\"error\", (err) => {\n clearTimeout(timer);\n resolve({ code: null, stdout, stderr: `${stderr}${String(err)}`, timedOut });\n });\n child.on(\"close\", (code) => {\n clearTimeout(timer);\n resolve({ code, stdout, stderr, timedOut });\n });\n });\n}\n\n/** Candidates for a bare `lean`: the PATH, then elan's default home. */\nfunction leanCandidates(h: Host): string[] {\n const home = h.env[\"ELAN_HOME\"] || join(h.home || homedir(), \".elan\");\n return [\"lean\", join(home, \"bin\", \"lean\")];\n}\n\n/**\n * The pinned toolchain if it is installed: through `elan run <toolchain>`\n * with the first elan that has it (Eutaxy's own, then the user's), else,\n * only when no elan answered at all, a bare `lean` of exactly that version.\n * Nothing is downloaded: an elan is run only for its toolchain list, and\n * with an elan present a bare `lean` would be its proxy.\n */\nexport async function findLean(\n h: Host = host(),\n elans: readonly Elan[] = elanCandidates(h),\n leans: readonly string[] = leanCandidates(h),\n): Promise<LeanToolchain | { readonly unavailable: string }> {\n let lacking: string | undefined;\n for (const elan of elans) {\n const list = await run(elan.command, [\"toolchain\", \"list\"], {\n timeoutMs: 20_000,\n env: elan.env,\n });\n if (list.code !== 0) continue;\n if (list.stdout.split(\"\\n\").some((l) => l.trim().split(\" \")[0] === leanToolchain))\n return {\n command: elan.command,\n args: [\"run\", leanToolchain, \"lean\"],\n version: leanVersion,\n ...(elan.env === undefined ? {} : { env: elan.env }),\n };\n lacking ??= `elan (${elan.command}) has no ${leanToolchain}`;\n }\n // With an elan on the machine a bare `lean` is most likely its proxy, which downloads whatever\n // toolchain it is asked for: never run it then, so a check downloads nothing.\n if (lacking !== undefined) return { unavailable: `${lacking}; ${installHint}` };\n for (const lean of leans) {\n const v = await run(lean, [\"--version\"], { timeoutMs: 20_000 });\n if (v.code !== 0) continue;\n const m = /Lean \\(version ([^,]+),/.exec(v.stdout);\n if (m?.[1] === leanVersion) return { command: lean, args: [], version: leanVersion };\n return {\n unavailable: `lean ${m?.[1] ?? \"of unknown version\"} found, but the engine is pinned to ${leanVersion}; ${installHint}`,\n };\n }\n return { unavailable: `no Lean toolchain found; ${installHint}` };\n}\n\n/** Parse Lean's diagnostics for the one file it was given. */\n/**\n * Lean's messages from `--json` output: one object per line, each with\n * its position. Lines that are not such an object (whatever a program\n * writes to the terminal) are not messages and are skipped, so nothing in\n * the checked file can pose as a message at a position it is not at.\n */\nexport function jsonDiagnostics(output: string): LeanDiagnostic[] {\n const out: LeanDiagnostic[] = [];\n for (const raw of output.split(\"\\n\")) {\n if (!raw.startsWith(\"{\")) continue;\n let m: { pos?: { line?: unknown; column?: unknown }; severity?: unknown; data?: unknown };\n try {\n m = JSON.parse(raw) as typeof m;\n } catch {\n continue;\n }\n const severity =\n m.severity === \"error\"\n ? \"error\"\n : m.severity === \"warning\"\n ? \"warning\"\n : m.severity === \"information\"\n ? \"info\"\n : undefined;\n if (severity === undefined || typeof m.pos?.line !== \"number\" || typeof m.data !== \"string\")\n continue;\n out.push({\n line: m.pos.line,\n column: typeof m.pos.column === \"number\" ? m.pos.column : 0,\n severity,\n message: m.data.trimEnd(),\n });\n }\n return out;\n}\n\nexport function diagnostics(output: string): LeanDiagnostic[] {\n const out: LeanDiagnostic[] = [];\n const re = /^(?:.*?):(\\d+):(\\d+): (error|warning|info): (.*)$/;\n let current:\n | { line: number; column: number; severity: LeanDiagnostic[\"severity\"]; lines: string[] }\n | undefined;\n const flush = (c: NonNullable<typeof current>) =>\n out.push({\n line: c.line,\n column: c.column,\n severity: c.severity,\n message: c.lines.join(\"\\n\").trimEnd(),\n });\n for (const raw of output.split(\"\\n\")) {\n const m = re.exec(raw);\n if (m) {\n if (current) flush(current);\n current = {\n line: Number(m[1]),\n column: Number(m[2]),\n severity: m[3] as LeanDiagnostic[\"severity\"],\n lines: [m[4] as string],\n };\n } else if (current) current.lines.push(raw);\n }\n if (current) flush(current);\n return out;\n}\n\nexport interface CheckedFile {\n readonly run: LeanRun;\n readonly diagnostics: readonly LeanDiagnostic[];\n}\n\n/** Write the source to a scratch directory pinned to the toolchain and check it. */\nexport async function checkLean(\n toolchain: LeanToolchain,\n source: string,\n options: { readonly timeoutMs?: number; readonly keep?: boolean } = {},\n): Promise<CheckedFile> {\n const dir = mkdtempSync(join(tmpdir(), \"eutaxy-lean-\"));\n try {\n writeFileSync(join(dir, \"lean-toolchain\"), `${leanToolchain}\\n`);\n writeFileSync(join(dir, \"Eutaxy.lean\"), source);\n const result = await run(toolchain.command, [...toolchain.args, \"--json\", \"Eutaxy.lean\"], {\n cwd: dir,\n timeoutMs: options.timeoutMs ?? 120_000,\n env: toolchain.env,\n });\n return { run: result, diagnostics: jsonDiagnostics(`${result.stdout}\\n${result.stderr}`) };\n } finally {\n if (!options.keep) rmSync(dir, { recursive: true, force: true });\n }\n}\n","/**\n * Proofs supplied beside a spec file, for claims the engine's tactic\n * script does not close: `domain.props.lean` beside `domain.props.ts`.\n * Lemmas come first; then each `-- proof: <property>` line opens the\n * tactic proof of that property's statement, which Eutaxy emits and the\n * proof cannot change (it is fixed as a definition before any supplied\n * text). Lean's kernel checks the proof, and Eutaxy accepts it only when\n * it rests on Lean's standard axioms; what could switch checking off, add\n * an axiom or change how the statement reads is refused outright.\n */\n\nexport interface SuppliedProofs {\n /** The proof file's name, for verdicts. */\n readonly file: string;\n /** Everything before the first `-- proof:` line: lemmas the proofs use. */\n readonly lemmas: string;\n /** Each property's tactic proof, by property name (the names also when the file is refused). */\n readonly proofs: ReadonlyMap<string, string>;\n /** Why the file is refused, when it is; then none of its proofs is used, and its properties say why. */\n readonly refused?: string;\n /** The SHA-256 of the module source the proofs were written for, when the file says (a goal file does). */\n readonly sourceSha256?: string;\n /** The SHA-256 of the spec file the proofs were written for, when the file says. */\n readonly specSha256?: string;\n}\n\n/** The lines a goal file carries, and a proof file copied from one keeps, tying the proofs to the files they were written for. */\nexport const sourceHashMarker = \"-- eutaxy-source-sha256: \";\nexport const specHashMarker = \"-- eutaxy-spec-sha256: \";\n\n/** The axioms a supplied proof may rest on: Lean's standard ones. */\nexport const standardAxioms: ReadonlySet<string> = new Set([\n \"propext\",\n \"Classical.choice\",\n \"Quot.sound\",\n]);\n\n/**\n * Words a supplied proof may not use, anywhere in the file, comments and\n * strings included: what adds axioms or trusted code (`axiom`, `sorry`,\n * `unsafe`, `implemented_by`, `extern`, `opaque`, `native_decide`),\n * switches checks off (`set_option`), registers code Lean would run while\n * the file is checked (`attribute`, `initialize`, `simproc` and the like)\n * or changes how text reads (`macro`, `syntax`, `notation` and the like),\n * and `import`. The list narrows when a legitimate proof is refused and\n * grows only with a Lean bump that adds such a command (see\n * `leanToolchain`); never because of what a hostile file could do, which\n * the design answers.\n */\nconst refusedWords = [\n \"sorry\",\n \"admit\",\n \"axiom\",\n \"unsafe\",\n \"implemented_by\",\n \"extern\",\n \"opaque\",\n \"native_decide\",\n \"set_option\",\n \"macro\",\n \"macro_rules\",\n \"syntax\",\n \"notation\",\n \"infix\",\n \"infixl\",\n \"infixr\",\n \"prefix\",\n \"postfix\",\n \"elab\",\n \"elab_rules\",\n \"import\",\n \"attribute\",\n \"initialize\",\n \"simproc\",\n \"dsimproc\",\n \"simproc_decl\",\n \"dsimproc_decl\",\n // Section variables become hypotheses of the theorems after them: `variable (h : False)` would.\n \"section\",\n \"namespace\",\n \"variable\",\n \"include\",\n \"omit\",\n \"universe\",\n];\n\n/** Command families refused by how a word starts: `run_cmd`, `builtin_initialize`, `register_option`, `declare_syntax_cat`. */\nconst refusedStarts = [\"run_\", \"builtin_\", \"register_\", \"declare_\"];\n\n/**\n * Refused wherever they appear, inside a name too: every command run\n * while the file is checked starts with `#`, and every attribute (which\n * can hand Lean a tactic, an elaborator or a simplification procedure to\n * run) with `@[`.\n */\nconst refusedAnywhere = [\"#\", \"@[\"];\n\n/** Lean's ASCII identifier characters after the first. */\nconst identRest = /[A-Za-z0-9_'!?]/u;\n\n/**\n * Whether the text just before `at` continues a name, so that a word\n * starting there is part of that name rather than a token of its own.\n * Only a run of identifier characters that starts with an ASCII letter or\n * `_` counts: one that starts with a digit is a numeral, and Lean starts a\n * new token right after a numeral (`0xfsorry` is `0xf`, then `sorry`).\n * Anything else (`.`, `«`, Unicode) counts as a boundary, which refuses\n * more, never less.\n */\nfunction continuesName(text: string, at: number): boolean {\n let i = at;\n while (i > 0 && identRest.test(text[i - 1] as string)) i--;\n return i < at && /[A-Za-z_]/u.test(text[i] as string);\n}\n\n/** The first refused word or command the text holds, as a token of its own, or undefined. */\nexport function refusedIn(text: string): string | undefined {\n const anywhere = refusedAnywhere.find((w) => text.includes(w));\n if (anywhere !== undefined) return anywhere;\n for (const [words, whole] of [\n [refusedWords, true],\n [refusedStarts, false],\n ] as const) {\n for (const w of words) {\n for (let at = text.indexOf(w); at >= 0; at = text.indexOf(w, at + 1)) {\n if (continuesName(text, at)) continue;\n // A whole word followed by an identifier character is a longer name, which Lean reads as one.\n if (whole && identRest.test(text[at + w.length] ?? \"\")) continue;\n return w;\n }\n }\n }\n return undefined;\n}\n\n/** `-- proof: <property>`: any name the spec file can export, Unicode letters included. */\nconst marker = /^-- proof: (\\S+)\\s*$/u;\n\n/** Read a proof file: its lemmas, its proofs by property, or why it is refused. */\nexport function readSupplied(file: string, text: string): SuppliedProofs {\n const lemmas: string[] = [];\n const proofs = new Map<string, string[]>();\n let current: string[] = lemmas;\n let twice: string | undefined;\n for (const line of text.split(\"\\n\")) {\n const m = marker.exec(line);\n if (!m) {\n current.push(line);\n continue;\n }\n const name = m[1] as string;\n twice ??= proofs.has(name) ? name : undefined;\n current = [];\n proofs.set(name, current);\n }\n if (twice !== undefined) return refuse({ file, proofs }, `${file} proves ${twice} twice`);\n // Checked over the whole text, comments and strings too: telling them apart is lexing Lean, and a\n // lexer that slips (`\"/-\"` in a string read as a comment) would let a refused command through. A\n // refused word in a comment refuses the file as well, which costs a word, never soundness.\n const word = refusedIn(text);\n if (word !== undefined)\n return refuse(\n { file, proofs },\n `${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)`,\n );\n const hashLine = (marker: string): string | undefined => {\n const line = lemmas.find((l) => l.startsWith(marker));\n const hex = line?.slice(marker.length).trim();\n return hex !== undefined && /^[0-9a-f]{64}$/.test(hex) ? hex : undefined;\n };\n const sourceSha256 = hashLine(sourceHashMarker);\n const specSha256 = hashLine(specHashMarker);\n return {\n file,\n lemmas: lemmas.join(\"\\n\").trim(),\n proofs: new Map([...proofs].map(([k, v]) => [k, v.join(\"\\n\").replace(/\\s+$/, \"\")])),\n ...(sourceSha256 === undefined ? {} : { sourceSha256 }),\n ...(specSha256 === undefined ? {} : { specSha256 }),\n };\n}\n\n/** The file refused: none of its proofs is used, and every property it names says why. */\nexport function refuse(\n supplied: { readonly file: string; readonly proofs: ReadonlyMap<string, unknown> },\n reason: string,\n): SuppliedProofs {\n return {\n file: supplied.file,\n lemmas: \"\",\n proofs: new Map([...supplied.proofs.keys()].map((k) => [k, \"\"])),\n refused: reason,\n };\n}\n\n/** Lean's messages at one line: an audit is read only when Lean's own message is the only one there. */\nfunction onlyAt(\n messages: readonly {\n readonly line: number;\n readonly severity: string;\n readonly message: string;\n }[],\n line: number,\n): string | undefined {\n const at = messages.filter((m) => m.line === line);\n return at.length === 1 && at[0]?.severity === \"info\" ? at[0].message : undefined;\n}\n\n/**\n * The axioms Lean reports a theorem depends on: the message of the\n * `#print axioms` at `line`, Eutaxy's own audit command, and no other.\n * Undefined unless that message is the only one at the line: anything\n * else there (a forged copy, printed by code the file ran) makes the\n * audit unreadable rather than letting either message stand.\n */\nexport function axiomsOf(\n messages: readonly {\n readonly line: number;\n readonly severity: string;\n readonly message: string;\n }[],\n line: number,\n theorem: string,\n): string[] | undefined {\n const message = onlyAt(messages, line);\n if (message === undefined) return undefined;\n if (message === `'${theorem}' does not depend on any axioms`) return [];\n const prefix = `'${theorem}' depends on axioms: [`;\n if (message.startsWith(prefix) && message.endsWith(\"]\"))\n return message\n .slice(prefix.length, -1)\n .split(\",\")\n .map((x) => x.trim())\n .filter((x) => x.length > 0);\n return undefined;\n}\n\n/**\n * Whether Lean's message at the `#check` of a supplied theorem shows it\n * proves exactly its fixed statement `s_<name>`: no hypothesis added (a\n * section variable would show as `False → …`).\n */\nexport function provesExactly(\n messages: readonly {\n readonly line: number;\n readonly severity: string;\n readonly message: string;\n }[],\n line: number,\n theorem: string,\n): boolean {\n return onlyAt(messages, line) === `${theorem} : s_${theorem}`;\n}\n","/**\n * The goal file: the properties the tactic script gave up on, each with\n * the statement Lean was asked to prove, written in the form of the proof\n * file the engine accepts (`domain.props.lean`) with every proof left\n * open. A coding agent copies it beside the spec file, puts lemmas above\n * the proofs and tactics under them, and the engine checks them as it\n * checks any supplied proof: nothing new is trusted. The hashes tie the\n * proofs to the module and the spec they were written for; the engine\n * calls a proof file stale once either changed.\n */\n\nimport type { OpenGoal } from \"@eutaxy/prover\";\nimport { ident } from \"./emit.ts\";\nimport { leanVersion } from \"./lean.ts\";\nimport { refusedIn, sourceHashMarker, specHashMarker } from \"./supplied.ts\";\n\nexport interface GoalFileInput {\n /** The spec file's name, for the header: `domain.props.ts`. */\n readonly specFile: string;\n readonly sourceSha256: string;\n readonly specSha256: string;\n readonly goals: readonly OpenGoal[];\n}\n\n/** The proof file's name beside a spec file: `domain.props.lean` for `domain.props.ts`. */\nexport function proofFileFor(specFile: string): string {\n return specFile.replace(/\\.ts$/, \".lean\");\n}\n\n/** The goal file's name beside a spec file: `domain.props.goals.lean` for `domain.props.ts`. */\nexport function goalFileFor(specFile: string): string {\n return specFile.replace(/\\.ts$/, \".goals.lean\");\n}\n\n/** A line of generated commentary: one a proof file may hold, or a note that it was left out. */\nconst commentLine = (text: string): string =>\n refusedIn(text) === undefined\n ? text\n : \"-- (a line left out: it held a word a proof file may not use)\";\n\nconst comment = (text: string): string =>\n text\n .split(\"\\n\")\n .map((l) => commentLine(l.length > 0 ? `-- ${l}` : \"--\"))\n .join(\"\\n\");\n\n/**\n * Render the goal file: the header with the hashes, each goal described\n * in comments (the proof file's lemma area, where comments cost nothing),\n * then one open `-- proof:` part per goal at the end, since everything\n * after a `-- proof:` line belongs to that proof. The text avoids every\n * word a supplied proof may not use, so the file copied as is reads as a\n * proof file with open proofs: every generated line is checked, and one\n * that would refuse the file (a reason Lean gave, a file or function name\n * that is itself a refused word) is left out, with a note in its place.\n * The function is named by its Lean identifier, as the statement names it.\n */\nexport function renderGoals(input: GoalFileInput): string {\n const header = [\n `-- Open proof goals for ${input.specFile}, written by Eutaxy's Lean engine (Lean ${leanVersion}).`,\n \"-- Each goal below is a property the tactic script could not close, with the statement Eutaxy\",\n \"-- emits for it. To supply proofs, copy this file to\",\n `-- ${proofFileFor(input.specFile)} beside the spec file, put lemmas above the \\`-- proof:\\` lines and`,\n \"-- tactics under each, and run the engine again (eutaxy report --prover lean). The hashes tie the\",\n \"-- proofs to these versions of the module and the spec: once either changes, the proofs are stale\",\n \"-- until the goals are written again.\",\n `${sourceHashMarker}${input.sourceSha256}`,\n `${specHashMarker}${input.specSha256}`,\n ];\n const described = input.goals.map((g) =>\n [\n commentLine(`-- goal: ${g.property}, a property of ${ident.fn(g.function)}`),\n commentLine(`-- Lean said: ${g.reason}`),\n \"-- statement:\",\n comment(g.statement.replace(/^/gm, \" \")),\n ].join(\"\\n\"),\n );\n const open = input.goals.map((g) => `-- proof: ${g.property}\\n -- tactics here`);\n return `${[header.map(commentLine).join(\"\\n\"), ...described, ...open].join(\"\\n\\n\")}\\n`;\n}\n","/**\n * The engine: a module's functions through the subset reader, the emitter\n * and Lean, and each property's outcome back. One Lean run per module;\n * errors are mapped to theorems by line, so one failed proof does not hide\n * another. A proof that fails is `gave_up` (the engine is weak or the\n * claim is false; Lean does not say which), a function or property outside\n * the subset is `unsupported`, and no pinned toolchain is `unavailable`.\n * `total` is proved by Lean accepting the definition.\n */\n\nimport { createHash } from \"node:crypto\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { basename } from \"node:path\";\nimport {\n type ModuleProofs,\n type OpenGoal,\n type ProofOutcome,\n type PropertyProof,\n type Prover,\n type ProveInput as ProverInput,\n proofsOf,\n unknownOutcome,\n} from \"@eutaxy/prover\";\nimport {\n builtinsAssumption,\n children,\n type Expr,\n engineGap,\n listKinds,\n OutsideSubset,\n outsideProofs,\n readForEngine,\n type SubsetFunction,\n type SubsetModule,\n type SubsetType,\n} from \"@eutaxy/prover/reader\";\nimport type { FunctionSpec, Property, SpecError, SpecType } from \"@eutaxy/spec\";\nimport { dividesOutside, divisionOutside, type Emitted, emitModule, stated } from \"./emit.ts\";\nimport { checkLean, findLean, type LeanDiagnostic, leanVersion } from \"./lean.ts\";\nimport {\n axiomsOf,\n provesExactly,\n readSupplied,\n refuse,\n type SuppliedProofs,\n standardAxioms,\n} from \"./supplied.ts\";\n\nexport const engineName = \"lean\";\n\n/** The types this engine translates: the integers, Bool, String and records of those. */\nexport const leanTakes = (t: SubsetType): boolean =>\n t.kind === \"int\" ||\n t.kind === \"bool\" ||\n t.kind === \"string\" ||\n t.kind === \"record\" ||\n (t.kind === \"list\" && leanTakes(t.element));\n\nexport type { ModuleProofs, ProofOutcome, PropertyProof } from \"@eutaxy/prover\";\n\nexport interface ProveInput extends ProverInput {\n /** Extra Lean lines appended after the theorems (translation checks). */\n readonly extra?: readonly string[];\n}\n\n/** This engine's report, with the Lean it checked. */\nexport interface LeanModuleProofs extends ModuleProofs {\n /** The Lean source checked, when any function was in the subset. */\n readonly lean?: string;\n}\n\n/** What every PROVEN verdict of this engine rests on. */\nexport const engineAssumptions: readonly string[] = [\n \"number is modelled as the unbounded integers: no overflow, no fractions, no NaN\",\n \"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\",\n \"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\",\n builtinsAssumption,\n `the proof was checked by the Lean ${leanVersion} kernel on the emitted statement, not by Eutaxy`,\n];\n\n/** What a PROVEN over arrays rests on besides: the list model. */\nexport const listAssumption =\n \"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\";\n\n/** What a PROVEN that unfolds a recursive function rests on besides: that the JavaScript returns. */\nexport const recursionAssumption =\n \"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\";\n\nconst proven: Extract<ProofOutcome, { kind: \"PROVEN\" }> = {\n kind: \"PROVEN\",\n engine: { name: engineName, version: leanVersion },\n assumptions: engineAssumptions,\n};\n\nconst unknown = unknownOutcome;\n\n/** The emitted Lean for the module's functions in the subset, and the functions with specs outside it with why. */\nexport interface Prepared {\n readonly module: SubsetModule;\n /** The proofs supplied beside the spec file, when there is a proof file. */\n readonly supplied?: SuppliedProofs;\n readonly emitted: Emitted;\n /** The functions to report on. */\n readonly fns: readonly FunctionSpec[];\n /** Those of them the subset does not take, with the reason. */\n readonly outside: ReadonlyMap<string, string>;\n /** Specs that did not read. */\n readonly specErrors: readonly SpecError[];\n}\n\n/**\n * Read and emit. Every function the subset takes is emitted (callees\n * included); properties are stated for the ones with specs among them.\n */\nexport function prepare(input: ProveInput): Prepared {\n const specs = input.specs;\n // Nullable types and tagged unions are read, but this engine does not take them yet: the SMT engine does.\n // Division leaves the integers this engine models, except as Math.floor(x / c).\n const read = readForEngine(input, [\n {\n takes: leanTakes,\n reason: \"nullable types and tagged unions are not in the Lean engine's subset yet\",\n },\n { takes: () => true, reason: divisionOutside, bodies: new Set(), refused: dividesOutside },\n ]);\n const { module, fns, outside } = read;\n const properties: { function: string; property: Property }[] = fns\n .filter((fn) => !outside.has(fn.name))\n .flatMap((fn) =>\n fn.properties\n .filter((p) => p.kind === \"forall\")\n .map((property) => ({ function: fn.name, property })),\n );\n const specErrors = specs.errors;\n // Proofs supplied beside the spec file: `domain.props.lean` beside `domain.props.ts`. A file that\n // names the hashes of the source and spec it was written for (a goal file does) is stale once either\n // changed: its proofs are not used, and its properties say so, rather than failing one by one on a\n // statement that moved under them.\n const proofFile = input.specPath?.replace(/\\.ts$/, \".lean\");\n let supplied =\n proofFile !== undefined && existsSync(proofFile)\n ? readSupplied(basename(proofFile), readFileSync(proofFile, \"utf8\"))\n : undefined;\n if (supplied && !supplied.refused) {\n const stale = staleness(supplied, input);\n if (stale !== undefined) supplied = refuse(supplied, stale);\n }\n try {\n return {\n module,\n ...(supplied ? { supplied } : {}),\n emitted: emitModule(\n module,\n properties,\n input.extra,\n supplied && !supplied.refused ? supplied : undefined,\n ),\n fns,\n outside,\n specErrors,\n };\n } catch (err) {\n // The emitter refusing something the reader let through is an engine gap: every function is unsupported, none guessed.\n if (!(err instanceof OutsideSubset)) throw err;\n engineGap(read, err.message);\n const empty: Emitted = { source: \"\", theorems: [], skipped: [] };\n return { module, emitted: empty, fns, outside, specErrors };\n }\n}\n\nconst sha256 = (text: string): string => createHash(\"sha256\").update(text).digest(\"hex\");\n\n/** Why a proof file is stale, when it names the hashes of the files it was written for and either moved. */\nfunction staleness(supplied: SuppliedProofs, input: ProveInput): string | undefined {\n const moved: string[] = [];\n if (supplied.sourceSha256 !== undefined && supplied.sourceSha256 !== sha256(input.source))\n moved.push(\"the module\");\n if (\n supplied.specSha256 !== undefined &&\n input.specPath !== undefined &&\n existsSync(input.specPath)\n ) {\n if (supplied.specSha256 !== sha256(readFileSync(input.specPath, \"utf8\")))\n moved.push(\"the spec file\");\n }\n if (moved.length === 0) return undefined;\n 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`;\n}\n\n/**\n * A supplied proof's outcome: given up on when its lemmas or its tactics\n * do not compile, or when it rests on an axiom beyond Lean's standard\n * ones (`sorry` is one); PROVEN otherwise, saying it was supplied.\n */\nfunction suppliedOutcome(\n file: string,\n error: LeanDiagnostic | undefined,\n axioms: readonly string[] | undefined,\n exact: boolean,\n assumptions: readonly string[],\n): ProofOutcome {\n if (error)\n return unknown(\n \"gave_up\",\n `the proof supplied in ${file} does not close: ${error.message.split(\"\\n\")[0]}`,\n );\n if (!exact)\n return unknown(\n \"gave_up\",\n `the proof supplied in ${file} proves more hypotheses than its statement has (a section variable?), or Lean did not report its type`,\n );\n if (axioms === undefined)\n return unknown(\"gave_up\", `Lean did not report the axioms of the proof supplied in ${file}`);\n const beyond = axioms.filter((a) => !standardAxioms.has(a));\n if (beyond.length > 0)\n return unknown(\n \"gave_up\",\n `the proof supplied in ${file} rests on ${beyond.join(\", \")}, beyond Lean's standard axioms`,\n );\n return {\n ...proven,\n assumptions: [\n ...assumptions,\n `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`,\n ],\n };\n}\n\n/** Prove a module's properties with the pinned Lean. */\nexport async function proveModule(input: ProveInput): Promise<LeanModuleProofs> {\n const { module, emitted, fns, outside, specErrors, supplied } = prepare(input);\n const inSubset = fns.filter((f) => !outside.has(f.name));\n const unsupported = outsideProofs(fns, outside);\n if (inSubset.length === 0) return { results: unsupported, specErrors };\n const lean = emitted.source;\n const rest = (outcome: ProofOutcome): LeanModuleProofs => ({\n results: [...unsupported, ...proofsOf(inSubset, outcome)],\n lean,\n specErrors,\n });\n const toolchain = await findLean();\n if (\"unavailable\" in toolchain) return rest(unknown(\"unavailable\", toolchain.unavailable));\n const timeoutMs = input.timeoutMs ?? 120_000;\n const checked = await checkLean(toolchain, lean, { timeoutMs });\n if (checked.run.timedOut)\n return rest(unknown(\"gave_up\", `Lean did not finish within ${timeoutMs} ms`));\n const errors = checked.diagnostics.filter((d) => d.severity === \"error\");\n const inTheorem = (d: LeanDiagnostic) =>\n emitted.theorems.find((t) => d.line >= t.from && d.line <= t.to);\n if (checked.run.code === null || (checked.run.code !== 0 && errors.length === 0))\n return rest(\n unknown(\n \"unavailable\",\n `Lean could not be run: ${checked.run.stderr.trim() || `exit ${checked.run.code}`}`,\n ),\n );\n const inLemmas = (d: LeanDiagnostic) =>\n emitted.lemmas !== undefined && d.line >= emitted.lemmas.from && d.line <= emitted.lemmas.to;\n const lemmaErrors = errors.filter(inLemmas);\n const elsewhere = errors.filter((d) => !inTheorem(d) && !inLemmas(d));\n if (elsewhere.length > 0) {\n // The emitted definitions themselves did not compile: an engine gap, never a verdict on the property.\n const where = elsewhere.map((d) => `line ${d.line}: ${d.message.split(\"\\n\")[0]}`).join(\"; \");\n return rest(unknown(\"unsupported\", `the emitted Lean did not compile: ${where}`));\n }\n const results: PropertyProof[] = [...unsupported];\n for (const fn of inSubset) {\n for (const property of fn.properties) {\n if (property.kind === \"total\") {\n results.push({\n function: fn.name,\n property: property.name,\n outcome: {\n ...proven,\n assumptions: [\n ...engineAssumptions,\n ...modelAssumptions(property, fn.name, module),\n \"Lean accepted the definition, so it terminates on every input\",\n ],\n },\n });\n continue;\n }\n const skipped = emitted.skipped.find(\n (s) => s.function === fn.name && s.property === property.name,\n );\n if (skipped) {\n results.push({\n function: fn.name,\n property: property.name,\n outcome: unknown(\"unsupported\", skipped.reason),\n });\n continue;\n }\n if (supplied?.refused && supplied.proofs.has(property.name)) {\n results.push({\n function: fn.name,\n property: property.name,\n outcome: unknown(\"gave_up\", supplied.refused),\n });\n continue;\n }\n const theorem = emitted.theorems.find(\n (t) => t.function === fn.name && t.property === property.name,\n );\n const failed = theorem\n ? errors.filter((d) => d.line >= theorem.from && d.line <= theorem.to)\n : [];\n if (theorem?.supplied && supplied) {\n results.push({\n function: fn.name,\n property: property.name,\n outcome: suppliedOutcome(\n supplied.file,\n lemmaErrors[0] ?? failed[0],\n axiomsOf(checked.diagnostics, theorem.axiomsLine ?? 0, theorem.name),\n provesExactly(checked.diagnostics, theorem.typeLine ?? 0, theorem.name),\n [...engineAssumptions, ...modelAssumptions(property, fn.name, module)],\n ),\n });\n continue;\n }\n results.push({\n function: fn.name,\n property: property.name,\n outcome:\n failed.length === 0\n ? {\n ...proven,\n assumptions: [...engineAssumptions, ...modelAssumptions(property, fn.name, module)],\n }\n : unknown(\n \"gave_up\",\n `Lean could not close the proof: ${(failed[0] as LeanDiagnostic).message.split(\"\\n\")[0]}`,\n ),\n });\n }\n }\n // The open goals: every forall property given up on, with the statement Lean was asked to prove. The\n // list is present, empty or not, only here, where Lean answered; a timeout or an engine gap above\n // returns without it, so no one takes \"no answer\" for \"no open goals\".\n const goals: OpenGoal[] = [];\n for (const fn of inSubset)\n for (const property of fn.properties) {\n if (property.kind !== \"forall\") continue;\n const r = results.find((x) => x.function === fn.name && x.property === property.name);\n if (r?.outcome.kind !== \"UNKNOWN\" || r.outcome.cause !== \"gave_up\") continue;\n goals.push({\n function: fn.name,\n property: property.name,\n statement: stated(property, module).text,\n reason: r.outcome.reason,\n });\n }\n return { results, lean, specErrors, goals };\n}\n\n/** The engine as a `Prover`: available when the pinned toolchain is installed. */\nexport const leanProver: Prover = {\n name: engineName,\n async available() {\n const toolchain = await findLean();\n return \"unavailable\" in toolchain ? toolchain : { version: toolchain.version };\n },\n prove: (input) => proveModule(input),\n};\n\n/** The list and recursion models a proof rests on, where its claim may meet them. */\nfunction modelAssumptions(property: Property, fn: string, module: SubsetModule): string[] {\n // The module functions this claim's own arrows name, by the spec file's names for them: named at\n // all, called or not, so `(sum)(xs)` counts; a disclosure may err only toward saying more.\n const arrows = [property.when?.body ?? \"\", property.ensures?.body ?? \"\"].join(\"\\n\");\n const called = property.imports.filter((i) =>\n new RegExp(`(^|[^\\\\w$])${i.local.replace(/\\$/g, \"\\\\$\")}($|[^\\\\w$])`).test(arrows),\n );\n const roots = [fn, ...called.map((i) => i.fn)];\n return [\n ...(usesLists(property, roots, module) ? [listAssumption] : []),\n ...(reached(roots, module).some((f) => f.structural !== undefined)\n ? [recursionAssumption]\n : []),\n ];\n}\n\n/**\n * The functions a property's claim may unfold: its function, the module\n * functions its arrows call, and, through their calls, everything they\n * reach.\n */\nfunction reached(roots: readonly string[], module: SubsetModule): SubsetFunction[] {\n const byName = new Map(module.functions.map((f) => [f.name, f]));\n const out = new Map<string, SubsetFunction>();\n const visit = (name: string) => {\n const f = byName.get(name);\n if (!f || out.has(name)) return;\n out.set(name, f);\n const walk = (e: Expr): void => {\n if (e.kind === \"call\") visit(e.callee);\n for (const c of children(e)) walk(c);\n };\n walk(f.body);\n };\n for (const r of roots) visit(r);\n return [...out.values()];\n}\n\n/**\n * Whether a list can be in play in a property: a binder whose type holds\n * an array at any depth, or a function the claim may unfold that holds a\n * list in its types (through records too) or builds one.\n */\nfunction usesLists(property: Property, roots: readonly string[], module: SubsetModule): boolean {\n const records = new Map(module.records.map((r) => [r.name, r]));\n const seen = new Set<string>();\n const hasList = (t: SubsetType): boolean => {\n if (t.kind === \"list\") return true;\n if (t.kind === \"nullable\") return hasList(t.inner);\n if (t.kind === \"record\" && !seen.has(t.name)) {\n seen.add(t.name);\n return records.get(t.name)?.fields.some((f) => hasList(f.type)) ?? false;\n }\n return false;\n };\n const hasArray = (t: SpecType): boolean => {\n if (t.kind === \"array\") return true;\n if (t.kind === \"union\") return t.members.some(hasArray);\n if (t.kind === \"record\") return t.fields.some((f) => hasArray(f.type));\n return false;\n };\n const builds = (e: Expr): boolean => listKinds.has(e.kind) || children(e).some(builds);\n // The arrows' own array literals and methods, read from their text: a disclosure may err only toward saying more.\n const arrowLists = [property.when, property.ensures].some(\n (a) => a !== undefined && /\\[|\\.(map|flatMap|every|some|reduce|slice|length)\\b/.test(a.body),\n );\n return (\n property.binders.some((b) => hasArray(b.type)) ||\n arrowLists ||\n reached(roots, module).some(\n (f) => hasList(f.returns) || f.params.some((p) => hasList(p.type)) || builds(f.body),\n )\n );\n}\n"],"mappings":";;;;;;;;;;;;;;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,MAAqB,UAAU,IAAI,EAAE,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC,KAAK,MAAM;CAErF,MAAM,aAAa,CAAC,SAAS,MAAM,SAAS,OAAO,CAAC,CAAC,MAClD,MAAM,MAAM,KAAA,KAAa,sDAAsD,KAAK,EAAE,IAAI,CAC7F;CACA,OACE,SAAS,QAAQ,MAAM,MAAM,SAAS,EAAE,IAAI,CAAC,KAC7C,cACA,QAAQ,OAAO,MAAM,CAAC,CAAC,MACpB,MAAM,QAAQ,EAAE,OAAO,KAAK,EAAE,OAAO,MAAM,MAAM,QAAQ,EAAE,IAAI,CAAC,KAAK,OAAO,EAAE,IAAI,CACrF;AAEJ"}
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
// packages/core/src/canonical-json.ts
|
|
2
|
+
function canonicalJson(value) {
|
|
3
|
+
if (value === null) return "null";
|
|
4
|
+
switch (typeof value) {
|
|
5
|
+
case "boolean": return value ? "true" : "false";
|
|
6
|
+
case "number":
|
|
7
|
+
if (!Number.isFinite(value)) throw new TypeError(`non-finite number: ${value}`);
|
|
8
|
+
return Object.is(value, -0) ? "0" : JSON.stringify(value);
|
|
9
|
+
case "string": return JSON.stringify(value);
|
|
10
|
+
case "object": {
|
|
11
|
+
if (Array.isArray(value)) {
|
|
12
|
+
const items = [];
|
|
13
|
+
for (let i = 0; i < value.length; i++) {
|
|
14
|
+
const v = value[i];
|
|
15
|
+
if (v === void 0) throw new TypeError(`hole or undefined at index ${i}`);
|
|
16
|
+
items.push(canonicalJson(v));
|
|
17
|
+
}
|
|
18
|
+
return `[${items.join(",")}]`;
|
|
19
|
+
}
|
|
20
|
+
const keys = Object.keys(value).sort();
|
|
21
|
+
const parts = [];
|
|
22
|
+
for (const k of keys) {
|
|
23
|
+
const v = value[k];
|
|
24
|
+
if (v === void 0) throw new TypeError(`undefined at key ${JSON.stringify(k)}`);
|
|
25
|
+
parts.push(`${JSON.stringify(k)}:${canonicalJson(v)}`);
|
|
26
|
+
}
|
|
27
|
+
return `{${parts.join(",")}}`;
|
|
28
|
+
}
|
|
29
|
+
default: throw new TypeError(`not JSON data: ${typeof value}`);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
Object.freeze({ entries: Object.freeze([]) });
|
|
33
|
+
/** One canonical JSON object per line, in sequence order. */
|
|
34
|
+
function serializeLog(log) {
|
|
35
|
+
return log.entries.map((e) => canonicalJson({
|
|
36
|
+
seq: e.seq,
|
|
37
|
+
kind: e.kind,
|
|
38
|
+
invocation: e.invocation,
|
|
39
|
+
target: e.target,
|
|
40
|
+
op: e.op,
|
|
41
|
+
payload: e.payload
|
|
42
|
+
})).join("\n");
|
|
43
|
+
}
|
|
44
|
+
// packages/core/src/prng.ts
|
|
45
|
+
function rotl(x, k) {
|
|
46
|
+
return (x << k | x >>> 32 - k) >>> 0;
|
|
47
|
+
}
|
|
48
|
+
/** splitmix32: expands a 32-bit seed into well-mixed words for seeding. */
|
|
49
|
+
function splitmix32(seed) {
|
|
50
|
+
let a = seed >>> 0;
|
|
51
|
+
return () => {
|
|
52
|
+
a = a + 2654435769 >>> 0;
|
|
53
|
+
let t = a;
|
|
54
|
+
t = Math.imul(t ^ t >>> 16, 569420461);
|
|
55
|
+
t = Math.imul(t ^ t >>> 15, 1935289751);
|
|
56
|
+
return (t ^ t >>> 15) >>> 0;
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
/** FNV-1a over UTF-16 code units, so string seeds are stable across runtimes. */
|
|
60
|
+
function hashString(s) {
|
|
61
|
+
let h = 2166136261;
|
|
62
|
+
for (let i = 0; i < s.length; i++) {
|
|
63
|
+
h ^= s.charCodeAt(i);
|
|
64
|
+
h = Math.imul(h, 16777619);
|
|
65
|
+
}
|
|
66
|
+
return h >>> 0;
|
|
67
|
+
}
|
|
68
|
+
/** Derive an initial state from a number (taken modulo 2^32) or a string. */
|
|
69
|
+
function seedPrng(seed) {
|
|
70
|
+
const next = splitmix32(typeof seed === "string" ? hashString(seed) : seed >>> 0);
|
|
71
|
+
const s = [
|
|
72
|
+
next(),
|
|
73
|
+
next(),
|
|
74
|
+
next(),
|
|
75
|
+
next()
|
|
76
|
+
];
|
|
77
|
+
if (s[0] === 0 && s[1] === 0 && s[2] === 0 && s[3] === 0) s[0] = 1;
|
|
78
|
+
return s;
|
|
79
|
+
}
|
|
80
|
+
/** Next 32-bit unsigned integer and the state that follows it. */
|
|
81
|
+
function nextU32(state) {
|
|
82
|
+
const [s0, s1, s2, s3] = state;
|
|
83
|
+
const result = Math.imul(rotl(Math.imul(s1, 5) >>> 0, 7), 9) >>> 0;
|
|
84
|
+
const t = s1 << 9 >>> 0;
|
|
85
|
+
let n2 = (s2 ^ s0) >>> 0;
|
|
86
|
+
let n3 = (s3 ^ s1) >>> 0;
|
|
87
|
+
const n1 = (s1 ^ n2) >>> 0;
|
|
88
|
+
const n0 = (s0 ^ n3) >>> 0;
|
|
89
|
+
n2 = (n2 ^ t) >>> 0;
|
|
90
|
+
n3 = rotl(n3, 11);
|
|
91
|
+
return [result, [
|
|
92
|
+
n0,
|
|
93
|
+
n1,
|
|
94
|
+
n2,
|
|
95
|
+
n3
|
|
96
|
+
]];
|
|
97
|
+
}
|
|
98
|
+
/** Next float in [0, 1) with 24 bits of precision. */
|
|
99
|
+
function nextFloat(state) {
|
|
100
|
+
const [u, next] = nextU32(state);
|
|
101
|
+
return [(u >>> 8) * 2 ** -24, next];
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Next integer in [0, bound). Uses rejection sampling, so every value is
|
|
105
|
+
* equally likely; a bound of 1 always yields 0 without consuming state.
|
|
106
|
+
*/
|
|
107
|
+
function nextInt(state, bound) {
|
|
108
|
+
if (!Number.isInteger(bound) || bound < 1 || bound > 4294967296) throw new RangeError(`nextInt bound must be an integer in [1, 2^32], got ${bound}`);
|
|
109
|
+
if (bound === 1) return [0, state];
|
|
110
|
+
const limit = 4294967296 - 4294967296 % bound;
|
|
111
|
+
let s = state;
|
|
112
|
+
for (;;) {
|
|
113
|
+
const [u, next] = nextU32(s);
|
|
114
|
+
s = next;
|
|
115
|
+
if (u < limit) return [u % bound, s];
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
export { serializeLog as a, seedPrng as i, nextInt as n, canonicalJson as o, nextU32 as r, nextFloat as t };
|
|
119
|
+
|
|
120
|
+
//# sourceMappingURL=src-BtLZPRyG.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"src-BtLZPRyG.mjs","names":[],"sources":["../../core/src/canonical-json.ts","../../core/src/effect-log.ts","../../core/src/prng.ts"],"sourcesContent":["/**\n * Canonical JSON: the one serialisation of a value, so that equal data always\n * produces equal bytes. Object keys are sorted; numbers must be finite; there\n * is no whitespace. Anything that is not plain JSON data is rejected.\n */\n\nexport type JsonValue =\n | null\n | boolean\n | number\n | string\n | readonly JsonValue[]\n | { readonly [key: string]: JsonValue };\n\nexport function canonicalJson(value: JsonValue): string {\n if (value === null) return \"null\";\n switch (typeof value) {\n case \"boolean\":\n return value ? \"true\" : \"false\";\n case \"number\":\n if (!Number.isFinite(value)) throw new TypeError(`non-finite number: ${value}`);\n return Object.is(value, -0) ? \"0\" : JSON.stringify(value);\n case \"string\":\n return JSON.stringify(value);\n case \"object\": {\n if (Array.isArray(value)) {\n const items: string[] = [];\n for (let i = 0; i < value.length; i++) {\n const v = value[i];\n if (v === undefined) throw new TypeError(`hole or undefined at index ${i}`);\n items.push(canonicalJson(v));\n }\n return `[${items.join(\",\")}]`;\n }\n const keys = Object.keys(value).sort();\n const parts: string[] = [];\n for (const k of keys) {\n const v = (value as { readonly [key: string]: JsonValue | undefined })[k];\n if (v === undefined) throw new TypeError(`undefined at key ${JSON.stringify(k)}`);\n parts.push(`${JSON.stringify(k)}:${canonicalJson(v)}`);\n }\n return `{${parts.join(\",\")}}`;\n }\n default:\n throw new TypeError(`not JSON data: ${typeof value}`);\n }\n}\n","/**\n * The effect log: the complete, ordered record of what a simulated run did at\n * its effect boundaries. It is plain data, appended immutably, and has one\n * canonical serialisation, so two runs are identical exactly when their\n * serialised logs are byte-identical.\n */\n\nimport { canonicalJson, type JsonValue } from \"./canonical-json.ts\";\nimport { utf8Encode } from \"./utf8.ts\";\n\n/** `snapshot` records platform state (e.g. D1 tables) captured at the end of a run; it is not an effect point. */\nexport type EffectKind = \"call\" | \"result\" | \"fault\" | \"snapshot\";\n\n/** One entry of the effect log: an effect's call, its result, an injected fault, or an end-of-run snapshot. */\nexport interface EffectRecord {\n /** Position in the log, dense from 0. */\n readonly seq: number;\n readonly kind: EffectKind;\n /** The invocation (request, message, alarm) this effect belongs to. */\n readonly invocation: string;\n /** The binding or global the effect went through, e.g. \"D1:DB\". */\n readonly target: string;\n /** The operation, e.g. \"run\", \"batch\", \"send\". */\n readonly op: string;\n /** Operation-specific data: arguments, results, or the injected fault. */\n readonly payload: JsonValue;\n}\n\n/** The ordered record of what a run did at its effect boundaries, which invariants are checked against. */\nexport interface EffectLog {\n readonly entries: readonly EffectRecord[];\n}\n\nexport const emptyLog: EffectLog = Object.freeze({ entries: Object.freeze([]) });\n\n/** Append one effect, assigning its sequence number. The input log is unchanged. */\nexport function appendEffect(log: EffectLog, effect: Omit<EffectRecord, \"seq\">): EffectLog {\n const record: EffectRecord = { ...effect, seq: log.entries.length };\n return { entries: [...log.entries, record] };\n}\n\n/** One canonical JSON object per line, in sequence order. */\nexport function serializeLog(log: EffectLog): string {\n return log.entries\n .map((e) =>\n canonicalJson({\n seq: e.seq,\n kind: e.kind,\n invocation: e.invocation,\n target: e.target,\n op: e.op,\n payload: e.payload,\n }),\n )\n .join(\"\\n\");\n}\n\n/** A 64-bit FNV-1a digest of the serialised log, as 16 hex digits. Not cryptographic. */\nexport function digestLog(log: EffectLog): string {\n const bytes = utf8Encode(serializeLog(log));\n let h = 0xcbf29ce484222325n;\n for (const b of bytes) {\n h ^= BigInt(b);\n h = (h * 0x100000001b3n) & 0xffffffffffffffffn;\n }\n return h.toString(16).padStart(16, \"0\");\n}\n","/**\n * A pure, seedable pseudo-random generator (xoshiro128**).\n *\n * State is an immutable tuple of four 32-bit words. Every operation returns a\n * value and the next state; nothing is mutated, so a schedule can be replayed\n * from any state and two explorations can never interfere with each other.\n * Not cryptographic.\n */\n\nexport type PrngState = readonly [number, number, number, number];\n\nfunction rotl(x: number, k: number): number {\n return ((x << k) | (x >>> (32 - k))) >>> 0;\n}\n\n/** splitmix32: expands a 32-bit seed into well-mixed words for seeding. */\nfunction splitmix32(seed: number): () => number {\n let a = seed >>> 0;\n return () => {\n a = (a + 0x9e3779b9) >>> 0;\n let t = a;\n t = Math.imul(t ^ (t >>> 16), 0x21f0aaad);\n t = Math.imul(t ^ (t >>> 15), 0x735a2d97);\n return (t ^ (t >>> 15)) >>> 0;\n };\n}\n\n/** FNV-1a over UTF-16 code units, so string seeds are stable across runtimes. */\nfunction hashString(s: string): number {\n let h = 0x811c9dc5;\n for (let i = 0; i < s.length; i++) {\n h ^= s.charCodeAt(i);\n h = Math.imul(h, 0x01000193);\n }\n return h >>> 0;\n}\n\n/** Derive an initial state from a number (taken modulo 2^32) or a string. */\nexport function seedPrng(seed: number | string): PrngState {\n const word = typeof seed === \"string\" ? hashString(seed) : seed >>> 0;\n const next = splitmix32(word);\n const s: [number, number, number, number] = [next(), next(), next(), next()];\n if (s[0] === 0 && s[1] === 0 && s[2] === 0 && s[3] === 0) {\n s[0] = 1; // xoshiro must never hold the all-zero state\n }\n return s;\n}\n\n/** Next 32-bit unsigned integer and the state that follows it. */\nexport function nextU32(state: PrngState): readonly [number, PrngState] {\n const [s0, s1, s2, s3] = state;\n const result = Math.imul(rotl(Math.imul(s1, 5) >>> 0, 7), 9) >>> 0;\n const t = (s1 << 9) >>> 0;\n let n2 = (s2 ^ s0) >>> 0;\n let n3 = (s3 ^ s1) >>> 0;\n const n1 = (s1 ^ n2) >>> 0;\n const n0 = (s0 ^ n3) >>> 0;\n n2 = (n2 ^ t) >>> 0;\n n3 = rotl(n3, 11);\n return [result, [n0, n1, n2, n3]];\n}\n\n/** Next float in [0, 1) with 24 bits of precision. */\nexport function nextFloat(state: PrngState): readonly [number, PrngState] {\n const [u, next] = nextU32(state);\n return [(u >>> 8) * 2 ** -24, next];\n}\n\n/**\n * Next integer in [0, bound). Uses rejection sampling, so every value is\n * equally likely; a bound of 1 always yields 0 without consuming state.\n */\nexport function nextInt(state: PrngState, bound: number): readonly [number, PrngState] {\n if (!Number.isInteger(bound) || bound < 1 || bound > 0x1_0000_0000) {\n throw new RangeError(`nextInt bound must be an integer in [1, 2^32], got ${bound}`);\n }\n if (bound === 1) return [0, state];\n const limit = 0x1_0000_0000 - (0x1_0000_0000 % bound);\n let s = state;\n for (;;) {\n const [u, next] = nextU32(s);\n s = next;\n if (u < limit) return [u % bound, s];\n }\n}\n"],"mappings":";AAcA,SAAgB,cAAc,OAA0B;CACtD,IAAI,UAAU,MAAM,OAAO;CAC3B,QAAQ,OAAO,OAAf;EACE,KAAK,WACH,OAAO,QAAQ,SAAS;EAC1B,KAAK;GACH,IAAI,CAAC,OAAO,SAAS,KAAK,GAAG,MAAM,IAAI,UAAU,sBAAsB,OAAO;GAC9E,OAAO,OAAO,GAAG,OAAO,EAAE,IAAI,MAAM,KAAK,UAAU,KAAK;EAC1D,KAAK,UACH,OAAO,KAAK,UAAU,KAAK;EAC7B,KAAK,UAAU;GACb,IAAI,MAAM,QAAQ,KAAK,GAAG;IACxB,MAAM,QAAkB,CAAC;IACzB,KAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;KACrC,MAAM,IAAI,MAAM;KAChB,IAAI,MAAM,KAAA,GAAW,MAAM,IAAI,UAAU,8BAA8B,GAAG;KAC1E,MAAM,KAAK,cAAc,CAAC,CAAC;IAC7B;IACA,OAAO,IAAI,MAAM,KAAK,GAAG,EAAE;GAC7B;GACA,MAAM,OAAO,OAAO,KAAK,KAAK,CAAC,CAAC,KAAK;GACrC,MAAM,QAAkB,CAAC;GACzB,KAAK,MAAM,KAAK,MAAM;IACpB,MA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