garage44.eu/jeroen/frits

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

cartopolis-agent · 2026-11-27T08:59:20Z

feat(frits): run without std, with math of its own

Pinnacle's apps have alloc and no std, and Frits is to run inside them. The
std feature (default) keeps the command line and the language server; the
language builds with alloc alone, its maps B-trees.

math is fmath.rs in every build, not the platform's: a no_std build has no
sin, and the platform's would let one script compute different last bits on
a server, in wasm and on a device, while a page rendered on a server can
only be taken over by a browser that draws the same tree. fdlibm's
algorithms, tested against std: sqrt exact, exp/ln/atan within 1 ulp,
sin/cos/atan2/hypot within 2; whole powers by squaring.
crates/frits/Cargo.toml      |   6 +
 crates/frits/src/aot.rs      |   6 +-
 crates/frits/src/ast.rs      |   2 +
 crates/frits/src/bytecode.rs |   4 +-
 crates/frits/src/compile.rs  |  60 +++---
 crates/frits/src/fmath.rs    | 496 +++++++++++++++++++++++++++++++++++++++++++
 crates/frits/src/fmt.rs      |   2 +
 crates/frits/src/guide.rs    |   8 +-
 crates/frits/src/imports.rs  |  30 +--
 crates/frits/src/json.rs     |  18 +-
 crates/frits/src/lexer.rs    |   4 +-
 crates/frits/src/lib.rs      |  26 ++-
 crates/frits/src/parser.rs   |   2 +
 crates/frits/src/platform.rs |  12 +-
 crates/frits/src/prelude.rs  |  33 +--
 crates/frits/src/runtime.rs  |   4 +-
 crates/frits/src/stdlib.rs   |  24 ++-
 crates/frits/src/tests.rs    |  11 +-
 crates/frits/src/types.rs    |  26 +--
 crates/frits/src/value.rs    |   4 +-
 crates/frits/src/view.rs     |   2 +
 crates/frits/src/vm.rs       |  16 +-
 docs/design.md               |  30 ++-
 23 files changed, 714 insertions(+), 112 deletions(-)

diff --git a/crates/frits/Cargo.toml b/crates/frits/Cargo.toml
index 79b1417..017ca1a 100644
--- a/crates/frits/Cargo.toml
+++ b/crates/frits/Cargo.toml
@@ -9,3 +9,9 @@ publish.workspace = true
 name = "frits"
 path = "src/main.rs"
 test = false
+required-features = ["std"]
+
+[features]
+default = ["std"]
+# The language server and the command line. The language needs only alloc.
+std = []
diff --git a/crates/frits/src/aot.rs b/crates/frits/src/aot.rs
index 9125484..8e5c9ea 100644
--- a/crates/frits/src/aot.rs
+++ b/crates/frits/src/aot.rs
@@ -14,8 +14,10 @@
 //! 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;
+#[allow(unused_imports)]
+use crate::base::*;
+use alloc::rc::Rc;
+use core::fmt::Write;
 
 use crate::bytecode::{Module, Op};
 use crate::platform::{Cx, Platform};
diff --git a/crates/frits/src/ast.rs b/crates/frits/src/ast.rs
index e83b256..5c3c404 100644
--- a/crates/frits/src/ast.rs
+++ b/crates/frits/src/ast.rs
@@ -1,5 +1,7 @@
 //! The parsed program, before types.
 
+#[allow(unused_imports)]
+use crate::base::*;
 pub type Name = String;
 
 #[derive(Debug, Default)]
diff --git a/crates/frits/src/bytecode.rs b/crates/frits/src/bytecode.rs
index aa91b19..7b57b72 100644
--- a/crates/frits/src/bytecode.rs
+++ b/crates/frits/src/bytecode.rs
@@ -5,7 +5,9 @@
 //! time beyond what the safe-Rust match in the VM costs. Registers are `u16`
 //! offsets from the frame's base.
 
-use std::rc::Rc;
+#[allow(unused_imports)]
+use crate::base::*;
+use alloc::rc::Rc;
 
 use crate::stdlib::Std;
 use crate::value::Value;
diff --git a/crates/frits/src/compile.rs b/crates/frits/src/compile.rs
index adeb452..e26fd80 100644
--- a/crates/frits/src/compile.rs
+++ b/crates/frits/src/compile.rs
@@ -6,8 +6,10 @@
 //! function's `/ …` list, and a call to a script function needs all of the
 //! callee's.
 
-use std::collections::HashMap;
-use std::rc::Rc;
+#[allow(unused_imports)]
+use crate::base::*;
+use alloc::collections::BTreeMap;
+use alloc::rc::Rc;
 
 use crate::Error;
 use crate::ast::*;
@@ -19,7 +21,7 @@ use crate::value::Value;
 pub fn compile(
     src: &str,
     plat: &PlatformDecl,
-    library: &HashMap<String, String>,
+    library: &BTreeMap<String, String>,
 ) -> Result<Module, Vec<Error>> {
     compile_in(src, plat, library, &mut Vec::new(), false)
 }
@@ -27,7 +29,7 @@ pub fn compile(
 fn compile_in(
     src: &str,
     plat: &PlatformDecl,
-    library: &HashMap<String, String>,
+    library: &BTreeMap<String, String>,
     stack: &mut Vec<String>,
     is_library: bool,
 ) -> Result<Module, Vec<Error>> {
@@ -129,22 +131,22 @@ struct Compiler<'p, 'a> {
     env: TypeEnv,
     enums: Vec<EnumInfo>,
     enum_names: Vec<String>,
-    variants: HashMap<String, (u32, u32)>,
+    variants: BTreeMap<String, (u32, u32)>,
     fns: Vec<FnSig>,
-    fn_index: HashMap<String, u32>,
+    fn_index: BTreeMap<String, u32>,
     globals: Vec<GlobalInfo>,
-    global_index: HashMap<String, u32>,
+    global_index: BTreeMap<String, u32>,
     module_effects: Vec<String>,
     out: Module,
     errors: Vec<Error>,
     f: FnState,
     line: u32,
-    const_index: HashMap<(u8, u64), u32>,
-    string_index: HashMap<String, u32>,
-    generic_fns: HashMap<String, &'a FnDecl>,
+    const_index: BTreeMap<(u8, u64), u32>,
+    string_index: BTreeMap<String, u32>,
+    generic_fns: BTreeMap<String, &'a FnDecl>,
     /// Generic functions compiled for one set of type arguments, by name and types.
-    instance_ids: HashMap<String, u32>,
-    pending: Vec<(&'a FnDecl, HashMap<String, Type>, u32)>,
+    instance_ids: BTreeMap<String, u32>,
+    pending: Vec<(&'a FnDecl, BTreeMap<String, Type>, u32)>,
     /// What `on receive` takes, when the script has one.
     inbox: Option<Type>,
 }
@@ -156,20 +158,20 @@ impl<'p, 'a> Compiler<'p, 'a> {
             env: plat.env.clone(),
             enums: Vec::new(),
             enum_names: Vec::new(),
-            variants: HashMap::new(),
+            variants: BTreeMap::new(),
             fns: Vec::new(),
-            fn_index: HashMap::new(),
+            fn_index: BTreeMap::new(),
             globals: Vec::new(),
-            global_index: HashMap::new(),
+            global_index: BTreeMap::new(),
             module_effects: Vec::new(),
             out: Module::default(),
             errors: Vec::new(),
             f: FnState::default(),
             line: 0,
-            const_index: HashMap::new(),
-            string_index: HashMap::new(),
-            generic_fns: HashMap::new(),
-            instance_ids: HashMap::new(),
+            const_index: BTreeMap::new(),
+            string_index: BTreeMap::new(),
+            generic_fns: BTreeMap::new(),
+            instance_ids: BTreeMap::new(),
             pending: Vec::new(),
             inbox: None,
         }
@@ -462,7 +464,7 @@ impl<'p, 'a> Compiler<'p, 'a> {
     /// with; an instance may call others, so until none is left.
     fn instances(&mut self) {
         while let Some((decl, bind, id)) = self.pending.pop() {
-            let saved = std::mem::replace(&mut self.env.generics, bind);
+            let saved = core::mem::replace(&mut self.env.generics, bind);
             self.function(decl, id, false);
             let args: Vec<String> = decl
                 .generics
@@ -529,7 +531,7 @@ impl<'p, 'a> Compiler<'p, 'a> {
     }
 
     fn finish(&mut self, id: u32, arity: u16) {
-        let f = std::mem::take(&mut self.f);
+        let f = core::mem::take(&mut self.f);
         self.out.funcs[id as usize] = Function {
             name: f.name,
             arity,
@@ -1436,11 +1438,11 @@ impl<'p, 'a> Compiler<'p, 'a> {
                     // A generic enum's arguments come from what is wanted, or
                     // from the values given.
                     let tparams = self.enums[e as usize].params.clone();
-                    let mut bind: HashMap<String, Type> = match want {
+                    let mut bind: BTreeMap<String, Type> = match want {
                         Some(Type::Enum(we, args)) if *we == e => {
                             tparams.iter().cloned().zip(args.iter().cloned()).collect()
                         }
-                        _ => HashMap::new(),
+                        _ => BTreeMap::new(),
                     };
                     if argv.len() != params.len() {
                         self.error(
@@ -2500,7 +2502,7 @@ impl<'p, 'a> Compiler<'p, 'a> {
             .filter(|a| a.guard.is_none())
             .map(|a| vec![a.pattern.clone()])
             .collect();
-        let exhaustive = total || st == Type::Error || self.covers(rows, std::slice::from_ref(&st));
+        let exhaustive = total || st == Type::Error || self.covers(rows, core::slice::from_ref(&st));
         if !exhaustive {
             let missing: Vec<String> = match names {
                 Some(n) => n
@@ -2590,7 +2592,7 @@ impl<'p, 'a> Compiler<'p, 'a> {
         let id = self.out.funcs.len() as u32;
         self.out.funcs.push(Self::placeholder());
         let outer_name = self.f.name.clone();
-        let outer = std::mem::take(&mut self.f);
+        let outer = core::mem::take(&mut self.f);
         self.begin(
             &format!("{outer_name}.<fn>"),
             ret.clone().unwrap_or(Type::Error),
@@ -2714,7 +2716,7 @@ impl<'p, 'a> Compiler<'p, 'a> {
         r: Reg,
         line: u32,
     ) -> Type {
-        let saved = std::mem::take(&mut self.env.generics);
+        let saved = core::mem::take(&mut self.env.generics);
         self.env.generics = decl
             .generics
             .iter()
@@ -2731,7 +2733,7 @@ impl<'p, 'a> Compiler<'p, 'a> {
             return Type::Error;
         }
         let base = self.alloc_n(n.max(1));
-        let mut bind = HashMap::new();
+        let mut bind = BTreeMap::new();
         let mut i = 0;
         if let Some((fr, ft)) = first {
             self.emit(Op::Move { dst: base, src: fr });
@@ -3231,7 +3233,7 @@ impl<'p, 'a> Compiler<'p, 'a> {
                         } else {
                             ListIndexOf
                         };
-                        self.std_call(f, rr, args, std::slice::from_ref(&e), r, name, line);
+                        self.std_call(f, rr, args, core::slice::from_ref(&e), r, name, line);
                         if name == "contains" {
                             Type::Bool
                         } else {
@@ -3353,7 +3355,7 @@ impl<'p, 'a> Compiler<'p, 'a> {
     /// A variant's payload types, for an enum with these type arguments.
     fn payload(&self, e: u32, tag: u32, args: &[Type]) -> Vec<Type> {
         let info = &self.enums[e as usize];
-        let bind: HashMap<String, Type> = info.params.iter().cloned().zip(args.iter().cloned()).collect();
+        let bind: BTreeMap<String, Type> = info.params.iter().cloned().zip(args.iter().cloned()).collect();
         info.variants[tag as usize]
             .1
             .iter()
diff --git a/crates/frits/src/fmath.rs b/crates/frits/src/fmath.rs
new file mode 100644
index 0000000..93e5e6b
--- /dev/null
+++ b/crates/frits/src/fmath.rs
@@ -0,0 +1,496 @@
+//! Floating-point functions written here rather than taken from the
+//! platform: a build without `std` (a Pinnacle app) has none, and taking the
+//! platform's would let the same script compute different last bits on a
+//! server, in a browser and on a device — and a view drawn from a number
+//! must come out the same on all three, or a page cannot be taken over.
+//! Only `+ - * /` are left to the hardware, which IEEE 754 makes exact.
+//!
+//! The algorithms are the classic ones (argument reduction, then a short
+//! polynomial; the coefficients are fdlibm's); the tests hold each function
+//! to std's within a few units in the last place.
+
+// The coefficients are written as fdlibm publishes them.
+#![allow(clippy::excessive_precision)]
+
+const SIGN: u64 = 1 << 63;
+
+pub fn abs(x: f64) -> f64 {
+    f64::from_bits(x.to_bits() & !SIGN)
+}
+
+fn copysign(x: f64, s: f64) -> f64 {
+    f64::from_bits((x.to_bits() & !SIGN) | (s.to_bits() & SIGN))
+}
+
+/// Toward zero. Every f64 of magnitude 2^52 or more is already whole.
+pub fn trunc(x: f64) -> f64 {
+    if !x.is_finite() || abs(x) >= 4_503_599_627_370_496.0 {
+        x
+    } else {
+        copysign((x as i64) as f64, x)
+    }
+}
+
+pub fn floor(x: f64) -> f64 {
+    let t = trunc(x);
+    if t > x { t - 1.0 } else { t }
+}
+
+pub fn ceil(x: f64) -> f64 {
+    let t = trunc(x);
+    if t < x { t + 1.0 } else { t }
+}
+
+/// Half away from zero, as std's.
+pub fn round(x: f64) -> f64 {
+    let t = trunc(x);
+    if abs(x - t) >= 0.5 {
+        t + copysign(1.0, x)
+    } else {
+        t
+    }
+}
+
+pub fn fract(x: f64) -> f64 {
+    x - trunc(x)
+}
+
+/// x · 2^n, exactly while the result is a normal number.
+fn scale(x: f64, n: i32) -> f64 {
+    let mut x = x;
+    let mut n = n;
+    while n > 1023 {
+        x *= f64::from_bits(0x7FE0_0000_0000_0000); // 2^1023
+        n -= 1023;
+    }
+    while n < -1022 {
+        x *= f64::from_bits(0x0010_0000_0000_0000); // 2^-1022
+        n += 1022;
+    }
+    x * f64::from_bits(((n + 1023) as u64) << 52)
+}
+
+/// x − y², exactly enough to compare neighbours: y² split into a rounded
+/// product and its error (Dekker), with no fused multiply-add needed.
+fn residual(x: f64, y: f64) -> f64 {
+    let c = 134_217_729.0 * y; // 2^27 + 1
+    let hi = c - (c - y);
+    let lo = y - hi;
+    let p = y * y;
+    let e = ((hi * hi - p) + 2.0 * hi * lo) + lo * lo;
+    (x - p) - e
+}
+
+/// Newton's iteration from a seed with half the exponent, then the
+/// neighbour whose square is nearest x, by the exact residual: the hardware's
+/// correctly rounded root.
+pub fn sqrt(x: f64) -> f64 {
+    if x.is_nan() || x < 0.0 {
+        return f64::NAN;
+    }
+    if x == 0.0 || x == f64::INFINITY {
+        return x;
+    }
+    let bits = x.to_bits();
+    let mut y = f64::from_bits((bits >> 1) + (0x3FF0_0000_0000_0000 >> 1));
+    for _ in 0..6 {
+        y = 0.5 * (y + x / y);
+    }
+    // Of y and its two neighbours, the one whose square is nearest x.
+    let below = f64::from_bits(y.to_bits() - 1);
+    let above = f64::from_bits(y.to_bits() + 1);
+    let err = |c: f64| abs(residual(x, c));
+    let mut best = y;
+    if err(below) < err(best) {
+        best = below;
+    }
+    if err(above) < err(best) {
+        best = above;
+    }
+    best
+}
+
+pub fn hypot(x: f64, y: f64) -> f64 {
+    let (a, b) = (abs(x), abs(y));
+    if a.is_infinite() || b.is_infinite() {
+        return f64::INFINITY;
+    }
+    let (big, small) = if a > b { (a, b) } else { (b, a) };
+    if big == 0.0 {
+        return 0.0;
+    }
+    let r = small / big;
+    big * sqrt(1.0 + r * r)
+}
+
+const LN2_HI: f64 = 6.931_471_803_691_238_164_90e-01;
+const LN2_LO: f64 = 1.908_214_929_270_587_700_02e-10;
+const INV_LN2: f64 = core::f64::consts::LOG2_E;
+
+pub fn exp(x: f64) -> f64 {
+    if x.is_nan() {
+        return x;
+    }
+    if x > 709.782_712_893_383_973_096 {
+        return f64::INFINITY;
+    }
+    if x < -745.133_219_101_941_108_420 {
+        return 0.0;
+    }
+    // x = k·ln2 + r, |r| ≤ ln2/2.
+    let k = round(x * INV_LN2);
+    let hi = x - k * LN2_HI;
+    let lo = k * LN2_LO;
+    let r = hi - lo;
+    const P1: f64 = 1.666_666_666_666_660_190_37e-01;
+    const P2: f64 = -2.777_777_777_701_559_338_42e-03;
+    const P3: f64 = 6.613_756_321_437_934_361_17e-05;
+    const P4: f64 = -1.653_390_220_546_525_153_90e-06;
+    const P5: f64 = 4.138_136_797_057_238_460_39e-08;
+    let t = r * r;
+    let c = r - t * (P1 + t * (P2 + t * (P3 + t * (P4 + t * P5))));
+    let y = 1.0 - ((lo - (r * c) / (2.0 - c)) - hi);
+    scale(y, k as i32)
+}
+
+pub fn ln(x: f64) -> f64 {
+    if x.is_nan() || x < 0.0 {
+        return f64::NAN;
+    }
+    if x == 0.0 {
+        return f64::NEG_INFINITY;
+    }
+    if x == f64::INFINITY {
+        return x;
+    }
+    // x = 2^k · m, m in [√2/2, √2).
+    let mut x = x;
+    let mut k = 0i32;
+    if x < f64::MIN_POSITIVE {
+        x *= 18_014_398_509_481_984.0; // 2^54
+        k -= 54;
+    }
+    let bits = x.to_bits();
+    k += ((bits >> 52) & 0x7FF) as i32 - 1023;
+    let mut m = f64::from_bits((bits & 0x000F_FFFF_FFFF_FFFF) | 0x3FF0_0000_0000_0000);
+    if m > core::f64::consts::SQRT_2 {
+        m *= 0.5;
+        k += 1;
+    }
+    let f = m - 1.0;
+    let s = f / (2.0 + f);
+    let z = s * s;
+    let w = z * z;
+    const LG1: f64 = 6.666_666_666_666_735_130e-01;
+    const LG2: f64 = 3.999_999_999_940_941_908e-01;
+    const LG3: f64 = 2.857_142_874_366_239_149e-01;
+    const LG4: f64 = 2.222_219_843_214_978_396e-01;
+    const LG5: f64 = 1.818_357_216_161_805_012e-01;
+    const LG6: f64 = 1.531_383_769_920_937_332e-01;
+    const LG7: f64 = 1.479_819_860_511_658_591e-01;
+    let t1 = w * (LG2 + w * (LG4 + w * LG6));
+    let t2 = z * (LG1 + w * (LG3 + w * (LG5 + w * LG7)));
+    let r = t2 + t1;
+    let hfsq = 0.5 * f * f;
+    let k = k as f64;
+    k * LN2_HI - ((hfsq - (s * (hfsq + r) + k * LN2_LO)) - f)
+}
+
+pub fn log10(x: f64) -> f64 {
+    ln(x) * core::f64::consts::LOG10_E
+}
+
+/// Whole powers by squaring, so `pow(2, 10)` is 1024 exactly; the rest
+/// through `exp(y·ln x)`.
+pub fn pow(x: f64, y: f64) -> f64 {
+    if y == 0.0 {
+        return 1.0;
+    }
+    if x.is_nan() || y.is_nan() {
+        return f64::NAN;
+    }
+    if trunc(y) == y && abs(y) < 2_147_483_648.0 {
+        let mut n = abs(y) as u64;
+        let mut base = x;
+        let mut acc = 1.0;
+        while n > 0 {
+            if n & 1 == 1 {
+                acc *= base;
+            }
+            base *= base;
+            n >>= 1;
+        }
+        return if y < 0.0 { 1.0 / acc } else { acc };
+    }
+    if x < 0.0 {
+        return f64::NAN;
+    }
+    if x == 0.0 {
+        return if y > 0.0 { 0.0 } else { f64::INFINITY };
+    }
+    exp(y * ln(x))
+}
+
+// ─── Circles ────────────────────────────────────────────────────────────────
+
+/// x = n·π/2 + r, |r| ≤ π/4, π/2 in three parts (Cody and Waite): exact
+/// enough while |n| < 2^20, about a million radians. Beyond that the angle
+/// is first taken modulo 2π as a double, which is the same on every machine
+/// but not std's answer: a script turning by a million radians has lost its
+/// angle long before (std reduces with 1200 bits of 2/π, which is not
+/// carried here).
+fn reduce(x: f64) -> (i64, f64) {
+    const PIO2_1: f64 = 1.570_796_326_734_125_614_17e+00;
+    const PIO2_2: f64 = 6.077_100_506_303_965_976_60e-11;
+    const PIO2_3: f64 = 2.022_266_248_711_166_455_80e-21;
+    let x = if abs(x) < 1.0e6 {
+        x
+    } else {
+        x % core::f64::consts::TAU
+    };
+    let n = round(x * core::f64::consts::FRAC_2_PI);
+    let r = ((x - n * PIO2_1) - n * PIO2_2) - n * PIO2_3;
+    (n as i64, r)
+}
+
+fn ksin(x: f64) -> f64 {
+    const S1: f64 = -1.666_666_666_666_663_243_48e-01;
+    const S2: f64 = 8.333_333_333_322_489_461_24e-03;
+    const S3: f64 = -1.984_126_982_985_794_931_34e-04;
+    const S4: f64 = 2.755_731_370_707_006_767_89e-06;
+    const S5: f64 = -2.505_076_025_340_686_341_95e-08;
+    const S6: f64 = 1.589_690_995_211_550_102_21e-10;
+    let z = x * x;
+    x + x * z * (S1 + z * (S2 + z * (S3 + z * (S4 + z * (S5 + z * S6)))))
+}
+
+fn kcos(x: f64) -> f64 {
+    const C1: f64 = 4.166_666_666_666_660_190_37e-02;
+    const C2: f64 = -1.388_888_888_887_410_957_49e-03;
+    const C3: f64 = 2.480_158_728_947_672_941_78e-05;
+    const C4: f64 = -2.755_731_435_139_066_330_35e-07;
+    const C5: f64 = 2.087_572_321_298_174_827_90e-09;
+    const C6: f64 = -1.135_964_755_778_819_482_65e-11;
+    let z = x * x;
+    let r = z * (C1 + z * (C2 + z * (C3 + z * (C4 + z * (C5 + z * C6)))));
+    let hz = 0.5 * z;
+    let w = 1.0 - hz;
+    w + (((1.0 - w) - hz) + z * r)
+}
+
+pub fn sin(x: f64) -> f64 {
+    if !x.is_finite() {
+        return f64::NAN;
+    }
+    let (n, r) = reduce(x);
+    match n.rem_euclid(4) {
+        0 => ksin(r),
+        1 => kcos(r),
+        2 => -ksin(r),
+        _ => -kcos(r),
+    }
+}
+
+pub fn cos(x: f64) -> f64 {
+    if !x.is_finite() {
+        return f64::NAN;
+    }
+    let (n, r) = reduce(x);
+    match n.rem_euclid(4) {
+        0 => kcos(r),
+        1 => -ksin(r),
+        2 => -kcos(r),
+        _ => ksin(r),
+    }
+}
+
+pub fn tan(x: f64) -> f64 {
+    sin(x) / cos(x)
+}
+
+pub fn atan(x: f64) -> f64 {
+    const HI: [f64; 4] = [
+        4.636_476_090_008_060_935_15e-01,
+        core::f64::consts::FRAC_PI_4,
+        9.827_937_232_473_290_540_82e-01,
+        core::f64::consts::FRAC_PI_2,
+    ];
+    const LO: [f64; 4] = [
+        2.269_877_745_296_168_709_24e-17,
+        3.061_616_997_868_383_017_93e-17,
+        1.390_331_103_123_099_845_16e-17,
+        6.123_233_995_736_766_035_87e-17,
+    ];
+    const AT: [f64; 11] = [
+        3.333_333_333_333_293_180_27e-01,
+        -1.999_999_999_987_648_324_76e-01,
+        1.428_571_427_250_346_637_11e-01,
+        -1.111_111_040_546_235_578_80e-01,
+        9.090_887_133_436_506_561_96e-02,
+        -7.691_876_205_044_829_994_95e-02,
+        6.661_073_137_387_531_206_69e-02,
+        -5.833_570_133_790_573_486_45e-02,
+        4.976_877_994_615_932_360_17e-02,
+        -3.653_157_274_421_691_552_70e-02,
+        1.628_582_011_536_578_236_23e-02,
+    ];
+    if x.is_nan() {
+        return x;
+    }
+    let a = abs(x);
+    if a >= 7.378_697_629_483_820_646_4e19 {
+        // 2^66: atan is π/2 to the last bit.
+        return copysign(HI[3] + LO[3], x);
+    }
+    let (id, t) = if a < 0.4375 {
+        (None, a)
+    } else if a < 0.6875 {
+        (Some(0), (2.0 * a - 1.0) / (2.0 + a))
+    } else if a < 1.1875 {
+        (Some(1), (a - 1.0) / (a + 1.0))
+    } else if a < 2.4375 {
+        (Some(2), (a - 1.5) / (1.0 + 1.5 * a))
+    } else {
+        (Some(3), -1.0 / a)
+    };
+    let z = t * t;
+    let w = z * z;
+    let s1 = z * (AT[0] + w * (AT[2] + w * (AT[4] + w * (AT[6] + w * (AT[8] + w * AT[10])))));
+    let s2 = w * (AT[1] + w * (AT[3] + w * (AT[5] + w * (AT[7] + w * AT[9]))));
+    let r = match id {
+        None => t - t * (s1 + s2),
+        Some(i) => HI[i] - ((t * (s1 + s2) - LO[i]) - t),
+    };
+    copysign(r, x)
+}
+
+pub fn atan2(y: f64, x: f64) -> f64 {
+    use core::f64::consts::{FRAC_PI_2, PI};
+    if x.is_nan() || y.is_nan() {
+        return f64::NAN;
+    }
+    if y == 0.0 {
+        // Signed zeros choose the side, as std's.
+        let neg_x = x < 0.0 || (x == 0.0 && x.is_sign_negative());
+        return if neg_x { copysign(PI, y) } else { y };
+    }
+    if x == 0.0 {
+        return copysign(FRAC_PI_2, y);
+    }
+    if x.is_infinite() || y.is_infinite() {
+        let base = match (x.is_infinite(), y.is_infinite()) {
+            (true, true) => {
+                if x > 0.0 {
+                    PI / 4.0
+                } else {
+                    3.0 * PI / 4.0
+                }
+            }
+            (true, false) => {
+                if x > 0.0 {
+                    0.0
+                } else {
+                    PI
+                }
+            }
+            _ => FRAC_PI_2,
+        };
+        return copysign(base, y);
+    }
+    let a = atan(abs(y / x));
+    let r = if x > 0.0 { a } else { PI - a };
+    copysign(r, y)
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    /// Units in the last place between a and b.
+    fn ulps(a: f64, b: f64) -> u64 {
+        if a == b || (a.is_nan() && b.is_nan()) {
+            return 0;
+        }
+        let (a, b) = (a.to_bits() as i64, b.to_bits() as i64);
+        a.abs_diff(b)
+    }
+
+    fn inputs() -> Vec<f64> {
+        let mut v = vec![
+            0.0, -0.0, 0.5, 1.0, -1.0, 2.0, 3.0, 10.0, 100.0, 1e-300, 1e300, 0.1, 0.7, 1e-8,
+        ];
+        let mut s = 0x9E37_79B9_7F4A_7C15u64;
+        for _ in 0..4000 {
+            s ^= s << 13;
+            s ^= s >> 7;
+            s ^= s << 17;
+            let u = (s >> 11) as f64 / (1u64 << 53) as f64;
+            v.push((u - 0.5) * 2000.0);
+            v.push((u - 0.5) * 8.0);
+            v.push(u * 1e-3);
+        }
+        v
+    }
+
+    fn check(name: &str, ours: fn(f64) -> f64, theirs: fn(f64) -> f64, tol: u64, only: fn(f64) -> bool) {
+        let mut worst = (0, 0.0);
+        for x in inputs().into_iter().filter(|x| only(*x)) {
+            let d = ulps(ours(x), theirs(x));
+            if d > worst.0 {
+                worst = (d, x);
+            }
+        }
+        assert!(
+            worst.0 <= tol,
+            "{name}: {} ulps at {}: {} vs {}",
+            worst.0,
+            worst.1,
+            ours(worst.1),
+            theirs(worst.1)
+        );
+    }
+
+    #[test]
+    fn whole_numbers_are_exact() {
+        for x in inputs() {
+            assert_eq!(trunc(x), x.trunc(), "trunc {x}");
+            assert_eq!(floor(x), x.floor(), "floor {x}");
+            assert_eq!(ceil(x), x.ceil(), "ceil {x}");
+            assert_eq!(round(x), x.round(), "round {x}");
+            assert_eq!(abs(x), x.abs());
+        }
+        assert_eq!(round(2.5), 3.0);
+        assert_eq!(round(-2.5), -3.0);
+        assert_eq!(pow(2.0, 10.0), 1024.0);
+        assert_eq!(pow(3.0, -2.0), 1.0 / 9.0);
+        assert_eq!(sqrt(16.0), 4.0);
+        assert_eq!(sqrt(2.0), 2f64.sqrt());
+    }
+
+    #[test]
+    fn within_a_few_ulps_of_std() {
+        check("sqrt", sqrt, f64::sqrt, 0, |x| x >= 0.0);
+        check("exp", exp, f64::exp, 1, |x| x.abs() < 700.0);
+        check("ln", ln, f64::ln, 1, |x| x > 0.0);
+        check("sin", sin, f64::sin, 2, |x| x.abs() < 1e6);
+        check("cos", cos, f64::cos, 2, |x| x.abs() < 1e6);
+        assert!(sin(1e300).abs() <= 1.0 && cos(-1e300).abs() <= 1.0);
+        check("tan", tan, f64::tan, 4, |x| x.abs() < 1.5);
+        check("atan", atan, f64::atan, 1, |_| true);
+        let mut worst = 0;
+        for (i, y) in inputs().into_iter().enumerate().take(3000) {
+            let x = inputs()[(i * 7 + 3) % 3000];
+            worst = worst.max(ulps(atan2(y, x), y.atan2(x)));
+            worst = worst.max(ulps(hypot(y, x), y.hypot(x)));
+            if x > 0.0 && y.abs() < 50.0 {
+                let p = pow(x, y);
+                let q = x.powf(y);
+                assert!(
+                    ulps(p, q) <= 64 || (p - q).abs() <= q.abs() * 1e-13,
+                    "pow {x} {y}: {p} {q}"
+                );
+            }
+        }
+        assert!(worst <= 2, "atan2/hypot: {worst} ulps");
+    }
+}
diff --git a/crates/frits/src/fmt.rs b/crates/frits/src/fmt.rs
index c1d62e3..f372536 100644
--- a/crates/frits/src/fmt.rs
+++ b/crates/frits/src/fmt.rs
@@ -8,6 +8,8 @@
 //! at the end. A file it cannot read (a string never closed) comes back as it
 //! was.
 
+#[allow(unused_imports)]
+use crate::base::*;
 #[derive(Clone, Copy, Debug, PartialEq)]
 enum Kind {
     Word,
diff --git a/crates/frits/src/guide.rs b/crates/frits/src/guide.rs
index b1150ec..db51671 100644
--- a/crates/frits/src/guide.rs
+++ b/crates/frits/src/guide.rs
@@ -4,14 +4,16 @@
 //! A host serves it to people and to agents (Cartopolis's `scripting_guide`), so
 //! the guide cannot drift from what scripts can actually call.
 
-use std::collections::HashMap;
+#[allow(unused_imports)]
+use crate::base::*;
+use alloc::collections::BTreeMap;
 
 use crate::types::{HostFnSig, PlatformDecl, Show};
 
 /// The comment lines written directly above each declaration, by
 /// `Namespace.name` (or `event name`, or `type Name`).
-pub fn doc_comments_of(src: &str) -> HashMap<String, String> {
-    let mut docs = HashMap::new();
+pub fn doc_comments_of(src: &str) -> BTreeMap<String, String> {
+    let mut docs = BTreeMap::new();
     let mut pending: Vec<String> = Vec::new();
     let mut namespace: Option<String> = None;
     for line in src.lines() {
diff --git a/crates/frits/src/imports.rs b/crates/frits/src/imports.rs
index 7bc52b4..c378858 100644
--- a/crates/frits/src/imports.rs
+++ b/crates/frits/src/imports.rs
@@ -8,7 +8,9 @@
 //! Enum variants keep their plain names, so two libraries cannot both have a
 //! variant called `Open`.
 
-use std::collections::{HashMap, HashSet};
+#[allow(unused_imports)]
+use crate::base::*;
+use alloc::collections::{BTreeMap, BTreeSet};
 
 use crate::Error;
 use crate::ast::*;
@@ -19,13 +21,13 @@ pub type CheckLibrary<'a> = dyn FnMut(&str, &str) -> Result<(), Vec<Error>> + 'a
 /// Merge every library `m` imports, directly or through another library.
 pub fn resolve(
     m: &mut Module,
-    library: &HashMap<String, String>,
+    library: &BTreeMap<String, String>,
     check: &mut CheckLibrary,
 ) -> Result<(), Vec<Error>> {
     let mut errors = Vec::new();
     let mut loaded: Vec<(String, Module)> = Vec::new();
     let mut queue: Vec<(String, u32)> = imports_of(m);
-    let mut seen: HashSet<String> = HashSet::new();
+    let mut seen: BTreeSet<String> = BTreeSet::new();
     while let Some((name, line)) = queue.pop() {
         if !seen.insert(name.clone()) {
             continue;
@@ -64,8 +66,8 @@ pub fn resolve(
     if !errors.is_empty() {
         return Err(errors);
     }
-    let aliases: HashSet<String> = loaded.iter().map(|(n, _)| n.clone()).collect();
-    let none = HashSet::new();
+    let aliases: BTreeSet<String> = loaded.iter().map(|(n, _)| n.clone()).collect();
+    let none = BTreeSet::new();
     Renamer::new(None, &none, &none, &aliases).module(m);
     let mut merged = Vec::new();
     for (name, mut lib) in loaded {
@@ -120,9 +122,9 @@ pub fn check_library(m: &Module) -> Vec<Error> {
     errors
 }
 
-fn own_names(m: &Module) -> (HashSet<String>, HashSet<String>) {
-    let mut fns = HashSet::new();
-    let mut types = HashSet::new();
+fn own_names(m: &Module) -> (BTreeSet<String>, BTreeSet<String>) {
+    let mut fns = BTreeSet::new();
+    let mut types = BTreeSet::new();
     for item in &m.items {
         match item {
             Item::Fn(f) => {
@@ -146,9 +148,9 @@ fn own_names(m: &Module) -> (HashSet<String>, HashSet<String>) {
 /// function is left alone.
 struct Renamer<'a> {
     prefix: Option<&'a str>,
-    fns: &'a HashSet<String>,
-    types: &'a HashSet<String>,
-    aliases: &'a HashSet<String>,
+    fns: &'a BTreeSet<String>,
+    types: &'a BTreeSet<String>,
+    aliases: &'a BTreeSet<String>,
     scopes: Vec<Vec<String>>,
     generics: Vec<String>,
 }
@@ -156,9 +158,9 @@ struct Renamer<'a> {
 impl<'a> Renamer<'a> {
     fn new(
         prefix: Option<&'a str>,
-        fns: &'a HashSet<String>,
-        types: &'a HashSet<String>,
-        aliases: &'a HashSet<String>,
+        fns: &'a BTreeSet<String>,
+        types: &'a BTreeSet<String>,
+        aliases: &'a BTreeSet<String>,
     ) -> Self {
         Renamer {
             prefix,
diff --git a/crates/frits/src/json.rs b/crates/frits/src/json.rs
index 1ae804e..cec84b5 100644
--- a/crates/frits/src/json.rs
+++ b/crates/frits/src/json.rs
@@ -1,6 +1,8 @@
 //! Just enough JSON for the language server: read a message, write one.
 
-use std::fmt::Write;
+#[allow(unused_imports)]
+use crate::base::*;
+use core::fmt::Write;
 
 #[derive(Clone, Debug, PartialEq)]
 pub enum Json {
@@ -45,12 +47,14 @@ impl Json {
     }
 }
 
-impl std::fmt::Display for Json {
-    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+impl core::fmt::Display for Json {
+    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
         match self {
             Json::Null => f.write_str("null"),
             Json::Bool(b) => write!(f, "{b}"),
-            Json::Num(n) if n.fract() == 0.0 && n.abs() < 1e15 => write!(f, "{}", *n as i64),
+            Json::Num(n) if crate::fmath::fract(*n) == 0.0 && crate::fmath::abs(*n) < 1e15 => {
+                write!(f, "{}", *n as i64)
+            }
             Json::Num(n) => write!(f, "{n}"),
             Json::Str(s) => {
                 f.write_char('"')?;
@@ -183,7 +187,7 @@ impl P<'_> {
                 {
                     self.i += 1;
                 }
-                std::str::from_utf8(&self.b[s..self.i])
+                core::str::from_utf8(&self.b[s..self.i])
                     .ok()?
                     .parse()
                     .ok()
@@ -213,14 +217,14 @@ impl P<'_> {
                         b'b' => out.push(8),
                         b'f' => out.push(12),
                         b'u' => {
-                            let hex = std::str::from_utf8(self.b.get(self.i..self.i + 4)?).ok()?;
+                            let hex = core::str::from_utf8(self.b.get(self.i..self.i + 4)?).ok()?;
                             self.i += 4;
                             let mut code = u32::from_str_radix(hex, 16).ok()?;
                             // A surrogate pair.
                             if (0xD800..0xDC00).contains(&code)
                                 && self.b.get(self.i..self.i + 2) == Some(b"\\u")
                             {
-                                let lo = std::str::from_utf8(self.b.get(self.i + 2..self.i + 6)?).ok()?;
+                                let lo = core::str::from_utf8(self.b.get(self.i + 2..self.i + 6)?).ok()?;
                                 let lo = u32::from_str_radix(lo, 16).ok()?;
                                 self.i += 6;
                                 code = 0x10000 + ((code - 0xD800) << 10) + (lo - 0xDC00);
diff --git a/crates/frits/src/lexer.rs b/crates/frits/src/lexer.rs
index fd47a3f..1364bef 100644
--- a/crates/frits/src/lexer.rs
+++ b/crates/frits/src/lexer.rs
@@ -6,6 +6,8 @@
 //! `} else {` stays on one line.
 
 use crate::Error;
+#[allow(unused_imports)]
+use crate::base::*;
 
 #[derive(Clone, Debug, PartialEq)]
 pub enum Tok {
@@ -217,7 +219,7 @@ pub fn lex(src: &str, first_line: u32) -> Result<Vec<Token>, Error> {
                     }
                     b'{' => {
                         if !lit.is_empty() {
-                            parts.push(StrPart::Lit(std::mem::take(&mut lit)));
+                            parts.push(StrPart::Lit(core::mem::take(&mut lit)));
                         }
                         let hole_line = line;
                         i += 1;
diff --git a/crates/frits/src/lib.rs b/crates/frits/src/lib.rs
index 1f626db..d4cecf6 100644
--- a/crates/frits/src/lib.rs
+++ b/crates/frits/src/lib.rs
@@ -4,17 +4,39 @@
 //! [`Runtime`] runs it as many small processes, each with its own heap and a
 //! fuel slice per tick. The VM is safe Rust: a bug in it is a wrong answer or
 //! a stopped script, never a memory error.
+//!
+//! Without the `std` feature (on by default) it needs only `alloc`, as a
+//! Pinnacle app has it: the language server and the command line need std,
+//! the language does not.
 #![forbid(unsafe_code)]
+#![cfg_attr(not(feature = "std"), no_std)]
+
+extern crate alloc;
+
+/// What std's prelude gives every module and a crate without std must name.
+mod base {
+    pub use alloc::borrow::ToOwned;
+    pub use alloc::boxed::Box;
+    pub use alloc::format;
+    pub use alloc::string::{String, ToString};
+    pub use alloc::vec;
+    pub use alloc::vec::Vec;
+}
+
+#[allow(unused_imports)]
+use base::*;
 
 pub mod aot;
 pub mod ast;
 pub mod bytecode;
 pub mod compile;
+pub mod fmath;
 pub mod fmt;
 pub mod guide;
 pub mod imports;
 pub mod json;
 pub mod lexer;
+#[cfg(feature = "std")]
 pub mod lsp;
 pub mod parser;
 pub mod platform;
@@ -50,8 +72,8 @@ impl Error {
     }
 }
 
-impl std::fmt::Display for Error {
-    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+impl core::fmt::Display for Error {
+    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
         if self.line == 0 {
             write!(f, "{}", self.msg)
         } else {
diff --git a/crates/frits/src/parser.rs b/crates/frits/src/parser.rs
index aae7109..838b220 100644
--- a/crates/frits/src/parser.rs
+++ b/crates/frits/src/parser.rs
@@ -2,6 +2,8 @@
 
 use crate::Error;
 use crate::ast::*;
+#[allow(unused_imports)]
+use crate::base::*;
 use crate::lexer::{Kw, StrPart, Tok, Token, lex};
 
 pub fn parse(src: &str) -> Result<Module, Error> {
diff --git a/crates/frits/src/platform.rs b/crates/frits/src/platform.rs
index 4a1ad3b..b071115 100644
--- a/crates/frits/src/platform.rs
+++ b/crates/frits/src/platform.rs
@@ -5,9 +5,11 @@
 //! by being compiled against a different platform. What a script may touch is
 //! exactly what its platform declared and its `script / …` line asked for.
 
-use std::cell::RefCell;
-use std::collections::HashMap;
-use std::rc::{Rc, Weak};
+#[allow(unused_imports)]
+use crate::base::*;
+use alloc::collections::BTreeMap;
+use alloc::rc::{Rc, Weak};
+use core::cell::RefCell;
 
 use crate::Error;
 use crate::bytecode::Module;
@@ -92,9 +94,9 @@ pub struct Platform<S> {
     pub(crate) consts: Vec<Option<HostValue>>,
     /// Compiled modules by source, so a thousand prims with one script share
     /// one module. Weak: a module nobody runs is dropped.
-    cache: RefCell<HashMap<String, Weak<Module>>>,
+    cache: RefCell<BTreeMap<String, Weak<Module>>>,
     /// Libraries a script can `import`, by name.
-    library: RefCell<HashMap<String, String>>,
+    library: RefCell<BTreeMap<String, String>>,
 }
 
 impl<S> Platform<S> {
diff --git a/crates/frits/src/prelude.rs b/crates/frits/src/prelude.rs
index cc66a6c..38d0d15 100644
--- a/crates/frits/src/prelude.rs
+++ b/crates/frits/src/prelude.rs
@@ -1,6 +1,9 @@
 //! What every platform has: `Vec3`, the pure `math` module, and `Random`, an
 //! effect because a script that rolls dice is not a pure function.
 
+#[allow(unused_imports)]
+use crate::base::*;
+use crate::fmath;
 use crate::platform::{Cx, Platform};
 use crate::value::{HostValue, Value};
 
@@ -63,17 +66,17 @@ fn f1(a: &[Value], f: fn(f64) -> f64) -> Result<Value, String> {
 }
 
 pub fn bind<S>(p: &mut Platform<S>) {
-    p.bind("math.sin", |_: &mut Cx<S>, a| f1(a, f64::sin))
-        .bind("math.cos", |_, a| f1(a, f64::cos))
-        .bind("math.tan", |_, a| f1(a, f64::tan))
+    p.bind("math.sin", |_: &mut Cx<S>, a| f1(a, fmath::sin))
+        .bind("math.cos", |_, a| f1(a, fmath::cos))
+        .bind("math.tan", |_, a| f1(a, fmath::tan))
         .bind("math.atan2", |_, a| {
-            Ok(Value::Float(a[0].float().atan2(a[1].float())))
+            Ok(Value::Float(fmath::atan2(a[0].float(), a[1].float())))
         })
-        .bind("math.sqrt", |_, a| f1(a, f64::sqrt))
-        .bind("math.abs", |_, a| f1(a, f64::abs))
-        .bind("math.floor", |_, a| f1(a, f64::floor))
-        .bind("math.ceil", |_, a| f1(a, f64::ceil))
-        .bind("math.round", |_, a| f1(a, f64::round))
+        .bind("math.sqrt", |_, a| f1(a, fmath::sqrt))
+        .bind("math.abs", |_, a| f1(a, fmath::abs))
+        .bind("math.floor", |_, a| f1(a, fmath::floor))
+        .bind("math.ceil", |_, a| f1(a, fmath::ceil))
+        .bind("math.round", |_, a| f1(a, fmath::round))
         .bind("math.min", |_, a| {
             Ok(Value::Float(a[0].float().min(a[1].float())))
         })
@@ -81,13 +84,13 @@ pub fn bind<S>(p: &mut Platform<S>) {
             Ok(Value::Float(a[0].float().max(a[1].float())))
         })
         .bind("math.pow", |_, a| {
-            Ok(Value::Float(a[0].float().powf(a[1].float())))
+            Ok(Value::Float(fmath::pow(a[0].float(), a[1].float())))
         })
-        .bind("math.exp", |_, a| f1(a, f64::exp))
-        .bind("math.ln", |_, a| f1(a, f64::ln))
-        .bind("math.log10", |_, a| f1(a, f64::log10))
+        .bind("math.exp", |_, a| f1(a, fmath::exp))
+        .bind("math.ln", |_, a| f1(a, fmath::ln))
+        .bind("math.log10", |_, a| f1(a, fmath::log10))
         .bind("math.hypot", |_, a| {
-            Ok(Value::Float(a[0].float().hypot(a[1].float())))
+            Ok(Value::Float(fmath::hypot(a[0].float(), a[1].float())))
         })
         .bind("math.clamp", |_, a| {
             let (x, lo, hi) = (a[0].float(), a[1].float(), a[2].float());
@@ -114,5 +117,5 @@ pub fn bind<S>(p: &mut Platform<S>) {
                 (lo as i128 + (cx.random() as u128 % span) as i128) as i64,
             ))
         })
-        .constant("math.pi", HostValue::Float(std::f64::consts::PI));
+        .constant("math.pi", HostValue::Float(core::f64::consts::PI));
 }
diff --git a/crates/frits/src/runtime.rs b/crates/frits/src/runtime.rs
index bf225e1..b208a2b 100644
--- a/crates/frits/src/runtime.rs
+++ b/crates/frits/src/runtime.rs
@@ -1,6 +1,8 @@
 //! Many processes, one platform, a fuel slice each per tick.
 
-use std::rc::Rc;
+#[allow(unused_imports)]
+use crate::base::*;
+use alloc::rc::Rc;
 
 use crate::bytecode::Module;
 use crate::platform::Platform;
diff --git a/crates/frits/src/stdlib.rs b/crates/frits/src/stdlib.rs
index 14e55ec..f09b749 100644
--- a/crates/frits/src/stdlib.rs
+++ b/crates/frits/src/stdlib.rs
@@ -4,8 +4,10 @@
 //! compiled into loops instead (`compile.rs`), so everything a script does is
 //! counted and can be paused.
 
-use std::cmp::Ordering;
-use std::rc::Rc;
+#[allow(unused_imports)]
+use crate::base::*;
+use alloc::rc::Rc;
+use core::cmp::Ordering;
 
 use crate::value::{Heap, Obj, Value};
 
@@ -86,7 +88,9 @@ pub const BYTES_PER_FUEL: u64 = 64;
 /// its bytes for a string.
 fn work(heap: &Heap, strings: &[Rc<str>], v: Value) -> u64 {
     match v {
-        Value::Static(i) => strings.get(i as usize).map_or(0, |s| s.len() as u64) / BYTES_PER_FUEL * ITEMS_PER_FUEL,
+        Value::Static(i) => {
+            strings.get(i as usize).map_or(0, |s| s.len() as u64) / BYTES_PER_FUEL * ITEMS_PER_FUEL
+        }
         _ => match heap.get(v) {
             Some(Obj::Str(s)) => s.len() as u64 / BYTES_PER_FUEL * ITEMS_PER_FUEL,
             Some(Obj::List(x) | Obj::Map(x)) => x.len() as u64,
@@ -123,8 +127,8 @@ pub fn cost(f: Std, heap: &Heap, strings: &[Rc<str>], a: &[Value], out: Value) -
     let items = match f {
         // Constant time whatever the size.
         ListGet | ListFirst | ListLast | MapLen | MapHas | MapGet | IntAbs | IntMin | IntMax | VecAdd
-        | VecSub | VecScale | VecDiv | VecDot | VecCross | VecLength | VecNormalize | VecDistance | VecLerp
-        | MapNew => 0,
+        | VecSub | VecScale | VecDiv | VecDot | VecCross | VecLength | VecNormalize | VecDistance
+        | VecLerp | MapNew => 0,
         ListSort => {
             let n = work(heap, strings, a[0]);
             n * (64 - n.leading_zeros() as u64)
@@ -236,14 +240,14 @@ fn char_range(text: &str, a: i64, b: i64) -> (usize, usize) {
     let mut idx = text
         .char_indices()
         .map(|(i, _)| i)
-        .chain(std::iter::once(text.len()));
+        .chain(core::iter::once(text.len()));
     let start = idx.nth(a).unwrap_or(text.len());
     let end = if b == a {
         start
     } else {
         text.char_indices()
             .map(|(i, _)| i)
-            .chain(std::iter::once(text.len()))
+            .chain(core::iter::once(text.len()))
             .nth(b)
             .unwrap_or(text.len())
     };
@@ -527,18 +531,18 @@ pub fn call(
         }
         VecLength => {
             let p = vec3(heap, a[0]);
-            Value::Float((p[0] * p[0] + p[1] * p[1] + p[2] * p[2]).sqrt())
+            Value::Float(crate::fmath::sqrt(p[0] * p[0] + p[1] * p[1] + p[2] * p[2]))
         }
         VecNormalize => {
             let p = vec3(heap, a[0]);
-            let l = (p[0] * p[0] + p[1] * p[1] + p[2] * p[2]).sqrt();
+            let l = crate::fmath::sqrt(p[0] * p[0] + p[1] * p[1] + p[2] * p[2]);
             let k = if l > 0.0 { 1.0 / l } else { 0.0 };
             new_vec3(heap, [p[0] * k, p[1] * k, p[2] * k])
         }
         VecDistance => {
             let (p, q) = (vec3(heap, a[0]), vec3(heap, a[1]));
             let d = [p[0] - q[0], p[1] - q[1], p[2] - q[2]];
-            Value::Float((d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt())
+            Value::Float(crate::fmath::sqrt(d[0] * d[0] + d[1] * d[1] + d[2] * d[2]))
         }
         Equal => Value::Bool(deep_equal(heap, strings, a[0], a[1])),
         OneOf => match heap
diff --git a/crates/frits/src/tests.rs b/crates/frits/src/tests.rs
index 16c853a..6906201 100644
--- a/crates/frits/src/tests.rs
+++ b/crates/frits/src/tests.rs
@@ -652,7 +652,11 @@ fn copying_a_big_value_costs_by_its_size() {
     let pid = rt.spawn(m, Log::default());
     rt.post(pid, "go", Vec::new());
     rt.tick();
-    assert_eq!(rt.get(pid).unwrap().status, Status::Paused, "2 GB of string in one slice");
+    assert_eq!(
+        rt.get(pid).unwrap().status,
+        Status::Paused,
+        "2 GB of string in one slice"
+    );
 }
 
 #[test]
@@ -1002,7 +1006,10 @@ fn a_field_sends_what_was_typed_in_it() {
     rt.post(pid, "receive", vec![typed]);
     rt.tick();
     let v = rt.get_mut(pid).unwrap().take_view().unwrap();
-    assert_eq!(view::decode(&v).unwrap().attr("value"), Some(&view::AttrValue::Str("milk".into())));
+    assert_eq!(
+        view::decode(&v).unwrap().attr("value"),
+        Some(&view::AttrValue::Str("milk".into()))
+    );
 }
 
 #[test]
diff --git a/crates/frits/src/types.rs b/crates/frits/src/types.rs
index c5d2343..0f552bb 100644
--- a/crates/frits/src/types.rs
+++ b/crates/frits/src/types.rs
@@ -1,8 +1,10 @@
 //! Types, and what a platform declares.
 
-use std::collections::HashMap;
-use std::fmt;
-use std::rc::Rc;
+#[allow(unused_imports)]
+use crate::base::*;
+use alloc::collections::BTreeMap;
+use alloc::rc::Rc;
+use core::fmt;
 
 use crate::Error;
 use crate::ast::{self, TypeExpr};
@@ -138,16 +140,16 @@ impl Type {
 
     /// Replace type parameters by what `bind` fixed them to; one it did not
     /// fix becomes `Error`.
-    pub fn subst(&self, bind: &HashMap<String, Type>) -> Type {
+    pub fn subst(&self, bind: &BTreeMap<String, Type>) -> Type {
         self.replace(bind, false)
     }
 
     /// As `subst`, but a parameter `bind` did not fix stays a parameter.
-    pub fn subst_known(&self, bind: &HashMap<String, Type>) -> Type {
+    pub fn subst_known(&self, bind: &BTreeMap<String, Type>) -> Type {
         self.replace(bind, true)
     }
 
-    fn replace(&self, bind: &HashMap<String, Type>, keep: bool) -> Type {
+    fn replace(&self, bind: &BTreeMap<String, Type>, keep: bool) -> Type {
         let r = |t: &Type| Rc::new(t.replace(bind, keep));
         match self {
             Type::Param(n) => {
@@ -179,7 +181,7 @@ impl Type {
 
     /// Match `self`, which may hold type parameters, against a concrete type,
     /// fixing the parameters in `bind`. False when they cannot agree.
-    pub fn unify(&self, actual: &Type, bind: &mut HashMap<String, Type>) -> bool {
+    pub fn unify(&self, actual: &Type, bind: &mut BTreeMap<String, Type>) -> bool {
         match (self, actual) {
             (Type::Param(n), _) => match bind.get(&**n) {
                 Some(t) => actual.fits(t),
@@ -332,14 +334,14 @@ impl fmt::Display for Show<'_> {
 /// Resolves written types against the aliases and enums in scope.
 #[derive(Debug, Default, Clone)]
 pub struct TypeEnv {
-    pub aliases: HashMap<String, Type>,
-    pub enums: HashMap<String, u32>,
+    pub aliases: BTreeMap<String, Type>,
+    pub enums: BTreeMap<String, u32>,
     /// Type parameters in scope, while a generic function is checked.
-    pub generics: HashMap<String, Type>,
+    pub generics: BTreeMap<String, Type>,
     /// How many type parameters each enum takes.
-    pub enum_params: HashMap<u32, usize>,
+    pub enum_params: BTreeMap<u32, usize>,
     /// `type Pair<A, B> = …`, resolved when used with its arguments.
-    pub generic_aliases: HashMap<String, (Vec<String>, TypeExpr)>,
+    pub generic_aliases: BTreeMap<String, (Vec<String>, TypeExpr)>,
 }
 
 impl TypeEnv {
diff --git a/crates/frits/src/value.rs b/crates/frits/src/value.rs
index 5023f56..589e730 100644
--- a/crates/frits/src/value.rs
+++ b/crates/frits/src/value.rs
@@ -5,7 +5,9 @@
 //! makes a memory ceiling a plain number, a collection one process's business,
 //! and stopping a script nothing more than dropping its heap.
 
-use std::rc::Rc;
+#[allow(unused_imports)]
+use crate::base::*;
+use alloc::rc::Rc;
 
 #[derive(Clone, Copy, Debug, PartialEq)]
 pub enum Value {
diff --git a/crates/frits/src/view.rs b/crates/frits/src/view.rs
index 50784e9..c908972 100644
--- a/crates/frits/src/view.rs
+++ b/crates/frits/src/view.rs
@@ -2,6 +2,8 @@
 //! markup (`Process::take_view`) into plain Rust, and find what pressing an
 //! element sends back.
 
+#[allow(unused_imports)]
+use crate::base::*;
 use crate::value::HostValue;
 
 #[derive(Clone, Debug, PartialEq)]
diff --git a/crates/frits/src/vm.rs b/crates/frits/src/vm.rs
index bd492ac..1362122 100644
--- a/crates/frits/src/vm.rs
+++ b/crates/frits/src/vm.rs
@@ -7,8 +7,10 @@
 //! in which a script cannot be paused: fuel runs out at an instruction, wherever
 //! that instruction is.
 
-use std::collections::VecDeque;
-use std::rc::Rc;
+#[allow(unused_imports)]
+use crate::base::*;
+use alloc::collections::VecDeque;
+use alloc::rc::Rc;
 
 use crate::bytecode::{Module, Op};
 use crate::platform::{Cx, Platform};
@@ -179,7 +181,7 @@ impl<S> Process<S> {
 
     /// The lines logged since the last call.
     pub fn take_log(&mut self) -> Vec<LogLine> {
-        std::mem::take(&mut self.log)
+        core::mem::take(&mut self.log)
     }
 
     /// The `keep var` globals as they are now: (name, type, value). A host
@@ -209,7 +211,7 @@ impl<S> Process<S> {
     }
 
     fn apply_restore(&mut self) {
-        for (name, ty, v) in std::mem::take(&mut self.restore) {
+        for (name, ty, v) in core::mem::take(&mut self.restore) {
             let m = &self.module;
             let Some(&(g, _)) = m
                 .kept
@@ -675,12 +677,14 @@ impl<S> Process<S> {
                     Op::Std { f, base: b, dst } => {
                         let s = base + b as usize;
                         let args = &self.regs[s..s + f.arity()];
-                        let args: [Value; 3] = std::array::from_fn(|i| args.get(i).copied().unwrap_or(Value::Unit));
+                        let args: [Value; 3] =
+                            core::array::from_fn(|i| args.get(i).copied().unwrap_or(Value::Unit));
                         let args = &args[..f.arity()];
                         match crate::stdlib::call(f, &mut self.heap, &m.strings, args, mem_limit) {
                             Ok(v) => {
                                 r!(dst) = v;
-                                fuel = fuel.saturating_sub(crate::stdlib::cost(f, &self.heap, &m.strings, args, v));
+                                fuel = fuel
+                                    .saturating_sub(crate::stdlib::cost(f, &self.heap, &m.strings, args, v));
                             }
                             Err(e) => fail!(e),
                         }
diff --git a/docs/design.md b/docs/design.md
index 0cc07bf..4c2c3c6 100644
--- a/docs/design.md
+++ b/docs/design.md
@@ -170,7 +170,14 @@ on receive(m: Msg) {
   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
 
@@ -243,6 +250,26 @@ A host function can do three things besides answering:
 - `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
@@ -300,7 +327,8 @@ In the order they are likely to matter:
 - 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.
-- wasm (deliberately left for later).
+- 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: