Skip to content

Truly independent web browser

LibWeb: Support namespaces and more IDL in the Rust bindings

Shannon Booth08169678fc20
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs
index cdacc1dd412..71e15d59a91 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs
@@ -659,6 +659,23 @@ unsafe fn borrowed_or_copied_bytes_of_buffer(buffer: &ArrayBuffer, bytes: Range<
Some(Cow::Borrowed(unsafe { ak::slice_from_raw_parts(data, bytes.len()) }))
}
+/// A promise converted from a JS value, https://webidl.spec.whatwg.org/#js-promise
+#[allow(
+ clippy::unnecessary_wraps,
+ reason = "the bindings convert every argument with a conversion that can throw"
+)]
+pub(crate) fn to_promise(vm: &Vm, value: Value) -> ThrowCompletionOr<WebIdlPromise> {
+ // 1. Let promiseCapability be ? NewPromiseCapability(%Promise%).
+ let realm = vm.current_realm().expect("a conversion runs in a realm");
+ let promise = crate::bindings::promise::create_promise(vm, realm);
+
+ // 2. Perform ? Call(promiseCapability.[[Resolve]], undefined, « V »).
+ crate::bindings::promise::resolve_promise(vm, promise, value);
+
+ // 3. Return promiseCapability.
+ Ok(promise)
+}
+
/// The value as a BufferSource, if it is an ArrayBuffer, a DataView or a typed array, without the checks of a
/// conversion to the type.
pub(crate) fn buffer_source_type_of(value: Value) -> Option<BufferSource> {
@@ -1062,6 +1079,12 @@ impl ToJs for Gc<TypedArrayBase> {
}
}
+impl ToJs for Gc<ArrayBuffer> {
+ fn to_js(self, _: &CallContext) -> ThrowCompletionOr<Value> {
+ Ok(Value::from_object(self))
+ }
+}
+
/// An object of an interface converted to a JS value, https://webidl.spec.whatwg.org/#js-interface
impl<T: Interface> ToJs for Ref<T> {
fn to_js(self, cx: &CallContext) -> ThrowCompletionOr<Value> {
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/promise.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/promise.rs
index 615d4d845df..1673289034a 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/promise.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/promise.rs
@@ -7,7 +7,7 @@
//! Promises as implementations hold them, https://webidl.spec.whatwg.org/#idl-promise: the PromiseCapability records
//! that LibWeb's C++ code calls WebIDL::Promise.
-use core::cell::Cell;
+use core::cell::{Cell, RefCell};
use core::ffi::c_void;
use core::ptr::NonNull;
@@ -26,6 +26,37 @@ unsafe extern "C" {
/// Queues a microtask that calls the function, a native function with no arguments, while an execution context of
/// the realm is on the stack, as HTML::queue_a_microtask() queues one without a document.
fn web_bindings_queue_a_microtask(realm: *mut c_void, function: *mut c_void);
+
+ /// Calls the steps with the VM and the cell in parallel: later, outside of any task, while an execution context of
+ /// the realm is on the stack. The cell lives until then.
+ fn web_bindings_run_in_parallel(
+ realm: *mut c_void,
+ cell: *mut c_void,
+ steps: unsafe extern "C" fn(*mut c_void, *mut c_void),
+ );
+
+ /// Queues a task on the task source, an HTML::Task::Source, that calls the steps with the VM and the cell while an
+ /// execution context of the realm is on the stack, as HTML::queue_a_task() queues one without a document. The
+ /// cell lives until then.
+ fn web_bindings_queue_a_task(
+ realm: *mut c_void,
+ task_source: u8,
+ cell: *mut c_void,
+ steps: unsafe extern "C" fn(*mut c_void, *mut c_void),
+ );
+}
+
+/// The task sources of HTML::Task::Source that the bindings queue tasks on.
+#[derive(Clone, Copy)]
+#[repr(u8)]
+pub(crate) enum TaskSource {
+ Unspecified = 0,
+ Networking = 3,
+}
+
+// SAFETY: A task source holds no cells.
+unsafe impl Trace for TaskSource {
+ fn trace(&self, _: &mut Visitor) {}
}
/// The promise that LibWeb's C++ code returns, a WebIDL::Promise.
@@ -456,6 +487,93 @@ pub(crate) fn queue_a_microtask<C: Trace + Copy + 'static>(vm: &Vm, realm: Gc<Re
unsafe { web_bindings_queue_a_microtask(realm.as_ptr().cast(), function.as_ptr().cast()) };
}
+/// Steps with what they capture, which run once, later, from a task or in parallel. They run as C++ code would, with
+/// no function of their own on the stack.
+trait DeferredSteps: Trace {
+ fn run(&self, vm: &Vm);
+}
+
+struct CapturedSteps<C> {
+ captures: C,
+ steps: fn(&Vm, C),
+}
+
+// SAFETY: The steps are a plain function, which holds no cells.
+unsafe impl<C: Trace> Trace for CapturedSteps<C> {
+ fn trace(&self, visitor: &mut Visitor) {
+ self.captures.trace(visitor);
+ }
+}
+
+impl<C: Trace + Copy + 'static> DeferredSteps for CapturedSteps<C> {
+ fn run(&self, vm: &Vm) {
+ (self.steps)(vm, self.captures);
+ }
+}
+
+/// The cell that keeps deferred steps and what they capture alive until they run.
+struct PendingSteps(RefCell<Option<Box<dyn DeferredSteps>>>);
+
+// SAFETY: The steps that have not run are all the cells this reaches.
+unsafe impl Trace for PendingSteps {
+ fn trace(&self, visitor: &mut Visitor) {
+ if let Some(steps) = &*self.0.borrow() {
+ steps.trace(visitor);
+ }
+ }
+}
+
+static PENDING_STEPS_CLASS: EmbedderClass<PendingSteps> = EmbedderClass::new("PendingSteps");
+
+impl EmbedderValue for PendingSteps {
+ const CLASS: &'static EmbedderClass<Self> = &PENDING_STEPS_CLASS;
+}
+
+fn pending_steps<C: Trace + Copy + 'static>(vm: &Vm, captures: C, steps: fn(&Vm, C)) -> *mut c_void {
+ PENDING_STEPS_CLASS
+ .allocate(vm, |_| {
+ let steps: Box<dyn DeferredSteps> = Box::new(CapturedSteps { captures, steps });
+ PendingSteps(RefCell::new(Some(steps)))
+ })
+ .as_ptr()
+ .cast()
+}
+
+unsafe extern "C" fn run_pending_steps(vm: *mut c_void, cell: *mut c_void) {
+ // SAFETY: LibWeb passes the VM and the cell that pending_steps() made, which it kept alive.
+ let (vm, cell) = unsafe {
+ (
+ &*vm.cast::<Vm>(),
+ Gc::from_non_null(NonNull::new_unchecked(cell.cast::<EmbedderCell<PendingSteps>>())),
+ )
+ };
+ // NB: The cell keeps what the steps capture alive while they run, and lets go of it once they have.
+ cell.0.borrow().as_ref().expect("deferred steps run once").run(vm);
+ cell.0.take();
+}
+
+/// Performs the steps with the captures in parallel, https://html.spec.whatwg.org/multipage/infrastructure.html#in-parallel,
+/// with an execution context of the realm on the stack.
+pub(crate) fn in_parallel<C: Trace + Copy + 'static>(vm: &Vm, realm: Gc<Realm>, captures: C, steps: fn(&Vm, C)) {
+ let cell = pending_steps(vm, captures, steps);
+ // SAFETY: The realm and the cell are live.
+ unsafe { web_bindings_run_in_parallel(realm.as_ptr().cast(), cell, run_pending_steps) };
+}
+
+/// Queues a task on the task source that performs the steps with the captures,
+/// https://html.spec.whatwg.org/multipage/webappapis.html#queue-a-task
+pub(crate) fn queue_a_task<C: Trace + Copy + 'static>(
+ vm: &Vm,
+ realm: Gc<Realm>,
+ task_source: TaskSource,
+ captures: C,
+ steps: fn(&Vm, C),
+) {
+ let cell = pending_steps(vm, captures, steps);
+ // SAFETY: The realm and the cell are live.
+ unsafe { web_bindings_queue_a_task(realm.as_ptr().cast(), task_source as u8, cell, run_pending_steps) };
+}
+
/// The [[Promise]] of a promise capability that LibWeb created, which is a Promise.
fn promise_object(promise: WebIdlPromise) -> Gc<Promise> {
promise
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/structured_data.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/structured_data.rs
index 46c20b4a80a..ab8a6dc1ff5 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/structured_data.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/structured_data.rs
@@ -39,6 +39,11 @@ unsafe extern "C" {
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_deserialize_i64(serialized: *mut c_void, out_value: &mut i64) -> RawNativeFunctionResult;
+ fn web_bindings_deserialize_bytes(
+ serialized: *mut c_void,
+ bytes: *mut c_void,
+ append: unsafe extern "C" fn(*mut c_void, *const u8, usize),
+ ) -> RawNativeFunctionResult;
fn web_bindings_deserialize_utf16_string(
serialized: *mut c_void,
out_string: &mut usize,
@@ -173,6 +178,18 @@ impl SerializationReader<'_> {
Ok(value)
}
+ pub(crate) fn read_bytes(&mut self) -> WebIdlResult<Vec<u8>> {
+ unsafe extern "C" fn append(bytes: *mut c_void, data: *const u8, length: usize) {
+ // SAFETY: The bytes are the Vec that read_bytes() lends, and LibWeb passes that many bytes.
+ unsafe { (*bytes.cast::<Vec<u8>>()).extend_from_slice(ak::slice_from_raw_parts(data, length)) };
+ }
+ let mut bytes = Vec::new();
+ // SAFETY: The reader and the bytes are lent for the steps.
+ unsafe { web_bindings_deserialize_bytes(self.raw.as_ptr(), (&raw mut bytes).cast(), append) }
+ .into_completion()?;
+ Ok(bytes)
+ }
+
pub(crate) fn read_utf16_string(&mut self) -> WebIdlResult<Utf16String> {
let mut string = 0;
// SAFETY: The reader is lent for the steps.
diff --git a/Libraries/LibWeb/Bindings/RustBindingsServices.cpp b/Libraries/LibWeb/Bindings/RustBindingsServices.cpp
index f18d206e633..0c828fcad6f 100644
--- a/Libraries/LibWeb/Bindings/RustBindingsServices.cpp
+++ b/Libraries/LibWeb/Bindings/RustBindingsServices.cpp
@@ -19,6 +19,7 @@
#include <LibWeb/HTML/StructuredSerialize.h>
#include <LibWeb/HTML/Window.h>
#include <LibWeb/HTML/WindowProxy.h>
+#include <LibWeb/Platform/EventLoopPlugin.h>
#include <LibWeb/WebIDL/AbstractOperations.h>
#include <LibWeb/WebIDL/CallbackType.h>
#include <LibWeb/WebIDL/DOMException.h>
@@ -91,6 +92,8 @@ 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);
void web_bindings_queue_a_microtask(void* realm, JSObject* function);
+void web_bindings_run_in_parallel(void* realm, void* cell, void (*steps)(JSVM*, void*));
+void web_bindings_queue_a_task(void* realm, u8 task_source, void* cell, void (*steps)(JSVM*, void*));
void* web_bindings_create_callback_function(JSObject* callable, bool returns_promise);
JSCompletion web_bindings_invoke_callback_function(void* callback, bool has_this_value, JSValue this_value, ReadonlySpan<JSValue> arguments);
void* web_bindings_invoke_promise_callback_function(void* callback, bool has_this_value, JSValue this_value, ReadonlySpan<JSValue> arguments);
@@ -111,6 +114,7 @@ JSCompletion web_bindings_deserialize_u32(RustSerializationReader*, u32* out_val
JSCompletion web_bindings_deserialize_f64(RustSerializationReader*, double* out_value);
JSCompletion web_bindings_deserialize_bool(RustSerializationReader*, bool* out_value);
JSCompletion web_bindings_deserialize_i64(RustSerializationReader*, i64* out_value);
+JSCompletion web_bindings_deserialize_bytes(RustSerializationReader*, void* bytes, void (*append)(void*, u8 const*, size_t));
JSCompletion web_bindings_deserialize_utf16_string(RustSerializationReader*, FlatPtr* out_string);
void web_bindings_serialize_inline_object_header(RustSerializationWriter*, u16 interface_name);
JSCompletion web_bindings_deserialize_inline_object_header(RustSerializationReader*, u16 interface_name);
@@ -247,6 +251,15 @@ JSCompletion web_bindings_deserialize_i64(RustSerializationReader* reader, i64*
return deserialize_plain_value(reader, out_value);
}
+JSCompletion web_bindings_deserialize_bytes(RustSerializationReader* reader, void* bytes, void (*append)(void*, u8 const*, size_t))
+{
+ ByteBuffer buffer;
+ auto result = deserialize_plain_value(reader, &buffer);
+ if (!buffer.is_empty())
+ append(bytes, buffer.data(), buffer.size());
+ return result;
+}
+
JSCompletion web_bindings_deserialize_utf16_string(RustSerializationReader* reader, FlatPtr* out_string)
{
Utf16String string;
@@ -305,6 +318,30 @@ void web_bindings_queue_a_microtask(void* realm, JSObject* function)
}));
}
+void web_bindings_run_in_parallel(void* realm, void* cell, void (*steps)(JSVM*, void*))
+{
+ GC::Ref<JS::Realm> js_realm = *static_cast<JS::Realm*>(realm);
+ // NB: The function's captures, which the collector scans, keep the cell alive until the steps run.
+ Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), [js_realm, cell, steps] {
+ HTML::TemporaryExecutionContext execution_context { js_realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };
+ steps(JS::HostABI::vm_to_abi(js_realm->vm()), cell);
+ }));
+}
+
+// NB: The task sources of the Rust bindings' TaskSource.
+static_assert(to_underlying(HTML::Task::Source::Unspecified) == 0);
+static_assert(to_underlying(HTML::Task::Source::Networking) == 3);
+
+void web_bindings_queue_a_task(void* realm, u8 task_source, void* cell, void (*steps)(JSVM*, void*))
+{
+ GC::Ref<JS::Realm> js_realm = *static_cast<JS::Realm*>(realm);
+ // NB: The task's captures, which the collector scans, keep the cell alive until the steps run.
+ HTML::queue_a_task(static_cast<HTML::Task::Source>(task_source), nullptr, nullptr, GC::create_function(GC::Heap::the(), [js_realm, cell, steps] {
+ HTML::TemporaryExecutionContext execution_context { js_realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };
+ steps(JS::HostABI::vm_to_abi(js_realm->vm()), cell);
+ }));
+}
+
void* web_bindings_create_callback_function(JSObject* callable, bool returns_promise)
{
auto& object = *JS::HostABI::object_from_abi(callable);
diff --git a/Meta/Generators/libweb_bindings/rust_bindings.py b/Meta/Generators/libweb_bindings/rust_bindings.py
index fabeca22c27..6e960fe8178 100644
--- a/Meta/Generators/libweb_bindings/rust_bindings.py
+++ b/Meta/Generators/libweb_bindings/rust_bindings.py
@@ -73,6 +73,9 @@ SUPPORTED_INTERFACE_EXTENDED_ATTRIBUTES = {
# 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 define the interface object of such an interface on the namespace object, whatever the
+ # language of the interface.
+ "LegacyNamespace",
# NB: The C++ bindings only leave the interface object of such an interface off the global object.
"LegacyNoInterfaceObject",
"NavigatorCompatibilityMode",
@@ -84,6 +87,14 @@ SUPPORTED_INTERFACE_EXTENDED_ATTRIBUTES = {
"Transferable",
}
+# The extended attributes of a namespace that the Rust bindings handle.
+SUPPORTED_NAMESPACE_EXTENDED_ATTRIBUTES = {
+ "Exposed",
+ "ImplementedIn",
+ # NB: The implementation finishes the namespace object through its function initialize().
+ "WithInitializer",
+}
+
def rust_module_name(interface: Interface) -> str:
return title_case_to_snake_case(interface.name)
@@ -118,11 +129,14 @@ def check_interface_is_supported(interface: Interface, module: Module, context:
def fail(message: str) -> None:
raise UnsupportedByRustBindings(f"{interface.path}: {interface.name} is [ImplementedIn=Rust], but {message}")
- unsupported_attributes = set(interface.extended_attributes) - SUPPORTED_INTERFACE_EXTENDED_ATTRIBUTES
+ supported_attributes = (
+ SUPPORTED_NAMESPACE_EXTENDED_ATTRIBUTES if interface.is_namespace else SUPPORTED_INTERFACE_EXTENDED_ATTRIBUTES
+ )
+ unsupported_attributes = set(interface.extended_attributes) - supported_attributes
if unsupported_attributes:
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.is_callback_interface:
+ fail("it is a callback 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.callback_functions:
@@ -139,6 +153,16 @@ def check_interface_is_supported(interface: Interface, module: Module, context:
def write_cpp_declaration(out: TextIO, includes: GeneratedIncludes, interface: Interface) -> None:
+ if interface.is_namespace:
+ includes.add("LibJS/Runtime/Object.h")
+ out.write(
+ f"""struct {interface.namespace_class} {{
+ static void initialize(JS::Realm&, JS::Object&);
+}};
+
+"""
+ )
+ return
includes.add("LibJS/HostObjectABI.h")
includes.add("LibJS/Runtime/NativeFunction.h")
includes.add("LibJS/Runtime/Object.h")
@@ -191,6 +215,22 @@ public:
def write_cpp_implementation(
out: TextIO, includes: GeneratedIncludes, context: GenerationContext, interface: Interface
) -> None:
+ if interface.is_namespace:
+ includes.add("LibJS/HostClassBuilder.h")
+ includes.add("LibJS/Runtime/Realm.h")
+ includes.add_binding(interface.implemented_name)
+ initialize_namespace = rust_entry_point_name(interface, "initialize_namespace")
+ out.write(
+ f"""extern "C" void {initialize_namespace}(JSVM*, void* realm, JSObject* object);
+
+void {interface.namespace_class}::initialize(JS::Realm& realm, JS::Object& object)
+{{
+ {initialize_namespace}(JS::HostABI::vm_to_abi(realm.vm()), &realm, JS::HostABI::object_to_abi(&object));
+}}
+
+"""
+ )
+ return
includes.add("LibJS/HostClassBuilder.h")
includes.add("LibJS/Runtime/Error.h")
includes.add("LibJS/Runtime/HostFunction.h")
@@ -339,7 +379,9 @@ extern "C" JSObject* web_bindings_ensure_web_iterator_prototype(void* realm, u16
def write_ensure_web_prototype_implementation(out: TextIO, intrinsics: List[Interface]) -> None:
- rust_interfaces = [interface for interface in intrinsics if is_implemented_in_rust(interface)]
+ rust_interfaces = [
+ interface for interface in intrinsics if is_implemented_in_rust(interface) and not interface.is_namespace
+ ]
def write_switch(function: str, interfaces: List[Interface], object_of: Callable[[Interface], str]) -> None:
out.write(
@@ -690,61 +732,109 @@ def write_rust_async_iterator(out: TextIO, context: GenerationContext, interface
)
-def write_rust_interface(
- out: TextIO, context: GenerationContext, module: Module, interface: Interface, interface_name_value: int
-) -> 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)
- )
- out.write(
- f"""
-/// The bindings of {interface.name}, which call these methods of its implementation, {implementation}:
-{method_documentation}pub(crate) mod {rust_module_name(interface)} {{
- #![allow(unused_imports)]
+# The context of an attribute or an operation that is [NeedsCallerRealm], whose results are created in the current realm.
+CALLER_REALM_CONTEXT = (
+ ' let mut cx = CallContext::new(vm, vm.current_realm().expect("a native function runs in a realm"));\n'
+)
+
+RUST_BINDINGS_IMPORTS = """ #![allow(unused_imports)]
use core::ffi::c_void;
use ak::Utf16String;
- use libjs_rust::api::{{
+ use libjs_rust::api::{
ArrayBuffer, DataView, EmbedderClass, ErrorKind, ErrorType, FunctionObject, Gc, JSHostClass, MarkedVec,
Object, PropertyKey, RawNativeFunctionResult, ThrowCompletionOr, TypedArrayBase, TypedArrayKind, Value, Vm,
is_host_instance_of, raw_native,
- }};
+ };
- use crate::bindings::conversions::{{
+ use crate::bindings::conversions::{
ArrayBufferView, BufferSource, BufferSourceRules, CppInterface, EmptyDictionary, FromJs, ToJs, UsvString,
implements_cpp_interface, record_from_js, 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_cpp_interface_in_union, to_dom_string,
to_dom_string_treating_null_as_empty, to_double, to_float, to_long, to_long_enforcing_range, to_long_long,
- to_long_long_clamping, to_long_long_enforcing_range, to_object, to_typed_array, to_unrestricted_double,
- to_unrestricted_float, to_unsigned_long, to_unsigned_long_enforcing_range, to_unsigned_long_long,
- to_unsigned_long_long_enforcing_range, to_usv_string,
- }};
- use crate::bindings::interface::{{
+ to_long_long_clamping, to_long_long_enforcing_range, to_object, to_promise, to_typed_array,
+ to_unrestricted_double, to_unrestricted_float, to_unsigned_long, 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, 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::async_iterable::{{
+ };
+ use crate::bindings::async_iterable::{
AsyncIterable, DefaultAsyncIterator, DefaultAsyncIteratorClasses, async_iterator_next, async_iterator_return,
create_default_async_iterator, define_async_iterator_properties,
- }};
- use crate::bindings::iterable::{{
+ };
+ use crate::bindings::iterable::{
DefaultIterator, DefaultIteratorClasses, define_pair_iterator_properties, entries, for_each, iterator_next, keys,
values,
- }};
- use crate::bindings::callback::{{CallbackFunction, PromiseCallbackFunction}};
+ };
+ use crate::bindings::callback::{CallbackFunction, PromiseCallbackFunction};
use crate::bindings::promise::WebIdlPromise;
use crate::bindings::structured_data;
- use crate::bindings::{{CallContext, WebIdlResult}};
+ use crate::bindings::{CallContext, WebIdlResult};
+"""
+
+def write_rust_operation_set(
+ out: TextIO,
+ context: GenerationContext,
+ interface: Interface,
+ operation_set: RustOperationSet,
+ write_steps: Callable[[TextIO, GenerationContext, Interface, str, str, RustOperation], None],
+) -> None:
+ """The native function of an operation, which `write_steps` writes for one overload, and which chooses between the
+ overloads of an overloaded operation."""
+ name = operation_set.name
+ if len(operation_set.overloads) == 1:
+ write_steps(out, context, interface, name, operation_set.function, operation_set.overloads[0])
+ return
+ for overload in operation_set.overloads:
+ write_steps(out, context, interface, name, overload.steps_function, overload)
+ returns_promise = operation_set.overloads[0].operation.return_type_is_promise()
+ resolution = operation_set.function
+ if returns_promise:
+ resolution = f"{operation_set.function.removesuffix('_function')}_overload_resolution"
+ write_operation_overload_resolution(
+ out,
+ context,
+ interface,
+ name,
+ resolution,
+ [overload.operation for overload in operation_set.overloads],
+ [overload.steps_function for overload in operation_set.overloads],
+ )
+ if returns_promise:
+ out.write(
+ f"""
+ fn {operation_set.function}(vm: &Vm) -> ThrowCompletionOr<Value> {{
+ // An exception that the overload resolution of an operation with a promise type throws rejects a new promise,
+ // https://webidl.spec.whatwg.org/#dfn-create-operation-function
+ {resolution}(vm).or_else(|throw| Ok(rejected_promise(vm, throw)))
+ }}
+"""
+ )
+
+
+def write_rust_interface(
+ out: TextIO, context: GenerationContext, module: Module, interface: Interface, interface_name_value: int
+) -> 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)
+ )
+ out.write(
+ f"""
+/// The bindings of {interface.name}, which call these methods of its implementation, {implementation}:
+{method_documentation}pub(crate) mod {rust_module_name(interface)} {{
+{RUST_BINDINGS_IMPORTS}
use {implementation} as Implementation;
/// Web::Bindings::InterfaceName::{interface.name}.
@@ -800,11 +890,16 @@ def write_rust_interface(
// a new promise.
Err(throw) => return Ok(rejected_promise(vm, throw)),
}"""
+ receiver = "(implementation, mut cx)"
+ caller_realm_context = ""
+ if "NeedsCallerRealm" in attribute.attribute.extended_attributes:
+ receiver = "(implementation, _)"
+ caller_realm_context = CALLER_REALM_CONTEXT
out.write(
f"""
pub(super) fn {attribute.getter_function}(vm: &Vm) -> ThrowCompletionOr<Value> {{
- let (implementation, mut cx) = {this_check};
- let result = {call}
+ let {receiver} = {this_check};
+{caller_realm_context} let result = {call}
.map_err(|exception| exception.throw(&cx))?;
{conversion}
}}
@@ -814,24 +909,10 @@ def write_rust_interface(
write_rust_attribute_setter(out, context, interface, attribute)
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)
continue
- if len(operation_set.overloads) == 1:
- write_rust_operation(out, context, interface, name, operation_set.function, operation_set.overloads[0])
- continue
- for overload in operation_set.overloads:
- write_rust_operation(out, context, interface, name, overload.steps_function, overload)
- write_operation_overload_resolution(
- out,
- context,
- interface,
- name,
- operation_set.function,
- [overload.operation for overload in operation_set.overloads],
- [overload.steps_function for overload in operation_set.overloads],
- )
+ write_rust_operation_set(out, context, interface, operation_set, write_rust_operation)
if members.stringifier is not None:
write_rust_stringifier(out, members.stringifier.function, members.stringifier.method)
@@ -849,14 +930,7 @@ def write_rust_interface(
write_rust_async_iterator(out, context, interface)
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]
- )
+ write_rust_operation_set(out, context, interface, operation_set, write_rust_static_operation)
out.write(
f"""
@@ -1012,6 +1086,112 @@ def write_rust_interface(
out.write("}\n")
+def namespace_function_signatures(context: GenerationContext, interface: Interface, members: RustMembers) -> List[str]:
+ """The functions the implementation of the namespace defines, which the bindings call."""
+ signatures = []
+ for attribute in members.attributes:
+ what = f"{interface.name}.{attribute.attribute.name}"
+ result_type = rust_type(attribute.attribute.type, context, what, is_result=True)
+ signatures.append(f"fn {attribute.getter_method}(cx: &mut CallContext) -> WebIdlResult<{result_type}>")
+ for operation_set in members.operation_sets:
+ for overload in operation_set.overloads:
+ what = f"{interface.name}.{operation_set.name}()"
+ parameters = "".join(
+ f", {rust_identifier(parameter.name)}: {rust_parameter_type(parameter, context, what)}"
+ for parameter in overload.operation.parameters
+ )
+ signatures.append(
+ f"fn {overload.method}(cx: &mut CallContext{parameters}) -> "
+ f"WebIdlResult<{rust_type(overload.operation.return_type, context, what, is_result=True)}>"
+ )
+ if "WithInitializer" in interface.extended_attributes:
+ signatures.append("fn initialize(cx: &mut CallContext, namespace_object: Gc<Object>)")
+ return signatures
+
+
+# https://webidl.spec.whatwg.org/#namespace-object
+def write_rust_namespace(out: TextIO, context: GenerationContext, interface: Interface) -> None:
+ """The bindings of a namespace, whose attributes and operations run in the current realm, as static operations
+ do."""
+ implementation = rust_interface_path(interface)
+ members = rust_members(interface)
+ if members.attributes_in_order != members.attributes or members.unimplemented_operation_names:
+ raise UnsupportedByRustBindings(
+ f"{interface.path}: the namespace {interface.name} has members marked [FIXME], which the Rust bindings do "
+ "not record on a namespace object yet"
+ )
+ if members.constants:
+ raise UnsupportedByRustBindings(
+ f"{interface.path}: the namespace {interface.name} has constants, which the Rust bindings do not handle yet"
+ )
+ for attribute in members.attributes:
+ if attribute.setter_method is not None:
+ raise UnsupportedByRustBindings(
+ f"{interface.path}: the attribute {attribute.attribute.name} of the namespace {interface.name} is not "
+ "read only, which the Rust bindings do not handle yet"
+ )
+ function_documentation = "".join(
+ f"/// - `{signature}`\n" for signature in namespace_function_signatures(context, interface, members)
+ )
+ out.write(
+ f"""
+/// The bindings of the namespace {interface.name}, which call these functions of its implementation, {implementation}:
+{function_documentation}pub(crate) mod {rust_module_name(interface)} {{
+{RUST_BINDINGS_IMPORTS}
+ use {implementation} as Implementation;
+"""
+ )
+ for attribute in members.attributes:
+ what = f"{interface.name}.{attribute.attribute.name}"
+ conversion = rust_to_js_value(attribute.attribute.type, "result", "&cx", context, what)
+ out.write(
+ f"""
+ fn {attribute.getter_function}(vm: &Vm) -> ThrowCompletionOr<Value> {{
+ let mut cx = CallContext::new(vm, vm.current_realm().expect("a native function runs in a realm"));
+ let result = Implementation::{attribute.getter_method}(&mut cx)
+ .map_err(|exception| exception.throw(&cx))?;
+ {conversion}
+ }}
+"""
+ )
+ for operation_set in members.operation_sets:
+ write_rust_operation_set(out, context, interface, operation_set, write_rust_static_operation)
+
+ out.write(
+ f"""
+ /// The steps of {interface.namespace_class}::initialize() of LibWeb's C++ bindings.
+ ///
+ /// # Safety
+ ///
+ /// The pointers must be the VM, a realm and the namespace object of the realm.
+ #[unsafe(no_mangle)]
+ pub unsafe extern "C" fn {rust_entry_point_name(interface, "initialize_namespace")}(
+ vm: *mut c_void,
+ realm: *mut c_void,
+ object: *mut c_void,
+ ) {{
+ // SAFETY: The caller passes live pointers.
+ let (vm, realm, object) = unsafe {{ entry_point_arguments(vm, realm, object) }};
+ // The class string of a namespace object is the namespace's identifier.
+ define_to_string_tag(vm, object, "{interface.name}");
+"""
+ )
+ for attribute in members.attributes:
+ out.write(
+ f' define_attribute(vm, realm, object, "{attribute.attribute.name}", '
+ f"raw_native!({attribute.getter_function}), None);\n"
+ )
+ for operation_set in members.operation_sets:
+ definition = (
+ f'define_operation(vm, realm, object, "{operation_set.name}", raw_native!({operation_set.function}), '
+ f"{operation_set.length});"
+ )
+ out.write(window_only_definition(definition, operation_set.is_window_only))
+ if "WithInitializer" in interface.extended_attributes:
+ out.write(" Implementation::initialize(&mut CallContext::new(vm, realm), object);\n")
+ out.write(" }\n}\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."""
@@ -1135,28 +1315,41 @@ def write_rust_static_operation(
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)
+ steps = StringIO()
+ steps.write(' let realm = vm.current_realm().expect("a native function runs in a realm");\n')
+ write_argument_count_check(steps, name, overload.length)
+ write_parameter_conversions(steps, 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})
+ steps.write(" let mut cx = CallContext::new(vm, realm);\n")
+ call = f"Implementation::{overload.method}(&mut cx{arguments})"
+ if operation.return_type.name == "undefined" and not operation.return_type.nullable:
+ steps.write(
+ f""" {call}
+ .map_err(|exception| exception.throw(&cx))?;
+ Ok(Value::UNDEFINED)
+"""
+ )
+ else:
+ conversion = rust_to_js_value(operation.return_type, "result", "&cx", context, what)
+ steps.write(
+ f""" let result = {call}
.map_err(|exception| exception.throw(&cx))?;
{conversion}
- }}
"""
- )
+ )
+ out.write(f"\n fn {function}(vm: &Vm) -> ThrowCompletionOr<Value> {{\n")
+ if is_promise_type(operation.return_type) and not operation.return_type.nullable:
+ out.write(
+ f""" // An exception that the steps of an operation with a promise type throw rejects a new promise,
+ // https://webidl.spec.whatwg.org/#dfn-create-operation-function
+ let steps = || -> ThrowCompletionOr<Value> {{
+{textwrap.indent(steps.getvalue(), " ")} }};
+ steps().or_else(|throw| Ok(rejected_promise(vm, throw)))
+"""
+ )
+ else:
+ out.write(steps.getvalue())
+ out.write(" }\n")
def write_rust_structured_data_entry_points(out: TextIO, interface: Interface) -> None:
@@ -1373,12 +1566,17 @@ def write_rust_attribute_setter(
}};"""
else:
conversion = f"let idl_value = {conversion}?;"
+ receiver = "(implementation, mut cx)"
+ caller_realm_context = ""
+ if "NeedsCallerRealm" in attribute.attribute.extended_attributes:
+ receiver = "(implementation, _)"
+ caller_realm_context = CALLER_REALM_CONTEXT
out.write(
f"""
fn {attribute.setter_function}(vm: &Vm) -> ThrowCompletionOr<Value> {{
let value = vm.argument(0);
- let (implementation, mut cx) = this_implementation(vm)?;
- let type_error_realm_scope = vm.type_error_realm_scope(cx.realm());
+ let {receiver} = this_implementation(vm)?;
+{caller_realm_context} let type_error_realm_scope = vm.type_error_realm_scope(cx.realm());
{conversion}
drop(type_error_realm_scope);
Implementation::{attribute.setter_method}(&implementation, &mut cx, idl_value)
@@ -1398,11 +1596,7 @@ def write_rust_operation(
what = f"{interface.name}.{name}()"
steps = StringIO()
if "NeedsCallerRealm" in operation.extended_attributes:
- steps.write(
- """ let (implementation, _) = this_implementation(vm)?;
- let mut cx = CallContext::new(vm, vm.current_realm().expect("a native function runs in a realm"));
-"""
- )
+ steps.write(f" let (implementation, _) = this_implementation(vm)?;\n{CALLER_REALM_CONTEXT}")
else:
steps.write(" let (implementation, mut cx) = this_implementation(vm)?;\n")
write_argument_count_check(steps, name, overload.length)
@@ -1575,7 +1769,10 @@ def write_rust_bindings(
interface = module.interface
if interface is None or not is_implemented_in_rust(interface):
continue
- write_rust_interface(out, context, module, interface, values[interface.name])
+ if interface.is_namespace:
+ write_rust_namespace(out, context, interface)
+ else:
+ write_rust_interface(out, context, module, interface, values[interface.name])
write_rust_wrap_for_cpp(out, context, usage)
diff --git a/Meta/Generators/libweb_bindings/rust_members.py b/Meta/Generators/libweb_bindings/rust_members.py
index f9fc9d14a43..b410beeb341 100644
--- a/Meta/Generators/libweb_bindings/rust_members.py
+++ b/Meta/Generators/libweb_bindings/rust_members.py
@@ -32,8 +32,16 @@ from Utils.webidl_parser import OperationParameter
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"}
-# NB: The context of an operation that is [NeedsCallerRealm] has the current realm, not the realm of the object.
+# NB: The context of an attribute or an operation that is [NeedsCallerRealm] has the current realm, not the realm of
+# the object.
+SUPPORTED_ATTRIBUTE_EXTENDED_ATTRIBUTES = {
+ "CachedAccessor",
+ "FIXME",
+ "ImplementedAs",
+ "NeedsCallerRealm",
+ "NewObject",
+ "SameObject",
+}
SUPPORTED_OPERATION_EXTENDED_ATTRIBUTES = {
"Default",
"Exposed",
@@ -404,8 +412,8 @@ def rust_members(interface: Interface) -> RustMembers:
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.return_type_is_promise() for operation in operations}) > 1:
+ fail(f"some overloads of its operation {name} return a promise type and others do not")
if len({operation.extended_attributes.get("Exposed") for operation in operations}) > 1:
fail(f"the overloads of its operation {name} are exposed differently")
overloads = [
diff --git a/Meta/Generators/libweb_bindings/rust_to_idl_value.py b/Meta/Generators/libweb_bindings/rust_to_idl_value.py
index 6f51ff450fa..e6284eead54 100644
--- a/Meta/Generators/libweb_bindings/rust_to_idl_value.py
+++ b/Meta/Generators/libweb_bindings/rust_to_idl_value.py
@@ -104,6 +104,8 @@ def rust_to_idl_value(
return f"sequence_from_js(vm, {value}, Vec::new(), |value| {element})"
if isinstance(idl_type, IDLParameterizedType) and idl_type.name == "record":
return rust_record_to_idl_value(idl_type, value, identifier, context, what)
+ if isinstance(idl_type, IDLParameterizedType) and idl_type.name == "Promise":
+ return f"to_promise(vm, {value})"
if isinstance(idl_type, IDLParameterizedType):
raise UnsupportedByRustBindings(
f"{what} has the type {idl_type}, which the Rust bindings do not convert to yet"
@@ -300,6 +302,10 @@ def rust_default_value(
numeric_literal = rust_numeric_literal(default_value, name)
if numeric_literal is not None:
return numeric_literal
+ if member.type.nullable and default_value == "null":
+ return "None"
+ if isinstance(member.type, IDLParameterizedType) and name == "sequence" and default_value == "[]":
+ return "Vec::new()"
dictionary = resolved_dictionary(member.type, context)
if dictionary is not None and default_value == "{}":
# NB: The C++ bindings do not run the conversion for a missing argument either, so the members of the default
diff --git a/Meta/Generators/libweb_bindings/rust_types.py b/Meta/Generators/libweb_bindings/rust_types.py
index 7e2c62f8f4b..6be83350aea 100644
--- a/Meta/Generators/libweb_bindings/rust_types.py
+++ b/Meta/Generators/libweb_bindings/rust_types.py
@@ -382,7 +382,7 @@ def rust_type(idl_type: IDLType, context: GenerationContext, what: str, is_resul
if is_result and holds_cells(element_type, context):
return f"MarkedVec<'_, {element}>"
return f"Vec<{element}>"
- if name == "Promise" and is_result:
+ if name == "Promise":
return "WebIdlPromise"
if name == "record":
key_type, value_type = idl_type.parameters
@@ -398,6 +398,8 @@ def rust_type(idl_type: IDLType, context: GenerationContext, what: str, is_resul
return "Gc<Object>"
if name in TYPED_ARRAY_NAMES:
return "Gc<TypedArrayBase>"
+ if name == "ArrayBuffer" and is_result:
+ return "Gc<ArrayBuffer>"
callback_function = context.callback_function(idl_type)
if callback_function is not None:
# NB: A callback function value that the implementation receives keeps its callback context, and one that it