lexer_rs/posn_and_span/
user_posn.rs

1//a PosnIn traits
2//tt UserPosn
3/// Trait for location within a stream
4///
5/// This base trait is used to enable tracking the position of a token
6/// parser within a stream in a manner that is useful for
7/// human-readable error messages
8///
9/// A simple implementation can be null, if the position is not
10/// critical for error messages for the token parser - for example,
11/// parsing a simple string in a test.
12///
13/// For a single file implementation see [crate::LineColumn]
14pub trait UserPosn:
15    Sized + std::fmt::Debug + Copy + std::default::Default + PartialEq + Eq + std::hash::Hash
16{
17    //fp advance_cols
18    /// Advance the state of the stream by a number of bytes and a
19    /// number of characters; the characters are guaranteed to *not*
20    /// be newlines
21    ///
22    /// For character streams (where num_bytes is not the same as
23    /// num_char) this *must* only be invoked to move on to a new UTF8
24    /// character boundary - hence num_bytes must be a (sum of)
25    /// len_utf8 values for the text at byte offset of self.
26    #[must_use]
27    fn advance_cols(self, _num_bytes: usize, _num_chars: usize) -> Self {
28        self
29    }
30
31    /// Advance the state of the stream by a number of bytes and to
32    /// the start of the next line
33    ///
34    /// For character streams this *must* only be invoked to move on
35    /// to a new UTF8 character boundary - hence num_bytes must be a
36    /// (sum of) len_utf8 values for the text at byte offset of self,
37    /// the last character of which is a newline
38    #[must_use]
39    fn advance_line(self, _num_bytes: usize) -> Self {
40        self
41    }
42
43    /// Return the line number (if supported, else 0)
44    #[must_use]
45    fn line(&self) -> usize {
46        0
47    }
48
49    /// Return the column number (if supported, else 0)
50    #[must_use]
51    fn column(&self) -> usize {
52        0
53    }
54
55    /// Format self for an error - this can be the same format as
56    /// Display (if implemented), or Debug, or whatever is desired
57    ///
58    /// It is required for a Lexer to generate a fail-to-parse-character
59    /// error
60    fn error_fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
61        std::fmt::Debug::fmt(self, fmt)
62    }
63}
64
65//ip UserPosn for ()
66impl UserPosn for () {}
67
68//ip UserPosn for usize
69impl UserPosn for usize {
70    fn advance_cols(self, byte_ofs: usize, _num_chars: usize) -> Self {
71        self + byte_ofs
72    }
73    fn advance_line(self, byte_ofs: usize) -> Self {
74        self + byte_ofs
75    }
76}