Make clippy a happy chappy

This commit is contained in:
Andrew Morris
2023-07-07 16:08:28 +10:00
parent 6c72b32111
commit 581965e01b
59 changed files with 728 additions and 992 deletions

View File

@@ -3,6 +3,7 @@ use super::super::vs_value::{Val, ValTrait};
use super::array_mapping_frame::{ArrayMappingFrame, ArrayMappingState};
pub static EVERY: NativeFrameFunction = NativeFrameFunction {
#[allow(clippy::box_default)]
make_frame: || Box::new(ArrayMappingFrame::new(Box::new(EveryState::default()))),
};

View File

@@ -5,6 +5,7 @@ use super::super::vs_value::{Val, ValTrait};
use super::array_mapping_frame::{ArrayMappingFrame, ArrayMappingState};
pub static FILTER: NativeFrameFunction = NativeFrameFunction {
#[allow(clippy::box_default)]
make_frame: || Box::new(ArrayMappingFrame::new(Box::new(FilterState::default()))),
};
@@ -19,7 +20,7 @@ impl ArrayMappingState for FilterState {
self.filter_results.push(element.clone());
}
return None;
None
}
fn finish(&mut self) -> Val {

View File

@@ -3,6 +3,7 @@ use super::super::vs_value::{Val, ValTrait};
use super::array_mapping_frame::{ArrayMappingFrame, ArrayMappingState};
pub static FIND: NativeFrameFunction = NativeFrameFunction {
#[allow(clippy::box_default)]
make_frame: || Box::new(ArrayMappingFrame::new(Box::new(FindState::default()))),
};

View File

@@ -3,6 +3,7 @@ use super::super::vs_value::{Val, ValTrait};
use super::array_mapping_frame::{ArrayMappingFrame, ArrayMappingState};
pub static FIND_INDEX: NativeFrameFunction = NativeFrameFunction {
#[allow(clippy::box_default)]
make_frame: || Box::new(ArrayMappingFrame::new(Box::new(FindIndexState::default()))),
};

View File

@@ -5,6 +5,7 @@ use super::super::vs_value::{Val, ValTrait};
use super::array_mapping_frame::{ArrayMappingFrame, ArrayMappingState};
pub static FLAT_MAP: NativeFrameFunction = NativeFrameFunction {
#[allow(clippy::box_default)]
make_frame: || Box::new(ArrayMappingFrame::new(Box::new(FlatMapState::default()))),
};
@@ -24,7 +25,7 @@ impl ArrayMappingState for FlatMapState {
}
}
return None;
None
}
fn finish(&mut self) -> Val {

View File

@@ -5,6 +5,7 @@ use super::super::vs_value::Val;
use super::array_mapping_frame::{ArrayMappingFrame, ArrayMappingState};
pub static MAP: NativeFrameFunction = NativeFrameFunction {
#[allow(clippy::box_default)]
make_frame: || Box::new(ArrayMappingFrame::new(Box::new(MapState::default()))),
};
@@ -16,7 +17,7 @@ struct MapState {
impl ArrayMappingState for MapState {
fn process(&mut self, _i: usize, _element: &Val, mapped: Val) -> Option<Val> {
self.map_results.push(mapped);
return None;
None
}
fn finish(&mut self) -> Val {

View File

@@ -34,15 +34,15 @@ pub struct ArrayMappingFrame {
impl ArrayMappingFrame {
pub fn new(state: Box<dyn ArrayMappingState>) -> ArrayMappingFrame {
return ArrayMappingFrame {
state: state,
ArrayMappingFrame {
state,
early_exit: None,
this: None,
array_i: 0,
mapper: Val::Void,
this_arg: Val::Undefined,
param_i: 0,
};
}
}
}
@@ -139,7 +139,7 @@ impl StackFrameTrait for ArrayMappingFrame {
self.early_exit = self
.state
.process(array_i, element, call_result.return_)
.map(|v| Ok(v));
.map(Ok);
}
fn get_call_result(&mut self) -> CallResult {

View File

@@ -3,6 +3,7 @@ use super::super::vs_value::{Val, ValTrait};
use super::array_mapping_frame::{ArrayMappingFrame, ArrayMappingState};
pub static SOME: NativeFrameFunction = NativeFrameFunction {
#[allow(clippy::box_default)]
make_frame: || Box::new(ArrayMappingFrame::new(Box::new(SomeState::default()))),
};

View File

@@ -84,7 +84,7 @@ impl SortTreeNode {
let mid = vals.start + (vals.end - vals.start) / 2;
return SortTreeNode {
SortTreeNode {
data: SortTreeNodeData::Branch(
Box::new(SortTreeNode::new(VecSlice {
vec: vals.vec,
@@ -97,33 +97,27 @@ impl SortTreeNode {
end: vals.end,
})),
),
};
}
}
fn get_compare_elements(&self) -> Option<(Val, Val)> {
match &self.data {
SortTreeNodeData::Branch(left, right) => {
return left
.get_compare_elements()
.or_else(|| right.get_compare_elements());
}
SortTreeNodeData::Branch(left, right) => left
.get_compare_elements()
.or_else(|| right.get_compare_elements()),
SortTreeNodeData::Sorting(_vals, left, right) => {
let lval_opt = left.vec.get(left.pos);
let rval_opt = right.vec.get(right.pos);
match (lval_opt, rval_opt) {
(Some(lval), Some(rval)) => {
return Some((lval.clone(), rval.clone()));
}
(Some(lval), Some(rval)) => Some((lval.clone(), rval.clone())),
_ => {
panic!("Failed to get compare elements from sorting state");
}
}
}
SortTreeNodeData::Sorted(_) => {
return None;
}
};
SortTreeNodeData::Sorted(_) => None,
}
}
fn apply_outcome(&mut self, should_swap: bool) {
@@ -136,26 +130,23 @@ impl SortTreeNode {
SortTreeNodeData::Sorted(left_vals) => {
right.apply_outcome(should_swap);
match &mut right.data {
SortTreeNodeData::Sorted(right_vals) => {
let mut owned_left_vals = vec![];
std::mem::swap(&mut owned_left_vals, left_vals);
let mut owned_right_vals = vec![];
std::mem::swap(&mut owned_right_vals, right_vals);
if let SortTreeNodeData::Sorted(right_vals) = &mut right.data {
let mut owned_left_vals = vec![];
std::mem::swap(&mut owned_left_vals, left_vals);
let mut owned_right_vals = vec![];
std::mem::swap(&mut owned_right_vals, right_vals);
self.data = SortTreeNodeData::Sorting(
vec![],
VecPos {
vec: owned_left_vals,
pos: 0,
},
VecPos {
vec: owned_right_vals,
pos: 0,
},
);
}
_ => {}
self.data = SortTreeNodeData::Sorting(
vec![],
VecPos {
vec: owned_left_vals,
pos: 0,
},
VecPos {
vec: owned_right_vals,
pos: 0,
},
);
};
}
};
@@ -220,12 +211,9 @@ impl StackFrameTrait for SortFrame {
}
fn write_param(&mut self, param: Val) {
match self.param_i {
0 => {
self.comparator = param;
}
_ => {}
};
if self.param_i == 0 {
self.comparator = param;
}
self.param_i += 1;
}
@@ -241,9 +229,7 @@ impl StackFrameTrait for SortFrame {
Val::Void => {
let array_data_mut = Rc::make_mut(array_data);
array_data_mut
.elements
.sort_by(|a, b| a.to_string().cmp(&b.to_string()));
array_data_mut.elements.sort_by_key(|a| a.to_string());
return Ok(FrameStepOk::Pop(CallResult {
return_: Val::Array(array_data.clone()),

View File

@@ -81,10 +81,10 @@ pub fn op_sub_array_index(array: &mut Rc<VsArray>, index: usize) -> Result<Val,
None => array.elements[index].clone(),
};
return Ok(match res {
Ok(match res {
Val::Void => Val::Undefined,
_ => res,
});
})
}
static AT: NativeFunction = native_fn(|this, params| {
@@ -230,7 +230,7 @@ static FILL: NativeFunction = native_fn(|mut this, params| {
static FLAT: NativeFunction = native_fn(|this, params| {
Ok(match this.get() {
Val::Array(array_data) => {
if params.len() > 0 {
if !params.is_empty() {
return Err("TODO: .flat depth parameter".to_internal_error());
}
@@ -300,7 +300,7 @@ static INDEX_OF: NativeFunction = native_fn(|this, params| {
static JOIN: NativeFunction = native_fn(|this, params| {
Ok(match this.get() {
Val::Array(vals) => {
if vals.elements.len() == 0 {
if vals.elements.is_empty() {
return Ok("".to_val());
}
@@ -359,7 +359,7 @@ static POP: NativeFunction = native_fn(|mut this, _params| {
Ok(match this {
Val::Array(array_data) => {
if array_data.elements.len() == 0 {
if array_data.elements.is_empty() {
return Ok(Val::Undefined);
}
@@ -396,7 +396,7 @@ static REVERSE: NativeFunction = native_fn(|mut this, _params| {
Ok(match this {
Val::Array(array_data) => {
if array_data.elements.len() == 0 {
if array_data.elements.is_empty() {
// Treating this as an edge case because rust protects us from
// underflow when computing last below.
return Ok(this.clone());
@@ -423,7 +423,7 @@ static SHIFT: NativeFunction = native_fn(|mut this, _params| {
Ok(match this {
Val::Array(array_data) => {
if array_data.elements.len() == 0 {
if array_data.elements.is_empty() {
return Ok(Val::Undefined);
}
@@ -496,9 +496,8 @@ static SPLICE: NativeFunction = native_fn(|mut this, params| {
let replace_len = min(insert_len, delete_count);
if insert_len > replace_len {
for i in 0..replace_len {
array_data_mut.elements[start + i] = params[i + 2].clone();
}
array_data_mut.elements[start..(replace_len + start)]
.clone_from_slice(&params[2..(replace_len + 2)]);
let gap = insert_len - replace_len;
@@ -510,13 +509,11 @@ static SPLICE: NativeFunction = native_fn(|mut this, params| {
array_data_mut.elements[i + gap] = array_data_mut.elements[i].clone();
}
for i in replace_len..insert_len {
array_data_mut.elements[start + i] = params[i + 2].clone();
}
array_data_mut.elements[(replace_len + start)..(insert_len + start)]
.clone_from_slice(&params[(replace_len + 2)..(insert_len + 2)]);
} else {
for i in 0..insert_len {
array_data_mut.elements[start + i] = params[i + 2].clone();
}
array_data_mut.elements[start..(insert_len + start)]
.clone_from_slice(&params[2..(insert_len + 2)]);
let gap = delete_count - insert_len;
@@ -547,11 +544,8 @@ static UNSHIFT: NativeFunction = native_fn(|mut this, params| {
Val::Array(array_data) => {
let array_data_mut = Rc::make_mut(array_data);
let mut i = 0;
for p in params {
for (i, p) in params.into_iter().enumerate() {
array_data_mut.elements.insert(i, p);
i += 1;
}
Val::Number(array_data_mut.elements.len() as f64)

View File

@@ -9,7 +9,8 @@ use crate::{
};
use super::{
builtin_object::BuiltinObject, range_error_builtin::ToRangeError, type_error_builtin::ToTypeError,
builtin_object::BuiltinObject, internal_error_builtin::ToInternalError,
range_error_builtin::ToRangeError, type_error_builtin::ToTypeError,
};
pub struct ArrayBuiltin {}
@@ -24,7 +25,7 @@ impl BuiltinObject for ArrayBuiltin {
"isArray" => IS_ARRAY.to_val(),
"from" => FROM.to_val(),
"of" => OF.to_val(),
_ => return Val::Undefined,
_ => Val::Undefined,
}
}
@@ -60,7 +61,7 @@ static FROM: NativeFunction = native_fn(|_this, params| {
};
if params.len() > 1 {
return Err(format!("TODO: Using Array.from with a map function").to_val());
return Err("TODO: Using Array.from with a map function".to_internal_error());
}
Ok(match first_param {
@@ -69,7 +70,9 @@ static FROM: NativeFunction = native_fn(|_this, params| {
Val::Void | Val::Undefined | Val::Null | Val::CopyCounter(..) => {
return Err("items is not iterable".to_type_error())
}
Val::Bool(..) | Val::Number(..) | Val::BigInt(..) | Val::Symbol(..) => VsArray::new().to_val(),
Val::Bool(..) | Val::Number(..) | Val::BigInt(..) | Val::Symbol(..) => {
VsArray::default().to_val()
}
Val::Object(..) | Val::Function(..) | Val::Class(..) | Val::Static(..) | Val::Dynamic(..) => {
let len = first_param
.sub(&"length".to_val())
@@ -78,7 +81,7 @@ static FROM: NativeFunction = native_fn(|_this, params| {
.to_number();
if len.is_sign_negative() || len.is_nan() {
return Ok(VsArray::new().to_val());
return Ok(VsArray::default().to_val());
}
if len.is_infinite() {

View File

@@ -127,15 +127,15 @@ pub static PARSE_INT: NativeFunction = native_fn(|_this, params| {
return Ok(Val::Number(f64::NAN));
}
let (is_negative, string_value) = if string_value.starts_with('-') {
(true, &string_value[1..])
let (is_negative, string_value) = if let Some(stripped) = string_value.strip_prefix('-') {
(true, stripped)
} else {
(false, string_value.as_str())
};
let string_value = match string_value.find(|c: char| !c.is_digit(radix as u32)) {
Some(pos) => &string_value[..pos],
None => &string_value,
None => string_value,
};
match i64::from_str_radix(string_value, radix as u32) {

View File

@@ -51,7 +51,7 @@ impl BytecodeType {
fn from_byte(byte: u8) -> BytecodeType {
use BytecodeType::*;
return match byte {
match byte {
0x00 => End,
0x01 => Void,
0x02 => Undefined,
@@ -74,7 +74,7 @@ impl BytecodeType {
0x14 => GeneratorFunction,
_ => Unrecognized,
};
}
}
}
@@ -82,19 +82,19 @@ impl BytecodeDecoder {
pub fn decode_byte(&mut self) -> u8 {
let byte = self.bytecode[self.pos];
self.pos += 1;
return byte;
byte
}
pub fn peek_byte(&self) -> u8 {
return self.bytecode[self.pos];
self.bytecode[self.pos]
}
pub fn decode_type(&mut self) -> BytecodeType {
return BytecodeType::from_byte(self.decode_byte());
BytecodeType::from_byte(self.decode_byte())
}
pub fn peek_type(&self) -> BytecodeType {
return BytecodeType::from_byte(self.peek_byte());
BytecodeType::from_byte(self.peek_byte())
}
pub fn decode_val(&mut self, registers: &mut Vec<Val>) -> Val {
@@ -171,7 +171,7 @@ impl BytecodeDecoder {
pub fn decode_signed_byte(&mut self) -> i8 {
let res = self.bytecode[self.pos] as i8;
self.pos += 1;
return res;
res
}
pub fn decode_number(&mut self) -> f64 {
@@ -179,7 +179,7 @@ impl BytecodeDecoder {
let next_pos = self.pos + 8;
buf.clone_from_slice(&self.bytecode[self.pos..next_pos]);
self.pos = next_pos;
return f64::from_le_bytes(buf);
f64::from_le_bytes(buf)
}
pub fn decode_bigint(&mut self) -> BigInt {
@@ -195,7 +195,7 @@ impl BytecodeDecoder {
let bytes = &self.bytecode[self.pos..self.pos + len];
self.pos += len;
return BigInt::from_bytes_le(sign, bytes);
BigInt::from_bytes_le(sign, bytes)
}
pub fn decode_string(&mut self) -> String {
@@ -205,7 +205,7 @@ impl BytecodeDecoder {
let res = String::from_utf8_lossy(&self.bytecode[start..end]).into_owned();
self.pos = end;
return res;
res
}
pub fn decode_varsize_uint(&mut self) -> usize {
@@ -227,7 +227,7 @@ impl BytecodeDecoder {
pub fn decode_pos(&mut self) -> usize {
// TODO: the number of bytes to represent a position should be based on the
// size of the bytecode
return self.decode_byte() as usize + 256 * self.decode_byte() as usize;
self.decode_byte() as usize + 256 * self.decode_byte() as usize
}
pub fn decode_register_index(&mut self) -> Option<usize> {
@@ -238,14 +238,14 @@ impl BytecodeDecoder {
return None;
}
return Some(byte as usize);
Some(byte as usize)
}
pub fn clone_at(&self, pos: usize) -> BytecodeDecoder {
return BytecodeDecoder {
BytecodeDecoder {
bytecode: self.bytecode.clone(),
pos,
};
}
}
pub fn decode_pointer(&mut self, registers: &mut Vec<Val>) -> Val {
@@ -267,12 +267,7 @@ impl BytecodeDecoder {
}
}
let cached_val = self
.bytecode
.cache
.borrow()
.get(&pos)
.map(|val| val.clone());
let cached_val = self.bytecode.cache.borrow().get(&pos).cloned();
match cached_val {
Some(val) => val,
@@ -290,7 +285,7 @@ impl BytecodeDecoder {
let register_count = self.decode_byte() as usize;
let parameter_count = self.decode_byte() as usize;
return VsFunction {
VsFunction {
bytecode: self.bytecode.clone(),
is_generator,
register_count,
@@ -298,10 +293,10 @@ impl BytecodeDecoder {
start: self.pos,
binds: Vec::new(),
}
.to_val();
.to_val()
}
pub fn decode_instruction(&mut self) -> InstructionByte {
return InstructionByte::from_byte(self.decode_byte());
InstructionByte::from_byte(self.decode_byte())
}
}

View File

@@ -38,10 +38,8 @@ impl BytecodeStackFrame {
pub fn apply_unary_op(&mut self, op: fn(input: &Val) -> Val) {
let input = self.decoder.decode_val(&mut self.registers);
let register_index = self.decoder.decode_register_index();
if register_index.is_some() {
self.registers[register_index.unwrap()] = op(&input);
if let Some(register_index) = self.decoder.decode_register_index() {
self.registers[register_index] = op(&input);
}
}
@@ -142,10 +140,9 @@ impl StackFrameTrait for BytecodeStackFrame {
Mov => {
let val = self.decoder.decode_val(&mut self.registers);
let register_index = self.decoder.decode_register_index();
if register_index.is_some() {
self.registers[register_index.unwrap()] = val;
if let Some(register_index) = self.decoder.decode_register_index() {
self.registers[register_index] = val;
}
}
@@ -235,11 +232,8 @@ impl StackFrameTrait for BytecodeStackFrame {
self.decode_parameters(),
)?;
match self.decoder.decode_register_index() {
Some(return_target) => {
self.registers[return_target] = res;
}
None => {}
if let Some(return_target) = self.decoder.decode_register_index() {
self.registers[return_target] = res;
};
}
};
@@ -277,24 +271,24 @@ impl StackFrameTrait for BytecodeStackFrame {
let params = self.decoder.decode_val(&mut self.registers);
let register_index = self.decoder.decode_register_index();
let params_array = params.as_array_data();
let params_array = match params.as_array_data() {
Some(params_array) => params_array,
if params_array.is_none() {
// Not sure this needs to be an exception in future since compiled
// code should never violate this
return Err("bind params should always be array".to_internal_error());
}
None => return Err("bind params should always be array".to_internal_error()),
};
let bound_fn = fn_val.bind((*params_array.unwrap()).elements.clone());
let bound_fn = match fn_val.bind(params_array.elements.clone()) {
Some(bound_fn) => bound_fn,
if bound_fn.is_none() {
// Not sure this needs to be an exception in future since compiled
// code should never violate this
return Err("fn parameter of bind should always be bindable".to_internal_error());
}
None => return Err("fn parameter of bind should always be bindable".to_internal_error()),
};
if register_index.is_some() {
self.registers[register_index.unwrap()] = bound_fn.unwrap();
if let Some(register_index) = register_index {
self.registers[register_index] = bound_fn;
}
}
@@ -348,11 +342,8 @@ impl StackFrameTrait for BytecodeStackFrame {
let res = native_fn(ThisWrapper::new(true, &mut obj), params)?;
match self.decoder.decode_register_index() {
Some(return_target) => {
self.registers[return_target] = res;
}
None => {}
if let Some(return_target) = self.decoder.decode_register_index() {
self.registers[return_target] = res;
};
}
};
@@ -388,11 +379,8 @@ impl StackFrameTrait for BytecodeStackFrame {
params,
)?;
match self.decoder.decode_register_index() {
Some(return_target) => {
self.registers[return_target] = res;
}
None => {}
if let Some(return_target) = self.decoder.decode_register_index() {
self.registers[return_target] = res;
};
}
};
@@ -471,11 +459,8 @@ impl StackFrameTrait for BytecodeStackFrame {
self.decode_parameters(),
)?;
match self.decoder.decode_register_index() {
Some(target) => {
self.registers[target] = instance;
}
None => {}
if let Some(target) = self.decoder.decode_register_index() {
self.registers[target] = instance;
};
}
},

View File

@@ -10,12 +10,12 @@ pub struct FirstStackFrame {
impl FirstStackFrame {
pub fn new() -> FirstStackFrame {
return FirstStackFrame {
FirstStackFrame {
call_result: CallResult {
return_: Val::Void,
this: Val::Void,
},
};
}
}
}
@@ -37,7 +37,8 @@ impl StackFrameTrait for FirstStackFrame {
}
fn get_call_result(&mut self) -> CallResult {
return self.call_result.clone();
// TODO: get_call_result(self) version? (Move memory variation)
self.call_result.clone()
}
fn catch_exception(&mut self, _exception: &mut Val) {

View File

@@ -27,10 +27,10 @@ pub struct Generator {
impl Generator {
pub fn new(frame: StackFrame) -> Generator {
return Generator {
Generator {
frame,
stack: vec![],
};
}
}
}
@@ -130,7 +130,7 @@ impl fmt::Display for Generator {
// needing to copy.
//
static NEXT: NativeFrameFunction = NativeFrameFunction {
make_frame: || Box::new(GeneratorFrame::default()),
make_frame: || Box::<GeneratorFrame>::default(),
};
#[derive(Clone, Default)]
@@ -151,12 +151,12 @@ impl StackFrameTrait for GeneratorFrame {
return Err("Cannot call Generator.next on a const generator".to_type_error());
}
let mut generator = dynamic_make_mut(&mut dynamic)
let generator = dynamic_make_mut(&mut dynamic)
.as_any_mut()
.downcast_mut::<Generator>()
.ok_or_else(|| "Generator.next called on different object".to_type_error())?;
self.generator = take(&mut generator);
self.generator = take(generator);
Ok(())
}
@@ -217,7 +217,7 @@ impl StackFrameTrait for GeneratorFrame {
swap(&mut frame, &mut self.generator.frame);
self.generator.stack.push(frame);
return Ok(FrameStepOk::Continue);
Ok(FrameStepOk::Continue)
}
}
}

View File

@@ -12,7 +12,7 @@ pub fn to_wrapping_index(index: Option<&Val>, len: usize) -> Option<usize> {
return None;
}
return Some(unchecked as usize);
Some(unchecked as usize)
}
pub fn to_wrapping_index_clamped(index: &Val, len: usize) -> isize {
@@ -28,7 +28,7 @@ pub fn to_wrapping_index_clamped(index: &Val, len: usize) -> isize {
return len as isize;
}
return wrapping_index;
wrapping_index
}
pub fn to_unchecked_wrapping_index(index: &Val, len: usize) -> isize {
@@ -43,5 +43,5 @@ pub fn to_unchecked_wrapping_index(index: &Val, len: usize) -> isize {
// TODO: Investigate potential pitfalls for arrays with length exceeding max
// isize.
return floored_index as isize;
floored_index as isize
}

View File

@@ -70,10 +70,7 @@ impl ValTrait for IterationResult {
}
fn has(&self, key: &Val) -> Option<bool> {
Some(match key.to_string().as_str() {
"value" | "done" => true,
_ => false,
})
Some(matches!(key.to_string().as_str(), "value" | "done"))
}
fn submov(&mut self, _key: &Val, _value: Val) -> Result<(), Val> {

View File

@@ -60,7 +60,7 @@ impl StringIterator {
value = (value << 6) | (next_byte & 0x3F) as u32;
}
Some(std::char::from_u32(value as u32).expect("Invalid code point"))
Some(std::char::from_u32(value).expect("Invalid code point"))
}
}

View File

@@ -14,7 +14,7 @@ pub struct MakeGeneratorFrame {
impl MakeGeneratorFrame {
pub fn new(frame: BytecodeStackFrame) -> MakeGeneratorFrame {
return MakeGeneratorFrame { frame: Some(frame) };
MakeGeneratorFrame { frame: Some(frame) }
}
fn frame_mut(&mut self) -> &mut BytecodeStackFrame {

View File

@@ -48,7 +48,7 @@ static TO_FIXED: NativeFunction = native_fn(|this, params| {
format!("{:.*}", precision as usize, number).to_val()
}
_ => return Err(format!("TODO: number indirection").to_val()),
_ => return Err("TODO: number indirection".to_internal_error()),
})
});
@@ -72,8 +72,8 @@ static TO_EXPONENTIAL: NativeFunction = native_fn(|this, params| {
});
static TODO_LOCALE: NativeFunction = native_fn(|this, _params| match this.get() {
Val::Number(_number) => return Err("TODO: locale".to_internal_error()),
_ => return Err("number indirection".to_internal_error()),
Val::Number(_number) => Err("TODO: locale".to_internal_error()),
_ => Err("number indirection".to_internal_error()),
});
static TO_STRING: NativeFunction = native_fn(|this, params| {

View File

@@ -45,7 +45,7 @@ pub fn op_plus(left: &Val, right: &Val) -> Result<Val, Val> {
}
}
return Ok(Val::Number(left_prim.to_number() + right_prim.to_number()));
Ok(Val::Number(left_prim.to_number() + right_prim.to_number()))
}
pub fn op_unary_plus(input: &Val) -> Val {
@@ -58,9 +58,7 @@ pub fn op_unary_plus(input: &Val) -> Val {
pub fn op_minus(left: &Val, right: &Val) -> Result<Val, Val> {
match (left.as_bigint_data(), right.as_bigint_data()) {
(Some(left_bigint), Some(right_bigint)) => Ok(Val::BigInt(left_bigint - right_bigint)),
(Some(_), None) | (None, Some(_)) => {
return Err("Cannot mix BigInt with other types".to_type_error())
}
(Some(_), None) | (None, Some(_)) => Err("Cannot mix BigInt with other types".to_type_error()),
_ => Ok(Val::Number(left.to_number() - right.to_number())),
}
}
@@ -117,10 +115,7 @@ pub fn op_exp(left: &Val, right: &Val) -> Result<Val, Val> {
pub fn op_eq_impl(left: &Val, right: &Val) -> Result<bool, Val> {
Ok(match (left, right) {
(left, Val::Undefined | Val::Null) => match left {
Val::Undefined | Val::Null => true,
_ => false,
},
(left, Val::Undefined | Val::Null) => matches!(left, Val::Undefined | Val::Null),
(Val::Bool(left_bool), Val::Bool(right_bool)) => left_bool == right_bool,
(Val::Number(left_number), Val::Number(right_number)) => left_number == right_number,
(Val::String(left_string), Val::String(right_string)) => left_string == right_string,
@@ -132,7 +127,7 @@ pub fn op_eq_impl(left: &Val, right: &Val) -> Result<bool, Val> {
}
(Val::BigInt(left_bigint), Val::BigInt(right_bigint)) => left_bigint == right_bigint,
(Val::Array(left_array), Val::Array(right_array)) => 'b: {
if &**left_array as *const _ == &**right_array as *const _ {
if std::ptr::eq(&**left_array, &**right_array) {
break 'b true;
}
@@ -155,7 +150,7 @@ pub fn op_eq_impl(left: &Val, right: &Val) -> Result<bool, Val> {
return Err("TODO: class instance comparison".to_internal_error());
}
if &**left_object as *const _ == &**right_object as *const _ {
if std::ptr::eq(&**left_object, &**right_object) {
break 'b true;
}
@@ -234,7 +229,7 @@ pub fn op_triple_eq_impl(left: &Val, right: &Val) -> Result<bool, Val> {
(Val::String(left_string), Val::String(right_string)) => left_string == right_string,
(Val::BigInt(left_bigint), Val::BigInt(right_bigint)) => left_bigint == right_bigint,
(Val::Array(left_array), Val::Array(right_array)) => 'b: {
if &**left_array as *const _ == &**right_array as *const _ {
if std::ptr::eq(&**left_array, &**right_array) {
break 'b true;
}
@@ -257,7 +252,7 @@ pub fn op_triple_eq_impl(left: &Val, right: &Val) -> Result<bool, Val> {
return Err("TODO: class instance comparison".to_internal_error());
}
if &**left_object as *const _ == &**right_object as *const _ {
if std::ptr::eq(&**left_object, &**right_object) {
break 'b true;
}
@@ -319,7 +314,7 @@ pub fn op_or(left: &Val, right: &Val) -> Result<Val, Val> {
}
pub fn op_not(input: &Val) -> Val {
return Val::Bool(!input.is_truthy());
Val::Bool(!input.is_truthy())
}
pub fn op_less(left: &Val, right: &Val) -> Result<Val, Val> {
@@ -330,10 +325,7 @@ pub fn op_less(left: &Val, right: &Val) -> Result<Val, Val> {
(Val::Number(left_number), Val::Number(right_number)) => left_number < right_number,
(Val::String(left_string), Val::String(right_string)) => left_string < right_string,
(Val::BigInt(left_bigint), Val::BigInt(right_bigint)) => left_bigint < right_bigint,
_ => match ecma_is_less_than(left, right) {
None => false,
Some(x) => x,
},
_ => ecma_is_less_than(left, right).unwrap_or(false),
}))
}
@@ -360,10 +352,7 @@ pub fn op_greater(left: &Val, right: &Val) -> Result<Val, Val> {
(Val::Number(left_number), Val::Number(right_number)) => left_number > right_number,
(Val::String(left_string), Val::String(right_string)) => left_string > right_string,
(Val::BigInt(left_bigint), Val::BigInt(right_bigint)) => left_bigint > right_bigint,
_ => match ecma_is_less_than(right, left) {
None => false,
Some(x) => x,
},
_ => ecma_is_less_than(right, left).unwrap_or(false),
}))
}
@@ -389,11 +378,11 @@ pub fn op_nullish_coalesce(left: &Val, right: &Val) -> Result<Val, Val> {
}
pub fn op_optional_chain(left: &mut Val, right: &Val) -> Result<Val, Val> {
return match left {
match left {
Val::Undefined | Val::Null => Ok(Val::Undefined),
_ => op_sub(left, right),
};
}
}
pub fn to_i32(x: f64) -> i32 {
@@ -403,7 +392,7 @@ pub fn to_i32(x: f64) -> i32 {
let int1 = (x.trunc() as i64) & 0xffffffff;
return int1 as i32;
int1 as i32
}
pub fn to_u32(x: f64) -> u32 {
@@ -413,7 +402,7 @@ pub fn to_u32(x: f64) -> u32 {
let int1 = (x.trunc() as i64) & 0xffffffff;
return int1 as u32;
int1 as u32
}
pub fn op_bit_and(left: &Val, right: &Val) -> Result<Val, Val> {

View File

@@ -282,20 +282,16 @@ static LAST_INDEX_OF: NativeFunction = native_fn(|this, params| {
static TODO_LOCALE: NativeFunction = native_fn(|this, _params| {
// TODO: Ok(...)
match this.get() {
Val::String(_string_data) => {
return Err("TODO: locale".to_internal_error());
}
_ => return Err("string indirection".to_internal_error()),
Val::String(_string_data) => Err("TODO: locale".to_internal_error()),
_ => Err("string indirection".to_internal_error()),
}
});
static TODO_REGEXES: NativeFunction = native_fn(|this, _params| {
// TODO: Ok(...)
match this.get() {
Val::String(_string_data) => {
return Err("TODO: regexes".to_internal_error());
}
_ => return Err("string indirection".to_internal_error()),
Val::String(_string_data) => Err("TODO: regexes".to_internal_error()),
_ => Err("string indirection".to_internal_error()),
}
});
@@ -304,9 +300,9 @@ static NORMALIZE: NativeFunction = native_fn(|this, _params| {
match this.get() {
Val::String(_string_data) => {
// Consider https://docs.rs/unicode-normalization/latest/unicode_normalization/
return Err("TODO: normalize".to_internal_error());
Err("TODO: normalize".to_internal_error())
}
_ => return Err("string indirection".to_internal_error()),
_ => Err("string indirection".to_internal_error()),
}
});
@@ -459,9 +455,8 @@ static SLICE: NativeFunction = native_fn(|this, params| {
// FIXME: This is a slow way of doing it. Part of the reason is that we're using rust's
// string type, so we can't just find the relevant byte range and copy it in one go.
for i in start..end {
match unicode_at(string_bytes, end as usize, i as usize) {
Some(c) => new_string.push(c),
None => {}
if let Some(c) = unicode_at(string_bytes, end as usize, i as usize) {
new_string.push(c)
}
}
@@ -603,9 +598,8 @@ static SUBSTRING: NativeFunction = native_fn(|this, params| {
// FIXME: This is a slow way of doing it. Part of the reason is that we're using rust's
// string type, so we can't just find the relevant byte range and copy it in one go.
for i in substring_start..substring_end {
match unicode_at(string_bytes, substring_end, i) {
Some(c) => new_string.push(c),
None => {}
if let Some(c) = unicode_at(string_bytes, substring_end, i) {
new_string.push(c)
}
}
@@ -674,7 +668,7 @@ static VALUES: NativeFunction = native_fn(|this, _params| match this.get() {
* - Successful match: Advances str_chars_param and returns true.
* - Unsuccessful match: Does not advance str_chars_param and returns false.
*/
fn match_chars(str_chars_param: &mut Chars, matcher: &String) -> bool {
fn match_chars(str_chars_param: &mut Chars, matcher: &str) -> bool {
let mut str_chars = str_chars_param.clone();
let mut matcher_chars = matcher.chars();
@@ -749,12 +743,8 @@ fn last_index_of(string_bytes: &[u8], search_bytes: &[u8], at_least_pos: usize)
}
pub fn unicode_at(bytes: &[u8], len: usize, index: usize) -> Option<char> {
match code_point_at(bytes, len, index) {
Some(code_point) => Some(
std::char::from_u32(code_point).expect("Invalid code point"), // TODO: Find out if this is reachable and what to do about it
),
None => None,
}
code_point_at(bytes, len, index)
.map(|code_point| std::char::from_u32(code_point).expect("Invalid code point"))
}
fn code_point_at(bytes: &[u8], len: usize, index: usize) -> Option<u32> {

View File

@@ -13,6 +13,15 @@ pub struct VirtualMachine {
pub stack: Vec<StackFrame>,
}
impl Default for VirtualMachine {
fn default() -> Self {
VirtualMachine {
frame: Box::new(FirstStackFrame::new()),
stack: Default::default(),
}
}
}
impl VirtualMachine {
pub fn run(
&mut self,
@@ -43,7 +52,7 @@ impl VirtualMachine {
self.step()?;
step_count += 1;
if self.stack.len() == 0 {
if self.stack.is_empty() {
return Ok(self.frame.get_call_result().return_);
}
}
@@ -51,7 +60,7 @@ impl VirtualMachine {
Err("step limit reached".to_internal_error())
}
None => {
while self.stack.len() > 0 {
while !self.stack.is_empty() {
self.step()?;
}
@@ -60,17 +69,6 @@ impl VirtualMachine {
}
}
pub fn new() -> VirtualMachine {
let mut registers: Vec<Val> = Vec::with_capacity(2);
registers.push(Val::Undefined);
registers.push(Val::Undefined);
return VirtualMachine {
frame: Box::new(FirstStackFrame::new()),
stack: Default::default(),
};
}
pub fn step(&mut self) -> Result<(), Val> {
let step_ok = match self.frame.step() {
Ok(step_ok) => step_ok,

View File

@@ -2,18 +2,14 @@ use std::rc::Rc;
use crate::vs_value::{ToVal, Val};
#[derive(Clone, Debug)]
#[derive(Clone, Debug, Default)]
pub struct VsArray {
pub elements: Vec<Val>,
pub elements: Vec<Val>, // TODO: VsArray(Vec<Val>)?
}
impl VsArray {
pub fn from(vals: Vec<Val>) -> VsArray {
return VsArray { elements: vals };
}
pub fn new() -> VsArray {
return VsArray { elements: vec![] };
VsArray { elements: vals }
}
}

View File

@@ -27,14 +27,14 @@ impl VsFunction {
new_binds.push(p);
}
return VsFunction {
VsFunction {
bytecode: self.bytecode.clone(),
is_generator: self.is_generator,
register_count: self.register_count,
parameter_count: self.parameter_count,
start: self.start,
binds: new_binds,
};
}
}
pub fn make_bytecode_frame(&self) -> BytecodeStackFrame {
@@ -51,7 +51,7 @@ impl VsFunction {
registers.push(Val::Void);
}
return BytecodeStackFrame {
BytecodeStackFrame {
decoder: BytecodeDecoder {
bytecode: self.bytecode.clone(),
pos: self.start,
@@ -63,7 +63,7 @@ impl VsFunction {
this_target: None,
return_target: None,
catch_setting: None,
};
}
}
pub fn make_frame(&self) -> StackFrame {

View File

@@ -174,7 +174,7 @@ impl ValTrait for Val {
fn typeof_(&self) -> VsType {
use Val::*;
return match self {
match self {
Void => VsType::Undefined,
Undefined => VsType::Undefined,
Null => VsType::Null,
@@ -190,13 +190,13 @@ impl ValTrait for Val {
Static(val) => val.typeof_(),
Dynamic(val) => val.typeof_(),
CopyCounter(_) => VsType::Object,
};
}
}
fn to_number(&self) -> f64 {
use Val::*;
return match self {
match self {
Void => f64::NAN,
Undefined => f64::NAN,
Null => 0_f64,
@@ -216,7 +216,7 @@ impl ValTrait for Val {
Static(val) => val.to_number(),
Dynamic(val) => val.to_number(),
CopyCounter(_) => f64::NAN,
};
}
}
fn to_index(&self) -> Option<usize> {
@@ -247,7 +247,7 @@ impl ValTrait for Val {
fn is_primitive(&self) -> bool {
use Val::*;
return match self {
match self {
Void => true,
Undefined => true,
Null => true,
@@ -263,13 +263,13 @@ impl ValTrait for Val {
Static(val) => val.is_primitive(), // TODO: false?
Dynamic(val) => val.is_primitive(),
CopyCounter(_) => false,
};
}
}
fn is_truthy(&self) -> bool {
use Val::*;
return match self {
match self {
Void => false,
Undefined => false,
Null => false,
@@ -285,7 +285,7 @@ impl ValTrait for Val {
Static(val) => val.is_truthy(), // TODO: true?
Dynamic(val) => val.is_truthy(),
CopyCounter(_) => true,
};
}
}
fn is_nullish(&self) -> bool {
@@ -313,49 +313,49 @@ impl ValTrait for Val {
fn bind(&self, params: Vec<Val>) -> Option<Val> {
use Val::*;
return match self {
match self {
Function(f) => Some(f.bind(params).to_val()),
Static(val) => val.bind(params),
Dynamic(val) => val.bind(params),
_ => None,
};
}
}
// TODO: &BigInt ?
fn as_bigint_data(&self) -> Option<BigInt> {
use Val::*;
return match self {
match self {
BigInt(b) => Some(b.clone()),
// TODO: Static? Others too?
Dynamic(val) => val.as_bigint_data(),
_ => None,
};
}
}
fn as_array_data(&self) -> Option<Rc<VsArray>> {
use Val::*;
return match self {
match self {
Array(a) => Some(a.clone()),
Dynamic(val) => val.as_array_data(),
_ => None,
};
}
}
fn as_class_data(&self) -> Option<Rc<VsClass>> {
use Val::*;
return match self {
match self {
Class(class) => Some(class.clone()),
Static(s) => s.as_class_data(),
Dynamic(val) => val.as_class_data(),
_ => None,
};
}
}
fn load_function(&self) -> LoadFunctionResult {
@@ -389,47 +389,46 @@ impl ValTrait for Val {
Val::Array(array) => {
let index = match key.to_index() {
None => {
return Some(match key.to_string().as_str() {
"at" => true,
"concat" => true,
"copyWithin" => true,
"entries" => true,
"every" => true,
"fill" => true,
"filter" => true,
"find" => true,
"findIndex" => true,
"flat" => true,
"flatMap" => true,
"includes" => true,
"indexOf" => true,
"join" => true,
"keys" => true,
"lastIndexOf" => true,
"length" => true,
"map" => true,
"pop" => true,
"push" => true,
"reduce" => true,
"reduceRight" => true,
"reverse" => true,
"shift" => true,
"slice" => true,
"some" => true,
"sort" => true,
"splice" => true,
"toLocaleString" => true,
"toString" => true,
"unshift" => true,
"values" => true,
_ => false,
});
return Some(matches!(
key.to_string().as_str(),
"at"
| "concat"
| "copyWithin"
| "entries"
| "every"
| "fill"
| "filter"
| "find"
| "findIndex"
| "flat"
| "flatMap"
| "includes"
| "indexOf"
| "join"
| "keys"
| "lastIndexOf"
| "length"
| "map"
| "pop"
| "push"
| "reduce"
| "reduceRight"
| "reverse"
| "shift"
| "slice"
| "some"
| "sort"
| "splice"
| "toLocaleString"
| "toString"
| "unshift"
| "values"
));
}
Some(i) => i,
};
return Some(index < array.elements.len());
Some(index < array.elements.len())
}
Val::Object(object) => match key {
Val::Symbol(symbol) => {
@@ -441,7 +440,7 @@ impl ValTrait for Val {
return proto.has(key);
}
return Some(false);
Some(false)
}
_ => {
if object.string_map.contains_key(&key.to_string()) {
@@ -452,17 +451,14 @@ impl ValTrait for Val {
return proto.has(key);
}
return Some(false);
Some(false)
}
},
Val::Function(_) => Some(false),
Val::Class(class) => class.static_.has(key),
Val::Static(static_) => static_.has(key),
Val::Dynamic(dynamic) => dynamic.has(key),
Val::CopyCounter(_) => Some(match key.to_string().as_str() {
"tag" | "count" => true,
_ => false,
}),
Val::CopyCounter(_) => Some(matches!(key.to_string().as_str(), "tag" | "count")),
}
}
@@ -485,7 +481,7 @@ impl ValTrait for Val {
Val::Symbol(s) => format!("Symbol.{}", symbol_to_name(s.clone())),
Val::String(str) => stringify_string(str),
Val::Array(vals) => {
if vals.elements.len() == 0 {
if vals.elements.is_empty() {
"[]".to_string()
} else if vals.elements.len() == 1 {
"[".to_string() + vals.elements[0].codify().as_str() + "]"
@@ -508,17 +504,14 @@ impl ValTrait for Val {
let mut res = String::new();
if let Some(proto) = &object.prototype {
match proto.sub(&"name".to_val()) {
Ok(name) => {
if name.typeof_() == VsType::String {
res += &name.to_string();
}
if let Ok(name) = proto.sub(&"name".to_val()) {
if name.typeof_() == VsType::String {
res += &name.to_string();
}
Err(_) => {}
}
}
if object.string_map.len() == 0 {
if object.string_map.is_empty() {
res += "{}";
return res;
}
@@ -580,7 +573,7 @@ impl fmt::Display for Val {
Symbol(s) => write!(f, "Symbol(Symbol.{})", symbol_to_name(s.clone())),
String(s) => s.fmt(f),
Array(vals) => {
if vals.elements.len() == 0 {
if vals.elements.is_empty() {
Ok(())
} else if vals.elements.len() == 1 {
vals.elements[0].fmt(f)
@@ -716,7 +709,7 @@ impl<'a> std::fmt::Display for PrettyVal<'a> {
Val::Symbol(_) => write!(f, "\x1b[32m{}\x1b[39m", self.val.codify()),
Val::String(_) => write!(f, "\x1b[32m{}\x1b[39m", self.val.codify()),
Val::Array(array) => {
if array.elements.len() == 0 {
if array.elements.is_empty() {
return write!(f, "[]");
}
@@ -738,17 +731,14 @@ impl<'a> std::fmt::Display for PrettyVal<'a> {
}
Val::Object(object) => {
if let Some(proto) = &object.prototype {
match proto.sub(&"name".to_val()) {
Ok(name) => {
if name.typeof_() == VsType::String {
write!(f, "{} ", name)?;
}
if let Ok(name) = proto.sub(&"name".to_val()) {
if name.typeof_() == VsType::String {
write!(f, "{} ", name)?;
}
Err(_) => {}
}
}
if object.string_map.len() == 0 {
if object.string_map.is_empty() {
return f.write_str("{}");
}
@@ -795,7 +785,7 @@ pub fn number_to_index(x: f64) -> Option<usize> {
return None;
}
return Some(x as usize);
Some(x as usize)
}
fn stringify_string(str: &str) -> String {