use crate::{BytePos, SessionGlobals};
use std::{cmp, fmt, ops::Range};
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Span {
lo: BytePos,
hi: BytePos,
}
impl Default for Span {
#[inline(always)]
fn default() -> Self {
Self::DUMMY
}
}
impl Default for &Span {
#[inline(always)]
fn default() -> Self {
&Span::DUMMY
}
}
impl fmt::Debug for Span {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fn fallback(span: Span, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Span({lo}..{hi})", lo = span.lo().0, hi = span.hi().0)
}
if SessionGlobals::is_set() {
SessionGlobals::with(|g: &SessionGlobals| {
let sm = g.source_map.lock();
if let Some(source_map) = &*sm {
f.write_str(&source_map.span_to_diagnostic_string(*self))
} else {
drop(sm);
fallback(*self, f)
}
})
} else {
fallback(*self, f)
}
}
}
impl Span {
pub const DUMMY: Self = Self { lo: BytePos(0), hi: BytePos(0) };
#[inline]
pub fn new(mut lo: BytePos, mut hi: BytePos) -> Self {
if lo > hi {
std::mem::swap(&mut lo, &mut hi);
}
Self { lo, hi }
}
#[inline]
pub fn to_range(self) -> Range<usize> {
self.lo().to_usize()..self.hi().to_usize()
}
#[inline]
pub fn to_u32_range(self) -> Range<u32> {
self.lo().to_u32()..self.hi().to_u32()
}
#[inline(always)]
pub fn lo(self) -> BytePos {
self.lo
}
#[inline]
pub fn with_lo(self, lo: BytePos) -> Self {
Self::new(lo, self.hi())
}
#[inline(always)]
pub fn hi(self) -> BytePos {
self.hi
}
#[inline]
pub fn with_hi(self, hi: BytePos) -> Self {
Self::new(self.lo(), hi)
}
#[inline]
pub fn shrink_to_lo(self) -> Self {
Self::new(self.lo(), self.lo())
}
#[inline]
pub fn shrink_to_hi(self) -> Self {
Self::new(self.hi(), self.hi())
}
#[inline]
pub fn is_dummy(self) -> bool {
self == Self::DUMMY
}
#[inline]
pub fn contains(self, other: Self) -> bool {
self.lo() <= other.lo() && other.hi() <= self.hi()
}
#[inline]
pub fn overlaps(self, other: Self) -> bool {
self.lo() < other.hi() && other.lo() < self.hi()
}
#[inline]
pub fn is_empty(self, other: Self) -> bool {
self.lo() == other.lo() && self.hi() == other.hi()
}
#[inline]
pub fn split_at(self, pos: u32) -> (Self, Self) {
let len = self.hi().0 - self.lo().0;
debug_assert!(pos <= len);
let split_pos = BytePos(self.lo().0 + pos);
(Self::new(self.lo(), split_pos), Self::new(split_pos, self.hi()))
}
#[inline]
pub fn to(self, end: Self) -> Self {
Self::new(cmp::min(self.lo(), end.lo()), cmp::max(self.hi(), end.hi()))
}
#[inline]
pub fn between(self, end: Self) -> Self {
Self::new(self.hi(), end.lo())
}
#[inline]
pub fn until(self, end: Self) -> Self {
Self::new(self.lo(), end.lo())
}
#[inline]
pub fn join_many(spans: impl IntoIterator<Item = Self>) -> Self {
spans.into_iter().reduce(Self::to).unwrap_or_default()
}
#[inline]
pub fn join_first_last(
spans: impl IntoIterator<Item = Self, IntoIter: DoubleEndedIterator>,
) -> Self {
let mut spans = spans.into_iter();
let first = spans.next().unwrap_or_default();
if let Some(last) = spans.next_back() {
first.to(last)
} else {
first
}
}
}