summaryrefslogtreecommitdiff
path: root/crates
diff options
context:
space:
mode:
authorHenry <mail@henrygressmann.de>2026-08-10 15:22:56 +0200
committerHenry <mail@henrygressmann.de>2026-08-10 15:22:56 +0200
commit666c7f59301acc9fcef10ac2da5beb464e57d665 (patch)
treee7f13addcf7278f63dd37d30ab303577b4281d7d /crates
parent6ecee15efc820a23bb8a47b5ff4111037ec76bc7 (diff)
chore: simplify runtime and clean up tests
Signed-off-by: Henry <mail@henrygressmann.de>
Diffstat (limited to 'crates')
-rw-r--r--crates/parser/src/conversion.rs48
-rw-r--r--crates/parser/src/macros.rs2
-rw-r--r--crates/parser/src/module.rs17
-rw-r--r--crates/parser/src/visit.rs73
-rw-r--r--crates/tinywasm/Cargo.toml28
-rw-r--r--crates/tinywasm/src/func/host.rs17
-rw-r--r--crates/tinywasm/src/imports.rs40
-rw-r--r--crates/tinywasm/src/interpreter/executor.rs5
-rw-r--r--crates/tinywasm/src/interpreter/simd/mod.rs2
-rw-r--r--crates/tinywasm/src/interpreter/simd/tests.rs60
-rw-r--r--crates/tinywasm/src/interpreter/stack/value_stack.rs4
-rw-r--r--crates/tinywasm/src/interpreter/values.rs48
-rw-r--r--crates/tinywasm/src/reference.rs2
-rw-r--r--crates/tinywasm/src/store/const_expr.rs120
-rw-r--r--crates/tinywasm/src/store/gc/arena.rs15
-rw-r--r--crates/tinywasm/src/store/gc/object.rs47
-rw-r--r--crates/tinywasm/src/store/global.rs28
-rw-r--r--crates/tinywasm/src/store/memory/mod.rs182
-rw-r--r--crates/tinywasm/src/store/memory/paged.rs45
-rw-r--r--crates/tinywasm/src/store/mod.rs14
-rw-r--r--crates/tinywasm/src/store/state.rs25
-rw-r--r--crates/tinywasm/src/store/table.rs55
-rw-r--r--crates/tinywasm/tests/generated/wasm-annotations.csv5
-rw-r--r--crates/tinywasm/tests/generated/wasm-extended-const.csv5
-rw-r--r--crates/tinywasm/tests/generated/wasm-function-references.csv3
-rw-r--r--crates/tinywasm/tests/generated/wasm-nontrapping-float-to-int-conversions.csv4
-rw-r--r--crates/tinywasm/tests/generated/wasm-reference-types.csv4
-rw-r--r--crates/tinywasm/tests/generated/wasm-sign-extension-ops.csv4
-rw-r--r--crates/tinywasm/tests/generated/wasm-tail-call.csv4
-rw-r--r--crates/tinywasm/tests/test-wasm-annotations.rs13
-rw-r--r--crates/tinywasm/tests/test-wasm-extended-const.rs13
-rw-r--r--crates/tinywasm/tests/test-wasm-function-references.rs13
-rw-r--r--crates/tinywasm/tests/test-wasm-nontrapping-float-to-int-conversions.rs14
-rw-r--r--crates/tinywasm/tests/test-wasm-reference-types.rs13
-rw-r--r--crates/tinywasm/tests/test-wasm-sign-extension-op.rs13
-rw-r--r--crates/tinywasm/tests/test-wasm-tail-call.rs14
-rw-r--r--crates/tinywasm/tests/wasm-custom/table-basics.wast32
-rw-r--r--crates/types/src/instructions.rs5
38 files changed, 329 insertions, 707 deletions
diff --git a/crates/parser/src/conversion.rs b/crates/parser/src/conversion.rs
index 7b52363..694c639 100644
--- a/crates/parser/src/conversion.rs
+++ b/crates/parser/src/conversion.rs
@@ -14,11 +14,14 @@ pub(crate) fn value_lane(ty: wasmparser::ValType) -> ValueLane {
}
}
-pub(crate) fn convert_module_element(element: wasmparser::Element<'_>) -> Result<tinywasm_types::Element> {
+pub(crate) fn convert_module_element(
+ element: wasmparser::Element<'_>,
+ global_types: &[WasmType],
+) -> Result<tinywasm_types::Element> {
let kind = match element.kind {
wasmparser::ElementKind::Active { table_index, offset_expr } => tinywasm_types::ElementKind::Active {
table: table_index.unwrap_or(0),
- offset: process_const_operators(offset_expr.get_operators_reader())?,
+ offset: process_const_operators(offset_expr.get_operators_reader(), global_types)?,
},
wasmparser::ElementKind::Passive => tinywasm_types::ElementKind::Passive,
wasmparser::ElementKind::Declared => tinywasm_types::ElementKind::Declared,
@@ -38,7 +41,7 @@ pub(crate) fn convert_module_element(element: wasmparser::Element<'_>) -> Result
wasmparser::ElementItems::Expressions(ty, exprs) => {
let items = exprs
.into_iter()
- .map(|expr| Ok(ElementItem::Expr(process_const_operators(expr?.get_operators_reader())?)))
+ .map(|expr| Ok(ElementItem::Expr(process_const_operators(expr?.get_operators_reader(), global_types)?)))
.collect::<Result<Vec<_>>>()?
.into_boxed_slice();
@@ -47,13 +50,16 @@ pub(crate) fn convert_module_element(element: wasmparser::Element<'_>) -> Result
}
}
-pub(crate) fn convert_module_data(data: wasmparser::Data<'_>) -> Result<tinywasm_types::Data> {
+pub(crate) fn convert_module_data(
+ data: wasmparser::Data<'_>,
+ global_types: &[WasmType],
+) -> Result<tinywasm_types::Data> {
Ok(tinywasm_types::Data {
data: data.data.to_vec().into_boxed_slice(),
range: data.range,
kind: match data.kind {
wasmparser::DataKind::Active { memory_index, offset_expr } => {
- let offset = process_const_operators(offset_expr.get_operators_reader())?;
+ let offset = process_const_operators(offset_expr.get_operators_reader(), global_types)?;
tinywasm_types::DataKind::Active { mem: memory_index, offset }
}
wasmparser::DataKind::Passive => tinywasm_types::DataKind::Passive,
@@ -96,16 +102,17 @@ pub(crate) fn convert_module_memory(memory: wasmparser::MemoryType) -> MemoryTyp
pub(crate) fn convert_module_globals(
globals: wasmparser::SectionLimited<'_, wasmparser::Global<'_>>,
+ global_types: &mut Vec<WasmType>,
) -> Result<Box<[Global]>> {
- globals
- .into_iter()
- .map(|global| {
- let global = global?;
- let ty = convert_valtype(&global.ty.content_type)?;
- let ops = global.init_expr.get_operators_reader();
- Ok(Global { init: process_const_operators(ops)?, ty: GlobalType::new(ty, global.ty.mutable) })
- })
- .collect::<Result<Box<_>>>()
+ let mut out = Vec::with_capacity(globals.count() as usize);
+ for global in globals {
+ let global = global?;
+ let ty = convert_valtype(&global.ty.content_type)?;
+ let init = process_const_operators(global.init_expr.get_operators_reader(), global_types)?;
+ global_types.push(ty);
+ out.push(Global { init, ty: GlobalType::new(ty, global.ty.mutable) });
+ }
+ Ok(out.into_boxed_slice())
}
pub(crate) fn convert_module_export(export: wasmparser::Export<'_>) -> Result<Export> {
@@ -313,7 +320,10 @@ fn convert_valtype_with_group(valtype: &wasmparser::ValType, group: Option<(u32,
}
}
-pub(crate) fn process_const_operators(ops: OperatorsReader<'_>) -> Result<Box<[ConstInstruction]>> {
+pub(crate) fn process_const_operators(
+ ops: OperatorsReader<'_>,
+ global_types: &[WasmType],
+) -> Result<Box<[ConstInstruction]>> {
let mut out = Vec::new();
let mut operator_count = 0;
let mut end_reached = false;
@@ -353,7 +363,13 @@ pub(crate) fn process_const_operators(ops: OperatorsReader<'_>) -> Result<Box<[C
wasmparser::Operator::F32Const { value } => ConstInstruction::F32Const(f32::from_bits(value.bits())),
wasmparser::Operator::F64Const { value } => ConstInstruction::F64Const(f64::from_bits(value.bits())),
wasmparser::Operator::V128Const { value } => ConstInstruction::V128Const(*value.bytes()),
- wasmparser::Operator::GlobalGet { global_index } => ConstInstruction::GlobalGet(global_index),
+ wasmparser::Operator::GlobalGet { global_index } => match global_types.get(global_index as usize) {
+ Some(WasmType::I32 | WasmType::F32) => ConstInstruction::GlobalGet32(global_index),
+ Some(WasmType::I64 | WasmType::F64) => ConstInstruction::GlobalGet64(global_index),
+ Some(WasmType::V128) => ConstInstruction::GlobalGet128(global_index),
+ Some(WasmType::Ref(_)) => ConstInstruction::GlobalGetRef(global_index),
+ None => return Err(crate::ParseError::Other(format!("global index out of bounds: {global_index}"))),
+ },
wasmparser::Operator::I32Add => ConstInstruction::I32Add,
wasmparser::Operator::I32Sub => ConstInstruction::I32Sub,
wasmparser::Operator::I32Mul => ConstInstruction::I32Mul,
diff --git a/crates/parser/src/macros.rs b/crates/parser/src/macros.rs
index 98312ab..9fa7a01 100644
--- a/crates/parser/src/macros.rs
+++ b/crates/parser/src/macros.rs
@@ -89,7 +89,7 @@ pub(crate) mod visit {
$visit:ident($type_index:ident: $type_ty:ty $(, $arg:ident: $arg_ty:ty)*) => $instr:ident
) => {
fn $visit(&mut self, $type_index: $type_ty $(, $arg: $arg_ty)*) -> Self::Output {
- let size = ModuleMetadata::storage_size(self.metadata.array_field($type_index)?.storage);
+ let size = self.metadata.array_field($type_index)?;
lowering_ops!(@emit self address(size) [$($input),*] => [$($output),*]
Instruction::$instr($type_index $(, $arg)*).into())
}
diff --git a/crates/parser/src/module.rs b/crates/parser/src/module.rs
index bbe2cf8..3d38ad6 100644
--- a/crates/parser/src/module.rs
+++ b/crates/parser/src/module.rs
@@ -64,6 +64,7 @@ pub(crate) struct ModuleReader<'a> {
pub(crate) end_reached: bool,
imported_func_count: usize,
imported_memory_count: u32,
+ global_types: Vec<WasmType>,
#[cfg(parallel_parser)]
pending_functions: Option<Vec<crate::parallel::PendingFunction<'a>>>,
@@ -148,7 +149,7 @@ impl<'a> ModuleReader<'a> {
if let Some(validator) = validator.as_mut() {
validator.global_section(&reader)?;
}
- self.globals = convert_module_globals(reader)?;
+ self.globals = convert_module_globals(reader, &mut self.global_types)?;
}
Payload::TableSection(reader) => {
check_section("table", !self.tables.is_empty())?;
@@ -168,7 +169,7 @@ impl<'a> ModuleReader<'a> {
let init = match table.init {
wasmparser::TableInit::RefNull => None,
wasmparser::TableInit::Expr(expr) => {
- Some(process_const_operators(expr.get_operators_reader())?)
+ Some(process_const_operators(expr.get_operators_reader(), &self.global_types)?)
}
};
tables.push(TableDefinition { ty, init });
@@ -209,8 +210,10 @@ impl<'a> ModuleReader<'a> {
if let Some(validator) = validator.as_mut() {
validator.element_section(&reader)?;
}
- self.elements =
- reader.into_iter().map(|element| convert_module_element(element?)).collect::<Result<_>>()?;
+ self.elements = reader
+ .into_iter()
+ .map(|element| convert_module_element(element?, &self.global_types))
+ .collect::<Result<_>>()?;
}
Payload::DataSection(reader) => {
check_section("data", !self.data.is_empty())?;
@@ -218,7 +221,10 @@ impl<'a> ModuleReader<'a> {
if let Some(validator) = validator.as_mut() {
validator.data_section(&reader)?;
}
- self.data = reader.into_iter().map(|data| convert_module_data(data?)).collect::<Result<_>>()?;
+ self.data = reader
+ .into_iter()
+ .map(|data| convert_module_data(data?, &self.global_types))
+ .collect::<Result<_>>()?;
}
Payload::DataCountSection { count, range } => {
debug!("Found data count section");
@@ -270,6 +276,7 @@ impl<'a> ModuleReader<'a> {
self.imported_func_count += 1;
}
ImportKind::Memory(_) => self.imported_memory_count += 1,
+ ImportKind::Global(ty) => self.global_types.push(ty.ty),
ImportKind::Tag(tag) => {
let ty = self.types.get(tag.type_idx).and_then(SubType::as_func).ok_or_else(|| {
ParseError::Other(format!(
diff --git a/crates/parser/src/visit.rs b/crates/parser/src/visit.rs
index c462d05..063bef4 100644
--- a/crates/parser/src/visit.rs
+++ b/crates/parser/src/visit.rs
@@ -3,11 +3,10 @@ use crate::{
conversion::{convert_heap_type, value_lane},
macros::visit::*,
};
-use alloc::string::ToString;
-use alloc::vec::Vec;
+use alloc::{boxed::Box, string::ToString, vec::Vec};
use tinywasm_types::{
- Global, Import, ImportKind, Instruction, MemoryArg, MemoryType, StorageType, SubType, TableDefinition, TagType,
- TypeSection, ValueCounts, ValueLane, WasmFunctionData,
+ Global, Import, ImportKind, Instruction, MemoryArg, MemoryType, StorageType, TableDefinition, TagType, TypeSection,
+ ValueCounts, ValueLane, WasmFunctionData,
};
use wasmparser::{FunctionBody, OperatorsReader, OperatorsReaderAllocations, VisitSimdOperator};
@@ -50,7 +49,13 @@ pub(crate) struct ModuleMetadata {
memories: Vec<ValueLane>,
tables: Vec<ValueLane>,
tags: Vec<u32>,
- types: Vec<SubType>,
+ aggregate_fields: Vec<AggregateFields>,
+}
+
+enum AggregateFields {
+ Other,
+ Struct(Box<[ValueLane]>),
+ Array(ValueLane),
}
#[derive(Default)]
@@ -109,7 +114,7 @@ impl<'a> FunctionBuilder<'a> {
field_index: u32,
instruction: fn(u32, u32) -> Instruction,
) -> Result<()> {
- let size = ModuleMetadata::storage_size(self.metadata.struct_field(type_index, field_index)?.storage);
+ let size = self.metadata.struct_field(type_index, field_index)?;
self.emit(&[ValueLane::S32], &[size], instruction(type_index, field_index))
}
}
@@ -170,6 +175,19 @@ impl ModuleMetadata {
})
})
.collect();
+ let aggregate_fields = types
+ .types
+ .iter()
+ .map(|ty| {
+ if let Some(ty) = ty.as_struct() {
+ AggregateFields::Struct(ty.fields.iter().map(|field| Self::storage_size(field.storage)).collect())
+ } else if let Some(ty) = ty.as_array() {
+ AggregateFields::Array(Self::storage_size(ty.field.storage))
+ } else {
+ AggregateFields::Other
+ }
+ })
+ .collect();
Self {
signatures,
functions,
@@ -177,7 +195,7 @@ impl ModuleMetadata {
memories: memory_sizes,
tables: table_sizes,
tags: tag_types,
- types: types.types.to_vec(),
+ aggregate_fields,
}
}
@@ -230,26 +248,30 @@ impl ModuleMetadata {
}
}
- fn struct_fields(&self, idx: u32) -> Result<&[tinywasm_types::FieldType]> {
- self.types
+ fn struct_fields(&self, idx: u32) -> Result<&[ValueLane]> {
+ self.aggregate_fields
.get(idx as usize)
- .and_then(SubType::as_struct)
- .map(|ty| ty.fields.as_ref())
+ .and_then(|fields| match fields {
+ AggregateFields::Struct(fields) => Some(fields.as_ref()),
+ AggregateFields::Other | AggregateFields::Array(_) => None,
+ })
.ok_or_else(|| crate::ParseError::Other(alloc::format!("type index is not a struct type: {idx}")))
}
- fn struct_field(&self, type_index: u32, field_index: u32) -> Result<tinywasm_types::FieldType> {
+ fn struct_field(&self, type_index: u32, field_index: u32) -> Result<ValueLane> {
self.struct_fields(type_index)?
.get(field_index as usize)
.copied()
.ok_or_else(|| crate::ParseError::Other("struct field index out of bounds".into()))
}
- fn array_field(&self, idx: u32) -> Result<tinywasm_types::FieldType> {
- self.types
+ fn array_field(&self, idx: u32) -> Result<ValueLane> {
+ self.aggregate_fields
.get(idx as usize)
- .and_then(SubType::as_array)
- .map(|ty| ty.field)
+ .and_then(|fields| match fields {
+ AggregateFields::Array(field) => Some(*field),
+ AggregateFields::Other | AggregateFields::Struct(_) => None,
+ })
.ok_or_else(|| crate::ParseError::Other(alloc::format!("type index is not an array type: {idx}")))
}
}
@@ -490,13 +512,14 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> {
}
fn visit_struct_new(&mut self, type_index: u32) -> Self::Output {
- let inputs = self
- .metadata
- .struct_fields(type_index)?
- .iter()
- .map(|field| ModuleMetadata::storage_size(field.storage))
- .collect::<Vec<_>>();
- self.emit(&inputs, &[ValueLane::S32], Instruction::StructNew(type_index))
+ let field_count = self.metadata.struct_fields(type_index)?.len();
+ for field_index in (0..field_count).rev() {
+ let size = self.metadata.struct_field(type_index, field_index as u32)?;
+ self.pop_expect(size)?;
+ }
+ self.push_sizes(&[ValueLane::S32])?;
+ self.instructions.push(Instruction::StructNew(type_index));
+ Ok(())
}
fn visit_struct_get(&mut self, type_index: u32, field_index: u32) -> Self::Output {
@@ -512,12 +535,12 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> {
}
fn visit_struct_set(&mut self, type_index: u32, field_index: u32) -> Self::Output {
- let size = ModuleMetadata::storage_size(self.metadata.struct_field(type_index, field_index)?.storage);
+ let size = self.metadata.struct_field(type_index, field_index)?;
self.emit(&[ValueLane::S32, size], &[], Instruction::StructSet(type_index, field_index))
}
fn visit_array_new_fixed(&mut self, type_index: u32, array_size: u32) -> Self::Output {
- let size = ModuleMetadata::storage_size(self.metadata.array_field(type_index)?.storage);
+ let size = self.metadata.array_field(type_index)?;
for _ in 0..array_size {
self.pop_expect(size)?;
}
diff --git a/crates/tinywasm/Cargo.toml b/crates/tinywasm/Cargo.toml
index 67d0742..65ef7f8 100644
--- a/crates/tinywasm/Cargo.toml
+++ b/crates/tinywasm/Cargo.toml
@@ -54,10 +54,6 @@ test = false
[[test]]
harness = false
-name = "test-wasm-annotations"
-
-[[test]]
-harness = false
name = "test-wast"
test = false
@@ -67,10 +63,6 @@ name = "test-wasm-custom-page-sizes"
[[test]]
harness = false
-name = "test-wasm-function-references"
-
-[[test]]
-harness = false
name = "test-wasm-custom"
[[test]]
@@ -79,18 +71,10 @@ name = "test-wasm-gc"
[[test]]
harness = false
-name = "test-wasm-tail-call"
-
-[[test]]
-harness = false
name = "test-wasm-memory64"
[[test]]
harness = false
-name = "test-wasm-extended-const"
-
-[[test]]
-harness = false
name = "test-wasm-relaxed-simd"
[[test]]
@@ -101,18 +85,6 @@ name = "test-wasm-simd"
harness = false
name = "test-wasm-wide-arithmetic"
-[[test]]
-harness = false
-name = "test-wasm-sign-extension-op"
-
-[[test]]
-harness = false
-name = "test-wasm-nontrapping-float-to-int-conversions"
-
-[[test]]
-harness = false
-name = "test-wasm-reference-types"
-
[[bench]]
harness = false
name = "argon2id"
diff --git a/crates/tinywasm/src/func/host.rs b/crates/tinywasm/src/func/host.rs
index 83b17f9..5335444 100644
--- a/crates/tinywasm/src/func/host.rs
+++ b/crates/tinywasm/src/func/host.rs
@@ -9,8 +9,8 @@ use crate::{Function, FunctionInstance, Result, Store};
pub struct HostFunction(Arc<HostFunctionInner>);
impl HostFunction {
- fn instantiate_canonical(&self, store: &mut Store, ty: &FuncType) -> Function {
- let type_addr = store.register_host_type(ty);
+ /// Instantiates the function with an already registered canonical type.
+ pub(crate) fn instantiate_registered(&self, store: &mut Store, type_addr: TypeAddr) -> Function {
let addr = store.add_func(FunctionInstance {
type_addr,
gc: store.state.func_gc_metadata(type_addr),
@@ -19,8 +19,12 @@ impl HostFunction {
Function { item: crate::StoreItem::new(store.id(), addr), module_id: 0 }
}
- /// Instantiates this definition after resolving the importing module's types.
- pub(crate) fn instantiate_for_import(&self, store: &mut Store, type_addrs: &[TypeAddr]) -> Result<Function> {
+ /// Resolves the importing module's types without allocating a function instance.
+ pub(crate) fn resolve_import_type(&self, type_addrs: &[TypeAddr]) -> Result<FuncType> {
+ let mut types = self.0.ty.params().iter().chain(self.0.ty.results());
+ if types.all(|ty| !matches!(ty, WasmType::Ref(ty) if ty.is_concrete())) {
+ return Ok(self.0.ty.clone());
+ }
let resolve = |ty: WasmType| -> Result<WasmType> {
let WasmType::Ref(ref_ty) = ty else { return Ok(ty) };
let Some(module_addr) = ref_ty.type_index() else { return Ok(ty) };
@@ -34,7 +38,7 @@ impl HostFunction {
};
let params = self.0.ty.params().iter().copied().map(resolve).collect::<Result<Vec<_>>>()?;
let results = self.0.ty.results().iter().copied().map(resolve).collect::<Result<Vec<_>>>()?;
- Ok(self.instantiate_canonical(store, &FuncType::new(&params, &results)))
+ Ok(FuncType::new(&params, &results))
}
/// Calls the host function through its untyped value interface.
@@ -111,7 +115,8 @@ impl HostFunction {
{
return Err(crate::Error::other("host function signature contains a concrete type from another store"));
}
- Ok(self.instantiate_canonical(store, &self.0.ty))
+ let type_addr = store.register_host_type(&self.0.ty);
+ Ok(self.instantiate_registered(store, type_addr))
}
/// Create a new untyped host function.
diff --git a/crates/tinywasm/src/imports.rs b/crates/tinywasm/src/imports.rs
index 8232a90..b8de4e0 100644
--- a/crates/tinywasm/src/imports.rs
+++ b/crates/tinywasm/src/imports.rs
@@ -168,8 +168,9 @@ impl Imports {
self
}
- pub(crate) fn take_defined(&self, import: &Import) -> Option<Extern> {
- self.externs.get(import.module.as_ref())?.get(import.name.as_ref()).cloned()
+ /// Returns an explicitly defined import without cloning its handle.
+ pub(crate) fn defined(&self, import: &Import) -> Option<&Extern> {
+ self.externs.get(import.module.as_ref())?.get(import.name.as_ref())
}
fn compare_types<T: PartialEq>(import: &Import, actual: &T, expected: &T) -> Result<()> {
@@ -247,27 +248,43 @@ impl Imports {
};
for import in &*module.imports {
- let (val, func_handle) = if let Some(defined) = self.take_defined(import) {
+ let val = if let Some(defined) = self.defined(import) {
match defined {
Extern::Global(global) => {
global.0.validate_store(store)?;
- (ExternVal::Global(global.0.addr), None)
+ ExternVal::Global(global.0.addr)
}
Extern::Table(table) => {
table.0.validate_store(store)?;
- (ExternVal::Table(table.0.addr), None)
+ ExternVal::Table(table.0.addr)
}
Extern::Memory(memory) => {
memory.0.validate_store(store)?;
- (ExternVal::Memory(memory.0.addr), None)
+ ExternVal::Memory(memory.0.addr)
+ }
+ Extern::Function(func) => {
+ func.item.validate_store(store)?;
+ ExternVal::Func(func.addr())
}
- Extern::Function(func) => (ExternVal::Func(func.addr()), Some(func)),
Extern::HostFunction(func) => {
- (ExternVal::Func(func.instantiate_for_import(store, type_addrs)?.addr()), None)
+ let ImportKind::Function(type_idx) = import.kind else {
+ cold_path();
+ return Err(LinkingError::incompatible_import_type(import).into());
+ };
+ let expected_type_addr = type_addrs
+ .get(type_idx as usize)
+ .ok_or_else(|| LinkingError::incompatible_import_type(import))?;
+ let actual_ty = func.resolve_import_type(type_addrs)?;
+ let actual_type_addr = store.register_host_type(&actual_ty);
+ if !store.state.type_addr_is_subtype(actual_type_addr, *expected_type_addr) {
+ cold_path();
+ return Err(LinkingError::incompatible_import_type(import).into());
+ }
+ ExternVal::Func(func.instantiate_registered(store, actual_type_addr).addr())
}
Extern::Tag(tag) => {
tag.0.validate_store(store)?;
- (ExternVal::Tag(tag.0.addr), None)
+ ExternVal::Tag(tag.0.addr)
}
}
} else {
@@ -276,7 +293,7 @@ impl Imports {
return Err(LinkingError::unknown_import(import).into());
};
instance.validate_store(store)?;
- (instance.export_addr(&import.name).ok_or_else(|| LinkingError::unknown_import(import))?, None)
+ instance.export_addr(&import.name).ok_or_else(|| LinkingError::unknown_import(import))?
};
if val.kind() != (&import.kind).into() {
@@ -317,9 +334,6 @@ impl Imports {
(ExternVal::Func(func_addr), ImportKind::Function(ty)) => {
let expected_type_addr =
type_addrs.get(*ty as usize).ok_or_else(|| LinkingError::incompatible_import_type(import))?;
- if let Some(func) = &func_handle {
- func.item.validate_store(store)?;
- }
if !store.state.type_addr_is_subtype(store.state.get_func(func_addr).type_addr, *expected_type_addr)
{
cold_path();
diff --git a/crates/tinywasm/src/interpreter/executor.rs b/crates/tinywasm/src/interpreter/executor.rs
index 22c8441..d9d00eb 100644
--- a/crates/tinywasm/src/interpreter/executor.rs
+++ b/crates/tinywasm/src/interpreter/executor.rs
@@ -1673,10 +1673,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
self.store.state.gc.copy_within(dst, src_index..src_end, dst_index).expect("live array range");
return Ok(());
}
- let mut values = Vec::new();
- values.try_reserve_exact(len).map_err(|_| Trap::OutOfMemory)?;
- values.extend_from_slice(&src_object.values[src_index..src_end]);
- self.store.state.gc.set_slice(dst, dst_index, &values).expect("live array range");
+ self.store.state.gc.copy_between(src, src_index..src_end, dst, dst_index).expect("live array ranges");
Ok(())
}
diff --git a/crates/tinywasm/src/interpreter/simd/mod.rs b/crates/tinywasm/src/interpreter/simd/mod.rs
index d54268f..406c0c7 100644
--- a/crates/tinywasm/src/interpreter/simd/mod.rs
+++ b/crates/tinywasm/src/interpreter/simd/mod.rs
@@ -3,8 +3,6 @@
#[macro_use]
mod macros;
mod instructions;
-#[cfg(test)]
-mod tests;
mod utils;
#[cfg(target_arch = "wasm32")]
diff --git a/crates/tinywasm/src/interpreter/simd/tests.rs b/crates/tinywasm/src/interpreter/simd/tests.rs
deleted file mode 100644
index 7400f6b..0000000
--- a/crates/tinywasm/src/interpreter/simd/tests.rs
+++ /dev/null
@@ -1,60 +0,0 @@
-use super::Value128;
-
-fn ref_swizzle(a: [u8; 16], idx: [u8; 16]) -> [u8; 16] {
- let mut out = [0u8; 16];
- for i in 0..16 {
- let j = idx[i];
- out[i] = if j < 16 { a[(j & 0x0f) as usize] } else { 0 };
- }
- out
-}
-
-fn ref_shuffle(a: [u8; 16], b: [u8; 16], idx: [u8; 16]) -> [u8; 16] {
- let mut out = [0u8; 16];
- for i in 0..16 {
- let j = idx[i] & 31;
- out[i] = if j < 16 { a[j as usize] } else { b[(j & 0x0f) as usize] };
- }
- out
-}
-
-#[test]
-fn swizzle_matches_reference() {
- let a = [0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff];
-
- for seed in 0u32..512 {
- let mut s = [0u8; 16];
- let mut x = seed.wrapping_mul(0x9e37_79b9).wrapping_add(0x7f4a_7c15);
- for byte in &mut s {
- x ^= x << 13;
- x ^= x >> 17;
- x ^= x << 5;
- *byte = (x & 0xff) as u8;
- }
-
- let got = Value128(a).i8x16_swizzle(Value128(s));
- let expected = ref_swizzle(a, s).into();
- assert_eq!(got, expected, "seed={seed}");
- }
-}
-
-#[test]
-fn shuffle_matches_reference() {
- let a = [0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f];
- let b = [0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf];
-
- for seed in 0u32..512 {
- let mut idx = [0u8; 16];
- let mut x = seed.wrapping_mul(0x85eb_ca6b).wrapping_add(0xc2b2_ae35);
- for byte in &mut idx {
- x ^= x << 13;
- x ^= x >> 17;
- x ^= x << 5;
- *byte = (x & 0xff) as u8;
- }
-
- let got = Value128::i8x16_shuffle(Value128(a), Value128(b), Value128(idx));
- let expected = ref_shuffle(a, b, idx).into();
- assert_eq!(got, expected, "seed={seed}");
- }
-}
diff --git a/crates/tinywasm/src/interpreter/stack/value_stack.rs b/crates/tinywasm/src/interpreter/stack/value_stack.rs
index 1824d20..ceea9eb 100644
--- a/crates/tinywasm/src/interpreter/stack/value_stack.rs
+++ b/crates/tinywasm/src/interpreter/stack/value_stack.rs
@@ -375,9 +375,7 @@ impl ValueStack {
WasmValue::I64(v) => self.stack_64.push(v as u64)?,
WasmValue::F32(v) => self.stack_32.push(v.to_bits())?,
WasmValue::F64(v) => self.stack_64.push(v.to_bits())?,
- WasmValue::Ref(v) => {
- self.stack_32.push(TinyWasmValue::from(WasmValue::Ref(v)).as_ref().unwrap().raw())?
- }
+ WasmValue::Ref(v) => self.stack_32.push(ValueRef::from(v).raw())?,
WasmValue::V128(v) => self.stack_128.push(v.into())?,
}
}
diff --git a/crates/tinywasm/src/interpreter/values.rs b/crates/tinywasm/src/interpreter/values.rs
index 6913605..b3382e8 100644
--- a/crates/tinywasm/src/interpreter/values.rs
+++ b/crates/tinywasm/src/interpreter/values.rs
@@ -87,55 +87,19 @@ impl From<RefValue> for ValueRef {
}
}
-#[allow(private_interfaces)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-/// A untyped WebAssembly value
-pub enum TinyWasmValue {
- /// A 32-bit value
+/// An untyped internal WebAssembly value.
+pub(crate) enum TinyWasmValue {
+ /// A 32-bit value.
Value32(Value32),
- /// A 64-bit value
+ /// A 64-bit value.
Value64(Value64),
- /// A 128-bit value
+ /// A 128-bit value.
Value128(Value128),
- /// A reference value
+ /// A reference value.
ValueRef(ValueRef),
}
-impl TinyWasmValue {
- /// Converts the value to a 32-bit value (returns None if the value is not a 32-bit value)
- pub fn as_32(self) -> Option<Value32> {
- match self {
- Self::Value32(v) => Some(v),
- _ => None,
- }
- }
-
- /// Converts the value to a 64-bit value (returns None if the value is not a 64-bit value)
- pub fn as_64(self) -> Option<Value64> {
- match self {
- Self::Value64(v) => Some(v),
- _ => None,
- }
- }
-
- /// Converts the value to a 128-bit value (returns None if the value is not a 128-bit value)
- pub fn as_128(self) -> Option<Value128> {
- match self {
- Self::Value128(v) => Some(v),
- _ => None,
- }
- }
-
- /// Converts the value to a reference value (returns None if the value is not a reference value)
- #[allow(private_interfaces, dead_code)]
- pub fn as_ref(self) -> Option<ValueRef> {
- match self {
- Self::ValueRef(v) => Some(v),
- _ => None,
- }
- }
-}
-
impl From<&WasmValue> for TinyWasmValue {
fn from(value: &WasmValue) -> Self {
match value {
diff --git a/crates/tinywasm/src/reference.rs b/crates/tinywasm/src/reference.rs
index 55f9e3b..dd31efa 100644
--- a/crates/tinywasm/src/reference.rs
+++ b/crates/tinywasm/src/reference.rs
@@ -369,7 +369,7 @@ impl Table {
}
let init = table_value_to_element(&store.state, ty.element_type, init).map_err(Error::from)?;
let addr = store.state.tables.len() as TableAddr;
- store.state.tables.push(TableInstance::new_with_init(ty, init)?);
+ store.state.tables.push(TableInstance::new(ty, init)?);
Ok(Self(StoreItem::new(store.id(), addr)))
}
diff --git a/crates/tinywasm/src/store/const_expr.rs b/crates/tinywasm/src/store/const_expr.rs
index 201a1e1..c371763 100644
--- a/crates/tinywasm/src/store/const_expr.rs
+++ b/crates/tinywasm/src/store/const_expr.rs
@@ -6,6 +6,42 @@ use super::{State, default_value};
use crate::interpreter::{TinyWasmValue, ValueRef};
use crate::{Error, Result, Trap};
+fn resolve<T: Copy>(items: &[T], index: u32, kind: &str) -> Result<T> {
+ items.get(index as usize).copied().ok_or_else(|| Error::Other(format!("{kind} {index} not found")))
+}
+
+fn pop_value(stack: &mut Vec<TinyWasmValue>, storage: StorageType) -> Result<TinyWasmValue> {
+ let value = stack.pop().ok_or_else(|| Error::other("const stack underflow"))?;
+ match (storage, value) {
+ (StorageType::I8, TinyWasmValue::Value32(value)) => Ok(TinyWasmValue::Value32(value as u8 as u32)),
+ (StorageType::I16, TinyWasmValue::Value32(value)) => Ok(TinyWasmValue::Value32(value as u16 as u32)),
+ (StorageType::Value(WasmType::I32 | WasmType::F32), value @ TinyWasmValue::Value32(_))
+ | (StorageType::Value(WasmType::I64 | WasmType::F64), value @ TinyWasmValue::Value64(_))
+ | (StorageType::Value(WasmType::V128), value @ TinyWasmValue::Value128(_))
+ | (StorageType::Value(WasmType::Ref(_)), value @ TinyWasmValue::ValueRef(_)) => Ok(value),
+ _ => Err(Error::other("type mismatch in GC constant")),
+ }
+}
+
+fn value_ref(value: &TinyWasmValue) -> Option<ValueRef> {
+ match value {
+ TinyWasmValue::ValueRef(value) => Some(*value),
+ _ => None,
+ }
+}
+
+fn alloc_object(
+ state: &mut State,
+ stack: &mut Vec<TinyWasmValue>,
+ type_addr: TypeAddr,
+ values: Vec<TinyWasmValue>,
+) -> Result<()> {
+ let roots = stack.iter().filter_map(value_ref).map(ValueRef::raw);
+ let reference = state.alloc_gc_object(type_addr, values, roots)?;
+ stack.push(TinyWasmValue::ValueRef(reference));
+ Ok(())
+}
+
#[inline]
pub(super) fn eval_const(
state: &mut State,
@@ -16,32 +52,6 @@ pub(super) fn eval_const(
) -> Result<TinyWasmValue> {
use ConstInstruction::*;
- let global_value = |state: &State, index: u32| -> Result<TinyWasmValue> {
- let addr =
- *global_addrs.get(index as usize).ok_or_else(|| Error::Other(format!("global {index} not found")))?;
- Ok(state.globals.get(addr))
- };
- let func_ref = |index: u32| -> Result<ValueRef> {
- let addr =
- *func_addrs.get(index as usize).ok_or_else(|| Error::Other(format!("function {index} not found")))?;
- Ok(ValueRef::from_category_addr(addr))
- };
- let type_addr = |index: TypeAddr| -> Result<TypeAddr> {
- type_addrs.get(index as usize).copied().ok_or_else(|| Error::other("GC constant type not found"))
- };
- let pop_value = |stack: &mut Vec<TinyWasmValue>, storage: StorageType| -> Result<TinyWasmValue> {
- let value = stack.pop().ok_or_else(|| Error::other("const stack underflow"))?;
- match (storage, value) {
- (StorageType::I8, TinyWasmValue::Value32(value)) => Ok(TinyWasmValue::Value32(value as u8 as u32)),
- (StorageType::I16, TinyWasmValue::Value32(value)) => Ok(TinyWasmValue::Value32(value as u16 as u32)),
- (StorageType::Value(WasmType::I32 | WasmType::F32), value @ TinyWasmValue::Value32(_))
- | (StorageType::Value(WasmType::I64 | WasmType::F64), value @ TinyWasmValue::Value64(_))
- | (StorageType::Value(WasmType::V128), value @ TinyWasmValue::Value128(_))
- | (StorageType::Value(WasmType::Ref(_)), value @ TinyWasmValue::ValueRef(_)) => Ok(value),
- _ => Err(Error::other("type mismatch in GC constant")),
- }
- };
-
if let [instruction] = instructions {
match instruction {
I32Const(value) => return Ok(TinyWasmValue::Value32(*value as u32)),
@@ -49,9 +59,24 @@ pub(super) fn eval_const(
F32Const(value) => return Ok(TinyWasmValue::Value32(value.to_bits())),
F64Const(value) => return Ok(TinyWasmValue::Value64(value.to_bits())),
V128Const(value) => return Ok(TinyWasmValue::Value128((*value).into())),
- GlobalGet(index) => return global_value(state, *index),
+ GlobalGet32(index) => {
+ return Ok(TinyWasmValue::Value32(state.globals.get_32(resolve(global_addrs, *index, "global")?)));
+ }
+ GlobalGet64(index) => {
+ return Ok(TinyWasmValue::Value64(state.globals.get_64(resolve(global_addrs, *index, "global")?)));
+ }
+ GlobalGet128(index) => {
+ return Ok(TinyWasmValue::Value128(state.globals.get_128(resolve(global_addrs, *index, "global")?)));
+ }
+ GlobalGetRef(index) => {
+ let value = state.globals.get_32(resolve(global_addrs, *index, "global")?);
+ return Ok(TinyWasmValue::ValueRef(ValueRef::from_raw(value)));
+ }
Ref(RefValue::Null) => return Ok(TinyWasmValue::ValueRef(ValueRef::NULL)),
- Ref(RefValue::Func(func)) => return Ok(TinyWasmValue::ValueRef(func_ref(func.addr())?)),
+ Ref(RefValue::Func(func)) => {
+ let addr = resolve(func_addrs, func.addr(), "function")?;
+ return Ok(TinyWasmValue::ValueRef(ValueRef::from_category_addr(addr)));
+ }
_ => {}
}
}
@@ -64,9 +89,24 @@ pub(super) fn eval_const(
F32Const(value) => stack.push(TinyWasmValue::Value32(value.to_bits())),
F64Const(value) => stack.push(TinyWasmValue::Value64(value.to_bits())),
V128Const(value) => stack.push(TinyWasmValue::Value128((*value).into())),
- GlobalGet(index) => stack.push(global_value(state, *index)?),
+ GlobalGet32(index) => {
+ stack.push(TinyWasmValue::Value32(state.globals.get_32(resolve(global_addrs, *index, "global")?)));
+ }
+ GlobalGet64(index) => {
+ stack.push(TinyWasmValue::Value64(state.globals.get_64(resolve(global_addrs, *index, "global")?)));
+ }
+ GlobalGet128(index) => {
+ stack.push(TinyWasmValue::Value128(state.globals.get_128(resolve(global_addrs, *index, "global")?)));
+ }
+ GlobalGetRef(index) => {
+ let value = state.globals.get_32(resolve(global_addrs, *index, "global")?);
+ stack.push(TinyWasmValue::ValueRef(ValueRef::from_raw(value)));
+ }
Ref(RefValue::Null) => stack.push(TinyWasmValue::ValueRef(ValueRef::NULL)),
- Ref(RefValue::Func(func)) => stack.push(TinyWasmValue::ValueRef(func_ref(func.addr())?)),
+ Ref(RefValue::Func(func)) => {
+ let addr = resolve(func_addrs, func.addr(), "function")?;
+ stack.push(TinyWasmValue::ValueRef(ValueRef::from_category_addr(addr)));
+ }
Ref(_) => {
cold_path();
return Err(Error::other("unsupported reference constant"));
@@ -86,13 +126,13 @@ pub(super) fn eval_const(
stack.push(value);
}
StructNew(type_index) | StructNewDefault(type_index) => {
- let type_addr = type_addr(*type_index)?;
+ let type_addr = resolve(type_addrs, *type_index, "type")?;
let fields = state
.get_type(type_addr)
.as_struct()
.ok_or_else(|| Error::other("GC constant type is not a struct"))?
.fields
- .clone();
+ .as_ref();
let default = matches!(instruction, StructNewDefault(_));
let mut values = Vec::new();
values.try_reserve_exact(fields.len()).map_err(|_| Trap::OutOfMemory)?;
@@ -104,12 +144,10 @@ pub(super) fn eval_const(
}
values.reverse();
}
- let roots = stack.iter().filter_map(|value| value.as_ref()).map(ValueRef::raw);
- let reference = state.alloc_gc_object(type_addr, values, roots)?;
- stack.push(TinyWasmValue::ValueRef(reference));
+ alloc_object(state, &mut stack, type_addr, values)?;
}
ArrayNew(type_index) | ArrayNewDefault(type_index) => {
- let type_addr = type_addr(*type_index)?;
+ let type_addr = resolve(type_addrs, *type_index, "type")?;
let storage = state
.get_type(type_addr)
.as_array()
@@ -127,12 +165,10 @@ pub(super) fn eval_const(
let mut values = Vec::new();
values.try_reserve_exact(len as usize).map_err(|_| Trap::OutOfMemory)?;
values.resize(len as usize, value);
- let roots = stack.iter().filter_map(|value| value.as_ref()).map(ValueRef::raw);
- let reference = state.alloc_gc_object(type_addr, values, roots)?;
- stack.push(TinyWasmValue::ValueRef(reference));
+ alloc_object(state, &mut stack, type_addr, values)?;
}
ArrayNewFixed(type_index, len) => {
- let type_addr = type_addr(*type_index)?;
+ let type_addr = resolve(type_addrs, *type_index, "type")?;
let storage = state
.get_type(type_addr)
.as_array()
@@ -145,9 +181,7 @@ pub(super) fn eval_const(
values.push(pop_value(&mut stack, storage)?);
}
values.reverse();
- let roots = stack.iter().filter_map(|value| value.as_ref()).map(ValueRef::raw);
- let reference = state.alloc_gc_object(type_addr, values, roots)?;
- stack.push(TinyWasmValue::ValueRef(reference));
+ alloc_object(state, &mut stack, type_addr, values)?;
}
I32Add | I32Sub | I32Mul => {
let rhs = stack.pop().ok_or_else(|| Error::other("const stack underflow"))?;
diff --git a/crates/tinywasm/src/store/gc/arena.rs b/crates/tinywasm/src/store/gc/arena.rs
index b8f5961..6238466 100644
--- a/crates/tinywasm/src/store/gc/arena.rs
+++ b/crates/tinywasm/src/store/gc/arena.rs
@@ -139,6 +139,21 @@ impl<T> Arena<T> {
}
}
+ /// Returns exclusive references for two distinct live handles.
+ pub(crate) fn get_disjoint_mut(&mut self, first: Handle, second: Handle) -> Option<(&mut T, &mut T)> {
+ let [first_slot, second_slot] =
+ self.slots.get_disjoint_mut([first.index as usize, second.index as usize]).ok()?;
+ if first_slot.generation != first.generation || second_slot.generation != second.generation {
+ return None;
+ }
+ match (&mut first_slot.state, &mut second_slot.state) {
+ (SlotState::Occupied { value: first, .. }, SlotState::Occupied { value: second, .. }) => {
+ Some((first, second))
+ }
+ _ => None,
+ }
+ }
+
/// Returns whether an allocation of this size should trigger collection.
pub(crate) fn should_collect(&self, out_of_line_bytes: usize) -> bool {
size_of::<Slot<T>>()
diff --git a/crates/tinywasm/src/store/gc/object.rs b/crates/tinywasm/src/store/gc/object.rs
index a3c5440..4af64c9 100644
--- a/crates/tinywasm/src/store/gc/object.rs
+++ b/crates/tinywasm/src/store/gc/object.rs
@@ -94,7 +94,10 @@ impl GcHeap {
}
pub(crate) fn set(&mut self, object: ValueRef, index: usize, value: TinyWasmValue) -> Option<()> {
- let reference = value.as_ref().and_then(|value| self.handle(value));
+ let reference = match value {
+ TinyWasmValue::ValueRef(value) => self.handle(value),
+ _ => None,
+ };
let object = self.get_mut(object)?;
*object.values.get_mut(index)? = value;
if let Some(references) = &mut object.references {
@@ -112,11 +115,14 @@ impl GcHeap {
object.values.get_mut(index..end)?.copy_from_slice(values);
if let Some(references) = &mut object.references {
for (reference, value) in references[index..end].iter_mut().zip(values) {
- *reference = value.as_ref().and_then(|value| {
- let key = value.addr()?;
- let index = directory.binary_search_by_key(&key, |entry| entry.0).ok()?;
- Some(directory[index].1)
- });
+ *reference = match value {
+ TinyWasmValue::ValueRef(value) => {
+ let key = value.addr();
+ key.and_then(|key| directory.binary_search_by_key(&key, |entry| entry.0).ok())
+ .map(|index| directory[index].1)
+ }
+ _ => None,
+ };
}
}
Some(())
@@ -129,7 +135,10 @@ impl GcHeap {
range: core::ops::Range<usize>,
value: TinyWasmValue,
) -> Option<()> {
- let reference = value.as_ref().and_then(|value| self.handle(value));
+ let reference = match value {
+ TinyWasmValue::ValueRef(value) => self.handle(value),
+ _ => None,
+ };
let object = self.get_mut(object)?;
object.values.get_mut(range.clone())?.fill(value);
if let Some(references) = &mut object.references {
@@ -176,6 +185,30 @@ impl GcHeap {
}
Some(())
}
+
+ /// Copies values and tracing metadata between two distinct objects.
+ pub(crate) fn copy_between(
+ &mut self,
+ src: ValueRef,
+ src_range: core::ops::Range<usize>,
+ dst: ValueRef,
+ dst_index: usize,
+ ) -> Option<()> {
+ let src = self.handle(src)?;
+ let dst = self.handle(dst)?;
+ let (src, dst) = self.objects.get_disjoint_mut(src, dst)?;
+ let src_values = src.values.get(src_range.clone())?;
+ let dst_end = dst_index.checked_add(src_values.len())?;
+ dst.values.get_mut(dst_index..dst_end)?.copy_from_slice(src_values);
+ if let Some(dst_refs) = &mut dst.references {
+ if let Some(src_refs) = &src.references {
+ dst_refs[dst_index..dst_end].copy_from_slice(&src_refs[src_range]);
+ } else {
+ dst_refs[dst_index..dst_end].fill(None);
+ }
+ }
+ Some(())
+ }
}
#[cfg(test)]
diff --git a/crates/tinywasm/src/store/global.rs b/crates/tinywasm/src/store/global.rs
index 638b01d..69e538f 100644
--- a/crates/tinywasm/src/store/global.rs
+++ b/crates/tinywasm/src/store/global.rs
@@ -1,7 +1,7 @@
use alloc::vec::Vec;
use tinywasm_types::*;
-use crate::interpreter::{TinyWasmValue, Value32, Value64, Value128, ValueRef};
+use crate::interpreter::{TinyWasmValue, Value32, Value64, Value128};
struct GlobalLane<T> {
values: Vec<T>,
@@ -116,28 +116,6 @@ impl Globals {
}
}
- /// Returns a dynamically represented global value.
- pub(crate) fn get(&self, addr: GlobalAddr) -> TinyWasmValue {
- let ty = self.ty(addr);
- match ty.ty {
- WasmType::I32 | WasmType::F32 => TinyWasmValue::Value32(self.get_32(addr)),
- WasmType::I64 | WasmType::F64 => TinyWasmValue::Value64(self.get_64(addr)),
- WasmType::Ref(_) => TinyWasmValue::ValueRef(ValueRef::from_raw(self.get_32(addr))),
- WasmType::V128 => TinyWasmValue::Value128(self.get_128(addr)),
- }
- }
-
- /// Sets a global from a dynamically represented value.
- pub(crate) fn set(&mut self, addr: GlobalAddr, value: TinyWasmValue) {
- match (self.ty(addr).ty, value) {
- (WasmType::I32 | WasmType::F32, TinyWasmValue::Value32(value)) => self.set_32(addr, value),
- (WasmType::Ref(_), TinyWasmValue::ValueRef(value)) => self.set_32(addr, value.raw()),
- (WasmType::I64 | WasmType::F64, TinyWasmValue::Value64(value)) => self.set_64(addr, value),
- (WasmType::V128, TinyWasmValue::Value128(value)) => self.set_128(addr, value),
- _ => unreachable!("global value does not match its declared type"),
- }
- }
-
/// Returns a raw value from the 32-bit lane.
#[inline(always)]
pub(crate) fn get_32(&self, addr: GlobalAddr) -> Value32 {
@@ -175,7 +153,7 @@ impl Globals {
}
/// Iterates over globals in the 32-bit lane for root tracing.
- pub(crate) fn globals_32(&self) -> impl Iterator<Item = (Value32, GlobalType)> + '_ {
- self.globals_32.values.iter().copied().zip(self.globals_32.types.iter().copied())
+ pub(crate) fn globals_32(&self) -> impl Iterator<Item = (&Value32, &GlobalType)> {
+ self.globals_32.values.iter().zip(&self.globals_32.types)
}
}
diff --git a/crates/tinywasm/src/store/memory/mod.rs b/crates/tinywasm/src/store/memory/mod.rs
index 5805c86..f25d4ae 100644
--- a/crates/tinywasm/src/store/memory/mod.rs
+++ b/crates/tinywasm/src/store/memory/mod.rs
@@ -436,185 +436,3 @@ impl MemValue<16> for Value128 {
const fn memory_oob(offset: usize, len: usize, max: usize) -> crate::Trap {
crate::Trap::MemoryOutOfBounds { offset, len, max }
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use tinywasm_types::MemoryArch;
-
- fn create_test_memory(kind: MemoryType, backend: MemoryBackend) -> MemoryInstance {
- MemoryInstance::new(kind, &backend).unwrap()
- }
-
- fn test_backends() -> [MemoryBackend; 2] {
- [MemoryBackend::vec(), MemoryBackend::paged(4)]
- }
-
- #[test]
- fn effective_memory_addresses_handle_host_and_wasm_overflow() {
- let memory = create_test_memory(MemoryType::new(MemoryArch::I32, 1, Some(1), None), MemoryBackend::vec());
- assert_eq!(memory.effective_addr_32::<1>(1, 2), Ok(3));
- assert_eq!(memory.effective_addr_64::<1>(1, 2), Ok(3));
- assert!(memory.effective_addr_64::<1>(u64::MAX, 1).is_err());
-
- #[cfg(target_pointer_width = "64")]
- assert_eq!(
- memory.effective_addr_32::<1>(u32::MAX, u64::from(u32::MAX)),
- Ok(usize::try_from(u64::from(u32::MAX) * 2).unwrap())
- );
-
- #[cfg(target_pointer_width = "32")]
- assert!(memory.effective_addr_32::<1>(u32::MAX, 1).is_err());
- }
-
- #[test]
- fn memory_copy_from_slice_and_read_vec_work() {
- for backend in test_backends() {
- let kind = MemoryType::new(MemoryArch::I32, 1, Some(2), None);
- let mut memory = create_test_memory(kind, backend);
- let data = [1, 2, 3, 4];
- assert!(memory.inner.write_all(0, &data).is_some());
- assert_eq!(memory.inner.read_vec(0, data.len()).unwrap(), data);
- }
- }
-
- #[test]
- fn memory_read_returns_partial_count() {
- for backend in test_backends() {
- let kind = MemoryType::new(MemoryArch::I32, 1, Some(1), Some(4));
- let memory = create_test_memory(kind, backend);
- let mut dst = [9; 8];
- assert_eq!(memory.inner.read(2, &mut dst), 2);
- assert_eq!(&dst[..2], &[0, 0]);
- assert_eq!(&dst[2..], &[9; 6]);
- }
- }
-
- #[test]
- fn memory_copy_from_slice_out_of_bounds_fails() {
- for backend in test_backends() {
- let kind = MemoryType::new(MemoryArch::I32, 1, Some(2), None);
- let mut memory = create_test_memory(kind, backend);
- let data = [1, 2, 3, 4];
- let len = memory.inner.len();
- assert!(memory.inner.write_all(len, &data).is_none());
- }
- }
-
- #[test]
- fn fixed_width_access_out_of_bounds_traps() {
- for backend in test_backends() {
- let kind = MemoryType::new(MemoryArch::I32, 1, Some(2), None);
- let mut memory = create_test_memory(kind, backend);
- let len = memory.inner.len();
-
- assert!(memory.inner.read_8(len).is_err());
- assert!(memory.inner.read_32(len - 3).is_err());
- assert!(memory.inner.write_8(len, &[0]).is_err());
- assert!(memory.inner.write_32(len - 3, &[0; 4]).is_err());
- }
- }
-
- #[test]
- fn memory_fill_works() {
- for backend in test_backends() {
- let kind = MemoryType::new(MemoryArch::I32, 1, Some(2), None);
- let mut memory = create_test_memory(kind, backend);
- assert!(memory.inner.fill(0, 10, 42).is_some());
- assert_eq!(memory.inner.read_vec(0, 10).unwrap(), vec![42; 10]);
- }
- }
-
- #[test]
- fn memory_fill_out_of_bounds_fails() {
- for backend in test_backends() {
- let kind = MemoryType::new(MemoryArch::I32, 1, Some(2), None);
- let mut memory = create_test_memory(kind, backend);
- let len = memory.inner.len();
- assert!(memory.inner.fill(len, 10, 42).is_none());
- }
- }
-
- #[test]
- fn memory_copy_within_works() {
- for backend in test_backends() {
- let kind = MemoryType::new(MemoryArch::I32, 1, Some(2), None);
- let mut memory = create_test_memory(kind, backend);
- memory.inner.fill(0, 10, 1).unwrap();
- assert!(memory.copy_within(10, 0, 10).is_ok());
- assert_eq!(memory.inner.read_vec(10, 10).unwrap(), vec![1; 10]);
- }
- }
-
- #[test]
- fn memory_copy_within_out_of_bounds_fails() {
- for backend in test_backends() {
- let kind = MemoryType::new(MemoryArch::I32, 1, Some(2), None);
- let mut memory = create_test_memory(kind, backend);
- assert!(memory.copy_within(memory.inner.len(), 0, 10).is_err());
- }
- }
-
- #[test]
- fn memory_grow_works() {
- for backend in test_backends() {
- let kind = MemoryType::new(MemoryArch::I32, 1, Some(2), None);
- let mut memory = create_test_memory(kind, backend);
- let original_pages = memory.page_count;
- assert_eq!(memory.grow(1, false).unwrap(), Some(original_pages as i64));
- assert_eq!(memory.page_count, original_pages + 1);
- }
- }
-
- #[test]
- fn memory_grow_out_of_bounds_fails() {
- for backend in test_backends() {
- let kind = MemoryType::new(MemoryArch::I32, 1, Some(2), None);
- let mut memory = create_test_memory(kind, backend);
- assert_eq!(memory.grow(memory.kind.max_size() as i64 + 1, false).unwrap(), None);
- }
- }
-
- #[test]
- fn memory_grow_respects_max_pages() {
- for backend in test_backends() {
- let kind = MemoryType::new(MemoryArch::I32, 1, Some(2), None);
- let mut memory = create_test_memory(kind, backend);
- assert_eq!(memory.grow(1, false).unwrap(), Some(1));
- assert_eq!(memory.grow(1, false).unwrap(), None);
- }
- }
-
- #[test]
- fn memory_grow_negative_delta_fails() {
- for backend in test_backends() {
- let kind = MemoryType::new(MemoryArch::I32, 1, Some(2), None);
- let mut memory = create_test_memory(kind, backend);
- let original_pages = memory.page_count;
- assert_eq!(memory.grow(-1, false).unwrap(), None);
- assert_eq!(memory.page_count, original_pages);
- }
- }
-
- #[test]
- fn memory_custom_page_size_out_of_bounds_fails() {
- for backend in test_backends() {
- let kind = MemoryType::new(MemoryArch::I32, 1, Some(2), Some(1));
- let mut memory = create_test_memory(kind, backend);
- let data = [1, 2];
- assert!(memory.inner.write_all(0, &data).is_none());
- }
- }
-
- #[test]
- fn memory_custom_page_size_grow_works() {
- for backend in test_backends() {
- let kind = MemoryType::new(MemoryArch::I32, 1, Some(2), Some(1));
- let mut memory = create_test_memory(kind, backend);
- assert_eq!(memory.grow(1, false).unwrap(), Some(1));
- let data = [1, 2];
- assert!(memory.inner.write_all(0, &data).is_some());
- assert_eq!(memory.inner.read_vec(0, data.len()).unwrap(), data);
- }
- }
-}
diff --git a/crates/tinywasm/src/store/memory/paged.rs b/crates/tinywasm/src/store/memory/paged.rs
index 6ae65af..fc5947c 100644
--- a/crates/tinywasm/src/store/memory/paged.rs
+++ b/crates/tinywasm/src/store/memory/paged.rs
@@ -297,48 +297,3 @@ impl LinearMemory for PagedMemory {
Ok(())
}
}
-
-#[cfg(test)]
-mod tests {
- use super::{LinearMemory, PagedMemory};
-
- #[test]
- fn paged_memory_reads_zeroes_from_sparse_chunks() {
- let memory = PagedMemory::try_new(16, 4).expect("test memory should be constructible");
- let mut dst = [1; 6];
- assert_eq!(memory.read(5, &mut dst), 3);
- assert_eq!(&dst[..3], &[0; 3]);
- assert_eq!(&dst[3..], &[1; 3]);
- }
-
- #[test]
- fn paged_memory_store_and_load_crosses_chunk_boundaries() {
- let mut memory = PagedMemory::try_new(16, 4).expect("test memory should be constructible");
- memory.write_all(3, &[1, 2, 3, 4, 5, 6]).unwrap();
-
- let mut dst = [0; 6];
- memory.read_exact(3, &mut dst).unwrap();
- assert_eq!(dst, [1, 2, 3, 4, 5, 6]);
- }
-
- #[test]
- fn paged_memory_copy_within_handles_overlap() {
- let mut memory = PagedMemory::try_new(16, 4).expect("test memory should be constructible");
- memory.write_all(0, &[1, 2, 3, 4, 5, 6]).unwrap();
- memory.copy_within(2, 0, 6).unwrap();
-
- let mut dst = [0; 8];
- memory.read_exact(0, &mut dst).unwrap();
- assert_eq!(dst, [1, 2, 1, 2, 3, 4, 5, 6]);
- }
-
- #[test]
- fn paged_memory_write_stops_at_chunk_boundary() {
- let mut memory = PagedMemory::try_new(16, 4).expect("test memory should be constructible");
- assert_eq!(memory.write(3, &[1, 2, 3, 4]), 1);
-
- let mut dst = [0; 4];
- memory.read_exact(3, &mut dst).unwrap();
- assert_eq!(dst, [1, 0, 0, 0]);
- }
-}
diff --git a/crates/tinywasm/src/store/mod.rs b/crates/tinywasm/src/store/mod.rs
index 84a52b5..1aabfb3 100644
--- a/crates/tinywasm/src/store/mod.rs
+++ b/crates/tinywasm/src/store/mod.rs
@@ -122,18 +122,6 @@ impl Store {
self.module_instances.push(instance);
}
- /// Gets a global by its opaque store address.
- #[doc(hidden)]
- pub fn get_global_val(&self, addr: GlobalAddr) -> TinyWasmValue {
- self.state.globals.get(addr)
- }
-
- /// Sets a global by its opaque store address.
- #[doc(hidden)]
- pub fn set_global_val(&mut self, addr: GlobalAddr, value: TinyWasmValue) {
- self.state.globals.set(addr, value);
- }
-
/// Returns whether a public value has the requested runtime type.
#[doc(hidden)]
pub fn value_matches_type(&self, value: WasmValue, ty: WasmType) -> bool {
@@ -264,7 +252,7 @@ impl Store {
MemoryArch::I32 => TableType::new(element_type, table.ty.size_initial, table.ty.size_max),
MemoryArch::I64 => TableType::new64(element_type, table.ty.size_initial, table.ty.size_max),
};
- self.state.tables.push(TableInstance::new_with_init(ty, init)?);
+ self.state.tables.push(TableInstance::new(ty, init)?);
}
Ok(start..start + tables.len() as TableAddr)
}
diff --git a/crates/tinywasm/src/store/state.rs b/crates/tinywasm/src/store/state.rs
index e6a213f..e12ef1a 100644
--- a/crates/tinywasm/src/store/state.rs
+++ b/crates/tinywasm/src/store/state.rs
@@ -92,7 +92,7 @@ impl State {
self.globals
.globals_32()
.filter(|(_, ty)| Self::type_may_contain_gc_in(canonical_types, &ty.ty))
- .map(|(value, _)| ValueRef::from_raw(value)),
+ .map(|(value, _)| ValueRef::from_raw(*value)),
)
.chain(
self.tables
@@ -108,12 +108,16 @@ impl State {
.filter(|element| Self::type_may_contain_gc_in(canonical_types, &WasmType::Ref(element.ty)))
.flat_map(|element| element.items.iter().flatten().copied()),
)
- .chain(
- self.exceptions
- .iter()
- .flat_map(|exception| exception.payload.iter().filter_map(|value| value.as_ref())),
- )
- .chain(values.iter().filter_map(|value| value.as_ref()));
+ .chain(self.exceptions.iter().flat_map(|exception| {
+ exception.payload.iter().filter_map(|value| match value {
+ TinyWasmValue::ValueRef(value) => Some(*value),
+ _ => None,
+ })
+ }))
+ .chain(values.iter().filter_map(|value| match value {
+ TinyWasmValue::ValueRef(value) => Some(*value),
+ _ => None,
+ }));
self.gc.collect(roots).map_err(|_| Trap::OutOfMemory)?;
}
self.gc.alloc(type_addr, values, trace_references).map_err(|_| Trap::OutOfMemory)
@@ -270,7 +274,7 @@ impl State {
let actual = RefType::new_concrete(false, func.type_addr).expect("canonical type fits");
return self.ref_type_is_subtype(actual, expected);
}
- if expected.is_exn() {
+ if expected.abstract_heap_type() == Some(AbstractHeapType::Exn) {
return value.addr().is_some_and(|addr| self.exceptions.get(addr as usize).is_some());
}
if value.is_i31() {
@@ -316,8 +320,9 @@ impl State {
{
false
}
- (WasmValue::Ref(RefValue::Exn(value)), WasmType::Ref(expected)) if expected.is_exn() => {
- self.exceptions.get(value.addr() as usize).is_some()
+ (WasmValue::Ref(RefValue::Exn(value)), WasmType::Ref(expected)) => {
+ expected.abstract_heap_type() == Some(AbstractHeapType::Exn)
+ && self.exceptions.get(value.addr() as usize).is_some()
}
(WasmValue::Ref(RefValue::Any(value)), WasmType::Ref(expected)) => {
self.value_ref_matches(ValueRef::from_raw(value.raw()), expected)
diff --git a/crates/tinywasm/src/store/table.rs b/crates/tinywasm/src/store/table.rs
index ece0001..5cbce74 100644
--- a/crates/tinywasm/src/store/table.rs
+++ b/crates/tinywasm/src/store/table.rs
@@ -15,12 +15,8 @@ pub(crate) struct TableInstance {
}
impl TableInstance {
- #[cfg(test)]
- pub(crate) fn new(kind: TableType) -> Result<Self> {
- Self::new_with_init(kind, ValueRef::NULL)
- }
-
- pub(crate) fn new_with_init(kind: TableType, init: ValueRef) -> Result<Self> {
+ /// Creates a table filled with the given initial reference.
+ pub(crate) fn new(kind: TableType, init: ValueRef) -> Result<Self> {
let size = usize::try_from(kind.size_initial).map_err(|_| Trap::OutOfMemory)?;
if size > MAX_TABLE_SIZE {
return Err(Trap::OutOfMemory.into());
@@ -101,50 +97,3 @@ impl TableInstance {
Ok(())
}
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use alloc::vec;
-
- // Helper to create a dummy TableType
- fn dummy_table_type() -> TableType {
- TableType::new(RefType::FUNCREF, 10, Some(20))
- }
-
- #[test]
- fn test_table_instance_creation() {
- let kind = dummy_table_type();
- let table_instance = TableInstance::new(kind).unwrap();
- assert_eq!(table_instance.size() as u64, kind.size_initial, "Table instance creation failed: size mismatch");
- }
-
- #[test]
- fn test_set_and_get() {
- let kind = dummy_table_type();
- let mut table_instance = TableInstance::new(kind).unwrap();
-
- let value = ValueRef::from_raw(2);
- let result = table_instance.set(0, value);
- assert!(result.is_ok(), "Setting table element failed");
-
- let elem = table_instance.get(0);
- assert!(elem.is_ok() && elem.unwrap() == &value, "Getting table element failed or returned incorrect value");
- }
-
- #[test]
- fn test_table_init() {
- let kind = dummy_table_type();
- let mut table_instance = TableInstance::new(kind).unwrap();
-
- let init_elements = vec![ValueRef::from_raw(2); 5];
- let result = table_instance.init(0, &init_elements);
-
- assert!(result.is_ok(), "Initializing table with elements failed");
-
- for i in 0..5 {
- let elem = table_instance.get(i);
- assert!(elem.is_ok() && !elem.unwrap().is_null(), "Element not initialized correctly at index {i}");
- }
- }
-}
diff --git a/crates/tinywasm/tests/generated/wasm-annotations.csv b/crates/tinywasm/tests/generated/wasm-annotations.csv
deleted file mode 100644
index f24ba50..0000000
--- a/crates/tinywasm/tests/generated/wasm-annotations.csv
+++ /dev/null
@@ -1,5 +0,0 @@
-0.8.0,142,0,[{"name":"annotations.wast","passed":74,"failed":0},{"name":"annotations/simd_lane.wast (skipped)","passed":0,"failed":0},{"name":"id.wast","passed":7,"failed":0},{"name":"token.wast","passed":61,"failed":0}]
-0.9.0,617,0,[{"name":"annotations.wast","passed":74,"failed":0},{"name":"id.wast","passed":7,"failed":0},{"name":"simd_lane.wast","passed":475,"failed":0},{"name":"token.wast","passed":61,"failed":0}]
-0.9.1,617,0,[{"name":"annotations.wast","passed":74,"failed":0},{"name":"id.wast","passed":7,"failed":0},{"name":"simd_lane.wast","passed":475,"failed":0},{"name":"token.wast","passed":61,"failed":0}]
-0.10.0,617,0,[{"name":"annotations.wast","passed":74,"failed":0},{"name":"id.wast","passed":7,"failed":0},{"name":"simd_lane.wast","passed":475,"failed":0},{"name":"token.wast","passed":61,"failed":0}]
-0.11.0-pre.0,617,0,[{"name":"annotations.wast","passed":74,"failed":0},{"name":"id.wast","passed":7,"failed":0},{"name":"simd_lane.wast","passed":475,"failed":0},{"name":"token.wast","passed":61,"failed":0}]
diff --git a/crates/tinywasm/tests/generated/wasm-extended-const.csv b/crates/tinywasm/tests/generated/wasm-extended-const.csv
deleted file mode 100644
index 1e4e851..0000000
--- a/crates/tinywasm/tests/generated/wasm-extended-const.csv
+++ /dev/null
@@ -1,5 +0,0 @@
-0.8.0,211,79,[{"name":"data.wast","passed":61,"failed":4},{"name":"elem.wast","passed":99,"failed":12},{"name":"global.wast","passed":51,"failed":63}]
-0.9.0,290,0,[{"name":"data.wast","passed":65,"failed":0},{"name":"elem.wast","passed":111,"failed":0},{"name":"global.wast","passed":114,"failed":0}]
-0.9.1,290,0,[{"name":"data.wast","passed":65,"failed":0},{"name":"elem.wast","passed":111,"failed":0},{"name":"global.wast","passed":114,"failed":0}]
-0.10.0,290,0,[{"name":"data.wast","passed":65,"failed":0},{"name":"elem.wast","passed":111,"failed":0},{"name":"global.wast","passed":114,"failed":0}]
-0.11.0-pre.0,284,0,[{"name":"data.wast","passed":63,"failed":0},{"name":"elem.wast","passed":109,"failed":0},{"name":"global.wast","passed":112,"failed":0}]
diff --git a/crates/tinywasm/tests/generated/wasm-function-references.csv b/crates/tinywasm/tests/generated/wasm-function-references.csv
deleted file mode 100644
index 9d6dd64..0000000
--- a/crates/tinywasm/tests/generated/wasm-function-references.csv
+++ /dev/null
@@ -1,3 +0,0 @@
-0.9.0,1536,331,[{"name":"binary.wast","passed":128,"failed":0},{"name":"br_on_non_null.wast","passed":0,"failed":9},{"name":"br_on_null.wast","passed":0,"failed":9},{"name":"br_table.wast","passed":24,"failed":162},{"name":"call_ref.wast","passed":3,"failed":31},{"name":"data.wast","passed":59,"failed":0},{"name":"elem.wast","passed":138,"failed":0},{"name":"func.wast","passed":175,"failed":0},{"name":"global.wast","passed":108,"failed":0},{"name":"if.wast","passed":241,"failed":0},{"name":"linking.wast","passed":146,"failed":21},{"name":"local_get.wast","passed":36,"failed":0},{"name":"local_init.wast","passed":10,"failed":0},{"name":"ref.wast","passed":12,"failed":1},{"name":"ref_as_non_null.wast","passed":1,"failed":6},{"name":"ref_is_null.wast","passed":2,"failed":20},{"name":"ref_null.wast","passed":0,"failed":4},{"name":"return_call.wast","passed":45,"failed":0},{"name":"return_call_indirect.wast","passed":76,"failed":0},{"name":"return_call_ref.wast","passed":10,"failed":40},{"name":"select.wast","passed":155,"failed":2},{"name":"table-sub.wast","passed":2,"failed":1},{"name":"table.wast","passed":35,"failed":8},{"name":"type-equivalence.wast","passed":7,"failed":7},{"name":"unreached-invalid.wast","passed":121,"failed":0},{"name":"unreached-valid.wast","passed":2,"failed":10}]
-0.10.0,1536,331,[{"name":"binary.wast","passed":128,"failed":0},{"name":"br_on_non_null.wast","passed":0,"failed":9},{"name":"br_on_null.wast","passed":0,"failed":9},{"name":"br_table.wast","passed":24,"failed":162},{"name":"call_ref.wast","passed":3,"failed":31},{"name":"data.wast","passed":59,"failed":0},{"name":"elem.wast","passed":138,"failed":0},{"name":"func.wast","passed":175,"failed":0},{"name":"global.wast","passed":108,"failed":0},{"name":"if.wast","passed":241,"failed":0},{"name":"linking.wast","passed":146,"failed":21},{"name":"local_get.wast","passed":36,"failed":0},{"name":"local_init.wast","passed":10,"failed":0},{"name":"ref.wast","passed":12,"failed":1},{"name":"ref_as_non_null.wast","passed":1,"failed":6},{"name":"ref_is_null.wast","passed":2,"failed":20},{"name":"ref_null.wast","passed":0,"failed":4},{"name":"return_call.wast","passed":45,"failed":0},{"name":"return_call_indirect.wast","passed":76,"failed":0},{"name":"return_call_ref.wast","passed":10,"failed":40},{"name":"select.wast","passed":155,"failed":2},{"name":"table-sub.wast","passed":2,"failed":1},{"name":"table.wast","passed":35,"failed":8},{"name":"type-equivalence.wast","passed":7,"failed":7},{"name":"unreached-invalid.wast","passed":121,"failed":0},{"name":"unreached-valid.wast","passed":2,"failed":10}]
-0.11.0-pre.0,1866,0,[{"name":"binary.wast","passed":128,"failed":0},{"name":"br_on_non_null.wast","passed":9,"failed":0},{"name":"br_on_null.wast","passed":9,"failed":0},{"name":"br_table.wast","passed":186,"failed":0},{"name":"call_ref.wast","passed":34,"failed":0},{"name":"data.wast","passed":59,"failed":0},{"name":"elem.wast","passed":138,"failed":0},{"name":"func.wast","passed":175,"failed":0},{"name":"global.wast","passed":108,"failed":0},{"name":"if.wast","passed":241,"failed":0},{"name":"linking.wast","passed":167,"failed":0},{"name":"local_get.wast","passed":36,"failed":0},{"name":"local_init.wast","passed":10,"failed":0},{"name":"ref.wast","passed":13,"failed":0},{"name":"ref_as_non_null.wast","passed":7,"failed":0},{"name":"ref_is_null.wast","passed":22,"failed":0},{"name":"ref_null.wast","passed":4,"failed":0},{"name":"return_call.wast","passed":45,"failed":0},{"name":"return_call_indirect.wast","passed":76,"failed":0},{"name":"return_call_ref.wast","passed":50,"failed":0},{"name":"select.wast","passed":157,"failed":0},{"name":"table-sub.wast","passed":3,"failed":0},{"name":"table.wast","passed":43,"failed":0},{"name":"type-equivalence.wast","passed":13,"failed":0},{"name":"unreached-invalid.wast","passed":121,"failed":0},{"name":"unreached-valid.wast","passed":12,"failed":0}]
diff --git a/crates/tinywasm/tests/generated/wasm-nontrapping-float-to-int-conversions.csv b/crates/tinywasm/tests/generated/wasm-nontrapping-float-to-int-conversions.csv
deleted file mode 100644
index 66d5329..0000000
--- a/crates/tinywasm/tests/generated/wasm-nontrapping-float-to-int-conversions.csv
+++ /dev/null
@@ -1,4 +0,0 @@
-0.9.0,615,0,[{"name":"conversions.wast","passed":615,"failed":0}]
-0.9.1,615,0,[{"name":"conversions.wast","passed":615,"failed":0}]
-0.10.0,615,0,[{"name":"conversions.wast","passed":615,"failed":0}]
-0.11.0-pre.0,615,0,[{"name":"conversions.wast","passed":615,"failed":0}]
diff --git a/crates/tinywasm/tests/generated/wasm-reference-types.csv b/crates/tinywasm/tests/generated/wasm-reference-types.csv
deleted file mode 100644
index 92a4650..0000000
--- a/crates/tinywasm/tests/generated/wasm-reference-types.csv
+++ /dev/null
@@ -1,4 +0,0 @@
-0.9.0,9124,0,[{"name":"binary-leb128.wast","passed":77,"failed":0},{"name":"binary.wast","passed":134,"failed":0},{"name":"br_table.wast","passed":172,"failed":0},{"name":"bulk.wast","passed":117,"failed":0},{"name":"call_indirect.wast","passed":169,"failed":0},{"name":"custom.wast","passed":11,"failed":0},{"name":"data.wast","passed":45,"failed":0},{"name":"elem.wast","passed":60,"failed":0},{"name":"exports.wast","passed":84,"failed":0},{"name":"global.wast","passed":86,"failed":0},{"name":"imports.wast","passed":158,"failed":0},{"name":"linking.wast","passed":132,"failed":0},{"name":"memory_copy.wast","passed":4450,"failed":0},{"name":"memory_fill.wast","passed":100,"failed":0},{"name":"memory_grow.wast","passed":96,"failed":0},{"name":"memory_init.wast","passed":240,"failed":0},{"name":"ref_func.wast","passed":17,"failed":0},{"name":"ref_is_null.wast","passed":16,"failed":0},{"name":"ref_null.wast","passed":3,"failed":0},{"name":"select.wast","passed":141,"failed":0},{"name":"table-sub.wast","passed":2,"failed":0},{"name":"table.wast","passed":19,"failed":0},{"name":"table_copy.wast","passed":1728,"failed":0},{"name":"table_fill.wast","passed":45,"failed":0},{"name":"table_get.wast","passed":16,"failed":0},{"name":"table_grow.wast","passed":50,"failed":0},{"name":"table_init.wast","passed":780,"failed":0},{"name":"table_set.wast","passed":26,"failed":0},{"name":"table_size.wast","passed":39,"failed":0},{"name":"unreached-invalid.wast","passed":111,"failed":0}]
-0.9.1,9124,0,[{"name":"binary-leb128.wast","passed":77,"failed":0},{"name":"binary.wast","passed":134,"failed":0},{"name":"br_table.wast","passed":172,"failed":0},{"name":"bulk.wast","passed":117,"failed":0},{"name":"call_indirect.wast","passed":169,"failed":0},{"name":"custom.wast","passed":11,"failed":0},{"name":"data.wast","passed":45,"failed":0},{"name":"elem.wast","passed":60,"failed":0},{"name":"exports.wast","passed":84,"failed":0},{"name":"global.wast","passed":86,"failed":0},{"name":"imports.wast","passed":158,"failed":0},{"name":"linking.wast","passed":132,"failed":0},{"name":"memory_copy.wast","passed":4450,"failed":0},{"name":"memory_fill.wast","passed":100,"failed":0},{"name":"memory_grow.wast","passed":96,"failed":0},{"name":"memory_init.wast","passed":240,"failed":0},{"name":"ref_func.wast","passed":17,"failed":0},{"name":"ref_is_null.wast","passed":16,"failed":0},{"name":"ref_null.wast","passed":3,"failed":0},{"name":"select.wast","passed":141,"failed":0},{"name":"table-sub.wast","passed":2,"failed":0},{"name":"table.wast","passed":19,"failed":0},{"name":"table_copy.wast","passed":1728,"failed":0},{"name":"table_fill.wast","passed":45,"failed":0},{"name":"table_get.wast","passed":16,"failed":0},{"name":"table_grow.wast","passed":50,"failed":0},{"name":"table_init.wast","passed":780,"failed":0},{"name":"table_set.wast","passed":26,"failed":0},{"name":"table_size.wast","passed":39,"failed":0},{"name":"unreached-invalid.wast","passed":111,"failed":0}]
-0.10.0,9124,0,[{"name":"binary-leb128.wast","passed":77,"failed":0},{"name":"binary.wast","passed":134,"failed":0},{"name":"br_table.wast","passed":172,"failed":0},{"name":"bulk.wast","passed":117,"failed":0},{"name":"call_indirect.wast","passed":169,"failed":0},{"name":"custom.wast","passed":11,"failed":0},{"name":"data.wast","passed":45,"failed":0},{"name":"elem.wast","passed":60,"failed":0},{"name":"exports.wast","passed":84,"failed":0},{"name":"global.wast","passed":86,"failed":0},{"name":"imports.wast","passed":158,"failed":0},{"name":"linking.wast","passed":132,"failed":0},{"name":"memory_copy.wast","passed":4450,"failed":0},{"name":"memory_fill.wast","passed":100,"failed":0},{"name":"memory_grow.wast","passed":96,"failed":0},{"name":"memory_init.wast","passed":240,"failed":0},{"name":"ref_func.wast","passed":17,"failed":0},{"name":"ref_is_null.wast","passed":16,"failed":0},{"name":"ref_null.wast","passed":3,"failed":0},{"name":"select.wast","passed":141,"failed":0},{"name":"table-sub.wast","passed":2,"failed":0},{"name":"table.wast","passed":19,"failed":0},{"name":"table_copy.wast","passed":1728,"failed":0},{"name":"table_fill.wast","passed":45,"failed":0},{"name":"table_get.wast","passed":16,"failed":0},{"name":"table_grow.wast","passed":50,"failed":0},{"name":"table_init.wast","passed":780,"failed":0},{"name":"table_set.wast","passed":26,"failed":0},{"name":"table_size.wast","passed":39,"failed":0},{"name":"unreached-invalid.wast","passed":111,"failed":0}]
-0.11.0-pre.0,9124,0,[{"name":"binary-leb128.wast","passed":77,"failed":0},{"name":"binary.wast","passed":134,"failed":0},{"name":"br_table.wast","passed":172,"failed":0},{"name":"bulk.wast","passed":117,"failed":0},{"name":"call_indirect.wast","passed":169,"failed":0},{"name":"custom.wast","passed":11,"failed":0},{"name":"data.wast","passed":45,"failed":0},{"name":"elem.wast","passed":60,"failed":0},{"name":"exports.wast","passed":84,"failed":0},{"name":"global.wast","passed":86,"failed":0},{"name":"imports.wast","passed":158,"failed":0},{"name":"linking.wast","passed":132,"failed":0},{"name":"memory_copy.wast","passed":4450,"failed":0},{"name":"memory_fill.wast","passed":100,"failed":0},{"name":"memory_grow.wast","passed":96,"failed":0},{"name":"memory_init.wast","passed":240,"failed":0},{"name":"ref_func.wast","passed":17,"failed":0},{"name":"ref_is_null.wast","passed":16,"failed":0},{"name":"ref_null.wast","passed":3,"failed":0},{"name":"select.wast","passed":141,"failed":0},{"name":"table-sub.wast","passed":2,"failed":0},{"name":"table.wast","passed":19,"failed":0},{"name":"table_copy.wast","passed":1728,"failed":0},{"name":"table_fill.wast","passed":45,"failed":0},{"name":"table_get.wast","passed":16,"failed":0},{"name":"table_grow.wast","passed":50,"failed":0},{"name":"table_init.wast","passed":780,"failed":0},{"name":"table_set.wast","passed":26,"failed":0},{"name":"table_size.wast","passed":39,"failed":0},{"name":"unreached-invalid.wast","passed":111,"failed":0}]
diff --git a/crates/tinywasm/tests/generated/wasm-sign-extension-ops.csv b/crates/tinywasm/tests/generated/wasm-sign-extension-ops.csv
deleted file mode 100644
index 4e7e2ee..0000000
--- a/crates/tinywasm/tests/generated/wasm-sign-extension-ops.csv
+++ /dev/null
@@ -1,4 +0,0 @@
-0.9.0,872,0,[{"name":"i32.wast","passed":458,"failed":0},{"name":"i64.wast","passed":414,"failed":0}]
-0.9.1,872,0,[{"name":"i32.wast","passed":458,"failed":0},{"name":"i64.wast","passed":414,"failed":0}]
-0.10.0,872,0,[{"name":"i32.wast","passed":458,"failed":0},{"name":"i64.wast","passed":414,"failed":0}]
-0.11.0-pre.0,872,0,[{"name":"i32.wast","passed":458,"failed":0},{"name":"i64.wast","passed":414,"failed":0}]
diff --git a/crates/tinywasm/tests/generated/wasm-tail-call.csv b/crates/tinywasm/tests/generated/wasm-tail-call.csv
deleted file mode 100644
index 316895d..0000000
--- a/crates/tinywasm/tests/generated/wasm-tail-call.csv
+++ /dev/null
@@ -1,4 +0,0 @@
-0.9.0,119,0,[{"name":"return_call.wast","passed":44,"failed":0},{"name":"return_call_indirect.wast","passed":75,"failed":0}]
-0.9.1,119,0,[{"name":"return_call.wast","passed":44,"failed":0},{"name":"return_call_indirect.wast","passed":75,"failed":0}]
-0.10.0,119,0,[{"name":"return_call.wast","passed":44,"failed":0},{"name":"return_call_indirect.wast","passed":75,"failed":0}]
-0.11.0-pre.0,119,0,[{"name":"return_call.wast","passed":44,"failed":0},{"name":"return_call_indirect.wast","passed":75,"failed":0}]
diff --git a/crates/tinywasm/tests/test-wasm-annotations.rs b/crates/tinywasm/tests/test-wasm-annotations.rs
deleted file mode 100644
index 8655d15..0000000
--- a/crates/tinywasm/tests/test-wasm-annotations.rs
+++ /dev/null
@@ -1,13 +0,0 @@
-mod testsuite;
-use eyre::Result;
-use testsuite::TestSuite;
-use wasm_testsuite::data::{Proposal, proposal};
-
-fn main() -> Result<()> {
- TestSuite::set_log_level(log::LevelFilter::Off);
-
- let mut test_suite = TestSuite::new();
- test_suite.run_files(proposal(&Proposal::Annotations))?;
- test_suite.save_csv("./tests/generated/wasm-annotations.csv", env!("CARGO_PKG_VERSION"))?;
- test_suite.report_status()
-}
diff --git a/crates/tinywasm/tests/test-wasm-extended-const.rs b/crates/tinywasm/tests/test-wasm-extended-const.rs
deleted file mode 100644
index 888a49f..0000000
--- a/crates/tinywasm/tests/test-wasm-extended-const.rs
+++ /dev/null
@@ -1,13 +0,0 @@
-mod testsuite;
-use eyre::Result;
-use testsuite::TestSuite;
-use wasm_testsuite::data::{Proposal, proposal};
-
-fn main() -> Result<()> {
- TestSuite::set_log_level(log::LevelFilter::Off);
-
- let mut test_suite = TestSuite::new();
- test_suite.run_files(proposal(&Proposal::ExtendedConst))?;
- test_suite.save_csv("./tests/generated/wasm-extended-const.csv", env!("CARGO_PKG_VERSION"))?;
- test_suite.report_status()
-}
diff --git a/crates/tinywasm/tests/test-wasm-function-references.rs b/crates/tinywasm/tests/test-wasm-function-references.rs
deleted file mode 100644
index d91ff82..0000000
--- a/crates/tinywasm/tests/test-wasm-function-references.rs
+++ /dev/null
@@ -1,13 +0,0 @@
-mod testsuite;
-use eyre::Result;
-use testsuite::TestSuite;
-use wasm_testsuite::data::{Proposal, proposal};
-
-fn main() -> Result<()> {
- TestSuite::set_log_level(log::LevelFilter::Off);
-
- let mut test_suite = TestSuite::new();
- test_suite.run_files(proposal(&Proposal::FunctionReferences))?;
- test_suite.save_csv("./tests/generated/wasm-function-references.csv", env!("CARGO_PKG_VERSION"))?;
- test_suite.report_status()
-}
diff --git a/crates/tinywasm/tests/test-wasm-nontrapping-float-to-int-conversions.rs b/crates/tinywasm/tests/test-wasm-nontrapping-float-to-int-conversions.rs
deleted file mode 100644
index 0475fac..0000000
--- a/crates/tinywasm/tests/test-wasm-nontrapping-float-to-int-conversions.rs
+++ /dev/null
@@ -1,14 +0,0 @@
-mod testsuite;
-use eyre::Result;
-use testsuite::TestSuite;
-use wasm_testsuite::data::{Proposal, proposal};
-
-fn main() -> Result<()> {
- TestSuite::set_log_level(log::LevelFilter::Off);
- let mut test_suite = TestSuite::new();
-
- test_suite.run_files(proposal(&Proposal::NontrappingFloatToIntConversions))?;
- test_suite
- .save_csv("./tests/generated/wasm-nontrapping-float-to-int-conversions.csv", env!("CARGO_PKG_VERSION"))?;
- test_suite.report_status()
-}
diff --git a/crates/tinywasm/tests/test-wasm-reference-types.rs b/crates/tinywasm/tests/test-wasm-reference-types.rs
deleted file mode 100644
index b6f1155..0000000
--- a/crates/tinywasm/tests/test-wasm-reference-types.rs
+++ /dev/null
@@ -1,13 +0,0 @@
-mod testsuite;
-use eyre::Result;
-use testsuite::TestSuite;
-use wasm_testsuite::data::{Proposal, proposal};
-
-fn main() -> Result<()> {
- TestSuite::set_log_level(log::LevelFilter::Off);
- let mut test_suite = TestSuite::new();
-
- test_suite.run_files(proposal(&Proposal::ReferenceTypes))?;
- test_suite.save_csv("./tests/generated/wasm-reference-types.csv", env!("CARGO_PKG_VERSION"))?;
- test_suite.report_status()
-}
diff --git a/crates/tinywasm/tests/test-wasm-sign-extension-op.rs b/crates/tinywasm/tests/test-wasm-sign-extension-op.rs
deleted file mode 100644
index c0ef143..0000000
--- a/crates/tinywasm/tests/test-wasm-sign-extension-op.rs
+++ /dev/null
@@ -1,13 +0,0 @@
-mod testsuite;
-use eyre::Result;
-use testsuite::TestSuite;
-use wasm_testsuite::data::{Proposal, proposal};
-
-fn main() -> Result<()> {
- TestSuite::set_log_level(log::LevelFilter::Off);
- let mut test_suite = TestSuite::new();
-
- test_suite.run_files(proposal(&Proposal::SignExtensionOps))?;
- test_suite.save_csv("./tests/generated/wasm-sign-extension-ops.csv", env!("CARGO_PKG_VERSION"))?;
- test_suite.report_status()
-}
diff --git a/crates/tinywasm/tests/test-wasm-tail-call.rs b/crates/tinywasm/tests/test-wasm-tail-call.rs
deleted file mode 100644
index b6d8b2b..0000000
--- a/crates/tinywasm/tests/test-wasm-tail-call.rs
+++ /dev/null
@@ -1,14 +0,0 @@
-mod testsuite;
-use eyre::Result;
-use testsuite::TestSuite;
-use wasm_testsuite::data::{Proposal, proposal};
-
-fn main() -> Result<()> {
- TestSuite::set_log_level(log::LevelFilter::Off);
-
- let mut test_suite = TestSuite::new();
- test_suite.run_files(proposal(&Proposal::TailCall))?;
- test_suite.print_errors();
- test_suite.save_csv("./tests/generated/wasm-tail-call.csv", env!("CARGO_PKG_VERSION"))?;
- test_suite.report_status()
-}
diff --git a/crates/tinywasm/tests/wasm-custom/table-basics.wast b/crates/tinywasm/tests/wasm-custom/table-basics.wast
new file mode 100644
index 0000000..64bda6c
--- /dev/null
+++ b/crates/tinywasm/tests/wasm-custom/table-basics.wast
@@ -0,0 +1,32 @@
+(module
+ (type $result (func (result i32)))
+ (func $seven (type $result) (i32.const 7))
+ (func $nine (type $result) (i32.const 9))
+
+ (table $table 3 5 funcref)
+ (elem (table $table) (i32.const 1) func $seven)
+ (elem $passive func $nine)
+
+ (func (export "size") (result i32)
+ (table.size $table))
+ (func (export "is-null") (param $index i32) (result i32)
+ (ref.is_null (table.get $table (local.get $index))))
+ (func (export "call") (param $index i32) (result i32)
+ (call_indirect $table (type $result) (local.get $index)))
+ (func (export "set-nine") (param $index i32)
+ (table.set $table (local.get $index) (ref.func $nine)))
+ (func (export "init-nine") (param $index i32)
+ (table.init $table $passive (local.get $index) (i32.const 0) (i32.const 1)))
+)
+
+(assert_return (invoke "size") (i32.const 3))
+(assert_return (invoke "is-null" (i32.const 0)) (i32.const 1))
+(assert_return (invoke "is-null" (i32.const 1)) (i32.const 0))
+(assert_return (invoke "call" (i32.const 1)) (i32.const 7))
+(assert_return (invoke "set-nine" (i32.const 0)))
+(assert_return (invoke "is-null" (i32.const 0)) (i32.const 0))
+(assert_return (invoke "call" (i32.const 0)) (i32.const 9))
+(assert_return (invoke "is-null" (i32.const 2)) (i32.const 1))
+(assert_return (invoke "init-nine" (i32.const 2)))
+(assert_return (invoke "is-null" (i32.const 2)) (i32.const 0))
+(assert_return (invoke "call" (i32.const 2)) (i32.const 9))
diff --git a/crates/types/src/instructions.rs b/crates/types/src/instructions.rs
index aff9e24..5eb5491 100644
--- a/crates/types/src/instructions.rs
+++ b/crates/types/src/instructions.rs
@@ -94,7 +94,10 @@ pub enum ConstInstruction {
F32Const(f32),
F64Const(f64),
V128Const([u8; 16]),
- GlobalGet(GlobalAddr),
+ GlobalGet32(GlobalAddr),
+ GlobalGet64(GlobalAddr),
+ GlobalGet128(GlobalAddr),
+ GlobalGetRef(GlobalAddr),
Ref(RefValue),
RefI31,
AnyConvertExtern,