Truly independent web browser
Meta+LibJS+LibWeb: Keep one wrapper per world for Rust interface objects
Aliaksandr Kalenik4f0031cefcc1
diff --git a/Libraries/LibJS/Rust/src/api.rs b/Libraries/LibJS/Rust/src/api.rsindex 2ce4225cbca..8793562f111 100644--- a/Libraries/LibJS/Rust/src/api.rs+++ b/Libraries/LibJS/Rust/src/api.rs@@ -9,7 +9,7 @@//! the runtime only through this module (Meta/Linters/check_libjs_rust_api.py), so the rest of the crate stays the//! runtime's own business.-pub use crate::embedding::host::host_object::{HostObject, host_class_of, host_data_of};+pub use crate::embedding::host::host_object::{HostObject, host_class_of, host_data_of, is_host_instance_of};pub use crate::gc::embedder_cell::{EmbedderCell, EmbedderClass, EmbedderValue};pub use crate::gc::root::{MarkedVec, Root};pub use crate::gc::visitor::{Trace, Visitor};diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rsindex b2dc73c5889..d2eb4e7dcee 100644--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs@@ -12,13 +12,13 @@ use core::mem::MaybeUninit;use ak::{Utf16String, Utf16StringUnits, convert_valid_utf16_to_utf8, utf8_length_from_valid_utf16};use libjs_rust::api::{Array, ArrayBuffer, ArrayBufferOrder, DataView, ErrorKind, ErrorType, FunctionObject, Gc, Object, PrimitiveString,- PropertyKey, ThrowCompletionOr, TypedArrayBase, TypedArrayKind, Value, Vm, get_view_byte_length,+ PropertyKey, Root, ThrowCompletionOr, Trace, TypedArrayBase, TypedArrayKind, Value, Vm, get_view_byte_length,is_typed_array_out_of_bounds, is_view_out_of_bounds, make_data_view_with_buffer_witness_record,make_typed_array_with_buffer_witness_record, to_well_formed, typed_array_byte_length,};use crate::bindings::CallContext;-use crate::bindings::interface::create_dictionary_object;+use crate::bindings::interface::{Interface, Ref, create_dictionary_object, wrap};/// A USVString, a string without lone surrogates. Its UTF-16 code units are always well-formed.pub(crate) struct UsvString(Utf16String);@@ -420,6 +420,13 @@ impl ToJs for Gc<TypedArrayBase> {}}+/// An object of an interface converted to a JS value, https://webidl.spec.whatwg.org/#js-interface+impl<T: Interface> ToJs for Ref<T> {+ fn to_js(self, cx: &CallContext) -> ThrowCompletionOr<Value> {+ Ok(Value::from_object(wrap(cx, self)))+ }+}+/// An IDL sequence converted to a JS value, https://webidl.spec.whatwg.org/#js-sequence, with the conversion of its/// elements.pub(crate) fn sequence_to_js<T>(@@ -449,6 +456,23 @@ pub(crate) fn sequence_to_js<T>(Ok(Value::from_object(array))}+/// sequence_to_js() for a sequence whose elements are cells, such as objects of interfaces. The conversion of an+/// element can allocate, and a Vec hides the elements after it from the collector, so the sequence is kept alive.+pub(crate) fn rooted_sequence_to_js<T: Trace + Clone + 'static>(+ cx: &CallContext,+ sequence: Vec<T>,+ mut element_to_js: impl FnMut(T) -> ThrowCompletionOr<Value>,+) -> ThrowCompletionOr<Value> {+ let sequence = Root::new(cx.vm(), sequence);+ let array = Array::create(cx.vm(), cx.realm(), sequence.get().len() as u64, None)?;+ for (index, element) in sequence.get().iter().enumerate() {+ let element = element_to_js(element.clone())?;+ let index = u32::try_from(index).expect("an array of the length of the sequence was created");+ array.create_data_property(cx.vm(), &PropertyKey::from(index), element, None, None)?;+ }+ Ok(Value::from_object(array))+}+/// An IDL record converted to a JS value, https://webidl.spec.whatwg.org/#js-record, with the conversion of its/// values. The entries of the record are in the order of the Vec.pub(crate) fn record_to_js<K: Into<Utf16String>, V>(diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/interface.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/interface.rsindex 74a8d787326..9f017e17598 100644--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/interface.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/interface.rs@@ -7,24 +7,111 @@//! What the generated bindings of an interface do with its wrappers, its interface object and its interface prototype//! object, https://webidl.spec.whatwg.org/#es-interfaces//!-//! A wrapper of an interface implemented in Rust is a platform object of the interface's wrapper class, which LibWeb's-//! C++ bindings define. Its host data holds the cell of its implementation, and its wrappable slot stays empty, so the-//! C++ bindings treat it like a platform object without a wrappable.+//! An object of an interface implemented in Rust is a cell that holds the implementation, a `Ref<T>`, which is what+//! implementations hold and pass each other. A wrapper of such an object is a platform object of the interface's+//! wrapper class, which LibWeb's C++ bindings define. Its host data is the cell, and its wrappable slot stays empty,+//! so the C++ bindings treat it like a platform object without a wrappable.+//!+//! An object has one wrapper per wrapper world, as an implementation object of the C++ bindings has+//! (Documentation/WrapperArchitecture.md), and wrap() finds or creates it.+use core::cell::Cell;use core::ffi::c_void;+use core::ops::Deref;use core::ptr::NonNull;use libjs_rust::api::{Attribute, EmbedderCell, EmbedderClass, EmbedderValue, ErrorKind, ErrorType, FunctionObject, Gc, HostObject,JSHostClass, Object, PrimitiveString, PropertyAttributes, PropertyKey, RawNativeFunctionPointer, Realm,- ThrowCompletionOr, Value, Vm, get_function_realm, host_class_of, host_data_of,+ ThrowCompletionOr, Trace, Value, Vm, get_function_realm, host_data_of, is_host_instance_of,};use crate::bindings::CallContext;-use crate::bindings::services::web_bindings_ensure_web_prototype;+use crate::bindings::realm_data::wrapper_world_of;+use crate::bindings::services::{+ web_bindings_ensure_web_prototype, web_bindings_rust_wrapper_for, web_bindings_set_rust_wrapper,+};++/// What an implementation can tell the bindings about its objects, as a C++ implementation object does by overriding+/// the virtual functions of Web::Bindings::Wrappable.+pub(crate) trait Wrappable {+ /// The realm of the relevant global object of the object, which the wrapper of the object in the main world is+ /// created in, as Wrappable::relevant_global_impl() decides for a C++ implementation object. Without one, the+ /// wrapper is created in the realm that first asks for it.+ fn relevant_realm(&self, _vm: &Vm) -> Option<Gc<Realm>> {+ None+ }+}++/// The value of the cell of an object of an interface: its implementation, and its wrapper in the main world.+///+/// The cell keeps that wrapper alive, and the wrapper keeps the cell alive through its host data, so the two live and+/// die together: the object has the same wrapper in the main world for as long as it lives. A C++ implementation+/// object holds its wrapper weakly until script makes the wrapper observable, which the wrapper of an interface+/// implemented in Rust has no hooks to tell.+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct Wrapped<T: Trace> {+ main_world_wrapper: Cell<Option<Gc<HostObject>>>,+ implementation: T,+}++impl<T: Trace> Deref for Wrapped<T> {+ type Target = T;++ fn deref(&self) -> &T {+ &self.implementation+ }+}++/// An object of the interface that `T` implements.+pub(crate) type Ref<T> = Gc<EmbedderCell<Wrapped<T>>>;++/// An implementation of an interface, as the generated bindings of the interface describe it.+pub(crate) trait Interface: Wrappable + Trace + Sized + 'static {+ /// The class of the cells of the objects of the interface.+ const CELL_CLASS: &'static EmbedderClass<Wrapped<Self>>;+ /// Web::Bindings::InterfaceName of the interface.+ const INTERFACE_NAME: u16;+ /// The name that errors call the interface.+ const NAME: &'static str;++ /// The class of the wrappers of the objects of the interface.+ fn wrapper_class() -> &'static JSHostClass;+}++impl<T: Interface> EmbedderValue for Wrapped<T> {+ const CLASS: &'static EmbedderClass<Self> = T::CELL_CLASS;+}++/// Without the generated bindings, which a build of the crate on its own leaves out, nothing creates or wraps an+/// object, but the implementations still name each other's objects. This stands in for the bindings of every+/// interface so that they compile.+#[cfg(not(web_idl_bindings))]+impl<T: Wrappable + Trace + Sized + 'static> Interface for T {+ const CELL_CLASS: &'static EmbedderClass<Wrapped<Self>> = &EmbedderClass::new("");+ const INTERFACE_NAME: u16 = 0;+ const NAME: &'static str = "";-/// The object an attribute or an operation of an interface runs on, if it is a wrapper of the interface, with the-/// object's realm. A nullish this value stands for the global object of the current realm.+ fn wrapper_class() -> &'static JSHostClass {+ unreachable!("an interface has no wrappers without its bindings")+ }+}++/// A new object of the interface, which has no wrapper until something asks for one.+pub(crate) fn allocate<T: Interface>(vm: &Vm, implementation: T) -> Ref<T> {+ T::CELL_CLASS.allocate(+ vm,+ Wrapped {+ main_world_wrapper: Cell::new(None),+ implementation,+ },+ )+}++/// The object an attribute or an operation of an interface runs on, if it is a wrapper of the interface or of an+/// interface that inherits from it, with the object's realm. A nullish this value stands for the global object of+/// the current realm.pub(crate) fn this_object(vm: &Vm,wrapper_class: &'static JSHostClass,@@ -37,21 +124,120 @@ pub(crate) fn this_object(}if this_value.is_object() {let object = this_value.as_object();- if host_class_of(&object).is_some_and(|host_class| core::ptr::eq(host_class, wrapper_class)) {+ if is_host_instance_of(&object, wrapper_class) {return Ok((object, object.shape().realm()));}}vm.throw_completion(ErrorKind::TypeError, ErrorType::NotAnObjectOfType, &[&interface_name])}-pub(crate) fn implementation_of<T: EmbedderValue>(- wrapper: Gc<Object>,- cell_class: &'static EmbedderClass<T>,-) -> Gc<EmbedderCell<T>> {- let host_data = host_data_of(&wrapper).expect("a wrapper holds the cell of its implementation");+/// The object that a wrapper of exactly the interface wraps.+pub(crate) fn implementation_of<T: Interface>(wrapper: Gc<Object>) -> Ref<T> {+ let host_data = host_data_of(&wrapper).expect("a wrapper holds the cell of its object");// SAFETY: The wrapper is a host object of the interface's wrapper class, whose host data the bindings set to a- // cell of the interface's implementation.- unsafe { cell_class.downcast(host_data) }.expect("a wrapper holds the cell of its implementation")+ // cell of the interface.+ unsafe { T::CELL_CLASS.downcast(host_data) }.expect("a wrapper holds the cell of its object")+}++/// An object of the interface converted from a JS value, https://webidl.spec.whatwg.org/#js-interface+pub(crate) fn to_interface<T: Interface>(vm: &Vm, value: Value) -> ThrowCompletionOr<Ref<T>> {+ // 1. If V implements I, then return the IDL interface type value that represents a reference to that platform+ // object.+ if value.is_object() {+ let object = value.as_object();+ if is_host_instance_of(&object, T::wrapper_class()) {+ return Ok(implementation_of(object));+ }+ }+ // 2. Throw a TypeError.+ vm.throw_completion(ErrorKind::TypeError, ErrorType::NotAnObjectOfType, &[&T::NAME])+}++/// The wrapper of the object in the wrapper world of the realm of the call context, which the first call for that+/// world creates, as Web::Bindings::wrap() does for a C++ implementation object.+pub(crate) fn wrap<T: Interface>(cx: &CallContext, object: Ref<T>) -> Gc<Object> {+ let vm = cx.vm();+ let realm = cx.realm();+ let main_world_wrapper = object.main_world_wrapper.get();+ if let Some(wrapper) = main_world_wrapper+ && wrapper.shape().realm() == realm+ {+ return wrapper.upcast();+ }++ let wrapper_world = wrapper_world_of(vm, realm);+ if wrapper_world.is_main_world() {+ if let Some(wrapper) = main_world_wrapper {+ // NB: An agent has one main world, which the realms of the agent share, and objects do not cross agents.+ assert!(+ wrapper_world_of(vm, wrapper.shape().realm()) == wrapper_world,+ "an object has a wrapper in the main world of another agent"+ );+ return wrapper.upcast();+ }+ let wrapper_realm = object+ .relevant_realm(vm)+ .filter(|relevant_realm| wrapper_world_of(vm, *relevant_realm) == wrapper_world)+ .unwrap_or(realm);+ let wrapper = create_wrapper(+ vm,+ wrapper_realm,+ interface_prototype_object(wrapper_realm, T::INTERFACE_NAME),+ object,+ );+ object.main_world_wrapper.set(Some(wrapper));+ return wrapper.upcast();+ }++ // SAFETY: The realm and the cell are live.+ let wrapper = unsafe { web_bindings_rust_wrapper_for(realm.as_ptr().cast(), object.as_ptr().cast()) };+ if let Some(wrapper) = NonNull::new(wrapper.cast::<Object>()) {+ // SAFETY: LibWeb returns a live wrapper.+ return unsafe { Gc::from_non_null(wrapper) };+ }+ let wrapper = create_wrapper(vm, realm, interface_prototype_object(realm, T::INTERFACE_NAME), object);+ register_wrapper_outside_main_world(realm, object, wrapper);+ wrapper.upcast()+}++/// The wrapper that a construction creates for the new object of the interface, with the prototype that the new+/// target of the construction decides.+pub(crate) fn construct_wrapper<T: Interface>(+ vm: &Vm,+ realm: Gc<Realm>,+ prototype: Gc<Object>,+ implementation: T,+) -> Gc<HostObject> {+ let object = allocate(vm, implementation);+ let wrapper = create_wrapper(vm, realm, prototype, object);+ if wrapper_world_of(vm, realm).is_main_world() {+ object.main_world_wrapper.set(Some(wrapper));+ } else {+ register_wrapper_outside_main_world(realm, object, wrapper);+ }+ wrapper+}++fn register_wrapper_outside_main_world<T: Interface>(realm: Gc<Realm>, object: Ref<T>, wrapper: Gc<HostObject>) {+ // SAFETY: The realm, the cell and the wrapper are live, and the wrapper is in the realm.+ unsafe {+ web_bindings_set_rust_wrapper(realm.as_ptr().cast(), object.as_ptr().cast(), wrapper.as_ptr().cast());+ }+}++/// A new wrapper of the object in the realm, whose host data is the cell of the object.+fn create_wrapper<T: Interface>(vm: &Vm, realm: Gc<Realm>, prototype: Gc<Object>, object: Ref<T>) -> Gc<HostObject> {+ // SAFETY: The wrapper class's hooks expect no wrappable, and the host data is a live cell.+ unsafe {+ HostObject::create(+ vm,+ realm,+ T::wrapper_class(),+ Some(prototype),+ None,+ Some(object.as_non_null().cast()),+ )+ }}/// The interface prototype object of the interface in the realm.@@ -86,27 +272,6 @@ pub(crate) fn prototype_from_new_target(Ok(interface_prototype_object(target_realm, interface_name))}-/// A new wrapper of the interface in the realm, whose host data holds the implementation.-pub(crate) fn create_wrapper<T: EmbedderValue>(- vm: &Vm,- realm: Gc<Realm>,- wrapper_class: &'static JSHostClass,- prototype: Gc<Object>,- implementation: Gc<EmbedderCell<T>>,-) -> Gc<HostObject> {- // SAFETY: The wrapper class's hooks expect no wrappable, and the host data is a live cell.- unsafe {- HostObject::create(- vm,- realm,- wrapper_class,- Some(prototype),- None,- Some(implementation.as_non_null().cast()),- )- }-}-/// Unwraps the raw arguments that LibWeb's C++ bindings pass the entry points that initialize the interface object and/// the interface prototype object, which run before any binding of the interface. The C++ bindings pass the runtime's/// VM and cells, as JS::HostABI::vm_to_abi() and object_to_abi() do.diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/realm_data.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/realm_data.rsindex ce1f69fa2e7..97801aa949d 100644--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/realm_data.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/realm_data.rs@@ -5,15 +5,35 @@*///! What the interfaces implemented in Rust keep for a realm: the objects that a specification has a global object-//! hold, which every object of an interface in the realm of that global returns.+//! hold, which every object of an interface in the realm of that global returns, and what the bindings ask LibWeb+//! about the realm once.use core::cell::Cell;+use core::ffi::c_void;+use core::ptr::NonNull;use libjs_rust::api::{EmbedderCell, EmbedderClass, EmbedderValue, FunctionObject, Gc, Realm, Trace, Vm};+use crate::bindings::services::web_bindings_wrapper_world;++/// The wrapper world of a realm, Web::Bindings::WrapperWorld, which the realm keeps alive.+#[derive(Clone, Copy, PartialEq, Eq)]+pub(crate) struct WrapperWorld {+ world: NonNull<c_void>,+ is_main_world: bool,+}++impl WrapperWorld {+ pub(crate) fn is_main_world(self) -> bool {+ self.is_main_world+ }+}+#[derive(Default, Trace)]#[gc(crate = libjs_rust)]pub(crate) struct RealmData {+ #[gc(untraced)]+ wrapper_world: Cell<Option<WrapperWorld>>,/// https://streams.spec.whatwg.org/#count-queuing-strategy-size-functionpub(crate) count_queuing_strategy_size_function: Cell<Option<Gc<FunctionObject>>>,/// https://streams.spec.whatwg.org/#byte-length-queuing-strategy-size-function@@ -35,3 +55,20 @@ pub(crate) fn realm_data(vm: &Vm, realm: Gc<Realm>) -> Gc<EmbedderCell<RealmDatarealm.set_embedder_data(data);data}++/// The wrapper world of the realm, which LibWeb is asked for once per realm.+pub(crate) fn wrapper_world_of(vm: &Vm, realm: Gc<Realm>) -> WrapperWorld {+ let data = realm_data(vm, realm);+ if let Some(wrapper_world) = data.wrapper_world.get() {+ return wrapper_world;+ }+ let mut is_main_world = false;+ // SAFETY: The realm is live, and LibWeb set its host defined data up before any binding runs in it.+ let world = unsafe { web_bindings_wrapper_world(realm.as_ptr().cast(), &raw mut is_main_world) };+ let wrapper_world = WrapperWorld {+ world: NonNull::new(world).expect("a realm of LibWeb has a wrapper world"),+ is_main_world,+ };+ data.wrapper_world.set(Some(wrapper_world));+ wrapper_world+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/services.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/services.rsindex fe313b0fbe2..981d20b8698 100644--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/services.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/services.rs@@ -5,7 +5,7 @@*///! The services of LibWeb's C++ bindings that the Rust bindings use, which the bindings generator defines in-//! Bindings/IntrinsicDefinitions.cpp.+//! Bindings/IntrinsicDefinitions.cpp and Bindings/RustBindingsServices.cpp defines by hand.use core::ffi::c_void;@@ -14,4 +14,15 @@ unsafe extern "C" {/// The realm and the object are the runtime's cells, and the interface name is a Web::Bindings::InterfaceName of an/// interface implemented in Rust.pub(crate) fn web_bindings_ensure_web_prototype(realm: *mut c_void, interface_name: u16) -> *mut c_void;++ /// The wrapper world of the realm, a cell that the realm keeps alive, and whether it is the main world of its+ /// agent.+ pub(crate) fn web_bindings_wrapper_world(realm: *mut c_void, is_main_world: *mut bool) -> *mut c_void;++ /// The wrapper that the world of the realm, which is not a main world, holds for the cell of an object of an+ /// interface implemented in Rust, or null.+ pub(crate) fn web_bindings_rust_wrapper_for(realm: *mut c_void, cell: *mut c_void) -> *mut c_void;++ /// Makes `wrapper` the wrapper that the world of its realm, which is not a main world, holds for the cell.+ pub(crate) fn web_bindings_set_rust_wrapper(realm: *mut c_void, cell: *mut c_void, wrapper: *mut c_void);}diff --git a/Libraries/LibWeb/Bindings/Rust/src/encoding/text_decoder.rs b/Libraries/LibWeb/Bindings/Rust/src/encoding/text_decoder.rsindex 468399c2d20..db3e618306b 100644--- a/Libraries/LibWeb/Bindings/Rust/src/encoding/text_decoder.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/encoding/text_decoder.rs@@ -12,6 +12,7 @@ use ak::Utf16String;use libjs_rust::api::Trace;use crate::bindings::conversions::{BufferSource, UsvString};+use crate::bindings::interface::Wrappable;use crate::bindings::{CallContext, Exception, WebIdlResult};use crate::encoding::decoding::{DecodingFailed, StreamingDecoder, encoding_for_label};@@ -35,6 +36,8 @@ pub(crate) struct TextDecoder {decoder: RefCell<StreamingDecoder>,}+impl Wrappable for TextDecoder {}+#[expect(clippy::unnecessary_wraps,reason = "the bindings call every method of an implementation for its WebIDL result, whether or not it can fail"diff --git a/Libraries/LibWeb/Bindings/Rust/src/encoding/text_encoder.rs b/Libraries/LibWeb/Bindings/Rust/src/encoding/text_encoder.rsindex 0be31c2d685..84832266e7d 100644--- a/Libraries/LibWeb/Bindings/Rust/src/encoding/text_encoder.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/encoding/text_encoder.rs@@ -16,6 +16,7 @@ use libjs_rust::api::{};use crate::bindings::conversions::UsvString;+use crate::bindings::interface::Wrappable;use crate::bindings::{CallContext, Exception, WebIdlResult};use crate::encoding::utf8::{self, EncodeIntoProgress};@@ -24,6 +25,8 @@ use crate::encoding::utf8::{self, EncodeIntoProgress};#[gc(crate = libjs_rust)]pub(crate) struct TextEncoder;+impl Wrappable for TextEncoder {}+/// The dictionary TextEncoderEncodeIntoResult of Encoding/TextEncoder.idl, whose members the bindings convert.pub(crate) struct TextEncoderEncodeIntoResult {pub(crate) read: Option<u64>,diff --git a/Libraries/LibWeb/Bindings/Rust/src/speech/speech_recognition_phrase.rs b/Libraries/LibWeb/Bindings/Rust/src/speech/speech_recognition_phrase.rsindex c5d2ade5be2..2d5663eddb7 100644--- a/Libraries/LibWeb/Bindings/Rust/src/speech/speech_recognition_phrase.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/speech/speech_recognition_phrase.rs@@ -9,6 +9,7 @@use ak::Utf16String;use libjs_rust::api::Trace;+use crate::bindings::interface::Wrappable;use crate::bindings::{CallContext, WebIdlResult};#[derive(Trace)]@@ -18,6 +19,8 @@ pub(crate) struct SpeechRecognitionPhrase {boost: f32,}+impl Wrappable for SpeechRecognitionPhrase {}+#[expect(clippy::unnecessary_wraps,reason = "the bindings call every method of an implementation for its WebIDL result, whether or not it can fail"diff --git a/Libraries/LibWeb/Bindings/Rust/src/streams/byte_length_queuing_strategy.rs b/Libraries/LibWeb/Bindings/Rust/src/streams/byte_length_queuing_strategy.rsindex cd0c447f289..4265ddec9d9 100644--- a/Libraries/LibWeb/Bindings/Rust/src/streams/byte_length_queuing_strategy.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/streams/byte_length_queuing_strategy.rs@@ -10,6 +10,7 @@ use libjs_rust::api::{FunctionObject, Gc, PropertyKey, RawNativeFunction, ThrowCompletionOr, Trace, Value, Vm, raw_native,};+use crate::bindings::interface::Wrappable;use crate::bindings::realm_data::realm_data;use crate::bindings::{CallContext, WebIdlResult};use crate::streams::queuing_strategy_init::QueuingStrategyInit;@@ -20,6 +21,8 @@ pub(crate) struct ByteLengthQueuingStrategy {high_water_mark: f64,}+impl Wrappable for ByteLengthQueuingStrategy {}+#[expect(clippy::unnecessary_wraps,reason = "the bindings call every method of an implementation for its WebIDL result, whether or not it can fail"diff --git a/Libraries/LibWeb/Bindings/Rust/src/streams/count_queuing_strategy.rs b/Libraries/LibWeb/Bindings/Rust/src/streams/count_queuing_strategy.rsindex 345bd26e31a..ea37f43b2a2 100644--- a/Libraries/LibWeb/Bindings/Rust/src/streams/count_queuing_strategy.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/streams/count_queuing_strategy.rs@@ -10,6 +10,7 @@ use libjs_rust::api::{FunctionObject, Gc, PropertyKey, RawNativeFunction, ThrowCompletionOr, Trace, Value, Vm, raw_native,};+use crate::bindings::interface::Wrappable;use crate::bindings::realm_data::realm_data;use crate::bindings::{CallContext, WebIdlResult};use crate::streams::queuing_strategy_init::QueuingStrategyInit;@@ -20,6 +21,8 @@ pub(crate) struct CountQueuingStrategy {high_water_mark: f64,}+impl Wrappable for CountQueuingStrategy {}+#[expect(clippy::unnecessary_wraps,reason = "the bindings call every method of an implementation for its WebIDL result, whether or not it can fail"diff --git a/Libraries/LibWeb/Bindings/Rust/src/url_pattern/url_pattern.rs b/Libraries/LibWeb/Bindings/Rust/src/url_pattern/url_pattern.rsindex 7ed3b6c43e2..b66353905bb 100644--- a/Libraries/LibWeb/Bindings/Rust/src/url_pattern/url_pattern.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/url_pattern/url_pattern.rs@@ -13,6 +13,7 @@ use liburl_rust::pattern::{};use crate::bindings::conversions::UsvString;+use crate::bindings::interface::Wrappable;use crate::bindings::{CallContext, Exception, WebIdlResult};/// The union URLPatternInput of URLPattern/URLPattern.idl, whose members the bindings convert.@@ -146,6 +147,8 @@ pub(crate) struct URLPattern {pattern: Pattern,}+impl Wrappable for URLPattern {}+#[expect(clippy::unnecessary_wraps,reason = "the bindings call every method of an implementation for its WebIDL result, whether or not it can fail"diff --git a/Libraries/LibWeb/Bindings/RustBindingsServices.cpp b/Libraries/LibWeb/Bindings/RustBindingsServices.cppnew file mode 100644index 00000000000..4b890392b00--- /dev/null+++ b/Libraries/LibWeb/Bindings/RustBindingsServices.cpp@@ -0,0 +1,48 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <LibJS/HostClassBuilder.h>+#include <LibJS/Runtime/HostObject.h>+#include <LibJS/Runtime/Realm.h>+#include <LibWeb/Bindings/RustInterface.h>+#include <LibWeb/Bindings/WrapperWorld.h>++// What the Rust bindings of the interfaces implemented in Rust ask of LibWeb's C++ bindings, declared on the Rust+// side in Libraries/LibWeb/Bindings/Rust/src/bindings/services.rs.++namespace Web::Bindings {++constexpr JSHostClass web_bindings_rust_interface_wrapper_host_class = JS::make_host_class(JS_HOST_CLASS_OBJECT, "RustInterface"sv,+ nullptr, nullptr, nullptr, JS_HOST_CLASS_IS_PLATFORM_OBJECT);++extern "C" {++void* web_bindings_wrapper_world(void* realm, bool* is_main_world);+JSObject* web_bindings_rust_wrapper_for(void* realm, void* cell);+void web_bindings_set_rust_wrapper(void* realm, void* cell, JSObject* wrapper);++void* web_bindings_wrapper_world(void* realm, bool* is_main_world)+{+ auto& wrapper_world = host_defined_wrapper_world(*static_cast<JS::Realm*>(realm));+ *is_main_world = wrapper_world.is_main_world();+ return &wrapper_world;+}++JSObject* web_bindings_rust_wrapper_for(void* realm, void* cell)+{+ auto& js_realm = *static_cast<JS::Realm*>(realm);+ auto wrapper = host_defined_wrapper_world(js_realm).rust_wrapper_for(*static_cast<RustInterfaceCell*>(cell), js_realm);+ return JS::HostABI::object_to_abi(wrapper.ptr());+}++void web_bindings_set_rust_wrapper(void* realm, void* cell, JSObject* wrapper)+{+ auto& host_object = as<JS::HostObject>(*JS::HostABI::object_from_abi(wrapper));+ host_defined_wrapper_world(*static_cast<JS::Realm*>(realm)).set_rust_wrapper(*static_cast<RustInterfaceCell*>(cell), host_object);+}+}++}diff --git a/Libraries/LibWeb/Bindings/RustInterface.h b/Libraries/LibWeb/Bindings/RustInterface.hnew file mode 100644index 00000000000..4a41fe2c8d6--- /dev/null+++ b/Libraries/LibWeb/Bindings/RustInterface.h@@ -0,0 +1,22 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#pragma once++#include <LibGC/Cell.h>+#include <LibJS/HostObjectABI.h>++namespace Web::Bindings {++// The cell of an object of an interface that is implemented in Rust, which the wrappers of the object hold as their+// host data. The Rust bindings in Libraries/LibWeb/Bindings/Rust create these cells and know what they hold.+class RustInterfaceCell : public GC::ForeignCell {+};++// The class that the wrapper class of every interface implemented in Rust derives from.+extern "C" JSHostClass const web_bindings_rust_interface_wrapper_host_class;++}diff --git a/Libraries/LibWeb/Bindings/Wrappable.cpp b/Libraries/LibWeb/Bindings/Wrappable.cppindex 052b26a2715..c3374502e21 100644--- a/Libraries/LibWeb/Bindings/Wrappable.cpp+++ b/Libraries/LibWeb/Bindings/Wrappable.cpp@@ -282,6 +282,11 @@ void preserve_wrapper(Wrappable& wrappable, JS::HostObject& wrapper)bool wrapper_is_preserved(JS::HostObject const& wrapper){+ // An object of an interface implemented in Rust keeps its wrapper in the main world alive itself. No other+ // world keeps a wrapper of it alive.+ if (JS::is_host_instance_of(wrapper, web_bindings_rust_interface_wrapper_host_class))+ return host_defined_wrapper_world(wrapper.shape().realm()).is_main_world();+auto const* wrappable = wrappable_impl_from(&wrapper);if (!wrappable)return false;diff --git a/Libraries/LibWeb/Bindings/WrapperWorld.cpp b/Libraries/LibWeb/Bindings/WrapperWorld.cppindex 770200147bb..2c6c09ec235 100644--- a/Libraries/LibWeb/Bindings/WrapperWorld.cpp+++ b/Libraries/LibWeb/Bindings/WrapperWorld.cpp@@ -46,6 +46,7 @@ void WrapperWorld::detach()wrappable.clear_preserved_wrappers(*this);m_preserved_wrappables.clear();m_wrappers.clear();+ m_rust_wrappers.clear();}void WrapperWorld::register_preserved_wrappable(GCAllocatedWrappable& wrappable)@@ -103,6 +104,29 @@ void WrapperWorld::clear_wrapper(Wrappable& wrappable, JS::HostObject const& wra}}+GC::Ptr<JS::HostObject> WrapperWorld::rust_wrapper_for(RustInterfaceCell const& cell, JS::Realm& realm) const+{+ VERIFY(!is_main_world());+ auto* wrapper = m_rust_wrappers.get(cell);+ if (!wrapper)+ return nullptr;+ VERIFY(&wrapper->shape().realm() == &realm);+ return const_cast<JS::HostObject*>(wrapper);+}++void WrapperWorld::set_rust_wrapper(RustInterfaceCell& cell, JS::HostObject& wrapper)+{+ VERIFY(!is_main_world());+ VERIFY(!is_detached());+ VERIFY(wrapper.shape().realm().host_defined());+ VERIFY(&host_defined_wrapper_world(wrapper.shape().realm()) == this);+ VERIFY(JS::host_data_of(wrapper).ptr() == GC::as_cell(&cell));+ // NB: The entry of a wrapper that was collected stays in the map until the map prunes it. get() does not return+ // the wrapper of such an entry, and set() replaces it.+ VERIFY(!m_rust_wrappers.get(cell));+ m_rust_wrappers.set(cell, wrapper);+}+WrapperWorld& host_defined_wrapper_world(JS::Realm& realm){return *host_defined_of(realm).wrapper_world;diff --git a/Libraries/LibWeb/Bindings/WrapperWorld.h b/Libraries/LibWeb/Bindings/WrapperWorld.hindex ba7ac59ce76..b80d78bdf49 100644--- a/Libraries/LibWeb/Bindings/WrapperWorld.h+++ b/Libraries/LibWeb/Bindings/WrapperWorld.h@@ -15,6 +15,7 @@#include <LibGC/WeakHashSet.h>#include <LibGC/WeakInlines.h>#include <LibWeb/Bindings/PlatformObject.h>+#include <LibWeb/Bindings/RustInterface.h>#include <LibWeb/Bindings/Wrappable.h>#include <LibWeb/Export.h>#include <LibWeb/Forward.h>@@ -48,6 +49,11 @@ public:void clear_wrapper(Wrappable&, JS::HostObject const&);void register_preserved_wrappable(GCAllocatedWrappable&);+ // The wrappers of the objects of the interfaces implemented in Rust. An object keeps its wrapper in the main+ // world itself, so only non-main worlds hold them here.+ [[nodiscard]] GC::Ptr<JS::HostObject> rust_wrapper_for(RustInterfaceCell const&, JS::Realm&) const;+ void set_rust_wrapper(RustInterfaceCell&, JS::HostObject&);+private:virtual void finalize() override;@@ -58,6 +64,7 @@ private:// multiple realms must allocate one WrapperWorld cell per realm. Both sides// are weak; the cache cannot keep either implementation or wrapper alive.GC::WeakHashMap<Wrappable, JS::HostObject> m_wrappers;+ GC::WeakHashMap<RustInterfaceCell, JS::HostObject> m_rust_wrappers;GC::WeakHashSet<GCAllocatedWrappable> m_preserved_wrappables;};diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txtindex 65670c11778..308a04d041e 100644--- a/Libraries/LibWeb/CMakeLists.txt+++ b/Libraries/LibWeb/CMakeLists.txt@@ -25,6 +25,7 @@ set(SOURCESBindings/MainThreadVM.cppBindings/OptionConstructor.cppBindings/PlatformObject.cpp+ Bindings/RustBindingsServices.cppBindings/PrincipalHostDefined.cppBindings/Wrappable.cppBindings/WrapperWorld.cppdiff --git a/Libraries/LibWeb/Internals/Internals.cpp b/Libraries/LibWeb/Internals/Internals.cppindex 55c2e785f66..6a5cc15899f 100644--- a/Libraries/LibWeb/Internals/Internals.cpp+++ b/Libraries/LibWeb/Internals/Internals.cpp@@ -453,9 +453,10 @@ WebIDL::ExceptionOr<Utf16String> Internals::set_time_zone(Utf16String const& timbool Internals::wrapper_is_preserved(JS::Object& object){- if (!Bindings::wrappable_impl_from(&object))+ auto* platform_object = Bindings::as_platform_object(object);+ if (!platform_object)return false;- return Bindings::wrapper_is_preserved(*Bindings::as_platform_object(object));+ return Bindings::wrapper_is_preserved(*platform_object);}bool Internals::has_activity_root(JS::Object& object)diff --git a/Meta/Generators/libweb_bindings/rust_bindings.py b/Meta/Generators/libweb_bindings/rust_bindings.pyindex 54c293416af..4444486473a 100644--- a/Meta/Generators/libweb_bindings/rust_bindings.py+++ b/Meta/Generators/libweb_bindings/rust_bindings.py@@ -35,11 +35,11 @@ from Generators.libweb_bindings.rust_to_js_value import rust_to_js_valuefrom Generators.libweb_bindings.rust_to_js_value import write_dictionary_to_jsfrom Generators.libweb_bindings.rust_to_js_value import write_union_to_jsfrom Generators.libweb_bindings.rust_types import UnsupportedByRustBindings-from Generators.libweb_bindings.rust_types import rust_module_path+from Generators.libweb_bindings.rust_types import is_implemented_in_rust+from Generators.libweb_bindings.rust_types import rust_interface_pathfrom Generators.libweb_bindings.rust_types import rust_parameter_typefrom Generators.libweb_bindings.rust_types import rust_typefrom Generators.libweb_bindings.rust_usage import DefinitionUsage-from Generators.libweb_bindings.rust_usage import is_implemented_in_rustfrom Generators.libweb_bindings.wrappers import wrapper_namefrom Utils.utils import title_case_to_snake_casefrom Utils.webidl_parser import Interface@@ -62,11 +62,6 @@ def wrapper_host_class_symbol(interface: Interface) -> str:return f"web_bindings_{wrapper_name(interface)}_host_class"-def implementation_path(interface: Interface) -> str:- """The Rust path of the implementation: crate::encoding::text_encoder::TextEncoder for Encoding/TextEncoder.idl."""- return f"{rust_module_path(interface.path)}::{interface.name}"--def interface_name_values(intrinsics: List[Interface]) -> Dict[str, int]:"""The value of Web::Bindings::InterfaceName for each interface, which the Rust bindings pass the C++ bindings:the interfaces in the order of the intrinsics, from 1, as 0 is Unknown."""@@ -152,6 +147,7 @@ def write_cpp_implementation(includes.add("LibJS/Runtime/Error.h")includes.add("LibJS/Runtime/HostFunction.h")includes.add("LibJS/Runtime/Realm.h")+ includes.add("LibWeb/Bindings/RustInterface.h")includes.add_binding(interface.implemented_name)initialize_prototype = rust_entry_point_name(interface, "initialize_prototype")@@ -175,7 +171,7 @@ void {initialize_constructor}(JSVM*, void* realm, JSObject* constructor);// not an implementation object in their wrappable slot, so they need none of the hooks and flags through which a// wrapper keeps its implementation object alive, and the engine's own property caches apply to them.constexpr JSHostClass {wrapper_host_class_symbol(interface)} = JS::make_host_class(JS_HOST_CLASS_OBJECT, "{interface.name}"sv,- nullptr, nullptr, nullptr, JS_HOST_CLASS_IS_PLATFORM_OBJECT);+ &web_bindings_rust_interface_wrapper_host_class, nullptr, nullptr, JS_HOST_CLASS_IS_PLATFORM_OBJECT);void {interface.prototype_class}::initialize(JS::Realm& realm, JS::Object& object){{@@ -341,7 +337,7 @@ def implementation_method_signatures(def write_rust_interface(out: TextIO, context: GenerationContext, module: Module, interface: Interface, interface_name_value: int) -> None:- implementation = implementation_path(interface)+ implementation = rust_interface_path(interface)members = rust_members(interface)method_documentation = "".join(f"/// - `{signature}`\n" for signature in implementation_method_signatures(context, interface, members)@@ -356,18 +352,20 @@ def write_rust_interface(use ak::Utf16String;use libjs_rust::api::{{- EmbedderCell, EmbedderClass, EmbedderValue, ErrorKind, ErrorType, FunctionObject, Gc, JSHostClass, Object,- RawNativeFunctionResult, ThrowCompletionOr, TypedArrayBase, TypedArrayKind, Value, Vm, raw_native,+ EmbedderClass, ErrorKind, ErrorType, FunctionObject, Gc, JSHostClass, Object, RawNativeFunctionResult,+ ThrowCompletionOr, TypedArrayBase, TypedArrayKind, Value, Vm, raw_native,}};use crate::bindings::conversions::{{- BufferSource, BufferSourceRules, EmptyDictionary, FromJs, ToJs, UsvString, record_to_js, sequence_to_js,- to_boolean, to_buffer_source, to_dom_string, to_float, to_typed_array, to_unrestricted_double, to_usv_string,+ BufferSource, BufferSourceRules, EmptyDictionary, FromJs, ToJs, UsvString, record_to_js,+ rooted_sequence_to_js, sequence_to_js, to_boolean, to_buffer_source, to_dom_string, to_float, to_typed_array,+ to_unrestricted_double, to_usv_string,}};use crate::bindings::interface::{{- construct_arguments, create_wrapper, define_attribute, define_interface_object_properties, define_operation,- define_to_string_tag, entry_point_arguments, implementation_of, prototype_from_new_target,- set_interface_prototype_object_prototype, this_object,+ Interface, Ref, Wrapped, construct_arguments, construct_wrapper, define_attribute,+ define_interface_object_properties, define_operation, define_to_string_tag, entry_point_arguments,+ implementation_of, prototype_from_new_target, set_interface_prototype_object_prototype, this_object,+ to_interface,}};use crate::bindings::{{CallContext, WebIdlResult}};@@ -376,26 +374,28 @@ def write_rust_interface(/// Web::Bindings::InterfaceName::{interface.name}.pub(crate) const INTERFACE_NAME: u16 = {interface_name_value};- /// The class of the cells that hold the implementations of the interface.- static CELL_CLASS: EmbedderClass<Implementation> = EmbedderClass::new("{interface.name}");-- impl EmbedderValue for Implementation {{- const CLASS: &'static EmbedderClass<Self> = &CELL_CLASS;- }}+ /// The class of the cells of the objects of the interface.+ static CELL_CLASS: EmbedderClass<Wrapped<Implementation>> = EmbedderClass::new("{interface.name}");unsafe extern "C" {{static {wrapper_host_class_symbol(interface)}: JSHostClass;}}- fn wrapper_class() -> &'static JSHostClass {{- // SAFETY: LibWeb defines the class of the wrappers as constant data.- unsafe {{ &{wrapper_host_class_symbol(interface)} }}+ impl Interface for Implementation {{+ const CELL_CLASS: &'static EmbedderClass<Wrapped<Self>> = &CELL_CLASS;+ const INTERFACE_NAME: u16 = INTERFACE_NAME;+ const NAME: &'static str = "{interface.namespaced_name}";++ fn wrapper_class() -> &'static JSHostClass {{+ // SAFETY: LibWeb defines the class of the wrappers as constant data.+ unsafe {{ &{wrapper_host_class_symbol(interface)} }}+ }}}}- /// The implementation that an attribute or an operation runs on, and the context it runs in.- fn this_implementation(vm: &Vm) -> ThrowCompletionOr<(Gc<EmbedderCell<Implementation>>, CallContext<'_>)> {{- let (object, realm) = this_object(vm, wrapper_class(), "{interface.namespaced_name}")?;- Ok((implementation_of(object, &CELL_CLASS), CallContext::new(vm, realm)))+ /// The object that an attribute or an operation runs on, and the context it runs in.+ fn this_implementation(vm: &Vm) -> ThrowCompletionOr<(Ref<Implementation>, CallContext<'_>)> {{+ let (object, realm) = this_object(vm, Implementation::wrapper_class(), Implementation::NAME)?;+ Ok((implementation_of(object), CallContext::new(vm, realm)))}}""")@@ -547,8 +547,7 @@ def write_rust_constructor(f""" let mut cx = CallContext::new(vm, realm);let implementation =Implementation::{constructor.method}(&mut cx{arguments}).map_err(|exception| exception.throw(vm))?;- let implementation = CELL_CLASS.allocate(vm, implementation);- Ok(Value::from_object(create_wrapper(vm, realm, wrapper_class(), prototype, implementation)))+ Ok(Value::from_object(construct_wrapper(vm, realm, prototype, implementation)))}}""")@@ -576,10 +575,10 @@ pub(crate) mod definitions {use crate::bindings::CallContext;use crate::bindings::conversions::{BufferSource, BufferSourceRules, EmptyDictionary, FromJs, ToJs, UsvString, dictionary_member,- dictionary_object, record_to_js, sequence_to_js, to_boolean, to_buffer_source, to_dom_string, to_float,- to_typed_array, to_unrestricted_double, to_usv_string,+ dictionary_object, record_to_js, rooted_sequence_to_js, sequence_to_js, to_boolean, to_buffer_source,+ to_dom_string, to_float, to_typed_array, to_unrestricted_double, to_usv_string,};- use crate::bindings::interface::{create_dictionary_object, set_dictionary_member};+ use crate::bindings::interface::{Ref, create_dictionary_object, set_dictionary_member, to_interface};""")for name, directions in usage.rust_dictionaries.items():diff --git a/Meta/Generators/libweb_bindings/rust_members.py b/Meta/Generators/libweb_bindings/rust_members.pyindex d78b39069b4..1935025e572 100644--- a/Meta/Generators/libweb_bindings/rust_members.py+++ b/Meta/Generators/libweb_bindings/rust_members.py@@ -30,6 +30,12 @@ SUPPORTED_ATTRIBUTE_EXTENDED_ATTRIBUTES = {"NewObject", "SameObject"}SUPPORTED_OPERATION_EXTENDED_ATTRIBUTES = {"NewObject", "SameObject"}+def generated_function_stem(method: str) -> str:+ """What the names of the generated functions of a member start with: the method without what makes a reserved+ name usable as an identifier, which a longer name does not need."""+ return method.removeprefix("r#").removesuffix("_")++@dataclassclass RustAttribute:attribute: Attribute@@ -39,7 +45,7 @@ class RustAttribute:@propertydef getter_function(self) -> str:"""The generated native function of the getter."""- return f"{self.getter_method.removeprefix('r#')}_getter"+ return f"{generated_function_stem(self.getter_method)}_getter"@dataclass@@ -63,7 +69,7 @@ class RustOperationSet:@propertydef function(self) -> str:"""The generated native function that the prototype holds."""- return f"{rust_identifier(self.name).removeprefix('r#')}_function"+ return f"{generated_function_stem(rust_identifier(self.name))}_function"@propertydef length(self) -> int:diff --git a/Meta/Generators/libweb_bindings/rust_to_idl_value.py b/Meta/Generators/libweb_bindings/rust_to_idl_value.pyindex 2ea734c8d98..11e1d6ba485 100644--- a/Meta/Generators/libweb_bindings/rust_to_idl_value.py+++ b/Meta/Generators/libweb_bindings/rust_to_idl_value.py@@ -17,9 +17,12 @@ from Generators.libweb_bindings.rust_types import FLOATING_POINT_TYPESfrom Generators.libweb_bindings.rust_types import TYPED_ARRAY_NAMESfrom Generators.libweb_bindings.rust_types import UnsupportedByRustBindingsfrom Generators.libweb_bindings.rust_types import is_named_union+from Generators.libweb_bindings.rust_types import member_other_than_undefinedfrom Generators.libweb_bindings.rust_types import resolved_dictionaryfrom Generators.libweb_bindings.rust_types import runtime_union_typefrom Generators.libweb_bindings.rust_types import rust_dictionary_path+from Generators.libweb_bindings.rust_types import rust_interface+from Generators.libweb_bindings.rust_types import rust_interface_pathfrom Generators.libweb_bindings.rust_types import rust_typefrom Generators.libweb_bindings.rust_types import rust_union_pathfrom Generators.libweb_bindings.rust_types import rust_union_variant@@ -52,7 +55,17 @@ def rust_to_idl_value(name of the parameter or member that the value is of, which the errors of some conversions name."""rust_type(idl_type, context, what)name = idl_type.name- if idl_type.nullable or isinstance(idl_type, IDLParameterizedType):+ # https://webidl.spec.whatwg.org/#js-nullable-type+ if idl_type.nullable:+ inner_type = idl_type.without_nullable()+ if member_other_than_undefined(inner_type) is not None:+ raise UnsupportedByRustBindings(+ f"{what} has the type {idl_type}, whose inner type includes undefined, which the Rust bindings do "+ "not convert to yet"+ )+ inner = rust_to_idl_value(inner_type, parameter_attributes, value, identifier, context, what)+ return f"if {value}.is_nullish() {{ Ok(None) }} else {{ {inner}.map(Some) }}"+ if isinstance(idl_type, IDLParameterizedType):raise UnsupportedByRustBindings(f"{what} has the type {idl_type}, which the Rust bindings do not convert to yet")@@ -71,6 +84,9 @@ def rust_to_idl_value(return f'to_typed_array(vm, {value}, TypedArrayKind::{name}, "{name}", {rules})'if runtime_union_type(idl_type, context) == "BufferSource":return f"to_buffer_source(vm, {value}, {buffer_source_rules(idl_type, parameter_attributes)})"+ interface = rust_interface(idl_type, context)+ if interface is not None:+ return f"to_interface::<{rust_interface_path(interface)}>(vm, {value})"dictionary = resolved_dictionary(idl_type, context)if dictionary is not None:return f"<{rust_dictionary_path(dictionary, context)}>::from_js(vm, {value})"diff --git a/Meta/Generators/libweb_bindings/rust_to_js_value.py b/Meta/Generators/libweb_bindings/rust_to_js_value.pyindex 7d1e4f088f8..b70ea2e2dfd 100644--- a/Meta/Generators/libweb_bindings/rust_to_js_value.py+++ b/Meta/Generators/libweb_bindings/rust_to_js_value.py@@ -14,6 +14,7 @@ from Generators.libweb_bindings.rust_names import rust_identifierfrom Generators.libweb_bindings.rust_names import rust_local_namefrom Generators.libweb_bindings.rust_types import member_other_than_undefinedfrom Generators.libweb_bindings.rust_types import rust_dictionary_path+from Generators.libweb_bindings.rust_types import rust_interfacefrom Generators.libweb_bindings.rust_types import rust_typefrom Generators.libweb_bindings.rust_types import rust_union_pathfrom Generators.libweb_bindings.rust_types import rust_union_variant@@ -47,7 +48,12 @@ def rust_to_js_value(None => Ok(Value::UNDEFINED),}}"""if isinstance(idl_type, IDLParameterizedType) and idl_type.name == "sequence":- return f"sequence_to_js({call_context}, {expression}, |value| {inner(idl_type.parameters[0])})"+ element_type = idl_type.parameters[0]+ # NB: The conversion of an object of an interface can create its wrapper, and the elements after it must+ # live through that.+ holds_cells = rust_interface(element_type.without_nullable(), context) is not None+ function = "rooted_sequence_to_js" if holds_cells else "sequence_to_js"+ return f"{function}({call_context}, {expression}, |value| {inner(element_type)})"if isinstance(idl_type, IDLParameterizedType) and idl_type.name == "record":return f"record_to_js({call_context}, {expression}, |value| {inner(idl_type.parameters[1])})"return f"{expression}.to_js({call_context})"diff --git a/Meta/Generators/libweb_bindings/rust_types.py b/Meta/Generators/libweb_bindings/rust_types.pyindex 5653c435235..93985d8ac83 100644--- a/Meta/Generators/libweb_bindings/rust_types.py+++ b/Meta/Generators/libweb_bindings/rust_types.py@@ -16,6 +16,7 @@ from Utils.webidl_parser import Dictionaryfrom Utils.webidl_parser import IDLParameterizedTypefrom Utils.webidl_parser import IDLTypefrom Utils.webidl_parser import IDLUnionType+from Utils.webidl_parser import Interfacefrom Utils.webidl_parser import OperationParameter# The typed arrays, whose names are the variants of the runtime's TypedArrayKind.@@ -50,10 +51,22 @@ class UnsupportedByRustBindings(Exception):pass+def is_implemented_in_rust(interface: Optional[Interface]) -> bool:+ return interface is not None and interface.extended_attributes.get("ImplementedIn") == "Rust"++def resolved_dictionary(idl_type: IDLType, context: GenerationContext) -> Optional[Dictionary]:return context.dictionaries.get(idl_type.name)+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)):+ return None+ interface = context.interfaces.get(idl_type.name)+ return interface if is_implemented_in_rust(interface) else None++def rust_module_path(idl_path: Path) -> str:"""The Rust module of the hand-written definitions of an IDL file, which follows from its path:Encoding/TextEncoder.idl names crate::encoding::text_encoder."""@@ -62,6 +75,12 @@ def rust_module_path(idl_path: Path) -> str:return f"crate::{title_case_to_snake_case(namespace)}::{title_case_to_snake_case(idl_path.stem)}"+def rust_interface_path(interface: Interface) -> str:+ """The Rust path of the implementation of an interface: crate::encoding::text_encoder::TextEncoder for+ Encoding/TextEncoder.idl."""+ return f"{rust_module_path(interface.path)}::{interface.name}"++def rust_dictionary_path(dictionary: Dictionary, context: GenerationContext) -> str:"""The Rust path of the struct of a dictionary, which is in the module of the IDL file that defines thedictionary: crate::encoding::text_encoder::TextEncoderEncodeIntoResult."""@@ -162,6 +181,9 @@ def rust_type(idl_type: IDLType, context: GenerationContext, what: str) -> str:return "Gc<TypedArrayBase>"if context.callback_function(idl_type) is not None:return "Gc<FunctionObject>"+ interface = rust_interface(idl_type, context)+ if interface is not None:+ return f"Ref<{rust_interface_path(interface)}>"dictionary = resolved_dictionary(idl_type, context)if dictionary is not None:return rust_dictionary_path(dictionary, context)diff --git a/Meta/Generators/libweb_bindings/rust_usage.py b/Meta/Generators/libweb_bindings/rust_usage.pyindex 5b0c10981d5..7779c524116 100644--- a/Meta/Generators/libweb_bindings/rust_usage.py+++ b/Meta/Generators/libweb_bindings/rust_usage.py@@ -10,11 +10,11 @@ from dataclasses import dataclassfrom typing import Dictfrom typing import Iterablefrom typing import List-from typing import Optionalfrom typing import Setfrom Generators.libweb_bindings.context import GenerationContextfrom Generators.libweb_bindings.rust_members import rust_members+from 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_typefrom Utils.webidl_parser import Dictionary@@ -24,10 +24,6 @@ from Utils.webidl_parser import Interfacefrom Utils.webidl_parser import Module-def is_implemented_in_rust(interface: Optional[Interface]) -> bool:- return interface is not None and interface.extended_attributes.get("ImplementedIn") == "Rust"--def types_named_by_interface(interface: Interface) -> List[IDLType]:"""Every type that the members of the interface name, which the bindings of the interface convert."""types = []