Skip to main content

rhue_parser/
parser.rs

1use std::rc::Rc;
2
3use rhue_common::{Diagnostic, Span};
4use rhue_lexer::{Spanned, Token, lex};
5
6use crate::ast::*;
7use crate::strings;
8
9/// Max nesting (recursion plus left-associative operator chains) before the
10/// parser gives up, so hostile input can't build an endlessly deep tree.
11pub const MAX_DEPTH: u32 = 1000;
12
13/// Stop collecting after this many errors, the later ones are usually cascades
14/// anyway.
15pub const MAX_ERRORS: usize = 20;
16
17/// Boxed so `Result`s stay small on the hot (successful) path.
18type PResult<T> = Result<T, Box<Diagnostic>>;
19
20/// Parses a whole chunk (a file or `Engine::eval` source). On failure you get
21/// every error it found (up to [`MAX_ERRORS`]), in source order.
22pub fn parse_chunk(source: &str) -> Result<Chunk, Vec<Diagnostic>> {
23    let mut p = Parser::new(source)?;
24    let body = p.block_until_eof();
25    if p.errors.is_empty() {
26        Ok(Chunk {
27            span: body.span,
28            body,
29            name_count: p.next_name,
30            mode: directive(source),
31        })
32    } else {
33        Err(p.errors)
34    }
35}
36
37/// Parses one expression and wraps it as `return <expr>` so it goes through the
38/// same pipeline as a chunk (REPL / `eval_expr`).
39pub fn parse_expr(source: &str) -> Result<Chunk, Vec<Diagnostic>> {
40    let mut p = Parser::new(source)?;
41    let result = p.expr().and_then(|e| {
42        p.expect(Token::Eof, "after expression")?;
43        Ok(e)
44    });
45    match result {
46        Ok(e) => {
47            let span = e.span;
48            let body = Block {
49                stmts: vec![],
50                ret: Some(Return {
51                    values: vec![e],
52                    span,
53                }),
54                span,
55            };
56            Ok(Chunk {
57                body,
58                span,
59                name_count: p.next_name,
60                mode: None,
61            })
62        }
63        Err(d) => Err(vec![*d]),
64    }
65}
66
67/// Parses a type by itself (`(number, string) -> boolean`), the way host
68/// declarations and definition strings are written.
69pub fn parse_type(source: &str) -> Result<TypeExpr, Vec<Diagnostic>> {
70    let mut p = Parser::new(source)?;
71    let t = p.type_expr().and_then(|t| {
72        p.expect(Token::Eof, "after the type")?;
73        Ok(t)
74    });
75    t.map_err(|d| vec![*d])
76}
77
78struct Parser<'s> {
79    source: &'s str,
80    tokens: Vec<Spanned>,
81    pos: usize,
82    depth: u32,
83    next_name: NameId,
84    errors: Vec<Diagnostic>,
85}
86
87/// Runs `f` on a fresh stack segment if there's less than 64 KiB left, so deep
88/// (but within the limit) nesting is fine even on an embedder's small threads.
89fn grow<R>(f: impl FnOnce() -> R) -> R {
90    stacker::maybe_grow(64 * 1024, 1024 * 1024, f)
91}
92
93/// Finds a `--!strict`, `--!nonstrict` or `--!nocheck` comment in the lines
94/// before the first code. Other `--!` directives (`--!native`, ...) get
95/// ignored.
96fn directive(source: &str) -> Option<(TypeMode, Span)> {
97    let mut offset = 0usize;
98    for line in source.split_inclusive('\n') {
99        let start = offset;
100        offset += line.len();
101        let trimmed = line.trim();
102        if trimmed.is_empty() {
103            continue;
104        }
105        let rest = trimmed.strip_prefix("--")?;
106        let Some(word) = rest.strip_prefix('!') else {
107            if rest.starts_with('[') {
108                // a block comment might hide code after it, stop looking
109                return None;
110            }
111            continue;
112        };
113        let word = word.split_whitespace().next().unwrap_or("");
114        let mode = match word {
115            "strict" => TypeMode::Strict,
116            "nonstrict" => TypeMode::NonStrict,
117            "nocheck" => TypeMode::NoCheck,
118            _ => continue,
119        };
120        let lead = line.len() - line.trim_start().len();
121        let s = rhue_common::offset(start + lead);
122        return Some((mode, Span::new(s, s + 3 + rhue_common::offset(word.len()))));
123    }
124    None
125}
126
127fn error(message: impl Into<String>, span: Span) -> Box<Diagnostic> {
128    Box::new(Diagnostic::error(message, span))
129}
130
131impl<'s> Parser<'s> {
132    fn new(source: &'s str) -> Result<Self, Vec<Diagnostic>> {
133        let lexed = lex(source);
134        if !lexed.errors.is_empty() {
135            return Err(lexed.errors);
136        }
137        Ok(Parser {
138            source,
139            tokens: lexed.tokens,
140            pos: 0,
141            depth: 0,
142            next_name: 0,
143            errors: Vec::new(),
144        })
145    }
146
147    // ─ Token Helpers ─────────────────────────────────────────────────────────
148
149    fn peek(&self) -> Spanned {
150        self.tokens[self.pos]
151    }
152
153    fn peek_nth(&self, n: usize) -> Spanned {
154        self.tokens[(self.pos + n).min(self.tokens.len() - 1)]
155    }
156
157    /// Whether there's a line break between the current token and the one
158    /// before.
159    fn newline_before(&self) -> bool {
160        let prev_end = if self.pos == 0 {
161            0
162        } else {
163            self.tokens[self.pos - 1].span.end
164        };
165        self.source[prev_end as usize..self.peek().span.start as usize].contains('\n')
166    }
167
168    fn at(&self, token: Token) -> bool {
169        self.peek().token == token
170    }
171
172    fn bump(&mut self) -> Spanned {
173        let t = self.peek();
174        if t.token != Token::Eof {
175            self.pos += 1;
176        }
177        t
178    }
179
180    fn eat(&mut self, token: Token) -> Option<Spanned> {
181        self.at(token).then(|| self.bump())
182    }
183
184    fn expect(&mut self, token: Token, context: &str) -> PResult<Spanned> {
185        match self.eat(token) {
186            Some(t) => Ok(t),
187            None => {
188                let found = self.peek();
189                Err(Box::new(
190                    Diagnostic::error(
191                        format!(
192                            "expected {} {context}, found {}",
193                            token.describe(),
194                            found.token.describe()
195                        ),
196                        found.span,
197                    )
198                    .with_label(format!("expected {}", token.describe())),
199                ))
200            }
201        }
202    }
203
204    /// Expects the `end` (or `until`) closing a construct, pointing back at the
205    /// opener when it's missing.
206    fn expect_closer(&mut self, closer: Token, opener: Spanned, what: &str) -> PResult<Spanned> {
207        self.expect(closer, &format!("to close `{what}`"))
208            .map_err(|mut d| {
209                if opener.span.start != d.span().start {
210                    d.secondary.push(rhue_common::Label {
211                        span: opener.span,
212                        message: format!("`{what}` opened here"),
213                    });
214                }
215                d
216            })
217    }
218
219    fn text(&self, span: Span) -> &'s str {
220        span.text(self.source)
221    }
222
223    fn new_name(&mut self, span: Span) -> Name {
224        let id = self.next_name;
225        self.next_name += 1;
226        Name {
227            text: Rc::from(self.text(span)),
228            id,
229            span,
230        }
231    }
232
233    fn name(&mut self, context: &str) -> PResult<Name> {
234        let t = self.expect(Token::Ident, context)?;
235        Ok(self.new_name(t.span))
236    }
237
238    // ─ Blocks & Error Recovery ───────────────────────────────────────────────
239
240    fn block_until_eof(&mut self) -> Block {
241        let mut block = self.block();
242        // a stray closer at the top level (an `end` with no opener, usually
243        // after an earlier error) gets reported, skipped, and we keep going
244        while !self.at(Token::Eof) && self.errors.len() < MAX_ERRORS {
245            let t = self.bump();
246            self.report(
247                error(format!("unexpected {}", t.token.describe()), t.span).with_label_boxed(
248                    if matches!(
249                        t.token,
250                        Token::End | Token::Until | Token::Else | Token::Elseif
251                    ) {
252                        "nothing here to close"
253                    } else {
254                        "expected a statement"
255                    },
256                ),
257            );
258            let more = self.block();
259            block.stmts.extend(more.stmts);
260            if more.ret.is_some() {
261                block.ret = more.ret;
262            }
263        }
264        block
265    }
266
267    #[allow(clippy::boxed_local)] // errors arrive boxed from `PResult`
268    fn report(&mut self, d: Box<Diagnostic>) {
269        if self.errors.len() < MAX_ERRORS {
270            self.errors.push(*d);
271        }
272    }
273
274    fn block(&mut self) -> Block {
275        // blocks nest through statements (`do do do ... end end end`) which the
276        // expression depth counter can't see, so count them too
277        self.depth += 1;
278        if self.depth > MAX_DEPTH {
279            let span = self.peek().span;
280            self.report(
281                error("blocks nest too deeply", span)
282                    .with_label_boxed(format!("nesting limit of {MAX_DEPTH} reached here")),
283            );
284            // nothing sensible can come after this, stop
285            self.pos = self.tokens.len() - 1;
286            self.depth -= 1;
287            return Block {
288                stmts: Vec::new(),
289                ret: None,
290                span,
291            };
292        }
293        let block = grow(|| self.block_inner());
294        self.depth -= 1;
295        block
296    }
297
298    fn block_inner(&mut self) -> Block {
299        let start = self.peek().span;
300        let mut stmts = Vec::new();
301        let mut ret = None;
302        while !self.block_follow() && self.errors.len() < MAX_ERRORS {
303            if self.eat(Token::Semi).is_some() {
304                continue;
305            }
306            if self.at(Token::Return) {
307                match self.return_stmt() {
308                    Ok(r) => ret = Some(r),
309                    Err(d) => {
310                        self.report(d);
311                        self.synchronize();
312                    }
313                }
314                if !self.block_follow() {
315                    let t = self.peek();
316                    self.report(
317                        error(
318                            format!(
319                                "expected end of block after `return`, found {}",
320                                t.token.describe()
321                            ),
322                            t.span,
323                        )
324                        .with_label_boxed("`return` must be the last statement in a block"),
325                    );
326                    self.synchronize();
327                    continue;
328                }
329                break;
330            }
331            let before = self.pos;
332            match self.statement() {
333                Ok(s) => stmts.push(s),
334                Err(d) => {
335                    self.report(d);
336                    self.synchronize();
337                    if self.pos == before {
338                        self.bump();
339                    }
340                }
341            }
342        }
343        let end = ret
344            .as_ref()
345            .map(|r: &Return| r.span)
346            .or(stmts.last().map(|s: &Stmt| s.span))
347            .unwrap_or(start);
348        Block {
349            stmts,
350            ret,
351            span: start.to(end),
352        }
353    }
354
355    /// Skips ahead to a token that could plausibly start or end a statement.
356    fn synchronize(&mut self) {
357        loop {
358            match self.peek().token {
359                Token::Eof
360                | Token::End
361                | Token::Else
362                | Token::Elseif
363                | Token::Until
364                | Token::Local
365                | Token::If
366                | Token::While
367                | Token::For
368                | Token::Repeat
369                | Token::Do
370                | Token::Return
371                | Token::Function
372                | Token::Break => return,
373                Token::Semi => {
374                    self.bump();
375                    return;
376                }
377                // statements usually start on a new line, an identifier there
378                // is most likely the next assignment
379                Token::Ident if self.newline_before() => return,
380                _ => {
381                    self.bump();
382                }
383            }
384        }
385    }
386
387    /// Tokens that end a block (Lua's `block_follow`).
388    fn block_follow(&self) -> bool {
389        matches!(
390            self.peek().token,
391            Token::Eof | Token::End | Token::Else | Token::Elseif | Token::Until
392        )
393    }
394
395    // ─ Statements ────────────────────────────────────────────────────────────
396
397    fn return_stmt(&mut self) -> PResult<Return> {
398        let kw = self.bump();
399        let mut values = Vec::new();
400        if !self.block_follow() && !self.at(Token::Semi) {
401            values = self.expr_list()?;
402        }
403        let mut span = values.last().map_or(kw.span, |e| kw.span.to(e.span));
404        if let Some(semi) = self.eat(Token::Semi) {
405            span = span.to(semi.span);
406        }
407        Ok(Return { values, span })
408    }
409
410    fn statement(&mut self) -> PResult<Stmt> {
411        let t = self.peek();
412        let stmt = |kind, end: Span| Stmt {
413            kind,
414            span: t.span.to(end),
415        };
416        match t.token {
417            Token::Local => {
418                self.bump();
419                if self.eat(Token::Function).is_some() {
420                    let name = self.name("after `local function`")?;
421                    let func = self.function_body(Some(name.text.clone()), t, false)?;
422                    let span = func.span;
423                    return Ok(stmt(
424                        StmtKind::LocalFunction {
425                            name,
426                            func: Rc::new(func),
427                        },
428                        span,
429                    ));
430                }
431                let (names, types) = self.binding_list("after `local`")?;
432                let values = if self.eat(Token::Eq).is_some() {
433                    self.expr_list()?
434                } else {
435                    Vec::new()
436                };
437                let end = values.last().map_or_else(
438                    || {
439                        types
440                            .last()
441                            .and_then(|t| t.as_ref().map(|t| t.span))
442                            .unwrap_or(names.last().unwrap().span)
443                    },
444                    |e| e.span,
445                );
446                Ok(stmt(
447                    StmtKind::Local {
448                        names,
449                        types,
450                        values,
451                    },
452                    end,
453                ))
454            }
455            Token::Do => {
456                self.bump();
457                let body = self.block();
458                let end = self.expect_closer(Token::End, t, "do")?;
459                Ok(stmt(StmtKind::Do(body), end.span))
460            }
461            Token::While => {
462                self.bump();
463                let cond = self.expr()?;
464                self.expect(Token::Do, "after `while` condition")?;
465                let body = self.block();
466                let end = self.expect_closer(Token::End, t, "while")?;
467                Ok(stmt(StmtKind::While { cond, body }, end.span))
468            }
469            Token::Repeat => {
470                self.bump();
471                let body = self.block();
472                self.expect_closer(Token::Until, t, "repeat")?;
473                let cond = self.expr()?;
474                let end = cond.span;
475                Ok(stmt(StmtKind::Repeat { body, cond }, end))
476            }
477            Token::If => self.if_stmt(),
478            Token::For => self.for_stmt(),
479            Token::Break => {
480                self.bump();
481                Ok(stmt(StmtKind::Break, t.span))
482            }
483            Token::Function => {
484                self.bump();
485                let name = self.name("after `function`")?;
486                let mut full_name = name.text.to_string();
487                let mut target = Expr {
488                    span: name.span,
489                    kind: ExprKind::Name(name),
490                };
491                // `function a.b.c()` and `function a.b:m()`
492                let mut method = None;
493                while matches!(self.peek().token, Token::Dot | Token::Colon) {
494                    let sep = self.bump();
495                    let field = self.expect(Token::Ident, "after `.` or `:` in a function name")?;
496                    let text = self.text(field.span);
497                    full_name.push(if sep.token == Token::Colon { ':' } else { '.' });
498                    full_name.push_str(text);
499                    let key = Expr {
500                        kind: ExprKind::String(Rc::from(text)),
501                        span: field.span,
502                    };
503                    let span = target.span.to(field.span);
504                    target = Expr {
505                        kind: ExprKind::Index {
506                            object: Box::new(target),
507                            key: Box::new(key),
508                        },
509                        span,
510                    };
511                    if sep.token == Token::Colon {
512                        method = Some(sep.span);
513                        break;
514                    }
515                }
516                let mut func =
517                    self.function_body(Some(Rc::from(full_name)), t, method.is_some())?;
518                if let Some(colon) = method {
519                    // methods get an implicit first parameter, `self`
520                    let id = self.next_name;
521                    self.next_name += 1;
522                    func.params.insert(
523                        0,
524                        Name {
525                            text: Rc::from("self"),
526                            id,
527                            span: colon,
528                        },
529                    );
530                    func.param_types.insert(0, None);
531                }
532                let span = func.span;
533                Ok(stmt(
534                    StmtKind::Function {
535                        target,
536                        func: Rc::new(func),
537                    },
538                    span,
539                ))
540            }
541            Token::Ident if self.type_alias_starts() => self.type_alias(),
542            Token::Ident if self.text(t.span) == "continue" && self.continue_is_statement() => {
543                self.bump();
544                Ok(stmt(StmtKind::Continue, t.span))
545            }
546            _ => self.expr_statement(),
547        }
548    }
549
550    /// `continue` is only a keyword in context in Luau. It's a statement unless
551    /// what follows makes it a normal name (`continue = 1`, `continue(...)`).
552    fn continue_is_statement(&self) -> bool {
553        !matches!(
554            self.peek_nth(1).token,
555            Token::Eq
556                | Token::Comma
557                | Token::LParen
558                | Token::Dot
559                | Token::LBracket
560                | Token::Colon
561                | Token::String
562                | Token::LBrace
563                | Token::PlusEq
564                | Token::MinusEq
565                | Token::StarEq
566                | Token::SlashEq
567                | Token::SlashSlashEq
568                | Token::PercentEq
569                | Token::CaretEq
570                | Token::DotDotEq
571        )
572    }
573
574    fn if_stmt(&mut self) -> PResult<Stmt> {
575        let kw = self.bump();
576        let mut branches = Vec::new();
577        let cond = self.expr()?;
578        self.expect(Token::Then, "after `if` condition")?;
579        branches.push((cond, self.block()));
580        let mut else_block = None;
581        loop {
582            if self.eat(Token::Elseif).is_some() {
583                let cond = self.expr()?;
584                self.expect(Token::Then, "after `elseif` condition")?;
585                branches.push((cond, self.block()));
586            } else if self.eat(Token::Else).is_some() {
587                else_block = Some(self.block());
588                break;
589            } else {
590                break;
591            }
592        }
593        let end = self.expect_closer(Token::End, kw, "if")?;
594        Ok(Stmt {
595            kind: StmtKind::If {
596                branches,
597                else_block,
598            },
599            span: kw.span.to(end.span),
600        })
601    }
602
603    fn for_stmt(&mut self) -> PResult<Stmt> {
604        let kw = self.bump();
605        let (mut names, mut types) = self.binding_list("after `for`")?;
606        if names.len() > 1 || self.at(Token::In) {
607            self.expect(Token::In, "after the `for` variables")?;
608            let exprs = self.expr_list()?;
609            self.expect(Token::Do, "after the `for ... in` list")?;
610            let body = self.block();
611            let end = self.expect_closer(Token::End, kw, "for")?;
612            return Ok(Stmt {
613                kind: StmtKind::GenericFor {
614                    names,
615                    types,
616                    exprs,
617                    body,
618                },
619                span: kw.span.to(end.span),
620            });
621        }
622        let var = names.pop().expect("one name");
623        let var_type = types.pop().expect("one type slot").map(Box::new);
624        self.expect(Token::Eq, "in numeric `for` (`for i = start, limit do`)")?;
625        let start = self.expr()?;
626        self.expect(Token::Comma, "after the `for` start value")?;
627        let limit = self.expr()?;
628        let step = if self.eat(Token::Comma).is_some() {
629            Some(self.expr()?)
630        } else {
631            None
632        };
633        self.expect(Token::Do, "after the `for` range")?;
634        let body = self.block();
635        let end = self.expect_closer(Token::End, kw, "for")?;
636        Ok(Stmt {
637            kind: StmtKind::NumericFor {
638                var,
639                var_type,
640                start,
641                limit,
642                step,
643                body,
644            },
645            span: kw.span.to(end.span),
646        })
647    }
648
649    /// Assignment or compound assignment. A bare expression is an error, only
650    /// calls can stand alone.
651    fn expr_statement(&mut self) -> PResult<Stmt> {
652        let first = self.peek();
653        if !matches!(first.token, Token::Ident | Token::LParen) {
654            return Err(error(
655                format!("expected a statement, found {}", first.token.describe()),
656                first.span,
657            )
658            .with_label_boxed("expected a statement"));
659        }
660        let target = self.expr()?;
661
662        if let ExprKind::Call { .. } | ExprKind::MethodCall { .. } = target.kind
663            && !matches!(self.peek().token, Token::Eq | Token::Comma)
664            && compound_op(self.peek().token).is_none()
665        {
666            let span = target.span;
667            return Ok(Stmt {
668                kind: StmtKind::Call(target),
669                span,
670            });
671        }
672
673        if let Some(op) = compound_op(self.peek().token) {
674            let op_tok = self.bump();
675            self.check_assignable(&target)?;
676            let value = self.expr()?;
677            let span = target.span.to(value.span);
678            return Ok(Stmt {
679                kind: StmtKind::CompoundAssign {
680                    op,
681                    op_span: op_tok.span,
682                    target,
683                    value,
684                },
685                span,
686            });
687        }
688
689        if matches!(self.peek().token, Token::Eq | Token::Comma) {
690            self.check_assignable(&target)?;
691            let mut targets = vec![target];
692            while self.eat(Token::Comma).is_some() {
693                let t = self.expr()?;
694                self.check_assignable(&t)?;
695                targets.push(t);
696            }
697            self.expect(Token::Eq, "in assignment")?;
698            let values = self.expr_list()?;
699            let span = targets[0].span.to(values.last().unwrap().span);
700            return Ok(Stmt {
701                kind: StmtKind::Assign { targets, values },
702                span,
703            });
704        }
705
706        Err(
707            error("incomplete statement: expected an assignment", target.span)
708                .with_label_boxed("this expression's value is never used")
709                .with_help_boxed("only assignments and function calls can be statements"),
710        )
711    }
712
713    /// `name[: T], name[: T], ...` (locals and `for` variables).
714    fn binding_list(&mut self, context: &str) -> PResult<(Vec<Name>, Vec<Option<TypeExpr>>)> {
715        let mut names = Vec::new();
716        let mut types = Vec::new();
717        loop {
718            names.push(self.name(context)?);
719            types.push(if self.eat(Token::Colon).is_some() {
720                Some(self.type_expr()?)
721            } else {
722                None
723            });
724            if self.eat(Token::Comma).is_none() {
725                return Ok((names, types));
726            }
727        }
728    }
729
730    /// Parses `<T>(params): R body end` after the `function` keyword (and
731    /// name). `is_method` means it was declared with `:` (the caller adds
732    /// `self`).
733    fn function_body(
734        &mut self,
735        name: Option<Rc<str>>,
736        kw: Spanned,
737        is_method: bool,
738    ) -> PResult<FunctionBody> {
739        // an error in the header would leave the body's `end` behind as a stray
740        // closer, so skip the whole function
741        let header = self.function_header();
742        let (generics, params, param_types, is_vararg, vararg_type, return_type) = match header {
743            Ok(h) => h,
744            Err(d) => {
745                self.skip_to_end(1);
746                return Err(d);
747            }
748        };
749        let body = self.block();
750        let end = self.expect_closer(Token::End, kw, "function")?;
751        Ok(FunctionBody {
752            generics,
753            params,
754            param_types,
755            is_vararg,
756            vararg_type,
757            return_type,
758            is_method,
759            body,
760            name,
761            span: kw.span.to(end.span),
762        })
763    }
764
765    /// Skips to the `end` (or `until`) matching `open` block openers that were
766    /// already eaten.
767    fn skip_to_end(&mut self, open: u32) {
768        let mut depth = open;
769        loop {
770            match self.peek().token {
771                Token::Eof => return,
772                Token::If | Token::Do | Token::Function | Token::Repeat => depth += 1,
773                Token::End | Token::Until => {
774                    depth -= 1;
775                    if depth == 0 {
776                        self.bump();
777                        return;
778                    }
779                }
780                _ => {}
781            }
782            self.bump();
783        }
784    }
785
786    #[allow(clippy::type_complexity)]
787    fn function_header(
788        &mut self,
789    ) -> PResult<(
790        Vec<GenericParam>,
791        Vec<Name>,
792        Vec<Option<TypeExpr>>,
793        bool,
794        Option<TypeExpr>,
795        Option<TypePack>,
796    )> {
797        let generics = self.generic_params(false)?;
798        self.expect(Token::LParen, "to start the parameter list")?;
799        let mut params = Vec::new();
800        let mut param_types = Vec::new();
801        let mut is_vararg = false;
802        let mut vararg_type = None;
803        if !self.at(Token::RParen) {
804            loop {
805                if self.eat(Token::Ellipsis).is_some() {
806                    is_vararg = true;
807                    if self.eat(Token::Colon).is_some() {
808                        vararg_type = Some(self.variadic_type()?);
809                    }
810                    break;
811                }
812                params.push(self.name("in parameter list")?);
813                param_types.push(if self.eat(Token::Colon).is_some() {
814                    Some(self.type_expr()?)
815                } else {
816                    None
817                });
818                if self.eat(Token::Comma).is_none() {
819                    break;
820                }
821            }
822        }
823        self.expect(Token::RParen, "to close the parameter list")?;
824        let return_type = if self.eat(Token::Colon).is_some() {
825            Some(self.return_pack()?)
826        } else {
827            None
828        };
829        Ok((
830            generics,
831            params,
832            param_types,
833            is_vararg,
834            vararg_type,
835            return_type,
836        ))
837    }
838
839    // ─ Types ─────────────────────────────────────────────────────────────────
840
841    /// `expr :: T`. Binds tighter than any binary operator, like Luau.
842    fn cast_expr(&mut self) -> PResult<Expr> {
843        let mut e = self.simple_expr()?;
844        while self.eat(Token::ColonColon).is_some() {
845            let ty = self.type_expr()?;
846            let span = e.span.to(ty.span);
847            e = Expr {
848                kind: ExprKind::Cast {
849                    expr: Box::new(e),
850                    ty: Box::new(ty),
851                },
852                span,
853            };
854        }
855        Ok(e)
856    }
857
858    /// `type` and `export` are only keywords when a type alias comes next.
859    fn type_alias_starts(&self) -> bool {
860        match self.text(self.peek().span) {
861            "type" => self.peek_nth(1).token == Token::Ident,
862            "export" => {
863                self.peek_nth(1).token == Token::Ident
864                    && self.text(self.peek_nth(1).span) == "type"
865                    && self.peek_nth(2).token == Token::Ident
866            }
867            _ => false,
868        }
869    }
870
871    /// `[export] type Name<T, U> = Type`
872    fn type_alias(&mut self) -> PResult<Stmt> {
873        let first = self.bump();
874        let exported = self.text(first.span) == "export";
875        if exported {
876            self.bump();
877        }
878        let name = self.expect(Token::Ident, "after `type`")?;
879        let generics = self.generic_params(true)?;
880        self.expect(Token::Eq, "after the type's name")?;
881        let ty = self.type_expr()?;
882        let span = first.span.to(ty.span);
883        Ok(Stmt {
884            kind: StmtKind::TypeAlias(Rc::new(TypeAlias {
885                name: Rc::from(self.text(name.span)),
886                name_span: name.span,
887                generics,
888                ty,
889                exported,
890            })),
891            span,
892        })
893    }
894
895    /// `<T, U...>`, or nothing. Defaults (`<T = string>`) only when `defaults`
896    /// is set (type aliases).
897    fn generic_params(&mut self, defaults: bool) -> PResult<Vec<GenericParam>> {
898        let mut out: Vec<GenericParam> = Vec::new();
899        if self.eat(Token::Lt).is_none() {
900            return Ok(out);
901        }
902        loop {
903            let t = self.expect(Token::Ident, "in a generic parameter list")?;
904            let pack = self.eat(Token::Ellipsis).is_some();
905            if !pack && out.iter().any(|g| g.pack) {
906                return Err(error(
907                    "generic type parameters must come before type packs",
908                    t.span,
909                )
910                .with_label_boxed("move this before the packs"));
911            }
912            let default = if let Some(eq) = self.eat(Token::Eq) {
913                if !defaults {
914                    return Err(error(
915                        "default type parameters are only allowed in type aliases",
916                        eq.span,
917                    )
918                    .with_label_boxed("not allowed here"));
919                }
920                Some(if pack {
921                    self.type_arg()?
922                } else {
923                    self.type_expr()?
924                })
925            } else {
926                if out.iter().any(|g| g.default.is_some()) {
927                    return Err(error(
928                        "generic parameters after one with a default need defaults too",
929                        t.span,
930                    )
931                    .with_label_boxed("needs a default"));
932                }
933                None
934            };
935            out.push(GenericParam {
936                name: Rc::from(self.text(t.span)),
937                span: t.span,
938                pack,
939                default,
940            });
941            if self.eat(Token::Comma).is_none() {
942                break;
943            }
944        }
945        self.expect(Token::Gt, "to close the generic parameter list")?;
946        Ok(out)
947    }
948
949    /// `T...` at the cursor (a generic pack named in a variadic slot).
950    fn at_generic_pack(&self) -> bool {
951        self.at(Token::Ident) && self.peek_nth(1).token == Token::Ellipsis
952    }
953
954    fn generic_pack(&mut self) -> PResult<TypeExpr> {
955        let name = self.bump();
956        let dots = self.bump();
957        Ok(TypeExpr {
958            kind: TypeKind::GenericPack(Rc::from(self.text(name.span))),
959            span: name.span.to(dots.span),
960        })
961    }
962
963    /// What can come after `...:` or `...`: a type, or a generic pack `T...`.
964    fn variadic_type(&mut self) -> PResult<TypeExpr> {
965        if self.at_generic_pack() {
966            self.generic_pack()
967        } else {
968            self.type_expr()
969        }
970    }
971
972    /// One type alias argument, a type or a pack (`(A, B)`, `()`, `...T`,
973    /// `T...`).
974    fn type_arg(&mut self) -> PResult<TypeExpr> {
975        let start = self.peek().span;
976        if self.eat(Token::Ellipsis).is_some() {
977            let t = self.type_expr()?;
978            return Ok(TypeExpr {
979                span: start.to(t.span),
980                kind: TypeKind::Pack(TypePack {
981                    types: Vec::new(),
982                    variadic: Some(Box::new(t)),
983                    span: start,
984                }),
985            });
986        }
987        if self.at_generic_pack() {
988            return self.generic_pack();
989        }
990        if self.at(Token::LParen) {
991            let (pos, names) = (self.pos, self.next_name);
992            self.bump();
993            let (params, variadic) = self.type_param_list()?;
994            let close = self.expect(Token::RParen, "to close the type pack")?;
995            let pack_like = !matches!(
996                self.peek().token,
997                Token::Arrow | Token::Pipe | Token::Amp | Token::Question
998            );
999            if pack_like && params.iter().all(|p| p.name.is_none()) {
1000                let span = start.to(close.span);
1001                return Ok(TypeExpr {
1002                    span,
1003                    kind: TypeKind::Pack(TypePack {
1004                        types: params.into_iter().map(|p| p.ty).collect(),
1005                        variadic,
1006                        span,
1007                    }),
1008                });
1009            }
1010            self.pos = pos;
1011            self.next_name = names;
1012        }
1013        self.type_expr()
1014    }
1015
1016    pub(crate) fn type_expr(&mut self) -> PResult<TypeExpr> {
1017        self.depth += 1;
1018        if self.depth > MAX_DEPTH {
1019            self.depth -= 1;
1020            return Err(error("type nests too deeply", self.peek().span)
1021                .with_label_boxed(format!("nesting limit of {MAX_DEPTH} reached here")));
1022        }
1023        let result = grow(|| self.type_expr_inner());
1024        self.depth -= 1;
1025        result
1026    }
1027
1028    /// Unions and intersections (a leading `|` or `&` is fine). Mixing the two
1029    /// needs parentheses.
1030    fn type_expr_inner(&mut self) -> PResult<TypeExpr> {
1031        let lead = self.peek().token;
1032        if matches!(lead, Token::Pipe | Token::Amp) {
1033            self.bump();
1034        }
1035        let first = self.optional_type()?;
1036        let sep = match self.peek().token {
1037            Token::Pipe | Token::Amp => self.peek().token,
1038            _ if matches!(lead, Token::Pipe | Token::Amp) => lead,
1039            _ => return Ok(first),
1040        };
1041        let mut parts = vec![first];
1042        while self.eat(sep).is_some() {
1043            parts.push(self.optional_type()?);
1044        }
1045        if matches!(self.peek().token, Token::Pipe | Token::Amp) {
1046            return Err(error(
1047                "mixing `|` and `&` in one type needs parentheses",
1048                self.peek().span,
1049            )
1050            .with_label_boxed("ambiguous"));
1051        }
1052        let span = parts[0].span.to(parts.last().unwrap().span);
1053        if parts.len() == 1 {
1054            return Ok(parts.pop().unwrap());
1055        }
1056        Ok(TypeExpr {
1057            kind: if sep == Token::Pipe {
1058                TypeKind::Union(parts)
1059            } else {
1060                TypeKind::Intersection(parts)
1061            },
1062            span,
1063        })
1064    }
1065
1066    fn optional_type(&mut self) -> PResult<TypeExpr> {
1067        let mut t = self.primary_type()?;
1068        while let Some(q) = self.eat(Token::Question) {
1069            t = TypeExpr {
1070                span: t.span.to(q.span),
1071                kind: TypeKind::Optional(Box::new(t)),
1072            };
1073        }
1074        Ok(t)
1075    }
1076
1077    fn primary_type(&mut self) -> PResult<TypeExpr> {
1078        let tok = self.peek();
1079        let simple = |kind| TypeExpr {
1080            kind,
1081            span: tok.span,
1082        };
1083        match tok.token {
1084            Token::Nil => {
1085                self.bump();
1086                Ok(simple(TypeKind::Name {
1087                    name: Rc::from("nil"),
1088                    args: Vec::new(),
1089                }))
1090            }
1091            Token::True | Token::False => {
1092                self.bump();
1093                Ok(simple(TypeKind::Singleton(Singleton::Bool(
1094                    tok.token == Token::True,
1095                ))))
1096            }
1097            Token::String => {
1098                self.bump();
1099                let text = strings::decode(self.text(tok.span), tok.span).map_err(Box::new)?;
1100                Ok(simple(TypeKind::Singleton(Singleton::String(Rc::from(
1101                    text,
1102                )))))
1103            }
1104            Token::Ident
1105                if self.text(tok.span) == "typeof" && self.peek_nth(1).token == Token::LParen =>
1106            {
1107                self.bump();
1108                self.bump();
1109                let e = self.expr()?;
1110                let close = self.expect(Token::RParen, "to close `typeof(`")?;
1111                Ok(TypeExpr {
1112                    kind: TypeKind::Typeof(Box::new(e)),
1113                    span: tok.span.to(close.span),
1114                })
1115            }
1116            Token::Ident => {
1117                self.bump();
1118                let mut name = self.text(tok.span).to_string();
1119                let mut span = tok.span;
1120                // `module.Type`, kept as one dotted name
1121                if self.at(Token::Dot) && self.peek_nth(1).token == Token::Ident {
1122                    self.bump();
1123                    let field = self.bump();
1124                    name.push('.');
1125                    name.push_str(self.text(field.span));
1126                    span = span.to(field.span);
1127                }
1128                let mut args = Vec::new();
1129                if self.eat(Token::Lt).is_some() {
1130                    loop {
1131                        args.push(self.type_arg()?);
1132                        if self.eat(Token::Comma).is_none() {
1133                            break;
1134                        }
1135                    }
1136                    span = span.to(self.expect(Token::Gt, "to close the type arguments")?.span);
1137                }
1138                Ok(TypeExpr {
1139                    kind: TypeKind::Name {
1140                        name: Rc::from(name),
1141                        args,
1142                    },
1143                    span,
1144                })
1145            }
1146            Token::LBrace => self.table_type(),
1147            Token::LParen | Token::Lt => self.function_type_or_group(),
1148            other => Err(error(
1149                format!("expected a type, found {}", other.describe()),
1150                tok.span,
1151            )
1152            .with_label_boxed("expected a type")),
1153        }
1154    }
1155
1156    /// `{T}`, `{ name: T, [K]: V }`.
1157    fn table_type(&mut self) -> PResult<TypeExpr> {
1158        let open = self.bump();
1159        let mut props = Vec::new();
1160        let mut indexer: Option<Box<(TypeExpr, TypeExpr)>> = None;
1161        // `read name: T` / `write name: T` (contextual words)
1162        let modifier = |p: &Self| {
1163            p.at(Token::Ident)
1164                && matches!(p.text(p.peek().span), "read" | "write")
1165                && (p.peek_nth(1).token == Token::Ident || p.peek_nth(1).token == Token::LBracket)
1166        };
1167        let is_entry = |p: &Self| {
1168            p.at(Token::LBracket)
1169                || (p.at(Token::Ident) && p.peek_nth(1).token == Token::Colon)
1170                || modifier(p)
1171        };
1172        if !self.at(Token::RBrace) && !is_entry(self) {
1173            // `{T}`, an array
1174            let elem = self.type_expr()?;
1175            let close = self.expect(Token::RBrace, "to close the array type `{T}`")?;
1176            let key = TypeExpr {
1177                kind: TypeKind::Name {
1178                    name: Rc::from("number"),
1179                    args: Vec::new(),
1180                },
1181                span: elem.span,
1182            };
1183            return Ok(TypeExpr {
1184                kind: TypeKind::Table {
1185                    props,
1186                    indexer: Some(Box::new((key, elem))),
1187                },
1188                span: open.span.to(close.span),
1189            });
1190        }
1191        while !self.at(Token::RBrace) {
1192            let access = if modifier(self) {
1193                let word = self.bump();
1194                if self.text(word.span) == "read" {
1195                    Access::Read
1196                } else {
1197                    Access::Write
1198                }
1199            } else {
1200                Access::ReadWrite
1201            };
1202            if self.at(Token::LBracket) {
1203                let lb = self.bump();
1204                let key = self.type_expr()?;
1205                self.expect(Token::RBracket, "to close `[` in a table type")?;
1206                self.expect(Token::Colon, "after `[key]` in a table type")?;
1207                let value = self.type_expr()?;
1208                match key.kind {
1209                    // `["name"]: T` is a property, not an indexer
1210                    TypeKind::Singleton(Singleton::String(name)) => props.push(TableProp {
1211                        name,
1212                        span: lb.span.to(value.span),
1213                        ty: value,
1214                        access,
1215                    }),
1216                    _ => {
1217                        if access != Access::ReadWrite {
1218                            return Err(error(
1219                                "`read` and `write` apply to properties, not indexers",
1220                                lb.span,
1221                            )
1222                            .with_label_boxed("an indexer"));
1223                        }
1224                        if indexer.is_some() {
1225                            return Err(error("a table type can have only one indexer", lb.span)
1226                                .with_label_boxed("second indexer"));
1227                        }
1228                        indexer = Some(Box::new((key, value)));
1229                    }
1230                }
1231            } else if self.at(Token::Ident) && self.peek_nth(1).token == Token::Colon {
1232                let name = self.bump();
1233                self.bump();
1234                let ty = self.type_expr()?;
1235                props.push(TableProp {
1236                    name: Rc::from(self.text(name.span)),
1237                    span: name.span.to(ty.span),
1238                    ty,
1239                    access,
1240                });
1241            } else {
1242                let t = self.peek();
1243                return Err(error(
1244                    format!(
1245                        "expected a property (`name: type`) or an indexer (`[key]: type`), found {}",
1246                        t.token.describe()
1247                    ),
1248                    t.span,
1249                )
1250                .with_label_boxed("expected a table type entry"));
1251            }
1252            if self.eat(Token::Comma).is_none() && self.eat(Token::Semi).is_none() {
1253                break;
1254            }
1255        }
1256        let close = self.expect(Token::RBrace, "to close the table type")?;
1257        Ok(TypeExpr {
1258            kind: TypeKind::Table { props, indexer },
1259            span: open.span.to(close.span),
1260        })
1261    }
1262
1263    /// `(A, B) -> R`, `<T>(T) -> T`, or a parenthesised type `(A | B)`.
1264    fn function_type_or_group(&mut self) -> PResult<TypeExpr> {
1265        let start = self.peek().span;
1266        let generics = self.generic_params(false)?;
1267        self.expect(Token::LParen, "to start a function type's parameters")?;
1268        let (params, variadic) = self.type_param_list()?;
1269        let close = self.expect(Token::RParen, "to close the parameter types")?;
1270        if self.eat(Token::Arrow).is_some() {
1271            let returns = self.return_pack()?;
1272            return Ok(TypeExpr {
1273                span: start.to(returns.span),
1274                kind: TypeKind::Function {
1275                    generics,
1276                    params,
1277                    variadic,
1278                    returns,
1279                },
1280            });
1281        }
1282        if generics.is_empty()
1283            && variadic.is_none()
1284            && params.len() == 1
1285            && let [FnParam { name: None, .. }] = params.as_slice()
1286        {
1287            let mut t = params.into_iter().next().unwrap().ty;
1288            t.span = start.to(close.span);
1289            return Ok(t);
1290        }
1291        Err(error(
1292            format!(
1293                "expected `->` after a function type's parameters, found {}",
1294                self.peek().token.describe()
1295            ),
1296            self.peek().span,
1297        )
1298        .with_label_boxed("expected `->`"))
1299    }
1300
1301    /// The inside of `( ... )` in a function type: `a: T, U, ...V`.
1302    fn type_param_list(&mut self) -> PResult<(Vec<FnParam>, Option<Box<TypeExpr>>)> {
1303        let mut params = Vec::new();
1304        let mut variadic = None;
1305        if self.at(Token::RParen) {
1306            return Ok((params, variadic));
1307        }
1308        loop {
1309            if self.eat(Token::Ellipsis).is_some() {
1310                variadic = Some(Box::new(self.type_expr()?));
1311                break;
1312            }
1313            if self.at_generic_pack() {
1314                variadic = Some(Box::new(self.generic_pack()?));
1315                break;
1316            }
1317            let name = if self.at(Token::Ident) && self.peek_nth(1).token == Token::Colon {
1318                let n = self.bump();
1319                self.bump();
1320                Some(Rc::from(self.text(n.span)))
1321            } else {
1322                None
1323            };
1324            let ty = self.type_expr()?;
1325            params.push(FnParam { name, ty });
1326            if self.eat(Token::Comma).is_none() {
1327                break;
1328            }
1329        }
1330        Ok((params, variadic))
1331    }
1332
1333    /// A function's results: `T`, `(A, B)`, `()`, `...T`, or a function type
1334    /// `(A) -> B` (which `(` alone can't tell apart from a pack).
1335    fn return_pack(&mut self) -> PResult<TypePack> {
1336        let start = self.peek().span;
1337        if self.at_generic_pack() {
1338            let t = self.generic_pack()?;
1339            return Ok(TypePack {
1340                span: t.span,
1341                types: Vec::new(),
1342                variadic: Some(Box::new(t)),
1343            });
1344        }
1345        if self.eat(Token::Ellipsis).is_some() {
1346            let t = self.type_expr()?;
1347            return Ok(TypePack {
1348                span: start.to(t.span),
1349                types: Vec::new(),
1350                variadic: Some(Box::new(t)),
1351            });
1352        }
1353        if self.at(Token::LParen) {
1354            let (pos, names) = (self.pos, self.next_name);
1355            self.bump();
1356            let (params, variadic) = self.type_param_list()?;
1357            let close = self.expect(Token::RParen, "to close the result types")?;
1358            if self.at(Token::Arrow)
1359                || matches!(
1360                    self.peek().token,
1361                    Token::Pipe | Token::Amp | Token::Question
1362                )
1363            {
1364                // it was a function type or a parenthesised type after all
1365                self.pos = pos;
1366                self.next_name = names;
1367            } else {
1368                if let Some(p) = params.iter().find(|p| p.name.is_some()) {
1369                    return Err(error("result types can't be named", p.ty.span)
1370                        .with_label_boxed("remove the name"));
1371                }
1372                return Ok(TypePack {
1373                    types: params.into_iter().map(|p| p.ty).collect(),
1374                    variadic,
1375                    span: start.to(close.span),
1376                });
1377            }
1378        }
1379        let t = self.type_expr()?;
1380        Ok(TypePack {
1381            span: t.span,
1382            types: vec![t],
1383            variadic: None,
1384        })
1385    }
1386
1387    fn check_assignable(&self, target: &Expr) -> PResult<()> {
1388        match target.kind {
1389            ExprKind::Name(_) | ExprKind::Index { .. } => Ok(()),
1390            _ => Err(error("cannot assign to this expression", target.span)
1391                .with_label_boxed("only variables can be assigned to")),
1392        }
1393    }
1394
1395    // ─ Expressions (Pratt) ───────────────────────────────────────────────────
1396
1397    fn expr_list(&mut self) -> PResult<Vec<Expr>> {
1398        let mut values = vec![self.expr()?];
1399        while self.eat(Token::Comma).is_some() {
1400            values.push(self.expr()?);
1401        }
1402        Ok(values)
1403    }
1404
1405    fn expr(&mut self) -> PResult<Expr> {
1406        self.expr_bp(0)
1407    }
1408
1409    fn too_deep(&self) -> Box<Diagnostic> {
1410        error("expression nests too deeply", self.peek().span)
1411            .with_label_boxed(format!("nesting limit of {MAX_DEPTH} reached here"))
1412    }
1413
1414    fn expr_bp(&mut self, min_bp: u8) -> PResult<Expr> {
1415        self.depth += 1;
1416        if self.depth > MAX_DEPTH {
1417            self.depth -= 1;
1418            return Err(self.too_deep());
1419        }
1420        let result = grow(|| self.expr_bp_inner(min_bp));
1421        self.depth -= 1;
1422        result
1423    }
1424
1425    fn expr_bp_inner(&mut self, min_bp: u8) -> PResult<Expr> {
1426        let mut lhs = match unary_op(self.peek().token) {
1427            Some(op) => {
1428                let op_tok = self.bump();
1429                let operand = self.expr_bp(UNARY_BP)?;
1430                Expr {
1431                    span: op_tok.span.to(operand.span),
1432                    kind: ExprKind::Unary {
1433                        op,
1434                        op_span: op_tok.span,
1435                        operand: Box::new(operand),
1436                    },
1437                }
1438            }
1439            None => self.cast_expr()?,
1440        };
1441
1442        // left-associative chains (`1 + 1 + 1 ...`) grow the tree without
1443        // recursing, so they count toward the depth limit too. keeps the AST
1444        // depth bounded for later passes (and for `Drop`)
1445        let mut chain = 0;
1446        while let Some(op) = binary_op(self.peek().token) {
1447            let (left_bp, right_bp) = op.binding_power();
1448            if left_bp < min_bp {
1449                break;
1450            }
1451            chain += 1;
1452            if self.depth + chain > MAX_DEPTH {
1453                return Err(self.too_deep());
1454            }
1455            let op_tok = self.bump();
1456            let rhs = self.expr_bp(right_bp)?;
1457            lhs = Expr {
1458                span: lhs.span.to(rhs.span),
1459                kind: ExprKind::Binary {
1460                    op,
1461                    op_span: op_tok.span,
1462                    lhs: Box::new(lhs),
1463                    rhs: Box::new(rhs),
1464                },
1465            };
1466        }
1467        Ok(lhs)
1468    }
1469
1470    /// Splits an interpolated string token into text and holes, lexing and
1471    /// parsing each hole as its own expression. (The caller bumps the token.)
1472    fn interp_string(&mut self, span: Span) -> PResult<ExprKind> {
1473        let raw = self.text(span);
1474        let mut parts = Vec::new();
1475        for piece in rhue_lexer::interp::pieces(raw) {
1476            match piece {
1477                rhue_lexer::interp::Piece::Text(r) => {
1478                    let text = strings::decode_interp_text(
1479                        &raw[r.clone()],
1480                        span.start + rhue_common::offset(r.start),
1481                    )
1482                    .map_err(Box::new)?;
1483                    parts.push(InterpPart::Text(Rc::from(text)));
1484                }
1485                rhue_lexer::interp::Piece::Hole(r) => {
1486                    let start = span.start + rhue_common::offset(r.start);
1487                    let hole = Span::new(start - 1, span.start + rhue_common::offset(r.end) + 1);
1488                    if raw[r.clone()].starts_with('{') {
1489                        return Err(Box::new(
1490                            Diagnostic::error(
1491                                "double braces aren't allowed in an interpolated string",
1492                                hole,
1493                            )
1494                            .with_label("use `\\{` for a literal brace"),
1495                        ));
1496                    }
1497                    parts.push(InterpPart::Expr(self.hole(&raw[r.clone()], start, hole)?));
1498                }
1499            }
1500        }
1501        if !parts.iter().any(|p| matches!(p, InterpPart::Expr(_))) {
1502            let text: String = parts
1503                .iter()
1504                .map(|p| match p {
1505                    InterpPart::Text(t) => &**t,
1506                    InterpPart::Expr(_) => "",
1507                })
1508                .collect();
1509            return Ok(ExprKind::String(Rc::from(text)));
1510        }
1511        Ok(ExprKind::Interp(parts))
1512    }
1513
1514    /// Parses the expression inside one `{...}` hole, starting at byte `start`
1515    /// of the source.
1516    fn hole(&mut self, text: &str, start: u32, hole: Span) -> PResult<Expr> {
1517        let lexed = rhue_lexer::lex(text);
1518        let shift = |s: Span| Span::new(s.start + start, s.end + start);
1519        if let Some(mut e) = lexed.errors.into_iter().next() {
1520            e.primary.span = shift(e.primary.span);
1521            for label in &mut e.secondary {
1522                label.span = shift(label.span);
1523            }
1524            return Err(Box::new(e));
1525        }
1526        let tokens: Vec<Spanned> = lexed
1527            .tokens
1528            .into_iter()
1529            .map(|t| Spanned {
1530                token: t.token,
1531                span: shift(t.span),
1532            })
1533            .collect();
1534        if tokens.len() == 1 {
1535            return Err(Box::new(
1536                Diagnostic::error("empty `{}` in an interpolated string", hole)
1537                    .with_label("expected an expression"),
1538            ));
1539        }
1540        let mut sub = Parser {
1541            source: self.source,
1542            tokens,
1543            pos: 0,
1544            depth: self.depth,
1545            next_name: self.next_name,
1546            errors: Vec::new(),
1547        };
1548        let result = sub.expr().and_then(|e| {
1549            sub.expect(Token::Eof, "in an interpolated string's `{}`")?;
1550            Ok(e)
1551        });
1552        self.next_name = sub.next_name;
1553        self.errors.append(&mut sub.errors);
1554        result
1555    }
1556
1557    fn simple_expr(&mut self) -> PResult<Expr> {
1558        let tok = self.peek();
1559        let kind = match tok.token {
1560            Token::Number(n) => ExprKind::Number(n),
1561            Token::Nil => ExprKind::Nil,
1562            Token::True => ExprKind::Bool(true),
1563            Token::False => ExprKind::Bool(false),
1564            Token::String => {
1565                let text = strings::decode(self.text(tok.span), tok.span).map_err(Box::new)?;
1566                ExprKind::String(Rc::from(text))
1567            }
1568            Token::InterpString => self.interp_string(tok.span)?,
1569            Token::Ident => {
1570                self.bump();
1571                let name = self.new_name(tok.span);
1572                return self.suffixes(Expr {
1573                    kind: ExprKind::Name(name),
1574                    span: tok.span,
1575                });
1576            }
1577            Token::If => return self.if_expr(),
1578            Token::LParen => {
1579                let open = self.bump();
1580                let inner = self.expr()?;
1581                let close = self.eat(Token::RParen).ok_or_else(|| {
1582                    let found = self.peek();
1583                    Box::new(
1584                        Diagnostic::error(
1585                            format!(
1586                                "expected `)` to close `(`, found {}",
1587                                found.token.describe()
1588                            ),
1589                            found.span,
1590                        )
1591                        .with_label("expected `)`")
1592                        .with_secondary(open.span, "unclosed `(` opened here"),
1593                    )
1594                })?;
1595                return self.suffixes(Expr {
1596                    span: open.span.to(close.span),
1597                    kind: ExprKind::Group(Box::new(inner)),
1598                });
1599            }
1600            Token::LBrace => return self.table_constructor(),
1601            Token::Function => {
1602                let kw = self.bump();
1603                let func = self.function_body(None, kw, false)?;
1604                return Ok(Expr {
1605                    span: func.span,
1606                    kind: ExprKind::Function(Rc::new(func)),
1607                });
1608            }
1609            Token::Ellipsis => ExprKind::Vararg,
1610            other => {
1611                return Err(error(
1612                    format!("expected an expression, found {}", other.describe()),
1613                    tok.span,
1614                )
1615                .with_label_boxed("expected an expression"));
1616            }
1617        };
1618        self.bump();
1619        let expr = Expr {
1620            kind,
1621            span: tok.span,
1622        };
1623        if matches!(expr.kind, ExprKind::String(_)) {
1624            return self.no_suffix(expr);
1625        }
1626        Ok(expr)
1627    }
1628
1629    /// Call and index suffixes after a name or parenthesised expression:
1630    /// `f(a)`, `f "s"`, `f(a)(b)`, `t.x[k]`.
1631    fn suffixes(&mut self, mut expr: Expr) -> PResult<Expr> {
1632        loop {
1633            match self.peek().token {
1634                Token::LParen => {
1635                    self.bump();
1636                    let args = if self.at(Token::RParen) {
1637                        Vec::new()
1638                    } else {
1639                        self.expr_list()?
1640                    };
1641                    let close = self.expect(Token::RParen, "to close the argument list")?;
1642                    let span = expr.span.to(close.span);
1643                    expr = Expr {
1644                        kind: ExprKind::Call {
1645                            callee: Box::new(expr),
1646                            args,
1647                        },
1648                        span,
1649                    };
1650                }
1651                Token::String => {
1652                    let t = self.bump();
1653                    let text = strings::decode(self.text(t.span), t.span).map_err(Box::new)?;
1654                    let arg = Expr {
1655                        kind: ExprKind::String(Rc::from(text)),
1656                        span: t.span,
1657                    };
1658                    let span = expr.span.to(t.span);
1659                    expr = Expr {
1660                        kind: ExprKind::Call {
1661                            callee: Box::new(expr),
1662                            args: vec![arg],
1663                        },
1664                        span,
1665                    };
1666                }
1667                Token::LBrace => {
1668                    let arg = self.table_constructor()?;
1669                    let span = expr.span.to(arg.span);
1670                    expr = Expr {
1671                        kind: ExprKind::Call {
1672                            callee: Box::new(expr),
1673                            args: vec![arg],
1674                        },
1675                        span,
1676                    };
1677                }
1678                Token::Dot => {
1679                    self.bump();
1680                    let field = self.expect(Token::Ident, "after `.`")?;
1681                    let key = Expr {
1682                        kind: ExprKind::String(Rc::from(self.text(field.span))),
1683                        span: field.span,
1684                    };
1685                    let span = expr.span.to(field.span);
1686                    expr = Expr {
1687                        kind: ExprKind::Index {
1688                            object: Box::new(expr),
1689                            key: Box::new(key),
1690                        },
1691                        span,
1692                    };
1693                }
1694                Token::LBracket => {
1695                    self.bump();
1696                    let key = self.expr()?;
1697                    let close = self.expect(Token::RBracket, "to close `[`")?;
1698                    let span = expr.span.to(close.span);
1699                    expr = Expr {
1700                        kind: ExprKind::Index {
1701                            object: Box::new(expr),
1702                            key: Box::new(key),
1703                        },
1704                        span,
1705                    };
1706                }
1707                Token::Colon => {
1708                    self.bump();
1709                    let name = self.expect(Token::Ident, "after `:` (a method name)")?;
1710                    let method: Rc<str> = Rc::from(self.text(name.span));
1711                    let (args, end) = match self.peek().token {
1712                        Token::LParen => {
1713                            self.bump();
1714                            let args = if self.at(Token::RParen) {
1715                                Vec::new()
1716                            } else {
1717                                self.expr_list()?
1718                            };
1719                            (
1720                                args,
1721                                self.expect(Token::RParen, "to close the argument list")?
1722                                    .span,
1723                            )
1724                        }
1725                        Token::String => {
1726                            let t = self.bump();
1727                            let text =
1728                                strings::decode(self.text(t.span), t.span).map_err(Box::new)?;
1729                            (
1730                                vec![Expr {
1731                                    kind: ExprKind::String(Rc::from(text)),
1732                                    span: t.span,
1733                                }],
1734                                t.span,
1735                            )
1736                        }
1737                        Token::LBrace => {
1738                            let t = self.table_constructor()?;
1739                            let span = t.span;
1740                            (vec![t], span)
1741                        }
1742                        other => {
1743                            return Err(error(
1744                                format!(
1745                                    "expected arguments after method `{method}`, found {}",
1746                                    other.describe()
1747                                ),
1748                                self.peek().span,
1749                            )
1750                            .with_label_boxed("expected `(`")
1751                            .with_help_boxed("`a:b` is only valid as a call: `a:b(...)`"));
1752                        }
1753                    };
1754                    let span = expr.span.to(end);
1755                    expr = Expr {
1756                        kind: ExprKind::MethodCall {
1757                            object: Box::new(expr),
1758                            method,
1759                            method_span: name.span,
1760                            args,
1761                        },
1762                        span,
1763                    };
1764                }
1765                _ => return Ok(expr),
1766            }
1767        }
1768    }
1769
1770    /// `{ a, b; name = c, [k] = d, }` (`,` or `;` between, trailing is fine).
1771    fn table_constructor(&mut self) -> PResult<Expr> {
1772        let open = self.bump();
1773        let mut items = Vec::new();
1774        while !self.at(Token::RBrace) {
1775            let item = match self.peek().token {
1776                Token::LBracket => {
1777                    self.bump();
1778                    let key = self.expr()?;
1779                    self.expect(Token::RBracket, "to close `[` in a table key")?;
1780                    self.expect(Token::Eq, "after a `[key]` in a table constructor")?;
1781                    TableItem::Keyed {
1782                        key,
1783                        value: self.expr()?,
1784                    }
1785                }
1786                Token::Ident if self.peek_nth(1).token == Token::Eq => {
1787                    let name = self.bump();
1788                    self.bump();
1789                    let key = Expr {
1790                        kind: ExprKind::String(Rc::from(self.text(name.span))),
1791                        span: name.span,
1792                    };
1793                    TableItem::Keyed {
1794                        key,
1795                        value: self.expr()?,
1796                    }
1797                }
1798                _ => TableItem::Positional(self.expr()?),
1799            };
1800            items.push(item);
1801            if self.eat(Token::Comma).is_none() && self.eat(Token::Semi).is_none() {
1802                break;
1803            }
1804        }
1805        let close = self.eat(Token::RBrace).ok_or_else(|| {
1806            let found = self.peek();
1807            Box::new(
1808                Diagnostic::error(
1809                    format!(
1810                        "expected `}}` to close the table, found {}",
1811                        found.token.describe()
1812                    ),
1813                    found.span,
1814                )
1815                .with_label("expected `}` or `,`")
1816                .with_secondary(open.span, "table opened here"),
1817            )
1818        })?;
1819        Ok(Expr {
1820            kind: ExprKind::Table(items),
1821            span: open.span.to(close.span),
1822        })
1823    }
1824
1825    /// Strings can't be called or indexed without parentheses.
1826    fn no_suffix(&self, expr: Expr) -> PResult<Expr> {
1827        match self.peek().token {
1828            Token::LParen | Token::String | Token::LBrace => Err(error(
1829                "a string literal can't be called directly",
1830                self.peek().span,
1831            )
1832            .with_help_boxed("wrap it in parentheses: `(\"...\")(...)`")),
1833            Token::Dot | Token::LBracket | Token::Colon => Err(error(
1834                "a string literal can't be indexed directly",
1835                self.peek().span,
1836            )
1837            .with_help_boxed("wrap it in parentheses: `(\"...\"):upper()`")),
1838            _ => Ok(expr),
1839        }
1840    }
1841
1842    /// `if c then a elseif c2 then b else d` (the `else` isn't optional).
1843    fn if_expr(&mut self) -> PResult<Expr> {
1844        let kw = self.bump();
1845        let mut branches = Vec::new();
1846        let cond = self.expr()?;
1847        self.expect(Token::Then, "after `if` condition")?;
1848        branches.push((cond, self.expr()?));
1849        while self.eat(Token::Elseif).is_some() {
1850            let cond = self.expr()?;
1851            self.expect(Token::Then, "after `elseif` condition")?;
1852            branches.push((cond, self.expr()?));
1853        }
1854        self.expect(
1855            Token::Else,
1856            "in `if` expression (the `else` branch is required)",
1857        )?;
1858        let else_expr = self.expr()?;
1859        let span = kw.span.to(else_expr.span);
1860        Ok(Expr {
1861            kind: ExprKind::IfElse {
1862                branches,
1863                else_expr: Box::new(else_expr),
1864            },
1865            span,
1866        })
1867    }
1868}
1869
1870trait BoxedDiagnosticExt {
1871    fn with_label_boxed(self, label: impl Into<String>) -> Self;
1872    fn with_help_boxed(self, help: impl Into<String>) -> Self;
1873}
1874
1875impl BoxedDiagnosticExt for Box<Diagnostic> {
1876    fn with_label_boxed(mut self, label: impl Into<String>) -> Self {
1877        self.primary.message = label.into();
1878        self
1879    }
1880
1881    fn with_help_boxed(mut self, help: impl Into<String>) -> Self {
1882        self.help = Some(help.into());
1883        self
1884    }
1885}
1886
1887fn unary_op(token: Token) -> Option<UnOp> {
1888    Some(match token {
1889        Token::Minus => UnOp::Neg,
1890        Token::Not => UnOp::Not,
1891        Token::Hash => UnOp::Len,
1892        _ => return None,
1893    })
1894}
1895
1896fn binary_op(token: Token) -> Option<BinOp> {
1897    Some(match token {
1898        Token::Plus => BinOp::Add,
1899        Token::Minus => BinOp::Sub,
1900        Token::Star => BinOp::Mul,
1901        Token::Slash => BinOp::Div,
1902        Token::SlashSlash => BinOp::IDiv,
1903        Token::Percent => BinOp::Mod,
1904        Token::Caret => BinOp::Pow,
1905        Token::DotDot => BinOp::Concat,
1906        Token::EqEq => BinOp::Eq,
1907        Token::NotEq => BinOp::Ne,
1908        Token::Lt => BinOp::Lt,
1909        Token::LtEq => BinOp::Le,
1910        Token::Gt => BinOp::Gt,
1911        Token::GtEq => BinOp::Ge,
1912        Token::And => BinOp::And,
1913        Token::Or => BinOp::Or,
1914        _ => return None,
1915    })
1916}
1917
1918fn compound_op(token: Token) -> Option<BinOp> {
1919    Some(match token {
1920        Token::PlusEq => BinOp::Add,
1921        Token::MinusEq => BinOp::Sub,
1922        Token::StarEq => BinOp::Mul,
1923        Token::SlashEq => BinOp::Div,
1924        Token::SlashSlashEq => BinOp::IDiv,
1925        Token::PercentEq => BinOp::Mod,
1926        Token::CaretEq => BinOp::Pow,
1927        Token::DotDotEq => BinOp::Concat,
1928        _ => return None,
1929    })
1930}