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