1
//! `FUNCALL` and `APPLY`: the function operand's effects run first, then the
2
//! other operands left to right. A call the compiler can see cannot be made (a
3
//! literal that is no function, an unknown function, a wrong arity, a last
4
//! operand that is no list, a function operand it cannot name) is a compile
5
//! error.
6

            
7
use crate::ast::{Expr, WasmType};
8
use crate::compiler::context::CompileContext;
9
use crate::compiler::emit::FunctionEmitter;
10
use crate::compiler::expr::fold::walk::is_lambda_literal;
11
use crate::compiler::expr::{
12
    compile_call, compile_call_for_stack, compile_expr, compile_for_effect, compile_for_stack,
13
    eval_value, fold_safe, fold_value,
14
};
15
use crate::compiler::join::NEVER_RETURNS;
16
use crate::compiler::native::function_operand::{
17
    effect_prefix, function_operand, hoist_call_function,
18
};
19

            
20
use super::{build_apply_call, resolve_apply_designator, spread_apply_last_arg};
21
use crate::error::{Error, Result};
22
use crate::runtime::{Symbol, SymbolKind, SymbolTable};
23

            
24
72350
pub(super) fn compile_funcall(
25
72350
    ctx: &mut CompileContext,
26
72350
    emit: &mut FunctionEmitter,
27
72350
    symbols: &mut SymbolTable,
28
72350
    original: &[Expr],
29
72350
) -> Result<()> {
30
72350
    let Some(args) = funcall_operands(ctx, emit, symbols, original)? else {
31
        return Ok(());
32
    };
33
65440
    compile_call(ctx, emit, symbols, &args)
34
72350
}
35

            
36
418995
pub(super) fn compile_funcall_for_stack(
37
418995
    ctx: &mut CompileContext,
38
418995
    emit: &mut FunctionEmitter,
39
418995
    symbols: &mut SymbolTable,
40
418995
    original: &[Expr],
41
418995
) -> Result<WasmType> {
42
418995
    let Some(args) = funcall_operands(ctx, emit, symbols, original)? else {
43
6
        return Ok(NEVER_RETURNS);
44
    };
45
418121
    compile_call_for_stack(ctx, emit, symbols, &args)
46
418995
}
47

            
48
/// `args` with the function operand's effects run once, ahead of the call, and
49
/// the function left in its place; `None` when the function operand always
50
/// raises.
51
503710
fn funcall_operands(
52
503710
    ctx: &mut CompileContext,
53
503710
    emit: &mut FunctionEmitter,
54
503710
    symbols: &mut SymbolTable,
55
503710
    args: &[Expr],
56
503710
) -> Result<Option<Vec<Expr>>> {
57
503710
    if args.is_empty() {
58
208
        return Err(Error::Compile(
59
208
            "funcall requires at least a function argument".to_string(),
60
208
        ));
61
503502
    }
62
503502
    let Some(mut hoisted) = hoist_call_function(ctx, emit, symbols, args)? else {
63
6
        return Ok(None);
64
    };
65
497597
    hoisted[0] = function_operand(symbols, &hoisted[0])?;
66
494883
    Ok(Some(hoisted))
67
503710
}
68

            
69
/// The call APPLY makes: each leading operand with an effect is compiled once
70
/// into a local of `bindings`, in order, then the last operand's `effects` run,
71
/// so every operand runs once, left to right; the function operand's effects
72
/// have already run.
73
pub(super) struct ApplyCall {
74
    bindings: Vec<(String, Expr)>,
75
    effects: Vec<Expr>,
76
    call: Vec<Expr>,
77
}
78

            
79
impl ApplyCall {
80
    /// Emits the bindings and effects, then `finish` of the call form, inside a
81
    /// scope that holds the locals.
82
9658
    fn emit<T>(
83
9658
        self,
84
9658
        ctx: &mut CompileContext,
85
9658
        emit: &mut FunctionEmitter,
86
9658
        symbols: &mut SymbolTable,
87
9658
        finish: impl FnOnce(
88
9658
            &mut CompileContext,
89
9658
            &mut FunctionEmitter,
90
9658
            &mut SymbolTable,
91
9658
            &Expr,
92
9658
        ) -> Result<T>,
93
9658
    ) -> Result<T> {
94
9658
        symbols.push_scope();
95
9658
        let result = self.emit_in_scope(ctx, emit, symbols, finish);
96
9658
        symbols.pop_scope()?;
97
9658
        result
98
9658
    }
99

            
100
9658
    fn emit_in_scope<T>(
101
9658
        self,
102
9658
        ctx: &mut CompileContext,
103
9658
        emit: &mut FunctionEmitter,
104
9658
        symbols: &mut SymbolTable,
105
9658
        finish: impl FnOnce(
106
9658
            &mut CompileContext,
107
9658
            &mut FunctionEmitter,
108
9658
            &mut SymbolTable,
109
9658
            &Expr,
110
9658
        ) -> Result<T>,
111
9658
    ) -> Result<T> {
112
9658
        for (name, operand) in &self.bindings {
113
2508
            let ty = compile_for_stack(ctx, emit, symbols, operand)?;
114
2508
            let idx = ctx.alloc_local(ty)?;
115
2508
            emit.local_set(idx);
116
            let local =
117
2508
                Symbol::new(name, SymbolKind::Variable).with_value(Expr::WasmLocal(idx, ty));
118
2508
            symbols.define_scoped(local);
119
        }
120
9658
        for effect in &self.effects {
121
1676
            compile_for_effect(ctx, emit, symbols, effect)?;
122
        }
123
9658
        finish(ctx, emit, symbols, &Expr::List(self.call))
124
9658
    }
125
}
126

            
127
5032
pub(super) fn compile_apply_form(
128
5032
    ctx: &mut CompileContext,
129
5032
    emit: &mut FunctionEmitter,
130
5032
    symbols: &mut SymbolTable,
131
5032
    args: &[Expr],
132
5032
) -> Result<()> {
133
5032
    let Some(call) = apply_call(ctx, emit, symbols, args)? else {
134
        return Ok(());
135
    };
136
3574
    call.emit(ctx, emit, symbols, compile_expr)
137
5032
}
138

            
139
7749
pub(super) fn compile_apply_form_for_stack(
140
7749
    ctx: &mut CompileContext,
141
7749
    emit: &mut FunctionEmitter,
142
7749
    symbols: &mut SymbolTable,
143
7749
    args: &[Expr],
144
7749
) -> Result<WasmType> {
145
7749
    let Some(call) = apply_call(ctx, emit, symbols, args)? else {
146
        return Ok(NEVER_RETURNS);
147
    };
148
6084
    call.emit(ctx, emit, symbols, compile_for_stack)
149
7749
}
150

            
151
/// The call APPLY makes. A call needing no operand compilation is built the
152
/// way the evaluator builds it; `None` when the function operand always raises.
153
12781
fn apply_call(
154
12781
    ctx: &mut CompileContext,
155
12781
    emit: &mut FunctionEmitter,
156
12781
    symbols: &mut SymbolTable,
157
12781
    original: &[Expr],
158
12781
) -> Result<Option<ApplyCall>> {
159
12781
    if original.len() < 2 {
160
        return Ok(Some(ApplyCall {
161
416
            bindings: Vec::new(),
162
416
            effects: Vec::new(),
163
416
            call: build_apply_call(symbols, original)?,
164
        }));
165
12365
    }
166
12365
    let Some(args) = funcall_operands(ctx, emit, symbols, original)? else {
167
        return Ok(None);
168
    };
169
11322
    plan_apply(symbols, &args).map(Some)
170
12781
}
171

            
172
/// Nothing is emitted here: the operands are compiled by [`ApplyCall::emit`].
173
11322
fn plan_apply(symbols: &mut SymbolTable, args: &[Expr]) -> Result<ApplyCall> {
174
11322
    let Some((last, leading)) = args.split_last() else {
175
        return Err(Error::Compile("apply requires a function".to_string()));
176
    };
177
11322
    let mut call = vec![resolve_apply_designator(symbols, &leading[0])?];
178
11114
    let mut bindings = Vec::new();
179
11114
    for arg in &leading[1..] {
180
3973
        call.push(apply_leading_operand(symbols, arg, &mut bindings)?);
181
    }
182
11114
    let (prefix, tail) = effect_prefix(last);
183
11114
    call.extend(spread_apply_last_arg(&mut symbols.clone(), tail)?);
184
9658
    let effects = match tail {
185
7554
        Expr::List(items) if is_list_constructor(items) => prefix.to_vec(),
186
2116
        _ if fold_safe(symbols, last) => Vec::new(),
187
425
        _ => vec![last.clone()],
188
    };
189
9658
    Ok(ApplyCall {
190
9658
        bindings,
191
9658
        effects,
192
9658
        call,
193
9658
    })
194
11322
}
195

            
196
7554
fn is_list_constructor(items: &[Expr]) -> bool {
197
7554
    matches!(items.first(), Some(Expr::Symbol(head)) if head.eq_ignore_ascii_case("LIST"))
198
7554
}
199

            
200
/// A leading operand as the call sees it: its value when it folds, and
201
/// otherwise a variable bound to it, so it is compiled once and never
202
/// evaluated at compile time.
203
3973
fn apply_leading_operand(
204
3973
    symbols: &mut SymbolTable,
205
3973
    arg: &Expr,
206
3973
    bindings: &mut Vec<(String, Expr)>,
207
3973
) -> Result<Expr> {
208
3973
    if is_lambda_literal(symbols, arg) {
209
        return eval_value(symbols, arg);
210
3973
    }
211
3973
    if let Some(value) = fold_value(symbols, arg)? {
212
1049
        return Ok(value);
213
2924
    }
214
2924
    let name = format!("%APPLY-ARG-{}", bindings.len());
215
2924
    bindings.push((name.clone(), arg.clone()));
216
2924
    Ok(Expr::Symbol(name))
217
3973
}