2018-01-12 10:53:06 +03:00
|
|
|
use fold::FoldWith;
|
|
|
|
use std::fmt::{self, Debug, Display, Formatter};
|
2017-12-22 15:51:36 +03:00
|
|
|
|
2018-01-15 04:33:18 +03:00
|
|
|
/// A new-type struct for position of specific byte.
|
|
|
|
///
|
|
|
|
/// See [Span](./struct.Span.html).
|
2018-01-12 10:53:06 +03:00
|
|
|
#[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 {
|
2018-01-12 10:53:06 +03:00
|
|
|
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
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-01-15 04:33:18 +03:00
|
|
|
/// Byte range of a token or node.
|
2018-01-12 10:53:06 +03:00
|
|
|
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
|
2017-12-22 15:51:36 +03:00
|
|
|
pub struct Span {
|
2018-01-12 10:53:06 +03:00
|
|
|
/// Inclusive
|
2017-12-22 15:51:36 +03:00
|
|
|
pub start: BytePos,
|
2018-01-12 10:53:06 +03:00
|
|
|
/// Inclusive
|
2017-12-22 15:51:36 +03:00
|
|
|
pub end: BytePos,
|
|
|
|
}
|
2018-01-12 10:53:06 +03:00
|
|
|
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 {
|
2018-01-15 04:33:18 +03:00
|
|
|
/// 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
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-01-12 10:53:06 +03:00
|
|
|
pub trait Spanned<T>: Sized {
|
2018-01-15 04:33:18 +03:00
|
|
|
/// Creates `Self` from `node` and `span.
|
2018-01-12 10:53:06 +03:00
|
|
|
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 {
|
2018-01-15 04:33:18 +03:00
|
|
|
/// No op as span does not have any child.
|
2018-01-12 10:53:06 +03:00
|
|
|
fn fold_children(self, _: &mut F) -> Span {
|
|
|
|
self
|
2017-12-22 15:51:36 +03:00
|
|
|
}
|
|
|
|
}
|