Truly independent web browser
Meta+LibWeb: Let an interface implemented in Rust inherit from another
Aliaksandr Kalenik842162144e31
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/interface.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/interface.rsindex 9a4d064777c..05d549f4a57 100644--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/interface.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/interface.rs@@ -30,8 +30,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_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_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@@ -69,6 +69,13 @@ impl<T: Trace> Deref for Wrapped<T> {/// An object of the interface that `T` implements.pub(crate) type Ref<T> = Gc<EmbedderCell<Wrapped<T>>>;+/// What the implementation of an interface that inherits from another implements, for the implementation of that+/// interface: where an object of the interface keeps what it is as an object of the inherited interface. The+/// attributes and operations of the inherited interface run on that.+pub(crate) trait Inherits<Parent> {+ fn parent(&self) -> &Parent;+}+/// 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.@@ -135,10 +142,16 @@ pub(crate) fn this_object(/// The object that a wrapper of exactly the interface wraps.pub(crate) fn implementation_of<T: Interface>(wrapper: Gc<Object>) -> Ref<T> {+ implementation_if(wrapper).expect("a wrapper holds the cell of its object")+}++/// The object that the wrapper of an interface implemented in Rust wraps, if it is an object of exactly this+/// interface and not of one that inherits from it.+pub(crate) fn implementation_if<T: Interface>(wrapper: Gc<Object>) -> Option<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.- unsafe { T::CELL_CLASS.downcast(host_data) }.expect("a wrapper holds the cell of its object")+ // SAFETY: The wrapper is a host object of the wrapper class of an interface implemented in Rust, whose host data+ // the bindings set to the cell of an object of such an interface.+ unsafe { T::CELL_CLASS.downcast(host_data) }}/// An object of the interface converted from a JS value, https://webidl.spec.whatwg.org/#js-interface@@ -315,10 +328,19 @@ pub(crate) unsafe fn construct_arguments<'vm>(vm: *mut c_void, new_target: *mutunsafe { (&*vm.cast::<Vm>(), Gc::from_non_null(new_target)) }}-/// Gives the interface prototype object its [[Prototype]], %Object.prototype%. The Rust bindings do not handle-/// interfaces that inherit from another interface yet.-pub(crate) fn set_interface_prototype_object_prototype(vm: &Vm, realm: Gc<Realm>, prototype: Gc<Object>) {- prototype.set_prototype(vm, Some(realm.intrinsics().object_prototype(vm)));+/// Gives the interface prototype object its [[Prototype]]: the interface prototype object of the interface that the+/// interface inherits from, or %Object.prototype%, https://webidl.spec.whatwg.org/#interface-prototype-object+pub(crate) fn set_interface_prototype_object_prototype(+ vm: &Vm,+ realm: Gc<Realm>,+ prototype: Gc<Object>,+ inherited_interface_name: Option<u16>,+) {+ let parent = match inherited_interface_name {+ Some(inherited_interface_name) => interface_prototype_object(realm, inherited_interface_name),+ None => realm.intrinsics().object_prototype(vm),+ };+ prototype.set_prototype(vm, Some(parent));}/// Defines a regular attribute on the interface prototype object, https://webidl.spec.whatwg.org/#es-attributes@@ -395,8 +417,9 @@ pub(crate) fn define_to_string_tag(vm: &Vm, prototype: Gc<Object>, name: &str) {);}-/// Defines the "length", "name" and "prototype" properties of the interface object,-/// https://webidl.spec.whatwg.org/#es-interface-call+/// Gives the interface object its [[Prototype]], if the interface inherits from another: the interface object of that+/// interface. Then defines the "length", "name" and "prototype" properties of the interface object,+/// https://webidl.spec.whatwg.org/#interface-objectpub(crate) fn define_interface_object_properties(vm: &Vm,realm: Gc<Realm>,@@ -404,7 +427,15 @@ pub(crate) fn define_interface_object_properties(name: &str,length: i32,interface_name: u16,+ inherited_interface_name: Option<u16>,) {+ if let Some(inherited_interface_name) = inherited_interface_name {+ // SAFETY: The realm is live, and the interface is implemented in Rust.+ let parent = unsafe { web_bindings_ensure_web_constructor(realm.as_ptr().cast(), inherited_interface_name) };+ let parent = NonNull::new(parent.cast::<Object>()).expect("the realm has the interface object");+ // SAFETY: LibWeb returns the live interface object.+ constructor.set_prototype(vm, Some(unsafe { Gc::from_non_null(parent) }));+ }constructor.define_direct_property(vm,&vm.names.length,diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/services.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/services.rsindex 61531a49bd0..89582f86212 100644--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/services.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/services.rs@@ -15,6 +15,9 @@ unsafe extern "C" {/// interface implemented in Rust.pub(crate) fn web_bindings_ensure_web_prototype(realm: *mut c_void, interface_name: u16) -> *mut c_void;+ /// The interface object of the interface in the realm, likewise.+ pub(crate) fn web_bindings_ensure_web_constructor(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;diff --git a/Meta/Generators/libweb_bindings/rust_bindings.py b/Meta/Generators/libweb_bindings/rust_bindings.pyindex 6041f8b479d..5bc4656e72d 100644--- a/Meta/Generators/libweb_bindings/rust_bindings.py+++ b/Meta/Generators/libweb_bindings/rust_bindings.py@@ -39,6 +39,7 @@ 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 inheriting_interfacesfrom Generators.libweb_bindings.rust_types import is_implemented_in_rustfrom Generators.libweb_bindings.rust_types import is_promise_typefrom Generators.libweb_bindings.rust_types import rust_interface_path@@ -93,14 +94,14 @@ def check_interface_is_supported(interface: Interface, module: Module, context:fail(f"the Rust bindings do not handle its extended attributes {sorted(unsupported_attributes)}")if interface.is_namespace or interface.is_callback_interface:fail("it is not a regular interface")- if interface.parent_name:- fail("it inherits from another interface")+ if interface.parent_name and not is_implemented_in_rust(context.interfaces.get(interface.parent_name)):+ fail(f"it inherits from {interface.parent_name}, which is not implemented in Rust")if module.enumerations or module.callback_functions:fail("its module defines enumerations or callback functions")- for other in context.interfaces.values():- if other.parent_name == interface.name:- fail(f"{other.name} inherits from it")+ for other in inheriting_interfaces(interface, context):+ if not is_implemented_in_rust(other):+ fail(f"{other.name}, which is not implemented in Rust, inherits from it")rust_members(interface)@@ -162,6 +163,12 @@ def write_cpp_implementation(includes.add("LibJS/Runtime/Realm.h")includes.add("LibWeb/Bindings/RustInterface.h")includes.add_binding(interface.implemented_name)+ parent = context.interfaces.get(interface.parent_name)+ if parent is not None:+ includes.add_binding(parent.implemented_name)+ parent_host_class = wrapper_host_class_symbol(parent)+ else:+ parent_host_class = "web_bindings_rust_interface_wrapper_host_class"initialize_prototype = rust_entry_point_name(interface, "initialize_prototype")initialize_constructor = rust_entry_point_name(interface, "initialize_constructor")@@ -184,7 +191,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,- &web_bindings_rust_interface_wrapper_host_class, nullptr, nullptr, JS_HOST_CLASS_IS_PLATFORM_OBJECT);+ &{parent_host_class}, nullptr, nullptr, JS_HOST_CLASS_IS_PLATFORM_OBJECT);void {interface.prototype_class}::initialize(JS::Realm& realm, JS::Object& object){{@@ -216,8 +223,10 @@ JS::ThrowCompletionOr<GC::Ref<JS::Object>> {interface.constructor_class}::constrdef write_ensure_web_prototype_declaration(out: TextIO) -> None:out.write("""-// The interface prototype object of an interface implemented in Rust in the realm, for the Rust bindings.+// The interface prototype object and the interface object of an interface implemented in Rust in the realm, for the+// Rust bindings.extern "C" JSObject* web_bindings_ensure_web_prototype(void* realm, u16 interface_name);+extern "C" JSObject* web_bindings_ensure_web_constructor(void* realm, u16 interface_name);""")@@ -244,6 +253,26 @@ JSObject* web_bindings_ensure_web_prototype(void* realm, u16 interface_name)VERIFY_NOT_REACHED();}}++JSObject* web_bindings_ensure_web_constructor(void* realm, u16 interface_name)+{+ [[maybe_unused]] auto& js_realm = *static_cast<JS::Realm*>(realm);+ switch (static_cast<InterfaceName>(interface_name)) {+"""+ )+ for interface in intrinsics:+ if not is_implemented_in_rust(interface):+ continue+ out.write(+ f""" case InterfaceName::{interface.name}:+ return JS::HostABI::object_to_abi(&ensure_web_constructor<{interface.prototype_class}>(js_realm, "{interface.namespaced_name}"_utf16_fly_string));+"""+ )+ out.write(+ """ default:+ VERIFY_NOT_REACHED();+ }+}""")@@ -357,6 +386,8 @@ def write_rust_interface() -> None:implementation = rust_interface_path(interface)members = rust_members(interface)+ parent = context.interfaces.get(interface.parent_name)+ inherited_interface_name = "None" if parent is None else f"Some(super::{rust_module_name(parent)}::INTERFACE_NAME)"method_documentation = "".join(f"/// - `{signature}`\n" for signature in implementation_method_signatures(context, interface, members))@@ -381,10 +412,11 @@ def write_rust_interface(to_unsigned_long_long, to_usv_string,}};use crate::bindings::interface::{{- Interface, Ref, Wrapped, construct_arguments, construct_wrapper, define_attribute, define_constants,- define_interface_object_properties, define_operation, define_to_string_tag, define_unimplemented_property,- entry_point_arguments, implementation_of, prototype_from_new_target, rejected_promise,- set_interface_prototype_object_prototype, this_object, to_interface,+ Inherits, Interface, Ref, Wrapped, construct_arguments, construct_wrapper, define_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,}};use crate::bindings::{{CallContext, WebIdlResult}};@@ -411,13 +443,9 @@ def write_rust_interface(}}}}- /// 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)))- }}""")+ write_this_implementation(out, context, interface)defined_property_names: List[str] = []recorded_unimplemented_names: List[str] = []@@ -468,7 +496,7 @@ def write_rust_interface() {{// SAFETY: The caller passes live pointers.let (vm, realm, prototype) = unsafe {{ entry_point_arguments(vm, realm, prototype) }};- set_interface_prototype_object_prototype(vm, realm, prototype);+ set_interface_prototype_object_prototype(vm, realm, prototype, {inherited_interface_name});""")# NB: The properties are defined in the order of the C++ bindings: the attributes, the operations, the operations@@ -518,7 +546,7 @@ def write_rust_interface() {{// SAFETY: The caller passes live pointers.let (vm, realm, constructor) = unsafe {{ entry_point_arguments(vm, realm, constructor) }};- define_interface_object_properties(vm, realm, constructor, "{interface.name}", {members.constructor_length}, INTERFACE_NAME);+ define_interface_object_properties(vm, realm, constructor, "{interface.name}", {members.constructor_length}, INTERFACE_NAME, {inherited_interface_name});""")if members.constants:@@ -553,6 +581,78 @@ def write_rust_interface(out.write("}\n")+def write_this_implementation(out: TextIO, context: GenerationContext, interface: Interface) -> None:+ """The function that finds what an attribute or an operation of the interface runs on. For an interface that+ others inherit from, that is an object of any of them, which the implementation of each reaches the inherited+ part of through Inherits."""+ inheriting = inheriting_interfaces(interface, context)+ if not inheriting:+ out.write(+ """+ /// 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)))+ }+"""+ )+ return++ variants = f" {interface.name}(Ref<Implementation>),\n"+ arms = f""" Self::{interface.name}(object) => {{+ let object: &Implementation = object;+ object+ }}+"""+ choices = f""" if let Some(object) = implementation_if::<Implementation>(object) {{+ return Ok((Receiver::{interface.name}(object), cx));+ }}+"""+ for other in inheriting:+ path = rust_interface_path(other)+ variants += f" {other.name}(Ref<{path}>),\n"+ # NB: An interface reaches the part of an interface it does not inherit from directly through the ones between.+ steps = f" let object: &{path} = object;\n"+ ancestor = other+ while ancestor.name != interface.name:+ next_ancestor = context.interfaces[ancestor.parent_name]+ next_path = "Implementation" if next_ancestor.name == interface.name else rust_interface_path(next_ancestor)+ steps += f" let object = <{rust_interface_path(ancestor)} as Inherits<{next_path}>>::parent(object);\n"+ ancestor = next_ancestor+ arms += f""" Self::{other.name}(object) => {{+{steps} object+ }}+"""+ choices += f""" if let Some(object) = implementation_if::<{path}>(object) {{+ return Ok((Receiver::{other.name}(object), cx));+ }}+"""+ out.write(+ f"""+ /// The object that an attribute or an operation of the interface runs on: an object of the interface, or of an+ /// interface that inherits from it.+ enum Receiver {{+{variants} }}++ impl core::ops::Deref for Receiver {{+ type Target = Implementation;++ fn deref(&self) -> &Implementation {{+ match self {{+{arms} }}+ }}+ }}++ /// The object that an attribute or an operation runs on, and the context it runs in.+ fn this_implementation(vm: &Vm) -> ThrowCompletionOr<(Receiver, CallContext<'_>)> {{+ let (object, realm) = this_object(vm, Implementation::wrapper_class(), Implementation::NAME)?;+ let cx = CallContext::new(vm, realm);+{choices} unreachable!("a wrapper of the interface wraps an object of it or of an interface that inherits from it")+ }}+"""+ )++def write_rust_attribute_setter(out: TextIO, context: GenerationContext, interface: Interface, attribute: RustAttribute) -> None:diff --git a/Meta/Generators/libweb_bindings/rust_types.py b/Meta/Generators/libweb_bindings/rust_types.pyindex 9f5f9852691..26bd5631f80 100644--- a/Meta/Generators/libweb_bindings/rust_types.py+++ b/Meta/Generators/libweb_bindings/rust_types.py@@ -8,6 +8,7 @@import refrom pathlib import Path+from typing import Listfrom typing import Optionalfrom Generators.libweb_bindings.context import GenerationContext@@ -111,6 +112,18 @@ 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 inheriting_interfaces(interface: Interface, context: GenerationContext) -> List[Interface]:+ """The interfaces that inherit from the interface, through any number of interfaces between them."""+ inheriting = []+ for other in context.interfaces.values():+ ancestor = context.interfaces.get(other.parent_name)+ while ancestor is not None and ancestor.name != interface.name:+ ancestor = context.interfaces.get(ancestor.parent_name)+ if ancestor is not None:+ inheriting.append(other)+ return inheriting++def rust_interface_path(interface: Interface) -> str:"""The Rust path of the implementation of an interface: crate::encoding::text_encoder::TextEncoder forEncoding/TextEncoder.idl."""@@ -223,6 +236,12 @@ 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.+ raise UnsupportedByRustBindings(+ f"{what} has the type {idl_type}, an interface that others inherit from, which the Rust bindings do "+ "not convert yet"+ )return f"Ref<{rust_interface_path(interface)}>"dictionary = resolved_dictionary(idl_type, context)if dictionary is not None: