rustla/parser/line_cursor.rs
1/*!
2A submodule that contains the line cursor type and its associated function definitions.
3
4Copyright © 2020 Santtu Söderholm
5*/
6
7/// ### LineCursor
8/// A line cursor type of a parser that holds the start line and offset from it.
9/// The relative offset cursor is used to actually access
10/// the source lines' contents, whereas the sum of relative and absolute cursors is
11/// used mainly for debug prints and|or error messages.
12#[derive(Debug)]
13pub struct LineCursor {
14
15 /// This is used to access the contents of the source lines vector held by the parser.
16 /// It should generally be initialized to `0`.
17 offset: Line,
18
19 /// The line of text that a parser started working on.
20 baseline: Line,
21}
22
23impl LineCursor {
24
25 /// A `LineCursor` constructor.
26 pub fn new(relative: Line, absolute: Line) -> Self {
27 Self {
28 offset: relative,
29 baseline: absolute,
30 }
31 }
32
33 /// Retrieves the line relative to the baseline that a (nested) parser is on.
34 pub fn relative_offset(&self) -> Line {
35 self.offset
36 }
37
38 /// Retrieves a mutable reference to the line that the (nested) parser is on.
39 pub fn relative_offset_mut_ref(&mut self) -> &mut Line {
40 &mut self.offset
41 }
42
43 /// Increments relative offset by given `amount`.
44 pub fn increment_by(&mut self, amount: Line) {
45 self.offset = match self.offset.checked_add(amount) {
46 Some(line) => line,
47 None => {
48 eprintln!("Tried incrementing relative line offset by {} on line {} but overflowed.\nComputer says no...\n", amount, self.sum_total());
49 panic!()
50 }
51 };
52 }
53
54 /// Returns the sum total of `self.relative_offset` and `*self.baseline`.
55 pub fn sum_total(&self) -> Line {
56 self.offset + self.baseline
57 }
58}
59
60/// A type alias for a line vector index.
61pub type Line = usize;