Skip to content

Truly independent web browser

Meta: Generate JSON conversions for Rust dictionaries

Shannon Boothba3dfe752217
diff --git a/Libraries/LibJS/Rust/src/api.rs b/Libraries/LibJS/Rust/src/api.rs
index 7965146d299..bb21f27d2db 100644
--- a/Libraries/LibJS/Rust/src/api.rs
+++ b/Libraries/LibJS/Rust/src/api.rs
@@ -68,6 +68,7 @@ pub use crate::runtime::iterator::{
IteratorHint, IteratorRecord, create_iterator_result_object, get_iterator, get_iterator_from_method_impl,
iterator_complete, iterator_next, iterator_step_value, iterator_to_list, iterator_value,
};
+pub use crate::runtime::json_object::JSONObject;
pub use crate::runtime::map::Map;
pub use crate::runtime::map_iterator::MapIterator;
pub use crate::runtime::module::Module;
@@ -96,6 +97,6 @@ pub use crate::runtime::typed_array::{
typed_array_byte_length, typed_array_length,
};
pub use crate::runtime::value::{number_to_string, same_value};
-pub use crate::utf16::{Utf16Display, to_well_formed};
+pub use crate::utf16::{Utf16Display, Utf16View, to_well_formed};
/// Derives Trace for a type of the embedder, which marks the type `#[gc(crate = libjs_rust)]`.
pub use libjs_runtime_macros::Trace;
diff --git a/Libraries/LibWeb/Bindings/NewGlobalObject.cpp b/Libraries/LibWeb/Bindings/NewGlobalObject.cpp
index 833c6db2b61..8c4c1131380 100644
--- a/Libraries/LibWeb/Bindings/NewGlobalObject.cpp
+++ b/Libraries/LibWeb/Bindings/NewGlobalObject.cpp
@@ -4,6 +4,7 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
+#include <LibJS/HostClassBuilder.h>
#include <LibJS/Runtime/JSONObject.h>
#include <LibWeb/Bindings/NewGlobalObject.h>
#include <LibWeb/HTML/StructuredSerialize.h>
@@ -18,6 +19,14 @@ JS::Completion throw_copy_of_error_in_current_realm(JS::VM& vm, JS::Value error)
return JS::throw_completion(TRY(WebIDL::throw_dom_exception_if_needed(vm, realm, [&] { return HTML::structured_deserialize(vm, serialized_error, realm); })));
}
+extern "C" JSCompletion web_bindings_throw_copy_of_error_in_current_realm(JSVM*, JSValue);
+
+JSCompletion web_bindings_throw_copy_of_error_in_current_realm(JSVM* vm, JSValue error)
+{
+ return JS::HostABI::completion_to_abi(JS::ThrowCompletionOr<JS::Value> {
+ throw_copy_of_error_in_current_realm(JS::HostABI::vm_from_abi(vm), JS::HostABI::value_from_abi(error)) });
+}
+
JS::ThrowCompletionOr<Utf16String> serialize_to_json_in_a_new_global_object(JS::VM& vm, Function<JS::Value(JS::Realm&)> const& create_value)
{
auto json = TRY(run_in_a_new_global_object<Optional<Utf16String>>(vm, [&](JS::Realm& realm) {
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/mod.rs
index 654c0478f94..5e5ef84dfe1 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/mod.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/mod.rs
@@ -30,6 +30,7 @@ pub(crate) mod global_object;
pub(crate) mod interface;
pub(crate) mod iterable;
pub(crate) mod maplike;
+pub(crate) mod new_global_object;
pub(crate) mod promise;
pub(crate) mod realm_data;
pub(crate) mod services;
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/new_global_object.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/new_global_object.rs
new file mode 100644
index 00000000000..1e31691270e
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/new_global_object.rs
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use core::ffi::c_void;
+
+use ak::Utf16String;
+use libjs_rust::api::{ErrorKind, Gc, JSONObject, Must, RawNativeFunctionResult, Realm, ThrowCompletionOr, Value, Vm};
+
+unsafe extern "C" {
+ fn web_bindings_throw_copy_of_error_in_current_realm(vm: *const c_void, error: u64) -> RawNativeFunctionResult;
+}
+
+pub(crate) fn run_in_a_new_global_object<T>(
+ vm: &Vm,
+ steps: impl FnOnce(Gc<Realm>) -> ThrowCompletionOr<T>,
+) -> ThrowCompletionOr<T> {
+ let execution_context = Realm::initialize_host_defined_realm(vm, None, None).must();
+ let realm = vm.current_realm().expect("the new execution context has a realm");
+ let result = steps(realm);
+ assert_eq!(vm.pop_execution_context(), execution_context.as_non_null());
+
+ // Recreate any thrown error in the caller's realm before it reaches script.
+ result.map_err(|error| {
+ // SAFETY: The VM and error are live.
+ unsafe {
+ web_bindings_throw_copy_of_error_in_current_realm(core::ptr::from_ref(vm).cast(), error.value().to_raw())
+ }
+ .into_completion()
+ .expect_err("throwing a copy of the error returns a throw completion")
+ })
+}
+
+pub(crate) fn serialize_to_json_in_a_new_global_object(
+ vm: &Vm,
+ create_value: impl FnOnce(Gc<Realm>) -> ThrowCompletionOr<Value>,
+) -> ThrowCompletionOr<Utf16String> {
+ let json = run_in_a_new_global_object(vm, |realm| {
+ JSONObject::stringify_impl(vm, create_value(realm)?, Value::UNDEFINED, Value::UNDEFINED)
+ })?;
+ let Some(json) = json else {
+ return vm.throw_completion_with_message(
+ ErrorKind::TypeError,
+ "Result of stringifying value must not be undefined".into(),
+ );
+ };
+ Ok(json)
+}
diff --git a/Meta/Generators/libweb_bindings/json_conversions.py b/Meta/Generators/libweb_bindings/json_conversions.py
index a888b42e0ae..e7b26c7bec6 100644
--- a/Meta/Generators/libweb_bindings/json_conversions.py
+++ b/Meta/Generators/libweb_bindings/json_conversions.py
@@ -4,8 +4,12 @@
from typing import TextIO
+from Generators.libweb_bindings.context import GenerationContext
from Generators.libweb_bindings.cpp_types import converter_function_name
from Generators.libweb_bindings.includes import GeneratedIncludes
+from Generators.libweb_bindings.rust_types import UnsupportedByRustBindings
+from Generators.libweb_bindings.rust_types import dictionary_holds_sequence_of_cells
+from Generators.libweb_bindings.rust_types import rust_dictionary_path
from Generators.libweb_bindings.to_js_value import to_value_function_name
from Utils.utils import make_name_acceptable_cpp
from Utils.utils import title_case_to_snake_case
@@ -63,3 +67,35 @@ def write_dictionary_json_conversions(out: TextIO, dictionary: Dictionary, inclu
"""
)
+
+
+def write_rust_dictionary_json_conversions(out: TextIO, context: GenerationContext, dictionary: Dictionary) -> None:
+ from_json = "GenerateFromJSON" in dictionary.extended_attributes
+ to_json = "GenerateToJSON" in dictionary.extended_attributes
+ if not from_json and not to_json:
+ return
+ if to_json and "GenerateToValue" not in dictionary.extended_attributes:
+ raise UnsupportedByRustBindings(
+ f"Dictionary '{dictionary.name}' has [GenerateToJSON] but not [GenerateToValue]"
+ )
+ if dictionary_holds_sequence_of_cells(dictionary, context):
+ raise UnsupportedByRustBindings(
+ f"The Rust bindings do not convert the dictionary {dictionary.name} to or from JSON"
+ )
+
+ out.write(f"\n impl {rust_dictionary_path(dictionary, context)} {{\n")
+ if from_json:
+ out.write(
+ """ pub(crate) fn from_json(vm: &Vm, json: Utf16View<'_>) -> ThrowCompletionOr<Self> {
+ run_in_a_new_global_object(vm, |_| Self::from_js(vm, JSONObject::parse_json(vm, json, None)?))
+ }
+"""
+ )
+ if to_json:
+ out.write(
+ """ pub(crate) fn to_json(self, vm: &Vm) -> ThrowCompletionOr<Utf16String> {
+ serialize_to_json_in_a_new_global_object(vm, |realm| self.to_js(&CallContext::new(vm, realm)))
+ }
+"""
+ )
+ out.write(" }\n")
diff --git a/Meta/Generators/libweb_bindings/rust_bindings.py b/Meta/Generators/libweb_bindings/rust_bindings.py
index 08cc33247d8..fb914259b40 100644
--- a/Meta/Generators/libweb_bindings/rust_bindings.py
+++ b/Meta/Generators/libweb_bindings/rust_bindings.py
@@ -26,6 +26,7 @@ from typing import Tuple
from Generators.libweb_bindings.context import GenerationContext
from Generators.libweb_bindings.includes import GeneratedIncludes
+from Generators.libweb_bindings.json_conversions import write_rust_dictionary_json_conversions
from Generators.libweb_bindings.operations import idl_type_is_json_type
from Generators.libweb_bindings.operations import operation_is_default_to_json
from Generators.libweb_bindings.rust_members import RustAttribute
@@ -2476,7 +2477,7 @@ pub(crate) mod definitions {
use ak::Utf16String;
use libjs_rust::api::{
- ErrorKind, ErrorType, Gc, MarkedVec, Object, PropertyKey, ThrowCompletionOr, TypedArrayBase, TypedArrayKind,
+ ErrorKind, ErrorType, Gc, JSONObject, MarkedVec, Object, PropertyKey, ThrowCompletionOr, TypedArrayBase, TypedArrayKind, Utf16View,
Value, Vm, is_host_instance_of,
};
@@ -2497,6 +2498,7 @@ pub(crate) mod definitions {
Interface, Ref, create_dictionary_object, implementation_if, implementation_of, set_dictionary_member,
to_interface,
};
+ use crate::bindings::new_global_object::{run_in_a_new_global_object, serialize_to_json_in_a_new_global_object};
"""
)
for name, directions in usage.rust_dictionaries.items():
@@ -2509,6 +2511,7 @@ pub(crate) mod definitions {
write_dictionary_from_js(out, context, dictionary)
if directions.to_js:
write_dictionary_to_js(out, context, dictionary)
+ write_rust_dictionary_json_conversions(out, context, dictionary)
for name, directions in usage.rust_enumerations.items():
enumeration = context.enumerations[name]
if directions.from_js:
diff --git a/Meta/Generators/libweb_bindings/rust_usage.py b/Meta/Generators/libweb_bindings/rust_usage.py
index f6b78361136..e6a08afddb9 100644
--- a/Meta/Generators/libweb_bindings/rust_usage.py
+++ b/Meta/Generators/libweb_bindings/rust_usage.py
@@ -180,6 +180,8 @@ class DefinitionUsage:
dictionary = self.context.dictionaries.get(idl_type.name)
if dictionary is None:
return
+ from_js = from_js or "GenerateFromJSON" in dictionary.extended_attributes
+ to_js = to_js or "GenerateToValue" in dictionary.extended_attributes
directions = self.rust_dictionaries.setdefault(dictionary.name, ConversionDirections())
if (directions.from_js or not from_js) and (directions.to_js or not to_js):
return