Skip to main content

nash_parse/declaration/
mod.rs

1//! Declaration parsing for Nash.
2//!
3//! Ported from Elm's `Parse/Declaration.hs`.
4//! Handles value definitions, type annotations, type aliases, custom types, and infix declarations.
5
6mod attribute;
7mod impl_;
8mod infix;
9mod trait_;
10mod type_alias;
11mod union;
12mod value;
13
14use nash_region::{Located, Position};
15use nash_source::{Alias, Comment, Impl, Trait, Union, Value};
16
17use crate::Parser;
18use crate::error::{self, Decl as DeclErr};
19
20/// A parsed declaration with optional doc comment.
21#[derive(Debug)]
22pub enum Decl<'a> {
23    Value(&'a Located<Value<'a>>),
24    Union(&'a Located<Union<'a>>),
25    Alias(&'a Located<Alias<'a>>),
26    Trait(&'a Located<Trait<'a>>),
27    Impl(&'a Located<Impl<'a>>),
28}
29
30impl<'a> Parser<'a> {
31    /// Parse a single declaration.
32    ///
33    /// Mirrors Elm's `declaration`:
34    /// ```haskell
35    /// declaration :: Space.Parser E.Decl Decl
36    /// declaration =
37    ///   do  maybeDocs <- chompDocComment
38    ///       start <- getPosition
39    ///       oneOf E.DeclStart
40    ///         [ typeDecl maybeDocs start
41    ///         , portDecl maybeDocs  -- skipped in Nash
42    ///         , valueDecl maybeDocs start
43    ///         ]
44    /// ```
45    pub fn declaration(&mut self) -> Result<(Decl<'a>, Position), error::Decl<'a>> {
46        let maybe_docs = self.chomp_doc_comment()?;
47        let attributes = self.chomp_attributes()?;
48
49        let start = self.get_position();
50
51        self.one_of(
52            DeclErr::Start,
53            vec![
54                // type alias or type (union)
55                Box::new(|p: &mut Parser<'a>| p.type_decl(maybe_docs, attributes, start)),
56                Box::new(|p: &mut Parser<'a>| p.trait_decl(maybe_docs, attributes, start)),
57                Box::new(|p: &mut Parser<'a>| p.impl_decl(maybe_docs, attributes, start)),
58                // value definition
59                Box::new(|p| p.value_decl(maybe_docs, attributes, start)),
60            ],
61        )
62    }
63
64    /// Parse an optional doc comment `{-| ... -}`.
65    ///
66    /// Mirrors Elm's `chompDocComment`:
67    /// ```haskell
68    /// chompDocComment =
69    ///   oneOfWithFallback
70    ///     [ do  docComment <- Space.docComment E.DeclStart E.DeclSpace
71    ///           Space.chomp E.DeclSpace
72    ///           Space.checkFreshLine E.DeclFreshLineAfterDocComment
73    ///           return (Just docComment)
74    ///     ]
75    ///     Nothing
76    /// ```
77    fn chomp_doc_comment(&mut self) -> Result<Option<&'a Comment<'a>>, error::Decl<'a>> {
78        self.one_of_with_fallback(
79            vec![Box::new(|p: &mut Parser<'a>| {
80                let doc = p.doc_comment(DeclErr::Start, |space, row, col| {
81                    DeclErr::Space(space, row, col)
82                })?;
83                p.chomp(DeclErr::Space)?;
84                p.check_fresh_line(DeclErr::FreshLineAfterDocComment)?;
85                Ok(Some(doc))
86            })],
87            None,
88        )
89    }
90
91    /// Parse a type declaration (alias or union).
92    ///
93    /// Mirrors Elm's `typeDecl`:
94    /// ```haskell
95    /// typeDecl maybeDocs start =
96    ///   inContext E.DeclType (Keyword.type_ E.DeclStart) $
97    ///     do  Space.chompAndCheckIndent E.DT_Space E.DT_IndentName
98    ///         oneOf E.DT_Name
99    ///           [ inContext E.DT_Alias (Keyword.alias_ E.DT_Name) $ ...
100    ///           , specialize E.DT_Union $ ...
101    ///           ]
102    /// ```
103    fn type_decl(
104        &mut self,
105        maybe_docs: Option<&'a Comment<'a>>,
106        attributes: &'a [&'a nash_source::Attribute<'a>],
107        start: Position,
108    ) -> Result<(Decl<'a>, Position), error::Decl<'a>> {
109        self.in_context(
110            |bump, e, row, col| error::Decl::Type(bump.alloc(e), row, col),
111            |p| p.keyword_type(error::Decl::Start),
112            |p| {
113                p.chomp_and_check_indent(error::DeclType::Space, error::DeclType::IndentName)?;
114
115                p.one_of(
116                    error::DeclType::Name,
117                    vec![
118                        // type alias
119                        Box::new(|p: &mut Parser<'a>| {
120                            p.in_context(
121                                |bump, e, row, col| error::DeclType::Alias(bump.alloc(e), row, col),
122                                |p| p.keyword_alias(error::DeclType::Name),
123                                |p| {
124                                    let (alias, end) =
125                                        p.type_alias_body(start, attributes, maybe_docs)?;
126                                    Ok((Decl::Alias(alias), end))
127                                },
128                            )
129                        }),
130                        // type union (custom type)
131                        Box::new(|p| {
132                            p.specialize(
133                                |bump, e, row, col| error::DeclType::Union(bump.alloc(e), row, col),
134                                |p| {
135                                    let (union, end) =
136                                        p.union_body(start, attributes, maybe_docs)?;
137                                    Ok((Decl::Union(union), end))
138                                },
139                            )
140                        }),
141                    ],
142                )
143            },
144        )
145    }
146}
147
148/// Macro for testing successful declaration parsing.
149#[cfg(test)]
150macro_rules! assert_decl_snapshot {
151    ($src:expr) => {{
152        let bump = bumpalo::Bump::new();
153        let src = indoc::indoc!($src);
154        let src_in_arena = bump.alloc_str(src);
155        let mut parser = crate::Parser::new(&bump, src_in_arena);
156        match parser.declaration() {
157            Ok((decl, _end)) => {
158                parser.chomp(|_, _, _| ()).expect("expected trailing space");
159                assert!(parser.is_eof(), "declaration parser left trailing input");
160                insta::with_settings!({
161                    description => src,
162                    omit_expression => true,
163                }, {
164                    insta::assert_debug_snapshot!(decl);
165                });
166            }
167            Err(e) => panic!("Expected Ok, got Err: {:?}\n\nSource:\n{}", e, src),
168        }
169    }};
170}
171
172#[cfg(test)]
173macro_rules! assert_decl_error_snapshot {
174    ($src:expr) => {{
175        let bump = bumpalo::Bump::new();
176        let src = indoc::indoc!($src);
177        let src_in_arena = bump.alloc_str(src);
178        let mut parser = nash_parse::Parser::new(&bump, src_in_arena);
179        let error = parser.declaration().expect_err("expected declaration parse error");
180        insta::with_settings!({
181            description => src,
182            omit_expression => true,
183                info => &"diagnostic",
184        }, {
185            insta::assert_snapshot!($crate::test_support::render_decl_error(src, &error));
186        });
187    }};
188}
189
190#[cfg(test)]
191pub(crate) use assert_decl_error_snapshot;
192#[cfg(test)]
193pub(crate) use assert_decl_snapshot;