From 8c2f301a41d5d709d6f8b6fc479a14e909cc2fce Mon Sep 17 00:00:00 2001 From: Tetsuharu Ohzeki Date: Sat, 10 Feb 2024 00:26:18 +0900 Subject: [PATCH 01/28] ide: Fix warnings about clippy `str_to_string` rule --- crates/ide/src/doc_links.rs | 10 +++++----- crates/ide/src/file_structure.rs | 2 +- crates/ide/src/highlight_related.rs | 2 +- crates/ide/src/hover/render.rs | 10 +++++----- crates/ide/src/interpret_function.rs | 4 ++-- crates/ide/src/join_lines.rs | 8 ++++---- crates/ide/src/lib.rs | 2 +- crates/ide/src/moniker.rs | 8 ++++---- crates/ide/src/navigation_target.rs | 4 ++-- crates/ide/src/prime_caches.rs | 2 +- crates/ide/src/runnables.rs | 2 +- crates/ide/src/ssr.rs | 2 +- crates/ide/src/status.rs | 2 +- crates/ide/src/syntax_tree.rs | 2 +- crates/ide/src/typing.rs | 15 ++++++--------- crates/ide/src/view_hir.rs | 2 +- crates/ide/src/view_mir.rs | 2 +- 17 files changed, 38 insertions(+), 41 deletions(-) diff --git a/crates/ide/src/doc_links.rs b/crates/ide/src/doc_links.rs index f22198571912..ea54734d344b 100644 --- a/crates/ide/src/doc_links.rs +++ b/crates/ide/src/doc_links.rs @@ -58,7 +58,7 @@ pub(crate) fn rewrite_links(db: &RootDatabase, markdown: &str, definition: Defin // and valid URLs so we choose to be too eager to try to resolve what might be // a URL. if target.contains("://") { - (Some(LinkType::Inline), target.to_string(), title.to_string()) + (Some(LinkType::Inline), target.to_owned(), title.to_owned()) } else { // Two possibilities: // * path-based links: `../../module/struct.MyStruct.html` @@ -66,9 +66,9 @@ pub(crate) fn rewrite_links(db: &RootDatabase, markdown: &str, definition: Defin if let Some((target, title)) = rewrite_intra_doc_link(db, definition, target, title) { (None, target, title) } else if let Some(target) = rewrite_url_link(db, definition, target) { - (Some(LinkType::Inline), target, title.to_string()) + (Some(LinkType::Inline), target, title.to_owned()) } else { - (None, target.to_string(), title.to_string()) + (None, target.to_owned(), title.to_owned()) } } }); @@ -186,7 +186,7 @@ pub(crate) fn extract_definitions_from_docs( let (link, ns) = parse_intra_doc_link(&target); Some(( TextRange::new(range.start.try_into().ok()?, range.end.try_into().ok()?), - link.to_string(), + link.to_owned(), ns, )) } @@ -388,7 +388,7 @@ fn rewrite_intra_doc_link( url = url.join(&file).ok()?; url.set_fragment(anchor); - Some((url.into(), strip_prefixes_suffixes(title).to_string())) + Some((url.into(), strip_prefixes_suffixes(title).to_owned())) } /// Try to resolve path to local documentation via path-based links (i.e. `../gateway/struct.Shard.html`). diff --git a/crates/ide/src/file_structure.rs b/crates/ide/src/file_structure.rs index b278924721c0..0e790e14205f 100644 --- a/crates/ide/src/file_structure.rs +++ b/crates/ide/src/file_structure.rs @@ -193,7 +193,7 @@ fn structure_token(token: SyntaxToken) -> Option { if let Some(region_name) = text.strip_prefix("// region:").map(str::trim) { return Some(StructureNode { parent: None, - label: region_name.to_string(), + label: region_name.to_owned(), navigation_range: comment.syntax().text_range(), node_range: comment.syntax().text_range(), kind: StructureNodeKind::Region, diff --git a/crates/ide/src/highlight_related.rs b/crates/ide/src/highlight_related.rs index 979ca4575d06..dd285e9b327c 100644 --- a/crates/ide/src/highlight_related.rs +++ b/crates/ide/src/highlight_related.rs @@ -521,7 +521,7 @@ mod tests { ReferenceCategory::Import => "import", ReferenceCategory::Test => "test", } - .to_string() + .to_owned() }), ) }) diff --git a/crates/ide/src/hover/render.rs b/crates/ide/src/hover/render.rs index 45386df2b266..eff055c95992 100644 --- a/crates/ide/src/hover/render.rs +++ b/crates/ide/src/hover/render.rs @@ -621,7 +621,7 @@ fn closure_ty( }) .join("\n"); if captures_rendered.trim().is_empty() { - captures_rendered = "This closure captures nothing".to_string(); + captures_rendered = "This closure captures nothing".to_owned(); } let mut targets: Vec = Vec::new(); let mut push_new_def = |item: hir::ModuleDef| { @@ -823,7 +823,7 @@ fn keyword_hints( } } _ => KeywordHint { - description: token.text().to_string(), + description: token.text().to_owned(), keyword_mod, actions: Vec::new(), }, @@ -835,9 +835,9 @@ fn keyword_hints( Some(_) => format!("prim_{}", token.text()), None => format!("{}_keyword", token.text()), }; - KeywordHint::new(token.text().to_string(), module) + KeywordHint::new(token.text().to_owned(), module) } - T![Self] => KeywordHint::new(token.text().to_string(), "self_upper_keyword".into()), - _ => KeywordHint::new(token.text().to_string(), format!("{}_keyword", token.text())), + T![Self] => KeywordHint::new(token.text().to_owned(), "self_upper_keyword".into()), + _ => KeywordHint::new(token.text().to_owned(), format!("{}_keyword", token.text())), } } diff --git a/crates/ide/src/interpret_function.rs b/crates/ide/src/interpret_function.rs index adbd19188844..df444a3f4d06 100644 --- a/crates/ide/src/interpret_function.rs +++ b/crates/ide/src/interpret_function.rs @@ -15,8 +15,8 @@ use syntax::{algo::ancestors_at_offset, ast, AstNode, TextRange}; // |=== pub(crate) fn interpret_function(db: &RootDatabase, position: FilePosition) -> String { let start_time = Instant::now(); - let mut result = find_and_interpret(db, position) - .unwrap_or_else(|| "Not inside a function body".to_string()); + let mut result = + find_and_interpret(db, position).unwrap_or_else(|| "Not inside a function body".to_owned()); let duration = Instant::now() - start_time; writeln!(result).unwrap(); writeln!(result, "----------------------").unwrap(); diff --git a/crates/ide/src/join_lines.rs b/crates/ide/src/join_lines.rs index 1cfde2362455..fef0ec35ba09 100644 --- a/crates/ide/src/join_lines.rs +++ b/crates/ide/src/join_lines.rs @@ -115,7 +115,7 @@ fn remove_newline( let range = TextRange::at(offset, ((n_spaces_after_line_break + 1) as u32).into()); let replace_with = if no_space { "" } else { " " }; - edit.replace(range, replace_with.to_string()); + edit.replace(range, replace_with.to_owned()); return; } @@ -140,7 +140,7 @@ fn remove_newline( }; edit.replace( TextRange::new(prev.text_range().start(), token.text_range().end()), - space.to_string(), + space.to_owned(), ); return; } @@ -154,7 +154,7 @@ fn remove_newline( Some(_) => cov_mark::hit!(join_two_ifs_with_existing_else), None => { cov_mark::hit!(join_two_ifs); - edit.replace(token.text_range(), " else ".to_string()); + edit.replace(token.text_range(), " else ".to_owned()); return; } } @@ -203,7 +203,7 @@ fn remove_newline( } // Remove newline but add a computed amount of whitespace characters - edit.replace(token.text_range(), compute_ws(prev.kind(), next.kind()).to_string()); + edit.replace(token.text_range(), compute_ws(prev.kind(), next.kind()).to_owned()); } fn join_single_expr_block(edit: &mut TextEditBuilder, token: &SyntaxToken) -> Option<()> { diff --git a/crates/ide/src/lib.rs b/crates/ide/src/lib.rs index e9f42d478554..effdbf2c1f04 100644 --- a/crates/ide/src/lib.rs +++ b/crates/ide/src/lib.rs @@ -238,7 +238,7 @@ impl Analysis { let mut host = AnalysisHost::default(); let file_id = FileId::from_raw(0); let mut file_set = FileSet::default(); - file_set.insert(file_id, VfsPath::new_virtual_path("/main.rs".to_string())); + file_set.insert(file_id, VfsPath::new_virtual_path("/main.rs".to_owned())); let source_root = SourceRoot::new_local(file_set); let mut change = Change::new(); diff --git a/crates/ide/src/moniker.rs b/crates/ide/src/moniker.rs index c49d75b2f811..80d265ae3739 100644 --- a/crates/ide/src/moniker.rs +++ b/crates/ide/src/moniker.rs @@ -383,18 +383,18 @@ pub(crate) fn def_to_moniker( let (name, repo, version) = match krate.origin(db) { CrateOrigin::Library { repo, name } => (name, repo, krate.version(db)), CrateOrigin::Local { repo, name } => ( - name.unwrap_or(krate.display_name(db)?.canonical_name().to_string()), + name.unwrap_or(krate.display_name(db)?.canonical_name().to_owned()), repo, krate.version(db), ), CrateOrigin::Rustc { name } => ( name.clone(), - Some("https://github.com/rust-lang/rust/".to_string()), + Some("https://github.com/rust-lang/rust/".to_owned()), Some(format!("https://github.com/rust-lang/rust/compiler/{name}",)), ), CrateOrigin::Lang(lang) => ( - krate.display_name(db)?.canonical_name().to_string(), - Some("https://github.com/rust-lang/rust/".to_string()), + krate.display_name(db)?.canonical_name().to_owned(), + Some("https://github.com/rust-lang/rust/".to_owned()), Some(match lang { LangCrateOrigin::Other => { "https://github.com/rust-lang/rust/library/".into() diff --git a/crates/ide/src/navigation_target.rs b/crates/ide/src/navigation_target.rs index bfd91feeb390..674ce6d52bf7 100644 --- a/crates/ide/src/navigation_target.rs +++ b/crates/ide/src/navigation_target.rs @@ -860,7 +860,7 @@ fn foo() { enum FooInner { } } "#, ); - let navs = analysis.symbol_search(Query::new("FooInner".to_string()), !0).unwrap(); + let navs = analysis.symbol_search(Query::new("FooInner".to_owned()), !0).unwrap(); expect![[r#" [ NavigationTarget { @@ -898,7 +898,7 @@ struct Foo; "#, ); - let navs = analysis.symbol_search(Query::new("foo".to_string()), !0).unwrap(); + let navs = analysis.symbol_search(Query::new("foo".to_owned()), !0).unwrap(); assert_eq!(navs.len(), 2) } } diff --git a/crates/ide/src/prime_caches.rs b/crates/ide/src/prime_caches.rs index a95d1771ce0b..5c14f496a0bc 100644 --- a/crates/ide/src/prime_caches.rs +++ b/crates/ide/src/prime_caches.rs @@ -105,7 +105,7 @@ pub(crate) fn parallel_prime_caches( work_sender .send(( crate_id, - graph[crate_id].display_name.as_deref().unwrap_or_default().to_string(), + graph[crate_id].display_name.as_deref().unwrap_or_default().to_owned(), )) .ok(); } diff --git a/crates/ide/src/runnables.rs b/crates/ide/src/runnables.rs index 3008722cdbb6..40b9a5de196a 100644 --- a/crates/ide/src/runnables.rs +++ b/crates/ide/src/runnables.rs @@ -72,7 +72,7 @@ impl Runnable { RunnableKind::Bench { test_id } => format!("bench {test_id}"), RunnableKind::DocTest { test_id, .. } => format!("doctest {test_id}"), RunnableKind::Bin => { - target.map_or_else(|| "run binary".to_string(), |t| format!("run {t}")) + target.map_or_else(|| "run binary".to_owned(), |t| format!("run {t}")) } } } diff --git a/crates/ide/src/ssr.rs b/crates/ide/src/ssr.rs index f0d18fdefa71..b49fe391bf25 100644 --- a/crates/ide/src/ssr.rs +++ b/crates/ide/src/ssr.rs @@ -41,7 +41,7 @@ pub(crate) fn ssr_assists( for (label, source_change) in assists.into_iter() { let assist = Assist { id, - label: Label::new(label.to_string()), + label: Label::new(label.to_owned()), group: Some(GroupLabel("Apply SSR".into())), target: comment_range, source_change, diff --git a/crates/ide/src/status.rs b/crates/ide/src/status.rs index b2b305c1d380..3321a0513b6f 100644 --- a/crates/ide/src/status.rs +++ b/crates/ide/src/status.rs @@ -105,7 +105,7 @@ pub(crate) fn status(db: &RootDatabase, file_id: Option) -> String { } } - buf.trim().to_string() + buf.trim().to_owned() } fn collect_query<'q, Q>(table: QueryTable<'q, Q>) -> ::Collector diff --git a/crates/ide/src/syntax_tree.rs b/crates/ide/src/syntax_tree.rs index 2108b53861c1..1065d5899ab7 100644 --- a/crates/ide/src/syntax_tree.rs +++ b/crates/ide/src/syntax_tree.rs @@ -55,7 +55,7 @@ fn syntax_tree_for_string(token: &SyntaxToken, text_range: TextRange) -> Option< fn syntax_tree_for_token(node: &SyntaxToken, text_range: TextRange) -> Option { // Range of the full node let node_range = node.text_range(); - let text = node.text().to_string(); + let text = node.text().to_owned(); // We start at some point inside the node // Either we have selected the whole string diff --git a/crates/ide/src/typing.rs b/crates/ide/src/typing.rs index b8856882ed7f..e87fc89fea2a 100644 --- a/crates/ide/src/typing.rs +++ b/crates/ide/src/typing.rs @@ -149,10 +149,7 @@ fn on_opening_bracket_typed( let tree: ast::UseTree = find_node_at_offset(file.syntax(), offset)?; - Some(TextEdit::insert( - tree.syntax().text_range().end() + TextSize::of("{"), - "}".to_string(), - )) + Some(TextEdit::insert(tree.syntax().text_range().end() + TextSize::of("{"), "}".to_owned())) } fn bracket_expr( @@ -235,7 +232,7 @@ fn on_eq_typed(file: &SourceFile, offset: TextSize) -> Option { return None; } let offset = expr.syntax().text_range().end(); - Some(TextEdit::insert(offset, ";".to_string())) + Some(TextEdit::insert(offset, ";".to_owned())) } /// `a =$0 b;` removes the semicolon if an expression is valid in this context. @@ -275,7 +272,7 @@ fn on_eq_typed(file: &SourceFile, offset: TextSize) -> Option { return None; } let offset = let_stmt.syntax().text_range().end(); - Some(TextEdit::insert(offset, ";".to_string())) + Some(TextEdit::insert(offset, ";".to_owned())) } } @@ -353,7 +350,7 @@ fn on_left_angle_typed(file: &SourceFile, offset: TextSize) -> Option".to_string()), + edit: TextEdit::replace(range, "<$0>".to_owned()), is_snippet: true, }); } @@ -363,7 +360,7 @@ fn on_left_angle_typed(file: &SourceFile, offset: TextSize) -> Option".to_string()), + edit: TextEdit::replace(range, "<$0>".to_owned()), is_snippet: true, }) } else { @@ -383,7 +380,7 @@ fn on_right_angle_typed(file: &SourceFile, offset: TextSize) -> Option } find_node_at_offset::(file.syntax(), offset)?; - Some(TextEdit::insert(after_arrow, " ".to_string())) + Some(TextEdit::insert(after_arrow, " ".to_owned())) } #[cfg(test)] diff --git a/crates/ide/src/view_hir.rs b/crates/ide/src/view_hir.rs index 9abe54cd3903..51cf45bd22b1 100644 --- a/crates/ide/src/view_hir.rs +++ b/crates/ide/src/view_hir.rs @@ -12,7 +12,7 @@ use syntax::{algo::ancestors_at_offset, ast, AstNode}; // |=== // image::https://user-images.githubusercontent.com/48062697/113065588-068bdb80-91b1-11eb-9a78-0b4ef1e972fb.gif[] pub(crate) fn view_hir(db: &RootDatabase, position: FilePosition) -> String { - body_hir(db, position).unwrap_or_else(|| "Not inside a function body".to_string()) + body_hir(db, position).unwrap_or_else(|| "Not inside a function body".to_owned()) } fn body_hir(db: &RootDatabase, position: FilePosition) -> Option { diff --git a/crates/ide/src/view_mir.rs b/crates/ide/src/view_mir.rs index 08d810c13462..5fb47039890b 100644 --- a/crates/ide/src/view_mir.rs +++ b/crates/ide/src/view_mir.rs @@ -11,7 +11,7 @@ use syntax::{algo::ancestors_at_offset, ast, AstNode}; // | VS Code | **rust-analyzer: View Mir** // |=== pub(crate) fn view_mir(db: &RootDatabase, position: FilePosition) -> String { - body_mir(db, position).unwrap_or_else(|| "Not inside a function body".to_string()) + body_mir(db, position).unwrap_or_else(|| "Not inside a function body".to_owned()) } fn body_mir(db: &RootDatabase, position: FilePosition) -> Option { From a9a315fd73f5019debbc6e77b2c164033eee9970 Mon Sep 17 00:00:00 2001 From: Tetsuharu Ohzeki Date: Sat, 10 Feb 2024 00:26:49 +0900 Subject: [PATCH 02/28] base-db: Fix warnings about clippy `str_to_string` rule --- crates/base-db/src/input.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/base-db/src/input.rs b/crates/base-db/src/input.rs index 51e6fdb9510a..9560826e373e 100644 --- a/crates/base-db/src/input.rs +++ b/crates/base-db/src/input.rs @@ -782,7 +782,7 @@ impl FromStr for Edition { "2018" => Edition::Edition2018, "2021" => Edition::Edition2021, "2024" => Edition::Edition2024, - _ => return Err(ParseEditionError { invalid_input: s.to_string() }), + _ => return Err(ParseEditionError { invalid_input: s.to_owned() }), }; Ok(res) } From 99f5d7ca4cb18b67481a548c9ce32e96f63e27e4 Mon Sep 17 00:00:00 2001 From: Tetsuharu Ohzeki Date: Sat, 10 Feb 2024 00:28:17 +0900 Subject: [PATCH 03/28] hir-def: Fix warnings about clippy `str_to_string` rule --- crates/hir-def/src/body/pretty.rs | 6 +++--- crates/hir-def/src/import_map.rs | 18 ++++++++---------- crates/hir-def/src/item_scope.rs | 2 +- crates/hir-def/src/item_tree/pretty.rs | 4 ++-- .../hir-def/src/macro_expansion_tests/mod.rs | 2 +- 5 files changed, 15 insertions(+), 17 deletions(-) diff --git a/crates/hir-def/src/body/pretty.rs b/crates/hir-def/src/body/pretty.rs index b821b91b8959..4afb40865170 100644 --- a/crates/hir-def/src/body/pretty.rs +++ b/crates/hir-def/src/body/pretty.rs @@ -29,11 +29,11 @@ pub(super) fn print_body_hir(db: &dyn DefDatabase, body: &Body, owner: DefWithBo "const {} = ", match &it.name { Some(name) => name.display(db.upcast()).to_string(), - None => "_".to_string(), + None => "_".to_owned(), } ) }), - DefWithBodyId::InTypeConstId(_) => "In type const = ".to_string(), + DefWithBodyId::InTypeConstId(_) => "In type const = ".to_owned(), DefWithBodyId::VariantId(it) => { let loc = it.lookup(db); let enum_loc = loc.parent.lookup(db); @@ -123,7 +123,7 @@ impl Printer<'_> { wln!(self); f(self); self.indent_level -= 1; - self.buf = self.buf.trim_end_matches('\n').to_string(); + self.buf = self.buf.trim_end_matches('\n').to_owned(); } fn whitespace(&mut self) { diff --git a/crates/hir-def/src/import_map.rs b/crates/hir-def/src/import_map.rs index c698510ca99b..98982c7db840 100644 --- a/crates/hir-def/src/import_map.rs +++ b/crates/hir-def/src/import_map.rs @@ -859,7 +859,7 @@ mod tests { check_search( ra_fixture, "main", - Query::new("fmt".to_string()).fuzzy(), + Query::new("fmt".to_owned()).fuzzy(), expect![[r#" dep::fmt (t) dep::fmt::Display::FMT_CONST (a) @@ -888,9 +888,7 @@ mod tests { check_search( ra_fixture, "main", - Query::new("fmt".to_string()) - .fuzzy() - .assoc_search_mode(AssocSearchMode::AssocItemsOnly), + Query::new("fmt".to_owned()).fuzzy().assoc_search_mode(AssocSearchMode::AssocItemsOnly), expect![[r#" dep::fmt::Display::FMT_CONST (a) dep::fmt::Display::format_function (a) @@ -901,7 +899,7 @@ mod tests { check_search( ra_fixture, "main", - Query::new("fmt".to_string()).fuzzy().assoc_search_mode(AssocSearchMode::Exclude), + Query::new("fmt".to_owned()).fuzzy().assoc_search_mode(AssocSearchMode::Exclude), expect![[r#" dep::fmt (t) "#]], @@ -937,7 +935,7 @@ pub mod fmt { check_search( ra_fixture, "main", - Query::new("fmt".to_string()).fuzzy(), + Query::new("fmt".to_owned()).fuzzy(), expect![[r#" dep::Fmt (m) dep::Fmt (t) @@ -951,7 +949,7 @@ pub mod fmt { check_search( ra_fixture, "main", - Query::new("fmt".to_string()), + Query::new("fmt".to_owned()), expect![[r#" dep::Fmt (m) dep::Fmt (t) @@ -991,7 +989,7 @@ pub mod fmt { check_search( ra_fixture, "main", - Query::new("fmt".to_string()), + Query::new("fmt".to_owned()), expect![[r#" dep::Fmt (m) dep::Fmt (t) @@ -1015,7 +1013,7 @@ pub mod fmt { check_search( ra_fixture, "main", - Query::new("FMT".to_string()), + Query::new("FMT".to_owned()), expect![[r#" dep::FMT (t) dep::FMT (v) @@ -1027,7 +1025,7 @@ pub mod fmt { check_search( ra_fixture, "main", - Query::new("FMT".to_string()).case_sensitive(), + Query::new("FMT".to_owned()).case_sensitive(), expect![[r#" dep::FMT (t) dep::FMT (v) diff --git a/crates/hir-def/src/item_scope.rs b/crates/hir-def/src/item_scope.rs index 4bd2801aaf8f..0e6826a75a6c 100644 --- a/crates/hir-def/src/item_scope.rs +++ b/crates/hir-def/src/item_scope.rs @@ -672,7 +672,7 @@ impl ItemScope { format_to!( buf, "{}:", - name.map_or("_".to_string(), |name| name.display(db).to_string()) + name.map_or("_".to_owned(), |name| name.display(db).to_string()) ); if let Some((.., i)) = def.types { diff --git a/crates/hir-def/src/item_tree/pretty.rs b/crates/hir-def/src/item_tree/pretty.rs index 520034d213ce..0086b7180b2b 100644 --- a/crates/hir-def/src/item_tree/pretty.rs +++ b/crates/hir-def/src/item_tree/pretty.rs @@ -24,7 +24,7 @@ pub(super) fn print_item_tree(db: &dyn DefDatabase, tree: &ItemTree) -> String { p.print_mod_item(*item); } - let mut s = p.buf.trim_end_matches('\n').to_string(); + let mut s = p.buf.trim_end_matches('\n').to_owned(); s.push('\n'); s } @@ -58,7 +58,7 @@ impl Printer<'_> { wln!(self); f(self); self.indent_level -= 1; - self.buf = self.buf.trim_end_matches('\n').to_string(); + self.buf = self.buf.trim_end_matches('\n').to_owned(); } /// Ensures that a blank line is output before the next text. diff --git a/crates/hir-def/src/macro_expansion_tests/mod.rs b/crates/hir-def/src/macro_expansion_tests/mod.rs index e315414e9bdd..fc5a6e80a427 100644 --- a/crates/hir-def/src/macro_expansion_tests/mod.rs +++ b/crates/hir-def/src/macro_expansion_tests/mod.rs @@ -224,7 +224,7 @@ fn reindent(indent: IndentLevel, pp: String) -> String { return pp; } let mut lines = pp.split_inclusive('\n'); - let mut res = lines.next().unwrap().to_string(); + let mut res = lines.next().unwrap().to_owned(); for line in lines { if line.trim().is_empty() { res.push_str(line) From cb95ee3bc0d9814f83470de87446bd87ea44c1be Mon Sep 17 00:00:00 2001 From: Tetsuharu Ohzeki Date: Sat, 10 Feb 2024 00:29:00 +0900 Subject: [PATCH 04/28] hir-def: Fix warnings about clippy `str_to_string` rule --- crates/hir-expand/src/builtin_fn_macro.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/hir-expand/src/builtin_fn_macro.rs b/crates/hir-expand/src/builtin_fn_macro.rs index 8d60f58628c7..6d3de0e55d24 100644 --- a/crates/hir-expand/src/builtin_fn_macro.rs +++ b/crates/hir-expand/src/builtin_fn_macro.rs @@ -515,7 +515,7 @@ fn concat_bytes_expand( tt::TokenTree::Leaf(tt::Leaf::Literal(lit)) => { let token = ast::make::tokens::literal(&lit.to_string()); match token.kind() { - syntax::SyntaxKind::BYTE => bytes.push(token.text().to_string()), + syntax::SyntaxKind::BYTE => bytes.push(token.text().to_owned()), syntax::SyntaxKind::BYTE_STRING => { let components = unquote_byte_string(lit).unwrap_or_default(); components.into_iter().for_each(|it| bytes.push(it.to_string())); @@ -570,7 +570,7 @@ fn concat_bytes_expand_subtree( let lit = ast::make::tokens::literal(&lit.to_string()); match lit.kind() { syntax::SyntaxKind::BYTE | syntax::SyntaxKind::INT_NUMBER => { - bytes.push(lit.text().to_string()) + bytes.push(lit.text().to_owned()) } _ => { return Err(mbe::ExpandError::UnexpectedToken.into()); @@ -749,7 +749,7 @@ fn env_expand( // We cannot use an empty string here, because for // `include!(concat!(env!("OUT_DIR"), "/foo.rs"))` will become // `include!("foo.rs"), which might go to infinite loop - "UNRESOLVED_ENV_VAR".to_string() + "UNRESOLVED_ENV_VAR".to_owned() }); let expanded = quote! {span => #s }; From d580b2c7bc6314086f8ebf09d0395ddb6919ceac Mon Sep 17 00:00:00 2001 From: Tetsuharu Ohzeki Date: Sat, 10 Feb 2024 00:31:33 +0900 Subject: [PATCH 05/28] hir-ty: Fix warnings about clippy `str_to_string` rule --- crates/hir-ty/src/consteval/tests.rs | 4 ++-- crates/hir-ty/src/infer/closure.rs | 10 ++++------ crates/hir-ty/src/mir/eval.rs | 8 ++++---- crates/hir-ty/src/mir/eval/shim.rs | 2 +- crates/hir-ty/src/mir/lower.rs | 6 +++--- crates/hir-ty/src/mir/lower/as_place.rs | 2 +- crates/hir-ty/src/tests.rs | 6 +++--- crates/hir-ty/src/traits.rs | 4 ++-- 8 files changed, 20 insertions(+), 22 deletions(-) diff --git a/crates/hir-ty/src/consteval/tests.rs b/crates/hir-ty/src/consteval/tests.rs index ac82208708ae..98384c47490a 100644 --- a/crates/hir-ty/src/consteval/tests.rs +++ b/crates/hir-ty/src/consteval/tests.rs @@ -133,7 +133,7 @@ fn bit_op() { check_number(r#"const GOAL: i8 = 1 << 7"#, (1i8 << 7) as i128); check_number(r#"const GOAL: i8 = -1 << 2"#, (-1i8 << 2) as i128); check_fail(r#"const GOAL: i8 = 1 << 8"#, |e| { - e == ConstEvalError::MirEvalError(MirEvalError::Panic("Overflow in Shl".to_string())) + e == ConstEvalError::MirEvalError(MirEvalError::Panic("Overflow in Shl".to_owned())) }); check_number(r#"const GOAL: i32 = 100000000i32 << 11"#, (100000000i32 << 11) as i128); } @@ -2756,7 +2756,7 @@ fn memory_limit() { "#, |e| { e == ConstEvalError::MirEvalError(MirEvalError::Panic( - "Memory allocation of 30000000000 bytes failed".to_string(), + "Memory allocation of 30000000000 bytes failed".to_owned(), )) }, ); diff --git a/crates/hir-ty/src/infer/closure.rs b/crates/hir-ty/src/infer/closure.rs index 572df8f71374..47fe9467a84b 100644 --- a/crates/hir-ty/src/infer/closure.rs +++ b/crates/hir-ty/src/infer/closure.rs @@ -194,17 +194,15 @@ impl CapturedItem { } let variant_data = f.parent.variant_data(db.upcast()); let field = match &*variant_data { - VariantData::Record(fields) => fields[f.local_id] - .name - .as_str() - .unwrap_or("[missing field]") - .to_string(), + VariantData::Record(fields) => { + fields[f.local_id].name.as_str().unwrap_or("[missing field]").to_owned() + } VariantData::Tuple(fields) => fields .iter() .position(|it| it.0 == f.local_id) .unwrap_or_default() .to_string(), - VariantData::Unit => "[missing field]".to_string(), + VariantData::Unit => "[missing field]".to_owned(), }; result = format!("{result}.{field}"); field_need_paren = false; diff --git a/crates/hir-ty/src/mir/eval.rs b/crates/hir-ty/src/mir/eval.rs index 50c4d00660b7..2f164e992539 100644 --- a/crates/hir-ty/src/mir/eval.rs +++ b/crates/hir-ty/src/mir/eval.rs @@ -1763,7 +1763,7 @@ impl Evaluator<'_> { } }; mem.get(pos..pos + size) - .ok_or_else(|| MirEvalError::UndefinedBehavior("out of bound memory read".to_string())) + .ok_or_else(|| MirEvalError::UndefinedBehavior("out of bound memory read".to_owned())) } fn write_memory_using_ref(&mut self, addr: Address, size: usize) -> Result<&mut [u8]> { @@ -1777,7 +1777,7 @@ impl Evaluator<'_> { } }; mem.get_mut(pos..pos + size) - .ok_or_else(|| MirEvalError::UndefinedBehavior("out of bound memory write".to_string())) + .ok_or_else(|| MirEvalError::UndefinedBehavior("out of bound memory write".to_owned())) } fn write_memory(&mut self, addr: Address, r: &[u8]) -> Result<()> { @@ -1800,7 +1800,7 @@ impl Evaluator<'_> { return Ok(()); } - let oob = || MirEvalError::UndefinedBehavior("out of bounds memory write".to_string()); + let oob = || MirEvalError::UndefinedBehavior("out of bounds memory write".to_owned()); match (addr, r.addr) { (Stack(dst), Stack(src)) => { @@ -2653,7 +2653,7 @@ pub fn render_const_using_debug_impl( ptr: ArenaMap::new(), body: db .mir_body(owner.into()) - .map_err(|_| MirEvalError::NotSupported("unreachable".to_string()))?, + .map_err(|_| MirEvalError::NotSupported("unreachable".to_owned()))?, drop_flags: DropFlags::default(), }; let data = evaluator.allocate_const_in_heap(locals, c)?; diff --git a/crates/hir-ty/src/mir/eval/shim.rs b/crates/hir-ty/src/mir/eval/shim.rs index b4fb99acae77..468b72bb579d 100644 --- a/crates/hir-ty/src/mir/eval/shim.rs +++ b/crates/hir-ty/src/mir/eval/shim.rs @@ -304,7 +304,7 @@ impl Evaluator<'_> { use LangItem::*; let mut args = args.iter(); match it { - BeginPanic => Err(MirEvalError::Panic("".to_string())), + BeginPanic => Err(MirEvalError::Panic("".to_owned())), PanicFmt => { let message = (|| { let resolver = self diff --git a/crates/hir-ty/src/mir/lower.rs b/crates/hir-ty/src/mir/lower.rs index f4a076737aa2..02d769039725 100644 --- a/crates/hir-ty/src/mir/lower.rs +++ b/crates/hir-ty/src/mir/lower.rs @@ -1634,7 +1634,7 @@ impl<'ctx> MirLowerCtx<'ctx> { self.set_goto(prev_block, begin, span); f(self, begin)?; let my = mem::replace(&mut self.current_loop_blocks, prev).ok_or( - MirLowerError::ImplementationError("current_loop_blocks is corrupt".to_string()), + MirLowerError::ImplementationError("current_loop_blocks is corrupt".to_owned()), )?; if let Some(prev) = prev_label { self.labeled_loop_blocks.insert(label.unwrap(), prev); @@ -1669,7 +1669,7 @@ impl<'ctx> MirLowerCtx<'ctx> { .current_loop_blocks .as_mut() .ok_or(MirLowerError::ImplementationError( - "Current loop access out of loop".to_string(), + "Current loop access out of loop".to_owned(), ))? .end { @@ -1679,7 +1679,7 @@ impl<'ctx> MirLowerCtx<'ctx> { self.current_loop_blocks .as_mut() .ok_or(MirLowerError::ImplementationError( - "Current loop access out of loop".to_string(), + "Current loop access out of loop".to_owned(), ))? .end = Some(s); s diff --git a/crates/hir-ty/src/mir/lower/as_place.rs b/crates/hir-ty/src/mir/lower/as_place.rs index 8d157944020d..afe33607d468 100644 --- a/crates/hir-ty/src/mir/lower/as_place.rs +++ b/crates/hir-ty/src/mir/lower/as_place.rs @@ -225,7 +225,7 @@ impl MirLowerCtx<'_> { { let Some(index_fn) = self.infer.method_resolution(expr_id) else { return Err(MirLowerError::UnresolvedMethod( - "[overloaded index]".to_string(), + "[overloaded index]".to_owned(), )); }; let Some((base_place, current)) = diff --git a/crates/hir-ty/src/tests.rs b/crates/hir-ty/src/tests.rs index 03e593d9d17d..5e159236f488 100644 --- a/crates/hir-ty/src/tests.rs +++ b/crates/hir-ty/src/tests.rs @@ -100,7 +100,7 @@ fn check_impl(ra_fixture: &str, allow_none: bool, only_types: bool, display_sour if only_types { types.insert(file_range, expected); } else if expected.starts_with("type: ") { - types.insert(file_range, expected.trim_start_matches("type: ").to_string()); + types.insert(file_range, expected.trim_start_matches("type: ").to_owned()); } else if expected.starts_with("expected") { mismatches.insert(file_range, expected); } else if expected.starts_with("adjustments:") { @@ -110,7 +110,7 @@ fn check_impl(ra_fixture: &str, allow_none: bool, only_types: bool, display_sour .trim_start_matches("adjustments:") .trim() .split(',') - .map(|it| it.trim().to_string()) + .map(|it| it.trim().to_owned()) .filter(|it| !it.is_empty()) .collect(), ); @@ -331,7 +331,7 @@ fn infer_with_mismatches(content: &str, include_mismatches: bool) -> String { }); for (node, ty) in &types { let (range, text) = if let Some(self_param) = ast::SelfParam::cast(node.value.clone()) { - (self_param.name().unwrap().syntax().text_range(), "self".to_string()) + (self_param.name().unwrap().syntax().text_range(), "self".to_owned()) } else { (node.value.text_range(), node.value.text().to_string().replace('\n', " ")) }; diff --git a/crates/hir-ty/src/traits.rs b/crates/hir-ty/src/traits.rs index 5303182d8ce4..b2232b920aa0 100644 --- a/crates/hir-ty/src/traits.rs +++ b/crates/hir-ty/src/traits.rs @@ -104,8 +104,8 @@ pub(crate) fn trait_solve_query( GoalData::DomainGoal(DomainGoal::Holds(WhereClause::Implemented(it))) => { db.trait_data(it.hir_trait_id()).name.display(db.upcast()).to_string() } - GoalData::DomainGoal(DomainGoal::Holds(WhereClause::AliasEq(_))) => "alias_eq".to_string(), - _ => "??".to_string(), + GoalData::DomainGoal(DomainGoal::Holds(WhereClause::AliasEq(_))) => "alias_eq".to_owned(), + _ => "??".to_owned(), }; let _p = tracing::span!(tracing::Level::INFO, "trait_solve_query", ?detail).entered(); tracing::info!("trait_solve_query({:?})", goal.value.goal); From eba1b1329548cae80b21e571b2888ab106b4c420 Mon Sep 17 00:00:00 2001 From: Tetsuharu Ohzeki Date: Sat, 10 Feb 2024 00:33:00 +0900 Subject: [PATCH 06/28] hir: Fix warnings about clippy `str_to_string` rule --- crates/hir/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/hir/src/lib.rs b/crates/hir/src/lib.rs index b2a793e53d07..60e829b0a76c 100644 --- a/crates/hir/src/lib.rs +++ b/crates/hir/src/lib.rs @@ -1933,7 +1933,7 @@ impl Function { }; let (result, output) = interpret_mir(db, body, false, None); let mut text = match result { - Ok(_) => "pass".to_string(), + Ok(_) => "pass".to_owned(), Err(e) => { let mut r = String::new(); _ = e.pretty_print(&mut r, db, &span_formatter); From d00f1c1b16abc9f5fc9fa456b189d2abc5364a91 Mon Sep 17 00:00:00 2001 From: Tetsuharu Ohzeki Date: Sat, 10 Feb 2024 00:35:55 +0900 Subject: [PATCH 07/28] ide-diagnostics: Fix warnings about clippy `str_to_string` rule --- crates/ide-diagnostics/src/handlers/inactive_code.rs | 2 +- crates/ide-diagnostics/src/handlers/incoherent_impl.rs | 2 +- crates/ide-diagnostics/src/handlers/incorrect_case.rs | 2 +- crates/ide-diagnostics/src/handlers/json_is_not_rust.rs | 6 +++--- crates/ide-diagnostics/src/handlers/macro_error.rs | 6 +++--- crates/ide-diagnostics/src/handlers/missing_fields.rs | 2 +- crates/ide-diagnostics/src/handlers/missing_match_arms.rs | 2 +- crates/ide-diagnostics/src/handlers/mutability_errors.rs | 6 +++--- .../ide-diagnostics/src/handlers/remove_trailing_return.rs | 4 ++-- .../ide-diagnostics/src/handlers/remove_unnecessary_else.rs | 2 +- .../src/handlers/replace_filter_map_next_with_find_map.rs | 4 ++-- crates/ide-diagnostics/src/handlers/trait_impl_orphan.rs | 2 +- .../src/handlers/trait_impl_redundant_assoc_item.rs | 2 +- crates/ide-diagnostics/src/handlers/type_mismatch.rs | 6 +++--- .../src/handlers/unimplemented_builtin_macro.rs | 2 +- crates/ide-diagnostics/src/handlers/unresolved_field.rs | 2 +- crates/ide-diagnostics/src/handlers/unresolved_method.rs | 2 +- crates/ide-diagnostics/src/handlers/unresolved_module.rs | 4 ++-- .../ide-diagnostics/src/handlers/unresolved_proc_macro.rs | 2 +- crates/ide-diagnostics/src/handlers/useless_braces.rs | 4 ++-- crates/ide-diagnostics/src/lib.rs | 2 +- crates/ide-diagnostics/src/tests.rs | 6 +++--- 22 files changed, 36 insertions(+), 36 deletions(-) diff --git a/crates/ide-diagnostics/src/handlers/inactive_code.rs b/crates/ide-diagnostics/src/handlers/inactive_code.rs index 9f754f9c6fca..7db5ea04fbd0 100644 --- a/crates/ide-diagnostics/src/handlers/inactive_code.rs +++ b/crates/ide-diagnostics/src/handlers/inactive_code.rs @@ -16,7 +16,7 @@ pub(crate) fn inactive_code( } let inactive = DnfExpr::new(d.cfg.clone()).why_inactive(&d.opts); - let mut message = "code is inactive due to #[cfg] directives".to_string(); + let mut message = "code is inactive due to #[cfg] directives".to_owned(); if let Some(inactive) = inactive { let inactive_reasons = inactive.to_string(); diff --git a/crates/ide-diagnostics/src/handlers/incoherent_impl.rs b/crates/ide-diagnostics/src/handlers/incoherent_impl.rs index 3b4d400912fc..9f56e1041454 100644 --- a/crates/ide-diagnostics/src/handlers/incoherent_impl.rs +++ b/crates/ide-diagnostics/src/handlers/incoherent_impl.rs @@ -9,7 +9,7 @@ pub(crate) fn incoherent_impl(ctx: &DiagnosticsContext<'_>, d: &hir::IncoherentI Diagnostic::new_with_syntax_node_ptr( ctx, DiagnosticCode::RustcHardError("E0210"), - "cannot define inherent `impl` for foreign type".to_string(), + "cannot define inherent `impl` for foreign type".to_owned(), InFile::new(d.file_id, d.impl_.into()), ) } diff --git a/crates/ide-diagnostics/src/handlers/incorrect_case.rs b/crates/ide-diagnostics/src/handlers/incorrect_case.rs index 96fbb4468f5c..dd64b93e4548 100644 --- a/crates/ide-diagnostics/src/handlers/incorrect_case.rs +++ b/crates/ide-diagnostics/src/handlers/incorrect_case.rs @@ -512,7 +512,7 @@ impl BAD_TRAIT for () { fn BadFunction() {} } "#, - std::iter::once("unused_variables".to_string()), + std::iter::once("unused_variables".to_owned()), ); } diff --git a/crates/ide-diagnostics/src/handlers/json_is_not_rust.rs b/crates/ide-diagnostics/src/handlers/json_is_not_rust.rs index d330973aaaa3..241fddbb9063 100644 --- a/crates/ide-diagnostics/src/handlers/json_is_not_rust.rs +++ b/crates/ide-diagnostics/src/handlers/json_is_not_rust.rs @@ -42,12 +42,12 @@ impl State { v.push("Deserialize"); } match v.as_slice() { - [] => "".to_string(), + [] => "".to_owned(), [x] => format!("#[derive({x})]\n"), [x, y] => format!("#[derive({x}, {y})]\n"), _ => { never!(); - "".to_string() + "".to_owned() } } } @@ -176,7 +176,7 @@ mod tests { #[test] fn diagnostic_for_simple_case() { let mut config = DiagnosticsConfig::test_sample(); - config.disabled.insert("syntax-error".to_string()); + config.disabled.insert("syntax-error".to_owned()); check_diagnostics_with_config( config, r#" diff --git a/crates/ide-diagnostics/src/handlers/macro_error.rs b/crates/ide-diagnostics/src/handlers/macro_error.rs index fc5c715981f5..e4cb53f3a2f7 100644 --- a/crates/ide-diagnostics/src/handlers/macro_error.rs +++ b/crates/ide-diagnostics/src/handlers/macro_error.rs @@ -99,7 +99,7 @@ pub macro panic { // FIXME: This is a false-positive, the file is actually linked in via // `include!` macro - config.disabled.insert("unlinked-file".to_string()); + config.disabled.insert("unlinked-file".to_owned()); check_diagnostics_with_config( config, @@ -268,8 +268,8 @@ fn f() { #[test] fn include_does_not_break_diagnostics() { let mut config = DiagnosticsConfig::test_sample(); - config.disabled.insert("inactive-code".to_string()); - config.disabled.insert("unlinked-file".to_string()); + config.disabled.insert("inactive-code".to_owned()); + config.disabled.insert("unlinked-file".to_owned()); check_diagnostics_with_config( config, r#" diff --git a/crates/ide-diagnostics/src/handlers/missing_fields.rs b/crates/ide-diagnostics/src/handlers/missing_fields.rs index 3bc043c8fc65..c70f39eb286f 100644 --- a/crates/ide-diagnostics/src/handlers/missing_fields.rs +++ b/crates/ide-diagnostics/src/handlers/missing_fields.rs @@ -170,7 +170,7 @@ fn make_ty(ty: &hir::Type, db: &dyn HirDatabase, module: hir::Module) -> ast::Ty let ty_str = match ty.as_adt() { Some(adt) => adt.name(db).display(db.upcast()).to_string(), None => { - ty.display_source_code(db, module.into(), false).ok().unwrap_or_else(|| "_".to_string()) + ty.display_source_code(db, module.into(), false).ok().unwrap_or_else(|| "_".to_owned()) } }; diff --git a/crates/ide-diagnostics/src/handlers/missing_match_arms.rs b/crates/ide-diagnostics/src/handlers/missing_match_arms.rs index cb6d568442d3..17dc679e055b 100644 --- a/crates/ide-diagnostics/src/handlers/missing_match_arms.rs +++ b/crates/ide-diagnostics/src/handlers/missing_match_arms.rs @@ -31,7 +31,7 @@ mod tests { #[test] fn empty_body() { let mut config = DiagnosticsConfig::test_sample(); - config.disabled.insert("syntax-error".to_string()); + config.disabled.insert("syntax-error".to_owned()); check_diagnostics_with_config( config, r#" diff --git a/crates/ide-diagnostics/src/handlers/mutability_errors.rs b/crates/ide-diagnostics/src/handlers/mutability_errors.rs index d9804cbd94ac..bdb55a9d98a2 100644 --- a/crates/ide-diagnostics/src/handlers/mutability_errors.rs +++ b/crates/ide-diagnostics/src/handlers/mutability_errors.rs @@ -19,7 +19,7 @@ pub(crate) fn need_mut(ctx: &DiagnosticsContext<'_>, d: &hir::NeedMut) -> Diagno for source in d.local.sources(ctx.sema.db) { let Some(ast) = source.name() else { continue }; // FIXME: macros - edit_builder.insert(ast.value.syntax().text_range().start(), "mut ".to_string()); + edit_builder.insert(ast.value.syntax().text_range().start(), "mut ".to_owned()); } let edit = edit_builder.finish(); Some(vec![fix( @@ -448,7 +448,7 @@ fn main(b: bool) { &mut x; } "#, - std::iter::once("remove-unnecessary-else".to_string()), + std::iter::once("remove-unnecessary-else".to_owned()), ); check_diagnostics_with_disabled( r#" @@ -463,7 +463,7 @@ fn main(b: bool) { &mut x; } "#, - std::iter::once("remove-unnecessary-else".to_string()), + std::iter::once("remove-unnecessary-else".to_owned()), ); } diff --git a/crates/ide-diagnostics/src/handlers/remove_trailing_return.rs b/crates/ide-diagnostics/src/handlers/remove_trailing_return.rs index 605e8baba0a2..a0d5d742d362 100644 --- a/crates/ide-diagnostics/src/handlers/remove_trailing_return.rs +++ b/crates/ide-diagnostics/src/handlers/remove_trailing_return.rs @@ -140,7 +140,7 @@ fn foo(x: usize) -> u8 { } //^^^^^^^^^ 💡 weak: replace return ; with } "#, - std::iter::once("remove-unnecessary-else".to_string()), + std::iter::once("remove-unnecessary-else".to_owned()), ); } @@ -309,7 +309,7 @@ fn foo(x: usize) -> u8 { } } "#, - std::iter::once("remove-unnecessary-else".to_string()), + std::iter::once("remove-unnecessary-else".to_owned()), ); check_fix( r#" diff --git a/crates/ide-diagnostics/src/handlers/remove_unnecessary_else.rs b/crates/ide-diagnostics/src/handlers/remove_unnecessary_else.rs index 124086c8fa11..ae8241ec2c69 100644 --- a/crates/ide-diagnostics/src/handlers/remove_unnecessary_else.rs +++ b/crates/ide-diagnostics/src/handlers/remove_unnecessary_else.rs @@ -90,7 +90,7 @@ mod tests { use crate::tests::{check_diagnostics, check_diagnostics_with_disabled, check_fix}; fn check_diagnostics_with_needless_return_disabled(ra_fixture: &str) { - check_diagnostics_with_disabled(ra_fixture, std::iter::once("needless_return".to_string())); + check_diagnostics_with_disabled(ra_fixture, std::iter::once("needless_return".to_owned())); } #[test] diff --git a/crates/ide-diagnostics/src/handlers/replace_filter_map_next_with_find_map.rs b/crates/ide-diagnostics/src/handlers/replace_filter_map_next_with_find_map.rs index 72896b891bdc..6d3dcf31ab4d 100644 --- a/crates/ide-diagnostics/src/handlers/replace_filter_map_next_with_find_map.rs +++ b/crates/ide-diagnostics/src/handlers/replace_filter_map_next_with_find_map.rs @@ -63,8 +63,8 @@ mod tests { #[track_caller] pub(crate) fn check_diagnostics(ra_fixture: &str) { let mut config = DiagnosticsConfig::test_sample(); - config.disabled.insert("inactive-code".to_string()); - config.disabled.insert("E0599".to_string()); + config.disabled.insert("inactive-code".to_owned()); + config.disabled.insert("E0599".to_owned()); check_diagnostics_with_config(config, ra_fixture) } diff --git a/crates/ide-diagnostics/src/handlers/trait_impl_orphan.rs b/crates/ide-diagnostics/src/handlers/trait_impl_orphan.rs index d36813381e43..78a04e15424f 100644 --- a/crates/ide-diagnostics/src/handlers/trait_impl_orphan.rs +++ b/crates/ide-diagnostics/src/handlers/trait_impl_orphan.rs @@ -13,7 +13,7 @@ pub(crate) fn trait_impl_orphan( ctx, DiagnosticCode::RustcHardError("E0117"), "only traits defined in the current crate can be implemented for arbitrary types" - .to_string(), + .to_owned(), InFile::new(d.file_id, d.impl_.into()), ) // Not yet checked for false positives diff --git a/crates/ide-diagnostics/src/handlers/trait_impl_redundant_assoc_item.rs b/crates/ide-diagnostics/src/handlers/trait_impl_redundant_assoc_item.rs index f58fcd1f7e2b..00710ef50760 100644 --- a/crates/ide-diagnostics/src/handlers/trait_impl_redundant_assoc_item.rs +++ b/crates/ide-diagnostics/src/handlers/trait_impl_redundant_assoc_item.rs @@ -103,7 +103,7 @@ fn quickfix_for_redundant_assoc_item( Some(vec![Assist { id: AssistId("add assoc item def into trait def", AssistKind::QuickFix), - label: Label::new("Add assoc item def into trait def".to_string()), + label: Label::new("Add assoc item def into trait def".to_owned()), group: None, target: range, source_change: Some(source_change_builder.finish()), diff --git a/crates/ide-diagnostics/src/handlers/type_mismatch.rs b/crates/ide-diagnostics/src/handlers/type_mismatch.rs index eec8efe785a6..e93eea8ce29e 100644 --- a/crates/ide-diagnostics/src/handlers/type_mismatch.rs +++ b/crates/ide-diagnostics/src/handlers/type_mismatch.rs @@ -120,7 +120,7 @@ fn add_missing_ok_or_some( let mut builder = TextEdit::builder(); builder.insert(expr.syntax().text_range().start(), format!("{variant_name}(")); - builder.insert(expr.syntax().text_range().end(), ")".to_string()); + builder.insert(expr.syntax().text_range().end(), ")".to_owned()); let source_change = SourceChange::from_text_edit(expr_ptr.file_id.original_file(ctx.sema.db), builder.finish()); let name = format!("Wrap in {variant_name}"); @@ -174,7 +174,7 @@ fn str_ref_to_owned( let expr = expr_ptr.value.to_node(&root); let expr_range = expr.syntax().text_range(); - let to_owned = ".to_owned()".to_string(); + let to_owned = ".to_owned()".to_owned(); let edit = TextEdit::insert(expr.syntax().text_range().end(), to_owned); let source_change = @@ -729,7 +729,7 @@ fn f() -> i32 { } fn g() { return; } "#, - std::iter::once("needless_return".to_string()), + std::iter::once("needless_return".to_owned()), ); } diff --git a/crates/ide-diagnostics/src/handlers/unimplemented_builtin_macro.rs b/crates/ide-diagnostics/src/handlers/unimplemented_builtin_macro.rs index 996b6eda59cf..06f176f86f4e 100644 --- a/crates/ide-diagnostics/src/handlers/unimplemented_builtin_macro.rs +++ b/crates/ide-diagnostics/src/handlers/unimplemented_builtin_macro.rs @@ -10,7 +10,7 @@ pub(crate) fn unimplemented_builtin_macro( Diagnostic::new_with_syntax_node_ptr( ctx, DiagnosticCode::Ra("unimplemented-builtin-macro", Severity::WeakWarning), - "unimplemented built-in macro".to_string(), + "unimplemented built-in macro".to_owned(), d.node, ) } diff --git a/crates/ide-diagnostics/src/handlers/unresolved_field.rs b/crates/ide-diagnostics/src/handlers/unresolved_field.rs index 0e7a5720d4d2..65abfd8a294b 100644 --- a/crates/ide-diagnostics/src/handlers/unresolved_field.rs +++ b/crates/ide-diagnostics/src/handlers/unresolved_field.rs @@ -65,7 +65,7 @@ fn method_fix( let FileRange { range, file_id } = ctx.sema.original_range_opt(expr.syntax())?; Some(vec![Assist { id: AssistId("expected-field-found-method-call-fix", AssistKind::QuickFix), - label: Label::new("Use parentheses to call the method".to_string()), + label: Label::new("Use parentheses to call the method".to_owned()), group: None, target: range, source_change: Some(SourceChange::from_text_edit( diff --git a/crates/ide-diagnostics/src/handlers/unresolved_method.rs b/crates/ide-diagnostics/src/handlers/unresolved_method.rs index 9f8fee67f31c..648d081898ce 100644 --- a/crates/ide-diagnostics/src/handlers/unresolved_method.rs +++ b/crates/ide-diagnostics/src/handlers/unresolved_method.rs @@ -101,7 +101,7 @@ fn field_fix( }; Some(Assist { id: AssistId("expected-method-found-field-fix", AssistKind::QuickFix), - label: Label::new("Use parentheses to call the value of the field".to_string()), + label: Label::new("Use parentheses to call the value of the field".to_owned()), group: None, target: range, source_change: Some(SourceChange::from_iter([ diff --git a/crates/ide-diagnostics/src/handlers/unresolved_module.rs b/crates/ide-diagnostics/src/handlers/unresolved_module.rs index 1604decf9073..115568832496 100644 --- a/crates/ide-diagnostics/src/handlers/unresolved_module.rs +++ b/crates/ide-diagnostics/src/handlers/unresolved_module.rs @@ -16,7 +16,7 @@ pub(crate) fn unresolved_module( ctx, DiagnosticCode::RustcHardError("E0583"), match &*d.candidates { - [] => "unresolved module".to_string(), + [] => "unresolved module".to_owned(), [candidate] => format!("unresolved module, can't find module file: {candidate}"), [candidates @ .., last] => { format!( @@ -46,7 +46,7 @@ fn fixes(ctx: &DiagnosticsContext<'_>, d: &hir::UnresolvedModule) -> Option format!("proc macro `{name}` not expanded"), - None => "proc macro not expanded".to_string(), + None => "proc macro not expanded".to_owned(), }; let severity = if config_enabled { Severity::Error } else { Severity::WeakWarning }; let def_map = ctx.sema.db.crate_def_map(d.krate); diff --git a/crates/ide-diagnostics/src/handlers/useless_braces.rs b/crates/ide-diagnostics/src/handlers/useless_braces.rs index 8dce2af23e32..863a7ab783ec 100644 --- a/crates/ide-diagnostics/src/handlers/useless_braces.rs +++ b/crates/ide-diagnostics/src/handlers/useless_braces.rs @@ -40,7 +40,7 @@ pub(crate) fn useless_braces( acc.push( Diagnostic::new( DiagnosticCode::RustcLint("unused_braces"), - "Unnecessary braces in use statement".to_string(), + "Unnecessary braces in use statement".to_owned(), FileRange { file_id, range: use_range }, ) .with_main_node(InFile::new(file_id.into(), node.clone())) @@ -112,7 +112,7 @@ mod a { ); let mut config = DiagnosticsConfig::test_sample(); - config.disabled.insert("syntax-error".to_string()); + config.disabled.insert("syntax-error".to_owned()); check_diagnostics_with_config( config, r#" diff --git a/crates/ide-diagnostics/src/lib.rs b/crates/ide-diagnostics/src/lib.rs index 7c5cf673303f..9d21bb4cd9fb 100644 --- a/crates/ide-diagnostics/src/lib.rs +++ b/crates/ide-diagnostics/src/lib.rs @@ -563,7 +563,7 @@ fn unresolved_fix(id: &'static str, label: &str, target: TextRange) -> Assist { assert!(!id.contains(' ')); Assist { id: AssistId(id, AssistKind::QuickFix), - label: Label::new(label.to_string()), + label: Label::new(label.to_owned()), group: None, target, source_change: None, diff --git a/crates/ide-diagnostics/src/tests.rs b/crates/ide-diagnostics/src/tests.rs index da563b874bd5..b62bb5affdd8 100644 --- a/crates/ide-diagnostics/src/tests.rs +++ b/crates/ide-diagnostics/src/tests.rs @@ -108,7 +108,7 @@ pub(crate) fn check_no_fix(ra_fixture: &str) { #[track_caller] pub(crate) fn check_diagnostics(ra_fixture: &str) { let mut config = DiagnosticsConfig::test_sample(); - config.disabled.insert("inactive-code".to_string()); + config.disabled.insert("inactive-code".to_owned()); check_diagnostics_with_config(config, ra_fixture) } @@ -207,8 +207,8 @@ fn minicore_smoke_test() { let source = minicore.source_code(); let mut config = DiagnosticsConfig::test_sample(); // This should be ignored since we conditionally remove code which creates single item use with braces - config.disabled.insert("unused_braces".to_string()); - config.disabled.insert("unused_variables".to_string()); + config.disabled.insert("unused_braces".to_owned()); + config.disabled.insert("unused_variables".to_owned()); check_diagnostics_with_config(config, &source); } From 5d1f2835af1e9dc67c1a0b72ccb0c0ccf9a413b4 Mon Sep 17 00:00:00 2001 From: Tetsuharu Ohzeki Date: Sat, 10 Feb 2024 00:37:27 +0900 Subject: [PATCH 08/28] project-model: Fix warnings about clippy `str_to_string` rule --- crates/project-model/src/build_scripts.rs | 8 ++++---- crates/project-model/src/cargo_workspace.rs | 6 +++--- crates/project-model/src/cfg_flag.rs | 2 +- crates/project-model/src/lib.rs | 2 +- crates/project-model/src/rustc_cfg.rs | 2 +- crates/project-model/src/tests.rs | 2 +- crates/project-model/src/workspace.rs | 10 +++++----- 7 files changed, 16 insertions(+), 16 deletions(-) diff --git a/crates/project-model/src/build_scripts.rs b/crates/project-model/src/build_scripts.rs index c1670c200490..a2c9856a3f73 100644 --- a/crates/project-model/src/build_scripts.rs +++ b/crates/project-model/src/build_scripts.rs @@ -322,7 +322,7 @@ impl WorkspaceBuildScripts { let mut deserializer = serde_json::Deserializer::from_str(line); deserializer.disable_recursion_limit(); let message = Message::deserialize(&mut deserializer) - .unwrap_or_else(|_| Message::TextLine(line.to_string())); + .unwrap_or_else(|_| Message::TextLine(line.to_owned())); match message { Message::BuildScriptExecuted(mut message) => { @@ -356,7 +356,7 @@ impl WorkspaceBuildScripts { if let Some(out_dir) = out_dir.as_os_str().to_str().map(|s| s.to_owned()) { - data.envs.push(("OUT_DIR".to_string(), out_dir)); + data.envs.push(("OUT_DIR".to_owned(), out_dir)); } data.out_dir = Some(out_dir); data.cfgs = cfgs; @@ -396,7 +396,7 @@ impl WorkspaceBuildScripts { let errors = if !output.status.success() { let errors = errors.into_inner(); - Some(if errors.is_empty() { "cargo check failed".to_string() } else { errors }) + Some(if errors.is_empty() { "cargo check failed".to_owned() } else { errors }) } else { None }; @@ -490,7 +490,7 @@ impl WorkspaceBuildScripts { // FIXME: Find a better way to know if it is a dylib. fn is_dylib(path: &Utf8Path) -> bool { - match path.extension().map(|e| e.to_string().to_lowercase()) { + match path.extension().map(|e| e.to_owned().to_lowercase()) { None => false, Some(ext) => matches!(ext.as_str(), "dll" | "dylib" | "so"), } diff --git a/crates/project-model/src/cargo_workspace.rs b/crates/project-model/src/cargo_workspace.rs index 5926e5a5f73b..a99ee6e664c5 100644 --- a/crates/project-model/src/cargo_workspace.rs +++ b/crates/project-model/src/cargo_workspace.rs @@ -285,7 +285,7 @@ impl CargoWorkspace { // FIXME: Fetching metadata is a slow process, as it might require // calling crates.io. We should be reporting progress here, but it's // unclear whether cargo itself supports it. - progress("metadata".to_string()); + progress("metadata".to_owned()); (|| -> Result { let mut command = meta.cargo_command(); @@ -502,7 +502,7 @@ fn rustc_discover_host_triple( let field = "host: "; let target = stdout.lines().find_map(|l| l.strip_prefix(field)); if let Some(target) = target { - Some(target.to_string()) + Some(target.to_owned()) } else { // If we fail to resolve the host platform, it's not the end of the world. tracing::info!("rustc -vV did not report host platform, got:\n{}", stdout); @@ -536,7 +536,7 @@ fn parse_output_cargo_config_build_target(stdout: String) -> Vec { let trimmed = stdout.trim_start_matches("build.target = ").trim_matches('"'); if !trimmed.starts_with('[') { - return [trimmed.to_string()].to_vec(); + return [trimmed.to_owned()].to_vec(); } let res = serde_json::from_str(trimmed); diff --git a/crates/project-model/src/cfg_flag.rs b/crates/project-model/src/cfg_flag.rs index e366d441c1bd..af682904b194 100644 --- a/crates/project-model/src/cfg_flag.rs +++ b/crates/project-model/src/cfg_flag.rs @@ -19,7 +19,7 @@ impl FromStr for CfgFlag { if !(value.starts_with('"') && value.ends_with('"')) { return Err(format!("Invalid cfg ({s:?}), value should be in quotes")); } - let key = key.to_string(); + let key = key.to_owned(); let value = value[1..value.len() - 1].to_string(); CfgFlag::KeyValue { key, value } } diff --git a/crates/project-model/src/lib.rs b/crates/project-model/src/lib.rs index 5114c9c016de..5b91f5d80589 100644 --- a/crates/project-model/src/lib.rs +++ b/crates/project-model/src/lib.rs @@ -167,7 +167,7 @@ fn utf8_stdout(mut cmd: Command) -> anyhow::Result { } } let stdout = String::from_utf8(output.stdout)?; - Ok(stdout.trim().to_string()) + Ok(stdout.trim().to_owned()) } #[derive(Copy, Clone, Debug, Default, PartialEq, Eq)] diff --git a/crates/project-model/src/rustc_cfg.rs b/crates/project-model/src/rustc_cfg.rs index cf12d5b71df5..0aee002fbb3f 100644 --- a/crates/project-model/src/rustc_cfg.rs +++ b/crates/project-model/src/rustc_cfg.rs @@ -33,7 +33,7 @@ pub(crate) fn get( res.push(CfgFlag::Atom("target_thread_local".into())); for ty in ["8", "16", "32", "64", "cas", "ptr"] { for key in ["target_has_atomic", "target_has_atomic_load_store"] { - res.push(CfgFlag::KeyValue { key: key.to_string(), value: ty.into() }); + res.push(CfgFlag::KeyValue { key: key.to_owned(), value: ty.into() }); } } diff --git a/crates/project-model/src/tests.rs b/crates/project-model/src/tests.rs index 7c078f72f529..74042e925ede 100644 --- a/crates/project-model/src/tests.rs +++ b/crates/project-model/src/tests.rs @@ -129,7 +129,7 @@ fn get_fake_sysroot() -> Sysroot { } fn rooted_project_json(data: ProjectJsonData) -> ProjectJson { - let mut root = "$ROOT$".to_string(); + let mut root = "$ROOT$".to_owned(); replace_root(&mut root, true); let path = Path::new(&root); let base = AbsPath::assert(path); diff --git a/crates/project-model/src/workspace.rs b/crates/project-model/src/workspace.rs index ad46b0bb59c5..cda5ad2f1109 100644 --- a/crates/project-model/src/workspace.rs +++ b/crates/project-model/src/workspace.rs @@ -241,7 +241,7 @@ impl ProjectWorkspace { .map_err(|p| Some(format!("rustc source path is not absolute: {p}"))), Some(RustLibSource::Discover) => { sysroot.as_ref().ok().and_then(Sysroot::discover_rustc_src).ok_or_else( - || Some("Failed to discover rustc source for sysroot.".to_string()), + || Some("Failed to discover rustc source for sysroot.".to_owned()), ) } None => Err(None), @@ -840,7 +840,7 @@ fn project_json_to_crate_graph( if let Some(name) = display_name.clone() { CrateOrigin::Local { repo: repository.clone(), - name: Some(name.canonical_name().to_string()), + name: Some(name.canonical_name().to_owned()), } } else { CrateOrigin::Local { repo: None, name: None } @@ -1117,7 +1117,7 @@ fn detached_files_to_crate_graph( let display_name = detached_file .file_stem() .and_then(|os_str| os_str.to_str()) - .map(|file_stem| CrateDisplayName::from_canonical_name(file_stem.to_string())); + .map(|file_stem| CrateDisplayName::from_canonical_name(file_stem.to_owned())); let detached_file_crate = crate_graph.add_crate_root( file_id, Edition::CURRENT, @@ -1129,7 +1129,7 @@ fn detached_files_to_crate_graph( false, CrateOrigin::Local { repo: None, - name: display_name.map(|n| n.canonical_name().to_string()), + name: display_name.map(|n| n.canonical_name().to_owned()), }, target_layout.clone(), None, @@ -1323,7 +1323,7 @@ fn add_target_crate_root( } } - let display_name = CrateDisplayName::from_canonical_name(cargo_name.to_string()); + let display_name = CrateDisplayName::from_canonical_name(cargo_name.to_owned()); let crate_id = crate_graph.add_crate_root( file_id, edition, From b89a4038c9212b08bed11db2f3915218fcfe4cc0 Mon Sep 17 00:00:00 2001 From: Tetsuharu Ohzeki Date: Sat, 10 Feb 2024 00:38:39 +0900 Subject: [PATCH 09/28] proc-macro-api: Fix warnings about clippy `str_to_string` rule --- crates/proc-macro-api/src/lib.rs | 2 +- crates/proc-macro-api/src/msg/flat.rs | 2 +- crates/proc-macro-api/src/process.rs | 6 +++--- crates/proc-macro-api/src/version.rs | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/crates/proc-macro-api/src/lib.rs b/crates/proc-macro-api/src/lib.rs index 379d184dd684..1dadfc40ac43 100644 --- a/crates/proc-macro-api/src/lib.rs +++ b/crates/proc-macro-api/src/lib.rs @@ -197,7 +197,7 @@ impl ProcMacro { &deserialize_span_data_index_map(&resp.span_data_table), ) })), - _ => Err(ServerError { message: "unexpected response".to_string(), io: None }), + _ => Err(ServerError { message: "unexpected response".to_owned(), io: None }), } } } diff --git a/crates/proc-macro-api/src/msg/flat.rs b/crates/proc-macro-api/src/msg/flat.rs index d4fdd5bde134..caf9e237fdd7 100644 --- a/crates/proc-macro-api/src/msg/flat.rs +++ b/crates/proc-macro-api/src/msg/flat.rs @@ -419,7 +419,7 @@ impl<'a, 'span, S: InternableSpan> Writer<'a, 'span, S> { let table = &mut self.text; *self.string_table.entry(text).or_insert_with(|| { let idx = table.len(); - table.push(text.to_string()); + table.push(text.to_owned()); idx as u32 }) } diff --git a/crates/proc-macro-api/src/process.rs b/crates/proc-macro-api/src/process.rs index 5ce601bce692..96f97bf5e205 100644 --- a/crates/proc-macro-api/src/process.rs +++ b/crates/proc-macro-api/src/process.rs @@ -78,7 +78,7 @@ impl ProcMacroProcessSrv { match response { Response::ApiVersionCheck(version) => Ok(version), - _ => Err(ServerError { message: "unexpected response".to_string(), io: None }), + _ => Err(ServerError { message: "unexpected response".to_owned(), io: None }), } } @@ -90,7 +90,7 @@ impl ProcMacroProcessSrv { match response { Response::SetConfig(crate::msg::ServerConfig { span_mode }) => Ok(span_mode), - _ => Err(ServerError { message: "unexpected response".to_string(), io: None }), + _ => Err(ServerError { message: "unexpected response".to_owned(), io: None }), } } @@ -104,7 +104,7 @@ impl ProcMacroProcessSrv { match response { Response::ListMacros(it) => Ok(it), - _ => Err(ServerError { message: "unexpected response".to_string(), io: None }), + _ => Err(ServerError { message: "unexpected response".to_owned(), io: None }), } } diff --git a/crates/proc-macro-api/src/version.rs b/crates/proc-macro-api/src/version.rs index 5f81c0a96d96..f768de3e31d4 100644 --- a/crates/proc-macro-api/src/version.rs +++ b/crates/proc-macro-api/src/version.rs @@ -38,7 +38,7 @@ pub fn read_dylib_info(dylib_path: &AbsPath) -> io::Result { let version_part = items.next().ok_or_else(|| err!("no version string"))?; let mut version_parts = version_part.split('-'); let version = version_parts.next().ok_or_else(|| err!("no version"))?; - let channel = version_parts.next().unwrap_or_default().to_string(); + let channel = version_parts.next().unwrap_or_default().to_owned(); let commit = match items.next() { Some(commit) => { From 80e684254da6bbe567199e1d9c6522cde3323d93 Mon Sep 17 00:00:00 2001 From: Tetsuharu Ohzeki Date: Sat, 10 Feb 2024 00:40:35 +0900 Subject: [PATCH 10/28] ide-assists: Fix warnings about clippy `str_to_string` rule --- crates/ide-assists/src/handlers/apply_demorgan.rs | 4 ++-- crates/ide-assists/src/handlers/convert_comment_block.rs | 2 +- crates/ide-assists/src/handlers/extract_function.rs | 4 ++-- crates/ide-assists/src/handlers/extract_variable.rs | 2 +- .../src/handlers/generate_documentation_template.rs | 4 ++-- crates/ide-assists/src/handlers/generate_enum_variant.rs | 2 +- crates/ide-assists/src/handlers/generate_function.rs | 4 ++-- crates/ide-assists/src/handlers/generate_is_empty_from_len.rs | 2 +- crates/ide-assists/src/handlers/generate_trait_from_impl.rs | 2 +- crates/ide-assists/src/handlers/inline_const_as_literal.rs | 2 +- crates/ide-assists/src/handlers/inline_macro.rs | 2 +- crates/ide-assists/src/handlers/introduce_named_lifetime.rs | 2 +- crates/ide-assists/src/handlers/move_module_to_file.rs | 2 +- crates/ide-assists/src/handlers/number_representation.rs | 2 +- crates/ide-assists/src/tests.rs | 4 ++-- crates/ide-assists/src/tests/sourcegen.rs | 4 ++-- crates/ide-assists/src/utils.rs | 2 +- crates/ide-assists/src/utils/suggest_name.rs | 4 ++-- 18 files changed, 25 insertions(+), 25 deletions(-) diff --git a/crates/ide-assists/src/handlers/apply_demorgan.rs b/crates/ide-assists/src/handlers/apply_demorgan.rs index 2d41243c20eb..55e0d7f3b28c 100644 --- a/crates/ide-assists/src/handlers/apply_demorgan.rs +++ b/crates/ide-assists/src/handlers/apply_demorgan.rs @@ -96,7 +96,7 @@ pub(crate) fn apply_demorgan(acc: &mut Assists, ctx: &AssistContext<'_>) -> Opti let dm_lhs = demorganed.lhs()?; acc.add_group( - &GroupLabel("Apply De Morgan's law".to_string()), + &GroupLabel("Apply De Morgan's law".to_owned()), AssistId("apply_demorgan", AssistKind::RefactorRewrite), "Apply De Morgan's law", op_range, @@ -187,7 +187,7 @@ pub(crate) fn apply_demorgan_iterator(acc: &mut Assists, ctx: &AssistContext<'_> let op_range = method_call.syntax().text_range(); let label = format!("Apply De Morgan's law to `Iterator::{}`", name.text().as_str()); acc.add_group( - &GroupLabel("Apply De Morgan's law".to_string()), + &GroupLabel("Apply De Morgan's law".to_owned()), AssistId("apply_demorgan_iterator", AssistKind::RefactorRewrite), label, op_range, diff --git a/crates/ide-assists/src/handlers/convert_comment_block.rs b/crates/ide-assists/src/handlers/convert_comment_block.rs index 3f478ee7d39a..fbc0b9f6739f 100644 --- a/crates/ide-assists/src/handlers/convert_comment_block.rs +++ b/crates/ide-assists/src/handlers/convert_comment_block.rs @@ -57,7 +57,7 @@ fn block_to_line(acc: &mut Assists, comment: ast::Comment) -> Option<()> { // Don't introduce trailing whitespace if line.is_empty() { - line_prefix.to_string() + line_prefix.to_owned() } else { format!("{line_prefix} {line}") } diff --git a/crates/ide-assists/src/handlers/extract_function.rs b/crates/ide-assists/src/handlers/extract_function.rs index 54e99e079593..d111005c2ec4 100644 --- a/crates/ide-assists/src/handlers/extract_function.rs +++ b/crates/ide-assists/src/handlers/extract_function.rs @@ -244,7 +244,7 @@ fn make_function_name(semantics_scope: &hir::SemanticsScope<'_>) -> ast::NameRef let default_name = "fun_name"; - let mut name = default_name.to_string(); + let mut name = default_name.to_owned(); let mut counter = 0; while names_in_scope.contains(&name) { counter += 1; @@ -1949,7 +1949,7 @@ fn with_tail_expr(block: ast::BlockExpr, tail_expr: ast::Expr) -> ast::BlockExpr } fn format_type(ty: &hir::Type, ctx: &AssistContext<'_>, module: hir::Module) -> String { - ty.display_source_code(ctx.db(), module.into(), true).ok().unwrap_or_else(|| "_".to_string()) + ty.display_source_code(ctx.db(), module.into(), true).ok().unwrap_or_else(|| "_".to_owned()) } fn make_ty(ty: &hir::Type, ctx: &AssistContext<'_>, module: hir::Module) -> ast::Type { diff --git a/crates/ide-assists/src/handlers/extract_variable.rs b/crates/ide-assists/src/handlers/extract_variable.rs index 22d16cf6b36e..36d312265120 100644 --- a/crates/ide-assists/src/handlers/extract_variable.rs +++ b/crates/ide-assists/src/handlers/extract_variable.rs @@ -115,7 +115,7 @@ pub(crate) fn extract_variable(acc: &mut Assists, ctx: &AssistContext<'_>) -> Op let trailing_ws = if prev_ws.is_some_and(|it| it.text().starts_with('\n')) { format!("\n{indent_to}") } else { - " ".to_string() + " ".to_owned() }; ted::insert_all_raw( diff --git a/crates/ide-assists/src/handlers/generate_documentation_template.rs b/crates/ide-assists/src/handlers/generate_documentation_template.rs index f298ce8916db..f720391cc82e 100644 --- a/crates/ide-assists/src/handlers/generate_documentation_template.rs +++ b/crates/ide-assists/src/handlers/generate_documentation_template.rs @@ -416,9 +416,9 @@ fn arguments_from_params(param_list: &ast::ParamList) -> String { true => format!("&mut {name}"), false => name.to_string(), }, - None => "_".to_string(), + None => "_".to_owned(), }, - _ => "_".to_string(), + _ => "_".to_owned(), }); args_iter.format(", ").to_string() } diff --git a/crates/ide-assists/src/handlers/generate_enum_variant.rs b/crates/ide-assists/src/handlers/generate_enum_variant.rs index 681f8c1fcf52..7faf2d5b1320 100644 --- a/crates/ide-assists/src/handlers/generate_enum_variant.rs +++ b/crates/ide-assists/src/handlers/generate_enum_variant.rs @@ -162,7 +162,7 @@ fn make_record_field_list( fn name_from_field(field: &ast::RecordExprField) -> ast::Name { let text = match field.name_ref() { Some(it) => it.to_string(), - None => name_from_field_shorthand(field).unwrap_or("unknown".to_string()), + None => name_from_field_shorthand(field).unwrap_or("unknown".to_owned()), }; make::name(&text) } diff --git a/crates/ide-assists/src/handlers/generate_function.rs b/crates/ide-assists/src/handlers/generate_function.rs index 1253bd803775..fe2f8ed6417d 100644 --- a/crates/ide-assists/src/handlers/generate_function.rs +++ b/crates/ide-assists/src/handlers/generate_function.rs @@ -202,7 +202,7 @@ fn get_adt_source( let file = ctx.sema.parse(range.file_id); let adt_source = ctx.sema.find_node_at_offset_with_macros(file.syntax(), range.range.start())?; - find_struct_impl(ctx, &adt_source, &[fn_name.to_string()]).map(|impl_| (impl_, range.file_id)) + find_struct_impl(ctx, &adt_source, &[fn_name.to_owned()]).map(|impl_| (impl_, range.file_id)) } struct FunctionTemplate { @@ -1007,7 +1007,7 @@ fn fn_arg_name(sema: &Semantics<'_, RootDatabase>, arg_expr: &ast::Expr) -> Stri name } Some(name) => name, - None => "arg".to_string(), + None => "arg".to_owned(), } } diff --git a/crates/ide-assists/src/handlers/generate_is_empty_from_len.rs b/crates/ide-assists/src/handlers/generate_is_empty_from_len.rs index 6bfc69b0ada6..4d369e705e88 100644 --- a/crates/ide-assists/src/handlers/generate_is_empty_from_len.rs +++ b/crates/ide-assists/src/handlers/generate_is_empty_from_len.rs @@ -79,7 +79,7 @@ pub(crate) fn generate_is_empty_from_len(acc: &mut Assists, ctx: &AssistContext< pub fn is_empty(&self) -> bool { self.len() == 0 }"# - .to_string(); + .to_owned(); builder.insert(range.end(), code) }, ) diff --git a/crates/ide-assists/src/handlers/generate_trait_from_impl.rs b/crates/ide-assists/src/handlers/generate_trait_from_impl.rs index 8881aa69f29d..24094de22c8d 100644 --- a/crates/ide-assists/src/handlers/generate_trait_from_impl.rs +++ b/crates/ide-assists/src/handlers/generate_trait_from_impl.rs @@ -118,7 +118,7 @@ pub(crate) fn generate_trait_from_impl(acc: &mut Assists, ctx: &AssistContext<'_ let arg_list = if let Some(genpars) = impl_ast.generic_param_list() { genpars.to_generic_args().to_string() } else { - "".to_string() + "".to_owned() }; if let Some(snippet_cap) = ctx.config.snippet_cap { diff --git a/crates/ide-assists/src/handlers/inline_const_as_literal.rs b/crates/ide-assists/src/handlers/inline_const_as_literal.rs index 18437453761c..111ea50fdc94 100644 --- a/crates/ide-assists/src/handlers/inline_const_as_literal.rs +++ b/crates/ide-assists/src/handlers/inline_const_as_literal.rs @@ -60,7 +60,7 @@ pub(crate) fn inline_const_as_literal(acc: &mut Assists, ctx: &AssistContext<'_> let id = AssistId("inline_const_as_literal", AssistKind::RefactorInline); - let label = "Inline const as literal".to_string(); + let label = "Inline const as literal".to_owned(); let target = variable.syntax().text_range(); return acc.add(id, label, target, |edit| { diff --git a/crates/ide-assists/src/handlers/inline_macro.rs b/crates/ide-assists/src/handlers/inline_macro.rs index c1beb46c8096..0c9e971dd23c 100644 --- a/crates/ide-assists/src/handlers/inline_macro.rs +++ b/crates/ide-assists/src/handlers/inline_macro.rs @@ -41,7 +41,7 @@ pub(crate) fn inline_macro(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option acc.add( AssistId("inline_macro", AssistKind::RefactorInline), - "Inline macro".to_string(), + "Inline macro".to_owned(), text_range, |builder| builder.replace(text_range, expanded.to_string()), ) diff --git a/crates/ide-assists/src/handlers/introduce_named_lifetime.rs b/crates/ide-assists/src/handlers/introduce_named_lifetime.rs index c5aa9755bc0b..62909c586e3d 100644 --- a/crates/ide-assists/src/handlers/introduce_named_lifetime.rs +++ b/crates/ide-assists/src/handlers/introduce_named_lifetime.rs @@ -129,7 +129,7 @@ fn generate_unique_lifetime_param_name( type_params.lifetime_params().map(|p| p.syntax().text().to_string()).collect(); ('a'..='z').map(|it| format!("'{it}")).find(|it| !used_lifetime_params.contains(it)) } - None => Some("'a".to_string()), + None => Some("'a".to_owned()), } .map(|it| make::lifetime(&it)) } diff --git a/crates/ide-assists/src/handlers/move_module_to_file.rs b/crates/ide-assists/src/handlers/move_module_to_file.rs index 166b25c69e18..048906d9d9f5 100644 --- a/crates/ide-assists/src/handlers/move_module_to_file.rs +++ b/crates/ide-assists/src/handlers/move_module_to_file.rs @@ -75,7 +75,7 @@ pub(crate) fn move_module_to_file(acc: &mut Assists, ctx: &AssistContext<'_>) -> let contents = { let items = module_items.dedent(IndentLevel(1)).to_string(); let mut items = - items.trim_start_matches('{').trim_end_matches('}').trim().to_string(); + items.trim_start_matches('{').trim_end_matches('}').trim().to_owned(); if !items.is_empty() { items.push('\n'); } diff --git a/crates/ide-assists/src/handlers/number_representation.rs b/crates/ide-assists/src/handlers/number_representation.rs index 7e3fef516bfd..a13799f9b131 100644 --- a/crates/ide-assists/src/handlers/number_representation.rs +++ b/crates/ide-assists/src/handlers/number_representation.rs @@ -33,7 +33,7 @@ pub(crate) fn reformat_number_literal(acc: &mut Assists, ctx: &AssistContext<'_> } let radix = literal.radix(); - let mut converted = prefix.to_string(); + let mut converted = prefix.to_owned(); converted.push_str(&add_group_separators(value, group_size(radix))); converted.push_str(suffix); diff --git a/crates/ide-assists/src/tests.rs b/crates/ide-assists/src/tests.rs index 466264d8e4da..9b6f7d018ee3 100644 --- a/crates/ide-assists/src/tests.rs +++ b/crates/ide-assists/src/tests.rs @@ -474,7 +474,7 @@ pub fn test_some_range(a: int) -> bool { &db, &cfg, AssistResolveStrategy::Single(SingleResolve { - assist_id: "SOMETHING_MISMATCHING".to_string(), + assist_id: "SOMETHING_MISMATCHING".to_owned(), assist_kind: AssistKind::RefactorExtract, }), frange, @@ -520,7 +520,7 @@ pub fn test_some_range(a: int) -> bool { &db, &cfg, AssistResolveStrategy::Single(SingleResolve { - assist_id: "extract_variable".to_string(), + assist_id: "extract_variable".to_owned(), assist_kind: AssistKind::RefactorExtract, }), frange, diff --git a/crates/ide-assists/src/tests/sourcegen.rs b/crates/ide-assists/src/tests/sourcegen.rs index 088d93f9a6ba..847cb1af51e0 100644 --- a/crates/ide-assists/src/tests/sourcegen.rs +++ b/crates/ide-assists/src/tests/sourcegen.rs @@ -15,7 +15,7 @@ fn sourcegen_assists_docs() { let mut buf = " use super::check_doc_test; " - .to_string(); + .to_owned(); for assist in assists.iter() { for (idx, section) in assist.sections.iter().enumerate() { let test_id = @@ -101,7 +101,7 @@ impl Assist { let mut assist = Assist { id, location, sections: Vec::new() }; while lines.peek().is_some() { - let doc = take_until(lines.by_ref(), "```").trim().to_string(); + let doc = take_until(lines.by_ref(), "```").trim().to_owned(); assert!( (doc.chars().next().unwrap().is_ascii_uppercase() && doc.ends_with('.')) || !assist.sections.is_empty(), diff --git a/crates/ide-assists/src/utils.rs b/crates/ide-assists/src/utils.rs index c167350be8d2..a4f14326751b 100644 --- a/crates/ide-assists/src/utils.rs +++ b/crates/ide-assists/src/utils.rs @@ -673,7 +673,7 @@ impl ReferenceConversion { pub(crate) fn convert_type(&self, db: &dyn HirDatabase) -> ast::Type { let ty = match self.conversion { ReferenceConversionType::Copy => self.ty.display(db).to_string(), - ReferenceConversionType::AsRefStr => "&str".to_string(), + ReferenceConversionType::AsRefStr => "&str".to_owned(), ReferenceConversionType::AsRefSlice => { let type_argument_name = self.ty.type_arguments().next().unwrap().display(db).to_string(); diff --git a/crates/ide-assists/src/utils/suggest_name.rs b/crates/ide-assists/src/utils/suggest_name.rs index 74377f8ec616..1859825b3d65 100644 --- a/crates/ide-assists/src/utils/suggest_name.rs +++ b/crates/ide-assists/src/utils/suggest_name.rs @@ -77,7 +77,7 @@ pub(crate) fn for_unique_generic_name( p => p.to_string(), }) .collect::>(); - let mut name = name.to_string(); + let mut name = name.to_owned(); let base_len = name.len(); let mut count = 0; while param_names.contains(&name) { @@ -165,7 +165,7 @@ pub(crate) fn for_variable(expr: &ast::Expr, sema: &Semantics<'_, RootDatabase>) } } - "var_name".to_string() + "var_name".to_owned() } fn normalize(name: &str) -> Option { From 395708d5e0793a5501f96c706877fb12b4f7eaf4 Mon Sep 17 00:00:00 2001 From: Tetsuharu Ohzeki Date: Sat, 10 Feb 2024 00:46:08 +0900 Subject: [PATCH 11/28] rust-analyzer: Fix warnings about clippy `str_to_string` rule --- crates/rust-analyzer/src/bin/main.rs | 4 +-- crates/rust-analyzer/src/caps.rs | 16 +++++----- .../rust-analyzer/src/cli/analysis_stats.rs | 8 ++--- crates/rust-analyzer/src/cli/diagnostics.rs | 2 +- crates/rust-analyzer/src/cli/lsif.rs | 10 +++---- .../rust-analyzer/src/cli/progress_report.rs | 2 +- crates/rust-analyzer/src/cli/run_tests.rs | 2 +- crates/rust-analyzer/src/cli/scip.rs | 14 ++++----- crates/rust-analyzer/src/config.rs | 4 +-- .../src/config/patch_old_style.rs | 2 +- crates/rust-analyzer/src/diagnostics.rs | 4 +-- .../rust-analyzer/src/diagnostics/to_proto.rs | 12 ++++---- crates/rust-analyzer/src/dispatch.rs | 6 ++-- crates/rust-analyzer/src/global_state.rs | 4 +-- .../src/handlers/notification.rs | 4 +-- crates/rust-analyzer/src/handlers/request.rs | 20 ++++++------- crates/rust-analyzer/src/lsp/from_proto.rs | 2 +- crates/rust-analyzer/src/lsp/to_proto.rs | 8 ++--- crates/rust-analyzer/src/lsp/utils.rs | 27 ++++++++--------- crates/rust-analyzer/src/main_loop.rs | 18 +++++------ crates/rust-analyzer/src/reload.rs | 6 ++-- crates/rust-analyzer/tests/slow-tests/main.rs | 30 +++++++++---------- .../rust-analyzer/tests/slow-tests/support.rs | 8 ++--- crates/rust-analyzer/tests/slow-tests/tidy.rs | 2 +- 24 files changed, 107 insertions(+), 108 deletions(-) diff --git a/crates/rust-analyzer/src/bin/main.rs b/crates/rust-analyzer/src/bin/main.rs index 72dc67b48a56..269dd3cfffe9 100644 --- a/crates/rust-analyzer/src/bin/main.rs +++ b/crates/rust-analyzer/src/bin/main.rs @@ -134,7 +134,7 @@ fn setup_logging(log_file_flag: Option) -> anyhow::Result<()> { writer, // Deliberately enable all `error` logs if the user has not set RA_LOG, as there is usually // useful information in there for debugging. - filter: env::var("RA_LOG").ok().unwrap_or_else(|| "error".to_string()), + filter: env::var("RA_LOG").ok().unwrap_or_else(|| "error".to_owned()), chalk_filter: env::var("CHALK_DEBUG").ok(), profile_filter: env::var("RA_PROFILE").ok(), } @@ -224,7 +224,7 @@ fn run_server() -> anyhow::Result<()> { MessageType, ShowMessageParams, }; let not = lsp_server::Notification::new( - ShowMessage::METHOD.to_string(), + ShowMessage::METHOD.to_owned(), ShowMessageParams { typ: MessageType::WARNING, message: e.to_string() }, ); connection.sender.send(lsp_server::Message::Notification(not)).unwrap(); diff --git a/crates/rust-analyzer/src/caps.rs b/crates/rust-analyzer/src/caps.rs index 94eab97e8fcd..a1469c22abf0 100644 --- a/crates/rust-analyzer/src/caps.rs +++ b/crates/rust-analyzer/src/caps.rs @@ -44,17 +44,17 @@ pub fn server_capabilities(config: &Config) -> ServerCapabilities { completion_provider: Some(CompletionOptions { resolve_provider: completions_resolve_provider(config.caps()), trigger_characters: Some(vec![ - ":".to_string(), - ".".to_string(), - "'".to_string(), - "(".to_string(), + ":".to_owned(), + ".".to_owned(), + "'".to_owned(), + "(".to_owned(), ]), all_commit_characters: None, completion_item: completion_item(config), work_done_progress_options: WorkDoneProgressOptions { work_done_progress: None }, }), signature_help_provider: Some(SignatureHelpOptions { - trigger_characters: Some(vec!["(".to_string(), ",".to_string(), "<".to_string()]), + trigger_characters: Some(vec!["(".to_owned(), ",".to_owned(), "<".to_owned()]), retrigger_characters: None, work_done_progress_options: WorkDoneProgressOptions { work_done_progress: None }, }), @@ -74,7 +74,7 @@ pub fn server_capabilities(config: &Config) -> ServerCapabilities { _ => Some(OneOf::Left(false)), }, document_on_type_formatting_provider: Some(DocumentOnTypeFormattingOptions { - first_trigger_character: "=".to_string(), + first_trigger_character: "=".to_owned(), more_trigger_character: Some(more_trigger_character(config)), }), selection_range_provider: Some(SelectionRangeProviderCapability::Simple(true)), @@ -222,9 +222,9 @@ fn code_action_capabilities(client_caps: &ClientCapabilities) -> CodeActionProvi } fn more_trigger_character(config: &Config) -> Vec { - let mut res = vec![".".to_string(), ">".to_string(), "{".to_string(), "(".to_string()]; + let mut res = vec![".".to_owned(), ">".to_owned(), "{".to_owned(), "(".to_owned()]; if config.snippet_cap() { - res.push("<".to_string()); + res.push("<".to_owned()); } res } diff --git a/crates/rust-analyzer/src/cli/analysis_stats.rs b/crates/rust-analyzer/src/cli/analysis_stats.rs index 31bdd2a0e82b..2741b4522256 100644 --- a/crates/rust-analyzer/src/cli/analysis_stats.rs +++ b/crates/rust-analyzer/src/cli/analysis_stats.rs @@ -397,7 +397,7 @@ impl flags::AnalysisStats { module .krate() .display_name(db) - .map(|it| it.canonical_name().to_string()) + .map(|it| it.canonical_name().to_owned()) .into_iter() .chain( module @@ -688,7 +688,7 @@ impl flags::AnalysisStats { module .krate() .display_name(db) - .map(|it| it.canonical_name().to_string()) + .map(|it| it.canonical_name().to_owned()) .into_iter() .chain( module @@ -833,7 +833,7 @@ impl flags::AnalysisStats { fn location_csv_expr(db: &RootDatabase, vfs: &Vfs, sm: &BodySourceMap, expr_id: ExprId) -> String { let src = match sm.expr_syntax(expr_id) { Ok(s) => s, - Err(SyntheticSyntax) => return "synthetic,,".to_string(), + Err(SyntheticSyntax) => return "synthetic,,".to_owned(), }; let root = db.parse_or_expand(src.file_id); let node = src.map(|e| e.to_node(&root).syntax().clone()); @@ -849,7 +849,7 @@ fn location_csv_expr(db: &RootDatabase, vfs: &Vfs, sm: &BodySourceMap, expr_id: fn location_csv_pat(db: &RootDatabase, vfs: &Vfs, sm: &BodySourceMap, pat_id: PatId) -> String { let src = match sm.pat_syntax(pat_id) { Ok(s) => s, - Err(SyntheticSyntax) => return "synthetic,,".to_string(), + Err(SyntheticSyntax) => return "synthetic,,".to_owned(), }; let root = db.parse_or_expand(src.file_id); let node = src.map(|e| e.to_node(&root).syntax().clone()); diff --git a/crates/rust-analyzer/src/cli/diagnostics.rs b/crates/rust-analyzer/src/cli/diagnostics.rs index 6d2e97be20e5..605670f6a82e 100644 --- a/crates/rust-analyzer/src/cli/diagnostics.rs +++ b/crates/rust-analyzer/src/cli/diagnostics.rs @@ -45,7 +45,7 @@ impl flags::Diagnostics { let file_id = module.definition_source_file_id(db).original_file(db); if !visited_files.contains(&file_id) { let crate_name = - module.krate().display_name(db).as_deref().unwrap_or("unknown").to_string(); + module.krate().display_name(db).as_deref().unwrap_or("unknown").to_owned(); println!("processing crate: {crate_name}, module: {}", _vfs.file_path(file_id)); for diagnostic in analysis .diagnostics( diff --git a/crates/rust-analyzer/src/cli/lsif.rs b/crates/rust-analyzer/src/cli/lsif.rs index 1b6187f8df56..1424a775777f 100644 --- a/crates/rust-analyzer/src/cli/lsif.rs +++ b/crates/rust-analyzer/src/cli/lsif.rs @@ -104,12 +104,12 @@ impl LsifManager<'_> { let result_set_id = self.add_vertex(lsif::Vertex::PackageInformation(lsif::PackageInformation { name: pi.name, - manager: "cargo".to_string(), + manager: "cargo".to_owned(), uri: None, content: None, repository: pi.repo.map(|url| lsif::Repository { url, - r#type: "git".to_string(), + r#type: "git".to_owned(), commit_id: None, }), version: pi.version, @@ -148,7 +148,7 @@ impl LsifManager<'_> { let path = self.vfs.file_path(id); let path = path.as_path().unwrap(); let doc_id = self.add_vertex(lsif::Vertex::Document(lsif::Document { - language_id: "rust".to_string(), + language_id: "rust".to_owned(), uri: lsp_types::Url::from_file_path(path).unwrap(), })); self.file_map.insert(id, doc_id); @@ -175,7 +175,7 @@ impl LsifManager<'_> { if let Some(moniker) = token.moniker { let package_id = self.get_package_id(moniker.package_information); let moniker_id = self.add_vertex(lsif::Vertex::Moniker(lsp_types::Moniker { - scheme: "rust-analyzer".to_string(), + scheme: "rust-analyzer".to_owned(), identifier: moniker.identifier.to_string(), unique: lsp_types::UniquenessLevel::Scheme, kind: Some(match moniker.kind { @@ -313,7 +313,7 @@ impl flags::Lsif { project_root: lsp_types::Url::from_file_path(path).unwrap(), position_encoding: lsif::Encoding::Utf16, tool_info: Some(lsp_types::lsif::ToolInfo { - name: "rust-analyzer".to_string(), + name: "rust-analyzer".to_owned(), args: vec![], version: Some(version().to_string()), }), diff --git a/crates/rust-analyzer/src/cli/progress_report.rs b/crates/rust-analyzer/src/cli/progress_report.rs index 8166aa23b447..b23373009973 100644 --- a/crates/rust-analyzer/src/cli/progress_report.rs +++ b/crates/rust-analyzer/src/cli/progress_report.rs @@ -92,7 +92,7 @@ impl<'a> ProgressReport<'a> { let _ = io::stdout().write(output.as_bytes()); let _ = io::stdout().flush(); - self.text = text.to_string(); + self.text = text.to_owned(); } fn set_value(&mut self, value: f32) { diff --git a/crates/rust-analyzer/src/cli/run_tests.rs b/crates/rust-analyzer/src/cli/run_tests.rs index d07dcdec2510..6b43e095429a 100644 --- a/crates/rust-analyzer/src/cli/run_tests.rs +++ b/crates/rust-analyzer/src/cli/run_tests.rs @@ -34,7 +34,7 @@ impl flags::RunTests { .filter(|x| x.is_test(db)); let span_formatter = |file_id, text_range: TextRange| { let line_col = match db.line_index(file_id).try_line_col(text_range.start()) { - None => " (unknown line col)".to_string(), + None => " (unknown line col)".to_owned(), Some(x) => format!("#{}:{}", x.line + 1, x.col), }; let path = &db diff --git a/crates/rust-analyzer/src/cli/scip.rs b/crates/rust-analyzer/src/cli/scip.rs index 1b0cfa6a5dc5..f4aec288348f 100644 --- a/crates/rust-analyzer/src/cli/scip.rs +++ b/crates/rust-analyzer/src/cli/scip.rs @@ -146,7 +146,7 @@ impl flags::Scip { let signature_documentation = token.signature.clone().map(|text| scip_types::Document { relative_path: relative_path.clone(), - language: "rust".to_string(), + language: "rust".to_owned(), text, position_encoding, ..Default::default() @@ -186,7 +186,7 @@ impl flags::Scip { scip_types::PositionEncoding::UTF8CodeUnitOffsetFromLineStart.into(); documents.push(scip_types::Document { relative_path, - language: "rust".to_string(), + language: "rust".to_owned(), occurrences, symbols, text: String::new(), @@ -216,7 +216,7 @@ fn get_relative_filepath( rootpath: &vfs::AbsPathBuf, file_id: ide::FileId, ) -> Option { - Some(vfs.file_path(file_id).as_path()?.strip_prefix(rootpath)?.as_ref().to_str()?.to_string()) + Some(vfs.file_path(file_id).as_path()?.strip_prefix(rootpath)?.as_ref().to_str()?.to_owned()) } // SCIP Ranges have a (very large) optimization that ranges if they are on the same line @@ -239,8 +239,8 @@ fn new_descriptor_str( suffix: scip_types::descriptor::Suffix, ) -> scip_types::Descriptor { scip_types::Descriptor { - name: name.to_string(), - disambiguator: "".to_string(), + name: name.to_owned(), + disambiguator: "".to_owned(), suffix: suffix.into(), special_fields: Default::default(), } @@ -311,9 +311,9 @@ fn moniker_to_symbol(moniker: &MonikerResult) -> scip_types::Symbol { scip_types::Symbol { scheme: "rust-analyzer".into(), package: Some(scip_types::Package { - manager: "cargo".to_string(), + manager: "cargo".to_owned(), name: package_name, - version: version.unwrap_or_else(|| ".".to_string()), + version: version.unwrap_or_else(|| ".".to_owned()), special_fields: Default::default(), }) .into(), diff --git a/crates/rust-analyzer/src/config.rs b/crates/rust-analyzer/src/config.rs index 3ba30cc38ef7..7bdd9ec866a5 100644 --- a/crates/rust-analyzer/src/config.rs +++ b/crates/rust-analyzer/src/config.rs @@ -904,7 +904,7 @@ impl Config { use serde::de::Error; if self.data.check_command.is_empty() { error_sink.push(( - "/check/command".to_string(), + "/check/command".to_owned(), serde_json::Error::custom("expected a non-empty string"), )); } @@ -2626,7 +2626,7 @@ mod tests { .replace('\n', "\n ") .trim_start_matches('\n') .trim_end() - .to_string(); + .to_owned(); schema.push_str(",\n"); // Transform the asciidoc form link to markdown style. diff --git a/crates/rust-analyzer/src/config/patch_old_style.rs b/crates/rust-analyzer/src/config/patch_old_style.rs index 73d2ed329845..92c0c0d048ab 100644 --- a/crates/rust-analyzer/src/config/patch_old_style.rs +++ b/crates/rust-analyzer/src/config/patch_old_style.rs @@ -19,7 +19,7 @@ pub(super) fn patch_json_for_outdated_configs(json: &mut Value) { Some(it) => { let mut last = it; for segment in [$(stringify!($dst)),+].into_iter().rev() { - last = Value::Object(serde_json::Map::from_iter(std::iter::once((segment.to_string(), last)))); + last = Value::Object(serde_json::Map::from_iter(std::iter::once((segment.to_owned(), last)))); } merge(json, last); diff --git a/crates/rust-analyzer/src/diagnostics.rs b/crates/rust-analyzer/src/diagnostics.rs index c91b22999ded..a0a53f545c9e 100644 --- a/crates/rust-analyzer/src/diagnostics.rs +++ b/crates/rust-analyzer/src/diagnostics.rs @@ -135,11 +135,11 @@ pub(crate) fn fetch_native_diagnostics( |line_index: &crate::line_index::LineIndex, d: ide::Diagnostic| lsp_types::Diagnostic { range: lsp::to_proto::range(line_index, d.range.range), severity: Some(lsp::to_proto::diagnostic_severity(d.severity)), - code: Some(lsp_types::NumberOrString::String(d.code.as_str().to_string())), + code: Some(lsp_types::NumberOrString::String(d.code.as_str().to_owned())), code_description: Some(lsp_types::CodeDescription { href: lsp_types::Url::parse(&d.code.url()).unwrap(), }), - source: Some("rust-analyzer".to_string()), + source: Some("rust-analyzer".to_owned()), message: d.message, related_information: None, tags: d.unused.then(|| vec![lsp_types::DiagnosticTag::UNNECESSARY]), diff --git a/crates/rust-analyzer/src/diagnostics/to_proto.rs b/crates/rust-analyzer/src/diagnostics/to_proto.rs index f79ae793c9a8..e900f2601d83 100644 --- a/crates/rust-analyzer/src/diagnostics/to_proto.rs +++ b/crates/rust-analyzer/src/diagnostics/to_proto.rs @@ -403,16 +403,16 @@ pub(crate) fn map_rust_diagnostic_to_lsp( related_info_macro_calls.push(lsp_types::DiagnosticRelatedInformation { location: secondary_location.clone(), message: if is_in_macro_call { - "Error originated from macro call here".to_string() + "Error originated from macro call here".to_owned() } else { - "Actual error occurred here".to_string() + "Actual error occurred here".to_owned() }, }); // For the additional in-macro diagnostic we add the inverse message pointing to the error location in code. let information_for_additional_diagnostic = vec![lsp_types::DiagnosticRelatedInformation { location: primary_location.clone(), - message: "Exact error occurred here".to_string(), + message: "Exact error occurred here".to_owned(), }]; let diagnostic = lsp_types::Diagnostic { @@ -467,7 +467,7 @@ pub(crate) fn map_rust_diagnostic_to_lsp( // `related_information`, which just produces hard-to-read links, at least in VS Code. let back_ref = lsp_types::DiagnosticRelatedInformation { location: primary_location, - message: "original diagnostic".to_string(), + message: "original diagnostic".to_owned(), }; for sub in &subdiagnostics { diagnostics.push(MappedRustDiagnostic { @@ -685,7 +685,7 @@ mod tests { fn rustc_unused_variable_as_info() { check_with_config( DiagnosticsMapConfig { - warnings_as_info: vec!["unused_variables".to_string()], + warnings_as_info: vec!["unused_variables".to_owned()], ..DiagnosticsMapConfig::default() }, r##"{ @@ -769,7 +769,7 @@ mod tests { fn rustc_unused_variable_as_hint() { check_with_config( DiagnosticsMapConfig { - warnings_as_hint: vec!["unused_variables".to_string()], + warnings_as_hint: vec!["unused_variables".to_owned()], ..DiagnosticsMapConfig::default() }, r##"{ diff --git a/crates/rust-analyzer/src/dispatch.rs b/crates/rust-analyzer/src/dispatch.rs index fa856a796a8e..7adaef4ff6ec 100644 --- a/crates/rust-analyzer/src/dispatch.rs +++ b/crates/rust-analyzer/src/dispatch.rs @@ -123,7 +123,7 @@ impl RequestDispatcher<'_> { Err(_) => Task::Response(lsp_server::Response::new_err( req.id, lsp_server::ErrorCode::ContentModified as i32, - "content modified".to_string(), + "content modified".to_owned(), )), } } @@ -179,7 +179,7 @@ impl RequestDispatcher<'_> { let response = lsp_server::Response::new_err( req.id, lsp_server::ErrorCode::MethodNotFound as i32, - "unknown request".to_string(), + "unknown request".to_owned(), ); self.global_state.respond(response); } @@ -269,7 +269,7 @@ where .map(String::as_str) .or_else(|| panic.downcast_ref::<&str>().copied()); - let mut message = "request handler panicked".to_string(); + let mut message = "request handler panicked".to_owned(); if let Some(panic_message) = panic_message { message.push_str(": "); message.push_str(panic_message) diff --git a/crates/rust-analyzer/src/global_state.rs b/crates/rust-analyzer/src/global_state.rs index 4b3bca8e4a2e..da4422a60a8a 100644 --- a/crates/rust-analyzer/src/global_state.rs +++ b/crates/rust-analyzer/src/global_state.rs @@ -388,7 +388,7 @@ impl GlobalState { params: R::Params, handler: ReqHandler, ) { - let request = self.req_queue.outgoing.register(R::METHOD.to_string(), params, handler); + let request = self.req_queue.outgoing.register(R::METHOD.to_owned(), params, handler); self.send(request.into()); } @@ -405,7 +405,7 @@ impl GlobalState { &self, params: N::Params, ) { - let not = lsp_server::Notification::new(N::METHOD.to_string(), params); + let not = lsp_server::Notification::new(N::METHOD.to_owned(), params); self.send(not.into()); } diff --git a/crates/rust-analyzer/src/handlers/notification.rs b/crates/rust-analyzer/src/handlers/notification.rs index 365d5fb2e050..d3c2073f09d2 100644 --- a/crates/rust-analyzer/src/handlers/notification.rs +++ b/crates/rust-analyzer/src/handlers/notification.rs @@ -184,7 +184,7 @@ pub(crate) fn handle_did_change_configuration( lsp_types::ConfigurationParams { items: vec![lsp_types::ConfigurationItem { scope_uri: None, - section: Some("rust-analyzer".to_string()), + section: Some("rust-analyzer".to_owned()), }], }, |this, resp| { @@ -236,7 +236,7 @@ pub(crate) fn handle_did_change_workspace_folders( if !config.has_linked_projects() && config.detached_files().is_empty() { config.rediscover_workspaces(); - state.fetch_workspaces_queue.request_op("client workspaces changed".to_string(), false) + state.fetch_workspaces_queue.request_op("client workspaces changed".to_owned(), false) } Ok(()) diff --git a/crates/rust-analyzer/src/handlers/request.rs b/crates/rust-analyzer/src/handlers/request.rs index 2be2ba5c4465..2a3633a48e9f 100644 --- a/crates/rust-analyzer/src/handlers/request.rs +++ b/crates/rust-analyzer/src/handlers/request.rs @@ -54,7 +54,7 @@ pub(crate) fn handle_workspace_reload(state: &mut GlobalState, _: ()) -> anyhow: state.proc_macro_clients = Arc::from_iter([]); state.proc_macro_changed = false; - state.fetch_workspaces_queue.request_op("reload workspace request".to_string(), false); + state.fetch_workspaces_queue.request_op("reload workspace request".to_owned(), false); Ok(()) } @@ -62,7 +62,7 @@ pub(crate) fn handle_proc_macros_rebuild(state: &mut GlobalState, _: ()) -> anyh state.proc_macro_clients = Arc::from_iter([]); state.proc_macro_changed = false; - state.fetch_build_data_queue.request_op("rebuild proc macros request".to_string(), ()); + state.fetch_build_data_queue.request_op("rebuild proc macros request".to_owned(), ()); Ok(()) } @@ -562,7 +562,7 @@ pub(crate) fn handle_will_rename_files( (Some(p1), Some(p2)) if p1 == p2 => { if from_path.is_dir() { // add '/' to end of url -- from `file://path/to/folder` to `file://path/to/folder/` - let mut old_folder_name = from_path.file_stem()?.to_str()?.to_string(); + let mut old_folder_name = from_path.file_stem()?.to_str()?.to_owned(); old_folder_name.push('/'); let from_with_trailing_slash = from.join(&old_folder_name).ok()?; @@ -570,7 +570,7 @@ pub(crate) fn handle_will_rename_files( let new_file_name = to_path.file_name()?.to_str()?; Some(( snap.url_to_file_id(&imitate_from_url).ok()?, - new_file_name.to_string(), + new_file_name.to_owned(), )) } else { let old_name = from_path.file_stem()?.to_str()?; @@ -578,7 +578,7 @@ pub(crate) fn handle_will_rename_files( match (old_name, new_name) { ("mod", _) => None, (_, "mod") => None, - _ => Some((snap.url_to_file_id(&from).ok()?, new_name.to_string())), + _ => Some((snap.url_to_file_id(&from).ok()?, new_name.to_owned())), } } } @@ -799,13 +799,13 @@ pub(crate) fn handle_runnables( None => { if !snap.config.linked_or_discovered_projects().is_empty() { res.push(lsp_ext::Runnable { - label: "cargo check --workspace".to_string(), + label: "cargo check --workspace".to_owned(), location: None, kind: lsp_ext::RunnableKind::Cargo, args: lsp_ext::CargoRunnable { workspace_root: None, override_cargo: config.override_cargo, - cargo_args: vec!["check".to_string(), "--workspace".to_string()], + cargo_args: vec!["check".to_owned(), "--workspace".to_owned()], cargo_extra_args: config.cargo_extra_args, executable_args: Vec::new(), expect_test: None, @@ -879,7 +879,7 @@ pub(crate) fn handle_completion_resolve( if !all_edits_are_disjoint(&original_completion, &[]) { return Err(invalid_params_error( - "Received a completion with overlapping edits, this is not LSP-compliant".to_string(), + "Received a completion with overlapping edits, this is not LSP-compliant".to_owned(), ) .into()); } @@ -1191,7 +1191,7 @@ pub(crate) fn handle_code_action_resolve( let _p = tracing::span!(tracing::Level::INFO, "handle_code_action_resolve").entered(); let params = match code_action.data.take() { Some(it) => it, - None => return Err(invalid_params_error("code action without data".to_string()).into()), + None => return Err(invalid_params_error("code action without data".to_owned()).into()), }; let file_id = from_proto::file_id(&snap, ¶ms.code_action_params.text_document.uri)?; @@ -1270,7 +1270,7 @@ fn parse_action_id(action_id: &str) -> anyhow::Result<(usize, SingleResolve), St }; Ok((index, SingleResolve { assist_id: assist_id_string.to_string(), assist_kind })) } - _ => Err("Action id contains incorrect number of segments".to_string()), + _ => Err("Action id contains incorrect number of segments".to_owned()), } } diff --git a/crates/rust-analyzer/src/lsp/from_proto.rs b/crates/rust-analyzer/src/lsp/from_proto.rs index 9923be382b77..f42985a91610 100644 --- a/crates/rust-analyzer/src/lsp/from_proto.rs +++ b/crates/rust-analyzer/src/lsp/from_proto.rs @@ -108,7 +108,7 @@ pub(crate) fn annotation( code_lens: lsp_types::CodeLens, ) -> anyhow::Result> { let data = - code_lens.data.ok_or_else(|| invalid_params_error("code lens without data".to_string()))?; + code_lens.data.ok_or_else(|| invalid_params_error("code lens without data".to_owned()))?; let resolve = from_json::("CodeLensResolveData", &data)?; match resolve.kind { diff --git a/crates/rust-analyzer/src/lsp/to_proto.rs b/crates/rust-analyzer/src/lsp/to_proto.rs index d363ac69fdc3..64f19f0b32d7 100644 --- a/crates/rust-analyzer/src/lsp/to_proto.rs +++ b/crates/rust-analyzer/src/lsp/to_proto.rs @@ -245,7 +245,7 @@ fn completion_item( ) { let insert_replace_support = config.insert_replace_support().then_some(tdpp.position); let ref_match = item.ref_match(); - let lookup = item.lookup().to_string(); + let lookup = item.lookup().to_owned(); let mut additional_text_edits = Vec::new(); @@ -367,7 +367,7 @@ pub(crate) fn signature_help( let params = call_info .parameter_labels() .map(|label| lsp_types::ParameterInformation { - label: lsp_types::ParameterLabel::Simple(label.to_string()), + label: lsp_types::ParameterLabel::Simple(label.to_owned()), documentation: None, }) .collect::>(); @@ -1498,7 +1498,7 @@ pub(crate) mod command { pub(crate) fn run_single(runnable: &lsp_ext::Runnable, title: &str) -> lsp_types::Command { lsp_types::Command { - title: title.to_string(), + title: title.to_owned(), command: "rust-analyzer.runSingle".into(), arguments: Some(vec![to_value(runnable).unwrap()]), } @@ -1608,7 +1608,7 @@ fn main() { } }"#; - let (analysis, file_id) = Analysis::from_single_file(text.to_string()); + let (analysis, file_id) = Analysis::from_single_file(text.to_owned()); let folds = analysis.folding_ranges(file_id).unwrap(); assert_eq!(folds.len(), 4); diff --git a/crates/rust-analyzer/src/lsp/utils.rs b/crates/rust-analyzer/src/lsp/utils.rs index fa5ea5b57db0..10335cb14533 100644 --- a/crates/rust-analyzer/src/lsp/utils.rs +++ b/crates/rust-analyzer/src/lsp/utils.rs @@ -333,21 +333,20 @@ mod tests { #[test] fn empty_completion_disjoint_tests() { - let empty_completion = - CompletionItem::new_simple("label".to_string(), "detail".to_string()); + let empty_completion = CompletionItem::new_simple("label".to_owned(), "detail".to_owned()); let disjoint_edit_1 = lsp_types::TextEdit::new( Range::new(Position::new(2, 2), Position::new(3, 3)), - "new_text".to_string(), + "new_text".to_owned(), ); let disjoint_edit_2 = lsp_types::TextEdit::new( Range::new(Position::new(3, 3), Position::new(4, 4)), - "new_text".to_string(), + "new_text".to_owned(), ); let joint_edit = lsp_types::TextEdit::new( Range::new(Position::new(1, 1), Position::new(5, 5)), - "new_text".to_string(), + "new_text".to_owned(), ); assert!( @@ -375,19 +374,19 @@ mod tests { fn completion_with_joint_edits_disjoint_tests() { let disjoint_edit = lsp_types::TextEdit::new( Range::new(Position::new(1, 1), Position::new(2, 2)), - "new_text".to_string(), + "new_text".to_owned(), ); let disjoint_edit_2 = lsp_types::TextEdit::new( Range::new(Position::new(2, 2), Position::new(3, 3)), - "new_text".to_string(), + "new_text".to_owned(), ); let joint_edit = lsp_types::TextEdit::new( Range::new(Position::new(1, 1), Position::new(5, 5)), - "new_text".to_string(), + "new_text".to_owned(), ); let mut completion_with_joint_edits = - CompletionItem::new_simple("label".to_string(), "detail".to_string()); + CompletionItem::new_simple("label".to_owned(), "detail".to_owned()); completion_with_joint_edits.additional_text_edits = Some(vec![disjoint_edit.clone(), joint_edit.clone()]); assert!( @@ -405,7 +404,7 @@ mod tests { completion_with_joint_edits.text_edit = Some(CompletionTextEdit::InsertAndReplace(InsertReplaceEdit { - new_text: "new_text".to_string(), + new_text: "new_text".to_owned(), insert: disjoint_edit.range, replace: disjoint_edit_2.range, })); @@ -420,19 +419,19 @@ mod tests { fn completion_with_disjoint_edits_disjoint_tests() { let disjoint_edit = lsp_types::TextEdit::new( Range::new(Position::new(1, 1), Position::new(2, 2)), - "new_text".to_string(), + "new_text".to_owned(), ); let disjoint_edit_2 = lsp_types::TextEdit::new( Range::new(Position::new(2, 2), Position::new(3, 3)), - "new_text".to_string(), + "new_text".to_owned(), ); let joint_edit = lsp_types::TextEdit::new( Range::new(Position::new(1, 1), Position::new(5, 5)), - "new_text".to_string(), + "new_text".to_owned(), ); let mut completion_with_disjoint_edits = - CompletionItem::new_simple("label".to_string(), "detail".to_string()); + CompletionItem::new_simple("label".to_owned(), "detail".to_owned()); completion_with_disjoint_edits.text_edit = Some(CompletionTextEdit::Edit(disjoint_edit)); let completion_with_disjoint_edits = completion_with_disjoint_edits; diff --git a/crates/rust-analyzer/src/main_loop.rs b/crates/rust-analyzer/src/main_loop.rs index 2a431a88bc7e..88660db7e93b 100644 --- a/crates/rust-analyzer/src/main_loop.rs +++ b/crates/rust-analyzer/src/main_loop.rs @@ -139,7 +139,7 @@ impl GlobalState { self.register_did_save_capability(); } - self.fetch_workspaces_queue.request_op("startup".to_string(), false); + self.fetch_workspaces_queue.request_op("startup".to_owned(), false); if let Some((cause, force_crate_graph_reload)) = self.fetch_workspaces_queue.should_start_op() { @@ -185,8 +185,8 @@ impl GlobalState { }; let registration = lsp_types::Registration { - id: "textDocument/didSave".to_string(), - method: "textDocument/didSave".to_string(), + id: "textDocument/didSave".to_owned(), + method: "textDocument/didSave".to_owned(), register_options: Some(serde_json::to_value(save_registration_options).unwrap()), }; self.send_request::( @@ -296,7 +296,7 @@ impl GlobalState { self.prime_caches_queue.op_completed(()); if cancelled { self.prime_caches_queue - .request_op("restart after cancellation".to_string(), ()); + .request_op("restart after cancellation".to_owned(), ()); } } }; @@ -340,7 +340,7 @@ impl GlobalState { self.flycheck.iter().for_each(FlycheckHandle::restart_workspace); } if self.config.prefill_caches() { - self.prime_caches_queue.request_op("became quiescent".to_string(), ()); + self.prime_caches_queue.request_op("became quiescent".to_owned(), ()); } } @@ -390,7 +390,7 @@ impl GlobalState { // See https://github.com/rust-lang/rust-analyzer/issues/13130 let patch_empty = |message: &mut String| { if message.is_empty() { - *message = " ".to_string(); + *message = " ".to_owned(); } }; @@ -557,12 +557,12 @@ impl GlobalState { } let old = Arc::clone(&self.workspaces); - self.switch_workspaces("fetched workspace".to_string()); + self.switch_workspaces("fetched workspace".to_owned()); let workspaces_updated = !Arc::ptr_eq(&old, &self.workspaces); if self.config.run_build_scripts() && workspaces_updated { self.fetch_build_data_queue - .request_op("workspace updated".to_string(), ()); + .request_op("workspace updated".to_owned(), ()); } (Progress::End, None) @@ -581,7 +581,7 @@ impl GlobalState { tracing::error!("FetchBuildDataError:\n{e}"); } - self.switch_workspaces("fetched build data".to_string()); + self.switch_workspaces("fetched build data".to_owned()); self.send_hint_refresh_query = true; (Some(Progress::End), None) diff --git a/crates/rust-analyzer/src/reload.rs b/crates/rust-analyzer/src/reload.rs index dcf6089ca7bb..7bd2877b00cb 100644 --- a/crates/rust-analyzer/src/reload.rs +++ b/crates/rust-analyzer/src/reload.rs @@ -83,7 +83,7 @@ impl GlobalState { } if self.config.linked_or_discovered_projects() != old_config.linked_or_discovered_projects() { - self.fetch_workspaces_queue.request_op("linked projects changed".to_string(), false) + self.fetch_workspaces_queue.request_op("linked projects changed".to_owned(), false) } else if self.config.flycheck() != old_config.flycheck() { self.reload_flycheck(); } @@ -440,8 +440,8 @@ impl GlobalState { .collect(), }; let registration = lsp_types::Registration { - id: "workspace/didChangeWatchedFiles".to_string(), - method: "workspace/didChangeWatchedFiles".to_string(), + id: "workspace/didChangeWatchedFiles".to_owned(), + method: "workspace/didChangeWatchedFiles".to_owned(), register_options: Some(serde_json::to_value(registration_options).unwrap()), }; self.send_request::( diff --git a/crates/rust-analyzer/tests/slow-tests/main.rs b/crates/rust-analyzer/tests/slow-tests/main.rs index 1ee1c1489a9a..79ae0c30cfc4 100644 --- a/crates/rust-analyzer/tests/slow-tests/main.rs +++ b/crates/rust-analyzer/tests/slow-tests/main.rs @@ -632,9 +632,9 @@ fn main() {{}} server.notification::(DidOpenTextDocumentParams { text_document: TextDocumentItem { uri: uri.clone(), - language_id: "rust".to_string(), + language_id: "rust".to_owned(), version: 0, - text: "/// Docs\nfn foo() {}".to_string(), + text: "/// Docs\nfn foo() {}".to_owned(), }, }); let expected = json!({ @@ -682,9 +682,9 @@ fn main() {{}} server.notification::(DidOpenTextDocumentParams { text_document: TextDocumentItem { uri: server.doc_id(&format!("src/m{i}.rs")).uri, - language_id: "rust".to_string(), + language_id: "rust".to_owned(), version: 0, - text: "/// Docs\nfn foo() {}".to_string(), + text: "/// Docs\nfn foo() {}".to_owned(), }, }); } @@ -1078,15 +1078,15 @@ use crate::old_folder::nested::foo as bar; server.request::( RenameFilesParams { files: vec![FileRename { - old_uri: base_path.join("src/old_file.rs").to_str().unwrap().to_string(), - new_uri: base_path.join("src/new_file.rs").to_str().unwrap().to_string(), + old_uri: base_path.join("src/old_file.rs").to_str().unwrap().to_owned(), + new_uri: base_path.join("src/new_file.rs").to_str().unwrap().to_owned(), }], }, json!({ "documentChanges": [ { "textDocument": { - "uri": format!("file://{}", tmp_dir_path.join("src").join("lib.rs").to_str().unwrap().to_string().replace("C:\\", "/c:/").replace('\\', "/")), + "uri": format!("file://{}", tmp_dir_path.join("src").join("lib.rs").to_str().unwrap().to_owned().replace("C:\\", "/c:/").replace('\\', "/")), "version": null }, "edits": [ @@ -1113,8 +1113,8 @@ use crate::old_folder::nested::foo as bar; server.request::( RenameFilesParams { files: vec![FileRename { - old_uri: base_path.join("src/from_mod/mod.rs").to_str().unwrap().to_string(), - new_uri: base_path.join("src/from_mod/foo.rs").to_str().unwrap().to_string(), + old_uri: base_path.join("src/from_mod/mod.rs").to_str().unwrap().to_owned(), + new_uri: base_path.join("src/from_mod/foo.rs").to_str().unwrap().to_owned(), }], }, json!(null), @@ -1124,8 +1124,8 @@ use crate::old_folder::nested::foo as bar; server.request::( RenameFilesParams { files: vec![FileRename { - old_uri: base_path.join("src/to_mod/foo.rs").to_str().unwrap().to_string(), - new_uri: base_path.join("src/to_mod/mod.rs").to_str().unwrap().to_string(), + old_uri: base_path.join("src/to_mod/foo.rs").to_str().unwrap().to_owned(), + new_uri: base_path.join("src/to_mod/mod.rs").to_str().unwrap().to_owned(), }], }, json!(null), @@ -1135,15 +1135,15 @@ use crate::old_folder::nested::foo as bar; server.request::( RenameFilesParams { files: vec![FileRename { - old_uri: base_path.join("src/old_folder").to_str().unwrap().to_string(), - new_uri: base_path.join("src/new_folder").to_str().unwrap().to_string(), + old_uri: base_path.join("src/old_folder").to_str().unwrap().to_owned(), + new_uri: base_path.join("src/new_folder").to_str().unwrap().to_owned(), }], }, json!({ "documentChanges": [ { "textDocument": { - "uri": format!("file://{}", tmp_dir_path.join("src").join("lib.rs").to_str().unwrap().to_string().replace("C:\\", "/c:/").replace('\\', "/")), + "uri": format!("file://{}", tmp_dir_path.join("src").join("lib.rs").to_str().unwrap().to_owned().replace("C:\\", "/c:/").replace('\\', "/")), "version": null }, "edits": [ @@ -1164,7 +1164,7 @@ use crate::old_folder::nested::foo as bar; }, { "textDocument": { - "uri": format!("file://{}", tmp_dir_path.join("src").join("old_folder").join("nested.rs").to_str().unwrap().to_string().replace("C:\\", "/c:/").replace('\\', "/")), + "uri": format!("file://{}", tmp_dir_path.join("src").join("old_folder").join("nested.rs").to_str().unwrap().to_owned().replace("C:\\", "/c:/").replace('\\', "/")), "version": null }, "edits": [ diff --git a/crates/rust-analyzer/tests/slow-tests/support.rs b/crates/rust-analyzer/tests/slow-tests/support.rs index c2bdefa217aa..d02cb45b8e35 100644 --- a/crates/rust-analyzer/tests/slow-tests/support.rs +++ b/crates/rust-analyzer/tests/slow-tests/support.rs @@ -95,7 +95,7 @@ impl Project<'_> { writer: TestWriter::default(), // Deliberately enable all `error` logs if the user has not set RA_LOG, as there is usually // useful information in there for debugging. - filter: std::env::var("RA_LOG").ok().unwrap_or_else(|| "error".to_string()), + filter: std::env::var("RA_LOG").ok().unwrap_or_else(|| "error".to_owned()), chalk_filter: std::env::var("CHALK_DEBUG").ok(), profile_filter: std::env::var("RA_PROFILE").ok(), }; @@ -193,7 +193,7 @@ impl Server { let (connection, client) = Connection::memory(); let _thread = stdx::thread::Builder::new(stdx::thread::ThreadIntent::Worker) - .name("test server".to_string()) + .name("test server".to_owned()) .spawn(move || main_loop(config, connection).unwrap()) .expect("failed to spawn a thread"); @@ -210,7 +210,7 @@ impl Server { N: lsp_types::notification::Notification, N::Params: Serialize, { - let r = Notification::new(N::METHOD.to_string(), params); + let r = Notification::new(N::METHOD.to_owned(), params); self.send_notification(r) } @@ -274,7 +274,7 @@ impl Server { let id = self.req_id.get(); self.req_id.set(id.wrapping_add(1)); - let r = Request::new(id.into(), R::METHOD.to_string(), params); + let r = Request::new(id.into(), R::METHOD.to_owned(), params); self.send_request_(r) } fn send_request_(&self, r: Request) -> Value { diff --git a/crates/rust-analyzer/tests/slow-tests/tidy.rs b/crates/rust-analyzer/tests/slow-tests/tidy.rs index 740626dfe382..3e38fc3ebcd7 100644 --- a/crates/rust-analyzer/tests/slow-tests/tidy.rs +++ b/crates/rust-analyzer/tests/slow-tests/tidy.rs @@ -373,7 +373,7 @@ fn find_marks(set: &mut HashSet, text: &str, mark: &str) { text = stripped_text.trim_start(); if let Some(idx2) = text.find(|c: char| !(c.is_alphanumeric() || c == '_')) { let mark_text = &text[..idx2]; - set.insert(mark_text.to_string()); + set.insert(mark_text.to_owned()); text = &text[idx2..]; } } From f4a4b6681b366eed2cc5e9817eab560cb08571a7 Mon Sep 17 00:00:00 2001 From: Tetsuharu Ohzeki Date: Sat, 10 Feb 2024 00:47:35 +0900 Subject: [PATCH 12/28] ide-completion: Fix warnings about clippy `str_to_string` rule --- crates/ide-completion/src/completions/extern_crate.rs | 4 ++-- crates/ide-completion/src/completions/postfix.rs | 2 +- crates/ide-completion/src/context.rs | 2 +- crates/ide-completion/src/item.rs | 2 +- crates/ide-completion/src/render.rs | 6 +++--- crates/ide-completion/src/render/function.rs | 4 ++-- crates/ide-completion/src/render/pattern.rs | 2 +- crates/ide-completion/src/render/variant.rs | 4 ++-- 8 files changed, 13 insertions(+), 13 deletions(-) diff --git a/crates/ide-completion/src/completions/extern_crate.rs b/crates/ide-completion/src/completions/extern_crate.rs index f9cde44667b7..b67d82c20d84 100644 --- a/crates/ide-completion/src/completions/extern_crate.rs +++ b/crates/ide-completion/src/completions/extern_crate.rs @@ -46,7 +46,7 @@ mod other_mod {} let completion_list = completion_list_no_kw(case); - assert_eq!("md other_crate_a\n".to_string(), completion_list); + assert_eq!("md other_crate_a\n".to_owned(), completion_list); } #[test] @@ -66,6 +66,6 @@ mod other_mod {} let completion_list = completion_list_no_kw(case); - assert_eq!("md other_crate_a\n".to_string(), completion_list); + assert_eq!("md other_crate_a\n".to_owned(), completion_list); } } diff --git a/crates/ide-completion/src/completions/postfix.rs b/crates/ide-completion/src/completions/postfix.rs index d34d2e7e98ec..72c0885e92fa 100644 --- a/crates/ide-completion/src/completions/postfix.rs +++ b/crates/ide-completion/src/completions/postfix.rs @@ -326,7 +326,7 @@ fn build_postfix_snippet_builder<'ctx>( delete_range: TextRange, ) -> impl Fn(&str, &str, &str) -> Builder + 'ctx { move |label, detail, snippet| { - let edit = TextEdit::replace(delete_range, snippet.to_string()); + let edit = TextEdit::replace(delete_range, snippet.to_owned()); let mut item = CompletionItem::new(CompletionItemKind::Snippet, ctx.source_range(), label); item.detail(detail).snippet_edit(cap, edit); diff --git a/crates/ide-completion/src/context.rs b/crates/ide-completion/src/context.rs index e07937787cf8..2a0004f60b82 100644 --- a/crates/ide-completion/src/context.rs +++ b/crates/ide-completion/src/context.rs @@ -665,7 +665,7 @@ impl<'a> CompletionContext<'a> { // actual completion. let file_with_fake_ident = { let parse = db.parse(file_id); - let edit = Indel::insert(offset, COMPLETION_MARKER.to_string()); + let edit = Indel::insert(offset, COMPLETION_MARKER.to_owned()); parse.reparse(&edit).tree() }; diff --git a/crates/ide-completion/src/item.rs b/crates/ide-completion/src/item.rs index bcf169f46530..8552a20392ab 100644 --- a/crates/ide-completion/src/item.rs +++ b/crates/ide-completion/src/item.rs @@ -553,7 +553,7 @@ impl Builder { self.detail = detail.map(Into::into); if let Some(detail) = &self.detail { if never!(detail.contains('\n'), "multiline detail:\n{}", detail) { - self.detail = Some(detail.split('\n').next().unwrap().to_string()); + self.detail = Some(detail.split('\n').next().unwrap().to_owned()); } } self diff --git a/crates/ide-completion/src/render.rs b/crates/ide-completion/src/render.rs index 5172829266e3..548466d8de4c 100644 --- a/crates/ide-completion/src/render.rs +++ b/crates/ide-completion/src/render.rs @@ -167,14 +167,14 @@ pub(crate) fn render_field( if !expected_fn_type { if let Some(receiver) = &dot_access.receiver { if let Some(receiver) = ctx.completion.sema.original_ast_node(receiver.clone()) { - builder.insert(receiver.syntax().text_range().start(), "(".to_string()); - builder.insert(ctx.source_range().end(), ")".to_string()); + builder.insert(receiver.syntax().text_range().start(), "(".to_owned()); + builder.insert(ctx.source_range().end(), ")".to_owned()); let is_parens_needed = !matches!(dot_access.kind, DotAccessKind::Method { has_parens: true }); if is_parens_needed { - builder.insert(ctx.source_range().end(), "()".to_string()); + builder.insert(ctx.source_range().end(), "()".to_owned()); } } } diff --git a/crates/ide-completion/src/render/function.rs b/crates/ide-completion/src/render/function.rs index 4ae7ea861c75..f3ac06c13164 100644 --- a/crates/ide-completion/src/render/function.rs +++ b/crates/ide-completion/src/render/function.rs @@ -184,12 +184,12 @@ pub(super) fn add_call_parens<'b>( } None => { let name = match param.ty().as_adt() { - None => "_".to_string(), + None => "_".to_owned(), Some(adt) => adt .name(ctx.db) .as_text() .map(|s| to_lower_snake_case(s.as_str())) - .unwrap_or_else(|| "_".to_string()), + .unwrap_or_else(|| "_".to_owned()), }; f(&format_args!("${{{}:{name}}}", index + offset)) } diff --git a/crates/ide-completion/src/render/pattern.rs b/crates/ide-completion/src/render/pattern.rs index a5f851566cb0..c07966f7a7a8 100644 --- a/crates/ide-completion/src/render/pattern.rs +++ b/crates/ide-completion/src/render/pattern.rs @@ -140,7 +140,7 @@ fn render_pat( StructKind::Record => { render_record_as_pat(ctx.db(), ctx.snippet_cap(), fields, name, fields_omitted) } - StructKind::Unit => name.to_string(), + StructKind::Unit => name.to_owned(), }; let needs_ascription = matches!( diff --git a/crates/ide-completion/src/render/variant.rs b/crates/ide-completion/src/render/variant.rs index a9a01a3a30f5..28238de45594 100644 --- a/crates/ide-completion/src/render/variant.rs +++ b/crates/ide-completion/src/render/variant.rs @@ -23,7 +23,7 @@ pub(crate) fn render_record_lit( path: &str, ) -> RenderedLiteral { if snippet_cap.is_none() { - return RenderedLiteral { literal: path.to_string(), detail: path.to_string() }; + return RenderedLiteral { literal: path.to_owned(), detail: path.to_owned() }; } let completions = fields.iter().enumerate().format_with(", ", |(idx, field), f| { if snippet_cap.is_some() { @@ -52,7 +52,7 @@ pub(crate) fn render_tuple_lit( path: &str, ) -> RenderedLiteral { if snippet_cap.is_none() { - return RenderedLiteral { literal: path.to_string(), detail: path.to_string() }; + return RenderedLiteral { literal: path.to_owned(), detail: path.to_owned() }; } let completions = fields.iter().enumerate().format_with(", ", |(idx, _), f| { if snippet_cap.is_some() { From fb8c0f514e066567a6f5800150b9a2910ce851fd Mon Sep 17 00:00:00 2001 From: Tetsuharu Ohzeki Date: Sat, 10 Feb 2024 00:48:15 +0900 Subject: [PATCH 13/28] ide-db: Fix warnings about clippy `str_to_string` rule --- crates/ide-db/src/syntax_helpers/format_string_exprs.rs | 2 +- crates/ide-db/src/tests/sourcegen_lints.rs | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/ide-db/src/syntax_helpers/format_string_exprs.rs b/crates/ide-db/src/syntax_helpers/format_string_exprs.rs index fc230818193d..49594aee9f35 100644 --- a/crates/ide-db/src/syntax_helpers/format_string_exprs.rs +++ b/crates/ide-db/src/syntax_helpers/format_string_exprs.rs @@ -203,7 +203,7 @@ mod tests { use expect_test::{expect, Expect}; fn check(input: &str, expect: &Expect) { - let (output, exprs) = parse_format_exprs(input).unwrap_or(("-".to_string(), vec![])); + let (output, exprs) = parse_format_exprs(input).unwrap_or(("-".to_owned(), vec![])); let outcome_repr = if !exprs.is_empty() { format!("{output}; {}", with_placeholders(exprs).join(", ")) } else { diff --git a/crates/ide-db/src/tests/sourcegen_lints.rs b/crates/ide-db/src/tests/sourcegen_lints.rs index a165470b57f5..86ed01c8e748 100644 --- a/crates/ide-db/src/tests/sourcegen_lints.rs +++ b/crates/ide-db/src/tests/sourcegen_lints.rs @@ -52,7 +52,7 @@ pub struct LintGroup { generate_lint_descriptor(sh, &mut contents); contents.push('\n'); - let cargo = std::env::var("CARGO").unwrap_or_else(|_| "cargo".to_string()); + let cargo = std::env::var("CARGO").unwrap_or_else(|_| "cargo".to_owned()); let unstable_book = project_root().join("./target/unstable-book-gen"); cmd!( sh, @@ -283,7 +283,7 @@ fn generate_descriptor_clippy(buf: &mut String, path: &Path) { let line = &line[..up_to]; let clippy_lint = clippy_lints.last_mut().expect("clippy lint must already exist"); - clippy_lint.help = unescape(line).trim().to_string(); + clippy_lint.help = unescape(line).trim().to_owned(); } } clippy_lints.sort_by(|lint, lint2| lint.id.cmp(&lint2.id)); From ae78dcae75694f44bc46c508086fb9d025ece858 Mon Sep 17 00:00:00 2001 From: Tetsuharu Ohzeki Date: Sat, 10 Feb 2024 00:49:00 +0900 Subject: [PATCH 14/28] ide-ssr: Fix warnings about clippy `str_to_string` rule --- crates/ide-ssr/src/matching.rs | 4 ++-- crates/ide-ssr/src/parsing.rs | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/ide-ssr/src/matching.rs b/crates/ide-ssr/src/matching.rs index 81f00d51a340..fb98e9568474 100644 --- a/crates/ide-ssr/src/matching.rs +++ b/crates/ide-ssr/src/matching.rs @@ -456,7 +456,7 @@ impl<'db, 'sema> Matcher<'db, 'sema> { SyntaxElement::Token(t) => Some(t.clone()), SyntaxElement::Node(n) => n.first_token(), }) - .map(|p| p.text().to_string()); + .map(|p| p.text().to_owned()); let first_matched_token = child.clone(); let mut last_matched_token = child; // Read code tokens util we reach one equal to the next token from our pattern @@ -795,7 +795,7 @@ mod tests { let edits = match_finder.edits(); assert_eq!(edits.len(), 1); let edit = &edits[&position.file_id]; - let mut after = input.to_string(); + let mut after = input.to_owned(); edit.apply(&mut after); assert_eq!(after, "fn foo() {} fn bar() {} fn main() { bar(1+2); }"); } diff --git a/crates/ide-ssr/src/parsing.rs b/crates/ide-ssr/src/parsing.rs index d78d009681a6..2f91271c4653 100644 --- a/crates/ide-ssr/src/parsing.rs +++ b/crates/ide-ssr/src/parsing.rs @@ -152,7 +152,7 @@ impl FromStr for SsrRule { .next() .ok_or_else(|| SsrError("Cannot find delimiter `==>>`".into()))? .trim() - .to_string(); + .to_owned(); if it.next().is_some() { return Err(SsrError("More than one delimiter found".into())); } From 80713250c5dc068e2e6d070366eadc7bb1882638 Mon Sep 17 00:00:00 2001 From: Tetsuharu Ohzeki Date: Sat, 10 Feb 2024 00:49:45 +0900 Subject: [PATCH 15/28] load-cargo: Fix warnings about clippy `str_to_string` rule --- crates/load-cargo/src/lib.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/load-cargo/src/lib.rs b/crates/load-cargo/src/lib.rs index 3878e20a2a63..c6dc071c394e 100644 --- a/crates/load-cargo/src/lib.rs +++ b/crates/load-cargo/src/lib.rs @@ -279,7 +279,7 @@ pub fn load_proc_macro( let dylib = MacroDylib::new(path.to_path_buf()); let vec = server.load_dylib(dylib).map_err(|e| format!("{e}"))?; if vec.is_empty() { - return Err("proc macro library returned no proc macros".to_string()); + return Err("proc macro library returned no proc macros".to_owned()); } Ok(vec .into_iter() @@ -382,7 +382,7 @@ impl ProcMacroExpander for Expander { call_site: Span, mixed_site: Span, ) -> Result, ProcMacroExpansionError> { - let env = env.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect(); + let env = env.iter().map(|(k, v)| (k.to_owned(), v.to_owned())).collect(); match self.0.expand(subtree, attrs, env, def_site, call_site, mixed_site) { Ok(Ok(subtree)) => Ok(subtree), Ok(Err(err)) => Err(ProcMacroExpansionError::Panic(err.0)), From edda6b8a1fe0607bc2b27be833958c179cc1fb3f Mon Sep 17 00:00:00 2001 From: Tetsuharu Ohzeki Date: Sat, 10 Feb 2024 00:50:09 +0900 Subject: [PATCH 16/28] mbe: Fix warnings about clippy `str_to_string` rule --- crates/mbe/src/syntax_bridge.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/mbe/src/syntax_bridge.rs b/crates/mbe/src/syntax_bridge.rs index b1c83cf422c9..bfc5d197f683 100644 --- a/crates/mbe/src/syntax_bridge.rs +++ b/crates/mbe/src/syntax_bridge.rs @@ -146,7 +146,7 @@ where } parser::Step::Enter { kind } => tree_sink.start_node(kind), parser::Step::Exit => tree_sink.finish_node(), - parser::Step::Error { msg } => tree_sink.error(msg.to_string()), + parser::Step::Error { msg } => tree_sink.error(msg.to_owned()), } } tree_sink.finish() From f474bd77be417f2de3f0679e2847d0190b1d27c6 Mon Sep 17 00:00:00 2001 From: Tetsuharu Ohzeki Date: Sat, 10 Feb 2024 00:50:44 +0900 Subject: [PATCH 17/28] parser: Fix warnings about clippy `str_to_string` rule --- crates/parser/src/lexed_str.rs | 2 +- crates/parser/src/tests/sourcegen_inline_tests.rs | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/parser/src/lexed_str.rs b/crates/parser/src/lexed_str.rs index bf1feb9a7eb0..2da9184693d9 100644 --- a/crates/parser/src/lexed_str.rs +++ b/crates/parser/src/lexed_str.rs @@ -149,7 +149,7 @@ impl<'a> Converter<'a> { if let Some(err) = err { let token = self.res.len() as u32; - let msg = err.to_string(); + let msg = err.to_owned(); self.res.error.push(LexError { msg, token }); } } diff --git a/crates/parser/src/tests/sourcegen_inline_tests.rs b/crates/parser/src/tests/sourcegen_inline_tests.rs index c02fb02c9dad..5a71bfd82b1a 100644 --- a/crates/parser/src/tests/sourcegen_inline_tests.rs +++ b/crates/parser/src/tests/sourcegen_inline_tests.rs @@ -60,9 +60,9 @@ fn collect_tests(s: &str) -> Vec { for comment_block in sourcegen::CommentBlock::extract_untagged(s) { let first_line = &comment_block.contents[0]; let (name, ok) = if let Some(name) = first_line.strip_prefix("test ") { - (name.to_string(), true) + (name.to_owned(), true) } else if let Some(name) = first_line.strip_prefix("test_err ") { - (name.to_string(), false) + (name.to_owned(), false) } else { continue; }; From 81c35d1f5633ba2fd10d242f4539e5d731279a8d Mon Sep 17 00:00:00 2001 From: Tetsuharu Ohzeki Date: Sat, 10 Feb 2024 00:51:58 +0900 Subject: [PATCH 18/28] syntax: Fix warnings about clippy `str_to_string` rule --- crates/syntax/src/ast/make.rs | 16 ++++++++-------- crates/syntax/src/fuzz.rs | 2 +- crates/syntax/src/lib.rs | 2 +- crates/syntax/src/parsing.rs | 2 +- crates/syntax/src/parsing/reparsing.rs | 2 +- crates/syntax/src/tests/sourcegen_ast.rs | 4 ++-- 6 files changed, 14 insertions(+), 14 deletions(-) diff --git a/crates/syntax/src/ast/make.rs b/crates/syntax/src/ast/make.rs index 9d6ed6736105..120d801c8d17 100644 --- a/crates/syntax/src/ast/make.rs +++ b/crates/syntax/src/ast/make.rs @@ -249,11 +249,11 @@ pub fn impl_( let gen_params = generic_params.map_or_else(String::new, |it| it.to_string()); let body_newline = - if where_clause.is_some() && body.is_none() { "\n".to_string() } else { String::new() }; + if where_clause.is_some() && body.is_none() { "\n".to_owned() } else { String::new() }; let where_clause = match where_clause { Some(pr) => format!("\n{pr}\n"), - None => " ".to_string(), + None => " ".to_owned(), }; let body = match body { @@ -291,13 +291,13 @@ pub fn impl_trait( let body_newline = if (ty_where_clause.is_some() || trait_where_clause.is_some()) && body.is_none() { - "\n".to_string() + "\n".to_owned() } else { String::new() }; let where_clause = merge_where_clause(ty_where_clause, trait_where_clause) - .map_or_else(|| " ".to_string(), |wc| format!("\n{}\n", wc)); + .map_or_else(|| " ".to_owned(), |wc| format!("\n{}\n", wc)); let body = match body { Some(bd) => bd.iter().map(|elem| elem.to_string()).join(""), @@ -378,7 +378,7 @@ pub fn use_tree( alias: Option, add_star: bool, ) -> ast::UseTree { - let mut buf = "use ".to_string(); + let mut buf = "use ".to_owned(); buf += &path.syntax().to_string(); if let Some(use_tree_list) = use_tree_list { format_to!(buf, "::{use_tree_list}"); @@ -444,7 +444,7 @@ pub fn block_expr( stmts: impl IntoIterator, tail_expr: Option, ) -> ast::BlockExpr { - let mut buf = "{\n".to_string(); + let mut buf = "{\n".to_owned(); for stmt in stmts.into_iter() { format_to!(buf, " {stmt}\n"); } @@ -459,7 +459,7 @@ pub fn async_move_block_expr( stmts: impl IntoIterator, tail_expr: Option, ) -> ast::BlockExpr { - let mut buf = "async move {\n".to_string(); + let mut buf = "async move {\n".to_owned(); for stmt in stmts.into_iter() { format_to!(buf, " {stmt}\n"); } @@ -482,7 +482,7 @@ pub fn hacky_block_expr( elements: impl IntoIterator, tail_expr: Option, ) -> ast::BlockExpr { - let mut buf = "{\n".to_string(); + let mut buf = "{\n".to_owned(); for node_or_token in elements.into_iter() { match node_or_token { rowan::NodeOrToken::Node(n) => format_to!(buf, " {n}\n"), diff --git a/crates/syntax/src/fuzz.rs b/crates/syntax/src/fuzz.rs index 15e68fc575db..28738671790c 100644 --- a/crates/syntax/src/fuzz.rs +++ b/crates/syntax/src/fuzz.rs @@ -34,7 +34,7 @@ impl CheckReparse { let mut lines = data.lines(); let delete_start = usize::from_str(lines.next()?).ok()? + PREFIX.len(); let delete_len = usize::from_str(lines.next()?).ok()?; - let insert = lines.next()?.to_string(); + let insert = lines.next()?.to_owned(); let text = lines.collect::>().join("\n"); let text = format!("{PREFIX}{text}{SUFFIX}"); text.get(delete_start..delete_start.checked_add(delete_len)?)?; // make sure delete is a valid range diff --git a/crates/syntax/src/lib.rs b/crates/syntax/src/lib.rs index 62a0261d7a45..960889b74211 100644 --- a/crates/syntax/src/lib.rs +++ b/crates/syntax/src/lib.rs @@ -432,7 +432,7 @@ fn api_walkthrough() { WalkEvent::Enter(node) => { let text = match &node { NodeOrToken::Node(it) => it.text().to_string(), - NodeOrToken::Token(it) => it.text().to_string(), + NodeOrToken::Token(it) => it.text().to_owned(), }; format_to!(buf, "{:indent$}{:?} {:?}\n", " ", text, node.kind(), indent = indent); indent += 2; diff --git a/crates/syntax/src/parsing.rs b/crates/syntax/src/parsing.rs index 047e670c9f45..1250b5274c18 100644 --- a/crates/syntax/src/parsing.rs +++ b/crates/syntax/src/parsing.rs @@ -28,7 +28,7 @@ pub(crate) fn build_tree( parser::StrStep::Enter { kind } => builder.start_node(kind), parser::StrStep::Exit => builder.finish_node(), parser::StrStep::Error { msg, pos } => { - builder.error(msg.to_string(), pos.try_into().unwrap()) + builder.error(msg.to_owned(), pos.try_into().unwrap()) } }); diff --git a/crates/syntax/src/parsing/reparsing.rs b/crates/syntax/src/parsing/reparsing.rs index 0ddc641711fb..14715b572534 100644 --- a/crates/syntax/src/parsing/reparsing.rs +++ b/crates/syntax/src/parsing/reparsing.rs @@ -105,7 +105,7 @@ fn get_text_after_edit(element: SyntaxElement, edit: &Indel) -> String { let edit = Indel::replace(edit.delete - element.text_range().start(), edit.insert.clone()); let mut text = match element { - NodeOrToken::Token(token) => token.text().to_string(), + NodeOrToken::Token(token) => token.text().to_owned(), NodeOrToken::Node(node) => node.text().to_string(), }; edit.apply(&mut text); diff --git a/crates/syntax/src/tests/sourcegen_ast.rs b/crates/syntax/src/tests/sourcegen_ast.rs index ccb13a0d933c..2fd7a4734989 100644 --- a/crates/syntax/src/tests/sourcegen_ast.rs +++ b/crates/syntax/src/tests/sourcegen_ast.rs @@ -573,7 +573,7 @@ fn lower(grammar: &Grammar) -> AstSrc { tokens: "Whitespace Comment String ByteString CString IntNumber FloatNumber Char Byte Ident" .split_ascii_whitespace() - .map(|it| it.to_string()) + .map(|it| it.to_owned()) .collect::>(), ..Default::default() }; @@ -816,7 +816,7 @@ fn extract_struct_trait(node: &mut AstNodeSrc, trait_name: &str, methods: &[&str } } if to_remove.len() == methods.len() { - node.traits.push(trait_name.to_string()); + node.traits.push(trait_name.to_owned()); node.remove_field(to_remove); } } From cee3c22ae8081b05f480146c9dfb0a72348d623c Mon Sep 17 00:00:00 2001 From: Tetsuharu Ohzeki Date: Sat, 10 Feb 2024 00:52:46 +0900 Subject: [PATCH 19/28] vfs: Fix warnings about clippy `str_to_string` rule --- crates/vfs/src/loader.rs | 2 +- crates/vfs/src/vfs_path/tests.rs | 14 +++++++------- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/crates/vfs/src/loader.rs b/crates/vfs/src/loader.rs index e49849d23077..c3d1ff7271a9 100644 --- a/crates/vfs/src/loader.rs +++ b/crates/vfs/src/loader.rs @@ -201,7 +201,7 @@ impl Directories { /// ``` fn dirs(base: AbsPathBuf, exclude: &[&str]) -> Directories { let exclude = exclude.iter().map(|it| base.join(it)).collect::>(); - Directories { extensions: vec!["rs".to_string()], include: vec![base], exclude } + Directories { extensions: vec!["rs".to_owned()], include: vec![base], exclude } } impl fmt::Debug for Message { diff --git a/crates/vfs/src/vfs_path/tests.rs b/crates/vfs/src/vfs_path/tests.rs index 510e021e8903..2d89362ee069 100644 --- a/crates/vfs/src/vfs_path/tests.rs +++ b/crates/vfs/src/vfs_path/tests.rs @@ -2,29 +2,29 @@ use super::*; #[test] fn virtual_path_extensions() { - assert_eq!(VirtualPath("/".to_string()).name_and_extension(), None); + assert_eq!(VirtualPath("/".to_owned()).name_and_extension(), None); assert_eq!( - VirtualPath("/directory".to_string()).name_and_extension(), + VirtualPath("/directory".to_owned()).name_and_extension(), Some(("directory", None)) ); assert_eq!( - VirtualPath("/directory/".to_string()).name_and_extension(), + VirtualPath("/directory/".to_owned()).name_and_extension(), Some(("directory", None)) ); assert_eq!( - VirtualPath("/directory/file".to_string()).name_and_extension(), + VirtualPath("/directory/file".to_owned()).name_and_extension(), Some(("file", None)) ); assert_eq!( - VirtualPath("/directory/.file".to_string()).name_and_extension(), + VirtualPath("/directory/.file".to_owned()).name_and_extension(), Some((".file", None)) ); assert_eq!( - VirtualPath("/directory/.file.rs".to_string()).name_and_extension(), + VirtualPath("/directory/.file.rs".to_owned()).name_and_extension(), Some((".file", Some("rs"))) ); assert_eq!( - VirtualPath("/directory/file.rs".to_string()).name_and_extension(), + VirtualPath("/directory/file.rs".to_owned()).name_and_extension(), Some(("file", Some("rs"))) ); } From 283b140321757fee60a87ef96724d8c5cb66bdff Mon Sep 17 00:00:00 2001 From: Tetsuharu Ohzeki Date: Sat, 10 Feb 2024 00:55:15 +0900 Subject: [PATCH 20/28] salsa: Fix warnings about clippy `str_to_string` rule --- crates/salsa/tests/interned.rs | 36 +++++++++++++++++----------------- 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/crates/salsa/tests/interned.rs b/crates/salsa/tests/interned.rs index b9b916d19af3..d097e41cfd63 100644 --- a/crates/salsa/tests/interned.rs +++ b/crates/salsa/tests/interned.rs @@ -44,47 +44,47 @@ impl salsa::InternKey for InternKey { #[test] fn test_intern1() { let db = Database::default(); - let foo0 = db.intern1("foo".to_string()); - let bar0 = db.intern1("bar".to_string()); - let foo1 = db.intern1("foo".to_string()); - let bar1 = db.intern1("bar".to_string()); + let foo0 = db.intern1("foo".to_owned()); + let bar0 = db.intern1("bar".to_owned()); + let foo1 = db.intern1("foo".to_owned()); + let bar1 = db.intern1("bar".to_owned()); assert_eq!(foo0, foo1); assert_eq!(bar0, bar1); assert_ne!(foo0, bar0); - assert_eq!("foo".to_string(), db.lookup_intern1(foo0)); - assert_eq!("bar".to_string(), db.lookup_intern1(bar0)); + assert_eq!("foo".to_owned(), db.lookup_intern1(foo0)); + assert_eq!("bar".to_owned(), db.lookup_intern1(bar0)); } #[test] fn test_intern2() { let db = Database::default(); - let foo0 = db.intern2("x".to_string(), "foo".to_string()); - let bar0 = db.intern2("x".to_string(), "bar".to_string()); - let foo1 = db.intern2("x".to_string(), "foo".to_string()); - let bar1 = db.intern2("x".to_string(), "bar".to_string()); + let foo0 = db.intern2("x".to_owned(), "foo".to_owned()); + let bar0 = db.intern2("x".to_owned(), "bar".to_owned()); + let foo1 = db.intern2("x".to_owned(), "foo".to_owned()); + let bar1 = db.intern2("x".to_owned(), "bar".to_owned()); assert_eq!(foo0, foo1); assert_eq!(bar0, bar1); assert_ne!(foo0, bar0); - assert_eq!(("x".to_string(), "foo".to_string()), db.lookup_intern2(foo0)); - assert_eq!(("x".to_string(), "bar".to_string()), db.lookup_intern2(bar0)); + assert_eq!(("x".to_owned(), "foo".to_owned()), db.lookup_intern2(foo0)); + assert_eq!(("x".to_owned(), "bar".to_owned()), db.lookup_intern2(bar0)); } #[test] fn test_intern_key() { let db = Database::default(); - let foo0 = db.intern_key("foo".to_string()); - let bar0 = db.intern_key("bar".to_string()); - let foo1 = db.intern_key("foo".to_string()); - let bar1 = db.intern_key("bar".to_string()); + let foo0 = db.intern_key("foo".to_owned()); + let bar0 = db.intern_key("bar".to_owned()); + let foo1 = db.intern_key("foo".to_owned()); + let bar1 = db.intern_key("bar".to_owned()); assert_eq!(foo0, foo1); assert_eq!(bar0, bar1); assert_ne!(foo0, bar0); - assert_eq!("foo".to_string(), db.lookup_intern_key(foo0)); - assert_eq!("bar".to_string(), db.lookup_intern_key(bar0)); + assert_eq!("foo".to_owned(), db.lookup_intern_key(foo0)); + assert_eq!("bar".to_owned(), db.lookup_intern_key(bar0)); } From 06f3995ca9c6e205bbcbe68a7d5f1e99101a735a Mon Sep 17 00:00:00 2001 From: Tetsuharu Ohzeki Date: Sat, 10 Feb 2024 00:56:07 +0900 Subject: [PATCH 21/28] xtask: Fix warnings about clippy `str_to_string` rule --- xtask/src/dist.rs | 8 ++++---- xtask/src/flags.rs | 2 +- xtask/src/install.rs | 2 +- xtask/src/metrics.rs | 6 +++--- xtask/src/release/changelog.rs | 2 +- 5 files changed, 10 insertions(+), 10 deletions(-) diff --git a/xtask/src/dist.rs b/xtask/src/dist.rs index 5a03c71b28a9..7e54d19fe4da 100644 --- a/xtask/src/dist.rs +++ b/xtask/src/dist.rs @@ -34,7 +34,7 @@ impl flags::Dist { format!("{VERSION_NIGHTLY}.{patch_version}") }; dist_server(sh, &format!("{version}-standalone"), &target)?; - let release_tag = if stable { date_iso(sh)? } else { "nightly".to_string() }; + let release_tag = if stable { date_iso(sh)? } else { "nightly".to_owned() }; dist_client(sh, &version, &release_tag, &target)?; } else { dist_server(sh, "0.0.0-standalone", &target)?; @@ -155,11 +155,11 @@ impl Target { Ok(target) => target, _ => { if cfg!(target_os = "linux") { - "x86_64-unknown-linux-gnu".to_string() + "x86_64-unknown-linux-gnu".to_owned() } else if cfg!(target_os = "windows") { - "x86_64-pc-windows-msvc".to_string() + "x86_64-pc-windows-msvc".to_owned() } else if cfg!(target_os = "macos") { - "x86_64-apple-darwin".to_string() + "x86_64-apple-darwin".to_owned() } else { panic!("Unsupported OS, maybe try setting RA_TARGET") } diff --git a/xtask/src/flags.rs b/xtask/src/flags.rs index 092ab8c593ce..99bb12896f10 100644 --- a/xtask/src/flags.rs +++ b/xtask/src/flags.rs @@ -129,7 +129,7 @@ impl FromStr for MeasurementType { "webrender-2022" => Ok(Self::AnalyzeWebRender), "diesel-1.4.8" => Ok(Self::AnalyzeDiesel), "hyper-0.14.18" => Ok(Self::AnalyzeHyper), - _ => Err("Invalid option".to_string()), + _ => Err("Invalid option".to_owned()), } } } diff --git a/xtask/src/install.rs b/xtask/src/install.rs index e8c00c72e070..dadee204d1ac 100644 --- a/xtask/src/install.rs +++ b/xtask/src/install.rs @@ -50,7 +50,7 @@ fn fix_path_for_mac(sh: &Shell) -> anyhow::Result<()> { [ROOT_DIR, &home_dir] .into_iter() - .map(|dir| dir.to_string() + COMMON_APP_PATH) + .map(|dir| dir.to_owned() + COMMON_APP_PATH) .map(PathBuf::from) .filter(|path| path.exists()) .collect() diff --git a/xtask/src/metrics.rs b/xtask/src/metrics.rs index c05874a0ccac..9bd3a661c24d 100644 --- a/xtask/src/metrics.rs +++ b/xtask/src/metrics.rs @@ -194,12 +194,12 @@ impl Host { bail!("can only collect metrics on Linux "); } - let os = read_field(sh, "/etc/os-release", "PRETTY_NAME=")?.trim_matches('"').to_string(); + let os = read_field(sh, "/etc/os-release", "PRETTY_NAME=")?.trim_matches('"').to_owned(); let cpu = read_field(sh, "/proc/cpuinfo", "model name")? .trim_start_matches(':') .trim() - .to_string(); + .to_owned(); let mem = read_field(sh, "/proc/meminfo", "MemTotal:")?; @@ -210,7 +210,7 @@ impl Host { text.lines() .find_map(|it| it.strip_prefix(field)) - .map(|it| it.trim().to_string()) + .map(|it| it.trim().to_owned()) .ok_or_else(|| format_err!("can't parse {}", path)) } } diff --git a/xtask/src/release/changelog.rs b/xtask/src/release/changelog.rs index 817863336dd4..086a4d463ea1 100644 --- a/xtask/src/release/changelog.rs +++ b/xtask/src/release/changelog.rs @@ -183,5 +183,5 @@ fn parse_title_line(s: &str) -> PrInfo { return PrInfo { message, kind }; } } - PrInfo { kind: PrKind::Other, message: Some(s.to_string()) } + PrInfo { kind: PrKind::Other, message: Some(s.to_owned()) } } From 0a879f7da48e9e6f8858f8638699f17d4b207a5a Mon Sep 17 00:00:00 2001 From: Tetsuharu Ohzeki Date: Sat, 10 Feb 2024 00:56:33 +0900 Subject: [PATCH 22/28] sourcegen: Fix warnings about clippy `str_to_string` rule --- crates/sourcegen/src/lib.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/sourcegen/src/lib.rs b/crates/sourcegen/src/lib.rs index ac3aa31b57a2..295b716b4e90 100644 --- a/crates/sourcegen/src/lib.rs +++ b/crates/sourcegen/src/lib.rs @@ -69,7 +69,7 @@ impl CommentBlock { panic!("Use plain (non-doc) comments with tags like {tag}:\n {first}"); } - block.id = id.trim().to_string(); + block.id = id.trim().to_owned(); true }); blocks @@ -93,7 +93,7 @@ impl CommentBlock { if let Some(' ') = contents.chars().next() { contents = &contents[1..]; } - block.contents.push(contents.to_string()); + block.contents.push(contents.to_owned()); } None => { if !block.contents.is_empty() { From c3699b9f3236b5f24d770fa8c9f129051f4fa84d Mon Sep 17 00:00:00 2001 From: Tetsuharu Ohzeki Date: Sat, 10 Feb 2024 00:58:06 +0900 Subject: [PATCH 23/28] test-utils: Fix warnings about clippy `str_to_string` rule --- crates/test-utils/src/bench_fixture.rs | 2 +- crates/test-utils/src/fixture.rs | 34 +++++++++++++------------- crates/test-utils/src/lib.rs | 4 +-- 3 files changed, 20 insertions(+), 20 deletions(-) diff --git a/crates/test-utils/src/bench_fixture.rs b/crates/test-utils/src/bench_fixture.rs index 9296fd2e6835..d83f95768628 100644 --- a/crates/test-utils/src/bench_fixture.rs +++ b/crates/test-utils/src/bench_fixture.rs @@ -12,7 +12,7 @@ pub fn big_struct() -> String { } pub fn big_struct_n(n: u32) -> String { - let mut buf = "pub struct RegisterBlock {".to_string(); + let mut buf = "pub struct RegisterBlock {".to_owned(); for i in 0..n { format_to!(buf, " /// Doc comment for {}.\n", i); format_to!(buf, " pub s{}: S{},\n", i, i); diff --git a/crates/test-utils/src/fixture.rs b/crates/test-utils/src/fixture.rs index 3f8b5a089690..595281336d58 100644 --- a/crates/test-utils/src/fixture.rs +++ b/crates/test-utils/src/fixture.rs @@ -178,13 +178,13 @@ impl FixtureWithProjectMeta { if let Some(meta) = fixture.strip_prefix("//- toolchain:") { let (meta, remain) = meta.split_once('\n').unwrap(); - toolchain = Some(meta.trim().to_string()); + toolchain = Some(meta.trim().to_owned()); fixture = remain; } if let Some(meta) = fixture.strip_prefix("//- proc_macros:") { let (meta, remain) = meta.split_once('\n').unwrap(); - proc_macro_names = meta.split(',').map(|it| it.trim().to_string()).collect(); + proc_macro_names = meta.split(',').map(|it| it.trim().to_owned()).collect(); fixture = remain; } @@ -234,7 +234,7 @@ impl FixtureWithProjectMeta { let meta = meta["//-".len()..].trim(); let mut components = meta.split_ascii_whitespace(); - let path = components.next().expect("fixture meta must start with a path").to_string(); + let path = components.next().expect("fixture meta must start with a path").to_owned(); assert!(path.starts_with('/'), "fixture path does not start with `/`: {path:?}"); let mut krate = None; @@ -246,7 +246,7 @@ impl FixtureWithProjectMeta { let mut introduce_new_source_root = None; let mut library = false; let mut target_data_layout = Some( - "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128".to_string(), + "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128".to_owned(), ); for component in components { if component == "library" { @@ -257,22 +257,22 @@ impl FixtureWithProjectMeta { let (key, value) = component.split_once(':').unwrap_or_else(|| panic!("invalid meta line: {meta:?}")); match key { - "crate" => krate = Some(value.to_string()), - "deps" => deps = value.split(',').map(|it| it.to_string()).collect(), + "crate" => krate = Some(value.to_owned()), + "deps" => deps = value.split(',').map(|it| it.to_owned()).collect(), "extern-prelude" => { if value.is_empty() { extern_prelude = Some(Vec::new()); } else { extern_prelude = - Some(value.split(',').map(|it| it.to_string()).collect::>()); + Some(value.split(',').map(|it| it.to_owned()).collect::>()); } } - "edition" => edition = Some(value.to_string()), + "edition" => edition = Some(value.to_owned()), "cfg" => { for entry in value.split(',') { match entry.split_once('=') { - Some((k, v)) => cfgs.push((k.to_string(), Some(v.to_string()))), - None => cfgs.push((entry.to_string(), None)), + Some((k, v)) => cfgs.push((k.to_owned(), Some(v.to_owned()))), + None => cfgs.push((entry.to_owned(), None)), } } } @@ -283,8 +283,8 @@ impl FixtureWithProjectMeta { } } } - "new_source_root" => introduce_new_source_root = Some(value.to_string()), - "target_data_layout" => target_data_layout = Some(value.to_string()), + "new_source_root" => introduce_new_source_root = Some(value.to_owned()), + "target_data_layout" => target_data_layout = Some(value.to_owned()), _ => panic!("bad component: {component:?}"), } } @@ -381,7 +381,7 @@ impl MiniCore { let (flag, deps) = line.split_once(':').unwrap(); let flag = flag.trim(); - self.valid_flags.push(flag.to_string()); + self.valid_flags.push(flag.to_owned()); implications.extend( iter::repeat(flag) .zip(deps.split(", ").map(str::trim).filter(|dep| !dep.is_empty())), @@ -401,7 +401,7 @@ impl MiniCore { let mut changed = false; for &(u, v) in &implications { if self.has_flag(u) && !self.has_flag(v) { - self.activated_flags.push(v.to_string()); + self.activated_flags.push(v.to_owned()); changed = true; } } @@ -486,9 +486,9 @@ fn parse_fixture_gets_full_meta() { mod m; "#, ); - assert_eq!(toolchain, Some("nightly".to_string())); - assert_eq!(proc_macro_names, vec!["identity".to_string()]); - assert_eq!(mini_core.unwrap().activated_flags, vec!["coerce_unsized".to_string()]); + assert_eq!(toolchain, Some("nightly".to_owned())); + assert_eq!(proc_macro_names, vec!["identity".to_owned()]); + assert_eq!(mini_core.unwrap().activated_flags, vec!["coerce_unsized".to_owned()]); assert_eq!(1, parsed.len()); let meta = &parsed[0]; diff --git a/crates/test-utils/src/lib.rs b/crates/test-utils/src/lib.rs index 854b613ddf76..b750107803a9 100644 --- a/crates/test-utils/src/lib.rs +++ b/crates/test-utils/src/lib.rs @@ -164,7 +164,7 @@ pub fn extract_tags(mut text: &str, tag: &str) -> (Vec<(TextRange, Option').unwrap(); let attr = text[open.len()..close_open].trim(); - let attr = if attr.is_empty() { None } else { Some(attr.to_string()) }; + let attr = if attr.is_empty() { None } else { Some(attr.to_owned()) }; text = &text[close_open + '>'.len_utf8()..]; let from = TextSize::of(&res); stack.push((from, attr)); @@ -326,7 +326,7 @@ fn extract_line_annotations(mut line: &str) -> Vec { content = &content["file".len()..]; } - let content = content.trim_start().to_string(); + let content = content.trim_start().to_owned(); let annotation = if continuation { LineAnnotation::Continuation { offset: range.end(), content } From bffb8880d5b8fd80396fae8a7dc9b69d5d1c01a6 Mon Sep 17 00:00:00 2001 From: Tetsuharu Ohzeki Date: Sat, 10 Feb 2024 00:58:48 +0900 Subject: [PATCH 24/28] lsp-server: Fix warnings about clippy `str_to_string` rule --- lib/lsp-server/src/lib.rs | 10 +++++----- lib/lsp-server/src/msg.rs | 2 +- lib/lsp-server/src/req_queue.rs | 2 +- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/lib/lsp-server/src/lib.rs b/lib/lsp-server/src/lib.rs index e40fc878a770..5dc052b58755 100644 --- a/lib/lsp-server/src/lib.rs +++ b/lib/lsp-server/src/lib.rs @@ -360,12 +360,12 @@ impl Connection { } Err(RecvTimeoutError::Timeout) => { return Err(ProtocolError::new( - "timed out waiting for exit notification".to_string(), + "timed out waiting for exit notification".to_owned(), )) } Err(RecvTimeoutError::Disconnected) => { return Err(ProtocolError::new( - "channel disconnected waiting for exit notification".to_string(), + "channel disconnected waiting for exit notification".to_owned(), )) } } @@ -406,7 +406,7 @@ mod tests { #[test] fn not_exit_notification() { let notification = crate::Notification { - method: Initialized::METHOD.to_string(), + method: Initialized::METHOD.to_owned(), params: to_value(InitializedParams {}).unwrap(), }; @@ -414,7 +414,7 @@ mod tests { let req_id = RequestId::from(234); let request = crate::Request { id: req_id.clone(), - method: Initialize::METHOD.to_string(), + method: Initialize::METHOD.to_owned(), params: params_as_value.clone(), }; @@ -427,7 +427,7 @@ mod tests { #[test] fn exit_notification() { let notification = - crate::Notification { method: Exit::METHOD.to_string(), params: to_value(()).unwrap() }; + crate::Notification { method: Exit::METHOD.to_owned(), params: to_value(()).unwrap() }; let notification_msg = Message::from(notification); initialize_start_test(TestCase { diff --git a/lib/lsp-server/src/msg.rs b/lib/lsp-server/src/msg.rs index ba318dd16908..71e5933689ac 100644 --- a/lib/lsp-server/src/msg.rs +++ b/lib/lsp-server/src/msg.rs @@ -269,7 +269,7 @@ fn read_msg_text(inp: &mut dyn BufRead) -> io::Result> { size = Some(header_value.parse::().map_err(invalid_data)?); } } - let size: usize = size.ok_or_else(|| invalid_data("no Content-Length".to_string()))?; + let size: usize = size.ok_or_else(|| invalid_data("no Content-Length".to_owned()))?; let mut buf = buf.into_bytes(); buf.resize(size, 0); inp.read_exact(&mut buf)?; diff --git a/lib/lsp-server/src/req_queue.rs b/lib/lsp-server/src/req_queue.rs index e5f19be20b06..7b47f5388b5e 100644 --- a/lib/lsp-server/src/req_queue.rs +++ b/lib/lsp-server/src/req_queue.rs @@ -40,7 +40,7 @@ impl Incoming { let _data = self.complete(id.clone())?; let error = ResponseError { code: ErrorCode::RequestCanceled as i32, - message: "canceled by client".to_string(), + message: "canceled by client".to_owned(), data: None, }; Some(Response { id, result: None, error: Some(error) }) From 1915d9abb76609ca8373e1d50b7957ead0b96f79 Mon Sep 17 00:00:00 2001 From: Tetsuharu Ohzeki Date: Sat, 10 Feb 2024 00:59:19 +0900 Subject: [PATCH 25/28] tt: Fix warnings about clippy `str_to_string` rule --- crates/tt/src/lib.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/tt/src/lib.rs b/crates/tt/src/lib.rs index b87c7ff4752d..9004bff53a80 100644 --- a/crates/tt/src/lib.rs +++ b/crates/tt/src/lib.rs @@ -336,11 +336,11 @@ impl Subtree { }; match (it, last) { (Leaf::Ident(_), Some(&TokenTree::Leaf(Leaf::Ident(_)))) => { - " ".to_string() + &s + " ".to_owned() + &s } (Leaf::Punct(_), Some(TokenTree::Leaf(Leaf::Punct(punct)))) => { if punct.spacing == Spacing::Alone { - " ".to_string() + &s + " ".to_owned() + &s } else { s } From a897566515a07fade0e1b5457a807bc23be354e0 Mon Sep 17 00:00:00 2001 From: Tetsuharu Ohzeki Date: Sat, 10 Feb 2024 00:59:54 +0900 Subject: [PATCH 26/28] test-fixture: Fix warnings about clippy `str_to_string` rule --- crates/test-fixture/src/lib.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/test-fixture/src/lib.rs b/crates/test-fixture/src/lib.rs index cb8c36b680b7..28e757e81bb2 100644 --- a/crates/test-fixture/src/lib.rs +++ b/crates/test-fixture/src/lib.rs @@ -260,7 +260,7 @@ impl ChangeFixture { file_id = FileId::from_raw(file_id.index() + 1); let mut fs = FileSet::default(); - fs.insert(core_file, VfsPath::new_virtual_path("/sysroot/core/lib.rs".to_string())); + fs.insert(core_file, VfsPath::new_virtual_path("/sysroot/core/lib.rs".to_owned())); roots.push(SourceRoot::new_library(fs)); source_change.change_file(core_file, Some(mini_core.source_code().into())); @@ -270,7 +270,7 @@ impl ChangeFixture { let core_crate = crate_graph.add_crate_root( core_file, Edition::Edition2021, - Some(CrateDisplayName::from_canonical_name("core".to_string())), + Some(CrateDisplayName::from_canonical_name("core".to_owned())), None, Default::default(), Default::default(), @@ -304,7 +304,7 @@ impl ChangeFixture { let mut fs = FileSet::default(); fs.insert( proc_lib_file, - VfsPath::new_virtual_path("/sysroot/proc_macros/lib.rs".to_string()), + VfsPath::new_virtual_path("/sysroot/proc_macros/lib.rs".to_owned()), ); roots.push(SourceRoot::new_library(fs)); @@ -315,7 +315,7 @@ impl ChangeFixture { let proc_macros_crate = crate_graph.add_crate_root( proc_lib_file, Edition::Edition2021, - Some(CrateDisplayName::from_canonical_name("proc_macros".to_string())), + Some(CrateDisplayName::from_canonical_name("proc_macros".to_owned())), None, Default::default(), Default::default(), From 88f088c4a011486b131eb4e3d6310419b53c41e7 Mon Sep 17 00:00:00 2001 From: Tetsuharu Ohzeki Date: Sat, 10 Feb 2024 01:00:17 +0900 Subject: [PATCH 27/28] text-edit: Fix warnings about clippy `str_to_string` rule --- crates/text-edit/src/lib.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/text-edit/src/lib.rs b/crates/text-edit/src/lib.rs index fb52a50f0b3f..e2ff373c1baa 100644 --- a/crates/text-edit/src/lib.rs +++ b/crates/text-edit/src/lib.rs @@ -231,11 +231,11 @@ mod tests { #[test] fn test_apply() { - let mut text = "_11h1_2222_xx3333_4444_6666".to_string(); + let mut text = "_11h1_2222_xx3333_4444_6666".to_owned(); let mut builder = TextEditBuilder::default(); - builder.replace(range(3, 4), "1".to_string()); + builder.replace(range(3, 4), "1".to_owned()); builder.delete(range(11, 13)); - builder.insert(22.into(), "_5555".to_string()); + builder.insert(22.into(), "_5555".to_owned()); let text_edit = builder.finish(); text_edit.apply(&mut text); From 71ea70ebf6d35e09df46d8b5d0e81e6f41d7b31c Mon Sep 17 00:00:00 2001 From: Tetsuharu Ohzeki Date: Sat, 10 Feb 2024 00:21:32 +0900 Subject: [PATCH 28/28] clippy: Enable `str_to_string` rule --- Cargo.toml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 30b59498bdc5..2b81f7b11b23 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -180,5 +180,4 @@ print_stdout = "warn" print_stderr = "warn" rc_buffer = "warn" -# FIXME enable this, we use this pattern a lot so its annoying work ... -# str_to_string = "warn" +str_to_string = "warn"