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#[derive(Clone, Copy)]
27struct ParserState {
28 comments_len: usize,
29 pos: usize,
30 indent: usize,
31 row: Row,
32 col: Col,
33}
34
35pub struct Parser<'a> {
43 comments: Vec<&'a nash_source::SourceComment<'a>>,
44 bump: &'a Bump,
46 src: &'a [u8],
48 pos: usize,
50 indent: usize,
52 row: Row,
54 col: Col,
56 depth: usize,
57 depth_error: Option<(Row, Col)>,
58}
59
60impl<'a> Parser<'a> {
61 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 indent: 1,
79 row: 1,
80 col: 1,
81 depth: 0,
82 depth_error: None,
83 }
84 }
85
86 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 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 #[inline]
120 pub fn position(&self) -> (Row, Col) {
121 (self.row, self.col)
122 }
123
124 #[inline]
126 pub fn get_position(&self) -> Position {
127 Position::new(self.row, self.col)
128 }
129
130 #[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 #[inline]
140 pub fn row(&self) -> Row {
141 self.row
142 }
143
144 #[inline]
146 pub fn col(&self) -> Col {
147 self.col
148 }
149
150 #[inline]
152 pub fn indent(&self) -> usize {
153 self.indent
154 }
155
156 #[inline]
158 pub fn set_indent(&mut self, indent: usize) {
159 self.indent = indent;
160 }
161
162 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 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 #[inline]
209 pub fn is_eof(&self) -> bool {
210 self.pos >= self.src.len()
211 }
212
213 #[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 #[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 #[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 if self.pos != before.pos || self.depth_error.is_some() {
276 return Err(e);
278 }
279 self.restore_state(before);
281 }
282 }
283 }
284
285 self.restore_state(initial_state);
287 let (row, col) = self.position();
288 Err(to_error(row, col))
289 }
290
291 #[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 if self.pos != before.pos || self.depth_error.is_some() {
312 return Err(e);
314 }
315 self.restore_state(before);
317 }
318 }
319 }
320
321 self.restore_state(initial_state);
323 Ok(fallback)
324 }
325
326 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 match start_parser(self) {
354 Ok(()) => {
355 match body_parser(self) {
357 Ok(value) => Ok(value),
358 Err(body_err) => {
359 Err(add_context(self.bump, body_err, start_row, start_col))
361 }
362 }
363 }
364 Err(start_err) => {
365 Err(start_err.into())
367 }
368 }
369 }
370
371 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 #[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 #[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 #[inline]
450 pub fn peek(&self) -> Option<u8> {
451 self.src.get(self.pos).copied()
452 }
453
454 #[inline]
456 pub fn peek_at(&self, offset: usize) -> Option<u8> {
457 self.src.get(self.pos.checked_add(offset)?).copied()
458 }
459
460 #[inline]
462 pub fn remaining(&self) -> &'a [u8] {
463 &self.src[self.pos..]
464 }
465
466 #[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 #[inline]
486 pub fn advance_by(&mut self, n: usize) {
487 for _ in 0..n {
488 self.advance();
489 }
490 }
491
492 #[inline]
498 pub fn alloc<T>(&self, value: T) -> &'a T {
499 self.bump.alloc(value)
500 }
501
502 #[inline]
504 pub fn alloc_slice_copy<T: Copy>(&self, slice: &[T]) -> &'a [T] {
505 self.bump.alloc_slice_copy(slice)
506 }
507
508 #[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(); assert_eq!(parser.position(), (1, 2));
693 parser.advance(); assert_eq!(parser.position(), (1, 3));
695 parser.advance(); assert_eq!(parser.position(), (2, 1));
697 parser.advance(); 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}