Skip to content

Commit

Permalink
js: Store value in exception
Browse files Browse the repository at this point in the history
Previously, we simply had an exception enum ("TypeError" only).
This is incorrect, as all sorts of values can be thrown.
  • Loading branch information
simonwuelker committed Mar 15, 2024
1 parent 76b41b7 commit a707d84
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 10 deletions.
24 changes: 21 additions & 3 deletions crates/js/src/bytecode/exception.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,25 @@
use crate::Value;

/// <https://262.ecma-international.org/14.0/#sec-completion-record-specification-type>
pub type ThrowCompletionOr<T> = Result<T, Exception>;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Exception {
TypeError,
#[derive(Clone, Debug)]
pub struct Exception {
value: Value,
}

impl Exception {
#[must_use]
pub const fn new(value: Value) -> Self {
Self { value }
}

#[must_use]
pub fn type_error() -> Self {
// FIXME: This should be a "typeerror" object, but we don't
// really support objects yet
Self {
value: "TypeError".to_string().into(),
}
}
}
5 changes: 2 additions & 3 deletions crates/js/src/bytecode/vm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,9 +112,8 @@ impl Vm {
self.set_register(*dst, result.into());
},
Instruction::Throw { value } => {
// FIXME: Actually use the value.
_ = value;
return Err(Exception::TypeError);
let value = self.register(*value).clone();
return Err(Exception::new(value));
},
other => todo!("Implement instruction {other:?}"),
}
Expand Down
6 changes: 3 additions & 3 deletions crates/js/src/value/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -246,7 +246,7 @@ impl Value {

// 5. If Type(lnum) is not Type(rnum), throw a TypeError exception.
if lnum.type_tag() != rnum.type_tag() {
return Err(Exception::TypeError);
return Err(Exception::type_error());
}

match (lnum, rnum) {
Expand Down Expand Up @@ -292,7 +292,7 @@ impl Value {
},
Self::Symbol(_) | Self::BigInt => {
// 2. If argument is either a Symbol or a BigInt, throw a TypeError exception.
Err(Exception::TypeError)
Err(Exception::type_error())
},
Self::Undefined => {
// 3. If argument is undefined, return NaN.
Expand Down Expand Up @@ -369,7 +369,7 @@ impl Value {
},
Self::Symbol(_) => {
// 2. If argument is a Symbol, throw a TypeError exception.
Err(Exception::TypeError)
Err(Exception::type_error())
},
Self::Undefined => {
// 3. If argument is undefined, return "undefined".
Expand Down
2 changes: 1 addition & 1 deletion crates/js/src/value/object/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ impl Object {

// 2. If success is false, throw a TypeError exception.
if !success {
return Err(Exception::TypeError);
return Err(Exception::type_error());
}

// 3. Return unused.
Expand Down

0 comments on commit a707d84

Please sign in to comment.