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