1use 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 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 self.keyword_module(error::Module::Problem)?;
44
45 self.chomp_and_check_indent(error::Module::Space, error::Module::Name)?;
46
47 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 self.chomp(error::Module::Space)?;
54
55 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 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 pub(crate) fn imports(&mut self) -> Result<&'a [&'a Import<'a>], error::Module<'a>> {
92 let mut imports = Vec::new();
93
94 loop {
95 let state = self.save_state();
97
98 match self.import() {
99 Ok(import) => {
100 imports.push(import);
101 }
103 Err(error) => {
104 if self.pos == state.pos {
106 self.restore_state(state);
107 break;
108 }
109 return Err(error);
111 }
112 }
113 }
114
115 Ok(self.alloc_slice_copy(&imports))
116 }
117
118 fn declarations(&mut self) -> Result<Vec<Decl<'a>>, error::Module<'a>> {
132 let mut decls = Vec::new();
133
134 loop {
135 let state = self.save_state();
137
138 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 self.chomp(error::Module::Space)?;
148
149 if self.is_eof() {
151 break;
152 }
153
154 if self.col != 1 {
156 break;
157 }
158 }
159 Err(error) => {
160 if self.pos == state.pos {
162 self.restore_state(state);
163 break;
164 }
165 return Err(error);
167 }
168 }
169 }
170
171 Ok(decls)
172 }
173
174 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 }
188 Err(_) => {
189 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 pub fn module(&mut self) -> Result<Module<'a>, error::Module<'a>> {
209 self.chomp(error::Module::Space)?;
211
212 let start_pos = self.get_position();
213
214 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 let imports = self.imports()?;
228
229 let infix_vec = self.infixes()?;
231 let binops = self.alloc_slice_copy(&infix_vec);
232
233 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 let (values, unions, aliases, traits, impls) = self.categorize_decls(decls);
250
251 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 #[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);
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 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);
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 #[test]
403 fn module_header_only() {
404 assert_module_snapshot!("module Main exposing (..)\n");
405 }
406
407 #[test]
408 fn module_with_imports() {
409 assert_module_snapshot!(
410 r#"
411 module Main exposing (..)
412
413 import List
414 import Maybe exposing (Maybe(..))
415 "#
416 );
417 }
418
419 #[test]
420 fn module_with_value() {
421 assert_module_snapshot!(
422 r#"
423 module Main exposing (..)
424
425 main = 42
426 "#
427 );
428 }
429
430 #[test]
431 fn module_with_type() {
432 assert_module_snapshot!(
433 r#"
434 module Main exposing (..)
435
436 type Maybe 'a
437 = Just 'a
438 | Nothing
439 "#
440 );
441 }
442
443 #[test]
444 fn module_with_union_then_value() {
445 assert_module_snapshot!(
448 r#"
449 module Main exposing (..)
450
451 type Wrap 'a
452 = Wrap 'a
453
454 f w = w
455 "#
456 );
457 }
458
459 #[test]
460 fn module_with_alias() {
461 assert_module_snapshot!(
462 r#"
463 module Main exposing (..)
464
465 type alias Point = { x : Int, y : Int }
466 "#
467 );
468 }
469
470 #[test]
471 fn module_full() {
472 assert_module_snapshot!(
473 r#"
474 module Main exposing (main, Model, Msg(..))
475
476 import Html exposing (div)
477 import Platform.Cmd as Cmd
478
479 type alias Model = { count : Int }
480
481 type Msg
482 = Increment
483 | Decrement
484
485 main = 0
486 "#
487 );
488 }
489
490 #[test]
491 fn module_no_header() {
492 assert_module_snapshot!("x = 1\n");
494 }
495
496 #[test]
497 fn module_with_infix() {
498 assert_module_snapshot!(
499 r#"
500 module Main exposing (..)
501
502 infix left 6 (|>) = apR
503
504 apR f x = f x
505 "#
506 );
507 }
508
509 #[test]
510 fn module_with_empty_trait_then_value() {
511 assert_module_snapshot!(
512 r#"
513 module Main exposing (..)
514
515 trait Marker 'a where
516
517 x = 1
518 "#
519 );
520 }
521 #[test]
522 fn later_constraint_does_not_imply_trait_superclass() {
523 assert_module_snapshot!(
524 r#"
525 module Main exposing (..)
526
527 trait Show 'a where
528
529 id : Eq 'a => 'a -> 'a
530 id x = x
531 "#
532 );
533 }
534
535 #[test]
536 fn module_with_empty_impl_then_value() {
537 assert_module_snapshot!(
538 r#"
539 module Main exposing (..)
540
541 impl Show unit where
542
543 x = 1
544 "#
545 );
546 }
547
548 #[test]
549 fn validator_module_full() {
550 assert_module_snapshot!(
551 r#"
552 validator module Vesting exposing (main)
553
554 import Cardano.Tx exposing (Tx, Output)
555
556 type Datum = Datum { owner : Bytes, deadline : Int }
557
558 type step 'a = Done 'a | Next int 'a
559
560 type alias acc = { total : int, seen : list Int }
561
562 main datum = assert True
563 "#
564 );
565 }
566}