1 use crate::utils::paths;
2 use crate::utils::{in_macro, iter_input_pats, match_type, method_chain_args, snippet, span_lint_and_then};
3 use if_chain::if_chain;
5 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
6 use rustc::ty::{self, Ty};
7 use rustc::{declare_lint_pass, declare_tool_lint};
8 use rustc_errors::Applicability;
9 use syntax::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 /// let x: Option<&str> = do_stuff();
24 /// x.map(log_err_msg);
25 /// x.map(|msg| log_err_msg(format_msg(msg)))
28 /// The correct use would be:
31 /// let x: Option<&str> = do_stuff();
32 /// if let Some(msg) = x {
35 /// if let Some(msg) = x {
36 /// log_err_msg(format_msg(msg))
39 pub OPTION_MAP_UNIT_FN,
41 "using `option.map(f)`, where f is a function or closure that returns ()"
44 declare_clippy_lint! {
45 /// **What it does:** Checks for usage of `result.map(f)` where f is a function
46 /// or closure that returns the unit type.
48 /// **Why is this bad?** Readability, this can be written more clearly with
49 /// an if let statement
51 /// **Known problems:** None.
56 /// let x: Result<&str, &str> = do_stuff();
57 /// x.map(log_err_msg);
58 /// x.map(|msg| log_err_msg(format_msg(msg)))
61 /// The correct use would be:
64 /// let x: Result<&str, &str> = do_stuff();
65 /// if let Ok(msg) = x {
68 /// if let Ok(msg) = x {
69 /// log_err_msg(format_msg(msg))
72 pub RESULT_MAP_UNIT_FN,
74 "using `result.map(f)`, where f is a function or closure that returns ()"
77 declare_lint_pass!(MapUnit => [OPTION_MAP_UNIT_FN, RESULT_MAP_UNIT_FN]);
79 fn is_unit_type(ty: Ty<'_>) -> bool {
81 ty::Tuple(slice) => slice.is_empty(),
87 fn is_unit_function(cx: &LateContext<'_, '_>, expr: &hir::Expr) -> bool {
88 let ty = cx.tables.expr_ty(expr);
90 if let ty::FnDef(id, _) = ty.sty {
91 if let Some(fn_type) = cx.tcx.fn_sig(id).no_bound_vars() {
92 return is_unit_type(fn_type.output());
98 fn is_unit_expression(cx: &LateContext<'_, '_>, expr: &hir::Expr) -> bool {
99 is_unit_type(cx.tables.expr_ty(expr))
102 /// The expression inside a closure may or may not have surrounding braces and
103 /// semicolons, which causes problems when generating a suggestion. Given an
104 /// expression that evaluates to '()' or '!', recursively remove useless braces
105 /// and semi-colons until is suitable for including in the suggestion template
106 fn reduce_unit_expression<'a>(cx: &LateContext<'_, '_>, expr: &'a hir::Expr) -> Option<Span> {
107 if !is_unit_expression(cx, expr) {
112 hir::ExprKind::Call(_, _) | hir::ExprKind::MethodCall(_, _, _) => {
113 // Calls can't be reduced any more
116 hir::ExprKind::Block(ref block, _) => {
117 match (&block.stmts[..], block.expr.as_ref()) {
118 (&[], Some(inner_expr)) => {
119 // If block only contains an expression,
120 // reduce `{ X }` to `X`
121 reduce_unit_expression(cx, inner_expr)
123 (&[ref inner_stmt], None) => {
124 // If block only contains statements,
125 // reduce `{ X; }` to `X` or `X;`
126 match inner_stmt.node {
127 hir::StmtKind::Local(ref local) => Some(local.span),
128 hir::StmtKind::Expr(ref e) => Some(e.span),
129 hir::StmtKind::Semi(..) => Some(inner_stmt.span),
130 hir::StmtKind::Item(..) => None,
134 // For closures that contain multiple statements
135 // it's difficult to get a correct suggestion span
136 // for all cases (multi-line closures specifically)
138 // We do not attempt to build a suggestion for those right now.
147 fn unit_closure<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'a hir::Expr) -> Option<(&'tcx hir::Arg, &'a hir::Expr)> {
148 if let hir::ExprKind::Closure(_, ref decl, inner_expr_id, _, _) = expr.node {
149 let body = cx.tcx.hir().body(inner_expr_id);
150 let body_expr = &body.value;
153 if decl.inputs.len() == 1;
154 if is_unit_expression(cx, body_expr);
155 if let Some(binding) = iter_input_pats(&decl, body).next();
157 return Some((binding, body_expr));
164 /// Builds a name for the let binding variable (`var_arg`)
166 /// `x.field` => `x_field`
169 /// Anything else will return `_`.
170 fn let_binding_name(cx: &LateContext<'_, '_>, var_arg: &hir::Expr) -> String {
171 match &var_arg.node {
172 hir::ExprKind::Field(_, _) => snippet(cx, var_arg.span, "_").replace(".", "_"),
173 hir::ExprKind::Path(_) => format!("_{}", snippet(cx, var_arg.span, "")),
174 _ => "_".to_string(),
178 fn suggestion_msg(function_type: &str, map_type: &str) -> String {
180 "called `map(f)` on an {0} value where `f` is a unit {1}",
181 map_type, function_type
185 fn lint_map_unit_fn(cx: &LateContext<'_, '_>, stmt: &hir::Stmt, expr: &hir::Expr, map_args: &[hir::Expr]) {
186 let var_arg = &map_args[0];
188 let (map_type, variant, lint) = if match_type(cx, cx.tables.expr_ty(var_arg), &paths::OPTION) {
189 ("Option", "Some", OPTION_MAP_UNIT_FN)
190 } else if match_type(cx, cx.tables.expr_ty(var_arg), &paths::RESULT) {
191 ("Result", "Ok", RESULT_MAP_UNIT_FN)
195 let fn_arg = &map_args[1];
197 if is_unit_function(cx, fn_arg) {
198 let msg = suggestion_msg("function", map_type);
199 let suggestion = format!(
200 "if let {0}({1}) = {2} {{ {3}(...) }}",
202 let_binding_name(cx, var_arg),
203 snippet(cx, var_arg.span, "_"),
204 snippet(cx, fn_arg.span, "_")
207 span_lint_and_then(cx, lint, expr.span, &msg, |db| {
208 db.span_suggestion(stmt.span, "try this", suggestion, Applicability::Unspecified);
210 } else if let Some((binding, closure_expr)) = unit_closure(cx, fn_arg) {
211 let msg = suggestion_msg("closure", map_type);
213 span_lint_and_then(cx, lint, expr.span, &msg, |db| {
214 if let Some(reduced_expr_span) = reduce_unit_expression(cx, closure_expr) {
215 let suggestion = format!(
216 "if let {0}({1}) = {2} {{ {3} }}",
218 snippet(cx, binding.pat.span, "_"),
219 snippet(cx, var_arg.span, "_"),
220 snippet(cx, reduced_expr_span, "_")
226 Applicability::MachineApplicable, // snippet
229 let suggestion = format!(
230 "if let {0}({1}) = {2} {{ ... }}",
232 snippet(cx, binding.pat.span, "_"),
233 snippet(cx, var_arg.span, "_")
235 db.span_suggestion(stmt.span, "try this", suggestion, Applicability::Unspecified);
241 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MapUnit {
242 fn check_stmt(&mut self, cx: &LateContext<'_, '_>, stmt: &hir::Stmt) {
243 if in_macro(stmt.span) {
247 if let hir::StmtKind::Semi(ref expr) = stmt.node {
248 if let Some(arglists) = method_chain_args(expr, &["map"]) {
249 lint_map_unit_fn(cx, stmt, expr, arglists[0]);