]> git.lizzy.rs Git - rust.git/blob - src/matches.rs
added wiki comments + wiki-generating python script
[rust.git] / src / matches.rs
1 use rustc::lint::*;
2 use rustc_front::hir::*;
3 use rustc::middle::ty;
4 use syntax::ast::Lit_::LitBool;
5 use syntax::codemap::Span;
6
7 use utils::{snippet, span_lint, span_help_and_lint, in_external_macro, expr_block};
8
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.
10 ///
11 /// **Why is this bad?** Just readability – `if let` nests less than a `match`.
12 ///
13 /// **Known problems:** None
14 ///
15 /// **Example:**
16 /// ```
17 /// match x {
18 ///     Some(ref foo) -> bar(foo),
19 ///     _ => ()
20 /// }
21 /// ```
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.
26 ///
27 /// **Why is this bad?** It just makes the code less readable. That reference destructuring adds nothing to the code.
28 ///
29 /// **Known problems:** None
30 ///
31 /// **Example:**
32 ///
33 /// ```
34 /// match x {
35 ///     &A(ref y) => foo(y),
36 ///     &B => bar(),
37 ///     _ => frob(&x),
38 /// }
39 /// ```
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.
44 ///
45 /// **Why is this bad?** It makes the code less readable.
46 ///
47 /// **Known problems:** None
48 ///
49 /// **Example:**
50 ///
51 /// ```
52 /// let condition: bool = true;
53 /// match condition {
54 ///     true => foo(),
55 ///     false => bar(),
56 /// }
57 /// ```
58 declare_lint!(pub MATCH_BOOL, Warn,
59               "a match on boolean expression; recommends `if..else` block instead");
60
61 #[allow(missing_copy_implementations)]
62 pub struct MatchPass;
63
64 impl LintPass for MatchPass {
65     fn get_lints(&self) -> LintArray {
66         lint_array!(SINGLE_MATCH, MATCH_REF_PATS, MATCH_BOOL)
67     }
68 }
69
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
75                 // only two arms
76             if arms.len() == 2 &&
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)
89             {
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, "..")));
97             }
98
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 {
105                             if let LitBool(val) = lit.node {
106                                 if val {
107                                     Some((&*arms[0].body, &*arms[1].body))
108                                 } else {
109                                     Some((&*arms[1].body, &*arms[0].body))
110                                 }
111                             } else { None }
112                         } else { None }
113                     } else { None };
114                     if let Some((ref true_expr, ref false_expr)) = exprs {
115                         if !is_unit_expr(true_expr) {
116                             if !is_unit_expr(false_expr) {
117                                 span_help_and_lint(cx, MATCH_BOOL, expr.span,
118                                     "you seem to be trying to match on a boolean expression. \
119                                    Consider using an if..else block:",
120                                    &format!("try\nif {} {} else {}",
121                                         snippet(cx, ex.span, "b"),
122                                         expr_block(cx, true_expr, None, ".."),
123                                         expr_block(cx, false_expr, None, "..")));
124                             } else {
125                                 span_help_and_lint(cx, MATCH_BOOL, expr.span,
126                                     "you seem to be trying to match on a boolean expression. \
127                                    Consider using an if..else block:",
128                                    &format!("try\nif {} {}",
129                                         snippet(cx, ex.span, "b"),
130                                         expr_block(cx, true_expr, None, "..")));
131                             }
132                         } else if !is_unit_expr(false_expr) {
133                             span_help_and_lint(cx, MATCH_BOOL, expr.span,
134                                 "you seem to be trying to match on a boolean expression. \
135                                Consider using an if..else block:",
136                                &format!("try\nif !{} {}",
137                                     snippet(cx, ex.span, "b"),
138                                     expr_block(cx, false_expr, None, "..")));
139                         } else {
140                             span_lint(cx, MATCH_BOOL, expr.span,
141                                    "you seem to be trying to match on a boolean expression. \
142                                    Consider using an if..else block");
143                         }
144                     } else {
145                         span_lint(cx, MATCH_BOOL, expr.span,
146                             "you seem to be trying to match on a boolean expression. \
147                             Consider using an if..else block");
148                     }
149                 } else {
150                     span_lint(cx, MATCH_BOOL, expr.span,
151                         "you seem to be trying to match on a boolean expression. \
152                         Consider using an if..else block");
153                 }
154             }
155         }
156         if let ExprMatch(ref ex, ref arms, source) = expr.node {
157             // check preconditions for MATCH_REF_PATS
158             if has_only_ref_pats(arms) {
159                 if let ExprAddrOf(Mutability::MutImmutable, ref inner) = ex.node {
160                     let template = match_template(cx, expr.span, source, "", inner);
161                     span_lint(cx, MATCH_REF_PATS, expr.span, &format!(
162                         "you don't need to add `&` to both the expression \
163                          and the patterns: use `{}`", template));
164                 } else {
165                     let template = match_template(cx, expr.span, source, "*", ex);
166                     span_lint(cx, MATCH_REF_PATS, expr.span, &format!(
167                         "instead of prefixing all patterns with `&`, you can dereference the \
168                          expression: `{}`", template));
169                 }
170             }
171         }
172     }
173 }
174
175 fn is_unit_expr(expr: &Expr) -> bool {
176     match expr.node {
177         ExprTup(ref v) if v.is_empty() => true,
178         ExprBlock(ref b) if b.stmts.is_empty() && b.expr.is_none() => true,
179         _ => false,
180     }
181 }
182
183 fn has_only_ref_pats(arms: &[Arm]) -> bool {
184     let mapped = arms.iter().flat_map(|a| &a.pats).map(|p| match p.node {
185         PatRegion(..) => Some(true),  // &-patterns
186         PatWild => Some(false),   // an "anything" wildcard is also fine
187         _ => None,                    // any other pattern is not fine
188     }).collect::<Option<Vec<bool>>>();
189     // look for Some(v) where there's at least one true element
190     mapped.map_or(false, |v| v.iter().any(|el| *el))
191 }
192
193 fn match_template(cx: &LateContext,
194                   span: Span,
195                   source: MatchSource,
196                   op: &str,
197                   expr: &Expr) -> String {
198     let expr_snippet = snippet(cx, expr.span, "..");
199     match source {
200         MatchSource::Normal => {
201             format!("match {}{} {{ ...", op, expr_snippet)
202         }
203         MatchSource::IfLetDesugar { .. } => {
204             format!("if let ... = {}{} {{", op, expr_snippet)
205         }
206         MatchSource::WhileLetDesugar => {
207             format!("while let ... = {}{} {{", op, expr_snippet)
208         }
209         MatchSource::ForLoopDesugar => {
210             cx.sess().span_bug(span, "for loop desugared to match with &-patterns!")
211         }
212     }
213 }