1 use crate::utils::paths;
3 use crate::utils::{in_macro_or_desugar, iter_input_pats, match_type, method_chain_args, snippet, span_lint_and_then};
4 use if_chain::if_chain;
6 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
7 use rustc::ty::{self, Ty};
8 use rustc::{declare_lint_pass, declare_tool_lint};
9 use rustc_errors::Applicability;
10 use syntax::source_map::Span;
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.
16 /// **Why is this bad?** Readability, this can be written more clearly with
17 /// an if let statement
19 /// **Known problems:** None.
24 /// let x: Option<&str> = do_stuff();
25 /// x.map(log_err_msg);
26 /// x.map(|msg| log_err_msg(format_msg(msg)))
29 /// The correct use would be:
32 /// let x: Option<&str> = do_stuff();
33 /// if let Some(msg) = x {
36 /// if let Some(msg) = x {
37 /// log_err_msg(format_msg(msg))
40 pub OPTION_MAP_UNIT_FN,
42 "using `option.map(f)`, where f is a function or closure that returns ()"
45 declare_clippy_lint! {
46 /// **What it does:** Checks for usage of `result.map(f)` where f is a function
47 /// or closure that returns the unit type.
49 /// **Why is this bad?** Readability, this can be written more clearly with
50 /// an if let statement
52 /// **Known problems:** None.
57 /// let x: Result<&str, &str> = do_stuff();
58 /// x.map(log_err_msg);
59 /// x.map(|msg| log_err_msg(format_msg(msg)))
62 /// The correct use would be:
65 /// let x: Result<&str, &str> = do_stuff();
66 /// if let Ok(msg) = x {
69 /// if let Ok(msg) = x {
70 /// log_err_msg(format_msg(msg))
73 pub RESULT_MAP_UNIT_FN,
75 "using `result.map(f)`, where f is a function or closure that returns ()"
78 declare_lint_pass!(MapUnit => [OPTION_MAP_UNIT_FN, RESULT_MAP_UNIT_FN]);
80 fn is_unit_type(ty: Ty<'_>) -> bool {
82 ty::Tuple(slice) => slice.is_empty(),
88 fn is_unit_function(cx: &LateContext<'_, '_>, expr: &hir::Expr) -> bool {
89 let ty = cx.tables.expr_ty(expr);
91 if let ty::FnDef(id, _) = ty.sty {
92 if let Some(fn_type) = cx.tcx.fn_sig(id).no_bound_vars() {
93 return is_unit_type(fn_type.output());
99 fn is_unit_expression(cx: &LateContext<'_, '_>, expr: &hir::Expr) -> bool {
100 is_unit_type(cx.tables.expr_ty(expr))
103 /// The expression inside a closure may or may not have surrounding braces and
104 /// semicolons, which causes problems when generating a suggestion. Given an
105 /// expression that evaluates to '()' or '!', recursively remove useless braces
106 /// and semi-colons until is suitable for including in the suggestion template
107 fn reduce_unit_expression<'a>(cx: &LateContext<'_, '_>, expr: &'a hir::Expr) -> Option<Span> {
108 if !is_unit_expression(cx, expr) {
113 hir::ExprKind::Call(_, _) | hir::ExprKind::MethodCall(_, _, _) => {
114 // Calls can't be reduced any more
117 hir::ExprKind::Block(ref block, _) => {
118 match (&block.stmts[..], block.expr.as_ref()) {
119 (&[], Some(inner_expr)) => {
120 // If block only contains an expression,
121 // reduce `{ X }` to `X`
122 reduce_unit_expression(cx, inner_expr)
124 (&[ref inner_stmt], None) => {
125 // If block only contains statements,
126 // reduce `{ X; }` to `X` or `X;`
127 match inner_stmt.node {
128 hir::StmtKind::Local(ref local) => Some(local.span),
129 hir::StmtKind::Expr(ref e) => Some(e.span),
130 hir::StmtKind::Semi(..) => Some(inner_stmt.span),
131 hir::StmtKind::Item(..) => None,
135 // For closures that contain multiple statements
136 // it's difficult to get a correct suggestion span
137 // for all cases (multi-line closures specifically)
139 // We do not attempt to build a suggestion for those right now.
148 fn unit_closure<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'a hir::Expr) -> Option<(&'tcx hir::Arg, &'a hir::Expr)> {
149 if let hir::ExprKind::Closure(_, ref decl, inner_expr_id, _, _) = expr.node {
150 let body = cx.tcx.hir().body(inner_expr_id);
151 let body_expr = &body.value;
154 if decl.inputs.len() == 1;
155 if is_unit_expression(cx, body_expr);
156 if let Some(binding) = iter_input_pats(&decl, body).next();
158 return Some((binding, body_expr));
165 /// Builds a name for the let binding variable (`var_arg`)
167 /// `x.field` => `x_field`
170 /// Anything else will return `_`.
171 fn let_binding_name(cx: &LateContext<'_, '_>, var_arg: &hir::Expr) -> String {
172 match &var_arg.node {
173 hir::ExprKind::Field(_, _) => snippet(cx, var_arg.span, "_").replace(".", "_"),
174 hir::ExprKind::Path(_) => format!("_{}", snippet(cx, var_arg.span, "")),
175 _ => "_".to_string(),
179 fn suggestion_msg(function_type: &str, map_type: &str) -> String {
181 "called `map(f)` on an {0} value where `f` is a unit {1}",
182 map_type, function_type
186 fn lint_map_unit_fn(cx: &LateContext<'_, '_>, stmt: &hir::Stmt, expr: &hir::Expr, map_args: &[hir::Expr]) {
187 let var_arg = &map_args[0];
189 let (map_type, variant, lint) = if match_type(cx, cx.tables.expr_ty(var_arg), &*paths::OPTION) {
190 ("Option", "Some", OPTION_MAP_UNIT_FN)
191 } else if match_type(cx, cx.tables.expr_ty(var_arg), &*paths::RESULT) {
192 ("Result", "Ok", RESULT_MAP_UNIT_FN)
196 let fn_arg = &map_args[1];
198 if is_unit_function(cx, fn_arg) {
199 let msg = suggestion_msg("function", map_type);
200 let suggestion = format!(
201 "if let {0}({1}) = {2} {{ {3}(...) }}",
203 let_binding_name(cx, var_arg),
204 snippet(cx, var_arg.span, "_"),
205 snippet(cx, fn_arg.span, "_")
208 span_lint_and_then(cx, lint, expr.span, &msg, |db| {
209 db.span_suggestion(stmt.span, "try this", suggestion, Applicability::Unspecified);
211 } else if let Some((binding, closure_expr)) = unit_closure(cx, fn_arg) {
212 let msg = suggestion_msg("closure", map_type);
214 span_lint_and_then(cx, lint, expr.span, &msg, |db| {
215 if let Some(reduced_expr_span) = reduce_unit_expression(cx, closure_expr) {
216 let suggestion = format!(
217 "if let {0}({1}) = {2} {{ {3} }}",
219 snippet(cx, binding.pat.span, "_"),
220 snippet(cx, var_arg.span, "_"),
221 snippet(cx, reduced_expr_span, "_")
227 Applicability::MachineApplicable, // snippet
230 let suggestion = format!(
231 "if let {0}({1}) = {2} {{ ... }}",
233 snippet(cx, binding.pat.span, "_"),
234 snippet(cx, var_arg.span, "_")
236 db.span_suggestion(stmt.span, "try this", suggestion, Applicability::Unspecified);
242 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MapUnit {
243 fn check_stmt(&mut self, cx: &LateContext<'_, '_>, stmt: &hir::Stmt) {
244 if in_macro_or_desugar(stmt.span) {
248 if let hir::StmtKind::Semi(ref expr) = stmt.node {
249 if let Some(arglists) = method_chain_args(expr, &[*sym::map]) {
250 lint_map_unit_fn(cx, stmt, expr, arglists[0]);