Skip to content

Truly independent web browser

Meta+LibWeb: Pass objects of C++ interfaces to the Rust bindings

Aliaksandr Kalenike8fcfe961c52
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs
index e4ae98d9add..815d3f4a0aa 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs
@@ -20,6 +20,7 @@ use libjs_rust::api::{
use crate::bindings::CallContext;
use crate::bindings::interface::{Interface, Ref, create_dictionary_object, wrap};
+use crate::bindings::services::web_bindings_object_implements_interface;
/// A USVString, a string without lone surrogates. Its UTF-16 code units are always well-formed.
pub(crate) struct UsvString(Utf16String);
@@ -720,6 +721,59 @@ impl<T: Interface> ToJs for Ref<T> {
}
}
+/// An object of an interface that LibWeb implements in C++, as its wrapper. Only the C++ code knows the object
+/// behind the wrapper, so an implementation hands the wrapper to a service of LibWeb to have something done with it.
+#[derive(Clone, Copy, Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct CppInterface(Gc<Object>);
+
+impl CppInterface {
+ /// The object whose wrapper a service of LibWeb returned.
+ ///
+ /// # Safety
+ ///
+ /// `wrapper` must be a wrapper of an object of the interface that the IDL names where the value is used.
+ pub(crate) unsafe fn from_wrapper(wrapper: Gc<Object>) -> Self {
+ Self(wrapper)
+ }
+
+ pub(crate) fn wrapper(self) -> Gc<Object> {
+ self.0
+ }
+}
+
+/// Whether the object is a wrapper of an object that implements the interface, which LibWeb implements in C++ and
+/// knows by the value of its Web::Bindings::InterfaceName.
+pub(crate) fn implements_cpp_interface(object: Gc<Object>, interface_name: u16) -> bool {
+ // SAFETY: The object is live.
+ object.is_platform_object()
+ && unsafe { web_bindings_object_implements_interface(object.as_ptr().cast(), interface_name) }
+}
+
+/// An object of an interface that LibWeb implements in C++ converted from a JS value,
+/// https://webidl.spec.whatwg.org/#js-interface
+pub(crate) fn to_cpp_interface(
+ vm: &Vm,
+ value: Value,
+ interface_name: u16,
+ name: &str,
+) -> ThrowCompletionOr<CppInterface> {
+ // 1. If V implements I, then return the IDL interface type value that represents a reference to that platform
+ // object.
+ if value.is_object() && implements_cpp_interface(value.as_object(), interface_name) {
+ return Ok(CppInterface(value.as_object()));
+ }
+ // 2. Throw a TypeError.
+ vm.throw_completion(ErrorKind::TypeError, ErrorType::NotAnObjectOfType, &[&name])
+}
+
+/// https://webidl.spec.whatwg.org/#js-interface
+impl ToJs for CppInterface {
+ fn to_js(self, _: &CallContext) -> ThrowCompletionOr<Value> {
+ Ok(Value::from_object(self.0))
+ }
+}
+
/// 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>(
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/services.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/services.rs
index 89582f86212..6a92d4662dd 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/services.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/services.rs
@@ -29,6 +29,10 @@ 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 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;
+
/// A promise rejected with the reason, in the realm of the this value of an operation that ran in the current
/// realm: the realm of the object, or the current realm for a value that is not an object.
pub(crate) fn web_bindings_rejected_promise(
diff --git a/Libraries/LibWeb/Bindings/RustBindingsServices.cpp b/Libraries/LibWeb/Bindings/RustBindingsServices.cpp
index 77cd692e3b2..7e31548b356 100644
--- a/Libraries/LibWeb/Bindings/RustBindingsServices.cpp
+++ b/Libraries/LibWeb/Bindings/RustBindingsServices.cpp
@@ -25,6 +25,7 @@ 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_object_implements_interface(JSObject* object, u16 interface_name);
void* web_bindings_wrapper_world(void* realm, bool* is_main_world)
{
@@ -46,6 +47,12 @@ 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_object_implements_interface(JSObject* object, u16 interface_name)
+{
+ auto* wrappable = wrappable_impl_from(JS::HostABI::object_from_abi(object));
+ return wrappable && wrappable->implements_interface(static_cast<InterfaceName>(interface_name));
+}
+
JSObject* web_bindings_rejected_promise(void* current_realm, JSValue this_value, JSValue reason)
{
auto& realm = *static_cast<JS::Realm*>(current_realm);
diff --git a/Meta/Generators/libweb_bindings/rust_bindings.py b/Meta/Generators/libweb_bindings/rust_bindings.py
index de4e7b8187e..3a910f4a4ec 100644
--- a/Meta/Generators/libweb_bindings/rust_bindings.py
+++ b/Meta/Generators/libweb_bindings/rust_bindings.py
@@ -41,6 +41,7 @@ from Generators.libweb_bindings.rust_to_js_value import write_dictionary_to_js
from Generators.libweb_bindings.rust_to_js_value import write_enumeration_to_js
from Generators.libweb_bindings.rust_to_js_value import write_union_to_js
from Generators.libweb_bindings.rust_types import UnsupportedByRustBindings
+from Generators.libweb_bindings.rust_types import cpp_interface_name_constant
from Generators.libweb_bindings.rust_types import inheriting_interfaces
from Generators.libweb_bindings.rust_types import is_implemented_in_rust
from Generators.libweb_bindings.rust_types import is_promise_type
@@ -408,10 +409,10 @@ def write_rust_interface(
}};
use crate::bindings::conversions::{{
- ArrayBufferView, BufferSource, BufferSourceRules, EmptyDictionary, FromJs, ToJs, UsvString, record_to_js,
- rooted_sequence_to_js, sequence_from_js, sequence_to_js, to_array_buffer_view, to_boolean, to_buffer_source,
- to_dom_string, to_float, to_long, to_long_long, to_typed_array, to_unrestricted_double,
- to_unrestricted_float, to_unsigned_long, to_unsigned_long_long, to_usv_string,
+ ArrayBufferView, BufferSource, BufferSourceRules, CppInterface, EmptyDictionary, FromJs, ToJs, UsvString,
+ record_to_js, rooted_sequence_to_js, sequence_from_js, sequence_to_js, to_array_buffer_view, to_boolean,
+ to_buffer_source, to_cpp_interface, to_dom_string, to_float, to_long, to_long_long, to_typed_array,
+ to_unrestricted_double, to_unrestricted_float, to_unsigned_long, to_unsigned_long_long, to_usv_string,
}};
use crate::bindings::interface::{{
Inherits, Interface, Ref, Wrapped, construct_arguments, construct_wrapper, define_attribute,
@@ -757,6 +758,28 @@ def write_rust_constructor(
)
+def write_cpp_interface_names(out: TextIO, usage: DefinitionUsage, interface_name_values: Dict[str, int]) -> None:
+ """The values by which the bindings ask LibWeb whether an object implements an interface that it implements in
+ C++."""
+ if not usage.cpp_interfaces_named_by_rust:
+ return
+ out.write(
+ """
+/// Web::Bindings::InterfaceName of the interfaces that LibWeb implements in C++ and that the interfaces implemented in
+/// Rust name.
+pub(crate) mod cpp_interface_names {
+"""
+ )
+ for name, interface in sorted(usage.cpp_interfaces_named_by_rust.items()):
+ if name not in interface_name_values:
+ raise UnsupportedByRustBindings(
+ f"An interface implemented in Rust names {name}, which has no Web::Bindings::InterfaceName"
+ )
+ constant = cpp_interface_name_constant(interface).rpartition("::")[2]
+ out.write(f" pub(crate) const {constant}: u16 = {interface_name_values[name]};\n")
+ out.write("}\n")
+
+
def write_rust_definitions(out: TextIO, context: GenerationContext, usage: DefinitionUsage) -> None:
"""The conversions of the dictionaries and unions that the interfaces implemented in Rust name, each written once,
whichever interfaces name it."""
@@ -778,12 +801,12 @@ pub(crate) mod definitions {
use crate::bindings::CallContext;
use crate::bindings::conversions::{
- ArrayBufferView, BufferSource, BufferSourceRules, EmptyDictionary, FromJs, ToJs, UsvString,
- dictionary_member, dictionary_object, enumeration_value_to_js, iterator_method, record_to_js,
- rooted_sequence_to_js, sequence_from_iterable, sequence_from_js, sequence_to_js,
- throw_no_union_types_matched, to_array_buffer_view, to_boolean, to_buffer_source, to_dom_string,
- to_enumeration_value, to_float, to_long, to_long_long, to_typed_array, to_unrestricted_double,
- to_unrestricted_float, to_unsigned_long, to_unsigned_long_long, to_usv_string,
+ ArrayBufferView, BufferSource, BufferSourceRules, CppInterface, EmptyDictionary, FromJs, ToJs, UsvString,
+ dictionary_member, dictionary_object, enumeration_value_to_js, implements_cpp_interface, iterator_method,
+ record_to_js, rooted_sequence_to_js, sequence_from_iterable, sequence_from_js, sequence_to_js,
+ throw_no_union_types_matched, to_array_buffer_view, to_boolean, to_buffer_source, to_cpp_interface,
+ to_dom_string, to_enumeration_value, to_float, to_long, to_long_long, to_typed_array,
+ to_unrestricted_double, to_unrestricted_float, to_unsigned_long, to_unsigned_long_long, to_usv_string,
};
use crate::bindings::interface::{Ref, create_dictionary_object, set_dictionary_member, to_interface};
"""
@@ -821,8 +844,9 @@ def write_rust_bindings(
// The bindings of the interfaces that are implemented in Rust.
"""
)
- write_rust_definitions(out, context, usage)
values = interface_name_values(intrinsics)
+ write_cpp_interface_names(out, usage, values)
+ write_rust_definitions(out, context, usage)
for module in context.modules:
interface = module.interface
if interface is None or not is_implemented_in_rust(interface):
diff --git a/Meta/Generators/libweb_bindings/rust_to_idl_value.py b/Meta/Generators/libweb_bindings/rust_to_idl_value.py
index 0d71d2bb0e1..6ecfdb06b0a 100644
--- a/Meta/Generators/libweb_bindings/rust_to_idl_value.py
+++ b/Meta/Generators/libweb_bindings/rust_to_idl_value.py
@@ -21,6 +21,8 @@ from Generators.libweb_bindings.rust_types import FLOATING_POINT_TYPES
from Generators.libweb_bindings.rust_types import INTEGER_TYPES
from Generators.libweb_bindings.rust_types import TYPED_ARRAY_NAMES
from Generators.libweb_bindings.rust_types import UnsupportedByRustBindings
+from Generators.libweb_bindings.rust_types import cpp_interface
+from Generators.libweb_bindings.rust_types import cpp_interface_name_constant
from Generators.libweb_bindings.rust_types import holds_cells
from Generators.libweb_bindings.rust_types import is_named_union
from Generators.libweb_bindings.rust_types import member_other_than_undefined
@@ -109,6 +111,9 @@ def rust_to_idl_value(
interface = rust_interface(idl_type, context)
if interface is not None:
return f"to_interface::<{rust_interface_path(interface)}>(vm, {value})"
+ interface = cpp_interface(idl_type, context)
+ if interface is not None:
+ return f'to_cpp_interface(vm, {value}, {cpp_interface_name_constant(interface)}, "{interface.name}")'
dictionary = resolved_dictionary(idl_type, context)
if dictionary is not None:
return f"<{rust_dictionary_path(dictionary, context)}>::from_js(vm, {value})"
@@ -148,6 +153,7 @@ class UnionMembers:
string_type: Optional[IDLType] = None
sequence_type: Optional[IDLParameterizedType] = None
typed_array_types: List[IDLType] = field(default_factory=list)
+ cpp_interface_types: List[IDLType] = field(default_factory=list)
def union_members_by_kind(union_type: IDLUnionType, context: GenerationContext, what: str) -> UnionMembers:
@@ -159,6 +165,8 @@ def union_members_by_kind(union_type: IDLUnionType, context: GenerationContext,
members.string_type = member_type
elif member_type.name in TYPED_ARRAY_NAMES:
members.typed_array_types.append(member_type)
+ elif cpp_interface(member_type, context) is not None:
+ members.cpp_interface_types.append(member_type)
elif (
isinstance(member_type, IDLParameterizedType)
and member_type.name == "sequence"
@@ -323,7 +331,7 @@ def write_union_from_js(out: TextIO, context: GenerationContext, union_type: IDL
dictionary_conversion = (
f"Ok(Self::{rust_union_variant(dictionary_type)}(<{dictionary_path}>::from_js(vm, value)?))"
)
- if members.typed_array_types or members.sequence_type is not None:
+ if members.typed_array_types or members.sequence_type is not None or members.cpp_interface_types:
if dictionary_conversion is not None:
steps.append(
f""" // 3. If V is null or undefined, then:
@@ -335,6 +343,19 @@ def write_union_from_js(out: TextIO, context: GenerationContext, union_type: IDL
"""
)
steps.append(" if value.is_object() {\n")
+ for interface_type in members.cpp_interface_types:
+ interface = context.interfaces[interface_type.name]
+ steps.append(
+ f""" // 5. If V is a platform object, then:
+ // 1. If types includes an interface type that V implements, then return the IDL value that is a
+ // reference to the object V.
+ if implements_cpp_interface(value.as_object(), {cpp_interface_name_constant(interface)}) {{
+ // SAFETY: The object is a wrapper of an object that implements the interface.
+ let object = unsafe {{ CppInterface::from_wrapper(value.as_object()) }};
+ return Ok(Self::{rust_union_variant(interface_type)}(object));
+ }}
+"""
+ )
for typed_array_type in members.typed_array_types:
name = typed_array_type.name
conversion = rust_to_idl_value(typed_array_type, {}, "value", "value", context, what)
diff --git a/Meta/Generators/libweb_bindings/rust_types.py b/Meta/Generators/libweb_bindings/rust_types.py
index f8fe4521b05..6f35193dedb 100644
--- a/Meta/Generators/libweb_bindings/rust_types.py
+++ b/Meta/Generators/libweb_bindings/rust_types.py
@@ -127,6 +127,30 @@ 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 cpp_interface(idl_type: IDLType, context: GenerationContext) -> Optional[Interface]:
+ """The interface that the type names, if LibWeb implements it in C++."""
+ if isinstance(idl_type, (IDLParameterizedType, IDLUnionType)):
+ return None
+ interface = context.interfaces.get(idl_type.name)
+ if interface is None or is_implemented_in_rust(interface):
+ return None
+ if interface.is_namespace or interface.is_callback_interface:
+ return None
+ return interface
+
+
+def cpp_interface_name_constant(interface: Interface) -> str:
+ """The constant of the generated Rust bindings that is the Web::Bindings::InterfaceName of an interface that
+ LibWeb implements in C++."""
+ return f"super::cpp_interface_names::{title_case_to_snake_case(interface.name).upper()}"
+
+
+def is_union_of_cpp_interfaces(idl_type: IDLType, context: GenerationContext) -> bool:
+ return isinstance(idl_type, IDLUnionType) and all(
+ cpp_interface(member_type, context) is not None for member_type in idl_type.flattened_member_types()
+ )
+
+
def inheriting_interfaces(interface: Interface, context: GenerationContext) -> List[Interface]:
"""The interfaces that inherit from the interface, through any number of interfaces between them."""
inheriting = []
@@ -154,14 +178,28 @@ def rust_dictionary_path(dictionary: Dictionary, context: GenerationContext) ->
raise RuntimeError(f"No module defines the dictionary {dictionary.name}")
-def union_typedef_name(idl_type: IDLUnionType, context: GenerationContext, what: str) -> str:
- """The name of the typedef that names the union. The generator resolves typedefs before it converts types, and the
- Rust type of a union needs a name, so the typedef is found again by its type."""
- names = sorted(
+def union_typedef_names(idl_type: IDLUnionType, context: GenerationContext) -> List[str]:
+ return sorted(
name
for name, typedef in context.typedefs.items()
if typedef.type.without_nullable() == idl_type.without_nullable()
)
+
+
+def is_unnamed_union_of_cpp_interfaces(idl_type: IDLType, context: GenerationContext) -> bool:
+ """Whether the IDL values of the union are objects of interfaces that LibWeb implements in C++ and nothing says
+ which. Their Rust type is that of such an object, which is all an implementation can do with one: hand it on."""
+ return (
+ isinstance(idl_type, IDLUnionType)
+ and is_union_of_cpp_interfaces(idl_type, context)
+ and not union_typedef_names(idl_type, context)
+ )
+
+
+def union_typedef_name(idl_type: IDLUnionType, context: GenerationContext, what: str) -> str:
+ """The name of the typedef that names the union. The generator resolves typedefs before it converts types, and the
+ Rust type of a union needs a name, so the typedef is found again by its type."""
+ names = union_typedef_names(idl_type, context)
if not names:
raise UnsupportedByRustBindings(f"{what} has the union type {idl_type}, which no typedef names")
if len(names) > 1:
@@ -194,6 +232,7 @@ def is_named_union(idl_type: IDLType, context: GenerationContext) -> bool:
isinstance(idl_type, IDLUnionType)
and runtime_union_type(idl_type, context) is None
and member_other_than_undefined(idl_type) is None
+ and not is_unnamed_union_of_cpp_interfaces(idl_type, context)
)
@@ -270,6 +309,8 @@ def rust_type(idl_type: IDLType, context: GenerationContext, what: str) -> str:
"not convert yet"
)
return f"Ref<{rust_interface_path(interface)}>"
+ if cpp_interface(idl_type, context) is not None or is_unnamed_union_of_cpp_interfaces(idl_type, context):
+ return "CppInterface"
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.py
index d9f88a73ba1..114e3671f7d 100644
--- a/Meta/Generators/libweb_bindings/rust_usage.py
+++ b/Meta/Generators/libweb_bindings/rust_usage.py
@@ -14,6 +14,7 @@ from typing import Set
from Generators.libweb_bindings.context import GenerationContext
from Generators.libweb_bindings.rust_members import rust_members
+from Generators.libweb_bindings.rust_types import cpp_interface
from Generators.libweb_bindings.rust_types import is_implemented_in_rust
from Generators.libweb_bindings.rust_types import is_named_union
from Generators.libweb_bindings.rust_types import runtime_union_type
@@ -77,6 +78,8 @@ class DefinitionUsage:
self.rust_unions: Dict[IDLUnionType, ConversionDirections] = {}
# The enumerations that the interfaces implemented in Rust name.
self.rust_enumerations: Dict[str, ConversionDirections] = {}
+ # The interfaces that LibWeb implements in C++ and that the interfaces implemented in Rust name.
+ self.cpp_interfaces_named_by_rust: Dict[str, Interface] = {}
# The dictionaries that have a C++ representation.
self.cpp_dictionary_names: Set[str] = set()
self._collect_rust_dictionaries()
@@ -120,6 +123,10 @@ class DefinitionUsage:
return
for child_type in idl_type.child_types():
self._name_for_rust(child_type, from_js, to_js)
+ named_cpp_interface = cpp_interface(idl_type, self.context)
+ if named_cpp_interface is not None:
+ self.cpp_interfaces_named_by_rust[named_cpp_interface.name] = named_cpp_interface
+ return
if idl_type.name in self.context.enumerations:
directions = self.rust_enumerations.setdefault(idl_type.name, ConversionDirections())
directions.from_js = directions.from_js or from_js