Skip to main content

nash_parse/
space.rs

1//! Whitespace and comment handling for Nash.
2//!
3//! Ported from Elm's `Parse/Space.hs`.
4//!
5//! Handles:
6//! - Spaces and newlines
7//! - Line comments (`--`)
8//! - Multi-line comments (`{- ... -}`) with nesting
9//! - Doc comments (`{-| ... -}`)
10//! - Indentation checking
11//! - Tab detection (tabs are not allowed)
12
13use crate::error::Space;
14use crate::{Col, Parser, Row};
15use nash_source::{Comment, CommentKind, Snippet, SourceComment};
16
17/// Result of eating spaces.
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub enum SpaceStatus {
20    /// Successfully consumed whitespace.
21    Good,
22    /// Encountered a tab character (not allowed).
23    HasTab,
24    /// Encountered an unclosed multi-line comment.
25    EndlessMultiComment(nash_region::Position),
26}
27
28impl<'a> Parser<'a> {
29    /// Consume whitespace and comments.
30    ///
31    /// Returns an error if tabs or unclosed comments are found.
32    /// Mirrors Elm's `Space.chomp`.
33    pub fn chomp<E>(&mut self, to_error: impl FnOnce(Space, Row, Col) -> E) -> Result<(), E> {
34        let (status, new_row, new_col) = self.eat_spaces();
35
36        match status {
37            SpaceStatus::Good => Ok(()),
38            SpaceStatus::HasTab => Err(to_error(Space::HasTab, new_row, new_col)),
39            SpaceStatus::EndlessMultiComment(opening) => Err(to_error(
40                Space::EndlessMultiComment(opening),
41                new_row,
42                new_col,
43            )),
44        }
45    }
46
47    /// Consume whitespace and require indentation past the current level.
48    /// A closing delimiter may align with the current statement.
49    ///
50    /// Mirrors Elm's `Space.chompAndCheckIndent`.
51    pub fn chomp_and_check_indent<E>(
52        &mut self,
53        to_space_error: impl FnOnce(Space, Row, Col) -> E,
54        to_indent_error: impl FnOnce(Row, Col) -> E,
55    ) -> Result<(), E> {
56        let (row_before, col_before) = self.position();
57        let (status, new_row, new_col) = self.eat_spaces();
58
59        match status {
60            SpaceStatus::Good => {
61                if new_col > 1
62                    && (new_col > self.indent
63                        || (new_col == self.indent
64                            && matches!(self.peek(), Some(b')' | b']' | b'}'))))
65                {
66                    Ok(())
67                } else {
68                    let (row, col) = if matches!(self.peek(), Some(b')' | b']' | b'}')) {
69                        (new_row, new_col)
70                    } else {
71                        (row_before, col_before)
72                    };
73                    Err(to_indent_error(row, col))
74                }
75            }
76            SpaceStatus::HasTab => Err(to_space_error(Space::HasTab, new_row, new_col)),
77            SpaceStatus::EndlessMultiComment(opening) => Err(to_space_error(
78                Space::EndlessMultiComment(opening),
79                new_row,
80                new_col,
81            )),
82        }
83    }
84
85    /// Check that the parser's CURRENT column is past the indent level and
86    /// not at column 1 (which starts a fresh top-level declaration).
87    ///
88    /// Mirrors Elm's `Space.checkIndent`: the passed position is only the
89    /// location to report on failure; the check itself is `col > indent
90    /// && col > 1` on the current state.
91    pub fn check_indent<E>(
92        &self,
93        end_row: Row,
94        end_col: Col,
95        to_error: impl FnOnce(Row, Col) -> E,
96    ) -> Result<(), E> {
97        if self.col > self.indent && self.col > 1 {
98            Ok(())
99        } else {
100            // A closing token is present but underindented. Keep its actual
101            // position even when intervening whitespace contains comments.
102            let (row, col) = if matches!(self.peek(), Some(b')' | b']' | b'}')) {
103                self.position()
104            } else {
105                (end_row, end_col)
106            };
107            Err(to_error(row, col))
108        }
109    }
110
111    /// Explicit continuation tokens may align with a statement. Ordinary
112    /// expression continuation stays strict so adjacent statements never merge.
113    pub(crate) fn check_explicit_indent<E>(
114        &self,
115        end_row: Row,
116        end_col: Col,
117        to_error: impl FnOnce(Row, Col) -> E,
118    ) -> Result<(), E> {
119        if self.col == self.indent && self.col > 1 {
120            Ok(())
121        } else {
122            self.check_indent(end_row, end_col, to_error)
123        }
124    }
125
126    /// Check that current column equals indent level (for alignment).
127    ///
128    /// Mirrors Elm's `Space.checkAligned`.
129    pub fn check_aligned<E>(&self, to_error: impl FnOnce(usize, Row, Col) -> E) -> Result<(), E> {
130        if self.col == self.indent {
131            Ok(())
132        } else {
133            Err(to_error(self.indent, self.row, self.col))
134        }
135    }
136
137    /// Check that we're at column 1 (start of a fresh line).
138    ///
139    /// Mirrors Elm's `Space.checkFreshLine`.
140    pub fn check_fresh_line<E>(&self, to_error: impl FnOnce(Row, Col) -> E) -> Result<(), E> {
141        if self.col == 1 {
142            Ok(())
143        } else {
144            Err(to_error(self.row, self.col))
145        }
146    }
147
148    /// Parse a doc comment `{-| ... -}`.
149    ///
150    /// Returns the Comment containing a Snippet of the content.
151    /// Mirrors Elm's `Space.docComment`.
152    pub fn doc_comment<E>(
153        &mut self,
154        to_expectation: impl FnOnce(Row, Col) -> E,
155        to_space_error: impl FnOnce(Space, Row, Col) -> E,
156    ) -> Result<&'a Comment<'a>, E> {
157        // Check for {-| at current position
158        if self.peek() == Some(0x7B)
159            && self.peek_at(1) == Some(0x2D)
160            && self.peek_at(2) == Some(0x7C)
161        {
162            let start_row = self.row;
163            let start_col = self.col + 3; // Column after {-|
164
165            // Skip {-|
166            self.advance();
167            self.advance();
168            self.advance();
169
170            let content_start = self.pos;
171
172            // Use the existing multi-comment helper with nesting=1
173            let status = self
174                .eat_multi_comment_help(1, nash_region::Position::new(start_row, start_col - 3));
175
176            match status {
177                SpaceStatus::Good => {
178                    // Content ends 2 bytes before current position (before -})
179                    let content_end = self.pos - 2;
180                    let content = &self.src[content_start..content_end];
181
182                    let snippet = self.alloc(Snippet {
183                        data: content,
184                        off_row: start_row,
185                        off_col: start_col,
186                    });
187                    let comment = self.alloc(Comment {
188                        region: nash_region::Region::new(
189                            nash_region::Position::new(start_row, start_col - 3),
190                            self.get_position(),
191                        ),
192                        snippet,
193                    });
194
195                    Ok(comment)
196                }
197                SpaceStatus::HasTab => Err(to_space_error(Space::HasTab, self.row, self.col)),
198                SpaceStatus::EndlessMultiComment(opening) => Err(to_space_error(
199                    Space::EndlessMultiComment(opening),
200                    self.row,
201                    self.col,
202                )),
203            }
204        } else {
205            Err(to_expectation(self.row, self.col))
206        }
207    }
208
209    /// Core function to eat spaces, newlines, and comments.
210    ///
211    /// Updates parser position and returns status.
212    fn eat_spaces(&mut self) -> (SpaceStatus, Row, Col) {
213        loop {
214            match self.peek() {
215                // Space
216                Some(0x20) => {
217                    self.advance();
218                }
219
220                // Newline
221                Some(0x0A) => {
222                    self.advance();
223                }
224
225                // Carriage return (skip)
226                Some(0x0D) => {
227                    self.advance();
228                }
229
230                // Potential comment start: { or -
231                Some(0x7B) => {
232                    // Check for {-
233                    if self.peek_at(1) == Some(0x2D) {
234                        // Check for {-| (doc comment marker - don't consume, let caller handle)
235                        if self.peek_at(2) == Some(0x7C) {
236                            return (SpaceStatus::Good, self.row, self.col);
237                        }
238                        // Multi-line comment
239                        match self.eat_multi_comment() {
240                            SpaceStatus::Good => {
241                                // Continue eating spaces
242                            }
243                            status => return (status, self.row, self.col),
244                        }
245                    } else {
246                        return (SpaceStatus::Good, self.row, self.col);
247                    }
248                }
249
250                Some(0x2D) => {
251                    // Check for --
252                    if self.peek_at(1) == Some(0x2D) {
253                        self.eat_line_comment();
254                        // Continue eating spaces
255                    } else {
256                        return (SpaceStatus::Good, self.row, self.col);
257                    }
258                }
259
260                // Tab (not allowed)
261                Some(0x09) => {
262                    return (SpaceStatus::HasTab, self.row, self.col);
263                }
264
265                // Anything else (including EOF)
266                _ => {
267                    return (SpaceStatus::Good, self.row, self.col);
268                }
269            }
270        }
271    }
272
273    /// Eat a line comment (from -- to end of line).
274    fn eat_line_comment(&mut self) {
275        let start = self.get_position();
276        self.advance_by(2);
277        let text_start = self.pos;
278        while !matches!(self.peek(), None | Some(b'\n'))
279            && !(self.peek() == Some(b'\r') && self.peek_at(1) == Some(b'\n'))
280        {
281            self.advance();
282        }
283        self.push_comment(start, CommentKind::Line, text_start, self.pos);
284        // The surrounding whitespace loop consumes the line ending.
285    }
286
287    fn push_comment(
288        &mut self,
289        start: nash_region::Position,
290        kind: CommentKind,
291        text_start: usize,
292        text_end: usize,
293    ) {
294        let text = std::str::from_utf8(&self.src[text_start..text_end])
295            .expect("source is valid UTF-8 and comment delimiters are ASCII");
296        let comment = self.alloc(SourceComment {
297            region: nash_region::Region::new(start, self.get_position()),
298            kind,
299            text,
300        });
301        self.comments.push(comment);
302    }
303
304    /// Eat a multi-line comment ({- ... -}).
305    ///
306    /// Supports nested comments.
307    fn eat_multi_comment(&mut self) -> SpaceStatus {
308        let opening = nash_region::Position::new(self.row(), self.col());
309        // Skip the {-
310        self.advance();
311        self.advance();
312
313        let text_start = self.pos;
314        let status = self.eat_multi_comment_help(1, opening);
315        if matches!(status, SpaceStatus::Good) {
316            self.push_comment(opening, CommentKind::Block, text_start, self.pos - 2);
317        }
318        status
319    }
320
321    /// Helper for eating multi-line comments with nesting.
322    fn eat_multi_comment_help(
323        &mut self,
324        mut open_comments: usize,
325        opening: nash_region::Position,
326    ) -> SpaceStatus {
327        loop {
328            match self.peek() {
329                // Newline
330                Some(0x0A) => {
331                    self.advance();
332                }
333
334                // Tab (not allowed even in comments)
335                Some(0x09) => {
336                    return SpaceStatus::HasTab;
337                }
338
339                // Potential close: -}
340                Some(0x2D) => {
341                    if self.peek_at(1) == Some(0x7D) {
342                        self.advance();
343                        self.advance();
344                        if open_comments == 1 {
345                            return SpaceStatus::Good;
346                        } else {
347                            open_comments -= 1;
348                        }
349                    } else {
350                        self.advance();
351                    }
352                }
353
354                // Potential nested open: {-
355                Some(0x7B) => {
356                    if self.peek_at(1) == Some(0x2D) {
357                        self.advance();
358                        self.advance();
359                        open_comments += 1;
360                    } else {
361                        self.advance();
362                    }
363                }
364
365                // Any other character
366                Some(_) => {
367                    self.advance();
368                }
369
370                // EOF without closing
371                None => {
372                    return SpaceStatus::EndlessMultiComment(opening);
373                }
374            }
375        }
376    }
377}
378
379#[cfg(test)]
380mod tests {
381    use super::*;
382    use bumpalo::Bump;
383
384    fn parse_and_chomp(input: &str) -> (SpaceStatus, usize, Row, Col) {
385        let bump = Bump::new();
386        let src = bump.alloc_str(input);
387        let mut parser = Parser::new(&bump, src);
388
389        let (status, row, col) = parser.eat_spaces();
390        (status, parser.pos, row, col)
391    }
392
393    #[test]
394    fn empty() {
395        let (status, pos, _, _) = parse_and_chomp("");
396        assert_eq!(status, SpaceStatus::Good);
397        assert_eq!(pos, 0);
398    }
399
400    #[test]
401    fn spaces_only() {
402        let (status, pos, _, _) = parse_and_chomp("   ");
403        assert_eq!(status, SpaceStatus::Good);
404        assert_eq!(pos, 3);
405    }
406
407    #[test]
408    fn newlines() {
409        let (status, pos, row, col) = parse_and_chomp("  \n  \n  ");
410        assert_eq!(status, SpaceStatus::Good);
411        assert_eq!(pos, 8);
412        assert_eq!(row, 3);
413        assert_eq!(col, 3);
414    }
415
416    #[test]
417    fn line_comment() {
418        let (status, pos, _, _) = parse_and_chomp("-- comment\nfoo");
419        assert_eq!(status, SpaceStatus::Good);
420        assert_eq!(pos, 11); // After the newline
421    }
422
423    #[test]
424    fn multi_comment() {
425        let (status, pos, _, _) = parse_and_chomp("{- comment -}foo");
426        assert_eq!(status, SpaceStatus::Good);
427        assert_eq!(pos, 13);
428    }
429
430    #[test]
431    fn nested_multi_comment() {
432        let (status, pos, _, _) = parse_and_chomp("{- outer {- inner -} outer -}foo");
433        assert_eq!(status, SpaceStatus::Good);
434        assert_eq!(pos, 29);
435    }
436
437    #[test]
438    fn tab_error() {
439        let (status, _, _, _) = parse_and_chomp("  \t  ");
440        assert_eq!(status, SpaceStatus::HasTab);
441    }
442
443    #[test]
444    fn endless_multi_comment() {
445        let (status, _, _, _) = parse_and_chomp("{- never closed");
446        assert_eq!(
447            status,
448            SpaceStatus::EndlessMultiComment(nash_region::Position::new(1, 1))
449        );
450    }
451
452    #[test]
453    fn doc_comment_not_consumed() {
454        // {-| should not be consumed - it's a doc comment for the caller
455        let (status, pos, _, _) = parse_and_chomp("{-| doc -}");
456        assert_eq!(status, SpaceStatus::Good);
457        assert_eq!(pos, 0); // Not consumed
458    }
459
460    #[test]
461    fn stops_at_content() {
462        let (status, pos, _, _) = parse_and_chomp("  foo");
463        assert_eq!(status, SpaceStatus::Good);
464        assert_eq!(pos, 2); // Stopped at 'f'
465    }
466
467    #[test]
468    fn doc_comment_simple() {
469        let bump = Bump::new();
470        let src = bump.alloc_str("{-| hello -}");
471        let mut parser = Parser::new(&bump, src);
472
473        let result = parser.doc_comment(|_, _| "expected", |_, _, _| "space error");
474        assert!(result.is_ok());
475        let comment = result.unwrap();
476        // Content is " hello " (between {-| and -})
477        assert_eq!(comment.snippet.data, b" hello ");
478        assert_eq!(comment.snippet.off_row, 1);
479        assert_eq!(comment.snippet.off_col, 4); // Column after {-|
480    }
481
482    #[test]
483    fn doc_comment_multiline() {
484        let bump = Bump::new();
485        let src = bump.alloc_str("{-| line one\nline two -}");
486        let mut parser = Parser::new(&bump, src);
487
488        let result = parser.doc_comment(|_, _| "expected", |_, _, _| "space error");
489        assert!(result.is_ok());
490        let comment = result.unwrap();
491        assert_eq!(comment.snippet.data, b" line one\nline two ");
492    }
493
494    #[test]
495    fn doc_comment_not_doc() {
496        let bump = Bump::new();
497        let src = bump.alloc_str("{- not a doc comment -}");
498        let mut parser = Parser::new(&bump, src);
499
500        let result = parser.doc_comment(|_, _| "expected", |_, _, _| "space error");
501        assert!(result.is_err());
502        assert_eq!(result.unwrap_err(), "expected");
503    }
504}