]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/methods/map_collect_result_unit.rs
Auto merge of #6957 - camsteffen:eq-ty-kind, r=flip1995
[rust.git] / clippy_lints / src / methods / map_collect_result_unit.rs
1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::is_trait_method;
3 use clippy_utils::source::snippet;
4 use clippy_utils::ty::is_type_diagnostic_item;
5 use if_chain::if_chain;
6 use rustc_errors::Applicability;
7 use rustc_hir as hir;
8 use rustc_lint::LateContext;
9 use rustc_middle::ty;
10 use rustc_span::symbol::sym;
11
12 use super::MAP_COLLECT_RESULT_UNIT;
13
14 pub(super) fn check(
15     cx: &LateContext<'_>,
16     expr: &hir::Expr<'_>,
17     map_args: &[hir::Expr<'_>],
18     collect_args: &[hir::Expr<'_>],
19 ) {
20     if_chain! {
21         // called on Iterator
22         if let [map_expr] = collect_args;
23         if is_trait_method(cx, map_expr, sym::Iterator);
24         // return of collect `Result<(),_>`
25         let collect_ret_ty = cx.typeck_results().expr_ty(expr);
26         if is_type_diagnostic_item(cx, collect_ret_ty, sym::result_type);
27         if let ty::Adt(_, substs) = collect_ret_ty.kind();
28         if let Some(result_t) = substs.types().next();
29         if result_t.is_unit();
30         // get parts for snippet
31         if let [iter, map_fn] = map_args;
32         then {
33             span_lint_and_sugg(
34                 cx,
35                 MAP_COLLECT_RESULT_UNIT,
36                 expr.span,
37                 "`.map().collect()` can be replaced with `.try_for_each()`",
38                 "try this",
39                 format!(
40                     "{}.try_for_each({})",
41                     snippet(cx, iter.span, ".."),
42                     snippet(cx, map_fn.span, "..")
43                 ),
44                 Applicability::MachineApplicable,
45             );
46         }
47     }
48 }