From 5d0fcfbf56bb53fa70783c3d0d0251a3700b4bd5 Mon Sep 17 00:00:00 2001 From: Jacher Date: Thu, 30 May 2024 17:02:23 +0000 Subject: [PATCH] modify str_to_string to be machine-applicable --- clippy_lints/src/strings.rs | 10 +++++++--- tests/ui/str_to_string.fixed | 9 +++++++++ tests/ui/str_to_string.stderr | 7 ++----- 3 files changed, 18 insertions(+), 8 deletions(-) create mode 100644 tests/ui/str_to_string.fixed diff --git a/clippy_lints/src/strings.rs b/clippy_lints/src/strings.rs index f8d36d6b92f..7da661485ab 100644 --- a/clippy_lints/src/strings.rs +++ b/clippy_lints/src/strings.rs @@ -399,13 +399,17 @@ fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &Expr<'_>) { && let ty::Ref(_, ty, ..) = ty.kind() && ty.is_str() { - span_lint_and_help( + let mut applicability = Applicability::MachineApplicable; + let snippet = snippet_with_applicability(cx, self_arg.span, "..", &mut applicability); + + span_lint_and_sugg( cx, STR_TO_STRING, expr.span, "`to_string()` called on a `&str`", - None, - "consider using `.to_owned()`", + "try", + format!("{snippet}.to_owned()"), + applicability, ); } } diff --git a/tests/ui/str_to_string.fixed b/tests/ui/str_to_string.fixed new file mode 100644 index 00000000000..52e40b45a8b --- /dev/null +++ b/tests/ui/str_to_string.fixed @@ -0,0 +1,9 @@ +#![warn(clippy::str_to_string)] + +fn main() { + let hello = "hello world".to_owned(); + //~^ ERROR: `to_string()` called on a `&str` + let msg = &hello[..]; + msg.to_owned(); + //~^ ERROR: `to_string()` called on a `&str` +} diff --git a/tests/ui/str_to_string.stderr b/tests/ui/str_to_string.stderr index 13b73622d69..a761d96cd6b 100644 --- a/tests/ui/str_to_string.stderr +++ b/tests/ui/str_to_string.stderr @@ -2,9 +2,8 @@ error: `to_string()` called on a `&str` --> tests/ui/str_to_string.rs:4:17 | LL | let hello = "hello world".to_string(); - | ^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `"hello world".to_owned()` | - = help: consider using `.to_owned()` = note: `-D clippy::str-to-string` implied by `-D warnings` = help: to override `-D warnings` add `#[allow(clippy::str_to_string)]` @@ -12,9 +11,7 @@ error: `to_string()` called on a `&str` --> tests/ui/str_to_string.rs:7:5 | LL | msg.to_string(); - | ^^^^^^^^^^^^^^^ - | - = help: consider using `.to_owned()` + | ^^^^^^^^^^^^^^^ help: try: `msg.to_owned()` error: aborting due to 2 previous errors