Skip to main content

nash_parse/
type_.rs

1//! Type parsing for Nash.
2//!
3//! Ported from Elm's `Parse/Type.hs`.
4//!
5//! Provides:
6//! - `type_term` - atomic types (variables, named types, tuples, records)
7//! - `type_expr` - full types including function arrows and type application
8
9use bumpalo::collections::Vec as BumpVec;
10use nash_region::{Located, Position, Region};
11use nash_source::{Annotation, Constraint, FieldType, Repr, Type, TypeParam};
12
13use crate::Parser;
14use crate::error::{self, TRecord, TTuple};
15
16/// Qualified or unqualified type name.
17enum TypeName<'a> {
18    Unqualified(&'a str),
19    Qualified(&'a str, &'a str), // (module, name)
20}
21
22enum Head<'a> {
23    Name(TypeName<'a>),
24    Var(&'a str),
25}
26
27impl<'a> Parser<'a> {
28    // -------------------------------------------------------------------------
29    // Type expressions (with arrows)
30    // -------------------------------------------------------------------------
31
32    /// Parse a type expression including function arrows.
33    ///
34    /// Returns `(type, end)` where `end` is the position at end of type (before any chomp).
35    ///
36    /// Mirrors Elm's `Type.expression`:
37    /// ```haskell
38    /// expression :: Space.Parser E.Type Src.Type
39    /// expression =
40    ///   do  start <- getPosition
41    ///       term1@(tipe1, end1) <- oneOf E.TStart [ app start, term... ]
42    ///       oneOfWithFallback [ arrow... ] term1
43    /// ```
44    pub fn type_expr(&mut self) -> Result<(&'a Located<Type<'a>>, Position), error::Type<'a>> {
45        let start = self.get_position();
46
47        // Parse first term - either type application or simple term
48        let (tipe1, end1) = self.one_of(
49            error::Type::Start,
50            vec![
51                // Type application: Maybe Int, Outcome String Int, etc.
52                Box::new(|p: &mut Parser<'a>| p.type_app(start)),
53                // Simple term
54                Box::new(|p: &mut Parser<'a>| {
55                    let term = p.type_term()?;
56                    let end = p.get_position();
57                    p.chomp(error::Type::Space)?;
58                    Ok((term, end))
59                }),
60            ],
61        )?;
62
63        // Try to parse function arrow
64        self.one_of_with_fallback(
65            vec![Box::new(|p: &mut Parser<'a>| {
66                p.check_indent(end1.line, end1.column, error::Type::IndentStart)?;
67                p.word2(0x2D, 0x3E, error::Type::Start)?; // ->
68                p.chomp_and_check_indent(error::Type::Space, error::Type::IndentStart)?;
69
70                let (tipe2, end2) = p.type_expr()?;
71                let tipe = p.alloc(Located::at(
72                    Region::new(start, end2),
73                    Type::Lambda {
74                        from: tipe1,
75                        to: tipe2,
76                    },
77                ));
78                Ok((tipe, end2))
79            })],
80            (tipe1, end1),
81        )
82    }
83
84    /// Parse an optional constraint context followed by a type.
85    pub fn type_scheme(&mut self) -> Result<(&'a Annotation<'a>, Position), error::Type<'a>> {
86        let start = self.get_position();
87        let (first, end1) = self.type_expr()?;
88
89        self.one_of_with_fallback(
90            vec![Box::new(|p: &mut Parser<'a>| {
91                p.check_indent(end1.line, end1.column, error::Type::IndentStart)?;
92                p.word2(b'=', b'>', error::Type::Start)?;
93                let constraints = p.to_constraints(first, start)?;
94                p.chomp_and_check_indent(error::Type::Space, error::Type::IndentAfterContext)?;
95                let (typ, end2) = p.type_expr()?;
96                Ok((p.alloc(Annotation { constraints, typ }), end2))
97            })],
98            (
99                self.alloc(Annotation {
100                    constraints: &[],
101                    typ: first,
102                }),
103                end1,
104            ),
105        )
106    }
107
108    fn to_constraints(
109        &self,
110        typ: &'a Located<Type<'a>>,
111        start: Position,
112    ) -> Result<&'a [&'a Located<Constraint<'a>>], error::Type<'a>> {
113        let bad = || error::Type::Context(start.line, start.column);
114        match &typ.value {
115            Type::Tuple {
116                first,
117                second,
118                rest,
119            } => {
120                let mut out = BumpVec::new_in(self.bump);
121                for typ in [*first, *second].into_iter().chain(rest.iter().copied()) {
122                    out.push(self.to_constraint(typ).ok_or_else(bad)?);
123                }
124                Ok(out.into_bump_slice())
125            }
126            _ => Ok(self.alloc_slice_copy(&[self.to_constraint(typ).ok_or_else(bad)?])),
127        }
128    }
129
130    pub(crate) fn to_constraint(
131        &self,
132        typ: &'a Located<Type<'a>>,
133    ) -> Option<&'a Located<Constraint<'a>>> {
134        let (region, module, name, args) = match &typ.value {
135            Type::Type { region, name, args } if !args.is_empty() => (*region, None, *name, *args),
136            Type::TypeQual {
137                region,
138                module,
139                name,
140                args,
141            } if !args.is_empty() => (*region, Some(*module), *name, *args),
142            _ => return None,
143        };
144        if !name.starts_with(|c: char| c.is_ascii_uppercase()) {
145            return None;
146        }
147        let class = self.alloc(Located::at(region, name));
148        Some(self.alloc(Located::at(
149            typ.region,
150            Constraint {
151                class,
152                module,
153                args,
154            },
155        )))
156    }
157
158    // -------------------------------------------------------------------------
159    // Type application
160    // -------------------------------------------------------------------------
161
162    /// Parse type application: `Maybe Int`, `Outcome String Int`, etc.
163    ///
164    /// Mirrors Elm's `Type.app`.
165    fn type_app(
166        &mut self,
167        start: Position,
168    ) -> Result<(&'a Located<Type<'a>>, Position), error::Type<'a>> {
169        let head = self.one_of(
170            error::Type::Start,
171            vec![
172                Box::new(|p: &mut Parser<'a>| p.type_name(error::Type::Start).map(Head::Name)),
173                Box::new(|p: &mut Parser<'a>| {
174                    p.type_var_name(error::Type::VarStart).map(Head::Var)
175                }),
176            ],
177        )?;
178        let head_end = self.get_position();
179        self.chomp(error::Type::Space)?;
180
181        let (args, end) = self.type_chomp_args(head_end)?;
182
183        let region = Region::new(start, head_end);
184        let tipe = match head {
185            Head::Name(TypeName::Unqualified(name)) => Type::Type { region, name, args },
186            Head::Name(TypeName::Qualified(module, name)) => Type::TypeQual {
187                region,
188                module,
189                name,
190                args,
191            },
192            Head::Var(name) if args.is_empty() => Type::Var(name),
193            Head::Var(name) => Type::VarApp { region, name, args },
194        };
195
196        Ok((self.alloc(Located::at(Region::new(start, end), tipe)), end))
197    }
198
199    /// Chomp type arguments for application.
200    ///
201    /// Mirrors Elm's `Type.chompArgs`.
202    fn type_chomp_args(
203        &mut self,
204        mut end: Position,
205    ) -> Result<(&'a [&'a Located<Type<'a>>], Position), error::Type<'a>> {
206        let mut args: BumpVec<'a, &'a Located<Type<'a>>> = BumpVec::new_in(self.bump);
207
208        loop {
209            let result = self.one_of_with_fallback(
210                vec![Box::new(|p: &mut Parser<'a>| {
211                    // Check CURRENT position (after chomp), not the end of previous token
212                    let (row, col) = p.position();
213                    p.check_indent(row, col, error::Type::IndentStart)?;
214                    let arg = p.type_term()?;
215                    let new_end = p.get_position();
216                    p.chomp(error::Type::Space)?;
217                    Ok(Some((arg, new_end)))
218                })],
219                None,
220            )?;
221
222            match result {
223                Some((arg, new_end)) => {
224                    args.push(arg);
225                    end = new_end;
226                }
227                None => break,
228            }
229        }
230
231        Ok((args.into_bump_slice(), end))
232    }
233
234    // -------------------------------------------------------------------------
235    // Type terms (atomic)
236    // -------------------------------------------------------------------------
237
238    /// Parse an atomic type (no arrows, no application).
239    ///
240    /// Mirrors Elm's `Type.term`:
241    /// - Named types: `Int`, `Maybe`, `Module.Type`
242    /// - Type variables: `a`, `msg`
243    /// - Tuples: `()`, `(Int, String)`
244    /// - Records: `{}`, `{ name : String }`
245    pub fn type_term(&mut self) -> Result<&'a Located<Type<'a>>, error::Type<'a>> {
246        let start = self.get_position();
247
248        self.one_of(
249            error::Type::Start,
250            vec![
251                // Named type (no args in term - args handled by app)
252                Box::new(|p: &mut Parser<'a>| {
253                    let name = p.type_name(error::Type::Start)?;
254                    let end = p.get_position();
255                    let region = Region::new(start, end);
256
257                    let tipe = match name {
258                        TypeName::Unqualified(name) => {
259                            let empty: &'a [&'a Located<Type<'a>>] = &[];
260                            Type::Type {
261                                region,
262                                name,
263                                args: empty,
264                            }
265                        }
266                        TypeName::Qualified(module, name) => {
267                            let empty: &'a [&'a Located<Type<'a>>] = &[];
268                            Type::TypeQual {
269                                region,
270                                module,
271                                name,
272                                args: empty,
273                            }
274                        }
275                    };
276
277                    Ok(p.add_end(start, tipe))
278                }),
279                // Type variable
280                Box::new(|p: &mut Parser<'a>| {
281                    let var = p.type_var_name(error::Type::VarStart)?;
282                    Ok(p.add_end(start, Type::Var(var)))
283                }),
284                // Tuple (or unit, or parenthesized)
285                Box::new(|p: &mut Parser<'a>| p.type_tuple(start)),
286                // Record
287                Box::new(|p: &mut Parser<'a>| p.type_record(start)),
288            ],
289        )
290    }
291
292    // -------------------------------------------------------------------------
293    // Tuples
294    // -------------------------------------------------------------------------
295
296    /// Parse a tuple type: `()`, `(a)`, `(a, b)`, `(a, b, c)`
297    fn type_tuple(&mut self, start: Position) -> Result<&'a Located<Type<'a>>, error::Type<'a>> {
298        self.in_context(
299            |bump, tuple_err, row, col| error::Type::Tuple(bump.alloc(tuple_err), row, col),
300            |p| p.word1(0x28, error::Type::Start), // (
301            |p| p.type_tuple_body(start),
302        )
303    }
304
305    /// Parse tuple type body after `(`.
306    fn type_tuple_body(&mut self, start: Position) -> Result<&'a Located<Type<'a>>, TTuple<'a>> {
307        self.chomp_and_check_indent(TTuple::Space, TTuple::IndentType1)?;
308
309        self.one_of(
310            TTuple::Open,
311            vec![
312                // Unit: `()`
313                Box::new(|p: &mut Parser<'a>| {
314                    p.word1(0x29, TTuple::Open)?; // )
315                    Ok(p.add_end(start, Type::Unit))
316                }),
317                // Type (might be parenthesized or tuple)
318                Box::new(|p: &mut Parser<'a>| {
319                    let (first, end) = p.type_tuple_entry()?;
320                    p.check_indent(end.line, end.column, TTuple::IndentEnd)?;
321                    p.one_of(
322                        TTuple::End,
323                        vec![
324                            Box::new(|p: &mut Parser<'a>| {
325                                p.word1(b':', TTuple::End)?;
326                                p.chomp_and_check_indent(TTuple::Space, TTuple::IndentRepr)?;
327                                let (repr, end) = p.specialize(
328                                    |bump, error, row, col| {
329                                        TTuple::Repr(bump.alloc(error), row, col)
330                                    },
331                                    |p| p.repr_annotation(),
332                                )?;
333                                p.check_indent(end.line, end.column, TTuple::IndentEnd)?;
334                                p.word1(b')', TTuple::End)?;
335                                Ok(p.add_end(start, Type::Repr { typ: first, repr }))
336                            }),
337                            Box::new(|p: &mut Parser<'a>| p.type_tuple_help(start, first)),
338                        ],
339                    )
340                }),
341            ],
342        )
343    }
344
345    /// Parse a type inside a tuple.
346    fn type_tuple_entry(&mut self) -> Result<(&'a Located<Type<'a>>, Position), TTuple<'a>> {
347        self.specialize(
348            |bump, type_err, row, col| TTuple::Type(bump.alloc(type_err), row, col),
349            |p| p.type_expr(),
350        )
351    }
352
353    /// Parse remaining tuple elements.
354    fn type_tuple_help(
355        &mut self,
356        start: Position,
357        first: &'a Located<Type<'a>>,
358    ) -> Result<&'a Located<Type<'a>>, TTuple<'a>> {
359        let mut rest: BumpVec<'a, &'a Located<Type<'a>>> = BumpVec::new_in(self.bump);
360
361        loop {
362            self.chomp(TTuple::Space)?;
363
364            let done = self.one_of(
365                TTuple::End,
366                vec![
367                    // Comma - another type
368                    Box::new(|p: &mut Parser<'a>| {
369                        p.word1(0x2C, TTuple::End)?; // ,
370                        p.chomp_and_check_indent(TTuple::Space, TTuple::IndentTypeN)?;
371
372                        let (tipe, end) = p.type_tuple_entry()?;
373                        rest.push(tipe);
374
375                        p.check_indent(end.line, end.column, TTuple::IndentEnd)?;
376                        Ok(false)
377                    }),
378                    // Close paren
379                    Box::new(|p: &mut Parser<'a>| {
380                        p.word1(0x29, TTuple::End)?; // )
381                        Ok(true)
382                    }),
383                ],
384            )?;
385
386            if done {
387                break;
388            }
389        }
390
391        if rest.is_empty() {
392            // Just parenthesized type
393            Ok(first)
394        } else {
395            // Tuple
396            let second = rest.remove(0);
397            let others = rest.into_bump_slice();
398            Ok(self.add_end(
399                start,
400                Type::Tuple {
401                    first,
402                    second,
403                    rest: others,
404                },
405            ))
406        }
407    }
408
409    // -------------------------------------------------------------------------
410    // Records
411    // -------------------------------------------------------------------------
412
413    /// Parse a record type: `{}`, `{ name : String }`
414    fn type_record(&mut self, start: Position) -> Result<&'a Located<Type<'a>>, error::Type<'a>> {
415        self.in_context(
416            |bump, record_err, row, col| error::Type::Record(bump.alloc(record_err), row, col),
417            |p| p.word1(0x7B, error::Type::Start), // {
418            |p| p.type_record_body(start),
419        )
420    }
421
422    /// Parse record type body after `{`.
423    fn type_record_body(&mut self, start: Position) -> Result<&'a Located<Type<'a>>, TRecord<'a>> {
424        self.chomp_and_check_indent(TRecord::Space, TRecord::IndentOpen)?;
425
426        self.one_of(
427            TRecord::Open,
428            vec![
429                // Empty record: `{}`
430                Box::new(|p: &mut Parser<'a>| {
431                    p.word1(0x7D, TRecord::Open)?; // }
432                    let empty: &'a [&'a FieldType<'a>] = &[];
433                    Ok(p.add_end(start, Type::Record(empty)))
434                }),
435                // Non-empty record
436                Box::new(|p: &mut Parser<'a>| {
437                    let field = p.type_record_field()?;
438                    let fields = p.type_record_end(field)?;
439                    Ok(p.add_end(start, Type::Record(fields)))
440                }),
441            ],
442        )
443    }
444
445    /// Parse a type inside a record field.
446    fn type_record_type_entry(&mut self) -> Result<(&'a Located<Type<'a>>, Position), TRecord<'a>> {
447        self.specialize(
448            |bump, type_err, row, col| TRecord::Type(bump.alloc(type_err), row, col),
449            |p| p.type_expr(),
450        )
451    }
452
453    /// Parse a record field: `name : Type`
454    fn type_record_field(&mut self) -> Result<&'a FieldType<'a>, TRecord<'a>> {
455        let name_start = self.get_position();
456        let name = self.lower_name(TRecord::Field)?;
457        let name_loc = self.add_end(name_start, name);
458
459        self.chomp_and_check_indent(TRecord::Space, TRecord::IndentColon)?;
460        self.word1(0x3A, TRecord::Colon)?; // :
461        self.chomp_and_check_indent(TRecord::Space, TRecord::IndentType)?;
462
463        let (tipe, end) = self.type_record_type_entry()?;
464        self.check_indent(end.line, end.column, TRecord::IndentEnd)?;
465
466        Ok(self.alloc(FieldType {
467            field: name_loc,
468            typ: tipe,
469        }))
470    }
471
472    /// Parse remaining record fields.
473    fn type_record_end(
474        &mut self,
475        first: &'a FieldType<'a>,
476    ) -> Result<&'a [&'a FieldType<'a>], TRecord<'a>> {
477        let mut fields: BumpVec<'a, &'a FieldType<'a>> = BumpVec::new_in(self.bump);
478        fields.push(first);
479
480        loop {
481            self.chomp(TRecord::Space)?;
482
483            let done = self.one_of(
484                TRecord::End,
485                vec![
486                    // Comma - another field
487                    Box::new(|p: &mut Parser<'a>| {
488                        p.word1(0x2C, TRecord::End)?; // ,
489                        p.chomp_and_check_indent(TRecord::Space, TRecord::IndentField)?;
490
491                        let field = p.type_record_field()?;
492                        fields.push(field);
493                        Ok(false)
494                    }),
495                    // Close brace
496                    Box::new(|p: &mut Parser<'a>| {
497                        p.word1(0x7D, TRecord::End)?; // }
498                        Ok(true)
499                    }),
500                ],
501            )?;
502
503            if done {
504                break;
505            }
506        }
507
508        Ok(fields.into_bump_slice())
509    }
510
511    /// Parse a declaration type parameter, with an optional representation annotation.
512    pub(crate) fn type_param(&mut self) -> Result<&'a TypeParam<'a>, error::TypeParam<'a>> {
513        let start = self.get_position();
514        self.one_of(
515            error::TypeParam::Start,
516            vec![
517                Box::new(|p: &mut Parser<'a>| {
518                    let name = p.type_var_name(error::TypeParam::Start)?;
519                    Ok(p.alloc(TypeParam {
520                        name: p.add_end(start, name),
521                        repr: None,
522                    }))
523                }),
524                Box::new(|p: &mut Parser<'a>| {
525                    p.word1(b'(', error::TypeParam::Start)?;
526                    p.chomp_and_check_indent(
527                        error::TypeParam::Space,
528                        error::TypeParam::IndentColon,
529                    )?;
530                    let name_start = p.get_position();
531                    let name = p.type_var_name(error::TypeParam::Start)?;
532                    let name = p.add_end(name_start, name);
533                    p.chomp_and_check_indent(
534                        error::TypeParam::Space,
535                        error::TypeParam::IndentColon,
536                    )?;
537                    p.word1(b':', error::TypeParam::Colon)?;
538                    p.chomp_and_check_indent(
539                        error::TypeParam::Space,
540                        error::TypeParam::IndentRepr,
541                    )?;
542                    let (repr, end) = p.specialize(
543                        |bump, e, row, col| error::TypeParam::Repr(bump.alloc(e), row, col),
544                        |p| p.repr_annotation(),
545                    )?;
546                    p.check_indent(end.line, end.column, error::TypeParam::IndentEnd)?;
547                    p.word1(b')', error::TypeParam::End)?;
548                    Ok(p.alloc(TypeParam {
549                        name,
550                        repr: Some(repr),
551                    }))
552                }),
553            ],
554        )
555    }
556
557    /// Parse representation sugar and reject the removed kind-arrow syntax.
558    fn repr_annotation(&mut self) -> Result<(&'a Located<Repr>, Position), error::Repr<'a>> {
559        let start = self.get_position();
560        let (row, col) = self.position();
561        let name = self.upper_name(error::Repr::Start)?;
562        let repr = match name {
563            "Big" => Repr::Big,
564            "Const" => Repr::Const,
565            "Term" => Repr::Term,
566            "Storable" => Repr::Storable,
567            "Little" => Repr::Little,
568            other => return Err(error::Repr::Name(other, row, col)),
569        };
570        let value = self.add_end(start, repr);
571        let end = self.get_position();
572        self.chomp(error::Repr::Space)?;
573        if self.peek() == Some(b'-') {
574            let (row, col) = self.position();
575            self.word2(b'-', b'>', error::Repr::Start)?;
576            return Err(error::Repr::Arrow(row, col));
577        }
578        Ok((value, end))
579    }
580
581    // -------------------------------------------------------------------------
582    // Helpers
583    // -------------------------------------------------------------------------
584
585    /// Parse a type name, with an uppercase module path and either type casing.
586    ///
587    /// Mirrors Elm's `Var.foreignUpper`.
588    fn type_name<E>(
589        &mut self,
590        to_error: impl FnOnce(usize, usize) -> E,
591    ) -> Result<TypeName<'a>, E> {
592        let (row, col) = self.position();
593        let start_pos = self.pos;
594
595        match self.peek() {
596            Some(b) if b.is_ascii_lowercase() => {
597                Ok(TypeName::Unqualified(self.lower_name(to_error)?))
598            }
599            Some(b) if b.is_ascii_uppercase() => {
600                self.advance();
601                self.chomp_inner_chars();
602
603                // Check for qualification
604                if self.is_dot_upper() || self.is_dot_lower() {
605                    self.chomp_qualified_upper_for_type(start_pos, to_error)
606                } else {
607                    let name = self.slice_from(start_pos);
608                    Ok(TypeName::Unqualified(name))
609                }
610            }
611            _ => Err(to_error(row, col)),
612        }
613    }
614
615    /// Chomp through Module.Module... chain for type names.
616    fn chomp_qualified_upper_for_type<E>(
617        &mut self,
618        start_pos: usize,
619        to_error: impl FnOnce(usize, usize) -> E,
620    ) -> Result<TypeName<'a>, E> {
621        loop {
622            if self.is_dot_upper() {
623                self.advance(); // consume dot
624                self.advance(); // consume first uppercase char
625                self.chomp_inner_chars();
626            } else if self.is_dot_lower() {
627                let module_end = self.pos;
628                self.advance();
629                let name = self.lower_name(to_error)?;
630                return Ok(TypeName::Qualified(
631                    &self.slice_from(start_pos)[..module_end - start_pos],
632                    name,
633                ));
634            } else {
635                // No more dots - split into module and name
636                let full = self.slice_from(start_pos);
637                if let Some(last_dot) = full.rfind('.') {
638                    let module = &full[..last_dot];
639                    let name = &full[last_dot + 1..];
640                    return Ok(TypeName::Qualified(module, name));
641                } else {
642                    return Ok(TypeName::Unqualified(full));
643                }
644            }
645        }
646    }
647}
648
649// =============================================================================
650// Tests
651// =============================================================================
652
653#[cfg(test)]
654macro_rules! assert_type_snapshot {
655    ($code:expr) => {{
656        let bump = bumpalo::Bump::new();
657        let src = bump.alloc_str(indoc::indoc!($code));
658        let mut parser = $crate::Parser::new(&bump, src);
659        let (result, _end) = parser.type_expr().expect("expected successful parse");
660        parser.chomp(|_, _, _| ()).expect("expected trailing space");
661        assert!(parser.is_eof(), "type parser left trailing input");
662
663        insta::with_settings!({
664            description => format!("Code:\n\n{}", indoc::indoc!($code)),
665            omit_expression => true,
666        }, {
667            insta::assert_debug_snapshot!(result);
668        });
669    }};
670}
671
672#[cfg(test)]
673macro_rules! assert_type_error_snapshot {
674    ($code:expr) => {{
675        let bump = bumpalo::Bump::new();
676        let src = bump.alloc_str(indoc::indoc!($code));
677        let mut parser = nash_parse::Parser::new(&bump, src);
678        let result = parser.type_expr().expect_err("expected parse error");
679
680        insta::with_settings!({
681            description => format!("Code:\n\n{}", indoc::indoc!($code)),
682            omit_expression => true,
683                info => &"diagnostic",
684        }, {
685            insta::assert_snapshot!($crate::test_support::render_type_error(src, &result));
686        });
687    }};
688}
689
690#[cfg(test)]
691macro_rules! assert_scheme_snapshot {
692    ($code:expr) => {{
693        let bump = bumpalo::Bump::new();
694        let src = bump.alloc_str(indoc::indoc!($code));
695        let mut parser = $crate::Parser::new(&bump, src);
696        let (result, _end) = parser.type_scheme().expect("expected successful parse");
697        parser.chomp(|_, _, _| ()).expect("expected trailing space");
698        assert!(parser.is_eof(), "type scheme parser left trailing input");
699
700        insta::with_settings!({
701            description => format!("Code:\n\n{}", indoc::indoc!($code)),
702            omit_expression => true,
703        }, {
704            insta::assert_debug_snapshot!(result);
705        });
706    }};
707}
708
709#[cfg(test)]
710macro_rules! assert_scheme_error_snapshot {
711    ($code:expr) => {{
712        let bump = bumpalo::Bump::new();
713        let src = bump.alloc_str(indoc::indoc!($code));
714        let mut parser = nash_parse::Parser::new(&bump, src);
715        let result = parser.type_scheme().expect_err("expected parse error");
716
717        insta::with_settings!({
718            description => format!("Code:\n\n{}", indoc::indoc!($code)),
719            omit_expression => true,
720                info => &"diagnostic",
721        }, {
722            insta::assert_snapshot!($crate::test_support::render_type_error(src, &result));
723        });
724    }};
725}
726
727/// Snapshot test macro for multiline types, laid out as they would appear
728/// indented inside a declaration (see `test_support::indent_fragment`).
729#[cfg(test)]
730macro_rules! assert_indented_type_snapshot {
731    ($code:expr) => {{
732        let bump = bumpalo::Bump::new();
733        let fragment = indoc::indoc!($code);
734        let indented = $crate::test_support::indent_fragment(fragment);
735        let src = bump.alloc_str(&indented);
736        let mut parser = $crate::Parser::new(&bump, src);
737        parser
738            .chomp(|_, _, _| "space error")
739            .expect("expected leading indent");
740        let (result, _end) = parser.type_expr().expect("expected successful parse");
741        parser.chomp(|_, _, _| ()).expect("expected trailing space");
742        assert!(parser.is_eof(), "type parser left trailing input");
743
744        insta::with_settings!({
745            description => format!("Code (indented inside a declaration):\n\n{}", indented),
746            omit_expression => true,
747        }, {
748            insta::assert_debug_snapshot!(result);
749        });
750    }};
751}
752
753#[cfg(test)]
754mod tests {
755    #[test]
756    fn little_representation_bound() {
757        assert_type_snapshot!("('a : Little)");
758    }
759
760    #[test]
761    fn scheme_single_constraint() {
762        assert_scheme_snapshot!("Eq 'a => 'a -> 'a -> bool");
763    }
764
765    #[test]
766    fn scheme_tuple_constraints() {
767        assert_scheme_snapshot!("(Eq 'a, Show 'b) => 'a -> 'b -> string");
768    }
769
770    #[test]
771    fn scheme_multi_argument_constraint() {
772        assert_scheme_snapshot!("Lift 'small 'big => 'small -> 'big");
773    }
774
775    #[test]
776    fn scheme_qualified_constraint() {
777        assert_scheme_snapshot!("Cardano.Eq Datum => Datum -> bool");
778    }
779
780    #[test]
781    fn scheme_without_constraints() {
782        assert_scheme_snapshot!("'a -> 'a");
783    }
784
785    #[test]
786    fn scheme_error_variable_context() {
787        assert_scheme_error_snapshot!("'a => 'a");
788    }
789
790    #[test]
791    fn scheme_error_constraint_without_argument() {
792        assert_scheme_error_snapshot!("Eq => 'a");
793    }
794
795    #[test]
796    fn scheme_error_tuple_member() {
797        assert_scheme_error_snapshot!("(Eq 'a, 'b) => 'a");
798    }
799
800    #[test]
801    fn scheme_error_little_class() {
802        assert_scheme_error_snapshot!("int 'a => 'a");
803    }
804
805    // Type variables
806    #[test]
807    fn representation_annotation_rejects_arrow() {
808        assert_type_error_snapshot!("('f : Big -> Big)");
809    }
810
811    #[test]
812    fn inline_representation_annotation_in_nested_type() {
813        assert_type_snapshot!("list (pair ('a : Big) ('b : Storable))");
814    }
815
816    #[test]
817    fn inline_representation_annotation_reports_unknown_name() {
818        assert_type_error_snapshot!("list ('a : Wrong)");
819    }
820
821    #[test]
822    fn type_var_simple() {
823        assert_type_snapshot!("'a");
824    }
825
826    #[test]
827    fn type_var_msg() {
828        assert_type_snapshot!("'msg");
829    }
830
831    // Named types (no args)
832    #[test]
833    fn named_type_int() {
834        assert_type_snapshot!("Int");
835    }
836
837    #[test]
838    fn named_type_qualified() {
839        assert_type_snapshot!("Dict.Dict");
840    }
841
842    #[test]
843    fn named_type_qualified_little() {
844        assert_type_snapshot!("Types.point");
845    }
846
847    #[test]
848    fn named_type_multi_qualified_little() {
849        assert_type_snapshot!("Some.Types.box 'a");
850    }
851
852    #[test]
853    fn named_type_multi_qualified() {
854        assert_type_snapshot!("Data.Map.Map");
855    }
856
857    // Type application
858    #[test]
859    fn type_app_maybe() {
860        assert_type_snapshot!("Maybe Int");
861    }
862
863    #[test]
864    fn type_app_result() {
865        assert_type_snapshot!("Outcome String Int");
866    }
867
868    #[test]
869    fn type_app_nested() {
870        assert_type_snapshot!("Maybe (List Int)");
871    }
872
873    #[test]
874    fn type_app_qualified() {
875        assert_type_snapshot!("Dict.Dict String Int");
876    }
877
878    // Function types
879    #[test]
880    fn function_simple() {
881        assert_type_snapshot!("'a -> 'b");
882    }
883
884    #[test]
885    fn function_multi() {
886        assert_type_snapshot!("'a -> 'b -> 'c");
887    }
888
889    #[test]
890    fn function_with_types() {
891        assert_type_snapshot!("Int -> String -> Bool");
892    }
893
894    #[test]
895    fn function_with_app() {
896        assert_type_snapshot!("Maybe 'a -> Outcome 'e 'a");
897    }
898
899    // Unit
900    #[test]
901    fn unit() {
902        assert_type_snapshot!("()");
903    }
904
905    // Tuple types
906    #[test]
907    fn tuple_pair() {
908        assert_type_snapshot!("(Int, String)");
909    }
910
911    #[test]
912    fn tuple_triple() {
913        assert_type_snapshot!("(Int, String, Bool)");
914    }
915
916    #[test]
917    fn tuple_nested() {
918        assert_type_snapshot!("((Int, String), Bool)");
919    }
920
921    #[test]
922    fn tuple_with_function() {
923        assert_type_snapshot!("('a -> 'b, 'c)");
924    }
925
926    #[test]
927    fn tuple_multiline() {
928        assert_indented_type_snapshot!(
929            "(
930                Int,
931                String,
932                Bool
933            )"
934        );
935    }
936
937    // Record types
938    #[test]
939    fn record_empty() {
940        assert_type_snapshot!("{}");
941    }
942
943    #[test]
944    fn record_single() {
945        assert_type_snapshot!("{ name : String }");
946    }
947
948    #[test]
949    fn record_multiple() {
950        assert_type_snapshot!("{ name : String, age : Int }");
951    }
952
953    #[test]
954    fn record_with_function() {
955        assert_type_snapshot!("{ onClick : 'msg -> Cmd 'msg }");
956    }
957
958    #[test]
959    fn record_multiline() {
960        assert_indented_type_snapshot!(
961            "{
962                name : String,
963                age : Int,
964                active : Bool
965            }"
966        );
967    }
968
969    // Parenthesized
970    #[test]
971    fn parenthesized() {
972        assert_type_snapshot!("(Int)");
973    }
974
975    #[test]
976    fn parenthesized_function() {
977        assert_type_snapshot!("('a -> 'b) -> List 'a -> List 'b");
978    }
979
980    // Complex combinations
981    #[test]
982    fn complex_model_msg() {
983        assert_type_snapshot!("{ model : Model, update : Msg -> Model -> Model }");
984    }
985
986    #[test]
987    fn little_type() {
988        assert_type_snapshot!("a");
989    }
990
991    #[test]
992    fn little_type_application() {
993        assert_type_snapshot!("list int");
994    }
995
996    #[test]
997    fn type_variable_application() {
998        assert_type_snapshot!("'f 'a");
999    }
1000
1001    #[test]
1002    fn mixed_type_names() {
1003        assert_type_snapshot!("option 'a -> 'a");
1004        assert_type_snapshot!("Map 'k (List 'v)");
1005        assert_type_snapshot!("{ x : int, y : Int }");
1006    }
1007
1008    #[test]
1009    fn error_empty_type_variable() {
1010        assert_type_error_snapshot!("'");
1011    }
1012
1013    #[test]
1014    fn error_upper_type_variable() {
1015        assert_type_error_snapshot!("'A");
1016    }
1017
1018    #[test]
1019    fn error_record_extension() {
1020        assert_type_error_snapshot!("{ r | x : int }");
1021    }
1022}