about summary refs log tree commit diff
diff options
context:
space:
mode:
authorJacher <jwc2002@outlook.com>2024-05-30 17:02:23 +0000
committerJacher <jwc2002@outlook.com>2024-06-01 09:05:27 +0000
commit5d0fcfbf56bb53fa70783c3d0d0251a3700b4bd5 (patch)
tree80d69ccd74426b4d82fced153049e86270619df8
parente7efe4381af5ae065105f6fa8c30ae86e01d3d9a (diff)
downloadrust-5d0fcfbf56bb53fa70783c3d0d0251a3700b4bd5.tar.gz
rust-5d0fcfbf56bb53fa70783c3d0d0251a3700b4bd5.zip
modify str_to_string to be machine-applicable
-rw-r--r--clippy_lints/src/strings.rs10
-rw-r--r--tests/ui/str_to_string.fixed9
-rw-r--r--tests/ui/str_to_string.stderr7
3 files changed, 18 insertions, 8 deletions
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 @@ impl<'tcx> LateLintPass<'tcx> for StrToString {
             && 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