|
| 1 | +use rustc::lint::*; |
| 2 | +use rustc::hir::*; |
| 3 | +use syntax::codemap::Span; |
| 4 | +use utils::{paths, span_lint_and_then, match_path, snippet}; |
| 5 | + |
| 6 | +/// **What it does:*** Lint for redundant pattern matching over `Result` or `Option` |
| 7 | +/// |
| 8 | +/// **Why is this bad?** It's more concise and clear to just use the proper utility function |
| 9 | +/// |
| 10 | +/// **Known problems:** None. |
| 11 | +/// |
| 12 | +/// **Example:** |
| 13 | +/// |
| 14 | +/// ```rust |
| 15 | +/// if let Ok(_) = Ok::<i32, i32>(42) {} |
| 16 | +/// if let Err(_) = Err::<i32, i32>(42) {} |
| 17 | +/// if let None = None::<()> {} |
| 18 | +/// if let Some(_) = Some(42) {} |
| 19 | +/// ``` |
| 20 | +/// |
| 21 | +/// The more idiomatic use would be: |
| 22 | +/// |
| 23 | +/// ```rust |
| 24 | +/// if Ok::<i32, i32>(42).is_ok() {} |
| 25 | +/// if Err::<i32, i32>(42).is_err() {} |
| 26 | +/// if None::<()>.is_none() {} |
| 27 | +/// if Some(42).is_some() {} |
| 28 | +/// ``` |
| 29 | +/// |
| 30 | +declare_lint! { |
| 31 | + pub IF_LET_REDUNDANT_PATTERN_MATCHING, |
| 32 | + Warn, |
| 33 | + "use the proper utility function avoiding an `if let`" |
| 34 | +} |
| 35 | + |
| 36 | +#[derive(Copy, Clone)] |
| 37 | +pub struct Pass; |
| 38 | + |
| 39 | +impl LintPass for Pass { |
| 40 | + fn get_lints(&self) -> LintArray { |
| 41 | + lint_array!(IF_LET_REDUNDANT_PATTERN_MATCHING) |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +impl LateLintPass for Pass { |
| 46 | + fn check_expr(&mut self, cx: &LateContext, expr: &Expr) { |
| 47 | + |
| 48 | + if let ExprMatch(ref op, ref arms, MatchSource::IfLetDesugar{..}) = expr.node { |
| 49 | + |
| 50 | + if arms[0].pats.len() == 1 { |
| 51 | + |
| 52 | + let good_method = match arms[0].pats[0].node { |
| 53 | + PatKind::TupleStruct(ref path, ref pats, _) if pats.len() == 1 && pats[0].node == PatKind::Wild => { |
| 54 | + |
| 55 | + if match_path(path, &paths::RESULT_OK) { |
| 56 | + "is_ok()" |
| 57 | + } else if match_path(path, &paths::RESULT_ERR) { |
| 58 | + "is_err()" |
| 59 | + } else if match_path(path, &paths::OPTION_SOME) { |
| 60 | + "is_some()" |
| 61 | + } else { |
| 62 | + return |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | + PatKind::Path(_, ref path) if match_path(path, &paths::OPTION_NONE) => { |
| 67 | + "is_none()" |
| 68 | + } |
| 69 | + |
| 70 | + _ => return |
| 71 | + }; |
| 72 | + |
| 73 | + span_lint_and_then(cx, |
| 74 | + IF_LET_REDUNDANT_PATTERN_MATCHING, |
| 75 | + arms[0].pats[0].span, |
| 76 | + &format!("redundant pattern matching, consider using `{}`", good_method), |
| 77 | + |db| { |
| 78 | + let span = Span { |
| 79 | + lo: expr.span.lo, |
| 80 | + hi: op.span.hi, |
| 81 | + expn_id: expr.span.expn_id, |
| 82 | + }; |
| 83 | + db.span_suggestion(span, |
| 84 | + "try this", |
| 85 | + format!("if {}.{}", snippet(cx, op.span, "_"), good_method)); |
| 86 | + }); |
| 87 | + } |
| 88 | + |
| 89 | + } |
| 90 | + } |
| 91 | +} |
0 commit comments