use crate::token::{Position, Punct, Span};
use std::fmt;
#[derive(Debug, Clone, PartialEq)]
pub struct Program {
pub kind: ProgramKind,
pub body: Vec<Stmt>,
pub span: Span,
pub strict: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ProgramKind {
Script,
Module,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Ident {
pub name: String,
pub span: Span,
}
impl Ident {
pub fn new(name: impl Into<String>) -> Ident {
Ident {
name: name.into(),
span: Span::default(),
}
}
}
impl fmt::Display for Ident {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.name)
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Stmt {
pub kind: StmtKind,
pub span: Span,
}
impl Stmt {
pub fn new(kind: StmtKind, span: Span) -> Stmt {
Stmt { kind, span }
}
pub fn is_empty(&self) -> bool {
matches!(self.kind, StmtKind::Empty)
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum StmtKind {
Empty,
Block(Vec<Stmt>),
Expr(Box<Expr>),
If {
test: Box<Expr>,
cons: Box<Stmt>,
alt: Option<Box<Stmt>>,
},
DoWhile {
body: Box<Stmt>,
test: Box<Expr>,
},
While {
test: Box<Expr>,
body: Box<Stmt>,
},
For {
init: Option<ForInit>,
test: Option<Box<Expr>>,
update: Option<Box<Expr>>,
body: Box<Stmt>,
},
ForIn {
left: ForHead,
right: Box<Expr>,
body: Box<Stmt>,
},
ForOf {
is_await: bool,
left: ForHead,
right: Box<Expr>,
body: Box<Stmt>,
},
Continue(Option<Ident>),
Break(Option<Ident>),
Return(Option<Box<Expr>>),
With {
object: Box<Expr>,
body: Box<Stmt>,
},
Labeled {
label: Ident,
body: Box<Stmt>,
},
Switch {
discriminant: Box<Expr>,
cases: Vec<SwitchCase>,
},
Throw(Box<Expr>),
Try {
block: Vec<Stmt>,
handler: Option<CatchClause>,
finalizer: Option<Vec<Stmt>>,
},
Debugger,
VarDecl(VarDecl),
FuncDecl(Box<Function>),
ClassDecl(Box<Class>),
Import(Box<ImportDecl>),
Export(Box<ExportDecl>),
}
#[derive(Debug, Clone, PartialEq)]
pub struct SwitchCase {
pub test: Option<Box<Expr>>,
pub body: Vec<Stmt>,
pub span: Span,
}
#[derive(Debug, Clone, PartialEq)]
pub struct CatchClause {
pub param: Option<Pattern>,
pub body: Vec<Stmt>,
pub span: Span,
}
#[derive(Debug, Clone, PartialEq)]
pub enum ForInit {
VarDecl(VarDecl),
Expr(Box<Expr>),
}
#[derive(Debug, Clone, PartialEq)]
pub enum ForHead {
VarDecl(VarDecl),
Assign(Box<Pattern>),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VarDeclKind {
Var,
Let,
Const,
}
impl VarDeclKind {
pub fn as_str(self) -> &'static str {
match self {
VarDeclKind::Var => "var",
VarDeclKind::Let => "let",
VarDeclKind::Const => "const",
}
}
pub fn is_lexical(self) -> bool {
!matches!(self, VarDeclKind::Var)
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct VarDecl {
pub kind: VarDeclKind,
pub declarators: Vec<Declarator>,
pub span: Span,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Declarator {
pub target: Pattern,
pub init: Option<Box<Expr>>,
pub span: Span,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Function {
pub name: Option<Ident>,
pub params: Vec<Pattern>,
pub body: FunctionBody,
pub is_async: bool,
pub is_generator: bool,
pub is_arrow: bool,
pub span: Span,
pub params_span: Span,
}
#[derive(Debug, Clone, PartialEq)]
pub enum FunctionBody {
Block(Vec<Stmt>),
Expr(Box<Expr>),
}
impl FunctionBody {
pub fn statements(&self) -> Option<&[Stmt]> {
match self {
FunctionBody::Block(body) => Some(body),
FunctionBody::Expr(_) => None,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Class {
pub name: Option<Ident>,
pub super_class: Option<Box<Expr>>,
pub elements: Vec<ClassElement>,
pub span: Span,
}
#[derive(Debug, Clone, PartialEq)]
pub enum ClassElement {
Method {
key: PropName,
is_static: bool,
kind: MethodKind,
func: Box<Function>,
span: Span,
},
Field {
key: PropName,
is_static: bool,
value: Option<Box<Expr>>,
span: Span,
},
StaticBlock {
body: Vec<Stmt>,
span: Span,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MethodKind {
Constructor,
Method,
Get,
Set,
}
#[derive(Debug, Clone, PartialEq)]
pub enum PropName {
Literal(PropKey),
Computed(Box<Expr>),
Private(Ident),
}
impl PropName {
pub fn static_name(&self) -> Option<PropKeyRef<'_>> {
match self {
PropName::Literal(k) => Some(k.as_ref()),
PropName::Private(id) => Some(PropKeyRef::Private(&id.name)),
PropName::Computed(_) => None,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum PropKey {
Str(String),
Num(f64),
}
impl PropKey {
pub fn as_ref(&self) -> PropKeyRef<'_> {
match self {
PropKey::Str(s) => PropKeyRef::Str(s),
PropKey::Num(n) => PropKeyRef::Num(*n),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum PropKeyRef<'a> {
Str(&'a str),
Num(f64),
Private(&'a str),
}
#[derive(Debug, Clone, PartialEq)]
pub struct Pattern {
pub kind: PatternKind,
pub span: Span,
}
impl Pattern {
pub fn new(kind: PatternKind, span: Span) -> Pattern {
Pattern { kind, span }
}
pub fn bound_names(&self, out: &mut Vec<Ident>) {
match &self.kind {
PatternKind::Ident(id) => out.push(id.clone()),
PatternKind::Array { elements, rest, .. }
| PatternKind::Object {
properties: elements,
rest,
..
} => {
for element in elements.iter().flatten() {
match element {
PatternElement::Pattern(p) => p.bound_names(out),
PatternElement::Property { value, .. } => value.bound_names(out),
}
}
if let Some(rest) = rest {
match &**rest {
RestElement::Pattern(p) => p.bound_names(out),
RestElement::Member(m) => m.bound_names(out),
}
}
}
PatternKind::Assign { target, .. } => target.bound_names(out),
PatternKind::Rest(target) => target.bound_names(out),
PatternKind::Invalid(_) => {}
PatternKind::Member(m) => m.bound_names(out),
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum PatternKind {
Ident(Ident),
Array {
elements: Vec<Option<PatternElement>>,
rest: Option<Box<RestElement>>,
},
Object {
properties: Vec<Option<PatternElement>>,
rest: Option<Box<RestElement>>,
},
Assign {
target: Box<Pattern>,
default: Box<Expr>,
},
Member(Box<MemberPattern>),
Rest(Box<Pattern>),
Invalid(Box<Expr>),
}
#[derive(Debug, Clone, PartialEq)]
pub enum PatternElement {
Pattern(Pattern),
Property {
key: PropName,
value: Pattern,
shorthand: bool,
span: Span,
},
}
#[derive(Debug, Clone, PartialEq)]
pub enum RestElement {
Pattern(Pattern),
Member(Box<MemberPattern>),
}
#[derive(Debug, Clone, PartialEq)]
pub struct MemberPattern {
pub object: Box<Expr>,
pub property: MemberProp,
pub span: Span,
pub op_pos: Option<Position>,
}
impl MemberPattern {
pub fn bound_names(&self, _out: &mut Vec<Ident>) {}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Expr {
pub kind: ExprKind,
pub span: Span,
pub op_pos: Option<Position>,
}
impl Expr {
pub fn new(kind: ExprKind, span: Span) -> Expr {
Expr {
kind,
span,
op_pos: None,
}
}
pub fn at_operator(kind: ExprKind, span: Span, pos: Position) -> Expr {
Expr {
kind,
span,
op_pos: Some(pos),
}
}
pub fn unparen(&self) -> &Expr {
let mut expr = self;
while let ExprKind::Paren(inner) = &expr.kind {
expr = inner;
}
expr
}
pub fn is_anonymous_function_definition(&self) -> bool {
match &self.kind {
ExprKind::Function(f) => f.name.is_none() && !f.is_arrow,
ExprKind::Arrow(_) => false,
ExprKind::Class(c) => c.name.is_none(),
_ => false,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum ExprKind {
Ident(Ident),
Null,
Bool(bool),
Number(f64),
BigInt {
digits: String,
radix: u32,
},
String(String),
RegExp {
pattern: String,
flags: String,
},
This,
Array {
elements: Vec<Option<ArrayElement>>,
},
Object(Vec<ObjectProperty>),
Function(Box<Function>),
Arrow(Box<Function>),
Class(Box<Class>),
Template(Box<TemplateLiteral>),
TaggedTemplate {
tag: Box<Expr>,
quasi: Box<TemplateLiteral>,
},
Member {
object: Box<Expr>,
property: MemberProp,
optional: bool,
},
Call {
callee: Box<Expr>,
arguments: Vec<Expr>,
optional: bool,
},
New {
callee: Box<Expr>,
arguments: Option<Vec<Expr>>,
},
NewTarget,
ImportMeta,
ImportCall(Box<Expr>),
SuperCall(Vec<Expr>),
SuperProp,
Unary {
op: UnaryOp,
argument: Box<Expr>,
},
Update {
op: UpdateOp,
argument: Box<Expr>,
prefix: bool,
},
Binary {
op: BinaryOp,
left: Box<Expr>,
right: Box<Expr>,
},
Logical {
op: LogicalOp,
left: Box<Expr>,
right: Box<Expr>,
},
Conditional {
test: Box<Expr>,
cons: Box<Expr>,
alt: Box<Expr>,
},
Assign {
op: AssignOp,
target: Box<Pattern>,
value: Box<Expr>,
},
Paren(Box<Expr>),
Sequence(Vec<Expr>),
Yield {
argument: Option<Box<Expr>>,
delegate: bool,
},
Await(Box<Expr>),
Spread(Box<Expr>),
OptionalChain(Box<Expr>),
PrivateIn {
name: Ident,
object: Box<Expr>,
},
}
#[derive(Debug, Clone, PartialEq)]
pub enum ArrayElement {
Expr(Box<Expr>),
Spread(Box<Expr>),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PropertyKind {
Value,
Method,
Get,
Set,
}
#[derive(Debug, Clone, PartialEq)]
pub enum ObjectProperty {
Property {
key: PropName,
value: Box<Expr>,
kind: PropertyKind,
shorthand: bool,
span: Span,
},
Spread(Box<Expr>),
}
#[derive(Debug, Clone, PartialEq)]
pub struct TemplateLiteral {
pub quasis: Vec<TemplateChunk>,
pub expressions: Vec<Expr>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TemplateChunk {
pub cooked: Option<String>,
pub raw: String,
pub tail: bool,
}
#[derive(Debug, Clone, PartialEq)]
pub enum MemberProp {
Ident(Ident),
Computed(Box<Expr>),
Private(Ident),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UnaryOp {
Minus,
Plus,
Not,
BitNot,
Typeof,
Void,
Delete,
}
impl UnaryOp {
pub fn as_str(self) -> &'static str {
match self {
UnaryOp::Minus => "-",
UnaryOp::Plus => "+",
UnaryOp::Not => "!",
UnaryOp::BitNot => "~",
UnaryOp::Typeof => "typeof",
UnaryOp::Void => "void",
UnaryOp::Delete => "delete",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UpdateOp {
Increment,
Decrement,
}
impl UpdateOp {
pub fn as_str(self) -> &'static str {
match self {
UpdateOp::Increment => "++",
UpdateOp::Decrement => "--",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BinaryOp {
Eq,
NotEq,
StrictEq,
StrictNotEq,
Lt,
LtEq,
Gt,
GtEq,
Shl,
Shr,
UShr,
Add,
Sub,
Mul,
Div,
Mod,
Pow,
BitOr,
BitXor,
BitAnd,
In,
Instanceof,
}
impl BinaryOp {
pub fn as_str(self) -> &'static str {
match self {
BinaryOp::Eq => "==",
BinaryOp::NotEq => "!=",
BinaryOp::StrictEq => "===",
BinaryOp::StrictNotEq => "!==",
BinaryOp::Lt => "<",
BinaryOp::LtEq => "<=",
BinaryOp::Gt => ">",
BinaryOp::GtEq => ">=",
BinaryOp::Shl => "<<",
BinaryOp::Shr => ">>",
BinaryOp::UShr => ">>>",
BinaryOp::Add => "+",
BinaryOp::Sub => "-",
BinaryOp::Mul => "*",
BinaryOp::Div => "/",
BinaryOp::Mod => "%",
BinaryOp::Pow => "**",
BinaryOp::BitOr => "|",
BinaryOp::BitXor => "^",
BinaryOp::BitAnd => "&",
BinaryOp::In => "in",
BinaryOp::Instanceof => "instanceof",
}
}
pub fn is_relational(self) -> bool {
matches!(
self,
BinaryOp::Lt
| BinaryOp::LtEq
| BinaryOp::Gt
| BinaryOp::GtEq
| BinaryOp::In
| BinaryOp::Instanceof
)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LogicalOp {
And,
Or,
Coalesce,
}
impl LogicalOp {
pub fn as_str(self) -> &'static str {
match self {
LogicalOp::And => "&&",
LogicalOp::Or => "||",
LogicalOp::Coalesce => "??",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AssignOp {
Assign,
Add,
Sub,
Mul,
Div,
Mod,
Pow,
Shl,
Shr,
UShr,
BitOr,
BitXor,
BitAnd,
And,
Or,
Coalesce,
}
impl AssignOp {
pub fn as_str(self) -> &'static str {
match self {
AssignOp::Assign => "=",
AssignOp::Add => "+=",
AssignOp::Sub => "-=",
AssignOp::Mul => "*=",
AssignOp::Div => "/=",
AssignOp::Mod => "%=",
AssignOp::Pow => "**=",
AssignOp::Shl => "<<=",
AssignOp::Shr => ">>=",
AssignOp::UShr => ">>>=",
AssignOp::BitOr => "|=",
AssignOp::BitXor => "^=",
AssignOp::BitAnd => "&=",
AssignOp::And => "&&=",
AssignOp::Or => "||=",
AssignOp::Coalesce => "??=",
}
}
pub fn is_simple(self) -> bool {
matches!(self, AssignOp::Assign)
}
pub fn binary_op(self) -> Option<BinaryOp> {
Some(match self {
AssignOp::Assign => return None,
AssignOp::Add => BinaryOp::Add,
AssignOp::Sub => BinaryOp::Sub,
AssignOp::Mul => BinaryOp::Mul,
AssignOp::Div => BinaryOp::Div,
AssignOp::Mod => BinaryOp::Mod,
AssignOp::Pow => BinaryOp::Pow,
AssignOp::Shl => BinaryOp::Shl,
AssignOp::Shr => BinaryOp::Shr,
AssignOp::UShr => BinaryOp::UShr,
AssignOp::BitOr => BinaryOp::BitOr,
AssignOp::BitXor => BinaryOp::BitXor,
AssignOp::BitAnd => BinaryOp::BitAnd,
AssignOp::And | AssignOp::Or | AssignOp::Coalesce => return None,
})
}
pub fn logical_op(self) -> Option<LogicalOp> {
match self {
AssignOp::And => Some(LogicalOp::And),
AssignOp::Or => Some(LogicalOp::Or),
AssignOp::Coalesce => Some(LogicalOp::Coalesce),
_ => None,
}
}
pub fn from_punct(p: Punct) -> Option<AssignOp> {
Some(match p {
Punct::Eq => AssignOp::Assign,
Punct::PlusEq => AssignOp::Add,
Punct::MinusEq => AssignOp::Sub,
Punct::StarEq => AssignOp::Mul,
Punct::SlashEq => AssignOp::Div,
Punct::PercentEq => AssignOp::Mod,
Punct::StarStarEq => AssignOp::Pow,
Punct::ShlEq => AssignOp::Shl,
Punct::ShrEq => AssignOp::Shr,
Punct::UShrEq => AssignOp::UShr,
Punct::PipeEq => AssignOp::BitOr,
Punct::CaretEq => AssignOp::BitXor,
Punct::AmpEq => AssignOp::BitAnd,
Punct::AmpAmpEq => AssignOp::And,
Punct::PipePipeEq => AssignOp::Or,
Punct::QuestionQuestionEq => AssignOp::Coalesce,
_ => return None,
})
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ModuleName {
Ident(Ident),
Str(String),
}
impl ModuleName {
pub fn as_str(&self) -> &str {
match self {
ModuleName::Ident(id) => &id.name,
ModuleName::Str(s) => s,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct ImportDecl {
pub specifiers: Vec<ImportSpecifier>,
pub source: String,
pub attributes: Vec<ImportAttribute>,
pub span: Span,
}
#[derive(Debug, Clone, PartialEq)]
pub enum ImportSpecifier {
Default(Ident),
Namespace(Ident),
Named {
imported: ModuleName,
local: Ident,
},
}
#[derive(Debug, Clone, PartialEq)]
pub struct ImportAttribute {
pub key: String,
pub value: String,
pub span: Span,
}
#[derive(Debug, Clone, PartialEq)]
pub struct ExportDecl {
pub kind: ExportKind,
pub span: Span,
}
#[derive(Debug, Clone, PartialEq)]
pub enum ExportKind {
Declaration(Box<Stmt>),
Default(Box<Expr>),
Named {
specifiers: Vec<ExportSpecifier>,
source: Option<String>,
attributes: Vec<ImportAttribute>,
},
All {
source: String,
exported: Option<ModuleName>,
attributes: Vec<ImportAttribute>,
},
}
#[derive(Debug, Clone, PartialEq)]
pub struct ExportSpecifier {
pub local: ModuleName,
pub exported: ModuleName,
pub span: Span,
}