Move check for PartialEq in UNCONDITIONAL_RECURSION lint into its own function

This commit is contained in:
Guillaume Gomez 2023-12-18 16:36:12 +01:00
parent 7e650b7610
commit 1c431f4da9

View File

@ -8,6 +8,7 @@ use rustc_hir::{Body, Expr, ExprKind, FnDecl, Item, ItemKind, Node};
use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::ty::{self, Ty};
use rustc_session::declare_lint_pass;
use rustc_span::symbol::Ident;
use rustc_span::{sym, Span};
declare_clippy_lint! {
@ -55,29 +56,24 @@ fn is_local(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
matches!(path_res(cx, expr), Res::Local(_))
}
impl<'tcx> LateLintPass<'tcx> for UnconditionalRecursion {
#[allow(clippy::unnecessary_def_path)]
fn check_fn(
&mut self,
cx: &LateContext<'tcx>,
kind: FnKind<'tcx>,
_decl: &'tcx FnDecl<'tcx>,
body: &'tcx Body<'tcx>,
fn check_partial_eq(
cx: &LateContext<'_>,
body: &Body<'_>,
method_span: Span,
def_id: LocalDefId,
method_def_id: LocalDefId,
name: Ident,
) {
// If the function is a method...
if let FnKind::Method(name, _) = kind
// That has two arguments.
&& let [self_arg, other_arg] = cx
let args = cx
.tcx
.instantiate_bound_regions_with_erased(cx.tcx.fn_sig(def_id).skip_binder())
.inputs()
.instantiate_bound_regions_with_erased(cx.tcx.fn_sig(method_def_id).skip_binder())
.inputs();
// That has two arguments.
if let [self_arg, other_arg] = args
&& let Some(self_arg) = get_ty_def_id(*self_arg)
&& let Some(other_arg) = get_ty_def_id(*other_arg)
// The two arguments are of the same type.
&& self_arg == other_arg
&& let hir_id = cx.tcx.local_def_id_to_hir_id(def_id)
&& let hir_id = cx.tcx.local_def_id_to_hir_id(method_def_id)
&& let Some((
_,
Node::Item(Item {
@ -101,9 +97,7 @@ impl<'tcx> LateLintPass<'tcx> for UnconditionalRecursion {
};
let expr = body.value.peel_blocks();
let is_bad = match expr.kind {
ExprKind::Binary(op, left, right) if op.node == to_check_op => {
is_local(cx, left) && is_local(cx, right)
},
ExprKind::Binary(op, left, right) if op.node == to_check_op => is_local(cx, left) && is_local(cx, right),
ExprKind::MethodCall(segment, receiver, &[arg], _) if segment.ident.name == name.name => {
if is_local(cx, receiver)
&& is_local(cx, &arg)
@ -131,4 +125,23 @@ impl<'tcx> LateLintPass<'tcx> for UnconditionalRecursion {
}
}
}
impl<'tcx> LateLintPass<'tcx> for UnconditionalRecursion {
#[allow(clippy::unnecessary_def_path)]
fn check_fn(
&mut self,
cx: &LateContext<'tcx>,
kind: FnKind<'tcx>,
_decl: &'tcx FnDecl<'tcx>,
body: &'tcx Body<'tcx>,
method_span: Span,
method_def_id: LocalDefId,
) {
// If the function is a method...
if let FnKind::Method(name, _) = kind {
if name.name == sym::eq || name.name == sym::ne {
check_partial_eq(cx, body, method_span, method_def_id, name);
}
}
}
}