git clone https://garage44.eu/jeroen/frits.gitcartopolis-agent · 2026-11-26T12:11:49Z
feat(frits): closures, a standard library, Result, generics and waiting
Part A of making Frits able to replace Bun in the simulator: what a JS
prim script can do, plus what only a pausable VM can offer.
- Functions are values; closures copy what they name when made and
cannot change it. `map`, `filter`, `any`, `all`, `find`, `count`
compile into loops in the script's own bytecode rather than a host
function calling back, so the callback is counted and pausable.
- Lists, strings, maps (`Map<K, V>`, `[k: v]`, `[:]`), `Vec3` with
operators, tuples, `Result<T, E>` with `?`, value `==` on compound
types, `x.f(a)` calling a script's own `f(x, a)`.
- Generic functions, compiled once per set of type arguments.
Generic types are left for later.
- Nested patterns, tuple and record patterns, guards, and an
exhaustiveness check by constructor specialisation; a guarded arm
covers nothing for certain.
- `cx.suspend()` lets a host call stop a handler mid-way until
`Process::wake` (`Timer.wait(2.5)`); `cx.charge(n)` makes a costly
host call spend fuel; `Random` is an effect with a per-process
stream.
- `keep var` globals survive a restart or a new version through
`Process::kept` / `restore`; one whose type changed is dropped.
- `log`, `warn`, `assert`, `test "…" { }` blocks, `frits test`.
- `Platform::compile` shares one compiled module per source (weakly).
Measured (mac-2, other sessions' load): loading 2000 firebirds went from
~220 ms to 5 ms and resident memory per firebird from 22 KB to 12 KB,
from the shared modules. Old against new build on that node: the busy
loop went from 2.4-2.55 to 2.9 ns per instruction, calls and fib(15)
unchanged; about 18% slower dispatch, not looked into yet.
A line ending in `>` (`-> Option<Int>`) no longer has to be followed by
`}`: a token on a new line now ends the statement. Found when a platform
declaration gained a function after one returning `Option<…>`, and every
test failed with "expected the end of the statement".crates/frits/src/ast.rs | 42 +-
crates/frits/src/bytecode.rs | 43 ++
crates/frits/src/compile.rs | 1679 +++++++++++++++++++++++++++++++++++++-----
crates/frits/src/lexer.rs | 23 +-
crates/frits/src/lib.rs | 5 +-
crates/frits/src/main.rs | 30 +-
crates/frits/src/parser.rs | 250 ++++++-
crates/frits/src/platform.rs | 46 +-
crates/frits/src/prelude.rs | 25 +-
crates/frits/src/runtime.rs | 44 +-
crates/frits/src/stdlib.rs | 496 +++++++++++++
crates/frits/src/tests.rs | 332 +++++++++
crates/frits/src/types.rs | 205 +++++-
crates/frits/src/value.rs | 66 +-
crates/frits/src/vm.rs | 204 ++++-
docs/design.md | 87 ++-
16 files changed, 3331 insertions(+), 246 deletions(-)
diff --git a/crates/frits/src/ast.rs b/crates/frits/src/ast.rs
index 6255c11..04bc0a7 100644
--- a/crates/frits/src/ast.rs
+++ b/crates/frits/src/ast.rs
@@ -21,11 +21,15 @@ pub enum Item {
Namespace(Namespace),
/// Platform declarations only: `event timer()`.
Event(FnDecl),
+ /// `test "a goal counts" { … }`
+ Test(String, Block, u32),
}
#[derive(Debug)]
pub struct FnDecl {
pub name: Name,
+ /// Type parameters: `fn first<T>(xs: List<T>) -> Option<T>`.
+ pub generics: Vec<Name>,
pub params: Vec<(Name, TypeExpr)>,
pub ret: Option<TypeExpr>,
pub effects: Vec<Name>,
@@ -44,6 +48,8 @@ pub struct EnumDecl {
#[derive(Debug)]
pub struct Global {
pub mutable: bool,
+ /// `keep var`: the value survives a restart or an update of the script.
+ pub keep: bool,
pub name: Name,
pub ty: Option<TypeExpr>,
pub value: Expr,
@@ -64,6 +70,19 @@ pub struct Namespace {
pub enum TypeExpr {
Named(Name, Vec<TypeExpr>, u32),
Record(Vec<(Name, TypeExpr)>, u32),
+ /// `(Int, Str)`
+ Tuple(Vec<TypeExpr>, u32),
+ /// `fn(Int, Str) -> Bool / Prim`
+ Fn(Vec<TypeExpr>, Option<Box<TypeExpr>>, Vec<Name>, u32),
+}
+
+/// `fn(x: Int) -> Int { x * 2 }`, or `fn(x) { x * 2 }` where the types are known.
+#[derive(Debug)]
+pub struct Lambda {
+ pub params: Vec<(Name, Option<TypeExpr>)>,
+ pub ret: Option<TypeExpr>,
+ pub effects: Vec<Name>,
+ pub body: Block,
}
#[derive(Debug, Default)]
@@ -75,6 +94,12 @@ pub struct Block {
#[derive(Debug)]
pub enum Stmt {
+ /// `let (x, _, z) = …`: a pattern that always matches.
+ LetPat {
+ pattern: Pattern,
+ value: Expr,
+ line: u32,
+ },
Let {
mutable: bool,
name: Name,
@@ -136,6 +161,13 @@ pub enum ExprKind {
Block(Block),
Record(Vec<(Name, Expr)>, Option<Box<Expr>>),
List(Vec<Expr>),
+ /// `["a": 1, "b": 2]`, or `[:]` for an empty one.
+ MapLit(Vec<(Expr, Expr)>),
+ Lambda(Box<Lambda>),
+ /// `(a, b)`
+ Tuple(Vec<Expr>),
+ /// `e?`: the value inside an Ok or Some, or return the Err or None.
+ Try(Box<Expr>),
}
#[derive(Debug)]
@@ -147,14 +179,20 @@ pub enum TPart {
#[derive(Debug)]
pub struct Arm {
pub pattern: Pattern,
+ /// `pattern if cond => …`
+ pub guard: Option<Expr>,
pub body: Expr,
}
#[derive(Debug, Clone)]
pub enum Pattern {
Wild,
- /// A capitalised name, with bindings for its payload: `Some(hit)`, `Patrol`.
- Variant(Name, Vec<Name>, u32),
+ /// A capitalised name, with patterns for its payload: `Some(hit)`, `Patrol`.
+ Variant(Name, Vec<Pattern>, u32),
+ /// `(x, _, z)`
+ Tuple(Vec<Pattern>),
+ /// `{ name, distance: d, .. }`: the fields named, `..` for the rest.
+ Record(Vec<(Name, Pattern)>, bool, u32),
/// A lower-case name: binds the whole value.
Bind(Name),
Int(i64),
diff --git a/crates/frits/src/bytecode.rs b/crates/frits/src/bytecode.rs
index f469e93..1bb4661 100644
--- a/crates/frits/src/bytecode.rs
+++ b/crates/frits/src/bytecode.rs
@@ -7,6 +7,7 @@
use std::rc::Rc;
+use crate::stdlib::Std;
use crate::value::Value;
pub type Reg = u16;
@@ -267,6 +268,41 @@ pub enum Op {
Panic {
msg: u32,
},
+ /// Panic with the string in `msg` when `cond` is false.
+ Assert {
+ cond: Reg,
+ msg: Reg,
+ },
+ /// Append the string in `src` to the process's log.
+ Log {
+ level: u8,
+ src: Reg,
+ },
+
+ /// A function value: `f` with the values in `base..base+n` captured.
+ MakeClosure {
+ dst: Reg,
+ f: u32,
+ base: Reg,
+ n: u16,
+ },
+ /// Call the function value in `f` with the arguments in `base..`.
+ CallValue {
+ f: Reg,
+ base: Reg,
+ dst: Reg,
+ },
+ /// A built-in method, its arguments in `base..`.
+ Std {
+ f: Std,
+ base: Reg,
+ dst: Reg,
+ },
+ /// Append to a list the compiler is building (never one a script can see).
+ ListPushMut {
+ list: Reg,
+ val: Reg,
+ },
}
#[derive(Debug)]
@@ -277,6 +313,8 @@ pub struct Function {
pub code: Vec<Op>,
/// Source line of each instruction, for error messages.
pub lines: Vec<u32>,
+ /// Where a closure's captured values go, in order.
+ pub captures: Vec<Reg>,
}
/// A compiled script. Immutable, and shared by every process that runs it.
@@ -292,6 +330,11 @@ pub struct Module {
/// Event name → handler function.
pub handlers: Vec<(String, u32)>,
pub effects: Vec<String>,
+ /// `keep var` globals, by index, with their type written out: kept values
+ /// are restored only into a global of the same name and type.
+ pub kept: Vec<(u32, String)>,
+ /// `test "name" { … }` blocks.
+ pub tests: Vec<(String, u32)>,
}
impl Module {
diff --git a/crates/frits/src/compile.rs b/crates/frits/src/compile.rs
index 7e9194e..b53e4eb 100644
--- a/crates/frits/src/compile.rs
+++ b/crates/frits/src/compile.rs
@@ -12,13 +12,15 @@ use std::rc::Rc;
use crate::Error;
use crate::ast::*;
use crate::bytecode::{Function, Module, Op, Reg};
-use crate::types::{PlatformDecl, Show, Type, TypeEnv};
+use crate::stdlib::Std;
+use crate::types::{FnType, PlatformDecl, Show, Type, TypeEnv};
use crate::value::Value;
pub fn compile(src: &str, plat: &PlatformDecl) -> Result<Module, Vec<Error>> {
let ast = crate::parser::parse(src).map_err(|e| vec![e])?;
let mut c = Compiler::new(plat);
c.module(&ast);
+ c.instances();
if c.errors.is_empty() {
Ok(c.out)
} else {
@@ -48,6 +50,8 @@ struct Local {
reg: Reg,
ty: Type,
mutable: bool,
+ /// A closure's copy of an outer variable.
+ captured: bool,
}
#[derive(Default)]
@@ -67,6 +71,7 @@ struct FnState {
ret: Type,
effects: Vec<String>,
name: String,
+ captures: Vec<Reg>,
}
/// Where an expression's value goes.
@@ -79,8 +84,10 @@ enum Dst<'a> {
const OPTION_NONE: u32 = 0;
const OPTION_SOME: u32 = 1;
+const RESULT_OK: u32 = 0;
+const RESULT_ERR: u32 = 1;
-struct Compiler<'p> {
+struct Compiler<'p, 'a> {
plat: &'p PlatformDecl,
env: TypeEnv,
enums: Vec<EnumInfo>,
@@ -97,9 +104,13 @@ struct Compiler<'p> {
line: u32,
const_index: HashMap<(u8, u64), u32>,
string_index: HashMap<String, u32>,
+ generic_fns: HashMap<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)>,
}
-impl<'p> Compiler<'p> {
+impl<'p, 'a> Compiler<'p, 'a> {
fn new(plat: &'p PlatformDecl) -> Self {
Compiler {
plat,
@@ -118,6 +129,9 @@ impl<'p> Compiler<'p> {
line: 0,
const_index: HashMap::new(),
string_index: HashMap::new(),
+ generic_fns: HashMap::new(),
+ instance_ids: HashMap::new(),
+ pending: Vec::new(),
}
}
@@ -141,7 +155,7 @@ impl<'p> Compiler<'p> {
// ── The module ──
- fn module(&mut self, m: &crate::ast::Module) {
+ fn module(&mut self, m: &'a crate::ast::Module) {
for e in &m.effects {
if !self.plat.effects.contains(e) {
let known = self.plat.effects.join(", ");
@@ -184,8 +198,7 @@ impl<'p> Compiler<'p> {
if !v.starts_with(|c: char| c.is_ascii_uppercase()) {
self.error(e.line, format!("variant `{v}` must start with a capital letter"));
}
- if v == "Some"
- || v == "None"
+ if ["Some", "None", "Ok", "Err"].contains(&v.as_str())
|| self.variants.insert(v.clone(), (id, tag as u32)).is_some()
{
self.error(e.line, format!("variant `{v}` is already defined"));
@@ -198,10 +211,20 @@ impl<'p> Compiler<'p> {
}
// Signatures, so bodies can call functions defined below them.
- let mut bodies: Vec<(&FnDecl, bool)> = Vec::new();
+ let mut bodies: Vec<(&'a FnDecl, bool)> = Vec::new();
for item in &m.items {
match item {
+ Item::Fn(f) if !f.generics.is_empty() => {
+ if self.generic_fns.insert(f.name.clone(), f).is_some()
+ || self.fn_index.contains_key(&f.name)
+ {
+ self.error(f.line, format!("function `{}` is defined twice", f.name));
+ }
+ }
Item::Fn(f) => {
+ if self.generic_fns.contains_key(&f.name) {
+ self.error(f.line, format!("function `{}` is defined twice", f.name));
+ }
let sig = self.signature(f);
let id = self.fns.len() as u32;
if self.fn_index.insert(f.name.clone(), id).is_some() {
@@ -258,15 +281,7 @@ impl<'p> Compiler<'p> {
}
let total = nfns + handlers.len() + 1;
self.out.init = (total - 1) as u32;
- self.out.funcs = (0..total)
- .map(|_| Function {
- name: String::new(),
- arity: 0,
- nregs: 0,
- code: Vec::new(),
- lines: Vec::new(),
- })
- .collect();
+ self.out.funcs = (0..total).map(|_| Self::placeholder()).collect();
// The globals' initialiser, which also settles their types.
self.begin("(init)", Type::Unit, self.module_effects.clone());
@@ -287,6 +302,10 @@ impl<'p> Compiler<'p> {
self.error(g.line, format!("`{}` is defined twice", g.name));
}
let gi = self.globals.len() as u32;
+ if g.keep {
+ let shown = self.show(&ty);
+ self.out.kept.push((gi, shown));
+ }
self.globals.push(GlobalInfo {
ty,
mutable: g.mutable,
@@ -315,6 +334,53 @@ impl<'p> Compiler<'p> {
};
self.function(f, id as u32, is_handler);
}
+
+ for item in &m.items {
+ if let Item::Test(name, body, line) = item {
+ let id = self.out.funcs.len() as u32;
+ self.out.funcs.push(Self::placeholder());
+ self.begin(
+ &format!("test \"{name}\""),
+ Type::Unit,
+ self.module_effects.clone(),
+ );
+ self.line = *line;
+ self.f.scopes.push(Vec::new());
+ self.block(body, Dst::Discard);
+ let r = self.alloc();
+ self.emit(Op::LoadUnit { dst: r });
+ self.emit(Op::Ret { src: r });
+ self.finish(id, 0);
+ self.out.tests.push((name.clone(), id));
+ }
+ }
+ }
+
+ fn placeholder() -> Function {
+ Function {
+ name: String::new(),
+ arity: 0,
+ nregs: 0,
+ code: Vec::new(),
+ lines: Vec::new(),
+ captures: Vec::new(),
+ }
+ }
+
+ /// Compile every generic function for the type arguments it was called
+ /// 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);
+ self.function(decl, id, false);
+ let args: Vec<String> = decl
+ .generics
+ .iter()
+ .map(|g| self.show(&self.env.generics[g]))
+ .collect();
+ self.out.funcs[id as usize].name = format!("{}<{}>", decl.name, args.join(", "));
+ self.env.generics = saved;
+ }
}
fn signature(&mut self, f: &FnDecl) -> FnSig {
@@ -344,6 +410,7 @@ impl<'p> Compiler<'p> {
reg: r,
ty: ty.clone(),
mutable: false,
+ captured: false,
});
}
let body = f.body.as_ref().expect("script functions have bodies");
@@ -378,6 +445,7 @@ impl<'p> Compiler<'p> {
nregs: f.max.max(1),
code: f.code,
lines: f.lines,
+ captures: f.captures,
};
}
@@ -520,11 +588,23 @@ impl<'p> Compiler<'p> {
reg: r,
ty,
mutable: *mutable,
+ captured: false,
});
// The local keeps its register; temporaries above it are free again.
self.f.next = r + 1;
return false;
}
+ Stmt::LetPat { pattern, value, line } => {
+ self.line = *line;
+ let r = self.alloc();
+ let t = self.expr(value, Dst::To(r, None));
+ let fails = self.pattern_test(pattern, r, &t, *line);
+ if !fails.is_empty() {
+ self.error(*line, "this pattern may not match: use `if let` or `match`");
+ }
+ // The bindings keep their registers.
+ return false;
+ }
Stmt::Assign {
target,
op,
@@ -634,6 +714,7 @@ impl<'p> Compiler<'p> {
reg: v,
ty: Type::Int,
mutable: false,
+ captured: false,
});
self.f.loops.push(LoopCtx::default());
self.block(body, Dst::Discard);
@@ -688,6 +769,7 @@ impl<'p> Compiler<'p> {
reg: v,
ty: elem,
mutable: false,
+ captured: false,
});
self.f.loops.push(LoopCtx::default());
self.block(body, Dst::Discard);
@@ -713,6 +795,64 @@ impl<'p> Compiler<'p> {
/// field changed: values are never shared mutably, so a field assignment is a
/// copy written back to the variable.
fn assign(&mut self, target: &Expr, op: Option<BinOp>, value: &Expr, line: u32) {
+ // `xs[i] = v` is `xs = xs with item i replaced`.
+ if let ExprKind::Index(list, idx) = &target.kind {
+ if op.is_some() {
+ self.error(
+ line,
+ "write `xs[i] = xs[i] + …`: `+=` on an item is not supported",
+ );
+ return;
+ }
+ self.store(list, line, &mut |c: &mut Self, cur, cur_ty, dst| {
+ let Type::List(elem) = cur_ty else {
+ if *cur_ty != Type::Error {
+ let s = c.show(cur_ty);
+ c.error(line, format!("only a List can be indexed, not {s}"));
+ }
+ return Type::Error;
+ };
+ let elem = (**elem).clone();
+ let base = c.alloc_n(3);
+ c.emit(Op::Move { dst: base, src: cur });
+ let t = c.expr(idx, Dst::To(base + 1, Some(&Type::Int)));
+ c.expect(&t, &Type::Int, line);
+ let t = c.expr(value, Dst::To(base + 2, Some(&elem)));
+ c.expect(&t, &elem, line);
+ c.emit(Op::Std {
+ f: Std::ListSet,
+ base,
+ dst,
+ });
+ cur_ty.clone()
+ });
+ return;
+ }
+ self.store(target, line, &mut |c: &mut Self, leaf, leaf_ty, v| match op {
+ None => {
+ let t = c.expr(value, Dst::To(v, Some(leaf_ty)));
+ c.expect(&t, leaf_ty, line);
+ leaf_ty.clone()
+ }
+ Some(op) => {
+ let (rv, rt) = c.expr_any(value, Some(leaf_ty));
+ let t = c.arith(op, leaf_ty, &rt, leaf, rv, v, line);
+ c.expect(&t, leaf_ty, line);
+ leaf_ty.clone()
+ }
+ });
+ }
+
+ /// Replace the value at `target` (a variable, or a field path from one)
+ /// with what `compute` makes from the current value: `compute` gets the
+ /// current value's register and type, and writes the new value to the
+ /// register it is given.
+ fn store(
+ &mut self,
+ target: &Expr,
+ line: u32,
+ compute: &mut dyn FnMut(&mut Self, Reg, &Type, Reg) -> Type,
+ ) {
// The path from the variable to the field being set.
let mut path: Vec<&str> = Vec::new();
let mut root = target;
@@ -729,21 +869,30 @@ impl<'p> Compiler<'p> {
Local(Reg),
Global(u32),
}
- let (slot, root_ty) =
- if let Some((reg, ty, mutable)) = self.lookup(name).map(|l| (l.reg, l.ty.clone(), l.mutable)) {
- if !mutable {
- self.error(line, format!("`{name}` cannot be changed: declare it with `var`"));
- }
- (Slot::Local(reg), ty)
- } else if let Some(&g) = self.global_index.get(name) {
- if !self.globals[g as usize].mutable {
- self.error(line, format!("`{name}` cannot be changed: declare it with `var`"));
- }
- (Slot::Global(g), self.globals[g as usize].ty.clone())
- } else {
- self.error(line, format!("unknown variable `{name}`"));
- return;
- };
+ let (slot, root_ty) = if let Some((reg, ty, mutable, captured)) = self
+ .lookup(name)
+ .map(|l| (l.reg, l.ty.clone(), l.mutable, l.captured))
+ {
+ if captured {
+ self.error(
+ line,
+ format!(
+ "`{name}` belongs to the enclosing function: a closure has a copy it cannot change"
+ ),
+ );
+ } else if !mutable {
+ self.error(line, format!("`{name}` cannot be changed: declare it with `var`"));
+ }
+ (Slot::Local(reg), ty)
+ } else if let Some(&g) = self.global_index.get(name) {
+ if !self.globals[g as usize].mutable {
+ self.error(line, format!("`{name}` cannot be changed: declare it with `var`"));
+ }
+ (Slot::Global(g), self.globals[g as usize].ty.clone())
+ } else {
+ self.error(line, format!("unknown variable `{name}`"));
+ return;
+ };
// Load the chain: regs[0] is the variable, regs[i+1] its field path[i].
let mut regs = Vec::new();
let mut tys = vec![root_ty.clone()];
@@ -779,17 +928,8 @@ impl<'p> Compiler<'p> {
let leaf_ty = tys.last().unwrap().clone();
let leaf = *regs.last().unwrap();
let v = self.alloc();
- match op {
- None => {
- let t = self.expr(value, Dst::To(v, Some(&leaf_ty)));
- self.expect(&t, &leaf_ty, line);
- }
- Some(op) => {
- let (rv, rt) = self.expr_any(value, Some(&leaf_ty));
- let t = self.arith(op, &leaf_ty, &rt, leaf, rv, v, line);
- self.expect(&t, &leaf_ty, line);
- }
- }
+ let t = compute(self, leaf, &leaf_ty, v);
+ self.expect(&t, &leaf_ty, line);
// Rebuild outward.
let mut cur = v;
for i in (0..path.len()).rev() {
@@ -963,6 +1103,10 @@ impl<'p> Compiler<'p> {
});
Type::List(Rc::new(elem.unwrap()))
}
+ ExprKind::Lambda(l) => self.lambda(l, r, want, line),
+ ExprKind::Tuple(items) => self.tuple(items, r, want),
+ ExprKind::MapLit(entries) => self.map_lit(entries, r, want, line),
+ ExprKind::Try(e) => self.try_expr(e, r, line),
ExprKind::If(..) | ExprKind::IfLet(..) | ExprKind::Match(..) | ExprKind::Block(_) => {
unreachable!()
}
@@ -1005,8 +1149,26 @@ impl<'p> Compiler<'p> {
self.emit(Op::LoadTag { dst: r, tag });
return Type::Enum(e);
}
- if self.fn_index.contains_key(n) {
- self.error(line, format!("`{n}` is a function: call it as `{n}(…)`"));
+ if let Some(&f) = self.fn_index.get(n) {
+ let sig = &self.fns[f as usize];
+ let ty = Type::Fn(Rc::new(FnType::new(
+ sig.params.clone(),
+ sig.ret.clone(),
+ sig.effects.clone(),
+ )));
+ self.emit(Op::MakeClosure {
+ dst: r,
+ f,
+ base: r,
+ n: 0,
+ });
+ return ty;
+ }
+ if self.generic_fns.contains_key(n) {
+ self.error(
+ line,
+ format!("`{n}` is generic: wrap it, `fn(x) {{ {n}(x) }}`, to pass it on"),
+ );
} else if self.plat.is_namespace(n) {
self.error(line, format!("`{n}` is a namespace: write `{n}.name`"));
} else {
@@ -1071,18 +1233,34 @@ impl<'p> Compiler<'p> {
}
}
- /// Arguments into consecutive registers at a fresh base.
- fn args(&mut self, args: &[Expr], params: &[Type], what: &str, line: u32) -> Reg {
- if args.len() != params.len() {
+ /// Arguments into consecutive registers at a fresh base; `first`, when
+ /// given, is an already compiled first argument (the `x` of `x.f()`).
+ fn args(
+ &mut self,
+ first: Option<(Reg, Type)>,
+ args: &[&Expr],
+ params: &[Type],
+ what: &str,
+ line: u32,
+ ) -> Reg {
+ let skip = first.is_some() as usize;
+ let n = skip + args.len();
+ if n != params.len() {
self.error(
line,
- format!("{what} takes {} argument(s), not {}", params.len(), args.len()),
+ format!("{what} takes {} argument(s), not {n}", params.len()),
);
}
- let base = self.alloc_n(args.len().max(1));
+ let base = self.alloc_n(n.max(1));
+ if let Some((fr, ft)) = first {
+ self.emit(Op::Move { dst: base, src: fr });
+ if let Some(w) = params.first() {
+ self.expect(&ft, w, line);
+ }
+ }
for (i, a) in args.iter().enumerate() {
- let want = params.get(i);
- let t = self.expr(a, Dst::To(base + i as Reg, want));
+ let want = params.get(skip + i);
+ let t = self.expr(a, Dst::To(base + (skip + i) as Reg, want));
if let Some(w) = want {
self.expect(&t, w, a.line);
}
@@ -1091,9 +1269,10 @@ impl<'p> Compiler<'p> {
}
fn call(&mut self, callee: &Expr, args: &[Expr], r: Reg, want: Option<&Type>, line: u32) -> Type {
+ let argv: Vec<&Expr> = args.iter().collect();
match &callee.kind {
- ExprKind::Field(ns_e, name) => {
- if let ExprKind::Ident(ns) = &ns_e.kind
+ ExprKind::Field(recv, name) => {
+ if let ExprKind::Ident(ns) = &recv.kind
&& self.lookup(ns).is_none()
&& !self.global_index.contains_key(ns)
&& self.plat.is_namespace(ns)
@@ -1108,7 +1287,7 @@ impl<'p> Compiler<'p> {
{
self.missing_effect(eff, line);
}
- let base = self.args(args, &sig.params, &format!("`{ns}.{name}`"), line);
+ let base = self.args(None, &argv, &sig.params, &format!("`{ns}.{name}`"), line);
self.emit(Op::CallHost {
f,
base,
@@ -1117,37 +1296,27 @@ impl<'p> Compiler<'p> {
});
return sig.ret;
}
- self.error(
- line,
- "only functions can be called; methods are not supported yet",
- );
- Type::Error
+ self.method(recv, name, &argv, r, want, line)
}
ExprKind::Ident(n) => {
+ // A variable holding a function.
+ let held = match self.lookup(n) {
+ Some(l) => Some(l.ty.clone()),
+ None => self
+ .global_index
+ .get(n)
+ .map(|&g| self.globals[g as usize].ty.clone()),
+ };
+ if let Some(t) = held {
+ let (fr, ft) = self.expr_any(callee, None);
+ let _ = t;
+ return self.call_value(fr, &ft, &argv, r, line);
+ }
if let Some(t) = self.builtin(n, args, r, line) {
return t;
}
- if n == "Some" {
- let inner_want = match want {
- Some(Type::Option(t)) => Some((**t).clone()),
- _ => None,
- };
- if args.len() != 1 {
- self.error(line, "`Some` takes one value");
- return Type::Error;
- }
- let base = self.alloc();
- let t = self.expr(&args[0], Dst::To(base, inner_want.as_ref()));
- if let Some(w) = &inner_want {
- self.expect(&t, w, line);
- }
- self.emit(Op::MakeVariant {
- dst: r,
- tag: OPTION_SOME,
- base,
- n: 1,
- });
- return Type::Option(Rc::new(inner_want.unwrap_or(t)));
+ if matches!(n.as_str(), "Some" | "Ok" | "Err") {
+ return self.wrap(n, args, r, want, line);
}
if let Some(&(e, tag)) = self.variants.get(n) {
let params = self.enums[e as usize].variants[tag as usize].1.clone();
@@ -1158,7 +1327,7 @@ impl<'p> Compiler<'p> {
);
return Type::Error;
}
- let base = self.args(args, ¶ms, &format!("`{n}`"), line);
+ let base = self.args(None, &argv, ¶ms, &format!("`{n}`"), line);
self.emit(Op::MakeVariant {
dst: r,
tag,
@@ -1167,26 +1336,18 @@ impl<'p> Compiler<'p> {
});
return Type::Enum(e);
}
+ if let Some(&decl) = self.generic_fns.get(n) {
+ return self.generic_call(decl, None, &argv, r, line);
+ }
let Some(&f) = self.fn_index.get(n) else {
self.error(line, format!("unknown function `{n}`"));
return Type::Error;
};
- let (params, ret, effects) = {
- let s = &self.fns[f as usize];
- (s.params.clone(), s.ret.clone(), s.effects.clone())
- };
- for eff in &effects {
- if !self.f.effects.contains(eff) {
- self.missing_effect(eff, line);
- }
- }
- let base = self.args(args, ¶ms, &format!("`{n}`"), line);
- self.emit(Op::Call { f, base, dst: r });
- ret
+ self.direct_call(f, None, &argv, r, n, line)
}
_ => {
- self.error(line, "only named functions can be called");
- Type::Error
+ let (fr, ft) = self.expr_any(callee, None);
+ self.call_value(fr, &ft, &argv, r, line)
}
}
}
@@ -1215,15 +1376,69 @@ impl<'p> Compiler<'p> {
"len" => {
let (a, t) = one(self)?;
match t {
- Type::List(_) => self.emit(Op::Len { dst: r, src: a }),
- Type::Str => self.emit(Op::StrLen { dst: r, src: a }),
- Type::Error => 0,
+ Type::List(_) | Type::Str | Type::Map(..) => self.len_of(a, &t, r),
+ Type::Error => {}
t => {
let s = self.show(&t);
- self.error(line, format!("`len` takes a List or a Str, not {s}"));
- 0
+ self.error(line, format!("`len` takes a List, Str or Map, not {s}"));
+ }
+ };
+ Type::Int
+ }
+ "log" | "warn" => {
+ let (a, t) = one(self)?;
+ self.expect(&t, &Type::Str, line);
+ self.emit(Op::Log {
+ level: u8::from(n == "warn"),
+ src: a,
+ });
+ self.emit(Op::LoadUnit { dst: r });
+ Type::Unit
+ }
+ "assert" => {
+ if args.is_empty() || args.len() > 2 {
+ self.error(line, "`assert` takes a condition and, if you like, a message");
+ return Some(Type::Unit);
+ }
+ let c = self.cond(&args[0]);
+ let m = match args.get(1) {
+ Some(e) => {
+ let (m, t) = self.expr_any(e, Some(&Type::Str));
+ self.expect(&t, &Type::Str, line);
+ m
+ }
+ None => {
+ let k = self.string(&format!("line {line}"));
+ let m = self.alloc();
+ self.emit(Op::LoadK { dst: m, k });
+ m
+ }
+ };
+ self.emit(Op::Assert { cond: c, msg: m });
+ self.emit(Op::LoadUnit { dst: r });
+ Type::Unit
+ }
+ "abs" | "min" | "max" => {
+ let want = if n == "abs" { 1 } else { 2 };
+ if args.len() != want {
+ self.error(line, format!("`{n}` takes {want} Int(s)"));
+ return Some(Type::Error);
+ }
+ let base = self.alloc_n(want);
+ for (i, a) in args.iter().enumerate() {
+ let t = self.expr(a, Dst::To(base + i as Reg, Some(&Type::Int)));
+ if t == Type::Float {
+ self.error(a.line, format!("`{n}` is for Int; for a Float use `math.{n}`"));
+ } else {
+ self.expect(&t, &Type::Int, a.line);
}
+ }
+ let f = match n {
+ "abs" => Std::IntAbs,
+ "min" => Std::IntMin,
+ _ => Std::IntMax,
};
+ self.emit(Op::Std { f, base, dst: r });
Type::Int
}
"panic" => {
@@ -1286,6 +1501,46 @@ impl<'p> Compiler<'p> {
self.emit(Op::Concat { dst, base, n: 2 });
Type::Str
}
+ (Type::List(x), Type::List(y)) if op == Add && x == y => {
+ let base = self.alloc_n(2);
+ self.emit(Op::Move { dst: base, src: a });
+ self.emit(Op::Move {
+ dst: base + 1,
+ src: b,
+ });
+ self.emit(Op::Std {
+ f: Std::ListConcat,
+ base,
+ dst,
+ });
+ lt.clone()
+ }
+ (v, w)
+ if v.is_vec3() && (w.is_vec3() || *w == Type::Float)
+ || (*v == Type::Float && w.is_vec3()) =>
+ {
+ let f = match (op, v.is_vec3(), w.is_vec3()) {
+ (Add, true, true) => Some((Std::VecAdd, a, b)),
+ (Sub, true, true) => Some((Std::VecSub, a, b)),
+ (Mul, true, false) => Some((Std::VecScale, a, b)),
+ (Mul, false, true) => Some((Std::VecScale, b, a)),
+ (Div, true, false) => Some((Std::VecDiv, a, b)),
+ _ => None,
+ };
+ let Some((f, x, y)) = f else {
+ let (l, r) = (self.show(lt), self.show(rt));
+ self.error(line, format!("cannot apply this operator to {l} and {r}"));
+ return Type::Error;
+ };
+ let base = self.alloc_n(2);
+ self.emit(Op::Move { dst: base, src: x });
+ self.emit(Op::Move {
+ dst: base + 1,
+ src: y,
+ });
+ self.emit(Op::Std { f, base, dst });
+ if v.is_vec3() { lt.clone() } else { rt.clone() }
+ }
(Type::Error, _) | (_, Type::Error) => Type::Error,
_ => {
let (l, r) = (self.show(lt), self.show(rt));
@@ -1326,11 +1581,17 @@ impl<'p> Compiler<'p> {
// An integer literal beside a Float is a Float: `2 * math.pi`.
let (ar, at, br, bt) = if matches!(a.kind, ExprKind::Int(_)) && !matches!(b.kind, ExprKind::Int(_)) {
let (br, bt) = self.expr_any(b, None);
- let (ar, at) = self.expr_any(a, Some(&bt));
+ let lw = if bt.is_vec3() { Type::Float } else { bt.clone() };
+ let (ar, at) = self.expr_any(a, Some(&lw));
(ar, at, br, bt)
} else {
let (ar, at) = self.expr_any(a, None);
- let (br, bt) = self.expr_any(b, Some(&at));
+ let rw = if at.is_vec3() && matches!(b.kind, ExprKind::Int(_)) {
+ Type::Float
+ } else {
+ at.clone()
+ };
+ let (br, bt) = self.expr_any(b, Some(&rw));
(ar, at, br, bt)
};
match op {
@@ -1380,9 +1641,26 @@ impl<'p> Compiler<'p> {
self.emit(Op::EqTag { dst: r, a: ar, b: br });
}
Type::Error => {}
+ t if !t.has_fn() => {
+ // Compared by value, all the way down.
+ let base = self.alloc_n(2);
+ self.emit(Op::Move { dst: base, src: ar });
+ self.emit(Op::Move {
+ dst: base + 1,
+ src: br,
+ });
+ self.emit(Op::Std {
+ f: Std::Equal,
+ base,
+ dst: r,
+ });
+ }
t => {
let s = self.show(t);
- self.error(line, format!("`==` does not apply to {s}: use `match`"));
+ self.error(
+ line,
+ format!("`==` does not apply to {s}: functions cannot be compared"),
+ );
}
}
} else {
@@ -1666,45 +1944,109 @@ impl<'p> Compiler<'p> {
/// current scope. Returns the jumps taken when it does not match.
fn pattern_test(&mut self, p: &Pattern, s: Reg, st: &Type, line: u32) -> Vec<usize> {
let mut fails = Vec::new();
+ self.pattern_into(p, s, st, line, &mut fails);
+ fails
+ }
+
+ fn bind(&mut self, name: &str, src: Reg, ty: Type) {
+ let r = self.alloc();
+ self.emit(Op::Move { dst: r, src });
+ self.f.scopes.last_mut().unwrap().push(Local {
+ name: name.to_string(),
+ reg: r,
+ ty,
+ mutable: false,
+ captured: false,
+ });
+ }
+
+ fn test_eq(&mut self, s: Reg, k: Reg, ty: &Type, fails: &mut Vec<usize>) {
+ let c = self.alloc();
+ self.emit(match ty {
+ Type::Int => Op::EqI { dst: c, a: s, b: k },
+ Type::Bool => Op::EqB { dst: c, a: s, b: k },
+ _ => Op::EqS { dst: c, a: s, b: k },
+ });
+ fails.push(self.emit(Op::JumpIfFalse { cond: c, to: 0 }));
+ }
+
+ fn pattern_into(&mut self, p: &Pattern, s: Reg, st: &Type, line: u32, fails: &mut Vec<usize>) {
match p {
Pattern::Wild => {}
- Pattern::Bind(n) => {
- let r = self.alloc();
- self.emit(Op::Move { dst: r, src: s });
- self.f.scopes.last_mut().unwrap().push(Local {
- name: n.clone(),
- reg: r,
- ty: st.clone(),
- mutable: false,
- });
- }
+ Pattern::Bind(n) => self.bind(n, s, st.clone()),
Pattern::Int(i) => {
self.expect(&Type::Int, st, line);
let k = self.konst(Value::Int(*i));
- let (kr, c) = (self.alloc(), self.alloc());
+ let kr = self.alloc();
self.emit(Op::LoadK { dst: kr, k });
- self.emit(Op::EqI { dst: c, a: s, b: kr });
- fails.push(self.emit(Op::JumpIfFalse { cond: c, to: 0 }));
+ self.test_eq(s, kr, &Type::Int, fails);
}
Pattern::Bool(b) => {
self.expect(&Type::Bool, st, line);
- let (kr, c) = (self.alloc(), self.alloc());
+ let kr = self.alloc();
self.emit(Op::LoadBool { dst: kr, v: *b });
- self.emit(Op::EqB { dst: c, a: s, b: kr });
- fails.push(self.emit(Op::JumpIfFalse { cond: c, to: 0 }));
+ self.test_eq(s, kr, &Type::Bool, fails);
}
Pattern::Str(text) => {
self.expect(&Type::Str, st, line);
let k = self.string(text);
- let (kr, c) = (self.alloc(), self.alloc());
+ let kr = self.alloc();
self.emit(Op::LoadK { dst: kr, k });
- self.emit(Op::EqS { dst: c, a: s, b: kr });
- fails.push(self.emit(Op::JumpIfFalse { cond: c, to: 0 }));
+ self.test_eq(s, kr, &Type::Str, fails);
+ }
+ Pattern::Tuple(subs) => {
+ let Type::Tuple(items) = st else {
+ if *st != Type::Error {
+ let t = self.show(st);
+ self.error(line, format!("a tuple pattern cannot match a value of type {t}"));
+ }
+ return;
+ };
+ if items.len() != subs.len() {
+ self.error(
+ line,
+ format!("the tuple has {} values, the pattern {}", items.len(), subs.len()),
+ );
+ return;
+ }
+ let items = items.clone();
+ for (i, (sub, t)) in subs.iter().zip(items.iter()).enumerate() {
+ if matches!(sub, Pattern::Wild) {
+ continue;
+ }
+ let r = self.alloc();
+ self.emit(Op::GetField {
+ dst: r,
+ src: s,
+ idx: i as u16,
+ });
+ self.pattern_into(sub, r, t, line, fails);
+ }
+ }
+ Pattern::Record(fields, _, rline) => {
+ for (name, sub) in fields {
+ let Some((idx, t)) = st.field(name).map(|(i, t)| (i, t.clone())) else {
+ if *st != Type::Error {
+ let t = self.show(st);
+ self.error(*rline, format!("{t} has no field `{name}`"));
+ }
+ continue;
+ };
+ let r = self.alloc();
+ self.emit(Op::GetField {
+ dst: r,
+ src: s,
+ idx: idx as u16,
+ });
+ self.pattern_into(sub, r, &t, line, fails);
+ }
}
- Pattern::Variant(name, binds, vline) => {
+ Pattern::Variant(name, subs, vline) => {
let (tag, payload): (u32, Vec<Type>) = match (name.as_str(), st) {
("Some", Type::Option(t)) => (OPTION_SOME, vec![(**t).clone()]),
("None", Type::Option(_)) => (OPTION_NONE, vec![]),
+ ("Ok", Type::Result(t, _)) => (RESULT_OK, vec![(**t).clone()]),
+ ("Err", Type::Result(_, e)) => (RESULT_ERR, vec![(**e).clone()]),
(_, Type::Enum(e)) => match self.variants.get(name) {
Some(&(ve, tag)) if ve == *e => {
(tag, self.enums[ve as usize].variants[tag as usize].1.clone())
@@ -1712,31 +2054,30 @@ impl<'p> Compiler<'p> {
_ => {
let en = self.enums[*e as usize].name.clone();
self.error(*vline, format!("`{name}` is not a variant of {en}"));
- return fails;
+ return;
}
},
- (_, Type::Error) => return fails,
+ (_, Type::Error) => return,
_ => {
let t = self.show(st);
self.error(*vline, format!("`{name}` cannot match a value of type {t}"));
- return fails;
+ return;
}
};
- if binds.len() != payload.len() {
+ if subs.len() != payload.len() {
self.error(
*vline,
- format!("`{name}` carries {} value(s), not {}", payload.len(), binds.len()),
+ format!("`{name}` carries {} value(s), not {}", payload.len(), subs.len()),
);
- return fails;
+ return;
}
let k = self.konst(Value::Int(tag as i64));
- let (tr, kr, c) = (self.alloc(), self.alloc(), self.alloc());
+ let (tr, kr) = (self.alloc(), self.alloc());
self.emit(Op::GetTag { dst: tr, src: s });
self.emit(Op::LoadK { dst: kr, k });
- self.emit(Op::EqI { dst: c, a: tr, b: kr });
- fails.push(self.emit(Op::JumpIfFalse { cond: c, to: 0 }));
- for (i, (b, t)) in binds.iter().zip(payload).enumerate() {
- if b == "_" {
+ self.test_eq(tr, kr, &Type::Int, fails);
+ for (i, (sub, t)) in subs.iter().zip(payload).enumerate() {
+ if matches!(sub, Pattern::Wild) {
continue;
}
let r = self.alloc();
@@ -1745,16 +2086,106 @@ impl<'p> Compiler<'p> {
src: s,
idx: i as u16,
});
- self.f.scopes.last_mut().unwrap().push(Local {
- name: b.clone(),
- reg: r,
- ty: t,
- mutable: false,
- });
+ self.pattern_into(sub, r, &t, line, fails);
}
}
}
- fails
+ }
+
+ /// A pattern that matches every value of its type.
+ fn irrefutable(p: &Pattern) -> bool {
+ match p {
+ Pattern::Wild | Pattern::Bind(_) => true,
+ Pattern::Tuple(subs) => subs.iter().all(Self::irrefutable),
+ Pattern::Record(fields, _, _) => fields.iter().all(|(_, p)| Self::irrefutable(p)),
+ _ => false,
+ }
+ }
+
+ /// Does every value of the types `tys` match one of `rows`, each a row of
+ /// patterns, one per type? The usual specialisation by constructor: a
+ /// tuple or record column becomes its parts; an Option, Result, enum or
+ /// Bool column splits into one problem per constructor.
+ fn covers(&self, rows: Vec<Vec<Pattern>>, tys: &[Type]) -> bool {
+ let Some((ty, rest)) = tys.split_first() else {
+ return !rows.is_empty();
+ };
+ if rows.is_empty() {
+ return false;
+ }
+ let wild = |p: &Pattern| matches!(p, Pattern::Wild | Pattern::Bind(_));
+ let parts: Option<Vec<Type>> = match ty {
+ Type::Tuple(items) => Some(items.to_vec()),
+ Type::Record(fields) => Some(fields.iter().map(|(_, t)| t.clone()).collect()),
+ _ => None,
+ };
+ if let Some(parts) = parts {
+ let n = parts.len();
+ let rows = rows
+ .into_iter()
+ .filter_map(|row| {
+ let head: Vec<Pattern> = match &row[0] {
+ p if wild(p) => vec![Pattern::Wild; n],
+ Pattern::Tuple(subs) if subs.len() == n => subs.clone(),
+ Pattern::Record(fs, _, _) => match ty {
+ Type::Record(fields) => fields
+ .iter()
+ .map(|(name, _)| {
+ fs.iter()
+ .find(|(f, _)| **f == **name)
+ .map(|(_, p)| p.clone())
+ .unwrap_or(Pattern::Wild)
+ })
+ .collect(),
+ _ => return None,
+ },
+ _ => return None,
+ };
+ Some(head.into_iter().chain(row[1..].iter().cloned()).collect())
+ })
+ .collect();
+ let tys: Vec<Type> = parts.into_iter().chain(rest.iter().cloned()).collect();
+ return self.covers(rows, &tys);
+ }
+ let ctors: Option<Vec<(String, Vec<Type>)>> = match ty {
+ Type::Option(t) => Some(vec![
+ ("None".into(), vec![]),
+ ("Some".into(), vec![(**t).clone()]),
+ ]),
+ Type::Result(t, e) => Some(vec![
+ ("Ok".into(), vec![(**t).clone()]),
+ ("Err".into(), vec![(**e).clone()]),
+ ]),
+ Type::Enum(e) => Some(self.enums[*e as usize].variants.clone()),
+ Type::Bool => Some(vec![("true".into(), vec![]), ("false".into(), vec![])]),
+ _ => None,
+ };
+ match ctors {
+ Some(cs) => cs.iter().all(|(name, payload)| {
+ let sub: Vec<Vec<Pattern>> = rows
+ .iter()
+ .filter_map(|row| {
+ let head = match &row[0] {
+ Pattern::Variant(n, subs, _) if n == name => subs.clone(),
+ Pattern::Bool(b) if b.to_string() == *name => vec![],
+ p if wild(p) => vec![Pattern::Wild; payload.len()],
+ _ => return None,
+ };
+ Some(head.into_iter().chain(row[1..].iter().cloned()).collect())
+ })
+ .collect();
+ let tys: Vec<Type> = payload.iter().cloned().chain(rest.iter().cloned()).collect();
+ self.covers(sub, &tys)
+ }),
+ None => {
+ let sub: Vec<Vec<Pattern>> = rows
+ .into_iter()
+ .filter(|row| wild(&row[0]))
+ .map(|row| row[1..].to_vec())
+ .collect();
+ self.covers(sub, rest)
+ }
+ }
}
fn match_expr(&mut self, scrut: &Expr, arms: &[Arm], dst: Dst, line: u32) -> Type {
@@ -1774,22 +2205,29 @@ impl<'p> Compiler<'p> {
}
self.f.scopes.push(Vec::new());
let arm_mark = self.f.next;
- let fails = self.pattern_test(&arm.pattern, s, &st, line);
- match &arm.pattern {
- Pattern::Wild | Pattern::Bind(_) => total = true,
- Pattern::Variant(n, binds, _) => {
- let tag = match n.as_str() {
- "Some" => Some(OPTION_SOME),
- "None" => Some(OPTION_NONE),
- _ => self.variants.get(n).map(|v| v.1),
- };
- // `Some(x)` covers Some; a nested pattern would not, but there are none yet.
- let _ = binds;
- if let Some(t) = tag {
- covered.push(t);
+ let mut fails = self.pattern_test(&arm.pattern, s, &st, line);
+ if let Some(g) = &arm.guard {
+ let c = self.cond(g);
+ fails.push(self.emit(Op::JumpIfFalse { cond: c, to: 0 }));
+ }
+ // What this arm covers for certain: nothing, when a guard may refuse it.
+ if arm.guard.is_none() {
+ match &arm.pattern {
+ p if Self::irrefutable(p) => total = true,
+ Pattern::Variant(n, subs, _) if subs.iter().all(Self::irrefutable) => {
+ let tag = match n.as_str() {
+ "Some" => Some(OPTION_SOME),
+ "None" => Some(OPTION_NONE),
+ "Ok" => Some(RESULT_OK),
+ "Err" => Some(RESULT_ERR),
+ _ => self.variants.get(n).map(|v| v.1),
+ };
+ if let Some(t) = tag {
+ covered.push(t);
+ }
}
+ _ => {}
}
- _ => {}
}
let want_owned = match dst {
Dst::To(_, w) => w.cloned().or_else(|| acc.clone().filter(|t| *t != Type::Never)),
@@ -1811,32 +2249,42 @@ impl<'p> Compiler<'p> {
self.f.scopes.pop();
self.f.next = arm_mark;
}
- let variants: Option<usize> = match &st {
- Type::Option(_) => Some(2),
- Type::Enum(e) => Some(self.enums[*e as usize].variants.len()),
+ let names: Option<Vec<String>> = match &st {
+ Type::Option(_) => Some(vec!["None".into(), "Some(_)".into()]),
+ Type::Result(..) => Some(vec!["Ok(_)".into(), "Err(_)".into()]),
+ Type::Enum(e) => Some(
+ self.enums[*e as usize]
+ .variants
+ .iter()
+ .map(|(n, _)| n.clone())
+ .collect(),
+ ),
_ => None,
};
- let exhaustive = total
- || variants.is_some_and(|n| (0..n as u32).all(|t| covered.contains(&t)))
- || st == Type::Error;
+ let rows: Vec<Vec<Pattern>> = arms
+ .iter()
+ .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));
if !exhaustive {
- let missing = match &st {
- Type::Option(_) => ["None", "Some(_)"]
- .iter()
- .enumerate()
- .filter(|(t, _)| !covered.contains(&(*t as u32)))
- .map(|(_, n)| n.to_string())
- .collect::<Vec<_>>(),
- Type::Enum(e) => self.enums[*e as usize]
- .variants
- .iter()
+ let missing: Vec<String> = match names {
+ Some(n) => n
+ .into_iter()
.enumerate()
.filter(|(t, _)| !covered.contains(&(*t as u32)))
- .map(|(_, (n, _))| n.clone())
+ .map(|(_, n)| n)
.collect(),
- _ => vec!["_".into()],
+ None => vec![],
};
- self.error(line, format!("this `match` misses: {}", missing.join(", ")));
+ if missing.is_empty() {
+ self.error(
+ line,
+ "this `match` misses some values: cover them, or add a `_ =>` arm",
+ );
+ } else {
+ self.error(line, format!("this `match` misses: {}", missing.join(", ")));
+ }
}
let k = self.string("no arm of the match fits");
let Value::Static(m) = self.out.consts[k as usize] else {
@@ -1854,4 +2302,887 @@ impl<'p> Compiler<'p> {
acc.unwrap_or(Type::Never)
}
}
+
+ // ── Function values ──
+
+ /// `fn(x: Int) -> Int { … }`. The closure copies every variable of the
+ /// enclosing function its body names, when it is made.
+ fn lambda(&mut self, lam: &Lambda, r: Reg, want: Option<&Type>, line: u32) -> Type {
+ let want_fn = match want {
+ Some(Type::Fn(f)) => Some(f.clone()),
+ _ => None,
+ };
+ let mut params = Vec::new();
+ for (i, (name, t)) in lam.params.iter().enumerate() {
+ let ty = match (t, want_fn.as_ref().and_then(|f| f.params.get(i))) {
+ (Some(t), _) => self.resolve(t),
+ (None, Some(t)) => t.clone(),
+ (None, None) => {
+ self.error(
+ line,
+ format!("the type of `{name}` is unknown here: write `{name}: Type`"),
+ );
+ Type::Error
+ }
+ };
+ params.push(ty);
+ }
+ let ret = match (&lam.ret, &want_fn) {
+ (Some(t), _) => Some(self.resolve(t)),
+ (None, Some(f)) if f.ret != Type::Error => Some(f.ret.clone()),
+ _ => None,
+ };
+ let effects = if !lam.effects.is_empty() {
+ for e in &lam.effects {
+ if !self.plat.effects.contains(e) {
+ self.error(line, format!("this platform has no effect `{e}`"));
+ }
+ }
+ lam.effects.clone()
+ } else {
+ want_fn.as_ref().map(|f| f.effects.clone()).unwrap_or_default()
+ };
+
+ // What it captures: every name its body uses that is a local here.
+ let mut names = Vec::new();
+ free_block(&lam.body, &mut names);
+ names.sort();
+ names.dedup();
+ let caps: Vec<(String, Reg, Type)> = names
+ .into_iter()
+ .filter_map(|n| self.lookup(&n).map(|l| (n, l.reg, l.ty.clone())))
+ .collect();
+
+ 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);
+ self.begin(
+ &format!("{outer_name}.<fn>"),
+ ret.clone().unwrap_or(Type::Error),
+ effects.clone(),
+ );
+ self.line = line;
+ let mut scope = Vec::new();
+ let first = self.alloc_n(params.len());
+ let cap_base = self.alloc_n(caps.len());
+ // Captures first, so a parameter of the same name hides one.
+ for (i, (n, _, t)) in caps.iter().enumerate() {
+ scope.push(Local {
+ name: n.clone(),
+ reg: cap_base + i as Reg,
+ ty: t.clone(),
+ mutable: false,
+ captured: true,
+ });
+ self.f.captures.push(cap_base + i as Reg);
+ }
+ for (i, ((n, _), t)) in lam.params.iter().zip(¶ms).enumerate() {
+ scope.push(Local {
+ name: n.clone(),
+ reg: first + i as Reg,
+ ty: t.clone(),
+ mutable: false,
+ captured: false,
+ });
+ }
+ self.f.scopes.push(scope);
+ let ret = match ret {
+ Some(Type::Unit) => {
+ self.block(&lam.body, Dst::Discard);
+ let u = self.alloc();
+ self.emit(Op::LoadUnit { dst: u });
+ self.emit(Op::Ret { src: u });
+ Type::Unit
+ }
+ Some(t) => {
+ let o = self.alloc();
+ let got = self.block(&lam.body, Dst::To(o, Some(&t)));
+ self.expect(&got, &t, line);
+ self.emit(Op::Ret { src: o });
+ t
+ }
+ None => {
+ let o = self.alloc();
+ let got = self.block(&lam.body, Dst::To(o, None));
+ self.emit(Op::Ret { src: o });
+ if got == Type::Never { Type::Unit } else { got }
+ }
+ };
+ self.finish(id, params.len() as u16);
+ self.f = outer;
+ let base = self.alloc_n(caps.len());
+ for (i, (_, src, _)) in caps.iter().enumerate() {
+ self.emit(Op::Move {
+ dst: base + i as Reg,
+ src: *src,
+ });
+ }
+ self.emit(Op::MakeClosure {
+ dst: r,
+ f: id,
+ base,
+ n: caps.len() as u16,
+ });
+ Type::Fn(Rc::new(FnType::new(params, ret, effects)))
+ }
+
+ fn check_effects(&mut self, effects: &[String], line: u32) {
+ for eff in effects {
+ if !self.f.effects.contains(eff) {
+ self.missing_effect(eff, line);
+ }
+ }
+ }
+
+ /// Call the function value in `fr`.
+ fn call_value(&mut self, fr: Reg, ft: &Type, args: &[&Expr], r: Reg, line: u32) -> Type {
+ let Type::Fn(f) = ft else {
+ if *ft != Type::Error {
+ let s = self.show(ft);
+ self.error(line, format!("{s} is not a function"));
+ }
+ return Type::Error;
+ };
+ let f = f.clone();
+ self.check_effects(&f.effects, line);
+ let base = self.args(None, args, &f.params, "this function", line);
+ self.emit(Op::CallValue { f: fr, base, dst: r });
+ f.ret.clone()
+ }
+
+ fn direct_call(
+ &mut self,
+ f: u32,
+ first: Option<(Reg, Type)>,
+ args: &[&Expr],
+ r: Reg,
+ n: &str,
+ line: u32,
+ ) -> Type {
+ let (params, ret, effects) = {
+ let s = &self.fns[f as usize];
+ (s.params.clone(), s.ret.clone(), s.effects.clone())
+ };
+ self.check_effects(&effects, line);
+ let base = self.args(first, args, ¶ms, &format!("`{n}`"), line);
+ self.emit(Op::Call { f, base, dst: r });
+ ret
+ }
+
+ /// A call of a generic function: its parameters' types are fixed by the
+ /// arguments, and it is compiled once for each set of them.
+ fn generic_call(
+ &mut self,
+ decl: &'a FnDecl,
+ first: Option<(Reg, Type)>,
+ args: &[&Expr],
+ r: Reg,
+ line: u32,
+ ) -> Type {
+ let saved = std::mem::take(&mut self.env.generics);
+ self.env.generics = decl
+ .generics
+ .iter()
+ .map(|g| (g.clone(), Type::Param(g.as_str().into())))
+ .collect();
+ let sig = self.signature(decl);
+ self.env.generics = saved;
+ let n = first.is_some() as usize + args.len();
+ if n != sig.params.len() {
+ self.error(
+ line,
+ format!("`{}` takes {} argument(s), not {n}", decl.name, sig.params.len()),
+ );
+ return Type::Error;
+ }
+ let base = self.alloc_n(n.max(1));
+ let mut bind = HashMap::new();
+ let mut i = 0;
+ if let Some((fr, ft)) = first {
+ self.emit(Op::Move { dst: base, src: fr });
+ if !sig.params[0].unify(&ft, &mut bind) {
+ let (w, g) = (self.show(&sig.params[0]), self.show(&ft));
+ self.error(line, format!("expected {w}, found {g}"));
+ }
+ i = 1;
+ }
+ for a in args {
+ let p = sig.params[i].clone();
+ let want = if p.has_param() { None } else { Some(p.clone()) };
+ let t = self.expr(a, Dst::To(base + i as Reg, want.as_ref()));
+ if !p.unify(&t, &mut bind) {
+ let (w, g) = (self.show(&p.subst(&bind)), self.show(&t));
+ self.error(a.line, format!("expected {w}, found {g}"));
+ }
+ i += 1;
+ }
+ for g in &decl.generics {
+ if !bind.contains_key(g) {
+ self.error(
+ line,
+ format!("what `{g}` is in this call of `{}` is unknown", decl.name),
+ );
+ bind.insert(g.clone(), Type::Error);
+ }
+ }
+ self.check_effects(&sig.effects, line);
+ let key = format!(
+ "{}<{}>",
+ decl.name,
+ decl.generics
+ .iter()
+ .map(|g| self.show(&bind[g]))
+ .collect::<Vec<_>>()
+ .join(",")
+ );
+ let id = match self.instance_ids.get(&key) {
+ Some(&id) => id,
+ None => {
+ let id = self.out.funcs.len() as u32;
+ self.out.funcs.push(Self::placeholder());
+ self.instance_ids.insert(key, id);
+ self.pending.push((decl, bind.clone(), id));
+ id
+ }
+ };
+ self.emit(Op::Call { f: id, base, dst: r });
+ sig.ret.subst(&bind)
+ }
+
+ /// `Some(v)`, `Ok(v)`, `Err(e)`.
+ fn wrap(&mut self, n: &str, args: &[Expr], r: Reg, want: Option<&Type>, line: u32) -> Type {
+ if args.len() != 1 {
+ self.error(line, format!("`{n}` takes one value"));
+ return Type::Error;
+ }
+ let (tag, inner_want) = match (n, want) {
+ ("Some", Some(Type::Option(t))) => (OPTION_SOME, Some((**t).clone())),
+ ("Some", _) => (OPTION_SOME, None),
+ ("Ok", Some(Type::Result(t, _))) => (RESULT_OK, Some((**t).clone())),
+ ("Err", Some(Type::Result(_, e))) => (RESULT_ERR, Some((**e).clone())),
+ _ => {
+ self.error(
+ line,
+ format!("the type of `{n}(…)` is unknown here: say what returns it, `-> Result<T, E>`"),
+ );
+ return Type::Error;
+ }
+ };
+ let base = self.alloc();
+ let t = self.expr(&args[0], Dst::To(base, inner_want.as_ref()));
+ if let Some(w) = &inner_want {
+ self.expect(&t, w, line);
+ }
+ self.emit(Op::MakeVariant {
+ dst: r,
+ tag,
+ base,
+ n: 1,
+ });
+ match n {
+ "Some" => Type::Option(Rc::new(inner_want.unwrap_or(t))),
+ _ => want.cloned().unwrap_or(Type::Error),
+ }
+ }
+
+ /// `e?`
+ fn try_expr(&mut self, e: &Expr, r: Reg, line: u32) -> Type {
+ let s = self.alloc();
+ let t = self.expr(e, Dst::To(s, None));
+ let ret = self.f.ret.clone();
+ let (fail_tag, inner) = match (&t, &ret) {
+ (Type::Result(v, er), Type::Result(_, er2)) => {
+ if !er.fits(er2) {
+ let (a, b) = (self.show(er), self.show(er2));
+ self.error(
+ line,
+ format!("`?` passes on an error of type {a}, but this function returns {b}"),
+ );
+ }
+ (RESULT_ERR, (**v).clone())
+ }
+ (Type::Option(v), Type::Option(_)) => (OPTION_NONE, (**v).clone()),
+ (Type::Error, _) => return Type::Error,
+ (Type::Result(..) | Type::Option(_), _) => {
+ let (a, b) = (self.show(&t), self.show(&ret));
+ self.error(
+ line,
+ format!("`?` on {a} needs a function that returns one too; this one returns {b}"),
+ );
+ return Type::Error;
+ }
+ _ => {
+ let a = self.show(&t);
+ self.error(line, format!("`?` takes a Result or an Option, not {a}"));
+ return Type::Error;
+ }
+ };
+ let k = self.konst(Value::Int(fail_tag as i64));
+ let (tr, kr, c) = (self.alloc(), self.alloc(), self.alloc());
+ self.emit(Op::GetTag { dst: tr, src: s });
+ self.emit(Op::LoadK { dst: kr, k });
+ self.emit(Op::EqI { dst: c, a: tr, b: kr });
+ let skip = self.emit(Op::JumpIfFalse { cond: c, to: 0 });
+ // The Err or None is a valid value of the function's own return type.
+ self.emit(Op::Ret { src: s });
+ let ok = self.here();
+ self.patch(skip, ok);
+ self.emit(Op::GetPayload {
+ dst: r,
+ src: s,
+ idx: 0,
+ });
+ inner
+ }
+
+ fn tuple(&mut self, items: &[Expr], r: Reg, want: Option<&Type>) -> Type {
+ let wants: Option<Rc<[Type]>> = match want {
+ Some(Type::Tuple(ts)) if ts.len() == items.len() => Some(ts.clone()),
+ _ => None,
+ };
+ let base = self.alloc_n(items.len());
+ let mut tys = Vec::new();
+ for (i, e) in items.iter().enumerate() {
+ let w = wants.as_ref().map(|ts| ts[i].clone());
+ let t = self.expr(e, Dst::To(base + i as Reg, w.as_ref()));
+ tys.push(t);
+ }
+ self.emit(Op::MakeRecord {
+ dst: r,
+ base,
+ n: items.len() as u16,
+ });
+ Type::Tuple(tys.into())
+ }
+
+ fn map_lit(&mut self, entries: &[(Expr, Expr)], r: Reg, want: Option<&Type>, line: u32) -> Type {
+ let (mut kt, mut vt) = match want {
+ Some(Type::Map(k, v)) => (Some((**k).clone()), Some((**v).clone())),
+ _ => (None, None),
+ };
+ if entries.is_empty() && kt.is_none() {
+ self.error(
+ line,
+ "the type of an empty map is unknown here: write `let m: Map<Str, Int> = [:]`",
+ );
+ return Type::Error;
+ }
+ self.emit(Op::Std {
+ f: Std::MapNew,
+ base: r,
+ dst: r,
+ });
+ for (k, v) in entries {
+ let base = self.alloc_n(3);
+ self.emit(Op::Move { dst: base, src: r });
+ let t = self.expr(k, Dst::To(base + 1, kt.as_ref()));
+ match &kt {
+ Some(w) => self.expect(&t, w, k.line),
+ None => {
+ if !matches!(t, Type::Int | Type::Str | Type::Error) {
+ self.error(k.line, "a Map's keys are Int or Str");
+ }
+ kt = Some(t)
+ }
+ }
+ let t = self.expr(v, Dst::To(base + 2, vt.as_ref()));
+ match &vt {
+ Some(w) => self.expect(&t, w, v.line),
+ None => vt = Some(t),
+ }
+ self.emit(Op::Std {
+ f: Std::MapWith,
+ base,
+ dst: r,
+ });
+ self.f.next = base;
+ }
+ Type::Map(Rc::new(kt.unwrap()), Rc::new(vt.unwrap()))
+ }
+
+ // ── Methods ──
+
+ fn is_place(&self, e: &Expr) -> bool {
+ match &e.kind {
+ ExprKind::Ident(n) => self.lookup(n).is_some() || self.global_index.contains_key(n),
+ ExprKind::Field(b, _) => self.is_place(b),
+ _ => false,
+ }
+ }
+
+ /// A built-in method into `r`: `recv` is in `rr`, the arguments compiled
+ /// against `wants`.
+ #[allow(clippy::too_many_arguments)]
+ fn std_call(&mut self, f: Std, rr: Reg, args: &[&Expr], wants: &[Type], r: Reg, what: &str, line: u32) {
+ if args.len() != wants.len() {
+ self.error(
+ line,
+ format!("`{what}` takes {} argument(s), not {}", wants.len(), args.len()),
+ );
+ }
+ let base = self.alloc_n(1 + wants.len());
+ self.emit(Op::Move { dst: base, src: rr });
+ for (i, (a, w)) in args.iter().zip(wants).enumerate() {
+ let t = self.expr(a, Dst::To(base + 1 + i as Reg, Some(w)));
+ self.expect(&t, w, a.line);
+ }
+ self.emit(Op::Std { f, base, dst: r });
+ }
+
+ fn method(
+ &mut self,
+ recv: &Expr,
+ name: &str,
+ args: &[&Expr],
+ r: Reg,
+ want: Option<&Type>,
+ line: u32,
+ ) -> Type {
+ if matches!(name, "push" | "remove_at" | "set" | "remove") && self.is_place(recv) {
+ return self.mutate(recv, name, args, r, line);
+ }
+ let (rr, rt) = self.expr_any(recv, None);
+ // A record field holding a function: `rules.score(3)`.
+ if let Some((idx, ft @ Type::Fn(_))) = rt.field(name).map(|(i, t)| (i, t.clone())) {
+ let fr = self.alloc();
+ self.emit(Op::GetField {
+ dst: fr,
+ src: rr,
+ idx: idx as u16,
+ });
+ return self.call_value(fr, &ft, args, r, line);
+ }
+ let arity0 = |c: &mut Self| {
+ if !args.is_empty() {
+ c.error(line, format!("`{name}` takes no arguments"));
+ }
+ };
+ use Std::*;
+ let t = match (&rt, name) {
+ (Type::Error, _) => return Type::Error,
+ (Type::List(_), "len") | (Type::Str, "len") | (Type::Map(..), "len") => {
+ arity0(self);
+ self.len_of(rr, &rt, r);
+ Type::Int
+ }
+ (Type::List(_) | Type::Str | Type::Map(..), "is_empty") => {
+ arity0(self);
+ let n = self.alloc();
+ self.len_of(rr, &rt, n);
+ let k = self.konst(Value::Int(0));
+ let z = self.alloc();
+ self.emit(Op::LoadK { dst: z, k });
+ self.emit(Op::EqI { dst: r, a: n, b: z });
+ Type::Bool
+ }
+ (Type::List(e), _) => {
+ let e = (**e).clone();
+ let opt = |t: Type| Type::Option(Rc::new(t));
+ match name {
+ "get" => {
+ self.std_call(ListGet, rr, args, &[Type::Int], r, name, line);
+ opt(e)
+ }
+ "first" | "last" => {
+ self.std_call(
+ if name == "first" { ListFirst } else { ListLast },
+ rr,
+ args,
+ &[],
+ r,
+ name,
+ line,
+ );
+ opt(e)
+ }
+ "contains" | "index_of" => {
+ if !e.has_eq() && !self.plain_enum(&e) {
+ let s = self.show(&e);
+ self.error(
+ line,
+ format!("`{name}` compares items with `==`, which {s} does not have"),
+ );
+ }
+ let f = if name == "contains" {
+ ListContains
+ } else {
+ ListIndexOf
+ };
+ self.std_call(f, rr, args, std::slice::from_ref(&e), r, name, line);
+ if name == "contains" {
+ Type::Bool
+ } else {
+ opt(Type::Int)
+ }
+ }
+ "slice" => {
+ self.std_call(ListSlice, rr, args, &[Type::Int, Type::Int], r, name, line);
+ rt.clone()
+ }
+ "join" => {
+ if e != Type::Str {
+ self.error(line, "`join` takes a List<Str>");
+ }
+ self.std_call(ListJoin, rr, args, &[Type::Str], r, name, line);
+ Type::Str
+ }
+ "sort" => {
+ if !matches!(e, Type::Int | Type::Float | Type::Str) {
+ let s = self.show(&e);
+ self.error(line, format!("`sort` orders Int, Float or Str, not {s}"));
+ }
+ self.std_call(ListSort, rr, args, &[], r, name, line);
+ rt.clone()
+ }
+ "reversed" => {
+ self.std_call(ListReversed, rr, args, &[], r, name, line);
+ rt.clone()
+ }
+ "map" | "filter" | "any" | "all" | "find" | "count" => {
+ if args.len() != 1 {
+ self.error(line, format!("`{name}` takes one function"));
+ return Type::Error;
+ }
+ self.list_loop(name, rr, &e, args[0], r, line)
+ }
+ _ => return self.ufcs(rr, rt.clone(), name, args, r, line),
+ }
+ }
+ (Type::Str, _) => {
+ let (f, wants, ret): (Std, Vec<Type>, Type) = match name {
+ "contains" => (StrContains, vec![Type::Str], Type::Bool),
+ "starts_with" => (StrStartsWith, vec![Type::Str], Type::Bool),
+ "ends_with" => (StrEndsWith, vec![Type::Str], Type::Bool),
+ "upper" => (StrUpper, vec![], Type::Str),
+ "lower" => (StrLower, vec![], Type::Str),
+ "trim" => (StrTrim, vec![], Type::Str),
+ "split" => (StrSplit, vec![Type::Str], Type::List(Rc::new(Type::Str))),
+ "replace" => (StrReplace, vec![Type::Str, Type::Str], Type::Str),
+ "slice" => (StrSlice, vec![Type::Int, Type::Int], Type::Str),
+ "index_of" => (StrIndexOf, vec![Type::Str], Type::Option(Rc::new(Type::Int))),
+ "parse_int" => (StrParseInt, vec![], Type::Option(Rc::new(Type::Int))),
+ "parse_float" => (StrParseFloat, vec![], Type::Option(Rc::new(Type::Float))),
+ "repeat" => (StrRepeat, vec![Type::Int], Type::Str),
+ _ => return self.ufcs(rr, rt.clone(), name, args, r, line),
+ };
+ self.std_call(f, rr, args, &wants, r, name, line);
+ ret
+ }
+ (Type::Map(k, v), _) => {
+ let (k, v) = ((**k).clone(), (**v).clone());
+ match name {
+ "get" => {
+ self.std_call(MapGet, rr, args, &[k], r, name, line);
+ Type::Option(Rc::new(v))
+ }
+ "has" => {
+ self.std_call(MapHas, rr, args, &[k], r, name, line);
+ Type::Bool
+ }
+ "keys" => {
+ self.std_call(MapKeys, rr, args, &[], r, name, line);
+ Type::List(Rc::new(k))
+ }
+ "values" => {
+ self.std_call(MapValues, rr, args, &[], r, name, line);
+ Type::List(Rc::new(v))
+ }
+ _ => return self.ufcs(rr, rt.clone(), name, args, r, line),
+ }
+ }
+ (t, _) if t.is_vec3() => {
+ let vt = t.clone();
+ let (f, wants, ret): (Std, Vec<Type>, Type) = match name {
+ "length" => (VecLength, vec![], Type::Float),
+ "normalize" => (VecNormalize, vec![], vt.clone()),
+ "dot" => (VecDot, vec![vt.clone()], Type::Float),
+ "cross" => (VecCross, vec![vt.clone()], vt.clone()),
+ "distance" => (VecDistance, vec![vt.clone()], Type::Float),
+ "lerp" => (VecLerp, vec![vt.clone(), Type::Float], vt.clone()),
+ _ => return self.ufcs(rr, rt.clone(), name, args, r, line),
+ };
+ self.std_call(f, rr, args, &wants, r, name, line);
+ ret
+ }
+ _ => return self.ufcs(rr, rt.clone(), name, args, r, line),
+ };
+ let _ = want;
+ t
+ }
+
+ fn plain_enum(&self, t: &Type) -> bool {
+ matches!(t, Type::Enum(e) if self.enums[*e as usize].variants.iter().all(|v| v.1.is_empty()))
+ }
+
+ fn len_of(&mut self, rr: Reg, t: &Type, r: Reg) {
+ match t {
+ Type::Str => self.emit(Op::StrLen { dst: r, src: rr }),
+ Type::Map(..) => {
+ let base = self.alloc();
+ self.emit(Op::Move { dst: base, src: rr });
+ self.emit(Op::Std {
+ f: Std::MapLen,
+ base,
+ dst: r,
+ })
+ }
+ _ => self.emit(Op::Len { dst: r, src: rr }),
+ };
+ }
+
+ /// `x.f(a)` for a script function `f` whose first parameter takes `x`.
+ fn ufcs(&mut self, rr: Reg, rt: Type, name: &str, args: &[&Expr], r: Reg, line: u32) -> Type {
+ if let Some(&f) = self.fn_index.get(name) {
+ return self.direct_call(f, Some((rr, rt)), args, r, name, line);
+ }
+ if let Some(&decl) = self.generic_fns.get(name) {
+ return self.generic_call(decl, Some((rr, rt)), args, r, line);
+ }
+ let s = self.show(&rt);
+ self.error(
+ line,
+ format!("{s} has no method `{name}`, and there is no function `{name}`"),
+ );
+ Type::Error
+ }
+
+ /// `xs.push(v)`, `xs.remove_at(i)`, `m.set(k, v)`, `m.remove(k)`: these
+ /// change the variable they are called on.
+ fn mutate(&mut self, recv: &Expr, name: &str, args: &[&Expr], r: Reg, line: u32) -> Type {
+ let name = name.to_string();
+ self.store(recv, line, &mut |c: &mut Self, cur, cur_ty, dst| {
+ let (f, wants): (Std, Vec<Type>) = match (name.as_str(), cur_ty) {
+ ("push", Type::List(e)) => (Std::ListPushed, vec![(**e).clone()]),
+ ("remove_at", Type::List(_)) => (Std::ListRemoved, vec![Type::Int]),
+ ("set", Type::Map(k, v)) => (Std::MapWith, vec![(**k).clone(), (**v).clone()]),
+ ("remove", Type::Map(k, _)) => (Std::MapWithout, vec![(**k).clone()]),
+ (_, Type::Error) => return Type::Error,
+ _ => {
+ let s = c.show(cur_ty);
+ c.error(line, format!("{s} has no method `{name}`"));
+ return Type::Error;
+ }
+ };
+ c.std_call(f, cur, args, &wants, dst, &name, line);
+ cur_ty.clone()
+ });
+ self.emit(Op::LoadUnit { dst: r });
+ Type::Unit
+ }
+
+ /// `map`, `filter`, `any`, `all`, `find`, `count`: loops in the script's own
+ /// code, so the function they call is counted and can pause like any other.
+ fn list_loop(&mut self, kind: &str, rr: Reg, elem: &Type, fe: &Expr, r: Reg, line: u32) -> Type {
+ let want_ret = if kind == "map" { Type::Error } else { Type::Bool };
+ let want = Type::Fn(Rc::new(FnType {
+ params: vec![elem.clone()],
+ ret: want_ret,
+ effects: self.f.effects.clone(),
+ }));
+ let (fr, ft) = self.expr_any(fe, Some(&want));
+ let Type::Fn(f) = &ft else {
+ if ft != Type::Error {
+ let s = self.show(&ft);
+ self.error(line, format!("`{kind}` takes a function, not {s}"));
+ }
+ return Type::Error;
+ };
+ let f = f.clone();
+ if f.params.len() != 1 || !elem.fits(&f.params[0]) {
+ let (e, s) = (self.show(elem), self.show(&ft));
+ self.error(
+ line,
+ format!("`{kind}` calls its function with one {e}; this one is {s}"),
+ );
+ }
+ if kind != "map" && !f.ret.fits(&Type::Bool) {
+ self.error(line, format!("`{kind}`'s function answers a Bool"));
+ }
+ self.check_effects(&f.effects, line);
+ let (n, i, one) = (self.alloc(), self.alloc(), self.alloc());
+ self.emit(Op::Len { dst: n, src: rr });
+ let k0 = self.konst(Value::Int(0));
+ let k1 = self.konst(Value::Int(1));
+ self.emit(Op::LoadK { dst: i, k: k0 });
+ self.emit(Op::LoadK { dst: one, k: k1 });
+ match kind {
+ "map" | "filter" => self.emit(Op::MakeList {
+ dst: r,
+ base: r,
+ n: 0,
+ }),
+ "any" => self.emit(Op::LoadBool { dst: r, v: false }),
+ "all" => self.emit(Op::LoadBool { dst: r, v: true }),
+ "count" => self.emit(Op::LoadK { dst: r, k: k0 }),
+ _ => self.emit(Op::LoadTag {
+ dst: r,
+ tag: OPTION_NONE,
+ }),
+ };
+ let c = self.alloc();
+ let start = self.here();
+ self.emit(Op::LtI { dst: c, a: i, b: n });
+ let exit = self.emit(Op::JumpIfFalse { cond: c, to: 0 });
+ let v = self.alloc();
+ self.emit(Op::ListGet {
+ dst: v,
+ list: rr,
+ idx: i,
+ });
+ let res = self.alloc();
+ let arg = self.alloc();
+ self.emit(Op::Move { dst: arg, src: v });
+ self.emit(Op::CallValue {
+ f: fr,
+ base: arg,
+ dst: res,
+ });
+ let mut done = Vec::new();
+ match kind {
+ "map" => {
+ self.emit(Op::ListPushMut { list: r, val: res });
+ }
+ "filter" => {
+ let skip = self.emit(Op::JumpIfFalse { cond: res, to: 0 });
+ self.emit(Op::ListPushMut { list: r, val: v });
+ let next = self.here();
+ self.patch(skip, next);
+ }
+ "count" => {
+ let skip = self.emit(Op::JumpIfFalse { cond: res, to: 0 });
+ self.emit(Op::AddI { dst: r, a: r, b: one });
+ let next = self.here();
+ self.patch(skip, next);
+ }
+ "any" | "find" => {
+ let skip = self.emit(Op::JumpIfFalse { cond: res, to: 0 });
+ if kind == "any" {
+ self.emit(Op::LoadBool { dst: r, v: true });
+ } else {
+ self.emit(Op::MakeVariant {
+ dst: r,
+ tag: OPTION_SOME,
+ base: v,
+ n: 1,
+ });
+ }
+ done.push(self.emit(Op::Jump { to: 0 }));
+ let next = self.here();
+ self.patch(skip, next);
+ }
+ _ => {
+ let skip = self.emit(Op::JumpIfTrue { cond: res, to: 0 });
+ self.emit(Op::LoadBool { dst: r, v: false });
+ done.push(self.emit(Op::Jump { to: 0 }));
+ let next = self.here();
+ self.patch(skip, next);
+ }
+ }
+ self.emit(Op::AddI { dst: i, a: i, b: one });
+ self.emit(Op::Jump { to: start });
+ let end = self.here();
+ self.patch(exit, end);
+ for d in done {
+ self.patch(d, end);
+ }
+ match kind {
+ "map" => Type::List(Rc::new(f.ret.clone())),
+ "filter" => Type::List(Rc::new(elem.clone())),
+ "count" => Type::Int,
+ "find" => Type::Option(Rc::new(elem.clone())),
+ _ => Type::Bool,
+ }
+ }
+}
+
+/// Every name a block mentions, to find what a closure must capture. It may
+/// include names the block declares itself; capturing those costs a copy only.
+fn free_block(b: &Block, out: &mut Vec<String>) {
+ for s in &b.stmts {
+ match s {
+ Stmt::Let { value, .. } | Stmt::LetPat { value, .. } => free_expr(value, out),
+ Stmt::Assign { target, value, .. } => {
+ free_expr(target, out);
+ free_expr(value, out);
+ }
+ Stmt::Expr(e) => free_expr(e, out),
+ Stmt::While { cond, body, .. } => {
+ free_expr(cond, out);
+ free_block(body, out);
+ }
+ Stmt::For { iter, body, .. } => {
+ match iter {
+ ForIter::Range(a, b) => {
+ free_expr(a, out);
+ free_expr(b, out);
+ }
+ ForIter::List(e) => free_expr(e, out),
+ }
+ free_block(body, out);
+ }
+ Stmt::Return(Some(e), _) => free_expr(e, out),
+ _ => {}
+ }
+ }
+ if let Some(t) = &b.tail {
+ free_expr(t, out);
+ }
+}
+
+fn free_expr(e: &Expr, out: &mut Vec<String>) {
+ match &e.kind {
+ ExprKind::Ident(n) => out.push(n.clone()),
+ ExprKind::Field(b, _) | ExprKind::Unary(_, b) | ExprKind::Try(b) => free_expr(b, out),
+ ExprKind::Call(c, args) => {
+ free_expr(c, out);
+ args.iter().for_each(|a| free_expr(a, out));
+ }
+ ExprKind::Index(a, b) | ExprKind::Binary(_, a, b) => {
+ free_expr(a, out);
+ free_expr(b, out);
+ }
+ ExprKind::If(c, then, els) => {
+ free_expr(c, out);
+ free_block(then, out);
+ if let Some(e) = els {
+ free_expr(e, out);
+ }
+ }
+ ExprKind::IfLet(_, v, then, els) => {
+ free_expr(v, out);
+ free_block(then, out);
+ if let Some(e) = els {
+ free_expr(e, out);
+ }
+ }
+ ExprKind::Match(s, arms) => {
+ free_expr(s, out);
+ for a in arms {
+ if let Some(g) = &a.guard {
+ free_expr(g, out);
+ }
+ free_expr(&a.body, out);
+ }
+ }
+ ExprKind::Block(b) => free_block(b, out),
+ ExprKind::Record(fields, spread) => {
+ fields.iter().for_each(|(_, e)| free_expr(e, out));
+ if let Some(s) = spread {
+ free_expr(s, out);
+ }
+ }
+ ExprKind::List(items) | ExprKind::Tuple(items) => items.iter().for_each(|e| free_expr(e, out)),
+ ExprKind::MapLit(entries) => entries.iter().for_each(|(k, v)| {
+ free_expr(k, out);
+ free_expr(v, out);
+ }),
+ ExprKind::Lambda(l) => free_block(&l.body, out),
+ ExprKind::Template(parts) => parts.iter().for_each(|p| {
+ if let TPart::Hole(e, _) = p {
+ free_expr(e, out);
+ }
+ }),
+ ExprKind::Int(_) | ExprKind::Float(_) | ExprKind::Bool(_) | ExprKind::Str(_) => {}
+ }
}
diff --git a/crates/frits/src/lexer.rs b/crates/frits/src/lexer.rs
index 5c05747..fd47a3f 100644
--- a/crates/frits/src/lexer.rs
+++ b/crates/frits/src/lexer.rs
@@ -59,9 +59,9 @@ pub struct Token {
pub line: u32,
}
-const SYMS: [&str; 32] = [
+const SYMS: [&str; 33] = [
"..", "=>", "->", "==", "!=", "<=", ">=", "&&", "||", "+=", "-=", "*=", "/=", "(", ")", "{", "}", "[",
- "]", ",", ".", ":", "=", "<", ">", "+", "-", "*", "/", "%", "!", "_",
+ "]", ",", ".", ":", "=", "<", ">", "+", "-", "*", "/", "%", "!", "_", "?",
];
fn keyword(s: &str) -> Option<Kw> {
@@ -228,8 +228,25 @@ pub fn lex(src: &str, first_line: u32) -> Result<Vec<Token>, Error> {
b'{' => nest += 1,
b'}' => nest -= 1,
b'\n' => line += 1,
+ // A string inside the hole, `{xs.join(", ")}`: skip it whole,
+ // braces and all.
b'"' => {
- return Err(Error::new(line, "a string inside `{…}` is not supported"));
+ i += 1;
+ while i < b.len() && b[i] != b'"' {
+ if b[i] == b'\\' {
+ i += 1;
+ }
+ if b.get(i) == Some(&b'\n') {
+ line += 1;
+ }
+ i += 1;
+ }
+ if i >= b.len() {
+ return Err(Error::new(
+ hole_line,
+ "a string inside `{…}` is never closed",
+ ));
+ }
}
_ => {}
}
diff --git a/crates/frits/src/lib.rs b/crates/frits/src/lib.rs
index 9aa59e3..537c6bd 100644
--- a/crates/frits/src/lib.rs
+++ b/crates/frits/src/lib.rs
@@ -14,6 +14,7 @@ pub mod parser;
pub mod platform;
pub mod prelude;
pub mod runtime;
+pub mod stdlib;
pub mod types;
pub mod value;
pub mod vm;
@@ -22,9 +23,9 @@ pub mod vm;
mod tests;
pub use platform::{Cx, HostFn, Platform};
-pub use runtime::{Limits, Pid, Runtime};
+pub use runtime::{Limits, Pid, Runtime, TestResult};
pub use value::{HostValue, Value};
-pub use vm::{Outcome, Process, Status};
+pub use vm::{Level, LogLine, Outcome, Process, Status};
/// A mistake in a script, with the line it is on.
#[derive(Clone, Debug, PartialEq)]
diff --git a/crates/frits/src/main.rs b/crates/frits/src/main.rs
index 3d01be7..0d9a9fe 100644
--- a/crates/frits/src/main.rs
+++ b/crates/frits/src/main.rs
@@ -1,6 +1,7 @@
-//! `frits run <file>`: run a script on the console platform.
+//! `frits run <file>` runs a script on the console platform; `frits test
+//! <file>` runs its `test` blocks.
-use frits::{Cx, Platform, Runtime, Status, Value};
+use frits::{Cx, Level, Platform, Runtime, Status, Value};
const CONSOLE: &str = "
effect Console {
@@ -20,8 +21,8 @@ fn console() -> Platform<()> {
fn main() {
let args: Vec<String> = std::env::args().collect();
- let (Some("run"), Some(path)) = (args.get(1).map(|s| s.as_str()), args.get(2)) else {
- eprintln!("usage: frits run <file.frits>");
+ let (Some(cmd @ ("run" | "test")), Some(path)) = (args.get(1).map(|s| s.as_str()), args.get(2)) else {
+ eprintln!("usage: frits run <file.frits>\n frits test <file.frits>");
std::process::exit(2);
};
let src = std::fs::read_to_string(path).unwrap_or_else(|e| {
@@ -38,10 +39,29 @@ fn main() {
std::process::exit(1);
}
};
+ if cmd == "test" {
+ let results = rt.test(&module, || (), 10_000_000);
+ let failed = results.iter().filter(|r| r.failure.is_some()).count();
+ for r in &results {
+ match &r.failure {
+ None => println!("ok {}", r.name),
+ Some(m) => println!("FAIL {}: {m}", r.name),
+ }
+ }
+ println!("{} passed, {failed} failed", results.len() - failed);
+ std::process::exit(i32::from(failed > 0));
+ }
let pid = rt.spawn(module, ());
rt.post(pid, "main", Vec::new());
loop {
- if let Some((_, msg)) = rt.tick().into_iter().next() {
+ let died = rt.tick();
+ if let Some(p) = rt.get_mut(pid) {
+ for l in p.take_log() {
+ let tag = if l.level == Level::Warn { "warn" } else { "log" };
+ eprintln!("{path}:{}: {tag}: {}", l.line, l.text);
+ }
+ }
+ if let Some((_, msg)) = died.into_iter().next() {
eprintln!("{path}: {msg}");
std::process::exit(1);
}
diff --git a/crates/frits/src/parser.rs b/crates/frits/src/parser.rs
index 823895b..e6f0934 100644
--- a/crates/frits/src/parser.rs
+++ b/crates/frits/src/parser.rs
@@ -100,6 +100,9 @@ impl Parser {
}
Tok::Eof => Ok(()),
Tok::Sym("}") => Ok(()),
+ // A line ending in a token the lexer cannot tell ends a statement,
+ // such as the `>` of `Option<Int>`: the next line starts a new one.
+ _ if self.pos > 0 && self.toks[self.pos - 1].line < self.line() => Ok(()),
t => self.err(format!(
"expected the end of the statement, found {}",
describe(t)
@@ -144,23 +147,30 @@ impl Parser {
let ty = self.type_expr()?;
m.items.push(Item::Type(name, ty, line));
}
- Tok::Kw(k @ (Kw::Let | Kw::Var)) => {
+ Tok::Ident(w) if w == "test" && matches!(self.peek_at(1), Tok::Str(_)) => {
self.next();
- let name = self.ident()?;
- let ty = if self.eat_sym(":") {
- Some(self.type_expr()?)
- } else {
- None
+ let Tok::Str(parts) = self.next() else {
+ unreachable!()
};
- self.expect_sym("=")?;
- let value = self.expr()?;
- m.items.push(Item::Global(Global {
- mutable: k == Kw::Var,
- name,
- ty,
- value,
- line,
- }));
+ let name = match parts.as_slice() {
+ [StrPart::Lit(s)] => s.clone(),
+ _ => return self.err("a test's name is a plain string"),
+ };
+ let body = self.block()?;
+ m.items.push(Item::Test(name, body, line));
+ }
+ Tok::Ident(w) if w == "keep" && matches!(self.peek_at(1), Tok::Kw(Kw::Var | Kw::Let)) => {
+ self.next();
+ if self.eat_kw(Kw::Let) {
+ return self.err("only a `var` can be kept: write `keep var`");
+ }
+ self.next();
+ m.items.push(Item::Global(self.global(true, true, line)?));
+ }
+ Tok::Kw(k @ (Kw::Let | Kw::Var)) => {
+ self.next();
+ m.items
+ .push(Item::Global(self.global(k == Kw::Var, false, line)?));
}
Tok::Kw(k @ (Kw::Effect | Kw::Module)) => {
self.next();
@@ -178,6 +188,25 @@ impl Parser {
Ok(m)
}
+ fn global(&mut self, mutable: bool, keep: bool, line: u32) -> R<Global> {
+ let name = self.ident()?;
+ let ty = if self.eat_sym(":") {
+ Some(self.type_expr()?)
+ } else {
+ None
+ };
+ self.expect_sym("=")?;
+ let value = self.expr()?;
+ Ok(Global {
+ mutable,
+ keep,
+ name,
+ ty,
+ value,
+ line,
+ })
+ }
+
fn name_list(&mut self) -> R<Vec<Name>> {
let mut v = vec![self.ident()?];
while self.eat_sym(",") {
@@ -189,6 +218,11 @@ impl Parser {
fn fn_decl(&mut self, body: bool) -> R<FnDecl> {
let line = self.line();
let name = self.ident()?;
+ let mut generics = Vec::new();
+ if self.eat_sym("<") {
+ generics = self.name_list()?;
+ self.expect_sym(">")?;
+ }
self.expect_sym("(")?;
let mut params = Vec::new();
while !self.is_sym(")") {
@@ -213,6 +247,7 @@ impl Parser {
let body = if body { Some(self.block()?) } else { None };
Ok(FnDecl {
name,
+ generics,
params,
ret,
effects,
@@ -283,6 +318,42 @@ impl Parser {
fn type_expr(&mut self) -> R<TypeExpr> {
let line = self.line();
+ if self.eat_sym("(") {
+ let mut items = Vec::new();
+ while !self.is_sym(")") {
+ items.push(self.type_expr()?);
+ if !self.eat_sym(",") {
+ break;
+ }
+ }
+ self.expect_sym(")")?;
+ if items.len() == 1 {
+ return Ok(items.pop().unwrap());
+ }
+ return Ok(TypeExpr::Tuple(items, line));
+ }
+ if self.eat_kw(Kw::Fn) {
+ self.expect_sym("(")?;
+ let mut params = Vec::new();
+ while !self.is_sym(")") {
+ params.push(self.type_expr()?);
+ if !self.eat_sym(",") {
+ break;
+ }
+ }
+ self.expect_sym(")")?;
+ let ret = if self.eat_sym("->") {
+ Some(Box::new(self.type_expr()?))
+ } else {
+ None
+ };
+ let effects = if self.eat_sym("/") {
+ self.name_list()?
+ } else {
+ Vec::new()
+ };
+ return Ok(TypeExpr::Fn(params, ret, effects, line));
+ }
if self.eat_sym("{") {
let mut fields = Vec::new();
loop {
@@ -346,6 +417,13 @@ impl Parser {
fn stmt(&mut self) -> R<Stmt> {
let line = self.line();
+ if self.is_kw(Kw::Let) && matches!(self.peek_at(1), Tok::Sym("(") | Tok::Sym("{")) {
+ self.next();
+ let pattern = self.pattern()?;
+ self.expect_sym("=")?;
+ let value = self.expr()?;
+ return Ok(Stmt::LetPat { pattern, value, line });
+ }
match self.peek().clone() {
Tok::Kw(k @ (Kw::Let | Kw::Var)) => {
self.next();
@@ -517,8 +595,19 @@ impl Parser {
kind: ExprKind::Call(Box::new(e), args),
line,
};
+ } else if self.eat_sym("?") {
+ e = Expr {
+ kind: ExprKind::Try(Box::new(e)),
+ line,
+ };
} else if self.eat_sym(".") {
- let f = self.ident()?;
+ let f = match self.peek().clone() {
+ Tok::Int(i) => {
+ self.next();
+ i.to_string()
+ }
+ _ => self.ident()?,
+ };
e = Expr {
kind: ExprKind::Field(Box::new(e), f),
line,
@@ -558,19 +647,86 @@ impl Parser {
Tok::Ident(n) => ExprKind::Ident(n),
Tok::Sym("(") => {
let e = self.expr()?;
+ if self.eat_sym(")") {
+ return Ok(e);
+ }
+ let mut items = vec![e];
+ while self.eat_sym(",") {
+ if self.is_sym(")") {
+ break;
+ }
+ items.push(self.expr()?);
+ }
self.expect_sym(")")?;
- return Ok(e);
+ ExprKind::Tuple(items)
}
Tok::Sym("[") => {
+ self.skip_semis();
+ if self.eat_sym(":") {
+ self.expect_sym("]")?;
+ return Ok(Expr {
+ kind: ExprKind::MapLit(Vec::new()),
+ line,
+ });
+ }
let mut items = Vec::new();
+ let mut entries = Vec::new();
while !self.is_sym("]") {
- items.push(self.expr()?);
+ let e = self.expr()?;
+ // `[k: v, …]` is a map; the first entry decides.
+ if (items.is_empty() && entries.is_empty() && self.is_sym(":")) || !entries.is_empty() {
+ self.expect_sym(":")?;
+ entries.push((e, self.expr()?));
+ } else {
+ items.push(e);
+ }
+ self.skip_semis();
if !self.eat_sym(",") {
break;
}
+ self.skip_semis();
}
+ self.skip_semis();
self.expect_sym("]")?;
- ExprKind::List(items)
+ if entries.is_empty() {
+ ExprKind::List(items)
+ } else {
+ ExprKind::MapLit(entries)
+ }
+ }
+ Tok::Kw(Kw::Fn) => {
+ self.expect_sym("(")?;
+ let mut params = Vec::new();
+ while !self.is_sym(")") {
+ let p = self.ident()?;
+ let t = if self.eat_sym(":") {
+ Some(self.type_expr()?)
+ } else {
+ None
+ };
+ params.push((p, t));
+ if !self.eat_sym(",") {
+ break;
+ }
+ }
+ self.expect_sym(")")?;
+ let ret = if self.eat_sym("->") {
+ Some(self.type_expr()?)
+ } else {
+ None
+ };
+ let effects = if self.eat_sym("/") {
+ self.name_list()?
+ } else {
+ Vec::new()
+ };
+ let body = self.block()?;
+ ExprKind::Lambda(Box::new(Lambda {
+ params,
+ ret,
+ effects,
+ body,
+ }))
}
Tok::Sym("{") => {
self.pos -= 1;
@@ -590,9 +746,14 @@ impl Parser {
break;
}
let pattern = self.pattern()?;
+ let guard = if self.eat_kw(Kw::If) {
+ Some(self.expr()?)
+ } else {
+ None
+ };
self.expect_sym("=>")?;
let body = self.expr()?;
- arms.push(Arm { pattern, body });
+ arms.push(Arm { pattern, guard, body });
self.eat_sym(",");
}
ExprKind::Match(Box::new(scrut), arms)
@@ -687,21 +848,56 @@ impl Parser {
_ => return self.err("a pattern string cannot have `{…}` in it"),
},
Tok::Ident(n) if n.starts_with(|c: char| c.is_ascii_uppercase()) => {
- let mut binds = Vec::new();
+ let mut subs = Vec::new();
if self.eat_sym("(") {
while !self.is_sym(")") {
- if self.eat_sym("_") {
- binds.push("_".to_string());
- } else {
- binds.push(self.ident()?);
- }
+ subs.push(self.pattern()?);
if !self.eat_sym(",") {
break;
}
}
self.expect_sym(")")?;
}
- Pattern::Variant(n, binds, line)
+ Pattern::Variant(n, subs, line)
+ }
+ Tok::Sym("(") => {
+ let mut subs = Vec::new();
+ while !self.is_sym(")") {
+ subs.push(self.pattern()?);
+ if !self.eat_sym(",") {
+ break;
+ }
+ }
+ self.expect_sym(")")?;
+ Pattern::Tuple(subs)
+ }
+ Tok::Sym("{") => {
+ let mut fields = Vec::new();
+ let mut rest = false;
+ loop {
+ self.skip_semis();
+ if self.eat_sym("}") {
+ break;
+ }
+ if self.eat_sym("..") {
+ rest = true;
+ } else {
+ let f = self.ident()?;
+ let p = if self.eat_sym(":") {
+ self.pattern()?
+ } else {
+ Pattern::Bind(f.clone())
+ };
+ fields.push((f, p));
+ }
+ self.skip_semis();
+ if !self.eat_sym(",") {
+ self.skip_semis();
+ self.expect_sym("}")?;
+ break;
+ }
+ }
+ Pattern::Record(fields, rest, line)
}
Tok::Ident(n) => Pattern::Bind(n),
t => {
diff --git a/crates/frits/src/platform.rs b/crates/frits/src/platform.rs
index d4694aa..3172b9a 100644
--- a/crates/frits/src/platform.rs
+++ b/crates/frits/src/platform.rs
@@ -5,7 +5,9 @@
//! 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::rc::Rc;
+use std::cell::RefCell;
+use std::collections::HashMap;
+use std::rc::{Rc, Weak};
use crate::Error;
use crate::bytecode::Module;
@@ -21,9 +23,35 @@ pub struct Cx<'a, S> {
pub state: &'a mut S,
pub heap: &'a mut Heap,
pub strings: &'a [Rc<str>],
+ pub(crate) rng: &'a mut u64,
+ pub(crate) suspend: &'a mut bool,
+ pub(crate) charged: &'a mut u64,
}
impl<S> Cx<'_, S> {
+ /// Stop the script after this call returns, until the host wakes it
+ /// (`Process::wake`). The call's value is what the script sees on waking.
+ /// This is how `Timer.wait(2.5)` pauses a handler in the middle.
+ pub fn suspend(&mut self) {
+ *self.suspend = true;
+ }
+
+ /// Count `fuel` instructions' worth of work done by this call against the
+ /// script's slice, so an expensive host function is not free.
+ pub fn charge(&mut self, fuel: u64) {
+ *self.charged += fuel;
+ }
+
+ /// The process's own random stream (xorshift64*), seeded by the runtime.
+ pub fn random(&mut self) -> u64 {
+ let mut x = *self.rng;
+ x ^= x >> 12;
+ x ^= x << 25;
+ x ^= x >> 27;
+ *self.rng = x;
+ x.wrapping_mul(0x2545_F491_4F6C_DD1D)
+ }
+
pub fn str(&self, v: Value) -> &str {
self.heap.str(v, self.strings)
}
@@ -62,6 +90,9 @@ pub struct Platform<S> {
pub decl: PlatformDecl,
pub(crate) fns: Vec<Option<HostFn<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>>>,
}
impl<S> Platform<S> {
@@ -72,6 +103,7 @@ impl<S> Platform<S> {
fns: vec![None; decl.fns.len()],
consts: vec![None; decl.consts.len()],
decl,
+ cache: RefCell::default(),
};
crate::prelude::bind(&mut p);
Ok(p)
@@ -115,7 +147,17 @@ impl<S> Platform<S> {
.collect()
}
+ /// Compile `src`, or hand back the module already compiled from it.
pub fn compile(&self, src: &str) -> Result<Rc<Module>, Vec<Error>> {
- crate::compile::compile(src, &self.decl).map(Rc::new)
+ if let Some(m) = self.cache.borrow().get(src).and_then(Weak::upgrade) {
+ return Ok(m);
+ }
+ let m = Rc::new(crate::compile::compile(src, &self.decl)?);
+ let mut cache = self.cache.borrow_mut();
+ if cache.len() >= 64 && cache.len().is_power_of_two() {
+ cache.retain(|_, w| w.strong_count() > 0);
+ }
+ cache.insert(src.to_string(), Rc::downgrade(&m));
+ Ok(m)
}
}
diff --git a/crates/frits/src/prelude.rs b/crates/frits/src/prelude.rs
index 40c813a..e52c9e2 100644
--- a/crates/frits/src/prelude.rs
+++ b/crates/frits/src/prelude.rs
@@ -1,9 +1,19 @@
-//! What every platform has: the pure `math` module.
+//! What every platform has: `Vec3`, the pure `math` module, and `Random`, an
+//! effect because a script that rolls dice is not a pure function.
use crate::platform::{Cx, Platform};
use crate::value::{HostValue, Value};
pub const DECL: &str = "
+type Vec3 = { x: Float, y: Float, z: Float }
+
+effect Random {
+ // From 0 up to (not including) 1.
+ fn float() -> Float
+ // From `lo` up to and including `hi`.
+ fn int(lo: Int, hi: Int) -> Int
+}
+
module math {
fn sin(x: Float) -> Float
fn cos(x: Float) -> Float
@@ -46,5 +56,18 @@ pub fn bind<S>(p: &mut Platform<S>) {
})
.bind("math.deg", |_, a| f1(a, f64::to_degrees))
.bind("math.rad", |_, a| f1(a, f64::to_radians))
+ .bind("Random.float", |cx, _| {
+ Ok(Value::Float((cx.random() >> 11) as f64 / (1u64 << 53) as f64))
+ })
+ .bind("Random.int", |cx, a| {
+ let (lo, hi) = (a[0].int(), a[1].int());
+ if hi < lo {
+ return Err(format!("`Random.int({lo}, {hi})`: the range is empty"));
+ }
+ let span = (hi as i128 - lo as i128 + 1) as u128;
+ Ok(Value::Int(
+ (lo as i128 + (cx.random() as u128 % span) as i128) as i64,
+ ))
+ })
.constant("math.pi", HostValue::Float(std::f64::consts::PI));
}
diff --git a/crates/frits/src/runtime.rs b/crates/frits/src/runtime.rs
index 2be4743..72adc2f 100644
--- a/crates/frits/src/runtime.rs
+++ b/crates/frits/src/runtime.rs
@@ -32,6 +32,15 @@ pub struct Runtime<S> {
pub limits: Limits,
procs: Vec<Option<Process<S>>>,
free: Vec<Pid>,
+ spawned: u64,
+}
+
+/// How one `test` block went.
+#[derive(Clone, Debug, PartialEq)]
+pub struct TestResult {
+ pub name: String,
+ /// None when it passed; the message when it panicked or ran too long.
+ pub failure: Option<String>,
}
impl<S> Runtime<S> {
@@ -41,12 +50,15 @@ impl<S> Runtime<S> {
limits: Limits::default(),
procs: Vec::new(),
free: Vec::new(),
+ spawned: 0,
}
}
/// Start a process running `module`; its globals are set on its first slice.
pub fn spawn(&mut self, module: Rc<Module>, state: S) -> Pid {
- let p = Process::new(module, state);
+ let mut p = Process::new(module, state);
+ self.spawned += 1;
+ p.seed(self.spawned);
match self.free.pop() {
Some(pid) => {
self.procs[pid as usize] = Some(p);
@@ -102,6 +114,36 @@ impl<S> Runtime<S> {
died
}
+ /// Run every `test` block in `module`, each in a fresh process whose host
+ /// state `state` makes, with at most `fuel` instructions each.
+ pub fn test(&mut self, module: &Rc<Module>, mut state: impl FnMut() -> S, fuel: u64) -> Vec<TestResult> {
+ let mut out = Vec::new();
+ for (name, f) in &module.tests {
+ let mut p = Process::new(module.clone(), state());
+ p.post_fn(*f);
+ let mut left = fuel;
+ let failure = loop {
+ let slice = left.min(self.limits.fuel);
+ let before = p.executed;
+ match p.run(&self.platform, slice, self.limits.memory) {
+ Outcome::Idle => break None,
+ Outcome::Died(m) => break Some(m),
+ Outcome::Waiting => p.wake(None),
+ Outcome::Paused => {}
+ }
+ left = left.saturating_sub(p.executed - before);
+ if left == 0 {
+ break Some(format!("did not finish in {fuel} instructions"));
+ }
+ };
+ out.push(TestResult {
+ name: name.clone(),
+ failure,
+ });
+ }
+ out
+ }
+
pub fn pids(&self) -> impl Iterator<Item = Pid> + '_ {
self.procs
.iter()
diff --git a/crates/frits/src/stdlib.rs b/crates/frits/src/stdlib.rs
new file mode 100644
index 0000000..5f1dabf
--- /dev/null
+++ b/crates/frits/src/stdlib.rs
@@ -0,0 +1,496 @@
+//! The built-in methods on lists, strings, maps and vectors.
+//!
+//! None of these calls back into script code: `map`, `filter` and the like are
+//! 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;
+
+use crate::value::{Heap, Obj, Value};
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Std {
+ ListGet,
+ ListFirst,
+ ListLast,
+ ListContains,
+ ListIndexOf,
+ ListSlice,
+ ListJoin,
+ ListSort,
+ ListReversed,
+ ListConcat,
+ ListPushed,
+ ListRemoved,
+ ListSet,
+ StrContains,
+ StrStartsWith,
+ StrEndsWith,
+ StrUpper,
+ StrLower,
+ StrTrim,
+ StrSplit,
+ StrReplace,
+ StrSlice,
+ StrIndexOf,
+ StrParseInt,
+ StrParseFloat,
+ StrRepeat,
+ MapNew,
+ MapGet,
+ MapHas,
+ MapWith,
+ MapWithout,
+ MapKeys,
+ MapValues,
+ MapLen,
+ IntAbs,
+ IntMin,
+ IntMax,
+ VecAdd,
+ VecSub,
+ VecScale,
+ VecDiv,
+ VecDot,
+ VecCross,
+ VecLength,
+ VecNormalize,
+ VecDistance,
+ VecLerp,
+ /// `==` on anything without functions in it, compared by value.
+ Equal,
+}
+
+impl Std {
+ pub fn arity(self) -> usize {
+ use Std::*;
+ match self {
+ MapNew => 0,
+ ListFirst | ListLast | ListSort | ListReversed | StrUpper | StrLower | StrTrim | StrParseInt
+ | StrParseFloat | MapKeys | MapValues | MapLen | IntAbs | VecLength | VecNormalize => 1,
+ ListSlice | ListSet | StrReplace | StrSlice | MapWith | VecLerp => 3,
+ _ => 2,
+ }
+ }
+}
+
+const NONE: Value = Value::Tag(0);
+
+fn some(heap: &mut Heap, v: Value) -> Value {
+ heap.alloc(Obj::Variant(1, Box::new([v])))
+}
+
+fn s<'a>(heap: &'a Heap, strings: &'a [Rc<str>], v: Value) -> &'a str {
+ heap.str(v, strings)
+}
+
+/// Order of two Int or Str keys (or list items of one sortable type).
+pub fn key_cmp(heap: &Heap, strings: &[Rc<str>], a: Value, b: Value) -> Ordering {
+ match (a, b) {
+ (Value::Int(x), Value::Int(y)) => x.cmp(&y),
+ (Value::Float(x), Value::Float(y)) => x.total_cmp(&y),
+ (Value::Bool(x), Value::Bool(y)) => x.cmp(&y),
+ (Value::Tag(x), Value::Tag(y)) => x.cmp(&y),
+ _ => heap.str(a, strings).cmp(heap.str(b, strings)),
+ }
+}
+
+/// Value equality all the way down: records, lists, maps, variants.
+pub fn deep_equal(heap: &Heap, strings: &[Rc<str>], a: Value, b: Value) -> bool {
+ if a == b {
+ return true;
+ }
+ let all = |x: &[Value], y: &[Value]| {
+ x.len() == y.len() && x.iter().zip(y).all(|(p, q)| deep_equal(heap, strings, *p, *q))
+ };
+ match (heap.get(a), heap.get(b)) {
+ (Some(Obj::Record(x)), Some(Obj::Record(y))) => all(x, y),
+ (Some(Obj::Map(x)), Some(Obj::Map(y))) | (Some(Obj::List(x)), Some(Obj::List(y))) => all(x, y),
+ (Some(Obj::Variant(s, x)), Some(Obj::Variant(t, y))) => {
+ s == t
+ && x.len() == y.len()
+ && x.iter()
+ .zip(y.iter())
+ .all(|(p, q)| deep_equal(heap, strings, *p, *q))
+ }
+ (Some(Obj::Closure(..)), _) | (_, Some(Obj::Closure(..))) => false,
+ _ => equal(heap, strings, a, b),
+ }
+}
+
+/// `==` on the types that have it: numbers, Bool, Str, payload-free enums.
+pub fn equal(heap: &Heap, strings: &[Rc<str>], a: Value, b: Value) -> bool {
+ match (a, b) {
+ (Value::Static(_) | Value::Obj(_), Value::Static(_) | Value::Obj(_)) => {
+ a == b || heap.str(a, strings) == heap.str(b, strings)
+ }
+ _ => a == b,
+ }
+}
+
+fn map_find(heap: &Heap, strings: &[Rc<str>], kv: &[Value], k: Value) -> Result<usize, usize> {
+ let n = kv.len() / 2;
+ let (mut lo, mut hi) = (0, n);
+ while lo < hi {
+ let mid = (lo + hi) / 2;
+ match key_cmp(heap, strings, kv[mid * 2], k) {
+ Ordering::Less => lo = mid + 1,
+ Ordering::Greater => hi = mid,
+ Ordering::Equal => return Ok(mid),
+ }
+ }
+ Err(lo)
+}
+
+fn vec3(heap: &Heap, v: Value) -> [f64; 3] {
+ // Fields in name order: x, y, z.
+ let f = heap.fields(v);
+ [
+ f.first().map_or(0.0, |v| v.float()),
+ f.get(1).map_or(0.0, |v| v.float()),
+ f.get(2).map_or(0.0, |v| v.float()),
+ ]
+}
+
+fn new_vec3(heap: &mut Heap, [x, y, z]: [f64; 3]) -> Value {
+ heap.alloc(Obj::Record(Box::new([
+ Value::Float(x),
+ Value::Float(y),
+ Value::Float(z),
+ ])))
+}
+
+fn new_str(heap: &mut Heap, text: String, limit: usize) -> Result<Value, String> {
+ if text.len() > limit {
+ return Err(format!("out of memory: a {} KiB string", text.len() / 1024));
+ }
+ Ok(heap.alloc(Obj::Str(text.into())))
+}
+
+/// Character positions, clamped, as byte offsets into `text`.
+fn char_range(text: &str, a: i64, b: i64) -> (usize, usize) {
+ let n = text.chars().count() as i64;
+ let a = a.clamp(0, n) as usize;
+ let b = b.clamp(a as i64, n) as usize;
+ let mut idx = text
+ .char_indices()
+ .map(|(i, _)| i)
+ .chain(std::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()))
+ .nth(b)
+ .unwrap_or(text.len())
+ };
+ (start, end)
+}
+
+pub fn call(
+ f: Std,
+ heap: &mut Heap,
+ strings: &[Rc<str>],
+ a: &[Value],
+ limit: usize,
+) -> Result<Value, String> {
+ use Std::*;
+ Ok(match f {
+ ListGet => {
+ let items = heap.fields(a[0]);
+ match usize::try_from(a[1].int())
+ .ok()
+ .and_then(|i| items.get(i))
+ .copied()
+ {
+ Some(v) => some(heap, v),
+ None => NONE,
+ }
+ }
+ ListFirst | ListLast => {
+ let items = heap.fields(a[0]);
+ match if f == ListFirst {
+ items.first()
+ } else {
+ items.last()
+ }
+ .copied()
+ {
+ Some(v) => some(heap, v),
+ None => NONE,
+ }
+ }
+ ListContains => {
+ let found = heap.fields(a[0]).iter().any(|x| equal(heap, strings, *x, a[1]));
+ Value::Bool(found)
+ }
+ ListIndexOf => match heap
+ .fields(a[0])
+ .iter()
+ .position(|x| equal(heap, strings, *x, a[1]))
+ {
+ Some(i) => some(heap, Value::Int(i as i64)),
+ None => NONE,
+ },
+ ListSlice => {
+ let items = heap.fields(a[0]);
+ let n = items.len() as i64;
+ let lo = a[1].int().clamp(0, n) as usize;
+ let hi = a[2].int().clamp(lo as i64, n) as usize;
+ let part = items[lo..hi].to_vec();
+ heap.alloc(Obj::List(part))
+ }
+ ListJoin => {
+ let sep = s(heap, strings, a[1]);
+ let parts: Vec<&str> = heap.fields(a[0]).iter().map(|v| heap.str(*v, strings)).collect();
+ let text = parts.join(sep);
+ new_str(heap, text, limit)?
+ }
+ ListSort => {
+ let mut items = heap.fields(a[0]).to_vec();
+ items.sort_by(|x, y| key_cmp(heap, strings, *x, *y));
+ heap.alloc(Obj::List(items))
+ }
+ ListReversed => {
+ let mut items = heap.fields(a[0]).to_vec();
+ items.reverse();
+ heap.alloc(Obj::List(items))
+ }
+ ListConcat => {
+ let mut items = heap.fields(a[0]).to_vec();
+ items.extend_from_slice(heap.fields(a[1]));
+ if items.len() * size_of::<Value>() > limit {
+ return Err(format!("out of memory: a list of {} items", items.len()));
+ }
+ heap.alloc(Obj::List(items))
+ }
+ ListPushed => {
+ let src = heap.fields(a[0]);
+ let mut items = Vec::with_capacity(src.len() + 1);
+ items.extend_from_slice(src);
+ items.push(a[1]);
+ heap.alloc(Obj::List(items))
+ }
+ ListRemoved => {
+ let mut items = heap.fields(a[0]).to_vec();
+ let i = a[1].int();
+ if let Ok(i) = usize::try_from(i)
+ && i < items.len()
+ {
+ items.remove(i);
+ }
+ heap.alloc(Obj::List(items))
+ }
+ ListSet => {
+ let mut items = heap.fields(a[0]).to_vec();
+ let i = a[1].int();
+ match usize::try_from(i).ok().and_then(|i| items.get_mut(i)) {
+ Some(slot) => *slot = a[2],
+ None => return Err(format!("index {i} is outside the list (length {})", items.len())),
+ }
+ heap.alloc(Obj::List(items))
+ }
+ StrContains | StrStartsWith | StrEndsWith => {
+ let (t, p) = (s(heap, strings, a[0]), s(heap, strings, a[1]));
+ Value::Bool(match f {
+ StrContains => t.contains(p),
+ StrStartsWith => t.starts_with(p),
+ _ => t.ends_with(p),
+ })
+ }
+ StrUpper => {
+ let t = s(heap, strings, a[0]).to_uppercase();
+ new_str(heap, t, limit)?
+ }
+ StrLower => {
+ let t = s(heap, strings, a[0]).to_lowercase();
+ new_str(heap, t, limit)?
+ }
+ StrTrim => {
+ let t = s(heap, strings, a[0]).trim().to_string();
+ new_str(heap, t, limit)?
+ }
+ StrSplit => {
+ let (t, sep) = (s(heap, strings, a[0]), s(heap, strings, a[1]));
+ let parts: Vec<String> = if sep.is_empty() {
+ t.chars().map(|c| c.to_string()).collect()
+ } else {
+ t.split(sep).map(str::to_string).collect()
+ };
+ let items = parts
+ .into_iter()
+ .map(|p| heap.alloc(Obj::Str(p.into())))
+ .collect();
+ heap.alloc(Obj::List(items))
+ }
+ StrReplace => {
+ let (t, from, to) = (
+ s(heap, strings, a[0]),
+ s(heap, strings, a[1]),
+ s(heap, strings, a[2]),
+ );
+ if from.is_empty() {
+ let t = t.to_string();
+ return new_str(heap, t, limit);
+ }
+ let grows = to.len().saturating_sub(from.len()) * t.matches(from).count();
+ if t.len() + grows > limit {
+ return Err(format!(
+ "out of memory: a {} KiB string",
+ (t.len() + grows) / 1024
+ ));
+ }
+ let out = t.replace(from, to);
+ new_str(heap, out, limit)?
+ }
+ StrSlice => {
+ let t = s(heap, strings, a[0]);
+ let (lo, hi) = char_range(t, a[1].int(), a[2].int());
+ let part = t[lo..hi].to_string();
+ new_str(heap, part, limit)?
+ }
+ StrIndexOf => {
+ let (t, p) = (s(heap, strings, a[0]), s(heap, strings, a[1]));
+ match t.find(p) {
+ Some(b) => {
+ let chars = t[..b].chars().count() as i64;
+ some(heap, Value::Int(chars))
+ }
+ None => NONE,
+ }
+ }
+ StrParseInt => match s(heap, strings, a[0]).trim().parse::<i64>() {
+ Ok(i) => some(heap, Value::Int(i)),
+ Err(_) => NONE,
+ },
+ StrParseFloat => match s(heap, strings, a[0]).trim().parse::<f64>() {
+ Ok(x) => some(heap, Value::Float(x)),
+ Err(_) => NONE,
+ },
+ StrRepeat => {
+ let t = s(heap, strings, a[0]);
+ let n = a[1].int().max(0) as usize;
+ if t.len().saturating_mul(n) > limit {
+ return Err(format!("out of memory: `repeat` of {n}"));
+ }
+ let out = t.repeat(n);
+ new_str(heap, out, limit)?
+ }
+ MapNew => heap.alloc(Obj::Map(Vec::new())),
+ MapGet | MapHas => {
+ let Some(Obj::Map(kv)) = heap.get(a[0]) else {
+ return Ok(NONE);
+ };
+ let hit = map_find(heap, strings, kv, a[1]).ok().map(|i| kv[i * 2 + 1]);
+ match (f, hit) {
+ (MapHas, h) => Value::Bool(h.is_some()),
+ (_, Some(v)) => some(heap, v),
+ (_, None) => NONE,
+ }
+ }
+ MapWith => {
+ let Some(Obj::Map(kv)) = heap.get(a[0]) else {
+ return Ok(NONE);
+ };
+ let mut kv = kv.clone();
+ match map_find(heap, strings, &kv, a[1]) {
+ Ok(i) => kv[i * 2 + 1] = a[2],
+ Err(i) => {
+ kv.insert(i * 2, a[2]);
+ kv.insert(i * 2, a[1]);
+ }
+ }
+ if kv.len() * size_of::<Value>() > limit {
+ return Err(format!("out of memory: a map of {} entries", kv.len() / 2));
+ }
+ heap.alloc(Obj::Map(kv))
+ }
+ MapWithout => {
+ let Some(Obj::Map(kv)) = heap.get(a[0]) else {
+ return Ok(NONE);
+ };
+ let mut kv = kv.clone();
+ if let Ok(i) = map_find(heap, strings, &kv, a[1]) {
+ kv.drain(i * 2..i * 2 + 2);
+ }
+ heap.alloc(Obj::Map(kv))
+ }
+ MapKeys | MapValues => {
+ let Some(Obj::Map(kv)) = heap.get(a[0]) else {
+ return Ok(NONE);
+ };
+ let skip = usize::from(f == MapValues);
+ let items: Vec<Value> = kv.iter().skip(skip).step_by(2).copied().collect();
+ heap.alloc(Obj::List(items))
+ }
+ MapLen => match heap.get(a[0]) {
+ Some(Obj::Map(kv)) => Value::Int(kv.len() as i64 / 2),
+ _ => Value::Int(0),
+ },
+ IntAbs => match a[0].int().checked_abs() {
+ Some(v) => Value::Int(v),
+ None => return Err("integer overflow in `abs`".into()),
+ },
+ IntMin => Value::Int(a[0].int().min(a[1].int())),
+ IntMax => Value::Int(a[0].int().max(a[1].int())),
+ VecAdd | VecSub => {
+ let (p, q) = (vec3(heap, a[0]), vec3(heap, a[1]));
+ let sign = if f == VecAdd { 1.0 } else { -1.0 };
+ new_vec3(heap, [p[0] + sign * q[0], p[1] + sign * q[1], p[2] + sign * q[2]])
+ }
+ VecScale | VecDiv => {
+ let p = vec3(heap, a[0]);
+ let k = if f == VecScale {
+ a[1].float()
+ } else {
+ 1.0 / a[1].float()
+ };
+ new_vec3(heap, [p[0] * k, p[1] * k, p[2] * k])
+ }
+ VecDot => {
+ let (p, q) = (vec3(heap, a[0]), vec3(heap, a[1]));
+ Value::Float(p[0] * q[0] + p[1] * q[1] + p[2] * q[2])
+ }
+ VecCross => {
+ let (p, q) = (vec3(heap, a[0]), vec3(heap, a[1]));
+ new_vec3(
+ heap,
+ [
+ p[1] * q[2] - p[2] * q[1],
+ p[2] * q[0] - p[0] * q[2],
+ p[0] * q[1] - p[1] * q[0],
+ ],
+ )
+ }
+ VecLength => {
+ let p = vec3(heap, a[0]);
+ Value::Float((p[0] * p[0] + p[1] * p[1] + p[2] * p[2]).sqrt())
+ }
+ VecNormalize => {
+ let p = vec3(heap, a[0]);
+ let l = (p[0] * p[0] + p[1] * p[1] + p[2] * p[2]).sqrt();
+ 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())
+ }
+ Equal => Value::Bool(deep_equal(heap, strings, a[0], a[1])),
+ VecLerp => {
+ let (p, q, t) = (vec3(heap, a[0]), vec3(heap, a[1]), a[2].float());
+ new_vec3(
+ heap,
+ [
+ p[0] + (q[0] - p[0]) * t,
+ p[1] + (q[1] - p[1]) * t,
+ p[2] + (q[2] - p[2]) * t,
+ ],
+ )
+ }
+ })
+}
diff --git a/crates/frits/src/tests.rs b/crates/frits/src/tests.rs
index 835bd41..4dc2c8f 100644
--- a/crates/frits/src/tests.rs
+++ b/crates/frits/src/tests.rs
@@ -6,6 +6,8 @@ effect Out {
fn say(text: Str)
fn here() -> Geo
fn find(n: Int) -> Option<{ id: Int, name: Str }>
+ fn wait(seconds: Float)
+ fn costly()
}
effect Net {
fn get(url: Str) -> Str
@@ -36,6 +38,14 @@ fn platform() -> Platform<Log> {
Ok(cx.none())
}
})
+ .bind("Out.wait", |cx, _| {
+ cx.suspend();
+ Ok(Value::Unit)
+ })
+ .bind("Out.costly", |cx, _| {
+ cx.charge(5_000);
+ Ok(Value::Unit)
+ })
.bind("Net.get", |_, _| Err("no network in tests".into()));
assert!(p.unbound().is_empty(), "{:?}", p.unbound());
p
@@ -314,3 +324,325 @@ fn an_idle_process_is_small() {
let bytes = rt.get(a).unwrap().memory();
assert!(bytes < 1024, "an idle process holds {bytes} bytes");
}
+
+#[test]
+fn closures_capture_and_are_called() {
+ let out = said(
+ "script / Out
+ fn twice(f: fn(Int) -> Int, x: Int) -> Int { f(f(x)) }
+ fn inc(x: Int) -> Int { x + 1 }
+ on go() {
+ let k = 10
+ let add_k = fn(x: Int) -> Int { x + k }
+ Out.say(\"{twice(add_k, 1)} {twice(inc, 1)}\")
+ let shout = fn(t: Str) / Out { Out.say(t.upper()) }
+ shout(\"hi\")
+ let rules = { score: fn(n: Int) -> Int { n * 3 } }
+ Out.say(\"{rules.score(4)}\")
+ }",
+ );
+ assert_eq!(out, ["21 3", "HI", "12"]);
+}
+
+#[test]
+fn a_closure_cannot_change_what_it_captured_nor_do_more_than_it_says() {
+ let e = errors("script / Out\non go() { var n = 0\n let f = fn() { n = 1 } }");
+ assert!(e[0].contains("a closure has a copy"), "{e:?}");
+ let e = errors("script / Out\nfn run(f: fn()) { f() }\non go() { run(fn() / Out { Out.say(\"x\") }) }");
+ assert!(e[0].contains("expected fn(), found fn() / Out"), "{e:?}");
+}
+
+#[test]
+fn list_methods() {
+ let out = said(
+ "script / Out
+ on go() {
+ var xs = [5, 3, 8]
+ xs.push(1)
+ let doubled = xs.map(fn(x) { x * 2 })
+ let big = xs.filter(fn(x) { x > 2 })
+ let words = [\"b\", \"a\", \"c\"].sort()
+ Out.say(\"{len(xs)} {doubled[3]} {len(big)} {words.join(\"-\")} {xs.contains(8)} {xs.any(fn(x) { x > 7 })} {xs.all(fn(x) { x > 0 })} {xs.count(fn(x) { x % 2 == 1 })}\")
+ if let Some(i) = xs.index_of(8) { Out.say(\"at {i}\") }
+ if let Some(x) = xs.find(fn(x) { x < 4 }) { Out.say(\"found {x}\") }
+ xs[0] = 50
+ xs.remove_at(1)
+ let all = xs + [9, 9]
+ Out.say(\"{xs[0]} {len(xs)} {len(all)} {xs.reversed()[0]} {xs.slice(0, 2)[1]}\")
+ match xs.get(99) { Some(_) => Out.say(\"?\"), None => Out.say(\"none\") }
+ }",
+ );
+ assert_eq!(
+ out,
+ [
+ "4 2 3 a-b-c true true true 3",
+ "at 2",
+ "found 3",
+ "50 3 5 1 8",
+ "none"
+ ]
+ );
+}
+
+#[test]
+fn string_methods() {
+ let out = said(
+ "script / Out
+ on go() {
+ let t = \" Hallo, wereld \".trim()
+ let parts = t.split(\", \")
+ Out.say(\"{parts[1]} {t.lower()} {t.starts_with(\"Hal\")} {t.replace(\"l\", \"L\")} {t.slice(0, 4)}\")
+ let n = match \"42\".parse_int() { Some(n) => n, None => 0 }
+ let x = \"nope\".parse_float()
+ Out.say(\"{n + 1} {x == None} {\"ab\".repeat(3)} {t.contains(\"wer\")}\")
+ }",
+ );
+ assert_eq!(
+ out,
+ [
+ "wereld hallo, wereld true HaLLo, wereLd Hall",
+ "43 true ababab true"
+ ]
+ );
+}
+
+#[test]
+fn maps() {
+ let out = said(
+ "script / Out
+ var scores: Map<Str, Int> = [:]
+ on go() {
+ scores.set(\"bo\", 2)
+ scores.set(\"ada\", 3)
+ scores.set(\"bo\", 5)
+ let ages = [\"x\": 1, \"y\": 2]
+ let bo = match scores.get(\"bo\") { Some(n) => n, None => 0 }
+ Out.say(\"{len(scores)} {bo} {scores.has(\"cy\")} {scores.keys().join(\",\")} {len(ages)}\")
+ scores.remove(\"bo\")
+ Out.say(\"{len(scores)} {scores.values()[0]}\")
+ }",
+ );
+ assert_eq!(out, ["2 5 false ada,bo 2", "1 3"]);
+}
+
+#[test]
+fn tuples_records_and_nested_patterns() {
+ let out = said(
+ "script / Out
+ enum Shape { Circle(Float), Rect(Float, Float) }
+ fn min_max(xs: List<Int>) -> (Int, Int) {
+ var lo = xs[0]
+ var hi = xs[0]
+ for x in xs { lo = min(lo, x); hi = max(hi, x) }
+ (lo, hi)
+ }
+ fn describe(s: Option<Shape>) -> Str {
+ match s {
+ Some(Circle(r)) if r > 10 => \"big circle\",
+ Some(Circle(_)) => \"circle\",
+ Some(Rect(w, h)) => \"rect {w * h}\",
+ None => \"nothing\",
+ }
+ }
+ on go() {
+ let (lo, hi) = min_max([4, -2, 9])
+ let pair = (lo, \"x\")
+ let { lat, lng: l } = Out.here()
+ Out.say(\"{lo} {hi} {pair.0} {pair.1} {lat} {l}\")
+ Out.say(\"{describe(Some(Circle(12)))}, {describe(Some(Circle(1)))}, {describe(Some(Rect(2, 3)))}, {describe(None)}\")
+ }",
+ );
+ assert_eq!(out, ["-2 9 -2 x 53.2 6.5", "big circle, circle, rect 6, nothing"]);
+}
+
+#[test]
+fn a_guarded_arm_does_not_count_as_covering() {
+ let e =
+ errors("script / Out\nfn f(x: Option<Int>) -> Int { match x { Some(n) if n > 0 => n, None => 0 } }");
+ assert!(e[0].contains("misses: Some(_)"), "{e:?}");
+}
+
+#[test]
+fn results_and_question_mark() {
+ let out = said(
+ "script / Out
+ fn parse(t: Str) -> Result<Int, Str> {
+ match t.parse_int() { Some(n) => Ok(n), None => Err(\"not a number: {t}\") }
+ }
+ fn sum(a: Str, b: Str) -> Result<Int, Str> {
+ let x = parse(a)?
+ let y = parse(b)?
+ Ok(x + y)
+ }
+ fn first_even(xs: List<Int>) -> Option<Int> {
+ let x = xs.find(fn(x) { x % 2 == 0 })?
+ Some(x * 10)
+ }
+ on go() {
+ match sum(\"2\", \"3\") { Ok(n) => Out.say(\"{n}\"), Err(e) => Out.say(e) }
+ match sum(\"2\", \"x\") { Ok(n) => Out.say(\"{n}\"), Err(e) => Out.say(e) }
+ Out.say(\"{first_even([1, 4]) == Some(40)}\")
+ }",
+ );
+ assert_eq!(out, ["5", "not a number: x", "true"]);
+}
+
+#[test]
+fn vec3_arithmetic() {
+ let out = said(
+ "script / Out
+ on go() {
+ let a: Vec3 = { x: 1, y: 2, z: 2 }
+ let b = a * 2 + { x: 1, y: 0, z: 0 }
+ let c = 0.5 * (b - a)
+ Out.say(\"{a.length()} {b.x} {c.y} {a.dot(b)} {a.normalize().x:.3} {a.distance(b):.3}\")
+ }",
+ );
+ assert_eq!(out, ["3 3 1 19 0.333 3.464"]);
+}
+
+#[test]
+fn methods_on_your_own_types_and_generics() {
+ let out = said(
+ "script / Out
+ type Pt = { x: Int, y: Int }
+ fn manhattan(p: Pt, q: Pt) -> Int { abs(p.x - q.x) + abs(p.y - q.y) }
+ fn first<T>(xs: List<T>) -> Option<T> { xs.get(0) }
+ fn pair<A, B>(a: A, b: B) -> (A, B) { (a, b) }
+ fn or_else<T>(x: Option<T>, d: T) -> T { match x { Some(v) => v, None => d } }
+ on go() {
+ let p: Pt = { x: 1, y: 2 }
+ Out.say(\"{p.manhattan({ x: 4, y: 6 })}\")
+ Out.say(\"{or_else(first([7, 8]), 0)} {or_else(first([\"a\"]), \"-\")} {[3].first().or_else(0)}\")
+ let (n, s) = pair(1, \"b\")
+ Out.say(\"{n}{s}\")
+ }",
+ );
+ assert_eq!(out, ["7", "7 a 3", "1b"]);
+}
+
+#[test]
+fn log_and_assert() {
+ let mut rt = Runtime::new(platform());
+ let m = rt
+ .platform
+ .compile(
+ "script / Out\non go() {\n log(\"hello\")\n warn(\"careful\")\n assert(1 + 1 == 3, \"maths\")\n}",
+ )
+ .unwrap();
+ let pid = rt.spawn(m, Log::default());
+ rt.post(pid, "go", Vec::new());
+ let died = rt.tick();
+ assert!(
+ died[0].1.contains("line 5") && died[0].1.contains("assertion failed: maths"),
+ "{died:?}"
+ );
+ let log = rt.get_mut(pid).unwrap().take_log();
+ assert_eq!(log.len(), 2);
+ assert_eq!(
+ (log[0].level, log[0].line, log[0].text.as_str()),
+ (Level::Info, 3, "hello")
+ );
+ assert_eq!(log[1].level, Level::Warn);
+}
+
+#[test]
+fn waiting_in_the_middle_of_a_handler() {
+ let mut rt = Runtime::new(platform());
+ let m = rt
+ .platform
+ .compile("script / Out\non go() { Out.say(\"shake\")\n Out.wait(2.5)\n Out.say(\"boom\") }\non msg(n: Int, t: Str) { Out.say(t) }")
+ .unwrap();
+ let pid = rt.spawn(m, Log::default());
+ rt.post(pid, "go", Vec::new());
+ rt.tick();
+ let p = rt.get(pid).unwrap();
+ assert_eq!(p.state.0, ["shake"]);
+ assert_eq!(p.status, Status::Waiting);
+ // An event that arrives meanwhile waits its turn; nothing runs.
+ rt.post(
+ pid,
+ "msg",
+ vec![HostValue::Int(1), HostValue::Str("later".into())],
+ );
+ rt.tick();
+ assert_eq!(rt.get(pid).unwrap().state.0, ["shake"]);
+ rt.get_mut(pid).unwrap().wake(None);
+ rt.tick();
+ assert_eq!(rt.get(pid).unwrap().state.0, ["shake", "boom", "later"]);
+}
+
+#[test]
+fn a_costly_host_call_spends_fuel() {
+ let mut rt = Runtime::new(platform());
+ rt.limits.fuel = 12_000;
+ let m = rt
+ .platform
+ .compile("script / Out\non go() { Out.costly()\n Out.costly()\n Out.costly()\n Out.say(\"done\") }")
+ .unwrap();
+ let pid = rt.spawn(m, Log::default());
+ rt.post(pid, "go", Vec::new());
+ rt.tick();
+ assert_eq!(rt.get(pid).unwrap().status, Status::Paused);
+ rt.tick();
+ assert_eq!(rt.get(pid).unwrap().state.0, ["done"]);
+}
+
+#[test]
+fn kept_values_survive_a_new_version_of_the_script() {
+ let mut rt = Runtime::new(platform());
+ let v1 = rt.platform.compile("script / Out\nkeep var goals = 0\nkeep var names: List<Str> = []\nvar plain = 0\non go() { goals += 2\n names.push(\"bo\")\n plain = 9 }").unwrap();
+ let a = rt.spawn(v1, Log::default());
+ rt.post(a, "go", Vec::new());
+ rt.tick();
+ let kept = rt.get(a).unwrap().kept();
+ assert_eq!(kept.len(), 2);
+ // The new version changed a kept type and dropped nothing else.
+ let v2 = rt.platform.compile("script / Out\nkeep var goals = 0\nkeep var names: List<Int> = []\nvar plain = 0\non go() { Out.say(\"{goals} {len(names)} {plain}\") }").unwrap();
+ let b = rt.spawn(v2, Log::default());
+ rt.get_mut(b).unwrap().restore(kept);
+ rt.post(b, "go", Vec::new());
+ rt.tick();
+ assert_eq!(rt.get(b).unwrap().state.0, ["2 0 0"]);
+}
+
+#[test]
+fn test_blocks_run_and_report() {
+ let mut rt = Runtime::new(platform());
+ let m = rt
+ .platform
+ .compile("script / Out\nfn double(x: Int) -> Int { x * 2 }\ntest \"doubles\" { assert(double(2) == 4) }\ntest \"wrong\" { assert(double(2) == 5, \"two twos\") }\ntest \"forever\" { while true { } }")
+ .unwrap();
+ let res = rt.test(&m, Log::default, 100_000);
+ assert_eq!(res.len(), 3);
+ assert_eq!(res[0].failure, None);
+ assert!(res[1].failure.as_ref().unwrap().contains("two twos"));
+ assert!(res[2].failure.as_ref().unwrap().contains("did not finish"));
+}
+
+#[test]
+fn random_is_an_effect_and_stays_in_range() {
+ let e = errors("script / Out\non go() { let x = Random.int(1, 6) }");
+ assert!(e[0].contains("`Random`"), "{e:?}");
+ let out = said(
+ "script / Out, Random
+ on go() {
+ var ok = true
+ for i in 0..1000 {
+ let d = Random.int(1, 6)
+ let f = Random.float()
+ if d < 1 || d > 6 || f < 0 || f >= 1 { ok = false }
+ }
+ Out.say(\"{ok}\")
+ }",
+ );
+ assert_eq!(out, ["true"]);
+}
+
+#[test]
+fn one_source_compiles_once() {
+ let p = platform();
+ let a = p.compile("script / Out\non go() { }").unwrap();
+ let b = p.compile("script / Out\non go() { }").unwrap();
+ assert!(std::rc::Rc::ptr_eq(&a, &b));
+}
diff --git a/crates/frits/src/types.rs b/crates/frits/src/types.rs
index 86510d5..c30dcf5 100644
--- a/crates/frits/src/types.rs
+++ b/crates/frits/src/types.rs
@@ -17,6 +17,14 @@ pub enum Type {
Str,
List(Rc<Type>),
Option(Rc<Type>),
+ /// Keys are Int or Str.
+ Map(Rc<Type>, Rc<Type>),
+ /// `Ok(T)` (tag 0) or `Err(E)` (tag 1).
+ Result(Rc<Type>, Rc<Type>),
+ Tuple(Rc<[Type]>),
+ Fn(Rc<FnType>),
+ /// A generic function's type parameter, before a call fixes it.
+ Param(Rc<str>),
/// Fields sorted by name: two records with the same fields are the same type,
/// whatever they were called where they were written.
Record(Rc<[(Rc<str>, Type)]>),
@@ -27,6 +35,23 @@ pub enum Type {
Error,
}
+/// A function value's type: `fn(Int, Str) -> Bool / Prim`.
+#[derive(Clone, Debug, PartialEq)]
+pub struct FnType {
+ pub params: Vec<Type>,
+ pub ret: Type,
+ /// Sorted, so two spellings of one set compare equal.
+ pub effects: Vec<String>,
+}
+
+impl FnType {
+ pub fn new(params: Vec<Type>, ret: Type, mut effects: Vec<String>) -> Self {
+ effects.sort();
+ effects.dedup();
+ FnType { params, ret, effects }
+ }
+}
+
impl Type {
pub fn record(mut fields: Vec<(Rc<str>, Type)>) -> Type {
fields.sort_by(|a, b| a.0.cmp(&b.0));
@@ -36,13 +61,127 @@ impl Type {
pub fn field(&self, name: &str) -> Option<(usize, &Type)> {
match self {
Type::Record(f) => f.iter().position(|(n, _)| &**n == name).map(|i| (i, &f[i].1)),
+ Type::Tuple(items) => name
+ .parse::<usize>()
+ .ok()
+ .and_then(|i| items.get(i).map(|t| (i, t))),
_ => None,
}
}
+ /// The prelude's `Vec3`, which has arithmetic.
+ pub fn is_vec3(&self) -> bool {
+ match self {
+ Type::Record(f) => {
+ f.len() == 3
+ && f.iter()
+ .zip(["x", "y", "z"])
+ .all(|((n, t), want)| &**n == want && *t == Type::Float)
+ }
+ _ => false,
+ }
+ }
+
+ /// Does a value of this type hold a function anywhere?
+ pub fn has_fn(&self) -> bool {
+ match self {
+ Type::Fn(_) => true,
+ Type::List(t) | Type::Option(t) => t.has_fn(),
+ Type::Map(a, b) | Type::Result(a, b) => a.has_fn() || b.has_fn(),
+ Type::Tuple(ts) => ts.iter().any(Type::has_fn),
+ Type::Record(fs) => fs.iter().any(|(_, t)| t.has_fn()),
+ // An enum's payloads are not looked into here; compared, a function
+ // in one compares as never equal.
+ _ => false,
+ }
+ }
+
+ pub fn has_param(&self) -> bool {
+ match self {
+ Type::Param(_) => true,
+ Type::List(t) | Type::Option(t) => t.has_param(),
+ Type::Map(a, b) | Type::Result(a, b) => a.has_param() || b.has_param(),
+ Type::Tuple(ts) => ts.iter().any(Type::has_param),
+ Type::Record(fs) => fs.iter().any(|(_, t)| t.has_param()),
+ Type::Fn(f) => f.ret.has_param() || f.params.iter().any(Type::has_param),
+ _ => false,
+ }
+ }
+
+ /// Replace type parameters by what `bind` fixed them to.
+ pub fn subst(&self, bind: &HashMap<String, Type>) -> Type {
+ let r = |t: &Type| Rc::new(t.subst(bind));
+ match self {
+ Type::Param(n) => bind.get(&**n).cloned().unwrap_or(Type::Error),
+ Type::List(t) => Type::List(r(t)),
+ Type::Option(t) => Type::Option(r(t)),
+ Type::Map(a, b) => Type::Map(r(a), r(b)),
+ Type::Result(a, b) => Type::Result(r(a), r(b)),
+ Type::Tuple(ts) => Type::Tuple(ts.iter().map(|t| t.subst(bind)).collect()),
+ Type::Record(fs) => Type::Record(fs.iter().map(|(n, t)| (n.clone(), t.subst(bind))).collect()),
+ Type::Fn(f) => Type::Fn(Rc::new(FnType {
+ params: f.params.iter().map(|t| t.subst(bind)).collect(),
+ ret: f.ret.subst(bind),
+ effects: f.effects.clone(),
+ })),
+ t => t.clone(),
+ }
+ }
+
+ /// 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 {
+ match (self, actual) {
+ (Type::Param(n), _) => match bind.get(&**n) {
+ Some(t) => actual.fits(t),
+ None => {
+ bind.insert(n.to_string(), actual.clone());
+ true
+ }
+ },
+ (_, Type::Error | Type::Never) => true,
+ (Type::List(a), Type::List(b)) | (Type::Option(a), Type::Option(b)) => a.unify(b, bind),
+ (Type::Map(a, b), Type::Map(c, d)) | (Type::Result(a, b), Type::Result(c, d)) => {
+ a.unify(c, bind) && b.unify(d, bind)
+ }
+ (Type::Tuple(a), Type::Tuple(b)) => {
+ a.len() == b.len() && a.iter().zip(b.iter()).all(|(x, y)| x.unify(y, bind))
+ }
+ (Type::Record(a), Type::Record(b)) => {
+ a.len() == b.len()
+ && a.iter()
+ .zip(b.iter())
+ .all(|((n, x), (m, y))| n == m && x.unify(y, bind))
+ }
+ (Type::Fn(f), Type::Fn(g)) => {
+ f.params.len() == g.params.len()
+ && f.params.iter().zip(&g.params).all(|(x, y)| x.unify(y, bind))
+ && f.ret.unify(&g.ret, bind)
+ }
+ _ => actual.fits(self),
+ }
+ }
+
/// Does a value of `self` fit where `want` is expected?
pub fn fits(&self, want: &Type) -> bool {
- self == want || matches!(self, Type::Never | Type::Error) || matches!(want, Type::Error)
+ if self == want || matches!(self, Type::Never | Type::Error) || matches!(want, Type::Error) {
+ return true;
+ }
+ // A function that does less fits where one that may do more is wanted.
+ match (self, want) {
+ (Type::Fn(a), Type::Fn(b)) => {
+ a.params == b.params && a.ret.fits(&b.ret) && a.effects.iter().all(|e| b.effects.contains(e))
+ }
+ _ => false,
+ }
+ }
+
+ /// Can `==` compare two values of this type?
+ pub fn has_eq(&self) -> bool {
+ matches!(
+ self,
+ Type::Int | Type::Float | Type::Bool | Type::Str | Type::Error
+ )
}
}
@@ -61,6 +200,36 @@ impl fmt::Display for Show<'_> {
Type::Str => write!(f, "Str"),
Type::List(t) => write!(f, "List<{}>", Show(t, names)),
Type::Option(t) => write!(f, "Option<{}>", Show(t, names)),
+ Type::Map(k, v) => write!(f, "Map<{}, {}>", Show(k, names), Show(v, names)),
+ Type::Result(t, e) => write!(f, "Result<{}, {}>", Show(t, names), Show(e, names)),
+ Type::Tuple(ts) => {
+ write!(f, "(")?;
+ for (i, t) in ts.iter().enumerate() {
+ if i > 0 {
+ write!(f, ", ")?;
+ }
+ write!(f, "{}", Show(t, names))?;
+ }
+ write!(f, ")")
+ }
+ Type::Param(n) => write!(f, "{n}"),
+ Type::Fn(ft) => {
+ write!(f, "fn(")?;
+ for (i, p) in ft.params.iter().enumerate() {
+ if i > 0 {
+ write!(f, ", ")?;
+ }
+ write!(f, "{}", Show(p, names))?;
+ }
+ write!(f, ")")?;
+ if ft.ret != Type::Unit {
+ write!(f, " -> {}", Show(&ft.ret, names))?;
+ }
+ if !ft.effects.is_empty() {
+ write!(f, " / {}", ft.effects.join(", "))?;
+ }
+ Ok(())
+ }
Type::Record(fields) => {
write!(f, "{{ ")?;
for (i, (n, t)) in fields.iter().enumerate() {
@@ -87,11 +256,29 @@ impl fmt::Display for Show<'_> {
pub struct TypeEnv {
pub aliases: HashMap<String, Type>,
pub enums: HashMap<String, u32>,
+ /// Type parameters in scope, while a generic function is checked.
+ pub generics: HashMap<String, Type>,
}
impl TypeEnv {
pub fn resolve(&self, t: &TypeExpr) -> Result<Type, Error> {
match t {
+ TypeExpr::Tuple(items, _) => Ok(Type::Tuple(
+ items
+ .iter()
+ .map(|t| self.resolve(t))
+ .collect::<Result<Vec<_>, _>>()?
+ .into(),
+ )),
+ TypeExpr::Fn(params, ret, effects, _) => {
+ let params = params.iter().map(|p| self.resolve(p)).collect::<Result<_, _>>()?;
+ let ret = ret
+ .as_ref()
+ .map(|r| self.resolve(r))
+ .transpose()?
+ .unwrap_or(Type::Unit);
+ Ok(Type::Fn(Rc::new(FnType::new(params, ret, effects.clone()))))
+ }
TypeExpr::Record(fields, line) => {
let mut out: Vec<(Rc<str>, Type)> = Vec::new();
for (n, ft) in fields {
@@ -142,9 +329,23 @@ impl TypeEnv {
arity(1)?;
Type::Option(Rc::new(self.resolve(&args[0])?))
}
+ "Result" => {
+ arity(2)?;
+ Type::Result(Rc::new(self.resolve(&args[0])?), Rc::new(self.resolve(&args[1])?))
+ }
+ "Map" => {
+ arity(2)?;
+ let k = self.resolve(&args[0])?;
+ if !matches!(k, Type::Int | Type::Str) {
+ return Err(Error::new(*line, "a Map's keys are Int or Str"));
+ }
+ Type::Map(Rc::new(k), Rc::new(self.resolve(&args[1])?))
+ }
_ => {
arity(0)?;
- if let Some(t) = self.aliases.get(name) {
+ if let Some(t) = self.generics.get(name) {
+ t.clone()
+ } else if let Some(t) = self.aliases.get(name) {
t.clone()
} else if let Some(&e) = self.enums.get(name) {
Type::Enum(e)
diff --git a/crates/frits/src/value.rs b/crates/frits/src/value.rs
index 5854922..5023f56 100644
--- a/crates/frits/src/value.rs
+++ b/crates/frits/src/value.rs
@@ -48,8 +48,13 @@ impl Value {
pub enum Obj {
Str(Box<str>),
Record(Box<[Value]>),
- List(Box<[Value]>),
+ /// A Vec so a list the compiler is still building can grow in place.
+ List(Vec<Value>),
Variant(u32, Box<[Value]>),
+ /// Keys and values alternating, `[k0, v0, k1, v1, …]`, sorted by key.
+ Map(Vec<Value>),
+ /// A function and the values it captured, copied when it was made.
+ Closure(u32, Box<[Value]>),
}
impl Obj {
@@ -58,9 +63,19 @@ impl Obj {
HEADER
+ match self {
Obj::Str(s) => s.len(),
- Obj::Record(v) | Obj::List(v) | Obj::Variant(_, v) => v.len() * size_of::<Value>(),
+ Obj::List(v) | Obj::Map(v) => v.capacity() * size_of::<Value>(),
+ o => size_of_val(o.slots()),
}
}
+
+ /// Every value the object holds, for the collector.
+ pub fn slots(&self) -> &[Value] {
+ match self {
+ Obj::Str(_) => &[],
+ Obj::Record(v) | Obj::Variant(_, v) | Obj::Closure(_, v) => v,
+ Obj::List(v) | Obj::Map(v) => v,
+ }
+ }
}
/// A value outside any heap: what the platform hands a script and gets back.
@@ -76,6 +91,8 @@ pub enum HostValue {
Record(Vec<HostValue>),
List(Vec<HostValue>),
Variant(u32, Vec<HostValue>),
+ /// Keys and values; a function value crosses as Unit.
+ Map(Vec<(HostValue, HostValue)>),
}
#[derive(Debug, Default)]
@@ -114,13 +131,34 @@ impl Heap {
}
}
+ pub fn get_mut(&mut self, v: Value) -> Option<&mut Obj> {
+ match v {
+ Value::Obj(i) => self.objs.get_mut(i as usize).and_then(|o| o.as_mut()),
+ _ => None,
+ }
+ }
+
+ /// A record's fields, a list's items or a variant's payload.
pub fn fields(&self, v: Value) -> &[Value] {
match self.get(v) {
- Some(Obj::Record(f) | Obj::List(f) | Obj::Variant(_, f)) => f,
+ Some(Obj::Record(f) | Obj::Variant(_, f)) => f,
+ Some(Obj::List(f)) => f,
_ => &[],
}
}
+ /// Append to a list nobody else can see yet (one the compiler is building).
+ pub fn list_push(&mut self, list: Value, x: Value) {
+ let Some(Obj::List(items)) = self.get_mut(list) else {
+ return;
+ };
+ let before = items.capacity();
+ items.push(x);
+ let grown = (items.capacity() - before) * size_of::<Value>();
+ self.bytes += grown;
+ self.since_gc += grown;
+ }
+
pub fn wants_gc(&self) -> bool {
self.since_gc > GC_FLOOR.max(self.bytes - self.since_gc)
}
@@ -139,9 +177,10 @@ impl Heap {
continue;
}
self.marks[i] = true;
- if let Some(Obj::Record(f) | Obj::List(f) | Obj::Variant(_, f)) = &self.objs[i] {
+ if let Some(o) = &self.objs[i] {
stack.extend(
- f.iter()
+ o.slots()
+ .iter()
.filter_map(|v| if let Value::Obj(j) = v { Some(*j) } else { None }),
);
}
@@ -197,7 +236,12 @@ impl Heap {
Some(Obj::Variant(t, f)) => {
HostValue::Variant(*t, f.iter().map(|x| self.export(*x, strings)).collect())
}
- None => HostValue::Unit,
+ Some(Obj::Map(kv)) => HostValue::Map(
+ kv.chunks(2)
+ .map(|p| (self.export(p[0], strings), self.export(p[1], strings)))
+ .collect(),
+ ),
+ Some(Obj::Closure(..)) | None => HostValue::Unit,
},
}
}
@@ -215,9 +259,17 @@ impl Heap {
self.alloc(Obj::Record(f))
}
HostValue::List(f) => {
- let f: Box<[Value]> = f.iter().map(|x| self.import(x)).collect();
+ let f: Vec<Value> = f.iter().map(|x| self.import(x)).collect();
self.alloc(Obj::List(f))
}
+ HostValue::Map(kv) => {
+ let mut pairs: Vec<(Value, Value)> =
+ kv.iter().map(|(k, v)| (self.import(k), self.import(v))).collect();
+ pairs.sort_by(|a, b| crate::stdlib::key_cmp(self, &[], a.0, b.0));
+ pairs.dedup_by(|a, b| crate::stdlib::key_cmp(self, &[], a.0, b.0).is_eq());
+ let flat = pairs.into_iter().flat_map(|(k, v)| [k, v]).collect();
+ self.alloc(Obj::Map(flat))
+ }
HostValue::Variant(t, f) => {
let f: Box<[Value]> = f.iter().map(|x| self.import(x)).collect();
self.alloc(Obj::Variant(*t, f))
diff --git a/crates/frits/src/vm.rs b/crates/frits/src/vm.rs
index 65c8cc8..2e16902 100644
--- a/crates/frits/src/vm.rs
+++ b/crates/frits/src/vm.rs
@@ -29,9 +29,26 @@ pub enum Status {
Idle,
/// In the middle of a handler, paused when its fuel ran out.
Paused,
+ /// In the middle of a handler, stopped by a host call (`Timer.wait`) until
+ /// the host wakes it.
+ Waiting,
Dead(String),
}
+/// A line the script logged.
+#[derive(Clone, Debug, PartialEq)]
+pub struct LogLine {
+ pub level: Level,
+ pub line: u32,
+ pub text: String,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Level {
+ Info,
+ Warn,
+}
+
pub struct Process<S> {
pub module: Rc<Module>,
globals: Vec<Value>,
@@ -43,8 +60,17 @@ pub struct Process<S> {
pub status: Status,
/// Instructions executed over the process's life.
pub executed: u64,
+ rng: u64,
+ waiting: bool,
+ /// What the script logged since the host last took it (`take_log`).
+ log: Vec<LogLine>,
+ /// Kept values to put back once the globals are initialised.
+ restore: Vec<(String, String, HostValue)>,
}
+/// The most log lines a process holds before the oldest are dropped.
+const LOG_CAP: usize = 256;
+
/// How `run` came back.
#[derive(Clone, Debug, PartialEq)]
pub enum Outcome {
@@ -52,6 +78,8 @@ pub enum Outcome {
Idle,
/// Fuel ran out; work is left for the next slice.
Paused,
+ /// A host call suspended it; `Process::wake` resumes it.
+ Waiting,
Died(String),
}
@@ -66,6 +94,10 @@ impl<S> Process<S> {
state,
status: Status::Idle,
executed: 0,
+ rng: 0x9E37_79B9_7F4A_7C15,
+ waiting: false,
+ log: Vec::new(),
+ restore: Vec::new(),
module,
};
let init = p.module.init;
@@ -85,7 +117,93 @@ impl<S> Process<S> {
}
pub fn has_work(&self) -> bool {
- !self.frames.is_empty() || !self.mailbox.is_empty()
+ !self.waiting && (!self.frames.is_empty() || !self.mailbox.is_empty())
+ }
+
+ /// Resume a process a host call suspended. The suspended call returns Unit
+ /// unless `value` says otherwise.
+ pub fn wake(&mut self, value: Option<HostValue>) {
+ if !self.waiting {
+ return;
+ }
+ self.waiting = false;
+ if self.status == Status::Waiting {
+ self.status = Status::Paused;
+ }
+ if let Some(v) = value
+ && let Some(fr) = self.frames.last()
+ {
+ // The suspended CallHost is the instruction before the saved pc.
+ let func = &self.module.funcs[fr.func as usize];
+ if let Some(crate::bytecode::Op::CallHost { dst, .. }) = func.code.get(fr.pc as usize - 1) {
+ let r = fr.base as usize + *dst as usize;
+ self.regs[r] = self.heap.import(&v);
+ }
+ }
+ }
+
+ pub fn is_waiting(&self) -> bool {
+ self.waiting
+ }
+
+ /// Seed the process's random stream; the runtime gives each process its own.
+ pub fn seed(&mut self, seed: u64) {
+ // splitmix64, so neighbouring seeds give unrelated streams; never zero.
+ let mut z = seed.wrapping_add(0x9E37_79B9_7F4A_7C15);
+ z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
+ z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
+ self.rng = (z ^ (z >> 31)) | 1;
+ }
+
+ /// The lines logged since the last call.
+ pub fn take_log(&mut self) -> Vec<LogLine> {
+ std::mem::take(&mut self.log)
+ }
+
+ /// The `keep var` globals as they are now: (name, type, value). A host
+ /// stores these and hands them to `restore` when the script starts again.
+ pub fn kept(&self) -> Vec<(String, String, HostValue)> {
+ if self.globals.is_empty() {
+ return Vec::new();
+ }
+ self.module
+ .kept
+ .iter()
+ .map(|(g, ty)| {
+ let name = self.module.globals[*g as usize].clone();
+ (
+ name,
+ ty.clone(),
+ self.heap.export(self.globals[*g as usize], &self.module.strings),
+ )
+ })
+ .collect()
+ }
+
+ /// Put back kept values once the globals are initialised. A value whose
+ /// global is gone, is no longer `keep`, or changed type is dropped.
+ pub fn restore(&mut self, values: Vec<(String, String, HostValue)>) {
+ self.restore = values;
+ }
+
+ fn apply_restore(&mut self) {
+ for (name, ty, v) in std::mem::take(&mut self.restore) {
+ let m = &self.module;
+ let Some(&(g, _)) = m
+ .kept
+ .iter()
+ .find(|(g, t)| m.globals[*g as usize] == name && *t == ty)
+ else {
+ continue;
+ };
+ self.globals[g as usize] = self.heap.import(&v);
+ }
+ }
+
+ /// Queue a call of function `f` with no arguments, as if it were an event:
+ /// how `test` blocks are run.
+ pub fn post_fn(&mut self, f: u32) {
+ self.mailbox.push_back((f, Vec::new()));
}
/// Bytes this process holds: heap objects, registers, globals, frames.
@@ -124,6 +242,9 @@ impl<S> Process<S> {
if let Status::Dead(m) = &self.status {
return Outcome::Died(m.clone());
}
+ if self.waiting {
+ return Outcome::Waiting;
+ }
let module = self.module.clone();
let m = &*module;
let mut fuel = fuel;
@@ -164,7 +285,7 @@ impl<S> Process<S> {
}
macro_rules! fail {
($msg:expr) => {{
- let msg = self.located(func_id, pc as u32, &$msg);
+ let msg = self.located(func_id, pc as u32 - 1, &$msg);
break 'events self.die(msg);
}};
}
@@ -297,6 +418,9 @@ impl<S> Process<S> {
let v = r!(src);
let done = self.frames.pop().unwrap();
let Some(caller) = self.frames.last() else {
+ if done.func == m.init && !self.restore.is_empty() {
+ self.apply_restore();
+ }
// The handler finished; on to the next event.
continue 'events;
};
@@ -320,15 +444,26 @@ impl<S> Process<S> {
));
};
let a = base + cb as usize;
+ let mut suspend = false;
+ let mut charged = 0;
let mut cx = Cx {
state: &mut self.state,
heap: &mut self.heap,
strings: &m.strings,
+ rng: &mut self.rng,
+ suspend: &mut suspend,
+ charged: &mut charged,
};
match hf(&mut cx, &self.regs[a..a + argc as usize]) {
Ok(v) => r!(dst) = v,
Err(e) => fail!(e),
}
+ fuel = fuel.saturating_sub(charged);
+ if suspend {
+ save!();
+ self.waiting = true;
+ break 'events Outcome::Waiting;
+ }
}
Op::HostConst { dst, c } => match &plat.consts[c as usize] {
Some(v) => r!(dst) = self.heap.import(v),
@@ -363,7 +498,7 @@ impl<S> Process<S> {
}
Op::MakeList { dst, base: b, n } => {
let s = base + b as usize;
- let f: Box<[Value]> = self.regs[s..s + n as usize].into();
+ let f: Vec<Value> = self.regs[s..s + n as usize].into();
r!(dst) = self.heap.alloc(Obj::List(f));
}
Op::ListGet { dst, list, idx } => {
@@ -443,6 +578,68 @@ impl<S> Process<S> {
.unwrap_or_default();
fail!(format!("panic: {text}"));
}
+ Op::Assert { cond, msg } => {
+ if !r!(cond).bool() {
+ let text = self.heap.str(r!(msg), &m.strings).to_string();
+ fail!(format!("assertion failed: {text}"));
+ }
+ }
+ Op::Log { level, src } => {
+ let text = self.heap.str(r!(src), &m.strings).to_string();
+ let line = m.funcs[func_id as usize].lines[pc - 1];
+ if self.log.len() >= LOG_CAP {
+ self.log.remove(0);
+ }
+ let level = if level == 0 { Level::Info } else { Level::Warn };
+ self.log.push(LogLine { level, line, text });
+ }
+ Op::MakeClosure { dst, f, base: b, n } => {
+ let s = base + b as usize;
+ let caps: Box<[Value]> = self.regs[s..s + n as usize].into();
+ r!(dst) = self.heap.alloc(Obj::Closure(f, caps));
+ }
+ Op::CallValue { f: fr, base: cb, dst } => {
+ safepoint!();
+ if self.frames.len() >= 2_000 {
+ fail!("too deep: more than 2000 calls in progress");
+ }
+ let Some(Obj::Closure(f, caps)) = self.heap.get(r!(fr)) else {
+ fail!("called something that is not a function");
+ };
+ let f = *f;
+ save!();
+ let nb = base + cb as usize;
+ let callee = &m.funcs[f as usize];
+ let n = callee.nregs as usize;
+ if self.regs.len() < nb + n {
+ self.regs.resize(nb + n, Value::Unit);
+ }
+ for (slot, v) in callee.captures.iter().zip(caps.iter()) {
+ self.regs[nb + *slot as usize] = *v;
+ }
+ self.frames.push(Frame {
+ func: f,
+ pc: 0,
+ base: nb as u32,
+ ret: dst,
+ });
+ func_id = f;
+ code = &m.funcs[f as usize].code[..];
+ pc = 0;
+ base = nb;
+ }
+ Op::Std { f, base: b, dst } => {
+ let s = base + b as usize;
+ let args = &self.regs[s..s + f.arity()];
+ match crate::stdlib::call(f, &mut self.heap, &m.strings, args, mem_limit) {
+ Ok(v) => r!(dst) = v,
+ Err(e) => fail!(e),
+ }
+ }
+ Op::ListPushMut { list, val } => {
+ let (l, v) = (r!(list), r!(val));
+ self.heap.list_push(l, v);
+ }
}
}
};
@@ -450,6 +647,7 @@ impl<S> Process<S> {
self.status = match &out {
Outcome::Idle => Status::Idle,
Outcome::Paused => Status::Paused,
+ Outcome::Waiting => Status::Waiting,
Outcome::Died(m) => Status::Dead(m.clone()),
};
out
diff --git a/docs/design.md b/docs/design.md
index f824fbd..9e44581 100644
--- a/docs/design.md
+++ b/docs/design.md
@@ -52,9 +52,37 @@ on timer() {
```
- 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.
+ `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, 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 })`).
+- Generic functions: `fn first<T>(xs: List<T>) -> Option<T>`, compiled once per
+ set of types they are called with. Generic types (`enum Tree<T>`) are not
+ built.
+- 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<T, E>`, 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.
@@ -79,8 +107,20 @@ p.bind("Prim.set_geo", |cx, a| { let f = cx.fields(a[0]); /* … */ Ok(Value::Un
```
`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.
+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.
## The runtime
@@ -94,6 +134,11 @@ same script runs on another host by being compiled against its platform.
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
@@ -108,28 +153,30 @@ the same scenarios as Cartopolis's Luau/Bun comparison (s693,
| 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 |
+| 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.
-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.
+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:
-- Content-addressed modules: one compiled module per source hash, shared.
-- Closures and functions as values; user generics; methods (`xs.len()`);
- modules and imports.
+- Generic types (`enum Tree<T>`, `type Pair<A, B>`).
+- 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
@@ -143,4 +190,10 @@ Known gaps in what is built:
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.
+- Fuel counts instructions; 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.