1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::is_trait_method;
3 use clippy_utils::source::snippet_with_applicability;
4 use clippy_utils::ty::is_type_diagnostic_item;
5 use rustc_errors::Applicability;
7 use rustc_lint::LateContext;
9 use rustc_span::{symbol::sym, Span};
11 use super::MAP_FLATTEN;
13 /// lint use of `map().flatten()` for `Iterators` and 'Options'
14 pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, recv: &Expr<'_>, map_arg: &Expr<'_>, map_span: Span) {
15 if let Some((caller_ty_name, method_to_use)) = try_get_caller_ty_name_and_method_name(cx, expr, recv, map_arg) {
16 let mut applicability = Applicability::MachineApplicable;
18 let closure_snippet = snippet_with_applicability(cx, map_arg.span, "..", &mut applicability);
22 expr.span.with_lo(map_span.lo()),
23 &format!("called `map(..).flatten()` on `{caller_ty_name}`"),
24 &format!("try replacing `map` with `{method_to_use}` and remove the `.flatten()`"),
25 format!("{method_to_use}({closure_snippet})"),
31 fn try_get_caller_ty_name_and_method_name(
34 caller_expr: &Expr<'_>,
36 ) -> Option<(&'static str, &'static str)> {
37 if is_trait_method(cx, expr, sym::Iterator) {
38 if is_map_to_option(cx, map_arg) {
39 // `(...).map(...)` has type `impl Iterator<Item=Option<...>>
40 Some(("Iterator", "filter_map"))
42 // `(...).map(...)` has type `impl Iterator<Item=impl Iterator<...>>
43 Some(("Iterator", "flat_map"))
46 if let ty::Adt(adt, _) = cx.typeck_results().expr_ty(caller_expr).kind() {
47 if cx.tcx.is_diagnostic_item(sym::Option, adt.did()) {
48 return Some(("Option", "and_then"));
49 } else if cx.tcx.is_diagnostic_item(sym::Result, adt.did()) {
50 return Some(("Result", "and_then"));
57 fn is_map_to_option(cx: &LateContext<'_>, map_arg: &Expr<'_>) -> bool {
58 let map_closure_ty = cx.typeck_results().expr_ty(map_arg);
59 match map_closure_ty.kind() {
60 ty::Closure(_, _) | ty::FnDef(_, _) | ty::FnPtr(_) => {
61 let map_closure_sig = match map_closure_ty.kind() {
62 ty::Closure(_, substs) => substs.as_closure().sig(),
63 _ => map_closure_ty.fn_sig(cx.tcx),
65 let map_closure_return_ty = cx.tcx.erase_late_bound_regions(map_closure_sig.output());
66 is_type_diagnostic_item(cx, map_closure_return_ty, sym::Option)