1use std::num::NonZeroU32;
18
19use parsec_base::{Diagnostic, Span};
20
21use crate::SourceType;
22
23#[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#[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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
56pub struct Comment {
57 pub kind: CommentKind,
58 pub span: Span,
60}
61
62#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
63pub enum CommentKind {
64 Line,
66 Block,
68 Hashbang,
70 HtmlOpen,
72 HtmlClose,
74}
75
76#[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#[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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
107pub enum FunctionKind {
108 Declaration,
109 Expression,
110 Arrow,
111}
112
113#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
116pub struct Function {
117 pub kind: FunctionKind,
118 pub id: Option<NodeId>,
119 pub params: List,
120 pub body: NodeId,
122 pub is_async: bool,
123 pub generator: bool,
124 pub expression: bool,
126}
127
128#[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 pub body: NodeId,
136}
137
138#[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#[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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
272pub enum Node {
273 Program {
275 body: List,
276 source_type: SourceType,
277 },
278
279 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 Method {
373 key: NodeId,
374 value: NodeId,
375 kind: MethodKind,
376 computed: bool,
377 is_static: bool,
378 },
379 Field {
381 key: NodeId,
382 value: Option<NodeId>,
383 computed: bool,
384 is_static: bool,
385 },
386 StaticBlock {
387 body: List,
388 },
389
390 Identifier,
392 PrivateIdentifier,
394 Literal(LiteralKind),
395 This,
396 Super,
397 Array {
399 elements: List,
400 comma_after_spread: bool,
401 },
402 Elision,
404 Object {
405 properties: List,
406 comma_after_spread: bool,
407 },
408 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 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 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 MetaProperty {
495 meta: NodeId,
496 property: NodeId,
497 },
498 Import {
500 source: NodeId,
501 options: Option<NodeId>,
502 },
503 Paren {
506 expression: NodeId,
507 },
508
509 ImportDeclaration {
513 specifiers: List,
514 source: NodeId,
515 attributes: List,
516 },
517 ImportSpecifier {
520 imported: NodeId,
521 local: NodeId,
522 },
523 ImportDefaultSpecifier {
524 local: NodeId,
525 },
526 ImportNamespaceSpecifier {
528 local: NodeId,
529 },
530 ImportAttribute {
532 key: NodeId,
533 value: NodeId,
534 },
535 ExportNamed {
537 declaration: Option<NodeId>,
538 specifiers: List,
539 source: Option<NodeId>,
540 attributes: List,
541 },
542 ExportSpecifier {
545 local: NodeId,
546 exported: NodeId,
547 },
548 ExportDefault {
550 declaration: NodeId,
551 },
552 ExportAll {
554 exported: Option<NodeId>,
555 source: NodeId,
556 attributes: List,
557 },
558
559 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#[derive(Clone, Debug)]
578pub struct Ast {
579 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 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 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 pub fn get(&self, list: List) -> &[NodeId] {
640 &self.lists[list.start as usize..(list.start + list.len) as usize]
641 }
642
643 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 pub fn ids(&self) -> impl Iterator<Item = NodeId> + '_ {
655 (1..self.nodes.len()).map(NodeId::new)
656 }
657
658 pub fn comments(&self) -> &[Comment] {
660 &self.comments
661 }
662
663 pub fn warnings(&self) -> &[Diagnostic] {
666 &self.warnings
667 }
668
669 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
678pub(crate) enum Ref<'a> {
680 Node(&'a mut NodeId),
681 List(&'a mut List),
682}
683
684pub(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}