1 use crate::consts::{constant, miri_to_const, Constant};
2 use crate::utils::paths;
3 use crate::utils::sugg::Sugg;
5 expr_block, is_allowed, is_expn_of, match_qpath, match_type, match_var, multispan_sugg, remove_blocks, snippet,
6 snippet_with_applicability, span_help_and_lint, span_lint_and_sugg, span_lint_and_then, span_note_and_lint,
9 use if_chain::if_chain;
10 use rustc::hir::map::Map;
11 use rustc::lint::{in_external_macro, LateContext, LateLintPass, LintArray, LintContext, LintPass};
12 use rustc::ty::{self, Ty};
13 use rustc_errors::Applicability;
14 use rustc_hir::def::CtorKind;
15 use rustc_hir::intravisit::{walk_expr, NestedVisitorMap, Visitor};
17 use rustc_lint::{LateContext, LateLintPass, LintContext};
18 use rustc_session::{declare_lint_pass, declare_tool_lint};
19 use rustc_span::source_map::Span;
20 use rustc_span::symbol::Ident;
21 use std::cmp::Ordering;
22 use std::collections::Bound;
23 use syntax::ast::{self, LitKind};
25 declare_clippy_lint! {
26 /// **What it does:** Checks for matches with a single arm where an `if let`
27 /// will usually suffice.
29 /// **Why is this bad?** Just readability – `if let` nests less than a `match`.
31 /// **Known problems:** None.
35 /// # fn bar(stool: &str) {}
36 /// # let x = Some("abc");
38 /// Some(ref foo) => bar(foo),
44 "a `match` statement with a single nontrivial arm (i.e., where the other arm is `_ => {}`) instead of `if let`"
47 declare_clippy_lint! {
48 /// **What it does:** Checks for matches with two arms where an `if let else` will
51 /// **Why is this bad?** Just readability – `if let` nests less than a `match`.
53 /// **Known problems:** Personal style preferences may differ.
60 /// # fn bar(foo: &usize) {}
61 /// # let other_ref: usize = 1;
62 /// # let x: Option<&usize> = Some(&1);
64 /// Some(ref foo) => bar(foo),
65 /// _ => bar(&other_ref),
69 /// Using `if let` with `else`:
72 /// # fn bar(foo: &usize) {}
73 /// # let other_ref: usize = 1;
74 /// # let x: Option<&usize> = Some(&1);
75 /// if let Some(ref foo) = x {
81 pub SINGLE_MATCH_ELSE,
83 "a `match` statement with two arms where the second arm's pattern is a placeholder instead of a specific match pattern"
86 declare_clippy_lint! {
87 /// **What it does:** Checks for matches where all arms match a reference,
88 /// suggesting to remove the reference and deref the matched expression
89 /// instead. It also checks for `if let &foo = bar` blocks.
91 /// **Why is this bad?** It just makes the code less readable. That reference
92 /// destructuring adds nothing to the code.
94 /// **Known problems:** None.
99 /// &A(ref y) => foo(y),
106 "a `match` or `if let` with all arms prefixed with `&` instead of deref-ing the match expression"
109 declare_clippy_lint! {
110 /// **What it does:** Checks for matches where match expression is a `bool`. It
111 /// suggests to replace the expression with an `if...else` block.
113 /// **Why is this bad?** It makes the code less readable.
115 /// **Known problems:** None.
121 /// let condition: bool = true;
122 /// match condition {
127 /// Use if/else instead:
131 /// let condition: bool = true;
140 "a `match` on a boolean expression instead of an `if..else` block"
143 declare_clippy_lint! {
144 /// **What it does:** Checks for overlapping match arms.
146 /// **Why is this bad?** It is likely to be an error and if not, makes the code
149 /// **Known problems:** None.
155 /// 1...10 => println!("1 ... 10"),
156 /// 5...15 => println!("5 ... 15"),
160 pub MATCH_OVERLAPPING_ARM,
162 "a `match` with overlapping arms"
165 declare_clippy_lint! {
166 /// **What it does:** Checks for arm which matches all errors with `Err(_)`
167 /// and take drastic actions like `panic!`.
169 /// **Why is this bad?** It is generally a bad practice, just like
170 /// catching all exceptions in java with `catch(Exception)`
172 /// **Known problems:** None.
176 /// let x: Result<i32, &str> = Ok(3);
178 /// Ok(_) => println!("ok"),
179 /// Err(_) => panic!("err"),
182 pub MATCH_WILD_ERR_ARM,
184 "a `match` with `Err(_)` arm and take drastic actions"
187 declare_clippy_lint! {
188 /// **What it does:** Checks for match which is used to add a reference to an
191 /// **Why is this bad?** Using `as_ref()` or `as_mut()` instead is shorter.
193 /// **Known problems:** None.
197 /// let x: Option<()> = None;
198 /// let r: Option<&()> = match x {
200 /// Some(ref v) => Some(v),
205 "a `match` on an Option value instead of using `as_ref()` or `as_mut`"
208 declare_clippy_lint! {
209 /// **What it does:** Checks for wildcard enum matches using `_`.
211 /// **Why is this bad?** New enum variants added by library updates can be missed.
213 /// **Known problems:** Suggested replacements may be incorrect if guards exhaustively cover some
214 /// variants, and also may not use correct path to enum if it's not present in the current scope.
218 /// # enum Foo { A(usize), B(usize) }
219 /// # let x = Foo::B(1);
225 pub WILDCARD_ENUM_MATCH_ARM,
227 "a wildcard enum match arm using `_`"
230 declare_clippy_lint! {
231 /// **What it does:** Checks for wildcard pattern used with others patterns in same match arm.
233 /// **Why is this bad?** Wildcard pattern already covers any other pattern as it will match anyway.
234 /// It makes the code less readable, especially to spot wildcard pattern use in match arm.
236 /// **Known problems:** None.
245 pub WILDCARD_IN_OR_PATTERNS,
247 "a wildcard pattern used with others patterns in same match arm"
250 declare_lint_pass!(Matches => [
255 MATCH_OVERLAPPING_ARM,
258 WILDCARD_ENUM_MATCH_ARM,
259 WILDCARD_IN_OR_PATTERNS
262 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Matches {
263 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
264 if in_external_macro(cx.sess(), expr.span) {
267 if let ExprKind::Match(ref ex, ref arms, MatchSource::Normal) = expr.kind {
268 check_single_match(cx, ex, arms, expr);
269 check_match_bool(cx, ex, arms, expr);
270 check_overlapping_arms(cx, ex, arms);
271 check_wild_err_arm(cx, ex, arms);
272 check_wild_enum_match(cx, ex, arms);
273 check_match_as_ref(cx, ex, arms, expr);
274 check_wild_in_or_pats(cx, arms);
276 if let ExprKind::Match(ref ex, ref arms, _) = expr.kind {
277 check_match_ref_pats(cx, ex, arms, expr);
283 fn check_single_match(cx: &LateContext<'_, '_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
284 if arms.len() == 2 && arms[0].guard.is_none() && arms[1].guard.is_none() {
285 if let PatKind::Or(..) = arms[0].pat.kind {
286 // don't lint for or patterns for now, this makes
287 // the lint noisy in unnecessary situations
290 let els = remove_blocks(&arms[1].body);
291 let els = if is_unit_expr(els) {
293 } else if let ExprKind::Block(_, _) = els.kind {
294 // matches with blocks that contain statements are prettier as `if let + else`
297 // allow match arms with just expressions
300 let ty = cx.tables.expr_ty(ex);
301 if ty.kind != ty::Bool || is_allowed(cx, MATCH_BOOL, ex.hir_id) {
302 check_single_match_single_pattern(cx, ex, arms, expr, els);
303 check_single_match_opt_like(cx, ex, arms, expr, ty, els);
308 fn check_single_match_single_pattern(
309 cx: &LateContext<'_, '_>,
313 els: Option<&Expr<'_>>,
315 if is_wild(&arms[1].pat) {
316 report_single_match_single_pattern(cx, ex, arms, expr, els);
320 fn report_single_match_single_pattern(
321 cx: &LateContext<'_, '_>,
325 els: Option<&Expr<'_>>,
327 let lint = if els.is_some() { SINGLE_MATCH_ELSE } else { SINGLE_MATCH };
328 let els_str = els.map_or(String::new(), |els| {
329 format!(" else {}", expr_block(cx, els, None, ".."))
335 "you seem to be trying to use match for destructuring a single pattern. Consider using `if \
339 "if let {} = {} {}{}",
340 snippet(cx, arms[0].pat.span, ".."),
341 snippet(cx, ex.span, ".."),
342 expr_block(cx, &arms[0].body, None, ".."),
345 Applicability::HasPlaceholders,
349 fn check_single_match_opt_like(
350 cx: &LateContext<'_, '_>,
355 els: Option<&Expr<'_>>,
357 // list of candidate `Enum`s we know will never get any more members
359 (&paths::COW, "Borrowed"),
360 (&paths::COW, "Cow::Borrowed"),
361 (&paths::COW, "Cow::Owned"),
362 (&paths::COW, "Owned"),
363 (&paths::OPTION, "None"),
364 (&paths::RESULT, "Err"),
365 (&paths::RESULT, "Ok"),
368 let path = match arms[1].pat.kind {
369 PatKind::TupleStruct(ref path, ref inner, _) => {
370 // Contains any non wildcard patterns (e.g., `Err(err)`)?
371 if !inner.iter().all(is_wild) {
374 print::to_string(print::NO_ANN, |s| s.print_qpath(path, false))
376 PatKind::Binding(BindingAnnotation::Unannotated, .., ident, None) => ident.to_string(),
377 PatKind::Path(ref path) => print::to_string(print::NO_ANN, |s| s.print_qpath(path, false)),
381 for &(ty_path, pat_path) in candidates {
382 if path == *pat_path && match_type(cx, ty, ty_path) {
383 report_single_match_single_pattern(cx, ex, arms, expr, els);
388 fn check_match_bool(cx: &LateContext<'_, '_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
389 // Type of expression is `bool`.
390 if cx.tables.expr_ty(ex).kind == ty::Bool {
395 "you seem to be trying to match on a boolean expression",
399 let exprs = if let PatKind::Lit(ref arm_bool) = arms[0].pat.kind {
400 if let ExprKind::Lit(ref lit) = arm_bool.kind {
402 LitKind::Bool(true) => Some((&*arms[0].body, &*arms[1].body)),
403 LitKind::Bool(false) => Some((&*arms[1].body, &*arms[0].body)),
413 if let Some((true_expr, false_expr)) = exprs {
414 let sugg = match (is_unit_expr(true_expr), is_unit_expr(false_expr)) {
415 (false, false) => Some(format!(
417 snippet(cx, ex.span, "b"),
418 expr_block(cx, true_expr, None, ".."),
419 expr_block(cx, false_expr, None, "..")
421 (false, true) => Some(format!(
423 snippet(cx, ex.span, "b"),
424 expr_block(cx, true_expr, None, "..")
427 let test = Sugg::hir(cx, ex, "..");
428 Some(format!("if {} {}", !test, expr_block(cx, false_expr, None, "..")))
430 (true, true) => None,
433 if let Some(sugg) = sugg {
436 "consider using an `if`/`else` expression",
438 Applicability::HasPlaceholders,
448 fn check_overlapping_arms<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ex: &'tcx Expr<'_>, arms: &'tcx [Arm<'_>]) {
449 if arms.len() >= 2 && cx.tables.expr_ty(ex).is_integral() {
450 let ranges = all_ranges(cx, arms, cx.tables.expr_ty(ex));
451 let type_ranges = type_ranges(&ranges);
452 if !type_ranges.is_empty() {
453 if let Some((start, end)) = overlapping(&type_ranges) {
456 MATCH_OVERLAPPING_ARM,
458 "some ranges overlap",
460 "overlaps with this",
467 fn is_wild<'tcx>(pat: &impl std::ops::Deref<Target = Pat<'tcx>>) -> bool {
469 PatKind::Wild => true,
474 fn is_unused<'tcx>(ident: &'tcx Ident, body: &'tcx Expr<'_>) -> bool {
475 let mut visitor = UsedVisitor {
479 walk_expr(&mut visitor, body);
484 var: ast::Name, // var to look for
485 used: bool, // has the var been used otherwise?
488 impl<'tcx> Visitor<'tcx> for UsedVisitor {
489 type Map = Map<'tcx>;
491 fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
492 if match_var(expr, self.var) {
495 walk_expr(self, expr);
499 fn nested_visit_map(&mut self) -> NestedVisitorMap<'_, Self::Map> {
500 NestedVisitorMap::None
504 fn check_wild_err_arm(cx: &LateContext<'_, '_>, ex: &Expr<'_>, arms: &[Arm<'_>]) {
505 let ex_ty = walk_ptrs_ty(cx.tables.expr_ty(ex));
506 if match_type(cx, ex_ty, &paths::RESULT) {
508 if let PatKind::TupleStruct(ref path, ref inner, _) = arm.pat.kind {
509 let path_str = print::to_string(print::NO_ANN, |s| s.print_qpath(path, false));
510 if path_str == "Err" {
511 let mut matching_wild = inner.iter().any(is_wild);
512 let mut ident_bind_name = String::from("_");
514 // Looking for unused bindings (i.e.: `_e`)
515 inner.iter().for_each(|pat| {
516 if let PatKind::Binding(.., ident, None) = &pat.kind {
517 if ident.as_str().starts_with('_') && is_unused(ident, arm.body) {
518 ident_bind_name = (&ident.name.as_str()).to_string();
519 matching_wild = true;
526 if let ExprKind::Block(ref block, _) = arm.body.kind;
527 if is_panic_block(block);
529 // `Err(_)` or `Err(_e)` arm with `panic!` found
530 span_note_and_lint(cx,
533 &format!("`Err({})` will match all errors, maybe not a good idea", &ident_bind_name),
535 "to remove this warning, match each error separately \
536 or use `unreachable!` macro");
545 fn check_wild_enum_match(cx: &LateContext<'_, '_>, ex: &Expr<'_>, arms: &[Arm<'_>]) {
546 let ty = cx.tables.expr_ty(ex);
548 // If there isn't a nice closed set of possible values that can be conveniently enumerated,
549 // don't complain about not enumerating the mall.
553 // First pass - check for violation, but don't do much book-keeping because this is hopefully
554 // the uncommon case, and the book-keeping is slightly expensive.
555 let mut wildcard_span = None;
556 let mut wildcard_ident = None;
558 if let PatKind::Wild = arm.pat.kind {
559 wildcard_span = Some(arm.pat.span);
560 } else if let PatKind::Binding(_, _, ident, None) = arm.pat.kind {
561 wildcard_span = Some(arm.pat.span);
562 wildcard_ident = Some(ident);
566 if let Some(wildcard_span) = wildcard_span {
567 // Accumulate the variants which should be put in place of the wildcard because they're not
570 let mut missing_variants = vec![];
571 if let ty::Adt(def, _) = ty.kind {
572 for variant in &def.variants {
573 missing_variants.push(variant);
578 if arm.guard.is_some() {
579 // Guards mean that this case probably isn't exhaustively covered. Technically
580 // this is incorrect, as we should really check whether each variant is exhaustively
581 // covered by the set of guards that cover it, but that's really hard to do.
584 if let PatKind::Path(ref path) = arm.pat.kind {
585 if let QPath::Resolved(_, p) = path {
586 missing_variants.retain(|e| e.ctor_def_id != Some(p.res.def_id()));
588 } else if let PatKind::TupleStruct(ref path, ..) = arm.pat.kind {
589 if let QPath::Resolved(_, p) = path {
590 missing_variants.retain(|e| e.ctor_def_id != Some(p.res.def_id()));
595 let mut suggestion: Vec<String> = missing_variants
598 let suffix = match v.ctor_kind {
599 CtorKind::Fn => "(..)",
600 CtorKind::Const | CtorKind::Fictive => "",
602 let ident_str = if let Some(ident) = wildcard_ident {
603 format!("{} @ ", ident.name)
607 // This path assumes that the enum type is imported into scope.
608 format!("{}{}{}", ident_str, cx.tcx.def_path_str(v.def_id), suffix)
612 if suggestion.is_empty() {
616 let mut message = "wildcard match will miss any future added variants";
618 if let ty::Adt(def, _) = ty.kind {
619 if def.is_variant_list_non_exhaustive() {
620 message = "match on non-exhaustive enum doesn't explicitly match all known variants";
621 suggestion.push(String::from("_"));
627 WILDCARD_ENUM_MATCH_ARM,
631 suggestion.join(" | "),
632 Applicability::MachineApplicable,
637 // If the block contains only a `panic!` macro (as expression or statement)
638 fn is_panic_block(block: &Block<'_>) -> bool {
639 match (&block.expr, block.stmts.len(), block.stmts.first()) {
640 (&Some(ref exp), 0, _) => {
641 is_expn_of(exp.span, "panic").is_some() && is_expn_of(exp.span, "unreachable").is_none()
643 (&None, 1, Some(stmt)) => {
644 is_expn_of(stmt.span, "panic").is_some() && is_expn_of(stmt.span, "unreachable").is_none()
650 fn check_match_ref_pats(cx: &LateContext<'_, '_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
651 if has_only_ref_pats(arms) {
652 let mut suggs = Vec::new();
653 let (title, msg) = if let ExprKind::AddrOf(BorrowKind::Ref, Mutability::Not, ref inner) = ex.kind {
654 let span = ex.span.source_callsite();
655 suggs.push((span, Sugg::hir_with_macro_callsite(cx, inner, "..").to_string()));
657 "you don't need to add `&` to both the expression and the patterns",
661 let span = ex.span.source_callsite();
662 suggs.push((span, Sugg::hir_with_macro_callsite(cx, ex, "..").deref().to_string()));
664 "you don't need to add `&` to all patterns",
665 "instead of prefixing all patterns with `&`, you can dereference the expression",
669 suggs.extend(arms.iter().filter_map(|a| {
670 if let PatKind::Ref(ref refp, _) = a.pat.kind {
671 Some((a.pat.span, snippet(cx, refp.span, "..").to_string()))
677 span_lint_and_then(cx, MATCH_REF_PATS, expr.span, title, |db| {
678 if !expr.span.from_expansion() {
679 multispan_sugg(db, msg.to_owned(), suggs);
685 fn check_match_as_ref(cx: &LateContext<'_, '_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
686 if arms.len() == 2 && arms[0].guard.is_none() && arms[1].guard.is_none() {
687 let arm_ref: Option<BindingAnnotation> = if is_none_arm(&arms[0]) {
688 is_ref_some_arm(&arms[1])
689 } else if is_none_arm(&arms[1]) {
690 is_ref_some_arm(&arms[0])
694 if let Some(rb) = arm_ref {
695 let suggestion = if rb == BindingAnnotation::Ref {
701 let output_ty = cx.tables.expr_ty(expr);
702 let input_ty = cx.tables.expr_ty(ex);
704 let cast = if_chain! {
705 if let ty::Adt(_, substs) = input_ty.kind;
706 let input_ty = substs.type_at(0);
707 if let ty::Adt(_, substs) = output_ty.kind;
708 let output_ty = substs.type_at(0);
709 if let ty::Ref(_, output_ty, _) = output_ty.kind;
710 if input_ty != output_ty;
718 let mut applicability = Applicability::MachineApplicable;
723 &format!("use `{}()` instead", suggestion),
727 snippet_with_applicability(cx, ex.span, "_", &mut applicability),
737 fn check_wild_in_or_pats(cx: &LateContext<'_, '_>, arms: &[Arm<'_>]) {
739 if let PatKind::Or(ref fields) = arm.pat.kind {
740 // look for multiple fields in this arm that contains at least one Wild pattern
741 if fields.len() > 1 && fields.iter().any(is_wild) {
744 WILDCARD_IN_OR_PATTERNS,
746 "wildcard pattern covers any other pattern as it will match anyway.",
747 "Consider handling `_` separately.",
754 /// Gets all arms that are unbounded `PatRange`s.
755 fn all_ranges<'a, 'tcx>(
756 cx: &LateContext<'a, 'tcx>,
757 arms: &'tcx [Arm<'_>],
759 ) -> Vec<SpannedRange<Constant>> {
763 ref pat, guard: None, ..
766 if let PatKind::Range(ref lhs, ref rhs, range_end) = pat.kind {
767 let lhs = match lhs {
768 Some(lhs) => constant(cx, cx.tables, lhs)?.0,
769 None => miri_to_const(ty.numeric_min_val(cx.tcx)?)?,
771 let rhs = match rhs {
772 Some(rhs) => constant(cx, cx.tables, rhs)?.0,
773 None => miri_to_const(ty.numeric_max_val(cx.tcx)?)?,
775 let rhs = match range_end {
776 RangeEnd::Included => Bound::Included(rhs),
777 RangeEnd::Excluded => Bound::Excluded(rhs),
779 return Some(SpannedRange {
785 if let PatKind::Lit(ref value) = pat.kind {
786 let value = constant(cx, cx.tables, value)?.0;
787 return Some(SpannedRange {
789 node: (value.clone(), Bound::Included(value)),
798 #[derive(Debug, Eq, PartialEq)]
799 pub struct SpannedRange<T> {
801 pub node: (T, Bound<T>),
804 type TypedRanges = Vec<SpannedRange<u128>>;
806 /// Gets all `Int` ranges or all `Uint` ranges. Mixed types are an error anyway
807 /// and other types than
808 /// `Uint` and `Int` probably don't make sense.
809 fn type_ranges(ranges: &[SpannedRange<Constant>]) -> TypedRanges {
812 .filter_map(|range| match range.node {
813 (Constant::Int(start), Bound::Included(Constant::Int(end))) => Some(SpannedRange {
815 node: (start, Bound::Included(end)),
817 (Constant::Int(start), Bound::Excluded(Constant::Int(end))) => Some(SpannedRange {
819 node: (start, Bound::Excluded(end)),
821 (Constant::Int(start), Bound::Unbounded) => Some(SpannedRange {
823 node: (start, Bound::Unbounded),
830 fn is_unit_expr(expr: &Expr<'_>) -> bool {
832 ExprKind::Tup(ref v) if v.is_empty() => true,
833 ExprKind::Block(ref b, _) if b.stmts.is_empty() && b.expr.is_none() => true,
838 // Checks if arm has the form `None => None`
839 fn is_none_arm(arm: &Arm<'_>) -> bool {
841 PatKind::Path(ref path) if match_qpath(path, &paths::OPTION_NONE) => true,
846 // Checks if arm has the form `Some(ref v) => Some(v)` (checks for `ref` and `ref mut`)
847 fn is_ref_some_arm(arm: &Arm<'_>) -> Option<BindingAnnotation> {
849 if let PatKind::TupleStruct(ref path, ref pats, _) = arm.pat.kind;
850 if pats.len() == 1 && match_qpath(path, &paths::OPTION_SOME);
851 if let PatKind::Binding(rb, .., ident, _) = pats[0].kind;
852 if rb == BindingAnnotation::Ref || rb == BindingAnnotation::RefMut;
853 if let ExprKind::Call(ref e, ref args) = remove_blocks(&arm.body).kind;
854 if let ExprKind::Path(ref some_path) = e.kind;
855 if match_qpath(some_path, &paths::OPTION_SOME) && args.len() == 1;
856 if let ExprKind::Path(ref qpath) = args[0].kind;
857 if let &QPath::Resolved(_, ref path2) = qpath;
858 if path2.segments.len() == 1 && ident.name == path2.segments[0].ident.name;
866 fn has_only_ref_pats(arms: &[Arm<'_>]) -> bool {
871 PatKind::Ref(..) => Some(true), // &-patterns
872 PatKind::Wild => Some(false), // an "anything" wildcard is also fine
873 _ => None, // any other pattern is not fine
876 .collect::<Option<Vec<bool>>>();
877 // look for Some(v) where there's at least one true element
878 mapped.map_or(false, |v| v.iter().any(|el| *el))
881 pub fn overlapping<T>(ranges: &[SpannedRange<T>]) -> Option<(&SpannedRange<T>, &SpannedRange<T>)>
885 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
887 Start(T, &'a SpannedRange<T>),
888 End(Bound<T>, &'a SpannedRange<T>),
891 impl<'a, T: Copy> Kind<'a, T> {
892 fn range(&self) -> &'a SpannedRange<T> {
894 Kind::Start(_, r) | Kind::End(_, r) => r,
898 fn value(self) -> Bound<T> {
900 Kind::Start(t, _) => Bound::Included(t),
901 Kind::End(t, _) => t,
906 impl<'a, T: Copy + Ord> PartialOrd for Kind<'a, T> {
907 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
908 Some(self.cmp(other))
912 impl<'a, T: Copy + Ord> Ord for Kind<'a, T> {
913 fn cmp(&self, other: &Self) -> Ordering {
914 match (self.value(), other.value()) {
915 (Bound::Included(a), Bound::Included(b)) | (Bound::Excluded(a), Bound::Excluded(b)) => a.cmp(&b),
916 // Range patterns cannot be unbounded (yet)
917 (Bound::Unbounded, _) | (_, Bound::Unbounded) => unimplemented!(),
918 (Bound::Included(a), Bound::Excluded(b)) => match a.cmp(&b) {
919 Ordering::Equal => Ordering::Greater,
922 (Bound::Excluded(a), Bound::Included(b)) => match a.cmp(&b) {
923 Ordering::Equal => Ordering::Less,
930 let mut values = Vec::with_capacity(2 * ranges.len());
933 values.push(Kind::Start(r.node.0, r));
934 values.push(Kind::End(r.node.1, r));
939 for (a, b) in values.iter().zip(values.iter().skip(1)) {
941 (&Kind::Start(_, ra), &Kind::End(_, rb)) => {
942 if ra.node != rb.node {
943 return Some((ra, rb));
946 (&Kind::End(a, _), &Kind::Start(b, _)) if a != Bound::Included(b) => (),
947 _ => return Some((a.range(), b.range())),