summaryrefslogtreecommitdiff
path: root/crates/parser
diff options
context:
space:
mode:
authorHenry Gressmann <mail@henrygressmann.de>2024-08-12 16:12:07 +0200
committerHenry Gressmann <mail@henrygressmann.de>2024-08-12 16:12:07 +0200
commit06f81026eca6446d737e3759951ca15001a819c5 (patch)
treee06d747eb225cac6e24557faa2694895d52741ae /crates/parser
parentd33a0c66a17316755e572b3620fb030ec1e52f61 (diff)
chore: clean up code
Signed-off-by: Henry Gressmann <mail@henrygressmann.de>
Diffstat (limited to 'crates/parser')
-rw-r--r--crates/parser/src/conversion.rs37
-rw-r--r--crates/parser/src/error.rs16
-rw-r--r--crates/parser/src/lib.rs8
-rw-r--r--crates/parser/src/module.rs10
-rw-r--r--crates/parser/src/visit.rs92
5 files changed, 81 insertions, 82 deletions
diff --git a/crates/parser/src/conversion.rs b/crates/parser/src/conversion.rs
index c733dcc..10607a1 100644
--- a/crates/parser/src/conversion.rs
+++ b/crates/parser/src/conversion.rs
@@ -38,7 +38,7 @@ pub(crate) fn convert_module_element(element: wasmparser::Element<'_>) -> Result
.collect::<Result<Vec<_>>>()?
.into_boxed_slice();
- Ok(tinywasm_types::Element { kind, items, ty: convert_reftype(&ty), range: element.range })
+ Ok(tinywasm_types::Element { kind, items, ty: convert_reftype(ty), range: element.range })
}
}
}
@@ -76,23 +76,23 @@ pub(crate) fn convert_module_import(import: wasmparser::Import<'_>) -> Result<Im
kind: match import.ty {
wasmparser::TypeRef::Func(ty) => ImportKind::Function(ty),
wasmparser::TypeRef::Table(ty) => ImportKind::Table(TableType {
- element_type: convert_reftype(&ty.element_type),
+ element_type: convert_reftype(ty.element_type),
size_initial: ty.initial.try_into().map_err(|_| {
crate::ParseError::UnsupportedOperator(format!("Table size initial is too large: {}", ty.initial))
})?,
size_max: match ty.maximum {
Some(max) => Some(max.try_into().map_err(|_| {
- crate::ParseError::UnsupportedOperator(format!("Table size max is too large: {}", max))
+ crate::ParseError::UnsupportedOperator(format!("Table size max is too large: {max}"))
})?),
None => None,
},
}),
- wasmparser::TypeRef::Memory(ty) => ImportKind::Memory(convert_module_memory(ty)?),
+ wasmparser::TypeRef::Memory(ty) => ImportKind::Memory(convert_module_memory(ty)),
wasmparser::TypeRef::Global(ty) => {
ImportKind::Global(GlobalType { mutable: ty.mutable, ty: convert_valtype(&ty.content_type) })
}
wasmparser::TypeRef::Tag(ty) => {
- return Err(crate::ParseError::UnsupportedOperator(format!("Unsupported import kind: {:?}", ty)))
+ return Err(crate::ParseError::UnsupportedOperator(format!("Unsupported import kind: {ty:?}")))
}
},
})
@@ -101,18 +101,15 @@ pub(crate) fn convert_module_import(import: wasmparser::Import<'_>) -> Result<Im
pub(crate) fn convert_module_memories<T: IntoIterator<Item = wasmparser::Result<wasmparser::MemoryType>>>(
memory_types: T,
) -> Result<Vec<MemoryType>> {
- memory_types.into_iter().map(|memory| convert_module_memory(memory?)).collect::<Result<Vec<_>>>()
+ memory_types.into_iter().map(|memory| Ok(convert_module_memory(memory?))).collect::<Result<Vec<_>>>()
}
-pub(crate) fn convert_module_memory(memory: wasmparser::MemoryType) -> Result<MemoryType> {
- Ok(MemoryType {
- arch: match memory.memory64 {
- true => MemoryArch::I64,
- false => MemoryArch::I32,
- },
+pub(crate) fn convert_module_memory(memory: wasmparser::MemoryType) -> MemoryType {
+ MemoryType {
+ arch: if memory.memory64 { MemoryArch::I64 } else { MemoryArch::I32 },
page_count_initial: memory.initial,
page_count_max: memory.maximum,
- })
+ }
}
pub(crate) fn convert_module_tables<'a, T: IntoIterator<Item = wasmparser::Result<wasmparser::Table<'a>>>>(
@@ -129,12 +126,12 @@ pub(crate) fn convert_module_table(table: wasmparser::Table<'_>) -> Result<Table
let size_max = match table.ty.maximum {
Some(max) => Some(
max.try_into()
- .map_err(|_| crate::ParseError::UnsupportedOperator(format!("Table size max is too large: {}", max)))?,
+ .map_err(|_| crate::ParseError::UnsupportedOperator(format!("Table size max is too large: {max}")))?,
),
None => None,
};
- Ok(TableType { element_type: convert_reftype(&table.ty.element_type), size_initial, size_max })
+ Ok(TableType { element_type: convert_reftype(table.ty.element_type), size_initial, size_max })
}
pub(crate) fn convert_module_globals(
@@ -185,11 +182,11 @@ pub(crate) fn convert_module_code(
for i in 0..validator.len_locals() {
match validator.get_local_type(i) {
- Some(wasmparser::ValType::I32) | Some(wasmparser::ValType::F32) => {
+ Some(wasmparser::ValType::I32 | wasmparser::ValType::F32) => {
local_addr_map.push(local_counts.c32);
local_counts.c32 += 1;
}
- Some(wasmparser::ValType::I64) | Some(wasmparser::ValType::F64) => {
+ Some(wasmparser::ValType::I64 | wasmparser::ValType::F64) => {
local_addr_map.push(local_counts.c64);
local_counts.c64 += 1;
}
@@ -225,7 +222,7 @@ pub(crate) fn convert_module_type(ty: wasmparser::RecGroup) -> Result<FuncType>
Ok(FuncType { params, results })
}
-pub(crate) fn convert_reftype(reftype: &wasmparser::RefType) -> ValType {
+pub(crate) fn convert_reftype(reftype: wasmparser::RefType) -> ValType {
match reftype {
_ if reftype.is_func_ref() => ValType::RefFunc,
_ if reftype.is_extern_ref() => ValType::RefExtern,
@@ -240,7 +237,7 @@ pub(crate) fn convert_valtype(valtype: &wasmparser::ValType) -> ValType {
wasmparser::ValType::F32 => ValType::F32,
wasmparser::ValType::F64 => ValType::F64,
wasmparser::ValType::V128 => ValType::V128,
- wasmparser::ValType::Ref(r) => convert_reftype(r),
+ wasmparser::ValType::Ref(r) => convert_reftype(*r),
}
}
@@ -260,7 +257,7 @@ pub(crate) fn process_const_operators(ops: OperatorsReader<'_>) -> Result<ConstI
wasmparser::Operator::F32Const { value } => Ok(ConstInstruction::F32Const(f32::from_bits(value.bits()))),
wasmparser::Operator::F64Const { value } => Ok(ConstInstruction::F64Const(f64::from_bits(value.bits()))),
wasmparser::Operator::GlobalGet { global_index } => Ok(ConstInstruction::GlobalGet(*global_index)),
- op => Err(crate::ParseError::UnsupportedOperator(format!("Unsupported const instruction: {:?}", op))),
+ op => Err(crate::ParseError::UnsupportedOperator(format!("Unsupported const instruction: {op:?}"))),
}
}
diff --git a/crates/parser/src/error.rs b/crates/parser/src/error.rs
index c32e026..7bd484f 100644
--- a/crates/parser/src/error.rs
+++ b/crates/parser/src/error.rs
@@ -42,19 +42,19 @@ impl Display for ParseError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::InvalidType => write!(f, "invalid type"),
- Self::UnsupportedSection(section) => write!(f, "unsupported section: {}", section),
- Self::DuplicateSection(section) => write!(f, "duplicate section: {}", section),
- Self::EmptySection(section) => write!(f, "empty section: {}", section),
- Self::UnsupportedOperator(operator) => write!(f, "unsupported operator: {}", operator),
+ Self::UnsupportedSection(section) => write!(f, "unsupported section: {section}"),
+ Self::DuplicateSection(section) => write!(f, "duplicate section: {section}"),
+ Self::EmptySection(section) => write!(f, "empty section: {section}"),
+ Self::UnsupportedOperator(operator) => write!(f, "unsupported operator: {operator}"),
Self::ParseError { message, offset } => {
- write!(f, "error parsing module: {} at offset {}", message, offset)
+ write!(f, "error parsing module: {message} at offset {offset}")
}
- Self::InvalidEncoding(encoding) => write!(f, "invalid encoding: {:?}", encoding),
+ Self::InvalidEncoding(encoding) => write!(f, "invalid encoding: {encoding:?}"),
Self::InvalidLocalCount { expected, actual } => {
- write!(f, "invalid local count: expected {}, actual {}", expected, actual)
+ write!(f, "invalid local count: expected {expected}, actual {actual}")
}
Self::EndNotReached => write!(f, "end of module not reached"),
- Self::Other(message) => write!(f, "unknown error: {}", message),
+ Self::Other(message) => write!(f, "unknown error: {message}"),
}
}
}
diff --git a/crates/parser/src/lib.rs b/crates/parser/src/lib.rs
index a517c52..c931b9e 100644
--- a/crates/parser/src/lib.rs
+++ b/crates/parser/src/lib.rs
@@ -49,7 +49,7 @@ impl Parser {
Self {}
}
- fn create_validator(&self) -> Validator {
+ fn create_validator() -> Validator {
let features = WasmFeaturesInflated {
bulk_memory: true,
floats: true,
@@ -85,7 +85,7 @@ impl Parser {
/// Parse a [`TinyWasmModule`] from bytes
pub fn parse_module_bytes(&self, wasm: impl AsRef<[u8]>) -> Result<TinyWasmModule> {
let wasm = wasm.as_ref();
- let mut validator = self.create_validator();
+ let mut validator = Self::create_validator();
let mut reader = ModuleReader::new();
for payload in wasmparser::Parser::new(0).parse_all(wasm) {
@@ -115,7 +115,7 @@ impl Parser {
pub fn parse_module_stream(&self, mut stream: impl std::io::Read) -> Result<TinyWasmModule> {
use alloc::format;
- let mut validator = self.create_validator();
+ let mut validator = Self::create_validator();
let mut reader = ModuleReader::new();
let mut buffer = alloc::vec::Vec::new();
let mut parser = wasmparser::Parser::new(0);
@@ -128,7 +128,7 @@ impl Parser {
buffer.extend((0..hint).map(|_| 0u8));
let read_bytes = stream
.read(&mut buffer[len..])
- .map_err(|e| ParseError::Other(format!("Error reading from stream: {}", e)))?;
+ .map_err(|e| ParseError::Other(format!("Error reading from stream: {e}")))?;
buffer.truncate(len + read_bytes);
eof = read_bytes == 0;
}
diff --git a/crates/parser/src/module.rs b/crates/parser/src/module.rs
index 74da1d9..20ed00d 100644
--- a/crates/parser/src/module.rs
+++ b/crates/parser/src/module.rs
@@ -168,12 +168,12 @@ impl ModuleReader {
validator.end(offset)?;
self.end_reached = true;
}
- CustomSection(_reader) => {
+ CustomSection(reader) => {
debug!("Found custom section");
- debug!("Skipping custom section: {:?}", _reader.name());
+ debug!("Skipping custom section: {:?}", reader.name());
}
UnknownSection { .. } => return Err(ParseError::UnsupportedSection("Unknown section".into())),
- section => return Err(ParseError::UnsupportedSection(format!("Unsupported section: {:?}", section))),
+ section => return Err(ParseError::UnsupportedSection(format!("Unsupported section: {section:?}"))),
};
Ok(())
@@ -196,7 +196,7 @@ impl ModuleReader {
.map(|((instructions, locals), ty_idx)| {
let mut params = ValueCountsSmall::default();
let ty = self.func_types.get(ty_idx as usize).expect("No func type for func, this is a bug").clone();
- for param in ty.params.iter() {
+ for param in &ty.params {
match param {
ValType::I32 | ValType::F32 => params.c32 += 1,
ValType::I64 | ValType::F64 => params.c64 += 1,
@@ -204,7 +204,7 @@ impl ModuleReader {
ValType::RefExtern | ValType::RefFunc => params.cref += 1,
}
}
- WasmFunction { instructions, params, locals, ty }
+ WasmFunction { instructions, locals, params, ty }
})
.collect::<Vec<_>>()
.into_boxed_slice();
diff --git a/crates/parser/src/visit.rs b/crates/parser/src/visit.rs
index 1f282f7..73cf9b4 100644
--- a/crates/parser/src/visit.rs
+++ b/crates/parser/src/visit.rs
@@ -362,7 +362,7 @@ impl<'a, R: WasmModuleResources> wasmparser::VisitOperator<'a> for FunctionBuild
fn visit_i32_store(&mut self, memarg: wasmparser::MemArg) -> Self::Output {
let arg = MemoryArg { offset: memarg.offset, mem_addr: memarg.memory };
let i32store = Instruction::I32Store { offset: arg.offset, mem_addr: arg.mem_addr };
- self.instructions.push(i32store)
+ self.instructions.push(i32store);
}
fn visit_local_get(&mut self, idx: u32) -> Self::Output {
@@ -394,28 +394,28 @@ impl<'a, R: WasmModuleResources> wasmparser::VisitOperator<'a> for FunctionBuild
return;
};
- match self.instructions.last() {
- Some(Instruction::LocalGet32(from))
- | Some(Instruction::LocalGet64(from))
- | Some(Instruction::LocalGet128(from))
- | Some(Instruction::LocalGetRef(from)) => {
- let from = *from;
- self.instructions.pop();
- // validation will ensure that the last instruction is the correct local.get
- match self.validator.get_operand_type(0) {
- Some(Some(t)) => self.instructions.push(match t {
- wasmparser::ValType::I32 => Instruction::LocalCopy32(from, resolved_idx),
- wasmparser::ValType::F32 => Instruction::LocalCopy32(from, resolved_idx),
- wasmparser::ValType::I64 => Instruction::LocalCopy64(from, resolved_idx),
- wasmparser::ValType::F64 => Instruction::LocalCopy64(from, resolved_idx),
- wasmparser::ValType::V128 => Instruction::LocalCopy128(from, resolved_idx),
- wasmparser::ValType::Ref(_) => Instruction::LocalCopyRef(from, resolved_idx),
- }),
- _ => self.visit_unreachable(),
- }
- return;
+ if let Some(
+ Instruction::LocalGet32(from)
+ | Instruction::LocalGet64(from)
+ | Instruction::LocalGet128(from)
+ | Instruction::LocalGetRef(from),
+ ) = self.instructions.last()
+ {
+ let from = *from;
+ self.instructions.pop();
+ // validation will ensure that the last instruction is the correct local.get
+ match self.validator.get_operand_type(0) {
+ Some(Some(t)) => self.instructions.push(match t {
+ wasmparser::ValType::I32 => Instruction::LocalCopy32(from, resolved_idx),
+ wasmparser::ValType::F32 => Instruction::LocalCopy32(from, resolved_idx),
+ wasmparser::ValType::I64 => Instruction::LocalCopy64(from, resolved_idx),
+ wasmparser::ValType::F64 => Instruction::LocalCopy64(from, resolved_idx),
+ wasmparser::ValType::V128 => Instruction::LocalCopy128(from, resolved_idx),
+ wasmparser::ValType::Ref(_) => Instruction::LocalCopyRef(from, resolved_idx),
+ }),
+ _ => self.visit_unreachable(),
}
- _ => {}
+ return;
}
match self.validator.get_operand_type(0) {
@@ -453,11 +453,11 @@ impl<'a, R: WasmModuleResources> wasmparser::VisitOperator<'a> for FunctionBuild
}
fn visit_i64_rotl(&mut self) -> Self::Output {
- self.instructions.push(Instruction::I64Rotl)
+ self.instructions.push(Instruction::I64Rotl);
}
fn visit_i32_add(&mut self) -> Self::Output {
- self.instructions.push(Instruction::I32Add)
+ self.instructions.push(Instruction::I32Add);
}
fn visit_block(&mut self, blockty: wasmparser::BlockType) -> Self::Output {
@@ -466,7 +466,7 @@ impl<'a, R: WasmModuleResources> wasmparser::VisitOperator<'a> for FunctionBuild
wasmparser::BlockType::Empty => Instruction::Block(0),
wasmparser::BlockType::FuncType(idx) => Instruction::BlockWithFuncType(idx, 0),
wasmparser::BlockType::Type(ty) => Instruction::BlockWithType(convert_valtype(&ty), 0),
- })
+ });
}
fn visit_loop(&mut self, ty: wasmparser::BlockType) -> Self::Output {
@@ -475,7 +475,7 @@ impl<'a, R: WasmModuleResources> wasmparser::VisitOperator<'a> for FunctionBuild
wasmparser::BlockType::Empty => Instruction::Loop(0),
wasmparser::BlockType::FuncType(idx) => Instruction::LoopWithFuncType(idx, 0),
wasmparser::BlockType::Type(ty) => Instruction::LoopWithType(convert_valtype(&ty), 0),
- })
+ });
}
fn visit_if(&mut self, ty: wasmparser::BlockType) -> Self::Output {
@@ -484,12 +484,12 @@ impl<'a, R: WasmModuleResources> wasmparser::VisitOperator<'a> for FunctionBuild
wasmparser::BlockType::Empty => Instruction::If(0, 0),
wasmparser::BlockType::FuncType(idx) => Instruction::IfWithFuncType(idx, 0, 0),
wasmparser::BlockType::Type(ty) => Instruction::IfWithType(convert_valtype(&ty), 0, 0),
- })
+ });
}
fn visit_else(&mut self) -> Self::Output {
self.label_ptrs.push(self.instructions.len());
- self.instructions.push(Instruction::Else(0))
+ self.instructions.push(Instruction::Else(0));
}
fn visit_end(&mut self) -> Self::Output {
@@ -536,15 +536,17 @@ impl<'a, R: WasmModuleResources> wasmparser::VisitOperator<'a> for FunctionBuild
.try_into()
.expect("else_instr_end_offset is too large, tinywasm does not support blocks that large");
}
- Some(Instruction::Block(end_offset))
- | Some(Instruction::BlockWithType(_, end_offset))
- | Some(Instruction::BlockWithFuncType(_, end_offset))
- | Some(Instruction::Loop(end_offset))
- | Some(Instruction::LoopWithFuncType(_, end_offset))
- | Some(Instruction::LoopWithType(_, end_offset))
- | Some(Instruction::If(_, end_offset))
- | Some(Instruction::IfWithFuncType(_, _, end_offset))
- | Some(Instruction::IfWithType(_, _, end_offset)) => {
+ Some(
+ Instruction::Block(end_offset)
+ | Instruction::BlockWithType(_, end_offset)
+ | Instruction::BlockWithFuncType(_, end_offset)
+ | Instruction::Loop(end_offset)
+ | Instruction::LoopWithFuncType(_, end_offset)
+ | Instruction::LoopWithType(_, end_offset)
+ | Instruction::If(_, end_offset)
+ | Instruction::IfWithFuncType(_, _, end_offset)
+ | Instruction::IfWithType(_, _, end_offset),
+ ) => {
*end_offset = (current_instr_ptr - label_pointer)
.try_into()
.expect("else_instr_end_offset is too large, tinywasm does not support blocks that large");
@@ -554,7 +556,7 @@ impl<'a, R: WasmModuleResources> wasmparser::VisitOperator<'a> for FunctionBuild
}
};
- self.instructions.push(Instruction::EndBlockFrame)
+ self.instructions.push(Instruction::EndBlockFrame);
}
fn visit_br_table(&mut self, targets: wasmparser::BrTable<'_>) -> Self::Output {
@@ -569,15 +571,15 @@ impl<'a, R: WasmModuleResources> wasmparser::VisitOperator<'a> for FunctionBuild
}
fn visit_call_indirect(&mut self, ty: u32, table: u32) -> Self::Output {
- self.instructions.push(Instruction::CallIndirect(ty, table))
+ self.instructions.push(Instruction::CallIndirect(ty, table));
}
fn visit_f32_const(&mut self, val: wasmparser::Ieee32) -> Self::Output {
- self.instructions.push(Instruction::F32Const(f32::from_bits(val.bits())))
+ self.instructions.push(Instruction::F32Const(f32::from_bits(val.bits())));
}
fn visit_f64_const(&mut self, val: wasmparser::Ieee64) -> Self::Output {
- self.instructions.push(Instruction::F64Const(f64::from_bits(val.bits())))
+ self.instructions.push(Instruction::F64Const(f64::from_bits(val.bits())));
}
// Bulk Memory Operations
@@ -594,16 +596,16 @@ impl<'a, R: WasmModuleResources> wasmparser::VisitOperator<'a> for FunctionBuild
}
fn visit_table_copy(&mut self, dst_table: u32, src_table: u32) -> Self::Output {
- self.instructions.push(Instruction::TableCopy { from: src_table, to: dst_table })
+ self.instructions.push(Instruction::TableCopy { from: src_table, to: dst_table });
}
// Reference Types
fn visit_ref_null(&mut self, ty: wasmparser::HeapType) -> Self::Output {
- self.instructions.push(Instruction::RefNull(convert_heaptype(ty)))
+ self.instructions.push(Instruction::RefNull(convert_heaptype(ty)));
}
fn visit_ref_is_null(&mut self) -> Self::Output {
- self.instructions.push(Instruction::RefIsNull)
+ self.instructions.push(Instruction::RefIsNull);
}
fn visit_typed_select(&mut self, ty: wasmparser::ValType) -> Self::Output {
@@ -614,7 +616,7 @@ impl<'a, R: WasmModuleResources> wasmparser::VisitOperator<'a> for FunctionBuild
wasmparser::ValType::F64 => Instruction::Select64,
wasmparser::ValType::V128 => Instruction::Select128,
wasmparser::ValType::Ref(_) => Instruction::SelectRef,
- })
+ });
}
define_primitive_operands! {