Skip to main content

nomiscript/runtime/symbol/
stdlib.rs

1//! Standard-library loading: the essential CL macros `WHEN`, `UNLESS`, plus
2//! the `UPCASE` utility wrapper.
3
4use std::collections::HashSet;
5
6use crate::ast::{Expr, LambdaParams, Number};
7use crate::error::{Error, Result};
8
9use super::entry::{Symbol, SymbolKind};
10use super::table::SymbolTable;
11
12impl SymbolTable {
13    /// The table every script starts from, before the prelude.
14    pub(super) fn without_prelude() -> Self {
15        let mut table = Self::new();
16        table.register_builtins();
17        table.load_standard_library();
18        table.register_compiler_natives();
19        table
20    }
21
22    /// Every name defined before the prelude: the one source of "built-in".
23    pub(crate) fn builtin_names() -> HashSet<String> {
24        Self::without_prelude().symbols.into_keys().collect()
25    }
26
27    pub(super) fn load_standard_library(&mut self) {
28        self.load_essential_macros();
29    }
30
31    fn load_essential_macros(&mut self) {
32        let when_params = LambdaParams {
33            required: vec!["test".to_string()],
34            optional: Vec::new(),
35            rest: Some("body".to_string()),
36            key: Vec::new(),
37            aux: Vec::new(),
38        };
39        let when_body = Expr::Quasiquote(Box::new(Expr::List(vec![
40            Expr::symbol("IF"),
41            Expr::Unquote(Box::new(Expr::Symbol("test".to_string()))),
42            Expr::List(vec![
43                Expr::symbol("PROGN"),
44                Expr::UnquoteSplicing(Box::new(Expr::Symbol("body".to_string()))),
45            ]),
46            Expr::Nil,
47        ])));
48        let when_lambda = Expr::Lambda(when_params, Box::new(when_body));
49        self.define(Symbol::new("WHEN", SymbolKind::Macro).with_function(when_lambda));
50
51        let unless_params = LambdaParams {
52            required: vec!["test".to_string()],
53            optional: Vec::new(),
54            rest: Some("body".to_string()),
55            key: Vec::new(),
56            aux: Vec::new(),
57        };
58        let unless_body = Expr::Quasiquote(Box::new(Expr::List(vec![
59            Expr::symbol("IF"),
60            Expr::Unquote(Box::new(Expr::Symbol("test".to_string()))),
61            Expr::Nil,
62            Expr::List(vec![
63                Expr::symbol("PROGN"),
64                Expr::UnquoteSplicing(Box::new(Expr::Symbol("body".to_string()))),
65            ]),
66        ])));
67        let unless_lambda = Expr::Lambda(unless_params, Box::new(unless_body));
68        self.define(Symbol::new("UNLESS", SymbolKind::Macro).with_function(unless_lambda));
69
70        let return_params = LambdaParams {
71            required: Vec::new(),
72            optional: Vec::new(),
73            rest: Some("value".to_string()),
74            key: Vec::new(),
75            aux: Vec::new(),
76        };
77        let return_body = Expr::Quasiquote(Box::new(Expr::List(vec![
78            Expr::symbol("RETURN-FROM"),
79            Expr::Nil,
80            Expr::UnquoteSplicing(Box::new(Expr::Symbol("value".to_string()))),
81        ])));
82        let return_lambda = Expr::Lambda(return_params, Box::new(return_body));
83        self.define(Symbol::new("RETURN", SymbolKind::Macro).with_function(return_lambda));
84
85        self.define(Symbol::new("DOTIMES", SymbolKind::Macro).with_function(dotimes_lambda()));
86
87        self.add_utility_functions();
88    }
89
90    fn add_utility_functions(&mut self) {
91        let upcase_params = LambdaParams::simple(vec!["string".to_string()]);
92        let upcase_body = Expr::List(vec![
93            Expr::symbol("UPCASE-STRING"),
94            Expr::Symbol("string".to_string()),
95        ]);
96        let upcase_lambda = Expr::Lambda(upcase_params, Box::new(upcase_body));
97        self.define(Symbol::new("UPCASE", SymbolKind::Function).with_function(upcase_lambda));
98    }
99
100    /// Loads the universal nomiscript prelude (ADR-0029) — reusable helpers
101    /// authored IN nomiscript and shared by every table. Called last in
102    /// `with_builtins*` so the prelude's DEFUNs see the builtins + accessors.
103    /// The source is DEFUN-only and references only universally-present
104    /// symbols, so it loads identically on the eval/host and pure-wasm paths
105    /// (a DEFUN stores its lambda body without resolving it). Host-fn-dependent
106    /// helpers are loaded separately on the rpc Session path.
107    ///
108    /// # Errors
109    /// The baked prelude source fails to load.
110    pub(super) fn load_prelude(&mut self) -> Result<()> {
111        self.load_nomiscript_defuns(include_str!("prelude.nms"))
112    }
113
114    /// Parses a DEFUN-only nomiscript source and registers each `defun` into
115    /// this table via the eval special-form path. Shared by the universal
116    /// prelude here and the rpc host prelude.
117    ///
118    /// # Errors
119    /// The source does not parse, a top-level form is not a DEFUN, or a DEFUN
120    /// is refused.
121    pub fn load_nomiscript_defuns(&mut self, source: &str) -> Result<()> {
122        let program = crate::reader::Reader::parse(source)?;
123        for form in &program.exprs {
124            match form.as_list().and_then(<[Expr]>::split_first) {
125                Some((Expr::Symbol(head), tail)) if head == "DEFUN" => {
126                    crate::compiler::special::call(self, "DEFUN", tail)?;
127                }
128                _ => {
129                    return Err(Error::Compile(
130                        "only top-level DEFUN forms are allowed".to_string(),
131                    ));
132                }
133            }
134        }
135        Ok(())
136    }
137}
138
139/// Both the hidden count variable of DOTIMES and the type word of the THE
140/// that checks it; no program can spell it.
141pub(crate) const DOTIMES_COUNT: &str = "DOTIMES COUNT";
142
143/// `(dotimes (var count result…) body…)` as a DO over `var` from 0 and a hidden
144/// variable holding `count`, evaluated once.
145fn dotimes_lambda() -> Expr {
146    let params = LambdaParams {
147        required: vec!["spec".to_string()],
148        optional: Vec::new(),
149        rest: Some("body".to_string()),
150        key: Vec::new(),
151        aux: Vec::new(),
152    };
153    let call = |name: &str, args: Vec<Expr>| {
154        Expr::List(std::iter::once(Expr::symbol(name)).chain(args).collect())
155    };
156    let unquote = |form: Expr| Expr::Unquote(Box::new(form));
157    let spec = || Expr::Symbol("spec".to_string());
158    let var = || unquote(call("CAR", vec![spec()]));
159    let count = Expr::Symbol(DOTIMES_COUNT.to_string());
160    let step = call("+", vec![var(), Expr::Number(Number::Index(1))]);
161    let bindings = Expr::List(vec![
162        Expr::List(vec![var(), Expr::Number(Number::Index(0)), step]),
163        Expr::List(vec![
164            count.clone(),
165            call(
166                "THE",
167                vec![
168                    Expr::symbol(DOTIMES_COUNT),
169                    unquote(call("CAR", vec![call("CDR", vec![spec()])])),
170                ],
171            ),
172        ]),
173    ]);
174    let results = call("CDR", vec![call("CDR", vec![spec()])]);
175    let end = Expr::List(vec![
176        call(">=", vec![var(), count]),
177        Expr::UnquoteSplicing(Box::new(results)),
178    ]);
179    let expansion = Expr::Quasiquote(Box::new(Expr::List(vec![
180        Expr::symbol("DO"),
181        bindings,
182        end,
183        Expr::UnquoteSplicing(Box::new(Expr::Symbol("body".to_string()))),
184    ])));
185    let extra_result = call("CDR", vec![call("CDR", vec![call("CDR", vec![spec()])])]);
186    let refuse = call(
187        "ERROR",
188        vec![
189            Expr::Quote(Box::new(Expr::symbol("DOTIMES"))),
190            Expr::String("DOTIMES takes at most one result form".to_string()),
191        ],
192    );
193    let body = call(
194        "PROGN",
195        vec![call("IF", vec![extra_result, refuse]), expansion],
196    );
197    Expr::Lambda(params, Box::new(body))
198}