Skip to content

Commit 993b401

Browse files
committed
Don't lint cmp_owned when From::from results in a copy type.
1 parent 0f1544f commit 993b401

File tree

3 files changed

+29
-3
lines changed

3 files changed

+29
-3
lines changed

clippy_lints/src/misc.rs

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use clippy_utils::diagnostics::{span_lint, span_lint_and_sugg, span_lint_and_then, span_lint_hir_and_then};
22
use clippy_utils::source::{snippet, snippet_opt};
3-
use clippy_utils::ty::implements_trait;
3+
use clippy_utils::ty::{implements_trait, is_copy};
44
use if_chain::if_chain;
55
use rustc_ast::ast::LitKind;
66
use rustc_errors::Applicability;
@@ -584,7 +584,11 @@ fn check_to_owned(cx: &LateContext<'_>, expr: &Expr<'_>, other: &Expr<'_>, left:
584584
ExprKind::Call(path, [arg])
585585
if path_def_id(cx, path)
586586
.and_then(|id| match_any_def_paths(cx, id, &[&paths::FROM_STR_METHOD, &paths::FROM_FROM]))
587-
.is_some() =>
587+
.map_or(false, |idx| match idx {
588+
0 => true,
589+
1 => !is_copy(cx, typeck.expr_ty(expr)),
590+
_ => false,
591+
}) =>
588592
{
589593
(arg, arg.span)
590594
},

tests/ui/cmp_owned/without_suggestion.rs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,10 @@ fn main() {
99
let x = &&Baz;
1010
let y = &Baz;
1111
y.to_owned() == **x;
12+
13+
let x = 0u32;
14+
let y = U32Wrapper(x);
15+
let _ = U32Wrapper::from(x) == y;
1216
}
1317

1418
struct Foo;
@@ -51,3 +55,21 @@ impl std::borrow::Borrow<Foo> for Bar {
5155
&FOO
5256
}
5357
}
58+
59+
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
60+
struct U32Wrapper(u32);
61+
impl From<u32> for U32Wrapper {
62+
fn from(x: u32) -> Self {
63+
Self(x)
64+
}
65+
}
66+
impl PartialEq<u32> for U32Wrapper {
67+
fn eq(&self, other: &u32) -> bool {
68+
self.0 == *other
69+
}
70+
}
71+
impl PartialEq<U32Wrapper> for u32 {
72+
fn eq(&self, other: &U32Wrapper) -> bool {
73+
*self == other.0
74+
}
75+
}

tests/ui/cmp_owned/without_suggestion.stderr

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ LL | y.to_owned() == **x;
1313
| ^^^^^^^^^^^^^^^^^^^ try implementing the comparison without allocating
1414

1515
error: this creates an owned instance just for comparison
16-
--> $DIR/without_suggestion.rs:18:9
16+
--> $DIR/without_suggestion.rs:22:9
1717
|
1818
LL | self.to_owned() == *other
1919
| ^^^^^^^^^^^^^^^^^^^^^^^^^ try implementing the comparison without allocating

0 commit comments

Comments
 (0)