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