From 5066e3bff62b5d401f9bbaeb19d567c99f287267 Mon Sep 17 00:00:00 2001 From: Till Schneidereit Date: Wed, 11 Nov 2026 15:14:43 +0100 Subject: [PATCH 1/5] IR: add an externref type and reject other abstract reference types. `From for Type` mapped every reference type without a type index to `Type::FuncRef`. An `externref` in a signature, local, global or table came out as `funcref`, so the output of `(module (func (result externref) (ref.null extern)))` failed validation. Reference types the IR has no variant for, such as `(ref func)` or `anyref`, were also turned into `funcref`. Add `Type::ExternRef` for nullable `extern` references, with its display name and its encoding. Replace the `From` conversions from `wasmparser::ValType` and `wasmparser::RefType` to `Type`, and from `wasmparser::FuncType` to `SignatureData`, with `TryFrom` conversions that return `FrontendError::UnsupportedFeature` for non-nullable abstract references, shared abstract references, exact references, references to a rec-group type index and abstract heap types other than `func` and `extern`. The frontend propagates the error from the type section, imports, globals, tables, locals and block types. A `select` whose type cannot be converted, and any other operator that `Operator::try_from` does not convert, now returns `FrontendError::UnsupportedFeature` instead of panicking. The type section also returns `FrontendError::UnsupportedFeature` for a shared function type. `SignatureData` has no field for `shared`, so the backend emitted such a type as an unshared function type. --- src/frontend.rs | 43 ++++++++++++++---------- src/ir.rs | 72 ++++++++++++++++++++++++++++++---------- src/ir/module.rs | 29 +++++++++------- src/ops.rs | 8 ++--- tests/reference_types.rs | 46 +++++++++++++++++++++++++ 5 files changed, 147 insertions(+), 51 deletions(-) create mode 100644 tests/reference_types.rs diff --git a/src/frontend.rs b/src/frontend.rs index 2960add..8ee1bcc 100644 --- a/src/frontend.rs +++ b/src/frontend.rs @@ -12,7 +12,7 @@ use addr2line::gimli; use anyhow::{bail, Result}; use fxhash::{FxHashMap, FxHashSet}; use log::trace; -use std::convert::TryFrom; +use std::convert::{TryFrom, TryInto}; use wasmparser::{BlockType, DataKind, ExternalKind, KnownCustom, Name, Parser, Payload, TypeRef}; /// Options to control the Wasm-to-bytecode translation process. @@ -98,7 +98,7 @@ fn element_type(items: &wasmparser::ElementItems) -> Result { wasmparser::ElementItems::Expressions(ty, _) if *ty == wasmparser::RefType::FUNCREF || ty.type_index().is_some() => { - Ok((*ty).into()) + Ok((*ty).try_into()?) } wasmparser::ElementItems::Expressions(ty, _) => bail!(FrontendError::UnsupportedFeature( format!("Unsupported element segment type: {:?}", ty) @@ -164,13 +164,14 @@ fn memory_data(ty: &wasmparser::MemoryType) -> Result { } /// Converts a table type to a `TableData` with no elements. Returns -/// `FrontendError::UnsupportedFeature` for a 64-bit table. +/// `FrontendError::UnsupportedFeature` for a 64-bit table and for an +/// element type that `Type` cannot represent. fn table_data(ty: &wasmparser::TableType) -> Result { if ty.table64 { bail!(FrontendError::UnsupportedFeature("64-bit table".into())); } Ok(TableData { - ty: ty.element_type.into(), + ty: ty.element_type.try_into()?, initial: ty.initial, max: ty.maximum, initializer: None, @@ -238,9 +239,14 @@ fn handle_payload<'a>( Payload::TypeSection(reader) => { for rec_group in reader { for ty in rec_group?.into_types() { + if ty.composite_type.shared { + bail!(FrontendError::UnsupportedFeature( + "shared type in type section".into() + )); + } match &ty.composite_type.inner { wasmparser::CompositeInnerType::Func(fty) => { - module.signatures.push(fty.into()); + module.signatures.push(fty.try_into()?); } _ => bail!(FrontendError::UnsupportedFeature( "non-function type in type section".into() @@ -265,7 +271,7 @@ fn handle_payload<'a>( } TypeRef::Global(ty) => { let mutable = ty.mutable; - let ty = ty.content_type.into(); + let ty = ty.content_type.try_into()?; let global = module.globals.push(GlobalData { ty, value: None, @@ -322,7 +328,7 @@ fn handle_payload<'a>( for global in reader { let global = global?; let mutable = global.ty.mutable; - let ty = global.ty.content_type.into(); + let ty = global.ty.content_type.try_into()?; let init_expr = parse_init_expr(&global.init_expr)?; module.globals.push(GlobalData { ty, @@ -549,7 +555,7 @@ fn handle_payload<'a>( let table = Table::from(table_index.unwrap_or(0)); let ty = match &element.items { wasmparser::ElementItems::Functions(_) => Type::FuncRef, - wasmparser::ElementItems::Expressions(ty, _) => (*ty).into(), + wasmparser::ElementItems::Expressions(ty, _) => (*ty).try_into()?, }; module.active_element_segments.push(ActiveElementSegment { index, @@ -671,7 +677,7 @@ pub(crate) fn parse_body<'a>( for _ in 0..locals.get_count() { let (count, ty) = locals.read()?; for _ in 0..count { - ret.locals.push(ty.into()); + ret.locals.push(ty.try_into()?); } } let locals = ret.locals.clone(); @@ -1618,7 +1624,10 @@ impl<'a, 'b> FunctionBodyBuilder<'a, 'b> { | wasmparser::Operator::RefFunc { .. } | wasmparser::Operator::MemoryFill { .. } | wasmparser::Operator::MemoryCopy { .. } => { - self.emit(Operator::try_from(&op).unwrap(), loc)? + let op = Operator::try_from(&op).map_err(|()| { + FrontendError::UnsupportedFeature(format!("Unsupported operator: {:?}", op)) + })?; + self.emit(op, loc)? } wasmparser::Operator::Nop => {} @@ -1851,7 +1860,7 @@ impl<'a, 'b> FunctionBodyBuilder<'a, 'b> { } wasmparser::Operator::Block { blockty } => { - let (params, results) = self.block_params_and_results(*blockty); + let (params, results) = self.block_params_and_results(*blockty)?; let out = self.body.add_block(); self.add_block_params(out, &results[..]); let start_depth = if self.reachable { @@ -1869,7 +1878,7 @@ impl<'a, 'b> FunctionBodyBuilder<'a, 'b> { } wasmparser::Operator::Loop { blockty } => { - let (params, results) = self.block_params_and_results(*blockty); + let (params, results) = self.block_params_and_results(*blockty)?; let header = self.body.add_block(); self.add_block_params(header, ¶ms[..]); let initial_args = if self.reachable { @@ -1895,7 +1904,7 @@ impl<'a, 'b> FunctionBodyBuilder<'a, 'b> { } wasmparser::Operator::If { blockty } => { - let (params, results) = self.block_params_and_results(*blockty); + let (params, results) = self.block_params_and_results(*blockty)?; let if_true = self.body.add_block(); let if_false = self.body.add_block(); let join = self.body.add_block(); @@ -1983,10 +1992,10 @@ impl<'a, 'b> FunctionBodyBuilder<'a, 'b> { } } - fn block_params_and_results(&self, ty: BlockType) -> (Vec, Vec) { - match ty { + fn block_params_and_results(&self, ty: BlockType) -> Result<(Vec, Vec)> { + Ok(match ty { BlockType::Empty => (vec![], vec![]), - BlockType::Type(ret_ty) => (vec![], vec![ret_ty.into()]), + BlockType::Type(ret_ty) => (vec![], vec![ret_ty.try_into()?]), BlockType::FuncType(sig_idx) => { let sig = &self.module.signatures[Signature::from(sig_idx)]; ( @@ -1994,7 +2003,7 @@ impl<'a, 'b> FunctionBodyBuilder<'a, 'b> { Vec::from(sig.returns.clone()), ) } - } + }) } fn relative_frame(&mut self, relative_depth: u32) -> &mut Frame { diff --git a/src/ir.rs b/src/ir.rs index 7f99bf4..d759085 100644 --- a/src/ir.rs +++ b/src/ir.rs @@ -1,12 +1,14 @@ //! Intermediate representation for Wasm. use crate::declare_entity; +use crate::FrontendError; +use std::convert::{TryFrom, TryInto}; /// Types in waffle's IR. /// /// These types correspond to (a subset of) the primitive Wasm value -/// types: integers, floats, SIMD vectors, and function references -/// (optionally typed). +/// types: integers, floats, SIMD vectors, function references +/// (optionally typed), and external references. /// /// Every SSA value in a function body has a `Type`, unless it is a /// tuple (multi-value or zero-value result). @@ -32,31 +34,61 @@ pub enum Type { V128, /// A function reference. FuncRef, + /// A nullable external reference (`externref`). + ExternRef, /// A typed function reference, optionally nullable, and with type /// specified by a signature index in the module's signature /// index-space. TypedFuncRef(bool, u32), } -impl From for Type { - fn from(ty: wasmparser::ValType) -> Self { +impl TryFrom for Type { + type Error = FrontendError; + + fn try_from(ty: wasmparser::ValType) -> Result { match ty { - wasmparser::ValType::I32 => Type::I32, - wasmparser::ValType::I64 => Type::I64, - wasmparser::ValType::F32 => Type::F32, - wasmparser::ValType::F64 => Type::F64, - wasmparser::ValType::V128 => Type::V128, - wasmparser::ValType::Ref(r) => r.into(), + wasmparser::ValType::I32 => Ok(Type::I32), + wasmparser::ValType::I64 => Ok(Type::I64), + wasmparser::ValType::F32 => Ok(Type::F32), + wasmparser::ValType::F64 => Ok(Type::F64), + wasmparser::ValType::V128 => Ok(Type::V128), + wasmparser::ValType::Ref(r) => r.try_into(), } } } -impl From for Type { - fn from(ty: wasmparser::RefType) -> Self { - match ty.type_index() { - Some(idx) => { - let nullable = ty.is_nullable(); - Type::TypedFuncRef(nullable, idx.as_module_index().unwrap()) +/// Converts a reference type to a `Type`. Nullable `func` and `extern` +/// references convert to `FuncRef` and `ExternRef`, and references to a +/// module type index convert to `TypedFuncRef`. Every other reference +/// type returns `FrontendError::UnsupportedFeature`: non-nullable +/// abstract references, shared abstract references, exact references, +/// references to a rec-group type index, and abstract heap types other +/// than `func` and `extern`. +impl TryFrom for Type { + type Error = FrontendError; + + fn try_from(ty: wasmparser::RefType) -> Result { + use wasmparser::{AbstractHeapType, HeapType, UnpackedIndex}; + match (ty.heap_type(), ty.is_nullable()) { + (HeapType::Concrete(UnpackedIndex::Module(idx)), nullable) => { + Ok(Type::TypedFuncRef(nullable, idx)) } - None => Type::FuncRef, + ( + HeapType::Abstract { + shared: false, + ty: AbstractHeapType::Func, + }, + true, + ) => Ok(Type::FuncRef), + ( + HeapType::Abstract { + shared: false, + ty: AbstractHeapType::Extern, + }, + true, + ) => Ok(Type::ExternRef), + _ => Err(FrontendError::UnsupportedFeature(format!( + "Unsupported reference type: {}", + ty + ))), } } } @@ -70,6 +102,7 @@ impl std::fmt::Display for Type { Type::F64 => write!(f, "f64"), Type::V128 => write!(f, "v128"), Type::FuncRef => write!(f, "funcref"), + Type::ExternRef => write!(f, "externref"), Type::TypedFuncRef(nullable, idx) => write!( f, "funcref({}, {})", @@ -88,7 +121,9 @@ impl From for wasm_encoder::ValType { Type::F32 => wasm_encoder::ValType::F32, Type::F64 => wasm_encoder::ValType::F64, Type::V128 => wasm_encoder::ValType::V128, - Type::FuncRef | Type::TypedFuncRef(..) => wasm_encoder::ValType::Ref(ty.into()), + Type::FuncRef | Type::ExternRef | Type::TypedFuncRef(..) => { + wasm_encoder::ValType::Ref(ty.into()) + } } } } @@ -97,6 +132,7 @@ impl From for wasm_encoder::RefType { fn from(ty: Type) -> wasm_encoder::RefType { match ty { Type::FuncRef => wasm_encoder::RefType::FUNCREF, + Type::ExternRef => wasm_encoder::RefType::EXTERNREF, Type::TypedFuncRef(nullable, idx) => wasm_encoder::RefType { nullable, heap_type: wasm_encoder::HeapType::Concrete(idx), diff --git a/src/ir/module.rs b/src/ir/module.rs index 5854561..880fed8 100644 --- a/src/ir/module.rs +++ b/src/ir/module.rs @@ -4,9 +4,10 @@ use super::{ }; use crate::entity::{EntityRef, EntityVec}; use crate::ir::{Debug, DebugMap, FunctionBody}; -use crate::{backend, frontend}; +use crate::{backend, frontend, FrontendError}; use anyhow::Result; use std::collections::BTreeMap; +use std::convert::{TryFrom, TryInto}; pub use crate::frontend::FrontendOptions; @@ -225,25 +226,29 @@ pub struct GlobalData { pub mutable: bool, } -impl From<&wasmparser::FuncType> for SignatureData { - fn from(fty: &wasmparser::FuncType) -> Self { - Self { +impl TryFrom<&wasmparser::FuncType> for SignatureData { + type Error = FrontendError; + + fn try_from(fty: &wasmparser::FuncType) -> Result { + Ok(Self { params: fty .params() .iter() - .map(|&ty| ty.into()) - .collect::>(), + .map(|&ty| ty.try_into()) + .collect::, _>>()?, returns: fty .results() .iter() - .map(|&ty| ty.into()) - .collect::>(), - } + .map(|&ty| ty.try_into()) + .collect::, _>>()?, + }) } } -impl From for SignatureData { - fn from(fty: wasmparser::FuncType) -> Self { - (&fty).into() +impl TryFrom for SignatureData { + type Error = FrontendError; + + fn try_from(fty: wasmparser::FuncType) -> Result { + (&fty).try_into() } } diff --git a/src/ops.rs b/src/ops.rs index 0e78d3b..23adfb4 100644 --- a/src/ops.rs +++ b/src/ops.rs @@ -15,7 +15,7 @@ //! control flow (these become `Terminator` instructions). use crate::{entity::EntityRef, Func, Global, Memory, Signature, Table, Type}; -use std::convert::TryFrom; +use std::convert::{TryFrom, TryInto}; pub use wasmparser::{Ieee32, Ieee64}; /// An argument to a memory load or store, specifying which memory, @@ -695,9 +695,9 @@ impl<'a, 'b> std::convert::TryFrom<&'b wasmparser::Operator<'a>> for Operator { &wasmparser::Operator::LocalTee { .. } => Err(()), &wasmparser::Operator::LocalGet { .. } => Err(()), &wasmparser::Operator::Select => Ok(Operator::Select), - &wasmparser::Operator::TypedSelect { ty } => { - Ok(Operator::TypedSelect { ty: ty.into() }) - } + &wasmparser::Operator::TypedSelect { ty } => Ok(Operator::TypedSelect { + ty: ty.try_into().map_err(|_| ())?, + }), &wasmparser::Operator::GlobalGet { global_index } => Ok(Operator::GlobalGet { global_index: Global::from(global_index), }), diff --git a/tests/reference_types.rs b/tests/reference_types.rs new file mode 100644 index 0000000..67eb357 --- /dev/null +++ b/tests/reference_types.rs @@ -0,0 +1,46 @@ +//! Tests for the reference types that the IR represents and the ones +//! the frontend rejects. + +use waffle::wasmparser::Validator; +use waffle::{FrontendError, FrontendOptions, Module}; + +#[test] +fn externref_is_preserved() { + let bytes = wat::parse_str("(module (func (result externref) (ref.null extern)))").unwrap(); + let module = Module::from_wasm_bytes(&bytes, &FrontendOptions::default()).unwrap(); + Validator::new() + .validate_all(&module.to_wasm_bytes().unwrap()) + .unwrap(); +} + +/// Parses `wat` and expands every function body, and asserts that one of +/// the two steps returns `FrontendError::UnsupportedFeature`. +fn assert_unsupported(wat: &str) { + let bytes = wat::parse_str(wat).unwrap(); + let result = Module::from_wasm_bytes(&bytes, &FrontendOptions::default()) + .and_then(|mut module| module.expand_all_funcs()); + let err = result + .err() + .unwrap_or_else(|| panic!("module was accepted: {}", wat)); + assert!( + matches!( + err.downcast_ref::(), + Some(FrontendError::UnsupportedFeature(_)) + ), + "unexpected error for {}: {:?}", + wat, + err + ); +} + +#[test] +fn unrepresentable_reference_types_are_unsupported() { + assert_unsupported("(module (type (shared (func))))"); + assert_unsupported("(module (func (param (ref func))))"); + assert_unsupported("(module (func (param (ref extern))))"); + assert_unsupported("(module (table 1 anyref))"); + assert_unsupported("(module (import \"\" \"\" (global nullfuncref)))"); + assert_unsupported("(module (func (local i31ref)))"); + assert_unsupported("(module (func (block (result exnref) (unreachable)) (drop)))"); + assert_unsupported("(module (func (drop (ref.null any))))"); +} From 9b2cf4d1af02566670da7e7e7b7c8f3007824c60 Mon Sep 17 00:00:00 2001 From: Till Schneidereit Date: Wed, 11 Nov 2026 14:52:34 +0100 Subject: [PATCH 2/5] Ops: translate ref.null with an abstract heap type. `Operator::RefNull` held a signature index, and `Operator::try_from` converted `ref.null` only with a concrete type index. Expanding a body with `ref.null func` or `ref.null extern` panicked in the frontend because the conversion failed. `Operator::RefNull` now holds its result type: `Type::FuncRef`, `Type::ExternRef`, or a nullable `Type::TypedFuncRef`. `ref.null` converts with any heap type that converts to one of these, and the backend encodes the heap type of the result type. Other heap types return `FrontendError::UnsupportedFeature`. --- src/backend/mod.rs | 4 ++-- src/op_traits.rs | 6 ++---- src/ops.rs | 15 +++++++++------ tests/roundtrip/ref-null-abstract.wat | 2 ++ 4 files changed, 15 insertions(+), 12 deletions(-) create mode 100644 tests/roundtrip/ref-null-abstract.wat diff --git a/src/backend/mod.rs b/src/backend/mod.rs index 8854253..33d8f2b 100644 --- a/src/backend/mod.rs +++ b/src/backend/mod.rs @@ -1006,8 +1006,8 @@ impl<'a> WasmFuncBackend<'a> { Some(wasm_encoder::Instruction::CallRef(sig_index.index() as u32)) } Operator::RefIsNull => Some(wasm_encoder::Instruction::RefIsNull), - Operator::RefNull { sig_index } => Some(wasm_encoder::Instruction::RefNull( - wasm_encoder::HeapType::Concrete(sig_index.index() as u32), + Operator::RefNull { ty } => Some(wasm_encoder::Instruction::RefNull( + wasm_encoder::RefType::from(*ty).heap_type, )), Operator::RefFunc { func_index } => { Some(wasm_encoder::Instruction::RefFunc(func_index.index() as u32)) diff --git a/src/op_traits.rs b/src/op_traits.rs index 9d70a70..b5bbc8b 100644 --- a/src/op_traits.rs +++ b/src/op_traits.rs @@ -956,9 +956,7 @@ pub fn op_outputs( Ok(Vec::from(module.signatures[*sig_index].returns.clone()).into()) } Operator::RefIsNull => Ok(Cow::Borrowed(&[Type::I32])), - Operator::RefNull { sig_index } => { - Ok(vec![Type::TypedFuncRef(true, sig_index.index() as u32)].into()) - } + Operator::RefNull { ty } => Ok(vec![*ty].into()), Operator::RefFunc { func_index } => { let ty = module.funcs[*func_index].sig(); Ok(vec![Type::TypedFuncRef(true, ty.index() as u32)].into()) @@ -2078,7 +2076,7 @@ impl std::fmt::Display for Operator { Operator::CallRef { sig_index } => write!(f, "call_ref<{}>", sig_index)?, Operator::RefIsNull => write!(f, "ref_is_null")?, - Operator::RefNull { sig_index } => write!(f, "ref_null<{}>", sig_index)?, + Operator::RefNull { ty } => write!(f, "ref_null<{}>", ty)?, Operator::RefFunc { func_index } => write!(f, "ref_func<{}>", func_index)?, } diff --git a/src/ops.rs b/src/ops.rs index 23adfb4..3e8a30c 100644 --- a/src/ops.rs +++ b/src/ops.rs @@ -660,8 +660,10 @@ pub enum Operator { sig_index: Signature, }, RefIsNull, + /// `ty` is the result type: `FuncRef`, `ExternRef`, or a nullable + /// `TypedFuncRef`. RefNull { - sig_index: Signature, + ty: Type, }, RefFunc { func_index: Func, @@ -1306,11 +1308,12 @@ impl<'a, 'b> std::convert::TryFrom<&'b wasmparser::Operator<'a>> for Operator { sig_index: Signature::from(type_index), }), &wasmparser::Operator::RefIsNull => Ok(Operator::RefIsNull), - &wasmparser::Operator::RefNull { - hty: wasmparser::HeapType::Concrete(wasmparser::UnpackedIndex::Module(sig)), - } => Ok(Operator::RefNull { - sig_index: Signature::from(sig), - }), + &wasmparser::Operator::RefNull { hty } => { + let ty = wasmparser::RefType::new(true, hty).ok_or(())?; + Ok(Operator::RefNull { + ty: ty.try_into().map_err(|_| ())?, + }) + } &wasmparser::Operator::RefFunc { function_index } => Ok(Operator::RefFunc { func_index: Func::from(function_index), }), diff --git a/tests/roundtrip/ref-null-abstract.wat b/tests/roundtrip/ref-null-abstract.wat new file mode 100644 index 0000000..be78b44 --- /dev/null +++ b/tests/roundtrip/ref-null-abstract.wat @@ -0,0 +1,2 @@ +(module + (func (result externref) (ref.null extern))) From 18d9504dbdee5f1a3d17221bdbd47e946bc3bca7 Mon Sep 17 00:00:00 2001 From: Till Schneidereit Date: Wed, 11 Nov 2026 15:15:08 +0100 Subject: [PATCH 3/5] Frontend: give nullable reference locals a ref.null default value. `LocalTracker::create_default_value` produced a zero constant for numeric and vector types and hit `todo!` for every reference type, so expanding a body that read a `funcref` local before setting it panicked. Nullable reference types (`Type::FuncRef`, `Type::ExternRef` and a nullable `Type::TypedFuncRef`) now default to a `ref.null` of that type. Non-nullable typed function references still hit `todo!`. Validation requires every read of a non-nullable local to follow a set of that local. The backend's global initializer had the same gap: a defined global with no value emitted `ref.null` only for a nullable `Type::TypedFuncRef` and hit `unimplemented!` for `Type::FuncRef`. It now emits `ref.null` for all three nullable reference types. --- src/backend/mod.rs | 5 ++--- src/frontend.rs | 5 ++++- tests/reference_types.rs | 16 +++++++++++++++- tests/roundtrip/ref-local-defaults.wat | 5 +++++ 4 files changed, 26 insertions(+), 5 deletions(-) create mode 100644 tests/roundtrip/ref-local-defaults.wat diff --git a/src/backend/mod.rs b/src/backend/mod.rs index 33d8f2b..fd3c131 100644 --- a/src/backend/mod.rs +++ b/src/backend/mod.rs @@ -1643,9 +1643,8 @@ fn const_init(ty: Type, value: Option) -> wasm_encoder::ConstExpr { Type::I64 => wasm_encoder::ConstExpr::i64_const(bits as i64), Type::F32 => wasm_encoder::ConstExpr::f32_const(f32::from_bits(bits as u32).into()), Type::F64 => wasm_encoder::ConstExpr::f64_const(f64::from_bits(bits as u64).into()), - Type::TypedFuncRef(true, sig) if bits == 0 => { - let hty = wasm_encoder::HeapType::Concrete(sig); - wasm_encoder::ConstExpr::ref_null(hty) + Type::FuncRef | Type::ExternRef | Type::TypedFuncRef(true, _) if bits == 0 => { + wasm_encoder::ConstExpr::ref_null(wasm_encoder::RefType::from(ty).heap_type) } _ => unimplemented!(), } diff --git a/src/frontend.rs b/src/frontend.rs index 8ee1bcc..cc5fff3 100644 --- a/src/frontend.rs +++ b/src/frontend.rs @@ -906,7 +906,10 @@ impl LocalTracker { Type::F32 => body.add_op(at_block, Operator::F32Const { value: 0 }, &[], &[ty]), Type::F64 => body.add_op(at_block, Operator::F64Const { value: 0 }, &[], &[ty]), Type::V128 => body.add_op(at_block, Operator::V128Const { value: 0 }, &[], &[ty]), - _ => todo!("unsupported type: {:?}", ty), + Type::FuncRef | Type::ExternRef | Type::TypedFuncRef(true, _) => { + body.add_op(at_block, Operator::RefNull { ty }, &[], &[ty]) + } + Type::TypedFuncRef(false, _) => todo!("unsupported type: {:?}", ty), }; log::trace!( "created default value {} of type {} at block {}", diff --git a/tests/reference_types.rs b/tests/reference_types.rs index 67eb357..fad609e 100644 --- a/tests/reference_types.rs +++ b/tests/reference_types.rs @@ -2,7 +2,7 @@ //! the frontend rejects. use waffle::wasmparser::Validator; -use waffle::{FrontendError, FrontendOptions, Module}; +use waffle::{FrontendError, FrontendOptions, GlobalData, Module, Type}; #[test] fn externref_is_preserved() { @@ -13,6 +13,20 @@ fn externref_is_preserved() { .unwrap(); } +#[test] +fn nullable_reference_globals_without_a_value_are_null() { + let mut module = Module::empty(); + for ty in [Type::FuncRef, Type::ExternRef] { + module.globals.push(GlobalData { + ty, + value: None, + mutable: false, + }); + } + let bytes = module.to_wasm_bytes().unwrap(); + Validator::new().validate_all(&bytes).unwrap(); +} + /// Parses `wat` and expands every function body, and asserts that one of /// the two steps returns `FrontendError::UnsupportedFeature`. fn assert_unsupported(wat: &str) { diff --git a/tests/roundtrip/ref-local-defaults.wat b/tests/roundtrip/ref-local-defaults.wat new file mode 100644 index 0000000..79d357a --- /dev/null +++ b/tests/roundtrip/ref-local-defaults.wat @@ -0,0 +1,5 @@ +(module + (type $t (func)) + (func (local funcref) (drop (local.get 0))) + (func (result externref) (local externref) (local.get 0)) + (func (result (ref null $t)) (local (ref null $t)) (local.get 0))) From 0f80e43a5db33ba1040d0a403d638e26756949bc Mon Sep 17 00:00:00 2001 From: Till Schneidereit Date: Wed, 11 Nov 2026 15:34:03 +0100 Subject: [PATCH 4/5] Frontend: accept reference operands whose type is a subtype of the expected type. The frontend checked each operand type against the type the operator expects with `assert_eq!`. A valid module panicked when an operand's type was a proper subtype of the expected type: a non-nullable `(ref $t)` passed to `call_ref $t`, which expects `(ref null $t)`, or the `(ref null $t)` result of `ref.func` passed to `table.set`, `global.set` or `call` where `funcref` is expected. Add `Type::is_subtype_of` and use it for the operand check. A typed function reference is a subtype of `funcref`. It is also a subtype of a typed function reference with the same signature index, unless it is nullable and the other is not. Signature indices are compared by index. --- src/frontend.rs | 7 ++++++- src/ir.rs | 18 ++++++++++++++++++ tests/roundtrip/ref-operand-subtyping.wat | 12 ++++++++++++ 3 files changed, 36 insertions(+), 1 deletion(-) create mode 100644 tests/roundtrip/ref-operand-subtyping.wat diff --git a/src/frontend.rs b/src/frontend.rs index cc5fff3..86a8254 100644 --- a/src/frontend.rs +++ b/src/frontend.rs @@ -2168,7 +2168,12 @@ impl<'a, 'b> FunctionBodyBuilder<'a, 'b> { let args = &mut self.body.arg_pool[input_operands]; for (i, &input) in inputs.into_iter().enumerate().rev() { let (stack_top_ty, stack_top) = self.op_stack.pop().unwrap(); - assert_eq!(stack_top_ty, input); + assert!( + stack_top_ty.is_subtype_of(input), + "operand type {} is not a subtype of {}", + stack_top_ty, + input + ); args[i] = stack_top; } log::trace!(" -> operands: {:?}", input_operands); diff --git a/src/ir.rs b/src/ir.rs index d759085..d03bde1 100644 --- a/src/ir.rs +++ b/src/ir.rs @@ -142,6 +142,24 @@ impl From for wasm_encoder::RefType { } } +impl Type { + /// Returns `true` if a value of type `self` is valid where a value of + /// type `other` is expected: the types are equal, `self` is a typed + /// function reference and `other` is `FuncRef`, or both are typed + /// function references with the same signature index and `other` is + /// nullable or `self` is not. Signature indices are compared by + /// index, not by the signatures they refer to. + pub(crate) fn is_subtype_of(self, other: Type) -> bool { + match (self, other) { + (Type::TypedFuncRef(..), Type::FuncRef) => true, + (Type::TypedFuncRef(sub_nullable, sub_sig), Type::TypedFuncRef(nullable, sig)) => { + sub_sig == sig && (nullable || !sub_nullable) + } + _ => self == other, + } + } +} + // Per-module index spaces: // A signature (list of parameter types and list of return types) in diff --git a/tests/roundtrip/ref-operand-subtyping.wat b/tests/roundtrip/ref-operand-subtyping.wat new file mode 100644 index 0000000..d4cb457 --- /dev/null +++ b/tests/roundtrip/ref-operand-subtyping.wat @@ -0,0 +1,12 @@ +(module + (type $t (func)) + (table 1 funcref) + (elem (i32.const 0) func $f) + + (func $f (type $t)) + + (func $call-non-nullable (param (ref $t)) + (call_ref $t (local.get 0))) + + (func $funcref-operand + (table.set (i32.const 0) (ref.func $f)))) From e1c8317dca927c1ad3fea660c6547c198f68bdae Mon Sep 17 00:00:00 2001 From: Till Schneidereit Date: Wed, 11 Nov 2026 15:34:03 +0100 Subject: [PATCH 5/5] Backend: accept block arguments whose type is a subtype of the parameter type. The backend asserted that each block argument has exactly the type of the block parameter it is passed to. The frontend creates the parameters of a join block with the declared types of the locals, so a `funcref` local that is assigned the result of `ref.func` on one path passes a `(ref null $t)` argument to a `funcref` parameter, and the backend panicked. Check the argument type with `Type::is_subtype_of` instead. --- src/backend/mod.rs | 7 ++++++- tests/roundtrip/ref-block-param-subtyping.wat | 5 +++++ 2 files changed, 11 insertions(+), 1 deletion(-) create mode 100644 tests/roundtrip/ref-block-param-subtyping.wat diff --git a/src/backend/mod.rs b/src/backend/mod.rs index fd3c131..4549c4e 100644 --- a/src/backend/mod.rs +++ b/src/backend/mod.rs @@ -216,7 +216,12 @@ impl<'a> WasmFuncBackend<'a> { let from_ty = self.body.values[self.body.resolve_alias(from)] .ty(&self.body.type_pool) .unwrap(); - assert_eq!(from_ty, to_ty); + assert!( + from_ty.is_subtype_of(to_ty), + "block argument type {} is not a subtype of {}", + from_ty, + to_ty + ); if ctx.locals.values[from].len() == 1 { assert_eq!(from_ty, ctx.locals.locals[ctx.locals.values[from][0]]); } diff --git a/tests/roundtrip/ref-block-param-subtyping.wat b/tests/roundtrip/ref-block-param-subtyping.wat new file mode 100644 index 0000000..27a7abc --- /dev/null +++ b/tests/roundtrip/ref-block-param-subtyping.wat @@ -0,0 +1,5 @@ +(module + (func $f (export "f") (param funcref i32) (result i32) + (if (local.get 1) + (then (local.set 0 (ref.func $f)))) + (ref.is_null (local.get 0))))