Browse Source

cargo fmt

pull/158/head
Jason Williams 5 years ago
parent
commit
090126ea13
  1. 12
      src/lib/environment/declarative_environment_record.rs
  2. 12
      src/lib/environment/function_environment_record.rs
  3. 35
      src/lib/environment/lexical_environment.rs
  4. 31
      src/lib/exec.rs
  5. 36
      src/lib/js/array.rs
  6. 4
      src/lib/js/console.rs
  7. 5
      src/lib/js/function.rs
  8. 6
      src/lib/js/math.rs
  9. 10
      src/lib/js/regexp.rs
  10. 41
      src/lib/js/string.rs
  11. 30
      src/lib/js/value.rs
  12. 14
      src/lib/syntax/lexer.rs
  13. 8
      src/lib/syntax/parser.rs

12
src/lib/environment/declarative_environment_record.rs

@ -122,9 +122,11 @@ impl EnvironmentRecordTrait for DeclarativeEnvironmentRecord {
fn get_binding_value(&self, name: &str, _strict: bool) -> Value {
match self.env_rec.get(name) {
Some(binding) => {
binding.value.as_ref().expect("Could not get record as reference").clone()
},
Some(binding) => binding
.value
.as_ref()
.expect("Could not get record as reference")
.clone(),
None => {
// TODO: change this when error handling comes into play
panic!("ReferenceError: Cannot get binding value for {}", name);
@ -141,10 +143,8 @@ impl EnvironmentRecordTrait for DeclarativeEnvironmentRecord {
} else {
false
}
},
None => {
false
}
None => false,
}
}

12
src/lib/environment/function_environment_record.rs

@ -180,9 +180,11 @@ impl EnvironmentRecordTrait for FunctionEnvironmentRecord {
fn get_binding_value(&self, name: &str, _strict: bool) -> Value {
match self.env_rec.get(name) {
Some(binding) => {
binding.value.as_ref().expect("Could not get record as reference").clone()
},
Some(binding) => binding
.value
.as_ref()
.expect("Could not get record as reference")
.clone(),
None => {
// TODO: change this when error handling comes into play
panic!("ReferenceError: Cannot get binding value for {}", name);
@ -199,10 +201,8 @@ impl EnvironmentRecordTrait for FunctionEnvironmentRecord {
} else {
false
}
},
None => {
false
}
None => false,
}
}

35
src/lib/environment/lexical_environment.rs

@ -91,8 +91,11 @@ impl LexicalEnvironment {
}
pub fn get_global_object(&self) -> Option<Value> {
self.environment_stack.get(0).expect("").borrow().get_global_object()
self.environment_stack
.get(0)
.expect("")
.borrow()
.get_global_object()
}
pub fn create_mutable_binding(&mut self, name: String, deletion: bool) {
@ -121,13 +124,18 @@ impl LexicalEnvironment {
/// (you only need to add a new variable binding, or you want to fetch a value)
pub fn get_current_environment_ref(&self) -> &Environment {
let index = self.environment_stack.len().wrapping_sub(1);
&self.environment_stack.get(index).expect("Could not get current environment")
&self
.environment_stack
.get(index)
.expect("Could not get current environment")
}
/// When neededing to clone an environment (linking it with another environnment)
/// cloning is more suited. The GC will remove the env once nothing is linking to it anymore
pub fn get_current_environment(&mut self) -> &mut Environment {
self.environment_stack.back_mut().expect("Could not get mutable reference to back object")
self.environment_stack
.back_mut()
.expect("Could not get mutable reference to back object")
}
pub fn get_binding_value(&mut self, name: &str) -> Value {
@ -142,10 +150,21 @@ impl LexicalEnvironment {
if borrowed_env.get_outer_environment().is_some() {
let mut outer: Option<Environment> = borrowed_env.get_outer_environment();
while outer.is_some() {
if outer.as_ref().expect("Could not get outer as reference").borrow().has_binding(&name) {
return outer.expect("Outer was None").borrow().get_binding_value(name, false);
}
outer = outer.expect("Outer was None").borrow().get_outer_environment();
if outer
.as_ref()
.expect("Could not get outer as reference")
.borrow()
.has_binding(&name)
{
return outer
.expect("Outer was None")
.borrow()
.get_binding_value(name, false);
}
outer = outer
.expect("Outer was None")
.borrow()
.get_outer_environment();
}
}

31
src/lib/exec.rs

@ -164,12 +164,20 @@ impl Executor for Interpreter {
}
}
if !matched && default.is_some() {
result = self.run(default.as_ref().expect("Could not get default as reference"))?;
result = self.run(
default
.as_ref()
.expect("Could not get default as reference"),
)?;
}
Ok(result)
}
ExprDef::ObjectDecl(ref map) => {
let global_val = &self.realm.environment.get_global_object().expect("Could not get the global object");
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(key.clone(), self.run(val)?);
@ -177,7 +185,11 @@ impl Executor for Interpreter {
Ok(obj)
}
ExprDef::ArrayDecl(ref arr) => {
let global_val = &self.realm.environment.get_global_object().expect("Could not get the global object");
let global_val = &self
.realm
.environment
.get_global_object()
.expect("Could not get the global object");
let arr_map = ValueData::new_obj(Some(global_val));
// Note that this object is an Array
arr_map.set_kind(ObjectKind::Array);
@ -206,9 +218,10 @@ impl Executor for Interpreter {
self.realm
.environment
.create_mutable_binding(name.clone().expect("No name was supplied"), false);
self.realm
.environment
.initialize_binding(name.as_ref().expect("Could not get name as reference"), val.clone())
self.realm.environment.initialize_binding(
name.as_ref().expect("Could not get name as reference"),
val.clone(),
)
}
Ok(val)
}
@ -277,8 +290,10 @@ impl Executor for Interpreter {
}))
}
ExprDef::BinOp(BinOp::Log(ref op), ref a, ref b) => {
let v_a = from_value::<bool>(self.run(a)?).expect("Could not convert JS value to bool");
let v_b = from_value::<bool>(self.run(b)?).expect("Could not convert JS value to bool");
let v_a =
from_value::<bool>(self.run(a)?).expect("Could not convert JS value to bool");
let v_b =
from_value::<bool>(self.run(b)?).expect("Could not convert JS value to bool");
Ok(match *op {
LogOp::And => to_value(v_a && v_b),
LogOp::Or => to_value(v_a || v_b),

36
src/lib/js/array.rs

@ -39,7 +39,10 @@ fn add_to_array_object(array_ptr: &Value, add_values: &[Value]) -> ResultValue {
array_ptr.set_field(new_index.to_string(), value.clone());
}
array_ptr.set_field_slice("length", to_value(orig_length.wrapping_add(add_values.len() as i32)));
array_ptr.set_field_slice(
"length",
to_value(orig_length.wrapping_add(add_values.len() as i32)),
);
Ok(array_ptr.clone())
}
@ -56,7 +59,8 @@ pub fn make_array(this: &Value, args: &[Value], _: &mut Interpreter) -> ResultVa
0 => construct_array(this, &[]),
1 => {
let array = construct_array(this, &[]).expect("Could not construct array");
let size: i32 = from_value(args.get(0).expect("Could not get argument").clone()).expect("Could not convert argument to i32");
let size: i32 = from_value(args.get(0).expect("Could not get argument").clone())
.expect("Could not convert argument to i32");
array.set_field_slice("length", to_value(size));
Ok(array)
}
@ -87,13 +91,15 @@ pub fn concat(this: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue
// one)
let mut new_values: Vec<Value> = Vec::new();
let this_length: i32 = from_value(this.get_field_slice("length")).expect("Could not convert argument to i32");
let this_length: i32 =
from_value(this.get_field_slice("length")).expect("Could not convert argument to i32");
for n in 0..this_length {
new_values.push(this.get_field(&n.to_string()));
}
for concat_array in args {
let concat_length: i32 = from_value(concat_array.get_field_slice("length")).expect("Could not convert argument to i32");
let concat_length: i32 = from_value(concat_array.get_field_slice("length"))
.expect("Could not convert argument to i32");
for n in 0..concat_length {
new_values.push(concat_array.get_field(&n.to_string()));
}
@ -118,7 +124,8 @@ pub fn push(this: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue {
/// The last element of the array is removed from the array and returned.
/// <https://tc39.es/ecma262/#sec-array.prototype.pop>
pub fn pop(this: &Value, _: &[Value], _: &mut Interpreter) -> ResultValue {
let curr_length: i32 = from_value(this.get_field_slice("length")).expect("Could not convert argument to i32");
let curr_length: i32 =
from_value(this.get_field_slice("length")).expect("Could not convert argument to i32");
if curr_length < 1 {
return Err(to_value(
"Cannot pop() on an array with zero length".to_string(),
@ -145,7 +152,8 @@ pub fn join(this: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue {
};
let mut elem_strs: Vec<String> = Vec::new();
let length: i32 = from_value(this.get_field_slice("length")).expect("Could not convert argument to i32");
let length: i32 =
from_value(this.get_field_slice("length")).expect("Could not convert argument to i32");
for n in 0..length {
let elem_str: String = this.get_field(&n.to_string()).to_string();
elem_strs.push(elem_str);
@ -161,7 +169,8 @@ pub fn join(this: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue {
/// <https://tc39.es/ecma262/#sec-array.prototype.reverse/>
#[allow(clippy::else_if_without_else)]
pub fn reverse(this: &Value, _: &[Value], _: &mut Interpreter) -> ResultValue {
let len: i32 = from_value(this.get_field_slice("length")).expect("Could not convert argument to i32");
let len: i32 =
from_value(this.get_field_slice("length")).expect("Could not convert argument to i32");
let middle: i32 = len.wrapping_div(2);
for lower in 0..middle {
@ -193,7 +202,8 @@ pub fn reverse(this: &Value, _: &[Value], _: &mut Interpreter) -> ResultValue {
/// The first element of the array is removed from the array and returned.
/// <https://tc39.es/ecma262/#sec-array.prototype.shift/>
pub fn shift(this: &Value, _: &[Value], _: &mut Interpreter) -> ResultValue {
let len: i32 = from_value(this.get_field_slice("length")).expect("Could not convert argument to i32");
let len: i32 =
from_value(this.get_field_slice("length")).expect("Could not convert argument to i32");
if len == 0 {
this.set_field_slice("length", to_value(0_i32));
@ -229,7 +239,8 @@ pub fn shift(this: &Value, _: &[Value], _: &mut Interpreter) -> ResultValue {
/// argument list.
/// <https://tc39.es/ecma262/#sec-array.prototype.unshift/>
pub fn unshift(this: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue {
let len: i32 = from_value(this.get_field_slice("length")).expect("Could not convert argument to i32");
let len: i32 =
from_value(this.get_field_slice("length")).expect("Could not convert argument to i32");
let arg_c: i32 = args.len() as i32;
if arg_c > 0 {
@ -245,7 +256,12 @@ pub fn unshift(this: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue
}
}
for j in 0..arg_c {
this.set_field_slice(&j.to_string(), args.get(j as usize).expect("Could not get argument").clone());
this.set_field_slice(
&j.to_string(),
args.get(j as usize)
.expect("Could not get argument")
.clone(),
);
}
}

4
src/lib/js/console.rs

@ -79,7 +79,9 @@ fn log_string_from(x: Value) -> String {
s,
"{}: {}",
key,
log_string_from(val.value.clone().expect("Could not read value").clone())
log_string_from(
val.value.clone().expect("Could not read value").clone()
)
)
.unwrap();
if key != last_key {

5
src/lib/js/function.rs

@ -152,6 +152,9 @@ mod tests {
let expected_return_val: f64 = 100.0;
let return_val = forward_val(&mut engine, "val").expect("value expected");
assert_eq!(return_val.is_double(), true);
assert_eq!(from_value::<f64>(return_val).expect("Could not convert value to f64"), expected_return_val);
assert_eq!(
from_value::<f64>(return_val).expect("Could not convert value to f64"),
expected_return_val
);
}
}

6
src/lib/js/math.rs

@ -139,8 +139,10 @@ pub fn min(_: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue {
/// Raise a number to a power
pub fn pow(_: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue {
Ok(to_value(if args.len() >= 2 {
let num: f64 = from_value(args.get(0).expect("Could not get argument").clone()).expect("Could not convert argument to f64");
let power: f64 = from_value(args.get(1).expect("Could not get argument").clone()).expect("Could not convert argument to f64");
let num: f64 = from_value(args.get(0).expect("Could not get argument").clone())
.expect("Could not convert argument to f64");
let power: f64 = from_value(args.get(1).expect("Could not get argument").clone())
.expect("Could not convert argument to f64");
num.powf(power)
} else {
f64::NAN

10
src/lib/js/regexp.rs

@ -62,10 +62,12 @@ pub fn make_regexp(this: &Value, args: &[Value], _: &mut Interpreter) -> ResultV
if slots.get("RegExpMatcher").is_some() {
// first argument is another `RegExp` object, so copy its pattern and flags
if let Some(body) = slots.get("OriginalSource") {
regex_body = from_value(body.clone()).expect("Could not convert value to String");
regex_body =
from_value(body.clone()).expect("Could not convert value to String");
}
if let Some(flags) = slots.get("OriginalFlags") {
regex_flags = from_value(flags.clone()).expect("Could not convert value to String");
regex_flags =
from_value(flags.clone()).expect("Could not convert value to String");
}
}
}
@ -227,7 +229,9 @@ pub fn exec(this: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue {
let mut result = Vec::with_capacity(locations.len());
for i in 0..locations.len() {
if let Some((start, end)) = locations.get(i) {
result.push(to_value(arg_str.get(start..end).expect("Could not get slice")));
result.push(to_value(
arg_str.get(start..end).expect("Could not get slice"),
));
} else {
result.push(Gc::new(ValueData::Undefined));
}

41
src/lib/js/string.rs

@ -203,7 +203,12 @@ pub fn slice(this: &Value, args: &[Value], ctx: &mut Interpreter) -> ResultValue
let mut new_str = String::new();
for i in from..from.wrapping_add(span) {
new_str.push(primitive_val.chars().nth(i as usize).expect("Could not get nth char"));
new_str.push(
primitive_val
.chars()
.nth(i as usize)
.expect("Could not get nth char"),
);
}
Ok(to_value(new_str))
}
@ -272,7 +277,8 @@ pub fn ends_with(this: &Value, args: &[Value], ctx: &mut Interpreter) -> ResultV
let end_position: i32 = if args.len() < 2 {
length
} else {
from_value(args.get(1).expect("Could not get argumetn").clone()).expect("Could not convert value to i32")
from_value(args.get(1).expect("Could not get argumetn").clone())
.expect("Could not convert value to i32")
};
let end = min(max(end_position, 0), length);
@ -311,7 +317,8 @@ pub fn includes(this: &Value, args: &[Value], ctx: &mut Interpreter) -> ResultVa
let position: i32 = if args.len() < 2 {
0
} else {
from_value(args.get(1).expect("Could not get argument").clone()).expect("Could not convert value to i32")
from_value(args.get(1).expect("Could not get argument").clone())
.expect("Could not convert value to i32")
};
let start = min(max(position, 0), length);
@ -347,7 +354,8 @@ pub fn index_of(this: &Value, args: &[Value], ctx: &mut Interpreter) -> ResultVa
let position: i32 = if args.len() < 2 {
0
} else {
from_value(args.get(1).expect("Could not get argument").clone()).expect("Could not convert value to i32")
from_value(args.get(1).expect("Could not get argument").clone())
.expect("Could not convert value to i32")
};
let start = min(max(position, 0), length);
@ -392,7 +400,8 @@ pub fn last_index_of(this: &Value, args: &[Value], ctx: &mut Interpreter) -> Res
let position: i32 = if args.len() < 2 {
0
} else {
from_value(args.get(1).expect("Could not get argument").clone()).expect("Could not convert value to i32")
from_value(args.get(1).expect("Could not get argument").clone())
.expect("Could not convert value to i32")
};
let start = min(max(position, 0), length);
@ -471,7 +480,10 @@ pub fn pad_end(this: &Value, args: &[Value], ctx: &mut Interpreter) -> ResultVal
.expect("failed to parse argument for String method");
let fill_string: Option<String> = match args.len() {
1 => None,
_ => Some(from_value(args.get(1).expect("Could not get argument").clone()).expect("Could not convert value to Option<String>")),
_ => Some(
from_value(args.get(1).expect("Could not get argument").clone())
.expect("Could not convert value to Option<String>"),
),
};
string_pad(primitive_val, max_length, fill_string, false)
@ -495,7 +507,10 @@ pub fn pad_start(this: &Value, args: &[Value], ctx: &mut Interpreter) -> ResultV
.expect("failed to parse argument for String method");
let fill_string: Option<String> = match args.len() {
1 => None,
_ => Some(from_value(args.get(1).expect("Could not get argument").clone()).expect("Could not convert value to Option<String>")),
_ => Some(
from_value(args.get(1).expect("Could not get argument").clone())
.expect("Could not convert value to Option<String>"),
),
};
string_pad(primitive_val, max_length, fill_string, true)
@ -587,7 +602,8 @@ pub fn substring(this: &Value, args: &[Value], ctx: &mut Interpreter) -> ResultV
let end = if args.len() < 2 {
length
} else {
from_value(args.get(1).expect("Could not get argument").clone()).expect("failed to parse argument for String method")
from_value(args.get(1).expect("Could not get argument").clone())
.expect("failed to parse argument for String method")
};
// Both start and end args replaced by 0 if they were negative
// or by the length of the String if they were greater
@ -598,7 +614,11 @@ pub fn substring(this: &Value, args: &[Value], ctx: &mut Interpreter) -> ResultV
let to = max(final_start, final_end) as usize;
// Extract the part of the string contained between the start index and the end index
// where start is guaranteed to be smaller or equals to end
let extracted_string: String = primitive_val.chars().skip(from).take(to.wrapping_sub(from)).collect();
let extracted_string: String = primitive_val
.chars()
.skip(from)
.take(to.wrapping_sub(from))
.collect();
Ok(to_value(extracted_string))
}
@ -631,7 +651,8 @@ pub fn substr(this: &Value, args: &[Value], ctx: &mut Interpreter) -> ResultValu
let end = if args.len() < 2 {
i32::max_value()
} else {
from_value(args.get(1).expect("Could not get argument").clone()).expect("failed to parse argument for String method")
from_value(args.get(1).expect("Could not get argument").clone())
.expect("failed to parse argument for String method")
};
// If start is negative it become the number of code units from the end of the string
if start < 0 {

30
src/lib/js/value.rs

@ -307,7 +307,10 @@ impl ValueData {
match prop_getter {
Some(val) => val,
None => {
let val = prop.value.as_ref().expect("Could not get property as reference");
let val = prop
.value
.as_ref()
.expect("Could not get property as reference");
val.clone()
}
}
@ -481,7 +484,9 @@ impl ValueData {
/// Convert from a JSON value to a JS value
pub fn from_json(json: JSONValue) -> Self {
match json {
JSONValue::Number(v) => ValueData::Number(v.as_f64().expect("Could not convert value to f64")),
JSONValue::Number(v) => {
ValueData::Number(v.as_f64().expect("Could not convert value to f64"))
}
JSONValue::String(v) => ValueData::String(v),
JSONValue::Bool(v) => ValueData::Boolean(v),
JSONValue::Array(vs) => {
@ -527,7 +532,9 @@ impl ValueData {
JSONValue::Object(new_obj)
}
ValueData::String(ref str) => JSONValue::String(str.clone()),
ValueData::Number(num) => JSONValue::Number(JSONNumber::from_f64(num).expect("Could not convert to JSONNumber")),
ValueData::Number(num) => JSONValue::Number(
JSONNumber::from_f64(num).expect("Could not convert to JSONNumber"),
),
ValueData::Integer(val) => JSONValue::Number(JSONNumber::from(val)),
}
}
@ -619,8 +626,12 @@ impl Add for ValueData {
type Output = Self;
fn add(self, other: Self) -> Self {
match (self, other) {
(ValueData::String(ref s), ref o) => ValueData::String(format!("{}{}", s.clone(), &o.to_string())),
(ref s, ValueData::String(ref o)) => ValueData::String(format!("{}{}", s.to_string(), o)),
(ValueData::String(ref s), ref o) => {
ValueData::String(format!("{}{}", s.clone(), &o.to_string()))
}
(ref s, ValueData::String(ref o)) => {
ValueData::String(format!("{}{}", s.to_string(), o))
}
(ref s, ref o) => ValueData::Number(s.to_num() + o.to_num()),
}
}
@ -725,7 +736,9 @@ impl FromValue for String {
impl<'s> ToValue for &'s str {
fn to_value(&self) -> Value {
Gc::new(ValueData::String(String::from_str(*self).expect("Could not convert string to self to String")))
Gc::new(ValueData::String(
String::from_str(*self).expect("Could not convert string to self to String"),
))
}
}
@ -736,7 +749,10 @@ impl ToValue for char {
}
impl FromValue for char {
fn from_value(v: Value) -> Result<Self, &'static str> {
Ok(v.to_string().chars().next().expect("Could not get next char"))
Ok(v.to_string()
.chars()
.next()
.expect("Could not get next char"))
}
}

14
src/lib/syntax/lexer.rs

@ -180,7 +180,9 @@ impl<'a> Lexer<'a> {
F: FnMut(char) -> bool,
{
let mut s = String::new();
while self.buffer.peek().is_some() && f(self.preview_next().expect("Could not preview next value")) {
while self.buffer.peek().is_some()
&& f(self.preview_next().expect("Could not preview next value"))
{
s.push(self.next()?);
}
@ -264,7 +266,8 @@ impl<'a> Lexer<'a> {
.expect("Invalid Unicode escape sequence");
self.next()?; // '}'
self.column_number += (s.len() as u64).wrapping_add(3);
self.column_number +=
(s.len() as u64).wrapping_add(3);
c
} else {
let mut codepoints: Vec<u16> = vec![];
@ -281,7 +284,8 @@ impl<'a> Lexer<'a> {
};
codepoints.push(as_num);
self.column_number += (s.len() as u64).wrapping_add(2);
self.column_number +=
(s.len() as u64).wrapping_add(2);
// Check for another UTF-16 codepoint
if self.next_is('\\') && self.next_is('u') {
@ -393,7 +397,9 @@ impl<'a> Lexer<'a> {
}
}
// TODO make this a bit more safe -------------------------------VVVV
self.push_token(TokenData::NumericLiteral(f64::from_str(&buf).expect("Could not convert value to f64")))
self.push_token(TokenData::NumericLiteral(
f64::from_str(&buf).expect("Could not convert value to f64"),
))
}
_ if ch.is_alphabetic() || ch == '$' || ch == '_' => {
let mut buf = ch.to_string();

8
src/lib/syntax/parser.rs

@ -201,7 +201,10 @@ impl Parser {
ExprDef::If(
Box::new(cond),
Box::new(expr),
if next.is_ok() && next.expect("Could not get next value").data == TokenData::Keyword(Keyword::Else) {
if next.is_ok()
&& next.expect("Could not get next value").data
== TokenData::Keyword(Keyword::Else)
{
self.pos += 1;
Some(Box::new(self.parse()?))
} else {
@ -507,7 +510,8 @@ impl Parser {
== TokenData::Punctuator(Punctuator::Colon) =>
{
let mut map = Box::new(BTreeMap::new());
while self.get_token(self.pos.wrapping_sub(1))?.data == TokenData::Punctuator(Punctuator::Comma)
while self.get_token(self.pos.wrapping_sub(1))?.data
== TokenData::Punctuator(Punctuator::Comma)
|| map.len() == 0
{
let tk = self.get_token(self.pos)?;

Loading…
Cancel
Save