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(_) => {
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::Module::ImportStart(self.row, self.col));
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(_) => {
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::Module::Declarations(
167                        self.bump.alloc(error::Decl::Start(self.row, self.col)),
168                        self.row,
169                        self.col,
170                    ));
171                }
172            }
173        }
174
175        Ok(decls)
176    }
177
178    /// Parse zero or more infix declarations.
179    ///
180    /// Infixes are parsed at module level (before regular declarations).
181    fn infixes(&mut self) -> Result<Vec<&'a Located<Infix<'a>>>, error::Module<'a>> {
182        let mut infixes = Vec::new();
183
184        loop {
185            let state = self.save_state();
186
187            match self.infix_decl() {
188                Ok(infix) => {
189                    infixes.push(infix);
190                    // infix_decl already ensures fresh line
191                }
192                Err(_) => {
193                    // If we didn't consume input, we're done
194                    if self.pos == state.pos {
195                        self.restore_state(state);
196                        break;
197                    }
198                    return Err(error::Module::Infix(self.row, self.col));
199                }
200            }
201        }
202
203        Ok(infixes)
204    }
205
206    /// Parse a complete module.
207    ///
208    /// Mirrors Elm's `chompModule`:
209    /// ```text
210    /// module = [ module_header ] { import } { infix } { declaration }
211    /// ```
212    pub fn module(&mut self) -> Result<Module<'a>, error::Module<'a>> {
213        // Consume initial whitespace
214        self.chomp(error::Module::Space)?;
215
216        let start_pos = self.get_position();
217
218        // Try to parse module header (optional)
219        let (kind, name, exports) =
220            if self.starts_keyword(b"module") || self.starts_keyword(b"validator") {
221                let (kind, name, exports) = self.module_header()?;
222                self.chomp(error::Module::Space)?;
223                self.check_fresh_line(error::Module::FreshLine)?;
224                (kind, Some(name), exports)
225            } else {
226                let default_exports = self.alloc(Located::at(Region::one(), Exposing::Open));
227                (ModuleKind::Normal, None, default_exports)
228            };
229
230        // Parse imports
231        let imports = self.imports()?;
232
233        // Parse infixes
234        let infix_vec = self.infixes()?;
235        let binops = self.alloc_slice_copy(&infix_vec);
236
237        // Parse declarations
238        let decls = self.declarations()?;
239
240        self.chomp(error::Module::Space)?;
241        let tests = self.one_of_with_fallback(
242            vec![Box::new(|parser: &mut Parser<'a>| {
243                parser.tests_block().map(Some)
244            })],
245            None,
246        )?;
247        self.chomp(error::Module::Space)?;
248        if !self.is_eof() {
249            return Err(error::Module::BadEnd(self.row, self.col));
250        }
251
252        // Categorize declarations into values, unions, aliases
253        let (values, unions, aliases, traits, impls) = self.categorize_decls(decls);
254
255        // Build docs (simplified: no module-level docs for now)
256        let docs = self.alloc(Docs::NoDocs(Region::new(start_pos, self.get_position())));
257
258        Ok(Module {
259            kind,
260            name,
261            exports,
262            docs,
263            imports,
264            values,
265            unions,
266            aliases,
267            traits,
268            impls,
269            tests,
270            binops,
271        })
272    }
273
274    fn starts_keyword(&self, keyword: &[u8]) -> bool {
275        let remaining = self.remaining();
276        remaining.starts_with(keyword)
277            && remaining
278                .get(keyword.len())
279                .is_none_or(|byte| !byte.is_ascii_alphanumeric() && *byte != b'_')
280    }
281
282    /// Categorize declarations into separate slices by type.
283    #[allow(clippy::type_complexity)]
284    fn categorize_decls(
285        &self,
286        decls: Vec<Decl<'a>>,
287    ) -> (
288        &'a [&'a Located<Value<'a>>],
289        &'a [&'a Located<Union<'a>>],
290        &'a [&'a Located<Alias<'a>>],
291        &'a [&'a Located<Trait<'a>>],
292        &'a [&'a Located<Impl<'a>>],
293    ) {
294        let mut values = Vec::new();
295        let mut unions = Vec::new();
296        let mut aliases = Vec::new();
297        let mut traits = Vec::new();
298        let mut impls = Vec::new();
299
300        for decl in decls {
301            match decl {
302                Decl::Value(_doc, value) => values.push(value),
303                Decl::Union(_doc, union) => unions.push(union),
304                Decl::Alias(_doc, alias) => aliases.push(alias),
305                Decl::Trait(trait_) => traits.push(trait_),
306                Decl::Impl(impl_) => impls.push(impl_),
307            }
308        }
309
310        (
311            self.alloc_slice_copy(&values),
312            self.alloc_slice_copy(&unions),
313            self.alloc_slice_copy(&aliases),
314            self.alloc_slice_copy(&traits),
315            self.alloc_slice_copy(&impls),
316        )
317    }
318}
319
320#[cfg(test)]
321mod tests {
322    use super::*;
323    use bumpalo::Bump;
324    use indoc::indoc;
325
326    macro_rules! assert_module_header_snapshot {
327        ($input:expr) => {{
328            let input = indoc!($input);
329            let bump = Bump::new();
330            let src = bump.alloc_str(input);
331            let mut parser = Parser::new(&bump, src.as_bytes());
332            let result = parser.module_header();
333            match result {
334                Ok((kind, name, exposing)) => {
335                    insta::with_settings!({
336                        description => format!("Code:\n\n{}", input),
337                        omit_expression => true,
338                    }, {
339                        insta::assert_debug_snapshot!((kind, name, exposing));
340                    });
341                }
342                Err(e) => {
343                    panic!("Expected successful parse, got error: {:?}", e);
344                }
345            }
346        }};
347    }
348
349    #[test]
350    fn module_header_simple_open() {
351        assert_module_header_snapshot!("module Foo exposing (..)");
352    }
353
354    #[test]
355    fn module_header_dotted() {
356        assert_module_header_snapshot!("module Foo.Bar exposing (baz)");
357    }
358
359    #[test]
360    fn module_header_mixed_exposing() {
361        assert_module_header_snapshot!("module Main exposing (main, Msg(..))");
362    }
363
364    #[test]
365    fn module_header_little_types() {
366        assert_module_header_snapshot!("module P exposing (type option(..), type step)");
367    }
368
369    #[test]
370    fn module_header_deeply_nested() {
371        assert_module_header_snapshot!("module Platform.Cmd.Extra exposing (batch, none)");
372    }
373
374    #[test]
375    fn validator_module_header() {
376        assert_module_header_snapshot!("validator module Vesting exposing (main)");
377    }
378
379    // =========================================================================
380    // Full module parsing tests
381    // =========================================================================
382
383    macro_rules! assert_module_snapshot {
384        ($input:expr) => {{
385            let input = indoc!($input);
386            let bump = Bump::new();
387            let src = bump.alloc_str(input);
388            let mut parser = Parser::new(&bump, src.as_bytes());
389            let result = parser.module();
390            match result {
391                Ok(module) => {
392                    insta::with_settings!({
393                        description => format!("Code:\n\n{}", input),
394                        omit_expression => true,
395                    }, {
396                        insta::assert_debug_snapshot!(module);
397                    });
398                }
399                Err(e) => {
400                    panic!("Expected successful parse, got error: {:?}", e);
401                }
402            }
403        }};
404    }
405
406    macro_rules! assert_module_error_snapshot {
407        ($input:expr) => {{
408            let input = indoc!($input);
409            let bump = Bump::new();
410            let src = bump.alloc_str(input);
411            let mut parser = Parser::new(&bump, src.as_bytes());
412            let error = parser.module().expect_err("expected module parse error");
413            insta::with_settings!({
414                description => format!("Code:\n\n{}", input),
415                omit_expression => true,
416            }, {
417                insta::assert_debug_snapshot!(error);
418            });
419        }};
420    }
421
422    #[test]
423    fn module_header_only() {
424        assert_module_snapshot!("module Main exposing (..)\n");
425    }
426
427    #[test]
428    fn module_with_imports() {
429        assert_module_snapshot!(
430            r#"
431            module Main exposing (..)
432
433            import List
434            import Maybe exposing (Maybe(..))
435        "#
436        );
437    }
438
439    #[test]
440    fn module_with_value() {
441        assert_module_snapshot!(
442            r#"
443            module Main exposing (..)
444
445            main = 42
446        "#
447        );
448    }
449
450    #[test]
451    fn module_with_type() {
452        assert_module_snapshot!(
453            r#"
454            module Main exposing (..)
455
456            type Maybe 'a
457                = Just 'a
458                | Nothing
459        "#
460        );
461    }
462
463    #[test]
464    fn module_with_union_then_value() {
465        // A definition at column 1 must end the union's variant list, not
466        // be swallowed as extra constructor arguments.
467        assert_module_snapshot!(
468            r#"
469            module Main exposing (..)
470
471            type Wrap 'a
472                = Wrap 'a
473
474            f w = w
475        "#
476        );
477    }
478
479    #[test]
480    fn module_with_alias() {
481        assert_module_snapshot!(
482            r#"
483            module Main exposing (..)
484
485            type alias Point = { x : Int, y : Int }
486        "#
487        );
488    }
489
490    #[test]
491    fn module_full() {
492        assert_module_snapshot!(
493            r#"
494            module Main exposing (main, Model, Msg(..))
495
496            import Html exposing (div)
497            import Platform.Cmd as Cmd
498
499            type alias Model = { count : Int }
500
501            type Msg
502                = Increment
503                | Decrement
504
505            main = 0
506        "#
507        );
508    }
509
510    #[test]
511    fn module_no_header() {
512        // Without header, defaults to name=None, exports=Open
513        assert_module_snapshot!("x = 1\n");
514    }
515
516    #[test]
517    fn module_with_infix() {
518        assert_module_snapshot!(
519            r#"
520            module Main exposing (..)
521
522            infix left 6 (|>) = apR
523
524            apR f x = f x
525        "#
526        );
527    }
528
529    #[test]
530    fn module_with_empty_trait_then_value() {
531        assert_module_snapshot!(
532            r#"
533            module Main exposing (..)
534
535            trait Marker 'a where
536
537            x = 1
538        "#
539        );
540    }
541    #[test]
542    fn later_constraint_does_not_imply_trait_superclass() {
543        assert_module_snapshot!(
544            r#"
545            module Main exposing (..)
546
547            trait Show 'a where
548
549            id : Eq 'a => 'a -> 'a
550            id x = x
551        "#
552        );
553    }
554
555    #[test]
556    fn module_with_empty_impl_then_value() {
557        assert_module_snapshot!(
558            r#"
559            module Main exposing (..)
560
561            impl Show unit where
562
563            x = 1
564        "#
565        );
566    }
567
568    #[test]
569    fn validator_module_full() {
570        assert_module_snapshot!(
571            r#"
572            validator module Vesting exposing (main)
573
574            import Cardano.Tx exposing (Tx, Output)
575
576            type Datum = Datum { owner : Bytes, deadline : Int }
577
578            type step 'a = Done 'a | Next int 'a
579
580            type alias acc = { total : int, seen : list Int }
581
582            main datum = assert True
583        "#
584        );
585    }
586
587    #[test]
588    fn validator_requires_module_keyword() {
589        assert_module_error_snapshot!("validator Vesting exposing (main)");
590    }
591
592    #[test]
593    fn validator_module_must_remain_indented() {
594        assert_module_error_snapshot!("validator\nmodule V exposing (..)");
595    }
596}