Skip to main content

logicaffeine_kernel/
elaborate.rs

1//! R4 — the elaborator: metavariables, unification, and implicit-argument inference.
2//!
3//! The layer between the surface language and the trusted kernel. A user writes `id 0`
4//! and means `id Nat 0`; `length xs` and means `length Nat xs`. The elaborator fills the
5//! gaps: it inserts METAVARIABLES (`?A`, …) for the omitted/implicit arguments and SOLVES
6//! them by UNIFICATION against the types it infers, producing a fully-explicit kernel
7//! `Term` that `infer_type` then re-checks. Nothing here is trusted — elaboration only
8//! *constructs* a term; the kernel still certifies it.
9//!
10//! A metavariable is represented as a `Term::Var` whose name starts with `?` (a character
11//! no real binder uses), so the whole machinery rides on the existing `Term` with no new
12//! variant. Scope: first-order unification with the occurs-check, and implicit-argument
13//! insertion driven by an explicit implicit/explicit mask — the core that makes the
14//! surface usable. (Higher-order / pattern unification is the next layer.)
15
16use std::collections::HashMap;
17
18use crate::error::{KernelError, KernelResult};
19use crate::reduction::normalize_elab as normalize;
20use crate::term::Term;
21use crate::type_checker::substitute;
22use crate::{infer_type, Context};
23
24/// Reserved head marking a surface anonymous constructor `⟨e₁, …, eₙ⟩` (E3). The parser
25/// emits `⟨anon⟩ e₁ … eₙ`; the elaborator (this module) rewrites it to the sole constructor
26/// of the expected inductive and then discards the marker — it NEVER reaches a kernel term.
27/// The name contains `⟨`/`⟩`, characters the identifier lexer cannot produce, so it can
28/// never collide with a user global. Like the `?`-prefixed metavariables above, this rides
29/// on the existing `Term` with no new variant.
30pub const ANON_CTOR_MARKER: &str = "⟨anon⟩";
31
32/// Reserved head marking surface dot notation `receiver.field` (E4). The parser emits
33/// `⟨proj⟩ receiver field` (the field name carried as a `Global`); the elaborator rewrites it
34/// to the projection `H_field params… receiver` and discards the marker. Collision-proof for
35/// the same reason as [`ANON_CTOR_MARKER`].
36pub const DOT_MARKER: &str = "⟨proj⟩";
37
38/// A surface-sugar application recognized by its reserved marker head.
39enum Sugar<'a> {
40    /// `⟨e₁, …, eₙ⟩` — an anonymous constructor with these component terms.
41    AnonCtor(Vec<&'a Term>),
42    /// `receiver.field` — a projection.
43    Dot(&'a Term, &'a str),
44}
45
46/// Recognize a marker-headed surface-sugar application (anonymous constructor or dot
47/// notation), returning its shape, or `None` for an ordinary term. Decomposing the spine
48/// here means a bare nullary `⟨⟩` (just the marker global) and a nested one are both caught.
49fn as_surface_sugar(term: &Term) -> Option<Sugar<'_>> {
50    // Fast path (the common case): walk to the spine head WITHOUT allocating and bail unless
51    // it is a marker — so an ordinary term costs only a pointer chase per `elaborate_in` call.
52    let mut head = term;
53    while let Term::App(f, _) = head {
54        head = f;
55    }
56    let is_anon = matches!(head, Term::Global(n) if n == ANON_CTOR_MARKER);
57    let is_dot = matches!(head, Term::Global(n) if n == DOT_MARKER);
58    if !is_anon && !is_dot {
59        return None;
60    }
61    // A marker head — now decompose the (rare) spine.
62    let mut args: Vec<&Term> = Vec::new();
63    let mut cur = term;
64    while let Term::App(f, a) = cur {
65        args.push(a);
66        cur = f;
67    }
68    args.reverse();
69    if is_anon {
70        Some(Sugar::AnonCtor(args))
71    } else if let [_, Term::Global(field)] = args.as_slice() {
72        Some(Sugar::Dot(args[0], field))
73    } else {
74        None
75    }
76}
77
78/// Elaborate a marker-headed surface-sugar term to a fully-explicit kernel term paired with
79/// its inferred type. Shared by [`elaborate_in`] (so NESTED sugar inside a field or receiver
80/// resolves with its expected type) and [`elab_surface`] (the top-level surface entry).
81fn elaborate_sugar(
82    ctx: &Context,
83    mctx: &mut MetaCtx,
84    sugar: Sugar<'_>,
85    expected: Option<&Term>,
86) -> KernelResult<(Term, Term)> {
87    let result = match sugar {
88        Sugar::AnonCtor(comps) => {
89            let expected = expected.ok_or_else(|| {
90                KernelError::CertificationError(
91                    "anonymous constructor `⟨…⟩` needs a known expected type to choose its \
92                     inductive — annotate it or use it where a type is expected"
93                        .to_string(),
94                )
95            })?;
96            let comps: Vec<Term> = comps.into_iter().cloned().collect();
97            elaborate_anon_ctor(ctx, mctx, expected, &comps)?
98        }
99        Sugar::Dot(receiver, field) => elaborate_dot(ctx, mctx, receiver, field)?,
100    };
101    let ty = infer_type(ctx, &result)?;
102    Ok((result, ty))
103}
104
105/// The metavariable context: fresh-name supply + the substitution being solved.
106#[derive(Debug, Default, Clone)]
107pub struct MetaCtx {
108    solutions: HashMap<String, Term>,
109    counter: usize,
110    holes: Vec<Hole>,
111}
112
113/// A hole (`_`) the elaborator met: its metavariable, the local context around it, and the type its
114/// position asks for — everything a tactic needs to make it a goal.
115#[derive(Debug, Clone)]
116pub(crate) struct Hole {
117    pub(crate) name: String,
118    pub(crate) scope: Vec<(String, Term)>,
119    pub(crate) ty: Term,
120}
121
122impl MetaCtx {
123    pub fn new() -> Self {
124        MetaCtx::default()
125    }
126
127    /// A fresh, unsolved metavariable `?n`.
128    pub fn fresh(&mut self) -> Term {
129        let m = Term::Var(format!("?{}", self.counter));
130        self.counter += 1;
131        m
132    }
133
134    /// The solution recorded for metavariable `name`, if any.
135    pub fn solution(&self, name: &str) -> Option<&Term> {
136        self.solutions.get(name)
137    }
138
139    /// Directly bind metavariable `name := term`, WITHOUT normalizing `term`. Used when
140    /// the term is already known well-typed and should be kept structured (e.g. a resolved
141    /// typeclass instance `list_inst Nat (mk Nat Zero)`, which must not be δ-unfolded into
142    /// its body). The kernel re-checks the assembled term regardless.
143    pub fn solve(&mut self, name: &str, term: Term) {
144        self.solutions.insert(name.to_string(), term);
145    }
146
147    /// The holes elaborated so far, in the order they were met.
148    pub(crate) fn holes(&self) -> &[Hole] {
149        &self.holes
150    }
151
152    fn declare_hole(&mut self, meta: &Term, scope: &[(String, Term)], ty: &Term) {
153        if let Term::Var(name) = meta {
154            self.holes.push(Hole {
155                name: name.clone(),
156                scope: scope.to_vec(),
157                ty: ty.clone(),
158            });
159        }
160    }
161}
162
163/// Whether `name` denotes a metavariable (the `?`-prefix convention).
164pub fn is_meta(name: &str) -> bool {
165    name.starts_with('?')
166}
167
168/// Substitute every solved metavariable throughout `term` (transitively, since a solution
169/// may itself mention other metavariables — the occurs-check keeps this terminating).
170pub fn instantiate(term: &Term, mctx: &MetaCtx) -> Term {
171    match term {
172        Term::Var(name) if is_meta(name) => match mctx.solutions.get(name) {
173            Some(sol) => instantiate(sol, mctx),
174            None => term.clone(),
175        },
176        Term::Var(_) | Term::Global(_) | Term::Sort(_) | Term::Lit(_) | Term::Hole => term.clone(),
177        Term::Const { name, levels } => Term::Const {
178            name: name.clone(),
179            levels: levels.clone(),
180        },
181        Term::Pi {
182            param,
183            param_type,
184            body_type,
185        } => Term::Pi {
186            param: param.clone(),
187            param_type: Box::new(instantiate(param_type, mctx)),
188            body_type: Box::new(instantiate(body_type, mctx)),
189        },
190        Term::Lambda {
191            param,
192            param_type,
193            body,
194        } => Term::Lambda {
195            param: param.clone(),
196            param_type: Box::new(instantiate(param_type, mctx)),
197            body: Box::new(instantiate(body, mctx)),
198        },
199        Term::App(f, a) => Term::App(
200            Box::new(instantiate(f, mctx)),
201            Box::new(instantiate(a, mctx)),
202        ),
203        Term::Match {
204            discriminant,
205            motive,
206            cases,
207        } => Term::Match {
208            discriminant: Box::new(instantiate(discriminant, mctx)),
209            motive: Box::new(instantiate(motive, mctx)),
210            cases: cases.iter().map(|c| instantiate(c, mctx)).collect(),
211        },
212        Term::Fix { name, body } => Term::Fix {
213            name: name.clone(),
214            body: Box::new(instantiate(body, mctx)),
215        },
216        Term::MutualFix { defs, index } => Term::MutualFix {
217            defs: defs
218                .iter()
219                .map(|(n, b)| (n.clone(), instantiate(b, mctx)))
220                .collect(),
221            index: *index,
222        },
223        Term::Let {
224            name,
225            ty,
226            value,
227            body,
228        } => Term::Let {
229            name: name.clone(),
230            ty: Box::new(instantiate(ty, mctx)),
231            value: Box::new(instantiate(value, mctx)),
232            body: Box::new(instantiate(body, mctx)),
233        },
234        Term::Annotated { annotation, term } => Term::Annotated {
235            annotation: annotation.clone(),
236            term: Box::new(instantiate(term, mctx)),
237        },
238    }
239}
240
241/// Whether `term` mentions any metavariable, solved or not.
242pub(crate) fn mentions_meta(term: &Term) -> bool {
243    match term {
244        Term::Var(name) => is_meta(name),
245        Term::Global(_) | Term::Sort(_) | Term::Lit(_) | Term::Hole | Term::Const { .. } => false,
246        Term::Pi {
247            param_type,
248            body_type,
249            ..
250        } => mentions_meta(param_type) || mentions_meta(body_type),
251        Term::Lambda {
252            param_type, body, ..
253        } => mentions_meta(param_type) || mentions_meta(body),
254        Term::App(f, a) => mentions_meta(f) || mentions_meta(a),
255        Term::Match {
256            discriminant,
257            motive,
258            cases,
259        } => {
260            mentions_meta(discriminant) || mentions_meta(motive) || cases.iter().any(mentions_meta)
261        }
262        Term::Fix { body, .. } => mentions_meta(body),
263        Term::MutualFix { defs, .. } => defs.iter().any(|(_, body)| mentions_meta(body)),
264        Term::Let {
265            ty, value, body, ..
266        } => mentions_meta(ty) || mentions_meta(value) || mentions_meta(body),
267        Term::Annotated { term, .. } => mentions_meta(term),
268    }
269}
270
271/// Whether the metavariable `m` occurs in `term` — the occurs-check that keeps the
272/// solution acyclic (`?m := f ?m` would loop).
273fn occurs(m: &str, term: &Term) -> bool {
274    match term {
275        Term::Var(name) => name == m,
276        Term::Global(_) | Term::Sort(_) | Term::Lit(_) | Term::Hole | Term::Const { .. } => false,
277        Term::Pi {
278            param_type,
279            body_type,
280            ..
281        } => occurs(m, param_type) || occurs(m, body_type),
282        Term::Lambda {
283            param_type, body, ..
284        } => occurs(m, param_type) || occurs(m, body),
285        Term::App(f, a) => occurs(m, f) || occurs(m, a),
286        Term::Match {
287            discriminant,
288            motive,
289            cases,
290        } => occurs(m, discriminant) || occurs(m, motive) || cases.iter().any(|c| occurs(m, c)),
291        Term::Fix { body, .. } => occurs(m, body),
292        Term::MutualFix { defs, .. } => defs.iter().any(|(_, b)| occurs(m, b)),
293        Term::Let {
294            ty, value, body, ..
295        } => occurs(m, ty) || occurs(m, value) || occurs(m, body),
296        Term::Annotated { term, .. } => occurs(m, term),
297    }
298}
299
300/// `instantiate` then weak-head-normalize — the form unification compares.
301fn resolve(ctx: &Context, mctx: &MetaCtx, t: &Term) -> Term {
302    normalize(ctx, &instantiate(t, mctx))
303}
304
305/// Expose only the Pi needed by the application telescope. An already-visible
306/// Pi does not need its potentially enormous domain/codomain normalized merely
307/// to peel a binder. Arguments and the assembled term still undergo all normal
308/// elaborator and kernel checks. Active rewrites retain the old full path;
309/// hidden heads retain elaborator (including irreducible) transparency.
310fn resolve_application_pi(ctx: &Context, mctx: &MetaCtx, t: &Term) -> Term {
311    let instantiated = instantiate(t, mctx);
312    if ctx.simp_rules().is_empty() && matches!(instantiated, Term::Pi { .. }) {
313        instantiated
314    } else {
315        normalize(ctx, &instantiated)
316    }
317}
318
319/// First-order unification of `a` and `b`, solving metavariables into `mctx`. Returns
320/// whether they were made equal. A metavariable unifies with anything (after the
321/// occurs-check); everything else decomposes structurally.
322pub fn unify(ctx: &Context, mctx: &mut MetaCtx, a: &Term, b: &Term) -> bool {
323    unify_in(ctx, mctx, &[], a, b)
324}
325
326/// Unify `a` and `b` under a LOCAL CONTEXT `lctx` (`(name, type)` of the bound variables
327/// in scope). The local context enables higher-order PATTERN (Miller) unification:
328/// `?M x̄ =?= t`, where `?M` is a metavariable applied to distinct bound variables `x̄`,
329/// is solved by `?M := λx̄. t`. The top-level [`unify`] runs with an empty context, so its
330/// behavior — and every existing caller — is the first-order one.
331pub fn unify_in(
332    ctx: &Context,
333    mctx: &mut MetaCtx,
334    lctx: &[(String, Term)],
335    a: &Term,
336    b: &Term,
337) -> bool {
338    // Two terms that are already the same term, with no metavariable left to solve, unify with
339    // nothing assigned: say so before normalizing either (a declaration whose inferred type IS its
340    // declared type is the common case, and its normal form can be enormous).
341    let (a, b) = (instantiate(a, mctx), instantiate(b, mctx));
342    if !mentions_meta(&a) && crate::type_checker::alpha_equivalent(&a, &b) {
343        return true;
344    }
345    if positive::equivalent_scoped(ctx, &a, &b) {
346        return true;
347    }
348    #[cfg(test)]
349    LAZY_UNIFY_FULL_NORMALIZATIONS.with(|n| n.set(n.get() + 1));
350    let a = normalize(ctx, &a);
351    let b = normalize(ctx, &b);
352    // A normal form can be far deeper than the written terms the caller's stack was sized for (a
353    // statement over literal arithmetic the positive check declines normalizes to a deep partial
354    // term), so the structural walk runs on a stack sized for what normalization produced, and a
355    // comparison past the kernel's depth door is a recorded resource stop, as in conversion.
356    let depth = crate::term_store::term_depth(&a).max(crate::term_store::term_depth(&b));
357    if depth > crate::type_checker::MAX_TERM_DEPTH {
358        crate::reduction::record_resource_stop(crate::Unreduced::TooDeep);
359        return false;
360    }
361    crate::term_store::grow_stack_for_depth(depth, move || unify_normal(ctx, mctx, lctx, a, b))
362}
363
364/// [`unify_in`] past normalization: `a` and `b` are normal forms, and the stack is sized for them.
365fn unify_normal(
366    ctx: &Context,
367    mctx: &mut MetaCtx,
368    lctx: &[(String, Term)],
369    a: Term,
370    b: Term,
371) -> bool {
372    if let Term::Var(n) = &a {
373        if is_meta(n) {
374            return assign(ctx, mctx, n, &b);
375        }
376    }
377    if let Term::Var(n) = &b {
378        if is_meta(n) {
379            return assign(ctx, mctx, n, &a);
380        }
381    }
382
383    // Higher-order PATTERN unification: `?M x̄ =?= t` ⇒ `?M := λx̄. t`.
384    if let Some(result) = try_pattern(mctx, lctx, &a, &b) {
385        return result;
386    }
387    if let Some(result) = try_pattern(mctx, lctx, &b, &a) {
388        return result;
389    }
390
391    // η-unification: `λx:A. body =?= t` (with `t` not a λ) ⇒ `body =?= t x` under the
392    // binder, and symmetrically — so a function and its η-expansion unify.
393    match (&a, &b) {
394        (
395            Term::Lambda {
396                param,
397                param_type,
398                body,
399            },
400            other,
401        )
402        | (
403            other,
404            Term::Lambda {
405                param,
406                param_type,
407                body,
408            },
409        ) if !matches!(other, Term::Lambda { .. }) => {
410            let applied = Term::App(Box::new(other.clone()), Box::new(Term::Var(param.clone())));
411            let mut lctx2 = lctx.to_vec();
412            lctx2.push((param.clone(), (**param_type).clone()));
413            return unify_in(ctx, mctx, &lctx2, body, &applied);
414        }
415        _ => {}
416    }
417
418    match (&a, &b) {
419        // A level METAVARIABLE (a universe-polymorphic head's level, instantiated for this
420        // application) is solved by the kernel's application rule when the finished term is
421        // checked; the elaborator has no level assignment of its own and does not refuse one.
422        (Term::Sort(u), Term::Sort(v)) => {
423            u.equiv(v)
424                || crate::term::mentions_level_meta(&a)
425                || crate::term::mentions_level_meta(&b)
426        }
427        (Term::Global(x), Term::Global(y)) => x == y,
428        (Term::Var(x), Term::Var(y)) => x == y,
429        (Term::Lit(x), Term::Lit(y)) => x == y,
430        (Term::Hole, Term::Hole) => true,
431        (Term::App(f1, a1), Term::App(f2, a2)) => {
432            unify_in(ctx, mctx, lctx, f1, f2) && unify_in(ctx, mctx, lctx, a1, a2)
433        }
434        (
435            Term::Pi {
436                param: p1,
437                param_type: t1,
438                body_type: b1,
439            },
440            Term::Pi {
441                param: p2,
442                param_type: t2,
443                body_type: b2,
444            },
445        ) => unify_binder(ctx, mctx, lctx, t1, b1, p1, t2, b2, p2),
446        (
447            Term::Lambda {
448                param: p1,
449                param_type: t1,
450                body: b1,
451            },
452            Term::Lambda {
453                param: p2,
454                param_type: t2,
455                body: b2,
456            },
457        ) => unify_binder(ctx, mctx, lctx, t1, b1, p1, t2, b2, p2),
458        (
459            Term::Const {
460                name: n1,
461                levels: l1,
462            },
463            Term::Const {
464                name: n2,
465                levels: l2,
466            },
467        ) => n1 == n2 && l1.len() == l2.len() && l1.iter().zip(l2.iter()).all(|(x, y)| x.equiv(y)),
468        _ => false,
469    }
470}
471
472/// Try to solve a Miller pattern `a = ?M x̄ =?= b`. Returns `None` if `a` is not a pattern
473/// (the caller falls through to structural unification), `Some(true)` if solved, and
474/// `Some(false)` if it IS a pattern but unsolvable (occurs-check / an out-of-scope
475/// variable on the right). The arguments `x̄` must be DISTINCT bound variables of `lctx`,
476/// and `b` may mention only those variables (plus globals/metavariables).
477fn try_pattern(mctx: &mut MetaCtx, lctx: &[(String, Term)], a: &Term, b: &Term) -> Option<bool> {
478    let (head, args) = spine(a);
479    if args.is_empty() {
480        return None;
481    }
482    let meta = match &head {
483        Term::Var(m) if is_meta(m) && mctx.solution(m).is_none() => m.clone(),
484        _ => return None,
485    };
486    // Every argument must be a distinct bound variable of the local context.
487    let mut var_names: Vec<String> = Vec::new();
488    for arg in &args {
489        match arg {
490            Term::Var(v) if !is_meta(v) && lctx.iter().any(|(n, _)| n == v) => {
491                if var_names.iter().any(|u| u == v) {
492                    return None; // a repeated argument — not a pattern
493                }
494                var_names.push(v.clone());
495            }
496            _ => return None, // a non-variable argument — not a pattern
497        }
498    }
499    // It IS a pattern; now decide whether it is solvable.
500    if occurs(&meta, b) {
501        return Some(false); // `?M` occurs in `t` — cyclic
502    }
503    if !pattern_rhs_in_scope(b, &var_names, &mut Vec::new()) {
504        return Some(false); // `t` mentions a variable we cannot abstract
505    }
506    // Solve `?M := λx̄. t`, taking each binder's type from the local context.
507    let mut sol = b.clone();
508    for name in var_names.iter().rev() {
509        let ty = lctx
510            .iter()
511            .find(|(n, _)| n == name)
512            .map(|(_, t)| t.clone())
513            .unwrap_or(Term::Hole);
514        sol = Term::Lambda {
515            param: name.clone(),
516            param_type: Box::new(ty),
517            body: Box::new(sol),
518        };
519    }
520    mctx.solve(&meta, sol);
521    Some(true)
522}
523
524/// Whether every FREE variable of `t` (tracking binders in `bound`) is either a
525/// metavariable, bound inside `t`, or one of the `allowed` pattern arguments — the
526/// condition for `λallowed. t` to be well-scoped.
527fn pattern_rhs_in_scope(t: &Term, allowed: &[String], bound: &mut Vec<String>) -> bool {
528    match t {
529        Term::Var(v) => {
530            is_meta(v) || bound.iter().any(|b| b == v) || allowed.iter().any(|a| a == v)
531        }
532        Term::Sort(_) | Term::Global(_) | Term::Lit(_) | Term::Hole | Term::Const { .. } => true,
533        Term::App(f, a) => {
534            pattern_rhs_in_scope(f, allowed, bound) && pattern_rhs_in_scope(a, allowed, bound)
535        }
536        Term::Pi {
537            param,
538            param_type,
539            body_type,
540        } => {
541            if !pattern_rhs_in_scope(param_type, allowed, bound) {
542                return false;
543            }
544            bound.push(param.clone());
545            let ok = pattern_rhs_in_scope(body_type, allowed, bound);
546            bound.pop();
547            ok
548        }
549        Term::Lambda {
550            param,
551            param_type,
552            body,
553        } => {
554            if !pattern_rhs_in_scope(param_type, allowed, bound) {
555                return false;
556            }
557            bound.push(param.clone());
558            let ok = pattern_rhs_in_scope(body, allowed, bound);
559            bound.pop();
560            ok
561        }
562        Term::Fix { name, body } => {
563            bound.push(name.clone());
564            let ok = pattern_rhs_in_scope(body, allowed, bound);
565            bound.pop();
566            ok
567        }
568        Term::MutualFix { defs, .. } => {
569            for (n, _) in defs {
570                bound.push(n.clone());
571            }
572            let ok = defs
573                .iter()
574                .all(|(_, b)| pattern_rhs_in_scope(b, allowed, bound));
575            for _ in defs {
576                bound.pop();
577            }
578            ok
579        }
580        Term::Match {
581            discriminant,
582            motive,
583            cases,
584        } => {
585            pattern_rhs_in_scope(discriminant, allowed, bound)
586                && pattern_rhs_in_scope(motive, allowed, bound)
587                && cases
588                    .iter()
589                    .all(|c| pattern_rhs_in_scope(c, allowed, bound))
590        }
591        Term::Let {
592            name,
593            ty,
594            value,
595            body,
596        } => {
597            if !pattern_rhs_in_scope(ty, allowed, bound)
598                || !pattern_rhs_in_scope(value, allowed, bound)
599            {
600                return false;
601            }
602            bound.push(name.clone());
603            let ok = pattern_rhs_in_scope(body, allowed, bound);
604            bound.pop();
605            ok
606        }
607        Term::Annotated { term, .. } => pattern_rhs_in_scope(term, allowed, bound),
608    }
609}
610
611/// Decompose an application spine `head a0 a1 …` into its head and arguments (in order).
612fn spine(t: &Term) -> (Term, Vec<Term>) {
613    let mut args = Vec::new();
614    let mut cur = t;
615    while let Term::App(f, a) = cur {
616        args.push((**a).clone());
617        cur = f;
618    }
619    args.reverse();
620    (cur.clone(), args)
621}
622
623/// Unify two binders (`Π`/`λ`): their domains, then their bodies α-renamed to a common
624/// binder name — under a local context EXTENDED with that binder, so pattern unification
625/// can fire on metavariables applied to it.
626#[allow(clippy::too_many_arguments)]
627fn unify_binder(
628    ctx: &Context,
629    mctx: &mut MetaCtx,
630    lctx: &[(String, Term)],
631    dom1: &Term,
632    body1: &Term,
633    p1: &str,
634    dom2: &Term,
635    body2: &Term,
636    p2: &str,
637) -> bool {
638    if !unify_in(ctx, mctx, lctx, dom1, dom2) {
639        return false;
640    }
641    let body2 = if p1 == p2 {
642        body2.clone()
643    } else {
644        substitute(body2, p2, &Term::Var(p1.to_string()))
645    };
646    let mut ext = lctx.to_vec();
647    ext.push((p1.to_string(), dom1.clone()));
648    unify_in(ctx, mctx, &ext, body1, &body2)
649}
650
651/// Solve metavariable `m := t` (or, if already solved, unify the existing solution with
652/// `t`). The occurs-check rejects a cyclic solution.
653fn assign(ctx: &Context, mctx: &mut MetaCtx, m: &str, t: &Term) -> bool {
654    if let Some(sol) = mctx.solutions.get(m).cloned() {
655        return unify(ctx, mctx, &sol, t);
656    }
657    let t = instantiate(t, mctx);
658    // `?m := ?m` is trivially satisfied; a deeper occurrence is a cycle.
659    if matches!(&t, Term::Var(n) if n == m) {
660        return true;
661    }
662    if occurs(m, &t) {
663        return false;
664    }
665    mctx.solutions.insert(m.to_string(), t);
666    true
667}
668
669/// Resolve a nonnegative numeral through the declared OfNat dictionary before
670/// using native literal conversion or LOGOS's record injection.
671fn elaborate_ofnat(
672    ctx: &Context,
673    mctx: &mut MetaCtx,
674    lit: &crate::term::Literal,
675    expected: &Term,
676) -> KernelResult<Option<Term>> {
677    use crate::term::{Literal, Universe};
678    let zero = logicaffeine_base::BigInt::from_i64(0);
679    let n = match lit {
680        Literal::Nat(n) | Literal::BigInt(n) if *n >= zero => n.clone(),
681        Literal::Int(n) if *n >= 0 => logicaffeine_base::BigInt::from_i64(*n),
682        _ => return Ok(None),
683    };
684    if ctx.poly_declaration("OfNat").is_none() {
685        return Ok(None);
686    }
687    let expected = instantiate(expected, mctx);
688    if has_unsolved_meta(&expected) {
689        return Ok(None);
690    }
691    let level: Universe = match crate::type_checker::infer_sort(ctx, &expected) {
692        Ok(level) => level,
693        Err(_) => return Ok(None),
694    };
695    let cref = |name: &str| Term::Const {
696        name: name.to_string(),
697        levels: vec![level.clone()],
698    };
699    let app = |f: Term, a: Term| Term::App(Box::new(f), Box::new(a));
700    let numeral = Term::Lit(Literal::Nat(n));
701    let required = app(app(cref("OfNat"), expected.clone()), numeral.clone());
702    let mut trial = mctx.clone();
703    let Some(dictionary) = resolve_instance(ctx, &mut trial, &required) else {
704        return Ok(None);
705    };
706    // Instance entries are search metadata, not typing evidence. Certify the selected
707    // dictionary and its projection before committing any metavariable assignments.
708    let value = app(
709        app(app(cref("OfNat_ofNat"), expected.clone()), numeral),
710        dictionary,
711    );
712    let actual = infer_type(ctx, &value)?;
713    if !unify(ctx, &mut trial, &actual, &expected) {
714        return Err(KernelError::TypeMismatch {
715            expected: expected.to_string(),
716            found: actual.to_string(),
717        });
718    }
719    *mctx = trial;
720    Ok(Some(normalize(ctx, &value)))
721}
722
723/// Native literal conversion used when no declared numeral dictionary applies.
724/// The expected carrier chooses the literal representation; typing still checks it.
725///
726/// The kernel types a literal by its kind and must keep doing so: `Literal::Nat(3) : Nat` is the
727/// kernel's answer and an expected type is never allowed to change what a term IS. What an
728/// expected type may do is decide which term to BUILD, which is elaboration's job — and `3`
729/// written where a `Nat` is wanted and `3` written where an `Int` is wanted are two different
730/// terms of the same surface token, exactly as `(3 : Nat)` and `(3 : Int)` are in Lean.
731///
732/// Only the two INTEGER kinds move, and only between each other. `Nat` is the non-negative half
733/// of `Int`, so a negative numeral at `Nat` has no reading at all and is left exactly as it was,
734/// to be refused where it always was; every other kind (`Text`, `Float`, `Date`, `Duration`,
735/// `Moment`) has a single carrier and is never retyped. Returning `None` therefore means "this
736/// numeral cannot mean that", never "I did not look".
737///
738/// The expected type is REDUCED before it is read, so an abbreviation (`Definition Count := Nat.`)
739/// asks for the same numeral its right-hand side does. A type the reduction leaves as anything but
740/// `Nat` or `Int` — a metavariable, a record, a Π — declines here and falls through to the
741/// injection path, which is the mechanism for a user carrier.
742fn retype_numeral(ctx: &Context, lit: &crate::term::Literal, expected: &Term) -> Option<Term> {
743    use crate::term::Literal;
744    let carrier = match normalize(ctx, expected) {
745        Term::Global(n) => n,
746        _ => return None,
747    };
748    let zero = logicaffeine_base::BigInt::from_i64(0);
749    match (carrier.as_str(), lit) {
750        // `(n : Nat)` for a numeral written as an `Int`. The `n >= 0` guard is the whole content
751        // of the `Nat`/`Int` distinction: below zero there is no `Nat` to take.
752        ("Nat", Literal::Int(n)) if *n >= 0 => Some(Term::Lit(Literal::Nat(
753            logicaffeine_base::BigInt::from_i64(*n),
754        ))),
755        ("Nat", Literal::BigInt(n)) if *n >= zero => Some(Term::Lit(Literal::Nat(n.clone()))),
756        // `(n : Int)` for a numeral written as a `Nat`. Always available — every `Nat` is an
757        // `Int` — and routed through `int_lit` so the one-representation-per-value invariant
758        // definitional equality of literals rests on is preserved above the `i64` boundary.
759        ("Int", Literal::Nat(n)) => Some(Term::Lit(crate::term::int_lit(n.clone()))),
760        _ => None,
761    }
762}
763
764/// Elaborate `term` (which may contain `Hole`s) against an optional `expected` type,
765/// solving the holes by unification. Returns the elaborated term and its type (both still
766/// containing metavariables until `instantiate`d).
767pub fn elaborate(
768    ctx: &Context,
769    mctx: &mut MetaCtx,
770    term: &Term,
771    expected: Option<&Term>,
772) -> KernelResult<(Term, Term)> {
773    elaborate_in(ctx, mctx, &[], term, expected)
774}
775
776/// Like [`elaborate`] but under a LOCAL CONTEXT `lctx` of bound variables. `ctx` is the
777/// kernel context already EXTENDED with those same variables (so `infer_type` sees them
778/// at the leaves), while `lctx` is the parallel `(name, type)` list the unifier uses for
779/// higher-order PATTERN unification. Descending under a `λ` extends both — which is how a
780/// metavariable applied to a bound variable (a motive `?P n`) gets solved in a body.
781pub fn elaborate_in(
782    ctx: &Context,
783    mctx: &mut MetaCtx,
784    lctx: &[(String, Term)],
785    term: &Term,
786    expected: Option<&Term>,
787) -> KernelResult<(Term, Term)> {
788    // Surface sugar `⟨…⟩` / `receiver.field` is dispatched FIRST, so a nested occurrence in a
789    // field or receiver resolves here too — with the expected type flowing in from the
790    // enclosing constructor domain (`⟨⟨a, b⟩, c⟩`) or projection.
791    if let Some(sugar) = as_surface_sugar(term) {
792        return elaborate_sugar(ctx, mctx, sugar, expected);
793    }
794    // A reference to a UNIVERSE-POLYMORPHIC declaration by its bare name, with the levels left
795    // unwritten. Solve them from the arguments and continue with the explicit `Const{name, ℓ…}`.
796    if let Some(rewritten) = solve_unwritten_levels(ctx, term)? {
797        return elaborate_in(ctx, mctx, lctx, &rewritten, expected);
798    }
799    if let (Term::Lit(lit), Some(exp)) = (term, expected) {
800        if let Some(value) = elaborate_ofnat(ctx, mctx, lit, exp)? {
801            let ty = infer_type(ctx, &value)?;
802            return Ok((value, ty));
803        }
804    }
805    match term {
806        Term::Hole => {
807            let m = mctx.fresh();
808            let ty = expected.cloned().unwrap_or_else(|| mctx.fresh());
809            mctx.declare_hole(&m, lctx, &ty);
810            Ok((m, ty))
811        }
812        Term::App(f, a) => {
813            let (f_elab, f_ty) = elaborate_in(ctx, mctx, lctx, f, None)?;
814            let f_ty = resolve_application_pi(ctx, mctx, &f_ty);
815            match f_ty {
816                Term::Pi {
817                    param,
818                    param_type,
819                    body_type,
820                } => {
821                    let (a_elab, a_ty) = elaborate_in(ctx, mctx, lctx, a, Some(&param_type))?;
822                    if !unify_in(ctx, mctx, lctx, &a_ty, &param_type) {
823                        return Err(KernelError::TypeMismatch {
824                            expected: format!("{}", instantiate(&param_type, mctx)),
825                            found: format!("{}", instantiate(&a_ty, mctx)),
826                        });
827                    }
828                    let result_ty = substitute(&body_type, &param, &a_elab);
829                    // Reconcile the result with the expected type — this is where a motive
830                    // `?P n` is solved against the application's actual type `Vec n`.
831                    if let Some(exp) = expected {
832                        unify_in(ctx, mctx, lctx, &result_ty, exp);
833                    }
834                    Ok((Term::App(Box::new(f_elab), Box::new(a_elab)), result_ty))
835                }
836                other => Err(KernelError::NotAFunction(format!("{}", other))),
837            }
838        }
839        Term::Lambda {
840            param,
841            param_type,
842            body,
843        } => {
844            // Descend under the binder, extending BOTH the kernel context (for leaf type
845            // inference) and the unification context (for pattern unification). The body's
846            // expected type is the expected `Π`'s codomain, α-renamed to this binder.
847            let body_expected = match expected.map(|e| resolve_application_pi(ctx, mctx, e)) {
848                Some(Term::Pi {
849                    param: ep,
850                    body_type: ecod,
851                    ..
852                }) => Some(if ep == *param {
853                    (*ecod).clone()
854                } else {
855                    substitute(&ecod, &ep, &Term::Var(param.clone()))
856                }),
857                _ => None,
858            };
859            let ext_ctx = ctx.extend(param, (**param_type).clone());
860            let mut ext_lctx = lctx.to_vec();
861            ext_lctx.push((param.clone(), (**param_type).clone()));
862            let (body_elab, body_ty) =
863                elaborate_in(&ext_ctx, mctx, &ext_lctx, body, body_expected.as_ref())?;
864            Ok((
865                Term::Lambda {
866                    param: param.clone(),
867                    param_type: param_type.clone(),
868                    body: Box::new(body_elab),
869                },
870                Term::Pi {
871                    param: param.clone(),
872                    param_type: param_type.clone(),
873                    body_type: Box::new(body_ty),
874                },
875            ))
876        }
877        _ => {
878            // A leaf (hole-free): defer to the kernel for its type (in the extended
879            // context, so bound variables resolve), then reconcile with the expected type
880            // via unification (which may solve metavariables on either side, including
881            // higher-order patterns over the local context).
882            let ty = infer_type(ctx, term)?;
883            if let Some(exp) = expected {
884                if unify_in(ctx, mctx, lctx, &ty, exp) {
885                    return Ok((term.clone(), ty));
886                }
887                // A NUMERAL that did not fit is retyped at the carrier the position asks for
888                // (see [`retype_numeral`]). This is the ARGUMENT and FIELD door — `f (3 : Nat)`
889                // and `⟨3⟩ : MyNum` reach it — and it has to be here rather than only on the
890                // top-level surface arm, or the same token would mean different things at
891                // depth 0 and depth 1.
892                //
893                // Attempted on a CLONE of the metavariable context and committed only when the
894                // retyped literal really does fit: a failed attempt must leave no solution
895                // behind, or a numeral that cannot be retyped would still have moved the
896                // unifier.
897                if let Term::Lit(l) = term {
898                    let exp_i = instantiate(exp, mctx);
899                    if let Some(retyped) = retype_numeral(ctx, l, &exp_i) {
900                        let rty = infer_type(ctx, &retyped)?;
901                        let mut trial = mctx.clone();
902                        if unify_in(ctx, &mut trial, lctx, &rty, exp) {
903                            *mctx = trial;
904                            return Ok((retyped, rty));
905                        }
906                    }
907                }
908            }
909            Ok((term.clone(), ty))
910        }
911    }
912}
913
914/// Fill in inferred motives for `match` expressions written WITHOUT a `return` clause
915/// (the `Hole` motive the parser leaves). The motive is a CONSTANT `λ_:I. T` — covering
916/// non-dependent matches — where `T` is the EXPECTED type (a definition's declared
917/// result type, propagated through binders) or, lacking one, the type of a nullary first
918/// branch. The pass threads the kernel context through binders so the discriminant's type
919/// resolves; a `match` it cannot give a motive (a dependent case, no expected type) is
920/// reported so the user can add an explicit `return`.
921pub fn fill_match_motives(
922    ctx: &Context,
923    term: &Term,
924    expected: Option<&Term>,
925) -> KernelResult<Term> {
926    match term {
927        Term::Match {
928            discriminant,
929            motive,
930            cases,
931        } => {
932            let disc = fill_match_motives(ctx, discriminant, None)?;
933            if cases
934                .iter()
935                .any(|c| crate::interface::raw_match::as_case(c).is_some())
936            {
937                return crate::interface::raw_match::compile(ctx, disc, motive, cases, expected);
938            }
939
940            let cases = cases
941                .iter()
942                .map(|c| fill_match_motives(ctx, c, None))
943                .collect::<KernelResult<Vec<_>>>()?;
944            let motive = if matches!(motive.as_ref(), Term::Hole) {
945                infer_match_motive(ctx, &disc, &cases, expected)?
946            } else {
947                fill_match_motives(ctx, motive, None)?
948            };
949            Ok(Term::Match {
950                discriminant: Box::new(disc),
951                motive: Box::new(motive),
952                cases,
953            })
954        }
955        Term::Lambda {
956            param,
957            param_type,
958            body,
959        } => {
960            let ext = ctx.extend(param, (**param_type).clone());
961            // The body's expected type is the codomain of the expected `Π`, α-renamed. It is read
962            // only by a `match` the λ-spine ends in (an application, a `Π` or a `fix` hands its
963            // subterms no expected type), so it is computed only for one: a declared type is
964            // otherwise never normalized just to be discarded.
965            let expected = expected.filter(|_| ends_in_match(body));
966            let body_expected = match expected.map(|e| normalize(ctx, e)) {
967                Some(Term::Pi {
968                    param: ep,
969                    body_type,
970                    ..
971                }) => Some(if ep == *param {
972                    *body_type
973                } else {
974                    substitute(&body_type, &ep, &Term::Var(param.clone()))
975                }),
976                _ => None,
977            };
978            Ok(Term::Lambda {
979                param: param.clone(),
980                param_type: param_type.clone(),
981                body: Box::new(fill_match_motives(&ext, body, body_expected.as_ref())?),
982            })
983        }
984        Term::App(f, a) => Ok(Term::App(
985            Box::new(fill_match_motives(ctx, f, None)?),
986            Box::new(fill_match_motives(ctx, a, None)?),
987        )),
988        Term::Pi {
989            param,
990            param_type,
991            body_type,
992        } => {
993            let ext = ctx.extend(param, (**param_type).clone());
994            Ok(Term::Pi {
995                param: param.clone(),
996                param_type: Box::new(fill_match_motives(ctx, param_type, None)?),
997                body_type: Box::new(fill_match_motives(&ext, body_type, None)?),
998            })
999        }
1000        Term::Fix { name, body } => Ok(Term::Fix {
1001            name: name.clone(),
1002            body: Box::new(fill_match_motives(ctx, body, None)?),
1003        }),
1004        Term::Annotated {
1005            annotation,
1006            term: inner,
1007        } => Ok(Term::Annotated {
1008            annotation: annotation.clone(),
1009            term: Box::new(fill_match_motives(ctx, inner, expected)?),
1010        }),
1011        _ => Ok(term.clone()),
1012    }
1013}
1014
1015/// Whether `term`'s λ-spine ends in a `match` — the only place [`fill_match_motives`] reads an
1016/// expected type.
1017fn ends_in_match(term: &Term) -> bool {
1018    let mut term = term;
1019    loop {
1020        match term {
1021            Term::Match { .. } => return true,
1022            Term::Lambda { body, .. } => term = body,
1023            _ => return false,
1024        }
1025    }
1026}
1027
1028/// Build the motive `λx:I. T[disc := x]` for a `match` written without a `return` clause,
1029/// by ABSTRACTING the discriminant out of the expected type — the Miller-pattern solution
1030/// of `?P disc =?= T`. When `T` mentions the discriminant the motive is DEPENDENT (so a
1031/// match whose result type varies per branch, like an eliminator `Π(n). P n`, elaborates);
1032/// when it does not, this collapses to the constant motive `λ_:I. T`. A bare variable
1033/// discriminant just captures the free variable; any other discriminant has its
1034/// occurrences replaced.
1035pub(crate) fn infer_match_motive(
1036    ctx: &Context,
1037    disc: &Term,
1038    cases: &[Term],
1039    expected: Option<&Term>,
1040) -> KernelResult<Term> {
1041    let disc_ty = normalize(ctx, &infer_type(ctx, disc)?);
1042    let result_ty = match expected {
1043        Some(t) => t.clone(),
1044        None => {
1045            // No expected type: infer it from a nullary first branch (a bare term, not a
1046            // case lambda whose binder types are placeholders we cannot infer through).
1047            match cases.first() {
1048                Some(c) if !matches!(c, Term::Lambda { .. }) => infer_type(ctx, c)?,
1049                _ => {
1050                    return Err(KernelError::CertificationError(
1051                        "cannot infer the motive of this `match`; add a `return` clause or a \
1052                         type annotation"
1053                            .to_string(),
1054                    ))
1055                }
1056            }
1057        }
1058    };
1059    let (param, body) = match disc {
1060        // A variable discriminant: bind its name so its free occurrences in the result
1061        // type are captured (`Π(n). P n` ⇒ motive `λn:I. P n`).
1062        Term::Var(v) => (v.clone(), result_ty),
1063        // Otherwise replace occurrences of the (compound) discriminant by a fresh binder.
1064        other => {
1065            let p = "__motive".to_string();
1066            (p.clone(), replace_subterm(&result_ty, other, &Term::Var(p)))
1067        }
1068    };
1069    Ok(Term::Lambda {
1070        param,
1071        param_type: Box::new(disc_ty),
1072        body: Box::new(body),
1073    })
1074}
1075
1076/// Replace every subterm structurally equal to `target` by `repl`.
1077fn replace_subterm(t: &Term, target: &Term, repl: &Term) -> Term {
1078    if t == target {
1079        return repl.clone();
1080    }
1081    match t {
1082        Term::Var(_)
1083        | Term::Global(_)
1084        | Term::Sort(_)
1085        | Term::Lit(_)
1086        | Term::Hole
1087        | Term::Const { .. } => t.clone(),
1088        Term::Pi {
1089            param,
1090            param_type,
1091            body_type,
1092        } => Term::Pi {
1093            param: param.clone(),
1094            param_type: Box::new(replace_subterm(param_type, target, repl)),
1095            body_type: Box::new(replace_subterm(body_type, target, repl)),
1096        },
1097        Term::Lambda {
1098            param,
1099            param_type,
1100            body,
1101        } => Term::Lambda {
1102            param: param.clone(),
1103            param_type: Box::new(replace_subterm(param_type, target, repl)),
1104            body: Box::new(replace_subterm(body, target, repl)),
1105        },
1106        Term::App(f, a) => Term::App(
1107            Box::new(replace_subterm(f, target, repl)),
1108            Box::new(replace_subterm(a, target, repl)),
1109        ),
1110        Term::Match {
1111            discriminant,
1112            motive,
1113            cases,
1114        } => Term::Match {
1115            discriminant: Box::new(replace_subterm(discriminant, target, repl)),
1116            motive: Box::new(replace_subterm(motive, target, repl)),
1117            cases: cases
1118                .iter()
1119                .map(|c| replace_subterm(c, target, repl))
1120                .collect(),
1121        },
1122        Term::Fix { name, body } => Term::Fix {
1123            name: name.clone(),
1124            body: Box::new(replace_subterm(body, target, repl)),
1125        },
1126        Term::MutualFix { defs, index } => Term::MutualFix {
1127            defs: defs
1128                .iter()
1129                .map(|(n, b)| (n.clone(), replace_subterm(b, target, repl)))
1130                .collect(),
1131            index: *index,
1132        },
1133        Term::Let {
1134            name,
1135            ty,
1136            value,
1137            body,
1138        } => Term::Let {
1139            name: name.clone(),
1140            ty: Box::new(replace_subterm(ty, target, repl)),
1141            value: Box::new(replace_subterm(value, target, repl)),
1142            body: Box::new(replace_subterm(body, target, repl)),
1143        },
1144        Term::Annotated { annotation, term } => Term::Annotated {
1145            annotation: annotation.clone(),
1146            term: Box::new(replace_subterm(term, target, repl)),
1147        },
1148    }
1149}
1150
1151/// Auto-bind free type variables as leading implicit parameters. A definition written
1152/// `id : A -> A := fun a : A => a` mentions `A` as a FREE, unregistered, single-uppercase
1153/// global — the type-variable convention. This pass generalizes each such variable: it
1154/// prepends `Π(A:Type)` to the type and `λ(A:Type)` to the body (converting `Global(A)`
1155/// to the bound `Var(A)`), and returns the new implicit count, so `A` becomes an inferred
1156/// implicit argument. Definitions that already bind their parameters reference them as
1157/// `Var`s, not free `Global`s, so they are untouched — this only rescues what was
1158/// previously an unbound-variable error.
1159pub fn auto_bind_implicits(
1160    ctx: &Context,
1161    ty: &Term,
1162    body: &Term,
1163    existing_implicit: usize,
1164) -> (Term, Term, usize) {
1165    let mut candidates: Vec<String> = Vec::new();
1166    collect_autobind(ctx, ty, &mut candidates);
1167    collect_autobind(ctx, body, &mut candidates);
1168    if candidates.is_empty() {
1169        return (ty.clone(), body.clone(), existing_implicit);
1170    }
1171
1172    let mut new_ty = ty.clone();
1173    let mut new_body = body.clone();
1174    for name in &candidates {
1175        new_ty = global_to_var(&new_ty, name);
1176        new_body = global_to_var(&new_body, name);
1177    }
1178    // First candidate becomes the OUTERMOST binder, quantified at the sort its OWN USES force —
1179    // `Sort u` for a fresh universe parameter when nothing forces one, which is Lean's
1180    // `autoImplicit`, and not `Type 0`.
1181    //
1182    // Pinning an invented binder to `Type 0` is a silent MONOMORPHISATION: `id : A -> A` then
1183    // accepts every value but no TYPE, so `id Nat` — where `A` has to be `Type 0`, one level up —
1184    // fails with a universe mismatch the writer never wrote a universe to cause. The level is a
1185    // real parameter of the declaration, and the kernel already solves such a parameter at each
1186    // use site from the argument's own type (`implicit_levels_for_head`), so the honest binder
1187    // costs nothing and monomorphises nothing.
1188    //
1189    // Where a use DOES force a level it is taken, which is the same answer Lean's unifier
1190    // reaches: `nil : TList A` applies `A` to a `Type 0 → Type 0` family, so `A : Type 0` and the
1191    // declaration is not polymorphic after all. Guessing `Sort u` there would produce a body the
1192    // kernel then refuses, and the diagnostic would name a universe the writer never mentioned.
1193    for name in candidates.iter().rev() {
1194        let sort = autobind_sort(ctx, name, ty, body);
1195        new_ty = Term::Pi {
1196            param: name.clone(),
1197            param_type: Box::new(sort.clone()),
1198            body_type: Box::new(new_ty),
1199        };
1200        new_body = Term::Lambda {
1201            param: name.clone(),
1202            param_type: Box::new(sort),
1203            body: Box::new(new_body),
1204        };
1205    }
1206    (new_ty, new_body, existing_implicit + candidates.len())
1207}
1208
1209/// The sort an auto-bound type variable is quantified at: the CONCRETE level its own uses force,
1210/// or a fresh universe parameter when nothing does.
1211///
1212/// A use forces a level when the variable is passed to something whose parameter at that position
1213/// is a written sort — `TList : Type 0 → Type 0` forces `A : Type 0` in `nil : TList A`. A
1214/// variable that appears only as a BINDER'S TYPE (`fun a : A => …`) constrains nothing, and that
1215/// is the polymorphic case.
1216fn autobind_sort(ctx: &Context, name: &str, ty: &Term, body: &Term) -> Term {
1217    forced_sort(ctx, name, ty)
1218        .or_else(|| forced_sort(ctx, name, body))
1219        .unwrap_or_else(|| Term::Sort(crate::term::Universe::Var(autobind_level(name))))
1220}
1221
1222/// Walk `t` for an application that passes `Global(name)` to a global whose parameter at that
1223/// position is a concrete sort, and return that sort.
1224fn forced_sort(ctx: &Context, name: &str, t: &Term) -> Option<Term> {
1225    if let Term::App(..) = t {
1226        let (head, args) = spine(t);
1227        if let Term::Global(h) = &head {
1228            if let Some(head_ty) = ctx.get_global(h) {
1229                let mut cur = head_ty;
1230                for a in &args {
1231                    let Term::Pi {
1232                        param_type,
1233                        body_type,
1234                        ..
1235                    } = cur
1236                    else {
1237                        break;
1238                    };
1239                    if matches!(a, Term::Global(n) if n == name) {
1240                        if let Term::Sort(u) = param_type.as_ref() {
1241                            return Some(Term::Sort(u.clone()));
1242                        }
1243                    }
1244                    cur = body_type;
1245                }
1246            }
1247        }
1248        for a in &args {
1249            if let Some(s) = forced_sort(ctx, name, a) {
1250                return Some(s);
1251            }
1252        }
1253        return forced_sort(ctx, name, &head);
1254    }
1255    match t {
1256        Term::Pi {
1257            param_type,
1258            body_type,
1259            ..
1260        } => forced_sort(ctx, name, param_type).or_else(|| forced_sort(ctx, name, body_type)),
1261        Term::Lambda {
1262            param_type, body, ..
1263        } => forced_sort(ctx, name, param_type).or_else(|| forced_sort(ctx, name, body)),
1264        Term::Fix { body, .. } => forced_sort(ctx, name, body),
1265        Term::MutualFix { defs, .. } => defs.iter().find_map(|(_, b)| forced_sort(ctx, name, b)),
1266        Term::Let {
1267            ty, value, body, ..
1268        } => forced_sort(ctx, name, ty)
1269            .or_else(|| forced_sort(ctx, name, value))
1270            .or_else(|| forced_sort(ctx, name, body)),
1271        Term::Match {
1272            discriminant,
1273            motive,
1274            cases,
1275        } => forced_sort(ctx, name, discriminant)
1276            .or_else(|| forced_sort(ctx, name, motive))
1277            .or_else(|| cases.iter().find_map(|c| forced_sort(ctx, name, c))),
1278        _ => None,
1279    }
1280}
1281
1282/// The universe parameter an unconstrained auto-bound type variable is quantified at. Named after
1283/// the variable so two auto-bound binders in one declaration get INDEPENDENT levels — `constf :
1284/// A -> B -> A` must not force `A` and `B` to the same universe.
1285fn autobind_level(name: &str) -> String {
1286    format!("u_{name}")
1287}
1288
1289/// A free auto-bind candidate: a single uppercase letter that is not a registered global.
1290fn is_autobind_name(n: &str) -> bool {
1291    n.len() == 1 && n.chars().next().is_some_and(|c| c.is_ascii_uppercase())
1292}
1293
1294/// Collect free auto-bind candidates from `term` in first-appearance order (deduped).
1295fn collect_autobind(ctx: &Context, term: &Term, acc: &mut Vec<String>) {
1296    match term {
1297        Term::Global(n) => {
1298            if is_autobind_name(n) && ctx.get_global(n).is_none() && !acc.contains(n) {
1299                acc.push(n.clone());
1300            }
1301        }
1302        Term::Pi {
1303            param_type,
1304            body_type,
1305            ..
1306        } => {
1307            collect_autobind(ctx, param_type, acc);
1308            collect_autobind(ctx, body_type, acc);
1309        }
1310        Term::Lambda {
1311            param_type, body, ..
1312        } => {
1313            collect_autobind(ctx, param_type, acc);
1314            collect_autobind(ctx, body, acc);
1315        }
1316        Term::App(f, a) => {
1317            collect_autobind(ctx, f, acc);
1318            collect_autobind(ctx, a, acc);
1319        }
1320        Term::Match {
1321            discriminant,
1322            motive,
1323            cases,
1324        } => {
1325            collect_autobind(ctx, discriminant, acc);
1326            collect_autobind(ctx, motive, acc);
1327            for c in cases {
1328                collect_autobind(ctx, c, acc);
1329            }
1330        }
1331        Term::Fix { body, .. } => collect_autobind(ctx, body, acc),
1332        Term::Annotated { term, .. } => collect_autobind(ctx, term, acc),
1333        _ => {}
1334    }
1335}
1336
1337/// Replace every `Global(name)` by `Var(name)` (turning a free type-variable reference
1338/// into a reference to the binder this pass prepends).
1339/// Recursive-definition sugar: if `body` refers to the definition's own `name` as a free
1340/// `Global`, bind that self-reference with a `fix` so the definition can call itself —
1341/// `Definition f : T := … f … .` becomes `f := fix f. …`. The kernel's termination guard
1342/// (run by `infer_type`) then certifies the recursion decreases structurally; a body with
1343/// no self-reference (or one that already wrote an explicit `fix`, whose self-references are
1344/// already bound `Var`s) is returned unchanged. A self-reference SHADOWS any same-named
1345/// global, so a recursive `Definition add` over `Nat` overrides a built-in `add`.
1346pub fn bind_self_recursion(name: &str, body: &Term) -> Term {
1347    if references_global(body, name) {
1348        Term::Fix {
1349            name: name.to_string(),
1350            body: Box::new(global_to_var(body, name)),
1351        }
1352    } else {
1353        body.clone()
1354    }
1355}
1356
1357/// Whether `term` mentions `Global(name)` anywhere — the self-reference test for
1358/// [`bind_self_recursion`]. Bound occurrences (already `Var`) do not count.
1359fn references_global(term: &Term, name: &str) -> bool {
1360    match term {
1361        Term::Global(n) => n == name,
1362        Term::Var(_) | Term::Sort(_) | Term::Lit(_) | Term::Hole | Term::Const { .. } => false,
1363        Term::Pi {
1364            param_type,
1365            body_type,
1366            ..
1367        } => references_global(param_type, name) || references_global(body_type, name),
1368        Term::Lambda {
1369            param_type, body, ..
1370        } => references_global(param_type, name) || references_global(body, name),
1371        Term::App(f, a) => references_global(f, name) || references_global(a, name),
1372        Term::Match {
1373            discriminant,
1374            motive,
1375            cases,
1376        } => {
1377            references_global(discriminant, name)
1378                || references_global(motive, name)
1379                || cases.iter().any(|c| references_global(c, name))
1380        }
1381        Term::Fix { body, .. } => references_global(body, name),
1382        Term::MutualFix { defs, .. } => defs.iter().any(|(_, b)| references_global(b, name)),
1383        Term::Let {
1384            ty, value, body, ..
1385        } => {
1386            references_global(ty, name)
1387                || references_global(value, name)
1388                || references_global(body, name)
1389        }
1390        Term::Annotated { term, .. } => references_global(term, name),
1391    }
1392}
1393
1394fn global_to_var(term: &Term, name: &str) -> Term {
1395    match term {
1396        Term::Global(n) if n == name => Term::Var(n.clone()),
1397        Term::Global(_)
1398        | Term::Var(_)
1399        | Term::Sort(_)
1400        | Term::Lit(_)
1401        | Term::Hole
1402        | Term::Const { .. } => term.clone(),
1403        Term::Pi {
1404            param,
1405            param_type,
1406            body_type,
1407        } => Term::Pi {
1408            param: param.clone(),
1409            param_type: Box::new(global_to_var(param_type, name)),
1410            body_type: Box::new(global_to_var(body_type, name)),
1411        },
1412        Term::Lambda {
1413            param,
1414            param_type,
1415            body,
1416        } => Term::Lambda {
1417            param: param.clone(),
1418            param_type: Box::new(global_to_var(param_type, name)),
1419            body: Box::new(global_to_var(body, name)),
1420        },
1421        Term::App(f, a) => Term::App(
1422            Box::new(global_to_var(f, name)),
1423            Box::new(global_to_var(a, name)),
1424        ),
1425        Term::Match {
1426            discriminant,
1427            motive,
1428            cases,
1429        } => Term::Match {
1430            discriminant: Box::new(global_to_var(discriminant, name)),
1431            motive: Box::new(global_to_var(motive, name)),
1432            cases: cases.iter().map(|c| global_to_var(c, name)).collect(),
1433        },
1434        Term::Fix { name: fname, body } => Term::Fix {
1435            name: fname.clone(),
1436            body: Box::new(global_to_var(body, name)),
1437        },
1438        Term::MutualFix { defs, index } => Term::MutualFix {
1439            defs: defs
1440                .iter()
1441                .map(|(fname, b)| (fname.clone(), global_to_var(b, name)))
1442                .collect(),
1443            index: *index,
1444        },
1445        Term::Let {
1446            name: lname,
1447            ty,
1448            value,
1449            body,
1450        } => Term::Let {
1451            name: lname.clone(),
1452            ty: Box::new(global_to_var(ty, name)),
1453            value: Box::new(global_to_var(value, name)),
1454            body: Box::new(global_to_var(body, name)),
1455        },
1456        Term::Annotated { annotation, term } => Term::Annotated {
1457            annotation: annotation.clone(),
1458            term: Box::new(global_to_var(term, name)),
1459        },
1460    }
1461}
1462
1463/// Elaborate a whole surface term: walk it, and at every application of a global with
1464/// declared implicit parameters (`Context::implicit_args`), insert and infer those
1465/// arguments — so `id 0` becomes `id Int 0`. Terms with no implicits are returned
1466/// unchanged. The result is fully explicit and metavariable-free; the kernel certifies
1467/// it as usual. This is the seam that wires the elaborator into the REPL.
1468pub fn surface_elaborate(ctx: &Context, term: &Term) -> KernelResult<Term> {
1469    surface_elaborate_against(ctx, term, None)
1470}
1471
1472/// Like [`surface_elaborate`] but with an EXPECTED type (e.g. a definition's declared
1473/// type). The expected type is propagated to the top-level application/global so an
1474/// implicit with no value argument — `nil : {A} → List A` used where a `List Int` is
1475/// wanted — is inferred from context.
1476pub fn surface_elaborate_against(
1477    ctx: &Context,
1478    term: &Term,
1479    expected: Option<&Term>,
1480) -> KernelResult<Term> {
1481    let mut mctx = MetaCtx::new();
1482    let elaborated = elab_surface(ctx, &mut mctx, term, expected)?;
1483    Ok(instantiate(&elaborated, &mctx))
1484}
1485
1486fn elab_surface(
1487    ctx: &Context,
1488    mctx: &mut MetaCtx,
1489    term: &Term,
1490    expected: Option<&Term>,
1491) -> KernelResult<Term> {
1492    let elaborated = elab_surface_uncoerced(ctx, mctx, term, expected)?;
1493    Ok(coerce_to_expected(ctx, mctx, elaborated, expected))
1494}
1495
1496/// An ASCRIBED type drives coercion insertion, the same way a parameter type does. Writing
1497/// `Definition coerced : Nat := true.` with `Bool ⇒ Nat` registered must produce
1498/// `boolToNat true`, not a `Bool` stamped with the type `Nat` — the declared type is the
1499/// constraint the term has to meet, and a coercion is how Lean meets it.
1500///
1501/// A term that already has the expected type is returned untouched, and a mismatch with no
1502/// registered path is left exactly as it was, so it fails where it would have failed before.
1503fn coerce_to_expected(
1504    ctx: &Context,
1505    mctx: &mut MetaCtx,
1506    elaborated: Term,
1507    expected: Option<&Term>,
1508) -> Term {
1509    let Some(exp) = expected else {
1510        return elaborated;
1511    };
1512    let Ok(actual) = infer_type(ctx, &elaborated) else {
1513        return elaborated;
1514    };
1515    let mut trial = mctx.clone();
1516    if unify(ctx, &mut trial, &actual, exp) {
1517        *mctx = trial;
1518        return elaborated;
1519    }
1520    let (actual, exp) = (instantiate(&actual, mctx), instantiate(exp, mctx));
1521    coerce_term(ctx, mctx, &elaborated, &actual, &exp).unwrap_or(elaborated)
1522}
1523
1524fn elab_surface_uncoerced(
1525    ctx: &Context,
1526    mctx: &mut MetaCtx,
1527    term: &Term,
1528    expected: Option<&Term>,
1529) -> KernelResult<Term> {
1530    // A top-level surface-sugar term (`⟨…⟩` / `receiver.field`) is resolved through the typed
1531    // core so its expected type propagates; its subterms are elaborated there.
1532    if let Some(sugar) = as_surface_sugar(term) {
1533        return elaborate_sugar(ctx, mctx, sugar, expected).map(|(t, _)| t);
1534    }
1535    if let Some(rewritten) = solve_unwritten_levels(ctx, term)? {
1536        return elab_surface_uncoerced(ctx, mctx, &rewritten, expected);
1537    }
1538    match term {
1539        Term::App(..) => {
1540            // Decompose the application spine `head a0 a1 …`.
1541            let mut args: Vec<&Term> = Vec::new();
1542            let mut cur = term;
1543            while let Term::App(f, a) = cur {
1544                args.push(a);
1545                cur = f;
1546            }
1547            args.reverse();
1548
1549            // SURFACE ARGUMENT SUGAR, read off the RAW spine before anything is elaborated: a
1550            // named argument and the `..` ellipsis are reserved marker applications, and
1551            // elaborating one as an ordinary term would report the marker as an unbound global.
1552            let ellipsis = args.last().is_some_and(|a| is_ellipsis_marker(a));
1553            let has_named = args.iter().any(|a| as_named_argument(a).is_some());
1554            if ellipsis || has_named {
1555                let resolved = match cur {
1556                    Term::Global(name) => ctx.get_global(name).cloned().map(|t| (name, t)),
1557                    _ => None,
1558                };
1559                let Some((name, head_ty)) = resolved else {
1560                    // Neither form means anything without a DECLARATION to read parameter names
1561                    // and arity from. Say so: dropping the request would silently change `f ..`
1562                    // into `f`, and elaborating the marker as an ordinary global would hand the
1563                    // kernel a term built out of a piece of syntax.
1564                    return Err(KernelError::CertificationError(format!(
1565                        "`{}` cannot take named arguments or `..`: it is not a declared global",
1566                        cur
1567                    )));
1568                };
1569                if ellipsis {
1570                    args.pop();
1571                }
1572                return elaborate_by_name(
1573                    ctx, mctx, name, cur, &head_ty, &args, ellipsis, expected,
1574                );
1575            }
1576
1577            let head = elab_surface(ctx, mctx, cur, None)?;
1578            let args: Vec<Term> = args
1579                .iter()
1580                .map(|a| elab_surface(ctx, mctx, a, None))
1581                .collect::<KernelResult<_>>()?;
1582
1583            // Route EVERY global-headed application through the typed elaboration path — even one
1584            // with no implicits — so argument type-checking and COERCION insertion apply
1585            // uniformly. An ANONYMOUS head takes the same path when its own binders carry kinds
1586            // (`Term::Annotated`): `(fun {α} (a : α) => a) 3` inserts `α` exactly as a declared
1587            // `{α} → α → α` does, because there is no name to record the kinds under.
1588            let typed = match &head {
1589                Term::Global(name) => ctx.get_global(name).cloned().map(|head_ty| {
1590                    let kinds = application_kinds(
1591                        ctx.binder_kinds(name),
1592                        ctx.implicit_args(name),
1593                        args.len(),
1594                    );
1595                    (head_ty, kinds)
1596                }),
1597                _ => annotated_binder_kinds(&head).and_then(|recorded| {
1598                    let head_ty = infer_type(ctx, &head).ok()?;
1599                    let leading = recorded
1600                        .iter()
1601                        .take_while(|k| **k == ParamKind::Implicit)
1602                        .count();
1603                    Some((
1604                        head_ty,
1605                        application_kinds(Some(&recorded), leading, args.len()),
1606                    ))
1607                }),
1608            };
1609            if let Some((head_ty, kinds)) = typed {
1610                match elaborate_app_against(ctx, mctx, &head, &head_ty, &kinds, &args, expected) {
1611                    Ok((t, _)) => return Ok(t),
1612                    Err(typed_err) => {
1613                        // A function type hidden by elaborator transparency must stay
1614                        // hidden; asking kernel conversion here would unfold it again.
1615                        if matches!(typed_err, KernelError::NotAFunction(_)) {
1616                            return Err(typed_err);
1617                        }
1618                        // Fall through to a plain application if typed elaboration did not
1619                        // apply (e.g. the head is not a function of the expected arity) —
1620                        // preserving the permissive behaviour for non-standard shapes.
1621                        //
1622                        // But an elaboration that returns `Ok` must return something the
1623                        // kernel accepts. If the plain application is ill-typed for a
1624                        // reason the typed path already diagnosed, report THAT — the
1625                        // alternative is an `Ok` whose failure surfaces later in
1626                        // `infer_type`, naming neither the argument nor the coercion that
1627                        // was missing.
1628                        //
1629                        // An UNBOUND VARIABLE is the one failure that does not mean the
1630                        // term is wrong: this pass carries no local context, so a body
1631                        // mentioning its own binder cannot be typed here and must keep the
1632                        // permissive answer.
1633                        let plain = args
1634                            .iter()
1635                            .cloned()
1636                            .fold(head.clone(), |f, a| Term::App(Box::new(f), Box::new(a)));
1637                        return match infer_type(ctx, &plain) {
1638                            Ok(_) | Err(KernelError::UnboundVariable(_)) => Ok(plain),
1639                            Err(_) => Err(typed_err),
1640                        };
1641                    }
1642                }
1643            }
1644            Ok(args
1645                .into_iter()
1646                .fold(head, |f, a| Term::App(Box::new(f), Box::new(a))))
1647        }
1648        // A bare implicit global (no value arguments) is elaborated only when an expected
1649        // type is available to pin its implicits — otherwise it stays the polymorphic
1650        // function value, not an unsolvable metavariable application.
1651        Term::Global(name) if expected.is_some() && ctx.implicit_args(name) > 0 => {
1652            let k = ctx.implicit_args(name);
1653            if let Some(head_ty) = ctx.get_global(name).cloned() {
1654                let kinds = vec![ParamKind::Implicit; k];
1655                let (t, _) =
1656                    elaborate_app_against(ctx, mctx, term, &head_ty, &kinds, &[], expected)?;
1657                Ok(t)
1658            } else {
1659                Ok(term.clone())
1660            }
1661        }
1662        // POSTPONEMENT — a λ whose parameter type the writer did not give.
1663        //
1664        // `fun x => Succ x` has NO type at all until something says what `x` is. Lean postpones
1665        // the whole elaboration problem onto a queue and re-runs it when the expected type
1666        // arrives; a single pass cannot postpone, but it does not have to: by the time this arm
1667        // runs, the expected type either is known or never will be. So the domain is read off it
1668        // here, and the body is elaborated against the codomain WITH the binder in scope — which
1669        // is the same answer the queue would have reached, one pass earlier.
1670        Term::Lambda {
1671            param,
1672            param_type,
1673            body,
1674        } => {
1675            let exp_pi = expected.map(|e| resolve_application_pi(ctx, mctx, e));
1676            let (exp_dom, exp_cod) = match &exp_pi {
1677                Some(Term::Pi {
1678                    param: ep,
1679                    param_type: d,
1680                    body_type: b,
1681                }) => (
1682                    Some((**d).clone()),
1683                    // The codomain may mention the expected type's own binder; α-rename it to
1684                    // this λ's binder so a DEPENDENT expected type stays correct.
1685                    Some(substitute(b, ep, &Term::Var(param.clone()))),
1686                ),
1687                _ => (None, None),
1688            };
1689            let dom = match (param_type.as_ref(), &exp_dom) {
1690                (Term::Hole, Some(d)) => d.clone(),
1691                _ => ensure_type(ctx, elab_surface(ctx, mctx, param_type, None)?),
1692            };
1693            // A domain that is still a hole cannot be put in scope — the binder would type-check
1694            // against anything. Elaborate the body without it, exactly as before.
1695            let body = if matches!(dom, Term::Hole) {
1696                elab_surface(ctx, mctx, body, exp_cod.as_ref())?
1697            } else {
1698                let scoped = ctx.extend(param, dom.clone());
1699                elab_surface(&scoped, mctx, body, exp_cod.as_ref())?
1700            };
1701            Ok(Term::Lambda {
1702                param: param.clone(),
1703                param_type: Box::new(dom),
1704                body: Box::new(body),
1705            })
1706        }
1707        // A Π has TWO type positions, its domain and its codomain, and each is an `ensureType`
1708        // site — which is why `Π(x : t). t` with a `CoeSort`-able `t` coerces on both sides.
1709        // The binder is in scope for the codomain, at its COERCED domain, so a codomain
1710        // mentioning it reads the type the elaborated binder actually has.
1711        Term::Pi {
1712            param,
1713            param_type,
1714            body_type,
1715        } => {
1716            let dom = ensure_type(ctx, elab_surface(ctx, mctx, param_type, None)?);
1717            let scoped = ctx.extend(param, dom.clone());
1718            let cod = ensure_type(&scoped, elab_surface(&scoped, mctx, body_type, None)?);
1719            Ok(Term::Pi {
1720                param: param.clone(),
1721                param_type: Box::new(dom),
1722                body_type: Box::new(cod),
1723            })
1724        }
1725        Term::Fix { name, body } => Ok(Term::Fix {
1726            name: name.clone(),
1727            body: Box::new(elab_surface(ctx, mctx, body, None)?),
1728        }),
1729        Term::Match { cases, .. }
1730            if cases
1731                .iter()
1732                .any(|c| crate::interface::raw_match::as_case(c).is_some()) =>
1733        {
1734            let compiled = fill_match_motives(ctx, term, expected)?;
1735            elab_surface(ctx, mctx, &compiled, expected)
1736        }
1737        Term::Match {
1738            discriminant,
1739            motive,
1740            cases,
1741        } => Ok(Term::Match {
1742            discriminant: Box::new(elab_surface(ctx, mctx, discriminant, None)?),
1743            motive: Box::new(elab_surface(ctx, mctx, motive, None)?),
1744            cases: cases
1745                .iter()
1746                .map(|c| elab_surface(ctx, mctx, c, None))
1747                .collect::<KernelResult<_>>()?,
1748        }),
1749        // An annotation is elaborated THROUGH: the term under it meets the same expected type,
1750        // and the annotation stays on what it produced.
1751        Term::Annotated {
1752            annotation,
1753            term: inner,
1754        } => Ok(Term::Annotated {
1755            annotation: annotation.clone(),
1756            term: Box::new(elab_surface_uncoerced(ctx, mctx, inner, expected)?),
1757        }),
1758        // Resolve declared numeral dictionaries before applying LOGOS record injection.
1759        //
1760        // The kernel types a literal by its KIND and must keep doing so: `Literal::Nat(3) : Nat`
1761        // is the kernel's answer, and an expected type is not allowed to change what a term IS.
1762        // What an expected type may do is decide what term to BUILD, which is elaboration's job.
1763        //
1764        // If no dictionary applies, a single-field record can still use LOGOS's
1765        // constructor injection; declared instances always determine the value first.
1766        Term::Lit(_) => {
1767            let Some(exp) = expected else {
1768                return Ok(term.clone());
1769            };
1770            let exp = instantiate(exp, mctx);
1771            if let Term::Lit(lit) = term {
1772                if let Some(value) = elaborate_ofnat(ctx, mctx, lit, &exp)? {
1773                    return Ok(value);
1774                }
1775            }
1776            // The literal already has the expected type: nothing to do, and in particular no
1777            // wrapping of a `Nat` literal in a `Nat`-carrying record that happens to be expected.
1778            if matches!(infer_type(ctx, term), Ok(native) if crate::is_subtype(ctx, &native, &exp))
1779            {
1780                return Ok(term.clone());
1781            }
1782            // THE KIND CHANGE, before any injection is considered: `Yield 1` against a
1783            // declared `-> Nat` is the `Nat` numeral `1`, not an `Int` wrapped in whatever
1784            // single-field record happens to be expected. Injection is the door for a USER
1785            // carrier; the two built-in integer carriers are reached by retyping the token.
1786            if let Term::Lit(l) = term {
1787                if let Some(retyped) = retype_numeral(ctx, l, &exp) {
1788                    return Ok(retyped);
1789                }
1790            }
1791            match elaborate_anon_ctor(ctx, mctx, &exp, std::slice::from_ref(term)) {
1792                Ok(wrapped) => Ok(wrapped),
1793                // No injection available. Hand back the literal unchanged so the mismatch is
1794                // reported where it always was, by the kernel, against the real expected type.
1795                Err(_) => Ok(term.clone()),
1796            }
1797        }
1798        _ => Ok(term.clone()),
1799    }
1800}
1801
1802/// The kinds an application of a head with `recorded` per-binder kinds and `implicit_args` leading
1803/// implicits supplies, given `explicit` written arguments: the recorded kinds (E2) when they exist
1804/// and name exactly that many explicit positions — so implicit and instance parameters interleave
1805/// with explicit ones — and otherwise the legacy model, the leading implicits then the explicit
1806/// arguments. One rule for a declared head and an anonymous one.
1807fn application_kinds(
1808    recorded: Option<&[ParamKind]>,
1809    implicit_args: usize,
1810    explicit: usize,
1811) -> Vec<ParamKind> {
1812    match recorded {
1813        Some(kinds) if kinds.iter().filter(|k| **k == ParamKind::Explicit).count() == explicit => {
1814            kinds.to_vec()
1815        }
1816        _ => {
1817            let mut kinds = vec![ParamKind::Implicit; implicit_args];
1818            kinds.extend(std::iter::repeat(ParamKind::Explicit).take(explicit));
1819            kinds
1820        }
1821    }
1822}
1823
1824/// The per-binder kinds an anonymous `fun` telescope carries as [`crate::Annotation::Binder`]s,
1825/// outermost first — `None` when no binder of it carries one, so an unannotated head keeps the
1826/// plain application it always had.
1827fn annotated_binder_kinds(head: &Term) -> Option<Vec<ParamKind>> {
1828    let mut kinds = Vec::new();
1829    let mut cur = head;
1830    while let Term::Lambda { body, .. } = cur.peel_annotations() {
1831        kinds.push(cur.binder_kind().unwrap_or(ParamKind::Explicit));
1832        cur = body;
1833    }
1834    kinds
1835        .iter()
1836        .any(|k| *k != ParamKind::Explicit)
1837        .then_some(kinds)
1838}
1839
1840/// How a function parameter is supplied during elaboration.
1841#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1842pub enum ParamKind {
1843    /// The caller provides the argument.
1844    Explicit,
1845    /// Inferred by unification (a fresh metavariable is inserted).
1846    Implicit,
1847    /// Lean's `⦃x : T⦄` — inferred like [`ParamKind::Implicit`], but inserted ONLY when a later
1848    /// EXPLICIT argument is actually supplied.
1849    ///
1850    /// The fourth inhabitant of Lean's `BinderInfo`, and the distinction is observable in one
1851    /// direction only: fully applied, a strict implicit and an eager one build the same term.
1852    /// Unapplied they do not. `nilOf ⦃α⦄ : List α` written on its own is still the polymorphic
1853    /// FUNCTION awaiting its type; inserting the metavariable there emits `nilOf ?0`, which
1854    /// nothing in the application can solve and which the kernel then reports as an unbound
1855    /// variable far from where it was made. Under-inserting leaves a term that is still correct;
1856    /// over-inserting manufactures one that is not.
1857    StrictImplicit,
1858    /// A typeclass instance, resolved from the [`Context`]'s instance database — but only
1859    /// AFTER the explicit arguments have been processed, so any metavariable in the class
1860    /// type (e.g. the `A` in `Inhabited A`) is solved first.
1861    Instance,
1862}
1863
1864/// Elaborate an application of `head` (of type `head_ty`) where leading parameters may be
1865/// implicit or instance-implicit (`kinds[i]`). A fresh metavariable is inserted for each
1866/// implicit position; instance positions get a placeholder metavariable whose resolution
1867/// is DEFERRED until all explicit arguments (which may pin the class's type variables)
1868/// have been unified. Returns the fully explicit, metavariable-instantiated term and type.
1869pub fn elaborate_app(
1870    ctx: &Context,
1871    mctx: &mut MetaCtx,
1872    head: &Term,
1873    head_ty: &Term,
1874    kinds: &[ParamKind],
1875    explicit_args: &[Term],
1876) -> KernelResult<(Term, Term)> {
1877    elaborate_app_against(ctx, mctx, head, head_ty, kinds, explicit_args, None)
1878}
1879
1880/// Like [`elaborate_app`] but with an EXPECTED result type. After the explicit arguments
1881/// are processed, the result type is unified with `expected` — so an implicit that the
1882/// arguments alone do not pin (e.g. the `A` of `nil : {A} → List A`, which has no value
1883/// argument) is solved from the surrounding context. The expected-type pass runs BEFORE
1884/// instance resolution, so a class's type variable can be fixed by the context too.
1885#[allow(clippy::too_many_arguments)]
1886pub fn elaborate_app_against(
1887    ctx: &Context,
1888    mctx: &mut MetaCtx,
1889    head: &Term,
1890    head_ty: &Term,
1891    kinds: &[ParamKind],
1892    explicit_args: &[Term],
1893    expected: Option<&Term>,
1894) -> KernelResult<(Term, Term)> {
1895    let mut fills: Vec<Fill> = Vec::with_capacity(kinds.len());
1896    let mut next_arg = 0usize;
1897    for (i, kind) in kinds.iter().enumerate() {
1898        // An implicit that NOTHING can determine is not inserted. If no later parameter takes
1899        // an explicit argument and no expected type was supplied, there is no constraint left
1900        // to solve it from, and filling it anyway emits `f ?0` — a term the kernel rejects as
1901        // an unbound variable, far from the application that created it. Leaving the function
1902        // polymorphic is both honest and useful: it is still a value awaiting its argument,
1903        // which is exactly Lean's treatment of a strict implicit `⦃α⦄` with nothing following.
1904        //
1905        // A MISSING EXPLICIT argument is a different thing and still a hard error: it becomes a
1906        // `Fill::Missing`, which the engine reports only once the position is known to exist.
1907        if *kind == ParamKind::Implicit
1908            && expected.is_none()
1909            && !kinds[i..].iter().any(|k| *k == ParamKind::Explicit)
1910        {
1911            break;
1912        }
1913        // A STRICT IMPLICIT waits for an argument that is actually WRITTEN — Lean's `⦃α⦄`, and
1914        // the one place the fourth binder kind is observable. The eager rule above stops when
1915        // nothing COULD determine the position; this one stops when nothing has been SUPPLIED,
1916        // which is stricter and is the point: an expected type is not a reason to instantiate
1917        // `nilOf`, because `nilOf` unapplied is still the function its type says it is.
1918        if *kind == ParamKind::StrictImplicit && next_arg >= explicit_args.len() {
1919            break;
1920        }
1921        fills.push(match kind {
1922            ParamKind::Implicit | ParamKind::StrictImplicit => Fill::Infer,
1923            ParamKind::Instance => Fill::Instance,
1924            ParamKind::Explicit => match explicit_args.get(next_arg) {
1925                Some(a) => {
1926                    next_arg += 1;
1927                    Fill::Given(a.clone())
1928                }
1929                // NOT WRITTEN — before this is an arity complaint, ask the DECLARATION whether it
1930                // filled the position itself. `f 1` against `f : Int -> (m : Int := 3) -> Int` is
1931                // `f 1 3`, at FULL arity: Lean inlines the default at the call site, so the term
1932                // the kernel sees has no hole in it and nothing downstream needs to know a default
1933                // was involved.
1934                None => match declared_default(ctx, head, i) {
1935                    Some(v) => Fill::Default(v),
1936                    None => Fill::Missing,
1937                },
1938            },
1939        });
1940    }
1941
1942    if next_arg != explicit_args.len() {
1943        return Err(KernelError::CertificationError(format!(
1944            "too many explicit arguments: {} provided, {} consumed",
1945            explicit_args.len(),
1946            next_arg
1947        )));
1948    }
1949
1950    // TRAILING OBLIGATIONS. `kinds` is sized by what the CALLER WROTE, so a declaration with more
1951    // parameters than arguments simply stops — which is right for a partial application and wrong
1952    // for a position the declaration expects to be discharged rather than written (Lean's
1953    // `(h : P := by tac)`). The remaining telescope positions are therefore walked as OPTIONAL:
1954    // each is discharged if it can be, and the first one that cannot ENDS the spine, leaving
1955    // exactly the partial application that was there before.
1956    if fills.len() == kinds.len() {
1957        for _ in kinds.len()..count_leading_pis(head_ty) {
1958            fills.push(Fill::Optional);
1959        }
1960    }
1961
1962    elaborate_spine(ctx, mctx, head, head_ty, &fills, expected)
1963}
1964
1965/// DISCHARGE A PROOF OBLIGATION the caller did not write — Lean's auto-param, by the route that
1966/// needs no new trusted constant.
1967///
1968/// `goal` must be a PROPOSITION. The proof is built the way the `decide` tactic builds one:
1969/// resolve `Decidable goal` from the instance database, COMPUTE `decide goal inst`, and — only if
1970/// it computes to `true` — hand back `of_decide_eq_true goal inst (refl Bool true)`.
1971/// `of_decide_eq_true` is a PROVEN prelude theorem (from `Decidable_rec` and Bool no-confusion),
1972/// so an obligation discharged here costs the trusted base nothing; axiomatising the obligation
1973/// instead is the one repair that must never be made, since the axiom's own proof is exactly what
1974/// is missing.
1975///
1976/// Three properties this has to have, and each is the reason for one line:
1977///
1978/// * it is ABOUT THIS CALL SITE. The goal arrives with the earlier arguments already substituted
1979///   in, so `safeDiv 10 2` and `safeDiv 9 3` discharge two different propositions and get two
1980///   different proof terms. Reusing one proof across call sites would prove the wrong thing.
1981/// * it never guesses. A goal whose `decide` does not compute to `true` — including one that is
1982///   simply FALSE — yields `None`, and the caller reports the missing argument exactly as before.
1983/// * the result is KERNEL-CHECKED here, not merely constructed: this is untrusted elaborator code
1984///   filling a position the writer never saw, which is the last place a term should be taken on
1985///   trust.
1986fn discharge_prop(ctx: &Context, mctx: &mut MetaCtx, goal: &Term) -> Option<Term> {
1987    if has_unsolved_meta(goal) {
1988        return None;
1989    }
1990    // A PROPOSITION, and nothing else. A missing `Nat` is a missing argument.
1991    if !matches!(
1992        normalize(ctx, &infer_type(ctx, goal).ok()?),
1993        Term::Sort(crate::term::Universe::Prop)
1994    ) {
1995        return None;
1996    }
1997    let dec_goal = Term::App(
1998        Box::new(Term::Global("Decidable".to_string())),
1999        Box::new(goal.clone()),
2000    );
2001    let mut trial = mctx.clone();
2002    let inst = resolve_instance(ctx, &mut trial, &dec_goal)?;
2003    let decided = Term::App(
2004        Box::new(Term::App(
2005            Box::new(Term::Global("decide".to_string())),
2006            Box::new(goal.clone()),
2007        )),
2008        Box::new(inst.clone()),
2009    );
2010    if normalize(ctx, &decided) != Term::Global("true".to_string()) {
2011        return None;
2012    }
2013    let refl_true = Term::App(
2014        Box::new(Term::App(
2015            Box::new(Term::Global("refl".to_string())),
2016            Box::new(Term::Global("Bool".to_string())),
2017        )),
2018        Box::new(Term::Global("true".to_string())),
2019    );
2020    let proof = Term::App(
2021        Box::new(Term::App(
2022            Box::new(Term::App(
2023                Box::new(Term::Global("of_decide_eq_true".to_string())),
2024                Box::new(goal.clone()),
2025            )),
2026            Box::new(inst),
2027        )),
2028        Box::new(refl_true),
2029    );
2030    let got = infer_type(ctx, &proof).ok()?;
2031    if !crate::is_subtype(ctx, &got, goal) {
2032        return None;
2033    }
2034    *mctx = trial;
2035    Some(proof)
2036}
2037
2038/// The DEFAULT declared for parameter `index` of the global `head` names, if there is one.
2039///
2040/// Only a `Term::Global` head can have one: a default is recorded against a DECLARATION, and an
2041/// anonymous function has no declaration to have written it in.
2042fn declared_default(ctx: &Context, head: &Term, index: usize) -> Option<Term> {
2043    let name = head_global(head)?;
2044    ctx.param_defaults(name)?.get(index)?.1.clone()
2045}
2046
2047/// The name the DECLARATION gave parameter `index` of the global `head` names, if it recorded one.
2048fn declared_param_name(ctx: &Context, head: &Term, index: usize) -> Option<String> {
2049    let name = head_global(head)?;
2050    Some(ctx.param_defaults(name)?.get(index)?.0.clone())
2051}
2052
2053/// How ONE parameter position of an application is supplied — the instruction set the spine
2054/// engine runs, and the single place where "what goes here" is decided.
2055///
2056/// Positional application, named arguments, the `..` ellipsis and η-expansion are all the same
2057/// walk down a Π-telescope; they differ only in what each position is told to do. Keeping that
2058/// difference in a per-position instruction is what stops a second call shape from becoming a
2059/// second copy of the engine — and a second copy is how two surface forms come to disagree about
2060/// coercion insertion, or about when instance resolution runs relative to the expected type.
2061#[derive(Clone, Debug)]
2062enum Fill {
2063    /// The caller supplied this argument (positionally or by name).
2064    Given(Term),
2065    /// Insert a fresh metavariable — an implicit, or a position the `..` ellipsis says to infer.
2066    Infer,
2067    /// Insert a placeholder resolved from the instance database AFTER the explicit arguments and
2068    /// the expected type have run.
2069    Instance,
2070    /// η-EXPAND this position under the given binder name: a LATER parameter was supplied by
2071    /// name, and a partial application cannot skip a parameter. Lean's answer to
2072    /// `sub3 (y := 2) (z := 9)` is `fun x => sub3 x 2 9`, a λ — not a shorter spine.
2073    Abstract(String),
2074    /// An explicit parameter the caller did not supply, filled from the DECLARATION'S OWN DEFAULT
2075    /// — Lean's `(m : Int := 3)`. Carried raw and closed over the arguments the earlier positions
2076    /// actually received, at the point in the walk where those are known.
2077    Default(Term),
2078    /// An explicit parameter the caller did not supply. Reported by the engine, so the position
2079    /// is known to exist before the arity complaint is made.
2080    Missing,
2081    /// A trailing parameter BEYOND the ones the caller addressed: discharged if it can be, and
2082    /// otherwise the end of the spine. Never an error — a partial application is a value.
2083    Optional,
2084}
2085
2086/// THE APPLICATION ENGINE: walk `head_ty`'s Π-telescope one position per [`Fill`], building the
2087/// spine, then run expected-type propagation and instance resolution in that order.
2088///
2089/// η-abstracted positions are wrapped back into λ-binders at the end, so a call that skipped an
2090/// explicit parameter is a FUNCTION of exactly the parameters it skipped.
2091fn elaborate_spine(
2092    ctx: &Context,
2093    mctx: &mut MetaCtx,
2094    head: &Term,
2095    head_ty: &Term,
2096    fills: &[Fill],
2097    expected: Option<&Term>,
2098) -> KernelResult<(Term, Term)> {
2099    let mut cur_term = head.clone();
2100    // A universe-polymorphic head's level variables become metavariables the arguments solve —
2101    // the kernel's own application rule (`type_checker::implicit_levels_for_head`). Left as
2102    // variables they pin the head to one level: `Type 0 ≤ u` is false for a variable `u` (it may
2103    // be `Prop`), so `Eq Nat 2 2` and `refl Nat 2` were refused here while the kernel accepts them.
2104    let mut cur_ty = crate::type_checker::implicit_levels_for_head(head, head_ty.clone());
2105    let mut levels: std::collections::HashMap<String, crate::Universe> =
2106        std::collections::HashMap::new();
2107    // (placeholder metavariable name, the class type to resolve it against).
2108    let mut obligations: Vec<(String, Term)> = Vec::new();
2109    // (binder name, domain) for every η-abstracted position, in order.
2110    let mut abstracted: Vec<(String, Term)> = Vec::new();
2111    // Every name that occurs in a SUPPLIED argument. An η-binder must avoid all of them or it
2112    // CAPTURES: `sub3 (y := x) (z := 9)` binding its own `x` would turn the caller's `x` into the
2113    // λ's, and the result still typechecks — it just computes with the wrong value.
2114    let mut occupied: Vec<String> = Vec::new();
2115    for f in fills {
2116        if let Fill::Given(t) = f {
2117            collect_var_names(t, &mut occupied);
2118        }
2119    }
2120
2121    // (parameter name, the argument that position received) for every position walked so far —
2122    // what a DEFAULT at a later position is closed over.
2123    let mut supplied: Vec<(String, Term)> = Vec::new();
2124
2125    for fill in fills {
2126        // A trailing OPTIONAL position stops the walk the moment it cannot be discharged, so a
2127        // partial application stays the function it is. Decided before the Π is peeled, because
2128        // running out of Π is also a reason to stop rather than to complain.
2129        if matches!(fill, Fill::Optional) {
2130            let Term::Pi { param_type, .. } = resolve_application_pi(ctx, mctx, &cur_ty) else {
2131                break;
2132            };
2133            if discharge_prop(ctx, mctx, &instantiate(&param_type, mctx)).is_none() {
2134                break;
2135            }
2136        }
2137        // COEFUN — a value used where a function is. Lean routes `g 0` for `g : Fn` through a
2138        // `CoeFun Fn (fun _ => Nat → Nat)` instance; a structure with exactly ONE function-typed
2139        // field IS that instance, and the coercion is the projection.
2140        //
2141        // It is a real mechanism and not a rewrite: `Named` keeps its other fields and every
2142        // theorem quantifying over it, because what is inserted is `Named_run n`, not `n`'s
2143        // function field standing in for `n`.
2144        let mut current = resolve_application_pi(ctx, mctx, &cur_ty);
2145        if !matches!(current, Term::Pi { .. }) {
2146            if let Some(coerced) = coe_fun(ctx, &current, &cur_term) {
2147                cur_ty = crate::infer_type(ctx, &coerced)?;
2148                cur_term = coerced;
2149                current = resolve_application_pi(ctx, mctx, &cur_ty);
2150            }
2151        }
2152        let (param, dom, body) = match current {
2153            Term::Pi {
2154                param,
2155                param_type,
2156                body_type,
2157            } => (param, *param_type, *body_type),
2158            other => {
2159                return Err(KernelError::NotAFunction(format!(
2160                    "expected a Π to apply an argument, got {}",
2161                    other
2162                )))
2163            }
2164        };
2165
2166        let arg = match fill {
2167            // AN OBLIGATION THE CALLER DID NOT WRITE. Lean's `(h : P := by tac)` runs a tactic at
2168            // every call site, about THAT call site's proposition; the position is not an
2169            // argument the caller forgot, it is one the declaration expects to be discharged.
2170            // So before the arity complaint, try to PROVE it (see [`discharge_prop`]) — and when
2171            // there is no proof, report the arity exactly as before.
2172            Fill::Missing => match discharge_prop(ctx, mctx, &instantiate(&dom, mctx)) {
2173                Some(proof) => proof,
2174                None => {
2175                    return Err(KernelError::CertificationError(
2176                        "too few explicit arguments".to_string(),
2177                    ))
2178                }
2179            },
2180            // Already decided above; the discharge is repeated rather than cached because the
2181            // metavariable context may have moved since, and a proof is about the goal as it
2182            // stands at the moment it is inserted.
2183            Fill::Optional => match discharge_prop(ctx, mctx, &instantiate(&dom, mctx)) {
2184                Some(proof) => proof,
2185                None => break,
2186            },
2187            // A DEFAULT is closed over the arguments the earlier parameters actually received —
2188            // `sized 5` against `Int -> (m : Int := mul n 2) -> Int` inlines `mul 5 2`, never an
2189            // open term with a free `n` in it. The substitution primitive is the declaration
2190            // door's own (`TermParser::substitute_param_ref`), so a default reaching the
2191            // elaborator through the recorded telescope and one inlined inside the parser cannot
2192            // come to mean two different things; only the source of the ARGUMENTS differs, and
2193            // only here are the elaborated ones known.
2194            //
2195            // The closed term is then elaborated against the position's declared domain exactly
2196            // as a written argument is, so a default is checked and coerced by the same rules and
2197            // cannot smuggle in a term the position would have refused.
2198            Fill::Default(value) => {
2199                let mut closed = value.clone();
2200                for (n, a) in &supplied {
2201                    if n == "_" {
2202                        continue;
2203                    }
2204                    closed = crate::interface::TermParser::substitute_param_ref(&closed, n, a);
2205                }
2206                let (d_elab, d_ty) = elaborate(ctx, mctx, &closed, Some(&dom))?;
2207                if unify(ctx, mctx, &d_ty, &dom) {
2208                    d_elab
2209                } else {
2210                    let (d_ty_i, dom_i) = (instantiate(&d_ty, mctx), instantiate(&dom, mctx));
2211                    match coerce_term(ctx, mctx, &d_elab, &d_ty_i, &dom_i) {
2212                        Some(coerced) => coerced,
2213                        None => {
2214                            return Err(KernelError::TypeMismatch {
2215                                expected: format!("{}", dom_i),
2216                                found: format!("{}", d_ty_i),
2217                            })
2218                        }
2219                    }
2220                }
2221            }
2222            Fill::Infer => mctx.fresh(),
2223            Fill::Instance => {
2224                let m = mctx.fresh();
2225                if let Term::Var(name) = &m {
2226                    obligations.push((name.clone(), dom.clone()));
2227                }
2228                m
2229            }
2230            Fill::Abstract(binder) => {
2231                let name = fresh_binder(binder, &abstracted, &occupied);
2232                abstracted.push((name.clone(), dom.clone()));
2233                Term::Var(name)
2234            }
2235            Fill::Given(provided) => {
2236                let (a_elab, a_ty) = elaborate(ctx, mctx, provided, Some(&dom))?;
2237                // The level metavariables in this position are solved from the argument, as the
2238                // kernel's `solve_domain_levels` solves them, and the solution is carried into
2239                // every later position.
2240                let dom = if crate::term::mentions_level_meta(&dom) {
2241                    let actual = match instantiate(&a_ty, mctx) {
2242                        sort @ Term::Sort(_) => sort,
2243                        other => normalize(ctx, &other),
2244                    };
2245                    crate::term::unify_levels(&dom, &actual, &mut levels);
2246                    crate::term::instantiate_universes(&dom, &levels)
2247                } else {
2248                    dom.clone()
2249                };
2250                if unify(ctx, mctx, &a_ty, &dom) {
2251                    a_elab
2252                } else {
2253                    // The argument type does not match — try to bridge it with a registered
2254                    // COERCION (`↑`). On success wrap the argument in the coercion function;
2255                    // otherwise it is a genuine type mismatch.
2256                    let a_ty_i = instantiate(&a_ty, mctx);
2257                    let dom_i = instantiate(&dom, mctx);
2258                    match coerce_term(ctx, mctx, &a_elab, &a_ty_i, &dom_i) {
2259                        Some(coerced) => coerced,
2260                        None => {
2261                            return Err(KernelError::TypeMismatch {
2262                                expected: format!("{}", dom_i),
2263                                found: format!("{}", a_ty_i),
2264                            })
2265                        }
2266                    }
2267                }
2268            }
2269        };
2270
2271        // The name a LATER default is closed over is the one the DECLARATION used, not the `Pi`
2272        // binder's: `Int -> (m : Int := mul n 2) -> Int` has an anonymous first binder, and the
2273        // default was written against `n`. The telescope's own name is the fallback for a head
2274        // with nothing recorded.
2275        let slot = declared_param_name(ctx, head, supplied.len()).unwrap_or_else(|| param.clone());
2276        supplied.push((slot, arg.clone()));
2277        cur_term = Term::App(Box::new(cur_term), Box::new(arg.clone()));
2278        cur_ty = substitute(&body, &param, &arg);
2279        if !levels.is_empty() {
2280            cur_ty = crate::term::instantiate_universes(&cur_ty, &levels);
2281        }
2282    }
2283
2284    // Expected-type propagation: unify the result type with the context's expected type,
2285    // solving any implicit not already pinned by the explicit arguments.
2286    //
2287    // An η-abstracted call is compared as the FUNCTION it will become, not as its body: the
2288    // expected type of `sub3 (y := 2)` is an `Int → Int`, and unifying that against the body's
2289    // `Int` would reject the very shape η-expansion exists to produce.
2290    if let Some(exp) = expected {
2291        let effective = abstracted
2292            .iter()
2293            .rev()
2294            .fold(cur_ty.clone(), |acc, (n, d)| Term::Pi {
2295                param: n.clone(),
2296                param_type: Box::new(d.clone()),
2297                body_type: Box::new(acc),
2298            });
2299        if !unify(ctx, mctx, &effective, exp) && !converts(ctx, mctx, &effective, exp) {
2300            return Err(KernelError::TypeMismatch {
2301                expected: format!("{}", instantiate(exp, mctx)),
2302                found: format!("{}", instantiate(&effective, mctx)),
2303            });
2304        }
2305    }
2306
2307    // Resolve the deferred instance obligations now that the metavariables their class
2308    // types mention have been solved by the explicit arguments (and the expected type).
2309    for (meta_name, class_ty) in &obligations {
2310        let required = instantiate(class_ty, mctx);
2311        match resolve_instance(ctx, mctx, &required) {
2312            Some(inst) => {
2313                // Bind directly (not via normalizing unification) so the instance stays
2314                // structured rather than being δ-unfolded into its body.
2315                mctx.solve(meta_name, inst);
2316            }
2317            None => {
2318                return Err(KernelError::CertificationError(format!(
2319                    "no typeclass instance found for {}",
2320                    required
2321                )))
2322            }
2323        }
2324    }
2325
2326    let mut term = instantiate(&cur_term, mctx);
2327    let mut ty = instantiate(&cur_ty, mctx);
2328    for (name, dom) in abstracted.iter().rev() {
2329        let dom = instantiate(dom, mctx);
2330        ty = Term::Pi {
2331            param: name.clone(),
2332            param_type: Box::new(dom.clone()),
2333            body_type: Box::new(ty),
2334        };
2335        term = Term::Lambda {
2336            param: name.clone(),
2337            param_type: Box::new(dom),
2338            body: Box::new(term),
2339        };
2340    }
2341    Ok((term, ty))
2342}
2343
2344/// The kernel's conversion, for an expected-type check the first-order unifier could not decide.
2345///
2346/// Lean's `ensureHasType` asks full definitional equality here, and the unifier's
2347/// normalise-then-compare does not see what conversion sees — a numeral beside the constructor
2348/// term it denotes, a definition that reduces only under conversion's δ-strategy:
2349/// `refl Nat 2 : Eq Nat 2 2` against a declared `Eq Nat (myAdd 1 1) 2`. Only a pair with nothing
2350/// left to solve is asked: a metavariable, a level metavariable or a hole is the unifier's to
2351/// settle, and conversion cannot settle one. The elaborated term is checked by the kernel
2352/// afterwards whatever this answers.
2353fn converts(ctx: &Context, mctx: &MetaCtx, found: &Term, expected: &Term) -> bool {
2354    let (found, expected) = (instantiate(found, mctx), instantiate(expected, mctx));
2355    let settled = |t: &Term| {
2356        !mentions_meta(t)
2357            && !crate::term::mentions_level_meta(t)
2358            && !crate::type_checker::mentions_hole(t)
2359    };
2360    settled(&found) && settled(&expected) && crate::is_subtype(ctx, &found, &expected)
2361}
2362
2363/// Lean's `CoeFun`, read off the declaration instead of off an instance: a structure with exactly
2364/// ONE function-typed field is applicable, and applying it means projecting that field.
2365///
2366/// Returns the PROJECTION APPLIED to the value (parameters first), or `None` when the type is not
2367/// a structure, has no function-typed field, or has more than one — in which case there is no
2368/// canonical choice and guessing would silently pick a meaning.
2369///
2370/// Why this is not spelled as an ordinary `Context::add_coercion` triple: a `Coe Fn (Nat → Nat)`
2371/// would make an `Fn` acceptable at every position a `Nat → Nat` is expected, which Lean's
2372/// `CoeFun` deliberately does not do. This fires in HEAD position only.
2373fn coe_fun(ctx: &Context, ty: &Term, value: &Term) -> Option<Term> {
2374    let (head, args) = spine(ty);
2375    let Term::Global(hname) = &head else {
2376        return None;
2377    };
2378    let info = ctx.struct_info(hname)?;
2379    let mut functional = info
2380        .fields
2381        .iter()
2382        .enumerate()
2383        .filter(|(_, (_, t))| matches!(t, Term::Pi { .. }));
2384    let (index, _) = functional.next()?;
2385    if functional.next().is_some() {
2386        return None;
2387    }
2388    let proj = info.projections.get(index)?;
2389    let applied = args.iter().fold(Term::Global(proj.clone()), |f, a| {
2390        Term::App(Box::new(f), Box::new(a.clone()))
2391    });
2392    Some(Term::App(Box::new(applied), Box::new(value.clone())))
2393}
2394
2395/// Lean's `CoeSort`, read off the declaration instead of off an instance: a structure with exactly
2396/// ONE sort-typed field may stand where a TYPE is expected, and standing there means projecting
2397/// that field.
2398///
2399/// This is `coe_fun`'s twin and is written as its twin on purpose — Lean's `CoeFun`
2400/// (`Init/Coe.lean:262`) and `CoeSort` (`Init/Coe.lean:277`) are one design with two consumers,
2401/// `coerceToFunction?` and `coerceToSort?` (`Lean/Meta/Coe.lean:56` and `:69`), and giving them
2402/// two different shapes here is how the second one came to be missing.
2403///
2404/// Returns the PROJECTION APPLIED to the value (structure parameters first), or `None` when the
2405/// value's type is not a structure, has no sort-typed field, or has more than one — in which case
2406/// there is no canonical choice and guessing would silently pick a meaning.
2407///
2408/// ★ WHERE THE LINE IS, and Lean puts it in the same place: this fires during ELABORATION, and
2409/// the KERNEL never learns to coerce. `ensureType` (`Lean/Elab/Term.lean:1859-1868`) calls
2410/// `coerceToSort?` before the term reaches the kernel, so a binder whose domain is not a sort is
2411/// still a type error — it is just not a term the elaborator ever emits.
2412fn coe_sort(ctx: &Context, value: &Term) -> Option<Term> {
2413    let ty = infer_type(ctx, value).ok()?;
2414    // `value` is ALREADY a type when its own type is a sort — nothing to coerce, and in
2415    // particular no wrapping of a genuine sort in a record that happens to carry one.
2416    if matches!(ty, Term::Sort(_)) {
2417        return None;
2418    }
2419    let (head, args) = spine(&crate::normalize(ctx, &ty));
2420    let Term::Global(hname) = &head else {
2421        return None;
2422    };
2423    let info = ctx.struct_info(hname)?;
2424    let mut carriers = info
2425        .fields
2426        .iter()
2427        .enumerate()
2428        .filter(|(_, (_, t))| matches!(t, Term::Sort(_)));
2429    let (index, _) = carriers.next()?;
2430    if carriers.next().is_some() {
2431        return None;
2432    }
2433    let proj = info.projections.get(index)?;
2434    let applied = args.iter().fold(Term::Global(proj.clone()), |f, a| {
2435        Term::App(Box::new(f), Box::new(a.clone()))
2436    });
2437    Some(Term::App(Box::new(applied), Box::new(value.clone())))
2438}
2439
2440/// `ensureType` — Lean's (`Lean/Elab/Term.lean:1859`). A TYPE POSITION holds a term whose own type
2441/// is a sort; one that is not gets a `CoeSort` inserted, and one that cannot be coerced is left
2442/// exactly as written so it fails where it would have failed before.
2443fn ensure_type(ctx: &Context, t: Term) -> Term {
2444    if matches!(infer_type(ctx, &t), Ok(Term::Sort(_)) | Err(_)) {
2445        return t;
2446    }
2447    coe_sort(ctx, &t).unwrap_or(t)
2448}
2449
2450/// A binder name for an η-abstracted position that collides with neither another binder of the
2451/// same expansion nor any name occurring in a supplied argument. `_` is not a name a body can
2452/// refer to, so it is replaced outright.
2453fn fresh_binder(wanted: &str, taken: &[(String, Term)], occupied: &[String]) -> String {
2454    let base = if wanted == "_" || wanted.is_empty() {
2455        "x"
2456    } else {
2457        wanted
2458    };
2459    let free = |c: &String| !taken.iter().any(|(n, _)| n == c) && !occupied.iter().any(|n| n == c);
2460    if free(&base.to_string()) {
2461        return base.to_string();
2462    }
2463    (1..).map(|i| format!("{base}{i}")).find(free).unwrap()
2464}
2465
2466/// Every variable name occurring in `t` — bound or free. η-expansion avoids all of them, because
2467/// distinguishing the two here would only buy a prettier binder name at the cost of a capture bug.
2468fn collect_var_names(t: &Term, acc: &mut Vec<String>) {
2469    let note = |n: &String, acc: &mut Vec<String>| {
2470        if !acc.contains(n) {
2471            acc.push(n.clone());
2472        }
2473    };
2474    match t {
2475        Term::Var(n) => note(n, acc),
2476        Term::Pi {
2477            param,
2478            param_type,
2479            body_type,
2480        } => {
2481            note(param, acc);
2482            collect_var_names(param_type, acc);
2483            collect_var_names(body_type, acc);
2484        }
2485        Term::Lambda {
2486            param,
2487            param_type,
2488            body,
2489        } => {
2490            note(param, acc);
2491            collect_var_names(param_type, acc);
2492            collect_var_names(body, acc);
2493        }
2494        Term::App(f, a) => {
2495            collect_var_names(f, acc);
2496            collect_var_names(a, acc);
2497        }
2498        Term::Fix { name, body } => {
2499            note(name, acc);
2500            collect_var_names(body, acc);
2501        }
2502        Term::MutualFix { defs, .. } => {
2503            for (n, b) in defs {
2504                note(n, acc);
2505                collect_var_names(b, acc);
2506            }
2507        }
2508        Term::Let {
2509            name,
2510            ty,
2511            value,
2512            body,
2513        } => {
2514            note(name, acc);
2515            collect_var_names(ty, acc);
2516            collect_var_names(value, acc);
2517            collect_var_names(body, acc);
2518        }
2519        Term::Match {
2520            discriminant,
2521            motive,
2522            cases,
2523        } => {
2524            collect_var_names(discriminant, acc);
2525            collect_var_names(motive, acc);
2526            for c in cases {
2527                collect_var_names(c, acc);
2528            }
2529        }
2530        Term::Annotated { term, .. } => collect_var_names(term, acc),
2531        _ => {}
2532    }
2533}
2534
2535// ===============================================================================================
2536// SURFACE ARGUMENT SUGAR — named arguments (`f (x := 1)`) and the ellipsis (`f ..`, `⟨a, ..⟩`)
2537// ===============================================================================================
2538//
2539// The parser records a REQUEST it cannot act on — only the elaborator knows a declaration's
2540// parameter names and arity. Both forms land on the same engine as ordinary application: they
2541// only decide what each parameter position is told to do (see [`Fill`]).
2542
2543/// Is `t` the parser's ELLIPSIS marker `..`?
2544fn is_ellipsis_marker(t: &Term) -> bool {
2545    matches!(t, Term::Global(n) if n == crate::interface::TermParser::ELLIPSIS_MARKER)
2546}
2547
2548/// Recognize a NAMED ARGUMENT `(x := v)`, returning the parameter name and the supplied value.
2549fn as_named_argument(t: &Term) -> Option<(&str, &Term)> {
2550    crate::interface::TermParser::as_named_arg(t)
2551}
2552
2553/// The PARAMETER NAMES of the global `name`, position by position.
2554///
2555/// Lean carries parameter names in the declaration's type, because `def f (x : Nat)` binds `x`
2556/// there. A LOGOS arrow type does not: `Definition sub3 : Int -> Int -> Int -> Int` has three
2557/// ANONYMOUS binders, and the names the writer used live in the body's λ-telescope instead. So
2558/// the type is asked first and the body answers for every position the type left as `_` — which
2559/// is what makes `sub3 (y := 2)` mean anything at all.
2560fn param_names(ctx: &Context, name: &str, head_ty: &Term) -> Vec<String> {
2561    let mut names: Vec<String> = Vec::new();
2562    let mut cur = head_ty;
2563    while let Term::Pi {
2564        param, body_type, ..
2565    } = cur
2566    {
2567        names.push(param.clone());
2568        cur = body_type;
2569    }
2570    if !names.iter().any(|n| n == "_") {
2571        return names;
2572    }
2573    // Fill the anonymous positions from the definition's own λ-telescope, where the writer's
2574    // names are. A `fix` wrapper (a recursive definition) is transparent for this purpose.
2575    let Some(mut body) = ctx.get_definition_body(name) else {
2576        return names;
2577    };
2578    while let Term::Fix { body: inner, .. } = body {
2579        body = inner;
2580    }
2581    for slot in names.iter_mut() {
2582        let Term::Lambda {
2583            param, body: inner, ..
2584        } = body
2585        else {
2586            break;
2587        };
2588        if slot == "_" && param != "_" {
2589            *slot = param.clone();
2590        }
2591        body = inner;
2592    }
2593    names
2594}
2595
2596/// The parameter KINDS of the global `name`, position by position, over its FULL arity.
2597///
2598/// Named arguments and the ellipsis both address positions the caller did not write, so unlike
2599/// the positional path this cannot stop at "as many explicits as there are arguments".
2600fn full_param_kinds(ctx: &Context, name: &str, arity: usize) -> Vec<ParamKind> {
2601    let mut kinds = match ctx.binder_kinds(name) {
2602        Some(bk) => bk.to_vec(),
2603        None => {
2604            let k = ctx.implicit_args(name).min(arity);
2605            let mut v = vec![ParamKind::Implicit; k];
2606            v.extend(std::iter::repeat(ParamKind::Explicit).take(arity - k));
2607            v
2608        }
2609    };
2610    kinds.truncate(arity);
2611    while kinds.len() < arity {
2612        kinds.push(ParamKind::Explicit);
2613    }
2614    kinds
2615}
2616
2617/// Elaborate an application written with NAMED arguments and/or a trailing ELLIPSIS.
2618///
2619/// Lean's two rules, and both are observable:
2620///
2621/// * a named argument goes to the parameter it NAMES, wherever the writer put it — resolving it
2622///   positionally is undetectable by the kernel when the parameters share a type, and computes a
2623///   different number;
2624/// * a named argument that SKIPS an earlier explicit parameter η-EXPANDS. `sub3 (y := 2) (z := 9)`
2625///   is `fun x => sub3 x 2 9`, a function of the skipped parameter — not a shorter spine, which
2626///   would apply `2` where `x` belongs.
2627///
2628/// The ellipsis means "infer every position I did not write", so it turns the remaining explicit
2629/// parameters into inferred ones rather than η-abstracting them.
2630#[allow(clippy::too_many_arguments)]
2631fn elaborate_by_name(
2632    ctx: &Context,
2633    mctx: &mut MetaCtx,
2634    name: &str,
2635    head: &Term,
2636    head_ty: &Term,
2637    args: &[&Term],
2638    ellipsis: bool,
2639    expected: Option<&Term>,
2640) -> KernelResult<Term> {
2641    let names = param_names(ctx, name, head_ty);
2642    let arity = names.len();
2643    let kinds = full_param_kinds(ctx, name, arity);
2644    let mut assigned: Vec<Option<Term>> = vec![None; arity];
2645
2646    let mut positional: Vec<&Term> = Vec::new();
2647    for a in args {
2648        match as_named_argument(a) {
2649            Some((pname, value)) => {
2650                let slot = names.iter().position(|n| n == pname).ok_or_else(|| {
2651                    KernelError::CertificationError(format!(
2652                        "`{name}` has no parameter named `{pname}` (its parameters are {})",
2653                        names.join(", ")
2654                    ))
2655                })?;
2656                if assigned[slot].is_some() {
2657                    return Err(KernelError::CertificationError(format!(
2658                        "`{name}`'s parameter `{pname}` is supplied twice"
2659                    )));
2660                }
2661                assigned[slot] = Some((*value).clone());
2662            }
2663            None => positional.push(a),
2664        }
2665    }
2666    // Positional arguments fill the remaining EXPLICIT positions, in order.
2667    let mut next = 0usize;
2668    for a in positional {
2669        let slot = (next..arity)
2670            .find(|i| kinds[*i] == ParamKind::Explicit && assigned[*i].is_none())
2671            .ok_or_else(|| {
2672                KernelError::CertificationError(format!(
2673                    "too many arguments for `{name}`: it has {arity} parameter(s)"
2674                ))
2675            })?;
2676        assigned[slot] = Some((*a).clone());
2677        next = slot + 1;
2678    }
2679
2680    // How far down the telescope to go. `..` says "every position". Otherwise stop just past the
2681    // last position the caller actually addressed — a partially applied function must stay a
2682    // function, not η-expand into one — and then keep going over trailing IMPLICIT and INSTANCE
2683    // parameters, which the caller never writes and which the expected type may still pin.
2684    let last = assigned.iter().rposition(|a| a.is_some());
2685    let mut limit = if ellipsis {
2686        arity
2687    } else {
2688        last.map_or(0, |i| i + 1)
2689    };
2690    while limit < arity && kinds[limit] != ParamKind::Explicit {
2691        limit += 1;
2692    }
2693
2694    // Supplied values go through the SAME preparation a positional argument does, so `f (x := a)`
2695    // and `f a` cannot come to disagree about how `a` elaborates.
2696    let mut fills: Vec<Fill> = Vec::with_capacity(limit);
2697    for i in 0..limit {
2698        fills.push(match (&assigned[i], kinds[i]) {
2699            (Some(v), _) => Fill::Given(elab_surface(ctx, mctx, v, None)?),
2700            (None, ParamKind::Implicit | ParamKind::StrictImplicit) => Fill::Infer,
2701            (None, ParamKind::Instance) => Fill::Instance,
2702            // An explicit position the caller skipped: `..` says infer it, a DECLARED DEFAULT
2703            // fills it, and only with neither does a named argument further right η-abstract it.
2704            // Lean's order, and it is the only one that makes sense: a parameter the declaration
2705            // already answered for is not a parameter the caller was asked to skip.
2706            (None, ParamKind::Explicit) => {
2707                if ellipsis {
2708                    Fill::Infer
2709                } else {
2710                    match declared_default(ctx, head, i) {
2711                        Some(v) => Fill::Default(v),
2712                        None => Fill::Abstract(names[i].clone()),
2713                    }
2714                }
2715            }
2716        });
2717    }
2718
2719    let (t, _) = elaborate_spine(ctx, mctx, head, head_ty, &fills, expected)?;
2720    // `..` and `_` are the same request, and a hole that survived it is a hole the kernel would
2721    // match against ANY type. Say so here, naming the parameter, rather than emitting a term
2722    // whose ill-typedness surfaces somewhere else entirely.
2723    let t = instantiate(&t, mctx);
2724    if let Some(unsolved) = first_unsolved_meta(&t) {
2725        let how = if ellipsis {
2726            "`..`"
2727        } else {
2728            "the arguments given"
2729        };
2730        return Err(KernelError::CertificationError(format!(
2731            "a parameter of `{name}` is left undetermined by {how} ({unsolved}): nothing pins \
2732             it, so write it"
2733        )));
2734    }
2735    Ok(t)
2736}
2737
2738/// How many leading `Π`s a type has — a constructor's arity.
2739fn count_leading_pis(t: &Term) -> usize {
2740    let mut n = 0;
2741    let mut cur = t;
2742    while let Term::Pi { body_type, .. } = cur {
2743        n += 1;
2744        cur = body_type;
2745    }
2746    n
2747}
2748
2749/// The first still-unsolved metavariable in `t`, if any.
2750fn first_unsolved_meta(t: &Term) -> Option<String> {
2751    match t {
2752        Term::Var(n) if is_meta(n) => Some(n.clone()),
2753        Term::Pi {
2754            param_type,
2755            body_type,
2756            ..
2757        } => first_unsolved_meta(param_type).or_else(|| first_unsolved_meta(body_type)),
2758        Term::Lambda {
2759            param_type, body, ..
2760        } => first_unsolved_meta(param_type).or_else(|| first_unsolved_meta(body)),
2761        Term::App(f, a) => first_unsolved_meta(f).or_else(|| first_unsolved_meta(a)),
2762        Term::Match {
2763            discriminant,
2764            motive,
2765            cases,
2766        } => first_unsolved_meta(discriminant)
2767            .or_else(|| first_unsolved_meta(motive))
2768            .or_else(|| cases.iter().find_map(first_unsolved_meta)),
2769        Term::Fix { body, .. } => first_unsolved_meta(body),
2770        Term::MutualFix { defs, .. } => defs.iter().find_map(|(_, b)| first_unsolved_meta(b)),
2771        Term::Let {
2772            ty, value, body, ..
2773        } => first_unsolved_meta(ty)
2774            .or_else(|| first_unsolved_meta(value))
2775            .or_else(|| first_unsolved_meta(body)),
2776        Term::Annotated { term, .. } => first_unsolved_meta(term),
2777        _ => None,
2778    }
2779}
2780
2781/// Depth bound on recursive instance resolution — a backstop against a pathological
2782/// instance set (`Inhabited A` from `Inhabited A`) looping forever.
2783const MAX_INSTANCE_DEPTH: usize = 64;
2784
2785/// The head `Global` of an application spine (`Inhabited (List A)` → `Inhabited`).
2786fn head_global(t: &Term) -> Option<&str> {
2787    let mut cur = t;
2788    while let Term::App(f, _) = cur {
2789        cur = f;
2790    }
2791    match cur {
2792        Term::Global(n) => Some(n),
2793        _ => None,
2794    }
2795}
2796
2797/// The set of typeclass "heads" — the head `Global` of every registered instance's
2798/// CONCLUSION (`Inhabited (List A)` and `Inhabited Nat` both contribute `Inhabited`).
2799/// A parameter whose type has one of these heads is an instance PREMISE, to be resolved
2800/// recursively, rather than a type parameter solved by unifying the conclusion.
2801///
2802/// A DECLARED class with no registered instance contributes nothing here, which is why the
2803/// test is `class_heads ∪ registered structures` at every use site: in LOGOS a class IS a
2804/// structure, so a `[Lonely α]` premise is a premise from the moment `Lonely` is declared —
2805/// not from the moment someone instantiates it. Reading classhood off the instance vector
2806/// alone made an uninstantiated class invisible, and its premise was silently demoted to an
2807/// ordinary type parameter that unifying the conclusion could never determine.
2808fn class_heads(ctx: &Context) -> std::collections::HashSet<String> {
2809    ctx.instances()
2810        .iter()
2811        .chain(ctx.fallback_instances())
2812        .filter_map(|(ty, _)| {
2813            let mut cur = ty;
2814            while let Term::Pi { body_type, .. } = cur {
2815                cur = body_type;
2816            }
2817            head_global(cur).map(|s| s.to_string())
2818        })
2819        .collect()
2820}
2821
2822/// Whether the type `t` is an instance PREMISE — its head names a class, either because some
2823/// instance concludes at that head or because it is a registered structure (a declared class
2824/// with no instances yet).
2825fn is_premise(ctx: &Context, heads: &std::collections::HashSet<String>, t: &Term) -> bool {
2826    head_global(t).is_some_and(|h| heads.contains(h) || ctx.struct_info(h).is_some())
2827}
2828
2829/// Whether `t` still carries an unsolved metavariable. The elaborator's contract is that none
2830/// may reach the kernel, and an instance whose freshened telescope still holds one has not
2831/// been PROVEN to apply — it has only failed to be contradicted.
2832fn has_unsolved_meta(t: &Term) -> bool {
2833    match t {
2834        Term::Var(n) => is_meta(n),
2835        Term::App(f, a) => has_unsolved_meta(f) || has_unsolved_meta(a),
2836        Term::Pi {
2837            param_type,
2838            body_type,
2839            ..
2840        } => has_unsolved_meta(param_type) || has_unsolved_meta(body_type),
2841        Term::Lambda {
2842            param_type, body, ..
2843        } => has_unsolved_meta(param_type) || has_unsolved_meta(body),
2844        Term::Match {
2845            discriminant,
2846            motive,
2847            cases,
2848        } => {
2849            has_unsolved_meta(discriminant)
2850                || has_unsolved_meta(motive)
2851                || cases.iter().any(has_unsolved_meta)
2852        }
2853        Term::Fix { body, .. } => has_unsolved_meta(body),
2854        Term::MutualFix { defs, .. } => defs.iter().any(|(_, b)| has_unsolved_meta(b)),
2855        Term::Let {
2856            ty, value, body, ..
2857        } => has_unsolved_meta(ty) || has_unsolved_meta(value) || has_unsolved_meta(body),
2858        Term::Annotated { term, .. } => has_unsolved_meta(term),
2859        Term::Global(_) | Term::Sort(_) | Term::Const { .. } | Term::Lit(_) | Term::Hole => false,
2860    }
2861}
2862
2863/// Unify an instance's CONCLUSION with the goal, leaving the class's OUTPUT positions out of
2864/// the match (Lean's `outParam`).
2865///
2866/// An output is determined BY the instance, so it must not filter candidates: `Decode Bool β`
2867/// selects on `Bool` alone, and the `β` the instance yields is then checked against whatever
2868/// the context expected — an ordinary type error at the use site. Letting the output take part
2869/// turns that error into a DIFFERENT instance, or into "no instance found" for a class that
2870/// plainly has one.
2871///
2872/// The output positions are still unified opportunistically, on a trial context committed only
2873/// on success, so a goal whose output is an open metavariable (`Decode Bool ?β`) gets it solved
2874/// from the instance — which is the entire point of an output parameter.
2875fn unify_conclusion(ctx: &Context, mctx: &mut MetaCtx, conclusion: &Term, goal: &Term) -> bool {
2876    let (c_head, c_args) = spine(conclusion);
2877    let (g_head, g_args) = spine(goal);
2878    let outs = match (&c_head, &g_head) {
2879        (Term::Global(c), Term::Global(g)) if c == g => ctx.out_params(c),
2880        _ => &[][..],
2881    };
2882    if outs.is_empty() || c_args.len() != g_args.len() {
2883        return unify(ctx, mctx, conclusion, goal);
2884    }
2885    for (i, (c, g)) in c_args.iter().zip(g_args.iter()).enumerate() {
2886        if outs.contains(&i) {
2887            continue;
2888        }
2889        if !unify(ctx, mctx, c, g) {
2890            return false;
2891        }
2892    }
2893    for i in outs {
2894        if let (Some(c), Some(g)) = (c_args.get(*i), g_args.get(*i)) {
2895            let mut trial = mctx.clone();
2896            if unify(ctx, &mut trial, c, g) {
2897                *mctx = trial;
2898            }
2899        }
2900    }
2901    true
2902}
2903
2904/// Search the [`Context`]'s instance database for an instance proving `required`,
2905/// returning the (metavariable-instantiated) instance term. Handles POLYMORPHIC /
2906/// RECURSIVE instances (`instance {A} [Inhabited A] : Inhabited (List A)`): the instance's
2907/// parameter telescope is freshened to metavariables, its conclusion is unified against
2908/// `required` (solving the type parameters), and each PREMISE parameter is then resolved
2909/// RECURSIVELY. The first instance that fully resolves wins; failed trials never pollute
2910/// `mctx` (each runs on a clone, committed only on success).
2911pub fn resolve_instance(ctx: &Context, mctx: &mut MetaCtx, required: &Term) -> Option<Term> {
2912    resolve_instance_at(ctx, mctx, required, 0)
2913}
2914
2915/// Which TIER an instance was found in, and where inside it.
2916///
2917/// Lean tells you *that* an instance was synthesised; `set_option trace.Meta.synthInstance` tells
2918/// you a search log you then have to read backwards. This names the winner's coordinates directly,
2919/// which is what a translator actually needs when two sources disagree about which instance a goal
2920/// picked up.
2921#[derive(Debug, Clone, PartialEq, Eq)]
2922pub enum InstanceTier {
2923    /// An explicitly declared instance — `Context::instances()[index]`.
2924    Declared { index: usize },
2925    /// A library/derived FALLBACK instance — `Context::fallback_instances()[index]`.
2926    Fallback { index: usize },
2927}
2928
2929/// A resolved instance together with WHY it won — the audit trail Lean's instance resolution
2930/// does not expose.
2931///
2932/// `considered` lists, in the exact order they were tried, every candidate the search touched
2933/// before settling: `(tier, priority, whether it applied)`. A candidate that applied but lost
2934/// (an ambiguous hierarchy diamond) is therefore distinguishable from one that never matched,
2935/// which is the distinction that makes an "unexpected instance" bug findable.
2936#[derive(Debug, Clone)]
2937pub struct InstanceChoice {
2938    /// The instance term, with its metavariables instantiated — exactly what
2939    /// [`resolve_instance`] returns.
2940    pub value: Term,
2941    /// Where the winner came from.
2942    pub tier: InstanceTier,
2943    /// Its priority (Lean's default, 1000, unless declared otherwise). Fallback entries carry
2944    /// no priority of their own — the tier itself is the ranking — and report the default.
2945    pub priority: i64,
2946    /// Every candidate the search touched, in the order it touched them.
2947    pub considered: Vec<InstanceProbe>,
2948    /// How many declared instances the DISCRIMINATION INDEX excluded before any of them was
2949    /// tried — see [`Context::instance_search_order_for`].
2950    ///
2951    /// Lean's `getUnify` hands back the surviving entries and throws this number away, so
2952    /// "why was my instance never tried?" has no answer there short of reading a trace log
2953    /// backwards. Here it is a field: `considered.len() + pruned` is the whole database.
2954    pub pruned: usize,
2955}
2956
2957/// One candidate examined during instance resolution.
2958#[derive(Debug, Clone)]
2959pub struct InstanceProbe {
2960    /// Where the candidate lives.
2961    pub tier: InstanceTier,
2962    /// Its priority.
2963    pub priority: i64,
2964    /// Whether it unified with the goal and discharged all of its premises.
2965    pub applied: bool,
2966}
2967
2968/// [`resolve_instance`] with the search recorded — the same answer, plus which entry won, at
2969/// what priority and declaration index, and everything that was tried on the way.
2970///
2971/// The winner is guaranteed identical to `resolve_instance`'s: both call one search.
2972pub fn resolve_instance_audited(
2973    ctx: &Context,
2974    mctx: &mut MetaCtx,
2975    required: &Term,
2976) -> Option<InstanceChoice> {
2977    let mut audit = Vec::new();
2978    let mut pruned = 0;
2979    let found = search_instance(ctx, mctx, required, 0, Some(&mut audit), Some(&mut pruned));
2980    found.map(|(value, tier, priority)| InstanceChoice {
2981        value,
2982        tier,
2983        priority,
2984        considered: audit,
2985        pruned,
2986    })
2987}
2988
2989/// Turn `polyId Nat Zero` — a UNIVERSE-POLYMORPHIC declaration referenced by its bare name, with
2990/// its levels unwritten — into `polyId.{0} Nat Zero`, or `None` if `term` is not such a reference.
2991///
2992/// A Lean file writes a level explicitly almost never; `Context::get_global` deliberately does not
2993/// see `universe_polys` (only `Term::Const { name, levels }` reaches them), so before this every
2994/// reference to a polymorphic declaration had to spell its levels out and one that did not was
2995/// simply an unbound name.
2996///
2997/// THE RULE, which is first-order and stated rather than guessed: a binder whose domain is
2998/// literally `Sort ℓ` for a level PARAMETER `ℓ` is inhabited by a TYPE, and `ℓ` is the least level
2999/// at or above that type's own sort. So `polyId : Π(A : Sort u). A → A` applied to `Nat : Type 0`
3000/// solves `u := Type 0`, and applied to a type in `SProp`, which is a sort and never a level, solves
3001/// `u := Prop`.
3002///
3003/// Its limits are deliberate and loud rather than defaulted:
3004///
3005/// * a level parameter no argument determines is REFUSED with its name, not defaulted to `Type 0`
3006///   — a silently defaulted level is a monomorphisation nobody asked for; and
3007/// * a domain that merely MENTIONS a level parameter (`Sort (u+1)`, `Sort (max u v)`) is not
3008///   solved from here. That needs level metavariables in the unifier, which is a separate change
3009///   in the level algebra; this pass never guesses in its place.
3010fn solve_unwritten_levels(ctx: &Context, term: &Term) -> KernelResult<Option<Term>> {
3011    let (head, args) = spine(term);
3012    let Term::Global(name) = &head else {
3013        return Ok(None);
3014    };
3015    // A name that IS an ordinary global keeps its ordinary meaning — one name, one declaration.
3016    if ctx.get_global(name).is_some() {
3017        return Ok(None);
3018    }
3019    let Some((params, poly_ty, _)) = ctx.get_universe_poly(name) else {
3020        return Ok(None);
3021    };
3022    let (params, poly_ty) = (params.clone(), poly_ty.clone());
3023
3024    let mut subst: std::collections::HashMap<String, crate::term::Universe> =
3025        std::collections::HashMap::new();
3026    let mut cur = &poly_ty;
3027    for a in &args {
3028        let Term::Pi {
3029            param_type,
3030            body_type,
3031            ..
3032        } = cur
3033        else {
3034            break;
3035        };
3036        if let Term::Sort(crate::term::Universe::Var(p)) = param_type.as_ref() {
3037            if params.iter().any(|q| q == p) && !subst.contains_key(p) {
3038                if let Ok(Term::Sort(u)) = infer_type(ctx, a) {
3039                    subst.insert(p.clone(), u.least_level());
3040                }
3041            }
3042        }
3043        cur = body_type;
3044    }
3045
3046    let mut levels = Vec::with_capacity(params.len());
3047    for p in &params {
3048        match subst.get(p) {
3049            Some(u) => levels.push(u.clone()),
3050            None => {
3051                return Err(KernelError::CertificationError(format!(
3052                    "the level `{p}` of `{name}` is not determined by any argument — write it \
3053                     explicitly as `{name}.{{…}}`; defaulting it would silently monomorphise the \
3054                     declaration"
3055                )))
3056            }
3057        }
3058    }
3059    let rewritten = args.iter().fold(
3060        Term::Const {
3061            name: name.clone(),
3062            levels,
3063        },
3064        |f, a| Term::App(Box::new(f), Box::new(a.clone())),
3065    );
3066    Ok(Some(rewritten))
3067}
3068
3069/// Elaborate an ANONYMOUS CONSTRUCTOR `⟨f₀, …, fₙ⟩` (E3) against an EXPECTED inductive/
3070/// structure type `H a…`. It applies `H`'s (unique) constructor to the type parameters
3071/// `a…`, read off the expected type, then the field values — so `⟨Zero, true⟩` expected at
3072/// `Prod Nat Bool` becomes `Prod_mk Nat Bool Zero true`. Each field is elaborated against
3073/// its declared type (so coercions/implicits fire), and the whole is kernel-certified.
3074pub fn elaborate_anon_ctor(
3075    ctx: &Context,
3076    mctx: &mut MetaCtx,
3077    expected: &Term,
3078    fields: &[Term],
3079) -> KernelResult<Term> {
3080    let exp = crate::normalize(ctx, &instantiate(expected, mctx));
3081    let (head, args) = spine(&exp);
3082    let hname = match &head {
3083        Term::Global(n) => n.clone(),
3084        _ => {
3085            return Err(KernelError::CertificationError(format!(
3086                "anonymous constructor: expected type {exp} is not an inductive"
3087            )))
3088        }
3089    };
3090    // A trailing `..` says "fill the REMAINING fields", so it is stripped here and honoured
3091    // after the written fields have been applied.
3092    let ellipsis = fields.last().is_some_and(is_ellipsis_marker);
3093    let fields = if ellipsis {
3094        &fields[..fields.len() - 1]
3095    } else {
3096        fields
3097    };
3098    let ctors = ctx.get_constructors(&hname);
3099    let ctor = match ctors.as_slice() {
3100        [(c, _)] => c.to_string(),
3101        _ => {
3102            return Err(KernelError::CertificationError(format!(
3103                "anonymous constructor: `{hname}` does not have exactly one constructor"
3104            )))
3105        }
3106    };
3107    // Apply the constructor to the type parameters, then each field elaborated against its
3108    // declared domain.
3109    let mut applied = Term::Global(ctor.clone());
3110    for a in &args {
3111        applied = Term::App(Box::new(applied), Box::new(a.clone()));
3112    }
3113    for fv in fields {
3114        let dom = match resolve(ctx, mctx, &crate::infer_type(ctx, &applied)?) {
3115            Term::Pi { param_type, .. } => Some(*param_type),
3116            _ => None,
3117        };
3118        let (fe, fty) = elaborate(ctx, mctx, fv, dom.as_ref())?;
3119        let arg = if let Some(d) = &dom {
3120            if unify(ctx, mctx, &fty, d) {
3121                fe
3122            } else {
3123                let (fty_i, d_i) = (instantiate(&fty, mctx), instantiate(d, mctx));
3124                coerce_term(ctx, mctx, &fe, &fty_i, &d_i).unwrap_or(fe)
3125            }
3126        } else {
3127            fe
3128        };
3129        applied = Term::App(Box::new(applied), Box::new(arg));
3130    }
3131    // `⟨a, ..⟩` — every field the writer did not name becomes a hole to SOLVE, exactly as `_`
3132    // would. With nothing left to fill this is a no-op, which is what makes a trailing `..` on a
3133    // complete literal the same term as the literal.
3134    if ellipsis {
3135        // Counted off the CONSTRUCTOR'S declared arity rather than by re-inferring the type after
3136        // each fill: a spine carrying an unsolved metavariable has no inferrable type, so asking
3137        // would report an unbound `?0` instead of the missing field.
3138        let total = ctx.get_global(&ctor).map(count_leading_pis).unwrap_or(0);
3139        for _ in (args.len() + fields.len())..total {
3140            applied = Term::App(Box::new(applied), Box::new(mctx.fresh()));
3141        }
3142    }
3143    crate::infer_type(ctx, &applied)?;
3144    let applied = instantiate(&applied, mctx);
3145    if let Some(unsolved) = first_unsolved_meta(&applied) {
3146        return Err(KernelError::CertificationError(format!(
3147            "`⟨…, ..⟩` left a field of `{hname}` undetermined ({unsolved}): nothing in the \
3148             expected type pins it, so write it"
3149        )));
3150    }
3151    Ok(applied)
3152}
3153
3154/// Elaborate DOT notation `receiver.field` (E4). The receiver's type head names an
3155/// inductive/structure `H`; the projection is `H_field` (K4's convention), applied to `H`'s
3156/// parameters — read off the receiver's type — and then the receiver itself. So
3157/// `p.fst` with `p : Prod A B` becomes `Prod_fst A B p`. Returns an error if no such
3158/// projection exists or the result does not type-check.
3159pub fn elaborate_dot(
3160    ctx: &Context,
3161    mctx: &mut MetaCtx,
3162    receiver: &Term,
3163    field: &str,
3164) -> KernelResult<Term> {
3165    let (r_elab, r_ty) = elaborate(ctx, mctx, receiver, None)?;
3166    let r_ty = crate::normalize(ctx, &instantiate(&r_ty, mctx));
3167    let (head, args) = spine(&r_ty);
3168    let hname = match &head {
3169        Term::Global(n) => n.clone(),
3170        _ => {
3171            return Err(KernelError::CertificationError(format!(
3172                "dot notation `.{field}`: the receiver's type {r_ty} is not headed by an inductive"
3173            )))
3174        }
3175    };
3176    let proj = format!("{hname}_{field}");
3177    if ctx.get_global(&proj).is_none() {
3178        return Err(KernelError::CertificationError(format!(
3179            "dot notation: no projection `{proj}` for field `{field}` of `{hname}`"
3180        )));
3181    }
3182    // `H_field params… receiver`.
3183    let mut applied = Term::Global(proj);
3184    for a in &args {
3185        applied = Term::App(Box::new(applied), Box::new(a.clone()));
3186    }
3187    applied = Term::App(Box::new(applied), Box::new(r_elab));
3188    // Certify it type-checks (the projection's arity/positions line up).
3189    crate::infer_type(ctx, &applied)?;
3190    Ok(applied)
3191}
3192
3193/// How many `Coe` steps a chain may compose. Lean's `CoeT` head/body/tail decomposition is
3194/// likewise bounded; the bound is what makes a CYCLIC coercion set (`A ⇒ B`, `B ⇒ A`) report
3195/// "no path" instead of searching forever.
3196const MAX_COERCION_STEPS: usize = 8;
3197
3198/// Find a registered coercion carrying `from` to `to` (up to unification), returning the
3199/// coercion FUNCTION to wrap the argument in — Lean's `↑`. The elaborator calls this when
3200/// an argument's type does not match the expected parameter type; a match commits the
3201/// unification (a polymorphic coercion's type variables get solved).
3202///
3203/// A single registered step is returned as ITSELF. A composed chain is returned as the
3204/// λ-abstraction of the composite, so the function is always something that can be applied to
3205/// one argument whatever its length; elaboration itself uses `coerce_term`, which applies
3206/// the steps directly and so leaves no β-redex behind.
3207pub fn resolve_coercion(ctx: &Context, mctx: &mut MetaCtx, from: &Term, to: &Term) -> Option<Term> {
3208    let path = coercion_path(ctx, mctx, from, to)?;
3209    match path.as_slice() {
3210        [single] => Some(single.clone()),
3211        steps => {
3212            let arg = Term::Var("↑x".to_string());
3213            let body = steps
3214                .iter()
3215                .fold(arg, |acc, f| Term::App(Box::new(f.clone()), Box::new(acc)));
3216            Some(Term::Lambda {
3217                param: "↑x".to_string(),
3218                param_type: Box::new(instantiate(from, mctx)),
3219                body: Box::new(body),
3220            })
3221        }
3222    }
3223}
3224
3225/// Wrap `term` (of type `from`) in the coercion path that carries it to `to`, or return `None`
3226/// if there is none. The steps are applied OUTWARD from the term, so a two-step bridge reads
3227/// `g (f x)` — the shape Lean's elaborated `↑↑x` has, and one the kernel reduces without a
3228/// β-step.
3229fn coerce_term(
3230    ctx: &Context,
3231    mctx: &mut MetaCtx,
3232    term: &Term,
3233    from: &Term,
3234    to: &Term,
3235) -> Option<Term> {
3236    let path = coercion_path(ctx, mctx, from, to)?;
3237    Some(
3238        path.into_iter()
3239            .fold(term.clone(), |acc, f| Term::App(Box::new(f), Box::new(acc))),
3240    )
3241}
3242
3243/// The shortest chain of registered coercions carrying `from` to `to`, as the functions to
3244/// apply in order (innermost first).
3245///
3246/// Lean composes `Coe` instances transitively — `CoeT` chains a head, a body and a tail — so
3247/// `Bit → Bool` and `Bool → Nat` bridge a `Bit` where a `Nat` is wanted with no `Bit → Nat`
3248/// instance declared. This is that closure, as a breadth-first search so the path found is the
3249/// SHORTEST (hence deterministic where several exist), bounded by [`MAX_COERCION_STEPS`] and
3250/// guarded by a visited set so a cyclic coercion set terminates.
3251///
3252/// Unification is done on a trial context per edge and the winning path's solutions are
3253/// committed to `mctx` only once the target is reached — a failed branch never pollutes the
3254/// caller's metavariables.
3255fn coercion_path(ctx: &Context, mctx: &mut MetaCtx, from: &Term, to: &Term) -> Option<Vec<Term>> {
3256    if ctx.coercions().is_empty() {
3257        return None;
3258    }
3259    // (type reached, the metavariable state that reached it, the functions applied so far).
3260    let mut frontier: Vec<(Term, MetaCtx, Vec<Term>)> =
3261        vec![(instantiate(from, mctx), mctx.clone(), Vec::new())];
3262    let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
3263    seen.insert(format!("{}", instantiate(from, mctx)));
3264
3265    for _ in 0..MAX_COERCION_STEPS {
3266        let mut next: Vec<(Term, MetaCtx, Vec<Term>)> = Vec::new();
3267        for (node, state, path) in frontier {
3268            for (c_from, c_to, c_fn) in ctx.coercions() {
3269                let mut trial = state.clone();
3270                if !unify(ctx, &mut trial, c_from, &node) {
3271                    continue;
3272                }
3273                let reached = instantiate(c_to, &trial);
3274                let mut path = path.clone();
3275                path.push(instantiate(c_fn, &trial));
3276                // Arrived? Only the final step has to meet the TARGET type.
3277                let mut arrived = trial.clone();
3278                if unify(ctx, &mut arrived, &reached, to) {
3279                    *mctx = arrived;
3280                    return Some(path);
3281                }
3282                if seen.insert(format!("{reached}")) {
3283                    next.push((reached, trial, path));
3284                }
3285            }
3286        }
3287        if next.is_empty() {
3288            return None;
3289        }
3290        frontier = next;
3291    }
3292    None
3293}
3294
3295/// If `inst_val` is a derived parent-forget edge, the parent class it reaches. A HIERARCHY
3296/// ROUTE, unlike an ordinary instance, is not something anyone declared for this goal — it is
3297/// generated from an `extends` relation, so two routes to one parent are a DIAMOND rather than
3298/// a deliberate overlap, and their dictionaries have to agree.
3299fn parent_route(ctx: &Context, inst_val: &Term) -> Option<String> {
3300    ctx.parent_edge_target(head_global(inst_val)?)
3301        .map(|s| s.to_string())
3302}
3303
3304fn resolve_instance_at(
3305    ctx: &Context,
3306    mctx: &mut MetaCtx,
3307    required: &Term,
3308    depth: usize,
3309) -> Option<Term> {
3310    search_instance(ctx, mctx, required, depth, None, None).map(|(value, _, _)| value)
3311}
3312
3313/// The ONE instance search. `resolve_instance`, `resolve_instance_at` and
3314/// `resolve_instance_audited` are all views of it, so no caller can be served by a different
3315/// ordering rule than another.
3316///
3317/// ORDER — Lean's, stated by [`Context::instance_search_order`]: higher priority first, then the
3318/// LATER declaration. The same order for every goal, whether or not the goal still carries an
3319/// unsolved metavariable. The previous two-tier scheme (forward for a pinned goal, backward for
3320/// an open one) had to exist because the forward direction is wrong for an open goal — the
3321/// earliest entry that unifies INVENTS the class variable from its own carrier — but it is
3322/// equally wrong for a pinned one, where it inverts every tie-break a Lean source relies on.
3323/// Once the rule is later-first, the two cases are the same case.
3324///
3325/// TIERS — `instances()` first, and only if the whole of it failed, `fallback_instances()`.
3326/// A fallback is a library or declaration-time entry (`decEq{I}`); it must be findable and must
3327/// never outrank something a user declared.
3328fn search_instance(
3329    ctx: &Context,
3330    mctx: &mut MetaCtx,
3331    required: &Term,
3332    depth: usize,
3333    mut audit: Option<&mut Vec<InstanceProbe>>,
3334    pruned_out: Option<&mut usize>,
3335) -> Option<(Term, InstanceTier, i64)> {
3336    if depth > MAX_INSTANCE_DEPTH {
3337        return None;
3338    }
3339    let heads = class_heads(ctx);
3340
3341    // THE INDEX, not a scan. `Context::instance_search_order_for` is a SUBSET of
3342    // `instance_search_order()` in the same relative order, so this changes what the search pays
3343    // and never what it answers — and the goal is instantiated first, because a goal still
3344    // carrying an unsolved metavariable at its head has no key and must see everything.
3345    let indexed_goal = instantiate(required, mctx);
3346    let (candidates, pruned) = ctx.instance_search_order_for(&indexed_goal);
3347    if let Some(slot) = pruned_out {
3348        *slot = pruned;
3349    }
3350    let declared = candidates.into_iter().map(|i| {
3351        (
3352            InstanceTier::Declared { index: i },
3353            ctx.instance_priority(i),
3354            &ctx.instances()[i],
3355        )
3356    });
3357    // The lower tier keeps the same tie-break — later declaration first — so one rule governs
3358    // both, and a fallback registered later (a re-derivation) supersedes its own predecessor.
3359    // Apply the same conservative head discrimination before cloning trial metas or
3360    // unifying a fallback. This lower tier keeps its original reverse order.
3361    let fallback = std::iter::once_with(|| ctx.fallback_instance_search_order_for(&indexed_goal))
3362        .flatten()
3363        .map(|i| {
3364            (
3365                InstanceTier::Fallback { index: i },
3366                crate::context::DEFAULT_INSTANCE_PRIORITY,
3367                &ctx.fallback_instances()[i],
3368            )
3369        });
3370
3371    let mut chosen: Option<(MetaCtx, Term, InstanceTier, i64)> = None;
3372    let mut exhausted_declared = false;
3373    for (tier, priority, (inst_ty, inst_val)) in declared.chain(fallback) {
3374        // The fallback tier is a strictly LOWER tier, not a continuation of the scan: an answer
3375        // from `instances()` is returned before a fallback is even considered.
3376        if matches!(tier, InstanceTier::Fallback { .. }) && !exhausted_declared {
3377            exhausted_declared = true;
3378            if let Some((trial, result, t, p)) = chosen.take() {
3379                *mctx = trial;
3380                return Some((result, t, p));
3381            }
3382        }
3383        let mut trial = mctx.clone();
3384        let result = try_instance(ctx, &mut trial, inst_ty, inst_val, required, &heads, depth);
3385        if let Some(a) = audit.as_deref_mut() {
3386            a.push(InstanceProbe {
3387                tier: tier.clone(),
3388                priority,
3389                applied: result.is_some(),
3390            });
3391        }
3392        let Some(result) = result else { continue };
3393        match &chosen {
3394            // The first candidate wins unless it is a hierarchy route, in which case the scan
3395            // continues to see whether a SECOND route reaches the same parent.
3396            None if parent_route(ctx, inst_val).is_none() => {
3397                *mctx = trial;
3398                return Some((result, tier, priority));
3399            }
3400            None => chosen = Some((trial, result, tier, priority)),
3401            Some((_, first, _, _)) => {
3402                if parent_route(ctx, inst_val).is_some()
3403                    && !crate::type_checker::def_eq(ctx, first, &result)
3404                {
3405                    // An INCOHERENT diamond. Both routes type-check and carry different data,
3406                    // so picking one silently mistranslates the source: the disagreement
3407                    // surfaces later as an unrelated proof failing `def_eq` arbitrarily far
3408                    // from the diamond. No answer is better than an arbitrary one.
3409                    return None;
3410                }
3411            }
3412        }
3413    }
3414    if let Some((trial, result, tier, priority)) = chosen {
3415        *mctx = trial;
3416        return Some((result, tier, priority));
3417    }
3418
3419    // THE DERIVED TIER — last, and only for a goal nothing declared answers.
3420    //
3421    // `Decidable (Eq I a b)` for an inductive `I` is Lean's `deriving DecidableEq`: the decision
3422    // procedure is DERIVABLE from the constructor list, so requiring a human to have written and
3423    // registered one is requiring a transcription, not a proof. Deriving it here — at the USE site,
3424    // from the same `recursor::derive_dec_eq` a declaration would have used — means the instance
3425    // exists for every inductive without the standard library paying to synthesise constants for
3426    // types nobody asks about.
3427    let derived = derived_dec_eq_candidate(ctx, &instantiate(required, mctx))?;
3428    let mut trial = mctx.clone();
3429    let result = try_instance(
3430        ctx, &mut trial, &derived.0, &derived.1, required, &heads, depth,
3431    )?;
3432    if let Some(a) = audit.as_deref_mut() {
3433        a.push(InstanceProbe {
3434            tier: InstanceTier::Fallback { index: usize::MAX },
3435            priority: crate::context::DEFAULT_INSTANCE_PRIORITY,
3436            applied: true,
3437        });
3438    }
3439    *mctx = trial;
3440    Some((
3441        result,
3442        InstanceTier::Fallback { index: usize::MAX },
3443        crate::context::DEFAULT_INSTANCE_PRIORITY,
3444    ))
3445}
3446
3447/// The `(type, value)` of a DERIVED decidable-equality instance for the goal `required`, if the
3448/// goal has the shape `Decidable (Eq I a b)` with `I` an inductive.
3449///
3450/// Two sources, in this order:
3451///
3452/// 1. a `decEq{I}` already in scope — hand-written (the prelude's `decEqNat`/`decEqBool`) or
3453///    synthesised by a declaration. Preferred, because a human-written procedure is the one whose
3454///    behaviour other proofs were written against;
3455/// 2. otherwise DERIVED on the spot, with every auxiliary it depends on INLINED into it so the
3456///    result is a closed term that needs nothing registered, and then KERNEL-CHECKED before it is
3457///    handed back. An untrusted derivation that does not check is declined, never returned.
3458///
3459/// The returned value is a candidate for `try_instance`, so the parameter telescope is freshened
3460/// and a `decEq` premise for a type parameter is resolved RECURSIVELY through this same tier —
3461/// which is how `Decidable (Eq (List Colour) …)` is answered without either being registered.
3462fn derived_dec_eq_candidate(ctx: &Context, goal: &Term) -> Option<(Term, Term)> {
3463    // `Decidable p`
3464    let (head, args) = spine(goal);
3465    if !matches!(&head, Term::Global(n) if n == "Decidable") || args.len() != 1 {
3466        return None;
3467    }
3468    // `Eq A a b`
3469    let (eq_head, eq_args) = spine(&args[0]);
3470    if !matches!(&eq_head, Term::Global(n) if n == "Eq") || eq_args.len() != 3 {
3471        return None;
3472    }
3473    let ind = head_global(&eq_args[0])?.to_string();
3474    if !ctx.is_inductive(&ind) {
3475        return None;
3476    }
3477    let name = format!("decEq{ind}");
3478    if let Some(ty) = ctx.get_global(&name) {
3479        return Some((ty.clone(), Term::Global(name)));
3480    }
3481    // Derive the whole group (it comes back in dependency order) and inline each earlier member
3482    // into the later ones, so `decEq{I}`'s term no longer references constants that were never
3483    // registered.
3484    let group = crate::recursor::derive_auxiliaries(ctx, &ind);
3485    let mut resolved: Vec<(String, Term)> = Vec::with_capacity(group.len());
3486    let mut answer: Option<(Term, Term)> = None;
3487    for aux in group {
3488        let mut term = aux.term;
3489        let mut ty = aux.ty;
3490        for (dep_name, dep_term) in &resolved {
3491            term = inline_global(&term, dep_name, dep_term);
3492            ty = inline_global(&ty, dep_name, dep_term);
3493        }
3494        if aux.name == name {
3495            answer = Some((ty, term));
3496            break;
3497        }
3498        resolved.push((aux.name, term));
3499    }
3500    let (ty, term) = answer?;
3501    // KERNEL-CHECKED before it is trusted: `derive_*` is untrusted front-end code, and an
3502    // instance is a term the surrounding proof will be built on.
3503    let inferred = crate::infer_type(ctx, &term).ok()?;
3504    if !crate::is_subtype(ctx, &inferred, &ty) {
3505        return None;
3506    }
3507    Some((ty, term))
3508}
3509
3510/// Replace every `Global(name)` in `t` by `value`. Used to close a derived term over auxiliaries
3511/// that were never registered; both sides are closed terms, so no binder can capture.
3512fn inline_global(t: &Term, name: &str, value: &Term) -> Term {
3513    match t {
3514        Term::Global(n) if n == name => value.clone(),
3515        Term::App(f, a) => Term::App(
3516            Box::new(inline_global(f, name, value)),
3517            Box::new(inline_global(a, name, value)),
3518        ),
3519        Term::Pi {
3520            param,
3521            param_type,
3522            body_type,
3523        } => Term::Pi {
3524            param: param.clone(),
3525            param_type: Box::new(inline_global(param_type, name, value)),
3526            body_type: Box::new(inline_global(body_type, name, value)),
3527        },
3528        Term::Lambda {
3529            param,
3530            param_type,
3531            body,
3532        } => Term::Lambda {
3533            param: param.clone(),
3534            param_type: Box::new(inline_global(param_type, name, value)),
3535            body: Box::new(inline_global(body, name, value)),
3536        },
3537        Term::Match {
3538            discriminant,
3539            motive,
3540            cases,
3541        } => Term::Match {
3542            discriminant: Box::new(inline_global(discriminant, name, value)),
3543            motive: Box::new(inline_global(motive, name, value)),
3544            cases: cases
3545                .iter()
3546                .map(|c| inline_global(c, name, value))
3547                .collect(),
3548        },
3549        Term::Fix { name: f, body } => Term::Fix {
3550            name: f.clone(),
3551            body: Box::new(inline_global(body, name, value)),
3552        },
3553        Term::MutualFix { defs, index } => Term::MutualFix {
3554            defs: defs
3555                .iter()
3556                .map(|(n, b)| (n.clone(), inline_global(b, name, value)))
3557                .collect(),
3558            index: *index,
3559        },
3560        Term::Let {
3561            name: l,
3562            ty,
3563            value: v,
3564            body,
3565        } => Term::Let {
3566            name: l.clone(),
3567            ty: Box::new(inline_global(ty, name, value)),
3568            value: Box::new(inline_global(v, name, value)),
3569            body: Box::new(inline_global(body, name, value)),
3570        },
3571        Term::Annotated { annotation, term } => Term::Annotated {
3572            annotation: annotation.clone(),
3573            term: Box::new(inline_global(term, name, value)),
3574        },
3575        Term::Var(_)
3576        | Term::Global(_)
3577        | Term::Sort(_)
3578        | Term::Lit(_)
3579        | Term::Hole
3580        | Term::Const { .. } => t.clone(),
3581    }
3582}
3583
3584/// Attempt one instance against `required`: freshen its parameters to metavariables,
3585/// unify its conclusion with `required`, and recursively resolve every premise parameter.
3586#[allow(clippy::too_many_arguments)]
3587fn try_instance(
3588    ctx: &Context,
3589    mctx: &mut MetaCtx,
3590    inst_ty: &Term,
3591    inst_val: &Term,
3592    required: &Term,
3593    heads: &std::collections::HashSet<String>,
3594    depth: usize,
3595) -> Option<Term> {
3596    // Freshen: peel the parameter telescope, replacing each parameter by a fresh
3597    // metavariable and recording which are instance premises. `applied` accumulates the
3598    // instance value applied to those metavariables.
3599    let mut applied = inst_val.clone();
3600    let mut premises: Vec<(Term, Term)> = Vec::new(); // (metavariable, premise type)
3601    let mut cur = inst_ty.clone();
3602    loop {
3603        match cur {
3604            Term::Pi {
3605                param,
3606                param_type,
3607                body_type,
3608            } => {
3609                let mv = mctx.fresh();
3610                if is_premise(ctx, heads, &param_type) {
3611                    premises.push((mv.clone(), (*param_type).clone()));
3612                }
3613                applied = Term::App(Box::new(applied), Box::new(mv.clone()));
3614                cur = substitute(&body_type, &param, &mv);
3615            }
3616            conclusion => {
3617                // The conclusion must match the goal (this solves the type parameters), with
3618                // the class's OUTPUT positions left out of the match.
3619                if !unify_conclusion(ctx, mctx, &conclusion, required) {
3620                    return None;
3621                }
3622                // Each premise is now (after that unification) a ground class goal; resolve
3623                // it recursively and bind its metavariable to the result.
3624                for (pm, pty) in &premises {
3625                    let sub_goal = instantiate(pty, mctx);
3626                    let resolved = resolve_instance_at(ctx, mctx, &sub_goal, depth + 1)?;
3627                    // Bind the premise's metavariable directly, keeping the (possibly
3628                    // nested) resolved instance structured.
3629                    match pm {
3630                        Term::Var(name) => mctx.solve(name, resolved),
3631                        _ => return None,
3632                    }
3633                }
3634                // DETERMINACY. Every position the telescope was freshened into must now be
3635                // solved. One that is not means the instance was never shown to apply — a
3636                // premise nothing discharged, or a parameter the conclusion never mentions —
3637                // and committing it would emit a `?`-variable that the kernel later reports as
3638                // an unbound name, arbitrarily far from the instance that produced it.
3639                let result = instantiate(&applied, mctx);
3640                if has_unsolved_meta(&result) {
3641                    return None;
3642                }
3643                return Some(result);
3644            }
3645        }
3646    }
3647}
3648
3649#[cfg(test)]
3650#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/elaborate/pi_exposure_controls.rs"]
3651mod pi_exposure_controls;
3652
3653#[cfg(test)]
3654#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/elaborate/fallback_prefilter_controls.rs"]
3655mod fallback_prefilter_controls;
3656
3657#[cfg(test)]
3658thread_local! { static LAZY_UNIFY_FULL_NORMALIZATIONS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; }
3659#[cfg(test)]
3660#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/elaborate/lazy_positive_controls.rs"]
3661mod lazy_positive_controls;
3662
3663#[path = "elaborate_positive.rs"]
3664mod positive;
3665
3666#[cfg(test)]
3667#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/elaborate/core_pi_exposure_controls.rs"]
3668mod core_pi_exposure_controls;
3669
3670#[cfg(test)]
3671#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/elaborate/compact_data_controls.rs"]
3672mod compact_data_controls;
3673
3674#[cfg(test)]
3675#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/elaborate/scoped_positive_controls.rs"]
3676mod scoped_positive_controls;
3677
3678#[cfg(test)]
3679#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/elaborate/natural_observation_controls.rs"]
3680mod natural_observation_controls;