]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/matches.rs
correctly check exclusive range patterns for overlap
[rust.git] / clippy_lints / src / matches.rs
1 use rustc::hir::*;
2 use rustc::lint::*;
3 use rustc::middle::const_val::ConstVal;
4 use rustc::ty;
5 use rustc_const_eval::EvalHint::ExprTypeChecked;
6 use rustc_const_eval::ConstContext;
7 use rustc_const_math::ConstInt;
8 use std::cmp::Ordering;
9 use std::collections::Bound;
10 use syntax::ast::LitKind;
11 use syntax::codemap::Span;
12 use utils::paths;
13 use utils::{match_type, snippet, span_note_and_lint, span_lint_and_then, in_external_macro, expr_block};
14 use utils::sugg::Sugg;
15
16 /// **What it does:** Checks for matches with a single arm where an `if let`
17 /// will usually suffice.
18 ///
19 /// **Why is this bad?** Just readability – `if let` nests less than a `match`.
20 ///
21 /// **Known problems:** None.
22 ///
23 /// **Example:**
24 /// ```rust
25 /// match x {
26 ///     Some(ref foo) => bar(foo),
27 ///     _ => ()
28 /// }
29 /// ```
30 declare_lint! {
31     pub SINGLE_MATCH,
32     Warn,
33     "a match statement with a single nontrivial arm (i.e, where the other arm \
34      is `_ => {}`) instead of `if let`"
35 }
36
37 /// **What it does:** Checks for matches with a two arms where an `if let` will
38 /// usually suffice.
39 ///
40 /// **Why is this bad?** Just readability – `if let` nests less than a `match`.
41 ///
42 /// **Known problems:** Personal style preferences may differ.
43 ///
44 /// **Example:**
45 /// ```rust
46 /// match x {
47 ///     Some(ref foo) => bar(foo),
48 ///     _ => bar(other_ref),
49 /// }
50 /// ```
51 declare_lint! {
52     pub SINGLE_MATCH_ELSE,
53     Allow,
54     "a match statement with a two arms where the second arm's pattern is a wildcard \
55      instead of `if let`"
56 }
57
58 /// **What it does:** Checks for matches where all arms match a reference,
59 /// suggesting to remove the reference and deref the matched expression
60 /// instead. It also checks for `if let &foo = bar` blocks.
61 ///
62 /// **Why is this bad?** It just makes the code less readable. That reference
63 /// destructuring adds nothing to the code.
64 ///
65 /// **Known problems:** None.
66 ///
67 /// **Example:**
68 /// ```rust
69 /// match x {
70 ///     &A(ref y) => foo(y),
71 ///     &B => bar(),
72 ///     _ => frob(&x),
73 /// }
74 /// ```
75 declare_lint! {
76     pub MATCH_REF_PATS,
77     Warn,
78     "a match or `if let` with all arms prefixed with `&` instead of deref-ing the match expression"
79 }
80
81 /// **What it does:** Checks for matches where match expression is a `bool`. It
82 /// suggests to replace the expression with an `if...else` block.
83 ///
84 /// **Why is this bad?** It makes the code less readable.
85 ///
86 /// **Known problems:** None.
87 ///
88 /// **Example:**
89 /// ```rust
90 /// let condition: bool = true;
91 /// match condition {
92 ///     true => foo(),
93 ///     false => bar(),
94 /// }
95 /// ```
96 declare_lint! {
97     pub MATCH_BOOL,
98     Warn,
99     "a match on a boolean expression instead of an `if..else` block"
100 }
101
102 /// **What it does:** Checks for overlapping match arms.
103 ///
104 /// **Why is this bad?** It is likely to be an error and if not, makes the code
105 /// less obvious.
106 ///
107 /// **Known problems:** None.
108 ///
109 /// **Example:**
110 /// ```rust
111 /// let x = 5;
112 /// match x {
113 ///     1 ... 10 => println!("1 ... 10"),
114 ///     5 ... 15 => println!("5 ... 15"),
115 ///     _ => (),
116 /// }
117 /// ```
118 declare_lint! {
119     pub MATCH_OVERLAPPING_ARM,
120     Warn,
121     "a match with overlapping arms"
122 }
123
124 #[allow(missing_copy_implementations)]
125 pub struct MatchPass;
126
127 impl LintPass for MatchPass {
128     fn get_lints(&self) -> LintArray {
129         lint_array!(SINGLE_MATCH,
130                     MATCH_REF_PATS,
131                     MATCH_BOOL,
132                     SINGLE_MATCH_ELSE,
133                     MATCH_OVERLAPPING_ARM)
134     }
135 }
136
137 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MatchPass {
138     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
139         if in_external_macro(cx, expr.span) {
140             return;
141         }
142         if let ExprMatch(ref ex, ref arms, MatchSource::Normal) = expr.node {
143             check_single_match(cx, ex, arms, expr);
144             check_match_bool(cx, ex, arms, expr);
145             check_overlapping_arms(cx, ex, arms);
146         }
147         if let ExprMatch(ref ex, ref arms, source) = expr.node {
148             check_match_ref_pats(cx, ex, arms, source, expr);
149         }
150     }
151 }
152
153 #[cfg_attr(rustfmt, rustfmt_skip)]
154 fn check_single_match(cx: &LateContext, ex: &Expr, arms: &[Arm], expr: &Expr) {
155     if arms.len() == 2 &&
156       arms[0].pats.len() == 1 && arms[0].guard.is_none() &&
157       arms[1].pats.len() == 1 && arms[1].guard.is_none() {
158         let els = if is_unit_expr(&arms[1].body) {
159             None
160         } else if let ExprBlock(_) = arms[1].body.node {
161             // matches with blocks that contain statements are prettier as `if let + else`
162             Some(&*arms[1].body)
163         } else {
164             // allow match arms with just expressions
165             return;
166         };
167         let ty = cx.tables.expr_ty(ex);
168         if ty.sty != ty::TyBool || cx.current_level(MATCH_BOOL) == Allow {
169             check_single_match_single_pattern(cx, ex, arms, expr, els);
170             check_single_match_opt_like(cx, ex, arms, expr, ty, els);
171         }
172     }
173 }
174
175 fn check_single_match_single_pattern(cx: &LateContext, ex: &Expr, arms: &[Arm], expr: &Expr, els: Option<&Expr>) {
176     if arms[1].pats[0].node == PatKind::Wild {
177         let lint = if els.is_some() {
178             SINGLE_MATCH_ELSE
179         } else {
180             SINGLE_MATCH
181         };
182         let els_str = els.map_or(String::new(), |els| format!(" else {}", expr_block(cx, els, None, "..")));
183         span_lint_and_then(cx,
184                            lint,
185                            expr.span,
186                            "you seem to be trying to use match for destructuring a single pattern. \
187                            Consider using `if let`",
188                            |db| {
189             db.span_suggestion(expr.span,
190                                "try this",
191                                format!("if let {} = {} {}{}",
192                                        snippet(cx, arms[0].pats[0].span, ".."),
193                                        snippet(cx, ex.span, ".."),
194                                        expr_block(cx, &arms[0].body, None, ".."),
195                                        els_str));
196         });
197     }
198 }
199
200 fn check_single_match_opt_like(
201     cx: &LateContext,
202     ex: &Expr,
203     arms: &[Arm],
204     expr: &Expr,
205     ty: ty::Ty,
206     els: Option<&Expr>
207 ) {
208     // list of candidate Enums we know will never get any more members
209     let candidates = &[(&paths::COW, "Borrowed"),
210                        (&paths::COW, "Cow::Borrowed"),
211                        (&paths::COW, "Cow::Owned"),
212                        (&paths::COW, "Owned"),
213                        (&paths::OPTION, "None"),
214                        (&paths::RESULT, "Err"),
215                        (&paths::RESULT, "Ok")];
216
217     let path = match arms[1].pats[0].node {
218         PatKind::TupleStruct(ref path, ref inner, _) => {
219             // contains any non wildcard patterns? e.g. Err(err)
220             if inner.iter().any(|pat| pat.node != PatKind::Wild) {
221                 return;
222             }
223             print::to_string(print::NO_ANN, |s| s.print_qpath(path, false))
224         },
225         PatKind::Binding(BindByValue(MutImmutable), _, ident, None) => ident.node.to_string(),
226         PatKind::Path(ref path) => print::to_string(print::NO_ANN, |s| s.print_qpath(path, false)),
227         _ => return,
228     };
229
230     for &(ty_path, pat_path) in candidates {
231         if &path == pat_path && match_type(cx, ty, ty_path) {
232             let lint = if els.is_some() {
233                 SINGLE_MATCH_ELSE
234             } else {
235                 SINGLE_MATCH
236             };
237             let els_str = els.map_or(String::new(), |els| format!(" else {}", expr_block(cx, els, None, "..")));
238             span_lint_and_then(cx,
239                                lint,
240                                expr.span,
241                                "you seem to be trying to use match for destructuring a single pattern. Consider \
242                                 using `if let`",
243                                |db| {
244                 db.span_suggestion(expr.span,
245                                    "try this",
246                                    format!("if let {} = {} {}{}",
247                                            snippet(cx, arms[0].pats[0].span, ".."),
248                                            snippet(cx, ex.span, ".."),
249                                            expr_block(cx, &arms[0].body, None, ".."),
250                                            els_str));
251             });
252         }
253     }
254 }
255
256 fn check_match_bool(cx: &LateContext, ex: &Expr, arms: &[Arm], expr: &Expr) {
257     // type of expression == bool
258     if cx.tables.expr_ty(ex).sty == ty::TyBool {
259         span_lint_and_then(cx,
260                            MATCH_BOOL,
261                            expr.span,
262                            "you seem to be trying to match on a boolean expression",
263                            move |db| {
264             if arms.len() == 2 && arms[0].pats.len() == 1 {
265                 // no guards
266                 let exprs = if let PatKind::Lit(ref arm_bool) = arms[0].pats[0].node {
267                     if let ExprLit(ref lit) = arm_bool.node {
268                         match lit.node {
269                             LitKind::Bool(true) => Some((&*arms[0].body, &*arms[1].body)),
270                             LitKind::Bool(false) => Some((&*arms[1].body, &*arms[0].body)),
271                             _ => None,
272                         }
273                     } else {
274                         None
275                     }
276                 } else {
277                     None
278                 };
279
280                 if let Some((true_expr, false_expr)) = exprs {
281                     let sugg = match (is_unit_expr(true_expr), is_unit_expr(false_expr)) {
282                         (false, false) => {
283                             Some(format!("if {} {} else {}",
284                                          snippet(cx, ex.span, "b"),
285                                          expr_block(cx, true_expr, None, ".."),
286                                          expr_block(cx, false_expr, None, "..")))
287                         },
288                         (false, true) => {
289                             Some(format!("if {} {}", snippet(cx, ex.span, "b"), expr_block(cx, true_expr, None, "..")))
290                         },
291                         (true, false) => {
292                             let test = Sugg::hir(cx, ex, "..");
293                             Some(format!("if {} {}", !test, expr_block(cx, false_expr, None, "..")))
294                         },
295                         (true, true) => None,
296                     };
297
298                     if let Some(sugg) = sugg {
299                         db.span_suggestion(expr.span, "consider using an if/else expression", sugg);
300                     }
301                 }
302             }
303
304         });
305     }
306 }
307
308 fn check_overlapping_arms(cx: &LateContext, ex: &Expr, arms: &[Arm]) {
309     if arms.len() >= 2 && cx.tables.expr_ty(ex).is_integral() {
310         let ranges = all_ranges(cx, arms);
311         let type_ranges = type_ranges(&ranges);
312         if !type_ranges.is_empty() {
313             if let Some((start, end)) = overlapping(&type_ranges) {
314                 span_note_and_lint(cx,
315                                    MATCH_OVERLAPPING_ARM,
316                                    start.span,
317                                    "some ranges overlap",
318                                    end.span,
319                                    "overlaps with this");
320             }
321         }
322     }
323 }
324
325 fn check_match_ref_pats(cx: &LateContext, ex: &Expr, arms: &[Arm], source: MatchSource, expr: &Expr) {
326     if has_only_ref_pats(arms) {
327         if let ExprAddrOf(Mutability::MutImmutable, ref inner) = ex.node {
328             span_lint_and_then(cx,
329                                MATCH_REF_PATS,
330                                expr.span,
331                                "you don't need to add `&` to both the expression and the patterns",
332                                |db| {
333                 let inner = Sugg::hir(cx, inner, "..");
334                 let template = match_template(expr.span, source, inner);
335                 db.span_suggestion(expr.span, "try", template);
336             });
337         } else {
338             span_lint_and_then(cx,
339                                MATCH_REF_PATS,
340                                expr.span,
341                                "you don't need to add `&` to all patterns",
342                                |db| {
343                 let ex = Sugg::hir(cx, ex, "..");
344                 let template = match_template(expr.span, source, ex.deref());
345                 db.span_suggestion(expr.span,
346                                    "instead of prefixing all patterns with `&`, you can dereference the expression",
347                                    template);
348             });
349         }
350     }
351 }
352
353 /// Get all arms that are unbounded `PatRange`s.
354 fn all_ranges(cx: &LateContext, arms: &[Arm]) -> Vec<SpannedRange<ConstVal>> {
355     let constcx = ConstContext::with_tables(cx.tcx, cx.tables);
356     arms.iter()
357         .flat_map(|arm| {
358             if let Arm { ref pats, guard: None, .. } = *arm {
359                     pats.iter()
360                 } else {
361                     [].iter()
362                 }
363                 .filter_map(|pat| {
364                     if_let_chain! {[
365                     let PatKind::Range(ref lhs, ref rhs, ref range_end) = pat.node,
366                     let Ok(lhs) = constcx.eval(lhs, ExprTypeChecked),
367                     let Ok(rhs) = constcx.eval(rhs, ExprTypeChecked)
368                 ], {
369                     let rhs = match *range_end {
370                         RangeEnd::Included => Bound::Included(rhs),
371                         RangeEnd::Excluded => Bound::Excluded(rhs),
372                     };
373                     return Some(SpannedRange { span: pat.span, node: (lhs, rhs) });
374                 }}
375
376                     if_let_chain! {[
377                     let PatKind::Lit(ref value) = pat.node,
378                     let Ok(value) = constcx.eval(value, ExprTypeChecked)
379                 ], {
380                     return Some(SpannedRange { span: pat.span, node: (value.clone(), Bound::Included(value)) });
381                 }}
382
383                     None
384                 })
385         })
386         .collect()
387 }
388
389 #[derive(Debug, Eq, PartialEq)]
390 pub struct SpannedRange<T> {
391     pub span: Span,
392     pub node: (T, Bound<T>),
393 }
394
395 type TypedRanges = Vec<SpannedRange<ConstInt>>;
396
397 /// Get all `Int` ranges or all `Uint` ranges. Mixed types are an error anyway and other types than
398 /// `Uint` and `Int` probably don't make sense.
399 fn type_ranges(ranges: &[SpannedRange<ConstVal>]) -> TypedRanges {
400     ranges.iter()
401         .filter_map(|range| match range.node {
402             (ConstVal::Integral(start), Bound::Included(ConstVal::Integral(end))) => {
403                 Some(SpannedRange {
404                     span: range.span,
405                     node: (start, Bound::Included(end)),
406                 })
407             },
408             (ConstVal::Integral(start), Bound::Excluded(ConstVal::Integral(end))) => {
409                 Some(SpannedRange {
410                     span: range.span,
411                     node: (start, Bound::Excluded(end)),
412                 })
413             },
414             (ConstVal::Integral(start), Bound::Unbounded) => {
415                 Some(SpannedRange {
416                     span: range.span,
417                     node: (start, Bound::Unbounded),
418                 })
419             },
420             _ => None,
421         })
422         .collect()
423 }
424
425 fn is_unit_expr(expr: &Expr) -> bool {
426     match expr.node {
427         ExprTup(ref v) if v.is_empty() => true,
428         ExprBlock(ref b) if b.stmts.is_empty() && b.expr.is_none() => true,
429         _ => false,
430     }
431 }
432
433 fn has_only_ref_pats(arms: &[Arm]) -> bool {
434     let mapped = arms.iter()
435         .flat_map(|a| &a.pats)
436         .map(|p| {
437             match p.node {
438                 PatKind::Ref(..) => Some(true),  // &-patterns
439                 PatKind::Wild => Some(false),   // an "anything" wildcard is also fine
440                 _ => None,                    // any other pattern is not fine
441             }
442         })
443         .collect::<Option<Vec<bool>>>();
444     // look for Some(v) where there's at least one true element
445     mapped.map_or(false, |v| v.iter().any(|el| *el))
446 }
447
448 fn match_template(span: Span, source: MatchSource, expr: Sugg) -> String {
449     match source {
450         MatchSource::Normal => format!("match {} {{ .. }}", expr),
451         MatchSource::IfLetDesugar { .. } => format!("if let .. = {} {{ .. }}", expr),
452         MatchSource::WhileLetDesugar => format!("while let .. = {} {{ .. }}", expr),
453         MatchSource::ForLoopDesugar => span_bug!(span, "for loop desugared to match with &-patterns!"),
454         MatchSource::TryDesugar => span_bug!(span, "`?` operator desugared to match with &-patterns!"),
455     }
456 }
457
458 pub fn overlapping<T>(ranges: &[SpannedRange<T>]) -> Option<(&SpannedRange<T>, &SpannedRange<T>)>
459     where T: Copy + Ord
460 {
461     #[derive(Copy, Clone, Debug, Eq, PartialEq)]
462     enum Kind<'a, T: 'a> {
463         Start(T, &'a SpannedRange<T>),
464         End(Bound<T>, &'a SpannedRange<T>),
465     }
466
467     impl<'a, T: Copy> Kind<'a, T> {
468         fn range(&self) -> &'a SpannedRange<T> {
469             match *self {
470                 Kind::Start(_, r) |
471                 Kind::End(_, r) => r,
472             }
473         }
474
475         fn value(self) -> Bound<T> {
476             match self {
477                 Kind::Start(t, _) => Bound::Included(t),
478                 Kind::End(t, _) => t,
479             }
480         }
481     }
482
483     impl<'a, T: Copy + Ord> PartialOrd for Kind<'a, T> {
484         fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
485             Some(self.cmp(other))
486         }
487     }
488
489     impl<'a, T: Copy + Ord> Ord for Kind<'a, T> {
490         fn cmp(&self, other: &Self) -> Ordering {
491             match (self.value(), other.value()) {
492                 (Bound::Included(a), Bound::Included(b)) |
493                 (Bound::Excluded(a), Bound::Excluded(b)) => a.cmp(&b),
494                 (Bound::Unbounded, _) |
495                 (_, Bound::Unbounded) => unimplemented!(),
496                 (Bound::Included(a), Bound::Excluded(b)) => {
497                     match a.cmp(&b) {
498                         Ordering::Equal => Ordering::Greater,
499                         other => other,
500                     }
501                 },
502                 (Bound::Excluded(a), Bound::Included(b)) => {
503                     match a.cmp(&b) {
504                         Ordering::Equal => Ordering::Less,
505                         other => other,
506                     }
507                 },
508             }
509         }
510     }
511
512     let mut values = Vec::with_capacity(2 * ranges.len());
513
514     for r in ranges {
515         values.push(Kind::Start(r.node.0, r));
516         values.push(Kind::End(r.node.1, r));
517     }
518
519     values.sort();
520
521     for (a, b) in values.iter().zip(values.iter().skip(1)) {
522         match (a, b) {
523             (&Kind::Start(_, ra), &Kind::End(_, rb)) => {
524                 if ra.node != rb.node {
525                     return Some((ra, rb));
526                 }
527             },
528             (&Kind::End(a, _), &Kind::Start(b, _)) if a != Bound::Included(b) => (),
529             _ => return Some((a.range(), b.range())),
530         }
531     }
532
533     None
534 }