1
use crate::ast::{Expr, KeyParam, LambdaParams, Number, StructId};
2
use crate::compiler::expr::format_form;
3
use crate::compiler::native::{STRUCT_COPY, STRUCT_NEW, STRUCT_P, STRUCT_REF, STRUCT_SET};
4
use crate::error::{Error, Result};
5
use crate::reserved::reject_reserved;
6
use crate::runtime::{Symbol, SymbolKind, SymbolTable};
7

            
8
use super::super::context::CompileContext;
9
use super::super::emit::FunctionEmitter;
10
use super::super::expr::compile_expr;
11

            
12
52628
pub(super) fn compile_defstruct(
13
52628
    ctx: &mut CompileContext,
14
52628
    emit: &mut FunctionEmitter,
15
52628
    symbols: &mut SymbolTable,
16
52628
    args: &[Expr],
17
52628
) -> Result<()> {
18
52628
    let result = defstruct(symbols, args)?;
19
51584
    compile_expr(ctx, emit, symbols, &result)
20
52628
}
21

            
22
13138
pub(super) fn compile_defstruct_for_effect(
23
13138
    _ctx: &mut CompileContext,
24
13138
    _emit: &mut FunctionEmitter,
25
13138
    symbols: &mut SymbolTable,
26
13138
    args: &[Expr],
27
13138
) -> Result<()> {
28
13138
    defstruct(symbols, args).map(drop)
29
13138
}
30

            
31
66390
pub(super) fn defstruct(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
32
66390
    if args.is_empty() {
33
        return Err(Error::Compile(
34
            "DEFSTRUCT requires a structure name".to_string(),
35
        ));
36
66390
    }
37
    // Always compile-time-only — same reasoning as DEFUN.
38
66390
    super::reject_definition_under_runtime_guard(symbols, "DEFSTRUCT")?;
39

            
40
66390
    let name = args[0].as_symbol().ok_or_else(|| {
41
3
        Error::Compile(format!(
42
3
            "DEFSTRUCT: expected structure name, got {}",
43
3
            format_form(&args[0])
44
3
        ))
45
3
    })?;
46

            
47
66387
    reject_reserved(symbols, name)?;
48
66384
    let fields: Vec<String> = args[1..]
49
66384
        .iter()
50
71381
        .map(|arg| {
51
71381
            let field = arg.as_symbol().ok_or_else(|| {
52
3
                Error::Compile(format!(
53
3
                    "DEFSTRUCT: expected field name, got {}",
54
3
                    format_form(arg)
55
3
                ))
56
3
            })?;
57
71378
            reject_reserved(symbols, field).map(|()| field.to_string())
58
71381
        })
59
6
        .collect::<Result<_>>()?;
60
66378
    let generated: Vec<String> = generated_names(name, &fields).collect();
61
66378
    generated
62
66378
        .iter()
63
270509
        .try_for_each(|generated| reject_reserved(symbols, generated))?;
64
66375
    super::reject_definition_after_exit(symbols, "DEFSTRUCT", name, args)?;
65
64918
    define_struct(symbols, name, fields)
66
66390
}
67

            
68
327331
fn call(native: &str, operands: impl IntoIterator<Item = Expr>) -> Expr {
69
327331
    let head = std::iter::once(Expr::symbol(native));
70
327331
    Expr::List(head.chain(operands).collect())
71
327331
}
72

            
73
63883
fn id_literal(id: StructId) -> Expr {
74
63883
    Expr::Number(Number::Index(i64::from(id.0)))
75
63883
}
76

            
77
67841
fn slot_literal(index: usize) -> Result<Expr> {
78
67841
    i64::try_from(index)
79
67841
        .map(|index| Expr::Number(Number::Index(index)))
80
        .map_err(|_| Error::Resource("structure layout too large".to_string()))
81
67841
}
82

            
83
399130
fn param(name: &str) -> Expr {
84
399130
    Expr::Symbol(name.to_string())
85
399130
}
86

            
87
327331
fn define_function(symbols: &mut SymbolTable, name: &str, params: LambdaParams, body: Expr) {
88
327331
    let lambda = Expr::Lambda(params, Box::new(body));
89
327331
    symbols.define(Symbol::new(name, SymbolKind::Function).with_function(lambda));
90
327331
}
91

            
92
195607
fn define_unary(symbols: &mut SymbolTable, name: &str, body: Expr) {
93
195607
    let params = LambdaParams::simple(vec!["O".to_string()]);
94
195607
    define_function(symbols, name, params, body);
95
195607
}
96

            
97
/// Registers a structure's constructor, predicate, copier, accessors and
98
/// setf accessors as lambdas over the runtime struct natives, without the
99
/// user-binding checks.
100
64924
fn define_struct(symbols: &mut SymbolTable, name: &str, fields: Vec<String>) -> Result<Expr> {
101
64924
    let id = id_literal(symbols.define_struct(name, fields.clone())?);
102

            
103
    let constructor = LambdaParams {
104
63883
        key: fields
105
63883
            .iter()
106
67841
            .map(|field| KeyParam::new(field, None))
107
            .collect(),
108
63883
        ..LambdaParams::simple(Vec::new())
109
    };
110
63883
    let values = fields.iter().map(String::as_str).map(param);
111
63883
    let make = call(STRUCT_NEW, std::iter::once(id.clone()).chain(values));
112
63883
    define_function(symbols, &format!("MAKE-{name}"), constructor, make);
113

            
114
    // Defined before the accessors: a field named P makes NAME-P an accessor, as in Common Lisp.
115
63883
    let predicate = call(STRUCT_P, [param("O"), id.clone()]);
116
63883
    define_unary(symbols, &format!("{name}-P"), predicate);
117
63883
    let copier = call(STRUCT_COPY, [param("O"), id.clone()]);
118
63883
    define_unary(symbols, &format!("COPY-{name}"), copier);
119

            
120
63883
    for (index, field) in fields.iter().enumerate() {
121
67841
        let accessor = format!("{name}-{field}");
122
67841
        let slot = slot_literal(index)?;
123
67841
        let read = call(STRUCT_REF, [param("O"), id.clone(), slot.clone()]);
124
67841
        define_unary(symbols, &accessor, read);
125

            
126
67841
        let setf_params = LambdaParams::simple(vec!["O".to_string(), "V".to_string()]);
127
67841
        let write = call(STRUCT_SET, [param("O"), id.clone(), slot, param("V")]);
128
67841
        define_function(symbols, &format!("(SETF {accessor})"), setf_params, write);
129
    }
130

            
131
63883
    Ok(Expr::quoted(Expr::Symbol(name.to_string())))
132
64924
}
133

            
134
/// Every function a DEFSTRUCT of `name` with `fields` defines, its setf
135
/// accessors among them; a field that is not a symbol names none.
136
131735
pub(in crate::compiler) fn struct_function_names(name: &str, fields: &[Expr]) -> Vec<String> {
137
131735
    let fields: Vec<String> = fields
138
131735
        .iter()
139
131735
        .filter_map(Expr::as_symbol)
140
131735
        .map(str::to_string)
141
131735
        .collect();
142
140475
    let setf = fields.iter().map(|field| format!("(SETF {name}-{field})"));
143
131735
    generated_names(name, &fields).chain(setf).collect()
144
131735
}
145

            
146
198113
fn generated_names<'a>(name: &'a str, fields: &'a [String]) -> impl Iterator<Item = String> + 'a {
147
198113
    [
148
198113
        format!("MAKE-{name}"),
149
198113
        format!("{name}-P"),
150
198113
        format!("COPY-{name}"),
151
198113
    ]
152
198113
    .into_iter()
153
211850
    .chain(fields.iter().map(move |field| format!("{name}-{field}")))
154
198113
}
155

            
156
#[cfg(test)]
157
#[path = "defstruct_tests.rs"]
158
mod tests;