Skip to content

Truly independent web browser

LibJS: Watch the RegExp properties that fast paths skip reading

Andreas Klingd9e7fb24d7d6
diff --git a/Libraries/LibJS/Rust/src/bytecode/executable.rs b/Libraries/LibJS/Rust/src/bytecode/executable.rs
index 36222914fea..9ac2bc35f8a 100644
--- a/Libraries/LibJS/Rust/src/bytecode/executable.rs
+++ b/Libraries/LibJS/Rust/src/bytecode/executable.rs
@@ -752,16 +752,6 @@ define_static_property_lookup_cache_sites! {
SetIterationIsUnobservableNextMethod,
RegExpIncrementLastIndexGetLastIndex,
RegExpIncrementLastIndexSetLastIndex,
- RegExpUnmodifiedInstanceExec,
- RegExpFlagsUnobservableFlags,
- RegExpFlagsUnobservableHasIndices,
- RegExpFlagsUnobservableGlobal,
- RegExpFlagsUnobservableIgnoreCase,
- RegExpFlagsUnobservableMultiline,
- RegExpFlagsUnobservableDotAll,
- RegExpFlagsUnobservableUnicode,
- RegExpFlagsUnobservableUnicodeSets,
- RegExpFlagsUnobservableSticky,
RegExpLastIndexUnobservableLastIndex,
RegExpBuiltinExecGetLastIndex,
RegExpBuiltinExecResetLastIndexPastEnd,
diff --git a/Libraries/LibJS/Rust/src/runtime/object.rs b/Libraries/LibJS/Rust/src/runtime/object.rs
index 800ad29d7e1..a5640ef0a30 100644
--- a/Libraries/LibJS/Rust/src/runtime/object.rs
+++ b/Libraries/LibJS/Rust/src/runtime/object.rs
@@ -3188,6 +3188,13 @@ impl Object {
if setter.is_some() {
accessor.set_setter(setter);
}
+ // NB: Changing the accessor in its slot changes the value of the property, as replacing it would.
+ let shape = self.shape();
+ if shape.has_watched_slots()
+ && let Some(metadata) = shape.lookup(property_key)
+ {
+ shape.note_slot_replacement(vm, metadata.offset);
+ }
} else {
let accessor = Accessor::create(vm, getter, setter, None);
self.define_direct_property(vm, property_key, Value::from_accessor(accessor), attributes);
diff --git a/Libraries/LibJS/Rust/src/runtime/realm.rs b/Libraries/LibJS/Rust/src/runtime/realm.rs
index 5087117af0f..cdaef99e99d 100644
--- a/Libraries/LibJS/Rust/src/runtime/realm.rs
+++ b/Libraries/LibJS/Rust/src/runtime/realm.rs
@@ -25,6 +25,7 @@ use crate::runtime::completion::ThrowCompletionOr;
use crate::runtime::global_object::{GlobalObject, set_default_global_bindings};
use crate::runtime::intrinsics::Intrinsics;
use crate::runtime::object::allocate_object;
+use crate::runtime::realm_watchpoints::WatchedCondition;
use crate::runtime::shape::Shape;
/// The parts of a realm the interpreter does not read.
@@ -33,6 +34,9 @@ pub struct RealmStorage {
/// The cell that an embedder written in Rust keeps its data of the realm in, next to [[HostDefined]], which an
/// embedder written in C++ sets.
embedder_data: ForeignCellSlot,
+ /// Whether %RegExp.prototype% and %RegExp% have the properties the fast paths of RegExp skip reading as the realm
+ /// made them (see `runtime::realm_watchpoints`).
+ pub(crate) regexp_primordial_properties: WatchedCondition,
}
define_cell!(Realm, Other);
@@ -46,6 +50,7 @@ unsafe impl Trace for Realm {
self.global_declarative_environment.trace(visitor);
self.host_defined.trace(visitor);
self.storage.embedder_data.trace(visitor);
+ self.storage.regexp_primordial_properties.trace(visitor);
self.array_iterator_next_watchpoint_set.trace(visitor);
self.array_iterator_return_watchpoint_set.trace(visitor);
}
diff --git a/Libraries/LibJS/Rust/src/runtime/realm_watchpoints.rs b/Libraries/LibJS/Rust/src/runtime/realm_watchpoints.rs
index 51e60b600c5..6b1deac62e6 100644
--- a/Libraries/LibJS/Rust/src/runtime/realm_watchpoints.rs
+++ b/Libraries/LibJS/Rust/src/runtime/realm_watchpoints.rs
@@ -13,15 +13,24 @@
//! %IteratorPrototype% and %Object.prototype% have no `return` property, and the first two keep their prototypes. It
//! depends on the set that fires when an object of that prototype chain changes (see
//! `Shape::prototype_chain_validity()`).
+//! - `regexp_primordial_properties`: %RegExp.prototype% and %RegExp% have the properties that the fast
+//! paths of RegExp skip reading as the realm made them (see `RegExpPrototype::primordial_properties_are_unchanged()`).
+//! It depends on the sets that fire when either object changes, and when the values of those properties change. The
+//! realm starts watching them when a fast path first asks, since it creates the RegExp intrinsics on demand.
//!
//! A change of an intrinsic fires the sets that depend on it, also one that leaves what they stand for in place, such
//! as a new property of %Object.prototype%. The next query of a fired set checks whether what it stands for still
//! holds, and if so, watches the intrinsics anew with a new set. Once it does not hold, the realm has no set anymore.
+use core::cell::Cell;
+
+use crate::gc::visitor::{Trace, Visitor};
use crate::interpreter::vm::Vm;
use crate::layout::cell::Gc;
use crate::layout::object::Object;
+use crate::runtime::property_key::PropertyKey;
use crate::runtime::realm::Realm;
+use crate::runtime::regexp_prototype::RegExpPrototype;
use crate::runtime::watchpoint_set::WatchpointSet;
/// Starts watching the intrinsics of a realm whose intrinsics were just created. Until then, changes of the watched
@@ -120,3 +129,87 @@ fn watch_array_iterator_return(vm: &Vm, realm: Gc<Realm>) -> Option<Gc<Watchpoin
prototype_chain_validity.add_dependent_set(vm, set);
Some(set)
}
+
+/// What a realm knows of a condition on its intrinsics that it watches from when a fast path first asks about it.
+#[derive(Default)]
+pub struct WatchedCondition {
+ /// The set that stays valid while the condition holds, since the realm last found it to hold.
+ set: Cell<Option<Gc<WatchpointSet>>>,
+ /// Whether the condition stopped holding, after which the realm does not watch it anymore.
+ stopped_holding: Cell<bool>,
+}
+
+// SAFETY: Visits the one cell a watched condition holds.
+unsafe impl Trace for WatchedCondition {
+ fn trace(&self, visitor: &mut Visitor) {
+ self.set.trace(visitor);
+ }
+}
+
+impl WatchedCondition {
+ /// Whether the condition holds. `watch` gives a new set that stays valid while it holds, if it holds.
+ #[inline]
+ fn holds(&self, vm: &Vm, realm: Gc<Realm>, watch: fn(&Vm, Gc<Realm>) -> Option<Gc<WatchpointSet>>) -> bool {
+ if self.set.get().is_some_and(|set| set.is_valid()) {
+ return true;
+ }
+ if self.stopped_holding.get() {
+ return false;
+ }
+ let set = watch(vm, realm);
+ self.set.set(set);
+ self.stopped_holding.set(set.is_none());
+ set.is_some()
+ }
+}
+
+/// A set that stays valid while `objects` keep their properties and prototypes, and the properties `slots` of them keep
+/// their values.
+fn watch_intrinsics(vm: &Vm, objects: &[Gc<Object>], slots: &[(Gc<Object>, PropertyKey)]) -> Option<Gc<WatchpointSet>> {
+ // NB: Prototype shapes belong to one object each, and have the watchpoint sets of their slots and prototype chains.
+ for object in objects {
+ object.convert_to_prototype_if_needed(vm);
+ }
+ let set = WatchpointSet::create(vm);
+ for object in objects {
+ let validity = object.shape().prototype_chain_validity()?;
+ if !validity.is_valid() {
+ return None;
+ }
+ validity.add_dependent_set(vm, set);
+ }
+ for (object, key) in slots {
+ let metadata = object.shape().lookup(key)?;
+ let replacement_watchpoint_set = object.shape().watch_slot_for_replacements(vm, metadata.offset)?;
+ replacement_watchpoint_set.add_dependent_set(vm, set);
+ }
+ Some(set)
+}
+
+/// Whether %RegExp.prototype% and %RegExp% of the realm have the properties that the fast paths of RegExp skip reading
+/// as the realm made them.
+pub fn regexp_primordial_properties_are_unchanged(vm: &Vm, realm: Gc<Realm>) -> bool {
+ realm
+ .storage
+ .regexp_primordial_properties
+ .holds(vm, realm, watch_regexp_primordial_properties)
+}
+
+/// The set that stays valid while %RegExp.prototype% and %RegExp% have the properties that the fast paths of RegExp skip
+/// reading as the realm made them, if they have.
+fn watch_regexp_primordial_properties(vm: &Vm, realm: Gc<Realm>) -> Option<Gc<WatchpointSet>> {
+ if !RegExpPrototype::primordial_properties_are_unchanged(vm, realm) {
+ return None;
+ }
+ let regexp_prototype = realm.intrinsics().regexp_prototype(vm);
+ let regexp_constructor: Gc<Object> = realm.intrinsics().regexp_constructor(vm).upcast();
+ let slots: Vec<_> = RegExpPrototype::primordial_property_keys(vm)
+ .map(|key| (regexp_prototype, key.clone()))
+ .into_iter()
+ .chain([
+ (regexp_prototype, PropertyKey::from(vm.well_known_symbols().match_)),
+ (regexp_constructor, PropertyKey::from(vm.well_known_symbols().species)),
+ ])
+ .collect();
+ watch_intrinsics(vm, &[regexp_prototype, regexp_constructor], &slots)
+}
diff --git a/Libraries/LibJS/Rust/src/runtime/regexp_prototype.rs b/Libraries/LibJS/Rust/src/runtime/regexp_prototype.rs
index 3155294b874..fcba198d39a 100644
--- a/Libraries/LibJS/Rust/src/runtime/regexp_prototype.rs
+++ b/Libraries/LibJS/Rust/src/runtime/regexp_prototype.rs
@@ -4,7 +4,7 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-use std::cell::{Cell, RefCell};
+use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use std::hash::{Hash, Hasher};
use std::rc::Rc;
@@ -27,13 +27,11 @@ use crate::runtime::abstract_operations::{
CaptureText, SubstitutionCaptures, append_substitution, call_function_object, checked_js_string_length_sum,
construct, get_substitution, length_of_array_like, species_constructor,
};
-use crate::runtime::accessor::Accessor;
use crate::runtime::array::Array;
use crate::runtime::completion::{Must, ThrowCompletionOr};
use crate::runtime::ecmascript_regex::{EcmaScriptRegex, MatchResult};
use crate::runtime::error::ErrorKind;
use crate::runtime::error_types::ErrorType;
-use crate::runtime::function_object::FunctionObject;
use crate::runtime::native_function::raw_native;
use crate::runtime::object::{MayInterfereWithIndexedPropertyAccess, ORDINARY_OBJECT_METHODS, define_object_class};
use crate::runtime::primitive_string::PrimitiveString;
@@ -41,6 +39,7 @@ use crate::runtime::property_attributes::{Attribute, DEFAULT_ATTRIBUTES, Propert
use crate::runtime::property_key::PropertyKey;
use crate::runtime::prototype_object::{this_object, typed_this_object};
use crate::runtime::realm::Realm;
+use crate::runtime::realm_watchpoints;
use crate::runtime::regexp_constructor::is_raw_native_function_running;
use crate::runtime::regexp_legacy_static_properties::{
invalidate_legacy_regexp_static_properties, update_legacy_regexp_static_properties_lazy,
@@ -51,7 +50,6 @@ use crate::runtime::regexp_object::{
REGEXP_FLAGS_WITH_CHARACTERS, RegExpFlags, RegExpObject, compile_flags_for, parse_regex_pattern,
};
use crate::runtime::regexp_string_iterator::RegExpStringIterator;
-use crate::runtime::shape::Shape;
use crate::runtime::string_prototype::code_point_at;
use crate::runtime::value::same_value;
use crate::utf16::{Utf16StringBuilder, Utf16View, concatenate};
@@ -69,13 +67,13 @@ fn cache(vm: &Vm, site: CacheSite) -> &PropertyLookupCache {
vm.static_property_lookup_cache(site)
}
-/// The getter of RegExp.prototype.flags, which reading_flags_is_unobservable() looks for.
+/// The getter of RegExp.prototype.flags, which primordial_properties_are_unchanged() looks for.
static FLAGS_GETTER: RawNativeFunctionPointer = raw_native!(RegExpPrototype::flags);
macro_rules! define_regexp_flag_getters {
- ($($flag:ident, $flag_name:ident, $property_name:ident, $getter_static:ident, $flags_cache:ident, $unobservable_cache:ident;)*) => {
+ ($($flag:ident, $flag_name:ident, $property_name:ident, $getter_static:ident, $flags_cache:ident;)*) => {
$(
- /// The getter of this flag, which reading_flags_is_unobservable() looks for.
+ /// The getter of this flag, which primordial_properties_are_unchanged() looks for.
static $getter_static: RawNativeFunctionPointer = raw_native!(RegExpPrototype::$flag_name);
)*
@@ -142,13 +140,7 @@ macro_rules! define_regexp_flag_getters {
fn every_flag_has_its_intrinsic_getter(vm: &Vm, regexp_prototype: &Object) -> bool {
$(
- if !has_intrinsic_getter(
- vm,
- regexp_prototype,
- &vm.names.$property_name,
- cache(vm, CacheSite::$unobservable_cache),
- $getter_static,
- ) {
+ if !has_intrinsic_getter(regexp_prototype, &vm.names.$property_name, vm, $getter_static) {
return false;
}
)*
@@ -175,14 +167,14 @@ fn flag_character(flag: RegExpFlags) -> u8 {
// 22.2.6.18 get RegExp.prototype.unicode, https://tc39.es/ecma262/#sec-get-regexp.prototype.unicode
// 22.2.6.19 get RegExp.prototype.unicodeSets, https://tc39.es/ecma262/#sec-get-regexp.prototype.unicodesets
define_regexp_flag_getters! {
- HAS_INDICES, has_indices, hasIndices, HAS_INDICES_GETTER, RegExpPrototypeFlagsHasIndices, RegExpFlagsUnobservableHasIndices;
- GLOBAL, global, global, GLOBAL_GETTER, RegExpPrototypeFlagsGlobal, RegExpFlagsUnobservableGlobal;
- IGNORE_CASE, ignore_case, ignoreCase, IGNORE_CASE_GETTER, RegExpPrototypeFlagsIgnoreCase, RegExpFlagsUnobservableIgnoreCase;
- MULTILINE, multiline, multiline, MULTILINE_GETTER, RegExpPrototypeFlagsMultiline, RegExpFlagsUnobservableMultiline;
- DOT_ALL, dot_all, dotAll, DOT_ALL_GETTER, RegExpPrototypeFlagsDotAll, RegExpFlagsUnobservableDotAll;
- UNICODE, unicode, unicode, UNICODE_GETTER, RegExpPrototypeFlagsUnicode, RegExpFlagsUnobservableUnicode;
- UNICODE_SETS, unicode_sets, unicodeSets, UNICODE_SETS_GETTER, RegExpPrototypeFlagsUnicodeSets, RegExpFlagsUnobservableUnicodeSets;
- STICKY, sticky, sticky, STICKY_GETTER, RegExpPrototypeFlagsSticky, RegExpFlagsUnobservableSticky;
+ HAS_INDICES, has_indices, hasIndices, HAS_INDICES_GETTER, RegExpPrototypeFlagsHasIndices;
+ GLOBAL, global, global, GLOBAL_GETTER, RegExpPrototypeFlagsGlobal;
+ IGNORE_CASE, ignore_case, ignoreCase, IGNORE_CASE_GETTER, RegExpPrototypeFlagsIgnoreCase;
+ MULTILINE, multiline, multiline, MULTILINE_GETTER, RegExpPrototypeFlagsMultiline;
+ DOT_ALL, dot_all, dotAll, DOT_ALL_GETTER, RegExpPrototypeFlagsDotAll;
+ UNICODE, unicode, unicode, UNICODE_GETTER, RegExpPrototypeFlagsUnicode;
+ UNICODE_SETS, unicode_sets, unicodeSets, UNICODE_SETS_GETTER, RegExpPrototypeFlagsUnicodeSets;
+ STICKY, sticky, sticky, STICKY_GETTER, RegExpPrototypeFlagsSticky;
}
/// %RegExp.prototype%.
@@ -190,19 +182,8 @@ define_regexp_flag_getters! {
#[derive(Trace)]
pub struct RegExpPrototype {
base: Object,
- // What reading_flags_is_unobservable() last found unchanged: the shape and dictionary generation of this prototype,
- // and the slot, accessor and getter of "flags" and of each flag. The cells are kept alive, so another accessor or
- // getter can never take one's place at the same address.
- flag_getters_shape: Cell<Option<Gc<Shape>>>,
- flag_getters_generation: Cell<u32>,
- flag_getter_offsets: [Cell<u32>; FLAG_GETTER_COUNT],
- flag_getter_accessors: [Cell<Option<Gc<Accessor>>>; FLAG_GETTER_COUNT],
- flag_getter_functions: [Cell<Option<Gc<FunctionObject>>>; FLAG_GETTER_COUNT],
}
-/// "flags" and the eight flags.
-const FLAG_GETTER_COUNT: usize = 9;
-
define_object_class!(RegExpPrototype, extends: [Object], methods: {
initialize: RegExpPrototype::initialize,
..ORDINARY_OBJECT_METHODS
@@ -803,18 +784,22 @@ pub fn advance_string_index(string: Utf16View<'_>, index: u64, unicode: bool) ->
index + code_point.code_unit_count as u64
}
+/// The value of the own property `name` of `object`, if it has one.
+fn own_property_value(object: &Object, name: &PropertyKey) -> Option<Value> {
+ let metadata = object.shape().lookup(name)?;
+ Some(object.get_direct(metadata.offset))
+}
+
+/// Whether `object` has an own accessor property `name` whose getter is `intrinsic_getter`.
fn has_intrinsic_getter(
- vm: &Vm,
- regexp_prototype: &Object,
+ object: &Object,
name: &PropertyKey,
- cache: &PropertyLookupCache,
+ vm: &Vm,
intrinsic_getter: RawNativeFunctionPointer,
) -> bool {
- let accessor = get_own_property_without_side_effects(regexp_prototype, name, cache);
- if !accessor.is_accessor() {
+ let Some(accessor) = own_property_value(object, name).filter(|value| value.is_accessor()) else {
return false;
- }
-
+ };
let Some(getter) = accessor.as_accessor().getter() else {
return false;
};
@@ -826,11 +811,6 @@ impl RegExpPrototype {
realm.create_object(
vm,
RegExpPrototype {
- flag_getters_shape: Cell::new(None),
- flag_getters_generation: Cell::new(0),
- flag_getter_offsets: Default::default(),
- flag_getter_accessors: Default::default(),
- flag_getter_functions: Default::default(),
base: Object::new_with_prototype(
vm,
Self::CLASS,
@@ -949,79 +929,58 @@ impl RegExpPrototype {
Self::define_flag_accessors(object, vm, realm);
}
- // The below predicates guard the fast paths the way other engines do: V8 BranchIfFastRegExp (builtins-regexp-gen.cc),
- // JSC RegExpObject::isSymbolReplaceFastAndNonObservable and its per-operation siblings (RegExpObjectInlines.h), and
- // SpiderMonkey IsOptimizableRegExpObject (RegExp.cpp) all compare the object's structure and consult a watchpoint,
- // protector cell, or fuse — never a property read. We have no such invalidation means, so we read the slots directly.
- //
- // RegExp.prototype carries enough properties that finding one by name is a binary search, and these run on every call.
- // So, they reach its slots through a cache keyed on its shape — just like the bytecode interpreter's property reads do.
- // And that cache can't go stale. Caching the lookup is safe because what's cached is the slot number, never the value:
- // Assigning RegExp.prototype.exec leaves the shape alone, so the cached slot is still right and the read sees the new
- // function — while adding, deleting, or redefining a property changes the shape, so the cache misses and looks again.
+ // The below predicates guard the fast paths the way other engines do: They check the object, and rely on a watchpoint
+ // set of the realm for the properties of %RegExp.prototype% and %RegExp% that the algorithms would read (see
+ // `realm_watchpoints::regexp_primordial_properties_are_unchanged()`).
+
+ // Whether %RegExp.prototype% and %RegExp% have the properties the realm made them with, of all that the fast paths
+ // below skip reading:
+ // - exec, the intrinsic of this realm. The intrinsic exec of another realm would run there, and update the legacy
+ // statics of that realm.
+ // - get RegExp.prototype.flags, which reads every flag off the receiver, and the getter of each flag.
+ // - @@match as a data property, which IsRegExp reads from the splitter that @@split constructs.
+ // - constructor and %RegExp%[@@species], which SpeciesConstructor(rx, %RegExp%) reads.
+ pub(crate) fn primordial_properties_are_unchanged(vm: &Vm, realm: Gc<Realm>) -> bool {
+ let regexp_prototype = realm.intrinsics().regexp_prototype(vm);
+ let regexp_constructor = realm.intrinsics().regexp_constructor(vm);
- // Whether this is a plain RegExp carrying this realm's intrinsic prototype, with nothing of its own to shadow what the
- // algorithm reads, and the intrinsic exec still on that prototype.
- fn is_unmodified_regexp_instance(vm: &Vm, realm: Gc<Realm>, regexp_object: &Object) -> bool {
- if !regexp_object.is::<RegExpObject>() {
+ let Some(exec_function) = own_property_value(&regexp_prototype, &vm.names.exec) else {
+ return false;
+ };
+ if !exec_function.is_function()
+ || exec_function.as_function().builtin() != Some(Builtin::RegExpPrototypeExec)
+ || exec_function.as_function().realm() != Some(realm)
+ {
return false;
}
- let regexp_prototype = realm.intrinsics().regexp_prototype(vm);
- if regexp_object.prototype() != Some(regexp_prototype) {
+ if !has_intrinsic_getter(&regexp_prototype, &vm.names.flags, vm, FLAGS_GETTER)
+ || !Self::every_flag_has_its_intrinsic_getter(vm, &regexp_prototype)
+ {
return false;
}
- // A RegExp is created with lastIndex as its one own property, and lastIndex can't be deleted — so a lone own
- // property is sufficient to confirm that nothing of the object's own shadows exec, a flag, constructor, or @@match.
- // One count confirms it for all of them at once — whereas asking by name would cost a slot lookup for each.
- // NB: An own exec shadows the prototype's, and it may belong to another realm — which the algorithm Calls, so that
- // it runs there and updates that realm's legacy statics, rather than running it here.
- if regexp_object.shape().property_count() != 1 {
+ let match_symbol = PropertyKey::from(vm.well_known_symbols().match_);
+ if own_property_value(&regexp_prototype, &match_symbol).is_none_or(|value| value.is_accessor()) {
return false;
}
- let exec_function = get_own_property_without_side_effects(
- &regexp_prototype,
- &vm.names.exec,
- cache(vm, CacheSite::RegExpUnmodifiedInstanceExec),
- );
- if !exec_function.is_function() || exec_function.as_function().builtin() != Some(Builtin::RegExpPrototypeExec) {
+ let Some(constructor) = own_property_value(&regexp_prototype, &vm.names.constructor) else {
+ return false;
+ };
+ if !constructor.is_object() || constructor.as_object() != regexp_constructor.upcast::<Object>() {
return false;
}
- // The intrinsic exec of another realm is still the builtin, and assigning it here would have the algorithm Call it.
- // So, it would run in that realm — and our legacy statics would never see the match.
- exec_function.as_function().realm() == Some(realm)
- }
-
- // get RegExp.prototype.flags reads every flag off the receiver, so an own property — data or accessor — changes the
- // string the algorithm derives global and fullUnicode from, and a replaced getter runs code of its own. Each of those
- // reads resolves to that flag's own accessor on the prototype, and redefining one of those leaves both flags and the
- // shape alone — so every one of them is asked for, too.
- // NB: Those are exactly the properties JSC installs its regExpPrimordialProperties watchpoints on (JSGlobalObject.cpp).
- // V8 reaches the same properties thru the prototype's map (PrototypeCheckAssembler in builtins-regexp-gen.cc) and
- // SpiderMonkey thru a realm fuse — either of which a redefinition invalidates on its own.
- fn reading_flags_is_unobservable(vm: &Vm, realm: Gc<Realm>) -> bool {
- let regexp_prototype = realm.intrinsics().regexp_prototype(vm);
-
- // OPTIMIZATION: Asking for every getter takes a lookup and a check of the getter's native function each, so
- // remember what the last check found, and only check that the slots still hold the same accessors
- // with the same getters.
- let typed_regexp_prototype = regexp_prototype.downcast::<RegExpPrototype>();
- if typed_regexp_prototype.is_some_and(|prototype| prototype.flag_getters_are_unchanged()) {
- return true;
- }
- let unobservable = Self::reading_flags_is_unobservable_uncached(vm, &regexp_prototype);
- if unobservable && let Some(typed_regexp_prototype) = typed_regexp_prototype {
- typed_regexp_prototype.remember_flag_getters(vm);
- }
- unobservable
+ regexp_constructor.has_intrinsic_symbol_species_getter(vm)
}
- fn flag_getter_names(vm: &Vm) -> [&PropertyKey; FLAG_GETTER_COUNT] {
+ /// The properties of %RegExp.prototype% whose values primordial_properties_are_unchanged() checks.
+ pub(crate) fn primordial_property_keys(vm: &Vm) -> [&PropertyKey; 11] {
let names = &vm.names;
[
+ &names.exec,
+ &names.constructor,
&names.flags,
&names.hasIndices,
&names.global,
@@ -1034,51 +993,26 @@ impl RegExpPrototype {
]
}
- fn flag_getters_are_unchanged(&self) -> bool {
- let shape = self.shape();
- if self.flag_getters_shape.get() != Some(shape)
- || self.flag_getters_generation.get() != shape.dictionary_generation()
- {
+ // Whether this is a plain RegExp carrying this realm's intrinsic prototype, with nothing of its own to shadow what the
+ // algorithm reads, and the properties of the prototype that the fast paths skip reading still as the realm made them.
+ fn is_unmodified_regexp_instance(vm: &Vm, realm: Gc<Realm>, regexp_object: &Object) -> bool {
+ if !regexp_object.is::<RegExpObject>() {
return false;
}
- (0..FLAG_GETTER_COUNT).all(|index| {
- let value = self.get_direct(self.flag_getter_offsets[index].get());
- value.is_accessor()
- && Some(value.as_accessor()) == self.flag_getter_accessors[index].get()
- && value.as_accessor().getter() == self.flag_getter_functions[index].get()
- })
- }
- fn remember_flag_getters(&self, vm: &Vm) {
- let shape = self.shape();
- for (index, name) in Self::flag_getter_names(vm).into_iter().enumerate() {
- let Some(metadata) = shape.lookup(name) else {
- return;
- };
- let value = self.get_direct(metadata.offset);
- if !value.is_accessor() {
- return;
- }
- self.flag_getter_offsets[index].set(metadata.offset);
- self.flag_getter_accessors[index].set(Some(value.as_accessor()));
- self.flag_getter_functions[index].set(value.as_accessor().getter());
+ let regexp_prototype = realm.intrinsics().regexp_prototype(vm);
+ if regexp_object.prototype() != Some(regexp_prototype) {
+ return false;
}
- self.flag_getters_shape.set(Some(shape));
- self.flag_getters_generation.set(shape.dictionary_generation());
- }
- fn reading_flags_is_unobservable_uncached(vm: &Vm, regexp_prototype: &Object) -> bool {
- if !has_intrinsic_getter(
- vm,
- regexp_prototype,
- &vm.names.flags,
- cache(vm, CacheSite::RegExpFlagsUnobservableFlags),
- FLAGS_GETTER,
- ) {
+ // A RegExp is created with lastIndex as its one own property, and lastIndex can't be deleted, so a lone own
+ // property is sufficient to confirm that nothing of the object's own shadows exec, a flag, constructor, or @@match.
+ // One count confirms it for all of them at once, whereas asking by name would cost a slot lookup for each.
+ if regexp_object.shape().property_count() != 1 {
return false;
}
- Self::every_flag_has_its_intrinsic_getter(vm, regexp_prototype)
+ realm_watchpoints::regexp_primordial_properties_are_unchanged(vm, realm)
}
// ToLength(Get(R, "lastIndex")) runs whatever valueOf the property holds, so the fast path needs a plain number there.
@@ -1106,7 +1040,6 @@ impl RegExpPrototype {
// it again to advance past an empty match.
fn replace_is_fast_and_non_observable(vm: &Vm, realm: Gc<Realm>, regexp_object: &Object) -> bool {
Self::is_unmodified_regexp_instance(vm, realm, regexp_object)
- && Self::reading_flags_is_unobservable(vm, realm)
&& Self::reading_last_index_is_unobservable(vm, regexp_object)
&& Self::writing_last_index_is_unobservable(vm, regexp_object)
}
@@ -1114,33 +1047,7 @@ impl RegExpPrototype {
// 22.2.6.14 RegExp.prototype [ @@split ] reads flags, resolves the species constructor, and constructs a splitter
// from it — and that construction runs IsRegExp(rx), which reads rx[@@match].
fn split_is_fast_and_non_observable(vm: &Vm, realm: Gc<Realm>, regexp_object: &Object) -> bool {
- if !Self::is_unmodified_regexp_instance(vm, realm, regexp_object) {
- return false;
- }
- if !Self::reading_flags_is_unobservable(vm, realm) {
- return false;
- }
-
- let regexp_prototype = realm.intrinsics().regexp_prototype(vm);
- let inherited_match = regexp_prototype.storage_get(vm, &PropertyKey::from(vm.well_known_symbols().match_));
- if inherited_match.is_none_or(|inherited_match| inherited_match.value.is_accessor()) {
- return false;
- }
-
- // SpeciesConstructor(rx, %RegExp%) reads rx.constructor and then that constructor's @@species, so both have to
- // still be the intrinsics for skipping the whole resolution to be unobservable.
- let regexp_constructor = realm.intrinsics().regexp_constructor(vm);
- let Some(inherited_constructor) = regexp_prototype.storage_get(vm, &vm.names.constructor) else {
- return false;
- };
- if !inherited_constructor.value.is_object() {
- return false;
- }
- if inherited_constructor.value.as_object() != regexp_constructor.upcast::<Object>() {
- return false;
- }
-
- regexp_constructor.has_intrinsic_symbol_species_getter(vm)
+ Self::is_unmodified_regexp_instance(vm, realm, regexp_object)
}
// 22.2.6.16 RegExp.prototype.test goes thru RegExpExec, which reads exec, and on into RegExpBuiltinExec, which coerces
diff --git a/Tests/LibJS/Runtime/builtins/RegExp/RegExp.prototype.primordial-properties.js b/Tests/LibJS/Runtime/builtins/RegExp/RegExp.prototype.primordial-properties.js
new file mode 100644
index 00000000000..9c8a88e1fba
--- /dev/null
+++ b/Tests/LibJS/Runtime/builtins/RegExp/RegExp.prototype.primordial-properties.js
@@ -0,0 +1,131 @@
+const originalExec = RegExp.prototype.exec;
+
+function runFastPaths() {
+ for (let i = 0; i < 10; ++i) {
+ expect(/b/.test("abc")).toBeTrue();
+ expect("abc".replace(/b/g, "x")).toBe("axc");
+ expect("a,b".split(/,/)).toEqual(["a", "b"]);
+ }
+}
+
+function withProperty(object, key, descriptor, callback) {
+ const original = Object.getOwnPropertyDescriptor(object, key);
+ Object.defineProperty(object, key, descriptor);
+ try {
+ callback();
+ } finally {
+ Object.defineProperty(object, key, original);
+ }
+}
+
+test("a replaced exec is called after the fast paths ran", () => {
+ runFastPaths();
+ let calls = 0;
+ RegExp.prototype.exec = function (string) {
+ ++calls;
+ return originalExec.call(this, string);
+ };
+ try {
+ expect(/b/.test("abc")).toBeTrue();
+ expect("abc".replace(/b/, "x")).toBe("axc");
+ expect(calls).toBe(2);
+ } finally {
+ RegExp.prototype.exec = originalExec;
+ }
+});
+
+test("a replaced flag getter is called after the fast paths ran", () => {
+ runFastPaths();
+ let calls = 0;
+ withProperty(
+ RegExp.prototype,
+ "hasIndices",
+ {
+ get() {
+ ++calls;
+ return false;
+ },
+ configurable: true,
+ },
+ () => {
+ expect("abab".replace(/b/, "x")).toBe("axab");
+ expect(calls).toBe(1);
+ }
+ );
+});
+
+test("a replaced constructor is used by split after the fast paths ran", () => {
+ runFastPaths();
+ let calls = 0;
+ function Splitter(pattern, flags) {
+ ++calls;
+ return new RegExp(pattern, flags);
+ }
+ Splitter[Symbol.species] = Splitter;
+ withProperty(RegExp.prototype, "constructor", { value: Splitter, configurable: true, writable: true }, () => {
+ expect("a,b".split(/,/)).toEqual(["a", "b"]);
+ expect(calls).toBe(1);
+ });
+});
+
+test("a replaced @@species getter is used by split after the fast paths ran", () => {
+ runFastPaths();
+ let calls = 0;
+ withProperty(
+ RegExp,
+ Symbol.species,
+ {
+ get() {
+ ++calls;
+ return RegExp;
+ },
+ configurable: true,
+ },
+ () => {
+ expect("a,b".split(/,/)).toEqual(["a", "b"]);
+ expect(calls).toBe(1);
+ }
+ );
+});
+
+test("an accessor @@match is read by split after the fast paths ran", () => {
+ runFastPaths();
+ let calls = 0;
+ const originalMatch = RegExp.prototype[Symbol.match];
+ withProperty(
+ RegExp.prototype,
+ Symbol.match,
+ {
+ get() {
+ ++calls;
+ return originalMatch;
+ },
+ configurable: true,
+ },
+ () => {
+ expect("a,b".split(/,/)).toEqual(["a", "b"]);
+ expect(calls).toBeGreaterThan(0);
+ }
+ );
+});
+
+test("a replaced exec is called after unrelated properties changed", () => {
+ runFastPaths();
+ for (const object of [RegExp.prototype, RegExp, Object.prototype]) {
+ object.unrelated = 1;
+ runFastPaths();
+ delete object.unrelated;
+ runFastPaths();
+ }
+ let calls = 0;
+ RegExp.prototype.exec = function (string) {
+ ++calls;
+ return originalExec.call(this, string);
+ };
+ try {
+ expect(/b/.test("abc")).toBeTrue();
+ expect(calls).toBe(1);
+ } finally {
+ RegExp.prototype.exec = originalExec;
+ }
+});
diff --git a/Tests/LibJS/Runtime/builtins/RegExp/RegExp.prototype.symbol-match-getter.js b/Tests/LibJS/Runtime/builtins/RegExp/RegExp.prototype.symbol-match-getter.js
new file mode 100644
index 00000000000..b851c420127
--- /dev/null
+++ b/Tests/LibJS/Runtime/builtins/RegExp/RegExp.prototype.symbol-match-getter.js
@@ -0,0 +1,14 @@
+test("an @@match getter is called by split after @@match became non-writable", () => {
+ for (let i = 0; i < 10; ++i) expect("a,b".split(/,/)).toEqual(["a", "b"]);
+ Object.defineProperty(RegExp.prototype, Symbol.match, { writable: false });
+ for (let i = 0; i < 10; ++i) expect("a,b".split(/,/)).toEqual(["a", "b"]);
+ let calls = 0;
+ Object.defineProperty(RegExp.prototype, Symbol.match, {
+ get() {
+ ++calls;
+ return true;
+ },
+ });
+ expect("a,b".split(/,/)).toEqual(["a", "b"]);
+ expect(calls).toBeGreaterThan(0);
+});