pub mod array;
pub mod await_expr;
pub mod block;
pub mod break_node;
pub mod call;
pub mod conditional;
pub mod declaration;
pub mod field;
pub mod identifier;
pub mod iteration;
pub mod new;
pub mod object;
pub mod operator;
pub mod return_smt;
pub mod spread;
pub mod statement_list;
pub mod switch;
pub mod template;
pub mod throw;
pub mod try_node;
pub use self::{
array::ArrayDecl,
await_expr::AwaitExpr,
block::Block,
break_node::Break,
call::Call,
conditional::{ConditionalOp, If},
declaration::{
ArrowFunctionDecl, AsyncFunctionDecl, AsyncFunctionExpr, Declaration, DeclarationList,
FunctionDecl, FunctionExpr,
},
field::{GetConstField, GetField},
identifier::Identifier,
iteration::{Continue, DoWhileLoop, ForInLoop, ForLoop, ForOfLoop, WhileLoop},
new::New,
object::Object,
operator::{Assign, BinOp, UnaryOp},
return_smt::Return,
spread::Spread,
statement_list::{RcStatementList, StatementList},
switch::{Case, Switch},
template::{TaggedTemplate, TemplateLit},
throw::Throw,
try_node::{Catch, Finally, Try},
};
use super::Const;
use crate::{
exec::Executable,
gc::{empty_trace, Finalize, Trace},
BoaProfiler, Context, JsResult, JsValue,
};
use std::{
cmp::Ordering,
fmt::{self, Display},
};
#[cfg(feature = "deser")]
use serde::{Deserialize, Serialize};
#[cfg_attr(feature = "deser", derive(Serialize, Deserialize))]
#[derive(Clone, Debug, Trace, Finalize, PartialEq)]
pub enum Node {
ArrayDecl(ArrayDecl),
ArrowFunctionDecl(ArrowFunctionDecl),
Assign(Assign),
AsyncFunctionDecl(AsyncFunctionDecl),
AsyncFunctionExpr(AsyncFunctionExpr),
AwaitExpr(AwaitExpr),
BinOp(BinOp),
Block(Block),
Break(Break),
Call(Call),
ConditionalOp(ConditionalOp),
Const(Const),
ConstDeclList(DeclarationList),
Continue(Continue),
DoWhileLoop(DoWhileLoop),
FunctionDecl(FunctionDecl),
FunctionExpr(FunctionExpr),
GetConstField(GetConstField),
GetField(GetField),
ForLoop(ForLoop),
ForInLoop(ForInLoop),
ForOfLoop(ForOfLoop),
If(If),
LetDeclList(DeclarationList),
Identifier(Identifier),
New(New),
Object(Object),
Return(Return),
Switch(Switch),
Spread(Spread),
TaggedTemplate(TaggedTemplate),
TemplateLit(TemplateLit),
Throw(Throw),
Try(Try),
This,
UnaryOp(UnaryOp),
VarDeclList(DeclarationList),
WhileLoop(WhileLoop),
Empty,
}
impl Display for Node {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.display(f, 0)
}
}
impl From<Const> for Node {
fn from(c: Const) -> Self {
Self::Const(c)
}
}
impl Node {
pub(crate) fn hoistable_order(a: &Node, b: &Node) -> Ordering {
match (a, b) {
(Node::FunctionDecl(_), Node::FunctionDecl(_)) => Ordering::Equal,
(_, Node::FunctionDecl(_)) => Ordering::Greater,
(Node::FunctionDecl(_), _) => Ordering::Less,
(_, _) => Ordering::Equal,
}
}
pub fn this() -> Self {
Self::This
}
fn display(&self, f: &mut fmt::Formatter<'_>, indentation: usize) -> fmt::Result {
let indent = " ".repeat(indentation);
match *self {
Self::Block(_) => {}
_ => write!(f, "{}", indent)?,
}
self.display_no_indent(f, indentation)
}
fn display_no_indent(&self, f: &mut fmt::Formatter<'_>, indentation: usize) -> fmt::Result {
match *self {
Self::Call(ref expr) => Display::fmt(expr, f),
Self::Const(ref c) => write!(f, "{}", c),
Self::ConditionalOp(ref cond_op) => Display::fmt(cond_op, f),
Self::ForLoop(ref for_loop) => for_loop.display(f, indentation),
Self::ForOfLoop(ref for_of) => for_of.display(f, indentation),
Self::ForInLoop(ref for_in) => for_in.display(f, indentation),
Self::This => write!(f, "this"),
Self::Try(ref try_catch) => try_catch.display(f, indentation),
Self::Break(ref break_smt) => Display::fmt(break_smt, f),
Self::Continue(ref cont) => Display::fmt(cont, f),
Self::Spread(ref spread) => Display::fmt(spread, f),
Self::Block(ref block) => block.display(f, indentation),
Self::Identifier(ref s) => Display::fmt(s, f),
Self::New(ref expr) => Display::fmt(expr, f),
Self::GetConstField(ref get_const_field) => Display::fmt(get_const_field, f),
Self::GetField(ref get_field) => Display::fmt(get_field, f),
Self::WhileLoop(ref while_loop) => while_loop.display(f, indentation),
Self::DoWhileLoop(ref do_while) => do_while.display(f, indentation),
Self::If(ref if_smt) => if_smt.display(f, indentation),
Self::Switch(ref switch) => switch.display(f, indentation),
Self::Object(ref obj) => obj.display(f, indentation),
Self::ArrayDecl(ref arr) => Display::fmt(arr, f),
Self::VarDeclList(ref list) => Display::fmt(list, f),
Self::FunctionDecl(ref decl) => decl.display(f, indentation),
Self::FunctionExpr(ref expr) => expr.display(f, indentation),
Self::ArrowFunctionDecl(ref decl) => decl.display(f, indentation),
Self::BinOp(ref op) => Display::fmt(op, f),
Self::UnaryOp(ref op) => Display::fmt(op, f),
Self::Return(ref ret) => Display::fmt(ret, f),
Self::TaggedTemplate(ref template) => Display::fmt(template, f),
Self::TemplateLit(ref template) => Display::fmt(template, f),
Self::Throw(ref throw) => Display::fmt(throw, f),
Self::Assign(ref op) => Display::fmt(op, f),
Self::LetDeclList(ref decl) => Display::fmt(decl, f),
Self::ConstDeclList(ref decl) => Display::fmt(decl, f),
Self::AsyncFunctionDecl(ref decl) => decl.display(f, indentation),
Self::AsyncFunctionExpr(ref expr) => expr.display(f, indentation),
Self::AwaitExpr(ref expr) => Display::fmt(expr, f),
Self::Empty => write!(f, ";"),
}
}
}
impl Executable for Node {
fn run(&self, context: &mut Context) -> JsResult<JsValue> {
let _timer = BoaProfiler::global().start_event("Executable", "exec");
match *self {
Node::AsyncFunctionDecl(ref decl) => decl.run(context),
Node::AsyncFunctionExpr(ref function_expr) => function_expr.run(context),
Node::AwaitExpr(ref expr) => expr.run(context),
Node::Call(ref call) => call.run(context),
Node::Const(Const::Null) => Ok(JsValue::null()),
Node::Const(Const::Num(num)) => Ok(JsValue::new(num)),
Node::Const(Const::Int(num)) => Ok(JsValue::new(num)),
Node::Const(Const::BigInt(ref num)) => Ok(JsValue::new(num.clone())),
Node::Const(Const::Undefined) => Ok(JsValue::undefined()),
Node::Const(Const::String(ref value)) => Ok(JsValue::new(value.to_string())),
Node::Const(Const::Bool(value)) => Ok(JsValue::new(value)),
Node::Block(ref block) => block.run(context),
Node::Identifier(ref identifier) => identifier.run(context),
Node::GetConstField(ref get_const_field_node) => get_const_field_node.run(context),
Node::GetField(ref get_field) => get_field.run(context),
Node::WhileLoop(ref while_loop) => while_loop.run(context),
Node::DoWhileLoop(ref do_while) => do_while.run(context),
Node::ForLoop(ref for_loop) => for_loop.run(context),
Node::ForOfLoop(ref for_of_loop) => for_of_loop.run(context),
Node::ForInLoop(ref for_in_loop) => for_in_loop.run(context),
Node::If(ref if_smt) => if_smt.run(context),
Node::ConditionalOp(ref op) => op.run(context),
Node::Switch(ref switch) => switch.run(context),
Node::Object(ref obj) => obj.run(context),
Node::ArrayDecl(ref arr) => arr.run(context),
Node::FunctionDecl(ref decl) => decl.run(context),
Node::FunctionExpr(ref function_expr) => function_expr.run(context),
Node::ArrowFunctionDecl(ref decl) => decl.run(context),
Node::BinOp(ref op) => op.run(context),
Node::UnaryOp(ref op) => op.run(context),
Node::New(ref call) => call.run(context),
Node::Return(ref ret) => ret.run(context),
Node::TaggedTemplate(ref template) => template.run(context),
Node::TemplateLit(ref template) => template.run(context),
Node::Throw(ref throw) => throw.run(context),
Node::Assign(ref op) => op.run(context),
Node::VarDeclList(ref decl) => decl.run(context),
Node::LetDeclList(ref decl) => decl.run(context),
Node::ConstDeclList(ref decl) => decl.run(context),
Node::Spread(ref spread) => spread.run(context),
Node::This => {
context.get_this_binding()
}
Node::Try(ref try_node) => try_node.run(context),
Node::Break(ref break_node) => break_node.run(context),
Node::Continue(ref continue_node) => continue_node.run(context),
Node::Empty => Ok(JsValue::undefined()),
}
}
}
fn join_nodes<N>(f: &mut fmt::Formatter<'_>, nodes: &[N]) -> fmt::Result
where
N: Display,
{
let mut first = true;
for e in nodes {
if !first {
f.write_str(", ")?;
}
first = false;
Display::fmt(e, f)?;
}
Ok(())
}
#[cfg_attr(feature = "deser", derive(Serialize, Deserialize))]
#[derive(Clone, Debug, PartialEq, Trace, Finalize)]
pub struct FormalParameter {
name: Box<str>,
init: Option<Node>,
is_rest_param: bool,
}
impl FormalParameter {
pub(in crate::syntax) fn new<N>(name: N, init: Option<Node>, is_rest_param: bool) -> Self
where
N: Into<Box<str>>,
{
Self {
name: name.into(),
init,
is_rest_param,
}
}
pub fn name(&self) -> &str {
&self.name
}
pub fn init(&self) -> Option<&Node> {
self.init.as_ref()
}
pub fn is_rest_param(&self) -> bool {
self.is_rest_param
}
}
impl Display for FormalParameter {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.is_rest_param {
write!(f, "...")?;
}
write!(f, "{}", self.name)?;
if let Some(n) = self.init.as_ref() {
write!(f, " = {}", n)?;
}
Ok(())
}
}
#[cfg_attr(feature = "deser", derive(Serialize, Deserialize))]
#[derive(Clone, Debug, PartialEq, Trace, Finalize)]
pub enum PropertyDefinition {
IdentifierReference(Box<str>),
Property(PropertyName, Node),
MethodDefinition(MethodDefinitionKind, PropertyName, FunctionExpr),
SpreadObject(Node),
}
impl PropertyDefinition {
pub fn identifier_reference<I>(ident: I) -> Self
where
I: Into<Box<str>>,
{
Self::IdentifierReference(ident.into())
}
pub fn property<N, V>(name: N, value: V) -> Self
where
N: Into<PropertyName>,
V: Into<Node>,
{
Self::Property(name.into(), value.into())
}
pub fn method_definition<N>(kind: MethodDefinitionKind, name: N, body: FunctionExpr) -> Self
where
N: Into<PropertyName>,
{
Self::MethodDefinition(kind, name.into(), body)
}
pub fn spread_object<O>(obj: O) -> Self
where
O: Into<Node>,
{
Self::SpreadObject(obj.into())
}
}
#[cfg_attr(feature = "deser", derive(Serialize, Deserialize))]
#[derive(Clone, Debug, PartialEq, Copy, Finalize)]
pub enum MethodDefinitionKind {
Get,
Set,
Ordinary,
}
unsafe impl Trace for MethodDefinitionKind {
empty_trace!();
}
#[cfg_attr(feature = "deser", derive(Serialize, Deserialize))]
#[derive(Clone, Debug, PartialEq, Finalize)]
pub enum PropertyName {
Literal(Box<str>),
Computed(Node),
}
impl Display for PropertyName {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
PropertyName::Literal(key) => write!(f, "{}", key),
PropertyName::Computed(key) => write!(f, "{}", key),
}
}
}
impl<T> From<T> for PropertyName
where
T: Into<Box<str>>,
{
fn from(name: T) -> Self {
Self::Literal(name.into())
}
}
impl From<Node> for PropertyName {
fn from(name: Node) -> Self {
Self::Computed(name)
}
}
unsafe impl Trace for PropertyName {
empty_trace!();
}
#[cfg(test)]
fn test_formatting(source: &'static str) {
let source = &source[1..];
let first_line = &source[..source.find('\n').unwrap()];
let trimmed_first_line = first_line.trim();
let characters_to_remove = first_line.len() - trimmed_first_line.len();
let scenario = source
.lines()
.map(|l| &l[characters_to_remove..]) .collect::<Vec<&'static str>>()
.join("\n");
let result = format!("{}", crate::parse(&scenario, false).unwrap());
if scenario != result {
eprint!("========= Expected:\n{}", scenario);
eprint!("========= Got:\n{}", result);
eprintln!("========= Expected: {:?}", scenario);
eprintln!("========= Got: {:?}", result);
panic!("parsing test did not give the correct result (see above)");
}
}