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