summaryrefslogtreecommitdiff
path: root/crates/types
diff options
context:
space:
mode:
Diffstat (limited to 'crates/types')
-rw-r--r--crates/types/src/archive.rs42
-rw-r--r--crates/types/src/instructions.rs7
-rw-r--r--crates/types/src/lib.rs43
-rw-r--r--crates/types/src/reference.rs166
-rw-r--r--crates/types/src/types.rs24
-rw-r--r--crates/types/src/value.rs299
6 files changed, 123 insertions, 458 deletions
diff --git a/crates/types/src/archive.rs b/crates/types/src/archive.rs
index db40263..b568155 100644
--- a/crates/types/src/archive.rs
+++ b/crates/types/src/archive.rs
@@ -7,7 +7,7 @@ use crate::Module;
#[rustfmt::skip]
const TWASM_MAGIC: [u8; 16] = [ TWASM_MAGIC_PREFIX[0], TWASM_MAGIC_PREFIX[1], TWASM_MAGIC_PREFIX[2], TWASM_MAGIC_PREFIX[3], TWASM_VERSION[0], TWASM_VERSION[1], 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
const TWASM_MAGIC_PREFIX: &[u8; 4] = b"TWAS";
-const TWASM_VERSION: &[u8; 2] = b"05";
+const TWASM_VERSION: &[u8; 2] = b"06";
fn validate_magic(wasm: &[u8]) -> Result<usize, TwasmError> {
if wasm.len() < TWASM_MAGIC.len() || &wasm[..TWASM_MAGIC_PREFIX.len()] != TWASM_MAGIC_PREFIX {
@@ -64,7 +64,10 @@ impl Module {
#[cfg(test)]
mod tests {
use super::*;
- use crate::{Instruction, ModuleInner, V128Operand, WasmFunction};
+ use crate::{
+ AbstractHeapType, ConstInstruction, Global, GlobalType, Instruction, ModuleFuncIdx, ModuleInner, RefType,
+ V128Operand, WasmFunction, WasmType,
+ };
use crate::{OperandIdx, OperandType};
use alloc::{boxed::Box, sync::Arc, vec};
@@ -94,7 +97,7 @@ mod tests {
let module = Module::from(ModuleInner { funcs: Box::new([Arc::new(function)]), ..ModuleInner::default() });
let archive = module.serialize_twasm().expect("serialize archive");
- assert_eq!(&archive[..6], b"TWAS05");
+ assert_eq!(&archive[..6], b"TWAS06");
let decoded = Module::try_from_twasm(&archive).expect("deserialize archive");
let function = &decoded.funcs[0];
@@ -106,4 +109,37 @@ mod tests {
assert_eq!(index.get(&function.data).value, bytes);
}
}
+
+ #[test]
+ fn const_reference_expressions_round_trip_archive() {
+ let null_type = RefType::new_abstract(true, AbstractHeapType::Extern);
+ let module = Module::from(ModuleInner {
+ globals: vec![
+ Global {
+ ty: GlobalType::new(WasmType::Ref(null_type), false),
+ init: vec![ConstInstruction::RefNull(null_type)].into_boxed_slice(),
+ },
+ Global {
+ ty: GlobalType::new(WasmType::Ref(RefType::FUNCREF), false),
+ init: vec![ConstInstruction::RefFunc(ModuleFuncIdx::new(7))].into_boxed_slice(),
+ },
+ Global {
+ ty: GlobalType::new(WasmType::Ref(RefType::new_abstract(false, AbstractHeapType::I31)), false),
+ init: vec![ConstInstruction::I32Const(42), ConstInstruction::RefI31].into_boxed_slice(),
+ },
+ ]
+ .into_boxed_slice(),
+ ..ModuleInner::default()
+ });
+
+ let archive = module.serialize_twasm().expect("serialize archive");
+ let decoded = Module::try_from_twasm(&archive).expect("deserialize archive");
+
+ assert!(matches!(decoded.globals[0].init.as_ref(), [ConstInstruction::RefNull(ty)] if *ty == null_type));
+ assert!(matches!(
+ decoded.globals[1].init.as_ref(),
+ [ConstInstruction::RefFunc(index)] if index.index() == 7
+ ));
+ assert!(matches!(decoded.globals[2].init.as_ref(), [ConstInstruction::I32Const(42), ConstInstruction::RefI31]));
+ }
}
diff --git a/crates/types/src/instructions.rs b/crates/types/src/instructions.rs
index c9786d3..7e0cd28 100644
--- a/crates/types/src/instructions.rs
+++ b/crates/types/src/instructions.rs
@@ -2,7 +2,7 @@ use alloc::boxed::Box;
use super::{FuncAddr, GlobalAddr, LocalAddr, TableAddr, TagAddr, TypeAddr, ValueCounts};
use crate::operands::sealed;
-use crate::{DataAddr, ElemAddr, MemAddr, Operand64, Operand128, OperandIdx, OperandType, RefType, RefValue};
+use crate::{DataAddr, ElemAddr, MemAddr, ModuleFuncIdx, Operand64, Operand128, OperandIdx, OperandType, RefType};
/// Represents a memory immediate in a WebAssembly memory instruction.
#[derive(Copy, Clone, PartialEq, Eq)]
@@ -429,7 +429,8 @@ pub enum ConstInstruction {
GlobalGet64(GlobalAddr),
GlobalGet128(GlobalAddr),
GlobalGetRef(GlobalAddr),
- Ref(RefValue),
+ RefNull(RefType),
+ RefFunc(ModuleFuncIdx),
RefI31,
AnyConvertExtern,
ExternConvertAny,
@@ -535,8 +536,6 @@ pub enum BinOp128 {
/// These instructions are an internal, version-specific representation and do not
/// map one-to-one to WebAssembly instructions. Their variants and serialized form
/// may change between TinyWasm releases.
-///
-/// See <https://webassembly.github.io/spec/core/binary/instructions.html>
#[rustfmt::skip]
#[derive(Clone, Copy, PartialEq)]
#[cfg_attr(feature = "debug", derive(Debug))]
diff --git a/crates/types/src/lib.rs b/crates/types/src/lib.rs
index d1f7453..686433d 100644
--- a/crates/types/src/lib.rs
+++ b/crates/types/src/lib.rs
@@ -47,11 +47,12 @@ pub mod archive {
impl core::error::Error for TwasmError {}
}
-/// A `TinyWasm` WebAssembly Module
+/// TinyWasm's parsed and lowered representation of a WebAssembly module.
///
-/// This is the internal representation of a WebAssembly module in `TinyWasm`.
/// Modules produced by the parser are validated by default, but validation can be
/// disabled for trusted input. Do not trust modules or archives from third parties.
+///
+/// See <https://webassembly.github.io/spec/core/syntax/modules.html#syntax-module>
#[derive(Clone, Default, PartialEq)]
#[cfg_attr(feature = "debug", derive(Debug))]
#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
@@ -326,13 +327,35 @@ pub type TableAddr = Addr;
pub type MemAddr = Addr;
pub type GlobalAddr = Addr;
pub type TagAddr = Addr;
-pub type ExnAddr = Addr;
pub type ElemAddr = Addr;
pub type DataAddr = Addr;
pub type ExternAddr = Addr;
pub type ConstIdx = Addr;
// additional internal addresses
+/// A function index in a WebAssembly module's function index space.
+///
+/// This remains module-local until instantiation resolves it to a [`FuncAddr`].
+#[derive(Clone, Copy, PartialEq, Eq, Hash)]
+#[cfg_attr(feature = "debug", derive(Debug))]
+#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
+#[cfg_attr(feature = "archive", serde(transparent))]
+pub struct ModuleFuncIdx(u32);
+
+impl ModuleFuncIdx {
+ /// Creates a module-local function index.
+ #[inline]
+ pub const fn new(index: u32) -> Self {
+ Self(index)
+ }
+
+ /// Returns the module-local function index.
+ #[inline]
+ pub const fn index(self) -> u32 {
+ self.0
+ }
+}
+
/// An address in the current type space.
///
/// Parsed modules use module-local addresses; instantiated types use their store's canonical addresses.
@@ -484,6 +507,9 @@ pub struct Global {
pub init: Box<[ConstInstruction]>,
}
+/// A WebAssembly global type.
+///
+/// See <https://webassembly.github.io/spec/core/syntax/types.html#syntax-globaltype>
#[derive(Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "debug", derive(Debug))]
#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
@@ -517,6 +543,9 @@ impl Default for GlobalType {
}
}
+/// A WebAssembly table type.
+///
+/// See <https://webassembly.github.io/spec/core/syntax/types.html#syntax-tabletype>
#[derive(Copy, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "debug", derive(Debug))]
#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
@@ -556,7 +585,9 @@ impl TableType {
}
}
-/// Represents a memory's type.
+/// A WebAssembly memory type.
+///
+/// See <https://webassembly.github.io/spec/core/syntax/types.html#syntax-memtype>
#[derive(Copy, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "debug", derive(Debug))]
#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
@@ -597,7 +628,7 @@ impl MemoryType {
}
}
- /// The declared maximum page count, or `None` when the memory is unbounded.
+ /// Returns the declared maximum page count, or `None` if no maximum was declared.
#[inline]
pub const fn page_count_max_declared(&self) -> Option<u64> {
self.page_count_max
@@ -648,6 +679,8 @@ pub enum MemoryArch {
}
/// A WebAssembly tag type.
+///
+/// See <https://webassembly.github.io/spec/core/syntax/types.html#syntax-tagtype>
#[derive(Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "debug", derive(Debug))]
#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
diff --git a/crates/types/src/reference.rs b/crates/types/src/reference.rs
index ed59ae5..2d725ca 100644
--- a/crates/types/src/reference.rs
+++ b/crates/types/src/reference.rs
@@ -1,15 +1,8 @@
-const HOST_REF_TAG: u32 = 1 << 30;
-
-const fn encode_host_ref(addr: u32) -> Option<u32> {
- if addr >= HOST_REF_TAG - 1 {
- return None;
- }
- Some((addr | HOST_REF_TAG).wrapping_add(1).wrapping_mul(2))
-}
-
/// An abstract WebAssembly heap type.
///
/// This contains exactly the abstract heap types in core Wasm 3.0.
+///
+/// See <https://webassembly.github.io/spec/core/syntax/types.html#syntax-absheaptype>
#[repr(u8)]
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "debug", derive(Debug))]
@@ -43,6 +36,8 @@ pub enum AbstractHeapType {
/// For concrete types, `payload` is a module type index before instantiation
/// and a canonical store type address at runtime.
/// Otherwise, it is an [`AbstractHeapType`].
+///
+/// See <https://webassembly.github.io/spec/core/syntax/types.html#syntax-reftype>
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
pub struct RefType(u32);
@@ -148,156 +143,3 @@ impl RefType {
matches!(self.abstract_heap_type(), Some(AbstractHeapType::Exn | AbstractHeapType::NoExn))
}
}
-
-/// A host-facing WebAssembly reference value.
-#[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),
-}
-
-/// A reference to a function in a store.
-///
-/// The payload is the function's store-local address.
-#[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]
- pub const fn new(addr: u32) -> Self {
- Self(addr)
- }
-
- #[inline]
- pub const fn addr(self) -> u32 {
- self.0
- }
-}
-
-/// An opaque external reference.
-///
-/// Packed as `[payload:31 i31:1]`. Host addresses use the upper payload
-/// category, Store-managed objects use the lower category, and odd values
-/// contain an externalized i31.
-#[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]
- pub const fn new(addr: u32) -> Self {
- let Some(value) = Self::try_new(addr) else { panic!("external reference address is too large") };
- value
- }
-
- /// Creates an external reference when `addr` fits the runtime encoding.
- #[inline]
- pub const fn try_new(addr: u32) -> Option<Self> {
- match encode_host_ref(addr) {
- Some(encoded) => Some(Self(encoded)),
- None => None,
- }
- }
-
- #[doc(hidden)]
- #[inline]
- pub const fn from_raw(raw: u32) -> Self {
- Self(raw)
- }
-
- #[doc(hidden)]
- #[inline]
- pub const fn raw(self) -> u32 {
- self.0
- }
-}
-
-/// A reference to an exception in a store.
-///
-/// The payload is the exception's store-local address.
-#[derive(Clone, Copy, PartialEq, Eq)]
-#[cfg_attr(feature = "debug", derive(Debug))]
-#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
-pub struct ExnRef(u32);
-
-impl ExnRef {
- #[inline]
- pub const fn new(addr: u32) -> Self {
- Self(addr)
- }
-
- #[inline]
- pub const fn addr(self) -> u32 {
- self.0
- }
-}
-
-/// A WebAssembly `anyref` value.
-///
-/// Packed as:
-///
-/// ```text
-/// [payload:31 i31:1]
-/// ```
-///
-/// Odd values contain an inline signed i31. Non-zero even values are reserved
-/// for store-managed references, and zero is reserved for null by the runtime.
-#[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 {
- /// Creates a host reference when `addr` fits the runtime encoding.
- #[inline]
- pub const fn from_host(addr: u32) -> Option<Self> {
- match encode_host_ref(addr) {
- Some(encoded) => Some(Self(encoded)),
- None => None,
- }
- }
-
- #[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 }
- }
-
- #[inline]
- pub const fn raw(self) -> u32 {
- self.0
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn host_reference_encoding_is_checked_and_unique() {
- assert_ne!(AnyRef::from_host(0), AnyRef::from_host(1));
- assert!(AnyRef::from_host(HOST_REF_TAG - 2).is_some());
- assert!(AnyRef::from_host(HOST_REF_TAG - 1).is_none());
- assert!(ExternRef::try_new(u32::MAX).is_none());
- }
-}
diff --git a/crates/types/src/types.rs b/crates/types/src/types.rs
index 0801849..12386f1 100644
--- a/crates/types/src/types.rs
+++ b/crates/types/src/types.rs
@@ -3,6 +3,8 @@ use alloc::{boxed::Box, sync::Arc};
use crate::{TypeAddr, WasmType};
/// The dense type index space of a WebAssembly module.
+///
+/// See <https://webassembly.github.io/spec/core/syntax/types.html#syntax-rectype>
#[derive(Clone, PartialEq, Eq, Default)]
#[cfg_attr(feature = "debug", derive(Debug))]
#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
@@ -31,6 +33,8 @@ impl TypeSection {
}
/// A type with optional declared subtyping.
+///
+/// See <https://webassembly.github.io/spec/core/syntax/types.html#syntax-subtype>
#[derive(Clone, PartialEq, Eq)]
#[cfg_attr(feature = "debug", derive(Debug))]
#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
@@ -58,6 +62,8 @@ impl SubType {
}
/// A function, struct, or array type.
+///
+/// See <https://webassembly.github.io/spec/core/syntax/types.html#syntax-comptype>
#[derive(Clone, PartialEq, Eq)]
#[cfg_attr(feature = "debug", derive(Debug))]
#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
@@ -123,6 +129,8 @@ impl FuncType {
}
/// A WebAssembly struct type.
+///
+/// See <https://webassembly.github.io/spec/core/syntax/types.html#syntax-structtype>
#[derive(Clone, PartialEq, Eq, Default)]
#[cfg_attr(feature = "debug", derive(Debug))]
#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
@@ -131,6 +139,8 @@ pub struct StructType {
}
/// A WebAssembly array type.
+///
+/// See <https://webassembly.github.io/spec/core/syntax/types.html#syntax-arraytype>
#[derive(Clone, PartialEq, Eq)]
#[cfg_attr(feature = "debug", derive(Debug))]
#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
@@ -139,6 +149,8 @@ pub struct ArrayType {
}
/// A struct field or array element type.
+///
+/// See <https://webassembly.github.io/spec/core/syntax/types.html#syntax-fieldtype>
#[derive(Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "debug", derive(Debug))]
#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
@@ -148,6 +160,8 @@ pub struct FieldType {
}
/// A field's packed or unpacked storage type.
+///
+/// See <https://webassembly.github.io/spec/core/syntax/types.html#syntax-storagetype>
#[derive(Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "debug", derive(Debug))]
#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
@@ -156,3 +170,13 @@ pub enum StorageType {
I16,
Value(WasmType),
}
+
+impl StorageType {
+ /// Returns the unpacked WebAssembly value type used on the stack.
+ pub const fn unpacked(self) -> WasmType {
+ match self {
+ Self::I8 | Self::I16 => WasmType::I32,
+ Self::Value(ty) => ty,
+ }
+ }
+}
diff --git a/crates/types/src/value.rs b/crates/types/src/value.rs
index 5049ba2..847e5e1 100644
--- a/crates/types/src/value.rs
+++ b/crates/types/src/value.rs
@@ -1,307 +1,38 @@
-use core::fmt::Debug;
-
-use crate::{ConstInstruction, RefType, RefValue};
-
-/// A WebAssembly value.
-///
-/// See <https://webassembly.github.io/spec/core/syntax/types.html#value-types>
-#[derive(Clone, Copy, PartialEq)]
-pub enum WasmValue {
- // Num types
- /// A 32-bit integer
- I32(i32),
- /// A 64-bit integer
- I64(i64),
- /// A 32-bit float
- F32(f32),
- /// A 64-bit float
- F64(f64),
- /// A 128-bit vector
- V128([u8; 16]),
- /// 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)) => {
- 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(value)), WasmType::Ref(ty)) => matches!(
- (value.as_i31(), ty.abstract_heap_type()),
- (
- Some(_),
- Some(crate::AbstractHeapType::I31 | crate::AbstractHeapType::Eq | crate::AbstractHeapType::Any)
- ) | (None, Some(crate::AbstractHeapType::Any))
- ),
- _ => false,
- }
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use crate::{AbstractHeapType, AnyRef, FuncRef, RefType};
-
- #[test]
- fn concrete_references_require_store_type_information() {
- let concrete = WasmType::Ref(RefType::new_concrete(false, 0));
-
- assert!(!WasmValue::from(FuncRef::new(0)).matches_type(concrete));
- assert!(!WasmValue::from(AnyRef::from_host(0).unwrap()).matches_type(concrete));
- }
-
- #[test]
- fn i31_only_matches_its_store_independent_supertypes() {
- let value = WasmValue::from(AnyRef::from_i31(0).unwrap());
-
- for ty in [AbstractHeapType::I31, AbstractHeapType::Eq, AbstractHeapType::Any] {
- assert!(value.matches_type(WasmType::Ref(RefType::new_abstract(false, ty))));
- }
- assert!(!value.matches_type(WasmType::Ref(RefType::new_abstract(false, AbstractHeapType::Struct))));
- }
-}
-
-impl Debug for WasmValue {
- fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
- match self {
- Self::I32(i) => write!(f, "i32({i})"),
- Self::I64(i) => write!(f, "i64({i})"),
- Self::F32(i) => write!(f, "f32({i})"),
- Self::F64(i) => write!(f, "f64({i})"),
- Self::V128(i) => write!(f, "v128({i:?})"),
- #[cfg(feature = "debug")]
- Self::Ref(i) => write!(f, "ref({i:?})"),
- #[cfg(not(feature = "debug"))]
- Self::Ref(_) => write!(f, "ref(...)"),
- }
- }
-}
-
-impl WasmValue {
- #[inline]
- /// Get the matching [`ConstInstruction`] for this value.
- pub fn const_instr(&self) -> alloc::boxed::Box<[ConstInstruction]> {
- alloc::boxed::Box::new([match self {
- Self::I32(i) => ConstInstruction::I32Const(*i),
- Self::I64(i) => ConstInstruction::I64Const(*i),
- Self::F32(i) => ConstInstruction::F32Const(*i),
- Self::F64(i) => ConstInstruction::F64Const(*i),
- Self::V128(i) => ConstInstruction::V128Const(*i),
- Self::Ref(i) => ConstInstruction::Ref(*i),
- }])
- }
-
- #[inline]
- /// Get the default value for a given type.
- pub const fn default_for(ty: WasmType) -> Option<Self> {
- match ty {
- 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,
- }
- }
-
- #[inline]
- /// Check if two values are equal, ignoring differences in NaN values.
- pub fn eq_loose(&self, other: &Self) -> bool {
- match (self, other) {
- (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::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,
- }
- }
-
- fn v128_nan_eq(a: [u8; 16], b: [u8; 16]) -> bool {
- let a_f32x4: [f32; 4] = [
- f32::from_le_bytes([a[0], a[1], a[2], a[3]]),
- f32::from_le_bytes([a[4], a[5], a[6], a[7]]),
- f32::from_le_bytes([a[8], a[9], a[10], a[11]]),
- f32::from_le_bytes([a[12], a[13], a[14], a[15]]),
- ];
- let b_f32x4: [f32; 4] = [
- f32::from_le_bytes([b[0], b[1], b[2], b[3]]),
- f32::from_le_bytes([b[4], b[5], b[6], b[7]]),
- f32::from_le_bytes([b[8], b[9], b[10], b[11]]),
- f32::from_le_bytes([b[12], b[13], b[14], b[15]]),
- ];
-
- let all_nan_match = a_f32x4.iter().zip(b_f32x4.iter()).all(|(x, y)| {
- if x.is_nan() && y.is_nan() {
- true
- } else if x.is_nan() || y.is_nan() {
- false
- } else {
- x.to_bits() == y.to_bits()
- }
- });
-
- if all_nan_match && a_f32x4.iter().any(|x| x.is_nan()) {
- return true;
- }
-
- let a_f64x2: [f64; 2] = [
- f64::from_le_bytes([a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7]]),
- f64::from_le_bytes([a[8], a[9], a[10], a[11], a[12], a[13], a[14], a[15]]),
- ];
- let b_f64x2: [f64; 2] = [
- f64::from_le_bytes([b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]]),
- f64::from_le_bytes([b[8], b[9], b[10], b[11], b[12], b[13], b[14], b[15]]),
- ];
-
- a_f64x2.iter().zip(b_f64x2.iter()).all(|(x, y)| {
- if x.is_nan() && y.is_nan() {
- true
- } else if x.is_nan() || y.is_nan() {
- false
- } else {
- x.to_bits() == y.to_bits()
- }
- }) && a_f64x2.iter().any(|x| x.is_nan())
- }
-}
+use crate::{RefType, StorageType};
/// Type of a WebAssembly value.
+///
+/// See <https://webassembly.github.io/spec/core/syntax/types.html#syntax-valtype>
#[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
+ /// A 128-bit vector.
V128,
- /// A reference type
+ /// A reference type.
Ref(RefType),
}
impl WasmType {
#[inline]
- pub const fn default_value(&self) -> Option<WasmValue> {
- WasmValue::default_for(*self)
- }
-
- #[inline]
- pub const fn is_simd(&self) -> bool {
+ pub const fn is_simd(self) -> bool {
matches!(self, Self::V128)
}
}
-macro_rules! impl_conversion_for_wasmvalue {
- ($($t:ty => $variant:ident, $accessor:ident, $doc:literal);* $(;)?) => {
- impl WasmValue {
- $(
- #[doc = $doc]
- pub const fn $accessor(&self) -> Option<$t> {
- match self {
- Self::$variant(value) => Some(*value),
- _ => None,
- }
- }
- )*
+impl From<StorageType> for WasmType {
+ fn from(value: StorageType) -> Self {
+ match value {
+ StorageType::I8 | StorageType::I16 => Self::I32,
+ StorageType::Value(value) => value,
}
-
- $(
- impl From<$t> for WasmValue {
- #[inline]
- fn from(i: $t) -> Self {
- Self::$variant(i)
- }
- }
-
- impl TryFrom<WasmValue> for $t {
- type Error = ();
-
- #[inline]
- fn try_from(value: WasmValue) -> Result<Self, Self::Error> {
- if let WasmValue::$variant(i) = value { Ok(i) } else { Err(()) }
- }
- }
- )*
}
}
-
-impl_conversion_for_wasmvalue! {
- i32 => I32, as_i32, "Return the `i32` from a `WasmValue`, if it is an `I32`.";
- i64 => I64, as_i64, "Return the `i64` from a `WasmValue`, if it is an `I64`.";
- 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`.";
- 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;
-}