Skip to main content

rhue_parser/
ast.rs

1use std::fmt;
2use std::rc::Rc;
3
4use rhue_common::Span;
5
6/// One occurrence of a name, a declaration or a use. The parser hands these out
7/// densely from 0, so later passes can keep side tables in a `Vec` indexed by
8/// `NameId` instead of hashing AST nodes.
9pub type NameId = u32;
10
11#[derive(Clone, Debug, PartialEq)]
12pub struct Name {
13    pub text: Rc<str>,
14    pub id: NameId,
15    pub span: Span,
16}
17
18#[derive(Clone, Debug, PartialEq)]
19pub struct Chunk {
20    pub body: Block,
21    pub span: Span,
22    /// How many `NameId`s got handed out, sizes the resolver's tables.
23    pub name_count: u32,
24    /// The `--!strict` / `--!nonstrict` / `--!nocheck` directive, if any.
25    pub mode: Option<(TypeMode, Span)>,
26}
27
28/// How hard a chunk gets type-checked, set by a directive comment at the top of
29/// the file.
30#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
31pub enum TypeMode {
32    /// `--!nocheck`: nothing's checked.
33    NoCheck,
34    /// `--!nonstrict`: anything unannotated is `any`, only definite mismatches
35    /// are errors.
36    NonStrict,
37    /// `--!strict`: also unknown globals, maybe-nil values and so on.
38    Strict,
39}
40
41#[derive(Clone, Debug, PartialEq)]
42pub struct Block {
43    pub stmts: Vec<Stmt>,
44    pub ret: Option<Return>,
45    pub span: Span,
46}
47
48#[derive(Clone, Debug, PartialEq)]
49pub struct Return {
50    pub values: Vec<Expr>,
51    pub span: Span,
52}
53
54#[derive(Clone, Debug, PartialEq)]
55pub struct Stmt {
56    pub kind: StmtKind,
57    pub span: Span,
58}
59
60#[derive(Clone, Debug, PartialEq)]
61pub enum StmtKind {
62    /// `local a, b = 1, 2` (or `local a: number = 1`)
63    Local {
64        names: Vec<Name>,
65        /// One per name, `None` where it's unannotated.
66        types: Vec<Option<TypeExpr>>,
67        values: Vec<Expr>,
68    },
69    /// `a, b = b, a`
70    Assign {
71        targets: Vec<Expr>,
72        values: Vec<Expr>,
73    },
74    /// `x += 1`, `s ..= "!"`
75    CompoundAssign {
76        op: BinOp,
77        op_span: Span,
78        target: Expr,
79        value: Expr,
80    },
81    Do(Block),
82    While {
83        cond: Expr,
84        body: Block,
85    },
86    /// The condition can see the body's locals, same as Lua.
87    Repeat {
88        body: Block,
89        cond: Expr,
90    },
91    If {
92        branches: Vec<(Expr, Block)>,
93        else_block: Option<Block>,
94    },
95    NumericFor {
96        var: Name,
97        var_type: Option<Box<TypeExpr>>,
98        start: Expr,
99        limit: Expr,
100        step: Option<Expr>,
101        body: Block,
102    },
103    Break,
104    Continue,
105    /// A call used as a statement (results get thrown away).
106    Call(Expr),
107    /// `function name(...) end`, assigns a new function to `name`.
108    Function {
109        target: Expr,
110        func: Rc<FunctionBody>,
111    },
112    /// `local function name(...) end`. `name` is in scope inside the body so
113    /// the function can call itself.
114    LocalFunction {
115        name: Name,
116        func: Rc<FunctionBody>,
117    },
118    /// `for k, v in explist do ... end`. The list gives an iterator function, a
119    /// state and a starting control value. Luau's generalized iteration (`for
120    /// k, v in t`) also takes a table directly.
121    GenericFor {
122        names: Vec<Name>,
123        types: Vec<Option<TypeExpr>>,
124        exprs: Vec<Expr>,
125        body: Block,
126    },
127    /// `type Name<T> = ...` or `export type ...`. Does nothing at runtime.
128    TypeAlias(Rc<TypeAlias>),
129}
130
131#[derive(Clone, Debug, PartialEq)]
132pub struct TypeAlias {
133    pub name: Rc<str>,
134    pub name_span: Span,
135    pub generics: Vec<GenericParam>,
136    pub ty: TypeExpr,
137    pub exported: bool,
138}
139
140/// Parameters and body, shared by every way of writing a function.
141#[derive(Clone, Debug, PartialEq)]
142pub struct FunctionBody {
143    /// `<T, U>` after the name.
144    pub generics: Vec<GenericParam>,
145    pub params: Vec<Name>,
146    /// One per parameter, `None` where it's unannotated (always for the
147    /// implicit `self` of a `function a:m()` method).
148    pub param_types: Vec<Option<TypeExpr>>,
149    pub is_vararg: bool,
150    /// `...: T`
151    pub vararg_type: Option<TypeExpr>,
152    /// `): T` or `): (A, B)`
153    pub return_type: Option<TypePack>,
154    /// Declared with `:`, so `params[0]` is the implicit `self`.
155    pub is_method: bool,
156    pub body: Block,
157    /// The name it was declared with, for tracebacks (`None` if anonymous).
158    pub name: Option<Rc<str>>,
159    pub span: Span,
160}
161
162#[derive(Clone, Debug, PartialEq)]
163pub struct Expr {
164    pub kind: ExprKind,
165    pub span: Span,
166}
167
168#[derive(Clone, Debug, PartialEq)]
169pub enum ExprKind {
170    Nil,
171    Bool(bool),
172    Number(f64),
173    String(Rc<str>),
174    /// `` `text {expr} text` `` with at least one hole (no holes is just an
175    /// [`ExprKind::String`]).
176    Interp(Vec<InterpPart>),
177    Name(Name),
178    /// A parenthesised expression. It stays a node because `(f())` truncates
179    /// multiple results to one.
180    Group(Box<Expr>),
181    Unary {
182        op: UnOp,
183        op_span: Span,
184        operand: Box<Expr>,
185    },
186    Binary {
187        op: BinOp,
188        op_span: Span,
189        lhs: Box<Expr>,
190        rhs: Box<Expr>,
191    },
192    /// Luau's `if a then b elseif c then d else e` expression.
193    IfElse {
194        branches: Vec<(Expr, Expr)>,
195        else_expr: Box<Expr>,
196    },
197    /// `f(a, b)` or `f "str"`.
198    Call {
199        callee: Box<Expr>,
200        args: Vec<Expr>,
201    },
202    /// `...` inside a vararg function.
203    Vararg,
204    /// `function(...) ... end`
205    Function(Rc<FunctionBody>),
206    /// `t[k]`, or `t.name` (`key` is a string literal then).
207    Index {
208        object: Box<Expr>,
209        key: Box<Expr>,
210    },
211    /// `obj:name(args)`, calls `obj.name` with `obj` as the first argument.
212    MethodCall {
213        object: Box<Expr>,
214        method: Rc<str>,
215        method_span: Span,
216        args: Vec<Expr>,
217    },
218    /// `{ a, b, name = c, [k] = d }`
219    Table(Vec<TableItem>),
220    /// `expr :: Type`, a type assertion. At runtime it's just `expr`.
221    Cast {
222        expr: Box<Expr>,
223        ty: Box<TypeExpr>,
224    },
225}
226
227// ─ Types ─────────────────────────────────────────────────────────────────────
228
229/// A type written in the source.
230#[derive(Clone, Debug, PartialEq)]
231pub struct TypeExpr {
232    pub kind: TypeKind,
233    pub span: Span,
234}
235
236#[derive(Clone, Debug, PartialEq)]
237pub enum TypeKind {
238    /// `number`, `Map<string, T>`, `nil`, a generic parameter.
239    Name {
240        name: Rc<str>,
241        args: Vec<TypeExpr>,
242    },
243    /// `"on"`, `true`
244    Singleton(Singleton),
245    /// `typeof(expr)`
246    Typeof(Box<Expr>),
247    /// `T?`
248    Optional(Box<TypeExpr>),
249    Union(Vec<TypeExpr>),
250    Intersection(Vec<TypeExpr>),
251    /// `{ x: number, [string]: boolean }`, or `{T}` (an indexer from number).
252    Table {
253        props: Vec<TableProp>,
254        indexer: Option<Box<(TypeExpr, TypeExpr)>>,
255    },
256    /// `T...`, a generic type pack, wherever a variadic type can go (`...:
257    /// T...`, `(A, T...) -> T...`).
258    GenericPack(Rc<str>),
259    /// An explicit type pack passed to a type alias: `(A, B)`, `()`, `(...T)`.
260    Pack(TypePack),
261    /// `<T>(a: T, ...number) -> (T, string)`
262    Function {
263        generics: Vec<GenericParam>,
264        params: Vec<FnParam>,
265        variadic: Option<Box<TypeExpr>>,
266        returns: TypePack,
267    },
268}
269
270#[derive(Clone, Debug, PartialEq)]
271pub enum Singleton {
272    Bool(bool),
273    String(Rc<str>),
274}
275
276#[derive(Clone, Debug, PartialEq)]
277pub struct TableProp {
278    pub name: Rc<str>,
279    pub ty: TypeExpr,
280    pub span: Span,
281    /// `read name: T` / `write name: T` (both if neither).
282    pub access: Access,
283}
284
285/// What a table type's property allows.
286#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
287pub enum Access {
288    #[default]
289    ReadWrite,
290    /// `read x: T`: readable, can't be assigned.
291    Read,
292    /// `write x: T`: assignable, can't be read.
293    Write,
294}
295
296impl Access {
297    pub fn can_read(self) -> bool {
298        self != Access::Write
299    }
300
301    pub fn can_write(self) -> bool {
302        self != Access::Read
303    }
304
305    /// `read ` / `write ` / nothing, as written before a property.
306    pub fn prefix(self) -> &'static str {
307        match self {
308            Access::ReadWrite => "",
309            Access::Read => "read ",
310            Access::Write => "write ",
311        }
312    }
313}
314
315#[derive(Clone, Debug, PartialEq)]
316pub struct FnParam {
317    /// Parameter names in function types are just documentation.
318    pub name: Option<Rc<str>>,
319    pub ty: TypeExpr,
320}
321
322#[derive(Clone, Debug, PartialEq)]
323pub struct GenericParam {
324    pub name: Rc<str>,
325    pub span: Span,
326    /// `T...`: a generic type pack (any number of types).
327    pub pack: bool,
328    /// `T = string` (type aliases only). For a pack it's a [`TypeKind::Pack`]
329    /// or [`TypeKind::GenericPack`].
330    pub default: Option<TypeExpr>,
331}
332
333/// A list of types: function results, `(A, B)`, `...T`, `()`.
334#[derive(Clone, Debug, PartialEq)]
335pub struct TypePack {
336    pub types: Vec<TypeExpr>,
337    pub variadic: Option<Box<TypeExpr>>,
338    pub span: Span,
339}
340
341impl fmt::Display for TypeExpr {
342    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
343        match &self.kind {
344            TypeKind::Name { name, args } => {
345                f.write_str(name)?;
346                if !args.is_empty() {
347                    let args: Vec<String> = args.iter().map(|a| a.to_string()).collect();
348                    write!(f, "<{}>", args.join(", "))?;
349                }
350                Ok(())
351            }
352            TypeKind::Singleton(Singleton::Bool(b)) => write!(f, "{b}"),
353            TypeKind::Singleton(Singleton::String(s)) => write!(f, "{s:?}"),
354            TypeKind::Typeof(e) => write!(f, "typeof({e})"),
355            TypeKind::Optional(t) => write!(f, "{t}?"),
356            TypeKind::GenericPack(name) => write!(f, "{name}..."),
357            TypeKind::Pack(p) => write!(f, "{p}"),
358            TypeKind::Union(ts) | TypeKind::Intersection(ts) => {
359                let sep = if matches!(self.kind, TypeKind::Union(_)) {
360                    " | "
361                } else {
362                    " & "
363                };
364                let parts: Vec<String> = ts.iter().map(|t| t.to_string()).collect();
365                write!(f, "({})", parts.join(sep))
366            }
367            TypeKind::Table { props, indexer } => {
368                let mut parts: Vec<String> = props
369                    .iter()
370                    .map(|p| format!("{}{}: {}", p.access.prefix(), p.name, p.ty))
371                    .collect();
372                if let Some(ix) = indexer {
373                    parts.push(format!("[{}]: {}", ix.0, ix.1));
374                }
375                write!(f, "{{{}}}", parts.join(", "))
376            }
377            TypeKind::Function {
378                generics,
379                params,
380                variadic,
381                returns,
382            } => {
383                if !generics.is_empty() {
384                    let g: Vec<String> = generics
385                        .iter()
386                        .map(|g| format!("{}{}", g.name, if g.pack { "..." } else { "" }))
387                        .collect();
388                    write!(f, "<{}>", g.join(", "))?;
389                }
390                let mut ps: Vec<String> = params.iter().map(|p| p.ty.to_string()).collect();
391                if let Some(v) = variadic {
392                    ps.push(variadic_text(v));
393                }
394                write!(f, "({}) -> {returns}", ps.join(", "))
395            }
396        }
397    }
398}
399
400impl fmt::Display for TypePack {
401    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
402        let mut parts: Vec<String> = self.types.iter().map(|t| t.to_string()).collect();
403        if let Some(v) = &self.variadic {
404            parts.push(variadic_text(v));
405        }
406        write!(f, "({})", parts.join(", "))
407    }
408}
409
410/// A variadic slot: `...T`, or a generic pack `T...` as-is.
411fn variadic_text(v: &TypeExpr) -> String {
412    match &v.kind {
413        TypeKind::GenericPack(_) => v.to_string(),
414        _ => format!("...{v}"),
415    }
416}
417
418/// One entry of a table constructor.
419#[derive(Clone, Debug, PartialEq)]
420pub enum TableItem {
421    /// `expr`, stored at the next array index (1, 2, ...). A trailing call or
422    /// `...` expands to all its values.
423    Positional(Expr),
424    /// `name = expr` or `[key] = expr`.
425    Keyed { key: Expr, value: Expr },
426}
427
428impl ExprKind {
429    /// Calls and `...` can give any number of values, everything else gives
430    /// exactly one.
431    pub fn is_multi(&self) -> bool {
432        matches!(
433            self,
434            ExprKind::Call { .. } | ExprKind::MethodCall { .. } | ExprKind::Vararg
435        )
436    }
437}
438
439/// A piece of an interpolated string.
440#[derive(Clone, Debug, PartialEq)]
441pub enum InterpPart {
442    Text(Rc<str>),
443    /// A hole's expression, its value goes through `tostring`.
444    Expr(Expr),
445}
446
447#[derive(Clone, Copy, Debug, PartialEq, Eq)]
448pub enum UnOp {
449    Neg,
450    Not,
451    Len,
452}
453
454#[derive(Clone, Copy, Debug, PartialEq, Eq)]
455pub enum BinOp {
456    Add,
457    Sub,
458    Mul,
459    Div,
460    IDiv,
461    Mod,
462    Pow,
463    Concat,
464    Eq,
465    Ne,
466    Lt,
467    Le,
468    Gt,
469    Ge,
470    And,
471    Or,
472}
473
474/// Binding power for every prefix operator. Higher than `* / // %` but lower
475/// than `^`, so `-2^2 == -(2^2)` while `-2*3 == (-2)*3`.
476pub const UNARY_BP: u8 = 30;
477
478impl BinOp {
479    /// `(left, right)` binding powers, Pratt-style. Left-associative operators
480    /// have `right = left + 1`, right-associative ones (`..`, `^`) have
481    /// `right < left`.
482    ///
483    /// Luau's precedence, lowest to highest:
484    /// `or` < `and` < comparison < `..` < `+ -` < `* / // %` < unary < `^`.
485    pub fn binding_power(self) -> (u8, u8) {
486        use BinOp::*;
487        match self {
488            Or => (1, 2),
489            And => (3, 4),
490            Eq | Ne | Lt | Le | Gt | Ge => (5, 6),
491            Concat => (9, 8),
492            Add | Sub => (10, 11),
493            Mul | Div | IDiv | Mod => (20, 21),
494            Pow => (41, 40),
495        }
496    }
497
498    pub fn symbol(self) -> &'static str {
499        use BinOp::*;
500        match self {
501            Add => "+",
502            Sub => "-",
503            Mul => "*",
504            Div => "/",
505            IDiv => "//",
506            Mod => "%",
507            Pow => "^",
508            Concat => "..",
509            Eq => "==",
510            Ne => "~=",
511            Lt => "<",
512            Le => "<=",
513            Gt => ">",
514            Ge => ">=",
515            And => "and",
516            Or => "or",
517        }
518    }
519}
520
521impl UnOp {
522    pub fn symbol(self) -> &'static str {
523        match self {
524            UnOp::Neg => "-",
525            UnOp::Not => "not",
526            UnOp::Len => "#",
527        }
528    }
529}
530
531/// S-expression printing, the tests lean on this a lot: `1 + 2 * 3` → `(+ 1 (*
532/// 2 3))`.
533impl fmt::Display for Expr {
534    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
535        match &self.kind {
536            ExprKind::Nil => f.write_str("nil"),
537            ExprKind::Bool(b) => write!(f, "{b}"),
538            ExprKind::Number(n) => write!(f, "{n}"),
539            ExprKind::String(s) => write!(f, "{s:?}"),
540            ExprKind::Name(n) => f.write_str(&n.text),
541            ExprKind::Group(e) => write!(f, "(group {e})"),
542            ExprKind::Unary { op, operand, .. } => write!(f, "({} {operand})", op.symbol()),
543            ExprKind::Binary { op, lhs, rhs, .. } => write!(f, "({} {lhs} {rhs})", op.symbol()),
544            ExprKind::IfElse {
545                branches,
546                else_expr,
547            } => {
548                f.write_str("(if")?;
549                for (c, v) in branches {
550                    write!(f, " {c} {v}")?;
551                }
552                write!(f, " {else_expr})")
553            }
554            ExprKind::Call { callee, args } => {
555                write!(f, "(call {callee}")?;
556                for a in args {
557                    write!(f, " {a}")?;
558                }
559                f.write_str(")")
560            }
561            ExprKind::Vararg => f.write_str("..."),
562            ExprKind::Interp(parts) => {
563                f.write_str("(interp")?;
564                for part in parts {
565                    match part {
566                        InterpPart::Text(t) => write!(f, " {t:?}")?,
567                        InterpPart::Expr(e) => write!(f, " {e}")?,
568                    }
569                }
570                f.write_str(")")
571            }
572            ExprKind::Function(func) => {
573                let mut params: Vec<&str> = func.params.iter().map(|p| &*p.text).collect();
574                if func.is_vararg {
575                    params.push("...");
576                }
577                write!(f, "(function ({}))", params.join(" "))
578            }
579            ExprKind::Index { object, key } => write!(f, "(index {object} {key})"),
580            ExprKind::Cast { expr, ty } => write!(f, "(:: {expr} {ty})"),
581            ExprKind::MethodCall {
582                object,
583                method,
584                args,
585                ..
586            } => {
587                write!(f, "(method {object} {method}")?;
588                for a in args {
589                    write!(f, " {a}")?;
590                }
591                f.write_str(")")
592            }
593            ExprKind::Table(items) => {
594                f.write_str("(table")?;
595                for item in items {
596                    match item {
597                        TableItem::Positional(e) => write!(f, " {e}")?,
598                        TableItem::Keyed { key, value } => write!(f, " [{key}]={value}")?,
599                    }
600                }
601                f.write_str(")")
602            }
603        }
604    }
605}