Skip to content

About

No description, website, or topics provided.

Resources

Stars

7 stars

Watchers

0 watching

Forks

Repository files navigation

Lean inductive models

lean-inductive-models performs translation validation of user-defined Lean inductives into an extensional type system with only a small hard-coded inductive basis.

It is a Lean 4 NDJSON-to-NDJSON filter and standalone model checker. For each supported inductive group, it retains the source declaration and adds ordinary definitions for a kernel-shaped interface: type formers, constructors, recursors and projections. The source inductive's computation rules hold by definitional equality inside Lean's kernel; the model publishes them, together with its other reduction and uniqueness laws, as the propositional-equality theorems listed in the output contract. That weakening is appropriate for an extensional consumer, but the generated model is not a drop-in source of Lean's definitional reduction.

This is translation validation, not a general soundness proof for inductive types and not yet a verified translation. The generator is not accepted on its own authority: on the default run, the structural checker reconstructs each generated family's expected interface from the exact inductive export record and compares its names, universe arities and declaration types literally. Lean's kernel then checks that the generated definitions and theorem proofs inhabit those types. Thus the source/model correspondence is validated for each output, rather than merely sampled by the test corpus. The checker and the constructions themselves are still ordinary, unverified Lean code; a future verified checker could reduce that remaining trust.

The idea and public model interface are human-authored; the implementations of the model constructions were generated by Claude and Codex.

Usage

lean-inductive-models [OPTIONS] IN.ndjson

IN.ndjson is an NDJSON kernel export of a Lean environment, as produced by leanprover/lean4export; it may be - for standard input. Stock upstream lean4export is all you need; this project builds nothing of its own on that side.

With no options, all generation routes and both structural checks run, each generated island is kernel-checked as it is produced, and the transformed export is written to standard output. Diagnostics go to standard error.

# Generate, check generated islands, and write to a file.
lean-inductive-models -o OUT.ndjson IN.ndjson

# Check an input without generating or writing anything.
lean-inductive-models --no-inductives --check --no-output IN.ndjson

# Also request a separate kernel check of the input declarations.
lean-inductive-models --type-check-input --no-output "$IN"
Option Default Meaning
--nested on Generate models for nested inductives.
--mutual on Generate models for plain mutual inductives.
--simple on Generate models for ordinary non-mutual inductives.
--basic on Generate bootstrap and generated-support models.
--inductives on Set all four generation options.
--check-input on Structurally check input model families.
--check-output on Structurally check final model families.
--check on Set both structural-check options.
--type-check-input off Replay the parsed input through Lean's kernel.
--type-check-generated on Kernel-check each generated model island as it is produced.
--output on Write the transformed export.
-o PATH - Select the output path and enable output.
--quiet off Suppress successful-pass diagnostics.

Every boolean long option has a --no-... form. Options apply left to right, so --no-inductives --simple enables only simple generation, while --simple --no-inductives disables every generation route. --no-output suppresses only the final write; enabled transformations and checks still run.

The input is parsed exactly once and nothing is ever re-read, re-parsed or spooled to disk: the tool opens no export file it was not given on the command line. Every pass — parsing, generation, structural checking, and both optional kernel gates — runs in the invoking process. It starts no checker worker and does not re-execute itself under a supervisor.

A named -o PATH output is built in a private sibling and renamed over the target only after every requested structural and kernel check has passed, so a rejected or failed run leaves an existing target untouched. Standard output cannot retract bytes, and a run that fails late may therefore already have written a valid declaration prefix.

Exit codes follow the Lean Kernel Arena checker contract:

Code Outcome
0 Accepted.
1 Rejected by a requested structural or kernel check.
2 A requested generation route declined an unsupported owner.
3 Parser, I/O, CLI, or internal tool error.

Building

The Lean version is pinned by lean-toolchain.

lake build
lake test

lake test is the quick fixture suite. Run the complete correctness interface with:

test/scripts/run-correctness.sh

Detailed target matrices, CI envelopes, fixture regeneration, and diagnostic tools are documented in Maintainer testing.

Idea

The filter represents a supported inductive family with ordinary definitions and theorems while retaining the source declarations. This gives downstream tools an explicit interface they can inspect without treating a generated name as evidence that it really models the source.

The structural checker supplies that missing evidence: it relates the public model declarations to exact exported kernel metadata and literal source syntax. Private declarations may implement the model, but they are not an additional public interface.

The small trusted basis is:

Eq  Nat  PUnit  PSigma'  Quot

The first four are ordinary inductive owners. Quot denotes Lean's kernel quotient bundle. Routes that derive function extensionality may additionally use Quot.sound; generated developments may use the standard axioms Classical.choice and propext when required.

Each of these is written by the tool itself, at a fixed declaration, wherever a generated island needs one — never taken from a record the input declares later in the stream. See the output contract below for what happens to such a record.

And nothing else is in the environment. A run starts from an empty environment; each island is a disposable extension of it, so the constants that exist at any point are exactly the source records consumed so far plus the basis declarations generation has written. There is no prelude underneath, and the tool never installs one.

Every conversion question is put to Lean's kernel. Whether a projection selects its field, whether a round trip is definitional, whether a recursive occurrence reduces to its owner, whether a basis declaration the input already holds is the one this tool would have written — each of those is decided by Lean.Kernel.isDefEq against the construction environment, not by the elaborator's Meta.isDefEq (src/InductiveModels/Gen/Monad.lean). The kernel is what judges the emitted island, so any other oracle could only disagree with the final verdict in two useless directions: decline a shape the kernel would accept, or accept one it then rejects. It is also the oracle that suits the environment above — it asks for no constant that is not in the terms it is given, where the elaborator's Nat-offset acceleration reaches for instAddNat on the strength of a constant name. A kernel exception at one of these gates is this tool's own bug and reaches its containment boundary; it is never read as a shape the tool declines to model.

A consumer using models as an inductive front end must therefore implement the five-member basis and admit the standard axioms of whichever generated route fired. With --basic on, that basis is the only unmodelled inductive residue in the output.

Output contract

Throughout, p⃗ is a member's parameters and i⃗ its indices, x⃗ is one constructor's own field telescope, and M⃗, m⃗ are a recursor's motives and minor premises. A modeled member T has constructors C_0 … C_{n-1} and recursor R, whose exported rule j belongs to C_j; ı⃗_j is the index tuple in C_j's result type, and A_j is field j's declared type.

Type formers, constructors, recursors and intrinsic projections are safe definitions; every iota_j, unitlike, ruleK and eta slot is a theorem. Each lives at exactly the name given.

Slot Present when Statement
T._model per member T's exported type, ∀ p⃗ i⃗, Sort w
C._model per constructor C's exported type, ∀ p⃗ x⃗, T._model p⃗ ı⃗(p⃗, x⃗)
R._model per recursor R's exported type, ∀ p⃗ M⃗ m⃗ i⃗ (x : T._model p⃗ i⃗), M i⃗ x
R._model.iota_j per exported rule j ∀ p⃗ M⃗ m⃗ x⃗, R._model p⃗ M⃗ m⃗ ı⃗_j (C_j._model p⃗ x⃗) = rhs_j, at type M ı⃗_j (C_j._model p⃗ x⃗)
T._model.proj_j field j is projectable ∀ p⃗ i⃗ (self : T._model p⃗ i⃗), A_j, each earlier field x_k occurring in A_j replaced by T._model.proj_k p⃗ i⃗ self
T._model.proj_j.iota with T._model.proj_j ∀ p⃗ x⃗, T._model.proj_j p⃗ ı⃗ (C._model p⃗ x⃗) = x_j
T._model.unitlike T is unit-like ∀ p⃗ (x y : T._model p⃗), x = y
T._model.eta T is structure-like and not a proposition ∀ p⃗ (x : T._model p⃗), x = C._model p⃗ (T._model.proj_0 p⃗ x) … (T._model.proj_{n-1} p⃗ x)
R._model.ruleK R is exported with k = true ∀ p⃗ M⃗ m⃗ (x : T._model p⃗ ı⃗_0), R._model p⃗ M⃗ m⃗ ı⃗_0 x = rhs_0

p⃗, i⃗ and w are read the way Lean's kernel reads them: it weak-head normalises the type former before each binder it peels, so inductive SF : MyFam with def MyFam := Nat → Type has one index, and SF._model.proj_j binds it, although SF._model restates the declared MyFam. A constructor's telescope, which the kernel reads as written, is read as written.

rhs_j is the exported rule's own right-hand side — for a plain block, m_j applied to x⃗ and to R._model at each recursive field. Structure-like is the kernel's own predicate: nonrecursive, unindexed, exactly one constructor. Unit-like is that with a zero-field constructor. Nonrecursive is read off the recursor rather than off the export's isRec flag: that flag is syntactic and reads true of a block whose only owner mention is one a definition discards, whose recursor then binds no induction hypothesis at all. A field is recursive exactly when an owner occurrence survives full reduction, which is the same reading every construction here uses. The scope is the whole block, as the flag's own is. A field is projectable when T has one constructor and the kernel's own proj walk is well typed there — which is every field of a non-propositional owner, and of a propositional one only its propositional fields, and only while no later field's type names a non-propositional one; the owner may be recursive or indexed. k = true forces one rule with a zero-field constructor, so ruleK is iota_0 with the constructor major replaced by an arbitrary inhabitant of that exact constructor-result fibre — an indexed family retains ı⃗_0 rather than quantifying over indices.

T._model, C._model and R._model carry their source declarations' exported types under one simultaneous current-group rewrite and nothing else. That rewrite replaces the type formers, constructors and recursors belonging to the same atomic inductive record as T; for a mutual record it therefore replaces all members together. Names belonging to any other inductive record remain source names, whether or not that other record already has a public model. R._model.iota_j states the exported reduction rule itself under the same current-group rewrite — the recursor's own minor premise supplies the motive application, constructor levels, parameters, indices and field telescope, and the exported rule supplies the right-hand side. The remaining five slots are reconstructed from the owner's own exported records — the constructor telescope, the recursor's minor premises, the kernel's projection rules — and then rewritten with that same scope; no source structure syntax is consulted, and T._model.eta reconstructs through the intrinsic projection slots rather than through any exported field wrapper. An atomic mutual block still exposes one interface per member; private mutual bookkeeping and support declarations are not public slots.

Generation consumes source declarations in their original order. At an accepted inductive owner it emits the complete generated island immediately before that source owner; all other source declarations retain their relative order. Dependencies generated recursively inside an island precede the generated declarations that consume them. There is no final global reorder or whole-output kernel replay.

Every record therefore declares each name it references before referencing it, so any prefix of the output that ends at a record boundary is itself a complete export. This is checked over the whole fixture corpus by test/EmissionOrderCensusTest.lean.

One class of source record is dropped rather than retained. Generation writes a fixed set of declarations of its own — the basis inductives above, the tight pair's six derived declarations, Nonempty, Iff, the kernel quotient, Quot.sound, Classical.choice and propext — at the first point one is needed, whatever the input reserves. When the input declares one of those names later in the stream, its record is compared against the declaration that was written: an identical record is dropped, since the output already carries it, and a record that is not that declaration rejects the run rather than being silently replaced. Every other source declaration is retained.

An inductive record is retained in the order of the block it declares: its types array in the first member's all order and its ctors array in the members' own ctors lists. That is the order Lean's kernel generated the block in and the order the Kernel Arena replays it in, so a stream that permutes either array declares the same block, and is read and written back in that order.

Checker contract

The structural checker discovers a family whenever any public model slot for an inductive record is present. It then requires the complete corresponding family and checks:

  • model-before-owner ordering and absence of public backreferences;
  • unique type-former, constructor, recursor, rule, projection, and metadata slots at their exact names, with no rule slot beyond the exported rule count;
  • matching universe arities and literal declaration types after simultaneously renaming exactly the current inductive record's source declarations to their model names;
  • exact recursor-iota and projection-iota propositions; every projection-iota right-hand side is the constructor field binder itself, on every route, and the checker recomputes exactly that;
  • safe definitions in implementation slots and theorem declarations in proof slots.

The checker is a pure function of the export text: it never asks Lean for definitional equality, never appeals to proof irrelevance, and never compares a declaration's value. Every correspondence verdict is syntactic equality of declaration types, up to binder names and binder information, after that current-group source-to-model renaming. In particular, the checker rejects a model type which uses U._model in place of an external source constant U, even when U belongs to an earlier modeled inductive record. Thus an accepted slot is exact rather than merely definitionally right, and the verdict is independent of the kernel's. Those two are what an export's expression arena is interned modulo, upstream in lean4export as much as here, so they are not available to compare.

Deciding what to compare against is a separate matter. Enumerating an owner's parameters and indices and reading its sort, enumerating a constructor's parameters and fields, deciding whether an owner or a field type is a proposition, and deciding which fields admit an intrinsic projection apply the kernel's own rules; that shape analysis does unfold transparent definitions and read their values — δ, β and ζ, and nothing else — except where it reads an owner's own type, which also takes ι and projection steps on literal constructor applications, as described under Stopped: a type former the checker cannot read as the kernel does. It settles which slots must exist and how their statements are spelled. It never loosens the comparison itself.

--check-input runs it on models already in the input. --check-output runs it on the final transformed stream, validating the compact incremental and final certificates rather than reconstructing and replaying the whole output. An input with no model slots is not rejected merely because an inductive is unsupported or generation is disabled. Independently of either flag, an input in which a public model declaration occurs after its owner is rejected before any other pass runs.

--type-check-input and --type-check-generated govern disjoint declaration classes. The former replays only input declarations, in stream order, through Lean's kernel. The latter, enabled by default, checks each exact generated model island incrementally as it is produced; input declarations are trusted dependencies in that environment, not checked a second time. With either flag off, that declaration class is not kernel-checked.

Constructions

Different inductive shapes use different constructions rather than one construction that handles everything. This keeps each construction focused and lets the constructions for more general shapes build on the simpler ones.

Some terminology used below:

  • A result sort is never-Prop when its universe is always positive (Type u, for example), and sometimes-Prop when it can become Prop at some universe instantiation (Sort u, for example).
  • A field is recursive only when an occurrence of the owner survives reduction; a mention discarded by reduction does not affect routing.
  • Large elimination means a recursor whose motive may live in an arbitrary Sort, rather than only in Prop.
  • A lift, analogous to PULift, raises a proposition to an exact requested sort without forgetting its proof.

Large elimination and lifts matter most at a sometimes-Prop sort: a Nat-tagged representation can never instantiate to Prop, while an unlifted Church proposition has the wrong sort at positive instantiations.

Here is the complete routing tree. A basis member is part of the routing: it is handled by emitting no model.

exported inductive
├─ basis owner                                      → 11. Basis (exempt)
├─ block marked nested                              →  1. Nested
├─ non-nested block with several members            →  2. Mutual
└─ single, non-nested member
   ├─ never-Prop
   │  ├─ indexed                                     →  3. Carve
   │  ├─ unindexed, recursive, necessarily empty     →  8. Empty
   │  ├─ unindexed, recursive, branching/infinitary  →  4. Tree
   │  ├─ unindexed, nonrecursive singleton, storable → 10. Direct storage
   │  └─ otherwise                                   →  9. Tuple tower
   ├─ literal Prop
   │  ├─ recursive large-elimination singleton       →  5. Graph
   │  ├─ indexed nonrecursive large-elimination singleton
   │  │                                                →  6. Index recovery
   │  └─ otherwise                                   →  7. Church
   └─ sometimes-Prop
      ├─ indexed                                      →  3. Carve
      ├─ unindexed nonrecursive singleton with fields
      │  ├─ storable                                  → 10. Direct storage
      │  └─ otherwise                                 → unsupported
      ├─ unindexed, recursive, necessarily empty       →  8. Empty
      └─ otherwise                                    →  7. Church

Indices and recursion do not by themselves rule out Church: it carries both, which is why indexed recursive propositions normally end there. A recursive large-elimination singleton instead uses Graph, whose carrier is the same Church encoding but whose graph construction supplies the large recursor. Index recovery supplies the other large eliminator that plain Church cannot provide. Indexed sometimes-Prop families use Carve because, at a positive universe instantiation, their constructor data may have to be returned by a projection; a lifted Church proposition is a subsingleton and cannot retain that data. Never-Prop families cannot use that carrier for the same reason.

The leaves state ownership, not the maximum reach of each idea. A specialised route may also be chosen because it gives a simpler uniform account of its shape; for example, some proof-only unindexed singletons could use Church, but Direct handles the whole storable singleton class as ordinary field storage.

The entries below stay in topological order, from specialised source shapes toward the more general representations they depend on. Whenever a model splices an auxiliary inductive, that auxiliary resumes the walk at a later entry (or, for PProd', at a smaller use of entry 10). Thus the longest chain runs from nested to mutual to indexed to tree and eventually reaches the basis. With --basic on, an auxiliary that cannot be modelled causes the enclosing model to be withdrawn; if nothing declines, the basis is the only unmodelled inductive residue. Each entry below makes its representation, reason for existing, and dependencies explicit.

1. Nested declarations

Scope. A block the exporter marked nested — the recursion passes through another inductive type. Lean.Syntax is the everyday example, recursing through Array:

Lean.Syntax.node :
  Lean.SourceInfo → Lean.SyntaxNodeKind → Array Lean.Syntax → Lean.Syntax

Idea and reason. The model specialises the nesting away: a mutual block with one extra member per nested container occurrence — a copy of the container at the declaration, Array-of-Syntax as an inductive type of its own — plus a pack/unpack pair of conversions per copy with both round trips proved as theorems, and one recursor and ι rule per member. It removes the nesting and keeps the mutuality. Entry 2 alone would remove mutuality but would not make an occurrence such as Array Lean.Syntax available as a recursive member; specialisation is the step that does so.

Dependencies. That specialised mutual block, modelled by entry 2 — whose tag and family then continue down the list, through entries 3 and 9, an entry-3 skeleton through entry 4 where it branches, and entry 4's support library through entries 9, 7, 6 and 5. That chain — 1, 2, 3, 4, on down to the basis — is the longest descent in the list, and entry 11 is where it visibly ends.

2. Mutual blocks

Scope. A mutual block with no nesting. A single-member block is handled by entries 3–10, while any block marked nested is handled by entry 1. Members are read as the kernel reads them, as every owner is, so a block declared at a definition that unfolds to its sort, index telescope, or a later member's parameters is in scope; a block at a sometimes-Prop sort with a data projection its recursor cannot express is not (see What is covered, and what is not).

mutual
  inductive Even : Type where
    | zero : Even
    | succ : Odd → Even
  inductive Odd : Type where
    | succ : Even → Odd
end

Idea and reason. The model removes the mutuality: one tag type with one constructor per member, carrying that member's index values as fields; one auxiliary inductive family indexed by the tag; and one model type per member — Even becomes the auxiliary family at the Even tag. Constructors, recursors and ι rules are all read through that encoding, and every ι rule holds by Eq.refl. Merely renaming the original mutual block would preserve the very feature this route is meant to eliminate; the tag makes member selection an ordinary index instead.

Dependencies. The tag and the auxiliary family, two new inductives. The tag is a plain non-recursive type and models through entry 9; the family is indexed and re-enters the list — through entry 3 for a recursive Type-valued block like this one, or with the propositions through entry 7 for a Prop-valued one.

3. Indexed non-Prop families, carved out of an index-free skeleton (the carve arm)

Scope. Every indexed family whose result is not literally Prop: both never-Prop and sometimes-Prop sorts. The classic length-indexed vector is the picture:

inductive Vec (α : Type u) : Nat → Type u where
  | nil  : Vec α 0
  | cons : α → Vec α n → Vec α (n + 1)

Idea. Delete the index and Vec α becomes List α. The model splices that index-free declaration into the output as a real inductive — the skeleton — and pairs a skeleton value with evidence that it belongs at the requested index, with the right indices all the way down.

There are two ways to express that evidence. At a never-Prop sort, good is a predicate computed by the skeleton's large recursor. At a sometimes-Prop sort, the skeleton has only small elimination, so Good is instead a spliced inductive relation mirroring the source constructors; the source recursor is built by recursion on its proof. The large-elimination singleton is the one special implementation inside this route: erasing its indices would discard the fact that the kernel grants it large elimination, so entry 6 recovers its data directly from those indices.

Why this route. It removes indices once, before any later representation has to care about them, while retaining constructor data and recursive fibres. The relational form is not also used at a never-Prop sort: its Good : Prop recursor could eliminate only into Prop, whereas the source recursor may eliminate into an arbitrary Sort. There the skeleton's large recursor is the simple way to compute both goodness and recursion.

Dependencies. The skeleton, which re-enters this list and goes wherever its own shape sends it. In test/fixtures/inductive-models/prim_carve.lean, a Vec like the one above has a linear skeleton that models through entry 9 in 6 declarations, while Bif, whose constructors branch, sends its skeleton through entry 4 at 215 declarations — nearly all of them the support library, paid once per output. If the skeleton does not model, the model is withdrawn and the declaration declines: the closure rule from the introduction, doing its work. A relational Good is an ordinary proposition and re-enters at entry 7. The large singleton subcase uses entry 6.

4. Branching recursion at a never-Prop sort, as well-founded trees (the tree arm)

Scope. Non-indexed, recursive, never-Prop, with recursion that entry 9 cannot express — some constructor has two or more recursive fields, or a recursive field under a binder, except when entry 8 proves the owner empty. Lean.Expr is the household example (Expr.app : Expr → Expr → Expr — two recursive fields), and Lean.ParserDescr another.

Idea and reason. Entry 9's depth counter takes exactly one predecessor per step, so the model here is a tagged well-founded tree instead. Linear recursion stays with entry 9 because a depth-indexed storage spine is the simpler representation there: without a boxed field it uses no axiom and every ι rule is Eq.refl. Branching and infinitary recursion need the general tree, its support library, and theorem-proved ι rules; its models admit propext and Quot.sound — for some shapes also Classical.choice. A field, or a binder of a recursive field, that needs entry 9's box is boxed the same way here, and under the same rule: where nothing later mentions it, the recursor, the ι rules and a one-constructor declaration's projection rule use the box's round-trip lemmas instead of asking the kernel to confirm the round trip.

Levels. The tree is built at the declaration's own sort, whatever never-Prop level that is — including one with no predecessor, such as Sort (max 1 u) holding a field at Sort u, for which no Type ℓ would do. That is why the support library below is written with Sort-valued paths, labels and edges rather than List, Option and Sigma.

Dependencies. The support library (the source calls it the _wcore fragment) — a fixed export of the well-founded-tree toolkit, twenty inductive types (its own PList and POption, PSigma, Subtype, Bool, Acc, WellFounded, Or, HEq, …, mostly under a reserved _wcore name prefix) with the definitions and proofs over them — spliced once into the output. Every inductive in it re-enters this list and goes wherever its own shape sends it: _wcore.Subtype to entry 10, _wcore.WT.PList to entry 9, _wcore.Or to entry 7, _wcore.HEq to entry 6, _wcore.Acc to entry 5. The _wcore names are reserved. An input that already declares the library — this tool's own output fed back in — has it reused, but only if the constants the tree arm names state what this version's do; an input that declares a _wcore name otherwise, such as the output of an earlier version whose library was Type-valued, has the owner that needs the library declined with name taken.

5. Recursive subsingletons at Prop: recursion recovered from its graph (the graph arm)

Scope. One constructor, recursive, a literal Prop, granted large elimination by the kernel. Acc, the accessibility predicate under every well-founded recursion, is the occupant and the reason the entry exists: Acc sat in the basis precisely for that recursor, and this construction derives it instead, so Acc models like any other declaration.

Acc.intro : ∀ {α : Sort u} {r : α → α → Prop} (x : α),
              (∀ (y : α), r y x → Acc r y) → Acc r x

Idea and reason. The model type is entry 7's Church encoding; the recursor is defined by its graph — the relation "eliminating this proof yields this value" — and the value is extracted from an existence proof with Classical.choice, so the ι rule is a theorem rather than an Eq.refl. The construction asserts Classical.choice, and adds function extensionality — derived from Quot.sound and spliced as a theorem — when a recursive field sits under a binder, as Acc's does. It fires only at a literal Prop: a sometimes-Prop declaration is granted no large elimination by the kernel in the first place. Dependencies: Classical.choice; function extensionality derived from Quot.sound when needed; and Nonempty, the domain of Classical.choice, modelled by entry 7.

6. Large indexed propositions: recover constructor data from the indices

Scope. One constructor, no recursion, indexed, and granted large elimination at a literal Prop or sometimes-Prop sort. A literal Prop reaches this entry directly; a sometimes-Prop family reaches it as the large-singleton implementation of Carve. HEq.refl is the familiar zero-field example.

Idea and reason. The kernel grants the large eliminator only when every data field is literally one of the index arguments in the constructor's conclusion. The construction therefore reads those fields from the recursor's indices, keeps the proof fields in a Church conjunction, and records one equation over the remaining index positions. This preserves the kernel's large eliminator without asking an index-erased skeleton to inherit that special privilege. Dependencies: only the basis; no auxiliary inductive family is introduced.

7. Propositions, and the sometimes-Prop remainder (the Church encoding)

Scope. This is the complete construction for every proposition outside the specialised cases in entries 5 and 6, and for every unindexed sometimes-Prop shape no earlier entry takes. Entry 5 reuses its model type but supplies a different recursor; entry 3 also uses Church later to model its spliced Good relation. This coverage is why literal Prop has no unsupported recursive shape.

Idea. A declaration is modelled by what can be concluded from it: the model type of Or a b is ∀ C : Prop, (a → C) → (b → C) → C. This is the impredicative encoding from the universe note above; at a sometimes-Prop sort it travels under the lift. Indices are carried, and recursion is too — the encoding's fold is strengthened into an induction — so And, Exists, Iff, False and most propositions in a real export land here, as do indexed recursive propositions, Nonempty (which entry 5 relies on), and PEmpty, a sometimes-Prop declaration with no constructors. A Church-encoded value remembers that something was concluded, not what it was built from. That is fine for propositions, which are never asked to hand data back — and it is exactly why indexed nonliteral-Prop families use entry 3 and unindexed data-bearing singletons use entry 10 instead. Thus Church is used where proof irrelevance makes that loss harmless, not as the representation for data-bearing structures. Dependencies: only the basis; it introduces no auxiliary inductive.

8. Types with no elements (the empty arm)

Scope. Recursive, non-indexed, and every constructor has a bare recursive field — a field whose type is the declaration itself, not under a binder — so no constructor can ever be applied and the type has no elements:

inductive Loop : Type where
  | mk : Loop → Loop

Idea and reason. The class is not about linearity — a constructor with two bare recursive fields is exactly as unusable as one with one — and the construction serves never-Prop and sometimes-Prop sorts on the same terms; a Prop of this shape is just an unprovable proposition, which entry 7 already covers. The model type is an empty type at exactly the declared sort. Where the declaration has one constructor and its universes allow, the model type is instead entry 10's storage over the non-recursive fields, ending at that emptiness — still uninhabited, because of its tail, but genuinely storing everything in front of it, so the projections the output contract owes exist. Representing the type as empty avoids paying for either a linear spine or a well-founded tree when neither can contain a value. Dependencies: only the basis; it introduces no auxiliary inductive.

9. Unindexed never-Prop types with at most linear recursion (the tuple tower)

Scope. This is the construction for constructor choice and linear recursion: a non-indexed declaration at a never-Prop sort with two or more constructors — or none at all — whose recursion, if it recurses, is linear: each constructor has at most one recursive field, and that field is not under a binder. Bool, Option and List all land here (List.cons : α → List α → List α — one recursive field). A one-constructor declaration with no recursion is entry 10's, with two exceptions this entry keeps: one with no fields at all, and one with a field whose universe level retains an imax the plain storage cannot absorb — this tower boxes such a field, wrapping its exposed structure so the level normalizes, and entry 10 deliberately does not.

Idea. The model type is a PSigma' pair of a Nat and a payload. The Nat is the constructor tag, and the payload at tag j is constructor j's field storage — exactly as in entry 10, dependent chain, balanced tree and one-element filler included — and an empty type at every tag past the last constructor. For a recursive declaration an outer Nat additionally counts recursive depth: a constructor with a recursive field stores that field's value one depth down. The recursor reads the tags with Nat.rec building a type — the large elimination the basis buys — and then walks the storage. Without a boxed field the whole construction uses no axiom, and every one of its ι rules holds by Eq.refl. This direct depth-and-storage account is why linear declarations use this route rather than entry 4's more general well-founded trees.

A boxed field costs funext. Boxing a function field converts its argument one way and its result the other, recursively, and unboxing converts back. That the two round trips give back the original value is true by computation, but Lean's kernel can only confirm it by taking the function apart at every arrow of its type, once per arrow counted as a tree — so a field type with many shared subterms, small as written, can make that check astronomically large. The tower therefore never asks the kernel for it: each round trip is a proved lemma, built once per distinct part of the field's type from lemmas about its parts, and those lemmas use function extensionality, funext, which comes from Quot.sound. Where a boxed field is one no later field mentions, the recursor transports the minor's result along that lemma, the ι rule is a theorem that uses it, and so does the projection rule of a one-constructor declaration. A boxed field that a later field's type does mention is still converted by the kernel: the later field's type is stated at the unboxed value, and that is a question only conversion answers. A run names every declaration whose model states a round trip as a lemma, on a boxed round trips proved stderr line; over Mathlib that is Coe, CoeFun, CoeHead, CoeHTC, CoeHTCT, CoeOTC, CoeOut, CoeSort, CoeTail, CoeTC, DFunLike, Equiv, EquivLike, Function.Embedding, Lean.Data.AC.EvalInformation, Plausible.SampleableExt and Trans.

Dependencies. PProd' for the balanced trees, modelled by entry 10. Basis members the input does not declare are spliced in at Lean's own shape and reported on prelude spliced lines, unmodelled under entry 11's exemption.

10. Unindexed structures outside Prop: field storage (the direct route)

Scope. One constructor with at least one field, no recursion, at any sort that is not a literal Prop — never-Prop and sometimes-Prop alike — and no indices. This is the everyday structure: Prod, Fin n, Subtype, Sigma and PSigma all land here. A literal Prop of this shape stays with the propositions, because a Prop owner is asked for no data projections and there is nothing here for storage to retain.

Idea. The model type stores the constructor's fields, and every part of the storage is level-generic — which is why the entry is not confined to either end of the sort distinction above. A single field whose universe is already the declared one is stored as itself: the model type is the field's type. A single field that is a proposition is stored under the lift. Any other field list is split in two: the fields that some later field's type mentions form a right-nested chain of PSigma' pairs, and the rest are gathered below it into a balanced tree of PProd' pairs, ended by a trivial one-element component wherever the fields' own universes do not add up to exactly the declared sort — that filler is a PSigma'.{0,w}, at Sort (max 0 w) = Sort w for a never-Prop w exactly as for a sometimes-Prop one. The two single-field answers are checked before the split on purpose, so that their model types stay the field itself and the bare lift rather than a pair around either. A never-Prop structure used to take entry 9's tuple instead, paying a constructor tag that a one-constructor declaration can only ever set to 0, along with the Nat splice behind it; the storage here is the same chain with none of that.

Boundary. Two never-Prop corners use another route rather than decline: a constructor with no fields has nothing to store, and a field whose universe level retains an imax can miss the declared sort in a way that only entry 9's boxing — a wrapper this plain storage does not use — absorbs. Either way the declaration goes to entry 9. At a sometimes-Prop sort there is no alternate box; a field level that misses the sort there is the decline this list's last section describes.

Typical sometimes-Prop input. The sometimes-Prop occupants deserve a word on where they come from. Ordinary inductive syntax refuses a result sort that is only sometimes Prop (core itself declares PUnit and PEmpty under a bootstrap option that lifts the refusal), so they enter from raw exports and, mostly, from this tool's own splices. The typical one is PProd', a pair whose two component types are independent of each other, which the storage above leans on:

PProd'    : {α : Sort u} → (β : Sort v) → Sort (max u v)
PProd'.mk : {α : Sort u} → {β : Sort v} → α → β → PProd' α β

(Lean's own PProd is a structure, so it lands at Sort (max 1 u v); the primed pair drops the 1 exactly as PSigma' does — and PProd itself, being never-Prop, is stored by this same entry.)

Dependencies. The route uses the basis and introduces PProd' whenever the balanced tree is used. It is then modelled by this same entry — necessarily as a plain PSigma' chain, since storing its own two independent fields the normal way would use a PProd'.

11. The basis: five types that are never modelled

Scope and role. Eq, PSigma', Nat and PUnit are what every model is written in, and Quot — the kernel's quotient bundle Quot, Quot.mk, Quot.lift, Quot.ind — stands beside them. No other owner is exempt.

Why a basis. These five are the trusted basis from the Idea section above, and their "construction" is that nothing is built: a model of a basis member would have to be built out of that member. A run leaves all five unmodelled. A basis member the input declares is reported on an exempt line of its own (Nat: exempt — …) and counted in a row of its own, outside the decline count; one the input does not declare is written into the output at Lean's own shape at the first point a construction needs it, and named on that declaration's prelude spliced line.

What the constructions rely on. PSigma' is Lean's dependent pair PSigma with the built-in universe 1 removed from its result sort — {α : Sort u} → (α → Sort v) → Sort (max u v) — so that it can pair propositions without leaving Prop. Membership is need, not principle: Acc was once a fifth inductive member, kept only for the recursor the kernel grants it, and entry 5, which derives that recursor instead, is how it stopped being one.

Two presentation adapters

Above the constructions sit two presentation adapters. They change what the public interface looks like, never how a shape is represented, and both exist so that intrinsic projections select their fields literally.

The indexed-fibre adapter applies to a safe, single-member, one-constructor, indexed, never-Prop family with a non-K recursor, whose recursive occurrences, if any, are direct and do not affect the result indices or later field types. It publishes aliases over the family's existing model — entry 3's carve — with identity roll/unroll conversions. It is not a new representation and it does not apply to unindexed owners, mutual blocks or Prop/sometimes-Prop families.

The mutual one-layer adapter applies to a safe, recursive, unindexed, never-Prop mutual strongly connected component whose recursive fields are direct and independent of later fields, and where at least one member has one constructor, a recursive field, and no field that needs entry 9's box. It publishes one simultaneous family over entry 2's tag-and-family encoding; the qualifying one-constructor members expose a constructor layer, while the others remain aliases of their private carriers. A member with a boxed field is not a qualifying one: the layer's conversions and ι rules hold by Eq.refl, which a box's round trip would make the kernel confirm at the cost of the field type's tree. Entry 2's own models box that field with the round-trip lemmas instead. Mutual blocks outside that scope still use entry 2, just without this presentation layer.

There is no adapter for a one-constructor recursive unindexed declaration. One was built and withdrawn after measurement: entries 9 and 4 already publish such a declaration's model type, constructor, recursor, ι rules and intrinsic projections at the exact source syntax, with literal projection ι rules — so a private fixed point with a wrapped layer over it bought nothing, and cost one transport along Eq.rec per recursive field in every ι rule it published.

What is covered, and what is not

The tool models every inductive declaration it can. When it cannot, it declines the declaration: the original passes through to the output unchanged, a stderr line names the declaration and the reason, and the run finishes with exit code 2 instead of 0. A decline is not a failure — every other declaration in the export is still modelled and checked — it is the run saying, precisely, that this one declaration gets no model.

Run over this repository's entire fixture corpus, the tool declines exactly four declarations as unsupported, in three fixture files. Three of them fall into the first situation below and the fourth into the second; each is shown shrunk to a minimal declaration that still declines. That is a count of what this corpus contains, not a bound on what other inputs may hit. Three further behaviours are not declines but are still user-visible: one shares its cause with the first situation and is described inside the same entry, one stops the run without a verdict, and the last closes the list.

What you can hit What the run does
a field whose universe level has an imax the declared universe only bounds declines that declaration
a mutual block at a sometimes-Prop sort with a one-constructor member that has a data field declines that declaration
an inductive whose type reaches its sort only by K, structure η or Nat arithmetic stops with exit 3
a universe equality Lean's kernel cannot check models it, and reports every such use
a Prop-valued structure-like carrying data fields models it, but silently omits some or all projections

unsafe inductives are exempt, not declined. Lean's kernel admits an unsafe inductive without its positivity check and forbids every safe declaration from naming one, so such a block is outside the logic the models are for: nothing safe that a consumer translates can depend on it, and a safe model of a negative one — unsafe inductive Bad | mk : (Bad → Nat) → Bad — would prove False. The tool passes the block through unchanged and reports it on an exempt line, as it reports the basis, and the run still exits 0. Lean Kernel Arena replay skips these records the same way.

Declined or reported: types whose models need a better level comparison than the kernel has

Everything in this entry — two shapes that decline, and one reported behaviour — is a single fact met three times: Lean's kernel compares universe levels by normal form alone, and that comparison is incomplete. When Lean admits an inductive, it can check that a field's level fits under the declared universe with an ordering test. A model has no ordering test to appeal to: it is built from ordinary definitions, the universe of a definition is computed from the levels of what it stores, and the result has to be definitionally equal to the declared level. Two levels can be equal at every instantiation while their normal forms differ — and then the kernel cannot see it, and the model cannot exist.

The wall itself.

universe u v

inductive Fun (α : Sort u) (β : Sort v) : Sort (max u v) where
  | mk : (α → β) → Fun α β

The field α → β lives at Sort (imax u v) — imax, because a function into a proposition is itself a proposition. Lean's kernel admits the declaration through its ordering test: imax u v ≤ max u v holds at every instantiation, so the field fits under the declared universe. The model must build an actual type that holds the constructor's fields, the universe of that type is computed from the field levels, and the result — a max with imax u v inside — would have to be definitionally equal to max u v. It is not: max (imax u v) (max u v) does not normalize to max u v, and no packaging of the field escapes this — a wrapper that removed the imax would raise the type's level floor above Prop, and Sort (max u v) can be Prop. So the tool declines the declaration. Lean's level normalizer is known to be incomplete around turning an imax into a max; leanprover/lean4#12747 records a related instance.

Ordinary Lean does not produce this shape: the inductive command refuses a resulting universe that is only sometimes Prop, so declaring Fun takes a bootstrap option (set_option bootstrap.inductiveCheckResultingUniverse false) or a raw kernel export. PadImax and PadImaxIdx in test/fixtures/inductive-models/prim_shape_declines.lean are the corpus's two instances.

The same wall, met at a dependent field.

universe u v

def Opaque := Sort (imax u v)

inductive E (α : Opaque.{u, v}) : Type (max 1 u v) where
  | mk (x : α) (f : α → Nat) (h : Eq (f x) Nat.zero) (rest : E α) : E α

The model of a one-constructor inductive carries a projection for each field, and for each projection a rule stating that on a constructor application it returns exactly that field. The type of h names the earlier fields x and f, so the two sides of h's rule only have the same type if the projections for x and f compute — actually reduce to those fields on E.mk x f h rest. Here they cannot. Every constructor of E requires an existing E, so the type is empty, and the model's carrier is an empty type whose projections are total by elimination rather than by selecting a stored field; storing x, whose type sits at Sort (imax u v), inside a carrier at Type (max 1 u v) runs into exactly the wall above. With no well-typed way even to state the rule for h, the tool declines the declaration — naming the field — rather than emit a model with a projection rule missing.

It is the level that declines here, not the dependency: EOpaque, the corpus's one instance, sits in test/fixtures/inductive-models/e_dependent_field.lean beside six variations that drop either the imax parameter or the dependency, and every one of those models. As the snippet shows, the trigger is legal Lean, but the Sort (imax u v) must be written by hand; ordinary code does not produce it.

Reported: when the tool's comparison outruns the kernel's. The tool plans universe levels with a complete decision procedure for Lean's level algebra — it decides the equalities the kernel's normal-form test misses, including the one both declines above run into. That strength cannot rescue them, deliberately: their level equation is one the kernel itself re-checks when it verifies the generated definitions, so accepting a plan the kernel refuses would not widen coverage, it would only turn a visible decline into a kernel rejection of the model. Where the comparison is the tool's own to make, the complete procedure is used, in one direction only: to accept a model that the elaborator's standard comparison would have forced it to decline. A model accepted this way may fail to verify under the stock kernel. Such a model is not wrong — it is correct under a complete theory of levels, and a checker with one accepts it — but the tool never lets it pass silently:

  • --type-check-generated (on by default) kernel-checks every generated declaration, so such a model surfaces as a reported rejection rather than a quiet difference;
  • when a plan needs the complete procedure, a level widening: stderr line names the declaration concerned;
  • every run prints levels: N planner comparisons, M escapes on stderr, where M counts the comparisons only the complete procedure accepted — M is 0 across the whole fixture corpus;
  • the Mathlib gate (scripts/check-mathlib-result.sh) requires M = 0, the condition under which this widening was accepted.

This entry is that one incompleteness and nothing else: a kernel with a complete level comparison would leave the two declines above without their reason, and no widening to report.

Declined: a projection onto data that the recursor cannot express

universe u

mutual
  inductive NC : Sort u where
    | mk : ND → NC
  inductive ND : Sort u where
    | nil : ND
    | cons : NC → ND
end

Lean's kernel grants two eliminations here by two different rules, and they disagree. The recursors eliminate only into Prop: a mutual block at a sort that may be Prop never gets a large eliminator. The projection Expr.proj NC 0, however, is refused only when the owner's sort is literally Prop, and Sort u is not — so the kernel admits NC.0 : NC → ND, which at every u ≥ 1 returns data. A model has to supply that projection, and every model here reads a field by eliminating the owner with its recursor, whose statement is fixed by the owner's own: a Prop-only recursor cannot return an ND. The mutual encoding (entry 2) has no other eliminator to offer — its carriers are one auxiliary family with several constructors at the same sometimes-Prop sort — so the tool declines the block, naming the field. The simple construction serves many single-member owners in the same position — its direct and empty arms store the field rather than eliminate for it — but not every one; no mutual route does.

This is the same fact as the next entry, seen from the other side (leanprover/lean4#7637). Ordinary Lean does not produce it: the inductive command refuses a resulting universe that is only sometimes Prop. NC in test/fixtures/inductive-models/mutual_kernel_sorts.lean is the corpus's instance.

Stopped: a type former the checker cannot read as the kernel does

inductive XK (h : (0 : Nat) = 0) :
    @Eq.rec Nat 0 (fun _ _ => Type 1) (Nat → Type) 0 h where
  | mk : Nat → XK h 0

Lean's kernel reads an inductive's parameters, indices and sort by weak-head normalising its type, so a type may be computed: behind a definition, a match, a casesOn, a projection of a structure literal. The constructions read owners with the kernel's own whnf. The structural checker restates each owner's telescope with its own reading, because it is a pure function of the export text and not a second kernel. That reading unfolds definitions and β/ζ-reduces, and takes an ι or projection step only on a literal constructor application: T.rec … (C a⃗) steps to C's rule exactly as the export states T.rec's rules, and (C a⃗).i to the field. A Nat literal counts as Nat.zero/Nat.succ, as it does in the kernel. So def pick : Bool → Type 1 | true => Nat → Type | false => Type and inductive XM : pick true is read as the kernel reads it, an indexed family with one index, and is modelled and verified like any other owner; test/fixtures/inductive-models/defhead_beyond_delta.lean holds that and ten more: casesOn, a projection, nested ι, Nat literals, computed indices and sorts, a structure and a mutual block.

The reading deliberately stops short of the kernel in three places:

  • K. XK above: Eq.rec reduces in the kernel on any proof of 0 = 0, including the variable h, by replacing it with Eq.refl 0. To the checker the recursor is stuck on a variable.
  • Structure η. PUnit.rec … u on a variable u reduces in the kernel by expanding u to PUnit.unit. To the checker it is stuck.
  • Proof irrelevance, quotients, and Nat/String literal arithmetic. The kernel evaluates 1 + 1 on literals natively to 2; the checker's reading reaches the same number through Nat.add's definition, but not as the same expression.

And it never steps through the recursors or constructors of the owner's own block: those rules are what the checker validates models against, so they must not also decide what it compares. A well-scoped type cannot mention its own block, so this excludes nothing Lean accepts. The rules it does use belong to earlier inductives, and are the kernel's own wherever the input is kernel checked: --type-check-input requires every exported recursor's rules to equal the ones Lean's kernel mints for its block.

These three are where the published kernel exploits live: the Kernel Arena's bad/bugs/* cases that compute an owner's sort do it on a stuck term, which this reading never reduces, and every one of the Arena's bad cases ends the same way with and without the ι and projection steps, with the input kernel check and without it. Every reading is also bounded: one that takes more than 100,000 reduction steps is abandoned.

Where the checker's reading does not reach a sort, runs out of steps, or reaches a different former from the kernel's — the driver compares the two on every owner it models, before any construction — the run stops with exit 3 and a line naming the member. That is not a decline, which would call the input valid and merely unmodelled: the claim would rest on Lean's kernel alone, because the checker cannot restate the owner, and this shape is where a specific, since-fixed kernel bug lived. Up to Lean v4.33.0, the kernel's is_prop answered "not a proposition" for a type whose sort was stuck, so data could be taken out of a proof, and the Arena's bad/bugs/proj-of-stuck-prop, proj-of-subst-prop and rec-of-subst-prop prove False with it. It was fixed by leanprover/lean4#14807; the first of the three also relies on the order-dependent definitional-equality cache that #14806 replaced. Both are in Lean v4.34.0 and later, and on this repository's toolchain --type-check-input rejects all three (exit 1) before this check runs. The elaborator writes these shapes only when a type is written with a recursor application on a variable, or with arithmetic; test/fixtures/unverifiable/ holds one of each (iota_needs_k, iota_needs_eta, iota_nat_arith).

Silent: a Prop-valued structure-like with data fields loses projections

universe u

inductive P : Prop where
  | mk (data : PUnit.{u}) (proof : True) : P

This declaration models and the run exits 0, but the model contains only P._model.proj_1, for proof. There is no P._model.proj_0 for data, and nothing on stderr says so.

The reason is the kernel's own rule for projecting out of a proposition: to keep data from escaping a proof, Lean allows a projection (Expr.proj) on a Prop-valued structure-like only where the projected field — and every earlier field its type can still see — is itself a proof. That test depends on the universe instantiation: PUnit.{u} is a proposition at u = 0 and a data type at every other u. The model is generated once, for the polymorphic declaration, so it can only carry the projections that are sound at every instantiation.

Lean tracks this as leanprover/lean4#7637: primitive projections are not conservative over recursors, so a projection the kernel admits at one instantiation can be inexpressible by the recursor — which is what a model has to go through.

The consequence for a consumer: the input may contain a raw Expr.proj that is perfectly well typed at its own instantiation — say at u := 0 — yet has no _model.proj_j counterpart, and the consumer must inline the elimination itself. Structures from ordinary Lean source never hit this, because the structure command refuses a Prop-valued structure with a data field ("field must be a proof"); it takes a raw kernel declaration. The published Lean Kernel Arena has two, good/tutorial/087 and good/tutorial/089: Prop structure-likes whose models correctly contain no projections at all, and which the Arena requires to be accepted — so declining them is not an option. In 087, even a field that is a proposition at every instantiation (an Eq) gets no projection, because its type names an earlier data field. A structure-like whose fields are all proofs at every instantiation keeps every projection.

Copyright and license

This project is licensed under the Apache License, Version 2.0 (Apache-2.0). Copyright information is in NOTICE.

About

No description, website, or topics provided.

Resources

Stars

7 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages