Skip to main content

parsec_base/
lib.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 James Conway
3
4//! What Parsec's parsers share, and nothing they don't: a [`Span`] of
5//! input, a [`LineIndex`] that turns byte offsets into lines, columns and
6//! UTF-16 offsets, a [`Diagnostic`] with a code and a span that
7//! [`Diagnostic::render`] prints as a code frame, and the
8//! [`Limits`] and [`Budget`] that keep hostile input from costing more
9//! than you allow.
10//!
11//! Each language keeps its own tokens, tree and error recovery; this
12//! crate is only the plumbing under them, and it has no dependencies.
13//!
14//! ```
15//! use parsec_base::{Diagnostic, LineIndex, Span};
16//!
17//! let src = "let a = 1;\nlet é = 'x\n";
18//! let bad = Diagnostic::error("unterminated-string", Span::new(20, 22), "a string has no closing quote");
19//! let lines = LineIndex::new(src);
20//! assert_eq!(lines.line_col(bad.span.start), (2, 9).into());
21//! assert_eq!(bad.span.text(src), "'x");
22//! ```
23
24use std::borrow::Cow;
25use std::fmt;
26use std::ops::Range;
27
28mod render;
29
30pub use render::RenderOptions;
31
32/// A byte range in the input, `start..end`.
33///
34/// Offsets are `u32`, so a span is 8 bytes and a token that carries one
35/// stays small; a parser that uses it takes at most [`Span::MAX_INPUT`]
36/// bytes of input.
37#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
38pub struct Span {
39    pub start: u32,
40    pub end: u32,
41}
42
43impl Span {
44    /// The longest input a `u32` offset can cover.
45    pub const MAX_INPUT: usize = u32::MAX as usize;
46
47    pub const fn new(start: u32, end: u32) -> Span {
48        debug_assert!(start <= end);
49        Span { start, end }
50    }
51
52    /// An empty span at `offset`, for something that's missing there.
53    pub const fn at(offset: u32) -> Span {
54        Span {
55            start: offset,
56            end: offset,
57        }
58    }
59
60    pub const fn len(self) -> u32 {
61        self.end - self.start
62    }
63
64    pub const fn is_empty(self) -> bool {
65        self.start == self.end
66    }
67
68    /// Whether `offset` is inside, the end excluded.
69    pub const fn contains(self, offset: u32) -> bool {
70        self.start <= offset && offset < self.end
71    }
72
73    /// The smallest span covering both.
74    pub fn to(self, other: Span) -> Span {
75        Span {
76            start: self.start.min(other.start),
77            end: self.end.max(other.end),
78        }
79    }
80
81    pub const fn range(self) -> Range<usize> {
82        self.start as usize..self.end as usize
83    }
84
85    /// The text this span covers in `src`, or `""` if it isn't a range of
86    /// whole characters there.
87    pub fn text(self, src: &str) -> &str {
88        src.get(self.range()).unwrap_or("")
89    }
90}
91
92impl From<Span> for Range<usize> {
93    fn from(s: Span) -> Range<usize> {
94        s.range()
95    }
96}
97
98/// A line and a column, both counted from 1.
99#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
100pub struct LineCol {
101    pub line: u32,
102    pub column: u32,
103}
104
105impl From<(u32, u32)> for LineCol {
106    fn from((line, column): (u32, u32)) -> LineCol {
107        LineCol { line, column }
108    }
109}
110
111impl fmt::Display for LineCol {
112    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
113        write!(f, "{}:{}", self.line, self.column)
114    }
115}
116
117/// Bytes between the checkpoints that keep a column lookup on a long line
118/// (a minified script is one line) from counting the whole line.
119const BLOCK: usize = 1024;
120
121/// Where each line starts in a text, for turning byte offsets into lines
122/// and columns, in characters or in UTF-16 code units as editors and the
123/// language server protocol count them.
124///
125/// Building it is one pass over the text. A lookup is a binary search for
126/// the line and a count of at most a thousand bytes for the column.
127#[derive(Clone, Debug)]
128pub struct LineIndex<'a> {
129    src: Cow<'a, str>,
130    /// The byte offset each line starts at; the first is 0.
131    starts: Vec<u32>,
132    /// Characters, and UTF-16 code units, before each `BLOCK`-byte block.
133    chars: Vec<u32>,
134    utf16: Vec<u32>,
135}
136
137impl<'a> LineIndex<'a> {
138    /// Lines ending at LF, CR or CRLF, as HTML, CSS and XML count them.
139    pub fn new(src: &'a str) -> LineIndex<'a> {
140        LineIndex::build(Cow::Borrowed(src), false)
141    }
142
143    /// As [`LineIndex::new`], keeping the text, for an index that outlives
144    /// the text it was made from, as a binding's document does.
145    ///
146    /// ```
147    /// let lines = parsec_base::LineIndex::owned("a\nbé".to_string());
148    /// assert_eq!(lines.line_col(5).column, 3);
149    /// ```
150    pub fn owned(src: String) -> LineIndex<'static> {
151        LineIndex::build(Cow::Owned(src), false)
152    }
153
154    /// Lines ending at LF, CR, CRLF, U+2028 or U+2029: ECMAScript's
155    /// LineTerminatorSequence.
156    pub fn ecmascript(src: &'a str) -> LineIndex<'a> {
157        LineIndex::build(Cow::Borrowed(src), true)
158    }
159
160    fn build(src: Cow<'a, str>, separators: bool) -> LineIndex<'a> {
161        assert!(
162            src.len() <= Span::MAX_INPUT,
163            "LineIndex takes at most 4 GiB"
164        );
165        let b = src.as_bytes();
166        let mut starts = vec![0];
167        let mut i = 0;
168        while i < b.len() {
169            match b[i] {
170                b'\n' => starts.push(i as u32 + 1),
171                b'\r' if b.get(i + 1) != Some(&b'\n') => starts.push(i as u32 + 1),
172                // U+2028 and U+2029 are E2 80 A8 and E2 80 A9.
173                0xE2 if separators
174                    && b.get(i + 1) == Some(&0x80)
175                    && matches!(b.get(i + 2), Some(0xA8 | 0xA9)) =>
176                {
177                    starts.push(i as u32 + 3);
178                    i += 2;
179                }
180                _ => {}
181            }
182            i += 1;
183        }
184        let (mut chars, mut utf16) = (Vec::new(), Vec::new());
185        let (mut c, mut u) = (0, 0);
186        for block in b.chunks(BLOCK) {
187            chars.push(c);
188            utf16.push(u);
189            let (bc, bu) = count(block);
190            c += bc;
191            u += bu;
192        }
193        chars.push(c);
194        utf16.push(u);
195        LineIndex {
196            src,
197            starts,
198            chars,
199            utf16,
200        }
201    }
202
203    pub fn line_count(&self) -> u32 {
204        self.starts.len() as u32
205    }
206
207    /// The byte offset line `line` (from 1) starts at.
208    pub fn line_start(&self, line: u32) -> Option<u32> {
209        self.starts.get(line.checked_sub(1)? as usize).copied()
210    }
211
212    /// The line `offset` is on, from 1. An offset past the end is on the
213    /// last line, and a line terminator is on the line it ends.
214    pub fn line(&self, offset: u32) -> u32 {
215        self.starts.partition_point(|&s| s <= offset) as u32
216    }
217
218    /// The line and column of `offset`, the column in characters (Unicode
219    /// scalar values). An offset inside a character counts as after it.
220    pub fn line_col(&self, offset: u32) -> LineCol {
221        let line = self.line(offset);
222        let start = self.starts[line as usize - 1];
223        let column = 1 + self.before(offset).0 - self.before(start).0;
224        LineCol { line, column }
225    }
226
227    /// The line and column of `offset`, the column in UTF-16 code units,
228    /// as JavaScript strings and source maps count it.
229    pub fn line_col_utf16(&self, offset: u32) -> LineCol {
230        let line = self.line(offset);
231        let start = self.starts[line as usize - 1];
232        let column = 1 + self.before(offset).1 - self.before(start).1;
233        LineCol { line, column }
234    }
235
236    /// `offset` as an offset in UTF-16 code units from the start of the
237    /// text: where it is in a JavaScript string of the same text.
238    pub fn utf16_offset(&self, offset: u32) -> u32 {
239        self.before(offset).1
240    }
241
242    /// `offset` as an offset in characters (Unicode scalar values) from
243    /// the start of the text: where it is in a Python `str` of the same
244    /// text.
245    pub fn char_offset(&self, offset: u32) -> u32 {
246        self.before(offset).0
247    }
248
249    /// Characters and UTF-16 code units before `offset`.
250    fn before(&self, offset: u32) -> (u32, u32) {
251        let at = (offset as usize).min(self.src.len());
252        let block = at / BLOCK;
253        let (c, u) = count(&self.src.as_bytes()[block * BLOCK..at]);
254        (self.chars[block] + c, self.utf16[block] + u)
255    }
256}
257
258/// Characters and UTF-16 code units in some UTF-8: one of each per byte
259/// that isn't a continuation byte, and a second code unit for a four-byte
260/// character.
261fn count(bytes: &[u8]) -> (u32, u32) {
262    let (mut c, mut u) = (0, 0);
263    for &b in bytes {
264        if b & 0xC0 != 0x80 {
265            c += 1;
266            u += 1 + u32::from(b >= 0xF0);
267        }
268    }
269    (c, u)
270}
271
272/// How bad a [`Diagnostic`] is.
273#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
274pub enum Severity {
275    /// The input breaks the grammar; what the parser gives back is its
276    /// recovery.
277    Error,
278    /// The input is allowed but worth knowing about, like a legacy form
279    /// strict code would reject.
280    Warning,
281}
282
283impl fmt::Display for Severity {
284    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
285        f.write_str(match self {
286            Severity::Error => "error",
287            Severity::Warning => "warning",
288        })
289    }
290}
291
292/// A second place a [`Diagnostic`] points at, with what it is.
293#[derive(Clone, Debug, PartialEq, Eq, Hash)]
294pub struct Label {
295    pub span: Span,
296    pub message: Cow<'static, str>,
297}
298
299/// Something a parser has to say about its input: a stable `code` to
300/// match on (like `unterminated-string`), where, and a sentence for
301/// people. With a `'static` message and no labels, making one allocates
302/// nothing.
303#[derive(Clone, Debug, PartialEq, Eq, Hash)]
304pub struct Diagnostic {
305    pub code: &'static str,
306    pub severity: Severity,
307    pub span: Span,
308    pub message: Cow<'static, str>,
309    pub labels: Vec<Label>,
310}
311
312impl Diagnostic {
313    pub fn new(
314        code: &'static str,
315        severity: Severity,
316        span: Span,
317        message: impl Into<Cow<'static, str>>,
318    ) -> Diagnostic {
319        Diagnostic {
320            code,
321            severity,
322            span,
323            message: message.into(),
324            labels: Vec::new(),
325        }
326    }
327
328    pub fn error(
329        code: &'static str,
330        span: Span,
331        message: impl Into<Cow<'static, str>>,
332    ) -> Diagnostic {
333        Diagnostic::new(code, Severity::Error, span, message)
334    }
335
336    pub fn warning(
337        code: &'static str,
338        span: Span,
339        message: impl Into<Cow<'static, str>>,
340    ) -> Diagnostic {
341        Diagnostic::new(code, Severity::Warning, span, message)
342    }
343
344    /// The same, pointing at `span` too.
345    pub fn with_label(mut self, span: Span, message: impl Into<Cow<'static, str>>) -> Diagnostic {
346        self.labels.push(Label {
347            span,
348            message: message.into(),
349        });
350        self
351    }
352
353    pub fn is_error(&self) -> bool {
354        self.severity == Severity::Error
355    }
356}
357
358impl fmt::Display for Diagnostic {
359    /// `error[code] at 12..14: message`.
360    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
361        write!(
362            f,
363            "{}[{}] at {}..{}: {}",
364            self.severity, self.code, self.span.start, self.span.end, self.message
365        )
366    }
367}
368
369impl std::error::Error for Diagnostic {}
370
371/// The most a parse may cost. `None` is no limit.
372///
373/// ```
374/// use parsec_base::Limits;
375///
376/// let limits = Limits { max_input: Some(1 << 20), ..Limits::default() };
377/// assert!(limits.check_input(2 << 20).is_err());
378/// ```
379#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
380pub struct Limits {
381    /// The longest input in bytes. Parsers using [`Span`] never take more
382    /// than [`Span::MAX_INPUT`], whatever this says.
383    pub max_input: Option<usize>,
384    /// How deep the parser's tree may nest.
385    pub max_depth: Option<u32>,
386    /// The work a parse may do, in the steps its parser counts.
387    pub max_steps: Option<u64>,
388}
389
390impl Limits {
391    /// An `input-too-large` error if `len` bytes are over the limit, or
392    /// over [`Span::MAX_INPUT`].
393    pub fn check_input(&self, len: usize) -> Result<(), Diagnostic> {
394        let max = self.max_input.unwrap_or(usize::MAX).min(Span::MAX_INPUT);
395        if len <= max {
396            return Ok(());
397        }
398        Err(Diagnostic::error(
399            "input-too-large",
400            Span::at(0),
401            format!("the input is {len} bytes, and the limit is {max}"),
402        ))
403    }
404
405    /// Whether depth `depth` is past the limit.
406    pub fn too_deep(&self, depth: u32) -> bool {
407        self.max_depth.is_some_and(|max| depth > max)
408    }
409
410    /// A budget of [`Limits::max_steps`].
411    pub fn budget(&self) -> Budget {
412        Budget {
413            left: self.max_steps,
414        }
415    }
416}
417
418/// Steps left to spend on a parse. Parsers spend from it on the work
419/// whose cost the input controls and stop when it runs out, so the cost
420/// of a hostile input is one you chose.
421#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
422pub struct Budget {
423    left: Option<u64>,
424}
425
426impl Budget {
427    pub const fn new(steps: u64) -> Budget {
428        Budget { left: Some(steps) }
429    }
430
431    pub const fn unlimited() -> Budget {
432        Budget { left: None }
433    }
434
435    /// Spends `steps`, or fails, spending nothing, if fewer are left.
436    pub fn spend(&mut self, steps: u64) -> Result<(), Exhausted> {
437        match &mut self.left {
438            None => Ok(()),
439            Some(left) if *left >= steps => {
440                *left -= steps;
441                Ok(())
442            }
443            Some(_) => Err(Exhausted),
444        }
445    }
446
447    /// The steps left, or `None` without a limit.
448    pub const fn left(&self) -> Option<u64> {
449        self.left
450    }
451}
452
453/// A [`Budget`] ran out.
454#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
455pub struct Exhausted;
456
457impl fmt::Display for Exhausted {
458    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
459        f.write_str("the step budget ran out")
460    }
461}
462
463impl std::error::Error for Exhausted {}
464
465#[cfg(test)]
466mod tests {
467    use super::*;
468
469    #[test]
470    fn span_basics() {
471        let s = Span::new(2, 5);
472        assert_eq!((s.len(), s.is_empty()), (3, false));
473        assert!(s.contains(2) && s.contains(4) && !s.contains(5));
474        assert!(Span::at(7).is_empty());
475        assert_eq!(s.to(Span::new(8, 9)), Span::new(2, 9));
476        assert_eq!(Span::new(8, 9).to(s), Span::new(2, 9));
477        assert_eq!(Range::<usize>::from(s), 2..5);
478        assert_eq!(s.text("abcdefg"), "cde");
479        // Not on character boundaries, or past the end: nothing.
480        assert_eq!(Span::new(1, 2).text("é"), "");
481        assert_eq!(Span::new(1, 20).text("abc"), "");
482        assert_eq!(std::mem::size_of::<Span>(), 8);
483    }
484
485    /// Line and column by counting from the start, the slow way.
486    fn slow(src: &str, separators: bool, offset: usize) -> (u32, u32, u32, u32) {
487        let (mut line, mut col, mut col16, mut off16) = (1, 1, 1, 0);
488        let mut chars = src.char_indices().peekable();
489        while let Some((i, c)) = chars.next() {
490            if i >= offset {
491                break;
492            }
493            off16 += c.len_utf16() as u32;
494            let crlf = c == '\r' && chars.peek().is_some_and(|&(_, n)| n == '\n');
495            if (c == '\n'
496                || c == '\r' && !crlf
497                || separators && matches!(c, '\u{2028}' | '\u{2029}'))
498                && i + c.len_utf8() <= offset
499            {
500                line += 1;
501                col = 1;
502                col16 = 1;
503            } else {
504                col += 1;
505                col16 += c.len_utf16() as u32;
506            }
507        }
508        (line, col, col16, off16)
509    }
510
511    #[test]
512    fn line_col_agrees_with_counting() {
513        // Every line end, characters of every width, and a line longer
514        // than a block, so checkpoints and line starts fall apart.
515        let src = "a\r\nb\rc\nd\u{2028}e\u{2029}é€😀\n".repeat(40) + &"😀x".repeat(700) + "\r\nend";
516        for separators in [false, true] {
517            let index = if separators {
518                LineIndex::ecmascript(&src)
519            } else {
520                LineIndex::new(&src)
521            };
522            for (offset, _) in src.char_indices().chain([(src.len(), ' ')]) {
523                let (line, col, col16, off16) = slow(&src, separators, offset);
524                let o = offset as u32;
525                assert_eq!(
526                    index.line_col(o),
527                    (line, col).into(),
528                    "{offset} {separators}"
529                );
530                assert_eq!(index.line_col_utf16(o), (line, col16).into(), "{offset}");
531                assert_eq!(index.utf16_offset(o), off16, "{offset}");
532            }
533        }
534    }
535
536    #[test]
537    fn line_starts() {
538        let index = LineIndex::new("ab\r\ncd\ref\n");
539        assert_eq!(index.line_count(), 4);
540        assert_eq!(index.line_start(1), Some(0));
541        assert_eq!(index.line_start(2), Some(4));
542        assert_eq!(index.line_start(3), Some(7));
543        assert_eq!(index.line_start(4), Some(10));
544        assert_eq!((index.line_start(0), index.line_start(5)), (None, None));
545        // The CR and the LF of a CRLF are both on the line they end.
546        assert_eq!((index.line(2), index.line(3), index.line(4)), (1, 1, 2));
547        // Past the end is the last line.
548        assert_eq!(index.line(1000), 4);
549        // Without separators, U+2028 is an ordinary character.
550        assert_eq!(LineIndex::new("a\u{2028}b").line_count(), 1);
551        assert_eq!(LineIndex::ecmascript("a\u{2028}b").line_count(), 2);
552        assert_eq!(LineIndex::new("").line_col(0), (1, 1).into());
553    }
554
555    #[test]
556    fn diagnostics() {
557        let d = Diagnostic::error("bad-thing", Span::new(3, 4), "a bad thing")
558            .with_label(Span::new(0, 1), "started here");
559        assert!(d.is_error());
560        assert_eq!(d.labels[0].message, "started here");
561        assert_eq!(d.to_string(), "error[bad-thing] at 3..4: a bad thing");
562        let w = Diagnostic::warning("odd", Span::at(0), String::from("odd"));
563        assert_eq!(
564            (w.is_error(), w.severity.to_string()),
565            (false, "warning".into())
566        );
567        assert!(Severity::Error < Severity::Warning);
568    }
569
570    #[test]
571    fn limits_and_budget() {
572        let none = Limits::default();
573        assert!(none.check_input(1 << 30).is_ok());
574        assert!(none.check_input(Span::MAX_INPUT + 1).is_err());
575        assert!(!none.too_deep(u32::MAX));
576        let l = Limits {
577            max_input: Some(10),
578            max_depth: Some(2),
579            max_steps: Some(5),
580        };
581        assert!(l.check_input(10).is_ok());
582        assert_eq!(l.check_input(11).unwrap_err().code, "input-too-large");
583        assert!(!l.too_deep(2) && l.too_deep(3));
584        let mut b = l.budget();
585        assert_eq!(b.spend(3), Ok(()));
586        assert_eq!(b.spend(3), Err(Exhausted));
587        assert_eq!(b.left(), Some(2));
588        assert_eq!(b.spend(2), Ok(()));
589        assert_eq!(b.spend(1), Err(Exhausted));
590        let mut u = Budget::unlimited();
591        assert_eq!((u.spend(u64::MAX), u.left()), (Ok(()), None));
592        assert_eq!(Budget::new(1).left(), Some(1));
593    }
594}