1 use clippy_utils::diagnostics::{span_lint, span_lint_and_sugg};
2 use clippy_utils::source::snippet;
3 use clippy_utils::ty::implements_trait;
4 use rustc_errors::Applicability;
6 use rustc_lint::LateContext;
9 use super::FILTER_NEXT;
11 /// lint use of `filter().next()` for `Iterators`
12 pub(super) fn check<'tcx>(
13 cx: &LateContext<'tcx>,
14 expr: &'tcx hir::Expr<'_>,
15 recv: &'tcx hir::Expr<'_>,
16 filter_arg: &'tcx hir::Expr<'_>,
18 // lint if caller of `.filter().next()` is an Iterator
19 let recv_impls_iterator = cx.tcx.get_diagnostic_item(sym::Iterator).map_or(false, |id| {
20 implements_trait(cx, cx.typeck_results().expr_ty(recv), id, &[])
22 if recv_impls_iterator {
23 let msg = "called `filter(..).next()` on an `Iterator`. This is more succinctly expressed by calling \
25 let filter_snippet = snippet(cx, filter_arg.span, "..");
26 if filter_snippet.lines().count() <= 1 {
27 let iter_snippet = snippet(cx, recv.span, "..");
28 // add note if not multi-line
35 format!("{iter_snippet}.find({filter_snippet})"),
36 Applicability::MachineApplicable,
39 span_lint(cx, FILTER_NEXT, expr.span, msg);