as_non_null: Wasm reference instruction
Baseline 2024>
Newly available
Since September 2024, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.
The ref.as_non_null reference instruction converts a nullable reference into a non-nullable one, trapping if the reference is null.
Try it
(module
(import "console" "log" (func $log (param externref)))
(global $greeting (import "js" "greeting") externref)
;; Only accepts non-null references
(func $log_non_null (param $value (ref extern))
(call $log (local.get $value))
)
(func $main
;; $greeting is nullable, so convert it before passing it on
(call $log_non_null
(ref.as_non_null (global.get $greeting))
)
)
(start $main)
)
const url = "{%wasm-url%}";
await WebAssembly.instantiateStreaming(fetch(url), {
console,
js: { greeting: "Hello!" },
});
WAT syntax
ref.as_non_null
ref.as_non_null-
The
ref.as_non_nullinstruction.
Immediates
None.
Operand stack
[input:(ref null heap_type)] -> [output:(ref heap_type)]
Traps
If the operand is a null reference, the instruction traps.
Binary encoding
| Instruction | Binary format | Example text => binary |
|---|---|---|
ref.as_non_null |
0xd4 |
ref.as_non_null => 0xd4 |
Description
The ref.as_non_null instruction checks that a reference isn't null and gives it a non-nullable type, such as (ref extern) instead of (ref null extern). Use it when you have a nullable reference that you need to pass to a function, store in a local, or return from a function whose type only accepts non-null references. Examples of such nullable references include references to nullable globals, locals, or table elements.
If the reference is null, ref.as_non_null traps. When Wasm code is called from JavaScript, a trap is reported as a WebAssembly.RuntimeError exception. In the example above, passing null as the greeting value would cause instantiation to fail with a RuntimeError, because the trap happens in the start function.
To check whether a reference is null without trapping, use ref.is_null.
Specifications
| Specification |
|---|
| WebAssembly Core Specification> # -hrefsyntax-instr-refmathsfrefas_non_null> |