]> git.lizzy.rs Git - rust.git/blob - src/matches.rs
Remove * dep
[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                             match lit.node {
106                                 LitBool(true) => Some((&*arms[0].body, &*arms[1].body)),
107                                 LitBool(false) => Some((&*arms[1].body, &*arms[0].body)),
108                                 _ => None,
109                             }
110                         } else { None }
111                     } else { None };
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, "..")));
122                             } else {
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, "..")));
129                             }
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, "..")));
137                         } else {
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");
141                         }
142                     } else {
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");
146                     }
147                 } else {
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");
151                 }
152             }
153         }
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));
162                 } else {
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));
167                 }
168             }
169         }
170     }
171 }
172
173 fn is_unit_expr(expr: &Expr) -> bool {
174     match expr.node {
175         ExprTup(ref v) if v.is_empty() => true,
176         ExprBlock(ref b) if b.stmts.is_empty() && b.expr.is_none() => true,
177         _ => false,
178     }
179 }
180
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))
189 }
190
191 fn match_template(cx: &LateContext,
192                   span: Span,
193                   source: MatchSource,
194                   op: &str,
195                   expr: &Expr) -> String {
196     let expr_snippet = snippet(cx, expr.span, "..");
197     match source {
198         MatchSource::Normal => {
199             format!("match {}{} {{ ...", op, expr_snippet)
200         }
201         MatchSource::IfLetDesugar { .. } => {
202             format!("if let ... = {}{} {{", op, expr_snippet)
203         }
204         MatchSource::WhileLetDesugar => {
205             format!("while let ... = {}{} {{", op, expr_snippet)
206         }
207         MatchSource::ForLoopDesugar => {
208             cx.sess().span_bug(span, "for loop desugared to match with &-patterns!")
209         }
210     }
211 }