Truly independent web browser
Meta: Let Rust interfaces take dictionaries that C++ converts
Shannon Boothffeddc2c14ba
diff --git a/Libraries/LibWeb/Bindings/CppDictionary.h b/Libraries/LibWeb/Bindings/CppDictionary.hnew file mode 100644index 00000000000..f45eefa0e6c--- /dev/null+++ b/Libraries/LibWeb/Bindings/CppDictionary.h@@ -0,0 +1,42 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#pragma once++#include <LibGC/Cell.h>+#include <LibGC/CellAllocator.h>++namespace Web::Bindings {++// A dictionary that the C++ bindings converted for an interface implemented in Rust, which hands it to the C++ code+// that uses it. Bindings/Rust/src/bindings/conversions.rs holds it as a CppDictionary.+template<typename Dictionary>+class CppDictionary final : public GC::Cell {+ GC_CELL(CppDictionary, GC::Cell);+ GC_DECLARE_ALLOCATOR(CppDictionary);++public:+ explicit CppDictionary(Dictionary dictionary)+ : m_dictionary(move(dictionary))+ {+ }++ Dictionary const& dictionary() const { return m_dictionary; }++private:+ virtual void visit_edges(Visitor& visitor) override+ {+ Base::visit_edges(visitor);+ m_dictionary.visit_edges(visitor);+ }++ Dictionary m_dictionary;+};++template<typename Dictionary>+GC_DEFINE_ALLOCATOR(CppDictionary<Dictionary>);++}diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rsindex b83155094bb..f845e7f3a66 100644--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs@@ -7,6 +7,7 @@//! Conversions between JS values and the Rust types of IDL values,//! https://webidl.spec.whatwg.org/#es-type-mapping+use core::ffi::c_void;use core::mem::MaybeUninit;use core::ops::Range;use std::borrow::Cow;@@ -14,14 +15,15 @@ use std::borrow::Cow;use ak::{Utf16String, Utf16StringUnits, convert_valid_utf16_to_utf8, utf8_length_from_valid_utf16};use libjs_rust::api::{Array, ArrayBuffer, ArrayBufferOrder, ArrayBufferShared, DataView, ErrorKind, ErrorType, FunctionObject, Gc,- IntegrityLevel, MarkedVec, Must, Object, PrimitiveString, PropertyKey, ThrowCompletionOr, Trace, TypedArrayBase,- TypedArrayKind, Value, Vm, create_typed_array_on_buffer, get_iterator_from_method_impl, get_view_byte_length,- is_typed_array_out_of_bounds, is_view_out_of_bounds, iterator_step_value,+ IntegrityLevel, MarkedVec, Must, Object, PrimitiveString, PropertyKey, RawNativeFunctionResult, ThrowCompletionOr,+ Trace, TypedArrayBase, TypedArrayKind, Value, Vm, create_typed_array_on_buffer, get_iterator_from_method_impl,+ get_view_byte_length, is_typed_array_out_of_bounds, is_view_out_of_bounds, iterator_step_value,make_data_view_with_buffer_witness_record, make_typed_array_with_buffer_witness_record, to_well_formed,typed_array_byte_length,};use crate::ak_format::ak_formatted;+use crate::bindings::cpp_cell::CppCell;use crate::bindings::interface::{Interface, Ref, create_dictionary_object, wrap};use crate::bindings::promise::WebIdlPromise;use crate::bindings::services::web_bindings_object_implements_interface;@@ -1284,6 +1286,38 @@ pub(crate) enum DOMStringOrDOMStringSequence {Sequence(Vec<Utf16String>),}+/// A dictionary that the C++ bindings converted, which only LibWeb's C++ code reads: a Web::Bindings::CppDictionary+/// that an implementation hands to a service of LibWeb.+#[derive(Clone, Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct CppDictionary(CppCell);++impl CppDictionary {+ pub(crate) fn as_ptr(&self) -> *mut c_void {+ self.0.as_ptr()+ }+}++/// https://webidl.spec.whatwg.org/#js-dictionary+pub(crate) fn to_cpp_dictionary(+ vm: &Vm,+ value: Value,+ converter: unsafe extern "C" fn(*mut c_void, u64, *mut *mut c_void) -> RawNativeFunctionResult,+) -> ThrowCompletionOr<CppDictionary> {+ let mut dictionary = core::ptr::null_mut();+ // SAFETY: The converter takes the live VM and the value, and writes a live cell to `dictionary` unless it throws.+ unsafe {+ converter(+ core::ptr::from_ref(vm).cast_mut().cast(),+ value.to_raw(),+ &raw mut dictionary,+ )+ }+ .into_completion()?;+ // SAFETY: The converter wrote a live cell.+ Ok(CppDictionary(unsafe { CppCell::from_raw(dictionary) }))+}+/// An object of an interface that LibWeb implements in C++, as its wrapper. Only the C++ code knows the object/// behind the wrapper, so an implementation hands the wrapper to a service of LibWeb to have something done with it.#[derive(Clone, Copy, Trace)]diff --git a/Meta/Generators/generate_libweb_bindings.py b/Meta/Generators/generate_libweb_bindings.pyindex 06909099ff8..d1cae6e5710 100644--- a/Meta/Generators/generate_libweb_bindings.py+++ b/Meta/Generators/generate_libweb_bindings.py@@ -149,6 +149,8 @@ def write_idl_implementation(out: TextIO, module: Module, context: GenerationConfor dictionary in usage.cpp_dictionaries(module):write_dictionary_conversion(body, dictionary, includes, context)+ if dictionary.name in usage.cpp_dictionaries_named_by_rust:+ rust_bindings.write_cpp_dictionary_converter(body, includes, dictionary)write_dictionary_to_javascript_value_conversion(body, dictionary, includes, context)write_dictionary_json_conversions(body, dictionary, includes)diff --git a/Meta/Generators/libweb_bindings/rust_bindings.py b/Meta/Generators/libweb_bindings/rust_bindings.pyindex e9b8860e8dd..66a44cfd06e 100644--- a/Meta/Generators/libweb_bindings/rust_bindings.py+++ b/Meta/Generators/libweb_bindings/rust_bindings.py@@ -25,6 +25,7 @@ from typing import TextIOfrom typing import Tuplefrom Generators.libweb_bindings.context import GenerationContext+from Generators.libweb_bindings.cpp_types import converter_function_namefrom Generators.libweb_bindings.includes import GeneratedIncludesfrom Generators.libweb_bindings.json_conversions import write_rust_dictionary_json_conversionsfrom Generators.libweb_bindings.operations import idl_type_is_json_type@@ -57,6 +58,7 @@ from Generators.libweb_bindings.rust_to_js_value import write_union_to_jsfrom Generators.libweb_bindings.rust_types import CPP_PARENT_INTERFACESfrom Generators.libweb_bindings.rust_types import UnsupportedByRustBindingsfrom Generators.libweb_bindings.rust_types import cpp_ancestor+from Generators.libweb_bindings.rust_types import cpp_dictionary_converter_symbolfrom Generators.libweb_bindings.rust_types import cpp_interface_name_constantfrom Generators.libweb_bindings.rust_types import holds_cellsfrom Generators.libweb_bindings.rust_types import inheriting_interfaces@@ -69,6 +71,7 @@ from Generators.libweb_bindings.rust_usage import DefinitionUsagefrom Generators.libweb_bindings.wrappers import wrapper_host_class_namefrom Generators.libweb_bindings.wrappers import wrapper_namefrom Utils.utils import title_case_to_snake_case+from Utils.webidl_parser import Dictionaryfrom Utils.webidl_parser import Interfacefrom Utils.webidl_parser import Modulefrom Utils.webidl_parser import OperationParameter@@ -317,6 +320,28 @@ constexpr JSHostClass {wrapper_host_class_symbol(interface)} = JS::make_host_cla)+def write_cpp_dictionary_converter(out: TextIO, includes: GeneratedIncludes, dictionary: Dictionary) -> None:+ """The C ABI function that converts a JS value to the dictionary for the interfaces implemented in Rust, which+ is_converted_by_cpp(), and hands them the C++ value."""+ includes.add("LibJS/HostClassBuilder.h")+ includes.add("LibWeb/Bindings/CppDictionary.h")+ out.write(+ f"""extern "C" JSCompletion {cpp_dictionary_converter_symbol(dictionary)}(JSVM*, JSValue, void** dictionary);++JSCompletion {cpp_dictionary_converter_symbol(dictionary)}(JSVM* vm, JSValue value, void** dictionary)+{{+ auto& js_vm = JS::HostABI::vm_from_abi(vm);+ auto converted = {converter_function_name(dictionary)}(js_vm, JS::HostABI::value_from_abi(value));+ if (converted.is_error())+ return JS::HostABI::throw_completion_to_abi(converted.error_value());+ *dictionary = js_vm.heap().allocate<CppDictionary<{dictionary.name}>>(converted.release_value()).ptr();+ return JS::HostABI::normal_completion_to_abi(0);+}}++"""+ )++def write_cpp_implementation(out: TextIO, includes: GeneratedIncludes, context: GenerationContext, interface: Interface) -> None:@@ -1137,7 +1162,8 @@ RUST_BINDINGS_IMPORTS = """ #![allow(unused_imports)]};use crate::bindings::conversions::{- ArrayBufferView, BufferSource, BufferSourceRules, ByteString, CppInterface, EmptyDictionary, FromJs, ToJs, UsvString,+ ArrayBufferView, BufferSource, BufferSourceRules, ByteString, CppDictionary, CppInterface, EmptyDictionary, FromJs, ToJs,+ UsvString, to_cpp_dictionary,frozen_array_to_js, implements_cpp_interface, iterator_method, record_from_js, record_to_js, rooted_sequence_to_js,sequence_from_js, sequence_to_js, to_array_buffer_view, to_boolean, to_buffer_source, to_byte_string, to_cpp_interface,to_cpp_interface_in_union, to_dom_string,@@ -2525,6 +2551,7 @@ def write_rust_definitions(out: TextIO, context: GenerationContext, usage: Definand not usage.rust_unionsand not usage.rust_enumerationsand not usage.rust_any_interfaces+ and not usage.cpp_dictionaries_named_by_rust):returnout.write(@@ -2534,19 +2561,20 @@ def write_rust_definitions(out: TextIO, context: GenerationContext, usage: Definpub(crate) mod definitions {#![allow(unused_imports)]+ use core::ffi::c_void;use std::sync::LazyLock;use ak::Utf16String;use libjs_rust::api::{- ErrorKind, ErrorType, Gc, JSONObject, MarkedVec, Object, PropertyKey, ThrowCompletionOr, TypedArrayBase, TypedArrayKind, Utf16View,- Value, Vm, is_host_instance_of,+ ErrorKind, ErrorType, Gc, JSONObject, MarkedVec, Object, PropertyKey, RawNativeFunctionResult, ThrowCompletionOr,+ TypedArrayBase, TypedArrayKind, Utf16View, Value, Vm, is_host_instance_of,};use crate::bindings::CallContext;use crate::bindings::callback::{CallbackFunction, CallbackInterface, PromiseCallbackFunction};use crate::bindings::conversions::{- ArrayBufferView, BufferSource, BufferSourceRules, ByteString, CppInterface, EmptyDictionary, FromJs, ToJs, UsvString,- buffer_source_if, dictionary_member, dictionary_object, enumeration_value_to_js, implements_cpp_interface,+ ArrayBufferView, BufferSource, BufferSourceRules, ByteString, CppDictionary, CppInterface, EmptyDictionary, FromJs, ToJs,+ UsvString, buffer_source_if, to_cpp_dictionary, dictionary_member, dictionary_object, enumeration_value_to_js, implements_cpp_interface,frozen_array_to_js, iterator_method, record_from_js, record_to_js, rooted_sequence_to_js, sequence_from_iterable, sequence_from_js,sequence_to_js, throw_no_union_types_matched, to_array_buffer_view, to_boolean, to_buffer_source,to_byte_string, to_cpp_interface,@@ -2586,6 +2614,20 @@ pub(crate) mod definitions {write_union_from_js(out, context, union_type)if directions.to_js:write_union_to_js(out, context, union_type)+ if usage.cpp_dictionaries_named_by_rust:+ out.write('\n unsafe extern "C" {\n')+ for dictionary in usage.cpp_dictionaries_named_by_rust.values():+ out.write(+ f""" /// The conversion of a JS value to the dictionary {dictionary.name}, which the C++ bindings write to+ /// `dictionary` as a Web::Bindings::CppDictionary.+ pub(crate) fn {cpp_dictionary_converter_symbol(dictionary)}(+ vm: *mut c_void,+ value: u64,+ dictionary: *mut *mut c_void,+ ) -> RawNativeFunctionResult;+"""+ )+ out.write(" }\n")out.write("}\n")diff --git a/Meta/Generators/libweb_bindings/rust_to_idl_value.py b/Meta/Generators/libweb_bindings/rust_to_idl_value.pyindex bc79f5cfd47..e95b545a8b4 100644--- a/Meta/Generators/libweb_bindings/rust_to_idl_value.py+++ b/Meta/Generators/libweb_bindings/rust_to_idl_value.py@@ -21,12 +21,14 @@ from Generators.libweb_bindings.rust_types import FLOATING_POINT_TYPESfrom Generators.libweb_bindings.rust_types import INTEGER_TYPESfrom Generators.libweb_bindings.rust_types import TYPED_ARRAY_NAMESfrom Generators.libweb_bindings.rust_types import UnsupportedByRustBindings+from Generators.libweb_bindings.rust_types import cpp_dictionary_converter_symbolfrom Generators.libweb_bindings.rust_types import cpp_interfacefrom Generators.libweb_bindings.rust_types import cpp_interface_name_constantfrom Generators.libweb_bindings.rust_types import dictionary_holds_sequence_of_cellsfrom Generators.libweb_bindings.rust_types import holds_cellsfrom Generators.libweb_bindings.rust_types import inheriting_interfacesfrom Generators.libweb_bindings.rust_types import is_callback_interface+from Generators.libweb_bindings.rust_types import is_converted_by_cppfrom Generators.libweb_bindings.rust_types import is_named_unionfrom Generators.libweb_bindings.rust_types import is_promise_typefrom Generators.libweb_bindings.rust_types import is_record_of_cells@@ -57,6 +59,8 @@ from Utils.webidl_parser import OperationParameter# NB: CSSOMString is a string type that an implementation chooses, https://drafts.csswg.org/cssom/#cssomstring-type,# and it is a DOMString here, as it is in the C++ bindings.+RUST_DEFINITIONS_PATH = "crate::bindings::generated::definitions"+DOM_STRING_TYPES = ("CSSOMString", "DOMString")STRING_TYPES = ("ByteString", *DOM_STRING_TYPES, "USVString")@@ -187,6 +191,8 @@ def rust_to_idl_value()return f"to_cpp_interface_in_union(vm, {value}, &[{interface_names}])"dictionary = resolved_dictionary(idl_type, context)+ if dictionary is not None and is_converted_by_cpp(dictionary):+ return f"to_cpp_dictionary(vm, {value}, {RUST_DEFINITIONS_PATH}::{cpp_dictionary_converter_symbol(dictionary)})"if dictionary is not None:if dictionary_holds_sequence_of_cells(dictionary, context) and not keeps_cells_alive:raise UnsupportedByRustBindings(@@ -359,6 +365,11 @@ def rust_default_value(return "MarkedVec::new(vm)"return "Vec::new()"dictionary = resolved_dictionary(member.type, context)+ if dictionary is not None and default_value == "{}" and is_converted_by_cpp(dictionary):+ if not isinstance(member, OperationParameter):+ raise UnsupportedByRustBindings(f"{what} is a dictionary member of {dictionary.name}, which C++ converts")+ converter = f"{RUST_DEFINITIONS_PATH}::{cpp_dictionary_converter_symbol(dictionary)}"+ return f"to_cpp_dictionary(vm, Value::UNDEFINED, {converter})?"if dictionary is not None and default_value == "{}":# NB: The C++ bindings do not run the conversion for a missing argument either, so the members of the default# value are not read from a JS object.diff --git a/Meta/Generators/libweb_bindings/rust_types.py b/Meta/Generators/libweb_bindings/rust_types.pyindex 9a4e14d4165..5d4f76070f5 100644--- a/Meta/Generators/libweb_bindings/rust_types.py+++ b/Meta/Generators/libweb_bindings/rust_types.py@@ -14,6 +14,7 @@ from typing import Listfrom typing import Optionalfrom Generators.libweb_bindings.context import GenerationContext+from Generators.libweb_bindings.cpp_types import converter_function_namefrom Utils.utils import string_to_cpp_enum_namefrom Utils.utils import title_case_to_snake_casefrom Utils.webidl_parser import Dictionary@@ -144,6 +145,17 @@ def resolved_dictionary(idl_type: IDLType, context: GenerationContext) -> Optionreturn context.dictionaries.get(idl_type.name)+def cpp_dictionary_converter_symbol(dictionary: Dictionary) -> str:+ """The C ABI function of the C++ bindings that converts a JS value to the dictionary, which is_converted_by_cpp()."""+ return f"web_bindings_{converter_function_name(dictionary)}"+++def is_converted_by_cpp(dictionary: Dictionary) -> bool:+ """Whether the C++ bindings convert JS values to the dictionary for the interfaces implemented in Rust as well,+ which hand the C++ value to the C++ code that uses it."""+ return dictionary.extended_attributes.get("ImplementedIn") == "Cpp"++def rust_interface(idl_type: IDLType, context: GenerationContext) -> Optional[Interface]:"""The interface that the type names, if it is implemented in Rust."""if isinstance(idl_type, (IDLParameterizedType, IDLUnionType)):@@ -463,6 +475,12 @@ def rust_type(idl_type: IDLType, context: GenerationContext, what: str, is_resulreturn "CppInterface"dictionary = resolved_dictionary(idl_type, context)if dictionary is not None:+ if is_converted_by_cpp(dictionary):+ if is_result:+ raise UnsupportedByRustBindings(+ f"{what} returns the dictionary {dictionary.name}, which the C++ bindings convert"+ )+ return "CppDictionary"return rust_dictionary_type(dictionary, context)enumeration = context.enumeration(idl_type)if enumeration is not None:diff --git a/Meta/Generators/libweb_bindings/rust_usage.py b/Meta/Generators/libweb_bindings/rust_usage.pyindex e6a08afddb9..09fe17d19d2 100644--- a/Meta/Generators/libweb_bindings/rust_usage.py+++ b/Meta/Generators/libweb_bindings/rust_usage.py@@ -14,8 +14,10 @@ from typing import Setfrom Generators.libweb_bindings.context import GenerationContextfrom Generators.libweb_bindings.rust_members import rust_members+from Generators.libweb_bindings.rust_types import UnsupportedByRustBindingsfrom Generators.libweb_bindings.rust_types import cpp_interfacefrom Generators.libweb_bindings.rust_types import inheriting_interfaces+from Generators.libweb_bindings.rust_types import is_converted_by_cppfrom Generators.libweb_bindings.rust_types import is_implemented_in_rustfrom Generators.libweb_bindings.rust_types import is_named_unionfrom Generators.libweb_bindings.rust_types import runtime_union_type@@ -93,6 +95,8 @@ class DefinitionUsage:self.cpp_interfaces_named_by_rust: Dict[str, Interface] = {}# The dictionaries that have a C++ representation.self.cpp_dictionary_names: Set[str] = set()+ # The dictionaries that the C++ bindings convert for the interfaces implemented in Rust, is_converted_by_cpp().+ self.cpp_dictionaries_named_by_rust: Dict[str, Dictionary] = {}# The interfaces implemented in Rust that the C++ bindings convert objects of, and so need a C++ class for.self.rust_interfaces_named_by_cpp: Dict[str, Interface] = {}# The interfaces implemented in Rust that others inherit from and that the interfaces implemented in Rust@@ -180,6 +184,15 @@ class DefinitionUsage:dictionary = self.context.dictionaries.get(idl_type.name)if dictionary is None:return+ if is_converted_by_cpp(dictionary):+ if to_js:+ raise UnsupportedByRustBindings(+ f"An interface implemented in Rust returns the dictionary {dictionary.name}, which the C++ "+ "bindings convert"+ )+ self.cpp_dictionaries_named_by_rust[dictionary.name] = dictionary+ self._name_for_cpp(dictionary.name)+ returnfrom_js = from_js or "GenerateFromJSON" in dictionary.extended_attributesto_js = to_js or "GenerateToValue" in dictionary.extended_attributesdirections = self.rust_dictionaries.setdefault(dictionary.name, ConversionDirections())