Skip to content

Commit 9907b90

Browse files
committed
Auto merge of #11938 - GuillaumeGomez:unconditional_recursion, r=llogiq
Add new `unconditional_recursion` lint Currently, rustc `unconditional_recursion` doesn't detect cases like: ```rust enum Foo { A, B, } impl PartialEq for Foo { fn eq(&self, other: &Self) -> bool { self == other } } ``` This is because the lint is currently implemented only for one level, and in the above code, `self == other` will then call `impl PartialEq for &T`, escaping from the detection. The fix for it seems to be a bit tricky (I started investigating potential solution to add one extra level of recursion [here](https://github.com/rust-lang/rust/compare/master...GuillaumeGomez:rust:trait-impl-recursion?expand=1) but completely broken at the moment). I expect that this situation will remain for a while. In the meantime, I think it's acceptable to check it directly into clippy for the time being as a lot of easy cases like this one can be easily checked (next I plan to extend it to cover other traits like `ToString`). changelog: Add new `unconditional_recursion` lint
2 parents b918434 + 6b444f3 commit 9907b90

File tree

6 files changed

+552
-0
lines changed

6 files changed

+552
-0
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5582,6 +5582,7 @@ Released 2018-09-13
55825582
[`type_id_on_box`]: https://rust-lang.github.io/rust-clippy/master/index.html#type_id_on_box
55835583
[`type_repetition_in_bounds`]: https://rust-lang.github.io/rust-clippy/master/index.html#type_repetition_in_bounds
55845584
[`unchecked_duration_subtraction`]: https://rust-lang.github.io/rust-clippy/master/index.html#unchecked_duration_subtraction
5585+
[`unconditional_recursion`]: https://rust-lang.github.io/rust-clippy/master/index.html#unconditional_recursion
55855586
[`undocumented_unsafe_blocks`]: https://rust-lang.github.io/rust-clippy/master/index.html#undocumented_unsafe_blocks
55865587
[`undropped_manually_drops`]: https://rust-lang.github.io/rust-clippy/master/index.html#undropped_manually_drops
55875588
[`unicode_not_nfc`]: https://rust-lang.github.io/rust-clippy/master/index.html#unicode_not_nfc

clippy_lints/src/declared_lints.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -676,6 +676,7 @@ pub(crate) static LINTS: &[&crate::LintInfo] = &[
676676
crate::types::REDUNDANT_ALLOCATION_INFO,
677677
crate::types::TYPE_COMPLEXITY_INFO,
678678
crate::types::VEC_BOX_INFO,
679+
crate::unconditional_recursion::UNCONDITIONAL_RECURSION_INFO,
679680
crate::undocumented_unsafe_blocks::UNDOCUMENTED_UNSAFE_BLOCKS_INFO,
680681
crate::undocumented_unsafe_blocks::UNNECESSARY_SAFETY_COMMENT_INFO,
681682
crate::unicode::INVISIBLE_CHARACTERS_INFO,

clippy_lints/src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -327,6 +327,7 @@ mod trait_bounds;
327327
mod transmute;
328328
mod tuple_array_conversions;
329329
mod types;
330+
mod unconditional_recursion;
330331
mod undocumented_unsafe_blocks;
331332
mod unicode;
332333
mod uninhabited_references;
@@ -1078,6 +1079,7 @@ pub fn register_lints(store: &mut rustc_lint::LintStore, conf: &'static Conf) {
10781079
store.register_late_pass(|_| Box::new(repeat_vec_with_capacity::RepeatVecWithCapacity));
10791080
store.register_late_pass(|_| Box::new(uninhabited_references::UninhabitedReferences));
10801081
store.register_late_pass(|_| Box::new(ineffective_open_options::IneffectiveOpenOptions));
1082+
store.register_late_pass(|_| Box::new(unconditional_recursion::UnconditionalRecursion));
10811083
// add lints here, do not remove this comment, it's used in `new_lint`
10821084
}
10831085

Lines changed: 134 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,134 @@
1+
use clippy_utils::diagnostics::span_lint_and_then;
2+
use clippy_utils::{get_trait_def_id, path_res};
3+
use rustc_ast::BinOpKind;
4+
use rustc_hir::def::Res;
5+
use rustc_hir::def_id::{DefId, LocalDefId};
6+
use rustc_hir::intravisit::FnKind;
7+
use rustc_hir::{Body, Expr, ExprKind, FnDecl, Item, ItemKind, Node};
8+
use rustc_lint::{LateContext, LateLintPass};
9+
use rustc_middle::ty::{self, Ty};
10+
use rustc_session::declare_lint_pass;
11+
use rustc_span::{sym, Span};
12+
13+
declare_clippy_lint! {
14+
/// ### What it does
15+
/// Checks that there isn't an infinite recursion in `PartialEq` trait
16+
/// implementation.
17+
///
18+
/// ### Why is this bad?
19+
/// This is a hard to find infinite recursion which will crashing any code
20+
/// using it.
21+
///
22+
/// ### Example
23+
/// ```no_run
24+
/// enum Foo {
25+
/// A,
26+
/// B,
27+
/// }
28+
///
29+
/// impl PartialEq for Foo {
30+
/// fn eq(&self, other: &Self) -> bool {
31+
/// self == other // bad!
32+
/// }
33+
/// }
34+
/// ```
35+
/// Use instead:
36+
///
37+
/// In such cases, either use `#[derive(PartialEq)]` or don't implement it.
38+
#[clippy::version = "1.76.0"]
39+
pub UNCONDITIONAL_RECURSION,
40+
suspicious,
41+
"detect unconditional recursion in some traits implementation"
42+
}
43+
44+
declare_lint_pass!(UnconditionalRecursion => [UNCONDITIONAL_RECURSION]);
45+
46+
fn get_ty_def_id(ty: Ty<'_>) -> Option<DefId> {
47+
match ty.peel_refs().kind() {
48+
ty::Adt(adt, _) => Some(adt.did()),
49+
ty::Foreign(def_id) => Some(*def_id),
50+
_ => None,
51+
}
52+
}
53+
54+
fn is_local(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
55+
matches!(path_res(cx, expr), Res::Local(_))
56+
}
57+
58+
impl<'tcx> LateLintPass<'tcx> for UnconditionalRecursion {
59+
#[allow(clippy::unnecessary_def_path)]
60+
fn check_fn(
61+
&mut self,
62+
cx: &LateContext<'tcx>,
63+
kind: FnKind<'tcx>,
64+
_decl: &'tcx FnDecl<'tcx>,
65+
body: &'tcx Body<'tcx>,
66+
method_span: Span,
67+
def_id: LocalDefId,
68+
) {
69+
// If the function is a method...
70+
if let FnKind::Method(name, _) = kind
71+
// That has two arguments.
72+
&& let [self_arg, other_arg] = cx
73+
.tcx
74+
.instantiate_bound_regions_with_erased(cx.tcx.fn_sig(def_id).skip_binder())
75+
.inputs()
76+
&& let Some(self_arg) = get_ty_def_id(*self_arg)
77+
&& let Some(other_arg) = get_ty_def_id(*other_arg)
78+
// The two arguments are of the same type.
79+
&& self_arg == other_arg
80+
&& let hir_id = cx.tcx.local_def_id_to_hir_id(def_id)
81+
&& let Some((
82+
_,
83+
Node::Item(Item {
84+
kind: ItemKind::Impl(impl_),
85+
owner_id,
86+
..
87+
}),
88+
)) = cx.tcx.hir().parent_iter(hir_id).next()
89+
// We exclude `impl` blocks generated from rustc's proc macros.
90+
&& !cx.tcx.has_attr(*owner_id, sym::automatically_derived)
91+
// It is a implementation of a trait.
92+
&& let Some(trait_) = impl_.of_trait
93+
&& let Some(trait_def_id) = trait_.trait_def_id()
94+
// The trait is `PartialEq`.
95+
&& Some(trait_def_id) == get_trait_def_id(cx, &["core", "cmp", "PartialEq"])
96+
{
97+
let to_check_op = if name.name == sym::eq {
98+
BinOpKind::Eq
99+
} else {
100+
BinOpKind::Ne
101+
};
102+
let expr = body.value.peel_blocks();
103+
let is_bad = match expr.kind {
104+
ExprKind::Binary(op, left, right) if op.node == to_check_op => {
105+
is_local(cx, left) && is_local(cx, right)
106+
},
107+
ExprKind::MethodCall(segment, receiver, &[arg], _) if segment.ident.name == name.name => {
108+
if is_local(cx, receiver)
109+
&& is_local(cx, &arg)
110+
&& let Some(fn_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id)
111+
&& let Some(trait_id) = cx.tcx.trait_of_item(fn_id)
112+
&& trait_id == trait_def_id
113+
{
114+
true
115+
} else {
116+
false
117+
}
118+
},
119+
_ => false,
120+
};
121+
if is_bad {
122+
span_lint_and_then(
123+
cx,
124+
UNCONDITIONAL_RECURSION,
125+
method_span,
126+
"function cannot return without recursing",
127+
|diag| {
128+
diag.span_note(expr.span, "recursive call site");
129+
},
130+
);
131+
}
132+
}
133+
}
134+
}

tests/ui/unconditional_recursion.rs

Lines changed: 163 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,163 @@
1+
//@no-rustfix
2+
3+
#![warn(clippy::unconditional_recursion)]
4+
#![allow(clippy::partialeq_ne_impl)]
5+
6+
enum Foo {
7+
A,
8+
B,
9+
}
10+
11+
impl PartialEq for Foo {
12+
fn ne(&self, other: &Self) -> bool {
13+
//~^ ERROR: function cannot return without recursing
14+
self != other
15+
}
16+
fn eq(&self, other: &Self) -> bool {
17+
//~^ ERROR: function cannot return without recursing
18+
self == other
19+
}
20+
}
21+
22+
enum Foo2 {
23+
A,
24+
B,
25+
}
26+
27+
impl PartialEq for Foo2 {
28+
fn ne(&self, other: &Self) -> bool {
29+
self != &Foo2::B // no error here
30+
}
31+
fn eq(&self, other: &Self) -> bool {
32+
self == &Foo2::B // no error here
33+
}
34+
}
35+
36+
enum Foo3 {
37+
A,
38+
B,
39+
}
40+
41+
impl PartialEq for Foo3 {
42+
fn ne(&self, other: &Self) -> bool {
43+
//~^ ERROR: function cannot return without recursing
44+
self.ne(other)
45+
}
46+
fn eq(&self, other: &Self) -> bool {
47+
//~^ ERROR: function cannot return without recursing
48+
self.eq(other)
49+
}
50+
}
51+
52+
enum Foo4 {
53+
A,
54+
B,
55+
}
56+
57+
impl PartialEq for Foo4 {
58+
fn ne(&self, other: &Self) -> bool {
59+
self.eq(other) // no error
60+
}
61+
fn eq(&self, other: &Self) -> bool {
62+
self.ne(other) // no error
63+
}
64+
}
65+
66+
enum Foo5 {
67+
A,
68+
B,
69+
}
70+
71+
impl Foo5 {
72+
fn a(&self) -> bool {
73+
true
74+
}
75+
}
76+
77+
impl PartialEq for Foo5 {
78+
fn ne(&self, other: &Self) -> bool {
79+
self.a() // no error
80+
}
81+
fn eq(&self, other: &Self) -> bool {
82+
self.a() // no error
83+
}
84+
}
85+
86+
struct S;
87+
88+
// Check the order doesn't matter.
89+
impl PartialEq for S {
90+
fn ne(&self, other: &Self) -> bool {
91+
//~^ ERROR: function cannot return without recursing
92+
other != self
93+
}
94+
fn eq(&self, other: &Self) -> bool {
95+
//~^ ERROR: function cannot return without recursing
96+
other == self
97+
}
98+
}
99+
100+
struct S2;
101+
102+
// Check that if the same element is compared, it's also triggering the lint.
103+
impl PartialEq for S2 {
104+
fn ne(&self, other: &Self) -> bool {
105+
//~^ ERROR: function cannot return without recursing
106+
other != other
107+
}
108+
fn eq(&self, other: &Self) -> bool {
109+
//~^ ERROR: function cannot return without recursing
110+
other == other
111+
}
112+
}
113+
114+
struct S3;
115+
116+
impl PartialEq for S3 {
117+
fn ne(&self, _other: &Self) -> bool {
118+
//~^ ERROR: function cannot return without recursing
119+
self != self
120+
}
121+
fn eq(&self, _other: &Self) -> bool {
122+
//~^ ERROR: function cannot return without recursing
123+
self == self
124+
}
125+
}
126+
127+
// There should be no warning here!
128+
#[derive(PartialEq)]
129+
enum E {
130+
A,
131+
B,
132+
}
133+
134+
#[derive(PartialEq)]
135+
struct Bar<T: PartialEq>(T);
136+
137+
struct S4;
138+
139+
impl PartialEq for S4 {
140+
fn eq(&self, other: &Self) -> bool {
141+
// No warning here.
142+
Bar(self) == Bar(other)
143+
}
144+
}
145+
146+
macro_rules! impl_partial_eq {
147+
($ty:ident) => {
148+
impl PartialEq for $ty {
149+
fn eq(&self, other: &Self) -> bool {
150+
self == other
151+
}
152+
}
153+
};
154+
}
155+
156+
struct S5;
157+
158+
impl_partial_eq!(S5);
159+
//~^ ERROR: function cannot return without recursing
160+
161+
fn main() {
162+
// test code goes here
163+
}

0 commit comments

Comments
 (0)