Map: core / IR
core/src/ir.rs is the call-by-push-value intermediate
representation — the target of elaboration and the input
to the evaluator.
A runtime program is a Toplevel { phrases, admits }: admits holds imported
bindings’ first-use contracts for readmission before execution; each
Phrase — Define (a top-level let, one Closed scheme per name the
pattern binds,
type-inference) or
Run (anything else) — runs in order, extending the
session environment the next phrase sees. Toplevel::referenced_names is
the phrase-level analogue of the Comp-level walk below, for the same lease
ledger.
One IR grammar is indexed independently by phase and representation.
Val, CompKind, Prim, Exec, their operand types and shared-node aliases
take P: Phase = Explicit and D: IrData = RuntimeData. Phase has
one associated type per annotated position: Bind (a CompKind::Bind’s or
Phrase::Define’s right-hand side), Call (a CompKind::App),
BindingCall (a CompKind::BindingCall) and Boundary (Exec.site, an
Option<P::Boundary>). Explicit has Bind = Call = (), an uninhabited
BindingCall and Boundary = Arc<Site>: it holds no unknowns, so
elaborator output, checked IR and runtime IR share it, and only checked IR
carries sites.
The checker’s own Inferring phase holds holes and types there
(typecheck); readback alone turns it into Explicit.
Serial marks the phases whose trees serialise: the skipped annotations
default, sites cross. Toplevel<D> always uses Explicit phrases, regardless
of the containing tree’s phase. Prim::map_operands converts Prim<P, D>
to Prim<Q, D> infallibly, preserving operand spans and the representation
axis; inference’s individual sub-rules retain their own operand order.
IrData selects the byte and scheme leaves and a node’s fields: RuntimeData
uses Bytes, Closed and a persistent imbl::OrdMap, sorted and distinct by
construction; marshal-private RawData uses String, Arc<Scheme> and the
pair sequence as written, which marshal/read/ir.rs checks on admission.
Val<P, D>::Bytes holds D::Bytes; DefineSchemes<D::Scheme> holds the
representation’s definition schemes. Serde bounds terminate at these
associated leaves, retaining explicit P: Serial and Phrase’s separate
scheme bounds, without requiring serde on representation markers or recursive
whole-tree bounds. Marshalling writes runtime IR directly and structurally
decodes the same grammar as raw IR. marshal/read/ir.rs admits it before
ValClos::closure, checking base64 and closing every nested linked-module
scheme while preserving metadata and JSON paths
(transport).
The runtime value types, ValClos, VClosRef, View, ListRef, MapRef,
Env and Binding, live in core/src/ir/{value,env}.rs and ir/value/
(shell-state,
runtime-values-are-value-closures).
Values, computations and shared nodes:
Val— inert data:Unit,String,Int,Float,Bool, lists, records, maps, variants, thunks, variables, and runtime constantsBytes,BuiltinandHandle. The elaborator writes none of those three;BuiltinandHandleare serde-skipped and occur only at a value closure’s root, crossing asmarshal::wire::Value::{Builtin, Handle}. Forming a value executes no computation. Collection and thunk syntax share theirArcnodes:Val::Thunk(Arc<ThunkNode>),Val::List(Arc<ListNode>),Val::Record, andVal::Map(eachArc<FieldsNode>, entries sorted by key; the elaborator refuses a key written twice) hold only a plain literal — no spread, no computed key.Valitself stays unspanned; every position onto which the checker narrows while emitting a constraint carriesSpanned<Val>.Node<S> { shape: S, occ: OnceLock<Occ> }is IR that closes: a shape plus what it mentions, computed on first use.Node::new(shape)hands back theArc<Self>every holder shares;shape()lends the shape back,occ()(pub(crate)) walks it once throughOcc::of, which sorts and dedups itsMentions, so a node built at run time pays only if something restricts to it.ThunkNode = Node<Arc<Comp>>,GroupNode = Node<Box<[(Name, Arc<Comp>)]>>,ListNode = Node<imbl::Vector<Spanned<Val>>>,FieldsNode = Node<Fields>withFieldstheIrDatamap.PartialEqcompares shapes; serde carries the shape alone (Node::from/Intothe shape), so decoding a node off the wire recomputes its occ rather than trusting one that rode along —Val’s own tests (T4) check a node crosses as its shape.Occ(Arc<[Name]>)is a node’s mentioned names, sorted and distinct by construction.Occ::of(shape)is the shared builder for nodes and boxed residual lambdas.lenandcontains(binary search) support lookup without scanning.Name = Arc<str>is every identifier the IR binds or mentions:Val::Variable, a variant’s label, the pattern’s names (the syntax’s ownPattern), aRecgroup’s members,CommandName::Bare, andEnv’s keys. A bind, a capture and a label clone a pointer.Val::Variant { label, payload: Box<Val> }always carries a payload; elaboration suppliesUnitfor a bare tag. RuntimeValClos::variantshares its payload’s syntax and capture;View::Variant’s payload is a borrowed value, which reads as()for a bare tag.CompKind::Prim(Prim)computes on value operands only.Prim::ListholdsValListElementries or spreads;Prim::MapholdsMapEntryV::{Entry(Spanned<Val>, Spanned<Val>), Spread(Spanned<Val>)};Prim::Updateholds one record base and named replacement fields. Operand computations hoist into surrounding binds in written order. Assembly may cost O(data) and fail, but runs no operand computation. Plain literals remain values.Comp— effectful, sequenced computation.Compwraps aCompKindplus an optionalSpanfor error reporting (synthetic nodes carryspan: None).
Computations partition into control, primitives and shell. The core
constructors are the control forms Return, Force, Lam, App, Bind,
Seq, Rec, If, Case, Try, Guard, Capture, and the value-only
operations in Prim.
Prim::operands and map_operands are the common operand traversals.
Guard { acquire, body, release }holds threeValoperands.Mentionstraverses all three; readback preserves them. Acquisition is shielded, then body receives the resource, then release receives resource and ending. The result type and grade are the body’s.Lambinds oneName; destructuring parameters useBindafter the lambda chain.Pattern::{Wildcard, Name, List, Record}andFieldPatternare defined inir/pattern.rs.App { head, args: Box<[Spanned<Val>]>, hole }applies a computation to values, with no spread.Bindtakes a pattern and ahole;Seqdiscards a computation’s result without generalisation. Holes are skipped by serde.Exec,Pipeline,Redirect,Within,Grant,Spawn,Gather,Audit,Tilde,UseandBindingCallform the shell layer.BindingCalland runtimeBuiltinare serde-skipped in both directions.BindingCallis a bare head bound in scope while the checker decides its splits. Readback makes it anExec, and it cannot occur in a checked tree. RuntimeCompKind::Builtin { builtin, args }is δ: a cached builtin η-expansion’s λs bindargs, and its environment bindsbuiltinto the entry itself.Mentionsincludes all these names; readback copies δ through. The elaborator writes none, andValClos::blockkeeps η residuals from the checker. Partial builtins are boxed λ residuals; marshalling writes their builtin name, environment row and supplied count, then rebuilds the receiver’s η suffix throughBuiltinEntry::residual. δ itself never crosses. Boundary partials remain expanded overExec, retaining their per-use checked site (runtime-values-are-value-closures).Use(Arc<Module<D>>)holdsToplevel<D>and itsSourceOrigin; module phrases remainExpliciteven inside anInferringtree. Elaboration links the one written path at check time; no path lookup remains for evaluation. The module is checked and run under Σ alone, and its public schemes contain no weak variables. Raw module schemes are admitted throughClosed::newrecursively on child read.Useis total in every IR phase;Toplevel::exported_schemessupplies the importer’s record type and the evaluator’s public-name projection. Marshalling carries the linked tree and origin, so a closure containingusereads no file when resumed.Within { opts, body }andGrant { caps, body }carry their options as one spread-freeArc<FieldsNode>, the same node as a record literal.handlers:is an ordinary map-valued field; no handler-specific AST or IR survives. Readback traverses that field through the option record. An absent field andhandlers: [:]still install different scopes.
See the IR invariant for the classification rule.
The checker builds explicit verdicts into the IR. Inference constructs
nodes beside their types; readback applies the solution’s decisions,
snapshots sites and settles schemes only after the unit succeeds. Site graphs
may retain free weak variables; they need not be ground. A stored name whose
scheme reaches a weak residual beneath a thunk or handle is statically
unusable in a later unit. Accepted residual occurrences are plain variables;
Toplevel.admits checks their existing data before execution, not future
arguments, results or handle payloads. Every evaluated Toplevel has passed
this check (scheme invariants).
-
CompKind::Pipelineis a struct variant{ stages }. The form’s value is its final stage’s. There is no per-stage type field, because every interior edge is an operating-system byte pipe allocated from stage position and no rule relates one stage’s type to its neighbour’s (pipes-are-positional-byte-wires, typecheck). -
CompKind::If { cond, then, else_ }andCaseArm { tag, body }carry their arms asSpanned<Val>: a thunk the form forces if it chooses it. A literal{ … }is that thunk, and so is a name holding one, so both are forced the same way; the elaborator refuses any other atom in arm position (Elaborator::elab_arm). -
CompKind::Case { scrutinee, arms: Vec<CaseArm> }is Levy’s sum eliminator: aCaseArmis a tag and the thunk of a function of its payload to run, so the alternatives are a list fixed at parse time and every arm is a node the checker builds — anifwith as many branches as the row has labels (case-is-syntax-try-is-not). -
Prim::Index { target, key }carries oneSpanned<Key>:Label(Str),Position(usize)orData(Val). The key’s form is explicit; no pass infers it from aVal. Readback andMentionstraverse onlyData; the checker requires a record, list or map, respectively. An index chain is a sequence of these primitives joined by binds. -
Exec { head, argv, redirects, site }is an external or builtin call;siteis the type the checker solved at a boundary call, which that door admits its value against, andNonefor every other head. -
CompKind::Capture(Arc<Comp>)is the kernel half of the checker’s one coercion: run the body, which isF^w Unit, collect what it writes, and return those bytes exactly — total and lossless.Prim::Decode(Val)is the other half: read thatBytesvalue as text, one trailing terminator dropped and a strict UTF-8 decode, which is the partial step — the kernel’sdecodetakes a value, so it reads a bound variable rather than nesting aComp. typecheck’s readback composes capture and decode (captured_string) asCapture(body) to x. Prim::Decode(x)around each command RHS a binding captures, andMentions’ walk descends into theCaptureand theBind. The reading is a node and not a command so that its meaning is fixed where the checker writes it (grades and capture, a-coercion-is-syntax, types). Neither has surface syntax. -
CompKind::Rec { group: Arc<GroupNode>, index }is theindex-th member of a recursive group —x⃗ : U C⃗ ⊢ Mᵢ : Cᵢ, typedCᵢₙdₑₓ— an n-ary generalisation of Levy’srec x. M, which is a group of one.group’s occ is the union of every member’s mentions, computed once when the elaborator builds theGroupNode; everyRecprojection of one group shares that oneArc. Inference checks a group once and memoises its member schemes and pending group by sourceArcidentity; readback memoises the checked group by pendingArcidentity. Each rebuilt group’s occ is computed from its own shape.
Every verdict the evaluator needs from the checker is explicit: capture/decode, returned-thunk splits, sites and schemes. The runtime builds no contract IR.
CommandName is the structured head for external dispatch (Bare / Path /
TildePath); written() gives it back as the source spelled it, ~
unexpanded, for a diagnostic raised before there is a HOME to expand it
against.
The IR owns the vocabulary it shares with the AST (ir/pattern.rs,
ir/op.rs, ir/redirect.rs): Pattern (with names() the one walk, and
Display), BinaryOp (Arith/Compare/Eq, each category its own enum), and
Redirects with its stream-once binding. A pattern binds names, never carries
a computation, so there is no parser syntax for elaboration to strip out
(ir-pure-cbpv).
Phrase<S = DefineSchemes, P = Explicit, D = RuntimeData> keeps its scheme
parameter independent of phase and representation: elaboration yields Unchecked
(Phrase<()>, explicit-phase terms without schemes); inference returns
Phrase<LiveSchemes, Inferring> carrying unsettled schemes. DefineSchemes
defaults to Closed schemes. Successful readback makes runtime Toplevel;
child reads reconstruct it only after raw IR admission, so the evaluator
cannot be handed unchecked IR. Exec::argv is Argv, a newtype over list
slots admitting spreads (positional(), arity()). Value application instead has a fixed
slice of arguments.
Mentions (pub(crate)) is the trait a Comp, a Val, and each of the four
node shapes implement: fn mentions(&self, out: &mut Vec<&Name>), one
exhaustive, wildcard-free arm per variant. Node::occ uses Occ::of over the
node’s shape to compute its own Occ on first use; a nested node’s
mentions contributes its already-computed occ rather than being walked
again, so occ for a whole program is linear in program text. Toplevel:: referenced_names (pub(crate)) is the same walk, run over a phrase’s Comp
top to bottom: the use-observation signal the
binding-lease ledger renews on
(binding-leases). What a
value captures uses the same occurrence sets: ValClos::close and
ValClos::thunk restrict at formation; close additionally pulls Σ-only
direct names into ρ.
Component reads share that ρ without another restriction
(a-closure-keeps-only-what-it-mentions).
This shape is what the prelude bake serialises with postcard; adding a field to
CompKind, Val, or Pattern invalidates every emitted blob (see
core and core/src/shell/boot.rs). docs/SPEC.md gives the formal CBPV account.