Skip to main content

nomiscript/
ast.rs

1use core::fmt;
2
3use num_rational::Ratio;
4
5pub type Fraction = Ratio<i64>;
6
7/// A numeric literal: its kind is the spelling the reader saw, so an integer
8/// token is an `Index` and a decimal, fraction or percent a `Scalar`, even a
9/// whole one.
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
11pub enum Number {
12    Index(i64),
13    Scalar(Fraction),
14}
15
16impl Number {
17    /// The exact value, whatever the kind.
18    #[must_use]
19    pub fn value(self) -> Fraction {
20        match self {
21            Self::Index(n) => Fraction::from_integer(n),
22            Self::Scalar(f) => f,
23        }
24    }
25}
26
27/// The readable spelling: an index as `N`, a scalar always as `n/d`.
28impl fmt::Display for Number {
29    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
30        match self {
31            Self::Index(n) => write!(f, "{n}"),
32            Self::Scalar(s) => write!(f, "{}/{}", s.numer(), s.denom()),
33        }
34    }
35}
36
37pub use crate::ast_pair::{PairElement, StructId};
38
39/// Kind tag for one server-entity wasm struct. Each variant maps to a
40/// concrete `$<kind>` GC struct registered in
41/// `CompileContext::new_skeleton`, plus a set of typed field accessors
42/// in the native registry. Adding an entity adds one variant here +
43/// one row in the `nomi_entity!` macro invocation; the compiler and
44/// host-side allocators pick up the rest by expansion.
45#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
46pub enum EntityKind {
47    Account,
48    Commodity,
49    Transaction,
50    Split,
51    Tag,
52    Price,
53    SshKey,
54    /// Error condition raised by `(error 'code "msg")` and caught by
55    /// `(handler-case)`. Maps to the `$nomi_condition` struct registered
56    /// for exception support; the clause variable `e` binds at this kind so
57    /// `(error-code e)` / `(error-message e)` type-check.
58    Condition,
59}
60
61impl EntityKind {
62    /// Every kind, in wire order: a kind's debug-value tag carries its index
63    /// here (`wire_code`), so the guest serializer and the host decoder agree
64    /// through this one table.
65    pub const ALL: [EntityKind; 8] = [
66        Self::Account,
67        Self::Commodity,
68        Self::Transaction,
69        Self::Split,
70        Self::Tag,
71        Self::Price,
72        Self::SshKey,
73        Self::Condition,
74    ];
75
76    /// The kind's position in [`Self::ALL`].
77    #[must_use]
78    pub fn wire_code(self) -> i64 {
79        Self::ALL
80            .iter()
81            .position(|kind| *kind == self)
82            .map_or(i64::MAX, |index| index as i64)
83    }
84
85    /// The kind at `code` in [`Self::ALL`], if any.
86    #[must_use]
87    pub fn from_wire_code(code: i64) -> Option<Self> {
88        usize::try_from(code)
89            .ok()
90            .and_then(|index| Self::ALL.get(index).copied())
91    }
92
93    /// Name of the wasm struct type the compiler registers in
94    /// `CompileContext::new_skeleton` for this entity kind. Keep in
95    /// lockstep with the `register_struct_type` calls there.
96    #[must_use]
97    pub fn type_name(self) -> &'static str {
98        match self {
99            Self::Account => "account",
100            Self::Commodity => "commodity_entity",
101            Self::Transaction => "transaction",
102            Self::Split => "split",
103            Self::Tag => "tag_entity",
104            Self::Price => "price",
105            Self::SshKey => "ssh_key",
106            Self::Condition => "nomi_condition",
107        }
108    }
109}
110
111impl fmt::Display for EntityKind {
112    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
113        write!(f, "{}", self.type_name())
114    }
115}
116
117/// Identifier for a closure signature interned in the compile
118/// context's closure registry. Distinct closures sharing the same
119/// `(arg-types) -> ret-type` signature share an id (and therefore a
120/// `$closure_<id>` wasm GC type); their env-struct types vary
121/// independently per scope. The id is allocated in registration order
122/// — small, dense, `Copy` — so it can ride inside `WasmType` without
123/// growing the enum.
124#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
125pub struct ClosureSigId(pub u32);
126
127impl fmt::Display for ClosureSigId {
128    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
129        write!(f, "{}", self.0)
130    }
131}
132
133#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
134pub enum WasmType {
135    I32,
136    /// Boolean: a comparison / predicate / `and` / `or` result, or a runtime
137    /// `t` / `nil`. Wasm representation is identical to `I32` (0 = nil,
138    /// nonzero = t), so it composes with `if` / `br_if` and boxes via
139    /// `ref.i31` exactly like `I32`. It is a DISTINCT compile-time type only
140    /// so the debug serializer can surface it as `Nil` / `T` rather than
141    /// `Number`: an `I32` is a raw count (tag-count, split-count, …) that
142    /// serializes as a number, whereas a `Bool` is a truth value. Refused by
143    /// arithmetic like every non-numeric type.
144    Bool,
145    Ratio,
146    StringRef,
147    /// Runtime symbol or keyword: `(ref null $symbol)` carrying its printed name.
148    SymbolRef,
149    /// Commodity-bearing numeric: rational amount + originating commodity
150    /// uuid. Distinct from `Ratio` so the compiler can refuse mixing money
151    /// and pure-rational arithmetic at compile time. Wasm representation:
152    /// `(i64 numer, i64 denom, i64 commodity_hi, i64 commodity_lo)`.
153    Commodity,
154    /// Homogeneous list cell: `$pair` WasmGC struct with an `anyref` car
155    /// and a nullable `$pair` cdr. The `PairElement` records the car's
156    /// type at compile time so CAR/CDR can emit the correct downcast and
157    /// CONS refuses heterogeneous mixing. Retires the i32-only `$cons` —
158    /// every runtime list shape in the compiler routes through this type.
159    PairRef(PairElement),
160    /// Raw `anyref` car payload extracted from a `PairRef(AnyRef)` or
161    /// produced by a host fn that returns a heterogeneous value
162    /// (ADR-0025). Refused by arithmetic / numeric comparison / closure
163    /// call / typed pair construction; the script must downcast via
164    /// type-test natives (e.g. `ok?`, `err-code`) before consuming.
165    AnyRef,
166    /// Typed server-entity reference: a `(ref null $<kind>)` GC struct
167    /// whose field layout matches the `nomi_entity!` declaration for the
168    /// kind. Refused by arithmetic / list-CONS / numeric comparison; the
169    /// only legal operations are the entity-specific accessor natives
170    /// (`account-id`, `commodity-name`, etc.) registered alongside the
171    /// struct type.
172    EntityRef(EntityKind),
173    /// A `DEFSTRUCT` instance: `(ref null $struct)`, one shape for every
174    /// layout. Identity is reference identity; only the struct natives read
175    /// or write it, and `nil` is `ref.null`.
176    StructRef(StructId),
177    /// First-class closure value: `(ref null $closure_<sig>)` carrying a
178    /// typed funcref + nullable env ref. The `ClosureSigId` indexes the
179    /// per-context registry that owns the wasm types and per-call-site
180    /// env-struct layouts. Eligible for FUNCALL / APPLY via `call_ref`;
181    /// refused by arithmetic / numeric comparison / pair construction.
182    Closure(ClosureSigId),
183}
184
185impl fmt::Display for WasmType {
186    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
187        match self {
188            Self::I32 => write!(f, "i32"),
189            Self::Bool => write!(f, "bool"),
190            Self::Ratio => write!(f, "ratio"),
191            Self::StringRef => write!(f, "string"),
192            Self::SymbolRef => write!(f, "symbol"),
193            Self::Commodity => write!(f, "commodity"),
194            Self::PairRef(elem) => write!(f, "pair<{elem}>"),
195            Self::EntityRef(kind) => write!(f, "entity<{kind}>"),
196            Self::StructRef(id) => write!(f, "{id}"),
197            Self::Closure(sig) => write!(f, "closure<{sig}>"),
198            Self::AnyRef => write!(f, "any"),
199        }
200    }
201}
202
203#[derive(Debug, Clone, PartialEq)]
204pub struct LambdaParams {
205    pub required: Vec<String>,
206    pub optional: Vec<(String, Option<Expr>)>,
207    pub rest: Option<String>,
208    pub key: Vec<KeyParam>,
209    pub aux: Vec<(String, Option<Expr>)>,
210}
211
212/// A `&key` parameter: the variable, the keyword a caller passes for it
213/// (upper case) and the default form.
214#[derive(Debug, Clone, PartialEq)]
215pub struct KeyParam {
216    pub name: String,
217    pub keyword: String,
218    pub default: Option<Expr>,
219}
220
221impl KeyParam {
222    /// A parameter whose keyword is its variable name.
223    #[must_use]
224    pub fn new(name: impl Into<String>, default: Option<Expr>) -> Self {
225        let name = name.into();
226        Self {
227            keyword: name.to_uppercase(),
228            name,
229            default,
230        }
231    }
232}
233
234impl LambdaParams {
235    /// The keyword a caller passes for the `&key` variable `var`.
236    #[must_use]
237    pub fn keyword_of(&self, var: &str) -> String {
238        self.key
239            .iter()
240            .find_map(|param| (param.name == var).then(|| param.keyword.clone()))
241            .unwrap_or_else(|| var.to_uppercase())
242    }
243
244    /// The `&optional`, `&key` and `&aux` parameters as `(variable, default)`.
245    pub fn defaulted(&self) -> impl Iterator<Item = (&str, Option<&Expr>)> {
246        let optional = self.optional.iter().map(|(name, default)| (name, default));
247        let key = self.key.iter().map(|param| (&param.name, &param.default));
248        let aux = self.aux.iter().map(|(name, default)| (name, default));
249        optional
250            .chain(key)
251            .chain(aux)
252            .map(|(name, default)| (name.as_str(), default.as_ref()))
253    }
254
255    /// The default forms of the `&optional`, `&key` and `&aux` parameters.
256    pub fn defaults(&self) -> impl Iterator<Item = &Expr> {
257        self.defaulted().filter_map(|(_, default)| default)
258    }
259
260    /// Mutable access to the same default forms as [`Self::defaults`].
261    pub fn defaults_mut(&mut self) -> impl Iterator<Item = &mut Expr> {
262        let optional = self.optional.iter_mut().map(|(_, default)| default);
263        let key = self.key.iter_mut().map(|param| &mut param.default);
264        let aux = self.aux.iter_mut().map(|(_, default)| default);
265        optional
266            .chain(key)
267            .chain(aux)
268            .filter_map(|default| default.as_mut())
269    }
270}
271
272impl LambdaParams {
273    pub fn simple(params: Vec<String>) -> Self {
274        Self {
275            required: params,
276            optional: Vec::new(),
277            rest: None,
278            key: Vec::new(),
279            aux: Vec::new(),
280        }
281    }
282}
283
284#[derive(Debug, Clone, PartialEq)]
285pub enum Expr {
286    Nil,
287    T,
288    Number(Number),
289    String(String),
290    Symbol(String),
291    Keyword(String),
292    Bytes(Vec<u8>),
293    Cons(Box<Expr>, Box<Expr>),
294    List(Vec<Expr>),
295    Quote(Box<Expr>),
296    /// An evaluated value that is the datum inside; the reader never makes it.
297    Datum(Box<Expr>),
298    Quasiquote(Box<Expr>),
299    Unquote(Box<Expr>),
300    UnquoteSplicing(Box<Expr>),
301    Lambda(LambdaParams, Box<Expr>),
302    RuntimeValue(crate::runtime::Value),
303    WasmRuntime(WasmType),
304    /// Value stored in WASM local variable (index, type)
305    WasmLocal(u32, WasmType),
306    /// Value stored in a mutable module global (index, type)
307    WasmGlobal(u32, WasmType),
308    /// A session struct instance an earlier unit left (serial, layout): a leaf
309    /// the unit's prologue binds to a module global; it never folds.
310    Instance(u32, StructId),
311}
312
313/// Where a runtime variable lives: a local of the current function or a
314/// module global every function reaches.
315#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
316pub enum Place {
317    Local(u32),
318    Global(u32),
319}
320
321impl Expr {
322    #[must_use]
323    pub fn cons(car: Expr, cdr: Expr) -> Self {
324        Expr::Cons(Box::new(car), Box::new(cdr))
325    }
326
327    #[must_use]
328    pub fn symbol(name: &str) -> Self {
329        Expr::Symbol(name.to_string())
330    }
331
332    /// A body of forms as one form: the sole form, else a `PROGN`.
333    #[must_use]
334    pub fn body(forms: &[Expr]) -> Self {
335        match forms {
336            [form] => form.clone(),
337            _ => Expr::List(
338                std::iter::once(Expr::symbol("PROGN"))
339                    .chain(forms.iter().cloned())
340                    .collect(),
341            ),
342        }
343    }
344
345    /// Returns the `WasmType` if this expression is a runtime value.
346    #[must_use]
347    pub fn wasm_type(&self) -> Option<WasmType> {
348        match self {
349            Self::WasmRuntime(ty) | Self::WasmLocal(_, ty) | Self::WasmGlobal(_, ty) => Some(*ty),
350            Self::Instance(_, id) => Some(WasmType::StructRef(*id)),
351            Self::RuntimeValue(crate::runtime::Value::Commodity { .. }) => {
352                Some(WasmType::Commodity)
353            }
354            _ => None,
355        }
356    }
357
358    /// True if this is a runtime value.
359    #[must_use]
360    pub fn is_wasm_runtime(&self) -> bool {
361        matches!(
362            self,
363            Self::WasmRuntime(_)
364                | Self::WasmLocal(_, _)
365                | Self::WasmGlobal(_, _)
366                | Self::Instance(_, _)
367        )
368    }
369
370    /// True for a runtime placeholder, local or global, which means nothing
371    /// outside the function that resolved it; a session instance does.
372    #[must_use]
373    pub fn is_runtime_variable(&self) -> bool {
374        matches!(
375            self,
376            Self::WasmRuntime(_) | Self::WasmLocal(_, _) | Self::WasmGlobal(_, _)
377        )
378    }
379
380    /// Whether `test` holds of the form or of any form inside it. Walked with
381    /// an explicit stack, so a deep form cannot overflow.
382    pub fn any_form(&self, test: impl Fn(&Expr) -> bool) -> bool {
383        let mut pending = vec![self];
384        while let Some(form) = pending.pop() {
385            if test(form) {
386                return true;
387            }
388            match form {
389                Self::List(items) => pending.extend(items),
390                Self::Cons(car, cdr) => pending.extend([car.as_ref(), cdr.as_ref()]),
391                Self::Quote(inner)
392                | Self::Datum(inner)
393                | Self::Quasiquote(inner)
394                | Self::Unquote(inner)
395                | Self::UnquoteSplicing(inner) => pending.push(inner),
396                Self::Lambda(params, body) => {
397                    pending.push(body);
398                    pending.extend(params.defaults());
399                }
400                _ => {}
401            }
402        }
403        false
404    }
405
406    /// The storage and type of a runtime variable; `None` for a placeholder
407    /// or a compile-time value.
408    #[must_use]
409    pub fn place(&self) -> Option<(Place, WasmType)> {
410        match self {
411            Self::WasmLocal(idx, ty) => Some((Place::Local(*idx), *ty)),
412            Self::WasmGlobal(idx, ty) => Some((Place::Global(*idx), *ty)),
413            _ => None,
414        }
415    }
416
417    /// Whether the value is a function: a lambda or a closure place.
418    #[must_use]
419    pub fn is_function_value(&self) -> bool {
420        matches!(self, Self::Lambda(..)) || matches!(self.place(), Some((_, WasmType::Closure(_))))
421    }
422}
423
424#[derive(Debug, Clone, PartialEq)]
425pub struct Annotation {
426    pub name: String,
427    pub value: Expr,
428}
429
430impl Expr {
431    /// The single compile-time truth test: a value is false exactly when it is nil.
432    #[must_use]
433    pub fn is_nil(&self) -> bool {
434        matches!(self, Expr::Nil)
435    }
436
437    #[must_use]
438    pub fn is_atom(&self) -> bool {
439        !matches!(self, Expr::List(_) | Expr::Cons(_, _))
440    }
441
442    #[must_use]
443    pub fn as_symbol(&self) -> Option<&str> {
444        match self {
445            Expr::Symbol(s) => Some(s),
446            _ => None,
447        }
448    }
449
450    /// The elements of a list; `nil` is the empty list.
451    #[must_use]
452    pub fn as_list(&self) -> Option<&[Expr]> {
453        match self {
454            Expr::List(l) => Some(l),
455            Expr::Nil => Some(&[]),
456            _ => None,
457        }
458    }
459
460    /// Splits a `Symbol` into `(namespace, name)`. A qualified symbol is
461    /// stored canonically as `NS:NAME` (ADR-0029); an unqualified one has no
462    /// `:` and yields `(None, name)`. Non-symbols yield `None`. The split is
463    /// on the single canonical `:` — `NS::NAME` was already folded to `NS:NAME`
464    /// by the reader, so at most one `:` is ever present here.
465    #[must_use]
466    pub fn symbol_parts(&self) -> Option<(Option<&str>, &str)> {
467        let name = self.as_symbol()?;
468        Some(match name.split_once(':') {
469            Some((ns, base)) => (Some(ns), base),
470            None => (None, name),
471        })
472    }
473}
474
475/// Builds the canonical symbol-table key for a (possibly namespaced) name.
476/// `NS:NAME` when a namespace is present, bare `NAME` otherwise — the single
477/// source of truth for how a qualified name maps to its flat table key.
478#[must_use]
479pub fn canonical_symbol(namespace: Option<&str>, name: &str) -> String {
480    match namespace {
481        Some(ns) => format!("{ns}:{name}"),
482        None => name.to_string(),
483    }
484}
485
486#[derive(Debug, Clone, Default)]
487pub struct Program {
488    pub exprs: Vec<Expr>,
489    pub annotations: Vec<Annotation>,
490}
491
492impl Program {
493    #[must_use]
494    pub fn new(exprs: Vec<Expr>) -> Self {
495        Self {
496            exprs,
497            annotations: Vec::new(),
498        }
499    }
500
501    #[must_use]
502    pub fn with_annotations(exprs: Vec<Expr>, annotations: Vec<Annotation>) -> Self {
503        Self { exprs, annotations }
504    }
505}
506
507#[cfg(test)]
508#[path = "ast_tests.rs"]
509mod tests;