Lines
100 %
Functions
75 %
Branches
//! Shared runtime null check for nullable-ref natives (ADR-0033 Phase 5).
//!
//! `StringRef` and `EntityRef` are the only value types whose `nil_repr` is
//! `Null` outside `PairRef` (which has its own `not_a_list` / `car_of_nil`
//! handling in `compiler::native::list::car_cdr`). Every consumer that
//! dereferences one — a typed-entity accessor's `struct.get`, a string
//! native's array read, `STRING=`/`EQUAL`, a host-import argument — routes
//! through this one helper rather than trapping the engine on a null
//! `struct.get`/`array.len`.
use super::super::context::CompileContext;
use super::super::emit::FunctionEmitter;
use crate::ast::WasmType;
use crate::error::Result;
use wasm_encoder::BlockType;
/// The `TYPE-ERROR` trap for a nullable value's `WasmType`, or `None` when
/// `ty` is never nil (or is `PairRef`, which has its own trap family).
pub(in crate::compiler) fn nullref_trap(ctx: &CompileContext, ty: WasmType) -> Option<u32> {
match ty {
WasmType::StringRef => Some(ctx.ids.nil_string),
WasmType::EntityRef(_) => Some(ctx.ids.nil_entity),
_ => None,
}
/// Consumes the nullable-ref value on top of the stack, throws `trap` when
/// it is null, and otherwise leaves an equal value back on top of the
/// stack — the null-checked value is stashed in a scratch local of type
/// `ty` so the check itself doesn't disturb it.
pub(in crate::compiler) fn require_non_null(
ctx: &mut CompileContext,
emit: &mut FunctionEmitter,
ty: WasmType,
trap: u32,
) -> Result<()> {
let local = ctx.alloc_local(ty)?;
emit.local_tee(local);
emit.ref_is_null();
emit.if_block(BlockType::Empty);
emit.call(trap);
emit.unreachable();
emit.block_end()?;
emit.local_get(local);
Ok(())