1
use crate::ast::{Expr, WasmType};
2
use crate::compiler::expr::format_form;
3
use crate::error::{Error, Result};
4
use crate::reserved::reject_reserved;
5
use crate::runtime::{Head, Symbol, SymbolKind, SymbolTable};
6

            
7
use super::super::context::CompileContext;
8
use super::super::emit::FunctionEmitter;
9
use super::super::expr::{compile_expr, compile_for_stack};
10
use super::SpecialFormSpec;
11
use super::binding::parse_macro_params;
12
use super::compile_eval::folded_form;
13

            
14
pub(super) const FORMS: &[SpecialFormSpec] = &[
15
    SpecialFormSpec {
16
        name: "DEFMACRO",
17
        eval: defmacro,
18
        compile: compile_defmacro_form,
19
        stack: None,
20
        effect: Some(compile_defmacro_for_effect),
21
    },
22
    SpecialFormSpec {
23
        name: "MACROEXPAND-1",
24
        eval: macroexpand_1,
25
        compile: compile_macroexpand_1_form,
26
        stack: Some(compile_macroexpand_1_for_stack),
27
        effect: Some(compile_macroexpand_1_for_effect),
28
    },
29
    SpecialFormSpec {
30
        name: "MACROEXPAND",
31
        eval: macroexpand,
32
        compile: compile_macroexpand_form,
33
        stack: Some(compile_macroexpand_for_stack),
34
        effect: Some(compile_macroexpand_for_effect),
35
    },
36
];
37

            
38
414757
pub(super) fn compile_defmacro_form(
39
414757
    ctx: &mut CompileContext,
40
414757
    emit: &mut FunctionEmitter,
41
414757
    symbols: &mut SymbolTable,
42
414757
    args: &[Expr],
43
414757
) -> Result<()> {
44
414757
    let result = defmacro(symbols, args)?;
45
412881
    compile_expr(ctx, emit, symbols, &result)
46
414757
}
47

            
48
434930
fn compile_defmacro_for_effect(
49
434930
    _ctx: &mut CompileContext,
50
434930
    _emit: &mut FunctionEmitter,
51
434930
    symbols: &mut SymbolTable,
52
434930
    args: &[Expr],
53
434930
) -> Result<()> {
54
434930
    defmacro(symbols, args).map(drop)
55
434930
}
56

            
57
1046
pub(super) fn compile_macroexpand_1_form(
58
1046
    ctx: &mut CompileContext,
59
1046
    emit: &mut FunctionEmitter,
60
1046
    symbols: &mut SymbolTable,
61
1046
    args: &[Expr],
62
1046
) -> Result<()> {
63
1046
    let result = macroexpand_1(symbols, args)?;
64
836
    compile_expr(ctx, emit, symbols, &result)
65
1046
}
66

            
67
1250
pub(super) fn compile_macroexpand_form(
68
1250
    ctx: &mut CompileContext,
69
1250
    emit: &mut FunctionEmitter,
70
1250
    symbols: &mut SymbolTable,
71
1250
    args: &[Expr],
72
1250
) -> Result<()> {
73
1250
    let result = macroexpand(symbols, args)?;
74
1042
    compile_expr(ctx, emit, symbols, &result)
75
1250
}
76

            
77
8
fn compile_macroexpand_1_for_stack(
78
8
    ctx: &mut CompileContext,
79
8
    emit: &mut FunctionEmitter,
80
8
    symbols: &mut SymbolTable,
81
8
    args: &[Expr],
82
8
) -> Result<WasmType> {
83
8
    let result = macroexpand_1(symbols, args)?;
84
5
    compile_for_stack(ctx, emit, symbols, &result)
85
8
}
86

            
87
18
fn compile_macroexpand_for_stack(
88
18
    ctx: &mut CompileContext,
89
18
    emit: &mut FunctionEmitter,
90
18
    symbols: &mut SymbolTable,
91
18
    args: &[Expr],
92
18
) -> Result<WasmType> {
93
18
    let result = macroexpand(symbols, args)?;
94
18
    compile_for_stack(ctx, emit, symbols, &result)
95
18
}
96

            
97
fn compile_macroexpand_1_for_effect(
98
    _ctx: &mut CompileContext,
99
    _emit: &mut FunctionEmitter,
100
    symbols: &mut SymbolTable,
101
    args: &[Expr],
102
) -> Result<()> {
103
    macroexpand_1(symbols, args).map(drop)
104
}
105

            
106
3
fn compile_macroexpand_for_effect(
107
3
    _ctx: &mut CompileContext,
108
3
    _emit: &mut FunctionEmitter,
109
3
    symbols: &mut SymbolTable,
110
3
    args: &[Expr],
111
3
) -> Result<()> {
112
3
    macroexpand(symbols, args).map(drop)
113
3
}
114

            
115
1710238
pub(super) fn defmacro(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
116
1710238
    if args.len() < 3 {
117
416
        return Err(Error::Compile(
118
416
            "DEFMACRO requires a name, parameter list, and body".to_string(),
119
416
        ));
120
1709822
    }
121
    // Always compile-time-only — same reasoning as DEFUN.
122
1709822
    super::reject_definition_under_runtime_guard(symbols, "DEFMACRO")?;
123
1709611
    let name = match &args[0] {
124
1709189
        Expr::Symbol(s) => reject_reserved(symbols, s).map(|()| s.clone())?,
125
        other => {
126
422
            return Err(Error::Compile(format!(
127
422
                "DEFMACRO: expected symbol name, got {}",
128
422
                format_form(other)
129
422
            )));
130
        }
131
    };
132
1709177
    super::reject_definition_after_exit(symbols, "DEFMACRO", &name, args)?;
133
1707510
    let params = parse_macro_params(symbols, "DEFMACRO", &args[1])?;
134
1705008
    if !params.aux.is_empty() {
135
416
        return Err(Error::Compile(
136
416
            "DEFMACRO: &aux is not yet supported".to_string(),
137
416
        ));
138
1704592
    }
139
1704592
    let (doc, body_idx) = match args.get(2) {
140
838
        Some(Expr::String(s)) if args.len() > 3 => (Some(s.clone()), 3),
141
1703760
        _ => (None, 2),
142
    };
143
1704592
    if body_idx >= args.len() {
144
        return Err(Error::Compile("DEFMACRO: missing body".to_string()));
145
1704592
    }
146
1704592
    let body = Expr::body(&args[body_idx..]);
147
1704592
    let lambda = Expr::Lambda(params, Box::new(body));
148

            
149
1704592
    if symbols.lookup(&name).is_some() {
150
8543
        symbols.note_redefinition();
151
1696049
    }
152
1704592
    let mut sym = Symbol::new(&name, SymbolKind::Macro).with_function(lambda);
153
1704592
    if let Some(d) = doc {
154
832
        sym = sym.with_doc(d);
155
1703760
    }
156
1704592
    symbols.define(sym);
157
1704592
    Ok(Expr::quoted(Expr::Symbol(name)))
158
1710238
}
159

            
160
6492
pub(super) fn macroexpand_1(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
161
6492
    if args.len() != 1 {
162
209
        return Err(Error::Arity {
163
209
            name: "MACROEXPAND-1".to_string(),
164
209
            expected: 1,
165
209
            actual: args.len(),
166
209
        });
167
6283
    }
168
6283
    let form = Expr::quoted(folded_form(symbols, "MACROEXPAND-1", &args[0])?);
169
6281
    macroexpand_1_impl(symbols, &form)
170
6492
}
171

            
172
1303
pub(super) fn macroexpand(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
173
1303
    if args.len() != 1 {
174
209
        return Err(Error::Arity {
175
209
            name: "MACROEXPAND".to_string(),
176
209
            expected: 1,
177
209
            actual: args.len(),
178
209
        });
179
1094
    }
180
1094
    let mut form = Expr::quoted(folded_form(symbols, "MACROEXPAND", &args[0])?);
181
    loop {
182
2355
        let expanded = macroexpand_1_impl(symbols, &form)?;
183
2355
        if expanded == form {
184
1094
            break;
185
1261
        }
186
1261
        form = expanded;
187
    }
188
1094
    Ok(form)
189
1303
}
190

            
191
8636
fn macroexpand_1_impl(symbols: &mut SymbolTable, form: &Expr) -> Result<Expr> {
192
8636
    match form {
193
8634
        Expr::Datum(inner) => match inner.as_ref() {
194
8426
            Expr::List(elems) if !elems.is_empty() => {
195
8426
                if let Some(name) = macro_head_name(&elems[0])
196
8218
                    && let Head::Macro(params, body) = symbols.resolve_head(name)
197
                {
198
7125
                    let (params, body) = (params.clone(), body.clone());
199
                    // `macroexpand-1` is one-step, but expanding the macro
200
                    // evaluates its body — which may itself call
201
                    // `macroexpand-1` on the same macro, recursing
202
                    // unboundedly. Bracket with the shared depth guard so a
203
                    // self-referential expander errors instead of
204
                    // overflowing the native stack.
205
7125
                    symbols.enter_macro_expansion()?;
206
                    let expanded =
207
6917
                        super::super::expr::expand_macro(symbols, &params, &body, &elems[1..]);
208
6917
                    symbols.exit_macro_expansion()?;
209
6917
                    return expanded.map(Expr::quoted);
210
1301
                }
211
1301
                Ok(form.clone())
212
            }
213
208
            _ => Ok(form.clone()),
214
        },
215
2
        _ => Ok(form.clone()),
216
    }
217
8636
}
218

            
219
8426
fn macro_head_name(expr: &Expr) -> Option<&str> {
220
8426
    match expr {
221
8218
        Expr::Symbol(name) => Some(name),
222
        Expr::Quote(inner) => match inner.as_ref() {
223
            Expr::Symbol(name) => Some(name),
224
            _ => None,
225
        },
226
208
        _ => None,
227
    }
228
8426
}