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 pos: usize,
29 indent: usize,
30 row: Row,
31 col: Col,
32}
33
34pub struct Parser<'a> {
42 bump: &'a Bump,
44 src: &'a [u8],
46 pos: usize,
48 indent: usize,
50 row: Row,
52 col: Col,
54 depth: usize,
55 depth_error: Option<(Row, Col)>,
56}
57
58impl<'a> Parser<'a> {
59 pub fn new(bump: &'a Bump, src: &'a str) -> Self {
69 Parser {
70 bump,
71 src: src.as_bytes(),
72 pos: 0,
73 indent: 1,
76 row: 1,
77 col: 1,
78 depth: 0,
79 depth_error: None,
80 }
81 }
82
83 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 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 #[inline]
117 pub fn position(&self) -> (Row, Col) {
118 (self.row, self.col)
119 }
120
121 #[inline]
123 pub fn get_position(&self) -> Position {
124 Position::new(self.row, self.col)
125 }
126
127 #[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 #[inline]
137 pub fn row(&self) -> Row {
138 self.row
139 }
140
141 #[inline]
143 pub fn col(&self) -> Col {
144 self.col
145 }
146
147 #[inline]
149 pub fn indent(&self) -> usize {
150 self.indent
151 }
152
153 #[inline]
155 pub fn set_indent(&mut self, indent: usize) {
156 self.indent = indent;
157 }
158
159 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 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 #[inline]
206 pub fn is_eof(&self) -> bool {
207 self.pos >= self.src.len()
208 }
209
210 #[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 #[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 #[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 if self.pos != before.pos || self.depth_error.is_some() {
271 return Err(e);
273 }
274 self.restore_state(before);
276 }
277 }
278 }
279
280 self.restore_state(initial_state);
282 let (row, col) = self.position();
283 Err(to_error(row, col))
284 }
285
286 #[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 if self.pos != before.pos || self.depth_error.is_some() {
307 return Err(e);
309 }
310 self.restore_state(before);
312 }
313 }
314 }
315
316 self.restore_state(initial_state);
318 Ok(fallback)
319 }
320
321 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 match start_parser(self) {
349 Ok(()) => {
350 match body_parser(self) {
352 Ok(value) => Ok(value),
353 Err(body_err) => {
354 Err(add_context(self.bump, body_err, start_row, start_col))
356 }
357 }
358 }
359 Err(start_err) => {
360 Err(start_err.into())
362 }
363 }
364 }
365
366 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 #[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 #[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 #[inline]
445 pub fn peek(&self) -> Option<u8> {
446 self.src.get(self.pos).copied()
447 }
448
449 #[inline]
451 pub fn peek_at(&self, offset: usize) -> Option<u8> {
452 self.src.get(self.pos.checked_add(offset)?).copied()
453 }
454
455 #[inline]
457 pub fn remaining(&self) -> &'a [u8] {
458 &self.src[self.pos..]
459 }
460
461 #[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 #[inline]
481 pub fn advance_by(&mut self, n: usize) {
482 for _ in 0..n {
483 self.advance();
484 }
485 }
486
487 #[inline]
493 pub fn alloc<T>(&self, value: T) -> &'a T {
494 self.bump.alloc(value)
495 }
496
497 #[inline]
499 pub fn alloc_slice_copy<T: Copy>(&self, slice: &[T]) -> &'a [T] {
500 self.bump.alloc_slice_copy(slice)
501 }
502
503 #[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(); assert_eq!(parser.position(), (1, 2));
688 parser.advance(); assert_eq!(parser.position(), (1, 3));
690 parser.advance(); assert_eq!(parser.position(), (2, 1));
692 parser.advance(); 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}