Skip to main content

Crate logicaffeine_kernel

Crate logicaffeine_kernel 

Source
Expand description

§logicaffeine-kernel

A pure Calculus of Constructions type checker (inductive types, fixpoints, universes, quotients) and the only part of Logicaffeine a proof asks you to trust. Everything above it, from the English parser to the Lean importer, only proposes terms, so a bug up there can lose a proof but never forge one; recheck, an independent de Bruijn checker, gives a second opinion, and says so when it cannot reach one. Its trusted base is written down and wider than Lean’s: 63 named assumptions to Lean 4’s three axioms, each argued in TCB.md.

Part of the Logicaffeine workspace, tier 1. Its only workspace dependency is logicaffeine_base; with no path to the lexicon (the Milner invariant) it never sees an English word, and new vocabulary never recompiles the type checker.

§Role in the workspace

The bottom of the proof stack, depended on by logicaffeine_compile, logicaffeine_proof and the web and CLI apps. It holds three checkers:

  • the named Term kernel (infer_type, is_subtype, normalize), the trust base;
  • recheck, a second implementation with its own de Bruijn terms, reduction and conversion, so a substitution bug in one surfaces as a disagreement instead of passing both; double_check runs both;
  • dag, the hash-consed core: Lean 4’s theory exactly, behind the Lean Kernel Arena checkers, and LOGOS’s own.

Types, values, functions and proofs are all one Term: Nat : Type 0, λx:Nat. x and refl : a = a alike. See proof and verification for how proposals flow down to this core.

§Example

refl Nat Zero proves Eq Nat Zero Zero, and both kernels agree:

use logicaffeine_kernel::prelude::StandardLibrary;
use logicaffeine_kernel::{double_check, infer_type, is_subtype, DoubleCheck, Term};

let ctx = StandardLibrary::context();
let g = |n: &str| Term::Global(n.to_string());
let app = |f: Term, x: Term| Term::App(Box::new(f), Box::new(x));

let proof = app(app(g("refl"), g("Nat")), g("Zero"));
let claim = app(app(app(g("Eq"), g("Nat")), g("Zero")), g("Zero"));
assert!(is_subtype(ctx, &infer_type(ctx, &proof).unwrap(), &claim));
assert_eq!(double_check(ctx, &proof), DoubleCheck::Agreed);

§Trusted base

The 63 assumptions StandardLibrary::register installs are 15 Primitive (Lean assumes or builds in the same, propext, Classical.choice and Quot.sound among them), 0 Definable, 37 Reflection (the semantics of the Syntax/Derivation embedding) and 11 DomainSpecific (temporal arithmetic). axiom_dependencies is Lean’s #print axioms as a function; ADMITTED_AXIOMS lists the placeholders, such as sorryAx and admit, that mark a proof admitted, and FOREIGN_AXIOMS pairs each name LOGOS deliberately lacks with the diagnostic to give instead of “unbound variable”.

§Public API

§Core types

  • Term: Sort(Universe), Var, Global, Const { name, levels } (a universe-polymorphic constant at explicit levels), Pi, Lambda, App, Match { discriminant, motive, cases }, Fix { name, body }, MutualFix, Let, Lit(Literal), Hole.
  • Universe: SProp | Prop | Type(u32), plus the level algebra of universe polymorphism: level variables Var, Succ, Max and the impredicative IMax. Cumulative: SProp ≤ Prop ≤ Type(i), Type(i) ≤ Type(j) iff i ≤ j. Π is impredicative in Prop (its sort is imax), so a universally-quantified FOL formula stays a Prop; any two proofs of an SProp are definitionally equal.
  • Literal: Int(i64), BigInt (the integers that overflow i64, canonically), Nat (an arbitrary-precision natural, definitionally equal to its unary Succ^n Zero in both kernels), Float(f64), Text(String), Duration(i64 ns), Date(i32 days), Moment(i64 ns UTC). Computed via ALU, not recursion.
  • Context: typing context. extend adds a local binding as an O(1) clone; the global environment (inductives, declarations, axioms, definitions, hints) is Arc-shared.
  • KernelError / KernelResult: unbound variable, type mismatch, non-function/non-type, bad motive / wrong case count, positivity and termination violations, certification errors, un-inferable hole.

§Type checking

  • infer_type: bidirectional CIC inference.
  • is_subtype: cumulative subtyping, as a bool.
  • normalize: beta/iota/delta + guarded-fix reduction with δ-cycle detection and a 2^20-step budget (normalize_checked reports why it stopped, as Unreduced); evaluates primitive ALU ops (add/sub/mul/div/mod, comparisons, ite) and the syn_* reflection builtins (syn_eval, syn_quote, …).

§Decision procedures

Each is a pub mod with a Rust entry point on Term (distinct from the prelude-registered try_* tactic terms below):

ModuleProvesEntry point
ringpolynomial equalitiesreify → Polynomial::canonical_eq
lialinear inequalities (Fourier–Motzkin over ℚ)fourier_motzkin_unsat
omegaexact integer arithmetic (discrete, GCD-normalized)omega_unsat
cccongruence closure over uninterpreted functionscheck_goal
simprewriting / constant folding (fuel-limited)check_goal
bitvectorreflection-symmetry identities (N-Queens)reflection_symmetry_proven

bitvector exhaustively machine-checks the bit-permutation identities for n = 1..=PROOF_WIDTH (16); edge-distance uniformity of the per-bit transport makes that a proof for all n (memoised via reflection_certificate).

Two algebraic-substrate modules build on ring: field_algebra proves identities over the prime field 𝔽_q of ML-KEM / ML-DSA, and word_ring proves them over the word ring ℤ/2ⁿ (Word8/Word16/Word32/Word64). Both are discharged by the kernel’s own decision procedures, so the certified-crypto arithmetic never trusts an external algebra system. eval is the call-by-value evaluator for the computational fragment (the engine behind native_decide), distinct from normalize’s substitution-based reduction.

§Elaboration and recursors

elaborate is the elaborator (metavariables, unification, implicit arguments), so id 0 becomes id Nat 0 before the kernel sees it; recursor derives the dependent eliminator I.rec of an inductive, as Lean and Coq do; tactics proves a statement by tactics over the kernel’s own goals (GoalState: intro, exact, apply, refine, rfl, change, rewrite, subst, injection, induction, cases, calc, and cc, decide and simp, which build their proof terms), each goal a metavariable with its hypotheses and target. All three propose terms the checker still re-verifies: GoalState::qed hands the kernel the finished proof.

§Representation and derived declarations

  • term_store: hash-consed term storage. A Term is a Box-recursive tree, so a subterm occurring n times is n trees checked n times; interning gives the sharing Lean’s Expr has, so equal subterms are one node and a repeated check is a pointer comparison.
  • int_inductive: Int as a real inductive (ofNat | negSucc, Lean’s shape) with its arithmetic defined rather than assumed. integer_laws proves the sixteen public ring and order laws over that carrier and installs each under its law’s name, so the prelude’s integer arithmetic rests on no axiom.
  • quotient: Lean’s four universe-polymorphic quotient primitives (kernel.quot.type, .mk, .lift, .ind) for kernel importers, installed in canonical form only and certified rather than admitted. The prelude’s Quot_rec is Lean’s definition over its own quotient primitives, not an assumption.
  • observational: observational equality, registered on request beside the standard library (observational::register). Obs.{u} A a b : SProp computes on the type it compares at: pointwise at a function type, logical equivalence at SProp and Prop, by formers at a universe, by constructors at an inductive family, by the equivalence closure of the relation at a quotient. Obs_cast carries a value along an equality of types and computes along universes, function types, parameterized families and quotients, so a closed numeral carried by Obs_cast is still a numeral. Function and propositional extensionality hold by conversion and the standard library’s Quot_sound is a theorem. The constants are certified as the quotient’s are (displacing a name they rest on revokes the certificate; the same spelling without it is an assumption) and compute in both kernels and in the dag core.
  • equations: equation lemmas. Definitions are δ-transparent, so dbl 3 ≡ 6 already holds by conversion; f_eq_def and f_eq_1 … f_eq_n give each such fact a name a proof can cite.
  • tactic_cert: the second kernel’s check of reflected ring, linear-arithmetic and congruence goals. Linear arithmetic and congruence replay certificates, ring uses exact Kronecker substitution, and none calls the first kernel’s engines: the rechecker trusts the certificate, not the tactic.

§Soundness gates

  • positivity::check_positivity_resolved: strict positivity of inductives at every declaration boundary, unfolding δ-aliases and checking nested occurrences through registered containers; rejects negative occurrences that would encode Russell’s paradox and declines a container it cannot decide. check_positivity is the syntactic, alias-blind variant.
  • termination::check_termination: guarded structural recursion by a lexicographic measure over the inductive binders (the matched binder first), shared by a mutual block; rejects fix f. f. structural_columns/structural_position give both kernels’ Fix reduction the column the guard chose.
  • inductive_compile: the nested-inductive compiler, an untrusted front-end for inductives that recur through other inductives, kernel-rechecked on the way back.

§Standard library (prelude)

StandardLibrary::register installs Entity (FOL domain), Nat, Bool, TList, True, False, Not, Eq, And, Or, Ex, Int as the inductive ofNat | negSucc with its arithmetic and its ring and order laws proven, the primitive Float/Text, the reflection embedding (Syntax, Derivation), hardware ops, and the kernel-level tactic terms try_ring/try_lia/try_cc/try_omega/try_simp plus try_auto (sequencing simp → ring → cc → omega → lia). StandardLibrary::context() is that registration made once per process: borrow it to ask questions, clone it (copy-on-write, about a microsecond) for a context of your own.

§Certificates (serde feature): the De Bruijn criterion

certificate::{Certificate, recheck, PRELUDE_VERSION} (PRELUDE_VERSION is logos-coc-6; a certificate minted against another prelude is refused). A Certificate carries only proof_term, claimed_type, and prelude_version, never a context. recheck checks against the trusted axiom context it registers itself (StandardLibrary::context), infers the term’s type, and requires it to be a subtype of the claim, so a certificate cannot smuggle in a bogus axiom. The trusted surface of a re-check is this crate plus a JSON parser: no proof search, no SMT. The recheck example re-checks one from a file:

cargo run -p logicaffeine-kernel --example recheck --features serde -- cert.json

TheoremCertificate (recheck_theorem) re-checks a proof over a disclosed delta and refuses a delta entry that reuses a prelude-owned name; EnvironmentCertificate carries a proof with every declaration it needs as a shared term table, rebuilt through the kernel’s checked gateways. read_certificate dispatches any certificate by shape and schema and recheck_document returns a RecheckReport. With --package <dir> the recheck example replays a Lean → LOGOS package.

§Interface

interface is a vernacular text front-end (TermParser, parse_command/Command, literate_parser, Repl) for driving the kernel by hand: Definition/Theorem/Opaque/Axiom/Check/Eval/Inductive/Structure/Quotient/Print Axioms commands with universe parameters, namespaces, sections, notation and hygienic macros, and an English-like literate syntax. Its printer is the exact inverse of its parser. It builds Terms for the trusted core; it is not part of the trusted surface.

interface::lean (the lean feature) reads a Lean 4 kernel export (lean4export NDJSON) as one more input surface. It is an untrusted reader: every declaration it builds is re-decided by the kernel and by the independent recheck, the target’s axioms are compared with Lean’s #print axioms, and the result is emitted as a literate .lg document the vernacular re-parses and re-checks. largo lean import and largo lean replay drive it.

§The hash-consed core (dag)

dag is a type theory over a hash-consed expression DAG in two modes, Lean 4’s theory exactly and LOGOS’s Calculus of Inductive Constructions (tc::Theory): de Bruijn indices, one id per structurally distinct term, loose-bound-variable ranges and free-variable flags cached per node, and every cache keyed on ids. It checks lean4export streams directly (dag::export::check_export), and the logos_kernel and logos_dual examples (the second requires tc and sem to agree) run it as Arena checkers. name, level and expr are its interned stores; env the admitted declarations; tc inference, reduction and definitional equality by substitution, and sem the same judgment by evaluation into closures; check, inductive and primitive the admission rules; json and export the streaming reader.

In LOGOS’s theory the same core checks the declarations of a Context: logos lowers and lifts Terms, logos_env admits them (admit, replay), and logos_tc holds the rules LOGOS has beside Lean’s: indexed match with coverage over the constructors the indices allow, fix and mutual fix under the guard and checked against the type their position expects, the K-like rule, cumulative inductives, the Int literal bridge and the elimination restrictions. It admits every declaration of the standard library and refuses each known paradox by the rule the Term kernel refuses it by; the Term kernel still decides LOGOS’s proof surfaces.

§Feature flags

FeatureDefaultEnables
serdeoffSerialize/Deserialize on Term/Literal/Universe, the certificate module and the recheck example
leanoffcompiles interface::lean, the Lean 4 export reader (implies serde)
shadowoffevery declaration a checked Context door decides is decided again by the dag core kept in step with the context (dag::mirror), and a disagreement panics with both verdicts
nbeoffcompiles dag::nbe, the dag core’s closure-based (NbE) conversion engine, opt-in while it is under construction

§Dependencies

  • Internal: logicaffeine-base, for the UnionFind behind the cc e-graph.
  • External: rustc-hash (id-keyed tables) and smallvec (application spines); serde and serde_json only with the serde/lean features, so the default trusted core has no serialization dependency.

§License

MIT License — see LICENSE.md.


Docs index · Root README · Changelog

Re-exports§

pub use eval::eval_bool;
pub use eval::eval_bool_tree;
pub use eval::native_compile_bool;
pub use eval::native_compile_decide;
pub use eval::native_decide;
pub use inductive_compile::NestedDecl;
pub use inductive_compile::NestedInfo;
pub use elaborate::auto_bind_implicits;
pub use elaborate::bind_self_recursion;
pub use elaborate::elaborate;
pub use elaborate::elaborate_anon_ctor;
pub use elaborate::elaborate_app;
pub use elaborate::elaborate_app_against;
pub use elaborate::elaborate_dot;
pub use elaborate::elaborate_in;
pub use elaborate::fill_match_motives;
pub use elaborate::instantiate;
pub use elaborate::resolve_coercion;
pub use elaborate::resolve_instance;
pub use elaborate::surface_elaborate;
pub use elaborate::surface_elaborate_against;
pub use elaborate::unify;
pub use elaborate::unify_in;
pub use elaborate::MetaCtx;
pub use elaborate::ParamKind;
pub use elaborate::ANON_CTOR_MARKER;
pub use elaborate::DOT_MARKER;
pub use recheck::double_check;
pub use recheck::recheck;
pub use recheck::DoubleCheck;
pub use recheck::Incomplete;
pub use recheck::IncompleteKind;
pub use recheck::ReCheckError;
pub use recursor::derive_recursor;
pub use reify::VarInterner;
pub use prelude::axiom_dependencies;
pub use prelude::axiom_dependencies_given;
pub use prelude::axiom_dependencies_of;
pub use prelude::foreign_axiom_note;
pub use prelude::is_admitted_axiom;
pub use prelude::AxiomUsage;
pub use prelude::ADMITTED_AXIOMS;
pub use prelude::FOREIGN_AXIOMS;
pub use recursor::derive_recursor_universe_poly;

Modules§

bitvector
Bitvector reflection-symmetry decision procedure.
cc
Congruence Closure Tactic
certificate
Independently re-checkable proof certificates — the De Bruijn criterion.
dag
The kernel core: a type theory over a hash-consed expression DAG, in two modes (tc::Theory): Lean 4’s theory exactly, and LOGOS’s Calculus of Inductive Constructions.
elaborate
R4 — the elaborator: metavariables, unification, and implicit-argument inference.
equations
Equation lemmas — Lean’s f.eq_def, f.eq_1 … f.eq_n — the NAME a proof cites when it appeals to a definition’s behaviour, which is what rw [f] / simp [f] / unfold f all need.
eval
A call-by-value evaluator for the kernel’s computational fragment — the engine behind native_decide.
field_algebra
Kernel algebra for the prime field 𝔽_q of ML-KEM / ML-DSA — the certified arithmetic substrate (F2 seed).
inductive_compile
Nested-inductive compiler (K3) — the UNTRUSTED front-end for inductives that recur nested inside a container, RTree := rnode : TList RTree → RTree.
int_inductive
Int as a real inductive — Lean’s ofNat | negSucc with its arithmetic defined rather than assumed (Init/Data/Int/Basic.lean:40-45, :78-166). The construction, packaged so the prelude adopts it in one call; the module header carries how Lean keeps it fast anyway. Int as a REAL INDUCTIVE — Lean’s ofNat | negSucc, with its arithmetic DEFINED.
interface
Vernacular interface for the Kernel.
lia
Linear Integer Arithmetic via Fourier-Motzkin Elimination
observational
Certified universe-polymorphic quotient primitives. Observational equality: Obs.{u} A a b : SProp, an equality over every type that computes on the weak-head normal form of A, with Obs_refl, Obs_transp (its elimination, into SProp only) and Obs_cast (a value carried along an equality of types), after Pujet and Tabareau’s CC^obs.
omega
Omega Test: True Integer Arithmetic Decision Procedure
positivity
Strict positivity checking for inductive types.
prelude
Standard Library for the Kernel.
quotient
Certified universe-polymorphic quotient primitives for kernel importers.
recheck
An independent proof-term re-checker (the de Bruijn criterion taken seriously).
recursor
R2 — auto-derived recursors (dependent eliminators) for inductive types.
reify
Shared reification substrate for the arithmetic decision procedures.
ring
Ring Tactic: Polynomial Equality by Normalization
simp
Simplifier Tactic
tactic_cert
Independent verification of reflected ring, linear-arithmetic, and congruence goals.
tactics
Tactics over the kernel’s own goals: a goal state of metavariables, outside the trusted base.
term_store
Hash-consed term storage — the representation a kernel needs to be as fast as Lean’s.
termination
Termination checking for fixpoints.
word_ring
Kernel ring proofs for the word ring ℤ/2ⁿ (Word8/Word16/Word32/Word64).

Structs§

BigInt
An exact, arbitrary-precision integer.
Context
Typing context: maps variable names to their types.
MutualInductive
One member of a MUTUAL inductive block: its name, arity sort, uniform parameter count, and constructors (name + full type). Constructor types may reference ANY member of the block — that is the whole point of a mutual declaration.
SimpRule
The @[simp] registry’s compiled rule — Context::simp_rules/simp_rules_for hand these to whatever does the rewriting, already destructured into ∀x̄. lhs ⟶ rhs. A @[simp] lemma COMPILED to the form a rewriter applies: ∀x̄. lhs ⟶ rhs.
SourcePosition
The transparent carrier’s payload: a binder’s kind, or where a subterm came from. A position in a source text, in Lean’s convention: the LINE is 1-based and the COLUMN is 0-based and counted in Unicode scalar values. Held in its canonical spelling, the one Lean prints a diagnostic’s position in — file:line:column — so a position IS its text: two positions are equal exactly when they print the same, and reading one back needs no rendering.
StructInfo
Metadata for a registered structure (record): its single constructor, how many leading type PARAMETERS it takes, the projection function names in field order, and the declaration shape the elaborator needs — the parameter and field telescopes, the parents recovered from a flattened field prefix, and which parameters are OUTPUTS.

Enums§

Annotation
The transparent carrier’s payload: a binder’s kind, or where a subterm came from. One piece of information about how a subterm was written. The elaborator and the interface printer read it; every kernel judgment erases it first.
ConstError
Why a Term::Const reference could not be resolved. Every kernel and the reducer report the same three failures, so a reference refused by typing is never a normal form to the reducer.
KernelError
Errors that can occur during type checking.
Literal
Primitive literal values.
MeaningChange
How a refused declaration would have changed a registered name’s meaning.
Provenance
The transparent carrier’s payload: a binder’s kind, or where a subterm came from. Where a subterm came from.
Reducibility
Lean’s reducibility axis, declared per constant — Context::is_irreducible is the predicate reduction::Transparency::Excluding is looking for. Lean’s REDUCIBILITY axis, declared per constant and read by the elaborator’s δ step.
StructureRefusal
Why structure η was refused. Every variant names the first condition that failed.
Term
Unified term representation.
Transparency
The δ-transparency axis (Lean’s TransparencyMode): normalize_at/normalize_checked_at keep an @[irreducible] constant folded with its body intact, while normalize stays the kernel’s own always-unfolding setting. How much δ a reduction is allowed — Lean’s TransparencyMode, narrowed to the axis that actually changes the answer.
Universe
Universe levels in the type hierarchy — a level EXPRESSION, so the kernel can be universe-POLYMORPHIC (R3). The concrete hierarchy is Prop : Type 1 : Type 2 : … with Prop ≤ Type i; on top of it, a level may mention universe VARIABLES, so one definition (id.{u} : Π(A : Sort u). A → A) is reusable at every level instead of duplicated per level.
Unreduced
Why a reduction stopped before reaching a normal form.

Constants§

DEFAULT_INSTANCE_PRIORITY
Lean’s default instance priority — what instance foo : C α := … gets when it says no (priority := n). Named rather than spelled 1000 at each site so a translator carrying a Lean source’s explicit priorities lands them on the same scale.

Functions§

check_positivity_for_test
Strict-positivity check of a constructor type — exposed so tests can pin the paradox fence (negative occurrences rejected, positive functional fields accepted) directly.
defeq_for_test
Definitional equality of two terms — exposed for tests that pin conversion behaviour (structure eta, proof irrelevance) directly.
discard_resource_stops
Whether a verdict depended on kernel work that stopped for want of a resource: a conversion that says “not equal” decided nothing when one of its reductions ran out of budget. Run f WITHOUT letting its resource stops reach the enclosing observation — for work whose answer the verdict does not use (a debug differential that re-decides a pair already decided).
infer_type
Infer the type of a term in a context.
instantiate_codomain
Substitute replacement for var in body, WRITING IT ONCE when copying it would blow the result up.
instantiate_universes
Instantiate universe variables throughout a term: substitute every Sort’s level by subst. This specializes a universe-POLYMORPHIC term (λA:Sort u. …) to a concrete level (u := Type 0), yielding an ordinary term the kernel checks as-is — so one definition is reused at every level instead of duplicated.
int_lit
The canonical Literal for an integer: Int(i64) when it fits (the fast, common path), otherwise the arbitrary-precision BigInt. This is the ONLY sanctioned way to build an integer literal from a BigInt result, guaranteeing the one-representation-per-value invariant on which definitional equality of literals rests.
is_subtype
Check if type a is a subtype of type b (cumulativity).
lit_bigint
The BigInt value of an integer literal, promoting a machine Int — for arithmetic that must run in arbitrary precision. None for non-integer literals.
normalize
Normalize a term to its normal form.
normalize_at
The δ-transparency axis (Lean’s TransparencyMode): normalize_at/normalize_checked_at keep an @[irreducible] constant folded with its body intact, while normalize stays the kernel’s own always-unfolding setting. normalize at a chosen transparency. At Transparency::Excluding the named constants keep their bodies and stay FOLDED, which is what @[irreducible] means at Lean’s default transparency; normalize itself is the kernel’s setting and unfolds everything.
normalize_checked
Normalize a term, reporting honestly when the reduction did not finish.
normalize_checked_at
The δ-transparency axis (Lean’s TransparencyMode): normalize_at/normalize_checked_at keep an @[irreducible] constant folded with its body intact, while normalize stays the kernel’s own always-unfolding setting. normalize_checked at a chosen transparency — the honest face of normalize_at.
normalize_checked_elab
The elaborator’s reduction face: @[irreducible] constants stay folded, body intact, with the opacity predicate built once from Context::is_irreducible rather than by each caller. normalize remains the kernel’s face and unfolds everything, exactly as Lean’s does. normalize_elab’s honest face: the elaborator’s transparency, and a reduction that did not finish reported as such rather than handed back as a normal form.
normalize_elab
The elaborator’s reduction face: @[irreducible] constants stay folded, body intact, with the opacity predicate built once from Context::is_irreducible rather than by each caller. normalize remains the kernel’s face and unfolds everything, exactly as Lean’s does. normalize at the ELABORATOR’s transparency, reading the context’s own reducibility registry — the door that makes @[irreducible] reachable without every caller inventing its own opacity predicate.
observe_resource_stops
Whether a verdict depended on kernel work that stopped for want of a resource: a conversion that says “not equal” decided nothing when one of its reductions ran out of budget. Run f and report the first resource stop of any kernel work it did — a reduction that spent its step budget, or a term too deep to descend — on this thread or on any sized-stack thread the kernel started for it.
reconcile_block_params
The ONE parameter-count rule for a MUTUAL block, stated where registration can enforce it.
resolve_const_levels
Resolve a Term::Const { name, levels } against a declaration, producing the universe substitution to apply to its type AND its body (rules 1-3 above). This is the ONE place the decision is made; instantiate_universes applies the result.
substitute
Substitute a term for a variable: body[var := replacement].

Type Aliases§

KernelResult
Result type for kernel operations.