1
//! The one place a definition form tells the host it ran (plan 0014
2
//! PERSIST): every definer, in tail and effect position alike, compiles
3
//! through [`compile_definition`], which sets one flag for the slots it filled.
4
//! A host keeps the last definition of a slot whose flag is 1.
5

            
6
use crate::ast::{Expr, WasmType};
7
use crate::compiler::context::CompileContext;
8
use crate::compiler::emit::FunctionEmitter;
9
use crate::error::Result;
10
use crate::runtime::{Slot, SymbolTable};
11

            
12
use super::CompileFn;
13
use super::defstruct::struct_function_names;
14

            
15
/// Compiles the definition form `head` with `run`, then sets the flag of the
16
/// slots it filled.
17
1857779
pub(super) fn compile_definition(
18
1857779
    ctx: &mut CompileContext,
19
1857779
    emit: &mut FunctionEmitter,
20
1857779
    symbols: &mut SymbolTable,
21
1857779
    head: &str,
22
1857779
    args: &[Expr],
23
1857779
    run: CompileFn,
24
1857779
) -> Result<()> {
25
1857779
    let slots = defined_slots(head, args);
26
1857779
    run(ctx, emit, symbols, args)?;
27
1809943
    if slots.is_empty() {
28
        return Ok(());
29
1809943
    }
30
1809943
    let flag = ctx.alloc_mutable_global(WasmType::I32)?;
31
1809943
    emit.i32_const(1);
32
1809943
    emit.global_set(flag);
33
1809943
    for (name, slot) in &slots {
34
2132879
        symbols.note_definition(name, *slot, flag);
35
    }
36
1809943
    Ok(())
37
1857779
}
38

            
39
/// The slots `head` fills: a DEFUN or DEFMACRO the function of its name, a
40
/// DEFSTRUCT the functions it generates, a DEFVAR or DEFPARAMETER the value
41
/// of its name. The flag of a cell's DEFVAR says the declaration ran; the
42
/// cell's own bound flag says it holds a value.
43
1857786
pub(super) fn defined_slots(head: &str, args: &[Expr]) -> Vec<(String, Slot)> {
44
1857786
    let Some(name) = args.first().and_then(Expr::as_symbol) else {
45
219
        return Vec::new();
46
    };
47
1857567
    match head {
48
1407796
        "DEFUN" | "DEFMACRO" => vec![(name.to_string(), Slot::Function)],
49
65764
        "DEFSTRUCT" => struct_function_names(name, &args[1..])
50
65764
            .into_iter()
51
337560
            .map(|function| (function, Slot::Function))
52
65764
            .chain(std::iter::once((name.to_string(), Slot::Layout)))
53
            .collect(),
54
384007
        "DEFVAR" | "DEFPARAMETER" => vec![(name.to_string(), Slot::Value)],
55
        _ => Vec::new(),
56
    }
57
1857786
}
58

            
59
#[cfg(test)]
60
#[path = "definition_tests.rs"]
61
mod tests;