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