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 uppercase name (for types).
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, Result 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`, `Result 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            other => return Err(error::Repr::Name(other, row, col)),
568        };
569        let value = self.add_end(start, repr);
570        let end = self.get_position();
571        self.chomp(error::Repr::Space)?;
572        if self.peek() == Some(b'-') {
573            let (row, col) = self.position();
574            self.word2(b'-', b'>', error::Repr::Start)?;
575            return Err(error::Repr::Arrow(row, col));
576        }
577        Ok((value, end))
578    }
579
580    // -------------------------------------------------------------------------
581    // Helpers
582    // -------------------------------------------------------------------------
583
584    /// Parse a possibly-qualified uppercase name (for types).
585    ///
586    /// Mirrors Elm's `Var.foreignUpper`.
587    fn type_name<E>(&mut self, to_error: impl FnOnce(u16, u16) -> E) -> Result<TypeName<'a>, E> {
588        let (row, col) = self.position();
589        let start_pos = self.pos;
590
591        match self.peek() {
592            Some(b) if b.is_ascii_lowercase() => {
593                Ok(TypeName::Unqualified(self.lower_name(to_error)?))
594            }
595            Some(b) if b.is_ascii_uppercase() => {
596                self.advance();
597                self.chomp_inner_chars();
598
599                // Check for qualification
600                if self.is_dot_upper() {
601                    self.chomp_qualified_upper_for_type(start_pos)
602                } else if self.is_dot_lower() {
603                    // Can't have lowercase after dot for types
604                    Err(to_error(row, col))
605                } else {
606                    let name = self.slice_from(start_pos);
607                    Ok(TypeName::Unqualified(name))
608                }
609            }
610            _ => Err(to_error(row, col)),
611        }
612    }
613
614    /// Chomp through Module.Module... chain for type names.
615    fn chomp_qualified_upper_for_type<E>(&mut self, start_pos: usize) -> Result<TypeName<'a>, E> {
616        loop {
617            if self.is_dot_upper() {
618                self.advance(); // consume dot
619                self.advance(); // consume first uppercase char
620                self.chomp_inner_chars();
621            } else {
622                // No more dots - split into module and name
623                let full = self.slice_from(start_pos);
624                if let Some(last_dot) = full.rfind('.') {
625                    let module = &full[..last_dot];
626                    let name = &full[last_dot + 1..];
627                    return Ok(TypeName::Qualified(module, name));
628                } else {
629                    return Ok(TypeName::Unqualified(full));
630                }
631            }
632        }
633    }
634}
635
636// =============================================================================
637// Tests
638// =============================================================================
639
640#[cfg(test)]
641macro_rules! assert_type_snapshot {
642    ($code:expr) => {{
643        let bump = bumpalo::Bump::new();
644        let src = bump.alloc_str(indoc::indoc!($code));
645        let mut parser = $crate::Parser::new(&bump, src.as_bytes());
646        let (result, _end) = parser.type_expr().expect("expected successful parse");
647        parser.chomp(|_, _, _| ()).expect("expected trailing space");
648        assert!(parser.is_eof(), "type parser left trailing input");
649
650        insta::with_settings!({
651            description => format!("Code:\n\n{}", indoc::indoc!($code)),
652            omit_expression => true,
653        }, {
654            insta::assert_debug_snapshot!(result);
655        });
656    }};
657}
658
659#[cfg(test)]
660macro_rules! assert_type_error_snapshot {
661    ($code:expr) => {{
662        let bump = bumpalo::Bump::new();
663        let src = bump.alloc_str(indoc::indoc!($code));
664        let mut parser = $crate::Parser::new(&bump, src.as_bytes());
665        let result = parser.type_expr().expect_err("expected parse error");
666
667        insta::with_settings!({
668            description => format!("Code:\n\n{}", indoc::indoc!($code)),
669            omit_expression => true,
670        }, {
671            insta::assert_debug_snapshot!(result);
672        });
673    }};
674}
675
676#[cfg(test)]
677macro_rules! assert_scheme_snapshot {
678    ($code:expr) => {{
679        let bump = bumpalo::Bump::new();
680        let src = bump.alloc_str(indoc::indoc!($code));
681        let mut parser = $crate::Parser::new(&bump, src.as_bytes());
682        let (result, _end) = parser.type_scheme().expect("expected successful parse");
683        parser.chomp(|_, _, _| ()).expect("expected trailing space");
684        assert!(parser.is_eof(), "type scheme parser left trailing input");
685
686        insta::with_settings!({
687            description => format!("Code:\n\n{}", indoc::indoc!($code)),
688            omit_expression => true,
689        }, {
690            insta::assert_debug_snapshot!(result);
691        });
692    }};
693}
694
695#[cfg(test)]
696macro_rules! assert_scheme_error_snapshot {
697    ($code:expr) => {{
698        let bump = bumpalo::Bump::new();
699        let src = bump.alloc_str(indoc::indoc!($code));
700        let mut parser = $crate::Parser::new(&bump, src.as_bytes());
701        let result = parser.type_scheme().expect_err("expected parse error");
702
703        insta::with_settings!({
704            description => format!("Code:\n\n{}", indoc::indoc!($code)),
705            omit_expression => true,
706        }, {
707            insta::assert_debug_snapshot!(result);
708        });
709    }};
710}
711
712/// Snapshot test macro for multiline types, laid out as they would appear
713/// indented inside a declaration (see `test_support::indent_fragment`).
714#[cfg(test)]
715macro_rules! assert_indented_type_snapshot {
716    ($code:expr) => {{
717        let bump = bumpalo::Bump::new();
718        let fragment = indoc::indoc!($code);
719        let indented = $crate::test_support::indent_fragment(fragment);
720        let src = bump.alloc_str(&indented);
721        let mut parser = $crate::Parser::new(&bump, src.as_bytes());
722        parser
723            .chomp(|_, _, _| "space error")
724            .expect("expected leading indent");
725        let (result, _end) = parser.type_expr().expect("expected successful parse");
726        parser.chomp(|_, _, _| ()).expect("expected trailing space");
727        assert!(parser.is_eof(), "type parser left trailing input");
728
729        insta::with_settings!({
730            description => format!("Code (indented inside a declaration):\n\n{}", indented),
731            omit_expression => true,
732        }, {
733            insta::assert_debug_snapshot!(result);
734        });
735    }};
736}
737
738#[cfg(test)]
739mod tests {
740    #[test]
741    fn scheme_single_constraint() {
742        assert_scheme_snapshot!("Eq 'a => 'a -> 'a -> bool");
743    }
744
745    #[test]
746    fn scheme_tuple_constraints() {
747        assert_scheme_snapshot!("(Eq 'a, Show 'b) => 'a -> 'b -> string");
748    }
749
750    #[test]
751    fn scheme_multi_argument_constraint() {
752        assert_scheme_snapshot!("Lift 'small 'big => 'small -> 'big");
753    }
754
755    #[test]
756    fn scheme_qualified_constraint() {
757        assert_scheme_snapshot!("Cardano.Eq Datum => Datum -> bool");
758    }
759
760    #[test]
761    fn scheme_without_constraints() {
762        assert_scheme_snapshot!("'a -> 'a");
763    }
764
765    #[test]
766    fn scheme_error_variable_context() {
767        assert_scheme_error_snapshot!("'a => 'a");
768    }
769
770    #[test]
771    fn scheme_error_constraint_without_argument() {
772        assert_scheme_error_snapshot!("Eq => 'a");
773    }
774
775    #[test]
776    fn scheme_error_tuple_member() {
777        assert_scheme_error_snapshot!("(Eq 'a, 'b) => 'a");
778    }
779
780    #[test]
781    fn scheme_error_little_class() {
782        assert_scheme_error_snapshot!("int 'a => 'a");
783    }
784
785    // Type variables
786    #[test]
787    fn representation_annotation_rejects_arrow() {
788        assert_type_error_snapshot!("('f : Big -> Big)");
789    }
790
791    #[test]
792    fn inline_representation_annotation_in_nested_type() {
793        assert_type_snapshot!("list (pair ('a : Big) ('b : Storable))");
794    }
795
796    #[test]
797    fn inline_representation_annotation_reports_unknown_name() {
798        assert_type_error_snapshot!("list ('a : Wrong)");
799    }
800
801    #[test]
802    fn type_var_simple() {
803        assert_type_snapshot!("'a");
804    }
805
806    #[test]
807    fn type_var_msg() {
808        assert_type_snapshot!("'msg");
809    }
810
811    // Named types (no args)
812    #[test]
813    fn named_type_int() {
814        assert_type_snapshot!("Int");
815    }
816
817    #[test]
818    fn named_type_qualified() {
819        assert_type_snapshot!("Dict.Dict");
820    }
821
822    #[test]
823    fn named_type_multi_qualified() {
824        assert_type_snapshot!("Data.Map.Map");
825    }
826
827    // Type application
828    #[test]
829    fn type_app_maybe() {
830        assert_type_snapshot!("Maybe Int");
831    }
832
833    #[test]
834    fn type_app_result() {
835        assert_type_snapshot!("Result String Int");
836    }
837
838    #[test]
839    fn type_app_nested() {
840        assert_type_snapshot!("Maybe (List Int)");
841    }
842
843    #[test]
844    fn type_app_qualified() {
845        assert_type_snapshot!("Dict.Dict String Int");
846    }
847
848    // Function types
849    #[test]
850    fn function_simple() {
851        assert_type_snapshot!("'a -> 'b");
852    }
853
854    #[test]
855    fn function_multi() {
856        assert_type_snapshot!("'a -> 'b -> 'c");
857    }
858
859    #[test]
860    fn function_with_types() {
861        assert_type_snapshot!("Int -> String -> Bool");
862    }
863
864    #[test]
865    fn function_with_app() {
866        assert_type_snapshot!("Maybe 'a -> Result 'e 'a");
867    }
868
869    // Unit
870    #[test]
871    fn unit() {
872        assert_type_snapshot!("()");
873    }
874
875    // Tuple types
876    #[test]
877    fn tuple_pair() {
878        assert_type_snapshot!("(Int, String)");
879    }
880
881    #[test]
882    fn tuple_triple() {
883        assert_type_snapshot!("(Int, String, Bool)");
884    }
885
886    #[test]
887    fn tuple_nested() {
888        assert_type_snapshot!("((Int, String), Bool)");
889    }
890
891    #[test]
892    fn tuple_with_function() {
893        assert_type_snapshot!("('a -> 'b, 'c)");
894    }
895
896    #[test]
897    fn tuple_multiline() {
898        assert_indented_type_snapshot!(
899            "(
900                Int,
901                String,
902                Bool
903            )"
904        );
905    }
906
907    // Record types
908    #[test]
909    fn record_empty() {
910        assert_type_snapshot!("{}");
911    }
912
913    #[test]
914    fn record_single() {
915        assert_type_snapshot!("{ name : String }");
916    }
917
918    #[test]
919    fn record_multiple() {
920        assert_type_snapshot!("{ name : String, age : Int }");
921    }
922
923    #[test]
924    fn record_with_function() {
925        assert_type_snapshot!("{ onClick : 'msg -> Cmd 'msg }");
926    }
927
928    #[test]
929    fn record_multiline() {
930        assert_indented_type_snapshot!(
931            "{
932                name : String,
933                age : Int,
934                active : Bool
935            }"
936        );
937    }
938
939    // Parenthesized
940    #[test]
941    fn parenthesized() {
942        assert_type_snapshot!("(Int)");
943    }
944
945    #[test]
946    fn parenthesized_function() {
947        assert_type_snapshot!("('a -> 'b) -> List 'a -> List 'b");
948    }
949
950    // Complex combinations
951    #[test]
952    fn complex_model_msg() {
953        assert_type_snapshot!("{ model : Model, update : Msg -> Model -> Model }");
954    }
955
956    #[test]
957    fn little_type() {
958        assert_type_snapshot!("a");
959    }
960
961    #[test]
962    fn little_type_application() {
963        assert_type_snapshot!("list int");
964    }
965
966    #[test]
967    fn type_variable_application() {
968        assert_type_snapshot!("'f 'a");
969    }
970
971    #[test]
972    fn mixed_type_names() {
973        assert_type_snapshot!("option 'a -> 'a");
974        assert_type_snapshot!("Map 'k (List 'v)");
975        assert_type_snapshot!("{ x : int, y : Int }");
976    }
977
978    #[test]
979    fn error_empty_type_variable() {
980        assert_type_error_snapshot!("'");
981    }
982
983    #[test]
984    fn error_upper_type_variable() {
985        assert_type_error_snapshot!("'A");
986    }
987
988    #[test]
989    fn error_record_extension() {
990        assert_type_error_snapshot!("{ r | x : int }");
991    }
992}