lexer_rs/posn_and_span/
stream_char_pos.rs

1//a Imports
2use crate::{PosnInCharStream, UserPosn};
3
4//a StreamCharPos
5//tp StreamCharPos
6/// This provides the byte offset of a character within a stream, with
7/// an associated position that might also accurately provide line and
8/// column numbers of the position
9///
10/// This can be used as a [PosnInCharStream] implementation for a
11/// lexer; if [crate::LineColumn] is used for the generic argument
12/// then the lexer will correctly track the line and column of the
13/// position of tokens.
14#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, Hash)]
15pub struct StreamCharPos<P>
16where
17    P: UserPosn,
18{
19    byte_ofs: usize,
20    pos: P,
21}
22
23//ip StreamCharPos
24impl<P> StreamCharPos<P>
25where
26    P: UserPosn,
27{
28    /// Get the descriptive position that [Self] includes; if that
29    /// type provides them accurately, this can give the line number
30    /// and column number of the position
31    pub fn pos(&self) -> P {
32        self.pos
33    }
34}
35
36//ip UserPosn for StreamCharPos
37impl<P> UserPosn for StreamCharPos<P>
38where
39    P: UserPosn,
40{
41    fn advance_cols(mut self, num_bytes: usize, num_chars: usize) -> Self {
42        self.byte_ofs += num_bytes;
43        self.pos = self.pos.advance_cols(num_bytes, num_chars);
44        self
45    }
46    fn advance_line(mut self, num_bytes: usize) -> Self {
47        self.byte_ofs += num_bytes;
48        self.pos = self.pos.advance_line(num_bytes);
49        self
50    }
51    fn line(&self) -> usize {
52        self.pos.line()
53    }
54
55    fn column(&self) -> usize {
56        self.pos.column()
57    }
58    fn error_fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
59        self.pos.error_fmt(fmt)
60    }
61}
62
63//ip PosnInCharStream for StreamCharPos
64impl<P> PosnInCharStream for StreamCharPos<P>
65where
66    P: UserPosn,
67{
68    fn byte_ofs(&self) -> usize {
69        self.byte_ofs
70    }
71}
72
73//ip Display for StreamCharPos
74impl<P> std::fmt::Display for StreamCharPos<P>
75where
76    P: UserPosn,
77{
78    fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
79        self.pos.error_fmt(fmt)
80    }
81}