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