diff --git a/Cargo.toml b/Cargo.toml index 595e3f1b599..ffd1ee0cba3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -20,8 +20,8 @@ members = [ exclude = [ "tests/fuzz", # Does weird things on Windows tests - "tests/src", # Just a hack to have fuzz inside tests - "tests/wpt", # Should not run WPT by default. + "tests/src", # Just a hack to have fuzz inside tests + "tests/wpt", # Should not run WPT by default. ] [workspace.package] @@ -78,7 +78,9 @@ oneshot = "0.2.1" phf = { version = "0.14.0", default-features = false } regex = "1.13.2" regress = { version = "0.12.0", features = ["utf16"] } -reqwest = { version = "0.13.5", default-features = false, features = ["rustls-no-provider"] } +reqwest = { version = "0.13.5", default-features = false, features = [ + "rustls-no-provider", +] } rustls = { version = "0.23.46", default-features = false, features = ["ring"] } rustc-hash = { version = "2.1.3", default-features = false } serde_json = "1.0.154" @@ -130,7 +132,9 @@ cfg-if = "1.0.5" either = "1.19.0" sys-locale = "0.3.2" timezone_provider = { version = "0.2.6" } -temporal_rs = { version = "0.2.6", default-features = false, features = ["float64_representable_durations"] } +temporal_rs = { version = "0.2.6", default-features = false, features = [ + "float64_representable_durations", +] } web-time = "1.1.0" criterion = "0.8.2" float-cmp = "0.10.0" diff --git a/cli/Cargo.toml b/cli/Cargo.toml index 2c466c9995d..bc57d38b264 100644 --- a/cli/Cargo.toml +++ b/cli/Cargo.toml @@ -12,7 +12,14 @@ repository.workspace = true rust-version.workspace = true [dependencies] -boa_engine = { workspace = true, features = ["deser", "float16", "flowgraph", "temporal", "trace", "xsum"] } +boa_engine = { workspace = true, features = [ + "deser", + "float16", + "flowgraph", + "temporal", + "trace", + "xsum", +] } boa_parser.workspace = true boa_gc.workspace = true boa_runtime = { workspace = true, features = ["test262"] } diff --git a/core/engine/Cargo.toml b/core/engine/Cargo.toml index 207486a7478..0ebc6373248 100644 --- a/core/engine/Cargo.toml +++ b/core/engine/Cargo.toml @@ -71,7 +71,12 @@ trace = ["js"] annex-b = ["boa_ast/annex-b", "boa_parser/annex-b"] # Enable Boa's Temporal proposal implementation -temporal = ["dep:icu_calendar", "dep:temporal_rs", "dep:timezone_provider", "timezone_provider/experimental_tzif"] +temporal = [ + "dep:icu_calendar", + "dep:temporal_rs", + "dep:timezone_provider", + "timezone_provider/experimental_tzif", +] #Enable access to host system timezone system-time-zone = ["dep:iana-time-zone"] @@ -122,7 +127,9 @@ thiserror.workspace = true dashmap.workspace = true num_enum.workspace = true thin-vec.workspace = true -itertools = { workspace = true, default-features = false, features = ["use_alloc"] } +itertools = { workspace = true, default-features = false, features = [ + "use_alloc", +] } icu_normalizer = { workspace = true, features = [ "compiled_data", "utf16_iter", @@ -153,7 +160,7 @@ icu_locale = { workspace = true, default-features = false, features = [ ], optional = true } icu_datetime = { workspace = true, default-features = false, features = [ "serde", - "unstable" + "unstable", ], optional = true } icu_time = { workspace = true, default-features = false, features = [ "serde", @@ -178,14 +185,13 @@ icu_segmenter = { workspace = true, default-features = false, features = [ "serde", ], optional = true } icu_decimal = { workspace = true, default-features = false, features = [ - "serde", "unstable" + "serde", + "unstable", ], optional = true } writeable = { workspace = true, optional = true } yoke = { workspace = true, optional = true } zerofrom = { workspace = true, optional = true } -fixed_decimal = { workspace = true, features = [ - "ryu", -], optional = true } +fixed_decimal = { workspace = true, features = ["ryu"], optional = true } tinystr = { workspace = true, optional = true } # temporal deps diff --git a/core/engine/src/builtins/array/mod.rs b/core/engine/src/builtins/array/mod.rs index 8c1264451aa..c7aab5a1074 100644 --- a/core/engine/src/builtins/array/mod.rs +++ b/core/engine/src/builtins/array/mod.rs @@ -75,6 +75,13 @@ impl JsData for Array { fn internal_methods(&self) -> &'static InternalObjectMethods { &ARRAY_EXOTIC_INTERNAL_METHODS } + + fn type_name() -> &'static str + where + Self: Sized, + { + "Array" + } } impl IntrinsicObject for Array { diff --git a/core/engine/src/builtins/array_buffer/mod.rs b/core/engine/src/builtins/array_buffer/mod.rs index 5b8c5a1bfa5..78aac07b911 100644 --- a/core/engine/src/builtins/array_buffer/mod.rs +++ b/core/engine/src/builtins/array_buffer/mod.rs @@ -496,19 +496,12 @@ impl ArrayBuffer { // 1. Let O be the this value. // 2. Perform ? RequireInternalSlot(O, [[ArrayBufferData]]). // 3. If IsSharedArrayBuffer(O) is true, throw a TypeError exception. - let object = this.as_object(); - let buf = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ() - .with_message("get ArrayBuffer.prototype.byteLength called with invalid `this`") - })?; + let buf = this.require_internal_slot::()?; // 4. If IsDetachedBuffer(O) is true, return +0𝔽. // 5. Let length be O.[[ArrayBufferByteLength]]. // 6. Return 𝔽(length). - Ok(buf.len().into()) + Ok(buf.borrow().data().len().into()) } /// [`get ArrayBuffer.prototype.maxByteLength`][spec]. @@ -522,18 +515,12 @@ impl ArrayBuffer { // 1. Let O be the this value. // 2. Perform ? RequireInternalSlot(O, [[ArrayBufferData]]). // 3. If IsSharedArrayBuffer(O) is true, throw a TypeError exception. - let object = this.as_object(); - let buf = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message( - "get ArrayBuffer.prototype.maxByteLength called with invalid `this`", - ) - })?; + let buf = this.require_internal_slot::()?; // 4. If IsDetachedBuffer(O) is true, return +0𝔽. - let Some(data) = buf.bytes() else { + let buf_data = buf.borrow(); + let buf_data = buf_data.data(); + let Some(data) = buf_data.bytes() else { return Ok(JsValue::from(0)); }; @@ -542,7 +529,7 @@ impl ArrayBuffer { // 6. Else, // a. Let length be O.[[ArrayBufferMaxByteLength]]. // 7. Return 𝔽(length). - Ok(buf.max_byte_len.unwrap_or(data.len() as u64).into()) + Ok(buf_data.max_byte_len.unwrap_or(data.len() as u64).into()) } /// [`get ArrayBuffer.prototype.resizable`][spec]. @@ -556,17 +543,10 @@ impl ArrayBuffer { // 1. Let O be the this value. // 2. Perform ? RequireInternalSlot(O, [[ArrayBufferData]]). // 3. If IsSharedArrayBuffer(O) is true, throw a TypeError exception. - let object = this.as_object(); - let buf = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ() - .with_message("get ArrayBuffer.prototype.resizable called with invalid `this`") - })?; + let buf = this.require_internal_slot::()?; // 4. If IsFixedLengthArrayBuffer(O) is false, return true; otherwise return false. - Ok(JsValue::from(!buf.is_fixed_len())) + Ok(JsValue::from(!buf.borrow().data().is_fixed_len())) } /// [`get ArrayBuffer.prototype.detached`][spec]. @@ -581,17 +561,10 @@ impl ArrayBuffer { // 1. Let O be the this value. // 2. Perform ? RequireInternalSlot(O, [[ArrayBufferData]]). // 3. If IsSharedArrayBuffer(O) is true, throw a TypeError exception. - let object = this.as_object(); - let buf = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ() - .with_message("get ArrayBuffer.prototype.detached called with invalid `this`") - })?; + let buf = this.require_internal_slot::()?; // 4. Return IsDetachedBuffer(O). - Ok(buf.is_detached().into()) + Ok(buf.borrow().data().is_detached().into()) } /// [`ArrayBuffer.prototype.resize ( newLength )`][spec]. @@ -605,13 +578,7 @@ impl ArrayBuffer { // 1. Let O be the this value. // 2. Perform ? RequireInternalSlot(O, [[ArrayBufferMaxByteLength]]). // 3. If IsSharedArrayBuffer(O) is true, throw a TypeError exception. - let buf = this - .as_object() - .and_then(|o| o.clone().downcast::().ok()) - .ok_or_else(|| { - JsNativeError::typ() - .with_message("ArrayBuffer.prototype.resize called with invalid `this`") - })?; + let buf = this.require_internal_slot::()?; // 4. Let newByteLength be ? ToIndex(newLength). let new_byte_length = args.get_or_undefined(0).to_index(context)?; @@ -649,13 +616,7 @@ impl ArrayBuffer { // 1. Let O be the this value. // 2. Perform ? RequireInternalSlot(O, [[ArrayBufferData]]). // 3. If IsSharedArrayBuffer(O) is true, throw a TypeError exception. - let buf = this - .as_object() - .and_then(|o| o.clone().downcast::().ok()) - .ok_or_else(|| { - JsNativeError::typ() - .with_message("ArrayBuffer.slice called with invalid `this` value") - })?; + let buf = this.require_internal_slot::()?; let len = { let buf = buf.borrow(); @@ -695,11 +656,7 @@ impl ArrayBuffer { // 17. Perform ? RequireInternalSlot(new, [[ArrayBufferData]]). // 18. If IsSharedArrayBuffer(new) is true, throw a TypeError exception. - let Ok(new) = new.downcast::() else { - return Err(JsNativeError::typ() - .with_message("ArrayBuffer constructor returned invalid object") - .into()); - }; + let new = new.require_internal_slot::()?; // 20. If SameValue(new, O) is true, throw a TypeError exception. if JsObject::equals(&buf, &new) { @@ -766,16 +723,7 @@ impl ArrayBuffer { // 1. Perform ? RequireInternalSlot(arrayBuffer, [[ArrayBufferData]]). // 2. If IsSharedArrayBuffer(arrayBuffer) is true, throw a TypeError exception. - let buf = this - .as_object() - .and_then(|o| o.clone().downcast::().ok()) - .ok_or_else(|| { - JsNativeError::typ().with_message(if TO_FIXED_LENGTH { - "ArrayBuffer.prototype.transferToFixedLength called with invalid `this`" - } else { - "ArrayBuffer.prototype.transfer called with invalid `this`" - }) - })?; + let buf = this.require_internal_slot::()?; // 3. If newLength is undefined, then let new_len = if new_length.is_undefined() { diff --git a/core/engine/src/builtins/array_buffer/shared.rs b/core/engine/src/builtins/array_buffer/shared.rs index 5c4b30b8482..9d5da541fb0 100644 --- a/core/engine/src/builtins/array_buffer/shared.rs +++ b/core/engine/src/builtins/array_buffer/shared.rs @@ -225,17 +225,10 @@ impl SharedArrayBuffer { // 1. Let O be the this value. // 2. Perform ? RequireInternalSlot(O, [[ArrayBufferData]]). // 3. If IsSharedArrayBuffer(O) is true, throw a TypeError exception. - let object = this.as_object(); - let buf = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ() - .with_message("SharedArrayBuffer.byteLength called with invalid value") - })?; + let buf = this.require_internal_slot::()?; // 4. Let length be ArrayBufferByteLength(O, seq-cst). - let len = buf.bytes(Ordering::SeqCst).len() as u64; + let len = buf.borrow().data().bytes(Ordering::SeqCst).len() as u64; // 5. Return 𝔽(length). Ok(len.into()) @@ -252,17 +245,10 @@ impl SharedArrayBuffer { // 1. Let O be the this value. // 2. Perform ? RequireInternalSlot(O, [[ArrayBufferData]]). // 3. If IsSharedArrayBuffer(O) is false, throw a TypeError exception. - let object = this.as_object(); - let buf = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ() - .with_message("get SharedArrayBuffer.growable called with invalid `this`") - })?; + let buf = this.require_internal_slot::()?; // 4. If IsFixedLengthArrayBuffer(O) is false, return true; otherwise return false. - Ok(JsValue::from(!buf.is_fixed_len())) + Ok(JsValue::from(!buf.borrow().data().is_fixed_len())) } /// [`get SharedArrayBuffer.prototype.maxByteLength`][spec]. @@ -276,21 +262,14 @@ impl SharedArrayBuffer { // 1. Let O be the this value. // 2. Perform ? RequireInternalSlot(O, [[ArrayBufferData]]). // 3. If IsSharedArrayBuffer(O) is false, throw a TypeError exception. - let object = this.as_object(); - let buf = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ() - .with_message("get SharedArrayBuffer.maxByteLength called with invalid value") - })?; + let buf = this.require_internal_slot::()?; // 4. If IsFixedLengthArrayBuffer(O) is true, then // a. Let length be O.[[ArrayBufferByteLength]]. // 5. Else, // a. Let length be O.[[ArrayBufferMaxByteLength]]. // 6. Return 𝔽(length). - Ok(buf.data.buffer.len().into()) + Ok(buf.borrow().data().data.buffer.len().into()) } /// [`SharedArrayBuffer.prototype.grow ( newLength )`][spec]. @@ -303,14 +282,7 @@ impl SharedArrayBuffer { ) -> JsResult { // 1. Let O be the this value. // 3. If IsSharedArrayBuffer(O) is false, throw a TypeError exception. - let Some(buf) = this - .as_object() - .and_then(|o| o.clone().downcast::().ok()) - else { - return Err(JsNativeError::typ() - .with_message("SharedArrayBuffer.grow called with non-object value") - .into()); - }; + let buf = this.require_internal_slot::()?; // 2. Perform ? RequireInternalSlot(O, [[ArrayBufferMaxByteLength]]). if buf.borrow().data().is_fixed_len() { @@ -398,13 +370,7 @@ impl SharedArrayBuffer { // 1. Let O be the this value. // 2. Perform ? RequireInternalSlot(O, [[ArrayBufferData]]). // 3. If IsSharedArrayBuffer(O) is false, throw a TypeError exception. - let buf = this - .as_object() - .and_then(|o| o.clone().downcast::().ok()) - .ok_or_else(|| { - JsNativeError::typ() - .with_message("SharedArrayBuffer.slice called with invalid `this` value") - })?; + let buf = this.require_internal_slot::()?; // 4. Let len be ArrayBufferByteLength(O, seq-cst). let len = buf.borrow().data().len(Ordering::SeqCst); diff --git a/core/engine/src/builtins/async_generator/mod.rs b/core/engine/src/builtins/async_generator/mod.rs index c3d99c3187b..86dad4f950a 100644 --- a/core/engine/src/builtins/async_generator/mod.rs +++ b/core/engine/src/builtins/async_generator/mod.rs @@ -136,11 +136,7 @@ impl AsyncGenerator { .into() }); let generator = if_abrupt_reject_promise!(result, promise_capability, context); - let result: JsResult<_> = generator.clone().downcast::().map_err(|_| { - JsNativeError::typ() - .with_message("generator resumed on non generator object") - .into() - }); + let result: JsResult<_> = generator.require_internal_slot::(); let generator = if_abrupt_reject_promise!(result, promise_capability, context); Self::inner_next( @@ -221,11 +217,7 @@ impl AsyncGenerator { .into() }); let generator_object = if_abrupt_reject_promise!(result, promise_capability, context); - let result: JsResult<_> = generator_object.clone().downcast::().map_err(|_| { - JsNativeError::typ() - .with_message("generator resumed on non generator object") - .into() - }); + let result: JsResult<_> = generator_object.require_internal_slot::(); let generator = if_abrupt_reject_promise!(result, promise_capability, context); Self::inner_return( @@ -301,11 +293,7 @@ impl AsyncGenerator { .into() }); let generator_object = if_abrupt_reject_promise!(result, promise_capability, context); - let result: JsResult<_> = generator_object.clone().downcast::().map_err(|_| { - JsNativeError::typ() - .with_message("generator resumed on non generator object") - .into() - }); + let result: JsResult<_> = generator_object.require_internal_slot::(); let generator = if_abrupt_reject_promise!(result, promise_capability, context); Self::inner_throw( &generator, diff --git a/core/engine/src/builtins/dataview/mod.rs b/core/engine/src/builtins/dataview/mod.rs index 36b2de954ab..d6e0f270ee4 100644 --- a/core/engine/src/builtins/dataview/mod.rs +++ b/core/engine/src/builtins/dataview/mod.rs @@ -331,14 +331,11 @@ impl DataView { ) -> JsResult { // 1. Let O be the this value. // 2. Perform ? RequireInternalSlot(O, [[DataView]]). - let object = this.as_object(); - let view = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| JsNativeError::typ().with_message("`this` is not a DataView"))?; + let view = this.require_internal_slot::()?; // 3. Assert: O has a [[ViewedArrayBuffer]] internal slot. // 4. Let buffer be O.[[ViewedArrayBuffer]]. - let buffer = view.viewed_array_buffer.clone(); + let view_data = view.borrow(); + let buffer = view_data.data().viewed_array_buffer.clone(); // 5. Return buffer. Ok(buffer.into()) } @@ -361,18 +358,15 @@ impl DataView { // 1. Let O be the this value. // 2. Perform ? RequireInternalSlot(O, [[DataView]]). // 3. Assert: O has a [[ViewedArrayBuffer]] internal slot. - let object = this.as_object(); - let view = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| JsNativeError::typ().with_message("`this` is not a DataView"))?; + let view = this.require_internal_slot::()?; // 4. Let viewRecord be MakeDataViewWithBufferWitnessRecord(O, seq-cst). // 5. If IsViewOutOfBounds(viewRecord) is true, throw a TypeError exception. - let buffer = view.viewed_array_buffer.as_buffer(); + let view_data = view.borrow(); + let buffer = view_data.data().viewed_array_buffer.as_buffer(); let Some(slice) = buffer .bytes(Ordering::SeqCst) - .filter(|s| !view.is_out_of_bounds(s.len())) + .filter(|s| !view.borrow().data().is_out_of_bounds(s.len())) else { return Err(JsNativeError::typ() .with_message("view out of bounds for its inner buffer") @@ -380,7 +374,8 @@ impl DataView { }; // 6. Let size be GetViewByteLength(viewRecord). - let size = view.byte_length(slice.len()); + let view_data = view.borrow(); + let size = view_data.data().byte_length(slice.len()); // 7. Return 𝔽(size). Ok(size.into()) @@ -404,20 +399,17 @@ impl DataView { ) -> JsResult { // 1. Let O be the this value. // 2. Perform ? RequireInternalSlot(O, [[DataView]]). - let object = this.as_object(); - let view = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| JsNativeError::typ().with_message("`this` is not a DataView"))?; + let view = this.require_internal_slot::()?; // 3. Assert: O has a [[ViewedArrayBuffer]] internal slot. - let buffer = view.viewed_array_buffer.as_buffer(); + let view_data = view.borrow(); + let buffer = view_data.data().viewed_array_buffer.as_buffer(); // 4. Let viewRecord be MakeDataViewWithBufferWitnessRecord(O, seq-cst). // 5. If IsViewOutOfBounds(viewRecord) is true, throw a TypeError exception. if buffer .bytes(Ordering::SeqCst) .as_ref() - .is_none_or(|b| view.is_out_of_bounds(b.len())) + .is_none_or(|b| view.borrow().data().is_out_of_bounds(b.len())) { return Err(JsNativeError::typ() .with_message("data view is outside the bounds of its inner buffer") @@ -425,7 +417,8 @@ impl DataView { } // 6. Let offset be O.[[ByteOffset]]. - let offset = view.byte_offset; + let view_data = view.borrow(); + let offset = view_data.data().byte_offset; // 7. Return 𝔽(offset). Ok(offset.into()) } @@ -448,11 +441,7 @@ impl DataView { ) -> JsResult { // 1. Perform ? RequireInternalSlot(view, [[DataView]]). // 2. Assert: view has a [[ViewedArrayBuffer]] internal slot. - let object = view.as_object(); - let view = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| JsNativeError::typ().with_message("`this` is not a DataView"))?; + let view = view.require_internal_slot::()?; // 3. Let getIndex be ? ToIndex(requestIndex). let get_index = request_index.to_index(context)?; @@ -463,10 +452,11 @@ impl DataView { // 6. Let viewRecord be MakeDataViewWithBufferWitnessRecord(view, unordered). // 7. NOTE: Bounds checking is not a synchronizing operation when view's backing buffer is a growable SharedArrayBuffer. // 8. If IsViewOutOfBounds(viewRecord) is true, throw a TypeError exception. - let buffer = view.viewed_array_buffer.as_buffer(); + let view_data = view.borrow(); + let buffer = view_data.data().viewed_array_buffer.as_buffer(); let Some(data) = buffer .bytes(Ordering::Relaxed) - .filter(|buf| !view.is_out_of_bounds(buf.len())) + .filter(|buf| !view.borrow().data().is_out_of_bounds(buf.len())) else { return Err(JsNativeError::typ() .with_message("view out of bounds for its inner buffer") @@ -474,10 +464,12 @@ impl DataView { }; // 5. Let viewOffset be view.[[ByteOffset]]. - let view_offset = view.byte_offset; + let view_data = view.borrow(); + let view_offset = view_data.data().byte_offset; // 9. Let viewSize be GetViewByteLength(viewRecord). - let view_size = view.byte_length(data.len()); + let view_data = view.borrow(); + let view_size = view_data.data().byte_length(data.len()); // 10. Let elementSize be the Element Size value specified in Table 71 for Element Type type. let element_size = size_of::() as u64; @@ -790,11 +782,7 @@ impl DataView { ) -> JsResult { // 1. Perform ? RequireInternalSlot(view, [[DataView]]). // 2. Assert: view has a [[ViewedArrayBuffer]] internal slot. - let object = view.as_object(); - let view = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| JsNativeError::typ().with_message("`this` is not a DataView"))?; + let view = view.require_internal_slot::()?; // 3. Let getIndex be ? ToIndex(requestIndex). let get_index = request_index.to_index(context)?; @@ -809,11 +797,15 @@ impl DataView { // 8. Let viewRecord be MakeDataViewWithBufferWitnessRecord(view, unordered). // 9. NOTE: Bounds checking is not a synchronizing operation when view's backing buffer is a growable SharedArrayBuffer. // 10. If IsViewOutOfBounds(viewRecord) is true, throw a TypeError exception. - let mut buffer = view.viewed_array_buffer.as_buffer_mut(); + let viewed_buffer = { + let view_data = view.borrow(); + view_data.data().viewed_array_buffer.clone() + }; + let mut buffer = viewed_buffer.as_buffer_mut(); let Some(mut data) = buffer .bytes(Ordering::Relaxed) - .filter(|buf| !view.is_out_of_bounds(buf.len())) + .filter(|buf| !view.borrow().data().is_out_of_bounds(buf.len())) else { return Err(JsNativeError::typ() .with_message("view out of bounds for its inner buffer") @@ -821,10 +813,12 @@ impl DataView { }; // 11. Let viewSize be GetViewByteLength(viewRecord). - let view_size = view.byte_length(data.len()); + let view_data = view.borrow(); + let view_size = view_data.data().byte_length(data.len()); // 7. Let viewOffset be view.[[ByteOffset]]. - let view_offset = view.byte_offset; + let view_data = view.borrow(); + let view_offset = view_data.data().byte_offset; // 12. Let elementSize be the Element Size value specified in Table 71 for Element Type type. let elem_size = size_of::(); diff --git a/core/engine/src/builtins/date/mod.rs b/core/engine/src/builtins/date/mod.rs index 05e28775e1b..2815d008850 100644 --- a/core/engine/src/builtins/date/mod.rs +++ b/core/engine/src/builtins/date/mod.rs @@ -451,11 +451,8 @@ impl Date { // 1. Let dateObject be the this value. // 2. Perform ? RequireInternalSlot(dateObject, [[DateValue]]). // 3. Let t be dateObject.[[DateValue]]. - let t = this - .as_object() - .and_then(|obj| obj.downcast_ref::().as_deref().copied()) - .ok_or_else(|| JsNativeError::typ().with_message("'this' is not a Date"))? - .0; + let date = this.require_internal_slot::()?; + let t = date.borrow().data().0; // 4. If t is NaN, return NaN. if t.is_nan() { @@ -490,11 +487,8 @@ impl Date { // 1. Let dateObject be the this value. // 2. Perform ? RequireInternalSlot(dateObject, [[DateValue]]). // 3. Let t be dateObject.[[DateValue]]. - let t = this - .as_object() - .and_then(|obj| obj.downcast_ref::().as_deref().copied()) - .ok_or_else(|| JsNativeError::typ().with_message("'this' is not a Date"))? - .0; + let date = this.require_internal_slot::()?; + let t = date.borrow().data().0; // 4. If t is NaN, return NaN. if t.is_nan() { @@ -532,11 +526,8 @@ impl Date { // 1. Let dateObject be the this value. // 2. Perform ? RequireInternalSlot(dateObject, [[DateValue]]). // 3. Let t be dateObject.[[DateValue]]. - let t = this - .as_object() - .and_then(|obj| obj.downcast_ref::().as_deref().copied()) - .ok_or_else(|| JsNativeError::typ().with_message("'this' is not a Date"))? - .0; + let date = this.require_internal_slot::()?; + let t = date.borrow().data().0; // 4. If t is NaN, return NaN. if t.is_nan() { @@ -564,11 +555,8 @@ impl Date { // 1. Let dateObject be the this value. // 2. Perform ? RequireInternalSlot(dateObject, [[DateValue]]). // 3. Let t be dateObject.[[DateValue]]. - let t = this - .as_object() - .and_then(|obj| obj.downcast_ref::().as_deref().copied()) - .ok_or_else(|| JsNativeError::typ().with_message("'this' is not a Date"))? - .0; + let date = this.require_internal_slot::()?; + let t = date.borrow().data().0; // 4. If t is NaN, return NaN. if t.is_nan() { @@ -602,11 +590,8 @@ impl Date { // 1. Let dateObject be the this value. // 2. Perform ? RequireInternalSlot(dateObject, [[DateValue]]). // 3. Let t be dateObject.[[DateValue]]. - let t = this - .as_object() - .and_then(|obj| obj.downcast_ref::().as_deref().copied()) - .ok_or_else(|| JsNativeError::typ().with_message("'this' is not a Date"))? - .0; + let date = this.require_internal_slot::()?; + let t = date.borrow().data().0; // 4. If t is NaN, return NaN. if t.is_nan() { @@ -640,11 +625,8 @@ impl Date { // 1. Let dateObject be the this value. // 2. Perform ? RequireInternalSlot(dateObject, [[DateValue]]). // 3. Let t be dateObject.[[DateValue]]. - let t = this - .as_object() - .and_then(|obj| obj.downcast_ref::().as_deref().copied()) - .ok_or_else(|| JsNativeError::typ().with_message("'this' is not a Date"))? - .0; + let date = this.require_internal_slot::()?; + let t = date.borrow().data().0; // 4. If t is NaN, return NaN. if t.is_nan() { @@ -678,11 +660,8 @@ impl Date { // 1. Let dateObject be the this value. // 2. Perform ? RequireInternalSlot(dateObject, [[DateValue]]). // 3. Let t be dateObject.[[DateValue]]. - let t = this - .as_object() - .and_then(|obj| obj.downcast_ref::().as_deref().copied()) - .ok_or_else(|| JsNativeError::typ().with_message("'this' is not a Date"))? - .0; + let date = this.require_internal_slot::()?; + let t = date.borrow().data().0; // 4. If t is NaN, return NaN. if t.is_nan() { @@ -717,11 +696,8 @@ impl Date { // 1. Let dateObject be the this value. // 2. Perform ? RequireInternalSlot(dateObject, [[DateValue]]). // 3. Let t be dateObject.[[DateValue]]. - let t = this - .as_object() - .and_then(|obj| obj.downcast_ref::().as_deref().copied()) - .ok_or_else(|| JsNativeError::typ().with_message("'this' is not a Date"))? - .0; + let date = this.require_internal_slot::()?; + let t = date.borrow().data().0; // 4. If t is NaN, return NaN. if t.is_nan() { @@ -755,11 +731,8 @@ impl Date { // 1. Let dateObject be the this value. // 2. Perform ? RequireInternalSlot(dateObject, [[DateValue]]). // 3. Let t be dateObject.[[DateValue]]. - let t = this - .as_object() - .and_then(|obj| obj.downcast_ref::().as_deref().copied()) - .ok_or_else(|| JsNativeError::typ().with_message("'this' is not a Date"))? - .0; + let date = this.require_internal_slot::()?; + let t = date.borrow().data().0; // 4. If t is NaN, return NaN. if t.is_nan() { @@ -796,12 +769,8 @@ impl Date { // 1. Let dateObject be the this value. // 2. Perform ? RequireInternalSlot(dateObject, [[DateValue]]). // 3. Return dateObject.[[DateValue]]. - Ok(this - .as_object() - .and_then(|obj| obj.downcast_ref::().as_deref().copied()) - .ok_or_else(|| JsNativeError::typ().with_message("'this' is not a Date"))? - .0 - .into()) + let date = this.require_internal_slot::()?; + Ok(date.borrow().data().0.into()) } /// `Date.prototype.getTimeZoneOffset()`. @@ -823,11 +792,8 @@ impl Date { // 1. Let dateObject be the this value. // 2. Perform ? RequireInternalSlot(dateObject, [[DateValue]]). // 3. Let t be dateObject.[[DateValue]]. - let t = this - .as_object() - .and_then(|obj| obj.downcast_ref::().as_deref().copied()) - .ok_or_else(|| JsNativeError::typ().with_message("'this' is not a Date"))? - .0; + let date = this.require_internal_slot::()?; + let t = date.borrow().data().0; // 4. If t is NaN, return NaN. if t.is_nan() { @@ -855,13 +821,10 @@ impl Date { ) -> JsResult { // 1. Let dateObject be the this value. // 2. Perform ? RequireInternalSlot(dateObject, [[DateValue]]). - let object = this.as_object(); - let date = object - .and_then(|o| o.downcast::().ok()) - .ok_or_else(|| JsNativeError::typ().with_message("'this' is not a Date"))?; + let date_obj = this.require_internal_slot::()?; // 3. Let t be dateObject.[[DateValue]]. - let mut t = date.borrow().data().0; + let mut t = date_obj.borrow().data().0; // 4. Let dt be ? ToNumber(date). let dt = args.get_or_undefined(0).to_number(context)?; @@ -891,7 +854,7 @@ impl Date { }; // 9. Set dateObject.[[DateValue]] to u. - date.borrow_mut().data_mut().0 = u; + date_obj.borrow_mut().data_mut().0 = u; // 10. Return u. Ok(JsValue::from(u)) @@ -912,14 +875,10 @@ impl Date { ) -> JsResult { // 1. Let dateObject be the this value. // 2. Perform ? RequireInternalSlot(dateObject, [[DateValue]]). - let object = this.as_object(); - - let date = object - .and_then(|o| o.downcast::().ok()) - .ok_or_else(|| JsNativeError::typ().with_message("'this' is not a Date"))?; + let date_obj = this.require_internal_slot::()?; // 3. Let t be dateObject.[[DateValue]]. - let t = date.borrow().data().0; + let t = date_obj.borrow().data().0; let t = if LOCAL { // 5. If t is NaN, set t to +0𝔽; otherwise, set t to LocalTime(t). @@ -962,7 +921,7 @@ impl Date { }; // 10. Set dateObject.[[DateValue]] to u. - date.borrow_mut().data_mut().0 = u; + date_obj.borrow_mut().data_mut().0 = u; // 11. Return u. Ok(JsValue::from(u)) @@ -985,13 +944,10 @@ impl Date { ) -> JsResult { // 1. Let dateObject be the this value. // 2. Perform ? RequireInternalSlot(dateObject, [[DateValue]]). - let object = this.as_object(); - let date = object - .and_then(|o| o.downcast::().ok()) - .ok_or_else(|| JsNativeError::typ().with_message("'this' is not a Date"))?; + let date_obj = this.require_internal_slot::()?; // 3. Let t be dateObject.[[DateValue]]. - let mut t = date.borrow().data().0; + let mut t = date_obj.borrow().data().0; // 4. Let h be ? ToNumber(hour). let h = args.get_or_undefined(0).to_number(context)?; @@ -1036,7 +992,7 @@ impl Date { }; // 15. Set dateObject.[[DateValue]] to u. - date.borrow_mut().data_mut().0 = u; + date_obj.borrow_mut().data_mut().0 = u; // 16. Return u. Ok(JsValue::from(u)) @@ -1056,13 +1012,10 @@ impl Date { ) -> JsResult { // 1. Let dateObject be the this value. // 2. Perform ? RequireInternalSlot(dateObject, [[DateValue]]). - let object = this.as_object(); - let date = object - .and_then(|o| o.downcast::().ok()) - .ok_or_else(|| JsNativeError::typ().with_message("'this' is not a Date"))?; + let date_obj = this.require_internal_slot::()?; // 3. Let t be dateObject.[[DateValue]]. - let mut t = date.borrow().data().0; + let mut t = date_obj.borrow().data().0; // 4. Set ms to ? ToNumber(ms). let ms = args.get_or_undefined(0).to_number(context)?; @@ -1097,7 +1050,7 @@ impl Date { }; // 9. Set dateObject.[[DateValue]] to u. - date.borrow_mut().data_mut().0 = u; + date_obj.borrow_mut().data_mut().0 = u; // 10. Return u. Ok(JsValue::from(u)) @@ -1117,13 +1070,10 @@ impl Date { ) -> JsResult { // 1. Let dateObject be the this value. // 2. Perform ? RequireInternalSlot(dateObject, [[DateValue]]). - let object = this.as_object(); - let date = object - .and_then(|o| o.downcast::().ok()) - .ok_or_else(|| JsNativeError::typ().with_message("'this' is not a Date"))?; + let date_obj = this.require_internal_slot::()?; // 3. Let t be dateObject.[[DateValue]]. - let mut t = date.borrow().data().0; + let mut t = date_obj.borrow().data().0; // 4. Let m be ? ToNumber(min). let m = args.get_or_undefined(0).to_number(context)?; @@ -1162,7 +1112,7 @@ impl Date { }; // 13. Set dateObject.[[DateValue]] to u. - date.borrow_mut().data_mut().0 = u; + date_obj.borrow_mut().data_mut().0 = u; // 14. Return u. Ok(JsValue::from(u)) @@ -1183,13 +1133,10 @@ impl Date { ) -> JsResult { // 1. Let dateObject be the this value. // 2. Perform ? RequireInternalSlot(dateObject, [[DateValue]]). - let object = this.as_object(); - let date = object - .and_then(|o| o.downcast::().ok()) - .ok_or_else(|| JsNativeError::typ().with_message("'this' is not a Date"))?; + let date_obj = this.require_internal_slot::()?; // 3. Let t be dateObject.[[DateValue]]. - let mut t = date.borrow().data().0; + let mut t = date_obj.borrow().data().0; // 4. Let m be ? ToNumber(month). let m = args.get_or_undefined(0).to_number(context)?; @@ -1225,7 +1172,7 @@ impl Date { }; // 11. Set dateObject.[[DateValue]] to u. - date.borrow_mut().data_mut().0 = u; + date_obj.borrow_mut().data_mut().0 = u; // 12. Return u. Ok(JsValue::from(u)) @@ -1245,13 +1192,10 @@ impl Date { ) -> JsResult { // 1. Let dateObject be the this value. // 2. Perform ? RequireInternalSlot(dateObject, [[DateValue]]). - let object = this.as_object(); - let date = object - .and_then(|o| o.downcast::().ok()) - .ok_or_else(|| JsNativeError::typ().with_message("'this' is not a Date"))?; + let date_obj = this.require_internal_slot::()?; // 3. Let t be dateObject.[[DateValue]]. - let mut t = date.borrow().data().0; + let mut t = date_obj.borrow().data().0; // 4. Let s be ? ToNumber(sec). let s = args.get_or_undefined(0).to_number(context)?; @@ -1287,7 +1231,7 @@ impl Date { }; // 11. Set dateObject.[[DateValue]] to u. - date.borrow_mut().data_mut().0 = u; + date_obj.borrow_mut().data_mut().0 = u; // 12. Return u. Ok(JsValue::from(u)) @@ -1314,13 +1258,10 @@ impl Date { ) -> JsResult { // 1. Let dateObject be the this value. // 2. Perform ? RequireInternalSlot(dateObject, [[DateValue]]). - let object = this.as_object(); - let date = object - .and_then(|o| o.downcast::().ok()) - .ok_or_else(|| JsNativeError::typ().with_message("'this' is not a Date"))?; + let date_obj = this.require_internal_slot::()?; // 3. Let t be dateObject.[[DateValue]]. - let t = date.borrow().data().0; + let t = date_obj.borrow().data().0; // 4. Let y be ? ToNumber(year). let y = args.get_or_undefined(0).to_number(context)?; @@ -1345,7 +1286,7 @@ impl Date { let u = time_clip(utc_t(dt, context.host_hooks().as_ref())); // 10. Set dateObject.[[DateValue]] to u. - date.borrow_mut().data_mut().0 = u; + date_obj.borrow_mut().data_mut().0 = u; // 11. Return u. Ok(JsValue::from(u)) @@ -1368,10 +1309,7 @@ impl Date { ) -> JsResult { // 1. Let dateObject be the this value. // 2. Perform ? RequireInternalSlot(dateObject, [[DateValue]]). - let object = this.as_object(); - let date = object - .and_then(|o| o.downcast::().ok()) - .ok_or_else(|| JsNativeError::typ().with_message("'this' is not a Date"))?; + let date_obj = this.require_internal_slot::()?; // 3. Let t be ? ToNumber(time). let t = args.get_or_undefined(0).to_number(context)?; @@ -1380,7 +1318,7 @@ impl Date { let v = time_clip(t); // 5. Set dateObject.[[DateValue]] to v. - date.borrow_mut().data_mut().0 = v; + date_obj.borrow_mut().data_mut().0 = v; // 6. Return v. Ok(JsValue::from(v)) @@ -1403,11 +1341,8 @@ impl Date { // 1. Let dateObject be the this value. // 2. Perform ? RequireInternalSlot(dateObject, [[DateValue]]). // 3. Let tv be dateObject.[[DateValue]]. - let tv = this - .as_object() - .and_then(|obj| obj.downcast_ref::().as_deref().copied()) - .ok_or_else(|| JsNativeError::typ().with_message("'this' is not a Date"))? - .0; + let date = this.require_internal_slot::()?; + let tv = date.borrow().data().0; // 4. If tv is NaN, return "Invalid Date". if tv.is_nan() { @@ -1440,11 +1375,8 @@ impl Date { // 1. Let dateObject be the this value. // 2. Perform ? RequireInternalSlot(dateObject, [[DateValue]]). // 3. Let tv be dateObject.[[DateValue]]. - let tv = this - .as_object() - .and_then(|obj| obj.downcast_ref::().as_deref().copied()) - .ok_or_else(|| JsNativeError::typ().with_message("'this' is not a Date"))? - .0; + let date = this.require_internal_slot::()?; + let tv = date.borrow().data().0; // 4. If tv is not finite, throw a RangeError exception. if !tv.is_finite() { @@ -1540,11 +1472,7 @@ impl Date { // 1. Let dateObject be the this value. // 2. Perform ? RequireInternalSlot(dateObject, [[DateValue]]). // 3. Let x be dateObject.[[DateValue]]. - let x = this - .as_object() - .and_then(|obj| obj.downcast_ref::().as_deref().copied()) - .ok_or_else(|| JsNativeError::typ().with_message("'this' is not a Date"))? - .0; + let x = this.require_internal_slot::()?.borrow().data().0; // 4. If x is NaN, return "Invalid Date". if x.is_nan() { @@ -1650,11 +1578,8 @@ impl Date { // 1. Let dateObject be the this value. // 2. Perform ? RequireInternalSlot(dateObject, [[DateValue]]). // 3. Let tv be dateObject.[[DateValue]]. - let tv = this - .as_object() - .and_then(|obj| obj.downcast_ref::().as_deref().copied()) - .ok_or_else(|| JsNativeError::typ().with_message("'this' is not a Date"))? - .0; + let date = this.require_internal_slot::()?; + let tv = date.borrow().data().0; // 4. Return ToDateString(tv). Ok(JsValue::from(to_date_string_t( @@ -1681,11 +1606,8 @@ impl Date { // 1. Let dateObject be the this value. // 2. Perform ? RequireInternalSlot(dateObject, [[DateValue]]). // 3. Let tv be dateObject.[[DateValue]]. - let tv = this - .as_object() - .and_then(|obj| obj.downcast_ref::().as_deref().copied()) - .ok_or_else(|| JsNativeError::typ().with_message("'this' is not a Date"))? - .0; + let date = this.require_internal_slot::()?; + let tv = date.borrow().data().0; // 4. If tv is NaN, return "Invalid Date". if tv.is_nan() { @@ -1719,11 +1641,8 @@ impl Date { // 1. Let dateObject be the this value. // 2. Perform ? RequireInternalSlot(dateObject, [[DateValue]]). // 3. Let tv be dateObject.[[DateValue]]. - let tv = this - .as_object() - .and_then(|obj| obj.downcast_ref::().as_deref().copied()) - .ok_or_else(|| JsNativeError::typ().with_message("'this' is not a Date"))? - .0; + let date = this.require_internal_slot::()?; + let tv = date.borrow().data().0; // 4. If tv is NaN, return "Invalid Date". if tv.is_nan() { @@ -1823,12 +1742,8 @@ impl Date { // 1. Let dateObject be the this value. // 2. Perform ? RequireInternalSlot(dateObject, [[DateValue]]). // 3. Return dateObject.[[DateValue]]. - Ok(this - .as_object() - .and_then(|obj| obj.downcast_ref::().as_deref().copied()) - .ok_or_else(|| JsNativeError::typ().with_message("'this' is not a Date"))? - .0 - .into()) + let date = this.require_internal_slot::()?; + Ok(date.borrow().data().0.into()) } /// [`Date.prototype [ @@toPrimitive ] ( hint )`][spec]. @@ -1896,11 +1811,8 @@ impl Date { // 1. Let dateObject be the this value. // 2. Perform ? RequireInternalSlot(dateObject, [[DateValue]]). // 3. Let t be dateObject.[[DateValue]]. - let t = this - .as_object() - .and_then(|obj| obj.downcast_ref::().as_deref().copied()) - .ok_or_else(|| js_error!(TypeError: "'this' is not a Date"))? - .0; + let date = this.require_internal_slot::()?; + let t = date.borrow().data().0; // 4. Let ns be ? NumberToBigInt(t) × ℤ(10**6). let ns = i128::from_f64(t) diff --git a/core/engine/src/builtins/date/tests.rs b/core/engine/src/builtins/date/tests.rs index a6b6aed6d2e..a4bf681e609 100644 --- a/core/engine/src/builtins/date/tests.rs +++ b/core/engine/src/builtins/date/tests.rs @@ -103,7 +103,7 @@ fn date_this_time_value() { run_test_actions([TestAction::assert_native_error( "({toString: Date.prototype.toString}).toString()", JsNativeErrorKind::Type, - "'this' is not a Date", + "object does not contain required internal slot `Date`", )]); } @@ -952,17 +952,17 @@ fn date_proto_to_locale_string_intl() { TestAction::assert_native_error( "Date.prototype.toLocaleString.call({})", JsNativeErrorKind::Type, - "'this' is not a Date", + "object does not contain required internal slot `Date`", ), TestAction::assert_native_error( "Date.prototype.toLocaleDateString.call({})", JsNativeErrorKind::Type, - "'this' is not a Date", + "object does not contain required internal slot `Date`", ), TestAction::assert_native_error( "Date.prototype.toLocaleTimeString.call({})", JsNativeErrorKind::Type, - "'this' is not a Date", + "object does not contain required internal slot `Date`", ), TestAction::assert_eq("new Date(NaN).toLocaleString()", js_str!("Invalid Date")), TestAction::assert("typeof new Date(2020, 6, 8).toLocaleString() === 'string'"), diff --git a/core/engine/src/builtins/function/arguments.rs b/core/engine/src/builtins/function/arguments.rs index b50e97aaa64..40d785ece3a 100644 --- a/core/engine/src/builtins/function/arguments.rs +++ b/core/engine/src/builtins/function/arguments.rs @@ -100,6 +100,13 @@ impl JsData for MappedArguments { &METHODS } + + fn type_name() -> &'static str + where + Self: Sized, + { + "MappedArguments" + } } impl MappedArguments { diff --git a/core/engine/src/builtins/function/bound.rs b/core/engine/src/builtins/function/bound.rs index f0331bb209b..2876e86caac 100644 --- a/core/engine/src/builtins/function/bound.rs +++ b/core/engine/src/builtins/function/bound.rs @@ -37,6 +37,13 @@ impl JsData for BoundFunction { &FUNCTION_METHODS } } + + fn type_name() -> &'static str + where + Self: Sized, + { + "BoundFunction" + } } impl BoundFunction { diff --git a/core/engine/src/builtins/function/mod.rs b/core/engine/src/builtins/function/mod.rs index 43c01dc48a0..37e4c66fad8 100644 --- a/core/engine/src/builtins/function/mod.rs +++ b/core/engine/src/builtins/function/mod.rs @@ -206,6 +206,13 @@ impl JsData for OrdinaryFunction { &FUNCTION_METHODS } } + + fn type_name() -> &'static str + where + Self: Sized, + { + "OrdinaryFunction" + } } impl OrdinaryFunction { diff --git a/core/engine/src/builtins/intl/collator/mod.rs b/core/engine/src/builtins/intl/collator/mod.rs index 00eb1eb84ea..3014659d629 100644 --- a/core/engine/src/builtins/intl/collator/mod.rs +++ b/core/engine/src/builtins/intl/collator/mod.rs @@ -413,14 +413,7 @@ impl Collator { fn resolved_options(this: &JsValue, _: &[JsValue], context: &mut Context) -> JsResult { // 1. Let collator be the this value. // 2. Perform ? RequireInternalSlot(collator, [[InitializedCollator]]). - let object = this.as_object(); - let collator = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ() - .with_message("`resolvedOptions` can only be called on a `Collator` object") - })?; + let collator = this.require_internal_slot::()?; // 3. Let options be OrdinaryObjectCreate(%Object.prototype%). let options = context @@ -442,14 +435,14 @@ impl Collator { options .create_data_property_or_throw( js_string!("locale"), - js_string!(collator.locale.to_string()), + js_string!(collator.borrow().data().locale.to_string()), context, ) .js_expect("operation must not fail per the spec")?; options .create_data_property_or_throw( js_string!("usage"), - match collator.usage { + match collator.borrow().data().usage { Usage::Search => js_string!("search"), Usage::Sort => js_string!("sort"), }, @@ -459,7 +452,7 @@ impl Collator { options .create_data_property_or_throw( js_string!("sensitivity"), - match collator.sensitivity { + match collator.borrow().data().sensitivity { Sensitivity::Base => js_string!("base"), Sensitivity::Accent => js_string!("accent"), Sensitivity::Case => js_string!("case"), @@ -471,7 +464,7 @@ impl Collator { options .create_data_property_or_throw( js_string!("ignorePunctuation"), - collator.ignore_punctuation, + collator.borrow().data().ignore_punctuation, context, ) .js_expect("operation must not fail per the spec")?; @@ -479,16 +472,22 @@ impl Collator { .create_data_property_or_throw( js_string!("collation"), collator + .borrow() + .data() .collation - .map(|co| js_string!(co.as_str())) + .map(|co: CollationType| js_string!(co.as_str())) .unwrap_or(js_string!("default")), context, ) .js_expect("operation must not fail per the spec")?; options - .create_data_property_or_throw(js_string!("numeric"), collator.numeric, context) + .create_data_property_or_throw( + js_string!("numeric"), + collator.borrow().data().numeric, + context, + ) .js_expect("operation must not fail per the spec")?; - if let Some(kf) = collator.case_first { + if let Some(kf) = collator.borrow().data().case_first { options .create_data_property_or_throw( js_string!("caseFirst"), diff --git a/core/engine/src/builtins/intl/date_time_format/mod.rs b/core/engine/src/builtins/intl/date_time_format/mod.rs index de90a7fb999..9ab4afca455 100644 --- a/core/engine/src/builtins/intl/date_time_format/mod.rs +++ b/core/engine/src/builtins/intl/date_time_format/mod.rs @@ -313,15 +313,7 @@ impl DateTimeFormat { ) -> JsResult { // 1. Let dtf be the this value. // 2. Perform ? RequireInternalSlot(dtf, [[InitializedDateTimeFormat]]). - let dtf = this - .as_object() - .and_then(|o| o.downcast::().ok()) - .ok_or_else(|| { - js_error!( - TypeError: - "value was not an initialized `Intl.DateTimeFormat` object" - ) - })?; + let dtf = this.require_internal_slot::()?; let date = args.get_or_undefined(0); // 3. If date is undefined, then let x = if date.is_undefined() { @@ -353,15 +345,7 @@ impl DateTimeFormat { // 1. Let dtf be this value. // 2. Perform ? RequireInternalSlot(dtf, [[InitializedDateTimeFormat]]). - let dtf = this - .as_object() - .and_then(|o| o.downcast::().ok()) - .ok_or_else(|| { - js_error!( - TypeError: - "value was not an initialized `Intl.DateTimeFormat` object" - ) - })?; + let dtf = this.require_internal_slot::()?; // 3. If startDate is undefined or endDate is undefined, throw a TypeError exception. if start_date.is_undefined() { diff --git a/core/engine/src/builtins/intl/number_format/mod.rs b/core/engine/src/builtins/intl/number_format/mod.rs index fb4c8f48147..930cf035316 100644 --- a/core/engine/src/builtins/intl/number_format/mod.rs +++ b/core/engine/src/builtins/intl/number_format/mod.rs @@ -677,15 +677,8 @@ impl NumberFormat { // 1. Let nf be the this value. // 2. Perform ? RequireInternalSlot(nf, [[InitializedNumberFormat]]). - let nf = this - .as_object() - .and_then(|o| o.downcast::().ok()) - .ok_or_else(|| { - js_error!( - TypeError: - "value was not an initialized `Intl.NumberFormat` object" - ) - })?; + let nf = this.require_internal_slot::()?; + // 3. Let x be ? ToIntlMathematicalValue(value). let mut x = to_intl_mathematical_value(args.get_or_undefined(0), context)?; diff --git a/core/engine/src/builtins/intl/segmenter/mod.rs b/core/engine/src/builtins/intl/segmenter/mod.rs index 459a385f6ed..3c8e30b0ccf 100644 --- a/core/engine/src/builtins/intl/segmenter/mod.rs +++ b/core/engine/src/builtins/intl/segmenter/mod.rs @@ -262,15 +262,7 @@ impl Segmenter { fn resolved_options(this: &JsValue, _: &[JsValue], context: &mut Context) -> JsResult { // 1. Let segmenter be the this value. // 2. Perform ? RequireInternalSlot(segmenter, [[InitializedSegmenter]]). - let object = this.as_object(); - let segmenter = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message( - "`resolved_options` can only be called on an `Intl.Segmenter` object", - ) - })?; + let segmenter = this.require_internal_slot::()?; // 3. Let options be OrdinaryObjectCreate(%Object.prototype%). // 4. For each row of Table 19, except the header row, in table order, do @@ -281,12 +273,12 @@ impl Segmenter { let options = ObjectInitializer::new(context) .property( js_string!("locale"), - js_string!(segmenter.locale.to_string()), + js_string!(segmenter.borrow().data().locale.to_string()), Attribute::all(), ) .property( js_string!("granularity"), - js_string!(segmenter.native.granularity().to_string()), + js_string!(segmenter.borrow().data().native.granularity().to_string()), Attribute::all(), ) .build(); diff --git a/core/engine/src/builtins/intl/segmenter/segments.rs b/core/engine/src/builtins/intl/segmenter/segments.rs index f489dce1247..e484ff234e7 100644 --- a/core/engine/src/builtins/intl/segmenter/segments.rs +++ b/core/engine/src/builtins/intl/segmenter/segments.rs @@ -55,24 +55,22 @@ impl Segments { fn containing(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult { // 1. Let segments be the this value. // 2. Perform ? RequireInternalSlot(segments, [[SegmentsSegmenter]]). - let object = this.as_object(); - let segments = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ() - .with_message("`containing` can only be called on a `Segments` object") - })?; + let segments = this.require_internal_slot::()?; // 3. Let segmenter be segments.[[SegmentsSegmenter]]. - let segmenter = segments - .segmenter + // 4. Let string be segments.[[SegmentsString]]. + let (segmenter_obj, string) = { + let seg_data = segments.borrow(); + let seg_data = seg_data.data(); + (seg_data.segmenter.clone(), seg_data.string.clone()) + }; + + let segmenter = segmenter_obj .downcast_ref::() .js_expect("segments object should contain a segmenter")?; - // 4. Let string be segments.[[SegmentsString]]. // 5. Let len be the length of string. - let len = segments.string.len() as i64; + let len = string.len() as i64; // 6. Let n be ? ToIntegerOrInfinity(index). let Some(n) = args @@ -89,8 +87,8 @@ impl Segments { // 8. Let startIndex be ! FindBoundary(segmenter, string, n, before). // 9. Let endIndex be ! FindBoundary(segmenter, string, n, after). let (range, is_word_like) = { - let mut segments = segmenter.native.segment(segments.string.variant()); - std::iter::from_fn(|| segments.next().map(|i| (i, segments.is_word_like()))) + let mut seg_iter = segmenter.native.segment(string.variant()); + std::iter::from_fn(|| seg_iter.next().map(|i| (i, seg_iter.is_word_like()))) .tuple_windows() .find(|((i, _), (j, _))| (*i..*j).contains(&n)) .map(|((i, _), (j, word))| ((i..j), word)) @@ -98,10 +96,7 @@ impl Segments { }; // 10. Return ! CreateSegmentDataObject(segmenter, string, startIndex, endIndex). - Ok( - create_segment_data_object(segments.string.clone(), range, is_word_like, context) - .into(), - ) + Ok(create_segment_data_object(string, range, is_word_like, context).into()) } /// [`%SegmentsPrototype% [ @@iterator ] ( )`][spec] diff --git a/core/engine/src/builtins/is_html_dda.rs b/core/engine/src/builtins/is_html_dda.rs index 037adc1638a..c0da9a75b40 100644 --- a/core/engine/src/builtins/is_html_dda.rs +++ b/core/engine/src/builtins/is_html_dda.rs @@ -40,6 +40,13 @@ impl JsData for IsHTMLDDA { }; &IS_HTML_DDA_INTERNAL_METHODS } + + fn type_name() -> &'static str + where + Self: Sized, + { + "IsHTMLDDA" + } } /// The `[[Call]]` internal method for `IsHTMLDDA` objects. diff --git a/core/engine/src/builtins/iterable/async_from_sync_iterator.rs b/core/engine/src/builtins/iterable/async_from_sync_iterator.rs index 56b198e80e3..fa7f7baafc1 100644 --- a/core/engine/src/builtins/iterable/async_from_sync_iterator.rs +++ b/core/engine/src/builtins/iterable/async_from_sync_iterator.rs @@ -6,6 +6,7 @@ use crate::{ promise::{PromiseCapability, if_abrupt_reject_promise}, }, context::intrinsics::Intrinsics, + error::PanicError, js_string, native_function::NativeFunction, object::{FunctionObjectBuilder, JsObject}, @@ -344,14 +345,19 @@ impl AsyncFromSyncIterator { // true, then Err(e) if !done && close_on_rejection => { // a. Set valueWrapper to Completion(IteratorClose(syncIteratorRecord, valueWrapper)). - Err(sync_iterator_record.close(Err(e), context).expect_err( - "closing an iterator with an error must always return an error back", - )) + let Err(e) = sync_iterator_record.close(Err(e), context) else { + return Err(PanicError::new( + "closing an iterator with an error must always return an error back", + ) + .into()); + }; + + Err(e) } - other => other.map(|o| { - o.downcast::() - .expect("%Promise% constructor must return a `Promise` object") - }), + Err(e) => Err(e), + Ok(o) => Ok(o + .require_internal_slot::() + .js_expect("%Promise% constructor must return a `Promise` object")?), }; // 8. IfAbruptRejectPromise(valueWrapper, promiseCapability). diff --git a/core/engine/src/builtins/iterable/iterator_helper/mod.rs b/core/engine/src/builtins/iterable/iterator_helper/mod.rs index d15f596d25f..6df5e850428 100644 --- a/core/engine/src/builtins/iterable/iterator_helper/mod.rs +++ b/core/engine/src/builtins/iterable/iterator_helper/mod.rs @@ -329,9 +329,7 @@ impl IteratorHelper { // // Slightly differs from the spec since we don't have a `[[GeneratorState]]`, // and we defer checking for `Executing` to `Self::next` and `Self::return`. - this.as_object() - .and_then(|o| o.downcast::().ok()) - .ok_or_else(|| js_error!(TypeError: "Iterator Helper method called on non-object")) + this.require_internal_slot::() } /// Creates a new `IteratorHelper` object. diff --git a/core/engine/src/builtins/map/map_iterator.rs b/core/engine/src/builtins/map/map_iterator.rs index 67233688762..6f91c8da6f0 100644 --- a/core/engine/src/builtins/map/map_iterator.rs +++ b/core/engine/src/builtins/map/map_iterator.rs @@ -5,11 +5,10 @@ //! //! [spec]: https://tc39.es/ecma262/#sec-map-iterator-objects -use super::ordered_map::OrderedMap; use crate::{ Context, JsData, JsResult, builtins::{ - Array, BuiltInBuilder, IntrinsicObject, JsValue, iterable::create_iter_result_object, + Array, BuiltInBuilder, IntrinsicObject, JsValue, Map, iterable::create_iter_result_object, }, context::intrinsics::Intrinsics, error::JsNativeError, @@ -22,18 +21,18 @@ use crate::{ use boa_gc::{Finalize, Trace}; #[derive(Debug, Trace)] -struct MapIteratorLock(JsObject>); +struct MapIteratorLock(JsObject); impl MapIteratorLock { - fn new(js_object: JsObject>) -> Self { - js_object.borrow_mut().data_mut().lock(); + fn new(js_object: JsObject) -> Self { + js_object.borrow_mut().data_mut().0.lock(); Self(js_object) } } impl Finalize for MapIteratorLock { fn finalize(&self) { - self.0.borrow_mut().data_mut().unlock(); + self.0.borrow_mut().data_mut().0.unlock(); } } @@ -79,7 +78,7 @@ impl MapIterator { /// /// [spec]: https://tc39.es/ecma262/#sec-createmapiterator pub(crate) fn create_map_iterator( - map: JsObject>, + map: JsObject, kind: PropertyNameKind, context: &mut Context, ) -> JsValue { @@ -116,7 +115,7 @@ impl MapIterator { if let Some(obj) = map_iterator.iterated_map.take() { let e = { let mut entries = obj.0.borrow_mut(); - let entries = entries.data_mut(); + let entries = &mut entries.data_mut().0; let len = entries.full_len(); loop { let element = entries diff --git a/core/engine/src/builtins/map/mod.rs b/core/engine/src/builtins/map/mod.rs index 9d5900961b0..49704ee220a 100644 --- a/core/engine/src/builtins/map/mod.rs +++ b/core/engine/src/builtins/map/mod.rs @@ -29,6 +29,8 @@ use super::{ }; mod map_iterator; +use boa_gc::{Finalize, Trace}; +use boa_macros::JsData; pub(crate) use map_iterator::MapIterator; pub mod ordered_map; @@ -37,8 +39,15 @@ use ordered_map::OrderedMap; #[cfg(test)] mod tests; -#[derive(Debug, Clone)] -pub(crate) struct Map; +/// The `Map` object. +#[derive(Debug, Trace, Finalize, JsData)] +pub struct Map(pub(crate) OrderedMap); + +impl AsMut> for Map { + fn as_mut(&mut self) -> &mut OrderedMap { + &mut self.0 + } +} impl IntrinsicObject for Map { fn init(realm: &Realm) { @@ -146,7 +155,7 @@ impl BuiltInConstructor for Map { let map = JsObject::from_proto_and_data_with_shared_shape( context.root_shape(), prototype, - >::new(), + Map(>::new()), ) .upcast(); @@ -203,14 +212,7 @@ impl Map { context: &mut Context, ) -> JsResult { // 1. Let M be the this value. - let this = this - .as_object() - .and_then(|o| o.downcast::>().ok()) - .ok_or_else(|| { - js_error!( - TypeError: "method `Map.prototype.entries` called on incompatible receiver" - ) - })?; + let this = this.require_internal_slot::()?; // 2. Return ? CreateMapIterator(M, key+value). Ok(MapIterator::create_map_iterator( @@ -232,10 +234,7 @@ impl Map { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/keys pub(crate) fn keys(this: &JsValue, _: &[JsValue], context: &mut Context) -> JsResult { // 1. Let M be the this value. - let this = this - .as_object() - .and_then(|o| o.downcast::>().ok()) - .ok_or_else(|| js_error!(TypeError: "method `Map.prototype.keys` called on incompatible receiver"))?; + let this = this.require_internal_slot::()?; // 2. Return ? CreateMapIterator(M, key). Ok(MapIterator::create_map_iterator( @@ -260,12 +259,7 @@ impl Map { // 1. Let M be the this value. // 2. Perform ? RequireInternalSlot(M, [[MapData]]). - let map = this - .as_object() - .and_then(|o| o.downcast::>().ok()) - .ok_or_else(|| { - js_error!(TypeError: "method `Map.prototype.set` called on incompatible receiver") - })?; + let map = this.require_internal_slot::()?; // 3. Set key to CanonicalizeKeyedCollectionKey(key). let key = canonicalize_keyed_collection_key(args.get_or_undefined(0).clone()); @@ -275,7 +269,7 @@ impl Map { // i. Set p.[[Value]] to value. // 5. Let p be the Record { [[Key]]: key, [[Value]]: value }. // 6. Append p to M.[[MapData]]. - map.borrow_mut().data_mut().insert(key, value.clone()); + map.borrow_mut().data_mut().0.insert(key, value.clone()); // 7. Return M. Ok(this.clone()) @@ -301,13 +295,10 @@ impl Map { // a. If p.[[Key]] is not empty, set count to count + 1. // 6. Return 𝔽(count). Ok(this - .as_object() - .and_then(|o| o.downcast::>().ok()) - .ok_or_else(|| { - js_error!(TypeError: "method `Map.prototype.set` called on incompatible receiver") - })? + .require_internal_slot::()? .borrow() .data() + .0 .len() .into()) } @@ -326,12 +317,7 @@ impl Map { pub(crate) fn delete(this: &JsValue, args: &[JsValue], _: &mut Context) -> JsResult { // 1. Let M be the this value. // 2. Perform ? RequireInternalSlot(M, [[MapData]]). - let map = this - .as_object() - .and_then(|o| o.downcast::>().ok()) - .ok_or_else(|| { - js_error!(TypeError: "method `Map.prototype.delete` called on incompatible receiver") - })?; + let map = this.require_internal_slot::()?; // 3. Set key to CanonicalizeKeyedCollectionKey(key). let key = canonicalize_keyed_collection_key(args.get_or_undefined(0).clone()); @@ -342,7 +328,7 @@ impl Map { // ii. Set p.[[Value]] to empty. // iii. Return true. // 5. Return false. - Ok(map.borrow_mut().data_mut().remove(&key).is_some().into()) + Ok(map.borrow_mut().data_mut().0.remove(&key).is_some().into()) } /// `Map.prototype.get( key )` @@ -358,12 +344,7 @@ impl Map { pub(crate) fn get(this: &JsValue, args: &[JsValue], _: &mut Context) -> JsResult { // 1. Let M be the this value. // 2. Perform ? RequireInternalSlot(M, [[MapData]]). - let map = this - .as_object() - .and_then(|o| o.downcast::>().ok()) - .ok_or_else(|| { - js_error!(TypeError: "method `Map.prototype.get` called on incompatible receiver") - })?; + let map = this.require_internal_slot::()?; // 3. Set key to CanonicalizeKeyedCollectionKey(key). let key = canonicalize_keyed_collection_key(args.get_or_undefined(0).clone()); @@ -371,7 +352,7 @@ impl Map { // 4. For each Record { [[Key]], [[Value]] } p of M.[[MapData]], do // a. If p.[[Key]] is not empty and SameValue(p.[[Key]], key) is true, return p.[[Value]]. // 5. Return undefined. - Ok(map.borrow().data().get(&key).cloned().unwrap_or_default()) + Ok(map.borrow().data().0.get(&key).cloned().unwrap_or_default()) } /// `Map.prototype.clear( )` @@ -387,19 +368,12 @@ impl Map { pub(crate) fn clear(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { // 1. Let M be the this value. // 2. Perform ? RequireInternalSlot(M, [[MapData]]). - let map = this - .as_object() - .and_then(|o| o.downcast::>().ok()) - .ok_or_else(|| { - js_error!( - TypeError: "method `Map.prototype.clear` called on incompatible receiver" - ) - })?; + let map = this.require_internal_slot::()?; // 3. For each Record { [[Key]], [[Value]] } p of M.[[MapData]], do // a. Set p.[[Key]] to empty. // b. Set p.[[Value]] to empty. - map.borrow_mut().data_mut().clear(); + map.borrow_mut().data_mut().0.clear(); // 4. Return undefined. Ok(JsValue::undefined()) @@ -418,14 +392,7 @@ impl Map { pub(crate) fn has(this: &JsValue, args: &[JsValue], _: &mut Context) -> JsResult { // 1. Let M be the this value. // 2. Perform ? RequireInternalSlot(M, [[MapData]]). - let map = this - .as_object() - .and_then(|o| o.downcast::>().ok()) - .ok_or_else(|| { - js_error!( - TypeError: "method `Map.prototype.has` called on incompatible receiver" - ) - })?; + let map = this.require_internal_slot::()?; // 3. Set key to CanonicalizeKeyedCollectionKey(key). let key = canonicalize_keyed_collection_key(args.get_or_undefined(0).clone()); @@ -433,7 +400,7 @@ impl Map { // 4. For each Record { [[Key]], [[Value]] } p of M.[[MapData]], do // a. If p.[[Key]] is not empty and SameValue(p.[[Key]], key) is true, return true. // 5. Return false. - Ok(map.borrow().data().contains_key(&key).into()) + Ok(map.borrow().data().0.contains_key(&key).into()) } /// `Map.prototype.forEach( callbackFn [ , thisArg ] )` @@ -453,14 +420,7 @@ impl Map { ) -> JsResult { // 1. Let M be the this value. // 2. Perform ? RequireInternalSlot(M, [[MapData]]). - let map = this - .as_object() - .and_then(|o| o.downcast::>().ok()) - .ok_or_else(|| { - js_error!( - TypeError: "method `Map.prototype.forEach` called on incompatible receiver" - ) - })?; + let map = this.require_internal_slot::()?; // 3. If IsCallable(callbackfn) is false, throw a TypeError exception. let Some(callback) = args.get_or_undefined(0).as_callable() else { @@ -489,7 +449,7 @@ impl Map { loop { let arguments = { let map = map.borrow(); - let map = map.data(); + let map = &map.data().0; if index < map.full_len() { map.get_index(index) .map(|(k, v)| [v.clone(), k.clone(), this.clone()]) @@ -523,14 +483,7 @@ impl Map { { // See `Self::for_each` for comments on the algo. - let map = this - .as_object() - .and_then(|o| o.downcast::>().ok()) - .ok_or_else(|| { - js_error!( - TypeError: "method `Map.prototype.forEach` called on incompatible receiver" - ) - })?; + let map = this.require_internal_slot::()?; let _lock = MapLock::new(&map); @@ -538,7 +491,7 @@ impl Map { loop { let (k, v) = { let map = map.borrow(); - let map = map.data(); + let map = &map.data().0; if index >= map.full_len() { return Ok(()); } @@ -572,14 +525,8 @@ impl Map { ) -> JsResult { // 1. Let M be the this value. // 2. Return ? CreateMapIterator(M, value). - let this = this - .as_object() - .and_then(|o| o.downcast::>().ok()) - .ok_or_else(|| { - js_error!( - TypeError: "method `Map.prototype.values` called on incompatible receiver" - ) - })?; + + let this = this.require_internal_slot::()?; Ok(MapIterator::create_map_iterator( this, @@ -608,27 +555,20 @@ impl Map { // 1. Let M be the this value. // 2. Perform ? RequireInternalSlot(M, [[MapData]]). - let map = this - .as_object() - .and_then(|o| o.downcast::>().ok()) - .ok_or_else(|| { - js_error!( - TypeError: "method `Map.prototype.getOrInsert` called on incompatible receiver" - ) - })?; + let map = this.require_internal_slot::()?; // 3. Set key to CanonicalizeKeyedCollectionKey(key). let key = canonicalize_keyed_collection_key(args.get_or_undefined(0).clone()); // 4. For each Record { [[Key]], [[Value]] } p of M.[[MapData]], do - if let Some(existing) = map.borrow().data().get(&key) { + if let Some(existing) = map.borrow().data().0.get(&key) { // a. If p.[[Key]] is not empty and SameValue(p.[[Key]], key) is true, return p.[[Value]]. return Ok(existing.clone()); } // 5. Let p be the Record { [[Key]]: key, [[Value]]: value }. // 6. Append p to M.[[MapData]]. - map.borrow_mut().data_mut().insert(key, value.clone()); + map.borrow_mut().data_mut().0.insert(key, value.clone()); // 7. Return value. Ok(value.clone()) @@ -653,14 +593,8 @@ impl Map { ) -> JsResult { // 1. Let M be the this value. // 2. Perform ? RequireInternalSlot(M, [[MapData]]). - let map = this - .as_object() - .and_then(|o| o.downcast::>().ok()) - .ok_or_else(|| { - js_error!( - TypeError: "method `Map.prototype.getOrInsertComputed` called on incompatible receiver" - ) - })?; + + let map = this.require_internal_slot::()?; // 3. If IsCallable(callbackfn) is false, throw a TypeError exception. let Some(callback_fn) = args.get_or_undefined(1).as_callable() else { @@ -673,7 +607,7 @@ impl Map { let key = canonicalize_keyed_collection_key(args.get_or_undefined(0).clone()); // 5. For each Record { [[Key]], [[Value]] } p of M.[[MapData]], do - if let Some(existing) = map.borrow().data().get(&key) { + if let Some(existing) = map.borrow().data().0.get(&key) { // a. If p.[[Key]] is not empty and SameValue(p.[[Key]], key) is true, return p.[[Value]]. return Ok(existing.clone()); } @@ -691,6 +625,7 @@ impl Map { // [`OrderedMap::insert`] handles both cases map.borrow_mut() .data_mut() + .0 .insert(key.clone(), value.clone()); // 11. Return value. Ok(value) diff --git a/core/engine/src/builtins/map/ordered_map.rs b/core/engine/src/builtins/map/ordered_map.rs index 9cedd69d1e7..8c7c6d0f33d 100644 --- a/core/engine/src/builtins/map/ordered_map.rs +++ b/core/engine/src/builtins/map/ordered_map.rs @@ -1,11 +1,12 @@ //! Implements a map type that preserves insertion order. -use crate::{JsData, JsValue, object::JsObject}; +use crate::{JsData, JsValue, NativeObject, object::JsObject}; use boa_gc::{Finalize, Trace, custom_trace}; use indexmap::{Equivalent, IndexMap}; use std::{ fmt::Debug, hash::{Hash, Hasher}, + marker::PhantomData, }; #[derive(PartialEq, Eq, Clone, Debug)] @@ -220,17 +221,20 @@ impl OrderedMap { } } -pub(crate) struct MapLock<'a, V: Trace + 'static>(&'a JsObject>); +pub(crate) struct MapLock<'a, V, A: NativeObject + AsMut>>( + &'a JsObject, + PhantomData, +); -impl<'a, V: Trace + 'static> MapLock<'a, V> { - pub(crate) fn new(js_object: &'a JsObject>) -> Self { - js_object.borrow_mut().data_mut().lock(); - Self(js_object) +impl<'a, V, A: NativeObject + AsMut>> MapLock<'a, V, A> { + pub(crate) fn new(js_object: &'a JsObject) -> Self { + js_object.borrow_mut().data_mut().as_mut().lock(); + Self(js_object, PhantomData) } } -impl Drop for MapLock<'_, V> { +impl>> Drop for MapLock<'_, V, A> { fn drop(&mut self) { - self.0.borrow_mut().data_mut().unlock(); + self.0.borrow_mut().data_mut().as_mut().unlock(); } } diff --git a/core/engine/src/builtins/map/tests.rs b/core/engine/src/builtins/map/tests.rs index c96cefee843..91194cf4595 100644 --- a/core/engine/src/builtins/map/tests.rs +++ b/core/engine/src/builtins/map/tests.rs @@ -351,7 +351,7 @@ fn get_or_insert_computed_this_not_map() { run_test_actions([TestAction::assert_native_error( "Map.prototype.getOrInsertComputed.call({}, 'k', x => x)", JsNativeErrorKind::Type, - "method `Map.prototype.getOrInsertComputed` called on incompatible receiver", + "object does not contain required internal slot `Map`", )]); } diff --git a/core/engine/src/builtins/promise/mod.rs b/core/engine/src/builtins/promise/mod.rs index 3e2788f8012..3c43dbf2f5d 100644 --- a/core/engine/src/builtins/promise/mod.rs +++ b/core/engine/src/builtins/promise/mod.rs @@ -2101,12 +2101,8 @@ impl Promise { context: &mut Context, ) -> JsResult { // 1. Let promise be the this value. - let promise = this; - // 2. If IsPromise(promise) is false, throw a TypeError exception. - let promise = promise.as_promise_object().ok_or_else(|| { - JsNativeError::typ().with_message("Promise.prototype.then: this is not a promise") - })?; + let promise = this.require_internal_slot::()?; let on_fulfilled = args .get_or_undefined(0) diff --git a/core/engine/src/builtins/proxy/mod.rs b/core/engine/src/builtins/proxy/mod.rs index b0047fbaf3e..5b645bbd6c5 100644 --- a/core/engine/src/builtins/proxy/mod.rs +++ b/core/engine/src/builtins/proxy/mod.rs @@ -85,6 +85,13 @@ impl JsData for Proxy { &BASIC } } + + fn type_name() -> &'static str + where + Self: Sized, + { + "Proxy" + } } impl IntrinsicObject for Proxy { diff --git a/core/engine/src/builtins/regexp/mod.rs b/core/engine/src/builtins/regexp/mod.rs index 037eed6eb19..b835a61b0a0 100644 --- a/core/engine/src/builtins/regexp/mod.rs +++ b/core/engine/src/builtins/regexp/mod.rs @@ -1032,12 +1032,7 @@ impl RegExp { ) -> JsResult { // 1. Let R be the this value. // 2. Perform ? RequireInternalSlot(R, [[RegExpMatcher]]). - let this = this.as_object(); - let obj = this - .and_then(|o| o.downcast::().ok()) - .ok_or_else(|| { - JsNativeError::typ().with_message("RegExp.prototype.exec called with invalid value") - })?; + let obj = this.require_internal_slot::()?; // 3. Let S be ? ToString(string). let arg_str = args.get_or_undefined(0).to_string(context)?; @@ -1081,11 +1076,7 @@ impl RegExp { } // 5. Perform ? RequireInternalSlot(R, [[RegExpMatcher]]). - let Ok(this) = this.clone().downcast::() else { - return Err(JsNativeError::typ() - .with_message("RegExpExec called with invalid value") - .into()); - }; + let this = this.clone().require_internal_slot::()?; // 6. Return ? RegExpBuiltinExec(R, S). Self::abstract_builtin_exec(this, &input, context) diff --git a/core/engine/src/builtins/set/mod.rs b/core/engine/src/builtins/set/mod.rs index 9052886b924..d7cb9bb619b 100644 --- a/core/engine/src/builtins/set/mod.rs +++ b/core/engine/src/builtins/set/mod.rs @@ -35,6 +35,8 @@ use crate::{ symbol::JsSymbol, }; use boa_engine::value::IntegerOrInfinity; +use boa_gc::{Finalize, Trace}; +use boa_macros::JsData; pub(crate) use set_iterator::SetIterator; /// A record containing information about a Set-like object. @@ -116,8 +118,15 @@ fn get_set_record(obj: &JsValue, context: &mut Context) -> JsResult { }) } -#[derive(Debug, Clone)] -pub(crate) struct Set; +/// The `Set` object. +#[derive(Debug, Trace, Finalize, JsData)] +pub struct Set(pub(crate) OrderedSet); + +impl AsMut for Set { + fn as_mut(&mut self) -> &mut OrderedSet { + &mut self.0 + } +} impl IntrinsicObject for Set { fn get(intrinsics: &Intrinsics) -> JsObject { @@ -223,7 +232,7 @@ impl BuiltInConstructor for Set { let set = JsObject::from_proto_and_data_with_shared_shape( context.root_shape(), prototype, - OrderedSet::default(), + Set(OrderedSet::default()), ) .upcast(); @@ -289,12 +298,7 @@ impl Set { pub(crate) fn add(this: &JsValue, args: &[JsValue], _: &mut Context) -> JsResult { // 1. Let S be the this value. // 2. Perform ? RequireInternalSlot(S, [[SetData]]). - let set = this - .as_object() - .and_then(|o| o.downcast::().ok()) - .ok_or_else(|| { - js_error!(TypeError: "method `Set.prototype.add` called on incompatible receiver") - })?; + let set = this.require_internal_slot::()?; // 3. Set value to CanonicalizeKeyedCollectionKey(value). let value = canonicalize_keyed_collection_key(args.get_or_undefined(0).clone()); @@ -303,7 +307,7 @@ impl Set { // a. If e is not empty and SameValueZero(e, value) is true, then // i. Return S. // 5. Append value to S.[[SetData]]. - set.borrow_mut().data_mut().add(value.clone()); + set.borrow_mut().data_mut().0.add(value.clone()); Ok(this.clone()) // 6. Return S. @@ -324,15 +328,10 @@ impl Set { // 2. Perform ? RequireInternalSlot(S, [[SetData]]). // 3. For each element e of S.[[SetData]], do // a. Replace the element of S.[[SetData]] whose value is e with an element whose value is empty. - this.as_object() - .and_then(|o| o.downcast::().ok()) - .ok_or_else(|| { - js_error!( - TypeError: "method `Set.prototype.clear` called on incompatible receiver" - ) - })? + this.require_internal_slot::()? .borrow_mut() .data_mut() + .0 .clear(); // 4. Return undefined. @@ -353,14 +352,7 @@ impl Set { pub(crate) fn delete(this: &JsValue, args: &[JsValue], _: &mut Context) -> JsResult { // 1. Let S be the this value. // 2. Perform ? RequireInternalSlot(S, [[SetData]]). - let this = this - .as_object() - .and_then(|o| o.downcast::().ok()) - .ok_or_else(|| { - js_error!( - TypeError: "method `Set.prototype.delete` called on incompatible receiver" - ) - })?; + let this = this.require_internal_slot::()?; let value = canonicalize_keyed_collection_key(args.get_or_undefined(0).clone()); @@ -369,7 +361,7 @@ impl Set { // i. Replace the element of S.[[SetData]] whose value is e with an element whose value is empty. // ii. Return true. // 4. Return false. - Ok(this.borrow_mut().data_mut().delete(&value).into()) + Ok(this.borrow_mut().data_mut().0.delete(&value).into()) } /// `Set.prototype.entries( )` @@ -387,14 +379,7 @@ impl Set { _: &[JsValue], context: &mut Context, ) -> JsResult { - let this = this - .as_object() - .and_then(|o| o.downcast::().ok()) - .ok_or_else(|| { - js_error!( - TypeError: "method `Set.prototype.entries` called on incompatible receiver" - ) - })?; + let this = this.require_internal_slot::()?; Ok(SetIterator::create_set_iterator( this.clone(), @@ -421,14 +406,7 @@ impl Set { // 1. Let S be the this value. // 2. Perform ? RequireInternalSlot(S, [[SetData]]). - let obj = this - .as_object() - .and_then(|o| o.downcast::().ok()) - .ok_or_else(|| { - js_error!( - TypeError: "method `Set.prototype.forEach` called on incompatible receiver" - ) - })?; + let obj = this.require_internal_slot::()?; // 3. If IsCallable(callbackfn) is false, throw a TypeError exception. let Some(callback_fn) = args.get_or_undefined(0).as_callable() else { @@ -446,9 +424,9 @@ impl Set { let mut index = 0; // 7. Repeat, while index < numEntries, - while index < obj.borrow().data().full_len() { + while index < obj.borrow().data().0.full_len() { // a. Let e be entries[index]. - let e = obj.borrow().data().get_index(index).cloned(); + let e = obj.borrow().data().0.get_index(index).cloned(); // b. Set index to index + 1. index += 1; @@ -484,14 +462,7 @@ impl Set { { // See `Self::for_each` for comments on the algo. - let set = this.as_object(); - let set = set - .and_then(|obj| obj.downcast::().ok()) - .ok_or_else(|| { - js_error!( - TypeError: "method `Set.prototype.forEach` called on incompatible receiver" - ) - })?; + let set = this.require_internal_slot::()?; let _lock = SetLock::new(&set); let mut index = 0; @@ -500,8 +471,8 @@ impl Set { let set = set.borrow(); let set = set.data(); - if index < set.full_len() { - if let Some(k) = set.get_index(index) { + if index < set.0.full_len() { + if let Some(k) = set.0.get_index(index) { k.clone() } else { continue; @@ -529,14 +500,7 @@ impl Set { pub(crate) fn has(this: &JsValue, args: &[JsValue], _: &mut Context) -> JsResult { // 1. Let M be the this value. // 2. Perform ? RequireInternalSlot(S, [[SetData]]). - let this = this - .as_object() - .and_then(|o| o.downcast::().ok()) - .ok_or_else(|| { - js_error!( - TypeError: "method `Set.prototype.has` called on incompatible receiver" - ) - })?; + let this = this.require_internal_slot::()?; // 3. Set value to CanonicalizeKeyedCollectionKey(key). let value = args.get_or_undefined(0); @@ -545,7 +509,7 @@ impl Set { // 4. For each element e of S.[[SetData]], do // a. If e is not empty and SameValue(e, value) is true, return true. // 5. Return false. - Ok(this.borrow().data().contains(&value).into()) + Ok(this.borrow().data().0.contains(&value).into()) } /// `Set.prototype.values( )` @@ -563,10 +527,7 @@ impl Set { _: &[JsValue], context: &mut Context, ) -> JsResult { - let this = this - .as_object() - .and_then(|o| o.downcast::().ok()) - .ok_or_else(|| js_error!(TypeError: "method `Set.prototype.values` called on incompatible receiver"))?; + let this = this.require_internal_slot::()?; Ok(SetIterator::create_set_iterator( this, @@ -595,25 +556,22 @@ impl Set { // 1. Let O be the this value. // 2. Perform ? RequireInternalSlot(O, [[SetData]]). - let this = this - .as_object() - .and_then(|o| o.downcast::().ok()) - .ok_or_else(|| js_error!(TypeError: "method `Set.prototype.isDisjointFrom` called on incompatible receiver"))?; + let this = this.require_internal_slot::()?; // 3. Let otherRec be ? GetSetRecord(other). let other = args.get_or_undefined(0); let other_rec = get_set_record(other, context)?; // 4. If SetDataSize(O.[[SetData]]) ≤ otherRec.[[Size]], then - if this.borrow().data().len() <= other_rec.size { + if this.borrow().data().0.len() <= other_rec.size { // a. Let thisSize be the number of elements in O.[[SetData]]. - let mut this_size = this.borrow().data().full_len(); + let mut this_size = this.borrow().data().0.full_len(); // b. Let index be 0. let mut index = 0; // c. Repeat, while index < thisSize, while index < this_size { // i. Let e be O.[[SetData]][index]. - let e = this.borrow().data().get_index(index).cloned(); + let e = this.borrow().data().0.get_index(index).cloned(); // ii. Set index to index + 1. index += 1; @@ -630,7 +588,7 @@ impl Set { // 3. NOTE: The number of elements in O.[[SetData]] may have increased during execution of otherRec.[[Has]]. // 4. Set thisSize to the number of elements in O.[[SetData]]. - this_size = this.borrow().data().full_len(); + this_size = this.borrow().data().0.full_len(); } } } else { @@ -646,7 +604,7 @@ impl Set { // 1. If SetDataHas(O.[[SetData]], next) is true, then let next = canonicalize_keyed_collection_key(next); - if this.borrow().data().contains(&next) { + if this.borrow().data().0.contains(&next) { // a. Perform ? IteratorClose(keysIter, NormalCompletion(unused)). keys_iter.close(Ok(JsValue::undefined()), context)?; @@ -679,28 +637,25 @@ impl Set { // 1. Let O be the this value. // 2. Perform ? RequireInternalSlot(O, [[SetData]]). - let this = this - .as_object() - .and_then(|o| o.downcast::().ok()) - .ok_or_else(|| js_error!(TypeError: "method `Set.prototype.isSubsetOf` called on incompatible receiver"))?; + let this = this.require_internal_slot::()?; // 3. Let otherRec be ? GetSetRecord(other). let other = args.get_or_undefined(0); let other_rec = get_set_record(other, context)?; // 4. If SetDataSize(O.[[SetData]]) > otherRec.[[Size]], return false. - if this.borrow().data().len() > other_rec.size { + if this.borrow().data().0.len() > other_rec.size { return Ok(JsValue::from(false)); } // 5. Let thisSize be the number of elements in O.[[SetData]]. - let mut this_size = this.borrow().data().full_len(); + let mut this_size = this.borrow().data().0.full_len(); // 6. Let index be 0. let mut index = 0; // 7. Repeat, while index < thisSize, while index < this_size { // a. Let e be O.[[SetData]][index]. - let e = this.borrow().data().get_index(index).cloned(); + let e = this.borrow().data().0.get_index(index).cloned(); // b. Set index to index + 1. index += 1; @@ -717,7 +672,7 @@ impl Set { // iii. NOTE: The number of elements in O.[[SetData]] may have increased during execution of otherRec.[[Has]]. // iv. Set thisSize to the number of elements in O.[[SetData]]. - this_size = this.borrow().data().full_len(); + this_size = this.borrow().data().0.full_len(); } } @@ -745,17 +700,14 @@ impl Set { // 1. Let O be the this value. // 2. Perform ? RequireInternalSlot(O, [[SetData]]). - let this = this - .as_object() - .and_then(|o| o.downcast::().ok()) - .ok_or_else(|| js_error!(TypeError: "method `Set.prototype.isSupersetOf` called on incompatible receiver"))?; + let this = this.require_internal_slot::()?; // 3. Let otherRec be ? GetSetRecord(other). let other = args.get_or_undefined(0); let other_rec = get_set_record(other, context)?; // 4. If SetDataSize(O.[[SetData]]) < otherRec.[[Size]], return false. - if this.borrow().data().len() < other_rec.size { + if this.borrow().data().0.len() < other_rec.size { return Ok(JsValue::from(false)); } @@ -769,7 +721,7 @@ impl Set { // b. If next is not done, then // i. If SetDataHas(O.[[SetData]], next) is false, then let next = canonicalize_keyed_collection_key(next); - if !this.borrow().data().contains(&next) { + if !this.borrow().data().0.contains(&next) { // 1. Perform ? IteratorClose(keysIter, NormalCompletion(unused)). keys_iter.close(Ok(JsValue::undefined()), context)?; // 2. Return false. @@ -799,10 +751,7 @@ impl Set { ) -> JsResult { // 1. Let O be the this value. // 2. Perform ? RequireInternalSlot(O, [[SetData]]). - let this = this - .as_object() - .and_then(|o| o.downcast::().ok()) - .ok_or_else(|| js_error!(TypeError: "method `Set.prototype.symmetricDifference` called on incompatible receiver"))?; + let this = this.require_internal_slot::()?; // 3. Let otherRec be ? GetSetRecord(other). let other = args.get_or_undefined(0); @@ -812,7 +761,7 @@ impl Set { let mut keys_iter = other.get_iterator_from_method(&other_rec.keys, context)?; // 5. Let resultSetData be a copy of O.[[SetData]]. - let mut result_set = this.borrow().data().clone(); + let mut result_set = this.borrow().data().0.clone(); // 6. Let next be not-started. // 7. Repeat, while next is not done, @@ -827,7 +776,7 @@ impl Set { // iv. If SetDataHas(O.[[SetData]], next) is true, then // 1. If alreadyInResult is true, set resultSetData[resultIndex] to empty. - if this.borrow().data().contains(&next) { + if this.borrow().data().0.contains(&next) { result_set.delete(&next); } // v. Else, @@ -843,7 +792,7 @@ impl Set { Ok(JsObject::from_proto_and_data_with_shared_shape( context.root_shape(), context.intrinsics().constructors().set().prototype(), - result_set, + Set(result_set), ) .into()) } @@ -867,10 +816,7 @@ impl Set { // 1. Let O be the this value. // 2. Perform ? RequireInternalSlot(O, [[SetData]]). - let this = this - .as_object() - .and_then(|o| o.downcast::().ok()) - .ok_or_else(|| js_error!(TypeError: "method `Set.prototype.union` called on incompatible receiver"))?; + let this = this.require_internal_slot::()?; // 3. Let otherRec be ? GetSetRecord(other). let other = args.get_or_undefined(0); @@ -880,7 +826,7 @@ impl Set { let mut keys_iter = other.get_iterator_from_method(&other_rec.keys, context)?; // 5. Let resultSetData be a copy of O.[[SetData]]. - let mut result_set = this.borrow().data().clone(); + let mut result_set = this.borrow().data().0.clone(); // 6. Let next be not-started. // 7. Repeat, while next is not done, @@ -899,7 +845,7 @@ impl Set { Ok(JsObject::from_proto_and_data_with_shared_shape( context.root_shape(), context.intrinsics().constructors().set().prototype(), - result_set, + Set(result_set), ) .into()) } @@ -924,10 +870,7 @@ impl Set { ) -> JsResult { // 1. Let S be the this value. // 2. Perform ? RequireInternalSlot(O, [[SetData]]). - let this = this - .as_object() - .and_then(|o| o.downcast::().ok()) - .ok_or_else(|| js_error!(TypeError: "method `Set.prototype.intersection` called on incompatible receiver"))?; + let this = this.require_internal_slot::()?; // 3. Let otherRec be ? GetSetRecord(other). let other = args.get_or_undefined(0); @@ -937,15 +880,15 @@ impl Set { let mut result_set = OrderedSet::new(); // 5. If SetDataSize(O.[[SetData]]) ≤ otherRec.[[Size]], then - if this.borrow().data().len() <= other_rec.size { + if this.borrow().data().0.len() <= other_rec.size { // a. Let thisSize be the number of elements in O.[[SetData]]. - let mut this_size = this.borrow().data().full_len(); + let mut this_size = this.borrow().data().0.full_len(); // b. Let index be 0. let mut index = 0; // c. Repeat, while index < thisSize, while index < this_size { // i. Let e be O.[[SetData]][index]. - let e = this.borrow().data().get_index(index).cloned(); + let e = this.borrow().data().0.get_index(index).cloned(); // ii. Set index to index + 1. index += 1; @@ -966,7 +909,7 @@ impl Set { result_set.add(e); // 3. NOTE: The number of elements in O.[[SetData]] may have increased during execution of otherRec.[[Has]]. // 4. Set thisSize to the number of elements in O.[[SetData]]. - this_size = this.borrow().data().full_len(); + this_size = this.borrow().data().0.full_len(); } } @@ -983,7 +926,7 @@ impl Set { let next = canonicalize_keyed_collection_key(next); // 2. Let inThis be SetDataHas(O.[[SetData]], next). // 3. If inThis is true, then - if this.borrow().data().contains(&next) { + if this.borrow().data().0.contains(&next) { // a. NOTE: Because other is an arbitrary object, it is possible for its "keys" iterator to produce the same value more than once. // b. If SetDataHas(resultSetData, next) is false, then // i. Append next to resultSetData. @@ -998,7 +941,7 @@ impl Set { Ok(JsObject::from_proto_and_data_with_shared_shape( context.root_shape(), context.intrinsics().constructors().set().prototype(), - result_set, + Set(result_set), ) .into()) } @@ -1021,26 +964,19 @@ impl Set { ) -> JsResult { // 1. Let O be the this value. // 2. Perform ? RequireInternalSlot(O, [[SetData]]). - let this = this - .as_object() - .and_then(|o| o.downcast::().ok()) - .ok_or_else(|| { - js_error!( - TypeError: "method `Set.prototype.difference` called on incompatible receiver" - ) - })?; + let this = this.require_internal_slot::()?; // 3. Let otherRec be ? GetSetRecord(other). let other = args.get_or_undefined(0); let other_rec = get_set_record(other, context)?; // 4. Let resultSetData be a copy of O.[[SetData]]. - let mut result_set = this.borrow().data().clone(); + let mut result_set = this.borrow().data().0.clone(); // 5. If SetDataSize(O.[[SetData]]) ≤ otherRec.[[Size]], then if result_set.len() <= other_rec.size { // a. Let thisSize be the number of elements in O.[[SetData]]. - let this_size = this.borrow().data().full_len(); + let this_size = this.borrow().data().0.full_len(); // b. Let index be 0. let mut index = 0; @@ -1095,7 +1031,7 @@ impl Set { Ok(JsObject::from_proto_and_data_with_shared_shape( context.root_shape(), context.intrinsics().constructors().set().prototype(), - result_set, + Set(result_set), ) .into()) } @@ -1103,7 +1039,7 @@ impl Set { fn size_getter(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { Ok(this .as_object() - .and_then(|o| o.downcast_ref::().map(|o| o.len())) + .and_then(|o| o.downcast_ref::().map(|o| o.0.len())) .ok_or_else(|| js_error!(TypeError: "method `get Set.prototype.size` called on incompatible receiver"))?.into()) } } diff --git a/core/engine/src/builtins/set/ordered_set.rs b/core/engine/src/builtins/set/ordered_set.rs index f3bb469d3e7..7c7ae564dae 100644 --- a/core/engine/src/builtins/set/ordered_set.rs +++ b/core/engine/src/builtins/set/ordered_set.rs @@ -1,6 +1,6 @@ //! Implements a set type that preserves insertion order. -use crate::{JsData, JsValue, builtins::map::ordered_map::MapKey, object::JsObject}; +use crate::{JsData, JsValue, NativeObject, builtins::map::ordered_map::MapKey, object::JsObject}; use boa_gc::{Finalize, Trace, custom_trace}; use indexmap::IndexSet; use std::fmt::Debug; @@ -166,17 +166,17 @@ impl OrderedSet { } } -pub(crate) struct SetLock<'a>(&'a JsObject); +pub(crate) struct SetLock<'a, A: AsMut + NativeObject>(&'a JsObject); -impl<'a> SetLock<'a> { - pub(crate) fn new(js_object: &'a JsObject) -> Self { - js_object.borrow_mut().data_mut().lock(); +impl<'a, A: AsMut + NativeObject> SetLock<'a, A> { + pub(crate) fn new(js_object: &'a JsObject) -> Self { + js_object.borrow_mut().data_mut().as_mut().lock(); Self(js_object) } } -impl Drop for SetLock<'_> { +impl + NativeObject> Drop for SetLock<'_, A> { fn drop(&mut self) { - self.0.borrow_mut().data_mut().unlock(); + self.0.borrow_mut().data_mut().as_mut().unlock(); } } diff --git a/core/engine/src/builtins/set/set_iterator.rs b/core/engine/src/builtins/set/set_iterator.rs index 03583591761..3f80cbd4ec3 100644 --- a/core/engine/src/builtins/set/set_iterator.rs +++ b/core/engine/src/builtins/set/set_iterator.rs @@ -5,11 +5,10 @@ //! //! [spec]: https://tc39.es/ecma262/#sec-set-iterator-objects -use super::ordered_set::OrderedSet; use crate::{ Context, JsData, JsResult, builtins::{ - Array, BuiltInBuilder, IntrinsicObject, JsValue, iterable::create_iter_result_object, + Array, BuiltInBuilder, IntrinsicObject, JsValue, Set, iterable::create_iter_result_object, }, context::intrinsics::Intrinsics, error::JsNativeError, @@ -22,18 +21,18 @@ use crate::{ use boa_gc::{Finalize, Trace}; #[derive(Debug, Trace)] -struct SetIteratorLock(JsObject); +struct SetIteratorLock(JsObject); impl SetIteratorLock { - fn new(js_object: JsObject) -> Self { - js_object.borrow_mut().data_mut().lock(); + fn new(js_object: JsObject) -> Self { + js_object.borrow_mut().data_mut().0.lock(); Self(js_object) } } impl Finalize for SetIteratorLock { fn finalize(&self) { - self.0.borrow_mut().data_mut().unlock(); + self.0.borrow_mut().data_mut().0.unlock(); } } @@ -79,7 +78,7 @@ impl SetIterator { /// /// [spec]: https://tc39.es/ecma262/#sec-createsetiterator pub(crate) fn create_set_iterator( - set: JsObject, + set: JsObject, kind: PropertyNameKind, context: &Context, ) -> JsValue { @@ -115,7 +114,7 @@ impl SetIterator { if let Some(obj) = set_iterator.iterated_set.take() { let e = { let mut entries = obj.0.borrow_mut(); - let entries = entries.data_mut(); + let entries = &mut entries.data_mut().0; let len = entries.full_len(); loop { let element = entries.get_index(set_iterator.next_index); diff --git a/core/engine/src/builtins/set/tests.rs b/core/engine/src/builtins/set/tests.rs index 51c2ac82085..f3b98aeb8c9 100644 --- a/core/engine/src/builtins/set/tests.rs +++ b/core/engine/src/builtins/set/tests.rs @@ -461,7 +461,7 @@ fn intersection_this_not_a_set() { run_test_actions([TestAction::assert_native_error( "Set.prototype.intersection.call({}, new Set([1, 2, 3]))", JsNativeErrorKind::Type, - "method `Set.prototype.intersection` called on incompatible receiver", + "object does not contain required internal slot `Set`", )]); } diff --git a/core/engine/src/builtins/temporal/duration/mod.rs b/core/engine/src/builtins/temporal/duration/mod.rs index 7e0d8026ae7..cfd749cf4c5 100644 --- a/core/engine/src/builtins/temporal/duration/mod.rs +++ b/core/engine/src/builtins/temporal/duration/mod.rs @@ -331,15 +331,10 @@ impl BuiltInConstructor for Duration { impl Duration { // Internal utility function for getting `Duration` field values. fn get_internal_field(this: &JsValue, field: &DateTimeValues) -> JsResult { - let object = this.as_object(); - let duration = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("this value must be a Duration object.") - })?; + let duration = this.require_internal_slot::()?; - let inner = &duration.inner; + let duration_data = duration.borrow(); + let inner = &duration_data.data().inner; match field { DateTimeValues::Year => Ok(JsValue::new(inner.years())), @@ -522,18 +517,12 @@ impl Duration { fn get_sign(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { // 1. Let duration be the this value. // 2. Perform ? RequireInternalSlot(duration, [[InitializedTemporalDuration]]). - let object = this.as_object(); - let duration = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("this value must be a Duration object.") - })?; + let duration = this.require_internal_slot::()?; // 3. Return 𝔽(! DurationSign(duration.[[Years]], duration.[[Months]], duration.[[Weeks]], // duration.[[Days]], duration.[[Hours]], duration.[[Minutes]], duration.[[Seconds]], // duration.[[Milliseconds]], duration.[[Microseconds]], duration.[[Nanoseconds]])). - Ok((duration.inner.sign() as i8).into()) + Ok((duration.borrow().data().inner.sign() as i8).into()) } /// 7.3.14 get `Temporal.Duration.prototype.blank` @@ -550,20 +539,14 @@ impl Duration { fn get_blank(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { // 1. Let duration be the this value. // 2. Perform ? RequireInternalSlot(duration, [[InitializedTemporalDuration]]). - let object = this.as_object(); - let duration = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("this value must be a Duration object.") - })?; + let duration = this.require_internal_slot::()?; // 3. Let sign be ! DurationSign(duration.[[Years]], duration.[[Months]], duration.[[Weeks]], // duration.[[Days]], duration.[[Hours]], duration.[[Minutes]], duration.[[Seconds]], // duration.[[Milliseconds]], duration.[[Microseconds]], duration.[[Nanoseconds]]). // 4. If sign = 0, return true. // 5. Return false. - Ok(duration.inner.is_zero().into()) + Ok(duration.borrow().data().inner.is_zero().into()) } } @@ -642,13 +625,7 @@ impl Duration { ) -> JsResult { // 1. Let duration be the this value. // 2. Perform ? RequireInternalSlot(duration, [[InitializedTemporalDuration]]). - let object = this.as_object(); - let duration = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("this value must be a Duration object.") - })?; + let duration = this.require_internal_slot::()?; // 3. Let temporalDurationLike be ? ToTemporalPartialDurationRecord(temporalDurationLike). let temporal_duration_like = @@ -660,7 +637,7 @@ impl Duration { // a. Let years be duration.[[Years]]. let years = temporal_duration_like .years - .unwrap_or(duration.inner.years()); + .unwrap_or(duration.borrow().data().inner.years()); // 6. If temporalDurationLike.[[Months]] is not undefined, then // a. Let months be temporalDurationLike.[[Months]]. @@ -668,7 +645,7 @@ impl Duration { // a. Let months be duration.[[Months]]. let months = temporal_duration_like .months - .unwrap_or(duration.inner.months()); + .unwrap_or(duration.borrow().data().inner.months()); // 8. If temporalDurationLike.[[Weeks]] is not undefined, then // a. Let weeks be temporalDurationLike.[[Weeks]]. @@ -676,13 +653,15 @@ impl Duration { // a. Let weeks be duration.[[Weeks]]. let weeks = temporal_duration_like .weeks - .unwrap_or(duration.inner.weeks()); + .unwrap_or(duration.borrow().data().inner.weeks()); // 10. If temporalDurationLike.[[Days]] is not undefined, then // a. Let days be temporalDurationLike.[[Days]]. // 11. Else, // a. Let days be duration.[[Days]]. - let days = temporal_duration_like.days.unwrap_or(duration.inner.days()); + let days = temporal_duration_like + .days + .unwrap_or(duration.borrow().data().inner.days()); // 12. If temporalDurationLike.[[Hours]] is not undefined, then // a. Let hours be temporalDurationLike.[[Hours]]. @@ -690,7 +669,7 @@ impl Duration { // a. Let hours be duration.[[Hours]]. let hours = temporal_duration_like .hours - .unwrap_or(duration.inner.hours()); + .unwrap_or(duration.borrow().data().inner.hours()); // 14. If temporalDurationLike.[[Minutes]] is not undefined, then // a. Let minutes be temporalDurationLike.[[Minutes]]. @@ -698,7 +677,7 @@ impl Duration { // a. Let minutes be duration.[[Minutes]]. let minutes = temporal_duration_like .minutes - .unwrap_or(duration.inner.minutes()); + .unwrap_or(duration.borrow().data().inner.minutes()); // 16. If temporalDurationLike.[[Seconds]] is not undefined, then // a. Let seconds be temporalDurationLike.[[Seconds]]. @@ -706,7 +685,7 @@ impl Duration { // a. Let seconds be duration.[[Seconds]]. let seconds = temporal_duration_like .seconds - .unwrap_or(duration.inner.seconds()); + .unwrap_or(duration.borrow().data().inner.seconds()); // 18. If temporalDurationLike.[[Milliseconds]] is not undefined, then // a. Let milliseconds be temporalDurationLike.[[Milliseconds]]. @@ -714,7 +693,7 @@ impl Duration { // a. Let milliseconds be duration.[[Milliseconds]]. let milliseconds = temporal_duration_like .milliseconds - .unwrap_or(duration.inner.milliseconds()); + .unwrap_or(duration.borrow().data().inner.milliseconds()); // 20. If temporalDurationLike.[[Microseconds]] is not undefined, then // a. Let microseconds be temporalDurationLike.[[Microseconds]]. @@ -722,7 +701,7 @@ impl Duration { // a. Let microseconds be duration.[[Microseconds]]. let microseconds = temporal_duration_like .microseconds - .unwrap_or(duration.inner.microseconds()); + .unwrap_or(duration.borrow().data().inner.microseconds()); // 22. If temporalDurationLike.[[Nanoseconds]] is not undefined, then // a. Let nanoseconds be temporalDurationLike.[[Nanoseconds]]. @@ -730,7 +709,7 @@ impl Duration { // a. Let nanoseconds be duration.[[Nanoseconds]]. let nanoseconds = temporal_duration_like .nanoseconds - .unwrap_or(duration.inner.nanoseconds()); + .unwrap_or(duration.borrow().data().inner.nanoseconds()); // 24. Return ? CreateTemporalDuration(years, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds). let new_duration = InnerDuration::new( @@ -767,15 +746,10 @@ impl Duration { // 1. Let duration be the this value. // 2. Perform ? RequireInternalSlot(duration, [[InitializedTemporalDuration]]). // 3. Return ! CreateNegatedTemporalDuration(duration). - let object = this.as_object(); - let duration = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("this value must be a Duration object.") - })?; - - create_temporal_duration(duration.inner.negated(), None, context).map(Into::into) + let duration = this.require_internal_slot::()?; + + create_temporal_duration(duration.borrow().data().inner.negated(), None, context) + .map(Into::into) } /// 7.3.17 `Temporal.Duration.prototype.abs ( )` @@ -795,15 +769,10 @@ impl Duration { // 3. Return ! CreateTemporalDuration(abs(duration.[[Years]]), abs(duration.[[Months]]), // abs(duration.[[Weeks]]), abs(duration.[[Days]]), abs(duration.[[Hours]]), abs(duration.[[Minutes]]), // abs(duration.[[Seconds]]), abs(duration.[[Milliseconds]]), abs(duration.[[Microseconds]]), abs(duration.[[Nanoseconds]])). - let object = this.as_object(); - let duration = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("this value must be a Duration object.") - })?; - - create_temporal_duration(duration.inner.abs(), None, context).map(Into::into) + let duration = this.require_internal_slot::()?; + + create_temporal_duration(duration.borrow().data().inner.abs(), None, context) + .map(Into::into) } /// 7.3.18 `Temporal.Duration.prototype.add ( other [ , options ] )` @@ -824,18 +793,13 @@ impl Duration { ) -> JsResult { // 1.Let duration be the this value. // 2. Perform ? RequireInternalSlot(duration, [[InitializedTemporalDuration]]). - let object = this.as_object(); - let duration = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("this value must be a Duration object.") - })?; + let duration = this.require_internal_slot::()?; // 3. Return ? AddDurations(add, duration, other). let other = to_temporal_duration_record(args.get_or_undefined(0), context)?; - create_temporal_duration(duration.inner.add(&other)?, None, context).map(Into::into) + create_temporal_duration(duration.borrow().data().inner.add(&other)?, None, context) + .map(Into::into) } /// 7.3.19 `Temporal.Duration.prototype.subtract ( other [ , options ] )` @@ -856,18 +820,17 @@ impl Duration { ) -> JsResult { // 1.Let duration be the this value. // 2. Perform ? RequireInternalSlot(duration, [[InitializedTemporalDuration]]). - let object = this.as_object(); - let duration = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("this value must be a Duration object.") - })?; + let duration = this.require_internal_slot::()?; let other = to_temporal_duration_record(args.get_or_undefined(0), context)?; // 3. Return ? AddDurations(add, duration, other). - create_temporal_duration(duration.inner.subtract(&other)?, None, context).map(Into::into) + create_temporal_duration( + duration.borrow().data().inner.subtract(&other)?, + None, + context, + ) + .map(Into::into) } /// 7.3.20 `Temporal.Duration.prototype.round ( roundTo )` @@ -888,13 +851,7 @@ impl Duration { ) -> JsResult { // 1. Let duration be the this value. // 2. Perform ? RequireInternalSlot(duration, [[InitializedTemporalDuration]]). - let object = this.as_object(); - let duration = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("this value must be a Duration object.") - })?; + let duration = this.require_internal_slot::()?; // 3. If roundTo is undefined, then let round_to_arg = args.get_or_undefined(0); @@ -962,7 +919,7 @@ impl Duration { // NOTE: execute step 21 earlier before initial values are shadowed. // 21. If smallestUnitPresent is false and largestUnitPresent is false, then - let rounded_duration = duration.inner.round_with_provider( + let rounded_duration = duration.borrow().data().inner.round_with_provider( options, relative_to, context.timezone_provider(), @@ -988,13 +945,7 @@ impl Duration { ) -> JsResult { // 1. Let duration be the this value. // 2. Perform ? RequireInternalSlot(duration, [[InitializedTemporalDuration]]). - let object = this.as_object(); - let duration = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("this value must be a Duration object.") - })?; + let duration = this.require_internal_slot::()?; let total_of = args.get_or_undefined(0); @@ -1042,6 +993,8 @@ impl Duration { .ok_or_else(|| JsNativeError::range().with_message("unit cannot be undefined."))?; Ok(duration + .borrow() + .data() .inner .total_with_provider(unit, relative_to, context.timezone_provider())? .as_inner() @@ -1064,13 +1017,7 @@ impl Duration { args: &[JsValue], context: &mut Context, ) -> JsResult { - let object = this.as_object(); - let duration = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("this value must be a Duration object.") - })?; + let duration = this.require_internal_slot::()?; let options = get_options_object(args.get_or_undefined(0))?; let precision = get_digits_option(&options, context)?; @@ -1078,11 +1025,16 @@ impl Duration { get_option::(&options, js_string!("roundingMode"), context)?; let smallest_unit = get_option::(&options, js_string!("smallestUnit"), context)?; - let result = duration.inner.as_temporal_string(ToStringRoundingOptions { - precision, - smallest_unit, - rounding_mode, - })?; + let result = + duration + .borrow() + .data() + .inner + .as_temporal_string(ToStringRoundingOptions { + precision, + smallest_unit, + rounding_mode, + })?; Ok(JsString::from(result).into()) } @@ -1097,15 +1049,11 @@ impl Duration { /// [spec]: https://tc39.es/proposal-temporal/#sec-temporal.duration.prototype.tojson /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/Duration/toJSON pub(crate) fn to_json(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { - let object = this.as_object(); - let duration = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("this value must be a Duration object.") - })?; + let duration = this.require_internal_slot::()?; let result = duration + .borrow() + .data() .inner .as_temporal_string(ToStringRoundingOptions::default())?; @@ -1127,15 +1075,11 @@ impl Duration { _: &mut Context, ) -> JsResult { // TODO: Update for ECMA-402 compliance - let object = this.as_object(); - let duration = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("this value must be a Duration object.") - })?; + let duration = this.require_internal_slot::()?; let result = duration + .borrow() + .data() .inner .as_temporal_string(ToStringRoundingOptions::default())?; diff --git a/core/engine/src/builtins/temporal/instant/mod.rs b/core/engine/src/builtins/temporal/instant/mod.rs index 1a26d930893..4a730dcb444 100644 --- a/core/engine/src/builtins/temporal/instant/mod.rs +++ b/core/engine/src/builtins/temporal/instant/mod.rs @@ -285,17 +285,11 @@ impl Instant { ) -> JsResult { // 1. Let instant be the this value. // 2. Perform ? RequireInternalSlot(instant, [[InitializedTemporalInstant]]). - let object = this.as_object(); - let instant = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be an instant object.") - })?; + let instant = this.require_internal_slot::()?; // 3. Let ns be instant.[[Nanoseconds]]. // 4. Let ms be floor(ℝ(ns) / 10^6). // 5. Return 𝔽(ms). - Ok(instant.inner.epoch_milliseconds().into()) + Ok(instant.borrow().data().inner.epoch_milliseconds().into()) } /// 8.3.6 get Temporal.Instant.prototype.epochNanoseconds @@ -316,16 +310,10 @@ impl Instant { ) -> JsResult { // 1. Let instant be the this value. // 2. Perform ? RequireInternalSlot(instant, [[InitializedTemporalInstant]]). - let object = this.as_object(); - let instant = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be an instant object.") - })?; + let instant = this.require_internal_slot::()?; // 3. Let ns be instant.[[Nanoseconds]]. // 4. Return ns. - Ok(JsBigInt::from(instant.inner.epoch_nanoseconds().as_i128()).into()) + Ok(JsBigInt::from(instant.borrow().data().inner.epoch_nanoseconds().as_i128()).into()) } } @@ -350,18 +338,12 @@ impl Instant { ) -> JsResult { // 1. Let instant be the this value. // 2. Perform ? RequireInternalSlot(instant, [[InitializedTemporalInstant]]). - let object = this.as_object(); - let instant = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be an instant object.") - })?; + let instant = this.require_internal_slot::()?; // 3. Return ? AddDurationToOrSubtractDurationFromInstant(add, instant, temporalDurationLike). let temporal_duration_like = to_temporal_duration_record(args.get_or_undefined(0), context)?; - let result = instant.inner.add(&temporal_duration_like)?; + let result = instant.borrow().data().inner.add(&temporal_duration_like)?; create_temporal_instant(result, None, context) } @@ -383,18 +365,16 @@ impl Instant { ) -> JsResult { // 1. Let instant be the this value. // 2. Perform ? RequireInternalSlot(instant, [[InitializedTemporalInstant]]). - let object = this.as_object(); - let instant = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be an instant object.") - })?; + let instant = this.require_internal_slot::()?; // 3. Return ? AddDurationToOrSubtractDurationFromInstant(subtract, instant, temporalDurationLike). let temporal_duration_like = to_temporal_duration_record(args.get_or_undefined(0), context)?; - let result = instant.inner.subtract(&temporal_duration_like)?; + let result = instant + .borrow() + .data() + .inner + .subtract(&temporal_duration_like)?; create_temporal_instant(result, None, context) } @@ -416,13 +396,7 @@ impl Instant { ) -> JsResult { // 1. Let instant be the this value. // 2. Perform ? RequireInternalSlot(instant, [[InitializedTemporalInstant]]). - let object = this.as_object(); - let instant = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be an instant object.") - })?; + let instant = this.require_internal_slot::()?; // 3. Return ? DifferenceTemporalInstant(until, instant, other, options). let other = to_temporal_instant(args.get_or_undefined(0), context)?; @@ -430,7 +404,7 @@ impl Instant { // Fetch the necessary options. let settings = get_difference_settings(&get_options_object(args.get_or_undefined(1))?, context)?; - let result = instant.inner.until(&other, settings)?; + let result = instant.borrow().data().inner.until(&other, settings)?; create_temporal_duration(result, None, context).map(Into::into) } @@ -452,19 +426,13 @@ impl Instant { ) -> JsResult { // 1. Let instant be the this value. // 2. Perform ? RequireInternalSlot(instant, [[InitializedTemporalInstant]]). - let object = this.as_object(); - let instant = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be an instant object.") - })?; + let instant = this.require_internal_slot::()?; // 3. Return ? DifferenceTemporalInstant(since, instant, other, options). let other = to_temporal_instant(args.get_or_undefined(0), context)?; let settings = get_difference_settings(&get_options_object(args.get_or_undefined(1))?, context)?; - let result = instant.inner.since(&other, settings)?; + let result = instant.borrow().data().inner.since(&other, settings)?; create_temporal_duration(result, None, context).map(Into::into) } @@ -486,13 +454,7 @@ impl Instant { ) -> JsResult { // 1. Let instant be the this value. // 2. Perform ? RequireInternalSlot(instant, [[InitializedTemporalInstant]]). - let object = this.as_object(); - let instant = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be an instant object.") - })?; + let instant = this.require_internal_slot::()?; // 3. If roundTo is undefined, then let round_to_arg = args.get_or_undefined(0); @@ -559,7 +521,7 @@ impl Instant { // unreachable here functions as 15.a. // 16. Perform ? ValidateTemporalRoundingIncrement(roundingIncrement, maximum, true). // 17. Let roundedNs be RoundTemporalInstant(instant.[[Nanoseconds]], roundingIncrement, smallestUnit, roundingMode). - let result = instant.inner.round(options)?; + let result = instant.borrow().data().inner.round(options)?; // 18. Return ! CreateTemporalInstant(roundedNs). create_temporal_instant(result, None, context) @@ -585,19 +547,13 @@ impl Instant { // 2. Perform ? RequireInternalSlot(instant, [[InitializedTemporalInstant]]). // 4. If instant.[[Nanoseconds]] ≠ other.[[Nanoseconds]], return false. // 5. Return true. - let object = this.as_object(); - let instant = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be an instant object.") - })?; + let instant = this.require_internal_slot::()?; // 3. Set other to ? ToTemporalInstant(other). let other = args.get_or_undefined(0); let other_instant = to_temporal_instant(other, context)?; - if *instant.inner != other_instant { + if *instant.borrow().data().inner != other_instant { return Ok(false.into()); } Ok(true.into()) @@ -615,14 +571,7 @@ impl Instant { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/Instant/toString /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.Instant.html#method.to_ixdtf_string fn to_string(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult { - let object = this.as_object(); - let instant = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ() - .with_message("the this object must be a Temporal.Instant object.") - })?; + let instant = this.require_internal_slot::()?; let options = get_options_object(args.get_or_undefined(0))?; @@ -642,11 +591,11 @@ impl Instant { rounding_mode, }; - let ixdtf = instant.inner.to_ixdtf_string_with_provider( - timezone, - options, - context.timezone_provider(), - )?; + let ixdtf = instant + .borrow() + .data() + .inner + .to_ixdtf_string_with_provider(timezone, options, context.timezone_provider())?; Ok(JsString::from(ixdtf).into()) } @@ -662,20 +611,17 @@ impl Instant { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/Instant/toLocaleString fn to_locale_string(this: &JsValue, _: &[JsValue], context: &mut Context) -> JsResult { // TODO: Update for ECMA-402 compliance - let object = this.as_object(); - let instant = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ() - .with_message("the this object must be a Temporal.Instant object.") - })?; - - let ixdtf = instant.inner.to_ixdtf_string_with_provider( - None, - ToStringRoundingOptions::default(), - context.timezone_provider(), - )?; + let instant = this.require_internal_slot::()?; + + let ixdtf = instant + .borrow() + .data() + .inner + .to_ixdtf_string_with_provider( + None, + ToStringRoundingOptions::default(), + context.timezone_provider(), + )?; Ok(JsString::from(ixdtf).into()) } @@ -689,20 +635,17 @@ impl Instant { /// [spec]: https://tc39.es/proposal-temporal/#sec-temporal.instant.tojson /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/Instant/toJSON fn to_json(this: &JsValue, _: &[JsValue], context: &mut Context) -> JsResult { - let object = this.as_object(); - let instant = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ() - .with_message("the this object must be a Temporal.Instant object.") - })?; - - let ixdtf = instant.inner.to_ixdtf_string_with_provider( - None, - ToStringRoundingOptions::default(), - context.timezone_provider(), - )?; + let instant = this.require_internal_slot::()?; + + let ixdtf = instant + .borrow() + .data() + .inner + .to_ixdtf_string_with_provider( + None, + ToStringRoundingOptions::default(), + context.timezone_provider(), + )?; Ok(JsString::from(ixdtf).into()) } @@ -739,20 +682,15 @@ impl Instant { ) -> JsResult { // 1. Let instant be the this value. // 2. Perform ? RequireInternalSlot(instant, [[InitializedTemporalInstant]]). - let object = this.as_object(); - let instant = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ() - .with_message("the this object must be a Temporal.Instant object.") - })?; + let instant = this.require_internal_slot::()?; // 3. Set timeZone to ? ToTemporalTimeZoneIdentifier(timeZone). let timezone = to_temporal_timezone_identifier(args.get_or_undefined(0), context)?; // 4. Return ! CreateTemporalZonedDateTime(instant.[[EpochNanoseconds]], timeZone, "iso8601"). let zdt = instant + .borrow() + .data() .inner .to_zoned_date_time_iso_with_provider(timezone, context.timezone_provider())?; create_temporal_zoneddatetime(zdt, None, context).map(Into::into) diff --git a/core/engine/src/builtins/temporal/plain_date/mod.rs b/core/engine/src/builtins/temporal/plain_date/mod.rs index e3a220ca78e..228290f1908 100644 --- a/core/engine/src/builtins/temporal/plain_date/mod.rs +++ b/core/engine/src/builtins/temporal/plain_date/mod.rs @@ -331,15 +331,9 @@ impl PlainDate { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/PlainDate/calendarId /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.PlainDate.html#method.calendar fn get_calendar_id(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { - let object = this.as_object(); - let date = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a PlainDate object.") - })?; - - Ok(JsString::from(date.inner.calendar().identifier()).into()) + let date = this.require_internal_slot::()?; + + Ok(JsString::from(date.borrow().data().inner.calendar().identifier()).into()) } /// 3.3.4 get `Temporal.PlainDate.prototype.era` @@ -801,15 +795,9 @@ impl PlainDate { ) -> JsResult { // 1. Let temporalDate be the this value. // 2. Perform ? RequireInternalSlot(temporalDate, [[InitializedTemporalDate]]). - let object = this.as_object(); - let date = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a PlainDate object.") - })?; - - let year_month = date.inner.to_plain_year_month()?; + let date = this.require_internal_slot::()?; + + let year_month = date.borrow().data().inner.to_plain_year_month()?; create_temporal_year_month(year_month, None, context) } @@ -831,15 +819,9 @@ impl PlainDate { ) -> JsResult { // 1. Let temporalDate be the this value. // 2. Perform ? RequireInternalSlot(temporalDate, [[InitializedTemporalDate]]). - let object = this.as_object(); - let date = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a PlainDate object.") - })?; - - let month_day = date.inner.to_plain_month_day()?; + let date = this.require_internal_slot::()?; + + let month_day = date.borrow().data().inner.to_plain_month_day()?; create_temporal_month_day(month_day, None, context) } @@ -857,13 +839,7 @@ impl PlainDate { fn add(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult { // 1. Let temporalDate be the this value. // 2. Perform ? RequireInternalSlot(temporalDate, [[InitializedTemporalDate]]). - let object = this.as_object(); - let date = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a PlainDate object.") - })?; + let date = this.require_internal_slot::()?; // 3. Let duration be ? ToTemporalDuration(temporalDurationLike). let duration = to_temporal_duration_record(args.get_or_undefined(0), context)?; @@ -875,7 +851,7 @@ impl PlainDate { // 5. Let calendarRec be ? CreateCalendarMethodsRecord(temporalDate.[[Calendar]], « date-add »). // 6. Return ? AddDate(calendarRec, temporalDate, duration, options). - let resolved_date = date.inner.add(&duration, overflow)?; + let resolved_date = date.borrow().data().inner.add(&duration, overflow)?; create_temporal_date(resolved_date, None, context).map(Into::into) } @@ -893,13 +869,7 @@ impl PlainDate { fn subtract(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult { // 1. Let temporalDate be the this value. // 2. Perform ? RequireInternalSlot(temporalDate, [[InitializedTemporalDate]]). - let object = this.as_object(); - let date = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a PlainDate object.") - })?; + let date = this.require_internal_slot::()?; // 3. Let duration be ? ToTemporalDuration(temporalDurationLike). let duration = to_temporal_duration_record(args.get_or_undefined(0), context)?; @@ -911,7 +881,7 @@ impl PlainDate { // 5. Let negatedDuration be CreateNegatedTemporalDuration(duration). // 6. Let calendarRec be ? CreateCalendarMethodsRecord(temporalDate.[[Calendar]], « date-add »). // 7. Return ? AddDate(calendarRec, temporalDate, negatedDuration, options). - let resolved_date = date.inner.subtract(&duration, overflow)?; + let resolved_date = date.borrow().data().inner.subtract(&duration, overflow)?; create_temporal_date(resolved_date, None, context).map(Into::into) } @@ -929,13 +899,7 @@ impl PlainDate { fn with(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult { // 1. Let temporalDate be the this value. // 2. Perform ? RequireInternalSlot(temporalDate, [[InitializedTemporalDate]]). - let object = this.as_object(); - let date = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a PlainDate object.") - })?; + let date = this.require_internal_slot::()?; // 3. If ? IsPartialTemporalObject(temporalDateLike) is false, throw a TypeError exception. let Some(partial_object) = @@ -951,7 +915,11 @@ impl PlainDate { // 5. Let fields be ISODateToFields(calendar, temporalDate.[[ISODate]], date). // 6. Let partialDate be ? PrepareCalendarFields(calendar, temporalDateLike, « year, month, month-code, day », « », partial). // 7. Set fields to CalendarMergeFields(calendar, fields, partialDate). - let fields = to_calendar_fields(&partial_object, date.inner.calendar(), context)?; + let fields = to_calendar_fields( + &partial_object, + date.borrow().data().inner.calendar(), + context, + )?; // 8. Let resolvedOptions be ? GetOptionsObject(options). let options = get_options_object(args.get_or_undefined(1))?; @@ -959,7 +927,7 @@ impl PlainDate { let overflow = get_option::(&options, js_string!("overflow"), context)?; // 10. Return ? CalendarDateFromFields(calendarRec, fields, resolvedOptions). - let resolved_date = date.inner.with(fields, overflow)?; + let resolved_date = date.borrow().data().inner.with(fields, overflow)?; create_temporal_date(resolved_date, None, context).map(Into::into) } @@ -977,19 +945,13 @@ impl PlainDate { /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.PlainDate.html#method.with_calendar fn with_calendar(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult { // 1. Let plainDate be the this value. - let object = this.as_object(); // 2. Perform ? RequireInternalSlot(plainDate, [[InitializedTemporalDate]]). - let date = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a PlainDate object.") - })?; + let date = this.require_internal_slot::()?; // 3. Let calendar be ? ToTemporalCalendarIdentifier(calendarLike). let calendar = to_temporal_calendar_identifier(args.get_or_undefined(0))?; // 4. Return ! CreateTemporalDate(plainDate.[[ISODate]], calendar). - let resolved_date = date.inner.with_calendar(calendar); + let resolved_date = date.borrow().data().inner.with_calendar(calendar); create_temporal_date(resolved_date, None, context).map(Into::into) } @@ -1007,13 +969,7 @@ impl PlainDate { fn until(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult { // 1. Let temporalDate be the this value. // 2. Perform ? RequireInternalSlot(temporalDate, [[InitializedTemporalDate]]). - let object = this.as_object(); - let date = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a PlainDate object.") - })?; + let date = this.require_internal_slot::()?; let other = to_temporal_date(args.get_or_undefined(0), None, context)?; @@ -1021,7 +977,12 @@ impl PlainDate { let options = get_options_object(args.get_or_undefined(1))?; let settings = get_difference_settings(&options, context)?; - create_temporal_duration(date.inner.until(&other, settings)?, None, context).map(Into::into) + create_temporal_duration( + date.borrow().data().inner.until(&other, settings)?, + None, + context, + ) + .map(Into::into) } /// 3.3.26 `Temporal.PlainDate.prototype.since ( other [ , options ] )` @@ -1038,13 +999,7 @@ impl PlainDate { fn since(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult { // 1. Let temporalDate be the this value. // 2. Perform ? RequireInternalSlot(temporalDate, [[InitializedTemporalDate]]). - let object = this.as_object(); - let date = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a PlainDate object.") - })?; + let date = this.require_internal_slot::()?; // 3. Return ? DifferenceTemporalPlainDate(since, temporalDate, other, options). let other = to_temporal_date(args.get_or_undefined(0), None, context)?; @@ -1052,7 +1007,12 @@ impl PlainDate { let options = get_options_object(args.get_or_undefined(1))?; let settings = get_difference_settings(&options, context)?; - create_temporal_duration(date.inner.since(&other, settings)?, None, context).map(Into::into) + create_temporal_duration( + date.borrow().data().inner.since(&other, settings)?, + None, + context, + ) + .map(Into::into) } /// 3.3.27 `Temporal.PlainDate.prototype.equals ( other )` @@ -1067,17 +1027,11 @@ impl PlainDate { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/PlainDate/equals /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.PlainDate.html#impl-Eq-for-PlainDate fn equals(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult { - let object = this.as_object(); - let date = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a PlainDate object.") - })?; + let date = this.require_internal_slot::()?; let other = to_temporal_date(args.get_or_undefined(0), None, context)?; - Ok((date.inner == other).into()) + Ok((date.borrow().data().inner == other).into()) } /// 3.3.28 `Temporal.PlainDate.prototype.toPlainDateTime ( [ temporalTime ] )` @@ -1098,13 +1052,7 @@ impl PlainDate { ) -> JsResult { // 1. Let temporalDate be the this value. // 2. Perform ? RequireInternalSlot(temporalDate, [[InitializedTemporalDate]]). - let object = this.as_object(); - let date = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a PlainDate object.") - })?; + let date = this.require_internal_slot::()?; // 3. Set temporalTime to ? ToTemporalTimeOrMidnight(temporalTime). let time = args @@ -1112,8 +1060,12 @@ impl PlainDate { .map(|v| to_temporal_time(v, None, context)) .transpose()?; // 4. Return ? CreateTemporalDateTime(temporalDate.[[ISOYear]], temporalDate.[[ISOMonth]], temporalDate.[[ISODay]], temporalTime.[[ISOHour]], temporalTime.[[ISOMinute]], temporalTime.[[ISOSecond]], temporalTime.[[ISOMillisecond]], temporalTime.[[ISOMicrosecond]], temporalTime.[[ISONanosecond]], temporalDate.[[Calendar]]). - create_temporal_datetime(date.inner.to_plain_date_time(time)?, None, context) - .map(Into::into) + create_temporal_datetime( + date.borrow().data().inner.to_plain_date_time(time)?, + None, + context, + ) + .map(Into::into) } /// 3.3.29 `Temporal.PlainDate.prototype.toZonedDateTime ( item )` @@ -1134,13 +1086,7 @@ impl PlainDate { ) -> JsResult { // 1. Let temporalDate be the this value. // 2. Perform ? RequireInternalSlot(temporalDate, [[InitializedTemporalDate]]). - let object = this.as_object(); - let date = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a PlainDate object.") - })?; + let date = this.require_internal_slot::()?; let item = args.get_or_undefined(0); // 3. If item is an Object, then @@ -1174,11 +1120,11 @@ impl PlainDate { (to_temporal_timezone_identifier(item, context)?, None) }; - let result = date.inner.to_zoned_date_time_with_provider( - timezone, - time, - context.timezone_provider(), - )?; + let result = date + .borrow() + .data() + .inner + .to_zoned_date_time_with_provider(timezone, time, context.timezone_provider())?; // 7. Return ! CreateTemporalZonedDateTime(epochNs, timeZone, temporalDate.[[Calendar]]). create_temporal_zoneddatetime(result, None, context).map(Into::into) @@ -1196,19 +1142,13 @@ impl PlainDate { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/PlainDate/toString /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.PlainDate.html#method.to_ixdtf_string fn to_string(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult { - let object = this.as_object(); - let date = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a PlainDate object.") - })?; + let date = this.require_internal_slot::()?; let options = get_options_object(args.get_or_undefined(0))?; let display_calendar = get_option::(&options, js_string!("calendarName"), context)? .unwrap_or(DisplayCalendar::Auto); - Ok(JsString::from(date.inner.to_ixdtf_string(display_calendar)).into()) + Ok(JsString::from(date.borrow().data().inner.to_ixdtf_string(display_calendar)).into()) } /// 3.3.31 `Temporal.PlainDate.prototype.toLocaleString ( [ locales [ , options ] ] )` @@ -1222,15 +1162,9 @@ impl PlainDate { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/PlainDate/toLocaleString fn to_locale_string(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { // TODO: Update for ECMA-402 compliance - let object = this.as_object(); - let date = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a PlainDate object.") - })?; - - Ok(JsString::from(date.inner.to_string()).into()) + let date = this.require_internal_slot::()?; + + Ok(JsString::from(date.borrow().data().inner.to_string()).into()) } /// 3.3.32 `Temporal.PlainDate.prototype.toJSON ( )` @@ -1243,15 +1177,9 @@ impl PlainDate { /// [spec]: https://tc39.es/proposal-temporal/#sec-temporal.plaindate.prototype.toJSON /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/PlainDate/toJSON fn to_json(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { - let object = this.as_object(); - let date = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a PlainDate object.") - })?; - - Ok(JsString::from(date.inner.to_string()).into()) + let date = this.require_internal_slot::()?; + + Ok(JsString::from(date.borrow().data().inner.to_string()).into()) } /// 3.3.33 `Temporal.PlainDate.prototype.valueOf ( )` diff --git a/core/engine/src/builtins/temporal/plain_date_time/mod.rs b/core/engine/src/builtins/temporal/plain_date_time/mod.rs index 4270df4f84e..7a94a43c6a7 100644 --- a/core/engine/src/builtins/temporal/plain_date_time/mod.rs +++ b/core/engine/src/builtins/temporal/plain_date_time/mod.rs @@ -487,15 +487,9 @@ impl PlainDateTime { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/PlainDateTime/calendarId /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.PlainDateTime.html#method.calendar fn get_calendar_id(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { - let object = this.as_object(); - let dt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a PlainDateTime object.") - })?; + let dt = this.require_internal_slot::()?; - Ok(JsString::from(dt.inner.calendar().identifier()).into()) + Ok(JsString::from(dt.borrow().data().inner.calendar().identifier()).into()) } /// 5.3.4 get `Temporal.PlainDateTime.prototype.era` @@ -510,15 +504,11 @@ impl PlainDateTime { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/PlainDateTime/era /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.PlainDateTime.html#method.era fn get_era(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { - let object = this.as_object(); - let dt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a PlainDateTime object.") - })?; + let dt = this.require_internal_slot::()?; Ok(dt + .borrow() + .data() .inner .era() .map(|s| JsString::from(s.as_str())) @@ -537,15 +527,9 @@ impl PlainDateTime { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/PlainDateTime/eraYear /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.PlainDateTime.html#method.era_year fn get_era_year(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { - let object = this.as_object(); - let dt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a PlainDateTime object.") - })?; + let dt = this.require_internal_slot::()?; - Ok(dt.inner.era_year().into_or_undefined()) + Ok(dt.borrow().data().inner.era_year().into_or_undefined()) } /// 5.3.6 get `Temporal.PlainDateTime.prototype.year` @@ -560,15 +544,9 @@ impl PlainDateTime { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/PlainDateTime/year /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.PlainDateTime.html#method.year fn get_year(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { - let object = this.as_object(); - let dt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a PlainDateTime object.") - })?; + let dt = this.require_internal_slot::()?; - Ok(dt.inner.year().into()) + Ok(dt.borrow().data().inner.year().into()) } /// 5.3.7 get `Temporal.PlainDateTime.prototype.month` @@ -583,15 +561,9 @@ impl PlainDateTime { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/PlainDateTime/month /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.PlainDateTime.html fn get_month(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { - let object = this.as_object(); - let dt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a PlainDateTime object.") - })?; + let dt = this.require_internal_slot::()?; - Ok(dt.inner.month().into()) + Ok(dt.borrow().data().inner.month().into()) } /// 5.3.8 get `Temporal.PlainDateTime.prototype.monthCode` @@ -606,15 +578,9 @@ impl PlainDateTime { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/PlainDateTime/monthCode /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.PlainDateTime.html#method.month_code fn get_month_code(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { - let object = this.as_object(); - let dt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a PlainDateTime object.") - })?; + let dt = this.require_internal_slot::()?; - Ok(JsString::from(dt.inner.month_code().as_str()).into()) + Ok(JsString::from(dt.borrow().data().inner.month_code().as_str()).into()) } /// 5.3.9 get `Temporal.PlainDateTime.prototype.day` @@ -629,15 +595,9 @@ impl PlainDateTime { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/PlainDateTime/day /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.PlainDateTime.html#method.day fn get_day(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { - let object = this.as_object(); - let dt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a PlainDateTime object.") - })?; + let dt = this.require_internal_slot::()?; - Ok(dt.inner.day().into()) + Ok(dt.borrow().data().inner.day().into()) } /// 5.3.10 get `Temporal.PlainDateTime.prototype.hour` @@ -654,16 +614,10 @@ impl PlainDateTime { fn get_hour(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { // 1. Let dateTime be the this value. // 2. Perform ? RequireInternalSlot(dateTime, [[InitializedTemporalDateTime]]). - let object = this.as_object(); - let dt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a PlainDateTime object.") - })?; + let dt = this.require_internal_slot::()?; // 3. Return 𝔽(datedt.[[ISOHour]]). - Ok(dt.inner.hour().into()) + Ok(dt.borrow().data().inner.hour().into()) } /// 5.3.11 get `Temporal.PlainDateTime.prototype.minute` @@ -680,16 +634,10 @@ impl PlainDateTime { fn get_minute(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { // 1. Let dateTime be the this value. // 2. Perform ? RequireInternalSlot(dateTime, [[InitializedTemporalDateTime]]). - let object = this.as_object(); - let dt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a PlainDateTime object.") - })?; + let dt = this.require_internal_slot::()?; // 3. Return 𝔽(datedt.[[ISOMinute]]). - Ok(dt.inner.minute().into()) + Ok(dt.borrow().data().inner.minute().into()) } /// 5.3.12 get `Temporal.PlainDateTime.prototype.second` @@ -706,16 +654,10 @@ impl PlainDateTime { fn get_second(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { // 1. Let dateTime be the this value. // 2. Perform ? RequireInternalSlot(dateTime, [[InitializedTemporalDateTime]]). - let object = this.as_object(); - let dt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a PlainDateTime object.") - })?; + let dt = this.require_internal_slot::()?; // 3. Return 𝔽(datedt.[[ISOSecond]]). - Ok(dt.inner.second().into()) + Ok(dt.borrow().data().inner.second().into()) } /// 5.3.13 get `Temporal.PlainDateTime.prototype.millisecond` @@ -732,16 +674,10 @@ impl PlainDateTime { fn get_millisecond(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { // 1. Let dateTime be the this value. // 2. Perform ? RequireInternalSlot(dateTime, [[InitializedTemporalDateTime]]). - let object = this.as_object(); - let dt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a PlainDateTime object.") - })?; + let dt = this.require_internal_slot::()?; // 3. Return 𝔽(datedt.[[ISOMillisecond]]). - Ok(dt.inner.millisecond().into()) + Ok(dt.borrow().data().inner.millisecond().into()) } /// 5.3.14 get `Temporal.PlainDateTime.prototype.microsecond` @@ -758,16 +694,10 @@ impl PlainDateTime { fn get_microsecond(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { // 1. Let dateTime be the this value. // 2. Perform ? RequireInternalSlot(dateTime, [[InitializedTemporalDateTime]]). - let object = this.as_object(); - let dt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a PlainDateTime object.") - })?; + let dt = this.require_internal_slot::()?; // 3. Return 𝔽(datedt.[[ISOMicrosecond]]). - Ok(dt.inner.microsecond().into()) + Ok(dt.borrow().data().inner.microsecond().into()) } /// 5.3.15 get `Temporal.PlainDateTime.prototype.nanosecond` @@ -784,16 +714,10 @@ impl PlainDateTime { fn get_nanosecond(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { // 1. Let dateTime be the this value. // 2. Perform ? RequireInternalSlot(dateTime, [[InitializedTemporalDateTime]]). - let object = this.as_object(); - let dt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a PlainDateTime object.") - })?; + let dt = this.require_internal_slot::()?; // 3. Return 𝔽(datedt.[[ISONanosecond]]). - Ok(dt.inner.nanosecond().into()) + Ok(dt.borrow().data().inner.nanosecond().into()) } /// 5.3.16 get `Temporal.PlainDateTime.prototype.dayOfWeek` @@ -808,15 +732,9 @@ impl PlainDateTime { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/PlainDateTime/dayOfWeek /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.PlainDateTime.html#method.day_of_week fn get_day_of_week(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { - let object = this.as_object(); - let dt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a PlainDateTime object.") - })?; + let dt = this.require_internal_slot::()?; - Ok(dt.inner.day_of_week().into()) + Ok(dt.borrow().data().inner.day_of_week().into()) } /// 5.3.17 get `Temporal.PlainDateTime.prototype.dayOfYear` @@ -831,15 +749,9 @@ impl PlainDateTime { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/PlainDateTime/dayOfYear /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.PlainDateTime.html#method.day_of_year fn get_day_of_year(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { - let object = this.as_object(); - let dt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a PlainDateTime object.") - })?; + let dt = this.require_internal_slot::()?; - Ok(dt.inner.day_of_year().into()) + Ok(dt.borrow().data().inner.day_of_year().into()) } /// 5.3.18 get `Temporal.PlainDateTime.prototype.weekOfYear` @@ -854,15 +766,9 @@ impl PlainDateTime { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/PlainDateTime/weekOfYear /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.PlainDateTime.html#method.week_of_year fn get_week_of_year(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { - let object = this.as_object(); - let dt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a PlainDateTime object.") - })?; + let dt = this.require_internal_slot::()?; - Ok(dt.inner.week_of_year().into_or_undefined()) + Ok(dt.borrow().data().inner.week_of_year().into_or_undefined()) } /// 5.3.19 get `Temporal.PlainDateTime.prototype.yearOfWeek` @@ -877,15 +783,9 @@ impl PlainDateTime { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/PlainDateTime/yearOfWeek /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.PlainDateTime.html#method.year_of_week fn get_year_of_week(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { - let object = this.as_object(); - let dt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a PlainDateTime object.") - })?; + let dt = this.require_internal_slot::()?; - Ok(dt.inner.year_of_week().into_or_undefined()) + Ok(dt.borrow().data().inner.year_of_week().into_or_undefined()) } /// 5.3.20 get `Temporal.PlainDateTime.prototype.daysInWeek` @@ -900,15 +800,9 @@ impl PlainDateTime { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/PlainDateTime/daysInWeek /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.PlainDateTime.html#method.days_in_week fn get_days_in_week(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { - let object = this.as_object(); - let dt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a PlainDateTime object.") - })?; + let dt = this.require_internal_slot::()?; - Ok(dt.inner.days_in_week().into()) + Ok(dt.borrow().data().inner.days_in_week().into()) } /// 5.3.21 get `Temporal.PlainDateTime.prototype.daysInMonth` @@ -923,15 +817,9 @@ impl PlainDateTime { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/PlainDateTime/daysInMonth /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.PlainDateTime.html#method.days_in_month fn get_days_in_month(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { - let object = this.as_object(); - let dt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a PlainDateTime object.") - })?; + let dt = this.require_internal_slot::()?; - Ok(dt.inner.days_in_month().into()) + Ok(dt.borrow().data().inner.days_in_month().into()) } /// 5.3.22 get `Temporal.PlainDateTime.prototype.daysInYear` @@ -946,15 +834,9 @@ impl PlainDateTime { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/PlainDateTime/daysInYear /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.PlainDateTime.html#method.days_in_year fn get_days_in_year(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { - let object = this.as_object(); - let dt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a PlainDateTime object.") - })?; + let dt = this.require_internal_slot::()?; - Ok(dt.inner.days_in_year().into()) + Ok(dt.borrow().data().inner.days_in_year().into()) } /// 5.3.23 get `Temporal.PlainDateTime.prototype.monthsInYear` @@ -969,15 +851,9 @@ impl PlainDateTime { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/PlainDateTime/monthsInYear /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.PlainDateTime.html#method.months_in_year fn get_months_in_year(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { - let object = this.as_object(); - let dt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a PlainDateTime object.") - })?; + let dt = this.require_internal_slot::()?; - Ok(dt.inner.months_in_year().into()) + Ok(dt.borrow().data().inner.months_in_year().into()) } /// 5.3.24 get `Temporal.PlainDateTime.prototype.inLeapYear` @@ -992,15 +868,9 @@ impl PlainDateTime { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/PlainDateTime/inLeapYear /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.PlainDateTime.html#method.in_leap_year fn get_in_leap_year(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { - let object = this.as_object(); - let dt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a PlainDateTime object.") - })?; + let dt = this.require_internal_slot::()?; - Ok(dt.inner.in_leap_year().into()) + Ok(dt.borrow().data().inner.in_leap_year().into()) } } @@ -1082,13 +952,7 @@ impl PlainDateTime { fn with(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult { // 1. Let plainDateTime be the this value. // 2. Perform ? RequireInternalSlot(plainDateTime, [[InitializedTemporalDateTime]]). - let object = this.as_object(); - let dt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a PlainDateTime object.") - })?; + let dt = this.require_internal_slot::()?; // 3. If ? IsPartialTemporalObject(temporalDateTimeLike) is false, throw a TypeError exception. let Some(partial_object) = @@ -1108,7 +972,11 @@ impl PlainDateTime { // 11. Set fields.[[Nanosecond]] to plainDateTime.[[ISODateTime]].[[Time]].[[Nanosecond]]. // 12. Let partialDateTime be ? PrepareCalendarFields(calendar, temporalDateTimeLike, « year, month, month-code, day », « hour, minute, second, millisecond, microsecond, nanosecond », partial). // 13. Set fields to CalendarMergeFields(calendar, fields, partialDateTime). - let fields = to_date_time_fields(&partial_object, dt.inner.calendar(), context)?; + let fields = to_date_time_fields( + &partial_object, + dt.borrow().data().inner.calendar(), + context, + )?; // 14. Let resolvedOptions be ? GetOptionsObject(options). let options = get_options_object(args.get_or_undefined(1))?; // 15. Let overflow be ? GetTemporalOverflowOption(resolvedOptions). @@ -1116,7 +984,12 @@ impl PlainDateTime { // 16. Let result be ? InterpretTemporalDateTimeFields(calendar, fields, overflow). // 17. Return ? CreateTemporalDateTime(result, calendar). - create_temporal_datetime(dt.inner.with(fields, overflow)?, None, context).map(Into::into) + create_temporal_datetime( + dt.borrow().data().inner.with(fields, overflow)?, + None, + context, + ) + .map(Into::into) } /// 5.3.26 Temporal.PlainDateTime.prototype.withPlainTime ( `[ plainTimeLike ]` ) @@ -1135,20 +1008,15 @@ impl PlainDateTime { args: &[JsValue], context: &mut Context, ) -> JsResult { - let object = this.as_object(); - let dt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a PlainDateTime object.") - })?; + let dt = this.require_internal_slot::()?; let time = args .get_or_undefined(0) .map(|v| to_temporal_time(v, None, context)) .transpose()?; - create_temporal_datetime(dt.inner.with_time(time)?, None, context).map(Into::into) + create_temporal_datetime(dt.borrow().data().inner.with_time(time)?, None, context) + .map(Into::into) } /// 5.3.27 `Temporal.PlainDateTime.prototype.withCalendar ( calendarLike )` @@ -1163,17 +1031,16 @@ impl PlainDateTime { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/PlainDateTime/withCalendar /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.PlainDateTime.html#method.with_calendar fn with_calendar(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult { - let object = this.as_object(); - let dt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a PlainDateTime object.") - })?; + let dt = this.require_internal_slot::()?; let calendar = to_temporal_calendar_identifier(args.get_or_undefined(0))?; - create_temporal_datetime(dt.inner.with_calendar(calendar), None, context).map(Into::into) + create_temporal_datetime( + dt.borrow().data().inner.with_calendar(calendar), + None, + context, + ) + .map(Into::into) } /// 5.3.28 `Temporal.PlainDateTime.prototype.add ( temporalDurationLike [ , options ] )` @@ -1190,13 +1057,7 @@ impl PlainDateTime { fn add(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult { // 1. Let temporalDate be the this value. // 2. Perform ? RequireInternalSlot(temporalDate, [[InitializedTemporalDate]]). - let object = this.as_object(); - let dt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a PlainDateTime object.") - })?; + let dt = this.require_internal_slot::()?; // 3. Let duration be ? ToTemporalDuration(temporalDurationLike). let duration = to_temporal_duration_record(args.get_or_undefined(0), context)?; @@ -1207,7 +1068,12 @@ impl PlainDateTime { // 5. Let calendarRec be ? CreateCalendarMethodsRecord(temporalDate.[[Calendar]], « date-add »). // 6. Return ? AddDate(calendarRec, temporalDate, duration, options). - create_temporal_datetime(dt.inner.add(&duration, overflow)?, None, context).map(Into::into) + create_temporal_datetime( + dt.borrow().data().inner.add(&duration, overflow)?, + None, + context, + ) + .map(Into::into) } /// 5.3.29 `Temporal.PlainDateTime.prototype.subtract ( temporalDurationLike [ , options ] )` @@ -1224,13 +1090,7 @@ impl PlainDateTime { fn subtract(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult { // 1. Let temporalDate be the this value. // 2. Perform ? RequireInternalSlot(temporalDate, [[InitializedTemporalDate]]). - let object = this.as_object(); - let dt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a PlainDateTime object.") - })?; + let dt = this.require_internal_slot::()?; // 3. Let duration be ? ToTemporalDuration(temporalDurationLike). let duration = to_temporal_duration_record(args.get_or_undefined(0), context)?; @@ -1242,8 +1102,12 @@ impl PlainDateTime { // 5. Let negatedDuration be CreateNegatedTemporalDuration(duration). // 6. Let calendarRec be ? CreateCalendarMethodsRecord(temporalDate.[[Calendar]], « date-add »). // 7. Return ? AddDate(calendarRec, temporalDate, negatedDuration, options). - create_temporal_datetime(dt.inner.subtract(&duration, overflow)?, None, context) - .map(Into::into) + create_temporal_datetime( + dt.borrow().data().inner.subtract(&duration, overflow)?, + None, + context, + ) + .map(Into::into) } /// 5.3.30 `Temporal.PlainDateTime.prototype.until ( other [ , options ] )` @@ -1258,20 +1122,19 @@ impl PlainDateTime { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/PlainDateTime/until /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.PlainDateTime.html#method.until fn until(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult { - let object = this.as_object(); - let dt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a PlainDateTime object.") - })?; + let dt = this.require_internal_slot::()?; let other = to_temporal_datetime(args.get_or_undefined(0), None, context)?; let options = get_options_object(args.get_or_undefined(1))?; let settings = get_difference_settings(&options, context)?; - create_temporal_duration(dt.inner.until(&other, settings)?, None, context).map(Into::into) + create_temporal_duration( + dt.borrow().data().inner.until(&other, settings)?, + None, + context, + ) + .map(Into::into) } /// 5.3.31 `Temporal.PlainDateTime.prototype.since ( other [ , options ] )` @@ -1286,20 +1149,19 @@ impl PlainDateTime { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/PlainDateTime/since /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.PlainDateTime.html#method.since fn since(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult { - let object = this.as_object(); - let dt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a PlainDateTime object.") - })?; + let dt = this.require_internal_slot::()?; let other = to_temporal_datetime(args.get_or_undefined(0), None, context)?; let options = get_options_object(args.get_or_undefined(1))?; let settings = get_difference_settings(&options, context)?; - create_temporal_duration(dt.inner.since(&other, settings)?, None, context).map(Into::into) + create_temporal_duration( + dt.borrow().data().inner.since(&other, settings)?, + None, + context, + ) + .map(Into::into) } /// 5.3.32 Temporal.PlainDateTime.prototype.round ( roundTo ) @@ -1314,13 +1176,7 @@ impl PlainDateTime { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/PlainDateTime/round /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.PlainDateTime.html#method.round fn round(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult { - let object = this.as_object(); - let dt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a PlainTime object.") - })?; + let dt = this.require_internal_slot::()?; // 3. If roundTo is undefined, then let round_to_arg = args.get_or_undefined(0); @@ -1366,7 +1222,8 @@ impl PlainDateTime { context, )?; - create_temporal_datetime(dt.inner().round(options)?, None, context).map(Into::into) + create_temporal_datetime(dt.borrow().data().inner().round(options)?, None, context) + .map(Into::into) } /// 5.3.33 Temporal.PlainDateTime.prototype.equals ( other ) @@ -1383,13 +1240,7 @@ impl PlainDateTime { fn equals(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult { // 1. Let dateTime be the this value. // 2. Perform ? RequireInternalSlot(dateTime, [[InitializedTemporalDateTime]]). - let object = this.as_object(); - let dt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a PlainDateTime object.") - })?; + let dt = this.require_internal_slot::()?; // 3. Set other to ? ToTemporalDateTime(other). let other = to_temporal_datetime(args.get_or_undefined(0), None, context)?; @@ -1402,7 +1253,7 @@ impl PlainDateTime { // other.[[ISOMicrosecond]], other.[[ISONanosecond]]). // 5. If result is not 0, return false. // 6. Return ? CalendarEquals(dateTime.[[Calendar]], other.[[Calendar]]). - Ok((dt.inner == other).into()) + Ok((dt.borrow().data().inner == other).into()) } /// 5.3.34 `Temporal.PlainDateTime.prototype.toString ( [ options ] )` @@ -1417,13 +1268,7 @@ impl PlainDateTime { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/PlainDateTime/with /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.PlainDateTime.html#method.to_ixdtf_string fn to_string(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult { - let object = this.as_object(); - let dt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a PlainDateTime object.") - })?; + let dt = this.require_internal_slot::()?; let options = get_options_object(args.get_or_undefined(0))?; @@ -1435,7 +1280,7 @@ impl PlainDateTime { get_option::(&options, js_string!("roundingMode"), context)?; let smallest_unit = get_option::(&options, js_string!("smallestUnit"), context)?; - let ixdtf = dt.inner.to_ixdtf_string( + let ixdtf = dt.borrow().data().inner.to_ixdtf_string( ToStringRoundingOptions { precision, smallest_unit, @@ -1457,15 +1302,11 @@ impl PlainDateTime { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/PlainDateTime/with fn to_locale_string(this: &JsValue, _args: &[JsValue], _: &mut Context) -> JsResult { // TODO: Update for ECMA-402 compliance - let object = this.as_object(); - let dt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a PlainDateTime object.") - })?; + let dt = this.require_internal_slot::()?; let ixdtf = dt + .borrow() + .data() .inner .to_ixdtf_string(ToStringRoundingOptions::default(), DisplayCalendar::Auto)?; Ok(JsString::from(ixdtf).into()) @@ -1481,15 +1322,11 @@ impl PlainDateTime { /// [spec]: https://tc39.es/proposal-temporal/#sec-temporal.plaindatetime.prototype.with /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/PlainDateTime/with fn to_json(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { - let object = this.as_object(); - let dt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a PlainDateTime object.") - })?; + let dt = this.require_internal_slot::()?; let ixdtf = dt + .borrow() + .data() .inner .to_ixdtf_string(ToStringRoundingOptions::default(), DisplayCalendar::Auto)?; Ok(JsString::from(ixdtf).into()) @@ -1528,13 +1365,7 @@ impl PlainDateTime { ) -> JsResult { // 1. Let dateTime be the this value. // 2. Perform ? RequireInternalSlot(dateTime, [[InitializedTemporalDateTime]]). - let object = this.as_object(); - let dt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a PlainDateTime object.") - })?; + let dt = this.require_internal_slot::()?; // 3. Let timeZone be ? ToTemporalTimeZoneIdentifier(temporalTimeZoneLike). let timezone = to_temporal_timezone_identifier(args.get_or_undefined(0), context)?; // 4. Let resolvedOptions be ? GetOptionsObject(options). @@ -1547,7 +1378,7 @@ impl PlainDateTime { // 6. Let epochNs be ? GetEpochNanosecondsFor(timeZone, dateTime.[[ISODateTime]], disambiguation). // 7. Return ! CreateTemporalZonedDateTime(epochNs, timeZone, dateTime.[[Calendar]]). - let result = dt.inner.to_zoned_date_time_with_provider( + let result = dt.borrow().data().inner.to_zoned_date_time_with_provider( timezone, disambiguation, context.timezone_provider(), @@ -1567,15 +1398,9 @@ impl PlainDateTime { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/PlainDateTime/toPlainDate /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.PlainDateTime.html#method.to_plain_date fn to_plain_date(this: &JsValue, _: &[JsValue], context: &mut Context) -> JsResult { - let object = this.as_object(); - let dt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a PlainDateTime object.") - })?; + let dt = this.require_internal_slot::()?; - let result = dt.inner.to_plain_date(); + let result = dt.borrow().data().inner.to_plain_date(); create_temporal_date(result, None, context).map(Into::into) } @@ -1591,15 +1416,9 @@ impl PlainDateTime { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/PlainDateTime/toPlainTime /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.PlainDateTime.html#method.to_plain_time fn to_plain_time(this: &JsValue, _: &[JsValue], context: &mut Context) -> JsResult { - let object = this.as_object(); - let dt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a PlainDateTime object.") - })?; + let dt = this.require_internal_slot::()?; - let result = dt.inner.to_plain_time(); + let result = dt.borrow().data().inner.to_plain_time(); create_temporal_time(result, None, context).map(Into::into) } } diff --git a/core/engine/src/builtins/temporal/plain_month_day/mod.rs b/core/engine/src/builtins/temporal/plain_month_day/mod.rs index dde472d2a2b..aaa952264ba 100644 --- a/core/engine/src/builtins/temporal/plain_month_day/mod.rs +++ b/core/engine/src/builtins/temporal/plain_month_day/mod.rs @@ -192,14 +192,9 @@ impl PlainMonthDay { impl PlainMonthDay { // Helper for retrieving internal fields fn get_internal_field(this: &JsValue, field: &DateTimeValues) -> JsResult { - let object = this.as_object(); - let month_day = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("this value must be a PlainMonthDay object.") - })?; - let inner = &month_day.inner; + let month_day = this.require_internal_slot::()?; + let month_day_data = month_day.borrow(); + let inner = &month_day_data.data().inner; match field { DateTimeValues::Day => Ok(inner.day().into()), DateTimeValues::MonthCode => Ok(js_string!(inner.month_code().as_str()).into()), @@ -219,14 +214,8 @@ impl PlainMonthDay { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/PlainMonthDay/calendarId /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.PlainMonthDay.html#method.calendar fn get_calendar_id(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { - let object = this.as_object(); - let month_day = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("this value must be a PlainMonthDay object.") - })?; - Ok(js_string!(month_day.inner.calendar().identifier()).into()) + let month_day = this.require_internal_slot::()?; + Ok(js_string!(month_day.borrow().data().inner.calendar().identifier()).into()) } /// 10.3.4 get `Temporal.PlainMonthDay.prototype.day` @@ -277,13 +266,7 @@ impl PlainMonthDay { fn with(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult { // 1. Let monthDay be the this value. // 2. Perform ? RequireInternalSlot(monthDay, [[InitializedTemporalMonthDay]]). - let object = this.as_object(); - let month_day = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("this value must be a PlainMonthDay object.") - })?; + let month_day = this.require_internal_slot::()?; // 3. If ? IsPartialTemporalObject(temporalMonthDayLike) is false, throw a TypeError exception. let Some(object) = is_partial_temporal_object(args.get_or_undefined(0), context)? else { @@ -294,7 +277,8 @@ impl PlainMonthDay { // 4. Let calendar be monthDay.[[Calendar]]. // 5. Let fields be ISODateToFields(calendar, monthDay.[[ISODate]], month-day). // 6. Let partialMonthDay be ? PrepareCalendarFields(calendar, temporalMonthDayLike, « year, month, month-code, day », « », partial). - let fields = to_calendar_fields(&object, month_day.inner.calendar(), context)?; + let fields = + to_calendar_fields(&object, month_day.borrow().data().inner.calendar(), context)?; // 7. Set fields to CalendarMergeFields(calendar, fields, partialMonthDay). // 8. Let resolvedOptions be ? GetOptionsObject(options). let resolved_options = get_options_object(args.get_or_undefined(1))?; @@ -302,7 +286,11 @@ impl PlainMonthDay { let overflow = get_option::(&resolved_options, js_string!("overflow"), context)?; // 10. Let isoDate be ? CalendarMonthDayFromFields(calendar, fields, overflow). // 11. Return ! CreateTemporalMonthDay(isoDate, calendar). - create_temporal_month_day(month_day.inner.with(fields, overflow)?, None, context) + create_temporal_month_day( + month_day.borrow().data().inner.with(fields, overflow)?, + None, + context, + ) } /// 10.3.7 `Temporal.PlainMonthDay.prototype.equals ( other )` @@ -317,18 +305,12 @@ impl PlainMonthDay { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/PlainMonthDay/equals /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.PlainMonthDay.html#impl-PartialEq-for-PlainMonthDay fn equals(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult { - let object = this.as_object(); - let month_day = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("this value must be a PlainMonthDay object.") - })?; + let month_day = this.require_internal_slot::()?; let other = to_temporal_month_day(args.get_or_undefined(0), &JsValue::undefined(), context)?; - Ok((month_day.inner == other).into()) + Ok((month_day.borrow().data().inner == other).into()) } /// 10.3.8 `Temporal.PlainMonthDay.prototype.toString ( [ options ] )` @@ -345,13 +327,7 @@ impl PlainMonthDay { fn to_string(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult { // 1. Let monthDay be the this value. // 2. Perform ? RequireInternalSlot(monthDay, [[InitializedTemporalMonthDay]]). - let object = this.as_object(); - let month_day = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("this value must be a PlainMonthDay object.") - })?; + let month_day = this.require_internal_slot::()?; // 3. Set options to ? NormalizeOptionsObject(options). let options = get_options_object(args.get_or_undefined(0))?; @@ -361,7 +337,11 @@ impl PlainMonthDay { get_option::(&options, js_string!("calendarName"), context)? .unwrap_or(DisplayCalendar::Auto); - let ixdtf = month_day.inner.to_ixdtf_string(show_calendar); + let ixdtf = month_day + .borrow() + .data() + .inner + .to_ixdtf_string(show_calendar); Ok(JsString::from(ixdtf).into()) } @@ -380,15 +360,9 @@ impl PlainMonthDay { _: &mut Context, ) -> JsResult { // TODO: Update for ECMA-402 compliance - let object = this.as_object(); - let month_day = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("this value must be a PlainMonthDay object.") - })?; - - Ok(JsString::from(month_day.inner.to_string()).into()) + let month_day = this.require_internal_slot::()?; + + Ok(JsString::from(month_day.borrow().data().inner.to_string()).into()) } /// 10.3.10 `Temporal.PlainMonthDay.prototype.toJSON ( )` @@ -401,15 +375,9 @@ impl PlainMonthDay { /// [spec]: https://tc39.es/proposal-temporal/#sec-temporal.plainmonthday.tojson /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/PlainMonthDay/toJSON pub(crate) fn to_json(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { - let object = this.as_object(); - let month_day = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("this value must be a PlainMonthDay object.") - })?; - - Ok(JsString::from(month_day.inner.to_string()).into()) + let month_day = this.require_internal_slot::()?; + + Ok(JsString::from(month_day.borrow().data().inner.to_string()).into()) } /// 9.3.11 `Temporal.PlainMonthDay.prototype.valueOf ( )` @@ -441,13 +409,7 @@ impl PlainMonthDay { fn to_plain_date(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult { // 1. Let monthDay be the this value. // 2. Perform ? RequireInternalSlot(monthDay, [[InitializedTemporalMonthDay]]). - let object = this.as_object(); - let month_day = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("this value must be a PlainMonthDay object.") - })?; + let month_day = this.require_internal_slot::()?; // 3. If item is not an Object, then let Some(item) = args.get_or_undefined(0).as_object() else { @@ -474,7 +436,11 @@ impl PlainMonthDay { // 7. Let mergedFields be CalendarMergeFields(calendar, fields, inputFields). // 8. Let isoDate be ? CalendarDateFromFields(calendar, mergedFields, constrain). // 9. Return ! CreateTemporalDate(isoDate, calendar). - let result = month_day.inner.to_plain_date(Some(fields))?; + let result = month_day + .borrow() + .data() + .inner + .to_plain_date(Some(fields))?; create_temporal_date(result, None, context).map(Into::into) } } diff --git a/core/engine/src/builtins/temporal/plain_time/mod.rs b/core/engine/src/builtins/temporal/plain_time/mod.rs index f9113dd5100..f3a1d25923d 100644 --- a/core/engine/src/builtins/temporal/plain_time/mod.rs +++ b/core/engine/src/builtins/temporal/plain_time/mod.rs @@ -266,16 +266,10 @@ impl PlainTime { fn get_hour(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { // 1. Let temporalTime be the this value. // 2. Perform ? RequireInternalSlot(temporalTime, [[InitializedTemporalTime]]). - let object = this.as_object(); - let time = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a PlainTime object.") - })?; + let time = this.require_internal_slot::()?; // 3. Return 𝔽(temporalTime.[[ISOHour]]). - Ok(time.inner.hour().into()) + Ok(time.borrow().data().inner.hour().into()) } /// 4.3.4 get `Temporal.PlainTime.prototype.minute` @@ -292,16 +286,10 @@ impl PlainTime { fn get_minute(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { // 1. Let temporalTime be the this value. // 2. Perform ? RequireInternalSlot(temporalTime, [[InitializedTemporalTime]]). - let object = this.as_object(); - let time = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a PlainTime object.") - })?; + let time = this.require_internal_slot::()?; // 3. Return 𝔽(temporalTime.[[ISOMinute]]). - Ok(time.inner.minute().into()) + Ok(time.borrow().data().inner.minute().into()) } /// 4.3.5 get `Temporal.PlainTime.prototype.second` @@ -318,16 +306,10 @@ impl PlainTime { fn get_second(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { // 1. Let temporalTime be the this value. // 2. Perform ? RequireInternalSlot(temporalTime, [[InitializedTemporalTime]]). - let object = this.as_object(); - let time = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a PlainTime object.") - })?; + let time = this.require_internal_slot::()?; // 3. Return 𝔽(temporalTime.[[ISOSecond]]). - Ok(time.inner.second().into()) + Ok(time.borrow().data().inner.second().into()) } /// 4.3.6 get `Temporal.PlainTime.prototype.millisecond` @@ -344,16 +326,10 @@ impl PlainTime { fn get_millisecond(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { // 1. Let temporalTime be the this value. // 2. Perform ? RequireInternalSlot(temporalTime, [[InitializedTemporalTime]]). - let object = this.as_object(); - let time = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a PlainTime object.") - })?; + let time = this.require_internal_slot::()?; // 3. Return 𝔽(temporalTime.[[ISOMillisecond]]). - Ok(time.inner.millisecond().into()) + Ok(time.borrow().data().inner.millisecond().into()) } /// 4.3.7 get `Temporal.PlainTime.prototype.microsecond` @@ -370,16 +346,10 @@ impl PlainTime { fn get_microsecond(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { // 1. Let temporalTime be the this value. // 2. Perform ? RequireInternalSlot(temporalTime, [[InitializedTemporalTime]]). - let object = this.as_object(); - let time = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a PlainTime object.") - })?; + let time = this.require_internal_slot::()?; // 3. Return 𝔽(temporalTime.[[ISOMicrosecond]]). - Ok(time.inner.microsecond().into()) + Ok(time.borrow().data().inner.microsecond().into()) } /// 4.3.8 get `Temporal.PlainTime.prototype.nanosecond` @@ -396,16 +366,10 @@ impl PlainTime { fn get_nanosecond(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { // 1. Let temporalTime be the this value. // 2. Perform ? RequireInternalSlot(temporalTime, [[InitializedTemporalTime]]). - let object = this.as_object(); - let time = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a PlainTime object.") - })?; + let time = this.require_internal_slot::()?; // 3. Return 𝔽(temporalTime.[[ISONanosecond]]). - Ok(time.inner.nanosecond().into()) + Ok(time.borrow().data().inner.nanosecond().into()) } } @@ -468,19 +432,14 @@ impl PlainTime { fn add(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult { // 1. Let temporalTime be the this value. // 2. Perform ? RequireInternalSlot(temporalTime, [[InitializedTemporalTime]]). - let object = this.as_object(); - let time = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a PlainTime object.") - })?; + let time = this.require_internal_slot::()?; let temporal_duration_like = args.get_or_undefined(0); let duration = to_temporal_duration_record(temporal_duration_like, context)?; // 3. Return ? AddDurationToOrSubtractDurationFromPlainTime(add, temporalTime, temporalDurationLike). - create_temporal_time(time.inner.add(&duration)?, None, context).map(Into::into) + create_temporal_time(time.borrow().data().inner.add(&duration)?, None, context) + .map(Into::into) } /// 4.3.10 `Temporal.PlainTime.prototype.subtract ( temporalDurationLike )` @@ -497,19 +456,18 @@ impl PlainTime { fn subtract(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult { // 1. Let temporalTime be the this value. // 2. Perform ? RequireInternalSlot(temporalTime, [[InitializedTemporalTime]]). - let object = this.as_object(); - let time = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a PlainTime object.") - })?; + let time = this.require_internal_slot::()?; let temporal_duration_like = args.get_or_undefined(0); let duration = to_temporal_duration_record(temporal_duration_like, context)?; // 3. Return ? AddDurationToOrSubtractDurationFromPlainTime(subtract, temporalTime, temporalDurationLike). - create_temporal_time(time.inner.subtract(&duration)?, None, context).map(Into::into) + create_temporal_time( + time.borrow().data().inner.subtract(&duration)?, + None, + context, + ) + .map(Into::into) } /// 4.3.11 `Temporal.PlainTime.prototype.with ( temporalTimeLike [ , options ] )` @@ -526,13 +484,7 @@ impl PlainTime { fn with(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult { // 1.Let temporalTime be the this value. // 2. Perform ? RequireInternalSlot(temporalTime, [[InitializedTemporalTime]]). - let object = this.as_object(); - let time = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a PlainTime object.") - })?; + let time = this.require_internal_slot::()?; // 3. If ? IsPartialTemporalObject(temporalTimeLike) is false, throw a TypeError exception. // 4. Set options to ? GetOptionsObject(options). @@ -552,7 +504,9 @@ impl PlainTime { let overflow = get_option::(&options, js_string!("overflow"), context)?; create_temporal_time( - time.inner + time.borrow() + .data() + .inner .with(partial.as_temporal_partial_time(overflow)?, overflow)?, None, context, @@ -572,20 +526,14 @@ impl PlainTime { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/PlainTime/until /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.PlainTime.html#method.until fn until(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult { - let object = this.as_object(); - let time = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a PlainTime object.") - })?; + let time = this.require_internal_slot::()?; let other = to_temporal_time(args.get_or_undefined(0), None, context)?; let settings = get_difference_settings(&get_options_object(args.get_or_undefined(1))?, context)?; - let result = time.inner.until(&other, settings)?; + let result = time.borrow().data().inner.until(&other, settings)?; create_temporal_duration(result, None, context).map(Into::into) } @@ -602,20 +550,14 @@ impl PlainTime { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/PlainTime/since /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.PlainTime.html#method.since fn since(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult { - let object = this.as_object(); - let time = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a PlainTime object.") - })?; + let time = this.require_internal_slot::()?; let other = to_temporal_time(args.get_or_undefined(0), None, context)?; let settings = get_difference_settings(&get_options_object(args.get_or_undefined(1))?, context)?; - let result = time.inner.since(&other, settings)?; + let result = time.borrow().data().inner.since(&other, settings)?; create_temporal_duration(result, None, context).map(Into::into) } @@ -634,13 +576,7 @@ impl PlainTime { fn round(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult { // 1. Let temporalTime be the this value. // 2. Perform ? RequireInternalSlot(temporalTime, [[InitializedTemporalTime]]). - let object = this.as_object(); - let time = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a PlainTime object.") - })?; + let time = this.require_internal_slot::()?; // 3. If roundTo is undefined, then let round_to_arg = args.get_or_undefined(0); @@ -691,7 +627,7 @@ impl PlainTime { // 11. Assert: maximum is not undefined. // 12. Perform ? ValidateTemporalRoundingIncrement(roundingIncrement, maximum, false). // 13. Let result be RoundTime(temporalTime.[[ISOHour]], temporalTime.[[ISOMinute]], temporalTime.[[ISOSecond]], temporalTime.[[ISOMillisecond]], temporalTime.[[ISOMicrosecond]], temporalTime.[[ISONanosecond]], roundingIncrement, smallestUnit, roundingMode). - let result = time.inner.round(options)?; + let result = time.borrow().data().inner.round(options)?; // 14. Return ! CreateTemporalTime(result.[[Hour]], result.[[Minute]], result.[[Second]], result.[[Millisecond]], result.[[Microsecond]], result.[[Nanosecond]]). create_temporal_time(result, None, context).map(Into::into) @@ -711,13 +647,7 @@ impl PlainTime { fn equals(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult { // 1. Let temporalTime be the this value. // 2. Perform ? RequireInternalSlot(temporalTime, [[InitializedTemporalTime]]). - let object = this.as_object(); - let time = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a PlainTime object.") - })?; + let time = this.require_internal_slot::()?; // 3. Set other to ? ToTemporalTime(other). let other = to_temporal_time(args.get_or_undefined(0), None, context)?; @@ -728,7 +658,7 @@ impl PlainTime { // 8. If temporalTime.[[ISOMicrosecond]] ≠ other.[[ISOMicrosecond]], return false. // 9. If temporalTime.[[ISONanosecond]] ≠ other.[[ISONanosecond]], return false. // 10. Return true. - Ok((time.inner == other).into()) + Ok((time.borrow().data().inner == other).into()) } /// 4.3.16 `Temporal.PlainTime.prototype.toString ( [ options ] )` @@ -743,13 +673,7 @@ impl PlainTime { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/PlainTime/toString /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.PlainTime.html#method.to_ixdtf_string fn to_string(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult { - let object = this.as_object(); - let time = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a PlainTime object.") - })?; + let time = this.require_internal_slot::()?; let options = get_options_object(args.get_or_undefined(0))?; @@ -764,7 +688,7 @@ impl PlainTime { smallest_unit, }; - let ixdtf = time.inner.to_ixdtf_string(options)?; + let ixdtf = time.borrow().data().inner.to_ixdtf_string(options)?; Ok(JsString::from(ixdtf).into()) } @@ -780,15 +704,11 @@ impl PlainTime { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/PlainTime/toLocaleString fn to_locale_string(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { // TODO: Update for ECMA-402 compliance - let object = this.as_object(); - let time = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a PlainTime object.") - })?; + let time = this.require_internal_slot::()?; let ixdtf = time + .borrow() + .data() .inner .to_ixdtf_string(ToStringRoundingOptions::default())?; Ok(JsString::from(ixdtf).into()) @@ -804,15 +724,11 @@ impl PlainTime { /// [spec]: https://tc39.es/proposal-temporal/#sec-temporal.plaintime.prototype.tojson /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/PlainTime/toJSON fn to_json(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { - let object = this.as_object(); - let time = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a PlainTime object.") - })?; + let time = this.require_internal_slot::()?; let ixdtf = time + .borrow() + .data() .inner .to_ixdtf_string(ToStringRoundingOptions::default())?; Ok(JsString::from(ixdtf).into()) diff --git a/core/engine/src/builtins/temporal/plain_year_month/mod.rs b/core/engine/src/builtins/temporal/plain_year_month/mod.rs index 1c328da5997..50b3aab4702 100644 --- a/core/engine/src/builtins/temporal/plain_year_month/mod.rs +++ b/core/engine/src/builtins/temporal/plain_year_month/mod.rs @@ -297,14 +297,9 @@ impl PlainYearMonth { impl PlainYearMonth { // Helper for retrieving internal fields fn get_internal_field(this: &JsValue, field: &DateTimeValues) -> JsResult { - let object = this.as_object(); - let year_month = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("this value must be a PlainYearMonth object.") - })?; - let inner = &year_month.inner; + let year_month = this.require_internal_slot::()?; + let year_month_data = year_month.borrow(); + let inner = &year_month_data.data().inner; match field { DateTimeValues::Year => Ok(inner.year().into()), DateTimeValues::Month => Ok(inner.month().into()), @@ -327,15 +322,7 @@ impl PlainYearMonth { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/PlainYearMonth/calendarId /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.PlainYearMonth.html#method.calendar fn get_calendar_id(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { - let obj = this - .as_object() - .ok_or_else(|| JsNativeError::typ().with_message("this must be an object."))?; - - let Ok(year_month) = obj.clone().downcast::() else { - return Err(JsNativeError::typ() - .with_message("the this object must be a PlainYearMonth object.") - .into()); - }; + let year_month = this.require_internal_slot::()?; let calendar = year_month.borrow().data().inner.calendar().clone(); Ok(js_string!(calendar.identifier()).into()) @@ -353,15 +340,11 @@ impl PlainYearMonth { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/PlainYearMonth/era /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.PlainYearMonth.html#method.era fn get_era(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { - let object = this.as_object(); - let year_month = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("this value must be a PlainYearMonth object.") - })?; + let year_month = this.require_internal_slot::()?; Ok(year_month + .borrow() + .data() .inner .era() .map(|s| JsString::from(s.as_str())) @@ -380,14 +363,13 @@ impl PlainYearMonth { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/PlainYearMonth/eraYear /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.PlainYearMonth.html#method.era_year fn get_era_year(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { - let object = this.as_object(); - let year_month = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("this value must be a PlainYearMonth object.") - })?; - Ok(year_month.inner.era_year().into_or_undefined()) + let year_month = this.require_internal_slot::()?; + Ok(year_month + .borrow() + .data() + .inner + .era_year() + .into_or_undefined()) } /// 9.3.6 get `Temporal.PlainYearMonth.prototype.year` @@ -447,14 +429,9 @@ impl PlainYearMonth { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/PlainYearMonth/daysInYear /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.PlainYearMonth.html#method.days_in_year fn get_days_in_year(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { - let object = this.as_object(); - let year_month = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("this value must be a PlainYearMonth object.") - })?; - let inner = &year_month.inner; + let year_month = this.require_internal_slot::()?; + let year_month_data = year_month.borrow(); + let inner = &year_month_data.data().inner; Ok(inner.days_in_year().into()) } @@ -470,14 +447,9 @@ impl PlainYearMonth { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/PlainYearMonth/daysInMonth /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.PlainYearMonth.html#method.days_in_month fn get_days_in_month(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { - let object = this.as_object(); - let year_month = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("this value must be a PlainYearMonth object.") - })?; - let inner = &year_month.inner; + let year_month = this.require_internal_slot::()?; + let year_month_data = year_month.borrow(); + let inner = &year_month_data.data().inner; Ok(inner.days_in_month().into()) } @@ -493,14 +465,9 @@ impl PlainYearMonth { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/PlainYearMonth/monthsInYear /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.PlainYearMonth.html#method.months_in_year fn get_months_in_year(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { - let object = this.as_object(); - let year_month = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("this value must be a PlainYearMonth object.") - })?; - let inner = &year_month.inner; + let year_month = this.require_internal_slot::()?; + let year_month_data = year_month.borrow(); + let inner = &year_month_data.data().inner; Ok(inner.months_in_year().into()) } @@ -516,15 +483,9 @@ impl PlainYearMonth { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/PlainYearMonth/inLeapYear /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.PlainYearMonth.html#method.in_leap_year fn get_in_leap_year(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { - let object = this.as_object(); - let year_month = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("this value must be a PlainYearMonth object.") - })?; - - Ok(year_month.inner.in_leap_year().into()) + let year_month = this.require_internal_slot::()?; + + Ok(year_month.borrow().data().inner.in_leap_year().into()) } } @@ -545,13 +506,7 @@ impl PlainYearMonth { fn with(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult { // 1. Let yearMonth be the this value. // 2. Perform ? RequireInternalSlot(yearMonth, [[InitializedTemporalYearMonth]]). - let object = this.as_object(); - let year_month = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("this value must be a PlainYearMonth object.") - })?; + let year_month = this.require_internal_slot::()?; // 3. If ? IsPartialTemporalObject(temporalYearMonthLike) is false, throw a TypeError exception. let Some(obj) = is_partial_temporal_object(args.get_or_undefined(0), context)? else { @@ -563,7 +518,11 @@ impl PlainYearMonth { // 5. Let fields be ISODateToFields(calendar, yearMonth.[[ISODate]], year-month). // 6. Let partialYearMonth be ? PrepareCalendarFields(calendar, temporalYearMonthLike, « year, month, month-code », « », partial). // 7. Set fields to CalendarMergeFields(calendar, fields, partialYearMonth). - let fields = to_year_month_calendar_fields(&obj, year_month.inner.calendar(), context)?; + let fields = to_year_month_calendar_fields( + &obj, + year_month.borrow().data().inner.calendar(), + context, + )?; // NOTE: Update temporal_rs to handle this. if fields.is_empty() { return Err(JsNativeError::typ() @@ -576,7 +535,11 @@ impl PlainYearMonth { let overflow = get_option::(&resolved_options, js_string!("overflow"), context)? .unwrap_or_default(); // 10. Let isoDate be ? CalendarYearMonthFromFields(calendar, fields, overflow). - let result = year_month.inner.with(fields, Some(overflow))?; + let result = year_month + .borrow() + .data() + .inner + .with(fields, Some(overflow))?; // 11. Return ! CreateTemporalYearMonth(isoDate, calendar). create_temporal_year_month(result, None, context) } @@ -629,17 +592,11 @@ impl PlainYearMonth { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/PlainYearMonth/until /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.PlainYearMonth.html#method.until fn until(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult { - let object = this.as_object(); - let year_month = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("this value must be a PlainYearMonth object.") - })?; + let year_month = this.require_internal_slot::()?; let other = to_temporal_year_month(args.get_or_undefined(0), None, context)?; - if year_month.inner.calendar() != other.calendar() { + if year_month.borrow().data().inner.calendar() != other.calendar() { return Err(JsNativeError::range() .with_message("calendars are not the same.") .into()); @@ -648,7 +605,7 @@ impl PlainYearMonth { let resolved_options = get_options_object(args.get_or_undefined(1))?; // TODO: Disallowed units must be rejected in `temporal_rs`. let settings = get_difference_settings(&resolved_options, context)?; - let result = year_month.inner.until(&other, settings)?; + let result = year_month.borrow().data().inner.until(&other, settings)?; create_temporal_duration(result, None, context).map(Into::into) } @@ -664,17 +621,11 @@ impl PlainYearMonth { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/PlainYearMonth/since /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.PlainYearMonth.html#method.since fn since(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult { - let object = this.as_object(); - let year_month = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("this value must be a PlainYearMonth object.") - })?; + let year_month = this.require_internal_slot::()?; let other = to_temporal_year_month(args.get_or_undefined(0), None, context)?; - if year_month.inner.calendar() != other.calendar() { + if year_month.borrow().data().inner.calendar() != other.calendar() { return Err(JsNativeError::range() .with_message("calendars are not the same.") .into()); @@ -683,7 +634,7 @@ impl PlainYearMonth { let resolved_options = get_options_object(args.get_or_undefined(1))?; // TODO: Disallowed units must be rejected in `temporal_rs`. let settings = get_difference_settings(&resolved_options, context)?; - let result = year_month.inner.since(&other, settings)?; + let result = year_month.borrow().data().inner.since(&other, settings)?; create_temporal_duration(result, None, context).map(Into::into) } @@ -699,17 +650,11 @@ impl PlainYearMonth { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/PlainYearMonth/equals /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.PlainYearMonth.html#impl-PartialEq-for-PlainYearMonth fn equals(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult { - let object = this.as_object(); - let year_month = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("this value must be a PlainYearMonth object.") - })?; + let year_month = this.require_internal_slot::()?; let other = to_temporal_year_month(args.get_or_undefined(0), None, context)?; - Ok((year_month.inner == other).into()) + Ok((year_month.borrow().data().inner == other).into()) } /// 9.3.19 `Temporal.PlainYearMonth.prototype.toString ( [ options ] )` @@ -726,13 +671,7 @@ impl PlainYearMonth { fn to_string(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult { // 1. Let YearMonth be the this value. // 2. Perform ? RequireInternalSlot(yearMonth, [[InitializedTemporalYearMonth]]). - let object = this.as_object(); - let year_month = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("this value must be a PlainYearMonth object.") - })?; + let year_month = this.require_internal_slot::()?; // 3. Set options to ? NormalizeOptionsObject(options). let options = get_options_object(args.get_or_undefined(0))?; @@ -742,7 +681,11 @@ impl PlainYearMonth { get_option::(&options, js_string!("calendarName"), context)? .unwrap_or(DisplayCalendar::Auto); - let ixdtf = year_month.inner.to_ixdtf_string(show_calendar); + let ixdtf = year_month + .borrow() + .data() + .inner + .to_ixdtf_string(show_calendar); Ok(JsString::from(ixdtf).into()) } @@ -761,15 +704,9 @@ impl PlainYearMonth { _: &mut Context, ) -> JsResult { // TODO: Update for ECMA-402 compliance - let object = this.as_object(); - let year_month = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("this value must be a PlainYearMonth object.") - })?; - - Ok(JsString::from(year_month.inner.to_string()).into()) + let year_month = this.require_internal_slot::()?; + + Ok(JsString::from(year_month.borrow().data().inner.to_string()).into()) } /// 9.3.21 `Temporal.PlainYearMonth.prototype.toJSON ( )` @@ -782,15 +719,9 @@ impl PlainYearMonth { /// [spec]: https://tc39.es/proposal-temporal/#sec-temporal.plainyearmonth.tojson /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/PlainYearMonth/toJSON pub(crate) fn to_json(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { - let object = this.as_object(); - let year_month = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("this value must be a PlainYearMonth object.") - })?; - - Ok(JsString::from(year_month.inner.to_string()).into()) + let year_month = this.require_internal_slot::()?; + + Ok(JsString::from(year_month.borrow().data().inner.to_string()).into()) } /// 9.3.22 `Temporal.PlainYearMonth.prototype.valueOf ( )` @@ -822,13 +753,7 @@ impl PlainYearMonth { fn to_plain_date(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult { // 1. Let yearMonth be the this value. // 2. Perform ? RequireInternalSlot(yearMonth, [[InitializedTemporalYearMonth]]). - let object = this.as_object(); - let year_month = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("this value must be a PlainYearMonth object.") - })?; + let year_month = this.require_internal_slot::()?; // 3. If item is not an Object, then let Some(obj) = args.get_or_undefined(0).as_object() else { @@ -854,7 +779,11 @@ impl PlainYearMonth { // 7. Let mergedFields be CalendarMergeFields(calendar, fields, inputFields). // 8. Let isoDate be ? CalendarDateFromFields(calendar, mergedFields, constrain). - let result = year_month.inner.to_plain_date(Some(fields))?; + let result = year_month + .borrow() + .data() + .inner + .to_plain_date(Some(fields))?; // 9. Return ! CreateTemporalDate(isoDate, calendar). create_temporal_date(result, None, context).map(Into::into) } diff --git a/core/engine/src/builtins/temporal/zoneddatetime/mod.rs b/core/engine/src/builtins/temporal/zoneddatetime/mod.rs index 7f186c87878..965b574dae8 100644 --- a/core/engine/src/builtins/temporal/zoneddatetime/mod.rs +++ b/core/engine/src/builtins/temporal/zoneddatetime/mod.rs @@ -478,15 +478,9 @@ impl ZonedDateTime { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/ZonedDateTime/calendarId /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.ZonedDateTime.html#method.calendar fn get_calendar_id(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { - let object = this.as_object(); - let zdt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a ZonedDateTime object.") - })?; - - Ok(JsString::from(zdt.inner.calendar().identifier()).into()) + let zdt = this.require_internal_slot::()?; + + Ok(JsString::from(zdt.borrow().data().inner.calendar().identifier()).into()) } /// 6.3.4 get `Temporal.ZonedDateTime.prototype.timeZoneId` @@ -501,16 +495,12 @@ impl ZonedDateTime { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/ZonedDateTime/timeZoneId /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.ZonedDateTime.html#method.timezone fn get_timezone_id(this: &JsValue, _: &[JsValue], context: &mut Context) -> JsResult { - let object = this.as_object(); - let zdt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a ZonedDateTime object.") - })?; + let zdt = this.require_internal_slot::()?; Ok(JsString::from( - zdt.inner + zdt.borrow() + .data() + .inner .time_zone() .identifier_with_provider(context.timezone_provider())?, ) @@ -529,15 +519,9 @@ impl ZonedDateTime { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/ZonedDateTime/era /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.ZonedDateTime.html#method.era fn get_era(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { - let object = this.as_object(); - let zdt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a ZonedDateTime object.") - })?; - - let era = zdt.inner.era(); + let zdt = this.require_internal_slot::()?; + + let era = zdt.borrow().data().inner.era(); Ok(era .map(|tinystr| JsString::from(tinystr.cow_to_lowercase())) .into_or_undefined()) @@ -555,15 +539,9 @@ impl ZonedDateTime { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/ZonedDateTime/eraYear /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.ZonedDateTime.html#method.era_year fn get_era_year(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { - let object = this.as_object(); - let zdt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a ZonedDateTime object.") - })?; - - Ok(zdt.inner.era_year().into_or_undefined()) + let zdt = this.require_internal_slot::()?; + + Ok(zdt.borrow().data().inner.era_year().into_or_undefined()) } /// 6.3.7 get `Temporal.ZonedDateTime.prototype.year` @@ -578,15 +556,9 @@ impl ZonedDateTime { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/ZonedDateTime/year /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.ZonedDateTime.html#method.year fn get_year(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { - let object = this.as_object(); - let zdt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a ZonedDateTime object.") - })?; - - Ok(zdt.inner.year().into()) + let zdt = this.require_internal_slot::()?; + + Ok(zdt.borrow().data().inner.year().into()) } /// 6.3.8 get `Temporal.ZonedDateTime.prototype.month` @@ -601,15 +573,9 @@ impl ZonedDateTime { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/ZonedDateTime/month /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.ZonedDateTime.html#method.month fn get_month(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { - let object = this.as_object(); - let zdt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a ZonedDateTime object.") - })?; - - Ok(zdt.inner.month().into()) + let zdt = this.require_internal_slot::()?; + + Ok(zdt.borrow().data().inner.month().into()) } /// 6.3.9 get `Temporal.ZonedDateTime.prototype.monthCode` @@ -624,15 +590,9 @@ impl ZonedDateTime { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/ZonedDateTime/monthCode /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.ZonedDateTime.html#method.month_code fn get_month_code(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { - let object = this.as_object(); - let zdt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a ZonedDateTime object.") - })?; - - Ok(JsString::from(zdt.inner.month_code().as_str()).into()) + let zdt = this.require_internal_slot::()?; + + Ok(JsString::from(zdt.borrow().data().inner.month_code().as_str()).into()) } /// 6.3.10 get `Temporal.ZonedDateTime.prototype.day` @@ -647,15 +607,9 @@ impl ZonedDateTime { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/ZonedDateTime/day /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.ZonedDateTime.html#method.day fn get_day(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { - let object = this.as_object(); - let zdt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a ZonedDateTime object.") - })?; - - Ok(zdt.inner.day().into()) + let zdt = this.require_internal_slot::()?; + + Ok(zdt.borrow().data().inner.day().into()) } /// 6.3.11 get `Temporal.ZonedDateTime.prototype.hour` @@ -670,15 +624,9 @@ impl ZonedDateTime { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/ZonedDateTime/hour /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.ZonedDateTime.html#method.hour fn get_hour(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { - let object = this.as_object(); - let zdt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a ZonedDateTime object.") - })?; - - Ok(zdt.inner.hour().into()) + let zdt = this.require_internal_slot::()?; + + Ok(zdt.borrow().data().inner.hour().into()) } /// 6.3.12 get `Temporal.ZonedDateTime.prototype.minute` @@ -693,15 +641,9 @@ impl ZonedDateTime { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/ZonedDateTime/minute /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.ZonedDateTime.html#method.minute fn get_minute(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { - let object = this.as_object(); - let zdt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a ZonedDateTime object.") - })?; - - Ok(zdt.inner.minute().into()) + let zdt = this.require_internal_slot::()?; + + Ok(zdt.borrow().data().inner.minute().into()) } /// 6.3.13 get `Temporal.ZonedDateTime.prototype.second` @@ -716,15 +658,9 @@ impl ZonedDateTime { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/ZonedDateTime/second /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.ZonedDateTime.html#method.second fn get_second(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { - let object = this.as_object(); - let zdt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a ZonedDateTime object.") - })?; - - Ok(zdt.inner.second().into()) + let zdt = this.require_internal_slot::()?; + + Ok(zdt.borrow().data().inner.second().into()) } /// 6.3.14 get `Temporal.ZonedDateTime.prototype.millisecond` @@ -739,15 +675,9 @@ impl ZonedDateTime { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/ZonedDateTime/millisecond /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.ZonedDateTime.html#method.millisecond fn get_millisecond(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { - let object = this.as_object(); - let zdt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a ZonedDateTime object.") - })?; - - Ok(zdt.inner.millisecond().into()) + let zdt = this.require_internal_slot::()?; + + Ok(zdt.borrow().data().inner.millisecond().into()) } /// 6.3.15 get `Temporal.ZonedDateTime.prototype.microsecond` @@ -762,15 +692,9 @@ impl ZonedDateTime { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/ZonedDateTime/microsecond /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.ZonedDateTime.html#method.microsecond fn get_microsecond(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { - let object = this.as_object(); - let zdt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a ZonedDateTime object.") - })?; - - Ok(zdt.inner.microsecond().into()) + let zdt = this.require_internal_slot::()?; + + Ok(zdt.borrow().data().inner.microsecond().into()) } /// 6.3.16 get `Temporal.ZonedDateTime.prototype.nanosecond` @@ -785,15 +709,9 @@ impl ZonedDateTime { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/ZonedDateTime/nanosecond /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.ZonedDateTime.html#method.nanosecond fn get_nanosecond(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { - let object = this.as_object(); - let zdt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a ZonedDateTime object.") - })?; - - Ok(zdt.inner.nanosecond().into()) + let zdt = this.require_internal_slot::()?; + + Ok(zdt.borrow().data().inner.nanosecond().into()) } /// 6.3.17 get `Temporal.ZonedDateTime.prototype.epochMilliseconds` @@ -808,15 +726,9 @@ impl ZonedDateTime { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/ZonedDateTime/epochMilliseconds /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.ZonedDateTime.html#method.epoch_milliseconds fn get_epoch_milliseconds(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { - let object = this.as_object(); - let zdt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a ZonedDateTime object.") - })?; - - Ok(zdt.inner.epoch_milliseconds().into()) + let zdt = this.require_internal_slot::()?; + + Ok(zdt.borrow().data().inner.epoch_milliseconds().into()) } /// 6.3.18 get `Temporal.ZonedDateTime.prototype.epochNanoseconds` @@ -831,15 +743,9 @@ impl ZonedDateTime { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/ZonedDateTime/epochNanoseconds /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.ZonedDateTime.html#method.epoch_nanoseconds fn get_epoch_nanoseconds(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { - let object = this.as_object(); - let zdt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a ZonedDateTime object.") - })?; - - Ok(JsBigInt::from(zdt.inner.epoch_nanoseconds().as_i128()).into()) + let zdt = this.require_internal_slot::()?; + + Ok(JsBigInt::from(zdt.borrow().data().inner.epoch_nanoseconds().as_i128()).into()) } /// 6.3.19 get `Temporal.ZonedDateTime.prototype.dayOfWeek` @@ -854,15 +760,9 @@ impl ZonedDateTime { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/ZonedDateTime/dayOfWeek /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.ZonedDateTime.html#method.day_of_week fn get_day_of_week(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { - let object = this.as_object(); - let zdt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a ZonedDateTime object.") - })?; - - Ok(zdt.inner.day_of_week().into()) + let zdt = this.require_internal_slot::()?; + + Ok(zdt.borrow().data().inner.day_of_week().into()) } /// 6.3.20 get `Temporal.ZonedDateTime.prototype.dayOfYear` @@ -877,15 +777,9 @@ impl ZonedDateTime { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/ZonedDateTime/dayOfYear /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.ZonedDateTime.html#method.day_of_year fn get_day_of_year(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { - let object = this.as_object(); - let zdt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a ZonedDateTime object.") - })?; - - Ok(zdt.inner.day_of_year().into()) + let zdt = this.require_internal_slot::()?; + + Ok(zdt.borrow().data().inner.day_of_year().into()) } /// 6.3.21 get `Temporal.ZonedDateTime.prototype.weekOfYear` @@ -900,15 +794,9 @@ impl ZonedDateTime { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/ZonedDateTime/weekOfYear /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.ZonedDateTime.html#method.week_of_year fn get_week_of_year(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { - let object = this.as_object(); - let zdt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a ZonedDateTime object.") - })?; - - Ok(zdt.inner.week_of_year().into_or_undefined()) + let zdt = this.require_internal_slot::()?; + + Ok(zdt.borrow().data().inner.week_of_year().into_or_undefined()) } /// 6.3.22 get `Temporal.ZonedDateTime.prototype.yearOfWeek` @@ -923,15 +811,9 @@ impl ZonedDateTime { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/ZonedDateTime/yearOfWeek /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.ZonedDateTime.html#method.year_of_week fn get_year_of_week(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { - let object = this.as_object(); - let zdt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a ZonedDateTime object.") - })?; - - Ok(zdt.inner.year_of_week().into_or_undefined()) + let zdt = this.require_internal_slot::()?; + + Ok(zdt.borrow().data().inner.year_of_week().into_or_undefined()) } /// 6.3.23 get `Temporal.ZonedDateTime.prototype.hoursInDay` @@ -946,15 +828,11 @@ impl ZonedDateTime { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/ZonedDateTime/hoursInDay /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.ZonedDateTime.html#method.hours_in_day fn get_hours_in_day(this: &JsValue, _: &[JsValue], context: &mut Context) -> JsResult { - let object = this.as_object(); - let zdt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a ZonedDateTime object.") - })?; + let zdt = this.require_internal_slot::()?; Ok(zdt + .borrow() + .data() .inner .hours_in_day_with_provider(context.timezone_provider())? .into()) @@ -972,15 +850,9 @@ impl ZonedDateTime { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/ZonedDateTime/daysInWeek /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.ZonedDateTime.html#method.days_in_week fn get_days_in_week(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { - let object = this.as_object(); - let zdt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a ZonedDateTime object.") - })?; - - Ok(zdt.inner.days_in_week().into()) + let zdt = this.require_internal_slot::()?; + + Ok(zdt.borrow().data().inner.days_in_week().into()) } /// 6.3.25 get `Temporal.ZonedDateTime.prototype.daysInMonth` @@ -995,15 +867,9 @@ impl ZonedDateTime { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/ZonedDateTime/daysInMonth /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.ZonedDateTime.html#method.days_in_month fn get_days_in_month(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { - let object = this.as_object(); - let zdt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a ZonedDateTime object.") - })?; - - Ok(zdt.inner.days_in_month().into()) + let zdt = this.require_internal_slot::()?; + + Ok(zdt.borrow().data().inner.days_in_month().into()) } /// 6.3.26 get `Temporal.ZonedDateTime.prototype.daysInYear` @@ -1018,15 +884,9 @@ impl ZonedDateTime { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/ZonedDateTime/daysInYear /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.ZonedDateTime.html#method.days_in_year fn get_days_in_year(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { - let object = this.as_object(); - let zdt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a ZonedDateTime object.") - })?; - - Ok(zdt.inner.days_in_year().into()) + let zdt = this.require_internal_slot::()?; + + Ok(zdt.borrow().data().inner.days_in_year().into()) } /// 6.3.27 get `Temporal.ZonedDateTime.prototype.monthsInYear` @@ -1041,15 +901,9 @@ impl ZonedDateTime { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/ZonedDateTime/monthsInYear /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.ZonedDateTime.html#method.months_in_year fn get_months_in_year(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { - let object = this.as_object(); - let zdt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a ZonedDateTime object.") - })?; - - Ok(zdt.inner.months_in_year().into()) + let zdt = this.require_internal_slot::()?; + + Ok(zdt.borrow().data().inner.months_in_year().into()) } /// 6.3.28 get `Temporal.ZonedDateTime.prototype.inLeapYear` @@ -1064,15 +918,9 @@ impl ZonedDateTime { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/ZonedDateTime/inLeapYear /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.ZonedDateTime.html#method.in_leap_year fn get_in_leap_year(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { - let object = this.as_object(); - let zdt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a ZonedDateTime object.") - })?; - - Ok(zdt.inner.in_leap_year().into()) + let zdt = this.require_internal_slot::()?; + + Ok(zdt.borrow().data().inner.in_leap_year().into()) } /// 6.3.29 get Temporal.ZonedDateTime.prototype.offsetNanoseconds @@ -1087,15 +935,9 @@ impl ZonedDateTime { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/ZonedDateTime/offsetNanoseconds /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.ZonedDateTime.html#method.offset_nanoseconds fn get_offset_nanoseconds(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { - let object = this.as_object(); - let zdt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a ZonedDateTime object.") - })?; - - Ok(zdt.inner.offset_nanoseconds().into()) + let zdt = this.require_internal_slot::()?; + + Ok(zdt.borrow().data().inner.offset_nanoseconds().into()) } /// 6.3.30 get Temporal.ZonedDateTime.prototype.offset @@ -1110,15 +952,9 @@ impl ZonedDateTime { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/ZonedDateTime/offset /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.ZonedDateTime.html#method.offset fn get_offset(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult { - let object = this.as_object(); - let zdt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a ZonedDateTime object.") - })?; - - Ok(JsString::from(zdt.inner.offset()).into()) + let zdt = this.require_internal_slot::()?; + + Ok(JsString::from(zdt.borrow().data().inner.offset()).into()) } } @@ -1178,13 +1014,7 @@ impl ZonedDateTime { fn with(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult { // 1. Let zonedDateTime be the this value. // 2. Perform ? RequireInternalSlot(zonedDateTime, [[InitializedTemporalZonedDateTime]]). - let object = this.as_object(); - let zdt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a ZonedDateTime object.") - })?; + let zdt = this.require_internal_slot::()?; // 3. If ? IsPartialTemporalObject(temporalZonedDateTimeLike) is false, throw a TypeError exception. let Some(obj) = is_partial_temporal_object(args.get_or_undefined(0), context)? else { return Err(JsNativeError::typ() @@ -1208,7 +1038,7 @@ impl ZonedDateTime { // 18. Set fields to CalendarMergeFields(calendar, fields, partialZonedDateTime). let (fields, _) = to_zoned_date_time_fields( &obj, - zdt.inner.calendar(), + zdt.borrow().data().inner.calendar(), ZdtFieldsType::NoTimeZone, context, )?; @@ -1224,7 +1054,7 @@ impl ZonedDateTime { // 22. Let overflow be ? GetTemporalOverflowOption(resolvedOptions). let overflow = get_option::(&resolved_options, js_string!("overflow"), context)?; - let result = zdt.inner.with_with_provider( + let result = zdt.borrow().data().inner.with_with_provider( fields, disambiguation, offset, @@ -1250,13 +1080,7 @@ impl ZonedDateTime { args: &[JsValue], context: &mut Context, ) -> JsResult { - let object = this.as_object(); - let zdt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a ZonedDateTime object.") - })?; + let zdt = this.require_internal_slot::()?; let time = args .get_or_undefined(0) @@ -1264,6 +1088,8 @@ impl ZonedDateTime { .transpose()?; let inner = zdt + .borrow() + .data() .inner .with_plain_time_and_provider(time, context.timezone_provider())?; create_temporal_zoneddatetime(inner, None, context).map(Into::into) @@ -1281,17 +1107,13 @@ impl ZonedDateTime { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/ZonedDateTime/withTimeZone /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.ZonedDateTime.html#method.with_timezone fn with_timezone(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult { - let object = this.as_object(); - let zdt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a ZonedDateTime object.") - })?; + let zdt = this.require_internal_slot::()?; let timezone = to_temporal_timezone_identifier(args.get_or_undefined(0), context)?; let inner = zdt + .borrow() + .data() .inner .with_time_zone_with_provider(timezone, context.timezone_provider())?; create_temporal_zoneddatetime(inner, None, context).map(Into::into) @@ -1309,17 +1131,11 @@ impl ZonedDateTime { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/ZonedDateTime/withCalendar /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.ZonedDateTime.html#method.with_calendar fn with_calendar(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult { - let object = this.as_object(); - let zdt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a ZonedDateTime object.") - })?; + let zdt = this.require_internal_slot::()?; let calendar = to_temporal_calendar_identifier(args.get_or_undefined(0))?; - let inner = zdt.inner.with_calendar(calendar); + let inner = zdt.borrow().data().inner.with_calendar(calendar); create_temporal_zoneddatetime(inner, None, context).map(Into::into) } @@ -1335,22 +1151,18 @@ impl ZonedDateTime { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/ZonedDateTime/add /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.ZonedDateTime.html#method.add fn add(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult { - let object = this.as_object(); - let zdt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a ZonedDateTime object.") - })?; + let zdt = this.require_internal_slot::()?; let duration = to_temporal_duration(args.get_or_undefined(0), context)?; let options = get_options_object(args.get_or_undefined(1))?; let overflow = get_option::(&options, js_string!("overflow"), context)?; - let result = - zdt.inner - .add_with_provider(&duration, overflow, context.timezone_provider())?; + let result = zdt.borrow().data().inner.add_with_provider( + &duration, + overflow, + context.timezone_provider(), + )?; create_temporal_zoneddatetime(result, None, context).map(Into::into) } @@ -1366,22 +1178,18 @@ impl ZonedDateTime { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/ZonedDateTime/subtract /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.ZonedDateTime.html#method.subtract fn subtract(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult { - let object = this.as_object(); - let zdt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a ZonedDateTime object.") - })?; + let zdt = this.require_internal_slot::()?; let duration = to_temporal_duration(args.get_or_undefined(0), context)?; let options = get_options_object(args.get_or_undefined(1))?; let overflow = get_option::(&options, js_string!("overflow"), context)?; - let result = - zdt.inner - .subtract_with_provider(&duration, overflow, context.timezone_provider())?; + let result = zdt.borrow().data().inner.subtract_with_provider( + &duration, + overflow, + context.timezone_provider(), + )?; create_temporal_zoneddatetime(result, None, context).map(Into::into) } @@ -1397,22 +1205,18 @@ impl ZonedDateTime { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/ZonedDateTime/until /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.ZonedDateTime.html#method.until fn until(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult { - let object = this.as_object(); - let zdt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a ZonedDateTime object.") - })?; + let zdt = this.require_internal_slot::()?; let other = to_temporal_zoneddatetime(args.get_or_undefined(0), None, context)?; let options = get_options_object(args.get_or_undefined(1))?; let settings = get_difference_settings(&options, context)?; - let result = - zdt.inner - .until_with_provider(&other, settings, context.timezone_provider())?; + let result = zdt.borrow().data().inner.until_with_provider( + &other, + settings, + context.timezone_provider(), + )?; create_temporal_duration(result, None, context).map(Into::into) } @@ -1428,22 +1232,18 @@ impl ZonedDateTime { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/ZonedDateTime/since /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.ZonedDateTime.html#method.since fn since(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult { - let object = this.as_object(); - let zdt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a ZonedDateTime object.") - })?; + let zdt = this.require_internal_slot::()?; let other = to_temporal_zoneddatetime(args.get_or_undefined(0), None, context)?; let options = get_options_object(args.get_or_undefined(1))?; let settings = get_difference_settings(&options, context)?; - let result = - zdt.inner - .since_with_provider(&other, settings, context.timezone_provider())?; + let result = zdt.borrow().data().inner.since_with_provider( + &other, + settings, + context.timezone_provider(), + )?; create_temporal_duration(result, None, context).map(Into::into) } @@ -1461,13 +1261,7 @@ impl ZonedDateTime { fn round(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult { // 1. Let zonedDateTime be the this value. // 2. Perform ? RequireInternalSlot(zonedDateTime, [[InitializedTemporalZonedDateTime]]). - let object = this.as_object(); - let zdt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a ZonedDateTime object.") - })?; + let zdt = this.require_internal_slot::()?; // 3. If roundTo is undefined, then let round_to_arg = args.get_or_undefined(0); @@ -1519,6 +1313,8 @@ impl ZonedDateTime { )?; let result = zdt + .borrow() + .data() .inner .round_with_provider(options, context.timezone_provider())?; create_temporal_zoneddatetime(result, None, context).map(Into::into) @@ -1536,16 +1332,12 @@ impl ZonedDateTime { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/ZonedDateTime/equals /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.ZonedDateTime.html#impl-PartialEq-for-ZonedDateTime fn equals(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult { - let object = this.as_object(); - let zdt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a ZonedDateTime object.") - })?; + let zdt = this.require_internal_slot::()?; let other = to_temporal_zoneddatetime(args.get_or_undefined(0), None, context)?; Ok(zdt + .borrow() + .data() .inner .equals_with_provider(&other, context.timezone_provider())? .into()) @@ -1563,13 +1355,7 @@ impl ZonedDateTime { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/ZonedDateTime/toString /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.ZonedDateTime.html#method.to_ixdtf_string fn to_string(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult { - let object = this.as_object(); - let zdt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a ZonedDateTime object.") - })?; + let zdt = this.require_internal_slot::()?; let options = get_options_object(args.get_or_undefined(0))?; @@ -1592,7 +1378,7 @@ impl ZonedDateTime { smallest_unit, rounding_mode, }; - let ixdtf = zdt.inner.to_ixdtf_string_with_provider( + let ixdtf = zdt.borrow().data().inner.to_ixdtf_string_with_provider( show_offset, display_timezone, show_calendar, @@ -1614,15 +1400,9 @@ impl ZonedDateTime { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/ZonedDateTime/toLocaleString fn to_locale_string(this: &JsValue, _: &[JsValue], context: &mut Context) -> JsResult { // TODO: Update for ECMA-402 compliance - let object = this.as_object(); - let zdt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a ZonedDateTime object.") - })?; - - let ixdtf = zdt.inner.to_ixdtf_string_with_provider( + let zdt = this.require_internal_slot::()?; + + let ixdtf = zdt.borrow().data().inner.to_ixdtf_string_with_provider( DisplayOffset::Auto, DisplayTimeZone::Auto, DisplayCalendar::Auto, @@ -1643,15 +1423,9 @@ impl ZonedDateTime { /// [spec]: https://tc39.es/proposal-temporal/#sec-temporal.zoneddatetime.prototype.tojson /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/ZonedDateTime/toJSON fn to_json(this: &JsValue, _: &[JsValue], context: &mut Context) -> JsResult { - let object = this.as_object(); - let zdt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a ZonedDateTime object.") - })?; - - let ixdtf = zdt.inner.to_ixdtf_string_with_provider( + let zdt = this.require_internal_slot::()?; + + let ixdtf = zdt.borrow().data().inner.to_ixdtf_string_with_provider( DisplayOffset::Auto, DisplayTimeZone::Auto, DisplayCalendar::Auto, @@ -1689,15 +1463,11 @@ impl ZonedDateTime { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/ZonedDateTime/startOfDay /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.ZonedDateTime.html#method.start_of_day fn start_of_day(this: &JsValue, _: &[JsValue], context: &mut Context) -> JsResult { - let object = this.as_object(); - let zdt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a ZonedDateTime object.") - })?; + let zdt = this.require_internal_slot::()?; let new = zdt + .borrow() + .data() .inner .start_of_day_with_provider(context.timezone_provider())?; create_temporal_zoneddatetime(new, None, context).map(Into::into) @@ -1722,13 +1492,7 @@ impl ZonedDateTime { // 1. Let zonedDateTime be the this value. // 2. Perform ? RequireInternalSlot(zonedDateTime, [[InitializedTemporalZonedDateTime]]). // 3. Let timeZone be zonedDateTime.[[TimeZone]]. - let object = this.as_object(); - let zdt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a ZonedDateTime object.") - })?; + let zdt = this.require_internal_slot::()?; let direction_param = args.get_or_undefined(0); // 4. If directionParam is undefined, throw a TypeError exception. @@ -1765,6 +1529,8 @@ impl ZonedDateTime { // Step 8-12 let result = zdt + .borrow() + .data() .inner .get_time_zone_transition_with_provider(direction, context.timezone_provider())?; @@ -1786,15 +1552,9 @@ impl ZonedDateTime { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/ZonedDateTime/toInstant /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.ZonedDateTime.html#method.to_instant fn to_instant(this: &JsValue, _: &[JsValue], context: &mut Context) -> JsResult { - let object = this.as_object(); - let zdt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a ZonedDateTime object.") - })?; - - create_temporal_instant(zdt.inner.to_instant(), None, context) + let zdt = this.require_internal_slot::()?; + + create_temporal_instant(zdt.borrow().data().inner.to_instant(), None, context) } /// 6.3.48 `Temporal.ZonedDateTime.prototype.toPlainDate ( )` @@ -1809,15 +1569,9 @@ impl ZonedDateTime { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/ZonedDateTime/toPlainDate /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.ZonedDateTime.html#method.to_plain_date fn to_plain_date(this: &JsValue, _: &[JsValue], context: &mut Context) -> JsResult { - let object = this.as_object(); - let zdt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a ZonedDateTime object.") - })?; - - let inner = zdt.inner.to_plain_date(); + let zdt = this.require_internal_slot::()?; + + let inner = zdt.borrow().data().inner.to_plain_date(); create_temporal_date(inner, None, context).map(Into::into) } @@ -1833,15 +1587,9 @@ impl ZonedDateTime { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/ZonedDateTime/toPlainTime /// [temporal_rs-docs]: https://docs.rs/temporal_rs/latest/temporal_rs/struct.ZonedDateTime.html#method.to_plain_time fn to_plain_time(this: &JsValue, _: &[JsValue], context: &mut Context) -> JsResult { - let object = this.as_object(); - let zdt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a ZonedDateTime object.") - })?; - - let new = zdt.inner.to_plain_time(); + let zdt = this.require_internal_slot::()?; + + let new = zdt.borrow().data().inner.to_plain_time(); create_temporal_time(new, None, context).map(Into::into) } @@ -1861,15 +1609,9 @@ impl ZonedDateTime { _: &[JsValue], context: &mut Context, ) -> JsResult { - let object = this.as_object(); - let zdt = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("the this object must be a ZonedDateTime object.") - })?; - - let new = zdt.inner.to_plain_date_time(); + let zdt = this.require_internal_slot::()?; + + let new = zdt.borrow().data().inner.to_plain_date_time(); create_temporal_datetime(new, None, context).map(Into::into) } } diff --git a/core/engine/src/builtins/typed_array/builtin.rs b/core/engine/src/builtins/typed_array/builtin.rs index d3ebbc1cc89..538eed558ec 100644 --- a/core/engine/src/builtins/typed_array/builtin.rs +++ b/core/engine/src/builtins/typed_array/builtin.rs @@ -409,17 +409,11 @@ impl BuiltinTypedArray { // 1. Let O be the this value. // 2. Perform ? RequireInternalSlot(O, [[TypedArrayName]]). // 3. Assert: O has a [[ViewedArrayBuffer]] internal slot. - let object = this.as_object(); - let ta = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("`this` is not a typed array object") - })?; + let ta = this.require_internal_slot::()?; // 4. Let buffer be O.[[ViewedArrayBuffer]]. // 5. Return buffer. - Ok(ta.viewed_array_buffer().clone().into()) + Ok(ta.borrow().data().viewed_array_buffer().clone().into()) } /// `get %TypedArray%.prototype.byteLength` @@ -432,16 +426,12 @@ impl BuiltinTypedArray { // 1. Let O be the this value. // 2. Perform ? RequireInternalSlot(O, [[TypedArrayName]]). // 3. Assert: O has a [[ViewedArrayBuffer]] internal slot. - let object = this.as_object(); - let ta = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("`this` is not a typed array object") - })?; + let ta = this.require_internal_slot::()?; // 4. Let taRecord be MakeTypedArrayWithBufferWitnessRecord(O, seq-cst). - let buf_len = ta + let ta_data = ta.borrow(); + let ta_data = ta_data.data(); + let buf_len = ta_data .viewed_array_buffer() .as_buffer() .bytes(Ordering::SeqCst) @@ -449,7 +439,7 @@ impl BuiltinTypedArray { // 5. Let size be TypedArrayByteLength(taRecord). // 6. Return 𝔽(size). - Ok(ta.byte_length(buf_len).into()) + Ok(ta_data.byte_length(buf_len).into()) } /// `get %TypedArray%.prototype.byteOffset` @@ -462,29 +452,26 @@ impl BuiltinTypedArray { // 1. Let O be the this value. // 2. Perform ? RequireInternalSlot(O, [[TypedArrayName]]). // 3. Assert: O has a [[ViewedArrayBuffer]] internal slot. - let object = this.as_object(); - let ta = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("Value is not a typed array object") - })?; + let ta = this.require_internal_slot::()?; // 4. Let taRecord be MakeTypedArrayWithBufferWitnessRecord(O, seq-cst). // 5. If IsTypedArrayOutOfBounds(taRecord) is true, return +0𝔽. - if ta - .viewed_array_buffer() - .as_buffer() - .bytes(Ordering::SeqCst) - .as_ref() - .is_none_or(|s| ta.is_out_of_bounds(s.len())) { - return Ok(0.into()); + let ta_data = ta.borrow(); + let ta_data = ta_data.data(); + if ta_data + .viewed_array_buffer() + .as_buffer() + .bytes(Ordering::SeqCst) + .is_none_or(|s| ta_data.is_out_of_bounds(s.len())) + { + return Ok(0.into()); + } } // 6. Let offset be O.[[ByteOffset]]. // 7. Return 𝔽(offset). - Ok(ta.byte_offset().into()) + Ok(ta.borrow().data().byte_offset().into()) } /// `%TypedArray%.prototype.copyWithin ( target, start [ , end ] )` @@ -1326,27 +1313,23 @@ impl BuiltinTypedArray { // 1. Let O be the this value. // 2. Perform ? RequireInternalSlot(O, [[TypedArrayName]]). // 3. Assert: O has [[ViewedArrayBuffer]] and [[ArrayLength]] internal slots. - let object = this.as_object(); - let ta = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - JsNativeError::typ().with_message("`this` is not a typed array object") - })?; + let ta = this.require_internal_slot::()?; // 4. Let taRecord be MakeTypedArrayWithBufferWitnessRecord(O, seq-cst). // 5. If IsTypedArrayOutOfBounds(taRecord) is true, return +0𝔽. - let buf = ta.viewed_array_buffer().as_buffer(); + let ta_data = ta.borrow(); + let ta_data = ta_data.data(); + let buf = ta_data.viewed_array_buffer().as_buffer(); let Some(buf) = buf .bytes(Ordering::SeqCst) - .filter(|s| !ta.is_out_of_bounds(s.len())) + .filter(|s| !ta_data.is_out_of_bounds(s.len())) else { return Ok(0.into()); }; // 6. Let length be TypedArrayLength(taRecord). // 7. Return 𝔽(length). - Ok(ta.array_length(buf.len()).into()) + Ok(ta.borrow().data().array_length(buf.len()).into()) } /// `%TypedArray%.prototype.map ( callbackfn [ , thisArg ] )` @@ -1663,13 +1646,7 @@ impl BuiltinTypedArray { // 1. Let target be the this value. // 2. Perform ? RequireInternalSlot(target, [[TypedArrayName]]). // 3. Assert: target has a [[ViewedArrayBuffer]] internal slot. - let target = this - .as_object() - .and_then(|o| o.clone().downcast::().ok()) - .ok_or_else(|| { - JsNativeError::typ() - .with_message("TypedArray.set must be called on typed array object") - })?; + let target = this.require_internal_slot::()?; // 4. Let targetOffset be ? ToIntegerOrInfinity(offset). let target_offset = args.get_or_undefined(1).to_integer_or_infinity(context)?; @@ -2378,12 +2355,7 @@ impl BuiltinTypedArray { // 1. Let O be the this value. // 2. Perform ? RequireInternalSlot(O, [[TypedArrayName]]). // 3. Assert: O has a [[ViewedArrayBuffer]] internal slot. - let src = this - .as_object() - .and_then(|o| o.clone().downcast::().ok()) - .ok_or_else(|| { - JsNativeError::typ().with_message("Value is not a typed array object") - })?; + let src = this.require_internal_slot::()?; let src_borrow = src.borrow(); diff --git a/core/engine/src/builtins/typed_array/builtin_uint8.rs b/core/engine/src/builtins/typed_array/builtin_uint8.rs index 6709581640e..5161f8346cc 100644 --- a/core/engine/src/builtins/typed_array/builtin_uint8.rs +++ b/core/engine/src/builtins/typed_array/builtin_uint8.rs @@ -114,10 +114,7 @@ impl BuiltinUint8Array { ) -> JsResult { // 1. Let into be the this value. // 2. Perform ? ValidateUint8Array(into). - let uint8array = this - .as_object() - .and_then(|o| o.clone().downcast::().ok()) - .ok_or_else(|| JsNativeError::typ().with_message("Value is not a Uint8Array object"))?; + let uint8array = this.require_internal_slot::()?; let uint8array_borrow = uint8array.borrow(); let uint8array_data = uint8array_borrow.data(); @@ -226,10 +223,7 @@ impl BuiltinUint8Array { ) -> JsResult { // 1. Let O be the this value. // 2. Perform ? ValidateUint8Array(O). - let uint8array = this - .as_object() - .and_then(|o| o.clone().downcast::().ok()) - .ok_or_else(|| JsNativeError::typ().with_message("Value is not a Uint8Array object"))?; + let uint8array = this.require_internal_slot::()?; let uint8array_borrow = uint8array.borrow(); let uint8array_data = uint8array_borrow.data(); @@ -373,10 +367,7 @@ impl BuiltinUint8Array { ) -> JsResult { // 1. Let into be the this value. // 2. Perform ? ValidateUint8Array(into). - let uint8array = this - .as_object() - .and_then(|o| o.clone().downcast::().ok()) - .ok_or_else(|| JsNativeError::typ().with_message("Value is not a Uint8Array object"))?; + let uint8array = this.require_internal_slot::()?; let uint8array_borrow = uint8array.borrow(); let uint8array_data = uint8array_borrow.data(); @@ -501,10 +492,7 @@ impl BuiltinUint8Array { ) -> JsResult { // 1. Let O be the this value. // 2. Perform ? ValidateUint8Array(O). - let uint8array = this - .as_object() - .and_then(|o| o.clone().downcast::().ok()) - .ok_or_else(|| JsNativeError::typ().with_message("Value is not a Uint8Array object"))?; + let uint8array = this.require_internal_slot::()?; let uint8array_borrow = uint8array.borrow(); let uint8array_data = uint8array_borrow.data(); diff --git a/core/engine/src/builtins/typed_array/object.rs b/core/engine/src/builtins/typed_array/object.rs index e0642302421..23887ed593a 100644 --- a/core/engine/src/builtins/typed_array/object.rs +++ b/core/engine/src/builtins/typed_array/object.rs @@ -53,6 +53,13 @@ impl JsData for TypedArray { &METHODS } + + fn type_name() -> &'static str + where + Self: Sized, + { + "TypedArray" + } } impl TypedArray { @@ -197,12 +204,7 @@ impl TypedArray { /// [spec]: https://tc39.es/ecma262/sec-validatetypedarray pub(crate) fn validate(this: &JsValue, order: Ordering) -> JsResult<(JsObject, usize)> { // 1. Perform ? RequireInternalSlot(O, [[TypedArrayName]]). - let obj = this - .as_object() - .and_then(|o| o.clone().downcast::().ok()) - .ok_or_else(|| { - JsNativeError::typ().with_message("`this` is not a typed array object") - })?; + let obj = this.require_internal_slot::()?; let len = { let array = obj.borrow(); @@ -732,8 +734,7 @@ pub(crate) fn typed_array_set_element( ) -> JsResult<()> { let obj = obj .clone() - .downcast::() - .ok() + .require_internal_slot::() .js_expect("function can only be called for typed array objects")?; // b. Let arrayTypeName be the String value of O.[[TypedArrayName]]. // e. Let elementType be the Element Type value in Table 73 for arrayTypeName. diff --git a/core/engine/src/builtins/weak/weak_ref.rs b/core/engine/src/builtins/weak/weak_ref.rs index a2bd0c4cde2..d7e3527081a 100644 --- a/core/engine/src/builtins/weak/weak_ref.rs +++ b/core/engine/src/builtins/weak/weak_ref.rs @@ -1,4 +1,5 @@ use boa_gc::{Finalize, Trace, WeakGc}; +use boa_macros::JsData; use crate::{ Context, JsArgs, JsNativeError, JsResult, JsString, JsValue, @@ -22,8 +23,8 @@ use crate::{ /// - [ECMAScript Reference][spec] /// /// [spec]: https://tc39.es/ecma262/#sec-weak-ref-objects -#[derive(Debug, Clone, Trace, Finalize)] -pub(crate) struct WeakRef; +#[derive(Clone, Trace, Finalize, JsData)] +pub(crate) struct WeakRef(pub(crate) WeakGc); impl IntrinsicObject for WeakRef { fn get(intrinsics: &Intrinsics) -> JsObject { @@ -87,7 +88,7 @@ impl BuiltInConstructor for WeakRef { let weak_ref = JsObject::from_proto_and_data_with_shared_shape( context.root_shape(), prototype, - WeakGc::new(target.inner()), + WeakRef(WeakGc::new(target.inner())), ); // 4. Perform AddToKeptObjects(target). @@ -108,15 +109,7 @@ impl WeakRef { pub(crate) fn deref(this: &JsValue, _: &[JsValue], context: &mut Context) -> JsResult { // 1. Let weakRef be the this value. // 2. Perform ? RequireInternalSlot(weakRef, [[WeakRefTarget]]). - let object = this.as_object(); - let weak_ref = object - .as_ref() - .and_then(JsObject::downcast_ref::>) - .ok_or_else(|| { - JsNativeError::typ().with_message( - "WeakRef.prototype.deref: expected `this` to be a `WeakRef` object", - ) - })?; + let weak_ref = this.require_internal_slot::()?; // 3. Return WeakRefDeref(weakRef). @@ -124,7 +117,7 @@ impl WeakRef { // https://tc39.es/ecma262/multipage/managing-memory.html#sec-weakrefderef // 1. Let target be weakRef.[[WeakRefTarget]]. // 2. If target is not empty, then - if let Some(object) = weak_ref.upgrade() { + if let Some(object) = weak_ref.borrow().data().0.upgrade() { let object = JsObject::from(object); // a. Perform AddToKeptObjects(target). @@ -229,7 +222,7 @@ mod tests { run_test_actions([TestAction::assert_native_error( "WeakRef.prototype.deref.call({})", JsNativeErrorKind::Type, - "WeakRef.prototype.deref: expected `this` to be a `WeakRef` object", + "object does not contain required internal slot `WeakRef`", )]); } diff --git a/core/engine/src/builtins/weak_map/mod.rs b/core/engine/src/builtins/weak_map/mod.rs index 5ef5abc8c83..3179956face 100644 --- a/core/engine/src/builtins/weak_map/mod.rs +++ b/core/engine/src/builtins/weak_map/mod.rs @@ -22,11 +22,12 @@ use crate::{ symbol::JsSymbol, }; use boa_gc::{Finalize, Trace}; +use boa_macros::JsData; pub(crate) type NativeWeakMap = boa_gc::WeakMap; -#[derive(Debug, Trace, Finalize)] -pub(crate) struct WeakMap; +#[derive(Trace, Finalize, JsData)] +pub(crate) struct WeakMap(pub(crate) NativeWeakMap); #[cfg(test)] mod tests; @@ -97,7 +98,7 @@ impl BuiltInConstructor for WeakMap { let map = JsObject::from_proto_and_data_with_shared_shape( context.root_shape(), prototype, - NativeWeakMap::new(), + WeakMap(NativeWeakMap::new()), ) .upcast(); @@ -138,7 +139,7 @@ impl WeakMap { let object = this.as_object(); let mut map = object .as_ref() - .and_then(JsObject::downcast_mut::) + .and_then(JsObject::downcast_mut::) .ok_or_else(|| { js_error!(TypeError: "WeakMap.prototype.delete: expected 'this' to be a WeakMap object", @@ -157,7 +158,7 @@ impl WeakMap { // ii. Set p.[[Value]] to empty. // iii. Return true. // 6. Return false. - Ok(map.remove(key.inner()).into()) + Ok(map.0.remove(key.inner()).into()) } /// `WeakMap.prototype.get ( key )` @@ -175,14 +176,7 @@ impl WeakMap { ) -> JsResult { // 1. Let M be the this value. // 2. Perform ? RequireInternalSlot(M, [[WeakMapData]]). - let object = this.as_object(); - let map = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - js_error!(TypeError: - "WeakMap.prototype.get: expected 'this' to be a WeakMap object") - })?; + let map = this.require_internal_slot::()?; // 3. Let entries be M.[[WeakMapData]]. // 4. If key is not an Object, return undefined. @@ -193,7 +187,7 @@ impl WeakMap { // 5. For each Record { [[Key]], [[Value]] } p of entries, do // a. If p.[[Key]] is not empty and SameValue(p.[[Key]], key) is true, return p.[[Value]]. // 6. Return undefined. - if let Some(entry) = map.get(key.inner()) + if let Some(entry) = map.borrow().data().0.get(key.inner()) && let Some(val) = entry.value() { Ok(val.clone()) @@ -217,14 +211,7 @@ impl WeakMap { ) -> JsResult { // 1. Let M be the this value. // 2. Perform ? RequireInternalSlot(M, [[WeakMapData]]). - let object = this.as_object(); - let map = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - js_error!(TypeError: - "WeakMap.prototype.has: expected 'this' to be a WeakMap object") - })?; + let map = this.require_internal_slot::()?; // 3. Let entries be M.[[WeakMapData]]. // 4. If key is not an Object, return false. @@ -235,7 +222,7 @@ impl WeakMap { // 5. For each Record { [[Key]], [[Value]] } p of entries, do // a. If p.[[Key]] is not empty and SameValue(p.[[Key]], key) is true, return true. // 6. Return false. - Ok(map.contains_key(key.inner()).into()) + Ok(map.borrow().data().0.contains_key(key.inner()).into()) } /// `WeakMap.prototype.set ( key, value )` @@ -256,7 +243,7 @@ impl WeakMap { let object = this.as_object(); let mut map = object .as_ref() - .and_then(JsObject::downcast_mut::) + .and_then(JsObject::downcast_mut::) .ok_or_else(|| { js_error!(TypeError: "WeakMap.prototype.set: expected 'this' to be a WeakMap object") @@ -278,7 +265,7 @@ impl WeakMap { // ii. Return M. // 6. Let p be the Record { [[Key]]: key, [[Value]]: value }. // 7. Append p to entries. - map.insert(key.inner(), args.get_or_undefined(1).clone()); + map.0.insert(key.inner(), args.get_or_undefined(1).clone()); // 8. Return M. Ok(this.clone()) @@ -302,14 +289,7 @@ impl WeakMap { ) -> JsResult { // 1. Let M be the this value. // 2. Perform ? RequireInternalSlot(M, [[WeakMapData]]). - let object = this.as_object(); - let map = object - .and_then(|obj| obj.clone().downcast::().ok()) - .ok_or_else(|| { - js_error!(TypeError: - "WeakMap.prototype.getOrInsert: expected 'this' to be a WeakMap object", - ) - })?; + let map = this.require_internal_slot::()?; // 3. If CanBeHeldWeakly(key) is false, throw a TypeError exception. // TODO: Implement proper CanBeHeldWeakly once available. For now, only @@ -324,7 +304,7 @@ impl WeakMap { }; // 4. For each Record { [[Key]], [[Value]] } p of M.[[WeakMapData]] - if let Some(existing) = map.borrow().data().get(key.inner()) + if let Some(existing) = map.borrow().data().0.get(key.inner()) && let Some(value) = existing.value() { // a. If p.[[Key]] is not empty and SameValue(p.[[Key]], key) is true, return p.[[Value]]. @@ -335,6 +315,7 @@ impl WeakMap { let value = args.get_or_undefined(1).clone(); map.borrow_mut() .data_mut() + .0 .insert(key.inner(), value.clone()); Ok(value) } @@ -357,14 +338,7 @@ impl WeakMap { ) -> JsResult { // 1. Let M be the this value. // 2. Perform ? RequireInternalSlot(M, [[WeakMapData]]). - let object = this.as_object(); - let map = object - .and_then(|obj| obj.clone().downcast::().ok()) - .ok_or_else(|| { - js_error!(TypeError: - "WeakMap.prototype.getOrInsertComputed: expected 'this' to be a WeakMap object", - ) - })?; + let map = this.require_internal_slot::()?; // 3. If CanBeHeldWeakly(key) is false, throw a TypeError exception. // TODO: Implement proper CanBeHeldWeakly once available. For now, only @@ -386,7 +360,7 @@ impl WeakMap { }; // 5. For each Record { [[Key]], [[Value]] } p of M.[[WeakMapData]] - if let Some(existing) = map.borrow().data().get(key_obj.inner()) + if let Some(existing) = map.borrow().data().0.get(key_obj.inner()) && let Some(value) = existing.value() { // a. If p.[[Key]] is not empty and SameValue(p.[[Key]], key) is true, return p.[[Value]]. @@ -404,6 +378,7 @@ impl WeakMap { // 8-10. Insert or update the entry and return value. map.borrow_mut() .data_mut() + .0 .insert(key_obj.inner(), value.clone()); Ok(value) } diff --git a/core/engine/src/builtins/weak_map/tests.rs b/core/engine/src/builtins/weak_map/tests.rs index a619e295409..134235e164a 100644 --- a/core/engine/src/builtins/weak_map/tests.rs +++ b/core/engine/src/builtins/weak_map/tests.rs @@ -101,7 +101,7 @@ fn get_or_insert_this_not_weakmap() { run_test_actions([TestAction::assert_native_error( "WeakMap.prototype.getOrInsert.call({}, {}, 1)", JsNativeErrorKind::Type, - "WeakMap.prototype.getOrInsert: expected 'this' to be a WeakMap object", + "object does not contain required internal slot `WeakMap`", )]); } @@ -110,7 +110,7 @@ fn get_or_insert_computed_this_not_weakmap() { run_test_actions([TestAction::assert_native_error( "WeakMap.prototype.getOrInsertComputed.call({}, {}, x => x)", JsNativeErrorKind::Type, - "WeakMap.prototype.getOrInsertComputed: expected 'this' to be a WeakMap object", + "object does not contain required internal slot `WeakMap`", )]); } diff --git a/core/engine/src/builtins/weak_set/mod.rs b/core/engine/src/builtins/weak_set/mod.rs index 7e9575f802f..fdd964c5896 100644 --- a/core/engine/src/builtins/weak_set/mod.rs +++ b/core/engine/src/builtins/weak_set/mod.rs @@ -19,13 +19,14 @@ use crate::{ symbol::JsSymbol, }; use boa_gc::{Finalize, Trace}; +use boa_macros::JsData; use super::iterable::IteratorHint; pub(crate) type NativeWeakSet = boa_gc::WeakMap; -#[derive(Debug, Trace, Finalize)] -pub(crate) struct WeakSet; +#[derive(Trace, Finalize, JsData)] +pub(crate) struct WeakSet(pub(crate) NativeWeakSet); impl IntrinsicObject for WeakSet { fn get(intrinsics: &Intrinsics) -> JsObject { @@ -86,7 +87,7 @@ impl BuiltInConstructor for WeakSet { let weak_set = JsObject::from_proto_and_data_with_shared_shape( context.root_shape(), prototype, - NativeWeakSet::new(), + WeakSet(NativeWeakSet::new()), ) .upcast(); @@ -143,7 +144,7 @@ impl WeakSet { let object = this.as_object(); let mut set = object .as_ref() - .and_then(JsObject::downcast_mut::) + .and_then(JsObject::downcast_mut::) .ok_or_else(|| { js_error!(TypeError: "WeakSet.prototype.add: expected 'this' to be a WeakSet object") @@ -160,14 +161,14 @@ impl WeakSet { // 4. Let entries be the List that is S.[[WeakSetData]]. // 5. For each element e of entries, do - if set.contains_key(value.inner()) { + if set.0.contains_key(value.inner()) { // a. If e is not empty and SameValue(e, value) is true, then // i. Return S. return Ok(this.clone()); } // 6. Append value as the last element of entries. - set.insert(value.inner(), ()); + set.0.insert(value.inner(), ()); // 7. Return S. Ok(this.clone()) @@ -193,7 +194,7 @@ impl WeakSet { let object = this.as_object(); let mut set = object .as_ref() - .and_then(JsObject::downcast_mut::) + .and_then(JsObject::downcast_mut::) .ok_or_else(|| { js_error!(TypeError: "WeakSet.prototype.delete: expected 'this' to be a WeakSet object", @@ -212,7 +213,7 @@ impl WeakSet { // i. Replace the element of entries whose value is e with an element whose value is empty. // ii. Return true. // 6. Return false. - Ok(set.remove(value.inner()).into()) + Ok(set.0.remove(value.inner()).into()) } /// `WeakSet.prototype.has( value )` @@ -232,14 +233,7 @@ impl WeakSet { ) -> JsResult { // 1. Let S be the this value. // 2. Perform ? RequireInternalSlot(S, [[WeakSetData]]). - let object = this.as_object(); - let set = object - .as_ref() - .and_then(JsObject::downcast_ref::) - .ok_or_else(|| { - js_error!(TypeError: - "WeakSet.prototype.has: expected 'this' to be a WeakSet object") - })?; + let set = this.require_internal_slot::()?; // 3. Let entries be the List that is S.[[WeakSetData]]. // 4. If Type(value) is not Object, return false. @@ -251,7 +245,7 @@ impl WeakSet { // 5. For each element e of entries, do // a. If e is not empty and SameValue(e, value) is true, return true. // 6. Return false. - Ok(set.contains_key(value.inner()).into()) + Ok(set.borrow().data().0.contains_key(value.inner()).into()) } } diff --git a/core/engine/src/interop/into_js_arguments.rs b/core/engine/src/interop/into_js_arguments.rs index f32810a2fdc..b7bb783ccbf 100644 --- a/core/engine/src/interop/into_js_arguments.rs +++ b/core/engine/src/interop/into_js_arguments.rs @@ -289,10 +289,7 @@ impl<'a, T: NativeObject + 'static> TryFromJsArgument<'a> for JsClass { rest: &'a [JsValue], _context: &mut Context, ) -> JsResult<(Self, &'a [JsValue])> { - let inner = this - .as_object() - .and_then(|o| o.clone().downcast::().ok()) - .ok_or_else(|| JsNativeError::typ().with_message("invalid this for class method"))?; + let inner = this.require_internal_slot::()?; Ok((JsClass { inner }, rest)) } diff --git a/core/engine/src/module/namespace.rs b/core/engine/src/module/namespace.rs index c686802a671..de5cc8777d0 100644 --- a/core/engine/src/module/namespace.rs +++ b/core/engine/src/module/namespace.rs @@ -60,6 +60,13 @@ impl JsData for ModuleNamespace { &METHODS } + + fn type_name() -> &'static str + where + Self: Sized, + { + "ModuleNamespace" + } } impl ModuleNamespace { diff --git a/core/engine/src/native_function/mod.rs b/core/engine/src/native_function/mod.rs index c6b0c7afb24..5abf43d15a3 100644 --- a/core/engine/src/native_function/mod.rs +++ b/core/engine/src/native_function/mod.rs @@ -113,6 +113,13 @@ impl JsData for NativeFunctionObject { &FUNCTION } } + + fn type_name() -> &'static str + where + Self: Sized, + { + "NativeFunctionObject" + } } /// A callable Rust function that can be invoked by the engine. diff --git a/core/engine/src/object/builtins/jsarraybuffer.rs b/core/engine/src/object/builtins/jsarraybuffer.rs index b377f684dee..02d63903cb5 100644 --- a/core/engine/src/object/builtins/jsarraybuffer.rs +++ b/core/engine/src/object/builtins/jsarraybuffer.rs @@ -148,14 +148,9 @@ impl JsArrayBuffer { /// This does not clone the fields of the array buffer, it only does a shallow clone of the object. #[inline] pub fn from_object(object: JsObject) -> JsResult { - object - .downcast::() - .map(|inner| Self { inner }) - .map_err(|_| { - JsNativeError::typ() - .with_message("object is not an ArrayBuffer") - .into() - }) + Ok(Self { + inner: object.require_internal_slot::()?, + }) } /// Returns the byte length of the array buffer. diff --git a/core/engine/src/object/builtins/jsasyncgenerator.rs b/core/engine/src/object/builtins/jsasyncgenerator.rs index 8cb567880e0..8db5ec3086c 100644 --- a/core/engine/src/object/builtins/jsasyncgenerator.rs +++ b/core/engine/src/object/builtins/jsasyncgenerator.rs @@ -3,7 +3,6 @@ use super::JsPromise; use crate::{ Context, JsNativeError, JsResult, JsValue, builtins::{async_generator::AsyncGenerator, promise::PromiseCapability}, - js_error, object::JsObject, value::TryFromJs, }; @@ -26,10 +25,9 @@ impl JsAsyncGenerator { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AsyncGenerator #[inline] pub fn from_object(object: JsObject) -> JsResult { - object - .downcast::() - .map(|inner| Self { inner }) - .map_err(|_| js_error!(TypeError: "object is not an AsyncGenerator object")) + Ok(Self { + inner: object.require_internal_slot::()?, + }) } /// Calls `AsyncGenerator.prototype.next()`. diff --git a/core/engine/src/object/builtins/jsdataview.rs b/core/engine/src/object/builtins/jsdataview.rs index 7bf07ade92d..f2b6a8c9cdf 100644 --- a/core/engine/src/object/builtins/jsdataview.rs +++ b/core/engine/src/object/builtins/jsdataview.rs @@ -154,14 +154,9 @@ impl JsDataView { /// Create a new `JsDataView` object from an existing object. #[inline] pub fn from_object(object: JsObject) -> JsResult { - object - .downcast::() - .map(|inner| Self { inner }) - .map_err(|_| { - JsNativeError::typ() - .with_message("object is not a DataView") - .into() - }) + Ok(Self { + inner: object.require_internal_slot::()?, + }) } /// Returns the `viewed_array_buffer` field for [`JsDataView`] diff --git a/core/engine/src/object/builtins/jsmap.rs b/core/engine/src/object/builtins/jsmap.rs index c35a014cdbf..bffaa52364c 100644 --- a/core/engine/src/object/builtins/jsmap.rs +++ b/core/engine/src/object/builtins/jsmap.rs @@ -154,10 +154,7 @@ impl JsMap { /// # fn main() -> JsResult<()> { /// # let context = &mut Context::default(); /// // `some_object` can be any JavaScript `Map` object. - /// let some_object = JsObject::from_proto_and_data( - /// context.intrinsics().constructors().map().prototype(), - /// OrderedMap::::new(), - /// ); + /// let some_object: JsObject = JsMap::new(context).into(); /// /// // Create `JsMap` object with incoming object. /// let js_map = JsMap::from_object(some_object)?; @@ -182,13 +179,9 @@ impl JsMap { /// ``` #[inline] pub fn from_object(object: JsObject) -> JsResult { - if object.is::>() { - Ok(Self { inner: object }) - } else { - Err(JsNativeError::typ() - .with_message("object is not a Map") - .into()) - } + Ok(Self { + inner: object.require_internal_slot::()?.upcast(), + }) } // Utility function to generate the default `Map` object. @@ -200,7 +193,7 @@ impl JsMap { JsObject::from_proto_and_data_with_shared_shape( context.root_shape(), prototype, - >::new(), + Map(>::new()), ) .upcast() } diff --git a/core/engine/src/object/builtins/jspromise.rs b/core/engine/src/object/builtins/jspromise.rs index a2ed16760ea..1b57055fa8b 100644 --- a/core/engine/src/object/builtins/jspromise.rs +++ b/core/engine/src/object/builtins/jspromise.rs @@ -261,12 +261,9 @@ impl JsPromise { /// ``` #[inline] pub fn from_object(object: JsObject) -> JsResult { - let Ok(inner) = object.downcast::() else { - return Err(JsNativeError::typ() - .with_message("`object` is not a Promise") - .into()); - }; - Ok(Self { inner }) + Ok(Self { + inner: object.require_internal_slot::()?, + }) } /// Creates a new `JsPromise` from a [`Future`]-like. diff --git a/core/engine/src/object/builtins/jsset.rs b/core/engine/src/object/builtins/jsset.rs index 01efe9407d6..21bdb2f9631 100644 --- a/core/engine/src/object/builtins/jsset.rs +++ b/core/engine/src/object/builtins/jsset.rs @@ -17,7 +17,7 @@ use crate::{ /// `JsSet` provides a wrapper for Boa's implementation of the ECMAScript `Set` object. #[derive(Debug, Clone, Trace, Finalize)] pub struct JsSet { - inner: JsObject, + inner: JsObject, } impl JsSet { @@ -31,7 +31,7 @@ impl JsSet { inner: JsObject::from_proto_and_data_with_shared_shape( context.root_shape(), context.intrinsics().constructors().set().prototype(), - OrderedSet::new(), + Set(OrderedSet::new()), ), } } @@ -42,7 +42,7 @@ impl JsSet { #[inline] #[must_use] pub fn size(&self) -> usize { - self.inner.borrow().data().len() + self.inner.borrow().data().0.len() } /// Appends value to the Set object. @@ -70,7 +70,7 @@ impl JsSet { /// Same as JavaScript's `set.clear()`. #[inline] pub fn clear(&self) { - self.inner.borrow_mut().data_mut().clear(); + self.inner.borrow_mut().data_mut().0.clear(); } /// Removes the element associated to the value. @@ -84,6 +84,7 @@ impl JsSet { { self.borrow_mut() .data_mut() + .0 .delete(&canonicalize_keyed_collection_key(value.into())) } @@ -98,6 +99,7 @@ impl JsSet { { self.borrow() .data() + .0 .contains(&canonicalize_keyed_collection_key(value.into())) } @@ -158,7 +160,7 @@ impl JsSet { /// Utility: Creates `JsSet` from `JsObject`, otherwise returns the original object as an `Err`. #[inline] pub fn from_object(object: JsObject) -> Result { - object.downcast::().map(|o| Self { inner: o }) + object.downcast::().map(|o| Self { inner: o }) } /// Utility: Creates a `JsSet` from a `` convertible object. @@ -181,14 +183,14 @@ impl JsSet { inner: JsObject::from_proto_and_data_with_shared_shape( context.root_shape(), context.intrinsics().constructors().set().prototype(), - set, + Set(set), ), } } } -impl From> for JsSet { - fn from(value: JsObject) -> Self { +impl From> for JsSet { + fn from(value: JsObject) -> Self { Self { inner: value } } } @@ -208,7 +210,7 @@ impl From for JsValue { } impl Deref for JsSet { - type Target = JsObject; + type Target = JsObject; #[inline] fn deref(&self) -> &Self::Target { &self.inner diff --git a/core/engine/src/object/builtins/jssharedarraybuffer.rs b/core/engine/src/object/builtins/jssharedarraybuffer.rs index b23d7f4e56f..f7f82e7614e 100644 --- a/core/engine/src/object/builtins/jssharedarraybuffer.rs +++ b/core/engine/src/object/builtins/jssharedarraybuffer.rs @@ -70,14 +70,9 @@ impl JsSharedArrayBuffer { /// the object. #[inline] pub fn from_object(object: JsObject) -> JsResult { - object - .downcast::() - .map(|inner| Self { inner }) - .map_err(|_| { - JsNativeError::typ() - .with_message("object is not a SharedArrayBuffer") - .into() - }) + Ok(Self { + inner: object.require_internal_slot::()?, + }) } /// Returns the byte length of the array buffer. diff --git a/core/engine/src/object/builtins/jsweakmap.rs b/core/engine/src/object/builtins/jsweakmap.rs index fe2d42d8cb7..5c12a2e34bc 100644 --- a/core/engine/src/object/builtins/jsweakmap.rs +++ b/core/engine/src/object/builtins/jsweakmap.rs @@ -30,7 +30,7 @@ impl JsWeakMap { inner: JsObject::from_proto_and_data_with_shared_shape( context.root_shape(), context.intrinsics().constructors().weak_map().prototype(), - NativeWeakMap::new(), + WeakMap(NativeWeakMap::new()), ) .upcast(), } @@ -134,7 +134,7 @@ impl JsWeakMap { /// if it is not a `WeakMap`. #[inline] pub fn from_object(object: JsObject) -> Result { - if object.downcast_ref::().is_some() { + if object.downcast_ref::().is_some() { Ok(Self { inner: object }) } else { Err(object) diff --git a/core/engine/src/object/builtins/jsweakset.rs b/core/engine/src/object/builtins/jsweakset.rs index 1409a81edb8..d9a2d0c6d9b 100644 --- a/core/engine/src/object/builtins/jsweakset.rs +++ b/core/engine/src/object/builtins/jsweakset.rs @@ -30,7 +30,7 @@ impl JsWeakSet { inner: JsObject::from_proto_and_data_with_shared_shape( context.root_shape(), context.intrinsics().constructors().weak_set().prototype(), - NativeWeakSet::new(), + WeakSet(NativeWeakSet::new()), ) .upcast(), } diff --git a/core/engine/src/object/datatypes.rs b/core/engine/src/object/datatypes.rs index 31ff76f55b9..7216a9e4d3b 100644 --- a/core/engine/src/object/datatypes.rs +++ b/core/engine/src/object/datatypes.rs @@ -46,6 +46,15 @@ pub trait JsData { { &ORDINARY_INTERNAL_METHODS } + + #[doc(hidden)] + #[must_use] + fn type_name() -> &'static str + where + Self: Sized, + { + std::any::type_name::() + } } macro_rules! default_impls { diff --git a/core/engine/src/object/internal_methods/string.rs b/core/engine/src/object/internal_methods/string.rs index f0d4212d49d..935932d8c6e 100644 --- a/core/engine/src/object/internal_methods/string.rs +++ b/core/engine/src/object/internal_methods/string.rs @@ -17,6 +17,13 @@ impl JsData for JsString { &METHODS } + + fn type_name() -> &'static str + where + Self: Sized, + { + "JsString" + } } /// Gets own property of 'String' exotic object diff --git a/core/engine/src/object/jsobject.rs b/core/engine/src/object/jsobject.rs index 97928bdcd3c..a8d6177f203 100644 --- a/core/engine/src/object/jsobject.rs +++ b/core/engine/src/object/jsobject.rs @@ -54,7 +54,14 @@ pub type ErasedObject = Object; #[derive(Debug, Trace, Finalize)] pub struct ErasedObjectData {} -impl JsData for ErasedObjectData {} +impl JsData for ErasedObjectData { + fn type_name() -> &'static str + where + Self: Sized, + { + "ErasedObjectData" + } +} /// Garbage collected `Object`. #[derive(Trace, Finalize)] @@ -307,6 +314,13 @@ impl JsObject { JsObject { inner } } + /// Downcasts `self` to a `JsObject`, returning a + /// `TypeError` if the cast fails. + pub fn require_internal_slot(self) -> JsResult> { + self.downcast::() + .map_err(|_| js_error!(TypeError: "object does not contain required internal slot `{}`", T::type_name())) + } + /// Downcasts a reference to the object, /// if the object is of type `T`. /// diff --git a/core/engine/src/object/mod.rs b/core/engine/src/object/mod.rs index aeaf2e37a9d..dd311a5123e 100644 --- a/core/engine/src/object/mod.rs +++ b/core/engine/src/object/mod.rs @@ -87,11 +87,7 @@ impl NativeObject for T { } fn type_name_of_value(&self) -> &'static str { - fn name_of_val(_val: &T) -> &'static str { - std::any::type_name::() - } - - name_of_val(self) + T::type_name() } } diff --git a/core/engine/src/value/display/map.rs b/core/engine/src/value/display/map.rs index ea0124f4218..d4014998686 100644 --- a/core/engine/src/value/display/map.rs +++ b/core/engine/src/value/display/map.rs @@ -1,7 +1,7 @@ use std::collections::HashSet; use std::fmt; -use crate::{JsObject, JsValue, builtins::map::ordered_map::OrderedMap}; +use crate::{JsObject, builtins::map::Map}; pub(super) fn log_map_to( f: &mut fmt::Formatter<'_>, @@ -9,10 +9,8 @@ pub(super) fn log_map_to( print_internals: bool, print_children: bool, ) -> fmt::Result { - let map = v - .downcast_ref::>() - .expect("object must be a map"); - let size = map.len(); + let map = v.downcast_ref::().expect("object must be a map"); + let size = map.0.len(); if size == 0 { return f.write_str("Map(0)"); @@ -24,7 +22,7 @@ pub(super) fn log_map_to( f.write_str("Map { ")?; let mut first = true; - for (key, value) in map.iter() { + for (key, value) in map.0.iter() { if !first { f.write_str(", ")?; } @@ -43,10 +41,8 @@ pub(super) fn log_map_compact( print_internals: bool, encounters: &mut HashSet, ) -> fmt::Result { - let map = v - .downcast_ref::>() - .expect("object must be a map"); - let size = map.len(); + let map = v.downcast_ref::().expect("object must be a map"); + let size = map.0.len(); if size == 0 { return f.write_str("Map(0)"); @@ -58,7 +54,7 @@ pub(super) fn log_map_compact( f.write_str("Map { ")?; let mut first = true; - for (key, value) in map.iter() { + for (key, value) in map.0.iter() { if !first { f.write_str(", ")?; } diff --git a/core/engine/src/value/display/set.rs b/core/engine/src/value/display/set.rs index 6aa86511bc1..4269a861c3c 100644 --- a/core/engine/src/value/display/set.rs +++ b/core/engine/src/value/display/set.rs @@ -1,7 +1,7 @@ use std::collections::HashSet; use std::fmt; -use crate::{JsObject, builtins::set::ordered_set::OrderedSet}; +use crate::{JsObject, builtins::set::Set}; pub(super) fn log_set_to( f: &mut fmt::Formatter<'_>, @@ -9,10 +9,8 @@ pub(super) fn log_set_to( print_internals: bool, print_children: bool, ) -> fmt::Result { - let set = v - .downcast_ref::() - .expect("object must be a set"); - let size = set.len(); + let set = v.downcast_ref::().expect("object must be a set"); + let size = set.0.len(); if size == 0 { return f.write_str("Set(0)"); @@ -24,7 +22,7 @@ pub(super) fn log_set_to( f.write_str("Set { ")?; let mut first = true; - for value in set.iter() { + for value in set.0.iter() { if !first { f.write_str(", ")?; } @@ -41,10 +39,8 @@ pub(super) fn log_set_compact( print_internals: bool, encounters: &mut HashSet, ) -> fmt::Result { - let set = v - .downcast_ref::() - .expect("object must be a set"); - let size = set.len(); + let set = v.downcast_ref::().expect("object must be a set"); + let size = set.0.len(); if size == 0 { return f.write_str("Set(0)"); @@ -56,7 +52,7 @@ pub(super) fn log_set_compact( f.write_str("Set { ")?; let mut first = true; - for value in set.iter() { + for value in set.0.iter() { if !first { f.write_str(", ")?; } diff --git a/core/engine/src/value/display/value.rs b/core/engine/src/value/display/value.rs index 9522825ee51..19f5847dc66 100644 --- a/core/engine/src/value/display/value.rs +++ b/core/engine/src/value/display/value.rs @@ -1,6 +1,9 @@ use std::collections::HashSet; use std::fmt::{self, Display}; +use crate::builtins::Map; +use crate::builtins::weak_map::WeakMap; +use crate::builtins::weak_set::WeakSet; use crate::property::CompletePropertyDescriptor; use crate::{ JsError, JsString, JsValue, JsVariant, @@ -11,12 +14,9 @@ use crate::{ OrdinaryFunction, arguments::{MappedArguments, UnmappedArguments}, }, - map::ordered_map::OrderedMap, promise::PromiseState, - set::ordered_set::OrderedSet, + set::Set, typed_array::TypedArray, - weak_map::NativeWeakMap, - weak_set::NativeWeakSet, }, js_string, property::PropertyKey, @@ -48,13 +48,13 @@ pub(crate) fn log_value_to( super::array::log_array_to(f, &v, print_internals, print_children) } else if v.is::() || v.is::() { super::arguments::log_arguments_to(f, &v, print_internals, print_children) - } else if v.downcast_ref::>().is_some() { + } else if v.downcast_ref::().is_some() { super::map::log_map_to(f, &v, print_internals, print_children) - } else if v.downcast_ref::().is_some() { + } else if v.downcast_ref::().is_some() { super::set::log_set_to(f, &v, print_internals, print_children) - } else if v.downcast_ref::().is_some() { + } else if v.downcast_ref::().is_some() { f.write_str("WeakMap { }") - } else if v.downcast_ref::().is_some() { + } else if v.downcast_ref::().is_some() { f.write_str("WeakSet { }") } else if v.is::() { let name: std::borrow::Cow<'static, str> = v @@ -203,13 +203,13 @@ pub(super) fn log_value_compact( } } else if v.is::() || v.is::() { f.write_str("[Arguments]") - } else if v.downcast_ref::>().is_some() { + } else if v.downcast_ref::().is_some() { super::map::log_map_compact(f, &v, depth, print_internals, encounters) - } else if v.downcast_ref::().is_some() { + } else if v.downcast_ref::().is_some() { super::set::log_set_compact(f, &v, depth, print_internals, encounters) - } else if v.downcast_ref::().is_some() { + } else if v.downcast_ref::().is_some() { f.write_str("WeakMap { }") - } else if v.downcast_ref::().is_some() { + } else if v.downcast_ref::().is_some() { f.write_str("WeakSet { }") } else if v.downcast_ref::().is_some() || v.downcast_ref::() diff --git a/core/engine/src/value/mod.rs b/core/engine/src/value/mod.rs index e92d4809447..4c52559e5b1 100644 --- a/core/engine/src/value/mod.rs +++ b/core/engine/src/value/mod.rs @@ -37,6 +37,7 @@ use crate::{ property::{PropertyDescriptor, PropertyKey}, symbol::JsSymbol, }; +use crate::{NativeObject, js_error}; mod conversions; pub(crate) mod display; @@ -1476,6 +1477,20 @@ impl JsValue { } } + /// Downcasts `self` to a `JsObject`, returning a + /// `TypeError` if the cast fails. + pub fn require_internal_slot(&self) -> JsResult> { + let Some(obj) = self.as_object() else { + return Err(js_error!( + TypeError: "cannot downcast a value of type `{}` to an object with internal slot `{}`", + self.type_of(), + T::type_name() + )); + }; + + obj.require_internal_slot() + } + /// The abstract operation `ToPropertyDescriptor`. /// /// More information: diff --git a/core/macros/src/lib.rs b/core/macros/src/lib.rs index 0d3579b5f48..e5b7bbbaa5d 100644 --- a/core/macros/src/lib.rs +++ b/core/macros/src/lib.rs @@ -453,7 +453,15 @@ decl_derive! { /// Derives the `JsData` trait. #[allow(clippy::needless_pass_by_value)] fn derive_js_data(s: Structure<'_>) -> proc_macro2::TokenStream { - s.unbound_impl(quote!(::boa_engine::JsData), quote!()) + let name = &s.ast().ident.to_string(); + s.unbound_impl( + quote!(::boa_engine::JsData), + quote!( + fn type_name() -> &'static str { + #name + } + ), + ) } /// Derives the `TryFromJs` trait, with the `#[boa()]` attribute. diff --git a/core/runtime/src/fetch/mod.rs b/core/runtime/src/fetch/mod.rs index 22fea5d2977..3f8a2fd4f6d 100644 --- a/core/runtime/src/fetch/mod.rs +++ b/core/runtime/src/fetch/mod.rs @@ -137,9 +137,7 @@ async fn fetch_inner( } Either::Right(request) => { // This can be a [`JsRequest`] object. - let Ok(request) = request.downcast::() else { - return Err(js_error!(TypeError: "Resource must be a URL or Request object")); - }; + let request = request.require_internal_slot::()?; let Ok(request_ref) = request.try_borrow() else { return Err(js_error!(TypeError: "Request object is already in use")); }; @@ -214,15 +212,7 @@ fn headers_symbol_iterator( _: &[JsValue], context: &mut Context, ) -> JsResult { - let this_object = this.as_object().ok_or_else( - || js_error!(TypeError: "`Headers.prototype[Symbol.iterator]` requires a `Headers` object"), - )?; - - let Ok(headers) = this_object.clone().downcast::() else { - return Err( - js_error!(TypeError: "`Headers.prototype[Symbol.iterator]` requires a `Headers` object"), - ); - }; + let headers = this.require_internal_slot::()?; HeadersIterator::create_headers_iterator(headers, IterationKind::KeyAndValue, context) } diff --git a/core/runtime/src/fetch/request.rs b/core/runtime/src/fetch/request.rs index 79f6c377f02..023ec4fbade 100644 --- a/core/runtime/src/fetch/request.rs +++ b/core/runtime/src/fetch/request.rs @@ -220,13 +220,13 @@ impl JsRequest { // Need to use a match as `Either::map_right` does not have an equivalent // `Either::map_right_ok`. let input = match input { - Either::Right(r) => { - if let Ok(request) = r.clone().downcast::() { - Either::Right(request.borrow().data().clone()) - } else { - return Err(js_error!(TypeError: "invalid input argument")); - } - } + Either::Right(r) => Either::Right( + r.clone() + .require_internal_slot::()? + .borrow() + .data() + .clone(), + ), Either::Left(i) => Either::Left(i), }; JsRequest::create_from_js(input, options) diff --git a/core/runtime/src/fetch/tests/headers.rs b/core/runtime/src/fetch/tests/headers.rs index ae19b97ae5e..7c015e32668 100644 --- a/core/runtime/src/fetch/tests/headers.rs +++ b/core/runtime/src/fetch/tests/headers.rs @@ -132,7 +132,7 @@ fn headers_iterator_throws_on_invalid_this() { throw Error("expected the call above to throw"); } catch (e) { assert(e instanceof TypeError); - assertEq(e.message, "`Headers.prototype[Symbol.iterator]` requires a `Headers` object"); + assertEq(e.message, "object does not contain required internal slot `JsHeaders`"); } try { @@ -140,7 +140,7 @@ fn headers_iterator_throws_on_invalid_this() { throw Error("expected the call above to throw"); } catch (e) { assert(e instanceof TypeError); - assertEq(e.message, "`Headers.prototype[Symbol.iterator]` requires a `Headers` object"); + assertEq(e.message, "cannot downcast a value of type `number` to an object with internal slot `JsHeaders`"); } "#, ), diff --git a/core/runtime/src/url.rs b/core/runtime/src/url.rs index f39de1bd2c8..1eaa36fb357 100644 --- a/core/runtime/src/url.rs +++ b/core/runtime/src/url.rs @@ -310,8 +310,7 @@ impl UrlSearchParams { }, context, )? - .downcast::() - .map_err(|_| js_error!(Error: "URLSearchParams class should be registered")) + .require_internal_slot::() } fn pairs(&self) -> Vec<(JsString, JsString)> { diff --git a/tests/macros/tests/derive/both.rs b/tests/macros/tests/derive/both.rs index bf270efa636..2672f7f4418 100644 --- a/tests/macros/tests/derive/both.rs +++ b/tests/macros/tests/derive/both.rs @@ -1,8 +1,8 @@ #![allow(unused)] use boa_engine::{ - value::{TryFromJs, TryIntoJs}, Context, JsResult, JsValue, + value::{TryFromJs, TryIntoJs}, }; #[derive(TryFromJs, TryIntoJs)] diff --git a/tests/wpt/src/lib.rs b/tests/wpt/src/lib.rs index 653beb45235..a504c038dc5 100644 --- a/tests/wpt/src/lib.rs +++ b/tests/wpt/src/lib.rs @@ -280,7 +280,9 @@ fn execute_test_file(path: &Path) { // Workspace `reqwest` uses `rustls-no-provider`; install ring as the // process-wide CryptoProvider so `BlockingReqwestFetcher` construction // in `create_context` doesn't panic with `No provider set`. - rustls::crypto::ring::default_provider().install_default().ok(); + rustls::crypto::ring::default_provider() + .install_default() + .ok(); let dir = path.parent().unwrap(); let wpt_path = PathBuf::from( std::env::var("WPT_ROOT").expect("Could not find the WPT_ROOT environment variable"),