Skip to main content

logicaffeine_kernel/
term.rs

1//! Unified term representation for the Calculus of Constructions.
2//!
3//! In CoC, there is no distinction between terms and types.
4//! Everything is a Term in an infinite hierarchy of universes.
5
6use std::fmt;
7
8/// Primitive literal values.
9///
10/// These are opaque values that compute via hardware ALU, not recursion.
11///
12/// `PartialEq` is written by hand rather than derived, because it is THE KERNEL'S EQUALITY:
13/// `type_checker::types_equal` and `recheck::def_eq` both compare two `Term::Lit` through this
14/// one impl, so it decides literal conversion in BOTH kernels at once and the de Bruijn
15/// criterion gives it no protection whatever. See the impl below for what the derive got wrong.
16#[derive(Debug, Clone)]
17#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
18pub enum Literal {
19    /// 64-bit signed integer
20    Int(i64),
21    /// 64-bit floating point
22    Float(f64),
23    /// UTF-8 string
24    Text(String),
25    /// Duration in nanoseconds (signed for negative offsets like "5 min early")
26    Duration(i64),
27    /// Calendar date as days since Unix epoch (i32 gives ±5.8 million year range)
28    Date(i32),
29    /// Instant in time as nanoseconds since Unix epoch (UTC)
30    Moment(i64),
31    /// Arbitrary-precision integer — the `Int` values that overflow `i64` (K6). This is a
32    /// PARALLEL representation, appended so existing certificates' `Int`/`Float`/… encoding
33    /// is byte-unchanged. A `BigInt` is CANONICAL: it holds only values `to_i64()` cannot,
34    /// so every integer has a unique `Literal` (small → `Int`, huge → `BigInt`) and
35    /// definitional equality stays sound. Serialized as a decimal string, stable across
36    /// `BigInt`'s internal limb layout. Produced by `int_lit`; never constructed directly
37    /// for a value that fits `i64`.
38    BigInt(#[cfg_attr(feature = "serde", serde(with = "bigint_dec"))] logicaffeine_base::BigInt),
39    /// Arbitrary-precision NATURAL-number literal — a compact, accelerated form of the
40    /// unary Peano numeral `Succ^n Zero` (K6). `Nat(n)` is DEFINITIONALLY EQUAL to `Succ`
41    /// applied `n` times to `Zero`: the kernel bridges the two in `extract_constructor`
42    /// (so a `match`/recursor computes on it, peeling one `Succ` per step) and in `def_eq`
43    /// (so `Nat(n)` and `Succ^n Zero` are interchangeable), in BOTH kernels. It stores the
44    /// count as one `BigInt` instead of `n` heap nodes. Serialized as a decimal string;
45    /// the value is non-negative.
46    Nat(#[cfg_attr(feature = "serde", serde(with = "bigint_dec"))] logicaffeine_base::BigInt),
47}
48
49/// The canonical `Literal` for an integer: `Int(i64)` when it fits (the fast, common path),
50/// otherwise the arbitrary-precision `BigInt`. This is the ONLY sanctioned way to build an
51/// integer literal from a `BigInt` result, guaranteeing the one-representation-per-value
52/// invariant on which definitional equality of literals rests.
53pub fn int_lit(n: logicaffeine_base::BigInt) -> Literal {
54    match n.to_i64() {
55        Some(x) => Literal::Int(x),
56        None => Literal::BigInt(n),
57    }
58}
59
60/// The `BigInt` value of an integer literal, promoting a machine `Int` — for arithmetic
61/// that must run in arbitrary precision. `None` for non-integer literals.
62pub fn lit_bigint(lit: &Literal) -> Option<logicaffeine_base::BigInt> {
63    match lit {
64        Literal::Int(x) => Some(logicaffeine_base::BigInt::from_i64(*x)),
65        Literal::BigInt(n) => Some(n.clone()),
66        _ => None,
67    }
68}
69
70/// Serialize a [`logicaffeine_base::BigInt`] as its decimal string — a representation
71/// independent of the internal limb layout, so certificates stay portable and stable.
72#[cfg(feature = "serde")]
73mod bigint_dec {
74    use logicaffeine_base::BigInt;
75
76    pub fn serialize<S: serde::Serializer>(v: &BigInt, s: S) -> Result<S::Ok, S::Error> {
77        s.serialize_str(&v.to_string())
78    }
79
80    pub fn deserialize<'de, D: serde::Deserializer<'de>>(d: D) -> Result<BigInt, D::Error> {
81        let s = <String as serde::Deserialize>::deserialize(d)?;
82        BigInt::parse_decimal(&s).ok_or_else(|| serde::de::Error::custom("invalid BigInt literal"))
83    }
84}
85
86/// Literal equality — identical to the derive on every arm but `Float`.
87///
88/// **Why `Float` is not compared with `==`.** IEEE-754 equality is not an equivalence relation:
89/// it is not REFLEXIVE at `NaN`, and it identifies `0.0` with `-0.0`, which have distinct
90/// encodings. A kernel whose conversion is not reflexive cannot retype `refl Float x : x = x`
91/// for a `NaN`, and one that identifies two distinct values proves an equation Lean refuses
92/// (`(0.0 : Float) = -0.0` is not closed by `rfl` there). Both are wrong, in opposite
93/// directions, and [`impl Eq for Literal`](Literal) is a written claim that neither happens.
94///
95/// `f64::to_bits` is the independent model the comparison is stated against: total, reflexive
96/// at every bit pattern including each `NaN` payload, and injective, so two literals are equal
97/// exactly when they are the same IEEE value. It is also what `term_store`'s interner already
98/// keys floats on, so id equality and `Term` equality now agree — the `float_free` caveat that
99/// module carries was about exactly this disagreement.
100impl PartialEq for Literal {
101    fn eq(&self, other: &Self) -> bool {
102        match (self, other) {
103            (Literal::Int(a), Literal::Int(b)) => a == b,
104            (Literal::Float(a), Literal::Float(b)) => a.to_bits() == b.to_bits(),
105            (Literal::Text(a), Literal::Text(b)) => a == b,
106            (Literal::Duration(a), Literal::Duration(b)) => a == b,
107            (Literal::Date(a), Literal::Date(b)) => a == b,
108            (Literal::Moment(a), Literal::Moment(b)) => a == b,
109            (Literal::BigInt(a), Literal::BigInt(b)) => a == b,
110            (Literal::Nat(a), Literal::Nat(b)) => a == b,
111            _ => false,
112        }
113    }
114}
115
116impl Eq for Literal {}
117
118impl fmt::Display for Literal {
119    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
120        match self {
121            Literal::Int(n) => write!(f, "{}", n),
122            Literal::Float(x) => write!(f, "{}", x),
123            Literal::Text(s) => write!(f, "{:?}", s),
124            Literal::Duration(nanos) => {
125                // Display in most human-readable unit
126                let abs = nanos.unsigned_abs();
127                let sign = if *nanos < 0 { "-" } else { "" };
128                if abs >= 3_600_000_000_000 {
129                    write!(f, "{}{}h", sign, abs / 3_600_000_000_000)
130                } else if abs >= 60_000_000_000 {
131                    write!(f, "{}{}min", sign, abs / 60_000_000_000)
132                } else if abs >= 1_000_000_000 {
133                    write!(f, "{}{}s", sign, abs / 1_000_000_000)
134                } else if abs >= 1_000_000 {
135                    write!(f, "{}{}ms", sign, abs / 1_000_000)
136                } else if abs >= 1_000 {
137                    write!(f, "{}{}μs", sign, abs / 1_000)
138                } else {
139                    write!(f, "{}{}ns", sign, abs)
140                }
141            }
142            Literal::Date(days) => {
143                // Convert days since epoch to ISO-8601 date
144                // Unix epoch is 1970-01-01 (day 0)
145                // We use a simple algorithm for display purposes
146                let days = *days as i64;
147                let (year, month, day) = days_to_ymd(days);
148                write!(f, "{:04}-{:02}-{:02}", year, month, day)
149            }
150            Literal::Moment(nanos) => {
151                // Convert to ISO-8601 datetime
152                let secs = nanos / 1_000_000_000;
153                let days = secs / 86400;
154                let time_secs = secs % 86400;
155                let hours = time_secs / 3600;
156                let mins = (time_secs % 3600) / 60;
157                let secs_rem = time_secs % 60;
158                let (year, month, day) = days_to_ymd(days);
159                write!(
160                    f,
161                    "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}Z",
162                    year, month, day, hours, mins, secs_rem
163                )
164            }
165            Literal::BigInt(n) => write!(f, "{}", n),
166            Literal::Nat(n) => write!(f, "{}", n),
167        }
168    }
169}
170
171/// Convert days since Unix epoch to (year, month, day).
172fn days_to_ymd(days: i64) -> (i64, u8, u8) {
173    // Civil date from days since epoch using the algorithm from Howard Hinnant
174    // https://howardhinnant.github.io/date_algorithms.html
175    let z = days + 719468;
176    let era = if z >= 0 {
177        z / 146097
178    } else {
179        (z - 146096) / 146097
180    };
181    let doe = (z - era * 146097) as u32;
182    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
183    let y = yoe as i64 + era * 400;
184    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
185    let mp = (5 * doy + 2) / 153;
186    let d = doy - (153 * mp + 2) / 5 + 1;
187    let m = if mp < 10 { mp + 3 } else { mp - 9 };
188    let year = if m <= 2 { y + 1 } else { y };
189    (year, m as u8, d as u8)
190}
191
192/// Universe levels in the type hierarchy — a level EXPRESSION, so the kernel can be
193/// universe-POLYMORPHIC (R3). The concrete hierarchy is `Prop : Type 1 : Type 2 : …`
194/// with `Prop ≤ Type i`; on top of it, a level may mention universe VARIABLES, so one
195/// definition (`id.{u} : Π(A : Sort u). A → A`) is reusable at every level instead of
196/// duplicated per level.
197///
198/// - `Prop` is the universe of propositions (the impredicative bottom; `Prop ≤` all)
199/// - `Type(n)` is the concrete universe at level n
200/// - `Var(u)` is a universe variable; it ranges over `Prop` and the `Type` levels (never `SProp`,
201///   which is a sort and not a level), so a level that mentions one may be `Prop`
202/// - `Succ(ℓ)` is `ℓ + 1`
203/// - `Max(ℓ₁, ℓ₂)` is the least upper bound (used in Π-type formation)
204///
205/// The algebra (`succ`/`max`/`equiv`/`is_subtype_of`) is decided over a canonical
206/// normal form, NOT by the derived structural equality — `max(u,u) ≡ u`,
207/// `max(succ u, u) ≡ succ u`, etc.
208#[derive(Debug, Clone, PartialEq, Eq)]
209#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
210pub enum Universe {
211    /// SProp — the DEFINITIONALLY-proof-irrelevant sort (S). The bottom of the hierarchy
212    /// (`SProp ≤ Prop ≤ Type n`): any two terms of a type in `SProp` are definitionally
213    /// equal, and it is impredicative (`Π` into `SProp` is `SProp`). It collapses out of
214    /// `max`/`imax`/`succ` so the `Prop=0` level encoding is never disturbed.
215    SProp,
216    /// Prop - the universe of propositions
217    Prop,
218    /// Type n - the universe of types at level n
219    Type(u32),
220    /// A universe variable (universe polymorphism).
221    Var(String),
222    /// The successor level `ℓ + 1`.
223    Succ(Box<Universe>),
224    /// The least upper bound of two levels.
225    Max(Box<Universe>, Box<Universe>),
226    /// The IMPREDICATIVE maximum, `imax(a, b)` = `b` if `b` is `Prop`, else
227    /// `max(a, b)`. It is the sort of `Π(x:A). B` where `A : Sort a`, `B : Sort b`:
228    /// a Π into a proposition is a proposition (Prop is impredicative), no matter
229    /// the domain. When `b` is a variable this stays symbolic — the level may be
230    /// `Prop` or not depending on the instantiation.
231    IMax(Box<Universe>, Box<Universe>),
232}
233
234impl Universe {
235    /// Get the successor universe: `Type n → Type (n+1)`, `Prop → Type 0`, and a
236    /// symbolic `Succ(ℓ)` for a level that mentions variables.
237    ///
238    /// `Prop.succ()` is `Type 0`, NOT `Type 1`. This function and `level_leq` must agree, and
239    /// `level_leq` decides everything over `level_order`'s ℕ-model, in which `Prop ↦ 0` and
240    /// `Type n ↦ n+1`. In that model `succ(Prop)` is level 1, which is spelled `Type 0`. Returning
241    /// `Type 1` made the successor operation and the level ORDERING disagree by one about `Prop`
242    /// alone — the algebra was not self-consistent, and it also put us one level off Lean, which
243    /// says `Prop : Type 0`.
244    ///
245    /// `SProp` moves with it for the same reason: `to_lnat` puts it at 0 as well, so its successor
246    /// is `Type 0` by the identical argument. The discriminator is narrow, which is why this
247    /// survived: `Prop → Type` agrees either way because the codomain's level already dominates;
248    /// only `Prop → Nat` (`Type 0` in Lean, `Type 1` here) told them apart.
249    pub fn succ(&self) -> Universe {
250        match self {
251            Universe::SProp | Universe::Prop => Universe::Type(0),
252            // AT THE CEILING of the machine representation the successor stays SYMBOLIC. Both
253            // machine answers to `Type(u32::MAX) + 1` are catastrophic and neither is a
254            // judgement: wrapping gives `Type u32::MAX : Type 0`, and `Type 0 ≤ Type u32::MAX`
255            // by cumulativity, so a universe contains itself — Girard's paradox, from which a
256            // closed term of type `False` follows; and overflowing makes the kernel's answer to
257            // a malformed input "the process is gone", which cannot be part of a trusted base.
258            // `to_lnat` decides the ordering in `u64`, where `Succ(Type u32::MAX)` is an
259            // ordinary level strictly above `Type u32::MAX`, so the symbolic answer is total,
260            // sound and fully comparable — and it costs the ordinary levels nothing.
261            Universe::Type(n) => match n.checked_add(1) {
262                Some(next) => Universe::Type(next),
263                None => Universe::Succ(Box::new(self.clone())),
264            },
265            other => Universe::Succ(Box::new(other.clone())),
266        }
267    }
268
269    /// Get the maximum of two universes (for Pi type formation). Concrete operands
270    /// collapse immediately; otherwise a symbolic `Max(…)` is formed (its algebra is
271    /// resolved by `normalize`).
272    pub fn max(&self, other: &Universe) -> Universe {
273        match (self, other) {
274            // SProp and Prop are absorbed (they are `≤` everything), SProp first (it is `≤ Prop`).
275            (Universe::SProp, u) | (u, Universe::SProp) => u.clone(),
276            (Universe::Prop, u) | (u, Universe::Prop) => u.clone(),
277            (Universe::Type(a), Universe::Type(b)) => Universe::Type((*a).max(*b)),
278            _ => Universe::Max(Box::new(self.clone()), Box::new(other.clone())),
279        }
280    }
281
282    /// The impredicative maximum `imax(a, b)` — the sort of a `Π` whose codomain
283    /// lives in `b`. Collapses when `b`'s Prop-ness is known: `imax(a, Prop) = Prop`,
284    /// `imax(a, Type n) = max(a, Type n)`; `imax(a, a) = a`. Otherwise (a variable or
285    /// other symbolic `b`) it stays a symbolic `IMax`, whose algebra `equiv`/
286    /// `is_subtype_of` decide by case-splitting on whether `b` is `Prop`.
287    pub fn imax(&self, other: &Universe) -> Universe {
288        match other {
289            // A Π into an S-proposition is an S-proposition (impredicative SProp).
290            Universe::SProp => Universe::SProp,
291            // A Π into a proposition is a proposition.
292            Universe::Prop => Universe::Prop,
293            // A concrete non-Prop codomain: the Π is predicative.
294            Universe::Type(_) | Universe::Succ(_) => self.max(other),
295            _ => {
296                // Construction preserves symbolic levels. Semantic equivalence is
297                // decided when checking conversion, not each time a Pi is formed.
298                if self == other {
299                    // imax(a, a) = a (a = 0 ⇒ 0; a ≥ 1 ⇒ max(a,a) = a).
300                    self.clone()
301                } else {
302                    Universe::IMax(Box::new(self.clone()), Box::new(other.clone()))
303                }
304            }
305        }
306    }
307
308    /// Cumulative subtyping `self ≤ other`, decided over the level normal form. Sound
309    /// for variables: `u ≤ u`, `Type 0 ≤ u`, `u ≤ succ u` hold, but `Type 1 ≤ u` and
310    /// `u ≤ v` do NOT (they fail for some instantiation).
311    pub fn is_subtype_of(&self, other: &Universe) -> bool {
312        level_leq(self, other)
313    }
314
315    /// Whether every instantiation of this level's variables puts it at `Type 0` or above: a
316    /// family in `Sort ℓ` is then never a proposition. `Sort u` may be `Prop` (at `u := 0`);
317    /// `Sort (u+1)` and `Sort (max 1 u)` never are.
318    pub fn is_never_prop(&self) -> bool {
319        level_leq(&Universe::Type(0), self)
320    }
321
322    /// The least universe LEVEL at or above this one: itself, with `SProp` raised to `Prop`. `SProp`
323    /// is a sort and never a level, and `SProp ≤ Prop`, so a level variable solved from a type in
324    /// `SProp` takes `Prop`, and cumulativity carries the type into `Sort Prop`.
325    pub fn least_level(&self) -> Universe {
326        match self {
327            Universe::SProp => Universe::Prop,
328            Universe::Prop | Universe::Type(_) | Universe::Var(_) => self.clone(),
329            Universe::Succ(l) => l.least_level().succ(),
330            Universe::Max(a, b) => a.least_level().max(&b.least_level()),
331            Universe::IMax(a, b) => a.least_level().imax(&b.least_level()),
332        }
333    }
334
335    /// Whether `SProp` occurs anywhere in this level expression.
336    pub fn mentions_sprop(&self) -> bool {
337        match self {
338            Universe::SProp => true,
339            Universe::Prop | Universe::Type(_) | Universe::Var(_) => false,
340            Universe::Succ(l) => l.mentions_sprop(),
341            Universe::Max(a, b) | Universe::IMax(a, b) => a.mentions_sprop() || b.mentions_sprop(),
342        }
343    }
344
345    /// Definitional equality of two level expressions, accounting for the algebra
346    /// (`max`, `imax`, `succ`, variables) — NOT the derived structural equality.
347    /// Decided as mutual subtyping over all variable instantiations.
348    pub fn equiv(&self, other: &Universe) -> bool {
349        level_leq(self, other) && level_leq(other, self)
350    }
351
352    /// The same rigid-level equivalence as `equiv`, charged to a shared construction budget.
353    pub(crate) fn equiv_bounded(
354        &self,
355        other: &Universe,
356        budget: &mut crate::recursor::bounded::RecursorBudget,
357    ) -> crate::recursor::bounded::GenerationResult<bool> {
358        level_order::equivalent(self, other, budget)
359    }
360
361    /// Substitute universe variables (replacing each `Var(v)` by `subst[v]`) throughout
362    /// this level expression — the heart of instantiating a universe-polymorphic global.
363    pub fn substitute(&self, subst: &std::collections::HashMap<String, Universe>) -> Universe {
364        match self {
365            Universe::SProp | Universe::Prop | Universe::Type(_) => self.clone(),
366            Universe::Var(v) => subst.get(v).cloned().unwrap_or_else(|| self.clone()),
367            Universe::Succ(l) => l.substitute(subst).succ(),
368            Universe::Max(a, b) => a.substitute(subst).max(&b.substitute(subst)),
369            Universe::IMax(a, b) => a.substitute(subst).imax(&b.substitute(subst)),
370        }
371    }
372}
373
374#[path = "term_level_order.rs"]
375mod level_order;
376
377#[cfg(test)]
378thread_local! { static LEVEL_COMPARISONS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; }
379
380fn level_leq(a: &Universe, b: &Universe) -> bool {
381    #[cfg(test)]
382    LEVEL_COMPARISONS.with(|n| n.set(n.get() + 1));
383    level_order::leq(a, b)
384}
385
386/// Unified term representation.
387///
388/// Every expression in CoC is a Term:
389/// - `Sort(u)` - universes (Type 0, Type 1, Prop)
390/// - `Var(x)` - variables
391/// - `Pi` - dependent function types: Π(x:A). B
392/// - `Lambda` - functions: λ(x:A). t
393/// - `App` - application: f x
394///
395/// `==` is the kernel's identity: it compares kernel meaning and does not see
396/// [`Term::Annotated`]. [`Term::identical`] is the comparison that does.
397#[derive(Debug, Clone)]
398#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
399pub enum Term {
400    /// Universe: Type n or Prop
401    Sort(Universe),
402
403    /// Local variable reference (bound by λ or Π)
404    Var(String),
405
406    /// Global definition (inductive type or constructor)
407    Global(String),
408
409    /// A universe-polymorphic global referenced at explicit levels — `name.{ℓ₀, ℓ₁, …}`.
410    /// `Global` is the monomorphic case (no level arguments); `Const` instantiates a
411    /// stored universe-polymorphic definition's universe parameters with `levels`.
412    Const { name: String, levels: Vec<Universe> },
413
414    /// Dependent function type: Π(x:A). B
415    ///
416    /// When B doesn't mention x, this is just A → B.
417    /// When B mentions x, this is a dependent type.
418    Pi {
419        param: String,
420        param_type: Box<Term>,
421        body_type: Box<Term>,
422    },
423
424    /// Lambda abstraction: λ(x:A). t
425    Lambda {
426        param: String,
427        param_type: Box<Term>,
428        body: Box<Term>,
429    },
430
431    /// Application: f x
432    App(Box<Term>, Box<Term>),
433
434    /// Pattern matching on inductive types.
435    ///
436    /// `match discriminant return motive with cases`
437    ///
438    /// - discriminant: the term being matched (must have inductive type)
439    /// - motive: λx:I. T — describes the return type
440    /// - cases: one case per constructor, in definition order
441    Match {
442        discriminant: Box<Term>,
443        motive: Box<Term>,
444        cases: Vec<Term>,
445    },
446
447    /// Fixpoint (recursive function).
448    ///
449    /// `fix name. body` binds `name` to itself within `body`.
450    /// Used for recursive definitions like addition.
451    Fix {
452        /// Name for self-reference within the body
453        name: String,
454        /// The body of the fixpoint (typically a lambda)
455        body: Box<Term>,
456    },
457
458    /// MUTUAL fixpoint — a block of mutually-recursive functions (K3).
459    ///
460    /// `mutualfix { f₀ := b₀, …, fₙ := bₙ }.index` binds ALL of `f₀ … fₙ` within EVERY
461    /// body `bᵢ` (that is the mutual part), and the whole term reduces to the
462    /// `index`-th definition. It is the body of a mutual inductive block's recursor:
463    /// `Even.rec`'s fixpoint calls `Odd.rec`'s on the smaller sub-proof and vice
464    /// versa. Each body's type is inferred structurally from its λ-telescope (like the
465    /// single `Fix`); termination is the MUTUAL Giménez guard — a call to ANY member
466    /// must pass a structurally-smaller argument at that member's recursive position.
467    MutualFix {
468        /// The mutually-recursive definitions, `(name, body)`, in block order. Every
469        /// name is in scope in every body.
470        defs: Vec<(String, Term)>,
471        /// Which definition this occurrence denotes (and reduces to).
472        index: usize,
473    },
474
475    /// Local definition: `let name : ty := value in body`.
476    ///
477    /// `name` is bound to `value` (of type `ty`) transparently within `body` —
478    /// so the body is type-checked and reduced with `name ≡ value` (ZETA), not
479    /// as an opaque hypothesis. The surface `let`; the sharing seam for the
480    /// elaborator.
481    Let {
482        name: String,
483        ty: Box<Term>,
484        value: Box<Term>,
485        body: Box<Term>,
486    },
487
488    /// Primitive literal value.
489    ///
490    /// Hardware-native values like i64, f64, String.
491    /// These compute via CPU ALU, not recursion.
492    Lit(Literal),
493
494    /// Hole (implicit argument).
495    ///
496    /// Represents an argument that should be inferred by the type checker.
497    /// Used in Literate syntax like `X equals Y` where the type of X/Y is implicit.
498    Hole,
499
500    /// `term`, carrying an [`Annotation`](crate::Annotation): a binder's kind, or where `term` came
501    /// from. TRANSPARENT — no judgment of the kernel reads it, `==` does not see it, and a
502    /// certificate cannot carry it (it has no serialized form). See `annotation.rs`.
503    #[cfg_attr(feature = "serde", serde(skip))]
504    Annotated {
505        annotation: crate::annotation::Annotation,
506        term: Box<Term>,
507    },
508}
509
510/// Equality of KERNEL MEANING: annotations are peeled at every node, so a term equals its
511/// annotated copy. Every other variant compares exactly as the derive did, field by field in
512/// declaration order.
513impl PartialEq for Term {
514    fn eq(&self, other: &Term) -> bool {
515        match (self.peel_annotations(), other.peel_annotations()) {
516            (Term::Sort(a), Term::Sort(b)) => a == b,
517            (Term::Var(a), Term::Var(b)) => a == b,
518            (Term::Global(a), Term::Global(b)) => a == b,
519            (Term::Const { name: m, levels: a }, Term::Const { name: n, levels: b }) => {
520                m == n && a == b
521            }
522            (
523                Term::Pi {
524                    param: p,
525                    param_type: s,
526                    body_type: t,
527                },
528                Term::Pi {
529                    param: q,
530                    param_type: u,
531                    body_type: v,
532                },
533            ) => p == q && s == u && t == v,
534            (
535                Term::Lambda {
536                    param: p,
537                    param_type: s,
538                    body: t,
539                },
540                Term::Lambda {
541                    param: q,
542                    param_type: u,
543                    body: v,
544                },
545            ) => p == q && s == u && t == v,
546            (Term::App(f, a), Term::App(g, b)) => f == g && a == b,
547            (
548                Term::Match {
549                    discriminant: d,
550                    motive: m,
551                    cases: cs,
552                },
553                Term::Match {
554                    discriminant: e,
555                    motive: n,
556                    cases: ds,
557                },
558            ) => d == e && m == n && cs == ds,
559            (Term::Fix { name: m, body: s }, Term::Fix { name: n, body: t }) => m == n && s == t,
560            (Term::MutualFix { defs: a, index: i }, Term::MutualFix { defs: b, index: j }) => {
561                a == b && i == j
562            }
563            (
564                Term::Let {
565                    name: m,
566                    ty: s1,
567                    value: s2,
568                    body: s3,
569                },
570                Term::Let {
571                    name: n,
572                    ty: t1,
573                    value: t2,
574                    body: t3,
575                },
576            ) => m == n && s1 == t1 && s2 == t2 && s3 == t3,
577            (Term::Lit(a), Term::Lit(b)) => a == b,
578            (Term::Hole, Term::Hole) => true,
579            _ => false,
580        }
581    }
582}
583
584impl Eq for Term {}
585
586enum SyntaxDisplayPart<'a> {
587    Term(&'a Term),
588    Universe(&'a Universe),
589    Text(&'a str),
590    Index(usize),
591    Levels(&'a [Universe]),
592    Cases(&'a [Term]),
593    Definitions(&'a [(String, Term)]),
594}
595
596// Formatting is also used on unfinished reductions in diagnostics. Such terms
597// may exceed the kernel's input depth, so both term and universe walks use a
598// borrowed work stack. Sequence continuations keep memory proportional to depth.
599fn display_syntax(part: SyntaxDisplayPart<'_>, f: &mut fmt::Formatter<'_>) -> fmt::Result {
600    use SyntaxDisplayPart as Part;
601    let mut pending = vec![part];
602    while let Some(part) = pending.pop() {
603        match part {
604            Part::Text(text) => f.write_str(text)?,
605            Part::Index(index) => write!(f, "{}", index)?,
606            Part::Levels(levels) => {
607                if let Some((first, rest)) = levels.split_first() {
608                    if !rest.is_empty() {
609                        pending.extend([Part::Levels(rest), Part::Text(", ")]);
610                    }
611                    pending.push(Part::Universe(first));
612                }
613            }
614            Part::Cases(cases) => {
615                if let Some((first, rest)) = cases.split_first() {
616                    if !rest.is_empty() {
617                        pending.extend([Part::Cases(rest), Part::Text(" | ")]);
618                    }
619                    pending.push(Part::Term(first));
620                }
621            }
622            Part::Definitions(definitions) => {
623                if let Some(((name, body), rest)) = definitions.split_first() {
624                    write!(f, "{} := ", name)?;
625                    if !rest.is_empty() {
626                        pending.extend([Part::Definitions(rest), Part::Text(", ")]);
627                    }
628                    pending.push(Part::Term(body));
629                }
630            }
631            Part::Universe(universe) => match universe {
632                Universe::SProp => f.write_str("SProp")?,
633                Universe::Prop => f.write_str("Prop")?,
634                Universe::Type(n) => write!(f, "Type{}", n)?,
635                Universe::Var(name) => f.write_str(name)?,
636                Universe::Succ(inner) => {
637                    f.write_str("(")?;
638                    pending.extend([Part::Text("+1)"), Part::Universe(inner)]);
639                }
640                Universe::Max(left, right) | Universe::IMax(left, right) => {
641                    f.write_str(if matches!(universe, Universe::Max(..)) {
642                        "max("
643                    } else {
644                        "imax("
645                    })?;
646                    pending.extend([
647                        Part::Text(")"),
648                        Part::Universe(right),
649                        Part::Text(", "),
650                        Part::Universe(left),
651                    ]);
652                }
653            },
654            Part::Term(term) => match term {
655                Term::Sort(universe) => pending.push(Part::Universe(universe)),
656                Term::Var(name) | Term::Global(name) => f.write_str(name)?,
657                Term::Const { name, levels } => {
658                    write!(f, "{}.{{", name)?;
659                    pending.extend([Part::Text("}"), Part::Levels(levels)]);
660                }
661                Term::Pi {
662                    param,
663                    param_type,
664                    body_type,
665                } => {
666                    if param == "_" {
667                        pending.extend([
668                            Part::Term(body_type),
669                            Part::Text(" -> "),
670                            Part::Term(param_type),
671                        ]);
672                    } else {
673                        write!(f, "Π({}:", param)?;
674                        pending.extend([
675                            Part::Term(body_type),
676                            Part::Text("). "),
677                            Part::Term(param_type),
678                        ]);
679                    }
680                }
681                Term::Lambda {
682                    param,
683                    param_type,
684                    body,
685                } => {
686                    write!(f, "λ({}:", param)?;
687                    pending.extend([Part::Term(body), Part::Text("). "), Part::Term(param_type)]);
688                }
689                Term::App(func, arg) => {
690                    f.write_str("(")?;
691                    let arrow = matches!(arg.as_ref(), Term::Pi { param, .. } if param == "_");
692                    pending.extend([
693                        Part::Text(if arrow { "))" } else { ")" }),
694                        Part::Term(arg),
695                        Part::Text(if arrow { " (" } else { " " }),
696                        Part::Term(func),
697                    ]);
698                }
699                Term::Match {
700                    discriminant,
701                    motive,
702                    cases,
703                } => {
704                    f.write_str("match ")?;
705                    pending.extend([
706                        Part::Cases(cases),
707                        Part::Text(" with "),
708                        Part::Term(motive),
709                        Part::Text(" return "),
710                        Part::Term(discriminant),
711                    ]);
712                }
713                Term::Fix { name, body } => {
714                    write!(f, "fix {}. ", name)?;
715                    pending.push(Part::Term(body));
716                }
717                Term::MutualFix { defs, index } => {
718                    f.write_str("mutualfix { ")?;
719                    pending.extend([
720                        Part::Index(*index),
721                        Part::Text(" }."),
722                        Part::Definitions(defs),
723                    ]);
724                }
725                Term::Let {
726                    name,
727                    ty,
728                    value,
729                    body,
730                } => {
731                    write!(f, "let {}:", name)?;
732                    pending.extend([
733                        Part::Term(body),
734                        Part::Text(" in "),
735                        Part::Term(value),
736                        Part::Text(" := "),
737                        Part::Term(ty),
738                    ]);
739                }
740                Term::Lit(literal) => write!(f, "{}", literal)?,
741                Term::Hole => f.write_str("_")?,
742                Term::Annotated { annotation, term } => {
743                    write!(f, "@[{}] ", annotation)?;
744                    pending.push(Part::Term(term));
745                }
746            },
747        }
748    }
749    Ok(())
750}
751
752impl fmt::Display for Universe {
753    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
754        display_syntax(SyntaxDisplayPart::Universe(self), f)
755    }
756}
757
758impl fmt::Display for Term {
759    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
760        display_syntax(SyntaxDisplayPart::Term(self), f)
761    }
762}
763
764/// Instantiate universe variables throughout a term: substitute every `Sort`'s level by
765/// `subst`. This specializes a universe-POLYMORPHIC term (`λA:Sort u. …`) to a concrete
766/// level (`u := Type 0`), yielding an ordinary term the kernel checks as-is — so one
767/// definition is reused at every level instead of duplicated.
768pub fn instantiate_universes(
769    term: &Term,
770    subst: &std::collections::HashMap<String, Universe>,
771) -> Term {
772    match term {
773        Term::Sort(u) => Term::Sort(u.substitute(subst)),
774        Term::Const { name, levels } => Term::Const {
775            name: name.clone(),
776            levels: levels.iter().map(|l| l.substitute(subst)).collect(),
777        },
778        Term::Var(_) | Term::Global(_) | Term::Lit(_) | Term::Hole => term.clone(),
779        Term::Pi {
780            param,
781            param_type,
782            body_type,
783        } => Term::Pi {
784            param: param.clone(),
785            param_type: Box::new(instantiate_universes(param_type, subst)),
786            body_type: Box::new(instantiate_universes(body_type, subst)),
787        },
788        Term::Lambda {
789            param,
790            param_type,
791            body,
792        } => Term::Lambda {
793            param: param.clone(),
794            param_type: Box::new(instantiate_universes(param_type, subst)),
795            body: Box::new(instantiate_universes(body, subst)),
796        },
797        Term::App(f, a) => Term::App(
798            Box::new(instantiate_universes(f, subst)),
799            Box::new(instantiate_universes(a, subst)),
800        ),
801        Term::Match {
802            discriminant,
803            motive,
804            cases,
805        } => Term::Match {
806            discriminant: Box::new(instantiate_universes(discriminant, subst)),
807            motive: Box::new(instantiate_universes(motive, subst)),
808            cases: cases
809                .iter()
810                .map(|c| instantiate_universes(c, subst))
811                .collect(),
812        },
813        Term::Fix { name, body } => Term::Fix {
814            name: name.clone(),
815            body: Box::new(instantiate_universes(body, subst)),
816        },
817        Term::MutualFix { defs, index } => Term::MutualFix {
818            defs: defs
819                .iter()
820                .map(|(n, b)| (n.clone(), instantiate_universes(b, subst)))
821                .collect(),
822            index: *index,
823        },
824        Term::Let {
825            name,
826            ty,
827            value,
828            body,
829        } => Term::Let {
830            name: name.clone(),
831            ty: Box::new(instantiate_universes(ty, subst)),
832            value: Box::new(instantiate_universes(value, subst)),
833            body: Box::new(instantiate_universes(body, subst)),
834        },
835        Term::Annotated { annotation, term } => Term::Annotated {
836            annotation: annotation.clone(),
837            term: Box::new(instantiate_universes(term, subst)),
838        },
839    }
840}
841
842// =================================================================================================
843// Universe-polymorphic references — the specification BOTH kernels implement
844// =================================================================================================
845//
846// `Term::Const { name, levels }` is the only instantiating form, and three places have to agree
847// about what it MEANS: the main kernel's typing rule, the de Bruijn re-checker's, and the
848// reducer's δ step. When they are written three times they disagree three ways — one of them
849// silently, by handing an ill-formed reference back as a settled normal form. So the decision
850// lives HERE, once, as pure syntax over `(declared params, stored type, level arguments)`, and
851// each kernel calls it with its own lookup. Sharing the SPECIFICATION is what makes two
852// independent implementations meaningful; sharing the arithmetic is what makes a bug invisible
853// in both.
854//
855// The rules, in the order they are decided:
856//
857// 1. **The level telescope.** An explicitly universe-polymorphic definition carries its own
858//    parameter list. Every other declaration — inductive, constructor, definition, axiom —
859//    AUTO-BINDS the free level variables of its stored type, in FIRST-OCCURRENCE order. That is
860//    Lean's auto-bound-implicit rule, and deriving it rather than storing it is why one
861//    registration path cannot disagree with another about what a name's telescope is.
862// 2. **Closure.** `free_level_vars(ty) ⊆ params`. A declaration carrying a level variable no
863//    parameter binds is refused at every reference — never instantiated with a partial
864//    substitution, which silently retains the free level and leaves the declaration usable at
865//    exactly one instantiation.
866// 3. **Arity.** `|levels| = |params|`, zipped POSITIONALLY. A level list on a monomorphic name
867//    is a statement about a declaration that does not exist, so it is refused too.
868// 4. **Bare references.** A bare `Term::Global` naming a declaration with a level telescope is an
869//    instance of it. At an application's head its levels are solved from the arguments
870//    (`type_checker::implicit_levels_for_head`); anywhere else it stands at the declaration's own
871//    parameters, as its type is read there. A stored term writes the second kind out
872//    ([`bare_references_at_own_levels`]), so rule 1 sees those levels and binds them, and an
873//    instantiation of the declaration around the reference moves them with everything else. Left
874//    implicit, `P2 : Sort u := B2` over `B2 : Sort u` would be checked where its own `u` and
875//    `B2`'s coincide and used where they do not: `P2.{0}` a proposition holding `B2`'s two
876//    constructors.
877
878/// Why a `Term::Const` reference could not be resolved. Every kernel and the reducer report the
879/// same three failures, so a reference refused by typing is never a normal form to the reducer.
880#[derive(Debug, Clone, PartialEq, Eq)]
881pub enum ConstError {
882    /// The level list does not match the declaration's telescope.
883    Arity {
884        name: String,
885        expected: usize,
886        got: usize,
887    },
888    /// The declaration's stored type mentions a level variable its parameter list does not bind.
889    /// Instantiating it would leave that level free, so the declaration is refused outright.
890    LevelNotClosed { name: String, level: String },
891    /// A level argument is or contains `SProp`, which is a sort and never a level.
892    SPropLevel { name: String },
893}
894
895impl fmt::Display for ConstError {
896    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
897        match self {
898            ConstError::Arity { name, expected, got } => write!(
899                f,
900                "universe-polymorphic '{name}' expects {expected} level argument(s), got {got}",
901            ),
902            ConstError::LevelNotClosed { name, level } => write!(
903                f,
904                "declaration '{name}' carries the level variable '{level}', which none of its \
905                 universe parameters binds — it could never be instantiated, so no reference to \
906                 it is well-formed",
907            ),
908            ConstError::SPropLevel { name } => write!(
909                f,
910                "'{name}' is instantiated at SProp, which is a sort and not a universe level: a level \
911                 ranges over Prop and the Type levels, so a polymorphic family checked as possibly \
912                 relevant can never become definitionally irrelevant",
913            ),
914        }
915    }
916}
917
918/// The free universe VARIABLES of a level expression, appended in first-occurrence order
919/// (duplicates suppressed).
920fn level_vars_of_universe(u: &Universe, out: &mut Vec<String>) {
921    match u {
922        Universe::SProp | Universe::Prop | Universe::Type(_) => {}
923        Universe::Var(v) => {
924            if !out.iter().any(|x| x == v) {
925                out.push(v.clone());
926            }
927        }
928        Universe::Succ(l) => level_vars_of_universe(l, out),
929        Universe::Max(a, b) | Universe::IMax(a, b) => {
930            level_vars_of_universe(a, out);
931            level_vars_of_universe(b, out);
932        }
933    }
934}
935
936/// The free universe variables of a TERM, in first-occurrence order under a left-to-right
937/// pre-order walk. This order is the positional contract a `Const`'s level list is zipped
938/// against, so it is part of the specification rather than an implementation detail: a
939/// declaration written `Π(A : Sort u). Π(B : Sort v). Sort v` has telescope `[u, v]`, and a
940/// swapped instantiation is therefore observable wherever the level expression is asymmetric.
941///
942/// Levels written INSIDE a nested `Const`'s own level arguments count: they are levels this
943/// declaration must supply, so they must be bound here.
944pub fn free_level_vars(term: &Term) -> Vec<String> {
945    #[cfg(test)]
946    LEVEL_COLLECTION_CALLS.with(|n| n.set(n.get() + 1));
947    let mut out = Vec::new();
948    collect_level_vars(term, &mut out);
949    out
950}
951
952fn collect_level_vars(term: &Term, out: &mut Vec<String>) {
953    // Pre-order, left to right, on a stack of its own: the order is the positional contract, and a
954    // door reads a term's levels before its depth limit has been checked.
955    let mut work = vec![term];
956    while let Some(t) = work.pop() {
957        match t {
958            Term::Sort(u) => level_vars_of_universe(u, out),
959            Term::Var(_) | Term::Global(_) | Term::Lit(_) | Term::Hole => {}
960            Term::Const { levels, .. } => {
961                for l in levels {
962                    level_vars_of_universe(l, out);
963                }
964            }
965            Term::Pi {
966                param_type,
967                body_type,
968                ..
969            } => {
970                work.push(body_type);
971                work.push(param_type);
972            }
973            Term::Lambda {
974                param_type, body, ..
975            } => {
976                work.push(body);
977                work.push(param_type);
978            }
979            Term::App(f, a) => {
980                work.push(a);
981                work.push(f);
982            }
983            Term::Match {
984                discriminant,
985                motive,
986                cases,
987            } => {
988                work.extend(cases.iter().rev());
989                work.push(motive);
990                work.push(discriminant);
991            }
992            Term::Fix { body, .. } => work.push(body),
993            Term::MutualFix { defs, .. } => work.extend(defs.iter().rev().map(|(_, b)| b)),
994            Term::Let {
995                ty, value, body, ..
996            } => {
997                work.push(body);
998                work.push(value);
999                work.push(ty);
1000            }
1001            Term::Annotated { term, .. } => work.push(term),
1002        }
1003    }
1004}
1005
1006/// The level telescope rule 1 gives a definition whose body mentions levels its type does not: the
1007/// type's level variables, then the body's, each in first-occurrence order. `None` when the body
1008/// adds none, so the type alone derives the telescope.
1009pub fn definition_telescope(ty: &Term, body: &Term) -> Option<Vec<String>> {
1010    let mut levels = free_level_vars(ty);
1011    let declared = levels.len();
1012    collect_level_vars(body, &mut levels);
1013    (levels.len() > declared).then_some(levels)
1014}
1015
1016/// `term`, in place, with each bare reference that is not an application's head written at the
1017/// level parameters `own_levels` gives its declaration (rule 4): `QUnit` becomes `QUnit.{u}`, and
1018/// `QUnit_rec P c x` keeps its bare head. A term with no such reference is read once and left as
1019/// it is. Both walks keep a stack of their own, since a door writes a term before its depth limit
1020/// has been checked.
1021pub fn bare_references_at_own_levels(
1022    term: &mut Term,
1023    own_levels: &dyn Fn(&str) -> Option<Vec<String>>,
1024) {
1025    if !mentions_bare_reference(term, own_levels) {
1026        return;
1027    }
1028    let mut work: Vec<(&mut Term, bool)> = vec![(term, false)];
1029    while let Some((node, head)) = work.pop() {
1030        if let Term::Global(name) = node {
1031            if !head {
1032                if let Some(params) = own_levels(name) {
1033                    let name = std::mem::take(name);
1034                    *node = Term::Const {
1035                        name,
1036                        levels: params.into_iter().map(Universe::Var).collect(),
1037                    };
1038                }
1039            }
1040            continue;
1041        }
1042        match node {
1043            Term::Sort(_)
1044            | Term::Var(_)
1045            | Term::Global(_)
1046            | Term::Const { .. }
1047            | Term::Lit(_)
1048            | Term::Hole => {}
1049            Term::App(f, a) => {
1050                work.push((f, true));
1051                work.push((a, false));
1052            }
1053            Term::Pi {
1054                param_type,
1055                body_type: body,
1056                ..
1057            }
1058            | Term::Lambda {
1059                param_type, body, ..
1060            } => {
1061                work.push((param_type, false));
1062                work.push((body, false));
1063            }
1064            Term::Match {
1065                discriminant,
1066                motive,
1067                cases,
1068            } => {
1069                work.push((discriminant, false));
1070                work.push((motive, false));
1071                work.extend(cases.iter_mut().map(|c| (c, false)));
1072            }
1073            Term::Fix { body, .. } => work.push((body, false)),
1074            Term::MutualFix { defs, .. } => work.extend(defs.iter_mut().map(|(_, b)| (b, false))),
1075            Term::Let {
1076                ty, value, body, ..
1077            } => {
1078                work.push((ty, false));
1079                work.push((value, false));
1080                work.push((body, false));
1081            }
1082            Term::Annotated { term, .. } => work.push((term, head)),
1083        }
1084    }
1085}
1086
1087/// Whether [`bare_references_at_own_levels`] has anything to write in `term`.
1088fn mentions_bare_reference(term: &Term, own_levels: &dyn Fn(&str) -> Option<Vec<String>>) -> bool {
1089    let mut work: Vec<(&Term, bool)> = vec![(term, false)];
1090    while let Some((node, head)) = work.pop() {
1091        match node {
1092            Term::Global(name) => {
1093                if !head && own_levels(name).is_some() {
1094                    return true;
1095                }
1096            }
1097            Term::Sort(_) | Term::Var(_) | Term::Const { .. } | Term::Lit(_) | Term::Hole => {}
1098            Term::App(f, a) => {
1099                work.push((f, true));
1100                work.push((a, false));
1101            }
1102            Term::Pi {
1103                param_type,
1104                body_type: body,
1105                ..
1106            }
1107            | Term::Lambda {
1108                param_type, body, ..
1109            } => {
1110                work.push((param_type, false));
1111                work.push((body, false));
1112            }
1113            Term::Match {
1114                discriminant,
1115                motive,
1116                cases,
1117            } => {
1118                work.push((discriminant, false));
1119                work.push((motive, false));
1120                work.extend(cases.iter().map(|c| (c, false)));
1121            }
1122            Term::Fix { body, .. } => work.push((body, false)),
1123            Term::MutualFix { defs, .. } => work.extend(defs.iter().map(|(_, b)| (b, false))),
1124            Term::Let {
1125                ty, value, body, ..
1126            } => {
1127                work.push((ty, false));
1128                work.push((value, false));
1129                work.push((body, false));
1130            }
1131            Term::Annotated { term, .. } => work.push((term, head)),
1132        }
1133    }
1134    false
1135}
1136
1137/// Whether `t` mentions any free universe VARIABLE — allocation-free and short-circuiting.
1138///
1139/// This is the GUARD in front of `free_level_vars`, and it is load-bearing for speed rather than
1140/// for meaning: the application rule asks the question at every node of every application, and
1141/// collecting a `Vec` there made registering the standard library two orders of magnitude slower.
1142/// Almost every declaration is monomorphic, so the answer is almost always "no" and must cost
1143/// nothing to learn.
1144pub fn mentions_level_var(t: &Term) -> bool {
1145    level_var_scan(t, &|_| true)
1146}
1147
1148/// Whether `t` mentions an unsolved level METAVARIABLE (a `?`-prefixed level variable) —
1149/// allocation-free and short-circuiting, for the same reason.
1150pub fn mentions_level_meta(t: &Term) -> bool {
1151    level_var_scan(t, &|v| is_level_meta(v))
1152}
1153
1154/// Short-circuiting search for a level variable satisfying `pred`.
1155///
1156/// Recursive and ALLOCATION-FREE by design. This runs at every application node of every
1157/// type-check, so a `Vec` here — even one that is usually empty — is a malloc per node; the
1158/// recursion instead costs a stack frame that the kernel's depth door already bounds, and the
1159/// walk short-circuits on the first hit.
1160fn level_var_scan(t: &Term, pred: &dyn Fn(&str) -> bool) -> bool {
1161    match t {
1162        Term::Sort(u) => universe_mentions(u, pred),
1163        Term::Var(_) | Term::Global(_) | Term::Lit(_) | Term::Hole => false,
1164        Term::Const { levels, .. } => levels.iter().any(|l| universe_mentions(l, pred)),
1165        Term::Pi {
1166            param_type,
1167            body_type,
1168            ..
1169        } => level_var_scan(param_type, pred) || level_var_scan(body_type, pred),
1170        Term::Lambda {
1171            param_type, body, ..
1172        } => level_var_scan(param_type, pred) || level_var_scan(body, pred),
1173        Term::App(f, a) => level_var_scan(f, pred) || level_var_scan(a, pred),
1174        Term::Match {
1175            discriminant,
1176            motive,
1177            cases,
1178        } => {
1179            level_var_scan(discriminant, pred)
1180                || level_var_scan(motive, pred)
1181                || cases.iter().any(|c| level_var_scan(c, pred))
1182        }
1183        Term::Fix { body, .. } => level_var_scan(body, pred),
1184        Term::MutualFix { defs, .. } => defs.iter().any(|(_, b)| level_var_scan(b, pred)),
1185        Term::Let {
1186            ty, value, body, ..
1187        } => level_var_scan(ty, pred) || level_var_scan(value, pred) || level_var_scan(body, pred),
1188        Term::Annotated { term, .. } => level_var_scan(term, pred),
1189    }
1190}
1191
1192/// Whether a level expression mentions a variable satisfying `pred` — allocation-free.
1193pub fn universe_mentions(u: &Universe, pred: &dyn Fn(&str) -> bool) -> bool {
1194    match u {
1195        Universe::SProp | Universe::Prop | Universe::Type(_) => false,
1196        Universe::Var(v) => pred(v),
1197        Universe::Succ(l) => universe_mentions(l, pred),
1198        Universe::Max(a, b) | Universe::IMax(a, b) => {
1199            universe_mentions(a, pred) || universe_mentions(b, pred)
1200        }
1201    }
1202}
1203
1204/// The level telescope of a declaration (rule 1 above). `declared` is `Some` only for an
1205/// explicitly universe-polymorphic definition, which carries its own ordered parameter list;
1206/// every other declaration auto-binds what its type mentions.
1207pub fn level_telescope(declared: Option<&[String]>, ty: &Term) -> Vec<String> {
1208    match declared {
1209        Some(params) => params.to_vec(),
1210        None => free_level_vars(ty),
1211    }
1212}
1213
1214/// Resolve a `Term::Const { name, levels }` against a declaration, producing the universe
1215/// substitution to apply to its type AND its body (rules 1-3 above). This is the ONE place the
1216/// decision is made; `instantiate_universes` applies the result.
1217pub fn resolve_const_levels(
1218    name: &str,
1219    declared: Option<&[String]>,
1220    ty: &Term,
1221    levels: &[Universe],
1222) -> Result<std::collections::HashMap<String, Universe>, ConstError> {
1223    // Explicit telescopes already own their ordered names. Validate closure
1224    // with the existing left-to-right short-circuiting scan; only a diagnostic
1225    // allocates an offending name. Inferred telescopes are closed by construction.
1226    let inferred;
1227    let params = match declared {
1228        Some(params) => {
1229            let missing = std::cell::RefCell::new(None);
1230            level_var_scan(ty, &|level| {
1231                if params.iter().any(|param| param == level) {
1232                    return false;
1233                }
1234                *missing.borrow_mut() = Some(level.to_owned());
1235                true
1236            });
1237            if let Some(level) = missing.into_inner() {
1238                return Err(ConstError::LevelNotClosed {
1239                    name: name.to_owned(),
1240                    level,
1241                });
1242            }
1243            params
1244        }
1245        None => {
1246            inferred = free_level_vars(ty);
1247            &inferred
1248        }
1249    };
1250    if params.len() != levels.len() {
1251        return Err(ConstError::Arity {
1252            name: name.to_string(),
1253            expected: params.len(),
1254            got: levels.len(),
1255        });
1256    }
1257    if levels.iter().any(Universe::mentions_sprop) {
1258        return Err(ConstError::SPropLevel {
1259            name: name.to_string(),
1260        });
1261    }
1262    Ok(params.iter().cloned().zip(levels.iter().cloned()).collect())
1263}
1264
1265// =================================================================================================
1266// Level metavariables — implicit instantiation at a bare reference
1267// =================================================================================================
1268//
1269// A bare `Term::Global` naming a declaration with a level telescope carries NO levels, so the
1270// levels have to be solved from the use site — which is what Lean's elaborator does and what a
1271// Mathlib file relies on in almost every line. The representation reuses the elaborator's own
1272// convention rather than adding a `Universe` variant: a level metavariable is a `Universe::Var`
1273// whose name begins with `?`, a spelling no source-level universe parameter can have.
1274//
1275// That choice is load-bearing for SOUNDNESS, not only for compatibility: an UNSOLVED `?`-level
1276// is an ordinary level variable to `level_leq`, where `Type 0 ⋠ ?u` because a variable ranges
1277// over all of ℕ including `Prop`. So a metavariable that never gets solved makes the reference
1278// FAIL rather than succeed — the conservative direction. Defaulting it to `Type 0` (the tempting
1279// move) would do the opposite.
1280
1281/// The marker a level metavariable's name begins with — the elaborator's convention for a term
1282/// metavariable, reused so the two never collide with a source-level universe parameter.
1283pub const LEVEL_META_MARKER: char = '?';
1284
1285/// Whether a universe variable name denotes a metavariable awaiting a solution.
1286pub fn is_level_meta(name: &str) -> bool {
1287    name.starts_with(LEVEL_META_MARKER)
1288}
1289
1290/// Fresh level metavariables for `params`, named after the declaration they came from.
1291///
1292/// The name is DERIVED (`?u@Box`) rather than drawn from a counter, so the kernel stays a pure
1293/// function of its input: two runs, two threads and two orders of evaluation produce the same
1294/// term and the same diagnostic. Two references to the SAME declaration therefore share a
1295/// metavariable name — which is harmless, because each application rule solves its own
1296/// substitution locally, and in the one case where two unsolved copies could meet in a single
1297/// level expression the shared name forces them EQUAL, which can only refuse a term, never
1298/// admit one.
1299pub fn fresh_level_metas(
1300    owner: &str,
1301    params: &[String],
1302) -> std::collections::HashMap<String, Universe> {
1303    params
1304        .iter()
1305        .map(|p| {
1306            (
1307                p.clone(),
1308                Universe::Var(format!("{LEVEL_META_MARKER}{p}@{owner}")),
1309            )
1310        })
1311        .collect()
1312}
1313
1314/// Solve level metavariables by matching an expected type (the PATTERN, which may contain
1315/// metavariables) against an actual one, recording solutions in `subst`.
1316///
1317/// Only a BARE metavariable is solved, and only once: a first solution wins, and a compound
1318/// level containing a metavariable (`max ?u v`) is left alone rather than inverted. This is a
1319/// heuristic for CHOOSING an instantiation, never a substitute for checking it — the caller
1320/// still checks the argument against the substituted domain, so an unhelpful choice makes the
1321/// application fail rather than succeed.
1322pub fn unify_levels(
1323    pattern: &Term,
1324    actual: &Term,
1325    subst: &mut std::collections::HashMap<String, Universe>,
1326) {
1327    match (pattern.peel_annotations(), actual.peel_annotations()) {
1328        (Term::Sort(p), Term::Sort(a)) => unify_level(p, a, subst),
1329        (
1330            Term::Pi {
1331                param_type: p1,
1332                body_type: b1,
1333                ..
1334            },
1335            Term::Pi {
1336                param_type: p2,
1337                body_type: b2,
1338                ..
1339            },
1340        ) => {
1341            unify_levels(p1, p2, subst);
1342            unify_levels(b1, b2, subst);
1343        }
1344        (
1345            Term::Lambda {
1346                param_type: p1,
1347                body: b1,
1348                ..
1349            },
1350            Term::Lambda {
1351                param_type: p2,
1352                body: b2,
1353                ..
1354            },
1355        ) => {
1356            unify_levels(p1, p2, subst);
1357            unify_levels(b1, b2, subst);
1358        }
1359        (Term::App(f1, a1), Term::App(f2, a2)) => {
1360            unify_levels(f1, f2, subst);
1361            unify_levels(a1, a2, subst);
1362        }
1363        (
1364            Term::Const {
1365                name: n1,
1366                levels: l1,
1367            },
1368            Term::Const {
1369                name: n2,
1370                levels: l2,
1371            },
1372        ) if n1 == n2 && l1.len() == l2.len() => {
1373            for (p, a) in l1.iter().zip(l2.iter()) {
1374                unify_level(p, a, subst);
1375            }
1376        }
1377        _ => {}
1378    }
1379}
1380
1381/// The level half of [`unify_levels`]: solve a bare metavariable, else look inside a matching
1382/// algebraic shape.
1383fn unify_level(
1384    pattern: &Universe,
1385    actual: &Universe,
1386    subst: &mut std::collections::HashMap<String, Universe>,
1387) {
1388    match pattern {
1389        Universe::Var(v) if is_level_meta(v) => {
1390            // An occurs check: solving `?u := succ ?u` would build a cyclic level.
1391            let mut occurring = Vec::new();
1392            level_vars_of_universe(actual, &mut occurring);
1393            if occurring.iter().any(|x| x == v) {
1394                return;
1395            }
1396            subst
1397                .entry(v.clone())
1398                .or_insert_with(|| actual.least_level());
1399        }
1400        // A concrete level is a successor too: `Type 0` is `succ Prop` and `Type n` is
1401        // `succ (Type (n-1))`, so `Type u` meets `Type 1` at `u := Type 0` exactly as it meets
1402        // `succ (Type 0)`.
1403        Universe::Succ(p) => match actual {
1404            Universe::Succ(a) => unify_level(p, a, subst),
1405            Universe::Type(0) => unify_level(p, &Universe::Prop, subst),
1406            Universe::Type(n) => unify_level(p, &Universe::Type(n - 1), subst),
1407            _ => {}
1408        },
1409        Universe::Max(p1, p2) => {
1410            if let Universe::Max(a1, a2) = actual {
1411                unify_level(p1, a1, subst);
1412                unify_level(p2, a2, subst);
1413            }
1414        }
1415        Universe::IMax(p1, p2) => {
1416            if let Universe::IMax(a1, a2) = actual {
1417                unify_level(p1, a1, subst);
1418                unify_level(p2, a2, subst);
1419            }
1420        }
1421        _ => {}
1422    }
1423}
1424
1425#[cfg(test)]
1426#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/term/universe_algebra_tests.rs"]
1427mod universe_algebra_tests;
1428
1429#[cfg(test)]
1430#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/term/display_date_and_serde_tests.rs"]
1431mod display_date_and_serde_tests;
1432
1433#[cfg(test)]
1434thread_local! {static LEVEL_COLLECTION_CALLS: std::cell::Cell<usize> = const {std::cell::Cell::new(0)};}
1435
1436#[cfg(test)]
1437#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/term/borrowed_telescope_controls.rs"]
1438mod borrowed_telescope_controls;
1439
1440#[cfg(test)]
1441#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/term/universe_constructor_controls.rs"]
1442mod universe_constructor_controls;
1443
1444#[cfg(test)]
1445#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/term/level_order_controls.rs"]
1446mod level_order_controls;