Skip to content

Commit 728f397

Browse files
committed
Auto merge of #6771 - MortenLohne:master, r=flip1995
Fix FP in inherent_to_string when the function has generic parameters Minimal example of the false positive: ```` struct G; impl G { fn to_string<const _N: usize>(&self) -> String { "G.to_string()".to_string() } } fn main() { let g = G; g.to_string::<1>(); } ```` Clippy emits an `inherent_to_string` warning, and suggests that we implement `Display` for `G` instead. However, this is not possible, since the generic parameter _N only exists in this function, not in `G` itself. This particular example uses const generics, which is where the issue is most likely to come up, but this PR skips the lint if the `to_string` function has any kind of generic parameters. changelog: Fix FP in `inherent_to_string`
2 parents 208e957 + 19a3775 commit 728f397

File tree

3 files changed

+14
-2
lines changed

3 files changed

+14
-2
lines changed

clippy_lints/src/inherent_to_string.rs

+1
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,7 @@ impl<'tcx> LateLintPass<'tcx> for InherentToString {
106106
let decl = &signature.decl;
107107
if decl.implicit_self.has_implicit_self();
108108
if decl.inputs.len() == 1;
109+
if impl_item.generics.params.is_empty();
109110

110111
// Check if return type is String
111112
if is_type_diagnostic_item(cx, return_ty(cx, impl_item.hir_id), sym::string_type);

tests/ui/inherent_to_string.rs

+11
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ struct C;
1414
struct D;
1515
struct E;
1616
struct F;
17+
struct G;
1718

1819
impl A {
1920
// Should be detected; emit warning
@@ -73,6 +74,13 @@ impl F {
7374
}
7475
}
7576

77+
impl G {
78+
// Should not be detected, as it does not match the function signature
79+
fn to_string<const _N: usize>(&self) -> String {
80+
"G.to_string()".to_string()
81+
}
82+
}
83+
7684
fn main() {
7785
let a = A;
7886
a.to_string();
@@ -93,4 +101,7 @@ fn main() {
93101

94102
let f = F;
95103
f.to_string(1);
104+
105+
let g = G;
106+
g.to_string::<1>();
96107
}

tests/ui/inherent_to_string.stderr

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
error: implementation of inherent method `to_string(&self) -> String` for type `A`
2-
--> $DIR/inherent_to_string.rs:20:5
2+
--> $DIR/inherent_to_string.rs:21:5
33
|
44
LL | / fn to_string(&self) -> String {
55
LL | | "A.to_string()".to_string()
@@ -10,7 +10,7 @@ LL | | }
1010
= help: implement trait `Display` for type `A` instead
1111

1212
error: type `C` implements inherent method `to_string(&self) -> String` which shadows the implementation of `Display`
13-
--> $DIR/inherent_to_string.rs:44:5
13+
--> $DIR/inherent_to_string.rs:45:5
1414
|
1515
LL | / fn to_string(&self) -> String {
1616
LL | | "C.to_string()".to_string()

0 commit comments

Comments
 (0)