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