1
//! Shared runtime null check for nullable-ref natives (ADR-0033 Phase 5).
2
//!
3
//! `StringRef` and `EntityRef` are the only value types whose `nil_repr` is
4
//! `Null` outside `PairRef` (which has its own `not_a_list` / `car_of_nil`
5
//! handling in `compiler::native::list::car_cdr`). Every consumer that
6
//! dereferences one — a typed-entity accessor's `struct.get`, a string
7
//! native's array read, `STRING=`/`EQUAL`, a host-import argument — routes
8
//! through this one helper rather than trapping the engine on a null
9
//! `struct.get`/`array.len`.
10

            
11
use super::super::context::CompileContext;
12
use super::super::emit::FunctionEmitter;
13
use crate::ast::WasmType;
14
use crate::error::Result;
15
use wasm_encoder::BlockType;
16

            
17
/// The `TYPE-ERROR` trap for a nullable value's `WasmType`, or `None` when
18
/// `ty` is never nil (or is `PairRef`, which has its own trap family).
19
705952
pub(in crate::compiler) fn nullref_trap(ctx: &CompileContext, ty: WasmType) -> Option<u32> {
20
705952
    match ty {
21
539136
        WasmType::StringRef => Some(ctx.ids.nil_string),
22
65728
        WasmType::EntityRef(_) => Some(ctx.ids.nil_entity),
23
101088
        _ => None,
24
    }
25
705952
}
26

            
27
/// Consumes the nullable-ref value on top of the stack, throws `trap` when
28
/// it is null, and otherwise leaves an equal value back on top of the
29
/// stack — the null-checked value is stashed in a scratch local of type
30
/// `ty` so the check itself doesn't disturb it.
31
759025
pub(in crate::compiler) fn require_non_null(
32
759025
    ctx: &mut CompileContext,
33
759025
    emit: &mut FunctionEmitter,
34
759025
    ty: WasmType,
35
759025
    trap: u32,
36
759025
) -> Result<()> {
37
759025
    let local = ctx.alloc_local(ty)?;
38
759025
    emit.local_tee(local);
39
759025
    emit.ref_is_null();
40
759025
    emit.if_block(BlockType::Empty);
41
759025
    emit.call(trap);
42
759025
    emit.unreachable();
43
759025
    emit.block_end()?;
44
759025
    emit.local_get(local);
45
759025
    Ok(())
46
759025
}