4 use syntax::codemap::Span;
5 use utils::{in_macro, iter_input_pats, match_type, method_chain_args, snippet, span_lint_and_then};
11 /// **What it does:** Checks for usage of `option.map(f)` where f is a function
12 /// or closure that returns the unit type.
14 /// **Why is this bad?** Readability, this can be written more clearly with
15 /// an if let statement
17 /// **Known problems:** None.
22 /// let x: Option<&str> = do_stuff();
23 /// x.map(log_err_msg);
24 /// x.map(|msg| log_err_msg(format_msg(msg)))
27 /// The correct use would be:
30 /// let x: Option<&str> = do_stuff();
31 /// if let Some(msg) = x {
34 /// if let Some(msg) = x {
35 /// log_err_msg(format_msg(msg))
38 declare_clippy_lint! {
39 pub OPTION_MAP_UNIT_FN,
41 "using `option.map(f)`, where f is a function or closure that returns ()"
44 /// **What it does:** Checks for usage of `result.map(f)` where f is a function
45 /// or closure that returns the unit type.
47 /// **Why is this bad?** Readability, this can be written more clearly with
48 /// an if let statement
50 /// **Known problems:** None.
55 /// let x: Result<&str, &str> = do_stuff();
56 /// x.map(log_err_msg);
57 /// x.map(|msg| log_err_msg(format_msg(msg)))
60 /// The correct use would be:
63 /// let x: Result<&str, &str> = do_stuff();
64 /// if let Ok(msg) = x {
67 /// if let Ok(msg) = x {
68 /// log_err_msg(format_msg(msg))
71 declare_clippy_lint! {
72 pub RESULT_MAP_UNIT_FN,
74 "using `result.map(f)`, where f is a function or closure that returns ()"
78 impl LintPass for Pass {
79 fn get_lints(&self) -> LintArray {
80 lint_array!(OPTION_MAP_UNIT_FN, RESULT_MAP_UNIT_FN)
84 fn is_unit_type(ty: ty::Ty) -> bool {
86 ty::TyTuple(slice) => slice.is_empty(),
92 fn is_unit_function(cx: &LateContext, expr: &hir::Expr) -> bool {
93 let ty = cx.tables.expr_ty(expr);
95 if let ty::TyFnDef(id, _) = ty.sty {
96 if let Some(fn_type) = cx.tcx.fn_sig(id).no_late_bound_regions() {
97 return is_unit_type(fn_type.output());
103 fn is_unit_expression(cx: &LateContext, expr: &hir::Expr) -> bool {
104 is_unit_type(cx.tables.expr_ty(expr))
107 /// The expression inside a closure may or may not have surrounding braces and
108 /// semicolons, which causes problems when generating a suggestion. Given an
109 /// expression that evaluates to '()' or '!', recursively remove useless braces
110 /// and semi-colons until is suitable for including in the suggestion template
111 fn reduce_unit_expression<'a>(cx: &LateContext, expr: &'a hir::Expr) -> Option<Span> {
112 if !is_unit_expression(cx, expr) {
117 hir::ExprCall(_, _) |
118 hir::ExprMethodCall(_, _, _) => {
119 // Calls can't be reduced any more
122 hir::ExprBlock(ref block) => {
123 match (&block.stmts[..], block.expr.as_ref()) {
124 (&[], Some(inner_expr)) => {
125 // If block only contains an expression,
126 // reduce `{ X }` to `X`
127 reduce_unit_expression(cx, inner_expr)
129 (&[ref inner_stmt], None) => {
130 // If block only contains statements,
131 // reduce `{ X; }` to `X` or `X;`
132 match inner_stmt.node {
133 hir::StmtDecl(ref d, _) => Some(d.span),
134 hir::StmtExpr(ref e, _) => Some(e.span),
135 hir::StmtSemi(_, _) => Some(inner_stmt.span),
139 // For closures that contain multiple statements
140 // it's difficult to get a correct suggestion span
141 // for all cases (multi-line closures specifically)
143 // We do not attempt to build a suggestion for those right now.
152 fn unit_closure<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'a hir::Expr) -> Option<(&'tcx hir::Arg, &'a hir::Expr)> {
153 if let hir::ExprClosure(_, ref decl, inner_expr_id, _, _) = expr.node {
154 let body = cx.tcx.hir.body(inner_expr_id);
155 let body_expr = &body.value;
158 if decl.inputs.len() == 1;
159 if is_unit_expression(cx, body_expr);
160 if let Some(binding) = iter_input_pats(&decl, body).next();
162 return Some((binding, body_expr));
169 /// Builds a name for the let binding variable (var_arg)
171 /// `x.field` => `x_field`
174 /// Anything else will return `_`.
175 fn let_binding_name(cx: &LateContext, var_arg: &hir::Expr) -> String {
176 match &var_arg.node {
177 hir::ExprField(_, _) => snippet(cx, var_arg.span, "_").replace(".", "_"),
178 hir::ExprPath(_) => format!("_{}", snippet(cx, var_arg.span, "")),
183 fn suggestion_msg(function_type: &str, map_type: &str) -> String {
185 "called `map(f)` on an {0} value where `f` is a unit {1}",
191 fn lint_map_unit_fn(cx: &LateContext, stmt: &hir::Stmt, expr: &hir::Expr, map_args: &[hir::Expr]) {
192 let var_arg = &map_args[0];
193 let fn_arg = &map_args[1];
195 let (map_type, variant, lint) =
196 if match_type(cx, cx.tables.expr_ty(var_arg), &paths::OPTION) {
197 ("Option", "Some", OPTION_MAP_UNIT_FN)
198 } else if match_type(cx, cx.tables.expr_ty(var_arg), &paths::RESULT) {
199 ("Result", "Ok", RESULT_MAP_UNIT_FN)
204 if is_unit_function(cx, fn_arg) {
205 let msg = suggestion_msg("function", map_type);
206 let suggestion = format!("if let {0}({1}) = {2} {{ {3}(...) }}",
208 let_binding_name(cx, var_arg),
209 snippet(cx, var_arg.span, "_"),
210 snippet(cx, fn_arg.span, "_"));
212 span_lint_and_then(cx, lint, expr.span, &msg, |db| {
213 db.span_approximate_suggestion(stmt.span, "try this", suggestion);
215 } else if let Some((binding, closure_expr)) = unit_closure(cx, fn_arg) {
216 let msg = suggestion_msg("closure", map_type);
218 span_lint_and_then(cx, lint, expr.span, &msg, |db| {
219 if let Some(reduced_expr_span) = reduce_unit_expression(cx, closure_expr) {
220 let suggestion = format!("if let {0}({1}) = {2} {{ {3} }}",
222 snippet(cx, binding.pat.span, "_"),
223 snippet(cx, var_arg.span, "_"),
224 snippet(cx, reduced_expr_span, "_"));
225 db.span_suggestion(stmt.span, "try this", suggestion);
227 let suggestion = format!("if let {0}({1}) = {2} {{ ... }}",
229 snippet(cx, binding.pat.span, "_"),
230 snippet(cx, var_arg.span, "_"));
231 db.span_approximate_suggestion(stmt.span, "try this", suggestion);
237 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
238 fn check_stmt(&mut self, cx: &LateContext, stmt: &hir::Stmt) {
239 if in_macro(stmt.span) {
243 if let hir::StmtSemi(ref expr, _) = stmt.node {
244 if let hir::ExprMethodCall(_, _, _) = expr.node {
245 if let Some(arglists) = method_chain_args(expr, &["map"]) {
246 lint_map_unit_fn(cx, stmt, expr, arglists[0]);