]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/eta_reduction.rs
Auto merge of #3968 - kraai:lint-pass-macros, r=flip1995
[rust.git] / clippy_lints / src / eta_reduction.rs
1 use if_chain::if_chain;
2 use rustc::hir::*;
3 use rustc::lint::{in_external_macro, LateContext, LateLintPass, LintArray, LintContext, LintPass};
4 use rustc::ty::{self, Ty};
5 use rustc::{declare_lint_pass, declare_tool_lint};
6 use rustc_errors::Applicability;
7
8 use crate::utils::{is_adjusted, iter_input_pats, snippet_opt, span_lint_and_then, type_is_unsafe_function};
9
10 declare_clippy_lint! {
11     /// **What it does:** Checks for closures which just call another function where
12     /// the function can be called directly. `unsafe` functions or calls where types
13     /// get adjusted are ignored.
14     ///
15     /// **Why is this bad?** Needlessly creating a closure adds code for no benefit
16     /// and gives the optimizer more work.
17     ///
18     /// **Known problems:** If creating the closure inside the closure has a side-
19     /// effect then moving the closure creation out will change when that side-
20     /// effect runs.
21     /// See rust-lang/rust-clippy#1439 for more details.
22     ///
23     /// **Example:**
24     /// ```rust,ignore
25     /// xs.map(|x| foo(x))
26     /// ```
27     /// where `foo(_)` is a plain function that takes the exact argument type of
28     /// `x`.
29     pub REDUNDANT_CLOSURE,
30     style,
31     "redundant closures, i.e., `|a| foo(a)` (which can be written as just `foo`)"
32 }
33
34 declare_lint_pass!(EtaReduction => [REDUNDANT_CLOSURE]);
35
36 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for EtaReduction {
37     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
38         if in_external_macro(cx.sess(), expr.span) {
39             return;
40         }
41
42         match expr.node {
43             ExprKind::Call(_, ref args) | ExprKind::MethodCall(_, _, ref args) => {
44                 for arg in args {
45                     check_closure(cx, arg)
46                 }
47             },
48             _ => (),
49         }
50     }
51 }
52
53 fn check_closure(cx: &LateContext<'_, '_>, expr: &Expr) {
54     if let ExprKind::Closure(_, ref decl, eid, _, _) = expr.node {
55         let body = cx.tcx.hir().body(eid);
56         let ex = &body.value;
57
58         if_chain!(
59             if let ExprKind::Call(ref caller, ref args) = ex.node;
60
61             // Not the same number of arguments, there is no way the closure is the same as the function return;
62             if args.len() == decl.inputs.len();
63
64             // Are the expression or the arguments type-adjusted? Then we need the closure
65             if !(is_adjusted(cx, ex) || args.iter().any(|arg| is_adjusted(cx, arg)));
66
67             let fn_ty = cx.tables.expr_ty(caller);
68             if !type_is_unsafe_function(cx, fn_ty);
69
70             if compare_inputs(&mut iter_input_pats(decl, body), &mut args.into_iter());
71
72             then {
73                 span_lint_and_then(cx, REDUNDANT_CLOSURE, expr.span, "redundant closure found", |db| {
74                     if let Some(snippet) = snippet_opt(cx, caller.span) {
75                         db.span_suggestion(
76                             expr.span,
77                             "remove closure as shown",
78                             snippet,
79                             Applicability::MachineApplicable,
80                         );
81                     }
82                 });
83             }
84         );
85
86         if_chain!(
87             if let ExprKind::MethodCall(ref path, _, ref args) = ex.node;
88
89             // Not the same number of arguments, there is no way the closure is the same as the function return;
90             if args.len() == decl.inputs.len();
91
92             // Are the expression or the arguments type-adjusted? Then we need the closure
93             if !(is_adjusted(cx, ex) || args.iter().skip(1).any(|arg| is_adjusted(cx, arg)));
94
95             let method_def_id = cx.tables.type_dependent_def_id(ex.hir_id).unwrap();
96             if !type_is_unsafe_function(cx, cx.tcx.type_of(method_def_id));
97
98             if compare_inputs(&mut iter_input_pats(decl, body), &mut args.into_iter());
99
100             if let Some(name) = get_ufcs_type_name(cx, method_def_id, &args[0]);
101
102             then {
103                 span_lint_and_then(cx, REDUNDANT_CLOSURE, expr.span, "redundant closure found", |db| {
104                     db.span_suggestion(
105                         expr.span,
106                         "remove closure as shown",
107                         format!("{}::{}", name, path.ident.name),
108                         Applicability::MachineApplicable,
109                     );
110                 });
111             }
112         );
113     }
114 }
115
116 /// Tries to determine the type for universal function call to be used instead of the closure
117 fn get_ufcs_type_name(
118     cx: &LateContext<'_, '_>,
119     method_def_id: def_id::DefId,
120     self_arg: &Expr,
121 ) -> std::option::Option<String> {
122     let expected_type_of_self = &cx.tcx.fn_sig(method_def_id).inputs_and_output().skip_binder()[0];
123     let actual_type_of_self = &cx.tables.node_type(self_arg.hir_id);
124
125     if let Some(trait_id) = cx.tcx.trait_of_item(method_def_id) {
126         if match_borrow_depth(expected_type_of_self, &actual_type_of_self) {
127             return Some(cx.tcx.def_path_str(trait_id));
128         }
129     }
130
131     cx.tcx.impl_of_method(method_def_id).and_then(|_| {
132         //a type may implicitly implement other type's methods (e.g. Deref)
133         if match_types(expected_type_of_self, &actual_type_of_self) {
134             return Some(get_type_name(cx, &actual_type_of_self));
135         }
136         None
137     })
138 }
139
140 fn match_borrow_depth(lhs: Ty<'_>, rhs: Ty<'_>) -> bool {
141     match (&lhs.sty, &rhs.sty) {
142         (ty::Ref(_, t1, _), ty::Ref(_, t2, _)) => match_borrow_depth(&t1, &t2),
143         (l, r) => match (l, r) {
144             (ty::Ref(_, _, _), _) | (_, ty::Ref(_, _, _)) => false,
145             (_, _) => true,
146         },
147     }
148 }
149
150 fn match_types(lhs: Ty<'_>, rhs: Ty<'_>) -> bool {
151     match (&lhs.sty, &rhs.sty) {
152         (ty::Bool, ty::Bool)
153         | (ty::Char, ty::Char)
154         | (ty::Int(_), ty::Int(_))
155         | (ty::Uint(_), ty::Uint(_))
156         | (ty::Str, ty::Str) => true,
157         (ty::Ref(_, t1, _), ty::Ref(_, t2, _))
158         | (ty::Array(t1, _), ty::Array(t2, _))
159         | (ty::Slice(t1), ty::Slice(t2)) => match_types(t1, t2),
160         (ty::Adt(def1, _), ty::Adt(def2, _)) => def1 == def2,
161         (_, _) => false,
162     }
163 }
164
165 fn get_type_name(cx: &LateContext<'_, '_>, ty: Ty<'_>) -> String {
166     match ty.sty {
167         ty::Adt(t, _) => cx.tcx.def_path_str(t.did),
168         ty::Ref(_, r, _) => get_type_name(cx, &r),
169         _ => ty.to_string(),
170     }
171 }
172
173 fn compare_inputs(closure_inputs: &mut dyn Iterator<Item = &Arg>, call_args: &mut dyn Iterator<Item = &Expr>) -> bool {
174     for (closure_input, function_arg) in closure_inputs.zip(call_args) {
175         if let PatKind::Binding(_, _, ident, _) = closure_input.pat.node {
176             // XXXManishearth Should I be checking the binding mode here?
177             if let ExprKind::Path(QPath::Resolved(None, ref p)) = function_arg.node {
178                 if p.segments.len() != 1 {
179                     // If it's a proper path, it can't be a local variable
180                     return false;
181                 }
182                 if p.segments[0].ident.name != ident.name {
183                     // The two idents should be the same
184                     return false;
185                 }
186             } else {
187                 return false;
188             }
189         } else {
190             return false;
191         }
192     }
193     true
194 }