From df96cba432d9e869765385d6474b505494533435 Mon Sep 17 00:00:00 2001 From: Zalathar Date: Mon, 3 Jun 2024 17:00:10 +1000 Subject: [PATCH] Add `Span::trim_end` This is the counterpart of `Span::trim_start`. --- compiler/rustc_span/src/lib.rs | 7 +++++++ compiler/rustc_span/src/tests.rs | 19 +++++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/compiler/rustc_span/src/lib.rs b/compiler/rustc_span/src/lib.rs index b2ca01fe3b9..82179a4a058 100644 --- a/compiler/rustc_span/src/lib.rs +++ b/compiler/rustc_span/src/lib.rs @@ -682,6 +682,13 @@ impl Span { if span.hi > other.hi { Some(span.with_lo(cmp::max(span.lo, other.hi))) } else { None } } + /// Returns `Some(span)`, where the end is trimmed by the start of `other`. + pub fn trim_end(self, other: Span) -> Option { + let span = self.data(); + let other = other.data(); + if span.lo < other.lo { Some(span.with_hi(cmp::min(span.hi, other.lo))) } else { None } + } + /// Returns the source span -- this is either the supplied span, or the span for /// the macro callsite that expanded to it. pub fn source_callsite(self) -> Span { diff --git a/compiler/rustc_span/src/tests.rs b/compiler/rustc_span/src/tests.rs index 5c9dcc2a80f..48fa786fb1c 100644 --- a/compiler/rustc_span/src/tests.rs +++ b/compiler/rustc_span/src/tests.rs @@ -61,6 +61,25 @@ fn test_trim() { // The resulting span's context should be that of `self`, not `other`. let other = span(start, end).with_ctxt(SyntaxContext::from_u32(999)); + // Test cases for `trim_end`. + + assert_eq!(span(well_before, before).trim_end(other), Some(span(well_before, before))); + assert_eq!(span(well_before, start).trim_end(other), Some(span(well_before, start))); + assert_eq!(span(well_before, mid).trim_end(other), Some(span(well_before, start))); + assert_eq!(span(well_before, end).trim_end(other), Some(span(well_before, start))); + assert_eq!(span(well_before, after).trim_end(other), Some(span(well_before, start))); + + assert_eq!(span(start, mid).trim_end(other), None); + assert_eq!(span(start, end).trim_end(other), None); + assert_eq!(span(start, after).trim_end(other), None); + + assert_eq!(span(mid, end).trim_end(other), None); + assert_eq!(span(mid, after).trim_end(other), None); + + assert_eq!(span(end, after).trim_end(other), None); + + assert_eq!(span(after, well_after).trim_end(other), None); + // Test cases for `trim_start`. assert_eq!(span(after, well_after).trim_start(other), Some(span(after, well_after)));