Skip to content

Truly independent web browser

LibJS: Remember what conversions find on the prototypes of each shape

Andreas Kling8603e1bf7f52
diff --git a/Libraries/LibJS/Rust/generate/layout_forward.rs b/Libraries/LibJS/Rust/generate/layout_forward.rs
index e4d0264300c..708fbacc869 100644
--- a/Libraries/LibJS/Rust/generate/layout_forward.rs
+++ b/Libraries/LibJS/Rust/generate/layout_forward.rs
@@ -32,6 +32,7 @@ pub struct Utf16StringSlot(usize);
pub struct RawNativeFunctionPointer(usize);
pub struct ShapeStorage;
+pub struct WatchpointSetStorage;
pub struct ObjectPropertyIteratorCacheDataStorage;
pub struct DeclarativeEnvironmentRareDataStorage;
pub struct EnvironmentShapeStorage;
diff --git a/Libraries/LibJS/Rust/src/bytecode/executable.rs b/Libraries/LibJS/Rust/src/bytecode/executable.rs
index 1dd52f1145e..36222914fea 100644
--- a/Libraries/LibJS/Rust/src/bytecode/executable.rs
+++ b/Libraries/LibJS/Rust/src/bytecode/executable.rs
@@ -722,10 +722,6 @@ define_static_property_lookup_cache_sites! {
SpeciesConstructorConstructor,
SpeciesConstructorSpecies,
ValueToPrimitive,
- ValueDefaultConversionsToString,
- ValueDefaultConversionsValueOf,
- ValueDefaultConversionsToPrimitive,
- ValueDefaultConversionsToStringTag,
GetPrototypeFromConstructorPrototype,
ValueIsRegExp,
InstanceOfHasInstance,
diff --git a/Libraries/LibJS/Rust/src/gc/class_id.rs b/Libraries/LibJS/Rust/src/gc/class_id.rs
index fae032672c1..da00e31728c 100644
--- a/Libraries/LibJS/Rust/src/gc/class_id.rs
+++ b/Libraries/LibJS/Rust/src/gc/class_id.rs
@@ -33,6 +33,7 @@ define_class_ids! {
Shape,
WatchpointSet,
Fuse,
+ SpecialPropertyCache,
DescriptorArray,
ValueStorage,
PrivateEnvironment,
diff --git a/Libraries/LibJS/Rust/src/layout/shape.rs b/Libraries/LibJS/Rust/src/layout/shape.rs
index 5eaf930ec8d..e80ed90ea6a 100644
--- a/Libraries/LibJS/Rust/src/layout/shape.rs
+++ b/Libraries/LibJS/Rust/src/layout/shape.rs
@@ -10,7 +10,7 @@ use super::cell::{CellHeader, Gc};
use super::object::Object;
use super::property_lookup_cache::ObjectPropertyIteratorCacheData;
use super::realm::Realm;
-use crate::layout_forward::ShapeStorage;
+use crate::layout_forward::{ShapeStorage, WatchpointSetStorage};
#[repr(C)]
pub struct Shape {
@@ -32,6 +32,5 @@ pub struct Shape {
pub struct WatchpointSet {
pub header: CellHeader,
pub valid: Cell<bool>,
- /// Keeps the cell at the minimum cell size.
- pub padding: usize,
+ pub storage: WatchpointSetStorage,
}
diff --git a/Libraries/LibJS/Rust/src/layout_forward.rs b/Libraries/LibJS/Rust/src/layout_forward.rs
index 82119058ad5..8ced4ea95dc 100644
--- a/Libraries/LibJS/Rust/src/layout_forward.rs
+++ b/Libraries/LibJS/Rust/src/layout_forward.rs
@@ -16,6 +16,7 @@ pub use crate::runtime::private_environment::PrivateEnvironmentStorage;
pub use crate::runtime::realm::RealmStorage;
pub use crate::runtime::shape::ShapeStorage;
pub use crate::runtime::symbol::Symbol;
+pub use crate::runtime::watchpoint_set::WatchpointSetStorage;
pub use ak::Utf16StringDataHeader;
pub use crate::runtime::intrinsics::Intrinsics;
diff --git a/Libraries/LibJS/Rust/src/runtime/json_object.rs b/Libraries/LibJS/Rust/src/runtime/json_object.rs
index 972ba783c74..e14daa3d01c 100644
--- a/Libraries/LibJS/Rust/src/runtime/json_object.rs
+++ b/Libraries/LibJS/Rust/src/runtime/json_object.rs
@@ -40,10 +40,11 @@ use crate::runtime::property_attributes::{Attribute, DEFAULT_ATTRIBUTES, Propert
use crate::runtime::property_key::PropertyKey;
use crate::runtime::raw_json_object::RawJSONObject;
use crate::runtime::realm::Realm;
-use crate::runtime::shape::{Shape, WatchpointSet};
+use crate::runtime::shape::Shape;
use crate::runtime::string_conversions::parse_first_number_f64;
use crate::runtime::string_object::StringObject;
use crate::runtime::value::{DecimalDigits, append_number_to_string, same_value};
+use crate::runtime::watchpoint_set::WatchpointSet;
use crate::simdjson;
use crate::utf16::{Utf16StringBuilder, Utf16View};
diff --git a/Libraries/LibJS/Rust/src/runtime/mod.rs b/Libraries/LibJS/Rust/src/runtime/mod.rs
index 1934d6319b2..784d14f24ef 100644
--- a/Libraries/LibJS/Rust/src/runtime/mod.rs
+++ b/Libraries/LibJS/Rust/src/runtime/mod.rs
@@ -162,6 +162,7 @@ pub mod shared_array_buffer_constructor;
pub mod shared_array_buffer_prototype;
pub mod shared_function_instance_data;
pub mod source_text_module;
+pub mod special_property_cache;
pub mod string_constructor;
pub mod string_conversions;
pub mod string_iterator;
@@ -185,6 +186,7 @@ pub mod value;
pub mod value_conversions;
pub mod value_storage;
pub mod value_traits;
+pub mod watchpoint_set;
pub mod weak_map;
pub mod weak_map_constructor;
pub mod weak_map_prototype;
diff --git a/Libraries/LibJS/Rust/src/runtime/object.rs b/Libraries/LibJS/Rust/src/runtime/object.rs
index c5e11f8296d..601cf478397 100644
--- a/Libraries/LibJS/Rust/src/runtime/object.rs
+++ b/Libraries/LibJS/Rust/src/runtime/object.rs
@@ -13,7 +13,7 @@ use ak::{Utf16FlyString, Utf16String};
use libjs_abi::{Builtin, PutKind};
use libjs_runtime_macros::Trace;
-use crate::bytecode::executable::{PropertyLookupCache, StaticPropertyLookupCacheSite};
+use crate::bytecode::executable::PropertyLookupCache;
use crate::bytecode::property_access::{Strict, put_by_property_key};
use crate::embedding::abi_types::JSRealm;
use crate::gc::class::{Class, Extends, ExternalMemorySize, GcCell, define_cell};
@@ -46,6 +46,7 @@ use crate::runtime::indexed_properties::{GenericIndexedPropertyStorage, ValueAnd
use crate::runtime::iterator::BuiltinIteratorNext;
use crate::runtime::native_function::{NativeFunction, NativeFunctionMethods, RawNativeFunction};
use crate::runtime::native_javascript_backed_function::NativeJavaScriptBackedFunction;
+use crate::runtime::object_prototype::ObjectPrototype;
use crate::runtime::primitive_string::PrimitiveString;
use crate::runtime::private_environment::PrivateName;
use crate::runtime::property_attributes::{DEFAULT_ATTRIBUTES, PropertyAttributes};
@@ -54,6 +55,7 @@ use crate::runtime::property_key::PropertyKey;
use crate::runtime::realm::Realm;
use crate::runtime::realm_fuses;
use crate::runtime::shape::{AssignCopy, Shape};
+use crate::runtime::special_property_cache::{self, SpecialPropertyKey};
use crate::runtime::symbol::Symbol;
use crate::runtime::value::{PreferredType, is_strictly_equal, same_value};
use crate::runtime::value_storage::{self, ValueStorageKind};
@@ -2563,6 +2565,11 @@ impl Object {
{
return;
}
+ // NB: Caches write to slots without telling what relies on their values, so nothing may rely
+ // on the value of a slot of a prototype once a cache may write to it.
+ if writes_data_property {
+ self.shape().note_slot_written_by_caches(vm, property_offset);
+ }
*cacheable_metadata = CacheableSetPropertyMetadata {
r#type: CacheableSetPropertyMetadataType::ChangeOwnProperty,
property_offset: Some(property_offset),
@@ -3363,33 +3370,31 @@ impl Object {
let method_names = if preferred_type == PreferredType::String {
// 1. If hint is string, then
// a. Let methodNames be « "toString", "valueOf" ».
- [vm.names.toString.clone(), vm.names.valueOf.clone()]
+ [SpecialPropertyKey::ToString, SpecialPropertyKey::ValueOf]
} else {
// 2. Else,
// a. Let methodNames be « "valueOf", "toString" ».
- [vm.names.valueOf.clone(), vm.names.toString.clone()]
+ [SpecialPropertyKey::ValueOf, SpecialPropertyKey::ToString]
};
// 3. For each element name of methodNames, do
- for method_name in &method_names {
+ for method_name in method_names {
// a. Let method be ? Get(O, name).
- let method = if *method_name == vm.names.toString {
- self.get_with_cache(
- vm,
- method_name,
- vm.static_property_lookup_cache(StaticPropertyLookupCacheSite::ObjectOrdinaryToPrimitiveToString),
- )?
- } else {
- debug_assert!(*method_name == vm.names.valueOf);
- self.get_with_cache(
- vm,
- method_name,
- vm.static_property_lookup_cache(StaticPropertyLookupCacheSite::ObjectOrdinaryToPrimitiveValueOf),
- )?
- };
+ let method = special_property_cache::get(vm, self, method_name)?;
// b. If IsCallable(method) is true, then
if method.is_function() {
+ // OPTIMIZATION: %Object.prototype.valueOf% gives the object, and %Object.prototype.toString% gives
+ // what the special property cache knows, if it does, without running code.
+ if ObjectPrototype::is_value_of_function(vm, method.as_function()) {
+ continue;
+ }
+ if ObjectPrototype::is_to_string_function(vm, method.as_function())
+ && let Some(string) = special_property_cache::object_to_string(self)
+ {
+ return Ok(Value::from_string(string));
+ }
+
// i. Let result be ? Call(method, O).
let result = call(vm, method, Value::from_object(self.as_gc()), &[])?;
@@ -3559,7 +3564,7 @@ impl Object {
self.set_flag(object_flag::HAS_INTRINSIC_ACCESSORS);
}
- fn has_unimplemented_properties(&self) -> bool {
+ pub(crate) fn has_unimplemented_properties(&self) -> bool {
self.has_flag(object_flag::HAS_UNIMPLEMENTED_PROPERTIES)
}
@@ -3605,18 +3610,25 @@ impl Object {
/// slot of a property that was just added, or the slot of an intrinsic accessor that computes its value the first
/// time it is read.
pub fn initialize_direct(&self, index: u32, value: Value) {
+ debug_assert!(!self.shape().is_slot_watched(index));
self.write_direct(index, value);
}
/// Writes a value to the slot of an own writable data property where a property lookup cache recorded a write.
- /// Caches only record writes that need nothing but the write itself (see `replace_direct()`).
+ /// Caches only record writes that need nothing but the write itself (see `replace_direct()`), and nothing relies on
+ /// the value of a slot that caches write to (see `Shape::note_slot_written_by_caches()`).
pub fn put_direct_from_cache(&self, index: u32, value: Value) {
+ debug_assert!(!self.shape().is_slot_watched(index));
self.write_direct(index, value);
}
/// Changes the value of the own named property in slot `index`, and tells what depends on the slot keeping its
/// value.
pub fn replace_direct(&self, vm: &Vm, index: u32, value: Value) {
+ let shape = self.shape();
+ if shape.has_watched_slots() && self.get_direct(index) != value {
+ shape.note_slot_replacement(vm, index);
+ }
// NB: JIT code may take the values of global object properties that were never assigned as constants.
if self.has_global_object_flag() {
let previous = self.get_direct(index);
diff --git a/Libraries/LibJS/Rust/src/runtime/object_prototype.rs b/Libraries/LibJS/Rust/src/runtime/object_prototype.rs
index 26b77800e8b..76390967a29 100644
--- a/Libraries/LibJS/Rust/src/runtime/object_prototype.rs
+++ b/Libraries/LibJS/Rust/src/runtime/object_prototype.rs
@@ -7,7 +7,6 @@
use ak::{Utf16FlyString, Utf16String};
use libjs_runtime_macros::Trace;
-use crate::bytecode::executable::StaticPropertyLookupCacheSite;
use crate::gc::class::{GcCell, define_cell};
use crate::gc::class_id::ClassId;
use crate::interpreter::vm::Vm;
@@ -30,10 +29,14 @@ use crate::runtime::property_descriptor::PropertyDescriptor;
use crate::runtime::property_key::PropertyKey;
use crate::runtime::realm::Realm;
use crate::runtime::regexp_constructor::is_raw_native_function_running;
+use crate::runtime::special_property_cache::{self, SpecialPropertyKey};
use crate::runtime::string_object::StringObject;
use crate::runtime::value::same_value;
use crate::utf16::{Utf16View, concatenate};
+/// %Object.prototype.toString%, which is_to_string_function() looks for.
+static TO_STRING_FUNCTION: RawNativeFunctionPointer = raw_native!(ObjectPrototype::to_string);
+
/// %Object.prototype.valueOf%, which is_value_of_function() looks for.
static VALUE_OF_FUNCTION: RawNativeFunctionPointer = raw_native!(ObjectPrototype::value_of);
@@ -53,25 +56,26 @@ define_object_class!(ObjectPrototype, extends: [Object], methods: {
/// The longest tag whose Object.prototype.toString result is made without building a string first.
const SHORT_TAG_LENGTH: usize = 23;
-/// Whether no object on the prototype chain of `object`, starting with `object`, has a @@toStringTag property, and all of
-/// them look properties up in their storage, so that Get of @@toStringTag gives undefined without running code.
-fn has_no_to_string_tag_on_prototype_chain(vm: &Vm, object: &Object) -> bool {
- const MAX_PROTOTYPE_CHAIN_LENGTH: usize = 8;
- let object_prototype = vm.current_realm().map(|realm| realm.object_prototype());
- let mut current = Some(object.as_gc());
- for _ in 0..MAX_PROTOTYPE_CHAIN_LENGTH {
- let Some(object) = current else {
- return true;
- };
- // NB: %Object.prototype% only has an exotic [[SetPrototypeOf]]. Intrinsic accessors, whose keys are in the shape
- // already, only have string keys.
- let is_ordinary = Some(object) == object_prototype || object.has_ordinary_named_property_lookup();
- if !is_ordinary || object.shape().has_to_string_tag(vm) {
- return false;
- }
- current = object.shape().prototype();
+/// Step 17 of Object.prototype.toString: the string-concatenation of "[object ", `tag`, and "]".
+fn object_to_string_with_tag(vm: &Vm, tag: Utf16View<'_>) -> Gc<PrimitiveString> {
+ // OPTIMIZATION: The VM has a cache for the extremely common "[object Object]" string.
+ if tag == "Object" {
+ return vm.cached_strings().object_Object;
+ }
+ // OPTIMIZATION: The result for a short ASCII tag is made from its characters without building a string first.
+ if let Utf16View::Ascii(tag_characters) = tag
+ && tag_characters.len() <= SHORT_TAG_LENGTH
+ {
+ let mut characters = [0; SHORT_TAG_LENGTH + 9];
+ characters[..8].copy_from_slice(b"[object ");
+ characters[8..8 + tag_characters.len()].copy_from_slice(tag_characters);
+ characters[8 + tag_characters.len()] = b']';
+ return PrimitiveString::create_from_ascii(vm, &characters[..tag_characters.len() + 9]);
}
- false
+ PrimitiveString::create(
+ vm,
+ concatenate(&[Utf16View::Ascii(b"[object "), tag, Utf16View::Ascii(b"]")]),
+ )
}
/// Steps 5 to 14 of Object.prototype.toString: the builtinTag of `object`, given whether IsArray(object) is true.
@@ -142,7 +146,7 @@ impl ObjectPrototype {
object.define_native_function(vm, realm, property_key, function, length, attr, None);
};
define_native_function(&names.hasOwnProperty, HAS_OWN_PROPERTY_FUNCTION, 1);
- define_native_function(&names.toString, raw_native!(ObjectPrototype::to_string), 0);
+ define_native_function(&names.toString, TO_STRING_FUNCTION, 0);
define_native_function(&names.toLocaleString, raw_native!(ObjectPrototype::to_locale_string), 0);
define_native_function(&names.valueOf, VALUE_OF_FUNCTION, 0);
define_native_function(
@@ -272,6 +276,11 @@ impl ObjectPrototype {
// 3. Let O be ! ToObject(this value).
let object = this_value.to_object(vm).must();
+ // OPTIMIZATION: The special property cache of the shape of O may know what the steps below give.
+ if let Some(string) = special_property_cache::object_to_string(&object) {
+ return Ok(Value::from_string(string));
+ }
+
// 4. Let isArray be ? IsArray(O).
let is_array = Value::from_object(object).is_array(vm)?;
@@ -279,16 +288,7 @@ impl ObjectPrototype {
let builtin_tag = builtin_tag(&object, is_array);
// 15. Let tag be ? Get(O, @@toStringTag).
- // OPTIMIZATION: Get finds nothing without running code when no object on the chain has the property.
- let to_string_tag = if has_no_to_string_tag_on_prototype_chain(vm, &object) {
- Value::UNDEFINED
- } else {
- object.get_with_cache(
- vm,
- &PropertyKey::from(vm.well_known_symbols().to_string_tag),
- vm.static_property_lookup_cache(StaticPropertyLookupCacheSite::ObjectPrototypeToStringToStringTag),
- )?
- };
+ let to_string_tag = special_property_cache::get(vm, &object, SpecialPropertyKey::ToStringTag)?;
// Optimization: Instead of creating another PrimitiveString from builtin_tag, we separate tag and to_string_tag and add an additional branch to step 16.
let custom_tag: Utf16String;
@@ -302,28 +302,14 @@ impl ObjectPrototype {
};
// 17. Return the string-concatenation of "[object ", tag, and "]".
+ let string = object_to_string_with_tag(vm, tag);
+ special_property_cache::note_object_to_string(&object, to_string_tag, string);
+ Ok(Value::from_string(string))
+ }
- // OPTIMIZATION: The VM has a cache for the extremely common "[object Object]" string.
- if tag == "Object" {
- return Ok(Value::from_string(vm.cached_strings().object_Object));
- }
- // OPTIMIZATION: The result for a short ASCII tag is made from its characters without building a string first.
- if let Utf16View::Ascii(tag_characters) = tag
- && tag_characters.len() <= SHORT_TAG_LENGTH
- {
- let mut characters = [0; SHORT_TAG_LENGTH + 9];
- characters[..8].copy_from_slice(b"[object ");
- characters[8..8 + tag_characters.len()].copy_from_slice(tag_characters);
- characters[8 + tag_characters.len()] = b']';
- return Ok(Value::from_string(PrimitiveString::create_from_ascii(
- vm,
- &characters[..tag_characters.len() + 9],
- )));
- }
- Ok(Value::from_string(PrimitiveString::create(
- vm,
- concatenate(&[Utf16View::Ascii(b"[object "), tag, Utf16View::Ascii(b"]")]),
- )))
+ /// Whether `function` is %Object.prototype.toString% of some realm.
+ pub fn is_to_string_function(vm: &Vm, function: Gc<FunctionObject>) -> bool {
+ is_raw_native_function_running(vm, function, TO_STRING_FUNCTION)
}
/// Whether `function` is %Object.prototype.valueOf% of some realm.
diff --git a/Libraries/LibJS/Rust/src/runtime/shape.rs b/Libraries/LibJS/Rust/src/runtime/shape.rs
index bac68132611..855a3a72368 100644
--- a/Libraries/LibJS/Rust/src/runtime/shape.rs
+++ b/Libraries/LibJS/Rust/src/runtime/shape.rs
@@ -21,13 +21,15 @@ use crate::jit::dependencies::{CellId, Dependency};
use crate::layout::cell::{CellHeader, Gc};
use crate::layout::object::Object;
use crate::layout::property_lookup_cache::ObjectPropertyIteratorCacheData;
-pub use crate::layout::shape::{Shape, WatchpointSet};
+pub use crate::layout::shape::Shape;
use crate::layout::value::Value;
use crate::runtime::descriptor_array::{DescriptorArray, MAX_DESCRIPTOR_COUNT, PropertyMetadata};
use crate::runtime::object::IntegrityLevel;
use crate::runtime::property_attributes::PropertyAttributes;
use crate::runtime::property_key::PropertyKey;
use crate::runtime::realm::Realm;
+use crate::runtime::special_property_cache::SpecialPropertyCache;
+use crate::runtime::watchpoint_set::WatchpointSet;
type RandomState = foldhash::fast::RandomState;
@@ -37,51 +39,13 @@ pub struct TransitionKey {
pub attributes: PropertyAttributes,
}
-define_cell!(WatchpointSet, Other);
-
-// SAFETY: A watchpoint set holds no cells.
-unsafe impl Trace for WatchpointSet {
- fn trace(&self, _: &mut Visitor) {}
-}
-
-impl WatchpointSet {
- pub fn create(vm: &Vm) -> Gc<WatchpointSet> {
- vm.heap().allocate(WatchpointSet {
- header: CellHeader::for_class(Self::CLASS),
- valid: Cell::new(true),
- padding: 0,
- })
- }
-
- pub fn is_valid(&self) -> bool {
- self.valid.get()
- }
-
- /// Notes that what the set stands for stopped holding, which invalidates the JIT code that depends on it.
- pub fn fire(&self, vm: &Vm) {
- if !self.is_valid() {
- return;
- }
- self.valid.set(false);
- crate::jit::dependencies::invalidate_dependents(
- vm,
- Dependency::WatchpointSetValid(CellId(core::ptr::from_ref(self) as u64)),
- );
- }
-}
-
/// The bits of Shape::flags, the flags of a shape that are not its forward transition storage.
mod shape_flag {
pub const DICTIONARY: u8 = 1 << 0;
pub const HAS_PARAMETER_MAP: u8 = 1 << 1;
- /// Whether HAS_CONVERSION_PROPERTIES has been found for a shape that is not a dictionary.
- pub const CONVERSION_PROPERTIES_KNOWN: u8 = 1 << 2;
- /// Whether the shape has one of the properties that conversions to primitives look up.
- pub const HAS_CONVERSION_PROPERTIES: u8 = 1 << 3;
- /// Whether HAS_TO_STRING_TAG has been found for a shape that is not a dictionary.
- pub const TO_STRING_TAG_KNOWN: u8 = 1 << 4;
- /// Whether the shape has a @@toStringTag property.
- pub const HAS_TO_STRING_TAG: u8 = 1 << 5;
+ /// Something relies on the value in a slot of the object of this prototype shape (see
+ /// `Shape::watch_slot_for_replacements()`).
+ pub const HAS_WATCHED_SLOTS: u8 = 1 << 2;
/// An object may have left the shape (see `Shape::is_stable()`).
pub const UNSTABLE: u8 = 1 << 6;
/// JIT code depends on the shape staying stable.
@@ -124,6 +88,17 @@ struct RareData {
assign_copy: Option<AssignCopy>,
/// The shapes that sealing and freezing objects of this shape give them, by integrity level.
integrity_level_shapes: [Option<Gc<Shape>>; 2],
+ /// What is known of the replacement of the values in the slots of the object that has this prototype shape, by
+ /// offset (see `Shape::watch_slot_for_replacements()`).
+ watched_slots: HashMap<u32, WatchedSlot, RandomState>,
+}
+
+/// What a prototype shape knows of the replacement of the value in one of the slots of its object.
+enum WatchedSlot {
+ /// The set fires when the value changes.
+ Watched(Gc<WatchpointSet>),
+ /// A property lookup cache may write to the slot, without telling anything.
+ WrittenByCaches,
}
/// What Object.assign of an object with a shape onto an empty object makes, as set_cached_assign_copy() keeps it.
@@ -155,6 +130,9 @@ pub struct ShapeStorage {
/// long as any object has a shape, the whole chain that leads to it stays cached and the next object built the same
/// way gets the same shape, also after a garbage collection.
previous: Cell<Option<Gc<Shape>>>,
+ /// What Get of the properties that conversions look up gives on the objects of this shape (see
+ /// `SpecialPropertyCache`).
+ special_property_cache: Cell<Option<Gc<SpecialPropertyCache>>>,
}
impl Default for ShapeStorage {
@@ -164,15 +142,18 @@ impl Default for ShapeStorage {
forward_transitions: GcRefCell::new(ForwardTransitions::Empty),
rare_data: GcRefCell::new(None),
previous: Cell::new(None),
+ special_property_cache: Cell::new(None),
}
}
}
-// SAFETY: Visits the descriptor array, the keys this storage owns and the previous shape. The shapes of transitions are
+// SAFETY: Visits the descriptor array, the keys this storage owns, the previous shape, the special property cache and
+// the watchpoint sets of slots. The shapes of transitions are
// weak, and so are the keys of prototype transitions, which are only compared.
unsafe impl Trace for ShapeStorage {
fn trace(&self, visitor: &mut Visitor) {
self.previous.trace(visitor);
+ self.special_property_cache.trace(visitor);
match &*self.property_storage.borrow() {
PropertyStorage::Descriptors(descriptors) => descriptors.trace(visitor),
@@ -210,6 +191,11 @@ unsafe impl Trace for ShapeStorage {
for shape in rare_data.integrity_level_shapes.iter().flatten() {
visitor.visit(*shape);
}
+ for watched_slot in rare_data.watched_slots.values() {
+ if let WatchedSlot::Watched(watchpoint_set) = watched_slot {
+ visitor.visit(*watchpoint_set);
+ }
+ }
}
}
}
@@ -710,13 +696,6 @@ impl Shape {
pub fn add_property_without_transition(&self, vm: &Vm, property_key: &PropertyKey, attributes: PropertyAttributes) {
self.invalidate_prototype_if_needed_for_change_without_transition(vm);
- self.flags.set(
- self.flags.get()
- & !(shape_flag::CONVERSION_PROPERTIES_KNOWN
- | shape_flag::HAS_CONVERSION_PROPERTIES
- | shape_flag::TO_STRING_TAG_KNOWN
- | shape_flag::HAS_TO_STRING_TAG),
- );
let property_count = self.property_count();
let metadata = PropertyMetadata {
offset: property_count,
@@ -908,6 +887,7 @@ impl Shape {
}
new_prototype_shape.set_prototype_shape(vm);
self.prototype_shape_validity().fire(vm);
+ self.fire_slot_watchpoints(vm);
self.invalidate_all_prototype_chains_leading_to_this(vm);
@@ -931,6 +911,7 @@ impl Shape {
}
self.prototype_shape_validity().fire(vm);
self.prototype_chain_validity.set(Some(WatchpointSet::create(vm)));
+ self.fire_slot_watchpoints(vm);
self.invalidate_all_prototype_chains_leading_to_this(vm);
}
@@ -1024,63 +1005,6 @@ impl Shape {
self.flags.set(self.flags.get() | shape_flag::HAS_PARAMETER_MAP);
}
- /// Whether objects of this shape have one of the properties that converting an object to a primitive looks up:
- /// "toString", "valueOf", @@toPrimitive and @@toStringTag.
- pub fn has_conversion_properties(&self, vm: &Vm) -> bool {
- if self.property_count() == 0 {
- return false;
- }
- // OPTIMIZATION: The properties of a shape that is not a dictionary only change when one is added to it without a
- // transition, which forgets the answer, so the answer is kept.
- let flags = self.flags.get();
- if flags & shape_flag::CONVERSION_PROPERTIES_KNOWN != 0 {
- return flags & shape_flag::HAS_CONVERSION_PROPERTIES != 0;
- }
- let well_known_symbols = vm.well_known_symbols();
- let has_conversion_properties = self.lookup(&vm.names.toString).is_some()
- || self.lookup(&vm.names.valueOf).is_some()
- || self
- .lookup(&PropertyKey::from(well_known_symbols.to_primitive))
- .is_some()
- || self
- .lookup(&PropertyKey::from(well_known_symbols.to_string_tag))
- .is_some();
- if !self.is_dictionary() {
- let has_flag = if has_conversion_properties {
- shape_flag::HAS_CONVERSION_PROPERTIES
- } else {
- 0
- };
- self.flags
- .set(flags | shape_flag::CONVERSION_PROPERTIES_KNOWN | has_flag);
- }
- has_conversion_properties
- }
-
- /// Whether objects of this shape have a @@toStringTag property.
- pub fn has_to_string_tag(&self, vm: &Vm) -> bool {
- if self.property_count() == 0 {
- return false;
- }
- // OPTIMIZATION: As with has_conversion_properties(), the answer is kept for shapes that are not dictionaries.
- let flags = self.flags.get();
- if flags & shape_flag::TO_STRING_TAG_KNOWN != 0 {
- return flags & shape_flag::HAS_TO_STRING_TAG != 0;
- }
- let has_to_string_tag = self
- .lookup(&PropertyKey::from(vm.well_known_symbols().to_string_tag))
- .is_some();
- if !self.is_dictionary() {
- let has_flag = if has_to_string_tag {
- shape_flag::HAS_TO_STRING_TAG
- } else {
- 0
- };
- self.flags.set(flags | shape_flag::TO_STRING_TAG_KNOWN | has_flag);
- }
- has_to_string_tag
- }
-
pub fn dictionary_generation(&self) -> u32 {
self.dictionary_generation.get()
}
@@ -1093,6 +1017,120 @@ impl Shape {
self.prototype_chain_validity.get()
}
+ pub fn special_property_cache(&self) -> Option<Gc<SpecialPropertyCache>> {
+ self.storage.special_property_cache.get()
+ }
+
+ pub fn set_special_property_cache(&self, cache: Gc<SpecialPropertyCache>) {
+ assert!(!self.is_dictionary() && !self.is_prototype_shape());
+ self.storage.special_property_cache.set(Some(cache));
+ }
+
+ /// The watchpoint set that fires when the value in slot `offset` of the object of this prototype shape changes, or
+ /// when the object leaves the shape. There is none for a slot that property lookup caches may write to, since they
+ /// write without telling anything.
+ pub fn watch_slot_for_replacements(&self, vm: &Vm, offset: u32) -> Option<Gc<WatchpointSet>> {
+ if !self.is_prototype_shape() {
+ return None;
+ }
+ match self
+ .storage
+ .rare_data
+ .borrow()
+ .as_ref()
+ .and_then(|rare_data| rare_data.watched_slots.get(&offset))
+ {
+ Some(WatchedSlot::WrittenByCaches) => return None,
+ Some(WatchedSlot::Watched(watchpoint_set)) if watchpoint_set.is_valid() => return Some(*watchpoint_set),
+ _ => {}
+ }
+ // NB: Allocating may collect garbage, which reads the rare data, so the set is made before borrowing it.
+ let watchpoint_set = WatchpointSet::create(vm);
+ self.with_rare_data(|rare_data| {
+ rare_data
+ .watched_slots
+ .insert(offset, WatchedSlot::Watched(watchpoint_set))
+ });
+ self.flags.set(self.flags.get() | shape_flag::HAS_WATCHED_SLOTS);
+ Some(watchpoint_set)
+ }
+
+ /// Whether something relies on the values in the slots of the object of this prototype shape.
+ #[inline]
+ pub fn has_watched_slots(&self) -> bool {
+ self.flags.get() & shape_flag::HAS_WATCHED_SLOTS != 0
+ }
+
+ /// Whether something relies on the value in slot `offset` of the object of this prototype shape.
+ pub fn is_slot_watched(&self, offset: u32) -> bool {
+ self.has_watched_slots()
+ && self.storage.rare_data.borrow().as_ref().is_some_and(|rare_data| {
+ matches!(
+ rare_data.watched_slots.get(&offset),
+ Some(WatchedSlot::Watched(watchpoint_set)) if watchpoint_set.is_valid()
+ )
+ })
+ }
+
+ /// Notes that the value in slot `offset` of the object of this prototype shape changes, which fires the watchpoint
+ /// set of the slot.
+ pub fn note_slot_replacement(&self, vm: &Vm, offset: u32) {
+ if !self.has_watched_slots() {
+ return;
+ }
+ let watchpoint_set = {
+ let mut rare_data = self.storage.rare_data.borrow_mut();
+ let Some(rare_data) = rare_data.as_mut() else {
+ return;
+ };
+ match rare_data.watched_slots.get(&offset) {
+ Some(WatchedSlot::Watched(watchpoint_set)) => {
+ let watchpoint_set = *watchpoint_set;
+ rare_data.watched_slots.remove(&offset);
+ watchpoint_set
+ }
+ Some(WatchedSlot::WrittenByCaches) | None => return,
+ }
+ };
+ watchpoint_set.fire(vm);
+ }
+
+ /// Notes that property lookup caches may write to slot `offset` of the object of this prototype shape from now on,
+ /// which fires the watchpoint set of the slot, and keeps the slot from getting another one.
+ pub fn note_slot_written_by_caches(&self, vm: &Vm, offset: u32) {
+ if !self.is_prototype_shape() {
+ return;
+ }
+ let watched_slot =
+ self.with_rare_data(|rare_data| rare_data.watched_slots.insert(offset, WatchedSlot::WrittenByCaches));
+ if let Some(WatchedSlot::Watched(watchpoint_set)) = watched_slot {
+ watchpoint_set.fire(vm);
+ }
+ }
+
+ /// Fires the watchpoint sets of the slots of the object of this prototype shape, as the object left the shape or
+ /// changed it in place, after which the offsets of its properties may be others. Which slots caches write to stays
+ /// known, since the caches that write to the shape in place may still do so.
+ fn fire_slot_watchpoints(&self, vm: &Vm) {
+ if !self.has_watched_slots() {
+ return;
+ }
+ self.flags.set(self.flags.get() & !shape_flag::HAS_WATCHED_SLOTS);
+ let mut watchpoint_sets = Vec::new();
+ if let Some(rare_data) = self.storage.rare_data.borrow_mut().as_mut() {
+ rare_data.watched_slots.retain(|_, watched_slot| match watched_slot {
+ WatchedSlot::Watched(watchpoint_set) => {
+ watchpoint_sets.push(*watchpoint_set);
+ false
+ }
+ WatchedSlot::WrittenByCaches => true,
+ });
+ }
+ for watchpoint_set in watchpoint_sets {
+ watchpoint_set.fire(vm);
+ }
+ }
+
pub fn property_iterator_cache(&self) -> Option<Gc<ObjectPropertyIteratorCacheData>> {
self.property_iterator_cache.get()
}
diff --git a/Libraries/LibJS/Rust/src/runtime/special_property_cache.rs b/Libraries/LibJS/Rust/src/runtime/special_property_cache.rs
new file mode 100644
index 00000000000..980f9e00684
--- /dev/null
+++ b/Libraries/LibJS/Rust/src/runtime/special_property_cache.rs
@@ -0,0 +1,344 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The special property cache of a shape: what Get of the properties that conversions of objects to primitives look
+//! up gives on the objects of the shape, for as long as that holds.
+//!
+//! The cache only knows what Get gives without running code: that no object on the prototype chain has the property,
+//! or that a prototype has it as a data property with a value. It relies on watchpoint sets for that to stay true. The
+//! shape of the prototype of the objects has one that fires when that prototype or one above it changes its
+//! properties or its prototype (see `Shape::prototype_chain_validity`), and the prototype that has the property has
+//! one that fires when the value of the property changes (see `Shape::watch_slot_for_replacements()`). The cache
+//! forgets everything it knows when one of them fires, and learns it again from the next Get.
+
+use core::cell::Cell;
+
+use crate::bytecode::executable::StaticPropertyLookupCacheSite;
+use crate::gc::class::{Class, GcCell, define_cell};
+use crate::gc::visitor::{Trace, Visitor};
+use crate::interpreter::vm::Vm;
+use crate::layout::cell::{CellHeader, Gc};
+use crate::layout::object::Object;
+use crate::layout::value::Value;
+use crate::runtime::completion::ThrowCompletionOr;
+use crate::runtime::function_object::FunctionObject;
+use crate::runtime::object_prototype::ObjectPrototype;
+use crate::runtime::primitive_string::PrimitiveString;
+use crate::runtime::property_key::PropertyKey;
+use crate::runtime::value::PreferredType;
+use crate::runtime::watchpoint_set::WatchpointSet;
+
+/// The most prototypes the cache looks through for a property.
+const MAX_PROTOTYPE_CHAIN_LENGTH: usize = 8;
+
+/// The properties the cache knows Get of.
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+#[repr(u8)]
+pub enum SpecialPropertyKey {
+ ToPrimitive,
+ ToString,
+ ValueOf,
+ ToStringTag,
+}
+
+const SPECIAL_PROPERTY_KEY_COUNT: usize = 4;
+
+impl SpecialPropertyKey {
+ fn property_key(self, vm: &Vm) -> PropertyKey {
+ match self {
+ Self::ToPrimitive => PropertyKey::from(vm.well_known_symbols().to_primitive),
+ Self::ToString => vm.names.toString.clone(),
+ Self::ValueOf => vm.names.valueOf.clone(),
+ Self::ToStringTag => PropertyKey::from(vm.well_known_symbols().to_string_tag),
+ }
+ }
+
+ fn static_property_lookup_cache_site(self) -> StaticPropertyLookupCacheSite {
+ match self {
+ Self::ToPrimitive => StaticPropertyLookupCacheSite::ValueToPrimitive,
+ Self::ToString => StaticPropertyLookupCacheSite::ObjectOrdinaryToPrimitiveToString,
+ Self::ValueOf => StaticPropertyLookupCacheSite::ObjectOrdinaryToPrimitiveValueOf,
+ Self::ToStringTag => StaticPropertyLookupCacheSite::ObjectPrototypeToStringToStringTag,
+ }
+ }
+}
+
+/// Whether ToPrimitive of the objects with one kind of preferred type gives what %Object.prototype.toString% gives for
+/// them without running code, as far as the cache knows.
+#[derive(Clone, Copy, PartialEq, Eq)]
+enum DefaultConversion {
+ Unknown,
+ Yes,
+ No,
+}
+
+#[repr(C)]
+pub struct SpecialPropertyCache {
+ header: CellHeader,
+ /// The class of the objects the cache knows of, since objects of different classes can have the same shape.
+ class: Cell<Option<&'static Class>>,
+ /// Whether objects of more than one class had the shape, which the cache gives up on.
+ gave_up: Cell<bool>,
+ /// How many times the cache forgot what it knew.
+ generation: Cell<u32>,
+ /// The validity of the shape of the prototype of the objects that the cache watches in this generation, which it
+ /// only watches once.
+ watched_prototype_chain_validity: Cell<Option<Gc<WatchpointSet>>>,
+ /// What Get of each key gives, or empty while that is not known.
+ values: [Cell<Value>; SPECIAL_PROPERTY_KEY_COUNT],
+ /// What %Object.prototype.toString% gives for the objects, while that is known.
+ object_to_string: Cell<Option<Gc<PrimitiveString>>>,
+ /// Whether ToPrimitive gives object_to_string with the preferred type string, and with the others.
+ default_conversions: [Cell<DefaultConversion>; 2],
+}
+
+define_cell!(SpecialPropertyCache, Other);
+
+// SAFETY: Visits the values and the string the cache knows, and the validity it watches.
+unsafe impl Trace for SpecialPropertyCache {
+ fn trace(&self, visitor: &mut Visitor) {
+ self.watched_prototype_chain_validity.trace(visitor);
+ for value in &self.values {
+ value.trace(visitor);
+ }
+ self.object_to_string.trace(visitor);
+ }
+}
+
+impl SpecialPropertyCache {
+ fn create(vm: &Vm) -> Gc<SpecialPropertyCache> {
+ vm.heap().allocate(SpecialPropertyCache {
+ header: CellHeader::for_class(Self::CLASS),
+ class: Cell::new(None),
+ gave_up: Cell::new(false),
+ generation: Cell::new(0),
+ watched_prototype_chain_validity: Cell::new(None),
+ values: core::array::from_fn(|_| Cell::new(Value::EMPTY)),
+ object_to_string: Cell::new(None),
+ default_conversions: core::array::from_fn(|_| Cell::new(DefaultConversion::Unknown)),
+ })
+ }
+
+ pub(crate) fn generation(&self) -> u32 {
+ self.generation.get()
+ }
+
+ /// Forgets what the cache knows, if it still knows what it knew in its generation `generation`.
+ pub(crate) fn forget(&self, generation: u32) {
+ if generation != self.generation.get() {
+ return;
+ }
+ self.generation.set(generation.wrapping_add(1));
+ self.class.set(None);
+ self.watched_prototype_chain_validity.set(None);
+ for value in &self.values {
+ value.set(Value::EMPTY);
+ }
+ self.object_to_string.set(None);
+ for default_conversion in &self.default_conversions {
+ default_conversion.set(DefaultConversion::Unknown);
+ }
+ }
+
+ /// Whether ToPrimitive of the objects gives object_to_string, if that is known yet.
+ fn default_conversion(&self, vm: &Vm, preferred_type: PreferredType) -> DefaultConversion {
+ let index = usize::from(preferred_type != PreferredType::String);
+ let known = self.default_conversions[index].get();
+ if known != DefaultConversion::Unknown {
+ return known;
+ }
+
+ // NB: ToPrimitive calls neither @@toPrimitive if it is undefined or null, nor valueOf if the preferred type is
+ // string. It skips %Object.prototype.valueOf%, which gives the object, and %Object.prototype.toString%
+ // gives object_to_string.
+ let value = |key: SpecialPropertyKey| self.values[key as usize].get();
+ let is_function_with = |value: Value, is_function: fn(&Vm, Gc<FunctionObject>) -> bool| {
+ value.is_function() && is_function(vm, value.as_function())
+ };
+ let to_primitive = value(SpecialPropertyKey::ToPrimitive);
+ let to_string = value(SpecialPropertyKey::ToString);
+ let value_of = value(SpecialPropertyKey::ValueOf);
+ let checks_value_of = preferred_type != PreferredType::String;
+ let definitely_not = (!to_primitive.is_empty() && !to_primitive.is_nullish())
+ || (!to_string.is_empty() && !is_function_with(to_string, ObjectPrototype::is_to_string_function))
+ || (checks_value_of
+ && !value_of.is_empty()
+ && !is_function_with(value_of, ObjectPrototype::is_value_of_function));
+ let known = if definitely_not {
+ DefaultConversion::No
+ } else if to_primitive.is_empty()
+ || to_string.is_empty()
+ || (checks_value_of && value_of.is_empty())
+ || self.object_to_string.get().is_none()
+ {
+ return DefaultConversion::Unknown;
+ } else {
+ DefaultConversion::Yes
+ };
+ self.default_conversions[index].set(known);
+ known
+ }
+}
+
+/// The cache of the shape of `object`, if it knows of objects like it.
+#[inline]
+fn cache_of(object: &Object) -> Option<Gc<SpecialPropertyCache>> {
+ let cache = object.shape().special_property_cache()?;
+ let class = cache.class.get()?;
+ // NB: The cache only knows of objects with ordinary property lookup, which only an object with unimplemented
+ // properties has without its class saying so.
+ (core::ptr::eq(class, object.class()) && !object.has_unimplemented_properties()).then_some(cache)
+}
+
+/// OPTIMIZATION: ToPrimitive(object, preferred_type) when it gives what %Object.prototype.toString% gives for the
+/// object without running code.
+#[inline]
+pub fn to_primitive_without_running_code(
+ vm: &Vm,
+ object: &Object,
+ preferred_type: PreferredType,
+) -> Option<Gc<PrimitiveString>> {
+ let cache = cache_of(object)?;
+ if cache.default_conversion(vm, preferred_type) != DefaultConversion::Yes {
+ return None;
+ }
+ cache.object_to_string.get()
+}
+
+/// What %Object.prototype.toString% gives for `object`, if the cache knows.
+pub fn object_to_string(object: &Object) -> Option<Gc<PrimitiveString>> {
+ cache_of(object)?.object_to_string.get()
+}
+
+/// Notes that %Object.prototype.toString% gave `string` for `object`, with `to_string_tag` from Get of @@toStringTag.
+pub fn note_object_to_string(object: &Object, to_string_tag: Value, string: Gc<PrimitiveString>) {
+ // NB: The string only depends on the class and the shape of the object, and on what Get of @@toStringTag gives,
+ // which the cache must know to be what the string was made from. A getter may have changed it since.
+ if let Some(cache) = cache_of(object)
+ && cache.values[SpecialPropertyKey::ToStringTag as usize].get() == to_string_tag
+ {
+ cache.object_to_string.set(Some(string));
+ }
+}
+
+/// Get(object, key), from the cache if it knows what that gives.
+pub fn get(vm: &Vm, object: &Object, key: SpecialPropertyKey) -> ThrowCompletionOr<Value> {
+ if let Some(cache) = cache_of(object) {
+ let value = cache.values[key as usize].get();
+ if !value.is_empty() {
+ return Ok(value);
+ }
+ }
+ let property_key = key.property_key(vm);
+ let value = object.get_with_cache(
+ vm,
+ &property_key,
+ vm.static_property_lookup_cache(key.static_property_lookup_cache_site()),
+ )?;
+ learn(vm, object, key, &property_key, value);
+ Ok(value)
+}
+
+/// Has the cache of the shape of `object` know that Get(object, key) gives `value`, if that holds without running code
+/// for as long as the watchpoint sets it relies on do not fire.
+fn learn(vm: &Vm, object: &Object, key: SpecialPropertyKey, property_key: &PropertyKey, value: Value) {
+ // NB: The objects of a dictionary shape or of a prototype shape change it in place.
+ let shape = object.shape();
+ if shape.is_dictionary() || shape.is_prototype_shape() || !object.has_ordinary_named_property_lookup() {
+ return;
+ }
+
+ // NB: The cache gives up on a shape that objects of more than one class have.
+ if let Some(cache) = shape.special_property_cache() {
+ if cache.gave_up.get() {
+ return;
+ }
+ if cache
+ .class
+ .get()
+ .is_some_and(|class| !core::ptr::eq(class, object.class()))
+ {
+ cache.forget(cache.generation());
+ cache.gave_up.set(true);
+ return;
+ }
+ }
+
+ // NB: An own property is not cached, since other objects that get the shape may have another value in it.
+ if shape.lookup(property_key).is_some() {
+ return;
+ }
+
+ let mut holder = None;
+ let first_prototype = shape.prototype();
+ let object_prototype = vm.current_realm().map(|realm| realm.object_prototype());
+ let mut current = first_prototype;
+ let mut chain_length = 0;
+ while let Some(prototype) = current {
+ chain_length += 1;
+ // NB: %Object.prototype% only has an exotic [[SetPrototypeOf]].
+ let is_ordinary = Some(prototype) == object_prototype || prototype.has_ordinary_named_property_lookup();
+ if chain_length > MAX_PROTOTYPE_CHAIN_LENGTH || !is_ordinary || prototype.has_unimplemented_properties() {
+ return;
+ }
+ if let Some(metadata) = prototype.shape().lookup(property_key) {
+ // NB: The value must be the one Get just gave, which also leaves out accessors and intrinsics that have
+ // not computed their value yet.
+ let slot_value = prototype.get_direct(metadata.offset);
+ if slot_value.is_accessor() || slot_value != value {
+ return;
+ }
+ holder = Some((prototype, metadata.offset));
+ break;
+ }
+ current = prototype.shape().prototype();
+ }
+ if holder.is_none() && !value.is_undefined() {
+ return;
+ }
+
+ let prototype_chain_validity = match first_prototype {
+ Some(first_prototype) => {
+ let Some(validity) = first_prototype.shape().prototype_chain_validity() else {
+ return;
+ };
+ if !validity.is_valid() {
+ return;
+ }
+ Some(validity)
+ }
+ None => None,
+ };
+
+ let cache = match shape.special_property_cache() {
+ Some(cache) => cache,
+ None => {
+ let cache = SpecialPropertyCache::create(vm);
+ shape.set_special_property_cache(cache);
+ cache
+ }
+ };
+ if cache.class.get().is_none() {
+ cache.class.set(Some(object.class()));
+ }
+
+ let generation = cache.generation();
+ if let Some((holder, offset)) = holder {
+ let Some(replacement_watchpoint_set) = holder.shape().watch_slot_for_replacements(vm, offset) else {
+ return;
+ };
+ replacement_watchpoint_set.add_watcher(vm, cache, generation);
+ }
+ if let Some(prototype_chain_validity) = prototype_chain_validity
+ && cache.watched_prototype_chain_validity.get() != Some(prototype_chain_validity)
+ {
+ prototype_chain_validity.add_watcher(vm, cache, generation);
+ cache
+ .watched_prototype_chain_validity
+ .set(Some(prototype_chain_validity));
+ }
+ cache.values[key as usize].set(value);
+}
diff --git a/Libraries/LibJS/Rust/src/runtime/value.rs b/Libraries/LibJS/Rust/src/runtime/value.rs
index 33349db3a00..5409d234fd4 100644
--- a/Libraries/LibJS/Rust/src/runtime/value.rs
+++ b/Libraries/LibJS/Rust/src/runtime/value.rs
@@ -13,9 +13,7 @@ use num_traits::Zero;
use crate::build_configuration::HEAP_REGION_OFFSET_MASK;
use crate::bytecode::executable::{PropertyLookupCache, StaticPropertyLookupCacheSite};
-use crate::bytecode::property_access::{
- CachePropertyAbsence, GetByIdMode, get_by_id, get_own_property_without_side_effects,
-};
+use crate::bytecode::property_access::{CachePropertyAbsence, GetByIdMode, get_by_id};
use crate::gc::capi::js_heap_region_base;
use crate::gc::class_id::ClassId;
use crate::interpreter::vm::Vm;
@@ -37,9 +35,9 @@ use crate::runtime::error::ErrorKind;
use crate::runtime::error_types::ErrorType;
use crate::runtime::number_object::NumberObject;
use crate::runtime::object::PropertyLookupPhase;
-use crate::runtime::object_prototype::{ObjectPrototype, builtin_tag};
use crate::runtime::property_key::PropertyKey;
use crate::runtime::proxy_object::ProxyObject;
+use crate::runtime::special_property_cache::{self, SpecialPropertyKey};
use crate::runtime::string_object::StringObject;
use crate::runtime::symbol::Symbol;
use crate::runtime::symbol_object::SymbolObject;
@@ -68,83 +66,6 @@ fn decode_cell_address(encoded: u64) -> usize {
address as usize
}
-/// The most objects on a prototype chain to_primitive_of_object_with_default_conversions() looks through.
-const MAX_DEFAULT_CONVERSION_PROTOTYPE_CHAIN_LENGTH: usize = 4;
-
-/// OPTIMIZATION: ToPrimitive of an object that inherits toString and valueOf from %Object.prototype%, without any
-/// @@toPrimitive or @@toStringTag on its prototype chain, is "[object Object]" for every preferred type:
-/// there is no exotic @@toPrimitive, valueOf returns the object itself, and toString is
-/// %Object.prototype.toString%. Returns nothing if the object is not such an object, or if its builtinTag
-/// is not "Object".
-fn to_primitive_of_object_with_default_conversions(vm: &Vm, object: &Object) -> Option<Gc<PrimitiveString>> {
- // NB: Only objects whose builtinTag is "Object" convert to the cached string, so the others, such as arrays, are left
- // to the generic path first. Proxies have no ordinary property lookup, so IsArray is whether the object is an
- // Array.
- if builtin_tag(object, object.is_array_exotic_object()) != "Object" {
- return None;
- }
-
- let realm = vm.current_realm()?;
- let object_prototype = realm.object_prototype();
-
- let to_primitive_key = PropertyKey::from(vm.well_known_symbols().to_primitive);
- let to_string_tag_key = PropertyKey::from(vm.well_known_symbols().to_string_tag);
-
- // Every object on the chain below %Object.prototype% looks these properties up in its own storage, and has none.
- let mut current = object.as_gc();
- let mut chain_length = 0;
- while current != object_prototype {
- chain_length += 1;
- if chain_length > MAX_DEFAULT_CONVERSION_PROTOTYPE_CHAIN_LENGTH || !current.has_ordinary_named_property_lookup()
- {
- return None;
- }
- let shape = current.shape();
- if shape.has_conversion_properties(vm) {
- return None;
- }
- current = shape.prototype()?;
- }
-
- // %Object.prototype% still has its own toString and valueOf, and no @@toPrimitive or @@toStringTag.
- let cache = |site| vm.static_property_lookup_cache(site);
- let to_string = get_own_property_without_side_effects(
- &object_prototype,
- &vm.names.toString,
- cache(StaticPropertyLookupCacheSite::ValueDefaultConversionsToString),
- );
- if !to_string.is_object()
- || to_string.as_object() != realm.intrinsics().object_prototype_to_string_function().upcast()
- {
- return None;
- }
- let value_of = get_own_property_without_side_effects(
- &object_prototype,
- &vm.names.valueOf,
- cache(StaticPropertyLookupCacheSite::ValueDefaultConversionsValueOf),
- );
- if !value_of.is_function() || !ObjectPrototype::is_value_of_function(vm, value_of.as_function()) {
- return None;
- }
- if !get_own_property_without_side_effects(
- &object_prototype,
- &to_primitive_key,
- cache(StaticPropertyLookupCacheSite::ValueDefaultConversionsToPrimitive),
- )
- .is_empty()
- || !get_own_property_without_side_effects(
- &object_prototype,
- &to_string_tag_key,
- cache(StaticPropertyLookupCacheSite::ValueDefaultConversionsToStringTag),
- )
- .is_empty()
- {
- return None;
- }
-
- Some(vm.cached_strings().object_Object)
-}
-
impl Value {
pub const fn from_bool(value: bool) -> Self {
if value { Self::TRUE } else { Self::FALSE }
@@ -492,15 +413,17 @@ impl Value {
fn to_primitive_slow_case(self, vm: &Vm, mut preferred_type: PreferredType) -> ThrowCompletionOr<Value> {
// 1. If input is an Object, then
if self.is_object() {
- if let Some(string) = to_primitive_of_object_with_default_conversions(vm, &self.as_object()) {
+ let object = self.as_object();
+ // OPTIMIZATION: The special property cache of the shape of the object may know what the steps below give.
+ if let Some(string) = special_property_cache::to_primitive_without_running_code(vm, &object, preferred_type)
+ {
return Ok(Value::from_string(string));
}
// a. Let exoticToPrim be ? GetMethod(input, @@toPrimitive).
- let exotic_to_primitive = self.get_method_with_cache(
+ let exotic_to_primitive = Self::finish_get_method(
vm,
- &PropertyKey::from(vm.well_known_symbols().to_primitive),
- vm.static_property_lookup_cache(StaticPropertyLookupCacheSite::ValueToPrimitive),
+ special_property_cache::get(vm, &object, SpecialPropertyKey::ToPrimitive)?,
)?;
// b. If exoticToPrim is not undefined, then
@@ -539,7 +462,7 @@ impl Value {
}
// d. Return ? OrdinaryToPrimitive(input, preferredType).
- return self.as_object().ordinary_to_primitive(vm, preferred_type);
+ return object.ordinary_to_primitive(vm, preferred_type);
}
// 2. Return input.
diff --git a/Libraries/LibJS/Rust/src/runtime/watchpoint_set.rs b/Libraries/LibJS/Rust/src/runtime/watchpoint_set.rs
new file mode 100644
index 00000000000..3b2f19b7452
--- /dev/null
+++ b/Libraries/LibJS/Rust/src/runtime/watchpoint_set.rs
@@ -0,0 +1,114 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Watchpoint sets: what the runtime and JIT code may rely on until it stops holding, when the set fires.
+
+use core::cell::{Cell, RefCell};
+
+use crate::gc::class::{GcCell, define_cell};
+use crate::gc::visitor::{Trace, Visitor};
+use crate::gc::weak::GcWeak;
+use crate::interpreter::vm::Vm;
+use crate::jit::dependencies::{CellId, Dependency};
+use crate::layout::cell::{CellHeader, Gc};
+pub use crate::layout::shape::WatchpointSet;
+use crate::runtime::special_property_cache::SpecialPropertyCache;
+
+/// A cache that relies on a watchpoint set, and forgets what it knows when the set fires.
+struct Watcher {
+ cache: GcWeak<SpecialPropertyCache>,
+ /// The generation of the cache when it started to rely on the set. Once the cache forgot what it knew, it relies
+ /// on the sets it watches anew, and the watchers of its earlier generations are stale.
+ generation: u32,
+}
+
+/// The fewest watchers a set prunes.
+const MIN_WATCHERS_TO_PRUNE: usize = 8;
+
+/// What a watchpoint set keeps besides whether it is valid: the caches that rely on it.
+pub struct WatchpointSetStorage {
+ watchers: RefCell<Vec<Watcher>>,
+ /// How many watchers the set has when it next prunes those that are stale.
+ prune_at: Cell<usize>,
+}
+
+impl Default for WatchpointSetStorage {
+ fn default() -> Self {
+ Self {
+ watchers: RefCell::new(Vec::new()),
+ prune_at: Cell::new(MIN_WATCHERS_TO_PRUNE),
+ }
+ }
+}
+
+define_cell!(WatchpointSet, Other);
+
+// SAFETY: A watchpoint set only holds weak references to the caches that watch it.
+unsafe impl Trace for WatchpointSet {
+ fn trace(&self, _: &mut Visitor) {}
+}
+
+impl WatchpointSet {
+ pub fn create(vm: &Vm) -> Gc<WatchpointSet> {
+ vm.heap().allocate(WatchpointSet {
+ header: CellHeader::for_class(Self::CLASS),
+ valid: Cell::new(true),
+ storage: WatchpointSetStorage::default(),
+ })
+ }
+
+ pub fn is_valid(&self) -> bool {
+ self.valid.get()
+ }
+
+ /// Has `cache` forget what it knows of its generation `generation` when the set fires.
+ pub(crate) fn add_watcher(&self, vm: &Vm, cache: Gc<SpecialPropertyCache>, generation: u32) {
+ assert!(self.is_valid());
+ let mut watchers = self.storage.watchers.borrow_mut();
+ if watchers
+ .last()
+ .is_some_and(|watcher| watcher.generation == generation && watcher.cache.get() == Some(cache))
+ {
+ return;
+ }
+ // NB: A set that never fires keeps the watchers of caches that died with their shapes, or that forgot what they
+ // knew. Pruning them each time the number of watchers doubled since it last pruned keeps them in check.
+ if watchers.len() >= self.storage.prune_at.get() {
+ watchers.retain(|watcher| {
+ watcher
+ .cache
+ .get()
+ .is_some_and(|cache| cache.generation() == watcher.generation)
+ });
+ self.storage
+ .prune_at
+ .set((watchers.len() * 2).max(MIN_WATCHERS_TO_PRUNE));
+ }
+ watchers.push(Watcher {
+ cache: GcWeak::new(vm.heap(), cache),
+ generation,
+ });
+ }
+
+ /// Notes that what the set stands for stopped holding, which has the caches that rely on it forget what they know,
+ /// and invalidates the JIT code that depends on it.
+ pub fn fire(&self, vm: &Vm) {
+ if !self.is_valid() {
+ return;
+ }
+ self.valid.set(false);
+ let watchers = core::mem::take(&mut *self.storage.watchers.borrow_mut());
+ for watcher in watchers {
+ if let Some(cache) = watcher.cache.get() {
+ cache.forget(watcher.generation);
+ }
+ }
+ crate::jit::dependencies::invalidate_dependents(
+ vm,
+ Dependency::WatchpointSetValid(CellId(core::ptr::from_ref(self) as u64)),
+ );
+ }
+}
diff --git a/Tests/LibJS/Runtime/special-property-cache.js b/Tests/LibJS/Runtime/special-property-cache.js
new file mode 100644
index 00000000000..e20af191c65
--- /dev/null
+++ b/Tests/LibJS/Runtime/special-property-cache.js
@@ -0,0 +1,228 @@
+// Conversions of objects to primitives remember what Get of toString, valueOf, @@toPrimitive and @@toStringTag gives
+// for the objects of a shape. These tests change those properties after conversions that remembered them.
+
+const convertOften = (object, count = 50) => {
+ let result;
+ for (let i = 0; i < count; ++i) result = `${object}`;
+ return result;
+};
+
+const withRestoredObjectPrototype = callback => {
+ const keys = ["toString", "valueOf", Symbol.toPrimitive, Symbol.toStringTag];
+ const descriptors = keys.map(key => Object.getOwnPropertyDescriptor(Object.prototype, key));
+ try {
+ callback();
+ } finally {
+ keys.forEach((key, index) => {
+ if (descriptors[index]) Object.defineProperty(Object.prototype, key, descriptors[index]);
+ else delete Object.prototype[key];
+ });
+ }
+};
+
+describe("replacing the values of properties of Object.prototype", () => {
+ test("toString", () => {
+ withRestoredObjectPrototype(() => {
+ const object = { a: 1 };
+ expect(convertOften(object)).toBe("[object Object]");
+ Object.prototype.toString = () => "replaced";
+ expect(`${object}`).toBe("replaced");
+ expect(String(object)).toBe("replaced");
+ expect([object, object].join()).toBe("replaced,replaced");
+ });
+ });
+
+ test("valueOf", () => {
+ withRestoredObjectPrototype(() => {
+ const object = { b: 1 };
+ expect(object + "").toBe("[object Object]");
+ expect(object + "").toBe("[object Object]");
+ Object.prototype.valueOf = () => 21;
+ expect(object * 2).toBe(42);
+ expect(object + "").toBe("21");
+ expect(`${object}`).toBe("[object Object]");
+ });
+ });
+
+ test("with assignments that property lookup caches make", () => {
+ withRestoredObjectPrototype(() => {
+ const object = { c: 1 };
+ const replacements = [() => "first", () => "second"];
+ const original = Object.prototype.toString;
+ const results = [];
+ for (let i = 0; i < 100; ++i) {
+ expect(convertOften(object, 2)).toBe(i === 0 ? "[object Object]" : "second");
+ Object.prototype.toString = replacements[0];
+ results.push(`${object}`);
+ Object.prototype.toString = replacements[1];
+ results.push(`${object}`);
+ }
+ Object.prototype.toString = original;
+ expect(`${object}`).toBe("[object Object]");
+ for (let i = 0; i < results.length; ++i) expect(results[i]).toBe(i % 2 === 0 ? "first" : "second");
+ });
+ });
+
+ test("with Object.assign", () => {
+ withRestoredObjectPrototype(() => {
+ const object = { d: 1 };
+ expect(convertOften(object)).toBe("[object Object]");
+ Object.assign(Object.prototype, { toString: () => "assigned" });
+ expect(`${object}`).toBe("assigned");
+ });
+ });
+
+ test("with Object.defineProperty", () => {
+ withRestoredObjectPrototype(() => {
+ const object = { e: 1 };
+ expect(convertOften(object)).toBe("[object Object]");
+ Object.defineProperty(Object.prototype, "toString", { value: () => "defined" });
+ expect(`${object}`).toBe("defined");
+ Object.defineProperty(Object.prototype, "toString", { get: () => () => "from getter" });
+ expect(`${object}`).toBe("from getter");
+ });
+ });
+});
+
+describe("adding properties to prototypes", () => {
+ test("@@toPrimitive on Object.prototype", () => {
+ withRestoredObjectPrototype(() => {
+ const object = { f: 1 };
+ expect(convertOften(object)).toBe("[object Object]");
+ Object.prototype[Symbol.toPrimitive] = hint => `primitive ${hint}`;
+ expect(`${object}`).toBe("primitive string");
+ expect(object + "").toBe("primitive default");
+ });
+ });
+
+ test("@@toStringTag on Object.prototype", () => {
+ withRestoredObjectPrototype(() => {
+ const object = { g: 1 };
+ expect(convertOften(object)).toBe("[object Object]");
+ expect(Object.prototype.toString.call(object)).toBe("[object Object]");
+ Object.prototype[Symbol.toStringTag] = "Tagged";
+ expect(`${object}`).toBe("[object Tagged]");
+ expect(Object.prototype.toString.call(object)).toBe("[object Tagged]");
+ });
+ });
+
+ test("toString on a prototype between the object and Object.prototype", () => {
+ class Base {}
+ class Derived extends Base {}
+ const object = new Derived();
+ expect(convertOften(object)).toBe("[object Object]");
+ Base.prototype.toString = () => "from Base";
+ expect(`${object}`).toBe("from Base");
+ Derived.prototype.toString = () => "from Derived";
+ expect(`${object}`).toBe("from Derived");
+ delete Derived.prototype.toString;
+ expect(`${object}`).toBe("from Base");
+ delete Base.prototype.toString;
+ expect(`${object}`).toBe("[object Object]");
+ });
+
+ test("changing the prototype of a prototype", () => {
+ const middle = {};
+ const object = Object.create(middle);
+ expect(convertOften(object)).toBe("[object Object]");
+ Object.setPrototypeOf(middle, { toString: () => "new chain" });
+ expect(`${object}`).toBe("new chain");
+ Object.setPrototypeOf(middle, null);
+ expect(() => `${object}`).toThrowWithMessage(TypeError, "Cannot convert object to string");
+ });
+
+ test("a prototype with many properties", () => {
+ const prototype = {};
+ for (let i = 0; i < 200; ++i) prototype[`property${i}`] = i;
+ const object = Object.create(prototype);
+ expect(convertOften(object)).toBe("[object Object]");
+ prototype.toString = () => "dictionary";
+ expect(`${object}`).toBe("dictionary");
+ prototype.toString = () => "dictionary again";
+ expect(`${object}`).toBe("dictionary again");
+ delete prototype.property5;
+ expect(`${object}`).toBe("dictionary again");
+ delete prototype.toString;
+ expect(`${object}`).toBe("[object Object]");
+ });
+});
+
+describe("objects of different kinds with the same prototype", () => {
+ test("errors and plain objects", () => {
+ const error = new Error();
+ const plain = Object.create(Error.prototype);
+ for (let i = 0; i < 10; ++i) {
+ expect(Object.prototype.toString.call(error)).toBe("[object Error]");
+ expect(Object.prototype.toString.call(plain)).toBe("[object Object]");
+ }
+ });
+
+ test("arrays and plain objects", () => {
+ const array = [];
+ const plain = Object.create(Array.prototype);
+ for (let i = 0; i < 10; ++i) {
+ expect(Object.prototype.toString.call(array)).toBe("[object Array]");
+ expect(Object.prototype.toString.call(plain)).toBe("[object Object]");
+ }
+ });
+
+ test("arguments objects and plain objects", () => {
+ function args() {
+ return arguments;
+ }
+ for (let i = 0; i < 10; ++i) {
+ expect(String(args())).toBe("[object Arguments]");
+ expect(String({})).toBe("[object Object]");
+ }
+ });
+
+ test("functions", () => {
+ const f = function () {};
+ for (let i = 0; i < 10; ++i) expect(Object.prototype.toString.call(f)).toBe("[object Function]");
+ });
+});
+
+test("own conversion properties", () => {
+ const objects = [];
+ for (let i = 0; i < 10; ++i) objects.push({ toString: () => `own ${i}` });
+ for (let i = 0; i < 10; ++i) expect(`${objects[i]}`).toBe(`own ${i}`);
+});
+
+test("toString that is not callable", () => {
+ const prototype = { toString: 42 };
+ const object = Object.create(prototype);
+ for (let i = 0; i < 10; ++i)
+ expect(() => `${object}`).toThrowWithMessage(TypeError, "Cannot convert object to string");
+ prototype.valueOf = () => 7;
+ expect(`${object}`).toBe("7");
+});
+
+test("primitive wrappers", () => {
+ for (let i = 0; i < 10; ++i) {
+ expect(Object.prototype.toString.call(1)).toBe("[object Number]");
+ expect(Object.prototype.toString.call("x")).toBe("[object String]");
+ expect(Object.prototype.toString.call(true)).toBe("[object Boolean]");
+ expect(Object.prototype.toString.call(Symbol())).toBe("[object Symbol]");
+ }
+});
+
+test("@@toStringTag getter that changes @@toStringTag", () => {
+ const prototype = {};
+ const first = Object.create(prototype);
+ const second = Object.create(prototype);
+ let calls = 0;
+ Object.defineProperty(prototype, Symbol.toStringTag, {
+ configurable: true,
+ get() {
+ if (calls++ === 0) {
+ Object.defineProperty(prototype, Symbol.toStringTag, { value: "X", configurable: true });
+ expect(Object.prototype.toString.call(second)).toBe("[object X]");
+ }
+ return "Y";
+ },
+ });
+ expect(Object.prototype.toString.call(first)).toBe("[object Y]");
+ expect(Object.prototype.toString.call(first)).toBe("[object X]");
+ expect(Object.prototype.toString.call(second)).toBe("[object X]");
+ expect(`${first}`).toBe("[object X]");
+});