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, overview) =
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                let overview = if self.remaining().starts_with(b"{-|") {
221                    let doc = self.doc_comment(error::Module::FreshLine, error::Module::Space)?;
222                    self.chomp(error::Module::Space)?;
223                    self.check_fresh_line(error::Module::FreshLine)?;
224                    Some(doc)
225                } else {
226                    None
227                };
228                (kind, Some(name), exports, overview)
229            } else {
230                let default_exports = self.alloc(Located::at(Region::one(), Exposing::Open));
231                (ModuleKind::Normal, None, default_exports, None)
232            };
233
234        // Parse imports
235        let imports = self.imports()?;
236
237        // Parse infixes
238        let infix_vec = self.infixes()?;
239        let binops = self.alloc_slice_copy(&infix_vec);
240
241        // Parse declarations
242        let decls = self.declarations()?;
243
244        self.chomp(error::Module::Space)?;
245        let tests = self.one_of_with_fallback(
246            vec![Box::new(|parser: &mut Parser<'a>| {
247                parser.tests_block().map(Some)
248            })],
249            None,
250        )?;
251        self.chomp(error::Module::Space)?;
252        if !self.is_eof() {
253            return Err(error::Module::BadEnd(self.row, self.col));
254        }
255
256        // Categorize declarations into values, unions, aliases
257        let (values, unions, aliases, traits, impls) = self.categorize_decls(decls);
258
259        let docs = self.alloc(match overview {
260            Some(overview) => {
261                let mut comments = Vec::new();
262                for (name, doc) in values
263                    .iter()
264                    .map(|v| (v.value.name, v.value.docs))
265                    .chain(unions.iter().map(|v| (v.value.name, v.value.docs)))
266                    .chain(aliases.iter().map(|v| (v.value.name, v.value.docs)))
267                    .chain(traits.iter().map(|v| (v.value.name, v.value.docs)))
268                {
269                    if let Some(doc) = doc {
270                        comments.push(self.alloc((name.value, doc)));
271                    }
272                }
273                comments.sort_by_key(|(_, doc)| (doc.region.start.line, doc.region.start.column));
274                Docs::YesDocs {
275                    overview,
276                    comments: self.alloc_slice_copy(&comments),
277                }
278            }
279            None => Docs::NoDocs(Region::new(start_pos, self.get_position())),
280        });
281        let comments = self.alloc_slice_copy(&self.comments);
282
283        Ok(Module {
284            kind,
285            name,
286            exports,
287            docs,
288            comments,
289            imports,
290            values,
291            unions,
292            aliases,
293            traits,
294            impls,
295            tests,
296            binops,
297        })
298    }
299
300    fn starts_keyword(&self, keyword: &[u8]) -> bool {
301        let remaining = self.remaining();
302        remaining.starts_with(keyword)
303            && remaining
304                .get(keyword.len())
305                .is_none_or(|byte| !byte.is_ascii_alphanumeric() && *byte != b'_')
306    }
307
308    /// Categorize declarations into separate slices by type.
309    #[allow(clippy::type_complexity)]
310    fn categorize_decls(
311        &self,
312        decls: Vec<Decl<'a>>,
313    ) -> (
314        &'a [&'a Located<Value<'a>>],
315        &'a [&'a Located<Union<'a>>],
316        &'a [&'a Located<Alias<'a>>],
317        &'a [&'a Located<Trait<'a>>],
318        &'a [&'a Located<Impl<'a>>],
319    ) {
320        let mut values = Vec::new();
321        let mut unions = Vec::new();
322        let mut aliases = Vec::new();
323        let mut traits = Vec::new();
324        let mut impls = Vec::new();
325
326        for decl in decls {
327            match decl {
328                Decl::Value(value) => values.push(value),
329                Decl::Union(union) => unions.push(union),
330                Decl::Alias(alias) => aliases.push(alias),
331                Decl::Trait(trait_) => traits.push(trait_),
332                Decl::Impl(impl_) => impls.push(impl_),
333            }
334        }
335
336        (
337            self.alloc_slice_copy(&values),
338            self.alloc_slice_copy(&unions),
339            self.alloc_slice_copy(&aliases),
340            self.alloc_slice_copy(&traits),
341            self.alloc_slice_copy(&impls),
342        )
343    }
344}
345
346#[cfg(test)]
347mod tests {
348    use super::*;
349    use bumpalo::Bump;
350    use indoc::indoc;
351
352    macro_rules! assert_module_header_snapshot {
353        ($input:expr) => {{
354            let input = indoc!($input);
355            let bump = Bump::new();
356            let src = bump.alloc_str(input);
357            let mut parser = Parser::new(&bump, src);
358            let result = parser.module_header();
359            match result {
360                Ok((kind, name, exposing)) => {
361                    insta::with_settings!({
362                        description => format!("Code:\n\n{}", input),
363                        omit_expression => true,
364                    }, {
365                        insta::assert_debug_snapshot!((kind, name, exposing));
366                    });
367                }
368                Err(e) => {
369                    panic!("Expected successful parse, got error: {:?}", e);
370                }
371            }
372        }};
373    }
374
375    #[test]
376    fn module_header_simple_open() {
377        assert_module_header_snapshot!("module Foo exposing (..)");
378    }
379
380    #[test]
381    fn module_header_dotted() {
382        assert_module_header_snapshot!("module Foo.Bar exposing (baz)");
383    }
384
385    #[test]
386    fn module_header_mixed_exposing() {
387        assert_module_header_snapshot!("module Main exposing (main, Msg(..))");
388    }
389
390    #[test]
391    fn module_header_little_types() {
392        assert_module_header_snapshot!("module P exposing (type option(..), type step)");
393    }
394
395    #[test]
396    fn module_header_deeply_nested() {
397        assert_module_header_snapshot!("module Platform.Cmd.Extra exposing (batch, none)");
398    }
399
400    #[test]
401    fn validator_module_header() {
402        assert_module_header_snapshot!("validator module Vesting exposing (main)");
403    }
404
405    // =========================================================================
406    // Full module parsing tests
407    // =========================================================================
408
409    macro_rules! assert_module_snapshot {
410        ($input:expr) => {{
411            let input = indoc!($input);
412            let bump = Bump::new();
413            let src = bump.alloc_str(input);
414            let mut parser = Parser::new(&bump, src);
415            let result = parser.module();
416            match result {
417                Ok(module) => {
418                    insta::with_settings!({
419                        description => format!("Code:\n\n{}", input),
420                        omit_expression => true,
421                    }, {
422                        insta::assert_debug_snapshot!(module);
423                    });
424                }
425                Err(e) => {
426                    panic!("Expected successful parse, got error: {:?}", e);
427                }
428            }
429        }};
430    }
431
432    macro_rules! assert_module_error_snapshot {
433        ($input:expr) => {{
434            let input = indoc!($input);
435            let bump = Bump::new();
436            let src = bump.alloc_str(input);
437            let mut parser = nash_parse::Parser::new(&bump, src);
438            let error = parser.module().expect_err("expected module parse error");
439            insta::with_settings!({
440                description => format!("Code:\n\n{}", input),
441                omit_expression => true,
442                info => &"diagnostic",
443            }, {
444                insta::assert_snapshot!($crate::test_support::render_module_error(src, &error));
445            });
446        }};
447    }
448
449    #[test]
450    fn module_header_only() {
451        assert_module_snapshot!("module Main exposing (..)\n");
452    }
453
454    #[test]
455    fn module_with_imports() {
456        assert_module_snapshot!(
457            r#"
458            module Main exposing (..)
459
460            import List
461            import Maybe exposing (Maybe(..))
462        "#
463        );
464    }
465
466    #[test]
467    fn module_with_value() {
468        assert_module_snapshot!(
469            r#"
470            module Main exposing (..)
471
472            main = 42
473        "#
474        );
475    }
476
477    #[test]
478    fn module_with_type() {
479        assert_module_snapshot!(
480            r#"
481            module Main exposing (..)
482
483            type Maybe 'a
484                = Just 'a
485                | Nothing
486        "#
487        );
488    }
489
490    #[test]
491    fn module_with_union_then_value() {
492        // A definition at column 1 must end the union's variant list, not
493        // be swallowed as extra constructor arguments.
494        assert_module_snapshot!(
495            r#"
496            module Main exposing (..)
497
498            type Wrap 'a
499                = Wrap 'a
500
501            f w = w
502        "#
503        );
504    }
505
506    #[test]
507    fn module_with_alias() {
508        assert_module_snapshot!(
509            r#"
510            module Main exposing (..)
511
512            type alias Point = { x : Int, y : Int }
513        "#
514        );
515    }
516
517    #[test]
518    fn module_full() {
519        assert_module_snapshot!(
520            r#"
521            module Main exposing (main, Model, Msg(..))
522
523            import Html exposing (div)
524            import Platform.Cmd as Cmd
525
526            type alias Model = { count : Int }
527
528            type Msg
529                = Increment
530                | Decrement
531
532            main = 0
533        "#
534        );
535    }
536
537    #[test]
538    fn module_no_header() {
539        // Without header, defaults to name=None, exports=Open
540        assert_module_snapshot!("x = 1\n");
541    }
542
543    #[test]
544    fn module_with_infix() {
545        assert_module_snapshot!(
546            r#"
547            module Main exposing (..)
548
549            infix left 6 (|>) = apR
550
551            apR f x = f x
552        "#
553        );
554    }
555
556    #[test]
557    fn module_with_empty_trait_then_value() {
558        assert_module_snapshot!(
559            r#"
560            module Main exposing (..)
561
562            trait Marker 'a where
563
564            x = 1
565        "#
566        );
567    }
568    #[test]
569    fn later_constraint_does_not_imply_trait_superclass() {
570        assert_module_snapshot!(
571            r#"
572            module Main exposing (..)
573
574            trait Show 'a where
575
576            id : Eq 'a => 'a -> 'a
577            id x = x
578        "#
579        );
580    }
581
582    #[test]
583    fn module_with_empty_impl_then_value() {
584        assert_module_snapshot!(
585            r#"
586            module Main exposing (..)
587
588            impl Show unit where
589
590            x = 1
591        "#
592        );
593    }
594
595    #[test]
596    fn validator_module_full() {
597        assert_module_snapshot!(
598            r#"
599            validator module Vesting exposing (main)
600
601            import Cardano.Tx exposing (Tx, Output)
602
603            type Datum = Datum { owner : Bytes, deadline : Int }
604
605            type step 'a = Done 'a | Next int 'a
606
607            type alias acc = { total : int, seen : list Int }
608
609            main datum = assert True
610        "#
611        );
612    }
613
614    #[test]
615    fn validator_requires_module_keyword() {
616        assert_module_error_snapshot!("validator Vesting exposing (main)");
617    }
618
619    #[test]
620    fn validator_module_must_remain_indented() {
621        assert_module_error_snapshot!("validator\nmodule V exposing (..)");
622    }
623
624    #[test]
625    fn module_preserves_import_alias_error() {
626        assert_module_error_snapshot!("import Cardano.Tx as tx");
627    }
628
629    #[test]
630    fn module_preserves_type_alias_error() {
631        assert_module_error_snapshot!("type alias account");
632    }
633
634    #[test]
635    fn module_preserves_pattern_error() {
636        assert_module_error_snapshot!("f (x as) = x");
637    }
638
639    #[test]
640    fn module_preserves_expression_error() {
641        assert_module_error_snapshot!("value = if True then 42");
642    }
643
644    #[test]
645    fn module_preserves_annotation_name_error() {
646        assert_module_error_snapshot!("f : int\ng = 1");
647    }
648    #[test]
649    fn comments_are_collected() {
650        assert_module_snapshot!(
651            r#"
652            -- leading
653            {- outer {- nested -} block -}
654            x = {- before value -} 1 -- trailing
655            -- eof
656        "#
657        );
658    }
659
660    #[test]
661    fn comments_preserve_unicode_and_crlf() {
662        assert_module_snapshot!("-- café\r\nx = 1 -- 終");
663    }
664
665    #[test]
666    fn doc_comment_attaches_to_value() {
667        assert_module_snapshot!("{-| value docs -}\nx = 1");
668    }
669
670    #[test]
671    fn module_doc_comment() {
672        assert_module_snapshot!(
673            r#"
674            module Main exposing (..)
675            -- before overview
676            {-| Overview with {- nested -} content. -}
677            import A -- import note
678
679            {-| Value docs. -}
680            @inline
681            x : int
682            x = 1
683        "#
684        );
685    }
686
687    #[test]
688    fn declaration_docs_survive_categorization() {
689        assert_module_snapshot!(
690            r#"
691            module Documented exposing (..)
692            {-| Overview. -}
693
694            {-| A union. -}
695            type Box = Box int
696
697            {-| An alias. -}
698            type alias Count = int
699
700            {-| A trait. -}
701            trait Measure 'a where
702                measure : 'a -> int
703
704            {-| An implementation. -}
705            impl Measure int where
706                measure x = x
707        "#
708        );
709    }
710
711    #[test]
712    fn backtracking_does_not_duplicate_comments() {
713        assert_module_snapshot!(
714            r#"
715            section = (1 + {- section -})
716            action = do
717                f {- speculative pattern -} x
718                pure ()
719        "#
720        );
721    }
722
723    #[test]
724    fn comments_in_tests_and_strings() {
725        assert_module_snapshot!(
726            r#"
727            text = "-- not a comment {- neither -}"
728            tests
729                -- test note
730                test "works" = do
731                    assert {- assertion note -} True
732        "#
733        );
734    }
735}