stackr_rs/interpreter/
location.rs

1use std::{fmt::Display, path::PathBuf};
2
3/// Location of a token/word in the source code.
4#[derive(Debug, PartialEq, Clone)]
5pub struct Location {
6    /// Line number.
7    pub line: usize,
8    /// Column number.
9    pub column: usize,
10    /// File name.
11    pub path: Option<PathBuf>,
12}
13impl Location {
14    pub fn new(path: Option<PathBuf>) -> Self {
15        Location {
16            line: 1,
17            column: 1,
18            path,
19        }
20    }
21
22    pub fn next(&mut self) {
23        self.column += 1;
24    }
25
26    pub fn new_line(&mut self) {
27        self.column = 0;
28        self.line += 1;
29    }
30}
31impl Default for Location {
32    fn default() -> Self {
33        Location {
34            line: 1,
35            column: 1,
36            path: None,
37        }
38    }
39}
40impl Display for Location {
41    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42        match &self.path {
43            Some(path) => write!(f, "{}:{}:{}", path.display(), self.line, self.column),
44            None => write!(f, "{}:{}:{}", "stdin", self.line, self.column),
45        }
46    }
47}
48impl From<(usize, usize)> for Location {
49    fn from((line, column): (usize, usize)) -> Self {
50        Location {
51            line,
52            column,
53            path: None,
54        }
55    }
56}