From 82f49cee543291a40f5724b169224c1b7e1c885c Mon Sep 17 00:00:00 2001 From: hardfist Date: Wed, 21 Aug 2024 17:40:45 +0800 Subject: [PATCH] refactor: add more clippy rule (#7594) * refactor: enable more clippy rules * chore: fix clippy rule * chore: fix conclict --- Cargo.toml | 71 +++++++++++++++++++ crates/rspack_core/Cargo.toml | 3 + .../src/build_chunk_graph/code_splitter.rs | 11 +-- crates/rspack_core/src/chunk.rs | 14 ++-- .../src/chunk_graph/chunk_graph_chunk.rs | 14 ++-- .../rspack_core/src/compiler/compilation.rs | 8 +-- crates/rspack_core/src/compiler/hmr.rs | 15 ++-- .../compiler/make/cutout/fix_build_meta.rs | 2 +- .../src/compiler/make/cutout/fix_issuers.rs | 2 +- .../make/cutout/has_module_graph_change.rs | 2 +- crates/rspack_core/src/compiler/make/mod.rs | 2 +- .../src/compiler/make/repair/factorize.rs | 1 - .../make/repair/process_dependencies.rs | 4 +- crates/rspack_core/src/compiler/mod.rs | 3 +- .../src/compiler/module_executor/execute.rs | 11 ++- .../src/compiler/module_executor/overwrite.rs | 4 +- crates/rspack_core/src/concatenated_module.rs | 25 ++++--- crates/rspack_core/src/context_module.rs | 4 +- .../rspack_core/src/context_module_factory.rs | 8 +-- .../src/dependency/runtime_template.rs | 6 +- crates/rspack_core/src/exports_info.rs | 25 +++---- crates/rspack_core/src/external_module.rs | 2 +- crates/rspack_core/src/init_fragment.rs | 10 +-- crates/rspack_core/src/module.rs | 3 +- crates/rspack_core/src/module_graph/mod.rs | 4 +- .../rspack_core/src/normal_module_factory.rs | 14 ++-- .../old_cache/occasion/create_chunk_assets.rs | 2 +- crates/rspack_core/src/options/output.rs | 2 +- .../src/options/resolve/clever_merge.rs | 2 +- crates/rspack_core/src/options/resolve/mod.rs | 2 +- .../rspack_core/src/resolver/resolver_impl.rs | 14 ++-- crates/rspack_core/src/runtime.rs | 2 +- crates/rspack_core/src/stats/mod.rs | 5 +- .../src/utils/compile_boolean_matcher.rs | 4 +- .../rspack_core/src/utils/find_graph_roots.rs | 10 +-- crates/rspack_core/src/utils/mod.rs | 2 +- crates/rspack_core/src/utils/runtime.rs | 2 +- 37 files changed, 188 insertions(+), 127 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 9bcebb14685..f4781e56e9c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -104,3 +104,74 @@ lto = "fat" debug = true inherits = "release" strip = false + +# the following lints rules are from https://github.com/biomejs/biome/blob/4bd3d6f09642952ee14445ed56af81a73796cea1/Cargo.toml#L7C1-L75C1 +[workspace.lints.rust] +absolute_paths_not_starting_with_crate = "warn" +dead_code = "warn" +trivial_numeric_casts = "warn" +unused_import_braces = "warn" +unused_lifetimes = "warn" +unused_macro_rules = "warn" + +[workspace.lints.clippy] +cargo_common_metadata = "allow" +empty_docs = "allow" # there are some false positives inside biome_wasm +multiple_crate_versions = "allow" + +# pedantic +checked_conversions = "warn" +cloned_instead_of_copied = "warn" +copy_iterator = "warn" +dbg_macro = "warn" +doc_link_with_quotes = "warn" +empty_enum = "warn" +expl_impl_clone_on_copy = "warn" +explicit_into_iter_loop = "warn" +filter_map_next = "warn" +flat_map_option = "warn" +fn_params_excessive_bools = "warn" +from_iter_instead_of_collect = "warn" +implicit_clone = "warn" +# not sure whether it's necessary +# implicit_hasher = "warn" +index_refutable_slice = "warn" +inefficient_to_string = "warn" +invalid_upcast_comparisons = "warn" +iter_not_returning_iterator = "warn" +large_stack_arrays = "warn" +large_types_passed_by_value = "warn" +macro_use_imports = "warn" +manual_ok_or = "warn" +manual_string_new = "warn" +map_flatten = "warn" +map_unwrap_or = "warn" +mismatching_type_param_order = "warn" +mut_mut = "warn" +naive_bytecount = "warn" +needless_bitwise_bool = "warn" +needless_continue = "warn" +needless_for_each = "warn" +no_effect_underscore_binding = "warn" +ref_binding_to_reference = "warn" +ref_option_ref = "warn" +stable_sort_primitive = "warn" +unnecessary_box_returns = "warn" +unnecessary_join = "warn" +unnested_or_patterns = "warn" +unreadable_literal = "warn" +verbose_bit_mask = "warn" +zero_sized_map_values = "warn" + +# restriction +empty_drop = "warn" +float_cmp_const = "warn" +get_unwrap = "warn" +infinite_loop = "warn" +lossy_float_literal = "warn" +rc_buffer = "warn" +rc_mutex = "warn" +rest_pat_in_fully_bound_structs = "warn" +verbose_file_reads = "warn" +# https://github.com/rustwasm/wasm-bindgen/issues/3944 +#mem_forget = "warn" diff --git a/crates/rspack_core/Cargo.toml b/crates/rspack_core/Cargo.toml index 58fdce6dde3..b9922c3442c 100644 --- a/crates/rspack_core/Cargo.toml +++ b/crates/rspack_core/Cargo.toml @@ -69,3 +69,6 @@ ustr = { workspace = true } [dev-dependencies] pretty_assertions = { version = "1.4.0" } + +[lints] +workspace = true diff --git a/crates/rspack_core/src/build_chunk_graph/code_splitter.rs b/crates/rspack_core/src/build_chunk_graph/code_splitter.rs index 05375b3656f..162bba70133 100644 --- a/crates/rspack_core/src/build_chunk_graph/code_splitter.rs +++ b/crates/rspack_core/src/build_chunk_graph/code_splitter.rs @@ -395,7 +395,7 @@ impl<'me> CodeSplitter<'me> { .compilation .get_module_graph() .module_identifier_by_dependency_id(dep) - .cloned() + .copied() }) .collect::>(); @@ -849,7 +849,7 @@ Or do you want to use the entrypoints '{name}' and '{runtime}' independently on .get_module_graph() .modules() .keys() - .cloned() + .copied() .collect::>(); for module_identifier in ids { self.compilation.chunk_graph.add_module(module_identifier) @@ -1278,8 +1278,9 @@ Or do you want to use the entrypoints '{name}' and '{runtime}' independently on entry_options .chunk_loading .as_ref() - .map(|x| !matches!(x, ChunkLoading::Disable)) - .unwrap_or(item_chunk_group_info.chunk_loading), + .map_or(item_chunk_group_info.chunk_loading, |x| { + !matches!(x, ChunkLoading::Disable) + }), entry_options .async_chunks .unwrap_or(item_chunk_group_info.async_chunks), @@ -1554,7 +1555,7 @@ Or do you want to use the entrypoints '{name}' and '{runtime}' independently on let chunk_group_ukey = chunk_group_info.chunk_group; // 1. Add new targets to the list of children - chunk_group_info.children.extend(targets.iter().cloned()); + chunk_group_info.children.extend(targets.iter().copied()); // 2. Calculate resulting available modules let resulting_available_modules = chunk_group_info diff --git a/crates/rspack_core/src/chunk.rs b/crates/rspack_core/src/chunk.rs index 3b117fd07a5..8f03ad750bc 100644 --- a/crates/rspack_core/src/chunk.rs +++ b/crates/rspack_core/src/chunk.rs @@ -532,13 +532,9 @@ impl Chunk { order_children .iter() .flat_map(|(_, child_chunks)| { - child_chunks.iter().filter_map(|chunk_ukey| { - compilation - .chunk_by_ukey - .expect_get(chunk_ukey) - .id - .to_owned() - }) + child_chunks + .iter() + .filter_map(|chunk_ukey| compilation.chunk_by_ukey.expect_get(chunk_ukey).id.clone()) }) .collect_vec() }) @@ -562,7 +558,7 @@ impl Chunk { ) { let chunk = compilation.chunk_by_ukey.expect_get(chunk_ukey); if let (Some(chunk_id), Some(child_chunk_ids)) = ( - chunk.id.to_owned(), + chunk.id.clone(), chunk.get_child_ids_by_order(order, compilation), ) { result @@ -577,7 +573,7 @@ impl Chunk { .get_sorted_groups_iter(&compilation.chunk_group_by_ukey) .filter_map(|chunk_group_ukey| { get_chunk_group_from_ukey(chunk_group_ukey, &compilation.chunk_group_by_ukey) - .map(|g| g.chunks.to_owned()) + .map(|g| g.chunks.clone()) }) .flatten() { diff --git a/crates/rspack_core/src/chunk_graph/chunk_graph_chunk.rs b/crates/rspack_core/src/chunk_graph/chunk_graph_chunk.rs index 447197d42f3..409d15fd17f 100644 --- a/crates/rspack_core/src/chunk_graph/chunk_graph_chunk.rs +++ b/crates/rspack_core/src/chunk_graph/chunk_graph_chunk.rs @@ -88,7 +88,7 @@ impl ChunkGraph { let old_cgm = self.get_chunk_graph_module(*old_module_id); // Using clone to avoid using mutable borrow and immutable borrow at the same time. - for chunk in old_cgm.chunks.clone().into_iter() { + for chunk in old_cgm.chunks.clone() { let cgc = self.get_chunk_graph_chunk_mut(chunk); cgc.modules.remove(old_module_id); cgc.modules.insert(*new_module_id); @@ -100,9 +100,9 @@ impl ChunkGraph { let old_cgm = self.get_chunk_graph_module_mut(*old_module_id); old_cgm.chunks.clear(); - for chunk in old_cgm.entry_in_chunks.clone().into_iter() { + for chunk in old_cgm.entry_in_chunks.clone() { let cgc = self.get_chunk_graph_chunk_mut(chunk); - if let Some(old) = cgc.entry_modules.get(old_module_id).cloned() { + if let Some(old) = cgc.entry_modules.get(old_module_id).copied() { let mut new_entry_modules = LinkedHashMap::default(); for (m, cg) in cgc.entry_modules.iter() { if m == old_module_id { @@ -122,7 +122,7 @@ impl ChunkGraph { old_cgm.entry_in_chunks.clear(); let old_cgm = self.get_chunk_graph_module(*old_module_id); - for chunk in old_cgm.runtime_in_chunks.clone().into_iter() { + for chunk in old_cgm.runtime_in_chunks.clone() { let cgc = self.get_chunk_graph_chunk_mut(chunk); // delete old module cgc.runtime_modules = std::mem::take(&mut cgc.runtime_modules) @@ -155,7 +155,7 @@ impl ChunkGraph { pub fn get_chunk_entry_modules(&self, chunk_ukey: &ChunkUkey) -> Vec { let chunk_graph_chunk = self.get_chunk_graph_chunk(chunk_ukey); - chunk_graph_chunk.entry_modules.keys().cloned().collect() + chunk_graph_chunk.entry_modules.keys().copied().collect() } pub fn get_chunk_entry_modules_with_chunk_group_iterable( @@ -476,7 +476,7 @@ impl ChunkGraph { module_graph: &ModuleGraph, ) -> Vec { let cgc = self.get_chunk_graph_chunk(chunk); - let mut input = cgc.modules.iter().cloned().collect::>(); + let mut input = cgc.modules.iter().copied().collect::>(); input.sort_unstable(); let mut modules = find_graph_roots(input, |module| { let mut set: IdentifierSet = Default::default(); @@ -825,6 +825,6 @@ impl ChunkGraph { None }) - .unwrap_or(module.source_types().iter().cloned().collect()) + .unwrap_or(module.source_types().iter().copied().collect()) } } diff --git a/crates/rspack_core/src/compiler/compilation.rs b/crates/rspack_core/src/compiler/compilation.rs index a2bce543933..0e66ac3aecc 100644 --- a/crates/rspack_core/src/compiler/compilation.rs +++ b/crates/rspack_core/src/compiler/compilation.rs @@ -924,7 +924,7 @@ impl Compilation { let chunk_ukey_and_manifest = results.into_inner(); - for result in chunk_ukey_and_manifest.into_iter() { + for result in chunk_ukey_and_manifest { let (chunk_ukey, manifest, diagnostics) = result?; self.extend_diagnostics(diagnostics); @@ -1005,7 +1005,7 @@ impl Compilation { // so use filter_map to ignore them module_graph .module_identifier_by_dependency_id(dep_id) - .cloned() + .copied() }) .collect() } @@ -1031,7 +1031,7 @@ impl Compilation { .values() .flat_map(|item| item.all_dependencies()) .chain(self.global_entry.all_dependencies()) - .cloned() + .copied() .collect(), )], )?; @@ -1277,7 +1277,7 @@ impl Compilation { let entrypoint = self.chunk_group_by_ukey.expect_get(entrypoint_ukey); entrypoint.get_runtime_chunk(&self.chunk_group_by_ukey) }); - UkeySet::from_iter(entries.chain(async_entries)) + entries.chain(async_entries).collect() } #[allow(clippy::unwrap_in_result)] diff --git a/crates/rspack_core/src/compiler/hmr.rs b/crates/rspack_core/src/compiler/hmr.rs index 8072f709c36..fb521212c05 100644 --- a/crates/rspack_core/src/compiler/hmr.rs +++ b/crates/rspack_core/src/compiler/hmr.rs @@ -27,14 +27,13 @@ where let (old_all_modules, old_runtime_modules) = collect_changed_modules(old.compilation)?; // TODO: should use `records` - let all_old_runtime = RuntimeSpec::from_iter( - old - .compilation - .get_chunk_graph_entries() - .into_iter() - .filter_map(|entry_ukey| get_chunk_from_ukey(&entry_ukey, &old.compilation.chunk_by_ukey)) - .flat_map(|entry_chunk| entry_chunk.runtime.clone()), - ); + let all_old_runtime = old + .compilation + .get_chunk_graph_entries() + .into_iter() + .filter_map(|entry_ukey| get_chunk_from_ukey(&entry_ukey, &old.compilation.chunk_by_ukey)) + .flat_map(|entry_chunk| entry_chunk.runtime.clone()) + .collect(); let mut old_chunks: Vec<(String, RuntimeSpec)> = vec![]; for (_, chunk) in old.compilation.chunk_by_ukey.iter() { diff --git a/crates/rspack_core/src/compiler/make/cutout/fix_build_meta.rs b/crates/rspack_core/src/compiler/make/cutout/fix_build_meta.rs index fbb115335d4..a27a2c47ca0 100644 --- a/crates/rspack_core/src/compiler/make/cutout/fix_build_meta.rs +++ b/crates/rspack_core/src/compiler/make/cutout/fix_build_meta.rs @@ -27,7 +27,7 @@ impl FixBuildMeta { pub fn fix_artifact(self, artifact: &mut MakeArtifact) { let mut module_graph = artifact.get_module_graph_mut(); - for (id, build_meta) in self.origin_module_build_meta.into_iter() { + for (id, build_meta) in self.origin_module_build_meta { if let Some(module) = module_graph.module_by_identifier_mut(&id) { if let Some(module) = module.as_normal_module_mut() { if matches!(module.source(), NormalModuleSource::BuiltFailed(_)) { diff --git a/crates/rspack_core/src/compiler/make/cutout/fix_issuers.rs b/crates/rspack_core/src/compiler/make/cutout/fix_issuers.rs index 40839221197..9dab42c52d6 100644 --- a/crates/rspack_core/src/compiler/make/cutout/fix_issuers.rs +++ b/crates/rspack_core/src/compiler/make/cutout/fix_issuers.rs @@ -25,7 +25,7 @@ impl FixIssuers { pub fn fix_artifact(self, artifact: &mut MakeArtifact) { let mut module_graph = artifact.get_module_graph_mut(); - for (id, issuer) in self.origin_module_issuers.into_iter() { + for (id, issuer) in self.origin_module_issuers { if let Some(mgm) = module_graph.module_graph_module_by_identifier_mut(&id) { mgm.set_issuer(issuer); } diff --git a/crates/rspack_core/src/compiler/make/cutout/has_module_graph_change.rs b/crates/rspack_core/src/compiler/make/cutout/has_module_graph_change.rs index b700f751f1e..2c31960a0af 100644 --- a/crates/rspack_core/src/compiler/make/cutout/has_module_graph_change.rs +++ b/crates/rspack_core/src/compiler/make/cutout/has_module_graph_change.rs @@ -163,7 +163,7 @@ mod t { self .ids .iter() - .map(|id| id.to_string().into()) + .map(|id| (*id).to_string().into()) .collect_vec() } } diff --git a/crates/rspack_core/src/compiler/make/mod.rs b/crates/rspack_core/src/compiler/make/mod.rs index 156dcd7c81f..4ae78b71481 100644 --- a/crates/rspack_core/src/compiler/make/mod.rs +++ b/crates/rspack_core/src/compiler/make/mod.rs @@ -113,7 +113,7 @@ pub fn make_module_graph( .values() .flat_map(|item| item.all_dependencies()) .chain(compilation.global_entry.all_dependencies()) - .cloned() + .copied() .collect(), )); } diff --git a/crates/rspack_core/src/compiler/make/repair/factorize.rs b/crates/rspack_core/src/compiler/make/repair/factorize.rs index 55c80a8f44a..e5456f22445 100644 --- a/crates/rspack_core/src/compiler/make/repair/factorize.rs +++ b/crates/rspack_core/src/compiler/make/repair/factorize.rs @@ -203,7 +203,6 @@ impl Task for FactorizeResultTask { context_dependencies, missing_dependencies, diagnostics, - .. } = *self; let artifact = &mut context.artifact; if !diagnostics.is_empty() { diff --git a/crates/rspack_core/src/compiler/make/repair/process_dependencies.rs b/crates/rspack_core/src/compiler/make/repair/process_dependencies.rs index 9038d5e99fc..defa8ff74a4 100644 --- a/crates/rspack_core/src/compiler/make/repair/process_dependencies.rs +++ b/crates/rspack_core/src/compiler/make/repair/process_dependencies.rs @@ -28,7 +28,7 @@ impl Task for ProcessDependenciesTask { let module_graph = &mut MakeTaskContext::get_module_graph_mut(&mut context.artifact.module_graph_partial); - dependencies.into_iter().for_each(|dependency_id| { + for dependency_id in dependencies { let dependency = module_graph .dependency_by_id(&dependency_id) .expect("should have dependency"); @@ -59,7 +59,7 @@ impl Task for ProcessDependenciesTask { .or_insert(vec![]) .push(dependency_id); } - }); + } let module = module_graph .module_by_identifier(&original_module_identifier) diff --git a/crates/rspack_core/src/compiler/mod.rs b/crates/rspack_core/src/compiler/mod.rs index 9fd07e87599..5a95b4c6981 100644 --- a/crates/rspack_core/src/compiler/mod.rs +++ b/crates/rspack_core/src/compiler/mod.rs @@ -313,8 +313,7 @@ where if let Some(source) = asset.get_source() { let filename = filename .split_once('?') - .map(|(filename, _query)| filename) - .unwrap_or(filename); + .map_or(filename, |(filename, _query)| filename); let file_path = output_path.join(filename); self .output_filesystem diff --git a/crates/rspack_core/src/compiler/module_executor/execute.rs b/crates/rspack_core/src/compiler/module_executor/execute.rs index 16c286a2e78..2b7e8c3b8da 100644 --- a/crates/rspack_core/src/compiler/module_executor/execute.rs +++ b/crates/rspack_core/src/compiler/module_executor/execute.rs @@ -101,7 +101,7 @@ impl Task for ExecuteTask { chunk.id = chunk.name.clone(); chunk.ids = vec![chunk.id.clone().expect("id is set")]; - let runtime = RuntimeSpec::from_iter(once("build time".into())); + let runtime: RuntimeSpec = once("build time".into()).collect(); chunk.runtime = runtime.clone(); @@ -165,7 +165,7 @@ impl Task for ExecuteTask { Handle::current().block_on(async { compilation .process_runtime_requirements( - Vec::from_iter(modules.iter().copied()), + modules.iter().copied().collect::>(), once(chunk_ukey), once(chunk_ukey), compilation.plugin_driver.clone(), @@ -257,7 +257,7 @@ impl Task for ExecuteTask { result.id = id; - modules.iter().for_each(|m| { + for m in modules.iter() { let codegen_result = codegen_results.get(m, Some(&runtime)); if let Some(source) = codegen_result.get(&SourceType::Asset) @@ -270,7 +270,7 @@ impl Task for ExecuteTask { CompilationAsset::new(Some(source.clone()), asset_info.inner().clone()), ); } - }); + } Ok(result) } @@ -305,8 +305,7 @@ impl Task for ExecuteTask { cacheable: runtime_module.cacheable(), size: runtime_module_size .get(&identifier) - .map(|s| s.to_owned()) - .unwrap_or(0 as f64), + .map_or(0 as f64, |s| s.to_owned()), } }) .collect_vec(); diff --git a/crates/rspack_core/src/compiler/module_executor/overwrite.rs b/crates/rspack_core/src/compiler/module_executor/overwrite.rs index 14bb424ac45..924b79d00a2 100644 --- a/crates/rspack_core/src/compiler/module_executor/overwrite.rs +++ b/crates/rspack_core/src/compiler/module_executor/overwrite.rs @@ -44,7 +44,7 @@ impl Task for OverwriteTask { let dep_id = factorize_result_task .dependencies .first() - .cloned() + .copied() .expect("should have dep_id"); let original_module_identifier = factorize_result_task.original_module_identifier; let res = origin_task.sync_run(context)?; @@ -60,7 +60,7 @@ impl Task for OverwriteTask { let dep_id = add_task .dependencies .first() - .cloned() + .copied() .expect("should have dep_id"); let original_module_identifier = add_task.original_module_identifier; let target_module_identifier = add_task.module.identifier(); diff --git a/crates/rspack_core/src/concatenated_module.rs b/crates/rspack_core/src/concatenated_module.rs index e3a0b3bb32a..2ae5fe99234 100644 --- a/crates/rspack_core/src/concatenated_module.rs +++ b/crates/rspack_core/src/concatenated_module.rs @@ -7,7 +7,7 @@ use std::{ }; use dashmap::DashMap; -use indexmap::{IndexMap, IndexSet}; +use indexmap::IndexMap; use rayon::prelude::*; use regex::Regex; use rspack_ast::javascript::Ast; @@ -409,7 +409,7 @@ impl ConcatenatedModule { for m in modules { identifiers.push(m.shorten_id.as_str()); } - identifiers.sort(); + identifiers.sort_unstable(); let mut hash = RspackHash::new(&hash_function.unwrap_or(HashFunction::MD4)); if let Some(id) = identifiers.first() { hash.write(id.as_bytes()); @@ -646,7 +646,7 @@ impl Module for ConcatenatedModule { .collect::>(); let mut updated_pairs = vec![]; - for item in tmp.into_iter() { + for item in tmp { updated_pairs.push(item?); } @@ -656,7 +656,7 @@ impl Module for ConcatenatedModule { module_to_info_map.insert(id, module_info); } - let mut all_used_names = HashSet::from_iter(RESERVED_NAMES.iter().map(|s| Atom::new(*s))); + let mut all_used_names: HashSet = RESERVED_NAMES.iter().map(|s| Atom::new(*s)).collect(); let mut top_level_declarations: HashSet = HashSet::default(); for module_info_id in modules_with_info.iter() { @@ -990,8 +990,7 @@ impl Module for ConcatenatedModule { let exports_argument = self .build_meta() - .map(|meta| meta.exports_argument) - .unwrap_or(ExportsArgument::Exports); + .map_or(ExportsArgument::Exports, |meta| meta.exports_argument); let should_skip_render_definitions = compilation .plugin_driver @@ -1043,10 +1042,10 @@ impl Module for ConcatenatedModule { for module_info_id in needed_namespace_objects.clone().iter() { if visited.contains(module_info_id) { continue; - } else { - visited.insert(*module_info_id); - changed = true; } + visited.insert(*module_info_id); + changed = true; + let module_info = module_to_info_map .get(module_info_id) .map(|m| m.as_concatenated()) @@ -1302,7 +1301,7 @@ impl Module for ConcatenatedModule { let runtime = runtime.as_deref(); for info in self.create_concatenation_list( self.root_module_ctxt.id, - IndexSet::from_iter(self.modules.iter().map(|item| item.id)), + self.modules.iter().map(|item| item.id).collect(), runtime, &compilation.get_module_graph(), ) { @@ -1418,7 +1417,7 @@ impl ConcatenatedModule { ) -> (Vec, IdentifierIndexMap) { let ordered_concatenation_list = self.create_concatenation_list( self.root_module_ctxt.id, - IndexSet::from_iter(self.modules.iter().map(|item| item.id)), + self.modules.iter().map(|item| item.id).collect(), runtime, mg, ); @@ -2169,7 +2168,7 @@ impl ConcatenatedModule { { let used_name = used_name.to_used_name_vec(); let comment = if used_name == export_name { - "".to_string() + String::new() } else { Template::to_normal_comment(&join_atom(export_name.iter(), ",")) }; @@ -2244,7 +2243,7 @@ pub fn find_new_name( "{}{}", info_part, if name.is_empty() { - "".to_string() + String::new() } else { format!("_{name}") } diff --git a/crates/rspack_core/src/context_module.rs b/crates/rspack_core/src/context_module.rs index 8b156c19554..0109f3af5f1 100644 --- a/crates/rspack_core/src/context_module.rs +++ b/crates/rspack_core/src/context_module.rs @@ -254,7 +254,7 @@ impl ContextModule { fn get_fake_map_init_statement(&self, fake_map: &FakeMapValue) -> String { match fake_map { - FakeMapValue::Bit(_) => "".to_string(), + FakeMapValue::Bit(_) => String::new(), FakeMapValue::Map(map) => format!("var fakeMap = {}", json_stringify(map)), } } @@ -1253,7 +1253,7 @@ fn create_identifier(options: &ContextModuleOptions) -> Identifier { pub fn normalize_context(str: &str) -> String { if str == "./" || str == "." { - return "".to_string(); + return String::new(); } if str.ends_with('/') { return str.to_string(); diff --git a/crates/rspack_core/src/context_module_factory.rs b/crates/rspack_core/src/context_module_factory.rs index 15ba7a17b00..d59b2454e9a 100644 --- a/crates/rspack_core/src/context_module_factory.rs +++ b/crates/rspack_core/src/context_module_factory.rs @@ -211,7 +211,7 @@ impl ContextModuleFactory { ); (request, resource) } - None => ("".to_string(), request), + None => (String::new(), request), }; let resolve_args = ResolveArgs { @@ -282,9 +282,9 @@ impl ContextModuleFactory { ) -> Result> { let context_options = &context_module_options.context_options; let after_resolve_data = AfterResolveData { - resource: context_module_options.resource.to_owned(), - context: context_options.context.to_owned(), - request: context_options.request.to_owned(), + resource: context_module_options.resource.clone(), + context: context_options.context.clone(), + request: context_options.request.clone(), reg_exp: context_options.reg_exp.clone(), }; diff --git a/crates/rspack_core/src/dependency/runtime_template.rs b/crates/rspack_core/src/dependency/runtime_template.rs index 4491f5e4683..18ab437e495 100644 --- a/crates/rspack_core/src/dependency/runtime_template.rs +++ b/crates/rspack_core/src/dependency/runtime_template.rs @@ -229,7 +229,7 @@ pub fn export_from_import( let comment = if *used_name != export_name { to_normal_comment(&property_access(&export_name, 0)) } else { - "".to_string() + String::new() }; let property = property_access(&*used_name, 0); let access = format!("{import_var}{comment}{property}"); @@ -373,7 +373,7 @@ pub fn import_statement( .module_identifier_by_dependency_id(id) .is_none() { - return (missing_module_statement(request), "".to_string()); + return (missing_module_statement(request), String::new()); }; let module_id_expr = module_id(compilation, id, request, false); @@ -400,7 +400,7 @@ pub fn import_statement( ), ); } - (import_content, "".to_string()) + (import_content, String::new()) } pub fn module_namespace_promise( diff --git a/crates/rspack_core/src/exports_info.rs b/crates/rspack_core/src/exports_info.rs index 26cfd1cbc8d..7e0519182df 100644 --- a/crates/rspack_core/src/exports_info.rs +++ b/crates/rspack_core/src/exports_info.rs @@ -108,7 +108,7 @@ impl ExportsInfo { let exports_info = mg.get_exports_info_by_id(self); let redirect_id = exports_info.redirect_to; let other_exports_info_id = exports_info.other_exports_info; - let export_id_list = exports_info.exports.values().cloned().collect::>(); + let export_id_list = exports_info.exports.values().copied().collect::>(); for export_info_id in export_id_list { let export_info = mg.get_export_info_mut_by_id(&export_info_id); if export_info.provided.is_none() { @@ -160,7 +160,7 @@ impl ExportsInfo { let exports_info = mg.get_exports_info_by_id(self); let redirect_to = exports_info.redirect_to; let other_exports_info = exports_info.other_exports_info; - let exports_id_list = exports_info.exports.values().cloned().collect::>(); + let exports_id_list = exports_info.exports.values().copied().collect::>(); for export_info in exports_id_list { if !can_mangle && export_info.can_mangle_provide(mg) != Some(false) { export_info.set_can_mangle_provide(mg, Some(false)); @@ -303,7 +303,7 @@ impl ExportsInfo { let redirect_to_id = exports_info.redirect_to; let other_exports_info_id = exports_info.other_exports_info; // this clone aiming to avoid use the mutable ref and immutable ref at the same time. - let export_id_list = exports_info.exports.values().cloned().collect::>(); + let export_id_list = exports_info.exports.values().copied().collect::>(); for export_info in export_id_list { export_info.set_has_use_info(mg); } @@ -325,7 +325,7 @@ impl ExportsInfo { let redirect = exports_info.redirect_to; let other_exports_info_id = exports_info.other_exports_info; // avoid use ref and mut ref at the same time - let export_info_id_list = exports_info.exports.values().cloned().collect::>(); + let export_info_id_list = exports_info.exports.values().copied().collect::>(); for export_info_id in export_info_id_list { let flag = export_info_id.set_used_without_info(mg, runtime); changed |= flag; @@ -352,7 +352,7 @@ impl ExportsInfo { ) -> bool { let mut changed = false; let exports_info = mg.get_exports_info_mut_by_id(self); - let export_info_id_list = exports_info.exports.values().cloned().collect::>(); + let export_info_id_list = exports_info.exports.values().copied().collect::>(); for export_info_id in export_info_id_list { let export_info = export_info_id.as_export_info_mut(mg); if !matches!(export_info.provided, Some(ExportInfoProvided::True)) { @@ -370,7 +370,7 @@ impl ExportsInfo { ) -> bool { let mut changed = false; let exports_info = mg.get_exports_info_by_id(self); - let export_info_id_list = exports_info.exports.values().cloned().collect::>(); + let export_info_id_list = exports_info.exports.values().copied().collect::>(); let redirect_to_id = exports_info.redirect_to; let other_exports_info_id = exports_info.other_exports_info; for export_info_id in export_info_id_list { @@ -484,7 +484,7 @@ impl ExportsInfo { for export_info_id in info.exports.values() { let export_info = export_info_id.as_export_info(mg); match export_info.provided { - Some(ExportInfoProvided::True) | Some(ExportInfoProvided::Null) | None => { + Some(ExportInfoProvided::True | ExportInfoProvided::Null) | None => { ret.push(export_info.name.clone().unwrap_or("".into())); } _ => {} @@ -524,7 +524,7 @@ impl ExportsInfo { UsageState::NoInfo => return UsedExports::Null, UsageState::Unknown => return UsedExports::Bool(true), UsageState::OnlyPropertiesUsed | UsageState::Used => { - if let Some(name) = export_info_id.as_export_info(mg).name.to_owned() { + if let Some(name) = export_info_id.as_export_info(mg).name.clone() { res.push(name); } } @@ -1637,14 +1637,11 @@ impl ExportInfoData { let used_name = init_from.and_then(|init_from| init_from.used_name.clone()); let global_used = init_from.and_then(|init_from| init_from.global_used); let used_in_runtime = init_from.and_then(|init_from| init_from.used_in_runtime.clone()); - let has_use_in_runtime_info = init_from - .map(|init_from| init_from.has_use_in_runtime_info) - .unwrap_or(false); + let has_use_in_runtime_info = + init_from.is_some_and(|init_from| init_from.has_use_in_runtime_info); let provided = init_from.and_then(|init_from| init_from.provided); - let terminal_binding = init_from - .map(|init_from| init_from.terminal_binding) - .unwrap_or(false); + let terminal_binding = init_from.is_some_and(|init_from| init_from.terminal_binding); let can_mangle_provide = init_from.and_then(|init_from| init_from.can_mangle_provide); let can_mangle_use = init_from.and_then(|init_from| init_from.can_mangle_use); diff --git a/crates/rspack_core/src/external_module.rs b/crates/rspack_core/src/external_module.rs index 0376a6fcfdf..e8173a5c66a 100644 --- a/crates/rspack_core/src/external_module.rs +++ b/crates/rspack_core/src/external_module.rs @@ -333,7 +333,7 @@ if(typeof {global} !== "undefined") return resolve(); load_script = RuntimeGlobals::LOAD_SCRIPT.name() ) } - _ => "".to_string(), + _ => String::new(), }; Ok(( RawSource::from(source).boxed(), diff --git a/crates/rspack_core/src/init_fragment.rs b/crates/rspack_core/src/init_fragment.rs index c8759e736b5..79277d89aaa 100644 --- a/crates/rspack_core/src/init_fragment.rs +++ b/crates/rspack_core/src/init_fragment.rs @@ -417,7 +417,7 @@ impl InitFragment for AwaitDependenciesInitFrag context.add_runtime_requirements(RuntimeGlobals::MODULE); if self.promises.is_empty() { Ok(InitFragmentContents { - start: "".to_string(), + start: String::new(), end: None, }) } else if self.promises.len() == 1 { @@ -518,8 +518,8 @@ impl InitFragment for ConditionalInitFragment { || self.content.is_empty() { InitFragmentContents { - start: "".to_owned(), - end: Some("".to_owned()), + start: String::new(), + end: Some(String::new()), } } else if matches!(self.runtime_condition, RuntimeCondition::Boolean(true)) { InitFragmentContents { @@ -651,7 +651,7 @@ impl InitFragment for ExternalModuleInitFragmen let mut imports_string: String; imports_string = if named_imports.is_empty() { - "".to_string() + String::new() } else { format!("{{{}}}", named_imports.join(", ")) }; @@ -661,7 +661,7 @@ impl InitFragment for ExternalModuleInitFragmen "{}{}", default_import, if imports_string.is_empty() { - "".to_string() + String::new() } else { format!(", {}", imports_string) } diff --git a/crates/rspack_core/src/module.rs b/crates/rspack_core/src/module.rs index f40f157c595..a234a70d174 100644 --- a/crates/rspack_core/src/module.rs +++ b/crates/rspack_core/src/module.rs @@ -249,8 +249,7 @@ pub trait Module: self .build_meta() .as_ref() - .map(|m| m.strict_harmony_module) - .unwrap_or(false) + .is_some_and(|m| m.strict_harmony_module) } /// The actual code generation of the module, which will be called by the `Compilation`. diff --git a/crates/rspack_core/src/module_graph/mod.rs b/crates/rspack_core/src/module_graph/mod.rs index 3f38358667d..547d7dfeff8 100644 --- a/crates/rspack_core/src/module_graph/mod.rs +++ b/crates/rspack_core/src/module_graph/mod.rs @@ -414,7 +414,7 @@ impl<'a> ModuleGraph<'a> { // avoid violating rustc borrow rules let mut add_outgoing_connection = vec![]; let mut delete_outgoing_connection = vec![]; - for connection_id in outgoing_connections.into_iter() { + for connection_id in outgoing_connections { let connection = match self.connection_by_connection_id(&connection_id) { Some(con) => con, // removed @@ -455,7 +455,7 @@ impl<'a> ModuleGraph<'a> { // avoid violating rustc borrow rules let mut add_incoming_connection = vec![]; let mut delete_incoming_connection = vec![]; - for connection_id in old_mgm.incoming_connections().clone().into_iter() { + for connection_id in old_mgm.incoming_connections().clone() { let connection = match self.connection_by_connection_id(&connection_id) { Some(con) => con, None => continue, diff --git a/crates/rspack_core/src/normal_module_factory.rs b/crates/rspack_core/src/normal_module_factory.rs index 375ceff4a2b..0f1841d314b 100644 --- a/crates/rspack_core/src/normal_module_factory.rs +++ b/crates/rspack_core/src/normal_module_factory.rs @@ -313,7 +313,7 @@ impl NormalModuleFactory { } else { // resource without scheme and without path if resource.is_empty() || resource.starts_with(QUESTION_MARK) { - ResourceData::new(resource.to_owned()).path(Utf8PathBuf::from("")) + ResourceData::new(resource.clone()).path(Utf8PathBuf::from("")) } else { // resource without scheme and with path let resolve_args = ResolveArgs { @@ -657,11 +657,11 @@ impl NormalModuleFactory { fn calculate_side_effects(&self, module_rules: &[&ModuleRuleEffect]) -> Option { let mut side_effect_res = None; // side_effects from module rule has higher priority - module_rules.iter().for_each(|rule| { + for rule in module_rules.iter() { if rule.side_effects.is_some() { side_effect_res = rule.side_effects; } - }); + } side_effect_res } @@ -736,11 +736,11 @@ impl NormalModuleFactory { module_rules: &[&ModuleRuleEffect], ) -> ModuleType { let mut resolved_module_type = matched_module_type.unwrap_or(ModuleType::JsAuto); - module_rules.iter().for_each(|module_rule| { + for module_rule in module_rules.iter() { if let Some(module_type) = module_rule.r#type { resolved_module_type = module_type; }; - }); + } resolved_module_type } @@ -751,11 +751,11 @@ impl NormalModuleFactory { module_rules: &[&ModuleRuleEffect], ) -> Option { let mut resolved_module_layer = issuer_layer; - module_rules.iter().for_each(|module_rule| { + for module_rule in module_rules.iter() { if let Some(module_layer) = &module_rule.layer { resolved_module_layer = Some(module_layer); }; - }); + } resolved_module_layer.cloned() } diff --git a/crates/rspack_core/src/old_cache/occasion/create_chunk_assets.rs b/crates/rspack_core/src/old_cache/occasion/create_chunk_assets.rs index d2aa39b53de..db85fa3a4ae 100644 --- a/crates/rspack_core/src/old_cache/occasion/create_chunk_assets.rs +++ b/crates/rspack_core/src/old_cache/occasion/create_chunk_assets.rs @@ -16,7 +16,7 @@ impl CreateChunkAssetsOccasion { Self { storage } } - pub async fn use_cache<'a, G, F>( + pub async fn use_cache( &self, compilation: &Compilation, chunk: &Chunk, diff --git a/crates/rspack_core/src/options/output.rs b/crates/rspack_core/src/options/output.rs index e4158b662b7..886530f77f5 100644 --- a/crates/rspack_core/src/options/output.rs +++ b/crates/rspack_core/src/options/output.rs @@ -317,7 +317,7 @@ impl PublicPath { pub fn render_auto_public_path(compilation: &Compilation, filename: &str) -> String { let public_path = match Utf8Path::new(filename).parent() { - None => "".to_string(), + None => String::new(), Some(dirname) => compilation .options .output diff --git a/crates/rspack_core/src/options/resolve/clever_merge.rs b/crates/rspack_core/src/options/resolve/clever_merge.rs index a1a15fff761..79b4b165463 100644 --- a/crates/rspack_core/src/options/resolve/clever_merge.rs +++ b/crates/rspack_core/src/options/resolve/clever_merge.rs @@ -472,7 +472,7 @@ mod test { use crate::AliasMap; fn string_list(a: &[&str]) -> Option> { - Some(a.iter().map(|s| s.to_string()).collect()) + Some(a.iter().map(|s| (*s).to_string()).collect()) } fn first_case_1() -> Resolve { diff --git a/crates/rspack_core/src/options/resolve/mod.rs b/crates/rspack_core/src/options/resolve/mod.rs index 8eb4cb735d0..caf362f81e7 100644 --- a/crates/rspack_core/src/options/resolve/mod.rs +++ b/crates/rspack_core/src/options/resolve/mod.rs @@ -83,7 +83,7 @@ pub struct Resolve { /// Configure resolve options by the type of module request. pub by_dependency: Option, /// The JSON files to use for descriptions - /// Default is ["package.json"] + /// Default is [`package.json`] pub description_files: Option, /// If enforce_extension is set to EnforceExtension::Enabled, resolution will not allow extension-less files. This means require('./foo.js') will resolve, while require('./foo') will not. pub enforce_extension: Option, diff --git a/crates/rspack_core/src/resolver/resolver_impl.rs b/crates/rspack_core/src/resolver/resolver_impl.rs index 1bfec02821f..a98e72a608c 100644 --- a/crates/rspack_core/src/resolver/resolver_impl.rs +++ b/crates/rspack_core/src/resolver/resolver_impl.rs @@ -180,13 +180,13 @@ fn to_rspack_resolver_options( ) -> rspack_resolver::ResolveOptions { let options = options.merge_by_dependency(dependency_type); let tsconfig = options.tsconfig.map(|c| c.into()); - let enforce_extension = options - .enforce_extension - .map(|e| match e { - true => rspack_resolver::EnforceExtension::Enabled, - false => rspack_resolver::EnforceExtension::Disabled, - }) - .unwrap_or(rspack_resolver::EnforceExtension::Auto); + let enforce_extension = + options + .enforce_extension + .map_or(rspack_resolver::EnforceExtension::Auto, |e| match e { + true => rspack_resolver::EnforceExtension::Enabled, + false => rspack_resolver::EnforceExtension::Disabled, + }); let description_files = options .description_files .unwrap_or_else(|| vec!["package.json".to_string()]); diff --git a/crates/rspack_core/src/runtime.rs b/crates/rspack_core/src/runtime.rs index c8c72a3faaf..c97b5ef92b4 100644 --- a/crates/rspack_core/src/runtime.rs +++ b/crates/rspack_core/src/runtime.rs @@ -96,7 +96,7 @@ impl RuntimeSpec { self.key = String::new(); return; } - let mut ordered = Vec::from_iter(self.inner.iter().cloned()); + let mut ordered = self.inner.iter().cloned().collect::>(); ordered.sort_unstable(); self.key = ordered.join("\n") } diff --git a/crates/rspack_core/src/stats/mod.rs b/crates/rspack_core/src/stats/mod.rs index 0b0b71a3eba..f147d0fbcc1 100644 --- a/crates/rspack_core/src/stats/mod.rs +++ b/crates/rspack_core/src/stats/mod.rs @@ -273,7 +273,7 @@ impl Stats<'_> { .into_iter() .collect::(); - let mut auxiliary_files = Vec::from_iter(c.auxiliary_files.iter().cloned()); + let mut auxiliary_files = c.auxiliary_files.iter().cloned().collect::>(); auxiliary_files.sort_unstable(); let chunk_modules = if options.chunk_modules { @@ -1113,8 +1113,7 @@ impl Stats<'_> { .compilation .runtime_module_code_generation_results .get(identifier) - .map(|(_, source)| source.size() as f64) - .unwrap_or(0 as f64); + .map_or(0 as f64, |(_, source)| source.size() as f64); let mut stats = StatsModule { r#type: "module", diff --git a/crates/rspack_core/src/utils/compile_boolean_matcher.rs b/crates/rspack_core/src/utils/compile_boolean_matcher.rs index f1aa8310833..dcb2741bfe1 100644 --- a/crates/rspack_core/src/utils/compile_boolean_matcher.rs +++ b/crates/rspack_core/src/utils/compile_boolean_matcher.rs @@ -88,7 +88,7 @@ pub(crate) fn items_to_regexp(items_arr: Vec) -> String { let mut finished_items = Vec::new(); let mut items_set: Vec<&str> = items_arr.iter().map(|s| s.as_str()).collect(); - items_set.sort(); + items_set.sort_unstable(); // Merge single char items: (a|b|c|d|ef) => ([abcd]|ef) let count_of_single_char_items = items_set.iter().filter(|&item| item.len() == 1).count(); @@ -96,7 +96,7 @@ pub(crate) fn items_to_regexp(items_arr: Vec) -> String { // Special case for only single char items if count_of_single_char_items == items_set.len() { let mut items_arr = items_set.into_iter().collect::>(); - items_arr.sort(); + items_arr.sort_unstable(); let single_char_items = items_arr.join(""); return format!("[{}]", quote_meta(&single_char_items)); } diff --git a/crates/rspack_core/src/utils/find_graph_roots.rs b/crates/rspack_core/src/utils/find_graph_roots.rs index 154dbf89134..4cada922af1 100644 --- a/crates/rspack_core/src/utils/find_graph_roots.rs +++ b/crates/rspack_core/src/utils/find_graph_roots.rs @@ -140,7 +140,7 @@ pub fn find_graph_roots< node.dependencies = get_dependencies(node.item) .into_iter() .filter_map(|item| item_to_node_ukey.get(&item)) - .cloned() + .copied() .collect::>(); }); @@ -153,7 +153,7 @@ pub fn find_graph_roots< // that is not part of the cycle let mut root_cycles: UkeySet>> = UkeySet::default(); - let mut keys = db.keys().cloned().collect::>(); + let mut keys = db.keys().copied().collect::>(); keys.sort_by(|a, b| db.expect_get(a).item.cmp(&db.expect_get(b).item)); // For all non-marked nodes @@ -169,7 +169,7 @@ pub fn find_graph_roots< let mut stack = vec![StackEntry { node: select_node, open_edges: { - let mut v: Vec<_> = db.expect_get(&select_node).dependencies.to_vec(); + let mut v: Vec<_> = db.expect_get(&select_node).dependencies.clone(); v.sort_by(|a, b| db.expect_get(a).item.cmp(&db.expect_get(b).item)); v }, @@ -201,7 +201,7 @@ pub fn find_graph_roots< stack.push(StackEntry { node: dependency, open_edges: { - let mut v: Vec<_> = db.expect_get(&dependency).dependencies.to_vec(); + let mut v: Vec<_> = db.expect_get(&dependency).dependencies.clone(); v.sort_unstable(); v }, @@ -286,7 +286,7 @@ pub fn find_graph_roots< let mut cycle_roots: UkeySet> = Default::default(); let nodes = &cycle_db.expect_get(&cycle).nodes; for node in nodes.iter() { - for dep in db.expect_get(node).dependencies.clone().into_iter() { + for dep in db.expect_get(node).dependencies.clone() { if nodes.contains(&dep) { db.expect_get_mut(&dep).incoming += 1; if db.expect_get(&dep).incoming < max { diff --git a/crates/rspack_core/src/utils/mod.rs b/crates/rspack_core/src/utils/mod.rs index e153f3b2f5b..bc4c8468109 100644 --- a/crates/rspack_core/src/utils/mod.rs +++ b/crates/rspack_core/src/utils/mod.rs @@ -79,7 +79,7 @@ pub fn parse_to_url(url: &str) -> url::Url { /// ``` pub fn join_string_component(mut components: Vec) -> String { match components.len() { - 0 => "".to_string(), + 0 => String::new(), 1 => std::mem::take(&mut components[0]), 2 => { format!("{} and {}", components[0], components[1]) diff --git a/crates/rspack_core/src/utils/runtime.rs b/crates/rspack_core/src/utils/runtime.rs index dec7d993d22..5c4b1233045 100644 --- a/crates/rspack_core/src/utils/runtime.rs +++ b/crates/rspack_core/src/utils/runtime.rs @@ -72,7 +72,7 @@ pub fn get_filename_without_hash_length( Some(m) => m.as_str().parse().ok(), None => None, } { - hash_len_map.insert(key.to_string(), hash_len); + hash_len_map.insert((*key).to_string(), hash_len); } key })