Truly independent web browser
LibJS: Downcast cell references through one checked helper
Andreas Kling995d0fbb5d8e
diff --git a/Libraries/LibJS/Rust/src/contrib/test262/262_object.rs b/Libraries/LibJS/Rust/src/contrib/test262/262_object.rsindex 76fb75d5829..19649701ae7 100644--- a/Libraries/LibJS/Rust/src/contrib/test262/262_object.rs+++ b/Libraries/LibJS/Rust/src/contrib/test262/262_object.rs@@ -12,7 +12,7 @@ use libjs_runtime_macros::Trace;use crate::contrib::test262::agent_object::AgentObject;use crate::contrib::test262::global_object::Test262GlobalObject;use crate::contrib::test262::is_htmldda::IsHTMLDDA;-use crate::gc::class::{GcCell, define_cell};+use crate::gc::class::{GcCell, cast_ref, define_cell};use crate::interpreter::vm::Vm;use crate::layout::cell::Gc;use crate::layout::object::Object;@@ -60,8 +60,7 @@ impl Dollar262Object {}fn initialize(object: &Object, vm: &Vm, realm: Gc<Realm>) {- // SAFETY: Only Dollar262Object has these methods.- let this = unsafe { &*core::ptr::from_ref(object).cast::<Dollar262Object>() };+ let this: &Dollar262Object = cast_ref(object);let agent = AgentObject::create(vm, realm);this.agent.set(Some(agent));diff --git a/Libraries/LibJS/Rust/src/contrib/test262/global_object.rs b/Libraries/LibJS/Rust/src/contrib/test262/global_object.rsindex afdd4313ca3..ebc8080f208 100644--- a/Libraries/LibJS/Rust/src/contrib/test262/global_object.rs+++ b/Libraries/LibJS/Rust/src/contrib/test262/global_object.rs@@ -10,7 +10,7 @@ use ak::Utf16FlyString;use libjs_runtime_macros::Trace;use crate::contrib::test262::dollar_262_object::Dollar262Object;-use crate::gc::class::{GcCell, define_cell};+use crate::gc::class::{GcCell, cast_ref, define_cell};use crate::interpreter::vm::Vm;use crate::layout::cell::Gc;use crate::layout::object::Object;@@ -58,8 +58,7 @@ impl Test262GlobalObject {.initialize;base_initialize(object, vm, realm);- // SAFETY: Only Test262GlobalObject has these methods.- let this = unsafe { &*core::ptr::from_ref(object).cast::<Test262GlobalObject>() };+ let this: &Test262GlobalObject = cast_ref(object);let dollar_262 = Dollar262Object::create(vm, realm);this.dollar_262.set(Some(dollar_262));diff --git a/Libraries/LibJS/Rust/src/embedding/host/console_client.rs b/Libraries/LibJS/Rust/src/embedding/host/console_client.rsindex ce1b45cb48f..af77f64e766 100644--- a/Libraries/LibJS/Rust/src/embedding/host/console_client.rs+++ b/Libraries/LibJS/Rust/src/embedding/host/console_client.rs@@ -20,7 +20,7 @@ use crate::embedding::abi_types::{error_data_into_abi, owned_utf16_string_into_abi, vm_from_abi, vm_into_abi,};use crate::embedding::console::{JSConsole, log_level_into_abi};-use crate::gc::class::{GcCell, class_of, define_cell};+use crate::gc::class::{GcCell, cast_ref, class_of, define_cell};use crate::gc::foreign::ForeignCellSlot;use crate::gc::root::MarkedVec;use crate::interpreter::vm::Vm;@@ -140,8 +140,7 @@ fn trace_frames_into_abi(trace: &ConsoleTrace) -> Vec<JSConsoleTraceFrame> {impl HostConsoleClient {fn of(client: &ConsoleClient) -> &HostConsoleClient {- // SAFETY: Only HostConsoleClient has these methods.- unsafe { &*core::ptr::from_ref(client).cast::<HostConsoleClient>() }+ cast_ref(client)}fn printer<'vm>(diff --git a/Libraries/LibJS/Rust/src/embedding/host/host_array.rs b/Libraries/LibJS/Rust/src/embedding/host/host_array.rsindex e192db2b0be..fa5721967d4 100644--- a/Libraries/LibJS/Rust/src/embedding/host/host_array.rs+++ b/Libraries/LibJS/Rust/src/embedding/host/host_array.rs@@ -31,7 +31,7 @@ use crate::embedding::host::class_table::{};use crate::embedding::host::registry::runtime_class_and_allocator_of_host_class;use crate::embedding::object::{lookup_phase_from_abi, set_cache_metadata_from_abi};-use crate::gc::class::{Class, define_cell};+use crate::gc::class::{Class, cast_ref, define_cell};use crate::gc::foreign::ForeignCellSlot;use crate::interpreter::vm::Vm;use crate::layout::cell::Gc;@@ -94,9 +94,7 @@ pub fn derive_host_array_class(table: &'static JSHostClass, parent: &'static Cla/// The host array an internal method of a host array class was called on.pub(crate) fn as_host_array(object: &Object) -> &HostArray {- debug_assert!(object.is::<HostArray>());- // SAFETY: The object is a HostArray, which starts with its Object.- unsafe { &*core::ptr::from_ref(object).cast::<HostArray>() }+ cast_ref(object)}fn hooks_of(object: &Object) -> &'static JSHostArrayHooks {diff --git a/Libraries/LibJS/Rust/src/embedding/host/host_function.rs b/Libraries/LibJS/Rust/src/embedding/host/host_function.rsindex 9bba56277ad..7a79c0e22da 100644--- a/Libraries/LibJS/Rust/src/embedding/host/host_function.rs+++ b/Libraries/LibJS/Rust/src/embedding/host/host_function.rs@@ -29,7 +29,7 @@ use crate::embedding::host::class_table::{copy_host_class_flags_into_object, host_class_from_abi, lend_object_to_hook, object_completion_from_hook,};use crate::embedding::host::registry::runtime_class_and_allocator_of_host_class;-use crate::gc::class::{Class, Finalize, define_cell};+use crate::gc::class::{Class, Finalize, cast_ref, define_cell};use crate::gc::foreign::ForeignCellSlot;use crate::interpreter::vm::Vm;use crate::layout::cell::Gc;@@ -102,9 +102,7 @@ pub fn derive_host_function_class(table: &'static JSHostClass, parent: &'static/// The host function an internal method of a host function class was called on.pub(crate) fn as_host_function(object: &Object) -> &HostFunction {- debug_assert!(object.is::<HostFunction>());- // SAFETY: The object is a HostFunction, which starts with its Object.- unsafe { &*core::ptr::from_ref(object).cast::<HostFunction>() }+ cast_ref(object)}fn host_function_has_constructor(object: &Object) -> bool {diff --git a/Libraries/LibJS/Rust/src/embedding/host/host_object.rs b/Libraries/LibJS/Rust/src/embedding/host/host_object.rsindex 35e893f4dd3..8431b8875fe 100644--- a/Libraries/LibJS/Rust/src/embedding/host/host_object.rs+++ b/Libraries/LibJS/Rust/src/embedding/host/host_object.rs@@ -33,7 +33,7 @@ use crate::embedding::host::host_array::as_host_array;use crate::embedding::host::host_function::as_host_function;use crate::embedding::host::registry::runtime_class_and_allocator_of_host_class;use crate::embedding::object::{property_descriptor_from_abi, property_descriptor_to_abi};-use crate::gc::class::{Class, Finalize, define_cell};+use crate::gc::class::{Class, Finalize, cast_ref, define_cell};use crate::gc::class_id::ClassId;use crate::gc::foreign::ForeignCellSlot;use crate::gc::root::MarkedVec;@@ -425,9 +425,7 @@ impl HostObject {/// The host object an internal method of a host object class was called on.pub(crate) fn as_host_object(object: &Object) -> &HostObject {- debug_assert!(object.is::<HostObject>());- // SAFETY: The object is a HostObject, which starts with its Object.- unsafe { &*core::ptr::from_ref(object).cast::<HostObject>() }+ cast_ref(object)}/// host_class_of(): the host class of an object of any host kind, or none for any other object.diff --git a/Libraries/LibJS/Rust/src/gc/class.rs b/Libraries/LibJS/Rust/src/gc/class.rsindex c953fc6a7c3..ce1213edcf9 100644--- a/Libraries/LibJS/Rust/src/gc/class.rs+++ b/Libraries/LibJS/Rust/src/gc/class.rs@@ -218,6 +218,13 @@ impl Class {self.parent.is_some_and(|parent| parent.id == self.id)}+ /// Whether the class is that of the cell type `T` or a subclass of it. Classes derived at run time have the id of+ /// the class they extend, and every cell type has an id of its own, so a class with the id of `T` is the class of+ /// `T` or one derived from it at run time. That covers the long chains of host classes without walking them.+ pub fn is_class_of<T: GcCell>(&self) -> bool {+ self.id == T::CLASS.id || self.is_subclass_of(T::CLASS)+ }+pub fn is_subclass_of(&self, ancestor: &Class) -> bool {let mut class = Some(self);while let Some(current) = class {@@ -262,12 +269,33 @@ pub unsafe trait Extends<Base> {}// SAFETY: Every type starts with itself.unsafe impl<T: GcCell> Extends<T> for T {}+// SAFETY: Every cell starts with its header.+unsafe impl<T: GcCell> Extends<CellHeader> for T {}+/// The class a cell was allocated with, which may be a subclass of its static type.pub fn class_of<T>(cell: crate::layout::cell::Gc<T>) -> &'static Class {// SAFETY: Every cell starts with its class.unsafe { cell.as_ptr().cast::<&'static Class>().read() }}+/// The cell as a `Derived`, if it was allocated as one or as a subclass of it.+///+/// NB: A cell carries the class it is constructed with from the start, and is only ever constructed as part of a+/// value of that class, so its class tells what the memory around it is.+pub fn downcast_ref<Base: GcCell, Derived: GcCell + Extends<Base>>(cell: &Base) -> Option<&Derived> {+ // SAFETY: Every cell starts with its class.+ let class = unsafe { core::ptr::from_ref(cell).cast::<&'static Class>().read() };+ class+ .is_class_of::<Derived>()+ // SAFETY: The cell is a Derived or a subclass of it, which starts with a Derived.+ .then(|| unsafe { &*core::ptr::from_ref(cell).cast::<Derived>() })+}++/// The cell as a `Derived`, which it has to have been allocated as, or as a subclass of.+pub fn cast_ref<Base: GcCell, Derived: GcCell + Extends<Base>>(cell: &Base) -> &Derived {+ downcast_ref(cell).unwrap_or_else(|| panic!("cell is not a {}", Derived::CLASS.name))+}+impl<T: ?Sized> core::fmt::Debug for crate::layout::cell::Gc<T> {fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {write!(formatter, "Gc({:p})", self.as_non_null())@@ -307,7 +335,7 @@ impl<T> crate::layout::cell::Gc<T> {pub fn downcast<Derived: GcCell + Extends<T>>(self) -> Option<crate::layout::cell::Gc<Derived>> {class_of(self)- .is_subclass_of(Derived::CLASS)+ .is_class_of::<Derived>()// SAFETY: The cell was allocated as a Derived or a subclass of it..then(|| unsafe { crate::layout::cell::Gc::from_non_null(self.as_non_null().cast()) })}diff --git a/Libraries/LibJS/Rust/src/jit/feedback_dump.rs b/Libraries/LibJS/Rust/src/jit/feedback_dump.rsindex ee54cd1c626..ab74060e893 100644--- a/Libraries/LibJS/Rust/src/jit/feedback_dump.rs+++ b/Libraries/LibJS/Rust/src/jit/feedback_dump.rs@@ -17,7 +17,7 @@ use crate::bytecode::feedback::{use crate::bytecode::instruction::{instruction_feedback_slots_from_bytes, instruction_length_from_bytes, instruction_name_from_opcode,};-use crate::gc::class::{GcCell, class_of};+use crate::gc::class::class_of;use crate::layout::cell::{CellHeader, Gc};use crate::layout::function_object::NativeFunction;use crate::layout::object::Object;@@ -41,14 +41,6 @@ const TYPED_ARRAY_KINDS: [TypedArrayKind; 12] = [TypedArrayKind::Float64Array,];-/// The cell as a `T`, if it is one.-fn cell_as<T: GcCell>(cell: Gc<CellHeader>) -> Option<Gc<T>> {- class_of(cell)- .is_subclass_of(T::CLASS)- // SAFETY: The cell was allocated as a T or a subclass of it.- .then(|| unsafe { Gc::from_non_null(cell.as_non_null().cast()) })-}-fn append_bits<T: Copy + Into<u32>>(out: &mut String, bits: T, names: &[(T, &str)]) {let bits: u32 = bits.into();if bits == 0 {@@ -74,11 +66,11 @@ fn append_cell(out: &mut String, cell: Option<Gc<CellHeader>>) {out.push_str("none");return;};- if let Some(string) = cell_as::<PrimitiveString>(cell) {+ if let Some(string) = cell.downcast::<PrimitiveString>() {let _ = write!(out, "\"{}\"", string.to_utf8());- } else if let Some(symbol) = cell_as::<Symbol>(cell) {+ } else if let Some(symbol) = cell.downcast::<Symbol>() {out.push_str(&Utf16View::of_string(&symbol.descriptive_string()).to_utf8());- } else if let Some(native_function) = cell_as::<NativeFunction>(cell) {+ } else if let Some(native_function) = cell.downcast::<NativeFunction>() {let name = native_function.name();let name = match native_function.initial_name() {Some(initial_name) if name.is_empty() => initial_name,@@ -90,7 +82,7 @@ fn append_cell(out: &mut String, cell: Option<Gc<CellHeader>>) {} else {let _ = write!(out, "native function {name}");}- } else if let Some(object) = cell_as::<Object>(cell)+ } else if let Some(object) = cell.downcast::<Object>()&& object.is_function(){let name = Utf16View::of_string(&object.name_for_call_stack()).to_utf8();diff --git a/Libraries/LibJS/Rust/src/jit/mod.rs b/Libraries/LibJS/Rust/src/jit/mod.rsindex 71c94a66b74..277592d5a3d 100644--- a/Libraries/LibJS/Rust/src/jit/mod.rs+++ b/Libraries/LibJS/Rust/src/jit/mod.rs@@ -55,14 +55,6 @@ fn frame_of<'a>(frame: NonNull<ExecutionContext>) -> &'a ExecutionContext {unsafe { frame.as_ref() }}-/// The cell as a `T`, if it is one.-fn cell_as<T: crate::gc::class::GcCell>(cell: Gc<CellHeader>) -> Option<Gc<T>> {- crate::gc::class::class_of(cell)- .is_subclass_of(T::CLASS)- // SAFETY: The cell was allocated as a T or a subclass of it.- .then(|| unsafe { Gc::from_non_null(cell.as_non_null().cast()) })-}-/// A field offset as JIT code takes it.fn offset(offset: usize) -> u32 {u32::try_from(offset).expect("field offsets fit in u32")diff --git a/Libraries/LibJS/Rust/src/jit/snapshot.rs b/Libraries/LibJS/Rust/src/jit/snapshot.rsindex 6b9b235b1eb..9670d8a8b26 100644--- a/Libraries/LibJS/Rust/src/jit/snapshot.rs+++ b/Libraries/LibJS/Rust/src/jit/snapshot.rs@@ -27,7 +27,6 @@ use super::allocation::{allocation_infos, closure_template_snapshots, closure_templates, function_environment_template,lexical_environment_templates,};-use super::cell_as;use super::code::{CapturedBindingAccesses, InlinedFunction, SnapshotExecutable};use super::runtime_info::RAW_NATIVE_FUNCTIONS_RETURN_IN_REGISTERS;use crate::bytecode::executable::{Executable, PropertyLookupCacheEntryData, PropertyLookupCacheTier};@@ -121,7 +120,7 @@ fn instruction_count(executable: &Executable, limit: u32) -> u32 {}pub(crate) fn ecmascript_function(cell: Option<Gc<CellHeader>>) -> Option<Gc<EcmascriptFunctionObject>> {- as_ecmascript_function_object(cell_as::<Object>(cell?)?)+ as_ecmascript_function_object(cell?.downcast::<Object>()?)}/// The target of a call site if it is a builtin written in JavaScript that JIT code can inline: a normal function@@ -130,7 +129,7 @@ fn builtin_inlining_candidate(target: Option<Gc<CellHeader>>,caller_realm: Gc<Realm>,) -> Option<Gc<NativeJavaScriptBackedFunction>> {- let builtin = cell_as::<NativeJavaScriptBackedFunction>(target?)?;+ let builtin = target?.downcast::<NativeJavaScriptBackedFunction>()?;let shared_data = builtin.shared_data();(shared_data.kind() == FunctionKind::Normal&& !builtin.function_environment_needed()@@ -142,19 +141,19 @@ fn builtin_inlining_candidate(/// The intrinsic the compiler knows an object as, if it is one.fn intrinsic_of(vm: &Vm, cell: Option<Gc<CellHeader>>) -> Option<Intrinsic> {let cell = cell?;- if cell_as::<StringConstructor>(cell).is_some() {+ if cell.downcast::<StringConstructor>().is_some() {return Some(Intrinsic::StringConstructor);}- if cell_as::<ArrayConstructor>(cell).is_some() {+ if cell.downcast::<ArrayConstructor>().is_some() {return Some(Intrinsic::ArrayConstructor);}- if cell_as::<ObjectConstructor>(cell).is_some() {+ if cell.downcast::<ObjectConstructor>().is_some() {return Some(Intrinsic::ObjectConstructor);}- if cell_as::<BooleanConstructor>(cell).is_some() {+ if cell.downcast::<BooleanConstructor>().is_some() {return Some(Intrinsic::BooleanConstructor);}- let function = cell_as::<RawNativeFunction>(cell)?;+ let function = cell.downcast::<RawNativeFunction>()?;match function.builtin() {Some(Builtin::StringFromCharCode) => return Some(Intrinsic::StringFromCharCode),Some(Builtin::RegExpPrototypeExec) => return Some(Intrinsic::RegExpPrototypeExec),@@ -312,7 +311,7 @@ fn native_call_target(vm: &Vm, feedback: &CallFeedback) -> Option<Gc<RawNativeFuif !RAW_NATIVE_FUNCTIONS_RETURN_IN_REGISTERS || feedback.flags.get() & call_feedback_flags::POLYMORPHIC != 0 {return None;}- let function = cell_as::<RawNativeFunction>(feedback.target()?)?;+ let function = feedback.target()?.downcast::<RawNativeFunction>()?;(!FunctionPrototype::is_call_function(vm, &function) && !FunctionPrototype::is_apply_function(vm, &function)).then_some(function)}@@ -691,7 +690,7 @@ impl SnapshotBuilder<'_> {bound_argument_count: 0,};if snapshot.forwarding == Forwarding::Bound {- let bound = cell_as::<BoundFunction>(call.target()?)?;+ let bound = call.target()?.downcast::<BoundFunction>()?;let bound_argument_count = bound.bound_arguments_count();if bound_argument_count > snapshot.bound_arguments.len() {return None;diff --git a/Libraries/LibJS/Rust/src/runtime/arguments_object.rs b/Libraries/LibJS/Rust/src/runtime/arguments_object.rsindex 9b646251fec..80d441c65c9 100644--- a/Libraries/LibJS/Rust/src/runtime/arguments_object.rs+++ b/Libraries/LibJS/Rust/src/runtime/arguments_object.rs@@ -11,7 +11,7 @@ use std::rc::Rc;use ak::Utf16FlyString;use libjs_runtime_macros::Trace;-use crate::gc::class::{GcCell, define_cell};+use crate::gc::class::{GcCell, cast_ref, define_cell};use crate::interpreter::vm::Vm;use crate::layout::cell::Gc;use crate::layout::environment::Environment;@@ -72,9 +72,7 @@ impl Deref for ArgumentsObject {/// The arguments object an internal method of an arguments object was called on.fn as_arguments_object(object: &Object) -> &ArgumentsObject {- assert!(object.is::<ArgumentsObject>());- // SAFETY: The object is an ArgumentsObject, which starts with its Object.- unsafe { &*core::ptr::from_ref(object).cast::<ArgumentsObject>() }+ cast_ref(object)}// NB: The inline named storage ends the object, so the extra slot continues it.diff --git a/Libraries/LibJS/Rust/src/runtime/array.rs b/Libraries/LibJS/Rust/src/runtime/array.rsindex 7f87edcdae9..0439306c1b9 100644--- a/Libraries/LibJS/Rust/src/runtime/array.rs+++ b/Libraries/LibJS/Rust/src/runtime/array.rs@@ -8,7 +8,7 @@ use core::cell::Cell;use libjs_runtime_macros::Trace;-use crate::gc::class::{Class, GcCell, define_cell};+use crate::gc::class::{Class, GcCell, cast_ref, define_cell};use crate::gc::root::MarkedVec;use crate::interpreter::vm::Vm;use crate::layout::cell::Gc;@@ -75,9 +75,7 @@ impl Object {/// The array an Array internal method was called on.fn as_array(object: &Object) -> &Array {- assert!(object.is_array_exotic_object());- // SAFETY: The object is an Array, which starts with its Object.- unsafe { &*core::ptr::from_ref(object).cast::<Array>() }+ cast_ref(object)}impl Array {diff --git a/Libraries/LibJS/Rust/src/runtime/bound_function.rs b/Libraries/LibJS/Rust/src/runtime/bound_function.rsindex 16a5a41e7f1..bda74eb77ae 100644--- a/Libraries/LibJS/Rust/src/runtime/bound_function.rs+++ b/Libraries/LibJS/Rust/src/runtime/bound_function.rs@@ -10,7 +10,7 @@ use core::ops::Deref;use ak::Utf16String;use libjs_runtime_macros::Trace;-use crate::gc::class::{GcCell, define_cell};+use crate::gc::class::{GcCell, cast_ref, define_cell};use crate::interpreter::vm::Vm;use crate::layout::cell::Gc;use crate::layout::execution_context::ExecutionContext;@@ -52,9 +52,7 @@ impl Deref for BoundFunction {/// The bound function an internal method of a bound function was called on.fn as_bound_function(object: &Object) -> &BoundFunction {- assert!(object.is_bound_function());- // SAFETY: The object is a BoundFunction, which starts with its Object.- unsafe { &*core::ptr::from_ref(object).cast::<BoundFunction>() }+ cast_ref(object)}impl Object {diff --git a/Libraries/LibJS/Rust/src/runtime/console_object.rs b/Libraries/LibJS/Rust/src/runtime/console_object.rsindex 7037e1108ed..927a26b300e 100644--- a/Libraries/LibJS/Rust/src/runtime/console_object.rs+++ b/Libraries/LibJS/Rust/src/runtime/console_object.rs@@ -10,7 +10,7 @@ use ak::Utf16FlyString;use libjs_runtime_macros::Trace;use crate::console::Console;-use crate::gc::class::{GcCell, define_cell};+use crate::gc::class::{GcCell, cast_ref, define_cell};use crate::interpreter::vm::Vm;use crate::layout::cell::Gc;use crate::layout::object::Object;@@ -68,8 +68,7 @@ impl ConsoleObject {}fn initialize(object: &Object, vm: &Vm, realm: Gc<Realm>) {- // SAFETY: Only ConsoleObject has these methods.- let this = unsafe { &*core::ptr::from_ref(object).cast::<ConsoleObject>() };+ let this: &ConsoleObject = cast_ref(object);let names = &vm.names;this.console.set(Some(Console::create(vm, realm)));let attr = PropertyAttributes::new(Attribute::WRITABLE | Attribute::ENUMERABLE | Attribute::CONFIGURABLE);diff --git a/Libraries/LibJS/Rust/src/runtime/ecmascript_function_object.rs b/Libraries/LibJS/Rust/src/runtime/ecmascript_function_object.rsindex 35cd6e6f180..61b319f0543 100644--- a/Libraries/LibJS/Rust/src/runtime/ecmascript_function_object.rs+++ b/Libraries/LibJS/Rust/src/runtime/ecmascript_function_object.rs@@ -13,7 +13,7 @@ use ak::{Utf16FlyString, Utf16String};use libjs_runtime_macros::Trace;use crate::bytecode::executable::Executable;-use crate::gc::class::{Extends, GcCell, define_cell};+use crate::gc::class::{Extends, GcCell, cast_ref, define_cell};use crate::gc::gc_ref_cell::GcRefCell;use crate::gc::root::MarkedVec;use crate::gc::visitor::{Trace, Visitor};@@ -121,9 +121,7 @@ impl Deref for EcmascriptFunctionObject {/// The function an internal method of an ECMAScript function object was called on.fn as_ecmascript_function(object: &Object) -> &EcmascriptFunctionObject {- assert!(object.is_ecmascript_function_object());- // SAFETY: Only ECMAScript function objects have the flag, and they start with their Object.- unsafe { &*core::ptr::from_ref(object).cast::<EcmascriptFunctionObject>() }+ cast_ref(object)}/// The object as an ECMAScript function object, if its flag says that it is one.diff --git a/Libraries/LibJS/Rust/src/runtime/environment.rs b/Libraries/LibJS/Rust/src/runtime/environment.rsindex a9b22be54ec..a9bdcdbce80 100644--- a/Libraries/LibJS/Rust/src/runtime/environment.rs+++ b/Libraries/LibJS/Rust/src/runtime/environment.rs@@ -148,18 +148,12 @@ impl Environment {/// The environment as a `T`, if it was allocated as one.pub fn downcast_ref<T: GcCell + Extends<Environment>>(&self) -> Option<&T> {- self.class()- .is_subclass_of(T::CLASS)- // SAFETY: The environment was allocated as a T or a subclass of it, which starts with a T.- .then(|| unsafe { &*core::ptr::from_ref(self).cast::<T>() })+ crate::gc::class::downcast_ref(self)}- /// The environment as a DeclarativeEnvironment, if its declarative flag is set.+ /// The environment as a DeclarativeEnvironment, if it is one.pub fn as_declarative_environment(&self) -> Option<&DeclarativeEnvironment> {- self.is_declarative_environment()- // SAFETY: Only DeclarativeEnvironment and the classes extending it are declarative, and they start with- // a DeclarativeEnvironment.- .then(|| unsafe { &*core::ptr::from_ref(self).cast::<DeclarativeEnvironment>() })+ self.downcast_ref()}pub fn has_this_binding(&self) -> bool {diff --git a/Libraries/LibJS/Rust/src/runtime/error.rs b/Libraries/LibJS/Rust/src/runtime/error.rsindex 81b81e4f922..e2aa4272fa8 100644--- a/Libraries/LibJS/Rust/src/runtime/error.rs+++ b/Libraries/LibJS/Rust/src/runtime/error.rs@@ -11,7 +11,7 @@ use libjs_runtime_macros::Trace;use super::completion::{Throw, ThrowCompletionOr};use super::error_types::ErrorType;-use crate::gc::class::{Class, ExternalMemorySize, GcCell, define_cell};+use crate::gc::class::{Class, ExternalMemorySize, GcCell, define_cell, downcast_ref};use crate::interpreter::vm::Vm;use crate::layout::cell::Gc;use crate::layout::object::Object;@@ -142,12 +142,7 @@ impl Deref for Error {/// The error_data method of ordinary objects, which finds the slot of the Error objects among them.pub fn error_data_of_error(object: &Object) -> Option<&ErrorData> {- if !object.is::<Error>() {- return None;- }- // SAFETY: The object is an Error, which starts with its Object.- let error = unsafe { &*core::ptr::from_ref(object).cast::<Error>() };- Some(&error.error_data)+ downcast_ref::<_, Error>(object).map(|error| &error.error_data)}impl Error {diff --git a/Libraries/LibJS/Rust/src/runtime/function_object.rs b/Libraries/LibJS/Rust/src/runtime/function_object.rsindex a7230fd3f0c..715ea79096e 100644--- a/Libraries/LibJS/Rust/src/runtime/function_object.rs+++ b/Libraries/LibJS/Rust/src/runtime/function_object.rs@@ -10,7 +10,7 @@ use core::ops::Deref;use ak::Utf16String;use libjs_abi::Builtin;-use crate::gc::class::{Class, define_cell};+use crate::gc::class::{Class, define_cell, downcast_ref};use crate::gc::visitor::{Trace, Visitor};use crate::interpreter::vm::Vm;use crate::layout::cell::Gc;@@ -236,8 +236,6 @@ impl FunctionObject {/// The function as a NativeFunction, if it is one.pub fn as_native_function(&self) -> Option<&NativeFunction> {- // SAFETY: A NativeFunction starts with its FunctionObject.- self.is::<NativeFunction>()- .then(|| unsafe { &*core::ptr::from_ref(self).cast::<NativeFunction>() })+ downcast_ref(self)}}diff --git a/Libraries/LibJS/Rust/src/runtime/intl/collator_compare_function.rs b/Libraries/LibJS/Rust/src/runtime/intl/collator_compare_function.rsindex bf8da77e9fb..cbfd0173305 100644--- a/Libraries/LibJS/Rust/src/runtime/intl/collator_compare_function.rs+++ b/Libraries/LibJS/Rust/src/runtime/intl/collator_compare_function.rs@@ -9,7 +9,7 @@ use core::ops::Deref;use libjs_runtime_macros::Trace;-use crate::gc::class::{GcCell, define_cell};+use crate::gc::class::{GcCell, cast_ref, define_cell};use crate::interpreter::vm::Vm;use crate::layout::cell::Gc;use crate::layout::object::Object;@@ -88,9 +88,7 @@ impl CollatorCompareFunction {// 10.3.3.1 Collator Compare Functions, https://tc39.es/ecma402/#sec-collator-compare-functionsfn call(function: &NativeFunction, vm: &Vm) -> ThrowCompletionOr<Value> {- assert!(function.is::<CollatorCompareFunction>());- // SAFETY: The function is a CollatorCompareFunction, which starts with its NativeFunction.- let function = unsafe { &*core::ptr::from_ref(function).cast::<CollatorCompareFunction>() };+ let function: &CollatorCompareFunction = cast_ref(function);// 1. Let collator be F.[[Collator]].// 2. Assert: Type(collator) is Object and collator has an [[InitializedCollator]] internal slot.diff --git a/Libraries/LibJS/Rust/src/runtime/intl/date_time_format_function.rs b/Libraries/LibJS/Rust/src/runtime/intl/date_time_format_function.rsindex 6972327cbb7..425a12175b8 100644--- a/Libraries/LibJS/Rust/src/runtime/intl/date_time_format_function.rs+++ b/Libraries/LibJS/Rust/src/runtime/intl/date_time_format_function.rs@@ -9,7 +9,7 @@ use core::ops::Deref;use libjs_runtime_macros::Trace;-use crate::gc::class::{GcCell, define_cell};+use crate::gc::class::{GcCell, cast_ref, define_cell};use crate::interpreter::vm::Vm;use crate::layout::cell::Gc;use crate::layout::object::Object;@@ -91,9 +91,7 @@ impl DateTimeFormatFunction {}fn call(function: &NativeFunction, vm: &Vm) -> ThrowCompletionOr<Value> {- assert!(function.is::<DateTimeFormatFunction>());- // SAFETY: The function is a DateTimeFormatFunction, which starts with its NativeFunction.- let function = unsafe { &*core::ptr::from_ref(function).cast::<DateTimeFormatFunction>() };+ let function: &DateTimeFormatFunction = cast_ref(function);let realm = vm.current_realm().expect("a built-in function runs in a realm");let date_value = vm.argument(0);diff --git a/Libraries/LibJS/Rust/src/runtime/intl/number_format_function.rs b/Libraries/LibJS/Rust/src/runtime/intl/number_format_function.rsindex 623f4ef4ddf..bd7e62c22f2 100644--- a/Libraries/LibJS/Rust/src/runtime/intl/number_format_function.rs+++ b/Libraries/LibJS/Rust/src/runtime/intl/number_format_function.rs@@ -9,7 +9,7 @@ use core::ops::Deref;use libjs_runtime_macros::Trace;-use crate::gc::class::{GcCell, define_cell};+use crate::gc::class::{GcCell, cast_ref, define_cell};use crate::interpreter::vm::Vm;use crate::layout::cell::Gc;use crate::layout::object::Object;@@ -87,9 +87,7 @@ impl NumberFormatFunction {}fn call(function: &NativeFunction, vm: &Vm) -> ThrowCompletionOr<Value> {- assert!(function.is::<NumberFormatFunction>());- // SAFETY: The function is a NumberFormatFunction, which starts with its NativeFunction.- let function = unsafe { &*core::ptr::from_ref(function).cast::<NumberFormatFunction>() };+ let function: &NumberFormatFunction = cast_ref(function);// 1. Let nf be F.[[NumberFormat]].// 2. Assert: Type(nf) is Object and nf has an [[InitializedNumberFormat]] internal slot.diff --git a/Libraries/LibJS/Rust/src/runtime/iterator_helper.rs b/Libraries/LibJS/Rust/src/runtime/iterator_helper.rsindex e8b14502c36..8ad271b05b2 100644--- a/Libraries/LibJS/Rust/src/runtime/iterator_helper.rs+++ b/Libraries/LibJS/Rust/src/runtime/iterator_helper.rs@@ -9,7 +9,7 @@ use core::ops::Deref;use libjs_runtime_macros::Trace;-use crate::gc::class::{Finalize, GcCell, define_cell};+use crate::gc::class::{Finalize, GcCell, cast_ref, define_cell};use crate::gc::gc_ref_cell::GcRefCell;use crate::gc::root::MarkedVec;use crate::interpreter::vm::Vm;@@ -179,9 +179,7 @@ impl IteratorHelper {}fn execute(generator: &GeneratorObject, vm: &Vm, completion: Completion) -> ThrowCompletionOr<IterationResult> {- assert!(generator.is::<IteratorHelper>());- // SAFETY: Only iterator helpers execute through this, and an IteratorHelper starts with its GeneratorObject.- let iterator = unsafe { &*core::ptr::from_ref(generator).cast::<IteratorHelper>() };+ let iterator: &IteratorHelper = cast_ref(generator);let result = iterator.execute_closure(vm, completion);vm.pop_execution_context();resultdiff --git a/Libraries/LibJS/Rust/src/runtime/module.rs b/Libraries/LibJS/Rust/src/runtime/module.rsindex 34627cd8ebb..129f85e8eda 100644--- a/Libraries/LibJS/Rust/src/runtime/module.rs+++ b/Libraries/LibJS/Rust/src/runtime/module.rs@@ -259,10 +259,7 @@ impl Module {/// The module as a `T`, if it was allocated as one.pub fn downcast_ref<T: GcCell + crate::gc::class::Extends<Module>>(&self) -> Option<&T> {- self.class()- .is_subclass_of(T::CLASS)- // SAFETY: The module was allocated as a T or a subclass of it, which starts with a Module.- .then(|| unsafe { &*core::ptr::from_ref(self).cast::<T>() })+ crate::gc::class::downcast_ref(self)}pub fn as_cyclic_module(&self) -> Option<&CyclicModule> {diff --git a/Libraries/LibJS/Rust/src/runtime/module_namespace_object.rs b/Libraries/LibJS/Rust/src/runtime/module_namespace_object.rsindex 04abb0d4a06..c6f88e071fa 100644--- a/Libraries/LibJS/Rust/src/runtime/module_namespace_object.rs+++ b/Libraries/LibJS/Rust/src/runtime/module_namespace_object.rs@@ -7,7 +7,7 @@use ak::Utf16FlyString;use libjs_runtime_macros::Trace;-use crate::gc::class::{GcCell, define_cell};+use crate::gc::class::{GcCell, cast_ref, define_cell};use crate::gc::root::MarkedVec;use crate::interpreter::vm::Vm;use crate::layout::cell::Gc;@@ -68,9 +68,7 @@ impl core::ops::Deref for ModuleNamespaceObject {/// The module namespace object an internal method of a module namespace object was called on.fn as_module_namespace_object(object: &Object) -> &ModuleNamespaceObject {- assert!(object.is::<ModuleNamespaceObject>());- // SAFETY: The object is a ModuleNamespaceObject, which starts with its Object.- unsafe { &*core::ptr::from_ref(object).cast::<ModuleNamespaceObject>() }+ cast_ref(object)}/// The String a property key that is not a Symbol stands for, which [[Exports]] holds export names as.diff --git a/Libraries/LibJS/Rust/src/runtime/native_function.rs b/Libraries/LibJS/Rust/src/runtime/native_function.rsindex ec8726bb538..1cd96bdfeb1 100644--- a/Libraries/LibJS/Rust/src/runtime/native_function.rs+++ b/Libraries/LibJS/Rust/src/runtime/native_function.rs@@ -12,7 +12,7 @@ use ak::{Utf16FlyString, Utf16String};use libjs_abi::Builtin;use libjs_runtime_macros::Trace;-use crate::gc::class::{Class, GcCell, define_cell};+use crate::gc::class::{Class, GcCell, cast_ref, define_cell};use crate::gc::visitor::{Trace, Visitor};use crate::interpreter::vm::Vm;use crate::layout::cell::Gc;@@ -89,9 +89,7 @@ fn as_native_javascript_backed_function(function: &NativeFunction) -> Gc<NativeJ/// The native function an internal method of a native function was called on.fn as_native_function(object: &Object) -> &NativeFunction {- assert!(object.is::<NativeFunction>());- // SAFETY: The object is a NativeFunction, which starts with its Object.- unsafe { &*core::ptr::from_ref(object).cast::<NativeFunction>() }+ cast_ref(object)}impl NativeFunction {@@ -538,8 +536,7 @@ impl CapturingNativeFunction {}fn call(function: &NativeFunction, vm: &Vm) -> ThrowCompletionOr<Value> {- // SAFETY: Only CapturingNativeFunction has these methods.- let function = unsafe { &*core::ptr::from_ref(function).cast::<CapturingNativeFunction>() };+ let function: &CapturingNativeFunction = cast_ref(function);// NB: The behaviour is borrowed for the whole call. That is sound: the function is the [[Function]] of the// running execution context, which keeps it and its behaviour alive, and the behaviour is never replaced.function@@ -785,9 +782,7 @@ impl RawNativeFunction {}fn call(function: &NativeFunction, vm: &Vm) -> ThrowCompletionOr<Value> {- assert!(function.is::<RawNativeFunction>());- // SAFETY: The function is a RawNativeFunction, which starts with its NativeFunction.- let function = unsafe { &*core::ptr::from_ref(function).cast::<RawNativeFunction>() };+ let function: &RawNativeFunction = cast_ref(function);call_raw_native_function(function.native_function(vm), vm)}diff --git a/Libraries/LibJS/Rust/src/runtime/native_javascript_backed_function.rs b/Libraries/LibJS/Rust/src/runtime/native_javascript_backed_function.rsindex fb6d3fc5bb6..d950a7376dd 100644--- a/Libraries/LibJS/Rust/src/runtime/native_javascript_backed_function.rs+++ b/Libraries/LibJS/Rust/src/runtime/native_javascript_backed_function.rs@@ -10,7 +10,7 @@ use core::ops::Deref;use libjs_runtime_macros::Trace;use crate::bytecode::executable::Executable;-use crate::gc::class::{GcCell, define_cell};+use crate::gc::class::{GcCell, cast_ref, define_cell};use crate::interpreter::run::should_dump_bytecode;use crate::interpreter::vm::Vm;use crate::layout::cell::Gc;@@ -74,9 +74,7 @@ impl Deref for NativeJavaScriptBackedFunction {/// The function an internal method of a NativeJavaScriptBackedFunction was called on.fn as_native_javascript_backed_function(object: &Object) -> &NativeJavaScriptBackedFunction {- assert!(object.is::<NativeJavaScriptBackedFunction>());- // SAFETY: The object is a NativeJavaScriptBackedFunction, which starts with its Object.- unsafe { &*core::ptr::from_ref(object).cast::<NativeJavaScriptBackedFunction>() }+ cast_ref(object)}impl NativeJavaScriptBackedFunction {diff --git a/Libraries/LibJS/Rust/src/runtime/object.rs b/Libraries/LibJS/Rust/src/runtime/object.rsindex a8d2b916bc2..b2b2bde0d94 100644--- a/Libraries/LibJS/Rust/src/runtime/object.rs+++ b/Libraries/LibJS/Rust/src/runtime/object.rs@@ -4432,6 +4432,6 @@ fn create_data_property_for_set(impl Object {/// Whether the object was allocated as a `T`.pub fn is<T: GcCell + Extends<Object>>(&self) -> bool {- self.class().is_subclass_of(T::CLASS)+ self.class().is_class_of::<T>()}}diff --git a/Libraries/LibJS/Rust/src/runtime/promise_resolving_element_functions.rs b/Libraries/LibJS/Rust/src/runtime/promise_resolving_element_functions.rsindex f9c35e7c80a..14809e27af7 100644--- a/Libraries/LibJS/Rust/src/runtime/promise_resolving_element_functions.rs+++ b/Libraries/LibJS/Rust/src/runtime/promise_resolving_element_functions.rs@@ -10,7 +10,7 @@ use core::ops::Deref;use ak::Utf16FlyString;use libjs_runtime_macros::Trace;-use crate::gc::class::{Class, Finalize, GcCell, define_cell};+use crate::gc::class::{Class, Finalize, GcCell, cast_ref, define_cell};use crate::gc::gc_ref_cell::GcRefCell;use crate::gc::root::MarkedVec;use crate::interpreter::vm::Vm;@@ -187,9 +187,7 @@ impl PromiseResolvingElementFunction {}fn call(function: &NativeFunction, vm: &Vm) -> ThrowCompletionOr<Value> {- assert!(function.is::<PromiseResolvingElementFunction>());- // SAFETY: The function is a PromiseResolvingElementFunction, which starts with its NativeFunction.- let function = unsafe { &*core::ptr::from_ref(function).cast::<PromiseResolvingElementFunction>() };+ let function: &PromiseResolvingElementFunction = cast_ref(function);if function.already_called.get() {return Ok(Value::UNDEFINED);diff --git a/Libraries/LibJS/Rust/src/runtime/promise_resolving_function.rs b/Libraries/LibJS/Rust/src/runtime/promise_resolving_function.rsindex fba5d98ee3f..a7838e13dc9 100644--- a/Libraries/LibJS/Rust/src/runtime/promise_resolving_function.rs+++ b/Libraries/LibJS/Rust/src/runtime/promise_resolving_function.rs@@ -9,7 +9,7 @@ use core::ops::Deref;use libjs_runtime_macros::Trace;-use crate::gc::class::{GcCell, define_cell};+use crate::gc::class::{GcCell, cast_ref, define_cell};use crate::interpreter::vm::Vm;use crate::layout::cell::Gc;use crate::layout::object::Object;@@ -130,9 +130,7 @@ impl PromiseResolvingFunction {reason = "the call of a native function returns a completion")]fn call(function: &NativeFunction, vm: &Vm) -> ThrowCompletionOr<Value> {- assert!(function.is::<PromiseResolvingFunction>());- // SAFETY: The function is a PromiseResolvingFunction, which starts with its NativeFunction.- let function = unsafe { &*core::ptr::from_ref(function).cast::<PromiseResolvingFunction>() };+ let function: &PromiseResolvingFunction = cast_ref(function);let promise = function.promise.get();let already_resolved_owner = function.already_resolved_owner();let already_resolved = &already_resolved_owner.already_resolved;diff --git a/Libraries/LibJS/Rust/src/runtime/proxy_object.rs b/Libraries/LibJS/Rust/src/runtime/proxy_object.rsindex 86ed0f8973b..588811395e6 100644--- a/Libraries/LibJS/Rust/src/runtime/proxy_object.rs+++ b/Libraries/LibJS/Rust/src/runtime/proxy_object.rs@@ -11,7 +11,7 @@ use std::collections::HashSet;use ak::Utf16String;use libjs_runtime_macros::Trace;-use crate::gc::class::{GcCell, define_cell};+use crate::gc::class::{GcCell, cast_ref, define_cell};use crate::gc::root::MarkedVec;use crate::interpreter::vm::Vm;use crate::layout::cell::Gc;@@ -121,9 +121,7 @@ impl Deref for ProxyObject {/// The proxy an internal method of a proxy was called on.fn as_proxy_object(object: &Object) -> &ProxyObject {- assert!(object.is_proxy_object());- // SAFETY: The object is a ProxyObject, which starts with its Object.- unsafe { &*core::ptr::from_ref(object).cast::<ProxyObject>() }+ cast_ref(object)}impl Object {diff --git a/Libraries/LibJS/Rust/src/runtime/string_object.rs b/Libraries/LibJS/Rust/src/runtime/string_object.rsindex 6a44db2a016..47452817fed 100644--- a/Libraries/LibJS/Rust/src/runtime/string_object.rs+++ b/Libraries/LibJS/Rust/src/runtime/string_object.rs@@ -8,7 +8,7 @@ use core::ops::{ControlFlow, Deref};use libjs_runtime_macros::Trace;-use crate::gc::class::{Class, GcCell, define_cell};+use crate::gc::class::{Class, GcCell, cast_ref, define_cell};use crate::gc::root::MarkedVec;use crate::interpreter::vm::Vm;use crate::layout::cell::Gc;@@ -55,9 +55,7 @@ impl Deref for StringObject {/// The String object an internal method of a String object was called on.fn as_string_object(object: &Object) -> &StringObject {- assert!(object.is::<StringObject>());- // SAFETY: The object is a StringObject, which starts with its Object.- unsafe { &*core::ptr::from_ref(object).cast::<StringObject>() }+ cast_ref(object)}impl StringObject {diff --git a/Libraries/LibJS/Rust/src/runtime/typed_array.rs b/Libraries/LibJS/Rust/src/runtime/typed_array.rsindex 311dd0456ee..9f9535403ab 100644--- a/Libraries/LibJS/Rust/src/runtime/typed_array.rs+++ b/Libraries/LibJS/Rust/src/runtime/typed_array.rs@@ -10,7 +10,7 @@ use core::ops::{ControlFlow, Deref};use ak::Utf16FlyString;use libjs_runtime_macros::Trace;-use crate::gc::class::{Class, GcCell, define_cell};+use crate::gc::class::{Class, GcCell, cast_ref, define_cell};use crate::gc::root::MarkedVec;use crate::gc::visitor::{Trace, Visitor};use crate::interpreter::vm::Vm;@@ -163,9 +163,7 @@ impl Deref for TypedArrayBase {/// The typed array an internal method of a typed array was called on.fn as_typed_array(object: &Object) -> &TypedArrayBase {- assert!(object.is::<TypedArrayBase>());- // SAFETY: The object is a TypedArrayBase, which starts with its Object.- unsafe { &*core::ptr::from_ref(object).cast::<TypedArrayBase>() }+ cast_ref(object)}impl TypedArrayBase {diff --git a/Libraries/LibJS/Rust/src/utilities/js.rs b/Libraries/LibJS/Rust/src/utilities/js.rsindex 86a1f9d9fe7..ad3a69777a1 100644--- a/Libraries/LibJS/Rust/src/utilities/js.rs+++ b/Libraries/LibJS/Rust/src/utilities/js.rs@@ -26,7 +26,7 @@ use crate::compile::parse;use crate::console::{Console, ConsoleClient, ConsoleClientMethods, LogLevel, PrinterArguments};use crate::contrib::test262::global_object::Test262GlobalObject;use crate::debugger::{Debugger, PauseInfo, PauseReason, ResumeMode};-use crate::gc::class::{GcCell, define_cell};+use crate::gc::class::{GcCell, cast_ref, define_cell};use crate::gc::root::Root;use crate::hash_table::HashTable;use crate::interpreter::run::set_dump_bytecode;@@ -1319,8 +1319,7 @@ impl ReplConsoleClient {}fn of(client: &ConsoleClient) -> &ReplConsoleClient {- // SAFETY: Only ReplConsoleClient has these methods.- unsafe { &*core::ptr::from_ref(client).cast::<ReplConsoleClient>() }+ cast_ref(client)}fn clear(client: &ConsoleClient) {