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