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, Snippet};
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,
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 => {
40                Err(to_error(Space::EndlessMultiComment, new_row, new_col))
41            }
42        }
43    }
44
45    /// Consume whitespace and check that we're indented past the current indent level.
46    ///
47    /// Mirrors Elm's `Space.chompAndCheckIndent`.
48    pub fn chomp_and_check_indent<E>(
49        &mut self,
50        to_space_error: impl FnOnce(Space, Row, Col) -> E,
51        to_indent_error: impl FnOnce(Row, Col) -> E,
52    ) -> Result<(), E> {
53        let (row_before, col_before) = self.position();
54        let (status, new_row, new_col) = self.eat_spaces();
55
56        match status {
57            SpaceStatus::Good => {
58                if new_col > self.indent && new_col > 1 {
59                    Ok(())
60                } else {
61                    Err(to_indent_error(row_before, col_before))
62                }
63            }
64            SpaceStatus::HasTab => Err(to_space_error(Space::HasTab, new_row, new_col)),
65            SpaceStatus::EndlessMultiComment => {
66                Err(to_space_error(Space::EndlessMultiComment, new_row, new_col))
67            }
68        }
69    }
70
71    /// Check that the parser's CURRENT column is past the indent level and
72    /// not at column 1 (which starts a fresh top-level declaration).
73    ///
74    /// Mirrors Elm's `Space.checkIndent`: the passed position is only the
75    /// location to report on failure; the check itself is `col > indent
76    /// && col > 1` on the current state.
77    pub fn check_indent<E>(
78        &self,
79        end_row: Row,
80        end_col: Col,
81        to_error: impl FnOnce(Row, Col) -> E,
82    ) -> Result<(), E> {
83        if self.col > self.indent && self.col > 1 {
84            Ok(())
85        } else {
86            Err(to_error(end_row, end_col))
87        }
88    }
89
90    /// Check that current column equals indent level (for alignment).
91    ///
92    /// Mirrors Elm's `Space.checkAligned`.
93    pub fn check_aligned<E>(&self, to_error: impl FnOnce(u16, Row, Col) -> E) -> Result<(), E> {
94        if self.col == self.indent {
95            Ok(())
96        } else {
97            Err(to_error(self.indent, self.row, self.col))
98        }
99    }
100
101    /// Check that we're at column 1 (start of a fresh line).
102    ///
103    /// Mirrors Elm's `Space.checkFreshLine`.
104    pub fn check_fresh_line<E>(&self, to_error: impl FnOnce(Row, Col) -> E) -> Result<(), E> {
105        if self.col == 1 {
106            Ok(())
107        } else {
108            Err(to_error(self.row, self.col))
109        }
110    }
111
112    /// Parse a doc comment `{-| ... -}`.
113    ///
114    /// Returns the Comment containing a Snippet of the content.
115    /// Mirrors Elm's `Space.docComment`.
116    pub fn doc_comment<E>(
117        &mut self,
118        to_expectation: impl FnOnce(Row, Col) -> E,
119        to_space_error: impl FnOnce(Space, Row, Col) -> E,
120    ) -> Result<&'a Comment<'a>, E> {
121        // Check for {-| at current position
122        if self.peek() == Some(0x7B)
123            && self.peek_at(1) == Some(0x2D)
124            && self.peek_at(2) == Some(0x7C)
125        {
126            let start_row = self.row;
127            let start_col = self.col + 3; // Column after {-|
128
129            // Skip {-|
130            self.advance();
131            self.advance();
132            self.advance();
133
134            let content_start = self.pos;
135
136            // Use the existing multi-comment helper with nesting=1
137            let status = self.eat_multi_comment_help(1);
138
139            match status {
140                SpaceStatus::Good => {
141                    // Content ends 2 bytes before current position (before -})
142                    let content_end = self.pos - 2;
143                    let content = &self.src[content_start..content_end];
144
145                    let snippet = self.alloc(Snippet {
146                        data: content,
147                        off_row: start_row,
148                        off_col: start_col,
149                    });
150                    let comment = self.alloc(Comment(snippet));
151
152                    Ok(comment)
153                }
154                SpaceStatus::HasTab => Err(to_space_error(Space::HasTab, self.row, self.col)),
155                SpaceStatus::EndlessMultiComment => Err(to_space_error(
156                    Space::EndlessMultiComment,
157                    self.row,
158                    self.col,
159                )),
160            }
161        } else {
162            Err(to_expectation(self.row, self.col))
163        }
164    }
165
166    /// Core function to eat spaces, newlines, and comments.
167    ///
168    /// Updates parser position and returns status.
169    fn eat_spaces(&mut self) -> (SpaceStatus, Row, Col) {
170        loop {
171            match self.peek() {
172                // Space
173                Some(0x20) => {
174                    self.advance();
175                }
176
177                // Newline
178                Some(0x0A) => {
179                    self.advance();
180                }
181
182                // Carriage return (skip)
183                Some(0x0D) => {
184                    self.advance();
185                }
186
187                // Potential comment start: { or -
188                Some(0x7B) => {
189                    // Check for {-
190                    if self.peek_at(1) == Some(0x2D) {
191                        // Check for {-| (doc comment marker - don't consume, let caller handle)
192                        if self.peek_at(2) == Some(0x7C) {
193                            return (SpaceStatus::Good, self.row, self.col);
194                        }
195                        // Multi-line comment
196                        match self.eat_multi_comment() {
197                            SpaceStatus::Good => {
198                                // Continue eating spaces
199                            }
200                            status => return (status, self.row, self.col),
201                        }
202                    } else {
203                        return (SpaceStatus::Good, self.row, self.col);
204                    }
205                }
206
207                Some(0x2D) => {
208                    // Check for --
209                    if self.peek_at(1) == Some(0x2D) {
210                        self.eat_line_comment();
211                        // Continue eating spaces
212                    } else {
213                        return (SpaceStatus::Good, self.row, self.col);
214                    }
215                }
216
217                // Tab (not allowed)
218                Some(0x09) => {
219                    return (SpaceStatus::HasTab, self.row, self.col);
220                }
221
222                // Anything else (including EOF)
223                _ => {
224                    return (SpaceStatus::Good, self.row, self.col);
225                }
226            }
227        }
228    }
229
230    /// Eat a line comment (from -- to end of line).
231    fn eat_line_comment(&mut self) {
232        // Skip the --
233        self.advance();
234        self.advance();
235
236        loop {
237            match self.peek() {
238                Some(0x0A) => {
239                    // Newline ends the comment
240                    self.advance();
241                    return;
242                }
243                Some(_) => {
244                    self.advance();
245                }
246                None => {
247                    // EOF ends the comment
248                    return;
249                }
250            }
251        }
252    }
253
254    /// Eat a multi-line comment ({- ... -}).
255    ///
256    /// Supports nested comments.
257    fn eat_multi_comment(&mut self) -> SpaceStatus {
258        // Skip the {-
259        self.advance();
260        self.advance();
261
262        self.eat_multi_comment_help(1)
263    }
264
265    /// Helper for eating multi-line comments with nesting.
266    fn eat_multi_comment_help(&mut self, open_comments: u16) -> SpaceStatus {
267        loop {
268            match self.peek() {
269                // Newline
270                Some(0x0A) => {
271                    self.advance();
272                }
273
274                // Tab (not allowed even in comments)
275                Some(0x09) => {
276                    return SpaceStatus::HasTab;
277                }
278
279                // Potential close: -}
280                Some(0x2D) => {
281                    if self.peek_at(1) == Some(0x7D) {
282                        self.advance();
283                        self.advance();
284                        if open_comments == 1 {
285                            return SpaceStatus::Good;
286                        } else {
287                            return self.eat_multi_comment_help(open_comments - 1);
288                        }
289                    } else {
290                        self.advance();
291                    }
292                }
293
294                // Potential nested open: {-
295                Some(0x7B) => {
296                    if self.peek_at(1) == Some(0x2D) {
297                        self.advance();
298                        self.advance();
299                        return self.eat_multi_comment_help(open_comments + 1);
300                    } else {
301                        self.advance();
302                    }
303                }
304
305                // Any other character
306                Some(_) => {
307                    self.advance();
308                }
309
310                // EOF without closing
311                None => {
312                    return SpaceStatus::EndlessMultiComment;
313                }
314            }
315        }
316    }
317}
318
319#[cfg(test)]
320mod tests {
321    use super::*;
322    use bumpalo::Bump;
323
324    fn parse_and_chomp(input: &str) -> (SpaceStatus, usize, Row, Col) {
325        let bump = Bump::new();
326        let src = bump.alloc_str(input);
327        let mut parser = Parser::new(&bump, src.as_bytes());
328
329        let (status, row, col) = parser.eat_spaces();
330        (status, parser.pos, row, col)
331    }
332
333    #[test]
334    fn empty() {
335        let (status, pos, _, _) = parse_and_chomp("");
336        assert_eq!(status, SpaceStatus::Good);
337        assert_eq!(pos, 0);
338    }
339
340    #[test]
341    fn spaces_only() {
342        let (status, pos, _, _) = parse_and_chomp("   ");
343        assert_eq!(status, SpaceStatus::Good);
344        assert_eq!(pos, 3);
345    }
346
347    #[test]
348    fn newlines() {
349        let (status, pos, row, col) = parse_and_chomp("  \n  \n  ");
350        assert_eq!(status, SpaceStatus::Good);
351        assert_eq!(pos, 8);
352        assert_eq!(row, 3);
353        assert_eq!(col, 3);
354    }
355
356    #[test]
357    fn line_comment() {
358        let (status, pos, _, _) = parse_and_chomp("-- comment\nfoo");
359        assert_eq!(status, SpaceStatus::Good);
360        assert_eq!(pos, 11); // After the newline
361    }
362
363    #[test]
364    fn multi_comment() {
365        let (status, pos, _, _) = parse_and_chomp("{- comment -}foo");
366        assert_eq!(status, SpaceStatus::Good);
367        assert_eq!(pos, 13);
368    }
369
370    #[test]
371    fn nested_multi_comment() {
372        let (status, pos, _, _) = parse_and_chomp("{- outer {- inner -} outer -}foo");
373        assert_eq!(status, SpaceStatus::Good);
374        assert_eq!(pos, 29);
375    }
376
377    #[test]
378    fn tab_error() {
379        let (status, _, _, _) = parse_and_chomp("  \t  ");
380        assert_eq!(status, SpaceStatus::HasTab);
381    }
382
383    #[test]
384    fn endless_multi_comment() {
385        let (status, _, _, _) = parse_and_chomp("{- never closed");
386        assert_eq!(status, SpaceStatus::EndlessMultiComment);
387    }
388
389    #[test]
390    fn doc_comment_not_consumed() {
391        // {-| should not be consumed - it's a doc comment for the caller
392        let (status, pos, _, _) = parse_and_chomp("{-| doc -}");
393        assert_eq!(status, SpaceStatus::Good);
394        assert_eq!(pos, 0); // Not consumed
395    }
396
397    #[test]
398    fn stops_at_content() {
399        let (status, pos, _, _) = parse_and_chomp("  foo");
400        assert_eq!(status, SpaceStatus::Good);
401        assert_eq!(pos, 2); // Stopped at 'f'
402    }
403
404    #[test]
405    fn doc_comment_simple() {
406        let bump = Bump::new();
407        let src = bump.alloc_str("{-| hello -}");
408        let mut parser = Parser::new(&bump, src.as_bytes());
409
410        let result = parser.doc_comment(|_, _| "expected", |_, _, _| "space error");
411        assert!(result.is_ok());
412        let comment = result.unwrap();
413        // Content is " hello " (between {-| and -})
414        assert_eq!(comment.0.data, b" hello ");
415        assert_eq!(comment.0.off_row, 1);
416        assert_eq!(comment.0.off_col, 4); // Column after {-|
417    }
418
419    #[test]
420    fn doc_comment_multiline() {
421        let bump = Bump::new();
422        let src = bump.alloc_str("{-| line one\nline two -}");
423        let mut parser = Parser::new(&bump, src.as_bytes());
424
425        let result = parser.doc_comment(|_, _| "expected", |_, _, _| "space error");
426        assert!(result.is_ok());
427        let comment = result.unwrap();
428        assert_eq!(comment.0.data, b" line one\nline two ");
429    }
430
431    #[test]
432    fn doc_comment_not_doc() {
433        let bump = Bump::new();
434        let src = bump.alloc_str("{- not a doc comment -}");
435        let mut parser = Parser::new(&bump, src.as_bytes());
436
437        let result = parser.doc_comment(|_, _| "expected", |_, _, _| "space error");
438        assert!(result.is_err());
439        assert_eq!(result.unwrap_err(), "expected");
440    }
441}