rustc_lint/
map_unit_fn.rs

1use rustc_hir::{Expr, ExprKind, HirId, Stmt, StmtKind};
2use rustc_middle::ty::{self, Ty};
3use rustc_session::{declare_lint, declare_lint_pass};
4
5use crate::lints::MappingToUnit;
6use crate::{LateContext, LateLintPass, LintContext};
7
8declare_lint! {
9    /// The `map_unit_fn` lint checks for `Iterator::map` receive
10    /// a callable that returns `()`.
11    ///
12    /// ### Example
13    ///
14    /// ```rust
15    /// fn foo(items: &mut Vec<u8>) {
16    ///     items.sort();
17    /// }
18    ///
19    /// fn main() {
20    ///     let mut x: Vec<Vec<u8>> = vec![
21    ///         vec![0, 2, 1],
22    ///         vec![5, 4, 3],
23    ///     ];
24    ///     x.iter_mut().map(foo);
25    /// }
26    /// ```
27    ///
28    /// {{produces}}
29    ///
30    /// ### Explanation
31    ///
32    /// Mapping to `()` is almost always a mistake.
33    pub MAP_UNIT_FN,
34    Warn,
35    "`Iterator::map` call that discard the iterator's values"
36}
37
38declare_lint_pass!(MapUnitFn => [MAP_UNIT_FN]);
39
40impl<'tcx> LateLintPass<'tcx> for MapUnitFn {
41    fn check_stmt(&mut self, cx: &LateContext<'tcx>, stmt: &Stmt<'_>) {
42        if stmt.span.from_expansion() {
43            return;
44        }
45
46        if let StmtKind::Semi(expr) = stmt.kind
47            && let ExprKind::MethodCall(path, receiver, args, span) = expr.kind
48        {
49            if path.ident.name.as_str() == "map" {
50                if receiver.span.from_expansion()
51                    || args.iter().any(|e| e.span.from_expansion())
52                    || !is_impl_slice(cx, receiver)
53                    || !is_diagnostic_name(cx, expr.hir_id, "IteratorMap")
54                {
55                    return;
56                }
57                let arg_ty = cx.typeck_results().expr_ty(&args[0]);
58                let default_span = args[0].span;
59                if let ty::FnDef(id, _) = arg_ty.kind() {
60                    let fn_ty = cx.tcx.fn_sig(id).skip_binder();
61                    let ret_ty = fn_ty.output().skip_binder();
62                    if is_unit_type(ret_ty) {
63                        cx.emit_span_lint(
64                            MAP_UNIT_FN,
65                            span,
66                            MappingToUnit {
67                                function_label: cx.tcx.span_of_impl(*id).unwrap_or(default_span),
68                                argument_label: args[0].span,
69                                map_label: span,
70                                suggestion: path.ident.span,
71                                replace: "for_each".to_string(),
72                            },
73                        )
74                    }
75                } else if let ty::Closure(id, subs) = arg_ty.kind() {
76                    let cl_ty = subs.as_closure().sig();
77                    let ret_ty = cl_ty.output().skip_binder();
78                    if is_unit_type(ret_ty) {
79                        cx.emit_span_lint(
80                            MAP_UNIT_FN,
81                            span,
82                            MappingToUnit {
83                                function_label: cx.tcx.span_of_impl(*id).unwrap_or(default_span),
84                                argument_label: args[0].span,
85                                map_label: span,
86                                suggestion: path.ident.span,
87                                replace: "for_each".to_string(),
88                            },
89                        )
90                    }
91                }
92            }
93        }
94    }
95}
96
97fn is_impl_slice(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
98    if let Some(method_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id)
99        && let Some(impl_id) = cx.tcx.impl_of_assoc(method_id)
100    {
101        return cx.tcx.type_of(impl_id).skip_binder().is_slice();
102    }
103    false
104}
105
106fn is_unit_type(ty: Ty<'_>) -> bool {
107    ty.is_unit() || ty.is_never()
108}
109
110fn is_diagnostic_name(cx: &LateContext<'_>, id: HirId, name: &str) -> bool {
111    if let Some(def_id) = cx.typeck_results().type_dependent_def_id(id)
112        && let Some(item) = cx.tcx.get_diagnostic_name(def_id)
113    {
114        if item.as_str() == name {
115            return true;
116        }
117    }
118    false
119}