]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/map_identity.rs
Merge commit '4911ab124c481430672a3833b37075e6435ec34d' into clippyup
[rust.git] / clippy_lints / src / map_identity.rs
1 use crate::utils::{
2     is_adjusted, is_type_diagnostic_item, match_path, match_trait_method, match_var, paths, remove_blocks,
3     span_lint_and_sugg,
4 };
5 use if_chain::if_chain;
6 use rustc_errors::Applicability;
7 use rustc_hir::{Body, Expr, ExprKind, Pat, PatKind, QPath, StmtKind};
8 use rustc_lint::{LateContext, LateLintPass};
9 use rustc_session::{declare_lint_pass, declare_tool_lint};
10 use rustc_span::sym;
11
12 declare_clippy_lint! {
13     /// **What it does:** Checks for instances of `map(f)` where `f` is the identity function.
14     ///
15     /// **Why is this bad?** It can be written more concisely without the call to `map`.
16     ///
17     /// **Known problems:** None.
18     ///
19     /// **Example:**
20     ///
21     /// ```rust
22     /// let x = [1, 2, 3];
23     /// let y: Vec<_> = x.iter().map(|x| x).map(|x| 2*x).collect();
24     /// ```
25     /// Use instead:
26     /// ```rust
27     /// let x = [1, 2, 3];
28     /// let y: Vec<_> = x.iter().map(|x| 2*x).collect();
29     /// ```
30     pub MAP_IDENTITY,
31     complexity,
32     "using iterator.map(|x| x)"
33 }
34
35 declare_lint_pass!(MapIdentity => [MAP_IDENTITY]);
36
37 impl<'tcx> LateLintPass<'tcx> for MapIdentity {
38     fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
39         if expr.span.from_expansion() {
40             return;
41         }
42
43         if_chain! {
44             if let Some([caller, func]) = get_map_argument(cx, expr);
45             if is_expr_identity_function(cx, func);
46             then {
47                 span_lint_and_sugg(
48                     cx,
49                     MAP_IDENTITY,
50                     expr.span.trim_start(caller.span).unwrap(),
51                     "unnecessary map of the identity function",
52                     "remove the call to `map`",
53                     String::new(),
54                     Applicability::MachineApplicable
55                 )
56             }
57         }
58     }
59 }
60
61 /// Returns the arguments passed into map() if the expression is a method call to
62 /// map(). Otherwise, returns None.
63 fn get_map_argument<'a>(cx: &LateContext<'_>, expr: &'a Expr<'a>) -> Option<&'a [Expr<'a>]> {
64     if_chain! {
65         if let ExprKind::MethodCall(ref method, _, ref args, _) = expr.kind;
66         if args.len() == 2 && method.ident.as_str() == "map";
67         let caller_ty = cx.typeck_results().expr_ty(&args[0]);
68         if match_trait_method(cx, expr, &paths::ITERATOR)
69             || is_type_diagnostic_item(cx, caller_ty, sym::result_type)
70             || is_type_diagnostic_item(cx, caller_ty, sym::option_type);
71         then {
72             Some(args)
73         } else {
74             None
75         }
76     }
77 }
78
79 /// Checks if an expression represents the identity function
80 /// Only examines closures and `std::convert::identity`
81 fn is_expr_identity_function(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
82     match expr.kind {
83         ExprKind::Closure(_, _, body_id, _, _) => is_body_identity_function(cx, cx.tcx.hir().body(body_id)),
84         ExprKind::Path(QPath::Resolved(_, ref path)) => match_path(path, &paths::STD_CONVERT_IDENTITY),
85         _ => false,
86     }
87 }
88
89 /// Checks if a function's body represents the identity function
90 /// Looks for bodies of the form `|x| x`, `|x| return x`, `|x| { return x }` or `|x| {
91 /// return x; }`
92 fn is_body_identity_function(cx: &LateContext<'_>, func: &Body<'_>) -> bool {
93     let params = func.params;
94     let body = remove_blocks(&func.value);
95
96     // if there's less/more than one parameter, then it is not the identity function
97     if params.len() != 1 {
98         return false;
99     }
100
101     match body.kind {
102         ExprKind::Path(QPath::Resolved(None, _)) => match_expr_param(cx, body, params[0].pat),
103         ExprKind::Ret(Some(ref ret_val)) => match_expr_param(cx, ret_val, params[0].pat),
104         ExprKind::Block(ref block, _) => {
105             if_chain! {
106                 if block.stmts.len() == 1;
107                 if let StmtKind::Semi(ref expr) | StmtKind::Expr(ref expr) = block.stmts[0].kind;
108                 if let ExprKind::Ret(Some(ref ret_val)) = expr.kind;
109                 then {
110                     match_expr_param(cx, ret_val, params[0].pat)
111                 } else {
112                     false
113                 }
114             }
115         },
116         _ => false,
117     }
118 }
119
120 /// Returns true iff an expression returns the same thing as a parameter's pattern
121 fn match_expr_param(cx: &LateContext<'_>, expr: &Expr<'_>, pat: &Pat<'_>) -> bool {
122     if let PatKind::Binding(_, _, ident, _) = pat.kind {
123         match_var(expr, ident.name) && !(cx.typeck_results().hir_owner == expr.hir_id.owner && is_adjusted(cx, expr))
124     } else {
125         false
126     }
127 }