Truly independent web browser
LibJS: Keep keys that are never symbols in a NonSymbolPropertyKey
Shannon Boothe6c00bccf318
diff --git a/Libraries/LibJS/Rust/src/interpreter/slow_paths/property_access.rs b/Libraries/LibJS/Rust/src/interpreter/slow_paths/property_access.rsindex c3a5b5a2533..a15c7ee2c34 100644--- a/Libraries/LibJS/Rust/src/interpreter/slow_paths/property_access.rs+++ b/Libraries/LibJS/Rust/src/interpreter/slow_paths/property_access.rs@@ -43,7 +43,7 @@ use crate::runtime::error_types::ErrorType;use crate::runtime::object::{IndexedStorageKind, Object};use crate::runtime::private_environment::{PrivateEnvironment, PrivateName};use crate::runtime::property_attributes::{Attribute, DEFAULT_ATTRIBUTES, PropertyAttributes};-use crate::runtime::property_key::PropertyKey;+use crate::runtime::property_key::{NonSymbolPropertyKey, PropertyKey};use crate::runtime::reference::Reference;use crate::runtime::typed_array::{Kind, is_valid_integer_index, typed_array_of_object};@@ -1000,11 +1000,10 @@ impl<'vm> SeenObjects<'vm> {}}-/// The keys a for-in has already decided about while it walks up the prototype chain. The keys are never symbols,-/// so a plain set may hold them.+/// The keys a for-in has already decided about while it walks up the prototype chain.struct ShadowingState {- seen_non_enumerable_properties: HashSet<PropertyKey>,- seen_properties: Option<HashSet<PropertyKey>>,+ seen_non_enumerable_properties: HashSet<NonSymbolPropertyKey>,+ seen_properties: Option<HashSet<NonSymbolPropertyKey>>,}impl ShadowingState {@@ -1015,14 +1014,21 @@ impl ShadowingState {}}- fn ensure_seen_properties(&mut self, properties: &MarkedVec<'_, PropertyKey>) -> &mut HashSet<PropertyKey> {+ fn key(property_key: &PropertyKey) -> NonSymbolPropertyKey {+ NonSymbolPropertyKey::new(property_key.clone()).expect("a for-in visits no symbols")+ }++ fn ensure_seen_properties(+ &mut self,+ properties: &MarkedVec<'_, PropertyKey>,+ ) -> &mut HashSet<NonSymbolPropertyKey> {self.seen_properties.get_or_insert_with(|| {// Prototype shadowing ignores enumerability, so once we start looking// above the receiver we need an explicit visited set for names we have// already decided to expose from lower objects.let mut seen_properties = HashSet::with_capacity(properties.len());for index in 0..properties.len() {- seen_properties.insert(properties.get(index).expect("the index is in bounds"));+ seen_properties.insert(Self::key(&properties.get(index).expect("the index is in bounds")));}seen_properties})@@ -1037,7 +1043,7 @@ impl ShadowingState {in_prototype_chain: bool,) {if !enumerable {- self.seen_non_enumerable_properties.insert(property_key.clone());+ self.seen_non_enumerable_properties.insert(Self::key(property_key));}if in_prototype_chain && enumerable {if self.seen_non_enumerable_properties.contains(property_key) {@@ -1051,7 +1057,7 @@ impl ShadowingState {properties.push(property_key.clone());}if let Some(seen_properties) = &mut self.seen_properties {- seen_properties.insert(property_key.clone());+ seen_properties.insert(Self::key(property_key));}}}@@ -1145,7 +1151,9 @@ fn try_get_fast_property_name_iterator_data(// table, but it still shadows enumerable `length` properties higher up the// prototype chain during for-in.if current.has_magical_length_property() {- shadowing.seen_non_enumerable_properties.insert(vm.names.length.clone());+ shadowing+ .seen_non_enumerable_properties+ .insert(ShadowingState::key(&vm.names.length));}currentdiff --git a/Libraries/LibJS/Rust/src/runtime/abstract_operations.rs b/Libraries/LibJS/Rust/src/runtime/abstract_operations.rsindex f16bce5f84c..41ae8235d39 100644--- a/Libraries/LibJS/Rust/src/runtime/abstract_operations.rs+++ b/Libraries/LibJS/Rust/src/runtime/abstract_operations.rs@@ -58,7 +58,7 @@ use crate::runtime::private_environment::PrivateEnvironment;use crate::runtime::promise_capability::{new_promise_capability, try_or_reject};use crate::runtime::property_attributes::PropertyAttributes;use crate::runtime::property_descriptor::PropertyDescriptor;-use crate::runtime::property_key::PropertyKey;+use crate::runtime::property_key::{NonSymbolPropertyKey, PropertyKey};use crate::runtime::proxy_object::ProxyObject;use crate::runtime::realm::Realm;use crate::runtime::shared_function_instance_data::{@@ -378,7 +378,7 @@ pub struct PropertyKeyGroups<'vm> {keys: MarkedVec<'vm, PropertyKey>,elements: Vec<MarkedVec<'vm, Value>>,/// Symbol keys are only kept in the marked list of keys and looked up one by one.- index_of_string_or_number_key: HashMap<PropertyKey, usize>,+ index_of_string_or_number_key: HashMap<NonSymbolPropertyKey, usize>,}impl<'vm> PropertyKeyGroups<'vm> {@@ -444,8 +444,8 @@ impl<'vm> KeyedGroups<'vm> for PropertyKeyGroups<'vm> {new_elements.push(value);// 3. Append group as the last element of groups.- if !key.is_symbol() {- self.index_of_string_or_number_key.insert(key.clone(), self.keys.len());+ if let Some(key) = NonSymbolPropertyKey::new(key.clone()) {+ self.index_of_string_or_number_key.insert(key, self.keys.len());}self.keys.push(key);self.elements.push(new_elements);diff --git a/Libraries/LibJS/Rust/src/runtime/json_object.rs b/Libraries/LibJS/Rust/src/runtime/json_object.rsindex c8957b26f21..e6165269e08 100644--- a/Libraries/LibJS/Rust/src/runtime/json_object.rs+++ b/Libraries/LibJS/Rust/src/runtime/json_object.rs@@ -37,7 +37,7 @@ use crate::runtime::object::{};use crate::runtime::primitive_string::PrimitiveString;use crate::runtime::property_attributes::{Attribute, DEFAULT_ATTRIBUTES, PropertyAttributes};-use crate::runtime::property_key::PropertyKey;+use crate::runtime::property_key::{NonSymbolPropertyKey, PropertyKey};use crate::runtime::raw_json_object::RawJSONObject;use crate::runtime::realm::Realm;use crate::runtime::shape::Shape;@@ -183,7 +183,7 @@ impl Drop for StringifyObjectStack<'_> {}struct StringifyCachedProperty {- property: PropertyKey,+ property: NonSymbolPropertyKey,offset: u32,serialized_key: Utf16String,}@@ -198,7 +198,10 @@ impl StringifyShapeInfo {fn new(shape: Gc<Shape>) -> Self {let mut properties = Vec::with_capacity(shape.property_count() as usize);shape.for_each_property_in_insertion_order(|property_key, metadata| {- if property_key.is_symbol() || !metadata.attributes.is_enumerable() {+ let Some(property) = NonSymbolPropertyKey::new(property_key.clone()) else {+ return ControlFlow::Continue(());+ };+ if !metadata.attributes.is_enumerable() {return ControlFlow::Continue(());}assert!(property_key.is_string());@@ -208,7 +211,7 @@ impl StringifyShapeInfo {key_builder.append_ascii(":");properties.push(StringifyCachedProperty {- property: property_key.clone(),+ property,offset: metadata.offset,serialized_key: key_builder.to_utf16_string(),});@@ -450,7 +453,7 @@ impl JSONTextBytes<'_> {/// An entry of the cache of the property keys of a text, by their raw bytes.struct JSONPropertyKeyCacheEntry {raw_key: Vec<u8>,- key: Option<PropertyKey>,+ key: Option<NonSymbolPropertyKey>,}struct JSONPropertyKeyCache {@@ -783,21 +786,21 @@ fn json_property_key(if let Some(key) = &entry.key&& entry.raw_key == raw_key{- return Ok(key.clone());+ return Ok(PropertyKey::from(key.clone()));}let key = if raw_key.contains(&b'\\') {let Some(unescaped_key) = unescape_json_string(raw_key) else {return json_malformed(vm);};- PropertyKey::from(&unescaped_key)+ NonSymbolPropertyKey::from(&unescaped_key)} else {- PropertyKey::from(Utf16FlyString::from_utf8(state.text.unescaped_text(raw_key)))+ NonSymbolPropertyKey::from(Utf16FlyString::from_utf8(state.text.unescaped_text(raw_key)))};let entry = state.property_keys.entry_for(raw_key);entry.raw_key = raw_key.to_vec();entry.key = Some(key.clone());- Ok(key)+ Ok(PropertyKey::from(key))}fn parse_simdjson_array<'a, T: SimdjsonValueOrDocument<'a>>(diff --git a/Libraries/LibJS/Rust/src/runtime/json_text_parser.rs b/Libraries/LibJS/Rust/src/runtime/json_text_parser.rsindex ff422e4bea4..776fc7f660d 100644--- a/Libraries/LibJS/Rust/src/runtime/json_text_parser.rs+++ b/Libraries/LibJS/Rust/src/runtime/json_text_parser.rs@@ -26,7 +26,7 @@ use crate::runtime::error_types::ErrorType;use crate::runtime::object::MAX_TRANSITIONS_BEFORE_CONVERTING_TO_DICTIONARY;use crate::runtime::primitive_string::PrimitiveString;use crate::runtime::property_attributes::DEFAULT_ATTRIBUTES;-use crate::runtime::property_key::PropertyKey;+use crate::runtime::property_key::{NonSymbolPropertyKey, PropertyKey};use crate::runtime::realm::Realm;use crate::runtime::shape::Shape;use crate::utf16::{Utf16View, is_json_special_code_unit, json_special_code_unit_lanes};@@ -123,7 +123,7 @@ struct JsonParseTables {keys: KeyCache,shapes: ShapeCache,/// The keys of the properties of the objects that are being parsed.- property_keys: Vec<PropertyKey>,+ property_keys: Vec<NonSymbolPropertyKey>,}/// Parses `text` as a JSON text, and returns the value of its parse node as ParseJSON does, or throws a SyntaxError@@ -170,7 +170,7 @@ fn are_code_units_of<C: CodeUnit>(units: &[C], key: &PropertyKey) -> bool {/// Property keys by their code units, in a small table indexed by a hash of them.struct KeyCache {- entries: Box<[Option<PropertyKey>; KeyCache::ENTRY_COUNT]>,+ entries: Box<[Option<NonSymbolPropertyKey>; KeyCache::ENTRY_COUNT]>,}impl Default for KeyCache {@@ -199,14 +199,14 @@ impl KeyCache {(hash ^ (hash >> 15)) as usize % Self::ENTRY_COUNT}- fn key<C: CodeUnit>(&mut self, units: &[C]) -> PropertyKey {+ fn key<C: CodeUnit>(&mut self, units: &[C]) -> NonSymbolPropertyKey {let entry = &mut self.entries[Self::slot(units)];if let Some(key) = entry&& are_code_units_of(units, key){return key.clone();}- let key = PropertyKey::from(C::make_fly_string(units));+ let key = NonSymbolPropertyKey::from(C::make_fly_string(units));// NB: Array indices are not kept, since they are numbers rather than strings.if key.is_string() {*entry = Some(key.clone());@@ -222,7 +222,7 @@ struct ShapeCache {}struct ShapeCacheEntry {- keys: Box<[PropertyKey]>,+ keys: Box<[NonSymbolPropertyKey]>,shape: GcWeak<Shape>,}@@ -237,7 +237,7 @@ impl Default for ShapeCache {impl ShapeCache {const ENTRY_COUNT: usize = 16;- fn slot(keys: &[PropertyKey]) -> usize {+ fn slot(keys: &[NonSymbolPropertyKey]) -> usize {let mut hasher = KeysHasher(keys.len() as u64);keys.hash(&mut hasher);hasher.finish() as usize % Self::ENTRY_COUNT@@ -246,7 +246,7 @@ impl ShapeCache {/// The shape of an object of `realm` with the properties `keys` in that order, as data properties with the default/// attributes, made by put transitions from the shape of new objects. Returns None for keys that an object/// cannot have in that shape: a key that repeats, an array index, or more keys than a shape takes.- fn shape_for_keys(&mut self, vm: &Vm, realm: Gc<Realm>, keys: &[PropertyKey]) -> Option<Gc<Shape>> {+ fn shape_for_keys(&mut self, vm: &Vm, realm: Gc<Realm>, keys: &[NonSymbolPropertyKey]) -> Option<Gc<Shape>> {if keys.len() > MAX_TRANSITIONS_BEFORE_CONVERTING_TO_DICTIONARY as usize {return None;}@@ -423,7 +423,7 @@ impl<'a, 'vm, C: CodeUnit> Parser<'a, 'vm, C> {}let token = self.scan_string()?;let key = if token.has_escapes {- PropertyKey::from(&self.make_string(&token)?)+ NonSymbolPropertyKey::from(&self.make_string(&token)?)} else {self.tables.keys.key(&self.units[token.start..token.end])};diff --git a/Libraries/LibJS/Rust/src/runtime/object.rs b/Libraries/LibJS/Rust/src/runtime/object.rsindex 0dd32a8cbba..ffb79a8df46 100644--- a/Libraries/LibJS/Rust/src/runtime/object.rs+++ b/Libraries/LibJS/Rust/src/runtime/object.rs@@ -52,7 +52,7 @@ use crate::runtime::primitive_string::PrimitiveString;use crate::runtime::private_environment::PrivateName;use crate::runtime::property_attributes::{DEFAULT_ATTRIBUTES, PropertyAttributes};use crate::runtime::property_descriptor::{PropertyDescriptor, to_property_descriptor};-use crate::runtime::property_key::PropertyKey;+use crate::runtime::property_key::{NonSymbolPropertyKey, PropertyKey};use crate::runtime::realm::Realm;use crate::runtime::shape::{AssignCopy, Shape};use crate::runtime::special_property_cache::{self, SpecialPropertyKey};@@ -2971,7 +2971,6 @@ impl Object {mut callback: impl FnMut(&PropertyKey, bool) -> ThrowCompletionOr<()>,) -> ThrowCompletionOr<()> {if self.eligible_for_own_property_enumeration_fast_path() {- // NB: These are index and string keys, which hold no cells, so they need no rooting.let mut keys = Vec::with_capacity(self.indexed_real_size()+ self.shape().property_count() as usize@@ -2987,18 +2986,21 @@ impl Object {{enumerable = result.attributes.is_enumerable();}- keys.push((PropertyKey::from(index), enumerable));+ keys.push((NonSymbolPropertyKey::from(index), enumerable));}}if self.has_magical_length_property() {- keys.push((vm.names.length.clone(), false));+ keys.push((NonSymbolPropertyKey::from(vm.names.length.as_string().clone()), false));}self.shape().for_each_property_in_insertion_order(|property_key, metadata| {if property_key.is_string() {- keys.push((property_key.clone(), metadata.attributes.is_enumerable()));+ keys.push((+ NonSymbolPropertyKey::from(property_key.as_string().clone()),+ metadata.attributes.is_enumerable(),+ ));}ControlFlow::Continue(())});diff --git a/Libraries/LibJS/Rust/src/runtime/property_key.rs b/Libraries/LibJS/Rust/src/runtime/property_key.rsindex 7db7cfdfae0..3ac313077a4 100644--- a/Libraries/LibJS/Rust/src/runtime/property_key.rs+++ b/Libraries/LibJS/Rust/src/runtime/property_key.rs@@ -4,9 +4,11 @@* SPDX-License-Identifier: BSD-2-Clause*/+use core::borrow::Borrow;use core::fmt;use core::hash::{Hash, Hasher};use core::num::NonZeroUsize;+use core::ops::Deref;use core::ptr::NonNull;use ak::{Utf16FlyString, Utf16String};@@ -261,6 +263,60 @@ unsafe impl Trace for PropertyKey {}}+/// A key that is a string or a number, never a symbol, so that it holds no cell and needs no rooting.+#[derive(Clone, PartialEq, Eq, Hash)]+pub struct NonSymbolPropertyKey(PropertyKey);++impl NonSymbolPropertyKey {+ pub fn new(key: PropertyKey) -> Option<Self> {+ (!key.is_symbol()).then_some(Self(key))+ }+}++impl Deref for NonSymbolPropertyKey {+ type Target = PropertyKey;++ fn deref(&self) -> &PropertyKey {+ &self.0+ }+}++impl Borrow<PropertyKey> for NonSymbolPropertyKey {+ fn borrow(&self) -> &PropertyKey {+ &self.0+ }+}++impl From<NonSymbolPropertyKey> for PropertyKey {+ fn from(key: NonSymbolPropertyKey) -> Self {+ key.0+ }+}++impl Utf16Display for NonSymbolPropertyKey {+ fn fmt_utf16(&self, builder: &mut Utf16StringBuilder) {+ self.0.fmt_utf16(builder);+ }+}++impl From<u32> for NonSymbolPropertyKey {+ fn from(index: u32) -> Self {+ Self(PropertyKey::from(index))+ }+}++impl From<Utf16FlyString> for NonSymbolPropertyKey {+ fn from(string: Utf16FlyString) -> Self {+ Self(PropertyKey::from(string))+ }+}++impl From<&Utf16String> for NonSymbolPropertyKey {+ fn from(string: &Utf16String) -> Self {+ Self(PropertyKey::from(string))+ }+}+/// Formats a key the way AK formats a JS::PropertyKey.impl Utf16Display for PropertyKey {fn fmt_utf16(&self, builder: &mut Utf16StringBuilder) {diff --git a/Libraries/LibJS/Rust/src/runtime/proxy_object.rs b/Libraries/LibJS/Rust/src/runtime/proxy_object.rsindex 63fdb20990b..d38c15f722b 100644--- a/Libraries/LibJS/Rust/src/runtime/proxy_object.rs+++ b/Libraries/LibJS/Rust/src/runtime/proxy_object.rs@@ -32,7 +32,7 @@ use crate::runtime::object::{PropertyLookupPhase, StackFrameInfo,};use crate::runtime::property_descriptor::{PropertyDescriptor, from_property_descriptor, to_property_descriptor};-use crate::runtime::property_key::PropertyKey;+use crate::runtime::property_key::{NonSymbolPropertyKey, PropertyKey};use crate::runtime::realm::Realm;use crate::runtime::value::same_value;@@ -134,7 +134,7 @@ impl Object {/// the list the trap result is collected into keeps them alive.#[derive(Default)]struct UniquePropertyKeys {- string_and_number_keys: HashSet<PropertyKey>,+ string_and_number_keys: HashSet<NonSymbolPropertyKey>,symbol_addresses: HashSet<usize>,}@@ -143,7 +143,8 @@ impl UniquePropertyKeys {if property_key.is_symbol() {self.symbol_addresses.insert(property_key.as_symbol().as_ptr().addr());} else {- self.string_and_number_keys.insert(property_key);+ self.string_and_number_keys+ .insert(NonSymbolPropertyKey::new(property_key).expect("the key is not a symbol"));}}diff --git a/Libraries/LibJS/Rust/src/runtime/shape.rs b/Libraries/LibJS/Rust/src/runtime/shape.rsindex efb47fcbabb..a063008496a 100644--- a/Libraries/LibJS/Rust/src/runtime/shape.rs+++ b/Libraries/LibJS/Rust/src/runtime/shape.rs@@ -27,7 +27,7 @@ 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::property_key::{NonSymbolPropertyKey, PropertyKey};use crate::runtime::realm::Realm;use crate::runtime::special_property_cache::SpecialPropertyCache;use crate::runtime::watchpoint_set::WatchpointSet;@@ -848,7 +848,10 @@ impl Shape {let mut property_keys = Vec::with_capacity(self.property_count() as usize);self.for_each_property_in_insertion_order(|property_key, metadata| {if property_key.is_string() {- property_keys.push((property_key.clone(), metadata.attributes.is_enumerable()));+ property_keys.push((+ NonSymbolPropertyKey::from(property_key.as_string().clone()),+ metadata.attributes.is_enumerable(),+ ));}ControlFlow::Continue(())});diff --git a/Libraries/LibJS/Rust/src/runtime/temporal/calendar.rs b/Libraries/LibJS/Rust/src/runtime/temporal/calendar.rsindex 6d55bcec7d7..37b596afd5f 100644--- a/Libraries/LibJS/Rust/src/runtime/temporal/calendar.rs+++ b/Libraries/LibJS/Rust/src/runtime/temporal/calendar.rs@@ -17,7 +17,7 @@ use crate::layout::value::Value;use crate::runtime::completion::{Must, ThrowCompletionOr};use crate::runtime::error::ErrorKind;use crate::runtime::error_types::ErrorType;-use crate::runtime::property_key::PropertyKey;+use crate::runtime::property_key::NonSymbolPropertyKey;use crate::runtime::temporal::abstract_operations::{DateType, Overflow, ShowCalendar, Unit, ascii_view, epoch_days_to_epoch_ms, iso_date_to_epoch_days,parse_temporal_calendar_string, to_integer_with_truncation, to_offset_string, to_positive_integer_with_truncation,@@ -236,7 +236,7 @@ pub struct BalancedDate {struct CalendarFieldData {key: CalendarField,- property: PropertyKey,+ property: NonSymbolPropertyKey,conversion: CalendarFieldConversion,}@@ -261,7 +261,7 @@ fn calendar_field_data(vm: &Vm, field: CalendarField) -> CalendarFieldData {};CalendarFieldData {key: field,- property: property.clone(),+ property: NonSymbolPropertyKey::from(property.as_string().clone()),conversion,}}