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