From 8a77369ca4aa14a4c72105f7b75631d25961d911 Mon Sep 17 00:00:00 2001 From: EvoPot Date: Sat, 2 May 2026 06:01:15 +0300 Subject: [PATCH] Add extra symbol check for `.to_owned()` Previously when adding a suggestion for using `Cow::into_owned()` instead of `ToOwned::to_owned()`, the compiler would just convert the methods `Span` into a `String` and do checks on that `String`. This PR adds an extra guard to that suggestion by checking if the method is `sym::to_owned_method`. --- .../src/diagnostics/conflict_errors.rs | 23 ++++++++++--------- compiler/rustc_span/src/symbol.rs | 1 + src/tools/clippy/clippy_utils/src/sym.rs | 1 - 3 files changed, 13 insertions(+), 12 deletions(-) diff --git a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs index f7d35f3ff3b4b..61a2dbc2f5fc2 100644 --- a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs @@ -3536,17 +3536,18 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { && let ty::Adt(adt_def, _) = return_ty.kind() && adt_def.did() == cow_did { - if let Ok(snippet) = tcx.sess.source_map().span_to_snippet(return_span) { - if let Some(pos) = snippet.rfind(".to_owned") { - let byte_pos = BytePos(pos as u32 + 1u32); - let to_owned_span = return_span.with_hi(return_span.lo() + byte_pos); - err.span_suggestion_short( - to_owned_span.shrink_to_hi(), - "try using `.into_owned()` if you meant to convert a `Cow<'_, T>` to an owned `T`", - "in", - Applicability::MaybeIncorrect, - ); - } + let typeck = tcx.typeck(self.mir_def_id()); + if let Some(expr) = self.find_expr(return_span) + && let Some(def_id) = typeck.type_dependent_def_id(expr.hir_id) + && tcx.is_diagnostic_item(sym::to_owned_method, def_id) + && let Some(to_owned_ident) = expr.method_ident() + { + err.span_suggestion_short( + to_owned_ident.span.shrink_to_lo(), + "try using `.into_owned()` if you meant to convert a `Cow<'_, T>` to an owned `T`", + "in", + Applicability::MaybeIncorrect, + ); } } } diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index caeb923c18f78..f46ea8295ae92 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -2046,6 +2046,7 @@ symbols! { thumb2, thumb_mode: "thumb-mode", tmm_reg, + to_owned_method, to_string, to_vec, tool_attributes, diff --git a/src/tools/clippy/clippy_utils/src/sym.rs b/src/tools/clippy/clippy_utils/src/sym.rs index 87aac25f5bd12..367ec897dae48 100644 --- a/src/tools/clippy/clippy_utils/src/sym.rs +++ b/src/tools/clippy/clippy_utils/src/sym.rs @@ -606,7 +606,6 @@ generate! { to_ne_bytes, to_os_string, to_owned, - to_owned_method, to_path_buf, to_string_method, to_uppercase,