1use crate::error::SyntaxError;
2use crate::error::SyntaxErrorType;
3use crate::token::TokenType;
4use std::cmp::max;
5use std::cmp::min;
6use std::ops::Add;
7use std::ops::AddAssign;
8
9#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
10pub struct Loc(pub usize, pub usize);
11
12impl Loc {
13 pub fn error(self, typ: SyntaxErrorType, actual_token: Option<TokenType>) -> SyntaxError {
14 SyntaxError::new(typ, self, actual_token)
15 }
16
17 pub fn is_empty(&self) -> bool {
18 self.0 >= self.1
19 }
20
21 pub fn len(&self) -> usize {
22 self.1 - self.0
23 }
24
25 pub fn extend(&mut self, other: Loc) {
26 self.0 = min(self.0, other.0);
27 self.1 = max(self.1, other.1);
28 }
29
30 pub fn add_option(self, rhs: Option<Loc>) -> Loc {
31 let mut new = self;
32 if let Some(rhs) = rhs {
33 new.extend(rhs);
34 };
35 new
36 }
37}
38
39impl Add for Loc {
40 type Output = Loc;
41
42 fn add(self, rhs: Self) -> Self::Output {
43 let mut new = self;
44 new.extend(rhs);
45 new
46 }
47}
48
49impl AddAssign for Loc {
50 fn add_assign(&mut self, rhs: Self) {
51 self.extend(rhs);
52 }
53}