]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/methods/map_collect_result_unit.rs
Merge commit 'fdb84cbfd25908df5683f8f62388f663d9260e39' into clippyup
[rust.git] / src / tools / clippy / 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     iter: &hir::Expr<'_>,
18     map_fn: &hir::Expr<'_>,
19     collect_recv: &hir::Expr<'_>,
20 ) {
21     if_chain! {
22         // called on Iterator
23         if is_trait_method(cx, collect_recv, 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);
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         then {
32             span_lint_and_sugg(
33                 cx,
34                 MAP_COLLECT_RESULT_UNIT,
35                 expr.span,
36                 "`.map().collect()` can be replaced with `.try_for_each()`",
37                 "try this",
38                 format!(
39                     "{}.try_for_each({})",
40                     snippet(cx, iter.span, ".."),
41                     snippet(cx, map_fn.span, "..")
42                 ),
43                 Applicability::MachineApplicable,
44             );
45         }
46     }
47 }