Skip to main content

kamo/parser/
span.rs

1use std::fmt;
2
3use crate::Position;
4
5use super::Input;
6
7/// A span is a range of positions in the input.
8///
9/// A span is composed of a start and an end position. The start position is
10/// included in the span but the end position is not. The end position is the
11/// position of the first character after the fragment.
12///
13/// If the span is empty, the start and end positions are the same. The span
14/// contains no character.
15#[derive(Copy, Clone, Default, PartialEq, Eq, Hash)]
16pub struct Span {
17    start: Position,
18    end: Position,
19}
20
21impl Span {
22    /// Creates a new span from the start and end positions. The start position
23    /// must be less than or equal to the end position.
24    ///
25    /// # Panics
26    ///
27    /// This function panics if the start position is greater than the end
28    /// position.
29    ///
30    /// # Examples
31    ///
32    /// ```rust
33    /// # use kamo::{Position, parser::Span};
34    /// let start = Position::new(0, 1, 1);
35    /// let end = Position::new(3, 1, 4);
36    /// let span = Span::new(start, end);
37    ///
38    /// assert_eq!(span.start(), start);
39    /// assert_eq!(span.end(), end);
40    /// ```
41    #[inline]
42    pub fn new(start: impl Into<Position>, end: impl Into<Position>) -> Self {
43        let start = start.into();
44        let end = end.into();
45
46        assert!(start <= end, "start > end");
47        Self { start, end }
48    }
49
50    /// Creates a new span at the given position. The start and end positions
51    /// are the same.
52    ///
53    /// # Examples
54    ///
55    /// ```rust
56    /// # use kamo::{Position, parser::Span};
57    /// let pos = Position::new(0, 1, 1);
58    /// let span = Span::new_at(pos);
59    ///
60    /// assert_eq!(span.start(), pos);
61    /// assert_eq!(span.end(), pos);
62    /// ```
63    #[inline]
64    pub fn new_at(pos: impl Into<Position>) -> Self {
65        let pos = pos.into();
66
67        Self {
68            start: pos,
69            end: pos,
70        }
71    }
72
73    /// Returns the start position of the span.
74    #[must_use]
75    #[inline]
76    pub const fn start(&self) -> Position {
77        self.start
78    }
79
80    /// Returns the end position of the span.
81    #[must_use]
82    #[inline]
83    pub const fn end(&self) -> Position {
84        self.end
85    }
86
87    /// Returns the byte offset of the start of the fragment relatively to the
88    /// input. It starts at 0.
89    #[must_use]
90    #[inline]
91    pub const fn offset(&self) -> usize {
92        self.start.offset()
93    }
94
95    /// Returns the line number on which the span starts. It starts at 1.
96    #[must_use]
97    #[inline]
98    pub const fn line(&self) -> usize {
99        self.start.line()
100    }
101
102    /// Returns the charcater (utf-8 encoded) column the span start. It starts
103    /// at 1.
104    #[must_use]
105    #[inline]
106    pub const fn column(&self) -> usize {
107        self.start.column()
108    }
109
110    /// Returns the first line that contains the fragment. The `source` must be
111    /// the original string the span was created from otherwise an arbitrarily
112    /// string will be returned.
113    ///
114    /// # Examples
115    ///
116    /// ```rust
117    /// # use kamo::{Position, parser::Span};
118    /// let pos = Position::new(0, 1, 1);
119    /// let span = Span::new_at(pos);
120    ///
121    /// assert_eq!(span.line_str("abc"), "abc");
122    ///
123    /// let pos = Position::new(5, 2, 2);
124    /// let span = Span::new_at(pos);
125    ///
126    /// assert_eq!(span.line_str("abc\ndef"), "def");
127    /// ```
128    #[must_use]
129    pub fn line_str<'a>(&self, source: &'a str) -> &'a str {
130        let column0 = self.before(source).0 - 1;
131        let line = source[self.start.offset() - column0..].as_bytes();
132
133        unsafe {
134            std::str::from_utf8_unchecked(
135                memchr::memchr(b'\n', &line[column0..]).map_or(line, |pos| &line[..column0 + pos]),
136            )
137        }
138    }
139
140    /// Returns the spanned fragement in the given source. The `source` must be
141    /// the original string the span was created from otherwise an arbitrarily
142    /// string will be returned.
143    ///
144    /// # Examples
145    ///
146    /// ```rust
147    /// # use kamo::{Position, parser::Span};
148    /// let start = Position::new(0, 1, 1);
149    /// let end = Position::new(2, 1, 3);
150    /// let span = Span::new(start, end);
151    ///
152    /// assert_eq!(span.fragment("abc"), "ab");
153    /// ```
154    #[must_use]
155    #[inline]
156    pub fn fragment<'a>(&self, source: &'a str) -> &'a str {
157        &source[self.start.offset()..self.end.offset()]
158    }
159
160    /// Returns the bytes before the span in the given source. The `source` must
161    /// be the original string the span was created from otherwise an
162    /// arbitrarily string will be returned.
163    fn before<'a>(&self, source: &'a str) -> (usize, &'a [u8]) {
164        let before_self = source[..self.offset()].as_bytes();
165        let offset = memchr::memrchr(b'\n', before_self)
166            .map_or_else(|| self.start.offset() + 1, |pos| self.start.offset() - pos);
167
168        (offset, &before_self[self.start.offset() - (offset - 1)..])
169    }
170
171    /// Return the length of the span in bytes.
172    #[must_use]
173    #[inline]
174    pub const fn len(&self) -> usize {
175        self.end.offset() - self.start.offset()
176    }
177
178    /// Return if the span is empty.
179    #[must_use]
180    #[inline]
181    pub const fn is_empty(&self) -> bool {
182        self.len() == 0
183    }
184}
185
186impl fmt::Display for Span {
187    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
188        if self.is_empty() {
189            write!(f, "{}:{}", self.start.line(), self.start.column(),)
190        } else {
191            write!(
192                f,
193                "{}:{}..{}:{}",
194                self.start.line(),
195                self.start.column(),
196                self.end.line(),
197                self.end.column(),
198            )
199        }
200    }
201}
202
203impl fmt::Debug for Span {
204    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
205        if self.is_empty() {
206            write!(
207                f,
208                "[{}] {}:{}",
209                self.start.offset(),
210                self.start.line(),
211                self.start.column(),
212            )
213        } else {
214            write!(
215                f,
216                "[{}..{}] {}:{}..{}:{}",
217                self.start.offset(),
218                self.end.offset(),
219                self.start.line(),
220                self.start.column(),
221                self.end.line(),
222                self.end.column(),
223            )
224        }
225    }
226}
227
228impl Ord for Span {
229    #[inline]
230    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
231        self.start.cmp(&other.start)
232    }
233}
234
235impl PartialOrd for Span {
236    #[inline]
237    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
238        Some(self.cmp(other))
239    }
240}
241
242impl From<Position> for Span {
243    #[inline]
244    fn from(pos: Position) -> Self {
245        Self::new_at(pos)
246    }
247}
248
249impl From<Input<'_>> for Span {
250    #[inline]
251    fn from(input: Input<'_>) -> Self {
252        Self::new_at(input.position())
253    }
254}
255
256#[cfg(test)]
257mod tests {
258    use super::*;
259
260    #[test]
261    fn create() {
262        let start = Position::new(0, 1, 1);
263        let end = Position::new(2, 1, 3);
264        let span = Span::new(start, end);
265
266        assert_eq!(span.start(), start);
267        assert_eq!(span.end(), end);
268
269        let pos = Position::new(0, 1, 1);
270        let span = Span::new_at(pos);
271
272        assert_eq!(span.start(), pos);
273        assert_eq!(span.end(), pos);
274    }
275
276    #[test]
277    fn line_str() {
278        let pos = Position::new(0, 1, 1);
279        let span = Span::new_at(pos);
280
281        assert_eq!(span.line_str("abc"), "abc");
282
283        let pos = Position::new(3, 1, 4);
284        let span = Span::new_at(pos);
285
286        assert_eq!(span.line_str("abc"), "abc");
287
288        let pos = Position::new(5, 2, 2);
289        let span = Span::new_at(pos);
290
291        assert_eq!(span.line_str("abc\ndef"), "def");
292    }
293
294    #[test]
295    fn fragment() {
296        let start = Position::new(0, 1, 1);
297        let end = Position::new(2, 1, 3);
298        let span = Span::new(start, end);
299
300        assert_eq!(span.fragment("abc"), "ab");
301
302        let start = Position::new(0, 1, 1);
303        let end = Position::new(3, 1, 4);
304        let span = Span::new(start, end);
305
306        assert_eq!(span.fragment("abc"), "abc");
307
308        let start = Position::new(0, 1, 1);
309        let end = Position::new(5, 2, 2);
310        let span = Span::new(start, end);
311
312        assert_eq!(span.fragment("abc\ndef"), "abc\nd");
313    }
314
315    #[test]
316    fn length() {
317        let pos = Position::new(0, 1, 1);
318        let span = Span::new_at(pos);
319
320        assert_eq!(span.len(), 0);
321
322        let start = Position::new(0, 1, 1);
323        let end = Position::new(2, 1, 3);
324        let span = Span::new(start, end);
325
326        assert_eq!(span.len(), 2);
327
328        let start = Position::new(0, 1, 1);
329        let end = Position::new(3, 1, 4);
330        let span = Span::new(start, end);
331
332        assert_eq!(span.len(), 3);
333
334        let start = Position::new(0, 1, 1);
335        let end = Position::new(5, 2, 2);
336        let span = Span::new(start, end);
337
338        assert_eq!(span.len(), 5);
339    }
340}