1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
10 use crate::rustc::hir;
11 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
13 use crate::rustc::{declare_tool_lint, lint_array};
14 use crate::rustc_errors::Applicability;
15 use crate::syntax::source_map::Span;
16 use crate::utils::paths;
17 use crate::utils::{in_macro, iter_input_pats, match_type, method_chain_args, snippet, span_lint_and_then};
18 use if_chain::if_chain;
23 /// **What it does:** Checks for usage of `option.map(f)` where f is a function
24 /// or closure that returns the unit type.
26 /// **Why is this bad?** Readability, this can be written more clearly with
27 /// an if let statement
29 /// **Known problems:** None.
34 /// let x: Option<&str> = do_stuff();
35 /// x.map(log_err_msg);
36 /// x.map(|msg| log_err_msg(format_msg(msg)))
39 /// The correct use would be:
42 /// let x: Option<&str> = do_stuff();
43 /// if let Some(msg) = x {
46 /// if let Some(msg) = x {
47 /// log_err_msg(format_msg(msg))
50 declare_clippy_lint! {
51 pub OPTION_MAP_UNIT_FN,
53 "using `option.map(f)`, where f is a function or closure that returns ()"
56 /// **What it does:** Checks for usage of `result.map(f)` where f is a function
57 /// or closure that returns the unit type.
59 /// **Why is this bad?** Readability, this can be written more clearly with
60 /// an if let statement
62 /// **Known problems:** None.
67 /// let x: Result<&str, &str> = do_stuff();
68 /// x.map(log_err_msg);
69 /// x.map(|msg| log_err_msg(format_msg(msg)))
72 /// The correct use would be:
75 /// let x: Result<&str, &str> = do_stuff();
76 /// if let Ok(msg) = x {
79 /// if let Ok(msg) = x {
80 /// log_err_msg(format_msg(msg))
83 declare_clippy_lint! {
84 pub RESULT_MAP_UNIT_FN,
86 "using `result.map(f)`, where f is a function or closure that returns ()"
89 impl LintPass for Pass {
90 fn get_lints(&self) -> LintArray {
91 lint_array!(OPTION_MAP_UNIT_FN, RESULT_MAP_UNIT_FN)
95 fn is_unit_type(ty: ty::Ty<'_>) -> bool {
97 ty::Tuple(slice) => slice.is_empty(),
103 fn is_unit_function(cx: &LateContext<'_, '_>, expr: &hir::Expr) -> bool {
104 let ty = cx.tables.expr_ty(expr);
106 if let ty::FnDef(id, _) = ty.sty {
107 if let Some(fn_type) = cx.tcx.fn_sig(id).no_bound_vars() {
108 return is_unit_type(fn_type.output());
114 fn is_unit_expression(cx: &LateContext<'_, '_>, expr: &hir::Expr) -> bool {
115 is_unit_type(cx.tables.expr_ty(expr))
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) {
128 hir::ExprKind::Call(_, _) | hir::ExprKind::MethodCall(_, _, _) => {
129 // Calls can't be reduced any more
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)
139 (&[ref inner_stmt], None) => {
140 // If block only contains statements,
141 // reduce `{ X; }` to `X` or `X;`
142 match inner_stmt.node {
143 hir::StmtKind::Decl(ref d, _) => Some(d.span),
144 hir::StmtKind::Expr(ref e, _) => Some(e.span),
145 hir::StmtKind::Semi(_, _) => Some(inner_stmt.span),
149 // For closures that contain multiple statements
150 // it's difficult to get a correct suggestion span
151 // for all cases (multi-line closures specifically)
153 // We do not attempt to build a suggestion for those right now.
162 fn unit_closure<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'a hir::Expr) -> Option<(&'tcx hir::Arg, &'a hir::Expr)> {
163 if let hir::ExprKind::Closure(_, ref decl, inner_expr_id, _, _) = expr.node {
164 let body = cx.tcx.hir().body(inner_expr_id);
165 let body_expr = &body.value;
168 if decl.inputs.len() == 1;
169 if is_unit_expression(cx, body_expr);
170 if let Some(binding) = iter_input_pats(&decl, body).next();
172 return Some((binding, body_expr));
179 /// Builds a name for the let binding variable (`var_arg`)
181 /// `x.field` => `x_field`
184 /// Anything else will return `_`.
185 fn let_binding_name(cx: &LateContext<'_, '_>, var_arg: &hir::Expr) -> String {
186 match &var_arg.node {
187 hir::ExprKind::Field(_, _) => snippet(cx, var_arg.span, "_").replace(".", "_"),
188 hir::ExprKind::Path(_) => format!("_{}", snippet(cx, var_arg.span, "")),
189 _ => "_".to_string(),
193 fn suggestion_msg(function_type: &str, map_type: &str) -> String {
195 "called `map(f)` on an {0} value where `f` is a unit {1}",
196 map_type, function_type
200 fn lint_map_unit_fn(cx: &LateContext<'_, '_>, stmt: &hir::Stmt, expr: &hir::Expr, map_args: &[hir::Expr]) {
201 let var_arg = &map_args[0];
202 let fn_arg = &map_args[1];
204 let (map_type, variant, lint) = if match_type(cx, cx.tables.expr_ty(var_arg), &paths::OPTION) {
205 ("Option", "Some", OPTION_MAP_UNIT_FN)
206 } else if match_type(cx, cx.tables.expr_ty(var_arg), &paths::RESULT) {
207 ("Result", "Ok", RESULT_MAP_UNIT_FN)
212 if is_unit_function(cx, fn_arg) {
213 let msg = suggestion_msg("function", map_type);
214 let suggestion = format!(
215 "if let {0}({1}) = {2} {{ {3}(...) }}",
217 let_binding_name(cx, var_arg),
218 snippet(cx, var_arg.span, "_"),
219 snippet(cx, fn_arg.span, "_")
222 span_lint_and_then(cx, lint, expr.span, &msg, |db| {
223 db.span_suggestion_with_applicability(stmt.span, "try this", suggestion, Applicability::Unspecified);
225 } else if let Some((binding, closure_expr)) = unit_closure(cx, fn_arg) {
226 let msg = suggestion_msg("closure", map_type);
228 span_lint_and_then(cx, lint, expr.span, &msg, |db| {
229 if let Some(reduced_expr_span) = reduce_unit_expression(cx, closure_expr) {
230 let suggestion = format!(
231 "if let {0}({1}) = {2} {{ {3} }}",
233 snippet(cx, binding.pat.span, "_"),
234 snippet(cx, var_arg.span, "_"),
235 snippet(cx, reduced_expr_span, "_")
237 db.span_suggestion_with_applicability(
241 Applicability::MachineApplicable, // snippet
244 let suggestion = format!(
245 "if let {0}({1}) = {2} {{ ... }}",
247 snippet(cx, binding.pat.span, "_"),
248 snippet(cx, var_arg.span, "_")
250 db.span_suggestion_with_applicability(stmt.span, "try this", suggestion, Applicability::Unspecified);
256 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
257 fn check_stmt(&mut self, cx: &LateContext<'_, '_>, stmt: &hir::Stmt) {
258 if in_macro(stmt.span) {
262 if let hir::StmtKind::Semi(ref expr, _) = stmt.node {
263 if let Some(arglists) = method_chain_args(expr, &["map"]) {
264 lint_map_unit_fn(cx, stmt, expr, arglists[0]);