1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
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);
  }
}