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(Option<&'a Comment<'a>>, &'a Located<Value<'a>>),
24    Union(Option<&'a Comment<'a>>, &'a Located<Union<'a>>),
25    Alias(Option<&'a Comment<'a>>, &'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(attributes, start)),
57                Box::new(|p: &mut Parser<'a>| p.impl_decl(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) = p.type_alias_body(start, attributes)?;
125                                    Ok((Decl::Alias(maybe_docs, alias), end))
126                                },
127                            )
128                        }),
129                        // type union (custom type)
130                        Box::new(|p| {
131                            p.specialize(
132                                |bump, e, row, col| error::DeclType::Union(bump.alloc(e), row, col),
133                                |p| {
134                                    let (union, end) = p.union_body(start, attributes)?;
135                                    Ok((Decl::Union(maybe_docs, union), end))
136                                },
137                            )
138                        }),
139                    ],
140                )
141            },
142        )
143    }
144}
145
146/// Macro for testing successful declaration parsing.
147#[cfg(test)]
148macro_rules! assert_decl_snapshot {
149    ($src:expr) => {{
150        let bump = bumpalo::Bump::new();
151        let src = indoc::indoc!($src);
152        let src_in_arena = bump.alloc_str(src);
153        let mut parser = crate::Parser::new(&bump, src_in_arena);
154        match parser.declaration() {
155            Ok((decl, _end)) => {
156                parser.chomp(|_, _, _| ()).expect("expected trailing space");
157                assert!(parser.is_eof(), "declaration parser left trailing input");
158                insta::with_settings!({
159                    description => src,
160                    omit_expression => true,
161                }, {
162                    insta::assert_debug_snapshot!(decl);
163                });
164            }
165            Err(e) => panic!("Expected Ok, got Err: {:?}\n\nSource:\n{}", e, src),
166        }
167    }};
168}
169
170#[cfg(test)]
171macro_rules! assert_decl_error_snapshot {
172    ($src:expr) => {{
173        let bump = bumpalo::Bump::new();
174        let src = indoc::indoc!($src);
175        let src_in_arena = bump.alloc_str(src);
176        let mut parser = nash_parse::Parser::new(&bump, src_in_arena);
177        let error = parser.declaration().expect_err("expected declaration parse error");
178        insta::with_settings!({
179            description => src,
180            omit_expression => true,
181                info => &"diagnostic",
182        }, {
183            insta::assert_snapshot!($crate::test_support::render_decl_error(src, &error));
184        });
185    }};
186}
187
188#[cfg(test)]
189pub(crate) use assert_decl_error_snapshot;
190#[cfg(test)]
191pub(crate) use assert_decl_snapshot;