1
//! Runtime-call path: lowers a recursive call with a runtime argument
2
//! through a monomorph helper fn (see `compiler/special/lambda/monomorph.rs`).
3

            
4
use crate::ast::{Expr, LambdaParams, WasmType};
5
use crate::compiler::context::CompileContext;
6
use crate::compiler::context::monomorph::{MonomorphEntry, Slot};
7
use crate::compiler::emit::FunctionEmitter;
8
use crate::compiler::special::lookup_or_emit_monomorph;
9
use crate::error::{Error, Result};
10
use crate::runtime::{Symbol, SymbolTable};
11

            
12
use super::boxing::emit_box_anyref;
13
use super::fold::{probe_typed, probe_value};
14
use super::local_cell::emit_local_read;
15
use super::operand::always_raises;
16
use super::stack::compile_for_stack;
17

            
18
/// Tier 1.5 Gap B runtime-call dispatch. If the inline const-fold walk
19
/// would diverge — `name` is recursive AND at least one arg resolves to
20
/// a runtime value — we lower the call through a real wasm fn instead.
21
/// The body is emitted once per call-site signature (cached) and each
22
/// matching call site emits `call $monomorph_idx`. Returns `None` to
23
/// signal "stay on the inline path"; `Some(ret_ty)` means the runtime
24
/// stack now holds the call's result.
25
460388
pub(super) fn try_compile_runtime_call(
26
460388
    ctx: &mut CompileContext,
27
460388
    emit: &mut FunctionEmitter,
28
460388
    symbols: &mut SymbolTable,
29
460388
    name: &str,
30
460388
    params: &LambdaParams,
31
460388
    body: &Expr,
32
460388
    args: &[Expr],
33
460388
) -> Result<Option<WasmType>> {
34
460388
    if !needs_runtime_call(ctx, symbols, name, body, args) || any_raises(symbols, args)? {
35
423285
        return Ok(None);
36
37103
    }
37
37103
    let arg_types = infer_arg_types(symbols, args)?;
38
37100
    let closures = arg_closure_sources(ctx, symbols, args)?;
39
37100
    let entry = lookup_or_emit_monomorph(ctx, symbols, name, params, body, &arg_types, closures)?;
40
36248
    emit_runtime_call(ctx, emit, symbols, args, &arg_types, &entry)?;
41
36237
    Ok(Some(entry.ret_ty))
42
460388
}
43

            
44
/// An always-raising argument stays on the inline path, which compiles the
45
/// arguments up to it and never enters the body.
46
37109
fn any_raises(symbols: &SymbolTable, args: &[Expr]) -> Result<bool> {
47
37109
    for arg in args {
48
51922
        if always_raises(symbols, arg)? {
49
6
            return Ok(true);
50
51916
        }
51
    }
52
37103
    Ok(false)
53
37109
}
54

            
55
/// Pure classification — the whole arg list is probed SEQUENTIALLY on ONE
56
/// DISPOSABLE clone (so a later arg's probe still sees an earlier arg's
57
/// compile-time effects, e.g. a `setf`), never on the live table: this runs
58
/// ahead of the real per-argument compile ([`compile_arg_for_param`]), so it
59
/// must not apply any argument's effects itself — the real, single
60
/// application happens later, in codegen.
61
460388
fn needs_runtime_call(
62
460388
    ctx: &CompileContext,
63
460388
    symbols: &SymbolTable,
64
460388
    self_name: &str,
65
460388
    body: &Expr,
66
460388
    args: &[Expr],
67
460388
) -> bool {
68
460388
    let mut probe = symbols.clone();
69
592265
    let any_runtime = args.iter().any(|arg| arg_resolves_runtime(&mut probe, arg));
70
460388
    any_runtime && body_calls_inlining_or_self(ctx, self_name, body)
71
460388
}
72

            
73
592265
fn arg_resolves_runtime(probe: &mut SymbolTable, arg: &Expr) -> bool {
74
592265
    probe_value(probe, arg).is_ok_and(|value| value.is_wasm_runtime())
75
592265
}
76

            
77
/// Same disposable-clone, sequential-visibility probing as
78
/// [`needs_runtime_call`] — a SEPARATE clone of the (still unmodified) live
79
/// table, since this runs only once `needs_runtime_call` already decided a
80
/// runtime call is needed and its own probe was already discarded.
81
37103
fn infer_arg_types(symbols: &SymbolTable, args: &[Expr]) -> Result<Vec<WasmType>> {
82
37103
    let mut probe = symbols.clone();
83
37103
    args.iter()
84
51910
        .map(|arg| infer_arg_type(&mut probe, arg))
85
        .collect()
86
37103
}
87

            
88
/// The interned source of each capture-free closure argument.
89
37100
fn arg_closure_sources(
90
37100
    ctx: &mut CompileContext,
91
37100
    symbols: &SymbolTable,
92
37100
    args: &[Expr],
93
37100
) -> Result<Vec<Option<u32>>> {
94
37100
    let mut probe = symbols.clone();
95
37100
    args.iter()
96
51907
        .map(|arg| {
97
51907
            let resolved = probe_value(&mut probe, arg)?;
98
51907
            let source = resolved
99
51907
                .place()
100
10340
                .and_then(|(place, _)| probe.closure_body(place))
101
                .cloned();
102
51907
            source
103
34
                .map(|(params, body)| ctx.monomorph_cache_mut().intern_source(params, body))
104
                .transpose()
105
51907
        })
106
        .collect()
107
37100
}
108

            
109
51910
fn infer_arg_type(probe: &mut SymbolTable, arg: &Expr) -> Result<WasmType> {
110
51910
    let resolved = probe_typed(probe, arg)?;
111
    // The monomorph parameter slot type is exactly the stack type the arg
112
    // lowers to — the shared classifier keeps the signature, the eval-path
113
    // recursive-call placeholder, and `compile_for_stack` in agreement.
114
51907
    crate::compiler::expr::classify_stack_type(&resolved).ok_or_else(|| {
115
        Error::Compile(format!(
116
            "runtime-call lowering can't classify argument type for {resolved:?}; \
117
             rewrite the call so each argument is a numeric or runtime value"
118
        ))
119
    })
120
51910
}
121

            
122
36250
fn emit_runtime_call(
123
36250
    ctx: &mut CompileContext,
124
36250
    emit: &mut FunctionEmitter,
125
36250
    symbols: &mut SymbolTable,
126
36250
    args: &[Expr],
127
36250
    arg_types: &[WasmType],
128
36250
    entry: &MonomorphEntry,
129
36250
) -> Result<()> {
130
36250
    for (arg, &expected) in args.iter().zip(arg_types.iter()) {
131
48144
        let actual = compile_for_stack(ctx, emit, symbols, arg)?;
132
48133
        if expected == WasmType::AnyRef {
133
2705
            emit_box_anyref(ctx, emit, actual);
134
45428
        } else if actual != expected {
135
1
            return Err(Error::Compile(format!(
136
1
                "runtime-call argument type mismatch: expected {expected:?}, got {actual:?}"
137
1
            )));
138
45427
        }
139
    }
140
36238
    for slot in &entry.slots {
141
8
        push_slot(ctx, emit, symbols, slot)?;
142
    }
143
36238
    emit.call(entry.func_idx);
144
36238
    Ok(())
145
36250
}
146

            
147
/// A cell slot passes the cell itself, so the helper and its caller share
148
/// every store; a plain slot passes the current value.
149
8
fn push_slot(
150
8
    ctx: &mut CompileContext,
151
8
    emit: &mut FunctionEmitter,
152
8
    symbols: &SymbolTable,
153
8
    slot: &Slot,
154
8
) -> Result<()> {
155
8
    let Some(Expr::WasmLocal(idx, _)) = symbols.lookup(&slot.name).and_then(Symbol::value) else {
156
        return Err(Error::Compile(format!(
157
            "{}: a runtime-call slot is not bound to a local at the call site",
158
            slot.name
159
        )));
160
    };
161
8
    match (slot.cell, ctx.cell_of(*idx)) {
162
        (true, None) => Err(Error::Compile(format!(
163
            "{}: a runtime-call slot expected a shared cell",
164
            slot.name
165
        ))),
166
        (true, Some(_)) => {
167
            emit.local_get(*idx);
168
            Ok(())
169
        }
170
        (false, _) => {
171
8
            emit_local_read(ctx, emit, *idx);
172
8
            Ok(())
173
        }
174
    }
175
8
}
176

            
177
2720618
fn body_calls_inlining_or_self(ctx: &CompileContext, self_name: &str, expr: &Expr) -> bool {
178
2720618
    match expr {
179
        Expr::List(elems) => {
180
951582
            if let Some(Expr::Symbol(name)) = elems.first()
181
859626
                && (name == self_name || ctx.is_inlining(name))
182
            {
183
37110
                return true;
184
914472
            }
185
914472
            elems
186
914472
                .iter()
187
2490290
                .any(|e| body_calls_inlining_or_self(ctx, self_name, e))
188
        }
189
41
        Expr::Quasiquote(template) => template
190
41
            .unquoted_forms()
191
41
            .into_iter()
192
40
            .any(|form| body_calls_inlining_or_self(ctx, self_name, form)),
193
        Expr::Unquote(inner) | Expr::UnquoteSplicing(inner) => {
194
            body_calls_inlining_or_self(ctx, self_name, inner)
195
        }
196
        Expr::Cons(car, cdr) => {
197
            body_calls_inlining_or_self(ctx, self_name, car)
198
                || body_calls_inlining_or_self(ctx, self_name, cdr)
199
        }
200
        Expr::Lambda(_, body) => body_calls_inlining_or_self(ctx, self_name, body),
201
1768995
        _ => false,
202
    }
203
2720618
}
204

            
205
#[cfg(test)]
206
#[path = "call_runtime_tests.rs"]
207
mod tests;