1
//! Compile-time emit for caller-supplied host fn calls.
2
//!
3
//! When `(rpc-protocol-version)` (or any other registered `HostFnSpec`)
4
//! shows up in nomiscript source, the dispatcher in `super::mod`
5
//! routes here. We push each argument onto the wasm stack via
6
//! `compile_for_stack`, validate the type matches the spec, and emit
7
//! `(call $idx)` against the import index recorded by
8
//! [`CompileContext::register_host_fn`].
9

            
10
use super::CompileContext;
11
use super::nullable::{nullref_trap, require_non_null};
12
use crate::ast::{Expr, WasmType};
13
use crate::compiler::emit::FunctionEmitter;
14
use crate::compiler::expr::compile_for_stack_as;
15
use crate::error::{Error, Result};
16
use crate::runtime::SymbolTable;
17

            
18
1560205
pub(in crate::compiler) fn compile_host_fn_for_stack(
19
1560205
    ctx: &mut CompileContext,
20
1560205
    emit: &mut FunctionEmitter,
21
1560205
    symbols: &mut SymbolTable,
22
1560205
    name: &str,
23
1560205
    args: &[Expr],
24
1560205
) -> Result<WasmType> {
25
1560205
    let entry = expect_entry(ctx, name)?;
26
1560205
    let result = entry.result.ok_or_else(|| {
27
416
        Error::Compile(format!(
28
416
            "host fn '{name}' has no return type and cannot produce a stack value"
29
416
        ))
30
416
    })?;
31
1559789
    let func_idx = entry.func_idx;
32
1559789
    let params = entry.params;
33
1559789
    push_args(ctx, emit, symbols, name, &params, args)?;
34
1559581
    symbols.mark_native_referenced(name);
35
1559581
    emit.call(func_idx);
36
    // Host imports declare GC-ref results with the abstract heap type
37
    // (`(ref null struct)` / `(ref null array)`) because that's what
38
    // `Rooted<StructRef>` / `Rooted<ArrayRef>` report through
39
    // `WasmTy::valtype()`. Cast the result back to the concrete type
40
    // the rest of the pipeline expects.
41
1559581
    emit_concrete_cast(ctx, emit, result)?;
42
1559581
    Ok(result)
43
1560205
}
44

            
45
23934
pub(in crate::compiler) fn compile_host_fn_for_effect(
46
23934
    ctx: &mut CompileContext,
47
23934
    emit: &mut FunctionEmitter,
48
23934
    symbols: &mut SymbolTable,
49
23934
    name: &str,
50
23934
    args: &[Expr],
51
23934
) -> Result<()> {
52
23934
    let entry = expect_entry(ctx, name)?;
53
23934
    let result = entry.result;
54
23934
    let func_idx = entry.func_idx;
55
23934
    let params = entry.params;
56
23934
    push_args(ctx, emit, symbols, name, &params, args)?;
57
23934
    symbols.mark_native_referenced(name);
58
23934
    emit.call(func_idx);
59
23934
    if let Some(ty) = result {
60
23726
        emit_concrete_cast(ctx, emit, ty)?;
61
23726
        emit.drop_value();
62
208
    }
63
23934
    Ok(())
64
23934
}
65

            
66
/// Casts the abstract `(ref null struct)` / `(ref null array)` left on
67
/// the stack by a host import to the concrete type the result's
68
/// `WasmType` declares. Primitive returns (I32) pass through unchanged.
69
/// Nullable variant: wasmtime surfaces `Option<Rooted<…>>` returns as
70
/// `(ref null …)`, so an empty `list-accounts` / not-found
71
/// `get-account` returns null and the cast must preserve it. The
72
/// non-null `ref_cast` would trap on every nil-shaped result.
73
1583307
pub(in crate::compiler) fn emit_concrete_cast(
74
1583307
    ctx: &CompileContext,
75
1583307
    emit: &mut FunctionEmitter,
76
1583307
    ty: WasmType,
77
1583307
) -> Result<()> {
78
1583307
    match ty {
79
1254593
        WasmType::I32 | WasmType::Bool => {}
80
3028
        WasmType::Ratio => emit.ref_cast_nullable(ctx.ids.ty_ratio),
81
17592
        WasmType::Commodity => emit.ref_cast_nullable(ctx.ids.ty_commodity),
82
133744
        WasmType::StringRef => emit.ref_cast_nullable(ctx.ids.ty_i8_array),
83
        WasmType::SymbolRef => emit.ref_cast_nullable(ctx.ids.ty_symbol),
84
18721
        WasmType::PairRef(_) => emit.ref_cast_nullable(ctx.ids.ty_pair),
85
84493
        WasmType::EntityRef(kind) => emit.ref_cast_nullable(ctx.ids.entity_type(kind)),
86
        WasmType::StructRef(_) => emit.ref_cast_nullable(ctx.ids.ty_struct),
87
        WasmType::Closure(sig) => emit.ref_cast_nullable(ctx.closure_sig(sig)?.closure_type_idx),
88
71136
        WasmType::AnyRef => {}
89
    }
90
1583307
    Ok(())
91
1583307
}
92

            
93
1584139
fn expect_entry(ctx: &CompileContext, name: &str) -> Result<HostFnSnapshot> {
94
1584139
    let entry = ctx.lookup_host_fn(name).ok_or_else(|| {
95
        Error::Compile(format!(
96
            "host fn dispatch reached for unregistered name '{name}'"
97
        ))
98
    })?;
99
1584139
    Ok(HostFnSnapshot {
100
1584139
        func_idx: entry.func_idx,
101
1584139
        params: entry.params.clone(),
102
1584139
        result: entry.result,
103
1584139
    })
104
1584139
}
105

            
106
struct HostFnSnapshot {
107
    func_idx: u32,
108
    params: Vec<WasmType>,
109
    result: Option<WasmType>,
110
}
111

            
112
1583723
fn push_args(
113
1583723
    ctx: &mut CompileContext,
114
1583723
    emit: &mut FunctionEmitter,
115
1583723
    symbols: &mut SymbolTable,
116
1583723
    name: &str,
117
1583723
    params: &[WasmType],
118
1583723
    args: &[Expr],
119
1583723
) -> Result<()> {
120
1583723
    if args.len() != params.len() {
121
        return Err(Error::Arity {
122
            name: name.to_string(),
123
            expected: params.len(),
124
            actual: args.len(),
125
        });
126
1583723
    }
127
    // Pass 1: evaluate every argument, left to right, into a scratch local —
128
    // BEFORE any validation runs. A validation throw (the null check below,
129
    // or the commodity atomicity guard) must never pre-empt a later
130
    // argument's own side effects/errors: `(f (if p x) (progn (error ...) y))`
131
    // must raise from evaluating the second argument even when the first
132
    // would fail its own check, exactly as evaluating both arguments would
133
    // with no host-fn call at all.
134
1583723
    let mut locals = Vec::with_capacity(args.len());
135
1583723
    for (idx, (arg, expected_ty)) in args.iter().zip(params.iter()).enumerate() {
136
        // Coerce each argument to the host fn's declared parameter type; an
137
        // integer/fractional literal crosses the sanctioned Index↔Scalar
138
        // boundary so e.g. a `Ratio` arg accepts a bare literal.
139
706160
        compile_for_stack_as(ctx, emit, symbols, arg, *expected_ty).map_err(|_| Error::Type {
140
208
            expected: format!("{expected_ty} for argument {idx} of '{name}'"),
141
208
            actual: "an incompatible value".to_string(),
142
208
        })?;
143
705952
        let local = ctx.alloc_local(*expected_ty)?;
144
705952
        emit.local_set(local);
145
705952
        locals.push((local, *expected_ty));
146
    }
147
    // Pass 2: validate every already-evaluated argument.
148
1583515
    for &(local, expected_ty) in &locals {
149
        // A nullable `StringRef` / `EntityRef` reaching a host import as `nil`
150
        // would surface as an uncatchable `Option::None`-vs-value mismatch on
151
        // the wasmtime boundary rather than a compiler-level condition; catch
152
        // it here as a catchable `TYPE-ERROR` before the call (ADR-0033 Phase
153
        // 5). `rpc::natives::*` keeps its own `Option` handling as a
154
        // defensive fallback, not the primary guard.
155
705952
        if let Some(trap) = nullref_trap(ctx, expected_ty) {
156
604864
            emit.local_get(local);
157
604864
            require_non_null(ctx, emit, expected_ty, trap)?;
158
604864
            emit.local_set(local);
159
101088
        }
160
        // ADR-0028 E2: the wasm↔host border is unit-erased — host fns only see
161
        // ATOMIC single-currency money (fields 0-3). Guard every Commodity arg:
162
        // `commodity_assert_atomic` returns it unchanged when its unit term is
163
        // null, else throws a catchable `NON-ATOMIC-COMMODITY`, so a compound
164
        // value can never be misread as `id = 0` money.
165
705952
        if expected_ty == WasmType::Commodity {
166
1456
            emit.local_get(local);
167
1456
            emit.call(ctx.ids.commodity_assert_atomic);
168
1456
            emit.local_set(local);
169
704496
        }
170
    }
171
    // Pass 3: reload the validated arguments onto the stack, in call order.
172
1583515
    for &(local, _) in &locals {
173
705952
        emit.local_get(local);
174
    }
175
1583515
    Ok(())
176
1583723
}