The type system: Hindley–Milner with rows
ral is typed by Hindley–Milner inference with let-polymorphism, run over the call-by-push-value IR after elaboration.
The two sorts of type mirror the command split:
- value types
Adescribe inert data; - computation types
Cdescribe effectful computations.
The value types are Unit, Bytes, Bool, Int, Float, String,
homogeneous lists [A] and maps Map A, closed and open records, their dual
the variant (a tagged sum over the same rows), the thunk {B}, the graded
handle Handle^ε A (what spawn returns; await gives back F^ε A), and
type/row variables. Records are
open-row-polymorphic; that fragment is its own page,
row-types. Records and maps share one runtime carrier but
answer different static questions — records-and-maps.
A type variable carries a kind — number, comparable, scalar or
data, or the unconstrained any — so that +, <, == and interpolation
state what they take and a helper over them keeps its generality:
let log = { |n| echo "n: $n" }
is ∀α:scalar. See operators-are-kinded.
The computation types are three:
C ::= F^ε A | A → C | γ ε ::= p | w | ε̂A parameterised block has the value type {A → C}. F carries a grade ε,
a producer kind: F^p A produces a value A (printed Returns A), and
F^w Unit produces output and nothing else (printed Command). A grade
variable prints from the alphabet ν ξ ο π, so explain retry reads
∀α ν. Integer → {Command[ν] α} → Command[ν] α, “some producer of α”. The variables are type,
computation, row and grade variables.
A command is F^w Unit
A command’s value is its output. A computation writes bytes to stdout, an
operating-system stream whose sink is chosen by position — a redirect, a
capture bracket, a pipeline stage’s place in the line — and
produces a result. The grade says how the result is produced, not whether
anything is written: it is deliberately a producer kind, not an effect, so
the body echo pre; return 5 has type F^ν Int for a fresh ν, and the
bind rule stays total.
A command is a call whose head writes: an external, ^name, a path head, a
builtin row that writes, or a handler arm standing in for one. It is F^w Unit.
{ echo hi } is {Command} and { 'hi' } is {Returns String}; an unresolved grade prints Command[ν] A.
| program | type |
|---|---|
hostname | Command |
echo hi | Command |
to-json $x | Command |
warn hi | ∀ν. Command[ν] Unit |
return 5 | Returns Integer |
from-bytes | Returns Bytes |
from-json | Returns α (a boundary) |
audit { echo hi } | Returns Report(Unit) |
The writing builtins are echo, to-json, to-string, to-line, to-lines,
to-jsonl, to-csv, to-bytes, ints-to-bytes, help, explain, clear and
reset. warn has a fresh unit-result grade: stderr is not the byte channel. each,
fold, fold-lines and audit are polymorphic in the grade of their body
(∀ε α. … U(F^ε α) …), run it, stream its output and keep its value; spawn
and watch keep the grade in the handle they return, Handle^ε α, and
await gives it back as F^ε α; fail, exit and diverges are F^ε α
for every ε. map accepts either callback grade; filter and sort-list-by demand a value.
Invariant, of inferred types. F^w A ⇒ A = Unit. This is a theorem about
what inference produces, not a well-formedness condition on types: F^w Int is
a formable type, and a scheme can instantiate to it
(∀ν α. U(F^ν α) → F^ν α at ν := w, α := Int). It holds because every
rule that introduces w does so at Unit, every rule that copies a grade
copies the value type with it, and a grade variable is only ever unified
together with the one value type it is paired with, so output appears only at
Unit — given that every builtin scheme, and the error type of fail and
try, pair their grade variables in the same way. Before binding either grade,
Unifier::unify_producers (core/src/typecheck/unify.rs) refuses an output pair
against a type whose kind excludes Unit; returners and handles share this check.
every_scheme_pairs_a_grade_with_one_value_type in core/src/shell/builtins/tests.rs
checks builtin schemes. Global producer improvement entails p whenever a
returner or handle payload’s head or kind excludes Unit, even without a
binding match; this is not a default. An unresolved grade lowers its payload
dependency to its rank, not conversely: a weak, Unit-capable payload leaves a
fresh grade generalisable. Structural lowering still reaches grades inside
weak roots. Young dependencies retire before generalisation so later
improvement affects instances, not quantified definitions
(type inference). Pairing is an inference invariant,
not a restriction on declarative type formation. Grades are atomic — a grade
variable binds only to p or w — so there is no occurs check or kind. Grades
have ranks but are not weak scheme entries.
Every external command is F^w Unit. A head’s type and argument gate depend
only on Σ and lexical bindings. The checker classifies a head as a binding,
a value builtin, a base frame or an external. Every base frame has type
[String] → Command by construction and takes the in-shell gate; every other
command name has the same type and takes the external gate, even when handled.
The handler stack supplies diagnostic names only.
One coercion, at let
Only binding turns output into a value. cap : F^w Unit ⇝ F^p String
is capture then decode; arguments, joins and handler arms use unification,
without wrappers (grades and capture).
- Every right-hand side runs. A function binds its residual block at
U Cwhen it finds no argument. F^w Unitis captured and bindsString;F^p AbindsA.- An unknown computation head or a grade not decided by producer improvement
suspends
bound τ C; the binder’s demanded type never selects the branch. A match on an enclosing parameter survives inner lets, with all its mentions lowered to the scrutinee’s rank. - Closing the owning region defaults its unresolved binding matches together:
F^ν Afixesν := p; a computation variable unifies withF^p α. No value type is defaulted. An unresolved application defaults to an arrow; conflicting defaults on one unknown are refused with both uses. - Only after successful unit closure does readback insert capture/decode. Generation emits equations and pending holes, not adaptations (suspended matches).
Commands introduce w; builtin parameters demanding values and boundary
results introduce p. Other term producers and ordinary builtin results have
fresh grades, paired with their value types. A free unit producer can unify
with a command; a let-fixed p producer cannot.
capture M returns exactly the bytes its command body writes. decode drops
one trailing LF or CRLF and strictly decodes UTF-8; a failure names
from-bytes as the way to keep binary output. On a halt, capture drops its
buffer and writes nothing. Both terms have no surface syntax: a translation’s
meaning cannot be redefined by the session
(a-coercion-is-syntax).
Command[ν] A prints an unresolved producer, unless its paired type excludes
Unit, in which case it prints Returns A. p prints Returns A, and w
prints Command; only visible grade variables appear in a scheme’s ∀.
The complete rules and examples live in grades and capture.
A stage feeds by writing
A pipeline stage feeds the next by writing, so every stage but the last is
accepted at Unit in any grade, and the pipeline’s type is the last stage’s.
A decoder (from-*, marked BuiltinDiagnostic::Decoder) in a non-final stage is
refused by its own mark (stage_decoder, DecoderMidPipeline, T0078):
“a decoder ends the byte pipeline: from-json returns a value and writes
nothing, so nothing reaches cat”. A value or block literal in stage position
“writes nothing to the pipe” (Reason::PipelineStageWrites, T0011), and
each { … } $xs | cat is accepted. A stdout redirect gives a fresh result grade,
M > f : F^ν A; stdin and stderr redirects and 2>&1 preserve it. The pipeline’s
value is its final stage’s, always
(pipes-are-positional-byte-wires).
A handler is a command
Every named handler has type U([String] → Command); the catch-all has
U(String → [String] → Command). Neither depends on a name, Σ, or other
handlers. Every argv manifest row is [String] → Command by construction:
it has no type rule. An arm for echo follows exactly the same rule as one
for curl. Its value is its output.
detach is a first-class value builtin, not a base frame: an arm named
detach must be a command and is accepted silently but never reached,
because the value binding wins. Stub it by binding its name
(builtins).
A ()-returning stub is admitted when its grade is free and captures "".
A call through the arm types as its head does; no handler scheme is persisted.
A mismatch is Reason::StandsIn; the name supplies diagnostic wording only.
within, rc and manifest options check a written handlers: map entry by
entry through stands_in, each arm in its own region, with a name and site
for each diagnostic. A bound or computed map is held by one equation against
Map(U([String] → Command)); a record is refused, with the map spelling.
The catch-all also uses the arm rule. Only persistent handlers retain the
run-time vet (arm_stands_in), which yields a verdict, not a scheme. Imported arms retain their module’s
sites. within’s static check is total and needs no install-time vet. An arm’s
parameters are its slot’s, read off its type, never its spelling (SPEC §17.7).
The module boundary checks complete used-export schemes, including nested
functions, and refuses a known incompatible scheme at use. Unresolved
re-exported shapes additionally carry recursive delayed contracts: an opaque
or weak function is guarded by exactly the caller-required arrow and result
contract, with incompatible applications or results raising when reached.
This is not certification of every function body before invocation, nor
inference at scoped handler installation (SPEC §10.3).
A host file’s options are uses
A host file writes its options, checked key by key during generation as
within and grant options are, with nested tables written too (SPEC §15.3).
Each field is an ordinary use: its equations may constrain binding and
application matches and reach decoder admission sites before freezing.
Generation is followed by unit closure and readback, with no inferred-row
ascription, queued table check or scratch judgement
(type inference).
Branching is HM over thunks, joined by grade
Every form that suspends a command — if, case, try, ?, guard,
within, grant — takes a thunk U C and forces the one it chooses. A
literal { … } is that thunk, and a thunk in hand ($aaah) is forced the same
way. An arm is a literal block, a lambda or a name; any other atom would be
hoisted and run before the form chose, and is refused at elaboration.
within, grant and guard pass their body’s F^ε A through; audit absorbs
it and returns F^ν Report(α) at a fresh ν.
Joins unify in source order. Each arm is checked against its own fresh
result; the results then unify with the join as the expected side. No arm is
captured or reordered. A disagreement blames the later arm and says whether
it or an earlier arm is the command. if $c { hostname } else { echo b }
is one Command; try { fetch } { |e| return 'none' } is refused. Return an
explicit capture from the command arm to join it with text.
A fresh return () can join either grade, unlike a unit producer whose grade
a let fixed to p. Diagnostics suggest explicit capture for text,
succeeds { … } for Bool, or decoding/returning a value of the required type.
The calculus is CBPV, graded by producer kind
F is a functor from value types to computation types and the adjunction with
U is unchanged; the grade is an annotation on the returner, atomic and
unifiable like a type variable. A sequence takes its tail’s type, and a discard
accepts any grade (cbpve).
The capture rule is stable through abstraction and application:
let f = { hostname }; let x = f binds the host name, like
let x = hostname. Only a bind defaults a free grade; arguments and joins
impose ordinary equalities. Capture placement is local to the resolved
right-hand side; unresolved choices wait for the owning region’s closure, and
readback inserts adaptations only after successful unit closure
(grades and capture).
Kinds form a chain, so inference is principal outright. number ⊂ comparable ⊂ scalar ⊂ data ⊂ any, by the heads each admits: every head has a least kind, and a kind admits the heads whose least kind lies at or below it. Two variables unite at the smaller of their kinds, no meet is empty, and since every kind admits at least two heads, no meet forces a variable to one type.
Programs need no type annotations; generalisation happens at the Bind boundary. A
leaf, meanwhile, commits before inference begins: a bare word’s value type is
fixed by the grammar that classifies it, never by the hole it lands in
(numerals-denote-numbers), so no
defaulting rule touches a leaf’s value type. Soundness then rests on two independent
legs:
- Recursion is governed by the strongly-connected-component structure of
binding groups: a non-recursive group generalises at its binding point, while a
mutually recursive group (
Rec) stays monomorphic within the group and generalises only once its fixed point is reached. - No value restriction is needed. Bindings are immutable, so there are no
polymorphic references; and CBPV’s
Bindsequences a computation’s effect before binding its result, so the thing generalised is always a value whose effect has already happened. What an effectful right-hand side can still emit is typed independently of the variables the bind generalises: values pass through the scheme, bytes are untyped, and a failure carries an error of a closed data type. That last is required: a failure raised inside a generalised right-hand side escapes the bind, and preservation holds only because its payload mentions no generalised variable. What a program did not decide, data entering through a checked boundary, has weak type variables, which aletnever quantifies: one type per unit (a-let-generalises-what-is-not-weak).
A type error aborts with exit status 1 and a positioned expected-vs-inferred message.
See also cbpv, grades and capture, pipelines, row-types, fixed-arity, rows-and-handlers (the effect typing ral declined). The volatile code map is typecheck.
Realised in type-inference.
Cite: RATIONALE §“Values and commands”, §“Pipelines follow their edges”,
§“Structured values cross once”; docs/SPEC.md §17.