Skip to content

[unnecessary_to_owned]: check that the adjusted type matches target #10913

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 9, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions clippy_lints/src/methods/unnecessary_to_owned.rs
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,11 @@ fn check_addr_of_expr(
if let Some(deref_trait_id) = cx.tcx.get_diagnostic_item(sym::Deref);
if implements_trait(cx, receiver_ty, deref_trait_id, &[]);
if cx.get_associated_type(receiver_ty, deref_trait_id, "Target") == Some(target_ty);
// Make sure that it's actually calling the right `.to_string()`, (#10033)
// *or* this is a `Cow::into_owned()` call (which would be the wrong into_owned receiver (str != Cow)
// but that's ok for Cow::into_owned specifically)
if cx.typeck_results().expr_ty_adjusted(receiver).peel_refs() == target_ty
|| is_cow_into_owned(cx, method_name, method_def_id);
then {
if n_receiver_refs > 0 {
span_lint_and_sugg(
Expand Down
33 changes: 33 additions & 0 deletions tests/ui/unnecessary_to_owned.fixed
Original file line number Diff line number Diff line change
Expand Up @@ -474,3 +474,36 @@ mod issue_10021 {
Ok(())
}
}

mod issue_10033 {
#![allow(dead_code)]
use std::{fmt::Display, ops::Deref};

fn _main() {
let f = Foo;

// Not actually unnecessary - this calls `Foo`'s `Display` impl, not `str`'s (even though `Foo` does
// deref to `str`)
foo(&f.to_string());
}

fn foo(s: &str) {
println!("{}", s);
}

struct Foo;

impl Deref for Foo {
type Target = str;

fn deref(&self) -> &Self::Target {
"str"
}
}

impl Display for Foo {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Foo")
}
}
}
33 changes: 33 additions & 0 deletions tests/ui/unnecessary_to_owned.rs
Original file line number Diff line number Diff line change
Expand Up @@ -474,3 +474,36 @@ mod issue_10021 {
Ok(())
}
}

mod issue_10033 {
#![allow(dead_code)]
use std::{fmt::Display, ops::Deref};

fn _main() {
let f = Foo;

// Not actually unnecessary - this calls `Foo`'s `Display` impl, not `str`'s (even though `Foo` does
// deref to `str`)
foo(&f.to_string());
}

fn foo(s: &str) {
println!("{}", s);
}

struct Foo;

impl Deref for Foo {
type Target = str;

fn deref(&self) -> &Self::Target {
"str"
}
}

impl Display for Foo {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Foo")
}
}
}