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