Skip to main content

nomiscript/runtime/symbol/
builtins.rs

1//! Built-in registrations: operators, special forms, native fns,
2//! entity-type/context constants, compiler-generated natives (entity and
3//! typed-entity accessors), and the MAP-family macros (MAPCAR / MAPC).
4
5use crate::ast::{Expr, LambdaParams, Number};
6
7use super::entry::{Symbol, SymbolKind};
8use super::table::SymbolTable;
9
10impl SymbolTable {
11    pub fn register_builtins(&mut self) {
12        // Name lists tangle from doc/scripting/builtin_reference.org
13        // into builtins_generated.rs — the org registry tables are
14        // the single source of truth. Adding a builtin = one org row.
15        for op in super::builtins_generated::OPERATORS {
16            self.define(Symbol::new(*op, SymbolKind::Operator));
17        }
18        for form in super::builtins_generated::SPECIAL_FORMS {
19            self.define(Symbol::new(*form, SymbolKind::SpecialForm));
20        }
21        for native in super::builtins_generated::NATIVES {
22            self.define(Symbol::new(*native, SymbolKind::Native));
23        }
24
25        self.register_entity_constants();
26        self.register_compiler_natives();
27
28        self.add_map_family_macros();
29    }
30
31    fn register_entity_constants(&mut self) {
32        use scripting_format::{ContextType, EntityType};
33
34        let entity_types: &[(&str, EntityType)] = &[
35            ("+ENTITY-TRANSACTION+", EntityType::Transaction),
36            ("+ENTITY-SPLIT+", EntityType::Split),
37            ("+ENTITY-TAG+", EntityType::Tag),
38            ("+ENTITY-ACCOUNT+", EntityType::Account),
39            ("+ENTITY-COMMODITY+", EntityType::Commodity),
40        ];
41        for (name, ty) in entity_types {
42            self.define_special(
43                Symbol::new(*name, SymbolKind::Variable)
44                    .with_value(Expr::Number(Number::Index(i64::from(*ty as u8)))),
45            );
46        }
47
48        let context_types: &[(&str, ContextType)] = &[
49            ("+CONTEXT-CREATE+", ContextType::EntityCreate),
50            ("+CONTEXT-UPDATE+", ContextType::EntityUpdate),
51            ("+CONTEXT-DELETE+", ContextType::EntityDelete),
52            ("+CONTEXT-BATCH+", ContextType::BatchProcess),
53        ];
54        for (name, ct) in context_types {
55            self.define_special(
56                Symbol::new(*name, SymbolKind::Variable)
57                    .with_value(Expr::Number(Number::Index(i64::from(*ct as u8)))),
58            );
59        }
60    }
61
62    pub(super) fn register_compiler_natives(&mut self) {
63        for name in crate::compiler::native_names() {
64            if !is_listed_builtin(name) {
65                self.define(Symbol::new(name, SymbolKind::Native));
66            }
67        }
68    }
69
70    fn add_map_family_macros(&mut self) {
71        let mapcar_params = LambdaParams {
72            required: vec!["func".to_string(), "list".to_string()],
73            optional: Vec::new(),
74            rest: Some("lists".to_string()),
75            key: Vec::new(),
76            aux: Vec::new(),
77        };
78        // Backquoted so the argument FORMS splice into the expansion unevaluated;
79        // evaluating them here would bake a runtime list's placeholder into it.
80        let mapcar_body = map_call_template(vec![
81            unquote("func"),
82            unquote("list"),
83            Expr::UnquoteSplicing(Box::new(Expr::Symbol("lists".to_string()))),
84        ]);
85        let mapcar_lambda = Expr::Lambda(mapcar_params, Box::new(mapcar_body));
86        self.define(Symbol::new("MAPCAR", SymbolKind::Macro).with_function(mapcar_lambda));
87
88        let mapc_params = LambdaParams::simple(vec!["func".to_string(), "list".to_string()]);
89        let mapc_body = mapc_template();
90        let mapc_lambda = Expr::Lambda(mapc_params, Box::new(mapc_body));
91        self.define(Symbol::new("MAPC", SymbolKind::Macro).with_function(mapc_lambda));
92    }
93}
94
95/// Names the builtin reference lists keep their listed kind.
96fn is_listed_builtin(name: &str) -> bool {
97    [
98        super::builtins_generated::OPERATORS,
99        super::builtins_generated::SPECIAL_FORMS,
100        super::builtins_generated::NATIVES,
101    ]
102    .iter()
103    .any(|names| names.contains(&name))
104}
105
106/// `` `(map ,@args) `` — a MAP call template for the map-family macros.
107fn map_call_template(args: Vec<Expr>) -> Expr {
108    let mut call = vec![Expr::symbol("MAP")];
109    call.extend(args);
110    Expr::Quasiquote(Box::new(Expr::List(call)))
111}
112
113/// `` `(let ((<l> ,list)) (map ,func <l>) <l>) ``: MAPC answers its list
114/// argument, evaluated once. `<l>` has a lowercase name with a space, which
115/// the reader never produces, so it cannot capture a variable `func` reads.
116fn mapc_template() -> Expr {
117    let list = || Expr::Symbol("mapc list".to_string());
118    Expr::Quasiquote(Box::new(Expr::List(vec![
119        Expr::symbol("LET"),
120        Expr::List(vec![Expr::List(vec![list(), unquote("list")])]),
121        Expr::List(vec![Expr::symbol("MAP"), unquote("func"), list()]),
122        list(),
123    ])))
124}
125
126fn unquote(param: &str) -> Expr {
127    Expr::Unquote(Box::new(Expr::Symbol(param.to_string())))
128}