From d4ebf4890a0b13f9796e22564f86743fb2179fe4 Mon Sep 17 00:00:00 2001 From: Wolfgang Silbermayr Date: Tue, 7 Jun 2022 09:12:28 +0200 Subject: [PATCH] Fix clippy lints Fixes: #2926 --- CHANGELOG.md | 2 + Makefile | 8 +- lib/api/src/js/ptr.rs | 8 +- lib/api/src/lib.rs | 4 +- lib/api/src/sys/exports.rs | 12 +- lib/api/src/sys/externals/function.rs | 23 ++- lib/api/src/sys/externals/global.rs | 9 +- lib/api/src/sys/externals/memory.rs | 15 +- lib/api/src/sys/externals/mod.rs | 10 +- lib/api/src/sys/externals/table.rs | 9 +- lib/api/src/sys/instance.rs | 2 +- lib/api/src/sys/mem_access.rs | 14 +- lib/api/src/sys/module.rs | 9 +- lib/api/src/sys/native.rs | 3 +- lib/api/src/sys/ptr.rs | 41 ++-- lib/api/src/sys/store.rs | 2 +- lib/api/src/sys/types.rs | 10 +- lib/artifact/src/artifact.rs | 14 +- lib/artifact/src/lib.rs | 3 +- lib/c-api/build.rs | 4 +- lib/c-api/src/error.rs | 2 +- lib/c-api/src/lib.rs | 3 + lib/c-api/src/wasm_c_api/engine.rs | 3 +- .../src/wasm_c_api/externals/function.rs | 6 +- lib/c-api/src/wasm_c_api/externals/global.rs | 2 +- lib/c-api/src/wasm_c_api/externals/memory.rs | 4 +- lib/c-api/src/wasm_c_api/externals/mod.rs | 12 +- lib/c-api/src/wasm_c_api/types/function.rs | 2 +- lib/c-api/src/wasm_c_api/types/global.rs | 2 +- lib/c-api/src/wasm_c_api/types/memory.rs | 2 +- lib/c-api/src/wasm_c_api/types/table.rs | 2 +- .../unstable/middlewares/metering.rs | 2 +- .../src/wasm_c_api/unstable/target_lexicon.rs | 2 +- lib/c-api/src/wasm_c_api/value.rs | 2 +- lib/c-api/src/wasm_c_api/version.rs | 4 +- lib/c-api/src/wasm_c_api/wat.rs | 4 +- lib/cli/src/c_gen/mod.rs | 4 +- lib/cli/src/commands/binfmt.rs | 7 +- lib/cli/src/commands/run.rs | 20 +- lib/cli/src/commands/run/wasi.rs | 10 +- lib/cli/src/store.rs | 8 +- lib/compiler-cranelift/src/address_map.rs | 2 +- lib/compiler-cranelift/src/compiler.rs | 24 ++- lib/compiler-cranelift/src/dwarf.rs | 2 +- lib/compiler-cranelift/src/func_environ.rs | 44 ++--- .../src/translator/code_translator.rs | 76 ++----- .../src/translator/func_environ.rs | 1 + .../src/translator/unwind.rs | 4 +- lib/compiler-llvm/src/compiler.rs | 4 +- lib/compiler-llvm/src/config.rs | 3 +- lib/compiler-llvm/src/trampoline/wasm.rs | 8 +- lib/compiler-llvm/src/translator/code.rs | 80 ++++---- .../src/translator/intrinsics.rs | 5 +- lib/compiler-llvm/src/translator/state.rs | 2 + lib/compiler-singlepass/src/address_map.rs | 4 +- lib/compiler-singlepass/src/arm64_decl.rs | 10 +- lib/compiler-singlepass/src/codegen.rs | 58 +++--- lib/compiler-singlepass/src/common_decl.rs | 3 +- lib/compiler-singlepass/src/compiler.rs | 22 +-- lib/compiler-singlepass/src/emitter_arm64.rs | 48 ++--- lib/compiler-singlepass/src/emitter_x64.rs | 4 +- lib/compiler-singlepass/src/location.rs | 2 +- lib/compiler-singlepass/src/machine.rs | 94 ++++++++- lib/compiler-singlepass/src/machine_arm64.rs | 186 ++++++++---------- lib/compiler-singlepass/src/machine_x64.rs | 99 +++++----- lib/compiler-singlepass/src/unwind.rs | 2 +- lib/compiler-singlepass/src/unwind_winx64.rs | 7 +- lib/compiler-singlepass/src/x64_decl.rs | 8 +- lib/compiler/src/target.rs | 8 + lib/derive/src/env/mod.rs | 66 +++---- lib/derive/src/value_type.rs | 2 +- lib/emscripten/src/emscripten_target.rs | 18 ++ lib/emscripten/src/lib.rs | 12 +- lib/emscripten/src/syscalls/unix.rs | 12 +- lib/emscripten/src/time.rs | 9 +- lib/emscripten/src/utils.rs | 6 +- lib/emscripten/src/varargs.rs | 5 +- lib/engine-dylib/src/artifact.rs | 28 +-- lib/engine-staticlib/src/artifact.rs | 19 +- lib/engine-staticlib/src/engine.rs | 10 +- lib/engine-universal/src/artifact.rs | 2 +- lib/engine-universal/src/code_memory.rs | 3 +- lib/engine-universal/src/engine.rs | 6 +- lib/engine/src/artifact.rs | 6 +- lib/engine/src/resolver.rs | 2 +- lib/engine/src/trap/error.rs | 14 +- lib/engine/src/trap/frame_info.rs | 4 +- lib/engine/src/tunables.rs | 27 ++- lib/object/src/module.rs | 6 +- lib/types/src/archives.rs | 21 +- lib/types/src/entity/packed_option.rs | 6 +- lib/types/src/native.rs | 2 + lib/types/src/trapcode.rs | 24 +-- lib/types/src/values.rs | 7 + lib/types/src/vmoffsets.rs | 1 + lib/universal-artifact/src/artifact.rs | 2 +- lib/universal-artifact/src/engine.rs | 4 +- lib/universal-artifact/src/lib.rs | 3 +- lib/universal-artifact/src/serialize.rs | 8 +- lib/vm/src/func_data_registry.rs | 14 +- lib/vm/src/instance/mod.rs | 8 +- lib/vm/src/lib.rs | 2 +- lib/vm/src/memory.rs | 6 +- lib/vm/src/sig_registry.rs | 6 +- lib/vm/src/table.rs | 7 +- lib/vm/src/trap/mod.rs | 2 + lib/vm/src/trap/trap.rs | 6 +- lib/vm/src/trap/traphandlers.rs | 22 ++- lib/wasi-experimental-io-devices/src/lib.rs | 8 +- lib/wasi-experimental-io-devices/src/util.rs | 16 +- lib/wasi-types/src/directory.rs | 57 ++++-- lib/wasi/src/state/builder.rs | 9 +- lib/wasi/src/state/mod.rs | 22 +-- lib/wasi/src/state/types.rs | 1 + lib/wasi/src/syscalls/mod.rs | 6 +- tests/lib/engine-dummy/src/artifact.rs | 4 +- tests/lib/engine-dummy/src/engine.rs | 13 +- tests/lib/wast/src/wasi_wast.rs | 9 +- tests/lib/wast/src/wast.rs | 15 +- 119 files changed, 863 insertions(+), 820 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a57779dc6c6..0e78af83e04 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,8 @@ Looking for changes that affect our C API? See the [C API Changelog](lib/c-api/C ## **Unreleased** +### Fixed +- [#2942](https://github.com/wasmerio/wasmer/pull/2942) Fix clippy lints. ## 2.3.0 - 2022/06/06 diff --git a/Makefile b/Makefile index f75a947f1c5..f6589baeb59 100644 --- a/Makefile +++ b/Makefile @@ -745,11 +745,11 @@ install-wasmer-headless-minimal: update-testsuite: git subtree pull --prefix tests/wast/spec https://github.com/WebAssembly/testsuite.git master --squash -lint-packages: RUSTFLAGS += -D dead-code -D nonstandard-style -D unused-imports -D unused-mut -D unused-variables -D unused-unsafe -D unreachable-patterns -D bad-style -D improper-ctypes -D unused-allocation -D unused-comparisons -D while-true -D unconditional-recursion -D bare-trait-objects # TODO: add `-D missing-docs` # TODO: add `-D function_item_references` (not available on Rust 1.47, try when upgrading) +lint-packages: RUSTFLAGS += -D dead-code -D nonstandard-style -D unused-imports -D unused-mut -D unused-variables -D unused-unsafe -D unreachable-patterns -D bad-style -D improper-ctypes -D unused-allocation -D unused-comparisons -D while-true -D unconditional-recursion -D bare-trait-objects -D function_item_references # TODO: add `-D missing-docs` lint-packages: - RUSTFLAGS="${RUSTFLAGS}" cargo clippy --all $(exclude_tests) - RUSTFLAGS="${RUSTFLAGS}" cargo clippy --manifest-path lib/cli/Cargo.toml $(compiler_features) - RUSTFLAGS="${RUSTFLAGS}" cargo clippy --manifest-path fuzz/Cargo.toml $(compiler_features) + RUSTFLAGS="${RUSTFLAGS}" cargo clippy --all -- -D clippy::all + RUSTFLAGS="${RUSTFLAGS}" cargo clippy --manifest-path lib/cli/Cargo.toml $(compiler_features) -- -D clippy::all + RUSTFLAGS="${RUSTFLAGS}" cargo clippy --manifest-path fuzz/Cargo.toml $(compiler_features) -- -D clippy::all lint-formatting: cargo fmt --all -- --check diff --git a/lib/api/src/js/ptr.rs b/lib/api/src/js/ptr.rs index fcf06f4015d..c3a4a177724 100644 --- a/lib/api/src/js/ptr.rs +++ b/lib/api/src/js/ptr.rs @@ -145,8 +145,7 @@ impl WasmPtr { /// /// This method returns an error if an address overflow occurs. #[inline] - #[must_use] - pub fn add(self, offset: M::Offset) -> Result { + pub fn add_offset(self, offset: M::Offset) -> Result { let base = self.offset.into(); let index = offset.into(); let offset = index @@ -164,8 +163,7 @@ impl WasmPtr { /// /// This method returns an error if an address overflow occurs. #[inline] - #[must_use] - pub fn sub(self, offset: M::Offset) -> Result { + pub fn sub_offset(self, offset: M::Offset) -> Result { let base = self.offset.into(); let index = offset.into(); let offset = index @@ -226,7 +224,7 @@ impl WasmPtr { let mut vec = Vec::new(); for i in 0u64.. { let i = M::Offset::try_from(i).map_err(|_| MemoryAccessError::Overflow)?; - let val = self.add(i)?.deref(memory).read()?; + let val = self.add_offset(i)?.deref(memory).read()?; if end(&val) { break; } diff --git a/lib/api/src/lib.rs b/lib/api/src/lib.rs index 0fe8d1fb3e1..2cf1dc6c20a 100644 --- a/lib/api/src/lib.rs +++ b/lib/api/src/lib.rs @@ -6,12 +6,12 @@ missing_docs, trivial_numeric_casts, unused_extern_crates, - broken_intra_doc_links + rustdoc::broken_intra_doc_links )] #![warn(unused_import_braces)] #![cfg_attr( feature = "cargo-clippy", - allow(clippy::new_without_default, vtable_address_comparisons) + allow(clippy::new_without_default, clippy::vtable_address_comparisons) )] #![cfg_attr( feature = "cargo-clippy", diff --git a/lib/api/src/sys/exports.rs b/lib/api/src/sys/exports.rs index eea8a9c9dc2..a89fab5e88f 100644 --- a/lib/api/src/sys/exports.rs +++ b/lib/api/src/sys/exports.rs @@ -170,7 +170,7 @@ impl Exports { T: ExportableWithGenerics<'a, Args, Rets>, { let mut out: T = self.get_with_generics(name)?; - out.into_weak_instance_ref(); + out.convert_to_weak_instance_ref(); Ok(out) } @@ -279,7 +279,7 @@ impl IntoIterator for Exports { type Item = (String, Extern); fn into_iter(self) -> Self::IntoIter { - self.map.clone().into_iter() + self.map.into_iter() } } @@ -311,7 +311,7 @@ pub trait Exportable<'a>: Sized { /// Convert the extern internally to hold a weak reference to the `InstanceRef`. /// This is useful for preventing cycles, for example for data stored in a /// type implementing `WasmerEnv`. - fn into_weak_instance_ref(&mut self); + fn convert_to_weak_instance_ref(&mut self); } /// A trait for accessing exports (like [`Exportable`]) but it takes generic @@ -323,7 +323,7 @@ pub trait ExportableWithGenerics<'a, Args: WasmTypeList, Rets: WasmTypeList>: Si /// Convert the extern internally to hold a weak reference to the `InstanceRef`. /// This is useful for preventing cycles, for example for data stored in a /// type implementing `WasmerEnv`. - fn into_weak_instance_ref(&mut self); + fn convert_to_weak_instance_ref(&mut self); } /// We implement it for all concrete [`Exportable`] types (that are `Clone`) @@ -333,7 +333,7 @@ impl<'a, T: Exportable<'a> + Clone + 'static> ExportableWithGenerics<'a, (), ()> T::get_self_from_extern(_extern).map(|i| i.clone()) } - fn into_weak_instance_ref(&mut self) { - ::into_weak_instance_ref(self); + fn convert_to_weak_instance_ref(&mut self) { + ::convert_to_weak_instance_ref(self); } } diff --git a/lib/api/src/sys/externals/function.rs b/lib/api/src/sys/externals/function.rs index 9a8ebea07eb..2fbb91f456f 100644 --- a/lib/api/src/sys/externals/function.rs +++ b/lib/api/src/sys/externals/function.rs @@ -45,8 +45,7 @@ pub struct Function { impl wasmer_types::WasmValueType for Function { /// Write the value. unsafe fn write_value_to(&self, p: *mut i128) { - let func_ref = - Val::into_vm_funcref(&Val::FuncRef(Some(self.clone())), &self.store).unwrap(); + let func_ref = Val::into_vm_funcref(Val::FuncRef(Some(self.clone())), &self.store).unwrap(); std::ptr::write(p as *mut VMFuncRef, func_ref); } @@ -533,7 +532,7 @@ impl Function { VMFunctionKind::Dynamic => unsafe { type VMContextWithEnv = VMDynamicFunctionContext>; let ctx = self.exported.vm_function.vmctx.host_env as *mut VMContextWithEnv; - Ok((*ctx).ctx.call(¶ms)?.into_boxed_slice()) + Ok((*ctx).ctx.call(params)?.into_boxed_slice()) }, VMFunctionKind::Static => { unimplemented!( @@ -704,12 +703,10 @@ impl<'a> Exportable<'a> for Function { } } - fn into_weak_instance_ref(&mut self) { - self.exported - .vm_function - .instance_ref - .as_mut() - .map(|v| *v = v.downgrade()); + fn convert_to_weak_instance_ref(&mut self) { + if let Some(v) = self.exported.vm_function.instance_ref.as_mut() { + *v = v.downgrade(); + } } } @@ -768,7 +765,7 @@ where Env: Sized + 'static + Send + Sync, { fn call(&self, args: &[Val]) -> Result, RuntimeError> { - (*self.func)(&*self.env, &args) + (*self.func)(&*self.env, args) } fn function_type(&self) -> &FunctionType { &self.function_type @@ -864,6 +861,10 @@ mod inner { /// `FromNativeWasmType` and `ToNativeWasmType` but it creates a /// non-negligible complexity in the `WasmTypeList` /// implementation. + /// + /// # Safety + /// This trait is unsafe given the nature of how values are written and read from the native + /// stack pub unsafe trait FromToNativeWasmType where Self: Sized, @@ -1219,6 +1220,7 @@ mod inner { type Array = [i128; count_idents!( $( $x ),* )]; + #[allow(clippy::unused_unit)] fn from_array(array: Self::Array) -> Self { // Unpack items of the array. #[allow(non_snake_case)] @@ -1254,6 +1256,7 @@ mod inner { [0; count_idents!( $( $x ),* )] } + #[allow(clippy::unused_unit)] fn from_c_struct(c_struct: Self::CStruct) -> Self { // Unpack items of the C structure. #[allow(non_snake_case)] diff --git a/lib/api/src/sys/externals/global.rs b/lib/api/src/sys/externals/global.rs index c5427b64642..70854091f17 100644 --- a/lib/api/src/sys/externals/global.rs +++ b/lib/api/src/sys/externals/global.rs @@ -254,10 +254,9 @@ impl<'a> Exportable<'a> for Global { } } - fn into_weak_instance_ref(&mut self) { - self.vm_global - .instance_ref - .as_mut() - .map(|v| *v = v.downgrade()); + fn convert_to_weak_instance_ref(&mut self) { + if let Some(v) = self.vm_global.instance_ref.as_mut() { + *v = v.downgrade(); + } } } diff --git a/lib/api/src/sys/externals/memory.rs b/lib/api/src/sys/externals/memory.rs index 467ee84178e..c5545a01a62 100644 --- a/lib/api/src/sys/externals/memory.rs +++ b/lib/api/src/sys/externals/memory.rs @@ -215,7 +215,7 @@ impl Memory { .checked_add(buf.len() as u64) .ok_or(MemoryAccessError::Overflow)?; if end > def.current_length.try_into().unwrap() { - Err(MemoryAccessError::HeapOutOfBounds)?; + return Err(MemoryAccessError::HeapOutOfBounds); } unsafe { volatile_memcpy_read(def.base.add(offset as usize), buf.as_mut_ptr(), buf.len()); @@ -245,7 +245,7 @@ impl Memory { .checked_add(buf.len() as u64) .ok_or(MemoryAccessError::Overflow)?; if end > def.current_length.try_into().unwrap() { - Err(MemoryAccessError::HeapOutOfBounds)?; + return Err(MemoryAccessError::HeapOutOfBounds); } let buf_ptr = buf.as_mut_ptr() as *mut u8; unsafe { @@ -269,7 +269,7 @@ impl Memory { .checked_add(data.len() as u64) .ok_or(MemoryAccessError::Overflow)?; if end > def.current_length.try_into().unwrap() { - Err(MemoryAccessError::HeapOutOfBounds)?; + return Err(MemoryAccessError::HeapOutOfBounds); } unsafe { volatile_memcpy_write(data.as_ptr(), def.base.add(offset as usize), data.len()); @@ -302,11 +302,10 @@ impl<'a> Exportable<'a> for Memory { } } - fn into_weak_instance_ref(&mut self) { - self.vm_memory - .instance_ref - .as_mut() - .map(|v| *v = v.downgrade()); + fn convert_to_weak_instance_ref(&mut self) { + if let Some(v) = self.vm_memory.instance_ref.as_mut() { + *v = v.downgrade(); + } } } diff --git a/lib/api/src/sys/externals/mod.rs b/lib/api/src/sys/externals/mod.rs index ce54fda5d31..c0b36487d49 100644 --- a/lib/api/src/sys/externals/mod.rs +++ b/lib/api/src/sys/externals/mod.rs @@ -70,12 +70,12 @@ impl<'a> Exportable<'a> for Extern { Ok(_extern) } - fn into_weak_instance_ref(&mut self) { + fn convert_to_weak_instance_ref(&mut self) { match self { - Self::Function(f) => f.into_weak_instance_ref(), - Self::Global(g) => g.into_weak_instance_ref(), - Self::Memory(m) => m.into_weak_instance_ref(), - Self::Table(t) => t.into_weak_instance_ref(), + Self::Function(f) => f.convert_to_weak_instance_ref(), + Self::Global(g) => g.convert_to_weak_instance_ref(), + Self::Memory(m) => m.convert_to_weak_instance_ref(), + Self::Table(t) => t.convert_to_weak_instance_ref(), } } } diff --git a/lib/api/src/sys/externals/table.rs b/lib/api/src/sys/externals/table.rs index 7fad03f7fd0..a776e009eb5 100644 --- a/lib/api/src/sys/externals/table.rs +++ b/lib/api/src/sys/externals/table.rs @@ -182,10 +182,9 @@ impl<'a> Exportable<'a> for Table { } } - fn into_weak_instance_ref(&mut self) { - self.vm_table - .instance_ref - .as_mut() - .map(|v| *v = v.downgrade()); + fn convert_to_weak_instance_ref(&mut self) { + if let Some(v) = self.vm_table.instance_ref.as_mut() { + *v = v.downgrade(); + } } } diff --git a/lib/api/src/sys/instance.rs b/lib/api/src/sys/instance.rs index df52ede4a07..e2c560a88c3 100644 --- a/lib/api/src/sys/instance.rs +++ b/lib/api/src/sys/instance.rs @@ -168,7 +168,7 @@ impl Instance { /// * Runtime errors that happen when running the module `start` function. pub fn new_by_index(module: &Module, externs: &[Extern]) -> Result { let store = module.store(); - let imports = externs.iter().cloned().collect::>(); + let imports = externs.to_vec(); let handle = module.instantiate(&imports)?; let exports = module .exports() diff --git a/lib/api/src/sys/mem_access.rs b/lib/api/src/sys/mem_access.rs index 98c98d2a2ba..7a6ba392ebd 100644 --- a/lib/api/src/sys/mem_access.rs +++ b/lib/api/src/sys/mem_access.rs @@ -29,12 +29,12 @@ pub enum MemoryAccessError { impl From for RuntimeError { fn from(err: MemoryAccessError) -> Self { - RuntimeError::new(err.to_string()) + Self::new(err.to_string()) } } impl From for MemoryAccessError { fn from(_err: FromUtf8Error) -> Self { - MemoryAccessError::NonUtf8String + Self::NonUtf8String } } @@ -191,6 +191,12 @@ impl<'a, T: ValueType> WasmSlice<'a, T> { self.len } + /// Returns `true` if the number of elements is 0. + #[inline] + pub fn is_empty(self) -> bool { + self.len == 0 + } + /// Get a reference to the Wasm memory backing this reference. #[inline] pub fn memory(self) -> &'a Memory { @@ -343,7 +349,7 @@ impl<'a, T: ValueType> Iterator for WasmSliceIter<'a, T> { type Item = WasmRef<'a, T>; fn next(&mut self) -> Option { - if self.slice.len() != 0 { + if !self.slice.is_empty() { let elem = self.slice.index(0); self.slice = self.slice.subslice(1..self.slice.len()); Some(elem) @@ -359,7 +365,7 @@ impl<'a, T: ValueType> Iterator for WasmSliceIter<'a, T> { impl<'a, T: ValueType> DoubleEndedIterator for WasmSliceIter<'a, T> { fn next_back(&mut self) -> Option { - if self.slice.len() != 0 { + if !self.slice.is_empty() { let elem = self.slice.index(self.slice.len() - 1); self.slice = self.slice.subslice(0..self.slice.len() - 1); Some(elem) diff --git a/lib/api/src/sys/module.rs b/lib/api/src/sys/module.rs index 8f62fd444a2..da5460acf0c 100644 --- a/lib/api/src/sys/module.rs +++ b/lib/api/src/sys/module.rs @@ -345,11 +345,10 @@ impl Module { pub fn set_name(&mut self, name: &str) -> bool { Arc::get_mut(&mut self.artifact) .and_then(|artifact| artifact.module_mut()) - .map(|mut module_info| { + .map_or(false, |mut module_info| { module_info.name = Some(name.to_string()); true }) - .unwrap_or(false) } /// Returns an iterator over the imported types in the Module. @@ -376,7 +375,7 @@ impl Module { /// # Ok(()) /// # } /// ``` - pub fn imports<'a>(&'a self) -> ImportsIterator + 'a> { + pub fn imports(&self) -> ImportsIterator + '_> { self.artifact.module_ref().imports() } @@ -403,7 +402,7 @@ impl Module { /// # Ok(()) /// # } /// ``` - pub fn exports<'a>(&'a self) -> ExportsIterator + 'a> { + pub fn exports(&self) -> ExportsIterator + '_> { self.artifact.module_ref().exports() } @@ -430,7 +429,7 @@ impl Module { /// However, the usage is highly discouraged. #[doc(hidden)] pub fn info(&self) -> &ModuleInfo { - &self.artifact.module_ref() + self.artifact.module_ref() } /// Gets the [`Artifact`] used internally by the Module. diff --git a/lib/api/src/sys/native.rs b/lib/api/src/sys/native.rs index 45b3364e9c3..3f204fc201a 100644 --- a/lib/api/src/sys/native.rs +++ b/lib/api/src/sys/native.rs @@ -132,6 +132,7 @@ macro_rules! impl_native_traits { Rets: WasmTypeList, { /// Call the typed func and return results. + #[allow(clippy::too_many_arguments)] pub fn call(&self, $( $x: $x, )* ) -> Result { if !self.is_host() { // We assume the trampoline is always going to be present for @@ -233,7 +234,7 @@ macro_rules! impl_native_traits { crate::Function::get_self_from_extern(_extern)?.native().map_err(|_| crate::sys::exports::ExportError::IncompatibleType) } - fn into_weak_instance_ref(&mut self) { + fn convert_to_weak_instance_ref(&mut self) { self.exported.vm_function.instance_ref.as_mut().map(|v| *v = v.downgrade()); } } diff --git a/lib/api/src/sys/ptr.rs b/lib/api/src/sys/ptr.rs index 3d50a248401..e52216049c8 100644 --- a/lib/api/src/sys/ptr.rs +++ b/lib/api/src/sys/ptr.rs @@ -7,6 +7,10 @@ use wasmer_types::{NativeWasmType, ValueType}; /// Trait for the `Memory32` and `Memory64` marker types. /// /// This allows code to be generic over 32-bit and 64-bit memories. +/// +/// # Safety +/// +/// Used for raw memory access. pub unsafe trait MemorySize { /// Type used to represent an offset into a memory. This is `u32` or `u64`. type Offset: Copy + Into + TryFrom; @@ -131,7 +135,7 @@ impl WasmPtr { /// Returns a null `UserPtr`. #[inline] pub fn null() -> Self { - WasmPtr::new(M::ZERO) + Self::new(M::ZERO) } /// Checks whether the `WasmPtr` is null. @@ -145,8 +149,7 @@ impl WasmPtr { /// /// This method returns an error if an address overflow occurs. #[inline] - #[must_use] - pub fn add(self, offset: M::Offset) -> Result { + pub fn add_offset(self, offset: M::Offset) -> Result { let base = self.offset.into(); let index = offset.into(); let offset = index @@ -156,16 +159,15 @@ impl WasmPtr { .checked_add(offset) .ok_or(MemoryAccessError::Overflow)?; let address = M::Offset::try_from(address).map_err(|_| MemoryAccessError::Overflow)?; - Ok(WasmPtr::new(address)) + Ok(Self::new(address)) } /// Calculates an offset from the current pointer address. The argument is /// in units of `T`. /// - /// This method returns an error if an address overflow occurs. + /// This method returns an error if an address underflow occurs. #[inline] - #[must_use] - pub fn sub(self, offset: M::Offset) -> Result { + pub fn sub_offset(self, offset: M::Offset) -> Result { let base = self.offset.into(); let index = offset.into(); let offset = index @@ -175,7 +177,7 @@ impl WasmPtr { .checked_sub(offset) .ok_or(MemoryAccessError::Overflow)?; let address = M::Offset::try_from(address).map_err(|_| MemoryAccessError::Overflow)?; - Ok(WasmPtr::new(address)) + Ok(Self::new(address)) } } @@ -183,7 +185,7 @@ impl WasmPtr { /// Creates a `WasmRef` from this `WasmPtr` which allows reading and /// mutating of the value being pointed to. #[inline] - pub fn deref<'a>(self, memory: &'a Memory) -> WasmRef<'a, T> { + pub fn deref(self, memory: &Memory) -> WasmRef<'_, T> { WasmRef::new(memory, self.offset.into()) } @@ -205,11 +207,11 @@ impl WasmPtr { /// Returns a `MemoryAccessError` if the slice length overflows a 64-bit /// address. #[inline] - pub fn slice<'a>( + pub fn slice( self, - memory: &'a Memory, + memory: &Memory, len: M::Offset, - ) -> Result, MemoryAccessError> { + ) -> Result, MemoryAccessError> { WasmSlice::new(memory, self.offset.into(), len.into()) } @@ -218,15 +220,15 @@ impl WasmPtr { /// /// This last value is not included in the returned vector. #[inline] - pub fn read_until<'a>( + pub fn read_until( self, - memory: &'a Memory, + memory: &Memory, mut end: impl FnMut(&T) -> bool, ) -> Result, MemoryAccessError> { let mut vec = Vec::new(); for i in 0u64.. { let i = M::Offset::try_from(i).map_err(|_| MemoryAccessError::Overflow)?; - let val = self.add(i)?.deref(memory).read()?; + let val = self.add_offset(i)?.deref(memory).read()?; if end(&val) { break; } @@ -242,9 +244,9 @@ impl WasmPtr { /// This method is safe to call even if the memory is being concurrently /// modified. #[inline] - pub fn read_utf8_string<'a>( + pub fn read_utf8_string( self, - memory: &'a Memory, + memory: &Memory, len: M::Offset, ) -> Result { let vec = self.slice(memory, len)?.read_to_vec()?; @@ -256,10 +258,7 @@ impl WasmPtr { /// This method is safe to call even if the memory is being concurrently /// modified. #[inline] - pub fn read_utf8_string_with_nul<'a>( - self, - memory: &'a Memory, - ) -> Result { + pub fn read_utf8_string_with_nul(self, memory: &Memory) -> Result { let vec = self.read_until(memory, |&byte| byte == 0)?; Ok(String::from_utf8(vec)?) } diff --git a/lib/api/src/sys/store.rs b/lib/api/src/sys/store.rs index 1a6d0f83306..a90d89d8100 100644 --- a/lib/api/src/sys/store.rs +++ b/lib/api/src/sys/store.rs @@ -80,7 +80,7 @@ impl PartialEq for Store { unsafe impl TrapHandler for Store { fn custom_trap_handler(&self, call: &dyn Fn(&TrapHandlerFn) -> bool) -> bool { - if let Some(handler) = *&self.trap_handler.read().unwrap().as_ref() { + if let Some(handler) = self.trap_handler.read().unwrap().as_ref() { call(handler) } else { false diff --git a/lib/api/src/sys/types.rs b/lib/api/src/sys/types.rs index 1464cf1c564..7ab7bca3ab8 100644 --- a/lib/api/src/sys/types.rs +++ b/lib/api/src/sys/types.rs @@ -37,17 +37,17 @@ impl From for Val { /// It provides useful functions for converting back and forth /// from [`Val`] into `FuncRef`. pub trait ValFuncRef { - fn into_vm_funcref(&self, store: &Store) -> Result; + fn into_vm_funcref(self, store: &Store) -> Result; fn from_vm_funcref(item: VMFuncRef, store: &Store) -> Self; - fn into_table_reference(&self, store: &Store) -> Result; + fn into_table_reference(self, store: &Store) -> Result; fn from_table_reference(item: wasmer_vm::TableElement, store: &Store) -> Self; } impl ValFuncRef for Val { - fn into_vm_funcref(&self, store: &Store) -> Result { + fn into_vm_funcref(self, store: &Store) -> Result { if !self.comes_from_same_store(store) { return Err(RuntimeError::new("cross-`Store` values are not supported")); } @@ -90,13 +90,13 @@ impl ValFuncRef for Val { Self::FuncRef(Some(f)) } - fn into_table_reference(&self, store: &Store) -> Result { + fn into_table_reference(self, store: &Store) -> Result { if !self.comes_from_same_store(store) { return Err(RuntimeError::new("cross-`Store` values are not supported")); } Ok(match self { // TODO(reftypes): review this clone - Self::ExternRef(extern_ref) => wasmer_vm::TableElement::ExternRef(extern_ref.clone()), + Self::ExternRef(extern_ref) => wasmer_vm::TableElement::ExternRef(extern_ref), Self::FuncRef(None) => wasmer_vm::TableElement::FuncRef(VMFuncRef::null()), Self::FuncRef(Some(f)) => wasmer_vm::TableElement::FuncRef(f.vm_funcref()), _ => return Err(RuntimeError::new("val is not reference")), diff --git a/lib/artifact/src/artifact.rs b/lib/artifact/src/artifact.rs index 71429ec5320..043dcce86f8 100644 --- a/lib/artifact/src/artifact.rs +++ b/lib/artifact/src/artifact.rs @@ -120,13 +120,17 @@ impl MetadataHeader { pub const ALIGN: usize = 16; /// Creates a new header for metadata of the given length. - pub fn new(len: usize) -> [u8; 16] { - let header = MetadataHeader { + pub fn new(len: usize) -> Self { + Self { magic: Self::MAGIC, version: Self::CURRENT_VERSION, len: len.try_into().expect("metadata exceeds maximum length"), - }; - unsafe { mem::transmute(header) } + } + } + + /// Convert the header into its bytes representation. + pub fn into_bytes(self) -> [u8; 16] { + unsafe { mem::transmute(self) } } /// Parses the header and returns the length of the metadata following it. @@ -143,7 +147,7 @@ impl MetadataHeader { })? .try_into() .unwrap(); - let header: MetadataHeader = unsafe { mem::transmute(bytes) }; + let header: Self = unsafe { mem::transmute(bytes) }; if header.magic != Self::MAGIC { return Err(DeserializeError::Incompatible( "The provided bytes were not serialized by Wasmer".to_string(), diff --git a/lib/artifact/src/lib.rs b/lib/artifact/src/lib.rs index 3c77a5cd666..14784ee14e5 100644 --- a/lib/artifact/src/lib.rs +++ b/lib/artifact/src/lib.rs @@ -12,8 +12,7 @@ clippy::float_arithmetic, clippy::mut_mut, clippy::nonminimal_bool, - clippy::option_map_unwrap_or, - clippy::option_map_unwrap_or_else, + clippy::map_unwrap_or, clippy::print_stdout, clippy::unicode_not_nfc, clippy::use_self diff --git a/lib/c-api/build.rs b/lib/c-api/build.rs index ed7f7e30d3d..329c360bc98 100644 --- a/lib/c-api/build.rs +++ b/lib/c-api/build.rs @@ -303,11 +303,11 @@ fn build_cdylib_link_arg() { // This is only set up to work on GNU toolchain versions of Rust lines.push(format!( "-Wl,--out-implib,{}", - shared_object_dir.join("wasmer.dll.a".to_string()).display() + shared_object_dir.join("wasmer.dll.a").display() )); lines.push(format!( "-Wl,--output-def,{}", - shared_object_dir.join("wasmer.def".to_string()).display() + shared_object_dir.join("wasmer.def").display() )); } diff --git a/lib/c-api/src/error.rs b/lib/c-api/src/error.rs index cdf3e155ca1..f47caec1b92 100644 --- a/lib/c-api/src/error.rs +++ b/lib/c-api/src/error.rs @@ -131,7 +131,7 @@ pub unsafe extern "C" fn wasmer_last_error_message( }; let error_message = match take_last_error() { - Some(err) => err.to_string(), + Some(err) => err, None => return 0, }; diff --git a/lib/c-api/src/lib.rs b/lib/c-api/src/lib.rs index c81630cb19d..0c0fae224e4 100644 --- a/lib/c-api/src/lib.rs +++ b/lib/c-api/src/lib.rs @@ -23,6 +23,9 @@ unused_unsafe, unreachable_patterns )] +// Because this crate exposes a lot of C APIs which are unsafe by definition, +// we allow unsafe without explicit safety documentation for each of them. +#![allow(clippy::missing_safety_doc)] pub mod error; pub mod wasm_c_api; diff --git a/lib/c-api/src/wasm_c_api/engine.rs b/lib/c-api/src/wasm_c_api/engine.rs index 0ae3beb00c0..9b59eb9c8f5 100644 --- a/lib/c-api/src/wasm_c_api/engine.rs +++ b/lib/c-api/src/wasm_c_api/engine.rs @@ -435,8 +435,7 @@ pub extern "C" fn wasm_engine_new_with_config( #[allow(dead_code)] fn return_with_error(msg: &str) -> Option> { update_last_error(msg); - - return None; + None } let config = config?; diff --git a/lib/c-api/src/wasm_c_api/externals/function.rs b/lib/c-api/src/wasm_c_api/externals/function.rs index da8d851fe38..97576e39676 100644 --- a/lib/c-api/src/wasm_c_api/externals/function.rs +++ b/lib/c-api/src/wasm_c_api/externals/function.rs @@ -56,7 +56,7 @@ pub unsafe extern "C" fn wasm_func_new( let num_rets = func_sig.results().len(); let inner_callback = move |args: &[Val]| -> Result, RuntimeError> { let processed_args: wasm_val_vec_t = args - .into_iter() + .iter() .map(TryInto::try_into) .collect::, _>>() .expect("Argument conversion failed") @@ -134,7 +134,7 @@ pub unsafe extern "C" fn wasm_func_new_with_env( let trampoline = move |env: &WrapperEnv, args: &[Val]| -> Result, RuntimeError> { let processed_args: wasm_val_vec_t = args - .into_iter() + .iter() .map(TryInto::try_into) .collect::, _>>() .expect("Argument conversion failed") @@ -208,7 +208,7 @@ pub unsafe extern "C" fn wasm_func_call( for (slot, val) in results .as_uninit_slice() .iter_mut() - .zip(wasm_results.into_iter()) + .zip(wasm_results.iter()) { *slot = MaybeUninit::new(val.try_into().expect("Results conversion failed")); } diff --git a/lib/c-api/src/wasm_c_api/externals/global.rs b/lib/c-api/src/wasm_c_api/externals/global.rs index 02615cd264c..02dd9ee49de 100644 --- a/lib/c-api/src/wasm_c_api/externals/global.rs +++ b/lib/c-api/src/wasm_c_api/externals/global.rs @@ -85,7 +85,7 @@ pub unsafe extern "C" fn wasm_global_same( #[no_mangle] pub extern "C" fn wasm_global_type(global: &wasm_global_t) -> Box { - Box::new(wasm_globaltype_t::new(global.inner.ty().clone())) + Box::new(wasm_globaltype_t::new(*global.inner.ty())) } #[cfg(test)] diff --git a/lib/c-api/src/wasm_c_api/externals/memory.rs b/lib/c-api/src/wasm_c_api/externals/memory.rs index 65dc9fc4a54..2e82455436f 100644 --- a/lib/c-api/src/wasm_c_api/externals/memory.rs +++ b/lib/c-api/src/wasm_c_api/externals/memory.rs @@ -28,7 +28,7 @@ pub unsafe extern "C" fn wasm_memory_new( let store = store?; let memory_type = memory_type?; - let memory_type = memory_type.inner().memory_type.clone(); + let memory_type = memory_type.inner().memory_type; let memory = c_try!(Memory::new(&store.inner, memory_type)); Some(Box::new(wasm_memory_t::new(memory))) @@ -49,7 +49,7 @@ pub unsafe extern "C" fn wasm_memory_type( ) -> Option> { let memory = memory?; - Some(Box::new(wasm_memorytype_t::new(memory.inner.ty().clone()))) + Some(Box::new(wasm_memorytype_t::new(memory.inner.ty()))) } // get a raw pointer into bytes diff --git a/lib/c-api/src/wasm_c_api/externals/mod.rs b/lib/c-api/src/wasm_c_api/externals/mod.rs index cd2b88368d8..ebad45c9637 100644 --- a/lib/c-api/src/wasm_c_api/externals/mod.rs +++ b/lib/c-api/src/wasm_c_api/externals/mod.rs @@ -82,15 +82,9 @@ impl wasm_extern_t { CApiExternTag::Function => { ExternType::Function(unsafe { self.inner.function.inner.ty().clone() }) } - CApiExternTag::Memory => { - ExternType::Memory(unsafe { self.inner.memory.inner.ty().clone() }) - } - CApiExternTag::Global => { - ExternType::Global(unsafe { self.inner.global.inner.ty().clone() }) - } - CApiExternTag::Table => { - ExternType::Table(unsafe { self.inner.table.inner.ty().clone() }) - } + CApiExternTag::Memory => ExternType::Memory(unsafe { self.inner.memory.inner.ty() }), + CApiExternTag::Global => ExternType::Global(unsafe { *self.inner.global.inner.ty() }), + CApiExternTag::Table => ExternType::Table(unsafe { *self.inner.table.inner.ty() }), } } } diff --git a/lib/c-api/src/wasm_c_api/types/function.rs b/lib/c-api/src/wasm_c_api/types/function.rs index d2aea10e054..a3ff1f6bdd7 100644 --- a/lib/c-api/src/wasm_c_api/types/function.rs +++ b/lib/c-api/src/wasm_c_api/types/function.rs @@ -57,7 +57,7 @@ impl wasm_functype_t { pub(crate) fn inner(&self) -> &WasmFunctionType { match &self.extern_type.inner { - WasmExternType::Function(wasm_function_type) => &wasm_function_type, + WasmExternType::Function(wasm_function_type) => wasm_function_type, _ => { unreachable!("Data corruption: `wasm_functype_t` does not contain a function type") } diff --git a/lib/c-api/src/wasm_c_api/types/global.rs b/lib/c-api/src/wasm_c_api/types/global.rs index 26342e42890..b15d3e820e6 100644 --- a/lib/c-api/src/wasm_c_api/types/global.rs +++ b/lib/c-api/src/wasm_c_api/types/global.rs @@ -38,7 +38,7 @@ impl wasm_globaltype_t { pub(crate) fn inner(&self) -> &WasmGlobalType { match &self.extern_type.inner { - WasmExternType::Global(wasm_global_type) => &wasm_global_type, + WasmExternType::Global(wasm_global_type) => wasm_global_type, _ => { unreachable!("Data corruption: `wasm_globaltype_t` does not contain a global type") } diff --git a/lib/c-api/src/wasm_c_api/types/memory.rs b/lib/c-api/src/wasm_c_api/types/memory.rs index e60eb8459fc..0cbbba7ce96 100644 --- a/lib/c-api/src/wasm_c_api/types/memory.rs +++ b/lib/c-api/src/wasm_c_api/types/memory.rs @@ -40,7 +40,7 @@ impl wasm_memorytype_t { pub(crate) fn inner(&self) -> &WasmMemoryType { match &self.extern_type.inner { - WasmExternType::Memory(wasm_memory_type) => &wasm_memory_type, + WasmExternType::Memory(wasm_memory_type) => wasm_memory_type, _ => { unreachable!("Data corruption: `wasm_memorytype_t` does not contain a memory type") } diff --git a/lib/c-api/src/wasm_c_api/types/table.rs b/lib/c-api/src/wasm_c_api/types/table.rs index a3d74ee79f8..3affb52296d 100644 --- a/lib/c-api/src/wasm_c_api/types/table.rs +++ b/lib/c-api/src/wasm_c_api/types/table.rs @@ -47,7 +47,7 @@ impl wasm_tabletype_t { pub(crate) fn inner(&self) -> &WasmTableType { match &self.extern_type.inner { - WasmExternType::Table(wasm_table_type) => &wasm_table_type, + WasmExternType::Table(wasm_table_type) => wasm_table_type, _ => unreachable!("Data corruption: `wasm_tabletype_t` does not contain a table type"), } } diff --git a/lib/c-api/src/wasm_c_api/unstable/middlewares/metering.rs b/lib/c-api/src/wasm_c_api/unstable/middlewares/metering.rs index 28fad3443b6..cf64aed6aa2 100644 --- a/lib/c-api/src/wasm_c_api/unstable/middlewares/metering.rs +++ b/lib/c-api/src/wasm_c_api/unstable/middlewares/metering.rs @@ -149,7 +149,7 @@ use wasmer_middlewares::{ /// # Example /// /// See module's documentation. -#[allow(non_camel_case_types)] +#[allow(non_camel_case_types, clippy::type_complexity)] pub struct wasmer_metering_t { pub(crate) inner: Arc u64 + Send + Sync>>>, } diff --git a/lib/c-api/src/wasm_c_api/unstable/target_lexicon.rs b/lib/c-api/src/wasm_c_api/unstable/target_lexicon.rs index ed8e9b2a589..541b7a87498 100644 --- a/lib/c-api/src/wasm_c_api/unstable/target_lexicon.rs +++ b/lib/c-api/src/wasm_c_api/unstable/target_lexicon.rs @@ -87,7 +87,7 @@ pub extern "C" fn wasmer_target_new( let cpu_features = cpu_features?; Some(Box::new(wasmer_target_t { - inner: Target::new(triple.inner.clone(), cpu_features.inner.clone()), + inner: Target::new(triple.inner.clone(), cpu_features.inner), })) } diff --git a/lib/c-api/src/wasm_c_api/value.rs b/lib/c-api/src/wasm_c_api/value.rs index 3ead5c0cc40..bb64140aa9a 100644 --- a/lib/c-api/src/wasm_c_api/value.rs +++ b/lib/c-api/src/wasm_c_api/value.rs @@ -116,7 +116,7 @@ impl Clone for wasm_val_t { fn clone(&self) -> Self { wasm_val_t { kind: self.kind, - of: self.of.clone(), + of: self.of, } } } diff --git a/lib/c-api/src/wasm_c_api/version.rs b/lib/c-api/src/wasm_c_api/version.rs index ab7a8c3d6d9..3d2130e8eb6 100644 --- a/lib/c-api/src/wasm_c_api/version.rs +++ b/lib/c-api/src/wasm_c_api/version.rs @@ -1,8 +1,8 @@ use lazy_static::lazy_static; use std::os::raw::c_char; -const VERSION: &'static str = concat!(env!("CARGO_PKG_VERSION"), "\0"); -const VERSION_PRE: &'static str = concat!(env!("CARGO_PKG_VERSION_PRE"), "\0"); +const VERSION: &str = concat!(env!("CARGO_PKG_VERSION"), "\0"); +const VERSION_PRE: &str = concat!(env!("CARGO_PKG_VERSION_PRE"), "\0"); lazy_static! { static ref VERSION_MAJOR: u8 = env!("CARGO_PKG_VERSION_MAJOR") diff --git a/lib/c-api/src/wasm_c_api/wat.rs b/lib/c-api/src/wasm_c_api/wat.rs index 2831f7b6949..fe985409882 100644 --- a/lib/c-api/src/wasm_c_api/wat.rs +++ b/lib/c-api/src/wasm_c_api/wat.rs @@ -8,6 +8,9 @@ use super::types::wasm_byte_vec_t; /// # Example /// /// See the module's documentation. +/// +/// # Safety +/// This function is unsafe in order to be callable from C. #[cfg(feature = "wat")] #[no_mangle] pub unsafe extern "C" fn wat2wasm(wat: &wasm_byte_vec_t, out: &mut wasm_byte_vec_t) { @@ -17,7 +20,6 @@ pub unsafe extern "C" fn wat2wasm(wat: &wasm_byte_vec_t, out: &mut wasm_byte_vec crate::error::update_last_error(err); out.data = std::ptr::null_mut(); out.size = 0; - return; } }; } diff --git a/lib/cli/src/c_gen/mod.rs b/lib/cli/src/c_gen/mod.rs index 49093072719..7f7417a33ba 100644 --- a/lib/cli/src/c_gen/mod.rs +++ b/lib/cli/src/c_gen/mod.rs @@ -124,7 +124,7 @@ impl CType { // function with no, name, assume it's a function pointer let ret: CType = return_value .as_ref() - .map(|i: &Box| (&**i).clone()) + .map(|i| (**i).clone()) .unwrap_or_default(); ret.generate_c(w); w.push(' '); @@ -181,7 +181,7 @@ impl CType { } => { let ret: CType = return_value .as_ref() - .map(|i: &Box| (&**i).clone()) + .map(|i| (**i).clone()) .unwrap_or_default(); ret.generate_c(w); w.push(' '); diff --git a/lib/cli/src/commands/binfmt.rs b/lib/cli/src/commands/binfmt.rs index 9fa7ef22727..dbbfa147f9e 100644 --- a/lib/cli/src/commands/binfmt.rs +++ b/lib/cli/src/commands/binfmt.rs @@ -118,9 +118,8 @@ impl Binfmt { .collect::>() .into_iter() .collect::>>()?; - match (self.action, unregister.into_iter().any(|b| b)) { - (Unregister, false) => bail!("Nothing unregistered"), - _ => (), + if let (Unregister, false) = (self.action, unregister.into_iter().any(|b| b)) { + bail!("Nothing unregistered"); } } _ => (), @@ -139,7 +138,7 @@ impl Binfmt { .open(register) .context("Open binfmt misc for registration")?; register - .write_all(&spec) + .write_all(spec) .context("Couldn't register binfmt")?; Ok(()) }) diff --git a/lib/cli/src/commands/run.rs b/lib/cli/src/commands/run.rs index 6f82382b922..e2f799751bd 100644 --- a/lib/cli/src/commands/run.rs +++ b/lib/cli/src/commands/run.rs @@ -112,7 +112,7 @@ impl Run { .map_err(|e| anyhow!("{}", e))?; let mut em_env = EmEnv::new(&emscripten_globals.data, Default::default()); let import_object = - generate_emscripten_env(module.store(), &mut emscripten_globals, &mut em_env); + generate_emscripten_env(module.store(), &mut emscripten_globals, &em_env); let mut instance = match Instance::new(&module, &import_object) { Ok(instance) => instance, Err(e) => { @@ -200,7 +200,7 @@ impl Run { if let Some(ref invoke) = self.invoke { let imports = imports! {}; let instance = Instance::new(&module, &imports)?; - let result = self.invoke_function(&instance, &invoke, &self.args)?; + let result = self.invoke_function(&instance, invoke, &self.args)?; println!( "{}", result @@ -282,9 +282,9 @@ impl Run { let hash = self .cache_key .as_ref() - .and_then(|key| Hash::from_str(&key).ok()) - .unwrap_or_else(|| Hash::generate(&contents)); - match unsafe { cache.load(&store, hash) } { + .and_then(|key| Hash::from_str(key).ok()) + .unwrap_or_else(|| Hash::generate(contents)); + match unsafe { cache.load(store, hash) } { Ok(module) => Ok(module), Err(e) => { match e { @@ -295,7 +295,7 @@ impl Run { warning!("cached module is corrupted: {}", err); } } - let module = Module::new(&store, &contents)?; + let module = Module::new(store, &contents)?; // Store the compiled Module in cache cache.store(hash, &module)?; Ok(module) @@ -344,7 +344,7 @@ impl Run { ) -> Result { Ok(instance .exports - .get_function(&name) + .get_function(name) .map_err(|e| { if instance.module().info().functions.is_empty() { anyhow!("The module has no exported functions to call.") @@ -362,7 +362,7 @@ impl Run { suggested_functions.get(0).unwrap_or(&String::new()), args.join(" ") ); - let suggestion = if suggested_functions.len() == 0 { + let suggestion = if suggested_functions.is_empty() { String::from("Can not find any export functions.") } else { format!( @@ -391,7 +391,7 @@ impl Run { invoke: &str, args: &[String], ) -> Result> { - let func: Function = self.try_find_function(&instance, invoke, args)?; + let func: Function = self.try_find_function(instance, invoke, args)?; let func_ty = func.ty(); let required_arguments = func_ty.params().len(); let provided_arguments = args.len(); @@ -482,7 +482,7 @@ impl Run { args, path: executable.into(), command_name: Some(original_executable), - store: store, + store, wasi: Wasi::for_binfmt_interpreter()?, ..Self::default() }) diff --git a/lib/cli/src/commands/run/wasi.rs b/lib/cli/src/commands/run/wasi.rs index dca9c9d8943..b7adf3a091f 100644 --- a/lib/cli/src/commands/run/wasi.rs +++ b/lib/cli/src/commands/run/wasi.rs @@ -59,14 +59,14 @@ impl Wasi { pub fn get_versions(module: &Module) -> Option> { // Get the wasi version in strict mode, so no other imports are // allowed. - get_wasi_versions(&module, true) + get_wasi_versions(module, true) } /// Checks if a given module has any WASI imports at all. pub fn has_wasi_imports(module: &Module) -> bool { // Get the wasi version in non-strict mode, so no other imports // are allowed - get_wasi_versions(&module, false).is_some() + get_wasi_versions(module, false).is_some() } /// Helper function for instantiating a module with Wasi imports for the `Run` command. @@ -94,8 +94,8 @@ impl Wasi { } let mut wasi_env = wasi_state_builder.finalize()?; - let import_object = wasi_env.import_object_for_all_wasi_versions(&module)?; - let instance = Instance::new(&module, &import_object)?; + let import_object = wasi_env.import_object_for_all_wasi_versions(module)?; + let instance = Instance::new(module, &import_object)?; Ok(instance) } @@ -121,7 +121,7 @@ impl Wasi { use std::env; let dir = env::var_os("WASMER_BINFMT_MISC_PREOPEN") .map(Into::into) - .unwrap_or(PathBuf::from(".")); + .unwrap_or_else(|| PathBuf::from(".")); Ok(Self { deny_multiple_wasi_versions: true, env_vars: env::vars().collect(), diff --git a/lib/cli/src/store.rs b/lib/cli/src/store.rs index caf7fa40745..a2044c1925c 100644 --- a/lib/cli/src/store.rs +++ b/lib/cli/src/store.rs @@ -242,13 +242,13 @@ impl CompilerOptions { } CompiledKind::FunctionCallTrampoline(func_type) => format!( "trampoline_call_{}_{}", - types_to_signature(&func_type.params()), - types_to_signature(&func_type.results()) + types_to_signature(func_type.params()), + types_to_signature(func_type.results()) ), CompiledKind::DynamicFunctionTrampoline(func_type) => format!( "trampoline_dynamic_{}_{}", - types_to_signature(&func_type.params()), - types_to_signature(&func_type.results()) + types_to_signature(func_type.params()), + types_to_signature(func_type.results()) ), CompiledKind::Module => "module".into(), } diff --git a/lib/compiler-cranelift/src/address_map.rs b/lib/compiler-cranelift/src/address_map.rs index ef261281d21..5296c108215 100644 --- a/lib/compiler-cranelift/src/address_map.rs +++ b/lib/compiler-cranelift/src/address_map.rs @@ -5,7 +5,7 @@ use cranelift_codegen::Context; use cranelift_codegen::MachSrcLoc; use wasmer_compiler::{wasmparser::Range, FunctionAddressMap, InstructionAddressMap, SourceLoc}; -pub fn get_function_address_map<'data>( +pub fn get_function_address_map( context: &Context, range: Range, body_len: usize, diff --git a/lib/compiler-cranelift/src/compiler.rs b/lib/compiler-cranelift/src/compiler.rs index 2c9582c688c..3de0f4b973b 100644 --- a/lib/compiler-cranelift/src/compiler.rs +++ b/lib/compiler-cranelift/src/compiler.rs @@ -223,8 +223,8 @@ impl Compiler for CraneliftCompiler { isa.frontend_config(), module, &signatures, - &memory_styles, - &table_styles, + memory_styles, + table_styles, ); context.func.name = get_function_name(func_index); context.func.signature = signatures[module.functions[func_index]].clone(); @@ -256,20 +256,20 @@ impl Compiler for CraneliftCompiler { let func_relocs = result .buffer .relocs() - .into_iter() + .iter() .map(|r| mach_reloc_to_reloc(module, r)) .collect::>(); let traps = result .buffer .traps() - .into_iter() + .iter() .map(mach_trap_to_trap) .collect::>(); let (unwind_info, fde) = match compiled_function_unwind_info(&*isa, &context)? { #[cfg(feature = "unwind")] - CraneliftUnwindInfo::FDE(fde) => { + CraneliftUnwindInfo::Fde(fde) => { if dwarf_frametable.is_some() { let fde = fde.to_fde(Address::Symbol { // The symbol is the kind of relocation. @@ -315,10 +315,8 @@ impl Compiler for CraneliftCompiler { #[cfg(feature = "unwind")] let dwarf = if let Some((mut dwarf_frametable, cie_id)) = dwarf_frametable { - for fde in fdes { - if let Some(fde) = fde { - dwarf_frametable.add_fde(cie_id, fde); - } + for fde in fdes.into_iter().flatten() { + dwarf_frametable.add_fde(cie_id, fde); } let mut eh_frame = EhFrame(WriterRelocate::new(target.triple().endianness().ok())); dwarf_frametable.write_eh_frame(&mut eh_frame).unwrap(); @@ -351,8 +349,8 @@ impl Compiler for CraneliftCompiler { .values() .collect::>() .par_iter() - .map_init(FunctionBuilderContext::new, |mut cx, sig| { - make_trampoline_function_call(&*isa, &mut cx, sig) + .map_init(FunctionBuilderContext::new, |cx, sig| { + make_trampoline_function_call(&*isa, cx, sig) }) .collect::, CompileError>>()? .into_iter() @@ -377,8 +375,8 @@ impl Compiler for CraneliftCompiler { .imported_function_types() .collect::>() .par_iter() - .map_init(FunctionBuilderContext::new, |mut cx, func_type| { - make_trampoline_dynamic_function(&*isa, &offsets, &mut cx, &func_type) + .map_init(FunctionBuilderContext::new, |cx, func_type| { + make_trampoline_dynamic_function(&*isa, &offsets, cx, func_type) }) .collect::, CompileError>>()? .into_iter() diff --git a/lib/compiler-cranelift/src/dwarf.rs b/lib/compiler-cranelift/src/dwarf.rs index 07e67bbdb00..d079c288587 100644 --- a/lib/compiler-cranelift/src/dwarf.rs +++ b/lib/compiler-cranelift/src/dwarf.rs @@ -20,7 +20,7 @@ impl WriterRelocate { // We autodetect it, based on the host None => RunTimeEndian::default(), }; - WriterRelocate { + Self { relocs: Vec::new(), writer: EndianVec::new(endianness), } diff --git a/lib/compiler-cranelift/src/func_environ.rs b/lib/compiler-cranelift/src/func_environ.rs index 891522cc24f..ed9377f9569 100644 --- a/lib/compiler-cranelift/src/func_environ.rs +++ b/lib/compiler-cranelift/src/func_environ.rs @@ -744,7 +744,7 @@ impl<'module_environment> FuncEnvironment<'module_environment> { ) -> (ir::Value, ir::Value) { // We use an indirect call so that we don't have to patch the code at runtime. let pointer_type = self.pointer_type(); - let vmctx = self.vmctx(&mut pos.func); + let vmctx = self.vmctx(pos.func); let base = pos.ins().global_value(pointer_type, vmctx); let mut mem_flags = ir::MemFlags::trusted(); @@ -834,7 +834,7 @@ impl<'module_environment> BaseFuncEnvironment for FuncEnvironment<'module_enviro delta: ir::Value, init_value: ir::Value, ) -> WasmResult { - let (func_sig, index_arg, func_idx) = self.get_table_grow_func(&mut pos.func, table_index); + let (func_sig, index_arg, func_idx) = self.get_table_grow_func(pos.func, table_index); let table_index = pos.ins().iconst(I32, index_arg as i64); let (vmctx, func_addr) = self.translate_load_builtin_function_address(&mut pos, func_idx); let call_inst = pos.ins().call_indirect( @@ -854,8 +854,7 @@ impl<'module_environment> BaseFuncEnvironment for FuncEnvironment<'module_enviro ) -> WasmResult { let mut pos = builder.cursor(); - let (func_sig, table_index_arg, func_idx) = - self.get_table_get_func(&mut pos.func, table_index); + let (func_sig, table_index_arg, func_idx) = self.get_table_get_func(pos.func, table_index); let table_index = pos.ins().iconst(I32, table_index_arg as i64); let (vmctx, func_addr) = self.translate_load_builtin_function_address(&mut pos, func_idx); let call_inst = pos @@ -874,8 +873,7 @@ impl<'module_environment> BaseFuncEnvironment for FuncEnvironment<'module_enviro ) -> WasmResult<()> { let mut pos = builder.cursor(); - let (func_sig, table_index_arg, func_idx) = - self.get_table_set_func(&mut pos.func, table_index); + let (func_sig, table_index_arg, func_idx) = self.get_table_set_func(pos.func, table_index); let table_index = pos.ins().iconst(I32, table_index_arg as i64); let (vmctx, func_addr) = self.translate_load_builtin_function_address(&mut pos, func_idx); pos.ins() @@ -891,8 +889,7 @@ impl<'module_environment> BaseFuncEnvironment for FuncEnvironment<'module_enviro val: ir::Value, len: ir::Value, ) -> WasmResult<()> { - let (func_sig, table_index_arg, func_idx) = - self.get_table_fill_func(&mut pos.func, table_index); + let (func_sig, table_index_arg, func_idx) = self.get_table_fill_func(pos.func, table_index); let (vmctx, func_addr) = self.translate_load_builtin_function_address(&mut pos, func_idx); let table_index_arg = pos.ins().iconst(I32, table_index_arg as i64); @@ -910,7 +907,7 @@ impl<'module_environment> BaseFuncEnvironment for FuncEnvironment<'module_enviro mut pos: cranelift_codegen::cursor::FuncCursor<'_>, externref: ir::Value, ) -> WasmResult<()> { - let (func_sig, func_idx) = self.get_externref_inc_func(&mut pos.func); + let (func_sig, func_idx) = self.get_externref_inc_func(pos.func); let (_vmctx, func_addr) = self.translate_load_builtin_function_address(&mut pos, func_idx); pos.ins().call_indirect(func_sig, func_addr, &[externref]); @@ -923,7 +920,7 @@ impl<'module_environment> BaseFuncEnvironment for FuncEnvironment<'module_enviro mut pos: cranelift_codegen::cursor::FuncCursor<'_>, externref: ir::Value, ) -> WasmResult<()> { - let (func_sig, func_idx) = self.get_externref_dec_func(&mut pos.func); + let (func_sig, func_idx) = self.get_externref_dec_func(pos.func); let (_vmctx, func_addr) = self.translate_load_builtin_function_address(&mut pos, func_idx); pos.ins().call_indirect(func_sig, func_addr, &[externref]); @@ -979,8 +976,7 @@ impl<'module_environment> BaseFuncEnvironment for FuncEnvironment<'module_enviro // // prototyping with a function call though - let (func_sig, func_index_arg, func_idx) = - self.get_func_ref_func(&mut pos.func, func_index); + let (func_sig, func_index_arg, func_idx) = self.get_func_ref_func(pos.func, func_index); let (vmctx, func_addr) = self.translate_load_builtin_function_address(&mut pos, func_idx); let func_index_arg = pos.ins().iconst(I32, func_index_arg as i64); @@ -1244,7 +1240,7 @@ impl<'module_environment> BaseFuncEnvironment for FuncEnvironment<'module_enviro // so that we don't have to patch the code at runtime. let pointer_type = self.pointer_type(); let sig_ref = pos.func.dfg.ext_funcs[callee].signature; - let vmctx = self.vmctx(&mut pos.func); + let vmctx = self.vmctx(pos.func); let base = pos.ins().global_value(pointer_type, vmctx); let mem_flags = ir::MemFlags::trusted(); @@ -1273,7 +1269,7 @@ impl<'module_environment> BaseFuncEnvironment for FuncEnvironment<'module_enviro _heap: ir::Heap, val: ir::Value, ) -> WasmResult { - let (func_sig, index_arg, func_idx) = self.get_memory_grow_func(&mut pos.func, index); + let (func_sig, index_arg, func_idx) = self.get_memory_grow_func(pos.func, index); let memory_index = pos.ins().iconst(I32, index_arg as i64); let (vmctx, func_addr) = self.translate_load_builtin_function_address(&mut pos, func_idx); let call_inst = pos @@ -1288,7 +1284,7 @@ impl<'module_environment> BaseFuncEnvironment for FuncEnvironment<'module_enviro index: MemoryIndex, _heap: ir::Heap, ) -> WasmResult { - let (func_sig, index_arg, func_idx) = self.get_memory_size_func(&mut pos.func, index); + let (func_sig, index_arg, func_idx) = self.get_memory_size_func(pos.func, index); let memory_index = pos.ins().iconst(I32, index_arg as i64); let (vmctx, func_addr) = self.translate_load_builtin_function_address(&mut pos, func_idx); let call_inst = pos @@ -1308,7 +1304,7 @@ impl<'module_environment> BaseFuncEnvironment for FuncEnvironment<'module_enviro src: ir::Value, len: ir::Value, ) -> WasmResult<()> { - let (func_sig, src_index, func_idx) = self.get_memory_copy_func(&mut pos.func, src_index); + let (func_sig, src_index, func_idx) = self.get_memory_copy_func(pos.func, src_index); let src_index_arg = pos.ins().iconst(I32, src_index as i64); @@ -1329,8 +1325,7 @@ impl<'module_environment> BaseFuncEnvironment for FuncEnvironment<'module_enviro val: ir::Value, len: ir::Value, ) -> WasmResult<()> { - let (func_sig, memory_index, func_idx) = - self.get_memory_fill_func(&mut pos.func, memory_index); + let (func_sig, memory_index, func_idx) = self.get_memory_fill_func(pos.func, memory_index); let memory_index_arg = pos.ins().iconst(I32, memory_index as i64); @@ -1355,7 +1350,7 @@ impl<'module_environment> BaseFuncEnvironment for FuncEnvironment<'module_enviro src: ir::Value, len: ir::Value, ) -> WasmResult<()> { - let (func_sig, func_idx) = self.get_memory_init_func(&mut pos.func); + let (func_sig, func_idx) = self.get_memory_init_func(pos.func); let memory_index_arg = pos.ins().iconst(I32, memory_index.index() as i64); let seg_index_arg = pos.ins().iconst(I32, seg_index as i64); @@ -1372,7 +1367,7 @@ impl<'module_environment> BaseFuncEnvironment for FuncEnvironment<'module_enviro } fn translate_data_drop(&mut self, mut pos: FuncCursor, seg_index: u32) -> WasmResult<()> { - let (func_sig, func_idx) = self.get_data_drop_func(&mut pos.func); + let (func_sig, func_idx) = self.get_data_drop_func(pos.func); let seg_index_arg = pos.ins().iconst(I32, seg_index as i64); let (vmctx, func_addr) = self.translate_load_builtin_function_address(&mut pos, func_idx); pos.ins() @@ -1386,7 +1381,7 @@ impl<'module_environment> BaseFuncEnvironment for FuncEnvironment<'module_enviro table_index: TableIndex, _table: ir::Table, ) -> WasmResult { - let (func_sig, index_arg, func_idx) = self.get_table_size_func(&mut pos.func, table_index); + let (func_sig, index_arg, func_idx) = self.get_table_size_func(pos.func, table_index); let table_index = pos.ins().iconst(I32, index_arg as i64); let (vmctx, func_addr) = self.translate_load_builtin_function_address(&mut pos, func_idx); let call_inst = pos @@ -1407,7 +1402,7 @@ impl<'module_environment> BaseFuncEnvironment for FuncEnvironment<'module_enviro len: ir::Value, ) -> WasmResult<()> { let (func_sig, dst_table_index_arg, src_table_index_arg, func_idx) = - self.get_table_copy_func(&mut pos.func, dst_table_index, src_table_index); + self.get_table_copy_func(pos.func, dst_table_index, src_table_index); let dst_table_index_arg = pos.ins().iconst(I32, dst_table_index_arg as i64); let src_table_index_arg = pos.ins().iconst(I32, src_table_index_arg as i64); @@ -1440,8 +1435,7 @@ impl<'module_environment> BaseFuncEnvironment for FuncEnvironment<'module_enviro src: ir::Value, len: ir::Value, ) -> WasmResult<()> { - let (func_sig, table_index_arg, func_idx) = - self.get_table_init_func(&mut pos.func, table_index); + let (func_sig, table_index_arg, func_idx) = self.get_table_init_func(pos.func, table_index); let table_index_arg = pos.ins().iconst(I32, table_index_arg as i64); let seg_index_arg = pos.ins().iconst(I32, seg_index as i64); @@ -1458,7 +1452,7 @@ impl<'module_environment> BaseFuncEnvironment for FuncEnvironment<'module_enviro } fn translate_elem_drop(&mut self, mut pos: FuncCursor, elem_index: u32) -> WasmResult<()> { - let (func_sig, func_idx) = self.get_elem_drop_func(&mut pos.func); + let (func_sig, func_idx) = self.get_elem_drop_func(pos.func); let elem_index_arg = pos.ins().iconst(I32, elem_index as i64); diff --git a/lib/compiler-cranelift/src/translator/code_translator.rs b/lib/compiler-cranelift/src/translator/code_translator.rs index 58f4e9626d2..490eed9c560 100644 --- a/lib/compiler-cranelift/src/translator/code_translator.rs +++ b/lib/compiler-cranelift/src/translator/code_translator.rs @@ -114,7 +114,7 @@ pub fn translate_operator( environ: &mut FE, ) -> WasmResult<()> { if !state.reachable { - translate_unreachable_operator(module_translation_state, &op, builder, state, environ)?; + translate_unreachable_operator(module_translation_state, op, builder, state, environ)?; return Ok(()); } @@ -128,13 +128,7 @@ pub fn translate_operator( let val = builder.use_var(Variable::with_u32(*local_index)); let local_type = environ.get_local_type(*local_index).unwrap(); let ref_counted = local_type == WasmerType::ExternRef; - state.push1_extra(( - val, - ValueExtraInfo { - ref_counted, - ..Default::default() - }, - )); + state.push1_extra((val, ValueExtraInfo { ref_counted })); let label = ValueLabel::from_u32(*local_index); builder.set_val_label(val, label); @@ -199,13 +193,7 @@ pub fn translate_operator( environ.translate_externref_inc(builder.cursor(), value)?; } - ( - value, - ValueExtraInfo { - ref_counted, - ..Default::default() - }, - ) + (value, ValueExtraInfo { ref_counted }) } GlobalVariable::Custom => ( environ.translate_custom_global_get(builder.cursor(), global_index)?, @@ -268,13 +256,7 @@ pub fn translate_operator( if ref_counted { let selected_ref = builder.ins().select(cond, arg1, arg2); let not_selected_ref = builder.ins().select(cond, arg2, arg1); - state.push1_extra(( - selected_ref, - ValueExtraInfo { - ref_counted, - ..Default::default() - }, - )); + state.push1_extra((selected_ref, ValueExtraInfo { ref_counted })); environ.translate_externref_dec(builder.cursor(), not_selected_ref)?; } else { state.push1_extra(( @@ -638,7 +620,7 @@ pub fn translate_operator( let callee_signature = &builder.func.dfg.signatures[builder.func.dfg.ext_funcs[fref].signature]; let types = wasm_param_types(&callee_signature.params, |i| { - environ.is_wasm_parameter(&callee_signature, i) + environ.is_wasm_parameter(callee_signature, i) }); bitcast_arguments(args, &types, builder); let func_index = FunctionIndex::from_u32(*function_index); @@ -656,10 +638,7 @@ pub fn translate_operator( let mut results_metadata = Vec::with_capacity(func_type.results().len()); for result in func_type.results() { results_metadata.push(if *result == WasmerType::ExternRef { - ValueExtraInfo { - ref_counted: true, - ..Default::default() - } + ValueExtraInfo { ref_counted: true } } else { Default::default() }); @@ -678,7 +657,7 @@ pub fn translate_operator( let callee_signature = &builder.func.dfg.signatures[sigref]; let (args, _) = state.peekn_mut(num_args); let types = wasm_param_types(&callee_signature.params, |i| { - environ.is_wasm_parameter(&callee_signature, i) + environ.is_wasm_parameter(callee_signature, i) }); bitcast_arguments(args, &types, builder); @@ -704,10 +683,7 @@ pub fn translate_operator( let mut results_metadata = Vec::with_capacity(func_type.results().len()); for result in func_type.results() { results_metadata.push(if *result == WasmerType::ExternRef { - ValueExtraInfo { - ref_counted: true, - ..Default::default() - } + ValueExtraInfo { ref_counted: true } } else { Default::default() }); @@ -1576,17 +1552,17 @@ pub fn translate_operator( | Operator::V128Store32Lane { memarg, lane } | Operator::V128Store64Lane { memarg, lane } => { let vector = pop1_with_bitcast(state, type_of(op), builder); - state.push1(builder.ins().extractlane(vector, lane.clone())); + state.push1(builder.ins().extractlane(vector, *lane)); translate_store(memarg, ir::Opcode::Store, builder, state, environ)?; } Operator::I8x16ExtractLaneS { lane } | Operator::I16x8ExtractLaneS { lane } => { let vector = pop1_with_bitcast(state, type_of(op), builder); - let extracted = builder.ins().extractlane(vector, lane.clone()); + let extracted = builder.ins().extractlane(vector, *lane); state.push1(builder.ins().sextend(I32, extracted)) } Operator::I8x16ExtractLaneU { lane } | Operator::I16x8ExtractLaneU { lane } => { let vector = pop1_with_bitcast(state, type_of(op), builder); - let extracted = builder.ins().extractlane(vector, lane.clone()); + let extracted = builder.ins().extractlane(vector, *lane); state.push1(builder.ins().uextend(I32, extracted)); // On x86, PEXTRB zeroes the upper bits of the destination register of extractlane so // uextend could be elided; for now, uextend is needed for Cranelift's type checks to @@ -1597,7 +1573,7 @@ pub fn translate_operator( | Operator::F32x4ExtractLane { lane } | Operator::F64x2ExtractLane { lane } => { let vector = pop1_with_bitcast(state, type_of(op), builder); - state.push1(builder.ins().extractlane(vector, lane.clone())) + state.push1(builder.ins().extractlane(vector, *lane)) } Operator::I8x16ReplaceLane { lane } | Operator::I16x8ReplaceLane { lane } => { let ((vector, _), (replacement, _)) = state.pop2(); @@ -2536,10 +2512,7 @@ fn translate_atomic_rmw( )) } }; - let w_ty_ok = match widened_ty { - I32 | I64 => true, - _ => false, - }; + let w_ty_ok = matches!(widened_ty, I32 | I64); assert!(w_ty_ok && widened_ty.bytes() >= access_ty.bytes()); assert!(arg2_ty.bytes() >= access_ty.bytes()); @@ -2586,10 +2559,7 @@ fn translate_atomic_cas( )) } }; - let w_ty_ok = match widened_ty { - I32 | I64 => true, - _ => false, - }; + let w_ty_ok = matches!(widened_ty, I32 | I64); assert!(w_ty_ok && widened_ty.bytes() >= access_ty.bytes()); assert!(expected_ty.bytes() >= access_ty.bytes()); @@ -2638,10 +2608,7 @@ fn translate_atomic_load( )) } }; - let w_ty_ok = match widened_ty { - I32 | I64 => true, - _ => false, - }; + let w_ty_ok = matches!(widened_ty, I32 | I64); assert!(w_ty_ok && widened_ty.bytes() >= access_ty.bytes()); let final_effective_address = @@ -2681,10 +2648,7 @@ fn translate_atomic_store( )) } }; - let d_ty_ok = match data_ty { - I32 | I64 => true, - _ => false, - }; + let d_ty_ok = matches!(data_ty, I32 | I64); assert!(d_ty_ok && data_ty.bytes() >= access_ty.bytes()); if data_ty.bytes() > access_ty.bytes() { @@ -2993,10 +2957,10 @@ fn optionally_bitcast_vector( #[inline(always)] fn is_non_canonical_v128(ty: ir::Type) -> bool { - match ty { - B8X16 | B16X8 | B32X4 | B64X2 | I64X2 | I32X4 | I16X8 | F32X4 | F64X2 => true, - _ => false, - } + matches!( + ty, + B8X16 | B16X8 | B32X4 | B64X2 | I64X2 | I32X4 | I16X8 | F32X4 | F64X2 + ) } /// Cast to I8X16, any vector values in `values` that are of "non-canonical" type (meaning, not diff --git a/lib/compiler-cranelift/src/translator/func_environ.rs b/lib/compiler-cranelift/src/translator/func_environ.rs index a5f74a094cf..b5f5b176a59 100644 --- a/lib/compiler-cranelift/src/translator/func_environ.rs +++ b/lib/compiler-cranelift/src/translator/func_environ.rs @@ -229,6 +229,7 @@ pub trait FuncEnvironment: TargetEnvironment { /// /// The `index` provided identifies the linear memory to query, and `heap` is the heap reference /// returned by `make_heap` for the same index. + #[allow(clippy::too_many_arguments)] fn translate_memory_copy( &mut self, pos: FuncCursor, diff --git a/lib/compiler-cranelift/src/translator/unwind.rs b/lib/compiler-cranelift/src/translator/unwind.rs index fea3f6ed29e..574a6ff8240 100644 --- a/lib/compiler-cranelift/src/translator/unwind.rs +++ b/lib/compiler-cranelift/src/translator/unwind.rs @@ -14,7 +14,7 @@ pub(crate) enum CraneliftUnwindInfo { WindowsX64(Vec), /// Dwarf FDE #[cfg(feature = "unwind")] - FDE(DwarfFDE), + Fde(DwarfFDE), /// No Unwind info attached None, } @@ -52,7 +52,7 @@ pub(crate) fn compiled_function_unwind_info( unwind.emit(&mut data[..]); Ok(CraneliftUnwindInfo::WindowsX64(data)) } - Some(UnwindInfo::SystemV(unwind)) => Ok(CraneliftUnwindInfo::FDE(unwind)), + Some(UnwindInfo::SystemV(unwind)) => Ok(CraneliftUnwindInfo::Fde(unwind)), Some(_) | None => Ok(CraneliftUnwindInfo::None), } } diff --git a/lib/compiler-llvm/src/compiler.rs b/lib/compiler-llvm/src/compiler.rs index ed5360798d8..6c597b468be 100644 --- a/lib/compiler-llvm/src/compiler.rs +++ b/lib/compiler-llvm/src/compiler.rs @@ -252,7 +252,7 @@ impl Compiler for LLVMCompiler { input, self.config(), memory_styles, - &table_styles, + table_styles, &ShortNames {}, ) }, @@ -353,7 +353,7 @@ impl Compiler for LLVMCompiler { FuncTrampoline::new(target_machine) }, |func_trampoline, func_type| { - func_trampoline.dynamic_trampoline(&func_type, self.config(), "") + func_trampoline.dynamic_trampoline(func_type, self.config(), "") }, ) .collect::, CompileError>>()? diff --git a/lib/compiler-llvm/src/config.rs b/lib/compiler-llvm/src/config.rs index 3b00db5996c..69d2eded123 100644 --- a/lib/compiler-llvm/src/config.rs +++ b/lib/compiler-llvm/src/config.rs @@ -110,6 +110,7 @@ impl LLVM { // // Since both linux and darwin use SysV ABI, this should work. // but not in the case of Aarch64, there the ABI is slightly different + #[allow(clippy::match_single_binding)] match target.triple().architecture { _ => wasmer_compiler::OperatingSystem::Linux, } @@ -174,7 +175,7 @@ impl LLVM { .map(|feature| format!("+{}", feature.to_string())) .join(","); - let target_triple = self.target_triple(&target); + let target_triple = self.target_triple(target); let llvm_target = InkwellTarget::from_triple(&target_triple).unwrap(); llvm_target .create_target_machine( diff --git a/lib/compiler-llvm/src/trampoline/wasm.rs b/lib/compiler-llvm/src/trampoline/wasm.rs index 5d7b202fa99..b1aee66742d 100644 --- a/lib/compiler-llvm/src/trampoline/wasm.rs +++ b/lib/compiler-llvm/src/trampoline/wasm.rs @@ -340,7 +340,7 @@ impl FuncTrampoline { } let callable_func = inkwell::values::CallableValue::try_from(func_ptr).unwrap(); - let call_site = builder.build_call(callable_func, args_vec.as_slice().into(), "call"); + let call_site = builder.build_call(callable_func, args_vec.as_slice(), "call"); for (attr, attr_loc) in func_attrs { call_site.add_attribute(*attr_loc, *attr); } @@ -475,7 +475,7 @@ impl FuncTrampoline { for (idx, value) in results.iter().enumerate() { let value = builder.build_bitcast( *value, - type_to_llvm(&intrinsics, func_sig.results()[idx])?, + type_to_llvm(intrinsics, func_sig.results()[idx])?, "", ); struct_value = builder @@ -487,9 +487,9 @@ impl FuncTrampoline { builder.build_return(None); } else { builder.build_return(Some(&self.abi.pack_values_for_register_return( - &intrinsics, + intrinsics, &builder, - &results.as_slice(), + results.as_slice(), &trampoline_func.get_type(), )?)); } diff --git a/lib/compiler-llvm/src/translator/code.rs b/lib/compiler-llvm/src/translator/code.rs index 1578373f7f0..cb4823af603 100644 --- a/lib/compiler-llvm/src/translator/code.rs +++ b/lib/compiler-llvm/src/translator/code.rs @@ -59,6 +59,7 @@ impl FuncTranslator { } } + #[allow(clippy::too_many_arguments)] pub fn translate_to_module( &self, wasm_module: &ModuleInfo, @@ -92,7 +93,7 @@ impl FuncTranslator { .unwrap(); // TODO: pointer width - let offsets = VMOffsets::new(8, &wasm_module); + let offsets = VMOffsets::new(8, wasm_module); let intrinsics = Intrinsics::declare(&module, &self.ctx, &target_data); let (func_type, func_attrs) = self.abi @@ -269,6 +270,7 @@ impl FuncTranslator { Ok(module) } + #[allow(clippy::too_many_arguments)] pub fn translate( &self, wasm_module: &ModuleInfo, @@ -347,6 +349,7 @@ impl<'ctx, 'a> LLVMFunctionCodeGenerator<'ctx, 'a> { // Convert floating point vector to integer and saturate when out of range. // https://github.com/WebAssembly/nontrapping-float-to-int-conversions/blob/master/proposals/nontrapping-float-to-int-conversion/Overview.md + #[allow(clippy::too_many_arguments)] fn trunc_sat>( &self, fvec_ty: T, @@ -464,6 +467,7 @@ impl<'ctx, 'a> LLVMFunctionCodeGenerator<'ctx, 'a> { // Convert floating point vector to integer and saturate when out of range. // https://github.com/WebAssembly/nontrapping-float-to-int-conversions/blob/master/proposals/nontrapping-float-to-int-conversion/Overview.md + #[allow(clippy::too_many_arguments)] fn trunc_sat_into_int>( &self, fvec_ty: T, @@ -1036,7 +1040,7 @@ impl<'ctx, 'a> LLVMFunctionCodeGenerator<'ctx, 'a> { }; self.mark_memaccess_nodelete(memory_index, memaccess)?; tbaa_label( - &self.module, + self.module, self.intrinsics, format!("memory {}", memory_index.as_u32()), memaccess, @@ -1241,7 +1245,7 @@ impl<'ctx, 'a> LLVMFunctionCodeGenerator<'ctx, 'a> { for (idx, value) in results.enumerate() { let value = self.builder.build_bitcast( value, - type_to_llvm(&self.intrinsics, wasm_fn_type.results()[idx])?, + type_to_llvm(self.intrinsics, wasm_fn_type.results()[idx])?, "", ); struct_value = self @@ -1255,7 +1259,7 @@ impl<'ctx, 'a> LLVMFunctionCodeGenerator<'ctx, 'a> { } else { self.builder .build_return(Some(&self.abi.pack_values_for_register_return( - &self.intrinsics, + self.intrinsics, &self.builder, &results.collect::>(), &func_type, @@ -1786,18 +1790,16 @@ impl<'ctx, 'a> LLVMFunctionCodeGenerator<'ctx, 'a> { if let ControlFrame::IfElse { if_else, next, - if_else_state, + if_else_state: IfElseState::If, else_phis, .. } = &frame { - if let IfElseState::If = if_else_state { - for (phi, else_phi) in frame.phis().iter().zip(else_phis.iter()) { - phi.add_incoming(&[(&else_phi.as_basic_value(), *if_else)]); - } - self.builder.position_at_end(*if_else); - self.builder.build_unconditional_branch(*next); + for (phi, else_phi) in frame.phis().iter().zip(else_phis.iter()) { + phi.add_incoming(&[(&else_phi.as_basic_value(), *if_else)]); } + self.builder.position_at_end(*if_else); + self.builder.build_unconditional_branch(*next); } self.builder.position_at_end(*frame.code_after()); @@ -2020,7 +2022,7 @@ impl<'ctx, 'a> LLVMFunctionCodeGenerator<'ctx, 'a> { let pointer_value = self.locals[local_index as usize]; let v = self.builder.build_load(pointer_value, ""); tbaa_label( - &self.module, + self.module, self.intrinsics, format!("local {}", local_index), v.as_instruction_value().unwrap(), @@ -2033,7 +2035,7 @@ impl<'ctx, 'a> LLVMFunctionCodeGenerator<'ctx, 'a> { let v = self.apply_pending_canonicalization(v, i); let store = self.builder.build_store(pointer_value, v); tbaa_label( - &self.module, + self.module, self.intrinsics, format!("local {}", local_index), store, @@ -2045,7 +2047,7 @@ impl<'ctx, 'a> LLVMFunctionCodeGenerator<'ctx, 'a> { let v = self.apply_pending_canonicalization(v, i); let store = self.builder.build_store(pointer_value, v); tbaa_label( - &self.module, + self.module, self.intrinsics, format!("local {}", local_index), store, @@ -2260,7 +2262,7 @@ impl<'ctx, 'a> LLVMFunctionCodeGenerator<'ctx, 'a> { */ self.abi - .rets_from_call(&self.builder, &self.intrinsics, call_site, func_type) + .rets_from_call(&self.builder, self.intrinsics, call_site, func_type) .iter() .for_each(|ret| self.state.push1(*ret)); } @@ -2461,8 +2463,8 @@ impl<'ctx, 'a> LLVMFunctionCodeGenerator<'ctx, 'a> { self.builder.position_at_end(continue_block); let (llvm_func_type, llvm_func_attrs) = self.abi.func_type_to_llvm( - &self.context, - &self.intrinsics, + self.context, + self.intrinsics, Some(self.ctx.get_offsets()), func_type, )?; @@ -2554,7 +2556,7 @@ impl<'ctx, 'a> LLVMFunctionCodeGenerator<'ctx, 'a> { */ self.abi - .rets_from_call(&self.builder, &self.intrinsics, call_site, func_type) + .rets_from_call(&self.builder, self.intrinsics, call_site, func_type) .iter() .for_each(|ret| self.state.push1(*ret)); } @@ -2615,7 +2617,7 @@ impl<'ctx, 'a> LLVMFunctionCodeGenerator<'ctx, 'a> { ]), "", ); - let left = extend_op(&self, left); + let left = extend_op(self, left); let right = self.builder.build_shuffle_vector( v, v.get_type().get_undef(), @@ -2631,7 +2633,7 @@ impl<'ctx, 'a> LLVMFunctionCodeGenerator<'ctx, 'a> { ]), "", ); - let right = extend_op(&self, right); + let right = extend_op(self, right); let res = self.builder.build_int_add(left, right, ""); let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, ""); @@ -2669,7 +2671,7 @@ impl<'ctx, 'a> LLVMFunctionCodeGenerator<'ctx, 'a> { ]), "", ); - let left = extend_op(&self, left); + let left = extend_op(self, left); let right = self.builder.build_shuffle_vector( v, v.get_type().get_undef(), @@ -2681,7 +2683,7 @@ impl<'ctx, 'a> LLVMFunctionCodeGenerator<'ctx, 'a> { ]), "", ); - let right = extend_op(&self, right); + let right = extend_op(self, right); let res = self.builder.build_int_add(left, right, ""); let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, ""); @@ -2904,10 +2906,8 @@ impl<'ctx, 'a> LLVMFunctionCodeGenerator<'ctx, 'a> { let max_values = self.builder .build_int_s_extend(max_values, self.intrinsics.i32x8_ty, ""); - let saturate_up = - self.builder - .build_int_compare(IntPredicate::SGT, res, max_values, ""); - saturate_up + self.builder + .build_int_compare(IntPredicate::SGT, res, max_values, "") }; let res = self @@ -2966,14 +2966,14 @@ impl<'ctx, 'a> LLVMFunctionCodeGenerator<'ctx, 'a> { VectorType::const_vector(&shuffle_array), "", ); - let val1 = extend_op(&self, val1); + let val1 = extend_op(self, val1); let val2 = self.builder.build_shuffle_vector( v2, v2.get_type().get_undef(), VectorType::const_vector(&shuffle_array), "", ); - let val2 = extend_op(&self, val2); + let val2 = extend_op(self, val2); let res = self.builder.build_int_mul(val1, val2, ""); let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, ""); self.state.push1(res); @@ -3015,14 +3015,14 @@ impl<'ctx, 'a> LLVMFunctionCodeGenerator<'ctx, 'a> { VectorType::const_vector(&shuffle_array), "", ); - let val1 = extend_op(&self, val1); + let val1 = extend_op(self, val1); let val2 = self.builder.build_shuffle_vector( v2, v2.get_type().get_undef(), VectorType::const_vector(&shuffle_array), "", ); - let val2 = extend_op(&self, val2); + let val2 = extend_op(self, val2); let res = self.builder.build_int_mul(val1, val2, ""); let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, ""); self.state.push1(res); @@ -3058,14 +3058,14 @@ impl<'ctx, 'a> LLVMFunctionCodeGenerator<'ctx, 'a> { VectorType::const_vector(&shuffle_array), "", ); - let val1 = extend_op(&self, val1); + let val1 = extend_op(self, val1); let val2 = self.builder.build_shuffle_vector( v2, v2.get_type().get_undef(), VectorType::const_vector(&shuffle_array), "", ); - let val2 = extend_op(&self, val2); + let val2 = extend_op(self, val2); let res = self.builder.build_int_mul(val1, val2, ""); let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, ""); self.state.push1(res); @@ -6777,7 +6777,7 @@ impl<'ctx, 'a> LLVMFunctionCodeGenerator<'ctx, 'a> { VectorType::const_vector(&indices), "", ); - let res = extend(&self, low); + let res = extend(self, low); let res = self.builder.build_bitcast(res, self.intrinsics.i128_ty, ""); self.state.push1(res); } @@ -7459,7 +7459,7 @@ impl<'ctx, 'a> LLVMFunctionCodeGenerator<'ctx, 'a> { ]), "", ); - let res = extend(&self, low); + let res = extend(self, low); let res = self .builder .build_signed_int_to_float(res, self.intrinsics.f64x2_ty, ""); @@ -9233,7 +9233,7 @@ impl<'ctx, 'a> LLVMFunctionCodeGenerator<'ctx, 'a> { ) .unwrap(); tbaa_label( - &self.module, + self.module, self.intrinsics, format!("memory {}", memory_index.as_u32()), old.as_instruction_value().unwrap(), @@ -9268,7 +9268,7 @@ impl<'ctx, 'a> LLVMFunctionCodeGenerator<'ctx, 'a> { ) .unwrap(); tbaa_label( - &self.module, + self.module, self.intrinsics, format!("memory {}", memory_index.as_u32()), old.as_instruction_value().unwrap(), @@ -9300,7 +9300,7 @@ impl<'ctx, 'a> LLVMFunctionCodeGenerator<'ctx, 'a> { ) .unwrap(); tbaa_label( - &self.module, + self.module, self.intrinsics, format!("memory {}", memory_index.as_u32()), old.as_instruction_value().unwrap(), @@ -11056,9 +11056,10 @@ impl<'ctx, 'a> LLVMFunctionCodeGenerator<'ctx, 'a> { Operator::TableGet { table } => { let table_index = self.intrinsics.i32_ty.const_int(table.into(), false); let elem = self.state.pop1()?; - let table_get = if let Some(_) = self + let table_get = if self .wasm_module .local_table_index(TableIndex::from_u32(table)) + .is_some() { self.intrinsics.table_get } else { @@ -11094,9 +11095,10 @@ impl<'ctx, 'a> LLVMFunctionCodeGenerator<'ctx, 'a> { let value = self .builder .build_bitcast(value, self.intrinsics.anyref_ty, ""); - let table_set = if let Some(_) = self + let table_set = if self .wasm_module .local_table_index(TableIndex::from_u32(table)) + .is_some() { self.intrinsics.table_set } else { diff --git a/lib/compiler-llvm/src/translator/intrinsics.rs b/lib/compiler-llvm/src/translator/intrinsics.rs index 916c741c161..741d870ae49 100644 --- a/lib/compiler-llvm/src/translator/intrinsics.rs +++ b/lib/compiler-llvm/src/translator/intrinsics.rs @@ -1126,7 +1126,7 @@ impl<'ctx, 'a> CtxType<'ctx, 'a> { cached_memory_size: HashMap::new(), // TODO: pointer width - offsets: VMOffsets::new(8, &wasm_module), + offsets: VMOffsets::new(8, wasm_module), } } @@ -1435,7 +1435,7 @@ impl<'ctx, 'a> CtxType<'ctx, 'a> { let global_ptr = cache_builder .build_bitcast( global_ptr, - type_to_llvm_ptr(&intrinsics, global_value_type)?, + type_to_llvm_ptr(intrinsics, global_value_type)?, "", ) .into_pointer_value(); @@ -1478,6 +1478,7 @@ impl<'ctx, 'a> CtxType<'ctx, 'a> { } } + #[allow(clippy::too_many_arguments)] pub fn local_func( &mut self, _local_function_index: LocalFunctionIndex, diff --git a/lib/compiler-llvm/src/translator/state.rs b/lib/compiler-llvm/src/translator/state.rs index e3046a09d09..b3300c19691 100644 --- a/lib/compiler-llvm/src/translator/state.rs +++ b/lib/compiler-llvm/src/translator/state.rs @@ -301,6 +301,7 @@ impl<'ctx> State<'ctx> { Ok((v1, v2)) } + #[allow(clippy::type_complexity)] pub fn pop2_extra( &mut self, ) -> Result< @@ -331,6 +332,7 @@ impl<'ctx> State<'ctx> { Ok((v1, v2, v3)) } + #[allow(clippy::type_complexity)] pub fn pop3_extra( &mut self, ) -> Result< diff --git a/lib/compiler-singlepass/src/address_map.rs b/lib/compiler-singlepass/src/address_map.rs index abe18209f93..59ce00fe91c 100644 --- a/lib/compiler-singlepass/src/address_map.rs +++ b/lib/compiler-singlepass/src/address_map.rs @@ -1,8 +1,8 @@ use wasmer_compiler::{FunctionAddressMap, FunctionBodyData, InstructionAddressMap, SourceLoc}; -pub fn get_function_address_map<'data>( +pub fn get_function_address_map( instructions: Vec, - data: &FunctionBodyData<'data>, + data: &FunctionBodyData, body_len: usize, ) -> FunctionAddressMap { // Generate source loc for a function start/end to identify boundary within module. diff --git a/lib/compiler-singlepass/src/arm64_decl.rs b/lib/compiler-singlepass/src/arm64_decl.rs index 92c62bda625..8488d60d4a7 100644 --- a/lib/compiler-singlepass/src/arm64_decl.rs +++ b/lib/compiler-singlepass/src/arm64_decl.rs @@ -90,17 +90,14 @@ impl AbstractReg for GPR { self as usize > 18 } fn is_reserved(self) -> bool { - match self.into_index() { - 0..=16 | 19..=27 => false, - _ => true, - } + !matches!(self.into_index(), 0..=16 | 19..=27) } fn into_index(self) -> usize { self as usize } fn from_index(n: usize) -> Result { match n { - 0..=31 => Ok(GPR::iterator().nth(n).unwrap().clone()), + 0..=31 => Ok(*GPR::iterator().nth(n).unwrap()), _ => Err(()), } } @@ -158,7 +155,7 @@ impl AbstractReg for NEON { } fn from_index(n: usize) -> Result { match n { - 0..=31 => Ok(NEON::iterator().nth(n).unwrap().clone()), + 0..=31 => Ok(*NEON::iterator().nth(n).unwrap()), _ => Err(()), } } @@ -206,6 +203,7 @@ impl AbstractReg for NEON { /// A machine register under the x86-64 architecture. #[derive(Copy, Clone, Debug, Eq, PartialEq)] +#[allow(clippy::upper_case_acronyms)] pub enum ARM64Register { /// General-purpose registers. GPR(GPR), diff --git a/lib/compiler-singlepass/src/codegen.rs b/lib/compiler-singlepass/src/codegen.rs index f01e05fc492..4a5af3b79d3 100644 --- a/lib/compiler-singlepass/src/codegen.rs +++ b/lib/compiler-singlepass/src/codegen.rs @@ -160,7 +160,7 @@ enum CanonicalizeType { } impl CanonicalizeType { - fn to_size(&self) -> Size { + fn to_size(self) -> Size { match self { CanonicalizeType::F32 => Size::S32, CanonicalizeType::F64 => Size::S64, @@ -204,10 +204,7 @@ trait WpTypeExt { impl WpTypeExt for WpType { fn is_float(&self) -> bool { - match self { - WpType::F32 | WpType::F64 => true, - _ => false, - } + matches!(self, WpType::F32 | WpType::F64) } } @@ -605,14 +602,14 @@ impl<'a, M: Machine> FuncGen<'a, M> { // Initialize all normal locals to zero. let mut init_stack_loc_cnt = 0; let mut last_stack_loc = Location::Memory(self.machine.local_pointer(), i32::MAX); - for i in sig.params().len()..n { - match locations[i] { + for location in locations.iter().take(n).skip(sig.params().len()) { + match location { Location::Memory(_, _) => { init_stack_loc_cnt += 1; - last_stack_loc = cmp::min(last_stack_loc, locations[i]); + last_stack_loc = cmp::min(last_stack_loc, *location); } Location::GPR(_) => { - self.machine.zero_location(Size::S64, locations[i]); + self.machine.zero_location(Size::S64, *location); } _ => unreachable!(), } @@ -756,7 +753,7 @@ impl<'a, M: Machine> FuncGen<'a, M> { // Save used SIMD registers. let used_simds = self.machine.get_used_simd(); - if used_simds.len() > 0 { + if !used_simds.is_empty() { used_stack += self.machine.push_used_simd(&used_simds); for r in used_simds.iter().rev() { @@ -803,6 +800,7 @@ impl<'a, M: Machine> FuncGen<'a, M> { } self.machine.adjust_stack(stack_offset as u32); + #[allow(clippy::type_complexity)] let mut call_movs: Vec<(Location, M::GPR)> = vec![]; // Prepare register & stack parameters. for (i, param) in params.iter().enumerate().rev() { @@ -1047,6 +1045,7 @@ impl<'a, M: Machine> FuncGen<'a, M> { Ok(()) } + #[allow(clippy::too_many_arguments)] pub fn new( module: &'a ModuleInfo, config: &'a Singlepass, @@ -1067,7 +1066,7 @@ impl<'a, M: Machine> FuncGen<'a, M> { .iter() .map(|&x| type_to_wp_type(x)) .collect(); - local_types.extend_from_slice(&local_types_excluding_arguments); + local_types.extend_from_slice(local_types_excluding_arguments); let mut machine = machine; let special_labels = SpecialLabelSet { @@ -1104,7 +1103,7 @@ impl<'a, M: Machine> FuncGen<'a, M> { save_area_offset: None, state: machine.new_machine_state(), track_state: true, - machine: machine, + machine, unreachable_depth: 0, fsm, relocations: vec![], @@ -2920,8 +2919,8 @@ impl<'a, M: Machine> FuncGen<'a, M> { } let frame = &self.control_stack.last_mut().unwrap(); - let stack_depth = frame.value_stack_depth.clone(); - let fp_depth = frame.fp_stack_depth.clone(); + let stack_depth = frame.value_stack_depth; + let fp_depth = frame.fp_stack_depth; self.release_locations_value(stack_depth); self.value_stack.truncate(stack_depth); self.fp_stack.truncate(fp_depth); @@ -3461,7 +3460,7 @@ impl<'a, M: Machine> FuncGen<'a, M> { target_value, memarg, target_addr, - config_nan_canonicalization && !fp.canonicalization.is_none(), + config_nan_canonicalization && fp.canonicalization.is_some(), need_check, imported_memories, offset, @@ -3703,7 +3702,7 @@ impl<'a, M: Machine> FuncGen<'a, M> { target_value, memarg, target_addr, - config_nan_canonicalization && !fp.canonicalization.is_none(), + config_nan_canonicalization && fp.canonicalization.is_some(), need_check, imported_memories, offset, @@ -3791,7 +3790,7 @@ impl<'a, M: Machine> FuncGen<'a, M> { .emit_function_return_value(first_return, canonicalize, loc); } let frame = &self.control_stack[0]; - let frame_depth = frame.value_stack_depth.clone(); + let frame_depth = frame.value_stack_depth; let label = frame.label; self.release_locations_keep_state(frame_depth); self.machine.jmp_unconditionnal(label); @@ -3821,7 +3820,7 @@ impl<'a, M: Machine> FuncGen<'a, M> { } let stack_len = self.control_stack.len(); let frame = &mut self.control_stack[stack_len - 1 - (relative_depth as usize)]; - let frame_depth = frame.value_stack_depth.clone(); + let frame_depth = frame.value_stack_depth; let label = frame.label; self.release_locations_keep_state(frame_depth); @@ -3859,8 +3858,8 @@ impl<'a, M: Machine> FuncGen<'a, M> { } let stack_len = self.control_stack.len(); let frame = &mut self.control_stack[stack_len - 1 - (relative_depth as usize)]; - let stack_depth = frame.value_stack_depth.clone(); - let label = frame.label.clone(); + let stack_depth = frame.value_stack_depth; + let label = frame.label; self.release_locations_keep_state(stack_depth); self.machine.jmp_unconditionnal(label); @@ -3916,9 +3915,9 @@ impl<'a, M: Machine> FuncGen<'a, M> { self.machine .emit_function_return_value(first_return, canonicalize, loc); } - let frame = &self.control_stack - [self.control_stack.len().clone() - 1 - (*target as usize)]; - let stack_depth = frame.value_stack_depth.clone(); + let frame = + &self.control_stack[self.control_stack.len() - 1 - (*target as usize)]; + let stack_depth = frame.value_stack_depth; let label = frame.label; self.release_locations_keep_state(stack_depth); self.machine.jmp_unconditionnal(label); @@ -3950,7 +3949,7 @@ impl<'a, M: Machine> FuncGen<'a, M> { } let frame = &self.control_stack [self.control_stack.len() - 1 - (default_target as usize)]; - let stack_depth = frame.value_stack_depth.clone(); + let stack_depth = frame.value_stack_depth; let label = frame.label; self.release_locations_keep_state(stack_depth); self.machine.jmp_unconditionnal(label); @@ -5915,21 +5914,16 @@ impl<'a, M: Machine> FuncGen<'a, M> { ( CompiledFunction { - body: FunctionBody { - body: body, - unwind_info, - }, + body: FunctionBody { body, unwind_info }, relocations: self.relocations.clone(), - frame_info: CompiledFunctionFrameInfo { - traps: traps, - address_map, - }, + frame_info: CompiledFunctionFrameInfo { traps, address_map }, }, fde, ) } // FIXME: This implementation seems to be not enough to resolve all kinds of register dependencies // at call place. + #[allow(clippy::type_complexity)] fn sort_call_movs(movs: &mut [(Location, M::GPR)]) { for i in 0..movs.len() { for j in (i + 1)..movs.len() { diff --git a/lib/compiler-singlepass/src/common_decl.rs b/lib/compiler-singlepass/src/common_decl.rs index c317c5b5e20..9d48cf69336 100644 --- a/lib/compiler-singlepass/src/common_decl.rs +++ b/lib/compiler-singlepass/src/common_decl.rs @@ -224,8 +224,7 @@ impl MachineState { impl MachineStateDiff { /// Creates a `MachineState` from the given `&FunctionStateMap`. pub fn _build_state(&self, m: &FunctionStateMap) -> MachineState { - let mut chain: Vec<&MachineStateDiff> = vec![]; - chain.push(self); + let mut chain: Vec<&MachineStateDiff> = vec![self]; let mut current = self.last; while let Some(x) = current { let that = &m.diffs[x]; diff --git a/lib/compiler-singlepass/src/compiler.rs b/lib/compiler-singlepass/src/compiler.rs index 29a29c9155b..b86c30fde0a 100644 --- a/lib/compiler-singlepass/src/compiler.rs +++ b/lib/compiler-singlepass/src/compiler.rs @@ -172,8 +172,8 @@ impl Compiler for SinglepassCompiler { module, &self.config, &vmoffsets, - &memory_styles, - &table_styles, + memory_styles, + table_styles, i, &locals, machine, @@ -186,7 +186,7 @@ impl Compiler for SinglepassCompiler { generator.feed_operator(op).map_err(to_compile_error)?; } - Ok(generator.finalize(&input)) + Ok(generator.finalize(input)) } Architecture::Aarch64(_) => { let machine = MachineARM64::new(); @@ -194,8 +194,8 @@ impl Compiler for SinglepassCompiler { module, &self.config, &vmoffsets, - &memory_styles, - &table_styles, + memory_styles, + table_styles, i, &locals, machine, @@ -208,7 +208,7 @@ impl Compiler for SinglepassCompiler { generator.feed_operator(op).map_err(to_compile_error)?; } - Ok(generator.finalize(&input)) + Ok(generator.finalize(input)) } _ => unimplemented!(), } @@ -222,7 +222,7 @@ impl Compiler for SinglepassCompiler { .values() .collect::>() .into_par_iter_if_rayon() - .map(|func_type| gen_std_trampoline(&func_type, target, calling_convention)) + .map(|func_type| gen_std_trampoline(func_type, target, calling_convention)) .collect::>() .into_iter() .collect::>(); @@ -245,11 +245,9 @@ impl Compiler for SinglepassCompiler { #[cfg(feature = "unwind")] let dwarf = if let Some((mut dwarf_frametable, cie_id)) = dwarf_frametable { - for fde in fdes { - if let Some(fde) = fde { - match fde { - UnwindFrame::SystemV(fde) => dwarf_frametable.add_fde(cie_id, fde), - } + for fde in fdes.into_iter().flatten() { + match fde { + UnwindFrame::SystemV(fde) => dwarf_frametable.add_fde(cie_id, fde), } } let mut eh_frame = EhFrame(WriterRelocate::new(target.triple().endianness().ok())); diff --git a/lib/compiler-singlepass/src/emitter_arm64.rs b/lib/compiler-singlepass/src/emitter_arm64.rs index abc797fac27..c2a306dc5a2 100644 --- a/lib/compiler-singlepass/src/emitter_arm64.rs +++ b/lib/compiler-singlepass/src/emitter_arm64.rs @@ -70,14 +70,14 @@ pub enum Condition { } #[derive(Copy, Clone, Debug, Eq, PartialEq)] -#[allow(dead_code)] +#[allow(dead_code, clippy::upper_case_acronyms)] pub enum NeonOrMemory { NEON(NEON), Memory(GPR, i32), } #[derive(Copy, Clone, Debug)] -#[allow(dead_code)] +#[allow(dead_code, clippy::upper_case_acronyms)] pub enum GPROrMemory { GPR(GPR), Memory(GPR, i32), @@ -1165,14 +1165,14 @@ impl EmitterARM64 for Assembler { } (Size::S64, Location::Imm32(imm), Location::GPR(dst)) => { let dst = dst.into_index() as u32; - if !encode_logical_immediate_64bit(imm as u64).is_some() { + if encode_logical_immediate_64bit(imm as u64).is_none() { unreachable!(); } dynasm!(self ; tst X(dst), imm as u64); } (Size::S64, Location::Imm64(imm), Location::GPR(dst)) => { let dst = dst.into_index() as u32; - if !encode_logical_immediate_64bit(imm as u64).is_some() { + if encode_logical_immediate_64bit(imm as u64).is_none() { unreachable!(); } dynasm!(self ; tst X(dst), imm as u64); @@ -1184,7 +1184,7 @@ impl EmitterARM64 for Assembler { } (Size::S32, Location::Imm32(imm), Location::GPR(dst)) => { let dst = dst.into_index() as u32; - if !encode_logical_immediate_64bit(imm as u64).is_some() { + if encode_logical_immediate_64bit(imm as u64).is_none() { unreachable!(); } dynasm!(self ; tst W(dst), imm); @@ -1458,7 +1458,7 @@ impl EmitterARM64 for Assembler { let src1 = src1.into_index() as u32; let src2 = src2 as u64; let dst = dst.into_index() as u32; - if !encode_logical_immediate_64bit(src2 as u64).is_some() { + if encode_logical_immediate_64bit(src2 as u64).is_none() { unreachable!(); } dynasm!(self ; orr X(dst), X(src1), src2); @@ -1467,7 +1467,7 @@ impl EmitterARM64 for Assembler { let src1 = src1.into_index() as u32; let src2 = src2 as u32; let dst = dst.into_index() as u32; - if !encode_logical_immediate_32bit(src2).is_some() { + if encode_logical_immediate_32bit(src2).is_none() { unreachable!(); } dynasm!(self ; orr W(dst), W(src1), src2); @@ -1496,7 +1496,7 @@ impl EmitterARM64 for Assembler { let src1 = src1.into_index() as u32; let src2 = src2 as u64; let dst = dst.into_index() as u32; - if !encode_logical_immediate_64bit(src2 as u64).is_some() { + if encode_logical_immediate_64bit(src2 as u64).is_none() { unreachable!(); } dynasm!(self ; and X(dst), X(src1), src2); @@ -1505,7 +1505,7 @@ impl EmitterARM64 for Assembler { let src1 = src1.into_index() as u32; let src2 = src2 as u32; let dst = dst.into_index() as u32; - if !encode_logical_immediate_32bit(src2).is_some() { + if encode_logical_immediate_32bit(src2).is_none() { unreachable!(); } dynasm!(self ; and W(dst), W(src1), src2); @@ -1534,7 +1534,7 @@ impl EmitterARM64 for Assembler { let src1 = src1.into_index() as u32; let src2 = src2 as u64; let dst = dst.into_index() as u32; - if !encode_logical_immediate_64bit(src2 as u64).is_some() { + if encode_logical_immediate_64bit(src2 as u64).is_none() { unreachable!(); } dynasm!(self ; eor X(dst), X(src1), src2); @@ -1543,7 +1543,7 @@ impl EmitterARM64 for Assembler { let src1 = src1.into_index() as u32; let src2 = src2 as u32; let dst = dst.into_index() as u32; - if !encode_logical_immediate_32bit(src2).is_some() { + if encode_logical_immediate_32bit(src2).is_none() { unreachable!(); } dynasm!(self ; eor W(dst), W(src1), src2); @@ -2453,6 +2453,7 @@ pub fn gen_std_trampoline_arm64( ); } _ => { + #[allow(clippy::single_match)] match calling_convention { CallingConvention::AppleAarch64 => { match sz { @@ -2613,6 +2614,7 @@ pub fn gen_std_dynamic_import_trampoline_arm64( } } + #[allow(clippy::match_single_binding)] match calling_convention { _ => { // Load target address. @@ -2694,6 +2696,7 @@ pub fn gen_import_call_trampoline_arm64( .iter() .any(|&x| x == Type::F32 || x == Type::F64) { + #[allow(clippy::match_single_binding)] match calling_convention { _ => { let mut param_locations: Vec = vec![]; @@ -2729,20 +2732,20 @@ pub fn gen_import_call_trampoline_arm64( } // Store all arguments to the stack to prevent overwrite. - for i in 0..sig.params().len() { + static PARAM_REGS: &[GPR] = &[ + GPR::X1, + GPR::X2, + GPR::X3, + GPR::X4, + GPR::X5, + GPR::X6, + GPR::X7, + ]; + for (i, r) in PARAM_REGS.iter().enumerate().take(sig.params().len()) { let loc = match i { 0..=6 => { - static PARAM_REGS: &[GPR] = &[ - GPR::X1, - GPR::X2, - GPR::X3, - GPR::X4, - GPR::X5, - GPR::X6, - GPR::X7, - ]; let loc = Location::Memory(GPR::XzrSp, (i * 8) as i32); - a.emit_str(Size::S64, Location::GPR(PARAM_REGS[i]), loc); + a.emit_str(Size::S64, Location::GPR(*r), loc); loc } _ => Location::Memory(GPR::XzrSp, stack_offset + ((i - 7) * 8) as i32), @@ -2816,6 +2819,7 @@ pub fn gen_import_call_trampoline_arm64( ); 0 }; + #[allow(clippy::match_single_binding)] match calling_convention { _ => { if (offset & 7) == 0 { diff --git a/lib/compiler-singlepass/src/emitter_x64.rs b/lib/compiler-singlepass/src/emitter_x64.rs index a3e3aaa588b..3ce8b7e160b 100644 --- a/lib/compiler-singlepass/src/emitter_x64.rs +++ b/lib/compiler-singlepass/src/emitter_x64.rs @@ -42,14 +42,14 @@ pub enum Condition { } #[derive(Copy, Clone, Debug, Eq, PartialEq)] -#[allow(dead_code)] +#[allow(dead_code, clippy::upper_case_acronyms)] pub enum XMMOrMemory { XMM(XMM), Memory(GPR, i32), } #[derive(Copy, Clone, Debug)] -#[allow(dead_code)] +#[allow(dead_code, clippy::upper_case_acronyms)] pub enum GPROrMemory { GPR(GPR), Memory(GPR, i32), diff --git a/lib/compiler-singlepass/src/location.rs b/lib/compiler-singlepass/src/location.rs index 4992fbf03af..ba8addfd6b4 100644 --- a/lib/compiler-singlepass/src/location.rs +++ b/lib/compiler-singlepass/src/location.rs @@ -14,7 +14,7 @@ pub enum Multiplier { Height = 8, } -#[allow(dead_code)] +#[allow(dead_code, clippy::upper_case_acronyms)] #[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)] pub enum Location { GPR(R), diff --git a/lib/compiler-singlepass/src/machine.rs b/lib/compiler-singlepass/src/machine.rs index 69ede6316c6..d71d98480b3 100644 --- a/lib/compiler-singlepass/src/machine.rs +++ b/lib/compiler-singlepass/src/machine.rs @@ -83,9 +83,9 @@ pub trait Machine { /// reserve a GPR fn reserve_gpr(&mut self, gpr: Self::GPR); /// Push used gpr to the stack. Return the bytes taken on the stack - fn push_used_gpr(&mut self, grps: &Vec) -> usize; + fn push_used_gpr(&mut self, grps: &[Self::GPR]) -> usize; /// Pop used gpr to the stack - fn pop_used_gpr(&mut self, grps: &Vec); + fn pop_used_gpr(&mut self, grps: &[Self::GPR]); /// Picks an unused SIMD register. /// /// This method does not mark the register as used @@ -101,9 +101,9 @@ pub trait Machine { /// Releases a temporary XMM register. fn release_simd(&mut self, simd: Self::SIMD); /// Push used simd regs to the stack. Return bytes taken on the stack - fn push_used_simd(&mut self, simds: &Vec) -> usize; + fn push_used_simd(&mut self, simds: &[Self::SIMD]) -> usize; /// Pop used simd regs to the stack - fn pop_used_simd(&mut self, simds: &Vec); + fn pop_used_simd(&mut self, simds: &[Self::SIMD]); /// Return a rounded stack adjustement value (must be multiple of 16bytes on ARM64 for example) fn round_stack_adjust(&self, value: usize) -> usize; /// Set the source location of the Wasm to the given offset. @@ -628,6 +628,7 @@ pub trait Machine { ret: Location, ); /// i32 load + #[allow(clippy::too_many_arguments)] fn i32_load( &mut self, addr: Location, @@ -639,6 +640,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i32 load of an unsigned 8bits + #[allow(clippy::too_many_arguments)] fn i32_load_8u( &mut self, addr: Location, @@ -650,6 +652,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i32 load of an signed 8bits + #[allow(clippy::too_many_arguments)] fn i32_load_8s( &mut self, addr: Location, @@ -661,6 +664,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i32 load of an unsigned 16bits + #[allow(clippy::too_many_arguments)] fn i32_load_16u( &mut self, addr: Location, @@ -672,6 +676,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i32 load of an signed 16bits + #[allow(clippy::too_many_arguments)] fn i32_load_16s( &mut self, addr: Location, @@ -683,6 +688,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i32 atomic load + #[allow(clippy::too_many_arguments)] fn i32_atomic_load( &mut self, addr: Location, @@ -694,6 +700,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i32 atomic load of an unsigned 8bits + #[allow(clippy::too_many_arguments)] fn i32_atomic_load_8u( &mut self, addr: Location, @@ -705,6 +712,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i32 atomic load of an unsigned 16bits + #[allow(clippy::too_many_arguments)] fn i32_atomic_load_16u( &mut self, addr: Location, @@ -716,6 +724,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i32 save + #[allow(clippy::too_many_arguments)] fn i32_save( &mut self, value: Location, @@ -727,6 +736,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i32 save of the lower 8bits + #[allow(clippy::too_many_arguments)] fn i32_save_8( &mut self, value: Location, @@ -738,6 +748,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i32 save of the lower 16bits + #[allow(clippy::too_many_arguments)] fn i32_save_16( &mut self, value: Location, @@ -749,6 +760,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i32 atomic save + #[allow(clippy::too_many_arguments)] fn i32_atomic_save( &mut self, value: Location, @@ -760,6 +772,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i32 atomic save of a the lower 8bits + #[allow(clippy::too_many_arguments)] fn i32_atomic_save_8( &mut self, value: Location, @@ -771,6 +784,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i32 atomic save of a the lower 16bits + #[allow(clippy::too_many_arguments)] fn i32_atomic_save_16( &mut self, value: Location, @@ -782,6 +796,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i32 atomic Add with i32 + #[allow(clippy::too_many_arguments)] fn i32_atomic_add( &mut self, loc: Location, @@ -794,6 +809,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i32 atomic Add with unsigned 8bits + #[allow(clippy::too_many_arguments)] fn i32_atomic_add_8u( &mut self, loc: Location, @@ -806,6 +822,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i32 atomic Add with unsigned 16bits + #[allow(clippy::too_many_arguments)] fn i32_atomic_add_16u( &mut self, loc: Location, @@ -818,6 +835,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i32 atomic Sub with i32 + #[allow(clippy::too_many_arguments)] fn i32_atomic_sub( &mut self, loc: Location, @@ -830,6 +848,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i32 atomic Sub with unsigned 8bits + #[allow(clippy::too_many_arguments)] fn i32_atomic_sub_8u( &mut self, loc: Location, @@ -842,6 +861,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i32 atomic Sub with unsigned 16bits + #[allow(clippy::too_many_arguments)] fn i32_atomic_sub_16u( &mut self, loc: Location, @@ -854,6 +874,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i32 atomic And with i32 + #[allow(clippy::too_many_arguments)] fn i32_atomic_and( &mut self, loc: Location, @@ -866,6 +887,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i32 atomic And with unsigned 8bits + #[allow(clippy::too_many_arguments)] fn i32_atomic_and_8u( &mut self, loc: Location, @@ -878,6 +900,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i32 atomic And with unsigned 16bits + #[allow(clippy::too_many_arguments)] fn i32_atomic_and_16u( &mut self, loc: Location, @@ -890,6 +913,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i32 atomic Or with i32 + #[allow(clippy::too_many_arguments)] fn i32_atomic_or( &mut self, loc: Location, @@ -902,6 +926,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i32 atomic Or with unsigned 8bits + #[allow(clippy::too_many_arguments)] fn i32_atomic_or_8u( &mut self, loc: Location, @@ -914,6 +939,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i32 atomic Or with unsigned 16bits + #[allow(clippy::too_many_arguments)] fn i32_atomic_or_16u( &mut self, loc: Location, @@ -926,6 +952,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i32 atomic Xor with i32 + #[allow(clippy::too_many_arguments)] fn i32_atomic_xor( &mut self, loc: Location, @@ -938,6 +965,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i32 atomic Xor with unsigned 8bits + #[allow(clippy::too_many_arguments)] fn i32_atomic_xor_8u( &mut self, loc: Location, @@ -950,6 +978,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i32 atomic Xor with unsigned 16bits + #[allow(clippy::too_many_arguments)] fn i32_atomic_xor_16u( &mut self, loc: Location, @@ -962,6 +991,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i32 atomic Exchange with i32 + #[allow(clippy::too_many_arguments)] fn i32_atomic_xchg( &mut self, loc: Location, @@ -974,6 +1004,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i32 atomic Exchange with u8 + #[allow(clippy::too_many_arguments)] fn i32_atomic_xchg_8u( &mut self, loc: Location, @@ -986,6 +1017,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i32 atomic Exchange with u16 + #[allow(clippy::too_many_arguments)] fn i32_atomic_xchg_16u( &mut self, loc: Location, @@ -998,6 +1030,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i32 atomic Compare and Exchange with i32 + #[allow(clippy::too_many_arguments)] fn i32_atomic_cmpxchg( &mut self, new: Location, @@ -1011,6 +1044,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i32 atomic Compare and Exchange with u8 + #[allow(clippy::too_many_arguments)] fn i32_atomic_cmpxchg_8u( &mut self, new: Location, @@ -1024,6 +1058,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i32 atomic Compare and Exchange with u16 + #[allow(clippy::too_many_arguments)] fn i32_atomic_cmpxchg_16u( &mut self, new: Location, @@ -1245,6 +1280,7 @@ pub trait Machine { ret: Location, ); /// i64 load + #[allow(clippy::too_many_arguments)] fn i64_load( &mut self, addr: Location, @@ -1256,6 +1292,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i64 load of an unsigned 8bits + #[allow(clippy::too_many_arguments)] fn i64_load_8u( &mut self, addr: Location, @@ -1267,6 +1304,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i64 load of an signed 8bits + #[allow(clippy::too_many_arguments)] fn i64_load_8s( &mut self, addr: Location, @@ -1278,6 +1316,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i64 load of an unsigned 32bits + #[allow(clippy::too_many_arguments)] fn i64_load_32u( &mut self, addr: Location, @@ -1289,6 +1328,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i64 load of an signed 32bits + #[allow(clippy::too_many_arguments)] fn i64_load_32s( &mut self, addr: Location, @@ -1300,6 +1340,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i64 load of an signed 16bits + #[allow(clippy::too_many_arguments)] fn i64_load_16u( &mut self, addr: Location, @@ -1311,6 +1352,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i64 load of an signed 16bits + #[allow(clippy::too_many_arguments)] fn i64_load_16s( &mut self, addr: Location, @@ -1322,6 +1364,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i64 atomic load + #[allow(clippy::too_many_arguments)] fn i64_atomic_load( &mut self, addr: Location, @@ -1333,6 +1376,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i64 atomic load from unsigned 8bits + #[allow(clippy::too_many_arguments)] fn i64_atomic_load_8u( &mut self, addr: Location, @@ -1344,6 +1388,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i64 atomic load from unsigned 16bits + #[allow(clippy::too_many_arguments)] fn i64_atomic_load_16u( &mut self, addr: Location, @@ -1355,6 +1400,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i64 atomic load from unsigned 32bits + #[allow(clippy::too_many_arguments)] fn i64_atomic_load_32u( &mut self, addr: Location, @@ -1366,6 +1412,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i64 save + #[allow(clippy::too_many_arguments)] fn i64_save( &mut self, value: Location, @@ -1377,6 +1424,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i64 save of the lower 8bits + #[allow(clippy::too_many_arguments)] fn i64_save_8( &mut self, value: Location, @@ -1388,6 +1436,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i64 save of the lower 16bits + #[allow(clippy::too_many_arguments)] fn i64_save_16( &mut self, value: Location, @@ -1399,6 +1448,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i64 save of the lower 32bits + #[allow(clippy::too_many_arguments)] fn i64_save_32( &mut self, value: Location, @@ -1410,6 +1460,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i64 atomic save + #[allow(clippy::too_many_arguments)] fn i64_atomic_save( &mut self, value: Location, @@ -1421,6 +1472,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i64 atomic save of a the lower 8bits + #[allow(clippy::too_many_arguments)] fn i64_atomic_save_8( &mut self, value: Location, @@ -1432,6 +1484,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i64 atomic save of a the lower 16bits + #[allow(clippy::too_many_arguments)] fn i64_atomic_save_16( &mut self, value: Location, @@ -1443,6 +1496,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i64 atomic save of a the lower 32bits + #[allow(clippy::too_many_arguments)] fn i64_atomic_save_32( &mut self, value: Location, @@ -1454,6 +1508,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i64 atomic Add with i64 + #[allow(clippy::too_many_arguments)] fn i64_atomic_add( &mut self, loc: Location, @@ -1466,6 +1521,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i64 atomic Add with unsigned 8bits + #[allow(clippy::too_many_arguments)] fn i64_atomic_add_8u( &mut self, loc: Location, @@ -1478,6 +1534,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i64 atomic Add with unsigned 16bits + #[allow(clippy::too_many_arguments)] fn i64_atomic_add_16u( &mut self, loc: Location, @@ -1490,6 +1547,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i64 atomic Add with unsigned 32bits + #[allow(clippy::too_many_arguments)] fn i64_atomic_add_32u( &mut self, loc: Location, @@ -1502,6 +1560,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i64 atomic Sub with i64 + #[allow(clippy::too_many_arguments)] fn i64_atomic_sub( &mut self, loc: Location, @@ -1514,6 +1573,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i64 atomic Sub with unsigned 8bits + #[allow(clippy::too_many_arguments)] fn i64_atomic_sub_8u( &mut self, loc: Location, @@ -1526,6 +1586,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i64 atomic Sub with unsigned 16bits + #[allow(clippy::too_many_arguments)] fn i64_atomic_sub_16u( &mut self, loc: Location, @@ -1538,6 +1599,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i64 atomic Sub with unsigned 32bits + #[allow(clippy::too_many_arguments)] fn i64_atomic_sub_32u( &mut self, loc: Location, @@ -1550,6 +1612,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i64 atomic And with i64 + #[allow(clippy::too_many_arguments)] fn i64_atomic_and( &mut self, loc: Location, @@ -1562,6 +1625,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i64 atomic And with unsigned 8bits + #[allow(clippy::too_many_arguments)] fn i64_atomic_and_8u( &mut self, loc: Location, @@ -1574,6 +1638,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i64 atomic And with unsigned 16bits + #[allow(clippy::too_many_arguments)] fn i64_atomic_and_16u( &mut self, loc: Location, @@ -1586,6 +1651,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i64 atomic And with unsigned 32bits + #[allow(clippy::too_many_arguments)] fn i64_atomic_and_32u( &mut self, loc: Location, @@ -1598,6 +1664,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i64 atomic Or with i64 + #[allow(clippy::too_many_arguments)] fn i64_atomic_or( &mut self, loc: Location, @@ -1610,6 +1677,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i64 atomic Or with unsigned 8bits + #[allow(clippy::too_many_arguments)] fn i64_atomic_or_8u( &mut self, loc: Location, @@ -1622,6 +1690,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i64 atomic Or with unsigned 16bits + #[allow(clippy::too_many_arguments)] fn i64_atomic_or_16u( &mut self, loc: Location, @@ -1634,6 +1703,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i64 atomic Or with unsigned 32bits + #[allow(clippy::too_many_arguments)] fn i64_atomic_or_32u( &mut self, loc: Location, @@ -1646,6 +1716,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i64 atomic Xor with i64 + #[allow(clippy::too_many_arguments)] fn i64_atomic_xor( &mut self, loc: Location, @@ -1658,6 +1729,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i64 atomic Xor with unsigned 8bits + #[allow(clippy::too_many_arguments)] fn i64_atomic_xor_8u( &mut self, loc: Location, @@ -1670,6 +1742,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i64 atomic Xor with unsigned 16bits + #[allow(clippy::too_many_arguments)] fn i64_atomic_xor_16u( &mut self, loc: Location, @@ -1682,6 +1755,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i64 atomic Xor with unsigned 32bits + #[allow(clippy::too_many_arguments)] fn i64_atomic_xor_32u( &mut self, loc: Location, @@ -1694,6 +1768,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i64 atomic Exchange with i64 + #[allow(clippy::too_many_arguments)] fn i64_atomic_xchg( &mut self, loc: Location, @@ -1706,6 +1781,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i64 atomic Exchange with u8 + #[allow(clippy::too_many_arguments)] fn i64_atomic_xchg_8u( &mut self, loc: Location, @@ -1718,6 +1794,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i64 atomic Exchange with u16 + #[allow(clippy::too_many_arguments)] fn i64_atomic_xchg_16u( &mut self, loc: Location, @@ -1730,6 +1807,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i64 atomic Exchange with u32 + #[allow(clippy::too_many_arguments)] fn i64_atomic_xchg_32u( &mut self, loc: Location, @@ -1742,6 +1820,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i64 atomic Compare and Exchange with i32 + #[allow(clippy::too_many_arguments)] fn i64_atomic_cmpxchg( &mut self, new: Location, @@ -1755,6 +1834,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i64 atomic Compare and Exchange with u8 + #[allow(clippy::too_many_arguments)] fn i64_atomic_cmpxchg_8u( &mut self, new: Location, @@ -1768,6 +1848,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i64 atomic Compare and Exchange with u16 + #[allow(clippy::too_many_arguments)] fn i64_atomic_cmpxchg_16u( &mut self, new: Location, @@ -1781,6 +1862,7 @@ pub trait Machine { heap_access_oob: Label, ); /// i64 atomic Compare and Exchange with u32 + #[allow(clippy::too_many_arguments)] fn i64_atomic_cmpxchg_32u( &mut self, new: Location, @@ -1795,6 +1877,7 @@ pub trait Machine { ); /// load an F32 + #[allow(clippy::too_many_arguments)] fn f32_load( &mut self, addr: Location, @@ -1806,6 +1889,7 @@ pub trait Machine { heap_access_oob: Label, ); /// f32 save + #[allow(clippy::too_many_arguments)] fn f32_save( &mut self, value: Location, @@ -1818,6 +1902,7 @@ pub trait Machine { heap_access_oob: Label, ); /// load an F64 + #[allow(clippy::too_many_arguments)] fn f64_load( &mut self, addr: Location, @@ -1829,6 +1914,7 @@ pub trait Machine { heap_access_oob: Label, ); /// f64 save + #[allow(clippy::too_many_arguments)] fn f64_save( &mut self, value: Location, diff --git a/lib/compiler-singlepass/src/machine_arm64.rs b/lib/compiler-singlepass/src/machine_arm64.rs index febf9f7755c..743c0619a94 100644 --- a/lib/compiler-singlepass/src/machine_arm64.rs +++ b/lib/compiler-singlepass/src/machine_arm64.rs @@ -151,19 +151,19 @@ impl MachineARM64 { match ty { ImmType::None => false, ImmType::NoneXzr => false, - ImmType::Bits8 => (imm >= 0) && (imm < 256), - ImmType::Bits12 => (imm >= 0) && (imm < 0x1000), - ImmType::Shift32 => (imm >= 0) && (imm < 32), - ImmType::Shift32No0 => (imm > 0) && (imm < 32), - ImmType::Shift64 => (imm >= 0) && (imm < 64), - ImmType::Shift64No0 => (imm > 0) && (imm < 64), + ImmType::Bits8 => (0..256).contains(&imm), + ImmType::Bits12 => (0..0x1000).contains(&imm), + ImmType::Shift32 => (0..32).contains(&imm), + ImmType::Shift32No0 => (1..32).contains(&imm), + ImmType::Shift64 => (0..64).contains(&imm), + ImmType::Shift64No0 => (1..64).contains(&imm), ImmType::Logical32 => encode_logical_immediate_32bit(imm as u32).is_some(), ImmType::Logical64 => encode_logical_immediate_64bit(imm as u64).is_some(), ImmType::UnscaledOffset => (imm > -256) && (imm < 256), - ImmType::OffsetByte => (imm >= 0) && (imm < 0x1000), - ImmType::OffsetHWord => (imm & 1 == 0) && (imm >= 0) && (imm < 0x2000), - ImmType::OffsetWord => (imm & 3 == 0) && (imm >= 0) && (imm < 0x4000), - ImmType::OffsetDWord => (imm & 7 == 0) && (imm >= 0) && (imm < 0x8000), + ImmType::OffsetByte => (0..0x1000).contains(&imm), + ImmType::OffsetHWord => (imm & 1 == 0) && (0..0x2000).contains(&imm), + ImmType::OffsetWord => (imm & 3 == 0) && (0..0x4000).contains(&imm), + ImmType::OffsetDWord => (imm & 7 == 0) && (0..0x8000).contains(&imm), } } @@ -181,67 +181,61 @@ impl MachineARM64 { Location::Imm8(val) => { if allow_imm == ImmType::NoneXzr && val == 0 { Location::GPR(GPR::XzrSp) + } else if self.compatible_imm(val as i64, allow_imm) { + src } else { - if self.compatible_imm(val as i64, allow_imm) { - src + let tmp = if let Some(wanted) = wanted { + wanted } else { - let tmp = if wanted.is_some() { - wanted.unwrap() - } else { - let tmp = self.acquire_temp_gpr().unwrap(); - temps.push(tmp.clone()); - tmp - }; - self.assembler.emit_mov_imm(Location::GPR(tmp), val as u64); - Location::GPR(tmp) - } + let tmp = self.acquire_temp_gpr().unwrap(); + temps.push(tmp); + tmp + }; + self.assembler.emit_mov_imm(Location::GPR(tmp), val as u64); + Location::GPR(tmp) } } Location::Imm32(val) => { if allow_imm == ImmType::NoneXzr && val == 0 { Location::GPR(GPR::XzrSp) + } else if self.compatible_imm(val as i64, allow_imm) { + src } else { - if self.compatible_imm(val as i64, allow_imm) { - src + let tmp = if let Some(wanted) = wanted { + wanted } else { - let tmp = if wanted.is_some() { - wanted.unwrap() - } else { - let tmp = self.acquire_temp_gpr().unwrap(); - temps.push(tmp.clone()); - tmp - }; - self.assembler - .emit_mov_imm(Location::GPR(tmp), (val as i64) as u64); - Location::GPR(tmp) - } + let tmp = self.acquire_temp_gpr().unwrap(); + temps.push(tmp); + tmp + }; + self.assembler + .emit_mov_imm(Location::GPR(tmp), (val as i64) as u64); + Location::GPR(tmp) } } Location::Imm64(val) => { if allow_imm == ImmType::NoneXzr && val == 0 { Location::GPR(GPR::XzrSp) + } else if self.compatible_imm(val as i64, allow_imm) { + src } else { - if self.compatible_imm(val as i64, allow_imm) { - src + let tmp = if let Some(wanted) = wanted { + wanted } else { - let tmp = if wanted.is_some() { - wanted.unwrap() - } else { - let tmp = self.acquire_temp_gpr().unwrap(); - temps.push(tmp.clone()); - tmp - }; - self.assembler.emit_mov_imm(Location::GPR(tmp), val as u64); - Location::GPR(tmp) - } + let tmp = self.acquire_temp_gpr().unwrap(); + temps.push(tmp); + tmp + }; + self.assembler.emit_mov_imm(Location::GPR(tmp), val as u64); + Location::GPR(tmp) } } Location::Memory(reg, val) => { - let tmp = if wanted.is_some() { - wanted.unwrap() + let tmp = if let Some(wanted) = wanted { + wanted } else { let tmp = self.acquire_temp_gpr().unwrap(); - temps.push(tmp.clone()); + temps.push(tmp); tmp }; if read_val { @@ -327,7 +321,7 @@ impl MachineARM64 { Location::SIMD(_) => src, Location::GPR(_) => { let tmp = self.acquire_temp_simd().unwrap(); - temps.push(tmp.clone()); + temps.push(tmp); if read_val { self.assembler.emit_mov(sz, src, Location::SIMD(tmp)); } @@ -339,7 +333,7 @@ impl MachineARM64 { } else { let gpr = self.acquire_temp_gpr().unwrap(); let tmp = self.acquire_temp_simd().unwrap(); - temps.push(tmp.clone()); + temps.push(tmp); self.assembler.emit_mov_imm(Location::GPR(gpr), val as u64); self.assembler .emit_mov(sz, Location::GPR(gpr), Location::SIMD(tmp)); @@ -353,7 +347,7 @@ impl MachineARM64 { } else { let gpr = self.acquire_temp_gpr().unwrap(); let tmp = self.acquire_temp_simd().unwrap(); - temps.push(tmp.clone()); + temps.push(tmp); self.assembler .emit_mov_imm(Location::GPR(gpr), (val as i64) as u64); self.assembler @@ -368,7 +362,7 @@ impl MachineARM64 { } else { let gpr = self.acquire_temp_gpr().unwrap(); let tmp = self.acquire_temp_simd().unwrap(); - temps.push(tmp.clone()); + temps.push(tmp); self.assembler.emit_mov_imm(Location::GPR(gpr), val as u64); self.assembler .emit_mov(sz, Location::GPR(gpr), Location::SIMD(tmp)); @@ -378,7 +372,7 @@ impl MachineARM64 { } Location::Memory(reg, val) => { let tmp = self.acquire_temp_simd().unwrap(); - temps.push(tmp.clone()); + temps.push(tmp); if read_val { let offsize = if sz == Size::S32 { ImmType::OffsetWord @@ -852,6 +846,7 @@ impl MachineARM64 { } } + #[allow(clippy::too_many_arguments)] fn memory_op( &mut self, addr: Location, @@ -1029,7 +1024,7 @@ impl MachineARM64 { if (offset & ((1 << shift) - 1)) != 0 { return false; } - return true; + true } fn emit_push(&mut self, sz: Size, src: Location) { @@ -1128,12 +1123,12 @@ impl MachineARM64 { fn set_default_nan(&mut self, temps: &mut Vec) -> GPR { // temporarly set FPCR to DefaultNan let old_fpcr = self.acquire_temp_gpr().unwrap(); - temps.push(old_fpcr.clone()); + temps.push(old_fpcr); self.assembler.emit_read_fpcr(old_fpcr); let new_fpcr = self.acquire_temp_gpr().unwrap(); - temps.push(new_fpcr.clone()); + temps.push(new_fpcr); let tmp = self.acquire_temp_gpr().unwrap(); - temps.push(tmp.clone()); + temps.push(tmp); self.assembler .emit_mov(Size::S32, Location::Imm32(1), Location::GPR(tmp)); self.assembler @@ -1152,10 +1147,10 @@ impl MachineARM64 { fn set_trap_enabled(&mut self, temps: &mut Vec) -> GPR { // temporarly set FPCR to DefaultNan let old_fpcr = self.acquire_temp_gpr().unwrap(); - temps.push(old_fpcr.clone()); + temps.push(old_fpcr); self.assembler.emit_read_fpcr(old_fpcr); let new_fpcr = self.acquire_temp_gpr().unwrap(); - temps.push(new_fpcr.clone()); + temps.push(new_fpcr); self.assembler .emit_mov(Size::S64, Location::GPR(old_fpcr), Location::GPR(new_fpcr)); // IOE is bit 8 of FPCR @@ -1195,7 +1190,7 @@ impl MachineARM64 { let end = self.assembler.get_label(); let fpsr = self.read_fpsr(); - temps.push(fpsr.clone()); + temps.push(fpsr); // no trap, than all good self.assembler .emit_tbz_label(Size::S32, Location::GPR(fpsr), 0, end); @@ -1264,26 +1259,14 @@ impl Machine for MachineARM64 { fn get_used_gprs(&self) -> Vec { GPR::iterator() - .filter_map(|x| { - if self.used_gprs & (1 << x.into_index()) != 0 { - Some(x) - } else { - None - } - }) + .filter(|x| self.used_gprs & (1 << x.into_index()) != 0) .cloned() .collect() } fn get_used_simd(&self) -> Vec { NEON::iterator() - .filter_map(|x| { - if self.used_simd & (1 << x.into_index()) != 0 { - Some(x) - } else { - None - } - }) + .filter(|x| self.used_simd & (1 << x.into_index()) != 0) .cloned() .collect() } @@ -1333,7 +1316,7 @@ impl Machine for MachineARM64 { self.used_gprs_insert(gpr); } - fn push_used_gpr(&mut self, used_gprs: &Vec) -> usize { + fn push_used_gpr(&mut self, used_gprs: &[GPR]) -> usize { if used_gprs.len() % 2 == 1 { self.emit_push(Size::S64, Location::GPR(GPR::XzrSp)); } @@ -1342,7 +1325,7 @@ impl Machine for MachineARM64 { } ((used_gprs.len() + 1) / 2) * 16 } - fn pop_used_gpr(&mut self, used_gprs: &Vec) { + fn pop_used_gpr(&mut self, used_gprs: &[GPR]) { for r in used_gprs.iter().rev() { self.emit_pop(Size::S64, Location::GPR(*r)); } @@ -1390,10 +1373,10 @@ impl Machine for MachineARM64 { // Releases a temporary NEON register. fn release_simd(&mut self, simd: NEON) { - assert_eq!(self.used_simd_remove(&simd), true); + assert!(self.used_simd_remove(&simd)); } - fn push_used_simd(&mut self, used_neons: &Vec) -> usize { + fn push_used_simd(&mut self, used_neons: &[NEON]) -> usize { let stack_adjust = if used_neons.len() & 1 == 1 { (used_neons.len() * 8) as u32 + 8 } else { @@ -1410,7 +1393,7 @@ impl Machine for MachineARM64 { } stack_adjust as usize } - fn pop_used_simd(&mut self, used_neons: &Vec) { + fn pop_used_simd(&mut self, used_neons: &[NEON]) { for (i, r) in used_neons.iter().enumerate() { self.assembler.emit_ldr( Size::S64, @@ -1671,10 +1654,8 @@ impl Machine for MachineARM64 { Size::S64 => 3, }; // align first - if sz > 1 { - if *stack_args & !((1 << sz) - 1) != 0 { - *stack_args = (*stack_args + ((1 << sz) - 1)) & !((1 << sz) - 1); - } + if sz > 1 && *stack_args & !((1 << sz) - 1) != 0 { + *stack_args = (*stack_args + ((1 << sz) - 1)) & !((1 << sz) - 1); } let loc = Location::Memory(GPR::XzrSp, *stack_args as i32); *stack_args += 1 << sz; @@ -1724,10 +1705,8 @@ impl Machine for MachineARM64 { Size::S64 => 3, }; // align first - if sz > 1 { - if *stack_args & !((1 << sz) - 1) != 0 { - *stack_args = (*stack_args + ((1 << sz) - 1)) & !((1 << sz) - 1); - } + if sz > 1 && *stack_args & !((1 << sz) - 1) != 0 { + *stack_args = (*stack_args + ((1 << sz) - 1)) & !((1 << sz) - 1); } let loc = Location::Memory(GPR::X29, 16 * 2 + *stack_args as i32); *stack_args += 1 << sz; @@ -1757,6 +1736,7 @@ impl Machine for MachineARM64 { idx: usize, calling_convention: CallingConvention, ) -> Location { + #[allow(clippy::match_single_binding)] match calling_convention { _ => match idx { 0 => Location::GPR(GPR::X0), @@ -1950,7 +1930,7 @@ impl Machine for MachineARM64 { let label = self.assembler.get_label(); let mut temps = vec![]; let dest = self.acquire_temp_gpr().unwrap(); - temps.push(dest.clone()); + temps.push(dest); let cnt = self.location_to_reg( Size::S64, Location::Imm64(init_stack_loc_cnt), @@ -2530,7 +2510,7 @@ impl Machine for MachineARM64 { let dest = self.location_to_reg(Size::S32, ret, &mut temps, ImmType::None, false, None); let dest = if dest == src1 || dest == src2 { let tmp = self.acquire_temp_gpr().unwrap(); - temps.push(tmp.clone()); + temps.push(tmp); self.assembler.emit_mov(Size::S32, dest, Location::GPR(tmp)); Location::GPR(tmp) } else { @@ -2564,7 +2544,7 @@ impl Machine for MachineARM64 { let dest = self.location_to_reg(Size::S32, ret, &mut temps, ImmType::None, false, None); let dest = if dest == src1 || dest == src2 { let tmp = self.acquire_temp_gpr().unwrap(); - temps.push(tmp.clone()); + temps.push(tmp); self.assembler.emit_mov(Size::S32, dest, Location::GPR(tmp)); Location::GPR(tmp) } else { @@ -2668,7 +2648,7 @@ impl Machine for MachineARM64 { let dest = self.location_to_reg(Size::S32, ret, &mut temps, ImmType::None, false, None); let src = if src == loc { let tmp = self.acquire_temp_gpr().unwrap(); - temps.push(tmp.clone()); + temps.push(tmp); self.assembler.emit_mov(Size::S32, src, Location::GPR(tmp)); Location::GPR(tmp) } else { @@ -2676,7 +2656,7 @@ impl Machine for MachineARM64 { }; let tmp = { let tmp = self.acquire_temp_gpr().unwrap(); - temps.push(tmp.clone()); + temps.push(tmp); Location::GPR(tmp) }; let label_loop = self.assembler.get_label(); @@ -3465,7 +3445,7 @@ impl Machine for MachineARM64 { let dest = self.location_to_reg(Size::S64, ret, &mut temps, ImmType::None, false, None); let dest = if dest == src1 || dest == src2 { let tmp = self.acquire_temp_gpr().unwrap(); - temps.push(tmp.clone()); + temps.push(tmp); self.assembler.emit_mov(Size::S32, dest, Location::GPR(tmp)); Location::GPR(tmp) } else { @@ -3499,7 +3479,7 @@ impl Machine for MachineARM64 { let dest = self.location_to_reg(Size::S64, ret, &mut temps, ImmType::None, false, None); let dest = if dest == src1 || dest == src2 { let tmp = self.acquire_temp_gpr().unwrap(); - temps.push(tmp.clone()); + temps.push(tmp); self.assembler.emit_mov(Size::S64, dest, Location::GPR(tmp)); Location::GPR(tmp) } else { @@ -3601,7 +3581,7 @@ impl Machine for MachineARM64 { let dest = self.location_to_reg(Size::S64, ret, &mut temps, ImmType::None, false, None); let src = if src == loc { let tmp = self.acquire_temp_gpr().unwrap(); - temps.push(tmp.clone()); + temps.push(tmp); self.assembler.emit_mov(Size::S64, src, Location::GPR(tmp)); Location::GPR(tmp) } else { @@ -3609,7 +3589,7 @@ impl Machine for MachineARM64 { }; let tmp = { let tmp = self.acquire_temp_gpr().unwrap(); - temps.push(tmp.clone()); + temps.push(tmp); Location::GPR(tmp) }; let label_loop = self.assembler.get_label(); @@ -5199,8 +5179,8 @@ impl Machine for MachineARM64 { let mut instructions = vec![]; for &(instruction_offset, ref inst) in &self.unwind_ops { let instruction_offset = instruction_offset as u32; - match inst { - &UnwindOps::PushFP { up_to_sp } => { + match *inst { + UnwindOps::PushFP { up_to_sp } => { instructions.push(( instruction_offset, CallFrameInstruction::CfaOffset(up_to_sp as i32), @@ -5210,7 +5190,7 @@ impl Machine for MachineARM64 { CallFrameInstruction::Offset(AArch64::X29, -(up_to_sp as i32)), )); } - &UnwindOps::Push2Regs { + UnwindOps::Push2Regs { reg1, reg2, up_to_sp, @@ -5228,13 +5208,13 @@ impl Machine for MachineARM64 { CallFrameInstruction::Offset(dwarf_index(reg1), -(up_to_sp as i32)), )); } - &UnwindOps::DefineNewFrame => { + UnwindOps::DefineNewFrame => { instructions.push(( instruction_offset, CallFrameInstruction::CfaRegister(AArch64::X29), )); } - &UnwindOps::SaveRegister { reg, bp_neg_offset } => instructions.push(( + UnwindOps::SaveRegister { reg, bp_neg_offset } => instructions.push(( instruction_offset, CallFrameInstruction::Offset(dwarf_index(reg), -bp_neg_offset), )), diff --git a/lib/compiler-singlepass/src/machine_x64.rs b/lib/compiler-singlepass/src/machine_x64.rs index 4f8d892e940..db657cdd21c 100644 --- a/lib/compiler-singlepass/src/machine_x64.rs +++ b/lib/compiler-singlepass/src/machine_x64.rs @@ -146,11 +146,13 @@ impl MachineX86_64 { } let mode = match (src, dst) { (Location::GPR(_), Location::GPR(_)) - if (op as *const u8 == AssemblerX64::emit_imul as *const u8) => + if std::ptr::eq(op as *const u8, AssemblerX64::emit_imul as *const u8) => { RelaxMode::Direct } - _ if (op as *const u8 == AssemblerX64::emit_imul as *const u8) => RelaxMode::BothToGPR, + _ if std::ptr::eq(op as *const u8, AssemblerX64::emit_imul as *const u8) => { + RelaxMode::BothToGPR + } (Location::Memory(_, _), Location::Memory(_, _)) => RelaxMode::SrcToGPR, (Location::Imm64(_), Location::Imm64(_)) | (Location::Imm64(_), Location::Imm32(_)) => { @@ -431,6 +433,7 @@ impl MachineX86_64 { f(&mut self.assembler, Size::S32, Location::GPR(GPR::RCX), ret); } + #[allow(clippy::too_many_arguments)] fn memory_op( &mut self, addr: Location, @@ -548,6 +551,7 @@ impl MachineX86_64 { self.release_gpr(tmp_addr); } + #[allow(clippy::too_many_arguments)] fn emit_compare_and_swap( &mut self, loc: Location, @@ -608,6 +612,7 @@ impl MachineX86_64 { } // Checks for underflow/overflow/nan. + #[allow(clippy::too_many_arguments)] fn emit_f32_int_conv_check( &mut self, reg: XMM, @@ -685,6 +690,7 @@ impl MachineX86_64 { self.emit_label(end); } + #[allow(clippy::too_many_arguments)] fn emit_f32_int_conv_check_sat< F1: FnOnce(&mut Self), F2: FnOnce(&mut Self), @@ -743,6 +749,7 @@ impl MachineX86_64 { self.emit_label(end); } // Checks for underflow/overflow/nan. + #[allow(clippy::too_many_arguments)] fn emit_f64_int_conv_check( &mut self, reg: XMM, @@ -817,6 +824,7 @@ impl MachineX86_64 { self.emit_label(end); } + #[allow(clippy::too_many_arguments)] fn emit_f64_int_conv_check_sat< F1: FnOnce(&mut Self), F2: FnOnce(&mut Self), @@ -1676,26 +1684,14 @@ impl Machine for MachineX86_64 { fn get_used_gprs(&self) -> Vec { GPR::iterator() - .filter_map(|x| { - if self.used_gprs & (1 << x.into_index()) != 0 { - Some(x) - } else { - None - } - }) + .filter(|x| self.used_gprs & (1 << x.into_index()) != 0) .cloned() .collect() } fn get_used_simd(&self) -> Vec { XMM::iterator() - .filter_map(|x| { - if self.used_simd & (1 << x.into_index()) != 0 { - Some(x) - } else { - None - } - }) + .filter(|x| self.used_simd & (1 << x.into_index()) != 0) .cloned() .collect() } @@ -1745,13 +1741,13 @@ impl Machine for MachineX86_64 { self.used_gprs_insert(gpr); } - fn push_used_gpr(&mut self, used_gprs: &Vec) -> usize { + fn push_used_gpr(&mut self, used_gprs: &[GPR]) -> usize { for r in used_gprs.iter() { self.assembler.emit_push(Size::S64, Location::GPR(*r)); } used_gprs.len() * 8 } - fn pop_used_gpr(&mut self, used_gprs: &Vec) { + fn pop_used_gpr(&mut self, used_gprs: &[GPR]) { for r in used_gprs.iter().rev() { self.assembler.emit_pop(Size::S64, Location::GPR(*r)); } @@ -1796,10 +1792,10 @@ impl Machine for MachineX86_64 { // Releases a temporary XMM register. fn release_simd(&mut self, simd: XMM) { - assert_eq!(self.used_simd_remove(&simd), true); + assert!(self.used_simd_remove(&simd)); } - fn push_used_simd(&mut self, used_xmms: &Vec) -> usize { + fn push_used_simd(&mut self, used_xmms: &[XMM]) -> usize { self.adjust_stack((used_xmms.len() * 8) as u32); for (i, r) in used_xmms.iter().enumerate() { @@ -1812,7 +1808,7 @@ impl Machine for MachineX86_64 { used_xmms.len() * 8 } - fn pop_used_simd(&mut self, used_xmms: &Vec) { + fn pop_used_simd(&mut self, used_xmms: &[XMM]) { for (i, r) in used_xmms.iter().enumerate() { self.move_location( Size::S64, @@ -7009,17 +7005,17 @@ impl Machine for MachineX86_64 { { match calling_convention { CallingConvention::WindowsFastcall => { - let mut param_locations: Vec = vec![]; - for i in 0..sig.params().len() { - let loc = match i { - 0..=2 => { - static PARAM_REGS: &[GPR] = &[GPR::RDX, GPR::R8, GPR::R9]; - Location::GPR(PARAM_REGS[i]) - } - _ => Location::Memory(GPR::RSP, 32 + 8 + ((i - 3) * 8) as i32), // will not be used anyway - }; - param_locations.push(loc); - } + static PARAM_REGS: &[GPR] = &[GPR::RDX, GPR::R8, GPR::R9]; + let gpr_iter = PARAM_REGS.iter().map(|r| Location::GPR(*r)); + let memory_iter = (0..) + .map(|i| Location::Memory(GPR::RSP, 32 + 8 + ((i - 3) * 8) as i32)) + .skip(PARAM_REGS.len()); + + let param_locations: Vec = gpr_iter + .chain(memory_iter) + .take(sig.params().len()) + .collect(); + // Copy Float arguments to XMM from GPR. let mut argalloc = ArgumentRegisterAllocator::default(); for (i, ty) in sig.params().iter().enumerate() { @@ -7034,8 +7030,6 @@ impl Machine for MachineX86_64 { } } _ => { - let mut param_locations: Vec = vec![]; - // Allocate stack space for arguments. let stack_offset: i32 = if sig.params().len() > 5 { 5 * 8 @@ -7051,21 +7045,18 @@ impl Machine for MachineX86_64 { } // Store all arguments to the stack to prevent overwrite. - for i in 0..sig.params().len() { - let loc = match i { - 0..=4 => { - static PARAM_REGS: &[GPR] = - &[GPR::RSI, GPR::RDX, GPR::RCX, GPR::R8, GPR::R9]; - let loc = Location::Memory(GPR::RSP, (i * 8) as i32); - a.emit_mov(Size::S64, Location::GPR(PARAM_REGS[i]), loc); - loc - } - _ => { - Location::Memory(GPR::RSP, stack_offset + 8 + ((i - 5) * 8) as i32) - } - }; - param_locations.push(loc); - } + static PARAM_REGS: &[GPR] = &[GPR::RSI, GPR::RDX, GPR::RCX, GPR::R8, GPR::R9]; + let gpr_iter = PARAM_REGS.iter().map(|r| Location::GPR(*r)); + let memory_iter = (0..) + .map(|i| { + Location::Memory(GPR::RSP, stack_offset + 8 + ((i - 5) * 8) as i32) + }) + .skip(gpr_iter.len()); + + let param_locations: Vec = gpr_iter + .chain(memory_iter) + .take(sig.params().len()) + .collect(); // Copy arguments. let mut argalloc = ArgumentRegisterAllocator::default(); @@ -7156,8 +7147,8 @@ impl Machine for MachineX86_64 { let mut instructions = vec![]; for &(instruction_offset, ref inst) in &self.unwind_ops { let instruction_offset = instruction_offset as u32; - match inst { - &UnwindOps::PushFP { up_to_sp } => { + match *inst { + UnwindOps::PushFP { up_to_sp } => { instructions.push(( instruction_offset, CallFrameInstruction::CfaOffset(up_to_sp as i32), @@ -7167,17 +7158,17 @@ impl Machine for MachineX86_64 { CallFrameInstruction::Offset(X86_64::RBP, -(up_to_sp as i32)), )); } - &UnwindOps::DefineNewFrame => { + UnwindOps::DefineNewFrame => { instructions.push(( instruction_offset, CallFrameInstruction::CfaRegister(X86_64::RBP), )); } - &UnwindOps::SaveRegister { reg, bp_neg_offset } => instructions.push(( + UnwindOps::SaveRegister { reg, bp_neg_offset } => instructions.push(( instruction_offset, CallFrameInstruction::Offset(dwarf_index(reg), -bp_neg_offset), )), - &UnwindOps::Push2Regs { .. } => unimplemented!(), + UnwindOps::Push2Regs { .. } => unimplemented!(), } } Some(UnwindInstructions { diff --git a/lib/compiler-singlepass/src/unwind.rs b/lib/compiler-singlepass/src/unwind.rs index 03ffe6ee642..8a7b60c45b1 100644 --- a/lib/compiler-singlepass/src/unwind.rs +++ b/lib/compiler-singlepass/src/unwind.rs @@ -37,7 +37,7 @@ impl UnwindInstructions { pub fn to_fde(&self, address: Address) -> UnwindFrame { let mut fde = FrameDescriptionEntry::new(address, self.len); for (offset, inst) in &self.instructions { - fde.add_instruction(*offset, inst.clone().into()); + fde.add_instruction(*offset, inst.clone()); } UnwindFrame::SystemV(fde) } diff --git a/lib/compiler-singlepass/src/unwind_winx64.rs b/lib/compiler-singlepass/src/unwind_winx64.rs index c2f4174809d..389cba3c927 100644 --- a/lib/compiler-singlepass/src/unwind_winx64.rs +++ b/lib/compiler-singlepass/src/unwind_winx64.rs @@ -95,10 +95,7 @@ impl UnwindCode { reg, stack_offset, } => { - let is_xmm = match self { - Self::SaveXmm { .. } => true, - _ => false, - }; + let is_xmm = matches!(self, Self::SaveXmm { .. }); let (op_small, op_large) = if is_xmm { (UnwindOperation::SaveXmm128, UnwindOperation::SaveXmm128Far) } else { @@ -243,7 +240,7 @@ impl UnwindInfo { const UNWIND_RBP_REG: u8 = 5; -pub(crate) fn create_unwind_info_from_insts(insts: &Vec<(usize, UnwindOps)>) -> Option { +pub(crate) fn create_unwind_info_from_insts(insts: &[(usize, UnwindOps)]) -> Option { let mut unwind_codes = vec![]; let mut frame_register_offset = 0; let mut max_unwind_offset = 0; diff --git a/lib/compiler-singlepass/src/x64_decl.rs b/lib/compiler-singlepass/src/x64_decl.rs index ecb4071f5ef..298c559cc26 100644 --- a/lib/compiler-singlepass/src/x64_decl.rs +++ b/lib/compiler-singlepass/src/x64_decl.rs @@ -261,8 +261,8 @@ impl ArgumentRegisterAllocator { pub fn next(&mut self, ty: Type, calling_convention: CallingConvention) -> Option { match calling_convention { CallingConvention::WindowsFastcall => { - static GPR_SEQ: &'static [GPR] = &[GPR::RCX, GPR::RDX, GPR::R8, GPR::R9]; - static XMM_SEQ: &'static [XMM] = &[XMM::XMM0, XMM::XMM1, XMM::XMM2, XMM::XMM3]; + static GPR_SEQ: &[GPR] = &[GPR::RCX, GPR::RDX, GPR::R8, GPR::R9]; + static XMM_SEQ: &[XMM] = &[XMM::XMM0, XMM::XMM1, XMM::XMM2, XMM::XMM3]; let idx = self.n_gprs + self.n_xmms; match ty { Type::I32 | Type::I64 => { @@ -290,9 +290,9 @@ impl ArgumentRegisterAllocator { } } _ => { - static GPR_SEQ: &'static [GPR] = + static GPR_SEQ: &[GPR] = &[GPR::RDI, GPR::RSI, GPR::RDX, GPR::RCX, GPR::R8, GPR::R9]; - static XMM_SEQ: &'static [XMM] = &[ + static XMM_SEQ: &[XMM] = &[ XMM::XMM0, XMM::XMM1, XMM::XMM2, diff --git a/lib/compiler/src/target.rs b/lib/compiler/src/target.rs index 9d18d79e87d..e2025d4a4b5 100644 --- a/lib/compiler/src/target.rs +++ b/lib/compiler/src/target.rs @@ -1,4 +1,12 @@ //! Target configuration + +// The clippy::use_self exception is due to a false positive indicating that +// `CpuFeature` should be replaced by `Self`. Attaching the allowance to the +// type itself has no effect, therefore it's disabled for the whole module. +// Feel free to remove this allow attribute once the bug is fixed. +// See https://github.com/rust-lang/rust-clippy/issues/6902 +#![allow(clippy::use_self)] + use crate::error::ParseCpuFeatureError; use crate::lib::std::str::FromStr; use crate::lib::std::string::{String, ToString}; diff --git a/lib/derive/src/env/mod.rs b/lib/derive/src/env/mod.rs index 8e034f670f7..b9558c5dbb7 100644 --- a/lib/derive/src/env/mod.rs +++ b/lib/derive/src/env/mod.rs @@ -137,9 +137,8 @@ fn derive_struct_fields(data: &DataStruct) -> (TokenStream, TokenStream) { if optional { quote_spanned! { f.span()=> - match #access_expr { - Ok(#name) => { self.#name.initialize(#name); }, - Err(_) => (), + if let Ok(#name) = #access_expr { + self.#name.initialize(#name); }; } } else { @@ -149,43 +148,38 @@ fn derive_struct_fields(data: &DataStruct) -> (TokenStream, TokenStream) { self.#name.initialize(#name); } } - } else { - if let Some(identifier) = identifier { - let mut access_expr = quote_spanned! { - f.span() => - instance.exports.get_with_generics_weak::<#inner_type, _, _>(#identifier) + } else if let Some(identifier) = identifier { + let mut access_expr = quote_spanned! { + f.span() => + instance.exports.get_with_generics_weak::<#inner_type, _, _>(#identifier) + }; + for alias in aliases { + access_expr = quote_spanned! { + f.span()=> + #access_expr .or_else(|_| instance.exports.get_with_generics_weak::<#inner_type, _, _>(#alias)) }; - for alias in aliases { - access_expr = quote_spanned! { - f.span()=> - #access_expr .or_else(|_| instance.exports.get_with_generics_weak::<#inner_type, _, _>(#alias)) - }; - } - let local_var = - Ident::new(&format!("field_{}", field_num), identifier.span()); - if optional { - quote_spanned! { - f.span()=> - match #access_expr { - Ok(#local_var) => { - self.#field_idx.initialize(#local_var); - }, - Err(_) => (), - } - } - } else { - quote_spanned! { - f.span()=> - let #local_var: #inner_type = #access_expr?; - self.#field_idx.initialize(#local_var); - } + } + let local_var = + Ident::new(&format!("field_{}", field_num), identifier.span()); + if optional { + quote_spanned! { + f.span()=> + if let Ok(#local_var) = #access_expr { + self.#field_idx.initialize(#local_var); + } } } else { - abort!( - span, - "Expected `name` field on export attribute because field does not have a name. For example: `#[wasmer(export(name = \"wasm_ident\"))]`.", - ); + quote_spanned! { + f.span()=> + let #local_var: #inner_type = #access_expr?; + self.#field_idx.initialize(#local_var); + } } + } else { + abort!( + span, + "Expected `name` field on export attribute because field does not have a name. For example: `#[wasmer(export(name = \"wasm_ident\"))]`.", + ); }; finish.push(finish_tokens); diff --git a/lib/derive/src/value_type.rs b/lib/derive/src/value_type.rs index 48fbb4ff60c..5e9fe23c826 100644 --- a/lib/derive/src/value_type.rs +++ b/lib/derive/src/value_type.rs @@ -98,7 +98,7 @@ pub fn impl_value_type(input: &DeriveInput) -> TokenStream { _ => abort!(input, "ValueType can only be derived for structs"), }; - let zero_padding = zero_padding(&fields); + let zero_padding = zero_padding(fields); quote! { unsafe impl #impl_generics ::wasmer::ValueType for #struct_name #ty_generics #where_clause { diff --git a/lib/emscripten/src/emscripten_target.rs b/lib/emscripten/src/emscripten_target.rs index 7b1a4336207..c4b3aff8d90 100644 --- a/lib/emscripten/src/emscripten_target.rs +++ b/lib/emscripten/src/emscripten_target.rs @@ -116,6 +116,7 @@ pub fn _getloadavg(_ctx: &EmEnv, _loadavg: i32, _nelem: i32) -> i32 { debug!("emscripten::getloadavg"); 0 } +#[allow(clippy::too_many_arguments)] pub fn _getnameinfo( _ctx: &EmEnv, _addr: i32, @@ -272,6 +273,7 @@ pub fn invoke_iiiiii(ctx: &EmEnv, index: i32, a1: i32, a2: i32, a3: i32, a4: i32 a5 ) } +#[allow(clippy::too_many_arguments)] pub fn invoke_iiiiiii( ctx: &EmEnv, index: i32, @@ -296,6 +298,7 @@ pub fn invoke_iiiiiii( a6 ) } +#[allow(clippy::too_many_arguments)] pub fn invoke_iiiiiiii( ctx: &EmEnv, index: i32, @@ -322,6 +325,7 @@ pub fn invoke_iiiiiiii( a7 ) } +#[allow(clippy::too_many_arguments)] pub fn invoke_iiiiiiiii( ctx: &EmEnv, index: i32, @@ -350,6 +354,7 @@ pub fn invoke_iiiiiiiii( a8 ) } +#[allow(clippy::too_many_arguments)] pub fn invoke_iiiiiiiiii( ctx: &EmEnv, index: i32, @@ -380,6 +385,7 @@ pub fn invoke_iiiiiiiiii( a9 ) } +#[allow(clippy::too_many_arguments)] pub fn invoke_iiiiiiiiiii( ctx: &EmEnv, index: i32, @@ -430,6 +436,7 @@ pub fn invoke_viiiii(ctx: &EmEnv, index: i32, a1: i32, a2: i32, a3: i32, a4: i32 a5 ) } +#[allow(clippy::too_many_arguments)] pub fn invoke_viiiiii( ctx: &EmEnv, index: i32, @@ -454,6 +461,7 @@ pub fn invoke_viiiiii( a6 ) } +#[allow(clippy::too_many_arguments)] pub fn invoke_viiiiiii( ctx: &EmEnv, index: i32, @@ -480,6 +488,7 @@ pub fn invoke_viiiiiii( a7 ) } +#[allow(clippy::too_many_arguments)] pub fn invoke_viiiiiiii( ctx: &EmEnv, index: i32, @@ -508,6 +517,7 @@ pub fn invoke_viiiiiiii( a8 ) } +#[allow(clippy::too_many_arguments)] pub fn invoke_viiiiiiiii( ctx: &EmEnv, index: i32, @@ -538,6 +548,7 @@ pub fn invoke_viiiiiiiii( a9 ) } +#[allow(clippy::too_many_arguments)] pub fn invoke_viiiiiiiiii( ctx: &EmEnv, index: i32, @@ -586,6 +597,7 @@ pub fn invoke_iiji(ctx: &EmEnv, index: i32, a1: i32, a2: i32, a3: i32, a4: i32) invoke!(ctx, dyn_call_iiji, dyn_call_iiji_ref, index, a1, a2, a3, a4) } +#[allow(clippy::too_many_arguments)] pub fn invoke_iiijj( ctx: &EmEnv, index: i32, @@ -645,6 +657,7 @@ pub fn invoke_viiij(ctx: &EmEnv, index: i32, a1: i32, a2: i32, a3: i32, a4: i32, a5 ) } +#[allow(clippy::too_many_arguments)] pub fn invoke_viiijiiii( ctx: &EmEnv, index: i32, @@ -675,6 +688,7 @@ pub fn invoke_viiijiiii( a9 ) } +#[allow(clippy::too_many_arguments)] pub fn invoke_viiijiiiiii( ctx: &EmEnv, index: i32, @@ -727,6 +741,7 @@ pub fn invoke_viiji(ctx: &EmEnv, index: i32, a1: i32, a2: i32, a3: i32, a4: i32, a5 ) } +#[allow(clippy::too_many_arguments)] pub fn invoke_viijiii( ctx: &EmEnv, index: i32, @@ -753,6 +768,7 @@ pub fn invoke_viijiii( a7 ) } +#[allow(clippy::too_many_arguments)] pub fn invoke_viijj(ctx: &EmEnv, index: i32, a1: i32, a2: i32, a3: i32, a4: i32, a5: i32, a6: i32) { debug!("emscripten::invoke_viijj"); invoke_no_stack_save!( @@ -794,6 +810,7 @@ pub fn invoke_viji(ctx: &EmEnv, index: i32, a1: i32, a2: i32, a3: i32, a4: i32) debug!("emscripten::invoke_viji"); invoke_no_stack_save!(ctx, dyn_call_viji, dyn_call_viji_ref, index, a1, a2, a3, a4) } +#[allow(clippy::too_many_arguments)] pub fn invoke_vijiii( ctx: &EmEnv, index: i32, @@ -854,6 +871,7 @@ pub fn invoke_viidii(ctx: &EmEnv, index: i32, a1: i32, a2: i32, a3: f64, a4: i32 a5 ); } +#[allow(clippy::too_many_arguments)] pub fn invoke_viidddddddd( ctx: &EmEnv, index: i32, diff --git a/lib/emscripten/src/lib.rs b/lib/emscripten/src/lib.rs index b509463cb5f..30e619a69c5 100644 --- a/lib/emscripten/src/lib.rs +++ b/lib/emscripten/src/lib.rs @@ -7,6 +7,10 @@ unused_unsafe, unreachable_patterns )] +// This allow attribute is ignored when placed directly on fields that also +// have a #[wasmer(...)] attribute. As a dirty workaround it is for now +// allowed for the whole library. +#![allow(clippy::type_complexity)] #![doc(html_favicon_url = "https://wasmer.io/images/icons/favicon-32x32.png")] #![doc(html_logo_url = "https://github.com/wasmerio.png?size=200")] @@ -394,7 +398,7 @@ fn store_module_arguments(ctx: &EmEnv, args: Vec<&str>) -> (u32, u32) { let mut args_slice = vec![0; argc]; for (slot, arg) in args_slice[0..argc].iter_mut().zip(args.iter()) { - *slot = unsafe { allocate_cstr_on_stack(ctx, &arg).0 }; + *slot = unsafe { allocate_cstr_on_stack(ctx, arg).0 }; } let (argv_offset, argv_slice): (_, &mut [u32]) = @@ -462,8 +466,8 @@ impl EmscriptenGlobals { } } - let (table_min, table_max) = get_emscripten_table_size(&module)?; - let (memory_min, memory_max, shared) = get_emscripten_memory_size(&module)?; + let (table_min, table_max) = get_emscripten_table_size(module)?; + let (memory_min, memory_max, shared) = get_emscripten_memory_size(module)?; // Memory initialization let memory_type = MemoryType::new(memory_min, memory_max, shared); @@ -488,7 +492,7 @@ impl EmscriptenGlobals { static_top += 16; let (dynamic_base, dynamictop_ptr) = - get_emscripten_metadata(&module)?.unwrap_or_else(|| { + get_emscripten_metadata(module)?.unwrap_or_else(|| { let dynamictop_ptr = static_alloc(&mut static_top, 4); ( align_memory(align_memory(static_top) + TOTAL_STACK), diff --git a/lib/emscripten/src/syscalls/unix.rs b/lib/emscripten/src/syscalls/unix.rs index c0c1855e12d..20518b052e3 100644 --- a/lib/emscripten/src/syscalls/unix.rs +++ b/lib/emscripten/src/syscalls/unix.rs @@ -452,10 +452,14 @@ pub fn ___syscall330(ctx: &EmEnv, _which: c_int, mut varargs: VarArgs) -> pid_t // Set flags on newfd (https://www.gnu.org/software/libc/manual/html_node/Descriptor-Flags.html) let mut old_flags = unsafe { fcntl(newfd, F_GETFD, 0) }; - if old_flags > 0 { - old_flags |= flags; - } else if old_flags == 0 { - old_flags &= !flags; + match old_flags { + f if f > 0 => { + old_flags |= flags; + } + 0 => { + old_flags &= !flags; + } + _ => {} } unsafe { diff --git a/lib/emscripten/src/time.rs b/lib/emscripten/src/time.rs index afb1049694f..d3efea6d520 100644 --- a/lib/emscripten/src/time.rs +++ b/lib/emscripten/src/time.rs @@ -317,12 +317,9 @@ pub fn _time(ctx: &EmEnv, time_p: u32) -> i32 { pub fn _ctime_r(ctx: &EmEnv, time_p: u32, buf: u32) -> u32 { debug!("emscripten::_ctime_r {} {}", time_p, buf); - // var stack = stackSave(); let (result_offset, _result_slice): (u32, &mut [u8]) = unsafe { allocate_on_stack(ctx, 44) }; let time = _localtime_r(ctx, time_p, result_offset) as u32; - let rv = _asctime_r(ctx, time, buf); - // stackRestore(stack); - rv + _asctime_r(ctx, time, buf) } pub fn _ctime(ctx: &EmEnv, time_p: u32) -> u32 { @@ -403,11 +400,11 @@ pub fn _strftime(ctx: &EmEnv, s_ptr: c_int, maxsize: u32, format_ptr: c_int, tm_ let tm = unsafe { &*tm }; let rust_date = time::Date::try_from_ymd(tm.tm_year, tm.tm_mon as u8, tm.tm_mday as u8); - if !rust_date.is_ok() { + if rust_date.is_err() { return 0; } let rust_time = time::Time::try_from_hms(tm.tm_hour as u8, tm.tm_min as u8, tm.tm_sec as u8); - if !rust_time.is_ok() { + if rust_time.is_err() { return 0; } let rust_datetime = time::PrimitiveDateTime::new(rust_date.unwrap(), rust_time.unwrap()); diff --git a/lib/emscripten/src/utils.rs b/lib/emscripten/src/utils.rs index 5ea2e99ad37..b535a1c9f3c 100644 --- a/lib/emscripten/src/utils.rs +++ b/lib/emscripten/src/utils.rs @@ -122,7 +122,9 @@ pub unsafe fn copy_cstr_into_wasm(ctx: &EmEnv, cstr: *const c_char) -> u32 { space_offset } -pub unsafe fn allocate_on_stack<'a, T: Copy>(ctx: &'a EmEnv, count: u32) -> (u32, &'a mut [T]) { +/// # Safety +/// This method is unsafe because it operates directly with the slice of memory represented by the address +pub unsafe fn allocate_on_stack(ctx: &EmEnv, count: u32) -> (u32, &mut [T]) { let offset = get_emscripten_data(ctx) .stack_alloc_ref() .unwrap() @@ -135,6 +137,8 @@ pub unsafe fn allocate_on_stack<'a, T: Copy>(ctx: &'a EmEnv, count: u32) -> (u32 (offset, slice) } +/// # Safety +/// This method is unsafe because it uses `allocate_on_stack` which is unsafe pub unsafe fn allocate_cstr_on_stack<'a>(ctx: &'a EmEnv, s: &str) -> (u32, &'a [u8]) { let (offset, slice) = allocate_on_stack(ctx, (s.len() + 1) as u32); diff --git a/lib/emscripten/src/varargs.rs b/lib/emscripten/src/varargs.rs index 4a9c886b046..e287d3b6767 100644 --- a/lib/emscripten/src/varargs.rs +++ b/lib/emscripten/src/varargs.rs @@ -17,12 +17,9 @@ impl VarArgs { unsafe { (ptr as *const T).read() } } - // pub fn getStr<'a>(&mut self, ctx: &mut Ctx) -> &'a CStr { pub fn get_str(&mut self, ctx: &EmEnv) -> *const c_char { let ptr_addr: u32 = self.get(ctx); - let ptr = emscripten_memory_pointer!(ctx.memory(0), ptr_addr) as *const c_char; - ptr - // unsafe { CStr::from_ptr(ptr) } + emscripten_memory_pointer!(ctx.memory(0), ptr_addr) as *const c_char } } diff --git a/lib/engine-dylib/src/artifact.rs b/lib/engine-dylib/src/artifact.rs index 0e2a204826a..a531d126c70 100644 --- a/lib/engine-dylib/src/artifact.rs +++ b/lib/engine-dylib/src/artifact.rs @@ -118,8 +118,9 @@ impl DylibArtifact { } } - #[cfg(feature = "compiler")] /// Generate a compilation + #[cfg(feature = "compiler")] + #[allow(clippy::type_complexity)] fn generate_metadata<'data>( data: &'data [u8], features: &Features, @@ -221,7 +222,7 @@ impl DylibArtifact { let serialized_data = metadata.serialize()?; let mut metadata_binary = vec![]; - metadata_binary.extend(MetadataHeader::new(serialized_data.len())); + metadata_binary.extend(MetadataHeader::new(serialized_data.len()).into_bytes()); metadata_binary.extend(serialized_data); let (compile_info, symbol_registry) = metadata.split(); @@ -361,10 +362,9 @@ impl DylibArtifact { // Get the location of the 'ld' linker for clang let fuse_linker = { let ld_install = which::which("ld"); - if ios_compile_target && ld_install.is_ok() { - ld_install.unwrap().into_os_string().into_string().unwrap() - } else { - "lld".to_string() + match (ios_compile_target, ld_install) { + (true, Ok(ld_install)) => ld_install.into_os_string().into_string().unwrap(), + _ => "lld".to_string(), } }; @@ -816,13 +816,7 @@ impl Artifact for DylibArtifact { // and the emitted size by the address map let ptr = function_pointer; let length = current_size_by_ptr; - let first = ( - index, - FunctionExtent { - ptr: *ptr, - length: length, - }, - ); + let first = (index, FunctionExtent { ptr: *ptr, length }); std::iter::once(first) .chain(iter.map(|(index, function_pointer)| { let fp = **function_pointer as usize; @@ -840,13 +834,7 @@ impl Artifact for DylibArtifact { // and the emitted size by the address map let ptr = function_pointer; let length = current_size_by_ptr; - ( - index, - FunctionExtent { - ptr: *ptr, - length: length, - }, - ) + (index, FunctionExtent { ptr: *ptr, length }) })) .collect::>() }) diff --git a/lib/engine-staticlib/src/artifact.rs b/lib/engine-staticlib/src/artifact.rs index 141e65659a0..9d98ce1e2a1 100644 --- a/lib/engine-staticlib/src/artifact.rs +++ b/lib/engine-staticlib/src/artifact.rs @@ -102,6 +102,7 @@ impl StaticlibArtifact { } #[cfg(feature = "compiler")] + #[allow(clippy::type_complexity)] /// Generate a compilation fn generate_metadata<'data>( data: &'data [u8], @@ -182,7 +183,7 @@ impl StaticlibArtifact { let mut metadata = ModuleMetadata { compile_info, - prefix: engine_inner.get_prefix(&data), + prefix: engine_inner.get_prefix(data), data_initializers, function_body_lengths, cpu_features: target.cpu_features().as_u64(), @@ -207,7 +208,7 @@ impl StaticlibArtifact { let serialized_data = bincode::serialize(&metadata).map_err(to_compile_error)?; let mut metadata_binary = vec![]; - metadata_binary.extend(MetadataHeader::new(serialized_data.len())); + metadata_binary.extend(MetadataHeader::new(serialized_data.len()).into_bytes()); metadata_binary.extend(serialized_data); let metadata_length = metadata_binary.len(); @@ -219,8 +220,8 @@ impl StaticlibArtifact { compile_info.module = Arc::new(module); let maybe_obj_bytes = compiler.experimental_native_compile_module( - &target, - &compile_info, + target, + compile_info, module_translation.as_ref().unwrap(), &function_body_inputs, &symbol_registry, @@ -231,7 +232,7 @@ impl StaticlibArtifact { obj_bytes? } else { let compilation = compiler.compile_module( - &target, + target, &metadata.compile_info, module_translation.as_ref().unwrap(), function_body_inputs, @@ -245,10 +246,10 @@ impl StaticlibArtifact { .map(|function_body| function_body.body.len() as u64) .collect::>(); */ - let mut obj = get_object_for_target(&target_triple).map_err(to_compile_error)?; + let mut obj = get_object_for_target(target_triple).map_err(to_compile_error)?; emit_data(&mut obj, WASMER_METADATA_SYMBOL, &metadata_binary, 1) .map_err(to_compile_error)?; - emit_compilation(&mut obj, compilation, &symbol_registry, &target_triple) + emit_compilation(&mut obj, compilation, &symbol_registry, target_triple) .map_err(to_compile_error)?; obj.write().map_err(to_compile_error)? }; @@ -344,7 +345,7 @@ impl StaticlibArtifact { for i in 0..num_imported_functions { let sig_idx = metadata.compile_info.module.functions[FunctionIndex::new(i)]; let func_type = &metadata.compile_info.module.signatures[sig_idx]; - let vm_shared_idx = signature_registry.register(&func_type); + let vm_shared_idx = signature_registry.register(func_type); sig_map.insert(sig_idx, vm_shared_idx); } // read finished functions in order now... @@ -353,7 +354,7 @@ impl StaticlibArtifact { let func_idx = metadata.compile_info.module.func_index(local_func_idx); let sig_idx = metadata.compile_info.module.functions[func_idx]; let func_type = &metadata.compile_info.module.signatures[sig_idx]; - let vm_shared_idx = signature_registry.register(&func_type); + let vm_shared_idx = signature_registry.register(func_type); sig_map.insert(sig_idx, vm_shared_idx); byte_buffer[0..WORD_SIZE] diff --git a/lib/engine-staticlib/src/engine.rs b/lib/engine-staticlib/src/engine.rs index ce73c2fdc43..70799fe294a 100644 --- a/lib/engine-staticlib/src/engine.rs +++ b/lib/engine-staticlib/src/engine.rs @@ -131,7 +131,7 @@ impl Engine for StaticlibEngine { binary: &[u8], tunables: &dyn Tunables, ) -> Result, CompileError> { - Ok(Arc::new(StaticlibArtifact::new(&self, binary, tunables)?)) + Ok(Arc::new(StaticlibArtifact::new(self, binary, tunables)?)) } /// Compile a WebAssembly binary (it will fail because the `compiler` flag is disabled). @@ -149,7 +149,7 @@ impl Engine for StaticlibEngine { /// Deserializes a WebAssembly module (binary content of a static object file) unsafe fn deserialize(&self, bytes: &[u8]) -> Result, DeserializeError> { - Ok(Arc::new(StaticlibArtifact::deserialize(&self, &bytes)?)) + Ok(Arc::new(StaticlibArtifact::deserialize(self, bytes)?)) } /// Deserializes a WebAssembly module from a path @@ -217,7 +217,7 @@ impl StaticlibEngineInner { #[cfg(feature = "compiler")] pub(crate) fn get_prefix(&self, bytes: &[u8]) -> String { if let Some(prefixer) = &self.prefixer { - prefixer(&bytes) + prefixer(bytes) } else { "".to_string() } @@ -230,13 +230,13 @@ impl StaticlibEngineInner { /// Validate the module #[cfg(feature = "compiler")] - pub fn validate<'data>(&self, data: &'data [u8]) -> Result<(), CompileError> { + pub fn validate(&self, data: &[u8]) -> Result<(), CompileError> { self.compiler()?.validate_module(self.features(), data) } /// Validate the module #[cfg(not(feature = "compiler"))] - pub fn validate<'data>(&self, _data: &'data [u8]) -> Result<(), CompileError> { + pub fn validate(&self, _data: &[u8]) -> Result<(), CompileError> { Err(CompileError::Validate( "The `StaticlibEngine` is not compiled with compiler support, which is required for validating".to_string(), )) diff --git a/lib/engine-universal/src/artifact.rs b/lib/engine-universal/src/artifact.rs index 8c25ff3af7b..32cba6b9d7a 100644 --- a/lib/engine-universal/src/artifact.rs +++ b/lib/engine-universal/src/artifact.rs @@ -124,7 +124,7 @@ impl UniversalArtifact { link_module( artifact.module_ref(), &finished_functions, - artifact.get_function_relocations().clone(), + artifact.get_function_relocations(), &custom_sections, artifact.get_custom_section_relocations_ref(), artifact.get_libcall_trampolines(), diff --git a/lib/engine-universal/src/code_memory.rs b/lib/engine-universal/src/code_memory.rs index 3d23e1eda5c..f2165f9444b 100644 --- a/lib/engine-universal/src/code_memory.rs +++ b/lib/engine-universal/src/code_memory.rs @@ -40,6 +40,7 @@ impl CodeMemory { } /// Allocate a single contiguous block of memory for the functions and custom sections, and copy the data in place. + #[allow(clippy::type_complexity)] pub fn allocate( &mut self, functions: &[&FunctionBody], @@ -188,7 +189,7 @@ impl CodeMemory { let padding = unwind_start - func_len; assert_eq!((func_len + padding) % 4, 0); let slice = remainder.split_at_mut(padding + unwind_size).0; - slice[padding..].copy_from_slice(&info); + slice[padding..].copy_from_slice(info); } if let Some(info) = &func.unwind_info { diff --git a/lib/engine-universal/src/engine.rs b/lib/engine-universal/src/engine.rs index 94236430240..f1676a9ffa8 100644 --- a/lib/engine-universal/src/engine.rs +++ b/lib/engine-universal/src/engine.rs @@ -113,7 +113,7 @@ impl Engine for UniversalEngine { binary: &[u8], tunables: &dyn Tunables, ) -> Result, CompileError> { - Ok(Arc::new(UniversalArtifact::new(&self, binary, tunables)?)) + Ok(Arc::new(UniversalArtifact::new(self, binary, tunables)?)) } /// Compile a WebAssembly binary @@ -131,7 +131,7 @@ impl Engine for UniversalEngine { /// Deserializes a WebAssembly module unsafe fn deserialize(&self, bytes: &[u8]) -> Result, DeserializeError> { - Ok(Arc::new(UniversalArtifact::deserialize(&self, &bytes)?)) + Ok(Arc::new(UniversalArtifact::deserialize(self, bytes)?)) } fn id(&self) -> &EngineId { @@ -167,7 +167,7 @@ impl UniversalEngineInner { } /// Validate the module - pub fn validate<'data>(&self, data: &'data [u8]) -> Result<(), CompileError> { + pub fn validate(&self, data: &[u8]) -> Result<(), CompileError> { self.builder.validate(data) } diff --git a/lib/engine/src/artifact.rs b/lib/engine/src/artifact.rs index 941c5b6ff0b..edd0af01183 100644 --- a/lib/engine/src/artifact.rs +++ b/lib/engine/src/artifact.rs @@ -62,10 +62,10 @@ pub trait Artifact: Send + Sync + Upcastable + ArtifactCreate { // host CPU features. let host_cpu_features = CpuFeature::for_host(); if !host_cpu_features.is_superset(self.cpu_features()) { - Err(InstantiationError::CpuFeature(format!( + return Err(InstantiationError::CpuFeature(format!( "{:?}", self.cpu_features().difference(host_cpu_features) - )))?; + ))); } self.preinstantiate()?; @@ -75,7 +75,7 @@ pub trait Artifact: Send + Sync + Upcastable + ArtifactCreate { let mut imports = resolve_imports( &module, imports, - &self.finished_dynamic_function_trampolines(), + self.finished_dynamic_function_trampolines(), self.memory_styles(), self.table_styles(), ) diff --git a/lib/engine/src/resolver.rs b/lib/engine/src/resolver.rs index f9ff20da99e..e78d16db888 100644 --- a/lib/engine/src/resolver.rs +++ b/lib/engine/src/resolver.rs @@ -75,7 +75,7 @@ pub fn resolve_imports( ImportError::UnknownImport(import_extern), )); }; - let export_extern = get_extern_from_export(module, &resolved); + let export_extern = get_extern_from_export(module, resolved); if !export_extern.is_compatible_with(&import_extern) { return Err(LinkError::Import( module_name.to_string(), diff --git a/lib/engine/src/trap/error.rs b/lib/engine/src/trap/error.rs index 9cbdda6f287..4a62f2eb0ec 100644 --- a/lib/engine/src/trap/error.rs +++ b/lib/engine/src/trap/error.rs @@ -16,7 +16,7 @@ pub struct RuntimeError { #[derive(Debug)] enum RuntimeErrorSource { Generic(String), - OOM, + OutOfMemory, User(Box), Trap(TrapCode), } @@ -26,7 +26,7 @@ impl fmt::Display for RuntimeErrorSource { match self { Self::Generic(s) => write!(f, "{}", s), Self::User(s) => write!(f, "{}", s), - Self::OOM => write!(f, "Wasmer VM out of memory"), + Self::OutOfMemory => write!(f, "Wasmer VM out of memory"), Self::Trap(s) => write!(f, "{}", s.message()), } } @@ -83,7 +83,7 @@ impl RuntimeError { } // A trap caused by the VM being Out of Memory Trap::OOM { backtrace } => { - Self::new_with_trace(&info, None, RuntimeErrorSource::OOM, backtrace) + Self::new_with_trace(&info, None, RuntimeErrorSource::OutOfMemory, backtrace) } // A trap caused by an error on the generated machine code for a Wasm function Trap::Wasm { @@ -138,7 +138,8 @@ impl RuntimeError { source: RuntimeErrorSource, native_trace: Backtrace, ) -> Self { - let frames: Vec = native_trace + // Let's construct the trace + let wasm_trace = native_trace .frames() .iter() .filter_map(|frame| { @@ -160,11 +161,6 @@ impl RuntimeError { Some(pc_to_lookup) } }) - .collect(); - - // Let's construct the trace - let wasm_trace = frames - .into_iter() .filter_map(|pc| info.lookup_frame_info(pc)) .collect::>(); diff --git a/lib/engine/src/trap/frame_info.rs b/lib/engine/src/trap/frame_info.rs index e5621ce36f5..44dd52d78e6 100644 --- a/lib/engine/src/trap/frame_info.rs +++ b/lib/engine/src/trap/frame_info.rs @@ -60,14 +60,14 @@ struct ModuleInfoFrameInfo { impl ModuleInfoFrameInfo { fn function_debug_info(&self, local_index: LocalFunctionIndex) -> &CompiledFunctionFrameInfo { - &self.frame_infos.get(local_index).unwrap() + self.frame_infos.get(local_index).unwrap() } /// Gets a function given a pc fn function_info(&self, pc: usize) -> Option<&FunctionInfo> { let (end, func) = self.functions.range(pc..).next()?; if func.start <= pc && pc <= *end { - return Some(func); + Some(func) } else { None } diff --git a/lib/engine/src/tunables.rs b/lib/engine/src/tunables.rs index 103c758c6ea..f07d5a78ba3 100644 --- a/lib/engine/src/tunables.rs +++ b/lib/engine/src/tunables.rs @@ -62,6 +62,9 @@ pub trait Tunables { } /// Allocate memory for just the memories of the current module. + /// + /// # Safety + /// - `memory_definition_locations` must point to a valid locations in VM memory. unsafe fn create_memories( &self, module: &ModuleInfo, @@ -71,13 +74,17 @@ pub trait Tunables { let num_imports = module.num_imported_memories; let mut memories: PrimaryMap = PrimaryMap::with_capacity(module.memories.len() - num_imports); - for index in num_imports..module.memories.len() { + for (index, mdl) in memory_definition_locations + .iter() + .enumerate() + .take(module.memories.len()) + .skip(num_imports) + { let mi = MemoryIndex::new(index); let ty = &module.memories[mi]; let style = &memory_styles[mi]; - let mdl = memory_definition_locations[index]; memories.push( - self.create_vm_memory(ty, style, mdl) + self.create_vm_memory(ty, style, *mdl) .map_err(|e| LinkError::Resource(format!("Failed to create memory: {}", e)))?, ); } @@ -85,6 +92,10 @@ pub trait Tunables { } /// Allocate memory for just the tables of the current module. + /// + /// # Safety + /// + /// To be done unsafe fn create_tables( &self, module: &ModuleInfo, @@ -94,13 +105,17 @@ pub trait Tunables { let num_imports = module.num_imported_tables; let mut tables: PrimaryMap = PrimaryMap::with_capacity(module.tables.len() - num_imports); - for index in num_imports..module.tables.len() { + for (index, tdl) in table_definition_locations + .iter() + .enumerate() + .take(module.tables.len()) + .skip(num_imports) + { let ti = TableIndex::new(index); let ty = &module.tables[ti]; let style = &table_styles[ti]; - let tdl = table_definition_locations[index]; tables.push( - self.create_vm_table(ty, style, tdl) + self.create_vm_table(ty, style, *tdl) .map_err(LinkError::Resource)?, ); } diff --git a/lib/object/src/module.rs b/lib/object/src/module.rs index cc196085125..13444234423 100644 --- a/lib/object/src/module.rs +++ b/lib/object/src/module.rs @@ -100,7 +100,7 @@ pub fn emit_data( flags: SymbolFlags::None, }); let section_id = obj.section_id(StandardSection::Data); - obj.add_symbol_data(symbol_id, section_id, &data, align); + obj.add_symbol_data(symbol_id, section_id, data, align); Ok(()) } @@ -150,7 +150,7 @@ pub fn emit_compilation( let custom_section_ids = custom_sections .into_iter() .map(|(section_index, custom_section)| { - if debug_index.map(|d| d == section_index).unwrap_or(false) { + if debug_index.map_or(false, |d| d == section_index) { // If this is the debug section let segment = obj.segment_name(StandardSegment::Debug).to_vec(); let section_id = @@ -264,7 +264,7 @@ pub fn emit_compilation( } for (section_index, relocations) in custom_section_relocations.into_iter() { - if !debug_index.map(|d| d == section_index).unwrap_or(false) { + if !debug_index.map_or(false, |d| d == section_index) { // Skip DWARF relocations just yet let (section_id, symbol_id) = custom_section_ids.get(section_index).unwrap(); all_relocations.push((*section_id, *symbol_id, relocations)); diff --git a/lib/types/src/archives.rs b/lib/types/src/archives.rs index a431aab1df1..f3887271d3c 100644 --- a/lib/types/src/archives.rs +++ b/lib/types/src/archives.rs @@ -15,24 +15,15 @@ impl From> for ArchivableIndexMap { fn from(it: IndexMap) -> Self { - let mut r = Self { - entries: Vec::new(), - }; - for (k, v) in it.into_iter() { - r.entries.push((k, v)); - } - r + let entries = it.into_iter().collect(); + Self { entries } } } -impl Into> - for ArchivableIndexMap +impl From> + for IndexMap { - fn into(self) -> IndexMap { - let mut r = IndexMap::new(); - for (k, v) in self.entries.into_iter() { - r.insert(k, v); - } - r + fn from(other: ArchivableIndexMap) -> Self { + other.entries.into_iter().collect() } } diff --git a/lib/types/src/entity/packed_option.rs b/lib/types/src/entity/packed_option.rs index 1e9bd8bfbd1..5ba5d8080bc 100644 --- a/lib/types/src/entity/packed_option.rs +++ b/lib/types/src/entity/packed_option.rs @@ -101,9 +101,9 @@ impl From> for PackedOption { } } -impl Into> for PackedOption { - fn into(self) -> Option { - self.expand() +impl From> for Option { + fn from(other: PackedOption) -> Self { + other.expand() } } diff --git a/lib/types/src/native.rs b/lib/types/src/native.rs index da7d719d0bc..45d7c8c3c6a 100644 --- a/lib/types/src/native.rs +++ b/lib/types/src/native.rs @@ -248,6 +248,8 @@ mod test_native_type { /// Trait for a Value type. A Value type is a type that is always valid and may /// be safely copied. /// +/// # Safety +/// /// To maintain safety, types which implement this trait must be valid for all /// bit patterns. This means that it cannot contain enums, `bool`, references, /// etc. diff --git a/lib/types/src/trapcode.rs b/lib/types/src/trapcode.rs index 0497744b71b..64a6d5fab63 100644 --- a/lib/types/src/trapcode.rs +++ b/lib/types/src/trapcode.rs @@ -111,18 +111,18 @@ impl FromStr for TrapCode { fn from_str(s: &str) -> Result { match s { - "stk_ovf" => Ok(TrapCode::StackOverflow), - "heap_get_oob" => Ok(TrapCode::HeapAccessOutOfBounds), - "heap_misaligned" => Ok(TrapCode::HeapMisaligned), - "table_get_oob" => Ok(TrapCode::TableAccessOutOfBounds), - "oob" => Ok(TrapCode::OutOfBounds), - "icall_null" => Ok(TrapCode::IndirectCallToNull), - "bad_sig" => Ok(TrapCode::BadSignature), - "int_ovf" => Ok(TrapCode::IntegerOverflow), - "int_divz" => Ok(TrapCode::IntegerDivisionByZero), - "bad_toint" => Ok(TrapCode::BadConversionToInteger), - "unreachable" => Ok(TrapCode::UnreachableCodeReached), - "unalign_atom" => Ok(TrapCode::UnalignedAtomic), + "stk_ovf" => Ok(Self::StackOverflow), + "heap_get_oob" => Ok(Self::HeapAccessOutOfBounds), + "heap_misaligned" => Ok(Self::HeapMisaligned), + "table_get_oob" => Ok(Self::TableAccessOutOfBounds), + "oob" => Ok(Self::OutOfBounds), + "icall_null" => Ok(Self::IndirectCallToNull), + "bad_sig" => Ok(Self::BadSignature), + "int_ovf" => Ok(Self::IntegerOverflow), + "int_divz" => Ok(Self::IntegerDivisionByZero), + "bad_toint" => Ok(Self::BadConversionToInteger), + "unreachable" => Ok(Self::UnreachableCodeReached), + "unalign_atom" => Ok(Self::UnalignedAtomic), _ => Err(()), } } diff --git a/lib/types/src/values.rs b/lib/types/src/values.rs index 66669fd2aba..ada2ab16935 100644 --- a/lib/types/src/values.rs +++ b/lib/types/src/values.rs @@ -65,9 +65,16 @@ macro_rules! accessors { /// between the API and the VM internals, specifically with `wasmer_types::Value`. pub trait WasmValueType: std::fmt::Debug + 'static { /// Write the value + /// + /// # Safety + /// You shouldn't use this method directly as it writes the value to a mutable pointer. unsafe fn write_value_to(&self, p: *mut i128); /// read the value + /// + /// # Safety + /// It reads the value directly from a memory pointer, you need to make sure is not corrupted + // // TODO(reftypes): passing the store as `dyn Any` is a hack to work around the // structure of our crates. We need to talk about the store in the rest of the // VM (for example where this method is used) but cannot do so. Fixing this diff --git a/lib/types/src/vmoffsets.rs b/lib/types/src/vmoffsets.rs index d6b63543440..3695d7ca82d 100644 --- a/lib/types/src/vmoffsets.rs +++ b/lib/types/src/vmoffsets.rs @@ -420,6 +420,7 @@ impl VMOffsets { } /// Return the size of `VMFuncRef`. + #[allow(clippy::identity_op)] pub const fn size_of_vm_funcref(&self) -> u8 { 1 * self.pointer_size } diff --git a/lib/universal-artifact/src/artifact.rs b/lib/universal-artifact/src/artifact.rs index 82bf96bb186..5ceb2fd7bb2 100644 --- a/lib/universal-artifact/src/artifact.rs +++ b/lib/universal-artifact/src/artifact.rs @@ -224,7 +224,7 @@ impl ArtifactCreate for UniversalArtifactBuild { let mut metadata_binary = vec![]; metadata_binary.extend(Self::MAGIC_HEADER); - metadata_binary.extend(MetadataHeader::new(serialized_data.len())); + metadata_binary.extend(MetadataHeader::new(serialized_data.len()).into_bytes()); metadata_binary.extend(serialized_data); Ok(metadata_binary) } diff --git a/lib/universal-artifact/src/engine.rs b/lib/universal-artifact/src/engine.rs index 81ed68e1b8b..573e8762621 100644 --- a/lib/universal-artifact/src/engine.rs +++ b/lib/universal-artifact/src/engine.rs @@ -17,7 +17,7 @@ impl UniversalEngineBuilder { /// Create a new builder with pre-made components #[cfg(feature = "compiler")] pub fn new(compiler: Option>, features: Features) -> Self { - UniversalEngineBuilder { compiler, features } + Self { compiler, features } } /// Gets the compiler associated to this engine. @@ -41,7 +41,7 @@ impl UniversalEngineBuilder { /// Validate the module #[cfg(feature = "compiler")] - pub fn validate<'data>(&self, data: &'data [u8]) -> Result<(), CompileError> { + pub fn validate(&self, data: &[u8]) -> Result<(), CompileError> { self.compiler()?.validate_module(self.features(), data) } diff --git a/lib/universal-artifact/src/lib.rs b/lib/universal-artifact/src/lib.rs index 952d6d3bd84..d3843a5882e 100644 --- a/lib/universal-artifact/src/lib.rs +++ b/lib/universal-artifact/src/lib.rs @@ -12,8 +12,7 @@ clippy::float_arithmetic, clippy::mut_mut, clippy::nonminimal_bool, - clippy::option_map_unwrap_or, - clippy::option_map_unwrap_or_else, + clippy::map_unwrap_or, clippy::print_stdout, clippy::unicode_not_nfc, clippy::use_self diff --git a/lib/universal-artifact/src/serialize.rs b/lib/universal-artifact/src/serialize.rs index 8ac1b603367..8bfc40db69b 100644 --- a/lib/universal-artifact/src/serialize.rs +++ b/lib/universal-artifact/src/serialize.rs @@ -81,9 +81,9 @@ impl SerializableModule { /// /// This method is unsafe. /// Please check `SerializableModule::deserialize` for more details. - unsafe fn archive_from_slice<'a>( - metadata_slice: &'a [u8], - ) -> Result<&'a ArchivedSerializableModule, DeserializeError> { + unsafe fn archive_from_slice( + metadata_slice: &[u8], + ) -> Result<&ArchivedSerializableModule, DeserializeError> { if metadata_slice.len() < 8 { return Err(DeserializeError::Incompatible( "invalid serialized data".into(), @@ -92,7 +92,7 @@ impl SerializableModule { let mut pos: [u8; 8] = Default::default(); pos.copy_from_slice(&metadata_slice[metadata_slice.len() - 8..metadata_slice.len()]); let pos: u64 = u64::from_le_bytes(pos); - Ok(archived_value::( + Ok(archived_value::( &metadata_slice[..metadata_slice.len() - 8], pos as usize, )) diff --git a/lib/vm/src/func_data_registry.rs b/lib/vm/src/func_data_registry.rs index 4ea8d36c0c7..ddf4eb7e6b8 100644 --- a/lib/vm/src/func_data_registry.rs +++ b/lib/vm/src/func_data_registry.rs @@ -9,7 +9,7 @@ use std::collections::HashMap; use std::sync::Mutex; /// The registry that holds the values that `VMFuncRef`s point to. -#[derive(Debug)] +#[derive(Debug, Default)] pub struct FuncDataRegistry { // This structure is stored in an `Engine` and is intended to be shared // across many instances. Ideally instances can themselves be sent across @@ -88,31 +88,29 @@ unsafe impl Sync for VMFuncRef {} #[derive(Debug, Default)] struct Inner { - func_data: Vec>, + func_data: Vec, anyfunc_to_index: HashMap, } impl FuncDataRegistry { /// Create a new `FuncDataRegistry`. pub fn new() -> Self { - Self { - inner: Default::default(), - } + Default::default() } /// Register a signature and return its unique index. pub fn register(&self, anyfunc: VMCallerCheckedAnyfunc) -> VMFuncRef { let mut inner = self.inner.lock().unwrap(); if let Some(&idx) = inner.anyfunc_to_index.get(&anyfunc) { - let data: &Box<_> = &inner.func_data[idx]; + let data: &_ = &inner.func_data[idx]; let inner_ptr: &VMCallerCheckedAnyfunc = &*data; VMFuncRef(inner_ptr) } else { let idx = inner.func_data.len(); - inner.func_data.push(Box::new(anyfunc.clone())); + inner.func_data.push(anyfunc); inner.anyfunc_to_index.insert(anyfunc, idx); - let data: &Box<_> = &inner.func_data[idx]; + let data: &_ = &inner.func_data[idx]; let inner_ptr: &VMCallerCheckedAnyfunc = &*data; VMFuncRef(inner_ptr) } diff --git a/lib/vm/src/instance/mod.rs b/lib/vm/src/instance/mod.rs index 837bb3bfcf9..c224b0ff4c7 100644 --- a/lib/vm/src/instance/mod.rs +++ b/lib/vm/src/instance/mod.rs @@ -33,7 +33,7 @@ use more_asserts::assert_lt; use std::any::Any; use std::cell::RefCell; use std::collections::HashMap; -use std::convert::{TryFrom, TryInto}; +use std::convert::TryFrom; use std::ffi; use std::fmt; use std::mem; @@ -1054,7 +1054,7 @@ impl InstanceHandle { pub fn lookup(&self, field: &str) -> Option { let export = self.module_ref().exports.get(field)?; - Some(self.lookup_by_declaration(&export)) + Some(self.lookup_by_declaration(export)) } /// Lookup an export with the given export declaration. @@ -1289,7 +1289,7 @@ unsafe fn get_memory_slice<'instance>( let import = instance.imported_memory(init.location.memory_index); *import.definition.as_ref() }; - slice::from_raw_parts_mut(memory.base, memory.current_length.try_into().unwrap()) + slice::from_raw_parts_mut(memory.base, memory.current_length) } /// Compute the offset for a table element initializer. @@ -1377,7 +1377,7 @@ fn initialize_memories( let start = get_memory_init_start(init, instance); if start .checked_add(init.data.len()) - .map_or(true, |end| end > memory.current_length.try_into().unwrap()) + .map_or(true, |end| end > memory.current_length) { return Err(Trap::lib(TrapCode::HeapAccessOutOfBounds)); } diff --git a/lib/vm/src/lib.rs b/lib/vm/src/lib.rs index 1da5a855bd3..03bc0330d03 100644 --- a/lib/vm/src/lib.rs +++ b/lib/vm/src/lib.rs @@ -5,7 +5,7 @@ #![warn(unused_import_braces)] #![cfg_attr( feature = "cargo-clippy", - allow(clippy::new_without_default, vtable_address_comparisons) + allow(clippy::new_without_default, clippy::vtable_address_comparisons) )] #![cfg_attr( feature = "cargo-clippy", diff --git a/lib/vm/src/memory.rs b/lib/vm/src/memory.rs index 422c63d58e0..b10a15e9a35 100644 --- a/lib/vm/src/memory.rs +++ b/lib/vm/src/memory.rs @@ -210,7 +210,7 @@ impl LinearMemory { }; let base_ptr = mmap.alloc.as_mut_ptr(); - let mem_length = memory.minimum.bytes().0.try_into().unwrap(); + let mem_length = memory.minimum.bytes().0; Ok(Self { mmap: Mutex::new(mmap), maximum: memory.maximum, @@ -255,7 +255,7 @@ impl Memory for LinearMemory { /// Returns the type for this memory. fn ty(&self) -> MemoryType { let minimum = self.size(); - let mut out = self.memory.clone(); + let mut out = self.memory; out.minimum = minimum; out @@ -353,7 +353,7 @@ impl Memory for LinearMemory { unsafe { let mut md_ptr = self.get_vm_memory_definition(); let md = md_ptr.as_mut(); - md.current_length = new_pages.bytes().0.try_into().unwrap(); + md.current_length = new_pages.bytes().0; md.base = mmap.alloc.as_mut_ptr() as _; } diff --git a/lib/vm/src/sig_registry.rs b/lib/vm/src/sig_registry.rs index 58b690fc6b7..121c808b846 100644 --- a/lib/vm/src/sig_registry.rs +++ b/lib/vm/src/sig_registry.rs @@ -15,7 +15,7 @@ use wasmer_types::FunctionType; /// call must match. To implement this efficiently, keep a registry of all /// signatures, shared by all instances, so that call sites can just do an /// index comparison. -#[derive(Debug)] +#[derive(Debug, Default)] pub struct SignatureRegistry { // This structure is stored in an `Engine` and is intended to be shared // across many instances. Ideally instances can themselves be sent across @@ -34,9 +34,7 @@ struct Inner { impl SignatureRegistry { /// Create a new `SignatureRegistry`. pub fn new() -> Self { - Self { - inner: Default::default(), - } + Default::default() } /// Register a signature and return its unique index. diff --git a/lib/vm/src/table.rs b/lib/vm/src/table.rs index 9df6f1e19e1..b6b00685644 100644 --- a/lib/vm/src/table.rs +++ b/lib/vm/src/table.rs @@ -318,11 +318,12 @@ impl Table for LinearTable { let element = match init_value { TableElement::ExternRef(extern_ref) => { let extern_ref: VMExternRef = extern_ref.into(); + // We reduce the amount we increment by because `into` prevents // dropping `init_value` (which is a caller-inc'd ref). - (new_len as usize) - .checked_sub(size as usize + 1) - .map(|val| extern_ref.ref_inc_by(val)); + if let Some(val) = (new_len as usize).checked_sub(size as usize + 1) { + extern_ref.ref_inc_by(val) + } RawTableElement { extern_ref } } TableElement::FuncRef(func_ref) => RawTableElement { func_ref }, diff --git a/lib/vm/src/trap/mod.rs b/lib/vm/src/trap/mod.rs index ca764576ba4..afa81642a45 100644 --- a/lib/vm/src/trap/mod.rs +++ b/lib/vm/src/trap/mod.rs @@ -3,6 +3,8 @@ //! This is the module that facilitates the usage of Traps //! in Wasmer Runtime + +#[allow(clippy::module_inception)] mod trap; mod traphandlers; diff --git a/lib/vm/src/trap/trap.rs b/lib/vm/src/trap/trap.rs index fdb20d3f590..0934364b024 100644 --- a/lib/vm/src/trap/trap.rs +++ b/lib/vm/src/trap/trap.rs @@ -44,7 +44,7 @@ impl Trap { /// /// Internally saves a backtrace when constructed. pub fn wasm(pc: usize, backtrace: Backtrace, signal_trap: Option) -> Self { - Trap::Wasm { + Self::Wasm { pc, backtrace, signal_trap, @@ -56,7 +56,7 @@ impl Trap { /// Internally saves a backtrace when constructed. pub fn lib(trap_code: TrapCode) -> Self { let backtrace = Backtrace::new_unresolved(); - Trap::Lib { + Self::Lib { trap_code, backtrace, } @@ -67,6 +67,6 @@ impl Trap { /// Internally saves a backtrace when constructed. pub fn oom() -> Self { let backtrace = Backtrace::new_unresolved(); - Trap::OOM { backtrace } + Self::OOM { backtrace } } } diff --git a/lib/vm/src/trap/traphandlers.rs b/lib/vm/src/trap/traphandlers.rs index b076a9c715a..21b26782950 100644 --- a/lib/vm/src/trap/traphandlers.rs +++ b/lib/vm/src/trap/traphandlers.rs @@ -90,6 +90,8 @@ unsafe fn process_illegal_op(addr: usize) -> Option { /// A package of functionality needed by `catch_traps` to figure out what to do /// when handling a trap. /// +/// # Safety +/// /// Note that this is an `unsafe` trait at least because it's being run in the /// context of a synchronous signal handler, so it needs to be careful to not /// access too much state in answering these queries. @@ -625,6 +627,8 @@ pub unsafe fn wasmer_call_trampoline( /// Catches any wasm traps that happen within the execution of `closure`, /// returning them as a `Result`. /// +/// # Safety +/// /// Highly unsafe since `closure` won't have any dtors run. pub unsafe fn catch_traps( trap_handler: &(dyn TrapHandler + 'static), @@ -636,7 +640,7 @@ where // Ensure that per-thread initialization is done. lazy_per_thread_init()?; - on_wasm_stack(trap_handler, closure).map_err(UnwindReason::to_trap) + on_wasm_stack(trap_handler, closure).map_err(UnwindReason::into_trap) } // We need two separate thread-local variables here: @@ -654,6 +658,7 @@ thread_local! { /// Read-only information that is used by signal handlers to handle and recover /// from traps. +#[allow(clippy::type_complexity)] struct TrapHandlerContext { inner: *const u8, handle_trap: fn( @@ -700,7 +705,7 @@ impl TrapHandlerContext { } } let inner = TrapHandlerContextInner { coro_trap_handler }; - let ctx = TrapHandlerContext { + let ctx = Self { inner: &inner as *const _ as *const u8, handle_trap: func::, custom_trap, @@ -709,10 +714,7 @@ impl TrapHandlerContext { compiler_fence(Ordering::Release); let prev = TRAP_HANDLER.with(|ptr| { let prev = ptr.load(Ordering::Relaxed); - ptr.store( - &ctx as *const TrapHandlerContext as *mut TrapHandlerContext, - Ordering::Relaxed, - ); + ptr.store(&ctx as *const Self as *mut Self, Ordering::Relaxed); prev }); @@ -824,7 +826,7 @@ enum UnwindReason { } impl UnwindReason { - fn to_trap(self) -> Trap { + fn into_trap(self) -> Trap { match self { UnwindReason::UserTrap(data) => Trap::User(data), UnwindReason::LibTrap(trap) => trap, @@ -964,7 +966,7 @@ pub fn lazy_per_thread_init() -> Result<(), Trap> { const MIN_STACK_SIZE: usize = 16 * 4096; enum Tls { - OOM, + OutOfMemory, Allocated { mmap_ptr: *mut libc::c_void, mmap_size: usize, @@ -997,7 +999,7 @@ pub fn lazy_per_thread_init() -> Result<(), Trap> { 0, ); if ptr == libc::MAP_FAILED { - return Tls::OOM; + return Tls::OutOfMemory; } // Prepare the stack with readable/writable memory and then register it @@ -1026,7 +1028,7 @@ pub fn lazy_per_thread_init() -> Result<(), Trap> { // Ensure TLS runs its initializer and return an error if it failed to // set up a separate stack for signal handlers. return TLS.with(|tls| { - if let Tls::OOM = tls { + if let Tls::OutOfMemory = tls { Err(Trap::oom()) } else { Ok(()) diff --git a/lib/wasi-experimental-io-devices/src/lib.rs b/lib/wasi-experimental-io-devices/src/lib.rs index 7c85358d818..66b910bf7db 100644 --- a/lib/wasi-experimental-io-devices/src/lib.rs +++ b/lib/wasi-experimental-io-devices/src/lib.rs @@ -239,9 +239,9 @@ impl Read for FrameBuffer { FrameBufferFileType::Buffer => { let mut bytes_copied = 0; - for i in 0..buf.len() { + for (i, b) in buf.iter_mut().enumerate() { if let Some(byte) = fb_state.get_byte(cursor + i) { - buf[i] = byte; + *b = byte; bytes_copied += 1; } else { break; @@ -257,8 +257,8 @@ impl Read for FrameBuffer { let mut bytes = resolution_data.bytes().skip(cursor); let bytes_to_copy = std::cmp::min(buf.len(), bytes.clone().count()); - for i in 0..bytes_to_copy { - buf[i] = bytes.next().unwrap(); + for byte in buf.iter_mut().take(bytes_to_copy) { + *byte = bytes.next().unwrap(); } self.cursor += bytes_to_copy as u32; diff --git a/lib/wasi-experimental-io-devices/src/util.rs b/lib/wasi-experimental-io-devices/src/util.rs index 1b6107505e3..19eee26b4d4 100644 --- a/lib/wasi-experimental-io-devices/src/util.rs +++ b/lib/wasi-experimental-io-devices/src/util.rs @@ -40,24 +40,16 @@ pub fn bytes_for_input_event(input_event: InputEvent) -> (u8, [u8; 8], usize) { MouseButton::Middle => MOUSE_PRESS_MIDDLE, }; let x_bytes = x.to_le_bytes(); - for i in 0..4 { - data[i] = x_bytes[i]; - } + data[..4].clone_from_slice(&x_bytes[..4]); let y_bytes = y.to_le_bytes(); - for i in 0..4 { - data[i + 4] = y_bytes[i]; - } + data[4..8].clone_from_slice(&y_bytes[..4]); (tag, data, 8) } InputEvent::MouseMoved(x, y) => { let x_bytes = x.to_le_bytes(); - for i in 0..4 { - data[i] = x_bytes[i]; - } + data[..4].clone_from_slice(&x_bytes[..4]); let y_bytes = y.to_le_bytes(); - for i in 0..4 { - data[i + 4] = y_bytes[i]; - } + data[4..8].clone_from_slice(&y_bytes[..4]); (MOUSE_MOVE, data, 8) } InputEvent::WindowClosed => (WINDOW_CLOSED, data, 0), diff --git a/lib/wasi-types/src/directory.rs b/lib/wasi-types/src/directory.rs index 71601821e1a..d43b709f61f 100644 --- a/lib/wasi-types/src/directory.rs +++ b/lib/wasi-types/src/directory.rs @@ -15,25 +15,46 @@ pub struct __wasi_dirent_t { } pub fn dirent_to_le_bytes(ent: &__wasi_dirent_t) -> Vec { - use mem::transmute; + let out: Vec = std::iter::empty() + .chain(ent.d_next.to_le_bytes()) + .chain(ent.d_ino.to_le_bytes()) + .chain(ent.d_namlen.to_le_bytes()) + .chain(u32::from(ent.d_type).to_le_bytes()) + .collect(); - let mut out = Vec::with_capacity(mem::size_of::<__wasi_dirent_t>()); - let bytes: [u8; 8] = unsafe { transmute(ent.d_next.to_le()) }; - for &b in &bytes { - out.push(b); - } - let bytes: [u8; 8] = unsafe { transmute(ent.d_ino.to_le()) }; - for &b in &bytes { - out.push(b); - } - let bytes: [u8; 4] = unsafe { transmute(ent.d_namlen.to_le()) }; - for &b in &bytes { - out.push(b); - } - out.push(ent.d_type); - out.push(0); - out.push(0); - out.push(0); assert_eq!(out.len(), mem::size_of::<__wasi_dirent_t>()); out } + +#[cfg(test)] +mod tests { + use super::{__wasi_dirent_t, dirent_to_le_bytes}; + + #[test] + fn test_dirent_to_le_bytes() { + let s = __wasi_dirent_t { + d_next: 0x0123456789abcdef, + d_ino: 0xfedcba9876543210, + d_namlen: 0xaabbccdd, + d_type: 0x99, + }; + + assert_eq!( + vec![ + // d_next + 0xef, 0xcd, 0xab, 0x89, 0x67, 0x45, 0x23, 0x01, + // + // d_ino + 0x10, 0x32, 0x54, 0x76, 0x98, 0xba, 0xdc, 0xfe, + // + // d_namelen + 0xdd, 0xcc, 0xbb, 0xaa, + // + // d_type + // plus padding + 0x99, 0x00, 0x00, 0x00, + ], + dirent_to_le_bytes(&s) + ); + } +} diff --git a/lib/wasi/src/state/builder.rs b/lib/wasi/src/state/builder.rs index ec437b7a5b1..37bf5c9d37b 100644 --- a/lib/wasi/src/state/builder.rs +++ b/lib/wasi/src/state/builder.rs @@ -401,10 +401,7 @@ impl WasiStateBuilder { } } - let fs_backing = self - .fs_override - .take() - .unwrap_or_else(|| default_fs_backing()); + let fs_backing = self.fs_override.take().unwrap_or_else(default_fs_backing); // self.preopens are checked in [`PreopenDirBuilder::build`] let mut wasi_fs = WasiFs::new_with_preopen(&self.preopens, &self.vfs_preopens, fs_backing) @@ -441,9 +438,9 @@ impl WasiStateBuilder { .iter() .map(|(key, value)| { let mut env = Vec::with_capacity(key.len() + value.len() + 1); - env.extend_from_slice(&key); + env.extend_from_slice(key); env.push(b'='); - env.extend_from_slice(&value); + env.extend_from_slice(value); env }) diff --git a/lib/wasi/src/state/mod.rs b/lib/wasi/src/state/mod.rs index a8e1d0b30e1..10212563715 100644 --- a/lib/wasi/src/state/mod.rs +++ b/lib/wasi/src/state/mod.rs @@ -287,13 +287,10 @@ impl WasiFs { &path.to_string_lossy(), &alias ); - let cur_dir_metadata = wasi_fs.fs_backing.metadata(path).map_err(|e| { - format!( - "Could not get metadata for file {:?}: {}", - path, - e.to_string() - ) - })?; + let cur_dir_metadata = wasi_fs + .fs_backing + .metadata(path) + .map_err(|e| format!("Could not get metadata for file {:?}: {}", path, e))?; let kind = if cur_dir_metadata.is_dir() { Kind::Dir { @@ -1189,12 +1186,11 @@ impl WasiFs { let inode = &mut self.inodes[fd.inode]; match &mut inode.kind { - Kind::File { handle, .. } => { - if let Some(file) = handle { - file.flush().map_err(|_| __WASI_EIO)? - } else { - return Err(__WASI_EIO); - } + Kind::File { + handle: Some(file), .. + } => file.flush().map_err(|_| __WASI_EIO)?, + Kind::File { handle: None, .. } => { + return Err(__WASI_EIO); } // TODO: verify this behavior Kind::Dir { .. } => return Err(__WASI_EISDIR), diff --git a/lib/wasi/src/state/types.rs b/lib/wasi/src/state/types.rs index 5276de8d364..f20e92efcd7 100644 --- a/lib/wasi/src/state/types.rs +++ b/lib/wasi/src/state/types.rs @@ -72,6 +72,7 @@ pub fn fs_error_into_wasi_err(fs_error: FsError) -> __wasi_errno_t { } #[derive(Debug, Clone)] +#[allow(clippy::enum_variant_names)] pub enum PollEvent { /// Data available to read PollIn = 1, diff --git a/lib/wasi/src/syscalls/mod.rs b/lib/wasi/src/syscalls/mod.rs index 94a69f8cd7b..fa87402614f 100644 --- a/lib/wasi/src/syscalls/mod.rs +++ b/lib/wasi/src/syscalls/mod.rs @@ -126,7 +126,7 @@ fn write_buffer_array( let data = wasi_try_mem!(new_ptr.slice(memory, sub_buffer.len() as u32)); wasi_try_mem!(data.write_slice(sub_buffer)); - wasi_try_mem!(wasi_try_mem!(new_ptr.add(sub_buffer.len() as u32)).write(memory, 0)); + wasi_try_mem!(wasi_try_mem!(new_ptr.add_offset(sub_buffer.len() as u32)).write(memory, 0)); current_buffer_offset += sub_buffer.len() as u32 + 1; } @@ -1051,8 +1051,8 @@ pub fn fd_readdir( buf_len as usize - buf_idx, std::mem::size_of::<__wasi_dirent_t>(), ); - for i in 0..upper_limit { - wasi_try_mem!(buf_arr.index((i + buf_idx) as u64).write(dirent_bytes[i])); + for (i, b) in dirent_bytes.iter().enumerate().take(upper_limit) { + wasi_try_mem!(buf_arr.index((i + buf_idx) as u64).write(*b)); } buf_idx += upper_limit; if upper_limit != std::mem::size_of::<__wasi_dirent_t>() { diff --git a/tests/lib/engine-dummy/src/artifact.rs b/tests/lib/engine-dummy/src/artifact.rs index b9ac06f970d..4d6cbd5b400 100644 --- a/tests/lib/engine-dummy/src/artifact.rs +++ b/tests/lib/engine-dummy/src/artifact.rs @@ -105,7 +105,7 @@ impl DummyArtifact { table_styles, cpu_features: engine.target().cpu_features().as_u64(), }; - Self::from_parts(&engine, metadata) + Self::from_parts(engine, metadata) } #[cfg(not(feature = "compiler"))] @@ -127,7 +127,7 @@ impl DummyArtifact { let metadata: DummyArtifactMetadata = bincode::deserialize(inner_bytes) .map_err(|e| DeserializeError::CorruptedBinary(format!("{:?}", e)))?; - Self::from_parts(&engine, metadata).map_err(DeserializeError::Compiler) + Self::from_parts(engine, metadata).map_err(DeserializeError::Compiler) } #[cfg(not(feature = "serialize"))] diff --git a/tests/lib/engine-dummy/src/engine.rs b/tests/lib/engine-dummy/src/engine.rs index b7e4423f764..831049e68b0 100644 --- a/tests/lib/engine-dummy/src/engine.rs +++ b/tests/lib/engine-dummy/src/engine.rs @@ -21,6 +21,7 @@ extern "C" fn dummy_trampoline( /// A WebAssembly `Dummy` Engine. #[derive(Clone)] +#[cfg_attr(feature = "compiler", derive(Default))] pub struct DummyEngine { signatures: Arc, func_data: Arc, @@ -32,13 +33,7 @@ pub struct DummyEngine { impl DummyEngine { #[cfg(feature = "compiler")] pub fn new() -> Self { - Self { - signatures: Arc::new(SignatureRegistry::new()), - func_data: Arc::new(FuncDataRegistry::new()), - features: Arc::new(Default::default()), - target: Arc::new(Default::default()), - engine_id: EngineId::default(), - } + Default::default() } pub fn features(&self) -> &Features { @@ -116,12 +111,12 @@ impl Engine for DummyEngine { binary: &[u8], tunables: &dyn Tunables, ) -> Result, CompileError> { - Ok(Arc::new(DummyArtifact::new(&self, binary, tunables)?)) + Ok(Arc::new(DummyArtifact::new(self, binary, tunables)?)) } /// Deserializes a WebAssembly module (binary content of a Shared Object file) unsafe fn deserialize(&self, bytes: &[u8]) -> Result, DeserializeError> { - Ok(Arc::new(DummyArtifact::deserialize(&self, &bytes)?)) + Ok(Arc::new(DummyArtifact::deserialize(self, bytes)?)) } fn id(&self) -> &EngineId { diff --git a/tests/lib/wast/src/wasi_wast.rs b/tests/lib/wast/src/wasi_wast.rs index f0f260b0f73..b01bc70672a 100644 --- a/tests/lib/wast/src/wasi_wast.rs +++ b/tests/lib/wast/src/wasi_wast.rs @@ -1,7 +1,7 @@ use anyhow::Context; use std::fs::{read_dir, File, OpenOptions, ReadDir}; use std::io::{self, Read, Seek, Write}; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use wasmer::{Imports, Instance, Module, Store}; use wasmer_vfs::{host_fs, mem_fs, FileSystem}; use wasmer_wasi::types::{__wasi_filesize_t, __wasi_timestamp_t}; @@ -95,7 +95,7 @@ impl<'a> WasiTest<'a> { wasm_module.read_to_end(&mut out)?; out }; - let module = Module::new(&store, &wasm_bytes)?; + let module = Module::new(store, &wasm_bytes)?; let (env, _tempdirs) = self.create_wasi_env(filesystem_kind)?; let imports = self.get_imports(store, &module, env.clone())?; let instance = Instance::new(&module, &imports)?; @@ -620,14 +620,13 @@ impl VirtualFile for OutputCapturerer { fn map_host_fs_to_mem_fs( fs: &mem_fs::FileSystem, directory_reader: ReadDir, - path_prefix: &PathBuf, + path_prefix: &Path, ) -> anyhow::Result<()> { for entry in directory_reader { let entry = entry?; let entry_type = entry.file_type()?; - let mut path = path_prefix.clone(); - path.push(entry.path().file_name().unwrap()); + let path = path_prefix.join(entry.path().file_name().unwrap()); if entry_type.is_dir() { fs.create_dir(&path)?; diff --git a/tests/lib/wast/src/wast.rs b/tests/lib/wast/src/wast.rs index d391bf0c633..9b21b8bd3fe 100644 --- a/tests/lib/wast/src/wast.rs +++ b/tests/lib/wast/src/wast.rs @@ -209,7 +209,7 @@ impl Wast { Err(e) => e, }; let error_message = format!("{:?}", err); - if !Self::matches_message_assert_invalid(&message, &error_message) { + if !Self::matches_message_assert_invalid(message, &error_message) { bail!( "assert_invalid: expected \"{}\", got \"{}\"", message, @@ -250,7 +250,7 @@ impl Wast { Err(e) => e, }; let error_message = format!("{:?}", err); - if !Self::matches_message_assert_unlinkable(&message, &error_message) { + if !Self::matches_message_assert_unlinkable(message, &error_message) { bail!( "assert_unlinkable: expected {}, got {}", message, @@ -278,7 +278,7 @@ impl Wast { let mut errors = Vec::with_capacity(ast.directives.len()); for directive in ast.directives { let sp = directive.span(); - if let Err(e) = self.run_directive(&test, directive) { + if let Err(e) = self.run_directive(test, directive) { let message = format!("{}", e); // If depends on an instance that doesn't exist if message.contains("no previous instance found") { @@ -317,7 +317,7 @@ impl Wast { Ok(s) => ret.push_str(s), Err(_) => bail!("malformed UTF-8 encoding"), } - ret.push_str(" "); + ret.push(' '); } let buf = wast::parser::ParseBuffer::new(&ret)?; let mut wat = wast::parser::parse::(&buf)?; @@ -403,7 +403,7 @@ impl Wast { field: &str, args: &[Val], ) -> Result> { - let instance = self.get_instance(instance_name.as_deref())?; + let instance = self.get_instance(instance_name)?; let func: &Function = instance.exports.get(field)?; match func.call(args) { Ok(result) => Ok(result.into()), @@ -413,7 +413,7 @@ impl Wast { /// Get the value of an exported global from an instance. fn get(&mut self, instance_name: Option<&str>, field: &str) -> Result> { - let instance = self.get_instance(instance_name.as_deref())?; + let instance = self.get_instance(instance_name)?; let global: &Global = instance.exports.get(field)?; Ok(vec![global.get()]) } @@ -473,8 +473,7 @@ impl Wast { || self .match_trap_messages .get(expected) - .map(|alternative| actual.contains(alternative)) - .unwrap_or(false) + .map_or(false, |alternative| actual.contains(alternative)) } fn val_matches(&self, actual: &Val, expected: &wast::AssertExpression) -> Result {