lexer_rs/posn_and_span/
line_column.rs

1//a Imports
2use crate::UserPosn;
3
4//a LineColumn
5//tp LineColumn
6/// A line and column within a text stream
7///
8/// This provides the [UserPosn] trait, which provides methods to
9/// retrieve the line and column values of the state. This can be used
10/// as the 'State' type for a lexer, allowing the line and column of
11/// tokens to be tracked, and hence lexer tokens can be formmatted in
12/// a user-friendly fashion.
13#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
14pub struct LineColumn {
15    line: usize,
16    column: usize,
17}
18
19//ip Default for LineColumn
20impl std::default::Default for LineColumn {
21    fn default() -> Self {
22        Self { line: 1, column: 1 }
23    }
24}
25
26//ip Display for LineColumn
27impl std::fmt::Display for LineColumn {
28    fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
29        write!(fmt, "line {} column {}", self.line, self.column)
30    }
31}
32
33//ip UserPosn for LineColumn
34impl UserPosn for LineColumn {
35    fn line(&self) -> usize {
36        self.line
37    }
38
39    fn column(&self) -> usize {
40        self.column
41    }
42    fn advance_cols(mut self, _: usize, num_chars: usize) -> Self {
43        self.column += num_chars;
44        self
45    }
46    fn advance_line(mut self, _: usize) -> Self {
47        self.column = 1;
48        self.line += 1;
49        self
50    }
51    fn error_fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
52        write!(fmt, "line {} column {}", self.line, self.column)
53    }
54}