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