1
//! The call of an `any` function value (PERSIST Q46-2). The call site pushes
2
//! the callee and each argument at its own type and calls one helper per
3
//! argument shape; the helper, filled once the unit's last body has compiled,
4
//! tests the callee against every closure signature of the call's arity, so
5
//! the candidates are the whole unit's. The result is always an `any` value;
6
//! `THE` narrows it. A callee that is no function or takes other arguments
7
//! throws a catchable `TYPE-ERROR`.
8

            
9
use wasm_encoder::{BlockType, HeapType, ValType};
10

            
11
use crate::ast::{Expr, PairElement, Place, WasmType};
12
use crate::compiler::context::{AnyCallHelper, CLOSURE_SIG_FIELD, ClosureSig, CompileContext};
13
use crate::compiler::emit::FunctionEmitter;
14
use crate::compiler::native::{Target, coerce_anyref_to_pair, emit_narrow};
15
use crate::error::{Error, Result};
16
use crate::runtime::SymbolTable;
17

            
18
use super::boxing::emit_box_anyref;
19
use super::local_cell::emit_place_read;
20
use super::stack::compile_for_stack;
21

            
22
/// Calls the `any` value in `place` with `args`, left to right; the result is
23
/// an `any` value.
24
15925
pub(in crate::compiler) fn compile_any_call(
25
15925
    ctx: &mut CompileContext,
26
15925
    emit: &mut FunctionEmitter,
27
15925
    symbols: &mut SymbolTable,
28
15925
    place: Place,
29
15925
    args: &[Expr],
30
15925
) -> Result<WasmType> {
31
15925
    emit_place_read(ctx, emit, place)?;
32
15925
    let mut shape = Vec::with_capacity(args.len());
33
15925
    for arg in args {
34
7377
        shape.push(compile_for_stack(ctx, emit, symbols, arg)?);
35
    }
36
15924
    emit.call(ctx.any_call_helper(&shape)?);
37
15924
    Ok(WasmType::AnyRef)
38
15925
}
39

            
40
/// Fills every helper reserved in the unit; runs once, after the last body.
41
2141123
pub(in crate::compiler) fn fill_any_call_helpers(ctx: &mut CompileContext) -> Result<()> {
42
2141123
    for helper in ctx.take_any_call_helpers() {
43
14458
        fill_helper(ctx, helper)?;
44
    }
45
2141123
    Ok(())
46
2141123
}
47

            
48
14458
fn fill_helper(ctx: &mut CompileContext, helper: AnyCallHelper) -> Result<()> {
49
14458
    let sigs = ctx.closure_sigs_of_arity(helper.shape.len());
50
14458
    let param_count = u32::try_from(helper.shape.len() + 1)
51
        .map_err(|_| crate::error::Error::Compile("any-call arity exceeds u32".to_string()))?;
52
14458
    let snapshot = ctx.take_local_pool(param_count);
53
14458
    let mut emit = FunctionEmitter::new();
54
14458
    let emitted = emit_dispatch(ctx, &mut emit, &helper.shape, &sigs);
55
14458
    let locals = ctx.build_helper_locals(param_count);
56
14458
    ctx.restore_local_pool(snapshot);
57
14458
    emitted?;
58
14458
    ctx.fill_helper(helper.slot, emit.finish(&locals?)?)
59
14458
}
60

            
61
/// `if callee is $closure_sig then call it else …` for each signature that can
62
/// take the arguments, then the error of a callee that matches none.
63
14458
fn emit_dispatch(
64
14458
    ctx: &mut CompileContext,
65
14458
    emit: &mut FunctionEmitter,
66
14458
    shape: &[WasmType],
67
14458
    sigs: &[ClosureSig],
68
14458
) -> Result<()> {
69
14458
    let result = BlockType::Result(ctx.anyref());
70
14458
    let mut open = 0;
71
14458
    for sig in sigs {
72
15483
        let Some(fits) = arm_fits(shape, sig) else {
73
6
            continue;
74
        };
75
15477
        emit_sig_test(ctx, emit, sig)?;
76
15477
        emit.if_block(result);
77
15477
        emit_arm(ctx, emit, sig, &fits)?;
78
15477
        emit.else_block();
79
15477
        open += 1;
80
    }
81
14458
    emit_failure(ctx, emit, result)?;
82
14458
    for _ in 0..open {
83
15477
        emit.block_end()?;
84
    }
85
14458
    Ok(())
86
14458
}
87

            
88
/// Leaves 1 when the callee is a closure of exactly `sig`.
89
15478
fn emit_sig_test(ctx: &CompileContext, emit: &mut FunctionEmitter, sig: &ClosureSig) -> Result<()> {
90
15478
    let sig_id = i32::try_from(sig.id.0)
91
        .map_err(|_| Error::Compile("closure signature id exceeds i32".to_string()))?;
92
15478
    emit.local_get(0);
93
15478
    emit.ref_test_non_null(HeapType::Concrete(ctx.ids.ty_closure_base));
94
15478
    emit.if_block(BlockType::Result(ValType::I32));
95
15478
    emit.local_get(0);
96
15478
    emit.ref_cast(ctx.ids.ty_closure_base);
97
15478
    emit.struct_get(ctx.ids.ty_closure_base, CLOSURE_SIG_FIELD);
98
15478
    emit.i32_const(sig_id);
99
15478
    emit.i32_eq();
100
15478
    emit.else_block();
101
15478
    emit.i32_const(0);
102
15478
    emit.block_end()
103
15478
}
104

            
105
15477
fn emit_arm(
106
15477
    ctx: &mut CompileContext,
107
15477
    emit: &mut FunctionEmitter,
108
15477
    sig: &ClosureSig,
109
15477
    fits: &[Fit],
110
15477
) -> Result<()> {
111
15477
    emit.local_get(0);
112
15477
    emit.ref_cast(sig.closure_type_idx);
113
15477
    emit.struct_get(sig.closure_type_idx, 1);
114
15477
    for (arg, fit) in (1..).zip(fits) {
115
6713
        emit.local_get(arg);
116
6713
        emit_fit(ctx, emit, *fit)?;
117
    }
118
15477
    emit.local_get(0);
119
15477
    emit.ref_cast(sig.closure_type_idx);
120
15477
    emit.struct_get(sig.closure_type_idx, 0);
121
15477
    emit.call_ref(sig.fn_type_idx);
122
15477
    emit_box_anyref(ctx, emit, sig.result);
123
15477
    Ok(())
124
15477
}
125

            
126
14458
fn emit_failure(ctx: &CompileContext, emit: &mut FunctionEmitter, result: BlockType) -> Result<()> {
127
14458
    emit.local_get(0);
128
14458
    emit.ref_test_non_null(HeapType::Concrete(ctx.ids.ty_closure_base));
129
14458
    emit.if_block(result);
130
14458
    emit.call(ctx.ids.wrong_function_arguments);
131
14458
    emit.unreachable();
132
14458
    emit.else_block();
133
14458
    emit.local_get(0);
134
14458
    emit.ref_test_non_null(HeapType::Concrete(ctx.ids.ty_symbol));
135
14458
    emit.if_block(result);
136
14458
    emit.call(ctx.ids.symbol_not_callable);
137
14458
    emit.unreachable();
138
14458
    emit.else_block();
139
14458
    emit.call(ctx.ids.not_a_function);
140
14458
    emit.unreachable();
141
14458
    emit.block_end()?;
142
14458
    emit.block_end()
143
14458
}
144

            
145
/// How an argument becomes the parameter of a signature. Only the
146
/// conversions that throw a catchable `TYPE-ERROR` on a mismatch exist: a
147
/// `$pair` cast cannot check its elements, so a list is never narrowed to a
148
/// typed list.
149
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
150
enum Fit {
151
    Pass,
152
    Box(WasmType),
153
    Narrow(Target),
154
    List,
155
}
156

            
157
15485
fn arm_fits(shape: &[WasmType], sig: &ClosureSig) -> Option<Vec<Fit>> {
158
15485
    shape
159
15485
        .iter()
160
15485
        .zip(&sig.params)
161
6721
        .map(|(arg, param)| fit(*arg, *param))
162
        .collect()
163
15485
}
164

            
165
6734
fn fit(arg: WasmType, param: WasmType) -> Option<Fit> {
166
6734
    match (arg, param) {
167
6734
        (ty, param) if ty == param => Some(Fit::Pass),
168
2
        (ty, WasmType::AnyRef) => Some(Fit::Box(ty)),
169
1
        (WasmType::AnyRef, WasmType::PairRef(PairElement::AnyRef)) => Some(Fit::List),
170
211
        (WasmType::AnyRef, param) => Target::from_wasm(param).map(Fit::Narrow),
171
12
        _ => None,
172
    }
173
6734
}
174

            
175
6713
fn emit_fit(ctx: &mut CompileContext, emit: &mut FunctionEmitter, fit: Fit) -> Result<()> {
176
6713
    match fit {
177
6505
        Fit::Pass => Ok(()),
178
        Fit::Box(ty) => {
179
            emit_box_anyref(ctx, emit, ty);
180
            Ok(())
181
        }
182
208
        Fit::Narrow(target) => emit_narrow(ctx, emit, target),
183
        Fit::List => coerce_anyref_to_pair(ctx, emit),
184
    }
185
6713
}
186

            
187
#[cfg(test)]
188
#[path = "any_call_tests.rs"]
189
mod tests;