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;
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;
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 `()`.
15 /// **Why is this bad?** Readability, this can be written more clearly with
16 /// an if let statement
18 /// **Known problems:** None.
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)));
32 /// The correct use would be:
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 {
43 /// # let x: Option<String> = do_stuff();
44 /// if let Some(msg) = x {
45 /// log_err_msg(format_msg(msg));
48 pub OPTION_MAP_UNIT_FN,
50 "using `option.map(f)`, where `f` is a function or closure that returns `()`"
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 `()`.
57 /// **Why is this bad?** Readability, this can be written more clearly with
58 /// an if let statement
60 /// **Known problems:** None.
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)));
74 /// The correct use would be:
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 {
84 /// # let x: Result<String, String> = do_stuff();
85 /// if let Ok(msg) = x {
86 /// log_err_msg(format_msg(msg));
89 pub RESULT_MAP_UNIT_FN,
91 "using `result.map(f)`, where `f` is a function or closure that returns `()`"
94 declare_lint_pass!(MapUnit => [OPTION_MAP_UNIT_FN, RESULT_MAP_UNIT_FN]);
96 fn is_unit_type(ty: Ty<'_>) -> bool {
98 ty::Tuple(slice) => slice.is_empty(),
104 fn is_unit_function(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> bool {
105 let ty = cx.typeck_results().expr_ty(expr);
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());
115 fn is_unit_expression(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> bool {
116 is_unit_type(cx.typeck_results().expr_ty(expr))
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) {
129 hir::ExprKind::Call(_, _) | hir::ExprKind::MethodCall(_, _, _, _) => {
130 // Calls can't be reduced any more
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)
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,
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)
155 // We do not attempt to build a suggestion for those right now.
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;
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();
177 return Some((binding, body_expr));
184 /// Builds a name for the let binding variable (`var_arg`)
186 /// `x.field` => `x_field`
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(),
199 fn suggestion_msg(function_type: &str, map_type: &str) -> String {
201 "called `map(f)` on an `{0}` value where `f` is a {1} that returns the unit type `()`",
202 map_type, function_type
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];
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)
217 let fn_arg = &map_args[1];
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}) }}",
224 snippet(cx, var_arg.span, "_"),
225 snippet(cx, fn_arg.span, "_"),
226 binding = let_binding_name(cx, var_arg)
229 span_lint_and_then(cx, lint, expr.span, &msg, |diag| {
230 diag.span_suggestion(stmt.span, "try this", suggestion, Applicability::MachineApplicable);
232 } else if let Some((binding, closure_expr)) = unit_closure(cx, fn_arg) {
233 let msg = suggestion_msg("closure", map_type);
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} }}",
240 snippet(cx, binding.pat.span, "_"),
241 snippet(cx, var_arg.span, "_"),
242 snippet(cx, reduced_expr_span, "_")
244 diag.span_suggestion(
248 Applicability::MachineApplicable, // snippet
251 let suggestion = format!(
252 "if let {0}({1}) = {2} {{ ... }}",
254 snippet(cx, binding.pat.span, "_"),
255 snippet(cx, var_arg.span, "_"),
257 diag.span_suggestion(stmt.span, "try this", suggestion, Applicability::HasPlaceholders);
263 impl<'tcx> LateLintPass<'tcx> for MapUnit {
264 fn check_stmt(&mut self, cx: &LateContext<'_>, stmt: &hir::Stmt<'_>) {
265 if stmt.span.from_expansion() {
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]);