4 use rustc_errors::{Applicability};
5 use syntax::codemap::Span;
6 use utils::{in_macro, iter_input_pats, match_type, method_chain_args, snippet, span_lint_and_then};
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 declare_clippy_lint! {
40 pub OPTION_MAP_UNIT_FN,
42 "using `option.map(f)`, where f is a function or closure that returns ()"
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 declare_clippy_lint! {
73 pub RESULT_MAP_UNIT_FN,
75 "using `result.map(f)`, where f is a function or closure that returns ()"
79 impl LintPass for Pass {
80 fn get_lints(&self) -> LintArray {
81 lint_array!(OPTION_MAP_UNIT_FN, RESULT_MAP_UNIT_FN)
85 fn is_unit_type(ty: ty::Ty) -> bool {
87 ty::TyTuple(slice) => slice.is_empty(),
93 fn is_unit_function(cx: &LateContext, expr: &hir::Expr) -> bool {
94 let ty = cx.tables.expr_ty(expr);
96 if let ty::TyFnDef(id, _) = ty.sty {
97 if let Some(fn_type) = cx.tcx.fn_sig(id).no_late_bound_regions() {
98 return is_unit_type(fn_type.output());
104 fn is_unit_expression(cx: &LateContext, expr: &hir::Expr) -> bool {
105 is_unit_type(cx.tables.expr_ty(expr))
108 /// The expression inside a closure may or may not have surrounding braces and
109 /// semicolons, which causes problems when generating a suggestion. Given an
110 /// expression that evaluates to '()' or '!', recursively remove useless braces
111 /// and semi-colons until is suitable for including in the suggestion template
112 fn reduce_unit_expression<'a>(cx: &LateContext, expr: &'a hir::Expr) -> Option<Span> {
113 if !is_unit_expression(cx, expr) {
118 hir::ExprCall(_, _) |
119 hir::ExprMethodCall(_, _, _) => {
120 // Calls can't be reduced any more
123 hir::ExprBlock(ref block, _) => {
124 match (&block.stmts[..], block.expr.as_ref()) {
125 (&[], Some(inner_expr)) => {
126 // If block only contains an expression,
127 // reduce `{ X }` to `X`
128 reduce_unit_expression(cx, inner_expr)
130 (&[ref inner_stmt], None) => {
131 // If block only contains statements,
132 // reduce `{ X; }` to `X` or `X;`
133 match inner_stmt.node {
134 hir::StmtDecl(ref d, _) => Some(d.span),
135 hir::StmtExpr(ref e, _) => Some(e.span),
136 hir::StmtSemi(_, _) => Some(inner_stmt.span),
140 // For closures that contain multiple statements
141 // it's difficult to get a correct suggestion span
142 // for all cases (multi-line closures specifically)
144 // We do not attempt to build a suggestion for those right now.
153 fn unit_closure<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'a hir::Expr) -> Option<(&'tcx hir::Arg, &'a hir::Expr)> {
154 if let hir::ExprClosure(_, ref decl, inner_expr_id, _, _) = expr.node {
155 let body = cx.tcx.hir.body(inner_expr_id);
156 let body_expr = &body.value;
159 if decl.inputs.len() == 1;
160 if is_unit_expression(cx, body_expr);
161 if let Some(binding) = iter_input_pats(&decl, body).next();
163 return Some((binding, body_expr));
170 /// Builds a name for the let binding variable (var_arg)
172 /// `x.field` => `x_field`
175 /// Anything else will return `_`.
176 fn let_binding_name(cx: &LateContext, var_arg: &hir::Expr) -> String {
177 match &var_arg.node {
178 hir::ExprField(_, _) => snippet(cx, var_arg.span, "_").replace(".", "_"),
179 hir::ExprPath(_) => format!("_{}", snippet(cx, var_arg.span, "")),
184 fn suggestion_msg(function_type: &str, map_type: &str) -> String {
186 "called `map(f)` on an {0} value where `f` is a unit {1}",
192 fn lint_map_unit_fn(cx: &LateContext, stmt: &hir::Stmt, expr: &hir::Expr, map_args: &[hir::Expr]) {
193 let var_arg = &map_args[0];
194 let fn_arg = &map_args[1];
196 let (map_type, variant, lint) =
197 if match_type(cx, cx.tables.expr_ty(var_arg), &paths::OPTION) {
198 ("Option", "Some", OPTION_MAP_UNIT_FN)
199 } else if match_type(cx, cx.tables.expr_ty(var_arg), &paths::RESULT) {
200 ("Result", "Ok", RESULT_MAP_UNIT_FN)
205 if is_unit_function(cx, fn_arg) {
206 let msg = suggestion_msg("function", map_type);
207 let suggestion = format!("if let {0}({1}) = {2} {{ {3}(...) }}",
209 let_binding_name(cx, var_arg),
210 snippet(cx, var_arg.span, "_"),
211 snippet(cx, fn_arg.span, "_"));
213 span_lint_and_then(cx, lint, expr.span, &msg, |db| {
214 db.span_suggestion_with_applicability(stmt.span,
217 Applicability::Unspecified);
219 } else if let Some((binding, closure_expr)) = unit_closure(cx, fn_arg) {
220 let msg = suggestion_msg("closure", map_type);
222 span_lint_and_then(cx, lint, expr.span, &msg, |db| {
223 if let Some(reduced_expr_span) = reduce_unit_expression(cx, closure_expr) {
224 let suggestion = format!("if let {0}({1}) = {2} {{ {3} }}",
226 snippet(cx, binding.pat.span, "_"),
227 snippet(cx, var_arg.span, "_"),
228 snippet(cx, reduced_expr_span, "_"));
229 db.span_suggestion(stmt.span, "try this", suggestion);
231 let suggestion = format!("if let {0}({1}) = {2} {{ ... }}",
233 snippet(cx, binding.pat.span, "_"),
234 snippet(cx, var_arg.span, "_"));
235 db.span_suggestion_with_applicability(stmt.span,
238 Applicability::Unspecified);
244 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
245 fn check_stmt(&mut self, cx: &LateContext, stmt: &hir::Stmt) {
246 if in_macro(stmt.span) {
250 if let hir::StmtSemi(ref expr, _) = stmt.node {
251 if let hir::ExprMethodCall(_, _, _) = expr.node {
252 if let Some(arglists) = method_chain_args(expr, &["map"]) {
253 lint_map_unit_fn(cx, stmt, expr, arglists[0]);