use super::error::SyntaxError;
use super::error::SyntaxErrorType;
use super::token::TokenType;
use std::cmp::max;
use std::cmp::min;
use std::ops::Add;
use std::ops::AddAssign;
#[derive(Clone, Copy, Debug)]
pub struct SourceRange {
start: u32,
end: u32,
}
impl SourceRange {
pub fn new(start: usize, end: usize) -> SourceRange {
debug_assert!(start <= end);
SourceRange {
start: start.try_into().unwrap(),
end: end.try_into().unwrap(),
}
}
pub fn start(&self) -> usize {
self.start.try_into().unwrap()
}
pub fn end(&self) -> usize {
self.end.try_into().unwrap()
}
pub fn at_start(&self) -> SourceRange {
SourceRange {
start: self.start,
end: self.start,
}
}
pub fn at_end(&self) -> SourceRange {
SourceRange {
start: self.end,
end: self.end,
}
}
pub fn error(self, typ: SyntaxErrorType, actual_token: Option<TokenType>) -> SyntaxError {
SyntaxError::from_loc(self, typ, actual_token)
}
pub fn add_option(self, rhs: Option<SourceRange>) -> SourceRange {
let mut new = self;
if let Some(rhs) = rhs {
new.extend(rhs);
};
new
}
pub fn is_empty(&self) -> bool {
self.end == self.start
}
pub fn len(&self) -> usize {
(self.end - self.start).try_into().unwrap()
}
pub fn extend(&mut self, other: SourceRange) {
self.start = min(self.start, other.start);
self.end = max(self.end, other.end);
}
}
impl Add for SourceRange {
type Output = SourceRange;
fn add(self, rhs: Self) -> Self::Output {
let mut new = self;
new.extend(rhs);
new
}
}
impl AddAssign for SourceRange {
fn add_assign(&mut self, rhs: Self) {
self.extend(rhs);
}
}