lang::typecheck::infer
lang/src/typecheck/infer.mo
pub struct TypedTerm {
term : Term,
typ : Term,
}A type-checked term paired with its type.
pub struct CheckedCase {
case_ : MatchCase,
body_typ_ : Term,
}A type-checked match case with inferred body type.
pub struct CaseAcc {
body_typ : Term,
cases : List MatchCase,
}Accumulator for processing match cases: the unified body type and the checked cases in reverse order.
pub def empty_locals : LocalScopeEmpty local scope (no local bindings).
pub def empty_local_types : List TermEmpty list of local types (no de Bruijn bindings).
pub def type_check (term : Term) (expected_type : Term) (scope : Scope) (local_types : List Term) (locals : LocalScope) : Result TypeError TypedTermType check a term bidirectionally.
Term.quote_/Term.var_macro are macro-expansion-only shapes --
quote_ is resolved away by macro_expand.mo's resolve_quote
before type-checking ever runs, and var_macro only ever appears
inside an unexpanded macro template. Neither should reach here in
the real pipeline (expand_decls always runs first), but this match
previously had no arm for either -- a genuine non-exhaustive-match
crash risk (no #[partial] on this def) if a macro ever expanded to
another macro call without fully resolving it. A clean TypeError
is safer than a raw interpreter crash either way.
Several arms return their OWN type without comparing it against
expected_type (type_check_lit, type_check_con, and
type_check_bound_var behind type_check_var). That is deliberate
here and gated one level up instead: lang/module.mo's
body_signature_diagnostics compares a def BODY's checked type against
the def's declared one, which is where the difference is a bug rather
than a placeholder.
pub def body_type_error (body : Term) (inferred : Term) (expected : Term)
(scope : Scope) (locals : LocalScope) : Option TypeErrorThe ONE definition of "is this body's type the type it was expected to
have", shared by def bodies (lang/module.mo's
body_signature_diagnostics, i.e. every top-level def) and lambda
bodies (type_check_lam_explicit, i.e. the parameterised half).
It exists because type_check returns its own idea of a term's type,
and for several arms that idea is either not compared against
expected_type at all (type_check_lit, type_check_con,
type_check_bound_var) or is a placeholder. unify accepts a
Term.hole on either side, so the comparison only ever bites where
both sides carry real information -- which is exactly where silence was
a bug: def p : I64 := "hello" used to check cleanly.
Four guards, each forced by a corpus measurement rather than written defensively:
- a body containing a
Term.holeis not a finished body:def p1 : T -> T := apply (fn x => x) _infersT, becausetype_check_appdoes not carry the callee's return type through a hole ARGUMENT (lang/src/module.mo's owntest_hole_in_infer_position_accepts_named_callee*pins); - either side mentioning a skolemized or unbound type variable is not
a fair comparison: a generic def's body infers an INSTANTIATED type
(
def empty_arities : HashMap String I64 := str_map_emptyinfersHashMap String V;lang.scope'snpath_map_emptyinfersHashMap K V); - two SORTS are compared by CUMULATIVITY (
type_check_sort_full), whichunifydoes not implement --let _f : (Sort 1 -> Sort 2) := fn x => x(init/src/tests.mo'stest_pi_universe) is legitimate andunify (Sort 2) (Sort 1)rejects it.
pub def type_head_name (t : Term) : Option IdentifierUnwrap a Term.app f a chain down to its head, returning the
Identifier if that head is a named free/global variable (Term.var _ (DebugName.named id)) -- covers both a bare type reference
(List) and an applied generic (List Identifier). Option.none
for anything else (Term.hole, a bound/unnamed var, ...) -- those
cases fall back to find_inductive_for_cases_by_constructor below.
A location wrapper is transparent here, and the Term.ctx arm is what
makes that structural rather than a per-call-site obligation (R10,
plans/type-system/core-term-simplification.md). It matters because
this function's Option.none is not an error -- it is a fallback to
an ambiguous constructor-name scan -- so a wrapper that stops the
match does not crash or fail to type: it makes an inductive resolve by
the WRONG path. Placement rule R1 keeps wrappers out of type position
(lower_parse_term_bare), which is why this has not been seen live;
class FromListLiteral (term_matches_carrier's own doc comment) is
the measured regression from the one site that did not have that
guarantee. The arm is the guarantee.
pub def find_inductive_for_cases_by_constructor (cases : List MatchCase) (scope : Scope) : Result TypeError (Option Inductive)The last-resort constructor-name-scan lookup -- still the correct
behavior when the scrutinee's own type isn't concretely known via any
of the preferred paths above, but now detects a genuine AMBIGUITY
(more than one inductive with a matching constructor name -- always
true between any two structs, whose auto-generated constructor is
always mk) and fails loudly instead of silently returning whichever
candidate HashMap.to_list's arbitrary bucket order finds first (see
scope_find_all_inductives_by_constructor's own doc comment,
lang/scope.mo, for the confirmed-live silent-wrong-value repro this
closes). A single, unambiguous match still resolves exactly as
before.
Pub because the check path's coverage-warning collector
(lang/module.mo) resolves a match's inductive exactly this way --
same fallback, same ambiguity behavior -- so the two cannot drift
about which match a gap is reported for.
pub def match_coverage_gap (cases : List MatchCase) (maybe_ind : Option Inductive) (scope : Scope) : Option (Pair Inductive (List NamePath))The rule as a pure QUERY: the uncovered constructors of this match, or
Option.none when it is covered, unresolved, or exempted. One place, so
the check that warns and a future check that errors cannot disagree about
what "uncovered" means -- the same single-source-of-truth reason the host
computes its use-completeness findings in one function
(unimported_names, rust/core/src/term/module.rs).
pub def match_coverage_gap_at (cases : List MatchCase) (maybe_ind : Option Inductive) (sc_typ : Term) (scope : Scope)
: Option (Pair Inductive (List NamePath))match_coverage_gap for a scrutinee of type sc_typ: a constructor whose
declared indices clash with the scrutinee's (nil against Vec (succ n) A) can never match, so it is not missing. An unknown type prunes nothing.
pub def match_coverage_warning (cases : List MatchCase) (maybe_ind : Option Inductive) (scope : Scope) : Option StringThe warning text for a coverage gap, or Option.none when there is none.
The message is prefix-free; the severity word comes from the renderer
(render_type_warning, lang/typecheck/diagnostic.mo).
pub struct IndexedArm {
ind : Inductive,
ctor : InductConstructor,
solution : IndexSolution,
}A positional arm of an INDEXED family whose constructor indices solved
against the scrutinee (ctor_refine.mo).
pub struct ResolvedFieldPattern {
resolved_name : Identifier,
declared_names : List Identifier,
declared_types : List Term,
written_to_declared : List I64,
}Resolved shape of a field-pattern match case: the real constructor
name (never case_'s own possibly-empty bare-form name), its
declared field names/types (in DECLARED order -- what
prepend_typed/prepend_typed_local_vars need to build the correct
local scope for the case body), and written_to_declared (parallel
to the pattern's own written fields: written_to_declared[w] is the
declared-order position written slot w fills) -- what
term_permute needs to retarget the ALREADY-PARSED body.
pub struct DccPair {
elab_args : List Term,
subst : List (Pair Identifier Term),
/// Level variables solved from the arguments so far (W1.4), keyed by
/// name exactly like `subst` is keyed by type variable. Threaded
/// beside `subst` rather than inside it because a `SortLevel` is not a
/// `Term`; `try_type_check_def_call` applies it to the return type
/// with `subst_levels_term`.
levels : List (Pair Identifier SortLevel),
}pub type CallArgOutcome {
ok (pair : DccPair),
decline,
type_error (err : TypeError),
}What the signature-driven argument loop concluded.
The probe is fail-open by design (try_type_check_def_call's own doc
comment): "this checker could not type this call this way" must fall
back to the ordinary path, so every pre-existing err is a decline.
type_error is the one real mismatch -- falling back cannot rescue it,
because the ordinary path checks that argument against Term.hole --
so it escapes the probe like validate_dict_hints' own hard error.
pub struct SigInfo {
params : List Term,
ret : Term,
}A signature decomposed for try_type_check_def_call: its explicit
Term.pi chain's parameter types, and the final return type. Its
implicit type parameters need no separate field: a def's registered
Def.typ stores them as FREE vars (Term.var sentinel ...) -- the
parser leaves them free and elaborate_def_typs (lang/module.mo)
forall-wraps them only AFTER the scope (and its def_sigs entries)
is built -- and solve_typevars records every free-var match it
finds, no precomputed name set required.
pub struct CalleeDomain {
dom : Term,
vars : List Identifier,
subst : List (Pair Identifier Term),
}A callee's domain at the argument position we are about to check, together with the names the callee's own declaration binds.
The names travel with the domain because they ARE the test that decides
whether the domain may be handed to a lambda (see lam_binder_hint), and
which names are variables depends on where the declaration came from and
not on its shape at all -- the same point sig_hints makes for the
resolution pass's identical hint, whose names parameter exists for the
same reason.
subst is what solved dom from the DECLARED parameter (empty for an
inferred, non-class callee). A consumer that needs another part of the
declaration solved the same way must start from the declaration and
apply this list, never re-substitute dom: once solved, dom may hold
a CALLER's type variable that shares a class variable's spelling (a
{M : Type} message type under Monad's M), and a second pass
rewrites it.
pub def lam_binder_hint (cd : CalleeDomain) (scope : Scope) : Option TermThe binder type an unannotated lambda argument should learn from its
callee, or Option.none when the callee's domain is not usable as one.
Only the DOMAIN is asserted, never the codomain -- the caller builds
Term.pi bt Term.hole, not the callee's Pi verbatim. The lambda's real
expected type is Term.pi dom ret, and handing that over whole would make
type_check_lam's branch A check the continuation's body against a ret
like IO B whose B is an unsolved free variable; with no metas there is
nothing to solve it against, so every do-bind in the corpus would fail on a
variable the checker cannot solve. The binder's type is what this bug is
about, and it is what gets enforced.
Three rejections, in order of what they protect:
- an uninformative binder type (hole or sort) says nothing, so it is no
better than the written hole -- the parser writes a sort for an omitted
annotation, and
is_uninformative_carrieris this module's own test for both shapes; - a free name that resolves to no type in
scopeis a TYPE VARIABLE the callee's declaration never solved (BinMonad.bind'sA -> M B, which nothing in the call site can bind -- the result position is not reachable from here). Handing one down is the foldable regression; - a name the callee's OWN declaration binds, even one that happens to
resolve as a type, because a class parameter's name is a variable to
the call site however the scope reads it.
class_method_var_namesreports that set, andhint_arrow_domain(lang/src/scope.mo) applies the identical rule before its own hint goes down.
pub def equiv_type (a_x : Term) (a_y : Term) : TermEquiv X Y := Sigma (X -> Y) (fn f => (b : Y) -> isContr (fiber X Y f b))
-- the library def's unfolding, one helper per level of it.
pub for the shape pin (test_glue_w_type_has_the_shape_of_equiv,
proofs/src/checker/cubical_props.mo), which reads the assembled type
rather than any intermediate -- the same reason as_cubical_type
(whnf.mo) is pub.
pub def struct_lit_con_name (np : NamePath) : IdentifierInductConstructor.mk's own name field is a full NamePath
(build_scope_struct registers it as NamePath.mk [mk]) --
Con.mk wants just the bare constructor Identifier, same as
every other constructor-application site in this file.
pub def struct_lit_build_args (params : List Param) (fields : List StructLitField) : List (Option Term)Reorders a struct literal's (name-matched, any-order) fields into
the struct's own declared Param order, producing the sparse
List (Option Term) shape check_con_args_against_params/Con
expect. A literal field with no matching declared param is simply
ignored (same leniency the reference's check_struct_fields has --
it only ever walks the struct's OWN declared fields, never the
literal's).
A field OMITTED from the literal falls back to its own declared
DEFAULT expression (Param's own default : Option Term, lang/ types.mo) when the struct declares one -- previously discarded
entirely (Param.mk pname _ _ _ _), always producing Option.none
for any omitted field regardless of whether a default existed.
codegen's lower_sparse_args (lang/lower_core_ir.mo) lowers a
constructor's args left-to-right and STOPS at the first Option. none hole -- correct for a genuinely under-saturated constructor
call, but a struct literal that legitimately omits a DEFAULTED field
(not a real "hole") needs that field's value actually present, not a
hole codegen will truncate the whole allocation at. Confirmed live
via a real self-compiled binary's own SIGSEGV: lang/scope.mo's
scope_data_empty (a 9-field ScopeData, 2 of which --
def_params/def_return_types -- are declared with defaults and
omitted from the literal) compiled to alloc_constructor(318, 7),
silently allocating only 7 fields' worth of space -- any later
monad_get_field/monad_set_field on field 7 or 8 read/wrote past
the end of the allocation.