Map: core / shell / evaluator
core/src/shell/evaluator/ is a CEK machine over the checked CBPV IR: the
focus is a computation closure ⟨M, ρ⟩, the continuation K is a stack of
frames, and the live Shell is the store. The
machine narrative walks its rules;
the IR invariant partitions control, primitives
and shell. Hosts enter only through the framed run in shell/run.rs.
Why a CEK machine
- Extent is structural. A binder’s scope is the environment a frame
carries, never an ambient scope pushed and popped around calls. A
letin anifarm scopes over the rest of that arm’s block and no further. - Tail calls are structural. β consumes its
Argframe and enters the body; no call frame remains, so there is no trampoline and no boundary that must re-absorb an escaping tail call. - Force is not a bracket. Entering a thunk pushes nothing, so a store
write in its body (
cd) persists.withinandgrantare the scoped forms; their frames hold the undo. - ρ is lexical, the store is not. ρ is a persistent map, captured by
restriction to occurrences.
Context(grants, handlers, env overrides, cwd) is store: policy code reads it directly, only frames holding undo change it, and no closure captures it. - Depth is counted in frames, before the effect. The machine does not
recurse on the host stack;
session.stack_limit(default 100 000) bounds K and is checked before any sink swap, redirect or grant is installed. - Cost: a builtin that applies a user function runs a nested machine on
the host stack, bounded separately by
NESTED_MACHINE_LIMIT.
Supersedes same-thread-body-shares-the-session. Refined by within-dir-is-local-state, a-closure-keeps-only-what-it-mentions, ambient-reads-are-builtins, the-checked-ir-is-the-calculus and runtime-values-are-value-closures.
Entry: evaluator.rs
run_phrases(top, env, mode, mooring, shell)first readmitstop.admitsagainst the suppliedenv(privatereadmit, undershell.fixings()). A refusal is located at the mismatch witness and named$name; no phrase runs.- It then runs each
Phraseas its own machine. A landedDefineextendsRan::envat once, so earlier definitions survive a later phrase’s failure; a non-final phrase’s error records the abandoned tail. Mode::Sessionalso writes each binding toshell.envand the lease ledger (Shell::note_define);Mode::Localdoes neither.shell::load::{run_module, evaluate_closed, extend_session}run over it.evaluator::applyadmits a thunk or builtin and callsmachine::apply; builtins taking functions and session hooks use it.
Machine: machine.rs
- Configuration.
Machine { cclos, stk }is ⟨(M, ρ), K⟩.CompClosure = Settled<(Arc<Comp>, Env)>is ⟨M, ρ⟩, withErr(e)read as ⟨raise e, ∅⟩.Stackis K:frames,call_site_frames, and the run’smooring. - Step.
Stack::stepmaps oneCompClosureto the next, borrowing only K, soMachine::runstill owns every frame after a panic and abandons them top-down; there is no placeholder state. An error pops a frame intounwind; a λ pops a frame intoresume; any other M goes toeval. - Returns are fused. Rules yield
Next: a closure, or aValClosfor the frame below.Stack::settlehands a value down through frames until one yields a closure. There is no value register and no allocatedreturn V.boxedcloses a λ meeting a value-receiving frame, or the empty stack, asValClos::thunk. - Application.
Apppushes oneFrame::Argper argument, first on top, then focuses the head. β happens atFrame::Arg: ⟨λx. M, ρ⟩ meetingArg(V)is ⟨M, ρ[x ↦ V]⟩. A value meetingArgis an invariant failure, never an implicit force.push_argsreserves all n frames at once. - Builtins.
ValClos::into_computationforces a builtin to its cached η-expansion (BuiltinEntry::eta), a λ-chain ending in δ (CompKind::Builtin), which reads the entry and arguments from ρ. Arity zero enters δ at once; under-application leaves an ordinary λ residual.Stack::callruns a builtin given exactly its arity directly, skipping η. - Literal force.
force_valruns a literal block in place, without closing it, forif,case,force,within,grant,audit,gatherandtry’s body.casefirst pushes oneArgholding the payload (Unitfor a bare tag). - Sequencing. Every
letruns its RHS.BindpushesFrame::To, which destructures the boxed result withpattern::bind;SeqpushesFrame::Seq. These are the only frames that carry anEnv. - Recursion.
Recunfolds one member of a sharedGroupNode; every sibling closes over ρ restricted to the group’s occurrences, and recursive references re-enter through force without rewriting bodies. - Provenance.
evalruns each named operation underShell::at_siteand locates its halts there;Exec,AppandForceinstead enter aFrame::CallSite, which restores the displaced site on return, halt or panic. Adjacent call sites coalesce and cost no stack budget. A spanless computation (η, decoded IR) takes the innermost call site’s span (or_call_site); code is never rewritten to carry a span. See the error record. - Stack cap. Every computational push goes through a
Slotfromreserve/reserve_n, checked againstsession.stack_limitfirst.Machine::runrefuses pastNESTED_MACHINE_LIMITnested machines. - Undo.
resumeandunwindare each frame’s return and halt rules;Frame::abandonis its panic rule. OnlySeqand a writtenletmark the abandoned tail; compiler-written binds do not. try.Frame::Trypasses values; on an error it enters atrycall site and calls the handler with the error as plain record data. Escapes pass through.guard. Entry checks room for three frames, polls, shields the scope and pushesFrame::Acquire. Acquire’s return restores the scope, pushesFrame::Guardand calls the body with the resource under aguardcall site.guard_releasesaves the outcome inFrame::Cleanup, shields again and calls release with the resource andexit_caseunder aguardcall site; release’s return restores the outcome, its halt overrides it. A halting acquire runs no release. Shields changeshell.scope, not the cradle. See a-guard-acquires.capture.Frame::Captureswaps stdout for a buffer. Return restores the sink and yields the bytes, or refuses on overflow; a halt restores the sink, drops the buffer, and adds its byte count to an error’sunwound.discarded.use.Use(module)runs the checked module throughshell::load::run_moduleand yields its public bindings as a record.- Shell forms.
Execresolves its head (Resolution::of) to a binding, a handler (pushingFrame::Unmask), a base handler or an external command; a boundary builtin runs saturated throughrun_boundarywith its checkedSite.Pipelineruns aPipeNodeto a value; each ral stage starts a fresh machine throughSTAGE_EVAL.Spawncallsconcurrency::spawn_form;Frame::Gatherowns aBroodGuard, installs a cradle over the current scope, and restores the displaced one on exit. See pipelines and worker scope. - Entry points.
machine::evaluateruns ⟨(M, ρ), ε⟩.machine::applyruns a builtin given exactly its arity without building a machine; otherwise it pushes the arguments, forces the head and runs.
Values and primitives
ir/value.rs,runtime/close.rs:ValClos::closecloses one layer of syntax over ρ restricted to its occurrences, pulling Σ’s answers for missing direct names;ValClos::thunkdoes the same for a computation.VClosRef::viewreads a head constructor only; lists and maps exposeListRef/MapRef. See runtime-values-are-value-closures.expr.rs:eval_priminterprets everyPrimon values.field,positionandlookupreadKey::{Label, Position, Data}.Decodedrops ρ before taking the bytes, strips one trailing terminator and decodes UTF-8 strictly.assemble.rs:eval_list,eval_updateandeval_mapbuild collections from already-run operands, callingListRef’s cons, snoc and concat. A repeated computed map key fails here; known duplicates are refused statically.pattern.rs:destructurestages every binding of aPattern::{Wildcard, Name, List, Record}before any is installed; a list pattern without rest requires exact length. Mismatches are catchable.
Shell interpretation
scope.rs:WithinScope::parsereadswithin’s option record (dir,env,handler,handlers); naming either handler key installs a handler frame, even for an empty map.WithinScope::enterreturns theWithinUndothatFrame::Withinapplies on exit. Handler dispatch is deep and self-masking.Grantpushes a capability layer;Frame::Grantremoves it by position.Auditopens a trail scope;Frame::Auditturns a value or error into a report and passes escapes.call.rs:run_nativeruns a builtin body insideBuiltinEntry::framed; the body may re-enter the machine.TildereadsHOMEthroughContext::require_home; other ambient reads are builtins.
See shell state, runtime, typecheck.