pub struct Context { /* private fields */ }Expand description
Typing context: maps variable names to their types.
The context is immutable-by-default: extend creates a new context
with the additional binding, preserving the original.
Also stores global definitions:
- Inductive types (e.g., Nat : Type 0)
- Constructors (e.g., Zero : Nat, Succ : Nat -> Nat)
- Declarations (e.g., hypotheses like h1 : P -> Q)
Implementations§
Source§impl Context
impl Context
Sourcepub fn shadows(&self) -> &[(String, String)]
pub fn shadows(&self) -> &[(String, String)]
The shadow table, as (written name, identity) pairs, in the order the written names were
first shadowed.
Sourcepub fn shadow_of(&self, written: &str) -> Option<String>
pub fn shadow_of(&self, written: &str) -> Option<String>
The identity the written absolute name written denotes, when a shadow redirects it: the
table’s own entry, or — for a constant DERIVED from a shadowing declaration (a recursor, an
equation lemma, a structure’s constructor or projection) — that constant, whose key spells
the identity where the written name spells the name: B2_rec reaches B2✝⟨1⟩_rec exactly
when B2 reaches B2✝⟨1⟩.
Sourcepub fn shadow_origin(&self, identity: &str) -> Option<&str>
pub fn shadow_origin(&self, identity: &str) -> Option<&str>
The written name a minted identity was minted for; None for every key no shadow minted.
Sourcepub fn shadow_root(&self, key: &str) -> Option<String>
pub fn shadow_root(&self, key: &str) -> Option<String>
The minted identity key IS, or is DERIVED from (a recursor, an equation lemma, a
structure’s constructor or projection, spelled with the identity inside its own key).
None for every key no shadow minted or derived from.
Sourcepub fn is_live_shadow(&self, identity: &str) -> bool
pub fn is_live_shadow(&self, identity: &str) -> bool
Whether the minted identity identity is the one its written name denotes NOW — false
once a later declaration of that name has been shadowed in over it.
Sourcepub fn spelled_by(&self, key: &str) -> Option<String>
pub fn spelled_by(&self, key: &str) -> Option<String>
The written absolute name that reaches key through a shadow, live or not: the name an
identity was minted for, or — for a constant derived from an identity — its key with that
name in the identity’s place. None for a key no shadow minted or derived from.
Sourcepub fn written_name(&self, key: &str) -> String
pub fn written_name(&self, key: &str) -> String
How key is WRITTEN here, for output that must read as source. A live identity is written
as the name it was minted for; an identity whose name has since been shadowed again is
written as that name marked inaccessible (add✝), the way Lean prints an inaccessible name;
a constant derived from an identity is written with the identity’s spelling in its place;
and a declaration a shadow hides is written with the _root_ escape, which still reaches
it. Every other key is written as itself.
Sourcepub fn register_struct_info(&mut self, name: &str, info: StructInfo)
pub fn register_struct_info(&mut self, name: &str, info: StructInfo)
Record structure metadata supplied by a caller. Registering StructInfo grants structure
η, so this door grants it only when Context::register_structure_checked’s decision does:
the named projections must be name’s projections, and info’s constructor and parameter
count must be the ones that decision found. The caller’s descriptive metadata (field and
parameter names, parents, output parameters) is kept. A refusal registers nothing and is
recorded in Context::refused_declarations, as every unchecked door records one.
Sourcepub fn struct_info(&self, name: &str) -> Option<&StructInfo>
pub fn struct_info(&self, name: &str) -> Option<&StructInfo>
The structure metadata for an inductive type name, if it is a registered
structure (record). None for ordinary inductives — eta never fires for them.
Sourcepub fn out_params(&self, name: &str) -> &[usize]
pub fn out_params(&self, name: &str) -> &[usize]
The parameter positions of the class name that are OUTPUTS — Lean’s outParam.
An output takes no part in instance MATCHING: the instance determines it, and a
mismatch against what the surrounding context expected is an ordinary type error at
the use site rather than a different instance. Empty for anything that is not a
registered structure.
Sourcepub fn set_out_params(&mut self, name: &str, positions: Vec<usize>)
pub fn set_out_params(&mut self, name: &str, positions: Vec<usize>)
Declare the class name’s output parameter positions explicitly, replacing the ones
Context::add_structure inferred. The inference is a default for classes declared
without annotation; this is the channel a translator uses to carry Lean’s outParam
across exactly.
Sourcepub fn parent_edge_target(&self, name: &str) -> Option<&str>
pub fn parent_edge_target(&self, name: &str) -> Option<&str>
If name is a derived parent-forget edge ({Child}_to{Parent}, generated by
Context::add_structure from a flattened field prefix), the parent class it forgets
to. Instance resolution uses this to tell a HIERARCHY route apart from an ordinary
overlapping instance: two routes to one parent that disagree are an incoherent diamond,
where two direct instances are merely overlap.
Sourcepub fn struct_of_constructor(&self, ctor: &str) -> Option<(&str, &StructInfo)>
pub fn struct_of_constructor(&self, ctor: &str) -> Option<(&str, &StructInfo)>
If ctor is the constructor of a registered structure, return (structure name, its info). Used to detect an η-expandable constructor head.
Sourcepub fn set_implicit_args(&mut self, name: &str, count: usize)
pub fn set_implicit_args(&mut self, name: &str, count: usize)
Record that the global name has count leading implicit parameters, so the
surface elaborator inserts that many inferred arguments at each application.
Sourcepub fn implicit_args(&self, name: &str) -> usize
pub fn implicit_args(&self, name: &str) -> usize
How many leading parameters of name are implicit (0 if none/unknown).
Sourcepub fn add_instance(&mut self, ty: Term, value: Term)
pub fn add_instance(&mut self, ty: Term, value: Term)
Register a typeclass instance: a value of type ty (e.g. mk Nat Zero of type
Inhabited Nat). The elaborator resolves an instance-implicit argument by
searching these for a ty that unifies with the required class type.
Registered at DEFAULT_INSTANCE_PRIORITY — Lean’s instance with no
(priority := …). Use Context::add_instance_with_priority to say otherwise.
Sourcepub fn add_instance_with_priority(
&mut self,
ty: Term,
value: Term,
priority: i64,
)
pub fn add_instance_with_priority( &mut self, ty: Term, value: Term, priority: i64, )
Register a typeclass instance at an explicit PRIORITY — Lean’s
instance (priority := n) …. Higher wins; ties go to the LATER declaration.
Sourcepub fn add_local_instance(&mut self, ty: Term, value: Term)
pub fn add_local_instance(&mut self, ty: Term, value: Term)
Register a local instance — Lean’s local instance, and the thing the flat push-only
Vec could not express: it wins for as long as the enclosing scope is open and LEAVES the
database at Context::pop_scope.
Registered OUTSIDE any open scope this is an ordinary permanent instance, because that is
what local means at file level in Lean: there is no end to revert it.
Sourcepub fn add_local_instance_with_priority(
&mut self,
ty: Term,
value: Term,
priority: i64,
)
pub fn add_local_instance_with_priority( &mut self, ty: Term, value: Term, priority: i64, )
Context::add_local_instance at an explicit priority.
Sourcepub fn push_scope(&mut self) -> usize
pub fn push_scope(&mut self) -> usize
Open a SCOPE — Lean’s section/namespace. Everything registered local inside it is
reverted by the matching Context::pop_scope; everything else is permanent.
THE INVARIANT, stated once so no future scoped thing can get it wrong: a scope reverts
the four ATTRIBUTE DATABASES — instances, coercions, simp rules, hints — and NEVER a
declaration. A def written inside a section survives its end, which is why
snapshotting and restoring the whole context is not a scoping mechanism: it would delete
the section’s real content along with its attributes.
Returns the new depth, so a caller can assert its own nesting.
Sourcepub fn pop_scope(&mut self)
pub fn pop_scope(&mut self)
Close the innermost scope — Lean’s end. Every local registration made at this depth
leaves the database it was in; declarations made inside are untouched.
A pop_scope with no scope open is a no-op rather than a panic: an unbalanced end is a
surface-syntax error, and the kernel’s job is to stay consistent, not to be the diagnostic.
Sourcepub fn scope_depth(&self) -> usize
pub fn scope_depth(&self) -> usize
How many scopes are open (0 = the permanent scope).
Sourcepub fn add_fallback_instance(&mut self, ty: Term, value: Term)
pub fn add_fallback_instance(&mut self, ty: Term, value: Term)
Register a FALLBACK instance — one consulted only after every ordinary instance has
failed to resolve the goal. This is the tier for library-shipped and DERIVED instances
(decEq{I}, Inhabited Nat): they must be findable, but a user instance for the same
goal must always outrank them, and they must not appear in Context::instances, which
is the faithful record of what was explicitly declared.
Better than Lean in one respect: Lean expresses this with a numeric priority that a user instance can accidentally undercut. A separate tier cannot be undercut at all.
Sourcepub fn fallback_instances(&self) -> &[(Term, Term)]
pub fn fallback_instances(&self) -> &[(Term, Term)]
All registered FALLBACK instances, as (type, value) pairs — the lower tier, searched
only once Context::instances has been exhausted.
Sourcepub fn instance_priority(&self, i: usize) -> i64
pub fn instance_priority(&self, i: usize) -> i64
The priority of the instance registered at index i (Lean’s default, 1000, for an
instance registered before priorities existed or through Context::add_instance).
Sourcepub fn instance_search_order(&self) -> Vec<usize>
pub fn instance_search_order(&self) -> Vec<usize>
The order instance resolution must scan Context::instances in — LEAN’S RULE, stated
once, here, so no scan site can invent its own:
higher PRIORITY first; among equal priorities, the LATER declaration first.
Earliest-first — what a linear 0..n scan gives — inverts every tie-break a Lean source
relies on, silently: both readings type-check and compute different answers.
Returned as indices into instances() so a caller can report WHICH entry won and why.
Sourcepub fn instance_search_order_for(&self, goal: &Term) -> (Vec<usize>, usize)
pub fn instance_search_order_for(&self, goal: &Term) -> (Vec<usize>, usize)
Context::instance_search_order restricted to the candidates that could answer goal —
Lean’s getUnify against the discrimination tree (Lean/Meta/SynthInstance.lean:210),
in the same order the unrestricted scan would have visited them.
THE INVARIANT, and it is the only one that matters: this is a SUBSET of
instance_search_order() containing every entry that could possibly unify, in the same
relative order. So it changes what a search PAYS, never what it ANSWERS — and
S_spine_extra::the_index_keeps_every_open_candidate_visible_and_the_order_unchanged
holds it to both halves.
Returns (candidates, pruned), where pruned is how many entries the index excluded
without a unification attempt. Lean’s tree throws that number away; reporting it is what
makes “why did this instance not fire?” answerable.
Sourcepub fn add_coercion(&mut self, from: Term, to: Term, coe: Term)
pub fn add_coercion(&mut self, from: Term, to: Term, coe: Term)
Register a coercion coe : from → to — the elaborator may insert it when an
argument of type from appears where to is expected.
Sourcepub fn add_local_coercion(&mut self, from: Term, to: Term, coe: Term)
pub fn add_local_coercion(&mut self, from: Term, to: Term, coe: Term)
A local coercion — reverted at Context::pop_scope. See Context::push_scope.
Sourcepub fn coercions(&self) -> &[(Term, Term, Term)]
pub fn coercions(&self) -> &[(Term, Term, Term)]
All registered coercions, as (from, to, coe) triples.
Sourcepub fn set_binder_kinds(&mut self, name: &str, kinds: Vec<ParamKind>)
pub fn set_binder_kinds(&mut self, name: &str, kinds: Vec<ParamKind>)
Record a global’s per-parameter kinds (implicit/explicit/instance, in order), so the elaborator can insert implicit and instance arguments at their real positions.
Sourcepub fn binder_kinds(&self, name: &str) -> Option<&[ParamKind]>
pub fn binder_kinds(&self, name: &str) -> Option<&[ParamKind]>
A global’s per-parameter kinds, if recorded.
Sourcepub fn set_param_defaults(
&mut self,
name: &str,
defaults: Vec<(String, Option<Term>)>,
)
pub fn set_param_defaults( &mut self, name: &str, defaults: Vec<(String, Option<Term>)>, )
Record a global’s per-parameter NAME and DEFAULT VALUE, in telescope order — the surface
information a Term::Pi has nowhere to put.
One entry per position, None where the parameter has no default. The declaration door
must name its anonymous binders (TermParser::name_anonymous_binders) BEFORE it records,
or a default that mentions an earlier parameter has no name to be closed over and the
elaborator would inline an open term.
Sourcepub fn param_defaults(&self, name: &str) -> Option<&[(String, Option<Term>)]>
pub fn param_defaults(&self, name: &str) -> Option<&[(String, Option<Term>)]>
A global’s per-parameter names and defaults, if recorded.
Sourcepub fn instances(&self) -> &[(Term, Term)]
pub fn instances(&self) -> &[(Term, Term)]
All registered typeclass instances, as (type, value) pairs, in DECLARATION order.
This is the record of what was explicitly declared, not the order resolution scans —
see Context::instance_search_order for that, and Context::fallback_instances
for the lower tier.
Sourcepub fn add_universe_poly(
&mut self,
name: &str,
params: Vec<String>,
ty: Term,
body: Term,
)
pub fn add_universe_poly( &mut self, name: &str, params: Vec<String>, ty: Term, body: Term, )
Register a universe-polymorphic definition name.{params} : ty := body. A
Term::Const { name, levels } reference later instantiates params with levels
(the .{ℓ…} syntax), so one definition is reused at every level.
Sourcepub fn declare_universe_poly(
&mut self,
name: &str,
params: Vec<String>,
ty: Term,
body: Term,
) -> KernelResult<()>
pub fn declare_universe_poly( &mut self, name: &str, params: Vec<String>, ty: Term, body: Term, ) -> KernelResult<()>
Check and register a definition with an explicit universe parameter telescope.
Sourcepub fn get_universe_poly(
&self,
name: &str,
) -> Option<&(Vec<String>, Term, Term)>
pub fn get_universe_poly( &self, name: &str, ) -> Option<&(Vec<String>, Term, Term)>
Look up a universe-polymorphic definition: (universe params, type, body).
Sourcepub fn add_universe_poly_inductive(
&mut self,
name: &str,
params: Vec<String>,
arity: Term,
num_params: usize,
)
pub fn add_universe_poly_inductive( &mut self, name: &str, params: Vec<String>, arity: Term, num_params: usize, )
Declare a UNIVERSE-POLYMORPHIC INDUCTIVE: name.{params…} : arity, where arity may
mention the level variables in params.
The ordinary inductive registry is populated too, at the same arity, so is_inductive,
get_constructors, the params/indices split and every Term::Global reference behave
exactly as they do for a monomorphic declaration. What this adds is the LEVEL TELESCOPE, so
a reference that writes its levels — Const { name, levels } — can be resolved and
instantiated instead of being reported as an unbound name.
★ ONE LINE MAKES IT VISIBLE TO TYPING, and it is the same line in both kernels:
type_checker::lookup_const and recheck’s Db::Const arm each read
Context::get_universe_poly and must read Context::poly_declaration instead — one
lookup that answers for a polymorphic DEFINITION and a polymorphic TYPE alike, so the two
kernels cannot come to disagree about which constants carry a level telescope. Reduction
must keep reading get_universe_poly: a type former has no body and must stay inert.
Sourcepub fn poly_declaration(&self, name: &str) -> Option<(&[String], &Term)>
pub fn poly_declaration(&self, name: &str) -> Option<(&[String], &Term)>
A name’s LEVEL TELESCOPE and the type it stands at — for a polymorphic type declaration or a polymorphic definition alike, in that order.
The ordering is the same one Context::get_global uses (a header outranks a body), and
it matters for exactly one case: a name re-declared from a definition into an inductive
must resolve as the inductive, or typing would read a level telescope the reducer no
longer has a body for.
Sourcepub fn is_universe_poly_inductive(&self, name: &str) -> bool
pub fn is_universe_poly_inductive(&self, name: &str) -> bool
Is name a universe-polymorphic TYPE declaration — one with a level telescope and no body?
Sourcepub fn add(&mut self, name: &str, ty: Term)
pub fn add(&mut self, name: &str, ty: Term)
Add a local binding to this context (mutates in place).
Sourcepub fn extend(&self, name: &str, ty: Term) -> Context
pub fn extend(&self, name: &str, ty: Term) -> Context
Create a new context extended with an additional local binding.
Does not mutate the original context.
Sourcepub fn add_inductive(&mut self, name: &str, sort: Term)
pub fn add_inductive(&mut self, name: &str, sort: Term)
Register an inductive type.
The sort is the type of the inductive (e.g., Type 0 for Nat).
All of the arity is treated as uniform parameters (0 indices) unless
set_inductive_params records a smaller parameter
count — see add_indexed_inductive.
Sourcepub fn declare_inductive(&mut self, name: &str, sort: Term) -> KernelResult<()>
pub fn declare_inductive(&mut self, name: &str, sort: Term) -> KernelResult<()>
Context::add_inductive answering instead of recording: the header is registered, kept
(the identical header something depends on is not a change), or refused with the reason.
Sourcepub fn is_derived_aux(&self, name: &str) -> bool
pub fn is_derived_aux(&self, name: &str) -> bool
Is name a constant THIS context auto-derived ({I}_rec, {I}_noConfusion, decEq{I}, …)
rather than one a human wrote?
The distinction is what lets declaration-time synthesis be idempotent: re-deriving must REPLACE its own prior generation — an inductive is incomplete until its last constructor, so the auxiliaries derived after the first one describe a different type — while never touching a hand-written constant of the same name.
Sourcepub fn derived_aux_names(&self, ind: &str) -> Option<&[String]>
pub fn derived_aux_names(&self, ind: &str) -> Option<&[String]>
The auxiliaries this context derived for a source declaration, in generation order. Inductives own recursors and related products; definitions own equation lemmas.
Sourcepub fn add_structure_at(
&mut self,
name: &str,
sort: Universe,
params: &[(&str, Term)],
fields: &[(&str, Term)],
) -> KernelResult<()>
pub fn add_structure_at( &mut self, name: &str, sort: Universe, params: &[(&str, Term)], fields: &[(&str, Term)], ) -> KernelResult<()>
Register a structure AT a DECLARED sort — Lean’s structure Foo (params) : <sort> where ….
The declared sort is CHECKED, not taken on faith: the generated constructor is run through
crate::type_checker::check_constructor_universes, the same gate add_mutual_inductives
uses, so a record may not claim a sort too small to hold what it stores. Prop is exempt,
because Prop is impredicative and may store any sort at the cost of restricted elimination
— exactly Lean’s and Coq’s rule, and what makes Exists (which stores an α : Sort u)
legal in Prop.
TRANSACTIONAL: the structure is built on a scratch context and committed only if the check passes, so a rejected declaration leaves nothing behind.
Better than Lean in one respect: the error names the FIELD that forced the larger sort, where Lean reports only the two universes.
Sourcepub fn add_structure_poly_at(
&mut self,
name: &str,
levels: Vec<String>,
sort: Universe,
params: &[(&str, Term)],
fields: &[(&str, Term)],
) -> KernelResult<()>
pub fn add_structure_poly_at( &mut self, name: &str, levels: Vec<String>, sort: Universe, params: &[(&str, Term)], fields: &[(&str, Term)], ) -> KernelResult<()>
Context::add_structure_at for a UNIVERSE-POLYMORPHIC structure — Lean’s
structure Foo.{u…} (params) : <sort> where …, where sort, the parameter telescope and
the field types may all mention the level parameters in levels.
The level telescope is the whole content: the arity is registered through
Context::add_universe_poly_inductive, so Foo.{ℓ…} resolves and ONE declaration serves
every level. Everything else — the checked sort, the transactional scratch context, the
constructor, the projections, the parent edges — is the monomorphic path verbatim, which is
what makes an empty levels list exactly the old declaration rather than a near-copy.
Sourcepub fn add_structure(
&mut self,
name: &str,
params: &[(&str, Term)],
fields: &[(&str, Term)],
)
pub fn add_structure( &mut self, name: &str, params: &[(&str, Term)], fields: &[(&str, Term)], )
Register a structure, INFERRING the least sort that can hold its fields.
Equivalent to add_structure_at(name, self.structure_min_sort(params, fields), …).
Invalid declarations are recorded in refused_declarations and leave the context intact. Use
Context::add_structure_at to declare a sort explicitly (a Prop record, or one placed
higher than it needs to be).
Sourcepub fn add_structure_poly(
&mut self,
name: &str,
levels: Vec<String>,
params: &[(&str, Term)],
fields: &[(&str, Term)],
) -> KernelResult<()>
pub fn add_structure_poly( &mut self, name: &str, levels: Vec<String>, params: &[(&str, Term)], fields: &[(&str, Term)], ) -> KernelResult<()>
Register a UNIVERSE-POLYMORPHIC structure, INFERRING the least sort that can hold its
fields — Lean’s class Mul.{u} (α : Sort u) where mul : α → α → α, and the shape the whole
algebraic hierarchy is built from.
This is the wall that decided the Mathlib question. add_structure computes its result
sort from a telescope of CONCRETE parameter types, so a class declared with α : Type 0
refuses a Type 0 carrier — Type 0 : Type 1 — and one declaration could serve exactly
one level. Monomorphising at Type 0 is the tempting wrong move and it is unsound rather
than merely lossy: keys are flat Strings, so two instantiations collapse into one
declaration, and because LOGOS is CUMULATIVE the resulting terms very often still
type-check.
The result sort is COMPUTED over the level telescope, not assumed, exactly as Lean’s
mkResultUniverse (Lean/Elab/Inductive.lean:484) computes it: the max of the stored
fields’ sorts, raised to at least Type 0 when anything is stored, and Prop when the
record stores nothing but proofs. That inferred sort dominates every field by construction,
and registration still validates the declaration’s types, positivity, and universes.
Invalid types, negative recursion, and inconsistent universes are refused transactionally.
This returns the error directly; add_structure records it in the refusal ledger.
Sourcepub fn add_indexed_inductive(
&mut self,
name: &str,
sort: Term,
num_params: usize,
)
pub fn add_indexed_inductive( &mut self, name: &str, sort: Term, num_params: usize, )
Register an INDEXED inductive: sort is its full arity Π(params). Π(indices). Sort, of which the first num_params leading arguments are uniform parameters and
the rest are indices that vary per constructor (e.g. Eq with num_params == 2).
Sourcepub fn set_inductive_params(&mut self, name: &str, num_params: usize)
pub fn set_inductive_params(&mut self, name: &str, num_params: usize)
Record how many leading arguments of name’s arity are uniform parameters.
Sourcepub fn inductive_arity(&self, name: &str) -> usize
pub fn inductive_arity(&self, name: &str) -> usize
The full arity of an inductive — the number of leading Πs in its sort (Nat →
0, TList : Type → Type → 1, Eq : Type → A → A → Prop → 3). 0 for an unknown
name.
Sourcepub fn inductive_declared_params(&self, name: &str) -> Option<usize>
pub fn inductive_declared_params(&self, name: &str) -> Option<usize>
The EXPLICITLY declared parameter count for name, or None if the inductive was
registered without one. Reduction uses this to skip exactly the parameters of an
indexed constructor (refl A x → 2), falling back to a syntactic heuristic for the
legacy inductives that never declared a split — so their ι-reduction is untouched.
Sourcepub fn inductive_num_params(&self, name: &str) -> usize
pub fn inductive_num_params(&self, name: &str) -> usize
How many leading arguments of name’s arity are uniform PARAMETERS.
Three sources, in strict order:
- the count the declaration stated (
Context::add_indexed_inductive) — always wins, so a translator carrying Lean’s own split across is never second-guessed; - otherwise the count INFERRED from the registered constructors (see
Context::infer_num_params); - otherwise the full arity, for a header with no constructors yet — a declaration in progress behaves exactly as it always did.
O(1): the inference is computed once per add_constructor, never per read. This is read on
ι-reduction’s argument-skipping path, so a scan here would be a scan inside reduction.
Sourcepub fn inductive_num_indices(&self, name: &str) -> usize
pub fn inductive_num_indices(&self, name: &str) -> usize
How many trailing arguments of name’s arity are INDICES (arity − parameters).
Sourcepub fn add_constructor(&mut self, name: &str, inductive: &str, ty: Term)
pub fn add_constructor(&mut self, name: &str, inductive: &str, ty: Term)
Register a constructor for an inductive type.
The ty is the full type of the constructor
(e.g., Nat for Zero, Nat -> Nat for Succ).
Constructors are tracked in registration order for match expressions.
Sourcepub fn set_auto_auxiliaries(&mut self, on: bool)
pub fn set_auto_auxiliaries(&mut self, on: bool)
Turn EAGER declaration-time auxiliary synthesis on or off — Lean’s behaviour, made explicit.
Turning it on also seals whatever is already owed, so enabling it partway
through a load does not silently lose the declarations that came first.
See the auto_aux field’s own note for what it costs and why the default is off.
Sourcepub fn auto_auxiliaries(&self) -> bool
pub fn auto_auxiliaries(&self) -> bool
Whether eager declaration-time auxiliary synthesis is on.
Sourcepub fn seal(&mut self)
pub fn seal(&mut self)
Synthesise the auxiliaries of every inductive declared since the last seal, in declaration order — ONE pass per inductive rather than one per constructor.
This is the door a library loader uses: register everything, then seal. Idempotent, and a no-op when nothing is owed.
Sourcepub fn unsealed_inductives(&self) -> &[String]
pub fn unsealed_inductives(&self) -> &[String]
The inductives whose auxiliaries are still OWED — declared, not yet synthesised.
An honest channel rather than silence: a caller can see exactly which declarations would
gain constants from a seal. Lean does not tell you, because there
synthesis is unconditional and its cost is invisible.
Sourcepub fn add_declaration(&mut self, name: &str, ty: Term)
pub fn add_declaration(&mut self, name: &str, ty: Term)
Add a declaration (typed assumption/hypothesis).
Used for proof certification where hypotheses are assumed. Example: h1 : P -> Q
The type must be a type; a declaration whose type is not one is refused and recorded in
Context::refused_declarations. A type that names a constant declared later is owed, as a
definition’s is: the assumption waits as a pending obligation, invisible to lookup, and is
checked when that name arrives.
Sourcepub fn add_universe_poly_declaration(
&mut self,
name: &str,
params: Vec<String>,
ty: Term,
) -> KernelResult<()>
pub fn add_universe_poly_declaration( &mut self, name: &str, params: Vec<String>, ty: Term, ) -> KernelResult<()>
Register an opaque assumption with an explicit universe telescope. Its type is checked before either the declaration or its metadata is installed.
Sourcepub fn declare_opaque_checked(
&mut self,
name: &str,
params: Vec<String>,
ty: Term,
body: Term,
) -> KernelResult<()>
pub fn declare_opaque_checked( &mut self, name: &str, params: Vec<String>, ty: Term, body: Term, ) -> KernelResult<()>
Check an opaque declaration without exposing its body to conversion.
Proof dependency evidence is derived internally from the original closed type/body after both checkers agree. Raw headers remain assumptions. This gateway is atomic on failure and never creates pending obligations.
Sourcepub fn declare_theorem_checked(
&mut self,
name: &str,
params: Vec<String>,
ty: Term,
body: Term,
) -> KernelResult<()>
pub fn declare_theorem_checked( &mut self, name: &str, params: Vec<String>, ty: Term, body: Term, ) -> KernelResult<()>
Check a proposition and its proof in both kernels, then retain its body for kernel delta reduction. Lean theorems use this rule; opaque values do not.
Sourcepub fn holds_checked_declaration(
&self,
name: &str,
params: &[String],
ty: &Term,
body: &Term,
transparent_theorem: bool,
) -> bool
pub fn holds_checked_declaration( &self, name: &str, params: &[String], ty: &Term, body: &Term, transparent_theorem: bool, ) -> bool
Whether name already holds exactly this checked declaration: published through the
checked door at the same universe parameters and type, with — for a transparent theorem —
the same body, and — for an opaque one, whose body is sealed — the same dependency evidence.
The checked door refuses every existing name, identical or not: it is append-only, as Lean’s environment is. A document read a second time meets its own declarations there, and asks this first, so its second reading registers nothing and refuses nothing.
Sourcepub fn holds_assumption(&self, name: &str, params: &[String], ty: &Term) -> bool
pub fn holds_assumption(&self, name: &str, params: &[String], ty: &Term) -> bool
Whether name already holds exactly this ASSUMPTION — a bodyless declaration at the same
universe parameters and type, published through the assumption door. The door refuses every
existing name; this is the question a document read again asks first (see
Context::holds_checked_declaration).
Sourcepub fn add_definition(&mut self, name: String, ty: Term, body: Term)
pub fn add_definition(&mut self, name: String, ty: Term, body: Term)
Register a definition: name : type := body
Definitions are transparent and unfold during normalization (delta reduction). This distinguishes them from declarations (axioms) which have no body.
The BODY IS CHECKED against the declared type — see Context::declare, which this is the
()-returning face of. A body that definitely does not have the declared type is REFUSED
and nothing is registered, so evil : False := Zero can no longer put a closed term of type
False in reach of the standard library. Use declare where the refusal can be reported.
Sourcepub fn refused_declarations(&self) -> &[(String, String)]
pub fn refused_declarations(&self) -> &[(String, String)]
Every declaration the checked gateway REFUSED, as (name, reason), in refusal order.
Empty is the healthy state and the thing to lock: it says every definition in this context was checked or is tracked as owed, and none was silently dropped.
Sourcepub fn declare(&mut self, name: &str, ty: Term, body: Term) -> KernelResult<()>
pub fn declare(&mut self, name: &str, ty: Term, body: Term) -> KernelResult<()>
THE CHECKED REGISTRATION GATEWAY — one door, and everything that registers a definition goes through it.
add_definition used to be an insert. That is a hole the size of the whole kernel: the
type a name is registered AT is the type infer_type hands back for it, so an unchecked
insert lets any caller mint a constant of any type, False included, and every proof built
on top of it certifies. The Repl surface had the check; the raw Context API, which is the
API several hundred call sites use, did not.
What it refuses, and what it deliberately does not:
- a body whose inferred type is not a subtype of the declared one — REFUSED, nothing registered. (That subsumes a nonsense declared type: nothing is a subtype of it.)
- a body mentioning a GLOBAL that is not yet in scope — ACCEPTED, with a PENDING OBLIGATION
recorded against the missing name. Forward references are legitimate and common (a
δ-chain registered in ascending order; a family of mutually-referring definitions). The
obligation is retried the moment the missing name is declared, so the check is DEFERRED
rather than skipped — and
Context::pending_obligationsreports what is still owed, which is strictly more than a kernel that simply accepted. - a body whose failure NOTHING can repair — REFUSED. A deferral is owed against a name a
later declaration could supply and against nothing else (see
Context::deferrable_blocker); an obligation keyed on anything else is an IOU with no payer, and a definition sitting in the library behind one has a body that will never be checked. That state is not reported here, it is made unreachable. - a body that would close a δ-CYCLE — REFUSED, before anything is inserted. See
Context::delta_cycle_through.
Better than Lean here: Lean’s addDecl refuses a forward reference outright, so a
translator has to topologically sort before it can emit. This accepts the emission order
and still reports every claim it has not been able to discharge.
Sourcepub fn declare_with_validation<E: From<KernelError>>(
&mut self,
name: &str,
ty: Term,
body: Term,
validate: impl FnOnce(&Context, &Term, &Term) -> Result<(), E>,
) -> Result<(), E>
pub fn declare_with_validation<E: From<KernelError>>( &mut self, name: &str, ty: Term, body: Term, validate: impl FnOnce(&Context, &Term, &Term) -> Result<(), E>, ) -> Result<(), E>
Run additional source-language checks and ordinary kernel body checking against one immutable context. The callback cannot authorize a body: the kernel still checks it, and all normal registration guards remain. Only kernel-earned positive conversion results are shared within this call.
Sourcepub fn pending_obligations(&self) -> Vec<(&str, &str)>
pub fn pending_obligations(&self) -> Vec<(&str, &str)>
Definitions whose body has NOT yet been checked against its declared type, and assumptions
whose type has not, each paired with the name it is still waiting for — our #print axioms
for deferred obligations.
Pending definitions remain recorded but are unavailable to constant lookup and reduction until their bodies have been checked. Resolving a dependency retries its waiting definitions and exposes only those whose checks succeed.
Sourcepub fn get_global(&self, name: &str) -> Option<&Term>
pub fn get_global(&self, name: &str) -> Option<&Term>
Look up a global definition (inductive, constructor, definition, or declaration).
Returns the type of the global.
Sourcepub fn is_definition(&self, name: &str) -> bool
pub fn is_definition(&self, name: &str) -> bool
Check if a name is a definition (has a body that can be unfolded).
Sourcepub fn get_definition_body(&self, name: &str) -> Option<&Term>
pub fn get_definition_body(&self, name: &str) -> Option<&Term>
Get the body of a definition, if it exists.
Returns None for axioms, constructors, and inductives (only definitions have bodies).
Sourcepub fn get_definition_type(&self, name: &str) -> Option<&Term>
pub fn get_definition_type(&self, name: &str) -> Option<&Term>
Get the type of a definition, if it exists.
Sourcepub fn is_constructor(&self, name: &str) -> bool
pub fn is_constructor(&self, name: &str) -> bool
Check if a name is a constructor.
Sourcepub fn constructor_inductive(&self, name: &str) -> Option<&str>
pub fn constructor_inductive(&self, name: &str) -> Option<&str>
Get the inductive type a constructor belongs to.
Sourcepub fn is_inductive(&self, name: &str) -> bool
pub fn is_inductive(&self, name: &str) -> bool
Check if a name is an inductive type.
Sourcepub fn get_constructors(&self, inductive: &str) -> Vec<(&str, &Term)>
pub fn get_constructors(&self, inductive: &str) -> Vec<(&str, &Term)>
Get all constructors for an inductive type, in registration order.
Returns a vector of (constructor_name, constructor_type) pairs.
Sourcepub fn iter_declarations(&self) -> impl Iterator<Item = (&str, &Term)>
pub fn iter_declarations(&self) -> impl Iterator<Item = (&str, &Term)>
Iterate over all declarations (hypotheses).
Used by the certifier to find hypothesis by type.
Sourcepub fn iter_definitions(&self) -> impl Iterator<Item = (&str, &Term, &Term)>
pub fn iter_definitions(&self) -> impl Iterator<Item = (&str, &Term, &Term)>
Iterate over all definitions.
Used by the UI to display definitions.
Sourcepub fn iter_inductives(&self) -> impl Iterator<Item = (&str, &Term)>
pub fn iter_inductives(&self) -> impl Iterator<Item = (&str, &Term)>
Iterate over all inductive types.
Used by the UI to display inductive types.
Sourcepub fn iter_universe_polys(
&self,
) -> impl Iterator<Item = (&str, &[String], &Term, &Term)>
pub fn iter_universe_polys( &self, ) -> impl Iterator<Item = (&str, &[String], &Term, &Term)>
Iterate over the universe-polymorphic definitions: name, level parameters, type, body.
pub fn add_constructor_checked( &mut self, name: &str, inductive: &str, ty: Term, ) -> KernelResult<()>
Sourcepub fn add_mutual_inductives(
&mut self,
block: &[MutualInductive],
) -> KernelResult<()>
pub fn add_mutual_inductives( &mut self, block: &[MutualInductive], ) -> KernelResult<()>
Register a MUTUAL block of inductives whose constructors may reference one
another (Even/Odd, Tree/Forest). Strict positivity is checked over the
WHOLE block up front — a sibling occurrence is a recursive occurrence, a
sibling in a negative position is a cross-block paradox and rejected — and the
registration is TRANSACTIONAL: if any constructor violates positivity, nothing
is added. On success every member’s header (with its parameter split), every
constructor, and the block-membership registry are populated, ready for the
auto-derived mutual recursors.
Sourcepub fn add_universe_poly_inductives(
&mut self,
levels: &[String],
block: &[MutualInductive],
) -> KernelResult<()>
pub fn add_universe_poly_inductives( &mut self, levels: &[String], block: &[MutualInductive], ) -> KernelResult<()>
Register a checked inductive block with one shared universe telescope.
Sourcepub fn unit_constructor(&self, inductive: &str) -> Option<&str>
pub fn unit_constructor(&self, inductive: &str) -> Option<&str>
A non-indexed, fieldless singleton at any universe. Recursive and indexed single-constructor families do not have the unit eta rule.
Sourcepub fn k_constructor(&self, inductive: &str) -> Option<&str>
pub fn k_constructor(&self, inductive: &str) -> Option<&str>
The unique constructor of a K-like proposition: no stored fields beyond the uniform parameters. Its indices still need conversion at each use.
Sourcepub fn mutual_block_of(&self, name: &str) -> Option<&[String]>
pub fn mutual_block_of(&self, name: &str) -> Option<&[String]>
The mutual block name belongs to (the full ordered member list), or None
if name is a standalone inductive. Used by the recursor derivation to give
every block member a motive and route sibling recursion.
Sourcepub fn add_nested_inductive(
&mut self,
decl: &NestedDecl,
) -> KernelResult<NestedInfo>
pub fn add_nested_inductive( &mut self, decl: &NestedDecl, ) -> KernelResult<NestedInfo>
Register a NESTED inductive (RTree := rnode : TList RTree → RTree) by compiling
it — via the UNTRUSTED inductive_compile front-end —
to a mutual block plus conversion isos, then registering the block and CHECKING
every iso through the trusted kernel. A mis-compiled sibling is caught by mutual
positivity; a mis-typed iso is caught here (its inferred type must match its
declared conversion type). Soundness rests entirely on those trusted checks — the
compiler adds no trusted code, exactly as Lean lowers nested inductives to mutual.
Sourcepub fn add_hint(&mut self, name: &str)
pub fn add_hint(&mut self, name: &str)
Register a theorem as a hint for the auto tactic.
Hints are theorems that auto will try to apply when decision procedures fail. This allows auto to “learn” from proven theorems.
Sourcepub fn add_local_hint(&mut self, name: &str)
pub fn add_local_hint(&mut self, name: &str)
A local hint — reverted at Context::pop_scope. See Context::push_scope.
Sourcepub fn get_hints(&self) -> &[String]
pub fn get_hints(&self) -> &[String]
Get all registered hints.
Returns the names of theorems registered as hints.
Sourcepub fn set_reducibility(&mut self, name: &str, r: Reducibility)
pub fn set_reducibility(&mut self, name: &str, r: Reducibility)
Declare name’s REDUCIBILITY — Lean’s @[reducible] / @[irreducible].
The axis is a property of the DECLARATION, not of the reducer, which is why it lives here:
Transparency::Excluding takes a predicate, and without a registry every caller had to
invent its own — so two of them would eventually disagree about whether a constant unfolds,
and def_eq would answer differently depending on which one asked.
The kernel itself still unfolds everything (normalize is Transparency::All), exactly as
Lean’s kernel ignores @[irreducible]: the attribute constrains the ELABORATOR, and making
it constrain the kernel would let an attribute change what is TRUE.
Sourcepub fn reducibility(&self, name: &str) -> Reducibility
pub fn reducibility(&self, name: &str) -> Reducibility
name’s declared reducibility (the default when nothing was declared).
Sourcepub fn is_irreducible(&self, name: &str) -> bool
pub fn is_irreducible(&self, name: &str) -> bool
Whether name is @[irreducible] — THE PREDICATE Transparency::Excluding wants.
One lookup in one map, so a reducer may ask it once per δ-candidate without the question costing more than the unfolding would have.
Sourcepub fn add_simp_lemma(&mut self, name: &str) -> KernelResult<()>
pub fn add_simp_lemma(&mut self, name: &str) -> KernelResult<()>
Register name as a @[simp] lemma — Lean’s @[simp] theorem.
The lemma’s DECLARED STATEMENT is compiled, once, into the shape a rewriter applies:
Π(x̄). lhs = rhs becomes the rule lhs ⟶ rhs under the binders x̄, keyed by lhs’s
head symbol. Compiling at registration rather than at every rewrite attempt is the whole
reason this is a registry and not a list of names — a name-list forces every consumer to
re-open the telescope and re-destructure the Eq for every candidate at every subterm.
REFUSED, with a reason rather than a silent no-op, because each of these is a rule that would make the simplifier wrong or non-terminating rather than merely weak:
- a statement that is not an equation — there is nothing to rewrite WITH;
x = rhswith a bare bound variable on the left — it matches every term at every position, so one such rule rewrites the whole universe;lhs = rhswhererhsmentions a variablelhsdoes not bind — matching cannot determine it, so the replacement would contain a free variable;lhs = lhs— an identity rule that fires for ever without changing anything.
Better than Lean here in one small way: Lean accepts a looping simp lemma and you find
out when simp diverges. The last two shapes are refused at the door with the lemma named.
Sourcepub fn add_local_simp_lemma(&mut self, name: &str) -> KernelResult<()>
pub fn add_local_simp_lemma(&mut self, name: &str) -> KernelResult<()>
A local/scoped @[simp] lemma — reverted at Context::pop_scope.
Sourcepub fn simp_rules(&self) -> &[SimpRule]
pub fn simp_rules(&self) -> &[SimpRule]
Every registered rewrite rule, in registration order.
Sourcepub fn simp_rules_for(&self, head: &str) -> impl Iterator<Item = &SimpRule>
pub fn simp_rules_for(&self, head: &str) -> impl Iterator<Item = &SimpRule>
The rules whose left-hand side has head symbol head — THE DISPATCH DOOR.
A rewriter walking a term asks this once per subterm and gets only the rules that can
possibly match it. Never scan Context::simp_rules linearly from a hot path.
Sourcepub fn is_simp_lemma(&self, name: &str) -> bool
pub fn is_simp_lemma(&self, name: &str) -> bool
Whether name is registered as a @[simp] lemma.
Source§impl Context
impl Context
Sourcepub fn register_structure_checked(
&mut self,
inductive: &str,
projections: &[String],
) -> Result<(), StructureRefusal>
pub fn register_structure_checked( &mut self, inductive: &str, projections: &[String], ) -> Result<(), StructureRefusal>
Grant structure η to inductive through projections, after deciding each condition a
StructureRefusal variant names: one constructor, no indices, no recursion, and
projections that compute their fields at the fields’ types. On refusal the context is
unchanged.