Skip to content
This repository was archived by the owner on Oct 3, 2025. It is now read-only.

Commit 3e7548c

Browse files
chore: simplify interpreter::exec
Signed-off-by: Henry Gressmann <mail@henrygressmann.de>
1 parent 4f405d1 commit 3e7548c

File tree

9 files changed

+128
-150
lines changed

9 files changed

+128
-150
lines changed

benches/fibonacci.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ fn criterion_benchmark(c: &mut Criterion) {
3030

3131
let mut group = c.benchmark_group("fibonacci");
3232
group.bench_function("tinywasm", |b| b.iter(|| run_tinywasm(module.clone())));
33-
// group.bench_function("wasmi", |b| b.iter(|| run_wasmi()));
33+
group.bench_function("wasmi", |b| b.iter(|| run_wasmi()));
3434
}
3535

3636
criterion_group!(

crates/tinywasm/src/func.rs

Lines changed: 30 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,17 @@
1-
use crate::{log, runtime::RawWasmValue};
1+
use crate::{log, runtime::RawWasmValue, unlikely, Function};
22
use alloc::{boxed::Box, format, string::String, string::ToString, vec, vec::Vec};
3-
use tinywasm_types::{FuncAddr, FuncType, ValType, WasmValue};
3+
use tinywasm_types::{FuncType, ModuleInstanceAddr, ValType, WasmValue};
44

55
use crate::{
66
runtime::{CallFrame, Stack},
7-
Error, FuncContext, ModuleInstance, Result, Store,
7+
Error, FuncContext, Result, Store,
88
};
99

1010
#[derive(Debug)]
1111
/// A function handle
1212
pub struct FuncHandle {
13-
pub(crate) module: ModuleInstance,
14-
pub(crate) addr: FuncAddr,
13+
pub(crate) module_addr: ModuleInstanceAddr,
14+
pub(crate) addr: u32,
1515
pub(crate) ty: FuncType,
1616

1717
/// The name of the function, if it has one
@@ -22,18 +22,13 @@ impl FuncHandle {
2222
/// Call a function (Invocation)
2323
///
2424
/// See <https://webassembly.github.io/spec/core/exec/modules.html#invocation>
25+
#[inline]
2526
pub fn call(&self, store: &mut Store, params: &[WasmValue]) -> Result<Vec<WasmValue>> {
26-
let mut stack = Stack::default();
27-
28-
// 1. Assert: funcs[func_addr] exists
29-
// 2. let func_inst be the functiuon instance funcs[func_addr]
30-
let func_inst = store.get_func(self.addr as usize)?.clone();
31-
3227
// 3. Let func_ty be the function type
3328
let func_ty = &self.ty;
3429

3530
// 4. If the length of the provided argument values is different from the number of expected arguments, then fail
36-
if func_ty.params.len() != params.len() {
31+
if unlikely(func_ty.params.len() != params.len()) {
3732
log::info!("func_ty.params: {:?}", func_ty.params);
3833
return Err(Error::Other(format!(
3934
"param count mismatch: expected {}, got {}",
@@ -43,31 +38,34 @@ impl FuncHandle {
4338
}
4439

4540
// 5. For each value type and the corresponding value, check if types match
46-
for (i, (ty, param)) in func_ty.params.iter().zip(params).enumerate() {
41+
if !unlikely(func_ty.params.iter().zip(params).enumerate().all(|(i, (ty, param))| {
4742
if ty != &param.val_type() {
48-
return Err(Error::Other(format!(
49-
"param type mismatch at index {}: expected {:?}, got {:?}",
50-
i, ty, param
51-
)));
43+
log::error!("param type mismatch at index {}: expected {:?}, got {:?}", i, ty, param);
44+
false
45+
} else {
46+
true
5247
}
48+
})) {
49+
return Err(Error::Other("Type mismatch".into()));
5350
}
5451

55-
let locals = match &func_inst.func {
56-
crate::Function::Host(h) => {
57-
let func = h.func.clone();
58-
let ctx = FuncContext { store, module: &self.module };
52+
let func_inst = store.get_func(self.addr as usize)?;
53+
let wasm_func = match &func_inst.func {
54+
Function::Host(host_func) => {
55+
let func = &host_func.clone().func;
56+
let ctx = FuncContext { store, module_addr: self.module_addr };
5957
return (func)(ctx, params);
6058
}
61-
crate::Function::Wasm(ref f) => f.locals.to_vec(),
59+
Function::Wasm(wasm_func) => wasm_func,
6260
};
6361

6462
// 6. Let f be the dummy frame
65-
log::debug!("locals: {:?}", locals);
66-
let call_frame = CallFrame::new(func_inst, params.iter().map(|v| RawWasmValue::from(*v)), locals);
63+
let call_frame =
64+
CallFrame::new(wasm_func.clone(), func_inst.owner, params.iter().map(|v| RawWasmValue::from(*v)));
6765

6866
// 7. Push the frame f to the call stack
6967
// & 8. Push the values to the stack (Not needed since the call frame owns the values)
70-
stack.call_stack.push(call_frame)?;
68+
let mut stack = Stack::new(call_frame);
7169

7270
// 9. Invoke the function instance
7371
let runtime = store.runtime();
@@ -125,6 +123,7 @@ macro_rules! impl_into_wasm_value_tuple {
125123
$($T: Into<WasmValue>),*
126124
{
127125
#[allow(non_snake_case)]
126+
#[inline]
128127
fn into_wasm_value_tuple(self) -> Vec<WasmValue> {
129128
let ($($T,)*) = self;
130129
vec![$($T.into(),)*]
@@ -136,6 +135,7 @@ macro_rules! impl_into_wasm_value_tuple {
136135
macro_rules! impl_into_wasm_value_tuple_single {
137136
($T:ident) => {
138137
impl IntoWasmValueTuple for $T {
138+
#[inline]
139139
fn into_wasm_value_tuple(self) -> Vec<WasmValue> {
140140
vec![self.into()]
141141
}
@@ -164,6 +164,7 @@ macro_rules! impl_from_wasm_value_tuple {
164164
where
165165
$($T: TryFrom<WasmValue, Error = ()>),*
166166
{
167+
#[inline]
167168
fn from_wasm_value_tuple(values: &[WasmValue]) -> Result<Self> {
168169
#[allow(unused_variables, unused_mut)]
169170
let mut iter = values.iter();
@@ -186,6 +187,7 @@ macro_rules! impl_from_wasm_value_tuple {
186187
macro_rules! impl_from_wasm_value_tuple_single {
187188
($T:ident) => {
188189
impl FromWasmValueTuple for $T {
190+
#[inline]
189191
fn from_wasm_value_tuple(values: &[WasmValue]) -> Result<Self> {
190192
#[allow(unused_variables, unused_mut)]
191193
let mut iter = values.iter();
@@ -254,6 +256,7 @@ macro_rules! impl_val_types_from_tuple {
254256
where
255257
$($t: ToValType,)+
256258
{
259+
#[inline]
257260
fn val_types() -> Box<[ValType]> {
258261
Box::new([$($t::to_val_type(),)+])
259262
}
@@ -262,6 +265,7 @@ macro_rules! impl_val_types_from_tuple {
262265
}
263266

264267
impl ValTypesFromTuple for () {
268+
#[inline]
265269
fn val_types() -> Box<[ValType]> {
266270
Box::new([])
267271
}
@@ -271,6 +275,7 @@ impl<T1> ValTypesFromTuple for T1
271275
where
272276
T1: ToValType,
273277
{
278+
#[inline]
274279
fn val_types() -> Box<[ValType]> {
275280
Box::new([T1::to_val_type()])
276281
}

crates/tinywasm/src/imports.rs

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ use crate::{
77
log, LinkingError, Result,
88
};
99
use alloc::{
10+
boxed::Box,
1011
collections::BTreeMap,
1112
rc::Rc,
1213
string::{String, ToString},
@@ -18,10 +19,10 @@ use tinywasm_types::*;
1819
#[derive(Debug, Clone)]
1920
pub enum Function {
2021
/// A host function
21-
Host(HostFunction),
22+
Host(Rc<HostFunction>),
2223

2324
/// A function defined in WebAssembly
24-
Wasm(WasmFunction),
25+
Wasm(Rc<WasmFunction>),
2526
}
2627

2728
impl Function {
@@ -34,7 +35,6 @@ impl Function {
3435
}
3536

3637
/// A host function
37-
#[derive(Clone)]
3838
pub struct HostFunction {
3939
pub(crate) ty: tinywasm_types::FuncType,
4040
pub(crate) func: HostFuncInner,
@@ -52,13 +52,13 @@ impl HostFunction {
5252
}
5353
}
5454

55-
pub(crate) type HostFuncInner = Rc<dyn Fn(FuncContext<'_>, &[WasmValue]) -> Result<Vec<WasmValue>>>;
55+
pub(crate) type HostFuncInner = Box<dyn Fn(FuncContext<'_>, &[WasmValue]) -> Result<Vec<WasmValue>>>;
5656

5757
/// The context of a host-function call
5858
#[derive(Debug)]
5959
pub struct FuncContext<'a> {
6060
pub(crate) store: &'a mut crate::Store,
61-
pub(crate) module: &'a crate::ModuleInstance,
61+
pub(crate) module_addr: ModuleInstanceAddr,
6262
}
6363

6464
impl FuncContext<'_> {
@@ -73,13 +73,13 @@ impl FuncContext<'_> {
7373
}
7474

7575
/// Get a reference to the module instance
76-
pub fn module(&self) -> &crate::ModuleInstance {
77-
self.module
76+
pub fn module(&self) -> crate::ModuleInstance {
77+
self.store.get_module_instance_raw(self.module_addr)
7878
}
7979

8080
/// Get a reference to an exported memory
8181
pub fn memory(&mut self, name: &str) -> Result<crate::MemoryRef> {
82-
self.module.exported_memory(self.store, name)
82+
self.module().exported_memory(self.store, name)
8383
}
8484
}
8585

@@ -140,7 +140,7 @@ impl Extern {
140140
ty: &tinywasm_types::FuncType,
141141
func: impl Fn(FuncContext<'_>, &[WasmValue]) -> Result<Vec<WasmValue>> + 'static,
142142
) -> Self {
143-
Self::Function(Function::Host(HostFunction { func: Rc::new(func), ty: ty.clone() }))
143+
Self::Function(Function::Host(Rc::new(HostFunction { func: Box::new(func), ty: ty.clone() })))
144144
}
145145

146146
/// Create a new typed function import
@@ -159,7 +159,7 @@ impl Extern {
159159

160160
let ty = tinywasm_types::FuncType { params: P::val_types(), results: R::val_types() };
161161

162-
Self::Function(Function::Host(HostFunction { func: Rc::new(inner_func), ty }))
162+
Self::Function(Function::Host(Rc::new(HostFunction { func: Box::new(inner_func), ty })))
163163
}
164164

165165
pub(crate) fn kind(&self) -> ExternalKind {

crates/tinywasm/src/instance.rs

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,10 @@ impl ModuleInstance {
4242
self.0 = other.0;
4343
}
4444

45+
pub(crate) fn swap_with(&mut self, other_addr: ModuleInstanceAddr, store: &mut Store) {
46+
self.swap(store.get_module_instance_raw(other_addr))
47+
}
48+
4549
/// Get the module instance's address
4650
pub fn id(&self) -> ModuleInstanceAddr {
4751
self.0.idx
@@ -172,7 +176,7 @@ impl ModuleInstance {
172176
let func_inst = store.get_func(func_addr as usize)?;
173177
let ty = func_inst.func.ty();
174178

175-
Ok(FuncHandle { addr: func_addr, module: self.clone(), name: Some(name.to_string()), ty: ty.clone() })
179+
Ok(FuncHandle { addr: func_addr, module_addr: self.id(), name: Some(name.to_string()), ty: ty.clone() })
176180
}
177181

178182
/// Get a typed exported function by name
@@ -230,7 +234,7 @@ impl ModuleInstance {
230234
let func_inst = store.get_func(*func_addr as usize)?;
231235
let ty = func_inst.func.ty();
232236

233-
Ok(Some(FuncHandle { module: self.clone(), addr: *func_addr, ty: ty.clone(), name: None }))
237+
Ok(Some(FuncHandle { module_addr: self.id(), addr: *func_addr, ty: ty.clone(), name: None }))
234238
}
235239

236240
/// Invoke the start function of the module

0 commit comments

Comments
 (0)