Skip to content

Commit c2061cf

Browse files
chore: cleanup
Signed-off-by: Henry <mail@henrygressmann.de>
1 parent ea895ee commit c2061cf

20 files changed

Lines changed: 229 additions & 211 deletions

File tree

crates/parser/README.md

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
# `tinywasm-parser`
22

3-
This crate provides a parser that can parse WebAssembly modules into a TinyWasm module.
4-
It uses [my fork](https://crates.io/crates/tinywasm-wasmparser) of the [`wasmparser`](https://crates.io/crates/wasmparser) crate that has been modified to be compatible with `no_std` environments.
3+
This crate provides a compiler that can convert WebAssembly modules into a `tinywasm` modules.
54

65
## Features
76

@@ -16,6 +15,6 @@ let bytes = include_bytes!("./file.wasm");
1615

1716
let parser = Parser::new();
1817
let module = parser.parse_module_bytes(bytes).unwrap();
19-
let mudule = parser.parse_module_file("path/to/file.wasm").unwrap();
18+
let module = parser.parse_module_file("path/to/file.wasm").unwrap();
2019
let module = parser.parse_module_stream(&mut stream).unwrap();
2120
```

crates/parser/src/conversion.rs

Lines changed: 18 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ pub(crate) fn convert_module_element(element: wasmparser::Element<'_>) -> Result
2828
.collect::<Result<Vec<_>>>()?
2929
.into_boxed_slice();
3030

31-
Ok(tinywasm_types::Element { kind, items, ty: ValType::RefFunc, range: element.range })
31+
Ok(tinywasm_types::Element { kind, items, ty: WasmType::RefFunc, range: element.range })
3232
}
3333

3434
wasmparser::ElementItems::Expressions(ty, exprs) => {
@@ -211,26 +211,26 @@ pub(crate) fn convert_module_type(ty: wasmparser::RecGroup) -> Result<FuncType>
211211
}
212212

213213
let ty = types.next().unwrap().unwrap_func();
214-
let params = ty.params().iter().map(convert_valtype).collect::<Vec<ValType>>().into_boxed_slice();
215-
let results = ty.results().iter().map(convert_valtype).collect::<Vec<ValType>>().into_boxed_slice();
216-
Ok(FuncType { params, results })
214+
let params: Vec<_> = ty.params().iter().map(convert_valtype).collect();
215+
let results: Vec<_> = ty.results().iter().map(convert_valtype).collect();
216+
Ok(FuncType::new(&params, &results))
217217
}
218218

219-
pub(crate) fn convert_reftype(reftype: wasmparser::RefType) -> ValType {
219+
pub(crate) fn convert_reftype(reftype: wasmparser::RefType) -> WasmType {
220220
match reftype {
221-
_ if reftype.is_func_ref() => ValType::RefFunc,
222-
_ if reftype.is_extern_ref() => ValType::RefExtern,
221+
_ if reftype.is_func_ref() => WasmType::RefFunc,
222+
_ if reftype.is_extern_ref() => WasmType::RefExtern,
223223
_ => unimplemented!("Unsupported reference type: {:?}, {:?}", reftype, reftype.heap_type()),
224224
}
225225
}
226226

227-
pub(crate) fn convert_valtype(valtype: &wasmparser::ValType) -> ValType {
227+
pub(crate) fn convert_valtype(valtype: &wasmparser::ValType) -> WasmType {
228228
match valtype {
229-
wasmparser::ValType::I32 => ValType::I32,
230-
wasmparser::ValType::I64 => ValType::I64,
231-
wasmparser::ValType::F32 => ValType::F32,
232-
wasmparser::ValType::F64 => ValType::F64,
233-
wasmparser::ValType::V128 => ValType::V128,
229+
wasmparser::ValType::I32 => WasmType::I32,
230+
wasmparser::ValType::I64 => WasmType::I64,
231+
wasmparser::ValType::F32 => WasmType::F32,
232+
wasmparser::ValType::F64 => WasmType::F64,
233+
wasmparser::ValType::V128 => WasmType::V128,
234234
wasmparser::ValType::Ref(r) => convert_reftype(*r),
235235
}
236236
}
@@ -247,8 +247,8 @@ pub(crate) fn process_const_operators(ops: OperatorsReader<'_>) -> Result<Box<[C
247247
for op in ops.iter().take(ops.len() - 1) {
248248
let instr = match op {
249249
wasmparser::Operator::RefNull { hty } => match convert_heaptype(*hty) {
250-
ValType::RefFunc => ConstInstruction::RefFunc(None),
251-
ValType::RefExtern => ConstInstruction::RefExtern(None),
250+
WasmType::RefFunc => ConstInstruction::RefFunc(None),
251+
WasmType::RefExtern => ConstInstruction::RefExtern(None),
252252
_ => unimplemented!("Unsupported heap type: {:?}", hty),
253253
},
254254
wasmparser::Operator::RefFunc { function_index } => ConstInstruction::RefFunc(Some(*function_index)),
@@ -276,11 +276,11 @@ pub(crate) fn process_const_operators(ops: OperatorsReader<'_>) -> Result<Box<[C
276276
Ok(out.into_boxed_slice())
277277
}
278278

279-
pub(crate) fn convert_heaptype(heap: wasmparser::HeapType) -> ValType {
279+
pub(crate) fn convert_heaptype(heap: wasmparser::HeapType) -> WasmType {
280280
match heap {
281-
wasmparser::HeapType::Abstract { shared: false, ty: wasmparser::AbstractHeapType::Func } => ValType::RefFunc,
281+
wasmparser::HeapType::Abstract { shared: false, ty: wasmparser::AbstractHeapType::Func } => WasmType::RefFunc,
282282
wasmparser::HeapType::Abstract { shared: false, ty: wasmparser::AbstractHeapType::Extern } => {
283-
ValType::RefExtern
283+
WasmType::RefExtern
284284
}
285285
_ => unimplemented!("Unsupported heap type: {:?}", heap),
286286
}

crates/parser/src/module.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -181,7 +181,7 @@ impl ModuleReader {
181181
let funcs = self.code.into_iter().zip(self.code_type_addrs).enumerate().map(
182182
|(func_idx, ((instructions, mut data, locals), ty_idx))| {
183183
let ty = self.func_types.get(ty_idx as usize).expect("No func type for func, this is a bug").clone();
184-
let params = ValueCounts::from_iter(&ty.params);
184+
let params = ValueCounts::from_iter(ty.params());
185185
let self_func = (imported_func_count + func_idx) as u32;
186186
let instructions = optimize::optimize_instructions(instructions, &mut data, self_func, options);
187187
WasmFunction { instructions: ArcSlice::from(instructions), data, locals, params, ty }

crates/tinywasm/src/func.rs

Lines changed: 28 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ use crate::reference::StoreItem;
33
use crate::{Error, FunctionInstance, InterpreterRuntime, Result, Store, unlikely};
44
use alloc::rc::Rc;
55
use alloc::{boxed::Box, format, string::ToString, vec, vec::Vec};
6-
use tinywasm_types::{ExternRef, FuncRef, FuncType, ModuleInstanceAddr, ValType, WasmValue};
6+
use tinywasm_types::{ExternRef, FuncRef, FuncType, ModuleInstanceAddr, WasmType, WasmValue};
77

88
impl Function {
99
/// Call a function (Invocation)
@@ -132,12 +132,12 @@ impl HostFunction {
132132
let ty = ty_inner.clone();
133133
let result = func(ctx, args)?;
134134

135-
if result.len() != ty.results.len() {
135+
if result.len() != ty.results().len() {
136136
return Err(crate::Error::InvalidHostFnReturn { expected: ty.clone(), actual: result });
137137
};
138138

139-
result.iter().zip(ty.results.iter()).try_for_each(|(val, res_ty)| {
140-
if val.val_type() != *res_ty {
139+
result.iter().zip(ty.results().iter()).try_for_each(|(val, res_ty)| {
140+
if WasmType::from(val) != *res_ty {
141141
return Err(crate::Error::InvalidHostFnReturn { expected: ty.clone(), actual: result.clone() });
142142
}
143143
Ok(())
@@ -153,17 +153,16 @@ impl HostFunction {
153153
/// Create a new typed host function import.
154154
pub fn from<P, R>(store: &mut Store, func: impl Fn(FuncContext<'_>, P) -> Result<R> + 'static) -> Function
155155
where
156-
P: FromWasmValueTuple + ValTypesFromTuple,
157-
R: IntoWasmValueTuple + ValTypesFromTuple,
156+
P: FromWasmValueTuple + WasmTypesFromTuple,
157+
R: IntoWasmValueTuple + WasmTypesFromTuple,
158158
{
159159
let inner_func = move |ctx: FuncContext<'_>, args: &[WasmValue]| -> Result<Vec<WasmValue>> {
160160
let args = P::from_wasm_value_tuple(args)?;
161161
let result = func(ctx, args)?;
162162
Ok(result.into_wasm_value_tuple())
163163
};
164164

165-
let results = R::val_types();
166-
let ty = tinywasm_types::FuncType { params: P::val_types(), results };
165+
let ty = tinywasm_types::FuncType::new(&P::wasm_types(), &R::wasm_types());
167166
let addr = store.add_func(FunctionInstance::Host(Rc::new(Self { func: Box::new(inner_func), ty: ty.clone() })));
168167
Function { item: crate::StoreItem::new(store.id(), addr), module_addr: 0, addr, ty }
169168
}
@@ -363,24 +362,24 @@ impl<'store> FuncExecution<'store> {
363362
}
364363

365364
fn validate_call_params(func_ty: &FuncType, params: &[WasmValue]) -> Result<()> {
366-
if unlikely(func_ty.params.len() != params.len()) {
365+
if unlikely(func_ty.params().len() != params.len()) {
367366
return Err(Error::Other(format!(
368367
"param count mismatch: expected {}, got {}",
369-
func_ty.params.len(),
368+
func_ty.params().len(),
370369
params.len()
371370
)));
372371
}
373372

374-
if !(func_ty.params.iter().zip(params).all(|(ty, param)| ty == &param.val_type())) {
373+
if !(func_ty.params().iter().zip(params).all(|(ty, param)| ty == &param.into())) {
375374
return Err(Error::Other("Type mismatch".into()));
376375
}
377376

378377
Ok(())
379378
}
380379

381380
fn collect_call_results(store: &mut Store, func_ty: &FuncType) -> Result<Vec<WasmValue>> {
382-
debug_assert!(store.stack.values.len() >= func_ty.results.len()); // m values are on the top of the stack (Ensured by validation)
383-
let mut res: Vec<_> = store.stack.values.pop_types(func_ty.results.iter().rev()).collect(); // pop in reverse order since the stack is LIFO
381+
debug_assert!(store.stack.values.len() >= func_ty.results().len()); // m values are on the top of the stack (Ensured by validation)
382+
let mut res: Vec<_> = store.stack.values.pop_types(func_ty.results().iter().rev()).collect(); // pop in reverse order since the stack is LIFO
384383
res.reverse(); // reverse to get the original order
385384
Ok(res)
386385
}
@@ -443,28 +442,28 @@ impl<'store, R: FromWasmValueTuple> FuncExecutionTyped<'store, R> {
443442
}
444443
}
445444

446-
pub trait ValTypesFromTuple {
447-
fn val_types() -> Box<[ValType]>;
445+
pub trait WasmTypesFromTuple {
446+
fn wasm_types() -> Box<[WasmType]>;
448447
}
449448

450-
pub trait ToValType {
451-
fn to_val_type() -> ValType;
449+
pub trait ToWasmType {
450+
fn to_wasm_type() -> WasmType;
452451
}
453452

454453
macro_rules! impl_scalar_wasm_traits {
455454
($($T:ty => $val_ty:ident),+ $(,)?) => {
456455
$(
457-
impl ToValType for $T {
456+
impl ToWasmType for $T {
458457
#[inline]
459-
fn to_val_type() -> ValType {
460-
ValType::$val_ty
458+
fn to_wasm_type() -> WasmType {
459+
WasmType::$val_ty
461460
}
462461
}
463462

464-
impl ValTypesFromTuple for $T {
463+
impl WasmTypesFromTuple for $T {
465464
#[inline]
466-
fn val_types() -> Box<[ValType]> {
467-
Box::new([ValType::$val_ty])
465+
fn wasm_types() -> Box<[WasmType]> {
466+
Box::new([WasmType::$val_ty])
468467
}
469468
}
470469

@@ -495,13 +494,13 @@ macro_rules! impl_scalar_wasm_traits {
495494

496495
macro_rules! impl_tuple_traits {
497496
($($T:ident),+) => {
498-
impl<$($T),+> ValTypesFromTuple for ($($T,)+)
497+
impl<$($T),+> WasmTypesFromTuple for ($($T,)+)
499498
where
500-
$($T: ToValType,)+
499+
$($T: ToWasmType,)+
501500
{
502501
#[inline]
503-
fn val_types() -> Box<[ValType]> {
504-
Box::new([$($T::to_val_type(),)+])
502+
fn wasm_types() -> Box<[WasmType]> {
503+
Box::new([$($T::to_wasm_type(),)+])
505504
}
506505
}
507506

@@ -569,9 +568,9 @@ impl_scalar_wasm_traits!(
569568
);
570569
impl_tuple!(impl_tuple_traits);
571570

572-
impl ValTypesFromTuple for () {
571+
impl WasmTypesFromTuple for () {
573572
#[inline]
574-
fn val_types() -> Box<[ValType]> {
573+
fn wasm_types() -> Box<[WasmType]> {
575574
Box::new([])
576575
}
577576
}

crates/tinywasm/src/imports.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ impl From<&Import> for ExternName {
6767
/// # use log;
6868
/// # fn main() -> tinywasm::Result<()> {
6969
/// use tinywasm::{Global, HostFunction, Imports, Memory, Module, Store, Table};
70-
/// use tinywasm::types::{ValType, TableType, MemoryType, WasmValue};
70+
/// use tinywasm::types::{WasmType, TableType, MemoryType, WasmValue};
7171
/// # let wasm = wat::parse_str("(module)").expect("valid wat");
7272
/// # let module = Module::parse_bytes(&wasm)?;
7373
/// # let mut store = Store::default();
@@ -81,9 +81,9 @@ impl From<&Import> for ExternName {
8181
/// Ok(())
8282
/// });
8383
///
84-
/// let table = Table::new(&mut store, TableType::new(ValType::RefFunc, 10, Some(20)), WasmValue::default_for(ValType::RefFunc))?;
84+
/// let table = Table::new(&mut store, TableType::new(WasmType::RefFunc, 10, Some(20)), WasmValue::default_for(WasmType::RefFunc))?;
8585
/// let memory = Memory::new(&mut store, MemoryType::default().with_page_count_initial(1).with_page_count_max(Some(2)))?;
86-
/// let global_i32 = Global::new(&mut store, tinywasm::types::GlobalType::default().with_ty(ValType::I32), WasmValue::I32(666))?;
86+
/// let global_i32 = Global::new(&mut store, tinywasm::types::GlobalType::default().with_ty(WasmType::I32), WasmValue::I32(666))?;
8787
///
8888
/// imports
8989
/// .define("my_module", "print_i32", print_i32)

crates/tinywasm/src/instance.rs

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ use alloc::boxed::Box;
22
use alloc::{format, rc::Rc};
33
use tinywasm_types::*;
44

5-
use crate::func::{FromWasmValueTuple, IntoWasmValueTuple, ValTypesFromTuple};
5+
use crate::func::{FromWasmValueTuple, IntoWasmValueTuple, WasmTypesFromTuple};
66
use crate::{Error, Function, FunctionTyped, Global, Imports, Memory, Module, Result, Store, Table};
77

88
/// A typed view over an exported extern value.
@@ -304,7 +304,7 @@ impl ModuleInstance {
304304
}
305305

306306
/// Get a typed function export by name.
307-
pub fn func<P: IntoWasmValueTuple + ValTypesFromTuple, R: FromWasmValueTuple + ValTypesFromTuple>(
307+
pub fn func<P: IntoWasmValueTuple + WasmTypesFromTuple, R: FromWasmValueTuple + WasmTypesFromTuple>(
308308
&self,
309309
store: &Store,
310310
name: &str,
@@ -317,7 +317,10 @@ impl ModuleInstance {
317317
/// Get a typed function by its module-local index.
318318
#[cfg_attr(docsrs, doc(cfg(feature = "guest_debug")))]
319319
#[cfg(feature = "guest_debug")]
320-
pub fn func_typed_by_index<P: IntoWasmValueTuple + ValTypesFromTuple, R: FromWasmValueTuple + ValTypesFromTuple>(
320+
pub fn func_typed_by_index<
321+
P: IntoWasmValueTuple + WasmTypesFromTuple,
322+
R: FromWasmValueTuple + WasmTypesFromTuple,
323+
>(
321324
&self,
322325
store: &Store,
323326
func_index: FuncAddr,
@@ -327,8 +330,11 @@ impl ModuleInstance {
327330
Ok(FunctionTyped { func, marker: core::marker::PhantomData })
328331
}
329332

330-
fn validate_typed_func<P: ValTypesFromTuple, R: ValTypesFromTuple>(func: &Function, func_name: &str) -> Result<()> {
331-
let expected = FuncType { params: P::val_types(), results: R::val_types() };
333+
fn validate_typed_func<P: WasmTypesFromTuple, R: WasmTypesFromTuple>(
334+
func: &Function,
335+
func_name: &str,
336+
) -> Result<()> {
337+
let expected = FuncType::new(&P::wasm_types(), &R::wasm_types());
332338
if func.ty != expected {
333339
#[cfg(feature = "debug")]
334340
return Err(Error::Other(format!(

crates/tinywasm/src/interpreter/executor.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -738,7 +738,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
738738
Ok(())
739739
}
740740
fn exec_call_host(&mut self, host_func: Rc<HostFunction>) -> Result<()> {
741-
let params = self.store.stack.values.pop_types(&host_func.ty.params).collect::<Box<_>>();
741+
let params = self.store.stack.values.pop_types(host_func.ty.params()).collect::<Box<_>>();
742742
let res = host_func.call(FuncContext { store: self.store, module_addr: self.module.idx }, &params)?;
743743
self.store.stack.values.extend_from_wasmvalues(&res)?;
744744
self.cf.incr_instr_ptr();
@@ -780,7 +780,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
780780
let func_ref = {
781781
let table_idx: u32 = self.store.stack.values.pop::<i32>() as u32;
782782
let table = self.store.state.get_table(self.module.resolve_table_addr(table_addr));
783-
assert!(table.kind.element_type == ValType::RefFunc, "table is not of type funcref");
783+
assert!(table.kind.element_type == WasmType::RefFunc, "table is not of type funcref");
784784
let table =
785785
table.get(table_idx).map_err(|_| Error::from(Trap::UndefinedElement { index: table_idx as usize }))?;
786786
table.addr().ok_or_else(|| Error::from(Trap::UninitializedElement { index: table_idx as usize }))?
@@ -814,7 +814,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
814814
}
815815

816816
fn exec_return(&mut self) -> bool {
817-
let results = ValueCounts::from_iter(&self.func.ty.results);
817+
let results = ValueCounts::from_iter(self.func.ty.results());
818818
self.store.stack.values.truncate_keep_counts(self.cf.locals_base, results);
819819
let Some(cf) = self.store.stack.call_stack.pop() else { return true };
820820

crates/tinywasm/src/interpreter/stack/value_stack.rs

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use alloc::boxed::Box;
22
use alloc::vec::Vec;
3-
use tinywasm_types::{ExternRef, FuncRef, LocalAddr, ValType, ValueCounts, WasmValue};
3+
use tinywasm_types::{ExternRef, FuncRef, LocalAddr, ValueCounts, WasmType, WasmValue};
44

55
use crate::{Result, Trap, engine::Config, interpreter::*, unlikely};
66

@@ -197,7 +197,7 @@ impl ValueStack {
197197

198198
pub(crate) fn pop_types<'a>(
199199
&'a mut self,
200-
val_types: impl IntoIterator<Item = &'a ValType>,
200+
val_types: impl IntoIterator<Item = &'a WasmType>,
201201
) -> impl core::iter::Iterator<Item = WasmValue> {
202202
val_types.into_iter().map(|val_type| self.pop_wasmvalue(*val_type))
203203
}
@@ -272,15 +272,15 @@ impl ValueStack {
272272
Ok(())
273273
}
274274

275-
pub(crate) fn pop_wasmvalue(&mut self, val_type: ValType) -> WasmValue {
275+
pub(crate) fn pop_wasmvalue(&mut self, val_type: WasmType) -> WasmValue {
276276
match val_type {
277-
ValType::I32 => WasmValue::I32(self.pop()),
278-
ValType::I64 => WasmValue::I64(self.pop()),
279-
ValType::F32 => WasmValue::F32(self.pop()),
280-
ValType::F64 => WasmValue::F64(self.pop()),
281-
ValType::RefExtern => WasmValue::RefExtern(ExternRef::new(self.pop())),
282-
ValType::RefFunc => WasmValue::RefFunc(FuncRef::new(self.pop())),
283-
ValType::V128 => WasmValue::V128(self.pop::<Value128>().into()),
277+
WasmType::I32 => WasmValue::I32(self.pop()),
278+
WasmType::I64 => WasmValue::I64(self.pop()),
279+
WasmType::F32 => WasmValue::F32(self.pop()),
280+
WasmType::F64 => WasmValue::F64(self.pop()),
281+
WasmType::RefExtern => WasmValue::RefExtern(ExternRef::new(self.pop())),
282+
WasmType::RefFunc => WasmValue::RefFunc(FuncRef::new(self.pop())),
283+
WasmType::V128 => WasmValue::V128(self.pop::<Value128>().into()),
284284
}
285285
}
286286

0 commit comments

Comments
 (0)