nash_parse/lib.rs
1use bumpalo::Bump;
2use nash_region::{Located, Position, Region};
3
4mod declaration;
5pub mod error;
6mod exposing;
7mod expression;
8mod import;
9mod keyword;
10mod module;
11mod number;
12mod pattern;
13mod space;
14mod string;
15mod symbol;
16#[cfg(test)]
17pub(crate) mod test_support;
18mod type_;
19
20pub type Row = u16;
21pub type Col = u16;
22
23/// Saved parser state for backtracking.
24#[derive(Clone, Copy)]
25struct ParserState {
26 pos: usize,
27 indent: u16,
28 row: Row,
29 col: Col,
30}
31
32/// Parser for Nash source code.
33///
34/// Combines the arena allocator with parsing state for a unified API.
35/// All parsed AST nodes are allocated in the provided bump arena.
36///
37/// The source bytes should already be allocated in the arena (via `bump.alloc_str`),
38/// so all string slices in the resulting AST share the `'a` lifetime.
39pub struct Parser<'a> {
40 /// Arena allocator for AST nodes
41 bump: &'a Bump,
42 /// Source bytes (UTF-8, already in arena)
43 src: &'a [u8],
44 /// Current byte position
45 pos: usize,
46 /// Current indentation level (for layout-sensitive parsing)
47 indent: u16,
48 /// Current row (1-indexed)
49 row: Row,
50 /// Current column (1-indexed)
51 col: Col,
52}
53
54impl<'a> Parser<'a> {
55 /// Create a new parser for the given source bytes.
56 ///
57 /// The source should already be allocated in the arena.
58 pub fn new(bump: &'a Bump, src: &'a [u8]) -> Self {
59 Parser {
60 bump,
61 src,
62 pos: 0,
63 // Elm starts at 0; 1 is behaviorally identical because
64 // `checkIndent`'s `col > 1` guard dominates at top level.
65 indent: 1,
66 row: 1,
67 col: 1,
68 }
69 }
70
71 // -------------------------------------------------------------------------
72 // Position & State
73 // -------------------------------------------------------------------------
74
75 /// Current position as (row, col).
76 #[inline]
77 pub fn position(&self) -> (Row, Col) {
78 (self.row, self.col)
79 }
80
81 /// Get the current position as a `Position`.
82 #[inline]
83 pub fn get_position(&self) -> Position {
84 Position::new(self.row, self.col)
85 }
86
87 /// Create a `Located` value spanning from `start` to the current position,
88 /// allocated directly in the arena.
89 #[inline]
90 pub fn add_end<T>(&self, start: Position, value: T) -> &'a Located<T> {
91 let end = self.get_position();
92 self.alloc(Located::at(Region::new(start, end), value))
93 }
94
95 /// Current row (1-indexed).
96 #[inline]
97 pub fn row(&self) -> Row {
98 self.row
99 }
100
101 /// Current column (1-indexed).
102 #[inline]
103 pub fn col(&self) -> Col {
104 self.col
105 }
106
107 /// Current indentation level.
108 #[inline]
109 pub fn indent(&self) -> u16 {
110 self.indent
111 }
112
113 /// Set the indentation level.
114 #[inline]
115 pub fn set_indent(&mut self, indent: u16) {
116 self.indent = indent;
117 }
118
119 /// Run a parser with the current column as the indent level,
120 /// then restore the old indent level.
121 ///
122 /// Mirrors Elm's `withIndent`:
123 /// ```haskell
124 /// withIndent (Parser parser) =
125 /// Parser $ \(State src pos end oldIndent row col) cok eok cerr eerr ->
126 /// let
127 /// cok' a (State s p e _ r c) = cok a (State s p e oldIndent r c)
128 /// eok' a (State s p e _ r c) = eok a (State s p e oldIndent r c)
129 /// in
130 /// parser (State src pos end col row col) cok' eok' cerr eerr
131 /// ```
132 pub fn with_indent<T, E>(
133 &mut self,
134 parser: impl FnOnce(&mut Self) -> Result<T, E>,
135 ) -> Result<T, E> {
136 let old_indent = self.indent;
137 self.indent = self.col;
138 let result = parser(self);
139 self.indent = old_indent;
140 result
141 }
142
143 /// Run a parser with indent set to (current column - backset),
144 /// then restore the old indent level.
145 ///
146 /// Mirrors Elm's `withBacksetIndent`:
147 /// ```haskell
148 /// withBacksetIndent backset (Parser parser) =
149 /// Parser $ \(State src pos end oldIndent row col) cok eok cerr eerr ->
150 /// parser (State src pos end (col - backset) row col) ...
151 /// ```
152 pub fn with_backset_indent<T, E>(
153 &mut self,
154 backset: u16,
155 parser: impl FnOnce(&mut Self) -> Result<T, E>,
156 ) -> Result<T, E> {
157 let old_indent = self.indent;
158 self.indent = self.col.saturating_sub(backset);
159 let result = parser(self);
160 self.indent = old_indent;
161 result
162 }
163
164 /// Check if we've reached the end of input.
165 #[inline]
166 pub fn is_eof(&self) -> bool {
167 self.pos >= self.src.len()
168 }
169
170 /// Save current parser state for backtracking.
171 #[inline]
172 fn save_state(&self) -> ParserState {
173 ParserState {
174 pos: self.pos,
175 indent: self.indent,
176 row: self.row,
177 col: self.col,
178 }
179 }
180
181 /// Restore parser state for backtracking.
182 #[inline]
183 fn restore_state(&mut self, state: ParserState) {
184 self.pos = state.pos;
185 self.indent = state.indent;
186 self.row = state.row;
187 self.col = state.col;
188 }
189
190 // -------------------------------------------------------------------------
191 // Combinators
192 // -------------------------------------------------------------------------
193
194 /// Try multiple parsers in order, returning the first success.
195 ///
196 /// Mirrors Elm's `oneOf`:
197 /// ```haskell
198 /// oneOf :: (Row -> Col -> x) -> [Parser x a] -> Parser x a
199 /// ```
200 ///
201 /// Key semantics:
202 /// - If a parser fails without consuming input, try the next one
203 /// - If a parser fails after consuming input, propagate the error (committed)
204 /// - If all parsers fail without consuming, call `to_error(row, col)`
205 ///
206 /// # Example
207 /// ```ignore
208 /// parser.one_of(
209 /// error::Expr::Start,
210 /// vec![
211 /// Box::new(|p: &mut Parser| p.string(start)),
212 /// Box::new(|p| p.number(start)),
213 /// ],
214 /// )
215 /// ```
216 #[allow(clippy::type_complexity)]
217 pub fn one_of<T, E>(
218 &mut self,
219 to_error: impl FnOnce(Row, Col) -> E,
220 parsers: Vec<Box<dyn FnOnce(&mut Self) -> Result<T, E> + '_>>,
221 ) -> Result<T, E> {
222 let initial_state = self.save_state();
223
224 for parser in parsers {
225 let before = self.save_state();
226 match parser(self) {
227 Ok(value) => return Ok(value),
228 Err(e) => {
229 // Did we consume any input?
230 if self.pos != before.pos {
231 // Committed - propagate error
232 return Err(e);
233 }
234 // No input consumed - restore and try next
235 self.restore_state(before);
236 }
237 }
238 }
239
240 // All parsers failed without consuming - restore to initial and return error
241 self.restore_state(initial_state);
242 let (row, col) = self.position();
243 Err(to_error(row, col))
244 }
245
246 /// Like `one_of` but returns a fallback value if nothing matches.
247 ///
248 /// Mirrors Elm's `oneOfWithFallback`:
249 /// ```haskell
250 /// oneOfWithFallback :: [Parser x a] -> a -> Parser x a
251 /// ```
252 #[allow(clippy::type_complexity)]
253 pub fn one_of_with_fallback<T, E>(
254 &mut self,
255 parsers: Vec<Box<dyn FnOnce(&mut Self) -> Result<T, E> + '_>>,
256 fallback: T,
257 ) -> Result<T, E> {
258 let initial_state = self.save_state();
259
260 for parser in parsers {
261 let before = self.save_state();
262 match parser(self) {
263 Ok(value) => return Ok(value),
264 Err(e) => {
265 // Did we consume any input?
266 if self.pos != before.pos {
267 // Committed - propagate error
268 return Err(e);
269 }
270 // No input consumed - restore and try next
271 self.restore_state(before);
272 }
273 }
274 }
275
276 // All parsers failed without consuming - return fallback
277 self.restore_state(initial_state);
278 Ok(fallback)
279 }
280
281 /// Parse with error context wrapping.
282 ///
283 /// Mirrors Elm's `inContext`:
284 /// ```haskell
285 /// inContext :: (x -> Row -> Col -> y) -> Parser y start -> Parser x a -> Parser y a
286 /// ```
287 ///
288 /// 1. Saves the starting position
289 /// 2. Runs `start_parser` - if it fails without consuming, returns that error
290 /// 3. If start succeeds, runs `body_parser`
291 /// 4. If body fails, wraps the error using `add_context` at the original position
292 ///
293 /// The `add_context` closure receives the bump allocator so it can allocate wrapped errors.
294 ///
295 /// This is used to provide better error context, e.g., "error in list expression".
296 pub fn in_context<T, StartErr, BodyErr, ContextErr>(
297 &mut self,
298 add_context: impl FnOnce(&'a Bump, BodyErr, Row, Col) -> ContextErr,
299 start_parser: impl FnOnce(&mut Self) -> Result<(), StartErr>,
300 body_parser: impl FnOnce(&mut Self) -> Result<T, BodyErr>,
301 ) -> Result<T, ContextErr>
302 where
303 StartErr: Into<ContextErr>,
304 {
305 let (start_row, start_col) = self.position();
306
307 // Try to parse start token
308 match start_parser(self) {
309 Ok(()) => {
310 // Start succeeded, now parse body
311 match body_parser(self) {
312 Ok(value) => Ok(value),
313 Err(body_err) => {
314 // Wrap body error with context at original position
315 Err(add_context(self.bump, body_err, start_row, start_col))
316 }
317 }
318 }
319 Err(start_err) => {
320 // Start failed - convert to context error type
321 Err(start_err.into())
322 }
323 }
324 }
325
326 /// Transform errors from one type to another with position context.
327 ///
328 /// Mirrors Elm's `specialize`:
329 /// ```haskell
330 /// specialize :: (x -> Row -> Col -> y) -> Parser x a -> Parser y a
331 /// ```
332 ///
333 /// Runs the parser and wraps any error with the context at the starting position.
334 /// The `add_context` closure receives the bump allocator so it can allocate wrapped errors.
335 pub fn specialize<T, InnerErr, OuterErr>(
336 &mut self,
337 add_context: impl FnOnce(&'a Bump, InnerErr, Row, Col) -> OuterErr,
338 parser: impl FnOnce(&mut Self) -> Result<T, InnerErr>,
339 ) -> Result<T, OuterErr> {
340 let (start_row, start_col) = self.position();
341
342 match parser(self) {
343 Ok(value) => Ok(value),
344 Err(inner_err) => Err(add_context(self.bump, inner_err, start_row, start_col)),
345 }
346 }
347
348 // -------------------------------------------------------------------------
349 // Single-byte parsing
350 // -------------------------------------------------------------------------
351
352 /// Parse a single expected byte.
353 ///
354 /// Mirrors Elm's `word1`:
355 /// ```haskell
356 /// word1 :: Word8 -> (Row -> Col -> x) -> Parser x ()
357 /// ```
358 ///
359 /// Returns `Ok(())` and advances if the byte matches.
360 /// Returns `Err` without consuming if it doesn't match.
361 #[inline]
362 pub fn word1<E>(
363 &mut self,
364 expected: u8,
365 to_error: impl FnOnce(Row, Col) -> E,
366 ) -> Result<(), E> {
367 if self.peek() == Some(expected) {
368 self.advance();
369 Ok(())
370 } else {
371 let (row, col) = self.position();
372 Err(to_error(row, col))
373 }
374 }
375
376 /// Parse two expected consecutive bytes.
377 ///
378 /// Mirrors Elm's `word2`:
379 /// ```haskell
380 /// word2 :: Word8 -> Word8 -> (Row -> Col -> x) -> Parser x ()
381 /// ```
382 #[inline]
383 pub fn word2<E>(
384 &mut self,
385 b1: u8,
386 b2: u8,
387 to_error: impl FnOnce(Row, Col) -> E,
388 ) -> Result<(), E> {
389 if self.peek() == Some(b1) && self.peek_at(1) == Some(b2) {
390 self.advance();
391 self.advance();
392 Ok(())
393 } else {
394 let (row, col) = self.position();
395 Err(to_error(row, col))
396 }
397 }
398
399 // -------------------------------------------------------------------------
400 // Peeking
401 // -------------------------------------------------------------------------
402
403 /// Peek at the current byte without consuming it.
404 #[inline]
405 pub fn peek(&self) -> Option<u8> {
406 self.src.get(self.pos).copied()
407 }
408
409 /// Peek at a byte at the given offset from current position.
410 #[inline]
411 pub fn peek_at(&self, offset: usize) -> Option<u8> {
412 self.src.get(self.pos + offset).copied()
413 }
414
415 /// Get the remaining bytes from current position.
416 #[inline]
417 pub fn remaining(&self) -> &'a [u8] {
418 &self.src[self.pos..]
419 }
420
421 // -------------------------------------------------------------------------
422 // Advancing
423 // -------------------------------------------------------------------------
424
425 /// Advance by one byte, updating row/col for newlines.
426 #[inline]
427 pub fn advance(&mut self) {
428 if let Some(b) = self.peek() {
429 self.pos += 1;
430 if b == b'\n' {
431 self.row += 1;
432 self.col = 1;
433 } else {
434 self.col += 1;
435 }
436 }
437 }
438
439 /// Advance by n bytes, tracking newlines.
440 #[inline]
441 pub fn advance_by(&mut self, n: usize) {
442 for _ in 0..n {
443 self.advance();
444 }
445 }
446
447 // -------------------------------------------------------------------------
448 // Allocation helpers
449 // -------------------------------------------------------------------------
450
451 /// Allocate a value in the arena.
452 #[inline]
453 pub fn alloc<T>(&self, value: T) -> &'a T {
454 self.bump.alloc(value)
455 }
456
457 /// Allocate a slice in the arena by copying.
458 #[inline]
459 pub fn alloc_slice_copy<T: Copy>(&self, slice: &[T]) -> &'a [T] {
460 self.bump.alloc_slice_copy(slice)
461 }
462
463 /// Allocate a string in the arena (for constructed strings like escape sequences).
464 #[inline]
465 pub fn alloc_str(&self, s: &str) -> &'a str {
466 self.bump.alloc_str(s)
467 }
468}
469
470#[cfg(test)]
471mod tests {
472 use super::*;
473
474 #[test]
475 fn test_parser_new() {
476 let bump = Bump::new();
477 let src = bump.alloc_str("hello");
478 let parser = Parser::new(&bump, src.as_bytes());
479
480 assert_eq!(parser.row(), 1);
481 assert_eq!(parser.col(), 1);
482 assert_eq!(parser.peek(), Some(b'h'));
483 assert!(!parser.is_eof());
484 }
485
486 #[test]
487 fn test_parser_advance() {
488 let bump = Bump::new();
489 let src = bump.alloc_str("ab\ncd");
490 let mut parser = Parser::new(&bump, src.as_bytes());
491
492 assert_eq!(parser.position(), (1, 1));
493 parser.advance(); // 'a'
494 assert_eq!(parser.position(), (1, 2));
495 parser.advance(); // 'b'
496 assert_eq!(parser.position(), (1, 3));
497 parser.advance(); // '\n'
498 assert_eq!(parser.position(), (2, 1));
499 parser.advance(); // 'c'
500 assert_eq!(parser.position(), (2, 2));
501 }
502
503 #[test]
504 fn test_parser_eof() {
505 let bump = Bump::new();
506 let src = bump.alloc_str("x");
507 let mut parser = Parser::new(&bump, src.as_bytes());
508
509 assert!(!parser.is_eof());
510 parser.advance();
511 assert!(parser.is_eof());
512 assert_eq!(parser.peek(), None);
513 }
514}