Skip to content

Commit 7d4dfd8

Browse files
chore: cleanup
1 parent 66c9f7a commit 7d4dfd8

File tree

13 files changed

+142
-287
lines changed

13 files changed

+142
-287
lines changed

crates/parser/src/conversion.rs

Lines changed: 32 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -70,38 +70,33 @@ pub(crate) fn convert_module_imports<'a, T: IntoIterator<Item = wasmparser::Resu
7070
}
7171

7272
pub(crate) fn convert_module_import(import: wasmparser::Import<'_>) -> Result<Import> {
73-
Ok(Import {
74-
module: import.module.to_string().into_boxed_str(),
75-
name: import.name.to_string().into_boxed_str(),
76-
kind: match import.ty {
77-
wasmparser::TypeRef::Func(ty) => ImportKind::Function(ty),
78-
wasmparser::TypeRef::Table(ty) => ImportKind::Table(TableType {
79-
element_type: convert_reftype(ty.element_type),
80-
size_initial: ty.initial.try_into().map_err(|_| {
81-
crate::ParseError::UnsupportedOperator(format!("Table size initial is too large: {}", ty.initial))
82-
})?,
83-
size_max: match ty.maximum {
84-
Some(max) => Some(max.try_into().map_err(|_| {
85-
crate::ParseError::UnsupportedOperator(format!("Table size max is too large: {max}"))
86-
})?),
87-
None => None,
88-
},
89-
}),
90-
wasmparser::TypeRef::Memory(ty) => ImportKind::Memory(convert_module_memory(ty)),
91-
wasmparser::TypeRef::Global(ty) => {
92-
ImportKind::Global(GlobalType { mutable: ty.mutable, ty: convert_valtype(&ty.content_type) })
93-
}
94-
wasmparser::TypeRef::Tag(ty) => {
95-
return Err(crate::ParseError::UnsupportedOperator(format!("Unsupported import kind: {ty:?}")));
96-
}
97-
_ => {
98-
return Err(crate::ParseError::UnsupportedOperator(format!(
99-
"Unsupported import kind: {:?}",
100-
import.ty
101-
)));
102-
}
103-
},
104-
})
73+
let kind = match import.ty {
74+
wasmparser::TypeRef::Func(ty) => ImportKind::Function(ty),
75+
wasmparser::TypeRef::Table(ty) => ImportKind::Table(TableType {
76+
element_type: convert_reftype(ty.element_type),
77+
size_initial: ty.initial.try_into().map_err(|_| {
78+
crate::ParseError::UnsupportedOperator(format!("Table size initial is too large: {}", ty.initial))
79+
})?,
80+
size_max: match ty.maximum {
81+
Some(max) => Some(max.try_into().map_err(|_| {
82+
crate::ParseError::UnsupportedOperator(format!("Table size max is too large: {max}"))
83+
})?),
84+
None => None,
85+
},
86+
}),
87+
wasmparser::TypeRef::Memory(ty) => ImportKind::Memory(convert_module_memory(ty)),
88+
wasmparser::TypeRef::Global(ty) => {
89+
ImportKind::Global(GlobalType { mutable: ty.mutable, ty: convert_valtype(&ty.content_type) })
90+
}
91+
wasmparser::TypeRef::Tag(ty) => {
92+
return Err(crate::ParseError::UnsupportedOperator(format!("Unsupported import kind: {ty:?}")));
93+
}
94+
_ => {
95+
return Err(crate::ParseError::UnsupportedOperator(format!("Unsupported import kind: {:?}", import.ty)));
96+
}
97+
};
98+
99+
Ok(Import { module: import.module.into(), name: import.name.into(), kind })
105100
}
106101

107102
pub(crate) fn convert_module_memories<T: IntoIterator<Item = wasmparser::Result<wasmparser::MemoryType>>>(
@@ -130,30 +125,24 @@ pub(crate) fn convert_module_table(table: wasmparser::Table<'_>) -> Result<Table
130125
crate::ParseError::UnsupportedOperator(format!("Table size initial is too large: {}", table.ty.initial))
131126
})?;
132127

133-
let size_max = match table.ty.maximum {
134-
Some(max) => Some(
135-
max.try_into()
136-
.map_err(|_| crate::ParseError::UnsupportedOperator(format!("Table size max is too large: {max}")))?,
137-
),
138-
None => None,
139-
};
140-
128+
let size_max = table.ty.maximum.map(|max| max.try_into()).transpose();
129+
let size_max =
130+
size_max.map_err(|e| crate::ParseError::UnsupportedOperator(format!("Table size max is too large: {e}")))?;
141131
Ok(TableType { element_type: convert_reftype(table.ty.element_type), size_initial, size_max })
142132
}
143133

144134
pub(crate) fn convert_module_globals(
145135
globals: wasmparser::SectionLimited<'_, wasmparser::Global<'_>>,
146136
) -> Result<Vec<Global>> {
147-
let globals = globals
137+
globals
148138
.into_iter()
149139
.map(|global| {
150140
let global = global?;
151141
let ty = convert_valtype(&global.ty.content_type);
152142
let ops = global.init_expr.get_operators_reader();
153143
Ok(Global { init: process_const_operators(ops)?, ty: GlobalType { mutable: global.ty.mutable, ty } })
154144
})
155-
.collect::<Result<Vec<_>>>()?;
156-
Ok(globals)
145+
.collect::<Result<Vec<_>>>()
157146
}
158147

159148
pub(crate) fn convert_module_export(export: wasmparser::Export<'_>) -> Result<Export> {
@@ -215,7 +204,6 @@ pub(crate) fn convert_module_code(
215204

216205
pub(crate) fn convert_module_type(ty: wasmparser::RecGroup) -> Result<FuncType> {
217206
let mut types = ty.types();
218-
219207
if types.len() != 1 {
220208
return Err(crate::ParseError::UnsupportedOperator(
221209
"Expected exactly one type in the type section".to_string(),
@@ -225,7 +213,6 @@ pub(crate) fn convert_module_type(ty: wasmparser::RecGroup) -> Result<FuncType>
225213
let ty = types.next().unwrap().unwrap_func();
226214
let params = ty.params().iter().map(convert_valtype).collect::<Vec<ValType>>().into_boxed_slice();
227215
let results = ty.results().iter().map(convert_valtype).collect::<Vec<ValType>>().into_boxed_slice();
228-
229216
Ok(FuncType { params, results })
230217
}
231218

crates/parser/src/lib.rs

Lines changed: 26 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ mod optimize;
3636
mod visit;
3737
pub use error::*;
3838
use module::ModuleReader;
39-
use wasmparser::{Validator, WasmFeaturesInflated};
39+
use wasmparser::{Validator, WasmFeatures};
4040

4141
pub use tinywasm_types::TinyWasmModule;
4242

@@ -79,56 +79,32 @@ impl Parser {
7979
}
8080

8181
fn create_validator(_options: ParserOptions) -> Validator {
82-
let features = WasmFeaturesInflated {
83-
bulk_memory: true,
84-
floats: true,
85-
multi_value: true,
86-
mutable_global: true,
87-
reference_types: true,
88-
sign_extension: true,
89-
saturating_float_to_int: true,
90-
function_references: true,
91-
tail_call: true,
92-
multi_memory: true,
93-
simd: true,
94-
memory64: true,
95-
custom_page_sizes: true,
96-
bulk_memory_opt: true,
97-
call_indirect_overlong: true,
98-
wide_arithmetic: true,
99-
relaxed_simd: true,
100-
101-
compact_imports: false,
102-
cm_map: false,
103-
custom_descriptors: false,
104-
cm_threading: false,
105-
extended_const: false,
106-
gc_types: true,
107-
stack_switching: false,
108-
component_model: false,
109-
exceptions: false,
110-
gc: false,
111-
memory_control: false,
112-
threads: false,
113-
shared_everything_threads: false,
114-
legacy_exceptions: false,
115-
cm_async: false,
116-
cm_async_builtins: false,
117-
cm_async_stackful: false,
118-
cm_nested_names: false,
119-
cm_values: false,
120-
cm_error_context: false,
121-
cm_fixed_length_lists: false,
122-
cm_gc: false,
123-
};
124-
Validator::new_with_features(features.into())
82+
let features = WasmFeatures::CALL_INDIRECT_OVERLONG
83+
| WasmFeatures::BULK_MEMORY_OPT
84+
| WasmFeatures::RELAXED_SIMD
85+
| WasmFeatures::GC_TYPES
86+
| WasmFeatures::REFERENCE_TYPES
87+
| WasmFeatures::MUTABLE_GLOBAL
88+
| WasmFeatures::MULTI_VALUE
89+
| WasmFeatures::FLOATS
90+
| WasmFeatures::BULK_MEMORY
91+
| WasmFeatures::SATURATING_FLOAT_TO_INT
92+
| WasmFeatures::SIGN_EXTENSION
93+
| WasmFeatures::FUNCTION_REFERENCES
94+
| WasmFeatures::TAIL_CALL
95+
| WasmFeatures::MULTI_MEMORY
96+
| WasmFeatures::SIMD
97+
| WasmFeatures::MEMORY64
98+
| WasmFeatures::CUSTOM_PAGE_SIZES
99+
| WasmFeatures::WIDE_ARITHMETIC;
100+
Validator::new_with_features(features)
125101
}
126102

127103
/// Parse a [`TinyWasmModule`] from bytes
128104
pub fn parse_module_bytes(&self, wasm: impl AsRef<[u8]>) -> Result<TinyWasmModule> {
129105
let wasm = wasm.as_ref();
130106
let mut validator = Self::create_validator(self.options.clone());
131-
let mut reader = ModuleReader::new();
107+
let mut reader = ModuleReader::default();
132108

133109
for payload in wasmparser::Parser::new(0).parse_all(wasm) {
134110
reader.process_payload(payload?, &mut validator)?;
@@ -144,21 +120,16 @@ impl Parser {
144120
#[cfg(feature = "std")]
145121
/// Parse a [`TinyWasmModule`] from a file. Requires `std` feature.
146122
pub fn parse_module_file(&self, path: impl AsRef<crate::std::path::Path> + Clone) -> Result<TinyWasmModule> {
147-
use alloc::format;
148-
let f = crate::std::fs::File::open(&path)
149-
.map_err(|e| ParseError::Other(format!("Error opening file {:?}: {}", path.as_ref(), e)))?;
150-
151-
let mut reader = crate::std::io::BufReader::new(f);
152-
self.parse_module_stream(&mut reader)
123+
let file = crate::std::fs::File::open(&path)
124+
.map_err(|e| ParseError::Other(alloc::format!("Error opening file {:?}: {}", path.as_ref(), e)))?;
125+
self.parse_module_stream(&mut crate::std::io::BufReader::new(file))
153126
}
154127

155128
#[cfg(feature = "std")]
156129
/// Parse a [`TinyWasmModule`] from a stream. Requires `std` feature.
157130
pub fn parse_module_stream(&self, mut stream: impl std::io::Read) -> Result<TinyWasmModule> {
158-
use alloc::format;
159-
160131
let mut validator = Self::create_validator(self.options.clone());
161-
let mut reader = ModuleReader::new();
132+
let mut reader = ModuleReader::default();
162133
let mut buffer = alloc::vec::Vec::new();
163134
let mut parser = wasmparser::Parser::new(0);
164135
let mut eof = false;
@@ -170,7 +141,7 @@ impl Parser {
170141
buffer.extend((0..hint).map(|_| 0u8));
171142
let read_bytes = stream
172143
.read(&mut buffer[len..])
173-
.map_err(|e| ParseError::Other(format!("Error reading from stream: {e}")))?;
144+
.map_err(|e| ParseError::Other(alloc::format!("Error reading from stream: {e}")))?;
174145
buffer.truncate(len + read_bytes);
175146
eof = read_bytes == 0;
176147
}

0 commit comments

Comments
 (0)