1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
use std::fmt;

/// Position in a source file.
///
/// This holds the line and column position of a character in a source file.
/// Some operations are available to move position in a file. In partular, the
/// [`next`](Position::next) method computes the next cursor position after
/// reading a given [`char`].
///
/// ## Display
///
/// The struct implements two different format traits:
///
///  * [`fmt::Display`] will format the position as `line {line} column
///    {column}`
///  * [`fmt::Debug`] will format the position as `{line}:{column}`.
///
/// Both of them will display lines and columns starting at `1` even though the
/// internal representation starts at `0`.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Default, PartialOrd, Ord)]
pub struct Position {
    /// Line number, starting at `0`.
    pub line: usize,

    /// Column number, starting at `0`.
    pub column: usize,
}

impl Position {
    /// Create a new position given a line and column.
    ///
    /// Indexes starts at `0`.
    #[must_use]
    pub const fn new(line: usize, column: usize) -> Self { Self { line, column } }

    /// Return the maximum position.
    ///
    /// # Example
    ///
    /// ```
    /// use source_span::Position;
    ///
    /// assert_eq!(
    ///     Position::end(),
    ///     Position::new(usize::max_value(), usize::max_value())
    /// );
    /// ```
    #[must_use]
    pub const fn end() -> Self {
        Self {
            line: usize::max_value(),
            column: usize::max_value(),
        }
    }

    /// Move to the next column.
    #[must_use]
    pub const fn next_column(&self) -> Self {
        Self {
            line: self.line,
            column: self.column + 1,
        }
    }

    /// Move to the begining of the line.
    #[must_use]
    pub const fn reset_column(&self) -> Self {
        Self {
            line: self.line,
            column: 0,
        }
    }

    /// Move to the next line, and reset the column position.
    #[must_use]
    pub const fn next_line(&self) -> Self {
        Self {
            line: self.line + 1,
            column: 0,
        }
    }

    /// Move to the position following the given [`char`].
    ///
    /// ## Control characters
    ///
    /// This crate is intended to help with incremental lexing/parsing.
    /// Therefore, any control character moving the cursor backward will be
    /// ignored: it will be treated as a 0-width character with no
    /// semantics.
    ///
    /// ### New lines
    ///
    /// The `\n` character is interpreted with the Unix semantics, as the new
    /// line (NL) character. It will reset the column position to `0` and
    /// move to the next line.
    ///
    /// ### Tabulations
    ///
    /// The `\t` will move the cursor to the next horizontal tab-top.
    /// This function assumes there is a tab-stop every 8 columns.
    /// Note that there is no standard on the size of a tabulation, however a
    /// length of 8 columns seems typical.
    ///
    /// As of today, there is no way to use another tab length.
    ///
    /// I understand that this lacks of flexibility may become an issue in the
    /// near future, and I will try to add this possibility. In the
    /// meantime, you are very welcome to contribute if you need this
    /// feature right away.
    ///
    /// ## Full-width characters
    ///
    /// As for now, double-width characters of full-width characters are *not*
    /// supported. They will move the cursor by only one column as any other
    /// regular-width character. You are welcome to contribute to handle
    /// them.
    #[must_use]
    pub fn next(&self, c: char) -> Self {
        match c {
            '\n' => self.next_line(),
            '\r' => self.reset_column(),
            '\t' => {
                Self {
                    line: self.line,
                    column: (self.column / 8) * 8 + 8,
                }
            }
            c if c.is_control() => *self,
            _ => self.next_column(),
        }
    }
}

impl fmt::Display for Position {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if self.line == usize::max_value() && self.column == usize::max_value() {
            write!(f, "line [end] column [end]")
        } else if self.line == usize::max_value() {
            write!(f, "line [end] column {}", self.column + 1)
        } else if self.column == usize::max_value() {
            write!(f, "line {} column [end]", self.line + 1)
        } else {
            write!(f, "line {} column {}", self.line + 1, self.column + 1)
        }
    }
}

impl fmt::Debug for Position {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if self.line == usize::max_value() && self.column == usize::max_value() {
            write!(f, "[end]:[end]")
        } else if self.line == usize::max_value() {
            write!(f, "[end]:{}", self.column + 1)
        } else if self.column == usize::max_value() {
            write!(f, "{}:[end]", self.line + 1)
        } else {
            write!(f, "{}:{}", self.line + 1, self.column + 1)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    macro_rules! min {
        ($x: expr) => ($x);
        ($x: expr, $($z: expr),+ $(,)* ) => (::std::cmp::min($x, min!($($z),*)));
    }

    macro_rules! max {
        ($x: expr) => ($x);
        ($x: expr, $($z: expr),+ $(,)* ) => (::std::cmp::max($x, max!($($z),*)));
    }

    // An order is a total order if it is (for all a, b and c):
    // - total and antisymmetric: exactly one of a < b, a == b or a > b is true; and
    // - transitive, a < b and b < c implies a < c. The same must hold for both ==
    //   and >.
    #[test]
    fn test_ord_position() {
        assert_eq!(
            min!(
                Position::new(1, 2),
                Position::new(1, 3),
                Position::new(1, 4),
                Position::new(1, 2),
                Position::new(2, 1),
                Position::new(3, 12),
                Position::new(4, 4),
            ),
            Position::new(1, 2)
        );

        assert_eq!(
            max!(
                Position::new(1, 2),
                Position::new(1, 3),
                Position::new(1, 4),
                Position::new(1, 2),
                Position::new(2, 1),
                Position::new(3, 12),
                Position::new(4, 4),
            ),
            Position::new(4, 4)
        );
    }

    #[test]
    fn test_debug() {
        assert_eq!(format!("{:?}", Position::new(2, 3)), "3:4".to_string());
        assert_eq!(
            format!("{:?}", Position::new(usize::max_value(), 3)),
            "[end]:4".to_string()
        );
        assert_eq!(
            format!("{:?}", Position::new(3, usize::max_value())),
            "4:[end]".to_string()
        );
        assert_eq!(
            format!(
                "{:?}",
                Position::new(usize::max_value(), usize::max_value())
            ),
            "[end]:[end]".to_string()
        );
    }
}