Skip to main content

parsec_js/
ast.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 James Conway
3
4//! The syntax tree: every node in one arena, addressed by [`NodeId`],
5//! with its [`Span`] beside it and its children's ids inside it.
6//!
7//! A node holds no text. An identifier's name, a string's value, a
8//! number's: each is in the source at the node's span, and
9//! [`Ast::to_estree`] reads it from there. A list of children (a block's
10//! statements, a call's arguments) is a [`List`], a range of one shared
11//! vector, so building a tree allocates a few vectors, not one per node.
12//!
13//! The node kinds follow ESTree's, so a tool written for acorn's tree
14//! finds what it expects, with one addition: [`Node::Paren`] keeps
15//! parentheses, which ESTree drops and the grammar's early errors need.
16
17use std::num::NonZeroU32;
18
19use parsec_base::{Diagnostic, Span};
20
21use crate::SourceType;
22
23/// A node in an [`Ast`].
24#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
25pub struct NodeId(NonZeroU32);
26
27impl NodeId {
28    pub(crate) fn new(index: usize) -> NodeId {
29        NodeId(NonZeroU32::new(index as u32).expect("node 0 is never handed out"))
30    }
31
32    pub const fn index(self) -> usize {
33        self.0.get() as usize
34    }
35}
36
37/// A run of nodes: `len` ids from `start` in the arena's shared list.
38#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
39pub struct List {
40    pub(crate) start: u32,
41    pub(crate) len: u32,
42}
43
44impl List {
45    pub const fn len(self) -> usize {
46        self.len as usize
47    }
48
49    pub const fn is_empty(self) -> bool {
50        self.len == 0
51    }
52}
53
54/// A comment, kept beside the tree rather than in it.
55#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
56pub struct Comment {
57    pub kind: CommentKind,
58    /// The whole comment, its `//`, `/* */`, `<!--` or `-->` included.
59    pub span: Span,
60}
61
62#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
63pub enum CommentKind {
64    /// `// ...`
65    Line,
66    /// `/* ... */`
67    Block,
68    /// `#!...` on the first line.
69    Hashbang,
70    /// Annex B's `<!-- ...`, in scripts.
71    HtmlOpen,
72    /// Annex B's `--> ...` at the start of a line, in scripts.
73    HtmlClose,
74}
75
76/// `var`, `let` or `const`.
77#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
78pub enum VarKind {
79    Var,
80    Let,
81    Const,
82}
83
84impl VarKind {
85    pub const fn as_str(self) -> &'static str {
86        match self {
87            VarKind::Var => "var",
88            VarKind::Let => "let",
89            VarKind::Const => "const",
90        }
91    }
92}
93
94/// What a literal is. Its value is in its text.
95#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
96pub enum LiteralKind {
97    String,
98    Number,
99    BigInt,
100    Boolean,
101    Null,
102    RegExp,
103}
104
105/// Which of the three a function is, as ESTree names them.
106#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
107pub enum FunctionKind {
108    Declaration,
109    Expression,
110    Arrow,
111}
112
113/// A function of any kind: a declaration, an expression, an arrow, or
114/// the value of a method.
115#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
116pub struct Function {
117    pub kind: FunctionKind,
118    pub id: Option<NodeId>,
119    pub params: List,
120    /// A block, or for an arrow with an expression body, the expression.
121    pub body: NodeId,
122    pub is_async: bool,
123    pub generator: bool,
124    /// An arrow whose body is an expression, not a block.
125    pub expression: bool,
126}
127
128/// A class declaration or expression.
129#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
130pub struct Class {
131    pub declaration: bool,
132    pub id: Option<NodeId>,
133    pub super_class: Option<NodeId>,
134    /// A [`Node::ClassBody`].
135    pub body: NodeId,
136}
137
138/// An object literal's, or an object pattern's, `kind`.
139#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
140pub enum PropertyKind {
141    Init,
142    Get,
143    Set,
144}
145
146impl PropertyKind {
147    pub const fn as_str(self) -> &'static str {
148        match self {
149            PropertyKind::Init => "init",
150            PropertyKind::Get => "get",
151            PropertyKind::Set => "set",
152        }
153    }
154}
155
156/// A class method's `kind`.
157#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
158pub enum MethodKind {
159    Constructor,
160    Method,
161    Get,
162    Set,
163}
164
165impl MethodKind {
166    pub const fn as_str(self) -> &'static str {
167        match self {
168            MethodKind::Constructor => "constructor",
169            MethodKind::Method => "method",
170            MethodKind::Get => "get",
171            MethodKind::Set => "set",
172        }
173    }
174}
175
176macro_rules! ops {
177    ($(#[$m:meta])* $name:ident { $($variant:ident = $text:literal,)* }) => {
178        $(#[$m])*
179        #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
180        pub enum $name {
181            $($variant,)*
182        }
183
184        impl $name {
185            pub const fn as_str(self) -> &'static str {
186                match self {
187                    $($name::$variant => $text,)*
188                }
189            }
190        }
191    };
192}
193
194ops! {
195    UnaryOp {
196        Minus = "-",
197        Plus = "+",
198        Not = "!",
199        BitNot = "~",
200        Typeof = "typeof",
201        Void = "void",
202        Delete = "delete",
203    }
204}
205
206ops! {
207    UpdateOp {
208        Increment = "++",
209        Decrement = "--",
210    }
211}
212
213ops! {
214    BinaryOp {
215        Eq = "==",
216        NotEq = "!=",
217        StrictEq = "===",
218        StrictNotEq = "!==",
219        Lt = "<",
220        LtEq = "<=",
221        Gt = ">",
222        GtEq = ">=",
223        Shl = "<<",
224        Shr = ">>",
225        UShr = ">>>",
226        Add = "+",
227        Sub = "-",
228        Mul = "*",
229        Div = "/",
230        Rem = "%",
231        Exp = "**",
232        BitOr = "|",
233        BitXor = "^",
234        BitAnd = "&",
235        In = "in",
236        Instanceof = "instanceof",
237    }
238}
239
240ops! {
241    LogicalOp {
242        Or = "||",
243        And = "&&",
244        Coalesce = "??",
245    }
246}
247
248ops! {
249    AssignOp {
250        Assign = "=",
251        Add = "+=",
252        Sub = "-=",
253        Mul = "*=",
254        Div = "/=",
255        Rem = "%=",
256        Exp = "**=",
257        Shl = "<<=",
258        Shr = ">>=",
259        UShr = ">>>=",
260        BitOr = "|=",
261        BitXor = "^=",
262        BitAnd = "&=",
263        Or = "||=",
264        And = "&&=",
265        Coalesce = "??=",
266    }
267}
268
269/// A node. The variants are ESTree's node types, named without their
270/// `Statement` and `Expression` suffixes where those are plain.
271#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
272pub enum Node {
273    /// The whole source. Its span is the whole input.
274    Program {
275        body: List,
276        source_type: SourceType,
277    },
278
279    // Statements.
280    /// An expression as a statement; `directive` when it's a string in a
281    /// directive prologue, like `"use strict"`.
282    Expression {
283        expression: NodeId,
284        directive: bool,
285    },
286    Block {
287        body: List,
288    },
289    Empty,
290    Debugger,
291    With {
292        object: NodeId,
293        body: NodeId,
294    },
295    Return {
296        argument: Option<NodeId>,
297    },
298    Labeled {
299        label: NodeId,
300        body: NodeId,
301    },
302    Break {
303        label: Option<NodeId>,
304    },
305    Continue {
306        label: Option<NodeId>,
307    },
308    If {
309        test: NodeId,
310        consequent: NodeId,
311        alternate: Option<NodeId>,
312    },
313    Switch {
314        discriminant: NodeId,
315        cases: List,
316    },
317    SwitchCase {
318        test: Option<NodeId>,
319        consequent: List,
320    },
321    Throw {
322        argument: NodeId,
323    },
324    Try {
325        block: NodeId,
326        handler: Option<NodeId>,
327        finalizer: Option<NodeId>,
328    },
329    CatchClause {
330        param: Option<NodeId>,
331        body: NodeId,
332    },
333    While {
334        test: NodeId,
335        body: NodeId,
336    },
337    DoWhile {
338        body: NodeId,
339        test: NodeId,
340    },
341    For {
342        init: Option<NodeId>,
343        test: Option<NodeId>,
344        update: Option<NodeId>,
345        body: NodeId,
346    },
347    ForIn {
348        left: NodeId,
349        right: NodeId,
350        body: NodeId,
351    },
352    ForOf {
353        left: NodeId,
354        right: NodeId,
355        body: NodeId,
356        is_await: bool,
357    },
358    VariableDeclaration {
359        kind: VarKind,
360        declarations: List,
361    },
362    VariableDeclarator {
363        id: NodeId,
364        init: Option<NodeId>,
365    },
366    Function(Function),
367    Class(Class),
368    ClassBody {
369        body: List,
370    },
371    /// A class method; `value` is its function.
372    Method {
373        key: NodeId,
374        value: NodeId,
375        kind: MethodKind,
376        computed: bool,
377        is_static: bool,
378    },
379    /// A class field, ESTree's PropertyDefinition.
380    Field {
381        key: NodeId,
382        value: Option<NodeId>,
383        computed: bool,
384        is_static: bool,
385    },
386    StaticBlock {
387        body: List,
388    },
389
390    // Expressions.
391    Identifier,
392    /// `#name`; the span includes the `#`.
393    PrivateIdentifier,
394    Literal(LiteralKind),
395    This,
396    Super,
397    /// `elements` has a [`Node::Elision`] for each hole.
398    Array {
399        elements: List,
400        comma_after_spread: bool,
401    },
402    /// A hole in an array: the nothing between `[,` and `,]`.
403    Elision,
404    Object {
405        properties: List,
406        comma_after_spread: bool,
407    },
408    /// An object literal's or object pattern's property.
409    Property {
410        key: NodeId,
411        value: NodeId,
412        kind: PropertyKind,
413        method: bool,
414        shorthand: bool,
415        computed: bool,
416    },
417    Template {
418        quasis: List,
419        expressions: List,
420    },
421    /// A template's text between delimiters; the span leaves the
422    /// delimiters out, as acorn's does. `cooked` is false for a tagged
423    /// template's invalid escape, whose cooked value is undefined.
424    TemplateElement {
425        tail: bool,
426        cooked: bool,
427    },
428    TaggedTemplate {
429        tag: NodeId,
430        quasi: NodeId,
431    },
432    Unary {
433        operator: UnaryOp,
434        argument: NodeId,
435    },
436    Update {
437        operator: UpdateOp,
438        prefix: bool,
439        argument: NodeId,
440    },
441    Binary {
442        operator: BinaryOp,
443        left: NodeId,
444        right: NodeId,
445    },
446    Logical {
447        operator: LogicalOp,
448        left: NodeId,
449        right: NodeId,
450    },
451    Assign {
452        operator: AssignOp,
453        left: NodeId,
454        right: NodeId,
455    },
456    Conditional {
457        test: NodeId,
458        consequent: NodeId,
459        alternate: NodeId,
460    },
461    Call {
462        callee: NodeId,
463        arguments: List,
464        optional: bool,
465    },
466    New {
467        callee: NodeId,
468        arguments: List,
469    },
470    Member {
471        object: NodeId,
472        property: NodeId,
473        computed: bool,
474        optional: bool,
475    },
476    /// An optional chain, `a?.b.c`, from its start to its end.
477    Chain {
478        expression: NodeId,
479    },
480    Sequence {
481        expressions: List,
482    },
483    Yield {
484        argument: Option<NodeId>,
485        delegate: bool,
486    },
487    Await {
488        argument: NodeId,
489    },
490    Spread {
491        argument: NodeId,
492    },
493    /// `new.target` or `import.meta`.
494    MetaProperty {
495        meta: NodeId,
496        property: NodeId,
497    },
498    /// `import(source)` or `import(source, options)`.
499    Import {
500        source: NodeId,
501        options: Option<NodeId>,
502    },
503    /// A parenthesized expression. ESTree has no such node, and
504    /// [`Ast::to_estree`] writes the expression inside instead.
505    Paren {
506        expression: NodeId,
507    },
508
509    // Modules.
510    /// `import ... from "source" with { ... }`; `attributes` are
511    /// [`Node::ImportAttribute`]s.
512    ImportDeclaration {
513        specifiers: List,
514        source: NodeId,
515        attributes: List,
516    },
517    /// `imported as local`, or one name as both; `imported` may be a
518    /// string literal.
519    ImportSpecifier {
520        imported: NodeId,
521        local: NodeId,
522    },
523    ImportDefaultSpecifier {
524        local: NodeId,
525    },
526    /// `* as local`.
527    ImportNamespaceSpecifier {
528        local: NodeId,
529    },
530    /// `type: "json"` in a `with` clause.
531    ImportAttribute {
532        key: NodeId,
533        value: NodeId,
534    },
535    /// `export` with a declaration, or with `{ ... }` and maybe a source.
536    ExportNamed {
537        declaration: Option<NodeId>,
538        specifiers: List,
539        source: Option<NodeId>,
540        attributes: List,
541    },
542    /// `local as exported`, or one name as both; either may be a string
543    /// literal.
544    ExportSpecifier {
545        local: NodeId,
546        exported: NodeId,
547    },
548    /// `export default`, with a declaration or an expression.
549    ExportDefault {
550        declaration: NodeId,
551    },
552    /// `export * from "source"`, or `export * as exported from ...`.
553    ExportAll {
554        exported: Option<NodeId>,
555        source: NodeId,
556        attributes: List,
557    },
558
559    // Patterns.
560    ObjectPattern {
561        properties: List,
562    },
563    ArrayPattern {
564        elements: List,
565    },
566    Rest {
567        argument: NodeId,
568    },
569    AssignmentPattern {
570        left: NodeId,
571        right: NodeId,
572    },
573}
574
575/// A parsed source: its nodes, the comments beside them, and the
576/// warnings the parse had.
577#[derive(Clone, Debug)]
578pub struct Ast {
579    /// Each node with its span, in one vector: making a node is one
580    /// push, and reading both is one cache line.
581    pub(crate) nodes: Vec<(Node, Span)>,
582    pub(crate) lists: Vec<NodeId>,
583    pub(crate) comments: Vec<Comment>,
584    pub(crate) root: Option<NodeId>,
585    pub(crate) warnings: Vec<Diagnostic>,
586}
587
588impl Ast {
589    pub(crate) fn new(capacity: usize) -> Ast {
590        let mut nodes = Vec::with_capacity(capacity + 1);
591        // Index 0 is never a node, so an `Option<NodeId>` is 4 bytes.
592        nodes.push((Node::Empty, Span::default()));
593        Ast {
594            nodes,
595            lists: Vec::with_capacity(capacity / 2),
596            comments: Vec::new(),
597            root: None,
598            warnings: Vec::new(),
599        }
600    }
601
602    pub(crate) fn push(&mut self, span: Span, node: Node) -> NodeId {
603        let id = NodeId::new(self.nodes.len());
604        self.nodes.push((node, span));
605        id
606    }
607
608    pub(crate) fn list(&mut self, ids: impl IntoIterator<Item = NodeId>) -> List {
609        let start = self.lists.len() as u32;
610        self.lists.extend(ids);
611        List {
612            start,
613            len: self.lists.len() as u32 - start,
614        }
615    }
616
617    /// The [`Node::Program`].
618    pub fn root(&self) -> NodeId {
619        self.root.expect("a parsed tree has a program")
620    }
621
622    pub fn node(&self, id: NodeId) -> &Node {
623        &self.nodes[id.index()].0
624    }
625
626    pub(crate) fn node_mut(&mut self, id: NodeId) -> &mut Node {
627        &mut self.nodes[id.index()].0
628    }
629
630    pub fn span(&self, id: NodeId) -> Span {
631        self.nodes[id.index()].1
632    }
633
634    pub(crate) fn set_span(&mut self, id: NodeId, span: Span) {
635        self.nodes[id.index()].1 = span;
636    }
637
638    /// The nodes in `list`.
639    pub fn get(&self, list: List) -> &[NodeId] {
640        &self.lists[list.start as usize..(list.start + list.len) as usize]
641    }
642
643    /// How many nodes there are.
644    pub fn len(&self) -> usize {
645        self.nodes.len() - 1
646    }
647
648    pub fn is_empty(&self) -> bool {
649        self.len() == 0
650    }
651
652    /// Every node, in the order they were made: children before their
653    /// parents, and the program last.
654    pub fn ids(&self) -> impl Iterator<Item = NodeId> + '_ {
655        (1..self.nodes.len()).map(NodeId::new)
656    }
657
658    /// The comments, in source order.
659    pub fn comments(&self) -> &[Comment] {
660        &self.comments
661    }
662
663    /// What the parse noticed that isn't an error, like a legacy octal
664    /// literal in sloppy code.
665    pub fn warnings(&self) -> &[Diagnostic] {
666        &self.warnings
667    }
668
669    /// The node inside any parentheses around `id`.
670    pub fn unparenthesized(&self, mut id: NodeId) -> NodeId {
671        while let Node::Paren { expression } = *self.node(id) {
672            id = expression;
673        }
674        id
675    }
676}
677
678/// A place in a node that refers to other nodes.
679pub(crate) enum Ref<'a> {
680    Node(&'a mut NodeId),
681    List(&'a mut List),
682}
683
684/// Calls `f` on each child id and child list `node` holds.
685pub(crate) fn refs(node: &mut Node, f: &mut dyn FnMut(Ref<'_>)) {
686    fn n(f: &mut dyn FnMut(Ref<'_>), id: &mut NodeId) {
687        f(Ref::Node(id));
688    }
689    fn o(f: &mut dyn FnMut(Ref<'_>), id: &mut Option<NodeId>) {
690        if let Some(id) = id {
691            f(Ref::Node(id));
692        }
693    }
694    fn l(f: &mut dyn FnMut(Ref<'_>), list: &mut List) {
695        f(Ref::List(list));
696    }
697    match node {
698        Node::Empty
699        | Node::Debugger
700        | Node::Identifier
701        | Node::PrivateIdentifier
702        | Node::Literal(_)
703        | Node::This
704        | Node::Super
705        | Node::Elision
706        | Node::TemplateElement { .. } => {}
707        Node::Program { body, .. }
708        | Node::Block { body }
709        | Node::ClassBody { body }
710        | Node::StaticBlock { body } => l(f, body),
711        Node::VariableDeclaration { declarations, .. } => l(f, declarations),
712        Node::Array { elements, .. } | Node::ArrayPattern { elements } => l(f, elements),
713        Node::Object { properties, .. } | Node::ObjectPattern { properties } => l(f, properties),
714        Node::Sequence { expressions } => l(f, expressions),
715        Node::Template {
716            quasis,
717            expressions,
718        } => {
719            l(f, quasis);
720            l(f, expressions);
721        }
722        Node::Switch {
723            discriminant,
724            cases,
725        } => {
726            n(f, discriminant);
727            l(f, cases);
728        }
729        Node::SwitchCase { test, consequent } => {
730            o(f, test);
731            l(f, consequent);
732        }
733        Node::Call {
734            callee, arguments, ..
735        }
736        | Node::New { callee, arguments } => {
737            n(f, callee);
738            l(f, arguments);
739        }
740        Node::Function(func) => {
741            o(f, &mut func.id);
742            l(f, &mut func.params);
743            n(f, &mut func.body);
744        }
745        Node::Class(c) => {
746            o(f, &mut c.id);
747            o(f, &mut c.super_class);
748            n(f, &mut c.body);
749        }
750        Node::ImportDeclaration {
751            specifiers,
752            source,
753            attributes,
754        } => {
755            l(f, specifiers);
756            n(f, source);
757            l(f, attributes);
758        }
759        Node::ExportNamed {
760            declaration,
761            specifiers,
762            source,
763            attributes,
764        } => {
765            o(f, declaration);
766            l(f, specifiers);
767            o(f, source);
768            l(f, attributes);
769        }
770        Node::ExportAll {
771            exported,
772            source,
773            attributes,
774        } => {
775            o(f, exported);
776            n(f, source);
777            l(f, attributes);
778        }
779        Node::Expression { expression, .. }
780        | Node::Chain { expression }
781        | Node::Paren { expression } => n(f, expression),
782        Node::Throw { argument }
783        | Node::Unary { argument, .. }
784        | Node::Update { argument, .. }
785        | Node::Await { argument }
786        | Node::Spread { argument }
787        | Node::Rest { argument } => n(f, argument),
788        Node::Return { argument } | Node::Yield { argument, .. } => o(f, argument),
789        Node::Break { label } | Node::Continue { label } => o(f, label),
790        Node::ImportDefaultSpecifier { local } | Node::ImportNamespaceSpecifier { local } => {
791            n(f, local)
792        }
793        Node::ExportDefault { declaration } => n(f, declaration),
794        Node::With { object: a, body: b }
795        | Node::Labeled { label: a, body: b }
796        | Node::While { test: a, body: b }
797        | Node::DoWhile { body: a, test: b }
798        | Node::Method {
799            key: a, value: b, ..
800        }
801        | Node::Property {
802            key: a, value: b, ..
803        }
804        | Node::TaggedTemplate { tag: a, quasi: b }
805        | Node::Binary {
806            left: a, right: b, ..
807        }
808        | Node::Logical {
809            left: a, right: b, ..
810        }
811        | Node::Assign {
812            left: a, right: b, ..
813        }
814        | Node::Member {
815            object: a,
816            property: b,
817            ..
818        }
819        | Node::MetaProperty {
820            meta: a,
821            property: b,
822        }
823        | Node::ImportSpecifier {
824            imported: a,
825            local: b,
826        }
827        | Node::ImportAttribute { key: a, value: b }
828        | Node::ExportSpecifier {
829            local: a,
830            exported: b,
831        }
832        | Node::AssignmentPattern { left: a, right: b } => {
833            n(f, a);
834            n(f, b);
835        }
836        Node::VariableDeclarator { id, init } => {
837            n(f, id);
838            o(f, init);
839        }
840        Node::Field { key, value, .. } => {
841            n(f, key);
842            o(f, value);
843        }
844        Node::Import { source, options } => {
845            n(f, source);
846            o(f, options);
847        }
848        Node::CatchClause { param, body } => {
849            o(f, param);
850            n(f, body);
851        }
852        Node::If {
853            test,
854            consequent,
855            alternate,
856        } => {
857            n(f, test);
858            n(f, consequent);
859            o(f, alternate);
860        }
861        Node::Try {
862            block,
863            handler,
864            finalizer,
865        } => {
866            n(f, block);
867            o(f, handler);
868            o(f, finalizer);
869        }
870        Node::Conditional {
871            test,
872            consequent,
873            alternate,
874        } => {
875            n(f, test);
876            n(f, consequent);
877            n(f, alternate);
878        }
879        Node::For {
880            init,
881            test,
882            update,
883            body,
884        } => {
885            o(f, init);
886            o(f, test);
887            o(f, update);
888            n(f, body);
889        }
890        Node::ForIn { left, right, body }
891        | Node::ForOf {
892            left, right, body, ..
893        } => {
894            n(f, left);
895            n(f, right);
896            n(f, body);
897        }
898    }
899}