Skip to main content

nash_parse/
module.rs

1//! Module parsing for Nash.
2//!
3//! Ported from Elm's `Parse/Module.hs`.
4//!
5//! Parses full modules including:
6//! - Module header: `module Main exposing (main)`
7//! - Imports: `import List exposing (map)`
8//! - Declarations: values, types, aliases
9
10use nash_region::{Located, Region};
11use nash_source::{
12    Alias, Docs, Exposing, Impl, Import, Infix, Module, ModuleKind, Trait, Union, Value,
13};
14
15use crate::Parser;
16use crate::declaration::Decl;
17use crate::error;
18
19impl<'a> Parser<'a> {
20    /// Parse a module header.
21    ///
22    /// Mirrors Elm's `chompHeader` (simplified - no port/effect modules):
23    /// ```text
24    /// module_header = 'module' module_name 'exposing' exposing_list
25    /// ```
26    ///
27    /// Returns the module name and exports as a tuple.
28    pub fn module_header(
29        &mut self,
30    ) -> Result<(ModuleKind, &'a Located<&'a str>, &'a Located<Exposing<'a>>), error::Module<'a>>
31    {
32        let kind = self.one_of_with_fallback(
33            vec![Box::new(|parser: &mut Parser<'a>| {
34                let start = parser.get_position();
35                parser.keyword_validator(error::Module::Validator)?;
36                let end = parser.get_position();
37                parser.chomp_and_check_indent(error::Module::Space, error::Module::Validator)?;
38                Ok(ModuleKind::Validator(Region::new(start, end)))
39            })],
40            ModuleKind::Normal,
41        )?;
42        // Match 'module' keyword
43        self.keyword_module(error::Module::Problem)?;
44
45        self.chomp_and_check_indent(error::Module::Space, error::Module::Name)?;
46
47        // Parse module name (e.g., "Json.Decode")
48        let start = self.get_position();
49        let name = self.module_name(error::Module::Name)?;
50        let module_name = self.add_end(start, name);
51
52        // Consume whitespace
53        self.chomp(error::Module::Space)?;
54
55        // Must have 'exposing' keyword
56        self.keyword_exposing(|row, col| {
57            error::Module::Exposing(self.bump.alloc(error::Exposing::Start(row, col)), row, col)
58        })?;
59
60        self.chomp_and_check_indent(error::Module::Space, |row, col| {
61            error::Module::Exposing(
62                self.bump.alloc(error::Exposing::IndentValue(row, col)),
63                row,
64                col,
65            )
66        })?;
67
68        // Parse the exposing list, wrapping errors
69        let exposing_start = self.get_position();
70        let exposing = self.specialize(
71            |bump, err, row, col| error::Module::Exposing(bump.alloc(err), row, col),
72            |p| p.exposing(),
73        )?;
74        let exposing_located = self.add_end(exposing_start, exposing);
75
76        Ok((kind, module_name, exposing_located))
77    }
78
79    /// Parse zero or more import statements.
80    ///
81    /// Mirrors Elm's `chompImports`:
82    /// ```haskell
83    /// chompImports :: [Src.Import] -> Parser E.Module [Src.Import]
84    /// chompImports imports =
85    ///   oneOfWithFallback
86    ///     [ do  i <- chompImport
87    ///           chompImports (i:imports)
88    ///     ]
89    ///     (reverse imports)
90    /// ```
91    pub(crate) fn imports(&mut self) -> Result<&'a [&'a Import<'a>], error::Module<'a>> {
92        let mut imports = Vec::new();
93
94        loop {
95            // Save state in case import keyword doesn't match
96            let state = self.save_state();
97
98            match self.import() {
99                Ok(import) => {
100                    imports.push(import);
101                    // import() already ensures fresh line at the end
102                }
103                Err(error) => {
104                    // If we didn't consume input, we're done with imports
105                    if self.pos == state.pos {
106                        self.restore_state(state);
107                        break;
108                    }
109                    // Otherwise propagate the error
110                    return Err(error);
111                }
112            }
113        }
114
115        Ok(self.alloc_slice_copy(&imports))
116    }
117
118    /// Parse zero or more declarations.
119    ///
120    /// Mirrors Elm's `chompDecls`:
121    /// ```haskell
122    /// chompDecls :: [Decl.Decl] -> Parser E.Decl [Decl.Decl]
123    /// chompDecls decls =
124    ///   do  (decl, _) <- Decl.declaration
125    ///       oneOfWithFallback
126    ///         [ do  Space.checkFreshLine E.DeclStart
127    ///               chompDecls (decl:decls)
128    ///         ]
129    ///         (reverse (decl:decls))
130    /// ```
131    fn declarations(&mut self) -> Result<Vec<Decl<'a>>, error::Module<'a>> {
132        let mut decls = Vec::new();
133
134        loop {
135            // Save state in case no declaration starts
136            let state = self.save_state();
137
138            // Try to parse a declaration
139            match self.specialize(
140                |bump, err, row, col| error::Module::Declarations(bump.alloc(err), row, col),
141                |p| p.declaration(),
142            ) {
143                Ok((decl, _end)) => {
144                    decls.push(decl);
145
146                    // Chomp any trailing whitespace
147                    self.chomp(error::Module::Space)?;
148
149                    // Check for fresh line (another declaration might follow)
150                    if self.is_eof() {
151                        break;
152                    }
153
154                    // If not at fresh line, we're done
155                    if self.col != 1 {
156                        break;
157                    }
158                }
159                Err(error) => {
160                    // If we didn't consume input, we're done with declarations
161                    if self.pos == state.pos {
162                        self.restore_state(state);
163                        break;
164                    }
165                    // Otherwise propagate the error
166                    return Err(error);
167                }
168            }
169        }
170
171        Ok(decls)
172    }
173
174    /// Parse zero or more infix declarations.
175    ///
176    /// Infixes are parsed at module level (before regular declarations).
177    fn infixes(&mut self) -> Result<Vec<&'a Located<Infix<'a>>>, error::Module<'a>> {
178        let mut infixes = Vec::new();
179
180        loop {
181            let state = self.save_state();
182
183            match self.infix_decl() {
184                Ok(infix) => {
185                    infixes.push(infix);
186                    // infix_decl already ensures fresh line
187                }
188                Err(_) => {
189                    // If we didn't consume input, we're done
190                    if self.pos == state.pos {
191                        self.restore_state(state);
192                        break;
193                    }
194                    return Err(error::Module::Infix(self.row, self.col));
195                }
196            }
197        }
198
199        Ok(infixes)
200    }
201
202    /// Parse a complete module.
203    ///
204    /// Mirrors Elm's `chompModule`:
205    /// ```text
206    /// module = [ module_header ] { import } { infix } { declaration }
207    /// ```
208    pub fn module(&mut self) -> Result<Module<'a>, error::Module<'a>> {
209        // Consume initial whitespace
210        self.chomp(error::Module::Space)?;
211
212        let start_pos = self.get_position();
213
214        // Try to parse module header (optional)
215        let (kind, name, exports) =
216            if self.starts_keyword(b"module") || self.starts_keyword(b"validator") {
217                let (kind, name, exports) = self.module_header()?;
218                self.chomp(error::Module::Space)?;
219                self.check_fresh_line(error::Module::FreshLine)?;
220                (kind, Some(name), exports)
221            } else {
222                let default_exports = self.alloc(Located::at(Region::one(), Exposing::Open));
223                (ModuleKind::Normal, None, default_exports)
224            };
225
226        // Parse imports
227        let imports = self.imports()?;
228
229        // Parse infixes
230        let infix_vec = self.infixes()?;
231        let binops = self.alloc_slice_copy(&infix_vec);
232
233        // Parse declarations
234        let decls = self.declarations()?;
235
236        self.chomp(error::Module::Space)?;
237        let tests = self.one_of_with_fallback(
238            vec![Box::new(|parser: &mut Parser<'a>| {
239                parser.tests_block().map(Some)
240            })],
241            None,
242        )?;
243        self.chomp(error::Module::Space)?;
244        if !self.is_eof() {
245            return Err(error::Module::BadEnd(self.row, self.col));
246        }
247
248        // Categorize declarations into values, unions, aliases
249        let (values, unions, aliases, traits, impls) = self.categorize_decls(decls);
250
251        // Build docs (simplified: no module-level docs for now)
252        let docs = self.alloc(Docs::NoDocs(Region::new(start_pos, self.get_position())));
253
254        Ok(Module {
255            kind,
256            name,
257            exports,
258            docs,
259            imports,
260            values,
261            unions,
262            aliases,
263            traits,
264            impls,
265            tests,
266            binops,
267        })
268    }
269
270    fn starts_keyword(&self, keyword: &[u8]) -> bool {
271        let remaining = self.remaining();
272        remaining.starts_with(keyword)
273            && remaining
274                .get(keyword.len())
275                .is_none_or(|byte| !byte.is_ascii_alphanumeric() && *byte != b'_')
276    }
277
278    /// Categorize declarations into separate slices by type.
279    #[allow(clippy::type_complexity)]
280    fn categorize_decls(
281        &self,
282        decls: Vec<Decl<'a>>,
283    ) -> (
284        &'a [&'a Located<Value<'a>>],
285        &'a [&'a Located<Union<'a>>],
286        &'a [&'a Located<Alias<'a>>],
287        &'a [&'a Located<Trait<'a>>],
288        &'a [&'a Located<Impl<'a>>],
289    ) {
290        let mut values = Vec::new();
291        let mut unions = Vec::new();
292        let mut aliases = Vec::new();
293        let mut traits = Vec::new();
294        let mut impls = Vec::new();
295
296        for decl in decls {
297            match decl {
298                Decl::Value(_doc, value) => values.push(value),
299                Decl::Union(_doc, union) => unions.push(union),
300                Decl::Alias(_doc, alias) => aliases.push(alias),
301                Decl::Trait(trait_) => traits.push(trait_),
302                Decl::Impl(impl_) => impls.push(impl_),
303            }
304        }
305
306        (
307            self.alloc_slice_copy(&values),
308            self.alloc_slice_copy(&unions),
309            self.alloc_slice_copy(&aliases),
310            self.alloc_slice_copy(&traits),
311            self.alloc_slice_copy(&impls),
312        )
313    }
314}
315
316#[cfg(test)]
317mod tests {
318    use super::*;
319    use bumpalo::Bump;
320    use indoc::indoc;
321
322    macro_rules! assert_module_header_snapshot {
323        ($input:expr) => {{
324            let input = indoc!($input);
325            let bump = Bump::new();
326            let src = bump.alloc_str(input);
327            let mut parser = Parser::new(&bump, src);
328            let result = parser.module_header();
329            match result {
330                Ok((kind, name, exposing)) => {
331                    insta::with_settings!({
332                        description => format!("Code:\n\n{}", input),
333                        omit_expression => true,
334                    }, {
335                        insta::assert_debug_snapshot!((kind, name, exposing));
336                    });
337                }
338                Err(e) => {
339                    panic!("Expected successful parse, got error: {:?}", e);
340                }
341            }
342        }};
343    }
344
345    #[test]
346    fn module_header_simple_open() {
347        assert_module_header_snapshot!("module Foo exposing (..)");
348    }
349
350    #[test]
351    fn module_header_dotted() {
352        assert_module_header_snapshot!("module Foo.Bar exposing (baz)");
353    }
354
355    #[test]
356    fn module_header_mixed_exposing() {
357        assert_module_header_snapshot!("module Main exposing (main, Msg(..))");
358    }
359
360    #[test]
361    fn module_header_little_types() {
362        assert_module_header_snapshot!("module P exposing (type option(..), type step)");
363    }
364
365    #[test]
366    fn module_header_deeply_nested() {
367        assert_module_header_snapshot!("module Platform.Cmd.Extra exposing (batch, none)");
368    }
369
370    #[test]
371    fn validator_module_header() {
372        assert_module_header_snapshot!("validator module Vesting exposing (main)");
373    }
374
375    // =========================================================================
376    // Full module parsing tests
377    // =========================================================================
378
379    macro_rules! assert_module_snapshot {
380        ($input:expr) => {{
381            let input = indoc!($input);
382            let bump = Bump::new();
383            let src = bump.alloc_str(input);
384            let mut parser = Parser::new(&bump, src);
385            let result = parser.module();
386            match result {
387                Ok(module) => {
388                    insta::with_settings!({
389                        description => format!("Code:\n\n{}", input),
390                        omit_expression => true,
391                    }, {
392                        insta::assert_debug_snapshot!(module);
393                    });
394                }
395                Err(e) => {
396                    panic!("Expected successful parse, got error: {:?}", e);
397                }
398            }
399        }};
400    }
401
402    macro_rules! assert_module_error_snapshot {
403        ($input:expr) => {{
404            let input = indoc!($input);
405            let bump = Bump::new();
406            let src = bump.alloc_str(input);
407            let mut parser = nash_parse::Parser::new(&bump, src);
408            let error = parser.module().expect_err("expected module parse error");
409            insta::with_settings!({
410                description => format!("Code:\n\n{}", input),
411                omit_expression => true,
412                info => &"diagnostic",
413            }, {
414                insta::assert_snapshot!($crate::test_support::render_module_error(src, &error));
415            });
416        }};
417    }
418
419    #[test]
420    fn module_header_only() {
421        assert_module_snapshot!("module Main exposing (..)\n");
422    }
423
424    #[test]
425    fn module_with_imports() {
426        assert_module_snapshot!(
427            r#"
428            module Main exposing (..)
429
430            import List
431            import Maybe exposing (Maybe(..))
432        "#
433        );
434    }
435
436    #[test]
437    fn module_with_value() {
438        assert_module_snapshot!(
439            r#"
440            module Main exposing (..)
441
442            main = 42
443        "#
444        );
445    }
446
447    #[test]
448    fn module_with_type() {
449        assert_module_snapshot!(
450            r#"
451            module Main exposing (..)
452
453            type Maybe 'a
454                = Just 'a
455                | Nothing
456        "#
457        );
458    }
459
460    #[test]
461    fn module_with_union_then_value() {
462        // A definition at column 1 must end the union's variant list, not
463        // be swallowed as extra constructor arguments.
464        assert_module_snapshot!(
465            r#"
466            module Main exposing (..)
467
468            type Wrap 'a
469                = Wrap 'a
470
471            f w = w
472        "#
473        );
474    }
475
476    #[test]
477    fn module_with_alias() {
478        assert_module_snapshot!(
479            r#"
480            module Main exposing (..)
481
482            type alias Point = { x : Int, y : Int }
483        "#
484        );
485    }
486
487    #[test]
488    fn module_full() {
489        assert_module_snapshot!(
490            r#"
491            module Main exposing (main, Model, Msg(..))
492
493            import Html exposing (div)
494            import Platform.Cmd as Cmd
495
496            type alias Model = { count : Int }
497
498            type Msg
499                = Increment
500                | Decrement
501
502            main = 0
503        "#
504        );
505    }
506
507    #[test]
508    fn module_no_header() {
509        // Without header, defaults to name=None, exports=Open
510        assert_module_snapshot!("x = 1\n");
511    }
512
513    #[test]
514    fn module_with_infix() {
515        assert_module_snapshot!(
516            r#"
517            module Main exposing (..)
518
519            infix left 6 (|>) = apR
520
521            apR f x = f x
522        "#
523        );
524    }
525
526    #[test]
527    fn module_with_empty_trait_then_value() {
528        assert_module_snapshot!(
529            r#"
530            module Main exposing (..)
531
532            trait Marker 'a where
533
534            x = 1
535        "#
536        );
537    }
538    #[test]
539    fn later_constraint_does_not_imply_trait_superclass() {
540        assert_module_snapshot!(
541            r#"
542            module Main exposing (..)
543
544            trait Show 'a where
545
546            id : Eq 'a => 'a -> 'a
547            id x = x
548        "#
549        );
550    }
551
552    #[test]
553    fn module_with_empty_impl_then_value() {
554        assert_module_snapshot!(
555            r#"
556            module Main exposing (..)
557
558            impl Show unit where
559
560            x = 1
561        "#
562        );
563    }
564
565    #[test]
566    fn validator_module_full() {
567        assert_module_snapshot!(
568            r#"
569            validator module Vesting exposing (main)
570
571            import Cardano.Tx exposing (Tx, Output)
572
573            type Datum = Datum { owner : Bytes, deadline : Int }
574
575            type step 'a = Done 'a | Next int 'a
576
577            type alias acc = { total : int, seen : list Int }
578
579            main datum = assert True
580        "#
581        );
582    }
583
584    #[test]
585    fn validator_requires_module_keyword() {
586        assert_module_error_snapshot!("validator Vesting exposing (main)");
587    }
588
589    #[test]
590    fn validator_module_must_remain_indented() {
591        assert_module_error_snapshot!("validator\nmodule V exposing (..)");
592    }
593
594    #[test]
595    fn module_preserves_import_alias_error() {
596        assert_module_error_snapshot!("import Cardano.Tx as tx");
597    }
598
599    #[test]
600    fn module_preserves_type_alias_error() {
601        assert_module_error_snapshot!("type alias account");
602    }
603
604    #[test]
605    fn module_preserves_pattern_error() {
606        assert_module_error_snapshot!("f (x as) = x");
607    }
608
609    #[test]
610    fn module_preserves_expression_error() {
611        assert_module_error_snapshot!("value = if True then 42");
612    }
613
614    #[test]
615    fn module_preserves_annotation_name_error() {
616        assert_module_error_snapshot!("f : int\ng = 1");
617    }
618}