Skip to content

Truly independent web browser

Meta+LibWeb: Let the C++ bindings name interfaces implemented in Rust

Aliaksandr Kalenik6c14a2ed87b9
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/interface.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/interface.rs
index 05d549f4a57..36d9617323b 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/interface.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/interface.rs
@@ -255,6 +255,23 @@ fn create_wrapper<T: Interface>(vm: &Vm, realm: Gc<Realm>, prototype: Gc<Object>
}
}
+/// The cell of an object of the interface, as LibWeb's C++ code holds it: a pointer to a class that derives from
+/// Web::Bindings::RustInterfaceCell.
+pub(crate) fn cell_into_abi<T: Interface>(object: Ref<T>) -> *mut c_void {
+ object.as_ptr().cast()
+}
+
+/// The object of the interface whose cell LibWeb's C++ code holds.
+///
+/// # Safety
+///
+/// `cell` must be a live cell of an object of an interface implemented in Rust.
+pub(crate) unsafe fn cell_from_abi<T: Interface>(cell: *mut c_void) -> 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) }.expect("C++ passes the cell of an object of the interface")
+}
+
/// 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-function
pub(crate) fn rejected_promise(vm: &Vm, throw: Throw) -> Value {
@@ -317,6 +334,17 @@ pub(crate) unsafe fn entry_point_arguments<'vm>(
unsafe { (&*vm.cast::<Vm>(), Gc::from_non_null(realm), Gc::from_non_null(object)) }
}
+/// Unwraps the VM and the realm that LibWeb's C++ bindings pass an entry point.
+///
+/// # Safety
+///
+/// The pointers must be the live VM and a live realm.
+pub(crate) unsafe fn realm_arguments<'vm>(vm: *mut c_void, realm: *mut c_void) -> (&'vm Vm, Gc<Realm>) {
+ let realm = NonNull::new(realm.cast::<Realm>()).expect("C++ passes a realm");
+ // SAFETY: The caller guarantees that the pointers are live.
+ unsafe { (&*vm.cast::<Vm>(), Gc::from_non_null(realm)) }
+}
+
/// Unwraps the raw arguments that LibWeb's C++ bindings pass the entry point that constructs an object.
///
/// # Safety
diff --git a/Libraries/LibWeb/Bindings/RustBindingsServices.cpp b/Libraries/LibWeb/Bindings/RustBindingsServices.cpp
index 7e31548b356..3cf3b3998a4 100644
--- a/Libraries/LibWeb/Bindings/RustBindingsServices.cpp
+++ b/Libraries/LibWeb/Bindings/RustBindingsServices.cpp
@@ -14,8 +14,20 @@
// What the Rust bindings of the interfaces implemented in Rust ask of LibWeb's C++ bindings, declared on the Rust
// side in Libraries/LibWeb/Bindings/Rust/src/bindings/services.rs.
+// The wrapper of an object of an interface implemented in Rust that the C++ bindings name, in the wrapper world of
+// the realm, which the Rust bindings generated for those interfaces define.
+extern "C" JSObject* web_rust_bindings_wrap(JSVM*, void* realm, u16 interface_name, void* cell);
+
namespace Web::Bindings {
+GC::Ref<JS::HostObject> wrap_rust_interface_object(WrapperWorld& wrapper_world, JS::Realm& preferred_realm, InterfaceName interface_name, RustInterfaceCell& cell)
+{
+ // NB: The Rust bindings find the wrapper world of an object through the realm that asks for its wrapper.
+ VERIFY(&wrapper_world == &host_defined_wrapper_world(preferred_realm));
+ auto* wrapper = web_rust_bindings_wrap(JS::HostABI::vm_to_abi(preferred_realm.vm()), &preferred_realm, to_underlying(interface_name), &cell);
+ return as<JS::HostObject>(*JS::HostABI::object_from_abi(wrapper));
+}
+
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);
diff --git a/Libraries/LibWeb/Bindings/RustInterface.h b/Libraries/LibWeb/Bindings/RustInterface.h
index 4a41fe2c8d6..dd6c02079d3 100644
--- a/Libraries/LibWeb/Bindings/RustInterface.h
+++ b/Libraries/LibWeb/Bindings/RustInterface.h
@@ -6,17 +6,72 @@
#pragma once
+#include <AK/Concepts.h>
#include <LibGC/Cell.h>
+#include <LibGC/Ptr.h>
#include <LibJS/HostObjectABI.h>
+#include <LibJS/Runtime/HostObject.h>
+#include <LibWeb/Bindings/IntrinsicDefinitions.h>
+#include <LibWeb/Export.h>
+#include <LibWeb/Forward.h>
namespace Web::Bindings {
// The cell of an object of an interface that is implemented in Rust, which the wrappers of the object hold as their
// host data. The Rust bindings in Libraries/LibWeb/Bindings/Rust create these cells and know what they hold.
+//
+// C++ code that holds or receives objects of such an interface names them through a class that derives from this
+// one and uses WEB_RUST_INTERFACE. The class has the name and the header that the implementation class of an
+// interface implemented in C++ would have, so the C++ bindings of the interfaces that name the interface convert
+// its objects as they convert any other: with impl_from() and wrap(), which are overloaded for these classes below.
class RustInterfaceCell : public GC::ForeignCell {
};
// The class that the wrapper class of every interface implemented in Rust derives from.
extern "C" JSHostClass const web_bindings_rust_interface_wrapper_host_class;
+// Says which interface a class that derives from RustInterfaceCell names the objects of. The generated header
+// LibWeb/Bindings/<class_>.h, which the header of the class includes, declares the class of the wrappers.
+#define WEB_RUST_INTERFACE(class_, snake_name) \
+public: \
+ static constexpr auto s_interface_name = ::Web::Bindings::InterfaceName::class_; \
+ static JSHostClass const& wrapper_host_class() \
+ { \
+ return ::Web::Bindings::web_bindings_##snake_name##_wrapper_host_class; \
+ } \
+ \
+private:
+
+template<typename T>
+concept RustInterfaceHandle = IsBaseOf<RustInterfaceCell, T> && GC::IsForeignCellHandle<T> && requires {
+ { T::s_interface_name } -> ConvertibleTo<InterfaceName>;
+ { T::wrapper_host_class() } -> SameAs<JSHostClass const&>;
+};
+
+WEB_API GC::Ref<JS::HostObject> wrap_rust_interface_object(WrapperWorld&, JS::Realm& preferred_realm, InterfaceName, RustInterfaceCell&);
+
+template<RustInterfaceHandle T>
+[[nodiscard]] GC::Ref<JS::HostObject> wrap(WrapperWorld& wrapper_world, JS::Realm& preferred_realm, GC::Ref<T> object)
+{
+ return wrap_rust_interface_object(wrapper_world, preferred_realm, T::s_interface_name, *object);
+}
+
+template<RustInterfaceHandle T>
+[[nodiscard]] GC::Ptr<JS::HostObject> wrap(WrapperWorld& wrapper_world, JS::Realm& preferred_realm, GC::Ptr<T> object)
+{
+ if (!object)
+ return nullptr;
+ 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.
+template<RustInterfaceHandle Impl, typename Object>
+[[nodiscard]] CopyConst<Object, Impl>* impl_from(Object* object)
+{
+ if (!object || !JS::is_host_instance_of(*object, Impl::wrapper_host_class()))
+ return nullptr;
+ return GC::static_cell_cast<Impl>(JS::host_data_of(*object).ptr());
+}
+
}
diff --git a/Libraries/LibWeb/Bindings/Wrappable.h b/Libraries/LibWeb/Bindings/Wrappable.h
index dcfd4f47b63..dcd6905453a 100644
--- a/Libraries/LibWeb/Bindings/Wrappable.h
+++ b/Libraries/LibWeb/Bindings/Wrappable.h
@@ -268,10 +268,9 @@ WEB_API Wrappable* wrappable_impl_from(JS::Object*);
WEB_API Wrappable const* wrappable_impl_from(JS::Object const*);
template<typename Impl, typename Object>
+requires(IsBaseOf<Wrappable, Impl>)
[[nodiscard]] CopyConst<Object, Impl>* impl_from(Object* object)
{
- static_assert(IsBaseOf<Wrappable, Impl>);
-
if (!object)
return nullptr;
diff --git a/Meta/Generators/generate_libweb_bindings.py b/Meta/Generators/generate_libweb_bindings.py
index e06ff03ef2f..dcdea39e2e4 100644
--- a/Meta/Generators/generate_libweb_bindings.py
+++ b/Meta/Generators/generate_libweb_bindings.py
@@ -187,7 +187,10 @@ def write_forward_header(out: TextIO, modules: List[Module], usage: DefinitionUs
for module in modules:
interface = module.interface
- if interface is None or interface.is_namespace or rust_bindings.is_implemented_in_rust(interface):
+ if interface is None or interface.is_namespace:
+ continue
+ # NB: An interface implemented in Rust has a C++ class only if the C++ bindings convert objects of it.
+ if rust_bindings.is_implemented_in_rust(interface) and interface.name not in usage.rust_interfaces_named_by_cpp:
continue
namespace_name = cpp_namespace_for_module_path(interface.path)
diff --git a/Meta/Generators/libweb_bindings/rust_bindings.py b/Meta/Generators/libweb_bindings/rust_bindings.py
index 566165d850d..b45d453eb90 100644
--- a/Meta/Generators/libweb_bindings/rust_bindings.py
+++ b/Meta/Generators/libweb_bindings/rust_bindings.py
@@ -110,27 +110,6 @@ def check_interface_is_supported(interface: Interface, module: Module, context:
rust_members(interface)
-def check_cpp_does_not_name_rust_interfaces(context: GenerationContext, usage: DefinitionUsage) -> None:
- """An interface implemented in Rust has no C++ implementation object, so the C++ bindings cannot convert it."""
- rust_interfaces = {interface.name for interface in context.interfaces.values() if is_implemented_in_rust(interface)}
- if not rust_interfaces:
- return
-
- def check(path, types) -> None:
- for idl_type in types:
- for nested_type in idl_type.nested_types():
- if nested_type.name in rust_interfaces:
- raise UnsupportedByRustBindings(
- f"{path}: uses {nested_type.name}, which is implemented in Rust and has no C++ representation"
- )
-
- for module in context.modules:
- if not is_implemented_in_rust(module.interface):
- check(module.path, usage.types_named_by_cpp_module(module))
- for dictionary in usage.cpp_dictionaries(module):
- check(module.path, [member.type for member in dictionary.members])
-
-
# C++ side
@@ -867,13 +846,68 @@ def write_rust_bindings(
if interface is None or not is_implemented_in_rust(interface):
continue
write_rust_interface(out, context, module, interface, values[interface.name])
+ write_rust_wrap_for_cpp(out, usage)
+
+
+def write_rust_wrap_for_cpp(out: TextIO, usage: DefinitionUsage) -> None:
+ """The entry point through which the C++ bindings of the interfaces that name an interface implemented in Rust
+ wrap an object of it, which C++ code holds as the cell of the object."""
+ documentation = """
+/// The wrapper of an object of an interface implemented in Rust in the wrapper world of the realm, for the C++
+/// bindings of the interfaces that name the interface.
+///
+/// # Safety
+///
+/// The pointers must be the VM, a live realm, and the live cell of an object of the interface.
+#[unsafe(no_mangle)]
+"""
+ if not usage.rust_interfaces_named_by_cpp:
+ out.write(
+ f"""{documentation}pub unsafe extern "C" fn web_rust_bindings_wrap(
+ _vm: *mut core::ffi::c_void,
+ _realm: *mut core::ffi::c_void,
+ _interface_name: u16,
+ _cell: *mut core::ffi::c_void,
+) -> *mut core::ffi::c_void {{
+ unreachable!("LibWeb's C++ bindings name no interface that is implemented in Rust")
+}}
+"""
+ )
+ return
+ arms = "".join(
+ 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())
+ )
+ out.write(
+ f"""{documentation}pub unsafe extern "C" fn web_rust_bindings_wrap(
+ vm: *mut core::ffi::c_void,
+ realm: *mut core::ffi::c_void,
+ interface_name: u16,
+ 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}};
+
+ // SAFETY: The caller passes the VM and a live realm.
+ let (vm, realm) = unsafe {{ realm_arguments(vm, realm) }};
+ let cx = CallContext::new(vm, realm);
+ let wrapper = match interface_name {{
+{arms} _ => unreachable!("LibWeb's C++ bindings name no other interface that is implemented in Rust"),
+ }};
+ wrapper.as_ptr().cast()
+}}
+"""
+ )
def check_rust_bindings(context: GenerationContext, usage: DefinitionUsage, intrinsics: List[Interface]) -> None:
"""Raises an error for every use of [ImplementedIn] that the bindings do not handle, before anything is written.
The functions that write the Rust bindings reject the types and the definitions that they do not handle
themselves, so the bindings are written once to find those."""
- check_cpp_does_not_name_rust_interfaces(context, usage)
for module in context.modules:
interface = module.interface
if interface is None:
diff --git a/Meta/Generators/libweb_bindings/rust_usage.py b/Meta/Generators/libweb_bindings/rust_usage.py
index 114e3671f7d..e2276656ed8 100644
--- a/Meta/Generators/libweb_bindings/rust_usage.py
+++ b/Meta/Generators/libweb_bindings/rust_usage.py
@@ -25,11 +25,20 @@ from Utils.webidl_parser import Interface
from Utils.webidl_parser import Module
-def types_named_by_interface(interface: Interface) -> List[IDLType]:
- """Every type that the members of the interface name, which the bindings of the interface convert."""
+def types_named_by_interface(interface: Interface, with_unimplemented_members: bool = True) -> List[IDLType]:
+ """Every type that the members of the interface name. The bindings of the interface convert them, except those of
+ the members marked [FIXME], which they only record as not implemented."""
+
+ def is_wanted(extended_attributes: Dict[str, str]) -> bool:
+ return with_unimplemented_members or "FIXME" not in extended_attributes
+
types = []
- types.extend(attribute.type for attribute in interface.regular_attributes + interface.static_attributes)
+ for attribute in interface.regular_attributes + interface.static_attributes:
+ if is_wanted(attribute.extended_attributes):
+ types.append(attribute.type)
for operation in interface.regular_operations + interface.static_operations:
+ if not is_wanted(operation.extended_attributes):
+ continue
types.append(operation.return_type)
types.extend(parameter.type for parameter in operation.parameters)
for constructor in interface.constructors:
@@ -82,8 +91,11 @@ class DefinitionUsage:
self.cpp_interfaces_named_by_rust: Dict[str, Interface] = {}
# The dictionaries that have a C++ representation.
self.cpp_dictionary_names: Set[str] = set()
+ # The interfaces implemented in Rust that the C++ bindings convert objects of, and so need a C++ class for.
+ self.rust_interfaces_named_by_cpp: Dict[str, Interface] = {}
self._collect_rust_dictionaries()
self._collect_cpp_dictionaries()
+ self._collect_rust_interfaces_named_by_cpp()
def cpp_dictionaries(self, module: Module) -> List[Dictionary]:
"""The dictionaries of the module that the C++ bindings declare and convert."""
@@ -161,11 +173,26 @@ class DefinitionUsage:
self._name_for_cpp(dictionary.name)
self._name_types_for_cpp(self.types_named_by_cpp_module(module))
- def types_named_by_cpp_module(self, module: Module) -> List[IDLType]:
+ def _collect_rust_interfaces_named_by_cpp(self) -> None:
+ def name(types: Iterable[IDLType]) -> None:
+ for idl_type in types:
+ for nested_type in idl_type.nested_types():
+ interface = self.context.interfaces.get(nested_type.name)
+ if is_implemented_in_rust(interface):
+ assert interface is not None
+ self.rust_interfaces_named_by_cpp[interface.name] = interface
+
+ for module in self.context.modules:
+ if not is_implemented_in_rust(module.interface):
+ name(self.types_named_by_cpp_module(module, with_unimplemented_members=False))
+ for dictionary in self.cpp_dictionaries(module):
+ name(member.type for member in dictionary.members)
+
+ def types_named_by_cpp_module(self, module: Module, with_unimplemented_members: bool = True) -> List[IDLType]:
"""The types that the interface, typedefs and callback functions of a module of the C++ bindings name."""
types = []
if module.interface is not None:
- types.extend(types_named_by_interface(module.interface))
+ types.extend(types_named_by_interface(module.interface, with_unimplemented_members))
types.extend(typedef.type for typedef in module.typedefs)
for callback_function in module.callback_functions:
types.append(callback_function.return_type)