Truly independent web browser
Meta+LibWeb: Support more of WebIDL in the Rust bindings
Andreas Kling8846c94d5462
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/interface.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/interface.rsindex 62a48155334..d5477186e33 100644--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/interface.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/interface.rs@@ -31,8 +31,8 @@ use libjs_rust::api::{use crate::bindings::CallContext;use crate::bindings::realm_data::wrapper_world_of;use crate::bindings::services::{- web_bindings_ensure_web_constructor, web_bindings_ensure_web_prototype, web_bindings_rejected_promise,- web_bindings_rust_wrapper_for, web_bindings_set_rust_wrapper,+ web_bindings_ensure_web_constructor, web_bindings_ensure_web_prototype, web_bindings_realm_is_window,+ web_bindings_rejected_promise, 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@@ -298,6 +298,25 @@ pub(crate) unsafe fn cell_from_abi<T: Interface>(cell: *mut c_void) -> Ref<T> {unsafe { T::CELL_CLASS.downcast(cell) }.expect("C++ passes the cell of an object of the interface")}+/// The object of the interface whose cell LibWeb's C++ code holds, if the cell is that of an object of exactly the+/// interface: C++ names an object of an interface that others inherit from by that interface, whichever it is.+///+/// # Safety+///+/// `cell` must be a live cell of an object of an interface implemented in Rust.+pub(crate) unsafe fn cell_if_abi<T: Interface>(cell: *mut c_void) -> Option<Ref<T>> {+ let cell = NonNull::new(cell).expect("C++ passes the cell of an object");+ // SAFETY: The caller passes a live cell of an embedder class.+ unsafe { T::CELL_CLASS.downcast(cell) }+}++/// Whether the global object of the realm is a Window, which the members that only a Window has, [Exposed=Window] on+/// an interface exposed elsewhere as well, are defined for.+pub(crate) fn realm_is_window(realm: Gc<Realm>) -> bool {+ // SAFETY: The realm is live.+ unsafe { web_bindings_realm_is_window(realm.as_ptr().cast()) }+}+/// What an operation that returns a promise type returns in place of throwing: a promise rejected with what its/// steps threw, https://webidl.spec.whatwg.org/#dfn-create-operation-functionpub(crate) fn rejected_promise(vm: &Vm, throw: Throw) -> Value {@@ -458,6 +477,27 @@ pub(crate) fn define_operation();}+/// Defines the properties of a value iterator on the interface prototype object of an interface that supports indexed+/// properties, which are those of %Array.prototype%, https://webidl.spec.whatwg.org/#define-the-iteration-methods+pub(crate) fn define_value_iterator_properties(vm: &Vm, realm: Gc<Realm>, prototype: Gc<Object>) {+ let array_prototype = realm.intrinsics().array_prototype(vm);+ let names = &vm.names;+ prototype.define_direct_property(+ vm,+ &PropertyKey::from(vm.well_known_symbols().iterator),+ array_prototype.get_without_side_effects(vm, &names.values),+ PropertyAttributes::new(Attribute::CONFIGURABLE | Attribute::WRITABLE),+ );+ for name in [&names.entries, &names.keys, &names.values, &names.forEach] {+ prototype.define_direct_property(+ vm,+ name,+ array_prototype.get_without_side_effects(vm, name),+ PropertyAttributes::new(Attribute::WRITABLE | Attribute::ENUMERABLE | Attribute::CONFIGURABLE),+ );+ }+}+/// Records a regular attribute or operation that the interface does not implement on the interface prototype object,/// so that a read of it is reported, without the property being there for script.pub(crate) fn define_unimplemented_property(vm: &Vm, prototype: Gc<Object>, name: &str) {diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/services.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/services.rsindex 0eb710d1ae9..b35482b4e67 100644--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/services.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/services.rs@@ -29,6 +29,9 @@ unsafe extern "C" {/// 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);+ /// Whether the global object of the realm is a Window.+ pub(crate) fn web_bindings_realm_is_window(realm: *mut c_void) -> bool;+/// Whether the object is a wrapper of an object that implements the interface, a Web::Bindings::InterfaceName of/// an interface that LibWeb implements in C++.pub(crate) fn web_bindings_object_implements_interface(object: *mut c_void, interface_name: u16) -> bool;diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/structured_data.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/structured_data.rsindex afe99e2bbe3..558e10530fc 100644--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/structured_data.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/structured_data.rs@@ -28,8 +28,17 @@ use crate::bindings::{CallContext, WebIdlResult};unsafe extern "C" {fn web_bindings_serialize_value(serialized: *mut c_void, value: u64) -> RawNativeFunctionResult;fn web_bindings_serialize_u32(serialized: *mut c_void, value: u32);+ fn web_bindings_serialize_f64(serialized: *mut c_void, value: f64);+ fn web_bindings_serialize_bool(serialized: *mut c_void, value: bool);fn web_bindings_deserialize_value(serialized: *mut c_void) -> RawNativeFunctionResult;fn web_bindings_deserialize_u32(serialized: *mut c_void, out_value: &mut u32) -> RawNativeFunctionResult;+ fn web_bindings_deserialize_f64(serialized: *mut c_void, out_value: &mut f64) -> RawNativeFunctionResult;+ fn web_bindings_deserialize_bool(serialized: *mut c_void, out_value: &mut bool) -> RawNativeFunctionResult;+ fn web_bindings_serialize_inline_object_header(serialized: *mut c_void, interface_name: u16);+ fn web_bindings_deserialize_inline_object_header(+ serialized: *mut c_void,+ interface_name: u16,+ ) -> RawNativeFunctionResult;}/// The record of a structured serialization, which the serialization steps of an object write to: a@@ -57,6 +66,30 @@ impl SerializationWriter<'_> {// SAFETY: The writer is lent for the steps.unsafe { web_bindings_serialize_u32(self.raw.as_ptr(), value) };}++ pub(crate) fn write_f64(&mut self, value: f64) {+ // SAFETY: The writer is lent for the steps.+ unsafe { web_bindings_serialize_f64(self.raw.as_ptr(), value) };+ }++ pub(crate) fn write_bool(&mut self, value: bool) {+ // SAFETY: The writer is lent for the steps.+ unsafe { web_bindings_serialize_bool(self.raw.as_ptr(), value) };+ }++ /// Writes the record of a serializable object in place, as StructuredSerializeInternal writes it, but without+ /// giving the object a position in the memory of the serialization, which a format that predates the+ /// sub-serialization of the object has none for.+ pub(crate) fn write_object_in_place<T: Serializable>(+ &mut self,+ cx: &mut CallContext,+ object: &T,+ for_storage: bool,+ ) -> WebIdlResult<()> {+ // SAFETY: The writer is lent for the steps.+ unsafe { web_bindings_serialize_inline_object_header(self.raw.as_ptr(), T::INTERFACE_NAME) };+ object.serialization_steps(cx, self, for_storage)+ }}/// The record of a structured deserialization, which the deserialization steps of an object read from: a@@ -86,6 +119,28 @@ impl SerializationReader<'_> {unsafe { web_bindings_deserialize_u32(self.raw.as_ptr(), &mut value) }.into_completion()?;Ok(value)}++ pub(crate) fn read_f64(&mut self) -> WebIdlResult<f64> {+ let mut value = 0.0;+ // SAFETY: The reader is lent for the steps.+ unsafe { web_bindings_deserialize_f64(self.raw.as_ptr(), &mut value) }.into_completion()?;+ Ok(value)+ }++ /// Reads what SerializationWriter::write_object_in_place() writes.+ pub(crate) fn read_object_in_place<T: Serializable>(&mut self, cx: &mut CallContext) -> WebIdlResult<T> {+ // SAFETY: The reader is lent for the steps.+ unsafe { web_bindings_deserialize_inline_object_header(self.raw.as_ptr(), T::INTERFACE_NAME) }+ .into_completion()?;+ T::deserialization_steps(cx, self)+ }++ pub(crate) fn read_bool(&mut self) -> WebIdlResult<bool> {+ let mut value = false;+ // SAFETY: The reader is lent for the steps.+ unsafe { web_bindings_deserialize_bool(self.raw.as_ptr(), &mut value) }.into_completion()?;+ Ok(value)+ }}/// An interface that is serializable, [Serializable] in its IDL.diff --git a/Libraries/LibWeb/Bindings/RustBindingsServices.cpp b/Libraries/LibWeb/Bindings/RustBindingsServices.cppindex d8e2c0a2ef2..af37f580cc1 100644--- a/Libraries/LibWeb/Bindings/RustBindingsServices.cpp+++ b/Libraries/LibWeb/Bindings/RustBindingsServices.cpp@@ -12,6 +12,7 @@#include <LibWeb/Bindings/RustSerialization.h>#include <LibWeb/Bindings/Wrappable.h>#include <LibWeb/Bindings/WrapperWorld.h>+#include <LibWeb/HTML/Scripting/Environments.h>#include <LibWeb/HTML/StructuredSerialize.h>#include <LibWeb/WebIDL/DOMException.h>#include <LibWeb/WebIDL/ExceptionOrUtils.h>@@ -37,6 +38,14 @@ GC::Ref<JS::HostObject> wrap_rust_interface_object(WrapperWorld& wrapper_world,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);+RustInterfaceCell* rust_interface_cell_of_wrapper(JS::Object& object, JSHostClass const& wrapper_host_class)+{+ auto* wrapper = as_if<JS::HostObject>(object);+ if (!wrapper || &wrapper->host_class() != &wrapper_host_class)+ return nullptr;+ return GC::static_cell_cast<RustInterfaceCell>(JS::host_data_of(object).ptr());+}+bool rust_interface_object_implements_interface(JS::Object const& object, StringView interface_name){if (!JS::is_host_instance_of(object, web_bindings_rust_interface_wrapper_host_class))@@ -57,18 +66,36 @@ JSCompletion completion_to_abi(JS::Realm& realm, WebIDL::ExceptionOr<JS::Value>return JS::HostABI::completion_to_abi(JS::ThrowCompletionOr<JS::Value> { result.release_value() });}+// A value of the type that the record of a structured deserialization holds next.+template<typename T>+static JSCompletion deserialize_plain_value(RustSerializationReader* reader, T* out_value)+{+ auto value = HTML::decode_or_throw_data_clone_error<T>(reader->realm, reader->serialized);+ if (value.is_exception())+ return completion_to_abi(reader->realm, value.exception());+ *out_value = value.release_value();+ return completion_to_abi(reader->realm, JS::js_undefined());+}+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);JSObject* web_bindings_rejected_promise(void* current_realm, JSValue this_value, JSValue reason);+bool web_bindings_realm_is_window(void* realm);bool web_bindings_object_implements_interface(JSObject* object, u16 interface_name);JSObject* web_bindings_create_dom_exception(void* realm, ReadonlyBytes name, FlatPtr message);JSCompletion web_bindings_serialize_value(RustSerializationWriter*, JSValue);void web_bindings_serialize_u32(RustSerializationWriter*, u32);+void web_bindings_serialize_f64(RustSerializationWriter*, double);+void web_bindings_serialize_bool(RustSerializationWriter*, bool);JSCompletion web_bindings_deserialize_value(RustSerializationReader*);JSCompletion web_bindings_deserialize_u32(RustSerializationReader*, u32* out_value);+JSCompletion web_bindings_deserialize_f64(RustSerializationReader*, double* out_value);+JSCompletion web_bindings_deserialize_bool(RustSerializationReader*, bool* out_value);+void web_bindings_serialize_inline_object_header(RustSerializationWriter*, u16 interface_name);+JSCompletion web_bindings_deserialize_inline_object_header(RustSerializationReader*, u16 interface_name);void* web_bindings_wrapper_world(void* realm, bool* is_main_world){@@ -90,6 +117,11 @@ void web_bindings_set_rust_wrapper(void* realm, void* cell, JSObject* wrapper)host_defined_wrapper_world(*static_cast<JS::Realm*>(realm)).set_rust_wrapper(*static_cast<RustInterfaceCell*>(cell), host_object);}+bool web_bindings_realm_is_window(void* realm)+{+ return HTML::window_from_global_object(static_cast<JS::Realm*>(realm)->global_object());+}+bool web_bindings_object_implements_interface(JSObject* object, u16 interface_name){auto* wrappable = wrappable_impl_from(JS::HostABI::object_from_abi(object));@@ -118,6 +150,16 @@ void web_bindings_serialize_u32(RustSerializationWriter* writer, u32 value)writer->serialized.encode(value);}+void web_bindings_serialize_f64(RustSerializationWriter* writer, double value)+{+ writer->serialized.encode(value);+}++void web_bindings_serialize_bool(RustSerializationWriter* writer, bool value)+{+ writer->serialized.encode(value);+}+// StructuredDeserialize of a value that the serialized form of an object holds, https://html.spec.whatwg.org/multipage/structured-data.html#sub-deserializationJSCompletion web_bindings_deserialize_value(RustSerializationReader* reader){@@ -126,11 +168,46 @@ JSCompletion web_bindings_deserialize_value(RustSerializationReader* reader)JSCompletion web_bindings_deserialize_u32(RustSerializationReader* reader, u32* out_value){- auto value = HTML::decode_or_throw_data_clone_error<u32>(reader->realm, reader->serialized);- if (value.is_exception())- return completion_to_abi(reader->realm, value.exception());- *out_value = value.release_value();- return completion_to_abi(reader->realm, JS::js_undefined());+ return deserialize_plain_value(reader, out_value);+}++JSCompletion web_bindings_deserialize_f64(RustSerializationReader* reader, double* out_value)+{+ return deserialize_plain_value(reader, out_value);+}++JSCompletion web_bindings_deserialize_bool(RustSerializationReader* reader, bool* out_value)+{+ return deserialize_plain_value(reader, out_value);+}++// The record of a serializable object of the interface as StructuredSerializeInternal starts it, for an object that+// steps serialize in place, without a position in the memory of the serialization.+void web_bindings_serialize_inline_object_header(RustSerializationWriter* writer, u16 interface_name)+{+ writer->serialized.encode(to_underlying(HTML::ValueTag::SerializableObject));+ writer->serialized.encode(static_cast<InterfaceName>(interface_name));+ if (writer->serialized.type() == HTML::SerializationType::Storage)+ writer->serialized.encode(HTML::serializable_payload_version);+}++// Reads what web_bindings_serialize_inline_object_header() writes, and throws a "DataCloneError" DOMException if it is+// not the start of the record of a serializable object of the interface.+JSCompletion web_bindings_deserialize_inline_object_header(RustSerializationReader* reader, u16 interface_name)+{+ auto result = [&]() -> WebIDL::ExceptionOr<JS::Value> {+ auto tag = TRY(HTML::decode_or_throw_data_clone_error<u8>(reader->realm, reader->serialized));+ auto name = TRY(HTML::decode_or_throw_data_clone_error<InterfaceName>(reader->realm, reader->serialized));+ if (tag != to_underlying(HTML::ValueTag::SerializableObject) || name != static_cast<InterfaceName>(interface_name))+ return WebIDL::DataCloneError::create(reader->realm, "Unexpected serializable object"_utf16);+ if (reader->serialized.type() == HTML::SerializationType::Storage) {+ auto version = TRY(HTML::decode_or_throw_data_clone_error<u64>(reader->realm, reader->serialized));+ if (version != HTML::serializable_payload_version)+ return WebIDL::DataCloneError::create(reader->realm, "Unsupported serializable payload version"_utf16);+ }+ return JS::js_undefined();+ }();+ return completion_to_abi(reader->realm, move(result));}JSObject* web_bindings_rejected_promise(void* current_realm, JSValue this_value, JSValue reason)diff --git a/Libraries/LibWeb/Bindings/RustInterface.h b/Libraries/LibWeb/Bindings/RustInterface.hindex e659aa077b7..b1fafa84f84 100644--- a/Libraries/LibWeb/Bindings/RustInterface.h+++ b/Libraries/LibWeb/Bindings/RustInterface.h@@ -51,6 +51,10 @@ concept RustInterfaceHandle = IsBaseOf<RustInterfaceCell, T> && GC::IsForeignCelWEB_API GC::Ref<JS::HostObject> wrap_rust_interface_object(WrapperWorld&, JS::Realm& preferred_realm, InterfaceName, RustInterfaceCell&);+// The cell of the object, if it is a wrapper of exactly the interface whose wrappers are of the class, and not of an+// interface that inherits from it.+WEB_API RustInterfaceCell* rust_interface_cell_of_wrapper(JS::Object&, JSHostClass const& wrapper_host_class);+// Whether the object is a wrapper of an object of an interface implemented in Rust that is or inherits from the// interface with the name, as Wrappable::implements_interface() says for the objects of the interfaces implemented in// C++.@@ -70,8 +74,8 @@ template<RustInterfaceHandle T>return wrap_rust_interface_object(wrapper_world, preferred_realm, T::s_interface_name, *object);}-// The object that a wrapper of the interface wraps. An interface implemented in Rust that others inherit from has-// objects whose cells are of several kinds, which no C++ class names, so Impl names an interface without those.+// The object that a wrapper of the interface wraps. The cell of an object of an interface implemented in Rust that+// others inherit from can be that of an object of any of them, which the C ABI of the interface accepts.template<RustInterfaceHandle Impl, typename Object>[[nodiscard]] CopyConst<Object, Impl>* impl_from(Object* object){diff --git a/Meta/Generators/libweb_bindings/attributes.py b/Meta/Generators/libweb_bindings/attributes.pyindex e3ab4549e36..227e44ddea1 100644--- a/Meta/Generators/libweb_bindings/attributes.py+++ b/Meta/Generators/libweb_bindings/attributes.py@@ -70,6 +70,10 @@ def validate_direct_getter(context: GenerationContext, interface: Interface, atttarget_interface = context.interface(resolved_type)if target_interface is None or target_interface.is_callback_interface:raise RuntimeError(f"{description} must have an interface type")+ if target_interface.extended_attributes.get("ImplementedIn") == "Rust":+ # NB: The engine reads the wrapper of a direct getter's object as a Wrappable keeps it, and the object of an+ # interface implemented in Rust is a cell that keeps its wrapper elsewhere.+ raise RuntimeError(f"{description} cannot return {target_interface.name}, which is implemented in Rust")if not cpp_type_for_idl_type_details(resolved_type, context).gc_ref_target_type:raise RuntimeError(f"{description} must convert from a GC pointer")diff --git a/Meta/Generators/libweb_bindings/rust_bindings.py b/Meta/Generators/libweb_bindings/rust_bindings.pyindex 275616316a0..46cbb3a4f58 100644--- a/Meta/Generators/libweb_bindings/rust_bindings.py+++ b/Meta/Generators/libweb_bindings/rust_bindings.py@@ -23,10 +23,13 @@ from typing import TextIOfrom Generators.libweb_bindings.context import GenerationContextfrom Generators.libweb_bindings.includes import GeneratedIncludes+from Generators.libweb_bindings.operations import idl_type_is_json_type+from Generators.libweb_bindings.operations import operation_is_default_to_jsonfrom Generators.libweb_bindings.rust_members import RustAttributefrom Generators.libweb_bindings.rust_members import RustConstructorfrom Generators.libweb_bindings.rust_members import RustMembersfrom Generators.libweb_bindings.rust_members import RustOperation+from Generators.libweb_bindings.rust_members import RustOperationSetfrom Generators.libweb_bindings.rust_members import rust_membersfrom Generators.libweb_bindings.rust_names import rust_identifierfrom Generators.libweb_bindings.rust_names import rust_local_name@@ -62,6 +65,9 @@ SUPPORTED_INTERFACE_EXTENDED_ATTRIBUTES = {"Experimental","Exposed","ImplementedIn",+ # NB: The C++ bindings expose the interface object under the aliases on the Window, whatever the language of the+ # interface.+ "LegacyWindowAlias",# NB: The C++ bindings only leave the interface object of such an interface off the global object."LegacyNoInterfaceObject","NavigatorCompatibilityMode",@@ -164,6 +170,12 @@ def write_cpp_implementation(initialize_prototype = rust_entry_point_name(interface, "initialize_prototype")initialize_constructor = rust_entry_point_name(interface, "initialize_constructor")construct = rust_entry_point_name(interface, "construct")+ supports_indexed_properties = rust_members(interface).indexed_property_getter is not None+ if supports_indexed_properties and inheriting_interfaces(interface, context):+ raise UnsupportedByRustBindings(+ f"{interface.path}: {interface.name} supports indexed properties and others inherit from it, which the "+ "Rust bindings do not handle yet"+ )out.write(f"""extern "C" {{@@ -172,10 +184,16 @@ void {initialize_prototype}(JSVM*, void* realm, JSObject* prototype);void {initialize_constructor}(JSVM*, void* realm, JSObject* constructor);""")+ if supports_indexed_properties:+ out.write(+ f"bool {item_value_entry_point(interface)}(JSVM*, void* realm, JSObject* wrapper, size_t index, "+ "JSValue* out_value);\n"+ )if interface.constructors:out.write(f"JSCompletion {construct}(JSVM*, JSObject* constructor, JSObject* new_target);\n")- out.write(- f"""+ if not supports_indexed_properties:+ out.write(+ f"""}}// The wrappers are platform objects with ordinary internal methods: their implementation is a cell in their host data,@@ -183,7 +201,37 @@ void {initialize_constructor}(JSVM*, void* realm, JSObject* constructor);// 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,&{parent_host_class}, nullptr, nullptr, JS_HOST_CLASS_IS_PLATFORM_OBJECT);+"""+ )+ else:+ includes.add("LibWeb/Bindings/PlatformObject.h")+ legacy_info = f"{wrapper_name(interface)}_legacy_platform_object_info"+ out.write(+ f"""+}}++static Optional<JS::Value> {wrapper_name(interface)}_item_value(JS::HostObject const& wrapper, WrapperWorld&, JS::Realm& realm, size_t index)+{{+ JSValue value {{}};+ if (!{item_value_entry_point(interface)}(JS::HostABI::vm_to_abi(realm.vm()), &realm, JS::HostABI::object_to_abi(const_cast<JS::HostObject*>(&wrapper)), index, &value))+ return {{}};+ return JS::HostABI::value_from_abi(value);+}}+static constexpr LegacyPlatformObjectInfo {legacy_info} {{+ .supports_indexed_properties = true,+ .item_value = {wrapper_name(interface)}_item_value,+}};++// The wrappers are legacy platform objects, whose indexed properties the Rust bindings read: their implementation is a+// cell in their host data, not an implementation object in their wrappable slot.+constexpr JSHostClass {wrapper_host_class_symbol(interface)} = JS::make_host_class(JS_HOST_CLASS_OBJECT, "{interface.name}"sv,+ &{parent_host_class}, &legacy_platform_object_hooks, &{legacy_info},+ platform_object_host_class_flags | JS_HOST_CLASS_NOT_CACHEABLE_FOR_INDEXED_PROPERTY_ABSENCE);+"""+ )+ out.write(+ f"""void {interface.prototype_class}::initialize(JS::Realm& realm, JS::Object& object){{{initialize_prototype}(JS::HostABI::vm_to_abi(realm.vm()), &realm, JS::HostABI::object_to_abi(&object));@@ -358,9 +406,10 @@ def implementation_method_signatures(for attribute in members.attributes:what = f"{interface.name}.{attribute.attribute.name}"attribute_type = rust_type(attribute.attribute.type, context, what)- signatures.append(- f"fn {attribute.getter_method}(&self, cx: &mut CallContext) -> WebIdlResult<{attribute_type}>"- )+ if not attribute.attribute.inherit:+ signatures.append(+ f"fn {attribute.getter_method}(&self, cx: &mut CallContext) -> WebIdlResult<{attribute_type}>"+ )if attribute.setter_method is not None:signatures.append(f"fn {attribute.setter_method}(&self, cx: &mut CallContext, value: {attribute_type}) -> "@@ -368,12 +417,32 @@ def implementation_method_signatures()for operation_set in members.operation_sets:for overload in operation_set.overloads:+ if overload.is_default_to_json:+ continuewhat = f"{interface.name}.{operation_set.name}()"parameters = parameter_list(what, overload.operation.parameters)signatures.append(f"fn {overload.method}(&self, cx: &mut CallContext{parameters}) -> "f"WebIdlResult<{rust_result_type(overload.operation.return_type, context, what)}>")+ if members.stringifier is not None:+ signatures.append(f"fn {members.stringifier.method}(&self, cx: &mut CallContext) -> WebIdlResult<Utf16String>")+ if members.indexed_property_getter is not None:+ getter = members.indexed_property_getter.operation+ what = f"{interface.name}.{getter.operation.name}()"+ parameters = parameter_list(what, getter.operation.parameters)+ signatures.append(+ f"fn {getter.method}(&self, cx: &mut CallContext{parameters}) -> "+ f"WebIdlResult<{rust_result_type(getter.operation.return_type, context, what)}>"+ )+ for operation_set in members.static_operation_sets:+ for overload in operation_set.overloads:+ what = f"{interface.name}.{operation_set.name}()"+ parameters = parameter_list(what, overload.operation.parameters)+ signatures.append(+ f"fn {overload.method}(cx: &mut CallContext{parameters}) -> "+ f"WebIdlResult<{rust_result_type(overload.operation.return_type, context, what)}>"+ )return signatures@@ -398,8 +467,8 @@ def write_rust_interface(use ak::Utf16String;use libjs_rust::api::{{ArrayBuffer, DataView, EmbedderClass, ErrorKind, ErrorType, FunctionObject, Gc, JSHostClass, Object,- RawNativeFunctionResult, ThrowCompletionOr, TypedArrayBase, TypedArrayKind, Value, Vm, is_host_instance_of,- raw_native,+ PropertyKey, RawNativeFunctionResult, ThrowCompletionOr, TypedArrayBase, TypedArrayKind, Value, Vm,+ is_host_instance_of, raw_native,}};use crate::bindings::conversions::{{@@ -411,11 +480,11 @@ def write_rust_interface(to_unsigned_long_enforcing_range, to_unsigned_long_long, to_unsigned_long_long_enforcing_range, to_usv_string,}};use crate::bindings::interface::{{- Inherits, Interface, Ref, Wrapped, cell_class, construct_arguments, construct_wrapper, define_attribute,- define_cached_attribute, define_constants, define_interface_object_properties, define_operation,- define_to_string_tag, define_unimplemented_property, entry_point_arguments, implementation_if,- implementation_of, prototype_from_new_target, rejected_promise, set_interface_prototype_object_prototype,- this_object, to_interface,+ Inherits, Interface, Ref, Wrapped, cell_class, construct_arguments, construct_wrapper, create_dictionary_object,+ define_attribute, define_cached_attribute, define_constants, define_interface_object_properties,+ define_operation, define_to_string_tag, define_unimplemented_property, define_value_iterator_properties,+ entry_point_arguments, implementation_if, implementation_of, prototype_from_new_target, realm_is_window,+ rejected_promise, set_dictionary_member, set_interface_prototype_object_prototype, this_object, to_interface,}};use crate::bindings::structured_data;use crate::bindings::{{CallContext, WebIdlResult}};@@ -463,11 +532,14 @@ def write_rust_interface(for attribute in members.attributes:name = attribute.attribute.nameconversion = rust_to_js_value(attribute.attribute.type, "result", "&cx", context, f"{interface.name}.{name}")+ call = f"Implementation::{attribute.getter_method}(&implementation, &mut cx)"+ if attribute.attribute.inherit:+ call = inherited_attribute_getter_call(context, interface, attribute)out.write(f"""- fn {attribute.getter_function}(vm: &Vm) -> ThrowCompletionOr<Value> {{+ pub(super) fn {attribute.getter_function}(vm: &Vm) -> ThrowCompletionOr<Value> {{let (implementation, mut cx) = this_implementation(vm)?;- let result = Implementation::{attribute.getter_method}(&implementation, &mut cx)+ let result = {call}.map_err(|exception| exception.throw(&cx))?;{conversion}}}@@ -478,6 +550,9 @@ def write_rust_interface(for operation_set in members.operation_sets:name = operation_set.name+ if len(operation_set.overloads) == 1 and operation_set.overloads[0].is_default_to_json:+ write_default_to_json(out, context, interface, operation_set.function)+ continueif len(operation_set.overloads) == 1:write_rust_operation(out, context, interface, name, operation_set.function, operation_set.overloads[0])continue@@ -493,6 +568,25 @@ def write_rust_interface([overload.steps_function for overload in operation_set.overloads],)+ if members.stringifier is not None:+ write_rust_stringifier(out, members.stringifier.function, members.stringifier.method)++ if members.indexed_property_getter is not None:+ getter = members.indexed_property_getter.operation+ getter_set = RustOperationSet(getter.operation.name, [getter])+ write_rust_operation(out, context, interface, getter_set.name, getter_set.function, getter)+ write_rust_item_value(out, context, interface, getter)++ for operation_set in members.static_operation_sets:+ if len(operation_set.overloads) > 1:+ raise UnsupportedByRustBindings(+ f"{interface.path}: the static operation {operation_set.name} of {interface.name} is overloaded, which "+ "the Rust bindings do not handle yet"+ )+ write_rust_static_operation(+ out, context, interface, operation_set.name, operation_set.function, operation_set.overloads[0]+ )+out.write(f"""/// The steps of {interface.prototype_class}::initialize() of LibWeb's C++ bindings.@@ -531,11 +625,27 @@ def write_rust_interface(name = operation_set.namefunction = operation_set.functionlength = operation_set.length- out.write(f' define_operation(vm, realm, prototype, "{name}", raw_native!({function}), {length});\n')+ definition = f'define_operation(vm, realm, prototype, "{name}", raw_native!({function}), {length});'+ out.write(window_only_definition(definition, operation_set.is_window_only))defined_property_names.append(name)for name in members.unimplemented_operation_names:out.write(f' define_unimplemented_property(vm, prototype, "{name}");\n')recorded_unimplemented_names.append(name)+ if members.stringifier is not None:+ function = members.stringifier.function+ definition = f'define_operation(vm, realm, prototype, "toString", raw_native!({function}), 0);'+ out.write(window_only_definition(definition, members.stringifier.is_window_only))+ defined_property_names.append("toString")+ if members.indexed_property_getter is not None:+ getter = members.indexed_property_getter.operation+ getter_set = RustOperationSet(getter.operation.name, [getter])+ out.write(+ f' define_operation(vm, realm, prototype, "{getter_set.name}", raw_native!({getter_set.function}), '+ f"{getter_set.length});\n"+ )+ defined_property_names.append(getter_set.name)+ if members.indexed_property_getter.has_value_iterator:+ out.write(" define_value_iterator_properties(vm, realm, prototype);\n")if members.constants:out.write(" define_constants(vm, prototype, &CONSTANTS);\n")defined_property_names.extend(constant.name for constant in members.constants)@@ -567,6 +677,13 @@ def write_rust_interface()if members.constants:out.write(" define_constants(vm, constructor, &CONSTANTS);\n")+ for operation_set in members.static_operation_sets:+ name = operation_set.name+ definition = (+ f'define_operation(vm, realm, constructor, "{name}", raw_native!({operation_set.function}), '+ f"{operation_set.length});"+ )+ out.write(window_only_definition(definition, operation_set.is_window_only))out.write(" }\n")for constructor in members.constructors:@@ -598,6 +715,153 @@ def write_rust_interface(out.write("}\n")+def window_only_definition(definition: str, is_window_only: bool) -> str:+ """A statement of the steps that initialize an interface object or an interface prototype object, which defines a+ member that only a Window has only if the global object of the realm is a Window."""+ if not is_window_only:+ return f" {definition}\n"+ return f""" if realm_is_window(realm) {{+ {definition}+ }}+"""+++def write_default_to_json(out: TextIO, context: GenerationContext, interface: Interface, function: str) -> None:+ """The native function of a [Default] toJSON operation, which runs the default toJSON steps, in the order of the C+++ bindings, https://webidl.spec.whatwg.org/#default-tojson-steps"""+ values = StringIO()+ # NB: The inheritance stack of the interface has the interface on top and the one it inherits from at the bottom,+ # and collecting the attribute values of the stack pops it, https://webidl.spec.whatwg.org/#collect-attribute-values-of-an-inheritance-stack+ # so the attributes of the interfaces that others inherit from are collected first.+ for interface_in_chain in context.inheritance_stack(interface):+ if not any(operation_is_default_to_json(operation) for operation in interface_in_chain.regular_operations):+ continue+ if not is_implemented_in_rust(interface_in_chain):+ raise UnsupportedByRustBindings(+ f"{interface.path}: {interface.name} inherits a [Default] toJSON() from {interface_in_chain.name}, "+ "which is not implemented in Rust"+ )+ module = "" if interface_in_chain.name == interface.name else f"super::{rust_module_name(interface_in_chain)}::"+ for attribute in rust_members(interface_in_chain).attributes:+ if not idl_type_is_json_type(attribute.attribute.type, context):+ continue+ values.write(+ f""" let value = {module}{attribute.getter_function}(vm)?;+ set_dictionary_member(&cx, result, &PropertyKey::from_utf8("{attribute.attribute.name}"), value)?;+"""+ )+ out.write(+ f"""+ fn {function}(vm: &Vm) -> ThrowCompletionOr<Value> {{+ this_implementation(vm)?;+ let realm = vm.current_realm().expect("a native function runs in a realm");+ let cx = CallContext::new(vm, realm);+ // 4. Let result be OrdinaryObjectCreate(%Object.prototype%).+ let result = create_dictionary_object(&cx);+ // 5. For each key → value of map:+{values.getvalue()} // 6. Return result.+ Ok(Value::from_object(result))+ }}+"""+ )+++def item_value_entry_point(interface: Interface) -> str:+ return rust_entry_point_name(interface, "item_value")+++def write_rust_item_value(out: TextIO, context: GenerationContext, interface: Interface, getter: RustOperation) -> None:+ """The entry point through which the internal methods of a legacy platform object that LibWeb's C++ defines read+ an indexed property of a wrapper of the interface, which has a value if the index is a supported property index,+ https://webidl.spec.whatwg.org/#legacy-platform-object-getownproperty"""+ return_type = getter.operation.return_type+ if not return_type.nullable:+ raise UnsupportedByRustBindings(+ f"{interface.path}: the indexed property getter of {interface.name} does not return a nullable type, by "+ "which the Rust bindings tell the indices that are not supported property indices"+ )+ what = f"the indexed property getter of {interface.name}"+ conversion = rust_to_js_value(return_type.without_nullable(), "value", "&cx", context, what)+ out.write(+ f"""+ /// The value of the indexed property of the wrapper, which LibWeb's C++ asks for, if the index is a supported+ /// property index.+ ///+ /// # Safety+ ///+ /// The pointers must be the VM, a live realm and a live wrapper of the interface.+ #[unsafe(no_mangle)]+ pub unsafe extern "C" fn {item_value_entry_point(interface)}(+ vm: *mut c_void,+ realm: *mut c_void,+ wrapper: *mut c_void,+ index: usize,+ out_value: &mut u64,+ ) -> bool {{+ // SAFETY: The caller passes live pointers.+ let (vm, realm, wrapper) = unsafe {{ entry_point_arguments(vm, realm, wrapper) }};+ let Ok(index) = u32::try_from(index) else {{+ return false;+ }};+ let implementation = implementation_of::<Implementation>(wrapper);+ let mut cx = CallContext::new(vm, realm);+ let Ok(Some(value)) = Implementation::{getter.method}(&implementation, &mut cx, index) else {{+ return false;+ }};+ let value = {conversion}.expect("converting an object to a JS value does not throw");+ *out_value = value.0;+ true+ }}+"""+ )+++def write_rust_stringifier(out: TextIO, function: str, method: str) -> None:+ """The native function of the stringifier, which calls the method of the implementation,+ https://webidl.spec.whatwg.org/#es-stringifier"""+ out.write(+ f"""+ fn {function}(vm: &Vm) -> ThrowCompletionOr<Value> {{+ let (implementation, mut cx) = this_implementation(vm)?;+ let result = Implementation::{method}(&implementation, &mut cx)+ .map_err(|exception| exception.throw(&cx))?;+ result.to_js(&cx)+ }}+"""+ )+++def write_rust_static_operation(+ out: TextIO, context: GenerationContext, interface: Interface, name: str, function: str, overload: RustOperation+) -> None:+ """The native function of a static operation, which runs in the current realm, in the order of the C++ bindings:+ the arguments are counted, then converted, https://webidl.spec.whatwg.org/#es-operations"""+ operation = overload.operation+ what = f"{interface.name}.{name}()"+ if is_promise_type(operation.return_type):+ raise UnsupportedByRustBindings(+ f"{what} is static and returns a promise type, which the Rust bindings do not handle yet"+ )+ out.write(+ f"""+ fn {function}(vm: &Vm) -> ThrowCompletionOr<Value> {{+ let realm = vm.current_realm().expect("a native function runs in a realm");+"""+ )+ write_argument_count_check(out, name, overload.length)+ write_parameter_conversions(out, what, operation.parameters, context)+ arguments = "".join(f", {rust_local_name(parameter.name)}" for parameter in operation.parameters)+ conversion = rust_to_js_value(operation.return_type, "result", "&cx", context, what)+ out.write(+ f""" let mut cx = CallContext::new(vm, realm);+ let result = Implementation::{overload.method}(&mut cx{arguments})+ .map_err(|exception| exception.throw(&cx))?;+ {conversion}+ }}+"""+ )++def write_rust_structured_data_entry_points(out: TextIO, interface: Interface) -> None:"""The entry points through which StructuredSerialize of LibWeb's C++ runs the steps of an interface that isserializable or transferable, which Meta/Generators/libweb_bindings/structured_serialize.py declares."""@@ -772,6 +1036,27 @@ def write_this_implementation(out: TextIO, context: GenerationContext, interface)+def inherited_attribute_getter_call(context: GenerationContext, interface: Interface, attribute: RustAttribute) -> str:+ """The call of the getter of an attribute that the interface redeclares with inherit, whose getter is that of the+ interface it inherits the attribute from, https://webidl.spec.whatwg.org/#dfn-inherit-getter. The implementation+ reaches the part that the getter runs on through Inherits."""+ name = attribute.attribute.name+ receiver = "&*implementation"+ path = rust_interface_path(interface)+ ancestor = context.interfaces.get(interface.parent_name)+ while ancestor is not None:+ ancestor_path = rust_interface_path(ancestor)+ receiver = f"<{path} as Inherits<{ancestor_path}>>::parent({receiver})"+ for ancestor_attribute in rust_members(ancestor).attributes:+ if ancestor_attribute.attribute.name == name and not ancestor_attribute.attribute.inherit:+ return f"{ancestor_path}::{ancestor_attribute.getter_method}({receiver}, &mut cx)"+ path = ancestor_path+ ancestor = context.interfaces.get(ancestor.parent_name)+ raise UnsupportedByRustBindings(+ f"{interface.path}: {interface.name} inherits the attribute {name}, which no interface it inherits from declares"+ )++def write_rust_attribute_setter(out: TextIO, context: GenerationContext, interface: Interface, attribute: RustAttribute) -> None:@@ -948,9 +1233,9 @@ pub(crate) mod definitions {)for name, directions in usage.rust_dictionaries.items():dictionary = context.dictionaries[name]- if dictionary.parent_name:+ if dictionary.parent_name and directions.to_js:raise UnsupportedByRustBindings(- f"The Rust bindings convert the dictionary {name}, which inherits from another dictionary"+ f"The Rust bindings convert the dictionary {name}, which inherits from another dictionary, to a JS value")if directions.from_js:write_dictionary_from_js(out, context, dictionary)@@ -987,10 +1272,10 @@ def write_rust_bindings(if interface is None or not is_implemented_in_rust(interface):continuewrite_rust_interface(out, context, module, interface, values[interface.name])- write_rust_wrap_for_cpp(out, usage)+ write_rust_wrap_for_cpp(out, context, usage)-def write_rust_wrap_for_cpp(out: TextIO, usage: DefinitionUsage) -> None:+def write_rust_wrap_for_cpp(out: TextIO, context: GenerationContext, usage: DefinitionUsage) -> None:"""The entry point through which the C++ bindings of the interfaces that name an interface implemented in Rustwrap an object of it, which C++ code holds as the cell of the object."""documentation = """@@ -1015,14 +1300,31 @@ def write_rust_wrap_for_cpp(out: TextIO, usage: DefinitionUsage) -> None:""")return- arms = "".join(- f""" {rust_module_name(interface)}::INTERFACE_NAME => {{++ def arm(interface: Interface) -> str:+ inheriting = inheriting_interfaces(interface, context)+ if not inheriting:+ return f""" {rust_module_name(interface)}::INTERFACE_NAME => {{// SAFETY: The caller passes the cell of an object of the interface.wrap(&cx, unsafe {{ cell_from_abi::<{rust_interface_path(interface)}>(cell) }})}}"""- for _, interface in sorted(usage.rust_interfaces_named_by_cpp.items())- )+ # NB: C++ names an object of an interface that others inherit from by that interface, whichever of them the+ # object is.+ choices = "".join(+ f""" // SAFETY: The caller passes a live cell.+ if let Some(object) = unsafe {{ cell_if_abi::<{rust_interface_path(candidate)}>(cell) }} {{+ break 'wrapper wrap(&cx, object);+ }}+"""+ for candidate in [interface] + inheriting+ )+ return f""" {rust_module_name(interface)}::INTERFACE_NAME => 'wrapper: {{+{choices} unreachable!("C++ passes the cell of an object of the interface or of one that inherits from it")+ }}+"""++ arms = "".join(arm(interface) for _, interface in sorted(usage.rust_interfaces_named_by_cpp.items()))out.write(f"""{documentation}pub unsafe extern "C" fn web_rust_bindings_wrap(vm: *mut core::ffi::c_void,@@ -1031,7 +1333,8 @@ def write_rust_wrap_for_cpp(out: TextIO, usage: DefinitionUsage) -> None:cell: *mut core::ffi::c_void,) -> *mut core::ffi::c_void {{use crate::bindings::CallContext;- use crate::bindings::interface::{{cell_from_abi, realm_arguments, wrap}};+ #[allow(unused_imports)]+ use crate::bindings::interface::{{cell_from_abi, cell_if_abi, realm_arguments, wrap}};// SAFETY: The caller passes the VM and a live realm.let (vm, realm) = unsafe {{ realm_arguments(vm, realm) }};diff --git a/Meta/Generators/libweb_bindings/rust_members.py b/Meta/Generators/libweb_bindings/rust_members.pyindex b31dfb1168b..12f44f9e6e2 100644--- a/Meta/Generators/libweb_bindings/rust_members.py+++ b/Meta/Generators/libweb_bindings/rust_members.py@@ -31,7 +31,12 @@ RUST_METHOD_NAME = re.compile(r"[a-z][a-z0-9_]*")# The extended attributes of the members of an interface that the Rust bindings handle.SUPPORTED_ATTRIBUTE_EXTENDED_ATTRIBUTES = {"CachedAccessor", "FIXME", "ImplementedAs", "NewObject", "SameObject"}-SUPPORTED_OPERATION_EXTENDED_ATTRIBUTES = {"FIXME", "ImplementedAs", "NewObject", "SameObject"}+SUPPORTED_OPERATION_EXTENDED_ATTRIBUTES = {"Default", "Exposed", "FIXME", "ImplementedAs", "NewObject", "SameObject"}+SUPPORTED_STRINGIFIER_EXTENDED_ATTRIBUTES = {"Exposed"}++# The value of [Exposed] that the Rust bindings handle on a member: a member that only a Window has, which the+# bindings define when the global object of the realm is a Window.+SUPPORTED_MEMBER_EXPOSURE = "Window"def generated_function_stem(method: str) -> str:@@ -68,13 +73,19 @@ class RustAttribute:@dataclassclass RustOperation:operation: Operation- # The method of the implementation that the steps of the operation call.+ # The method of the implementation that the steps of the operation call, which the implementation does not define+ # for a [Default] toJSON operation: the bindings run the default toJSON steps instead,+ # https://webidl.spec.whatwg.org/#default-tojson-stepsmethod: str@propertydef length(self) -> int:return operation_length(self.operation)+ @property+ def is_default_to_json(self) -> bool:+ return "Default" in self.operation.extended_attributes+@propertydef steps_function(self) -> str:"""The generated function of the steps of the operation, when the operation is one of several overloads that@@ -98,6 +109,35 @@ class RustOperationSet:def length(self) -> int:return min(overload.length for overload in self.overloads)+ @property+ def is_window_only(self) -> bool:+ """Whether only a Window has the operation: [Exposed=Window] on an interface exposed elsewhere as well."""+ return self.overloads[0].operation.extended_attributes.get("Exposed") == SUPPORTED_MEMBER_EXPOSURE+++@dataclass+class RustStringifier:+ """The stringifier of an interface, which the implementation runs through its method to_string,+ https://webidl.spec.whatwg.org/#es-stringifier"""++ # Whether only a Window has the stringifier.+ is_window_only: bool++ method = "to_string"+ function = "to_string_function"+++@dataclass+class RustIndexedPropertyGetter:+ """The indexed property getter of an interface, which has an identifier: the operation of that identifier, whose+ method the getter steps of a supported property index call as well, https://webidl.spec.whatwg.org/#idl-indexed-properties+ An index for which the method returns nothing is not a supported property index."""++ operation: RustOperation+ # Whether the interface declares a value iterator, which it implements through the indexed properties,+ # https://webidl.spec.whatwg.org/#dfn-value-iterator+ has_value_iterator: bool+@dataclassclass RustConstant:@@ -125,6 +165,10 @@ class RustMembers:# The attributes and the operations that the implementation has methods for.attributes: List[RustAttribute] = field(default_factory=list)operation_sets: List[RustOperationSet] = field(default_factory=list)+ # The static operations, which the interface object has.+ static_operation_sets: List[RustOperationSet] = field(default_factory=list)+ stringifier: Optional[RustStringifier] = None+ indexed_property_getter: Optional[RustIndexedPropertyGetter] = Noneconstructors: List[RustConstructor] = field(default_factory=list)constants: List[RustConstant] = field(default_factory=list)# The regular attributes in the order of the IDL, as the prototype defines them: an attribute of `attributes`, or@@ -144,6 +188,10 @@ class RustMembers:their definition."""names = [attribute.attribute.name for attribute in self.attributes]names.extend(operation_set.name for operation_set in self.operation_sets)+ if self.stringifier is not None:+ names.append("toString")+ if self.indexed_property_getter is not None:+ names.append(self.indexed_property_getter.operation.operation.name)names.extend(constant.name for constant in self.constants)return names@@ -176,20 +224,57 @@ def rust_members(interface: Interface) -> RustMembers:special_operations = [interface.named_property_getter,- interface.indexed_property_getter,interface.named_property_setter,interface.indexed_property_setter,interface.named_property_deleter,]- if any(special_operations) or interface.stringifier is not None:- fail("it has special operations")- if interface.iterable or interface.async_iterable or interface.maplike or interface.setlike:- fail("it is iterable or a maplike or setlike")- if interface.static_attributes or interface.static_operations:- fail("it has static members")+ if any(special_operations):+ fail("it has special operations other than an indexed property getter")+ if interface.async_iterable or interface.maplike or interface.setlike:+ fail("it is async iterable or a maplike or setlike")+ has_value_iterator = interface.iterable is not None and interface.iterable.key_type is None+ if interface.iterable is not None and not has_value_iterator:+ fail("it declares a pair iterator, which the Rust bindings do not handle yet")+ if interface.static_attributes:+ fail("it has static attributes")members = RustMembers()+ getter = interface.indexed_property_getter+ if has_value_iterator and getter is None:+ fail("it declares a value iterator and supports no indexed properties")+ if getter is not None:+ if not getter.name:+ fail("its indexed property getter has no identifier, which the Rust bindings do not handle yet")+ if interface.parent_name:+ fail("it supports indexed properties and inherits from another interface")+ if not any(attribute.name == "length" for attribute in interface.regular_attributes):+ fail("it supports indexed properties and has no length attribute")+ check_extended_attributes(getter.name, getter.extended_attributes, {"ImplementedAs"})+ getter_operation = Operation(getter.name, getter.return_type, getter.parameters, getter.extended_attributes)+ members.indexed_property_getter = RustIndexedPropertyGetter(+ RustOperation(getter_operation, method_of(getter.name, getter.extended_attributes)), has_value_iterator+ )++ def check_exposure(member_name: str, extended_attributes: dict) -> None:+ exposure = extended_attributes.get("Exposed")+ if exposure is not None and exposure != SUPPORTED_MEMBER_EXPOSURE:+ fail(+ f"{member_name} is [Exposed={exposure}], and the Rust bindings only handle [Exposed=Window] on members"+ )++ if interface.stringifier is not None:+ stringifier = interface.stringifier+ if stringifier.attribute is not None:+ fail("its stringifier is an attribute, which the Rust bindings do not handle yet")+ check_extended_attributes(+ "its stringifier", stringifier.extended_attributes, SUPPORTED_STRINGIFIER_EXTENDED_ATTRIBUTES+ )+ check_exposure("its stringifier", stringifier.extended_attributes)+ members.stringifier = RustStringifier(+ stringifier.extended_attributes.get("Exposed") == SUPPORTED_MEMBER_EXPOSURE+ )+constructor_attributes = {"ImplementedAs"} if len(interface.constructors) > 1 else set()for constructor in interface.constructors:unsupported_attributes = set(constructor.extended_attributes) - constructor_attributes@@ -228,32 +313,51 @@ def rust_members(interface: Interface) -> RustMembers:members.attributes.append(rust_attribute)members.attributes_in_order.append(rust_attribute)- for operation in interface.regular_operations:- check_extended_attributes(- operation.name, operation.extended_attributes, SUPPORTED_OPERATION_EXTENDED_ATTRIBUTES- )-- # NB: operation_overload_sets() leaves out the operations marked [FIXME], which the prototype records as not- # implemented unless another overload of theirs is.- overload_sets = operation_overload_sets(interface)- for name, operations in overload_sets.items():- if len(operations) > 1:- # NB: As for constructors, the IDL names the Rust method of every overload.- if not all("ImplementedAs" in operation.extended_attributes for operation in operations):+ def operation_sets(static: bool) -> List[RustOperationSet]:+ operations_of_interface = interface.static_operations if static else interface.regular_operations+ for operation in operations_of_interface:+ check_extended_attributes(+ operation.name, operation.extended_attributes, SUPPORTED_OPERATION_EXTENDED_ATTRIBUTES+ )+ check_exposure(operation.name, operation.extended_attributes)+ if "Default" in operation.extended_attributes and (+ static or operation.name != "toJSON" or operation.return_type.name != "object" or operation.parameters+ ):fail(- f"its operation {name} is overloaded, and not all of the overloads name their Rust method with "- "[ImplementedAs]"+ f"its operation {operation.name} is [Default], which only a regular toJSON() that returns an object can be")- if any(operation.return_type_is_promise() for operation in operations):- fail(f"its operation {name} is overloaded and returns a promise type")- overloads = [- RustOperation(operation, method_of(name, operation.extended_attributes)) for operation in operations- ]- members.operation_sets.append(RustOperationSet(name, overloads))- for operation in interface.regular_operations:- is_unimplemented = "FIXME" in operation.extended_attributes and operation.name not in overload_sets- if is_unimplemented and operation.name not in members.unimplemented_operation_names:- members.unimplemented_operation_names.append(operation.name)++ sets = []+ # NB: operation_overload_sets() leaves out the operations marked [FIXME], which the prototype records as not+ # implemented unless another overload of theirs is.+ overload_sets = operation_overload_sets(interface, static=static)+ for name, operations in overload_sets.items():+ if len(operations) > 1:+ # NB: As for constructors, the IDL names the Rust method of every overload.+ if not all("ImplementedAs" in operation.extended_attributes for operation in operations):+ fail(+ f"its operation {name} is overloaded, and not all of the overloads name their Rust method with "+ "[ImplementedAs]"+ )+ if any(operation.return_type_is_promise() for operation in operations):+ fail(f"its operation {name} is overloaded and returns a promise type")+ if len({operation.extended_attributes.get("Exposed") for operation in operations}) > 1:+ fail(f"the overloads of its operation {name} are exposed differently")+ overloads = [+ RustOperation(operation, method_of(name, operation.extended_attributes)) for operation in operations+ ]+ sets.append(RustOperationSet(name, overloads))+ if static and any("FIXME" in operation.extended_attributes for operation in operations_of_interface):+ fail("it has static operations marked [FIXME], which the Rust bindings do not record yet")+ if not static:+ for operation in operations_of_interface:+ is_unimplemented = "FIXME" in operation.extended_attributes and operation.name not in overload_sets+ if is_unimplemented and operation.name not in members.unimplemented_operation_names:+ members.unimplemented_operation_names.append(operation.name)+ return sets++ members.operation_sets = operation_sets(static=False)+ members.static_operation_sets = operation_sets(static=True)for constant in interface.constants:value = idl_integer_value(constant.value, constant.type.name) if constant.type.name in INTEGER_TYPES else None@@ -264,7 +368,16 @@ def rust_members(interface: Interface) -> RustMembers:methods = [attribute.getter_method for attribute in members.attributes]methods.extend(attribute.setter_method for attribute in members.attributes if attribute.setter_method is not None)- methods.extend(overload.method for operation_set in members.operation_sets for overload in operation_set.overloads)+ methods.extend(+ overload.method+ for operation_set in members.operation_sets + members.static_operation_sets+ for overload in operation_set.overloads+ if not overload.is_default_to_json+ )+ if members.stringifier is not None:+ methods.append(members.stringifier.method)+ if members.indexed_property_getter is not None:+ methods.append(members.indexed_property_getter.operation.method)methods.extend(constructor.method for constructor in members.constructors)repeated_methods = sorted({method for method in methods if methods.count(method) > 1})if repeated_methods:diff --git a/Meta/Generators/libweb_bindings/rust_to_idl_value.py b/Meta/Generators/libweb_bindings/rust_to_idl_value.pyindex 6f7f1e4678a..9f37fbad2b3 100644--- a/Meta/Generators/libweb_bindings/rust_to_idl_value.py+++ b/Meta/Generators/libweb_bindings/rust_to_idl_value.py@@ -259,8 +259,14 @@ def rust_default_value()-def dictionary_can_be_empty(dictionary: Dictionary) -> bool:- return not any(member.required for member in dictionary.members)+def dictionary_can_be_empty(context: GenerationContext, dictionary: Dictionary) -> bool:+ """Whether the dictionary has a value without members: none of its members or of those of the dictionaries it+ inherits from is required."""+ return not any(+ member.required+ for inherited_dictionary in context.dictionary_inheritance_stack(dictionary)+ for member in inherited_dictionary.members+ )def write_dictionary_from_js(out: TextIO, context: GenerationContext, dictionary: Dictionary) -> None:@@ -271,6 +277,15 @@ def write_dictionary_from_js(out: TextIO, context: GenerationContext, dictionarykeys = []conversions = []empty_fields = []+ parent_field = []+ parent_conversion = ""+ if dictionary.parent_name:+ # NB: The struct of a dictionary that inherits from another holds that dictionary's struct in the field+ # `parent`, whose members are converted first, step 4 of https://webidl.spec.whatwg.org/#js-dictionary+ parent_path = rust_dictionary_path(context.dictionaries[dictionary.parent_name], context)+ parent_field = ["parent"]+ parent_conversion = f" let parent = <{parent_path}>::from_js(vm, value)?;\n"+ empty_fields.append(f"parent: <{parent_path} as EmptyDictionary>::empty()")for member in dictionary.members:what = f"{dictionary.name}.{member.name}"local = rust_local_name(member.name)@@ -302,7 +317,8 @@ def write_dictionary_from_js(out: TextIO, context: GenerationContext, dictionary""")fields = ", ".join(- f"{rust_identifier(member.name)}: {rust_local_name(member.name)}" for member in dictionary.members+ parent_field+ + [f"{rust_identifier(member.name)}: {rust_local_name(member.name)}" for member in dictionary.members])out.write(f"""@@ -310,12 +326,12 @@ def write_dictionary_from_js(out: TextIO, context: GenerationContext, dictionaryimpl FromJs for {path} {{fn from_js(vm: &Vm, value: Value) -> ThrowCompletionOr<Self> {{{"".join(keys)} let object = dictionary_object(vm, value, "{dictionary.name}")?;-{"".join(conversions)} Ok(Self {{ {fields} }})+{parent_conversion}{"".join(conversions)} Ok(Self {{ {fields} }})}}}}""")- if dictionary_can_be_empty(dictionary):+ if dictionary_can_be_empty(context, dictionary):out.write(f"""impl EmptyDictionary for {path} {{diff --git a/Meta/Generators/libweb_bindings/rust_to_js_value.py b/Meta/Generators/libweb_bindings/rust_to_js_value.pyindex 83abb54fe45..1af4f22d849 100644--- a/Meta/Generators/libweb_bindings/rust_to_js_value.py+++ b/Meta/Generators/libweb_bindings/rust_to_js_value.py@@ -34,7 +34,7 @@ def rust_to_js_value("""An expression of type ThrowCompletionOr<Value> that converts the IDL value to a JS value. The call context is anexpression of type &CallContext. Nullable types and unions with undefined both have an Option as their Rust type,so the conversion follows from the IDL type and not from the Rust one."""- rust_type(idl_type, context, what)+ rust_type(idl_type, context, what, is_result=True)def inner(inner_type: IDLType) -> str:return rust_to_js_value(inner_type, "value", call_context, context, what)diff --git a/Meta/Generators/libweb_bindings/rust_types.py b/Meta/Generators/libweb_bindings/rust_types.pyindex 4acbe9b3a31..778392b5777 100644--- a/Meta/Generators/libweb_bindings/rust_types.py+++ b/Meta/Generators/libweb_bindings/rust_types.py@@ -236,11 +236,22 @@ def unnamed_union_idl_path(idl_type: IDLUnionType, context: GenerationContext, wpaths = {mixin.path for mixin in context.mixins.values() if name_the_union(member_types_of_interface(mixin))}if not paths:+ interfaces = []for module in context.modules:if module.interface is not None and name_the_union(member_types_of_interface(module.interface)):paths.add(module.path)+ interfaces.append(module.interface)if any(name_the_union(member.type for member in dictionary.members) for dictionary in module.dictionaries):paths.add(module.path)+ # NB: A union that an interface and the interfaces that inherit from it name, as the constructors of+ # DOMMatrixReadOnly and DOMMatrix do, is the union of the interface that the others inherit from.+ roots = [+ interface+ for interface in interfaces+ if all(other is interface or other in inheriting_interfaces(interface, context) for other in interfaces)+ ]+ if len(roots) == 1 and len(paths) == len(interfaces):+ paths = {roots[0].path}if len(paths) != 1:raise UnsupportedByRustBindings(f"{what} has the union type {idl_type}, which no typedef names and which the IDL files "@@ -323,17 +334,18 @@ def rust_union_path(idl_type: IDLUnionType, context: GenerationContext, what: straise RuntimeError(f"No module defines the typedef {name}")-def rust_type(idl_type: IDLType, context: GenerationContext, what: str) -> str:- """The Rust type of the IDL values of the type."""+def rust_type(idl_type: IDLType, context: GenerationContext, what: str, is_result: bool = False) -> str:+ """The Rust type of the IDL values of the type. A result is a value that the implementation returns, which it+ creates, so that it knows the interface of an object it returns."""unsupported_attributes = set(idl_type.extended_attributes) - SUPPORTED_TYPE_EXTENDED_ATTRIBUTESif unsupported_attributes:raise UnsupportedByRustBindings(f"{what} has extended attributes {sorted(unsupported_attributes)}")if idl_type.nullable:- return f"Option<{rust_type(idl_type.without_nullable(), context, what)}>"+ return f"Option<{rust_type(idl_type.without_nullable(), context, what, is_result)}>"name = idl_type.nameif isinstance(idl_type, IDLParameterizedType):if name == "sequence":- return f"Vec<{rust_type(idl_type.parameters[0], context, what)}>"+ return f"Vec<{rust_type(idl_type.parameters[0], context, what, is_result)}>"if name == "record":key_type, value_type = idl_type.parametersif key_type.name not in ("DOMString", "USVString"):@@ -352,8 +364,9 @@ def rust_type(idl_type: IDLType, context: GenerationContext, what: str) -> str:return "Gc<FunctionObject>"interface = rust_interface(idl_type, context)if interface is not None:- if inheriting_interfaces(interface, context):- # NB: An object of such a type is a cell of any of several classes, which Ref<T> cannot express.+ if inheriting_interfaces(interface, context) and not is_result:+ # NB: An object of such a type is a cell of any of several classes, which Ref<T> cannot express. An object+ # that an implementation returns is one of exactly the interface, whose cell it created.raise UnsupportedByRustBindings(f"{what} has the type {idl_type}, an interface that others inherit from, which the Rust bindings do ""not convert yet"@@ -389,7 +402,7 @@ def rust_result_type(idl_type: IDLType, context: GenerationContext, what: str) -promise object, which is the only place the Rust bindings handle a promise type in."""if is_promise_type(idl_type) and not idl_type.nullable:return "Gc<Object>"- return rust_type(idl_type, context, what)+ return rust_type(idl_type, context, what, is_result=True)def holds_cells(diff --git a/Meta/Generators/libweb_bindings/rust_usage.py b/Meta/Generators/libweb_bindings/rust_usage.pyindex 913c1df9efd..d175cd968d7 100644--- a/Meta/Generators/libweb_bindings/rust_usage.py+++ b/Meta/Generators/libweb_bindings/rust_usage.py@@ -110,11 +110,17 @@ class DefinitionUsage:for attribute in members.attributes:has_setter = attribute.setter_method is not Noneself._name_for_rust(attribute.attribute.type, from_js=has_setter, to_js=True)- for operation_set in members.operation_sets:- for overload in operation_set.overloads:- self._name_for_rust(overload.operation.return_type, from_js=False, to_js=True)- for parameter in overload.operation.parameters:- self._name_for_rust(parameter.type, from_js=True, to_js=False)+ operations = [+ overload.operation+ for operation_set in members.operation_sets + members.static_operation_sets+ for overload in operation_set.overloads+ ]+ if members.indexed_property_getter is not None:+ operations.append(members.indexed_property_getter.operation.operation)+ for operation in operations:+ self._name_for_rust(operation.return_type, from_js=False, to_js=True)+ for parameter in operation.parameters:+ self._name_for_rust(parameter.type, from_js=True, to_js=False)for constructor in members.constructors:for parameter in constructor.constructor.parameters:self._name_for_rust(parameter.type, from_js=True, to_js=False)@@ -154,6 +160,9 @@ class DefinitionUsage:directions.to_js = directions.to_js or to_jsfor member in self._members_with_inherited(dictionary):self._name_for_rust(member.type, from_js, to_js)+ if dictionary.parent_name:+ # NB: The conversion of a dictionary converts the dictionary that it inherits from first.+ self._name_for_rust(IDLType(dictionary.parent_name), from_js, to_js)def _members_with_inherited(self, dictionary: Dictionary):members = list(dictionary.members)diff --git a/Meta/Generators/libweb_bindings/structured_serialize.py b/Meta/Generators/libweb_bindings/structured_serialize.pyindex 79272e39f73..a1537908292 100644--- a/Meta/Generators/libweb_bindings/structured_serialize.py+++ b/Meta/Generators/libweb_bindings/structured_serialize.py@@ -8,6 +8,7 @@ from typing import TextIOfrom Generators.libweb_bindings.cpp_types import fully_qualified_name_for_interfacefrom Generators.libweb_bindings.cpp_types import implementation_header_for_interfacefrom Generators.libweb_bindings.rust_bindings import rust_entry_point_name+from Generators.libweb_bindings.rust_bindings import wrapper_host_class_symbolfrom Generators.libweb_bindings.rust_types import is_implemented_in_rustfrom Utils.webidl_parser import Interface@@ -82,7 +83,10 @@ def write_structured_serialize_bindings_implementation(out: TextIO, interfaces:)for interface in included_interfaces:out.write(f"#include <LibWeb/Bindings/{interface.implemented_name}.h>\n")- out.write(f"#include <{implementation_header_for_interface(interface)}>\n")+ # NB: The bindings find the cells of the objects of an interface implemented in Rust by the class of their+ # wrappers, which LibWeb/Bindings/<interface>.h declares, so they need no C++ class of the interface.+ if not is_implemented_in_rust(interface):+ out.write(f"#include <{implementation_header_for_interface(interface)}>\n")out.write("""@@ -103,7 +107,7 @@ Optional<TransferablePlatformObject> transferable_from_object(JS::Object& object)for interface in rust_transferable:out.write(- f""" if (auto* cell = Bindings::impl_from<{fully_qualified_name_for_interface(interface)}>(&object))+ f""" if (auto* cell = rust_interface_cell_of_wrapper(object, {wrapper_host_class_symbol(interface)}))return TransferablePlatformObject {{ .rust_object = cell, .primary_interface = HTML::TransferType::{interface.name} }};""")@@ -191,7 +195,7 @@ Optional<SerializablePlatformObject> serializable_from_object(JS::Object& object)for interface in rust_serializable:out.write(- f""" if (auto* cell = Bindings::impl_from<{fully_qualified_name_for_interface(interface)}>(&object))+ f""" if (auto* cell = rust_interface_cell_of_wrapper(object, {wrapper_host_class_symbol(interface)}))return SerializablePlatformObject {{ .rust_object = cell, .interface_name = InterfaceName::{interface.name}, .realm = &object.shape().realm() }};""")