Skip to content

Commit 5054545

Browse files
refactor: simplify runtime APIs and state
Signed-off-by: Henry <mail@henrygressmann.de>
1 parent 3bcb73a commit 5054545

7 files changed

Lines changed: 110 additions & 108 deletions

File tree

‎crates/tinywasm/src/func.rs‎

Lines changed: 26 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use crate::interpreter::stack::{CallFrame, ValueStack};
22
use crate::reference::StoreItem;
33
use crate::{Error, FunctionInstance, InterpreterRuntime, Result, Store, Trap};
4-
use alloc::{boxed::Box, format, rc::Rc, sync::Arc, vec, vec::Vec};
4+
use alloc::{borrow::Cow, boxed::Box, format, rc::Rc, sync::Arc, vec, vec::Vec};
55
use core::hint::cold_path;
66
use tinywasm_types::{ExternRef, FuncRef, FuncType, ModuleInstanceAddr, WasmType, WasmValue};
77

@@ -574,31 +574,30 @@ impl<'store, R: FromWasmValues> FuncExecutionTyped<'store, R> {
574574

575575
/// Describes the WebAssembly value types produced by a Rust value or tuple shape.
576576
pub trait ToWasmTypes {
577+
/// Static WebAssembly types for shapes that do not require runtime concatenation.
578+
const WASM_TYPES: Option<&'static [WasmType]>;
579+
577580
/// Return the flattened WebAssembly value types for this tuple shape.
578-
fn wasm_types() -> Box<[WasmType]>;
581+
fn wasm_types() -> Cow<'static, [WasmType]> {
582+
Cow::Borrowed(Self::WASM_TYPES.expect("dynamic ToWasmTypes implementation must override wasm_types"))
583+
}
579584
}
580585

581586
/// Describes the WebAssembly value types produced by a scalar Rust type.
582587
pub trait ToWasmType {
583-
/// Return the single WebAssembly value type for this scalar type.
584-
fn wasm_type() -> WasmType;
588+
/// The single WebAssembly value type for this scalar type.
589+
const WASM_TYPE: WasmType;
585590
}
586591

587592
macro_rules! impl_scalar_wasm_traits {
588593
($($T:ty => $val_ty:ident),+ $(,)?) => {
589594
$(
590595
impl ToWasmType for $T {
591-
#[inline]
592-
fn wasm_type() -> WasmType {
593-
WasmType::$val_ty
594-
}
596+
const WASM_TYPE: WasmType = WasmType::$val_ty;
595597
}
596598

597599
impl ToWasmTypes for $T {
598-
#[inline]
599-
fn wasm_types() -> Box<[WasmType]> {
600-
Box::new([WasmType::$val_ty])
601-
}
600+
const WASM_TYPES: Option<&'static [WasmType]> = Some(&[WasmType::$val_ty]);
602601
}
603602

604603
impl IntoWasmValues for $T {
@@ -611,9 +610,16 @@ macro_rules! impl_scalar_wasm_traits {
611610
impl FromWasmValues for $T {
612611
#[inline]
613612
fn from_wasm_values(values: &[WasmValue]) -> Result<Self> {
614-
let value = *values.first().ok_or(Error::other("Not enough elemennts in &[WasmValue]"))?;
613+
let value = *values.first().ok_or_else(|| {
614+
core::hint::cold_path();
615+
Error::other("Not enough elements in &[WasmValue]")
616+
})?;
617+
615618
<$T>::try_from(value).map_err(|e| {
616-
Error::Other(format!("FromWasmValues: Could not convert WasmValue to expected type: {e:?}"))
619+
core::hint::cold_path();
620+
Error::Other(format!(
621+
"FromWasmValues: Could not convert WasmValue to expected type: {e:?}"
622+
))
617623
})
618624
}
619625
}
@@ -627,10 +633,7 @@ macro_rules! impl_tuple_traits {
627633
where
628634
$($T: ToWasmType,)+
629635
{
630-
#[inline]
631-
fn wasm_types() -> Box<[WasmType]> {
632-
Box::new([$($T::wasm_type(),)+])
633-
}
636+
const WASM_TYPES: Option<&'static [WasmType]> = Some(&[$($T::WASM_TYPE,)+]);
634637
}
635638

636639
impl<$($T),+> IntoWasmValues for ($($T,)+)
@@ -757,12 +760,14 @@ impl<T1, T2> From<(T1, T2)> for WasmTupleChain<T1, T2> {
757760
}
758761

759762
impl<T1: ToWasmTypes, T2: ToWasmTypes> ToWasmTypes for WasmTupleChain<T1, T2> {
763+
const WASM_TYPES: Option<&'static [WasmType]> = None;
764+
760765
#[inline]
761-
fn wasm_types() -> Box<[WasmType]> {
766+
fn wasm_types() -> Cow<'static, [WasmType]> {
762767
let mut types = Vec::new();
763768
types.extend_from_slice(&T1::wasm_types());
764769
types.extend_from_slice(&T2::wasm_types());
765-
types.into_boxed_slice()
770+
Cow::Owned(types)
766771
}
767772
}
768773

@@ -788,10 +793,7 @@ impl<T1: FromWasmValues + ToWasmTypes, T2: FromWasmValues> FromWasmValues for Wa
788793
}
789794

790795
impl ToWasmTypes for () {
791-
#[inline]
792-
fn wasm_types() -> Box<[WasmType]> {
793-
Box::new([])
794-
}
796+
const WASM_TYPES: Option<&'static [WasmType]> = Some(&[]);
795797
}
796798

797799
impl IntoWasmValues for () {

‎crates/tinywasm/src/instance.rs‎

Lines changed: 41 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -210,25 +210,23 @@ impl ModuleInstance {
210210
let instance = ModuleInstance(Rc::new(instance));
211211
store.add_instance(instance.clone());
212212

213-
match (elem_trapped, data_trapped) {
214-
(Some(trap), _) | (_, Some(trap)) => {
215-
cold_path();
216-
Err(trap.into())
217-
}
218-
_ => Ok(instance),
213+
if let Some(trap) = elem_trapped.or(data_trapped) {
214+
cold_path();
215+
return Err(trap.into());
219216
}
217+
Ok(instance)
220218
}
221219

222220
/// Get a export by name
223221
pub fn export_addr(&self, name: &str) -> Option<ExternVal> {
224-
let exports = self.0.exports.iter().find(|e| *e.name == *name)?;
225-
let addr = match exports.kind {
226-
ExternalKind::Func => self.0.func_addrs.get(exports.index as usize)?,
227-
ExternalKind::Table => self.0.table_addrs.get(exports.index as usize)?,
228-
ExternalKind::Memory => self.0.mem_addrs.get(exports.index as usize)?,
229-
ExternalKind::Global => self.0.global_addrs.get(exports.index as usize)?,
222+
let export = self.0.exports.iter().find(|e| *e.name == *name)?;
223+
let addr = match export.kind {
224+
ExternalKind::Func => self.0.func_addrs.get(export.index as usize)?,
225+
ExternalKind::Table => self.0.table_addrs.get(export.index as usize)?,
226+
ExternalKind::Memory => self.0.mem_addrs.get(export.index as usize)?,
227+
ExternalKind::Global => self.0.global_addrs.get(export.index as usize)?,
230228
};
231-
Some(ExternVal::new(exports.kind, *addr))
229+
Some(ExternVal::new(export.kind, *addr))
232230
}
233231

234232
/// Returns an iterator over all exported extern values for this instance.
@@ -288,25 +286,19 @@ impl ModuleInstance {
288286

289287
#[inline]
290288
fn require_export(&self, name: &str) -> Result<ExternVal> {
291-
match self.export_addr(name) {
292-
Some(addr) => Ok(addr),
293-
None => {
294-
cold_path();
295-
Err(Error::Other(format!("Export not found: {name}")))
296-
}
297-
}
289+
self.export_addr(name).ok_or_else(|| {
290+
cold_path();
291+
Error::Other(format!("Export not found: {name}"))
292+
})
298293
}
299294

300295
#[inline]
301296
#[cfg(feature = "guest-debug")]
302297
fn index_addr<T: Copy>(slice: &[T], idx: u32, kind: &str) -> Result<T> {
303-
match slice.get(idx as usize) {
304-
Some(addr) => Ok(*addr),
305-
None => {
306-
cold_path();
307-
Err(Error::Other(format!("{kind} index out of bounds: {idx}")))
308-
}
309-
}
298+
slice.get(idx as usize).copied().ok_or_else(|| {
299+
cold_path();
300+
Error::Other(format!("{kind} index out of bounds: {idx}"))
301+
})
310302
}
311303

312304
/// Get any exported extern value by name.
@@ -376,12 +368,9 @@ impl ModuleInstance {
376368
pub fn func_untyped(&self, store: &Store, name: &str) -> Result<Function> {
377369
self.validate_store(store)?;
378370

379-
let func_addr = match self.require_export(name)? {
380-
ExternVal::Func(func_addr) => func_addr,
381-
_ => {
382-
cold_path();
383-
return Err(Error::Other(format!("Export is not a function: {name}")));
384-
}
371+
let ExternVal::Func(func_addr) = self.require_export(name)? else {
372+
cold_path();
373+
return Err(Error::Other(format!("Export is not a function: {name}")));
385374
};
386375

387376
Ok(Function {
@@ -444,7 +433,20 @@ impl ModuleInstance {
444433
store: &Store,
445434
name: &str,
446435
) -> Result<FunctionTyped<P, R>> {
447-
let func = self.func_untyped(store, name)?;
436+
self.validate_store(store)?;
437+
438+
let ExternVal::Func(func_addr) = self.require_export(name)? else {
439+
cold_path();
440+
return Err(Error::Other(format!("Export is not a function: {name}")));
441+
};
442+
443+
let func = Function {
444+
item: StoreItem::new(self.0.store_id, func_addr),
445+
addr: func_addr,
446+
module_addr: self.id(),
447+
ty: store.state.get_func(func_addr).ty().clone(),
448+
};
449+
448450
Self::validate_typed_func::<P, R>(&func, name)?;
449451
Ok(FunctionTyped { func, marker: core::marker::PhantomData })
450452
}
@@ -462,14 +464,17 @@ impl ModuleInstance {
462464
Ok(FunctionTyped { func, marker: core::marker::PhantomData })
463465
}
464466

467+
#[inline]
465468
fn validate_typed_func<P: ToWasmTypes, R: ToWasmTypes>(func: &Function, func_name: &str) -> Result<()> {
466-
if *func.ty.params() != *P::wasm_types() || *func.ty.results() != *R::wasm_types() {
469+
let params = P::wasm_types();
470+
let results = R::wasm_types();
471+
if func.ty.params() != params.as_ref() || func.ty.results() != results.as_ref() {
467472
cold_path();
468473

469474
#[cfg(feature = "debug")]
470475
return Err(Error::Other(format!(
471476
"function type mismatch for {func_name}: expected {:?}, actual {:?}",
472-
FuncType::new(&P::wasm_types(), &R::wasm_types()),
477+
FuncType::new(&params, &results),
473478
func.ty
474479
)));
475480

‎crates/tinywasm/src/interpreter/executor.rs‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1497,8 +1497,6 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
14971497
let dst = self.pop_table_operand(self.store.state.get_table(table_addr).kind.arch())?; // d
14981498
let elem_addr = self.module.resolve_elem_addr(elem_index) as usize;
14991499
let elem = self.store.state.elements.get(elem_addr).ok_or_else(|| Trap::Other("element not found"))?;
1500-
// Element kind storage is removed separately; table.init only depends on retained items.
1501-
let _ = &elem.kind;
15021500
let items = elem.items.as_deref().unwrap_or(&[]);
15031501
let Some(end) = offset.checked_add(size) else {
15041502
cold_path();

‎crates/tinywasm/src/reference.rs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -446,7 +446,7 @@ impl Global {
446446
/// Get the current value of the global.
447447
pub fn get(&self, store: &Store) -> Result<WasmValue> {
448448
let global = self.instance(store)?;
449-
let value = global.value.get().attach_type(global.ty.ty);
449+
let value = global.value.attach_type(global.ty.ty);
450450
Ok(value.unwrap_or_else(|| unreachable!("Global value type does not match global type, this is a bug")))
451451
}
452452

@@ -461,7 +461,7 @@ impl Global {
461461
cold_path();
462462
return Err(Error::Other("invalid global value type".to_string()));
463463
}
464-
global.value.set(value.into());
464+
global.value = value.into();
465465
Ok(())
466466
}
467467
}

‎crates/tinywasm/src/store/element.rs‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,11 @@
11
use crate::TableElement;
22
use alloc::vec::Vec;
3-
use tinywasm_types::*;
43

54
/// A WebAssembly Element Instance
65
///
76
/// See <https://webassembly.github.io/spec/core/exec/runtime.html#element-instances>
87
#[cfg_attr(feature = "debug", derive(Debug))]
98
pub(crate) struct ElementInstance {
10-
pub(crate) kind: ElementKind,
119
pub(crate) items: Option<Vec<TableElement>>, // none is the element was dropped
1210
}
1311

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,17 @@
11
use crate::interpreter::TinyWasmValue;
2-
use core::cell::Cell;
32
use tinywasm_types::*;
43

54
/// A WebAssembly Global Instance
65
///
76
/// See <https://webassembly.github.io/spec/core/exec/runtime.html#global-instances>
87
#[cfg_attr(feature = "debug", derive(Debug))]
98
pub(crate) struct GlobalInstance {
10-
pub(crate) value: Cell<TinyWasmValue>,
9+
pub(crate) value: TinyWasmValue,
1110
pub(crate) ty: GlobalType,
1211
}
1312

1413
impl GlobalInstance {
1514
pub(crate) fn new(ty: GlobalType, value: TinyWasmValue) -> Self {
16-
Self { ty, value: value.into() }
15+
Self { ty, value }
1716
}
1817
}

0 commit comments

Comments
 (0)