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 = nash_parse::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                info => &"diagnostic",
691        }, {
692            insta::assert_snapshot!($crate::test_support::render_type_error(src, &result));
693        });
694    }};
695}
696
697#[cfg(test)]
698macro_rules! assert_scheme_snapshot {
699    ($code:expr) => {{
700        let bump = bumpalo::Bump::new();
701        let src = bump.alloc_str(indoc::indoc!($code));
702        let mut parser = $crate::Parser::new(&bump, src);
703        let (result, _end) = parser.type_scheme().expect("expected successful parse");
704        parser.chomp(|_, _, _| ()).expect("expected trailing space");
705        assert!(parser.is_eof(), "type scheme parser left trailing input");
706
707        insta::with_settings!({
708            description => format!("Code:\n\n{}", indoc::indoc!($code)),
709            omit_expression => true,
710        }, {
711            insta::assert_debug_snapshot!(result);
712        });
713    }};
714}
715
716#[cfg(test)]
717macro_rules! assert_scheme_error_snapshot {
718    ($code:expr) => {{
719        let bump = bumpalo::Bump::new();
720        let src = bump.alloc_str(indoc::indoc!($code));
721        let mut parser = nash_parse::Parser::new(&bump, src);
722        let result = parser.type_scheme().expect_err("expected parse error");
723
724        insta::with_settings!({
725            description => format!("Code:\n\n{}", indoc::indoc!($code)),
726            omit_expression => true,
727                info => &"diagnostic",
728        }, {
729            insta::assert_snapshot!($crate::test_support::render_type_error(src, &result));
730        });
731    }};
732}
733
734/// Snapshot test macro for multiline types, laid out as they would appear
735/// indented inside a declaration (see `test_support::indent_fragment`).
736#[cfg(test)]
737macro_rules! assert_indented_type_snapshot {
738    ($code:expr) => {{
739        let bump = bumpalo::Bump::new();
740        let fragment = indoc::indoc!($code);
741        let indented = $crate::test_support::indent_fragment(fragment);
742        let src = bump.alloc_str(&indented);
743        let mut parser = $crate::Parser::new(&bump, src);
744        parser
745            .chomp(|_, _, _| "space error")
746            .expect("expected leading indent");
747        let (result, _end) = parser.type_expr().expect("expected successful parse");
748        parser.chomp(|_, _, _| ()).expect("expected trailing space");
749        assert!(parser.is_eof(), "type parser left trailing input");
750
751        insta::with_settings!({
752            description => format!("Code (indented inside a declaration):\n\n{}", indented),
753            omit_expression => true,
754        }, {
755            insta::assert_debug_snapshot!(result);
756        });
757    }};
758}
759
760#[cfg(test)]
761mod tests {
762    #[test]
763    fn scheme_single_constraint() {
764        assert_scheme_snapshot!("Eq 'a => 'a -> 'a -> bool");
765    }
766
767    #[test]
768    fn scheme_tuple_constraints() {
769        assert_scheme_snapshot!("(Eq 'a, Show 'b) => 'a -> 'b -> string");
770    }
771
772    #[test]
773    fn scheme_multi_argument_constraint() {
774        assert_scheme_snapshot!("Lift 'small 'big => 'small -> 'big");
775    }
776
777    #[test]
778    fn scheme_qualified_constraint() {
779        assert_scheme_snapshot!("Cardano.Eq Datum => Datum -> bool");
780    }
781
782    #[test]
783    fn scheme_without_constraints() {
784        assert_scheme_snapshot!("'a -> 'a");
785    }
786
787    #[test]
788    fn scheme_error_variable_context() {
789        assert_scheme_error_snapshot!("'a => 'a");
790    }
791
792    #[test]
793    fn scheme_error_constraint_without_argument() {
794        assert_scheme_error_snapshot!("Eq => 'a");
795    }
796
797    #[test]
798    fn scheme_error_tuple_member() {
799        assert_scheme_error_snapshot!("(Eq 'a, 'b) => 'a");
800    }
801
802    #[test]
803    fn scheme_error_little_class() {
804        assert_scheme_error_snapshot!("int 'a => 'a");
805    }
806
807    // Type variables
808    #[test]
809    fn representation_annotation_rejects_arrow() {
810        assert_type_error_snapshot!("('f : Big -> Big)");
811    }
812
813    #[test]
814    fn inline_representation_annotation_in_nested_type() {
815        assert_type_snapshot!("list (pair ('a : Big) ('b : Storable))");
816    }
817
818    #[test]
819    fn inline_representation_annotation_reports_unknown_name() {
820        assert_type_error_snapshot!("list ('a : Wrong)");
821    }
822
823    #[test]
824    fn type_var_simple() {
825        assert_type_snapshot!("'a");
826    }
827
828    #[test]
829    fn type_var_msg() {
830        assert_type_snapshot!("'msg");
831    }
832
833    // Named types (no args)
834    #[test]
835    fn named_type_int() {
836        assert_type_snapshot!("Int");
837    }
838
839    #[test]
840    fn named_type_qualified() {
841        assert_type_snapshot!("Dict.Dict");
842    }
843
844    #[test]
845    fn named_type_qualified_little() {
846        assert_type_snapshot!("Types.point");
847    }
848
849    #[test]
850    fn named_type_multi_qualified_little() {
851        assert_type_snapshot!("Some.Types.box 'a");
852    }
853
854    #[test]
855    fn named_type_multi_qualified() {
856        assert_type_snapshot!("Data.Map.Map");
857    }
858
859    // Type application
860    #[test]
861    fn type_app_maybe() {
862        assert_type_snapshot!("Maybe Int");
863    }
864
865    #[test]
866    fn type_app_result() {
867        assert_type_snapshot!("Result String Int");
868    }
869
870    #[test]
871    fn type_app_nested() {
872        assert_type_snapshot!("Maybe (List Int)");
873    }
874
875    #[test]
876    fn type_app_qualified() {
877        assert_type_snapshot!("Dict.Dict String Int");
878    }
879
880    // Function types
881    #[test]
882    fn function_simple() {
883        assert_type_snapshot!("'a -> 'b");
884    }
885
886    #[test]
887    fn function_multi() {
888        assert_type_snapshot!("'a -> 'b -> 'c");
889    }
890
891    #[test]
892    fn function_with_types() {
893        assert_type_snapshot!("Int -> String -> Bool");
894    }
895
896    #[test]
897    fn function_with_app() {
898        assert_type_snapshot!("Maybe 'a -> Result 'e 'a");
899    }
900
901    // Unit
902    #[test]
903    fn unit() {
904        assert_type_snapshot!("()");
905    }
906
907    // Tuple types
908    #[test]
909    fn tuple_pair() {
910        assert_type_snapshot!("(Int, String)");
911    }
912
913    #[test]
914    fn tuple_triple() {
915        assert_type_snapshot!("(Int, String, Bool)");
916    }
917
918    #[test]
919    fn tuple_nested() {
920        assert_type_snapshot!("((Int, String), Bool)");
921    }
922
923    #[test]
924    fn tuple_with_function() {
925        assert_type_snapshot!("('a -> 'b, 'c)");
926    }
927
928    #[test]
929    fn tuple_multiline() {
930        assert_indented_type_snapshot!(
931            "(
932                Int,
933                String,
934                Bool
935            )"
936        );
937    }
938
939    // Record types
940    #[test]
941    fn record_empty() {
942        assert_type_snapshot!("{}");
943    }
944
945    #[test]
946    fn record_single() {
947        assert_type_snapshot!("{ name : String }");
948    }
949
950    #[test]
951    fn record_multiple() {
952        assert_type_snapshot!("{ name : String, age : Int }");
953    }
954
955    #[test]
956    fn record_with_function() {
957        assert_type_snapshot!("{ onClick : 'msg -> Cmd 'msg }");
958    }
959
960    #[test]
961    fn record_multiline() {
962        assert_indented_type_snapshot!(
963            "{
964                name : String,
965                age : Int,
966                active : Bool
967            }"
968        );
969    }
970
971    // Parenthesized
972    #[test]
973    fn parenthesized() {
974        assert_type_snapshot!("(Int)");
975    }
976
977    #[test]
978    fn parenthesized_function() {
979        assert_type_snapshot!("('a -> 'b) -> List 'a -> List 'b");
980    }
981
982    // Complex combinations
983    #[test]
984    fn complex_model_msg() {
985        assert_type_snapshot!("{ model : Model, update : Msg -> Model -> Model }");
986    }
987
988    #[test]
989    fn little_type() {
990        assert_type_snapshot!("a");
991    }
992
993    #[test]
994    fn little_type_application() {
995        assert_type_snapshot!("list int");
996    }
997
998    #[test]
999    fn type_variable_application() {
1000        assert_type_snapshot!("'f 'a");
1001    }
1002
1003    #[test]
1004    fn mixed_type_names() {
1005        assert_type_snapshot!("option 'a -> 'a");
1006        assert_type_snapshot!("Map 'k (List 'v)");
1007        assert_type_snapshot!("{ x : int, y : Int }");
1008    }
1009
1010    #[test]
1011    fn error_empty_type_variable() {
1012        assert_type_error_snapshot!("'");
1013    }
1014
1015    #[test]
1016    fn error_upper_type_variable() {
1017        assert_type_error_snapshot!("'A");
1018    }
1019
1020    #[test]
1021    fn error_record_extension() {
1022        assert_type_error_snapshot!("{ r | x : int }");
1023    }
1024}