garage44.eu/jeroen/frits

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

cartopolis-agent · 2026-11-26T12:31:34Z

feat(frits): compile scripts to native Rust ahead of time

`frits aot` writes a module's bytecode as Rust: one function per script
function, basic blocks as straight code with constants written in, on
the interpreter's own registers, heap and collector so memory limits and
collection behave the same. `Process::set_natives` attaches them and
checks a fingerprint of the bytecode, so natives from other code are
refused rather than run against the wrong module.

Native code runs to completion: not counted by fuel, not pausable, and a
host call that suspends fails. It is for installed apps on a system that
preempts threads (Pinnacle), never for uploaded sim scripts.

`crates/aot-check` generates natives in its build script and checks
them against the interpreter on a script mixing recursion, an
allocating loop, closures, maps and `Result`: same output, 67.5 ms
interpreted against 32.8 ms compiled (2.1x, release, vps-1).

The lockfile entry for the new crate was written by hand: the node's
cargo had updated its own copy, so `--locked` passed there while the
committed lockfile would have failed a clean gate.
CLAUDE.md                               |  13 +-
 Cargo.lock                              |   7 +
 Cargo.toml                              |   2 +-
 crates/aot-check/Cargo.toml             |  14 +
 crates/aot-check/build.rs               |  21 ++
 crates/aot-check/scripts/platform.frits |   4 +
 crates/aot-check/scripts/work.frits     |  53 +++
 crates/aot-check/src/lib.rs             |  86 +++++
 crates/frits/src/aot.rs                 | 588 ++++++++++++++++++++++++++++++++
 crates/frits/src/lib.rs                 |   1 +
 crates/frits/src/main.rs                |  32 +-
 crates/frits/src/vm.rs                  |  48 ++-
 docs/design.md                          |  24 +-
 13 files changed, 874 insertions(+), 19 deletions(-)

diff --git a/CLAUDE.md b/CLAUDE.md
index ead53d9..1636154 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -10,7 +10,8 @@ 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 test --workspace                 # crates/frits unit tests, the ported scripts in crates/bench,
+                                       # and crates/aot-check (natives generated at build time vs the interpreter)
 cargo run --release -p frits-bench     # numbers comparable with Cartopolis's Luau/Bun table; run on mac-1
 cargo clippy --workspace --all-targets
 ```
@@ -20,9 +21,13 @@ cargo clippy --workspace --all-targets
 - **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.
+- **Every path that runs uploaded 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. Native
+  code (`aot.rs`) is the one exception, and only for installed apps.
+- **A new `Op` needs three places**: the compiler that emits it, the VM
+  (`vm.rs`) and the native code generator (`aot.rs`); `crates/aot-check`
+  catches a generator that disagrees with the VM.
 - **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.
diff --git a/Cargo.lock b/Cargo.lock
index f30a414..fe0aeba 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -6,6 +6,13 @@ version = 4
 name = "frits"
 version = "0.1.0"
 
+[[package]]
+name = "frits-aot-check"
+version = "0.1.0"
+dependencies = [
+ "frits",
+]
+
 [[package]]
 name = "frits-bench"
 version = "0.1.0"
diff --git a/Cargo.toml b/Cargo.toml
index 81659ef..1cc1bd8 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,5 +1,5 @@
 [workspace]
-members = ["crates/frits", "crates/bench"]
+members = ["crates/frits", "crates/bench", "crates/aot-check"]
 resolver = "3"
 
 [workspace.package]
diff --git a/crates/aot-check/Cargo.toml b/crates/aot-check/Cargo.toml
new file mode 100644
index 0000000..70f6560
--- /dev/null
+++ b/crates/aot-check/Cargo.toml
@@ -0,0 +1,14 @@
+[package]
+name = "frits-aot-check"
+version.workspace = true
+edition.workspace = true
+license.workspace = true
+publish.workspace = true
+
+# Generates native code for the scripts in `scripts/` at build time, and tests
+# that it does what the interpreter does.
+[dependencies]
+frits = { path = "../frits" }
+
+[build-dependencies]
+frits = { path = "../frits" }
diff --git a/crates/aot-check/build.rs b/crates/aot-check/build.rs
new file mode 100644
index 0000000..d0390e5
--- /dev/null
+++ b/crates/aot-check/build.rs
@@ -0,0 +1,21 @@
+//! Compile every script in `scripts/` against `scripts/platform.frits` and
+//! write its native code to `$OUT_DIR/<name>.rs`.
+
+fn main() {
+    let decl = std::fs::read_to_string("scripts/platform.frits").unwrap();
+    let plat: frits::Platform<()> = frits::Platform::new(&decl).unwrap();
+    let out = std::env::var("OUT_DIR").unwrap();
+    println!("cargo::rerun-if-changed=scripts");
+    for entry in std::fs::read_dir("scripts").unwrap() {
+        let path = entry.unwrap().path();
+        let name = path.file_stem().unwrap().to_str().unwrap().to_string();
+        if name == "platform" {
+            continue;
+        }
+        let src = std::fs::read_to_string(&path).unwrap();
+        let m = plat
+            .compile(&src)
+            .unwrap_or_else(|e| panic!("{}: {e:?}", path.display()));
+        std::fs::write(format!("{out}/{name}.rs"), frits::aot::generate(&m)).unwrap();
+    }
+}
diff --git a/crates/aot-check/scripts/platform.frits b/crates/aot-check/scripts/platform.frits
new file mode 100644
index 0000000..1d4da88
--- /dev/null
+++ b/crates/aot-check/scripts/platform.frits
@@ -0,0 +1,4 @@
+effect Out {
+    fn say(text: Str)
+}
+event go()
diff --git a/crates/aot-check/scripts/work.frits b/crates/aot-check/scripts/work.frits
new file mode 100644
index 0000000..07858b6
--- /dev/null
+++ b/crates/aot-check/scripts/work.frits
@@ -0,0 +1,53 @@
+// A bit of everything, run both interpreted and compiled.
+script / Out
+
+enum Shape { Circle(Float), Rect(Float, Float) }
+
+var calls = 0
+
+fn fib(n: Int) -> Int {
+    calls += 1
+    if n < 2 { n } else { fib(n - 1) + fib(n - 2) }
+}
+
+fn area(s: Shape) -> Float {
+    match s {
+        Circle(r) => 3.0 * r * r,
+        Rect(w, h) => w * h,
+    }
+}
+
+fn parse(t: Str) -> Result<Int, Str> {
+    match t.parse_int() {
+        Some(n) => Ok(n),
+        None => Err("bad {t}"),
+    }
+}
+
+fn total(xs: List<Str>) -> Result<Int, Str> {
+    var sum = 0
+    for x in xs { sum += parse(x)? }
+    Ok(sum)
+}
+
+on go() {
+    Out.say("fib {fib(22)} after {calls} calls")
+    var acc = 0.0
+    for i in 0..200000 {
+        acc += area(if i % 2 == 0 { Circle(1.0) } else { Rect(2.0, float(i % 7)) })
+    }
+    Out.say("area {acc:.1}")
+    let k = 3
+    let xs = [1, 2, 3, 4, 5].map(fn(x) { x * k }).filter(fn(x) { x > 4 })
+    var m: Map<Str, Int> = [:]
+    for x in xs { m.set("n{x}", x) }
+    Out.say("{xs.join_ints()} {m.keys().join(",")}")
+    match total(["1", "2", "x"]) { Ok(n) => Out.say("{n}"), Err(e) => Out.say(e) }
+    var p = { x: 1, y: { z: 2 } }
+    p.y.z = 40
+    Out.say("{p.y.z + p.x + 1}")
+}
+
+fn join_ints(xs: List<Int>) -> Str {
+    xs.map(fn(x) { "{x}" }).join("+")
+}
diff --git a/crates/aot-check/src/lib.rs b/crates/aot-check/src/lib.rs
new file mode 100644
index 0000000..b7cf695
--- /dev/null
+++ b/crates/aot-check/src/lib.rs
@@ -0,0 +1,86 @@
+//! Natives generated at build time from `scripts/`, checked against the
+//! interpreter.
+
+pub mod work {
+    include!(concat!(env!("OUT_DIR"), "/work.rs"));
+}
+
+#[cfg(test)]
+mod tests {
+    use std::time::Instant;
+
+    use frits::{Cx, Platform, Runtime, Status, Value};
+
+    fn platform() -> Platform<Vec<String>> {
+        let mut p = Platform::new(include_str!("../scripts/platform.frits")).unwrap();
+        p.bind("Out.say", |cx: &mut Cx<Vec<String>>, a| {
+            let s = cx.str(a[0]).to_string();
+            cx.state.push(s);
+            Ok(Value::Unit)
+        });
+        p
+    }
+
+    /// Run `work.frits` to the end; returns what it said and how long it took.
+    fn run(native: bool) -> (Vec<String>, f64) {
+        let mut rt = Runtime::new(platform());
+        rt.limits.memory = 64 << 20;
+        let m = rt
+            .platform
+            .compile(include_str!("../scripts/work.frits"))
+            .unwrap();
+        let pid = rt.spawn(m, Vec::new());
+        if native {
+            let ok = rt.get_mut(pid).unwrap().set_natives(
+                crate::work::frits_native::natives(),
+                crate::work::frits_native::FINGERPRINT,
+            );
+            assert!(ok, "the natives do not match the compiled script");
+        }
+        rt.post(pid, "go", Vec::new());
+        let t = Instant::now();
+        while rt.get(pid).unwrap().has_work() {
+            let died = rt.tick();
+            assert!(died.is_empty(), "{died:?}");
+        }
+        assert_eq!(rt.get(pid).unwrap().status, Status::Idle);
+        (rt.get(pid).unwrap().state.clone(), t.elapsed().as_secs_f64())
+    }
+
+    #[test]
+    fn compiled_code_does_what_the_interpreter_does() {
+        let (a, ti) = run(false);
+        let (b, tn) = run(true);
+        assert_eq!(
+            a,
+            [
+                "fib 17711 after 57313 calls",
+                "area 899992.0",
+                "6+9+12+15 n12,n15,n6,n9",
+                "bad x",
+                "42"
+            ]
+        );
+        assert_eq!(a, b);
+        eprintln!(
+            "interpreted {:.1} ms, compiled {:.1} ms ({:.1}×)",
+            ti * 1e3,
+            tn * 1e3,
+            ti / tn
+        );
+    }
+
+    #[test]
+    fn natives_from_other_code_are_refused() {
+        let rt = Runtime::new(platform());
+        let m = rt
+            .platform
+            .compile("script / Out\non go() { Out.say(\"other\") }")
+            .unwrap();
+        let mut p = frits::Process::new(m, Vec::<String>::new());
+        assert!(!p.set_natives(
+            crate::work::frits_native::natives(),
+            crate::work::frits_native::FINGERPRINT
+        ));
+    }
+}
diff --git a/crates/frits/src/aot.rs b/crates/frits/src/aot.rs
new file mode 100644
index 0000000..9125484
--- /dev/null
+++ b/crates/frits/src/aot.rs
@@ -0,0 +1,588 @@
+//! Ahead-of-time compilation: a script's bytecode as Rust source, one native
+//! function per script function, for apps that are installed rather than
+//! uploaded (Pinnacle's).
+//!
+//! The generated code works on the same registers, heap and collector as the
+//! interpreter; what goes is the interpreter's dispatch. Each basic block is
+//! straight Rust, constants are written in, and a block ends in a jump to the
+//! next. A host attaches the natives to a process with
+//! `Process::set_natives`; their fingerprint must match the module compiled
+//! from the same source, or they are refused and the interpreter runs.
+//!
+//! **Native code runs to completion.** It is not counted by fuel and cannot be
+//! paused, so a host call that suspends (`Timer.wait`) stops it with an error.
+//! It is for code the device's owner installed, on a system that preempts
+//! threads; uploaded scripts (the Cartopolis simulator's) stay interpreted.
+
+use std::fmt::Write;
+use std::rc::Rc;
+
+use crate::bytecode::{Module, Op};
+use crate::platform::{Cx, Platform};
+use crate::stdlib::{self, Std};
+use crate::value::{HostValue, Obj, Value};
+use crate::vm::{Level, LogLine, Process};
+
+/// A compiled function: `base` is where its registers start.
+pub type NativeFn<S> = fn(&mut Native<S>, usize) -> Result<Value, String>;
+
+/// What native code works in: the process, its platform and module.
+pub struct Native<'a, S> {
+    pub p: &'a mut Process<S>,
+    pub plat: &'a Platform<S>,
+    pub m: &'a Module,
+    pub natives: &'a [NativeFn<S>],
+    pub mem_limit: usize,
+    pub depth: usize,
+}
+
+/// A stable fingerprint of a module's code, which generated natives carry.
+pub fn fingerprint(m: &Module) -> u64 {
+    // FNV-1a over the code as written out: any change in the compiler or the
+    // script changes it.
+    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
+    let mut eat = |s: &str| {
+        for b in s.bytes() {
+            h ^= b as u64;
+            h = h.wrapping_mul(0x0100_0000_01b3);
+        }
+    };
+    for f in &m.funcs {
+        eat(&format!("{}:{}:{:?}:{:?}", f.arity, f.nregs, f.captures, f.code));
+    }
+    eat(&format!("{:?}{:?}", m.consts, m.strings));
+    h
+}
+
+impl<S> Native<'_, S> {
+    #[inline]
+    pub fn r(&self, i: usize) -> Value {
+        self.p.regs[i]
+    }
+
+    #[inline]
+    pub fn set(&mut self, i: usize, v: Value) {
+        self.p.regs[i] = v;
+    }
+
+    #[inline]
+    pub fn global(&self, g: usize) -> Value {
+        self.p.globals[g]
+    }
+
+    #[inline]
+    pub fn set_global(&mut self, g: usize, v: Value) {
+        self.p.globals[g] = v;
+    }
+
+    pub fn fail(&self, func: u32, pc: u32, msg: &str) -> String {
+        self.p.located(func, pc, msg)
+    }
+
+    pub fn enter(&mut self, top: usize) -> Result<(), String> {
+        if self.p.regs.len() < top {
+            self.p.regs.resize(top, Value::Unit);
+        }
+        Ok(())
+    }
+
+    /// Collect when due; `top` is the end of the live registers.
+    pub fn safepoint(&mut self, top: usize) -> Result<(), String> {
+        if self.p.heap.wants_gc() {
+            self.p.collect(top);
+            if self.p.heap.bytes > self.mem_limit {
+                return Err(format!(
+                    "out of memory: {} KiB live, the limit is {} KiB",
+                    self.p.heap.bytes / 1024,
+                    self.mem_limit / 1024
+                ));
+            }
+        }
+        Ok(())
+    }
+
+    pub fn call(&mut self, f: u32, base: usize) -> Result<Value, String> {
+        if self.depth >= 2_000 {
+            return Err("too deep: more than 2000 calls in progress".into());
+        }
+        self.depth += 1;
+        let v = (self.natives[f as usize])(self, base);
+        self.depth -= 1;
+        v
+    }
+
+    pub fn call_value(&mut self, fr: usize, base: usize) -> Result<Value, String> {
+        let Some(Obj::Closure(f, caps)) = self.p.heap.get(self.p.regs[fr]) else {
+            return Err("called something that is not a function".into());
+        };
+        let (f, caps) = (*f, caps.clone());
+        let callee = &self.m.funcs[f as usize];
+        let top = base + callee.nregs as usize;
+        if self.p.regs.len() < top {
+            self.p.regs.resize(top, Value::Unit);
+        }
+        for (slot, v) in callee.captures.iter().zip(caps.iter()) {
+            self.p.regs[base + *slot as usize] = *v;
+        }
+        self.call(f, base)
+    }
+
+    pub fn host(&mut self, f: u32, base: usize, argc: usize) -> Result<Value, String> {
+        let Some(hf) = self.plat.fns[f as usize] else {
+            let s = &self.plat.decl.fns[f as usize];
+            return Err(format!(
+                "the platform does not implement `{}.{}`",
+                s.namespace, s.name
+            ));
+        };
+        let mut suspend = false;
+        let mut charged = 0;
+        let p = &mut *self.p;
+        let mut cx = Cx {
+            state: &mut p.state,
+            heap: &mut p.heap,
+            strings: &self.m.strings,
+            rng: &mut p.rng,
+            suspend: &mut suspend,
+            charged: &mut charged,
+        };
+        let v = hf(&mut cx, &p.regs[base..base + argc])?;
+        if suspend {
+            let s = &self.plat.decl.fns[f as usize];
+            return Err(format!(
+                "`{}.{}` pauses the script, which compiled code cannot do",
+                s.namespace, s.name
+            ));
+        }
+        Ok(v)
+    }
+
+    pub fn host_const(&mut self, c: u32) -> Result<Value, String> {
+        match &self.plat.consts[c as usize] {
+            Some(v) => Ok(self.p.heap.import(v)),
+            None => {
+                let s = &self.plat.decl.consts[c as usize];
+                Err(format!(
+                    "the platform does not provide `{}.{}`",
+                    s.namespace, s.name
+                ))
+            }
+        }
+    }
+
+    pub fn alloc(&mut self, o: Obj) -> Value {
+        self.p.heap.alloc(o)
+    }
+
+    pub fn slots(&self, base: usize, n: usize) -> Vec<Value> {
+        self.p.regs[base..base + n].to_vec()
+    }
+
+    pub fn field(&self, v: Value, i: usize) -> Value {
+        self.p.heap.fields(v).get(i).copied().unwrap_or(Value::Unit)
+    }
+
+    pub fn set_field(&mut self, v: Value, i: usize, x: Value) -> Value {
+        let mut f: Box<[Value]> = self.p.heap.fields(v).into();
+        if let Some(slot) = f.get_mut(i) {
+            *slot = x;
+        }
+        self.p.heap.alloc(Obj::Record(f))
+    }
+
+    pub fn list_get(&self, list: Value, i: i64) -> Result<Value, String> {
+        let items = self.p.heap.fields(list);
+        usize::try_from(i)
+            .ok()
+            .and_then(|i| items.get(i).copied())
+            .ok_or_else(|| format!("index {i} is outside the list (length {})", items.len()))
+    }
+
+    pub fn len(&self, v: Value) -> i64 {
+        self.p.heap.fields(v).len() as i64
+    }
+
+    pub fn str_len(&self, v: Value) -> i64 {
+        self.p.heap.str(v, &self.m.strings).chars().count() as i64
+    }
+
+    pub fn eq_s(&self, a: Value, b: Value) -> bool {
+        a == b || self.p.heap.str(a, &self.m.strings) == self.p.heap.str(b, &self.m.strings)
+    }
+
+    pub fn tag(&self, v: Value) -> i64 {
+        match v {
+            Value::Tag(t) => t as i64,
+            _ => match self.p.heap.get(v) {
+                Some(Obj::Variant(t, _)) => *t as i64,
+                _ => -1,
+            },
+        }
+    }
+
+    pub fn text(&mut self, s: String) -> Value {
+        self.p.heap.alloc(Obj::Str(s.into()))
+    }
+
+    pub fn concat(&mut self, base: usize, n: usize) -> Result<Value, String> {
+        let parts = &self.p.regs[base..base + n];
+        let total: usize = parts
+            .iter()
+            .map(|v| self.p.heap.str(*v, &self.m.strings).len())
+            .sum();
+        if total > self.mem_limit {
+            return Err(format!("out of memory: a {} KiB string", total / 1024));
+        }
+        let mut out = String::with_capacity(total);
+        for v in parts {
+            out.push_str(self.p.heap.str(*v, &self.m.strings));
+        }
+        Ok(self.p.heap.alloc(Obj::Str(out.into())))
+    }
+
+    pub fn std(&mut self, f: Std, base: usize) -> Result<Value, String> {
+        let args = &self.p.regs[base..base + f.arity()];
+        stdlib::call(f, &mut self.p.heap, &self.m.strings, args, self.mem_limit)
+    }
+
+    pub fn log(&mut self, level: u8, line: u32, v: Value) {
+        let text = self.p.heap.str(v, &self.m.strings).to_string();
+        if self.p.log.len() >= 256 {
+            self.p.log.remove(0);
+        }
+        let level = if level == 0 { Level::Info } else { Level::Warn };
+        self.p.log.push(LogLine { level, line, text });
+    }
+
+    pub fn string_of(&self, v: Value) -> String {
+        self.p.heap.str(v, &self.m.strings).to_string()
+    }
+
+    pub fn render(&mut self, v: Value) {
+        self.p.view = Some(self.p.heap.export(v, &self.m.strings));
+    }
+
+    pub fn send(&mut self, to: Value, msg: Value, ty: u32) -> Result<(), String> {
+        let hv: HostValue = self.p.heap.export(msg, &self.m.strings);
+        if self.p.outbox.len() >= crate::vm::MAILBOX_CAP {
+            return Err("sent too much: more than 1024 messages not yet delivered".into());
+        }
+        self.p
+            .outbox
+            .push((to.int(), self.m.strings[ty as usize].to_string(), hv));
+        Ok(())
+    }
+
+    pub fn list_push(&mut self, list: Value, v: Value) {
+        self.p.heap.list_push(list, v);
+    }
+}
+
+/// Rust source for `m`: `pub fn natives<S>() -> Vec<NativeFn<S>>` and its
+/// fingerprint, `pub const FINGERPRINT: u64`.
+pub fn generate(m: &Module) -> String {
+    let mut out = String::new();
+    let _ = writeln!(
+        out,
+        "// Generated by `frits aot`. Do not edit: regenerate from the script."
+    );
+    let _ = writeln!(out, "#[allow(unused, clippy::all)]");
+    let _ = writeln!(out, "pub mod frits_native {{");
+    let _ = writeln!(
+        out,
+        "use frits::aot::Native;\nuse frits::Value;\nuse frits::value::Obj;\nuse frits::stdlib::Std;"
+    );
+    let _ = writeln!(out, "pub const FINGERPRINT: u64 = {};", fingerprint(m));
+    let _ = writeln!(
+        out,
+        "pub fn natives<S>() -> Vec<frits::aot::NativeFn<S>> {{\n    vec!["
+    );
+    for i in 0..m.funcs.len() {
+        let _ = writeln!(out, "        f{i}::<S>,");
+    }
+    let _ = writeln!(out, "    ]\n}}");
+    for (id, f) in m.funcs.iter().enumerate() {
+        function(&mut out, m, id as u32, f);
+    }
+    let _ = writeln!(out, "}}");
+    out
+}
+
+fn konst(v: Value) -> String {
+    match v {
+        Value::Int(i) => format!("Value::Int({i})"),
+        Value::Float(f) => format!("Value::Float(f64::from_bits({:#x}))", f.to_bits()),
+        Value::Static(s) => format!("Value::Static({s})"),
+        Value::Bool(b) => format!("Value::Bool({b})"),
+        Value::Tag(t) => format!("Value::Tag({t})"),
+        Value::Unit => "Value::Unit".into(),
+        Value::Obj(_) => unreachable!("constants are never heap objects"),
+    }
+}
+
+fn function(out: &mut String, m: &Module, id: u32, f: &crate::bytecode::Function) {
+    // Basic blocks: they start at 0, at every jump target, and after every jump
+    // and return.
+    let n = f.code.len();
+    let mut leader = vec![false; n + 1];
+    leader[0] = true;
+    for (pc, op) in f.code.iter().enumerate() {
+        match *op {
+            Op::Jump { to } | Op::JumpIfFalse { to, .. } | Op::JumpIfTrue { to, .. } => {
+                leader[to as usize] = true;
+                leader[pc + 1] = true;
+            }
+            Op::Ret { .. } | Op::Panic { .. } => leader[pc + 1] = true,
+            _ => {}
+        }
+    }
+    let nregs = f.nregs as usize;
+    let _ = writeln!(out, "\n/// {}", f.name.replace('\n', " "));
+    let _ = writeln!(
+        out,
+        "fn f{id}<S>(x: &mut Native<S>, b: usize) -> Result<Value, String> {{"
+    );
+    let _ = writeln!(out, "    x.enter(b + {nregs})?;");
+    let _ = writeln!(out, "    let mut pc: u32 = 0;\n    loop {{\n        match pc {{");
+    let mut pc = 0;
+    while pc < n {
+        let _ = writeln!(out, "            {pc} => {{");
+        loop {
+            let line = f.lines.get(pc).copied().unwrap_or(0);
+            let ends = op(out, m, id, pc as u32, line, f.code[pc], nregs);
+            pc += 1;
+            if ends {
+                break;
+            }
+            if leader[pc] {
+                let _ = writeln!(out, "                pc = {pc};");
+                break;
+            }
+        }
+        let _ = writeln!(out, "            }}");
+    }
+    let _ = writeln!(out, "            _ => unreachable!(),\n        }}\n    }}\n}}");
+}
+
+/// Emit one instruction; returns whether it ends its block.
+fn op(out: &mut String, m: &Module, id: u32, pc: u32, line: u32, op: Op, nregs: usize) -> bool {
+    let r = |i: u16| format!("x.r(b + {i})");
+    let set = |i: u16, v: String| format!("x.set(b + {i}, {v});");
+    let fail = |msg: &str| format!("return Err(x.fail({id}, {pc}, {msg:?}))");
+    let try_ =
+        |e: String| format!("match {e} {{ Ok(v) => v, Err(e) => return Err(x.fail({id}, {pc}, &e)) }}");
+    let _ = line;
+    let s = match op {
+        Op::LoadK { dst, k } => set(dst, konst(m.consts[k as usize])),
+        Op::LoadUnit { dst } => set(dst, "Value::Unit".into()),
+        Op::LoadBool { dst, v } => set(dst, format!("Value::Bool({v})")),
+        Op::LoadTag { dst, tag } => set(dst, format!("Value::Tag({tag})")),
+        Op::Move { dst, src } => set(dst, r(src)),
+        Op::GetGlobal { dst, g } => set(dst, format!("x.global({g})")),
+        Op::SetGlobal { g, src } => format!("x.set_global({g}, {});", r(src)),
+        Op::AddI { dst, a, b }
+        | Op::SubI { dst, a, b }
+        | Op::MulI { dst, a, b }
+        | Op::DivI { dst, a, b }
+        | Op::RemI { dst, a, b } => {
+            let (method, what) = match op {
+                Op::AddI { .. } => ("checked_add", "integer overflow in `+`"),
+                Op::SubI { .. } => ("checked_sub", "integer overflow in `-`"),
+                Op::MulI { .. } => ("checked_mul", "integer overflow in `*`"),
+                Op::DivI { .. } => ("checked_div", "integer division by zero"),
+                _ => ("checked_rem", "integer remainder by zero"),
+            };
+            format!(
+                "match {}.int().{method}({}.int()) {{ Some(v) => {{ {} }} None => {} }}",
+                r(a),
+                r(b),
+                set(dst, "Value::Int(v)".into()),
+                fail(what)
+            )
+        }
+        Op::NegI { dst, a } => format!(
+            "match {}.int().checked_neg() {{ Some(v) => {{ {} }} None => {} }}",
+            r(a),
+            set(dst, "Value::Int(v)".into()),
+            fail("integer overflow in `-`")
+        ),
+        Op::AddF { dst, a, b } => set(dst, format!("Value::Float({}.float() + {}.float())", r(a), r(b))),
+        Op::SubF { dst, a, b } => set(dst, format!("Value::Float({}.float() - {}.float())", r(a), r(b))),
+        Op::MulF { dst, a, b } => set(dst, format!("Value::Float({}.float() * {}.float())", r(a), r(b))),
+        Op::DivF { dst, a, b } => set(dst, format!("Value::Float({}.float() / {}.float())", r(a), r(b))),
+        Op::RemF { dst, a, b } => set(dst, format!("Value::Float({}.float() % {}.float())", r(a), r(b))),
+        Op::NegF { dst, a } => set(dst, format!("Value::Float(-{}.float())", r(a))),
+        Op::Not { dst, a } => set(dst, format!("Value::Bool(!{}.bool())", r(a))),
+        Op::LtI { dst, a, b } => set(dst, format!("Value::Bool({}.int() < {}.int())", r(a), r(b))),
+        Op::LeI { dst, a, b } => set(dst, format!("Value::Bool({}.int() <= {}.int())", r(a), r(b))),
+        Op::LtF { dst, a, b } => set(dst, format!("Value::Bool({}.float() < {}.float())", r(a), r(b))),
+        Op::LeF { dst, a, b } => set(dst, format!("Value::Bool({}.float() <= {}.float())", r(a), r(b))),
+        Op::EqI { dst, a, b } => set(dst, format!("Value::Bool({}.int() == {}.int())", r(a), r(b))),
+        Op::EqF { dst, a, b } => set(dst, format!("Value::Bool({}.float() == {}.float())", r(a), r(b))),
+        Op::EqB { dst, a, b } => set(dst, format!("Value::Bool({}.bool() == {}.bool())", r(a), r(b))),
+        Op::EqTag { dst, a, b } => set(dst, format!("Value::Bool({} == {})", r(a), r(b))),
+        Op::EqS { dst, a, b } => set(dst, format!("Value::Bool(x.eq_s({}, {}))", r(a), r(b))),
+        Op::IntToFloat { dst, a } => set(dst, format!("Value::Float({}.int() as f64)", r(a))),
+        Op::FloatToInt { dst, a } => set(dst, format!("Value::Int({}.float() as i64)", r(a))),
+        Op::Jump { to } => {
+            let gc = if to <= pc {
+                format!("{} ", try_(format!("x.safepoint(b + {nregs})")))
+            } else {
+                String::new()
+            };
+            let _ = writeln!(out, "                {gc};pc = {to};");
+            return true;
+        }
+        Op::JumpIfFalse { cond, to } | Op::JumpIfTrue { cond, to } => {
+            let neg = if matches!(op, Op::JumpIfFalse { .. }) {
+                "!"
+            } else {
+                ""
+            };
+            let _ = writeln!(
+                out,
+                "                pc = if {neg}{}.bool() {{ {to} }} else {{ {} }};",
+                r(cond),
+                pc + 1
+            );
+            return true;
+        }
+        Op::Call { f, base, dst } => format!(
+            "{} let v = {}; {}",
+            try_(format!("x.safepoint(b + {nregs})")) + ";",
+            try_(format!("x.call({f}, b + {base})")),
+            set(dst, "v".into())
+        ),
+        Op::CallValue { f, base, dst } => format!(
+            "{} let v = {}; {}",
+            try_(format!("x.safepoint(b + {nregs})")) + ";",
+            try_(format!("x.call_value(b + {f}, b + {base})")),
+            set(dst, "v".into())
+        ),
+        Op::Ret { src } => {
+            let _ = writeln!(out, "                return Ok({});", r(src));
+            return true;
+        }
+        Op::CallHost { f, base, argc, dst } => {
+            format!(
+                "let v = {}; {}",
+                try_(format!("x.host({f}, b + {base}, {argc})")),
+                set(dst, "v".into())
+            )
+        }
+        Op::HostConst { dst, c } => format!(
+            "let v = {}; {}",
+            try_(format!("x.host_const({c})")),
+            set(dst, "v".into())
+        ),
+        Op::MakeRecord { dst, base, n } => format!(
+            "let v = x.slots(b + {base}, {n}); let v = x.alloc(Obj::Record(v.into())); {}",
+            set(dst, "v".into())
+        ),
+        Op::GetField { dst, src, idx } => set(dst, format!("x.field({}, {idx})", r(src))),
+        Op::SetField { dst, src, idx, val } => {
+            format!(
+                "let v = x.set_field({}, {idx}, {}); {}",
+                r(src),
+                r(val),
+                set(dst, "v".into())
+            )
+        }
+        Op::MakeList { dst, base, n } => {
+            format!(
+                "let v = x.slots(b + {base}, {n}); let v = x.alloc(Obj::List(v)); {}",
+                set(dst, "v".into())
+            )
+        }
+        Op::ListGet { dst, list, idx } => {
+            format!(
+                "let v = {}; {}",
+                try_(format!("x.list_get({}, {}.int())", r(list), r(idx))),
+                set(dst, "v".into())
+            )
+        }
+        Op::Len { dst, src } => set(dst, format!("Value::Int(x.len({}))", r(src))),
+        Op::StrLen { dst, src } => set(dst, format!("Value::Int(x.str_len({}))", r(src))),
+        Op::MakeVariant { dst, tag, base, n } => format!(
+            "let v = x.slots(b + {base}, {n}); let v = x.alloc(Obj::Variant({tag}, v.into())); {}",
+            set(dst, "v".into())
+        ),
+        Op::GetTag { dst, src } => set(dst, format!("Value::Int(x.tag({}))", r(src))),
+        Op::GetPayload { dst, src, idx } => set(dst, format!("x.field({}, {idx})", r(src))),
+        Op::IntToStr { dst, a } => format!(
+            "let v = x.text({}.int().to_string()); {}",
+            r(a),
+            set(dst, "v".into())
+        ),
+        Op::FloatToStr { dst, a, prec } => {
+            let fmt = if prec == u8::MAX {
+                "format!(\"{}\", f)".to_string()
+            } else {
+                format!("format!(\"{{:.{prec}}}\", f)")
+            };
+            format!(
+                "let f = {}.float(); let v = x.text({fmt}); {}",
+                r(a),
+                set(dst, "v".into())
+            )
+        }
+        Op::BoolToStr { dst, a } => format!(
+            "let v = x.text(if {}.bool() {{ \"true\" }} else {{ \"false\" }}.to_string()); {}",
+            r(a),
+            set(dst, "v".into())
+        ),
+        Op::Concat { dst, base, n } => {
+            format!(
+                "let v = {}; {}",
+                try_(format!("x.concat(b + {base}, {n})")),
+                set(dst, "v".into())
+            )
+        }
+        Op::Panic { msg } => {
+            let text = format!(
+                "panic: {}",
+                m.strings
+                    .get(msg as usize)
+                    .map(|s| s.to_string())
+                    .unwrap_or_default()
+            );
+            let _ = writeln!(out, "                {};", fail(&text));
+            return true;
+        }
+        Op::Assert { cond, msg } => format!(
+            "if !{}.bool() {{ let t = format!(\"assertion failed: {{}}\", x.string_of({})); return Err(x.fail({id}, {pc}, &t)); }}",
+            r(cond),
+            r(msg)
+        ),
+        Op::Log { level, src } => format!("x.log({level}, {line}, {});", r(src)),
+        Op::MakeClosure { dst, f, base, n } => format!(
+            "let v = x.slots(b + {base}, {n}); let v = x.alloc(Obj::Closure({f}, v.into())); {}",
+            set(dst, "v".into())
+        ),
+        Op::Std { f, base, dst } => {
+            format!(
+                "let v = {}; {}",
+                try_(format!("x.std(Std::{f:?}, b + {base})")),
+                set(dst, "v".into())
+            )
+        }
+        Op::Render { src } => format!("x.render({});", r(src)),
+        Op::Me { dst } => set(dst, "Value::Int(x.p.addr)".into()),
+        Op::Send { to, msg, ty } => format!("{};", try_(format!("x.send({}, {}, {ty})", r(to), r(msg)))),
+        Op::ListPushMut { list, val } => format!("x.list_push({}, {});", r(list), r(val)),
+    };
+    let _ = writeln!(out, "                {s}");
+    false
+}
+
+impl<S> Process<S> {
+    /// Run this process's functions as native code. Refused (false) when the
+    /// natives were generated from different code.
+    pub fn set_natives(&mut self, natives: Vec<NativeFn<S>>, fingerprint: u64) -> bool {
+        if fingerprint != self::fingerprint(&self.module) || natives.len() != self.module.funcs.len() {
+            return false;
+        }
+        self.natives = Some(Rc::from(natives));
+        true
+    }
+}
diff --git a/crates/frits/src/lib.rs b/crates/frits/src/lib.rs
index 0697e54..1f626db 100644
--- a/crates/frits/src/lib.rs
+++ b/crates/frits/src/lib.rs
@@ -6,6 +6,7 @@
 //! a stopped script, never a memory error.
 #![forbid(unsafe_code)]
 
+pub mod aot;
 pub mod ast;
 pub mod bytecode;
 pub mod compile;
diff --git a/crates/frits/src/main.rs b/crates/frits/src/main.rs
index a39e023..6614467 100644
--- a/crates/frits/src/main.rs
+++ b/crates/frits/src/main.rs
@@ -4,7 +4,8 @@
 //! - `frits test <file>` runs its `test` blocks;
 //! - `frits fmt [--check] <file>…` formats scripts in place;
 //! - `frits lsp [--platform <decl.frits>]` serves an editor;
-//! - `frits guide [--platform <decl.frits>] [--title <t>]` writes the scripting guide.
+//! - `frits guide [--platform <decl.frits>] [--title <t>]` writes the scripting guide;
+//! - `frits aot [--platform <decl.frits>] <file>` writes the script as Rust source.
 
 use frits::{Cx, Level, Platform, Runtime, Status, Value};
 
@@ -63,6 +64,35 @@ fn main() {
             }
             return;
         }
+        Some("aot") => {
+            // `frits aot [--platform <decl>] <file>`: the script as Rust source.
+            let Some(path) = args[2..]
+                .iter()
+                .rev()
+                .find(|a| a.ends_with(".frits") && Some(*a) != flag(&args, "--platform").as_ref())
+            else {
+                eprintln!("usage: frits aot [--platform <decl.frits>] <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 plat: Platform<()> = Platform::new(&platform_source(&args)).unwrap_or_else(|e| {
+                eprintln!("the platform declaration: {e}");
+                std::process::exit(1);
+            });
+            match plat.compile(&src) {
+                Ok(m) => print!("{}", frits::aot::generate(&m)),
+                Err(errs) => {
+                    for e in errs {
+                        eprintln!("{path}:{e}");
+                    }
+                    std::process::exit(1);
+                }
+            }
+            return;
+        }
         Some("fmt") => {
             let check = args.iter().any(|a| a == "--check");
             let mut differ = 0;
diff --git a/crates/frits/src/vm.rs b/crates/frits/src/vm.rs
index e2cc6fa..1debd04 100644
--- a/crates/frits/src/vm.rs
+++ b/crates/frits/src/vm.rs
@@ -15,7 +15,7 @@ use crate::platform::{Cx, Platform};
 use crate::value::{Heap, HostValue, Obj, Value};
 
 #[derive(Clone, Copy, Debug)]
-struct Frame {
+pub(crate) struct Frame {
     func: u32,
     pc: u32,
     base: u32,
@@ -51,27 +51,29 @@ pub enum Level {
 
 pub struct Process<S> {
     pub module: Rc<Module>,
-    globals: Vec<Value>,
-    regs: Vec<Value>,
-    frames: Vec<Frame>,
+    pub(crate) globals: Vec<Value>,
+    pub(crate) regs: Vec<Value>,
+    pub(crate) frames: Vec<Frame>,
     pub heap: Heap,
-    mailbox: VecDeque<(u32, Vec<HostValue>)>,
+    pub(crate) mailbox: VecDeque<(u32, Vec<HostValue>)>,
     pub state: S,
     pub status: Status,
     /// Instructions executed over the process's life.
     pub executed: u64,
-    rng: u64,
-    waiting: bool,
+    pub(crate) rng: u64,
+    pub(crate) waiting: bool,
     /// What the script logged since the host last took it (`take_log`).
-    log: Vec<LogLine>,
+    pub(crate) log: Vec<LogLine>,
     /// Kept values to put back once the globals are initialised.
-    restore: Vec<(String, String, HostValue)>,
+    pub(crate) 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)>,
     /// The view last rendered and not yet taken by the host.
-    view: Option<HostValue>,
+    pub(crate) view: Option<HostValue>,
+    /// Compiled code for every function, when the host attached it (`aot`).
+    pub(crate) natives: Option<Rc<[crate::aot::NativeFn<S>]>>,
 }
 
 /// Events a process holds before more are refused: a script flooded with
@@ -111,6 +113,7 @@ impl<S> Process<S> {
             addr: 0,
             outbox: Vec::new(),
             view: None,
+            natives: None,
             module,
         };
         let init = p.module.init;
@@ -235,7 +238,7 @@ impl<S> Process<S> {
             + self.mailbox.capacity() * size_of::<(u32, Vec<HostValue>)>()
     }
 
-    fn collect(&mut self, top: usize) {
+    pub(crate) fn collect(&mut self, top: usize) {
         let top = top.min(self.regs.len());
         self.heap.collect(self.globals.iter().chain(&self.regs[..top]));
     }
@@ -250,7 +253,7 @@ impl<S> Process<S> {
         Outcome::Died(msg)
     }
 
-    fn located(&self, f: u32, pc: u32, msg: &str) -> String {
+    pub(crate) 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)
@@ -284,6 +287,27 @@ impl<S> Process<S> {
                 for (i, a) in args.iter().enumerate() {
                     self.regs[i] = self.heap.import(a);
                 }
+                if let Some(natives) = self.natives.clone() {
+                    // Compiled code runs the whole handler at once.
+                    fuel = fuel.saturating_sub(1);
+                    let mut x = crate::aot::Native {
+                        p: self,
+                        plat,
+                        m,
+                        natives: &natives,
+                        mem_limit,
+                        depth: 0,
+                    };
+                    match (natives[f as usize])(&mut x, 0) {
+                        Ok(_) => {
+                            if f == m.init && !self.restore.is_empty() {
+                                self.apply_restore();
+                            }
+                            continue 'events;
+                        }
+                        Err(e) => break 'events self.die(e),
+                    }
+                }
                 self.frames.push(Frame {
                     func: f,
                     pc: 0,
diff --git a/docs/design.md b/docs/design.md
index 0c74ae7..b0739cb 100644
--- a/docs/design.md
+++ b/docs/design.md
@@ -161,6 +161,28 @@ on receive(m: Msg) {
   `Process::take_view` and reads it with `frits::view::decode`.
 - Tags and attribute names are the host's: Frits does not check them yet.
 
+## Compiled ahead of time
+
+`frits aot [--platform <decl.frits>] <file>` writes a script as Rust source:
+one native function per script function, each basic block straight Rust with
+its constants written in, on the same registers, heap and collector as the
+interpreter. A host builds it into its binary and attaches it with
+`Process::set_natives(natives(), FINGERPRINT)`; natives generated from other
+code (another script, another compiler) are refused and the interpreter runs.
+`crates/aot-check` generates natives at build time and checks them against the
+interpreter.
+
+**Native code runs to completion**: fuel does not count it and it cannot be
+paused, so a host call that suspends (`Timer.wait`) stops it with an error.
+It is for apps the device's owner installs, on a system that preempts threads
+(Pinnacle); uploaded scripts, such as the Cartopolis simulator's, stay
+interpreted.
+
+Measured on vps-1 (release, 2026-11-26), `crates/aot-check/scripts/work.frits`
+(recursion, a 200,000-step loop allocating enum values, closures, maps,
+`Result`): interpreted 67.5 ms, compiled 32.8 ms, 2.1×. Allocation and
+collection are untouched by compilation and likely most of what is left.
+
 ## Tools
 
 - `frits fmt [--check] <file>…` gives every script one layout. It works on the
@@ -178,7 +200,7 @@ on receive(m: Msg) {
   host serves it (Cartopolis's MCP `scripting_guide`), so it cannot drift from
   what scripts can call.
 - `frits test <file>` runs a script's `test` blocks; `frits run <file>` runs it
-  on the console platform.
+  on the console platform; `frits aot` is above.
 
 ## The platform