1
//! A function operand written `(progn effects… <function>)`: the effects run
2
//! once, ahead of the call, and the function stays in place.
3

            
4
use crate::ast::{ClosureSigId, Expr, LambdaParams, Place, WasmType};
5
use crate::compiler::context::CompileContext;
6
use crate::compiler::emit::FunctionEmitter;
7
use crate::compiler::expr::fold::fold_safe_under;
8
use crate::compiler::expr::fold::walk::is_lambda_literal;
9
use crate::compiler::expr::{
10
    call_place, close_factory_call, compile_for_effect, compile_for_stack, compile_raising_to_end,
11
    emit_place_read, eval_value, expand_macro_then, fold_safe, fold_value, is_untyped,
12
    reject_unbound_capture,
13
};
14
use crate::compiler::native::designator_class::{is_function_macro, reject_non_function};
15
use crate::compiler::special::is_closure_factory_call;
16
use crate::error::{Error, Result, with_article};
17
use crate::runtime::{Head, Symbol, SymbolKind, SymbolTable};
18

            
19
/// `args` with a `(progn effects… <lambda>)` function argument (`args[0]`)
20
/// split: the effects run once, ahead of the list, and the lambda literal stays
21
/// in place so it keeps the scope it is created in. Any other argument is left
22
/// as it is.
23
///
24
/// A higher-order native reads its function operand once, before iterating, so
25
/// a closure place is always held in a local.
26
///
27
/// `None` when the function operand always raises: it is compiled and control
28
/// ends there.
29
57012
pub(in crate::compiler) fn hoist_function_arg(
30
57012
    ctx: &mut CompileContext,
31
57012
    emit: &mut FunctionEmitter,
32
57012
    symbols: &mut SymbolTable,
33
57012
    args: &[Expr],
34
57012
) -> Result<Option<Vec<Expr>>> {
35
57012
    hoist(ctx, emit, symbols, args, Pin::Always)
36
57012
}
37

            
38
/// [`hoist_function_arg`] for FUNCALL and APPLY, whose closure place is held
39
/// only when a later operand runs something.
40
503506
pub(in crate::compiler) fn hoist_call_function(
41
503506
    ctx: &mut CompileContext,
42
503506
    emit: &mut FunctionEmitter,
43
503506
    symbols: &mut SymbolTable,
44
503506
    args: &[Expr],
45
503506
) -> Result<Option<Vec<Expr>>> {
46
503506
    hoist(ctx, emit, symbols, args, Pin::WhenLaterRuns)
47
503506
}
48

            
49
#[derive(Clone, Copy, PartialEq, Eq)]
50
enum Pin {
51
    Always,
52
    WhenLaterRuns,
53
}
54

            
55
/// A function operand with `(QUOTE f)` read as the datum `f`: the one function
56
/// designator every higher-order native and FUNCALL takes its function from.
57
/// It is a datum, never a quote form, so a call headed by it is the call of
58
/// the function and no source-written quoted head.
59
2116919
pub(in crate::compiler) fn designator_form(designator: &Expr) -> Expr {
60
2116919
    match designator {
61
1008515
        Expr::List(items) => match items.as_slice() {
62
            [Expr::Symbol(quote), named @ Expr::Symbol(_)]
63
74561
                if quote.eq_ignore_ascii_case("QUOTE") =>
64
            {
65
1
                Expr::Datum(Box::new(named.clone()))
66
            }
67
1008514
            _ => designator.clone(),
68
        },
69
39349
        Expr::Quote(named) if matches!(named.as_ref(), Expr::Symbol(_)) => {
70
37043
            Expr::Datum(named.clone())
71
        }
72
1071361
        other => other.clone(),
73
    }
74
2116919
}
75

            
76
/// The function operand `designator` names on every surface: `'f` read as
77
/// [`designator_form`] does, and a quoted name that a LABELS function hides as
78
/// the alias of the global function it names.
79
2116919
pub(in crate::compiler) fn resolve_designator(
80
2116919
    symbols: &SymbolTable,
81
2116919
    designator: &Expr,
82
2116919
) -> Result<Expr> {
83
2116919
    let designator = designator_form(&function_designator(symbols, designator));
84
2116919
    let Expr::Datum(named) = &designator else {
85
2023162
        return Ok(designator);
86
    };
87
93757
    let Expr::Symbol(name) = named.as_ref() else {
88
        return Ok(designator);
89
    };
90
93757
    reject_non_function(symbols, name)?;
91
91884
    Ok(symbols
92
91884
        .designated_function(name)?
93
91459
        .map_or(designator, |alias| {
94
11361
            Expr::Datum(Box::new(Expr::Symbol(alias)))
95
11361
        }))
96
2116919
}
97

            
98
/// A constant-folding designator form (`#'name`, `(car (list 'name))`) as the
99
/// name datum it folds to, so it reads as `'name`.
100
2116919
fn function_designator(symbols: &SymbolTable, designator: &Expr) -> Expr {
101
2116919
    match designator {
102
1018606
        Expr::List(_) => match fold_value(&mut symbols.clone(), designator) {
103
10097
            Ok(Some(named @ Expr::Datum(_))) if is_named(&named) => named,
104
1008515
            _ => designator.clone(),
105
        },
106
1098313
        _ => designator.clone(),
107
    }
108
2116919
}
109

            
110
10097
fn is_named(datum: &Expr) -> bool {
111
10097
    matches!(datum, Expr::Datum(inner) if matches!(inner.as_ref(), Expr::Symbol(_)))
112
10097
}
113

            
114
560518
fn hoist(
115
560518
    ctx: &mut CompileContext,
116
560518
    emit: &mut FunctionEmitter,
117
560518
    symbols: &mut SymbolTable,
118
560518
    args: &[Expr],
119
560518
    pin: Pin,
120
560518
) -> Result<Option<Vec<Expr>>> {
121
560518
    let mut hoisted = args.to_vec();
122
560518
    let Some(function) = args.first() else {
123
        return Ok(Some(hoisted));
124
    };
125
560518
    let (effects, value) = effect_prefix(function);
126
560518
    for effect in effects {
127
3967
        compile_for_effect(ctx, emit, symbols, effect)?;
128
    }
129
560518
    let designator = resolve_designator(symbols, value)?;
130
558221
    if compile_raising_to_end(ctx, emit, symbols, &designator)? {
131
10
        return Ok(None);
132
558211
    }
133
558211
    let function = designator_operand(ctx, emit, symbols, &designator)?;
134
554385
    if pin == Pin::Always && is_any_operand(symbols, &function) {
135
224
        return Err(Error::Compile(
136
224
            "the function operand is an any value; call it through (lambda (x) (funcall f x))"
137
224
                .to_string(),
138
224
        ));
139
554161
    }
140
554161
    hoisted[0] = pin_closure(ctx, emit, symbols, function, &args[1..], pin)?;
141
554161
    Ok(Some(hoisted))
142
560518
}
143

            
144
56784
fn is_any_operand(symbols: &SymbolTable, function: &Expr) -> bool {
145
56784
    let value = match function {
146
11963
        Expr::Symbol(name) => variable_value(symbols, name),
147
44821
        other => Some(other),
148
    };
149
56784
    matches!(value.and_then(Expr::place), Some((_, WasmType::AnyRef)))
150
56784
}
151

            
152
/// The function operand a call synthesised for a higher-order native, FUNCALL
153
/// or APPLY uses: what the variable of that name holds, never the function of
154
/// the same name, and a name without a variable is unbound. Then
155
/// [`resolve_designator`].
156
1559109
pub(in crate::compiler) fn function_operand(
157
1559109
    symbols: &SymbolTable,
158
1559109
    designator: &Expr,
159
1559109
) -> Result<Expr> {
160
1559109
    let operand = match designator {
161
        Expr::Symbol(name) => {
162
552538
            variable_value(symbols, name).ok_or_else(|| unbound(symbols, name))?
163
        }
164
1006571
        other => other,
165
    };
166
1556395
    resolve_designator(symbols, operand)
167
1559109
}
168

            
169
/// The one error for a bare function name used as an operand: it names no variable.
170
7124
pub(in crate::compiler) fn unbound(symbols: &SymbolTable, name: &str) -> Error {
171
7124
    symbols.lost_read(name).unwrap_or_else(|| {
172
5252
        if is_function_macro(name) {
173
1248
            return Error::Compile(format!("{name} cannot be used as a function value yet"));
174
4004
        }
175
4004
        let lower = name.to_lowercase();
176
4004
        Error::Compile(format!(
177
4004
            "variable {name} is unbound; use '{lower} or #'{lower}"
178
4004
        ))
179
5252
    })
180
7124
}
181

            
182
/// The value of the variable `name`, without the stand-in a host function
183
/// carries in its value cell.
184
564501
fn variable_value<'a>(symbols: &'a SymbolTable, name: &str) -> Option<&'a Expr> {
185
564501
    symbols
186
564501
        .lookup(name)
187
564501
        .filter(|symbol| symbol.kind() != SymbolKind::Native)
188
564501
        .and_then(Symbol::value)
189
564501
}
190

            
191
/// A closure place is read now, in the call's operand order: the call uses
192
/// the function value from before the later operands' effects, as Common Lisp
193
/// does. A local that already holds a pinned value is left alone.
194
554161
fn pin_closure(
195
554161
    ctx: &mut CompileContext,
196
554161
    emit: &mut FunctionEmitter,
197
554161
    symbols: &mut SymbolTable,
198
554161
    function: Expr,
199
554161
    later: &[Expr],
200
554161
    pin: Pin,
201
554161
) -> Result<Expr> {
202
554161
    let pure_later = later.iter().all(|arg| runs_nothing(symbols, arg));
203
554161
    if matches!(function, Expr::WasmLocal(..)) || (pin == Pin::WhenLaterRuns && pure_later) {
204
147771
        return Ok(function);
205
406390
    }
206
406390
    let Some((place, sig)) = closure_place(symbols, &function) else {
207
392213
        return Ok(function);
208
    };
209
14177
    emit_place_read(ctx, emit, place)?;
210
14177
    pin_stack_closure(
211
14177
        ctx,
212
14177
        emit,
213
14177
        symbols,
214
14177
        sig,
215
14177
        symbols.closure_body(place).cloned(),
216
14177
    )
217
554161
}
218

            
219
/// Moves the closure on the stack into a fresh local that keeps the source
220
/// `body` recorded for the value, so a higher-order native can still inline it.
221
26700
fn pin_stack_closure(
222
26700
    ctx: &mut CompileContext,
223
26700
    emit: &mut FunctionEmitter,
224
26700
    symbols: &mut SymbolTable,
225
26700
    sig: ClosureSigId,
226
26700
    body: Option<(LambdaParams, Expr)>,
227
26700
) -> Result<Expr> {
228
26700
    let ty = WasmType::Closure(sig);
229
26700
    let idx = ctx.alloc_local(ty)?;
230
26700
    emit.local_set(idx);
231
26700
    if let Some((params, body)) = body {
232
12041
        symbols.record_closure_body(Place::Local(idx), params, body);
233
14659
    }
234
26700
    Ok(Expr::WasmLocal(idx, ty))
235
26700
}
236

            
237
/// Moves the `any` value on the stack into a fresh local, which a call checks
238
/// at run time.
239
12726
fn pin_stack_any(ctx: &mut CompileContext, emit: &mut FunctionEmitter) -> Result<Expr> {
240
12726
    let idx = ctx.alloc_local(WasmType::AnyRef)?;
241
12726
    emit.local_set(idx);
242
12726
    Ok(Expr::WasmLocal(idx, WasmType::AnyRef))
243
12726
}
244

            
245
406390
fn closure_place(symbols: &SymbolTable, function: &Expr) -> Option<(Place, ClosureSigId)> {
246
406390
    match function {
247
17770
        Expr::Symbol(name) => symbols.lookup(name).and_then(Symbol::closure_value),
248
388620
        other => call_place(other),
249
    }
250
406390
}
251

            
252
/// A function operand that is a call whose value only compiling can tell: not
253
/// a function literal and not foldable.
254
559695
pub(in crate::compiler) fn is_computed(symbols: &SymbolTable, designator: &Expr) -> Result<bool> {
255
559695
    let Expr::List(items) = designator else {
256
130553
        return Ok(false);
257
    };
258
429142
    let literal = matches!(items.first(), Some(Expr::Symbol(head))
259
526152
        if ["LAMBDA", "FUNCTION", "QUOTE"].iter().any(|h| head.eq_ignore_ascii_case(h)));
260
429142
    Ok(!literal
261
39673
        && (is_closure_factory_call(symbols, designator)? || !fold_safe(symbols, designator)))
262
559695
}
263

            
264
/// The function operand ready to compile: a computed one is lowered once,
265
/// any other stays as written.
266
559689
pub(in crate::compiler) fn designator_operand(
267
559689
    ctx: &mut CompileContext,
268
559689
    emit: &mut FunctionEmitter,
269
559689
    symbols: &mut SymbolTable,
270
559689
    designator: &Expr,
271
559689
) -> Result<Expr> {
272
559689
    if !is_computed(symbols, designator)? {
273
520438
        return Ok(designator.clone());
274
39251
    }
275
39251
    if is_closure_factory_call(symbols, designator)? {
276
3422
        return close_factory_call(ctx, emit, symbols, designator);
277
35829
    }
278
35829
    if let Expr::List(items) = designator
279
35829
        && let Some(Expr::Symbol(head)) = items.first()
280
35829
        && let Head::Macro(params, body) = symbols.resolve_head(head)
281
    {
282
1477
        let (params, body) = (params.clone(), body.clone());
283
1477
        return expand_macro_then(symbols, &params, &body, &items[1..], |symbols, code| {
284
1477
            designator_operand(ctx, emit, symbols, &code)
285
1477
        });
286
34352
    }
287
34352
    match eval_value(&mut symbols.clone(), designator) {
288
        Ok(name @ Expr::Datum(_)) => {
289
1251
            compile_for_effect(ctx, emit, symbols, designator)?;
290
1251
            Ok(name)
291
        }
292
        Ok(function)
293
30592
            if is_untyped(&function)
294
15784
                || matches!(function, Expr::WasmRuntime(WasmType::Closure(_)))
295
6396
                || (function.is_function_value() && has_special_form_head(symbols, designator)) =>
296
        {
297
25459
            let body = recorded_body(symbols, &function);
298
25459
            lower_closure_designator(ctx, emit, symbols, designator, body)
299
        }
300
5133
        Ok(function) if function.is_function_value() && head_runs_nothing(symbols, designator) => {
301
4075
            reject_unbound_capture(symbols, &function)?;
302
4069
            if call_place(&function).is_some() && !args_run_nothing(symbols, designator) {
303
9
                let body = recorded_body(symbols, &function);
304
9
                return lower_closure_designator(ctx, emit, symbols, designator, body);
305
4060
            }
306
4060
            emit_effectful_args(ctx, emit, symbols, designator)?;
307
4060
            Ok(function)
308
        }
309
        Err(
310
            err
311
            @ (Error::UndefinedSymbol(_) | Error::Resource(_) | Error::UnclosableFactory { .. }),
312
9
        ) => Err(err),
313
3558
        _ if has_special_form_head(symbols, designator) => {
314
3335
            lower_conditional_designator(ctx, emit, symbols, designator)
315
        }
316
223
        _ => Err(computed_at_runtime()),
317
    }
318
559689
}
319

            
320
1269
fn computed_at_runtime() -> Error {
321
1269
    Error::Compile(
322
1269
        "the function operand is computed at runtime; it must be a lambda or a function name"
323
1269
            .to_string(),
324
1269
    )
325
1269
}
326

            
327
/// A special form that chooses a function at runtime, held in a local; one that
328
/// yields anything but a single function type is not a function operand.
329
3335
fn lower_conditional_designator(
330
3335
    ctx: &mut CompileContext,
331
3335
    emit: &mut FunctionEmitter,
332
3335
    symbols: &mut SymbolTable,
333
3335
    designator: &Expr,
334
3335
) -> Result<Expr> {
335
3335
    match compile_for_stack(ctx, emit, symbols, designator)? {
336
1040
        WasmType::Closure(sig) => pin_stack_closure(ctx, emit, symbols, sig, None),
337
1249
        WasmType::AnyRef => pin_stack_any(ctx, emit),
338
1046
        _ => Err(computed_at_runtime()),
339
    }
340
3335
}
341

            
342
/// A list whose head is a special form.
343
8905
fn has_special_form_head(symbols: &SymbolTable, call: &Expr) -> bool {
344
8905
    matches!(call, Expr::List(items) if matches!(items.first(),
345
8905
        Some(Expr::Symbol(head)) if matches!(symbols.resolve_head(head), Head::SpecialForm)))
346
8905
}
347

            
348
9
fn args_run_nothing(symbols: &SymbolTable, call: &Expr) -> bool {
349
9
    matches!(call, Expr::List(items) if items[1..].iter().all(|arg| runs_nothing(symbols, arg)))
350
9
}
351

            
352
/// The body recorded for the closure `place` now.
353
25468
fn recorded_body(symbols: &SymbolTable, place: &Expr) -> Option<(LambdaParams, Expr)> {
354
25468
    place
355
25468
        .place()
356
9
        .and_then(|(place, _)| symbols.closure_body(place).cloned())
357
25468
}
358

            
359
/// A designator call returning a closure, compiled in order so its argument
360
/// effects follow the place read, and held in a local. `body` is the one
361
/// recorded for the value the call returns.
362
25468
fn lower_closure_designator(
363
25468
    ctx: &mut CompileContext,
364
25468
    emit: &mut FunctionEmitter,
365
25468
    symbols: &mut SymbolTable,
366
25468
    designator: &Expr,
367
25468
    body: Option<(LambdaParams, Expr)>,
368
25468
) -> Result<Expr> {
369
25468
    match compile_for_stack(ctx, emit, symbols, designator)? {
370
11483
        WasmType::Closure(sig) => pin_stack_closure(ctx, emit, symbols, sig, body),
371
11477
        WasmType::AnyRef => pin_stack_any(ctx, emit),
372
        other => Err(Error::Compile(format!(
373
            "the function operand is {} value, not a function",
374
            with_article(other)
375
        ))),
376
    }
377
25468
}
378

            
379
/// The arguments of the call `designator` that run something, compiled once
380
/// for effect, left to right.
381
4060
fn emit_effectful_args(
382
4060
    ctx: &mut CompileContext,
383
4060
    emit: &mut FunctionEmitter,
384
4060
    symbols: &mut SymbolTable,
385
4060
    designator: &Expr,
386
4060
) -> Result<()> {
387
4060
    let Expr::List(items) = designator else {
388
        return Ok(());
389
    };
390
4060
    for arg in &items[1..] {
391
3957
        if !runs_nothing(symbols, arg) {
392
3138
            compile_for_effect(ctx, emit, symbols, arg)?;
393
819
        }
394
    }
395
4060
    Ok(())
396
4060
}
397

            
398
/// A call whose head runs nothing whatever its arguments: a foldable builtin,
399
/// or a user function whose body runs nothing. Only the arguments' own effects
400
/// are left to emit.
401
65488
fn head_runs_nothing(symbols: &SymbolTable, call: &Expr) -> bool {
402
65488
    let Expr::List(items) = call else {
403
        return false;
404
    };
405
65488
    let Some(Expr::Symbol(head)) = items.first() else {
406
2095
        return false;
407
    };
408
63393
    match symbols.resolve_head(head) {
409
        Head::Function(params, body) => {
410
3349
            let bound: Vec<&str> = params.required.iter().map(String::as_str).collect();
411
3349
            params.optional.is_empty()
412
3346
                && params.rest.is_none()
413
3343
                && params.key.is_empty()
414
2719
                && params.aux.is_empty()
415
2719
                && (is_lambda_literal(symbols, body) || fold_safe_under(symbols, &bound, body))
416
        }
417
3141
        Head::Macro(..) => false,
418
        _ => {
419
56903
            let masked = items[..1]
420
56903
                .iter()
421
56903
                .cloned()
422
56903
                .chain(items[1..].iter().map(|_| Expr::Nil));
423
56903
            fold_safe(symbols, &Expr::List(masked.collect()))
424
        }
425
    }
426
65488
}
427

            
428
/// An operand whose evaluation runs nothing: it folds, is a function literal,
429
/// or is a call that runs nothing on operands that run nothing.
430
641331
pub(in crate::compiler) fn runs_nothing(symbols: &SymbolTable, operand: &Expr) -> bool {
431
641331
    let Expr::List(items) = operand else {
432
497782
        return fold_safe(symbols, operand);
433
    };
434
143549
    fold_safe(symbols, operand)
435
112007
        || is_lambda_literal(symbols, operand)
436
61404
        || (head_runs_nothing(symbols, operand)
437
35093
            && items[1..].iter().all(|arg| runs_nothing(symbols, arg)))
438
641331
}
439

            
440
/// Splits `(progn effects… value)` into its effects and value; any other form
441
/// is its own value.
442
2336000
pub(in crate::compiler) fn effect_prefix(form: &Expr) -> (&[Expr], &Expr) {
443
2336000
    if let Expr::List(items) = form
444
612491
        && matches!(items.first(), Some(Expr::Symbol(head))
445
612491
            if head.eq_ignore_ascii_case("PROGN"))
446
17619
        && let Some((value, effects)) = items[1..].split_last()
447
    {
448
17619
        return (effects, value);
449
2318381
    }
450
2318381
    (&[], form)
451
2336000
}
452

            
453
#[cfg(test)]
454
#[path = "function_operand_tests.rs"]
455
mod tests;