use std::num::NonZeroU32;
use parsec_base::{Diagnostic, Span};
use crate::SourceType;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct NodeId(NonZeroU32);
impl NodeId {
pub(crate) fn new(index: usize) -> NodeId {
NodeId(NonZeroU32::new(index as u32).expect("node 0 is never handed out"))
}
pub const fn index(self) -> usize {
self.0.get() as usize
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct List {
pub(crate) start: u32,
pub(crate) len: u32,
}
impl List {
pub const fn len(self) -> usize {
self.len as usize
}
pub const fn is_empty(self) -> bool {
self.len == 0
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Comment {
pub kind: CommentKind,
pub span: Span,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum CommentKind {
Line,
Block,
Hashbang,
HtmlOpen,
HtmlClose,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum VarKind {
Var,
Let,
Const,
}
impl VarKind {
pub const fn as_str(self) -> &'static str {
match self {
VarKind::Var => "var",
VarKind::Let => "let",
VarKind::Const => "const",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum LiteralKind {
String,
Number,
BigInt,
Boolean,
Null,
RegExp,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum FunctionKind {
Declaration,
Expression,
Arrow,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Function {
pub kind: FunctionKind,
pub id: Option<NodeId>,
pub params: List,
pub body: NodeId,
pub is_async: bool,
pub generator: bool,
pub expression: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Class {
pub declaration: bool,
pub id: Option<NodeId>,
pub super_class: Option<NodeId>,
pub body: NodeId,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum PropertyKind {
Init,
Get,
Set,
}
impl PropertyKind {
pub const fn as_str(self) -> &'static str {
match self {
PropertyKind::Init => "init",
PropertyKind::Get => "get",
PropertyKind::Set => "set",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum MethodKind {
Constructor,
Method,
Get,
Set,
}
impl MethodKind {
pub const fn as_str(self) -> &'static str {
match self {
MethodKind::Constructor => "constructor",
MethodKind::Method => "method",
MethodKind::Get => "get",
MethodKind::Set => "set",
}
}
}
macro_rules! ops {
($(#[$m:meta])* $name:ident { $($variant:ident = $text:literal,)* }) => {
$(#[$m])*
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum $name {
$($variant,)*
}
impl $name {
pub const fn as_str(self) -> &'static str {
match self {
$($name::$variant => $text,)*
}
}
}
};
}
ops! {
UnaryOp {
Minus = "-",
Plus = "+",
Not = "!",
BitNot = "~",
Typeof = "typeof",
Void = "void",
Delete = "delete",
}
}
ops! {
UpdateOp {
Increment = "++",
Decrement = "--",
}
}
ops! {
BinaryOp {
Eq = "==",
NotEq = "!=",
StrictEq = "===",
StrictNotEq = "!==",
Lt = "<",
LtEq = "<=",
Gt = ">",
GtEq = ">=",
Shl = "<<",
Shr = ">>",
UShr = ">>>",
Add = "+",
Sub = "-",
Mul = "*",
Div = "/",
Rem = "%",
Exp = "**",
BitOr = "|",
BitXor = "^",
BitAnd = "&",
In = "in",
Instanceof = "instanceof",
}
}
ops! {
LogicalOp {
Or = "||",
And = "&&",
Coalesce = "??",
}
}
ops! {
AssignOp {
Assign = "=",
Add = "+=",
Sub = "-=",
Mul = "*=",
Div = "/=",
Rem = "%=",
Exp = "**=",
Shl = "<<=",
Shr = ">>=",
UShr = ">>>=",
BitOr = "|=",
BitXor = "^=",
BitAnd = "&=",
Or = "||=",
And = "&&=",
Coalesce = "??=",
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Node {
Program {
body: List,
source_type: SourceType,
},
Expression {
expression: NodeId,
directive: bool,
},
Block {
body: List,
},
Empty,
Debugger,
With {
object: NodeId,
body: NodeId,
},
Return {
argument: Option<NodeId>,
},
Labeled {
label: NodeId,
body: NodeId,
},
Break {
label: Option<NodeId>,
},
Continue {
label: Option<NodeId>,
},
If {
test: NodeId,
consequent: NodeId,
alternate: Option<NodeId>,
},
Switch {
discriminant: NodeId,
cases: List,
},
SwitchCase {
test: Option<NodeId>,
consequent: List,
},
Throw {
argument: NodeId,
},
Try {
block: NodeId,
handler: Option<NodeId>,
finalizer: Option<NodeId>,
},
CatchClause {
param: Option<NodeId>,
body: NodeId,
},
While {
test: NodeId,
body: NodeId,
},
DoWhile {
body: NodeId,
test: NodeId,
},
For {
init: Option<NodeId>,
test: Option<NodeId>,
update: Option<NodeId>,
body: NodeId,
},
ForIn {
left: NodeId,
right: NodeId,
body: NodeId,
},
ForOf {
left: NodeId,
right: NodeId,
body: NodeId,
is_await: bool,
},
VariableDeclaration {
kind: VarKind,
declarations: List,
},
VariableDeclarator {
id: NodeId,
init: Option<NodeId>,
},
Function(Function),
Class(Class),
ClassBody {
body: List,
},
Method {
key: NodeId,
value: NodeId,
kind: MethodKind,
computed: bool,
is_static: bool,
},
Field {
key: NodeId,
value: Option<NodeId>,
computed: bool,
is_static: bool,
},
StaticBlock {
body: List,
},
Identifier,
PrivateIdentifier,
Literal(LiteralKind),
This,
Super,
Array {
elements: List,
comma_after_spread: bool,
},
Elision,
Object {
properties: List,
comma_after_spread: bool,
},
Property {
key: NodeId,
value: NodeId,
kind: PropertyKind,
method: bool,
shorthand: bool,
computed: bool,
},
Template {
quasis: List,
expressions: List,
},
TemplateElement {
tail: bool,
cooked: bool,
},
TaggedTemplate {
tag: NodeId,
quasi: NodeId,
},
Unary {
operator: UnaryOp,
argument: NodeId,
},
Update {
operator: UpdateOp,
prefix: bool,
argument: NodeId,
},
Binary {
operator: BinaryOp,
left: NodeId,
right: NodeId,
},
Logical {
operator: LogicalOp,
left: NodeId,
right: NodeId,
},
Assign {
operator: AssignOp,
left: NodeId,
right: NodeId,
},
Conditional {
test: NodeId,
consequent: NodeId,
alternate: NodeId,
},
Call {
callee: NodeId,
arguments: List,
optional: bool,
},
New {
callee: NodeId,
arguments: List,
},
Member {
object: NodeId,
property: NodeId,
computed: bool,
optional: bool,
},
Chain {
expression: NodeId,
},
Sequence {
expressions: List,
},
Yield {
argument: Option<NodeId>,
delegate: bool,
},
Await {
argument: NodeId,
},
Spread {
argument: NodeId,
},
MetaProperty {
meta: NodeId,
property: NodeId,
},
Import {
source: NodeId,
options: Option<NodeId>,
},
Paren {
expression: NodeId,
},
ImportDeclaration {
specifiers: List,
source: NodeId,
attributes: List,
},
ImportSpecifier {
imported: NodeId,
local: NodeId,
},
ImportDefaultSpecifier {
local: NodeId,
},
ImportNamespaceSpecifier {
local: NodeId,
},
ImportAttribute {
key: NodeId,
value: NodeId,
},
ExportNamed {
declaration: Option<NodeId>,
specifiers: List,
source: Option<NodeId>,
attributes: List,
},
ExportSpecifier {
local: NodeId,
exported: NodeId,
},
ExportDefault {
declaration: NodeId,
},
ExportAll {
exported: Option<NodeId>,
source: NodeId,
attributes: List,
},
ObjectPattern {
properties: List,
},
ArrayPattern {
elements: List,
},
Rest {
argument: NodeId,
},
AssignmentPattern {
left: NodeId,
right: NodeId,
},
}
#[derive(Clone, Debug)]
pub struct Ast {
pub(crate) nodes: Vec<(Node, Span)>,
pub(crate) lists: Vec<NodeId>,
pub(crate) comments: Vec<Comment>,
pub(crate) root: Option<NodeId>,
pub(crate) warnings: Vec<Diagnostic>,
}
impl Ast {
pub(crate) fn new(capacity: usize) -> Ast {
let mut nodes = Vec::with_capacity(capacity + 1);
nodes.push((Node::Empty, Span::default()));
Ast {
nodes,
lists: Vec::with_capacity(capacity / 2),
comments: Vec::new(),
root: None,
warnings: Vec::new(),
}
}
pub(crate) fn push(&mut self, span: Span, node: Node) -> NodeId {
let id = NodeId::new(self.nodes.len());
self.nodes.push((node, span));
id
}
pub(crate) fn list(&mut self, ids: impl IntoIterator<Item = NodeId>) -> List {
let start = self.lists.len() as u32;
self.lists.extend(ids);
List {
start,
len: self.lists.len() as u32 - start,
}
}
pub fn root(&self) -> NodeId {
self.root.expect("a parsed tree has a program")
}
pub fn node(&self, id: NodeId) -> &Node {
&self.nodes[id.index()].0
}
pub(crate) fn node_mut(&mut self, id: NodeId) -> &mut Node {
&mut self.nodes[id.index()].0
}
pub fn span(&self, id: NodeId) -> Span {
self.nodes[id.index()].1
}
pub(crate) fn set_span(&mut self, id: NodeId, span: Span) {
self.nodes[id.index()].1 = span;
}
pub fn get(&self, list: List) -> &[NodeId] {
&self.lists[list.start as usize..(list.start + list.len) as usize]
}
pub fn len(&self) -> usize {
self.nodes.len() - 1
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn ids(&self) -> impl Iterator<Item = NodeId> + '_ {
(1..self.nodes.len()).map(NodeId::new)
}
pub fn comments(&self) -> &[Comment] {
&self.comments
}
pub fn warnings(&self) -> &[Diagnostic] {
&self.warnings
}
pub fn unparenthesized(&self, mut id: NodeId) -> NodeId {
while let Node::Paren { expression } = *self.node(id) {
id = expression;
}
id
}
}
pub(crate) enum Ref<'a> {
Node(&'a mut NodeId),
List(&'a mut List),
}
pub(crate) fn refs(node: &mut Node, f: &mut dyn FnMut(Ref<'_>)) {
fn n(f: &mut dyn FnMut(Ref<'_>), id: &mut NodeId) {
f(Ref::Node(id));
}
fn o(f: &mut dyn FnMut(Ref<'_>), id: &mut Option<NodeId>) {
if let Some(id) = id {
f(Ref::Node(id));
}
}
fn l(f: &mut dyn FnMut(Ref<'_>), list: &mut List) {
f(Ref::List(list));
}
match node {
Node::Empty
| Node::Debugger
| Node::Identifier
| Node::PrivateIdentifier
| Node::Literal(_)
| Node::This
| Node::Super
| Node::Elision
| Node::TemplateElement { .. } => {}
Node::Program { body, .. }
| Node::Block { body }
| Node::ClassBody { body }
| Node::StaticBlock { body } => l(f, body),
Node::VariableDeclaration { declarations, .. } => l(f, declarations),
Node::Array { elements, .. } | Node::ArrayPattern { elements } => l(f, elements),
Node::Object { properties, .. } | Node::ObjectPattern { properties } => l(f, properties),
Node::Sequence { expressions } => l(f, expressions),
Node::Template {
quasis,
expressions,
} => {
l(f, quasis);
l(f, expressions);
}
Node::Switch {
discriminant,
cases,
} => {
n(f, discriminant);
l(f, cases);
}
Node::SwitchCase { test, consequent } => {
o(f, test);
l(f, consequent);
}
Node::Call {
callee, arguments, ..
}
| Node::New { callee, arguments } => {
n(f, callee);
l(f, arguments);
}
Node::Function(func) => {
o(f, &mut func.id);
l(f, &mut func.params);
n(f, &mut func.body);
}
Node::Class(c) => {
o(f, &mut c.id);
o(f, &mut c.super_class);
n(f, &mut c.body);
}
Node::ImportDeclaration {
specifiers,
source,
attributes,
} => {
l(f, specifiers);
n(f, source);
l(f, attributes);
}
Node::ExportNamed {
declaration,
specifiers,
source,
attributes,
} => {
o(f, declaration);
l(f, specifiers);
o(f, source);
l(f, attributes);
}
Node::ExportAll {
exported,
source,
attributes,
} => {
o(f, exported);
n(f, source);
l(f, attributes);
}
Node::Expression { expression, .. }
| Node::Chain { expression }
| Node::Paren { expression } => n(f, expression),
Node::Throw { argument }
| Node::Unary { argument, .. }
| Node::Update { argument, .. }
| Node::Await { argument }
| Node::Spread { argument }
| Node::Rest { argument } => n(f, argument),
Node::Return { argument } | Node::Yield { argument, .. } => o(f, argument),
Node::Break { label } | Node::Continue { label } => o(f, label),
Node::ImportDefaultSpecifier { local } | Node::ImportNamespaceSpecifier { local } => {
n(f, local)
}
Node::ExportDefault { declaration } => n(f, declaration),
Node::With { object: a, body: b }
| Node::Labeled { label: a, body: b }
| Node::While { test: a, body: b }
| Node::DoWhile { body: a, test: b }
| Node::Method {
key: a, value: b, ..
}
| Node::Property {
key: a, value: b, ..
}
| Node::TaggedTemplate { tag: a, quasi: b }
| Node::Binary {
left: a, right: b, ..
}
| Node::Logical {
left: a, right: b, ..
}
| Node::Assign {
left: a, right: b, ..
}
| Node::Member {
object: a,
property: b,
..
}
| Node::MetaProperty {
meta: a,
property: b,
}
| Node::ImportSpecifier {
imported: a,
local: b,
}
| Node::ImportAttribute { key: a, value: b }
| Node::ExportSpecifier {
local: a,
exported: b,
}
| Node::AssignmentPattern { left: a, right: b } => {
n(f, a);
n(f, b);
}
Node::VariableDeclarator { id, init } => {
n(f, id);
o(f, init);
}
Node::Field { key, value, .. } => {
n(f, key);
o(f, value);
}
Node::Import { source, options } => {
n(f, source);
o(f, options);
}
Node::CatchClause { param, body } => {
o(f, param);
n(f, body);
}
Node::If {
test,
consequent,
alternate,
} => {
n(f, test);
n(f, consequent);
o(f, alternate);
}
Node::Try {
block,
handler,
finalizer,
} => {
n(f, block);
o(f, handler);
o(f, finalizer);
}
Node::Conditional {
test,
consequent,
alternate,
} => {
n(f, test);
n(f, consequent);
n(f, alternate);
}
Node::For {
init,
test,
update,
body,
} => {
o(f, init);
o(f, test);
o(f, update);
n(f, body);
}
Node::ForIn { left, right, body }
| Node::ForOf {
left, right, body, ..
} => {
n(f, left);
n(f, right);
n(f, body);
}
}
}