Skip to content

Commit

Permalink
Auto merge of #12871 - Jacherr:issue-12768, r=blyxyas
Browse files Browse the repository at this point in the history
Modify str_to_string to be machine-applicable

Fixes #12768

I'm not sure if there is any potential for edge cases with this - since it only ever acts on `&str` types I can't think of any, and especially since the methods do the same thing anyway.

changelog: allow `str_to_string` lint to be automatically applied
  • Loading branch information
bors committed Jun 2, 2024
2 parents 436675b + 5d0fcfb commit 568f4fc
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 8 deletions.
10 changes: 7 additions & 3 deletions clippy_lints/src/strings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
);
}
}
Expand Down
9 changes: 9 additions & 0 deletions tests/ui/str_to_string.fixed
Original file line number Diff line number Diff line change
@@ -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`
}
7 changes: 2 additions & 5 deletions tests/ui/str_to_string.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,16 @@ 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)]`

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

0 comments on commit 568f4fc

Please sign in to comment.