needless_for_each: Check HIR tree first.

This commit is contained in:
Jason Newcomb 2024-06-15 02:13:32 -04:00
parent 139dad8849
commit 7c17dd331b

View file

@ -3,7 +3,7 @@ use rustc_hir::intravisit::{walk_expr, Visitor};
use rustc_hir::{Block, BlockCheckMode, Closure, Expr, ExprKind, Stmt, StmtKind}; use rustc_hir::{Block, BlockCheckMode, Closure, Expr, ExprKind, Stmt, StmtKind};
use rustc_lint::{LateContext, LateLintPass}; use rustc_lint::{LateContext, LateLintPass};
use rustc_session::declare_lint_pass; use rustc_session::declare_lint_pass;
use rustc_span::{sym, Span, Symbol}; use rustc_span::{sym, Span};
use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::diagnostics::span_lint_and_then;
use clippy_utils::is_trait_method; use clippy_utils::is_trait_method;
@ -55,16 +55,8 @@ declare_lint_pass!(NeedlessForEach => [NEEDLESS_FOR_EACH]);
impl<'tcx> LateLintPass<'tcx> for NeedlessForEach { impl<'tcx> LateLintPass<'tcx> for NeedlessForEach {
fn check_stmt(&mut self, cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'_>) { fn check_stmt(&mut self, cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'_>) {
let (StmtKind::Expr(expr) | StmtKind::Semi(expr)) = stmt.kind else { if let StmtKind::Expr(expr) | StmtKind::Semi(expr) = stmt.kind
return; && let ExprKind::MethodCall(method_name, for_each_recv, [for_each_arg], _) = expr.kind
};
if let ExprKind::MethodCall(method_name, for_each_recv, [for_each_arg], _) = expr.kind
// Check the method name is `for_each`.
&& method_name.ident.name == Symbol::intern("for_each")
// Check `for_each` is an associated function of `Iterator`.
&& is_trait_method(cx, expr, sym::Iterator)
// Checks the receiver of `for_each` is also a method call.
&& let ExprKind::MethodCall(_, iter_recv, [], _) = for_each_recv.kind && let ExprKind::MethodCall(_, iter_recv, [], _) = for_each_recv.kind
// Skip the lint if the call chain is too long. e.g. `v.field.iter().for_each()` or // Skip the lint if the call chain is too long. e.g. `v.field.iter().for_each()` or
// `v.foo().iter().for_each()` must be skipped. // `v.foo().iter().for_each()` must be skipped.
@ -72,6 +64,8 @@ impl<'tcx> LateLintPass<'tcx> for NeedlessForEach {
iter_recv.kind, iter_recv.kind,
ExprKind::Array(..) | ExprKind::Call(..) | ExprKind::Path(..) ExprKind::Array(..) | ExprKind::Call(..) | ExprKind::Path(..)
) )
&& method_name.ident.name.as_str() == "for_each"
&& is_trait_method(cx, expr, sym::Iterator)
// Checks the type of the `iter` method receiver is NOT a user defined type. // Checks the type of the `iter` method receiver is NOT a user defined type.
&& has_iter_method(cx, cx.typeck_results().expr_ty(iter_recv)).is_some() && has_iter_method(cx, cx.typeck_results().expr_ty(iter_recv)).is_some()
// Skip the lint if the body is not block because this is simpler than `for` loop. // Skip the lint if the body is not block because this is simpler than `for` loop.