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
- 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.
- 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 (Cartopolisdocs/notes/prim-scripting.md), cannot occur. - 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. - Nothing is ambient. No global
fetch,processor file-readingrequire: a platform declares every function a script can call.
The language as built
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>,Map<K, V>(keys Int or Str),Option<T>,Result<T, E>, tuples(Int, Str), records ({ x: Float }, equal when their fields are), enums with payloads, functionsfn(Int) -> Bool / Prim,Vec3, andtypealiases. 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<T>(xs: List<T>) -> Option<T>, compiled once per set of types it is called with;enum Tree<T> { Leaf, Node(Tree<T>, T, Tree<T>) }andtype Pair<A, B> = { first: A, second: B }. A value that takes its type from where it goes (Leaf,None,[]) gets it from the other arguments first. - Methods: built in on lists (
push,get,map,filter,any,all,find,count,contains,index_of,sort,join,slice,reversed,remove_at,xs[i] = v,xs + ys), strings (split,trim,upper,replace,slice,parse_int, …), maps (get,set,has,remove,keys,values) andVec3(+ - * /,length,normalize,dot,cross,distance,lerp).x.f(a)calls a script's ownf(x, a). A method that changes its receiver (push,set,remove,remove_at) needs a variable. matchtakes 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) = …andlet { lat, lng } = …take a pattern that always matches.- Errors are values:
Result<T, E>, ande?passes anErrorNoneon to the caller.==compares anything without functions in it, by value. log(text),warn(text)andassert(cond, "why");test "name" { … }blocks run withfrits testorRuntime::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 = 1on avarbuilds 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, noasync, no implicit conversions (float(i),int(x)).
Libraries, messages and rights
import geometrymerges a library the host supplies (Platform::set_library): functions, types, enums and tests, noscriptline, handlers or globals. Its names are used asgeometry.area(b)andgeometry.Box; its variants keep their plain names (Left, orgeometry.Left). Each library is checked on its own first, so its mistakes are reported as "in librarygeometry, 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 typeAddr<T>; another sends to it withsend(addr, m), which needs theMaileffect. 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 fromme()and from the host (Runtime::addr_of); a script cannot make one from a number. Secret<T>: a value the host hands out (a key, a token) that a script can hold and pass to a host function taking aSecret, and nothing else: it cannot be written into a string, compared, logged, kept, or received in a message.Untrusted<Str>: text from someone else (chat, another person's prim, a message), as the platform declares it (event heard(text: Untrusted<Str>)). It can be shown: logged, put in a view, passed to a host function that takesUntrusted<Str>, and a string built from it ("{text}",+,.trim(),.split()) is untrusted too. It cannot go where a plainStris 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, andlen,containsand==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 Doorin 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 aDoorcannot 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):
script / Ui
enum Msg { Inc, Dec }
var n = 0
fn draw() -> View<Msg> {
<Column gap=8>
<Text size=1.5>"Count: {n}"</Text>
<Row>
<Button on_press=Dec>"-"</Button>
<Button on_press=Inc>"+"</Button>
</Row>
</Column>
}
on receive(m: Msg) {
match m {
Inc => n += 1,
Dec => n -= 1,
}
render(draw())
}
- Markup is an expression of type
View<M>(the prelude's enum:ViewEl(tag, attributes, children)orViewText), so a view is built with ordinary code:{rows}takes a list of views,.map(fn(i) { <Text>"{i}"</Text> })makes one. - An attribute is a Str, Int, Float, Bool, or a message
M;Mis what the script'son receivetakes. 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 theUieffect; the host takes the tree withProcess::take_viewand reads it withfrits::view::decode.- A message variant that carries one Str, named bare (
on_input=Typedforenum Msg { Typed(Str) }), becomesAttrInput(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_fritsis 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 <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 text, so comments and how numbers are written survive; brackets opened on one line indent what follows by one level.frits lsp [--platform <decl.frits>]is a language server for any editor: errors as you type (a whole line, since errors carry lines, not columns), completion afterPrim.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 <decl.frits>] [--title <t>]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 MCPscripting_guide), so it cannot drift from what scripts can call.frits test <file>runs a script'stestblocks;frits run <file>runs it on the console platform;frits aotis above.
The platform
A host describes what it offers in Frits, and binds Rust functions to it:
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, events
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 callsProcess::wake. That is howTimer.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)countsninstructions 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::tickgives 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::compilekeeps compiled modules by source (weakly), so a thousand prims running one script share one compiled module.map,filterand 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:
spawnfrom 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 calledonis 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
pushorsetis copied each time: building a list of n items one push at a time costs n²/2 copies.mapandfilterbuild in place. - The return type of a closure without
-> Tis taken from its last expression; areturninside it is not checked against that.