Skip to main content

oxilean_kernel/
lib.rs

1#![allow(unused_imports)]
2
3//! # OxiLean Kernel — Trusted Computing Base
4//!
5//! The minimal, auditable kernel implementing the **Calculus of Inductive Constructions (CiC)**
6//! with universe polymorphism. This crate is the **trusted core** of OxiLean.
7//!
8//! ## Philosophy
9//!
10//! - **Minimal TCB**: Only ~3,500 SLOC need to be trusted for soundness
11//! - **Zero dependencies**: Uses only `std` (and is `no_std`-compatible where feasible)
12//! - **No unsafe**: `#![forbid(unsafe_code)]` ensures memory safety via Rust's guarantees
13//! - **Layered trust**: Bugs in the parser or elaborator cannot produce unsound proofs
14//! - **Arena-based memory**: All expressions allocated in typed arenas for O(1) equality
15//! - **WASM-first**: Compiles to `wasm32-unknown-unknown` with no system calls or FFI
16//!
17//! ## Quick Start
18//!
19//! ### Creating a Type
20//!
21//! ```ignore
22//! use oxilean_kernel::{Expr, Environment, Level};
23//!
24//! let env = Environment::new();
25//! // Nat : Type 0
26//! let nat_type = Expr::Sort(Level::Zero);
27//! ```
28//!
29//! ### Type Checking
30//!
31//! ```ignore
32//! use oxilean_kernel::{TypeChecker, KernelError};
33//!
34//! let mut checker = TypeChecker::new(&env);
35//! // Type-check an expression
36//! let result = checker.infer(expr)?;
37//! ```
38//!
39//! ## Architecture Overview
40//!
41//! The kernel is organized into three layers:
42//!
43//! ### Layer 1: Core Data Structures
44//!
45//! - **`arena`** — Typed arena allocator (`Arena<T>`, `Idx<T>`)
46//! - **`name`** — Hierarchical identifiers (`Nat.add.comm`)
47//! - **`level`** — Universe levels (`Zero`, `Succ`, `Max`, `IMax`, `Param`)
48//! - **`expr`** — Core AST (11 node types: `BVar`, `FVar`, `Sort`, `Const`, `App`, `Lam`, `Pi`, `Let`, `Lit`, `Proj`, `Rec`)
49//!
50//! ### Layer 2: Environment & Declarations
51//!
52//! - **`env`** — Global environment holding axioms, definitions, inductives, etc.
53//! - **`declaration`** — Declaration types: `Axiom`, `Def`, `Theorem`, `Inductive`, `Quotient`, `Recursor`, `Opaque`, `Constructor`
54//! - **`context`** — Local variable contexts and context snapshots
55//!
56//! ### Layer 3: Type Theory Engine
57//!
58//! - **`infer`** — Type inference: `infer_type(expr) → Type`
59//! - **`def_eq`** — Definitional equality: `is_def_eq(t1, t2) → bool`
60//! - **`whnf`** — Weak head normal form: `whnf(expr) → Expr`
61//! - **`check`** — Declaration checking and environment validation
62//!
63//! ### Layer 4: Reduction & Normalization
64//!
65//! - **`beta`** — β-reduction (function application)
66//! - **`eta`** — η-reduction (function extensionality)
67//! - **`simp`** — Simplification using equations
68//! - **`reduce`** — Generic reducer trait with reducibility hints
69//! - **`normalize`** — Full normal form computation
70//!
71//! ### Layer 5: Inductive Types & Recursion
72//!
73//! - **`inductive`** — Inductive type validation and recursor synthesis
74//! - **`match_compile`** — Pattern matching compilation to decision trees
75//! - **`quotient`** — Quotient type operations
76//! - **`termination`** — Structural recursion validation
77//!
78//! ## Key Concepts & Terminology
79//!
80//! ### Calculus of Inductive Constructions (CiC)
81//!
82//! OxiLean implements a variant of CiC featuring:
83//! - **Dependent types**: `Π (x : A), B x` (types can depend on values)
84//! - **Universe polymorphism**: Definitions can abstract over type universe levels
85//! - **Inductive types**: Type families with auto-generated recursion principles
86//! - **Impredicativity**: `Prop : Prop` (proofs of propositions are proof-irrelevant)
87//! - **Quotient types**: Extensional equality for abstract types\
88//!
89//! ### Trust Boundary
90//!
91//! Only the kernel is trusted. External code paths:
92//! 1. **Parser** → produces AST (can contain errors/malice)
93//! 2. **Elaborator** → converts AST to kernel terms (can produce invalid proofs)
94//! 3. **Kernel** → validates every declaration independently (soundness gate)
95//!
96//! If parser or elaborator is compromised, users get proof failures, never unsoundness.
97//!
98//! ### Soundness Properties
99//!
100//! - Every type-checkable declaration is sound by construction
101//! - No `unsafe` code means memory safety is Rust's responsibility
102//! - Axiom tracking prevents unsound axioms from polluting proofs
103//! - Universe polymorphism respects level constraints
104//!
105//! ### Memory Layout
106//!
107//! Expressions live in **typed arenas**:
108//! ```text
109//! Environment
110//!   ├─ expr_arena: Arena<Expr>     // All Expr nodes
111//!   ├─ level_arena: Arena<Level>   // All universe levels
112//!   └─ name_arena: Arena<Name>     // All identifiers
113//!
114//! Idx<Expr> = u32 (not a pointer, just an index)
115//! → O(1) equality via index comparison
116//! → Cache-friendly dense layout
117//! → Deterministic, no GC pauses
118//! ```
119//!
120//! ### Reduction Strategy
121//!
122//! - **WHNF (Weak Head Normal Form)**: Reduces until top-level constructor
123//!   - `λ x. t` stays as lambda
124//!   - `App (λ x. t) a` reduces to `t[a/x]`
125//!   - Inductive pattern match reduces to branch
126//! - **Full Normal Form**: WHNF + reduce inside binders
127//! - **Eta-expansion**: Insert `λ x. f x` for functions
128//!
129//! ### Locally Nameless Representation
130//!
131//! - **Bound variables** (inside binders): de Bruijn indices (`BVar(0)` = innermost binder)
132//! - **Free variables** (global/local): unique IDs (`FVar(id)`)
133//! - **Converting between**: `abstract` (close over binder), `instantiate` (substitute FVar)\
134//!
135//! ## Module Organization
136//!
137//! ### Foundational Modules\
138//!
139//! | Module | SLOC | Purpose |
140//! |--------|------|---------|
141//! | `arena` | ~150 | Typed arena allocator |
142//! | `name` | ~200 | Hierarchical names |
143//! | `level` | ~300 | Universe level computation |
144//! | `expr` | ~400 | Expression AST definition |
145//! | `subst` | ~150 | Substitution/instantiation |
146//! | `context` | ~100 | Local context management |
147//!
148//! ### Type Checking Core
149//!
150//! | Module | SLOC | Purpose |
151//! |--------|------|---------|
152//! | `infer` | ~500 | Type inference |
153//! | `def_eq` | ~400 | Definitional equality |
154//! | `whnf` | ~300 | Weak head normal form |
155//! | `check` | ~250 | Declaration validation |
156//!
157//! ### Reduction & Normalization
158//!
159//! | Module | SLOC | Purpose |
160//! |--------|------|---------|
161//! | `beta` | ~200 | Beta reduction |
162//! | `eta` | ~150 | Eta reduction |
163//! | `reduce` | ~200 | Generic reduction infrastructure |
164//! | `simp` | ~300 | Simplification engine |
165//! | `normalize` | ~150 | Full normalization |
166//!
167//! ### Type Families
168//!
169//! | Module | SLOC | Purpose |
170//! |--------|------|---------|
171//! | `inductive` | ~500 | Inductive types and recursors |
172//! | `quotient` | ~300 | Quotient types |
173//! | `match_compile` | ~400 | Pattern match compilation |
174//! | `termination` | ~350 | Recursion validation |
175//!
176//! ### Utilities
177//!
178//! | Module | SLOC | Purpose |
179//! |--------|------|---------|
180//! | `alpha` | ~200 | Alpha equivalence |
181//! | `axiom` | ~250 | Axiom tracking and safety |
182//! | `congruence` | ~300 | Congruence closure |
183//! | `export` | ~400 | Module serialization |
184//! | `prettyprint` | ~350 | Expression printing |
185//! | `trace` | ~200 | Debug tracing |
186//!
187//! ## Usage Examples
188//!
189//! ### Example 1: Check if Two Terms Are Definitionally Equal
190//!
191//! ```ignore
192//! use oxilean_kernel::{DefEqChecker, Expr};
193//!
194//! let checker = DefEqChecker::new(&env);
195//! let eq = checker.is_def_eq(expr1, expr2)?;
196//! assert!(eq);
197//! ```
198//!
199//! ### Example 2: Normalize an Expression
200//!
201//! ```ignore
202//! use oxilean_kernel::normalize;
203//!
204//! let normal = normalize(&env, expr)?;
205//! // normal is now in full normal form\
206//! ```
207//!
208//! ### Example 3: Work with Inductive Types
209//!
210//! ```ignore
211//! use oxilean_kernel::{InductiveType, check_inductive};
212//!
213//! let nat_ind = InductiveType::new(/* ... */);
214//! check_inductive(&env, &nat_ind)?;
215//! // nat_ind is validated and recursors are synthesized
216//! ```
217//!
218//! ## Integration with Other Crates
219//!
220//! ### With `oxilean-meta`
221//!
222//! The meta layer (`oxilean-meta`) extends the kernel with:
223//! - **Metavariable support**: Holes `?m` for unification
224//! - **Meta WHNF**: WHNF aware of unsolved metavars
225//! - **Meta DefEq**: Unification that assigns metavars
226//! - **App builder**: Helpers for constructing proof terms
227//!
228//! ### With `oxilean-elab`
229//!
230//! The elaborator (`oxilean-elab`) uses the kernel for:
231//! - **Type checking**: Validates elaborated proofs via `TypeChecker`
232//! - **Definitional equality**: Checks `is_def_eq` during elaboration
233//! - **Declaration checking**: Ensures all definitions are sound
234//!
235//! ### With `oxilean-parse`
236//!
237//! The parser provides surface syntax (`Expr` types) that the elaborator converts to kernel `Expr`.
238//!
239//! ## Soundness Guarantees
240//!
241//! OxiLean provides the following soundness invariants:
242//!
243//! 1. **Type Safety**: No expression can be assigned a type that doesn't logically follow
244//! 2. **Axiom Tracking**: All uses of axioms are recorded; proofs can be reviewed for axiomatic assumptions
245//! 3. **Termination**: Recursive definitions are proven terminating before acceptance
246//! 4. **Universe Consistency**: No universe cycles or level violations
247//! 5. **Proof Irrelevance**: All proofs of the same `Prop` are definitionally equal
248//!
249//! ## Performance Characteristics
250//!
251//! - **Expression comparison**: O(1) via arena indexing
252//! - **WHNF reduction**: O(depth × reduction_steps) for typical programs
253//! - **Environment lookup**: O(log n) (indexed environment)
254//! - **Memory**: Dense arena layout, no pointer chasing
255//! - **GC**: None needed (Rust ownership handles deallocation)\
256//!
257//! ## Further Reading
258//!
259//! - [ARCHITECTURE.md](../../ARCHITECTURE.md) — System architecture
260//! - [BLUEPRINT.md](../../BLUEPRINT.md) — Formal CiC specification
261//! - Module documentation for specific subcomponents
262
263#![forbid(unsafe_code)]
264#![allow(missing_docs)]
265#![warn(clippy::all)]
266
267pub mod arena;
268pub mod expr;
269pub mod level;
270pub mod name;
271
272// Re-exports for convenience
273pub use arena::{Arena, Idx};
274pub use expr::{BinderInfo, Expr, FVarId, Literal};
275pub use level::{Level, LevelMVarId};
276pub use name::Name;
277pub mod subst;
278
279pub use subst::{abstract_expr, instantiate};
280pub mod env;
281pub mod reduce;
282
283pub use env::{Declaration, EnvError, Environment};
284pub use reduce::{reduce_nat_op, Reducer, ReducibilityHint};
285pub mod error;
286pub mod infer;
287
288// Phase 3.1: Kernel Foundation modules
289pub mod r#abstract;
290pub mod declaration;
291pub mod equiv_manager;
292pub mod expr_cache;
293pub mod expr_util;
294pub mod instantiate;
295
296pub use declaration::{
297    instantiate_level_params, AxiomVal, ConstantInfo, ConstantVal, ConstructorVal,
298    DefinitionSafety, DefinitionVal, InductiveVal, OpaqueVal, QuotKind, QuotVal, RecursorRule,
299    RecursorVal, TheoremVal,
300};
301pub use equiv_manager::EquivManager;
302
303pub use error::KernelError;
304pub use infer::{LocalDecl, TypeChecker};
305pub mod abstract_interp;
306pub mod alpha;
307pub mod axiom;
308pub mod beta;
309pub mod builtin;
310pub mod check;
311pub mod congruence;
312pub mod context;
313pub mod conversion;
314pub mod def_eq;
315pub mod eta;
316pub mod export;
317pub mod inductive;
318pub mod match_compile;
319pub mod normalize;
320pub mod prettyprint;
321pub mod proof;
322pub mod quotient;
323pub mod reduction;
324pub mod serial;
325pub mod simp;
326pub mod struct_eta;
327pub mod substitution;
328pub mod termination;
329pub mod trace;
330pub mod type_erasure;
331pub mod typeclasses;
332pub mod universe;
333pub mod whnf;
334
335/// Benchmarking support utilities for the OxiLean kernel.
336pub mod bench_support;
337/// Caching infrastructure for performance optimization.
338pub mod cache;
339/// Foreign function interface support.
340pub mod ffi;
341/// Structural sharing (hash-consing) for `Expr` values.
342pub mod hash_cons;
343/// No-std compatibility layer for constrained and WASM environments.
344pub mod no_std_compat;
345/// Thread-safe string interning pool for `Name` construction.
346pub mod string_intern;
347
348pub use alpha::{alpha_equiv, canonicalize};
349pub use axiom::{
350    classify_axiom, extract_axioms, has_unsafe_dependencies, transitive_axiom_deps, AxiomSafety,
351    AxiomValidator,
352};
353pub use beta::{beta_normalize, beta_step, beta_under_binder, is_beta_normal, mk_beta_redex};
354pub use builtin::{init_builtin_env, is_nat_op, is_string_op};
355pub use check::{check_constant_info, check_constant_infos, check_declaration, check_declarations};
356pub use congruence::{
357    mk_congr_theorem, mk_congr_theorem_with_fixed, CongrArgKind, CongruenceClosure,
358    CongruenceTheorem,
359};
360pub use context::{ContextSnapshot, NameGenerator};
361pub use conversion::ConversionChecker;
362pub use def_eq::{is_def_eq_simple, DefEqChecker};
363pub use eta::{eta_contract, eta_expand, is_eta_expandable};
364pub use export::{
365    deserialize_module_header, export_environment, import_module, serialize_module, ExportedModule,
366    ModuleCache,
367};
368pub use inductive::{check_inductive, reduce_recursor, InductiveEnv, InductiveType, IntroRule};
369pub use match_compile::{
370    CompileResult, ConstructorInfo as MatchConstructorInfo, DecisionTree, MatchArm, MatchCompiler,
371    Pattern,
372};
373pub use normalize::{alpha_eq_env, evaluate, is_normal_form, normalize_env, normalize_whnf};
374pub use prettyprint::{print_expr, print_expr_ascii, ExprPrinter};
375pub use proof::ProofTerm;
376pub use quotient::{
377    check_equivalence_relation, check_quot_usage, is_quot_type_expr, quot_eq, reduce_quot_lift,
378    QuotUsageKind, QuotientType,
379};
380pub use simp::{alpha_eq, normalize, simplify};
381pub use termination::{ParamInfo, RecCallInfo, TerminationChecker, TerminationResult};
382pub use trace::{TraceEvent, TraceLevel, Tracer};
383pub use typeclasses::{
384    is_class_constraint, Instance as KernelInstance, Method as KernelMethod,
385    TypeClass as KernelTypeClass, TypeClassRegistry as KernelTypeClassRegistry,
386};
387pub use universe::{UnivChecker, UnivConstraint};
388pub use whnf::{is_whnf, whnf, whnf_is_lambda, whnf_is_pi, whnf_is_sort};
389
390pub mod core_types;
391pub use core_types::*;
392
393/// Proof Certificate System — compact, verifiable records of kernel-checked proofs.
394pub mod proof_cert;
395pub use proof_cert::{
396    create_certificate, deserialize_cert, hash_declaration, hash_expr, serialize_cert,
397    verify_certificate, CertCheckResult, CertificateStore, ProofCertId, ProofCertificate,
398    ProofStep,
399};
400
401/// Definitional Equality Cache — memoised results for `is_def_eq` queries.
402pub mod def_eq_cache;
403pub use def_eq_cache::{
404    with_cache, CacheEviction, DefEqCache, DefEqCacheStats, DefEqEntry, DefEqKey,
405};
406
407/// Indexed environment for fast declaration lookup.
408pub mod env_index;
409pub use env_index::{
410    is_in_namespace, namespace_of, EnvIndex, IndexStats, LookupResult, ModuleIndex, NameIndex,
411    TypeIndex,
412};
413
414/// Memoized WHNF reduction with environment-version-aware cache invalidation.
415pub mod whnf_memo;
416pub use whnf_memo::{hash_bytes, with_memo, MemoConfig, MemoStats, WhnfEntry, WhnfKey, WhnfMemo};