]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/matches.rs
Auto merge of #3725 - mikerite:fix-2728, 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 /// **What it does:** Checks for wildcard enum matches using `_`.
191 ///
192 /// **Why is this bad?** New enum variants added by library updates can be missed.
193 ///
194 /// **Known problems:** Nested wildcards a la `Foo(_)` are currently not detected.
195 ///
196 /// **Example:**
197 /// ```rust
198 /// match x {
199 ///     A => {},
200 ///     _ => {},
201 /// }
202 /// ```
203 declare_clippy_lint! {
204     pub WILDCARD_ENUM_MATCH_ARM,
205     restriction,
206     "a wildcard enum match arm using `_`"
207 }
208
209 #[allow(missing_copy_implementations)]
210 pub struct MatchPass;
211
212 impl LintPass for MatchPass {
213     fn get_lints(&self) -> LintArray {
214         lint_array!(
215             SINGLE_MATCH,
216             MATCH_REF_PATS,
217             MATCH_BOOL,
218             SINGLE_MATCH_ELSE,
219             MATCH_OVERLAPPING_ARM,
220             MATCH_WILD_ERR_ARM,
221             MATCH_AS_REF,
222             WILDCARD_ENUM_MATCH_ARM
223         )
224     }
225
226     fn name(&self) -> &'static str {
227         "Matches"
228     }
229 }
230
231 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MatchPass {
232     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
233         if in_external_macro(cx.sess(), expr.span) {
234             return;
235         }
236         if let ExprKind::Match(ref ex, ref arms, MatchSource::Normal) = expr.node {
237             check_single_match(cx, ex, arms, expr);
238             check_match_bool(cx, ex, arms, expr);
239             check_overlapping_arms(cx, ex, arms);
240             check_wild_err_arm(cx, ex, arms);
241             check_wild_enum_match(cx, ex, arms);
242             check_match_as_ref(cx, ex, arms, expr);
243         }
244         if let ExprKind::Match(ref ex, ref arms, _) = expr.node {
245             check_match_ref_pats(cx, ex, arms, expr);
246         }
247     }
248 }
249
250 #[rustfmt::skip]
251 fn check_single_match(cx: &LateContext<'_, '_>, ex: &Expr, arms: &[Arm], expr: &Expr) {
252     if arms.len() == 2 &&
253       arms[0].pats.len() == 1 && arms[0].guard.is_none() &&
254       arms[1].pats.len() == 1 && arms[1].guard.is_none() {
255         let els = remove_blocks(&arms[1].body);
256         let els = if is_unit_expr(els) {
257             None
258         } else if let ExprKind::Block(_, _) = els.node {
259             // matches with blocks that contain statements are prettier as `if let + else`
260             Some(els)
261         } else {
262             // allow match arms with just expressions
263             return;
264         };
265         let ty = cx.tables.expr_ty(ex);
266         if ty.sty != ty::Bool || is_allowed(cx, MATCH_BOOL, ex.id) {
267             check_single_match_single_pattern(cx, ex, arms, expr, els);
268             check_single_match_opt_like(cx, ex, arms, expr, ty, els);
269         }
270     }
271 }
272
273 fn check_single_match_single_pattern(
274     cx: &LateContext<'_, '_>,
275     ex: &Expr,
276     arms: &[Arm],
277     expr: &Expr,
278     els: Option<&Expr>,
279 ) {
280     if is_wild(&arms[1].pats[0]) {
281         report_single_match_single_pattern(cx, ex, arms, expr, els);
282     }
283 }
284
285 fn report_single_match_single_pattern(
286     cx: &LateContext<'_, '_>,
287     ex: &Expr,
288     arms: &[Arm],
289     expr: &Expr,
290     els: Option<&Expr>,
291 ) {
292     let lint = if els.is_some() { SINGLE_MATCH_ELSE } else { SINGLE_MATCH };
293     let els_str = els.map_or(String::new(), |els| {
294         format!(" else {}", expr_block(cx, els, None, ".."))
295     });
296     span_lint_and_sugg(
297         cx,
298         lint,
299         expr.span,
300         "you seem to be trying to use match for destructuring a single pattern. Consider using `if \
301          let`",
302         "try this",
303         format!(
304             "if let {} = {} {}{}",
305             snippet(cx, arms[0].pats[0].span, ".."),
306             snippet(cx, ex.span, ".."),
307             expr_block(cx, &arms[0].body, None, ".."),
308             els_str,
309         ),
310         Applicability::HasPlaceholders,
311     );
312 }
313
314 fn check_single_match_opt_like(
315     cx: &LateContext<'_, '_>,
316     ex: &Expr,
317     arms: &[Arm],
318     expr: &Expr,
319     ty: Ty<'_>,
320     els: Option<&Expr>,
321 ) {
322     // list of candidate Enums we know will never get any more members
323     let candidates = &[
324         (&paths::COW, "Borrowed"),
325         (&paths::COW, "Cow::Borrowed"),
326         (&paths::COW, "Cow::Owned"),
327         (&paths::COW, "Owned"),
328         (&paths::OPTION, "None"),
329         (&paths::RESULT, "Err"),
330         (&paths::RESULT, "Ok"),
331     ];
332
333     let path = match arms[1].pats[0].node {
334         PatKind::TupleStruct(ref path, ref inner, _) => {
335             // contains any non wildcard patterns? e.g. Err(err)
336             if !inner.iter().all(is_wild) {
337                 return;
338             }
339             print::to_string(print::NO_ANN, |s| s.print_qpath(path, false))
340         },
341         PatKind::Binding(BindingAnnotation::Unannotated, .., ident, None) => ident.to_string(),
342         PatKind::Path(ref path) => print::to_string(print::NO_ANN, |s| s.print_qpath(path, false)),
343         _ => return,
344     };
345
346     for &(ty_path, pat_path) in candidates {
347         if path == *pat_path && match_type(cx, ty, ty_path) {
348             report_single_match_single_pattern(cx, ex, arms, expr, els);
349         }
350     }
351 }
352
353 fn check_match_bool(cx: &LateContext<'_, '_>, ex: &Expr, arms: &[Arm], expr: &Expr) {
354     // type of expression == bool
355     if cx.tables.expr_ty(ex).sty == ty::Bool {
356         span_lint_and_then(
357             cx,
358             MATCH_BOOL,
359             expr.span,
360             "you seem to be trying to match on a boolean expression",
361             move |db| {
362                 if arms.len() == 2 && arms[0].pats.len() == 1 {
363                     // no guards
364                     let exprs = if let PatKind::Lit(ref arm_bool) = arms[0].pats[0].node {
365                         if let ExprKind::Lit(ref lit) = arm_bool.node {
366                             match lit.node {
367                                 LitKind::Bool(true) => Some((&*arms[0].body, &*arms[1].body)),
368                                 LitKind::Bool(false) => Some((&*arms[1].body, &*arms[0].body)),
369                                 _ => None,
370                             }
371                         } else {
372                             None
373                         }
374                     } else {
375                         None
376                     };
377
378                     if let Some((true_expr, false_expr)) = exprs {
379                         let sugg = match (is_unit_expr(true_expr), is_unit_expr(false_expr)) {
380                             (false, false) => Some(format!(
381                                 "if {} {} else {}",
382                                 snippet(cx, ex.span, "b"),
383                                 expr_block(cx, true_expr, None, ".."),
384                                 expr_block(cx, false_expr, None, "..")
385                             )),
386                             (false, true) => Some(format!(
387                                 "if {} {}",
388                                 snippet(cx, ex.span, "b"),
389                                 expr_block(cx, true_expr, None, "..")
390                             )),
391                             (true, false) => {
392                                 let test = Sugg::hir(cx, ex, "..");
393                                 Some(format!("if {} {}", !test, expr_block(cx, false_expr, None, "..")))
394                             },
395                             (true, true) => None,
396                         };
397
398                         if let Some(sugg) = sugg {
399                             db.span_suggestion(
400                                 expr.span,
401                                 "consider using an if/else expression",
402                                 sugg,
403                                 Applicability::HasPlaceholders,
404                             );
405                         }
406                     }
407                 }
408             },
409         );
410     }
411 }
412
413 fn check_overlapping_arms<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ex: &'tcx Expr, arms: &'tcx [Arm]) {
414     if arms.len() >= 2 && cx.tables.expr_ty(ex).is_integral() {
415         let ranges = all_ranges(cx, arms);
416         let type_ranges = type_ranges(&ranges);
417         if !type_ranges.is_empty() {
418             if let Some((start, end)) = overlapping(&type_ranges) {
419                 span_note_and_lint(
420                     cx,
421                     MATCH_OVERLAPPING_ARM,
422                     start.span,
423                     "some ranges overlap",
424                     end.span,
425                     "overlaps with this",
426                 );
427             }
428         }
429     }
430 }
431
432 fn is_wild(pat: &impl std::ops::Deref<Target = Pat>) -> bool {
433     match pat.node {
434         PatKind::Wild => true,
435         _ => false,
436     }
437 }
438
439 fn check_wild_err_arm(cx: &LateContext<'_, '_>, ex: &Expr, arms: &[Arm]) {
440     let ex_ty = walk_ptrs_ty(cx.tables.expr_ty(ex));
441     if match_type(cx, ex_ty, &paths::RESULT) {
442         for arm in arms {
443             if let PatKind::TupleStruct(ref path, ref inner, _) = arm.pats[0].node {
444                 let path_str = print::to_string(print::NO_ANN, |s| s.print_qpath(path, false));
445                 if_chain! {
446                     if path_str == "Err";
447                     if inner.iter().any(is_wild);
448                     if let ExprKind::Block(ref block, _) = arm.body.node;
449                     if is_panic_block(block);
450                     then {
451                         // `Err(_)` arm with `panic!` found
452                         span_note_and_lint(cx,
453                                            MATCH_WILD_ERR_ARM,
454                                            arm.pats[0].span,
455                                            "Err(_) will match all errors, maybe not a good idea",
456                                            arm.pats[0].span,
457                                            "to remove this warning, match each error separately \
458                                             or use unreachable macro");
459                     }
460                 }
461             }
462         }
463     }
464 }
465
466 fn check_wild_enum_match(cx: &LateContext<'_, '_>, ex: &Expr, arms: &[Arm]) {
467     if cx.tables.expr_ty(ex).is_enum() {
468         for arm in arms {
469             if is_wild(&arm.pats[0]) {
470                 span_note_and_lint(
471                     cx,
472                     WILDCARD_ENUM_MATCH_ARM,
473                     arm.pats[0].span,
474                     "wildcard match will miss any future added variants.",
475                     arm.pats[0].span,
476                     "to resolve, match each variant explicitly",
477                 );
478             }
479         }
480     }
481 }
482
483 // If the block contains only a `panic!` macro (as expression or statement)
484 fn is_panic_block(block: &Block) -> bool {
485     match (&block.expr, block.stmts.len(), block.stmts.first()) {
486         (&Some(ref exp), 0, _) => {
487             is_expn_of(exp.span, "panic").is_some() && is_expn_of(exp.span, "unreachable").is_none()
488         },
489         (&None, 1, Some(stmt)) => {
490             is_expn_of(stmt.span, "panic").is_some() && is_expn_of(stmt.span, "unreachable").is_none()
491         },
492         _ => false,
493     }
494 }
495
496 fn check_match_ref_pats(cx: &LateContext<'_, '_>, ex: &Expr, arms: &[Arm], expr: &Expr) {
497     if has_only_ref_pats(arms) {
498         let mut suggs = Vec::new();
499         let (title, msg) = if let ExprKind::AddrOf(Mutability::MutImmutable, ref inner) = ex.node {
500             suggs.push((ex.span, Sugg::hir(cx, inner, "..").to_string()));
501             (
502                 "you don't need to add `&` to both the expression and the patterns",
503                 "try",
504             )
505         } else {
506             suggs.push((ex.span, Sugg::hir(cx, ex, "..").deref().to_string()));
507             (
508                 "you don't need to add `&` to all patterns",
509                 "instead of prefixing all patterns with `&`, you can dereference the expression",
510             )
511         };
512
513         suggs.extend(arms.iter().flat_map(|a| &a.pats).filter_map(|p| {
514             if let PatKind::Ref(ref refp, _) = p.node {
515                 Some((p.span, snippet(cx, refp.span, "..").to_string()))
516             } else {
517                 None
518             }
519         }));
520
521         span_lint_and_then(cx, MATCH_REF_PATS, expr.span, title, |db| {
522             if !in_macro(expr.span) {
523                 multispan_sugg(db, msg.to_owned(), suggs);
524             }
525         });
526     }
527 }
528
529 fn check_match_as_ref(cx: &LateContext<'_, '_>, ex: &Expr, arms: &[Arm], expr: &Expr) {
530     if arms.len() == 2
531         && arms[0].pats.len() == 1
532         && arms[0].guard.is_none()
533         && arms[1].pats.len() == 1
534         && arms[1].guard.is_none()
535     {
536         let arm_ref: Option<BindingAnnotation> = if is_none_arm(&arms[0]) {
537             is_ref_some_arm(&arms[1])
538         } else if is_none_arm(&arms[1]) {
539             is_ref_some_arm(&arms[0])
540         } else {
541             None
542         };
543         if let Some(rb) = arm_ref {
544             let suggestion = if rb == BindingAnnotation::Ref {
545                 "as_ref"
546             } else {
547                 "as_mut"
548             };
549             let mut applicability = Applicability::MachineApplicable;
550             span_lint_and_sugg(
551                 cx,
552                 MATCH_AS_REF,
553                 expr.span,
554                 &format!("use {}() instead", suggestion),
555                 "try this",
556                 format!(
557                     "{}.{}()",
558                     snippet_with_applicability(cx, ex.span, "_", &mut applicability),
559                     suggestion
560                 ),
561                 applicability,
562             )
563         }
564     }
565 }
566
567 /// Get all arms that are unbounded `PatRange`s.
568 fn all_ranges<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, arms: &'tcx [Arm]) -> Vec<SpannedRange<Constant>> {
569     arms.iter()
570         .flat_map(|arm| {
571             if let Arm {
572                 ref pats, guard: None, ..
573             } = *arm
574             {
575                 pats.iter()
576             } else {
577                 [].iter()
578             }
579             .filter_map(|pat| {
580                 if let PatKind::Range(ref lhs, ref rhs, ref range_end) = pat.node {
581                     let lhs = constant(cx, cx.tables, lhs)?.0;
582                     let rhs = constant(cx, cx.tables, rhs)?.0;
583                     let rhs = match *range_end {
584                         RangeEnd::Included => Bound::Included(rhs),
585                         RangeEnd::Excluded => Bound::Excluded(rhs),
586                     };
587                     return Some(SpannedRange {
588                         span: pat.span,
589                         node: (lhs, rhs),
590                     });
591                 }
592
593                 if let PatKind::Lit(ref value) = pat.node {
594                     let value = constant(cx, cx.tables, value)?.0;
595                     return Some(SpannedRange {
596                         span: pat.span,
597                         node: (value.clone(), Bound::Included(value)),
598                     });
599                 }
600
601                 None
602             })
603         })
604         .collect()
605 }
606
607 #[derive(Debug, Eq, PartialEq)]
608 pub struct SpannedRange<T> {
609     pub span: Span,
610     pub node: (T, Bound<T>),
611 }
612
613 type TypedRanges = Vec<SpannedRange<u128>>;
614
615 /// Get all `Int` ranges or all `Uint` ranges. Mixed types are an error anyway
616 /// and other types than
617 /// `Uint` and `Int` probably don't make sense.
618 fn type_ranges(ranges: &[SpannedRange<Constant>]) -> TypedRanges {
619     ranges
620         .iter()
621         .filter_map(|range| match range.node {
622             (Constant::Int(start), Bound::Included(Constant::Int(end))) => Some(SpannedRange {
623                 span: range.span,
624                 node: (start, Bound::Included(end)),
625             }),
626             (Constant::Int(start), Bound::Excluded(Constant::Int(end))) => Some(SpannedRange {
627                 span: range.span,
628                 node: (start, Bound::Excluded(end)),
629             }),
630             (Constant::Int(start), Bound::Unbounded) => Some(SpannedRange {
631                 span: range.span,
632                 node: (start, Bound::Unbounded),
633             }),
634             _ => None,
635         })
636         .collect()
637 }
638
639 fn is_unit_expr(expr: &Expr) -> bool {
640     match expr.node {
641         ExprKind::Tup(ref v) if v.is_empty() => true,
642         ExprKind::Block(ref b, _) if b.stmts.is_empty() && b.expr.is_none() => true,
643         _ => false,
644     }
645 }
646
647 // Checks if arm has the form `None => None`
648 fn is_none_arm(arm: &Arm) -> bool {
649     match arm.pats[0].node {
650         PatKind::Path(ref path) if match_qpath(path, &paths::OPTION_NONE) => true,
651         _ => false,
652     }
653 }
654
655 // Checks if arm has the form `Some(ref v) => Some(v)` (checks for `ref` and `ref mut`)
656 fn is_ref_some_arm(arm: &Arm) -> Option<BindingAnnotation> {
657     if_chain! {
658         if let PatKind::TupleStruct(ref path, ref pats, _) = arm.pats[0].node;
659         if pats.len() == 1 && match_qpath(path, &paths::OPTION_SOME);
660         if let PatKind::Binding(rb, .., ident, _) = pats[0].node;
661         if rb == BindingAnnotation::Ref || rb == BindingAnnotation::RefMut;
662         if let ExprKind::Call(ref e, ref args) = remove_blocks(&arm.body).node;
663         if let ExprKind::Path(ref some_path) = e.node;
664         if match_qpath(some_path, &paths::OPTION_SOME) && args.len() == 1;
665         if let ExprKind::Path(ref qpath) = args[0].node;
666         if let &QPath::Resolved(_, ref path2) = qpath;
667         if path2.segments.len() == 1 && ident.name == path2.segments[0].ident.name;
668         then {
669             return Some(rb)
670         }
671     }
672     None
673 }
674
675 fn has_only_ref_pats(arms: &[Arm]) -> bool {
676     let mapped = arms
677         .iter()
678         .flat_map(|a| &a.pats)
679         .map(|p| {
680             match p.node {
681                 PatKind::Ref(..) => Some(true), // &-patterns
682                 PatKind::Wild => Some(false),   // an "anything" wildcard is also fine
683                 _ => None,                      // any other pattern is not fine
684             }
685         })
686         .collect::<Option<Vec<bool>>>();
687     // look for Some(v) where there's at least one true element
688     mapped.map_or(false, |v| v.iter().any(|el| *el))
689 }
690
691 pub fn overlapping<T>(ranges: &[SpannedRange<T>]) -> Option<(&SpannedRange<T>, &SpannedRange<T>)>
692 where
693     T: Copy + Ord,
694 {
695     #[derive(Copy, Clone, Debug, Eq, PartialEq)]
696     enum Kind<'a, T: 'a> {
697         Start(T, &'a SpannedRange<T>),
698         End(Bound<T>, &'a SpannedRange<T>),
699     }
700
701     impl<'a, T: Copy> Kind<'a, T> {
702         fn range(&self) -> &'a SpannedRange<T> {
703             match *self {
704                 Kind::Start(_, r) | Kind::End(_, r) => r,
705             }
706         }
707
708         fn value(self) -> Bound<T> {
709             match self {
710                 Kind::Start(t, _) => Bound::Included(t),
711                 Kind::End(t, _) => t,
712             }
713         }
714     }
715
716     impl<'a, T: Copy + Ord> PartialOrd for Kind<'a, T> {
717         fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
718             Some(self.cmp(other))
719         }
720     }
721
722     impl<'a, T: Copy + Ord> Ord for Kind<'a, T> {
723         fn cmp(&self, other: &Self) -> Ordering {
724             match (self.value(), other.value()) {
725                 (Bound::Included(a), Bound::Included(b)) | (Bound::Excluded(a), Bound::Excluded(b)) => a.cmp(&b),
726                 // Range patterns cannot be unbounded (yet)
727                 (Bound::Unbounded, _) | (_, Bound::Unbounded) => unimplemented!(),
728                 (Bound::Included(a), Bound::Excluded(b)) => match a.cmp(&b) {
729                     Ordering::Equal => Ordering::Greater,
730                     other => other,
731                 },
732                 (Bound::Excluded(a), Bound::Included(b)) => match a.cmp(&b) {
733                     Ordering::Equal => Ordering::Less,
734                     other => other,
735                 },
736             }
737         }
738     }
739
740     let mut values = Vec::with_capacity(2 * ranges.len());
741
742     for r in ranges {
743         values.push(Kind::Start(r.node.0, r));
744         values.push(Kind::End(r.node.1, r));
745     }
746
747     values.sort();
748
749     for (a, b) in values.iter().zip(values.iter().skip(1)) {
750         match (a, b) {
751             (&Kind::Start(_, ra), &Kind::End(_, rb)) => {
752                 if ra.node != rb.node {
753                     return Some((ra, rb));
754                 }
755             },
756             (&Kind::End(a, _), &Kind::Start(b, _)) if a != Bound::Included(b) => (),
757             _ => return Some((a.range(), b.range())),
758         }
759     }
760
761     None
762 }