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