Lines
93.58 %
Functions
88.54 %
Branches
100 %
use core::fmt;
use num_rational::Ratio;
pub type Fraction = Ratio<i64>;
/// A numeric literal: its kind is the spelling the reader saw, so an integer
/// token is an `Index` and a decimal, fraction or percent a `Scalar`, even a
/// whole one.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Number {
Index(i64),
Scalar(Fraction),
}
impl Number {
/// The exact value, whatever the kind.
#[must_use]
pub fn value(self) -> Fraction {
match self {
Self::Index(n) => Fraction::from_integer(n),
Self::Scalar(f) => f,
/// The readable spelling: an index as `N`, a scalar always as `n/d`.
impl fmt::Display for Number {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
Self::Index(n) => write!(f, "{n}"),
Self::Scalar(s) => write!(f, "{}/{}", s.numer(), s.denom()),
pub use crate::ast_pair::{PairElement, StructId};
/// Kind tag for one server-entity wasm struct. Each variant maps to a
/// concrete `$<kind>` GC struct registered in
/// `CompileContext::new_skeleton`, plus a set of typed field accessors
/// in the native registry. Adding an entity adds one variant here +
/// one row in the `nomi_entity!` macro invocation; the compiler and
/// host-side allocators pick up the rest by expansion.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum EntityKind {
Account,
Commodity,
Transaction,
Split,
Tag,
Price,
SshKey,
/// Error condition raised by `(error 'code "msg")` and caught by
/// `(handler-case)`. Maps to the `$nomi_condition` struct registered
/// for exception support; the clause variable `e` binds at this kind so
/// `(error-code e)` / `(error-message e)` type-check.
Condition,
impl EntityKind {
/// Every kind, in wire order: a kind's debug-value tag carries its index
/// here (`wire_code`), so the guest serializer and the host decoder agree
/// through this one table.
pub const ALL: [EntityKind; 8] = [
Self::Account,
Self::Commodity,
Self::Transaction,
Self::Split,
Self::Tag,
Self::Price,
Self::SshKey,
Self::Condition,
];
/// The kind's position in [`Self::ALL`].
pub fn wire_code(self) -> i64 {
Self::ALL
.iter()
.position(|kind| *kind == self)
.map_or(i64::MAX, |index| index as i64)
/// The kind at `code` in [`Self::ALL`], if any.
pub fn from_wire_code(code: i64) -> Option<Self> {
usize::try_from(code)
.ok()
.and_then(|index| Self::ALL.get(index).copied())
/// Name of the wasm struct type the compiler registers in
/// `CompileContext::new_skeleton` for this entity kind. Keep in
/// lockstep with the `register_struct_type` calls there.
pub fn type_name(self) -> &'static str {
Self::Account => "account",
Self::Commodity => "commodity_entity",
Self::Transaction => "transaction",
Self::Split => "split",
Self::Tag => "tag_entity",
Self::Price => "price",
Self::SshKey => "ssh_key",
Self::Condition => "nomi_condition",
impl fmt::Display for EntityKind {
write!(f, "{}", self.type_name())
/// Identifier for a closure signature interned in the compile
/// context's closure registry. Distinct closures sharing the same
/// `(arg-types) -> ret-type` signature share an id (and therefore a
/// `$closure_<id>` wasm GC type); their env-struct types vary
/// independently per scope. The id is allocated in registration order
/// — small, dense, `Copy` — so it can ride inside `WasmType` without
/// growing the enum.
pub struct ClosureSigId(pub u32);
impl fmt::Display for ClosureSigId {
write!(f, "{}", self.0)
pub enum WasmType {
I32,
/// Boolean: a comparison / predicate / `and` / `or` result, or a runtime
/// `t` / `nil`. Wasm representation is identical to `I32` (0 = nil,
/// nonzero = t), so it composes with `if` / `br_if` and boxes via
/// `ref.i31` exactly like `I32`. It is a DISTINCT compile-time type only
/// so the debug serializer can surface it as `Nil` / `T` rather than
/// `Number`: an `I32` is a raw count (tag-count, split-count, …) that
/// serializes as a number, whereas a `Bool` is a truth value. Refused by
/// arithmetic like every non-numeric type.
Bool,
Ratio,
StringRef,
/// Runtime symbol or keyword: `(ref null $symbol)` carrying its printed name.
SymbolRef,
/// Commodity-bearing numeric: rational amount + originating commodity
/// uuid. Distinct from `Ratio` so the compiler can refuse mixing money
/// and pure-rational arithmetic at compile time. Wasm representation:
/// `(i64 numer, i64 denom, i64 commodity_hi, i64 commodity_lo)`.
/// Homogeneous list cell: `$pair` WasmGC struct with an `anyref` car
/// and a nullable `$pair` cdr. The `PairElement` records the car's
/// type at compile time so CAR/CDR can emit the correct downcast and
/// CONS refuses heterogeneous mixing. Retires the i32-only `$cons` —
/// every runtime list shape in the compiler routes through this type.
PairRef(PairElement),
/// Raw `anyref` car payload extracted from a `PairRef(AnyRef)` or
/// produced by a host fn that returns a heterogeneous value
/// (ADR-0025). Refused by arithmetic / numeric comparison / closure
/// call / typed pair construction; the script must downcast via
/// type-test natives (e.g. `ok?`, `err-code`) before consuming.
AnyRef,
/// Typed server-entity reference: a `(ref null $<kind>)` GC struct
/// whose field layout matches the `nomi_entity!` declaration for the
/// kind. Refused by arithmetic / list-CONS / numeric comparison; the
/// only legal operations are the entity-specific accessor natives
/// (`account-id`, `commodity-name`, etc.) registered alongside the
/// struct type.
EntityRef(EntityKind),
/// A `DEFSTRUCT` instance: `(ref null $struct)`, one shape for every
/// layout. Identity is reference identity; only the struct natives read
/// or write it, and `nil` is `ref.null`.
StructRef(StructId),
/// First-class closure value: `(ref null $closure_<sig>)` carrying a
/// typed funcref + nullable env ref. The `ClosureSigId` indexes the
/// per-context registry that owns the wasm types and per-call-site
/// env-struct layouts. Eligible for FUNCALL / APPLY via `call_ref`;
/// refused by arithmetic / numeric comparison / pair construction.
Closure(ClosureSigId),
impl fmt::Display for WasmType {
Self::I32 => write!(f, "i32"),
Self::Bool => write!(f, "bool"),
Self::Ratio => write!(f, "ratio"),
Self::StringRef => write!(f, "string"),
Self::SymbolRef => write!(f, "symbol"),
Self::Commodity => write!(f, "commodity"),
Self::PairRef(elem) => write!(f, "pair<{elem}>"),
Self::EntityRef(kind) => write!(f, "entity<{kind}>"),
Self::StructRef(id) => write!(f, "{id}"),
Self::Closure(sig) => write!(f, "closure<{sig}>"),
Self::AnyRef => write!(f, "any"),
#[derive(Debug, Clone, PartialEq)]
pub struct LambdaParams {
pub required: Vec<String>,
pub optional: Vec<(String, Option<Expr>)>,
pub rest: Option<String>,
pub key: Vec<KeyParam>,
pub aux: Vec<(String, Option<Expr>)>,
/// A `&key` parameter: the variable, the keyword a caller passes for it
/// (upper case) and the default form.
pub struct KeyParam {
pub name: String,
pub keyword: String,
pub default: Option<Expr>,
impl KeyParam {
/// A parameter whose keyword is its variable name.
pub fn new(name: impl Into<String>, default: Option<Expr>) -> Self {
let name = name.into();
Self {
keyword: name.to_uppercase(),
name,
default,
impl LambdaParams {
/// The keyword a caller passes for the `&key` variable `var`.
pub fn keyword_of(&self, var: &str) -> String {
self.key
.find_map(|param| (param.name == var).then(|| param.keyword.clone()))
.unwrap_or_else(|| var.to_uppercase())
/// The `&optional`, `&key` and `&aux` parameters as `(variable, default)`.
pub fn defaulted(&self) -> impl Iterator<Item = (&str, Option<&Expr>)> {
let optional = self.optional.iter().map(|(name, default)| (name, default));
let key = self.key.iter().map(|param| (¶m.name, ¶m.default));
let aux = self.aux.iter().map(|(name, default)| (name, default));
optional
.chain(key)
.chain(aux)
.map(|(name, default)| (name.as_str(), default.as_ref()))
/// The default forms of the `&optional`, `&key` and `&aux` parameters.
pub fn defaults(&self) -> impl Iterator<Item = &Expr> {
self.defaulted().filter_map(|(_, default)| default)
/// Mutable access to the same default forms as [`Self::defaults`].
pub fn defaults_mut(&mut self) -> impl Iterator<Item = &mut Expr> {
let optional = self.optional.iter_mut().map(|(_, default)| default);
let key = self.key.iter_mut().map(|param| &mut param.default);
let aux = self.aux.iter_mut().map(|(_, default)| default);
.filter_map(|default| default.as_mut())
pub fn simple(params: Vec<String>) -> Self {
required: params,
optional: Vec::new(),
rest: None,
key: Vec::new(),
aux: Vec::new(),
pub enum Expr {
Nil,
T,
Number(Number),
String(String),
Symbol(String),
Keyword(String),
Bytes(Vec<u8>),
Cons(Box<Expr>, Box<Expr>),
List(Vec<Expr>),
Quote(Box<Expr>),
/// An evaluated value that is the datum inside; the reader never makes it.
Datum(Box<Expr>),
Quasiquote(Box<Expr>),
Unquote(Box<Expr>),
UnquoteSplicing(Box<Expr>),
Lambda(LambdaParams, Box<Expr>),
RuntimeValue(crate::runtime::Value),
WasmRuntime(WasmType),
/// Value stored in WASM local variable (index, type)
WasmLocal(u32, WasmType),
/// Value stored in a mutable module global (index, type)
WasmGlobal(u32, WasmType),
/// A session struct instance an earlier unit left (serial, layout): a leaf
/// the unit's prologue binds to a module global; it never folds.
Instance(u32, StructId),
/// Where a runtime variable lives: a local of the current function or a
/// module global every function reaches.
pub enum Place {
Local(u32),
Global(u32),
impl Expr {
pub fn cons(car: Expr, cdr: Expr) -> Self {
Expr::Cons(Box::new(car), Box::new(cdr))
pub fn symbol(name: &str) -> Self {
Expr::Symbol(name.to_string())
/// A body of forms as one form: the sole form, else a `PROGN`.
pub fn body(forms: &[Expr]) -> Self {
match forms {
[form] => form.clone(),
_ => Expr::List(
std::iter::once(Expr::symbol("PROGN"))
.chain(forms.iter().cloned())
.collect(),
),
/// Returns the `WasmType` if this expression is a runtime value.
pub fn wasm_type(&self) -> Option<WasmType> {
Self::WasmRuntime(ty) | Self::WasmLocal(_, ty) | Self::WasmGlobal(_, ty) => Some(*ty),
Self::Instance(_, id) => Some(WasmType::StructRef(*id)),
Self::RuntimeValue(crate::runtime::Value::Commodity { .. }) => {
Some(WasmType::Commodity)
_ => None,
/// True if this is a runtime value.
pub fn is_wasm_runtime(&self) -> bool {
matches!(
self,
Self::WasmRuntime(_)
| Self::WasmLocal(_, _)
| Self::WasmGlobal(_, _)
| Self::Instance(_, _)
)
/// True for a runtime placeholder, local or global, which means nothing
/// outside the function that resolved it; a session instance does.
pub fn is_runtime_variable(&self) -> bool {
Self::WasmRuntime(_) | Self::WasmLocal(_, _) | Self::WasmGlobal(_, _)
/// Whether `test` holds of the form or of any form inside it. Walked with
/// an explicit stack, so a deep form cannot overflow.
pub fn any_form(&self, test: impl Fn(&Expr) -> bool) -> bool {
let mut pending = vec![self];
while let Some(form) = pending.pop() {
if test(form) {
return true;
match form {
Self::List(items) => pending.extend(items),
Self::Cons(car, cdr) => pending.extend([car.as_ref(), cdr.as_ref()]),
Self::Quote(inner)
| Self::Datum(inner)
| Self::Quasiquote(inner)
| Self::Unquote(inner)
| Self::UnquoteSplicing(inner) => pending.push(inner),
Self::Lambda(params, body) => {
pending.push(body);
pending.extend(params.defaults());
_ => {}
false
/// The storage and type of a runtime variable; `None` for a placeholder
/// or a compile-time value.
pub fn place(&self) -> Option<(Place, WasmType)> {
Self::WasmLocal(idx, ty) => Some((Place::Local(*idx), *ty)),
Self::WasmGlobal(idx, ty) => Some((Place::Global(*idx), *ty)),
/// Whether the value is a function: a lambda or a closure place.
pub fn is_function_value(&self) -> bool {
matches!(self, Self::Lambda(..)) || matches!(self.place(), Some((_, WasmType::Closure(_))))
pub struct Annotation {
pub value: Expr,
/// The single compile-time truth test: a value is false exactly when it is nil.
pub fn is_nil(&self) -> bool {
matches!(self, Expr::Nil)
pub fn is_atom(&self) -> bool {
!matches!(self, Expr::List(_) | Expr::Cons(_, _))
pub fn as_symbol(&self) -> Option<&str> {
Expr::Symbol(s) => Some(s),
/// The elements of a list; `nil` is the empty list.
pub fn as_list(&self) -> Option<&[Expr]> {
Expr::List(l) => Some(l),
Expr::Nil => Some(&[]),
/// Splits a `Symbol` into `(namespace, name)`. A qualified symbol is
/// stored canonically as `NS:NAME` (ADR-0029); an unqualified one has no
/// `:` and yields `(None, name)`. Non-symbols yield `None`. The split is
/// on the single canonical `:` — `NS::NAME` was already folded to `NS:NAME`
/// by the reader, so at most one `:` is ever present here.
pub fn symbol_parts(&self) -> Option<(Option<&str>, &str)> {
let name = self.as_symbol()?;
Some(match name.split_once(':') {
Some((ns, base)) => (Some(ns), base),
None => (None, name),
})
/// Builds the canonical symbol-table key for a (possibly namespaced) name.
/// `NS:NAME` when a namespace is present, bare `NAME` otherwise — the single
/// source of truth for how a qualified name maps to its flat table key.
pub fn canonical_symbol(namespace: Option<&str>, name: &str) -> String {
match namespace {
Some(ns) => format!("{ns}:{name}"),
None => name.to_string(),
#[derive(Debug, Clone, Default)]
pub struct Program {
pub exprs: Vec<Expr>,
pub annotations: Vec<Annotation>,
impl Program {
pub fn new(exprs: Vec<Expr>) -> Self {
exprs,
annotations: Vec::new(),
pub fn with_annotations(exprs: Vec<Expr>, annotations: Vec<Annotation>) -> Self {
Self { exprs, annotations }
#[cfg(test)]
#[path = "ast_tests.rs"]
mod tests;