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