Skip to main content

constructo_runtime/
parser.rs

1//! A recursive-descent parser for types files and values files.
2//!
3//! It is the parser of `constructo check`. Generated code reads values through `codec::parse`, which uses it, and
4//! does not parse types files.
5//!
6//! The parser stops at the first syntax error: there is no error recovery.
7
8use crate::ast::{
9    Argument, ConstDecl, EnumDecl, Field, Member, Parameter, TaggedBody, Type, TypeParam, TypesFile, Value, ValueKind,
10    Variant, VariantBody,
11};
12use crate::diagnostics::{shown, Pos};
13use crate::lexer::{lex, Tok, Token};
14use crate::limits::MAX_DEPTH;
15
16/// The first syntax error found in a text.
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct SyntaxError {
19    /// Where the error was found.
20    pub pos: Pos,
21    /// What the error is.
22    pub message: String,
23    /// The enum or const being parsed when the error occurred, if its name had been read, e.g. `enum Shape`.
24    pub context: Option<String>,
25}
26
27type Result<T> = std::result::Result<T, SyntaxError>;
28
29/// The kind of a file, which is decided by its first token.
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub enum SourceKind {
32    /// A types file, which declares enums and consts.
33    Types,
34    /// A values file, which holds data values.
35    Values,
36}
37
38impl SourceKind {
39    /// The name used for the kind in messages.
40    pub fn label(self) -> &'static str {
41        match self {
42            SourceKind::Types => "data-types",
43            SourceKind::Values => "data-values",
44        }
45    }
46}
47
48/// The contents of a successfully parsed file.
49#[derive(Debug, Clone, PartialEq, Eq)]
50pub enum Parsed {
51    /// The declarations of a types file.
52    Types(TypesFile),
53    /// The values of a values file, in order.
54    Values(Vec<Value>),
55}
56
57/// The experimental features of the syntax, each of which has to be switched on to be accepted.
58#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
59pub struct Experimental {
60    /// The postfix `?` on a value, which is shorthand for `Some`.
61    pub some_query: bool,
62}
63
64impl Experimental {
65    /// Every experimental feature switched on.
66    pub fn all() -> Experimental {
67        Experimental { some_query: true }
68    }
69}
70
71/// Parses the text of a types file into its declarations, with no experimental features.
72pub fn parse(text: &str) -> Result<TypesFile> {
73    Parser::new(text, Experimental::default()).types()
74}
75
76/// Parses the text of a values file into its values, with no experimental features.
77pub fn parse_values(text: &str) -> Result<Vec<Value>> {
78    parse_values_with(text, Experimental::default())
79}
80
81/// Parses the text of a values file into its values, accepting the experimental features that are switched on.
82pub fn parse_values_with(text: &str, experimental: Experimental) -> Result<Vec<Value>> {
83    Parser::new(text, experimental).values()
84}
85
86/// Classifies a file by its first token and parses it with the matching grammar.
87///
88/// A types file always starts with `enum` or `const` and a values file starts with one only as a part of a qualifier,
89/// as in `const::Circle`. A file with no tokens is treated as a types file, which is how it was handled before values
90/// files were supported. The kind is returned even when parsing fails.
91pub fn parse_file(text: &str, experimental: Experimental) -> (SourceKind, Result<Parsed>) {
92    let mut parser = Parser::new(text, experimental);
93    let kind = match parser.peek() {
94        Tok::Enum | Tok::Const if !parser.at_qualifier() => SourceKind::Types,
95        Tok::Eof => SourceKind::Types,
96        _ => SourceKind::Values,
97    };
98    let parsed = match kind {
99        SourceKind::Types => parser.types().map(Parsed::Types),
100        SourceKind::Values => parser.values().map(Parsed::Values),
101    };
102    (kind, parsed)
103}
104
105struct Parser {
106    tokens: Vec<Token>,
107    index: usize,
108    context: Option<String>,
109    depth: u32,
110    /// The height of the tallest of the children that have been parsed so far for the construct being parsed.
111    tallest: u32,
112    /// The number of postfix `?` that have been parsed so far for the construct being parsed. Each one adds a level.
113    wrapped: u32,
114    experimental: Experimental,
115}
116
117impl Parser {
118    fn new(text: &str, experimental: Experimental) -> Parser {
119        Parser {
120            tokens: lex(text),
121            index: 0,
122            context: None,
123            depth: 0,
124            tallest: 0,
125            wrapped: 0,
126            experimental,
127        }
128    }
129
130    fn types(&mut self) -> Result<TypesFile> {
131        let mut file = TypesFile::default();
132        while self.peek() != &Tok::Eof {
133            // Errors before the name has been read are not attributed to the previous declaration.
134            self.context = None;
135            match self.peek() {
136                Tok::Const => file.consts.push(self.const_decl()?),
137                Tok::Enum => file.enums.push(self.enum_decl()?),
138                _ => return self.error("'enum' or 'const'"),
139            }
140        }
141        Ok(file)
142    }
143
144    /// Runs a parser for a nested construct. The limit is a defensive check: the parser is recursive, so without it
145    /// deeply nested input would overflow the stack and crash instead of being reported as a syntax error.
146    ///
147    /// The limit is on the height of the tree as well as on the depth of the calls. A postfix `?` adds a level to the
148    /// tree without a call, so the height of a construct is worked out from its children and its `?`, and is passed up
149    /// to the construct that contains it.
150    fn nested<T>(&mut self, parse: impl FnOnce(&mut Self) -> Result<T>) -> Result<T> {
151        if self.depth >= MAX_DEPTH {
152            return Err(self.too_deep());
153        }
154        self.depth += 1;
155        let outer = (std::mem::take(&mut self.tallest), std::mem::take(&mut self.wrapped));
156        let result = parse(self);
157        let height = self.tallest + 1 + self.wrapped;
158        (self.tallest, self.wrapped) = outer;
159        self.depth -= 1;
160        if result.is_ok() && height > MAX_DEPTH {
161            return Err(self.too_deep());
162        }
163        self.tallest = self.tallest.max(height);
164        result
165    }
166
167    fn too_deep(&self) -> SyntaxError {
168        SyntaxError {
169            pos: self.pos(),
170            message: "Nesting is too deep".to_string(),
171            context: self.context.clone(),
172        }
173    }
174
175    fn peek(&self) -> &Tok {
176        &self.tokens[self.index].tok
177    }
178
179    fn pos(&self) -> Pos {
180        self.tokens[self.index].pos
181    }
182
183    /// Advances past the current token. The final `Eof` token is never consumed.
184    fn bump(&mut self) {
185        if self.index + 1 < self.tokens.len() {
186            self.index += 1;
187        }
188    }
189
190    fn error<T>(&self, expected: &str) -> Result<T> {
191        let message = match self.peek() {
192            Tok::Invalid(c) => format!("Unexpected character '{}'", shown(&c.to_string())),
193            Tok::Error(message) => message.clone(),
194            _ => format!("Expected {}", expected),
195        };
196        Err(SyntaxError {
197            pos: self.pos(),
198            message,
199            context: self.context.clone(),
200        })
201    }
202
203    fn expect(&mut self, tok: Tok, expected: &str) -> Result<()> {
204        if self.peek() == &tok {
205            self.bump();
206            Ok(())
207        } else {
208            self.error(expected)
209        }
210    }
211
212    fn type_name(&mut self, expected: &str) -> Result<(String, Pos)> {
213        if let Tok::TypeName(name) = self.peek() {
214            let result = (name.clone(), self.pos());
215            self.bump();
216            Ok(result)
217        } else {
218            self.error(expected)
219        }
220    }
221
222    /// The text of a token that can be a part of a qualifier. The keywords are allowed, so `acme.const::X` is a
223    /// qualified name. A keyword is a part only if a dot or `::` follows it, which the callers check.
224    fn qualifier_part(tok: &Tok) -> Option<&str> {
225        match tok {
226            Tok::Name(part) | Tok::TypeName(part) => Some(part),
227            Tok::Enum => Some("enum"),
228            Tok::Const => Some("const"),
229            _ => None,
230        }
231    }
232
233    /// Whether the tokens from the current one are a qualifier: names separated by dots and ending in `::`, as in
234    /// `bundle::` or `acme.shapes::`. The parts may be keywords.
235    fn at_qualifier(&self) -> bool {
236        let mut i = self.index;
237        loop {
238            if Self::qualifier_part(&self.tokens[i].tok).is_none() {
239                return false;
240            }
241            // The final token is `Eof`, which is neither a name nor a dot, so this never runs off the end.
242            match self.tokens[i + 1].tok {
243                Tok::Dot => i += 2,
244                Tok::ColonColon => return true,
245                _ => return false,
246            }
247        }
248    }
249
250    /// Consumes a qualifier that the caller has checked is there, and returns it with the `::`, as `acme.shapes::`.
251    fn qualifier(&mut self) -> String {
252        let mut text = String::new();
253        loop {
254            match Self::qualifier_part(self.peek()) {
255                Some(part) => text.push_str(part),
256                None => unreachable!("at_qualifier has checked the tokens"),
257            }
258            self.bump();
259            if self.peek() == &Tok::Dot {
260                text.push('.');
261                self.bump();
262            } else {
263                self.bump();
264                text.push_str("::");
265                return text;
266            }
267        }
268    }
269
270    fn enum_decl(&mut self) -> Result<EnumDecl> {
271        self.expect(Tok::Enum, "'enum'")?;
272        let (name, pos) = self.type_name("type name")?;
273        self.context = Some(format!("enum {}", name));
274        let params = if self.peek() == &Tok::Lt {
275            self.type_params()?
276        } else {
277            Vec::new()
278        };
279        self.expect(Tok::Eq, "'='")?;
280        let mut variants = vec![self.variant()?];
281        loop {
282            match self.peek() {
283                Tok::Comma => {
284                    self.bump();
285                    // A trailing comma is allowed before the semi-colon.
286                    if self.peek() == &Tok::Semi {
287                        break;
288                    }
289                    variants.push(self.variant()?);
290                }
291                Tok::Semi => break,
292                _ => return self.error("comma or semi-colon"),
293            }
294        }
295        self.expect(Tok::Semi, "semi-colon")?;
296        Ok(EnumDecl {
297            name,
298            pos,
299            params,
300            variants,
301        })
302    }
303
304    /// `const name<Params>: Type = value;` The name starts with a lower-case letter or `_`.
305    fn const_decl(&mut self) -> Result<ConstDecl> {
306        self.expect(Tok::Const, "'const'")?;
307        let pos = self.pos();
308        // A const name starts with a lower-case letter or `_`, so that in a value it cannot be taken for a constructor,
309        // whose name starts with a capital letter (decision 35).
310        let name = match self.peek() {
311            Tok::Name(name) => name.clone(),
312            Tok::TypeName(_) => return self.error("const name that starts with a lower-case letter"),
313            _ => return self.error("const name"),
314        };
315        self.bump();
316        self.context = Some(format!("const {}", name));
317        let params = if self.peek() == &Tok::Lt {
318            self.type_params()?
319        } else {
320            Vec::new()
321        };
322        // The type is optional, and is inferred from the value if it is left out.
323        let ty = if self.peek() == &Tok::Colon {
324            self.bump();
325            Some(self.ty()?)
326        } else {
327            None
328        };
329        self.expect(Tok::Eq, if ty.is_some() { "'='" } else { "':' or '='" })?;
330        let value = self.value()?;
331        self.expect(Tok::Semi, "semi-colon")?;
332        Ok(ConstDecl {
333            name,
334            pos,
335            params,
336            ty,
337            value,
338        })
339    }
340
341    fn type_params(&mut self) -> Result<Vec<TypeParam>> {
342        self.expect(Tok::Lt, "'<'")?;
343        let mut params = Vec::new();
344        loop {
345            params.push(self.type_param()?);
346            match self.peek() {
347                Tok::Comma => self.bump(),
348                Tok::Gt => break,
349                _ => return self.error("comma or '>'"),
350            }
351        }
352        self.expect(Tok::Gt, "'>'")?;
353        Ok(params)
354    }
355
356    /// A type parameter is a type name, optionally preceded by an underscore.
357    fn type_param(&mut self) -> Result<TypeParam> {
358        let pos = self.pos();
359        match self.peek() {
360            Tok::TypeName(name) => {
361                let name = name.clone();
362                self.bump();
363                Ok(TypeParam {
364                    name,
365                    pos,
366                    underscore: false,
367                })
368            }
369            Tok::Name(name) if name.chars().nth(1).is_some_and(|c| c.is_ascii_uppercase()) && name.starts_with('_') => {
370                let name = name.clone();
371                self.bump();
372                Ok(TypeParam {
373                    name,
374                    pos,
375                    underscore: true,
376                })
377            }
378            _ => self.error("type parameter name"),
379        }
380    }
381
382    fn variant(&mut self) -> Result<Variant> {
383        let (name, pos) = self.type_name("constructor name")?;
384        let body = match self.peek() {
385            Tok::LBrace => VariantBody::Record(self.record_body()?),
386            Tok::LParen => VariantBody::Tuple(self.tuple_body()?),
387            Tok::LBracket => VariantBody::Array(self.array_body()?),
388            _ => VariantBody::Unit,
389        };
390        Ok(Variant { name, pos, body })
391    }
392
393    /// The element type in the brackets of a variant such as `Users[User]`. There is exactly one.
394    fn array_body(&mut self) -> Result<Type> {
395        self.expect(Tok::LBracket, "'['")?;
396        let element = self.ty()?;
397        if self.peek() == &Tok::Comma {
398            return self.error("']' because an array variant has exactly one element type");
399        }
400        self.expect(Tok::RBracket, "']'")?;
401        Ok(element)
402    }
403
404    fn record_body(&mut self) -> Result<Vec<Field>> {
405        self.expect(Tok::LBrace, "'{'")?;
406        let mut fields = Vec::new();
407        while self.peek() != &Tok::RBrace {
408            let pos = self.pos();
409            let name = match self.peek() {
410                Tok::Name(name) => name.clone(),
411                _ => return self.error("field name"),
412            };
413            self.bump();
414            self.expect(Tok::Colon, "':'")?;
415            let ty = self.ty()?;
416            fields.push(Field { name, pos, ty });
417            match self.peek() {
418                Tok::Comma => self.bump(),
419                Tok::RBrace => {}
420                _ => return self.error("comma or '}'"),
421            }
422        }
423        self.expect(Tok::RBrace, "'}'")?;
424        Ok(fields)
425    }
426
427    /// Parses the parameters of a tuple constructor. A parameter may be preceded by its name, but once one has been
428    /// named all the later ones must be too.
429    fn tuple_body(&mut self) -> Result<Vec<Parameter>> {
430        self.expect(Tok::LParen, "'('")?;
431        let mut params: Vec<Parameter> = Vec::new();
432        while self.peek() != &Tok::RParen {
433            let pos = self.pos();
434            // A name begins a qualified type if it is followed by `::`, or by dots and then `::`.
435            let name = match self.peek() {
436                Tok::Name(name) if !self.at_qualifier() => {
437                    let name = name.clone();
438                    self.bump();
439                    self.expect(Tok::Colon, "':'")?;
440                    Some(name)
441                }
442                _ => None,
443            };
444            if name.is_none() && params.last().is_some_and(|p| p.name.is_some()) {
445                return Err(SyntaxError {
446                    pos,
447                    message: "Unnamed parameter after a named parameter".to_string(),
448                    context: self.context.clone(),
449                });
450            }
451            let ty = self.ty()?;
452            params.push(Parameter { name, pos, ty });
453            match self.peek() {
454                Tok::Comma => self.bump(),
455                Tok::RParen => {}
456                _ => return self.error("comma or ')'"),
457            }
458        }
459        self.expect(Tok::RParen, "')'")?;
460        Ok(params)
461    }
462
463    fn ty(&mut self) -> Result<Type> {
464        self.nested(Self::ty_unchecked)
465    }
466
467    /// Parses a type and then any postfix `?`, each of which makes the type optional.
468    fn ty_unchecked(&mut self) -> Result<Type> {
469        let pos = self.pos();
470        let mut ty = self.primary_type()?;
471        while self.peek() == &Tok::Question {
472            self.question()?;
473            ty = Type::Ref {
474                name: "Option".to_string(),
475                pos,
476                args: vec![ty],
477            };
478        }
479        Ok(ty)
480    }
481
482    /// Consumes a postfix `?`. Each one wraps what it follows and so adds a level to the tree, which has to be counted
483    /// at once because a long run of them would otherwise build a tree that is too tall before anything notices.
484    fn question(&mut self) -> Result<()> {
485        self.bump();
486        self.wrapped += 1;
487        if self.tallest + 1 + self.wrapped > MAX_DEPTH {
488            return Err(self.too_deep());
489        }
490        Ok(())
491    }
492
493    fn primary_type(&mut self) -> Result<Type> {
494        match self.peek() {
495            Tok::TypeName(_) | Tok::Name(_) | Tok::Enum | Tok::Const
496                if self.at_qualifier() || matches!(self.peek(), Tok::TypeName(_)) =>
497            {
498                let pos = self.pos();
499                let qualifier = if self.at_qualifier() {
500                    self.qualifier()
501                } else {
502                    String::new()
503                };
504                let (name, _) = self.type_name("type")?;
505                let name = format!("{}{}", qualifier, name);
506                let mut args = Vec::new();
507                if self.peek() == &Tok::Lt {
508                    self.bump();
509                    loop {
510                        args.push(self.ty()?);
511                        match self.peek() {
512                            Tok::Comma => self.bump(),
513                            Tok::Gt => break,
514                            _ => return self.error("comma or '>'"),
515                        }
516                    }
517                    self.expect(Tok::Gt, "'>'")?;
518                }
519                Ok(Type::Ref { name, pos, args })
520            }
521            Tok::LBracket => {
522                self.bump();
523                let element = self.ty()?;
524                self.expect(Tok::RBracket, "']'")?;
525                Ok(Type::Array(Box::new(element)))
526            }
527            Tok::LBrace => Ok(Type::Record(self.record_body()?)),
528            _ => self.error("type"),
529        }
530    }
531}
532
533impl Parser {
534    /// A values file is a sequence of values separated by semi-colons, with an optional final semi-colon.
535    fn values(&mut self) -> Result<Vec<Value>> {
536        let mut values = Vec::new();
537        if self.peek() == &Tok::Eof {
538            return Ok(values);
539        }
540        loop {
541            values.push(self.value()?);
542            match self.peek() {
543                Tok::Semi => {
544                    self.bump();
545                    if self.peek() == &Tok::Eof {
546                        break;
547                    }
548                }
549                Tok::Eof => break,
550                _ => return self.error("semi-colon"),
551            }
552        }
553        Ok(values)
554    }
555
556    fn value(&mut self) -> Result<Value> {
557        self.nested(Self::value_unchecked)
558    }
559
560    /// Parses a value and then any postfix `?`, each of which wraps it in `Some`.
561    fn value_unchecked(&mut self) -> Result<Value> {
562        let mut value = self.primary_value()?;
563        while self.peek() == &Tok::Question {
564            if !self.experimental.some_query {
565                return Err(SyntaxError {
566                    pos: self.pos(),
567                    message: "Postfix '?' is experimental; enable it with --experimental=some-query".to_string(),
568                    context: self.context.clone(),
569                });
570            }
571            self.question()?;
572            let pos = value.pos;
573            value = Value {
574                pos,
575                kind: ValueKind::Tagged {
576                    name: "Some".to_string(),
577                    body: Some(TaggedBody::Tuple(vec![Argument { name: None, pos, value }])),
578                },
579            };
580        }
581        Ok(value)
582    }
583
584    fn primary_value(&mut self) -> Result<Value> {
585        let pos = self.pos();
586        let kind = match self.peek().clone() {
587            Tok::Name(_) | Tok::TypeName(_) | Tok::Enum | Tok::Const if self.at_qualifier() => {
588                let qualifier = self.qualifier();
589                match self.peek().clone() {
590                    Tok::Name(name) => {
591                        self.bump();
592                        ValueKind::Tagged {
593                            name: format!("{}{}", qualifier, name),
594                            body: None,
595                        }
596                    }
597                    Tok::TypeName(name) => {
598                        self.bump();
599                        let name = format!("{}{}", qualifier, name);
600                        let body = self.tagged_body()?;
601                        ValueKind::Tagged { name, body }
602                    }
603                    _ => return self.error("name after '::'"),
604                }
605            }
606            Tok::Nat(text) => self.literal(ValueKind::Nat(text)),
607            Tok::Int(text) => self.literal(ValueKind::Int(text)),
608            Tok::Float(text) => self.literal(ValueKind::Float(text)),
609            Tok::Str(text) => self.literal(ValueKind::Str(text)),
610            // A lowercase name can only refer to a const, so it takes no body.
611            Tok::Name(name) => {
612                self.bump();
613                ValueKind::Tagged { name, body: None }
614            }
615            Tok::LBrace => ValueKind::Record(self.members()?),
616            Tok::LBracket => ValueKind::Array(self.array()?),
617            Tok::TypeName(name) => {
618                self.bump();
619                let body = self.tagged_body()?;
620                ValueKind::Tagged { name, body }
621            }
622            _ => return self.error("value"),
623        };
624        Ok(Value { pos, kind })
625    }
626
627    /// The record, tuple or array that may follow the name of a constructor.
628    fn tagged_body(&mut self) -> Result<Option<TaggedBody>> {
629        Ok(match self.peek() {
630            Tok::LBrace => Some(TaggedBody::Record(self.members()?)),
631            Tok::LParen => Some(TaggedBody::Tuple(self.tuple()?)),
632            Tok::LBracket => Some(TaggedBody::Array(self.array()?)),
633            _ => None,
634        })
635    }
636
637    /// Consumes the current token, which has already been read as a literal.
638    fn literal(&mut self, kind: ValueKind) -> ValueKind {
639        self.bump();
640        kind
641    }
642
643    fn members(&mut self) -> Result<Vec<Member>> {
644        self.expect(Tok::LBrace, "'{'")?;
645        let mut members = Vec::new();
646        while self.peek() != &Tok::RBrace {
647            let pos = self.pos();
648            let name = match self.peek() {
649                Tok::Name(name) => name.clone(),
650                _ => return self.error("field name"),
651            };
652            self.bump();
653            self.expect(Tok::Colon, "':'")?;
654            let value = self.value()?;
655            members.push(Member { name, pos, value });
656            match self.peek() {
657                Tok::Comma => self.bump(),
658                Tok::RBrace => {}
659                _ => return self.error("comma or '}'"),
660            }
661        }
662        self.expect(Tok::RBrace, "'}'")?;
663        Ok(members)
664    }
665
666    /// Parses the arguments of a tuple constructor. A lowercase name followed by a colon names the parameter that the
667    /// argument is for. Positional arguments may not follow named ones.
668    fn tuple(&mut self) -> Result<Vec<Argument>> {
669        self.expect(Tok::LParen, "'('")?;
670        let mut args: Vec<Argument> = Vec::new();
671        while self.peek() != &Tok::RParen {
672            let pos = self.pos();
673            let name = match (self.peek(), self.tokens.get(self.index + 1).map(|t| &t.tok)) {
674                (Tok::Name(name), Some(Tok::Colon)) => {
675                    let name = name.clone();
676                    self.bump();
677                    self.bump();
678                    Some(name)
679                }
680                _ => None,
681            };
682            if name.is_none() && args.last().is_some_and(|a| a.name.is_some()) {
683                return Err(SyntaxError {
684                    pos,
685                    message: "Positional argument after a named argument".to_string(),
686                    context: self.context.clone(),
687                });
688            }
689            let value = self.value()?;
690            args.push(Argument { name, pos, value });
691            match self.peek() {
692                Tok::Comma => self.bump(),
693                Tok::RParen => {}
694                _ => return self.error("comma or ')'"),
695            }
696        }
697        self.expect(Tok::RParen, "')'")?;
698        Ok(args)
699    }
700
701    fn array(&mut self) -> Result<Vec<Value>> {
702        self.expect(Tok::LBracket, "'['")?;
703        self.value_list(Tok::RBracket, "']'")
704    }
705
706    /// Parses comma-separated values, with an optional trailing comma, up to and including the closing token.
707    fn value_list(&mut self, close: Tok, close_name: &str) -> Result<Vec<Value>> {
708        let mut values = Vec::new();
709        while self.peek() != &close {
710            values.push(self.value()?);
711            match self.peek() {
712                Tok::Comma => self.bump(),
713                tok if tok == &close => {}
714                _ => return self.error(&format!("comma or {}", close_name)),
715            }
716        }
717        self.expect(close, close_name)?;
718        Ok(values)
719    }
720}
721
722#[cfg(test)]
723mod tests {
724    use super::*;
725
726    fn err(text: &str) -> (u32, u32, String) {
727        let e = parse(text).unwrap_err();
728        (e.pos.line, e.pos.col, e.message)
729    }
730
731    #[test]
732    fn parses_a_generic_recursive_enum() {
733        let decls = parse("enum List<T> = Nil, Cons { head: T, tail: List<T> };")
734            .unwrap()
735            .enums;
736        assert_eq!(decls.len(), 1);
737        assert_eq!(decls[0].params.len(), 1);
738        assert_eq!(decls[0].variants.len(), 2);
739    }
740
741    #[test]
742    fn accepts_empty_input_and_trailing_commas() {
743        assert_eq!(parse("// Nothing here.\n").unwrap(), TypesFile::default());
744        assert!(parse("enum A = X(Int,), Y {a: Int,},;").is_ok());
745        assert!(parse("enum A = Ping(), Pong {};").is_ok());
746    }
747
748    #[test]
749    fn parses_named_parameters_after_unnamed_ones() {
750        let decls = parse("enum A = X(Int, a: Int, b: [Int],);").unwrap().enums;
751        let VariantBody::Tuple(params) = &decls[0].variants[0].body else {
752            panic!("expected a tuple");
753        };
754        let names: Vec<Option<&str>> = params.iter().map(|p| p.name.as_deref()).collect();
755        assert_eq!(names, vec![None, Some("a"), Some("b")]);
756    }
757
758    #[test]
759    fn rejects_malformed_parameter_lists() {
760        assert_eq!(
761            err("enum A = X(a: Int, Int);"),
762            (1, 20, "Unnamed parameter after a named parameter".to_string())
763        );
764        assert_eq!(err("enum A = X(a Int);").2, "Expected ':'");
765        assert_eq!(err("enum A = X(const: Int);").2, "Expected type");
766    }
767
768    #[test]
769    fn parses_named_arguments_after_positional_ones() {
770        let values = parse_values("X(1, a: 2, b: c,)").unwrap();
771        let ValueKind::Tagged {
772            body: Some(TaggedBody::Tuple(args)),
773            ..
774        } = &values[0].kind
775        else {
776            panic!("expected a tuple");
777        };
778        let names: Vec<Option<&str>> = args.iter().map(|a| a.name.as_deref()).collect();
779        assert_eq!(names, vec![None, Some("a"), Some("b")]);
780        // The name before a colon is not a const reference, but the value after it can be.
781        assert!(matches!(&args[2].value.kind, ValueKind::Tagged { name, body: None } if name == "c"));
782    }
783
784    #[test]
785    fn rejects_positional_arguments_after_named_ones() {
786        let e = parse_values("X(a: 1, 2)").unwrap_err();
787        assert_eq!((e.pos.line, e.pos.col), (1, 9));
788        assert_eq!(e.message, "Positional argument after a named argument");
789    }
790
791    #[test]
792    fn parses_an_array_variant_with_one_element_type() {
793        let decls = parse("enum L<T> = Items[T], Join[L<T>], Rows[[Nat]], Maybe[Nat?], Done;")
794            .unwrap()
795            .enums;
796        let shown: Vec<String> = decls[0]
797            .variants
798            .iter()
799            .map(|v| match &v.body {
800                VariantBody::Array(element) => element.to_string(),
801                _ => "-".to_string(),
802            })
803            .collect();
804        assert_eq!(shown, ["T", "L<T>", "[Nat]", "Option<Nat>", "-"]);
805    }
806
807    #[test]
808    fn rejects_an_array_variant_without_exactly_one_element_type() {
809        let err = |text: &str| {
810            let e = parse(text).unwrap_err();
811            (e.pos.line, e.pos.col, e.message)
812        };
813        assert_eq!(err("enum A = X[];"), (1, 12, "Expected type".to_string()));
814        let (line, col, message) = err("enum A = X[Nat, String];");
815        assert_eq!((line, col), (1, 15));
816        assert!(message.contains("exactly one element type"), "{}", message);
817        assert_eq!(err("enum A = X[Nat;").2, "Expected ']'");
818    }
819
820    #[test]
821    fn parses_a_tagged_array_value() {
822        let values = parse_values("Items[1, 2,]; Items[]; Join[Items[1], Items[]]").unwrap();
823        let sizes: Vec<usize> = values
824            .iter()
825            .map(|v| match &v.kind {
826                ValueKind::Tagged {
827                    body: Some(TaggedBody::Array(items)),
828                    ..
829                } => items.len(),
830                other => panic!("not an array body: {:?}", other),
831            })
832            .collect();
833        assert_eq!(sizes, [2, 0, 2]);
834    }
835
836    #[test]
837    fn a_tagged_array_value_has_no_named_elements() {
838        let e = parse_values("Items[x: 1]").unwrap_err();
839        assert_eq!((e.pos.line, e.pos.col), (1, 8));
840        assert_eq!(e.message, "Expected comma or ']'");
841    }
842
843    #[test]
844    fn a_tagged_array_counts_towards_the_nesting_limit() {
845        let deep = |levels: usize| format!("{}1{}", "A[".repeat(levels), "]".repeat(levels));
846        assert!(parse_values(&deep(100)).is_ok());
847        assert!(parse_values(&deep(MAX_DEPTH as usize + 1)).is_err());
848    }
849
850    #[test]
851    fn parses_qualified_names_in_types() {
852        let text =
853            "enum A<T> = X(bundle::T, acme.shapes::U<Nat>, P.Q.R::Left, named: g::V?), Y[local::W], Z { f: [h::K] };";
854        let decls = parse(text).unwrap().enums;
855        let shown: Vec<String> = decls[0]
856            .variants
857            .iter()
858            .flat_map(|v| match &v.body {
859                VariantBody::Tuple(params) => params.iter().map(|p| p.ty.to_string()).collect::<Vec<_>>(),
860                VariantBody::Array(element) => vec![element.to_string()],
861                VariantBody::Record(fields) => fields.iter().map(|f| f.ty.to_string()).collect(),
862                VariantBody::Unit => Vec::new(),
863            })
864            .collect();
865        assert_eq!(
866            shown,
867            [
868                "bundle::T",
869                "acme.shapes::U<Nat>",
870                "P.Q.R::Left",
871                "Option<g::V>",
872                "local::W",
873                "[h::K]"
874            ]
875        );
876    }
877
878    #[test]
879    fn a_keyword_can_be_a_part_of_a_qualifier() {
880        let values = parse_values("const::Foo(1); acme.enum::Bar; enum.const::baz").unwrap();
881        let names: Vec<&str> = values
882            .iter()
883            .map(|v| match &v.kind {
884                ValueKind::Tagged { name, .. } => name.as_str(),
885                other => panic!("not tagged: {:?}", other),
886            })
887            .collect();
888        assert_eq!(names, ["const::Foo", "acme.enum::Bar", "enum.const::baz"]);
889        let decls = parse("enum E = A(const::T, acme.enum::U<Nat>), B { f: enum.const::V };")
890            .unwrap()
891            .enums;
892        let shown: Vec<String> = decls[0]
893            .variants
894            .iter()
895            .flat_map(|v| match &v.body {
896                VariantBody::Tuple(params) => params.iter().map(|p| p.ty.to_string()).collect::<Vec<_>>(),
897                VariantBody::Record(fields) => fields.iter().map(|f| f.ty.to_string()).collect(),
898                _ => Vec::new(),
899            })
900            .collect();
901        assert_eq!(shown, ["const::T", "acme.enum::U<Nat>", "enum.const::V"]);
902    }
903
904    #[test]
905    fn a_keyword_alone_still_begins_a_declaration() {
906        // Without a dot or `::` after it, the keyword is not a part of a qualifier.
907        assert_eq!(parse_file("enum E = A;", Experimental::default()).0, SourceKind::Types);
908        assert_eq!(parse_file("const x = 1;", Experimental::default()).0, SourceKind::Types);
909        assert_eq!(parse_file("const::X", Experimental::default()).0, SourceKind::Values);
910        assert_eq!(parse_file("enum.a::X", Experimental::default()).0, SourceKind::Values);
911        assert!(parse_values("const").is_err());
912        assert!(parse_values("const::").is_err());
913    }
914
915    #[test]
916    fn parses_qualified_names_in_values() {
917        let values = parse_values(
918            "bundle::Foo(1); acme.shapes::Circle { r: 1.0 }; g::x; g::Foo[1, 2]; P.Q.R::Dot; local::Foo(a: g::y)",
919        )
920        .unwrap();
921        let names: Vec<(&str, bool)> = values
922            .iter()
923            .map(|v| match &v.kind {
924                ValueKind::Tagged { name, body } => (name.as_str(), body.is_some()),
925                other => panic!("not tagged: {:?}", other),
926            })
927            .collect();
928        assert_eq!(
929            names,
930            [
931                ("bundle::Foo", true),
932                ("acme.shapes::Circle", true),
933                ("g::x", false),
934                ("g::Foo", true),
935                ("P.Q.R::Dot", false),
936                ("local::Foo", true)
937            ]
938        );
939        // The position of a qualified value is the start of its qualifier.
940        assert_eq!((values[1].pos.line, values[1].pos.col), (1, 17));
941    }
942
943    #[test]
944    fn a_declaration_is_never_qualified() {
945        assert_eq!(parse("enum g::A = X;").unwrap_err().message, "Expected type name");
946        assert_eq!(
947            parse("enum A = g::X;").unwrap_err().message,
948            "Expected constructor name"
949        );
950        assert_eq!(parse("const g::x = 1;").unwrap_err().message, "Expected ':' or '='");
951    }
952
953    #[test]
954    fn rejects_a_qualifier_without_a_name() {
955        assert_eq!(parse("enum A = X(g::);").unwrap_err().message, "Expected type");
956        assert_eq!(parse_values("g::;").unwrap_err().message, "Expected name after '::'");
957        assert_eq!(parse_values("g::1").unwrap_err().message, "Expected name after '::'");
958        // A dot is only part of a qualifier, so this is not a value.
959        assert_eq!(parse_values("a.b").unwrap_err().message, "Expected semi-colon");
960        assert_eq!(parse("enum A = X(a.b);").unwrap_err().message, "Expected ':'");
961    }
962
963    #[test]
964    fn a_parameter_name_is_not_taken_for_a_qualifier() {
965        // A single colon still names a parameter or a field, and `::` begins a type.
966        let decls = parse("enum A = X(n: Nat, m: g::T);").unwrap().enums;
967        let VariantBody::Tuple(params) = &decls[0].variants[0].body else {
968            panic!("not a tuple");
969        };
970        assert_eq!(params[0].name.as_deref(), Some("n"));
971        assert_eq!(params[1].name.as_deref(), Some("m"));
972        assert_eq!(params[1].ty.to_string(), "g::T");
973        let values = parse_values("X(g::y, n: g::x)").unwrap();
974        let ValueKind::Tagged {
975            body: Some(TaggedBody::Tuple(args)),
976            ..
977        } = &values[0].kind
978        else {
979            panic!("not a tuple");
980        };
981        assert_eq!(args[0].name, None);
982        assert_eq!(args[1].name.as_deref(), Some("n"));
983    }
984
985    #[test]
986    fn accepts_underscore_type_parameters() {
987        let decls = parse("enum Phantom<_T, U> = P(U);").unwrap().enums;
988        assert!(decls[0].params[0].underscore);
989        assert!(!decls[0].params[1].underscore);
990    }
991
992    #[test]
993    fn rejects_bad_underscore_parameters() {
994        assert!(parse("enum A<_> = X;").is_err());
995        assert!(parse("enum A<_t> = X;").is_err());
996    }
997
998    #[test]
999    fn reports_missing_separators_at_the_next_token() {
1000        assert_eq!(
1001            err("enum A = X\nenum B = Y;"),
1002            (2, 1, "Expected comma or semi-colon".to_string())
1003        );
1004        assert_eq!(err("enum A = X {a: Int b: Int};").2, "Expected comma or '}'");
1005    }
1006
1007    #[test]
1008    fn attributes_errors_to_the_enclosing_enum_once_it_is_named() {
1009        let context_of = |text: &str| parse(text).unwrap_err().context;
1010        assert_eq!(context_of("enum Shape = Circle { r: }"), Some("enum Shape".to_string()));
1011        assert_eq!(context_of("enum Shape"), Some("enum Shape".to_string()));
1012        assert_eq!(context_of("enum a = X;"), None);
1013        assert_eq!(context_of("enum A = X; B"), None);
1014        assert_eq!(context_of("enum A = X; enum B = ;"), Some("enum B".to_string()));
1015        assert_eq!(context_of("const n: Nat = ;"), Some("const n".to_string()));
1016        assert_eq!(context_of("const n Nat = 1;"), Some("const n".to_string()));
1017        assert_eq!(context_of("const : Nat = 1;"), None);
1018        assert_eq!(context_of("const a: Nat = 1; enum"), None);
1019    }
1020
1021    #[test]
1022    fn reports_other_syntax_errors() {
1023        assert_eq!(err("enum A = ;").2, "Expected constructor name");
1024        assert_eq!(err("enum a = X;").2, "Expected type name");
1025        assert_eq!(err("enum A = X([]);").2, "Expected type");
1026        assert_eq!(err("enum L{T} = Nil;").2, "Expected '='");
1027        assert_eq!(err("enum A = X; B").2, "Expected 'enum' or 'const'");
1028        assert_eq!(err("enum A = X(Int").2, "Expected comma or ')'");
1029        assert_eq!(err("enum A = X #").2, "Unexpected character '#'");
1030        assert_eq!(err("enum A = X \u{1b}").2, "Unexpected character '\\u001b'");
1031        assert_eq!(err("enum A = X \u{7f}").2, "Unexpected character '\\u007f'");
1032    }
1033
1034    fn value_err(text: &str) -> (u32, u32, String) {
1035        let e = parse_values(text).unwrap_err();
1036        (e.pos.line, e.pos.col, e.message)
1037    }
1038
1039    #[test]
1040    fn parses_values_separated_by_semicolons() {
1041        let values = parse_values("Circle { radius: 3.0 };\nQuit; [1, 2,]; null; \"s\"; +8; -2.5e3;").unwrap();
1042        assert_eq!(values.len(), 7);
1043        assert!(
1044            matches!(&values[0].kind, ValueKind::Tagged { name, body: Some(TaggedBody::Record(m)) }
1045            if name == "Circle" && m.len() == 1)
1046        );
1047        assert!(matches!(&values[1].kind, ValueKind::Tagged { body: None, .. }));
1048        assert!(matches!(&values[3].kind, ValueKind::Tagged { name, body: None } if name == "null"));
1049        assert!(matches!(&values[5].kind, ValueKind::Int(t) if t == "+8"));
1050    }
1051
1052    #[test]
1053    fn a_single_value_needs_no_semicolon() {
1054        assert_eq!(parse_values("{ x: 1 }").unwrap().len(), 1);
1055        assert_eq!(parse_values("{ x: 1 };").unwrap().len(), 1);
1056        assert!(parse_values("// Only a comment.\n").unwrap().is_empty());
1057    }
1058
1059    #[test]
1060    fn a_semicolon_separates_values_so_a_tag_does_not_swallow_the_next_value() {
1061        let values = parse_values("Quit; { x: 1 }").unwrap();
1062        assert!(matches!(&values[0].kind, ValueKind::Tagged { body: None, .. }));
1063        assert!(matches!(&values[1].kind, ValueKind::Record(_)));
1064        // Without the separator the record is the body of the tag.
1065        let values = parse_values("Quit { x: 1 }").unwrap();
1066        assert_eq!(values.len(), 1);
1067    }
1068
1069    #[test]
1070    fn distinguishes_an_empty_tuple_from_a_bare_tag() {
1071        let values = parse_values("Ping(); Ping; Pong {}").unwrap();
1072        assert!(matches!(&values[0].kind, ValueKind::Tagged { body: Some(TaggedBody::Tuple(t)), .. } if t.is_empty()));
1073        assert!(matches!(&values[1].kind, ValueKind::Tagged { body: None, .. }));
1074        assert!(matches!(&values[2].kind, ValueKind::Tagged { body: Some(TaggedBody::Record(m)), .. } if m.is_empty()));
1075    }
1076
1077    #[test]
1078    fn reports_value_syntax_errors() {
1079        assert_eq!(value_err("1 2"), (1, 3, "Expected semi-colon".to_string()));
1080        assert_eq!(value_err("1;;2").2, "Expected value");
1081        assert_eq!(value_err(";").2, "Expected value");
1082        assert_eq!(value_err("[1 2]").2, "Expected comma or ']'");
1083        assert_eq!(value_err("{ x: 1 y: 2 }").2, "Expected comma or '}'");
1084        assert_eq!(value_err("{ \"x\": 1 }").2, "Expected field name");
1085        assert_eq!(value_err("(1, 2)").2, "Expected value");
1086        assert_eq!(value_err("circle { radius: 3.0 }").2, "Expected semi-colon");
1087        assert_eq!(value_err("Circle { radius: 3.0").2, "Expected comma or '}'");
1088        assert_eq!(
1089            value_err("3."),
1090            (1, 3, "Expected a digit after the decimal point".to_string())
1091        );
1092        assert_eq!(value_err("\"\\q\"").2, "Invalid escape in string");
1093        assert_eq!(value_err("Write(\"oops)").2, "Unterminated string");
1094    }
1095
1096    #[test]
1097    fn classifies_a_file_by_its_first_token() {
1098        assert_eq!(parse_file("enum A = X;", Experimental::default()).0, SourceKind::Types);
1099        assert_eq!(parse_file("A { x: 1 }", Experimental::default()).0, SourceKind::Values);
1100        assert_eq!(parse_file("42", Experimental::default()).0, SourceKind::Values);
1101        assert_eq!(
1102            parse_file("const n: Nat = 1;", Experimental::default()).0,
1103            SourceKind::Types
1104        );
1105        assert_eq!(parse_file("n", Experimental::default()).0, SourceKind::Values);
1106        assert_eq!(parse_file("", Experimental::default()).0, SourceKind::Types);
1107        assert_eq!(
1108            parse_file("// Just a comment.\n", Experimental::default()).0,
1109            SourceKind::Types
1110        );
1111        // The kind is known even when the file does not parse.
1112        let (kind, parsed) = parse_file("circle {", Experimental::default());
1113        assert_eq!(kind, SourceKind::Values);
1114        assert!(parsed.is_err());
1115    }
1116
1117    #[test]
1118    fn parses_const_definitions_interleaved_with_enums() {
1119        let file =
1120            parse("const a: Nat = 1;\nenum E = X;\nconst b: [E] = [X, X];\nconst c: { a: Nat } = { a: 2 };").unwrap();
1121        assert_eq!(file.enums.len(), 1);
1122        assert_eq!(
1123            file.consts.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(),
1124            ["a", "b", "c"]
1125        );
1126        assert!(matches!(&file.consts[1].ty, Some(Type::Array(_))));
1127        assert!(matches!(&file.consts[2].value.kind, ValueKind::Record(m) if m.len() == 1));
1128    }
1129
1130    #[test]
1131    fn reports_const_syntax_errors() {
1132        assert_eq!(err("const n Nat = 1;"), (1, 9, "Expected ':' or '='".to_string()));
1133        assert_eq!(err("const n: Nat 1;").2, "Expected '='");
1134        assert_eq!(err("const n: Nat = 1").2, "Expected semi-colon");
1135        assert_eq!(err("const n: Nat = ;").2, "Expected value");
1136        assert_eq!(err("const 1: Nat = 1;").2, "Expected const name");
1137        assert_eq!(err("const enum: Nat = 1;").2, "Expected const name");
1138    }
1139
1140    #[test]
1141    fn parses_generic_consts() {
1142        let file = parse("const null<T>: Option<T> = None;\nconst pair<_A, B>: B = x;").unwrap();
1143        assert_eq!(file.consts[0].params.len(), 1);
1144        assert_eq!(file.consts[0].params[0].name, "T");
1145        assert!(file.consts[1].params[1].name == "B" && file.consts[1].params[0].underscore);
1146        assert_eq!(err("const n<>: Nat = 1;").2, "Expected type parameter name");
1147        assert_eq!(err("const n<T: Nat = 1;").2, "Expected comma or '>'");
1148        assert_eq!(err("const n<t>: Nat = 1;").2, "Expected type parameter name");
1149    }
1150
1151    #[test]
1152    fn a_const_name_cannot_start_with_a_capital_letter() {
1153        assert_eq!(
1154            err("const N: Nat = 1;"),
1155            (
1156                1,
1157                7,
1158                "Expected const name that starts with a lower-case letter".to_string()
1159            )
1160        );
1161        assert!(parse("const _n: Nat = 1;\nconst nN: Nat = 1;").is_ok());
1162    }
1163
1164    #[test]
1165    fn the_type_of_a_const_is_optional() {
1166        let file = parse("const n = 1;\nconst e = [];\nconst t: Nat = 2;").unwrap();
1167        assert!(file.consts[0].ty.is_none() && file.consts[1].ty.is_none());
1168        assert!(file.consts[2].ty.is_some());
1169        assert_eq!(err("const n = ;").2, "Expected value");
1170        assert_eq!(err("const n: = 1;").2, "Expected type");
1171        // The parameters are read before the type is known to be missing, which is reported after the parse.
1172        assert_eq!(parse("const n<T> = 1;").unwrap().consts[0].params.len(), 1);
1173    }
1174
1175    #[test]
1176    fn displays_types_as_they_are_written() {
1177        let file = parse("const x: { a: [Option<Nat>], b: {}, c: Map<String, [Int]> } = y;").unwrap();
1178        let ty = file.consts[0].ty.as_ref().unwrap();
1179        assert_eq!(ty.to_string(), "{ a: [Option<Nat>], b: {}, c: Map<String, [Int]> }");
1180    }
1181
1182    #[test]
1183    fn null_is_an_ordinary_name() {
1184        assert!(parse("const null<T>: Option<T> = None;").is_ok());
1185        let values = parse_values("null").unwrap();
1186        assert!(matches!(&values[0].kind, ValueKind::Tagged { name, body: None } if name == "null"));
1187    }
1188
1189    #[test]
1190    fn const_is_a_reserved_word() {
1191        assert!(parse("enum E = X { const: Nat };").is_err());
1192        assert!(parse_values("{ const: 1 }").is_err());
1193        assert!(parse_values("const").is_err());
1194    }
1195
1196    #[test]
1197    fn a_lowercase_name_is_a_value_that_takes_no_body() {
1198        let values = parse_values("limit; [Limit, limit]").unwrap();
1199        assert!(matches!(&values[0].kind, ValueKind::Tagged { name, body: None } if name == "limit"));
1200        assert_eq!(value_err("limit(1)").2, "Expected semi-colon");
1201    }
1202
1203    #[test]
1204    fn rejects_very_deep_nesting_instead_of_overflowing_the_stack() {
1205        let deep_value = "[".repeat(10_000);
1206        assert_eq!(value_err(&deep_value).2, "Nesting is too deep");
1207        let deep_type = format!("enum A = X({});", "[".repeat(10_000));
1208        assert_eq!(err(&deep_type).2, "Nesting is too deep");
1209        // Moderate nesting is fine.
1210        let nested = format!("{}1{}", "[".repeat(50), "]".repeat(50));
1211        assert!(parse_values(&nested).is_ok());
1212    }
1213
1214    fn option_of(ty: &Type) -> Option<&Type> {
1215        match ty {
1216            Type::Ref { name, args, .. } if name == "Option" && args.len() == 1 => Some(&args[0]),
1217            _ => None,
1218        }
1219    }
1220
1221    #[test]
1222    fn a_postfix_question_makes_a_type_optional() {
1223        let decls = parse("enum A = X(Nat?, [Nat]?, { a: Nat }?, Box<Nat>?, Nat??, Nat ?);")
1224            .unwrap()
1225            .enums;
1226        let VariantBody::Tuple(params) = &decls[0].variants[0].body else {
1227            panic!("expected a tuple");
1228        };
1229        let shown: Vec<String> = params.iter().map(|p| p.ty.to_string()).collect();
1230        assert_eq!(
1231            shown,
1232            vec![
1233                "Option<Nat>",
1234                "Option<[Nat]>",
1235                "Option<{ a: Nat }>",
1236                "Option<Box<Nat>>",
1237                "Option<Option<Nat>>",
1238                "Option<Nat>"
1239            ]
1240        );
1241        // Only the whole type is wrapped, so the question mark inside an array is for the elements.
1242        let decls = parse("enum A = X([Nat?]);").unwrap().enums;
1243        let VariantBody::Tuple(params) = &decls[0].variants[0].body else {
1244            panic!("expected a tuple");
1245        };
1246        assert_eq!(params[0].ty.to_string(), "[Option<Nat>]");
1247    }
1248
1249    #[test]
1250    fn an_optional_type_is_positioned_at_the_start_of_its_operand() {
1251        let decls = parse("enum A = X(  Nat?);").unwrap().enums;
1252        let VariantBody::Tuple(params) = &decls[0].variants[0].body else {
1253            panic!("expected a tuple");
1254        };
1255        let Type::Ref { pos, .. } = &params[0].ty else {
1256            panic!("expected a reference");
1257        };
1258        assert_eq!((pos.line, pos.col), (1, 14));
1259        assert!(option_of(&params[0].ty).is_some());
1260    }
1261
1262    #[test]
1263    fn rejects_a_question_with_nothing_to_make_optional() {
1264        assert_eq!(err("enum A = X(?);"), (1, 12, "Expected type".to_string()));
1265        assert_eq!(err("enum A = X(Nat, ?);"), (1, 17, "Expected type".to_string()));
1266        assert_eq!(err("enum A = ?;"), (1, 10, "Expected constructor name".to_string()));
1267    }
1268
1269    #[test]
1270    fn many_question_marks_are_stopped_by_the_nesting_limit() {
1271        let text = format!("enum A = X(Nat{});", "?".repeat(1000));
1272        assert_eq!(err(&text).2, "Nesting is too deep");
1273        let text = format!("enum A = X(Nat{});", "?".repeat(50));
1274        assert!(parse(&text).is_ok());
1275    }
1276
1277    const SOME_QUERY: Experimental = Experimental { some_query: true };
1278
1279    #[test]
1280    fn a_postfix_question_on_a_value_needs_the_feature() {
1281        let e = parse_values("0?").unwrap_err();
1282        assert_eq!(
1283            (e.pos.line, e.pos.col, e.message.as_str()),
1284            (
1285                1,
1286                2,
1287                "Postfix '?' is experimental; enable it with --experimental=some-query"
1288            )
1289        );
1290        // The feature is for values, wherever they are written.
1291        let e = parse("const a = 0?;").unwrap_err();
1292        assert_eq!(
1293            e.message,
1294            "Postfix '?' is experimental; enable it with --experimental=some-query"
1295        );
1296        assert!(parse_values_with("0?", Experimental::default()).is_err());
1297        assert!(parse_values_with("0?", SOME_QUERY).is_ok());
1298        assert!(parse_values_with("0?", Experimental::all()).is_ok());
1299    }
1300
1301    #[test]
1302    fn a_postfix_question_on_a_value_is_some() {
1303        let values = parse_values_with("1?; [2?]; Point(1, 2)?; x ?; 3??", SOME_QUERY).unwrap();
1304        let ValueKind::Tagged { name, body } = &values[0].kind else {
1305            panic!("expected a constructor");
1306        };
1307        assert_eq!(name, "Some");
1308        let Some(TaggedBody::Tuple(arguments)) = body else {
1309            panic!("expected a tuple");
1310        };
1311        assert_eq!(arguments.len(), 1);
1312        assert_eq!(arguments[0].name, None);
1313        assert!(matches!(&arguments[0].value.kind, ValueKind::Nat(text) if text == "1"));
1314        // The Some is positioned at its operand, as is the argument.
1315        assert_eq!((values[0].pos.line, values[0].pos.col), (1, 1));
1316        assert_eq!(arguments[0].pos, values[0].pos);
1317        // It applies to the whole value, including the body of a constructor.
1318        let ValueKind::Tagged {
1319            body: Some(TaggedBody::Tuple(arguments)),
1320            ..
1321        } = &values[2].kind
1322        else {
1323            panic!("expected a constructor");
1324        };
1325        assert!(matches!(&arguments[0].value.kind, ValueKind::Tagged { name, .. } if name == "Point"));
1326        // A repeated question mark wraps once for each.
1327        let ValueKind::Tagged {
1328            body: Some(TaggedBody::Tuple(arguments)),
1329            ..
1330        } = &values[4].kind
1331        else {
1332            panic!("expected a constructor");
1333        };
1334        assert!(matches!(&arguments[0].value.kind, ValueKind::Tagged { name, .. } if name == "Some"));
1335    }
1336
1337    #[test]
1338    fn a_postfix_question_on_a_value_is_not_confused_with_a_named_argument() {
1339        let values = parse_values_with("X(a: 1?, b: 2)", SOME_QUERY).unwrap();
1340        let ValueKind::Tagged {
1341            body: Some(TaggedBody::Tuple(arguments)),
1342            ..
1343        } = &values[0].kind
1344        else {
1345            panic!("expected a constructor");
1346        };
1347        let names: Vec<Option<&str>> = arguments.iter().map(|a| a.name.as_deref()).collect();
1348        assert_eq!(names, vec![Some("a"), Some("b")]);
1349    }
1350
1351    #[test]
1352    fn many_question_marks_on_a_value_are_stopped_by_the_nesting_limit() {
1353        let text = format!("1{}", "?".repeat(1000));
1354        assert_eq!(
1355            parse_values_with(&text, SOME_QUERY).unwrap_err().message,
1356            "Nesting is too deep"
1357        );
1358    }
1359
1360    #[test]
1361    fn question_marks_between_arrays_count_towards_the_nesting_limit() {
1362        // Each level is an array and a `?`, so the tree is twice as tall as the calls are deep.
1363        let text = format!("enum A = X({}Nat{});", "[".repeat(150), "]?".repeat(150));
1364        assert_eq!(err(&text).2, "Nesting is too deep");
1365        let text = format!("enum A = X({}Nat{});", "[".repeat(90), "]?".repeat(90));
1366        assert!(parse(&text).is_ok());
1367        let text = format!("{}1{}", "[".repeat(150), "]?".repeat(150));
1368        assert_eq!(
1369            parse_values_with(&text, SOME_QUERY).unwrap_err().message,
1370            "Nesting is too deep"
1371        );
1372        let text = format!("{}1{}", "[".repeat(90), "]?".repeat(90));
1373        assert!(parse_values_with(&text, SOME_QUERY).is_ok());
1374    }
1375
1376    #[test]
1377    fn question_marks_between_other_constructs_count_towards_the_nesting_limit() {
1378        // A constructor, a record and a type argument, each followed by a `?`.
1379        let text = format!("{}1{}", "Box(".repeat(150), ")?".repeat(150));
1380        assert_eq!(
1381            parse_values_with(&text, SOME_QUERY).unwrap_err().message,
1382            "Nesting is too deep"
1383        );
1384        let text = format!("{}1{}", "{ a: ".repeat(150), " }?".repeat(150));
1385        assert_eq!(
1386            parse_values_with(&text, SOME_QUERY).unwrap_err().message,
1387            "Nesting is too deep"
1388        );
1389        let text = format!("enum A = X({}Nat{});", "Box<".repeat(150), ">?".repeat(150));
1390        assert_eq!(err(&text).2, "Nesting is too deep");
1391    }
1392}