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

            
7
use super::super::context::CompileContext;
8
use super::super::emit::FunctionEmitter;
9
use super::super::expr::{compile_body, compile_body_for_stack, compile_for_effect};
10
use super::SpecialFormSpec;
11
use super::binding::{eval_body, parse_param_list, rebind_params};
12

            
13
pub(super) const FORMS: &[SpecialFormSpec] = &[SpecialFormSpec {
14
    name: "LABELS",
15
    eval: labels_form,
16
    compile: compile_labels,
17
    stack: Some(compile_labels_for_stack),
18
    effect: Some(compile_labels_for_effect),
19
}];
20

            
21
struct LabelDef {
22
    name: String,
23
    params: Vec<String>,
24
    body: Expr,
25
}
26

            
27
43842
fn parse_labels_defs<'a>(
28
43842
    symbols: &SymbolTable,
29
43842
    args: &'a [Expr],
30
43842
) -> Result<(Vec<LabelDef>, &'a [Expr])> {
31
43842
    if args.len() < 2 {
32
416
        return Err(Error::Compile(
33
416
            "LABELS requires a definitions list and at least one body form".to_string(),
34
416
        ));
35
43426
    }
36
43426
    let defs_list = args[0].as_list().ok_or_else(|| {
37
3
        Error::Compile(format!(
38
3
            "LABELS: expected definitions list, got {}",
39
3
            format_form(&args[0])
40
3
        ))
41
3
    })?;
42
43423
    let defs = defs_list
43
43423
        .iter()
44
44061
        .map(|def| {
45
44061
            let elems = def.as_list().ok_or_else(|| {
46
3
                Error::Compile(format!(
47
3
                    "LABELS: expected function definition, got {}",
48
3
                    format_form(def)
49
3
                ))
50
3
            })?;
51
44058
            if elems.len() < 3 {
52
208
                return Err(Error::Compile(
53
208
                    "LABELS: each definition needs a name, params, and body".to_string(),
54
208
                ));
55
43850
            }
56
43850
            let name = elems[0]
57
43850
                .as_symbol()
58
3
                .ok_or_else(|| {
59
3
                    Error::Compile(format!(
60
3
                        "LABELS: expected function name, got {}",
61
3
                        format_form(&elems[0])
62
3
                    ))
63
3
                })?
64
                .to_string();
65
43847
            reject_reserved(symbols, &name)?;
66
43844
            let params = parse_param_list(symbols, "LABELS", &elems[1])?;
67
43633
            let (params, body) = rebind_params(
68
43633
                symbols,
69
43633
                LambdaParams::simple(params),
70
43633
                Expr::body(&elems[2..]),
71
43633
            )?;
72
43633
            Ok(LabelDef {
73
43633
                name,
74
43633
                params: params.required,
75
43633
                body,
76
43633
            })
77
44061
        })
78
428
        .collect::<Result<Vec<_>>>()?;
79
42995
    Ok((defs, &args[1..]))
80
43842
}
81

            
82
/// Runs `body` with the LABELS functions bound in a scope of `symbols`, so a
83
/// definition the body makes outlives the form; `block_depth` is the BLOCK
84
/// labels open at the form, which their bodies see (ISS-179).
85
42995
fn within_labels<T>(
86
42995
    symbols: &mut SymbolTable,
87
42995
    defs: Vec<LabelDef>,
88
42995
    block_depth: usize,
89
42995
    body: impl FnOnce(&mut SymbolTable) -> Result<T>,
90
42995
) -> Result<T> {
91
42995
    symbols.push_scope();
92
43633
    let names: Vec<String> = defs.iter().map(|def| def.name.clone()).collect();
93
42995
    for def in defs {
94
43633
        let lambda = Expr::Lambda(LambdaParams::simple(def.params), Box::new(def.body));
95
43633
        let mut symbol = Symbol::new(&def.name, SymbolKind::Function)
96
43633
            .with_function(lambda)
97
43633
            .local_function();
98
43633
        symbol.set_block_depth(block_depth);
99
43633
        symbols.define_scoped(symbol);
100
    }
101
42995
    let env = symbols.lexical_names();
102
42995
    for name in &names {
103
43633
        if let Some(symbol) = symbols.lookup_mut(name) {
104
43633
            symbol.set_lexical_env(env.clone());
105
        }
106
    }
107
42995
    for name in &names {
108
43633
        symbols.define_local_alias(name);
109
    }
110
42995
    let result = body(symbols);
111
42995
    symbols.pop_scope()?;
112
42995
    result
113
42995
}
114

            
115
16232
pub(super) fn labels_form(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
116
16232
    let (defs, body) = parse_labels_defs(symbols, args)?;
117
16232
    within_labels(symbols, defs, 0, |symbols| eval_body(symbols, body))
118
16232
}
119

            
120
16607
pub(super) fn compile_labels(
121
16607
    ctx: &mut CompileContext,
122
16607
    emit: &mut FunctionEmitter,
123
16607
    symbols: &mut SymbolTable,
124
16607
    args: &[Expr],
125
16607
) -> Result<()> {
126
16607
    let (defs, body) = parse_labels_defs(symbols, args)?;
127
15765
    within_labels(symbols, defs, ctx.block_label_count(), |symbols| {
128
15765
        compile_body(ctx, emit, symbols, body)
129
15765
    })
130
16607
}
131

            
132
5566
pub(super) fn compile_labels_for_stack(
133
5566
    ctx: &mut CompileContext,
134
5566
    emit: &mut FunctionEmitter,
135
5566
    symbols: &mut SymbolTable,
136
5566
    args: &[Expr],
137
5566
) -> Result<WasmType> {
138
5566
    let (defs, body) = parse_labels_defs(symbols, args)?;
139
5561
    within_labels(symbols, defs, ctx.block_label_count(), |symbols| {
140
5561
        compile_body_for_stack(ctx, emit, symbols, body)
141
5561
    })
142
5566
}
143

            
144
/// Unlike `compile_labels` (value position — its body's TAIL form is
145
/// serialized to the RPC output stream via `compile_body`/`compile_expr`),
146
/// LABELS in effect position must never serialize: every body form,
147
/// including the tail, is compiled purely for its effects and dropped —
148
/// same contract `PROGN` gives its own body. Without this, a LABELS in a
149
/// loop body (`(do (...) (...) (funcall-through-labels ...))`) would push
150
/// one output entity per iteration until the output buffer is exhausted.
151
5437
pub(super) fn compile_labels_for_effect(
152
5437
    ctx: &mut CompileContext,
153
5437
    emit: &mut FunctionEmitter,
154
5437
    symbols: &mut SymbolTable,
155
5437
    args: &[Expr],
156
5437
) -> Result<()> {
157
5437
    let (defs, body) = parse_labels_defs(symbols, args)?;
158
5437
    within_labels(symbols, defs, ctx.block_label_count(), |symbols| {
159
5437
        body.iter()
160
5437
            .try_for_each(|form| compile_for_effect(ctx, emit, symbols, form))
161
5437
    })
162
5437
}