diff options
Diffstat (limited to 'crates/types')
| -rw-r--r-- | crates/types/README.md | 4 | ||||
| -rw-r--r-- | crates/types/src/instructions.rs | 14 | ||||
| -rw-r--r-- | crates/types/src/lib.rs | 92 | ||||
| -rw-r--r-- | crates/types/src/reference.rs | 255 | ||||
| -rw-r--r-- | crates/types/src/value.rs | 163 |
5 files changed, 394 insertions, 134 deletions
diff --git a/crates/types/README.md b/crates/types/README.md index 315a340..ed5a641 100644 --- a/crates/types/README.md +++ b/crates/types/README.md @@ -3,3 +3,7 @@ This crate contains the shared module, instruction, value, and archive types used by [`tinywasm`](https://crates.io/crates/tinywasm) and [`tinywasm-parser`](https://crates.io/crates/tinywasm-parser). Most users should depend on `tinywasm` directly. This crate is useful when you need to work with parsed modules, serialized `twasm` archives, or shared type definitions without pulling in the runtime. + +## API stability + +`tinywasm-types` is semver-exempt and may make breaking API changes in any release. Types re-exported by `tinywasm` remain covered by `tinywasm`'s compatibility policy when used through that crate. diff --git a/crates/types/src/instructions.rs b/crates/types/src/instructions.rs index cec9d5b..a53576e 100644 --- a/crates/types/src/instructions.rs +++ b/crates/types/src/instructions.rs @@ -1,5 +1,5 @@ -use super::{FuncAddr, GlobalAddr, LocalAddr, TableAddr, TypeAddr, ValueCounts, WasmType}; -use crate::{ConstIdx, DataAddr, ElemAddr, ExternAddr, MemAddr}; +use super::{FuncAddr, GlobalAddr, LocalAddr, TableAddr, TypeAddr, ValueCounts}; +use crate::{ConstIdx, DataAddr, ElemAddr, MemAddr, RefType, RefValue}; /// Represents a memory immediate in a WebAssembly memory instruction. #[derive(Copy, Clone, PartialEq, Eq)] @@ -53,8 +53,7 @@ pub enum ConstInstruction { F64Const(f64), V128Const([u8; 16]), GlobalGet(GlobalAddr), - RefFunc(Option<FuncAddr>), - RefExtern(Option<ExternAddr>), + Ref(RefValue), I32Add, I32Sub, I32Mul, @@ -195,6 +194,8 @@ pub enum Instruction { JumpIfNonZero32(u32), JumpIfZero64(u32), JumpIfNonZero64(u32), + JumpIfRefNull(u32), + JumpIfRefNonNull(u32), JumpIfLocalZero32 { target_ip: u32, local: LocalAddr }, JumpIfLocalNonZero32 { target_ip: u32, local: LocalAddr }, JumpIfLocalZero64 { target_ip: u32, local: LocalAddr }, @@ -215,9 +216,11 @@ pub enum Instruction { Call(FuncAddr), CallSelf, CallIndirect(TypeAddr, TableAddr), + CallRef(TypeAddr), ReturnCall(FuncAddr), ReturnCallSelf, ReturnCallIndirect(TypeAddr, TableAddr), + ReturnCallRef(TypeAddr), // > Parametric Instructions // See <https://webassembly.github.io/spec/core/binary/instructions.html#parametric-instructions> @@ -265,9 +268,10 @@ pub enum Instruction { Const64(i64), // > Reference Types - RefNull(WasmType), + RefNull(RefType), RefFunc(FuncAddr), RefIsNull, + RefAsNonNull, // > Numeric Instructions // See <https://webassembly.github.io/spec/core/binary/instructions.html#numeric-instructions> diff --git a/crates/types/src/lib.rs b/crates/types/src/lib.rs index 0b4b54c..0b15927 100644 --- a/crates/types/src/lib.rs +++ b/crates/types/src/lib.rs @@ -84,10 +84,10 @@ pub struct ModuleInner { /// A vector of type definitions, indexed by `TypeAddr` /// /// Corresponds to the `type` section of the original WebAssembly module. - pub func_types: Arc<[Arc<FuncType>]>, + pub func_types: Box<[FuncType]>, /// Function index to type index mapping in module index space, including imports. - pub func_type_idxs: Arc<[u32]>, + pub func_type_idxs: Box<[TypeAddr]>, /// Exported items of the WebAssembly module. /// @@ -102,7 +102,7 @@ pub struct ModuleInner { /// Table components of the WebAssembly module used to initialize tables. /// /// Corresponds to the `table` section of the original WebAssembly module. - pub table_types: Box<[TableType]>, + pub tables: Box<[TableDefinition]>, /// Memory components of the WebAssembly module used to initialize memories. /// @@ -193,7 +193,8 @@ impl Module { if idx < imported_funcs { imported_type(&self.0, ExternalKind::Func, idx)? } else { - ExportType::Func(&self.0.funcs.get(idx - imported_funcs)?.ty) + let type_idx = *self.0.func_type_idxs.get(idx)?; + ExportType::Func(self.0.func_types.get(type_idx as usize)?) } } ExternalKind::Table => { @@ -201,7 +202,7 @@ impl Module { if idx < imported_tables { imported_type(&self.0, ExternalKind::Table, idx)? } else { - ExportType::Table(self.0.table_types.get(idx - imported_tables)?) + ExportType::Table(&self.0.tables.get(idx - imported_tables)?.ty) } } ExternalKind::Memory => { @@ -318,9 +319,12 @@ pub type ExternAddr = Addr; pub type ConstIdx = Addr; // additional internal addresses +/// An address in the current type space. +/// +/// Parsed modules use module-local addresses; instantiated types use their store's canonical addresses. pub type TypeAddr = Addr; pub type LocalAddr = u16; // there can't be more than 50.000 locals in a function -pub type ModuleInstanceAddr = Addr; +pub type ModuleInstanceId = Addr; /// A WebAssembly External Value. /// @@ -383,6 +387,61 @@ impl FuncType { pub fn results(&self) -> &[WasmType] { &self.data[self.param_count as usize..] } + + /// Compare function types while resolving concrete references in their respective type spaces. + pub fn equivalent(&self, types: &[FuncType], other: &Self, other_types: &[FuncType]) -> bool { + fn refs_equal( + left_types: &[FuncType], + left: RefType, + right_types: &[FuncType], + right: RefType, + visited: &mut alloc::vec::Vec<(u32, u32)>, + ) -> bool { + if left.is_nullable() != right.is_nullable() { + return false; + } + match (left.type_index(), right.type_index()) { + (Some(left_idx), Some(right_idx)) => { + if visited.contains(&(left_idx, right_idx)) { + return true; + } + let (Some(left), Some(right)) = + (left_types.get(left_idx as usize), right_types.get(right_idx as usize)) + else { + return false; + }; + visited.push((left_idx, right_idx)); + funcs_equal(left, left_types, right, right_types, visited) + } + (None, None) => left.abstract_heap_type() == right.abstract_heap_type(), + _ => false, + } + } + + fn funcs_equal( + left: &FuncType, + left_types: &[FuncType], + right: &FuncType, + right_types: &[FuncType], + visited: &mut alloc::vec::Vec<(u32, u32)>, + ) -> bool { + left.params().len() == right.params().len() + && left.results().len() == right.results().len() + && left.params().iter().chain(left.results()).zip(right.params().iter().chain(right.results())).all( + |(&left, &right)| match (left, right) { + (WasmType::Ref(left), WasmType::Ref(right)) => { + refs_equal(left_types, left, right_types, right, visited) + } + _ => left == right, + }, + ) + } + + if core::ptr::eq(types, other_types) && self == other { + return true; + } + funcs_equal(self, types, other, other_types, &mut alloc::vec::Vec::new()) + } } #[derive(Default, Clone, Copy, PartialEq, Eq)] @@ -408,7 +467,7 @@ impl<'a> FromIterator<&'a WasmType> for ValueCounts { for ty in iter { match ty { - WasmType::I32 | WasmType::F32 | WasmType::RefExtern | WasmType::RefFunc => counts.c32 += 1, + WasmType::I32 | WasmType::F32 | WasmType::Ref(_) => counts.c32 += 1, WasmType::I64 | WasmType::F64 => counts.c64 += 1, WasmType::V128 => counts.c128 += 1, } @@ -426,7 +485,6 @@ pub struct WasmFunction { pub locals: ValueCounts, pub params: ValueCounts, pub results: ValueCounts, - pub ty: Arc<FuncType>, } #[derive(Clone, PartialEq, Eq, Default)] @@ -504,23 +562,31 @@ impl Default for GlobalType { #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] pub struct TableType { arch: MemoryArch, - pub element_type: WasmType, + pub element_type: RefType, pub size_initial: u64, pub size_max: Option<u64>, } +#[derive(Clone, PartialEq)] +#[cfg_attr(feature = "debug", derive(Debug))] +#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] +pub struct TableDefinition { + pub ty: TableType, + pub init: Option<Box<[ConstInstruction]>>, +} + impl TableType { pub const fn empty() -> Self { - Self::new(WasmType::RefFunc, 0, None) + Self::new(RefType::FUNCREF, 0, None) } /// Create a table with 32-bit indices. - pub const fn new(element_type: WasmType, size_initial: u64, size_max: Option<u64>) -> Self { + pub const fn new(element_type: RefType, size_initial: u64, size_max: Option<u64>) -> Self { Self { arch: MemoryArch::I32, element_type, size_initial, size_max } } /// Create a table with 64-bit indices. - pub const fn new64(element_type: WasmType, size_initial: u64, size_max: Option<u64>) -> Self { + pub const fn new64(element_type: RefType, size_initial: u64, size_max: Option<u64>) -> Self { Self { arch: MemoryArch::I64, element_type, size_initial, size_max } } @@ -675,7 +741,7 @@ pub struct Element { pub kind: ElementKind, pub items: Box<[ElementItem]>, pub range: Range<usize>, - pub ty: WasmType, + pub ty: RefType, } #[derive(Clone, PartialEq)] diff --git a/crates/types/src/reference.rs b/crates/types/src/reference.rs index 7970dc8..ee66965 100644 --- a/crates/types/src/reference.rs +++ b/crates/types/src/reference.rs @@ -1,112 +1,255 @@ -use crate::{ExternAddr, FuncAddr}; +/// An abstract WebAssembly heap type. +/// +/// This contains exactly the abstract heap types in core Wasm 3.0. +#[repr(u8)] +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "debug", derive(Debug))] +#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] +pub enum AbstractHeapType { + Any, + Eq, + I31, + Struct, + Array, + None, -const NULL_REF: u32 = u32::MAX; + Func, + NoFunc, -#[derive(Clone, Copy, PartialEq, Eq)] -pub struct ExternRef(u32); + Exn, + NoExn, -#[derive(Clone, Copy, PartialEq, Eq)] -pub struct FuncRef(u32); + Extern, + NoExtern, +} + +/// A WebAssembly reference type. +/// +/// Packed as: +/// +/// ```text +/// [nullable:1 concrete:1 payload:30] +/// ``` +/// +/// For concrete types, `payload` is a module type index. +/// Otherwise, it is an [`AbstractHeapType`]. +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] +pub struct RefType(u32); #[cfg(feature = "debug")] -impl core::fmt::Debug for ExternRef { +impl core::fmt::Debug for RefType { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - match self.addr() { - Some(addr) => write!(f, "extern({addr:?})"), - None => write!(f, "extern(null)"), + if self.is_concrete() { + write!(f, "concrete({})", self.type_index().unwrap()) + } else { + write!(f, "abstract({:?})", self.abstract_heap_type().unwrap()) } } } -#[cfg(feature = "debug")] -impl core::fmt::Debug for FuncRef { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - match self.addr() { - Some(addr) => write!(f, "func({addr:?})"), - None => write!(f, "func(null)"), +impl RefType { + const NULLABLE: u32 = 1 << 31; + const CONCRETE: u32 = 1 << 30; + const PAYLOAD_MASK: u32 = Self::CONCRETE - 1; + + pub const FUNCREF: Self = Self::new_abstract(true, AbstractHeapType::Func); + pub const EXTERNREF: Self = Self::new_abstract(true, AbstractHeapType::Extern); + pub const EXNREF: Self = Self::new_abstract(true, AbstractHeapType::Exn); + + #[inline] + pub const fn new_abstract(nullable: bool, heap_type: AbstractHeapType) -> Self { + Self((nullable as u32) << 31 | heap_type as u32) + } + + #[inline] + pub const fn new_concrete(nullable: bool, type_index: u32) -> Option<Self> { + if type_index <= Self::PAYLOAD_MASK { + Some(Self(((nullable as u32) << 31) | Self::CONCRETE | type_index)) + } else { + None } } -} -impl FuncRef { #[inline] - /// Create a new [`FuncRef`] from a [`FuncAddr`]. - pub const fn new(addr: Option<FuncAddr>) -> Self { - match addr { - Some(addr) => Self(addr), - None => Self::null(), + pub const fn is_nullable(self) -> bool { + self.0 & Self::NULLABLE != 0 + } + + #[inline] + pub const fn is_concrete(self) -> bool { + self.0 & Self::CONCRETE != 0 + } + + #[inline] + pub const fn type_index(self) -> Option<u32> { + if self.is_concrete() { Some(self.0 & Self::PAYLOAD_MASK) } else { None } + } + + #[inline] + pub const fn abstract_heap_type(self) -> Option<AbstractHeapType> { + if self.is_concrete() { + return None; + } + + match self.0 & Self::PAYLOAD_MASK { + 0 => Some(AbstractHeapType::Any), + 1 => Some(AbstractHeapType::Eq), + 2 => Some(AbstractHeapType::I31), + 3 => Some(AbstractHeapType::Struct), + 4 => Some(AbstractHeapType::Array), + 5 => Some(AbstractHeapType::None), + 6 => Some(AbstractHeapType::Func), + 7 => Some(AbstractHeapType::NoFunc), + 8 => Some(AbstractHeapType::Exn), + 9 => Some(AbstractHeapType::NoExn), + 10 => Some(AbstractHeapType::Extern), + 11 => Some(AbstractHeapType::NoExtern), + _ => None, } } #[inline] - /// Create a null [`FuncRef`]. - pub const fn null() -> Self { - Self(NULL_REF) + pub const fn with_nullability(self, nullable: bool) -> Self { + Self((self.0 & !Self::NULLABLE) | ((nullable as u32) << 31)) } #[inline] - /// Check if the [`FuncRef`] is null. - pub const fn is_null(&self) -> bool { - self.0 == NULL_REF + pub const fn is_func(self) -> bool { + // TODO(wasm3): Classify concrete refs from the module type definition once GC types are represented. + self.is_concrete() + || matches!(self.abstract_heap_type(), Some(AbstractHeapType::Func | AbstractHeapType::NoFunc)) } #[inline] - /// Get the [`FuncAddr`] from the [`FuncRef`]. - pub const fn addr(&self) -> Option<FuncAddr> { - if self.is_null() { None } else { Some(self.0) } + pub const fn is_extern(self) -> bool { + matches!(self.abstract_heap_type(), Some(AbstractHeapType::Extern | AbstractHeapType::NoExtern)) } #[inline] - #[doc(hidden)] - pub const fn from_raw(raw: u32) -> Self { - Self(raw) + pub const fn is_exn(self) -> bool { + matches!(self.abstract_heap_type(), Some(AbstractHeapType::Exn | AbstractHeapType::NoExn)) } +} +#[derive(Clone, Copy, PartialEq, Eq)] +#[cfg_attr(feature = "debug", derive(Debug))] +#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] +pub enum RefValue { + Null, + Func(FuncRef), + Extern(ExternRef), + Any(AnyRef), + Exn(ExnRef), +} + +impl RefValue { + /// Return the reference's raw representation, or `None` for null. + pub const fn raw(self) -> Option<u32> { + match self { + Self::Null => None, + Self::Func(value) => Some(value.addr()), + Self::Extern(value) => Some(value.addr()), + Self::Any(value) => Some(value.raw()), + Self::Exn(value) => Some(value.addr()), + } + } +} + +#[derive(Clone, Copy, PartialEq, Eq)] +#[cfg_attr(feature = "debug", derive(Debug))] +#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] +pub struct FuncRef(u32); + +impl FuncRef { #[inline] - #[doc(hidden)] - pub const fn raw(&self) -> u32 { + pub const fn new(addr: u32) -> Self { + Self(addr) + } + + #[inline] + pub const fn addr(self) -> u32 { self.0 } } +#[derive(Clone, Copy, PartialEq, Eq)] +#[cfg_attr(feature = "debug", derive(Debug))] +#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] +pub struct ExternRef(u32); + impl ExternRef { #[inline] - /// Create a new [`ExternRef`] from an [`ExternAddr`]. - /// Should only be used by the runtime. - pub const fn new(addr: Option<ExternAddr>) -> Self { - match addr { - Some(addr) => Self(addr), - None => Self::null(), - } + pub const fn new(addr: u32) -> Self { + Self(addr) } - /// Create a null [`ExternRef`]. #[inline] - pub const fn null() -> Self { - Self(NULL_REF) + pub const fn addr(self) -> u32 { + self.0 } +} + +#[derive(Clone, Copy, PartialEq, Eq)] +#[cfg_attr(feature = "debug", derive(Debug))] +#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] +pub struct ExnRef(u32); - /// Check if the [`ExternRef`] is null. +impl ExnRef { #[inline] - pub const fn is_null(&self) -> bool { - self.0 == NULL_REF + pub const fn new(addr: u32) -> Self { + Self(addr) } - /// Get the [`ExternAddr`] from the [`ExternRef`]. #[inline] - pub const fn addr(&self) -> Option<ExternAddr> { - if self.is_null() { None } else { Some(self.0) } + pub const fn addr(self) -> u32 { + self.0 } +} + +#[derive(Clone, Copy, PartialEq, Eq)] +#[cfg_attr(feature = "debug", derive(Debug))] +#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] +pub struct AnyRef(u32); + +impl AnyRef { + // Odd values are inline i31s. + // Even values are GC object handles. - #[inline] #[doc(hidden)] + #[inline] pub const fn from_raw(raw: u32) -> Self { Self(raw) } + pub const fn from_i31(value: i32) -> Option<Self> { + if value < -(1 << 30) || value >= (1 << 30) { + return None; + } + + Some(Self(((value as u32) << 1) | 1)) + } + + pub const fn as_i31(self) -> Option<i32> { + if self.0 & 1 == 1 { Some((self.0 as i32) >> 1) } else { None } + } + + pub const fn from_gc_addr(addr: u32) -> Option<Self> { + match addr.checked_add(1) { + Some(raw) => match raw.checked_mul(2) { + Some(raw) => Some(Self(raw)), + None => None, + }, + None => None, + } + } + + pub const fn gc_addr(self) -> Option<u32> { + if self.0 != 0 && self.0 & 1 == 0 { Some(self.0 / 2 - 1) } else { None } + } + #[inline] - #[doc(hidden)] - pub const fn raw(&self) -> u32 { + pub const fn raw(self) -> u32 { self.0 } } diff --git a/crates/types/src/value.rs b/crates/types/src/value.rs index 782cdb8..92c660b 100644 --- a/crates/types/src/value.rs +++ b/crates/types/src/value.rs @@ -1,6 +1,6 @@ use core::fmt::Debug; -use crate::{ConstInstruction, ExternRef, FuncRef}; +use crate::{ConstInstruction, RefType, RefValue}; /// A WebAssembly value. /// @@ -8,18 +8,64 @@ use crate::{ConstInstruction, ExternRef, FuncRef}; #[derive(Clone, Copy, PartialEq)] pub enum WasmValue { // Num types - /// A 32-bit integer. + /// A 32-bit integer I32(i32), - /// A 64-bit integer. + /// A 64-bit integer I64(i64), - /// A 32-bit float. + /// A 32-bit float F32(f32), - /// A 64-bit float. + /// A 64-bit float F64(f64), - // /// A 128-bit vector + /// A 128-bit vector V128([u8; 16]), - RefExtern(ExternRef), - RefFunc(FuncRef), + /// A reference type + Ref(RefValue), +} + +impl WasmValue { + /// Return this value's broad WebAssembly type. + /// + /// A null reference has no intrinsic heap type and returns `None`. + pub const fn ty(self) -> Option<WasmType> { + match self { + Self::I32(_) => Some(WasmType::I32), + Self::I64(_) => Some(WasmType::I64), + Self::F32(_) => Some(WasmType::F32), + Self::F64(_) => Some(WasmType::F64), + Self::V128(_) => Some(WasmType::V128), + Self::Ref(RefValue::Null) => None, + Self::Ref(RefValue::Func(_)) => Some(WasmType::Ref(RefType::FUNCREF)), + Self::Ref(RefValue::Extern(_)) => Some(WasmType::Ref(RefType::EXTERNREF)), + Self::Ref(RefValue::Exn(_)) => Some(WasmType::Ref(RefType::EXNREF)), + Self::Ref(RefValue::Any(_)) => { + Some(WasmType::Ref(RefType::new_abstract(true, crate::AbstractHeapType::Any))) + } + } + } + + #[inline] + pub const fn matches_type(self, ty: WasmType) -> bool { + // Concrete references require a store lookup; this method only classifies their broad heap type. + match (self, ty) { + (Self::I32(_), WasmType::I32) + | (Self::I64(_), WasmType::I64) + | (Self::F32(_), WasmType::F32) + | (Self::F64(_), WasmType::F64) + | (Self::V128(_), WasmType::V128) => true, + (Self::Ref(RefValue::Null), WasmType::Ref(ty)) => ty.is_nullable(), + (Self::Ref(RefValue::Func(_)), WasmType::Ref(ty)) => { + ty.is_concrete() || matches!(ty.abstract_heap_type(), Some(crate::AbstractHeapType::Func)) + } + (Self::Ref(RefValue::Extern(_)), WasmType::Ref(ty)) => { + matches!(ty.abstract_heap_type(), Some(crate::AbstractHeapType::Extern)) + } + (Self::Ref(RefValue::Exn(_)), WasmType::Ref(ty)) => { + matches!(ty.abstract_heap_type(), Some(crate::AbstractHeapType::Exn)) + } + (Self::Ref(RefValue::Any(_)), WasmType::Ref(ty)) => !ty.is_func() && !ty.is_extern() && !ty.is_exn(), + _ => false, + } + } } impl Debug for WasmValue { @@ -31,13 +77,9 @@ impl Debug for WasmValue { Self::F64(i) => write!(f, "f64({i})"), Self::V128(i) => write!(f, "v128({i:?})"), #[cfg(feature = "debug")] - Self::RefExtern(i) => write!(f, "ref({i:?})"), - #[cfg(feature = "debug")] - Self::RefFunc(i) => write!(f, "func({i:?})"), - #[cfg(not(feature = "debug"))] - Self::RefExtern(_) => write!(f, "ref()"), + Self::Ref(i) => write!(f, "ref({i:?})"), #[cfg(not(feature = "debug"))] - Self::RefFunc(_) => write!(f, "func()"), + Self::Ref(_) => write!(f, "ref(...)"), } } } @@ -52,22 +94,21 @@ impl WasmValue { Self::F32(i) => ConstInstruction::F32Const(*i), Self::F64(i) => ConstInstruction::F64Const(*i), Self::V128(i) => ConstInstruction::V128Const(*i), - Self::RefFunc(i) => ConstInstruction::RefFunc(i.addr()), - Self::RefExtern(i) => ConstInstruction::RefExtern(i.addr()), + Self::Ref(i) => ConstInstruction::Ref(*i), }]) } #[inline] /// Get the default value for a given type. - pub const fn default_for(ty: WasmType) -> Self { + pub const fn default_for(ty: WasmType) -> Option<Self> { match ty { - WasmType::I32 => Self::I32(0), - WasmType::I64 => Self::I64(0), - WasmType::F32 => Self::F32(0.0), - WasmType::F64 => Self::F64(0.0), - WasmType::V128 => Self::V128([0; 16]), - WasmType::RefFunc => Self::RefFunc(FuncRef::null()), - WasmType::RefExtern => Self::RefExtern(ExternRef::null()), + WasmType::I32 => Some(Self::I32(0)), + WasmType::I64 => Some(Self::I64(0)), + WasmType::F32 => Some(Self::F32(0.0)), + WasmType::F64 => Some(Self::F64(0.0)), + WasmType::V128 => Some(Self::V128([0; 16])), + WasmType::Ref(ty) if ty.is_nullable() => Some(Self::Ref(RefValue::Null)), + WasmType::Ref(_) => None, } } @@ -78,8 +119,7 @@ impl WasmValue { (Self::I32(a), Self::I32(b)) => a == b, (Self::I64(a), Self::I64(b)) => a == b, (Self::V128(a), Self::V128(b)) => a == b || Self::v128_nan_eq(*a, *b), - (Self::RefExtern(addr), Self::RefExtern(addr2)) => addr == addr2, - (Self::RefFunc(addr), Self::RefFunc(addr2)) => addr == addr2, + (Self::Ref(a), Self::Ref(b)) => a == b, (Self::F32(a), Self::F32(b)) => a.is_nan() && b.is_nan() || a.to_bits() == b.to_bits(), (Self::F64(a), Self::F64(b)) => a.is_nan() && b.is_nan() || a.to_bits() == b.to_bits(), _ => false, @@ -135,51 +175,28 @@ impl WasmValue { } } -impl From<&WasmValue> for WasmType { - #[inline] - fn from(value: &WasmValue) -> Self { - match value { - WasmValue::I32(_) => WasmType::I32, - WasmValue::I64(_) => WasmType::I64, - WasmValue::F32(_) => WasmType::F32, - WasmValue::F64(_) => WasmType::F64, - WasmValue::V128(_) => WasmType::V128, - WasmValue::RefExtern(_) => WasmType::RefExtern, - WasmValue::RefFunc(_) => WasmType::RefFunc, - } - } -} - -impl From<WasmValue> for WasmType { - #[inline] - fn from(value: WasmValue) -> Self { - Self::from(&value) - } -} - /// Type of a WebAssembly value. -#[derive(Clone, Copy, PartialEq, Eq, Debug)] +#[derive(Clone, Copy, PartialEq, Eq)] +#[cfg_attr(feature = "debug", derive(Debug))] #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] pub enum WasmType { - /// A 32-bit integer. + /// A 32-bit integer I32, - /// A 64-bit integer. + /// A 64-bit integer I64, - /// A 32-bit float. + /// A 32-bit float F32, - /// A 64-bit float. + /// A 64-bit float F64, /// A 128-bit vector V128, - /// A reference to a function. - RefFunc, - /// A reference to an external value. - RefExtern, + /// A reference type + Ref(RefType), } impl WasmType { #[inline] - pub const fn default_value(&self) -> WasmValue { + pub const fn default_value(&self) -> Option<WasmValue> { WasmValue::default_for(*self) } @@ -229,6 +246,32 @@ impl_conversion_for_wasmvalue! { f32 => F32, as_f32, "Return the `f32` from a `WasmValue`, if it is a `F32`."; f64 => F64, as_f64, "Return the `f64` from a `WasmValue`, if it is a `F64`."; [u8; 16] => V128, as_v128, "Return the raw little-endian bytes from a `WasmValue`, if it is a `V128`."; - ExternRef => RefExtern, as_ref_extern, "Return the [`ExternRef`] from a `WasmValue`, if it is one"; - FuncRef => RefFunc, as_ref_func, "Return the [`FuncRef`] from a `WasmValue`, if it is one"; + RefValue => Ref, as_ref, "Return the `RefValue` from a `WasmValue`, if it is a `Ref`."; +} + +macro_rules! impl_ref_conversion_for_wasmvalue { + ($($ty:ty => $variant:ident);* $(;)?) => { + $( + impl From<$ty> for WasmValue { + fn from(value: $ty) -> Self { + Self::Ref(RefValue::$variant(value)) + } + } + + impl TryFrom<WasmValue> for $ty { + type Error = (); + + fn try_from(value: WasmValue) -> Result<Self, Self::Error> { + if let WasmValue::Ref(RefValue::$variant(value)) = value { Ok(value) } else { Err(()) } + } + } + )* + }; +} + +impl_ref_conversion_for_wasmvalue! { + crate::FuncRef => Func; + crate::ExternRef => Extern; + crate::AnyRef => Any; + crate::ExnRef => Exn; } |
