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