diff --git a/CHANGELOG.md b/CHANGELOG.md index 03bd6442d7..2298d2afe9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,13 @@ and Unreleased holds what has landed since. - The `lexlean` crate that goes to crates.io is the crate the release attaches (`RP-18`, #260). `.github/workflows/crate.yml`, which `release.yml` calls on every run, packages the crate twice to the same bytes, runs `cargo publish --dry-run`, checks the archive for what crates.io needs (description, license, repository, the readme it names, at most 10 MiB), and compares its SHA-256 with `release/lexlean.crate` and the line `checksums.txt` lists for it; the tag's `publish` job repeats the comparison against the dry-run package and uploads to crates.io only when a `CARGO_REGISTRY_TOKEN` secret or trusted publishing (the repository variable `CRATES_IO_TRUSTED_PUBLISHING`) authorises it, and otherwise creates the release and says the crate was not uploaded, where before the first run failed after the tag was pushed because no `lexlean` crate and no trusted publisher existed. Dispatched on a `release/vX.Y` line, `crate.yml` does the same for the pre-release `X.Y.0-dev.N`, `N` being the commit's number of first-parent commits, and uploads it under the same authority. The decisions are in `.github/crate-publication.sh`, which the case runs against planted archives, checksums, refs and environments. SPEC.md §30.3 states the rule. Register 449. +- `term_cases` decides constructor disjointness and injectivity (#280, SPEC.md + §17.10, `SM-35`). Its fixed `simp only` set adds `reduceCtorEq`, `false_implies`, + `imp_self`, `and_true`, `true_and`, the injectivity lemmas of `Option`, `Result` + (`Except`), and `List`, and the injectivity lemma of every constructor with a + field of the module's inductive types, so "if the check returns `bad p`, the + report names `p`" is proved and a false case is still rejected. No + compiler-semantics identity moves. - The Rust runtime as source, #91 stage 4 (SPEC.md §17.16, §17.17, `SP-21`, `RB-15`, `SP-23`, `SM-35`, `SM-36`, `RB-16`, `SP-22`, `RB-17`, `SP-25`, `RB-19`, `BS-09`, `SP-26`). The declared Rust machine grows by the primitives the runtime is written in diff --git a/CONFORMANCE.md b/CONFORMANCE.md index a2fe8e9cb1..c48a9f4cd6 100644 --- a/CONFORMANCE.md +++ b/CONFORMANCE.md @@ -578,7 +578,7 @@ the error registry does not sanction (R5, `ERRORS.md`). | `SM-32` | `build` | Language 1.2 widening conversions, to_int from every fixed-width integer type to Int and to_nat from every unsigned fixed-width type to Nat, are total, are rejected under language 1.1, and elaborate in linking to ordinary terms over bit_and, equal, conditionals, and exact integer and natural sums, so that a production root decodes a byte string to integers with no decimal text in its lowered program and is certified like any other root. | | `SM-33` | `build` | A version 2 core-module row that states its type and value and whose name the pinned Lean reserves is not submitted as data: the decoder runs the pinned Lean's own action for the name and refuses the module when the action does not make the name or makes a constant whose kind, levels, type, or value differ from the row's. | | `SM-34` | `build` | A version 2 core-module row may be derived, stating its name, kind, and extension state, and for a sparse casesOn its recipe, and no universe parameters, type, or value: the decoder makes the constant with the pinned Lean's own construction at the row's place in the order, and refuses the module when the name is not one the pinned Lean reserves and the row states no sparse casesOn recipe, when the construction does not make the name, or when the constant it makes is not a theorem, definition, or abbreviation as the row says; the notation writes a derived row without a type, the schema and the linker refuse a derived row that states what the construction decides, a stored row is still checked against the construction, the decoder checks that the constructors a recipe names are constructors of the type and are named once, that the module states every sparse casesOn its construction makes, and that every derived sparse casesOn is referred to by the type or value of a row, and the content of a derived row is checked by its uses alone, so that a recipe naming other valid constructors of the type is not distinguished where the use accepts it; and the shipped preservation library states every row that carries a sparse casesOn record or is named like an equation, an unfolding equation, a splitter, or an else equation as a derived row. | -| `SM-35` | `build` | A language-1.2 theorem may be proved by `term_cases`, a split on the value of a document term: the proof names a term and a nonempty, strictly sorted, duplicate-free list of prior document definitions, the term's type is an inductive type of the document, and the backend lowers the proof to a split of the goal on every constructor of that type with the hypothesis that equates the term to the constructor, then `simp only` over the named definitions, that hypothesis, and the reduction of a conditional on a decided condition, with closed propositions decided, which uses exactly the axioms the theorem's policy states; the schema, the linker, the notation, the Lean backend, the canonical LaTeX, and the formatter accept it, and a use in language 1.1, a term whose type is not an inductive type of the document, an empty list, an unsorted or repeated name, a name that is not a prior definition, and a theorem parameter that takes the hypothesis's name are each refused. | +| `SM-35` | `build` | A language-1.2 theorem may be proved by `term_cases`, a split on the value of a document term: the proof names a term and a nonempty, strictly sorted, duplicate-free list of prior document definitions, the term's type is an inductive type of the document, and the backend lowers the proof to a split of the goal on every constructor of that type with the hypothesis that equates the term to the constructor, then `simp only` over the named definitions, that hypothesis, the reduction of a conditional on a decided condition, the refutation of an equation between two different constructors, the injectivity equation of every constructor with a field of `Option`, `Result`, `List`, and each inductive type the module declares, and the fixed rules that close an implication from `False` or of a proposition by itself and drop `True` from a conjunction, with closed propositions decided, which uses exactly the axioms the theorem's policy states, so a theorem whose cases need constructor disjointness or injectivity verifies and a false one is rejected by Lean; the schema, the linker, the notation, the Lean backend, the canonical LaTeX, and the formatter accept it, and a use in language 1.1, a term whose type is not an inductive type of the document, an empty list, an unsorted or repeated name, a name that is not a prior definition, and a theorem parameter that takes the hypothesis's name are each refused. | | `SM-36` | `build` | A language-1.2 `cases` proof may split a local of type `Bool` into its two constructors: the proof names the local and gives a branch for `false` and one for `true`, each with no binders, the backend lowers it to `cases` on the local with those two alternatives, the theorem verifies with exactly the axioms its policy states, and the schema, the linker, the notation, the formatter, and the canonical LaTeX accept it; a use in language 1.1, a missing branch, a repeated branch, a branch with a binder, and an `induction` on a Boolean are each refused. | ## stdlib diff --git a/SPEC.md b/SPEC.md index fd96888239..3d15be617a 100644 --- a/SPEC.md +++ b/SPEC.md @@ -2678,11 +2678,30 @@ cannot carry a proof-term or tactic string. A `term_cases` proof (language 1.2, `SM-35`) names a document term and a nonempty, strictly sorted, duplicate-free list of prior document definitions. The term's type must be an inductive type of the document. It lowers to -`set_option linter.unusedSimpArgs false in cases llCase : <;> simp (config := {decide := true}) only [, llCase, ite_true, ite_false]`: +`set_option linter.unusedSimpArgs false in cases llCase : <;> simp (config := {decide := true}) only [, llCase, ite_true, ite_false, reduceCtorEq, false_implies, imp_self, and_true, true_and, Option.some.injEq, Except.error.injEq, Except.ok.injEq, List.cons.injEq, ]`, +where `` is `..injEq` for every constructor `c` with at least +one field of every inductive type `T` the module declares, in declaration order: the goal is split on every constructor of the term's type, `llCase` is the hypothesis that equates the term to the constructor, and the definitions, that -hypothesis, and the reduction of a conditional on a decided condition are the -only rewrite rules, with closed propositions decided; the unused-argument linter is off for the one script, because the list of definitions is a superset the unfolding draws on and an unused name is not an error. It is +hypothesis, the reduction of a conditional on a decided condition, and the fixed +constructor rules are the only rewrite rules, with closed propositions decided. +Deciding closed propositions does not decide an equation between constructors +over variables, such as `Verdict.good = Verdict.bad p` or +`Verdict.bad x = Verdict.bad p`; the constructor rules do. `reduceCtorEq`, the +pinned Lean's no-confusion simplification procedure, rewrites an equation between +two different constructors to `False`; each `injEq` lemma, which Lean generates for +every constructor with a field, rewrites an equation between two applications of +that constructor to the equations of their fields; `false_implies`, `imp_self`, +`and_true`, and `true_and` close the implication and the conjunction those +equations leave. The +constructors of `Option`, of `Result` (Lean's `Except`), and of `List` are named +because a statement about a document term commonly returns one of them. So a +theorem such as "if the check returns `bad p`, the report names `p`" is proved, and +a case that is false is still left open and the theorem rejected. The rule set is +fixed by the module's declarations, and every rule is named in the script; none is +drawn from `simp`'s default set. The unused-argument linter is off for the one +script, because the list is a superset the unfolding draws on and an unused name is +not an error. It is admitted because an evaluation that matches on the same term twice, once through a wrapper that matches on the result of the first, is a case-of-case that conversion does not commute, so such an equation cannot be proved by @@ -10473,7 +10492,7 @@ Every row below is normative, has honesty level `build`, and MUST be copied byte | `SM-32` | `semantic-ir` | Language 1.2 widening conversions, to_int from every fixed-width integer type to Int and to_nat from every unsigned fixed-width type to Nat, are total, are rejected under language 1.1, and elaborate in linking to ordinary terms over bit_and, equal, conditionals, and exact integer and natural sums, so that a production root decodes a byte string to integers with no decimal text in its lowered program and is certified like any other root. | §17.12 | | `SM-33` | `semantic-ir` | A version 2 core-module row that states its type and value and whose name the pinned Lean reserves is not submitted as data: the decoder runs the pinned Lean's own action for the name and refuses the module when the action does not make the name or makes a constant whose kind, levels, type, or value differ from the row's. | §17.10 | | `SM-34` | `semantic-ir` | A version 2 core-module row may be derived, stating its name, kind, and extension state, and for a sparse casesOn its recipe, and no universe parameters, type, or value: the decoder makes the constant with the pinned Lean's own construction at the row's place in the order, and refuses the module when the name is not one the pinned Lean reserves and the row states no sparse casesOn recipe, when the construction does not make the name, or when the constant it makes is not a theorem, definition, or abbreviation as the row says; the notation writes a derived row without a type, the schema and the linker refuse a derived row that states what the construction decides, a stored row is still checked against the construction, the decoder checks that the constructors a recipe names are constructors of the type and are named once, that the module states every sparse casesOn its construction makes, and that every derived sparse casesOn is referred to by the type or value of a row, and the content of a derived row is checked by its uses alone, so that a recipe naming other valid constructors of the type is not distinguished where the use accepts it; and the shipped preservation library states every row that carries a sparse casesOn record or is named like an equation, an unfolding equation, a splitter, or an else equation as a derived row. | §17.10 | -| `SM-35` | `semantic-ir` | A language-1.2 theorem may be proved by `term_cases`, a split on the value of a document term: the proof names a term and a nonempty, strictly sorted, duplicate-free list of prior document definitions, the term's type is an inductive type of the document, and the backend lowers the proof to a split of the goal on every constructor of that type with the hypothesis that equates the term to the constructor, then `simp only` over the named definitions, that hypothesis, and the reduction of a conditional on a decided condition, with closed propositions decided, which uses exactly the axioms the theorem's policy states; the schema, the linker, the notation, the Lean backend, the canonical LaTeX, and the formatter accept it, and a use in language 1.1, a term whose type is not an inductive type of the document, an empty list, an unsorted or repeated name, a name that is not a prior definition, and a theorem parameter that takes the hypothesis's name are each refused. | §17.10 | +| `SM-35` | `semantic-ir` | A language-1.2 theorem may be proved by `term_cases`, a split on the value of a document term: the proof names a term and a nonempty, strictly sorted, duplicate-free list of prior document definitions, the term's type is an inductive type of the document, and the backend lowers the proof to a split of the goal on every constructor of that type with the hypothesis that equates the term to the constructor, then `simp only` over the named definitions, that hypothesis, the reduction of a conditional on a decided condition, the refutation of an equation between two different constructors, the injectivity equation of every constructor with a field of `Option`, `Result`, `List`, and each inductive type the module declares, and the fixed rules that close an implication from `False` or of a proposition by itself and drop `True` from a conjunction, with closed propositions decided, which uses exactly the axioms the theorem's policy states, so a theorem whose cases need constructor disjointness or injectivity verifies and a false one is rejected by Lean; the schema, the linker, the notation, the Lean backend, the canonical LaTeX, and the formatter accept it, and a use in language 1.1, a term whose type is not an inductive type of the document, an empty list, an unsorted or repeated name, a name that is not a prior definition, and a theorem parameter that takes the hypothesis's name are each refused. | §17.10 | | `SM-36` | `semantic-ir` | A language-1.2 `cases` proof may split a local of type `Bool` into its two constructors: the proof names the local and gives a branch for `false` and one for `true`, each with no binders, the backend lowers it to `cases` on the local with those two alternatives, the theorem verifies with exactly the axioms its policy states, and the schema, the linker, the notation, the formatter, and the canonical LaTeX accept it; a use in language 1.1, a missing branch, a repeated branch, a branch with a binder, and an `induction` on a Boolean are each refused. | §17.10 | | `DF-01` | `declarations` | A valid type-definition sentence emits one nonrecursive sort-valued Lean def linked to its document entry. | §15.7, §18.6 | | `DF-02` | `declarations` | A valid term-definition sentence emits one nonrecursive explicitly typed Lean def. | §15.7, §18.6 | diff --git a/VERIFICATION.md b/VERIFICATION.md index 805e5b6f4d..699a648bae 100644 --- a/VERIFICATION.md +++ b/VERIFICATION.md @@ -1830,6 +1830,81 @@ Not planted: the check that the term's type is an inductive of the document, the the absent definition, and the reserved name, each of which the case exercises with its own misuse; their checks were not removed one by one. +### a split on a document term decides constructor equations, and can fail (SM-35, #280) + +The first lowering of `term_cases` decided closed propositions only, so a case that equates +two different constructors over a variable (`Verdict.good = Verdict.bad p`, `none = some p`) +or one constructor over different fields (`Verdict.bad x = Verdict.bad p`) was left open, +and "if the check returns `bad p`, the report names `p`" could not be proved (#280, +UOR-Foundation/MCP#20). The lowering now names, after the definitions, `llCase`, `ite_true`, +and `ite_false`, the fixed constructor rules `reduceCtorEq`, `false_implies`, `imp_self`, +`and_true`, `true_and`, `Option.some.injEq`, `Except.error.injEq`, `Except.ok.injEq`, +`List.cons.injEq`, and then `..injEq` for every constructor with a field of every +inductive type the module declares, in declaration order (§17.10). Every rule is named in +the script; none comes from `simp`'s default set. + +Reproduced first on `release/v0.4` f057b8308 with the issue's module through `lexlean verify` +(Lean 4.32.1): `LLV7002`, unsolved goals `case good … ⊢ Verdict.good = Verdict.bad p → none = +some p` and `case bad … ⊢ Verdict.bad x✝ = Verdict.bad p → some x✝ = some p`, the goals the +issue reports. With the new lowering the same command prints `verified 1 module`. + +`conformance_sm_35` builds four more language-1.2 projects from the issue's module and +checks that the generated Lean names the rules: the issue's module itself (disjointness and +injectivity of `Verdict` and `Option`), the converse statement `report n = none → check n = +Verdict.good` (an `Option` disjointness in the hypothesis), a statement over a constructor +of two fields, `check n = Verdict.bad p → paired n = Pair.mk 0 p` (injectivity, and +`true_and` for the equal field), and the false statement `check n = Verdict.bad p → report n += none`. Where the pinned Lean is installed the first three verify with exactly `[propext]` +and the fourth is rejected with `LLV7002` and unsolved goals (`case bad … ⊢ x✝ = p → +False`). The first cut of the rules lacked `false_implies`: the two-field project then +failed with `⊢ False → 0 = p` (its hypothesis refuted, its conclusion not), so the rule and +the SM-35 text name it. + +Each plant was one edit, run with `cargo test -p repo-conformance --test conformance -- +conformance_sm_35` and with `lexlean verify` on the four projects, and restored with `git +checkout`. Every lowering plant fails the case at its assertion on the generated rule list; +the Lean outputs below are the four projects through the CLI with the planted compiler. + +Planted (a): the old lowering (no constructor rule). The case fails. The issue's project +leaves both goals open, as above; the `Option` project `case bad … ⊢ some x✝ = none → +Verdict.bad x✝ = Verdict.good`; the two-field project `case good … ⊢ Verdict.good = +Verdict.bad p → Pair.mk 0 0 = Pair.mk 0 p` and `case bad … ⊢ Verdict.bad x✝ = Verdict.bad p +→ Pair.mk 0 x✝ = Pair.mk 0 p`; the false project stays rejected. + +Planted (b): `reduceCtorEq` removed. The case fails. The issue's project leaves `case good … +⊢ Verdict.good = Verdict.bad p → none = some p`, the `Option` project `⊢ some x✝ = none → +Verdict.bad x✝ = Verdict.good`, the two-field project `⊢ Verdict.good = Verdict.bad p → 0 = +p`. + +Planted (c): every `injEq` lemma removed (the four fixed ones and the module's). The case +fails. The issue's project leaves `case bad … ⊢ Verdict.bad x✝ = Verdict.bad p → some x✝ = +some p`, the two-field project `⊢ Verdict.bad x✝ = Verdict.bad p → Pair.mk 0 x✝ = Pair.mk 0 +p`; the `Option` project, which needs only disjointness, still verifies. + +Planted (d): `false_implies` removed. The case fails; the two-field project leaves `case good +… ⊢ False → 0 = p`; the issue's and the `Option` projects verify. + +Planted (e): the false statement of the case replaced by the issue's true one. The case fails +at its expectation that verification fails (`verify fails`): the negative assertion is live. + +Not planted, and not exercised: `Except.error.injEq`, `Except.ok.injEq`, and +`List.cons.injEq`. No project of the case equates two `Result` or two `List` constructors, so +removing one of those three lemmas alone leaves the case green; they are named because a +statement about a document term commonly returns one of those types (§17.10), and Lean +generates each of them. + +The other committed uses of `term_cases` (the eleven `RuntimeKeys*` modules of `compiler/`, +`RuntimeSupport`, and `RustRuntime`, also under `language/rust-runtime-1.2/`) were checked with +the new lowering: `cargo xtask verify-examples` reports, for `compiler`, `stdlib`, +`std-models`, `std-reasoning`, `bootstrap`, and every example except `uor-atlas`, that the +normalized verification records equal `expected/verify`; `conformance_sp_25`, +`conformance_rb_16`, `conformance_rb_17`, and `conformance_sm_36` pass. The +compiler-semantics IDs are digests of `language/` and `schemas/`, which this change does not +touch, so no identity moves and no lock or expected record is regenerated. Not verified +locally: `uor-atlas` (CI shards it), and `conformance_sp_22`, which the kernel's OOM killer +stopped inside a 10 GB memory scope with this lowering and, in the same scope, on the +unchanged `release/v0.4` head f057b8308; CI is the evidence for both. + ### the machine's natural and integer arithmetic can fail (SP-23) `RustSyntax.Machine` gains nine constructors (`checkedNatAdd`, `natSub`, `checkedNatMul`, diff --git a/crates/conformance/src/cases/semantic_ir.rs b/crates/conformance/src/cases/semantic_ir.rs index 230cc994f5..1d5e079b62 100644 --- a/crates/conformance/src/cases/semantic_ir.rs +++ b/crates/conformance/src/cases/semantic_ir.rs @@ -2649,28 +2649,115 @@ pub(crate) fn run(id: &str) { serde_json::to_value(&checked.modules["Main"].document.semantic).expect("JSON"), "the formatted source is the same module" ); - let built = accepted.build_ok(); - let build_dir = accepted.build_dir(&built.build_id.expect("a build id")); - let lean = std::fs::read_dir(build_dir.join("modules").as_std_path()) - .expect("the modules") - .flatten() - .flat_map(|entry| { - std::fs::read_dir(entry.path()) - .into_iter() - .flatten() - .flatten() - }) - .filter(|entry| entry.path().extension().is_some_and(|ext| ext == "lean")) - .map(|entry| std::fs::read_to_string(entry.path()).expect("Lean text")) - .collect::(); + let generated_lean = |project: &P| -> String { + let built = project.build_ok(); + let build_dir = project.build_dir(&built.build_id.expect("a build id")); + std::fs::read_dir(build_dir.join("modules").as_std_path()) + .expect("the modules") + .flatten() + .flat_map(|entry| { + std::fs::read_dir(entry.path()) + .into_iter() + .flatten() + .flatten() + }) + .filter(|entry| entry.path().extension().is_some_and(|ext| ext == "lean")) + .map(|entry| std::fs::read_to_string(entry.path()).expect("Lean text")) + .collect::() + }; + // The fixed rules after the named definitions (§17.10): the + // hypothesis, the conditional, and the constructor rules. + let rules = "llCase, ite_true, ite_false, reduceCtorEq, false_implies, imp_self, and_true, true_and, Option.some.injEq, Except.error.injEq, Except.ok.injEq, List.cons.injEq"; + let lean = generated_lean(&accepted); + // `Flag` has no constructor with a field, so the list ends at + // the fixed rules. assert!( lean.contains("cases llCase : flagOf (n) <;>") - && lean.contains( - "simp (config := {decide := true}) only [direct, wrapped, llCase, ite_true, ite_false]" - ), + && lean.contains(&format!( + "simp (config := {{decide := true}}) only [direct, wrapped, {rules}]\n" + )), "{lean}" ); support::verify_ok_backed("SM-35", &accepted); + // #280: the constructor rules decide an equation between + // constructors over variables. The first project is the issue's + // module; the second needs an `Option` disjointness, the third the + // injectivity of a constructor of two fields, and the fourth + // states a false theorem, whose case Lean leaves open. + let issue = "\\begin{lexlean}{Main}\n\\useglossary{lexlean.std.nat@1.2.0}\n\\title{Natural number addition}\n\\begin{semanticmodule}\ninductive{name: Verdict, type_parameters: [], parameters: [], constructors: [{name: good, fields: []}, {name: bad, fields: [Nat]}]}\n\ndefinition{\n name: check,\n parameters: [n : Nat],\n result: Verdict,\n body: (if (n =? 0) then (ctor Verdict.good) else (ctor Verdict.bad n))\n}\n\ndefinition{\n name: report,\n parameters: [n : Nat],\n result: (Option Nat),\n body: (match (check n)\n | Verdict.good => (ctor Option.none [Nat])\n | Verdict.bad at => (ctor Option.some [Nat] at))\n}\n\ntheorem{\n name: report_names_the_bad_value,\n parameters: [n : Nat, p : Nat],\n statement: (((check n) = (ctor Verdict.bad p)) -> ((report n) = (ctor Option.some [Nat] p))),\n proof: term_cases{scrutinee: (check n), definitions: [report]},\n axioms: [propext]\n}\n\\end{semanticmodule}\n\\end{lexlean}\n".to_owned(); + let theorem = + "(((check n) = (ctor Verdict.bad p)) -> ((report n) = (ctor Option.some [Nat] p)))"; + let option = issue.replace( + theorem, + "(((report n) = (ctor Option.none [Nat])) -> ((check n) = (ctor Verdict.good)))", + ); + let pair = issue + .replace( + "\ndefinition{\n name: check,", + "inductive{name: Pair, type_parameters: [], parameters: [], constructors: [{name: mk, fields: [Nat, Nat]}]}\n\ndefinition{\n name: check,", + ) + .replace( + "\ntheorem{", + "definition{\n name: paired,\n parameters: [n : Nat],\n result: Pair,\n body: (match (check n)\n | Verdict.good => (ctor Pair.mk 0 0)\n | Verdict.bad at => (ctor Pair.mk 0 at))\n}\n\ntheorem{", + ) + .replace( + theorem, + "(((check n) = (ctor Verdict.bad p)) -> ((paired n) = (ctor Pair.mk 0 p)))", + ) + .replace("definitions: [report]", "definitions: [paired]"); + let false_theorem = issue.replace( + theorem, + "(((check n) = (ctor Verdict.bad p)) -> ((report n) = (ctor Option.none [Nat])))", + ); + assert!( + option != issue && pair != issue && false_theorem != issue, + "each variant edits the issue's module" + ); + for (what, text, lowering) in [ + ( + "the issue's module (disjointness and injectivity of `Verdict` and `Option`)", + &issue, + format!("[report, {rules}, Verdict.bad.injEq]"), + ), + ( + "an `Option` disjointness in the hypothesis", + &option, + format!("[report, {rules}, Verdict.bad.injEq]"), + ), + ( + "the injectivity of a constructor of two fields", + &pair, + format!("[paired, {rules}, Verdict.bad.injEq, Pair.mk.injEq]"), + ), + ( + "a false theorem", + &false_theorem, + format!("[report, {rules}, Verdict.bad.injEq]"), + ), + ] { + let project = project_of(text, "1.2"); + let lean = generated_lean(&project); + assert!( + lean.contains(&format!( + "simp (config := {{decide := true}}) only {lowering}\n" + )), + "{what}: the generated Lean names the fixed rules: {lean}" + ); + if !support::lean_backed("SM-35") { + continue; + } + if *text == false_theorem { + let error = project.verify_fails_with("LLV7002"); + let shown = format!("{error:?}"); + assert!( + shown.contains("unsolved goals"), + "{what}: Lean leaves the false case open: {shown}" + ); + } else { + eprintln!("SM-35: verifying {what}"); + support::verify_ok(&project); + } + } let tex = support::tex_body(&support::tex_text(&support::rendered(&accepted), "Main")) .to_owned(); // The canonical LaTeX of a semantic module is a catalog of its diff --git a/crates/lexlean/src/backend/semantic.rs b/crates/lexlean/src/backend/semantic.rs index b0d2fea8ad..46bb491261 100644 --- a/crates/lexlean/src/backend/semantic.rs +++ b/crates/lexlean/src/backend/semantic.rs @@ -35,6 +35,10 @@ struct Render<'a> { /// qualified: a cross-check named `E.thm` would otherwise resolve the /// theorem `thm` it restates to itself (§17.12, models). qualify: Option<&'a str>, + /// Each constructor with a field of an inductive type the module + /// declares, as `T.c` in declaration order: `term_cases` names its + /// injectivity lemma (§17.10, `SM-35`). + injective: &'a [String], } /// The generated name of well-founded hypothesis `index`. Semantic names @@ -747,6 +751,7 @@ impl Render<'_> { hypotheses: std::collections::BTreeMap::new(), document: false, qualify: Some(module), + injective: self.injective, }; let this = &qualified; let name = identifier(&check.name); @@ -1281,11 +1286,18 @@ impl Render<'_> { scrutinee, definitions, } => format!( - "{pad}set_option linter.unusedSimpArgs false in\n{pad}cases llCase : {} <;>\n{pad} simp (config := {{decide := true}}) only [{}, llCase, ite_true, ite_false]\n", + "{pad}set_option linter.unusedSimpArgs false in\n{pad}cases llCase : {} <;>\n{pad} simp (config := {{decide := true}}) only [{}]\n", self.term(scrutinee), definitions .iter() .map(|member| self.member(member)) + .chain(TERM_CASES_RULES.iter().map(|rule| (*rule).to_owned())) + .chain(self.injective.iter().map(|constructor| { + self.member(&MemberRef { + module: None, + name: format!("{constructor}.injEq"), + }) + })) .collect::>() .join(", ") ), @@ -1388,6 +1400,27 @@ impl Render<'_> { } } +/// The fixed rules `term_cases` names after the definitions (§17.10, +/// `SM-35`): the case hypothesis, the conditional on a decided condition, +/// the pinned Lean's no-confusion procedure for two different constructors, +/// the units an injectivity equation leaves, and the injectivity lemmas of +/// the constructors with a field of `Option`, `Result` (`Except`), and +/// `List`. The injectivity lemmas of the module's own constructors follow. +const TERM_CASES_RULES: &[&str] = &[ + "llCase", + "ite_true", + "ite_false", + "reduceCtorEq", + "false_implies", + "imp_self", + "and_true", + "true_and", + "Option.some.injEq", + "Except.error.injEq", + "Except.ok.injEq", + "List.cons.injEq", +]; + /// The fixed Boolean comparisons `linear_arithmetic` reflects into /// propositions, and the runtime definitions it unfolds (§17.12). const LINEAR_BRIDGES: &[&str] = &[ @@ -1513,6 +1546,7 @@ fn well_founded_definition( .collect(), document: false, qualify: base.qualify, + injective: base.injective, }; // A parameter the measure alone mentions is used: `termination_by` // references it. @@ -1907,12 +1941,31 @@ pub fn render_lean( }); let runtime = elaborated.contains("\"kind\":\"primitive\"") || reasoning; let document = &checked.document; + // §17.10 (`SM-35`): the constructors whose injectivity lemma + // `term_cases` names, those with a field of the module's own inductives. + let injective: Vec = module + .declarations + .iter() + .filter_map(|declaration| match declaration { + SemanticDeclaration::Inductive { + name, constructors, .. + } => Some( + constructors + .iter() + .filter(|constructor| !constructor.fields.is_empty()) + .map(move |constructor| format!("{name}.{}", constructor.name)), + ), + _ => None, + }) + .flatten() + .collect(); let base_render = Render { prefix: module_prefix, lean_imports: &document.import_lean, hypotheses: std::collections::BTreeMap::new(), document: false, qualify: None, + injective: &injective, }; // A declaration a model elaborates to is named `R.x`, and Lean resolves // a name inside it against the namespace `R` first, so every local @@ -1923,6 +1976,7 @@ pub fn render_lean( hypotheses: std::collections::BTreeMap::new(), document: false, qualify: Some(&document.lean_module), + injective: &injective, }; // §17.12: the runtime a module uses. A language-1.2 module imports the // runtime modules, native modules of the embedded runtime project; a @@ -3079,6 +3133,7 @@ pub fn render_latex( hypotheses: std::collections::BTreeMap::new(), document: true, qualify: None, + injective: &[], }; let version_2 = module.spec == "lexlean/semantic-module/2"; let mut text = String::from( @@ -3317,6 +3372,7 @@ mod byte_literal_tests { hypotheses: std::collections::BTreeMap::new(), document, qualify: None, + injective: &[], } .term(term) } diff --git a/crates/lexlean/src/ir/semantic.rs b/crates/lexlean/src/ir/semantic.rs index 9ef7d22731..6e5a0cc244 100644 --- a/crates/lexlean/src/ir/semantic.rs +++ b/crates/lexlean/src/ir/semantic.rs @@ -714,8 +714,9 @@ pub enum SemanticProof { /// of an inductive type of the document and a nonempty set of prior /// document definitions, and lowers to a split of the goal on every /// constructor of the term's type, with the hypothesis that equates the - /// term to the constructor, then `simp only` over the definitions and that - /// hypothesis with closed propositions decided (§17.10, `SM-35`). + /// term to the constructor, then `simp only` over the definitions, that + /// hypothesis, and the fixed conditional and constructor rules, with + /// closed propositions decided (§17.10, `SM-35`). TermCases { scrutinee: SemanticTerm, definitions: Vec, diff --git a/features/suites/semantic-ir.feature b/features/suites/semantic-ir.feature index c18373d035..d343de165f 100644 --- a/features/suites/semantic-ir.feature +++ b/features/suites/semantic-ir.feature @@ -245,10 +245,12 @@ Feature: semantic-ir And every row of the shipped preservation library that carries a sparse casesOn record or is named like an equation, an unfolding equation, a splitter, or an else equation is a derived row, and no derived row is anything else @SM-35 @build - Scenario: A language-1.2 theorem may be proved by `term_cases`, a split on the value of a document term: the proof names a term and a nonempty, strictly sorted, duplicate-free list of prior document definitions, the term's type is an inductive type of the document, and the backend lowers the proof to a split of the goal on every constructor of that type with the hypothesis that equates the term to the constructor, then `simp only` over the named definitions, that hypothesis, and the reduction of a conditional on a decided condition, with closed propositions decided, which uses exactly the axioms the theorem's policy states; the schema, the linker, the notation, the Lean backend, the canonical LaTeX, and the formatter accept it, and a use in language 1.1, a term whose type is not an inductive type of the document, an empty list, an unsorted or repeated name, a name that is not a prior definition, and a theorem parameter that takes the hypothesis's name are each refused. - Given a language-1.2 project whose theorem is stated as an equation between two evaluations that both match on one document term, and the planted projects that misuse the proof form - When the project is linked, built, and verified by the pinned Lean, its formatted source and its LaTeX are read back, and each planted project is linked + Scenario: A language-1.2 theorem may be proved by `term_cases`, a split on the value of a document term: the proof names a term and a nonempty, strictly sorted, duplicate-free list of prior document definitions, the term's type is an inductive type of the document, and the backend lowers the proof to a split of the goal on every constructor of that type with the hypothesis that equates the term to the constructor, then `simp only` over the named definitions, that hypothesis, the reduction of a conditional on a decided condition, the refutation of an equation between two different constructors, the injectivity equation of every constructor with a field of `Option`, `Result`, `List`, and each inductive type the module declares, and the fixed rules that close an implication from `False` or of a proposition by itself and drop `True` from a conjunction, with closed propositions decided, which uses exactly the axioms the theorem's policy states, so a theorem whose cases need constructor disjointness or injectivity verifies and a false one is rejected by Lean; the schema, the linker, the notation, the Lean backend, the canonical LaTeX, and the formatter accept it, and a use in language 1.1, a term whose type is not an inductive type of the document, an empty list, an unsorted or repeated name, a name that is not a prior definition, and a theorem parameter that takes the hypothesis's name are each refused. + Given a language-1.2 project whose theorem is stated as an equation between two evaluations that both match on one document term, three projects whose theorems need constructor disjointness or injectivity in their cases (over a document inductive, over `Option`, and over a constructor of two fields), one whose theorem is false, and the planted projects that misuse the proof form + When the projects are linked, built, and verified by the pinned Lean, the first project's formatted source and LaTeX are read back, and each planted project is linked Then the theorem verifies with exactly the axioms its policy states, the formatter writes the proof unchanged, and the LaTeX states the term and the definitions + And the generated Lean names the fixed constructor rules and the injectivity lemma of every constructor with a field of the module's inductive types + And the three theorems verify with exactly the axioms their policies state, and the false theorem is rejected by Lean And each planted project is refused naming the misuse @SM-36 @build diff --git a/model/ids.toml b/model/ids.toml index 7cc9829415..ac7ee66e4a 100644 --- a/model/ids.toml +++ b/model/ids.toml @@ -713,7 +713,7 @@ statement = "A version 2 core-module row may be derived, stating its name, kind, id = "SM-35" level = "build" suite = "semantic-ir" -statement = "A language-1.2 theorem may be proved by `term_cases`, a split on the value of a document term: the proof names a term and a nonempty, strictly sorted, duplicate-free list of prior document definitions, the term's type is an inductive type of the document, and the backend lowers the proof to a split of the goal on every constructor of that type with the hypothesis that equates the term to the constructor, then `simp only` over the named definitions, that hypothesis, and the reduction of a conditional on a decided condition, with closed propositions decided, which uses exactly the axioms the theorem's policy states; the schema, the linker, the notation, the Lean backend, the canonical LaTeX, and the formatter accept it, and a use in language 1.1, a term whose type is not an inductive type of the document, an empty list, an unsorted or repeated name, a name that is not a prior definition, and a theorem parameter that takes the hypothesis's name are each refused." +statement = "A language-1.2 theorem may be proved by `term_cases`, a split on the value of a document term: the proof names a term and a nonempty, strictly sorted, duplicate-free list of prior document definitions, the term's type is an inductive type of the document, and the backend lowers the proof to a split of the goal on every constructor of that type with the hypothesis that equates the term to the constructor, then `simp only` over the named definitions, that hypothesis, the reduction of a conditional on a decided condition, the refutation of an equation between two different constructors, the injectivity equation of every constructor with a field of `Option`, `Result`, `List`, and each inductive type the module declares, and the fixed rules that close an implication from `False` or of a proposition by itself and drop `True` from a conjunction, with closed propositions decided, which uses exactly the axioms the theorem's policy states, so a theorem whose cases need constructor disjointness or injectivity verifies and a false one is rejected by Lean; the schema, the linker, the notation, the Lean backend, the canonical LaTeX, and the formatter accept it, and a use in language 1.1, a term whose type is not an inductive type of the document, an empty list, an unsorted or repeated name, a name that is not a prior definition, and a theorem parameter that takes the hypothesis's name are each refused." [[id]] id = "SM-36"