From dd87384893dadfad0633d7dd1f47b0fd4ffc67d3 Mon Sep 17 00:00:00 2001 From: Hero Bird Date: Sun, 31 Jan 2021 15:27:15 +0100 Subject: [PATCH 1/3] Applies all clippy suggestions (#244) * Applies all clippy suggestions In a few cases a clippy annotation was provided to ignore the clippy warning. * apply rustfmt * make wasmi compiler under no_std again * use rustfmt +stable --- examples/invoke.rs | 28 ++- examples/tictactoe.rs | 14 +- src/func.rs | 16 +- src/host.rs | 6 +- src/imports.rs | 26 +-- src/isa.rs | 6 +- src/lib.rs | 8 +- src/memory/mod.rs | 36 ++-- src/module.rs | 16 +- src/prepare/compile.rs | 15 +- src/prepare/mod.rs | 5 +- src/prepare/tests.rs | 5 +- src/runner.rs | 421 ++++++++++++++++++++-------------------- src/table.rs | 2 +- src/tests/host.rs | 15 +- src/tests/mod.rs | 1 - src/tests/wasm.rs | 8 +- src/types.rs | 2 +- src/value.rs | 20 +- tests/spec/run.rs | 28 ++- validation/src/func.rs | 20 +- validation/src/lib.rs | 31 ++- validation/src/stack.rs | 2 +- 23 files changed, 343 insertions(+), 388 deletions(-) diff --git a/examples/invoke.rs b/examples/invoke.rs index a2389cc7c99..5e49c823470 100644 --- a/examples/invoke.rs +++ b/examples/invoke.rs @@ -34,11 +34,11 @@ fn main() { .entries() .iter() .find(|entry| func_name == entry.field()) - .expect(&format!("No export with name {} found", func_name)); + .unwrap_or_else(|| panic!("No export with name {} found", func_name)); // Function index in the function index space (internally-defined + imported) let function_index: usize = match found_entry.internal() { - &Internal::Function(index) => index as usize, + Internal::Function(index) => *index as usize, _ => panic!("Founded export is not a function"), }; @@ -48,10 +48,7 @@ fn main() { Some(import) => import .entries() .iter() - .filter(|entry| match entry.external() { - &External::Function(_) => true, - _ => false, - }) + .filter(|entry| matches!(entry.external(), External::Function(_))) .count(), None => 0, }; @@ -64,8 +61,9 @@ fn main() { function_section.entries()[function_index_in_section].type_ref() as usize; // Use the reference to get an actual function type + #[allow(clippy::infallible_destructuring_match)] let function_type: &FunctionType = match &type_section.types()[func_type_ref] { - &Type::Function(ref func_type) => func_type, + Type::Function(ref func_type) => func_type, }; // Parses arguments and constructs runtime values in correspondence of their types @@ -74,26 +72,26 @@ fn main() { .iter() .enumerate() .map(|(i, value)| match value { - &ValueType::I32 => RuntimeValue::I32( + ValueType::I32 => RuntimeValue::I32( program_args[i] .parse::() - .expect(&format!("Can't parse arg #{} as i32", program_args[i])), + .unwrap_or_else(|_| panic!("Can't parse arg #{} as i32", program_args[i])), ), - &ValueType::I64 => RuntimeValue::I64( + ValueType::I64 => RuntimeValue::I64( program_args[i] .parse::() - .expect(&format!("Can't parse arg #{} as i64", program_args[i])), + .unwrap_or_else(|_| panic!("Can't parse arg #{} as i64", program_args[i])), ), - &ValueType::F32 => RuntimeValue::F32( + ValueType::F32 => RuntimeValue::F32( program_args[i] .parse::() - .expect(&format!("Can't parse arg #{} as f32", program_args[i])) + .unwrap_or_else(|_| panic!("Can't parse arg #{} as f32", program_args[i])) .into(), ), - &ValueType::F64 => RuntimeValue::F64( + ValueType::F64 => RuntimeValue::F64( program_args[i] .parse::() - .expect(&format!("Can't parse arg #{} as f64", program_args[i])) + .unwrap_or_else(|_| panic!("Can't parse arg #{} as f64", program_args[i])) .into(), ), }) diff --git a/examples/tictactoe.rs b/examples/tictactoe.rs index 7ee89a024b6..74a7adeeb43 100644 --- a/examples/tictactoe.rs +++ b/examples/tictactoe.rs @@ -1,3 +1,5 @@ +#![allow(clippy::wrong_self_convention)] + extern crate parity_wasm; extern crate wasmi; @@ -67,7 +69,7 @@ mod tictactoe { } pub fn set(&mut self, idx: i32, player: Player) -> Result<(), Error> { - if idx < 0 || idx > 9 { + if !(0..9).contains(&idx) { return Err(Error::OutOfRange); } if self.board[idx as usize] != None { @@ -78,7 +80,7 @@ mod tictactoe { } pub fn get(&self, idx: i32) -> Result, Error> { - if idx < 0 || idx > 9 { + if !(0..9).contains(&idx) { return Err(Error::OutOfRange); } Ok(self.board[idx as usize]) @@ -103,6 +105,7 @@ mod tictactoe { ]; // Returns Some(player) if all cells contain same Player. + #[allow(clippy::question_mark)] let all_same = |i1: usize, i2: usize, i3: usize| -> Option { if self.board[i1].is_none() { return None; @@ -221,14 +224,13 @@ fn play( { let mut runtime = Runtime { player: turn_of, - game: game, + game, }; let _ = instance.invoke_export("mk_turn", &[], &mut runtime)?; } - match game.game_result() { - Some(game_result) => break game_result, - None => {} + if let Some(game_result) = game.game_result() { + break game_result; } turn_of = next_turn_of; diff --git a/src/func.rs b/src/func.rs index 4c9d9dda5cf..d47afcae1a5 100644 --- a/src/func.rs +++ b/src/func.rs @@ -60,12 +60,12 @@ pub(crate) enum FuncInstanceInternal { impl fmt::Debug for FuncInstance { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.as_internal() { - &FuncInstanceInternal::Internal { ref signature, .. } => { + FuncInstanceInternal::Internal { ref signature, .. } => { // We can't write description of self.module here, because it generate // debug string for function instances and this will lead to infinite loop. write!(f, "Internal {{ signature={:?} }}", signature,) } - &FuncInstanceInternal::Host { ref signature, .. } => { + FuncInstanceInternal::Host { ref signature, .. } => { write!(f, "Host {{ signature={:?} }}", signature) } } @@ -112,7 +112,7 @@ impl FuncInstance { ) -> FuncRef { let func = FuncInstanceInternal::Internal { signature, - module: module, + module, body: Rc::new(body), }; FuncRef(Rc::new(FuncInstance(func))) @@ -269,19 +269,19 @@ impl<'args> FuncInvocation<'args> { /// Whether this invocation is currently resumable. pub fn is_resumable(&self) -> bool { match &self.kind { - &FuncInvocationKind::Internal(ref interpreter) => interpreter.state().is_resumable(), - &FuncInvocationKind::Host { .. } => false, + FuncInvocationKind::Internal(ref interpreter) => interpreter.state().is_resumable(), + FuncInvocationKind::Host { .. } => false, } } /// If the invocation is resumable, the expected return value type to be feed back in. pub fn resumable_value_type(&self) -> Option { match &self.kind { - &FuncInvocationKind::Internal(ref interpreter) => match interpreter.state() { - &InterpreterState::Resumable(ref value_type) => value_type.clone(), + FuncInvocationKind::Internal(ref interpreter) => match interpreter.state() { + InterpreterState::Resumable(ref value_type) => *value_type, _ => None, }, - &FuncInvocationKind::Host { .. } => None, + FuncInvocationKind::Host { .. } => None, } } diff --git a/src/host.rs b/src/host.rs index aff0b3feec0..ba70f828e8c 100644 --- a/src/host.rs +++ b/src/host.rs @@ -32,10 +32,10 @@ impl<'a> RuntimeArgs<'a> { where T: FromRuntimeValue, { - Ok(self - .nth_value_checked(idx)? + self.nth_value_checked(idx)? .try_into() - .ok_or_else(|| TrapKind::UnexpectedSignature)?) + .ok_or(TrapKind::UnexpectedSignature) + .map_err(Into::into) } /// Extract argument as a [`RuntimeValue`] by index `idx`. diff --git a/src/imports.rs b/src/imports.rs index be07dfbc225..4f3a1a831e4 100644 --- a/src/imports.rs +++ b/src/imports.rs @@ -255,14 +255,11 @@ pub trait ModuleImportResolver { impl ModuleImportResolver for ModuleRef { fn resolve_func(&self, field_name: &str, _signature: &Signature) -> Result { - Ok(self - .export_by_name(field_name) + self.export_by_name(field_name) .ok_or_else(|| Error::Instantiation(format!("Export {} not found", field_name)))? .as_func() .cloned() - .ok_or_else(|| { - Error::Instantiation(format!("Export {} is not a function", field_name)) - })?) + .ok_or_else(|| Error::Instantiation(format!("Export {} is not a function", field_name))) } fn resolve_global( @@ -270,14 +267,11 @@ impl ModuleImportResolver for ModuleRef { field_name: &str, _global_type: &GlobalDescriptor, ) -> Result { - Ok(self - .export_by_name(field_name) + self.export_by_name(field_name) .ok_or_else(|| Error::Instantiation(format!("Export {} not found", field_name)))? .as_global() .cloned() - .ok_or_else(|| { - Error::Instantiation(format!("Export {} is not a global", field_name)) - })?) + .ok_or_else(|| Error::Instantiation(format!("Export {} is not a global", field_name))) } fn resolve_memory( @@ -285,14 +279,11 @@ impl ModuleImportResolver for ModuleRef { field_name: &str, _memory_type: &MemoryDescriptor, ) -> Result { - Ok(self - .export_by_name(field_name) + self.export_by_name(field_name) .ok_or_else(|| Error::Instantiation(format!("Export {} not found", field_name)))? .as_memory() .cloned() - .ok_or_else(|| { - Error::Instantiation(format!("Export {} is not a memory", field_name)) - })?) + .ok_or_else(|| Error::Instantiation(format!("Export {} is not a memory", field_name))) } fn resolve_table( @@ -300,11 +291,10 @@ impl ModuleImportResolver for ModuleRef { field_name: &str, _table_type: &TableDescriptor, ) -> Result { - Ok(self - .export_by_name(field_name) + self.export_by_name(field_name) .ok_or_else(|| Error::Instantiation(format!("Export {} not found", field_name)))? .as_table() .cloned() - .ok_or_else(|| Error::Instantiation(format!("Export {} is not a table", field_name)))?) + .ok_or_else(|| Error::Instantiation(format!("Export {} is not a table", field_name))) } } diff --git a/src/isa.rs b/src/isa.rs index 1981706295e..c6e5201342a 100644 --- a/src/isa.rs +++ b/src/isa.rs @@ -595,11 +595,7 @@ impl<'a> Iterator for InstructionIter<'a> { #[inline] fn next(&mut self) -> Option { - let internal = if let Some(i) = self.instructions.get(self.position as usize) { - i - } else { - return None; - }; + let internal = self.instructions.get(self.position as usize)?; let out = match *internal { InstructionInternal::GetLocal(x) => Instruction::GetLocal(x), diff --git a/src/lib.rs b/src/lib.rs index 652bb893c9a..1dd324634f8 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -96,6 +96,8 @@ #![warn(missing_docs)] #![cfg_attr(not(feature = "std"), no_std)] +#![allow(clippy::len_without_is_empty)] +#![allow(clippy::new_ret_no_self)] #[cfg(not(feature = "std"))] #[macro_use] @@ -246,10 +248,7 @@ pub enum TrapKind { impl TrapKind { /// Whether this trap is specified by the host. pub fn is_host(&self) -> bool { - match self { - &TrapKind::Host(_) => true, - _ => false, - } + matches!(self, TrapKind::Host(_)) } } @@ -333,6 +332,7 @@ impl Error { } } +#[allow(clippy::from_over_into)] impl Into for Error { fn into(self) -> String { match self { diff --git a/src/memory/mod.rs b/src/memory/mod.rs index 4448e7f0b4b..e23bd3474c8 100644 --- a/src/memory/mod.rs +++ b/src/memory/mod.rs @@ -143,13 +143,11 @@ impl MemoryInstance { let initial_size: Bytes = initial.into(); Ok(MemoryInstance { - limits: limits, - buffer: RefCell::new( - ByteBuf::new(initial_size.0).map_err(|err| Error::Memory(err.to_string()))?, - ), - initial: initial, + limits, + buffer: RefCell::new(ByteBuf::new(initial_size.0).map_err(Error::Memory)?), + initial, current_size: Cell::new(initial_size.0), - maximum: maximum, + maximum, }) } @@ -267,9 +265,9 @@ impl MemoryInstance { return Ok(size_before_grow); } if additional > Pages(65536) { - return Err(Error::Memory(format!( - "Trying to grow memory by more than 65536 pages" - ))); + return Err(Error::Memory( + "Trying to grow memory by more than 65536 pages".to_string(), + )); } let new_size: Pages = size_before_grow + additional; @@ -287,7 +285,7 @@ impl MemoryInstance { self.buffer .borrow_mut() .realloc(new_buffer_length.0) - .map_err(|err| Error::Memory(err.to_string()))?; + .map_err(Error::Memory)?; self.current_size.set(new_buffer_length.0); @@ -316,10 +314,7 @@ impl MemoryInstance { ))); } - Ok(CheckedRegion { - offset: offset, - size: size, - }) + Ok(CheckedRegion { offset, size }) } fn checked_region_pair( @@ -421,9 +416,9 @@ impl MemoryInstance { self.checked_region_pair(&mut buffer, src_offset, len, dst_offset, len)?; if read_region.intersects(&write_region) { - return Err(Error::Memory(format!( - "non-overlapping copy is used for overlapping regions" - ))); + return Err(Error::Memory( + "non-overlapping copy is used for overlapping regions".to_string(), + )); } unsafe { @@ -501,10 +496,7 @@ impl MemoryInstance { /// /// Might be useful for some optimization shenanigans. pub fn erase(&self) -> Result<(), Error> { - self.buffer - .borrow_mut() - .erase() - .map_err(|err| Error::Memory(err)) + self.buffer.borrow_mut().erase().map_err(Error::Memory) } /// Provides direct access to the underlying memory buffer. @@ -564,7 +556,7 @@ mod tests { for (index, &(initial, maybe_max, expected_ok)) in fixtures.iter().enumerate() { let initial: Pages = Pages(initial); - let maximum: Option = maybe_max.map(|m| Pages(m)); + let maximum: Option = maybe_max.map(Pages); let result = MemoryInstance::alloc(initial, maximum); if result.is_ok() != expected_ok { panic!( diff --git a/src/module.rs b/src/module.rs index a94e6399894..b98a8318b4b 100644 --- a/src/module.rs +++ b/src/module.rs @@ -215,7 +215,7 @@ impl ModuleInstance { /// Access all globals. This is a non-standard API so it's unlikely to be /// portable to other engines. - pub fn globals<'a>(&self) -> Ref> { + pub fn globals(&self) -> Ref> { self.globals.borrow() } @@ -240,7 +240,7 @@ impl ModuleInstance { .import_section() .map(|is| is.entries()) .unwrap_or(&[]) - .into_iter(); + .iter(); let mut extern_vals = extern_vals; loop { // Iterate on imports and extern_vals in lockstep, a-la `Iterator:zip`. @@ -312,9 +312,7 @@ impl ModuleInstance { "Due to validation func and body counts must match" ); - for (index, (ty, body)) in - Iterator::zip(funcs.into_iter(), bodies.into_iter()).enumerate() - { + for (index, (ty, body)) in Iterator::zip(funcs.iter(), bodies.iter()).enumerate() { let signature = instance .signature_by_index(ty.type_ref()) .expect("Due to validation type should exists"); @@ -323,7 +321,7 @@ impl ModuleInstance { ).clone(); let func_body = FuncBody { locals: body.locals().to_vec(), - code: code, + code, }; let func_instance = FuncInstance::alloc_internal(Rc::downgrade(&instance.0), signature, func_body); @@ -440,7 +438,7 @@ impl ModuleInstance { )); } - for (j, func_idx) in element_segment.members().into_iter().enumerate() { + for (j, func_idx) in element_segment.members().iter().enumerate() { let func = module_ref .func_by_index(*func_idx) .expect("Due to validation funcs from element segments should exists"); @@ -632,7 +630,7 @@ impl ModuleInstance { ) -> Result, Error> { let func_instance = self.func_by_name(func_name)?; - FuncInstance::invoke(&func_instance, args, externals).map_err(|t| Error::Trap(t)) + FuncInstance::invoke(&func_instance, args, externals).map_err(Error::Trap) } /// Invoke exported function by a name using recycled stacks. @@ -652,7 +650,7 @@ impl ModuleInstance { let func_instance = self.func_by_name(func_name)?; FuncInstance::invoke_with_stack(&func_instance, args, externals, stack_recycler) - .map_err(|t| Error::Trap(t)) + .map_err(Error::Trap) } fn func_by_name(&self, func_name: &str) -> Result { diff --git a/src/prepare/compile.rs b/src/prepare/compile.rs index 17a7d4d974c..e8410b40367 100644 --- a/src/prepare/compile.rs +++ b/src/prepare/compile.rs @@ -278,7 +278,7 @@ impl Compiler { context.step(instruction)?; // These two unwraps are guaranteed to succeed by validation. - const REQUIRE_TARGET_PROOF: &'static str = + const REQUIRE_TARGET_PROOF: &str = "validation step ensures that the value stack underflows; validation also ensures that the depth is correct; qed"; @@ -1179,7 +1179,7 @@ impl Sink { let dst_pc = self.pc_or_placeholder(label, || isa::Reloc::Br { pc }); self.ins.push(isa::InstructionInternal::Br(isa::Target { dst_pc, - drop_keep: drop_keep.into(), + drop_keep, })); } @@ -1190,7 +1190,7 @@ impl Sink { self.ins .push(isa::InstructionInternal::BrIfEqz(isa::Target { dst_pc, - drop_keep: drop_keep.into(), + drop_keep, })); } @@ -1201,7 +1201,7 @@ impl Sink { self.ins .push(isa::InstructionInternal::BrIfNez(isa::Target { dst_pc, - drop_keep: drop_keep.into(), + drop_keep, })); } @@ -1221,7 +1221,7 @@ impl Sink { self.ins .push(isa::InstructionInternal::BrTableTarget(isa::Target { dst_pc, - drop_keep: drop_keep.into(), + drop_keep, })); } } @@ -1262,9 +1262,8 @@ impl Sink { { self.labels .iter() - .all(|(state, unresolved)| match (state, unresolved) { - (Label::Resolved(_), unresolved) if unresolved.is_empty() => true, - _ => false, + .all(|(state, unresolved)| { + matches!((state, unresolved), (Label::Resolved(_), unresolved) if unresolved.is_empty()) }) }, "there are unresolved labels left: {:?}", diff --git a/src/prepare/mod.rs b/src/prepare/mod.rs index 7820197e6f8..32097680213 100644 --- a/src/prepare/mod.rs +++ b/src/prepare/mod.rs @@ -3,6 +3,9 @@ use alloc::vec::Vec; use parity_wasm::elements::Module; use validation::{validate_module, Error, Validator}; +#[cfg(feature = "core")] +use crate::alloc::string::ToString; + mod compile; #[cfg(test)] @@ -154,7 +157,7 @@ pub fn deny_floating_point(module: &Module) -> Result<(), Error> { .chain(func.return_type().as_ref()) .any(|&typ| typ == ValueType::F32 || typ == ValueType::F64) { - return Err(Error(format!("Use of floating point types denied"))); + return Err(Error("Use of floating point types denied".to_string())); } } } diff --git a/src/prepare/tests.rs b/src/prepare/tests.rs index 0f2ce5da9e4..1638e0e4acb 100644 --- a/src/prepare/tests.rs +++ b/src/prepare/tests.rs @@ -8,13 +8,10 @@ use super::{compile_module, CompiledModule}; use crate::isa; use parity_wasm::{deserialize_buffer, elements::Module}; -use wabt; - fn validate(wat: &str) -> CompiledModule { let wasm = wabt::wat2wasm(wat).unwrap(); let module = deserialize_buffer::(&wasm).unwrap(); - let compiled_module = compile_module(module).unwrap(); - compiled_module + compile_module(module).unwrap() } fn compile(module: &CompiledModule) -> (Vec, Vec) { diff --git a/src/runner.rs b/src/runner.rs index db21fd897e2..7fbc0b819b3 100644 --- a/src/runner.rs +++ b/src/runner.rs @@ -1,3 +1,5 @@ +#![allow(clippy::unnecessary_wraps)] + use crate::func::{FuncInstance, FuncInstanceInternal, FuncRef}; use crate::host::Externals; use crate::isa; @@ -147,10 +149,7 @@ pub enum InterpreterState { impl InterpreterState { pub fn is_resumable(&self) -> bool { - match self { - &InterpreterState::Resumable(_) => true, - _ => false, - } + matches!(self, InterpreterState::Resumable(_)) } } @@ -376,217 +375,217 @@ impl Interpreter { instruction: &isa::Instruction, ) -> Result { match instruction { - &isa::Instruction::Unreachable => self.run_unreachable(context), - - &isa::Instruction::Br(target) => self.run_br(context, target.clone()), - &isa::Instruction::BrIfEqz(target) => self.run_br_eqz(target.clone()), - &isa::Instruction::BrIfNez(target) => self.run_br_nez(target.clone()), - &isa::Instruction::BrTable(targets) => self.run_br_table(targets), - &isa::Instruction::Return(drop_keep) => self.run_return(drop_keep), - - &isa::Instruction::Call(index) => self.run_call(context, index), - &isa::Instruction::CallIndirect(index) => self.run_call_indirect(context, index), - - &isa::Instruction::Drop => self.run_drop(), - &isa::Instruction::Select => self.run_select(), - - &isa::Instruction::GetLocal(depth) => self.run_get_local(depth), - &isa::Instruction::SetLocal(depth) => self.run_set_local(depth), - &isa::Instruction::TeeLocal(depth) => self.run_tee_local(depth), - &isa::Instruction::GetGlobal(index) => self.run_get_global(context, index), - &isa::Instruction::SetGlobal(index) => self.run_set_global(context, index), - - &isa::Instruction::I32Load(offset) => self.run_load::(context, offset), - &isa::Instruction::I64Load(offset) => self.run_load::(context, offset), - &isa::Instruction::F32Load(offset) => self.run_load::(context, offset), - &isa::Instruction::F64Load(offset) => self.run_load::(context, offset), - &isa::Instruction::I32Load8S(offset) => { - self.run_load_extend::(context, offset) + isa::Instruction::Unreachable => self.run_unreachable(context), + + isa::Instruction::Br(target) => self.run_br(context, *target), + isa::Instruction::BrIfEqz(target) => self.run_br_eqz(*target), + isa::Instruction::BrIfNez(target) => self.run_br_nez(*target), + isa::Instruction::BrTable(targets) => self.run_br_table(*targets), + isa::Instruction::Return(drop_keep) => self.run_return(*drop_keep), + + isa::Instruction::Call(index) => self.run_call(context, *index), + isa::Instruction::CallIndirect(index) => self.run_call_indirect(context, *index), + + isa::Instruction::Drop => self.run_drop(), + isa::Instruction::Select => self.run_select(), + + isa::Instruction::GetLocal(depth) => self.run_get_local(*depth), + isa::Instruction::SetLocal(depth) => self.run_set_local(*depth), + isa::Instruction::TeeLocal(depth) => self.run_tee_local(*depth), + isa::Instruction::GetGlobal(index) => self.run_get_global(context, *index), + isa::Instruction::SetGlobal(index) => self.run_set_global(context, *index), + + isa::Instruction::I32Load(offset) => self.run_load::(context, *offset), + isa::Instruction::I64Load(offset) => self.run_load::(context, *offset), + isa::Instruction::F32Load(offset) => self.run_load::(context, *offset), + isa::Instruction::F64Load(offset) => self.run_load::(context, *offset), + isa::Instruction::I32Load8S(offset) => { + self.run_load_extend::(context, *offset) } - &isa::Instruction::I32Load8U(offset) => { - self.run_load_extend::(context, offset) + isa::Instruction::I32Load8U(offset) => { + self.run_load_extend::(context, *offset) } - &isa::Instruction::I32Load16S(offset) => { - self.run_load_extend::(context, offset) + isa::Instruction::I32Load16S(offset) => { + self.run_load_extend::(context, *offset) } - &isa::Instruction::I32Load16U(offset) => { - self.run_load_extend::(context, offset) + isa::Instruction::I32Load16U(offset) => { + self.run_load_extend::(context, *offset) } - &isa::Instruction::I64Load8S(offset) => { - self.run_load_extend::(context, offset) + isa::Instruction::I64Load8S(offset) => { + self.run_load_extend::(context, *offset) } - &isa::Instruction::I64Load8U(offset) => { - self.run_load_extend::(context, offset) + isa::Instruction::I64Load8U(offset) => { + self.run_load_extend::(context, *offset) } - &isa::Instruction::I64Load16S(offset) => { - self.run_load_extend::(context, offset) + isa::Instruction::I64Load16S(offset) => { + self.run_load_extend::(context, *offset) } - &isa::Instruction::I64Load16U(offset) => { - self.run_load_extend::(context, offset) + isa::Instruction::I64Load16U(offset) => { + self.run_load_extend::(context, *offset) } - &isa::Instruction::I64Load32S(offset) => { - self.run_load_extend::(context, offset) + isa::Instruction::I64Load32S(offset) => { + self.run_load_extend::(context, *offset) } - &isa::Instruction::I64Load32U(offset) => { - self.run_load_extend::(context, offset) + isa::Instruction::I64Load32U(offset) => { + self.run_load_extend::(context, *offset) } - &isa::Instruction::I32Store(offset) => self.run_store::(context, offset), - &isa::Instruction::I64Store(offset) => self.run_store::(context, offset), - &isa::Instruction::F32Store(offset) => self.run_store::(context, offset), - &isa::Instruction::F64Store(offset) => self.run_store::(context, offset), - &isa::Instruction::I32Store8(offset) => self.run_store_wrap::(context, offset), - &isa::Instruction::I32Store16(offset) => { - self.run_store_wrap::(context, offset) + isa::Instruction::I32Store(offset) => self.run_store::(context, *offset), + isa::Instruction::I64Store(offset) => self.run_store::(context, *offset), + isa::Instruction::F32Store(offset) => self.run_store::(context, *offset), + isa::Instruction::F64Store(offset) => self.run_store::(context, *offset), + isa::Instruction::I32Store8(offset) => self.run_store_wrap::(context, *offset), + isa::Instruction::I32Store16(offset) => { + self.run_store_wrap::(context, *offset) } - &isa::Instruction::I64Store8(offset) => self.run_store_wrap::(context, offset), - &isa::Instruction::I64Store16(offset) => { - self.run_store_wrap::(context, offset) + isa::Instruction::I64Store8(offset) => self.run_store_wrap::(context, *offset), + isa::Instruction::I64Store16(offset) => { + self.run_store_wrap::(context, *offset) } - &isa::Instruction::I64Store32(offset) => { - self.run_store_wrap::(context, offset) + isa::Instruction::I64Store32(offset) => { + self.run_store_wrap::(context, *offset) } - &isa::Instruction::CurrentMemory => self.run_current_memory(context), - &isa::Instruction::GrowMemory => self.run_grow_memory(context), - - &isa::Instruction::I32Const(val) => self.run_const(val.into()), - &isa::Instruction::I64Const(val) => self.run_const(val.into()), - &isa::Instruction::F32Const(val) => self.run_const(val.into()), - &isa::Instruction::F64Const(val) => self.run_const(val.into()), - - &isa::Instruction::I32Eqz => self.run_eqz::(), - &isa::Instruction::I32Eq => self.run_eq::(), - &isa::Instruction::I32Ne => self.run_ne::(), - &isa::Instruction::I32LtS => self.run_lt::(), - &isa::Instruction::I32LtU => self.run_lt::(), - &isa::Instruction::I32GtS => self.run_gt::(), - &isa::Instruction::I32GtU => self.run_gt::(), - &isa::Instruction::I32LeS => self.run_lte::(), - &isa::Instruction::I32LeU => self.run_lte::(), - &isa::Instruction::I32GeS => self.run_gte::(), - &isa::Instruction::I32GeU => self.run_gte::(), - - &isa::Instruction::I64Eqz => self.run_eqz::(), - &isa::Instruction::I64Eq => self.run_eq::(), - &isa::Instruction::I64Ne => self.run_ne::(), - &isa::Instruction::I64LtS => self.run_lt::(), - &isa::Instruction::I64LtU => self.run_lt::(), - &isa::Instruction::I64GtS => self.run_gt::(), - &isa::Instruction::I64GtU => self.run_gt::(), - &isa::Instruction::I64LeS => self.run_lte::(), - &isa::Instruction::I64LeU => self.run_lte::(), - &isa::Instruction::I64GeS => self.run_gte::(), - &isa::Instruction::I64GeU => self.run_gte::(), - - &isa::Instruction::F32Eq => self.run_eq::(), - &isa::Instruction::F32Ne => self.run_ne::(), - &isa::Instruction::F32Lt => self.run_lt::(), - &isa::Instruction::F32Gt => self.run_gt::(), - &isa::Instruction::F32Le => self.run_lte::(), - &isa::Instruction::F32Ge => self.run_gte::(), - - &isa::Instruction::F64Eq => self.run_eq::(), - &isa::Instruction::F64Ne => self.run_ne::(), - &isa::Instruction::F64Lt => self.run_lt::(), - &isa::Instruction::F64Gt => self.run_gt::(), - &isa::Instruction::F64Le => self.run_lte::(), - &isa::Instruction::F64Ge => self.run_gte::(), - - &isa::Instruction::I32Clz => self.run_clz::(), - &isa::Instruction::I32Ctz => self.run_ctz::(), - &isa::Instruction::I32Popcnt => self.run_popcnt::(), - &isa::Instruction::I32Add => self.run_add::(), - &isa::Instruction::I32Sub => self.run_sub::(), - &isa::Instruction::I32Mul => self.run_mul::(), - &isa::Instruction::I32DivS => self.run_div::(), - &isa::Instruction::I32DivU => self.run_div::(), - &isa::Instruction::I32RemS => self.run_rem::(), - &isa::Instruction::I32RemU => self.run_rem::(), - &isa::Instruction::I32And => self.run_and::(), - &isa::Instruction::I32Or => self.run_or::(), - &isa::Instruction::I32Xor => self.run_xor::(), - &isa::Instruction::I32Shl => self.run_shl::(0x1F), - &isa::Instruction::I32ShrS => self.run_shr::(0x1F), - &isa::Instruction::I32ShrU => self.run_shr::(0x1F), - &isa::Instruction::I32Rotl => self.run_rotl::(), - &isa::Instruction::I32Rotr => self.run_rotr::(), - - &isa::Instruction::I64Clz => self.run_clz::(), - &isa::Instruction::I64Ctz => self.run_ctz::(), - &isa::Instruction::I64Popcnt => self.run_popcnt::(), - &isa::Instruction::I64Add => self.run_add::(), - &isa::Instruction::I64Sub => self.run_sub::(), - &isa::Instruction::I64Mul => self.run_mul::(), - &isa::Instruction::I64DivS => self.run_div::(), - &isa::Instruction::I64DivU => self.run_div::(), - &isa::Instruction::I64RemS => self.run_rem::(), - &isa::Instruction::I64RemU => self.run_rem::(), - &isa::Instruction::I64And => self.run_and::(), - &isa::Instruction::I64Or => self.run_or::(), - &isa::Instruction::I64Xor => self.run_xor::(), - &isa::Instruction::I64Shl => self.run_shl::(0x3F), - &isa::Instruction::I64ShrS => self.run_shr::(0x3F), - &isa::Instruction::I64ShrU => self.run_shr::(0x3F), - &isa::Instruction::I64Rotl => self.run_rotl::(), - &isa::Instruction::I64Rotr => self.run_rotr::(), - - &isa::Instruction::F32Abs => self.run_abs::(), - &isa::Instruction::F32Neg => self.run_neg::(), - &isa::Instruction::F32Ceil => self.run_ceil::(), - &isa::Instruction::F32Floor => self.run_floor::(), - &isa::Instruction::F32Trunc => self.run_trunc::(), - &isa::Instruction::F32Nearest => self.run_nearest::(), - &isa::Instruction::F32Sqrt => self.run_sqrt::(), - &isa::Instruction::F32Add => self.run_add::(), - &isa::Instruction::F32Sub => self.run_sub::(), - &isa::Instruction::F32Mul => self.run_mul::(), - &isa::Instruction::F32Div => self.run_div::(), - &isa::Instruction::F32Min => self.run_min::(), - &isa::Instruction::F32Max => self.run_max::(), - &isa::Instruction::F32Copysign => self.run_copysign::(), - - &isa::Instruction::F64Abs => self.run_abs::(), - &isa::Instruction::F64Neg => self.run_neg::(), - &isa::Instruction::F64Ceil => self.run_ceil::(), - &isa::Instruction::F64Floor => self.run_floor::(), - &isa::Instruction::F64Trunc => self.run_trunc::(), - &isa::Instruction::F64Nearest => self.run_nearest::(), - &isa::Instruction::F64Sqrt => self.run_sqrt::(), - &isa::Instruction::F64Add => self.run_add::(), - &isa::Instruction::F64Sub => self.run_sub::(), - &isa::Instruction::F64Mul => self.run_mul::(), - &isa::Instruction::F64Div => self.run_div::(), - &isa::Instruction::F64Min => self.run_min::(), - &isa::Instruction::F64Max => self.run_max::(), - &isa::Instruction::F64Copysign => self.run_copysign::(), - - &isa::Instruction::I32WrapI64 => self.run_wrap::(), - &isa::Instruction::I32TruncSF32 => self.run_trunc_to_int::(), - &isa::Instruction::I32TruncUF32 => self.run_trunc_to_int::(), - &isa::Instruction::I32TruncSF64 => self.run_trunc_to_int::(), - &isa::Instruction::I32TruncUF64 => self.run_trunc_to_int::(), - &isa::Instruction::I64ExtendSI32 => self.run_extend::(), - &isa::Instruction::I64ExtendUI32 => self.run_extend::(), - &isa::Instruction::I64TruncSF32 => self.run_trunc_to_int::(), - &isa::Instruction::I64TruncUF32 => self.run_trunc_to_int::(), - &isa::Instruction::I64TruncSF64 => self.run_trunc_to_int::(), - &isa::Instruction::I64TruncUF64 => self.run_trunc_to_int::(), - &isa::Instruction::F32ConvertSI32 => self.run_extend::(), - &isa::Instruction::F32ConvertUI32 => self.run_extend::(), - &isa::Instruction::F32ConvertSI64 => self.run_wrap::(), - &isa::Instruction::F32ConvertUI64 => self.run_wrap::(), - &isa::Instruction::F32DemoteF64 => self.run_wrap::(), - &isa::Instruction::F64ConvertSI32 => self.run_extend::(), - &isa::Instruction::F64ConvertUI32 => self.run_extend::(), - &isa::Instruction::F64ConvertSI64 => self.run_extend::(), - &isa::Instruction::F64ConvertUI64 => self.run_extend::(), - &isa::Instruction::F64PromoteF32 => self.run_extend::(), - - &isa::Instruction::I32ReinterpretF32 => self.run_reinterpret::(), - &isa::Instruction::I64ReinterpretF64 => self.run_reinterpret::(), - &isa::Instruction::F32ReinterpretI32 => self.run_reinterpret::(), - &isa::Instruction::F64ReinterpretI64 => self.run_reinterpret::(), + isa::Instruction::CurrentMemory => self.run_current_memory(context), + isa::Instruction::GrowMemory => self.run_grow_memory(context), + + isa::Instruction::I32Const(val) => self.run_const((*val).into()), + isa::Instruction::I64Const(val) => self.run_const((*val).into()), + isa::Instruction::F32Const(val) => self.run_const((*val).into()), + isa::Instruction::F64Const(val) => self.run_const((*val).into()), + + isa::Instruction::I32Eqz => self.run_eqz::(), + isa::Instruction::I32Eq => self.run_eq::(), + isa::Instruction::I32Ne => self.run_ne::(), + isa::Instruction::I32LtS => self.run_lt::(), + isa::Instruction::I32LtU => self.run_lt::(), + isa::Instruction::I32GtS => self.run_gt::(), + isa::Instruction::I32GtU => self.run_gt::(), + isa::Instruction::I32LeS => self.run_lte::(), + isa::Instruction::I32LeU => self.run_lte::(), + isa::Instruction::I32GeS => self.run_gte::(), + isa::Instruction::I32GeU => self.run_gte::(), + + isa::Instruction::I64Eqz => self.run_eqz::(), + isa::Instruction::I64Eq => self.run_eq::(), + isa::Instruction::I64Ne => self.run_ne::(), + isa::Instruction::I64LtS => self.run_lt::(), + isa::Instruction::I64LtU => self.run_lt::(), + isa::Instruction::I64GtS => self.run_gt::(), + isa::Instruction::I64GtU => self.run_gt::(), + isa::Instruction::I64LeS => self.run_lte::(), + isa::Instruction::I64LeU => self.run_lte::(), + isa::Instruction::I64GeS => self.run_gte::(), + isa::Instruction::I64GeU => self.run_gte::(), + + isa::Instruction::F32Eq => self.run_eq::(), + isa::Instruction::F32Ne => self.run_ne::(), + isa::Instruction::F32Lt => self.run_lt::(), + isa::Instruction::F32Gt => self.run_gt::(), + isa::Instruction::F32Le => self.run_lte::(), + isa::Instruction::F32Ge => self.run_gte::(), + + isa::Instruction::F64Eq => self.run_eq::(), + isa::Instruction::F64Ne => self.run_ne::(), + isa::Instruction::F64Lt => self.run_lt::(), + isa::Instruction::F64Gt => self.run_gt::(), + isa::Instruction::F64Le => self.run_lte::(), + isa::Instruction::F64Ge => self.run_gte::(), + + isa::Instruction::I32Clz => self.run_clz::(), + isa::Instruction::I32Ctz => self.run_ctz::(), + isa::Instruction::I32Popcnt => self.run_popcnt::(), + isa::Instruction::I32Add => self.run_add::(), + isa::Instruction::I32Sub => self.run_sub::(), + isa::Instruction::I32Mul => self.run_mul::(), + isa::Instruction::I32DivS => self.run_div::(), + isa::Instruction::I32DivU => self.run_div::(), + isa::Instruction::I32RemS => self.run_rem::(), + isa::Instruction::I32RemU => self.run_rem::(), + isa::Instruction::I32And => self.run_and::(), + isa::Instruction::I32Or => self.run_or::(), + isa::Instruction::I32Xor => self.run_xor::(), + isa::Instruction::I32Shl => self.run_shl::(0x1F), + isa::Instruction::I32ShrS => self.run_shr::(0x1F), + isa::Instruction::I32ShrU => self.run_shr::(0x1F), + isa::Instruction::I32Rotl => self.run_rotl::(), + isa::Instruction::I32Rotr => self.run_rotr::(), + + isa::Instruction::I64Clz => self.run_clz::(), + isa::Instruction::I64Ctz => self.run_ctz::(), + isa::Instruction::I64Popcnt => self.run_popcnt::(), + isa::Instruction::I64Add => self.run_add::(), + isa::Instruction::I64Sub => self.run_sub::(), + isa::Instruction::I64Mul => self.run_mul::(), + isa::Instruction::I64DivS => self.run_div::(), + isa::Instruction::I64DivU => self.run_div::(), + isa::Instruction::I64RemS => self.run_rem::(), + isa::Instruction::I64RemU => self.run_rem::(), + isa::Instruction::I64And => self.run_and::(), + isa::Instruction::I64Or => self.run_or::(), + isa::Instruction::I64Xor => self.run_xor::(), + isa::Instruction::I64Shl => self.run_shl::(0x3F), + isa::Instruction::I64ShrS => self.run_shr::(0x3F), + isa::Instruction::I64ShrU => self.run_shr::(0x3F), + isa::Instruction::I64Rotl => self.run_rotl::(), + isa::Instruction::I64Rotr => self.run_rotr::(), + + isa::Instruction::F32Abs => self.run_abs::(), + isa::Instruction::F32Neg => self.run_neg::(), + isa::Instruction::F32Ceil => self.run_ceil::(), + isa::Instruction::F32Floor => self.run_floor::(), + isa::Instruction::F32Trunc => self.run_trunc::(), + isa::Instruction::F32Nearest => self.run_nearest::(), + isa::Instruction::F32Sqrt => self.run_sqrt::(), + isa::Instruction::F32Add => self.run_add::(), + isa::Instruction::F32Sub => self.run_sub::(), + isa::Instruction::F32Mul => self.run_mul::(), + isa::Instruction::F32Div => self.run_div::(), + isa::Instruction::F32Min => self.run_min::(), + isa::Instruction::F32Max => self.run_max::(), + isa::Instruction::F32Copysign => self.run_copysign::(), + + isa::Instruction::F64Abs => self.run_abs::(), + isa::Instruction::F64Neg => self.run_neg::(), + isa::Instruction::F64Ceil => self.run_ceil::(), + isa::Instruction::F64Floor => self.run_floor::(), + isa::Instruction::F64Trunc => self.run_trunc::(), + isa::Instruction::F64Nearest => self.run_nearest::(), + isa::Instruction::F64Sqrt => self.run_sqrt::(), + isa::Instruction::F64Add => self.run_add::(), + isa::Instruction::F64Sub => self.run_sub::(), + isa::Instruction::F64Mul => self.run_mul::(), + isa::Instruction::F64Div => self.run_div::(), + isa::Instruction::F64Min => self.run_min::(), + isa::Instruction::F64Max => self.run_max::(), + isa::Instruction::F64Copysign => self.run_copysign::(), + + isa::Instruction::I32WrapI64 => self.run_wrap::(), + isa::Instruction::I32TruncSF32 => self.run_trunc_to_int::(), + isa::Instruction::I32TruncUF32 => self.run_trunc_to_int::(), + isa::Instruction::I32TruncSF64 => self.run_trunc_to_int::(), + isa::Instruction::I32TruncUF64 => self.run_trunc_to_int::(), + isa::Instruction::I64ExtendSI32 => self.run_extend::(), + isa::Instruction::I64ExtendUI32 => self.run_extend::(), + isa::Instruction::I64TruncSF32 => self.run_trunc_to_int::(), + isa::Instruction::I64TruncUF32 => self.run_trunc_to_int::(), + isa::Instruction::I64TruncSF64 => self.run_trunc_to_int::(), + isa::Instruction::I64TruncUF64 => self.run_trunc_to_int::(), + isa::Instruction::F32ConvertSI32 => self.run_extend::(), + isa::Instruction::F32ConvertUI32 => self.run_extend::(), + isa::Instruction::F32ConvertSI64 => self.run_wrap::(), + isa::Instruction::F32ConvertUI64 => self.run_wrap::(), + isa::Instruction::F32DemoteF64 => self.run_wrap::(), + isa::Instruction::F64ConvertSI32 => self.run_extend::(), + isa::Instruction::F64ConvertUI32 => self.run_extend::(), + isa::Instruction::F64ConvertSI64 => self.run_extend::(), + isa::Instruction::F64ConvertUI64 => self.run_extend::(), + isa::Instruction::F64PromoteF32 => self.run_extend::(), + + isa::Instruction::I32ReinterpretF32 => self.run_reinterpret::(), + isa::Instruction::I64ReinterpretF64 => self.run_reinterpret::(), + isa::Instruction::F32ReinterpretI32 => self.run_reinterpret::(), + isa::Instruction::F64ReinterpretI64 => self.run_reinterpret::(), } } @@ -660,7 +659,7 @@ impl Interpreter { let func_ref = table .get(table_func_idx) .map_err(|_| TrapKind::TableAccessOutOfBounds)? - .ok_or_else(|| TrapKind::ElemUninitialized)?; + .ok_or(TrapKind::ElemUninitialized)?; { let actual_function_type = func_ref.signature(); @@ -704,7 +703,7 @@ impl Interpreter { } fn run_tee_local(&mut self, index: u32) -> Result { - let val = self.value_stack.top().clone(); + let val = *self.value_stack.top(); *self.value_stack.pick_mut(index as usize) = val; Ok(InstructionOutcome::RunNextInstruction) } @@ -1270,9 +1269,9 @@ impl FunctionContext { let memory = module.memory_by_index(DEFAULT_MEMORY_INDEX); FunctionContext { is_initialized: false, - function: function, + function, module: ModuleRef(module), - memory: memory, + memory, position: 0, } } @@ -1340,11 +1339,8 @@ pub fn check_function_args(signature: &Signature, args: &[RuntimeValue]) -> Resu if signature .params() .iter() - .zip(args) - .any(|(expected_type, param_value)| { - let actual_type = param_value.value_type(); - &actual_type != expected_type - }) + .zip(args.iter().map(|param_value| param_value.value_type())) + .any(|(expected_type, actual_type)| &actual_type != expected_type) { return Err(TrapKind::UnexpectedSignature.into()); } @@ -1427,10 +1423,7 @@ impl ValueStack { #[inline] fn push(&mut self, value: RuntimeValueInternal) -> Result<(), TrapKind> { - let cell = self - .buf - .get_mut(self.sp) - .ok_or_else(|| TrapKind::StackOverflow)?; + let cell = self.buf.get_mut(self.sp).ok_or(TrapKind::StackOverflow)?; *cell = value; self.sp += 1; Ok(()) @@ -1440,7 +1433,7 @@ impl ValueStack { let cells = self .buf .get_mut(self.sp..self.sp + len) - .ok_or_else(|| TrapKind::StackOverflow)?; + .ok_or(TrapKind::StackOverflow)?; for cell in cells { *cell = Default::default(); } diff --git a/src/table.rs b/src/table.rs index 38a1599743d..2ff97bfe3a5 100644 --- a/src/table.rs +++ b/src/table.rs @@ -72,7 +72,7 @@ impl TableInstance { check_limits(&limits)?; Ok(TableInstance { buffer: RefCell::new(vec![None; limits.initial() as usize]), - limits: limits, + limits, }) } diff --git a/src/tests/host.rs b/src/tests/host.rs index 443a5dde846..0ec54ee08f4 100644 --- a/src/tests/host.rs +++ b/src/tests/host.rs @@ -146,7 +146,7 @@ impl Externals for TestHost { .expect("Function 'recurse' expects attached module instance") .clone(); let result = instance - .invoke_export("recursive", &[val.into()], self) + .invoke_export("recursive", &[val], self) .expect("Failed to call 'recursive'") .expect("expected to be Some"); @@ -163,7 +163,7 @@ impl Externals for TestHost { let result: RuntimeValue = (a - b).into(); self.trap_sub_result = Some(result); - return Err(TrapKind::Host(Box::new(HostErrorWithCode { error_code: 301 })).into()); + Err(TrapKind::Host(Box::new(HostErrorWithCode { error_code: 301 })).into()) } _ => panic!("env doesn't provide function at index {}", index), } @@ -345,13 +345,10 @@ fn resume_call_host_func_type_mismatch() { assert!(invocation.is_resumable()); let err = invocation.resume_execution(val, &mut env).unwrap_err(); - match &err { - ResumableError::Trap(trap) => { - if let TrapKind::UnexpectedSignature = trap.kind() { - return; - } + if let ResumableError::Trap(trap) = &err { + if let TrapKind::UnexpectedSignature = trap.kind() { + return; } - _ => {} } // If didn't return in the previous `match`... @@ -554,7 +551,7 @@ fn defer_providing_externals() { field_name ))); } - if signature.params() != &[ValueType::I32] || signature.return_type() != None { + if signature.params() != [ValueType::I32] || signature.return_type() != None { return Err(Error::Instantiation(format!( "Export `{}` doesnt match expected type {:?}", field_name, signature diff --git a/src/tests/mod.rs b/src/tests/mod.rs index 6c2f7822101..1c97600bf9b 100644 --- a/src/tests/mod.rs +++ b/src/tests/mod.rs @@ -1,5 +1,4 @@ use crate::Module; -use wabt; mod host; mod wasm; diff --git a/src/tests/wasm.rs b/src/tests/wasm.rs index e6812611f24..4eec56dfb3b 100644 --- a/src/tests/wasm.rs +++ b/src/tests/wasm.rs @@ -91,7 +91,7 @@ fn load_from_file(filename: &str) -> Module { #[test] fn interpreter_inc_i32() { // Name of function contained in WASM file (note the leading underline) - const FUNCTION_NAME: &'static str = "_inc_i32"; + const FUNCTION_NAME: &str = "_inc_i32"; // The WASM file containing the module and function const WASM_FILE: &str = &"res/fixtures/inc_i32.wast"; @@ -117,7 +117,7 @@ fn interpreter_inc_i32() { #[test] fn interpreter_accumulate_u8() { // Name of function contained in WASM file (note the leading underline) - const FUNCTION_NAME: &'static str = "_accumulate_u8"; + const FUNCTION_NAME: &str = "_accumulate_u8"; // The WASM file containing the module and function const WASM_FILE: &str = &"res/fixtures/accumulate_u8.wast"; // The octet sequence being accumulated @@ -131,7 +131,7 @@ fn interpreter_accumulate_u8() { .expect("Failed to instantiate module") .assert_no_start(); - let env_memory = env.memory.clone(); + let env_memory = env.memory; // Place the octet-sequence at index 0 in linear memory let offset: u32 = 0; @@ -147,7 +147,7 @@ fn interpreter_accumulate_u8() { .expect("Failed to execute function"); // For verification, repeat accumulation using native code - let accu = BUF.into_iter().fold(0 as i32, |a, b| a + *b as i32); + let accu = BUF.iter().fold(0_i32, |a, b| a + *b as i32); let exp_retval: Option = Some(RuntimeValue::I32(accu)); // Verify calculation from WebAssembly runtime is identical to expected result diff --git a/src/types.rs b/src/types.rs index f0b5c844f15..12a8d5986bc 100644 --- a/src/types.rs +++ b/src/types.rs @@ -43,7 +43,7 @@ impl Signature { ) -> Signature { Signature { params: params.into(), - return_type: return_type, + return_type, } } diff --git a/src/value.rs b/src/value.rs index 43a37ed46a6..e10edb53c4b 100644 --- a/src/value.rs +++ b/src/value.rs @@ -581,7 +581,7 @@ impl LittleEndianConvert for i8 { buffer .get(0) .map(|v| *v as i8) - .ok_or_else(|| Error::InvalidLittleEndianBuffer) + .ok_or(Error::InvalidLittleEndianBuffer) } } @@ -594,7 +594,7 @@ impl LittleEndianConvert for u8 { buffer .get(0) .cloned() - .ok_or_else(|| Error::InvalidLittleEndianBuffer) + .ok_or(Error::InvalidLittleEndianBuffer) } } @@ -611,7 +611,7 @@ impl LittleEndianConvert for i16 { res.copy_from_slice(s); Self::from_le_bytes(res) }) - .ok_or_else(|| Error::InvalidLittleEndianBuffer) + .ok_or(Error::InvalidLittleEndianBuffer) } } @@ -628,7 +628,7 @@ impl LittleEndianConvert for u16 { res.copy_from_slice(s); Self::from_le_bytes(res) }) - .ok_or_else(|| Error::InvalidLittleEndianBuffer) + .ok_or(Error::InvalidLittleEndianBuffer) } } @@ -645,7 +645,7 @@ impl LittleEndianConvert for i32 { res.copy_from_slice(s); Self::from_le_bytes(res) }) - .ok_or_else(|| Error::InvalidLittleEndianBuffer) + .ok_or(Error::InvalidLittleEndianBuffer) } } @@ -662,7 +662,7 @@ impl LittleEndianConvert for u32 { res.copy_from_slice(s); Self::from_le_bytes(res) }) - .ok_or_else(|| Error::InvalidLittleEndianBuffer) + .ok_or(Error::InvalidLittleEndianBuffer) } } @@ -679,7 +679,7 @@ impl LittleEndianConvert for i64 { res.copy_from_slice(s); Self::from_le_bytes(res) }) - .ok_or_else(|| Error::InvalidLittleEndianBuffer) + .ok_or(Error::InvalidLittleEndianBuffer) } } @@ -696,7 +696,7 @@ impl LittleEndianConvert for f32 { res.copy_from_slice(s); Self::from_bits(u32::from_le_bytes(res)) }) - .ok_or_else(|| Error::InvalidLittleEndianBuffer) + .ok_or(Error::InvalidLittleEndianBuffer) } } @@ -713,7 +713,7 @@ impl LittleEndianConvert for f64 { res.copy_from_slice(s); Self::from_bits(u64::from_le_bytes(res)) }) - .ok_or_else(|| Error::InvalidLittleEndianBuffer) + .ok_or(Error::InvalidLittleEndianBuffer) } } @@ -845,6 +845,8 @@ mod fmath { // These wrappers handle that delegation. macro_rules! impl_float { ($type:ident, $fXX:ident, $iXX:ident) => { + // In this particular instance we want to directly compare floating point numbers. + #[allow(clippy::float_cmp)] impl Float<$type> for $type { fn abs(self) -> $type { fmath::$fXX::abs($fXX::from(self)).into() diff --git a/tests/spec/run.rs b/tests/spec/run.rs index 0e4d7784638..d5d72571882 100644 --- a/tests/spec/run.rs +++ b/tests/spec/run.rs @@ -108,7 +108,7 @@ impl ModuleImportResolver for SpecModule { } let func = FuncInstance::alloc_host(func_type.clone(), index); - return Ok(func); + Ok(func) } fn resolve_global( @@ -268,7 +268,7 @@ fn try_load(wasm: &[u8], spec_driver: &mut SpecDriver) -> Result<(), Error> { let instance = ModuleInstance::new(&module, &ImportsBuilder::default())?; instance .run_start(spec_driver.spec_module()) - .map_err(|trap| Error::Start(trap))?; + .map_err(Error::Start)?; Ok(()) } @@ -281,7 +281,7 @@ fn load_module( let instance = ModuleInstance::new(&module, spec_driver) .map_err(|e| Error::Load(e.to_string()))? .run_start(spec_driver.spec_module()) - .map_err(|trap| Error::Start(trap))?; + .map_err(Error::Start)?; let module_name = name.clone(); spec_driver.add_module(module_name, instance.clone()); @@ -301,10 +301,7 @@ fn run_action( } => { let module = program .module_or_last(module.as_ref().map(|x| x.as_ref())) - .expect(&format!( - "Expected program to have loaded module {:?}", - module - )); + .unwrap_or_else(|_| panic!("Expected program to have loaded module {:?}", module)); let vec_args = args .iter() .cloned() @@ -319,10 +316,7 @@ fn run_action( } => { let module = program .module_or_last(module.as_ref().map(|x| x.as_ref())) - .expect(&format!( - "Expected program to have loaded module {:?}", - module - )); + .unwrap_or_else(|_| panic!("Expected program to have loaded module {:?}", module)); let global = module .export_by_name(&field) .ok_or_else(|| { @@ -398,15 +392,15 @@ fn try_spec(name: &str) -> Result<(), Error> { assert_eq!(actual_result.value_type(), spec_expected.value_type()); // f32::NAN != f32::NAN match spec_expected { - &RuntimeValue::F32(val) if val.is_nan() => match actual_result { - &RuntimeValue::F32(val) => assert!(val.is_nan()), + RuntimeValue::F32(val) if val.is_nan() => match actual_result { + RuntimeValue::F32(val) => assert!(val.is_nan()), _ => unreachable!(), // checked above that types are same }, - &RuntimeValue::F64(val) if val.is_nan() => match actual_result { - &RuntimeValue::F64(val) => assert!(val.is_nan()), + RuntimeValue::F64(val) if val.is_nan() => match actual_result { + RuntimeValue::F64(val) => assert!(val.is_nan()), _ => unreachable!(), // checked above that types are same }, - spec_expected @ _ => assert_eq!(actual_result, spec_expected), + spec_expected => assert_eq!(actual_result, spec_expected), } } } @@ -432,7 +426,7 @@ fn try_spec(name: &str) -> Result<(), Error> { panic!("Expected nan value, got {:?}", val) } } - val @ _ => { + val => { panic!("Expected action to return float value, got {:?}", val) } } diff --git a/validation/src/func.rs b/validation/src/func.rs index 851694224f7..7e041fe7591 100644 --- a/validation/src/func.rs +++ b/validation/src/func.rs @@ -147,11 +147,11 @@ impl<'a> FunctionValidationContext<'a> { return_type: BlockType, ) -> Result { let mut ctx = FunctionValidationContext { - module: module, - locals: locals, + module, + locals, value_stack: StackWithLimit::with_limit(value_stack_limit), frame_stack: StackWithLimit::with_limit(frame_stack_limit), - return_type: return_type, + return_type, }; push_label( StartedWith::Block, @@ -247,9 +247,9 @@ impl<'a> FunctionValidationContext<'a> { pop_label(&mut self.value_stack, &mut self.frame_stack)?; - // We just poped the last frame. To avoid some difficulties - // we prefer to keep this branch explicit and bail out here. - () + // We just popped the last frame. To avoid some difficulties + // we prefer to keep this branch explicit, bail out here, thus + // returning `()`. } else { pop_label(&mut self.value_stack, &mut self.frame_stack)?; @@ -1098,7 +1098,7 @@ fn push_value( value_stack: &mut StackWithLimit, value_type: StackValueType, ) -> Result<(), Error> { - Ok(value_stack.push(value_type.into())?) + Ok(value_stack.push(value_type)?) } fn pop_value( @@ -1128,7 +1128,7 @@ fn pop_value( Ok(actual_value) } StackValueType::Any => Ok(actual_value), - stack_value_type @ _ => Err(Error(format!( + stack_value_type => Err(Error(format!( "Expected value of type {:?} on top of stack. Got {:?}", expected_value_ty, stack_value_type ))), @@ -1153,7 +1153,7 @@ fn push_label( ) -> Result<(), Error> { Ok(frame_stack.push(BlockFrame { started_with, - block_type: block_type, + block_type, value_stack_len: value_stack.len(), polymorphic_stack: false, })?) @@ -1212,5 +1212,5 @@ pub fn require_label( } fn require_local(locals: &Locals, idx: u32) -> Result { - Ok(locals.type_of_local(idx)?) + locals.type_of_local(idx) } diff --git a/validation/src/lib.rs b/validation/src/lib.rs index a51a49f03c2..88c18b14dd1 100644 --- a/validation/src/lib.rs +++ b/validation/src/lib.rs @@ -97,12 +97,9 @@ impl Validator for PlainValidator { &mut self, _index: u32, _output: <::FuncValidator as FuncValidator>::Output, - ) -> () { - () - } - fn finish(self) -> () { - () + ) { } + fn finish(self) {} } /// A function validator that just validates modules and produces no result. @@ -123,9 +120,7 @@ impl FuncValidator for PlainFuncValidator { ctx.step(instruction) } - fn finish(self) -> () { - () - } + fn finish(self) {} } pub fn validate_module(module: &Module) -> Result { @@ -139,7 +134,7 @@ pub fn validate_module(module: &Module) -> Result(module: &Module) -> Result context_builder.push_func_type_index(idx), - External::Table(ref table) => context_builder.push_table(table.clone()), - External::Memory(ref memory) => context_builder.push_memory(memory.clone()), + External::Table(ref table) => context_builder.push_table(*table), + External::Memory(ref memory) => context_builder.push_memory(*memory), External::Global(ref global) => { - context_builder.push_global(global.clone()); - imported_globals.push(global.clone()); + context_builder.push_global(*global); + imported_globals.push(*global); } } } @@ -173,19 +168,19 @@ pub fn validate_module(module: &Module) -> Result(module: &Module) -> Result(&context, function, function_body) .map_err(|Error(ref msg)| { @@ -233,7 +228,7 @@ pub fn validate_module(module: &Module) -> Result []".into(), )); diff --git a/validation/src/stack.rs b/validation/src/stack.rs index 60e62dabcd9..7ca295f1238 100644 --- a/validation/src/stack.rs +++ b/validation/src/stack.rs @@ -39,7 +39,7 @@ where pub fn with_limit(limit: usize) -> Self { StackWithLimit { values: Vec::new(), - limit: limit, + limit, } } From c09b745512b3c32a3acb055fe0e63e3704a9dc94 Mon Sep 17 00:00:00 2001 From: Hero Bird Date: Sun, 31 Jan 2021 17:23:03 +0100 Subject: [PATCH 2/3] Add GitHub CI with check, test, fmt and clippy pipelines (#245) * add GitHub CI with check, test, fmt and clippy pipelines * check out git submodule before testing * add no_std checks for cargo check and cargo clippy * use nightly clippy in GH Actions CI * add RUSTFLAGS '--cfg debug_assertions' to test pipeline * add --release to test pipeline --- .github/workflows/rust.yml | 104 +++++++++++++++++++++++++++++++++++++ 1 file changed, 104 insertions(+) create mode 100644 .github/workflows/rust.yml diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml new file mode 100644 index 00000000000..fa50a393249 --- /dev/null +++ b/.github/workflows/rust.yml @@ -0,0 +1,104 @@ +name: Rust - Continuous Integration + +on: + push: + branches: [ master ] + pull_request: + branches: [ master ] + +jobs: + check: + name: Check + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: actions-rs/toolchain@v1 + with: + profile: minimal + toolchain: stable + override: true + - uses: actions-rs/cargo@v1 + with: + command: check + + check_no_std: + name: Check (no_std) + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: actions-rs/toolchain@v1 + with: + profile: minimal + toolchain: stable + override: true + - uses: actions-rs/cargo@v1 + with: + command: build + args: --no-default-features --features core + + test: + name: Test + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: actions-rs/toolchain@v1 + with: + profile: minimal + toolchain: stable + override: true + - name: Checkout Submodules + run: git submodule update --init --recursive + - uses: actions-rs/cargo@v1 + env: + RUSTFLAGS: '--cfg debug_assertions' + with: + command: test + args: --release + + fmt: + name: Formatting + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: actions-rs/toolchain@v1 + with: + profile: minimal + toolchain: stable + override: true + components: rustfmt + - uses: actions-rs/cargo@v1 + with: + command: fmt + args: --all -- --check + + clippy: + name: Clippy + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: actions-rs/toolchain@v1 + with: + profile: minimal + toolchain: nightly + override: true + components: clippy + - uses: actions-rs/cargo@v1 + with: + command: clippy + args: -- -D warnings + + clippy_no_std: + name: Clippy (no_std) + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: actions-rs/toolchain@v1 + with: + profile: minimal + toolchain: nightly + override: true + components: clippy + - uses: actions-rs/cargo@v1 + with: + command: clippy + args: --no-default-features --features core -- -D warnings From 076d77a6bcc1ca2776b66451ab126987f96ddf60 Mon Sep 17 00:00:00 2001 From: Pierre Krieger Date: Mon, 8 Feb 2021 12:00:08 +0100 Subject: [PATCH 3/3] Add MemoryInstance::direct_access and direct_access_mut (#246) * Add MemoryInstance::direct_access and direct_access_mut * Rustfmt --- src/memory/mod.rs | 42 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 41 insertions(+), 1 deletion(-) diff --git a/src/memory/mod.rs b/src/memory/mod.rs index e23bd3474c8..c404ecb048d 100644 --- a/src/memory/mod.rs +++ b/src/memory/mod.rs @@ -3,7 +3,7 @@ use crate::value::LittleEndianConvert; use crate::Error; use alloc::{rc::Rc, string::ToString, vec::Vec}; use core::{ - cell::{Cell, RefCell}, + cell::{Cell, Ref, RefCell, RefMut}, cmp, fmt, ops::Range, u32, @@ -526,6 +526,46 @@ impl MemoryInstance { let mut buf = self.buffer.borrow_mut(); f(buf.as_slice_mut()) } + + /// Provides direct access to the underlying memory buffer. + /// + /// # Panics + /// + /// Any call that requires write access to memory (such as [`set`], [`clear`], etc) made while + /// the returned value is alive will panic. + /// + /// [`set`]: #method.get + /// [`clear`]: #method.set + pub fn direct_access<'a>(&'a self) -> impl AsRef<[u8]> + 'a { + struct Buffer<'a>(Ref<'a, ByteBuf>); + impl<'a> AsRef<[u8]> for Buffer<'a> { + fn as_ref(&self) -> &[u8] { + self.0.as_slice() + } + } + + Buffer(self.buffer.borrow()) + } + + /// Provides direct mutable access to the underlying memory buffer. + /// + /// # Panics + /// + /// Any call that requires either read or write access to memory (such as [`get`], [`set`], + /// [`copy`], etc) made while the returned value is alive will panic. Proceed with caution. + /// + /// [`get`]: #method.get + /// [`set`]: #method.set + pub fn direct_access_mut<'a>(&'a self) -> impl AsMut<[u8]> + 'a { + struct Buffer<'a>(RefMut<'a, ByteBuf>); + impl<'a> AsMut<[u8]> for Buffer<'a> { + fn as_mut(&mut self) -> &mut [u8] { + self.0.as_slice_mut() + } + } + + Buffer(self.buffer.borrow_mut()) + } } #[cfg(test)]