1
//! Standard-library loading: the essential CL macros `WHEN`, `UNLESS`, plus
2
//! the `UPCASE` utility wrapper.
3

            
4
use std::collections::HashSet;
5

            
6
use crate::ast::{Expr, LambdaParams, Number};
7
use crate::error::{Error, Result};
8

            
9
use super::entry::{Symbol, SymbolKind};
10
use super::table::SymbolTable;
11

            
12
impl SymbolTable {
13
    /// The table every script starts from, before the prelude.
14
1532510
    pub(super) fn without_prelude() -> Self {
15
1532510
        let mut table = Self::new();
16
1532510
        table.register_builtins();
17
1532510
        table.load_standard_library();
18
1532510
        table.register_compiler_natives();
19
1532510
        table
20
1532510
    }
21

            
22
    /// Every name defined before the prelude: the one source of "built-in".
23
536770
    pub(crate) fn builtin_names() -> HashSet<String> {
24
536770
        Self::without_prelude().symbols.into_keys().collect()
25
536770
    }
26

            
27
1532510
    pub(super) fn load_standard_library(&mut self) {
28
1532510
        self.load_essential_macros();
29
1532510
    }
30

            
31
1532510
    fn load_essential_macros(&mut self) {
32
1532510
        let when_params = LambdaParams {
33
1532510
            required: vec!["test".to_string()],
34
1532510
            optional: Vec::new(),
35
1532510
            rest: Some("body".to_string()),
36
1532510
            key: Vec::new(),
37
1532510
            aux: Vec::new(),
38
1532510
        };
39
1532510
        let when_body = Expr::Quasiquote(Box::new(Expr::List(vec![
40
1532510
            Expr::symbol("IF"),
41
1532510
            Expr::Unquote(Box::new(Expr::Symbol("test".to_string()))),
42
1532510
            Expr::List(vec![
43
1532510
                Expr::symbol("PROGN"),
44
1532510
                Expr::UnquoteSplicing(Box::new(Expr::Symbol("body".to_string()))),
45
1532510
            ]),
46
1532510
            Expr::Nil,
47
1532510
        ])));
48
1532510
        let when_lambda = Expr::Lambda(when_params, Box::new(when_body));
49
1532510
        self.define(Symbol::new("WHEN", SymbolKind::Macro).with_function(when_lambda));
50

            
51
1532510
        let unless_params = LambdaParams {
52
1532510
            required: vec!["test".to_string()],
53
1532510
            optional: Vec::new(),
54
1532510
            rest: Some("body".to_string()),
55
1532510
            key: Vec::new(),
56
1532510
            aux: Vec::new(),
57
1532510
        };
58
1532510
        let unless_body = Expr::Quasiquote(Box::new(Expr::List(vec![
59
1532510
            Expr::symbol("IF"),
60
1532510
            Expr::Unquote(Box::new(Expr::Symbol("test".to_string()))),
61
1532510
            Expr::Nil,
62
1532510
            Expr::List(vec![
63
1532510
                Expr::symbol("PROGN"),
64
1532510
                Expr::UnquoteSplicing(Box::new(Expr::Symbol("body".to_string()))),
65
1532510
            ]),
66
1532510
        ])));
67
1532510
        let unless_lambda = Expr::Lambda(unless_params, Box::new(unless_body));
68
1532510
        self.define(Symbol::new("UNLESS", SymbolKind::Macro).with_function(unless_lambda));
69

            
70
1532510
        let return_params = LambdaParams {
71
1532510
            required: Vec::new(),
72
1532510
            optional: Vec::new(),
73
1532510
            rest: Some("value".to_string()),
74
1532510
            key: Vec::new(),
75
1532510
            aux: Vec::new(),
76
1532510
        };
77
1532510
        let return_body = Expr::Quasiquote(Box::new(Expr::List(vec![
78
1532510
            Expr::symbol("RETURN-FROM"),
79
1532510
            Expr::Nil,
80
1532510
            Expr::UnquoteSplicing(Box::new(Expr::Symbol("value".to_string()))),
81
1532510
        ])));
82
1532510
        let return_lambda = Expr::Lambda(return_params, Box::new(return_body));
83
1532510
        self.define(Symbol::new("RETURN", SymbolKind::Macro).with_function(return_lambda));
84

            
85
1532510
        self.define(Symbol::new("DOTIMES", SymbolKind::Macro).with_function(dotimes_lambda()));
86

            
87
1532510
        self.add_utility_functions();
88
1532510
    }
89

            
90
1532510
    fn add_utility_functions(&mut self) {
91
1532510
        let upcase_params = LambdaParams::simple(vec!["string".to_string()]);
92
1532510
        let upcase_body = Expr::List(vec![
93
1532510
            Expr::symbol("UPCASE-STRING"),
94
1532510
            Expr::Symbol("string".to_string()),
95
1532510
        ]);
96
1532510
        let upcase_lambda = Expr::Lambda(upcase_params, Box::new(upcase_body));
97
1532510
        self.define(Symbol::new("UPCASE", SymbolKind::Function).with_function(upcase_lambda));
98
1532510
    }
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
995740
    pub(super) fn load_prelude(&mut self) -> Result<()> {
111
995740
        self.load_nomiscript_defuns(include_str!("prelude.nms"))
112
995740
    }
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
1366608
    pub fn load_nomiscript_defuns(&mut self, source: &str) -> Result<()> {
122
1366608
        let program = crate::reader::Reader::parse(source)?;
123
1366607
        for form in &program.exprs {
124
4724691
            match form.as_list().and_then(<[Expr]>::split_first) {
125
4724691
                Some((Expr::Symbol(head), tail)) if head == "DEFUN" => {
126
4724690
                    crate::compiler::special::call(self, "DEFUN", tail)?;
127
                }
128
                _ => {
129
1
                    return Err(Error::Compile(
130
1
                        "only top-level DEFUN forms are allowed".to_string(),
131
1
                    ));
132
                }
133
            }
134
        }
135
1366605
        Ok(())
136
1366608
    }
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.
141
pub(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.
145
1532510
fn dotimes_lambda() -> Expr {
146
1532510
    let params = LambdaParams {
147
1532510
        required: vec!["spec".to_string()],
148
1532510
        optional: Vec::new(),
149
1532510
        rest: Some("body".to_string()),
150
1532510
        key: Vec::new(),
151
1532510
        aux: Vec::new(),
152
1532510
    };
153
24520160
    let call = |name: &str, args: Vec<Expr>| {
154
24520160
        Expr::List(std::iter::once(Expr::symbol(name)).chain(args).collect())
155
24520160
    };
156
6130040
    let unquote = |form: Expr| Expr::Unquote(Box::new(form));
157
9195060
    let spec = || Expr::Symbol("spec".to_string());
158
4597530
    let var = || unquote(call("CAR", vec![spec()]));
159
1532510
    let count = Expr::Symbol(DOTIMES_COUNT.to_string());
160
1532510
    let step = call("+", vec![var(), Expr::Number(Number::Index(1))]);
161
1532510
    let bindings = Expr::List(vec![
162
1532510
        Expr::List(vec![var(), Expr::Number(Number::Index(0)), step]),
163
1532510
        Expr::List(vec![
164
1532510
            count.clone(),
165
1532510
            call(
166
1532510
                "THE",
167
1532510
                vec![
168
1532510
                    Expr::symbol(DOTIMES_COUNT),
169
1532510
                    unquote(call("CAR", vec![call("CDR", vec![spec()])])),
170
1532510
                ],
171
1532510
            ),
172
1532510
        ]),
173
1532510
    ]);
174
1532510
    let results = call("CDR", vec![call("CDR", vec![spec()])]);
175
1532510
    let end = Expr::List(vec![
176
1532510
        call(">=", vec![var(), count]),
177
1532510
        Expr::UnquoteSplicing(Box::new(results)),
178
1532510
    ]);
179
1532510
    let expansion = Expr::Quasiquote(Box::new(Expr::List(vec![
180
1532510
        Expr::symbol("DO"),
181
1532510
        bindings,
182
1532510
        end,
183
1532510
        Expr::UnquoteSplicing(Box::new(Expr::Symbol("body".to_string()))),
184
1532510
    ])));
185
1532510
    let extra_result = call("CDR", vec![call("CDR", vec![call("CDR", vec![spec()])])]);
186
1532510
    let refuse = call(
187
1532510
        "ERROR",
188
1532510
        vec![
189
1532510
            Expr::Quote(Box::new(Expr::symbol("DOTIMES"))),
190
1532510
            Expr::String("DOTIMES takes at most one result form".to_string()),
191
1532510
        ],
192
1532510
    );
193
1532510
    let body = call(
194
1532510
        "PROGN",
195
1532510
        vec![call("IF", vec![extra_result, refuse]), expansion],
196
1532510
    );
197
1532510
    Expr::Lambda(params, Box::new(body))
198
1532510
}