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