swc/common/src/span.rs

73 lines
1.6 KiB
Rust
Raw Normal View History

use fold::FoldWith;
use std::fmt::{self, Debug, Display, Formatter};
2017-12-22 15:51:36 +03:00
/// A new-type struct for position of specific byte.
///
/// See [Span](./struct.Span.html).
#[derive(Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
2017-12-22 15:51:36 +03:00
pub struct BytePos(pub u32);
impl Display for BytePos {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
Display::fmt(&self.0, f)
}
}
impl Debug for BytePos {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
Debug::fmt(&self.0, f)
2017-12-22 15:51:36 +03:00
}
}
/// Byte range of a token or node.
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
2017-12-22 15:51:36 +03:00
pub struct Span {
/// Inclusive
2017-12-22 15:51:36 +03:00
pub start: BytePos,
/// Inclusive
2017-12-22 15:51:36 +03:00
pub end: BytePos,
}
impl Debug for Span {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
if self.start == BytePos(0) && self.end == BytePos(0) {
write!(f, "_")
} else {
write!(f, "{}..{}", self.start, self.end.0 + 1)
}
}
}
2017-12-22 15:51:36 +03:00
impl Span {
/// Dummy span. This is same as `Span::defult()`.
2017-12-22 15:51:36 +03:00
pub const DUMMY: Span = Span {
start: BytePos(0),
end: BytePos(0),
};
}
impl Default for Span {
#[inline]
fn default() -> Self {
Span::DUMMY
}
}
pub trait Spanned<T>: Sized {
/// Creates `Self` from `node` and `span.
fn from_unspanned(node: T, span: Span) -> Self;
}
impl<S, T> Spanned<T> for Box<S>
where
S: Spanned<T>,
{
fn from_unspanned(node: T, span: Span) -> Self {
box S::from_unspanned(node, span)
}
}
impl<F> FoldWith<F> for Span {
/// No op as span does not have any child.
fn fold_children(self, _: &mut F) -> Span {
self
2017-12-22 15:51:36 +03:00
}
}