garage44.eu/jeroen/frits

logclone: git clone https://garage44.eu/jeroen/frits.git

cartopolis-agent · 2026-11-26T06:35:47Z

feat(frits): the language core, compiler and process runtime

A first working Frits: lexer, parser, a one-pass type checker that emits
typed register bytecode, and a VM that runs each script as a process
with its own heap, mailbox and fuel slice.

The choices that shaped it, from the s851 brainstorm:
- Every script's execution state is data in `Process`, never the Rust
  stack, and fuel is counted per instruction. A busy loop at the top
  level, in a handler or 1500 calls deep is paused and resumed; there is
  no non-yieldable context, which was Luau's silent failure in the
  simulator (a yield outside a coroutine was dropped without error).
- One heap per process with a precise mark-and-sweep: a memory hog
  dies alone ("out of memory"), garbage under the limit is collected,
  and values cross processes only as copied `HostValue`s.
- Effects are checked by the compiler: `script / Prim` for the script,
  `fn f() / Prim` for a function, callers need all of a callee's.
- Platforms are declared in Frits (`effect`, `module`, `event`, `type`)
  and bound to Rust functions, so one script compiles against Pinnacle,
  the simulator or the console.
- The VM is `#![forbid(unsafe_code)]`; typed instructions mean no tag
  checks beyond the safe match.

Rejected for now: closures, user generics, methods and modules, to get
a measurable core first. An integer literal beside a Float is a Float
(`2 * math.pi`), but an Int variable never converts silently.

The GC threshold is 4 KiB of fresh allocation (or the live size, if
larger): at 16 KiB a firebird held 23 KB, at 4 KiB 3.3 KB, with the
tick time unchanged within noise on mac-1.
CLAUDE.md                    |   33 +
 Cargo.lock                   |    7 +
 Cargo.toml                   |   14 +
 crates/frits/Cargo.toml      |   11 +
 crates/frits/src/ast.rs      |  186 +++++
 crates/frits/src/bytecode.rs |  301 +++++++
 crates/frits/src/compile.rs  | 1857 ++++++++++++++++++++++++++++++++++++++++++
 crates/frits/src/lexer.rs    |  302 +++++++
 crates/frits/src/lib.rs      |   53 ++
 crates/frits/src/main.rs     |   53 ++
 crates/frits/src/parser.rs   |  750 +++++++++++++++++
 crates/frits/src/platform.rs |  121 +++
 crates/frits/src/prelude.rs  |   50 ++
 crates/frits/src/runtime.rs  |  112 +++
 crates/frits/src/tests.rs    |  316 +++++++
 crates/frits/src/types.rs    |  280 +++++++
 crates/frits/src/value.rs    |  227 ++++++
 crates/frits/src/vm.rs       |  457 +++++++++++
 rust-toolchain.toml          |    3 +
 rustfmt.toml                 |    1 +
 20 files changed, 5134 insertions(+)

diff --git a/CLAUDE.md b/CLAUDE.md
new file mode 100644
index 0000000..ead53d9
--- /dev/null
+++ b/CLAUDE.md
@@ -0,0 +1,33 @@
+# CLAUDE.md
+
+Frits is a scripting language for Pinnacle (and later the Cartopolis
+simulator). `docs/design.md` holds the decisions, what is built, the
+measurements and what is missing; read it before changing the language.
+
+## Build
+
+Builds run on a midas node (`midas run -- cargo …`, or `midas take` then
+`ssh <node> …`). The landing gate is `cargo test --locked --workspace`.
+
+```bash
+cargo test --workspace                 # crates/frits unit tests + the ported scripts in crates/bench
+cargo run --release -p frits-bench     # numbers comparable with Cartopolis's Luau/Bun table; run on mac-1
+cargo clippy --workspace --all-targets
+```
+
+## Rules
+
+- **No outside crates**, like Pinnacle: everything is written here.
+- **`#![forbid(unsafe_code)]` in `frits`.** A VM bug may give a wrong answer or
+  stop a script, never corrupt memory.
+- **Every path that runs script code goes through `Process::run`'s loop**, which
+  counts fuel per instruction. A host function must never call back into
+  script code: that would be a context that cannot be paused.
+- **A process's heap is its own.** Values cross between processes, or to the
+  host, only as `HostValue` (copied). Never hand a `Value::Obj` from one heap to
+  another process.
+- **Record fields are stored in name order.** A host building a record with
+  `Cx::record` passes the fields sorted by name.
+- Ported Cartopolis scripts live in `crates/bench/scripts/`, with behaviour
+  tests in `crates/bench/src/main.rs`: when the language changes, they must
+  still read naturally.
diff --git a/Cargo.lock b/Cargo.lock
new file mode 100644
index 0000000..c6aac05
--- /dev/null
+++ b/Cargo.lock
@@ -0,0 +1,7 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 4
+
+[[package]]
+name = "frits"
+version = "0.1.0"
diff --git a/Cargo.toml b/Cargo.toml
new file mode 100644
index 0000000..7ea7fd3
--- /dev/null
+++ b/Cargo.toml
@@ -0,0 +1,14 @@
+[workspace]
+members = ["crates/frits"]
+resolver = "3"
+
+[workspace.package]
+version = "0.1.0"
+edition = "2024"
+license = "GPL-3.0-or-later"
+publish = false
+
+[profile.release]
+opt-level = 3
+codegen-units = 1
+debug = 1
diff --git a/crates/frits/Cargo.toml b/crates/frits/Cargo.toml
new file mode 100644
index 0000000..79b1417
--- /dev/null
+++ b/crates/frits/Cargo.toml
@@ -0,0 +1,11 @@
+[package]
+name = "frits"
+version.workspace = true
+edition.workspace = true
+license.workspace = true
+publish.workspace = true
+
+[[bin]]
+name = "frits"
+path = "src/main.rs"
+test = false
diff --git a/crates/frits/src/ast.rs b/crates/frits/src/ast.rs
new file mode 100644
index 0000000..6255c11
--- /dev/null
+++ b/crates/frits/src/ast.rs
@@ -0,0 +1,186 @@
+//! The parsed program, before types.
+
+pub type Name = String;
+
+#[derive(Debug, Default)]
+pub struct Module {
+    /// `script / Prim, Chat`: what the script as a whole may do.
+    pub effects: Vec<Name>,
+    pub items: Vec<Item>,
+}
+
+#[derive(Debug)]
+pub enum Item {
+    Fn(FnDecl),
+    /// `on timer() { … }`: a handler for one of the platform's events.
+    On(FnDecl),
+    Enum(EnumDecl),
+    Type(Name, TypeExpr, u32),
+    Global(Global),
+    /// Platform declarations only: `effect Prim { fn … }`, `module math { … }`.
+    Namespace(Namespace),
+    /// Platform declarations only: `event timer()`.
+    Event(FnDecl),
+}
+
+#[derive(Debug)]
+pub struct FnDecl {
+    pub name: Name,
+    pub params: Vec<(Name, TypeExpr)>,
+    pub ret: Option<TypeExpr>,
+    pub effects: Vec<Name>,
+    /// None in a platform declaration, where Rust supplies the body.
+    pub body: Option<Block>,
+    pub line: u32,
+}
+
+#[derive(Debug)]
+pub struct EnumDecl {
+    pub name: Name,
+    pub variants: Vec<(Name, Vec<TypeExpr>)>,
+    pub line: u32,
+}
+
+#[derive(Debug)]
+pub struct Global {
+    pub mutable: bool,
+    pub name: Name,
+    pub ty: Option<TypeExpr>,
+    pub value: Expr,
+    pub line: u32,
+}
+
+#[derive(Debug)]
+pub struct Namespace {
+    pub name: Name,
+    /// `effect` (calls need the effect) or `module` (pure).
+    pub effect: bool,
+    pub fns: Vec<FnDecl>,
+    /// `let pi: Float`: a value the platform binds.
+    pub consts: Vec<(Name, TypeExpr, u32)>,
+}
+
+#[derive(Debug, Clone)]
+pub enum TypeExpr {
+    Named(Name, Vec<TypeExpr>, u32),
+    Record(Vec<(Name, TypeExpr)>, u32),
+}
+
+#[derive(Debug, Default)]
+pub struct Block {
+    pub stmts: Vec<Stmt>,
+    /// The value of the block: its last expression, when no `;` or newline ended it.
+    pub tail: Option<Box<Expr>>,
+}
+
+#[derive(Debug)]
+pub enum Stmt {
+    Let {
+        mutable: bool,
+        name: Name,
+        ty: Option<TypeExpr>,
+        value: Expr,
+        line: u32,
+    },
+    Assign {
+        target: Expr,
+        op: Option<BinOp>,
+        value: Expr,
+        line: u32,
+    },
+    Expr(Expr),
+    While {
+        cond: Expr,
+        body: Block,
+        line: u32,
+    },
+    For {
+        var: Name,
+        iter: ForIter,
+        body: Block,
+        line: u32,
+    },
+    Return(Option<Expr>, u32),
+    Break(u32),
+    Continue(u32),
+}
+
+#[derive(Debug)]
+pub enum ForIter {
+    Range(Expr, Expr),
+    List(Expr),
+}
+
+#[derive(Debug)]
+pub struct Expr {
+    pub kind: ExprKind,
+    pub line: u32,
+}
+
+#[derive(Debug)]
+pub enum ExprKind {
+    Int(i64),
+    Float(f64),
+    Bool(bool),
+    Str(String),
+    Template(Vec<TPart>),
+    Ident(Name),
+    Field(Box<Expr>, Name),
+    Call(Box<Expr>, Vec<Expr>),
+    Index(Box<Expr>, Box<Expr>),
+    Binary(BinOp, Box<Expr>, Box<Expr>),
+    Unary(UnOp, Box<Expr>),
+    If(Box<Expr>, Block, Option<Box<Expr>>),
+    IfLet(Pattern, Box<Expr>, Block, Option<Box<Expr>>),
+    Match(Box<Expr>, Vec<Arm>),
+    Block(Block),
+    Record(Vec<(Name, Expr)>, Option<Box<Expr>>),
+    List(Vec<Expr>),
+}
+
+#[derive(Debug)]
+pub enum TPart {
+    Lit(String),
+    Hole(Expr, Option<String>),
+}
+
+#[derive(Debug)]
+pub struct Arm {
+    pub pattern: Pattern,
+    pub body: Expr,
+}
+
+#[derive(Debug, Clone)]
+pub enum Pattern {
+    Wild,
+    /// A capitalised name, with bindings for its payload: `Some(hit)`, `Patrol`.
+    Variant(Name, Vec<Name>, u32),
+    /// A lower-case name: binds the whole value.
+    Bind(Name),
+    Int(i64),
+    Str(String),
+    Bool(bool),
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum BinOp {
+    Add,
+    Sub,
+    Mul,
+    Div,
+    Rem,
+    Eq,
+    Ne,
+    Lt,
+    Le,
+    Gt,
+    Ge,
+    And,
+    Or,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum UnOp {
+    Neg,
+    Not,
+}
diff --git a/crates/frits/src/bytecode.rs b/crates/frits/src/bytecode.rs
new file mode 100644
index 0000000..f469e93
--- /dev/null
+++ b/crates/frits/src/bytecode.rs
@@ -0,0 +1,301 @@
+//! The compiled form: typed register instructions.
+//!
+//! The type checker has already proved what every register holds, so there is an
+//! instruction per type (`AddI`, `AddF`) and none of them checks a tag at run
+//! time beyond what the safe-Rust match in the VM costs. Registers are `u16`
+//! offsets from the frame's base.
+
+use std::rc::Rc;
+
+use crate::value::Value;
+
+pub type Reg = u16;
+
+#[derive(Clone, Copy, Debug)]
+pub enum Op {
+    /// A constant from the module's pool: numbers and string literals.
+    LoadK {
+        dst: Reg,
+        k: u32,
+    },
+    LoadUnit {
+        dst: Reg,
+    },
+    LoadBool {
+        dst: Reg,
+        v: bool,
+    },
+    LoadTag {
+        dst: Reg,
+        tag: u32,
+    },
+    Move {
+        dst: Reg,
+        src: Reg,
+    },
+    GetGlobal {
+        dst: Reg,
+        g: u32,
+    },
+    SetGlobal {
+        g: u32,
+        src: Reg,
+    },
+
+    AddI {
+        dst: Reg,
+        a: Reg,
+        b: Reg,
+    },
+    SubI {
+        dst: Reg,
+        a: Reg,
+        b: Reg,
+    },
+    MulI {
+        dst: Reg,
+        a: Reg,
+        b: Reg,
+    },
+    DivI {
+        dst: Reg,
+        a: Reg,
+        b: Reg,
+    },
+    RemI {
+        dst: Reg,
+        a: Reg,
+        b: Reg,
+    },
+    NegI {
+        dst: Reg,
+        a: Reg,
+    },
+    AddF {
+        dst: Reg,
+        a: Reg,
+        b: Reg,
+    },
+    SubF {
+        dst: Reg,
+        a: Reg,
+        b: Reg,
+    },
+    MulF {
+        dst: Reg,
+        a: Reg,
+        b: Reg,
+    },
+    DivF {
+        dst: Reg,
+        a: Reg,
+        b: Reg,
+    },
+    RemF {
+        dst: Reg,
+        a: Reg,
+        b: Reg,
+    },
+    NegF {
+        dst: Reg,
+        a: Reg,
+    },
+    Not {
+        dst: Reg,
+        a: Reg,
+    },
+    LtI {
+        dst: Reg,
+        a: Reg,
+        b: Reg,
+    },
+    LeI {
+        dst: Reg,
+        a: Reg,
+        b: Reg,
+    },
+    LtF {
+        dst: Reg,
+        a: Reg,
+        b: Reg,
+    },
+    LeF {
+        dst: Reg,
+        a: Reg,
+        b: Reg,
+    },
+    EqI {
+        dst: Reg,
+        a: Reg,
+        b: Reg,
+    },
+    EqF {
+        dst: Reg,
+        a: Reg,
+        b: Reg,
+    },
+    EqB {
+        dst: Reg,
+        a: Reg,
+        b: Reg,
+    },
+    EqS {
+        dst: Reg,
+        a: Reg,
+        b: Reg,
+    },
+    /// Payload-free enum values: compares the tags.
+    EqTag {
+        dst: Reg,
+        a: Reg,
+        b: Reg,
+    },
+    IntToFloat {
+        dst: Reg,
+        a: Reg,
+    },
+    FloatToInt {
+        dst: Reg,
+        a: Reg,
+    },
+
+    Jump {
+        to: u32,
+    },
+    JumpIfFalse {
+        cond: Reg,
+        to: u32,
+    },
+    JumpIfTrue {
+        cond: Reg,
+        to: u32,
+    },
+
+    /// Arguments sit in `base..`; the callee's frame starts there.
+    Call {
+        f: u32,
+        base: Reg,
+        dst: Reg,
+    },
+    CallHost {
+        f: u32,
+        base: Reg,
+        argc: u16,
+        dst: Reg,
+    },
+    /// A value the platform bound to a name (`Prim.fire`), copied into the heap.
+    HostConst {
+        dst: Reg,
+        c: u32,
+    },
+    Ret {
+        src: Reg,
+    },
+
+    /// Fields in `base..base+n`, in the record type's (sorted) field order.
+    MakeRecord {
+        dst: Reg,
+        base: Reg,
+        n: u16,
+    },
+    GetField {
+        dst: Reg,
+        src: Reg,
+        idx: u16,
+    },
+    /// A copy of the record in `src` with one field replaced.
+    SetField {
+        dst: Reg,
+        src: Reg,
+        idx: u16,
+        val: Reg,
+    },
+    MakeList {
+        dst: Reg,
+        base: Reg,
+        n: u16,
+    },
+    ListGet {
+        dst: Reg,
+        list: Reg,
+        idx: Reg,
+    },
+    Len {
+        dst: Reg,
+        src: Reg,
+    },
+    StrLen {
+        dst: Reg,
+        src: Reg,
+    },
+    MakeVariant {
+        dst: Reg,
+        tag: u32,
+        base: Reg,
+        n: u16,
+    },
+    /// The tag of an enum value, as an Int, for `match`.
+    GetTag {
+        dst: Reg,
+        src: Reg,
+    },
+    GetPayload {
+        dst: Reg,
+        src: Reg,
+        idx: u16,
+    },
+
+    IntToStr {
+        dst: Reg,
+        a: Reg,
+    },
+    /// `prec` is decimals after the point, or `u8::MAX` for the shortest form.
+    FloatToStr {
+        dst: Reg,
+        a: Reg,
+        prec: u8,
+    },
+    BoolToStr {
+        dst: Reg,
+        a: Reg,
+    },
+    Concat {
+        dst: Reg,
+        base: Reg,
+        n: u16,
+    },
+    Panic {
+        msg: u32,
+    },
+}
+
+#[derive(Debug)]
+pub struct Function {
+    pub name: String,
+    pub arity: u16,
+    pub nregs: u16,
+    pub code: Vec<Op>,
+    /// Source line of each instruction, for error messages.
+    pub lines: Vec<u32>,
+}
+
+/// A compiled script. Immutable, and shared by every process that runs it.
+#[derive(Debug, Default)]
+pub struct Module {
+    pub funcs: Vec<Function>,
+    pub consts: Vec<Value>,
+    /// String literals, which `Value::Static` points into.
+    pub strings: Vec<Rc<str>>,
+    pub globals: Vec<String>,
+    /// The function that initialises the globals, run when a process starts.
+    pub init: u32,
+    /// Event name → handler function.
+    pub handlers: Vec<(String, u32)>,
+    pub effects: Vec<String>,
+}
+
+impl Module {
+    pub fn handler(&self, event: &str) -> Option<u32> {
+        self.handlers.iter().find(|(n, _)| n == event).map(|(_, f)| *f)
+    }
+}
diff --git a/crates/frits/src/compile.rs b/crates/frits/src/compile.rs
new file mode 100644
index 0000000..7e9194e
--- /dev/null
+++ b/crates/frits/src/compile.rs
@@ -0,0 +1,1857 @@
+//! Type checking and code generation, in one pass over each function.
+//!
+//! Every expression is checked as it is compiled: `expr` returns the type it
+//! proved, and picks the typed instruction from it. Effects are checked here
+//! too: a call into an `effect` namespace needs that effect in the enclosing
+//! function's `/ …` list, and a call to a script function needs all of the
+//! callee's.
+
+use std::collections::HashMap;
+use std::rc::Rc;
+
+use crate::Error;
+use crate::ast::*;
+use crate::bytecode::{Function, Module, Op, Reg};
+use crate::types::{PlatformDecl, Show, Type, TypeEnv};
+use crate::value::Value;
+
+pub fn compile(src: &str, plat: &PlatformDecl) -> Result<Module, Vec<Error>> {
+    let ast = crate::parser::parse(src).map_err(|e| vec![e])?;
+    let mut c = Compiler::new(plat);
+    c.module(&ast);
+    if c.errors.is_empty() {
+        Ok(c.out)
+    } else {
+        c.errors.sort_by_key(|e| e.line);
+        Err(c.errors)
+    }
+}
+
+struct EnumInfo {
+    name: String,
+    variants: Vec<(String, Vec<Type>)>,
+}
+
+struct FnSig {
+    params: Vec<Type>,
+    ret: Type,
+    effects: Vec<String>,
+}
+
+struct GlobalInfo {
+    ty: Type,
+    mutable: bool,
+}
+
+struct Local {
+    name: String,
+    reg: Reg,
+    ty: Type,
+    mutable: bool,
+}
+
+#[derive(Default)]
+struct LoopCtx {
+    breaks: Vec<usize>,
+    continues: Vec<usize>,
+}
+
+#[derive(Default)]
+struct FnState {
+    code: Vec<Op>,
+    lines: Vec<u32>,
+    scopes: Vec<Vec<Local>>,
+    next: Reg,
+    max: Reg,
+    loops: Vec<LoopCtx>,
+    ret: Type,
+    effects: Vec<String>,
+    name: String,
+}
+
+/// Where an expression's value goes.
+#[derive(Clone, Copy)]
+enum Dst<'a> {
+    To(Reg, Option<&'a Type>),
+    /// Statement position: the value is dropped, so `if` and `match` arms need not agree.
+    Discard,
+}
+
+const OPTION_NONE: u32 = 0;
+const OPTION_SOME: u32 = 1;
+
+struct Compiler<'p> {
+    plat: &'p PlatformDecl,
+    env: TypeEnv,
+    enums: Vec<EnumInfo>,
+    enum_names: Vec<String>,
+    variants: HashMap<String, (u32, u32)>,
+    fns: Vec<FnSig>,
+    fn_index: HashMap<String, u32>,
+    globals: Vec<GlobalInfo>,
+    global_index: HashMap<String, u32>,
+    module_effects: Vec<String>,
+    out: Module,
+    errors: Vec<Error>,
+    f: FnState,
+    line: u32,
+    const_index: HashMap<(u8, u64), u32>,
+    string_index: HashMap<String, u32>,
+}
+
+impl<'p> Compiler<'p> {
+    fn new(plat: &'p PlatformDecl) -> Self {
+        Compiler {
+            plat,
+            env: plat.env.clone(),
+            enums: Vec::new(),
+            enum_names: Vec::new(),
+            variants: HashMap::new(),
+            fns: Vec::new(),
+            fn_index: HashMap::new(),
+            globals: Vec::new(),
+            global_index: HashMap::new(),
+            module_effects: Vec::new(),
+            out: Module::default(),
+            errors: Vec::new(),
+            f: FnState::default(),
+            line: 0,
+            const_index: HashMap::new(),
+            string_index: HashMap::new(),
+        }
+    }
+
+    fn error(&mut self, line: u32, msg: impl Into<String>) {
+        self.errors.push(Error::new(line, msg));
+    }
+
+    fn show(&self, t: &Type) -> String {
+        Show(t, &self.enum_names).to_string()
+    }
+
+    fn resolve(&mut self, t: &TypeExpr) -> Type {
+        match self.env.resolve(t) {
+            Ok(t) => t,
+            Err(e) => {
+                self.errors.push(e);
+                Type::Error
+            }
+        }
+    }
+
+    // ── The module ──
+
+    fn module(&mut self, m: &crate::ast::Module) {
+        for e in &m.effects {
+            if !self.plat.effects.contains(e) {
+                let known = self.plat.effects.join(", ");
+                self.error(1, format!("this platform has no effect `{e}` (it has: {known})"));
+            }
+        }
+        self.module_effects = m.effects.clone();
+        self.out.effects = m.effects.clone();
+
+        // Types first, so signatures can name them; enums before aliases, so an
+        // alias can name an enum.
+        for item in &m.items {
+            if let Item::Enum(e) = item {
+                let id = self.enums.len() as u32;
+                if self.env.enums.insert(e.name.clone(), id).is_some()
+                    || self.env.aliases.contains_key(&e.name)
+                {
+                    self.error(e.line, format!("type `{}` is defined twice", e.name));
+                }
+                self.enum_names.push(e.name.clone());
+                self.enums.push(EnumInfo {
+                    name: e.name.clone(),
+                    variants: Vec::new(),
+                });
+            }
+        }
+        for item in &m.items {
+            if let Item::Type(name, t, line) = item {
+                let ty = self.resolve(t);
+                if self.env.aliases.insert(name.clone(), ty).is_some() || self.env.enums.contains_key(name) {
+                    self.error(*line, format!("type `{name}` is defined twice"));
+                }
+            }
+        }
+        for item in &m.items {
+            if let Item::Enum(e) = item {
+                let id = self.env.enums[&e.name];
+                let mut vs = Vec::new();
+                for (tag, (v, payload)) in e.variants.iter().enumerate() {
+                    if !v.starts_with(|c: char| c.is_ascii_uppercase()) {
+                        self.error(e.line, format!("variant `{v}` must start with a capital letter"));
+                    }
+                    if v == "Some"
+                        || v == "None"
+                        || self.variants.insert(v.clone(), (id, tag as u32)).is_some()
+                    {
+                        self.error(e.line, format!("variant `{v}` is already defined"));
+                    }
+                    let tys = payload.iter().map(|t| self.resolve(t)).collect();
+                    vs.push((v.clone(), tys));
+                }
+                self.enums[id as usize].variants = vs;
+            }
+        }
+
+        // Signatures, so bodies can call functions defined below them.
+        let mut bodies: Vec<(&FnDecl, bool)> = Vec::new();
+        for item in &m.items {
+            match item {
+                Item::Fn(f) => {
+                    let sig = self.signature(f);
+                    let id = self.fns.len() as u32;
+                    if self.fn_index.insert(f.name.clone(), id).is_some() {
+                        self.error(f.line, format!("function `{}` is defined twice", f.name));
+                    }
+                    for e in &f.effects {
+                        if !self.plat.effects.contains(e) {
+                            self.error(f.line, format!("this platform has no effect `{e}`"));
+                        }
+                    }
+                    self.fns.push(sig);
+                    bodies.push((f, false));
+                }
+                Item::On(f) => bodies.push((f, true)),
+                Item::Namespace(_) | Item::Event(_) => self.error(
+                    1,
+                    "`effect`, `module` and `event` belong in a platform declaration, not a script",
+                ),
+                _ => {}
+            }
+        }
+        // Function ids: script functions in order, then handlers, then the init.
+        let handlers: Vec<&FnDecl> = bodies.iter().filter(|(_, h)| *h).map(|(f, _)| *f).collect();
+        let nfns = self.fns.len();
+        for (i, h) in handlers.iter().enumerate() {
+            let id = (nfns + i) as u32;
+            match self.plat.events.iter().find(|(n, _)| *n == h.name) {
+                None => {
+                    let known: Vec<_> = self.plat.events.iter().map(|(n, _)| n.as_str()).collect();
+                    self.error(
+                        h.line,
+                        format!("there is no event `{}` (events: {})", h.name, known.join(", ")),
+                    );
+                }
+                Some((_, params)) => {
+                    let sig = self.signature(h);
+                    if sig.params.len() != params.len() || sig.params.iter().zip(params).any(|(a, b)| a != b)
+                    {
+                        let want: Vec<_> = params.iter().map(|t| self.show(t)).collect();
+                        self.error(h.line, format!("`on {}` takes ({})", h.name, want.join(", ")));
+                    }
+                    if !h.effects.is_empty() {
+                        self.error(
+                            h.line,
+                            "a handler has the script's effects; it declares none of its own",
+                        );
+                    }
+                }
+            }
+            if self.out.handlers.iter().any(|(n, _)| *n == h.name) {
+                self.error(h.line, format!("`on {}` is defined twice", h.name));
+            }
+            self.out.handlers.push((h.name.clone(), id));
+        }
+        let total = nfns + handlers.len() + 1;
+        self.out.init = (total - 1) as u32;
+        self.out.funcs = (0..total)
+            .map(|_| Function {
+                name: String::new(),
+                arity: 0,
+                nregs: 0,
+                code: Vec::new(),
+                lines: Vec::new(),
+            })
+            .collect();
+
+        // The globals' initialiser, which also settles their types.
+        self.begin("(init)", Type::Unit, self.module_effects.clone());
+        for item in &m.items {
+            if let Item::Global(g) = item {
+                self.line = g.line;
+                let want = g.ty.as_ref().map(|t| self.resolve(t));
+                let r = self.alloc();
+                let ty = self.expr(&g.value, Dst::To(r, want.as_ref()));
+                let ty = match want {
+                    Some(w) => {
+                        self.expect(&ty, &w, g.line);
+                        w
+                    }
+                    None => ty,
+                };
+                if self.global_index.contains_key(&g.name) || self.fn_index.contains_key(&g.name) {
+                    self.error(g.line, format!("`{}` is defined twice", g.name));
+                }
+                let gi = self.globals.len() as u32;
+                self.globals.push(GlobalInfo {
+                    ty,
+                    mutable: g.mutable,
+                });
+                self.global_index.insert(g.name.clone(), gi);
+                self.out.globals.push(g.name.clone());
+                self.emit(Op::SetGlobal { g: gi, src: r });
+                self.f.next = 0;
+            }
+        }
+        let r = self.alloc();
+        self.emit(Op::LoadUnit { dst: r });
+        self.emit(Op::Ret { src: r });
+        let init = self.out.init;
+        self.finish(init, 0);
+
+        let mut handler_i = 0;
+        let mut fn_i = 0;
+        for (f, is_handler) in bodies {
+            let id = if is_handler {
+                handler_i += 1;
+                nfns + handler_i - 1
+            } else {
+                fn_i += 1;
+                fn_i - 1
+            };
+            self.function(f, id as u32, is_handler);
+        }
+    }
+
+    fn signature(&mut self, f: &FnDecl) -> FnSig {
+        let params = f.params.iter().map(|(_, t)| self.resolve(t)).collect();
+        let ret = f.ret.as_ref().map(|t| self.resolve(t)).unwrap_or(Type::Unit);
+        FnSig {
+            params,
+            ret,
+            effects: f.effects.clone(),
+        }
+    }
+
+    fn function(&mut self, f: &FnDecl, id: u32, is_handler: bool) {
+        let sig = self.signature(f);
+        let effects = if is_handler {
+            self.module_effects.clone()
+        } else {
+            f.effects.clone()
+        };
+        self.begin(&f.name, sig.ret.clone(), effects);
+        self.line = f.line;
+        self.f.scopes.push(Vec::new());
+        for ((name, _), ty) in f.params.iter().zip(&sig.params) {
+            let r = self.alloc();
+            self.f.scopes.last_mut().unwrap().push(Local {
+                name: name.clone(),
+                reg: r,
+                ty: ty.clone(),
+                mutable: false,
+            });
+        }
+        let body = f.body.as_ref().expect("script functions have bodies");
+        if sig.ret == Type::Unit {
+            self.block(body, Dst::Discard);
+            let r = self.alloc();
+            self.emit(Op::LoadUnit { dst: r });
+            self.emit(Op::Ret { src: r });
+        } else {
+            let r = self.alloc();
+            let ty = self.block(body, Dst::To(r, Some(&sig.ret)));
+            self.expect(&ty, &sig.ret, f.line);
+            self.emit(Op::Ret { src: r });
+        }
+        self.finish(id, sig.params.len() as u16);
+    }
+
+    fn begin(&mut self, name: &str, ret: Type, effects: Vec<String>) {
+        self.f = FnState {
+            ret,
+            effects,
+            name: name.to_string(),
+            ..Default::default()
+        };
+    }
+
+    fn finish(&mut self, id: u32, arity: u16) {
+        let f = std::mem::take(&mut self.f);
+        self.out.funcs[id as usize] = Function {
+            name: f.name,
+            arity,
+            nregs: f.max.max(1),
+            code: f.code,
+            lines: f.lines,
+        };
+    }
+
+    // ── Emitting ──
+
+    fn emit(&mut self, op: Op) -> usize {
+        self.f.code.push(op);
+        self.f.lines.push(self.line);
+        self.f.code.len() - 1
+    }
+
+    fn here(&self) -> u32 {
+        self.f.code.len() as u32
+    }
+
+    fn patch(&mut self, at: usize, to: u32) {
+        match &mut self.f.code[at] {
+            Op::Jump { to: t } | Op::JumpIfFalse { to: t, .. } | Op::JumpIfTrue { to: t, .. } => *t = to,
+            _ => unreachable!("patching a non-jump"),
+        }
+    }
+
+    fn alloc(&mut self) -> Reg {
+        let r = self.f.next;
+        self.f.next += 1;
+        self.f.max = self.f.max.max(self.f.next);
+        r
+    }
+
+    fn alloc_n(&mut self, n: usize) -> Reg {
+        let r = self.f.next;
+        self.f.next += n as Reg;
+        self.f.max = self.f.max.max(self.f.next);
+        r
+    }
+
+    fn konst(&mut self, v: Value) -> u32 {
+        let key = match v {
+            Value::Int(i) => (0, i as u64),
+            Value::Float(f) => (1, f.to_bits()),
+            Value::Static(s) => (2, s as u64),
+            _ => unreachable!(),
+        };
+        if let Some(&k) = self.const_index.get(&key) {
+            return k;
+        }
+        let k = self.out.consts.len() as u32;
+        self.out.consts.push(v);
+        self.const_index.insert(key, k);
+        k
+    }
+
+    fn string(&mut self, s: &str) -> u32 {
+        if let Some(&i) = self.string_index.get(s) {
+            return self.konst(Value::Static(i));
+        }
+        let i = self.out.strings.len() as u32;
+        self.out.strings.push(s.into());
+        self.string_index.insert(s.to_string(), i);
+        self.konst(Value::Static(i))
+    }
+
+    fn expect(&mut self, got: &Type, want: &Type, line: u32) {
+        if !got.fits(want) {
+            let (g, w) = (self.show(got), self.show(want));
+            self.error(line, format!("expected {w}, found {g}"));
+        }
+    }
+
+    fn lookup(&self, name: &str) -> Option<&Local> {
+        self.f
+            .scopes
+            .iter()
+            .rev()
+            .flat_map(|s| s.iter().rev())
+            .find(|l| l.name == name)
+    }
+
+    // ── Blocks and statements ──
+
+    fn block(&mut self, b: &Block, dst: Dst) -> Type {
+        self.f.scopes.push(Vec::new());
+        let mark = self.f.next;
+        let mut diverges = false;
+        for s in &b.stmts {
+            diverges |= self.stmt(s);
+        }
+        let ty = match (&b.tail, dst) {
+            (Some(e), d) => self.expr(e, d),
+            (None, Dst::To(r, _)) => {
+                if !diverges {
+                    self.emit(Op::LoadUnit { dst: r });
+                }
+                Type::Unit
+            }
+            (None, Dst::Discard) => Type::Unit,
+        };
+        self.f.scopes.pop();
+        self.f.next = mark;
+        if diverges && b.tail.is_none() {
+            Type::Never
+        } else {
+            ty
+        }
+    }
+
+    /// Returns whether the statement never falls through (`return`, `break`).
+    fn stmt(&mut self, s: &Stmt) -> bool {
+        let mark = self.f.next;
+        let mut diverges = false;
+        match s {
+            Stmt::Let {
+                mutable,
+                name,
+                ty,
+                value,
+                line,
+            } => {
+                self.line = *line;
+                let want = ty.as_ref().map(|t| self.resolve(t));
+                let r = self.alloc();
+                let got = self.expr(value, Dst::To(r, want.as_ref()));
+                let ty = match want {
+                    Some(w) => {
+                        self.expect(&got, &w, *line);
+                        w
+                    }
+                    None => {
+                        if got == Type::Never {
+                            self.error(
+                                *line,
+                                "this value never arrives: the expression always returns or panics",
+                            );
+                        }
+                        got
+                    }
+                };
+                self.f.scopes.last_mut().unwrap().push(Local {
+                    name: name.clone(),
+                    reg: r,
+                    ty,
+                    mutable: *mutable,
+                });
+                // The local keeps its register; temporaries above it are free again.
+                self.f.next = r + 1;
+                return false;
+            }
+            Stmt::Assign {
+                target,
+                op,
+                value,
+                line,
+            } => {
+                self.line = *line;
+                self.assign(target, *op, value, *line);
+            }
+            Stmt::Expr(e) => {
+                let ty = self.expr(e, Dst::Discard);
+                diverges = ty == Type::Never;
+            }
+            Stmt::While { cond, body, line } => {
+                self.line = *line;
+                let start = self.here();
+                let c = self.cond(cond);
+                let exit = self.emit(Op::JumpIfFalse { cond: c, to: 0 });
+                self.f.next = mark;
+                self.f.loops.push(LoopCtx::default());
+                self.block(body, Dst::Discard);
+                self.emit(Op::Jump { to: start });
+                let end = self.here();
+                self.patch(exit, end);
+                let l = self.f.loops.pop().unwrap();
+                for b in l.breaks {
+                    self.patch(b, end);
+                }
+                for c in l.continues {
+                    self.patch(c, start);
+                }
+            }
+            Stmt::For {
+                var,
+                iter,
+                body,
+                line,
+            } => {
+                self.line = *line;
+                self.for_loop(var, iter, body, *line);
+            }
+            Stmt::Return(v, line) => {
+                self.line = *line;
+                let ret = self.f.ret.clone();
+                let r = self.alloc();
+                match v {
+                    Some(e) => {
+                        let t = self.expr(e, Dst::To(r, Some(&ret)));
+                        self.expect(&t, &ret, *line);
+                    }
+                    None => {
+                        if ret != Type::Unit {
+                            let w = self.show(&ret);
+                            self.error(*line, format!("`return` needs a value of type {w}"));
+                        }
+                        self.emit(Op::LoadUnit { dst: r });
+                    }
+                }
+                self.emit(Op::Ret { src: r });
+                diverges = true;
+            }
+            Stmt::Break(line) | Stmt::Continue(line) => {
+                self.line = *line;
+                let at = self.emit(Op::Jump { to: 0 });
+                let is_break = matches!(s, Stmt::Break(_));
+                match self.f.loops.last_mut() {
+                    Some(l) if is_break => l.breaks.push(at),
+                    Some(l) => l.continues.push(at),
+                    None => self.error(*line, "`break` and `continue` belong inside a loop"),
+                }
+                diverges = true;
+            }
+        }
+        self.f.next = mark;
+        diverges
+    }
+
+    fn cond(&mut self, e: &Expr) -> Reg {
+        let (r, t) = self.expr_any(e, Some(&Type::Bool));
+        self.expect(&t, &Type::Bool, e.line);
+        r
+    }
+
+    fn for_loop(&mut self, var: &str, iter: &ForIter, body: &Block, line: u32) {
+        self.f.scopes.push(Vec::new());
+        let mark = self.f.next;
+        match iter {
+            ForIter::Range(from, to) => {
+                let i = self.alloc();
+                let t = self.expr(from, Dst::To(i, Some(&Type::Int)));
+                self.expect(&t, &Type::Int, line);
+                let end = self.alloc();
+                let t = self.expr(to, Dst::To(end, Some(&Type::Int)));
+                self.expect(&t, &Type::Int, line);
+                let one = self.alloc();
+                let k = self.konst(Value::Int(1));
+                self.emit(Op::LoadK { dst: one, k });
+                let c = self.alloc();
+                let start = self.here();
+                self.emit(Op::LtI { dst: c, a: i, b: end });
+                let exit = self.emit(Op::JumpIfFalse { cond: c, to: 0 });
+                // The body sees a copy, so assigning the loop variable cannot skip steps.
+                let v = self.alloc();
+                self.emit(Op::Move { dst: v, src: i });
+                self.f.scopes.last_mut().unwrap().push(Local {
+                    name: var.to_string(),
+                    reg: v,
+                    ty: Type::Int,
+                    mutable: false,
+                });
+                self.f.loops.push(LoopCtx::default());
+                self.block(body, Dst::Discard);
+                let step = self.here();
+                self.emit(Op::AddI { dst: i, a: i, b: one });
+                self.emit(Op::Jump { to: start });
+                let end_pc = self.here();
+                self.patch(exit, end_pc);
+                let l = self.f.loops.pop().unwrap();
+                for b in l.breaks {
+                    self.patch(b, end_pc);
+                }
+                for c in l.continues {
+                    self.patch(c, step);
+                }
+            }
+            ForIter::List(list) => {
+                let lr = self.alloc();
+                let lt = self.expr(list, Dst::To(lr, None));
+                let elem = match &lt {
+                    Type::List(t) => (**t).clone(),
+                    Type::Error => Type::Error,
+                    t => {
+                        let s = self.show(t);
+                        self.error(
+                            line,
+                            format!("`for … in` needs a List or a range `a..b`, found {s}"),
+                        );
+                        Type::Error
+                    }
+                };
+                let n = self.alloc();
+                self.emit(Op::Len { dst: n, src: lr });
+                let i = self.alloc();
+                let k0 = self.konst(Value::Int(0));
+                self.emit(Op::LoadK { dst: i, k: k0 });
+                let one = self.alloc();
+                let k1 = self.konst(Value::Int(1));
+                self.emit(Op::LoadK { dst: one, k: k1 });
+                let c = self.alloc();
+                let start = self.here();
+                self.emit(Op::LtI { dst: c, a: i, b: n });
+                let exit = self.emit(Op::JumpIfFalse { cond: c, to: 0 });
+                let v = self.alloc();
+                self.emit(Op::ListGet {
+                    dst: v,
+                    list: lr,
+                    idx: i,
+                });
+                self.f.scopes.last_mut().unwrap().push(Local {
+                    name: var.to_string(),
+                    reg: v,
+                    ty: elem,
+                    mutable: false,
+                });
+                self.f.loops.push(LoopCtx::default());
+                self.block(body, Dst::Discard);
+                let step = self.here();
+                self.emit(Op::AddI { dst: i, a: i, b: one });
+                self.emit(Op::Jump { to: start });
+                let end_pc = self.here();
+                self.patch(exit, end_pc);
+                let l = self.f.loops.pop().unwrap();
+                for b in l.breaks {
+                    self.patch(b, end_pc);
+                }
+                for c in l.continues {
+                    self.patch(c, step);
+                }
+            }
+        }
+        self.f.scopes.pop();
+        self.f.next = mark;
+    }
+
+    /// `x = v`, `x += v`, and `a.b.c = v`, which builds a new `a` with the one
+    /// field changed: values are never shared mutably, so a field assignment is a
+    /// copy written back to the variable.
+    fn assign(&mut self, target: &Expr, op: Option<BinOp>, value: &Expr, line: u32) {
+        // The path from the variable to the field being set.
+        let mut path: Vec<&str> = Vec::new();
+        let mut root = target;
+        while let ExprKind::Field(inner, f) = &root.kind {
+            path.push(f);
+            root = inner;
+        }
+        path.reverse();
+        let ExprKind::Ident(name) = &root.kind else {
+            self.error(line, "only a variable or one of its fields can be assigned to");
+            return;
+        };
+        enum Slot {
+            Local(Reg),
+            Global(u32),
+        }
+        let (slot, root_ty) =
+            if let Some((reg, ty, mutable)) = self.lookup(name).map(|l| (l.reg, l.ty.clone(), l.mutable)) {
+                if !mutable {
+                    self.error(line, format!("`{name}` cannot be changed: declare it with `var`"));
+                }
+                (Slot::Local(reg), ty)
+            } else if let Some(&g) = self.global_index.get(name) {
+                if !self.globals[g as usize].mutable {
+                    self.error(line, format!("`{name}` cannot be changed: declare it with `var`"));
+                }
+                (Slot::Global(g), self.globals[g as usize].ty.clone())
+            } else {
+                self.error(line, format!("unknown variable `{name}`"));
+                return;
+            };
+        // Load the chain: regs[0] is the variable, regs[i+1] its field path[i].
+        let mut regs = Vec::new();
+        let mut tys = vec![root_ty.clone()];
+        let r0 = match slot {
+            Slot::Local(r) => r,
+            Slot::Global(g) => {
+                let r = self.alloc();
+                self.emit(Op::GetGlobal { dst: r, g });
+                r
+            }
+        };
+        regs.push(r0);
+        let mut idxs = Vec::new();
+        for f in &path {
+            let cur = tys.last().unwrap().clone();
+            let Some((idx, fty)) = cur.field(f).map(|(i, t)| (i, t.clone())) else {
+                if cur != Type::Error {
+                    let s = self.show(&cur);
+                    self.error(line, format!("{s} has no field `{f}`"));
+                }
+                return;
+            };
+            let r = self.alloc();
+            self.emit(Op::GetField {
+                dst: r,
+                src: *regs.last().unwrap(),
+                idx: idx as u16,
+            });
+            regs.push(r);
+            idxs.push(idx as u16);
+            tys.push(fty);
+        }
+        let leaf_ty = tys.last().unwrap().clone();
+        let leaf = *regs.last().unwrap();
+        let v = self.alloc();
+        match op {
+            None => {
+                let t = self.expr(value, Dst::To(v, Some(&leaf_ty)));
+                self.expect(&t, &leaf_ty, line);
+            }
+            Some(op) => {
+                let (rv, rt) = self.expr_any(value, Some(&leaf_ty));
+                let t = self.arith(op, &leaf_ty, &rt, leaf, rv, v, line);
+                self.expect(&t, &leaf_ty, line);
+            }
+        }
+        // Rebuild outward.
+        let mut cur = v;
+        for i in (0..path.len()).rev() {
+            let r = self.alloc();
+            self.emit(Op::SetField {
+                dst: r,
+                src: regs[i],
+                idx: idxs[i],
+                val: cur,
+            });
+            cur = r;
+        }
+        match slot {
+            Slot::Local(r) => {
+                self.emit(Op::Move { dst: r, src: cur });
+            }
+            Slot::Global(g) => {
+                self.emit(Op::SetGlobal { g, src: cur });
+            }
+        }
+    }
+
+    // ── Expressions ──
+
+    /// The expression's value in some register: a local's own, or a fresh one.
+    fn expr_any(&mut self, e: &Expr, want: Option<&Type>) -> (Reg, Type) {
+        if let ExprKind::Ident(n) = &e.kind
+            && let Some(l) = self.lookup(n)
+        {
+            return (l.reg, l.ty.clone());
+        }
+        let r = self.alloc();
+        let t = self.expr(e, Dst::To(r, want));
+        (r, t)
+    }
+
+    fn expr(&mut self, e: &Expr, dst: Dst) -> Type {
+        self.line = e.line;
+        let line = e.line;
+        // Control flow passes `dst` down; everything else computes into a register.
+        match &e.kind {
+            ExprKind::If(c, then, els) => return self.if_expr(c, then, els.as_deref(), dst, line),
+            ExprKind::IfLet(p, v, then, els) => return self.if_let(p, v, then, els.as_deref(), dst, line),
+            ExprKind::Match(s, arms) => return self.match_expr(s, arms, dst, line),
+            ExprKind::Block(b) => return self.block(b, dst),
+            _ => {}
+        }
+        let (r, want) = match dst {
+            Dst::To(r, w) => (r, w),
+            Dst::Discard => {
+                let mark = self.f.next;
+                let r = self.alloc();
+                let t = self.expr(e, Dst::To(r, None));
+                self.f.next = mark;
+                return t;
+            }
+        };
+        match &e.kind {
+            ExprKind::Int(i) => {
+                if want == Some(&Type::Float) {
+                    let k = self.konst(Value::Float(*i as f64));
+                    self.emit(Op::LoadK { dst: r, k });
+                    return Type::Float;
+                }
+                let k = self.konst(Value::Int(*i));
+                self.emit(Op::LoadK { dst: r, k });
+                Type::Int
+            }
+            ExprKind::Float(f) => {
+                let k = self.konst(Value::Float(*f));
+                self.emit(Op::LoadK { dst: r, k });
+                Type::Float
+            }
+            ExprKind::Bool(b) => {
+                self.emit(Op::LoadBool { dst: r, v: *b });
+                Type::Bool
+            }
+            ExprKind::Str(s) => {
+                let k = self.string(s);
+                self.emit(Op::LoadK { dst: r, k });
+                Type::Str
+            }
+            ExprKind::Template(parts) => self.template(parts, r),
+            ExprKind::Ident(n) => self.ident(n, r, want, line),
+            ExprKind::Field(base, f) => self.field(base, f, r, line),
+            ExprKind::Call(callee, args) => self.call(callee, args, r, want, line),
+            ExprKind::Index(list, idx) => {
+                let (lr, lt) = self.expr_any(list, None);
+                let (ir, it) = self.expr_any(idx, Some(&Type::Int));
+                self.expect(&it, &Type::Int, line);
+                match lt {
+                    Type::List(t) => {
+                        self.emit(Op::ListGet {
+                            dst: r,
+                            list: lr,
+                            idx: ir,
+                        });
+                        (*t).clone()
+                    }
+                    Type::Error => Type::Error,
+                    t => {
+                        let s = self.show(&t);
+                        self.error(line, format!("only a List can be indexed, not {s}"));
+                        Type::Error
+                    }
+                }
+            }
+            ExprKind::Binary(op, a, b) => self.binary(*op, a, b, r, line),
+            ExprKind::Unary(op, a) => {
+                let (ar, at) = self.expr_any(a, want);
+                match (op, &at) {
+                    (UnOp::Neg, Type::Int) => {
+                        self.emit(Op::NegI { dst: r, a: ar });
+                        Type::Int
+                    }
+                    (UnOp::Neg, Type::Float) => {
+                        self.emit(Op::NegF { dst: r, a: ar });
+                        Type::Float
+                    }
+                    (UnOp::Not, Type::Bool) => {
+                        self.emit(Op::Not { dst: r, a: ar });
+                        Type::Bool
+                    }
+                    (_, Type::Error) => Type::Error,
+                    _ => {
+                        let s = self.show(&at);
+                        let o = if *op == UnOp::Neg { "-" } else { "!" };
+                        self.error(line, format!("`{o}` does not apply to {s}"));
+                        Type::Error
+                    }
+                }
+            }
+            ExprKind::Record(fields, spread) => self.record(fields, spread.as_deref(), r, want, line),
+            ExprKind::List(items) => {
+                let elem_want = match want {
+                    Some(Type::List(t)) => Some((**t).clone()),
+                    _ => None,
+                };
+                if items.is_empty() {
+                    return match elem_want {
+                        Some(t) => {
+                            self.emit(Op::MakeList {
+                                dst: r,
+                                base: r,
+                                n: 0,
+                            });
+                            Type::List(Rc::new(t))
+                        }
+                        None => {
+                            self.error(
+                                line,
+                                "the type of an empty list is unknown here: write `let xs: List<Int> = []`",
+                            );
+                            Type::Error
+                        }
+                    };
+                }
+                let base = self.alloc_n(items.len());
+                let mut elem = elem_want;
+                for (i, it) in items.iter().enumerate() {
+                    let t = self.expr(it, Dst::To(base + i as Reg, elem.as_ref()));
+                    match &elem {
+                        Some(w) => self.expect(&t, w, it.line),
+                        None => elem = Some(t),
+                    }
+                }
+                self.emit(Op::MakeList {
+                    dst: r,
+                    base,
+                    n: items.len() as u16,
+                });
+                Type::List(Rc::new(elem.unwrap()))
+            }
+            ExprKind::If(..) | ExprKind::IfLet(..) | ExprKind::Match(..) | ExprKind::Block(_) => {
+                unreachable!()
+            }
+        }
+    }
+
+    fn ident(&mut self, n: &str, r: Reg, want: Option<&Type>, line: u32) -> Type {
+        if let Some(l) = self.lookup(n) {
+            let (src, ty) = (l.reg, l.ty.clone());
+            self.emit(Op::Move { dst: r, src });
+            return ty;
+        }
+        if let Some(&g) = self.global_index.get(n) {
+            self.emit(Op::GetGlobal { dst: r, g });
+            return self.globals[g as usize].ty.clone();
+        }
+        if n == "None" {
+            return match want {
+                Some(t @ Type::Option(_)) => {
+                    self.emit(Op::LoadTag {
+                        dst: r,
+                        tag: OPTION_NONE,
+                    });
+                    t.clone()
+                }
+                _ => {
+                    self.error(
+                        line,
+                        "the type of `None` is unknown here: write `let x: Option<Float> = None`",
+                    );
+                    Type::Error
+                }
+            };
+        }
+        if let Some(&(e, tag)) = self.variants.get(n) {
+            if !self.enums[e as usize].variants[tag as usize].1.is_empty() {
+                self.error(line, format!("`{n}` carries values: write `{n}(…)`"));
+                return Type::Error;
+            }
+            self.emit(Op::LoadTag { dst: r, tag });
+            return Type::Enum(e);
+        }
+        if self.fn_index.contains_key(n) {
+            self.error(line, format!("`{n}` is a function: call it as `{n}(…)`"));
+        } else if self.plat.is_namespace(n) {
+            self.error(line, format!("`{n}` is a namespace: write `{n}.name`"));
+        } else {
+            self.error(line, format!("unknown name `{n}`"));
+        }
+        Type::Error
+    }
+
+    fn field(&mut self, base: &Expr, f: &str, r: Reg, line: u32) -> Type {
+        if let ExprKind::Ident(ns) = &base.kind
+            && self.lookup(ns).is_none()
+            && !self.global_index.contains_key(ns)
+            && self.plat.is_namespace(ns)
+        {
+            let Some((c, sig)) = self.plat.host_const(ns, f) else {
+                self.error(
+                    line,
+                    format!("`{ns}` has no value `{f}` (to call a function, write `{ns}.{f}(…)`)"),
+                );
+                return Type::Error;
+            };
+            let ty = sig.ty.clone();
+            if self.plat.effects.iter().any(|e| e == ns) && !self.f.effects.iter().any(|e| e == ns) {
+                self.missing_effect(ns, line);
+            }
+            self.emit(Op::HostConst { dst: r, c });
+            return ty;
+        }
+        let (br, bt) = self.expr_any(base, None);
+        match bt.field(f) {
+            Some((idx, t)) => {
+                let t = t.clone();
+                self.emit(Op::GetField {
+                    dst: r,
+                    src: br,
+                    idx: idx as u16,
+                });
+                t
+            }
+            None => {
+                if bt != Type::Error {
+                    let s = self.show(&bt);
+                    self.error(line, format!("{s} has no field `{f}`"));
+                }
+                Type::Error
+            }
+        }
+    }
+
+    fn missing_effect(&mut self, effect: &str, line: u32) {
+        let who = self.f.name.clone();
+        if who == "(init)" || self.out.handlers.iter().any(|(n, _)| *n == who) {
+            self.error(
+                line,
+                format!("this needs the effect `{effect}`: add it to `script / …`"),
+            );
+        } else {
+            self.error(
+                line,
+                format!("this needs the effect `{effect}`: declare it as `fn {who}(…) / {effect}`"),
+            );
+        }
+    }
+
+    /// Arguments into consecutive registers at a fresh base.
+    fn args(&mut self, args: &[Expr], params: &[Type], what: &str, line: u32) -> Reg {
+        if args.len() != params.len() {
+            self.error(
+                line,
+                format!("{what} takes {} argument(s), not {}", params.len(), args.len()),
+            );
+        }
+        let base = self.alloc_n(args.len().max(1));
+        for (i, a) in args.iter().enumerate() {
+            let want = params.get(i);
+            let t = self.expr(a, Dst::To(base + i as Reg, want));
+            if let Some(w) = want {
+                self.expect(&t, w, a.line);
+            }
+        }
+        base
+    }
+
+    fn call(&mut self, callee: &Expr, args: &[Expr], r: Reg, want: Option<&Type>, line: u32) -> Type {
+        match &callee.kind {
+            ExprKind::Field(ns_e, name) => {
+                if let ExprKind::Ident(ns) = &ns_e.kind
+                    && self.lookup(ns).is_none()
+                    && !self.global_index.contains_key(ns)
+                    && self.plat.is_namespace(ns)
+                {
+                    let Some((f, sig)) = self.plat.host_fn(ns, name) else {
+                        self.error(line, format!("`{ns}` has no function `{name}`"));
+                        return Type::Error;
+                    };
+                    let sig = sig.clone();
+                    if let Some(eff) = &sig.effect
+                        && !self.f.effects.contains(eff)
+                    {
+                        self.missing_effect(eff, line);
+                    }
+                    let base = self.args(args, &sig.params, &format!("`{ns}.{name}`"), line);
+                    self.emit(Op::CallHost {
+                        f,
+                        base,
+                        argc: args.len() as u16,
+                        dst: r,
+                    });
+                    return sig.ret;
+                }
+                self.error(
+                    line,
+                    "only functions can be called; methods are not supported yet",
+                );
+                Type::Error
+            }
+            ExprKind::Ident(n) => {
+                if let Some(t) = self.builtin(n, args, r, line) {
+                    return t;
+                }
+                if n == "Some" {
+                    let inner_want = match want {
+                        Some(Type::Option(t)) => Some((**t).clone()),
+                        _ => None,
+                    };
+                    if args.len() != 1 {
+                        self.error(line, "`Some` takes one value");
+                        return Type::Error;
+                    }
+                    let base = self.alloc();
+                    let t = self.expr(&args[0], Dst::To(base, inner_want.as_ref()));
+                    if let Some(w) = &inner_want {
+                        self.expect(&t, w, line);
+                    }
+                    self.emit(Op::MakeVariant {
+                        dst: r,
+                        tag: OPTION_SOME,
+                        base,
+                        n: 1,
+                    });
+                    return Type::Option(Rc::new(inner_want.unwrap_or(t)));
+                }
+                if let Some(&(e, tag)) = self.variants.get(n) {
+                    let params = self.enums[e as usize].variants[tag as usize].1.clone();
+                    if params.is_empty() {
+                        self.error(
+                            line,
+                            format!("`{n}` carries no values: write `{n}` without `(…)`"),
+                        );
+                        return Type::Error;
+                    }
+                    let base = self.args(args, &params, &format!("`{n}`"), line);
+                    self.emit(Op::MakeVariant {
+                        dst: r,
+                        tag,
+                        base,
+                        n: params.len() as u16,
+                    });
+                    return Type::Enum(e);
+                }
+                let Some(&f) = self.fn_index.get(n) else {
+                    self.error(line, format!("unknown function `{n}`"));
+                    return Type::Error;
+                };
+                let (params, ret, effects) = {
+                    let s = &self.fns[f as usize];
+                    (s.params.clone(), s.ret.clone(), s.effects.clone())
+                };
+                for eff in &effects {
+                    if !self.f.effects.contains(eff) {
+                        self.missing_effect(eff, line);
+                    }
+                }
+                let base = self.args(args, &params, &format!("`{n}`"), line);
+                self.emit(Op::Call { f, base, dst: r });
+                ret
+            }
+            _ => {
+                self.error(line, "only named functions can be called");
+                Type::Error
+            }
+        }
+    }
+
+    fn builtin(&mut self, n: &str, args: &[Expr], r: Reg, line: u32) -> Option<Type> {
+        let one = |c: &mut Self| -> Option<(Reg, Type)> {
+            if args.len() != 1 {
+                c.error(line, format!("`{n}` takes one value"));
+                return None;
+            }
+            Some(c.expr_any(&args[0], None))
+        };
+        Some(match n {
+            "float" => {
+                let (a, t) = one(self)?;
+                self.expect(&t, &Type::Int, line);
+                self.emit(Op::IntToFloat { dst: r, a });
+                Type::Float
+            }
+            "int" => {
+                let (a, t) = one(self)?;
+                self.expect(&t, &Type::Float, line);
+                self.emit(Op::FloatToInt { dst: r, a });
+                Type::Int
+            }
+            "len" => {
+                let (a, t) = one(self)?;
+                match t {
+                    Type::List(_) => self.emit(Op::Len { dst: r, src: a }),
+                    Type::Str => self.emit(Op::StrLen { dst: r, src: a }),
+                    Type::Error => 0,
+                    t => {
+                        let s = self.show(&t);
+                        self.error(line, format!("`len` takes a List or a Str, not {s}"));
+                        0
+                    }
+                };
+                Type::Int
+            }
+            "panic" => {
+                let msg = match args {
+                    [
+                        Expr {
+                            kind: ExprKind::Str(s),
+                            ..
+                        },
+                    ] => s.clone(),
+                    _ => {
+                        self.error(line, "`panic` takes a plain string");
+                        String::new()
+                    }
+                };
+                let k = self.string(&msg);
+                let Value::Static(s) = self.out.consts[k as usize] else {
+                    unreachable!()
+                };
+                self.emit(Op::Panic { msg: s });
+                Type::Never
+            }
+            _ => return None,
+        })
+    }
+
+    #[allow(clippy::too_many_arguments)]
+    fn arith(&mut self, op: BinOp, lt: &Type, rt: &Type, a: Reg, b: Reg, dst: Reg, line: u32) -> Type {
+        use BinOp::*;
+        match (lt, rt) {
+            (Type::Int, Type::Int) => {
+                self.emit(match op {
+                    Add => Op::AddI { dst, a, b },
+                    Sub => Op::SubI { dst, a, b },
+                    Mul => Op::MulI { dst, a, b },
+                    Div => Op::DivI { dst, a, b },
+                    Rem => Op::RemI { dst, a, b },
+                    _ => unreachable!(),
+                });
+                Type::Int
+            }
+            (Type::Float, Type::Float) => {
+                self.emit(match op {
+                    Add => Op::AddF { dst, a, b },
+                    Sub => Op::SubF { dst, a, b },
+                    Mul => Op::MulF { dst, a, b },
+                    Div => Op::DivF { dst, a, b },
+                    Rem => Op::RemF { dst, a, b },
+                    _ => unreachable!(),
+                });
+                Type::Float
+            }
+            (Type::Str, Type::Str) if op == Add => {
+                let base = self.alloc_n(2);
+                self.emit(Op::Move { dst: base, src: a });
+                self.emit(Op::Move {
+                    dst: base + 1,
+                    src: b,
+                });
+                self.emit(Op::Concat { dst, base, n: 2 });
+                Type::Str
+            }
+            (Type::Error, _) | (_, Type::Error) => Type::Error,
+            _ => {
+                let (l, r) = (self.show(lt), self.show(rt));
+                let hint = if matches!((lt, rt), (Type::Int, Type::Float) | (Type::Float, Type::Int)) {
+                    " (convert with `float(…)` or `int(…)`)"
+                } else {
+                    ""
+                };
+                let sym = match op {
+                    Add => "+",
+                    Sub => "-",
+                    Mul => "*",
+                    Div => "/",
+                    _ => "%",
+                };
+                self.error(line, format!("cannot apply `{sym}` to {l} and {r}{hint}"));
+                Type::Error
+            }
+        }
+    }
+
+    fn binary(&mut self, op: BinOp, a: &Expr, b: &Expr, r: Reg, line: u32) -> Type {
+        use BinOp::*;
+        if matches!(op, And | Or) {
+            let t = self.expr(a, Dst::To(r, Some(&Type::Bool)));
+            self.expect(&t, &Type::Bool, a.line);
+            let skip = if op == And {
+                self.emit(Op::JumpIfFalse { cond: r, to: 0 })
+            } else {
+                self.emit(Op::JumpIfTrue { cond: r, to: 0 })
+            };
+            let t = self.expr(b, Dst::To(r, Some(&Type::Bool)));
+            self.expect(&t, &Type::Bool, b.line);
+            let end = self.here();
+            self.patch(skip, end);
+            return Type::Bool;
+        }
+        // An integer literal beside a Float is a Float: `2 * math.pi`.
+        let (ar, at, br, bt) = if matches!(a.kind, ExprKind::Int(_)) && !matches!(b.kind, ExprKind::Int(_)) {
+            let (br, bt) = self.expr_any(b, None);
+            let (ar, at) = self.expr_any(a, Some(&bt));
+            (ar, at, br, bt)
+        } else {
+            let (ar, at) = self.expr_any(a, None);
+            let (br, bt) = self.expr_any(b, Some(&at));
+            (ar, at, br, bt)
+        };
+        match op {
+            Add | Sub | Mul | Div | Rem => self.arith(op, &at, &bt, ar, br, r, line),
+            Lt | Le | Gt | Ge => {
+                let (x, y) = if matches!(op, Gt | Ge) { (br, ar) } else { (ar, br) };
+                let strict = matches!(op, Lt | Gt);
+                match (&at, &bt) {
+                    (Type::Int, Type::Int) => {
+                        self.emit(if strict {
+                            Op::LtI { dst: r, a: x, b: y }
+                        } else {
+                            Op::LeI { dst: r, a: x, b: y }
+                        });
+                    }
+                    (Type::Float, Type::Float) => {
+                        self.emit(if strict {
+                            Op::LtF { dst: r, a: x, b: y }
+                        } else {
+                            Op::LeF { dst: r, a: x, b: y }
+                        });
+                    }
+                    (Type::Error, _) | (_, Type::Error) => {}
+                    _ => {
+                        let (l, rr) = (self.show(&at), self.show(&bt));
+                        self.error(line, format!("cannot compare {l} with {rr}"));
+                    }
+                }
+                Type::Bool
+            }
+            Eq | Ne => {
+                if at.fits(&bt) || bt.fits(&at) {
+                    match &at {
+                        Type::Int => {
+                            self.emit(Op::EqI { dst: r, a: ar, b: br });
+                        }
+                        Type::Float => {
+                            self.emit(Op::EqF { dst: r, a: ar, b: br });
+                        }
+                        Type::Bool => {
+                            self.emit(Op::EqB { dst: r, a: ar, b: br });
+                        }
+                        Type::Str => {
+                            self.emit(Op::EqS { dst: r, a: ar, b: br });
+                        }
+                        Type::Enum(e) if self.enums[*e as usize].variants.iter().all(|v| v.1.is_empty()) => {
+                            self.emit(Op::EqTag { dst: r, a: ar, b: br });
+                        }
+                        Type::Error => {}
+                        t => {
+                            let s = self.show(t);
+                            self.error(line, format!("`==` does not apply to {s}: use `match`"));
+                        }
+                    }
+                } else {
+                    let (l, rr) = (self.show(&at), self.show(&bt));
+                    self.error(line, format!("cannot compare {l} with {rr}"));
+                }
+                if op == Ne {
+                    self.emit(Op::Not { dst: r, a: r });
+                }
+                Type::Bool
+            }
+            And | Or => unreachable!(),
+        }
+    }
+
+    fn template(&mut self, parts: &[TPart], r: Reg) -> Type {
+        let base = self.alloc_n(parts.len());
+        for (i, p) in parts.iter().enumerate() {
+            let slot = base + i as Reg;
+            match p {
+                TPart::Lit(s) => {
+                    let k = self.string(s);
+                    self.emit(Op::LoadK { dst: slot, k });
+                }
+                TPart::Hole(e, fmt) => {
+                    let (er, t) = self.expr_any(e, None);
+                    let prec = match fmt {
+                        None => u8::MAX,
+                        Some(f) => match f.strip_prefix('.').and_then(|d| d.parse::<u8>().ok()) {
+                            Some(p) if p < 20 => p,
+                            _ => {
+                                self.error(
+                                    e.line,
+                                    format!("unknown format `{f}`: write `.2` for two decimals"),
+                                );
+                                u8::MAX
+                            }
+                        },
+                    };
+                    if fmt.is_some() && t != Type::Float {
+                        self.error(e.line, "only a Float takes a `:.N` format");
+                    }
+                    match t {
+                        Type::Str => {
+                            self.emit(Op::Move { dst: slot, src: er });
+                        }
+                        Type::Int => {
+                            self.emit(Op::IntToStr { dst: slot, a: er });
+                        }
+                        Type::Float => {
+                            self.emit(Op::FloatToStr {
+                                dst: slot,
+                                a: er,
+                                prec,
+                            });
+                        }
+                        Type::Bool => {
+                            self.emit(Op::BoolToStr { dst: slot, a: er });
+                        }
+                        Type::Error => {}
+                        t => {
+                            let s = self.show(&t);
+                            self.error(e.line, format!("{s} cannot be written into a string yet"));
+                        }
+                    }
+                }
+            }
+        }
+        self.emit(Op::Concat {
+            dst: r,
+            base,
+            n: parts.len() as u16,
+        });
+        Type::Str
+    }
+
+    fn record(
+        &mut self,
+        fields: &[(Name, Expr)],
+        spread: Option<&Expr>,
+        r: Reg,
+        want: Option<&Type>,
+        line: u32,
+    ) -> Type {
+        for (i, (n, _)) in fields.iter().enumerate() {
+            if fields[..i].iter().any(|(m, _)| m == n) {
+                self.error(line, format!("field `{n}` is given twice"));
+                return Type::Error;
+            }
+        }
+        if let Some(s) = spread {
+            let (sr, st) = self.expr_any(s, want);
+            let Type::Record(tf) = &st else {
+                if st != Type::Error {
+                    let t = self.show(&st);
+                    self.error(line, format!("`..` takes a record, not {t}"));
+                }
+                return Type::Error;
+            };
+            let tf = tf.clone();
+            for (n, _) in fields {
+                if !tf.iter().any(|(m, _)| **m == **n) {
+                    let t = self.show(&st);
+                    self.error(line, format!("{t} has no field `{n}`"));
+                    return Type::Error;
+                }
+            }
+            let base = self.alloc_n(tf.len());
+            for (i, (fname, fty)) in tf.iter().enumerate() {
+                let slot = base + i as Reg;
+                match fields.iter().find(|(n, _)| **n == **fname) {
+                    Some((_, e)) => {
+                        let t = self.expr(e, Dst::To(slot, Some(fty)));
+                        self.expect(&t, fty, e.line);
+                    }
+                    None => {
+                        self.emit(Op::GetField {
+                            dst: slot,
+                            src: sr,
+                            idx: i as u16,
+                        });
+                    }
+                }
+            }
+            self.emit(Op::MakeRecord {
+                dst: r,
+                base,
+                n: tf.len() as u16,
+            });
+            return st;
+        }
+        let mut order: Vec<usize> = (0..fields.len()).collect();
+        order.sort_by(|&a, &b| fields[a].0.cmp(&fields[b].0));
+        let base = self.alloc_n(fields.len());
+        let mut tys: Vec<(Rc<str>, Type)> = Vec::new();
+        for (slot, &i) in order.iter().enumerate() {
+            let (n, e) = &fields[i];
+            let fw = want.and_then(|w| w.field(n)).map(|(_, t)| t.clone());
+            let t = self.expr(e, Dst::To(base + slot as Reg, fw.as_ref()));
+            tys.push((n.as_str().into(), t));
+        }
+        self.emit(Op::MakeRecord {
+            dst: r,
+            base,
+            n: fields.len() as u16,
+        });
+        Type::Record(tys.into())
+    }
+
+    /// Merge one branch's type into the running result of an `if` or `match`.
+    fn join(&mut self, acc: &mut Option<Type>, t: Type, line: u32) {
+        match acc {
+            None => *acc = Some(t),
+            Some(a) if *a == Type::Never => *acc = Some(t),
+            Some(a) => {
+                if !t.fits(a) {
+                    let (x, y) = (self.show(a), self.show(&t));
+                    self.error(line, format!("the branches disagree: {x} and {y}"));
+                }
+            }
+        }
+    }
+
+    fn if_expr(&mut self, c: &Expr, then: &Block, els: Option<&Expr>, dst: Dst, line: u32) -> Type {
+        let mark = self.f.next;
+        let cr = self.cond(c);
+        let jf = self.emit(Op::JumpIfFalse { cond: cr, to: 0 });
+        self.f.next = mark;
+        let mut acc = None;
+        let t = self.block(then, dst);
+        self.join(&mut acc, t, line);
+        let Some(els) = els else {
+            match dst {
+                Dst::To(r, _) => {
+                    if acc
+                        .as_ref()
+                        .is_some_and(|t| *t != Type::Unit && *t != Type::Never)
+                    {
+                        self.error(line, "an `if` that gives a value needs an `else`");
+                    }
+                    // The value of the missing else branch.
+                    let skip = self.emit(Op::Jump { to: 0 });
+                    let e = self.here();
+                    self.patch(jf, e);
+                    self.emit(Op::LoadUnit { dst: r });
+                    let end = self.here();
+                    self.patch(skip, end);
+                }
+                Dst::Discard => {
+                    let end = self.here();
+                    self.patch(jf, end);
+                }
+            }
+            return Type::Unit;
+        };
+        let jend = self.emit(Op::Jump { to: 0 });
+        let e = self.here();
+        self.patch(jf, e);
+        let want_owned = match dst {
+            Dst::To(_, w) => w.cloned().or_else(|| acc.clone().filter(|t| *t != Type::Never)),
+            _ => None,
+        };
+        let dst2 = match dst {
+            Dst::To(r, _) => Dst::To(r, want_owned.as_ref()),
+            d => d,
+        };
+        let t = self.expr(els, dst2);
+        if matches!(dst, Dst::To(..)) {
+            self.join(&mut acc, t, line);
+        }
+        let end = self.here();
+        self.patch(jend, end);
+        if matches!(dst, Dst::Discard) {
+            Type::Unit
+        } else {
+            acc.unwrap_or(Type::Unit)
+        }
+    }
+
+    fn if_let(
+        &mut self,
+        p: &Pattern,
+        v: &Expr,
+        then: &Block,
+        els: Option<&Expr>,
+        dst: Dst,
+        line: u32,
+    ) -> Type {
+        let mark = self.f.next;
+        let s = self.alloc();
+        let st = self.expr(v, Dst::To(s, None));
+        self.f.scopes.push(Vec::new());
+        let fails = self.pattern_test(p, s, &st, line);
+        let mut acc = None;
+        let t = self.block(then, dst);
+        self.join(&mut acc, t, line);
+        self.f.scopes.pop();
+        let jend = self.emit(Op::Jump { to: 0 });
+        let e = self.here();
+        for f in fails {
+            self.patch(f, e);
+        }
+        match els {
+            Some(els) => {
+                let want_owned = match dst {
+                    Dst::To(_, w) => w.cloned().or_else(|| acc.clone().filter(|t| *t != Type::Never)),
+                    _ => None,
+                };
+                let d = match dst {
+                    Dst::To(r, _) => Dst::To(r, want_owned.as_ref()),
+                    d => d,
+                };
+                let t = self.expr(els, d);
+                if matches!(dst, Dst::To(..)) {
+                    self.join(&mut acc, t, line);
+                }
+            }
+            None => {
+                if let Dst::To(r, _) = dst {
+                    if acc
+                        .as_ref()
+                        .is_some_and(|t| *t != Type::Unit && *t != Type::Never)
+                    {
+                        self.error(line, "an `if let` that gives a value needs an `else`");
+                    }
+                    self.emit(Op::LoadUnit { dst: r });
+                }
+            }
+        }
+        let end = self.here();
+        self.patch(jend, end);
+        self.f.next = mark;
+        if matches!(dst, Dst::Discard) {
+            Type::Unit
+        } else {
+            acc.unwrap_or(Type::Unit)
+        }
+    }
+
+    /// Emit the test of `p` against the value in `s`, binding its names in the
+    /// current scope. Returns the jumps taken when it does not match.
+    fn pattern_test(&mut self, p: &Pattern, s: Reg, st: &Type, line: u32) -> Vec<usize> {
+        let mut fails = Vec::new();
+        match p {
+            Pattern::Wild => {}
+            Pattern::Bind(n) => {
+                let r = self.alloc();
+                self.emit(Op::Move { dst: r, src: s });
+                self.f.scopes.last_mut().unwrap().push(Local {
+                    name: n.clone(),
+                    reg: r,
+                    ty: st.clone(),
+                    mutable: false,
+                });
+            }
+            Pattern::Int(i) => {
+                self.expect(&Type::Int, st, line);
+                let k = self.konst(Value::Int(*i));
+                let (kr, c) = (self.alloc(), self.alloc());
+                self.emit(Op::LoadK { dst: kr, k });
+                self.emit(Op::EqI { dst: c, a: s, b: kr });
+                fails.push(self.emit(Op::JumpIfFalse { cond: c, to: 0 }));
+            }
+            Pattern::Bool(b) => {
+                self.expect(&Type::Bool, st, line);
+                let (kr, c) = (self.alloc(), self.alloc());
+                self.emit(Op::LoadBool { dst: kr, v: *b });
+                self.emit(Op::EqB { dst: c, a: s, b: kr });
+                fails.push(self.emit(Op::JumpIfFalse { cond: c, to: 0 }));
+            }
+            Pattern::Str(text) => {
+                self.expect(&Type::Str, st, line);
+                let k = self.string(text);
+                let (kr, c) = (self.alloc(), self.alloc());
+                self.emit(Op::LoadK { dst: kr, k });
+                self.emit(Op::EqS { dst: c, a: s, b: kr });
+                fails.push(self.emit(Op::JumpIfFalse { cond: c, to: 0 }));
+            }
+            Pattern::Variant(name, binds, vline) => {
+                let (tag, payload): (u32, Vec<Type>) = match (name.as_str(), st) {
+                    ("Some", Type::Option(t)) => (OPTION_SOME, vec![(**t).clone()]),
+                    ("None", Type::Option(_)) => (OPTION_NONE, vec![]),
+                    (_, Type::Enum(e)) => match self.variants.get(name) {
+                        Some(&(ve, tag)) if ve == *e => {
+                            (tag, self.enums[ve as usize].variants[tag as usize].1.clone())
+                        }
+                        _ => {
+                            let en = self.enums[*e as usize].name.clone();
+                            self.error(*vline, format!("`{name}` is not a variant of {en}"));
+                            return fails;
+                        }
+                    },
+                    (_, Type::Error) => return fails,
+                    _ => {
+                        let t = self.show(st);
+                        self.error(*vline, format!("`{name}` cannot match a value of type {t}"));
+                        return fails;
+                    }
+                };
+                if binds.len() != payload.len() {
+                    self.error(
+                        *vline,
+                        format!("`{name}` carries {} value(s), not {}", payload.len(), binds.len()),
+                    );
+                    return fails;
+                }
+                let k = self.konst(Value::Int(tag as i64));
+                let (tr, kr, c) = (self.alloc(), self.alloc(), self.alloc());
+                self.emit(Op::GetTag { dst: tr, src: s });
+                self.emit(Op::LoadK { dst: kr, k });
+                self.emit(Op::EqI { dst: c, a: tr, b: kr });
+                fails.push(self.emit(Op::JumpIfFalse { cond: c, to: 0 }));
+                for (i, (b, t)) in binds.iter().zip(payload).enumerate() {
+                    if b == "_" {
+                        continue;
+                    }
+                    let r = self.alloc();
+                    self.emit(Op::GetPayload {
+                        dst: r,
+                        src: s,
+                        idx: i as u16,
+                    });
+                    self.f.scopes.last_mut().unwrap().push(Local {
+                        name: b.clone(),
+                        reg: r,
+                        ty: t,
+                        mutable: false,
+                    });
+                }
+            }
+        }
+        fails
+    }
+
+    fn match_expr(&mut self, scrut: &Expr, arms: &[Arm], dst: Dst, line: u32) -> Type {
+        let mark = self.f.next;
+        let s = self.alloc();
+        let st = self.expr(scrut, Dst::To(s, None));
+        let mut acc: Option<Type> = None;
+        let mut ends = Vec::new();
+        let mut covered: Vec<u32> = Vec::new();
+        let mut total = false;
+        for arm in arms {
+            if total {
+                self.error(
+                    arm.body.line,
+                    "this arm is never reached: an earlier one matches everything",
+                );
+            }
+            self.f.scopes.push(Vec::new());
+            let arm_mark = self.f.next;
+            let fails = self.pattern_test(&arm.pattern, s, &st, line);
+            match &arm.pattern {
+                Pattern::Wild | Pattern::Bind(_) => total = true,
+                Pattern::Variant(n, binds, _) => {
+                    let tag = match n.as_str() {
+                        "Some" => Some(OPTION_SOME),
+                        "None" => Some(OPTION_NONE),
+                        _ => self.variants.get(n).map(|v| v.1),
+                    };
+                    // `Some(x)` covers Some; a nested pattern would not, but there are none yet.
+                    let _ = binds;
+                    if let Some(t) = tag {
+                        covered.push(t);
+                    }
+                }
+                _ => {}
+            }
+            let want_owned = match dst {
+                Dst::To(_, w) => w.cloned().or_else(|| acc.clone().filter(|t| *t != Type::Never)),
+                _ => None,
+            };
+            let d = match dst {
+                Dst::To(r, _) => Dst::To(r, want_owned.as_ref()),
+                d => d,
+            };
+            let t = self.expr(&arm.body, d);
+            if matches!(dst, Dst::To(..)) {
+                self.join(&mut acc, t, arm.body.line);
+            }
+            ends.push(self.emit(Op::Jump { to: 0 }));
+            let next = self.here();
+            for f in fails {
+                self.patch(f, next);
+            }
+            self.f.scopes.pop();
+            self.f.next = arm_mark;
+        }
+        let variants: Option<usize> = match &st {
+            Type::Option(_) => Some(2),
+            Type::Enum(e) => Some(self.enums[*e as usize].variants.len()),
+            _ => None,
+        };
+        let exhaustive = total
+            || variants.is_some_and(|n| (0..n as u32).all(|t| covered.contains(&t)))
+            || st == Type::Error;
+        if !exhaustive {
+            let missing = match &st {
+                Type::Option(_) => ["None", "Some(_)"]
+                    .iter()
+                    .enumerate()
+                    .filter(|(t, _)| !covered.contains(&(*t as u32)))
+                    .map(|(_, n)| n.to_string())
+                    .collect::<Vec<_>>(),
+                Type::Enum(e) => self.enums[*e as usize]
+                    .variants
+                    .iter()
+                    .enumerate()
+                    .filter(|(t, _)| !covered.contains(&(*t as u32)))
+                    .map(|(_, (n, _))| n.clone())
+                    .collect(),
+                _ => vec!["_".into()],
+            };
+            self.error(line, format!("this `match` misses: {}", missing.join(", ")));
+        }
+        let k = self.string("no arm of the match fits");
+        let Value::Static(m) = self.out.consts[k as usize] else {
+            unreachable!()
+        };
+        self.emit(Op::Panic { msg: m });
+        let end = self.here();
+        for j in ends {
+            self.patch(j, end);
+        }
+        self.f.next = mark;
+        if matches!(dst, Dst::Discard) {
+            Type::Unit
+        } else {
+            acc.unwrap_or(Type::Never)
+        }
+    }
+}
diff --git a/crates/frits/src/lexer.rs b/crates/frits/src/lexer.rs
new file mode 100644
index 0000000..5c05747
--- /dev/null
+++ b/crates/frits/src/lexer.rs
@@ -0,0 +1,302 @@
+//! Source text to tokens.
+//!
+//! Statements end at a newline when the line's last token could end one (Go's
+//! rule), so scripts need no semicolons. A consequence worth knowing: a binary
+//! operator that continues an expression goes at the *end* of the line, and
+//! `} else {` stays on one line.
+
+use crate::Error;
+
+#[derive(Clone, Debug, PartialEq)]
+pub enum Tok {
+    Ident(String),
+    Int(i64),
+    Float(f64),
+    /// A string literal, split at its `{…}` holes.
+    Str(Vec<StrPart>),
+    Kw(Kw),
+    Sym(&'static str),
+    /// A statement end: `;`, or a newline after a token that can end one.
+    Semi,
+    Eof,
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub enum StrPart {
+    Lit(String),
+    /// The hole's source, its line, and the format after a `:` (`.1` → one decimal).
+    Hole(String, u32, Option<String>),
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Kw {
+    Fn,
+    Let,
+    Var,
+    If,
+    Else,
+    While,
+    For,
+    In,
+    Match,
+    Return,
+    Break,
+    Continue,
+    Enum,
+    Type,
+    Script,
+    On,
+    True,
+    False,
+    Effect,
+    Event,
+    Module,
+}
+
+#[derive(Clone, Debug)]
+pub struct Token {
+    pub tok: Tok,
+    pub line: u32,
+}
+
+const SYMS: [&str; 32] = [
+    "..", "=>", "->", "==", "!=", "<=", ">=", "&&", "||", "+=", "-=", "*=", "/=", "(", ")", "{", "}", "[",
+    "]", ",", ".", ":", "=", "<", ">", "+", "-", "*", "/", "%", "!", "_",
+];
+
+fn keyword(s: &str) -> Option<Kw> {
+    Some(match s {
+        "fn" => Kw::Fn,
+        "let" => Kw::Let,
+        "var" => Kw::Var,
+        "if" => Kw::If,
+        "else" => Kw::Else,
+        "while" => Kw::While,
+        "for" => Kw::For,
+        "in" => Kw::In,
+        "match" => Kw::Match,
+        "return" => Kw::Return,
+        "break" => Kw::Break,
+        "continue" => Kw::Continue,
+        "enum" => Kw::Enum,
+        "type" => Kw::Type,
+        "script" => Kw::Script,
+        "on" => Kw::On,
+        "true" => Kw::True,
+        "false" => Kw::False,
+        "effect" => Kw::Effect,
+        "event" => Kw::Event,
+        "module" => Kw::Module,
+        _ => return None,
+    })
+}
+
+fn ends_statement(t: &Tok) -> bool {
+    match t {
+        Tok::Ident(_) | Tok::Int(_) | Tok::Float(_) | Tok::Str(_) => true,
+        Tok::Kw(k) => matches!(k, Kw::Return | Kw::Break | Kw::Continue | Kw::True | Kw::False),
+        Tok::Sym(s) => matches!(*s, ")" | "]" | "}" | "_" | "?"),
+        _ => false,
+    }
+}
+
+pub fn lex(src: &str, first_line: u32) -> Result<Vec<Token>, Error> {
+    let b = src.as_bytes();
+    let mut out: Vec<Token> = Vec::new();
+    let mut i = 0;
+    let mut line = first_line;
+    // Inside `(` and `[` a newline never ends a statement.
+    let mut depth: Vec<u8> = Vec::new();
+    let push = |out: &mut Vec<Token>, tok: Tok, line: u32| out.push(Token { tok, line });
+    while i < b.len() {
+        let c = b[i];
+        if c == b'\n' {
+            let open = matches!(depth.last(), Some(b'(') | Some(b'['));
+            if !open && out.last().is_some_and(|t| ends_statement(&t.tok)) {
+                push(&mut out, Tok::Semi, line);
+            }
+            line += 1;
+            i += 1;
+            continue;
+        }
+        if c.is_ascii_whitespace() {
+            i += 1;
+            continue;
+        }
+        if c == b'/' && b.get(i + 1) == Some(&b'/') {
+            while i < b.len() && b[i] != b'\n' {
+                i += 1;
+            }
+            continue;
+        }
+        if c == b';' {
+            push(&mut out, Tok::Semi, line);
+            i += 1;
+            continue;
+        }
+        if c.is_ascii_alphabetic() || (c == b'_' && b.get(i + 1).is_some_and(|n| n.is_ascii_alphanumeric())) {
+            let s = i;
+            while i < b.len() && (b[i].is_ascii_alphanumeric() || b[i] == b'_') {
+                i += 1;
+            }
+            let word = &src[s..i];
+            let tok = keyword(word)
+                .map(Tok::Kw)
+                .unwrap_or_else(|| Tok::Ident(word.to_string()));
+            push(&mut out, tok, line);
+            continue;
+        }
+        if c.is_ascii_digit() {
+            let s = i;
+            let mut float = false;
+            while i < b.len() && (b[i].is_ascii_digit() || b[i] == b'_') {
+                i += 1;
+            }
+            // `0..10` is a range, not the float `0.`.
+            if i < b.len() && b[i] == b'.' && b.get(i + 1).is_some_and(|n| n.is_ascii_digit()) {
+                float = true;
+                i += 1;
+                while i < b.len() && (b[i].is_ascii_digit() || b[i] == b'_') {
+                    i += 1;
+                }
+            }
+            if i < b.len() && (b[i] == b'e' || b[i] == b'E') {
+                let mut j = i + 1;
+                if j < b.len() && (b[j] == b'+' || b[j] == b'-') {
+                    j += 1;
+                }
+                if j < b.len() && b[j].is_ascii_digit() {
+                    float = true;
+                    i = j;
+                    while i < b.len() && b[i].is_ascii_digit() {
+                        i += 1;
+                    }
+                }
+            }
+            let text: String = src[s..i].chars().filter(|&c| c != '_').collect();
+            let tok = if float {
+                Tok::Float(
+                    text.parse()
+                        .map_err(|_| Error::new(line, format!("bad number `{text}`")))?,
+                )
+            } else {
+                Tok::Int(
+                    text.parse()
+                        .map_err(|_| Error::new(line, format!("integer `{text}` is too large")))?,
+                )
+            };
+            push(&mut out, tok, line);
+            continue;
+        }
+        if c == b'"' {
+            let start_line = line;
+            i += 1;
+            let mut parts = Vec::new();
+            let mut lit = String::new();
+            loop {
+                let Some(&ch) = b.get(i) else {
+                    return Err(Error::new(start_line, "string is never closed"));
+                };
+                match ch {
+                    b'"' => {
+                        i += 1;
+                        break;
+                    }
+                    b'\\' => {
+                        let esc = b.get(i + 1).copied().unwrap_or(b'\\');
+                        lit.push(match esc {
+                            b'n' => '\n',
+                            b't' => '\t',
+                            b'"' => '"',
+                            b'\\' => '\\',
+                            b'{' => '{',
+                            b'}' => '}',
+                            _ => return Err(Error::new(line, format!("unknown escape `\\{}`", esc as char))),
+                        });
+                        i += 2;
+                    }
+                    b'{' => {
+                        if !lit.is_empty() {
+                            parts.push(StrPart::Lit(std::mem::take(&mut lit)));
+                        }
+                        let hole_line = line;
+                        i += 1;
+                        let s = i;
+                        let mut nest = 0;
+                        while i < b.len() && !(b[i] == b'}' && nest == 0) {
+                            match b[i] {
+                                b'{' => nest += 1,
+                                b'}' => nest -= 1,
+                                b'\n' => line += 1,
+                                b'"' => {
+                                    return Err(Error::new(line, "a string inside `{…}` is not supported"));
+                                }
+                                _ => {}
+                            }
+                            i += 1;
+                        }
+                        if i >= b.len() {
+                            return Err(Error::new(
+                                hole_line,
+                                "`{` in a string is never closed (write `\\{` for a brace)",
+                            ));
+                        }
+                        let inner = &src[s..i];
+                        i += 1;
+                        let (expr, fmt) = match inner.rfind(':') {
+                            Some(k) if inner[k + 1..].trim_start().starts_with('.') => {
+                                (inner[..k].to_string(), Some(inner[k + 1..].trim().to_string()))
+                            }
+                            _ => (inner.to_string(), None),
+                        };
+                        parts.push(StrPart::Hole(expr, hole_line, fmt));
+                    }
+                    _ => {
+                        if ch == b'\n' {
+                            line += 1;
+                        }
+                        // Copy one whole UTF-8 character.
+                        let len = utf8_len(ch);
+                        lit.push_str(&src[i..i + len]);
+                        i += len;
+                    }
+                }
+            }
+            if !lit.is_empty() || parts.is_empty() {
+                parts.push(StrPart::Lit(lit));
+            }
+            push(&mut out, Tok::Str(parts), start_line);
+            continue;
+        }
+        let rest = &src[i..];
+        let Some(sym) = SYMS.iter().find(|s| rest.starts_with(**s)) else {
+            return Err(Error::new(
+                line,
+                format!("unexpected character `{}`", rest.chars().next().unwrap()),
+            ));
+        };
+        match *sym {
+            "(" | "[" | "{" => depth.push(sym.as_bytes()[0]),
+            ")" | "]" | "}" => {
+                depth.pop();
+            }
+            _ => {}
+        }
+        push(&mut out, Tok::Sym(sym), line);
+        i += sym.len();
+    }
+    if out.last().is_some_and(|t| ends_statement(&t.tok)) {
+        push(&mut out, Tok::Semi, line);
+    }
+    push(&mut out, Tok::Eof, line);
+    Ok(out)
+}
+
+fn utf8_len(first: u8) -> usize {
+    match first {
+        0xF0..=0xFF => 4,
+        0xE0..=0xEF => 3,
+        0xC0..=0xDF => 2,
+        _ => 1,
+    }
+}
diff --git a/crates/frits/src/lib.rs b/crates/frits/src/lib.rs
new file mode 100644
index 0000000..9aa59e3
--- /dev/null
+++ b/crates/frits/src/lib.rs
@@ -0,0 +1,53 @@
+//! Frits: Pinnacle's scripting language.
+//!
+//! Source compiles against a [`Platform`] into typed bytecode ([`compile`]); a
+//! [`Runtime`] runs it as many small processes, each with its own heap and a
+//! fuel slice per tick. The VM is safe Rust: a bug in it is a wrong answer or
+//! a stopped script, never a memory error.
+#![forbid(unsafe_code)]
+
+pub mod ast;
+pub mod bytecode;
+pub mod compile;
+pub mod lexer;
+pub mod parser;
+pub mod platform;
+pub mod prelude;
+pub mod runtime;
+pub mod types;
+pub mod value;
+pub mod vm;
+
+#[cfg(test)]
+mod tests;
+
+pub use platform::{Cx, HostFn, Platform};
+pub use runtime::{Limits, Pid, Runtime};
+pub use value::{HostValue, Value};
+pub use vm::{Outcome, Process, Status};
+
+/// A mistake in a script, with the line it is on.
+#[derive(Clone, Debug, PartialEq)]
+pub struct Error {
+    pub line: u32,
+    pub msg: String,
+}
+
+impl Error {
+    pub fn new(line: u32, msg: impl Into<String>) -> Self {
+        Error {
+            line,
+            msg: msg.into(),
+        }
+    }
+}
+
+impl std::fmt::Display for Error {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        if self.line == 0 {
+            write!(f, "{}", self.msg)
+        } else {
+            write!(f, "line {}: {}", self.line, self.msg)
+        }
+    }
+}
diff --git a/crates/frits/src/main.rs b/crates/frits/src/main.rs
new file mode 100644
index 0000000..3d01be7
--- /dev/null
+++ b/crates/frits/src/main.rs
@@ -0,0 +1,53 @@
+//! `frits run <file>`: run a script on the console platform.
+
+use frits::{Cx, Platform, Runtime, Status, Value};
+
+const CONSOLE: &str = "
+effect Console {
+    fn print(text: Str)
+}
+event main()
+";
+
+fn console() -> Platform<()> {
+    let mut p = Platform::new(CONSOLE).expect("the console declaration parses");
+    p.bind("Console.print", |cx: &mut Cx<()>, a| {
+        println!("{}", cx.str(a[0]));
+        Ok(Value::Unit)
+    });
+    p
+}
+
+fn main() {
+    let args: Vec<String> = std::env::args().collect();
+    let (Some("run"), Some(path)) = (args.get(1).map(|s| s.as_str()), args.get(2)) else {
+        eprintln!("usage: frits run <file.frits>");
+        std::process::exit(2);
+    };
+    let src = std::fs::read_to_string(path).unwrap_or_else(|e| {
+        eprintln!("{path}: {e}");
+        std::process::exit(2);
+    });
+    let mut rt = Runtime::new(console());
+    let module = match rt.platform.compile(&src) {
+        Ok(m) => m,
+        Err(errs) => {
+            for e in errs {
+                eprintln!("{path}:{e}");
+            }
+            std::process::exit(1);
+        }
+    };
+    let pid = rt.spawn(module, ());
+    rt.post(pid, "main", Vec::new());
+    loop {
+        if let Some((_, msg)) = rt.tick().into_iter().next() {
+            eprintln!("{path}: {msg}");
+            std::process::exit(1);
+        }
+        match rt.get(pid).map(|p| (&p.status, p.has_work())) {
+            Some((Status::Idle, false)) | None => break,
+            _ => {}
+        }
+    }
+}
diff --git a/crates/frits/src/parser.rs b/crates/frits/src/parser.rs
new file mode 100644
index 0000000..823895b
--- /dev/null
+++ b/crates/frits/src/parser.rs
@@ -0,0 +1,750 @@
+//! Tokens to the syntax tree.
+
+use crate::Error;
+use crate::ast::*;
+use crate::lexer::{Kw, StrPart, Tok, Token, lex};
+
+pub fn parse(src: &str) -> Result<Module, Error> {
+    let toks = lex(src, 1)?;
+    let mut p = Parser { toks, pos: 0 };
+    p.module()
+}
+
+struct Parser {
+    toks: Vec<Token>,
+    pos: usize,
+}
+
+type R<T> = Result<T, Error>;
+
+impl Parser {
+    fn peek(&self) -> &Tok {
+        &self.toks[self.pos].tok
+    }
+
+    fn peek_at(&self, n: usize) -> &Tok {
+        &self.toks[(self.pos + n).min(self.toks.len() - 1)].tok
+    }
+
+    fn line(&self) -> u32 {
+        self.toks[self.pos].line
+    }
+
+    fn next(&mut self) -> Tok {
+        let t = self.toks[self.pos].tok.clone();
+        if self.pos < self.toks.len() - 1 {
+            self.pos += 1;
+        }
+        t
+    }
+
+    fn err<T>(&self, msg: impl Into<String>) -> R<T> {
+        Err(Error::new(self.line(), msg))
+    }
+
+    fn is_sym(&self, s: &str) -> bool {
+        matches!(self.peek(), Tok::Sym(x) if *x == s)
+    }
+
+    fn is_kw(&self, k: Kw) -> bool {
+        matches!(self.peek(), Tok::Kw(x) if *x == k)
+    }
+
+    fn eat_sym(&mut self, s: &str) -> bool {
+        if self.is_sym(s) {
+            self.next();
+            true
+        } else {
+            false
+        }
+    }
+
+    fn eat_kw(&mut self, k: Kw) -> bool {
+        if self.is_kw(k) {
+            self.next();
+            true
+        } else {
+            false
+        }
+    }
+
+    fn expect_sym(&mut self, s: &str) -> R<()> {
+        if self.eat_sym(s) {
+            Ok(())
+        } else {
+            self.err(format!("expected `{s}`, found {}", describe(self.peek())))
+        }
+    }
+
+    fn ident(&mut self) -> R<Name> {
+        match self.next() {
+            Tok::Ident(s) => Ok(s),
+            t => {
+                self.pos -= 1;
+                self.err(format!("expected a name, found {}", describe(&t)))
+            }
+        }
+    }
+
+    fn skip_semis(&mut self) {
+        while matches!(self.peek(), Tok::Semi) {
+            self.next();
+        }
+    }
+
+    fn end_stmt(&mut self) -> R<()> {
+        match self.peek() {
+            Tok::Semi => {
+                self.skip_semis();
+                Ok(())
+            }
+            Tok::Eof => Ok(()),
+            Tok::Sym("}") => Ok(()),
+            t => self.err(format!(
+                "expected the end of the statement, found {}",
+                describe(t)
+            )),
+        }
+    }
+
+    // ── Items ──
+
+    fn module(&mut self) -> R<Module> {
+        let mut m = Module::default();
+        self.skip_semis();
+        while !matches!(self.peek(), Tok::Eof) {
+            let line = self.line();
+            match self.peek().clone() {
+                Tok::Kw(Kw::Script) => {
+                    self.next();
+                    if self.eat_sym("/") {
+                        m.effects = self.name_list()?;
+                    }
+                }
+                Tok::Kw(Kw::Fn) => {
+                    self.next();
+                    m.items.push(Item::Fn(self.fn_decl(true)?));
+                }
+                Tok::Kw(Kw::On) => {
+                    self.next();
+                    m.items.push(Item::On(self.fn_decl(true)?));
+                }
+                Tok::Kw(Kw::Event) => {
+                    self.next();
+                    m.items.push(Item::Event(self.fn_decl(false)?));
+                }
+                Tok::Kw(Kw::Enum) => {
+                    self.next();
+                    m.items.push(Item::Enum(self.enum_decl(line)?));
+                }
+                Tok::Kw(Kw::Type) => {
+                    self.next();
+                    let name = self.ident()?;
+                    self.expect_sym("=")?;
+                    let ty = self.type_expr()?;
+                    m.items.push(Item::Type(name, ty, line));
+                }
+                Tok::Kw(k @ (Kw::Let | Kw::Var)) => {
+                    self.next();
+                    let name = self.ident()?;
+                    let ty = if self.eat_sym(":") {
+                        Some(self.type_expr()?)
+                    } else {
+                        None
+                    };
+                    self.expect_sym("=")?;
+                    let value = self.expr()?;
+                    m.items.push(Item::Global(Global {
+                        mutable: k == Kw::Var,
+                        name,
+                        ty,
+                        value,
+                        line,
+                    }));
+                }
+                Tok::Kw(k @ (Kw::Effect | Kw::Module)) => {
+                    self.next();
+                    m.items.push(Item::Namespace(self.namespace(k == Kw::Effect)?));
+                }
+                t => {
+                    return self.err(format!(
+                        "expected `fn`, `on`, `let`, `var`, `enum` or `type`, found {}",
+                        describe(&t)
+                    ));
+                }
+            }
+            self.end_stmt()?;
+        }
+        Ok(m)
+    }
+
+    fn name_list(&mut self) -> R<Vec<Name>> {
+        let mut v = vec![self.ident()?];
+        while self.eat_sym(",") {
+            v.push(self.ident()?);
+        }
+        Ok(v)
+    }
+
+    fn fn_decl(&mut self, body: bool) -> R<FnDecl> {
+        let line = self.line();
+        let name = self.ident()?;
+        self.expect_sym("(")?;
+        let mut params = Vec::new();
+        while !self.is_sym(")") {
+            let p = self.ident()?;
+            self.expect_sym(":")?;
+            params.push((p, self.type_expr()?));
+            if !self.eat_sym(",") {
+                break;
+            }
+        }
+        self.expect_sym(")")?;
+        let ret = if self.eat_sym("->") {
+            Some(self.type_expr()?)
+        } else {
+            None
+        };
+        let effects = if self.eat_sym("/") {
+            self.name_list()?
+        } else {
+            Vec::new()
+        };
+        let body = if body { Some(self.block()?) } else { None };
+        Ok(FnDecl {
+            name,
+            params,
+            ret,
+            effects,
+            body,
+            line,
+        })
+    }
+
+    fn enum_decl(&mut self, line: u32) -> R<EnumDecl> {
+        let name = self.ident()?;
+        self.expect_sym("{")?;
+        let mut variants = Vec::new();
+        loop {
+            self.skip_semis();
+            if self.eat_sym("}") {
+                break;
+            }
+            let v = self.ident()?;
+            let mut payload = Vec::new();
+            if self.eat_sym("(") {
+                while !self.is_sym(")") {
+                    payload.push(self.type_expr()?);
+                    if !self.eat_sym(",") {
+                        break;
+                    }
+                }
+                self.expect_sym(")")?;
+            }
+            variants.push((v, payload));
+            self.skip_semis();
+            if !self.eat_sym(",") {
+                self.skip_semis();
+                self.expect_sym("}")?;
+                break;
+            }
+        }
+        Ok(EnumDecl { name, variants, line })
+    }
+
+    fn namespace(&mut self, effect: bool) -> R<Namespace> {
+        let name = self.ident()?;
+        self.expect_sym("{")?;
+        let mut ns = Namespace {
+            name,
+            effect,
+            fns: Vec::new(),
+            consts: Vec::new(),
+        };
+        loop {
+            self.skip_semis();
+            if self.eat_sym("}") {
+                break;
+            }
+            let line = self.line();
+            if self.eat_kw(Kw::Fn) {
+                ns.fns.push(self.fn_decl(false)?);
+            } else if self.eat_kw(Kw::Let) {
+                let n = self.ident()?;
+                self.expect_sym(":")?;
+                ns.consts.push((n, self.type_expr()?, line));
+            } else {
+                return self.err("expected `fn` or `let` in a platform declaration");
+            }
+            self.end_stmt()?;
+        }
+        Ok(ns)
+    }
+
+    fn type_expr(&mut self) -> R<TypeExpr> {
+        let line = self.line();
+        if self.eat_sym("{") {
+            let mut fields = Vec::new();
+            loop {
+                self.skip_semis();
+                if self.eat_sym("}") {
+                    break;
+                }
+                let f = self.ident()?;
+                self.expect_sym(":")?;
+                fields.push((f, self.type_expr()?));
+                self.skip_semis();
+                if !self.eat_sym(",") {
+                    self.skip_semis();
+                    self.expect_sym("}")?;
+                    break;
+                }
+            }
+            return Ok(TypeExpr::Record(fields, line));
+        }
+        let name = self.ident()?;
+        let mut args = Vec::new();
+        if self.eat_sym("<") {
+            loop {
+                args.push(self.type_expr()?);
+                if !self.eat_sym(",") {
+                    break;
+                }
+            }
+            self.expect_sym(">")?;
+        }
+        Ok(TypeExpr::Named(name, args, line))
+    }
+
+    // ── Statements ──
+
+    fn block(&mut self) -> R<Block> {
+        self.expect_sym("{")?;
+        let mut b = Block::default();
+        loop {
+            self.skip_semis();
+            if self.eat_sym("}") {
+                break;
+            }
+            if matches!(self.peek(), Tok::Eof) {
+                return self.err("block is never closed: expected `}`");
+            }
+            let s = self.stmt()?;
+            b.stmts.push(s);
+            self.end_stmt()?;
+        }
+        // The block's value is its last statement, when that is an expression: a
+        // newline cannot tell `x` from `x;` the way Rust's `;` does.
+        if matches!(b.stmts.last(), Some(Stmt::Expr(_))) {
+            let Some(Stmt::Expr(e)) = b.stmts.pop() else {
+                unreachable!()
+            };
+            b.tail = Some(Box::new(e));
+        }
+        Ok(b)
+    }
+
+    fn stmt(&mut self) -> R<Stmt> {
+        let line = self.line();
+        match self.peek().clone() {
+            Tok::Kw(k @ (Kw::Let | Kw::Var)) => {
+                self.next();
+                let name = self.ident()?;
+                let ty = if self.eat_sym(":") {
+                    Some(self.type_expr()?)
+                } else {
+                    None
+                };
+                self.expect_sym("=")?;
+                let value = self.expr()?;
+                Ok(Stmt::Let {
+                    mutable: k == Kw::Var,
+                    name,
+                    ty,
+                    value,
+                    line,
+                })
+            }
+            Tok::Kw(Kw::While) => {
+                self.next();
+                let cond = self.expr()?;
+                let body = self.block()?;
+                Ok(Stmt::While { cond, body, line })
+            }
+            Tok::Kw(Kw::For) => {
+                self.next();
+                let var = self.ident()?;
+                if !self.eat_kw(Kw::In) {
+                    return self.err("expected `in`");
+                }
+                let first = self.expr()?;
+                let iter = if self.eat_sym("..") {
+                    ForIter::Range(first, self.expr()?)
+                } else {
+                    ForIter::List(first)
+                };
+                let body = self.block()?;
+                Ok(Stmt::For {
+                    var,
+                    iter,
+                    body,
+                    line,
+                })
+            }
+            Tok::Kw(Kw::Return) => {
+                self.next();
+                let v = if matches!(self.peek(), Tok::Semi | Tok::Sym("}") | Tok::Eof) {
+                    None
+                } else {
+                    Some(self.expr()?)
+                };
+                Ok(Stmt::Return(v, line))
+            }
+            Tok::Kw(Kw::Break) => {
+                self.next();
+                Ok(Stmt::Break(line))
+            }
+            Tok::Kw(Kw::Continue) => {
+                self.next();
+                Ok(Stmt::Continue(line))
+            }
+            _ => {
+                let e = self.expr()?;
+                let op = match self.peek() {
+                    Tok::Sym("=") => None,
+                    Tok::Sym("+=") => Some(BinOp::Add),
+                    Tok::Sym("-=") => Some(BinOp::Sub),
+                    Tok::Sym("*=") => Some(BinOp::Mul),
+                    Tok::Sym("/=") => Some(BinOp::Div),
+                    _ => return Ok(Stmt::Expr(e)),
+                };
+                self.next();
+                let value = self.expr()?;
+                Ok(Stmt::Assign {
+                    target: e,
+                    op,
+                    value,
+                    line,
+                })
+            }
+        }
+    }
+
+    // ── Expressions ──
+
+    pub fn expr(&mut self) -> R<Expr> {
+        self.binary(0)
+    }
+
+    fn binary(&mut self, min: u8) -> R<Expr> {
+        let mut lhs = self.unary()?;
+        loop {
+            let (op, prec) = match self.peek() {
+                Tok::Sym("||") => (BinOp::Or, 1),
+                Tok::Sym("&&") => (BinOp::And, 2),
+                Tok::Sym("==") => (BinOp::Eq, 3),
+                Tok::Sym("!=") => (BinOp::Ne, 3),
+                Tok::Sym("<") => (BinOp::Lt, 4),
+                Tok::Sym("<=") => (BinOp::Le, 4),
+                Tok::Sym(">") => (BinOp::Gt, 4),
+                Tok::Sym(">=") => (BinOp::Ge, 4),
+                Tok::Sym("+") => (BinOp::Add, 5),
+                Tok::Sym("-") => (BinOp::Sub, 5),
+                Tok::Sym("*") => (BinOp::Mul, 6),
+                Tok::Sym("/") => (BinOp::Div, 6),
+                Tok::Sym("%") => (BinOp::Rem, 6),
+                _ => break,
+            };
+            if prec < min {
+                break;
+            }
+            let line = self.line();
+            self.next();
+            // An operator at the end of a line continues on the next.
+            self.skip_semis();
+            let rhs = self.binary(prec + 1)?;
+            lhs = Expr {
+                kind: ExprKind::Binary(op, Box::new(lhs), Box::new(rhs)),
+                line,
+            };
+        }
+        Ok(lhs)
+    }
+
+    fn unary(&mut self) -> R<Expr> {
+        let line = self.line();
+        if self.eat_sym("-") {
+            let e = self.unary()?;
+            return Ok(match e.kind {
+                ExprKind::Int(i) => Expr {
+                    kind: ExprKind::Int(-i),
+                    line,
+                },
+                ExprKind::Float(f) => Expr {
+                    kind: ExprKind::Float(-f),
+                    line,
+                },
+                _ => Expr {
+                    kind: ExprKind::Unary(UnOp::Neg, Box::new(e)),
+                    line,
+                },
+            });
+        }
+        if self.eat_sym("!") {
+            let e = self.unary()?;
+            return Ok(Expr {
+                kind: ExprKind::Unary(UnOp::Not, Box::new(e)),
+                line,
+            });
+        }
+        self.postfix()
+    }
+
+    fn postfix(&mut self) -> R<Expr> {
+        let mut e = self.primary()?;
+        loop {
+            let line = self.line();
+            if self.eat_sym("(") {
+                let mut args = Vec::new();
+                while !self.is_sym(")") {
+                    args.push(self.expr()?);
+                    if !self.eat_sym(",") {
+                        break;
+                    }
+                }
+                self.expect_sym(")")?;
+                e = Expr {
+                    kind: ExprKind::Call(Box::new(e), args),
+                    line,
+                };
+            } else if self.eat_sym(".") {
+                let f = self.ident()?;
+                e = Expr {
+                    kind: ExprKind::Field(Box::new(e), f),
+                    line,
+                };
+            } else if self.eat_sym("[") {
+                let i = self.expr()?;
+                self.expect_sym("]")?;
+                e = Expr {
+                    kind: ExprKind::Index(Box::new(e), Box::new(i)),
+                    line,
+                };
+            } else {
+                break;
+            }
+        }
+        Ok(e)
+    }
+
+    /// `{` starts a record when a `name:` or `..` follows; otherwise a block.
+    fn starts_record(&self) -> bool {
+        let mut n = 1;
+        while matches!(self.peek_at(n), Tok::Semi) {
+            n += 1;
+        }
+        matches!(self.peek_at(n), Tok::Sym(".."))
+            || (matches!(self.peek_at(n), Tok::Ident(_)) && matches!(self.peek_at(n + 1), Tok::Sym(":")))
+    }
+
+    fn primary(&mut self) -> R<Expr> {
+        let line = self.line();
+        let kind = match self.next() {
+            Tok::Int(i) => ExprKind::Int(i),
+            Tok::Float(f) => ExprKind::Float(f),
+            Tok::Kw(Kw::True) => ExprKind::Bool(true),
+            Tok::Kw(Kw::False) => ExprKind::Bool(false),
+            Tok::Str(parts) => self.template(parts)?,
+            Tok::Ident(n) => ExprKind::Ident(n),
+            Tok::Sym("(") => {
+                let e = self.expr()?;
+                self.expect_sym(")")?;
+                return Ok(e);
+            }
+            Tok::Sym("[") => {
+                let mut items = Vec::new();
+                while !self.is_sym("]") {
+                    items.push(self.expr()?);
+                    if !self.eat_sym(",") {
+                        break;
+                    }
+                }
+                self.expect_sym("]")?;
+                ExprKind::List(items)
+            }
+            Tok::Sym("{") => {
+                self.pos -= 1;
+                if self.starts_record() {
+                    return self.record();
+                }
+                ExprKind::Block(self.block()?)
+            }
+            Tok::Kw(Kw::If) => return self.if_expr(line),
+            Tok::Kw(Kw::Match) => {
+                let scrut = self.expr()?;
+                self.expect_sym("{")?;
+                let mut arms = Vec::new();
+                loop {
+                    self.skip_semis();
+                    if self.eat_sym("}") {
+                        break;
+                    }
+                    let pattern = self.pattern()?;
+                    self.expect_sym("=>")?;
+                    let body = self.expr()?;
+                    arms.push(Arm { pattern, body });
+                    self.eat_sym(",");
+                }
+                ExprKind::Match(Box::new(scrut), arms)
+            }
+            t => {
+                self.pos -= 1;
+                return self.err(format!("expected an expression, found {}", describe(&t)));
+            }
+        };
+        Ok(Expr { kind, line })
+    }
+
+    fn if_expr(&mut self, line: u32) -> R<Expr> {
+        if self.eat_kw(Kw::Let) {
+            let pat = self.pattern()?;
+            self.expect_sym("=")?;
+            let value = self.expr()?;
+            let then = self.block()?;
+            let els = self.else_part()?;
+            return Ok(Expr {
+                kind: ExprKind::IfLet(pat, Box::new(value), then, els),
+                line,
+            });
+        }
+        let cond = self.expr()?;
+        let then = self.block()?;
+        let els = self.else_part()?;
+        Ok(Expr {
+            kind: ExprKind::If(Box::new(cond), then, els),
+            line,
+        })
+    }
+
+    fn else_part(&mut self) -> R<Option<Box<Expr>>> {
+        if !self.eat_kw(Kw::Else) {
+            return Ok(None);
+        }
+        let line = self.line();
+        if self.eat_kw(Kw::If) {
+            return Ok(Some(Box::new(self.if_expr(line)?)));
+        }
+        Ok(Some(Box::new(Expr {
+            kind: ExprKind::Block(self.block()?),
+            line,
+        })))
+    }
+
+    fn record(&mut self) -> R<Expr> {
+        let line = self.line();
+        self.expect_sym("{")?;
+        let mut fields = Vec::new();
+        let mut spread = None;
+        loop {
+            self.skip_semis();
+            if self.eat_sym("}") {
+                break;
+            }
+            if self.eat_sym("..") {
+                spread = Some(Box::new(self.expr()?));
+            } else {
+                let f = self.ident()?;
+                self.expect_sym(":")?;
+                self.skip_semis();
+                fields.push((f, self.expr()?));
+            }
+            self.skip_semis();
+            if !self.eat_sym(",") {
+                self.skip_semis();
+                self.expect_sym("}")?;
+                break;
+            }
+        }
+        Ok(Expr {
+            kind: ExprKind::Record(fields, spread),
+            line,
+        })
+    }
+
+    fn pattern(&mut self) -> R<Pattern> {
+        let line = self.line();
+        Ok(match self.next() {
+            Tok::Sym("_") => Pattern::Wild,
+            Tok::Int(i) => Pattern::Int(i),
+            Tok::Sym("-") => match self.next() {
+                Tok::Int(i) => Pattern::Int(-i),
+                _ => return self.err("expected a number after `-` in a pattern"),
+            },
+            Tok::Kw(Kw::True) => Pattern::Bool(true),
+            Tok::Kw(Kw::False) => Pattern::Bool(false),
+            Tok::Str(parts) => match parts.as_slice() {
+                [StrPart::Lit(s)] => Pattern::Str(s.clone()),
+                _ => return self.err("a pattern string cannot have `{…}` in it"),
+            },
+            Tok::Ident(n) if n.starts_with(|c: char| c.is_ascii_uppercase()) => {
+                let mut binds = Vec::new();
+                if self.eat_sym("(") {
+                    while !self.is_sym(")") {
+                        if self.eat_sym("_") {
+                            binds.push("_".to_string());
+                        } else {
+                            binds.push(self.ident()?);
+                        }
+                        if !self.eat_sym(",") {
+                            break;
+                        }
+                    }
+                    self.expect_sym(")")?;
+                }
+                Pattern::Variant(n, binds, line)
+            }
+            Tok::Ident(n) => Pattern::Bind(n),
+            t => {
+                self.pos -= 1;
+                return self.err(format!("expected a pattern, found {}", describe(&t)));
+            }
+        })
+    }
+
+    fn template(&mut self, parts: Vec<StrPart>) -> R<ExprKind> {
+        if let [StrPart::Lit(s)] = parts.as_slice() {
+            return Ok(ExprKind::Str(s.clone()));
+        }
+        let mut out = Vec::new();
+        for p in parts {
+            match p {
+                StrPart::Lit(s) => out.push(TPart::Lit(s)),
+                StrPart::Hole(src, line, fmt) => {
+                    let toks = lex(&src, line)?;
+                    let mut sub = Parser { toks, pos: 0 };
+                    sub.skip_semis();
+                    let e = sub.expr()?;
+                    sub.skip_semis();
+                    if !matches!(sub.peek(), Tok::Eof) {
+                        return sub.err("unexpected text after the expression in `{…}`");
+                    }
+                    out.push(TPart::Hole(e, fmt));
+                }
+            }
+        }
+        Ok(ExprKind::Template(out))
+    }
+}
+
+fn describe(t: &Tok) -> String {
+    match t {
+        Tok::Ident(s) => format!("`{s}`"),
+        Tok::Int(i) => format!("`{i}`"),
+        Tok::Float(f) => format!("`{f}`"),
+        Tok::Str(_) => "a string".into(),
+        Tok::Kw(k) => format!("`{}`", format!("{k:?}").to_lowercase()),
+        Tok::Sym(s) => format!("`{s}`"),
+        Tok::Semi => "the end of the line".into(),
+        Tok::Eof => "the end of the file".into(),
+    }
+}
diff --git a/crates/frits/src/platform.rs b/crates/frits/src/platform.rs
new file mode 100644
index 0000000..d4694aa
--- /dev/null
+++ b/crates/frits/src/platform.rs
@@ -0,0 +1,121 @@
+//! A platform: the effects, modules and events a host offers, declared in
+//! Frits and implemented in Rust.
+//!
+//! The same script runs on Pinnacle, in the Cartopolis simulator or on the web
+//! by being compiled against a different platform. What a script may touch is
+//! exactly what its platform declared and its `script / …` line asked for.
+
+use std::rc::Rc;
+
+use crate::Error;
+use crate::bytecode::Module;
+use crate::types::PlatformDecl;
+use crate::value::{Heap, HostValue, Obj, Value};
+
+/// A host function: reads its arguments, may change the process's host state,
+/// and returns a value or an error that stops the process.
+pub type HostFn<S> = fn(&mut Cx<S>, &[Value]) -> Result<Value, String>;
+
+/// What a host function can reach: the process's own state and heap.
+pub struct Cx<'a, S> {
+    pub state: &'a mut S,
+    pub heap: &'a mut Heap,
+    pub strings: &'a [Rc<str>],
+}
+
+impl<S> Cx<'_, S> {
+    pub fn str(&self, v: Value) -> &str {
+        self.heap.str(v, self.strings)
+    }
+
+    pub fn new_str(&mut self, s: &str) -> Value {
+        self.heap.alloc(Obj::Str(s.into()))
+    }
+
+    /// A record from its fields, given in name order.
+    pub fn record(&mut self, fields: &[Value]) -> Value {
+        self.heap.alloc(Obj::Record(fields.into()))
+    }
+
+    pub fn fields(&self, v: Value) -> &[Value] {
+        self.heap.fields(v)
+    }
+
+    pub fn some(&mut self, v: Value) -> Value {
+        self.heap.alloc(Obj::Variant(1, Box::new([v])))
+    }
+
+    pub fn none(&self) -> Value {
+        Value::Tag(0)
+    }
+
+    pub fn import(&mut self, h: &HostValue) -> Value {
+        self.heap.import(h)
+    }
+
+    pub fn export(&self, v: Value) -> HostValue {
+        self.heap.export(v, self.strings)
+    }
+}
+
+pub struct Platform<S> {
+    pub decl: PlatformDecl,
+    pub(crate) fns: Vec<Option<HostFn<S>>>,
+    pub(crate) consts: Vec<Option<HostValue>>,
+}
+
+impl<S> Platform<S> {
+    /// Parse the declaration; the prelude (`math`) comes bound.
+    pub fn new(decl: &str) -> Result<Self, Error> {
+        let decl = PlatformDecl::parse(decl)?;
+        let mut p = Platform {
+            fns: vec![None; decl.fns.len()],
+            consts: vec![None; decl.consts.len()],
+            decl,
+        };
+        crate::prelude::bind(&mut p);
+        Ok(p)
+    }
+
+    /// Supply the body of `Namespace.name`. Panics on a name the declaration
+    /// lacks: that is a mistake in the host, found the first time it starts.
+    pub fn bind(&mut self, qualified: &str, f: HostFn<S>) -> &mut Self {
+        let (ns, name) = qualified.split_once('.').expect("bind takes `Namespace.name`");
+        let (i, _) = self
+            .decl
+            .host_fn(ns, name)
+            .unwrap_or_else(|| panic!("the platform declares no `{qualified}`"));
+        self.fns[i as usize] = Some(f);
+        self
+    }
+
+    pub fn constant(&mut self, qualified: &str, v: HostValue) -> &mut Self {
+        let (ns, name) = qualified
+            .split_once('.')
+            .expect("constant takes `Namespace.name`");
+        let (i, _) = self
+            .decl
+            .host_const(ns, name)
+            .unwrap_or_else(|| panic!("the platform declares no `{qualified}`"));
+        self.consts[i as usize] = Some(v);
+        self
+    }
+
+    /// Everything declared but not bound, which a script could call and fail on.
+    pub fn unbound(&self) -> Vec<String> {
+        let fns = self.decl.fns.iter().zip(&self.fns).filter(|(_, f)| f.is_none());
+        let consts = self
+            .decl
+            .consts
+            .iter()
+            .zip(&self.consts)
+            .filter(|(_, c)| c.is_none());
+        fns.map(|(s, _)| format!("{}.{}", s.namespace, s.name))
+            .chain(consts.map(|(s, _)| format!("{}.{}", s.namespace, s.name)))
+            .collect()
+    }
+
+    pub fn compile(&self, src: &str) -> Result<Rc<Module>, Vec<Error>> {
+        crate::compile::compile(src, &self.decl).map(Rc::new)
+    }
+}
diff --git a/crates/frits/src/prelude.rs b/crates/frits/src/prelude.rs
new file mode 100644
index 0000000..40c813a
--- /dev/null
+++ b/crates/frits/src/prelude.rs
@@ -0,0 +1,50 @@
+//! What every platform has: the pure `math` module.
+
+use crate::platform::{Cx, Platform};
+use crate::value::{HostValue, Value};
+
+pub const DECL: &str = "
+module math {
+    fn sin(x: Float) -> Float
+    fn cos(x: Float) -> Float
+    fn tan(x: Float) -> Float
+    fn atan2(y: Float, x: Float) -> Float
+    fn sqrt(x: Float) -> Float
+    fn abs(x: Float) -> Float
+    fn floor(x: Float) -> Float
+    fn ceil(x: Float) -> Float
+    fn round(x: Float) -> Float
+    fn min(a: Float, b: Float) -> Float
+    fn max(a: Float, b: Float) -> Float
+    fn deg(radians: Float) -> Float
+    fn rad(degrees: Float) -> Float
+    let pi: Float
+}
+";
+
+fn f1(a: &[Value], f: fn(f64) -> f64) -> Result<Value, String> {
+    Ok(Value::Float(f(a[0].float())))
+}
+
+pub fn bind<S>(p: &mut Platform<S>) {
+    p.bind("math.sin", |_: &mut Cx<S>, a| f1(a, f64::sin))
+        .bind("math.cos", |_, a| f1(a, f64::cos))
+        .bind("math.tan", |_, a| f1(a, f64::tan))
+        .bind("math.atan2", |_, a| {
+            Ok(Value::Float(a[0].float().atan2(a[1].float())))
+        })
+        .bind("math.sqrt", |_, a| f1(a, f64::sqrt))
+        .bind("math.abs", |_, a| f1(a, f64::abs))
+        .bind("math.floor", |_, a| f1(a, f64::floor))
+        .bind("math.ceil", |_, a| f1(a, f64::ceil))
+        .bind("math.round", |_, a| f1(a, f64::round))
+        .bind("math.min", |_, a| {
+            Ok(Value::Float(a[0].float().min(a[1].float())))
+        })
+        .bind("math.max", |_, a| {
+            Ok(Value::Float(a[0].float().max(a[1].float())))
+        })
+        .bind("math.deg", |_, a| f1(a, f64::to_degrees))
+        .bind("math.rad", |_, a| f1(a, f64::to_radians))
+        .constant("math.pi", HostValue::Float(std::f64::consts::PI));
+}
diff --git a/crates/frits/src/runtime.rs b/crates/frits/src/runtime.rs
new file mode 100644
index 0000000..2be4743
--- /dev/null
+++ b/crates/frits/src/runtime.rs
@@ -0,0 +1,112 @@
+//! Many processes, one platform, a fuel slice each per tick.
+
+use std::rc::Rc;
+
+use crate::bytecode::Module;
+use crate::platform::Platform;
+use crate::value::HostValue;
+use crate::vm::{Outcome, Process, Status};
+
+pub type Pid = u32;
+
+#[derive(Clone, Copy, Debug)]
+pub struct Limits {
+    /// Instructions a process may run per tick before it is paused.
+    pub fuel: u64,
+    /// Live heap bytes a process may hold.
+    pub memory: usize,
+}
+
+impl Default for Limits {
+    fn default() -> Self {
+        // Luau's slice in the Cartopolis simulator was 20,000 instructions.
+        Limits {
+            fuel: 20_000,
+            memory: 256 * 1024,
+        }
+    }
+}
+
+pub struct Runtime<S> {
+    pub platform: Platform<S>,
+    pub limits: Limits,
+    procs: Vec<Option<Process<S>>>,
+    free: Vec<Pid>,
+}
+
+impl<S> Runtime<S> {
+    pub fn new(platform: Platform<S>) -> Self {
+        Runtime {
+            platform,
+            limits: Limits::default(),
+            procs: Vec::new(),
+            free: Vec::new(),
+        }
+    }
+
+    /// Start a process running `module`; its globals are set on its first slice.
+    pub fn spawn(&mut self, module: Rc<Module>, state: S) -> Pid {
+        let p = Process::new(module, state);
+        match self.free.pop() {
+            Some(pid) => {
+                self.procs[pid as usize] = Some(p);
+                pid
+            }
+            None => {
+                self.procs.push(Some(p));
+                self.procs.len() as Pid - 1
+            }
+        }
+    }
+
+    pub fn kill(&mut self, pid: Pid) -> Option<Process<S>> {
+        let p = self.procs.get_mut(pid as usize)?.take()?;
+        self.free.push(pid);
+        Some(p)
+    }
+
+    pub fn get(&self, pid: Pid) -> Option<&Process<S>> {
+        self.procs.get(pid as usize)?.as_ref()
+    }
+
+    pub fn get_mut(&mut self, pid: Pid) -> Option<&mut Process<S>> {
+        self.procs.get_mut(pid as usize)?.as_mut()
+    }
+
+    /// Deliver an event. Its values are copied into the process's own heap when
+    /// the handler starts. Returns whether the script handles it.
+    pub fn post(&mut self, pid: Pid, event: &str, args: Vec<HostValue>) -> bool {
+        self.get_mut(pid).is_some_and(|p| p.post(event, args))
+    }
+
+    /// Run one process for one slice.
+    pub fn run(&mut self, pid: Pid) -> Option<Outcome> {
+        let limits = self.limits;
+        let p = self.procs.get_mut(pid as usize)?.as_mut()?;
+        Some(p.run(&self.platform, limits.fuel, limits.memory))
+    }
+
+    /// One slice for every process with work. Returns the ones that died.
+    pub fn tick(&mut self) -> Vec<(Pid, String)> {
+        let limits = self.limits;
+        let mut died = Vec::new();
+        for (pid, slot) in self.procs.iter_mut().enumerate() {
+            let Some(p) = slot else { continue };
+            if !p.has_work() || matches!(p.status, Status::Dead(_)) {
+                continue;
+            }
+            if let Outcome::Died(m) = p.run(&self.platform, limits.fuel, limits.memory) {
+                died.push((pid as Pid, m));
+            }
+        }
+        died
+    }
+
+    pub fn pids(&self) -> impl Iterator<Item = Pid> + '_ {
+        self.procs
+            .iter()
+            .enumerate()
+            .filter(|(_, p)| p.is_some())
+            .map(|(i, _)| i as Pid)
+    }
+}
diff --git a/crates/frits/src/tests.rs b/crates/frits/src/tests.rs
new file mode 100644
index 0000000..835bd41
--- /dev/null
+++ b/crates/frits/src/tests.rs
@@ -0,0 +1,316 @@
+use crate::*;
+
+const DECL: &str = "
+type Geo = { lat: Float, lng: Float }
+effect Out {
+    fn say(text: Str)
+    fn here() -> Geo
+    fn find(n: Int) -> Option<{ id: Int, name: Str }>
+}
+effect Net {
+    fn get(url: Str) -> Str
+}
+event go()
+event msg(n: Int, text: Str)
+";
+
+#[derive(Default)]
+struct Log(Vec<String>);
+
+fn platform() -> Platform<Log> {
+    let mut p = Platform::new(DECL).unwrap();
+    p.bind("Out.say", |cx: &mut Cx<Log>, a| {
+        let s = cx.str(a[0]).to_string();
+        cx.state.0.push(s);
+        Ok(Value::Unit)
+    })
+    .bind("Out.here", |cx, _| {
+        Ok(cx.record(&[Value::Float(53.2), Value::Float(6.5)]))
+    })
+    .bind("Out.find", |cx, a| {
+        if a[0].int() > 0 {
+            let name = cx.new_str("Ada");
+            let r = cx.record(&[Value::Int(a[0].int()), name]);
+            Ok(cx.some(r))
+        } else {
+            Ok(cx.none())
+        }
+    })
+    .bind("Net.get", |_, _| Err("no network in tests".into()));
+    assert!(p.unbound().is_empty(), "{:?}", p.unbound());
+    p
+}
+
+fn errors(src: &str) -> Vec<String> {
+    match platform().compile(src) {
+        Ok(_) => Vec::new(),
+        Err(e) => e.into_iter().map(|e| e.to_string()).collect(),
+    }
+}
+
+/// Run `src`, post `go`, and run until idle. Returns what it said and how it ended.
+fn run(src: &str) -> (Vec<String>, Status) {
+    let mut rt = Runtime::new(platform());
+    let m = rt.platform.compile(src).unwrap_or_else(|e| panic!("{e:?}"));
+    let pid = rt.spawn(m, Log::default());
+    rt.post(pid, "go", Vec::new());
+    for _ in 0..10_000 {
+        rt.tick();
+        if !rt.get(pid).unwrap().has_work() || matches!(rt.get(pid).unwrap().status, Status::Dead(_)) {
+            break;
+        }
+    }
+    let p = rt.get(pid).unwrap();
+    (p.state.0.clone(), p.status.clone())
+}
+
+fn said(src: &str) -> Vec<String> {
+    let (out, status) = run(src);
+    assert_eq!(status, Status::Idle, "said {out:?}");
+    out
+}
+
+#[test]
+fn arithmetic_and_functions() {
+    let out = said(
+        "script / Out
+        fn fib(n: Int) -> Int { if n < 2 { n } else { fib(n - 1) + fib(n - 2) } }
+        fn half(x: Float) -> Float { x / 2 }
+        on go() {
+            Out.say(\"fib {fib(20)}\")
+            Out.say(\"half {half(3.0)} {2 * math.pi:.3}\")
+            var s = 0
+            for i in 0..10 { s += i }
+            Out.say(\"sum {s}\")
+        }",
+    );
+    assert_eq!(out, ["fib 6765", "half 1.5 6.283", "sum 45"]);
+}
+
+#[test]
+fn globals_records_and_field_assignment() {
+    let out = said(
+        "script / Out
+        let BASE = { count: 1, life: 1.5, color: { r: 1.0, g: 0.5 } }
+        var flame = { ..BASE, count: 120 }
+        on go() {
+            flame.count = 200
+            flame.color.g = 0.25
+            Out.say(\"{flame.count} {flame.life} {flame.color.g} {BASE.count} {BASE.color.g}\")
+            let p = Out.here()
+            Out.say(\"{p.lat}\")
+        }",
+    );
+    assert_eq!(out, ["200 1.5 0.25 1 0.5", "53.2"]);
+}
+
+#[test]
+fn enums_match_and_options() {
+    let out = said(
+        "script / Out
+        enum State { Patrol, Summoned, Hit(Int, Str) }
+        var state = Patrol
+        fn describe(s: State) -> Str {
+            match s {
+                Patrol => \"patrol\",
+                Summoned => \"summoned\",
+                Hit(n, who) => \"hit {n} by {who}\",
+            }
+        }
+        on go() {
+            Out.say(describe(state))
+            state = Hit(3, \"Bo\")
+            Out.say(describe(state))
+            if let Some(f) = Out.find(7) { Out.say(\"found {f.name} {f.id}\") }
+            if let Some(f) = Out.find(0) { Out.say(\"wrong\") } else { Out.say(\"none\") }
+            let x: Option<Float> = None
+            let y = match x { Some(v) => v, None => 2.5 }
+            Out.say(\"{y}\")
+        }",
+    );
+    assert_eq!(out, ["patrol", "hit 3 by Bo", "found Ada 7", "none", "2.5"]);
+}
+
+#[test]
+fn lists_and_loops() {
+    let out = said(
+        "script / Out
+        on go() {
+            let xs = [3, 1, 4, 1, 5]
+            var best = 0
+            for x in xs { if x > best { best = x } }
+            var i = 0
+            while true {
+                i += 1
+                if i == 3 { continue }
+                if i > 5 { break }
+            }
+            let w = \"héllo\"
+            Out.say(\"{best} {len(xs)} {xs[2]} {i} {len(w)}\")
+        }",
+    );
+    assert_eq!(out, ["5 5 4 6 5"]);
+}
+
+#[test]
+fn type_errors_are_reported_with_lines() {
+    // A literal `1` beside a Float is a Float; an Int variable is not.
+    assert!(errors("script / Out\non go() { let x = 1 + 2.5 }").is_empty());
+    let e = errors("script / Out\non go() {\n let a = 1\n let x = a + 2.5 }");
+    assert!(
+        e[0].contains("line 4") && e[0].contains("`+` to Int and Float"),
+        "{e:?}"
+    );
+    let e = errors("script / Out\non go() { let x = 1\n x = 2 }");
+    assert!(e[0].contains("declare it with `var`"), "{e:?}");
+    let e = errors("script / Out\nenum S { A, B }\nfn f(s: S) -> Int { match s { A => 1 } }");
+    assert!(e[0].contains("misses: B"), "{e:?}");
+    let e = errors("script / Out\non go() { Out.say(3) }");
+    assert!(e[0].contains("expected Str, found Int"), "{e:?}");
+    let e = errors("on nope() { }");
+    assert!(e[0].contains("no event `nope`"), "{e:?}");
+}
+
+#[test]
+fn effects_must_be_declared() {
+    // A script that did not ask for Out cannot use it.
+    let e = errors("on go() { Out.say(\"hi\") }");
+    assert!(e[0].contains("add it to `script / …`"), "{e:?}");
+    // A function must say what it does.
+    let e = errors("script / Out\nfn hello() { Out.say(\"hi\") }");
+    assert!(e[0].contains("fn hello(…) / Out"), "{e:?}");
+    // And its callers must be allowed all of it.
+    let e = errors(
+        "script / Out, Net\nfn fetch() -> Str / Net { Net.get(\"x\") }\nfn f() / Out { Out.say(fetch()) }",
+    );
+    assert!(e[0].contains("`Net`"), "{e:?}");
+    // Asking for an effect the platform lacks.
+    let e = errors("script / Files");
+    assert!(e[0].contains("no effect `Files`"), "{e:?}");
+    assert!(errors("script / Out, Net\nfn fetch() -> Str / Net { Net.get(\"x\") }\nfn f() / Out, Net { Out.say(fetch()) }").is_empty());
+}
+
+#[test]
+fn a_busy_loop_is_paused_not_killed_and_its_neighbour_runs() {
+    let mut rt = Runtime::new(platform());
+    rt.limits.fuel = 1000;
+    // At the top level, the place Luau once could not pause.
+    let busy = rt.platform.compile("script / Out\nvar n = 0\nlet x = { while n < 100000 { n += 1 }; n }\non go() { Out.say(\"done {x}\") }").unwrap();
+    let calm = rt
+        .platform
+        .compile("script / Out\non go() { Out.say(\"hi\") }")
+        .unwrap();
+    let a = rt.spawn(busy, Log::default());
+    let b = rt.spawn(calm, Log::default());
+    rt.post(a, "go", Vec::new());
+    rt.post(b, "go", Vec::new());
+    rt.tick();
+    assert_eq!(rt.get(a).unwrap().status, Status::Paused);
+    assert_eq!(rt.get(b).unwrap().state.0, ["hi"]);
+    let mut ticks = 1;
+    while rt.get(a).unwrap().has_work() {
+        rt.tick();
+        ticks += 1;
+    }
+    assert_eq!(rt.get(a).unwrap().state.0, ["done 100000"]);
+    assert!(ticks > 100, "the loop took {ticks} slices of 1000 instructions");
+}
+
+#[test]
+fn deep_recursion_pauses_too() {
+    let mut rt = Runtime::new(platform());
+    rt.limits.fuel = 500;
+    let m = rt.platform.compile("script / Out\nfn down(n: Int) -> Int { if n == 0 { 0 } else { 1 + down(n - 1) } }\non go() { Out.say(\"{down(1500)}\") }").unwrap();
+    let a = rt.spawn(m, Log::default());
+    rt.post(a, "go", Vec::new());
+    while rt.get(a).unwrap().has_work() {
+        assert!(rt.tick().is_empty());
+    }
+    assert_eq!(rt.get(a).unwrap().state.0, ["1500"]);
+}
+
+#[test]
+fn a_memory_hog_dies_alone() {
+    let mut rt = Runtime::new(platform());
+    let hog = rt
+        .platform
+        .compile("script / Out\non go() { var s = \"x\"\n while true { s = s + s } }")
+        .unwrap();
+    let calm = rt
+        .platform
+        .compile("script / Out\non go() { Out.say(\"fine\") }")
+        .unwrap();
+    let a = rt.spawn(hog, Log::default());
+    let b = rt.spawn(calm, Log::default());
+    rt.post(a, "go", Vec::new());
+    rt.post(b, "go", Vec::new());
+    let mut died = Vec::new();
+    for _ in 0..100 {
+        died.extend(rt.tick());
+    }
+    assert_eq!(died.len(), 1, "{died:?}");
+    assert_eq!(died[0].0, a);
+    assert!(died[0].1.contains("out of memory"), "{}", died[0].1);
+    assert_eq!(rt.get(b).unwrap().state.0, ["fine"]);
+}
+
+#[test]
+fn garbage_is_collected_under_the_limit() {
+    let (out, status) = run("script / Out
+        on go() {
+            var total = 0
+            for i in 0..20000 {
+                let r = { a: \"item {i}\", b: [i, i, i, i] }
+                total += len(r.b)
+            }
+            Out.say(\"{total}\")
+        }");
+    assert_eq!(status, Status::Idle);
+    assert_eq!(out, ["80000"]);
+}
+
+#[test]
+fn runtime_errors_stop_the_script_with_a_line() {
+    let (_, s) = run("script / Out\non go() {\n let z = 0\n let x = 10 / z\n}");
+    assert!(
+        matches!(&s, Status::Dead(m) if m.contains("line 4") && m.contains("division by zero")),
+        "{s:?}"
+    );
+    let (_, s) = run("script / Out\non go() { let x = [1]\n let y = x[3] }");
+    assert!(
+        matches!(&s, Status::Dead(m) if m.contains("outside the list")),
+        "{s:?}"
+    );
+    // A host function's error stops the script the same way.
+    let (_, s) = run("script / Out, Net\non go() { let x = Net.get(\"a\") }");
+    assert!(matches!(&s, Status::Dead(m) if m.contains("no network")), "{s:?}");
+}
+
+#[test]
+fn messages_are_copied_into_the_receiver() {
+    let mut rt = Runtime::new(platform());
+    let m = rt.platform.compile("script / Out\nvar seen = \"\"\non msg(n: Int, text: Str) { seen = seen + text\n Out.say(\"{n}: {seen}\") }").unwrap();
+    let a = rt.spawn(m.clone(), Log::default());
+    let b = rt.spawn(m, Log::default());
+    rt.post(a, "msg", vec![HostValue::Int(1), HostValue::Str("a".into())]);
+    rt.post(a, "msg", vec![HostValue::Int(2), HostValue::Str("b".into())]);
+    rt.post(b, "msg", vec![HostValue::Int(3), HostValue::Str("c".into())]);
+    rt.tick();
+    assert_eq!(rt.get(a).unwrap().state.0, ["1: a", "2: ab"]);
+    assert_eq!(rt.get(b).unwrap().state.0, ["3: c"]);
+    // An event the script does not handle is not queued.
+    assert!(!rt.post(a, "go", Vec::new()));
+}
+
+#[test]
+fn an_idle_process_is_small() {
+    let mut rt = Runtime::new(platform());
+    let m = rt
+        .platform
+        .compile("script / Out\non msg(n: Int, text: Str) { }")
+        .unwrap();
+    let a = rt.spawn(m, Log::default());
+    rt.tick();
+    let bytes = rt.get(a).unwrap().memory();
+    assert!(bytes < 1024, "an idle process holds {bytes} bytes");
+}
diff --git a/crates/frits/src/types.rs b/crates/frits/src/types.rs
new file mode 100644
index 0000000..86510d5
--- /dev/null
+++ b/crates/frits/src/types.rs
@@ -0,0 +1,280 @@
+//! Types, and what a platform declares.
+
+use std::collections::HashMap;
+use std::fmt;
+use std::rc::Rc;
+
+use crate::Error;
+use crate::ast::{self, TypeExpr};
+
+#[derive(Clone, Debug, Default, PartialEq)]
+pub enum Type {
+    #[default]
+    Unit,
+    Bool,
+    Int,
+    Float,
+    Str,
+    List(Rc<Type>),
+    Option(Rc<Type>),
+    /// Fields sorted by name: two records with the same fields are the same type,
+    /// whatever they were called where they were written.
+    Record(Rc<[(Rc<str>, Type)]>),
+    Enum(u32),
+    /// What `return` and `panic` evaluate to: fits wherever a value is wanted.
+    Never,
+    /// Stands in after an error, so one mistake is reported once.
+    Error,
+}
+
+impl Type {
+    pub fn record(mut fields: Vec<(Rc<str>, Type)>) -> Type {
+        fields.sort_by(|a, b| a.0.cmp(&b.0));
+        Type::Record(fields.into())
+    }
+
+    pub fn field(&self, name: &str) -> Option<(usize, &Type)> {
+        match self {
+            Type::Record(f) => f.iter().position(|(n, _)| &**n == name).map(|i| (i, &f[i].1)),
+            _ => None,
+        }
+    }
+
+    /// Does a value of `self` fit where `want` is expected?
+    pub fn fits(&self, want: &Type) -> bool {
+        self == want || matches!(self, Type::Never | Type::Error) || matches!(want, Type::Error)
+    }
+}
+
+/// Names for the types, for messages. Enums need the compiler's table, so
+/// they print as `enum #n` here and the compiler substitutes names.
+pub struct Show<'a>(pub &'a Type, pub &'a [String]);
+
+impl fmt::Display for Show<'_> {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        let names = self.1;
+        match self.0 {
+            Type::Unit => write!(f, "Unit"),
+            Type::Bool => write!(f, "Bool"),
+            Type::Int => write!(f, "Int"),
+            Type::Float => write!(f, "Float"),
+            Type::Str => write!(f, "Str"),
+            Type::List(t) => write!(f, "List<{}>", Show(t, names)),
+            Type::Option(t) => write!(f, "Option<{}>", Show(t, names)),
+            Type::Record(fields) => {
+                write!(f, "{{ ")?;
+                for (i, (n, t)) in fields.iter().enumerate() {
+                    if i > 0 {
+                        write!(f, ", ")?;
+                    }
+                    write!(f, "{n}: {}", Show(t, names))?;
+                }
+                write!(f, " }}")
+            }
+            Type::Enum(i) => write!(
+                f,
+                "{}",
+                names.get(*i as usize).map(|s| s.as_str()).unwrap_or("enum")
+            ),
+            Type::Never => write!(f, "Never"),
+            Type::Error => write!(f, "?"),
+        }
+    }
+}
+
+/// Resolves written types against the aliases and enums in scope.
+#[derive(Debug, Default, Clone)]
+pub struct TypeEnv {
+    pub aliases: HashMap<String, Type>,
+    pub enums: HashMap<String, u32>,
+}
+
+impl TypeEnv {
+    pub fn resolve(&self, t: &TypeExpr) -> Result<Type, Error> {
+        match t {
+            TypeExpr::Record(fields, line) => {
+                let mut out: Vec<(Rc<str>, Type)> = Vec::new();
+                for (n, ft) in fields {
+                    if out.iter().any(|(m, _)| &**m == n) {
+                        return Err(Error::new(*line, format!("field `{n}` is named twice")));
+                    }
+                    out.push((n.as_str().into(), self.resolve(ft)?));
+                }
+                Ok(Type::record(out))
+            }
+            TypeExpr::Named(name, args, line) => {
+                let arity = |n: usize| -> Result<(), Error> {
+                    if args.len() == n {
+                        Ok(())
+                    } else {
+                        Err(Error::new(
+                            *line,
+                            format!("`{name}` takes {n} type argument(s), not {}", args.len()),
+                        ))
+                    }
+                };
+                Ok(match name.as_str() {
+                    "Unit" => {
+                        arity(0)?;
+                        Type::Unit
+                    }
+                    "Bool" => {
+                        arity(0)?;
+                        Type::Bool
+                    }
+                    "Int" => {
+                        arity(0)?;
+                        Type::Int
+                    }
+                    "Float" => {
+                        arity(0)?;
+                        Type::Float
+                    }
+                    "Str" => {
+                        arity(0)?;
+                        Type::Str
+                    }
+                    "List" => {
+                        arity(1)?;
+                        Type::List(Rc::new(self.resolve(&args[0])?))
+                    }
+                    "Option" => {
+                        arity(1)?;
+                        Type::Option(Rc::new(self.resolve(&args[0])?))
+                    }
+                    _ => {
+                        arity(0)?;
+                        if let Some(t) = self.aliases.get(name) {
+                            t.clone()
+                        } else if let Some(&e) = self.enums.get(name) {
+                            Type::Enum(e)
+                        } else {
+                            return Err(Error::new(*line, format!("unknown type `{name}`")));
+                        }
+                    }
+                })
+            }
+        }
+    }
+}
+
+#[derive(Debug, Clone)]
+pub struct HostFnSig {
+    pub namespace: String,
+    pub name: String,
+    /// The effect a call needs, or None for a pure module.
+    pub effect: Option<String>,
+    pub params: Vec<Type>,
+    pub ret: Type,
+}
+
+#[derive(Debug, Clone)]
+pub struct HostConstSig {
+    pub namespace: String,
+    pub name: String,
+    pub ty: Type,
+}
+
+/// What a platform offers scripts, parsed from its Frits declaration: the
+/// effects with their calls, pure modules, types and events. Rust supplies the
+/// bodies (`Platform::bind`).
+#[derive(Debug, Default, Clone)]
+pub struct PlatformDecl {
+    pub env: TypeEnv,
+    pub fns: Vec<HostFnSig>,
+    pub consts: Vec<HostConstSig>,
+    pub effects: Vec<String>,
+    pub modules: Vec<String>,
+    pub events: Vec<(String, Vec<Type>)>,
+}
+
+impl PlatformDecl {
+    pub fn parse(src: &str) -> Result<PlatformDecl, Error> {
+        let mut d = PlatformDecl::default();
+        d.add(crate::prelude::DECL)?;
+        d.add(src)?;
+        Ok(d)
+    }
+
+    fn add(&mut self, src: &str) -> Result<(), Error> {
+        let m = crate::parser::parse(src)?;
+        for item in m.items {
+            match item {
+                ast::Item::Type(name, t, _) => {
+                    let ty = self.env.resolve(&t)?;
+                    self.env.aliases.insert(name, ty);
+                }
+                ast::Item::Namespace(ns) => {
+                    if ns.effect {
+                        self.effects.push(ns.name.clone());
+                    } else {
+                        self.modules.push(ns.name.clone());
+                    }
+                    for f in &ns.fns {
+                        let params = f
+                            .params
+                            .iter()
+                            .map(|(_, t)| self.env.resolve(t))
+                            .collect::<Result<_, _>>()?;
+                        let ret = f
+                            .ret
+                            .as_ref()
+                            .map(|t| self.env.resolve(t))
+                            .transpose()?
+                            .unwrap_or(Type::Unit);
+                        self.fns.push(HostFnSig {
+                            namespace: ns.name.clone(),
+                            name: f.name.clone(),
+                            effect: ns.effect.then(|| ns.name.clone()),
+                            params,
+                            ret,
+                        });
+                    }
+                    for (n, t, _) in &ns.consts {
+                        let ty = self.env.resolve(t)?;
+                        self.consts.push(HostConstSig {
+                            namespace: ns.name.clone(),
+                            name: n.clone(),
+                            ty,
+                        });
+                    }
+                }
+                ast::Item::Event(f) => {
+                    let params = f
+                        .params
+                        .iter()
+                        .map(|(_, t)| self.env.resolve(t))
+                        .collect::<Result<_, _>>()?;
+                    self.events.push((f.name, params));
+                }
+                _ => {
+                    return Err(Error::new(
+                        0,
+                        "a platform declaration holds only `type`, `effect`, `module` and `event`",
+                    ));
+                }
+            }
+        }
+        Ok(())
+    }
+
+    pub fn host_fn(&self, ns: &str, name: &str) -> Option<(u32, &HostFnSig)> {
+        self.fns
+            .iter()
+            .enumerate()
+            .find(|(_, f)| f.namespace == ns && f.name == name)
+            .map(|(i, f)| (i as u32, f))
+    }
+
+    pub fn host_const(&self, ns: &str, name: &str) -> Option<(u32, &HostConstSig)> {
+        self.consts
+            .iter()
+            .enumerate()
+            .find(|(_, c)| c.namespace == ns && c.name == name)
+            .map(|(i, c)| (i as u32, c))
+    }
+
+    pub fn is_namespace(&self, n: &str) -> bool {
+        self.effects.iter().chain(&self.modules).any(|e| e == n)
+    }
+}
diff --git a/crates/frits/src/value.rs b/crates/frits/src/value.rs
new file mode 100644
index 0000000..5854922
--- /dev/null
+++ b/crates/frits/src/value.rs
@@ -0,0 +1,227 @@
+//! Values and the per-process heap.
+//!
+//! Every process owns one `Heap`. Nothing in it is reachable from another
+//! process: a message is copied across (`Heap::export` / `import`). That is what
+//! makes a memory ceiling a plain number, a collection one process's business,
+//! and stopping a script nothing more than dropping its heap.
+
+use std::rc::Rc;
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub enum Value {
+    Unit,
+    Bool(bool),
+    Int(i64),
+    Float(f64),
+    /// An enum value without a payload.
+    Tag(u32),
+    /// A string literal of the module, shared by all its processes.
+    Static(u32),
+    /// An object in this process's heap.
+    Obj(u32),
+}
+
+impl Value {
+    #[inline]
+    pub fn int(self) -> i64 {
+        match self {
+            Value::Int(i) => i,
+            _ => 0,
+        }
+    }
+
+    #[inline]
+    pub fn float(self) -> f64 {
+        match self {
+            Value::Float(f) => f,
+            _ => 0.0,
+        }
+    }
+
+    #[inline]
+    pub fn bool(self) -> bool {
+        matches!(self, Value::Bool(true))
+    }
+}
+
+#[derive(Debug, Clone)]
+pub enum Obj {
+    Str(Box<str>),
+    Record(Box<[Value]>),
+    List(Box<[Value]>),
+    Variant(u32, Box<[Value]>),
+}
+
+impl Obj {
+    fn size(&self) -> usize {
+        const HEADER: usize = 32;
+        HEADER
+            + match self {
+                Obj::Str(s) => s.len(),
+                Obj::Record(v) | Obj::List(v) | Obj::Variant(_, v) => v.len() * size_of::<Value>(),
+            }
+    }
+}
+
+/// A value outside any heap: what the platform hands a script and gets back.
+#[derive(Clone, Debug, PartialEq)]
+pub enum HostValue {
+    Unit,
+    Bool(bool),
+    Int(i64),
+    Float(f64),
+    Str(String),
+    Tag(u32),
+    /// Fields in name order.
+    Record(Vec<HostValue>),
+    List(Vec<HostValue>),
+    Variant(u32, Vec<HostValue>),
+}
+
+#[derive(Debug, Default)]
+pub struct Heap {
+    objs: Vec<Option<Obj>>,
+    free: Vec<u32>,
+    marks: Vec<bool>,
+    /// Bytes held by live and not-yet-collected objects.
+    pub bytes: usize,
+    /// Bytes allocated since the last collection.
+    pub since_gc: usize,
+    pub collections: u32,
+}
+
+/// Below this much fresh allocation a collection is not worth its walk.
+const GC_FLOOR: usize = 4 * 1024;
+
+impl Heap {
+    pub fn alloc(&mut self, o: Obj) -> Value {
+        let sz = o.size();
+        self.bytes += sz;
+        self.since_gc += sz;
+        if let Some(i) = self.free.pop() {
+            self.objs[i as usize] = Some(o);
+            Value::Obj(i)
+        } else {
+            self.objs.push(Some(o));
+            Value::Obj(self.objs.len() as u32 - 1)
+        }
+    }
+
+    pub fn get(&self, v: Value) -> Option<&Obj> {
+        match v {
+            Value::Obj(i) => self.objs.get(i as usize).and_then(|o| o.as_ref()),
+            _ => None,
+        }
+    }
+
+    pub fn fields(&self, v: Value) -> &[Value] {
+        match self.get(v) {
+            Some(Obj::Record(f) | Obj::List(f) | Obj::Variant(_, f)) => f,
+            _ => &[],
+        }
+    }
+
+    pub fn wants_gc(&self) -> bool {
+        self.since_gc > GC_FLOOR.max(self.bytes - self.since_gc)
+    }
+
+    /// Mark from `roots`, free the rest. Precise: every value that can reach an
+    /// object is a root or inside a marked object.
+    pub fn collect<'a>(&mut self, roots: impl Iterator<Item = &'a Value>) {
+        self.marks.clear();
+        self.marks.resize(self.objs.len(), false);
+        let mut stack: Vec<u32> = roots
+            .filter_map(|v| if let Value::Obj(i) = v { Some(*i) } else { None })
+            .collect();
+        while let Some(i) = stack.pop() {
+            let i = i as usize;
+            if i >= self.marks.len() || self.marks[i] {
+                continue;
+            }
+            self.marks[i] = true;
+            if let Some(Obj::Record(f) | Obj::List(f) | Obj::Variant(_, f)) = &self.objs[i] {
+                stack.extend(
+                    f.iter()
+                        .filter_map(|v| if let Value::Obj(j) = v { Some(*j) } else { None }),
+                );
+            }
+        }
+        for (i, slot) in self.objs.iter_mut().enumerate() {
+            if !self.marks[i]
+                && let Some(o) = slot.take()
+            {
+                self.bytes -= o.size();
+                self.free.push(i as u32);
+            }
+        }
+        // Give the tail back, so an idle process holds no empty slots.
+        while matches!(self.objs.last(), Some(None)) {
+            self.objs.pop();
+        }
+        let len = self.objs.len() as u32;
+        self.free.retain(|&i| i < len);
+        self.objs.shrink_to(self.objs.len() * 2);
+        self.since_gc = 0;
+        self.collections += 1;
+    }
+
+    /// Approximate resident cost of the heap's own tables.
+    pub fn overhead(&self) -> usize {
+        self.objs.capacity() * size_of::<Option<Obj>>() + self.free.capacity() * 4 + self.marks.capacity()
+    }
+
+    pub fn str<'a>(&'a self, v: Value, strings: &'a [Rc<str>]) -> &'a str {
+        match v {
+            Value::Static(i) => strings.get(i as usize).map(|s| &**s).unwrap_or(""),
+            _ => match self.get(v) {
+                Some(Obj::Str(s)) => s,
+                _ => "",
+            },
+        }
+    }
+
+    pub fn export(&self, v: Value, strings: &[Rc<str>]) -> HostValue {
+        match v {
+            Value::Unit => HostValue::Unit,
+            Value::Bool(b) => HostValue::Bool(b),
+            Value::Int(i) => HostValue::Int(i),
+            Value::Float(f) => HostValue::Float(f),
+            Value::Tag(t) => HostValue::Tag(t),
+            Value::Static(_) => HostValue::Str(self.str(v, strings).to_string()),
+            Value::Obj(_) => match self.get(v) {
+                Some(Obj::Str(s)) => HostValue::Str(s.to_string()),
+                Some(Obj::Record(f)) => {
+                    HostValue::Record(f.iter().map(|x| self.export(*x, strings)).collect())
+                }
+                Some(Obj::List(f)) => HostValue::List(f.iter().map(|x| self.export(*x, strings)).collect()),
+                Some(Obj::Variant(t, f)) => {
+                    HostValue::Variant(*t, f.iter().map(|x| self.export(*x, strings)).collect())
+                }
+                None => HostValue::Unit,
+            },
+        }
+    }
+
+    pub fn import(&mut self, h: &HostValue) -> Value {
+        match h {
+            HostValue::Unit => Value::Unit,
+            HostValue::Bool(b) => Value::Bool(*b),
+            HostValue::Int(i) => Value::Int(*i),
+            HostValue::Float(f) => Value::Float(*f),
+            HostValue::Tag(t) => Value::Tag(*t),
+            HostValue::Str(s) => self.alloc(Obj::Str(s.as_str().into())),
+            HostValue::Record(f) => {
+                let f: Box<[Value]> = f.iter().map(|x| self.import(x)).collect();
+                self.alloc(Obj::Record(f))
+            }
+            HostValue::List(f) => {
+                let f: Box<[Value]> = f.iter().map(|x| self.import(x)).collect();
+                self.alloc(Obj::List(f))
+            }
+            HostValue::Variant(t, f) => {
+                let f: Box<[Value]> = f.iter().map(|x| self.import(x)).collect();
+                self.alloc(Obj::Variant(*t, f))
+            }
+        }
+    }
+}
diff --git a/crates/frits/src/vm.rs b/crates/frits/src/vm.rs
new file mode 100644
index 0000000..65c8cc8
--- /dev/null
+++ b/crates/frits/src/vm.rs
@@ -0,0 +1,457 @@
+//! The interpreter, and the processes it runs.
+//!
+//! A process is a script instance: its globals, its registers and frames, its
+//! heap and its mailbox. Its whole execution state is plain data in this
+//! struct, never the Rust stack, so stopping it anywhere is returning from
+//! `run` and resuming it is calling `run` again. There is therefore no context
+//! in which a script cannot be paused: fuel runs out at an instruction, wherever
+//! that instruction is.
+
+use std::collections::VecDeque;
+use std::rc::Rc;
+
+use crate::bytecode::{Module, Op};
+use crate::platform::{Cx, Platform};
+use crate::value::{Heap, HostValue, Obj, Value};
+
+#[derive(Clone, Copy, Debug)]
+struct Frame {
+    func: u32,
+    pc: u32,
+    base: u32,
+    /// The caller's register that receives the result.
+    ret: u16,
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub enum Status {
+    /// Waiting for an event.
+    Idle,
+    /// In the middle of a handler, paused when its fuel ran out.
+    Paused,
+    Dead(String),
+}
+
+pub struct Process<S> {
+    pub module: Rc<Module>,
+    globals: Vec<Value>,
+    regs: Vec<Value>,
+    frames: Vec<Frame>,
+    pub heap: Heap,
+    mailbox: VecDeque<(u32, Vec<HostValue>)>,
+    pub state: S,
+    pub status: Status,
+    /// Instructions executed over the process's life.
+    pub executed: u64,
+}
+
+/// How `run` came back.
+#[derive(Clone, Debug, PartialEq)]
+pub enum Outcome {
+    /// Nothing left to do.
+    Idle,
+    /// Fuel ran out; work is left for the next slice.
+    Paused,
+    Died(String),
+}
+
+impl<S> Process<S> {
+    pub fn new(module: Rc<Module>, state: S) -> Self {
+        let mut p = Process {
+            globals: vec![Value::Unit; module.globals.len()],
+            regs: Vec::new(),
+            frames: Vec::new(),
+            heap: Heap::default(),
+            mailbox: VecDeque::new(),
+            state,
+            status: Status::Idle,
+            executed: 0,
+            module,
+        };
+        let init = p.module.init;
+        p.mailbox.push_back((init, Vec::new()));
+        p
+    }
+
+    /// Queue `event` if the script handles it. Returns whether it does.
+    pub fn post(&mut self, event: &str, args: Vec<HostValue>) -> bool {
+        match self.module.handler(event) {
+            Some(f) if !matches!(self.status, Status::Dead(_)) => {
+                self.mailbox.push_back((f, args));
+                true
+            }
+            _ => false,
+        }
+    }
+
+    pub fn has_work(&self) -> bool {
+        !self.frames.is_empty() || !self.mailbox.is_empty()
+    }
+
+    /// Bytes this process holds: heap objects, registers, globals, frames.
+    pub fn memory(&self) -> usize {
+        self.heap.bytes
+            + self.heap.overhead()
+            + self.regs.capacity() * size_of::<Value>()
+            + self.globals.capacity() * size_of::<Value>()
+            + self.frames.capacity() * size_of::<Frame>()
+            + self.mailbox.capacity() * size_of::<(u32, Vec<HostValue>)>()
+    }
+
+    fn collect(&mut self, top: usize) {
+        let top = top.min(self.regs.len());
+        self.heap.collect(self.globals.iter().chain(&self.regs[..top]));
+    }
+
+    fn die(&mut self, msg: String) -> Outcome {
+        self.status = Status::Dead(msg.clone());
+        self.frames.clear();
+        self.mailbox.clear();
+        self.regs = Vec::new();
+        self.globals = Vec::new();
+        self.heap = Heap::default();
+        Outcome::Died(msg)
+    }
+
+    fn located(&self, f: u32, pc: u32, msg: &str) -> String {
+        let func = &self.module.funcs[f as usize];
+        let line = func.lines.get(pc as usize).copied().unwrap_or(0);
+        format!("line {line}, in {}: {msg}", func.name)
+    }
+
+    /// Run for at most `fuel` instructions.
+    pub fn run(&mut self, plat: &Platform<S>, fuel: u64, mem_limit: usize) -> Outcome {
+        if let Status::Dead(m) = &self.status {
+            return Outcome::Died(m.clone());
+        }
+        let module = self.module.clone();
+        let m = &*module;
+        let mut fuel = fuel;
+        let start_fuel = fuel;
+        let out = 'events: loop {
+            if self.frames.is_empty() {
+                let Some((f, args)) = self.mailbox.pop_front() else {
+                    if self.heap.wants_gc() {
+                        self.collect(0);
+                    }
+                    break Outcome::Idle;
+                };
+                let func = &m.funcs[f as usize];
+                let n = func.nregs as usize;
+                if self.regs.len() < n {
+                    self.regs.resize(n, Value::Unit);
+                }
+                for (i, a) in args.iter().enumerate() {
+                    self.regs[i] = self.heap.import(a);
+                }
+                self.frames.push(Frame {
+                    func: f,
+                    pc: 0,
+                    base: 0,
+                    ret: 0,
+                });
+            }
+            let fr = *self.frames.last().unwrap();
+            let mut func_id = fr.func;
+            let mut code = &m.funcs[func_id as usize].code[..];
+            let mut pc = fr.pc as usize;
+            let mut base = fr.base as usize;
+
+            macro_rules! r {
+                ($x:expr) => {
+                    self.regs[base + $x as usize]
+                };
+            }
+            macro_rules! fail {
+                ($msg:expr) => {{
+                    let msg = self.located(func_id, pc as u32, &$msg);
+                    break 'events self.die(msg);
+                }};
+            }
+            macro_rules! save {
+                () => {
+                    self.frames.last_mut().unwrap().pc = pc as u32;
+                };
+            }
+            macro_rules! safepoint {
+                () => {
+                    if self.heap.wants_gc() {
+                        let top = base + m.funcs[func_id as usize].nregs as usize;
+                        self.collect(top);
+                        if self.heap.bytes > mem_limit {
+                            fail!(format!(
+                                "out of memory: {} KiB live, the limit is {} KiB",
+                                self.heap.bytes / 1024,
+                                mem_limit / 1024
+                            ));
+                        }
+                    }
+                };
+            }
+            loop {
+                if fuel == 0 {
+                    save!();
+                    break 'events Outcome::Paused;
+                }
+                fuel -= 1;
+                let op = code[pc];
+                pc += 1;
+                match op {
+                    Op::LoadK { dst, k } => r!(dst) = m.consts[k as usize],
+                    Op::LoadUnit { dst } => r!(dst) = Value::Unit,
+                    Op::LoadBool { dst, v } => r!(dst) = Value::Bool(v),
+                    Op::LoadTag { dst, tag } => r!(dst) = Value::Tag(tag),
+                    Op::Move { dst, src } => r!(dst) = r!(src),
+                    Op::GetGlobal { dst, g } => r!(dst) = self.globals[g as usize],
+                    Op::SetGlobal { g, src } => self.globals[g as usize] = r!(src),
+
+                    Op::AddI { dst, a, b } => match r!(a).int().checked_add(r!(b).int()) {
+                        Some(v) => r!(dst) = Value::Int(v),
+                        None => fail!("integer overflow in `+`"),
+                    },
+                    Op::SubI { dst, a, b } => match r!(a).int().checked_sub(r!(b).int()) {
+                        Some(v) => r!(dst) = Value::Int(v),
+                        None => fail!("integer overflow in `-`"),
+                    },
+                    Op::MulI { dst, a, b } => match r!(a).int().checked_mul(r!(b).int()) {
+                        Some(v) => r!(dst) = Value::Int(v),
+                        None => fail!("integer overflow in `*`"),
+                    },
+                    Op::DivI { dst, a, b } => match r!(a).int().checked_div(r!(b).int()) {
+                        Some(v) => r!(dst) = Value::Int(v),
+                        None => fail!("integer division by zero"),
+                    },
+                    Op::RemI { dst, a, b } => match r!(a).int().checked_rem(r!(b).int()) {
+                        Some(v) => r!(dst) = Value::Int(v),
+                        None => fail!("integer remainder by zero"),
+                    },
+                    Op::NegI { dst, a } => match r!(a).int().checked_neg() {
+                        Some(v) => r!(dst) = Value::Int(v),
+                        None => fail!("integer overflow in `-`"),
+                    },
+                    Op::AddF { dst, a, b } => r!(dst) = Value::Float(r!(a).float() + r!(b).float()),
+                    Op::SubF { dst, a, b } => r!(dst) = Value::Float(r!(a).float() - r!(b).float()),
+                    Op::MulF { dst, a, b } => r!(dst) = Value::Float(r!(a).float() * r!(b).float()),
+                    Op::DivF { dst, a, b } => r!(dst) = Value::Float(r!(a).float() / r!(b).float()),
+                    Op::RemF { dst, a, b } => r!(dst) = Value::Float(r!(a).float() % r!(b).float()),
+                    Op::NegF { dst, a } => r!(dst) = Value::Float(-r!(a).float()),
+                    Op::Not { dst, a } => r!(dst) = Value::Bool(!r!(a).bool()),
+                    Op::LtI { dst, a, b } => r!(dst) = Value::Bool(r!(a).int() < r!(b).int()),
+                    Op::LeI { dst, a, b } => r!(dst) = Value::Bool(r!(a).int() <= r!(b).int()),
+                    Op::LtF { dst, a, b } => r!(dst) = Value::Bool(r!(a).float() < r!(b).float()),
+                    Op::LeF { dst, a, b } => r!(dst) = Value::Bool(r!(a).float() <= r!(b).float()),
+                    Op::EqI { dst, a, b } => r!(dst) = Value::Bool(r!(a).int() == r!(b).int()),
+                    Op::EqF { dst, a, b } => r!(dst) = Value::Bool(r!(a).float() == r!(b).float()),
+                    Op::EqB { dst, a, b } => r!(dst) = Value::Bool(r!(a).bool() == r!(b).bool()),
+                    Op::EqTag { dst, a, b } => r!(dst) = Value::Bool(r!(a) == r!(b)),
+                    Op::EqS { dst, a, b } => {
+                        let eq = {
+                            let (x, y) = (r!(a), r!(b));
+                            x == y || self.heap.str(x, &m.strings) == self.heap.str(y, &m.strings)
+                        };
+                        r!(dst) = Value::Bool(eq);
+                    }
+                    Op::IntToFloat { dst, a } => r!(dst) = Value::Float(r!(a).int() as f64),
+                    Op::FloatToInt { dst, a } => r!(dst) = Value::Int(r!(a).float() as i64),
+
+                    Op::Jump { to } => {
+                        if (to as usize) < pc {
+                            safepoint!();
+                        }
+                        pc = to as usize;
+                    }
+                    Op::JumpIfFalse { cond, to } => {
+                        if !r!(cond).bool() {
+                            pc = to as usize;
+                        }
+                    }
+                    Op::JumpIfTrue { cond, to } => {
+                        if r!(cond).bool() {
+                            pc = to as usize;
+                        }
+                    }
+
+                    Op::Call { f, base: cb, dst } => {
+                        safepoint!();
+                        if self.frames.len() >= 2_000 {
+                            fail!("too deep: more than 2000 calls in progress");
+                        }
+                        save!();
+                        let nb = base + cb as usize;
+                        let n = m.funcs[f as usize].nregs as usize;
+                        if self.regs.len() < nb + n {
+                            self.regs.resize(nb + n, Value::Unit);
+                        }
+                        self.frames.push(Frame {
+                            func: f,
+                            pc: 0,
+                            base: nb as u32,
+                            ret: dst,
+                        });
+                        func_id = f;
+                        code = &m.funcs[f as usize].code[..];
+                        pc = 0;
+                        base = nb;
+                    }
+                    Op::Ret { src } => {
+                        let v = r!(src);
+                        let done = self.frames.pop().unwrap();
+                        let Some(caller) = self.frames.last() else {
+                            // The handler finished; on to the next event.
+                            continue 'events;
+                        };
+                        func_id = caller.func;
+                        code = &m.funcs[func_id as usize].code[..];
+                        pc = caller.pc as usize;
+                        base = caller.base as usize;
+                        r!(done.ret) = v;
+                    }
+                    Op::CallHost {
+                        f,
+                        base: cb,
+                        argc,
+                        dst,
+                    } => {
+                        let Some(hf) = plat.fns[f as usize] else {
+                            let s = &plat.decl.fns[f as usize];
+                            fail!(format!(
+                                "the platform does not implement `{}.{}`",
+                                s.namespace, s.name
+                            ));
+                        };
+                        let a = base + cb as usize;
+                        let mut cx = Cx {
+                            state: &mut self.state,
+                            heap: &mut self.heap,
+                            strings: &m.strings,
+                        };
+                        match hf(&mut cx, &self.regs[a..a + argc as usize]) {
+                            Ok(v) => r!(dst) = v,
+                            Err(e) => fail!(e),
+                        }
+                    }
+                    Op::HostConst { dst, c } => match &plat.consts[c as usize] {
+                        Some(v) => r!(dst) = self.heap.import(v),
+                        None => {
+                            let s = &plat.decl.consts[c as usize];
+                            fail!(format!(
+                                "the platform does not provide `{}.{}`",
+                                s.namespace, s.name
+                            ));
+                        }
+                    },
+
+                    Op::MakeRecord { dst, base: b, n } => {
+                        let s = base + b as usize;
+                        let f: Box<[Value]> = self.regs[s..s + n as usize].into();
+                        r!(dst) = self.heap.alloc(Obj::Record(f));
+                    }
+                    Op::GetField { dst, src, idx } => {
+                        r!(dst) = self
+                            .heap
+                            .fields(r!(src))
+                            .get(idx as usize)
+                            .copied()
+                            .unwrap_or(Value::Unit);
+                    }
+                    Op::SetField { dst, src, idx, val } => {
+                        let mut f: Box<[Value]> = self.heap.fields(r!(src)).into();
+                        if let Some(slot) = f.get_mut(idx as usize) {
+                            *slot = r!(val);
+                        }
+                        r!(dst) = self.heap.alloc(Obj::Record(f));
+                    }
+                    Op::MakeList { dst, base: b, n } => {
+                        let s = base + b as usize;
+                        let f: Box<[Value]> = self.regs[s..s + n as usize].into();
+                        r!(dst) = self.heap.alloc(Obj::List(f));
+                    }
+                    Op::ListGet { dst, list, idx } => {
+                        let i = r!(idx).int();
+                        let items = self.heap.fields(r!(list));
+                        match usize::try_from(i).ok().and_then(|i| items.get(i)) {
+                            Some(v) => r!(dst) = *v,
+                            None => {
+                                let n = items.len();
+                                fail!(format!("index {i} is outside the list (length {n})"));
+                            }
+                        }
+                    }
+                    Op::Len { dst, src } => r!(dst) = Value::Int(self.heap.fields(r!(src)).len() as i64),
+                    Op::StrLen { dst, src } => {
+                        r!(dst) = Value::Int(self.heap.str(r!(src), &m.strings).chars().count() as i64)
+                    }
+                    Op::MakeVariant { dst, tag, base: b, n } => {
+                        let s = base + b as usize;
+                        let f: Box<[Value]> = self.regs[s..s + n as usize].into();
+                        r!(dst) = self.heap.alloc(Obj::Variant(tag, f));
+                    }
+                    Op::GetTag { dst, src } => {
+                        let v = r!(src);
+                        r!(dst) = Value::Int(match v {
+                            Value::Tag(t) => t as i64,
+                            _ => match self.heap.get(v) {
+                                Some(Obj::Variant(t, _)) => *t as i64,
+                                _ => -1,
+                            },
+                        });
+                    }
+                    Op::GetPayload { dst, src, idx } => {
+                        r!(dst) = self
+                            .heap
+                            .fields(r!(src))
+                            .get(idx as usize)
+                            .copied()
+                            .unwrap_or(Value::Unit);
+                    }
+
+                    Op::IntToStr { dst, a } => {
+                        let s = r!(a).int().to_string();
+                        r!(dst) = self.heap.alloc(Obj::Str(s.into()));
+                    }
+                    Op::FloatToStr { dst, a, prec } => {
+                        let x = r!(a).float();
+                        let s = if prec == u8::MAX {
+                            format!("{x}")
+                        } else {
+                            format!("{x:.*}", prec as usize)
+                        };
+                        r!(dst) = self.heap.alloc(Obj::Str(s.into()));
+                    }
+                    Op::BoolToStr { dst, a } => {
+                        let s = if r!(a).bool() { "true" } else { "false" };
+                        r!(dst) = self.heap.alloc(Obj::Str(s.into()));
+                    }
+                    Op::Concat { dst, base: b, n } => {
+                        let s = base + b as usize;
+                        let parts = &self.regs[s..s + n as usize];
+                        let total: usize = parts.iter().map(|v| self.heap.str(*v, &m.strings).len()).sum();
+                        if total > mem_limit {
+                            fail!(format!("out of memory: a {} KiB string", total / 1024));
+                        }
+                        let mut out = String::with_capacity(total);
+                        for v in parts {
+                            out.push_str(self.heap.str(*v, &m.strings));
+                        }
+                        r!(dst) = self.heap.alloc(Obj::Str(out.into()));
+                    }
+                    Op::Panic { msg } => {
+                        let text = m
+                            .strings
+                            .get(msg as usize)
+                            .map(|s| s.to_string())
+                            .unwrap_or_default();
+                        fail!(format!("panic: {text}"));
+                    }
+                }
+            }
+        };
+        self.executed += start_fuel - fuel;
+        self.status = match &out {
+            Outcome::Idle => Status::Idle,
+            Outcome::Paused => Status::Paused,
+            Outcome::Died(m) => Status::Dead(m.clone()),
+        };
+        out
+    }
+}
diff --git a/rust-toolchain.toml b/rust-toolchain.toml
new file mode 100644
index 0000000..73cb934
--- /dev/null
+++ b/rust-toolchain.toml
@@ -0,0 +1,3 @@
+[toolchain]
+channel = "stable"
+components = ["rustfmt", "clippy"]
diff --git a/rustfmt.toml b/rustfmt.toml
new file mode 100644
index 0000000..284d219
--- /dev/null
+++ b/rustfmt.toml
@@ -0,0 +1 @@
+max_width = 110