garage44.eu/jeroen/frits

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

cartopolis-agent · 2026-11-26T12:19:15Z

feat(frits): imports, messages between scripts, Secret and generic types

Part B: what scripts need to work together and to hold rights.

- `import geometry` merges a library the host supplies by name
  (`Platform::set_library`) under `geometry.` names, renaming only its
  own top-level names and leaving locals that share them alone. Each
  library is first compiled on its own, so its errors read "in library
  `geometry`, line 3" at the import; cycles are refused. Replacing a
  library drops the compiled-module cache, since any module may hold it.
- `on receive(m: T)`, `me() -> Addr<T>` and `send(addr, m)` (effect
  `Mail`). Addresses carry the pid's generation, so a reused pid does
  not get its predecessor's mail; a message whose type, written out,
  differs from the receiver's inbox is dropped and counted. Mailboxes
  stop at 1024 events.
- `Secret<T>` can be held and passed to host functions only: no
  interpolation, `==`, log, keep or message. `opaque Door` in a platform
  declaration is a right only the host can make.
- Generic enums and type aliases. Arguments that take their type from
  where they go (`Leaf`, `None`, `[]`) are compiled after the others,
  so `Node(Leaf, "x", Leaf)` and `walk(t, [])` need no annotation.

The exhaustiveness check now skips a column no arm looks into: without
that, a recursive type (`Tree<T>` holding a `Tree<T>`) was split forever
and the test binary died of a stack overflow (SIGABRT) with no message.

A match arm may be a statement (`Add(n) => sum += n`).
crates/frits/src/ast.rs      |  10 +-
 crates/frits/src/bytecode.rs |  13 ++
 crates/frits/src/compile.rs  | 256 ++++++++++++++++++++++++--
 crates/frits/src/imports.rs  | 424 +++++++++++++++++++++++++++++++++++++++++++
 crates/frits/src/lib.rs      |   1 +
 crates/frits/src/parser.rs   |  50 ++++-
 crates/frits/src/platform.rs |  14 +-
 crates/frits/src/prelude.rs  |   4 +
 crates/frits/src/runtime.rs  |  52 +++++-
 crates/frits/src/tests.rs    | 225 ++++++++++++++++++++++-
 crates/frits/src/types.rs    | 140 +++++++++++---
 crates/frits/src/vm.rs       |  21 ++-
 docs/design.md               |  43 ++++-
 13 files changed, 1193 insertions(+), 60 deletions(-)

diff --git a/crates/frits/src/ast.rs b/crates/frits/src/ast.rs
index 04bc0a7..c3c0427 100644
--- a/crates/frits/src/ast.rs
+++ b/crates/frits/src/ast.rs
@@ -15,7 +15,8 @@ pub enum Item {
     /// `on timer() { … }`: a handler for one of the platform's events.
     On(FnDecl),
     Enum(EnumDecl),
-    Type(Name, TypeExpr, u32),
+    /// `type Pair<A, B> = { a: A, b: B }`: name, type parameters, type.
+    Type(Name, Vec<Name>, TypeExpr, u32),
     Global(Global),
     /// Platform declarations only: `effect Prim { fn … }`, `module math { … }`.
     Namespace(Namespace),
@@ -23,6 +24,11 @@ pub enum Item {
     Event(FnDecl),
     /// `test "a goal counts" { … }`
     Test(String, Block, u32),
+    /// `import geometry`: a library the host supplies by name.
+    Import(Name, u32),
+    /// Platform declarations only: `opaque Door`, a value only the host can
+    /// make, which a script can hold and pass on but not look into.
+    Opaque(Name, u32),
 }
 
 #[derive(Debug)]
@@ -41,6 +47,8 @@ pub struct FnDecl {
 #[derive(Debug)]
 pub struct EnumDecl {
     pub name: Name,
+    /// `enum Tree<T> { … }`
+    pub generics: Vec<Name>,
     pub variants: Vec<(Name, Vec<TypeExpr>)>,
     pub line: u32,
 }
diff --git a/crates/frits/src/bytecode.rs b/crates/frits/src/bytecode.rs
index 1bb4661..b26c63e 100644
--- a/crates/frits/src/bytecode.rs
+++ b/crates/frits/src/bytecode.rs
@@ -298,6 +298,17 @@ pub enum Op {
         base: Reg,
         dst: Reg,
     },
+    /// This process's own address.
+    Me {
+        dst: Reg,
+    },
+    /// Send `msg` to the address in `to`; `ty` is the message type, written
+    /// out (a module string), which the receiver's inbox must match.
+    Send {
+        to: Reg,
+        msg: Reg,
+        ty: u32,
+    },
     /// Append to a list the compiler is building (never one a script can see).
     ListPushMut {
         list: Reg,
@@ -335,6 +346,8 @@ pub struct Module {
     pub kept: Vec<(u32, String)>,
     /// `test "name" { … }` blocks.
     pub tests: Vec<(String, u32)>,
+    /// The type `on receive` takes, written out, when the script has one.
+    pub inbox: Option<String>,
 }
 
 impl Module {
diff --git a/crates/frits/src/compile.rs b/crates/frits/src/compile.rs
index b53e4eb..f909df1 100644
--- a/crates/frits/src/compile.rs
+++ b/crates/frits/src/compile.rs
@@ -16,8 +16,43 @@ use crate::stdlib::Std;
 use crate::types::{FnType, 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])?;
+pub fn compile(
+    src: &str,
+    plat: &PlatformDecl,
+    library: &HashMap<String, String>,
+) -> Result<Module, Vec<Error>> {
+    compile_in(src, plat, library, &mut Vec::new(), false)
+}
+
+fn compile_in(
+    src: &str,
+    plat: &PlatformDecl,
+    library: &HashMap<String, String>,
+    stack: &mut Vec<String>,
+    is_library: bool,
+) -> Result<Module, Vec<Error>> {
+    let mut ast = crate::parser::parse(src).map_err(|e| vec![e])?;
+    if is_library {
+        let errors = crate::imports::check_library(&ast);
+        if !errors.is_empty() {
+            return Err(errors);
+        }
+    }
+    if ast.items.iter().any(|i| matches!(i, Item::Import(..))) {
+        crate::imports::resolve(&mut ast, library, &mut |name, lib_src| {
+            if stack.iter().any(|s| s == name) {
+                let path = stack.join(" → ");
+                return Err(vec![Error::new(
+                    0,
+                    format!("the imports go round: {path} → {name}"),
+                )]);
+            }
+            stack.push(name.to_string());
+            let checked = compile_in(lib_src, plat, library, stack, true).map(|_| ());
+            stack.pop();
+            checked
+        })?;
+    }
     let mut c = Compiler::new(plat);
     c.module(&ast);
     c.instances();
@@ -31,6 +66,8 @@ pub fn compile(src: &str, plat: &PlatformDecl) -> Result<Module, Vec<Error>> {
 
 struct EnumInfo {
     name: String,
+    /// Type parameters; the variants' payload types name them as `Type::Param`.
+    params: Vec<String>,
     variants: Vec<(String, Vec<Type>)>,
 }
 
@@ -108,6 +145,8 @@ struct Compiler<'p, 'a> {
     /// Generic functions compiled for one set of type arguments, by name and types.
     instance_ids: HashMap<String, u32>,
     pending: Vec<(&'a FnDecl, HashMap<String, Type>, u32)>,
+    /// What `on receive` takes, when the script has one.
+    inbox: Option<Type>,
 }
 
 impl<'p, 'a> Compiler<'p, 'a> {
@@ -132,6 +171,7 @@ impl<'p, 'a> Compiler<'p, 'a> {
             generic_fns: HashMap::new(),
             instance_ids: HashMap::new(),
             pending: Vec::new(),
+            inbox: None,
         }
     }
 
@@ -176,14 +216,27 @@ impl<'p, 'a> Compiler<'p, 'a> {
                     self.error(e.line, format!("type `{}` is defined twice", e.name));
                 }
                 self.enum_names.push(e.name.clone());
+                self.env.enum_params.insert(id, e.generics.len());
                 self.enums.push(EnumInfo {
                     name: e.name.clone(),
+                    params: e.generics.clone(),
                     variants: Vec::new(),
                 });
             }
         }
         for item in &m.items {
-            if let Item::Type(name, t, line) = item {
+            if let Item::Type(name, generics, t, line) = item {
+                if !generics.is_empty() {
+                    if self
+                        .env
+                        .generic_aliases
+                        .insert(name.clone(), (generics.clone(), t.clone()))
+                        .is_some()
+                    {
+                        self.error(*line, format!("type `{name}` is defined twice"));
+                    }
+                    continue;
+                }
                 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"));
@@ -203,7 +256,13 @@ impl<'p, 'a> Compiler<'p, 'a> {
                     {
                         self.error(e.line, format!("variant `{v}` is already defined"));
                     }
+                    self.env.generics = e
+                        .generics
+                        .iter()
+                        .map(|g| (g.clone(), Type::Param(g.as_str().into())))
+                        .collect();
                     let tys = payload.iter().map(|t| self.resolve(t)).collect();
+                    self.env.generics.clear();
                     vs.push((v.clone(), tys));
                 }
                 self.enums[id as usize].variants = vs;
@@ -251,7 +310,24 @@ impl<'p, 'a> Compiler<'p, 'a> {
         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) {
+            let event = if h.name == "receive" {
+                // Messages from other scripts: whatever one type the script names.
+                let sig = self.signature(h);
+                match sig.params.as_slice() {
+                    [t] if !t.has_fn() && !t.has_secret() => {
+                        self.inbox = Some(t.clone());
+                        self.out.inbox = Some(self.show(t));
+                    }
+                    _ => self.error(
+                        h.line,
+                        "`on receive` takes one value, without functions or Secrets in it",
+                    ),
+                }
+                Some(("receive".to_string(), sig.params))
+            } else {
+                self.plat.events.iter().find(|(n, _)| *n == h.name).cloned()
+            };
+            match event.as_ref() {
                 None => {
                     let known: Vec<_> = self.plat.events.iter().map(|(n, _)| n.as_str()).collect();
                     self.error(
@@ -302,6 +378,9 @@ impl<'p, 'a> Compiler<'p, 'a> {
                     self.error(g.line, format!("`{}` is defined twice", g.name));
                 }
                 let gi = self.globals.len() as u32;
+                if g.keep && ty.has_secret() {
+                    self.error(g.line, "a Secret is not kept: the host would have to store it");
+                }
                 if g.keep {
                     let shown = self.show(&ty);
                     self.out.kept.push((gi, shown));
@@ -1146,8 +1225,22 @@ impl<'p, 'a> Compiler<'p, 'a> {
                 self.error(line, format!("`{n}` carries values: write `{n}(…)`"));
                 return Type::Error;
             }
+            let args: Rc<[Type]> = match want {
+                Some(Type::Enum(we, args)) if *we == e => args.clone(),
+                _ if self.enums[e as usize].params.is_empty() => Rc::from([]),
+                _ => {
+                    let en = self.enums[e as usize].name.clone();
+                    self.error(
+                        line,
+                        format!(
+                            "which {en} `{n}` is, is unknown here: write its type, `let x: {en}<…> = {n}`"
+                        ),
+                    );
+                    return Type::Error;
+                }
+            };
             self.emit(Op::LoadTag { dst: r, tag });
-            return Type::Enum(e);
+            return Type::Enum(e, args);
         }
         if let Some(&f) = self.fn_index.get(n) {
             let sig = &self.fns[f as usize];
@@ -1327,14 +1420,49 @@ impl<'p, 'a> Compiler<'p, 'a> {
                         );
                         return Type::Error;
                     }
-                    let base = self.args(None, &argv, &params, &format!("`{n}`"), line);
+                    // A generic enum's arguments come from what is wanted, or
+                    // from the values given.
+                    let tparams = self.enums[e as usize].params.clone();
+                    let mut bind: HashMap<String, Type> = match want {
+                        Some(Type::Enum(we, args)) if *we == e => {
+                            tparams.iter().cloned().zip(args.iter().cloned()).collect()
+                        }
+                        _ => HashMap::new(),
+                    };
+                    if argv.len() != params.len() {
+                        self.error(
+                            line,
+                            format!("`{n}` takes {} value(s), not {}", params.len(), argv.len()),
+                        );
+                        return Type::Error;
+                    }
+                    let base = self.alloc_n(params.len());
+                    for i in needs_want_last(&argv) {
+                        let (a, p) = (argv[i], &params[i]);
+                        let w = p.subst_known(&bind);
+                        let want = if w.has_param() { None } else { Some(w) };
+                        let t = self.expr(a, Dst::To(base + i as Reg, want.as_ref()));
+                        if !p.unify(&t, &mut bind) {
+                            let (w, g) = (self.show(&p.subst(&bind)), self.show(&t));
+                            self.error(a.line, format!("expected {w}, found {g}"));
+                        }
+                    }
+                    for g in &tparams {
+                        if !bind.contains_key(g) {
+                            self.error(
+                                line,
+                                format!("what `{g}` is in this `{n}` is unknown: write its type"),
+                            );
+                            bind.insert(g.clone(), Type::Error);
+                        }
+                    }
                     self.emit(Op::MakeVariant {
                         dst: r,
                         tag,
                         base,
                         n: params.len() as u16,
                     });
-                    return Type::Enum(e);
+                    return Type::Enum(e, tparams.iter().map(|g| bind[g].clone()).collect());
                 }
                 if let Some(&decl) = self.generic_fns.get(n) {
                     return self.generic_call(decl, None, &argv, r, line);
@@ -1385,6 +1513,48 @@ impl<'p, 'a> Compiler<'p, 'a> {
                 };
                 Type::Int
             }
+            "me" => {
+                if !args.is_empty() {
+                    self.error(line, "`me` takes no arguments");
+                }
+                let Some(t) = self.inbox.clone() else {
+                    self.error(
+                        line,
+                        "this script receives nothing: add `on receive(m: T)` to have an address",
+                    );
+                    return Some(Type::Error);
+                };
+                self.emit(Op::Me { dst: r });
+                Type::Addr(Rc::new(t))
+            }
+            "send" => {
+                if args.len() != 2 {
+                    self.error(line, "`send` takes an address and a message");
+                    return Some(Type::Error);
+                }
+                if !self.f.effects.iter().any(|e| e == "Mail") {
+                    self.missing_effect("Mail", line);
+                }
+                let (to, tt) = self.expr_any(&args[0], None);
+                let Type::Addr(t) = &tt else {
+                    if tt != Type::Error {
+                        let s = self.show(&tt);
+                        self.error(line, format!("`send` sends to an Addr, not {s}"));
+                    }
+                    return Some(Type::Error);
+                };
+                let t = (**t).clone();
+                let (msg, mt) = self.expr_any(&args[1], Some(&t));
+                self.expect(&mt, &t, line);
+                let shown = self.show(&t);
+                let k = self.string(&shown);
+                let Value::Static(ty) = self.out.consts[k as usize] else {
+                    unreachable!()
+                };
+                self.emit(Op::Send { to, msg, ty });
+                self.emit(Op::LoadUnit { dst: r });
+                Type::Unit
+            }
             "log" | "warn" => {
                 let (a, t) = one(self)?;
                 self.expect(&t, &Type::Str, line);
@@ -1637,10 +1807,15 @@ impl<'p, 'a> Compiler<'p, 'a> {
                         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()) => {
+                        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 if t.has_secret() => {
+                            self.error(line, "a Secret cannot be compared: only the host can open it");
+                        }
                         t if !t.has_fn() => {
                             // Compared by value, all the way down.
                             let base = self.alloc_n(2);
@@ -1721,6 +1896,9 @@ impl<'p, 'a> Compiler<'p, 'a> {
                             self.emit(Op::BoolToStr { dst: slot, a: er });
                         }
                         Type::Error => {}
+                        t if t.has_secret() => {
+                            self.error(e.line, "a Secret cannot be written into a string");
+                        }
                         t => {
                             let s = self.show(&t);
                             self.error(e.line, format!("{s} cannot be written into a string yet"));
@@ -2047,10 +2225,8 @@ impl<'p, 'a> Compiler<'p, 'a> {
                     ("None", Type::Option(_)) => (OPTION_NONE, vec![]),
                     ("Ok", Type::Result(t, _)) => (RESULT_OK, vec![(**t).clone()]),
                     ("Err", Type::Result(_, e)) => (RESULT_ERR, vec![(**e).clone()]),
-                    (_, 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())
-                        }
+                    (_, Type::Enum(e, args)) => match self.variants.get(name) {
+                        Some(&(ve, tag)) if ve == *e => (tag, self.payload(ve, tag, args)),
                         _ => {
                             let en = self.enums[*e as usize].name.clone();
                             self.error(*vline, format!("`{name}` is not a variant of {en}"));
@@ -2114,6 +2290,12 @@ impl<'p, 'a> Compiler<'p, 'a> {
             return false;
         }
         let wild = |p: &Pattern| matches!(p, Pattern::Wild | Pattern::Bind(_));
+        // No row looks into this column: it needs no splitting. Without this a
+        // recursive type (`Tree<T>` holding a `Tree<T>`) would be split forever.
+        if rows.iter().all(|row| wild(&row[0])) {
+            let rows = rows.into_iter().map(|row| row[1..].to_vec()).collect();
+            return self.covers(rows, rest);
+        }
         let parts: Option<Vec<Type>> = match ty {
             Type::Tuple(items) => Some(items.to_vec()),
             Type::Record(fields) => Some(fields.iter().map(|(_, t)| t.clone()).collect()),
@@ -2156,7 +2338,16 @@ impl<'p, 'a> Compiler<'p, 'a> {
                 ("Ok".into(), vec![(**t).clone()]),
                 ("Err".into(), vec![(**e).clone()]),
             ]),
-            Type::Enum(e) => Some(self.enums[*e as usize].variants.clone()),
+            Type::Enum(e, args) => Some(
+                (0..self.enums[*e as usize].variants.len())
+                    .map(|tag| {
+                        (
+                            self.enums[*e as usize].variants[tag].0.clone(),
+                            self.payload(*e, tag as u32, args),
+                        )
+                    })
+                    .collect(),
+            ),
             Type::Bool => Some(vec![("true".into(), vec![]), ("false".into(), vec![])]),
             _ => None,
         };
@@ -2252,7 +2443,7 @@ impl<'p, 'a> Compiler<'p, 'a> {
         let names: Option<Vec<String>> = match &st {
             Type::Option(_) => Some(vec!["None".into(), "Some(_)".into()]),
             Type::Result(..) => Some(vec!["Ok(_)".into(), "Err(_)".into()]),
-            Type::Enum(e) => Some(
+            Type::Enum(e, _) => Some(
                 self.enums[*e as usize]
                     .variants
                     .iter()
@@ -2507,15 +2698,18 @@ impl<'p, 'a> Compiler<'p, 'a> {
             }
             i = 1;
         }
-        for a in args {
+        let skip = i;
+        for k in needs_want_last(args) {
+            let (a, i) = (args[k], skip + k);
             let p = sig.params[i].clone();
-            let want = if p.has_param() { None } else { Some(p.clone()) };
+            // What earlier arguments fixed already shapes this one: `walk(t, [])`.
+            let w = p.subst_known(&bind);
+            let want = if w.has_param() { None } else { Some(w) };
             let t = self.expr(a, Dst::To(base + i as Reg, want.as_ref()));
             if !p.unify(&t, &mut bind) {
                 let (w, g) = (self.show(&p.subst(&bind)), self.show(&t));
                 self.error(a.line, format!("expected {w}, found {g}"));
             }
-            i += 1;
         }
         for g in &decl.generics {
             if !bind.contains_key(g) {
@@ -2912,7 +3106,18 @@ impl<'p, 'a> Compiler<'p, 'a> {
     }
 
     fn plain_enum(&self, t: &Type) -> bool {
-        matches!(t, Type::Enum(e) if self.enums[*e as usize].variants.iter().all(|v| v.1.is_empty()))
+        matches!(t, Type::Enum(e, _) if self.enums[*e as usize].variants.iter().all(|v| v.1.is_empty()))
+    }
+
+    /// A variant's payload types, for an enum with these type arguments.
+    fn payload(&self, e: u32, tag: u32, args: &[Type]) -> Vec<Type> {
+        let info = &self.enums[e as usize];
+        let bind: HashMap<String, Type> = info.params.iter().cloned().zip(args.iter().cloned()).collect();
+        info.variants[tag as usize]
+            .1
+            .iter()
+            .map(|t| t.subst(&bind))
+            .collect()
     }
 
     fn len_of(&mut self, rr: Reg, t: &Type, r: Reg) {
@@ -3096,6 +3301,21 @@ impl<'p, 'a> Compiler<'p, 'a> {
     }
 }
 
+/// The order to compile arguments in: values that take their type from what
+/// is wanted (`None`, `Leaf`, `[]`, `[:]`) last, after the others have fixed
+/// the type parameters they need.
+fn needs_want_last(args: &[&Expr]) -> Vec<usize> {
+    let needs = |e: &Expr| match &e.kind {
+        ExprKind::Ident(n) => n.starts_with(|c: char| c.is_ascii_uppercase()),
+        ExprKind::List(items) => items.is_empty(),
+        ExprKind::MapLit(entries) => entries.is_empty(),
+        _ => false,
+    };
+    let (mut first, last): (Vec<usize>, Vec<usize>) = (0..args.len()).partition(|&i| !needs(args[i]));
+    first.extend(last);
+    first
+}
+
 /// Every name a block mentions, to find what a closure must capture. It may
 /// include names the block declares itself; capturing those costs a copy only.
 fn free_block(b: &Block, out: &mut Vec<String>) {
diff --git a/crates/frits/src/imports.rs b/crates/frits/src/imports.rs
new file mode 100644
index 0000000..1bfa516
--- /dev/null
+++ b/crates/frits/src/imports.rs
@@ -0,0 +1,424 @@
+//! `import geometry`: libraries merged into a script before it is checked.
+//!
+//! A library is Frits source the host supplies by name (`Platform::library`):
+//! functions, types, enums and tests, no `script` line, handlers or globals. Its
+//! names become `geometry.clamp` and `geometry.Box`; a script calls
+//! `geometry.clamp(x)` and writes the type `geometry.Box`. Each library is first
+//! checked on its own, so a mistake in it is reported against the library.
+//! Enum variants keep their plain names, so two libraries cannot both have a
+//! variant called `Open`.
+
+use std::collections::{HashMap, HashSet};
+
+use crate::Error;
+use crate::ast::*;
+
+/// Checks one library on its own: its name and source.
+pub type CheckLibrary<'a> = dyn FnMut(&str, &str) -> Result<(), Vec<Error>> + 'a;
+
+/// Merge every library `m` imports, directly or through another library.
+pub fn resolve(
+    m: &mut Module,
+    library: &HashMap<String, String>,
+    check: &mut CheckLibrary,
+) -> Result<(), Vec<Error>> {
+    let mut errors = Vec::new();
+    let mut loaded: Vec<(String, Module)> = Vec::new();
+    let mut queue: Vec<(String, u32)> = imports_of(m);
+    let mut seen: HashSet<String> = HashSet::new();
+    while let Some((name, line)) = queue.pop() {
+        if !seen.insert(name.clone()) {
+            continue;
+        }
+        let Some(src) = library.get(&name) else {
+            let known: Vec<&str> = library.keys().map(|s| s.as_str()).collect();
+            errors.push(Error::new(
+                line,
+                format!(
+                    "there is no library `{name}` (libraries: {})",
+                    if known.is_empty() {
+                        "none".to_string()
+                    } else {
+                        known.join(", ")
+                    }
+                ),
+            ));
+            continue;
+        };
+        if let Err(es) = check(&name, src) {
+            for e in es {
+                errors.push(Error::new(line, format!("in library `{name}`, {e}")));
+            }
+            continue;
+        }
+        let lib = match crate::parser::parse(src) {
+            Ok(lib) => lib,
+            Err(e) => {
+                errors.push(Error::new(line, format!("in library `{name}`, {e}")));
+                continue;
+            }
+        };
+        queue.extend(imports_of(&lib));
+        loaded.push((name, lib));
+    }
+    if !errors.is_empty() {
+        return Err(errors);
+    }
+    let aliases: HashSet<String> = loaded.iter().map(|(n, _)| n.clone()).collect();
+    let none = HashSet::new();
+    Renamer::new(None, &none, &none, &aliases).module(m);
+    let mut merged = Vec::new();
+    for (name, mut lib) in loaded {
+        let (fns, types) = own_names(&lib);
+        Renamer::new(Some(&name), &fns, &types, &aliases).module(&mut lib);
+        merged.extend(
+            lib.items
+                .into_iter()
+                .filter(|i| !matches!(i, Item::Import(..) | Item::Test(..))),
+        );
+    }
+    merged.append(&mut m.items);
+    m.items = merged;
+    Ok(())
+}
+
+fn imports_of(m: &Module) -> Vec<(String, u32)> {
+    m.items
+        .iter()
+        .filter_map(|i| {
+            if let Item::Import(n, l) = i {
+                Some((n.clone(), *l))
+            } else {
+                None
+            }
+        })
+        .collect()
+}
+
+/// What a library may hold; anything else is reported by `check_library`.
+pub fn check_library(m: &Module) -> Vec<Error> {
+    let mut errors = Vec::new();
+    if !m.effects.is_empty() {
+        errors.push(Error::new(
+            1,
+            "a library has no `script` line: each function says what it does",
+        ));
+    }
+    for item in &m.items {
+        match item {
+            Item::On(f) => errors.push(Error::new(
+                f.line,
+                "a library has no handlers: `on` belongs in a script",
+            )),
+            Item::Global(g) => errors.push(Error::new(
+                g.line,
+                "a library has no `let` or `var` at the top: put the value in a function",
+            )),
+            _ => {}
+        }
+    }
+    errors
+}
+
+fn own_names(m: &Module) -> (HashSet<String>, HashSet<String>) {
+    let mut fns = HashSet::new();
+    let mut types = HashSet::new();
+    for item in &m.items {
+        match item {
+            Item::Fn(f) => {
+                fns.insert(f.name.clone());
+            }
+            Item::Enum(e) => {
+                types.insert(e.name.clone());
+            }
+            Item::Type(n, _, _, _) => {
+                types.insert(n.clone());
+            }
+            _ => {}
+        }
+    }
+    (fns, types)
+}
+
+/// Renames a library's own names to `lib.name`, and in any module turns
+/// `lib.f` (a field of an imported library's name) into the one name
+/// `lib.f`. Tracks local variables, so a local that shares a name with a
+/// function is left alone.
+struct Renamer<'a> {
+    prefix: Option<&'a str>,
+    fns: &'a HashSet<String>,
+    types: &'a HashSet<String>,
+    aliases: &'a HashSet<String>,
+    scopes: Vec<Vec<String>>,
+    generics: Vec<String>,
+}
+
+impl<'a> Renamer<'a> {
+    fn new(
+        prefix: Option<&'a str>,
+        fns: &'a HashSet<String>,
+        types: &'a HashSet<String>,
+        aliases: &'a HashSet<String>,
+    ) -> Self {
+        Renamer {
+            prefix,
+            fns,
+            types,
+            aliases,
+            scopes: Vec::new(),
+            generics: Vec::new(),
+        }
+    }
+
+    fn local(&self, n: &str) -> bool {
+        self.scopes.iter().any(|s| s.iter().any(|x| x == n))
+    }
+
+    fn declare(&mut self, n: &str) {
+        if let Some(s) = self.scopes.last_mut() {
+            s.push(n.to_string());
+        }
+    }
+
+    fn prefixed(&self, n: &str) -> String {
+        format!("{}.{n}", self.prefix.unwrap_or(""))
+    }
+
+    fn module(&mut self, m: &mut Module) {
+        for item in &mut m.items {
+            match item {
+                Item::Fn(f) | Item::On(f) => self.function(f),
+                Item::Enum(e) => {
+                    if self.prefix.is_some() {
+                        e.name = self.prefixed(&e.name);
+                    }
+                    self.generics = e.generics.clone();
+                    for (_, payload) in &mut e.variants {
+                        payload.iter_mut().for_each(|t| self.ty(t));
+                    }
+                    self.generics.clear();
+                }
+                Item::Type(n, generics, t, _) => {
+                    if self.prefix.is_some() {
+                        *n = self.prefixed(n);
+                    }
+                    self.generics = generics.clone();
+                    self.ty(t);
+                    self.generics.clear();
+                }
+                Item::Global(g) => {
+                    if let Some(t) = &mut g.ty {
+                        self.ty(t);
+                    }
+                    self.scopes.push(Vec::new());
+                    self.expr(&mut g.value);
+                    self.scopes.pop();
+                }
+                Item::Test(_, b, _) => self.block(b),
+                _ => {}
+            }
+        }
+        // Function names last, so calls inside bodies were matched on the old names.
+        if self.prefix.is_some() {
+            for item in &mut m.items {
+                if let Item::Fn(f) = item {
+                    f.name = self.prefixed(&f.name);
+                }
+            }
+        }
+    }
+
+    fn function(&mut self, f: &mut FnDecl) {
+        self.generics = f.generics.clone();
+        for (_, t) in &mut f.params {
+            self.ty(t);
+        }
+        if let Some(t) = &mut f.ret {
+            self.ty(t);
+        }
+        self.scopes
+            .push(f.params.iter().map(|(n, _)| n.clone()).collect());
+        if let Some(b) = &mut f.body {
+            self.block(b);
+        }
+        self.scopes.pop();
+        self.generics.clear();
+    }
+
+    fn ty(&mut self, t: &mut TypeExpr) {
+        match t {
+            TypeExpr::Named(n, args, _) => {
+                if self.prefix.is_some() && !self.generics.contains(n) && self.types.contains(n.as_str()) {
+                    *n = self.prefixed(n);
+                }
+                args.iter_mut().for_each(|a| self.ty(a));
+            }
+            TypeExpr::Record(fields, _) => fields.iter_mut().for_each(|(_, t)| self.ty(t)),
+            TypeExpr::Tuple(items, _) => items.iter_mut().for_each(|t| self.ty(t)),
+            TypeExpr::Fn(params, ret, _, _) => {
+                params.iter_mut().for_each(|t| self.ty(t));
+                if let Some(r) = ret {
+                    self.ty(r);
+                }
+            }
+        }
+    }
+
+    fn block(&mut self, b: &mut Block) {
+        self.scopes.push(Vec::new());
+        for s in &mut b.stmts {
+            self.stmt(s);
+        }
+        if let Some(t) = &mut b.tail {
+            self.expr(t);
+        }
+        self.scopes.pop();
+    }
+
+    fn stmt(&mut self, s: &mut Stmt) {
+        match s {
+            Stmt::Let { name, ty, value, .. } => {
+                if let Some(t) = ty {
+                    self.ty(t);
+                }
+                self.expr(value);
+                let n = name.clone();
+                self.declare(&n);
+            }
+            Stmt::LetPat { pattern, value, .. } => {
+                self.expr(value);
+                let mut binds = Vec::new();
+                binds_of(pattern, &mut binds);
+                binds.iter().for_each(|n| self.declare(n));
+            }
+            Stmt::Assign { target, value, .. } => {
+                self.expr(target);
+                self.expr(value);
+            }
+            Stmt::Expr(e) => self.expr(e),
+            Stmt::While { cond, body, .. } => {
+                self.expr(cond);
+                self.block(body);
+            }
+            Stmt::For { var, iter, body, .. } => {
+                match iter {
+                    ForIter::Range(a, b) => {
+                        self.expr(a);
+                        self.expr(b);
+                    }
+                    ForIter::List(e) => self.expr(e),
+                }
+                self.scopes.push(vec![var.clone()]);
+                self.block(body);
+                self.scopes.pop();
+            }
+            Stmt::Return(Some(e), _) => self.expr(e),
+            _ => {}
+        }
+    }
+
+    fn expr(&mut self, e: &mut Expr) {
+        // `lib.f` → the one name `lib.f`, unless `lib` is a local.
+        if let ExprKind::Field(base, f) = &e.kind
+            && let ExprKind::Ident(a) = &base.kind
+            && self.aliases.contains(a)
+            && !self.local(a)
+        {
+            // Variants keep their plain names: `geometry.Left` is `Left`.
+            e.kind = if f.starts_with(|c: char| c.is_ascii_uppercase()) {
+                ExprKind::Ident(f.clone())
+            } else {
+                ExprKind::Ident(format!("{a}.{f}"))
+            };
+            return;
+        }
+        match &mut e.kind {
+            ExprKind::Ident(n) => {
+                if self.prefix.is_some() && !self.local(n) && self.fns.contains(n.as_str()) {
+                    *n = self.prefixed(n);
+                }
+            }
+            ExprKind::Field(b, _) | ExprKind::Unary(_, b) | ExprKind::Try(b) => self.expr(b),
+            ExprKind::Call(c, args) => {
+                self.expr(c);
+                args.iter_mut().for_each(|a| self.expr(a));
+            }
+            ExprKind::Index(a, b) | ExprKind::Binary(_, a, b) => {
+                self.expr(a);
+                self.expr(b);
+            }
+            ExprKind::If(c, then, els) => {
+                self.expr(c);
+                self.block(then);
+                if let Some(e) = els {
+                    self.expr(e);
+                }
+            }
+            ExprKind::IfLet(p, v, then, els) => {
+                self.expr(v);
+                let mut binds = Vec::new();
+                binds_of(p, &mut binds);
+                self.scopes.push(binds);
+                self.block(then);
+                self.scopes.pop();
+                if let Some(e) = els {
+                    self.expr(e);
+                }
+            }
+            ExprKind::Match(s, arms) => {
+                self.expr(s);
+                for a in arms {
+                    let mut binds = Vec::new();
+                    binds_of(&a.pattern, &mut binds);
+                    self.scopes.push(binds);
+                    if let Some(g) = &mut a.guard {
+                        self.expr(g);
+                    }
+                    self.expr(&mut a.body);
+                    self.scopes.pop();
+                }
+            }
+            ExprKind::Block(b) => self.block(b),
+            ExprKind::Record(fields, spread) => {
+                fields.iter_mut().for_each(|(_, e)| self.expr(e));
+                if let Some(s) = spread {
+                    self.expr(s);
+                }
+            }
+            ExprKind::List(items) | ExprKind::Tuple(items) => items.iter_mut().for_each(|e| self.expr(e)),
+            ExprKind::MapLit(entries) => entries.iter_mut().for_each(|(k, v)| {
+                self.expr(k);
+                self.expr(v);
+            }),
+            ExprKind::Lambda(l) => {
+                for (_, t) in &mut l.params {
+                    if let Some(t) = t {
+                        self.ty(t);
+                    }
+                }
+                if let Some(t) = &mut l.ret {
+                    self.ty(t);
+                }
+                self.scopes
+                    .push(l.params.iter().map(|(n, _)| n.clone()).collect());
+                self.block(&mut l.body);
+                self.scopes.pop();
+            }
+            ExprKind::Template(parts) => parts.iter_mut().for_each(|p| {
+                if let TPart::Hole(e, _) = p {
+                    self.expr(e);
+                }
+            }),
+            ExprKind::Int(_) | ExprKind::Float(_) | ExprKind::Bool(_) | ExprKind::Str(_) => {}
+        }
+    }
+}
+
+fn binds_of(p: &Pattern, out: &mut Vec<String>) {
+    match p {
+        Pattern::Bind(n) => out.push(n.clone()),
+        Pattern::Variant(_, subs, _) | Pattern::Tuple(subs) => subs.iter().for_each(|s| binds_of(s, out)),
+        Pattern::Record(fields, _, _) => fields.iter().for_each(|(_, s)| binds_of(s, out)),
+        _ => {}
+    }
+}
diff --git a/crates/frits/src/lib.rs b/crates/frits/src/lib.rs
index 537c6bd..1a8b57c 100644
--- a/crates/frits/src/lib.rs
+++ b/crates/frits/src/lib.rs
@@ -9,6 +9,7 @@
 pub mod ast;
 pub mod bytecode;
 pub mod compile;
+pub mod imports;
 pub mod lexer;
 pub mod parser;
 pub mod platform;
diff --git a/crates/frits/src/parser.rs b/crates/frits/src/parser.rs
index e6f0934..4b7ef42 100644
--- a/crates/frits/src/parser.rs
+++ b/crates/frits/src/parser.rs
@@ -143,9 +143,20 @@ impl Parser {
                 Tok::Kw(Kw::Type) => {
                     self.next();
                     let name = self.ident()?;
+                    let generics = self.generics()?;
                     self.expect_sym("=")?;
                     let ty = self.type_expr()?;
-                    m.items.push(Item::Type(name, ty, line));
+                    m.items.push(Item::Type(name, generics, ty, line));
+                }
+                Tok::Ident(w) if w == "import" && matches!(self.peek_at(1), Tok::Ident(_)) => {
+                    self.next();
+                    let name = self.ident()?;
+                    m.items.push(Item::Import(name, line));
+                }
+                Tok::Ident(w) if w == "opaque" && matches!(self.peek_at(1), Tok::Ident(_)) => {
+                    self.next();
+                    let name = self.ident()?;
+                    m.items.push(Item::Opaque(name, line));
                 }
                 Tok::Ident(w) if w == "test" && matches!(self.peek_at(1), Tok::Str(_)) => {
                     self.next();
@@ -256,8 +267,18 @@ impl Parser {
         })
     }
 
+    fn generics(&mut self) -> R<Vec<Name>> {
+        if !self.eat_sym("<") {
+            return Ok(Vec::new());
+        }
+        let g = self.name_list()?;
+        self.expect_sym(">")?;
+        Ok(g)
+    }
+
     fn enum_decl(&mut self, line: u32) -> R<EnumDecl> {
         let name = self.ident()?;
+        let generics = self.generics()?;
         self.expect_sym("{")?;
         let mut variants = Vec::new();
         loop {
@@ -284,7 +305,12 @@ impl Parser {
                 break;
             }
         }
-        Ok(EnumDecl { name, variants, line })
+        Ok(EnumDecl {
+            name,
+            generics,
+            variants,
+            line,
+        })
     }
 
     fn namespace(&mut self, effect: bool) -> R<Namespace> {
@@ -373,7 +399,12 @@ impl Parser {
             }
             return Ok(TypeExpr::Record(fields, line));
         }
-        let name = self.ident()?;
+        let mut name = self.ident()?;
+        // A library's type: `geometry.Box`.
+        if self.is_sym(".") && matches!(self.peek_at(1), Tok::Ident(_)) {
+            self.next();
+            name = format!("{name}.{}", self.ident()?);
+        }
         let mut args = Vec::new();
         if self.eat_sym("<") {
             loop {
@@ -752,7 +783,18 @@ impl Parser {
                         None
                     };
                     self.expect_sym("=>")?;
-                    let body = self.expr()?;
+                    // An arm may be a statement: `Add(n) => sum += n`.
+                    let body_line = self.line();
+                    let body = match self.stmt()? {
+                        Stmt::Expr(e) => e,
+                        s => Expr {
+                            kind: ExprKind::Block(Block {
+                                stmts: vec![s],
+                                tail: None,
+                            }),
+                            line: body_line,
+                        },
+                    };
                     arms.push(Arm { pattern, guard, body });
                     self.eat_sym(",");
                 }
diff --git a/crates/frits/src/platform.rs b/crates/frits/src/platform.rs
index 3172b9a..4a1ad3b 100644
--- a/crates/frits/src/platform.rs
+++ b/crates/frits/src/platform.rs
@@ -93,6 +93,8 @@ pub struct Platform<S> {
     /// Compiled modules by source, so a thousand prims with one script share
     /// one module. Weak: a module nobody runs is dropped.
     cache: RefCell<HashMap<String, Weak<Module>>>,
+    /// Libraries a script can `import`, by name.
+    library: RefCell<HashMap<String, String>>,
 }
 
 impl<S> Platform<S> {
@@ -104,6 +106,7 @@ impl<S> Platform<S> {
             consts: vec![None; decl.consts.len()],
             decl,
             cache: RefCell::default(),
+            library: RefCell::default(),
         };
         crate::prelude::bind(&mut p);
         Ok(p)
@@ -147,12 +150,21 @@ impl<S> Platform<S> {
             .collect()
     }
 
+    /// Offer `src` to scripts as the library `name` (`import name`). Replacing a
+    /// library forgets every compiled module, since any may have imported it.
+    pub fn set_library(&self, name: &str, src: &str) {
+        self.library
+            .borrow_mut()
+            .insert(name.to_string(), src.to_string());
+        self.cache.borrow_mut().clear();
+    }
+
     /// Compile `src`, or hand back the module already compiled from it.
     pub fn compile(&self, src: &str) -> Result<Rc<Module>, Vec<Error>> {
         if let Some(m) = self.cache.borrow().get(src).and_then(Weak::upgrade) {
             return Ok(m);
         }
-        let m = Rc::new(crate::compile::compile(src, &self.decl)?);
+        let m = Rc::new(crate::compile::compile(src, &self.decl, &self.library.borrow())?);
         let mut cache = self.cache.borrow_mut();
         if cache.len() >= 64 && cache.len().is_power_of_two() {
             cache.retain(|_, w| w.strong_count() > 0);
diff --git a/crates/frits/src/prelude.rs b/crates/frits/src/prelude.rs
index e52c9e2..05cf1d9 100644
--- a/crates/frits/src/prelude.rs
+++ b/crates/frits/src/prelude.rs
@@ -7,6 +7,10 @@ use crate::value::{HostValue, Value};
 pub const DECL: &str = "
 type Vec3 = { x: Float, y: Float, z: Float }
 
+// Sending to other scripts: `send(addr, msg)`.
+effect Mail {
+}
+
 effect Random {
     // From 0 up to (not including) 1.
     fn float() -> Float
diff --git a/crates/frits/src/runtime.rs b/crates/frits/src/runtime.rs
index 72adc2f..bf225e1 100644
--- a/crates/frits/src/runtime.rs
+++ b/crates/frits/src/runtime.rs
@@ -33,6 +33,11 @@ pub struct Runtime<S> {
     procs: Vec<Option<Process<S>>>,
     free: Vec<Pid>,
     spawned: u64,
+    /// How often each pid has been reused, so an old address never reaches the
+    /// process that took its place.
+    generations: Vec<u32>,
+    /// Messages that found no receiver since the host last asked.
+    pub undelivered: u64,
 }
 
 /// How one `test` block went.
@@ -51,6 +56,8 @@ impl<S> Runtime<S> {
             procs: Vec::new(),
             free: Vec::new(),
             spawned: 0,
+            generations: Vec::new(),
+            undelivered: 0,
         }
     }
 
@@ -59,15 +66,45 @@ impl<S> Runtime<S> {
         let mut p = Process::new(module, state);
         self.spawned += 1;
         p.seed(self.spawned);
-        match self.free.pop() {
+        let pid = match self.free.pop() {
             Some(pid) => {
-                self.procs[pid as usize] = Some(p);
+                self.generations[pid as usize] += 1;
                 pid
             }
             None => {
-                self.procs.push(Some(p));
+                self.procs.push(None);
+                self.generations.push(0);
                 self.procs.len() as Pid - 1
             }
+        };
+        p.addr = self.addr_of(pid);
+        self.procs[pid as usize] = Some(p);
+        pid
+    }
+
+    /// The address `me()` gives in process `pid`, for a host to hand out.
+    pub fn addr_of(&self, pid: Pid) -> i64 {
+        ((self.generations[pid as usize] as i64) << 32) | pid as i64
+    }
+
+    /// Hand every sent message to its receiver's mailbox, copied. A message to
+    /// a process that is gone, or whose inbox takes another type, is dropped
+    /// and counted in `undelivered`.
+    pub fn deliver(&mut self) {
+        let mut mail = Vec::new();
+        for p in self.procs.iter_mut().flatten() {
+            mail.append(&mut p.outbox);
+        }
+        for (to, ty, msg) in mail {
+            let pid = (to & 0xFFFF_FFFF) as usize;
+            let generation = (to >> 32) as u32;
+            let ok = self.generations.get(pid) == Some(&generation)
+                && self.procs[pid].as_mut().is_some_and(|p| {
+                    p.module.inbox.as_deref() == Some(ty.as_str()) && p.post("receive", vec![msg])
+                });
+            if !ok {
+                self.undelivered += 1;
+            }
         }
     }
 
@@ -98,8 +135,15 @@ impl<S> Runtime<S> {
         Some(p.run(&self.platform, limits.fuel, limits.memory))
     }
 
-    /// One slice for every process with work. Returns the ones that died.
+    /// One slice for every process with work, then the messages they sent
+    /// are delivered (they run on the next tick). Returns the ones that died.
     pub fn tick(&mut self) -> Vec<(Pid, String)> {
+        let died = self.run_all();
+        self.deliver();
+        died
+    }
+
+    fn run_all(&mut self) -> Vec<(Pid, String)> {
         let limits = self.limits;
         let mut died = Vec::new();
         for (pid, slot) in self.procs.iter_mut().enumerate() {
diff --git a/crates/frits/src/tests.rs b/crates/frits/src/tests.rs
index 4dc2c8f..a88d9da 100644
--- a/crates/frits/src/tests.rs
+++ b/crates/frits/src/tests.rs
@@ -2,6 +2,13 @@ use crate::*;
 
 const DECL: &str = "
 type Geo = { lat: Float, lng: Float }
+opaque Door
+effect Vault {
+    fn key() -> Secret<Str>
+    fn unlock(k: Secret<Str>) -> Bool
+    fn door() -> Door
+    fn knock(d: Door) -> Str
+}
 effect Out {
     fn say(text: Str)
     fn here() -> Geo
@@ -46,7 +53,13 @@ fn platform() -> Platform<Log> {
         cx.charge(5_000);
         Ok(Value::Unit)
     })
-    .bind("Net.get", |_, _| Err("no network in tests".into()));
+    .bind("Net.get", |_, _| Err("no network in tests".into()))
+    .bind("Vault.key", |cx, _| Ok(cx.new_str("hunter2")))
+    .bind("Vault.unlock", |cx, a| Ok(Value::Bool(cx.str(a[0]) == "hunter2")))
+    .bind("Vault.door", |_, _| Ok(Value::Int(7)))
+    .bind("Vault.knock", |cx, a| {
+        Ok(cx.new_str(&format!("door {}", a[0].int())))
+    });
     assert!(p.unbound().is_empty(), "{:?}", p.unbound());
     p
 }
@@ -646,3 +659,213 @@ fn one_source_compiles_once() {
     let b = p.compile("script / Out\non go() { }").unwrap();
     assert!(std::rc::Rc::ptr_eq(&a, &b));
 }
+
+#[test]
+fn imports_bring_in_a_library() {
+    let p = platform();
+    p.set_library(
+        "geometry",
+        "type Box = { w: Float, h: Float }
+        enum Turn { Left, Right }
+        fn area(b: Box) -> Float { b.w * b.h }
+        fn grow(b: Box, by: Float) -> Box { { w: b.w + by, h: b.h + by } }
+        fn twice(b: Box) -> Float { let area = 2.0\n area * area_of(b) }
+        fn area_of(b: Box) -> Float { area(b) }
+        test \"area\" { assert(area({ w: 2, h: 3 }) == 6) }",
+    );
+    let mut rt = Runtime::new(p);
+    let m = rt
+        .platform
+        .compile(
+            "script / Out
+            import geometry
+            on go() {
+                let b: geometry.Box = { w: 2, h: 3 }
+                let turn = geometry.Left
+                Out.say(\"{geometry.area(geometry.grow(b, 1))} {geometry.twice(b)}\")
+            }",
+        )
+        .unwrap_or_else(|e| panic!("{e:?}"));
+    let pid = rt.spawn(m, Log::default());
+    rt.post(pid, "go", Vec::new());
+    rt.tick();
+    assert_eq!(rt.get(pid).unwrap().state.0, ["12 12"]);
+}
+
+#[test]
+fn a_broken_or_missing_library_is_reported_against_the_import() {
+    let p = platform();
+    p.set_library("bad", "fn f() -> Int { \"x\" }");
+    p.set_library("loop_a", "import loop_b\nfn a() { }");
+    p.set_library("loop_b", "import loop_a\nfn b() { }");
+    p.set_library("scripty", "on go() { }");
+    let errs = |src: &str| -> Vec<String> {
+        p.compile(src)
+            .err()
+            .unwrap()
+            .into_iter()
+            .map(|e| e.to_string())
+            .collect()
+    };
+    let e = errs("script / Out\nimport bad");
+    assert!(
+        e[0].contains("line 2: in library `bad`, line 1: expected Int, found Str"),
+        "{e:?}"
+    );
+    let e = errs("import nothing_here");
+    assert!(e[0].contains("there is no library `nothing_here`"), "{e:?}");
+    let e = errs("import loop_a");
+    assert!(e.iter().any(|e| e.contains("the imports go round")), "{e:?}");
+    let e = errs("import scripty");
+    assert!(e[0].contains("a library has no handlers"), "{e:?}");
+}
+
+#[test]
+fn scripts_send_each_other_typed_messages() {
+    let mut rt = Runtime::new(platform());
+    let counter = rt
+        .platform
+        .compile(
+            "script / Out, Mail
+            enum Ask { Add(Int), Total(Addr<Int>) }
+            var sum = 0
+            on receive(m: Ask) {
+                match m {
+                    Add(n) => sum += n,
+                    Total(reply) => send(reply, sum),
+                }
+            }",
+        )
+        .unwrap();
+    let asker = rt
+        .platform
+        .compile(
+            "script / Out, Mail
+            enum Ask { Add(Int), Total(Addr<Int>) }
+            on msg(to: Int, t: Str) { }
+            on receive(total: Int) { Out.say(\"total {total}\") }",
+        )
+        .unwrap();
+    let c = rt.spawn(counter, Log::default());
+    let a = rt.spawn(asker, Log::default());
+    // The host introduces them: it posts the counter's address as a message.
+    let c_addr = rt.addr_of(c);
+    let a_addr = rt.addr_of(a);
+    let ask = |n: u32, v: Vec<HostValue>| HostValue::Variant(n, v);
+    rt.get_mut(a)
+        .unwrap()
+        .outbox
+        .push((c_addr, "Ask".into(), ask(0, vec![HostValue::Int(4)])));
+    rt.get_mut(a)
+        .unwrap()
+        .outbox
+        .push((c_addr, "Ask".into(), ask(0, vec![HostValue::Int(5)])));
+    rt.get_mut(a)
+        .unwrap()
+        .outbox
+        .push((c_addr, "Ask".into(), ask(1, vec![HostValue::Int(a_addr)])));
+    // A message of the wrong type is dropped, not delivered.
+    rt.get_mut(a)
+        .unwrap()
+        .outbox
+        .push((c_addr, "Int".into(), HostValue::Int(1)));
+    for _ in 0..4 {
+        rt.tick();
+    }
+    assert_eq!(rt.get(a).unwrap().state.0, ["total 9"]);
+    assert_eq!(rt.undelivered, 1);
+    // An address outlives its process without reaching the next one.
+    rt.kill(c);
+    let again = rt
+        .platform
+        .compile("script / Out\non receive(m: Int) { Out.say(\"wrong\") }")
+        .unwrap();
+    let c2 = rt.spawn(again, Log::default());
+    assert_eq!(c2, c);
+    rt.get_mut(a)
+        .unwrap()
+        .outbox
+        .push((c_addr, "Int".into(), HostValue::Int(1)));
+    rt.tick();
+    rt.tick();
+    assert!(rt.get(c2).unwrap().state.0.is_empty());
+}
+
+#[test]
+fn me_and_send_need_an_inbox_and_mail() {
+    let e = errors("script / Out\non go() { let a = me() }");
+    assert!(e[0].contains("receives nothing"), "{e:?}");
+    let e = errors("script / Out\non receive(n: Int) { send(me(), n) }");
+    assert!(e[0].contains("`Mail`"), "{e:?}");
+    let e = errors("script / Out, Mail\non receive(n: Int) { send(me(), \"x\") }");
+    assert!(e[0].contains("expected Int, found Str"), "{e:?}");
+}
+
+#[test]
+fn a_secret_can_be_passed_on_but_never_seen() {
+    let out = said(
+        "script / Out, Vault
+        fn try_it(k: Secret<Str>) -> Bool / Vault { Vault.unlock(k) }
+        on go() {
+            let k = Vault.key()
+            let d = Vault.door()
+            Out.say(\"{try_it(k)} {Vault.knock(d)}\")
+        }",
+    );
+    assert_eq!(out, ["true door 7"]);
+    for (src, want) in [
+        (
+            "on go() { let k = Vault.key()\n let s = \"{k}\" }",
+            "cannot be written into a string",
+        ),
+        (
+            "on go() { let k = Vault.key()\n let b = k == k }",
+            "cannot be compared",
+        ),
+        (
+            "on go() { let k = Vault.key()\n log(k) }",
+            "expected Str, found Secret<Str>",
+        ),
+        ("keep var k: Option<Secret<Str>> = None", "is not kept"),
+        ("on receive(k: Secret<Str>) { }", "without functions or Secrets"),
+    ] {
+        let e = errors(&format!("script / Out, Vault\n{src}"));
+        assert!(e.iter().any(|e| e.contains(want)), "{src}: {e:?}");
+    }
+}
+
+#[test]
+fn generic_types() {
+    let out = said(
+        "script / Out
+        enum Tree<T> { Leaf, Node(Tree<T>, T, Tree<T>) }
+        type Pair<A, B> = { first: A, second: B }
+        fn insert(t: Tree<Int>, x: Int) -> Tree<Int> {
+            match t {
+                Leaf => Node(Leaf, x, Leaf),
+                Node(l, v, r) if x < v => Node(insert(l, x), v, r),
+                Node(l, v, r) => Node(l, v, insert(r, x)),
+            }
+        }
+        fn walk<T>(t: Tree<T>, out: List<T>) -> List<T> {
+            match t {
+                Leaf => out,
+                Node(l, v, r) => walk(r, walk(l, out) + [v]),
+            }
+        }
+        on go() {
+            var t: Tree<Int> = Leaf
+            for x in [5, 2, 8, 1] { t = insert(t, x) }
+            let p: Pair<Str, Int> = { first: \"n\", second: len(walk(t, [])) }
+            let words = Node(Leaf, \"mid\", Leaf)
+            Out.say(\"{walk(t, []).map(fn(x) { \"{x}\" }).join(\",\")} {p.first}{p.second} {len(walk(words, []))}\")
+        }",
+    );
+    assert_eq!(out, ["1,2,5,8 n4 1"]);
+    let e = errors("script / Out\nenum Box<T> { Empty, Full(T) }\non go() { let b = Empty }");
+    assert!(e[0].contains("is unknown here"), "{e:?}");
+    let e = errors(
+        "script / Out\nenum Box<T> { Empty, Full(T) }\nfn f(b: Box<Int>) -> Int { match b { Full(n) => n } }",
+    );
+    assert!(e[0].contains("misses: Empty"), "{e:?}");
+}
diff --git a/crates/frits/src/types.rs b/crates/frits/src/types.rs
index c30dcf5..3daa9a1 100644
--- a/crates/frits/src/types.rs
+++ b/crates/frits/src/types.rs
@@ -25,10 +25,19 @@ pub enum Type {
     Fn(Rc<FnType>),
     /// A generic function's type parameter, before a call fixes it.
     Param(Rc<str>),
+    /// A value a script can hold and pass on but never see: it cannot be
+    /// written into a string, compared, logged or kept. Only the host makes one
+    /// and only a host function taking a `Secret` can open it.
+    Secret(Rc<Type>),
+    /// `opaque Door` in a platform declaration: a right only the host can make.
+    Opaque(Rc<str>),
+    /// The address of a script whose `on receive` takes a T.
+    Addr(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),
+    /// An enum, with its type arguments when it is generic.
+    Enum(u32, Rc<[Type]>),
     /// What `return` and `panic` evaluate to: fits wherever a value is wanted.
     Never,
     /// Stands in after an error, so one mistake is reported once.
@@ -82,13 +91,25 @@ impl Type {
         }
     }
 
+    /// Does a value of this type hold a Secret anywhere?
+    pub fn has_secret(&self) -> bool {
+        match self {
+            Type::Secret(_) => true,
+            Type::List(t) | Type::Option(t) => t.has_secret(),
+            Type::Map(a, b) | Type::Result(a, b) => a.has_secret() || b.has_secret(),
+            Type::Tuple(ts) | Type::Enum(_, ts) => ts.iter().any(Type::has_secret),
+            Type::Record(fs) => fs.iter().any(|(_, t)| t.has_secret()),
+            _ => false,
+        }
+    }
+
     /// Does a value of this type hold a function anywhere?
     pub fn has_fn(&self) -> bool {
         match self {
             Type::Fn(_) => true,
             Type::List(t) | Type::Option(t) => t.has_fn(),
             Type::Map(a, b) | Type::Result(a, b) => a.has_fn() || b.has_fn(),
-            Type::Tuple(ts) => ts.iter().any(Type::has_fn),
+            Type::Tuple(ts) | Type::Enum(_, ts) => ts.iter().any(Type::has_fn),
             Type::Record(fs) => fs.iter().any(|(_, t)| t.has_fn()),
             // An enum's payloads are not looked into here; compared, a function
             // in one compares as never equal.
@@ -99,29 +120,50 @@ impl Type {
     pub fn has_param(&self) -> bool {
         match self {
             Type::Param(_) => true,
-            Type::List(t) | Type::Option(t) => t.has_param(),
+            Type::List(t) | Type::Option(t) | Type::Secret(t) | Type::Addr(t) => t.has_param(),
             Type::Map(a, b) | Type::Result(a, b) => a.has_param() || b.has_param(),
-            Type::Tuple(ts) => ts.iter().any(Type::has_param),
+            Type::Tuple(ts) | Type::Enum(_, ts) => ts.iter().any(Type::has_param),
             Type::Record(fs) => fs.iter().any(|(_, t)| t.has_param()),
             Type::Fn(f) => f.ret.has_param() || f.params.iter().any(Type::has_param),
             _ => false,
         }
     }
 
-    /// Replace type parameters by what `bind` fixed them to.
+    /// Replace type parameters by what `bind` fixed them to; one it did not
+    /// fix becomes `Error`.
     pub fn subst(&self, bind: &HashMap<String, Type>) -> Type {
-        let r = |t: &Type| Rc::new(t.subst(bind));
+        self.replace(bind, false)
+    }
+
+    /// As `subst`, but a parameter `bind` did not fix stays a parameter.
+    pub fn subst_known(&self, bind: &HashMap<String, Type>) -> Type {
+        self.replace(bind, true)
+    }
+
+    fn replace(&self, bind: &HashMap<String, Type>, keep: bool) -> Type {
+        let r = |t: &Type| Rc::new(t.replace(bind, keep));
         match self {
-            Type::Param(n) => bind.get(&**n).cloned().unwrap_or(Type::Error),
+            Type::Param(n) => {
+                bind.get(&**n)
+                    .cloned()
+                    .unwrap_or(if keep { self.clone() } else { Type::Error })
+            }
             Type::List(t) => Type::List(r(t)),
             Type::Option(t) => Type::Option(r(t)),
+            Type::Secret(t) => Type::Secret(r(t)),
+            Type::Addr(t) => Type::Addr(r(t)),
             Type::Map(a, b) => Type::Map(r(a), r(b)),
             Type::Result(a, b) => Type::Result(r(a), r(b)),
-            Type::Tuple(ts) => Type::Tuple(ts.iter().map(|t| t.subst(bind)).collect()),
-            Type::Record(fs) => Type::Record(fs.iter().map(|(n, t)| (n.clone(), t.subst(bind))).collect()),
+            Type::Tuple(ts) => Type::Tuple(ts.iter().map(|t| t.replace(bind, keep)).collect()),
+            Type::Enum(e, ts) => Type::Enum(*e, ts.iter().map(|t| t.replace(bind, keep)).collect()),
+            Type::Record(fs) => Type::Record(
+                fs.iter()
+                    .map(|(n, t)| (n.clone(), t.replace(bind, keep)))
+                    .collect(),
+            ),
             Type::Fn(f) => Type::Fn(Rc::new(FnType {
-                params: f.params.iter().map(|t| t.subst(bind)).collect(),
-                ret: f.ret.subst(bind),
+                params: f.params.iter().map(|t| t.replace(bind, keep)).collect(),
+                ret: f.ret.replace(bind, keep),
                 effects: f.effects.clone(),
             })),
             t => t.clone(),
@@ -140,10 +182,16 @@ impl Type {
                 }
             },
             (_, Type::Error | Type::Never) => true,
-            (Type::List(a), Type::List(b)) | (Type::Option(a), Type::Option(b)) => a.unify(b, bind),
+            (Type::List(a), Type::List(b))
+            | (Type::Option(a), Type::Option(b))
+            | (Type::Secret(a), Type::Secret(b))
+            | (Type::Addr(a), Type::Addr(b)) => a.unify(b, bind),
             (Type::Map(a, b), Type::Map(c, d)) | (Type::Result(a, b), Type::Result(c, d)) => {
                 a.unify(c, bind) && b.unify(d, bind)
             }
+            (Type::Enum(e, a), Type::Enum(f, b)) => {
+                e == f && a.len() == b.len() && a.iter().zip(b.iter()).all(|(x, y)| x.unify(y, bind))
+            }
             (Type::Tuple(a), Type::Tuple(b)) => {
                 a.len() == b.len() && a.iter().zip(b.iter()).all(|(x, y)| x.unify(y, bind))
             }
@@ -213,6 +261,9 @@ impl fmt::Display for Show<'_> {
                 write!(f, ")")
             }
             Type::Param(n) => write!(f, "{n}"),
+            Type::Secret(t) => write!(f, "Secret<{}>", Show(t, names)),
+            Type::Opaque(n) => write!(f, "{n}"),
+            Type::Addr(t) => write!(f, "Addr<{}>", Show(t, names)),
             Type::Fn(ft) => {
                 write!(f, "fn(")?;
                 for (i, p) in ft.params.iter().enumerate() {
@@ -240,11 +291,24 @@ impl fmt::Display for Show<'_> {
                 }
                 write!(f, " }}")
             }
-            Type::Enum(i) => write!(
-                f,
-                "{}",
-                names.get(*i as usize).map(|s| s.as_str()).unwrap_or("enum")
-            ),
+            Type::Enum(i, args) => {
+                write!(
+                    f,
+                    "{}",
+                    names.get(*i as usize).map(|s| s.as_str()).unwrap_or("enum")
+                )?;
+                if !args.is_empty() {
+                    write!(f, "<")?;
+                    for (k, a) in args.iter().enumerate() {
+                        if k > 0 {
+                            write!(f, ", ")?;
+                        }
+                        write!(f, "{}", Show(a, names))?;
+                    }
+                    write!(f, ">")?;
+                }
+                Ok(())
+            }
             Type::Never => write!(f, "Never"),
             Type::Error => write!(f, "?"),
         }
@@ -258,6 +322,10 @@ pub struct TypeEnv {
     pub enums: HashMap<String, u32>,
     /// Type parameters in scope, while a generic function is checked.
     pub generics: HashMap<String, Type>,
+    /// How many type parameters each enum takes.
+    pub enum_params: HashMap<u32, usize>,
+    /// `type Pair<A, B> = …`, resolved when used with its arguments.
+    pub generic_aliases: HashMap<String, (Vec<String>, TypeExpr)>,
 }
 
 impl TypeEnv {
@@ -329,6 +397,14 @@ impl TypeEnv {
                         arity(1)?;
                         Type::Option(Rc::new(self.resolve(&args[0])?))
                     }
+                    "Secret" => {
+                        arity(1)?;
+                        Type::Secret(Rc::new(self.resolve(&args[0])?))
+                    }
+                    "Addr" => {
+                        arity(1)?;
+                        Type::Addr(Rc::new(self.resolve(&args[0])?))
+                    }
                     "Result" => {
                         arity(2)?;
                         Type::Result(Rc::new(self.resolve(&args[0])?), Rc::new(self.resolve(&args[1])?))
@@ -342,13 +418,27 @@ impl TypeEnv {
                         Type::Map(Rc::new(k), Rc::new(self.resolve(&args[1])?))
                     }
                     _ => {
-                        arity(0)?;
                         if let Some(t) = self.generics.get(name) {
+                            arity(0)?;
                             t.clone()
                         } else if let Some(t) = self.aliases.get(name) {
+                            arity(0)?;
                             t.clone()
+                        } else if let Some((params, body)) = self.generic_aliases.get(name) {
+                            arity(params.len())?;
+                            let mut inner = self.clone();
+                            for (p, a) in params.iter().zip(args) {
+                                let t = self.resolve(a)?;
+                                inner.generics.insert(p.clone(), t);
+                            }
+                            inner.resolve(body)?
                         } else if let Some(&e) = self.enums.get(name) {
-                            Type::Enum(e)
+                            arity(self.enum_params.get(&e).copied().unwrap_or(0))?;
+                            let args = args
+                                .iter()
+                                .map(|a| self.resolve(a))
+                                .collect::<Result<Vec<_>, _>>()?;
+                            Type::Enum(e, args.into())
                         } else {
                             return Err(Error::new(*line, format!("unknown type `{name}`")));
                         }
@@ -401,7 +491,10 @@ impl PlatformDecl {
         let m = crate::parser::parse(src)?;
         for item in m.items {
             match item {
-                ast::Item::Type(name, t, _) => {
+                ast::Item::Type(name, generics, t, _) if !generics.is_empty() => {
+                    self.env.generic_aliases.insert(name, (generics, t));
+                }
+                ast::Item::Type(name, _, t, _) => {
                     let ty = self.env.resolve(&t)?;
                     self.env.aliases.insert(name, ty);
                 }
@@ -440,6 +533,11 @@ impl PlatformDecl {
                         });
                     }
                 }
+                ast::Item::Opaque(name, _) => {
+                    self.env
+                        .aliases
+                        .insert(name.clone(), Type::Opaque(name.as_str().into()));
+                }
                 ast::Item::Event(f) => {
                     let params = f
                         .params
@@ -451,7 +549,7 @@ impl PlatformDecl {
                 _ => {
                     return Err(Error::new(
                         0,
-                        "a platform declaration holds only `type`, `effect`, `module` and `event`",
+                        "a platform declaration holds only `type`, `opaque`, `effect`, `module` and `event`",
                     ));
                 }
             }
diff --git a/crates/frits/src/vm.rs b/crates/frits/src/vm.rs
index 2e16902..8cd44e6 100644
--- a/crates/frits/src/vm.rs
+++ b/crates/frits/src/vm.rs
@@ -66,8 +66,16 @@ pub struct Process<S> {
     log: Vec<LogLine>,
     /// Kept values to put back once the globals are initialised.
     restore: Vec<(String, String, HostValue)>,
+    /// This process's address, as `me()` gives it; the runtime sets it.
+    pub addr: i64,
+    /// Messages sent and not yet delivered: (to, message type, message).
+    pub outbox: Vec<(i64, String, HostValue)>,
 }
 
+/// Events a process holds before more are refused: a script flooded with
+/// messages loses the newest, not its memory.
+pub const MAILBOX_CAP: usize = 1024;
+
 /// The most log lines a process holds before the oldest are dropped.
 const LOG_CAP: usize = 256;
 
@@ -98,6 +106,8 @@ impl<S> Process<S> {
             waiting: false,
             log: Vec::new(),
             restore: Vec::new(),
+            addr: 0,
+            outbox: Vec::new(),
             module,
         };
         let init = p.module.init;
@@ -108,7 +118,7 @@ impl<S> Process<S> {
     /// 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(_)) => {
+            Some(f) if !matches!(self.status, Status::Dead(_)) && self.mailbox.len() < MAILBOX_CAP => {
                 self.mailbox.push_back((f, args));
                 true
             }
@@ -636,6 +646,15 @@ impl<S> Process<S> {
                             Err(e) => fail!(e),
                         }
                     }
+                    Op::Me { dst } => r!(dst) = Value::Int(self.addr),
+                    Op::Send { to, msg, ty } => {
+                        let hv = self.heap.export(r!(msg), &m.strings);
+                        let ty = m.strings[ty as usize].to_string();
+                        if self.outbox.len() >= MAILBOX_CAP {
+                            fail!("sent too much: more than 1024 messages not yet delivered");
+                        }
+                        self.outbox.push((r!(to).int(), ty, hv));
+                    }
                     Op::ListPushMut { list, val } => {
                         let (l, v) = (r!(list), r!(val));
                         self.heap.list_push(l, v);
diff --git a/docs/design.md b/docs/design.md
index 9e44581..c6b7e12 100644
--- a/docs/design.md
+++ b/docs/design.md
@@ -60,9 +60,11 @@ on timer() {
 - Functions are values. `fn(x) { x * 2 }` is a closure; it copies the
   variables it names when it is made, and cannot change them. Its parameter
   types may be left out where the call says them (`xs.map(fn(x) { x * 2 })`).
-- Generic functions: `fn first<T>(xs: List<T>) -> Option<T>`, compiled once per
-  set of types they are called with. Generic types (`enum Tree<T>`) are not
-  built.
+- Generics: `fn first<T>(xs: List<T>) -> Option<T>`, compiled once per set of
+  types it is called with; `enum Tree<T> { Leaf, Node(Tree<T>, T, Tree<T>) }`
+  and `type Pair<A, B> = { first: A, second: B }`. A value that takes its type
+  from where it goes (`Leaf`, `None`, `[]`) gets it from the other arguments
+  first.
 - Methods: built in on lists (`push`, `get`, `map`, `filter`, `any`, `all`,
   `find`, `count`, `contains`, `index_of`, `sort`, `join`, `slice`, `reversed`,
   `remove_at`, `xs[i] = v`, `xs + ys`), strings (`split`, `trim`, `upper`,
@@ -92,6 +94,32 @@ on timer() {
 - No `null`, no exceptions, no classes, no `async`, no implicit conversions
   (`float(i)`, `int(x)`).
 
+## Libraries, messages and rights
+
+- **`import geometry`** merges a library the host supplies
+  (`Platform::set_library`): functions, types, enums and tests, no `script`
+  line, handlers or globals. Its names are used as `geometry.area(b)` and
+  `geometry.Box`; its variants keep their plain names (`Left`, or
+  `geometry.Left`). Each library is checked on its own first, so its mistakes
+  are reported as "in library `geometry`, line 3: …" against the import.
+  Imports that go round are refused.
+- **Messages between scripts.** A script with `on receive(m: T)` has an
+  address, `me()`, of type `Addr<T>`; another sends to it with `send(addr, m)`,
+  which needs the `Mail` effect. The message is copied into the receiver and
+  runs its handler on the next tick (`Runtime::deliver`). An address names one
+  process: a pid reused by a new process does not take its old mail, and a
+  message whose type does not match the receiver's inbox is dropped and
+  counted (`Runtime::undelivered`). A mailbox holds at most 1024 events.
+  Addresses come from `me()` and from the host (`Runtime::addr_of`); a script
+  cannot make one from a number.
+- **`Secret<T>`**: a value the host hands out (a key, a token) that a script can
+  hold and pass to a host function taking a `Secret`, and nothing else: it
+  cannot be written into a string, compared, logged, kept, or received in a
+  message.
+- **`opaque Door`** in a platform declaration: a right only the host can make
+  (a value the script holds and passes back, never builds or looks into). This
+  is the capability: a script that was never given a `Door` cannot open one.
+
 ## The platform
 
 A host describes what it offers in Frits, and binds Rust functions to it:
@@ -175,12 +203,9 @@ looked into.
 
 In the order they are likely to matter:
 
-- Generic types (`enum Tree<T>`, `type Pair<A, B>`).
-- Modules and imports.
-- The capability types and labels from the brainstorm: rights you cannot forge,
-  `Secret<T>`, untrusted-origin labels.
-- Process-to-process messages inside the language (`spawn`, `send`) and
-  supervisors; today processes talk only through the platform.
+- Untrusted-origin labels (text from another person cannot steer what an
+  agent or script does): not designed yet, a question for the owner.
+- `spawn` from inside a script, and supervisors; the host starts processes.
 - A language server, formatter and debugger.
 - `view` markup on the component library; AOT for Pinnacle apps; wasm.