Fix str_to_string wrongly unmangled macros (#16276)

Closes rust-lang/rust-clippy#16271

changelog: [`str_to_string`] fix wrongly unmangled macros
This commit is contained in:
Jason Newcomb 2026-01-06 17:06:23 +00:00 committed by GitHub
commit e3c975f389
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 38 additions and 3 deletions

View file

@ -1,6 +1,6 @@
use clippy_utils::diagnostics::{span_lint, span_lint_and_sugg, span_lint_and_then};
use clippy_utils::res::{MaybeDef, MaybeQPath};
use clippy_utils::source::{snippet, snippet_with_applicability};
use clippy_utils::source::{snippet, snippet_with_applicability, snippet_with_context};
use clippy_utils::{
SpanlessEq, get_expr_use_or_unification_node, get_parent_expr, is_lint_allowed, method_calls, peel_blocks, sym,
};
@ -404,7 +404,8 @@ impl<'tcx> LateLintPass<'tcx> for StrToString {
"`to_string()` called on a `&str`",
|diag| {
let mut applicability = Applicability::MachineApplicable;
let snippet = snippet_with_applicability(cx, self_arg.span, "..", &mut applicability);
let (snippet, _) =
snippet_with_context(cx, self_arg.span, expr.span.ctxt(), "..", &mut applicability);
diag.span_suggestion(expr.span, "try", format!("{snippet}.to_owned()"), applicability);
},
);

View file

@ -8,3 +8,17 @@ fn main() {
msg.to_owned();
//~^ str_to_string
}
fn issue16271(key: &[u8]) {
macro_rules! t {
($e:expr) => {
match $e {
Ok(e) => e,
Err(e) => panic!("{} failed with {}", stringify!($e), e),
}
};
}
let _value = t!(str::from_utf8(key)).to_owned();
//~^ str_to_string
}

View file

@ -8,3 +8,17 @@ fn main() {
msg.to_string();
//~^ str_to_string
}
fn issue16271(key: &[u8]) {
macro_rules! t {
($e:expr) => {
match $e {
Ok(e) => e,
Err(e) => panic!("{} failed with {}", stringify!($e), e),
}
};
}
let _value = t!(str::from_utf8(key)).to_string();
//~^ str_to_string
}

View file

@ -13,5 +13,11 @@ error: `to_string()` called on a `&str`
LL | msg.to_string();
| ^^^^^^^^^^^^^^^ help: try: `msg.to_owned()`
error: aborting due to 2 previous errors
error: `to_string()` called on a `&str`
--> tests/ui/str_to_string.rs:22:18
|
LL | let _value = t!(str::from_utf8(key)).to_string();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `t!(str::from_utf8(key)).to_owned()`
error: aborting due to 3 previous errors