Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixed all tests #286

Merged
merged 5 commits into from
Mar 30, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 34 additions & 10 deletions boa/src/exec/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ use crate::{
realm::Realm,
syntax::ast::{
constant::Const,
node::Node,
node::{MethodDefinitionKind, Node, PropertyDefinition},
op::{AssignOp, BinOp, BitOp, CompOp, LogOp, NumOp, UnaryOp},
},
};
Expand Down Expand Up @@ -141,7 +141,7 @@ impl Executor for Interpreter {
};
let mut v_args = Vec::with_capacity(args.len());
for arg in args.iter() {
if let Node::UnaryOp(UnaryOp::Spread, ref x) = arg.deref() {
if let Node::Spread(ref x) = arg.deref() {
let val = self.run(x)?;
let mut vals = self.extract_array_properties(&val).unwrap();
v_args.append(&mut vals);
Expand Down Expand Up @@ -205,23 +205,39 @@ impl Executor for Interpreter {
}
Ok(result)
}
Node::ObjectDecl(ref map) => {
Node::Object(ref properties) => {
let global_val = &self
.realm
.environment
.get_global_object()
.expect("Could not get the global object");
let obj = ValueData::new_obj(Some(global_val));
for (key, val) in map.iter() {
obj.borrow().set_field_slice(&key.clone(), self.run(val)?);

// TODO: Implement the rest of the property types.
for property in properties {
match property {
PropertyDefinition::Property(key, value) => {
obj.borrow().set_field_slice(&key.clone(), self.run(value)?);
}
PropertyDefinition::MethodDefinition(kind, name, func) => {
if let MethodDefinitionKind::Ordinary = kind {
obj.borrow().set_field_slice(&name.clone(), self.run(func)?);
} else {
// TODO: Implement other types of MethodDefinitionKinds.
unimplemented!("other types of property method definitions.");
}
}
i => unimplemented!("{:?} type of property", i),
}
}

Ok(obj)
}
Node::ArrayDecl(ref arr) => {
let array = array::new_array(self)?;
let mut elements: Vec<Value> = vec![];
for elem in arr.iter() {
if let Node::UnaryOp(UnaryOp::Spread, ref x) = elem.deref() {
if let Node::Spread(ref x) = elem.deref() {
let val = self.run(x)?;
let mut vals = self.extract_array_properties(&val).unwrap();
elements.append(&mut vals);
Expand Down Expand Up @@ -286,7 +302,6 @@ impl Executor for Interpreter {
!(num_v_a as i32)
})
}
UnaryOp::Spread => Gc::new(v_a), // for now we can do nothing but return the value as-is
_ => unreachable!(),
})
}
Expand Down Expand Up @@ -356,7 +371,12 @@ impl Executor for Interpreter {
}
_ => Ok(Gc::new(ValueData::Undefined)),
},
Node::Construct(ref callee, ref args) => {
Node::New(ref call) => {
let (callee, args) = match call.as_ref() {
Node::Call(callee, args) => (callee, args),
_ => unreachable!("Node::New(ref call): 'call' must only be Node::Call type."),
};

let func_object = self.run(callee)?;
let mut v_args = Vec::with_capacity(args.len());
for arg in args.iter() {
Expand Down Expand Up @@ -538,7 +558,11 @@ impl Executor for Interpreter {

Ok(obj)
}
_ => unimplemented!(),
Node::Spread(ref node) => {
// TODO: for now we can do nothing but return the value as-is
Ok(Gc::new((*self.run(node)?).clone()))
}
ref i => unimplemented!("{}", i),
}
}
}
Expand Down Expand Up @@ -591,7 +615,7 @@ impl Interpreter {
.environment
.initialize_binding(name, expr.clone());
}
Node::UnaryOp(UnaryOp::Spread, ref expr) => {
Node::Spread(ref expr) => {
Razican marked this conversation as resolved.
Show resolved Hide resolved
if let Node::Local(ref name) = expr.deref() {
let array = array::new_array(self)?;
array::add_to_array_object(&array, &arguments_list[i..])?;
Expand Down
49 changes: 29 additions & 20 deletions boa/src/syntax/ast/node.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use crate::syntax::ast::{
op::{BinOp, Operator, UnaryOp},
};
use gc_derive::{Finalize, Trace};
use std::{collections::btree_map::BTreeMap, fmt};
use std::fmt;

#[cfg(feature = "serde-ast")]
use serde::{Deserialize, Serialize};
Expand Down Expand Up @@ -32,8 +32,6 @@ pub enum Node {
Const(Const),
/// Const declaration.
ConstDecl(Vec<(String, Node)>),
/// Construct an object from the function and arguments.
Construct(Box<Node>, Vec<Node>),
/// Continue with an optional label.
Continue(Option<String>),
/// Create a function with the given name, arguments, and internal AST node.
Expand All @@ -57,15 +55,13 @@ pub enum Node {
Local(String),
/// New
New(Box<Node>),
/// Create an object out of the binary tree given
ObjectDecl(Box<BTreeMap<String, Node>>),
/// Object Declaration (replaces ObjectDecl)
/// Object Declaration
Object(Vec<PropertyDefinition>),
/// Return the expression from a function
Return(Option<Box<Node>>),
/// Run blocks whose cases match the expression
Switch(Box<Node>, Vec<(Node, Vec<Node>)>, Option<Box<Node>>),
/// Spread operator
/// `...a` - spread an iterable value
Spread(Box<Node>),
// Similar to Block but without the braces
StatementList(Vec<Node>),
Expand Down Expand Up @@ -99,18 +95,14 @@ pub enum Node {
impl Operator for Node {
fn get_assoc(&self) -> bool {
match *self {
Node::Construct(_, _)
| Node::UnaryOp(_, _)
| Node::TypeOf(_)
| Node::If(_, _, _)
| Node::Assign(_, _) => false,
Node::UnaryOp(_, _) | Node::TypeOf(_) | Node::If(_, _, _) | Node::Assign(_, _) => false,
_ => true,
}
}
fn get_precedence(&self) -> u64 {
match self {
Node::GetField(_, _) | Node::GetConstField(_, _) => 1,
Node::Call(_, _) | Node::Construct(_, _) => 2,
Node::Call(_, _) => 2,
Node::UnaryOp(UnaryOp::IncrementPost, _)
| Node::UnaryOp(UnaryOp::IncrementPre, _)
| Node::UnaryOp(UnaryOp::DecrementPost, _)
Expand Down Expand Up @@ -148,12 +140,10 @@ impl Node {
Self::ConditionalOp(_, _, _) => write!(f, "Conditional op"), // TODO
Self::ForLoop(_, _, _, _) => write!(f, "for loop"), // TODO
Self::This => write!(f, "this"), // TODO
Self::Object(_) => write!(f, "object"), // TODO
Self::Spread(_) => write!(f, "spread"), // TODO
Self::New(_) => write!(f, "new"), // TODO
Self::Try(_, _, _, _) => write!(f, "try/catch/finally"), // TODO
Self::Break(_) => write!(f, "break"), // TODO: add potential value
Self::Continue(_) => write!(f, "continue"), // TODO: add potential value
Self::Spread(ref node) => write!(f, "...{}", node),
Self::Block(ref block) => {
writeln!(f, "{{")?;
for node in block.iter() {
Expand Down Expand Up @@ -197,7 +187,12 @@ impl Node {
let arg_strs: Vec<String> = args.iter().map(ToString::to_string).collect();
write!(f, "{})", arg_strs.join(", "))
}
Self::Construct(ref func, ref args) => {
Self::New(ref call) => {
let (func, args) = match call.as_ref() {
Node::Call(func, args) => (func, args),
_ => unreachable!("Node::New(ref call): 'call' must only be Node::Call type."),
};

write!(f, "new {}", func)?;
f.write_str("(")?;
let mut first = true;
Expand Down Expand Up @@ -242,10 +237,24 @@ impl Node {
def.display(f, indentation + 1)?;
write!(f, "{}}}", indent)
}
Self::ObjectDecl(ref map) => {
Self::Object(ref properties) => {
f.write_str("{\n")?;
for (key, value) in map.iter() {
write!(f, "{} {}: {},", indent, key, value)?;
for property in properties {
match property {
PropertyDefinition::IdentifierReference(key) => {
write!(f, "{} {},", indent, key)?;
}
PropertyDefinition::Property(key, value) => {
write!(f, "{} {}: {},", indent, key, value)?;
}
PropertyDefinition::SpreadObject(key) => {
write!(f, "{} ...{},", indent, key)?;
}
PropertyDefinition::MethodDefinition(_kind, _key, _node) => {
// TODO: Implement display for PropertyDefinition::MethodDefinition.
unimplemented!("Display for PropertyDefinition::MethodDefinition");
}
}
}
f.write_str("}")
}
Expand Down
3 changes: 0 additions & 3 deletions boa/src/syntax/ast/op.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,6 @@ pub enum UnaryOp {
Tilde,
/// `typeof` - Get the type of object
TypeOf,
/// `...a` - spread an iterable value
Spread,
/// The JavaScript `delete` operator removes a property from an object.
///
/// Unlike what common belief suggests, the delete operator has nothing to do with
Expand Down Expand Up @@ -117,7 +115,6 @@ impl Display for UnaryOp {
UnaryOp::Minus => "-",
UnaryOp::Not => "!",
UnaryOp::Tilde => "~",
UnaryOp::Spread => "...",
UnaryOp::Delete => "delete",
UnaryOp::TypeOf => "typeof",
UnaryOp::Void => "void",
Expand Down
26 changes: 17 additions & 9 deletions boa/src/syntax/parser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1386,8 +1386,14 @@ impl Parser {
return Err(ParseError::AbruptEnd);
}
}

args.push(self.read_assignment_expression()?);
if self
.next_if(TokenKind::Punctuator(Punctuator::Spread))
.is_some()
{
args.push(Node::Spread(Box::new(self.read_assignment_expression()?)));
} else {
args.push(self.read_assignment_expression()?);
}
}

Ok(args)
Expand Down Expand Up @@ -1415,13 +1421,15 @@ impl Parser {
TokenKind::Identifier(ident) => Ok(Node::Local(ident)),
TokenKind::StringLiteral(s) => Ok(Node::Const(Const::String(s))),
TokenKind::NumericLiteral(num) => Ok(Node::Const(Const::Num(num))),
TokenKind::RegularExpressionLiteral(body, flags) => Ok(Node::Construct(
Box::new(Node::Local("RegExp".to_string())),
vec![
Node::Const(Const::String(body)),
Node::Const(Const::String(flags)),
],
)),
TokenKind::RegularExpressionLiteral(body, flags) => {
Ok(Node::New(Box::new(Node::Call(
Box::new(Node::Local("RegExp".to_string())),
vec![
Node::Const(Const::String(body)),
Node::Const(Const::String(flags)),
],
))))
}
_ => Err(ParseError::Unexpected(tok, None)),
}
}
Expand Down