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