]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/map_unit_fn.rs
Adapt codebase to the tool_lints
[rust.git] / clippy_lints / src / map_unit_fn.rs
1 use rustc::hir;
2 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
3 use rustc::{declare_tool_lint, lint_array};
4 use if_chain::if_chain;
5 use rustc::ty;
6 use rustc_errors::Applicability;
7 use syntax::source_map::Span;
8 use crate::utils::{in_macro, iter_input_pats, match_type, method_chain_args, snippet, span_lint_and_then};
9 use crate::utils::paths;
10
11 #[derive(Clone)]
12 pub struct Pass;
13
14 /// **What it does:** Checks for usage of `option.map(f)` where f is a function
15 /// or closure that returns the unit type.
16 ///
17 /// **Why is this bad?** Readability, this can be written more clearly with
18 /// an if let statement
19 ///
20 /// **Known problems:** None.
21 ///
22 /// **Example:**
23 ///
24 /// ```rust
25 /// let x: Option<&str> = do_stuff();
26 /// x.map(log_err_msg);
27 /// x.map(|msg| log_err_msg(format_msg(msg)))
28 /// ```
29 ///
30 /// The correct use would be:
31 ///
32 /// ```rust
33 /// let x: Option<&str> = do_stuff();
34 /// if let Some(msg) = x {
35 ///     log_err_msg(msg)
36 /// }
37 /// if let Some(msg) = x {
38 ///     log_err_msg(format_msg(msg))
39 /// }
40 /// ```
41 declare_clippy_lint! {
42     pub OPTION_MAP_UNIT_FN,
43     complexity,
44     "using `option.map(f)`, where f is a function or closure that returns ()"
45 }
46
47 /// **What it does:** Checks for usage of `result.map(f)` where f is a function
48 /// or closure that returns the unit type.
49 ///
50 /// **Why is this bad?** Readability, this can be written more clearly with
51 /// an if let statement
52 ///
53 /// **Known problems:** None.
54 ///
55 /// **Example:**
56 ///
57 /// ```rust
58 /// let x: Result<&str, &str> = do_stuff();
59 /// x.map(log_err_msg);
60 /// x.map(|msg| log_err_msg(format_msg(msg)))
61 /// ```
62 ///
63 /// The correct use would be:
64 ///
65 /// ```rust
66 /// let x: Result<&str, &str> = do_stuff();
67 /// if let Ok(msg) = x {
68 ///     log_err_msg(msg)
69 /// }
70 /// if let Ok(msg) = x {
71 ///     log_err_msg(format_msg(msg))
72 /// }
73 /// ```
74 declare_clippy_lint! {
75     pub RESULT_MAP_UNIT_FN,
76     complexity,
77     "using `result.map(f)`, where f is a function or closure that returns ()"
78 }
79
80
81 impl LintPass for Pass {
82     fn get_lints(&self) -> LintArray {
83         lint_array!(OPTION_MAP_UNIT_FN, RESULT_MAP_UNIT_FN)
84     }
85 }
86
87 fn is_unit_type(ty: ty::Ty<'_>) -> bool {
88     match ty.sty {
89         ty::Tuple(slice) => slice.is_empty(),
90         ty::Never => true,
91         _ => false,
92     }
93 }
94
95 fn is_unit_function(cx: &LateContext<'_, '_>, expr: &hir::Expr) -> bool {
96     let ty = cx.tables.expr_ty(expr);
97
98     if let ty::FnDef(id, _) = ty.sty {
99         if let Some(fn_type) = cx.tcx.fn_sig(id).no_late_bound_regions() {
100             return is_unit_type(fn_type.output());
101         }
102     }
103     false
104 }
105
106 fn is_unit_expression(cx: &LateContext<'_, '_>, expr: &hir::Expr) -> bool {
107     is_unit_type(cx.tables.expr_ty(expr))
108 }
109
110 /// The expression inside a closure may or may not have surrounding braces and
111 /// semicolons, which causes problems when generating a suggestion. Given an
112 /// expression that evaluates to '()' or '!', recursively remove useless braces
113 /// and semi-colons until is suitable for including in the suggestion template
114 fn reduce_unit_expression<'a>(cx: &LateContext<'_, '_>, expr: &'a hir::Expr) -> Option<Span> {
115     if !is_unit_expression(cx, expr) {
116         return None;
117     }
118
119     match expr.node {
120         hir::ExprKind::Call(_, _) |
121         hir::ExprKind::MethodCall(_, _, _) => {
122             // Calls can't be reduced any more
123             Some(expr.span)
124         },
125         hir::ExprKind::Block(ref block, _) => {
126             match (&block.stmts[..], block.expr.as_ref()) {
127                 (&[], Some(inner_expr)) => {
128                     // If block only contains an expression,
129                     // reduce `{ X }` to `X`
130                     reduce_unit_expression(cx, inner_expr)
131                 },
132                 (&[ref inner_stmt], None) => {
133                     // If block only contains statements,
134                     // reduce `{ X; }` to `X` or `X;`
135                     match inner_stmt.node {
136                         hir::StmtKind::Decl(ref d, _) => Some(d.span),
137                         hir::StmtKind::Expr(ref e, _) => Some(e.span),
138                         hir::StmtKind::Semi(_, _) => Some(inner_stmt.span),
139                     }
140                 },
141                 _ => {
142                     // For closures that contain multiple statements
143                     // it's difficult to get a correct suggestion span
144                     // for all cases (multi-line closures specifically)
145                     //
146                     // We do not attempt to build a suggestion for those right now.
147                     None
148                 }
149             }
150         },
151         _ => None,
152     }
153 }
154
155 fn unit_closure<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'a hir::Expr) -> Option<(&'tcx hir::Arg, &'a hir::Expr)> {
156     if let hir::ExprKind::Closure(_, ref decl, inner_expr_id, _, _) = expr.node {
157         let body = cx.tcx.hir.body(inner_expr_id);
158         let body_expr = &body.value;
159
160         if_chain! {
161             if decl.inputs.len() == 1;
162             if is_unit_expression(cx, body_expr);
163             if let Some(binding) = iter_input_pats(&decl, body).next();
164             then {
165                 return Some((binding, body_expr));
166             }
167         }
168     }
169     None
170 }
171
172 /// Builds a name for the let binding variable (var_arg)
173 ///
174 /// `x.field` => `x_field`
175 /// `y` => `_y`
176 ///
177 /// Anything else will return `_`.
178 fn let_binding_name(cx: &LateContext<'_, '_>, var_arg: &hir::Expr) -> String {
179     match &var_arg.node {
180         hir::ExprKind::Field(_, _) => snippet(cx, var_arg.span, "_").replace(".", "_"),
181         hir::ExprKind::Path(_) => format!("_{}", snippet(cx, var_arg.span, "")),
182         _ => "_".to_string()
183     }
184 }
185
186 fn suggestion_msg(function_type: &str, map_type: &str) -> String {
187     format!(
188         "called `map(f)` on an {0} value where `f` is a unit {1}",
189         map_type,
190         function_type
191     )
192 }
193
194 fn lint_map_unit_fn(cx: &LateContext<'_, '_>, stmt: &hir::Stmt, expr: &hir::Expr, map_args: &[hir::Expr]) {
195     let var_arg = &map_args[0];
196     let fn_arg = &map_args[1];
197
198     let (map_type, variant, lint) =
199         if match_type(cx, cx.tables.expr_ty(var_arg), &paths::OPTION) {
200             ("Option", "Some", OPTION_MAP_UNIT_FN)
201         } else if match_type(cx, cx.tables.expr_ty(var_arg), &paths::RESULT) {
202             ("Result", "Ok", RESULT_MAP_UNIT_FN)
203         } else {
204             return
205         };
206
207     if is_unit_function(cx, fn_arg) {
208         let msg = suggestion_msg("function", map_type);
209         let suggestion = format!("if let {0}({1}) = {2} {{ {3}(...) }}",
210                                  variant,
211                                  let_binding_name(cx, var_arg),
212                                  snippet(cx, var_arg.span, "_"),
213                                  snippet(cx, fn_arg.span, "_"));
214
215         span_lint_and_then(cx, lint, expr.span, &msg, |db| {
216             db.span_suggestion_with_applicability(stmt.span,
217                                                   "try this",
218                                                   suggestion,
219                                                   Applicability::Unspecified);
220         });
221     } else if let Some((binding, closure_expr)) = unit_closure(cx, fn_arg) {
222         let msg = suggestion_msg("closure", map_type);
223
224         span_lint_and_then(cx, lint, expr.span, &msg, |db| {
225             if let Some(reduced_expr_span) = reduce_unit_expression(cx, closure_expr) {
226                 let suggestion = format!("if let {0}({1}) = {2} {{ {3} }}",
227                                          variant,
228                                          snippet(cx, binding.pat.span, "_"),
229                                          snippet(cx, var_arg.span, "_"),
230                                          snippet(cx, reduced_expr_span, "_"));
231                 db.span_suggestion(stmt.span, "try this", suggestion);
232             } else {
233                 let suggestion = format!("if let {0}({1}) = {2} {{ ... }}",
234                                          variant,
235                                          snippet(cx, binding.pat.span, "_"),
236                                          snippet(cx, var_arg.span, "_"));
237                 db.span_suggestion_with_applicability(stmt.span,
238                                                       "try this",
239                                                       suggestion,
240                                                       Applicability::Unspecified);
241             }
242         });
243     }
244 }
245
246 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
247     fn check_stmt(&mut self, cx: &LateContext<'_, '_>, stmt: &hir::Stmt) {
248         if in_macro(stmt.span) {
249             return;
250         }
251
252         if let hir::StmtKind::Semi(ref expr, _) = stmt.node {
253             if let hir::ExprKind::MethodCall(_, _, _) = expr.node {
254                 if let Some(arglists) = method_chain_args(expr, &["map"]) {
255                     lint_map_unit_fn(cx, stmt, expr, arglists[0]);
256                 }
257             }
258         }
259     }
260 }