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.as_bytes());
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.as_bytes());
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 = Parser::new(&bump, src.as_bytes());
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            }, {
413                insta::assert_debug_snapshot!(error);
414            });
415        }};
416    }
417
418    #[test]
419    fn module_header_only() {
420        assert_module_snapshot!("module Main exposing (..)\n");
421    }
422
423    #[test]
424    fn module_with_imports() {
425        assert_module_snapshot!(
426            r#"
427            module Main exposing (..)
428
429            import List
430            import Maybe exposing (Maybe(..))
431        "#
432        );
433    }
434
435    #[test]
436    fn module_with_value() {
437        assert_module_snapshot!(
438            r#"
439            module Main exposing (..)
440
441            main = 42
442        "#
443        );
444    }
445
446    #[test]
447    fn module_with_type() {
448        assert_module_snapshot!(
449            r#"
450            module Main exposing (..)
451
452            type Maybe 'a
453                = Just 'a
454                | Nothing
455        "#
456        );
457    }
458
459    #[test]
460    fn module_with_union_then_value() {
461        // A definition at column 1 must end the union's variant list, not
462        // be swallowed as extra constructor arguments.
463        assert_module_snapshot!(
464            r#"
465            module Main exposing (..)
466
467            type Wrap 'a
468                = Wrap 'a
469
470            f w = w
471        "#
472        );
473    }
474
475    #[test]
476    fn module_with_alias() {
477        assert_module_snapshot!(
478            r#"
479            module Main exposing (..)
480
481            type alias Point = { x : Int, y : Int }
482        "#
483        );
484    }
485
486    #[test]
487    fn module_full() {
488        assert_module_snapshot!(
489            r#"
490            module Main exposing (main, Model, Msg(..))
491
492            import Html exposing (div)
493            import Platform.Cmd as Cmd
494
495            type alias Model = { count : Int }
496
497            type Msg
498                = Increment
499                | Decrement
500
501            main = 0
502        "#
503        );
504    }
505
506    #[test]
507    fn module_no_header() {
508        // Without header, defaults to name=None, exports=Open
509        assert_module_snapshot!("x = 1\n");
510    }
511
512    #[test]
513    fn module_with_infix() {
514        assert_module_snapshot!(
515            r#"
516            module Main exposing (..)
517
518            infix left 6 (|>) = apR
519
520            apR f x = f x
521        "#
522        );
523    }
524
525    #[test]
526    fn module_with_empty_trait_then_value() {
527        assert_module_snapshot!(
528            r#"
529            module Main exposing (..)
530
531            trait Marker 'a where
532
533            x = 1
534        "#
535        );
536    }
537    #[test]
538    fn later_constraint_does_not_imply_trait_superclass() {
539        assert_module_snapshot!(
540            r#"
541            module Main exposing (..)
542
543            trait Show 'a where
544
545            id : Eq 'a => 'a -> 'a
546            id x = x
547        "#
548        );
549    }
550
551    #[test]
552    fn module_with_empty_impl_then_value() {
553        assert_module_snapshot!(
554            r#"
555            module Main exposing (..)
556
557            impl Show unit where
558
559            x = 1
560        "#
561        );
562    }
563
564    #[test]
565    fn validator_module_full() {
566        assert_module_snapshot!(
567            r#"
568            validator module Vesting exposing (main)
569
570            import Cardano.Tx exposing (Tx, Output)
571
572            type Datum = Datum { owner : Bytes, deadline : Int }
573
574            type step 'a = Done 'a | Next int 'a
575
576            type alias acc = { total : int, seen : list Int }
577
578            main datum = assert True
579        "#
580        );
581    }
582
583    #[test]
584    fn validator_requires_module_keyword() {
585        assert_module_error_snapshot!("validator Vesting exposing (main)");
586    }
587
588    #[test]
589    fn validator_module_must_remain_indented() {
590        assert_module_error_snapshot!("validator\nmodule V exposing (..)");
591    }
592
593    #[test]
594    fn module_preserves_import_alias_error() {
595        assert_module_error_snapshot!("import Cardano.Tx as tx");
596    }
597
598    #[test]
599    fn module_preserves_type_alias_error() {
600        assert_module_error_snapshot!("type alias account");
601    }
602
603    #[test]
604    fn module_preserves_pattern_error() {
605        assert_module_error_snapshot!("f (x as) = x");
606    }
607
608    #[test]
609    fn module_preserves_expression_error() {
610        assert_module_error_snapshot!("value = if True then 42");
611    }
612
613    #[test]
614    fn module_preserves_annotation_name_error() {
615        assert_module_error_snapshot!("f : int\ng = 1");
616    }
617}