summaryrefslogtreecommitdiff
path: root/crates/types
diff options
context:
space:
mode:
authorHenry <mail@henrygressmann.de>2026-07-14 20:48:18 +0200
committerHenry <mail@henrygressmann.de>2026-07-14 20:48:18 +0200
commitdc366165b8cd0f8c43cfe7017cb37f0a16887d6d (patch)
treea0e9eeba6211fe9fddde96547a6338aca79d7c3f /crates/types
parentfe43e4816efbf622e8cdc106a552dfb9aadfb80e (diff)
chore: simplify runtime, parser, types, and SIMD internals
Signed-off-by: Henry <mail@henrygressmann.de>
Diffstat (limited to 'crates/types')
-rw-r--r--crates/types/src/archive.rs3
-rw-r--r--crates/types/src/lib.rs115
-rw-r--r--crates/types/src/reference.rs112
-rw-r--r--crates/types/src/value.rs209
4 files changed, 166 insertions, 273 deletions
diff --git a/crates/types/src/archive.rs b/crates/types/src/archive.rs
index 92bb87a..5a6f94b 100644
--- a/crates/types/src/archive.rs
+++ b/crates/types/src/archive.rs
@@ -42,9 +42,6 @@ impl Display for TwasmError {
}
}
-#[cfg(feature = "std")]
-extern crate std;
-
impl core::error::Error for TwasmError {}
impl Module {
diff --git a/crates/types/src/lib.rs b/crates/types/src/lib.rs
index e576027..e918e46 100644
--- a/crates/types/src/lib.rs
+++ b/crates/types/src/lib.rs
@@ -10,7 +10,6 @@
extern crate alloc;
use alloc::{boxed::Box, sync::Arc};
-use core::hint::cold_path;
use core::ops::{Deref, Range};
// Memory defaults
@@ -21,26 +20,11 @@ const fn max_page_count(page_size: u64) -> u64 {
MAX_MEMORY_SIZE / page_size
}
-// log for logging (optional).
-#[cfg(feature = "log")]
-#[allow(clippy::single_component_path_imports, unused_imports)]
-use log;
-
-// noop fallback if logging is disabled.
-#[cfg(not(feature = "log"))]
-#[allow(unused_imports, unused_macros)]
-pub(crate) mod log {
- macro_rules! debug ( ($($tt:tt)*) => {{}} );
- macro_rules! info ( ($($tt:tt)*) => {{}} );
- macro_rules! error ( ($($tt:tt)*) => {{}} );
- pub(crate) use debug;
- pub(crate) use error;
- pub(crate) use info;
-}
-
mod instructions;
+mod reference;
mod value;
pub use instructions::*;
+pub use reference::*;
pub use value::*;
#[cfg(feature = "archive")]
@@ -48,7 +32,7 @@ pub mod archive;
#[cfg(not(feature = "archive"))]
pub mod archive {
- #[derive(Debug)]
+ #[derive(Debug, PartialEq, Eq)]
pub enum TwasmError {}
impl core::fmt::Display for TwasmError {
fn fmt(&self, _: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
@@ -181,56 +165,24 @@ impl Module {
.count()
}
- fn imported_func_type(module: &ModuleInner, function_index: usize) -> Option<&FuncType> {
- let mut seen = 0usize;
- for import in module.imports.iter() {
- if let ImportKind::Function(type_idx) = import.kind {
- if seen == function_index {
- return module.func_types.get(type_idx as usize).map(|ty| &**ty);
- }
- seen += 1;
- }
- }
- None
- }
+ fn imported_type(module: &ModuleInner, kind: ExternalKind, index: usize) -> Option<ExportType<'_>> {
+ let mut imports = module.imports.iter().filter(|import| {
+ matches!(
+ (kind, &import.kind),
+ (ExternalKind::Func, ImportKind::Function(_))
+ | (ExternalKind::Table, ImportKind::Table(_))
+ | (ExternalKind::Memory, ImportKind::Memory(_))
+ | (ExternalKind::Global, ImportKind::Global(_))
+ )
+ });
+ let import = imports.nth(index)?;
- fn imported_table_type(module: &ModuleInner, table_index: usize) -> Option<&TableType> {
- let mut seen = 0usize;
- for import in module.imports.iter() {
- if let ImportKind::Table(table_ty) = &import.kind {
- if seen == table_index {
- return Some(table_ty);
- }
- seen += 1;
- }
- }
- None
- }
-
- fn imported_memory_type(module: &ModuleInner, memory_index: usize) -> Option<&MemoryType> {
- let mut seen = 0usize;
- for import in module.imports.iter() {
- if let ImportKind::Memory(memory_ty) = &import.kind {
- if seen == memory_index {
- return Some(memory_ty);
- }
- seen += 1;
- }
- }
- None
- }
-
- fn imported_global_type(module: &Module, global_index: usize) -> Option<&GlobalType> {
- let mut seen = 0usize;
- for import in module.imports.iter() {
- if let ImportKind::Global(global_ty) = &import.kind {
- if seen == global_index {
- return Some(global_ty);
- }
- seen += 1;
- }
+ match &import.kind {
+ ImportKind::Function(type_idx) => Some(ExportType::Func(module.func_types.get(*type_idx as usize)?)),
+ ImportKind::Table(table_ty) => Some(ExportType::Table(table_ty)),
+ ImportKind::Memory(memory_ty) => Some(ExportType::Memory(memory_ty)),
+ ImportKind::Global(global_ty) => Some(ExportType::Global(global_ty)),
}
- None
}
self.0.exports.iter().filter_map(move |export| {
@@ -239,37 +191,33 @@ impl Module {
ExternalKind::Func => {
let imported_funcs = imported_count(&self.0, ExternalKind::Func);
if idx < imported_funcs {
- ExportType::Func(imported_func_type(&self.0, idx)?)
+ imported_type(&self.0, ExternalKind::Func, idx)?
} else {
- let local_idx = idx - imported_funcs;
- ExportType::Func(&self.0.funcs.get(local_idx)?.ty)
+ ExportType::Func(&self.0.funcs.get(idx - imported_funcs)?.ty)
}
}
ExternalKind::Table => {
let imported_tables = imported_count(&self.0, ExternalKind::Table);
if idx < imported_tables {
- ExportType::Table(imported_table_type(&self.0, idx)?)
+ imported_type(&self.0, ExternalKind::Table, idx)?
} else {
- let local_idx = idx - imported_tables;
- ExportType::Table(self.0.table_types.get(local_idx)?)
+ ExportType::Table(self.0.table_types.get(idx - imported_tables)?)
}
}
ExternalKind::Memory => {
let imported_memories = imported_count(&self.0, ExternalKind::Memory);
if idx < imported_memories {
- ExportType::Memory(imported_memory_type(&self.0, idx)?)
+ imported_type(&self.0, ExternalKind::Memory, idx)?
} else {
- let local_idx = idx - imported_memories;
- ExportType::Memory(self.0.memory_types.get(local_idx)?)
+ ExportType::Memory(self.0.memory_types.get(idx - imported_memories)?)
}
}
ExternalKind::Global => {
let imported_globals = imported_count(&self.0, ExternalKind::Global);
if idx < imported_globals {
- ExportType::Global(imported_global_type(self, idx)?)
+ imported_type(&self.0, ExternalKind::Global, idx)?
} else {
- let local_idx = idx - imported_globals;
- ExportType::Global(&self.0.globals.get(local_idx)?.ty)
+ ExportType::Global(&self.0.globals.get(idx - imported_globals)?.ty)
}
}
};
@@ -422,9 +370,8 @@ pub struct FuncType {
impl FuncType {
/// Create a new function type.
pub fn new(params: &[WasmType], results: &[WasmType]) -> Self {
- let param_count = params.len() as u16;
let data: Box<[WasmType]> = params.iter().cloned().chain(results.iter().cloned()).collect();
- Self { data, param_count }
+ Self { data, param_count: params.len() as u16 }
}
/// Get the parameter types of this function type.
@@ -494,11 +441,7 @@ impl WasmFunctionData {
/// Panics if `idx` is out of bounds.
#[inline(always)]
pub fn v128_const(&self, idx: ConstIdx) -> [u8; 16] {
- let Some(val) = self.v128_constants.get(idx as usize) else {
- cold_path();
- unreachable!("invalid v128 constant index");
- };
- *val
+ *self.v128_constants.get(idx as usize).unwrap_or_else(|| unreachable!("invalid v128 constant index: {idx}"))
}
}
diff --git a/crates/types/src/reference.rs b/crates/types/src/reference.rs
new file mode 100644
index 0000000..7970dc8
--- /dev/null
+++ b/crates/types/src/reference.rs
@@ -0,0 +1,112 @@
+use crate::{ExternAddr, FuncAddr};
+
+const NULL_REF: u32 = u32::MAX;
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+pub struct ExternRef(u32);
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+pub struct FuncRef(u32);
+
+#[cfg(feature = "debug")]
+impl core::fmt::Debug for ExternRef {
+ 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)"),
+ }
+ }
+}
+
+#[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 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(),
+ }
+ }
+
+ #[inline]
+ /// Create a null [`FuncRef`].
+ pub const fn null() -> Self {
+ Self(NULL_REF)
+ }
+
+ #[inline]
+ /// Check if the [`FuncRef`] is null.
+ pub const fn is_null(&self) -> bool {
+ self.0 == NULL_REF
+ }
+
+ #[inline]
+ /// Get the [`FuncAddr`] from the [`FuncRef`].
+ pub const fn addr(&self) -> Option<FuncAddr> {
+ if self.is_null() { None } else { Some(self.0) }
+ }
+
+ #[inline]
+ #[doc(hidden)]
+ pub const fn from_raw(raw: u32) -> Self {
+ Self(raw)
+ }
+
+ #[inline]
+ #[doc(hidden)]
+ pub const fn raw(&self) -> u32 {
+ self.0
+ }
+}
+
+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(),
+ }
+ }
+
+ /// Create a null [`ExternRef`].
+ #[inline]
+ pub const fn null() -> Self {
+ Self(NULL_REF)
+ }
+
+ /// Check if the [`ExternRef`] is null.
+ #[inline]
+ pub const fn is_null(&self) -> bool {
+ self.0 == NULL_REF
+ }
+
+ /// Get the [`ExternAddr`] from the [`ExternRef`].
+ #[inline]
+ pub const fn addr(&self) -> Option<ExternAddr> {
+ if self.is_null() { None } else { Some(self.0) }
+ }
+
+ #[inline]
+ #[doc(hidden)]
+ pub const fn from_raw(raw: u32) -> Self {
+ Self(raw)
+ }
+
+ #[inline]
+ #[doc(hidden)]
+ pub const fn raw(&self) -> u32 {
+ self.0
+ }
+}
diff --git a/crates/types/src/value.rs b/crates/types/src/value.rs
index d01214f..782cdb8 100644
--- a/crates/types/src/value.rs
+++ b/crates/types/src/value.rs
@@ -1,6 +1,6 @@
use core::fmt::Debug;
-use crate::{ConstInstruction, ExternAddr, FuncAddr};
+use crate::{ConstInstruction, ExternRef, FuncRef};
/// A WebAssembly value.
///
@@ -42,117 +42,6 @@ impl Debug for WasmValue {
}
}
-const NULL_REF: u32 = u32::MAX;
-
-#[derive(Clone, Copy, PartialEq, Eq)]
-pub struct ExternRef(u32);
-
-#[derive(Clone, Copy, PartialEq, Eq)]
-pub struct FuncRef(u32);
-
-#[cfg(feature = "debug")]
-impl Debug for ExternRef {
- 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)"),
- }
- }
-}
-
-#[cfg(feature = "debug")]
-impl 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 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(),
- }
- }
-
- #[inline]
- /// Create a null [`FuncRef`].
- pub const fn null() -> Self {
- Self(NULL_REF)
- }
-
- #[inline]
- /// Check if the [`FuncRef`] is null.
- pub const fn is_null(&self) -> bool {
- self.0 == NULL_REF
- }
-
- #[inline]
- /// Get the [`FuncAddr`] from the [`FuncRef`].
- pub const fn addr(&self) -> Option<FuncAddr> {
- if self.is_null() { None } else { Some(self.0) }
- }
-
- #[inline]
- #[doc(hidden)]
- pub const fn from_raw(raw: u32) -> Self {
- Self(raw)
- }
-
- #[inline]
- #[doc(hidden)]
- pub const fn raw(&self) -> u32 {
- self.0
- }
-}
-
-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(),
- }
- }
-
- /// Create a null [`ExternRef`].
- #[inline]
- pub const fn null() -> Self {
- Self(NULL_REF)
- }
-
- /// Check if the [`ExternRef`] is null.
- #[inline]
- pub const fn is_null(&self) -> bool {
- self.0 == NULL_REF
- }
-
- /// Get the [`ExternAddr`] from the [`ExternRef`].
- #[inline]
- pub const fn addr(&self) -> Option<ExternAddr> {
- if self.is_null() { None } else { Some(self.0) }
- }
-
- #[inline]
- #[doc(hidden)]
- pub const fn from_raw(raw: u32) -> Self {
- Self(raw)
- }
-
- #[inline]
- #[doc(hidden)]
- pub const fn raw(&self) -> u32 {
- self.0
- }
-}
-
impl WasmValue {
#[inline]
/// Get the matching [`ConstInstruction`] for this value.
@@ -191,20 +80,8 @@ impl WasmValue {
(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::F32(a), Self::F32(b)) => {
- if a.is_nan() && b.is_nan() {
- true
- } else {
- a.to_bits() == b.to_bits()
- }
- }
- (Self::F64(a), Self::F64(b)) => {
- if a.is_nan() && b.is_nan() {
- true
- } else {
- a.to_bits() == b.to_bits()
- }
- }
+ (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,
}
}
@@ -256,62 +133,6 @@ impl WasmValue {
}
}) && a_f64x2.iter().any(|x| x.is_nan())
}
-
- /// Return the `i32` from a `WasmValue`, if it is an `I32`.
- pub const fn as_i32(&self) -> Option<i32> {
- match self {
- Self::I32(i) => Some(*i),
- _ => None,
- }
- }
-
- /// Return the `i64` from a `WasmValue`, if it is an `I64`.
- pub const fn as_i64(&self) -> Option<i64> {
- match self {
- Self::I64(i) => Some(*i),
- _ => None,
- }
- }
-
- /// Return the `f32` from a `WasmValue`, if it is a `F32`.
- pub const fn as_f32(&self) -> Option<f32> {
- match self {
- Self::F32(i) => Some(*i),
- _ => None,
- }
- }
-
- /// Return the `f64` from a `WasmValue`, if it is a `F64`.
- pub const fn as_f64(&self) -> Option<f64> {
- match self {
- Self::F64(i) => Some(*i),
- _ => None,
- }
- }
-
- /// Return the raw little-endian bytes from a `WasmValue`, if it is a `V128`.
- pub const fn as_v128(&self) -> Option<[u8; 16]> {
- match self {
- Self::V128(i) => Some(*i),
- _ => None,
- }
- }
-
- /// Return the [[`ExternRef`]] from a `WasmValue`, if it is one
- pub const fn as_ref_extern(&self) -> Option<ExternRef> {
- match self {
- Self::RefExtern(ref_extern) => Some(*ref_extern),
- _ => None,
- }
- }
-
- /// Return the [`FuncRef`] from a `WasmValue`, if it is one
- pub const fn as_ref_func(&self) -> Option<FuncRef> {
- match self {
- Self::RefFunc(ref_func) => Some(*ref_func),
- _ => None,
- }
- }
}
impl From<&WasmValue> for WasmType {
@@ -369,7 +190,19 @@ impl WasmType {
}
macro_rules! impl_conversion_for_wasmvalue {
- ($($t:ty => $variant:ident),*) => {
+ ($($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<$t> for WasmValue {
#[inline]
@@ -390,4 +223,12 @@ macro_rules! impl_conversion_for_wasmvalue {
}
}
-impl_conversion_for_wasmvalue! { i32 => I32, i64 => I64, f32 => F32, f64 => F64, [u8; 16] => V128, ExternRef => RefExtern, FuncRef => RefFunc }
+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`.";
+ 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";
+}