Skip to content

Commit

Permalink
Implement instanceof
Browse files Browse the repository at this point in the history
  • Loading branch information
voltrevo committed Jul 27, 2023
1 parent f6546ab commit 9c21f0e
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 2 deletions.
17 changes: 17 additions & 0 deletions inputs/failing/instanceof.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
//! test_output([true,false,true])

export default () => {
return [
new X() instanceof X,
new X() instanceof Y,
new Error("") instanceof Error,
];
};

class X {
x() {}
}

class Y {
y() {}
}
25 changes: 23 additions & 2 deletions valuescript_vm/src/operations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -318,6 +318,10 @@ pub fn op_triple_eq_impl(left: &Val, right: &Val) -> Result<bool, Val> {

left.hash == right.hash
}
#[allow(clippy::vtable_address_comparisons)] // TODO: Is this ok?
(Val::Static(left), Val::Static(right)) => std::ptr::eq(&**left, &**right),
#[allow(clippy::vtable_address_comparisons)] // TODO: Is this ok?
(Val::Dynamic(left), Val::Dynamic(right)) => std::ptr::eq(&**left, &**right),
(Val::Static(..) | Val::Dynamic(..) | Val::CopyCounter(..), _)
| (_, Val::Static(..) | Val::Dynamic(..) | Val::CopyCounter(..)) => {
if left.typeof_() != right.typeof_() {
Expand Down Expand Up @@ -551,8 +555,25 @@ pub fn op_typeof(input: &Val) -> Val {
.to_val()
}

pub fn op_instance_of(_left: &Val, _right: &Val) -> Result<Val, Val> {
Err("TODO: op_instance_of".to_internal_error())
pub fn op_instance_of(left: &Val, right: &Val) -> Result<Val, Val> {
let class_data = match right.as_class_data() {
Some(class_data) => class_data,
None => return Err("Right-hand side of `instanceof` is not a class".to_type_error()),
};

let left_prototype = match left {
Val::Object(obj) => match &obj.prototype {
Some(proto) => proto,
None => return Ok(false.to_val()),
},
Val::Null => return Ok(false.to_val()),
_ => match left.typeof_() {
VsType::Object => return Err("TODO: instanceof indirection".to_internal_error()),
_ => return Ok(false.to_val()),
},
};

Ok(op_triple_eq_impl(left_prototype, &class_data.prototype)?.to_val())
}

pub fn op_in(left: &Val, right: &Val) -> Result<Val, Val> {
Expand Down

0 comments on commit 9c21f0e

Please sign in to comment.