use nash_region::{Located, Region};
use nash_source::{
Alias, Docs, Exposing, Impl, Import, Infix, Module, ModuleKind, Trait, Union, Value,
};
use crate::Parser;
use crate::declaration::Decl;
use crate::error;
impl<'a> Parser<'a> {
pub fn module_header(
&mut self,
) -> Result<(ModuleKind, &'a Located<&'a str>, &'a Located<Exposing<'a>>), error::Module<'a>>
{
let kind = self.one_of_with_fallback(
vec![Box::new(|parser: &mut Parser<'a>| {
let start = parser.get_position();
parser.keyword_validator(error::Module::Validator)?;
let end = parser.get_position();
parser.chomp_and_check_indent(error::Module::Space, error::Module::Validator)?;
Ok(ModuleKind::Validator(Region::new(start, end)))
})],
ModuleKind::Normal,
)?;
self.keyword_module(error::Module::Problem)?;
self.chomp_and_check_indent(error::Module::Space, error::Module::Name)?;
let start = self.get_position();
let name = self.module_name(error::Module::Name)?;
let module_name = self.add_end(start, name);
self.chomp(error::Module::Space)?;
self.keyword_exposing(|row, col| {
error::Module::Exposing(self.bump.alloc(error::Exposing::Start(row, col)), row, col)
})?;
self.chomp_and_check_indent(error::Module::Space, |row, col| {
error::Module::Exposing(
self.bump.alloc(error::Exposing::IndentValue(row, col)),
row,
col,
)
})?;
let exposing_start = self.get_position();
let exposing = self.specialize(
|bump, err, row, col| error::Module::Exposing(bump.alloc(err), row, col),
|p| p.exposing(),
)?;
let exposing_located = self.add_end(exposing_start, exposing);
Ok((kind, module_name, exposing_located))
}
pub(crate) fn imports(&mut self) -> Result<&'a [&'a Import<'a>], error::Module<'a>> {
let mut imports = Vec::new();
loop {
let state = self.save_state();
match self.import() {
Ok(import) => {
imports.push(import);
}
Err(error) => {
if self.pos == state.pos {
self.restore_state(state);
break;
}
return Err(error);
}
}
}
Ok(self.alloc_slice_copy(&imports))
}
fn declarations(&mut self) -> Result<Vec<Decl<'a>>, error::Module<'a>> {
let mut decls = Vec::new();
loop {
let state = self.save_state();
match self.specialize(
|bump, err, row, col| error::Module::Declarations(bump.alloc(err), row, col),
|p| p.declaration(),
) {
Ok((decl, _end)) => {
decls.push(decl);
self.chomp(error::Module::Space)?;
if self.is_eof() {
break;
}
if self.col != 1 {
break;
}
}
Err(error) => {
if self.pos == state.pos {
self.restore_state(state);
break;
}
return Err(error);
}
}
}
Ok(decls)
}
fn infixes(&mut self) -> Result<Vec<&'a Located<Infix<'a>>>, error::Module<'a>> {
let mut infixes = Vec::new();
loop {
let state = self.save_state();
match self.infix_decl() {
Ok(infix) => {
infixes.push(infix);
}
Err(_) => {
if self.pos == state.pos {
self.restore_state(state);
break;
}
return Err(error::Module::Infix(self.row, self.col));
}
}
}
Ok(infixes)
}
pub fn module(&mut self) -> Result<Module<'a>, error::Module<'a>> {
self.chomp(error::Module::Space)?;
let start_pos = self.get_position();
let (kind, name, exports, overview) =
if self.starts_keyword(b"module") || self.starts_keyword(b"validator") {
let (kind, name, exports) = self.module_header()?;
self.chomp(error::Module::Space)?;
self.check_fresh_line(error::Module::FreshLine)?;
let overview = if self.remaining().starts_with(b"{-|") {
let doc = self.doc_comment(error::Module::FreshLine, error::Module::Space)?;
self.chomp(error::Module::Space)?;
self.check_fresh_line(error::Module::FreshLine)?;
Some(doc)
} else {
None
};
(kind, Some(name), exports, overview)
} else {
let default_exports = self.alloc(Located::at(Region::one(), Exposing::Open));
(ModuleKind::Normal, None, default_exports, None)
};
let imports = self.imports()?;
let infix_vec = self.infixes()?;
let binops = self.alloc_slice_copy(&infix_vec);
let decls = self.declarations()?;
self.chomp(error::Module::Space)?;
let tests = self.one_of_with_fallback(
vec![Box::new(|parser: &mut Parser<'a>| {
parser.tests_block().map(Some)
})],
None,
)?;
self.chomp(error::Module::Space)?;
if !self.is_eof() {
return Err(error::Module::BadEnd(self.row, self.col));
}
let (values, unions, aliases, traits, impls) = self.categorize_decls(decls);
let docs = self.alloc(match overview {
Some(overview) => {
let mut comments = Vec::new();
for (name, doc) in values
.iter()
.map(|v| (v.value.name, v.value.docs))
.chain(unions.iter().map(|v| (v.value.name, v.value.docs)))
.chain(aliases.iter().map(|v| (v.value.name, v.value.docs)))
.chain(traits.iter().map(|v| (v.value.name, v.value.docs)))
{
if let Some(doc) = doc {
comments.push(self.alloc((name.value, doc)));
}
}
comments.sort_by_key(|(_, doc)| (doc.region.start.line, doc.region.start.column));
Docs::YesDocs {
overview,
comments: self.alloc_slice_copy(&comments),
}
}
None => Docs::NoDocs(Region::new(start_pos, self.get_position())),
});
let comments = self.alloc_slice_copy(&self.comments);
Ok(Module {
kind,
name,
exports,
docs,
comments,
imports,
values,
unions,
aliases,
traits,
impls,
tests,
binops,
})
}
fn starts_keyword(&self, keyword: &[u8]) -> bool {
let remaining = self.remaining();
remaining.starts_with(keyword)
&& remaining
.get(keyword.len())
.is_none_or(|byte| !byte.is_ascii_alphanumeric() && *byte != b'_')
}
#[allow(clippy::type_complexity)]
fn categorize_decls(
&self,
decls: Vec<Decl<'a>>,
) -> (
&'a [&'a Located<Value<'a>>],
&'a [&'a Located<Union<'a>>],
&'a [&'a Located<Alias<'a>>],
&'a [&'a Located<Trait<'a>>],
&'a [&'a Located<Impl<'a>>],
) {
let mut values = Vec::new();
let mut unions = Vec::new();
let mut aliases = Vec::new();
let mut traits = Vec::new();
let mut impls = Vec::new();
for decl in decls {
match decl {
Decl::Value(value) => values.push(value),
Decl::Union(union) => unions.push(union),
Decl::Alias(alias) => aliases.push(alias),
Decl::Trait(trait_) => traits.push(trait_),
Decl::Impl(impl_) => impls.push(impl_),
}
}
(
self.alloc_slice_copy(&values),
self.alloc_slice_copy(&unions),
self.alloc_slice_copy(&aliases),
self.alloc_slice_copy(&traits),
self.alloc_slice_copy(&impls),
)
}
}
#[cfg(test)]
mod tests {
use super::*;
use bumpalo::Bump;
use indoc::indoc;
macro_rules! assert_module_header_snapshot {
($input:expr) => {{
let input = indoc!($input);
let bump = Bump::new();
let src = bump.alloc_str(input);
let mut parser = Parser::new(&bump, src);
let result = parser.module_header();
match result {
Ok((kind, name, exposing)) => {
insta::with_settings!({
description => format!("Code:\n\n{}", input),
omit_expression => true,
}, {
insta::assert_debug_snapshot!((kind, name, exposing));
});
}
Err(e) => {
panic!("Expected successful parse, got error: {:?}", e);
}
}
}};
}
#[test]
fn module_header_simple_open() {
assert_module_header_snapshot!("module Foo exposing (..)");
}
#[test]
fn module_header_dotted() {
assert_module_header_snapshot!("module Foo.Bar exposing (baz)");
}
#[test]
fn module_header_mixed_exposing() {
assert_module_header_snapshot!("module Main exposing (main, Msg(..))");
}
#[test]
fn module_header_little_types() {
assert_module_header_snapshot!("module P exposing (type option(..), type step)");
}
#[test]
fn module_header_deeply_nested() {
assert_module_header_snapshot!("module Platform.Cmd.Extra exposing (batch, none)");
}
#[test]
fn validator_module_header() {
assert_module_header_snapshot!("validator module Vesting exposing (main)");
}
macro_rules! assert_module_snapshot {
($input:expr) => {{
let input = indoc!($input);
let bump = Bump::new();
let src = bump.alloc_str(input);
let mut parser = Parser::new(&bump, src);
let result = parser.module();
match result {
Ok(module) => {
insta::with_settings!({
description => format!("Code:\n\n{}", input),
omit_expression => true,
}, {
insta::assert_debug_snapshot!(module);
});
}
Err(e) => {
panic!("Expected successful parse, got error: {:?}", e);
}
}
}};
}
macro_rules! assert_module_error_snapshot {
($input:expr) => {{
let input = indoc!($input);
let bump = Bump::new();
let src = bump.alloc_str(input);
let mut parser = nash_parse::Parser::new(&bump, src);
let error = parser.module().expect_err("expected module parse error");
insta::with_settings!({
description => format!("Code:\n\n{}", input),
omit_expression => true,
info => &"diagnostic",
}, {
insta::assert_snapshot!($crate::test_support::render_module_error(src, &error));
});
}};
}
#[test]
fn module_header_only() {
assert_module_snapshot!("module Main exposing (..)\n");
}
#[test]
fn module_with_imports() {
assert_module_snapshot!(
r#"
module Main exposing (..)
import List
import Maybe exposing (Maybe(..))
"#
);
}
#[test]
fn module_with_value() {
assert_module_snapshot!(
r#"
module Main exposing (..)
main = 42
"#
);
}
#[test]
fn module_with_type() {
assert_module_snapshot!(
r#"
module Main exposing (..)
type Maybe 'a
= Just 'a
| Nothing
"#
);
}
#[test]
fn module_with_union_then_value() {
assert_module_snapshot!(
r#"
module Main exposing (..)
type Wrap 'a
= Wrap 'a
f w = w
"#
);
}
#[test]
fn module_with_alias() {
assert_module_snapshot!(
r#"
module Main exposing (..)
type alias Point = { x : Int, y : Int }
"#
);
}
#[test]
fn module_full() {
assert_module_snapshot!(
r#"
module Main exposing (main, Model, Msg(..))
import Html exposing (div)
import Platform.Cmd as Cmd
type alias Model = { count : Int }
type Msg
= Increment
| Decrement
main = 0
"#
);
}
#[test]
fn module_no_header() {
assert_module_snapshot!("x = 1\n");
}
#[test]
fn module_with_infix() {
assert_module_snapshot!(
r#"
module Main exposing (..)
infix left 6 (|>) = apR
apR f x = f x
"#
);
}
#[test]
fn module_with_empty_trait_then_value() {
assert_module_snapshot!(
r#"
module Main exposing (..)
trait Marker 'a where
x = 1
"#
);
}
#[test]
fn later_constraint_does_not_imply_trait_superclass() {
assert_module_snapshot!(
r#"
module Main exposing (..)
trait Show 'a where
id : Eq 'a => 'a -> 'a
id x = x
"#
);
}
#[test]
fn module_with_empty_impl_then_value() {
assert_module_snapshot!(
r#"
module Main exposing (..)
impl Show unit where
x = 1
"#
);
}
#[test]
fn validator_module_full() {
assert_module_snapshot!(
r#"
validator module Vesting exposing (main)
import Cardano.Tx exposing (Tx, Output)
type Datum = Datum { owner : Bytes, deadline : Int }
type step 'a = Done 'a | Next int 'a
type alias acc = { total : int, seen : list Int }
main datum = assert True
"#
);
}
#[test]
fn validator_requires_module_keyword() {
assert_module_error_snapshot!("validator Vesting exposing (main)");
}
#[test]
fn validator_module_must_remain_indented() {
assert_module_error_snapshot!("validator\nmodule V exposing (..)");
}
#[test]
fn module_preserves_import_alias_error() {
assert_module_error_snapshot!("import Cardano.Tx as tx");
}
#[test]
fn module_preserves_type_alias_error() {
assert_module_error_snapshot!("type alias account");
}
#[test]
fn module_preserves_pattern_error() {
assert_module_error_snapshot!("f (x as) = x");
}
#[test]
fn module_preserves_expression_error() {
assert_module_error_snapshot!("value = if True then 42");
}
#[test]
fn module_preserves_annotation_name_error() {
assert_module_error_snapshot!("f : int\ng = 1");
}
#[test]
fn comments_are_collected() {
assert_module_snapshot!(
r#"
-- leading
{- outer {- nested -} block -}
x = {- before value -} 1 -- trailing
-- eof
"#
);
}
#[test]
fn comments_preserve_unicode_and_crlf() {
assert_module_snapshot!("-- café\r\nx = 1 -- 終");
}
#[test]
fn doc_comment_attaches_to_value() {
assert_module_snapshot!("{-| value docs -}\nx = 1");
}
#[test]
fn module_doc_comment() {
assert_module_snapshot!(
r#"
module Main exposing (..)
-- before overview
{-| Overview with {- nested -} content. -}
import A -- import note
{-| Value docs. -}
@inline
x : int
x = 1
"#
);
}
#[test]
fn declaration_docs_survive_categorization() {
assert_module_snapshot!(
r#"
module Documented exposing (..)
{-| Overview. -}
{-| A union. -}
type Box = Box int
{-| An alias. -}
type alias Count = int
{-| A trait. -}
trait Measure 'a where
measure : 'a -> int
{-| An implementation. -}
impl Measure int where
measure x = x
"#
);
}
#[test]
fn backtracking_does_not_duplicate_comments() {
assert_module_snapshot!(
r#"
section = (1 + {- section -})
action = do
f {- speculative pattern -} x
pure ()
"#
);
}
#[test]
fn comments_in_tests_and_strings() {
assert_module_snapshot!(
r#"
text = "-- not a comment {- neither -}"
tests
-- test note
test "works" = do
assert {- assertion note -} True
"#
);
}
}