]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/methods/map_collect_result_unit.rs
Auto merge of #105018 - zertosh:path_buf_deref_mut, r=dtolnay
[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::source::snippet;
3 use clippy_utils::ty::is_type_diagnostic_item;
4 use if_chain::if_chain;
5 use rustc_errors::Applicability;
6 use rustc_hir as hir;
7 use rustc_lint::LateContext;
8 use rustc_middle::ty;
9 use rustc_span::symbol::sym;
10
11 use super::MAP_COLLECT_RESULT_UNIT;
12
13 pub(super) fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>, iter: &hir::Expr<'_>, map_fn: &hir::Expr<'_>) {
14     // return of collect `Result<(),_>`
15     let collect_ret_ty = cx.typeck_results().expr_ty(expr);
16     if_chain! {
17         if is_type_diagnostic_item(cx, collect_ret_ty, sym::Result);
18         if let ty::Adt(_, substs) = collect_ret_ty.kind();
19         if let Some(result_t) = substs.types().next();
20         if result_t.is_unit();
21         // get parts for snippet
22         then {
23             span_lint_and_sugg(
24                 cx,
25                 MAP_COLLECT_RESULT_UNIT,
26                 expr.span,
27                 "`.map().collect()` can be replaced with `.try_for_each()`",
28                 "try this",
29                 format!(
30                     "{}.try_for_each({})",
31                     snippet(cx, iter.span, ".."),
32                     snippet(cx, map_fn.span, "..")
33                 ),
34                 Applicability::MachineApplicable,
35             );
36         }
37     }
38 }