1
//! The `$any_call_<shape>` dispatch helpers a call of an `any` value rides
2
//! (PERSIST Q46-2): one function per argument shape, reserved at the first
3
//! call of that shape and filled once the unit's last body has compiled.
4

            
5
use super::{ClosureSig, HelperSlot};
6
use crate::ast::WasmType;
7
use crate::compiler::context::CompileContext;
8
use crate::error::Result;
9

            
10
#[derive(Debug, Clone)]
11
pub(crate) struct AnyCallHelper {
12
    pub shape: Vec<WasmType>,
13
    pub func_idx: u32,
14
    pub slot: HelperSlot,
15
}
16

            
17
impl CompileContext {
18
    /// The function index of the helper for `shape`, registered with its code
19
    /// slot reserved on first use.
20
15928
    pub(crate) fn any_call_helper(&mut self, shape: &[WasmType]) -> Result<u32> {
21
15928
        if let Some(helper) = self.closures.any_calls.iter().find(|h| h.shape == shape) {
22
1044
            return Ok(helper.func_idx);
23
14884
        }
24
14884
        let name = format!("__any_call_{}", self.closures.any_calls.len());
25
14884
        let anyref = self.anyref();
26
14884
        let mut params = vec![anyref];
27
14884
        for arg in shape {
28
7172
            params.push(self.wasm_val_type(*arg)?);
29
        }
30
14884
        let func_idx = self.register_function(&name, &params, &[anyref])?;
31
14884
        let slot = self.reserve_helper();
32
14884
        self.closures.any_calls.push(AnyCallHelper {
33
14884
            shape: shape.to_vec(),
34
14884
            func_idx,
35
14884
            slot,
36
14884
        });
37
14884
        Ok(func_idx)
38
15928
    }
39

            
40
    /// The helpers still to be filled.
41
2141127
    pub(crate) fn take_any_call_helpers(&mut self) -> Vec<AnyCallHelper> {
42
2141127
        std::mem::take(&mut self.closures.any_calls)
43
2141127
    }
44

            
45
    /// Every closure signature of `arity` parameters, in interning order.
46
14460
    pub(crate) fn closure_sigs_of_arity(&self, arity: usize) -> Vec<ClosureSig> {
47
14460
        self.closures
48
14460
            .by_id
49
14460
            .iter()
50
17383
            .filter(|sig| sig.params.len() == arity)
51
            .cloned()
52
            .collect()
53
14460
    }
54
}