1 use crate::utils::{is_adjusted, iter_input_pats, snippet_opt, span_lint_and_then, type_is_unsafe_function};
2 use if_chain::if_chain;
4 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
6 use rustc::{declare_tool_lint, lint_array};
7 use rustc_errors::Applicability;
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.
15 /// **Why is this bad?** Needlessly creating a closure adds code for no benefit
16 /// and gives the optimizer more work.
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-
21 /// See https://github.com/rust-lang/rust-clippy/issues/1439 for more
26 /// xs.map(|x| foo(x))
28 /// where `foo(_)` is a plain function that takes the exact argument type of
30 declare_clippy_lint! {
31 pub REDUNDANT_CLOSURE,
33 "redundant closures, i.e. `|a| foo(a)` (which can be written as just `foo`)"
36 impl LintPass for EtaPass {
37 fn get_lints(&self) -> LintArray {
38 lint_array!(REDUNDANT_CLOSURE)
41 fn name(&self) -> &'static str {
46 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for EtaPass {
47 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
49 ExprKind::Call(_, ref args) | ExprKind::MethodCall(_, _, ref args) => {
51 check_closure(cx, arg)
59 fn check_closure(cx: &LateContext<'_, '_>, expr: &Expr) {
60 if let ExprKind::Closure(_, ref decl, eid, _, _) = expr.node {
61 let body = cx.tcx.hir().body(eid);
65 if let ExprKind::Call(ref caller, ref args) = ex.node;
67 // Not the same number of arguments, there is no way the closure is the same as the function return;
68 if args.len() == decl.inputs.len();
70 // Are the expression or the arguments type-adjusted? Then we need the closure
71 if !(is_adjusted(cx, ex) || args.iter().any(|arg| is_adjusted(cx, arg)));
73 let fn_ty = cx.tables.expr_ty(caller);
74 if !type_is_unsafe_function(cx, fn_ty);
76 if compare_inputs(&mut iter_input_pats(decl, body), &mut args.into_iter());
79 span_lint_and_then(cx, REDUNDANT_CLOSURE, expr.span, "redundant closure found", |db| {
80 if let Some(snippet) = snippet_opt(cx, caller.span) {
83 "remove closure as shown",
85 Applicability::MachineApplicable,
93 if let ExprKind::MethodCall(ref path, _, ref args) = ex.node;
95 // Not the same number of arguments, there is no way the closure is the same as the function return;
96 if args.len() == decl.inputs.len();
98 // Are the expression or the arguments type-adjusted? Then we need the closure
99 if !(is_adjusted(cx, ex) || args.iter().skip(1).any(|arg| is_adjusted(cx, arg)));
101 let method_def_id = cx.tables.type_dependent_defs()[ex.hir_id].def_id();
102 if !type_is_unsafe_function(cx, cx.tcx.type_of(method_def_id));
104 if compare_inputs(&mut iter_input_pats(decl, body), &mut args.into_iter());
106 if let Some(name) = get_ufcs_type_name(cx, method_def_id, &args[0]);
109 span_lint_and_then(cx, REDUNDANT_CLOSURE, expr.span, "redundant closure found", |db| {
112 "remove closure as shown",
113 format!("{}::{}", name, path.ident.name),
114 Applicability::MachineApplicable,
122 /// Tries to determine the type for universal function call to be used instead of the closure
123 fn get_ufcs_type_name(
124 cx: &LateContext<'_, '_>,
125 method_def_id: def_id::DefId,
127 ) -> std::option::Option<String> {
128 let expected_type_of_self = &cx.tcx.fn_sig(method_def_id).inputs_and_output().skip_binder()[0].sty;
129 let actual_type_of_self = &cx.tables.node_id_to_type(self_arg.hir_id).sty;
131 if let Some(trait_id) = cx.tcx.trait_of_item(method_def_id) {
132 //if the method expectes &self, ufcs requires explicit borrowing so closure can't be removed
133 return match (expected_type_of_self, actual_type_of_self) {
134 (ty::Ref(_, _, _), ty::Ref(_, _, _)) => Some(cx.tcx.item_path_str(trait_id)),
135 (l, r) => match (l, r) {
136 (ty::Ref(_, _, _), _) | (_, ty::Ref(_, _, _)) => None,
137 (_, _) => Some(cx.tcx.item_path_str(trait_id)),
142 cx.tcx.impl_of_method(method_def_id).and_then(|_| {
143 //a type may implicitly implement other types methods (e.g. Deref)
144 if match_types(expected_type_of_self, actual_type_of_self) {
145 return Some(get_type_name(cx, &actual_type_of_self));
151 fn match_types(lhs: &ty::TyKind<'_>, rhs: &ty::TyKind<'_>) -> bool {
154 | (ty::Char, ty::Char)
155 | (ty::Int(_), ty::Int(_))
156 | (ty::Uint(_), ty::Uint(_))
157 | (ty::Str, ty::Str) => true,
158 (ty::Ref(_, t1, _), ty::Ref(_, t2, _))
159 | (ty::Array(t1, _), ty::Array(t2, _))
160 | (ty::Slice(t1), ty::Slice(t2)) => match_types(&t1.sty, &t2.sty),
161 (ty::Adt(def1, _), ty::Adt(def2, _)) => def1 == def2,
166 fn get_type_name(cx: &LateContext<'_, '_>, kind: &ty::TyKind<'_>) -> String {
168 ty::Adt(t, _) => cx.tcx.item_path_str(t.did),
169 ty::Ref(_, r, _) => get_type_name(cx, &r.sty),
170 _ => kind.to_string(),
174 fn compare_inputs(closure_inputs: &mut dyn Iterator<Item = &Arg>, call_args: &mut dyn Iterator<Item = &Expr>) -> bool {
175 for (closure_input, function_arg) in closure_inputs.zip(call_args) {
176 if let PatKind::Binding(_, _, _, ident, _) = closure_input.pat.node {
177 // XXXManishearth Should I be checking the binding mode here?
178 if let ExprKind::Path(QPath::Resolved(None, ref p)) = function_arg.node {
179 if p.segments.len() != 1 {
180 // If it's a proper path, it can't be a local variable
183 if p.segments[0].ident.name != ident.name {
184 // The two idents should be the same