2 use rustc_front::hir::*;
4 use syntax::ast::Lit_::LitBool;
5 use syntax::codemap::Span;
7 use utils::{snippet, span_lint, span_help_and_lint, in_external_macro, expr_block};
9 /// **What it does:** This lint checks for matches with a single arm where an `if let` will usually suffice. It is `Warn` by default.
11 /// **Why is this bad?** Just readability – `if let` nests less than a `match`.
13 /// **Known problems:** None
18 /// Some(ref foo) -> bar(foo),
22 declare_lint!(pub SINGLE_MATCH, Warn,
23 "a match statement with a single nontrivial arm (i.e, where the other arm \
24 is `_ => {}`) is used; recommends `if let` instead");
25 /// **What it does:** This lint checks for matches where all arms match a reference, suggesting to remove the reference and deref the matched expression instead. It is `Warn` by default.
27 /// **Why is this bad?** It just makes the code less readable. That reference destructuring adds nothing to the code.
29 /// **Known problems:** None
35 /// &A(ref y) => foo(y),
40 declare_lint!(pub MATCH_REF_PATS, Warn,
41 "a match has all arms prefixed with `&`; the match expression can be \
42 dereferenced instead");
43 /// **What it does:** This lint checks for matches where match expression is a `bool`. It suggests to replace the expression with an `if...else` block. It is `Warn` by default.
45 /// **Why is this bad?** It makes the code less readable.
47 /// **Known problems:** None
52 /// let condition: bool = true;
58 declare_lint!(pub MATCH_BOOL, Warn,
59 "a match on boolean expression; recommends `if..else` block instead");
61 #[allow(missing_copy_implementations)]
64 impl LintPass for MatchPass {
65 fn get_lints(&self) -> LintArray {
66 lint_array!(SINGLE_MATCH, MATCH_REF_PATS, MATCH_BOOL)
70 impl LateLintPass for MatchPass {
71 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
72 if in_external_macro(cx, expr.span) { return; }
73 if let ExprMatch(ref ex, ref arms, MatchSource::Normal) = expr.node {
74 // check preconditions for SINGLE_MATCH
77 // both of the arms have a single pattern and no guard
78 arms[0].pats.len() == 1 && arms[0].guard.is_none() &&
79 arms[1].pats.len() == 1 && arms[1].guard.is_none() &&
80 // and the second pattern is a `_` wildcard: this is not strictly necessary,
81 // since the exhaustiveness check will ensure the last one is a catch-all,
82 // but in some cases, an explicit match is preferred to catch situations
83 // when an enum is extended, so we don't consider these cases
84 arms[1].pats[0].node == PatWild &&
85 // we don't want any content in the second arm (unit or empty block)
86 is_unit_expr(&arms[1].body) &&
87 // finally, MATCH_BOOL doesn't apply here
88 (cx.tcx.expr_ty(ex).sty != ty::TyBool || cx.current_level(MATCH_BOOL) == Allow)
90 span_help_and_lint(cx, SINGLE_MATCH, expr.span,
91 "you seem to be trying to use match for destructuring a \
92 single pattern. Consider using `if let`",
93 &format!("try\nif let {} = {} {}",
94 snippet(cx, arms[0].pats[0].span, ".."),
95 snippet(cx, ex.span, ".."),
96 expr_block(cx, &arms[0].body, None, "..")));
99 // check preconditions for MATCH_BOOL
100 // type of expression == bool
101 if cx.tcx.expr_ty(ex).sty == ty::TyBool {
102 if arms.len() == 2 && arms[0].pats.len() == 1 { // no guards
103 let exprs = if let PatLit(ref arm_bool) = arms[0].pats[0].node {
104 if let ExprLit(ref lit) = arm_bool.node {
106 LitBool(true) => Some((&*arms[0].body, &*arms[1].body)),
107 LitBool(false) => Some((&*arms[1].body, &*arms[0].body)),
112 if let Some((ref true_expr, ref false_expr)) = exprs {
113 if !is_unit_expr(true_expr) {
114 if !is_unit_expr(false_expr) {
115 span_help_and_lint(cx, MATCH_BOOL, expr.span,
116 "you seem to be trying to match on a boolean expression. \
117 Consider using an if..else block:",
118 &format!("try\nif {} {} else {}",
119 snippet(cx, ex.span, "b"),
120 expr_block(cx, true_expr, None, ".."),
121 expr_block(cx, false_expr, None, "..")));
123 span_help_and_lint(cx, MATCH_BOOL, expr.span,
124 "you seem to be trying to match on a boolean expression. \
125 Consider using an if..else block:",
126 &format!("try\nif {} {}",
127 snippet(cx, ex.span, "b"),
128 expr_block(cx, true_expr, None, "..")));
130 } else if !is_unit_expr(false_expr) {
131 span_help_and_lint(cx, MATCH_BOOL, expr.span,
132 "you seem to be trying to match on a boolean expression. \
133 Consider using an if..else block:",
134 &format!("try\nif !{} {}",
135 snippet(cx, ex.span, "b"),
136 expr_block(cx, false_expr, None, "..")));
138 span_lint(cx, MATCH_BOOL, expr.span,
139 "you seem to be trying to match on a boolean expression. \
140 Consider using an if..else block");
143 span_lint(cx, MATCH_BOOL, expr.span,
144 "you seem to be trying to match on a boolean expression. \
145 Consider using an if..else block");
148 span_lint(cx, MATCH_BOOL, expr.span,
149 "you seem to be trying to match on a boolean expression. \
150 Consider using an if..else block");
154 if let ExprMatch(ref ex, ref arms, source) = expr.node {
155 // check preconditions for MATCH_REF_PATS
156 if has_only_ref_pats(arms) {
157 if let ExprAddrOf(Mutability::MutImmutable, ref inner) = ex.node {
158 let template = match_template(cx, expr.span, source, "", inner);
159 span_lint(cx, MATCH_REF_PATS, expr.span, &format!(
160 "you don't need to add `&` to both the expression \
161 and the patterns: use `{}`", template));
163 let template = match_template(cx, expr.span, source, "*", ex);
164 span_lint(cx, MATCH_REF_PATS, expr.span, &format!(
165 "instead of prefixing all patterns with `&`, you can dereference the \
166 expression: `{}`", template));
173 fn is_unit_expr(expr: &Expr) -> bool {
175 ExprTup(ref v) if v.is_empty() => true,
176 ExprBlock(ref b) if b.stmts.is_empty() && b.expr.is_none() => true,
181 fn has_only_ref_pats(arms: &[Arm]) -> bool {
182 let mapped = arms.iter().flat_map(|a| &a.pats).map(|p| match p.node {
183 PatRegion(..) => Some(true), // &-patterns
184 PatWild => Some(false), // an "anything" wildcard is also fine
185 _ => None, // any other pattern is not fine
186 }).collect::<Option<Vec<bool>>>();
187 // look for Some(v) where there's at least one true element
188 mapped.map_or(false, |v| v.iter().any(|el| *el))
191 fn match_template(cx: &LateContext,
195 expr: &Expr) -> String {
196 let expr_snippet = snippet(cx, expr.span, "..");
198 MatchSource::Normal => {
199 format!("match {}{} {{ ...", op, expr_snippet)
201 MatchSource::IfLetDesugar { .. } => {
202 format!("if let ... = {}{} {{", op, expr_snippet)
204 MatchSource::WhileLetDesugar => {
205 format!("while let ... = {}{} {{", op, expr_snippet)
207 MatchSource::ForLoopDesugar => {
208 cx.sess().span_bug(span, "for loop desugared to match with &-patterns!")