From 4af578d75570a7e50987344628471d3790b41e8c Mon Sep 17 00:00:00 2001 From: Mia Date: Tue, 27 Oct 2026 21:02:44 +0100 Subject: [PATCH 1/5] feat(runtime): embed Chasm scripts with typed host callbacks Let Rust applications compile and call scalar scripts without a C toolchain. Capture output, bind host capabilities at compilation, and return source and execution failures as values. Heap-backed call and control stacks keep script recursion off the host stack; per-call fuel stops runaway execution. Seal callback conversions so declared host signatures cannot drift from the values callbacks return. Scripts can call home; they cannot rewrite the guest list. Co-Authored-By: Claude Opus 5.5 Co-Authored-By: GPT-6.1 Sol --- host/examples/embed.rs | 84 ++++++++ host/src/diag.rs | 14 +- host/src/embed.rs | 475 +++++++++++++++++++++++++++++++++++++++++ host/src/emit_c.rs | 20 +- host/src/interp.rs | 414 ++++++++++++++++++++++++----------- host/src/ir.rs | 34 ++- host/src/lib.rs | 44 ++++ host/src/lower.rs | 99 ++++++--- host/src/main.rs | 34 ++- host/src/validate.rs | 59 +++-- 10 files changed, 1062 insertions(+), 215 deletions(-) create mode 100644 host/examples/embed.rs create mode 100644 host/src/embed.rs create mode 100644 host/src/lib.rs diff --git a/host/examples/embed.rs b/host/examples/embed.rs new file mode 100644 index 0000000..8fa9f49 --- /dev/null +++ b/host/examples/embed.rs @@ -0,0 +1,84 @@ +//! Runs a Chasm script inside a Rust application. +//! +//! The host owns a wallet balance and lends scripts two capabilities: +//! `withdraw` and `log`. Each call's failure comes back as a value, and the +//! runtime keeps working afterwards. +//! +//! Run with `cargo run --example embed` from `host/`. + +use std::cell::Cell; +use std::rc::Rc; + +use chasm::{Runtime, Value}; + +const SCRIPT: &str = r#" +fn checkout(price: Int, quantity: Int) -> Int { + let total = price * quantity + let left = withdraw(total) + log("paid") + print(left) + return left +} + +fn spin() { + while true { + } +} +"#; + +fn main() { + let balance = Rc::new(Cell::new(100)); + let mut runtime = Runtime::new(); + + let wallet = Rc::clone(&balance); + runtime + .register("withdraw", move |amount: i32| -> Result { + if amount < 0 { + return Err(format!("cannot withdraw a negative amount ({amount})")); + } + if amount > wallet.get() { + return Err(format!( + "cannot withdraw {amount}; the balance is {}", + wallet.get() + )); + } + wallet.set(wallet.get() - amount); + Ok(wallet.get()) + }) + .expect("`withdraw` is a valid, unused name"); + runtime + .register("log", |message: String| -> Result<(), String> { + println!(" host log: {message}"); + Ok(()) + }) + .expect("`log` is a valid, unused name"); + + let script = match runtime.compile(SCRIPT) { + Ok(script) => script, + Err(error) => { + eprintln!("{error}"); + std::process::exit(1); + } + }; + runtime.set_fuel(10_000); + + let calls: [(&str, Vec); 5] = [ + ("checkout", vec![30.into(), 2.into()]), + ("checkout", vec![50.into(), 1.into()]), + ("checkout", vec![i32::MAX.into(), 2.into()]), + ("spin", vec![]), + ("checkout", vec![10.into(), 1.into()]), + ]; + for (name, args) in calls { + println!("{name}({args:?})"); + match runtime.call(&script, name, &args) { + Ok(value) => println!(" returned {value:?}"), + Err(error) => println!(" failed: {error}"), + } + let printed = runtime.take_output(); + if !printed.is_empty() { + print!(" script printed: {printed}"); + } + println!(" balance: {}", balance.get()); + } +} diff --git a/host/src/diag.rs b/host/src/diag.rs index 676e5a7..27133f1 100644 --- a/host/src/diag.rs +++ b/host/src/diag.rs @@ -9,7 +9,7 @@ pub struct Span { } /// One compile error, rendered as `PATH:LINE:COLUMN: error: MESSAGE`. -#[derive(Debug)] +#[derive(Clone, Debug, PartialEq, Eq)] pub struct Diagnostic { pub span: Span, pub message: String, @@ -24,8 +24,16 @@ impl Diagnostic { } pub fn render(&self, path: &str) -> String { - format!( - "{path}:{}:{}: error: {}", + format!("{path}:{self}") + } +} + +/// `LINE:COLUMN: error: MESSAGE`, for source without a path. +impl std::fmt::Display for Diagnostic { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + write!( + f, + "{}:{}: error: {}", self.span.line, self.span.col, self.message ) } diff --git a/host/src/embed.rs b/host/src/embed.rs new file mode 100644 index 0000000..5a30e99 --- /dev/null +++ b/host/src/embed.rs @@ -0,0 +1,475 @@ +//! Embedding API: compile Chasm source in memory, register host functions, +//! and call Chasm functions from Rust. `docs/embedding.md` is the guide. + +use std::fmt; +use std::sync::atomic::{AtomicU64, Ordering}; + +use crate::diag::{Diagnostic, Span}; +use crate::interp::{self, Env, Trap}; +use crate::ir::{HostSig, Program, Ty}; +use crate::lexer::{self, Tok}; + +/// Fuel for each call unless the host sets a budget: one unit per IR +/// statement executed and per loop iteration. +const DEFAULT_FUEL: u64 = 1_000_000; + +static NEXT_RUNTIME: AtomicU64 = AtomicU64::new(0); + +/// A scalar crossing between Rust and Chasm: `Int`, `Bool`, or `String`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Value { + Int(i32), + Bool(bool), + String(String), +} + +impl Value { + fn ty(&self) -> Ty { + match self { + Value::Int(_) => Ty::Int, + Value::Bool(_) => Ty::Bool, + Value::String(_) => Ty::String, + } + } + + fn into_interp(self) -> interp::Value { + match self { + Value::Int(n) => interp::Value::Int(n), + Value::Bool(b) => interp::Value::Bool(b), + Value::String(text) => interp::Value::Str(text.into()), + } + } + + fn from_interp(value: interp::Value) -> Self { + match value { + interp::Value::Int(n) => Value::Int(n), + interp::Value::Bool(b) => Value::Bool(b), + interp::Value::Str(text) => Value::String(text.to_string()), + } + } +} + +impl From for Value { + fn from(n: i32) -> Self { + Value::Int(n) + } +} + +impl From for Value { + fn from(b: bool) -> Self { + Value::Bool(b) + } +} + +impl From for Value { + fn from(text: String) -> Self { + Value::String(text) + } +} + +impl From<&str> for Value { + fn from(text: &str) -> Self { + Value::String(text.into()) + } +} + +/// Compiles Chasm source and calls its functions, with the host functions +/// registered on it. +/// +/// A runtime keeps no execution state between calls. Each call starts with +/// a fresh fuel budget and call stack, so a call that fails leaves the +/// runtime ready for the next one. Host callbacks run on the calling thread +/// and are trusted: fuel does not interrupt them, and a callback panic +/// unwinds out of [`Runtime::call`]. +pub struct Runtime { + id: u64, + /// Append-only, so a compiled script's host indices stay valid. + hosts: Vec, + output: Vec, + fuel: u64, +} + +type Callback = Box) -> Result, String>>; + +struct Host { + sig: HostSig, + callback: Callback, +} + +/// Checked source, ready to call. Calls to host functions are bound when the +/// script compiles, so it runs only on the runtime that compiled it. +pub struct Script { + runtime: u64, + program: Program, +} + +impl Default for Runtime { + fn default() -> Self { + Runtime { + id: NEXT_RUNTIME.fetch_add(1, Ordering::Relaxed), + hosts: Vec::new(), + output: Vec::new(), + fuel: DEFAULT_FUEL, + } + } +} + +impl Runtime { + /// A runtime with no host functions and the default fuel budget. + pub fn new() -> Self { + Self::default() + } + + /// Sets the fuel each later call starts with. A call fails with + /// [`CallError::OutOfFuel`] when it would execute an IR statement or + /// start a loop iteration with none left. + pub fn set_fuel(&mut self, fuel: u64) { + self.fuel = fuel; + } + + /// Makes `function` callable by `name` from scripts compiled afterwards. + /// Its Rust signature sets its Chasm one: parameters and the `Ok` value + /// are `i32` (Int), `bool` (Bool), or `String`; `()` returns no value. + /// An `Err` stops the script with [`CallError::Host`]. + /// + /// ``` + /// let mut runtime = chasm::Runtime::new(); + /// runtime + /// .register("double", |n: i32| -> Result { + /// n.checked_mul(2).ok_or_else(|| "too large".into()) + /// }) + /// .unwrap(); + /// ``` + pub fn register(&mut self, name: &str, mut function: F) -> Result<(), RegisterError> + where + F: HostFn, + { + if !is_identifier(name) { + return Err(RegisterError::InvalidName(name.into())); + } + if name == "print" || self.hosts.iter().any(|host| host.sig.name == name) { + return Err(RegisterError::Taken(name.into())); + } + let (params, ret) = F::signature(); + self.hosts.push(Host { + sig: HostSig { + name: name.into(), + params, + ret, + }, + callback: Box::new(move |args| function.call(args)), + }); + Ok(()) + } + + /// Checks `source` as a library: a list of functions, with no `main` + /// required. It may call the host functions registered so far. + pub fn compile(&self, source: &str) -> Result { + let hosts: Vec = self.hosts.iter().map(|host| host.sig.clone()).collect(); + let program = crate::compile(source, &hosts, false)?; + Ok(Script { + runtime: self.id, + program, + }) + } + + /// Calls the script function `name` and returns its result, or `None` + /// when it returns no value. Arguments are checked against its + /// parameters before anything runs. + pub fn call( + &mut self, + script: &Script, + name: &str, + args: &[Value], + ) -> Result, CallError> { + if script.runtime != self.id { + return Err(CallError::ForeignScript); + } + let program = &script.program; + let Some(func) = program.functions.iter().position(|f| f.name == name) else { + return Err(CallError::UnknownFunction(name.into())); + }; + let params = &program.functions[func].locals[..program.functions[func].param_count]; + if args.len() != params.len() { + return Err(CallError::Arguments(format!( + "`{name}` takes {} argument(s), but {} were given", + params.len(), + args.len() + ))); + } + for (arg, param) in args.iter().zip(params) { + if arg.ty() != param.ty { + return Err(CallError::Arguments(format!( + "argument `{}` of `{name}` expects {}, found {}", + param.name, + param.ty.name(), + arg.ty().name() + ))); + } + } + + let args = args.iter().cloned().map(Value::into_interp).collect(); + let hosts = &mut self.hosts; + let mut host = |id: usize, args| (hosts[id].callback)(args); + let env = Env { + out: &mut self.output, + host: &mut host, + fuel: Some(self.fuel), + }; + match interp::call(program, func, args, env) { + Ok(value) => Ok(value.map(Value::from_interp)), + Err(Trap::Panic { message, span }) => Err(CallError::Panic { message, span }), + Err(Trap::OutOfFuel) => Err(CallError::OutOfFuel), + Err(Trap::Host { + host, + message, + span, + }) => Err(CallError::Host { + function: program.hosts[host].name.clone(), + message, + span, + }), + Err(Trap::Output(_)) => unreachable!("writing to a Vec cannot fail"), + } + } + + /// Returns the text `print` has written since the last call to this + /// method, including output from calls that failed. + pub fn take_output(&mut self) -> String { + String::from_utf8(std::mem::take(&mut self.output)).expect("`print` writes UTF-8 text") + } +} + +/// Whether scripts can call a function by this name: a single identifier, +/// not a keyword or reserved word. +fn is_identifier(name: &str) -> bool { + matches!( + lexer::lex(name).as_slice(), + [ident, end] if ident.tok == Tok::Ident(name.into()) && end.tok == Tok::Eof + ) +} + +mod sealed { + pub trait Sealed {} + pub trait Callable {} + impl Sealed for i32 {} + impl Sealed for bool {} + impl Sealed for String {} + impl Sealed for () {} +} + +/// A Rust type that stands for a Chasm type in a host function signature: +/// `i32` is Int, `bool` is Bool, `String` is String. +pub trait ScriptType: sealed::Sealed + Sized { + #[doc(hidden)] + const TY: Ty; + #[doc(hidden)] + fn from_value(value: interp::Value) -> Self; + #[doc(hidden)] + fn into_value(self) -> interp::Value; +} + +impl ScriptType for i32 { + const TY: Ty = Ty::Int; + fn from_value(value: interp::Value) -> Self { + match value { + interp::Value::Int(n) => n, + _ => unreachable!("the checker matched the argument types"), + } + } + fn into_value(self) -> interp::Value { + interp::Value::Int(self) + } +} + +impl ScriptType for bool { + const TY: Ty = Ty::Bool; + fn from_value(value: interp::Value) -> Self { + match value { + interp::Value::Bool(b) => b, + _ => unreachable!("the checker matched the argument types"), + } + } + fn into_value(self) -> interp::Value { + interp::Value::Bool(self) + } +} + +impl ScriptType for String { + const TY: Ty = Ty::String; + fn from_value(value: interp::Value) -> Self { + match value { + interp::Value::Str(text) => text.to_string(), + _ => unreachable!("the checker matched the argument types"), + } + } + fn into_value(self) -> interp::Value { + interp::Value::Str(self.into()) + } +} + +/// The `Ok` type of a host function: a [`ScriptType`], or `()` for a +/// function that returns no value. +pub trait HostReturn: sealed::Sealed { + #[doc(hidden)] + const TY: Option; + #[doc(hidden)] + fn into_value(self) -> Option; +} + +impl HostReturn for T { + const TY: Option = Some(T::TY); + fn into_value(self) -> Option { + Some(ScriptType::into_value(self)) + } +} + +impl HostReturn for () { + const TY: Option = None; + fn into_value(self) -> Option { + None + } +} + +/// A Rust closure or function that [`Runtime::register`] accepts: up to four +/// [`ScriptType`] parameters, returning `Result` where `R` is a +/// [`HostReturn`]. `Args` is the parameter tuple; Rust infers it. +/// This trait is sealed so a registration cannot supply a signature that +/// disagrees with its argument or return conversions. +pub trait HostFn: sealed::Callable + 'static { + #[doc(hidden)] + fn signature() -> (Vec, Option); + #[doc(hidden)] + fn call(&mut self, args: Vec) -> Result, String>; +} + +macro_rules! host_fn { + ($($arg:ident),*) => { + impl sealed::Callable<($($arg,)*)> for F + where + F: FnMut($($arg),*) -> Result + 'static, + R: HostReturn, + $($arg: ScriptType,)* + {} + + impl HostFn<($($arg,)*)> for F + where + F: FnMut($($arg),*) -> Result + 'static, + R: HostReturn, + $($arg: ScriptType,)* + { + fn signature() -> (Vec, Option) { + (vec![$($arg::TY),*], R::TY) + } + + #[allow(non_snake_case, unused_mut, unused_variables)] + fn call(&mut self, args: Vec) -> Result, String> { + let mut args = args.into_iter(); + $(let $arg = $arg::from_value(args.next().expect("the checker matched the arity"));)* + self($($arg),*).map(HostReturn::into_value) + } + } + }; +} + +host_fn!(); +host_fn!(A); +host_fn!(A, B); +host_fn!(A, B, C); +host_fn!(A, B, C, D); + +/// Source that failed to compile. +#[derive(Debug)] +pub enum CompileError { + /// The source is invalid. Diagnostics follow the order `docs/alpha.md` + /// describes. + Source(Vec), + /// The compiler rejected its own output: a compiler bug, not a source + /// error. + Internal(String), +} + +/// A call that did not finish. Effects that happened before the failure, +/// such as host callbacks and `print` output, are not rolled back. +#[derive(Debug)] +pub enum CallError { + /// The script has no function by this name. Nothing ran. + UnknownFunction(String), + /// The arguments do not match the function's parameters. Nothing ran. + Arguments(String), + /// The script was compiled by a different runtime. Nothing ran. + ForeignScript, + /// A Chasm panic: `integer overflow`, `division by zero`, or + /// `call depth limit exceeded`, at the operation or call that caused it. + Panic { message: &'static str, span: Span }, + /// The call used up its fuel. + OutOfFuel, + /// The host function called at `span` returned an error. + Host { + function: String, + message: String, + span: Span, + }, +} + +/// A host function name that [`Runtime::register`] refused. +#[derive(Debug, PartialEq, Eq)] +pub enum RegisterError { + /// Scripts cannot call this name: it is not an identifier, or it is a + /// keyword or reserved word. + InvalidName(String), + /// `print` or an already registered host function has this name. + Taken(String), +} + +impl fmt::Display for CompileError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + CompileError::Source(diagnostics) => { + let lines: Vec = diagnostics.iter().map(|d| d.to_string()).collect(); + f.write_str(&lines.join("\n")) + } + CompileError::Internal(error) => { + write!(f, "internal compiler error: invalid IR {error}") + } + } + } +} + +impl fmt::Display for CallError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + CallError::UnknownFunction(name) => write!(f, "the script has no function `{name}`"), + CallError::Arguments(message) => f.write_str(message), + CallError::ForeignScript => f.write_str("the script was compiled by another runtime"), + CallError::Panic { message, span } => { + write!(f, "panic: {message} at {}:{}", span.line, span.col) + } + CallError::OutOfFuel => f.write_str("the call ran out of fuel"), + CallError::Host { + function, + message, + span, + } => write!( + f, + "host function `{function}` failed at {}:{}: {message}", + span.line, span.col + ), + } + } +} + +impl fmt::Display for RegisterError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + RegisterError::InvalidName(name) => { + write!(f, "`{name}` is not a name scripts can call") + } + RegisterError::Taken(name) => write!(f, "a function named `{name}` already exists"), + } + } +} + +impl std::error::Error for CompileError {} +impl std::error::Error for CallError {} +impl std::error::Error for RegisterError {} diff --git a/host/src/emit_c.rs b/host/src/emit_c.rs index 8ceb336..7a516b2 100644 --- a/host/src/emit_c.rs +++ b/host/src/emit_c.rs @@ -8,7 +8,7 @@ use std::fmt::Write; use crate::ir::{ - BinOp, Function, MAX_CALL_DEPTH, Operand, PANIC_CALL_DEPTH, PANIC_DIVIDE_BY_ZERO, + BinOp, Callee, Function, MAX_CALL_DEPTH, Operand, PANIC_CALL_DEPTH, PANIC_DIVIDE_BY_ZERO, PANIC_OVERFLOW, Program, Rvalue, Stmt, Ty, }; @@ -37,7 +37,8 @@ pub fn emit(program: &Program, source_path: &str) -> String { c.push('\n'); emit_function(&mut c, program, function); } - let main = &program.functions[program.main].name; + let main = program.main.expect("the CLI compiles programs with `main`"); + let main = &program.functions[main].name; let _ = write!( c, "\nint main(void) {{\n chasm_fn_{main}();\n return 0;\n}}\n" @@ -196,9 +197,9 @@ impl Emitter<'_> { match stmt { Stmt::Assign { dst, - value: Rvalue::Call { func, args, span }, + value: Rvalue::Call { callee, args, span }, } => { - let call = self.call(*func, args); + let call = self.call(*callee, args); self.line(depth, &format!("chasm_enter({}, {});", span.line, span.col)); self.line(depth, &format!("l{dst} = {call};")); self.line(depth, "chasm_depth--;"); @@ -207,8 +208,8 @@ impl Emitter<'_> { let value = self.rvalue(value); self.line(depth, &format!("l{dst} = {value};")); } - Stmt::Call { func, args, span } => { - let call = self.call(*func, args); + Stmt::Call { callee, args, span } => { + let call = self.call(*callee, args); self.line(depth, &format!("chasm_enter({}, {});", span.line, span.col)); self.line(depth, &format!("{call};")); self.line(depth, "chasm_depth--;"); @@ -280,11 +281,14 @@ impl Emitter<'_> { ) } Rvalue::Not(operand) => format!("!{}", operand_c(*operand)), - Rvalue::Call { func, args, .. } => self.call(*func, args), + Rvalue::Call { callee, args, .. } => self.call(*callee, args), } } - fn call(&self, func: usize, args: &[Operand]) -> String { + fn call(&self, callee: Callee, args: &[Operand]) -> String { + let Callee::Fn(func) = callee else { + unreachable!("the CLI registers no host functions") + }; let args: Vec = args.iter().map(|arg| operand_c(*arg)).collect(); let name = &self.program.functions[func].name; format!("chasm_fn_{name}({})", args.join(", ")) diff --git a/host/src/interp.rs b/host/src/interp.rs index 489f1f7..89b5d81 100644 --- a/host/src/interp.rs +++ b/host/src/interp.rs @@ -1,177 +1,323 @@ //! Reference interpreter over validated IR. +//! +//! Execution keeps calls, locals, and block cursors in heap vectors, so Chasm +//! call and block nesting never consumes the host thread's stack. Each call +//! into the interpreter starts with fresh stacks, fuel, and call depth. use std::io::{self, Write}; +use std::rc::Rc; use crate::diag::Span; use crate::ir::{ - BinOp, FuncId, Function, MAX_CALL_DEPTH, Operand, PANIC_CALL_DEPTH, PANIC_DIVIDE_BY_ZERO, - PANIC_OVERFLOW, Program, Rvalue, Stmt, Ty, + BinOp, Callee, FuncId, HostId, LocalId, MAX_CALL_DEPTH, Operand, PANIC_CALL_DEPTH, + PANIC_DIVIDE_BY_ZERO, PANIC_OVERFLOW, Program, Rvalue, Stmt, Ty, }; /// Why a run stopped early. pub enum Trap { - Panic { message: &'static str, span: Span }, + Panic { + message: &'static str, + span: Span, + }, + /// The run used up its fuel before finishing. + OutOfFuel, + /// A host function returned an error from the call at `span`. + Host { + host: HostId, + message: String, + span: Span, + }, Output(io::Error), } -/// Runs `main`, writing `print` output to `out`. +/// A runtime value. Strings are shared rather than indexed, so a string +/// outlives the program whose literal or host call produced it. +#[derive(Clone, PartialEq, Eq)] +pub enum Value { + Int(i32), + Bool(bool), + Str(Rc), +} + +/// Runs a host function. Arguments match its signature; the result must too. +pub type HostCall<'h> = dyn FnMut(HostId, Vec) -> Result, String> + 'h; + +/// Everything a run reaches outside the program. +pub struct Env<'e> { + /// Receives `print` output. + pub out: &'e mut dyn Write, + pub host: &'e mut HostCall<'e>, + /// Statements and loop iterations the run may execute; `None` is + /// unlimited. + pub fuel: Option, +} + +/// Runs `main` with unlimited fuel and no host functions, writing `print` +/// output to `out`. pub fn run(program: &Program, out: &mut dyn Write) -> Result<(), Trap> { + let main = program.main.expect("the CLI compiles programs with `main`"); + let mut no_hosts = |_, _| unreachable!("the CLI registers no host functions"); + let env = Env { + out, + host: &mut no_hosts, + fuel: None, + }; + call(program, main, Vec::new(), env).map(|_| ()) +} + +/// Calls `func` with arguments that match its parameters and returns its +/// result. +pub fn call( + program: &Program, + func: FuncId, + args: Vec, + env: Env, +) -> Result, Trap> { let mut interp = Interp { program, - out, - depth: 1, + env, + locals: Vec::new(), + calls: Vec::new(), + control: Vec::new(), }; - interp.call(program.main, &[])?; - Ok(()) + let base = interp.enter(func, None); + for (slot, arg) in interp.locals[base..].iter_mut().zip(args) { + *slot = arg; + } + interp.execute() } -#[derive(Clone, Copy, PartialEq, Eq)] -enum Value { - Int(i32), - Bool(bool), - Str(usize), +struct Call { + locals_base: usize, + control_base: usize, + /// Absolute slot in the caller, or `None` when the result is discarded. + dst: Option, } -enum Flow { - Next, - Break, - Return(Option), +struct Block<'a> { + stmts: &'a [Stmt], + next: usize, + repeat: bool, } -struct Interp<'a> { +struct Interp<'a, 'e> { program: &'a Program, - out: &'a mut dyn Write, - /// Active calls, counting `main`. - depth: u32, + env: Env<'e>, + /// Contiguous local slots for active calls, reclaimed on return. + locals: Vec, + /// Active calls, counting the entry call; no tail-call elision at the + /// depth limit. + calls: Vec, + control: Vec>, } -impl Interp<'_> { - fn call(&mut self, func: FuncId, args: &[Value]) -> Result, Trap> { +impl<'a> Interp<'a, '_> { + /// Pushes a call to `func` with zeroed locals and returns where they + /// start. + fn enter(&mut self, func: FuncId, dst: Option) -> usize { let function = &self.program.functions[func]; - let mut locals: Vec = function - .locals - .iter() - .map(|local| match local.ty { + let locals_base = self.locals.len(); + self.locals + .extend(function.locals.iter().map(|local| match local.ty { Ty::Int => Value::Int(0), Ty::Bool => Value::Bool(false), - Ty::String => Value::Str(0), - }) - .collect(); - locals[..args.len()].copy_from_slice(args); - match self.block(function, &mut locals, &function.body)? { - Flow::Return(value) => Ok(value), - Flow::Next => Ok(None), - Flow::Break => unreachable!("the validator rejects `break` outside a loop"), - } + Ty::String => Value::Str(Rc::from("")), + })); + self.calls.push(Call { + locals_base, + control_base: self.control.len(), + dst, + }); + self.control.push(Block { + stmts: &function.body, + next: 0, + repeat: false, + }); + locals_base } - fn block( - &mut self, - function: &Function, - locals: &mut [Value], - stmts: &[Stmt], - ) -> Result { - for stmt in stmts { - match self.stmt(function, locals, stmt)? { - Flow::Next => {} - flow @ (Flow::Break | Flow::Return(_)) => return Ok(flow), - } - } - Ok(Flow::Next) + /// Ends the active call. Returns the value when nothing in the program + /// receives it: the entry call's result, or a discarded one. + fn leave(&mut self, value: Option) -> Option { + let call = self.calls.pop().expect("an active call"); + // Return skips all pending branches and loops in this call, while its + // caller's cursor already points to the statement after the call. + self.control.truncate(call.control_base); + self.locals.truncate(call.locals_base); + let Some(dst) = call.dst else { + return value; + }; + self.locals[dst] = value.expect("the validator requires a return value"); + None } - fn stmt( - &mut self, - function: &Function, - locals: &mut [Value], - stmt: &Stmt, - ) -> Result { - match stmt { - Stmt::Assign { dst, value } => { - locals[*dst] = self.rvalue(locals, value)?; - } - Stmt::Call { func, args, span } => { - self.invoke(locals, *func, args, *span)?; - } - Stmt::Print(operand) => { - let result = match read(locals, *operand) { - Value::Int(n) => writeln!(self.out, "{n}"), - Value::Bool(b) => writeln!(self.out, "{b}"), - Value::Str(id) => { - let text = &self.program.strings[id]; - self.out + fn execute(&mut self) -> Result, Trap> { + loop { + let call = self.calls.last().expect("an active call"); + let base = call.locals_base; + let control_base = call.control_base; + let block = self.control.last_mut().expect("an active block"); + let Some(stmt) = block.stmts.get(block.next) else { + if block.repeat { + // Reuse the loop cursor: iterations do not grow the stack. + // Charging the iteration bounds even a loop with no body. + spend(&mut self.env.fuel)?; + block.next = 0; + } else { + self.control.pop(); + if self.control.len() == control_base { + let value = self.leave(None); + if self.calls.is_empty() { + return Ok(value); + } + } + } + continue; + }; + block.next += 1; + spend(&mut self.env.fuel)?; + let locals = Slots { + locals: &self.locals[base..], + strings: &self.program.strings, + }; + match stmt { + Stmt::Assign { + dst, + value: Rvalue::Call { callee, args, span }, + } => self.invoke(*callee, args, *span, Some(*dst))?, + Stmt::Assign { dst, value } => { + self.locals[base + *dst] = rvalue(locals, value)?; + } + Stmt::Call { callee, args, span } => self.invoke(*callee, args, *span, None)?, + Stmt::Print(operand) => { + let result = match read(locals, *operand) { + Value::Int(n) => writeln!(self.env.out, "{n}"), + Value::Bool(b) => writeln!(self.env.out, "{b}"), + Value::Str(text) => self + .env + .out .write_all(text.as_bytes()) - .and_then(|()| self.out.write_all(b"\n")) + .and_then(|()| self.env.out.write_all(b"\n")), + }; + result.map_err(Trap::Output)?; + } + Stmt::If { + cond, + then_body, + else_body, + } => { + let stmts = if read(locals, *cond) == Value::Bool(true) { + then_body + } else { + else_body + }; + self.control.push(Block { + stmts, + next: 0, + repeat: false, + }); + } + Stmt::Loop(stmts) => { + self.control.push(Block { + stmts, + next: 0, + repeat: true, + }); + } + Stmt::Break => { + let loop_index = self.control[control_base..] + .iter() + .rposition(|block| block.repeat) + .expect("the validator rejects `break` outside a loop"); + self.control.truncate(control_base + loop_index); + } + Stmt::Return(value) => { + let value = value.map(|operand| read(locals, operand)); + let value = self.leave(value); + if self.calls.is_empty() { + return Ok(value); } - }; - result.map_err(Trap::Output)?; - } - Stmt::If { - cond, - then_body, - else_body, - } => { - let body = if read(locals, *cond) == Value::Bool(true) { - then_body - } else { - else_body - }; - return self.block(function, locals, body); - } - Stmt::Loop(body) => loop { - match self.block(function, locals, body)? { - Flow::Next => {} - Flow::Break => return Ok(Flow::Next), - flow @ Flow::Return(_) => return Ok(flow), } - }, - Stmt::Break => return Ok(Flow::Break), - Stmt::Return(value) => { - return Ok(Flow::Return(value.map(|operand| read(locals, operand)))); } } - Ok(Flow::Next) - } - - fn rvalue(&mut self, locals: &[Value], rvalue: &Rvalue) -> Result { - Ok(match rvalue { - Rvalue::Use(operand) => read(locals, *operand), - Rvalue::Binary { op, lhs, rhs, span } => { - binary(*op, read(locals, *lhs), read(locals, *rhs), *span)? - } - Rvalue::Neg { operand, span } => { - let n = int(read(locals, *operand)); - Value::Int( - n.checked_neg() - .ok_or_else(|| panic(PANIC_OVERFLOW, *span))?, - ) - } - Rvalue::Not(operand) => Value::Bool(read(locals, *operand) != Value::Bool(true)), - Rvalue::Call { func, args, span } => self - .invoke(locals, *func, args, *span)? - .expect("the validator rejects using a call without a value"), - }) } fn invoke( &mut self, - locals: &[Value], - func: FuncId, + callee: Callee, args: &[Operand], span: Span, - ) -> Result, Trap> { - let args: Vec = args.iter().map(|arg| read(locals, *arg)).collect(); - if self.depth >= MAX_CALL_DEPTH { + dst: Option, + ) -> Result<(), Trap> { + if self.calls.len() >= MAX_CALL_DEPTH as usize { return Err(panic(PANIC_CALL_DEPTH, span)); } - self.depth += 1; - let result = self.call(func, &args); - self.depth -= 1; - result + let caller_base = self.calls.last().expect("an active caller").locals_base; + let dst = dst.map(|dst| caller_base + dst); + match callee { + Callee::Fn(func) => { + let callee_base = self.enter(func, dst); + // Arguments are already lowered operands. Read caller slots + // even when growing the shared vector relocated it. + for (index, arg) in args.iter().enumerate() { + let caller = Slots { + locals: &self.locals[caller_base..callee_base], + strings: &self.program.strings, + }; + self.locals[callee_base + index] = read(caller, *arg); + } + } + Callee::Host(host) => { + let caller = Slots { + locals: &self.locals[caller_base..], + strings: &self.program.strings, + }; + let args = args.iter().map(|arg| read(caller, *arg)).collect(); + let result = (self.env.host)(host, args).map_err(|message| Trap::Host { + host, + message, + span, + })?; + if let Some(dst) = dst { + self.locals[dst] = result.expect("the host returns its declared type"); + } + } + } + Ok(()) + } +} + +/// Charges one unit of fuel, failing when none is left. +fn spend(fuel: &mut Option) -> Result<(), Trap> { + match fuel { + None => Ok(()), + Some(0) => Err(Trap::OutOfFuel), + Some(left) => { + *left -= 1; + Ok(()) + } } } -fn binary(op: BinOp, lhs: Value, rhs: Value, span: Span) -> Result { +fn rvalue(locals: Slots, rvalue: &Rvalue) -> Result { + Ok(match rvalue { + Rvalue::Use(operand) => read(locals, *operand), + Rvalue::Binary { op, lhs, rhs, span } => { + binary(*op, &read(locals, *lhs), &read(locals, *rhs), *span)? + } + Rvalue::Neg { operand, span } => { + let n = int(&read(locals, *operand)); + Value::Int( + n.checked_neg() + .ok_or_else(|| panic(PANIC_OVERFLOW, *span))?, + ) + } + Rvalue::Not(operand) => Value::Bool(read(locals, *operand) != Value::Bool(true)), + Rvalue::Call { .. } => unreachable!("calls suspend in the execution loop"), + }) +} + +fn binary(op: BinOp, lhs: &Value, rhs: &Value, span: Span) -> Result { let overflow = || panic(PANIC_OVERFLOW, span); let divide_by_zero = || panic(PANIC_DIVIDE_BY_ZERO, span); Ok(match op { @@ -193,18 +339,26 @@ fn binary(op: BinOp, lhs: Value, rhs: Value, span: Span) -> Result }) } -fn read(locals: &[Value], operand: Operand) -> Value { +/// What an operand can name: the active call's locals and the program's +/// string literals. +#[derive(Clone, Copy)] +struct Slots<'s> { + locals: &'s [Value], + strings: &'s [Rc], +} + +fn read(slots: Slots, operand: Operand) -> Value { match operand { - Operand::Local(id) => locals[id], + Operand::Local(id) => slots.locals[id].clone(), Operand::Int(n) => Value::Int(n), Operand::Bool(b) => Value::Bool(b), - Operand::Str(id) => Value::Str(id), + Operand::Str(id) => Value::Str(Rc::clone(&slots.strings[id])), } } -fn int(value: Value) -> i32 { +fn int(value: &Value) -> i32 { match value { - Value::Int(n) => n, + Value::Int(n) => *n, Value::Bool(_) | Value::Str(_) => unreachable!("the validator checks operand types"), } } diff --git a/host/src/ir.rs b/host/src/ir.rs index 83c895f..1acb815 100644 --- a/host/src/ir.rs +++ b/host/src/ir.rs @@ -4,9 +4,12 @@ //! result in a variable. A backend executes statements in order and evaluates //! nothing implicitly, so source evaluation order survives unchanged. +use std::rc::Rc; + use crate::diag::Span; pub type FuncId = usize; +pub type HostId = usize; pub type LocalId = usize; pub type StrId = usize; @@ -29,9 +32,22 @@ impl Ty { pub struct Program { pub functions: Vec, - /// String literal contents, indexed by `StrId`. - pub strings: Vec, - pub main: FuncId, + /// Host functions the program was checked against, indexed by `HostId`. + pub hosts: Vec, + /// String literal contents, indexed by `StrId`. Shared so a running + /// program can hand a literal around without copying it. + pub strings: Vec>, + /// `fn main()`, when compiled as a program rather than a library. + pub main: Option, +} + +/// The signature of a function the embedding application provides. +#[derive(Clone)] +pub struct HostSig { + pub name: String, + pub params: Vec, + /// `None` for functions that return no value. + pub ret: Option, } pub struct Function { @@ -50,6 +66,14 @@ pub struct Local { pub ty: Ty, } +/// The function a call runs: one defined in the program, or one the host +/// registered. +#[derive(Clone, Copy, Debug)] +pub enum Callee { + Fn(FuncId), + Host(HostId), +} + #[derive(Clone, Copy, Debug)] pub enum Operand { Local(LocalId), @@ -72,7 +96,7 @@ pub enum Rvalue { }, Not(Operand), Call { - func: FuncId, + callee: Callee, args: Vec, span: Span, }, @@ -85,7 +109,7 @@ pub enum Stmt { }, /// A call whose result, if any, is discarded. Call { - func: FuncId, + callee: Callee, args: Vec, span: Span, }, diff --git a/host/src/lib.rs b/host/src/lib.rs new file mode 100644 index 0000000..c63b3f7 --- /dev/null +++ b/host/src/lib.rs @@ -0,0 +1,44 @@ +//! Stage-zero Chasm: the compiler behind the `chasm` CLI, and an embedding +//! API that runs Chasm functions inside a Rust application. +//! +//! [`Runtime`] is the embedding entry point; `docs/embedding.md` describes +//! it. `docs/alpha.md` specifies the language and the CLI. + +mod ast; +mod embed; +mod lexer; +mod lower; +mod parser; +mod validate; + +// Compiler internals the `chasm` CLI uses. They are not a stable API. +#[doc(hidden)] +pub mod diag; +#[doc(hidden)] +pub mod emit_c; +#[doc(hidden)] +pub mod interp; +#[doc(hidden)] +pub mod ir; +#[doc(hidden)] +pub mod native; + +pub use diag::{Diagnostic, Span}; +pub use embed::{ + CallError, CompileError, HostFn, HostReturn, RegisterError, Runtime, Script, ScriptType, Value, +}; + +/// Checks and lowers source text. `hosts` are the host functions it may call; +/// `require_main` applies the CLI's program contract. +#[doc(hidden)] +pub fn compile( + source: &str, + hosts: &[ir::HostSig], + require_main: bool, +) -> Result { + let decls = + parser::parse(lexer::lex(source)).map_err(|error| CompileError::Source(vec![error]))?; + let program = lower::lower(&decls, hosts, require_main).map_err(CompileError::Source)?; + validate::validate(&program).map_err(CompileError::Internal)?; + Ok(program) +} diff --git a/host/src/lower.rs b/host/src/lower.rs index 37fcac2..858c757 100644 --- a/host/src/lower.rs +++ b/host/src/lower.rs @@ -5,9 +5,13 @@ //! that is sound only because no expression can assign a variable, so nothing //! evaluated in between can change it. +use std::rc::Rc; + use crate::ast::{self, Arg, Expr, ExprKind, FnDecl, TypeName}; use crate::diag::{Diagnostic, Span}; -use crate::ir::{BinOp, FuncId, Function, Local, LocalId, Operand, Program, Rvalue, Stmt, Ty}; +use crate::ir::{ + BinOp, Callee, Function, HostSig, Local, LocalId, Operand, Program, Rvalue, Stmt, Ty, +}; type LResult = Result; @@ -17,13 +21,21 @@ struct Sig { ret: Option, } -/// Checks the program and lowers it. Reports every signature error, or else -/// the first error in each function body. -pub fn lower(decls: &[FnDecl]) -> Result> { +/// Checks the source and lowers it. `hosts` are the host functions it may +/// call. A program needs `fn main()`; a library (`require_main` false) is a +/// set of functions for an embedding application to call by name. +/// +/// Reports every signature error, or else the first error in each function +/// body. +pub fn lower( + decls: &[FnDecl], + hosts: &[HostSig], + require_main: bool, +) -> Result> { let mut errors = Vec::new(); let mut sigs = Vec::new(); for (index, decl) in decls.iter().enumerate() { - match signature(decl, &decls[..index]) { + match signature(decl, &decls[..index], hosts) { Ok(sig) => sigs.push(sig), Err(error) => errors.push(error), } @@ -33,6 +45,8 @@ pub fn lower(decls: &[FnDecl]) -> Result> { } let main = match sigs.iter().position(|s| s.name == "main") { + // A library has no entry point, so `main` is an ordinary name there. + _ if !require_main => None, None => { let start = Span { line: 1, col: 1 }; return Err(vec![Diagnostic::new( @@ -44,13 +58,25 @@ pub fn lower(decls: &[FnDecl]) -> Result> { let message = "`main` must take no parameters and return no value"; return Err(vec![Diagnostic::new(decls[main].span, message)]); } - Some(main) => main, + Some(main) => Some(main), }; + // Host parameters have no names, so calls fill them by position. + let host_sigs: Vec = hosts + .iter() + .map(|host| Sig { + name: host.name.clone(), + params: (1..) + .zip(&host.params) + .map(|(position, ty)| (format!("#{position}"), *ty)) + .collect(), + ret: host.ret, + }) + .collect(); let mut strings = Vec::new(); let mut functions = Vec::new(); for (decl, sig) in decls.iter().zip(&sigs) { - match lower_function(decl, sig, &sigs, &mut strings) { + match lower_function(decl, sig, &sigs, &host_sigs, &mut strings) { Ok(function) => functions.push(function), Err(error) => errors.push(error), } @@ -60,16 +86,21 @@ pub fn lower(decls: &[FnDecl]) -> Result> { } Ok(Program { functions, + hosts: hosts.to_vec(), strings, main, }) } -fn signature(decl: &FnDecl, earlier: &[FnDecl]) -> LResult { +fn signature(decl: &FnDecl, earlier: &[FnDecl], hosts: &[HostSig]) -> LResult { if decl.name == "print" { let message = "`print` is a prelude function and cannot be redefined"; return Err(Diagnostic::new(decl.span, message)); } + if hosts.iter().any(|host| host.name == decl.name) { + let message = format!("`{}` is a host function and cannot be redefined", decl.name); + return Err(Diagnostic::new(decl.span, message)); + } if let Some(first) = earlier.iter().find(|d| d.name == decl.name) { let message = format!( "function `{}` is already defined on line {}", @@ -109,11 +140,13 @@ fn lower_function( decl: &FnDecl, sig: &Sig, sigs: &[Sig], - strings: &mut Vec, + hosts: &[Sig], + strings: &mut Vec>, ) -> LResult { let mut lower = FnLower { sig, sigs, + hosts, strings, locals: Vec::new(), scopes: vec![Vec::new()], @@ -158,13 +191,14 @@ fn always_returns(stmts: &[ast::Stmt]) -> bool { struct FnLower<'a> { sig: &'a Sig, sigs: &'a [Sig], - strings: &'a mut Vec, + hosts: &'a [Sig], + strings: &'a mut Vec>, locals: Vec, /// Visible variables, innermost block last. scopes: Vec>, } -impl FnLower<'_> { +impl<'a> FnLower<'a> { fn block(&mut self, stmts: &[ast::Stmt]) -> LResult> { self.scopes.push(Vec::new()); let mut out = Vec::new(); @@ -312,9 +346,9 @@ impl FnLower<'_> { out.push(Stmt::Print(value)); return Ok(()); } - let func = self.function(callee, span)?; - let args = self.arguments(func, args, span, out)?; - out.push(Stmt::Call { func, args, span }); + let callee = self.function(callee, span)?; + let args = self.arguments(callee, args, span, out)?; + out.push(Stmt::Call { callee, args, span }); Ok(()) } @@ -337,25 +371,33 @@ impl FnLower<'_> { Ok(self.operand(&arg.value, out)?.0) } - fn function(&self, name: &str, span: Span) -> LResult { - self.sigs - .iter() - .position(|s| s.name == name) + /// Program functions and host functions share one namespace; `signature` + /// rejects a program function that reuses a host function's name. + fn function(&self, name: &str, span: Span) -> LResult { + let position = |sigs: &[Sig]| sigs.iter().position(|s| s.name == name); + position(self.sigs) + .map(Callee::Fn) + .or_else(|| position(self.hosts).map(Callee::Host)) .ok_or_else(|| Diagnostic::new(span, format!("unknown function `{name}`"))) } + fn sig(&self, callee: Callee) -> &'a Sig { + match callee { + Callee::Fn(id) => &self.sigs[id], + Callee::Host(id) => &self.hosts[id], + } + } + /// Evaluates arguments in the order written and returns them in /// parameter order. fn arguments( &mut self, - func: FuncId, + callee: Callee, args: &[Arg], span: Span, out: &mut Vec, ) -> LResult> { - // Copy the slice reference so `sig` does not borrow `self`. - let sigs = self.sigs; - let sig = &sigs[func]; + let sig = self.sig(callee); let mut slots: Vec> = vec![None; sig.params.len()]; for (position, arg) in args.iter().enumerate() { let index = match &arg.name { @@ -423,7 +465,7 @@ impl FnLower<'_> { ExprKind::Int(n) => (Rvalue::Use(Operand::Int(*n)), Ty::Int), ExprKind::Bool(b) => (Rvalue::Use(Operand::Bool(*b)), Ty::Bool), ExprKind::Str(text) => { - self.strings.push(text.clone()); + self.strings.push(text.as_str().into()); ( Rvalue::Use(Operand::Str(self.strings.len() - 1)), Ty::String, @@ -454,14 +496,15 @@ impl FnLower<'_> { "`print` returns no value, so its result cannot be used", )); } - let func = self.function(callee, span)?; - let args = self.arguments(func, args, span, out)?; - let Some(ty) = self.sigs[func].ret else { + let name = callee; + let callee = self.function(name, span)?; + let args = self.arguments(callee, args, span, out)?; + let Some(ty) = self.sig(callee).ret else { let message = - format!("`{callee}` returns no value, so its result cannot be used"); + format!("`{name}` returns no value, so its result cannot be used"); return Err(Diagnostic::new(span, message)); }; - (Rvalue::Call { func, args, span }, ty) + (Rvalue::Call { callee, args, span }, ty) } }) } diff --git a/host/src/main.rs b/host/src/main.rs index ea3f876..fb67cee 100644 --- a/host/src/main.rs +++ b/host/src/main.rs @@ -1,17 +1,6 @@ //! `chasm`: the stage-zero Chasm compiler for the scalar alpha. //! `docs/alpha.md` specifies the commands and language it accepts. -mod ast; -mod diag; -mod emit_c; -mod interp; -mod ir; -mod lexer; -mod lower; -mod native; -mod parser; -mod validate; - use std::ffi::OsString; use std::fs; use std::io::{self, BufWriter, Write}; @@ -19,7 +8,8 @@ use std::path::{Path, PathBuf}; use std::process::ExitCode; use std::thread; -use interp::Trap; +use chasm::interp::{self, Trap}; +use chasm::{CompileError, diag, emit_c, ir, native}; const USAGE: &str = "\ Usage: @@ -41,7 +31,8 @@ const USAGE_ERROR: u8 = 2; const INTERNAL_ERROR: u8 = 70; const PANIC_STATUS: u8 = 101; -/// Room for the interpreter's recursion at the call depth limit. +/// Generous room for the recursive compile passes, which the 200-level +/// nesting limit bounds. The interpreter keeps Chasm calls on the heap. const STACK_BYTES: usize = 512 << 20; enum Cli { @@ -209,13 +200,13 @@ fn compile(path: &Path) -> Result { "source is not valid UTF-8 text", )]) })?; - let decls = parser::parse(lexer::lex(&source)).map_err(|d| report(&[d]))?; - let program = lower::lower(&decls).map_err(|d| report(&d))?; - if let Err(error) = validate::validate(&program) { - eprintln!("chasm: internal compiler error: invalid IR {error}"); - return Err(ExitCode::from(INTERNAL_ERROR)); - } - Ok(program) + chasm::compile(&source, &[], true).map_err(|error| match error { + CompileError::Source(diagnostics) => report(&diagnostics), + CompileError::Internal(_) => { + eprintln!("chasm: {error}"); + ExitCode::from(INTERNAL_ERROR) + } + }) } fn run(program: &ir::Program, path: &Path) -> ExitCode { @@ -236,6 +227,9 @@ fn run(program: &ir::Program, path: &Path) -> ExitCode { (Err(Trap::Output(error)), _) | (Ok(()), Err(error)) => { fail(&format!("cannot write output: {error}")) } + (Err(Trap::OutOfFuel | Trap::Host { .. }), _) => { + unreachable!("the CLI runs with unlimited fuel and no host functions") + } (Ok(()), Ok(())) => ExitCode::SUCCESS, } } diff --git a/host/src/validate.rs b/host/src/validate.rs index 5473192..0d53b06 100644 --- a/host/src/validate.rs +++ b/host/src/validate.rs @@ -4,15 +4,17 @@ //! placement, and returns on every path. They catch some lowering mistakes; //! they do not show that lowering preserved the source program's meaning. -use crate::ir::{BinOp, Function, Operand, Program, Rvalue, Stmt, Ty}; +use crate::ir::{BinOp, Callee, Function, Operand, Program, Rvalue, Stmt, Ty}; pub fn validate(program: &Program) -> Result<(), String> { - let main = program - .functions - .get(program.main) - .ok_or("`main` index is out of range")?; - if main.param_count != 0 || main.ret.is_some() { - return Err("`main` must take no parameters and return no value".into()); + if let Some(main) = program.main { + let main = program + .functions + .get(main) + .ok_or("`main` index is out of range")?; + if main.param_count != 0 || main.ret.is_some() { + return Err("`main` must take no parameters and return no value".into()); + } } for function in &program.functions { let check = Checker { program, function }; @@ -54,7 +56,7 @@ impl Checker<'_> { let value_ty = self.rvalue(value)?; expect(dst_ty, value_ty, "assignment") } - Stmt::Call { func, args, .. } => self.call(*func, args).map(|_| ()), + Stmt::Call { callee, args, .. } => self.call(*callee, args).map(|_| ()), Stmt::Print(operand) => self.operand(*operand).map(|_| ()), Stmt::If { cond, @@ -113,25 +115,40 @@ impl Checker<'_> { expect(Ty::Bool, self.operand(*operand)?, "`not` operand")?; Ok(Ty::Bool) } - Rvalue::Call { func, args, .. } => self - .call(*func, args)? + Rvalue::Call { callee, args, .. } => self + .call(*callee, args)? .ok_or_else(|| "using the result of a call that returns no value".into()), } } - fn call(&self, func: usize, args: &[Operand]) -> Result, String> { - let callee = self - .program - .functions - .get(func) - .ok_or("call to an unknown function index")?; - if args.len() != callee.param_count { - return Err(format!("wrong argument count for `{}`", callee.name)); + fn call(&self, callee: Callee, args: &[Operand]) -> Result, String> { + let (name, params, ret): (_, Vec, _) = match callee { + Callee::Fn(id) => { + let function = self + .program + .functions + .get(id) + .ok_or("call to an unknown function index")?; + let params = function.locals.iter().take(function.param_count); + let params = params.map(|local| local.ty).collect(); + (&function.name, params, function.ret) + } + Callee::Host(id) => { + let host = self + .program + .hosts + .get(id) + .ok_or("call to an unknown host function index")?; + (&host.name, host.params.clone(), host.ret) + } + }; + if args.len() != params.len() { + return Err(format!("wrong argument count for `{name}`")); } - for (arg, param) in args.iter().zip(&callee.locals) { - expect(param.ty, self.operand(*arg)?, "argument")?; + for (arg, param) in args.iter().zip(params) { + expect(param, self.operand(*arg)?, "argument")?; } - Ok(callee.ret) + Ok(ret) } fn operand(&self, operand: Operand) -> Result { From 76f0150f6533af7829b1946b257e94db74114636 Mon Sep 17 00:00:00 2001 From: Mia Date: Tue, 27 Oct 2026 21:02:44 +0100 Subject: [PATCH 2/5] test(runtime): exercise embedding failures and host reuse Prove scalar round trips, callback evaluation order, validation before effects, captured output, deterministic fuel, exact call depth, and nested recursion on a normal host stack. Each failure must leave the next invocation room to succeed. Co-Authored-By: Claude Opus 5.5 --- host/tests/embedding.rs | 412 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 412 insertions(+) create mode 100644 host/tests/embedding.rs diff --git a/host/tests/embedding.rs b/host/tests/embedding.rs new file mode 100644 index 0000000..21e7e60 --- /dev/null +++ b/host/tests/embedding.rs @@ -0,0 +1,412 @@ +//! Black-box checks of the embedding API in `docs/embedding.md`. + +use std::cell::RefCell; +use std::rc::Rc; + +use chasm::{CallError, CompileError, RegisterError, Runtime, Span, Value}; + +fn int(n: i32) -> Option { + Some(Value::Int(n)) +} + +#[test] +fn a_library_without_main_returns_every_scalar_type_across_repeated_calls() { + let mut runtime = Runtime::new(); + let script = runtime + .compile( + r#" +fn add(a: Int, b: Int) -> Int { + return a + b +} +fn is_even(n: Int) -> Bool { + return n % 2 == 0 +} +fn greeting() -> String { + return "héllo" +} +fn echo(text: String) -> String { + return text +} +fn nothing() { +} +fn main(n: Int) -> Int { + return n +} +"#, + ) + .unwrap(); + + for _ in 0..3 { + assert_eq!( + runtime.call(&script, "add", &[2.into(), 3.into()]).unwrap(), + int(5) + ); + } + assert_eq!( + runtime.call(&script, "is_even", &[7.into()]).unwrap(), + Some(false.into()) + ); + assert_eq!( + runtime.call(&script, "greeting", &[]).unwrap(), + Some("héllo".into()) + ); + assert_eq!(runtime.call(&script, "nothing", &[]).unwrap(), None); + // `main` is an ordinary function in a library. + assert_eq!(runtime.call(&script, "main", &[9.into()]).unwrap(), int(9)); + + // A string from one script stays itself inside another, whose literal + // table holds different text. + let other = runtime + .compile("fn first() -> String {\n return \"beta\"\n}\nfn echo(text: String) -> String {\n return text\n}") + .unwrap(); + let alpha = runtime.call(&script, "greeting", &[]).unwrap().unwrap(); + assert_eq!( + runtime.call(&other, "echo", &[alpha]).unwrap(), + Some("héllo".into()) + ); +} + +#[test] +fn host_functions_run_in_source_order_and_exchange_typed_values() { + let log = Rc::new(RefCell::new(Vec::new())); + let mut runtime = Runtime::new(); + let marks = Rc::clone(&log); + runtime + .register("mark", move |n: i32| -> Result { + marks.borrow_mut().push(n.to_string()); + Ok(n) + }) + .unwrap(); + let notes = Rc::clone(&log); + runtime + .register( + "note", + move |text: String, loud: bool| -> Result<(), String> { + notes + .borrow_mut() + .push(if loud { text.to_uppercase() } else { text }); + Ok(()) + }, + ) + .unwrap(); + runtime + .register("shout", |text: String| -> Result { + Ok(format!("{text}!")) + }) + .unwrap(); + let script = runtime + .compile( + r#" +fn pair(a: Int, b: Int) -> Int { + return a * 10 + b +} +fn run(name: String) -> String { + let result = pair(b: mark(2), a: mark(1)) + mark(result) + note(name, true) + note("quiet", false) + return shout(name) +} +"#, + ) + .unwrap(); + + let result = runtime.call(&script, "run", &["ada".into()]).unwrap(); + + assert_eq!(result, Some("ada!".into())); + assert_eq!(*log.borrow(), ["2", "1", "12", "ADA", "quiet"]); +} + +#[test] +fn invalid_calls_are_rejected_before_anything_runs() { + let calls = Rc::new(RefCell::new(0)); + let mut runtime = Runtime::new(); + let counter = Rc::clone(&calls); + runtime + .register("touch", move || -> Result<(), String> { + *counter.borrow_mut() += 1; + Ok(()) + }) + .unwrap(); + let script = runtime + .compile("fn go(n: Int, label: String) {\n touch()\n print(label)\n}") + .unwrap(); + let foreign = Runtime::new() + .compile("fn go(n: Int, label: String) {\n}") + .unwrap(); + + let rejected = [ + runtime.call(&script, "go", &[1.into()]), + runtime.call(&script, "go", &[1.into(), 2.into()]), + runtime.call(&script, "go", &["1".into(), "x".into()]), + runtime.call(&script, "touch", &[]), + runtime.call(&script, "missing", &[]), + runtime.call(&foreign, "go", &[1.into(), "x".into()]), + ]; + + let messages: Vec = rejected + .iter() + .map(|r| r.as_ref().unwrap_err().to_string()) + .collect(); + assert_eq!( + messages, + [ + "`go` takes 2 argument(s), but 1 were given", + "argument `label` of `go` expects String, found Int", + "argument `n` of `go` expects Int, found String", + "the script has no function `touch`", + "the script has no function `missing`", + "the script was compiled by another runtime", + ] + ); + assert_eq!(*calls.borrow(), 0); + assert_eq!(runtime.take_output(), ""); +} + +#[test] +fn host_function_mistakes_are_rejected_at_registration_or_compile_time() { + let mut runtime = Runtime::new(); + let noop = || -> Result<(), String> { Ok(()) }; + runtime.register("noop", noop).unwrap(); + runtime + .register("twice", |n: i32| -> Result { Ok(n * 2) }) + .unwrap(); + + for name in ["", "two words", "if", "struct", "x//", "9lives"] { + assert_eq!( + runtime.register(name, noop), + Err(RegisterError::InvalidName(name.into())) + ); + } + for name in ["print", "noop"] { + assert_eq!( + runtime.register(name, noop), + Err(RegisterError::Taken(name.into())) + ); + } + + let diagnostics = |source: &str| match runtime.compile(source) { + Err(CompileError::Source(diagnostics)) => diagnostics + .iter() + .map(ToString::to_string) + .collect::>(), + _ => panic!("expected source diagnostics for {source:?}"), + }; + assert_eq!( + diagnostics("fn twice(n: Int) -> Int {\n return n\n}"), + ["1:4: error: `twice` is a host function and cannot be redefined"] + ); + assert_eq!( + diagnostics("fn f() -> Int {\n return twice(true)\n}"), + ["2:15: error: argument `#1` of `twice` expects Int, found Bool"] + ); + assert_eq!( + diagnostics("fn f() -> Int {\n return noop()\n}"), + ["2:9: error: `noop` returns no value, so its result cannot be used"] + ); +} + +#[test] +fn rejected_source_is_reported_as_data_and_the_runtime_keeps_working() { + let mut runtime = Runtime::new(); + + let Err(CompileError::Source(diagnostics)) = runtime.compile("fn broken( {\n}") else { + panic!("broken source must not compile"); + }; + assert_eq!(diagnostics.len(), 1); + assert_eq!(diagnostics[0].span, Span { line: 1, col: 12 }); + + let script = runtime.compile("fn ok() -> Int {\n return 1\n}").unwrap(); + assert_eq!(runtime.call(&script, "ok", &[]).unwrap(), int(1)); +} + +#[test] +fn runtime_failures_are_returned_and_the_next_call_succeeds() { + let mut runtime = Runtime::new(); + runtime + .register("check", |n: i32| -> Result { + if n < 0 { + return Err(format!("{n} is negative")); + } + Ok(n) + }) + .unwrap(); + let script = runtime + .compile( + r#" +fn run(n: Int, d: Int) -> Int { + print(n) + let checked = check(n) + return checked / d +} +"#, + ) + .unwrap(); + + let host = runtime.call(&script, "run", &[(-1).into(), 1.into()]); + let divide = runtime.call(&script, "run", &[1.into(), 0.into()]); + let ok = runtime.call(&script, "run", &[6.into(), 3.into()]); + + match host.unwrap_err() { + CallError::Host { + function, + message, + span, + } => { + assert_eq!( + (function.as_str(), message.as_str()), + ("check", "-1 is negative") + ); + assert_eq!(span, Span { line: 4, col: 19 }); + } + other => panic!("expected a host error, got {other:?}"), + } + assert!(matches!( + divide.unwrap_err(), + CallError::Panic { + message: "division by zero", + span: Span { line: 5, col: 20 } + } + )); + assert_eq!(ok.unwrap(), int(2)); + // Output before each failure is kept, not rolled back. + assert_eq!(runtime.take_output(), "-1\n1\n6\n"); +} + +#[test] +fn runaway_loops_and_recursion_stop_deterministically() { + let ticks = Rc::new(RefCell::new(0)); + let mut runtime = Runtime::new(); + let counter = Rc::clone(&ticks); + runtime + .register("tick", move || -> Result { + *counter.borrow_mut() += 1; + Ok(true) + }) + .unwrap(); + let source = String::from( + r#" +fn spin() { + while tick() { + } +} +fn forever() -> Int { + return forever() +} +fn even(n: Int) -> Bool { + if n == 0 { + return true + } + return odd(n - 1) +} +fn odd(n: Int) -> Bool { + if n == 0 { + return false + } + return even(n - 1) +} +"#, + ); + let script = runtime.compile(&source).unwrap(); + + runtime.set_fuel(100); + let first = runtime.call(&script, "spin", &[]); + let first_ticks = ticks.replace(0); + let second = runtime.call(&script, "spin", &[]); + assert!(matches!(first, Err(CallError::OutOfFuel))); + assert!(matches!(second, Err(CallError::OutOfFuel))); + assert!(first_ticks > 0); + assert_eq!(ticks.replace(0), first_ticks, "fuel must be deterministic"); + + runtime.set_fuel(0); + assert!(matches!( + runtime.call(&script, "spin", &[]), + Err(CallError::OutOfFuel) + )); + assert_eq!(*ticks.borrow(), 0); + + runtime.set_fuel(u64::MAX); + assert!(matches!( + runtime.call(&script, "forever", &[]), + Err(CallError::Panic { + message: "call depth limit exceeded", + span: Span { line: 7, col: 12 } + }) + )); + // 10000 active calls, counting the entry call, is the limit. + assert_eq!( + runtime.call(&script, "even", &[9999.into()]).unwrap(), + Some(false.into()) + ); + assert!(matches!( + runtime.call(&script, "even", &[10000.into()]), + Err(CallError::Panic { + message: "call depth limit exceeded", + .. + }) + )); +} + +#[test] +fn deep_recursion_through_nested_blocks_fits_a_default_thread_stack() { + // Many nested blocks per call; with deep recursion this would overflow + // a 2 MiB stack, Rust's default for spawned threads, if blocks or calls + // recursed in Rust. + let mut source = String::from("fn dive(n: Int) -> Int {\nif n == 0 {\nreturn 0\n}\n"); + source.push_str(&"if true {\n".repeat(120)); + source.push_str("return dive(n - 1) + 1\n"); + source.push_str(&"}\n".repeat(120)); + source.push_str("return -1\n}\n"); + + let dive = std::thread::Builder::new() + .stack_size(2 << 20) + .spawn(move || { + let mut runtime = Runtime::new(); + runtime.set_fuel(10_000_000); + let script = runtime.compile(&source).unwrap(); + runtime.call(&script, "dive", &[9999.into()]).unwrap() + }) + .unwrap() + .join() + .unwrap(); + + assert_eq!(dive, int(9999)); +} + +/// Set in the child process of `print_writes_to_runtime_output_not_stdout`. +const CHILD: &str = "CHASM_EMBED_STDOUT_CHILD"; +const MARKER: &str = "printed-by-chasm"; + +#[test] +fn print_writes_to_runtime_output_not_stdout() { + if std::env::var_os(CHILD).is_some() { + let mut runtime = Runtime::new(); + let script = runtime + .compile(&format!("fn shout() {{\n print(\"{MARKER}\")\n}}")) + .unwrap(); + runtime.call(&script, "shout", &[]).unwrap(); + assert_eq!(runtime.take_output(), format!("{MARKER}\n")); + return; + } + // Rerun just this test in a child process with capture off, so any + // write to the process's stdout would reach the pipe read here. + let child = std::process::Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "print_writes_to_runtime_output_not_stdout", + "--nocapture", + ]) + .env(CHILD, "1") + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&child.stdout); + assert!(child.status.success(), "child failed:\n{stdout}"); + assert!( + stdout.contains("1 passed"), + "the child must run the test:\n{stdout}" + ); + assert!( + !stdout.contains(MARKER), + "print leaked to stdout:\n{stdout}" + ); +} From 3e559fa8d56de07c36e555dfb9e2e2dc7a7e8657 Mon Sep 17 00:00:00 2001 From: Mia Date: Tue, 27 Oct 2026 21:02:44 +0100 Subject: [PATCH 3/5] docs(runtime): document embedding prototype and wayfinding boundary Describe the callable API, trusted host boundary, fuel and memory limits, and the runnable wallet example. Record the working prototype and pause implementation scope at wayfinding with Mia; the map comes after the first foothold. Co-Authored-By: Claude Opus 5.5 Co-Authored-By: GPT-6.1 Sol --- DIRECTION.md | 17 +++-- README.md | 2 + docs/alpha.md | 13 ++-- docs/embedding.md | 156 ++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 178 insertions(+), 10 deletions(-) create mode 100644 docs/embedding.md diff --git a/DIRECTION.md b/DIRECTION.md index f66e377..b95ab0d 100644 --- a/DIRECTION.md +++ b/DIRECTION.md @@ -21,6 +21,12 @@ booleans, and literal strings work in single-file programs. Independent CLI tests compare interpreter/native results and exercise diagnostics, evaluation order, arithmetic traps, build safety, and optimized/UBSan C output. +The Rust [embedding prototype](docs/embedding.md) compiles in-memory libraries, +calls scalar functions, registers typed host callbacks, and returns failures as +data. Output is captured by the runtime. Heap-backed execution stacks and +per-call fuel bound script execution; callbacks remain trusted and memory is +unbounded. It is a prototype API, not a sandbox. + The [alpha contract](docs/alpha.md) defines implemented behavior. The wider language proposal remains in the [README](README.md) and design notes. Borrowing, resources, regions, JavaScript, and self-hosting are unimplemented; @@ -28,12 +34,11 @@ memory feasibility and performance gates remain unperformed. ## Immediate priority -Make the existing interpreter embeddable for runtime scripts and plugins before -self-hosting. Hosts need to load and check source, register typed host functions, -call Chasm functions, and receive values and diagnostics without terminating the -host process. Runtime execution must work without an external C compiler. -Interpretation is the initial execution strategy; a JIT is a later optimization -subject to measured need and the same semantic conformance gates. +Finish and adversarially review the bounded embedding prototype, then wayfind +with Mia before selecting the next implementation slice. Compare its real host +integration and execution limits with the agent-authoring goals. Embedding +precedes self-hosting and runs without an external C compiler. A JIT is a later +optimization subject to measured need and the same semantic conformance gates. Extend the working scalar core toward the bootstrap subset in thin slices. Resolve copying versus resource ownership, borrow validity during storage changes, diff --git a/README.md b/README.md index 8f4baf6..7a6171c 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,8 @@ single source file. It supports typed functions, mutable locals, `if`/`else`, `while`, recursion, named arguments, checked 32-bit integers, booleans, and string literals. See the [alpha contract](docs/alpha.md) for the implemented syntax, commands, and limits, and [examples/](examples/) for runnable programs. +Rust applications can also run Chasm functions in-process; see +[Embedding](docs/embedding.md). ```sh cargo test --workspace diff --git a/docs/alpha.md b/docs/alpha.md index af0d9b1..5aa7e99 100644 --- a/docs/alpha.md +++ b/docs/alpha.md @@ -246,9 +246,10 @@ before the panic is written to stdout first. | `call depth limit exceeded` | a call would make more than 10000 calls active at once, counting `main` | The interpreter and native executables apply the same call-count guard. Their -host resource limits differ: the interpreter uses a 512 MiB worker stack, while -native executables use the platform's main-thread stack. Large frames or deep -recursion can exhaust either stack before the guard is reached. Host memory or +host resource limits differ: the interpreter keeps calls and blocks on the heap, +so recursion reaches the guard without using the host stack, while native +executables use the platform's main-thread stack, which large frames or deep +recursion can exhaust before the guard is reached. Host memory or stack exhaustion is outside the portable contract and may terminate execution without a Chasm panic. Infinite loops run forever on both lanes while host resources remain available. @@ -263,10 +264,14 @@ with status 1, while native executables ignore them. ```text source → lexer → parser → checker + lowering → typed IR → IR validator - ├── interpreter (run) + ├── interpreter (run, embedding) └── C emitter → cc (emit c, build) ``` +The crate is also a library: Rust applications can compile source and call +its functions through the interpreter. [Embedding](embedding.md) describes that +API. + - The IR is structured: blocks, `if`, `loop`, `break`, and `return`. Every operand is a variable or a constant, and every operation stores into a variable, so evaluation order is fixed in the IR rather than left to C. diff --git a/docs/embedding.md b/docs/embedding.md new file mode 100644 index 0000000..5686081 --- /dev/null +++ b/docs/embedding.md @@ -0,0 +1,156 @@ +# Embedding Chasm + +> **Status:** prototype on the `0.1.0-alpha.1` scalar language. The API may +> change in any release. It runs trusted host code with untrusted-script +> limits on fuel and call depth only; it is not a sandbox. + +The `chasm` crate in `host/` is a library as well as the CLI. A Rust +application compiles Chasm source in memory, registers host functions that +scripts may call, and calls script functions by name. Execution uses the +interpreter, so no C compiler is involved. The language is the one +[the alpha contract](alpha.md) describes. + +```rust +use chasm::{CallError, Runtime, Value}; + +let mut runtime = Runtime::new(); +runtime.register("double", |n: i32| -> Result { + n.checked_mul(2).ok_or_else(|| "too large".into()) +})?; + +let script = runtime.compile("fn quadruple(n: Int) -> Int {\n return double(double(n))\n}")?; +assert_eq!(runtime.call(&script, "quadruple", &[5.into()])?, Some(Value::Int(20))); + +match runtime.call(&script, "quadruple", &[i32::MAX.into()]) { + Err(CallError::Host { function, message, span }) => { /* "double", "too large", 2:16 */ } + other => { /* ... */ } +} +``` + +`host/examples/embed.rs` is a complete program with a stateful wallet +capability, a host error, an arithmetic panic, fuel exhaustion, and a +successful call afterwards. Run it from `host/` with +`cargo run --example embed`. + +## API + +| Item | Purpose | +| --- | --- | +| `Runtime::new()` | A runtime with no host functions and the default fuel. | +| `runtime.register(name, f)` | Lets scripts compiled afterwards call `f` as `name`. | +| `runtime.compile(source)` | Checks source into a `Script`, or returns `CompileError`. | +| `runtime.call(&script, name, &args)` | Calls a script function; returns `Option` or `CallError`. | +| `runtime.set_fuel(n)` | Sets the fuel each later call starts with. | +| `runtime.take_output()` | Returns and clears the text `print` has written. | + +`Value` is `Int(i32)`, `Bool(bool)`, or `String(String)`, with `From` +conversions from `i32`, `bool`, `String`, and `&str`. A function without a +return type returns `None`. Returned strings are owned by the caller. + +### Libraries + +`compile` treats source as a library: a list of functions with no `main` +required. `main` is an ordinary function name there. The CLI still requires +`fn main()`. + +### Host functions + +A host function's Rust signature sets its Chasm signature. Parameters are +`i32` (Int), `bool` (Bool), or `String`, up to four of them. The closure +returns `Result`, where `R` is one of those types or `()` for no +value. The compiler checks every script call against that signature, so a +callback only ever receives arguments of its declared types, and its result +type is fixed by Rust. + +- Scripts call host functions by bare name, positionally. Host parameters + have no names; diagnostics call them `#1`, `#2`, and so on. +- `register` rejects names that are not identifiers or are keywords or + reserved words (`RegisterError::InvalidName`), and `print` or an already + registered name (`RegisterError::Taken`). +- A script that defines a function with a host function's name does not + compile. +- Registrations are permanent and append-only. A script's host calls are + bound when it compiles, and it runs only on the runtime that compiled it + (`CallError::ForeignScript` otherwise). A function registered later is + visible only to scripts compiled later. +- An `Err(message)` from a callback stops the script with + `CallError::Host { function, message, span }`, where `span` is the call site. + +### Errors + +`CompileError::Source` holds the diagnostics the CLI would print, each with a +`span` (1-based line and column) and a `message`. `CompileError::Internal` +reports a compiler bug. + +`CallError` variants: + +| Variant | Meaning | Did anything run? | +| --- | --- | --- | +| `UnknownFunction` | The script has no function by that name. | No | +| `Arguments` | Wrong argument count or types. | No | +| `ForeignScript` | Another runtime compiled the script. | No | +| `Panic { message, span }` | `integer overflow`, `division by zero`, or `call depth limit exceeded`. | Yes | +| `OutOfFuel` | The call used up its fuel. | Yes | +| `Host { function, message, span }` | A host function returned `Err`. | Yes | + +Errors are values: nothing is printed and the process does not exit. A +failed call's effects stay: host callbacks it already made and output it +already printed are not rolled back. The runtime keeps no other state +between calls, so the next call starts with fresh fuel and an empty call +stack. A rejected source leaves the runtime unchanged. + +### Output + +`print` appends to a buffer the runtime owns, never to the process's stdout +or stderr. `take_output` returns and clears it. The buffer grows until taken; +fuel bounds how many lines one call can print. + +## Execution limits + +| Limit | Default | Notes | +| --- | --- | --- | +| Fuel | 1,000,000 per call | One unit per IR statement executed and per loop iteration. Configurable. | +| Call depth | 10,000 active calls | The language's limit, counting the entry call and host calls. Not configurable. | + +- **Fuel** is deterministic: the same script, arguments, and host results use + the same fuel and fail at the same point, including loops whose conditions + call host functions. The unit depends on the compiler's IR, so counts may + change between releases. Fuel is not a time limit: it does not run while a + host callback runs. `set_fuel(0)` fails any call that executes a statement; + `set_fuel(u64::MAX)` is effectively unlimited, so an infinite loop runs + until it exhausts that budget or execution is terminated externally. +- **Call depth** past the limit is `CallError::Panic` with + `call depth limit exceeded`, as in the CLI. +- **Host stack.** The interpreter keeps calls and nested blocks in heap + vectors, so script recursion and nesting do not grow the Rust stack. The + compiler passes and IR destruction still use the Rust stack. The + 200-level syntax limit bounds nesting, not stack usage in bytes. The + integration suite compiles and runs a 120-block recursive function on + a 2 MiB thread in debug and release; arbitrary small host stacks are + unsupported. +- **Heap.** Memory grows with the active call depth times each function's + locals and nesting, plus string sizes and the output buffer. There is no + memory budget; allocation failure behaves as it does elsewhere in Rust. + +## Trust model + +Host callbacks are trusted code. They run synchronously on the calling thread, +fuel cannot interrupt them, and they may block, loop, or panic. A callback +panic unwinds out of `Runtime::call`; the runtime holds no partial state, so +a host that catches the panic can keep using it. Callbacks cannot call back +into the runtime, since `call` holds it mutably. + +Scripts can affect the world only through registered host functions and +`print`. The runtime does not limit memory or wall-clock time and gives no +process isolation, so do not treat it as a security boundary. + +`Runtime` and `Script` are not `Send`: callbacks may capture `Rc` state, and +scripts share string literals through `Rc`. Create and use them on one +thread. + +## Not included + +Modules and imports, borrows and resources, typed call entry points (`call` +takes `&[Value]`), host functions with more than four parameters, +reentrant callbacks, async or suspended execution, hot reloading, a JIT, and +memory or time budgets. From 8d9b2cc11bf7fd4a44eb4b1b0e9dc082239f0328 Mon Sep 17 00:00:00 2001 From: Mia Date: Tue, 27 Oct 2026 21:09:07 +0100 Subject: [PATCH 4/5] docs(runtime): describe the available embedding prototype The runtime overview still said there was no embedding API while the quick start linked to it. Point both readers at the same working prototype; the JIT is still waiting in the wings. Co-Authored-By: GPT-6.1 Sol --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 7a6171c..d803656 100644 --- a/README.md +++ b/README.md @@ -105,8 +105,8 @@ Runtime scripting and plugins are core requirements. An application should be able to load Chasm source, check it, and execute it through an embedded runtime without an external C compiler. The typed-IR interpreter is the initial path; a bytecode VM or JIT can improve execution speed later. Embedding comes before -self-hosting. The alpha currently provides CLI interpretation through `chasm run`; -it has no public embedding API or JIT. +self-hosting. The alpha provides CLI interpretation through `chasm run` and a +prototype Rust [embedding API](docs/embedding.md); it has no JIT. The runtime also supports the planned REPL, hot module replacement, and local development. Native compilation supports release binaries, servers, desktop applications, and command-line tools. JavaScript compilation supports browsers, Node.js, and worker runtimes without requiring WebAssembly. From 9da34a0caac8be4ff30b549312431aebe34e300b Mon Sep 17 00:00:00 2001 From: Mia Date: Wed, 28 Oct 2026 17:59:34 +0100 Subject: [PATCH 5/5] fix(parser): bound expression tree height, not just descent depth Operator chains are built in a loop, so each operator sinks the tree built so far one level deeper without the parser descending. A parenthesized chain repeated inside another chain reached thousands of levels and overflowed the host stack in later passes. Each expression now records its height and is rejected once depth plus height passes the limit. Co-Authored-By: Claude Opus 5.5 --- docs/alpha.md | 9 +++--- host/src/ast.rs | 3 ++ host/src/parser.rs | 68 +++++++++++++++++++---------------------- host/tests/embedding.rs | 67 ++++++++++++++++++++++++++++++++++++++++ 4 files changed, 107 insertions(+), 40 deletions(-) diff --git a/docs/alpha.md b/docs/alpha.md index 5aa7e99..bb20a86 100644 --- a/docs/alpha.md +++ b/docs/alpha.md @@ -148,10 +148,11 @@ Precedence runs from loosest to tightest: `or`, `and`, `not`, comparisons, left-associative. Comparisons do not chain: `a < b < c` is an error. Nesting is limited to 200 levels. Each block, `else if`, parenthesized -expression, call argument, condition, unary `-` or `not`, and each binary -operator in a chain such as `1 + 2 + 3` adds a level while it is open, so a -chain of more than about 200 operators in one expression is rejected. Split -long expressions with `let`. +expression, call argument, condition, unary `-` or `not`, and binary operator +adds a level. In a chain such as `1 + 2 + 3`, each operator nests everything +to its left one level deeper, so a chain of more than about 200 operators in +one expression is rejected. Parentheses do not reset the count. Split long +expressions with `let`. ### Declarations and names diff --git a/host/src/ast.rs b/host/src/ast.rs index 1671635..57f5008 100644 --- a/host/src/ast.rs +++ b/host/src/ast.rs @@ -57,6 +57,9 @@ pub enum Stmt { pub struct Expr { pub kind: ExprKind, pub span: Span, + /// Levels of expression below this one; 0 for a leaf. The parser bounds it + /// so the recursive passes stay off the end of the host stack. + pub height: u32, } pub enum ExprKind { diff --git a/host/src/parser.rs b/host/src/parser.rs index 42807dd..8ec41f5 100644 --- a/host/src/parser.rs +++ b/host/src/parser.rs @@ -185,22 +185,18 @@ impl Parser { } fn or(&mut self) -> PResult { - let start = self.depth; let mut lhs = self.and()?; while *self.peek() == Tok::Or { lhs = self.binary(lhs, BinOp::Or, Self::and)?; } - self.depth = start; Ok(lhs) } fn and(&mut self) -> PResult { - let start = self.depth; let mut lhs = self.not()?; while *self.peek() == Tok::And { lhs = self.binary(lhs, BinOp::And, Self::not)?; } - self.depth = start; Ok(lhs) } @@ -213,10 +209,7 @@ impl Parser { self.enter()?; let operand = self.not()?; self.depth -= 1; - Ok(Expr { - kind: ExprKind::Not(Box::new(operand)), - span, - }) + self.node(ExprKind::Not(Box::new(operand)), span) } fn compare(&mut self) -> PResult { @@ -228,12 +221,10 @@ impl Parser { if comparison(self.peek()).is_some() { return Err(self.error("comparisons cannot be chained; combine them with `and`")); } - self.depth -= 1; Ok(expr) } fn sum(&mut self) -> PResult { - let start = self.depth; let mut lhs = self.product()?; loop { let op = match self.peek() { @@ -243,12 +234,10 @@ impl Parser { }; lhs = self.binary(lhs, op, Self::product)?; } - self.depth = start; Ok(lhs) } fn product(&mut self) -> PResult { - let start = self.depth; let mut lhs = self.unary()?; loop { let op = match self.peek() { @@ -259,15 +248,10 @@ impl Parser { }; lhs = self.binary(lhs, op, Self::unary)?; } - self.depth = start; Ok(lhs) } /// Consumes the operator at the cursor and parses its right operand. - /// - /// Each operator in a chain deepens the left-leaning tree by one, so it - /// counts toward the nesting limit until the caller's chain ends and - /// restores the depth. Later passes recurse over that tree. fn binary( &mut self, lhs: Expr, @@ -275,13 +259,9 @@ impl Parser { rhs: fn(&mut Self) -> PResult, ) -> PResult { let span = self.span(); - self.enter()?; self.bump(); let rhs = rhs(self)?; - Ok(Expr { - kind: ExprKind::Binary(op, Box::new(lhs), Box::new(rhs)), - span, - }) + self.node(ExprKind::Binary(op, Box::new(lhs), Box::new(rhs)), span) } fn unary(&mut self) -> PResult { @@ -296,18 +276,12 @@ impl Parser { self.bump(); let value = i32::try_from(-i64::from(magnitude)).expect("lexer caps literal magnitude at 2^31"); - return Ok(Expr { - kind: ExprKind::Int(value), - span, - }); + return self.node(ExprKind::Int(value), span); } self.enter()?; let operand = self.unary()?; self.depth -= 1; - Ok(Expr { - kind: ExprKind::Neg(Box::new(operand)), - span, - }) + self.node(ExprKind::Neg(Box::new(operand)), span) } fn primary(&mut self) -> PResult { @@ -335,7 +309,7 @@ impl Parser { _ => return Err(self.unexpected("an expression")), }; self.bump(); - Ok(Expr { kind, span }) + self.node(kind, span) } fn call(&mut self, callee: String) -> PResult { @@ -366,10 +340,7 @@ impl Parser { } } self.bump(); - Ok(Expr { - kind: ExprKind::Call { callee, args }, - span, - }) + self.node(ExprKind::Call { callee, args }, span) } fn ident(&mut self, expected: &str) -> PResult<(String, Span)> { @@ -397,9 +368,34 @@ impl Parser { found } + /// Opens a level while the parser descends into nested syntax. fn enter(&mut self) -> PResult<()> { self.depth += 1; - if self.depth > MAX_NESTING { + self.check_nesting(self.depth) + } + + /// Builds an expression one level above its tallest operand. + /// + /// A chain such as `1 + 2 + 3` is built in a loop, and each operator sinks + /// the tree built so far one level deeper. Descent depth alone misses that, + /// so every node checks its full height from the current depth. + fn node(&self, kind: ExprKind, span: Span) -> PResult { + let height = match &kind { + ExprKind::Int(_) | ExprKind::Bool(_) | ExprKind::Str(_) | ExprKind::Var(_) => 0, + ExprKind::Neg(operand) | ExprKind::Not(operand) => operand.height + 1, + ExprKind::Binary(_, lhs, rhs) => lhs.height.max(rhs.height) + 1, + ExprKind::Call { args, .. } => args + .iter() + .map(|arg| arg.value.height + 1) + .max() + .unwrap_or(0), + }; + self.check_nesting(self.depth + height)?; + Ok(Expr { kind, span, height }) + } + + fn check_nesting(&self, depth: u32) -> PResult<()> { + if depth > MAX_NESTING { return Err(self.error(format!( "nesting is too deep; the limit is {MAX_NESTING} levels" ))); diff --git a/host/tests/embedding.rs b/host/tests/embedding.rs index 21e7e60..f029764 100644 --- a/host/tests/embedding.rs +++ b/host/tests/embedding.rs @@ -373,6 +373,73 @@ fn deep_recursion_through_nested_blocks_fits_a_default_thread_stack() { assert_eq!(dive, int(9999)); } +#[test] +fn excessive_compiler_nesting_returns_diagnostics_without_aborting_the_host() { + const CHILD_CASE: &str = "CHASM_COMPILE_NESTING_CHILD"; + if let Ok(case) = std::env::var(CHILD_CASE) { + std::thread::Builder::new() + .stack_size(2 << 20) + .spawn(move || { + let mut expression = match case.as_str() { + "invalid" => "missing", + "boolean" => "true", + _ => "1", + } + .to_owned(); + for _ in 0..70 { + expression = match case.as_str() { + "boolean" => format!("({expression}){}", " and true".repeat(70)), + "calls" => format!("id(({expression}){})", " + 1".repeat(70)), + _ => format!("({expression}){}", " + 1".repeat(70)), + }; + } + if case == "syntax" { + expression.push_str(" + @"); + } + let ty = if case == "boolean" { "Bool" } else { "Int" }; + let source = format!( + "fn id(n: Int) -> Int {{ return n }}\nfn run() -> {ty} {{ return {expression} }}" + ); + let mut runtime = Runtime::new(); + let Err(CompileError::Source(diagnostics)) = runtime.compile(&source) else { + panic!("excessive nesting must return source diagnostics"); + }; + assert!(diagnostics[0].message.contains("nesting is too deep")); + assert_eq!(diagnostics[0].span.line, 2); + // Ordinary composite expressions still compile, and a rejected + // script leaves the same runtime usable. + let expression = format!("(1{}){}", " + 1".repeat(40), " + 1".repeat(40)); + let source = format!("fn ok() -> Int {{ return {expression} }}"); + let script = runtime.compile(&source).unwrap(); + assert_eq!(runtime.call(&script, "ok", &[]).unwrap(), int(81)); + }) + .unwrap() + .join() + .unwrap(); + return; + } + + // Stack overflow aborts the whole process, so isolate each probe and + // assert that the public API returns normally on an ordinary host stack. + for case in ["arithmetic", "invalid", "boolean", "calls", "syntax"] { + let child = std::process::Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "excessive_compiler_nesting_returns_diagnostics_without_aborting_the_host", + "--nocapture", + ]) + .env(CHILD_CASE, case) + .output() + .unwrap(); + assert!( + child.status.success(), + "{case}: {}\n{}", + String::from_utf8_lossy(&child.stdout), + String::from_utf8_lossy(&child.stderr) + ); + } +} + /// Set in the child process of `print_writes_to_runtime_output_not_stdout`. const CHILD: &str = "CHASM_EMBED_STDOUT_CHILD"; const MARKER: &str = "printed-by-chasm";