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