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