Skip to content

Truly independent web browser

LibJS: Look toJSON up through the special property cache of shapes

Andreas Kling9e8c57ba88c4
diff --git a/Libraries/LibJS/Rust/src/runtime/json_object.rs b/Libraries/LibJS/Rust/src/runtime/json_object.rs
index e14daa3d01c..cee72d8010f 100644
--- a/Libraries/LibJS/Rust/src/runtime/json_object.rs
+++ b/Libraries/LibJS/Rust/src/runtime/json_object.rs
@@ -41,10 +41,10 @@ use crate::runtime::property_key::PropertyKey;
use crate::runtime::raw_json_object::RawJSONObject;
use crate::runtime::realm::Realm;
use crate::runtime::shape::Shape;
+use crate::runtime::special_property_cache::{self, SpecialPropertyKey};
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};
@@ -192,13 +192,10 @@ struct StringifyCachedProperty {
struct StringifyShapeInfo {
/// The properties it serializes: their keys as JSON strings followed by a colon, and where their values are.
properties: Vec<StringifyCachedProperty>,
- /// The validity of the shape of the prototype of the objects when neither they nor their prototypes had a "toJSON"
- /// property, which stops being valid when a prototype changes its properties.
- to_json_absence: Option<GcWeak<WatchpointSet>>,
}
impl StringifyShapeInfo {
- fn new(vm: &Vm, shape: Gc<Shape>) -> Self {
+ 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() {
@@ -217,41 +214,7 @@ impl StringifyShapeInfo {
});
ControlFlow::Continue(())
});
- Self {
- properties,
- to_json_absence: Self::to_json_absence(vm, shape),
- }
- }
-
- fn to_json_absence(vm: &Vm, shape: Gc<Shape>) -> Option<GcWeak<WatchpointSet>> {
- let to_json = &vm.names.toJSON;
- if shape.lookup(to_json).is_some() {
- return None;
- }
- let first_prototype = shape.prototype()?;
- let validity = first_prototype.shape().prototype_chain_validity()?;
- if !validity.is_valid() {
- return None;
- }
- let object_prototype = vm.current_realm().map(|realm| realm.object_prototype());
- let mut prototype = Some(first_prototype);
- while let Some(current) = prototype {
- // NB: %Object.prototype% only has an exotic [[SetPrototypeOf]].
- let is_ordinary = Some(current) == object_prototype || current.has_ordinary_named_property_lookup();
- if !is_ordinary || current.has_intrinsic_accessors() || current.shape().lookup(to_json).is_some() {
- return None;
- }
- prototype = current.shape().prototype();
- }
- Some(GcWeak::new(vm.heap(), validity))
- }
-
- /// Whether Get of "toJSON" on the objects gives undefined without running any code.
- fn has_no_to_json(&self) -> bool {
- self.to_json_absence
- .as_ref()
- .and_then(GcWeak::get)
- .is_some_and(|validity| validity.is_valid())
+ Self { properties }
}
}
@@ -303,7 +266,7 @@ impl JsonStringifyCache {
{
return entry.info.clone();
}
- let info = Rc::new(StringifyShapeInfo::new(vm, shape));
+ let info = Rc::new(StringifyShapeInfo::new(shape));
self.entries.borrow_mut()[slot] = Some(StringifyShapeCacheEntry {
shape: GcWeak::new(vm.heap(), shape),
info: info.clone(),
@@ -1262,25 +1225,31 @@ impl JSONObject {
}
}
- // OPTIMIZATION: What is known of the shape of an object without other properties tells whether it has a toJSON
- // to look up, and what to serialize of it when nothing runs before it is serialized.
+ // OPTIMIZATION: The special property cache of the shape of an object without other properties may know that it
+ // has no toJSON to call, and then what is known of the shape tells what to serialize of it when
+ // nothing runs before it is serialized.
let mut shape_info = None;
- if value.is_object() && state.replacer_function.is_none() && can_use_direct_property_access(&value.as_object())
+ if value.is_object()
+ && state.replacer_function.is_none()
+ && can_use_direct_property_access(&value.as_object())
+ && special_property_cache::known(&value.as_object(), SpecialPropertyKey::ToJson)
+ .is_some_and(|to_json| to_json.is_undefined())
{
- let info = vm.json_stringify_cache().info(vm, value.as_object().shape());
- if info.has_no_to_json() {
- shape_info = Some(info);
- }
+ shape_info = Some(vm.json_stringify_cache().info(vm, value.as_object().shape()));
}
// 2. If Type(value) is Object or BigInt, then
if (value.is_object() || value.is_bigint()) && shape_info.is_none() {
// a. Let toJSON be ? GetV(value, "toJSON").
- let to_json = value.get_with_cache(
- vm,
- &vm.names.toJSON,
- vm.static_property_lookup_cache(StaticPropertyLookupCacheSite::JSONSerializeToJSON),
- )?;
+ let to_json = if value.is_object() {
+ special_property_cache::get(vm, &value.as_object(), SpecialPropertyKey::ToJson)?
+ } else {
+ value.get_with_cache(
+ vm,
+ &vm.names.toJSON,
+ vm.static_property_lookup_cache(StaticPropertyLookupCacheSite::JSONSerializeToJSON),
+ )?
+ };
// b. If IsCallable(toJSON) is true, then
if to_json.is_function() {
diff --git a/Libraries/LibJS/Rust/src/runtime/special_property_cache.rs b/Libraries/LibJS/Rust/src/runtime/special_property_cache.rs
index 980f9e00684..f489ec3c5bb 100644
--- a/Libraries/LibJS/Rust/src/runtime/special_property_cache.rs
+++ b/Libraries/LibJS/Rust/src/runtime/special_property_cache.rs
@@ -4,8 +4,8 @@
* 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 special property cache of a shape: what Get of the properties that conversions of objects to primitives and
+//! JSON.stringify 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
@@ -42,9 +42,10 @@ pub enum SpecialPropertyKey {
ToString,
ValueOf,
ToStringTag,
+ ToJson,
}
-const SPECIAL_PROPERTY_KEY_COUNT: usize = 4;
+const SPECIAL_PROPERTY_KEY_COUNT: usize = 5;
impl SpecialPropertyKey {
fn property_key(self, vm: &Vm) -> PropertyKey {
@@ -53,6 +54,7 @@ impl SpecialPropertyKey {
Self::ToString => vm.names.toString.clone(),
Self::ValueOf => vm.names.valueOf.clone(),
Self::ToStringTag => PropertyKey::from(vm.well_known_symbols().to_string_tag),
+ Self::ToJson => vm.names.toJSON.clone(),
}
}
@@ -62,6 +64,7 @@ impl SpecialPropertyKey {
Self::ToString => StaticPropertyLookupCacheSite::ObjectOrdinaryToPrimitiveToString,
Self::ValueOf => StaticPropertyLookupCacheSite::ObjectOrdinaryToPrimitiveValueOf,
Self::ToStringTag => StaticPropertyLookupCacheSite::ObjectPrototypeToStringToStringTag,
+ Self::ToJson => StaticPropertyLookupCacheSite::JSONSerializeToJSON,
}
}
}
@@ -218,19 +221,23 @@ pub fn note_object_to_string(object: &Object, to_string_tag: Value, string: Gc<P
// 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
+ && known(object, SpecialPropertyKey::ToStringTag) == Some(to_string_tag)
{
cache.object_to_string.set(Some(string));
}
}
+/// What Get(object, key) gives, if the cache knows.
+#[inline]
+pub fn known(object: &Object, key: SpecialPropertyKey) -> Option<Value> {
+ let value = cache_of(object)?.values[key as usize].get();
+ (!value.is_empty()).then_some(value)
+}
+
/// 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);
- }
+ if let Some(value) = known(object, key) {
+ return Ok(value);
}
let property_key = key.property_key(vm);
let value = object.get_with_cache(
diff --git a/Tests/LibJS/Runtime/special-property-cache.js b/Tests/LibJS/Runtime/special-property-cache.js
index e20af191c65..33b7b78a0c7 100644
--- a/Tests/LibJS/Runtime/special-property-cache.js
+++ b/Tests/LibJS/Runtime/special-property-cache.js
@@ -206,6 +206,53 @@ test("primitive wrappers", () => {
}
});
+describe("toJSON in JSON.stringify", () => {
+ test("added to Object.prototype", () => {
+ const object = { h: 1 };
+ try {
+ for (let i = 0; i < 10; ++i) expect(JSON.stringify(object)).toBe('{"h":1}');
+ Object.prototype.toJSON = () => "added";
+ expect(JSON.stringify(object)).toBe('"added"');
+ expect(JSON.stringify([object, { i: 2 }])).toBe('"added"');
+ } finally {
+ delete Object.prototype.toJSON;
+ }
+ expect(JSON.stringify(object)).toBe('{"h":1}');
+ });
+
+ test("replaced on a prototype", () => {
+ class Point {
+ constructor(x) {
+ this.x = x;
+ }
+ toJSON() {
+ return `point ${this.x}`;
+ }
+ }
+ const points = [new Point(1), new Point(2)];
+ for (let i = 0; i < 10; ++i) expect(JSON.stringify(points)).toBe('["point 1","point 2"]');
+ Point.prototype.toJSON = function () {
+ return this.x * 10;
+ };
+ expect(JSON.stringify(points)).toBe("[10,20]");
+ delete Point.prototype.toJSON;
+ expect(JSON.stringify(points)).toBe('[{"x":1},{"x":2}]');
+ });
+
+ test("Date.prototype.toJSON replaced", () => {
+ const original = Date.prototype.toJSON;
+ const date = new Date(0);
+ try {
+ for (let i = 0; i < 10; ++i) expect(JSON.stringify(date)).toBe('"1970-01-01T00:00:00.000Z"');
+ Date.prototype.toJSON = () => "replaced";
+ expect(JSON.stringify(date)).toBe('"replaced"');
+ } finally {
+ Date.prototype.toJSON = original;
+ }
+ expect(JSON.stringify(date)).toBe('"1970-01-01T00:00:00.000Z"');
+ });
+});
+
test("@@toStringTag getter that changes @@toStringTag", () => {
const prototype = {};
const first = Object.create(prototype);