Skip to main content

nash_parse/
lib.rs

1use bumpalo::Bump;
2use nash_region::{Located, Position, Region};
3
4mod bytes;
5mod declaration;
6pub mod error;
7mod exposing;
8mod expression;
9mod import;
10pub mod keyword;
11mod module;
12mod number;
13mod pattern;
14mod space;
15mod string;
16pub mod symbol;
17#[cfg(test)]
18pub(crate) mod test_support;
19mod tests_block;
20mod type_;
21
22pub type Row = usize;
23pub type Col = usize;
24
25/// Saved parser state for backtracking.
26#[derive(Clone, Copy)]
27struct ParserState {
28    pos: usize,
29    indent: usize,
30    row: Row,
31    col: Col,
32}
33
34/// Parser for Nash source code.
35///
36/// Combines the arena allocator with parsing state for a unified API.
37/// All parsed AST nodes are allocated in the provided bump arena.
38///
39/// The source text should already be allocated in the arena (via `bump.alloc_str`),
40/// so all string slices in the resulting AST share the `'a` lifetime.
41pub struct Parser<'a> {
42    /// Arena allocator for AST nodes
43    bump: &'a Bump,
44    /// Source bytes (UTF-8, already in arena)
45    src: &'a [u8],
46    /// Current byte position
47    pos: usize,
48    /// Current indentation level (for layout-sensitive parsing)
49    indent: usize,
50    /// Current row (1-indexed)
51    row: Row,
52    /// Current column (1-indexed)
53    col: Col,
54    depth: usize,
55    depth_error: Option<(Row, Col)>,
56}
57
58impl<'a> Parser<'a> {
59    /// Create a new parser for valid UTF-8 source text.
60    ///
61    /// The source should already be allocated in the arena.
62    ///
63    /// Arbitrary byte buffers are not a parser input:
64    /// ```compile_fail
65    /// let bump = bumpalo::Bump::new();
66    /// nash_parse::Parser::new(&bump, &[b'"', 0xff, b'"']);
67    /// ```
68    pub fn new(bump: &'a Bump, src: &'a str) -> Self {
69        Parser {
70            bump,
71            src: src.as_bytes(),
72            pos: 0,
73            // Elm starts at 0; 1 is behaviorally identical because
74            // `checkIndent`'s `col > 1` guard dominates at top level.
75            indent: 1,
76            row: 1,
77            col: 1,
78            depth: 0,
79            depth_error: None,
80        }
81    }
82
83    /// Count recursive expression, pattern, and type entries together. This state
84    /// is deliberately outside ParserState: backtracking cannot undo exhaustion.
85    fn with_depth<T, E>(
86        &mut self,
87        to_error: impl FnOnce(error::Space, Row, Col) -> E,
88        parse: impl FnOnce(&mut Self) -> Result<T, E>,
89    ) -> Result<T, E> {
90        const MAX_DEPTH: usize = 64;
91        if self.depth == MAX_DEPTH || self.depth_error.is_some() {
92            let position = self.position();
93            let (row, col) = *self.depth_error.get_or_insert(position);
94            return Err(to_error(error::Space::TooDeep, row, col));
95        }
96        self.depth += 1;
97        let result = parse(self);
98        self.depth -= 1;
99        // A speculative parser may swallow an error. Never turn exhaustion into
100        // a successful prefix parse, even when it restored the input position.
101        let result = match (result, self.depth_error) {
102            (Ok(_), Some((row, col))) => Err(to_error(error::Space::TooDeep, row, col)),
103            (result, _) => result,
104        };
105        if self.depth == 0 {
106            self.depth_error = None;
107        }
108        result
109    }
110
111    // -------------------------------------------------------------------------
112    // Position & State
113    // -------------------------------------------------------------------------
114
115    /// Current position as (row, col).
116    #[inline]
117    pub fn position(&self) -> (Row, Col) {
118        (self.row, self.col)
119    }
120
121    /// Get the current position as a `Position`.
122    #[inline]
123    pub fn get_position(&self) -> Position {
124        Position::new(self.row, self.col)
125    }
126
127    /// Create a `Located` value spanning from `start` to the current position,
128    /// allocated directly in the arena.
129    #[inline]
130    pub fn add_end<T>(&self, start: Position, value: T) -> &'a Located<T> {
131        let end = self.get_position();
132        self.alloc(Located::at(Region::new(start, end), value))
133    }
134
135    /// Current row (1-indexed).
136    #[inline]
137    pub fn row(&self) -> Row {
138        self.row
139    }
140
141    /// Current column (1-indexed).
142    #[inline]
143    pub fn col(&self) -> Col {
144        self.col
145    }
146
147    /// Current indentation level.
148    #[inline]
149    pub fn indent(&self) -> usize {
150        self.indent
151    }
152
153    /// Set the indentation level.
154    #[inline]
155    pub fn set_indent(&mut self, indent: usize) {
156        self.indent = indent;
157    }
158
159    /// Run a parser with the current column as the indent level,
160    /// then restore the old indent level.
161    ///
162    /// Mirrors Elm's `withIndent`:
163    /// ```haskell
164    /// withIndent (Parser parser) =
165    ///   Parser $ \(State src pos end oldIndent row col) cok eok cerr eerr ->
166    ///     let
167    ///       cok' a (State s p e _ r c) = cok a (State s p e oldIndent r c)
168    ///       eok' a (State s p e _ r c) = eok a (State s p e oldIndent r c)
169    ///     in
170    ///     parser (State src pos end col row col) cok' eok' cerr eerr
171    /// ```
172    pub fn with_indent<T, E>(
173        &mut self,
174        parser: impl FnOnce(&mut Self) -> Result<T, E>,
175    ) -> Result<T, E> {
176        let old_indent = self.indent;
177        self.indent = self.col;
178        let result = parser(self);
179        self.indent = old_indent;
180        result
181    }
182
183    /// Run a parser with indent set to (current column - backset),
184    /// then restore the old indent level.
185    ///
186    /// Mirrors Elm's `withBacksetIndent`:
187    /// ```haskell
188    /// withBacksetIndent backset (Parser parser) =
189    ///   Parser $ \(State src pos end oldIndent row col) cok eok cerr eerr ->
190    ///     parser (State src pos end (col - backset) row col) ...
191    /// ```
192    pub fn with_backset_indent<T, E>(
193        &mut self,
194        backset: usize,
195        parser: impl FnOnce(&mut Self) -> Result<T, E>,
196    ) -> Result<T, E> {
197        let old_indent = self.indent;
198        self.indent = self.col.saturating_sub(backset);
199        let result = parser(self);
200        self.indent = old_indent;
201        result
202    }
203
204    /// Check if we've reached the end of input.
205    #[inline]
206    pub fn is_eof(&self) -> bool {
207        self.pos >= self.src.len()
208    }
209
210    /// Save current parser state for backtracking.
211    #[inline]
212    fn save_state(&self) -> ParserState {
213        ParserState {
214            pos: self.pos,
215            indent: self.indent,
216            row: self.row,
217            col: self.col,
218        }
219    }
220
221    /// Restore parser state for backtracking.
222    #[inline]
223    fn restore_state(&mut self, state: ParserState) {
224        self.pos = state.pos;
225        self.indent = state.indent;
226        self.row = state.row;
227        self.col = state.col;
228    }
229
230    // -------------------------------------------------------------------------
231    // Combinators
232    // -------------------------------------------------------------------------
233
234    /// Try multiple parsers in order, returning the first success.
235    ///
236    /// Mirrors Elm's `oneOf`:
237    /// ```haskell
238    /// oneOf :: (Row -> Col -> x) -> [Parser x a] -> Parser x a
239    /// ```
240    ///
241    /// Key semantics:
242    /// - If a parser fails without consuming input, try the next one
243    /// - If a parser fails after consuming input, propagate the error (committed)
244    /// - If all parsers fail without consuming, call `to_error(row, col)`
245    ///
246    /// # Example
247    /// ```ignore
248    /// parser.one_of(
249    ///     error::Expr::Start,
250    ///     vec![
251    ///         Box::new(|p: &mut Parser| p.string(start)),
252    ///         Box::new(|p| p.number(start)),
253    ///     ],
254    /// )
255    /// ```
256    #[allow(clippy::type_complexity)]
257    pub fn one_of<T, E>(
258        &mut self,
259        to_error: impl FnOnce(Row, Col) -> E,
260        parsers: Vec<Box<dyn FnOnce(&mut Self) -> Result<T, E> + '_>>,
261    ) -> Result<T, E> {
262        let initial_state = self.save_state();
263
264        for parser in parsers {
265            let before = self.save_state();
266            match parser(self) {
267                Ok(value) => return Ok(value),
268                Err(e) => {
269                    // Did we consume any input?
270                    if self.pos != before.pos || self.depth_error.is_some() {
271                        // Committed - propagate error
272                        return Err(e);
273                    }
274                    // No input consumed - restore and try next
275                    self.restore_state(before);
276                }
277            }
278        }
279
280        // All parsers failed without consuming - restore to initial and return error
281        self.restore_state(initial_state);
282        let (row, col) = self.position();
283        Err(to_error(row, col))
284    }
285
286    /// Like `one_of` but returns a fallback value if nothing matches.
287    ///
288    /// Mirrors Elm's `oneOfWithFallback`:
289    /// ```haskell
290    /// oneOfWithFallback :: [Parser x a] -> a -> Parser x a
291    /// ```
292    #[allow(clippy::type_complexity)]
293    pub fn one_of_with_fallback<T, E>(
294        &mut self,
295        parsers: Vec<Box<dyn FnOnce(&mut Self) -> Result<T, E> + '_>>,
296        fallback: T,
297    ) -> Result<T, E> {
298        let initial_state = self.save_state();
299
300        for parser in parsers {
301            let before = self.save_state();
302            match parser(self) {
303                Ok(value) => return Ok(value),
304                Err(e) => {
305                    // Did we consume any input?
306                    if self.pos != before.pos || self.depth_error.is_some() {
307                        // Committed - propagate error
308                        return Err(e);
309                    }
310                    // No input consumed - restore and try next
311                    self.restore_state(before);
312                }
313            }
314        }
315
316        // All parsers failed without consuming - return fallback
317        self.restore_state(initial_state);
318        Ok(fallback)
319    }
320
321    /// Parse with error context wrapping.
322    ///
323    /// Mirrors Elm's `inContext`:
324    /// ```haskell
325    /// inContext :: (x -> Row -> Col -> y) -> Parser y start -> Parser x a -> Parser y a
326    /// ```
327    ///
328    /// 1. Saves the starting position
329    /// 2. Runs `start_parser` - if it fails without consuming, returns that error
330    /// 3. If start succeeds, runs `body_parser`
331    /// 4. If body fails, wraps the error using `add_context` at the original position
332    ///
333    /// The `add_context` closure receives the bump allocator so it can allocate wrapped errors.
334    ///
335    /// This is used to provide better error context, e.g., "error in list expression".
336    pub fn in_context<T, StartErr, BodyErr, ContextErr>(
337        &mut self,
338        add_context: impl FnOnce(&'a Bump, BodyErr, Row, Col) -> ContextErr,
339        start_parser: impl FnOnce(&mut Self) -> Result<(), StartErr>,
340        body_parser: impl FnOnce(&mut Self) -> Result<T, BodyErr>,
341    ) -> Result<T, ContextErr>
342    where
343        StartErr: Into<ContextErr>,
344    {
345        let (start_row, start_col) = self.position();
346
347        // Try to parse start token
348        match start_parser(self) {
349            Ok(()) => {
350                // Start succeeded, now parse body
351                match body_parser(self) {
352                    Ok(value) => Ok(value),
353                    Err(body_err) => {
354                        // Wrap body error with context at original position
355                        Err(add_context(self.bump, body_err, start_row, start_col))
356                    }
357                }
358            }
359            Err(start_err) => {
360                // Start failed - convert to context error type
361                Err(start_err.into())
362            }
363        }
364    }
365
366    /// Transform errors from one type to another with position context.
367    ///
368    /// Mirrors Elm's `specialize`:
369    /// ```haskell
370    /// specialize :: (x -> Row -> Col -> y) -> Parser x a -> Parser y a
371    /// ```
372    ///
373    /// Runs the parser and wraps any error with the context at the starting position.
374    /// The `add_context` closure receives the bump allocator so it can allocate wrapped errors.
375    pub fn specialize<T, InnerErr, OuterErr>(
376        &mut self,
377        add_context: impl FnOnce(&'a Bump, InnerErr, Row, Col) -> OuterErr,
378        parser: impl FnOnce(&mut Self) -> Result<T, InnerErr>,
379    ) -> Result<T, OuterErr> {
380        let (start_row, start_col) = self.position();
381
382        match parser(self) {
383            Ok(value) => Ok(value),
384            Err(inner_err) => Err(add_context(self.bump, inner_err, start_row, start_col)),
385        }
386    }
387
388    // -------------------------------------------------------------------------
389    // Single-byte parsing
390    // -------------------------------------------------------------------------
391
392    /// Parse a single expected byte.
393    ///
394    /// Mirrors Elm's `word1`:
395    /// ```haskell
396    /// word1 :: Word8 -> (Row -> Col -> x) -> Parser x ()
397    /// ```
398    ///
399    /// Returns `Ok(())` and advances if the byte matches.
400    /// Returns `Err` without consuming if it doesn't match.
401    #[inline]
402    pub fn word1<E>(
403        &mut self,
404        expected: u8,
405        to_error: impl FnOnce(Row, Col) -> E,
406    ) -> Result<(), E> {
407        if self.peek() == Some(expected) {
408            self.advance();
409            Ok(())
410        } else {
411            let (row, col) = self.position();
412            Err(to_error(row, col))
413        }
414    }
415
416    /// Parse two expected consecutive bytes.
417    ///
418    /// Mirrors Elm's `word2`:
419    /// ```haskell
420    /// word2 :: Word8 -> Word8 -> (Row -> Col -> x) -> Parser x ()
421    /// ```
422    #[inline]
423    pub fn word2<E>(
424        &mut self,
425        b1: u8,
426        b2: u8,
427        to_error: impl FnOnce(Row, Col) -> E,
428    ) -> Result<(), E> {
429        if self.peek() == Some(b1) && self.peek_at(1) == Some(b2) {
430            self.advance();
431            self.advance();
432            Ok(())
433        } else {
434            let (row, col) = self.position();
435            Err(to_error(row, col))
436        }
437    }
438
439    // -------------------------------------------------------------------------
440    // Peeking
441    // -------------------------------------------------------------------------
442
443    /// Peek at the current byte without consuming it.
444    #[inline]
445    pub fn peek(&self) -> Option<u8> {
446        self.src.get(self.pos).copied()
447    }
448
449    /// Peek at a byte at the given offset from current position.
450    #[inline]
451    pub fn peek_at(&self, offset: usize) -> Option<u8> {
452        self.src.get(self.pos.checked_add(offset)?).copied()
453    }
454
455    /// Get the remaining bytes from current position.
456    #[inline]
457    pub fn remaining(&self) -> &'a [u8] {
458        &self.src[self.pos..]
459    }
460
461    // -------------------------------------------------------------------------
462    // Advancing
463    // -------------------------------------------------------------------------
464
465    /// Advance by one byte, updating row/col for newlines.
466    #[inline]
467    pub fn advance(&mut self) {
468        if let Some(b) = self.peek() {
469            self.pos += 1;
470            if b == b'\n' {
471                self.row += 1;
472                self.col = 1;
473            } else {
474                self.col += 1;
475            }
476        }
477    }
478
479    /// Advance by n bytes, tracking newlines.
480    #[inline]
481    pub fn advance_by(&mut self, n: usize) {
482        for _ in 0..n {
483            self.advance();
484        }
485    }
486
487    // -------------------------------------------------------------------------
488    // Allocation helpers
489    // -------------------------------------------------------------------------
490
491    /// Allocate a value in the arena.
492    #[inline]
493    pub fn alloc<T>(&self, value: T) -> &'a T {
494        self.bump.alloc(value)
495    }
496
497    /// Allocate a slice in the arena by copying.
498    #[inline]
499    pub fn alloc_slice_copy<T: Copy>(&self, slice: &[T]) -> &'a [T] {
500        self.bump.alloc_slice_copy(slice)
501    }
502
503    /// Allocate a string in the arena (for constructed strings like escape sequences).
504    #[inline]
505    pub fn alloc_str(&self, s: &str) -> &'a str {
506        self.bump.alloc_str(s)
507    }
508}
509
510#[cfg(test)]
511mod tests {
512    #[test]
513    fn nesting_is_bounded_on_a_small_stack() {
514        std::thread::Builder::new()
515            .stack_size(2 * 1024 * 1024)
516            .spawn(|| {
517                for depth in [8, 512] {
518                    for (open, leaf, close, kind) in [
519                        ("(", "1", ")", 0),
520                        ("(-", "1", ")", 0),
521                        ("[", "1", "]", 0),
522                        ("\\x -> ", "1", "", 0),
523                        ("Just (", "x", ")", 1),
524                        ("(", "x", ")", 2),
525                        ("Int -> ", "Int", "", 3),
526                        ("(", "Int", ")", 4),
527                    ] {
528                        let bump = Bump::new();
529                        let source =
530                            format!("{}{}{}", open.repeat(depth), leaf, close.repeat(depth));
531                        let mut parser = Parser::new(&bump, &source);
532                        let result = match kind {
533                            0 => parser
534                                .expression()
535                                .map(|_| ())
536                                .map_err(|e| format!("{e:?}")),
537                            1 => parser
538                                .pattern_expr()
539                                .map(|_| ())
540                                .map_err(|e| format!("{e:?}")),
541                            2 => parser
542                                .pattern_term()
543                                .map(|_| ())
544                                .map_err(|e| format!("{e:?}")),
545                            3 => parser.type_expr().map(|_| ()).map_err(|e| format!("{e:?}")),
546                            _ => parser.type_term().map(|_| ()).map_err(|e| format!("{e:?}")),
547                        };
548                        if depth == 8 {
549                            assert!(result.is_ok(), "{open}: {result:?}");
550                            assert!(parser.is_eof());
551                        } else {
552                            assert!(result.unwrap_err().contains("TooDeep"), "{open}");
553                        }
554                        assert_eq!(parser.depth, 0);
555                        assert_eq!(parser.depth_error, None);
556                    }
557                }
558            })
559            .unwrap()
560            .join()
561            .unwrap();
562    }
563
564    #[test]
565    fn nesting_exhaustion_survives_backtracking_and_resets() {
566        let bump = Bump::new();
567        let mut parser = Parser::new(&bump, "x");
568        let result = parser.with_depth(error::Expr::Space, |p| {
569            let saved = p.save_state();
570            p.depth_error = Some((1, 1));
571            p.restore_state(saved);
572            p.one_of_with_fallback(
573                vec![Box::new(|_| {
574                    Err(error::Expr::Space(error::Space::TooDeep, 1, 1))
575                })],
576                (),
577            )
578        });
579        assert!(matches!(
580            result,
581            Err(error::Expr::Space(error::Space::TooDeep, 1, 1))
582        ));
583        parser.expression().unwrap();
584        assert!(parser.is_eof());
585    }
586
587    #[test]
588    fn flat_sequences_use_bounded_stack() {
589        std::thread::Builder::new()
590            .stack_size(2 * 1024 * 1024)
591            .spawn(|| {
592                let expressions = [
593                    format!("x{}", ".field".repeat(2_000)),
594                    format!("\\{}-> x", "x ".repeat(2_000)),
595                    format!("{}0", "if True then 1 else ".repeat(2_000)),
596                    format!("let\n{}in x", "    x = 1\n".repeat(2_000)),
597                    format!("case x of\n{}", "    _ -> 1\n".repeat(2_000)),
598                ];
599                for source in expressions {
600                    let source = crate::test_support::indent_fragment(&source);
601                    let bump = Bump::new();
602                    let mut parser = Parser::new(&bump, &source);
603                    parser.chomp(|_, _, _| ()).unwrap();
604                    parser.expression().unwrap();
605                    assert!(parser.is_eof());
606                }
607                let bump = Bump::new();
608                let source = format!("type Many = A{}", " | A".repeat(2_000));
609                let mut parser = Parser::new(&bump, &source);
610                parser.declaration().unwrap();
611                assert!(parser.is_eof());
612                let source = format!("{}{}", "{-".repeat(65_536), "-}".repeat(65_536));
613                let mut parser = Parser::new(&bump, &source);
614                parser.chomp(|_, _, _| ()).unwrap();
615                assert!(parser.is_eof());
616            })
617            .unwrap()
618            .join()
619            .unwrap();
620    }
621
622    #[test]
623    fn coordinates_cover_large_sources() {
624        let bump = Bump::new();
625        let lines = "\n".repeat(65_536);
626        let mut parser = Parser::new(&bump, &lines);
627        parser.advance_by(lines.len());
628        assert_eq!(parser.row(), 65_537);
629        assert_eq!(parser.col(), 1);
630
631        let string = format!("\"{}\"", "x".repeat(65_536));
632        let mut parser = Parser::new(&bump, &string);
633        parser.expression().expect("long string");
634        assert!(parser.is_eof());
635        assert_eq!(parser.col(), string.len() + 1);
636
637        let indented = format!("{}x", " ".repeat(65_536));
638        let mut parser = Parser::new(&bump, &indented);
639        parser.chomp(|_, _, _| ()).expect("long indentation");
640        assert_eq!(parser.col(), 65_537);
641        parser.expression().expect("indented expression");
642        assert!(parser.is_eof());
643
644        let escaped = format!("\"\\u{{{}}}\"", "F".repeat(65_536));
645        let mut parser = Parser::new(&bump, &escaped);
646        let error::Expr::String(
647            error::StringError::Escape(error::Escape::BadUnicodeCode(width)),
648            1,
649            3,
650        ) = parser.expression().expect_err("oversized Unicode escape")
651        else {
652            panic!("expected an invalid Unicode code with its full width");
653        };
654        assert_eq!(width, 65_539);
655    }
656
657    #[test]
658    fn lookahead_offset_cannot_wrap() {
659        let bump = Bump::new();
660        let mut parser = Parser::new(&bump, "xy");
661        parser.advance();
662        assert_eq!(parser.peek_at(usize::MAX), None);
663    }
664
665    use super::*;
666
667    #[test]
668    fn test_parser_new() {
669        let bump = Bump::new();
670        let src = bump.alloc_str("hello");
671        let parser = Parser::new(&bump, src);
672
673        assert_eq!(parser.row(), 1);
674        assert_eq!(parser.col(), 1);
675        assert_eq!(parser.peek(), Some(b'h'));
676        assert!(!parser.is_eof());
677    }
678
679    #[test]
680    fn test_parser_advance() {
681        let bump = Bump::new();
682        let src = bump.alloc_str("ab\ncd");
683        let mut parser = Parser::new(&bump, src);
684
685        assert_eq!(parser.position(), (1, 1));
686        parser.advance(); // 'a'
687        assert_eq!(parser.position(), (1, 2));
688        parser.advance(); // 'b'
689        assert_eq!(parser.position(), (1, 3));
690        parser.advance(); // '\n'
691        assert_eq!(parser.position(), (2, 1));
692        parser.advance(); // 'c'
693        assert_eq!(parser.position(), (2, 2));
694    }
695
696    #[test]
697    fn test_parser_eof() {
698        let bump = Bump::new();
699        let src = bump.alloc_str("x");
700        let mut parser = Parser::new(&bump, src);
701
702        assert!(!parser.is_eof());
703        parser.advance();
704        assert!(parser.is_eof());
705        assert_eq!(parser.peek(), None);
706    }
707}