1
//! Per-`(defun_name, signature)` monomorph cache.
2
//!
3
//! Tier 1.5 closes Gap B (recursive defun called with a runtime arg) by
4
//! lowering through a real wasm fn rather than the inline const-fold
5
//! walk. Each distinct call-site signature gets its own emitted fn:
6
//! `(defun fact (n) ...)` called with a `Ratio` arg emits one wasm fn,
7
//! the same defun called with (hypothetically) a `Commodity` arg emits
8
//! another. The cache lookup is keyed by `(name, params)` so call sites
9
//! with identical signatures share one fn — including the recursive
10
//! self-call inside the body.
11
//!
12
//! The cache is mutated only by [`CompileContext::lookup_or_emit_monomorph`]
13
//! (added in `compiler/expr/call.rs`) and snapshot-restored along with
14
//! the rest of the wasm-section state via [`super::snapshot`].
15

            
16
use std::collections::HashMap;
17

            
18
use crate::ast::{Expr, LambdaParams, WasmType};
19
use crate::error::{Error, Result};
20

            
21
use super::CompileContext;
22

            
23
/// A free runtime name the helper reads from its caller: passed after the
24
/// arguments, as the shared cell itself or as a plain value.
25
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
26
pub(crate) struct Slot {
27
    pub name: String,
28
    pub ty: WasmType,
29
    pub cell: bool,
30
}
31

            
32
/// One monomorph entry: the wasm fn idx at which the body was emitted
33
/// plus the body-derived return type and the slots every call passes.
34
/// Cloneable + Eq because it lives in the snapshot/restore graph.
35
#[derive(Debug, Clone, PartialEq, Eq)]
36
pub(crate) struct MonomorphEntry {
37
    pub func_idx: u32,
38
    pub ret_ty: WasmType,
39
    pub slots: Vec<Slot>,
40
}
41

            
42
/// Cache key: defun name, the table-assigned id of the definition it
43
/// resolved to, the redefinition epoch, the monomorph parameter signature and the free
44
/// runtime names it takes. The body AST stays
45
/// stored on the `Symbol::function` slot and is re-fetched at emit time;
46
/// a redefinition or a shadowing LABELS gets a fresh id, so it misses.
47
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
48
pub(crate) struct MonomorphKey {
49
    pub name: String,
50
    pub definition: u32,
51
    pub epoch: u32,
52
    pub params: Vec<WasmType>,
53
    /// Per parameter, the interned source of a capture-free closure argument:
54
    /// the helper inlines it per call, as the call site would, so two lambdas
55
    /// of one signature never share a helper.
56
    pub closures: Vec<Option<u32>>,
57
    pub slots: Vec<Slot>,
58
}
59

            
60
#[derive(Debug, Default, Clone)]
61
pub(crate) struct MonomorphCache {
62
    entries: HashMap<MonomorphKey, MonomorphEntry>,
63
    sources: Vec<(LambdaParams, Expr)>,
64
}
65

            
66
impl MonomorphCache {
67
38
    pub(crate) fn intern_source(&mut self, params: LambdaParams, body: Expr) -> Result<u32> {
68
38
        let source = (params, body);
69
38
        let at = match self.sources.iter().position(|known| *known == source) {
70
18
            Some(at) => at,
71
            None => {
72
20
                self.sources.push(source);
73
20
                self.sources.len() - 1
74
            }
75
        };
76
38
        u32::try_from(at).map_err(|_| Error::Compile("closure source id space exhausted".into()))
77
38
    }
78

            
79
19
    pub(crate) fn source(&self, id: u32) -> Option<&(LambdaParams, Expr)> {
80
19
        self.sources.get(usize::try_from(id).ok()?)
81
19
    }
82

            
83
37097
    pub(crate) fn get(&self, key: &MonomorphKey) -> Option<&MonomorphEntry> {
84
37097
        self.entries.get(key)
85
37097
    }
86

            
87
36884
    pub(crate) fn insert(&mut self, key: MonomorphKey, entry: MonomorphEntry) {
88
36884
        self.entries.insert(key, entry);
89
36884
    }
90
}
91

            
92
impl CompileContext {
93
37114
    pub(crate) fn monomorph_cache(&self) -> &MonomorphCache {
94
37114
        &self.monomorphs
95
37114
    }
96

            
97
36918
    pub(crate) fn monomorph_cache_mut(&mut self) -> &mut MonomorphCache {
98
36918
        &mut self.monomorphs
99
36918
    }
100
}
101

            
102
#[cfg(test)]
103
#[path = "monomorph_tests.rs"]
104
mod tests;