|
| 1 | +use clippy_utils::diagnostics::span_lint_and_sugg; |
| 2 | +use clippy_utils::paths::BOOL_THEN; |
| 3 | +use clippy_utils::source::snippet_opt; |
| 4 | +use clippy_utils::{is_from_proc_macro, match_def_path, peel_blocks}; |
| 5 | +use rustc_errors::Applicability; |
| 6 | +use rustc_hir::{Expr, ExprKind}; |
| 7 | +use rustc_lint::{LateContext, LintContext}; |
| 8 | +use rustc_middle::lint::in_external_macro; |
| 9 | +use rustc_span::Span; |
| 10 | + |
| 11 | +use super::FILTER_MAP_BOOL_THEN; |
| 12 | + |
| 13 | +pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>, arg: &Expr<'_>, call_span: Span) { |
| 14 | + if !in_external_macro(cx.sess(), expr.span) |
| 15 | + && let ExprKind::Closure(closure) = arg.kind |
| 16 | + && let body = peel_blocks(cx.tcx.hir().body(closure.body).value) |
| 17 | + && let ExprKind::MethodCall(_, recv, [then_arg], _) = body.kind |
| 18 | + && let ExprKind::Closure(then_closure) = then_arg.kind |
| 19 | + && let then_body = peel_blocks(cx.tcx.hir().body(then_closure.body).value) |
| 20 | + && let Some(def_id) = cx.typeck_results().type_dependent_def_id(body.hir_id) |
| 21 | + && match_def_path(cx, def_id, &BOOL_THEN) |
| 22 | + && !is_from_proc_macro(cx, expr) |
| 23 | + && let Some(decl_snippet) = closure.fn_arg_span.and_then(|s| snippet_opt(cx, s)) |
| 24 | + // NOTE: This will include the `()` (parenthesis) around it. Maybe there's some utils method |
| 25 | + // to remove them? `unused_parens` will already take care of this but it may be nice. |
| 26 | + && let Some(filter) = snippet_opt(cx, recv.span) |
| 27 | + && let Some(map) = snippet_opt(cx, then_body.span) |
| 28 | + { |
| 29 | + span_lint_and_sugg( |
| 30 | + cx, |
| 31 | + FILTER_MAP_BOOL_THEN, |
| 32 | + call_span, |
| 33 | + "usage of `bool::then` in `filter_map`", |
| 34 | + "use `filter` then `map` instead", |
| 35 | + format!("filter({decl_snippet} {filter}).map({decl_snippet} {map})"), |
| 36 | + Applicability::MachineApplicable, |
| 37 | + ); |
| 38 | + } |
| 39 | +} |
0 commit comments