]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/map_unit_fn.rs
fix new lint error
[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 use rustc_span::sym;
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.kind() {
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.typeck_results().expr_ty(expr);
106
107     if let ty::FnDef(id, _) = *ty.kind() {
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.typeck_results().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.kind {
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.kind {
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<'tcx>(
165     cx: &LateContext<'tcx>,
166     expr: &hir::Expr<'_>,
167 ) -> Option<(&'tcx hir::Param<'tcx>, &'tcx hir::Expr<'tcx>)> {
168     if let hir::ExprKind::Closure(_, ref decl, inner_expr_id, _, _) = expr.kind {
169         let body = cx.tcx.hir().body(inner_expr_id);
170         let body_expr = &body.value;
171
172         if_chain! {
173             if decl.inputs.len() == 1;
174             if is_unit_expression(cx, body_expr);
175             if let Some(binding) = iter_input_pats(&decl, body).next();
176             then {
177                 return Some((binding, body_expr));
178             }
179         }
180     }
181     None
182 }
183
184 /// Builds a name for the let binding variable (`var_arg`)
185 ///
186 /// `x.field` => `x_field`
187 /// `y` => `_y`
188 ///
189 /// Anything else will return `a`.
190 fn let_binding_name(cx: &LateContext<'_>, var_arg: &hir::Expr<'_>) -> String {
191     match &var_arg.kind {
192         hir::ExprKind::Field(_, _) => snippet(cx, var_arg.span, "_").replace(".", "_"),
193         hir::ExprKind::Path(_) => format!("_{}", snippet(cx, var_arg.span, "")),
194         _ => "a".to_string(),
195     }
196 }
197
198 #[must_use]
199 fn suggestion_msg(function_type: &str, map_type: &str) -> String {
200     format!(
201         "called `map(f)` on an `{0}` value where `f` is a {1} that returns the unit type `()`",
202         map_type, function_type
203     )
204 }
205
206 fn lint_map_unit_fn(cx: &LateContext<'_>, stmt: &hir::Stmt<'_>, expr: &hir::Expr<'_>, map_args: &[hir::Expr<'_>]) {
207     let var_arg = &map_args[0];
208
209     let (map_type, variant, lint) =
210         if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(var_arg), sym::option_type) {
211             ("Option", "Some", OPTION_MAP_UNIT_FN)
212         } else if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(var_arg), sym::result_type) {
213             ("Result", "Ok", RESULT_MAP_UNIT_FN)
214         } else {
215             return;
216         };
217     let fn_arg = &map_args[1];
218
219     if is_unit_function(cx, fn_arg) {
220         let msg = suggestion_msg("function", map_type);
221         let suggestion = format!(
222             "if let {0}({binding}) = {1} {{ {2}({binding}) }}",
223             variant,
224             snippet(cx, var_arg.span, "_"),
225             snippet(cx, fn_arg.span, "_"),
226             binding = let_binding_name(cx, var_arg)
227         );
228
229         span_lint_and_then(cx, lint, expr.span, &msg, |diag| {
230             diag.span_suggestion(stmt.span, "try this", suggestion, Applicability::MachineApplicable);
231         });
232     } else if let Some((binding, closure_expr)) = unit_closure(cx, fn_arg) {
233         let msg = suggestion_msg("closure", map_type);
234
235         span_lint_and_then(cx, lint, expr.span, &msg, |diag| {
236             if let Some(reduced_expr_span) = reduce_unit_expression(cx, closure_expr) {
237                 let suggestion = format!(
238                     "if let {0}({1}) = {2} {{ {3} }}",
239                     variant,
240                     snippet(cx, binding.pat.span, "_"),
241                     snippet(cx, var_arg.span, "_"),
242                     snippet(cx, reduced_expr_span, "_")
243                 );
244                 diag.span_suggestion(
245                     stmt.span,
246                     "try this",
247                     suggestion,
248                     Applicability::MachineApplicable, // snippet
249                 );
250             } else {
251                 let suggestion = format!(
252                     "if let {0}({1}) = {2} {{ ... }}",
253                     variant,
254                     snippet(cx, binding.pat.span, "_"),
255                     snippet(cx, var_arg.span, "_"),
256                 );
257                 diag.span_suggestion(stmt.span, "try this", suggestion, Applicability::HasPlaceholders);
258             }
259         });
260     }
261 }
262
263 impl<'tcx> LateLintPass<'tcx> for MapUnit {
264     fn check_stmt(&mut self, cx: &LateContext<'_>, stmt: &hir::Stmt<'_>) {
265         if stmt.span.from_expansion() {
266             return;
267         }
268
269         if let hir::StmtKind::Semi(ref expr) = stmt.kind {
270             if let Some(arglists) = method_chain_args(expr, &["map"]) {
271                 lint_map_unit_fn(cx, stmt, expr, arglists[0]);
272             }
273         }
274     }
275 }