git clone https://garage44.eu/jeroen/frits.gitcartopolis-agent · 2026-11-26T06:35:47Z
feat(bench): Cartopolis's firebird and football in Frits, measured The two content packs ported from Lua, a stand-in simulator platform, behaviour tests for both, and the benchmark of s693's scenarios. Measured on mac-1 (Apple M5 Pro VM), 2026-11-26, against the Bun 1.4.4 and Luau figures Cartopolis recorded on the same machine: - 2000 firebirds: 0.9-1.1 ms a tick (Bun 10.8, Luau 11.1) - 2000 footballs: 0.46-0.69 ms (Bun 3.2, Luau 3.3) - fuel bank, 10 x 20,000 instructions: 0.32 ms (Bun 0.46, Luau 2.6) - fib(15): 0.037 ms (Bun ~0.18, Luau ~0.055) - load 2000 firebirds: ~220 ms (Bun 20-32, Luau 165-337) - idle script: 1.1 KB resident (Luau ~440-510 KB) The content rows flatter Frits: this host sends no per-tick prim views across a thread and has no command channel, which the simulator's does. The fuel bank and fib rows compare the engines alone. Load time is one compile per script; most of the 22 KB resident per firebird is that compiled copy, which a module shared per source hash would remove. A test compiles the `frits` examples in README.md and docs/design.md, so the documentation fails the build when the language moves away.
Cargo.lock | 7 +
Cargo.toml | 2 +-
README.md | 31 +++
crates/bench/Cargo.toml | 14 +
crates/bench/scripts/firebird.frits | 207 ++++++++++++++
crates/bench/scripts/football.frits | 99 +++++++
crates/bench/src/main.rs | 534 ++++++++++++++++++++++++++++++++++++
docs/design.md | 146 ++++++++++
8 files changed, 1039 insertions(+), 1 deletion(-)
diff --git a/Cargo.lock b/Cargo.lock
index c6aac05..f30a414 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -5,3 +5,10 @@ version = 4
[[package]]
name = "frits"
version = "0.1.0"
+
+[[package]]
+name = "frits-bench"
+version = "0.1.0"
+dependencies = [
+ "frits",
+]
diff --git a/Cargo.toml b/Cargo.toml
index 7ea7fd3..81659ef 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,5 +1,5 @@
[workspace]
-members = ["crates/frits"]
+members = ["crates/frits", "crates/bench"]
resolver = "3"
[workspace.package]
diff --git a/README.md b/README.md
index afe0ac6..46fdede 100644
--- a/README.md
+++ b/README.md
@@ -5,3 +5,34 @@ simulator as well. It replaces TypeScript/Bun for apps, scripts, the shell and
prim scripts.
Written in Rust with no outside crates, like Pinnacle itself.
+
+- **Typed, without writing many types.** Records, enums and `match`, and no
+ `null`. Locals are inferred.
+- **Every script is a small process** with its own heap. Its memory has a
+ ceiling, and its time has a fuel slice per tick. A script that runs too long
+ is paused and resumed, not killed.
+- **Effects are rights.** `script / Prim, Chat` says what a script may touch,
+ and `fn fly() / Prim` what a function does. The compiler holds both to it.
+
+```frits
+script / Prim, Chat, Timer
+
+enum State { Patrol, Summoned }
+var state = Patrol
+
+on timer() {
+ match state {
+ Patrol => Prim.set_geo({ lat: 53.2194, lng: 6.5665 }),
+ Summoned => Chat.say("Coming, {Timer.now():.1} s in."),
+ }
+}
+```
+
+`docs/design.md` describes the language, the runtime and how they measure
+against Luau and Bun.
+
+```bash
+cargo test --workspace # the language's tests and the ported Cartopolis scripts
+cargo run --release -p frits-bench # the benchmark against the simulator scenarios
+cargo run -p frits -- run hello.frits # a script on the console platform (`on main()`)
+```
diff --git a/crates/bench/Cargo.toml b/crates/bench/Cargo.toml
new file mode 100644
index 0000000..f7d80cd
--- /dev/null
+++ b/crates/bench/Cargo.toml
@@ -0,0 +1,14 @@
+[package]
+name = "frits-bench"
+version.workspace = true
+edition.workspace = true
+license.workspace = true
+publish.workspace = true
+
+[dependencies]
+frits = { path = "../frits" }
+
+[[bin]]
+name = "frits-bench"
+path = "src/main.rs"
+test = true
diff --git a/crates/bench/scripts/firebird.frits b/crates/bench/scripts/firebird.frits
new file mode 100644
index 0000000..d35922f
--- /dev/null
+++ b/crates/bench/scripts/firebird.frits
@@ -0,0 +1,207 @@
+// The firebird: a burning thing that circles Groningen, comes when the beacon on
+// the Grote Markt calls it, and goes off if you sneak up on it.
+//
+// Cartopolis's `content/firebird.lua`, written in Frits. What changed in the
+// translation: the state machine is an enum, so `match` checks every state is
+// handled; positions are records; and the script says up front what it does
+// (`script / …`), which is all it can do.
+
+script / Prim, Chat, Channel, Sensor, Timer
+
+// Where it circles, how wide, how long a lap takes, and how high it flies.
+let CENTRE = { lat: 53.2194, lng: 6.5665 }
+let RADIUS_M = 180.0
+let LAP_S = 48.0
+let ALTITUDE_M = 45.0
+
+// Where it hovers when it has been called in.
+let BEACON = { lat: 53.21935, lng: 6.56675 }
+let HOVER_M = 9.0
+let HOVER_DRIFT_M = 2.5
+
+// How near an avatar has to get to startle it, in metres.
+let NOTICE_M = 45.0
+
+// How long it shakes before it goes, and how far it rattles.
+let SHAKE_S = 2.5
+let SHAKE_M = 0.6
+
+// How long the blast is left standing before the shell reforms.
+let LINGER_S = 2.0
+
+// How long after being released it is too busy climbing away to be startled.
+let RELEASE_GRACE_S = 6.0
+
+// The channel the beacon is on.
+let CHANNEL = 4747
+
+// Metres per degree here, computed once: this thing never leaves Groningen.
+let M = geo.metres_per_degree(CENTRE.lat)
+
+enum State { Patrol, Summoned, Shaking, Blown }
+
+var state = Patrol
+var marked = 0.0
+// Time the patrol is measured from, so being summoned and released does not
+// teleport it round its own circle.
+var lap_epoch = 0.0
+var calm_until = 0.0
+
+// A flame: hot core, rising, curling. Every field left out keeps the fire preset's.
+var flame = {
+ ..Prim.fire,
+ count: 120,
+ life: 1.3,
+ speed: 2.2,
+ spread_deg: 26,
+ gravity: 2.6,
+ source_radius: 0.6,
+ size_start: 1.1,
+ size_end: 0.15,
+ color_start: { r: 5.0, g: 2.2, b: 0.5 },
+ color_end: { r: 1.2, g: 0.1, b: 0.02 },
+ turbulence: 1.2,
+}
+
+fn light_it() / Prim {
+ Prim.alpha(1.0)
+ Prim.glow(0.25)
+ Prim.particles(flame)
+}
+
+fn at_height(y: Float) / Prim {
+ let p = Prim.pos()
+ Prim.set_pos({ ..p, y: y })
+}
+
+on start() {
+ Prim.name("Firebird")
+ // A dark shell, so what you see is the fire and not a lit cylinder.
+ Prim.color({ r: 0.09, g: 0.07, b: 0.06 })
+ Prim.scale({ x: 1.6, y: 0.9, z: 1.6 })
+ at_height(ALTITUDE_M)
+ light_it()
+ Channel.listen(CHANNEL)
+ Chat.shout("The firebird is up.")
+ // One tick at 20 Hz.
+ Timer.every(0.05)
+}
+
+// Where on the circle it is at time `t`.
+fn fly(t: Float) / Prim {
+ let a = (t - lap_epoch) / LAP_S * 2 * math.pi
+ Prim.set_geo({
+ lat: CENTRE.lat + RADIUS_M * math.cos(a) / M.lat,
+ lng: CENTRE.lng + RADIUS_M * math.sin(a) / M.lng,
+ })
+ // Nose along the tangent.
+ Prim.set_rot({ x: 0, y: -math.deg(a), z: 0 })
+}
+
+// Hovering over the beacon, turning slowly and bobbing.
+fn hover(t: Float) / Prim {
+ let a = t * 0.7
+ Prim.set_geo({
+ lat: BEACON.lat + HOVER_DRIFT_M * math.cos(a) / M.lat,
+ lng: BEACON.lng + HOVER_DRIFT_M * math.sin(a) / M.lng,
+ })
+ at_height(HOVER_M + 0.6 * math.sin(t * 1.7))
+ Prim.set_rot({ x: 0, y: math.deg(a) * 2, z: 0 })
+}
+
+// What the beacon's label is asking about.
+fn report() / Channel {
+ Channel.send(CHANNEL, if state == Summoned { "here" } else { "patrolling" })
+}
+
+on message(channel: Int, text: Str, sender: Int) {
+ if text == "where" {
+ report()
+ return
+ }
+ // Anything else on this channel is a press.
+ match state {
+ Summoned => {
+ state = Patrol
+ // Rejoin the circle where it left it.
+ lap_epoch = Timer.now()
+ calm_until = Timer.now() + RELEASE_GRACE_S
+ at_height(ALTITUDE_M)
+ Chat.shout("Back to the rounds.")
+ report()
+ }
+ Patrol => {
+ state = Summoned
+ Chat.shout("Coming.")
+ report()
+ }
+ // Mid-explosion: it reports again when it reforms.
+ Shaking => {}
+ Blown => {}
+ }
+}
+
+on timer() {
+ let now = Timer.now()
+ match state {
+ Summoned => hover(now),
+ Patrol => {
+ fly(now)
+ if now >= calm_until {
+ if let Some(who) = Sensor.nearest(NOTICE_M) {
+ state = Shaking
+ marked = now
+ Chat.shout("{who.name} is {who.distance:.0} m away. Stand back.")
+ // Wind the flame up: the fire is the warning.
+ flame = { ..flame, count: 200, speed: 4.0, size_start: 1.6 }
+ Prim.particles(flame)
+ }
+ }
+ }
+ Shaking => {
+ let t = now - marked
+ // Rattle in place, in geo: horizontal position is the anchor's.
+ let wobble = SHAKE_M * (t / SHAKE_S)
+ let g = Prim.geo()
+ Prim.set_geo({
+ lat: g.lat + wobble * math.sin(t * 47) / M.lat,
+ lng: g.lng + wobble * math.cos(t * 53) / M.lng,
+ })
+ Prim.set_rot({ x: 6 * math.sin(t * 61), y: 0, z: 6 * math.cos(t * 59) })
+ if t >= SHAKE_S {
+ state = Blown
+ marked = now
+ Chat.shout("...")
+ Prim.burst({
+ ..Prim.fire,
+ count: 240,
+ life: 1.4,
+ speed: 18.0,
+ spread_deg: 180,
+ gravity: -9.0,
+ source_radius: 1.0,
+ size_start: 2.2,
+ size_end: 0.3,
+ color_start: { r: 8.0, g: 3.6, b: 1.0 },
+ color_end: { r: 0.9, g: 0.12, b: 0.02 },
+ })
+ // The shell goes, the blast stays.
+ Prim.alpha(0.0)
+ Prim.glow(0.0)
+ }
+ }
+ Blown => {
+ if now - marked >= LINGER_S {
+ // Reform out on the circle, away from whoever startled it.
+ state = Patrol
+ lap_epoch = now
+ calm_until = now + RELEASE_GRACE_S
+ flame = { ..flame, count: 120, speed: 2.2, size_start: 1.1 }
+ at_height(ALTITUDE_M)
+ fly(now)
+ light_it()
+ report()
+ }
+ }
+ }
+}
diff --git a/crates/bench/scripts/football.frits b/crates/bench/scripts/football.frits
new file mode 100644
index 0000000..9c4cae3
--- /dev/null
+++ b/crates/bench/scripts/football.frits
@@ -0,0 +1,99 @@
+// The football in the Euroborg: a physical prim that referees itself.
+//
+// Cartopolis's `content/football.lua`, written in Frits. The physics is the
+// simulator's; the script notices the ball crossing a goal line between the
+// posts, keeps the score, says so, and puts the ball back on the centre spot.
+
+script / Prim, Chat, Timer, Sound
+
+let NORTH = { lat: 53.20661975, lng: 6.5916658 }
+let SOUTH = { lat: 53.20566315, lng: 6.5916427 }
+
+let GOAL_HALF_WIDTH = 3.66 // metres either side of the middle of the line
+let GOAL_HEIGHT = 2.44
+let BALL_RADIUS = 0.11
+// Further than this outside the lines and the ball is past the advertising boards.
+let OUT_OF_PLAY = 4.5
+// Half of the pitch's 68 m width; the two goal points carry only its length.
+let HALF_WIDTH = 34.0
+
+let CENTRE = { lat: (NORTH.lat + SOUTH.lat) / 2, lng: (NORTH.lng + SOUTH.lng) / 2 }
+let M = geo.metres_per_degree(CENTRE.lat)
+
+// The pitch's own axes in metres: `along` points at the north goal, `across`
+// is square to it, pointing roughly east.
+let AXIS = {
+ let e = (NORTH.lng - SOUTH.lng) * M.lng
+ let n = (NORTH.lat - SOUTH.lat) * M.lat
+ let length = math.sqrt(e * e + n * n)
+ { e: e / length, n: n / length, half_length: length / 2 }
+}
+
+var north_score = 0
+var south_score = 0
+// Seconds until the ball goes back to the centre spot, when it is out of play.
+var restart_in: Option<Float> = None
+
+fn on_pitch() -> { along: Float, across: Float } / Prim {
+ let g = Prim.geo()
+ let e = (g.lng - CENTRE.lng) * M.lng
+ let n = (g.lat - CENTRE.lat) * M.lat
+ { along: e * AXIS.e + n * AXIS.n, across: e * AXIS.n - n * AXIS.e }
+}
+
+fn score_line() -> Str {
+ "North {north_score} – {south_score} South"
+}
+
+fn place_on_centre_spot() / Prim {
+ Prim.set_geo(CENTRE)
+ let p = Prim.pos()
+ // Dropped from a little height, so a restart reads as one.
+ Prim.set_pos({ ..p, y: 1.0 })
+ Prim.set_vel({ x: 0, y: 0, z: 0 })
+}
+
+on start() {
+ Prim.name("Football — run into it to dribble, kick emote (5) to shoot")
+ Prim.color({ r: 1.0, g: 1.0, b: 1.0 })
+ Prim.physical(true)
+ Timer.every(0.1)
+}
+
+on touch(id: Int, name: Str) {
+ Chat.say("{name} puts the ball on the centre spot. {score_line()}")
+ restart_in = None
+ place_on_centre_spot()
+}
+
+on timer() {
+ if let Some(t) = restart_in {
+ if t - 0.1 <= 0 {
+ restart_in = None
+ place_on_centre_spot()
+ } else {
+ restart_in = Some(t - 0.1)
+ }
+ return
+ }
+
+ let p = on_pitch()
+ let y = Prim.pos().y
+ let between_posts = math.abs(p.across) < GOAL_HALF_WIDTH - BALL_RADIUS && y < GOAL_HEIGHT - BALL_RADIUS
+
+ // Wholly over the line, between the posts and under the bar.
+ if between_posts && p.along > AXIS.half_length + BALL_RADIUS {
+ south_score += 1
+ Chat.shout("GOAL at the north end! {score_line()}")
+ Sound.play("bell")
+ restart_in = Some(3)
+ } else if between_posts && p.along < -(AXIS.half_length + BALL_RADIUS) {
+ north_score += 1
+ Chat.shout("GOAL at the south end! {score_line()}")
+ Sound.play("bell")
+ restart_in = Some(3)
+ } else if math.abs(p.along) > AXIS.half_length + OUT_OF_PLAY || math.abs(p.across) > HALF_WIDTH + OUT_OF_PLAY {
+ Chat.say("The ball went over the boards; back to the centre spot.")
+ restart_in = Some(1)
+ }
+}
diff --git a/crates/bench/src/main.rs b/crates/bench/src/main.rs
new file mode 100644
index 0000000..7e638fc
--- /dev/null
+++ b/crates/bench/src/main.rs
@@ -0,0 +1,534 @@
+//! Frits under the scenarios Cartopolis measured Luau and Bun with (session
+//! s693, `tools/script-host/bench`, mac-1): N prims running one content pack,
+//! 200 ticks at 20 Hz with a touch on prim 1 every 20 ticks; ten scripts that
+//! never stop; load time; memory per script.
+//!
+//! The platform is a stand-in for the simulator's: prim state lives in Rust,
+//! every call does the bookkeeping a host would (a command per change), and
+//! channel messages are routed between prims after each tick.
+
+use std::rc::Rc;
+use std::time::Instant;
+
+use frits::{Cx, HostValue, Limits, Platform, Runtime, Value};
+
+const SIM: &str = "
+type Geo = { lat: Float, lng: Float }
+type Vec3 = { x: Float, y: Float, z: Float }
+type Rgb = { r: Float, g: Float, b: Float }
+type Particles = {
+ count: Int, life: Float, speed: Float, spread_deg: Float, gravity: Float,
+ source_radius: Float, size_start: Float, size_end: Float,
+ color_start: Rgb, color_end: Rgb, turbulence: Float,
+}
+
+effect Prim {
+ fn name(text: Str)
+ fn color(c: Rgb)
+ fn scale(s: Vec3)
+ fn pos() -> Vec3
+ fn set_pos(p: Vec3)
+ fn geo() -> Geo
+ fn set_geo(g: Geo)
+ fn set_rot(degrees: Vec3)
+ fn alpha(a: Float)
+ fn glow(g: Float)
+ fn physical(enabled: Bool)
+ fn set_vel(v: Vec3)
+ fn particles(p: Particles)
+ fn burst(p: Particles)
+ let fire: Particles
+}
+effect Chat {
+ fn say(text: Str)
+ fn shout(text: Str)
+}
+effect Channel {
+ fn listen(channel: Int)
+ fn send(channel: Int, text: Str)
+}
+effect Sensor {
+ fn nearest(radius: Float) -> Option<{ distance: Float, id: Int, name: Str }>
+}
+effect Timer {
+ fn every(seconds: Float)
+ fn now() -> Float
+}
+effect Sound {
+ fn play(name: Str)
+}
+module geo {
+ fn metres_per_degree(lat: Float) -> Geo
+}
+
+event start()
+event timer()
+event message(channel: Int, text: Str, sender: Int)
+event touch(id: Int, name: Str)
+";
+
+/// What the simulator would have to do with a script's call.
+#[allow(dead_code)]
+enum Command {
+ Moved,
+ Look,
+ Particles,
+ Said(String),
+ Sound(String),
+}
+
+#[derive(Default)]
+struct Prim {
+ geo: (f64, f64),
+ pos: [f64; 3],
+ now: f64,
+ timer: Option<f64>,
+ next_timer: f64,
+ listening: Vec<i64>,
+ sent: Vec<(i64, String)>,
+ commands: Vec<Command>,
+ /// The avatar the sensor sees, if any: id, name, metres away.
+ nearby: Option<(i64, String, f64)>,
+}
+
+fn vec3(cx: &Cx<Prim>, v: Value) -> [f64; 3] {
+ let f = cx.fields(v);
+ [f[0].float(), f[1].float(), f[2].float()]
+}
+
+fn platform() -> Platform<Prim> {
+ let mut p = Platform::new(SIM).expect("the simulator declaration parses");
+ fn look(cx: &mut Cx<Prim>, _: &[Value]) -> Result<Value, String> {
+ cx.state.commands.push(Command::Look);
+ Ok(Value::Unit)
+ }
+ fn particles(cx: &mut Cx<Prim>, a: &[Value]) -> Result<Value, String> {
+ // A host reads the whole record to build its emitter.
+ let n = cx.fields(a[0]).len();
+ if n != 11 {
+ return Err("bad particles".into());
+ }
+ cx.state.commands.push(Command::Particles);
+ Ok(Value::Unit)
+ }
+ p.bind("Prim.name", look)
+ .bind("Prim.color", look)
+ .bind("Prim.scale", look)
+ .bind("Prim.alpha", look)
+ .bind("Prim.glow", look)
+ .bind("Prim.physical", look)
+ .bind("Prim.set_rot", look)
+ .bind("Prim.set_vel", look)
+ .bind("Prim.particles", particles)
+ .bind("Prim.burst", particles)
+ .bind("Prim.pos", |cx, _| {
+ let [x, y, z] = cx.state.pos;
+ Ok(cx.record(&[Value::Float(x), Value::Float(y), Value::Float(z)]))
+ })
+ .bind("Prim.set_pos", |cx, a| {
+ cx.state.pos = vec3(cx, a[0]);
+ cx.state.commands.push(Command::Moved);
+ Ok(Value::Unit)
+ })
+ .bind("Prim.geo", |cx, _| {
+ let (lat, lng) = cx.state.geo;
+ Ok(cx.record(&[Value::Float(lat), Value::Float(lng)]))
+ })
+ .bind("Prim.set_geo", |cx, a| {
+ let f = cx.fields(a[0]);
+ cx.state.geo = (f[0].float(), f[1].float());
+ cx.state.commands.push(Command::Moved);
+ Ok(Value::Unit)
+ })
+ .bind("Chat.say", |cx, a| {
+ let s = cx.str(a[0]).to_string();
+ cx.state.commands.push(Command::Said(s));
+ Ok(Value::Unit)
+ })
+ .bind("Chat.shout", |cx, a| {
+ let s = cx.str(a[0]).to_string();
+ cx.state.commands.push(Command::Said(s));
+ Ok(Value::Unit)
+ })
+ .bind("Channel.listen", |cx, a| {
+ cx.state.listening.push(a[0].int());
+ Ok(Value::Unit)
+ })
+ .bind("Channel.send", |cx, a| {
+ let s = cx.str(a[1]).to_string();
+ cx.state.sent.push((a[0].int(), s));
+ Ok(Value::Unit)
+ })
+ // No avatars in the benchmark world, as in s693's; the tests place one.
+ .bind("Sensor.nearest", |cx, a| match cx.state.nearby.clone() {
+ Some((id, name, d)) if d <= a[0].float() => {
+ let name = cx.new_str(&name);
+ let r = cx.record(&[Value::Float(d), Value::Int(id), name]);
+ Ok(cx.some(r))
+ }
+ _ => Ok(cx.none()),
+ })
+ .bind("Timer.every", |cx, a| {
+ cx.state.timer = Some(a[0].float());
+ cx.state.next_timer = cx.state.now + a[0].float();
+ Ok(Value::Unit)
+ })
+ .bind("Timer.now", |cx, _| Ok(Value::Float(cx.state.now)))
+ .bind("Sound.play", |cx, a| {
+ let s = cx.str(a[0]).to_string();
+ cx.state.commands.push(Command::Sound(s));
+ Ok(Value::Unit)
+ })
+ .bind("geo.metres_per_degree", |cx, a| {
+ let phi = a[0].float().to_radians();
+ let lat = 111_132.92 - 559.82 * (2.0 * phi).cos() + 1.175 * (4.0 * phi).cos();
+ let lng = 111_412.84 * phi.cos() - 93.5 * (3.0 * phi).cos();
+ Ok(cx.record(&[Value::Float(lat), Value::Float(lng)]))
+ });
+ let rgb = |r, g, b| {
+ HostValue::Record(vec![
+ HostValue::Float(b),
+ HostValue::Float(g),
+ HostValue::Float(r),
+ ])
+ };
+ // Fields in name order: color_end, color_start, count, gravity, life,
+ // size_end, size_start, source_radius, speed, spread_deg, turbulence.
+ p.constant(
+ "Prim.fire",
+ HostValue::Record(vec![
+ rgb(1.0, 0.1, 0.0),
+ rgb(4.0, 1.5, 0.3),
+ HostValue::Int(80),
+ HostValue::Float(2.0),
+ HostValue::Float(1.0),
+ HostValue::Float(0.1),
+ HostValue::Float(1.0),
+ HostValue::Float(0.5),
+ HostValue::Float(2.0),
+ HostValue::Float(20.0),
+ HostValue::Float(1.0),
+ ]),
+ );
+ let unbound = p.unbound();
+ assert!(unbound.is_empty(), "unbound: {unbound:?}");
+ p
+}
+
+fn rss() -> f64 {
+ let out = std::process::Command::new("ps")
+ .args(["-o", "rss=", "-p", &std::process::id().to_string()])
+ .output()
+ .expect("ps");
+ String::from_utf8_lossy(&out.stdout)
+ .trim()
+ .parse::<f64>()
+ .unwrap_or(0.0)
+ * 1024.0
+}
+
+fn stats(mut ms: Vec<f64>) -> (f64, f64) {
+ ms.sort_by(|a, b| a.partial_cmp(b).unwrap());
+ let mean = ms.iter().sum::<f64>() / ms.len() as f64;
+ let p99 = ms[((ms.len() as f64) * 0.99) as usize - 1];
+ (mean, p99)
+}
+
+struct World {
+ rt: Runtime<Prim>,
+ pids: Vec<u32>,
+ now: f64,
+}
+
+impl World {
+ fn new() -> Self {
+ World {
+ rt: Runtime::new(platform()),
+ pids: Vec::new(),
+ now: 0.0,
+ }
+ }
+
+ /// Compile each script on its own, as a host that stores source per prim must.
+ fn load(&mut self, sources: &[&str], n: usize) -> f64 {
+ let t = Instant::now();
+ for i in 0..n {
+ let m = self
+ .rt
+ .platform
+ .compile(sources[i % sources.len()])
+ .unwrap_or_else(|e| panic!("{e:?}"));
+ let prim = Prim {
+ geo: (53.2194, 6.5665),
+ pos: [0.0, 0.0, 0.0],
+ ..Default::default()
+ };
+ let pid = self.rt.spawn(m, prim);
+ self.rt.post(pid, "start", Vec::new());
+ self.pids.push(pid);
+ }
+ // Run the globals and `on start` before timing anything else.
+ while !self.rt.tick().is_empty() {}
+ t.elapsed().as_secs_f64() * 1000.0
+ }
+
+ /// One simulator tick: advance the clock, fire due timers, run a slice each,
+ /// route channel messages. Returns milliseconds.
+ fn tick(&mut self, dt: f64, touch: bool) -> f64 {
+ let t = Instant::now();
+ self.now += dt;
+ let now = self.now;
+ for (i, &pid) in self.pids.iter().enumerate() {
+ let p = self.rt.get_mut(pid).unwrap();
+ p.state.now = now;
+ p.state.commands.clear();
+ if let Some(every) = p.state.timer
+ && now + 1e-9 >= p.state.next_timer
+ {
+ p.state.next_timer += every;
+ p.post("timer", Vec::new());
+ }
+ if touch && i == 0 {
+ p.post("touch", vec![HostValue::Int(42), HostValue::Str("Anna".into())]);
+ }
+ }
+ let died = self.rt.tick();
+ assert!(died.is_empty(), "{died:?}");
+ // Deliver what was sent to everyone listening on the channel.
+ let mut mail = Vec::new();
+ for &pid in &self.pids {
+ let p = self.rt.get_mut(pid).unwrap();
+ for (ch, text) in p.state.sent.drain(..) {
+ mail.push((pid, ch, text));
+ }
+ }
+ if !mail.is_empty() {
+ let listeners: Vec<(u32, Vec<i64>)> = self
+ .pids
+ .iter()
+ .map(|&p| (p, self.rt.get(p).unwrap().state.listening.clone()))
+ .collect();
+ for (from, ch, text) in mail {
+ for (to, chans) in &listeners {
+ if *to != from && chans.contains(&ch) {
+ let args = vec![
+ HostValue::Int(ch),
+ HostValue::Str(text.clone()),
+ HostValue::Int(from as i64),
+ ];
+ self.rt.post(*to, "message", args);
+ }
+ }
+ }
+ }
+ t.elapsed().as_secs_f64() * 1000.0
+ }
+
+ fn script_bytes(&self) -> usize {
+ self.pids.iter().map(|&p| self.rt.get(p).unwrap().memory()).sum()
+ }
+}
+
+fn main() {
+ let firebird = include_str!("../scripts/firebird.frits");
+ let football = include_str!("../scripts/football.frits");
+ let idle = "script / Chat\non touch(id: Int, name: Str) { }";
+ let groups: [(&str, Vec<&str>); 3] = [
+ ("idle", vec![idle]),
+ ("firebird", vec![firebird]),
+ ("football", vec![football]),
+ ];
+
+ println!(
+ "scenario scripts load_ms tick_mean_ms tick_p99_ms rss_bytes_per_script own_bytes_per_script"
+ );
+ for n in [200usize, 2000] {
+ for (label, sources) in &groups {
+ let before = rss();
+ let mut w = World::new();
+ let load_ms = w.load(sources, n);
+ let mut ms = Vec::new();
+ for tick in 0..200 {
+ ms.push(w.tick(0.05, tick % 20 == 5));
+ }
+ let after = rss();
+ let (mean, p99) = stats(ms);
+ println!(
+ "{label:<9} {n:>7} {load_ms:>7.1} {mean:>12.3} {p99:>11.3} {:>20.0} {:>20.0}",
+ (after - before) / n as f64,
+ w.script_bytes() as f64 / n as f64
+ );
+ }
+ }
+
+ // Ten scripts that never stop, so every slice is spent: the fuel bank.
+ let busy = "script / Chat\nvar s = 0\non start() { while true { s = s + 1\n if s % 100000 == 0 { Chat.say(\"{s}\") } } }";
+ let calls = "script / Chat\nvar n = 0\nfn fib(k: Int) -> Int { if k < 2 { k } else { fib(k - 1) + fib(k - 2) } }\non start() { while true { let x = fib(15)\n n = n + 1\n if n % 100 == 0 { Chat.say(\"{n}\") } } }";
+ println!();
+ println!(
+ "scenario scripts fuel_per_slice tick_mean_ms tick_p99_ms instructions_per_tick ns_per_instruction"
+ );
+ for (label, src) in [("busy", busy), ("calls", calls)] {
+ let mut w = World::new();
+ w.rt.limits = Limits::default();
+ let m: Rc<_> = w.rt.platform.compile(src).unwrap();
+ for _ in 0..10 {
+ let pid = w.rt.spawn(m.clone(), Prim::default());
+ w.rt.post(pid, "start", Vec::new());
+ w.pids.push(pid);
+ }
+ let mut ms = Vec::new();
+ for _ in 0..100 {
+ ms.push(w.tick(0.05, false));
+ }
+ let (mean, p99) = stats(ms);
+ let executed: u64 = w.pids.iter().map(|&p| w.rt.get(p).unwrap().executed).sum();
+ let per_tick = executed as f64 / 100.0;
+ let ns = mean * 1e6 / per_tick;
+ println!(
+ "{label:<9} {:>7} {:>14} {mean:>12.3} {p99:>11.3} {per_tick:>21.0} {ns:>18.2}",
+ 10, w.rt.limits.fuel
+ );
+ }
+
+ // One fib(15), measured alone with all the fuel it wants.
+ let mut w = World::new();
+ w.rt.limits.fuel = u64::MAX;
+ let m = w.rt.platform.compile("script / Chat\nfn fib(k: Int) -> Int { if k < 2 { k } else { fib(k - 1) + fib(k - 2) } }\non start() { var i = 0\n while i < 1000 { let x = fib(15)\n i += 1 } }").unwrap();
+ let pid = w.rt.spawn(m, Prim::default());
+ w.rt.tick();
+ w.rt.post(pid, "start", Vec::new());
+ let t = Instant::now();
+ w.rt.tick();
+ let per = t.elapsed().as_secs_f64() * 1000.0 / 1000.0;
+ println!(
+ "\nfib(15): {per:.4} ms each ({} instructions each)",
+ w.rt.get(pid).unwrap().executed / 1000
+ );
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn said(w: &World, pid: u32) -> Vec<String> {
+ let p = w.rt.get(pid).unwrap();
+ p.state
+ .commands
+ .iter()
+ .filter_map(|c| {
+ if let Command::Said(s) = c {
+ Some(s.clone())
+ } else {
+ None
+ }
+ })
+ .collect()
+ }
+
+ #[test]
+ fn the_firebird_circles_is_startled_explodes_and_reforms() {
+ let mut w = World::new();
+ w.load(&[include_str!("../scripts/firebird.frits")], 1);
+ let pid = w.pids[0];
+ let start = w.rt.get(pid).unwrap().state.geo;
+ let mut heard = Vec::new();
+ for _ in 0..20 {
+ w.tick(0.05, false);
+ heard.extend(said(&w, pid));
+ }
+ assert!(heard.is_empty(), "{heard:?}");
+ assert_ne!(w.rt.get(pid).unwrap().state.geo, start, "it does not fly");
+ // Someone walks up after the release grace has passed.
+ while w.now < 6.0 {
+ w.tick(0.05, false);
+ }
+ w.rt.get_mut(pid).unwrap().state.nearby = Some((7, "Anna".into(), 12.4));
+ for _ in 0..120 {
+ w.tick(0.05, false);
+ heard.extend(said(&w, pid));
+ }
+ assert_eq!(heard, ["Anna is 12 m away. Stand back.", "..."]);
+ assert_eq!(w.rt.get(pid).unwrap().state.sent.len(), 0);
+ }
+
+ #[test]
+ fn the_beacon_summons_and_releases_it() {
+ let mut w = World::new();
+ w.load(&[include_str!("../scripts/firebird.frits")], 1);
+ let pid = w.pids[0];
+ let press = |w: &mut World| {
+ w.rt.get_mut(pid).unwrap().state.commands.clear();
+ w.rt.post(
+ pid,
+ "message",
+ vec![
+ HostValue::Int(4747),
+ HostValue::Str("press".into()),
+ HostValue::Int(99),
+ ],
+ );
+ // The runtime's tick, not the world's, which would deliver what it sent.
+ assert!(w.rt.tick().is_empty());
+ let p = w.rt.get_mut(pid).unwrap();
+ let sent: Vec<String> = p.state.sent.drain(..).map(|(_, t)| t).collect();
+ (said(w, pid), sent)
+ };
+ assert_eq!(
+ press(&mut w),
+ (vec!["Coming.".to_string()], vec!["here".to_string()])
+ );
+ assert_eq!(
+ press(&mut w),
+ (
+ vec!["Back to the rounds.".to_string()],
+ vec!["patrolling".to_string()]
+ )
+ );
+ }
+
+ #[test]
+ fn the_football_counts_a_goal_and_restarts() {
+ let mut w = World::new();
+ w.load(&[include_str!("../scripts/football.frits")], 1);
+ let pid = w.pids[0];
+ // Just over the north goal line, between the posts, on the ground.
+ w.rt.get_mut(pid).unwrap().state.geo = (53.20661975 + 0.00001, 6.5916658);
+ let mut heard = Vec::new();
+ for _ in 0..80 {
+ w.tick(0.05, false);
+ heard.extend(said(&w, pid));
+ }
+ assert_eq!(heard[0], "GOAL at the north end! North 0 – 1 South");
+ let (lat, _) = w.rt.get(pid).unwrap().state.geo;
+ assert!(
+ (lat - 53.20614145).abs() < 1e-6,
+ "not back on the centre spot: {lat}"
+ );
+ w.tick(0.05, true);
+ assert_eq!(
+ said(&w, pid),
+ ["Anna puts the ball on the centre spot. North 0 – 1 South"]
+ );
+ }
+
+ /// The `frits` examples in the documentation compile against this platform.
+ #[test]
+ fn the_documented_examples_compile() {
+ let docs = [
+ include_str!("../../../README.md"),
+ include_str!("../../../docs/design.md"),
+ ];
+ let mut n = 0;
+ for doc in docs {
+ for block in doc.split("```frits\n").skip(1) {
+ let src = block.split("```").next().unwrap();
+ if let Err(e) = platform().compile(src) {
+ panic!("{e:?}\n{src}");
+ }
+ n += 1;
+ }
+ }
+ assert_eq!(n, 2);
+ }
+}
diff --git a/docs/design.md b/docs/design.md
new file mode 100644
index 0000000..f824fbd
--- /dev/null
+++ b/docs/design.md
@@ -0,0 +1,146 @@
+# Frits: design, and what is built
+
+Frits is the scripting language of Pinnacle, meant to take over from
+TypeScript/Bun for apps, scripts and the shell, and from Bun for prim scripts in
+the Cartopolis simulator. This file holds the decisions and the state of the
+code; the reasoning behind each choice is in the 2026-11-26 brainstorm (session
+s851).
+
+## The four choices everything else follows from
+
+1. **Every script is a process with its own heap.** Processes share no mutable
+ memory; a message is copied into the receiver. A memory ceiling is a number
+ per heap, a collection is one process's business, and stopping a script is
+ dropping its heap.
+2. **Every script can be paused anywhere.** The VM counts fuel per instruction.
+ A process's whole execution state (registers, frames, program counter) is
+ data in `vm::Process`, never the Rust stack, so there is no context in which
+ a pause cannot happen. Luau's trap, a yield silently ignored outside a
+ coroutine (Cartopolis `docs/notes/prim-scripting.md`), cannot occur.
+3. **The outside world is reached through effects, and an effect is a right.**
+ A script names what it needs (`script / Prim, Chat`); a function names what
+ it does (`fn fly(t: Float) / Prim`). The compiler refuses a call whose effect
+ the caller lacks. The host still enforces the rights it hands out; the
+ compiler is not a security boundary.
+4. **Nothing is ambient.** No global `fetch`, `process` or file-reading
+ `require`: a platform declares every function a script can call.
+
+## The language as built
+
+```frits
+script / Prim, Chat, Timer
+
+enum State { Patrol, Summoned, Hit(Int, Str) }
+
+let CENTRE = { lat: 53.2194, lng: 6.5665 } // records are structural
+var state = Patrol
+var restart_in: Option<Float> = None
+
+fn fly(t: Float) / Prim {
+ let a = t / 48 * 2 * math.pi // an Int literal beside a Float is a Float
+ Prim.set_geo({ lat: CENTRE.lat + math.cos(a) / 1000, lng: CENTRE.lng })
+}
+
+on timer() {
+ match state { // match must cover every variant
+ Patrol => fly(Timer.now()),
+ Summoned => {}
+ Hit(n, who) => Chat.say("{who} hit it {n} times, {Timer.now():.1} s in"),
+ }
+ if let Some(t) = restart_in { restart_in = Some(t - 0.1) }
+}
+```
+
+- Types: `Int` (64-bit, overflow stops the script), `Float`, `Bool`, `Str`,
+ `List<T>`, `Option<T>`, records (`{ x: Float }`, equal when their fields
+ are), enums with payloads, and `type` aliases. Every local's type is inferred;
+ parameters and non-Unit returns are written.
+- Values are immutable. `p.y = 1` on a `var` builds a new record with the one
+ field changed and stores it back; `{ ..p, y: 1 }` does the same as an
+ expression.
+- Statements end at a newline (Go's rule): an operator that continues a line
+ goes at its end, and `} else {` stays on one line.
+- Strings interpolate: `"{name} is {d:.0} m away"`.
+- No `null`, no exceptions, no classes, no `async`, no implicit conversions
+ (`float(i)`, `int(x)`).
+
+## The platform
+
+A host describes what it offers in Frits, and binds Rust functions to it:
+
+```rust
+let mut p = Platform::<Prim>::new("
+ type Geo = { lat: Float, lng: Float }
+ effect Prim { fn geo() -> Geo fn set_geo(g: Geo) let fire: Particles }
+ module geo { fn metres_per_degree(lat: Float) -> Geo }
+ event timer()
+")?;
+p.bind("Prim.set_geo", |cx, a| { let f = cx.fields(a[0]); /* … */ Ok(Value::Unit) });
+```
+
+`effect` namespaces need the effect, `module` namespaces are pure, `event`s
+are what `on` handlers answer. `math` is in every platform (`prelude.rs`). The
+same script runs on another host by being compiled against its platform.
+
+## The runtime
+
+- Source → tokens (`lexer`) → tree (`parser`) → checked, typed register
+ bytecode (`compile`, one pass) → `vm`. The VM is `#![forbid(unsafe_code)]`.
+- `Runtime::tick` gives every process with work one slice (default 20,000
+ instructions, Luau's slice in the simulator). An unfinished handler resumes on
+ the next tick; events queue in the process's mailbox meanwhile.
+- The collector is a precise mark-and-sweep over one process's heap, run at
+ calls and backward jumps once 4 KiB has been allocated since the last
+ collection (or more, with a larger heap). Live bytes over the limit (default
+ 256 KiB) stop that process.
+- String literals live in the module and are shared by all its processes.
+
+## Measured
+
+mac-1 (Apple M5 Pro VM), 2026-11-26, `cargo run --release -p frits-bench`:
+the same scenarios as Cartopolis's Luau/Bun comparison (s693,
+`docs/notes/javascript-prim-scripts.md` there, also mac-1). Each scenario runs
+200 ticks at 20 Hz, with a touch on prim 1 every 20 ticks.
+
+| | Frits | Bun 1.4.4 | Luau |
+|---|---|---|---|
+| 2000 firebirds, ms per tick | 0.9–1.1 | 10.8 | 11.1 |
+| 2000 footballs, ms per tick | 0.46–0.69 | 3.2 | 3.3 |
+| fuel bank (10 × 20,000 instructions), ms | 0.32 | 0.46 | 2.6 |
+| per `fib(15)`, ms | 0.037 | ~0.18 | ~0.055 |
+| load 2000 firebirds, ms | 217–223 | 20–32 | 165–337 |
+| memory per firebird, runtime's count | 3.3 KB | — | — |
+| memory per firebird, resident | 22 KB | 3–33 KB | 160–435 KB |
+| memory per idle script, resident | 1.1 KB | ~480 KB | ~440–510 KB |
+
+**Read the content rows with care.** The stand-in host here does less than the
+simulator's: no per-tick prim views sent across a thread, no command channel.
+The VM rows (fuel bank, fib) compare the engines alone; the content rows
+compare an engine plus a lighter host against an engine plus the real one.
+
+Load time is compiling each script separately (2000 compiles), as a host that
+stores source per prim would. Most of the resident memory per firebird is that
+compiled copy. Sharing one compiled module among identical sources (the
+content-addressing step) would remove both.
+
+## Not built yet
+
+In the order they are likely to matter:
+
+- Content-addressed modules: one compiled module per source hash, shared.
+- Closures and functions as values; user generics; methods (`xs.len()`);
+ 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.
+- A language server, formatter and debugger.
+- `view` markup on the component library; AOT for Pinnacle apps; wasm.
+
+Known gaps in what is built:
+
+- A function called from a global's initialiser may read a global declared
+ after it; it sees that global as zero/empty rather than an error.
+- Keywords cannot be names (`on`, `in`, `type`…): a parameter called `on` is a
+ syntax error.
+- Fuel counts instructions, so a host function's cost is not charged.