Skip to content
typhdotcomPublic
forked from digama0/lean4lean

About

LLM-maintained research fork of lean4lean

Resources

Stars

0 stars

Watchers

0 watching

Forks

 
 

Repository files navigation

Lean-for-Lean: experimental fork

LLM-maintained and unaudited. This fork's changes and documentation are maintained with LLM agents and have not received an independent human audit. The main verification theorem is conditional on two open metatheoretic assumptions, described below.

This is a research fork of digama0/lean4lean, an implementation of the Lean 4 kernel in mostly pure Lean 4, with a formal specification and proofs connecting the implementation to it. The implementation derives from Lean's C++ kernel and can share its bugs. This fork extends the inductive-type specification and verification, changes some kernel checks, and develops the remaining metatheory. It grew out of other work and is not coordinated with upstream.

Upstream's addDecl.WF leaves inductive declarations as sorry, and its Injectivity.lean states sort_inv, sort_forallE_inv and forallE_inv_stratified with sorry proofs. Here the inductive case is proved for flat and nested blocks, and a shape model proves the first two. The third, with injectivity of inductive type formers, which inductives add, is the class VEnv.Injective, which the labelled model proves (VEnv.injective).

Verification status and trust assumptions

Area Status
Declaration checking, including flat and nested inductives and quotient initialization Lean4Lean.addDecl.WF is proved assuming VEnv.Injective, as are the supporting results that need injectivity; VEnv.injective proves the class.
Primitive projections, structure eta, recursor and quotient reduction Specified and connected to the implementation; the verification uses the same injectivity hypothesis where needed.
Shape model Sound for well-formed environments. Proves that a sort cannot equal a pi type, and that equal sorts have equivalent universe levels, without the injectivity hypothesis.
Injectivity of pi types and inductive type formers Proved: VEnv.injective : VEnv.Injective (Labelled/Injective.lean), at [propext, Classical.choice, Quot.sound]; choice comes from upstream definitions and lemmas, not the model.
Logical relation intended to establish injectivity Incomplete at a recursor's full application (IndRecSat), especially K-like reduction and indexed iota reduction.
Church–Rosser and experimental developments Unfinished. NormalEq.parRed has two sorry cases; Experimental contains further incomplete proofs.

The Verify development is sorry-free, so addDecl.WF depends on no sorryAx; VEnv.Injective enters as an explicit argument, which Verify/Unconditional.lean discharges by instance (addDecl.WF_unconditional, addDecls.venv_wf_unconditional). The theorem states that successful declaration checking preserves the formal environment invariant; consistency of the type theory is a separate question. Lean4Lean.addDecls.WF folds it over a list of declarations, and Lean4Lean.addDecls.venv_wf starts the fold from an environment with no constants and no quotient: whatever addDecls returns from there is modelled by a well-formed abstract environment. To check:

import Lean4Lean.Verify
#check @Lean4Lean.addDecl.WF
#print axioms Lean4Lean.addDecl.WF
#check @Lean4Lean.addDecls.venv_wf

The verification also trusts the runtime-model axioms in Verify/Axioms.lean, Lean's proof checker, and the compiler/runtime correspondence for native and opaque operations. The fork corrects some inherited axiom statements and removes others; runtime comparison tests exercise the rest.

Build and test

Install elan, then run these commands from the repository root. The toolchain is pinned in lean-toolchain (currently Lean v4.33.0-rc2), and dependencies in lake-manifest.json.

lake build
lake build Lean4Lean.Tests Lean4Lean.Experimental

The default build includes the library, executable, theory and verification. Tests and experimental modules are separate targets. Unfinished theory and experiments emit sorry warnings.

Target Contents
lake build Lean4Lean Kernel library, without the verification proofs
lake build lean4lean Command-line checker
lake build Lean4Lean.Theory Abstract type theory and metatheory
lake build Lean4Lean.Verify Implementation verification
lake build Lean4Lean.Tests Regression suite, including compile-time runtime-model checks
lake build Lean4Lean.Experimental Unfinished formalization experiments

Run the checker

CI runs both replay modes as smoke tests:

lake exe lean4lean Init.Core
lake exe lean4lean --fresh Init.System.IO

The checker replays built .olean files; it does not read the export format used by lake check and the Lean Kernel Arena.

Without a module argument, the checker infers the current package's main module from its Lake manifest. Otherwise, each module argument is a prefix: it checks all matching built modules. Ordinary replay checks each module against its imported environment and runs modules concurrently. Broad prefixes can use a large amount of memory; start with a single small module.

--fresh requires the prefix to match exactly one module. It rechecks that module and its imports into a fresh environment; it does not rebuild the source files.

To check another package, build that package with the same toolchain, change to its directory, and run this fork's executable in that package's Lake environment:

lake env /path/to/lean4lean/.lake/build/bin/lean4lean MyPackage.Module
Option Effect
--fresh Recheck one module and all its imports from scratch
-v, --verbose Print declarations as they are checked
--compare Compare slow checks with Lean's C++ kernel
--config=path.json Read fuel limits from a JSON file
--config:field=value Override one fuel limit with a JSON value

The configuration fields and defaults are in FuelConfig.lean. File and field options are applied in command-line order. Imported declarations are trusted in ordinary replay; use --fresh when that distinction matters.

What this fork changes

  • Inductive declarations and their verification. VInductDecl.WF specifies mutual blocks, positivity, universes, large elimination, constructors, recursors and iota rules. Flat and nested addInductive paths are connected to VEnv.addInduct, including Bool and Nat. Generated recursors and rules are proved well typed under the stated metatheoretic assumptions.
  • Primitive projections. VExpr.proj models projections directly, with typing, iota and structure-eta rules. Translation is syntactic and unique. Projection permissions are tested at the instantiated sort, including structures that may inhabit Prop.
  • Context-sensitive checking. Support and simulation theorems describe which variables, universe parameters and constants a checker run can read. Caches and the equivalence manager track the scopes their facts depend on. Verification no longer assumes that typing or definitional equality can always be strengthened by dropping unused variables.
  • Kernel checks and runtime models. Annotation definitions are checked before stripping them; nested restoration, projection and reduction checks expose conditions the proofs need. Simultaneous instantiation and abstraction are modelled correctly, and the inconsistent mkLevelIMaxCore_eq axiom is removed.
  • Metatheory. A shape model proves sort separation and sort injectivity. A logical relation develops the remaining injectivity argument and makes its unresolved recursor case explicit.

These changes include deliberate acceptance differences from Lean's C++ kernel. See divergences.md for the behavior and reproducing tests, and bugs-found.md for upstream's existing bug catalogue.

Findings and regression tests

The examples were found against the pinned toolchain. On v4.35.0 and v4.36.0-rc1, Lean's kernel also rejects the BinderScope and FieldViews declarations, but still accepts the loose-variable and _nested_1 declarations in NestedInductive. Annotations and UnsafeEq use a custom prelude, which Lean's kernel assumes it is not given; this fork checks those cases because its proofs need them.

Example What is exercised
InductiveSpec Generated recursors and iota/eta rules checked against Lean's kernel; primitive projections at instantiated universe levels
NestedInductive Restoring nested blocks with nontrivial levels, metadata and let types
Annotations A custom prelude whose non-identity annotation definitions let Lean generate ill-typed recursors; this fork checks the definitions
BinderScope Equivalences and cached checks learned under a binder being reused outside its scope
FieldViews Field domains with defaults and dead lets, including a structure accepted through a fact learned under a discarded field
PrimitiveScope Primitive recognizers checking retained terms outside temporary binders, while still recognizing the prelude's primitives
AxiomModels, LevelStd Runtime operations compared with their logical models, including open terms, repeated variables, metadata and universe levels
QuotInit Quotient declarations matching Lean's, including binder information
DeclFVar, ReservedName, UnsafeEq Malformed declaration inputs, the reserved panic constant, and unsafe Eq during quotient initialization

The old instantiation model substituted one term at a time. Lean substitutes simultaneously: (bvar 0).instantiate #[bvar 0, X] is bvar 0, not X. The old abstraction model similarly mishandled loose bound variables and repeated variables. The replacement models state simultaneous semantics; the old forms are derived for the closed, distinct-variable inputs where they apply. A third axiom, mkLevelIMaxCore_eq, equated two definitions that disagree on imax 1 u; it was unused and has been removed. The tests cover only inputs on which the runtime does not panic.

Design and proof guide

Inductive blocks and nested restoration

The specification states a block's constructor and recursor facts with its types declared but without its constructors. Index telescopes must already be types before the block exists, since an index cannot depend on the block's types. The implementation sometimes normalizes in a larger environment; simulation repeats those runs in the environment the specification needs.

Nested auxiliary types stand for occurrences of earlier types at parameters mentioning the new block. They have motives, minor premises, recursors and iota rules, but introduce no auxiliary type constants in the final specification. The kernel's temporary auxiliary constants are eliminated when it restores the block. AuxWF relates their declarations to the earlier types up to equivalent universe levels, accommodating the simplification performed by level instantiation.

restoreNested replaces an auxiliary application at its own arguments and levels. It preserves metadata and checks that restored terms contain no auxiliary constants; restored terms with lets are checked explicitly. Nested occurrences are checked against the block's types as axioms, before relying on the finished environment. The final insertion order may interleave each type with its constructors and recursor, so AddInduct allows that order.

The proof starts in Verify/Environment/Inductive.lean. Run.lean assembles the flat phases; MkRecInfos.lean and Rules.lean handle recursors; NestedBranch.lean assembles the nested path. Restoration in the theory is developed in Nested.lean through NestedWF.lean.

Projections and field domains

Primitive projections cannot always be represented by recursor applications: the kernel can project from Foo.{1} even when Foo's recursor eliminates only into Prop. Recording blocks in VEnv.inducts lets each projection rule identify the structure's declaration and constructor telescope directly.

ProjAllowed describes when a projection from a possibly propositional type is permitted. projEta requires those permissions for the expansion's projections. The model can be more permissive than the kernel about dependencies of fields after the projected field; soundness only needs the fields reached by the projection. The Ex example in InductiveSpec exercises this distinction. Lean's planned kernel renovation removes projections from propositional structures with data fields, which would change the cases ProjAllowed covers.

checkConstructors checks each field's declared domain, its form with lets unfolded, and its view with annotations stripped. FieldsKeptWF and CtorDoms provide the domain typings needed when a projection skips earlier fields. These are established by simulation in the smaller contexts, and survive nested restoration. The proof of inferProj.WF therefore does not assume strengthening.

The checker compares structure names, checks projection indices and universe counts, and reduces only complete constructor applications. Quotient reduction also checks the constructor's type and relation against the eliminator. These checks avoid relying on additional unproved separation properties of type formers. divergences.md records the observable differences.

Scope tracking and simulation

A fact learned under p : P a can depend on p without mentioning it. Proof irrelevance can equate hI with I.mk a p, enabling an iota reduction that has no known derivation after p leaves scope. Merely examining a cached term's free variables does not justify keeping that fact.

Each cache entry and union-find link carries the deepest scope of the facts its derivation consulted. Entries depending on a closed scope cease to be current; other entries remain available. Keys need no extra label for their own free variables because variable identifiers are fresh and a key mentioning a closed variable cannot be queried again. withFreshId rejects an already declared identifier.

Verify/Support proves support and simulation separately from typing, so these properties do not themselves require VEnv.Injective. The cache proofs rerun computations in the context where their results are used, with facts above the allowed scope set aside by a ceiling. ScopedEquivManager.lean and its verification handle labelled equivalences.

Scope tracking costs about 16.7% on a local replay of Lean core (1155.5 versus 990.4 billion user-mode instructions), mostly from cache bookkeeping, larger state and the pair map.

Primitive recognizers likewise check retained closed terms outside the binders where they discovered them. The kernel checks annotation definitions as identities before stripping them and uses the total, cached Expr.anySubterm instead of relying on an axiom for native subterm search.

Open metatheory

The shape model is sound and distinguishes sorts and pi types, but does not establish injectivity of pi domains/codomains or inductive parameters/indices; the labelled model does (VEnv.injective). The logical relation's remaining IndRecSat case must relate a recursor's reduct at the type of its full application. K-like and indexed iota reduction require a judgmental equality between the spine's indices and the constructor's indices. Turning that equality into a relation at the motive's argument shape is the unresolved conversion problem.

No counterexample to either injectivity assumption is known. Attempts to prove them through the current relation, or by induction on derivations, stop at this same step; the notes below record those arguments informally.

The verification also avoids assuming general strengthening, which the binder-scope examples suggest may fail, and uses support, simulation and explicit domain checks instead.

Research notes: the conversion gap and attempted injectivity arguments

The logical relation (LogRel/Rel.lean, RelS.lean) has every adequacy case but a recursor's full application (IndRecSat), in its K-like case and its iota case at a type with indices. Every use of the conjectures on addDecl.WF's path goes through unique typing or untyped defeq composition (isDefEqArgs compares arguments without their types), so nothing weaker than full injectivity serves; it has to come from the relation.

  • The gap. T.rec mot m is h steps when the indices is equal the constructor's idx judgmentally (KFields.index; in the iota case CtorParams' SubstRel). The reduct is typed at mot idx …, the spine at mot is …; converting between them goes through the motive's PiDefEq, which needs is and idx related at a shape at or above the valuation's ρ_is. Judgmental equality alone does not give that: the relation is not known to be closed under conversion, and closure would itself give forallE_inv.

  • Normalization is not the obstacle: relevant terms need a weak head normal form only at non-bot shapes, and a recursor on a proof major steps by the K-like rule without reducing it, Acc's included.

  • Tightness (in progress): a related pair's value shape lies below both terms' interpretations at the all-bot valuation in the model with no given shapes (Tight, AxBelow). It keeps stuck values at shapes their interpretations reach.

  • Every source of closure tried so far fails on depth. The relation is defined by recursion on depth, and adequacy needs it to agree across depths: LR.DefEq.lift/TyDefEq.lift are used in both directions, and the application case relates F X at the function's depth and lowers the result to the goal's.

    • Depth-bounded adequacy (adequacy of the whole environment below a constant case's depth) fails because the application case climbs depth: f : (Nat → Nat) → Nat needs depth 2 for a result at depth 0, and InterpTyped.out moves premises to the model's witness depth.
    • Saturation (pi clauses and related substitutions quantify only over arguments related at every typed shape below their interpretation) gives adequacy from saturated substitutions (LE_Interp.subst is an equivalence, valuations join), the identity substitution is saturated (variables at bot), and a firing condition stated with it makes both substitutions fire together. But "every shape below the interpretation" depends on the depth: at depth n it ranges over depth-n shapes. lift's direction from depth n' to n ≤ n' then needs arguments saturated at depth n to be saturated at depth n', which nothing gives; quantifying over every depth makes LR (n+1) refer to deeper relations.
    • Relational firing (the relation's reduction fires K-like and indexed iota steps only when the indices are related to idx at every shape below their interpretation, one depth down) settles the K and iota cases and the derived K-like equalities: a firing condition is a fact about the terms, and wherever adequacy needs it the index equality is a subderivation. It fails the same way: a spine can fire at depth n+1 (indices related at every depth-n shape) and stay stuck at depth n+2, so lift and mono_l across that depth relate two stuck spines at one depth and need their reducts related at the other. Firing at the interpretation's own depth is not well founded, since a spine's indices can be interpreted deeper than the spine is checked.
  • All three need the same missing fact: pairs related at every depth-n shape below their interpretation are related at every deeper one. For judgmentally equal terms that is closure under conversion again.

  • The K-like case needs injectivity itself, not only some closure. For X Y : Type, Eq.rec (motive := fun T _ => T) (m : X) Y h : Y steps to m when Y ≡ X; relating m at Y is LR.conv with TyDefEq X Y, and where X and Y are pi types that is the relation of their domains, forallE_inv's content at the motive's argument depth. Any route through the relation must prove injectivity below a recursor's depth inside its constant case, from the one fact the case has, Y ≡ X.

  • Other recursion orders do not supply it.

    • Depth-free shapes ordered by structure: the size the motive conversion needs is bounded by the motive's shape, as with depth, but the relation there comes from adequacy of the derivation of Y ≡ X, and adequacy at a shape needs constant cases at larger ones (the application case climbs, as with depth: (fun g => g 0) (fun _ => 5) at a depth-6 result needs fun _ => 5 at depth 7 and the function at depth 8). The regress has no measure: each constant case appeals to another derivation in the whole environment.
    • Depth-uniform relations (the relation at depth n agreeing with every deeper one on lifted shapes): depth n+1 sees fields and graph entries depth n does not, so relation at every depth-n shape never implies relation at depth n+1 unless the terms are judgmentally equal and the relation is closed under conversion, the fact sought.
    • Firing and conversion decided by the model: the model gives ⟦X⟧ = ⟦Y⟧ and, at sort shapes, equivalent levels (sort_inv), but TyDefEq at a pi shape asks for the domains' judgmental equality, which no interpretation determines; proving X ≡ Y ∧ tight → TyDefEq X Y a by induction on a stops at the pi case, where it is forallE_inv.
  • So the logical relation, with constant cases quantified over arbitrary related substitutions, cannot close IndRecSat's K-like case on its own. Closing it needs injectivity below each depth from an independent argument, such as a confluence proof for a reduction that includes the K-like and eta steps.

  • No counterexample to forallE_inv or indApp_inv is known. A failure needs a type-level redex whose major premise the theory equates with two different values; every rule that equates terms non-congruently is ruled out as a source:

    • Proof irrelevance equates proofs, never types, and only at one type. Large elimination out of a proposition needs a single constructor whose non-proof fields appear among its indices as variables (LargeElimOK, as the kernel's isLargeEliminator), so two constructor applications at one type differ only in proofs unless their indices already differ: a failure of indApp_inv is needed before proof irrelevance can produce one. The same holds for Eq.rec's K-like computation, Acc, a quotient of a proposition (Quot.lift out of a proof of Quot α r computes at a proof of α) and Quot.lift's rule, whose left side repeats α and r.
    • Structure eta expands deterministically, and on a type that may be a proposition only where every projection is allowed, so only proofs are projected; unit-like types hold no types.
    • The remaining rules (beta, delta, iota, projections, the quotient's, partial definitions' recursive equations) have one rule per head, so they overlap only through proof irrelevance and eta.
  • K-like reduction with an impredicative Prop, where Gilbert–Cockx–Sozeau–Tabareau and Abel–Coquand locate the breakdown of the usual metatheory, gives no counterexample either:

    • A cast Eq.rec (motive := fun T _ => T) m Y h computes only once refl X : Eq X Y, that is Eq X X ≡ Eq X Y; no hypothesis or proof supplies a judgmental equality (there is no equality reflection), so it needs X ≡ Y or an indApp_inv failure first.
    • A Prop-valued result (Eq X X against Eq X Y) out of a proof needs a motive into Type, which is large elimination: Or and other non-subsingletons eliminate only into Prop, so proof irrelevance between Or.inl a and Or.inr b produces no type equality.
    • Large elimination out of a proof computes from the spine's own indices, whatever the proof: Lean's kernel does not reduce K.rec … h for inductive K : Bool → Type → Prop | mk X : K true X at a hypothesis h (it does no K-like step there), while the spec derives it through h ≡ K.mk Y, at the same Y → Nat iota gives at K.mk Y. An index that is not a variable (mk n : I (n+1)) removes large elimination.
    • Abel–Coquand's non-normalizing proofs only loop: proof irrelevance already equates them with every proof of their type, so they add no equality between types. Likewise Acc and other impredicative inductives in Prop: unfolding Acc.rec through proof irrelevance is deterministic in the spine.
    • Every non-joinable peak between type-producing redexes therefore needs a proof typed at a type former applied to arguments other than its own indices (c fs : I idx with I (ctorIdx fs) ≡ I idx, ctorIdx fs ≢ idx), which is a smaller indApp_inv failure in the major's typing derivation. Turning that regress into a proof needs the statement for every zigzag of steps, not only between type formers: transitivity passes through arbitrary redexes, which is where a confluence argument would be needed.
  • Injectivity fails for heads that are not type formers, so the relation must not assume it there: a definition with an unused level parameter is equal at any two levels (C.{0} ≡ C.{1} for def C.{u} : Type := Nat), a definition can ignore its arguments, and a variable applied to proofs is equal at any two proofs.

  • Induction on derivations (sketched, not formalized). The invariant is a typed relation Inv Γ e e' T, defined by recursion on the head form of T under a deterministic type-level head reduction (beta, delta, iota, projections' iota, the quotient's rule, and for recursors of large-eliminating propositions only the K-like step, firing when the spine's indices equal the constructor's judgmentally, so that it never overlaps ordinary iota):

    • at a sort: if either side head-reduces to a head form, so does the other, and the two agree: equivalent sorts; pi types with related domains and codomains; the same type former, level and argument by level and argument; the same neutral head with related arguments;
    • at a pi type: applications to related arguments are related (this absorbs lambda eta);
    • at a structure: projections are related (structure eta); at a proposition: nothing (proof irrelevance); at an inductive type: the least relation closed under constructors and neutrals.

    The recursion is on universe level and structure: Prop contributes nothing, so impredicativity does not enter, and types without a head form (Acc.rec unfolding forever) are covered by the clause that transfers having one. forallE_inv and indApp_inv are its sort clause. Unique typing at the components' sorts has to be carried along, as IsDefEq.uniq does.

  • The rules, with the fundamental lemma stated under related substitutions:

    • pass from the induction hypothesis: symm, sortDF, forallEDF, lamDF (substitution), beta, eta, proofIrrel (a proposition's clause is empty), defeqDF (the type equality is a subderivation, so its sort clause moves the relation from A to B), projDF, projIota, projEta;
    • pass with a lemma: bvar (determinism of the head reduction), constDF (reduction commutes with instL, and the K-like firing condition moves along equivalent levels), trans (agreement composes once components' sorts agree), extra (the right side's typing is not a subderivation, so this needs an outer induction on the environment, as AdequacyHyps does);
    • fail: appDF at a recursor spine, in the recursor's own case. Ordinary iota is a constant case like the logical relation's. The K-like step fails: it fires on a judgmental index equality with no derivation in the induction, and relating the reduct needs the relation between the motive at the spine's indices and at the constructor's. For Eq.rec (motive := fun T _ => T) (m : X) Y h that is Inv of X ≡ Y at Type, from an arbitrary derivation. Neither derivation size nor the stratification index bounds it: HasTypeStratified.defeq holds an unstratified conversion. Universe level grows the wrong way (the needed judgment X ≡ Y : Type sits one universe above m : Y).
    • Firing the K-like step only on syntactically equal indices, or on indices related by the induction hypothesis, breaks congruence under proof irrelevance instead: Eq.rec mot m Y h ≡ Eq.rec mot m Y (refl X) relates a stuck spine to one that computes. Allowing ordinary iota on proof majors as well brings an overlap with the K-like step whose reducts agree only by indApp_inv on the major's typing, again an unbounded conversion.
  • So this route stops at the same place as the logical relation, the K-like case, and for the same reason: no measure decreases from the judgment being proved to the index equality that lets a K-like step fire.

Labelled model

Theory/Typing/Labelled is a second model, beside LogRel, after the labelled model of domain-semantics-lean: shapes carry syntactic labels, the interpretation Interp Δ Γ t σ ρ m is relative to a stage σ into an ambient context Δ, application is a graph lookup at the argument's label, and inversion is read off soundness by projecting a label. It imports neither LogRel nor Injectivity.

An inductive type former is interpreted as a curried graph (CurriedI): one λ-binder per parameter and index, each entry labelled by an argument and carrying its approximant as an input, typed as a constructor's inputs are. A full path ends below the inductive shape ind s ls args fc at those arguments, whose component fc approximates the field telescope of the type's single constructor, weakened past the indices (indFields, Type for other types), at the path's arguments and inputs, and is a type. Partial and full applications are then ordinary graph lookups, and η holds because the constant itself has λ-shaped approximants. The model reads the telescope off the block the environment records (IndSpec); LModel is unchanged, and the unfolding table is not read at a type former.

A constructor is a curried graph too (CurriedI), along its parameters and fields, whose entries carry their arguments' approximants as inputs and end in a constructor shape ctor c ls ps fl fv: the parameter and field labels, compared along the telescope (CtorLabelEq), and the field approximants below the inputs. Each input is hereditarily typed at an approximant of its argument's type, indexed by its position in the shape (Interp.ctorConst), and each full path's leaf is hereditarily typed at an approximant of the constructor's result type at the path's labels and inputs; that is what the constant's semantic typing is built from (curriedCode). A constructor shape is typed at its type former's application when that is not a proposition. At a type with one constructor it is moreover hereditarily typed field by field (Named.ind): each field's approximant at the domain of a code reached from the inductive shape's field code fc by lookups along the earlier fields' labels and approximants (Reach); and, named by a term, its field labels are that term's projections (ProjNamed). A constructor application builds that field code from its arguments' codes (fieldCodeE), at any application of the type former whose parameters are the constructor's (indApp_interpX, ctorCodeX): at its result, and at a recursor's major entry, whose indices are the constructor's.

A projection is read off its subject's constructor shape, of a type with one constructor, whose projections up to it are allowed (ProjAllowed): below the field at its index (Interp.proj). It is typed at its type (soundTy_proj): the subject's shape is below one named by the subject at an inductive code, whose field code reaches a code typing the field (Reach.interp); the labels being the subject's projections, that code's domain approximates the projection's type, read through the substitution by the type's own typing and Pinned conditions (Interp.of_substTerm'). Moving a constructor between equivalent levels moves those witnesses, which is Interp.relevel: the interpretation of a typed term is blind to equivalent levels, given body_levels.

The soundness induction on a sub-environment's derivations also carries, for each side that is a constructor applied to arguments, its spine (CtorSF): the arguments typed along the constructor's telescope, each semantically typed at its entry with codes that are types (SoundTyT), and the derived type's approximants among those of the rest of the telescope (TyIncl). It starts at the constant from ctor_type, and an application moves it on: a Π-type included in another has the domain included, and, at an argument, the codomain (TyIncl.forallE_dom, TyIncl.forallE_cod, by a Π-shape with one entry at the argument's slot). From it projIota is sound (projIota_soundEq): below the projection is a field of a constructor shape of the application, below the argument (spine_invI), and conversely the application has a constructor shape whose field is above the argument's approximant (ctorApp_teleN, allowed at a structure with η when that field is informative). So is projEta (projEta_soundEq): an informative saturated approximant of the term is the constructor shape at the type's parameters and the term's projections, whose fields approximate them (saturated_ctor), so the expansion has a shape above it; and a constructor shape of the expansion is below the saturated join of the term's approximants its fields are read off. Both read the constructor's telescope as pinned, which a chain's step gives from SoundOn its envT (DeclFacts.ctor_pin).

A recursor that eliminates into every sort, of one of its block's own types (RecSpec) or of an auxiliary type of a nested block (RecSpecA, RecSpecG), is a curried graph along its parameters, motives, minor premises, indices and major premise whose entries carry inputs (Interp.recConst). A full path's leaf is below the iota rule's right side for the constructor the major premise's input is a shape of (RecWitness), read at the path's labels and that constructor shape's field labels, under the inputs and the shape's field approximants; at a constructor of a structure with η, whatever the major premise's input, at the major premise label's projections up to definitional equality, under the input's fields if it is a constructor shape and ⊥ otherwise (RecWitnessE); or, at an instance that is a proposition of a block whose one constructor's fields are proofs or indices, for that constructor at any major premise, at field labels equal to the index labels where the fields are indices (RecWitnessP); each input and each leaf is hereditarily typed at an approximant of its type. Its semantic typing is built as the constructor's (recCode), and its declared type is literally the telescope. An auxiliary type's constructors are the earlier type's, so its major premise's constructor shape is the earlier constructor's at the levels and parameters the occurrence gives (headLvls, headPs), whose labels are related exactly when they are along the auxiliary constructor's telescope (RecSpecA0.lab). Other recursors have only ⊥.

Directedness (Interp.dirAt) is an induction on the first of the two derivations, not on typing: a recursor's leaves interpret its iota rules' right sides, which mention the recursor, so they are subderivations of its interpretation but not of its typing. Two recursor shapes are compatible when their leaves are wherever their paths' labels are related and inputs compatible (CurriedI.compat_paths'); there the major premises' constructor shapes are compatible, so the constructor and its field labels agree, the iota stages are related (iotaStage_substEq), and the first leaf's directedness bounds both. At a structure with η the constructor is the type's only one (RecSpecG.eta_unique), and the projections of related major premises are related (RecSpecG.etaProj_congr, by projDF along the field telescope).

Below a recursor applied to an iota rule's left side, every approximant is one of its right side (iota_to): a recursor shape is a curried graph whose saturated applications are approximants of the right side (recOut), so a spine of lookups lands below one at the arguments' labels and approximants (spine_invI), and the major premise's constructor shape fixes the field labels. Conversely, below the minor premise's application is the recursor at the constructor (iota_from): the right side's approximant is saturated, and a one-path recursor shape at the binders' slots, with the constructor shape at the fields' slots as the major premise's input, has it as its leaf. An index entry's input is lowered through the motive's slot to inputs named at the motive's domain codes (lookup_lower, spine_lower), which move to the recursor's telescope (Interp.relift). At an instance that is a proposition, a block whose only constructor's fields are proofs or indices (FieldKind: an index field's type is the index's at the result's earlier arguments, up to definitional equality) reduces at any major premise whose index labels are the constructor's indices at the field labels (RecWitnessP): proof fields' labels are related by proof irrelevance and a proof variable's slot is ⊥ (Adm.slot_bot_of_prop), and an index field's label is the path's index label, at a type the index equations convert (fieldTy_idx). Its iota rule is sound by the same construction with a ⊥ major input (iota_fromP), the index inputs saturated along the recursor's telescope by the left side's arguments' semantic typings (PropSem, tele_inputs), so a field's input is its slot. The saturation is decoded from the closed rule's semantic typing under its binders (SoundTy.lams_inv), and both directions lift back over the binders (sound_lams_eq), so those iota rules are sound outright (IsC1Iota.soundEq). A constructor applied to arbitrary arguments, not only to the binders' variables, has its constructor shape above given approximants of the field arguments, given each argument's semantic typing at its instantiated telescope entry and the entries' Pinned (ctorApp_tele): each argument's approximant is saturated by its typing, and the code is moved back along the substitution by the earlier arguments (Interp.to_substTerm), whose saturation is the same construction one entry shorter (tele_inputs). The shape comes with the code the constructor's result gives it at those inputs (ctorLeaf_codeE, the inputs indexed by position): when an auxiliary type's earlier type is a structure, its recursor's major premise input is typed there, moved along the head's arguments into the iota rule's context (Interp.of_substTerm) and on to the recursor's telescope (iota_major_domA).

The iota rule of a structure with η at an informative instance, of a block's own type or headed by one in an auxiliary type, is sound the same way (IsEtaIota.soundEq). From left to right the field labels are the projections of the constructor's application, which are its fields by the projection iota rule (IndSpec.projs_mk), and the fields' inputs are below their slots. From right to left the major premise's input is the constructor shape at the fields' slots when one of them is informative (ctorApp_interp, ctorApp_tele), and ⊥ otherwise, below which every approximant of the constructor's application lies (ctorApp_le_bot_eta) (iota_fromG, iota_fromAG). The projections must be allowed (HeadProjAllowed): a block that eliminates into every sort at a sort that may be zero has one constructor whose fields are proofs, and one with auxiliary types has a sort never zero, which is its auxiliary head's (headProjAllowed_own, headProjAllowed_aux).

The quotient's constants have clauses of their own, read off the environment's addQuot declarations (QuotSpec). Quot is a curried graph without inputs (Curried) ending in the label-only shape quot ls [α, r]; Quot.mk one ending in qmk ls [α, r, a] y with y below a's input, as a constructor is, and only ⊥ at a proposition; Quot.lift one along its six arguments whose full path's leaf is below f a, read at the element label a of the major premise's qmk input and under its element approximant, or, at a proposition, at any a : α (LiftWitness). Quot.ind has only ⊥. The declared types are literally the telescopes, so the constants are semantically typed outright (soundTy_quotConst_of, soundTy_mkConst_of, soundTy_liftConst_of). Below Quot.lift applied to the rule's arguments every approximant is one of f a (quot_to): a Quot.lift shape is a curried graph whose saturated applications are approximants of f a (liftOut), and the major premise's qmk input is below Quot.mk r a's, so its label is a's, or, at a proposition, any a : α, related to a by proof irrelevance. Conversely, below f a is the one-path Quot.lift shape at the binders' slots, with the qmk shape of a's slot as the major premise's input (quot_from). So the rule is sound (quot_soundEq). A chain whose environment has the rule ran addQuot, which only it adds, and its names are read by no other clause (VEnv.WF'.quotEnv, QuotSpec), so QuotSound holds at every chain's model (VEnv.quotSound).

Two applications of constructors with the same approximants, the first informative (its instance not a proposition, and not a structure's with η), are of the same constructor with parameters and fields related along its telescope (ctorLabel_of_defeq): its constructor shape at ⊥ fields is the probe.

It covers the core rules (variables, sorts, Π, λ, application, β, η, conversion, proof irrelevance, constDF, at type formers too) and takes the rest as the explicit interface LabelledSound: the semantic typing and level invariance of the bodies the unfolding table LModel.δ reads constants as, that a type former's and a constructor's declared types are semantically their telescopes (ind_type, ctor_type), and SoundEq of the two sides of every extra instance other than those iota rules (IsC1Iota) and rules whose type is a proposition (IsPropRule, both sides having only ⊥), and of every projIota and projEta instance at an informative field or structure (at a proposition both sides have only ⊥, sound_of_proofs). projDF is proved (sound_projDF). A constant in the table is read below approximants of its body that are typed at an approximant of its type and name it, as popl27's fixed point carries its slot, so the constant is semantically typed by its clause alone (soundTy_delta). Definitional unfolding (c.{params} ≡ body with δ c = some body) is discharged given the body's and the type's semantic typing (sound_unfold), and ind_type at a declared type that is literally the telescope outright (ind_type_of_eq, both in LabelledSound.of_families).

File Content
Basic the model's data LModel, universes up to ≈, labels (TyEq, PiLabelEq, IndLabelEq, Stable), IndSpec
QuotLabel the quotient's telescopes, QuotSpec, its labels (QuotLabelEq, MkLabelEq)
Shape, HasType shapes, their order, compatibility and join; typing of shapes
Curried curried graphs for constants with arguments: CurriedI with inputs (type formers, constructors, recursors), Curried without (Quot)
QuotCurried the quotient's curried families (quotOut, mkOut) and Quot.lift's leaf (LiftWitness)
RecSpec what the model reads off the environment about a recursor and its iota rules
Interp the interpretation, admissible stages, the clause conditions Pinned
RecJoin compatibility of curried shapes from their leaves, the iota stage, the recursor clause's premises (RecData)
RecEta the recursor at a structure with η: its one constructor (RecSpecG.eta_unique), projections of related major premises (RecSpecG.etaProj_congr), a constructor application's projections (IndSpec.projs_mk)
QuotJoin joins of Quot.mk and Quot.lift shapes (LiftData), related leaf stages (LiftWitness.pair)
Directed, Sound directedness of interpretations of typed terms; the per-rule soundness lemmas
IndConst the code a curried shape is hereditarily typed at (curriedCode); the type former's probe and saturated family (indOutF)
Relevel the interpretation of a typed term at equivalent levels
CtorConst, RecConst the code a curried constructor or recursor shape is hereditarily typed at
QuotConst the codes the quotient's curried shapes are hereditarily typed at
QuotIota the quotient's rule: quot_to, quot_from, quot_soundEq
Soundness the interface and IsDefEqStrong.sound / IsDefEq.sound
Inversion Π- and sort injectivity up to chains, sort/Π no-confusion, the stratified form given sort uniqueness
Uniqueness unique typing, sort uniqueness and chain collapse, given ProjUnique
IndInversion injectivity of type formers and no-confusion, ProjUnique from IndFacts
RecIota recursor applications are below the iota rule's right side (recOut, spine_invI, iota_to)
LamInv semantic typing under binders (SoundTy.lams_inv), open equivalences lifted over them (sound_lams_eq)
RecIotaFrom one-path curried shapes; constructor shapes at informative inputs and their codes (fieldCode, ctorLeaf_code); slots read in sub-telescopes
RecIotaSound the right side is below the recursor's application (iota_fromG, iota_from), lowering index inputs through the motive's slot (lookup_lower, spine_lower); iota_soundEq
ProjSound a projection's semantic typing (soundTy_proj, sound_projDF)
ProjSpine constructor spines along a derivation (CtorSF); projIota and projEta (projIota_soundEq, projEta_soundEq)
CtorInversion no-confusion and injectivity of informative constructors (ctorLabel_of_defeq)
TeleInputs inputs typed along a telescope for arguments with semantic typings (tele_inputs)
TeleDom a constructor's shape at arguments with semantic typings (ctorApp_tele)
RecIotaAux an auxiliary type's iota rule, from left to right (iota_toA); its recursor's telescope, major premise and iota rule at a stage
RecIotaAuxFrom an auxiliary type's iota rule, from right to left (iota_fromAG, iota_fromA), given the head constructor's semantic typings (HeadSem); the η-structures' iota rules (IsEtaIota.soundEq)
Labelled.lean the statements, and VEnv.InjectiveAt, both fields of VEnv.Injective at one environment
EnvTable the unfolding table of a declaration chain; every defining equation is an entry's, the quotient's rule or an iota rule
Specs CtorSpec0 for a constructor of a well-formed block, given unique typing and Π-injectivity in its envT
EnvInd the induction along the environment: Obligations, Good, StepObligations
RecSpecs RecSpec0 for a recursor of a well-formed block, given unique typing and Π-injectivity in its envT and envR
EnvIota the iota rules IsC1Iota and IsPropRule cover, at every well-formed environment given the remaining families
IotaProp the iota rules of a block that eliminates only into Prop are IsPropRule
AuxSpecs RecSpecA0 from any environment with the block, unique typing and unique sorts (RecSpecA0.of_env): label transport through the earlier constructor (auxLab_iff), the head's sort (aux_level_equiv), recursor names unique across blocks (WF.recName_inj)
BlockSpecs a block's iota rules at its step are sound (blockIota); the projections of an η-structure's iota rule are allowed (headProjAllowed_own, headProjAllowed_aux); the semantic facts from SoundOn an environment (HeadSem.of_env, teleSem_of_env); index fields' types (fieldKind_of_block)
RecSpecsAux RecSpecA at every auxiliary recursor of a well-formed environment, given QuotSound (WF.recSpecA_of_rules)
IotaCover given QuotSound, every iota rule is IotaCovered (WF'.iota_classify; WF'.isAuxIota)
RelevelFree Interp.relevel without a table hypothesis; every table's bodies are level-invariant (body_levels_of)
SoundOn soundness of a sub-environment's derivations, from LabelledSound's fields at its constants (IsDefEqStrong.soundOn)
EnvSound a model is sound at a chain's declarations one after another (GoodChain.facts), given the quotient's rule (Families)
EnvRules every chain's model is sound given the remaining families; CtorSpec and RecSpec at every well-formed environment
EnvQuot a chain with the quotient's rule ran addQuot (WF'.quotEnv); QuotSound (VEnv.quotSound)
Injective VEnv.Injective (VEnv.injective), and from StepObligations

TyEq is the transitive closure of ∃ u, Γ ⊢ A ≡ A' : .sort u: the raw judgment has no transitivity across sorts, so inversion read off soundness is up to such chains (IsDefEq.forallE_inv_labelled). A chain is sound, SoundEq being type-agnostic and transitive, so chains invert at sorts and Π-types as single equations do. Two typings of a term then have chain-related types, by induction on the syntax-directed HasTypeStrong; hence sorts are unique and chains collapse (IsDefEq.uniq_labelled, HasType.sort_uniq_labelled, IsDefEqU.forallE_inv_labelled), and VEnv.Injective.forallE_inv_stratified's statement holds at the model's environment (IsDefEqU.forallE_inv_stratified_labelled).

Injectivity of a type former is the same projection as Π-injectivity: the probe is the label-only shape of one application, and below a curried graph every approximant of a saturated application is below the label-only shape at its own arguments (IsDefEqU.indApp_inv_labelled, with no-confusion against sorts, Π-types and other type formers). Building the probe types the arguments along the telescope, by unique typing of the head spine only, which meets no projection. The projection case of unique typing then follows from projType_congr (ProjUnique.of_facts). Both take IndFacts, what the model uses of a well-formed environment about its inductive types, which VEnv.WF implies (IndFacts.of_wf); VEnv.WF is defined with classical choice, so only injectiveAt_labelled_of_wf depends on it.

Along a well-formed chain ds the model reads constants by the chain's table VDecl.table ds, which is valid outright (VEnv.WF'.table_spec), and LabelledSound reduces to Obligations: its fields without the unfolding family of extra, the quotient's rule and the iota rules remaining (VEnv.WF'.defeqs_cases). VEnv.injective_of_steps proves VEnv.Injective from StepObligations: each step's Obligations, given Good of the earlier environment (unique typing, Π-injectivity, both fields of VEnv.Injective, CtorSpec0 of its constructors) and the new environment's constructor specs. Those are read off VInductDecl.WF in the block's envT (CtorSpec0.of_block), indexed families included: envT is the earlier environment with the type formers as axioms, Good by the same steps. The obligations are stated at each step's whole environment, since Interp there reads stages that mention the new constants. Injective imports Injectivity for the statement of the class only.

VEnv.injective proves VEnv.Injective: every chain's model is LabelledSound, the quotient's rule being sound there (VEnv.quotSound), and projIota and projEta are sound at every chain's model (VEnv.projRules). A rule typed at a sort ≈ zero is exactly an IsPropRule one (VEnv.WF.isPropRule_iff, by sort uniqueness); the iota rules of a block that eliminates only into Prop are IsPropRule, its motive's application being a proposition (VEnv.WF.isPropRule_of_not_large); and the iota rules of a block's own types, when it eliminates into every sort, are IsC1Iota at a constructor of an informative instance that is not a structure's with η, and at the one constructor of a proposition instance whose fields are proofs or indices (VEnv.WF'.isC1Iota): RecSpec, the recursor's and the constructor's absence from the table and the type formers (VEnv.WF'.block_names) and the proofs' sorts in the rule's context (iotaCtx_field_sort) are theorems. Every iota rule is IotaCovered (VEnv.WF'.iota_classify): an auxiliary type's is IsAuxIota, or IsEtaIota when its head constructor is an η-structure's (VEnv.WF'.isAuxIota), an own η-structure's at an informative instance is IsEtaIota, a proposition instance's is IsC1Iota at FieldKind. The rest is proved by induction along the chain for the final model (GoodChain.facts): a body added at step k is typed in the prefix before it, whose derivations are sound in the final model given SoundOn that prefix (IsDefEqStrong.soundOn), which the earlier steps give; body_levels holds of every table (body_levels_of). A mutualDef block's bodies are typed with the block's constants, which their clause types, so they are sound given SoundOn the environment before the block (mutual_bodies). A type former's declared type is its telescope already before its block (VInductDecl.WF.typeDefEq, as checkInductiveTypes checks it). A block's iota rules are proved sound at its step, without the hypotheses (blockIota, the chain's DeclFacts.iota): its specs are read in its envT and envR, where GoodChain gives unique typing, Π-injectivity and unique sorts (RecSpec0.of_block, RecSpecA0.of_env, CtorSpec0.of_block), and its semantic facts from SoundOn envR (soundOn_block, HeadSem.of_env, teleSem_of_env); so no iota rule is asked of Families. The recursor of each of a block's own types, when it eliminates into every sort, satisfies RecSpec (VEnv.WF.recSpec_of_rules), each field read off the block (RecSpec0.of_block): the iota rule's right side at its type under its binders by λ-inversion in envR, and each field at its declared sort from the constructor's check.

LabelledSound is not satisfiable for an environment with an extra rule whose right side has an approximant its left side lacks: in particular an iota rule into a sort above Prop at a proposition instance whose constructor has a field that is neither a proof nor an index at its own type, since a proposition's constructor shape is ⊥.

Source map and contributing

Path Starting point
Main.lean, Replay.lean CLI and replay
Environment.lean, TypeChecker.lean Kernel entry points
Inductive/Add.lean, Inductive/Reduce.lean Inductive declaration checking and reduction
Theory/Inductive.lean, Theory/Typing/Basic.lean Inductive specification and typing rules
Verify/Environment.lean Top-level declaration verification
Theory/Typing/Injectivity.lean Explicit open hypotheses and proved sort properties
Theory/Typing/LogRel Shape model and logical relation
Theory/Typing/Labelled Labelled model of the core rules and inductive types
Verify/Axioms.lean Trusted runtime models
Tests, Experimental Regressions and unfinished experiments

For a review or proposed change, state which specification, implementation or proof obligation it affects, include a reproducer for behavior changes, and run the relevant build and replay checks above. New hypotheses and differences from Lean's kernel should be explicit. Reports about this fork should be filed here; establish whether an issue also occurs upstream before reporting it there.

The project retains upstream's Apache 2.0 license, copyright notices and author attribution. The LLM-maintenance notice applies to this fork's changes, not to upstream.

About

LLM-maintained research fork of lean4lean

Resources

Stars

0 stars

Watchers

0 watching

Forks

Contributors

Languages