]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/matches.rs
Merge pull request #2284 from rust-lang-nursery/new-macro
[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::{self, Ty};
5 use rustc::ty::subst::Substs;
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::ast::NodeId;
12 use syntax::codemap::Span;
13 use utils::paths;
14 use utils::{expr_block, in_external_macro, is_allowed, is_expn_of, match_qpath, match_type, remove_blocks,
15             snippet, span_lint_and_sugg, span_lint_and_then, span_note_and_lint, walk_ptrs_ty};
16 use utils::sugg::Sugg;
17
18 /// **What it does:** Checks for matches with a single arm where an `if let`
19 /// will usually suffice.
20 ///
21 /// **Why is this bad?** Just readability – `if let` nests less than a `match`.
22 ///
23 /// **Known problems:** None.
24 ///
25 /// **Example:**
26 /// ```rust
27 /// match x {
28 ///     Some(ref foo) => bar(foo),
29 ///     _ => ()
30 /// }
31 /// ```
32 declare_lint! {
33     pub SINGLE_MATCH,
34     Warn,
35     "a match statement with a single nontrivial arm (i.e. where the other arm \
36      is `_ => {}`) instead of `if let`"
37 }
38
39 /// **What it does:** Checks for matches with a two arms where an `if let` will
40 /// usually suffice.
41 ///
42 /// **Why is this bad?** Just readability – `if let` nests less than a `match`.
43 ///
44 /// **Known problems:** Personal style preferences may differ.
45 ///
46 /// **Example:**
47 /// ```rust
48 /// match x {
49 ///     Some(ref foo) => bar(foo),
50 ///     _ => bar(other_ref),
51 /// }
52 /// ```
53 declare_lint! {
54     pub SINGLE_MATCH_ELSE,
55     Allow,
56     "a match statement with a two arms where the second arm's pattern is a wildcard \
57      instead of `if let`"
58 }
59
60 /// **What it does:** Checks for matches where all arms match a reference,
61 /// suggesting to remove the reference and deref the matched expression
62 /// instead. It also checks for `if let &foo = bar` blocks.
63 ///
64 /// **Why is this bad?** It just makes the code less readable. That reference
65 /// destructuring adds nothing to the code.
66 ///
67 /// **Known problems:** None.
68 ///
69 /// **Example:**
70 /// ```rust
71 /// match x {
72 ///     &A(ref y) => foo(y),
73 ///     &B => bar(),
74 ///     _ => frob(&x),
75 /// }
76 /// ```
77 declare_lint! {
78     pub MATCH_REF_PATS,
79     Warn,
80     "a match or `if let` with all arms prefixed with `&` instead of deref-ing the match expression"
81 }
82
83 /// **What it does:** Checks for matches where match expression is a `bool`. It
84 /// suggests to replace the expression with an `if...else` block.
85 ///
86 /// **Why is this bad?** It makes the code less readable.
87 ///
88 /// **Known problems:** None.
89 ///
90 /// **Example:**
91 /// ```rust
92 /// let condition: bool = true;
93 /// match condition {
94 ///     true => foo(),
95 ///     false => bar(),
96 /// }
97 /// ```
98 declare_lint! {
99     pub MATCH_BOOL,
100     Warn,
101     "a match on a boolean expression instead of an `if..else` block"
102 }
103
104 /// **What it does:** Checks for overlapping match arms.
105 ///
106 /// **Why is this bad?** It is likely to be an error and if not, makes the code
107 /// less obvious.
108 ///
109 /// **Known problems:** None.
110 ///
111 /// **Example:**
112 /// ```rust
113 /// let x = 5;
114 /// match x {
115 ///     1 ... 10 => println!("1 ... 10"),
116 ///     5 ... 15 => println!("5 ... 15"),
117 ///     _ => (),
118 /// }
119 /// ```
120 declare_lint! {
121     pub MATCH_OVERLAPPING_ARM,
122     Warn,
123     "a match with overlapping arms"
124 }
125
126 /// **What it does:** Checks for arm which matches all errors with `Err(_)`
127 /// and take drastic actions like `panic!`.
128 ///
129 /// **Why is this bad?** It is generally a bad practice, just like
130 /// catching all exceptions in java with `catch(Exception)`
131 ///
132 /// **Known problems:** None.
133 ///
134 /// **Example:**
135 /// ```rust
136 /// let x : Result(i32, &str) = Ok(3);
137 /// match x {
138 ///     Ok(_) => println!("ok"),
139 ///     Err(_) => panic!("err"),
140 /// }
141 /// ```
142 declare_lint! {
143     pub MATCH_WILD_ERR_ARM,
144     Warn,
145     "a match with `Err(_)` arm and take drastic actions"
146 }
147
148 /// **What it does:** Checks for match which is used to add a reference to an
149 /// `Option` value.
150 ///
151 /// **Why is this bad?** Using `as_ref()` or `as_mut()` instead is shorter.
152 ///
153 /// **Known problems:** None.
154 ///
155 /// **Example:**
156 /// ```rust
157 /// let x: Option<()> = None;
158 /// let r: Option<&()> = match x {
159 ///   None => None,
160 ///   Some(ref v) => Some(v),
161 /// };
162 /// ```
163 declare_lint! {
164     pub MATCH_AS_REF,
165     Warn,
166     "a match on an Option value instead of using `as_ref()` or `as_mut`"
167 }
168
169 #[allow(missing_copy_implementations)]
170 pub struct MatchPass;
171
172 impl LintPass for MatchPass {
173     fn get_lints(&self) -> LintArray {
174         lint_array!(
175             SINGLE_MATCH,
176             MATCH_REF_PATS,
177             MATCH_BOOL,
178             SINGLE_MATCH_ELSE,
179             MATCH_OVERLAPPING_ARM,
180             MATCH_WILD_ERR_ARM,
181             MATCH_AS_REF
182         )
183     }
184 }
185
186 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MatchPass {
187     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
188         if in_external_macro(cx, expr.span) {
189             return;
190         }
191         if let ExprMatch(ref ex, ref arms, MatchSource::Normal) = expr.node {
192             check_single_match(cx, ex, arms, expr);
193             check_match_bool(cx, ex, arms, expr);
194             check_overlapping_arms(cx, ex, arms);
195             check_wild_err_arm(cx, ex, arms);
196             check_match_as_ref(cx, ex, arms, expr);
197         }
198         if let ExprMatch(ref ex, ref arms, source) = expr.node {
199             check_match_ref_pats(cx, ex, arms, source, expr);
200         }
201     }
202 }
203
204 #[cfg_attr(rustfmt, rustfmt_skip)]
205 fn check_single_match(cx: &LateContext, ex: &Expr, arms: &[Arm], expr: &Expr) {
206     if arms.len() == 2 &&
207       arms[0].pats.len() == 1 && arms[0].guard.is_none() &&
208       arms[1].pats.len() == 1 && arms[1].guard.is_none() {
209         let els = remove_blocks(&arms[1].body);
210         let els = if is_unit_expr(els) {
211             None
212         } else if let ExprBlock(_) = els.node {
213             // matches with blocks that contain statements are prettier as `if let + else`
214             Some(els)
215         } else {
216             // allow match arms with just expressions
217             return;
218         };
219         let ty = cx.tables.expr_ty(ex);
220         if ty.sty != ty::TyBool || is_allowed(cx, MATCH_BOOL, ex.id) {
221             check_single_match_single_pattern(cx, ex, arms, expr, els);
222             check_single_match_opt_like(cx, ex, arms, expr, ty, els);
223         }
224     }
225 }
226
227 fn check_single_match_single_pattern(cx: &LateContext, ex: &Expr, arms: &[Arm], expr: &Expr, els: Option<&Expr>) {
228     if arms[1].pats[0].node == PatKind::Wild {
229         report_single_match_single_pattern(cx, ex, arms, expr, els);
230     }
231 }
232
233 fn report_single_match_single_pattern(cx: &LateContext, ex: &Expr, arms: &[Arm], expr: &Expr, els: Option<&Expr>) {
234     let lint = if els.is_some() {
235         SINGLE_MATCH_ELSE
236     } else {
237         SINGLE_MATCH
238     };
239     let els_str = els.map_or(String::new(), |els| format!(" else {}", expr_block(cx, els, None, "..")));
240     span_lint_and_sugg(
241         cx,
242         lint,
243         expr.span,
244         "you seem to be trying to use match for destructuring a single pattern. Consider using `if \
245          let`",
246         "try this",
247         format!(
248             "if let {} = {} {}{}",
249             snippet(cx, arms[0].pats[0].span, ".."),
250             snippet(cx, ex.span, ".."),
251             expr_block(cx, &arms[0].body, None, ".."),
252             els_str
253         ),
254     );
255 }
256
257 fn check_single_match_opt_like(cx: &LateContext, ex: &Expr, arms: &[Arm], expr: &Expr, ty: Ty, els: Option<&Expr>) {
258     // list of candidate Enums we know will never get any more members
259     let candidates = &[
260         (&paths::COW, "Borrowed"),
261         (&paths::COW, "Cow::Borrowed"),
262         (&paths::COW, "Cow::Owned"),
263         (&paths::COW, "Owned"),
264         (&paths::OPTION, "None"),
265         (&paths::RESULT, "Err"),
266         (&paths::RESULT, "Ok"),
267     ];
268
269     let path = match arms[1].pats[0].node {
270         PatKind::TupleStruct(ref path, ref inner, _) => {
271             // contains any non wildcard patterns? e.g. Err(err)
272             if inner.iter().any(|pat| pat.node != PatKind::Wild) {
273                 return;
274             }
275             print::to_string(print::NO_ANN, |s| s.print_qpath(path, false))
276         },
277         PatKind::Binding(BindingAnnotation::Unannotated, _, ident, None) => ident.node.to_string(),
278         PatKind::Path(ref path) => print::to_string(print::NO_ANN, |s| s.print_qpath(path, false)),
279         _ => return,
280     };
281
282     for &(ty_path, pat_path) in candidates {
283         if path == *pat_path && match_type(cx, ty, ty_path) {
284             report_single_match_single_pattern(cx, ex, arms, expr, els);
285         }
286     }
287 }
288
289 fn check_match_bool(cx: &LateContext, ex: &Expr, arms: &[Arm], expr: &Expr) {
290     // type of expression == bool
291     if cx.tables.expr_ty(ex).sty == ty::TyBool {
292         span_lint_and_then(
293             cx,
294             MATCH_BOOL,
295             expr.span,
296             "you seem to be trying to match on a boolean expression",
297             move |db| {
298                 if arms.len() == 2 && arms[0].pats.len() == 1 {
299                     // no guards
300                     let exprs = if let PatKind::Lit(ref arm_bool) = arms[0].pats[0].node {
301                         if let ExprLit(ref lit) = arm_bool.node {
302                             match lit.node {
303                                 LitKind::Bool(true) => Some((&*arms[0].body, &*arms[1].body)),
304                                 LitKind::Bool(false) => Some((&*arms[1].body, &*arms[0].body)),
305                                 _ => None,
306                             }
307                         } else {
308                             None
309                         }
310                     } else {
311                         None
312                     };
313
314                     if let Some((true_expr, false_expr)) = exprs {
315                         let sugg = match (is_unit_expr(true_expr), is_unit_expr(false_expr)) {
316                             (false, false) => Some(format!(
317                                 "if {} {} else {}",
318                                 snippet(cx, ex.span, "b"),
319                                 expr_block(cx, true_expr, None, ".."),
320                                 expr_block(cx, false_expr, None, "..")
321                             )),
322                             (false, true) => Some(format!(
323                                 "if {} {}",
324                                 snippet(cx, ex.span, "b"),
325                                 expr_block(cx, true_expr, None, "..")
326                             )),
327                             (true, false) => {
328                                 let test = Sugg::hir(cx, ex, "..");
329                                 Some(format!("if {} {}", !test, expr_block(cx, false_expr, None, "..")))
330                             },
331                             (true, true) => None,
332                         };
333
334                         if let Some(sugg) = sugg {
335                             db.span_suggestion(expr.span, "consider using an if/else expression", sugg);
336                         }
337                     }
338                 }
339             },
340         );
341     }
342 }
343
344 fn check_overlapping_arms<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ex: &'tcx Expr, arms: &'tcx [Arm]) {
345     if arms.len() >= 2 && cx.tables.expr_ty(ex).is_integral() {
346         let ranges = all_ranges(cx, arms, ex.id);
347         let type_ranges = type_ranges(&ranges);
348         if !type_ranges.is_empty() {
349             if let Some((start, end)) = overlapping(&type_ranges) {
350                 span_note_and_lint(
351                     cx,
352                     MATCH_OVERLAPPING_ARM,
353                     start.span,
354                     "some ranges overlap",
355                     end.span,
356                     "overlaps with this",
357                 );
358             }
359         }
360     }
361 }
362
363 fn check_wild_err_arm(cx: &LateContext, ex: &Expr, arms: &[Arm]) {
364     let ex_ty = walk_ptrs_ty(cx.tables.expr_ty(ex));
365     if match_type(cx, ex_ty, &paths::RESULT) {
366         for arm in arms {
367             if let PatKind::TupleStruct(ref path, ref inner, _) = arm.pats[0].node {
368                 let path_str = print::to_string(print::NO_ANN, |s| s.print_qpath(path, false));
369                 if_chain! {
370                     if path_str == "Err";
371                     if inner.iter().any(|pat| pat.node == PatKind::Wild);
372                     if let ExprBlock(ref block) = arm.body.node;
373                     if is_panic_block(block);
374                     then {
375                         // `Err(_)` arm with `panic!` found
376                         span_note_and_lint(cx,
377                                            MATCH_WILD_ERR_ARM,
378                                            arm.pats[0].span,
379                                            "Err(_) will match all errors, maybe not a good idea",
380                                            arm.pats[0].span,
381                                            "to remove this warning, match each error seperately \
382                                             or use unreachable macro");
383                     }
384                 }
385             }
386         }
387     }
388 }
389
390 // If the block contains only a `panic!` macro (as expression or statement)
391 fn is_panic_block(block: &Block) -> bool {
392     match (&block.expr, block.stmts.len(), block.stmts.first()) {
393         (&Some(ref exp), 0, _) => {
394             is_expn_of(exp.span, "panic").is_some() && is_expn_of(exp.span, "unreachable").is_none()
395         },
396         (&None, 1, Some(stmt)) => {
397             is_expn_of(stmt.span, "panic").is_some() && is_expn_of(stmt.span, "unreachable").is_none()
398         },
399         _ => false,
400     }
401 }
402
403 fn check_match_ref_pats(cx: &LateContext, ex: &Expr, arms: &[Arm], source: MatchSource, expr: &Expr) {
404     if has_only_ref_pats(arms) {
405         if let ExprAddrOf(Mutability::MutImmutable, ref inner) = ex.node {
406             span_lint_and_then(
407                 cx,
408                 MATCH_REF_PATS,
409                 expr.span,
410                 "you don't need to add `&` to both the expression and the patterns",
411                 |db| {
412                     let inner = Sugg::hir(cx, inner, "..");
413                     let template = match_template(expr.span, source, &inner);
414                     db.span_suggestion(expr.span, "try", template);
415                 },
416             );
417         } else {
418             span_lint_and_then(
419                 cx,
420                 MATCH_REF_PATS,
421                 expr.span,
422                 "you don't need to add `&` to all patterns",
423                 |db| {
424                     let ex = Sugg::hir(cx, ex, "..");
425                     let template = match_template(expr.span, source, &ex.deref());
426                     db.span_suggestion(
427                         expr.span,
428                         "instead of prefixing all patterns with `&`, you can dereference the expression",
429                         template,
430                     );
431                 },
432             );
433         }
434     }
435 }
436
437 fn check_match_as_ref(cx: &LateContext, ex: &Expr, arms: &[Arm], expr: &Expr) {
438     if arms.len() == 2 &&
439         arms[0].pats.len() == 1 && arms[0].guard.is_none() &&
440         arms[1].pats.len() == 1 && arms[1].guard.is_none() {
441         let arm_ref: Option<BindingAnnotation> = if is_none_arm(&arms[0]) {
442             is_ref_some_arm(&arms[1])
443         } else if is_none_arm(&arms[1]) {
444             is_ref_some_arm(&arms[0])
445         } else {
446             None
447         };
448         if let Some(rb) = arm_ref {
449             let suggestion = if rb == BindingAnnotation::Ref { "as_ref" } else { "as_mut" };
450             span_lint_and_sugg(
451                 cx,
452                 MATCH_AS_REF,
453                 expr.span,
454                 &format!("use {}() instead", suggestion),
455                 "try this",
456                 format!("{}.{}()", snippet(cx, ex.span, "_"), suggestion)
457             )
458         }
459     }
460 }
461
462 /// Get all arms that are unbounded `PatRange`s.
463 fn all_ranges<'a, 'tcx>(
464     cx: &LateContext<'a, 'tcx>,
465     arms: &'tcx [Arm],
466     id: NodeId,
467 ) -> Vec<SpannedRange<&'tcx ty::Const<'tcx>>> {
468     let parent_item = cx.tcx.hir.get_parent(id);
469     let parent_def_id = cx.tcx.hir.local_def_id(parent_item);
470     let substs = Substs::identity_for_item(cx.tcx, parent_def_id);
471     let constcx = ConstContext::new(cx.tcx, cx.param_env.and(substs), cx.tables);
472     arms.iter()
473         .flat_map(|arm| {
474             if let Arm {
475                 ref pats,
476                 guard: None,
477                 ..
478             } = *arm
479             {
480                 pats.iter()
481             } else {
482                 [].iter()
483             }.filter_map(|pat| {
484                 if_chain! {
485                     if let PatKind::Range(ref lhs, ref rhs, ref range_end) = pat.node;
486                     if let Ok(lhs) = constcx.eval(lhs);
487                     if let Ok(rhs) = constcx.eval(rhs);
488                     then {
489                         let rhs = match *range_end {
490                             RangeEnd::Included => Bound::Included(rhs),
491                             RangeEnd::Excluded => Bound::Excluded(rhs),
492                         };
493                         return Some(SpannedRange { span: pat.span, node: (lhs, rhs) });
494                     }
495                 }
496
497                 if_chain! {
498                     if let PatKind::Lit(ref value) = pat.node;
499                     if let Ok(value) = constcx.eval(value);
500                     then {
501                         return Some(SpannedRange { span: pat.span, node: (value, Bound::Included(value)) });
502                     }
503                 }
504
505                 None
506             })
507         })
508         .collect()
509 }
510
511 #[derive(Debug, Eq, PartialEq)]
512 pub struct SpannedRange<T> {
513     pub span: Span,
514     pub node: (T, Bound<T>),
515 }
516
517 type TypedRanges = Vec<SpannedRange<ConstInt>>;
518
519 /// Get all `Int` ranges or all `Uint` ranges. Mixed types are an error anyway
520 /// and other types than
521 /// `Uint` and `Int` probably don't make sense.
522 fn type_ranges(ranges: &[SpannedRange<&ty::Const>]) -> TypedRanges {
523     ranges
524         .iter()
525         .filter_map(|range| match range.node {
526             (
527                 &ty::Const {
528                     val: ConstVal::Integral(start),
529                     ..
530                 },
531                 Bound::Included(&ty::Const {
532                     val: ConstVal::Integral(end),
533                     ..
534                 }),
535             ) => Some(SpannedRange {
536                 span: range.span,
537                 node: (start, Bound::Included(end)),
538             }),
539             (
540                 &ty::Const {
541                     val: ConstVal::Integral(start),
542                     ..
543                 },
544                 Bound::Excluded(&ty::Const {
545                     val: ConstVal::Integral(end),
546                     ..
547                 }),
548             ) => Some(SpannedRange {
549                 span: range.span,
550                 node: (start, Bound::Excluded(end)),
551             }),
552             (
553                 &ty::Const {
554                     val: ConstVal::Integral(start),
555                     ..
556                 },
557                 Bound::Unbounded,
558             ) => Some(SpannedRange {
559                 span: range.span,
560                 node: (start, Bound::Unbounded),
561             }),
562             _ => None,
563         })
564         .collect()
565 }
566
567 fn is_unit_expr(expr: &Expr) -> bool {
568     match expr.node {
569         ExprTup(ref v) if v.is_empty() => true,
570         ExprBlock(ref b) if b.stmts.is_empty() && b.expr.is_none() => true,
571         _ => false,
572     }
573 }
574
575 // Checks if arm has the form `None => None`
576 fn is_none_arm(arm: &Arm) -> bool {
577     match arm.pats[0].node {
578         PatKind::Path(ref path) if match_qpath(path, &paths::OPTION_NONE) => true,
579         _ => false,
580     }
581 }
582
583 // Checks if arm has the form `Some(ref v) => Some(v)` (checks for `ref` and `ref mut`)
584 fn is_ref_some_arm(arm: &Arm) -> Option<BindingAnnotation> {
585     if_chain! {
586         if let PatKind::TupleStruct(ref path, ref pats, _) = arm.pats[0].node;
587         if pats.len() == 1 && match_qpath(path, &paths::OPTION_SOME);
588         if let PatKind::Binding(rb, _, ref ident, _) = pats[0].node;
589         if rb == BindingAnnotation::Ref || rb == BindingAnnotation::RefMut;
590         if let ExprCall(ref e, ref args) = remove_blocks(&arm.body).node;
591         if let ExprPath(ref some_path) = e.node;
592         if match_qpath(some_path, &paths::OPTION_SOME) && args.len() == 1;
593         if let ExprPath(ref qpath) = args[0].node;
594         if let &QPath::Resolved(_, ref path2) = qpath;
595         if path2.segments.len() == 1 && ident.node == path2.segments[0].name;
596         then {
597             return Some(rb)
598         }
599     }
600     None
601 }
602
603 fn has_only_ref_pats(arms: &[Arm]) -> bool {
604     let mapped = arms.iter()
605         .flat_map(|a| &a.pats)
606         .map(|p| {
607             match p.node {
608                 PatKind::Ref(..) => Some(true), // &-patterns
609                 PatKind::Wild => Some(false),   // an "anything" wildcard is also fine
610                 _ => None,                      // any other pattern is not fine
611             }
612         })
613         .collect::<Option<Vec<bool>>>();
614     // look for Some(v) where there's at least one true element
615     mapped.map_or(false, |v| v.iter().any(|el| *el))
616 }
617
618 fn match_template(span: Span, source: MatchSource, expr: &Sugg) -> String {
619     match source {
620         MatchSource::Normal => format!("match {} {{ .. }}", expr),
621         MatchSource::IfLetDesugar { .. } => format!("if let .. = {} {{ .. }}", expr),
622         MatchSource::WhileLetDesugar => format!("while let .. = {} {{ .. }}", expr),
623         MatchSource::ForLoopDesugar => span_bug!(span, "for loop desugared to match with &-patterns!"),
624         MatchSource::TryDesugar => span_bug!(span, "`?` operator desugared to match with &-patterns!"),
625     }
626 }
627
628 pub fn overlapping<T>(ranges: &[SpannedRange<T>]) -> Option<(&SpannedRange<T>, &SpannedRange<T>)>
629 where
630     T: Copy + Ord,
631 {
632     #[derive(Copy, Clone, Debug, Eq, PartialEq)]
633     enum Kind<'a, T: 'a> {
634         Start(T, &'a SpannedRange<T>),
635         End(Bound<T>, &'a SpannedRange<T>),
636     }
637
638     impl<'a, T: Copy> Kind<'a, T> {
639         fn range(&self) -> &'a SpannedRange<T> {
640             match *self {
641                 Kind::Start(_, r) | Kind::End(_, r) => r,
642             }
643         }
644
645         fn value(self) -> Bound<T> {
646             match self {
647                 Kind::Start(t, _) => Bound::Included(t),
648                 Kind::End(t, _) => t,
649             }
650         }
651     }
652
653     impl<'a, T: Copy + Ord> PartialOrd for Kind<'a, T> {
654         fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
655             Some(self.cmp(other))
656         }
657     }
658
659     impl<'a, T: Copy + Ord> Ord for Kind<'a, T> {
660         fn cmp(&self, other: &Self) -> Ordering {
661             match (self.value(), other.value()) {
662                 (Bound::Included(a), Bound::Included(b)) | (Bound::Excluded(a), Bound::Excluded(b)) => a.cmp(&b),
663                 // Range patterns cannot be unbounded (yet)
664                 (Bound::Unbounded, _) | (_, Bound::Unbounded) => unimplemented!(),
665                 (Bound::Included(a), Bound::Excluded(b)) => match a.cmp(&b) {
666                     Ordering::Equal => Ordering::Greater,
667                     other => other,
668                 },
669                 (Bound::Excluded(a), Bound::Included(b)) => match a.cmp(&b) {
670                     Ordering::Equal => Ordering::Less,
671                     other => other,
672                 },
673             }
674         }
675     }
676
677     let mut values = Vec::with_capacity(2 * ranges.len());
678
679     for r in ranges {
680         values.push(Kind::Start(r.node.0, r));
681         values.push(Kind::End(r.node.1, r));
682     }
683
684     values.sort();
685
686     for (a, b) in values.iter().zip(values.iter().skip(1)) {
687         match (a, b) {
688             (&Kind::Start(_, ra), &Kind::End(_, rb)) => if ra.node != rb.node {
689                 return Some((ra, rb));
690             },
691             (&Kind::End(a, _), &Kind::Start(b, _)) if a != Bound::Included(b) => (),
692             _ => return Some((a.range(), b.range())),
693         }
694     }
695
696     None
697 }