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