Skip to main content

bamts_compiler/
syntax.rs

1//! Immutable, parser-owned syntax data.
2//!
3//! Child edges are owned values and public traversal only exposes shared borrows.
4//! There are deliberately no parent links or interior-mutable caches: a parsed
5//! [`SourceFile`] can be shared without changing the tree it describes.
6
7use std::sync::Arc;
8
9use crate::diagnostic::Diagnostic;
10use crate::source::{ScriptKind, SourceId, SourceText, TextRange};
11
12/// A stable identity assigned by the parser to one AST node.
13#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
14pub struct NodeId(u32);
15
16impl NodeId {
17    pub const fn new(value: u32) -> Self {
18        Self(value)
19    }
20
21    pub const fn get(self) -> u32 {
22        self.0
23    }
24}
25
26/// A lexical token kind. This is intentionally separate from [`NodeKind`].
27#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
28pub enum TokenKind {
29    EndOfFile,
30    Unknown,
31    Whitespace,
32    LineComment,
33    BlockComment,
34    Shebang,
35    Identifier,
36    PrivateIdentifier,
37    NumericLiteral,
38    BigIntLiteral,
39    StringLiteral,
40    RegularExpressionLiteral,
41    NoSubstitutionTemplate,
42    TemplateHead,
43    TemplateMiddle,
44    TemplateTail,
45    KwAbstract,
46    KwAccessor,
47    KwAny,
48    KwAs,
49    KwAsserts,
50    KwAsync,
51    KwAwait,
52    KwBigint,
53    KwBoolean,
54    KwBreak,
55    KwCase,
56    KwCatch,
57    KwClass,
58    KwConst,
59    KwConstructor,
60    KwContinue,
61    KwDeclare,
62    KwDebugger,
63    KwDefault,
64    KwDelete,
65    KwDo,
66    KwElse,
67    KwEnum,
68    KwExport,
69    KwExtends,
70    KwFalse,
71    KwFinally,
72    KwFor,
73    KwFrom,
74    KwFunction,
75    KwGet,
76    KwIf,
77    KwImplements,
78    KwImport,
79    KwIn,
80    KwInfer,
81    KwInstanceof,
82    KwInterface,
83    KwIs,
84    KwKeyof,
85    KwLet,
86    KwNamespace,
87    KwNever,
88    KwNew,
89    KwNull,
90    KwNumber,
91    KwObject,
92    KwOf,
93    KwOverride,
94    KwPackage,
95    KwPrivate,
96    KwProtected,
97    KwPublic,
98    KwReadonly,
99    KwReturn,
100    KwSatisfies,
101    KwSet,
102    KwStatic,
103    KwString,
104    KwSuper,
105    KwSwitch,
106    KwSymbol,
107    KwThis,
108    KwThrow,
109    KwTrue,
110    KwTry,
111    KwType,
112    KwTypeof,
113    KwUndefined,
114    KwUnique,
115    KwUnknown,
116    KwVar,
117    KwVoid,
118    KwWhile,
119    KwWith,
120    KwYield,
121    LBrace,
122    RBrace,
123    LBracket,
124    RBracket,
125    LParen,
126    RParen,
127    Dot,
128    DotDotDot,
129    Comma,
130    Semicolon,
131    Colon,
132    Question,
133    QuestionDot,
134    QuestionQuestion,
135    At,
136    Arrow,
137    Plus,
138    Minus,
139    Star,
140    StarStar,
141    Slash,
142    Percent,
143    PlusPlus,
144    MinusMinus,
145    LessThan,
146    GreaterThan,
147    LessThanEq,
148    GreaterThanEq,
149    LessLess,
150    GreaterGreater,
151    GreaterGreaterGreater,
152    Eq,
153    EqEq,
154    EqEqEq,
155    Bang,
156    BangEq,
157    BangEqEq,
158    Amp,
159    AmpAmp,
160    Pipe,
161    PipePipe,
162    Caret,
163    Tilde,
164    PlusEq,
165    MinusEq,
166    StarEq,
167    StarStarEq,
168    SlashEq,
169    PercentEq,
170    LessLessEq,
171    GreaterGreaterEq,
172    GreaterGreaterGreaterEq,
173    AmpEq,
174    AmpAmpEq,
175    PipeEq,
176    PipePipeEq,
177    CaretEq,
178    QuestionQuestionEq,
179}
180
181/// A grammar node kind. A value of this type can never name a token.
182#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
183pub enum NodeKind {
184    SourceFile,
185    ImportDeclaration,
186    ImportEqualsDeclaration,
187    ImportSpecifier,
188    ExportDeclaration,
189    ExportSpecifier,
190    VariableDeclaration,
191    VariableDeclarator,
192    FunctionDeclaration,
193    ClassDeclaration,
194    InterfaceDeclaration,
195    TypeAliasDeclaration,
196    EnumDeclaration,
197    EnumMember,
198    NamespaceDeclaration,
199    BlockStatement,
200    EmptyStatement,
201    ExpressionStatement,
202    IfStatement,
203    SwitchStatement,
204    SwitchCase,
205    ForStatement,
206    ForInStatement,
207    ForOfStatement,
208    WhileStatement,
209    DoWhileStatement,
210    TryStatement,
211    CatchClause,
212    WithStatement,
213    LabeledStatement,
214    BreakStatement,
215    ContinueStatement,
216    ReturnStatement,
217    ThrowStatement,
218    DebuggerStatement,
219    DeclareStatement,
220    MissingStatement,
221    Identifier,
222    PrivateIdentifier,
223    StringLiteral,
224    NumericLiteral,
225    BigIntLiteral,
226    BooleanLiteral,
227    NullLiteral,
228    RegexLiteral,
229    TemplateElement,
230    IdentifierExpression,
231    ThisExpression,
232    SuperExpression,
233    LiteralExpression,
234    ArrayExpression,
235    ObjectExpression,
236    FunctionExpression,
237    ClassExpression,
238    ArrowFunction,
239    CallExpression,
240    MemberExpression,
241    NewExpression,
242    AwaitExpression,
243    YieldExpression,
244    UnaryExpression,
245    UpdateExpression,
246    BinaryExpression,
247    LogicalExpression,
248    ConditionalExpression,
249    AssignmentExpression,
250    SequenceExpression,
251    ParenthesizedExpression,
252    AsExpression,
253    SatisfiesExpression,
254    TypeAssertionExpression,
255    NonNullExpression,
256    TaggedTemplateExpression,
257    TemplateExpression,
258    ImportExpression,
259    MetaProperty,
260    MissingExpression,
261    BindingIdentifier,
262    ObjectBindingPattern,
263    ArrayBindingPattern,
264    RestBindingPattern,
265    AssignmentBindingPattern,
266    MissingBindingPattern,
267    MemberAssignmentTarget,
268    IdentifierAssignmentTarget,
269    ArrayAssignmentTarget,
270    ObjectAssignmentTarget,
271    MissingAssignmentTarget,
272    Parameter,
273    TypeAnnotation,
274    KeywordType,
275    LiteralType,
276    TypeReference,
277    UnionType,
278    IntersectionType,
279    ArrayType,
280    TupleType,
281    ObjectType,
282    FunctionType,
283    ConstructorType,
284    TypeQuery,
285    TypeOperator,
286    IndexedAccessType,
287    ConditionalType,
288    MappedType,
289    InferType,
290    ImportType,
291    TemplateLiteralType,
292    ParenthesizedType,
293    ThisType,
294    TypePredicate,
295    MissingType,
296    TypeParameter,
297    TypeMember,
298    ClassMember,
299    ObjectMember,
300    Decorator,
301}
302
303/// The complete syntax-kind space, with token and node categories represented
304/// by different variants instead of a shared integer namespace.
305#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
306pub enum SyntaxKind {
307    Token(TokenKind),
308    Node(NodeKind),
309}
310
311impl SyntaxKind {
312    pub const fn token(kind: TokenKind) -> Self {
313        Self::Token(kind)
314    }
315
316    pub const fn node(kind: NodeKind) -> Self {
317        Self::Node(kind)
318    }
319
320    pub const fn is_token(self) -> bool {
321        matches!(self, Self::Token(_))
322    }
323
324    pub const fn is_node(self) -> bool {
325        matches!(self, Self::Node(_))
326    }
327}
328
329impl From<TokenKind> for SyntaxKind {
330    fn from(kind: TokenKind) -> Self {
331        Self::Token(kind)
332    }
333}
334
335impl From<NodeKind> for SyntaxKind {
336    fn from(kind: NodeKind) -> Self {
337        Self::Node(kind)
338    }
339}
340
341/// An immutable lexical token. Its lexeme stays in [`SourceText`], avoiding
342/// one allocation and reference-counted handle per scanner token.
343#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
344pub struct Token {
345    kind: TokenKind,
346    range: TextRange,
347    missing: bool,
348}
349
350impl Token {
351    pub const fn new(kind: TokenKind, range: TextRange) -> Self {
352        Self {
353            kind,
354            range,
355            missing: false,
356        }
357    }
358
359    pub const fn missing(kind: TokenKind, range: TextRange) -> Self {
360        Self {
361            kind,
362            range,
363            missing: true,
364        }
365    }
366
367    pub const fn kind(&self) -> TokenKind {
368        self.kind
369    }
370
371    pub const fn syntax_kind(&self) -> SyntaxKind {
372        SyntaxKind::Token(self.kind)
373    }
374
375    pub const fn range(&self) -> TextRange {
376        self.range
377    }
378
379    pub const fn is_missing(&self) -> bool {
380        self.missing
381    }
382}
383
384/// Data stored in a typed AST node.
385///
386/// This trait lets [`Node`] derive its syntax kind from its closed payload
387/// enum, so callers never supply a potentially mismatched `NodeKind`.
388pub trait NodeData {
389    fn node_kind(&self) -> NodeKind;
390}
391
392/// The common immutable header for every AST node.
393#[derive(Clone, Debug, Eq, PartialEq)]
394pub struct Node<T> {
395    id: NodeId,
396    range: TextRange,
397    data: T,
398}
399
400impl<T> Node<T> {
401    pub fn new(id: NodeId, range: TextRange, data: T) -> Self {
402        Self { id, range, data }
403    }
404
405    pub const fn id(&self) -> NodeId {
406        self.id
407    }
408
409    pub const fn range(&self) -> TextRange {
410        self.range
411    }
412
413    pub fn data(&self) -> &T {
414        &self.data
415    }
416
417    pub fn into_data(self) -> T {
418        self.data
419    }
420}
421
422impl<T: NodeData> Node<T> {
423    pub fn kind(&self) -> NodeKind {
424        self.data.node_kind()
425    }
426
427    pub fn syntax_kind(&self) -> SyntaxKind {
428        SyntaxKind::Node(self.kind())
429    }
430}
431
432pub type StatementNode = Node<Statement>;
433pub type Stmt = StatementNode;
434pub type ExpressionNode = Node<Expression>;
435pub type Expr = ExpressionNode;
436pub type TypeNodeRef = Node<TypeNode>;
437pub type Ty = TypeNodeRef;
438pub type BindingPatternNode = Node<BindingPattern>;
439pub type Pattern = BindingPatternNode;
440pub type AssignmentTargetNode = Node<AssignmentTarget>;
441pub type ParameterNode = Node<Parameter>;
442pub type VariableDeclaratorNode = Node<VariableDeclarator>;
443pub type BlockNode = Node<Block>;
444pub type ClassMemberNode = Node<ClassMember>;
445pub type ObjectMemberNode = Node<ObjectMember>;
446pub type ImportSpecifierNode = Node<ImportSpecifier>;
447pub type ExportSpecifierNode = Node<ExportSpecifier>;
448pub type TypeAnnotationNode = Node<TypeAnnotation>;
449pub type TypeParameterNode = Node<TypeParameter>;
450pub type TypeMemberNode = Node<TypeMember>;
451pub type CatchClauseNode = Node<CatchClause>;
452pub type SwitchCaseNode = Node<SwitchCase>;
453pub type EnumMemberNode = Node<EnumMember>;
454pub type DecoratorNode = Node<Decorator>;
455
456macro_rules! token_leaf {
457    ($name:ident, $alias:ident, $kind:ident) => {
458        #[derive(Clone, Debug, Eq, PartialEq)]
459        pub struct $name {
460            token: Token,
461        }
462
463        impl $name {
464            pub fn new(token: Token) -> Self {
465                Self { token }
466            }
467
468            pub fn token(&self) -> &Token {
469                &self.token
470            }
471        }
472
473        impl NodeData for $name {
474            fn node_kind(&self) -> NodeKind {
475                NodeKind::$kind
476            }
477        }
478
479        pub type $alias = Node<$name>;
480    };
481}
482
483token_leaf!(Identifier, IdentifierNode, Identifier);
484token_leaf!(PrivateIdentifier, PrivateIdentifierNode, PrivateIdentifier);
485token_leaf!(StringLiteral, StringLiteralNode, StringLiteral);
486token_leaf!(NumericLiteral, NumericLiteralNode, NumericLiteral);
487token_leaf!(BigIntLiteral, BigIntLiteralNode, BigIntLiteral);
488token_leaf!(BooleanLiteral, BooleanLiteralNode, BooleanLiteral);
489token_leaf!(NullLiteral, NullLiteralNode, NullLiteral);
490token_leaf!(RegexLiteral, RegexLiteralNode, RegexLiteral);
491token_leaf!(TemplateElement, TemplateElementNode, TemplateElement);
492
493/// Recovery payload for an omitted grammar node. Its enclosing [`Node`] still
494/// carries the insertion range and identity.
495#[derive(Clone, Debug, Eq, PartialEq)]
496pub struct MissingNode {
497    expected: NodeKind,
498}
499
500impl MissingNode {
501    pub const fn new(expected: NodeKind) -> Self {
502        Self { expected }
503    }
504
505    pub const fn expected(&self) -> NodeKind {
506        self.expected
507    }
508}
509
510#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
511pub enum Accessibility {
512    Public,
513    Protected,
514    Private,
515}
516
517#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
518pub enum Variance {
519    In,
520    Out,
521    InOut,
522    #[default]
523    Invariant,
524}
525
526#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
527pub enum VariableKind {
528    Var,
529    Let,
530    Const,
531    Using,
532    AwaitUsing,
533}
534
535#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
536pub enum ImportSpecifierMode {
537    Value,
538    TypeOnly,
539}
540
541#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
542pub enum ExportSpecifierMode {
543    Value,
544    TypeOnly,
545}
546
547#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
548pub enum UnaryOperator {
549    Plus,
550    Minus,
551    Not,
552    BitNot,
553    Typeof,
554    Void,
555    Delete,
556}
557
558#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
559pub enum UpdateOperator {
560    Increment,
561    Decrement,
562}
563
564#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
565pub enum BinaryOperator {
566    Add,
567    Subtract,
568    Multiply,
569    Divide,
570    Remainder,
571    Exponentiate,
572    LeftShift,
573    SignedRightShift,
574    UnsignedRightShift,
575    LessThan,
576    LessThanOrEqual,
577    GreaterThan,
578    GreaterThanOrEqual,
579    In,
580    Instanceof,
581    Equal,
582    NotEqual,
583    StrictEqual,
584    StrictNotEqual,
585    BitAnd,
586    BitXor,
587    BitOr,
588}
589
590#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
591pub enum LogicalOperator {
592    And,
593    Or,
594    Nullish,
595}
596
597#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
598pub enum AssignmentOperator {
599    Assign,
600    AddAssign,
601    SubtractAssign,
602    MultiplyAssign,
603    DivideAssign,
604    RemainderAssign,
605    ExponentiateAssign,
606    LeftShiftAssign,
607    SignedRightShiftAssign,
608    UnsignedRightShiftAssign,
609    BitAndAssign,
610    BitXorAssign,
611    BitOrAssign,
612    LogicalAndAssign,
613    LogicalOrAssign,
614    NullishAssign,
615}
616
617#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
618pub enum KeywordType {
619    Any,
620    Unknown,
621    Never,
622    Void,
623    Undefined,
624    Null,
625    Boolean,
626    Number,
627    BigInt,
628    String,
629    Symbol,
630    Object,
631    Intrinsic,
632}
633
634#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
635pub enum TypeOperator {
636    Keyof,
637    Unique,
638    Readonly,
639}
640
641#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
642pub enum MappedModifier {
643    Preserve,
644    Add,
645    Remove,
646}
647
648#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
649pub enum ForOfMode {
650    Sync,
651    Async,
652}
653
654#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
655pub enum PropertyModifier {
656    None,
657    Get,
658    Set,
659}
660
661#[derive(Clone, Debug, Default, Eq, PartialEq)]
662pub struct DeclarationModifiers {
663    pub accessibility: Option<Accessibility>,
664    pub is_abstract: bool,
665    pub is_declare: bool,
666    pub is_override: bool,
667    pub is_readonly: bool,
668    pub is_static: bool,
669}
670
671#[derive(Clone, Debug, Eq, PartialEq)]
672pub struct TypeParameter {
673    pub name: IdentifierNode,
674    pub variance: Variance,
675    pub constraint: Option<Box<Ty>>,
676    pub default: Option<Box<Ty>>,
677}
678
679impl NodeData for TypeParameter {
680    fn node_kind(&self) -> NodeKind {
681        NodeKind::TypeParameter
682    }
683}
684
685#[derive(Clone, Debug, Default, Eq, PartialEq)]
686pub struct TypeParameterList {
687    pub parameters: Vec<TypeParameterNode>,
688}
689
690#[derive(Clone, Debug, Default, Eq, PartialEq)]
691pub struct TypeArgumentList {
692    pub arguments: Vec<Ty>,
693}
694
695#[derive(Clone, Debug, Eq, PartialEq)]
696pub struct TypeAnnotation {
697    pub type_node: Box<Ty>,
698}
699
700impl NodeData for TypeAnnotation {
701    fn node_kind(&self) -> NodeKind {
702        NodeKind::TypeAnnotation
703    }
704}
705
706#[derive(Clone, Debug, Eq, PartialEq)]
707pub struct Decorator {
708    pub expression: Box<Expr>,
709}
710
711impl NodeData for Decorator {
712    fn node_kind(&self) -> NodeKind {
713        NodeKind::Decorator
714    }
715}
716
717#[derive(Clone, Debug, Default, Eq, PartialEq)]
718pub struct ParameterModifiers {
719    pub accessibility: Option<Accessibility>,
720    pub is_readonly: bool,
721    pub is_override: bool,
722}
723
724#[derive(Clone, Debug, Eq, PartialEq)]
725pub struct Parameter {
726    pub decorators: Vec<DecoratorNode>,
727    pub modifiers: ParameterModifiers,
728    pub binding: Pattern,
729    pub optional: bool,
730    pub type_annotation: Option<TypeAnnotationNode>,
731    pub initializer: Option<Box<Expr>>,
732}
733
734impl NodeData for Parameter {
735    fn node_kind(&self) -> NodeKind {
736        NodeKind::Parameter
737    }
738}
739
740#[derive(Clone, Debug, Eq, PartialEq)]
741pub enum PropertyName {
742    Identifier(IdentifierNode),
743    Private(PrivateIdentifierNode),
744    String(StringLiteralNode),
745    Number(NumericLiteralNode),
746    Computed(Box<Expr>),
747    Missing(MissingNode),
748}
749
750#[derive(Clone, Debug, Eq, PartialEq)]
751pub enum ModuleExportName {
752    Identifier(IdentifierNode),
753    String(StringLiteralNode),
754    Missing(MissingNode),
755}
756
757#[derive(Clone, Debug, Eq, PartialEq)]
758pub struct ObjectBindingProperty {
759    pub name: PropertyName,
760    pub binding: Pattern,
761    pub initializer: Option<Box<Expr>>,
762}
763
764#[derive(Clone, Debug, Eq, PartialEq)]
765pub struct ObjectBindingPattern {
766    pub properties: Vec<ObjectBindingProperty>,
767}
768
769#[derive(Clone, Debug, Eq, PartialEq)]
770pub enum ArrayBindingElement {
771    Binding(Pattern),
772    Elision,
773    Missing(MissingNode),
774}
775
776#[derive(Clone, Debug, Eq, PartialEq)]
777pub struct ArrayBindingPattern {
778    pub elements: Vec<ArrayBindingElement>,
779}
780
781#[derive(Clone, Debug, Eq, PartialEq)]
782pub struct RestBindingPattern {
783    pub argument: Box<Pattern>,
784}
785
786#[derive(Clone, Debug, Eq, PartialEq)]
787pub struct AssignmentBindingPattern {
788    pub left: Box<Pattern>,
789    pub right: Box<Expr>,
790}
791
792#[derive(Clone, Debug, Eq, PartialEq)]
793pub enum BindingPattern {
794    Identifier(IdentifierNode),
795    Object(ObjectBindingPattern),
796    Array(ArrayBindingPattern),
797    Rest(RestBindingPattern),
798    Assignment(AssignmentBindingPattern),
799    Missing(MissingNode),
800}
801
802impl NodeData for BindingPattern {
803    fn node_kind(&self) -> NodeKind {
804        match self {
805            Self::Identifier(_) => NodeKind::BindingIdentifier,
806            Self::Object(_) => NodeKind::ObjectBindingPattern,
807            Self::Array(_) => NodeKind::ArrayBindingPattern,
808            Self::Rest(_) => NodeKind::RestBindingPattern,
809            Self::Assignment(_) => NodeKind::AssignmentBindingPattern,
810            Self::Missing(_) => NodeKind::MissingBindingPattern,
811        }
812    }
813}
814
815#[derive(Clone, Debug, Eq, PartialEq)]
816pub enum MemberProperty {
817    Named(IdentifierNode),
818    Private(PrivateIdentifierNode),
819    Computed(Box<Expr>),
820}
821
822#[derive(Clone, Debug, Eq, PartialEq)]
823pub struct MemberExpression {
824    pub object: Box<Expr>,
825    pub property: MemberProperty,
826    pub optional: bool,
827}
828
829#[derive(Clone, Debug, Eq, PartialEq)]
830pub struct AssignmentMemberTarget {
831    pub object: Box<Expr>,
832    pub property: MemberProperty,
833}
834
835#[derive(Clone, Debug, Eq, PartialEq)]
836pub struct AssignmentObjectProperty {
837    pub name: PropertyName,
838    pub target: AssignmentTargetNode,
839    pub initializer: Option<Box<Expr>>,
840}
841
842#[derive(Clone, Debug, Eq, PartialEq)]
843pub struct AssignmentObjectPattern {
844    pub properties: Vec<AssignmentObjectProperty>,
845}
846
847#[derive(Clone, Debug, Eq, PartialEq)]
848pub enum AssignmentArrayElement {
849    Target(AssignmentTargetNode),
850    Elision,
851    Missing(MissingNode),
852}
853
854#[derive(Clone, Debug, Eq, PartialEq)]
855pub struct AssignmentArrayPattern {
856    pub elements: Vec<AssignmentArrayElement>,
857}
858
859#[derive(Clone, Debug, Eq, PartialEq)]
860pub enum AssignmentTarget {
861    Identifier(IdentifierNode),
862    Member(AssignmentMemberTarget),
863    Object(AssignmentObjectPattern),
864    Array(AssignmentArrayPattern),
865    Missing(MissingNode),
866}
867
868impl NodeData for AssignmentTarget {
869    fn node_kind(&self) -> NodeKind {
870        match self {
871            Self::Identifier(_) => NodeKind::IdentifierAssignmentTarget,
872            Self::Member(_) => NodeKind::MemberAssignmentTarget,
873            Self::Object(_) => NodeKind::ObjectAssignmentTarget,
874            Self::Array(_) => NodeKind::ArrayAssignmentTarget,
875            Self::Missing(_) => NodeKind::MissingAssignmentTarget,
876        }
877    }
878}
879
880#[derive(Clone, Debug, Eq, PartialEq)]
881pub struct VariableDeclarator {
882    pub binding: Pattern,
883    pub definite: bool,
884    pub type_annotation: Option<TypeAnnotationNode>,
885    pub initializer: Option<Box<Expr>>,
886}
887
888impl NodeData for VariableDeclarator {
889    fn node_kind(&self) -> NodeKind {
890        NodeKind::VariableDeclarator
891    }
892}
893
894#[derive(Clone, Debug, Eq, PartialEq)]
895pub struct VariableDeclaration {
896    pub kind: VariableKind,
897    pub declarations: Vec<VariableDeclaratorNode>,
898}
899
900#[derive(Clone, Debug, Eq, PartialEq)]
901pub struct FunctionLike {
902    pub decorators: Vec<DecoratorNode>,
903    pub name: Option<IdentifierNode>,
904    pub is_async: bool,
905    pub is_generator: bool,
906    pub type_parameters: Option<TypeParameterList>,
907    pub parameters: Vec<ParameterNode>,
908    pub return_type: Option<TypeAnnotationNode>,
909    pub body: Option<FunctionBody>,
910}
911
912#[derive(Clone, Debug, Eq, PartialEq)]
913pub enum FunctionBody {
914    Block(BlockNode),
915    Expression(Box<Expr>),
916    Missing(MissingNode),
917}
918
919#[derive(Clone, Debug, Eq, PartialEq)]
920pub struct FunctionDeclaration {
921    pub function: FunctionLike,
922}
923
924#[derive(Clone, Debug, Eq, PartialEq)]
925pub struct FunctionExpression {
926    pub function: FunctionLike,
927}
928
929#[derive(Clone, Debug, Eq, PartialEq)]
930pub struct ArrowFunction {
931    pub is_async: bool,
932    pub type_parameters: Option<TypeParameterList>,
933    pub parameters: Vec<ParameterNode>,
934    pub return_type: Option<TypeAnnotationNode>,
935    pub body: FunctionBody,
936}
937
938#[derive(Clone, Debug, Eq, PartialEq)]
939pub struct ConstructorDeclaration {
940    pub modifiers: DeclarationModifiers,
941    pub parameters: Vec<ParameterNode>,
942    pub body: BlockNode,
943}
944
945#[derive(Clone, Debug, Eq, PartialEq)]
946pub struct MethodDeclaration {
947    pub modifiers: DeclarationModifiers,
948    pub modifier: PropertyModifier,
949    pub name: PropertyName,
950    pub optional: bool,
951    pub function: FunctionLike,
952}
953
954#[derive(Clone, Debug, Eq, PartialEq)]
955pub struct ClassProperty {
956    pub modifiers: DeclarationModifiers,
957    pub name: PropertyName,
958    pub optional: bool,
959    pub definite: bool,
960    pub type_annotation: Option<TypeAnnotationNode>,
961    pub initializer: Option<Box<Expr>>,
962}
963
964#[derive(Clone, Debug, Eq, PartialEq)]
965pub struct AutoAccessor {
966    pub modifiers: DeclarationModifiers,
967    pub name: PropertyName,
968    pub type_annotation: Option<TypeAnnotationNode>,
969    pub initializer: Option<Box<Expr>>,
970}
971
972#[derive(Clone, Debug, Eq, PartialEq)]
973pub struct IndexSignature {
974    pub readonly: bool,
975    pub parameters: Vec<ParameterNode>,
976    pub type_annotation: TypeAnnotationNode,
977}
978
979#[derive(Clone, Debug, Eq, PartialEq)]
980pub enum ClassMember {
981    Constructor(ConstructorDeclaration),
982    Method(MethodDeclaration),
983    Property(ClassProperty),
984    AutoAccessor(AutoAccessor),
985    StaticBlock(BlockNode),
986    IndexSignature(IndexSignature),
987    Missing(MissingNode),
988}
989
990impl NodeData for ClassMember {
991    fn node_kind(&self) -> NodeKind {
992        NodeKind::ClassMember
993    }
994}
995
996#[derive(Clone, Debug, Eq, PartialEq)]
997pub struct ClassHeritage {
998    pub expression: Box<Expr>,
999    pub type_arguments: Option<TypeArgumentList>,
1000}
1001
1002#[derive(Clone, Debug, Eq, PartialEq)]
1003pub struct ClassDeclaration {
1004    pub decorators: Vec<DecoratorNode>,
1005    pub modifiers: DeclarationModifiers,
1006    pub name: Option<IdentifierNode>,
1007    pub type_parameters: Option<TypeParameterList>,
1008    pub extends: Option<ClassHeritage>,
1009    pub implements: Vec<Ty>,
1010    pub members: Vec<ClassMemberNode>,
1011}
1012
1013#[derive(Clone, Debug, Eq, PartialEq)]
1014pub struct ClassExpression {
1015    pub class: ClassDeclaration,
1016}
1017
1018#[derive(Clone, Debug, Eq, PartialEq)]
1019pub struct InterfaceDeclaration {
1020    pub name: IdentifierNode,
1021    pub type_parameters: Option<TypeParameterList>,
1022    pub extends: Vec<TypeReference>,
1023    pub members: Vec<TypeMemberNode>,
1024}
1025
1026#[derive(Clone, Debug, Eq, PartialEq)]
1027pub struct TypeAliasDeclaration {
1028    pub name: IdentifierNode,
1029    pub type_parameters: Option<TypeParameterList>,
1030    pub type_node: Box<Ty>,
1031}
1032
1033#[derive(Clone, Debug, Eq, PartialEq)]
1034pub struct EnumDeclaration {
1035    pub is_const: bool,
1036    pub name: IdentifierNode,
1037    pub members: Vec<EnumMemberNode>,
1038}
1039
1040#[derive(Clone, Debug, Eq, PartialEq)]
1041pub struct EnumMember {
1042    pub name: PropertyName,
1043    pub initializer: Option<Box<Expr>>,
1044}
1045
1046impl NodeData for EnumMember {
1047    fn node_kind(&self) -> NodeKind {
1048        NodeKind::EnumMember
1049    }
1050}
1051
1052#[derive(Clone, Debug, Eq, PartialEq)]
1053pub struct NamespaceDeclaration {
1054    pub name: IdentifierNode,
1055    pub body: BlockNode,
1056}
1057
1058#[derive(Clone, Debug, Eq, PartialEq)]
1059pub struct ImportClause {
1060    pub default: Option<IdentifierNode>,
1061    pub binding: Option<ImportBinding>,
1062}
1063
1064#[derive(Clone, Debug, Eq, PartialEq)]
1065pub enum ImportBinding {
1066    Namespace(IdentifierNode),
1067    Named(Vec<ImportSpecifierNode>),
1068}
1069
1070#[derive(Clone, Debug, Eq, PartialEq)]
1071pub struct ImportSpecifier {
1072    pub mode: ImportSpecifierMode,
1073    pub imported: ModuleExportName,
1074    pub local: IdentifierNode,
1075}
1076
1077impl NodeData for ImportSpecifier {
1078    fn node_kind(&self) -> NodeKind {
1079        NodeKind::ImportSpecifier
1080    }
1081}
1082
1083#[derive(Clone, Debug, Eq, PartialEq)]
1084pub struct ImportAttribute {
1085    pub name: ModuleExportName,
1086    pub value: StringLiteralNode,
1087}
1088
1089#[derive(Clone, Debug, Default, Eq, PartialEq)]
1090pub struct ImportAttributes {
1091    pub entries: Vec<ImportAttribute>,
1092}
1093
1094#[derive(Clone, Debug, Eq, PartialEq)]
1095pub struct ImportDeclaration {
1096    pub type_only: bool,
1097    pub clause: Option<ImportClause>,
1098    pub source: StringLiteralNode,
1099    pub attributes: Option<ImportAttributes>,
1100}
1101
1102#[derive(Clone, Debug, Eq, PartialEq)]
1103pub enum ExternalModuleReference {
1104    Require(StringLiteralNode),
1105    Qualified(EntityName),
1106    Missing(MissingNode),
1107}
1108
1109#[derive(Clone, Debug, Eq, PartialEq)]
1110pub struct ImportEqualsDeclaration {
1111    pub is_type_only: bool,
1112    pub local: IdentifierNode,
1113    pub reference: ExternalModuleReference,
1114}
1115
1116#[derive(Clone, Debug, Eq, PartialEq)]
1117pub enum ExportDeclaration {
1118    Named(ExportNamedDeclaration),
1119    All(ExportAllDeclaration),
1120    Default(ExportDefaultDeclaration),
1121    Assignment(Box<Expr>),
1122}
1123
1124#[derive(Clone, Debug, Eq, PartialEq)]
1125pub enum ExportNamedDeclaration {
1126    Declaration(Box<Stmt>),
1127    Specifiers {
1128        type_only: bool,
1129        specifiers: Vec<ExportSpecifierNode>,
1130        source: Option<StringLiteralNode>,
1131        attributes: Option<ImportAttributes>,
1132    },
1133}
1134
1135#[derive(Clone, Debug, Eq, PartialEq)]
1136pub struct ExportAllDeclaration {
1137    pub type_only: bool,
1138    pub exported: Option<ModuleExportName>,
1139    pub source: StringLiteralNode,
1140    pub attributes: Option<ImportAttributes>,
1141}
1142
1143#[derive(Clone, Debug, Eq, PartialEq)]
1144pub enum ExportDefaultValue {
1145    Function(FunctionLike),
1146    Class(ClassDeclaration),
1147    Expression(Box<Expr>),
1148    Missing(MissingNode),
1149}
1150
1151#[derive(Clone, Debug, Eq, PartialEq)]
1152pub struct ExportDefaultDeclaration {
1153    pub value: ExportDefaultValue,
1154}
1155
1156#[derive(Clone, Debug, Eq, PartialEq)]
1157pub struct ExportSpecifier {
1158    pub mode: ExportSpecifierMode,
1159    pub local: ModuleExportName,
1160    pub exported: ModuleExportName,
1161}
1162
1163impl NodeData for ExportSpecifier {
1164    fn node_kind(&self) -> NodeKind {
1165        NodeKind::ExportSpecifier
1166    }
1167}
1168
1169#[derive(Clone, Debug, Eq, PartialEq)]
1170pub struct Block {
1171    pub statements: Vec<Stmt>,
1172}
1173
1174impl NodeData for Block {
1175    fn node_kind(&self) -> NodeKind {
1176        NodeKind::BlockStatement
1177    }
1178}
1179
1180#[derive(Clone, Debug, Eq, PartialEq)]
1181pub struct ExpressionStatement {
1182    pub expression: Box<Expr>,
1183}
1184
1185#[derive(Clone, Debug, Eq, PartialEq)]
1186pub struct IfStatement {
1187    pub test: Box<Expr>,
1188    pub consequent: Box<Stmt>,
1189    pub alternate: Option<Box<Stmt>>,
1190}
1191
1192#[derive(Clone, Debug, Eq, PartialEq)]
1193pub struct SwitchStatement {
1194    pub discriminant: Box<Expr>,
1195    pub cases: Vec<SwitchCaseNode>,
1196}
1197
1198#[derive(Clone, Debug, Eq, PartialEq)]
1199pub struct SwitchCase {
1200    pub test: Option<Box<Expr>>,
1201    pub consequent: Vec<Stmt>,
1202}
1203
1204impl NodeData for SwitchCase {
1205    fn node_kind(&self) -> NodeKind {
1206        NodeKind::SwitchCase
1207    }
1208}
1209
1210#[derive(Clone, Debug, Eq, PartialEq)]
1211pub enum ForInitializer {
1212    Variable(VariableDeclaration),
1213    Expression(Box<Expr>),
1214}
1215
1216#[derive(Clone, Debug, Eq, PartialEq)]
1217pub struct ForStatement {
1218    pub initializer: Option<ForInitializer>,
1219    pub test: Option<Box<Expr>>,
1220    pub update: Option<Box<Expr>>,
1221    pub body: Box<Stmt>,
1222}
1223
1224#[derive(Clone, Debug, Eq, PartialEq)]
1225pub enum ForBinding {
1226    Variable(VariableDeclaration),
1227    Target(AssignmentTargetNode),
1228}
1229
1230#[derive(Clone, Debug, Eq, PartialEq)]
1231pub struct ForInStatement {
1232    pub binding: ForBinding,
1233    pub object: Box<Expr>,
1234    pub body: Box<Stmt>,
1235}
1236
1237#[derive(Clone, Debug, Eq, PartialEq)]
1238pub struct ForOfStatement {
1239    pub mode: ForOfMode,
1240    pub binding: ForBinding,
1241    pub iterable: Box<Expr>,
1242    pub body: Box<Stmt>,
1243}
1244
1245#[derive(Clone, Debug, Eq, PartialEq)]
1246pub struct WhileStatement {
1247    pub test: Box<Expr>,
1248    pub body: Box<Stmt>,
1249}
1250
1251#[derive(Clone, Debug, Eq, PartialEq)]
1252pub struct DoWhileStatement {
1253    pub body: Box<Stmt>,
1254    pub test: Box<Expr>,
1255}
1256
1257#[derive(Clone, Debug, Eq, PartialEq)]
1258pub struct CatchClause {
1259    pub binding: Option<Pattern>,
1260    pub body: BlockNode,
1261}
1262
1263impl NodeData for CatchClause {
1264    fn node_kind(&self) -> NodeKind {
1265        NodeKind::CatchClause
1266    }
1267}
1268
1269#[derive(Clone, Debug, Eq, PartialEq)]
1270pub struct TryStatement {
1271    pub block: BlockNode,
1272    pub handler: Option<CatchClauseNode>,
1273    pub finalizer: Option<BlockNode>,
1274}
1275
1276#[derive(Clone, Debug, Eq, PartialEq)]
1277pub struct WithStatement {
1278    pub object: Box<Expr>,
1279    pub body: Box<Stmt>,
1280}
1281
1282#[derive(Clone, Debug, Eq, PartialEq)]
1283pub struct LabeledStatement {
1284    pub label: IdentifierNode,
1285    pub body: Box<Stmt>,
1286}
1287
1288#[derive(Clone, Debug, Eq, PartialEq)]
1289pub struct JumpStatement {
1290    pub label: Option<IdentifierNode>,
1291}
1292
1293#[derive(Clone, Debug, Eq, PartialEq)]
1294pub struct ReturnStatement {
1295    pub argument: Option<Box<Expr>>,
1296}
1297
1298#[derive(Clone, Debug, Eq, PartialEq)]
1299pub struct ThrowStatement {
1300    pub argument: Box<Expr>,
1301}
1302
1303#[derive(Clone, Debug, Eq, PartialEq)]
1304pub enum Statement {
1305    Import(ImportDeclaration),
1306    ImportEquals(ImportEqualsDeclaration),
1307    Export(ExportDeclaration),
1308    Variable(VariableDeclaration),
1309    Function(FunctionDeclaration),
1310    Class(ClassDeclaration),
1311    Interface(InterfaceDeclaration),
1312    TypeAlias(TypeAliasDeclaration),
1313    Enum(EnumDeclaration),
1314    Namespace(NamespaceDeclaration),
1315    Declare(Box<Stmt>),
1316    Block(BlockNode),
1317    Empty,
1318    Expression(ExpressionStatement),
1319    If(IfStatement),
1320    Switch(SwitchStatement),
1321    For(ForStatement),
1322    ForIn(ForInStatement),
1323    ForOf(ForOfStatement),
1324    While(WhileStatement),
1325    DoWhile(DoWhileStatement),
1326    Try(TryStatement),
1327    With(WithStatement),
1328    Labeled(LabeledStatement),
1329    Break(JumpStatement),
1330    Continue(JumpStatement),
1331    Return(ReturnStatement),
1332    Throw(ThrowStatement),
1333    Debugger,
1334    Missing(MissingNode),
1335}
1336
1337impl Statement {
1338    /// Type-only declarations are erasable without inspecting runtime syntax.
1339    pub const fn is_erasable(&self) -> bool {
1340        matches!(
1341            self,
1342            Self::Interface(_) | Self::TypeAlias(_) | Self::Declare(_)
1343        )
1344    }
1345}
1346
1347impl NodeData for Statement {
1348    fn node_kind(&self) -> NodeKind {
1349        match self {
1350            Self::Import(_) => NodeKind::ImportDeclaration,
1351            Self::ImportEquals(_) => NodeKind::ImportEqualsDeclaration,
1352            Self::Export(_) => NodeKind::ExportDeclaration,
1353            Self::Variable(_) => NodeKind::VariableDeclaration,
1354            Self::Function(_) => NodeKind::FunctionDeclaration,
1355            Self::Class(_) => NodeKind::ClassDeclaration,
1356            Self::Interface(_) => NodeKind::InterfaceDeclaration,
1357            Self::TypeAlias(_) => NodeKind::TypeAliasDeclaration,
1358            Self::Enum(_) => NodeKind::EnumDeclaration,
1359            Self::Namespace(_) => NodeKind::NamespaceDeclaration,
1360            Self::Declare(_) => NodeKind::DeclareStatement,
1361            Self::Block(_) => NodeKind::BlockStatement,
1362            Self::Empty => NodeKind::EmptyStatement,
1363            Self::Expression(_) => NodeKind::ExpressionStatement,
1364            Self::If(_) => NodeKind::IfStatement,
1365            Self::Switch(_) => NodeKind::SwitchStatement,
1366            Self::For(_) => NodeKind::ForStatement,
1367            Self::ForIn(_) => NodeKind::ForInStatement,
1368            Self::ForOf(_) => NodeKind::ForOfStatement,
1369            Self::While(_) => NodeKind::WhileStatement,
1370            Self::DoWhile(_) => NodeKind::DoWhileStatement,
1371            Self::Try(_) => NodeKind::TryStatement,
1372            Self::With(_) => NodeKind::WithStatement,
1373            Self::Labeled(_) => NodeKind::LabeledStatement,
1374            Self::Break(_) => NodeKind::BreakStatement,
1375            Self::Continue(_) => NodeKind::ContinueStatement,
1376            Self::Return(_) => NodeKind::ReturnStatement,
1377            Self::Throw(_) => NodeKind::ThrowStatement,
1378            Self::Debugger => NodeKind::DebuggerStatement,
1379            Self::Missing(_) => NodeKind::MissingStatement,
1380        }
1381    }
1382}
1383
1384#[derive(Clone, Debug, Eq, PartialEq)]
1385pub enum Literal {
1386    String(StringLiteralNode),
1387    Number(NumericLiteralNode),
1388    BigInt(BigIntLiteralNode),
1389    Boolean(BooleanLiteralNode),
1390    Null(NullLiteralNode),
1391    Regex(RegexLiteralNode),
1392}
1393
1394#[derive(Clone, Debug, Eq, PartialEq)]
1395pub struct TemplateLiteral {
1396    pub elements: Vec<TemplateElementNode>,
1397    pub expressions: Vec<Expr>,
1398}
1399
1400#[derive(Clone, Debug, Eq, PartialEq)]
1401pub struct TaggedTemplateExpression {
1402    pub tag: Box<Expr>,
1403    pub template: TemplateLiteral,
1404}
1405
1406#[derive(Clone, Debug, Eq, PartialEq)]
1407pub struct SpreadElement {
1408    pub argument: Box<Expr>,
1409}
1410
1411#[derive(Clone, Debug, Eq, PartialEq)]
1412pub enum ArrayElement {
1413    Expression(Box<Expr>),
1414    Spread(SpreadElement),
1415    Elision,
1416    Missing(MissingNode),
1417}
1418
1419#[derive(Clone, Debug, Eq, PartialEq)]
1420pub struct ArrayLiteral {
1421    pub elements: Vec<ArrayElement>,
1422}
1423
1424#[derive(Clone, Debug, Eq, PartialEq)]
1425pub struct ObjectProperty {
1426    pub name: PropertyName,
1427    pub value: Box<Expr>,
1428    pub modifier: PropertyModifier,
1429    pub shorthand: bool,
1430}
1431
1432#[derive(Clone, Debug, Eq, PartialEq)]
1433pub struct ObjectMethod {
1434    pub name: PropertyName,
1435    pub modifier: PropertyModifier,
1436    pub function: FunctionLike,
1437}
1438
1439#[derive(Clone, Debug, Eq, PartialEq)]
1440pub enum ObjectMember {
1441    Property(ObjectProperty),
1442    Method(ObjectMethod),
1443    Spread(SpreadElement),
1444    Missing(MissingNode),
1445}
1446
1447impl NodeData for ObjectMember {
1448    fn node_kind(&self) -> NodeKind {
1449        NodeKind::ObjectMember
1450    }
1451}
1452
1453#[derive(Clone, Debug, Eq, PartialEq)]
1454pub struct ObjectLiteral {
1455    pub members: Vec<ObjectMemberNode>,
1456}
1457
1458#[derive(Clone, Debug, Eq, PartialEq)]
1459pub enum CallArgument {
1460    Expression(Box<Expr>),
1461    Spread(SpreadElement),
1462    Missing(MissingNode),
1463}
1464
1465#[derive(Clone, Debug, Eq, PartialEq)]
1466pub struct CallExpression {
1467    pub callee: Box<Expr>,
1468    pub optional: bool,
1469    pub type_arguments: Option<TypeArgumentList>,
1470    pub arguments: Vec<CallArgument>,
1471}
1472
1473#[derive(Clone, Debug, Eq, PartialEq)]
1474pub struct NewExpression {
1475    pub callee: Box<Expr>,
1476    pub type_arguments: Option<TypeArgumentList>,
1477    pub arguments: Vec<CallArgument>,
1478}
1479
1480#[derive(Clone, Debug, Eq, PartialEq)]
1481pub struct AwaitExpression {
1482    pub argument: Box<Expr>,
1483}
1484
1485#[derive(Clone, Debug, Eq, PartialEq)]
1486pub struct YieldExpression {
1487    pub delegate: bool,
1488    pub argument: Option<Box<Expr>>,
1489}
1490
1491#[derive(Clone, Debug, Eq, PartialEq)]
1492pub struct UnaryExpression {
1493    pub operator: UnaryOperator,
1494    pub argument: Box<Expr>,
1495}
1496
1497#[derive(Clone, Debug, Eq, PartialEq)]
1498pub struct UpdateExpression {
1499    pub operator: UpdateOperator,
1500    pub argument: Box<AssignmentTargetNode>,
1501    pub prefix: bool,
1502}
1503
1504#[derive(Clone, Debug, Eq, PartialEq)]
1505pub struct BinaryExpression {
1506    pub operator: BinaryOperator,
1507    pub left: Box<Expr>,
1508    pub right: Box<Expr>,
1509}
1510
1511#[derive(Clone, Debug, Eq, PartialEq)]
1512pub struct LogicalExpression {
1513    pub operator: LogicalOperator,
1514    pub left: Box<Expr>,
1515    pub right: Box<Expr>,
1516}
1517
1518#[derive(Clone, Debug, Eq, PartialEq)]
1519pub struct ConditionalExpression {
1520    pub test: Box<Expr>,
1521    pub consequent: Box<Expr>,
1522    pub alternate: Box<Expr>,
1523}
1524
1525#[derive(Clone, Debug, Eq, PartialEq)]
1526pub struct AssignmentExpression {
1527    pub operator: AssignmentOperator,
1528    pub left: AssignmentTargetNode,
1529    pub right: Box<Expr>,
1530}
1531
1532#[derive(Clone, Debug, Eq, PartialEq)]
1533pub struct SequenceExpression {
1534    pub expressions: Vec<Expr>,
1535}
1536
1537#[derive(Clone, Debug, Eq, PartialEq)]
1538pub struct AsExpression {
1539    pub expression: Box<Expr>,
1540    pub type_node: Option<Box<Ty>>,
1541}
1542
1543#[derive(Clone, Debug, Eq, PartialEq)]
1544pub struct SatisfiesExpression {
1545    pub expression: Box<Expr>,
1546    pub type_node: Box<Ty>,
1547}
1548
1549#[derive(Clone, Debug, Eq, PartialEq)]
1550pub struct TypeAssertionExpression {
1551    pub expression: Box<Expr>,
1552    pub type_node: Box<Ty>,
1553}
1554
1555#[derive(Clone, Debug, Eq, PartialEq)]
1556pub struct NonNullExpression {
1557    pub expression: Box<Expr>,
1558}
1559
1560#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
1561pub enum MetaProperty {
1562    NewTarget,
1563    ImportMeta,
1564}
1565
1566#[derive(Clone, Debug, Eq, PartialEq)]
1567pub struct ImportExpression {
1568    pub source: Box<Expr>,
1569    pub options: Option<Box<Expr>>,
1570}
1571
1572#[derive(Clone, Debug, Eq, PartialEq)]
1573pub enum Expression {
1574    Identifier(IdentifierNode),
1575    This,
1576    Super,
1577    Literal(Literal),
1578    Template(TemplateLiteral),
1579    TaggedTemplate(TaggedTemplateExpression),
1580    Array(ArrayLiteral),
1581    Object(ObjectLiteral),
1582    Function(FunctionExpression),
1583    Class(ClassExpression),
1584    Arrow(ArrowFunction),
1585    Call(CallExpression),
1586    Member(MemberExpression),
1587    New(NewExpression),
1588    Await(AwaitExpression),
1589    Yield(YieldExpression),
1590    Unary(UnaryExpression),
1591    Update(UpdateExpression),
1592    Binary(BinaryExpression),
1593    Logical(LogicalExpression),
1594    Conditional(ConditionalExpression),
1595    Assignment(AssignmentExpression),
1596    Sequence(SequenceExpression),
1597    Parenthesized(Box<Expr>),
1598    As(AsExpression),
1599    Satisfies(SatisfiesExpression),
1600    TypeAssertion(TypeAssertionExpression),
1601    NonNull(NonNullExpression),
1602    Import(ImportExpression),
1603    Meta(MetaProperty),
1604    Missing(MissingNode),
1605}
1606
1607impl NodeData for Expression {
1608    fn node_kind(&self) -> NodeKind {
1609        match self {
1610            Self::Identifier(_) => NodeKind::IdentifierExpression,
1611            Self::This => NodeKind::ThisExpression,
1612            Self::Super => NodeKind::SuperExpression,
1613            Self::Literal(_) => NodeKind::LiteralExpression,
1614            Self::Template(_) => NodeKind::TemplateExpression,
1615            Self::TaggedTemplate(_) => NodeKind::TaggedTemplateExpression,
1616            Self::Array(_) => NodeKind::ArrayExpression,
1617            Self::Object(_) => NodeKind::ObjectExpression,
1618            Self::Function(_) => NodeKind::FunctionExpression,
1619            Self::Class(_) => NodeKind::ClassExpression,
1620            Self::Arrow(_) => NodeKind::ArrowFunction,
1621            Self::Call(_) => NodeKind::CallExpression,
1622            Self::Member(_) => NodeKind::MemberExpression,
1623            Self::New(_) => NodeKind::NewExpression,
1624            Self::Await(_) => NodeKind::AwaitExpression,
1625            Self::Yield(_) => NodeKind::YieldExpression,
1626            Self::Unary(_) => NodeKind::UnaryExpression,
1627            Self::Update(_) => NodeKind::UpdateExpression,
1628            Self::Binary(_) => NodeKind::BinaryExpression,
1629            Self::Logical(_) => NodeKind::LogicalExpression,
1630            Self::Conditional(_) => NodeKind::ConditionalExpression,
1631            Self::Assignment(_) => NodeKind::AssignmentExpression,
1632            Self::Sequence(_) => NodeKind::SequenceExpression,
1633            Self::Parenthesized(_) => NodeKind::ParenthesizedExpression,
1634            Self::As(_) => NodeKind::AsExpression,
1635            Self::Satisfies(_) => NodeKind::SatisfiesExpression,
1636            Self::TypeAssertion(_) => NodeKind::TypeAssertionExpression,
1637            Self::NonNull(_) => NodeKind::NonNullExpression,
1638            Self::Import(_) => NodeKind::ImportExpression,
1639            Self::Meta(_) => NodeKind::MetaProperty,
1640            Self::Missing(_) => NodeKind::MissingExpression,
1641        }
1642    }
1643}
1644
1645#[derive(Clone, Debug, Eq, PartialEq)]
1646pub enum EntityName {
1647    Identifier(IdentifierNode),
1648    Qualified {
1649        left: Box<EntityName>,
1650        right: IdentifierNode,
1651    },
1652    Missing(MissingNode),
1653}
1654
1655#[derive(Clone, Debug, Eq, PartialEq)]
1656pub struct TypeReference {
1657    pub name: EntityName,
1658    pub type_arguments: Option<TypeArgumentList>,
1659}
1660
1661#[derive(Clone, Debug, Eq, PartialEq)]
1662pub enum TypeLiteral {
1663    String(StringLiteralNode),
1664    Number(NumericLiteralNode),
1665    BigInt(BigIntLiteralNode),
1666    Boolean(BooleanLiteralNode),
1667    Null(NullLiteralNode),
1668    Unary {
1669        operator: UnaryOperator,
1670        operand: Box<Ty>,
1671    },
1672}
1673
1674#[derive(Clone, Debug, Eq, PartialEq)]
1675pub struct TupleElement {
1676    pub name: Option<IdentifierNode>,
1677    pub optional: bool,
1678    pub rest: bool,
1679    pub type_node: Box<Ty>,
1680}
1681
1682#[derive(Clone, Debug, Eq, PartialEq)]
1683pub struct TupleType {
1684    pub readonly: bool,
1685    pub elements: Vec<TupleElement>,
1686}
1687
1688#[derive(Clone, Debug, Eq, PartialEq)]
1689pub struct FunctionTypeParameter {
1690    pub name: IdentifierNode,
1691    pub optional: bool,
1692    pub rest: bool,
1693    pub type_annotation: TypeAnnotationNode,
1694}
1695
1696#[derive(Clone, Debug, Eq, PartialEq)]
1697pub struct FunctionType {
1698    pub type_parameters: Option<TypeParameterList>,
1699    pub parameters: Vec<FunctionTypeParameter>,
1700    pub return_type: Box<Ty>,
1701}
1702
1703#[derive(Clone, Debug, Eq, PartialEq)]
1704pub struct ConstructorType {
1705    pub is_abstract: bool,
1706    pub function: FunctionType,
1707}
1708
1709#[derive(Clone, Debug, Eq, PartialEq)]
1710pub struct TypeQuery {
1711    pub name: EntityName,
1712    pub type_arguments: Option<TypeArgumentList>,
1713}
1714
1715#[derive(Clone, Debug, Eq, PartialEq)]
1716pub struct IndexedAccessType {
1717    pub object_type: Box<Ty>,
1718    pub index_type: Box<Ty>,
1719}
1720
1721#[derive(Clone, Debug, Eq, PartialEq)]
1722pub struct ConditionalType {
1723    pub check_type: Box<Ty>,
1724    pub extends_type: Box<Ty>,
1725    pub true_type: Box<Ty>,
1726    pub false_type: Box<Ty>,
1727}
1728
1729#[derive(Clone, Debug, Eq, PartialEq)]
1730pub struct MappedType {
1731    pub readonly_modifier: MappedModifier,
1732    pub parameter: TypeParameterNode,
1733    pub name_type: Option<Box<Ty>>,
1734    pub optional_modifier: MappedModifier,
1735    pub value_type: Option<Box<Ty>>,
1736}
1737
1738#[derive(Clone, Debug, Eq, PartialEq)]
1739pub struct InferType {
1740    pub parameter: TypeParameterNode,
1741}
1742
1743#[derive(Clone, Debug, Eq, PartialEq)]
1744pub struct ImportType {
1745    pub argument: StringLiteralNode,
1746    pub qualifier: Option<EntityName>,
1747    pub type_arguments: Option<TypeArgumentList>,
1748    pub attributes: Option<ImportAttributes>,
1749}
1750
1751#[derive(Clone, Debug, Eq, PartialEq)]
1752pub struct TemplateLiteralType {
1753    pub elements: Vec<TemplateElementNode>,
1754    pub types: Vec<Ty>,
1755}
1756
1757#[derive(Clone, Debug, Eq, PartialEq)]
1758pub struct TypePredicate {
1759    pub asserts: bool,
1760    pub parameter_name: EntityName,
1761    pub type_node: Option<Box<Ty>>,
1762}
1763
1764#[derive(Clone, Debug, Eq, PartialEq)]
1765pub struct TypePropertySignature {
1766    pub readonly: bool,
1767    pub name: PropertyName,
1768    pub optional: bool,
1769    pub type_annotation: Option<TypeAnnotationNode>,
1770}
1771
1772#[derive(Clone, Debug, Eq, PartialEq)]
1773pub struct TypeMethodSignature {
1774    pub name: PropertyName,
1775    pub optional: bool,
1776    pub function: FunctionType,
1777}
1778
1779#[derive(Clone, Debug, Eq, PartialEq)]
1780pub struct CallSignature {
1781    pub function: FunctionType,
1782}
1783
1784#[derive(Clone, Debug, Eq, PartialEq)]
1785pub struct ConstructSignature {
1786    pub function: ConstructorType,
1787}
1788
1789#[derive(Clone, Debug, Eq, PartialEq)]
1790pub struct TypeIndexSignature {
1791    pub readonly: bool,
1792    pub parameters: Vec<FunctionTypeParameter>,
1793    pub type_annotation: TypeAnnotationNode,
1794}
1795
1796#[derive(Clone, Debug, Eq, PartialEq)]
1797pub enum TypeMember {
1798    Property(TypePropertySignature),
1799    Method(TypeMethodSignature),
1800    Call(CallSignature),
1801    Construct(ConstructSignature),
1802    Index(TypeIndexSignature),
1803    Missing(MissingNode),
1804}
1805
1806impl NodeData for TypeMember {
1807    fn node_kind(&self) -> NodeKind {
1808        NodeKind::TypeMember
1809    }
1810}
1811
1812#[derive(Clone, Debug, Eq, PartialEq)]
1813pub struct ObjectType {
1814    pub members: Vec<TypeMemberNode>,
1815}
1816
1817/// Type syntax is kept in this closed enum so erasure never has to inspect a
1818/// runtime expression variant.
1819#[derive(Clone, Debug, Eq, PartialEq)]
1820pub enum TypeNode {
1821    Keyword(KeywordType),
1822    Literal(TypeLiteral),
1823    Reference(TypeReference),
1824    Union(Vec<Ty>),
1825    Intersection(Vec<Ty>),
1826    Array(Box<Ty>),
1827    Tuple(TupleType),
1828    Object(ObjectType),
1829    Function(FunctionType),
1830    Constructor(ConstructorType),
1831    Query(TypeQuery),
1832    Operator {
1833        operator: TypeOperator,
1834        operand: Box<Ty>,
1835    },
1836    IndexedAccess(IndexedAccessType),
1837    Conditional(ConditionalType),
1838    Mapped(MappedType),
1839    Infer(InferType),
1840    Import(ImportType),
1841    TemplateLiteral(TemplateLiteralType),
1842    Parenthesized(Box<Ty>),
1843    This,
1844    Predicate(TypePredicate),
1845    Missing(MissingNode),
1846}
1847
1848impl NodeData for TypeNode {
1849    fn node_kind(&self) -> NodeKind {
1850        match self {
1851            Self::Keyword(_) => NodeKind::KeywordType,
1852            Self::Literal(_) => NodeKind::LiteralType,
1853            Self::Reference(_) => NodeKind::TypeReference,
1854            Self::Union(_) => NodeKind::UnionType,
1855            Self::Intersection(_) => NodeKind::IntersectionType,
1856            Self::Array(_) => NodeKind::ArrayType,
1857            Self::Tuple(_) => NodeKind::TupleType,
1858            Self::Object(_) => NodeKind::ObjectType,
1859            Self::Function(_) => NodeKind::FunctionType,
1860            Self::Constructor(_) => NodeKind::ConstructorType,
1861            Self::Query(_) => NodeKind::TypeQuery,
1862            Self::Operator { .. } => NodeKind::TypeOperator,
1863            Self::IndexedAccess(_) => NodeKind::IndexedAccessType,
1864            Self::Conditional(_) => NodeKind::ConditionalType,
1865            Self::Mapped(_) => NodeKind::MappedType,
1866            Self::Infer(_) => NodeKind::InferType,
1867            Self::Import(_) => NodeKind::ImportType,
1868            Self::TemplateLiteral(_) => NodeKind::TemplateLiteralType,
1869            Self::Parenthesized(_) => NodeKind::ParenthesizedType,
1870            Self::This => NodeKind::ThisType,
1871            Self::Predicate(_) => NodeKind::TypePredicate,
1872            Self::Missing(_) => NodeKind::MissingType,
1873        }
1874    }
1875}
1876
1877/// The immutable parser product. Diagnostics retain parser order by value;
1878/// callers cannot mutate the tree, token stream, or diagnostics through this
1879/// API.
1880pub struct SourceFile {
1881    id: NodeId,
1882    range: TextRange,
1883    source_id: SourceId,
1884    script_kind: ScriptKind,
1885    source: Arc<SourceText>,
1886    tokens: Vec<Token>,
1887    statements: Vec<Stmt>,
1888    eof: Token,
1889    diagnostics: Vec<Diagnostic>,
1890}
1891
1892impl SourceFile {
1893    #[allow(clippy::too_many_arguments)]
1894    pub fn new(
1895        id: NodeId,
1896        source_id: SourceId,
1897        script_kind: ScriptKind,
1898        range: TextRange,
1899        source: Arc<SourceText>,
1900        tokens: Vec<Token>,
1901        statements: Vec<Stmt>,
1902        eof: Token,
1903        diagnostics: Vec<Diagnostic>,
1904    ) -> Self {
1905        Self {
1906            id,
1907            range,
1908            source_id,
1909            script_kind,
1910            source,
1911            tokens,
1912            statements,
1913            eof,
1914            diagnostics,
1915        }
1916    }
1917
1918    pub const fn id(&self) -> NodeId {
1919        self.id
1920    }
1921
1922    pub const fn kind(&self) -> NodeKind {
1923        NodeKind::SourceFile
1924    }
1925
1926    pub const fn syntax_kind(&self) -> SyntaxKind {
1927        SyntaxKind::Node(NodeKind::SourceFile)
1928    }
1929
1930    pub const fn range(&self) -> TextRange {
1931        self.range
1932    }
1933
1934    pub const fn source_id(&self) -> SourceId {
1935        self.source_id
1936    }
1937
1938    pub const fn script_kind(&self) -> ScriptKind {
1939        self.script_kind
1940    }
1941
1942    pub fn source_text(&self) -> &SourceText {
1943        &self.source
1944    }
1945
1946    /// Non-EOF source tokens in lexical order.
1947    pub fn tokens(&self) -> &[Token] {
1948        &self.tokens
1949    }
1950
1951    /// Returns the zero-copy lexeme for a token range in this source file.
1952    ///
1953    /// `None` identifies a range that is not a valid UTF-16 slice of this
1954    /// file, which cannot arise from a parser-produced token.
1955    pub fn token_text(&self, token: &Token) -> Option<&str> {
1956        if token.is_missing() {
1957            return Some("");
1958        }
1959
1960        let range = token.range();
1961        let start = self.source.utf16_to_byte(range.start()).ok()?;
1962        let end = self.source.utf16_to_byte(range.end()).ok()?;
1963        self.source.as_str().get(start..end)
1964    }
1965
1966    pub fn eof(&self) -> &Token {
1967        &self.eof
1968    }
1969
1970    pub fn statements(&self) -> &[Stmt] {
1971        &self.statements
1972    }
1973
1974    /// Parser diagnostics in the parser's stable source order.
1975    pub fn diagnostics(&self) -> &[Diagnostic] {
1976        &self.diagnostics
1977    }
1978}
1979
1980#[cfg(test)]
1981mod tests {
1982
1983    use super::*;
1984    use crate::source::Utf16Pos;
1985
1986    fn range(start: usize, end: usize) -> TextRange {
1987        TextRange::new(Utf16Pos::new(start), Utf16Pos::new(end)).expect("ordered test range")
1988    }
1989
1990    #[test]
1991    fn token_and_node_categories_stay_distinct() {
1992        let token = Token::new(TokenKind::Identifier, range(0, 1));
1993        let identifier = Node::new(NodeId::new(1), range(0, 1), Identifier::new(token));
1994        let expression = Node::new(
1995            NodeId::new(2),
1996            range(0, 1),
1997            Expression::Identifier(identifier),
1998        );
1999        let missing = Token::missing(TokenKind::RParen, range(1, 1));
2000
2001        assert_eq!(
2002            token.syntax_kind(),
2003            SyntaxKind::Token(TokenKind::Identifier)
2004        );
2005        assert_eq!(
2006            expression.syntax_kind(),
2007            SyntaxKind::Node(NodeKind::IdentifierExpression)
2008        );
2009        assert!(token.syntax_kind().is_token());
2010        assert!(expression.syntax_kind().is_node());
2011        assert!(missing.is_missing());
2012        assert_eq!(missing.kind(), TokenKind::RParen);
2013    }
2014
2015    #[test]
2016    fn nodes_cover_their_nested_ranges() {
2017        let name = Node::new(
2018            NodeId::new(2),
2019            range(4, 5),
2020            Identifier::new(Token::new(TokenKind::Identifier, range(4, 5))),
2021        );
2022        let binding = Node::new(
2023            NodeId::new(3),
2024            range(4, 5),
2025            BindingPattern::Identifier(name),
2026        );
2027        let declarator = Node::new(
2028            NodeId::new(4),
2029            range(4, 9),
2030            VariableDeclarator {
2031                binding,
2032                definite: false,
2033                type_annotation: None,
2034                initializer: None,
2035            },
2036        );
2037        let statement = Node::new(
2038            NodeId::new(1),
2039            range(0, 9),
2040            Statement::Variable(VariableDeclaration {
2041                kind: VariableKind::Let,
2042                declarations: vec![declarator],
2043            }),
2044        );
2045
2046        assert_eq!(statement.range().start().get(), 0);
2047        assert_eq!(statement.range().end().get(), 9);
2048        assert_eq!(statement.kind(), NodeKind::VariableDeclaration);
2049    }
2050
2051    #[test]
2052    fn source_file_owns_recovered_nodes_and_diagnostics() {
2053        let missing = Node::new(
2054            NodeId::new(1),
2055            range(4, 4),
2056            Expression::Missing(MissingNode::new(NodeKind::IdentifierExpression)),
2057        );
2058        let statement = Node::new(
2059            NodeId::new(2),
2060            range(0, 5),
2061            Statement::Expression(ExpressionStatement {
2062                expression: Box::new(missing),
2063            }),
2064        );
2065        let source = std::sync::Arc::new(SourceText::new("let ;"));
2066        let eof = Token::new(TokenKind::EndOfFile, range(5, 5));
2067        let file = SourceFile::new(
2068            NodeId::new(0),
2069            SourceId::new(7),
2070            ScriptKind::TypeScript,
2071            range(0, 5),
2072            source,
2073            vec![Token::new(TokenKind::KwLet, range(0, 3))],
2074            vec![statement],
2075            eof,
2076            Vec::new(),
2077        );
2078
2079        assert_eq!(file.script_kind(), ScriptKind::TypeScript);
2080        assert_eq!(file.range().end().get(), 5);
2081        assert_eq!(file.statements().len(), 1);
2082        assert!(file.diagnostics().is_empty());
2083        assert_eq!(file.token_text(&file.tokens()[0]), Some("let"));
2084        assert_eq!(file.statements()[0].kind(), NodeKind::ExpressionStatement);
2085    }
2086}