Map: core / typecheck
core/src/typecheck/ generates constraints, closes a ranked solver, then
reads back checked CBPV IR. The algorithm is
type inference; the architectural decision is
suspended matches.
Entry points
core/src/typecheck.rs owns the inference sessions and their export checks.
typecheck(phrases, SessionSchemes, Unit)generates pending phrases.Unit::{Script, Host(&'static Table), Module}states the unit’s purpose;Hostchecks its tail as written options (SPEC §15.3). After successfulSolver::close,Modulejudges public definitions over&Solutionand the pending IR, before readback settles schemes. Each public type still reaching a weak variable earnsUndecidedExport { name, ty, source }, naming the boundary call that left it undecided. Closure errors take precedence; export errors are sorted by span and refuse readback. Successful readback builds aToplevelwhose sites and readmissions name one freshUnitId. No checked tree escapes a refused unit. Re-checking a checked tree accepts it and inserts no further elaboration; raw variable ids are not canonical, so the two trees need not be==.SessionSchemescarries bindings,handled: Vec<String>for diagnostics only, and the host’sManifest.Solver::seedimports them at rank zero, re-seeding residuals once per unit. Every session binding has aClosedscheme. Scheme-less captured block locals receive one weak monomorphic unknown (WeakSource::Host) during closure re-inference at hook or handler installation.bindingstherefore remainsVec<(String, Option<Closed>)>.bake_preludechecks against the manifest and returns the annotated prelude, whose definitions carry their schemes; there is no separate scheme blob.arm_stands_in(name, comp, schemes)enters a region to check a persistent handler againstU([String] → Command)and closes the unit before returning an install verdict.withinneeds no runtime vet. It stores no scheme.binding_value_schemeinstead exports a closed lexical binding scheme;close_thunk_schemegeneralises after region exit, then settles only a successful unit. Both doors retain every error from close (Vec<TypeError>); the runtime reports refusal as oneIllTypedfact throughTypeError::diagnostic(diagnostics).
Constraint generation
generate.rs and generate/ never resolve a live solved type. Stored schemes
are inspected only for cross-unit admissibility.
generate.rs:Generator, phrases,let_, patterns, lambdas, force/return, recursive groups,check,regionand lexical scopes. Input is anExplicittree, output anInferringone.let_closes the RHS/pattern region beforebind_patterngeneralises.checkwrites a lambda’s arrow equation before checking its body.rec_groupchecks a group once in its own region and caches the members’ generalised schemes with the pending group; every projection instantiates its member’s scheme.note_residual_userefuses a stored name once per unit if its scheme’sdelays_weakreaches a weak residual beneath a thunk or handle. The rule includes function arguments and follows μ-equations in both data and delayed contexts; a shared recursive root must be judged in both. Existing residual data instead entersToplevel.admitsfor readmission before execution. A decided function beside that data is allowed (scheme invariants).generate/call.rs: application chains, head lookup, builtin calls, boundary saturation, argv and handler arms.head_classfollows binding → value builtin → base frame → external, consulting Σ and lexical bindings alone. A base-frame call has resultCommandwithout consulting its row’s scheme.apply_argstakes oneCallHoleand writes left-to-right argument matches, naming the head variable when there is one; a bare binding head becomesCompKind::BindingCall.argvqueues single-element gates, while a spread only demands a list.armgenerates the block (literal bodies usecheck_arm_body), then callsstands_in. That is the sole rule for written scoped entries, the catch-all and persistent install checks: equate the slot shape, then its fresh result withCommand, independent of the name and Σ.install_armowns a region.generate/data.rs: values, records, maps, primitives, updates and indexing.Key::{Label, Position, Data}immediately requires a record slot, list or string-keyed map; duplicate static keys in updates and written maps are diagnosed (DuplicateField). There is no deferred read or index-made weakness (a written key is a name).generate/control.rs: joins,if,case,try,guard, pipelines, redirects, capture and linkedUse.Useinstantiates every public scheme in the module’s checkedToplevel, returningFof their closed record; an importingletgeneralises normally. The module is checked against Σ, never the importer’s bindings. Arms meet fresh results, then equate with the join.Generator::guardchecksacquireas a thunked binding (Solver::binding, carrying aBindHoleso command acquisitions capture toString), checks body against one resource argument and a producer tail, and release against resource plusExitCase::<ErrorRecord>::ty()and a discarded producer tail. Only the body’s producer type and grade are returned;GuardBodyandGuardReleaseexplain the operand-specific argument demands. Every pipeline stage demands ready-producer shape; non-final stages must write, and decoders are refused there.stage_root_stdin_feedrejects an overridden pipe edge. Stdout redirects retain the payload at a fresh result grade.generate/scope.rs:within,grant, options, audit, spawn, and gather.file_optionsfollows elaborated binds and sequences to a written tail; only a manifest admits a written one-parameter factory, one level deep.check_optionschecks keys withcheck_option, diagnosing unknown, refused, duplicate and missing keys during generation.Holds::Tablerecurses on a record literal immediately; a bound or computed table, map or()is T0079.Holds::Atconstrains field values throughequate_held. ForHolds::Handlers, aVal::Mapchecks each entry throughinstall_armin its own region, in forms and host files alike; any other value uses the ordinary map equation. Only a writtenwithinmap supplies handled names to the body’s diagnostics.Holds::CatchAllchecks the catch-all by the arm rule alone. Rcprompt/startupand manifesthooks/keybindingsremainHolds::Decoded, with no static hook-type obligation. Installation infers thunk closures and checks arity, including the host-made default prompt; handler installation retains its inference check too.
Solver and readback
Only solve.rs observes the live store.
Solverowns the privateUnifier, suspended matches keyed by their scrutinee’s root, per-hole decisions, obligations and errors.binding(rhs, forced) -> (Ty, BindHole),call() -> CallHoleandargument(call, head, callee, arg, recursive_call)are the only ways to suspend a match.Unifier.atis the one current span;WithSpan for Solverborrows it.- Every public constraint is one private operation followed by one
propagate, which drainstake_touched: it improves the producer pairs on touched roots and re-steps their waiters, re-keyed under each root’s new representative.stepdecides a match at a known head, recording aModeor a split, and otherwise lowers its mentions to the scrutinee’s rank.close_regionchooses all young defaults together;ConflictingDefaults(T0080) refuses a root with both a binding and an argument match waiting, carrying the variable each names, if any. Refused regions retire unresolved young matches. Solver::closecloses rank zero and retires every elaboration match, judges final-head argv gates and attaches unit-read notes. It yields aSolutiononly for an error-free unit; otherwise the sorted errors.Solutionexposes decisions, resolution, sites and scheme settlement, never constraints. Itsscratchcopy andUnifier: Cloneare test-only; production table checks all run during generation.readback.rs:Readbackturns anInferringtree into anExplicitone. It applies eachBindHole’sMode(run or capture/decode) and eachCallHole’s splits, turns aBindingCallinto anExec, snapshots sites, settles definition schemes intoClosed, buildsToplevel.admits, and memoises rebuilt recursive groups.env.rs:TyEnv, handled-name sets for diagnostics only, and theInferringphase (Bind = BindHole,Call = BindingCall = CallHole,Boundary = Ty) (IR). Accepted residual occurrences remain plain variables; no runtime contract IR is generated.
Types, tables and diagnostics
unify.rs: four typed union-find stores (Store<T: Sort>, slotsParentor a rankedRootwhose state is free or bound), each root ranked even when bound; unions keep the minimum, bindings lower reachable unknowns, weakness is rank zero. A free row’s meta isDepth::{Shallow, Deep(witness)}.take_touchedreports the roots changed since it was last called.WeakSourcerecords provenance; a boundary source includes its call span, retained bySolutionfor export refusals and weak-mismatch notes.WeakSource::Hostidentifies scheme-less captured locals during closure re-inference, not ordinary session bindings. Data-guarded recursive types,Pairs, Rémy row rewrite and kind admission remain here. The depth budget of a binding or one-sided obligation reads each handle’s cached syntacticheightin O(1). Every unifier walk (apply_*,lower,remember_producers,reach,data_*,refuse_data_free_cycle) visits each interned handle once, andPairsguards resolved structure pairs as it guards roots, so shared DAGs stay linear in unique handles;apply_*does not memoize a result beneath which a root proved cyclic.bind_rowenforces finite tail spines and type-rooted field payloads (row types).unify_producerschecks grade/payload pairing for returners and handles;improve_producersentails value grades from non-unit payloads, lowers pair dependencies andexitretires young pairs before generalisation (capture).subst.rs:Subst, a simultaneous substitution read at variable leaves, andMemo, which applies one substituting each distinct handle once. Renamings, weak settlement and the unifier’s root view (shallow_*) are its instances.generalize.rs: rank-basedgeneralize, fresheninginstantiate,settle_weak(toClosed),reseed_weak, cyclic snapshots and syntactic closure over the whole scheme graph. No environment scan or cached environment free variables (schemes leave closed).builtins.rs:Decl,Manifest,Convention::{Value(BuiltinTypeRule), Argv}, and cached schemes/curry spines. Value rules are closed byBinders::closewithout the live unifier.Argvhas no type rule:Decl::schemederivesU([String] → Command)fromArm::Named(name).ty().Arm::{Named, CatchAll}suppliesshape,tyand diagnosticstanding; the privatehandler()also supplies the member type ofhandlers_ty(). No name or manifest lookup selects a handler’s type.Manifestclones share declaration rows and caches (fixed arity, builtins). Every registered boundary’s declared result has data-constrained type variables and deep row variables; a decoded function or handle is a kind error at the use, not a runtime contract.site.rs:Site::snapshotpreserves free identities and sharing in every sort: one node per variable root and per other interned handle; a bound root keeps a node apart from its binding’s, for its witness. Module exports use their checked schemes directly, not boundary admission. The graph data is in ty; runtime admission isshell/runtime/admit.rs. A readmission site may contain a decided function beside undecided data; only its head needs checking, because no weak residual beneath it can be imported.table.rsandtable/:Table,Key,Holds,Vocab,declared(Form)and enum-derived vocabulary shapes.Key::requiredis independent ofHolds;Key::blanksupplies declared empty values for diagnostics and the rc skeleton, including`inheritfor nestedLIMITSandTHEMEkeys.setting_table!derives each nested table and its parent’s blank from one label list.RCrequires all twelve keys,LIMITSall three child-limit keys, andTHEMEboth display keys.setting_rowsupplies the closed[`inherit, `set T]vocabulary;Vocabulary::Settingidentifies its diagnostic vocabulary.MANIFESTrequires onlynameand admits a factory;GRANTand its nested tables have no required keys.unify_heldandunify_vocabword field equations;Reason::Handlersexplains the map spelling and arm mismatches. No declared table becomes a unified record type. Runtime decoders keep value-shape and domain checks; grant decoding also retains shape and keyset checks for grants received as data.error.rs:TypeError,TypeErrorKind,Reason,Standing,UnitCall.Unwrittenclassifies refused syntax:OptionsNotWritten(T0077) for a file tail,TableNotWritten(T0079) for a nested table.OptionsContextdistinguishes a file’s factory admission from a factory body’s written result, so advice names the right context. Variable advice uses the actual variable; spread and computed results use a neutral$valueexample.OptionsMissing(T0081) lists only missing required keys in one diagnosis per table; it does not claim that optional keys are required. Its defaults hint appears when every missing key declares a blank.Reason::{Binding, Call}carrydefaulted_at, the closing span when a default chose the branch, andCallwhether it is a recursive call; failed head/coverage equations retain their source-specific diagnosis.ExecArgNotTextretains whether a head was handled where written, so final gate refusal can explain why the handler does not widen the external gate.explain.rs: the pure wording of errors and hints, including both-use default conflicts.()notes are recorded during generation and attached from the final solution. Final-head static gates do not establish uniform runtimeUnitrefusal for arbitrary handlers (docs/SPEC.md§6.6).- Evidence lives in
solve.rs,unify.rs,generalize.rs,site.rsandreadback.rstests, andcore/tests/suspended_matches.rs(whole programs’ verdicts, elaborations and hints). Scope and remaining gates are recorded in type inference.
The type language, schemes and site data live below this module in
ty. Formal rules: docs/SPEC.md §§17.3–17.7.