|
| 1 | +use rustc::hir; |
| 2 | +use rustc::lint::*; |
| 3 | +use rustc::ty; |
| 4 | +use syntax::codemap::Span; |
| 5 | +use utils::{in_macro, iter_input_pats, match_type, method_chain_args, snippet, span_lint_and_then}; |
| 6 | +use utils::paths; |
| 7 | + |
| 8 | +#[derive(Clone)] |
| 9 | +pub struct Pass; |
| 10 | + |
| 11 | +/// **What it does:** Checks for usage of `option.map(f)` where f is a function |
| 12 | +/// or closure that returns the unit type. |
| 13 | +/// |
| 14 | +/// **Why is this bad?** Readability, this can be written more clearly with |
| 15 | +/// an if let statement |
| 16 | +/// |
| 17 | +/// **Known problems:** None. |
| 18 | +/// |
| 19 | +/// **Example:** |
| 20 | +/// |
| 21 | +/// ```rust |
| 22 | +/// let x: Option<&str> = do_stuff(); |
| 23 | +/// x.map(log_err_msg); |
| 24 | +/// x.map(|msg| log_err_msg(format_msg(msg))) |
| 25 | +/// ``` |
| 26 | +/// |
| 27 | +/// The correct use would be: |
| 28 | +/// |
| 29 | +/// ```rust |
| 30 | +/// let x: Option<&str> = do_stuff(); |
| 31 | +/// if let Some(msg) = x { |
| 32 | +/// log_err_msg(msg) |
| 33 | +/// } |
| 34 | +/// if let Some(msg) = x { |
| 35 | +/// log_err_msg(format_msg(msg)) |
| 36 | +/// } |
| 37 | +/// ``` |
| 38 | +declare_clippy_lint! { |
| 39 | + pub OPTION_MAP_UNIT_FN, |
| 40 | + complexity, |
| 41 | + "using `option.map(f)`, where f is a function or closure that returns ()" |
| 42 | +} |
| 43 | + |
| 44 | +/// **What it does:** Checks for usage of `result.map(f)` where f is a function |
| 45 | +/// or closure that returns the unit type. |
| 46 | +/// |
| 47 | +/// **Why is this bad?** Readability, this can be written more clearly with |
| 48 | +/// an if let statement |
| 49 | +/// |
| 50 | +/// **Known problems:** None. |
| 51 | +/// |
| 52 | +/// **Example:** |
| 53 | +/// |
| 54 | +/// ```rust |
| 55 | +/// let x: Result<&str, &str> = do_stuff(); |
| 56 | +/// x.map(log_err_msg); |
| 57 | +/// x.map(|msg| log_err_msg(format_msg(msg))) |
| 58 | +/// ``` |
| 59 | +/// |
| 60 | +/// The correct use would be: |
| 61 | +/// |
| 62 | +/// ```rust |
| 63 | +/// let x: Result<&str, &str> = do_stuff(); |
| 64 | +/// if let Ok(msg) = x { |
| 65 | +/// log_err_msg(msg) |
| 66 | +/// } |
| 67 | +/// if let Ok(msg) = x { |
| 68 | +/// log_err_msg(format_msg(msg)) |
| 69 | +/// } |
| 70 | +/// ``` |
| 71 | +declare_clippy_lint! { |
| 72 | + pub RESULT_MAP_UNIT_FN, |
| 73 | + complexity, |
| 74 | + "using `result.map(f)`, where f is a function or closure that returns ()" |
| 75 | +} |
| 76 | + |
| 77 | + |
| 78 | +impl LintPass for Pass { |
| 79 | + fn get_lints(&self) -> LintArray { |
| 80 | + lint_array!(OPTION_MAP_UNIT_FN, RESULT_MAP_UNIT_FN) |
| 81 | + } |
| 82 | +} |
| 83 | + |
| 84 | +fn is_unit_type(ty: ty::Ty) -> bool { |
| 85 | + match ty.sty { |
| 86 | + ty::TyTuple(slice) => slice.is_empty(), |
| 87 | + ty::TyNever => true, |
| 88 | + _ => false, |
| 89 | + } |
| 90 | +} |
| 91 | + |
| 92 | +fn is_unit_function(cx: &LateContext, expr: &hir::Expr) -> bool { |
| 93 | + let ty = cx.tables.expr_ty(expr); |
| 94 | + |
| 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()); |
| 98 | + } |
| 99 | + } |
| 100 | + false |
| 101 | +} |
| 102 | + |
| 103 | +fn is_unit_expression(cx: &LateContext, expr: &hir::Expr) -> bool { |
| 104 | + is_unit_type(cx.tables.expr_ty(expr)) |
| 105 | +} |
| 106 | + |
| 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) { |
| 113 | + return None; |
| 114 | + } |
| 115 | + |
| 116 | + match expr.node { |
| 117 | + hir::ExprCall(_, _) | |
| 118 | + hir::ExprMethodCall(_, _, _) => { |
| 119 | + // Calls can't be reduced any more |
| 120 | + Some(expr.span) |
| 121 | + }, |
| 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) |
| 128 | + }, |
| 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), |
| 136 | + } |
| 137 | + }, |
| 138 | + _ => { |
| 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) |
| 142 | + // |
| 143 | + // We do not attempt to build a suggestion for those right now. |
| 144 | + None |
| 145 | + } |
| 146 | + } |
| 147 | + }, |
| 148 | + _ => None, |
| 149 | + } |
| 150 | +} |
| 151 | + |
| 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; |
| 156 | + |
| 157 | + if_chain! { |
| 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(); |
| 161 | + then { |
| 162 | + return Some((binding, body_expr)); |
| 163 | + } |
| 164 | + } |
| 165 | + } |
| 166 | + None |
| 167 | +} |
| 168 | + |
| 169 | +/// Builds a name for the let binding variable (var_arg) |
| 170 | +/// |
| 171 | +/// `x.field` => `x_field` |
| 172 | +/// `y` => `_y` |
| 173 | +/// |
| 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, "")), |
| 179 | + _ => "_".to_string() |
| 180 | + } |
| 181 | +} |
| 182 | + |
| 183 | +fn suggestion_msg(function_type: &str, map_type: &str) -> String { |
| 184 | + format!( |
| 185 | + "called `map(f)` on an {0} value where `f` is a unit {1}", |
| 186 | + map_type, |
| 187 | + function_type |
| 188 | + ) |
| 189 | +} |
| 190 | + |
| 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]; |
| 194 | + |
| 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) |
| 200 | + } else { |
| 201 | + return |
| 202 | + }; |
| 203 | + |
| 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}(...) }}", |
| 207 | + variant, |
| 208 | + let_binding_name(cx, var_arg), |
| 209 | + snippet(cx, var_arg.span, "_"), |
| 210 | + snippet(cx, fn_arg.span, "_")); |
| 211 | + |
| 212 | + span_lint_and_then(cx, lint, expr.span, &msg, |db| { |
| 213 | + db.span_approximate_suggestion(stmt.span, "try this", suggestion); |
| 214 | + }); |
| 215 | + } else if let Some((binding, closure_expr)) = unit_closure(cx, fn_arg) { |
| 216 | + let msg = suggestion_msg("closure", map_type); |
| 217 | + |
| 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} }}", |
| 221 | + variant, |
| 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); |
| 226 | + } else { |
| 227 | + let suggestion = format!("if let {0}({1}) = {2} {{ ... }}", |
| 228 | + variant, |
| 229 | + snippet(cx, binding.pat.span, "_"), |
| 230 | + snippet(cx, var_arg.span, "_")); |
| 231 | + db.span_approximate_suggestion(stmt.span, "try this", suggestion); |
| 232 | + } |
| 233 | + }); |
| 234 | + } |
| 235 | +} |
| 236 | + |
| 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) { |
| 240 | + return; |
| 241 | + } |
| 242 | + |
| 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]); |
| 247 | + } |
| 248 | + } |
| 249 | + } |
| 250 | + } |
| 251 | +} |
0 commit comments