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