From e5ca7bcb9dfaa04acf37c835b29f01bbadfb1d3c Mon Sep 17 00:00:00 2001 From: hardfist Date: Thu, 15 Aug 2024 22:21:11 +0800 Subject: [PATCH] refactor: enable more clippy rules --- Cargo.toml | 70 +++++++++++++++++++ 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 | 10 +-- .../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 +- .../make/repair/process_dependencies.rs | 4 +- crates/rspack_core/src/compiler/mod.rs | 3 +- .../src/compiler/module_executor/execute.rs | 19 +++-- .../src/compiler/module_executor/overwrite.rs | 4 +- crates/rspack_core/src/concatenated_module.rs | 11 ++- 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 +- .../rspack_core/src/resolver/resolver_impl.rs | 14 ++-- crates/rspack_core/src/stats/mod.rs | 3 +- .../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/module_rules.rs | 3 +- crates/rspack_core/src/utils/runtime.rs | 2 +- 34 files changed, 175 insertions(+), 116 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index b2dbc5640ca0..09834d26a853 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -103,3 +103,73 @@ 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" +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 34ebfbf3c4e4..628f6673e67e 100644 --- a/crates/rspack_core/Cargo.toml +++ b/crates/rspack_core/Cargo.toml @@ -68,3 +68,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 84014cf44aea..5d5ba06cf21e 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 87e911b45a58..5f6f3579a94f 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 447197d42f35..409d15fd17f5 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 edc862a2dda8..41a3fce8b43d 100644 --- a/crates/rspack_core/src/compiler/compilation.rs +++ b/crates/rspack_core/src/compiler/compilation.rs @@ -768,11 +768,11 @@ impl Compilation { .collect(), )?; - results.iter().for_each(|module_identifier| { + for module_identifier in results.iter() { compilation .code_generated_modules .insert(*module_identifier); - }); + } Ok(()) } @@ -935,7 +935,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); @@ -1016,7 +1016,7 @@ impl Compilation { // so use filter_map to ignore them module_graph .module_identifier_by_dependency_id(dep_id) - .cloned() + .copied() }) .collect() } @@ -1042,7 +1042,7 @@ impl Compilation { .values() .flat_map(|item| item.all_dependencies()) .chain(self.global_entry.all_dependencies()) - .cloned() + .copied() .collect(), )], )?; 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 fbb115335d4c..a27a2c47ca0e 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 40839221197b..9dab42c52d6c 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 b700f751f1e1..2c31960a0afc 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 156dcd7c81f6..4ae78b71481b 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/process_dependencies.rs b/crates/rspack_core/src/compiler/make/repair/process_dependencies.rs index 9038d5e99fc6..defa8ff74a48 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 d4b7e6ead8bf..edac20319fbd 100644 --- a/crates/rspack_core/src/compiler/mod.rs +++ b/crates/rspack_core/src/compiler/mod.rs @@ -310,8 +310,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 = Path::new(&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 db14705659f4..0d4470e86eea 100644 --- a/crates/rspack_core/src/compiler/module_executor/execute.rs +++ b/crates/rspack_core/src/compiler/module_executor/execute.rs @@ -166,13 +166,11 @@ impl Task for ExecuteTask { let code_generation_results = compilation.code_generation_modules(&mut None, modules.clone())?; - code_generation_results - .iter() - .for_each(|module_identifier| { - compilation - .code_generated_modules - .insert(*module_identifier); - }); + for module_identifier in code_generation_results.iter() { + compilation + .code_generated_modules + .insert(*module_identifier); + } Handle::current().block_on(async { compilation @@ -269,7 +267,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) @@ -282,7 +280,7 @@ impl Task for ExecuteTask { CompilationAsset::new(Some(source.clone()), asset_info.inner().clone()), ); } - }); + } Ok(result) } @@ -317,8 +315,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 14bb424ac45b..924b79d00a27 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 e3a0b3bb32a4..2a7f71e92c90 100644 --- a/crates/rspack_core/src/concatenated_module.rs +++ b/crates/rspack_core/src/concatenated_module.rs @@ -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?); } @@ -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 @@ -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 8c7b6a86f989..eec76f5b2e8f 100644 --- a/crates/rspack_core/src/context_module.rs +++ b/crates/rspack_core/src/context_module.rs @@ -258,7 +258,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)), } } @@ -1260,7 +1260,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 e0e2c7fc943e..99d1e6f42899 100644 --- a/crates/rspack_core/src/context_module_factory.rs +++ b/crates/rspack_core/src/context_module_factory.rs @@ -210,7 +210,7 @@ impl ContextModuleFactory { ); (request, resource) } - None => ("".to_string(), request), + None => (String::new(), request), }; let resolve_args = ResolveArgs { @@ -281,9 +281,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 2c172f1570e4..655561d622e6 100644 --- a/crates/rspack_core/src/dependency/runtime_template.rs +++ b/crates/rspack_core/src/dependency/runtime_template.rs @@ -230,7 +230,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}"); @@ -374,7 +374,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); @@ -401,7 +401,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 26cfd1cbc8d6..7e0519182df0 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 0376a6fcfdfd..e8173a5c66a3 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 c8759e736b52..79277d89aaa3 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 f40f157c5953..a234a70d1745 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 3f38358667d8..547d7dfeff8f 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 0639d4eb9511..6324f0740953 100644 --- a/crates/rspack_core/src/normal_module_factory.rs +++ b/crates/rspack_core/src/normal_module_factory.rs @@ -311,7 +311,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("".into()) + ResourceData::new(resource.clone()).path("".into()) } else { // resource without scheme and with path let resolve_args = ResolveArgs { @@ -655,11 +655,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 } @@ -734,11 +734,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 } @@ -749,11 +749,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 d2aa39b53de0..db85fa3a4aed 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 53f9fc9dad34..0cc1b9e774f7 100644 --- a/crates/rspack_core/src/options/output.rs +++ b/crates/rspack_core/src/options/output.rs @@ -323,7 +323,7 @@ impl PublicPath { pub fn render_auto_public_path(compilation: &Compilation, filename: &str) -> String { let public_path = match Path::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 a1a15fff7612..79b4b165463a 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/resolver/resolver_impl.rs b/crates/rspack_core/src/resolver/resolver_impl.rs index 670bca2fe5d8..3f115e9b6d4a 100644 --- a/crates/rspack_core/src/resolver/resolver_impl.rs +++ b/crates/rspack_core/src/resolver/resolver_impl.rs @@ -191,13 +191,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/stats/mod.rs b/crates/rspack_core/src/stats/mod.rs index 0b0b71a3eba3..5260294ca716 100644 --- a/crates/rspack_core/src/stats/mod.rs +++ b/crates/rspack_core/src/stats/mod.rs @@ -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 f1aa83108339..dcb2741bfe15 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 154dbf89134e..4cada922af1e 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 e153f3b2f5b8..bc4c84681097 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/module_rules.rs b/crates/rspack_core/src/utils/module_rules.rs index ada9c92903ae..045a52ecfd13 100644 --- a/crates/rspack_core/src/utils/module_rules.rs +++ b/crates/rspack_core/src/utils/module_rules.rs @@ -55,8 +55,7 @@ pub async fn module_rule_matcher<'a>( resource_data .resource_path .as_deref() - .map(|p| p.to_string_lossy()) - .unwrap_or_else(|| Cow::Borrowed("")) + .map_or_else(|| Cow::Borrowed(""), |p| p.to_string_lossy()) }; if let Some(test_rule) = &module_rule.test diff --git a/crates/rspack_core/src/utils/runtime.rs b/crates/rspack_core/src/utils/runtime.rs index dec7d993d226..5c4b12330452 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 })