1
use core::fmt;
2

            
3
use num_rational::Ratio;
4

            
5
pub 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)]
11
pub enum Number {
12
    Index(i64),
13
    Scalar(Fraction),
14
}
15

            
16
impl Number {
17
    /// The exact value, whatever the kind.
18
    #[must_use]
19
58396851
    pub fn value(self) -> Fraction {
20
58396851
        match self {
21
58263415
            Self::Index(n) => Fraction::from_integer(n),
22
133436
            Self::Scalar(f) => f,
23
        }
24
58396851
    }
25
}
26

            
27
/// The readable spelling: an index as `N`, a scalar always as `n/d`.
28
impl fmt::Display for Number {
29
45586007
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
30
45586007
        match self {
31
45523379
            Self::Index(n) => write!(f, "{n}"),
32
62628
            Self::Scalar(s) => write!(f, "{}/{}", s.numer(), s.denom()),
33
        }
34
45586007
    }
35
}
36

            
37
pub 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)]
46
pub 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

            
61
impl 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
1591114
    pub fn wire_code(self) -> i64 {
79
1591114
        Self::ALL
80
1591114
            .iter()
81
7163660
            .position(|kind| *kind == self)
82
1591114
            .map_or(i64::MAX, |index| index as i64)
83
1591114
    }
84

            
85
    /// The kind at `code` in [`Self::ALL`], if any.
86
    #[must_use]
87
11242
    pub fn from_wire_code(code: i64) -> Option<Self> {
88
11242
        usize::try_from(code)
89
11242
            .ok()
90
11241
            .and_then(|index| Self::ALL.get(index).copied())
91
11242
    }
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
7947508
    pub fn type_name(self) -> &'static str {
98
7947508
        match self {
99
1136330
            Self::Account => "account",
100
1135890
            Self::Commodity => "commodity_entity",
101
1135889
            Self::Transaction => "transaction",
102
1134433
            Self::Split => "split",
103
1135889
            Self::Tag => "tag_entity",
104
1134433
            Self::Price => "price",
105
1134433
            Self::SshKey => "ssh_key",
106
211
            Self::Condition => "nomi_condition",
107
        }
108
7947508
    }
109
}
110

            
111
impl fmt::Display for EntityKind {
112
237
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
113
237
        write!(f, "{}", self.type_name())
114
237
    }
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)]
125
pub struct ClosureSigId(pub u32);
126

            
127
impl fmt::Display for ClosureSigId {
128
3847
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
129
3847
        write!(f, "{}", self.0)
130
3847
    }
131
}
132

            
133
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
134
pub 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

            
185
impl fmt::Display for WasmType {
186
36782
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
187
36782
        match self {
188
14897
            Self::I32 => write!(f, "i32"),
189
3892
            Self::Bool => write!(f, "bool"),
190
715
            Self::Ratio => write!(f, "ratio"),
191
4412
            Self::StringRef => write!(f, "string"),
192
449
            Self::SymbolRef => write!(f, "symbol"),
193
222
            Self::Commodity => write!(f, "commodity"),
194
1712
            Self::PairRef(elem) => write!(f, "pair<{elem}>"),
195
237
            Self::EntityRef(kind) => write!(f, "entity<{kind}>"),
196
1458
            Self::StructRef(id) => write!(f, "{id}"),
197
1126
            Self::Closure(sig) => write!(f, "closure<{sig}>"),
198
7662
            Self::AnyRef => write!(f, "any"),
199
        }
200
36782
    }
201
}
202

            
203
#[derive(Debug, Clone, PartialEq)]
204
pub 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)]
215
pub struct KeyParam {
216
    pub name: String,
217
    pub keyword: String,
218
    pub default: Option<Expr>,
219
}
220

            
221
impl KeyParam {
222
    /// A parameter whose keyword is its variable name.
223
    #[must_use]
224
1930649
    pub fn new(name: impl Into<String>, default: Option<Expr>) -> Self {
225
1930649
        let name = name.into();
226
1930649
        Self {
227
1930649
            keyword: name.to_uppercase(),
228
1930649
            name,
229
1930649
            default,
230
1930649
        }
231
1930649
    }
232
}
233

            
234
impl 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
180826186
    pub fn defaulted(&self) -> impl Iterator<Item = (&str, Option<&Expr>)> {
246
180826186
        let optional = self.optional.iter().map(|(name, default)| (name, default));
247
180826186
        let key = self.key.iter().map(|param| (&param.name, &param.default));
248
180826186
        let aux = self.aux.iter().map(|(name, default)| (name, default));
249
180826186
        optional
250
180826186
            .chain(key)
251
180826186
            .chain(aux)
252
194071
            .map(|(name, default)| (name.as_str(), default.as_ref()))
253
180826186
    }
254

            
255
    /// The default forms of the `&optional`, `&key` and `&aux` parameters.
256
4607547
    pub fn defaults(&self) -> impl Iterator<Item = &Expr> {
257
4607547
        self.defaulted().filter_map(|(_, default)| default)
258
4607547
    }
259

            
260
    /// Mutable access to the same default forms as [`Self::defaults`].
261
12873861
    pub fn defaults_mut(&mut self) -> impl Iterator<Item = &mut Expr> {
262
12873861
        let optional = self.optional.iter_mut().map(|(_, default)| default);
263
12873861
        let key = self.key.iter_mut().map(|param| &mut param.default);
264
12873861
        let aux = self.aux.iter_mut().map(|(_, default)| default);
265
12873861
        optional
266
12873861
            .chain(key)
267
12873861
            .chain(aux)
268
4484750
            .filter_map(|default| default.as_mut())
269
12873861
    }
270
}
271

            
272
impl LambdaParams {
273
12592914
    pub fn simple(params: Vec<String>) -> Self {
274
12592914
        Self {
275
12592914
            required: params,
276
12592914
            optional: Vec::new(),
277
12592914
            rest: None,
278
12592914
            key: Vec::new(),
279
12592914
            aux: Vec::new(),
280
12592914
        }
281
12592914
    }
282
}
283

            
284
#[derive(Debug, Clone, PartialEq)]
285
pub 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)]
316
pub enum Place {
317
    Local(u32),
318
    Global(u32),
319
}
320

            
321
impl Expr {
322
    #[must_use]
323
516548
    pub fn cons(car: Expr, cdr: Expr) -> Self {
324
516548
        Expr::Cons(Box::new(car), Box::new(cdr))
325
516548
    }
326

            
327
    #[must_use]
328
49619485
    pub fn symbol(name: &str) -> Self {
329
49619485
        Expr::Symbol(name.to_string())
330
49619485
    }
331

            
332
    /// A body of forms as one form: the sole form, else a `PROGN`.
333
    #[must_use]
334
11419747
    pub fn body(forms: &[Expr]) -> Self {
335
11419747
        match forms {
336
11395372
            [form] => form.clone(),
337
24375
            _ => Expr::List(
338
24375
                std::iter::once(Expr::symbol("PROGN"))
339
24375
                    .chain(forms.iter().cloned())
340
24375
                    .collect(),
341
24375
            ),
342
        }
343
11419747
    }
344

            
345
    /// Returns the `WasmType` if this expression is a runtime value.
346
    #[must_use]
347
19798167
    pub fn wasm_type(&self) -> Option<WasmType> {
348
19798167
        match self {
349
14736785
            Self::WasmRuntime(ty) | Self::WasmLocal(_, ty) | Self::WasmGlobal(_, ty) => Some(*ty),
350
38480
            Self::Instance(_, id) => Some(WasmType::StructRef(*id)),
351
            Self::RuntimeValue(crate::runtime::Value::Commodity { .. }) => {
352
2288
                Some(WasmType::Commodity)
353
            }
354
5020614
            _ => None,
355
        }
356
19798167
    }
357

            
358
    /// True if this is a runtime value.
359
    #[must_use]
360
950851167
    pub fn is_wasm_runtime(&self) -> bool {
361
950851167
        matches!(
362
950851167
            self,
363
            Self::WasmRuntime(_)
364
                | Self::WasmLocal(_, _)
365
                | Self::WasmGlobal(_, _)
366
                | Self::Instance(_, _)
367
        )
368
950851167
    }
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
5172083
    pub fn is_runtime_variable(&self) -> bool {
374
5172083
        matches!(
375
5172083
            self,
376
            Self::WasmRuntime(_) | Self::WasmLocal(_, _) | Self::WasmGlobal(_, _)
377
        )
378
5172083
    }
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
28280575
    pub fn any_form(&self, test: impl Fn(&Expr) -> bool) -> bool {
383
28280575
        let mut pending = vec![self];
384
845766271
        while let Some(form) = pending.pop() {
385
818625700
            if test(form) {
386
1140004
                return true;
387
817485696
            }
388
817485696
            match form {
389
23345223
                Self::List(items) => pending.extend(items),
390
209
                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
330143
                | Self::UnquoteSplicing(inner) => pending.push(inner),
396
                Self::Lambda(params, body) => {
397
186473
                    pending.push(body);
398
186473
                    pending.extend(params.defaults());
399
                }
400
793623648
                _ => {}
401
            }
402
        }
403
27140571
        false
404
28280575
    }
405

            
406
    /// The storage and type of a runtime variable; `None` for a placeholder
407
    /// or a compile-time value.
408
    #[must_use]
409
4702447
    pub fn place(&self) -> Option<(Place, WasmType)> {
410
4702447
        match self {
411
1777039
            Self::WasmLocal(idx, ty) => Some((Place::Local(*idx), *ty)),
412
572705
            Self::WasmGlobal(idx, ty) => Some((Place::Global(*idx), *ty)),
413
2352703
            _ => None,
414
        }
415
4702447
    }
416

            
417
    /// Whether the value is a function: a lambda or a closure place.
418
    #[must_use]
419
14474
    pub fn is_function_value(&self) -> bool {
420
14474
        matches!(self, Self::Lambda(..)) || matches!(self.place(), Some((_, WasmType::Closure(_))))
421
14474
    }
422
}
423

            
424
#[derive(Debug, Clone, PartialEq)]
425
pub struct Annotation {
426
    pub name: String,
427
    pub value: Expr,
428
}
429

            
430
impl Expr {
431
    /// The single compile-time truth test: a value is false exactly when it is nil.
432
    #[must_use]
433
108928930
    pub fn is_nil(&self) -> bool {
434
108928930
        matches!(self, Expr::Nil)
435
108928930
    }
436

            
437
    #[must_use]
438
9
    pub fn is_atom(&self) -> bool {
439
9
        !matches!(self, Expr::List(_) | Expr::Cons(_, _))
440
9
    }
441

            
442
    #[must_use]
443
64643114
    pub fn as_symbol(&self) -> Option<&str> {
444
64643114
        match self {
445
52621824
            Expr::Symbol(s) => Some(s),
446
12021290
            _ => None,
447
        }
448
64643114
    }
449

            
450
    /// The elements of a list; `nil` is the empty list.
451
    #[must_use]
452
272205148
    pub fn as_list(&self) -> Option<&[Expr]> {
453
272205148
        match self {
454
271040500
            Expr::List(l) => Some(l),
455
1152282
            Expr::Nil => Some(&[]),
456
12366
            _ => None,
457
        }
458
272205148
    }
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]
479
4361961
pub fn canonical_symbol(namespace: Option<&str>, name: &str) -> String {
480
4361961
    match namespace {
481
4361960
        Some(ns) => format!("{ns}:{name}"),
482
1
        None => name.to_string(),
483
    }
484
4361961
}
485

            
486
#[derive(Debug, Clone, Default)]
487
pub struct Program {
488
    pub exprs: Vec<Expr>,
489
    pub annotations: Vec<Annotation>,
490
}
491

            
492
impl Program {
493
    #[must_use]
494
661456
    pub fn new(exprs: Vec<Expr>) -> Self {
495
661456
        Self {
496
661456
            exprs,
497
661456
            annotations: Vec::new(),
498
661456
        }
499
661456
    }
500

            
501
    #[must_use]
502
18048988
    pub fn with_annotations(exprs: Vec<Expr>, annotations: Vec<Annotation>) -> Self {
503
18048988
        Self { exprs, annotations }
504
18048988
    }
505
}
506

            
507
#[cfg(test)]
508
#[path = "ast_tests.rs"]
509
mod tests;