From 386d438e173f4c505798361d46f901c7a56567fb Mon Sep 17 00:00:00 2001 From: Johann Hemmann Date: Mon, 22 Jan 2024 00:42:46 +0100 Subject: [PATCH 01/17] skip_while_next --- Cargo.toml | 1 - crates/ide-completion/src/context/analysis.rs | 3 +-- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index d5f9740c6d..099ac296e4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -179,7 +179,6 @@ new_without_default = "allow" non_canonical_clone_impl = "allow" non_canonical_partial_ord_impl = "allow" self_named_constructors = "allow" -skip_while_next = "allow" too_many_arguments = "allow" toplevel_ref_arg = "allow" type_complexity = "allow" diff --git a/crates/ide-completion/src/context/analysis.rs b/crates/ide-completion/src/context/analysis.rs index 65ecaf6bac..c06b64df1c 100644 --- a/crates/ide-completion/src/context/analysis.rs +++ b/crates/ide-completion/src/context/analysis.rs @@ -1267,8 +1267,7 @@ fn pattern_context_for( pat .syntax() .ancestors() - .skip_while(|it| ast::Pat::can_cast(it.kind())) - .next() + .find(|it| !ast::Pat::can_cast(it.kind())) .map_or((PatternRefutability::Irrefutable, false), |node| { let refutability = match_ast! { match node { From daa20725c5e651d2e63f7fbd7d2a8654e9afb6d7 Mon Sep 17 00:00:00 2001 From: Johann Hemmann Date: Mon, 22 Jan 2024 01:00:13 +0100 Subject: [PATCH 02/17] toplevel_ref_arg --- Cargo.toml | 1 - crates/hir-def/src/import_map.rs | 4 ++-- crates/hir/src/lib.rs | 2 +- 3 files changed, 3 insertions(+), 4 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 099ac296e4..f49593db5f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -180,7 +180,6 @@ non_canonical_clone_impl = "allow" non_canonical_partial_ord_impl = "allow" self_named_constructors = "allow" too_many_arguments = "allow" -toplevel_ref_arg = "allow" type_complexity = "allow" unnecessary_cast = "allow" unnecessary_filter_map = "allow" diff --git a/crates/hir-def/src/import_map.rs b/crates/hir-def/src/import_map.rs index 66d9cf54da..5d096c7a5e 100644 --- a/crates/hir-def/src/import_map.rs +++ b/crates/hir-def/src/import_map.rs @@ -396,7 +396,7 @@ impl Query { pub fn search_dependencies( db: &dyn DefDatabase, krate: CrateId, - ref query: Query, + query: &Query, ) -> FxHashSet { let _p = tracing::span!(tracing::Level::INFO, "search_dependencies", ?query).entered(); @@ -516,7 +516,7 @@ mod tests { }) .expect("could not find crate"); - let actual = search_dependencies(db.upcast(), krate, query) + let actual = search_dependencies(db.upcast(), krate, &query) .into_iter() .filter_map(|dependency| { let dependency_krate = dependency.krate(db.upcast())?; diff --git a/crates/hir/src/lib.rs b/crates/hir/src/lib.rs index 28decd4ce7..2c5474c5c8 100644 --- a/crates/hir/src/lib.rs +++ b/crates/hir/src/lib.rs @@ -236,7 +236,7 @@ impl Crate { query: import_map::Query, ) -> impl Iterator> { let _p = tracing::span!(tracing::Level::INFO, "query_external_importables"); - import_map::search_dependencies(db, self.into(), query).into_iter().map(|item| { + import_map::search_dependencies(db, self.into(), &query).into_iter().map(|item| { match ItemInNs::from(item) { ItemInNs::Types(mod_id) | ItemInNs::Values(mod_id) => Either::Left(mod_id), ItemInNs::Macros(mac_id) => Either::Right(mac_id), From de6f9561f2822b87aede9f5edc6e14951da570ba Mon Sep 17 00:00:00 2001 From: Johann Hemmann Date: Mon, 22 Jan 2024 01:00:50 +0100 Subject: [PATCH 03/17] unnecessary_cast --- Cargo.toml | 1 - crates/hir-def/src/import_map.rs | 4 ++-- crates/hir/src/lib.rs | 4 ++-- 3 files changed, 4 insertions(+), 5 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index f49593db5f..8d861f2a18 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -181,7 +181,6 @@ non_canonical_partial_ord_impl = "allow" self_named_constructors = "allow" too_many_arguments = "allow" type_complexity = "allow" -unnecessary_cast = "allow" unnecessary_filter_map = "allow" unnecessary_lazy_evaluations = "allow" unnecessary_mut_passed = "allow" diff --git a/crates/hir-def/src/import_map.rs b/crates/hir-def/src/import_map.rs index 5d096c7a5e..c698510ca9 100644 --- a/crates/hir-def/src/import_map.rs +++ b/crates/hir-def/src/import_map.rs @@ -297,7 +297,7 @@ impl SearchMode { SearchMode::Exact => candidate.eq_ignore_ascii_case(query), SearchMode::Prefix => { query.len() <= candidate.len() && { - let prefix = &candidate[..query.len() as usize]; + let prefix = &candidate[..query.len()]; if case_sensitive { prefix == query } else { @@ -446,7 +446,7 @@ fn search_maps( let end = (value & 0xFFFF_FFFF) as usize; let start = (value >> 32) as usize; let ImportMap { item_to_info_map, importables, .. } = &*import_maps[import_map_idx]; - let importables = &importables[start as usize..end]; + let importables = &importables[start..end]; let iter = importables .iter() diff --git a/crates/hir/src/lib.rs b/crates/hir/src/lib.rs index 2c5474c5c8..1e21045e98 100644 --- a/crates/hir/src/lib.rs +++ b/crates/hir/src/lib.rs @@ -903,7 +903,7 @@ fn emit_def_diagnostic_( } DefDiagnosticKind::InvalidDeriveTarget { ast, id } => { let node = ast.to_node(db.upcast()); - let derive = node.attrs().nth(*id as usize); + let derive = node.attrs().nth(*id); match derive { Some(derive) => { acc.push( @@ -918,7 +918,7 @@ fn emit_def_diagnostic_( } DefDiagnosticKind::MalformedDerive { ast, id } => { let node = ast.to_node(db.upcast()); - let derive = node.attrs().nth(*id as usize); + let derive = node.attrs().nth(*id); match derive { Some(derive) => { acc.push( From f15ee8a380c18cf7d9d53a91c2b4a6d6161e9877 Mon Sep 17 00:00:00 2001 From: Johann Hemmann Date: Mon, 22 Jan 2024 01:11:59 +0100 Subject: [PATCH 04/17] unnecessary_filter_map --- Cargo.toml | 1 - crates/ide-completion/src/tests.rs | 25 ++++++++---------------- crates/rust-analyzer/src/lsp/to_proto.rs | 12 +++++------- 3 files changed, 13 insertions(+), 25 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 8d861f2a18..b8f273af47 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -181,7 +181,6 @@ non_canonical_partial_ord_impl = "allow" self_named_constructors = "allow" too_many_arguments = "allow" type_complexity = "allow" -unnecessary_filter_map = "allow" unnecessary_lazy_evaluations = "allow" unnecessary_mut_passed = "allow" useless_conversion = "allow" diff --git a/crates/ide-completion/src/tests.rs b/crates/ide-completion/src/tests.rs index c421be51a0..154b69875a 100644 --- a/crates/ide-completion/src/tests.rs +++ b/crates/ide-completion/src/tests.rs @@ -210,23 +210,14 @@ pub(crate) fn check_edit_with_config( let mut combined_edit = completion.text_edit.clone(); - resolve_completion_edits( - &db, - &config, - position, - completion - .import_to_add - .iter() - .cloned() - .filter_map(|(import_path, import_name)| Some((import_path, import_name))), - ) - .into_iter() - .flatten() - .for_each(|text_edit| { - combined_edit.union(text_edit).expect( - "Failed to apply completion resolve changes: change ranges overlap, but should not", - ) - }); + resolve_completion_edits(&db, &config, position, completion.import_to_add.iter().cloned()) + .into_iter() + .flatten() + .for_each(|text_edit| { + combined_edit.union(text_edit).expect( + "Failed to apply completion resolve changes: change ranges overlap, but should not", + ) + }); combined_edit.apply(&mut actual); assert_eq_text!(&ra_fixture_after, &actual) diff --git a/crates/rust-analyzer/src/lsp/to_proto.rs b/crates/rust-analyzer/src/lsp/to_proto.rs index f221863aff..d363ac69fd 100644 --- a/crates/rust-analyzer/src/lsp/to_proto.rs +++ b/crates/rust-analyzer/src/lsp/to_proto.rs @@ -312,16 +312,14 @@ fn completion_item( set_score(&mut lsp_item, max_relevance, item.relevance); if config.completion().enable_imports_on_the_fly && !item.import_to_add.is_empty() { - let imports: Vec<_> = item + let imports = item .import_to_add .into_iter() - .filter_map(|(import_path, import_name)| { - Some(lsp_ext::CompletionImport { - full_import_path: import_path, - imported_name: import_name, - }) + .map(|(import_path, import_name)| lsp_ext::CompletionImport { + full_import_path: import_path, + imported_name: import_name, }) - .collect(); + .collect::>(); if !imports.is_empty() { let data = lsp_ext::CompletionResolveData { position: tdpp.clone(), imports }; lsp_item.data = Some(to_value(data).unwrap()); From c4302eaa566eb74083c4233a56788d32f147a88d Mon Sep 17 00:00:00 2001 From: Johann Hemmann Date: Mon, 22 Jan 2024 01:19:28 +0100 Subject: [PATCH 05/17] unnecessary_lazy_evaluations --- Cargo.toml | 1 - crates/hir-def/src/hir/format_args.rs | 1 + crates/hir-expand/src/attrs.rs | 2 +- crates/hir/src/attrs.rs | 2 +- 4 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index b8f273af47..20bd27c63e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -181,7 +181,6 @@ non_canonical_partial_ord_impl = "allow" self_named_constructors = "allow" too_many_arguments = "allow" type_complexity = "allow" -unnecessary_lazy_evaluations = "allow" unnecessary_mut_passed = "allow" useless_conversion = "allow" useless_format = "allow" diff --git a/crates/hir-def/src/hir/format_args.rs b/crates/hir-def/src/hir/format_args.rs index 113f9441a0..dc09b0ef3e 100644 --- a/crates/hir-def/src/hir/format_args.rs +++ b/crates/hir-def/src/hir/format_args.rs @@ -166,6 +166,7 @@ enum PositionUsedAs { } use PositionUsedAs::*; +#[allow(clippy::unnecessary_lazy_evaluations)] pub(crate) fn parse( s: &ast::String, fmt_snippet: Option, diff --git a/crates/hir-expand/src/attrs.rs b/crates/hir-expand/src/attrs.rs index b0b2501ce9..c20c1639e1 100644 --- a/crates/hir-expand/src/attrs.rs +++ b/crates/hir-expand/src/attrs.rs @@ -230,7 +230,7 @@ impl Attr { ) ) }) - .unwrap_or_else(|| tt.len()); + .unwrap_or(tt.len()); let (path, input) = tt.split_at(path_end); let path = Interned::new(ModPath::from_tt(db, path)?); diff --git a/crates/hir/src/attrs.rs b/crates/hir/src/attrs.rs index f2b9db669e..8978be8133 100644 --- a/crates/hir/src/attrs.rs +++ b/crates/hir/src/attrs.rs @@ -297,7 +297,7 @@ fn as_module_def_if_namespace_matches( AssocItem::TypeAlias(it) => (ModuleDef::TypeAlias(it), Namespace::Types), }; - (ns.unwrap_or(expected_ns) == expected_ns).then(|| DocLinkDef::ModuleDef(def)) + (ns.unwrap_or(expected_ns) == expected_ns).then_some(DocLinkDef::ModuleDef(def)) } fn modpath_from_str(link: &str) -> Option { From f191b807990cce67a7662254127e9b6adb030d8d Mon Sep 17 00:00:00 2001 From: Johann Hemmann Date: Mon, 22 Jan 2024 01:19:50 +0100 Subject: [PATCH 06/17] Refactor --- crates/hir-def/src/hir/format_args.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/hir-def/src/hir/format_args.rs b/crates/hir-def/src/hir/format_args.rs index dc09b0ef3e..22864b3289 100644 --- a/crates/hir-def/src/hir/format_args.rs +++ b/crates/hir-def/src/hir/format_args.rs @@ -178,9 +178,9 @@ pub(crate) fn parse( let text = s.text_without_quotes(); let str_style = match s.quote_offsets() { Some(offsets) => { - let raw = u32::from(offsets.quotes.0.len()) - 1; + let raw = usize::from(offsets.quotes.0.len()) - 1; // subtract 1 for the `r` prefix - (raw != 0).then(|| raw as usize - 1) + (raw != 0).then(|| raw - 1) } None => None, }; From e7d0deac538af1d7372608bb02f6caa8bf834de2 Mon Sep 17 00:00:00 2001 From: Johann Hemmann Date: Mon, 22 Jan 2024 01:25:39 +0100 Subject: [PATCH 07/17] unnecessary_mut_passed --- Cargo.toml | 1 - crates/hir-ty/src/mir/lower/pattern_matching.rs | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 20bd27c63e..9fb04589e2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -181,7 +181,6 @@ non_canonical_partial_ord_impl = "allow" self_named_constructors = "allow" too_many_arguments = "allow" type_complexity = "allow" -unnecessary_mut_passed = "allow" useless_conversion = "allow" useless_format = "allow" wildcard_in_or_patterns = "allow" diff --git a/crates/hir-ty/src/mir/lower/pattern_matching.rs b/crates/hir-ty/src/mir/lower/pattern_matching.rs index 65ab12929d..8202bac532 100644 --- a/crates/hir-ty/src/mir/lower/pattern_matching.rs +++ b/crates/hir-ty/src/mir/lower/pattern_matching.rs @@ -114,7 +114,7 @@ impl MirLowerCtx<'_> { index: i as u32, })) }), - &mut cond_place, + &cond_place, mode, )? } From b73ee2f50df1488be42a0fb9b2f7d915a7cae49d Mon Sep 17 00:00:00 2001 From: Johann Hemmann Date: Mon, 22 Jan 2024 01:31:50 +0100 Subject: [PATCH 08/17] useless_conversion --- Cargo.toml | 1 - crates/hir-def/src/body/tests.rs | 4 ++-- crates/hir-def/src/data.rs | 2 +- crates/hir-def/src/nameres/path_resolution.rs | 2 +- crates/hir-def/src/per_ns.rs | 6 ++---- crates/hir/src/attrs.rs | 7 +++---- crates/rust-analyzer/src/config.rs | 2 +- 7 files changed, 10 insertions(+), 14 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 9fb04589e2..640f478b0c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -181,7 +181,6 @@ non_canonical_partial_ord_impl = "allow" self_named_constructors = "allow" too_many_arguments = "allow" type_complexity = "allow" -useless_conversion = "allow" useless_format = "allow" wildcard_in_or_patterns = "allow" wrong_self_convention = "allow" diff --git a/crates/hir-def/src/body/tests.rs b/crates/hir-def/src/body/tests.rs index a76ddffb41..a27ffe2167 100644 --- a/crates/hir-def/src/body/tests.rs +++ b/crates/hir-def/src/body/tests.rs @@ -256,7 +256,7 @@ impl SsrError { "##, ); - assert_eq!(db.body_with_source_map(def.into()).1.diagnostics(), &[]); + assert_eq!(db.body_with_source_map(def).1.diagnostics(), &[]); expect![[r#" fn main() { _ = $crate::error::SsrError::new( @@ -309,7 +309,7 @@ fn f() { "#, ); - let (_, source_map) = db.body_with_source_map(def.into()); + let (_, source_map) = db.body_with_source_map(def); assert_eq!(source_map.diagnostics(), &[]); for (_, def_map) in body.blocks(&db) { diff --git a/crates/hir-def/src/data.rs b/crates/hir-def/src/data.rs index 73fbad5e67..7ce05b64d0 100644 --- a/crates/hir-def/src/data.rs +++ b/crates/hir-def/src/data.rs @@ -782,7 +782,7 @@ impl<'a> AssocItemCollector<'a> { self.diagnostics.push(DefDiagnostic::macro_expansion_parse_error( self.module_id.local_id, error_call_kind(), - errors.into(), + errors, )); } diff --git a/crates/hir-def/src/nameres/path_resolution.rs b/crates/hir-def/src/nameres/path_resolution.rs index 2c7e222791..70da0ef8e1 100644 --- a/crates/hir-def/src/nameres/path_resolution.rs +++ b/crates/hir-def/src/nameres/path_resolution.rs @@ -475,7 +475,7 @@ impl DefMap { let macro_use_prelude = || { self.macro_use_prelude.get(name).map_or(PerNs::none(), |&(it, _extern_crate)| { PerNs::macros( - it.into(), + it, Visibility::Public, // FIXME? None, // extern_crate.map(ImportOrExternCrate::ExternCrate), diff --git a/crates/hir-def/src/per_ns.rs b/crates/hir-def/src/per_ns.rs index 6a62ef6970..23d41cc0d8 100644 --- a/crates/hir-def/src/per_ns.rs +++ b/crates/hir-def/src/per_ns.rs @@ -131,13 +131,11 @@ impl PerNs { .into_iter() .chain( self.values - .map(|it| (ItemInNs::Values(it.0), it.2.map(ImportOrExternCrate::Import))) - .into_iter(), + .map(|it| (ItemInNs::Values(it.0), it.2.map(ImportOrExternCrate::Import))), ) .chain( self.macros - .map(|it| (ItemInNs::Macros(it.0), it.2.map(ImportOrExternCrate::Import))) - .into_iter(), + .map(|it| (ItemInNs::Macros(it.0), it.2.map(ImportOrExternCrate::Import))), ) } } diff --git a/crates/hir/src/attrs.rs b/crates/hir/src/attrs.rs index 8978be8133..5c369f42e6 100644 --- a/crates/hir/src/attrs.rs +++ b/crates/hir/src/attrs.rs @@ -239,10 +239,9 @@ fn resolve_impl_trait_item( ) -> Option { let canonical = ty.canonical(); let krate = ty.krate(db); - let environment = resolver.generic_def().map_or_else( - || crate::TraitEnvironment::empty(krate.id).into(), - |d| db.trait_environment(d), - ); + let environment = resolver + .generic_def() + .map_or_else(|| crate::TraitEnvironment::empty(krate.id), |d| db.trait_environment(d)); let traits_in_scope = resolver.traits_in_scope(db.upcast()); let mut result = None; diff --git a/crates/rust-analyzer/src/config.rs b/crates/rust-analyzer/src/config.rs index eeb28b8fe4..54d96ab138 100644 --- a/crates/rust-analyzer/src/config.rs +++ b/crates/rust-analyzer/src/config.rs @@ -1744,7 +1744,7 @@ impl Config { } pub fn main_loop_num_threads(&self) -> usize { - self.data.numThreads.unwrap_or(num_cpus::get_physical().try_into().unwrap_or(1)) + self.data.numThreads.unwrap_or(num_cpus::get_physical()) } pub fn typing_autoclose_angle(&self) -> bool { From b176cf2478ae9bc7b0c293c8cf0669d6e64e9474 Mon Sep 17 00:00:00 2001 From: Johann Hemmann Date: Mon, 22 Jan 2024 01:36:39 +0100 Subject: [PATCH 09/17] useless_format --- Cargo.toml | 1 - crates/hir-def/src/body/pretty.rs | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 640f478b0c..8296c91295 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -181,7 +181,6 @@ non_canonical_partial_ord_impl = "allow" self_named_constructors = "allow" too_many_arguments = "allow" type_complexity = "allow" -useless_format = "allow" wildcard_in_or_patterns = "allow" wrong_self_convention = "allow" diff --git a/crates/hir-def/src/body/pretty.rs b/crates/hir-def/src/body/pretty.rs index 0f2b279670..b821b91b89 100644 --- a/crates/hir-def/src/body/pretty.rs +++ b/crates/hir-def/src/body/pretty.rs @@ -33,7 +33,7 @@ pub(super) fn print_body_hir(db: &dyn DefDatabase, body: &Body, owner: DefWithBo } ) }), - DefWithBodyId::InTypeConstId(_) => format!("In type const = "), + DefWithBodyId::InTypeConstId(_) => "In type const = ".to_string(), DefWithBodyId::VariantId(it) => { let loc = it.lookup(db); let enum_loc = loc.parent.lookup(db); From 0adb4d16856d22ba6a63b659d7dbd37b514b2d0c Mon Sep 17 00:00:00 2001 From: Johann Hemmann Date: Mon, 22 Jan 2024 01:41:42 +0100 Subject: [PATCH 10/17] wildcard_in_or_patterns --- Cargo.toml | 1 - crates/hir-ty/src/inhabitedness.rs | 3 +-- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 8296c91295..0d42f9c655 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -181,7 +181,6 @@ non_canonical_partial_ord_impl = "allow" self_named_constructors = "allow" too_many_arguments = "allow" type_complexity = "allow" -wildcard_in_or_patterns = "allow" wrong_self_convention = "allow" ## warn at following lints diff --git a/crates/hir-ty/src/inhabitedness.rs b/crates/hir-ty/src/inhabitedness.rs index a63556f450..532b650e8f 100644 --- a/crates/hir-ty/src/inhabitedness.rs +++ b/crates/hir-ty/src/inhabitedness.rs @@ -84,8 +84,7 @@ impl TypeVisitor for UninhabitedFrom<'_> { Some(0) | None => CONTINUE_OPAQUELY_INHABITED, Some(1..) => item_ty.super_visit_with(self, outer_binder), }, - - TyKind::Ref(..) | _ => CONTINUE_OPAQUELY_INHABITED, + _ => CONTINUE_OPAQUELY_INHABITED, }; self.recursive_ty.remove(ty); self.max_depth += 1; From c4688343de3b9a99aa0b0899195abaf037232372 Mon Sep 17 00:00:00 2001 From: Johann Hemmann Date: Mon, 22 Jan 2024 01:50:51 +0100 Subject: [PATCH 11/17] derivable_impls --- Cargo.toml | 1 - crates/hir-def/src/per_ns.rs | 8 +------- 2 files changed, 1 insertion(+), 8 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 0d42f9c655..6350027ddb 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -168,7 +168,6 @@ new_ret_no_self = "allow" ## Following lints should be tackled at some point borrowed_box = "allow" borrow_deref_ref = "allow" -derivable_impls = "allow" derived_hash_with_manual_eq = "allow" field_reassign_with_default = "allow" forget_non_drop = "allow" diff --git a/crates/hir-def/src/per_ns.rs b/crates/hir-def/src/per_ns.rs index 23d41cc0d8..36ab62d0f7 100644 --- a/crates/hir-def/src/per_ns.rs +++ b/crates/hir-def/src/per_ns.rs @@ -16,19 +16,13 @@ pub enum Namespace { Macros, } -#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] +#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)] pub struct PerNs { pub types: Option<(ModuleDefId, Visibility, Option)>, pub values: Option<(ModuleDefId, Visibility, Option)>, pub macros: Option<(MacroId, Visibility, Option)>, } -impl Default for PerNs { - fn default() -> Self { - PerNs { types: None, values: None, macros: None } - } -} - impl PerNs { pub fn none() -> PerNs { PerNs { types: None, values: None, macros: None } From dd9f27b8d361180d6df350ac95087d739e3e9023 Mon Sep 17 00:00:00 2001 From: Johann Hemmann Date: Mon, 22 Jan 2024 01:54:55 +0100 Subject: [PATCH 12/17] borrow_deref_ref --- Cargo.toml | 1 - crates/hir-def/src/nameres/collector.rs | 2 +- crates/hir-def/src/test_db.rs | 4 ++-- 3 files changed, 3 insertions(+), 4 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 6350027ddb..d29f46ca2b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -167,7 +167,6 @@ new_ret_no_self = "allow" ## Following lints should be tackled at some point borrowed_box = "allow" -borrow_deref_ref = "allow" derived_hash_with_manual_eq = "allow" field_reassign_with_default = "allow" forget_non_drop = "allow" diff --git a/crates/hir-def/src/nameres/collector.rs b/crates/hir-def/src/nameres/collector.rs index bdef9c8a93..fb6fd867a1 100644 --- a/crates/hir-def/src/nameres/collector.rs +++ b/crates/hir-def/src/nameres/collector.rs @@ -1924,7 +1924,7 @@ impl ModCollector<'_, '_> { item_tree: self.item_tree, mod_dir, } - .collect_in_top_module(&*items); + .collect_in_top_module(items); if is_macro_use { self.import_all_legacy_macros(module_id); } diff --git a/crates/hir-def/src/test_db.rs b/crates/hir-def/src/test_db.rs index c992c3c920..9edb03c7ca 100644 --- a/crates/hir-def/src/test_db.rs +++ b/crates/hir-def/src/test_db.rs @@ -41,13 +41,13 @@ impl Default for TestDB { impl Upcast for TestDB { fn upcast(&self) -> &(dyn ExpandDatabase + 'static) { - &*self + self } } impl Upcast for TestDB { fn upcast(&self) -> &(dyn DefDatabase + 'static) { - &*self + self } } From 04ccef80cbe066ab0228fc93ccba159f47a2a5f0 Mon Sep 17 00:00:00 2001 From: Johann Hemmann Date: Mon, 22 Jan 2024 02:15:29 +0100 Subject: [PATCH 13/17] field_reassign_with_default --- Cargo.toml | 1 - crates/ide/src/hover.rs | 1 + crates/rust-analyzer/src/cli/analysis_stats.rs | 12 +++++++----- crates/rust-analyzer/src/cli/diagnostics.rs | 4 ++-- crates/rust-analyzer/src/cli/lsif.rs | 4 ++-- crates/rust-analyzer/src/cli/run_tests.rs | 4 ++-- crates/rust-analyzer/src/cli/rustc_tests.rs | 4 ++-- crates/rust-analyzer/src/cli/ssr.rs | 4 ++-- 8 files changed, 18 insertions(+), 16 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index d29f46ca2b..7eb5ab9d61 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -168,7 +168,6 @@ new_ret_no_self = "allow" ## Following lints should be tackled at some point borrowed_box = "allow" derived_hash_with_manual_eq = "allow" -field_reassign_with_default = "allow" forget_non_drop = "allow" format_collect = "allow" large_enum_variant = "allow" diff --git a/crates/ide/src/hover.rs b/crates/ide/src/hover.rs index 77a06a97e2..19b181ae3b 100644 --- a/crates/ide/src/hover.rs +++ b/crates/ide/src/hover.rs @@ -120,6 +120,7 @@ pub(crate) fn hover( Some(res) } +#[allow(clippy::field_reassign_with_default)] fn hover_simple( sema: &Semantics<'_, RootDatabase>, FilePosition { file_id, offset }: FilePosition, diff --git a/crates/rust-analyzer/src/cli/analysis_stats.rs b/crates/rust-analyzer/src/cli/analysis_stats.rs index c33fbddcef..31bdd2a0e8 100644 --- a/crates/rust-analyzer/src/cli/analysis_stats.rs +++ b/crates/rust-analyzer/src/cli/analysis_stats.rs @@ -58,12 +58,14 @@ impl flags::AnalysisStats { Rand32::new(seed) }; - let mut cargo_config = CargoConfig::default(); - cargo_config.sysroot = match self.no_sysroot { - true => None, - false => Some(RustLibSource::Discover), + let cargo_config = CargoConfig { + sysroot: match self.no_sysroot { + true => None, + false => Some(RustLibSource::Discover), + }, + sysroot_query_metadata: self.query_sysroot_metadata, + ..Default::default() }; - cargo_config.sysroot_query_metadata = self.query_sysroot_metadata; let no_progress = &|_| (); let mut db_load_sw = self.stop_watch(); diff --git a/crates/rust-analyzer/src/cli/diagnostics.rs b/crates/rust-analyzer/src/cli/diagnostics.rs index 0182cf5402..6d2e97be20 100644 --- a/crates/rust-analyzer/src/cli/diagnostics.rs +++ b/crates/rust-analyzer/src/cli/diagnostics.rs @@ -13,8 +13,8 @@ use crate::cli::flags; impl flags::Diagnostics { pub fn run(self) -> anyhow::Result<()> { - let mut cargo_config = CargoConfig::default(); - cargo_config.sysroot = Some(RustLibSource::Discover); + let cargo_config = + CargoConfig { sysroot: Some(RustLibSource::Discover), ..Default::default() }; let with_proc_macro_server = if let Some(p) = &self.proc_macro_srv { let path = vfs::AbsPathBuf::assert(std::env::current_dir()?.join(p)); ProcMacroServerChoice::Explicit(path) diff --git a/crates/rust-analyzer/src/cli/lsif.rs b/crates/rust-analyzer/src/cli/lsif.rs index 2138ecead5..64f965e22a 100644 --- a/crates/rust-analyzer/src/cli/lsif.rs +++ b/crates/rust-analyzer/src/cli/lsif.rs @@ -287,8 +287,8 @@ impl flags::Lsif { pub fn run(self) -> anyhow::Result<()> { eprintln!("Generating LSIF started..."); let now = Instant::now(); - let mut cargo_config = CargoConfig::default(); - cargo_config.sysroot = Some(RustLibSource::Discover); + let cargo_config = + CargoConfig { sysroot: Some(RustLibSource::Discover), ..Default::default() }; let no_progress = &|_| (); let load_cargo_config = LoadCargoConfig { load_out_dirs_from_check: true, diff --git a/crates/rust-analyzer/src/cli/run_tests.rs b/crates/rust-analyzer/src/cli/run_tests.rs index e170419915..d07dcdec25 100644 --- a/crates/rust-analyzer/src/cli/run_tests.rs +++ b/crates/rust-analyzer/src/cli/run_tests.rs @@ -13,8 +13,8 @@ use crate::cli::{flags, full_name_of_item, Result}; impl flags::RunTests { pub fn run(self) -> Result<()> { - let mut cargo_config = CargoConfig::default(); - cargo_config.sysroot = Some(RustLibSource::Discover); + let cargo_config = + CargoConfig { sysroot: Some(RustLibSource::Discover), ..Default::default() }; let load_cargo_config = LoadCargoConfig { load_out_dirs_from_check: true, with_proc_macro_server: ProcMacroServerChoice::Sysroot, diff --git a/crates/rust-analyzer/src/cli/rustc_tests.rs b/crates/rust-analyzer/src/cli/rustc_tests.rs index 522eb53128..be7e434aca 100644 --- a/crates/rust-analyzer/src/cli/rustc_tests.rs +++ b/crates/rust-analyzer/src/cli/rustc_tests.rs @@ -59,8 +59,8 @@ impl Tester { path.push("ra-rustc-test.rs"); let tmp_file = AbsPathBuf::try_from(path).unwrap(); std::fs::write(&tmp_file, "")?; - let mut cargo_config = CargoConfig::default(); - cargo_config.sysroot = Some(RustLibSource::Discover); + let cargo_config = + CargoConfig { sysroot: Some(RustLibSource::Discover), ..Default::default() }; let workspace = ProjectWorkspace::DetachedFiles { files: vec![tmp_file.clone()], sysroot: Ok(Sysroot::discover( diff --git a/crates/rust-analyzer/src/cli/ssr.rs b/crates/rust-analyzer/src/cli/ssr.rs index f87dcb889a..8f11d82f8f 100644 --- a/crates/rust-analyzer/src/cli/ssr.rs +++ b/crates/rust-analyzer/src/cli/ssr.rs @@ -10,8 +10,8 @@ use crate::cli::flags; impl flags::Ssr { pub fn run(self) -> anyhow::Result<()> { use ide_db::base_db::SourceDatabaseExt; - let mut cargo_config = CargoConfig::default(); - cargo_config.sysroot = Some(RustLibSource::Discover); + let cargo_config = + CargoConfig { sysroot: Some(RustLibSource::Discover), ..Default::default() }; let load_cargo_config = LoadCargoConfig { load_out_dirs_from_check: true, with_proc_macro_server: ProcMacroServerChoice::Sysroot, From e7e09e775019171a31649ef3256507981e6c085c Mon Sep 17 00:00:00 2001 From: Johann Hemmann Date: Mon, 22 Jan 2024 02:43:28 +0100 Subject: [PATCH 14/17] large_enum_variant --- Cargo.toml | 1 - crates/flycheck/src/lib.rs | 6 ++++-- crates/proc-macro-api/src/lib.rs | 2 +- crates/proc-macro-api/src/msg.rs | 2 +- crates/proc-macro-srv-cli/src/main.rs | 6 ++++-- crates/project-model/src/workspace.rs | 13 +++++++------ 6 files changed, 17 insertions(+), 13 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 7eb5ab9d61..365f7db374 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -170,7 +170,6 @@ borrowed_box = "allow" derived_hash_with_manual_eq = "allow" forget_non_drop = "allow" format_collect = "allow" -large_enum_variant = "allow" needless_doctest_main = "allow" new_without_default = "allow" non_canonical_clone_impl = "allow" diff --git a/crates/flycheck/src/lib.rs b/crates/flycheck/src/lib.rs index 68faca51e8..22603842a1 100644 --- a/crates/flycheck/src/lib.rs +++ b/crates/flycheck/src/lib.rs @@ -493,7 +493,9 @@ impl CargoActor { // Skip certain kinds of messages to only spend time on what's useful JsonMessage::Cargo(message) => match message { cargo_metadata::Message::CompilerArtifact(artifact) if !artifact.fresh => { - self.sender.send(CargoMessage::CompilerArtifact(artifact)).unwrap(); + self.sender + .send(CargoMessage::CompilerArtifact(Box::new(artifact))) + .unwrap(); } cargo_metadata::Message::CompilerMessage(msg) => { self.sender.send(CargoMessage::Diagnostic(msg.message)).unwrap(); @@ -538,7 +540,7 @@ impl CargoActor { } enum CargoMessage { - CompilerArtifact(cargo_metadata::Artifact), + CompilerArtifact(Box), Diagnostic(Diagnostic), } diff --git a/crates/proc-macro-api/src/lib.rs b/crates/proc-macro-api/src/lib.rs index 345608d3d0..379d184dd6 100644 --- a/crates/proc-macro-api/src/lib.rs +++ b/crates/proc-macro-api/src/lib.rs @@ -184,7 +184,7 @@ impl ProcMacro { .process .lock() .unwrap_or_else(|e| e.into_inner()) - .send_task(msg::Request::ExpandMacro(task))?; + .send_task(msg::Request::ExpandMacro(Box::new(task)))?; match response { msg::Response::ExpandMacro(it) => { diff --git a/crates/proc-macro-api/src/msg.rs b/crates/proc-macro-api/src/msg.rs index 557ddba5c7..e28fe387b8 100644 --- a/crates/proc-macro-api/src/msg.rs +++ b/crates/proc-macro-api/src/msg.rs @@ -29,7 +29,7 @@ pub enum Request { /// Since [`NO_VERSION_CHECK_VERSION`] ListMacros { dylib_path: PathBuf }, /// Since [`NO_VERSION_CHECK_VERSION`] - ExpandMacro(ExpandMacro), + ExpandMacro(Box), /// Since [`VERSION_CHECK_VERSION`] ApiVersionCheck {}, /// Since [`RUST_ANALYZER_SPAN_SUPPORT`] diff --git a/crates/proc-macro-srv-cli/src/main.rs b/crates/proc-macro-srv-cli/src/main.rs index af9a03826f..a36200cdb4 100644 --- a/crates/proc-macro-srv-cli/src/main.rs +++ b/crates/proc-macro-srv-cli/src/main.rs @@ -45,9 +45,11 @@ fn run() -> io::Result<()> { msg::Response::ListMacros(srv.list_macros(&dylib_path)) } msg::Request::ExpandMacro(task) => match srv.span_mode() { - msg::SpanMode::Id => msg::Response::ExpandMacro(srv.expand(task).map(|(it, _)| it)), + msg::SpanMode::Id => { + msg::Response::ExpandMacro(srv.expand(*task).map(|(it, _)| it)) + } msg::SpanMode::RustAnalyzer => msg::Response::ExpandMacroExtended( - srv.expand(task).map(|(tree, span_data_table)| msg::ExpandMacroExtended { + srv.expand(*task).map(|(tree, span_data_table)| msg::ExpandMacroExtended { tree, span_data_table, }), diff --git a/crates/project-model/src/workspace.rs b/crates/project-model/src/workspace.rs index e6e2fa7a97..8c5ea0619a 100644 --- a/crates/project-model/src/workspace.rs +++ b/crates/project-model/src/workspace.rs @@ -60,7 +60,7 @@ pub enum ProjectWorkspace { cargo: CargoWorkspace, build_scripts: WorkspaceBuildScripts, sysroot: Result>, - rustc: Result<(CargoWorkspace, WorkspaceBuildScripts), Option>, + rustc: Result, Option>, /// Holds cfg flags for the current target. We get those by running /// `rustc --print cfg`. /// @@ -119,7 +119,7 @@ impl fmt::Debug for ProjectWorkspace { .field("sysroot", &sysroot.is_ok()) .field( "n_rustc_compiler_crates", - &rustc.as_ref().map_or(0, |(rc, _)| rc.packages().len()), + &rustc.as_ref().map(|a| a.as_ref()).map_or(0, |(rc, _)| rc.packages().len()), ) .field("n_rustc_cfg", &rustc_cfg.len()) .field("n_cfg_overrides", &cfg_overrides.len()) @@ -265,7 +265,7 @@ impl ProjectWorkspace { cargo_toml.parent(), &config.extra_env, ); - Ok((workspace, buildscripts)) + Ok(Box::new((workspace, buildscripts))) } Err(e) => { tracing::error!( @@ -603,7 +603,7 @@ impl ProjectWorkspace { PackageRoot { is_local, include, exclude } }) .chain(mk_sysroot(sysroot.as_ref(), Some(cargo.workspace_root()))) - .chain(rustc.iter().flat_map(|(rustc, _)| { + .chain(rustc.iter().map(|a| a.as_ref()).flat_map(|(rustc, _)| { rustc.packages().map(move |krate| PackageRoot { is_local: false, include: vec![rustc[krate].manifest.parent().to_path_buf()], @@ -631,7 +631,8 @@ impl ProjectWorkspace { sysroot_package_len + project.n_crates() } ProjectWorkspace::Cargo { cargo, sysroot, rustc, .. } => { - let rustc_package_len = rustc.as_ref().map_or(0, |(it, _)| it.packages().len()); + let rustc_package_len = + rustc.as_ref().map(|a| a.as_ref()).map_or(0, |(it, _)| it.packages().len()); let sysroot_package_len = sysroot.as_ref().map_or(0, |it| it.num_packages()); cargo.packages().len() + sysroot_package_len + rustc_package_len } @@ -672,7 +673,7 @@ impl ProjectWorkspace { target_layout, } => cargo_to_crate_graph( load, - rustc.as_ref().ok(), + rustc.as_ref().map(|a| a.as_ref()).ok(), cargo, sysroot.as_ref().ok(), rustc_cfg.clone(), From d37f4e0d21577753f3be96549e0d4e99ac5ae2e2 Mon Sep 17 00:00:00 2001 From: Johann Hemmann Date: Tue, 30 Jan 2024 12:03:33 +0100 Subject: [PATCH 15/17] new_without_default --- Cargo.toml | 1 - crates/hir-def/src/hir/format_args.rs | 4 ++-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 365f7db374..53581c4460 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -171,7 +171,6 @@ derived_hash_with_manual_eq = "allow" forget_non_drop = "allow" format_collect = "allow" needless_doctest_main = "allow" -new_without_default = "allow" non_canonical_clone_impl = "allow" non_canonical_partial_ord_impl = "allow" self_named_constructors = "allow" diff --git a/crates/hir-def/src/hir/format_args.rs b/crates/hir-def/src/hir/format_args.rs index 22864b3289..b097a721c7 100644 --- a/crates/hir-def/src/hir/format_args.rs +++ b/crates/hir-def/src/hir/format_args.rs @@ -433,7 +433,7 @@ pub(crate) fn parse( } } -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Clone, Debug, Default, Eq, PartialEq)] pub struct FormatArgumentsCollector { arguments: Vec, num_unnamed_args: usize, @@ -452,7 +452,7 @@ impl FormatArgumentsCollector { } pub fn new() -> Self { - Self { arguments: vec![], names: vec![], num_unnamed_args: 0, num_explicit_args: 0 } + Default::default() } pub fn add(&mut self, arg: FormatArgument) -> usize { From 771c6c9271f423ab7d0584b308a6abeb599009bc Mon Sep 17 00:00:00 2001 From: Johann Hemmann Date: Tue, 30 Jan 2024 14:12:42 +0100 Subject: [PATCH 16/17] format_collect --- Cargo.toml | 1 - .../hir-def/src/macro_expansion_tests/mod.rs | 5 ++- crates/ide-assists/src/tests/sourcegen.rs | 7 ++--- crates/rust-analyzer/src/config.rs | 31 ++++++++++--------- crates/rust-analyzer/tests/slow-tests/main.rs | 7 +++-- crates/stdx/src/macros.rs | 16 ++++++++++ crates/syntax/src/ast/make.rs | 18 +++++------ crates/syntax/src/tests.rs | 8 ++--- 8 files changed, 54 insertions(+), 39 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 53581c4460..5a74864811 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -169,7 +169,6 @@ new_ret_no_self = "allow" borrowed_box = "allow" derived_hash_with_manual_eq = "allow" forget_non_drop = "allow" -format_collect = "allow" needless_doctest_main = "allow" non_canonical_clone_impl = "allow" non_canonical_partial_ord_impl = "allow" diff --git a/crates/hir-def/src/macro_expansion_tests/mod.rs b/crates/hir-def/src/macro_expansion_tests/mod.rs index ec29940538..e315414e9b 100644 --- a/crates/hir-def/src/macro_expansion_tests/mod.rs +++ b/crates/hir-def/src/macro_expansion_tests/mod.rs @@ -25,7 +25,7 @@ use hir_expand::{ InFile, MacroFileId, MacroFileIdExt, }; use span::Span; -use stdx::format_to; +use stdx::{format_to, format_to_acc}; use syntax::{ ast::{self, edit::IndentLevel}, AstNode, @@ -149,8 +149,7 @@ pub fn identity_when_valid(_attr: TokenStream, item: TokenStream) -> TokenStream if tree { let tree = format!("{:#?}", parse.syntax_node()) .split_inclusive('\n') - .map(|line| format!("// {line}")) - .collect::(); + .fold(String::new(), |mut acc, line| format_to_acc!(acc, "// {line}")); format_to!(expn_text, "\n{}", tree) } let range = call.syntax().text_range(); diff --git a/crates/ide-assists/src/tests/sourcegen.rs b/crates/ide-assists/src/tests/sourcegen.rs index ad5ec83287..088d93f9a6 100644 --- a/crates/ide-assists/src/tests/sourcegen.rs +++ b/crates/ide-assists/src/tests/sourcegen.rs @@ -2,6 +2,7 @@ use std::{fmt, fs, path::Path}; +use stdx::format_to_acc; use test_utils::project_root; #[test] @@ -172,8 +173,7 @@ impl fmt::Display for Assist { fn hide_hash_comments(text: &str) -> String { text.split('\n') // want final newline .filter(|&it| !(it.starts_with("# ") || it == "#")) - .map(|it| format!("{it}\n")) - .collect() + .fold(String::new(), |mut acc, it| format_to_acc!(acc, "{it}\n")) } fn reveal_hash_comments(text: &str) -> String { @@ -187,6 +187,5 @@ fn reveal_hash_comments(text: &str) -> String { it } }) - .map(|it| format!("{it}\n")) - .collect() + .fold(String::new(), |mut acc, it| format_to_acc!(acc, "{it}\n")) } diff --git a/crates/rust-analyzer/src/config.rs b/crates/rust-analyzer/src/config.rs index 54d96ab138..815f6ea12e 100644 --- a/crates/rust-analyzer/src/config.rs +++ b/crates/rust-analyzer/src/config.rs @@ -32,6 +32,7 @@ use project_model::{ }; use rustc_hash::{FxHashMap, FxHashSet}; use serde::{de::DeserializeOwned, Deserialize}; +use stdx::format_to_acc; use vfs::{AbsPath, AbsPathBuf}; use crate::{ @@ -2563,14 +2564,13 @@ fn field_props(field: &str, ty: &str, doc: &[&str], default: &str) -> serde_json #[cfg(test)] fn manual(fields: &[(&'static str, &'static str, &[&str], &str)]) -> String { - fields - .iter() - .map(|(field, _ty, doc, default)| { - let name = format!("rust-analyzer.{}", field.replace('_', ".")); - let doc = doc_comment_to_string(doc); - if default.contains('\n') { - format!( - r#"[[{name}]]{name}:: + fields.iter().fold(String::new(), |mut acc, (field, _ty, doc, default)| { + let name = format!("rust-analyzer.{}", field.replace('_', ".")); + let doc = doc_comment_to_string(doc); + if default.contains('\n') { + format_to_acc!( + acc, + r#"[[{name}]]{name}:: + -- Default: @@ -2580,16 +2580,17 @@ Default: {doc} -- "# - ) - } else { - format!("[[{name}]]{name} (default: `{default}`)::\n+\n--\n{doc}--\n") - } - }) - .collect::() + ) + } else { + format_to_acc!(acc, "[[{name}]]{name} (default: `{default}`)::\n+\n--\n{doc}--\n") + } + }) } fn doc_comment_to_string(doc: &[&str]) -> String { - doc.iter().map(|it| it.strip_prefix(' ').unwrap_or(it)).map(|it| format!("{it}\n")).collect() + doc.iter() + .map(|it| it.strip_prefix(' ').unwrap_or(it)) + .fold(String::new(), |mut acc, it| format_to_acc!(acc, "{it}\n")) } #[cfg(test)] diff --git a/crates/rust-analyzer/tests/slow-tests/main.rs b/crates/rust-analyzer/tests/slow-tests/main.rs index f7f654b890..19890110d5 100644 --- a/crates/rust-analyzer/tests/slow-tests/main.rs +++ b/crates/rust-analyzer/tests/slow-tests/main.rs @@ -31,6 +31,7 @@ use lsp_types::{ }; use rust_analyzer::lsp::ext::{OnEnter, Runnables, RunnablesParams}; use serde_json::json; +use stdx::format_to_acc; use test_utils::skip_slow_tests; use crate::{ @@ -591,8 +592,10 @@ fn diagnostics_dont_block_typing() { return; } - let librs: String = (0..10).map(|i| format!("mod m{i};")).collect(); - let libs: String = (0..10).map(|i| format!("//- /src/m{i}.rs\nfn foo() {{}}\n\n")).collect(); + let librs: String = (0..10).fold(String::new(), |mut acc, i| format_to_acc!(acc, "mod m{i};")); + let libs: String = (0..10).fold(String::new(), |mut acc, i| { + format_to_acc!(acc, "//- /src/m{i}.rs\nfn foo() {{}}\n\n") + }); let server = Project::with_fixture(&format!( r#" //- /Cargo.toml diff --git a/crates/stdx/src/macros.rs b/crates/stdx/src/macros.rs index d71e418c89..5713abb6fc 100644 --- a/crates/stdx/src/macros.rs +++ b/crates/stdx/src/macros.rs @@ -24,6 +24,22 @@ macro_rules! format_to { }; } +/// Appends formatted string to a `String` and returns the `String`. +/// +/// Useful for folding iterators into a `String`. +#[macro_export] +macro_rules! format_to_acc { + ($buf:expr, $lit:literal $($arg:tt)*) => { + { + use ::std::fmt::Write as _; + // We can't do ::std::fmt::Write::write_fmt($buf, format_args!($lit $($arg)*)) + // unfortunately, as that loses out on autoref behavior. + _ = $buf.write_fmt(format_args!($lit $($arg)*)); + $buf + } + }; +} + /// Generates `From` impls for `Enum E { Foo(Foo), Bar(Bar) }` enums /// /// # Example diff --git a/crates/syntax/src/ast/make.rs b/crates/syntax/src/ast/make.rs index 62d64319e3..d5eda8f15e 100644 --- a/crates/syntax/src/ast/make.rs +++ b/crates/syntax/src/ast/make.rs @@ -9,10 +9,11 @@ //! API should require to assemble every node piecewise. The trick of //! `parse(format!())` we use internally is an implementation detail -- long //! term, it will be replaced with direct tree manipulation. + use itertools::Itertools; use parser::T; use rowan::NodeOrToken; -use stdx::{format_to, never}; +use stdx::{format_to, format_to_acc, never}; use crate::{ast, utils::is_raw_identifier, AstNode, SourceFile, SyntaxKind, SyntaxToken}; @@ -759,15 +760,12 @@ pub fn match_arm_with_guard( } pub fn match_arm_list(arms: impl IntoIterator) -> ast::MatchArmList { - let arms_str = arms - .into_iter() - .map(|arm| { - let needs_comma = arm.expr().map_or(true, |it| !it.is_block_like()); - let comma = if needs_comma { "," } else { "" }; - let arm = arm.syntax(); - format!(" {arm}{comma}\n") - }) - .collect::(); + let arms_str = arms.into_iter().fold(String::new(), |mut acc, arm| { + let needs_comma = arm.expr().map_or(true, |it| !it.is_block_like()); + let comma = if needs_comma { "," } else { "" }; + let arm = arm.syntax(); + format_to_acc!(acc, " {arm}{comma}\n") + }); return from_text(&arms_str); fn from_text(text: &str) -> ast::MatchArmList { diff --git a/crates/syntax/src/tests.rs b/crates/syntax/src/tests.rs index 8ae1242cf7..4c0a538f71 100644 --- a/crates/syntax/src/tests.rs +++ b/crates/syntax/src/tests.rs @@ -11,6 +11,7 @@ use std::{ use ast::HasName; use expect_test::expect_file; use rayon::prelude::*; +use stdx::format_to_acc; use test_utils::{bench, bench_fixture, project_root}; use crate::{ast, fuzz, AstNode, SourceFile, SyntaxError}; @@ -104,10 +105,9 @@ fn self_hosting_parsing() { .collect::>(); if !errors.is_empty() { - let errors = errors - .into_iter() - .map(|(path, err)| format!("{}: {:?}\n", path.display(), err[0])) - .collect::(); + let errors = errors.into_iter().fold(String::new(), |mut acc, (path, err)| { + format_to_acc!(acc, "{}: {:?}\n", path.display(), err[0]) + }); panic!("Parsing errors:\n{errors}\n"); } } From df2c7a6e4eca35d726795fb4baccc925d8ad7610 Mon Sep 17 00:00:00 2001 From: Johann Hemmann Date: Wed, 31 Jan 2024 16:29:50 +0100 Subject: [PATCH 17/17] `cargo clippy --fix` --- crates/hir-ty/src/utils.rs | 2 +- crates/ide-db/src/imports/merge_imports.rs | 3 +-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/crates/hir-ty/src/utils.rs b/crates/hir-ty/src/utils.rs index c6e238ff8b..c0ca9d713c 100644 --- a/crates/hir-ty/src/utils.rs +++ b/crates/hir-ty/src/utils.rs @@ -440,7 +440,7 @@ pub(crate) fn detect_variant_from_bytes<'a>( (db.enum_data(e).variants[index.0].0, layout) } hir_def::layout::Variants::Multiple { tag, tag_encoding, variants, .. } => { - let size = tag.size(&*target_data_layout).bytes_usize(); + let size = tag.size(target_data_layout).bytes_usize(); let offset = layout.fields.offset(0).bytes_usize(); // The only field on enum variants is the tag field let tag = i128::from_le_bytes(pad16(&b[offset..offset + size], false)); match tag_encoding { diff --git a/crates/ide-db/src/imports/merge_imports.rs b/crates/ide-db/src/imports/merge_imports.rs index 77c32fd852..b153aafa0e 100644 --- a/crates/ide-db/src/imports/merge_imports.rs +++ b/crates/ide-db/src/imports/merge_imports.rs @@ -467,8 +467,7 @@ fn recursive_normalize(use_tree: &ast::UseTree, style: NormalizationStyle) -> Op } ted::replace_all(start..=end, elements); } else { - let new_use_tree_list = - make::use_tree_list(subtrees.into_iter()).clone_for_update(); + let new_use_tree_list = make::use_tree_list(subtrees).clone_for_update(); ted::replace(use_tree_list.syntax(), new_use_tree_list.syntax()); } modified = true;