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, Kind, 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.type_tuple_help(start, first)
322                }),
323            ],
324        )
325    }
326
327    /// Parse a type inside a tuple.
328    fn type_tuple_entry(&mut self) -> Result<(&'a Located<Type<'a>>, Position), TTuple<'a>> {
329        self.specialize(
330            |bump, type_err, row, col| TTuple::Type(bump.alloc(type_err), row, col),
331            |p| p.type_expr(),
332        )
333    }
334
335    /// Parse remaining tuple elements.
336    fn type_tuple_help(
337        &mut self,
338        start: Position,
339        first: &'a Located<Type<'a>>,
340    ) -> Result<&'a Located<Type<'a>>, TTuple<'a>> {
341        let mut rest: BumpVec<'a, &'a Located<Type<'a>>> = BumpVec::new_in(self.bump);
342
343        loop {
344            self.chomp(TTuple::Space)?;
345
346            let done = self.one_of(
347                TTuple::End,
348                vec![
349                    // Comma - another type
350                    Box::new(|p: &mut Parser<'a>| {
351                        p.word1(0x2C, TTuple::End)?; // ,
352                        p.chomp_and_check_indent(TTuple::Space, TTuple::IndentTypeN)?;
353
354                        let (tipe, end) = p.type_tuple_entry()?;
355                        rest.push(tipe);
356
357                        p.check_indent(end.line, end.column, TTuple::IndentEnd)?;
358                        Ok(false)
359                    }),
360                    // Close paren
361                    Box::new(|p: &mut Parser<'a>| {
362                        p.word1(0x29, TTuple::End)?; // )
363                        Ok(true)
364                    }),
365                ],
366            )?;
367
368            if done {
369                break;
370            }
371        }
372
373        if rest.is_empty() {
374            // Just parenthesized type
375            Ok(first)
376        } else {
377            // Tuple
378            let second = rest.remove(0);
379            let others = rest.into_bump_slice();
380            Ok(self.add_end(
381                start,
382                Type::Tuple {
383                    first,
384                    second,
385                    rest: others,
386                },
387            ))
388        }
389    }
390
391    // -------------------------------------------------------------------------
392    // Records
393    // -------------------------------------------------------------------------
394
395    /// Parse a record type: `{}`, `{ name : String }`
396    fn type_record(&mut self, start: Position) -> Result<&'a Located<Type<'a>>, error::Type<'a>> {
397        self.in_context(
398            |bump, record_err, row, col| error::Type::Record(bump.alloc(record_err), row, col),
399            |p| p.word1(0x7B, error::Type::Start), // {
400            |p| p.type_record_body(start),
401        )
402    }
403
404    /// Parse record type body after `{`.
405    fn type_record_body(&mut self, start: Position) -> Result<&'a Located<Type<'a>>, TRecord<'a>> {
406        self.chomp_and_check_indent(TRecord::Space, TRecord::IndentOpen)?;
407
408        self.one_of(
409            TRecord::Open,
410            vec![
411                // Empty record: `{}`
412                Box::new(|p: &mut Parser<'a>| {
413                    p.word1(0x7D, TRecord::Open)?; // }
414                    let empty: &'a [&'a FieldType<'a>] = &[];
415                    Ok(p.add_end(start, Type::Record(empty)))
416                }),
417                // Non-empty record
418                Box::new(|p: &mut Parser<'a>| {
419                    let field = p.type_record_field()?;
420                    let fields = p.type_record_end(field)?;
421                    Ok(p.add_end(start, Type::Record(fields)))
422                }),
423            ],
424        )
425    }
426
427    /// Parse a type inside a record field.
428    fn type_record_type_entry(&mut self) -> Result<(&'a Located<Type<'a>>, Position), TRecord<'a>> {
429        self.specialize(
430            |bump, type_err, row, col| TRecord::Type(bump.alloc(type_err), row, col),
431            |p| p.type_expr(),
432        )
433    }
434
435    /// Parse a record field: `name : Type`
436    fn type_record_field(&mut self) -> Result<&'a FieldType<'a>, TRecord<'a>> {
437        let name_start = self.get_position();
438        let name = self.lower_name(TRecord::Field)?;
439        let name_loc = self.add_end(name_start, name);
440
441        self.chomp_and_check_indent(TRecord::Space, TRecord::IndentColon)?;
442        self.word1(0x3A, TRecord::Colon)?; // :
443        self.chomp_and_check_indent(TRecord::Space, TRecord::IndentType)?;
444
445        let (tipe, end) = self.type_record_type_entry()?;
446        self.check_indent(end.line, end.column, TRecord::IndentEnd)?;
447
448        Ok(self.alloc(FieldType {
449            field: name_loc,
450            typ: tipe,
451        }))
452    }
453
454    /// Parse remaining record fields.
455    fn type_record_end(
456        &mut self,
457        first: &'a FieldType<'a>,
458    ) -> Result<&'a [&'a FieldType<'a>], TRecord<'a>> {
459        let mut fields: BumpVec<'a, &'a FieldType<'a>> = BumpVec::new_in(self.bump);
460        fields.push(first);
461
462        loop {
463            self.chomp(TRecord::Space)?;
464
465            let done = self.one_of(
466                TRecord::End,
467                vec![
468                    // Comma - another field
469                    Box::new(|p: &mut Parser<'a>| {
470                        p.word1(0x2C, TRecord::End)?; // ,
471                        p.chomp_and_check_indent(TRecord::Space, TRecord::IndentField)?;
472
473                        let field = p.type_record_field()?;
474                        fields.push(field);
475                        Ok(false)
476                    }),
477                    // Close brace
478                    Box::new(|p: &mut Parser<'a>| {
479                        p.word1(0x7D, TRecord::End)?; // }
480                        Ok(true)
481                    }),
482                ],
483            )?;
484
485            if done {
486                break;
487            }
488        }
489
490        Ok(fields.into_bump_slice())
491    }
492
493    /// Parse a declaration type parameter, with an optional kind annotation.
494    pub(crate) fn type_param(&mut self) -> Result<&'a TypeParam<'a>, error::TypeParam<'a>> {
495        let start = self.get_position();
496        self.one_of(
497            error::TypeParam::Start,
498            vec![
499                Box::new(|p: &mut Parser<'a>| {
500                    let name = p.type_var_name(error::TypeParam::Start)?;
501                    Ok(p.alloc(TypeParam {
502                        name: p.add_end(start, name),
503                        kind: None,
504                    }))
505                }),
506                Box::new(|p: &mut Parser<'a>| {
507                    p.word1(b'(', error::TypeParam::Start)?;
508                    p.chomp_and_check_indent(
509                        error::TypeParam::Space,
510                        error::TypeParam::IndentColon,
511                    )?;
512                    let name_start = p.get_position();
513                    let name = p.type_var_name(error::TypeParam::Start)?;
514                    let name = p.add_end(name_start, name);
515                    p.chomp_and_check_indent(
516                        error::TypeParam::Space,
517                        error::TypeParam::IndentColon,
518                    )?;
519                    p.word1(b':', error::TypeParam::Colon)?;
520                    p.chomp_and_check_indent(
521                        error::TypeParam::Space,
522                        error::TypeParam::IndentKind,
523                    )?;
524                    let (kind, end) = p.specialize(
525                        |bump, e, row, col| error::TypeParam::Kind(bump.alloc(e), row, col),
526                        |p| p.kind_expr(),
527                    )?;
528                    p.check_indent(end.line, end.column, error::TypeParam::IndentEnd)?;
529                    p.word1(b')', error::TypeParam::End)?;
530                    Ok(p.alloc(TypeParam {
531                        name,
532                        kind: Some(kind),
533                    }))
534                }),
535            ],
536        )
537    }
538
539    /// Parse a kind expression.
540    fn kind_expr(&mut self) -> Result<(&'a Located<Kind<'a>>, Position), error::Kind<'a>> {
541        let start = self.get_position();
542        let atom = self.kind_atom()?;
543        let end1 = self.get_position();
544        self.chomp(error::Kind::Space)?;
545        self.one_of_with_fallback(
546            vec![Box::new(|p: &mut Parser<'a>| {
547                p.check_indent(end1.line, end1.column, error::Kind::IndentStart)?;
548                p.word2(b'-', b'>', error::Kind::Start)?;
549                p.chomp_and_check_indent(error::Kind::Space, error::Kind::IndentStart)?;
550                let (to, end2) = p.kind_expr()?;
551                Ok((
552                    p.alloc(Located::at(
553                        Region::new(start, end2),
554                        Kind::Arrow { from: atom, to },
555                    )),
556                    end2,
557                ))
558            })],
559            (atom, end1),
560        )
561    }
562
563    /// Parse a base or parenthesized kind.
564    fn kind_atom(&mut self) -> Result<&'a Located<Kind<'a>>, error::Kind<'a>> {
565        let start = self.get_position();
566        self.one_of(
567            error::Kind::Start,
568            vec![
569                Box::new(|p: &mut Parser<'a>| {
570                    let (row, col) = p.position();
571                    let name = p.upper_name(error::Kind::Start)?;
572                    let kind = match name {
573                        "Big" => Kind::Big,
574                        "Const" => Kind::Const,
575                        "Term" => Kind::Term,
576                        "Storable" => Kind::Storable,
577                        other => return Err(error::Kind::Name(other, row, col)),
578                    };
579                    Ok(p.add_end(start, kind))
580                }),
581                Box::new(|p: &mut Parser<'a>| {
582                    p.in_context(
583                        |bump, e, row, col| error::Kind::Paren(bump.alloc(e), row, col),
584                        |p| p.word1(b'(', error::Kind::Start),
585                        |p| {
586                            p.chomp_and_check_indent(error::Kind::Space, error::Kind::IndentStart)?;
587                            let (kind, end) = p.kind_expr()?;
588                            p.check_indent(end.line, end.column, error::Kind::End)?;
589                            p.word1(b')', error::Kind::End)?;
590                            Ok(kind)
591                        },
592                    )
593                }),
594            ],
595        )
596    }
597
598    // -------------------------------------------------------------------------
599    // Helpers
600    // -------------------------------------------------------------------------
601
602    /// Parse a possibly-qualified uppercase name (for types).
603    ///
604    /// Mirrors Elm's `Var.foreignUpper`.
605    fn type_name<E>(&mut self, to_error: impl FnOnce(u16, u16) -> E) -> Result<TypeName<'a>, E> {
606        let (row, col) = self.position();
607        let start_pos = self.pos;
608
609        match self.peek() {
610            Some(b) if b.is_ascii_lowercase() => {
611                Ok(TypeName::Unqualified(self.lower_name(to_error)?))
612            }
613            Some(b) if b.is_ascii_uppercase() => {
614                self.advance();
615                self.chomp_inner_chars();
616
617                // Check for qualification
618                if self.is_dot_upper() {
619                    self.chomp_qualified_upper_for_type(start_pos)
620                } else if self.is_dot_lower() {
621                    // Can't have lowercase after dot for types
622                    Err(to_error(row, col))
623                } else {
624                    let name = self.slice_from(start_pos);
625                    Ok(TypeName::Unqualified(name))
626                }
627            }
628            _ => Err(to_error(row, col)),
629        }
630    }
631
632    /// Chomp through Module.Module... chain for type names.
633    fn chomp_qualified_upper_for_type<E>(&mut self, start_pos: usize) -> Result<TypeName<'a>, E> {
634        loop {
635            if self.is_dot_upper() {
636                self.advance(); // consume dot
637                self.advance(); // consume first uppercase char
638                self.chomp_inner_chars();
639            } else {
640                // No more dots - split into module and name
641                let full = self.slice_from(start_pos);
642                if let Some(last_dot) = full.rfind('.') {
643                    let module = &full[..last_dot];
644                    let name = &full[last_dot + 1..];
645                    return Ok(TypeName::Qualified(module, name));
646                } else {
647                    return Ok(TypeName::Unqualified(full));
648                }
649            }
650        }
651    }
652}
653
654// =============================================================================
655// Tests
656// =============================================================================
657
658#[cfg(test)]
659macro_rules! assert_type_snapshot {
660    ($code:expr) => {{
661        let bump = bumpalo::Bump::new();
662        let src = bump.alloc_str(indoc::indoc!($code));
663        let mut parser = $crate::Parser::new(&bump, src.as_bytes());
664        let (result, _end) = parser.type_expr().expect("expected successful parse");
665        parser.chomp(|_, _, _| ()).expect("expected trailing space");
666        assert!(parser.is_eof(), "type parser left trailing input");
667
668        insta::with_settings!({
669            description => format!("Code:\n\n{}", indoc::indoc!($code)),
670            omit_expression => true,
671        }, {
672            insta::assert_debug_snapshot!(result);
673        });
674    }};
675}
676
677#[cfg(test)]
678macro_rules! assert_type_error_snapshot {
679    ($code:expr) => {{
680        let bump = bumpalo::Bump::new();
681        let src = bump.alloc_str(indoc::indoc!($code));
682        let mut parser = $crate::Parser::new(&bump, src.as_bytes());
683        let result = parser.type_expr().expect_err("expected parse error");
684
685        insta::with_settings!({
686            description => format!("Code:\n\n{}", indoc::indoc!($code)),
687            omit_expression => true,
688        }, {
689            insta::assert_debug_snapshot!(result);
690        });
691    }};
692}
693
694#[cfg(test)]
695macro_rules! assert_scheme_snapshot {
696    ($code:expr) => {{
697        let bump = bumpalo::Bump::new();
698        let src = bump.alloc_str(indoc::indoc!($code));
699        let mut parser = $crate::Parser::new(&bump, src.as_bytes());
700        let (result, _end) = parser.type_scheme().expect("expected successful parse");
701        parser.chomp(|_, _, _| ()).expect("expected trailing space");
702        assert!(parser.is_eof(), "type scheme parser left trailing input");
703
704        insta::with_settings!({
705            description => format!("Code:\n\n{}", indoc::indoc!($code)),
706            omit_expression => true,
707        }, {
708            insta::assert_debug_snapshot!(result);
709        });
710    }};
711}
712
713#[cfg(test)]
714macro_rules! assert_scheme_error_snapshot {
715    ($code:expr) => {{
716        let bump = bumpalo::Bump::new();
717        let src = bump.alloc_str(indoc::indoc!($code));
718        let mut parser = $crate::Parser::new(&bump, src.as_bytes());
719        let result = parser.type_scheme().expect_err("expected parse error");
720
721        insta::with_settings!({
722            description => format!("Code:\n\n{}", indoc::indoc!($code)),
723            omit_expression => true,
724        }, {
725            insta::assert_debug_snapshot!(result);
726        });
727    }};
728}
729
730/// Snapshot test macro for multiline types, laid out as they would appear
731/// indented inside a declaration (see `test_support::indent_fragment`).
732#[cfg(test)]
733macro_rules! assert_indented_type_snapshot {
734    ($code:expr) => {{
735        let bump = bumpalo::Bump::new();
736        let fragment = indoc::indoc!($code);
737        let indented = $crate::test_support::indent_fragment(fragment);
738        let src = bump.alloc_str(&indented);
739        let mut parser = $crate::Parser::new(&bump, src.as_bytes());
740        parser
741            .chomp(|_, _, _| "space error")
742            .expect("expected leading indent");
743        let (result, _end) = parser.type_expr().expect("expected successful parse");
744        parser.chomp(|_, _, _| ()).expect("expected trailing space");
745        assert!(parser.is_eof(), "type parser left trailing input");
746
747        insta::with_settings!({
748            description => format!("Code (indented inside a declaration):\n\n{}", indented),
749            omit_expression => true,
750        }, {
751            insta::assert_debug_snapshot!(result);
752        });
753    }};
754}
755
756#[cfg(test)]
757mod tests {
758    #[test]
759    fn scheme_single_constraint() {
760        assert_scheme_snapshot!("Eq 'a => 'a -> 'a -> bool");
761    }
762
763    #[test]
764    fn scheme_tuple_constraints() {
765        assert_scheme_snapshot!("(Eq 'a, Show 'b) => 'a -> 'b -> string");
766    }
767
768    #[test]
769    fn scheme_multi_argument_constraint() {
770        assert_scheme_snapshot!("Lift 'small 'big => 'small -> 'big");
771    }
772
773    #[test]
774    fn scheme_qualified_constraint() {
775        assert_scheme_snapshot!("Cardano.Eq Datum => Datum -> bool");
776    }
777
778    #[test]
779    fn scheme_without_constraints() {
780        assert_scheme_snapshot!("'a -> 'a");
781    }
782
783    #[test]
784    fn scheme_error_variable_context() {
785        assert_scheme_error_snapshot!("'a => 'a");
786    }
787
788    #[test]
789    fn scheme_error_constraint_without_argument() {
790        assert_scheme_error_snapshot!("Eq => 'a");
791    }
792
793    #[test]
794    fn scheme_error_tuple_member() {
795        assert_scheme_error_snapshot!("(Eq 'a, 'b) => 'a");
796    }
797
798    #[test]
799    fn scheme_error_little_class() {
800        assert_scheme_error_snapshot!("int 'a => 'a");
801    }
802
803    // Type variables
804    #[test]
805    fn type_var_simple() {
806        assert_type_snapshot!("'a");
807    }
808
809    #[test]
810    fn type_var_msg() {
811        assert_type_snapshot!("'msg");
812    }
813
814    // Named types (no args)
815    #[test]
816    fn named_type_int() {
817        assert_type_snapshot!("Int");
818    }
819
820    #[test]
821    fn named_type_string() {
822        assert_type_snapshot!("String");
823    }
824
825    #[test]
826    fn named_type_qualified() {
827        assert_type_snapshot!("Dict.Dict");
828    }
829
830    #[test]
831    fn named_type_multi_qualified() {
832        assert_type_snapshot!("Data.Map.Map");
833    }
834
835    // Type application
836    #[test]
837    fn type_app_maybe() {
838        assert_type_snapshot!("Maybe Int");
839    }
840
841    #[test]
842    fn type_app_result() {
843        assert_type_snapshot!("Result String Int");
844    }
845
846    #[test]
847    fn type_app_nested() {
848        assert_type_snapshot!("Maybe (List Int)");
849    }
850
851    #[test]
852    fn type_app_qualified() {
853        assert_type_snapshot!("Dict.Dict String Int");
854    }
855
856    // Function types
857    #[test]
858    fn function_simple() {
859        assert_type_snapshot!("'a -> 'b");
860    }
861
862    #[test]
863    fn function_multi() {
864        assert_type_snapshot!("'a -> 'b -> 'c");
865    }
866
867    #[test]
868    fn function_with_types() {
869        assert_type_snapshot!("Int -> String -> Bool");
870    }
871
872    #[test]
873    fn function_with_app() {
874        assert_type_snapshot!("Maybe 'a -> Result 'e 'a");
875    }
876
877    // Unit
878    #[test]
879    fn unit() {
880        assert_type_snapshot!("()");
881    }
882
883    // Tuple types
884    #[test]
885    fn tuple_pair() {
886        assert_type_snapshot!("(Int, String)");
887    }
888
889    #[test]
890    fn tuple_triple() {
891        assert_type_snapshot!("(Int, String, Bool)");
892    }
893
894    #[test]
895    fn tuple_nested() {
896        assert_type_snapshot!("((Int, String), Bool)");
897    }
898
899    #[test]
900    fn tuple_with_function() {
901        assert_type_snapshot!("('a -> 'b, 'c)");
902    }
903
904    #[test]
905    fn tuple_multiline() {
906        assert_indented_type_snapshot!(
907            "(
908                Int,
909                String,
910                Bool
911            )"
912        );
913    }
914
915    // Record types
916    #[test]
917    fn record_empty() {
918        assert_type_snapshot!("{}");
919    }
920
921    #[test]
922    fn record_single() {
923        assert_type_snapshot!("{ name : String }");
924    }
925
926    #[test]
927    fn record_multiple() {
928        assert_type_snapshot!("{ name : String, age : Int }");
929    }
930
931    #[test]
932    fn record_with_function() {
933        assert_type_snapshot!("{ onClick : 'msg -> Cmd 'msg }");
934    }
935
936    #[test]
937    fn record_multiline() {
938        assert_indented_type_snapshot!(
939            "{
940                name : String,
941                age : Int,
942                active : Bool
943            }"
944        );
945    }
946
947    // Parenthesized
948    #[test]
949    fn parenthesized() {
950        assert_type_snapshot!("(Int)");
951    }
952
953    #[test]
954    fn parenthesized_function() {
955        assert_type_snapshot!("('a -> 'b) -> List 'a -> List 'b");
956    }
957
958    // Complex combinations
959    #[test]
960    fn complex_model_msg() {
961        assert_type_snapshot!("{ model : Model, update : Msg -> Model -> Model }");
962    }
963
964    #[test]
965    fn little_type() {
966        assert_type_snapshot!("a");
967    }
968
969    #[test]
970    fn little_type_application() {
971        assert_type_snapshot!("list int");
972    }
973
974    #[test]
975    fn type_variable_application() {
976        assert_type_snapshot!("'f 'a");
977    }
978
979    #[test]
980    fn mixed_type_names() {
981        assert_type_snapshot!("option 'a -> 'a");
982        assert_type_snapshot!("Map 'k (List 'v)");
983        assert_type_snapshot!("{ x : int, y : Int }");
984    }
985
986    #[test]
987    fn error_empty_type_variable() {
988        assert_type_error_snapshot!("'");
989    }
990
991    #[test]
992    fn error_upper_type_variable() {
993        assert_type_error_snapshot!("'A");
994    }
995
996    #[test]
997    fn error_record_extension() {
998        assert_type_error_snapshot!("{ r | x : int }");
999    }
1000}