1
//! `DEFUN`: the eval handler that registers a function.
2

            
3
use crate::ast::Expr;
4
use crate::compiler::special::expanded_function;
5
use crate::error::{Error, Result};
6
use crate::runtime::{Symbol, SymbolKind, SymbolTable};
7

            
8
use super::define::def_name;
9
use super::kept::kept_lexicals;
10
use super::parse::parse_function_params;
11
use super::rebind::rebind_params;
12

            
13
5287812
pub(super) fn defun(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
14
5287812
    if args.len() < 3 {
15
        return Err(Error::Compile(
16
            "DEFUN requires a name, parameter list, and body".to_string(),
17
        ));
18
5287812
    }
19
    // DEFUN's registration is ALWAYS compile-time-only (a lambda has no
20
    // "runtime-backed" form the way a DEFVAR/DEFPARAMETER initializer can
21
    // be) — unconditionally refused under a runtime AND/OR guard.
22
5287812
    super::super::reject_definition_under_runtime_guard(symbols, "DEFUN")?;
23
5284053
    let name = def_name(symbols, "DEFUN", &args[0])?;
24
5282780
    super::super::reject_definition_after_exit(symbols, "DEFUN", &name, args)?;
25
5271332
    let params = parse_function_params(symbols, "DEFUN", &args[1])?;
26
5269219
    let (doc, body_idx) = match args.get(2) {
27
2081
        Some(Expr::String(s)) if args.len() > 3 => (Some(s.clone()), 3),
28
5268594
        _ => (None, 2),
29
    };
30
5269219
    if body_idx >= args.len() {
31
        return Err(Error::Compile("DEFUN: missing body".to_string()));
32
5269219
    }
33
5269219
    let (params, body) = expanded_function(
34
5269219
        symbols,
35
5269219
        Some(&name),
36
5269219
        &params,
37
5269219
        &Expr::body(&args[body_idx..]),
38
5269219
    )?;
39
5269219
    let (params, body) = rebind_params(symbols, params, body)?;
40
5269213
    let lambda = Expr::Lambda(params, Box::new(body));
41

            
42
5269213
    let env = symbols.lexical_names();
43
5269213
    let kept = kept_lexicals(symbols, &lambda)?;
44
5269213
    let mut sym = Symbol::new(&name, SymbolKind::Function).with_function(lambda);
45
5269213
    sym.set_lexical_env(env);
46
5269213
    sym.set_lexical_values(kept);
47
5269213
    if let Some(d) = doc {
48
625
        sym = sym.with_doc(d);
49
5268588
    }
50
5269213
    if symbols.contains(&name) {
51
38549
        symbols.reject_redefinition_after_closure(&name)?;
52
19617
        symbols.note_redefinition();
53
5230664
    }
54
5250281
    symbols.define(sym);
55
5250281
    Ok(Expr::quoted(Expr::Symbol(name)))
56
5287812
}