# 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 = 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`, `Map` (keys Int or Str), `Option`, `Result`, tuples `(Int, Str)`, records (`{ x: Float }`, equal when their fields are), enums with payloads, functions `fn(Int) -> Bool / Prim`, `Vec3`, and `type` aliases. Every local's type is inferred; parameters and non-Unit returns are written. - 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 })`). - Generics: `fn first(xs: List) -> Option`, compiled once per set of types it is called with; `enum Tree { Leaf, Node(Tree, T, Tree) }` and `type Pair = { 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`, `replace`, `slice`, `parse_int`, …), maps (`get`, `set`, `has`, `remove`, `keys`, `values`) and `Vec3` (`+ - * /`, `length`, `normalize`, `dot`, `cross`, `distance`, `lerp`). `x.f(a)` calls a script's own `f(x, a)`. A method that changes its receiver (`push`, `set`, `remove`, `remove_at`) needs a variable. - `match` takes nested patterns (`Some(Circle(r))`), tuples, records (`{ name, distance: d }`) and guards (`p if r > 10 =>`), and must cover every value; a guarded arm covers nothing for certain. `let (x, _, z) = …` and `let { lat, lng } = …` take a pattern that always matches. - Errors are values: `Result`, and `e?` passes an `Err` or `None` on to the caller. `==` compares anything without functions in it, by value. - `log(text)`, `warn(text)` and `assert(cond, "why")`; `test "name" { … }` blocks run with `frits test` or `Runtime::test`. - `keep var score = 0`: the host can read kept globals (`Process::kept`) and hand them to a new process (`Process::restore`), so a value survives a restart or a new version of the script. A kept value whose global changed type is dropped. - 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)`). ## 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`; 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`**: 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. - **`Untrusted`**: text from someone else (chat, another person's prim, a message), as the platform declares it (`event heard(text: Untrusted)`). It can be shown: logged, put in a view, passed to a host function that takes `Untrusted`, and a string built from it (`"{text}"`, `+`, `.trim()`, `.split()`) is untrusted too. It cannot go where a plain `Str` is wanted, so it cannot steer an action until the script has checked it: `text.one_of([…])` gives back the script's own matching item, `match text { "reset" => … }` compares it with literals, `.parse_int()` reads a number, and `len`, `contains` and `==` answer questions about it. Trusted text goes wherever untrusted text may. The owner chose this over a label that spreads through every computation (stronger, but surprising) and over rights alone. - **`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. ## Views A script describes a user interface with markup, and the host draws it with its own components (on Pinnacle, the component library): ```frits script / Ui enum Msg { Inc, Dec } var n = 0 fn draw() -> View { "Count: {n}" } on receive(m: Msg) { match m { Inc => n += 1, Dec => n -= 1, } render(draw()) } ``` - Markup is an expression of type `View` (the prelude's enum: `ViewEl(tag, attributes, children)` or `ViewText`), so a view is built with ordinary code: `{rows}` takes a list of views, `.map(fn(i) { "{i}" })` makes one. - An attribute is a Str, Int, Float, Bool, or a message `M`; `M` is what the script's `on receive` takes. Pressing something the host drew posts that message back: the script's state changes only in its own handler (the Elm loop). - `render(v)` needs the `Ui` effect; the host takes the tree with `Process::take_view` and reads it with `frits::view::decode`. - A message variant that carries one Str, named bare (`on_input=Typed` for `enum Msg { Typed(Str) }`), becomes `AttrInput(tag)`: the host builds the message with what the control holds (`view::AttrValue::message`). A constructor rather than a closure, because a closure cannot cross to the host, nor from a server to a browser. - Tags and attribute names are the host's: Frits does not check them yet. Mithril's `mithril_frits` is a host that draws them with its component library, on a server as HTML, in a browser over the DOM, and natively. ## Compiled ahead of time `frits aot [--platform ] ` 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] …` gives every script one layout. It works on the text, so comments and how numbers are written survive; brackets opened on one line indent what follows by one level. - `frits lsp [--platform ]` is a language server for any editor: errors as you type (a whole line, since errors carry lines, not columns), completion after `Prim.` with each function's signature and explanation, hover, and formatting. It checks against the platform declaration it is given, so a Cartopolis prim script is checked against the simulator's. - `frits guide [--platform ] [--title ]` writes the scripting guide as Markdown from the declaration: every effect, module, function, event and type, with the comment above each in the declaration as its explanation, and a page on the language whose examples a test compiles. A host serves it (Cartopolis's MCP `scripting_guide`), so it cannot drift from what scripts can call. - `frits test ` runs a script's `test` blocks; `frits run ` runs it on the console platform; `frits aot` is above. ## The platform A host describes what it offers in Frits, and binds Rust functions to it: ```rust let mut p = Platform::::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. `Vec3`, `math` and the `Random` effect are in every platform (`prelude.rs`). The same script runs on another host by being compiled against its platform. A host function can do three things besides answering: - `cx.suspend()` stops the script after the call until the host calls `Process::wake`. That is how `Timer.wait(2.5)` pauses a handler in its middle, and the rest of the handler runs when it wakes: sequences need no state machine. Events that arrive meanwhile wait their turn. - `cx.charge(n)` counts `n` instructions against the script's slice, so an expensive call is not free. - `cx.random()` draws from the process's own random stream, which the runtime seeds per process. ## Without std, and the same numbers everywhere The `std` feature (on by default) is for the command line and the language server; the language needs only `alloc`, as a Pinnacle app has it (`cargo check -p frits --lib --no-default-features --target aarch64-unknown-none`). Its maps are B-trees, so what a script lists comes out in one order on every machine. `math` is `fmath.rs`, written here, in every build: a no_std build has no `sin`, and taking the platform's would let one script compute different last bits on a server, in a browser (wasm) and on a device — and a view drawn from a number must be the same on all three for a browser to take a server's page over. fdlibm's algorithms; held to std's within 0 ulps (`sqrt`), 1 (`exp`, `ln`, `atan`), 2 (`sin`, `cos`, `atan2`, `hypot`); whole powers by squaring, so `pow(2, 10)` is 1024. Angles beyond a million radians are reduced modulo 2π as a double: the same everywhere, but not std's answer. The interpreter builds for wasm32 unchanged (2026-11-27, Mithril's `examples/frits-web`: 929 KB of wasm with the compiler, 234 KB gzipped). ## 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. - `Platform::compile` keeps compiled modules by source (weakly), so a thousand prims running one script share one compiled module. - `map`, `filter` and the other methods that take a function are compiled into loops in the script's own bytecode, so the function they call is counted and can be paused like any other code. No host function calls back into a script. ## 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 | 5 | 20–32 | 165–337 | | memory per firebird, runtime's count | 3.5 KB | — | — | | memory per firebird, resident | 12 KB | 3–33 KB | 160–435 KB | | memory per idle script, resident | 0.7 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. The load and memory rows were measured again after compiled modules came to be shared per source (mac-2, under other sessions' load): loading 2000 firebirds went from ~220 ms to 5 ms, and resident memory per firebird from 22 KB to 12 KB. The same run, old build against new on that one node, put the busy loop at 2.4–2.55 ns per instruction before part A of the language extension and 2.9 ns after (calls and `fib` unchanged): about 18% slower dispatch, not yet looked into. ## Not built yet In the order they are likely to matter: - `spawn` from inside a script, and supervisors; the host starts processes. - A debugger (breakpoints, stepping): the VM's state is plain data, so it is within reach, but nothing is built. - Checking markup tags and attributes against what the host's components take. - A smaller browser build: shipping compiled modules instead of the compiler (how much of the 929 KB the compiler is has not been measured). 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, plus the size of what a built-in method copies, sorts or compares (one unit per 8 items or 64 string bytes, `stdlib::cost`), so a slice cannot copy a big list thousands of times for free. A host function's cost counts only when the host charges it (`cx.charge`). - A list or map changed through `push` or `set` is copied each time: building a list of n items one push at a time costs n²/2 copies. `map` and `filter` build in place. - The return type of a closure without `-> T` is taken from its last expression; a `return` inside it is not checked against that.