1
//! The operand of a reflective form (`EVAL`, `MACROEXPAND`, `COMPILE`,
2
//! `DESCRIBE`) is a folded constant form on every compilation surface.
3

            
4
use crate::ast::Expr;
5
use crate::compiler::expr::fold_value;
6
use crate::compiler::special::binding::shared::{fully_macro_expanded, mentions_expanded};
7
use crate::error::{Error, Result};
8
use crate::runtime::SymbolTable;
9

            
10
/// The form `operand` folds to; a non-constant operand is a compile error,
11
/// never the operand returned as the result.
12
15730
pub(in crate::compiler::special) fn folded_form(
13
15730
    symbols: &mut SymbolTable,
14
15730
    who: &str,
15
15730
    operand: &Expr,
16
15730
) -> Result<Expr> {
17
15730
    let operand = &fully_macro_expanded(symbols, operand)?;
18
15730
    match fold_value(symbols, operand)? {
19
12934
        Some(Expr::Datum(inner)) => Ok(*inner),
20
2765
        Some(form) => Ok(form),
21
31
        None => Err(Error::Compile(format!(
22
31
            "{who}: the form is not a compile-time constant"
23
31
        ))),
24
    }
25
15730
}
26

            
27
/// The symbol name `operand` folds to.
28
3157
pub(in crate::compiler::special) fn folded_symbol(
29
3157
    symbols: &mut SymbolTable,
30
3157
    who: &str,
31
3157
    operand: &Expr,
32
3157
) -> Result<String> {
33
3157
    match folded_form(symbols, who, operand)? {
34
2946
        Expr::Symbol(name) => Ok(name),
35
209
        _ => Err(Error::Compile(format!(
36
209
            "{who}: argument must be a quoted symbol"
37
209
        ))),
38
    }
39
3157
}
40

            
41
/// The form EVAL's operand folds to; EVAL sees only global definitions, so a
42
/// form mentioning a name a local binding holds here is a compile error.
43
3463
pub(in crate::compiler::special) fn folded_eval_form(
44
3463
    symbols: &mut SymbolTable,
45
3463
    operand: &Expr,
46
3463
) -> Result<Expr> {
47
3463
    let form = folded_form(symbols, "EVAL", operand)?;
48
3440
    for (name, _) in symbols.lexical_names() {
49
519
        if mentions_expanded(symbols, &form, &name)? {
50
151
            return Err(Error::Compile(format!(
51
151
                "EVAL: {name} is bound locally here; EVAL sees only global definitions"
52
151
            )));
53
368
        }
54
    }
55
3289
    Ok(form)
56
3463
}