Skip to content

Truly independent web browser

LibWeb: Support promises, callbacks and async iterables in Rust bindings

Shannon Booth36d9105e98c4
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/async_iterable.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/async_iterable.rs
new file mode 100644
index 00000000000..0c3eda80524
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/async_iterable.rs
@@ -0,0 +1,460 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The asynchronous iterators of the interfaces implemented in Rust, https://webidl.spec.whatwg.org/#idl-async-iterable,
+//! for a value asynchronously iterable declaration.
+
+use core::cell::Cell;
+use core::ptr::NonNull;
+
+use libjs_rust::api::{
+ Attribute, EmbedderCell, EmbedderClass, EmbedderValue, ErrorKind, ErrorType, Gc, HostObject, JSHostClass, Must,
+ NativeFunction, Object, Promise, PropertyAttributes, PropertyKey, RawNativeFunctionPointer, Realm, Throw,
+ ThrowCompletionOr, Trace, Value, Vm, call, create_iterator_result_object, host_data_of, is_host_instance_of,
+};
+
+use crate::bindings::CallContext;
+use crate::bindings::interface::{Interface, define_operation};
+use crate::bindings::promise::{NativeSteps, WebIdlPromise, create_promise};
+use crate::bindings::services::web_bindings_ensure_web_iterator_prototype;
+
+/// What the steps that get the next iteration result fulfill their promise with at the end of the iteration,
+/// https://webidl.spec.whatwg.org/#end-of-iteration
+pub(crate) const END_OF_ITERATION: Value = Value::EMPTY;
+
+/// What the implementation of an interface with a value asynchronously iterable declaration implements, for a default
+/// asynchronous iterator object of the interface whose state its asynchronous iterator initialization steps created.
+pub(crate) trait AsyncIterable: Interface {
+ type IteratorState: Trace + 'static;
+
+ /// The steps to get the next iteration result, https://webidl.spec.whatwg.org/#dfn-get-the-next-iteration-result,
+ /// which return a promise fulfilled with the next value or END_OF_ITERATION.
+ fn get_the_next_iteration_result(cx: &CallContext, state: &Self::IteratorState) -> WebIdlPromise;
+
+ /// The asynchronous iterator return algorithm, https://webidl.spec.whatwg.org/#asynchronous-iterator-return, of an
+ /// interface whose IDL marks it [DefinesAsyncIteratorReturn].
+ fn asynchronous_iterator_return(cx: &CallContext, state: &Self::IteratorState, value: Value) -> WebIdlPromise;
+}
+
+/// What the generated bindings of an interface with an asynchronously iterable declaration define: the classes of its
+/// default asynchronous iterator objects.
+pub(crate) trait DefaultAsyncIteratorClasses: AsyncIterable {
+ /// The class of the cells of the default asynchronous iterator objects of the interface.
+ const ASYNC_ITERATOR_CELL_CLASS: &'static EmbedderClass<DefaultAsyncIterator<Self>>;
+
+ /// The class of the default asynchronous iterator objects of the interface.
+ fn async_iterator_class() -> &'static JSHostClass;
+}
+
+/// A default asynchronous iterator object, https://webidl.spec.whatwg.org/#default-asynchronous-iterator-object,
+/// which is the host data of a host object of the asynchronous iterator class of its interface.
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct DefaultAsyncIterator<T: AsyncIterable> {
+ realm: Gc<Realm>,
+ state: T::IteratorState,
+ ongoing_promise: Cell<Option<Gc<Promise>>>,
+ is_finished: Cell<bool>,
+}
+
+impl<T: DefaultAsyncIteratorClasses> EmbedderValue for DefaultAsyncIterator<T> {
+ const CLASS: &'static EmbedderClass<Self> = T::ASYNC_ITERATOR_CELL_CLASS;
+}
+
+type IteratorCell<T> = Gc<EmbedderCell<DefaultAsyncIterator<T>>>;
+
+/// Defines the "values" and %Symbol.asyncIterator% methods of an interface with a value asynchronously iterable
+/// declaration on its interface prototype object, https://webidl.spec.whatwg.org/#define-the-asynchronous-iteration-methods
+pub(crate) fn define_async_iterator_properties(
+ vm: &Vm,
+ realm: Gc<Realm>,
+ prototype: Gc<Object>,
+ values: RawNativeFunctionPointer,
+ length: i32,
+) {
+ define_operation(vm, realm, prototype, "values", values, length);
+ prototype.define_direct_property(
+ vm,
+ &PropertyKey::from(vm.well_known_symbols().async_iterator),
+ prototype.get_without_side_effects(vm, &vm.names.values),
+ PropertyAttributes::new(Attribute::CONFIGURABLE | Attribute::WRITABLE),
+ );
+}
+
+/// A newly created default asynchronous iterator object for the interface in the realm of the call context, with the
+/// state that the asynchronous iterator initialization steps of the interface created.
+pub(crate) fn create_default_async_iterator<T: DefaultAsyncIteratorClasses>(
+ cx: &CallContext,
+ state: T::IteratorState,
+) -> Value {
+ let vm = cx.vm();
+ let realm = cx.realm();
+ let iterator = T::ASYNC_ITERATOR_CELL_CLASS.allocate(
+ vm,
+ DefaultAsyncIterator {
+ realm,
+ state,
+ ongoing_promise: Cell::new(None),
+ is_finished: Cell::new(false),
+ },
+ );
+ // SAFETY: The realm is live, and the interface is asynchronously iterable.
+ let prototype = unsafe { web_bindings_ensure_web_iterator_prototype(realm.as_ptr().cast(), T::INTERFACE_NAME) };
+ let prototype = NonNull::new(prototype.cast::<Object>()).expect("LibWeb returns the iterator prototype object");
+ // SAFETY: LibWeb returns a live object, the iterator class has no hooks, and the host data is a live cell.
+ let object = unsafe {
+ HostObject::create(
+ vm,
+ realm,
+ T::async_iterator_class(),
+ Some(Gc::from_non_null(prototype)),
+ None,
+ Some(iterator.as_non_null().cast()),
+ )
+ };
+ Value::from_object(object.upcast::<Object>())
+}
+
+/// Validates the this value of the "next" and "return" methods of the asynchronous iterator prototype object, steps
+/// 3 to 7: the default asynchronous iterator object, or the promise of thisValidationPromiseCapability, which it
+/// rejected.
+fn validate_this<T: DefaultAsyncIteratorClasses>(
+ vm: &Vm,
+ this_validation_promise_capability: WebIdlPromise,
+) -> Result<IteratorCell<T>, Value> {
+ let reject = |error: Value| {
+ call(
+ vm,
+ Value::from_object(this_validation_promise_capability.reject().upcast::<Object>()),
+ Value::UNDEFINED,
+ &[error],
+ )
+ .must();
+ Value::from_object(this_validation_promise_capability.promise())
+ };
+
+ // 3. Let thisValue be the this value.
+ let this_value = vm.this_value();
+
+ // 4. Let object be Completion(ToObject(thisValue)).
+ // 5. IfAbruptRejectPromise(object, thisValidationPromiseCapability).
+ let object = this_value.to_object(vm).map_err(|throw| reject(throw.value()))?;
+
+ // 6. If object is a platform object, then perform a security check, passing:
+ // * the platform object object,
+ // * the identifier "next", and
+ // * the type "method".
+ // NB: A default asynchronous iterator object is not a platform object.
+
+ // 7. If object is not a default asynchronous iterator object for interface, then:
+ let Some(iterator) = default_async_iterator_of::<T>(object) else {
+ // 1. Let error be a new TypeError.
+ let name = format!("{}AsyncIterator", T::NAME);
+ let error = vm
+ .throw_completion::<()>(ErrorKind::TypeError, ErrorType::NotAnObjectOfType, &[&name])
+ .expect_err("throwing a completion throws");
+
+ // 2. Perform ! Call(thisValidationPromiseCapability.[[Reject]], undefined, « error »).
+ // 3. Return thisValidationPromiseCapability.[[Promise]].
+ return Err(reject(error.value()));
+ };
+ Ok(iterator)
+}
+
+fn default_async_iterator_of<T: DefaultAsyncIteratorClasses>(object: Gc<Object>) -> Option<IteratorCell<T>> {
+ if !is_host_instance_of(&object, T::async_iterator_class()) {
+ return None;
+ }
+ let host_data = host_data_of(&object).expect("a default asynchronous iterator object holds its cell");
+ // SAFETY: The object is a host object of the asynchronous iterator class, whose host data is the cell of a default
+ // asynchronous iterator.
+ unsafe { T::ASYNC_ITERATOR_CELL_CLASS.downcast(host_data) }
+}
+
+/// The realm that the "next" and "return" methods create their promise in, as LibWeb's C++ bindings do: the realm of
+/// the this value, or the current realm for a this value that is not an object.
+fn this_value_realm(vm: &Vm) -> Gc<Realm> {
+ let this_value = vm.this_value();
+ if this_value.is_object() {
+ return this_value.as_object().shape().realm();
+ }
+ vm.current_realm().expect("a native function runs in a realm")
+}
+
+/// The steps of a built-in function that the iterator creates, given its captures.
+type BuiltinSteps<C> = fn(&Vm, C) -> ThrowCompletionOr<Value>;
+
+fn native_function<C: Trace + Copy + 'static>(
+ vm: &Vm,
+ realm: Gc<Realm>,
+ captures: C,
+ behaviour: BuiltinSteps<C>,
+) -> Value {
+ let function = NativeFunction::create(
+ vm,
+ NativeSteps {
+ captures,
+ steps: behaviour,
+ },
+ |vm: &Vm, function: &NativeSteps<C, BuiltinSteps<C>>| (function.steps)(vm, function.captures),
+ 0,
+ &PropertyKey::from_utf8(""),
+ Some(realm),
+ None,
+ None,
+ );
+ Value::from_object(function.upcast::<Object>())
+}
+
+/// Runs the steps after the ongoing promise of the iterator settles, or now if it has none, and makes their promise
+/// the ongoing promise, steps 9 to 11 of the "next" and "return" methods.
+fn chain_onto_ongoing_promise<T: DefaultAsyncIteratorClasses, C: Trace + Copy + 'static>(
+ vm: &Vm,
+ iterator: IteratorCell<T>,
+ captures: C,
+ steps: BuiltinSteps<C>,
+) {
+ let realm = iterator.realm;
+
+ // 9. Let ongoingPromise be object’s ongoing promise.
+ // 10. If ongoingPromise is not null, then:
+ if let Some(ongoing_promise) = iterator.ongoing_promise.get() {
+ // 1. Let afterOngoingPromiseCapability be ! NewPromiseCapability(%Promise%).
+ let after_ongoing_promise_capability = create_promise(vm, realm);
+
+ // 2. Let onSettled be CreateBuiltinFunction(steps, « »).
+ let on_settled = native_function(vm, realm, captures, steps);
+
+ // 3. Perform PerformPromiseThen(ongoingPromise, onSettled, onSettled, afterOngoingPromiseCapability).
+ ongoing_promise.perform_then(vm, on_settled, on_settled, Some(after_ongoing_promise_capability));
+
+ // 4. Set object’s ongoing promise to afterOngoingPromiseCapability.[[Promise]].
+ iterator
+ .ongoing_promise
+ .set(Some(promise_of(after_ongoing_promise_capability.promise())));
+ }
+ // 11. Otherwise:
+ else {
+ // 1. Set object’s ongoing promise to the result of running steps.
+ let result = steps(vm, captures).must();
+ iterator.ongoing_promise.set(Some(promise_of(result.as_object())));
+ }
+}
+
+fn promise_of(object: Gc<Object>) -> Gc<Promise> {
+ object.downcast::<Promise>().expect("the steps return a promise")
+}
+
+/// The "next" method of the asynchronous iterator prototype object of the interface,
+/// https://webidl.spec.whatwg.org/#es-asynchronous-iterator-prototype-object
+pub(crate) fn async_iterator_next<T: DefaultAsyncIteratorClasses>(vm: &Vm) -> ThrowCompletionOr<Value> {
+ // 1. Let interface be the interface for which the asynchronous iterator prototype object exists.
+ // 2. Let thisValidationPromiseCapability be ! NewPromiseCapability(%Promise%).
+ let this_validation_promise_capability = create_promise(vm, this_value_realm(vm));
+
+ // 3. Let thisValue be the this value.
+ // 4. Let object be Completion(ToObject(thisValue)).
+ // 5. IfAbruptRejectPromise(object, thisValidationPromiseCapability).
+ // 6. If object is a platform object, then perform a security check, passing:
+ // 7. If object is not a default asynchronous iterator object for interface, then:
+ let iterator = match validate_this::<T>(vm, this_validation_promise_capability) {
+ Ok(iterator) => iterator,
+ Err(promise) => return Ok(promise),
+ };
+
+ // 8. Let nextSteps be the following steps:
+ fn next_steps<T: DefaultAsyncIteratorClasses>(vm: &Vm, iterator: IteratorCell<T>) -> ThrowCompletionOr<Value> {
+ let realm = iterator.realm;
+
+ // 1. Let nextPromiseCapability be ! NewPromiseCapability(%Promise%).
+ let next_promise_capability = create_promise(vm, realm);
+
+ // 2. If object’s is finished is true, then:
+ if iterator.is_finished.get() {
+ // 1. Let result be CreateIteratorResultObject(undefined, true).
+ let result = create_iterator_result_object(vm, realm, Value::UNDEFINED, true);
+
+ // 2. Perform ! Call(nextPromiseCapability.[[Resolve]], undefined, « result »).
+ call(
+ vm,
+ Value::from_object(next_promise_capability.resolve().upcast::<Object>()),
+ Value::UNDEFINED,
+ &[Value::from_object(result)],
+ )
+ .must();
+
+ // 3. Return nextPromiseCapability.[[Promise]].
+ return Ok(Value::from_object(next_promise_capability.promise()));
+ }
+
+ // 3. Let kind be object’s kind.
+ // 4. Let nextPromise be the result of getting the next iteration result with object’s target and object.
+ let next_promise = T::get_the_next_iteration_result(&CallContext::new(vm, realm), &iterator.state);
+
+ // 5. Let fulfillSteps be the following steps, given next:
+ fn fulfill_steps<T: DefaultAsyncIteratorClasses>(
+ vm: &Vm,
+ iterator: IteratorCell<T>,
+ ) -> ThrowCompletionOr<Value> {
+ let next = vm.argument(0);
+
+ // 1. Set object’s ongoing promise to null.
+ iterator.ongoing_promise.set(None);
+
+ // 2. If next is end of iteration, then:
+ if next == END_OF_ITERATION {
+ // 1. Set object’s is finished to true.
+ iterator.is_finished.set(true);
+
+ // 2. Return CreateIteratorResultObject(undefined, true).
+ return Ok(Value::from_object(create_iterator_result_object(
+ vm,
+ iterator.realm,
+ Value::UNDEFINED,
+ true,
+ )));
+ }
+
+ // 3. Otherwise, if interface has a pair asynchronously iterable declaration:
+ // NB: The bindings only handle a value asynchronously iterable declaration.
+
+ // 4. Otherwise:
+ // 1. Assert: interface has a value asynchronously iterable declaration.
+ // 2. Assert: next is a value of the type that appears in the declaration.
+ // 3. Let value be next, converted to a JavaScript value.
+ // 4. Return CreateIteratorResultObject(value, false).
+ Ok(Value::from_object(create_iterator_result_object(
+ vm,
+ iterator.realm,
+ next,
+ false,
+ )))
+ }
+
+ // 6. Let onFulfilled be CreateBuiltinFunction(fulfillSteps, « »).
+ let on_fulfilled = native_function(vm, realm, iterator, fulfill_steps::<T>);
+
+ // 7. Let rejectSteps be the following steps, given reason:
+ fn reject_steps<T: DefaultAsyncIteratorClasses>(
+ vm: &Vm,
+ iterator: IteratorCell<T>,
+ ) -> ThrowCompletionOr<Value> {
+ // 1. Set object’s ongoing promise to null.
+ iterator.ongoing_promise.set(None);
+
+ // 2. Set object’s is finished to true.
+ iterator.is_finished.set(true);
+
+ // 3. Throw reason.
+ Err(Throw::new(vm.argument(0)))
+ }
+
+ // 8. Let onRejected be CreateBuiltinFunction(rejectSteps, « »).
+ let on_rejected = native_function(vm, realm, iterator, reject_steps::<T>);
+
+ // 9. Perform PerformPromiseThen(nextPromise, onFulfilled, onRejected, nextPromiseCapability).
+ promise_of(next_promise.promise()).perform_then(vm, on_fulfilled, on_rejected, Some(next_promise_capability));
+
+ // 10. Return nextPromiseCapability.[[Promise]].
+ Ok(Value::from_object(next_promise_capability.promise()))
+ }
+
+ // 9. Let ongoingPromise be object’s ongoing promise.
+ // 10. If ongoingPromise is not null, then:
+ // 11. Otherwise:
+ chain_onto_ongoing_promise(vm, iterator, iterator, next_steps::<T>);
+
+ // 12. Return object’s ongoing promise.
+ let ongoing_promise = iterator
+ .ongoing_promise
+ .get()
+ .expect("the iterator has an ongoing promise");
+ Ok(Value::from_object(ongoing_promise.upcast::<Object>()))
+}
+
+/// The "return" method of the asynchronous iterator prototype object of an interface whose IDL marks it
+/// [DefinesAsyncIteratorReturn], https://webidl.spec.whatwg.org/#es-asynchronous-iterator-prototype-object
+pub(crate) fn async_iterator_return<T: DefaultAsyncIteratorClasses>(vm: &Vm) -> ThrowCompletionOr<Value> {
+ let value = vm.argument(0);
+
+ // 1. Let interface be the interface for which the asynchronous iterator prototype object exists.
+ // 2. Let returnPromiseCapability be ! NewPromiseCapability(%Promise%).
+ let return_promise_capability = create_promise(vm, this_value_realm(vm));
+
+ // 3. Let thisValue be the this value.
+ // 4. Let object be Completion(ToObject(thisValue)).
+ // 5. IfAbruptRejectPromise(object, returnPromiseCapability).
+ // 6. If object is a platform object, then perform a security check, passing:
+ // 7. If object is not a default asynchronous iterator object for interface, then:
+ let iterator = match validate_this::<T>(vm, return_promise_capability) {
+ Ok(iterator) => iterator,
+ Err(promise) => return Ok(promise),
+ };
+ let realm = iterator.realm;
+
+ // 8. Let returnSteps be the following steps:
+ fn return_steps<T: DefaultAsyncIteratorClasses>(
+ vm: &Vm,
+ (iterator, value): (IteratorCell<T>, Value),
+ ) -> ThrowCompletionOr<Value> {
+ let realm = iterator.realm;
+
+ // 1. Let returnPromiseCapability be ! NewPromiseCapability(%Promise%).
+ let return_promise_capability = create_promise(vm, realm);
+
+ // 2. If object’s is finished is true, then:
+ if iterator.is_finished.get() {
+ // 1. Let result be CreateIteratorResultObject(value, true).
+ let result = create_iterator_result_object(vm, realm, value, true);
+
+ // 2. Perform ! Call(returnPromiseCapability.[[Resolve]], undefined, « result »).
+ call(
+ vm,
+ Value::from_object(return_promise_capability.resolve().upcast::<Object>()),
+ Value::UNDEFINED,
+ &[Value::from_object(result)],
+ )
+ .must();
+
+ // 3. Return returnPromiseCapability.[[Promise]].
+ return Ok(Value::from_object(return_promise_capability.promise()));
+ }
+
+ // 3. Set object’s is finished to true.
+ iterator.is_finished.set(true);
+
+ // 4. Return the result of running the asynchronous iterator return algorithm for interface, given object’s
+ // target, object, and value.
+ let promise = T::asynchronous_iterator_return(&CallContext::new(vm, realm), &iterator.state, value);
+ Ok(Value::from_object(promise.promise()))
+ }
+
+ // 9. Let ongoingPromise be object’s ongoing promise.
+ // 10. If ongoingPromise is not null, then:
+ // 11. Otherwise:
+ chain_onto_ongoing_promise(vm, iterator, (iterator, value), return_steps::<T>);
+
+ // 12. Let fulfillSteps be the following steps:
+ fn fulfill_steps(vm: &Vm, (realm, value): (Gc<Realm>, Value)) -> ThrowCompletionOr<Value> {
+ // 1. Return CreateIteratorResultObject(value, true).
+ Ok(Value::from_object(create_iterator_result_object(
+ vm, realm, value, true,
+ )))
+ }
+
+ // 13. Let onFulfilled be CreateBuiltinFunction(fulfillSteps, « »).
+ let on_fulfilled = native_function(vm, realm, (realm, value), fulfill_steps);
+
+ // 14. Perform PerformPromiseThen(object’s ongoing promise, onFulfilled, undefined, returnPromiseCapability).
+ let ongoing_promise = iterator
+ .ongoing_promise
+ .get()
+ .expect("the iterator has an ongoing promise");
+ ongoing_promise.perform_then(vm, on_fulfilled, Value::UNDEFINED, Some(return_promise_capability));
+
+ // 15. Return returnPromiseCapability.[[Promise]].
+ Ok(Value::from_object(return_promise_capability.promise()))
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/callback.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/callback.rs
new file mode 100644
index 00000000000..804f46faeea
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/callback.rs
@@ -0,0 +1,137 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Callback function values, https://webidl.spec.whatwg.org/#idl-callback-function, which LibWeb's C++ code
+//! represents as a WebIDL::CallbackType: the function object and its callback context.
+
+use core::ffi::c_void;
+use core::ptr::NonNull;
+
+use libjs_rust::api::{
+ ErrorKind, ErrorType, ForeignCellSlot, RawNativeFunctionResult, ThrowCompletionOr, Trace, Value, Vm,
+};
+
+use crate::bindings::promise::{WebIdlPromise, promise_from_abi};
+
+unsafe extern "C" {
+ /// A new WebIDL::CallbackType of the callable object, whose callback context is the incumbent settings object.
+ fn web_bindings_create_callback_function(callable: *mut c_void, returns_promise: bool) -> *mut c_void;
+
+ /// WebIDL::invoke_callback() of the WebIDL::CallbackType with the this value, if `has_this_value`, and the
+ /// arguments.
+ fn web_bindings_invoke_callback_function(
+ callback: *mut c_void,
+ has_this_value: bool,
+ this_value: u64,
+ arguments: ak::Span<'_, Value>,
+ ) -> RawNativeFunctionResult;
+
+ /// WebIDL::invoke_promise_callback() of the WebIDL::CallbackType, whose return type is a promise type, with the this
+ /// value, if `has_this_value`, and the arguments.
+ fn web_bindings_invoke_promise_callback_function(
+ callback: *mut c_void,
+ has_this_value: bool,
+ this_value: u64,
+ arguments: ak::Span<'_, Value>,
+ ) -> *mut c_void;
+}
+
+/// A callback function value, https://webidl.spec.whatwg.org/#idl-callback-function
+#[derive(Clone, Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct CallbackFunction(CallbackType);
+
+/// A callback function value whose return type is a promise type.
+#[derive(Clone, Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct PromiseCallbackFunction(CallbackType);
+
+/// The WebIDL::CallbackType of a callback function value.
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+struct CallbackType(ForeignCellSlot);
+
+impl Clone for CallbackType {
+ fn clone(&self) -> Self {
+ // SAFETY: The slot keeps the callback alive.
+ unsafe { Self::from_raw(self.0.as_ptr()) }
+ }
+}
+
+impl CallbackType {
+ /// # Safety
+ ///
+ /// `callback` must be a live WebIDL::CallbackType.
+ unsafe fn from_raw(callback: *mut c_void) -> Self {
+ let slot = ForeignCellSlot::empty();
+ // SAFETY: The caller passes a live WebIDL::CallbackType, a cell of the heap.
+ unsafe { slot.set(Some(NonNull::new(callback).expect("LibWeb passes a callback"))) };
+ Self(slot)
+ }
+
+ // https://webidl.spec.whatwg.org/#js-callback-function
+ fn from_js(vm: &Vm, value: Value, returns_promise: bool) -> ThrowCompletionOr<Self> {
+ // 1. If the result of calling IsCallable(V) is false and the conversion to an IDL value is not being performed
+ // due to V being assigned to an attribute whose type is a nullable callback function that is annotated with
+ // [LegacyTreatNonObjectAsNull], then throw a TypeError.
+ if !value.is_function() {
+ return vm.throw_completion(ErrorKind::TypeError, ErrorType::NotAFunction, &[&value]);
+ }
+
+ // 2. Return the IDL callback function type value that represents a reference to the same object that V
+ // represents, with the incumbent realm as the callback context.
+ // SAFETY: The value is a live object.
+ Ok(unsafe {
+ Self::from_raw(web_bindings_create_callback_function(
+ value.as_object().as_ptr().cast(),
+ returns_promise,
+ ))
+ })
+ }
+}
+
+impl CallbackFunction {
+ /// The callback function value of a JS value, https://webidl.spec.whatwg.org/#js-callback-function
+ pub(crate) fn from_js(vm: &Vm, value: Value) -> ThrowCompletionOr<Self> {
+ CallbackType::from_js(vm, value, false).map(Self)
+ }
+
+ /// Invokes the callback function with the this value and the arguments, https://webidl.spec.whatwg.org/#invoke-a-callback-function
+ pub(crate) fn invoke(&self, this_value: Option<Value>, arguments: &[Value]) -> ThrowCompletionOr<Value> {
+ // SAFETY: The slot keeps the callback alive, and the values are live for the call.
+ unsafe {
+ web_bindings_invoke_callback_function(
+ self.0.0.as_ptr(),
+ this_value.is_some(),
+ this_value.unwrap_or(Value::UNDEFINED).0,
+ ak::Span::new(arguments),
+ )
+ }
+ .into_completion()
+ }
+}
+
+impl PromiseCallbackFunction {
+ /// The callback function value of a JS value, https://webidl.spec.whatwg.org/#js-callback-function
+ pub(crate) fn from_js(vm: &Vm, value: Value) -> ThrowCompletionOr<Self> {
+ CallbackType::from_js(vm, value, true).map(Self)
+ }
+
+ /// Invokes the callback function with the this value and the arguments, https://webidl.spec.whatwg.org/#invoke-a-callback-function:
+ /// the promise that it returns, or one rejected with what it throws.
+ pub(crate) fn invoke(&self, this_value: Option<Value>, arguments: &[Value]) -> WebIdlPromise {
+ // SAFETY: The slot keeps the callback alive, and the values are live for the call.
+ // LibWeb returns a live promise.
+ unsafe {
+ promise_from_abi(web_bindings_invoke_promise_callback_function(
+ self.0.0.as_ptr(),
+ this_value.is_some(),
+ this_value.unwrap_or(Value::UNDEFINED).0,
+ ak::Span::new(arguments),
+ ))
+ }
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs
index a08993bb203..a7e3b864bfe 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs
@@ -23,6 +23,7 @@ use libjs_rust::api::{
use crate::ak_format::ak_formatted;
use crate::bindings::interface::{Interface, Ref, create_dictionary_object, wrap};
+use crate::bindings::promise::WebIdlPromise;
use crate::bindings::services::web_bindings_object_implements_interface;
use crate::bindings::{CallContext, Exception, WebIdlResult};
@@ -170,6 +171,17 @@ pub(crate) fn enumeration_value_to_js(cx: &CallContext, enumeration_value: &str)
))
}
+/// An object converted from a JS value, https://webidl.spec.whatwg.org/#js-object
+pub(crate) fn to_object(vm: &Vm, value: Value) -> ThrowCompletionOr<Gc<Object>> {
+ // 1. If V is not an Object, then throw a TypeError.
+ if !value.is_object() {
+ return vm.throw_completion(ErrorKind::TypeError, ErrorType::NotAnObject, &[&value]);
+ }
+
+ // 2. Return the IDL object value that is a reference to the same object as V.
+ Ok(value.as_object())
+}
+
/// A JS value converted to a boolean, https://webidl.spec.whatwg.org/#js-boolean
#[expect(
clippy::unnecessary_wraps,
@@ -974,6 +986,13 @@ impl ToJs for Gc<Object> {
}
}
+/// https://webidl.spec.whatwg.org/#js-promise
+impl ToJs for WebIdlPromise {
+ fn to_js(self, _: &CallContext) -> ThrowCompletionOr<Value> {
+ Ok(Value::from_object(self.promise()))
+ }
+}
+
/// https://webidl.spec.whatwg.org/#js-long
impl ToJs for i32 {
fn to_js(self, _: &CallContext) -> ThrowCompletionOr<Value> {
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/interface.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/interface.rs
index 8b7a08754c6..70fa6e557a5 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/interface.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/interface.rs
@@ -344,6 +344,16 @@ pub(crate) fn realm_is_window(realm: Gc<Realm>) -> bool {
/// Runs the steps while an execution context of the realm is on the stack, for steps that can run script but that do not
/// run on behalf of script, as an HTML::TemporaryExecutionContext does for C++.
pub(crate) fn with_temporary_execution_context<F: FnOnce() -> R, R>(realm: Gc<Realm>, steps: F) -> R {
+ run_with_temporary_execution_context(realm, false, steps)
+}
+
+/// Runs the steps as with_temporary_execution_context() does, with the realm prepared to run callbacks as well, as an
+/// HTML::TemporaryExecutionContext with CallbacksEnabled::Yes does for C++.
+pub(crate) fn with_temporary_execution_context_and_callbacks<F: FnOnce() -> R, R>(realm: Gc<Realm>, steps: F) -> R {
+ run_with_temporary_execution_context(realm, true, steps)
+}
+
+fn run_with_temporary_execution_context<F: FnOnce() -> R, R>(realm: Gc<Realm>, callbacks_enabled: bool, steps: F) -> R {
unsafe extern "C" fn run_steps<F: FnOnce() -> R, R>(context: *mut c_void) {
// SAFETY: The context is the steps and the slot for their result, which outlive the call.
let (steps, result) = unsafe { &mut *context.cast::<(Option<F>, Option<R>)>() };
@@ -355,6 +365,7 @@ pub(crate) fn with_temporary_execution_context<F: FnOnce() -> R, R>(realm: Gc<Re
unsafe {
web_bindings_with_temporary_execution_context(
realm.as_ptr().cast(),
+ callbacks_enabled,
(&raw mut context).cast(),
run_steps::<F, R>,
);
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/mod.rs
index d12ede36115..217e2e4b9f8 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/mod.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/mod.rs
@@ -14,11 +14,18 @@
//! Values and cells live in locals while a binding runs, which the collector scans; a binding that gathers values in
//! a container keeps them in a MarkedVec.
+#[allow(
+ clippy::unnecessary_wraps,
+ reason = "the asynchronous iterator steps are built-in functions, which can throw"
+)]
+pub(crate) mod async_iterable;
+pub(crate) mod callback;
pub(crate) mod conversions;
#[cfg(web_idl_bindings)]
pub(crate) mod generated;
pub(crate) mod interface;
pub(crate) mod iterable;
+pub(crate) mod promise;
pub(crate) mod realm_data;
pub(crate) mod services;
pub(crate) mod structured_data;
@@ -72,6 +79,14 @@ impl From<Throw> for Exception {
}
impl Exception {
+ pub(crate) fn type_error(message: &str) -> Self {
+ Self::TypeError(Utf16String::from_utf8(message))
+ }
+
+ pub(crate) fn range_error(message: &str) -> Self {
+ Self::RangeError(Utf16String::from_utf8(message))
+ }
+
pub(crate) fn index_size_error(message: Utf16String) -> Self {
Self::Dom("IndexSizeError", message)
}
@@ -111,3 +126,18 @@ fn thrown(completion: ThrowCompletionOr<()>) -> Throw {
}
pub(crate) type WebIdlResult<T> = Result<T, Exception>;
+
+/// The value of a WebIDL result that cannot be an exception, as `!` asserts of an abstract operation.
+pub(crate) trait MustNotThrow<T> {
+ fn must(self) -> T;
+}
+
+impl<T> MustNotThrow<T> for WebIdlResult<T> {
+ #[track_caller]
+ fn must(self) -> T {
+ match self {
+ Ok(value) => value,
+ Err(_) => panic!("a step that cannot throw threw"),
+ }
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/promise.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/promise.rs
new file mode 100644
index 00000000000..21c609263f3
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/promise.rs
@@ -0,0 +1,468 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! 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::ffi::c_void;
+use core::ptr::NonNull;
+
+use libjs_rust::api::{
+ Array, EmbedderCell, EmbedderClass, EmbedderValue, Gc, Must, NativeFunction, Object, Promise, PromiseCapability,
+ PromiseState, PropertyKey, Realm, RejectionOperation, Trace, Value, Visitor, Vm, call, new_promise_capability,
+};
+
+use crate::bindings::interface::{with_temporary_execution_context, with_temporary_execution_context_and_callbacks};
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+
+/// A Promise<T> value, https://webidl.spec.whatwg.org/#idl-promise
+pub(crate) type WebIdlPromise = Gc<PromiseCapability>;
+
+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);
+}
+
+/// The promise that LibWeb's C++ code returns, a WebIDL::Promise.
+///
+/// # Safety
+///
+/// `promise` must be a live WebIDL::Promise.
+pub(crate) unsafe fn promise_from_abi(promise: *mut c_void) -> WebIdlPromise {
+ let promise = NonNull::new(promise.cast::<PromiseCapability>()).expect("LibWeb returns a promise");
+ // SAFETY: The caller passes a live promise capability.
+ unsafe { Gc::from_non_null(promise) }
+}
+
+/// A new promise in the realm, https://webidl.spec.whatwg.org/#a-new-promise
+pub(crate) fn create_promise(vm: &Vm, realm: Gc<Realm>) -> WebIdlPromise {
+ // 1. Let constructor be realm.[[Intrinsics]].[[%Promise%]].
+ let constructor = realm.intrinsics().promise_constructor(vm);
+
+ // 2. Return ? NewPromiseCapability(constructor).
+ // NB: When called with %Promise%, NewPromiseCapability can't throw.
+ new_promise_capability(vm, Value::from_object(constructor)).must()
+}
+
+/// A promise resolved with the value in the realm, https://webidl.spec.whatwg.org/#a-promise-resolved-with
+pub(crate) fn create_resolved_promise(vm: &Vm, realm: Gc<Realm>, value: Value) -> WebIdlPromise {
+ // 1. Let value be the result of converting x to an ECMAScript value.
+ // 2. Let constructor be realm.[[Intrinsics]].[[%Promise%]].
+ // 3. Let promiseCapability be ? NewPromiseCapability(constructor).
+ let promise = create_promise(vm, realm);
+
+ // 4. Perform ! Call(promiseCapability.[[Resolve]], undefined, « value »).
+ resolve_promise(vm, promise, value);
+
+ // 5. Return promiseCapability.
+ promise
+}
+
+/// A promise rejected with the reason in the realm, https://webidl.spec.whatwg.org/#a-promise-rejected-with
+pub(crate) fn create_rejected_promise(vm: &Vm, realm: Gc<Realm>, reason: Value) -> WebIdlPromise {
+ // 1. Let constructor be realm.[[Intrinsics]].[[%Promise%]].
+ // 2. Let promiseCapability be ? NewPromiseCapability(constructor).
+ let promise = create_promise(vm, realm);
+
+ // 3. Perform ! Call(promiseCapability.[[Reject]], undefined, « r »).
+ reject_promise(vm, promise, reason);
+
+ // 4. Return promiseCapability.
+ promise
+}
+
+/// A promise rejected with the exception, which is created in the realm of the promise.
+pub(crate) fn create_rejected_promise_from_exception(vm: &Vm, realm: Gc<Realm>, exception: Exception) -> WebIdlPromise {
+ let reason = exception_value(vm, realm, exception);
+ create_rejected_promise(vm, realm, reason)
+}
+
+/// The value of an exception that is created in the realm.
+pub(crate) fn exception_value(vm: &Vm, realm: Gc<Realm>, exception: Exception) -> Value {
+ let _type_error_realm = vm.type_error_realm_scope(realm);
+ with_temporary_execution_context(realm, || exception.throw(&CallContext::new(vm, realm)).value())
+}
+
+/// The realm of the promise's [[Promise]], which its reactions run in.
+pub(crate) fn promise_realm(promise: WebIdlPromise) -> Gc<Realm> {
+ promise.promise().shape().realm()
+}
+
+/// Resolves the promise with the value, https://webidl.spec.whatwg.org/#resolve
+pub(crate) fn resolve_promise(vm: &Vm, promise: WebIdlPromise, value: Value) {
+ // 1. If x is not given, then let it be the undefined value.
+ // 2. Let value be the result of converting x to an ECMAScript value.
+ // 3. Perform ! Call(p.[[Resolve]], undefined, « value »).
+ call(
+ vm,
+ Value::from_object(promise.resolve().upcast::<Object>()),
+ Value::UNDEFINED,
+ &[value],
+ )
+ .must();
+}
+
+/// Rejects the promise with the reason, https://webidl.spec.whatwg.org/#reject
+pub(crate) fn reject_promise(vm: &Vm, promise: WebIdlPromise, reason: Value) {
+ // 1. Perform ! Call(p.[[Reject]], undefined, « r »).
+ call(
+ vm,
+ Value::from_object(promise.reject().upcast::<Object>()),
+ Value::UNDEFINED,
+ &[reason],
+ )
+ .must();
+}
+
+/// Rejects the promise with the exception, which is created in the realm of the promise.
+pub(crate) fn reject_promise_with_exception(vm: &Vm, promise: WebIdlPromise, exception: Exception) {
+ let reason = exception_value(vm, promise_realm(promise), exception);
+ reject_promise(vm, promise, reason);
+}
+
+/// The steps that a reaction to a promise performs given what the reaction captures and the value or the reason.
+pub(crate) type ReactionSteps<C> = fn(&CallContext, C, Value) -> WebIdlResult<Value>;
+
+/// What a native function that runs steps given by a plain function captures: the state that the steps are given, and
+/// the steps, which the native function's behaviour itself cannot capture.
+pub(crate) struct NativeSteps<C, S> {
+ pub(crate) captures: C,
+ pub(crate) steps: S,
+}
+
+// SAFETY: The steps are a plain function, which holds no cells.
+unsafe impl<C: Trace, S> Trace for NativeSteps<C, S> {
+ fn trace(&self, visitor: &mut Visitor) {
+ self.captures.trace(visitor);
+ }
+}
+
+/// Reacts to the promise with the steps, https://webidl.spec.whatwg.org/#dfn-perform-steps-once-promise-is-settled,
+/// which are given the captures.
+pub(crate) fn react_to_promise<C: Trace + Copy + 'static>(
+ vm: &Vm,
+ promise: WebIdlPromise,
+ captures: C,
+ on_fulfilled: Option<ReactionSteps<C>>,
+ on_rejected: Option<ReactionSteps<C>>,
+) -> WebIdlPromise {
+ let realm = promise_realm(promise);
+ let name = PropertyKey::from_utf8("");
+
+ // 1. Let onFulfilledSteps be the following steps given argument V:
+ let on_fulfilled_steps = |vm: &Vm, function: &NativeSteps<(C, Gc<Realm>), Option<ReactionSteps<C>>>| {
+ let (captures, realm) = function.captures;
+ let cx = CallContext::new(vm, realm);
+
+ // 1. Let value be the result of converting V to an IDL value of type T.
+ let value = vm.argument(0);
+
+ // 2. If there is a set of steps to be run if the promise was fulfilled, then let result be the result of
+ // performing them, given value if T is not undefined. Otherwise, let result be value.
+ let result = match function.steps {
+ Some(steps) => steps(&cx, captures, value).map_err(|exception| exception.throw(&cx))?,
+ None => value,
+ };
+
+ // 3. Return result, converted to an ECMAScript value.
+ Ok(result)
+ };
+
+ // 2. Let onFulfilled be CreateBuiltinFunction(onFulfilledSteps, 1, "", « »):
+ let on_fulfilled_function = NativeFunction::create(
+ vm,
+ NativeSteps {
+ captures: (captures, realm),
+ steps: on_fulfilled,
+ },
+ on_fulfilled_steps,
+ 1,
+ &name,
+ Some(realm),
+ None,
+ None,
+ );
+
+ // 3. Let onRejectedSteps be the following steps given argument R:
+ let on_rejected_steps = |vm: &Vm, function: &NativeSteps<(C, Gc<Realm>), Option<ReactionSteps<C>>>| {
+ let (captures, realm) = function.captures;
+ let cx = CallContext::new(vm, realm);
+
+ // 1. Let reason be the result of converting R to an IDL value of type any.
+ let reason = vm.argument(0);
+
+ // 2. If there is a set of steps to be run if the promise was rejected, then let result be the result of
+ // performing them, given reason. Otherwise, let result be a promise rejected with reason.
+ let result = match function.steps {
+ Some(steps) => steps(&cx, captures, reason).map_err(|exception| exception.throw(&cx))?,
+ None => Value::from_object(create_rejected_promise(vm, realm, reason).promise()),
+ };
+
+ // 3. Return result, converted to an ECMAScript value.
+ Ok(result)
+ };
+
+ // 4. Let onRejected be CreateBuiltinFunction(onRejectedSteps, 1, "", « »):
+ let on_rejected_function = NativeFunction::create(
+ vm,
+ NativeSteps {
+ captures: (captures, realm),
+ steps: on_rejected,
+ },
+ on_rejected_steps,
+ 1,
+ &name,
+ Some(realm),
+ None,
+ None,
+ );
+
+ // 5. Let constructor be promise.[[Promise]].[[Realm]].[[Intrinsics]].[[%Promise%]].
+ // 6. Let newCapability be ? NewPromiseCapability(constructor).
+ let new_capability = create_promise(vm, realm);
+
+ // 7. Perform PerformPromiseThen(promise.[[Promise]], onFulfilled, onRejected, newCapability).
+ promise_object(promise).perform_then(
+ vm,
+ Value::from_object(on_fulfilled_function.upcast::<Object>()),
+ Value::from_object(on_rejected_function.upcast::<Object>()),
+ Some(new_capability),
+ );
+
+ // 8. Return newCapability.
+ new_capability
+}
+
+/// Performs the steps upon fulfillment of the promise, https://webidl.spec.whatwg.org/#upon-fulfillment
+pub(crate) fn upon_fulfillment<C: Trace + Copy + 'static>(
+ vm: &Vm,
+ promise: WebIdlPromise,
+ captures: C,
+ steps: ReactionSteps<C>,
+) -> WebIdlPromise {
+ // 1. Return the result of reacting to promise:
+ // - If promise was fulfilled with value v, then:
+ // 1. Perform steps with v.
+ react_to_promise(vm, promise, captures, Some(steps), None)
+}
+
+/// Performs the steps upon rejection of the promise, https://webidl.spec.whatwg.org/#upon-rejection
+pub(crate) fn upon_rejection<C: Trace + Copy + 'static>(
+ vm: &Vm,
+ promise: WebIdlPromise,
+ captures: C,
+ steps: ReactionSteps<C>,
+) -> WebIdlPromise {
+ // 1. Return the result of reacting to promise:
+ // - If promise was rejected with reason r, then:
+ // 1. Perform steps with r.
+ react_to_promise(vm, promise, captures, None, Some(steps))
+}
+
+/// Marks the promise as handled, https://webidl.spec.whatwg.org/#mark-a-promise-as-handled
+pub(crate) fn mark_promise_as_handled(vm: &Vm, promise: WebIdlPromise) {
+ // To mark as handled a Promise<T> promise, set promise.[[Promise]].[[PromiseIsHandled]] to true.
+ let promise_object = promise_object(promise);
+
+ // AD-HOC: If the promise was already rejected, tell the host it is now handled, matching what
+ // PerformPromiseThen does when a handler is attached to a rejected promise. This pulls the
+ // promise out of the about-to-be-notified rejected promises list, so specs that reject a
+ // promise and then mark it as handled (the Streams API does this on every reader and writer
+ // release) don't leave a trail of queued unhandled-rejection notification tasks behind.
+ if promise_object.state() == PromiseState::Rejected && !promise_object.is_handled() {
+ vm.host_promise_rejection_tracker()(vm, promise_object, RejectionOperation::Handle);
+ }
+
+ promise_object.set_is_handled();
+}
+
+pub(crate) fn is_promise_fulfilled(promise: WebIdlPromise) -> bool {
+ promise_object(promise).state() == PromiseState::Fulfilled
+}
+
+/// A promise that settles once every promise has, https://webidl.spec.whatwg.org/#waiting-for-all-promise
+pub(crate) fn get_promise_for_wait_for_all(vm: &Vm, realm: Gc<Realm>, promises: &[WebIdlPromise]) -> WebIdlPromise {
+ // 1. Let promise be a new promise of type Promise<sequence<T>> in realm.
+ let promise = create_promise(vm, realm);
+
+ // 2. Let successSteps be the following steps, given results:
+ // 3. Let failureSteps be the following steps, given reason:
+ // 4. Wait for all with promises, given successSteps and failureSteps.
+ wait_for_all(vm, realm, promises, promise);
+
+ // 5. Return promise.
+ promise
+}
+
+/// The state of waiting for all of some promises, https://webidl.spec.whatwg.org/#wait-for-all, whose success and
+/// failure steps settle `promise`.
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+struct WaitForAll {
+ promise: WebIdlPromise,
+ realm: Gc<Realm>,
+ rejected: Cell<bool>,
+ result: Gc<Array>,
+ #[gc(untraced)]
+ total: usize,
+ #[gc(untraced)]
+ fulfilled_count: Cell<usize>,
+}
+
+static WAIT_FOR_ALL_CLASS: EmbedderClass<WaitForAll> = EmbedderClass::new("WaitForAll");
+
+impl EmbedderValue for WaitForAll {
+ const CLASS: &'static EmbedderClass<Self> = &WAIT_FOR_ALL_CLASS;
+}
+
+impl WaitForAll {
+ // 2. Let successSteps be the following steps, given results:
+ fn success_steps(&self, vm: &Vm) {
+ with_temporary_execution_context_and_callbacks(self.realm, || {
+ // 1. Resolve promise with results.
+ resolve_promise(vm, self.promise, Value::from_object(self.result.upcast::<Object>()));
+ });
+ }
+
+ // 3. Let failureSteps be the following steps, given reason:
+ fn failure_steps(&self, vm: &Vm, reason: Value) {
+ with_temporary_execution_context_and_callbacks(self.realm, || {
+ // 1. Reject promise with reason.
+ reject_promise(vm, self.promise, reason);
+ });
+ }
+}
+
+/// Waits for all of the promises, https://webidl.spec.whatwg.org/#wait-for-all, with the success and failure steps of
+/// getting a promise to wait for all, which settle `promise`.
+fn wait_for_all(vm: &Vm, realm: Gc<Realm>, promises: &[WebIdlPromise], promise: WebIdlPromise) {
+ let name = PropertyKey::from_utf8("");
+
+ // 1. Let fullfilledCount be 0.
+ // 2. Let rejected be false.
+ // 5. Let total be promises’s size.
+ // 8. Let result be a list containing total null values.
+ let total = promises.len();
+ let result = Array::create_from(vm, realm, &vec![Value::NULL; total]);
+ let state = WAIT_FOR_ALL_CLASS.allocate(
+ vm,
+ WaitForAll {
+ promise,
+ realm,
+ rejected: Cell::new(false),
+ result,
+ total,
+ fulfilled_count: Cell::new(0),
+ },
+ );
+
+ // 3. Let rejectionHandlerSteps be the following steps given arg:
+ let rejection_handler_steps = |vm: &Vm, state: &Gc<EmbedderCell<WaitForAll>>| {
+ // 1. If rejected is true, abort these steps.
+ if state.rejected.get() {
+ return Ok(Value::UNDEFINED);
+ }
+
+ // 2. Set rejected to true.
+ state.rejected.set(true);
+
+ // 3. Perform failureSteps given arg.
+ state.failure_steps(vm, vm.argument(0));
+ Ok(Value::UNDEFINED)
+ };
+
+ // 4. Let rejectionHandler be CreateBuiltinFunction(rejectionHandlerSteps, 1, "", « »):
+ let rejection_handler =
+ NativeFunction::create(vm, state, rejection_handler_steps, 1, &name, Some(realm), None, None);
+
+ // 6. If total is 0, then:
+ if total == 0 {
+ // 1. Queue a microtask to perform successSteps given « ».
+ queue_a_microtask(vm, realm, state, |vm, state| state.success_steps(vm));
+
+ // 2. Return.
+ return;
+ }
+
+ // 7. Let index be 0.
+ // 9. For each promise of promises:
+ for (index, each_promise) in promises.iter().enumerate() {
+ // 1. Let promiseIndex be index.
+ let promise_index = u32::try_from(index).expect("a list of promises fits an array");
+
+ // 2. Let fulfillmentHandler be the following steps given arg:
+ let fulfillment_handler_steps = |vm: &Vm, captures: &(Gc<EmbedderCell<WaitForAll>>, u32)| {
+ let (state, promise_index) = *captures;
+
+ // 1. Set result[promiseIndex] to arg.
+ state
+ .result
+ .create_data_property(vm, &PropertyKey::from(promise_index), vm.argument(0), None, None)
+ .must();
+
+ // 2. Set fullfilledCount to fullfilledCount + 1.
+ state.fulfilled_count.set(state.fulfilled_count.get() + 1);
+
+ // 3. If fullfilledCount equals total, then perform successSteps given result.
+ if state.fulfilled_count.get() == state.total {
+ state.success_steps(vm);
+ }
+ Ok(Value::UNDEFINED)
+ };
+
+ // 3. Let fulfillmentHandler be CreateBuiltinFunction(fulfillmentHandler, 1, "", « »):
+ let fulfillment_handler = NativeFunction::create(
+ vm,
+ (state, promise_index),
+ fulfillment_handler_steps,
+ 1,
+ &name,
+ Some(realm),
+ None,
+ None,
+ );
+
+ // 4. Perform PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler).
+ promise_object(*each_promise).perform_then(
+ vm,
+ Value::from_object(fulfillment_handler.upcast::<Object>()),
+ Value::from_object(rejection_handler.upcast::<Object>()),
+ None,
+ );
+
+ // 5. Set index to index + 1.
+ }
+}
+
+/// Queues a microtask that performs the steps with the captures,
+/// https://html.spec.whatwg.org/multipage/webappapis.html#queue-a-microtask
+pub(crate) fn queue_a_microtask<C: Trace + Copy + 'static>(vm: &Vm, realm: Gc<Realm>, captures: C, steps: fn(&Vm, C)) {
+ let function = NativeFunction::create(
+ vm,
+ NativeSteps { captures, steps },
+ |vm: &Vm, function: &NativeSteps<C, fn(&Vm, C)>| {
+ (function.steps)(vm, function.captures);
+ Ok(Value::UNDEFINED)
+ },
+ 0,
+ &PropertyKey::from_utf8(""),
+ Some(realm),
+ None,
+ None,
+ );
+ // SAFETY: The realm and the function are live.
+ unsafe { web_bindings_queue_a_microtask(realm.as_ptr().cast(), function.as_ptr().cast()) };
+}
+
+/// The [[Promise]] of a promise capability that LibWeb created, which is a Promise.
+fn promise_object(promise: WebIdlPromise) -> Gc<Promise> {
+ promise
+ .promise()
+ .downcast::<Promise>()
+ .expect("the promise of a capability that the bindings create is a Promise")
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/services.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/services.rs
index 8ef31f3dea7..8633f55fc71 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/services.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/services.rs
@@ -36,9 +36,10 @@ unsafe extern "C" {
pub(crate) fn web_bindings_realm_is_window(realm: *mut c_void) -> bool;
/// Runs the steps with the context while an execution context of the realm is on the stack, as an
- /// HTML::TemporaryExecutionContext puts it there.
+ /// HTML::TemporaryExecutionContext puts it there, with callbacks enabled if `callbacks_enabled`.
pub(crate) fn web_bindings_with_temporary_execution_context(
realm: *mut c_void,
+ callbacks_enabled: bool,
context: *mut c_void,
steps: unsafe extern "C" fn(*mut c_void),
);
diff --git a/Libraries/LibWeb/Bindings/Rust/src/file_api/blob.rs b/Libraries/LibWeb/Bindings/Rust/src/file_api/blob.rs
index b32777a0c7b..48c16adeb8e 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/file_api/blob.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/file_api/blob.rs
@@ -18,6 +18,7 @@ use libwebcommon_rust::mime_sniff::mime_type::MimeType;
use super::file::File;
use crate::bindings::conversions::{BufferSource, CppInterface, UsvString};
use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate, cell_into_abi};
+use crate::bindings::promise::{WebIdlPromise, promise_from_abi};
use crate::bindings::structured_data::{Serializable, SerializationReader, SerializationWriter};
use crate::bindings::{CallContext, WebIdlResult};
@@ -476,10 +477,10 @@ impl Blob {
}
// https://w3c.github.io/FileAPI/#dom-blob-text
- pub(crate) fn text(&self, cx: &mut CallContext) -> WebIdlResult<Gc<Object>> {
+ pub(crate) fn text(&self, cx: &mut CallContext) -> WebIdlResult<WebIdlPromise> {
// SAFETY: The realm is live, LibWeb copies the bytes, and it returns a new promise.
Ok(unsafe {
- object_from_abi(web_blob_text(
+ promise_from_abi(web_blob_text(
cx.realm().as_ptr().cast(),
ak::Span::new(&self.raw_bytes()),
))
@@ -487,10 +488,10 @@ impl Blob {
}
// https://w3c.github.io/FileAPI/#dom-blob-arraybuffer
- pub(crate) fn array_buffer(&self, cx: &mut CallContext) -> WebIdlResult<Gc<Object>> {
+ pub(crate) fn array_buffer(&self, cx: &mut CallContext) -> WebIdlResult<WebIdlPromise> {
// SAFETY: The realm is live, LibWeb copies the bytes, and it returns a new promise.
Ok(unsafe {
- object_from_abi(web_blob_array_buffer(
+ promise_from_abi(web_blob_array_buffer(
cx.realm().as_ptr().cast(),
ak::Span::new(&self.raw_bytes()),
))
@@ -498,10 +499,10 @@ impl Blob {
}
// https://w3c.github.io/FileAPI/#dom-blob-bytes
- pub(crate) fn bytes(&self, cx: &mut CallContext) -> WebIdlResult<Gc<Object>> {
+ pub(crate) fn bytes(&self, cx: &mut CallContext) -> WebIdlResult<WebIdlPromise> {
// SAFETY: The realm is live, LibWeb copies the bytes, and it returns a new promise.
Ok(unsafe {
- object_from_abi(web_blob_bytes(
+ promise_from_abi(web_blob_bytes(
cx.realm().as_ptr().cast(),
ak::Span::new(&self.raw_bytes()),
))
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/canvas.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/canvas.rs
index 8526e595bfa..9d8952950ae 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/web_gl/canvas.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/canvas.rs
@@ -17,6 +17,7 @@ use libjs_rust::api::{Gc, Object, Realm};
use super::host::Frame;
use super::pixel_unpacking::PixelUnpackState;
use crate::bindings::conversions::CppInterface;
+use crate::bindings::promise::{WebIdlPromise, promise_from_abi};
/// The sources of texture images that are implemented in C++, in the order of the C++ enum of the same name.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -201,10 +202,7 @@ fn tex_image_source_frame(result: u8, frame: *mut c_void) -> TexImageSourceFrame
/// # Safety
///
/// `context` is the cell of a WebGL context.
-pub(crate) unsafe fn make_xr_compatible(context: *mut c_void) -> Gc<Object> {
- // SAFETY: The caller passes the cell of a context.
- let promise = unsafe { web_webgl_make_xr_compatible(context) };
- let promise = NonNull::new(promise.cast::<Object>()).expect("LibWeb returns the promise");
- // SAFETY: LibWeb returns a live promise.
- unsafe { Gc::from_non_null(promise) }
+pub(crate) unsafe fn make_xr_compatible(context: *mut c_void) -> WebIdlPromise {
+ // SAFETY: The caller passes the cell of a context, and LibWeb returns a live promise.
+ unsafe { promise_from_abi(web_webgl_make_xr_compatible(context)) }
}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/web_gl_rendering_context_base.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/web_gl_rendering_context_base.rs
index 168b0eba7ae..4126ca43f65 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/web_gl/web_gl_rendering_context_base.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/web_gl_rendering_context_base.rs
@@ -41,6 +41,7 @@ use super::web_gl_texture::WebGLTexture;
use super::web_gl_uniform_location::WebGLUniformLocation;
use crate::bindings::conversions::CppInterface;
use crate::bindings::interface::Ref;
+use crate::bindings::promise::WebIdlPromise;
use crate::bindings::{CallContext, WebIdlResult};
/// https://www.khronos.org/registry/webgl/specs/latest/1.0/#WEBGLCONTEXTATTRIBUTES
@@ -850,7 +851,7 @@ impl<V: Version> RenderingContext<V> {
Ok(self.proxy.get_attrib_location(program_handle, &utf8_bytes(&name)))
}
- pub(crate) fn make_xr_compatible(&self, _: &mut CallContext) -> WebIdlResult<Gc<Object>> {
+ pub(crate) fn make_xr_compatible(&self, _: &mut CallContext) -> WebIdlResult<WebIdlPromise> {
// SAFETY: The cell is that of this context.
Ok(unsafe { super::canvas::make_xr_compatible(self.context_ref().cell()) })
}
diff --git a/Libraries/LibWeb/Bindings/RustBindingsServices.cpp b/Libraries/LibWeb/Bindings/RustBindingsServices.cpp
index e9f9c2aa940..f18d206e633 100644
--- a/Libraries/LibWeb/Bindings/RustBindingsServices.cpp
+++ b/Libraries/LibWeb/Bindings/RustBindingsServices.cpp
@@ -13,11 +13,14 @@
#include <LibWeb/Bindings/RustSerialization.h>
#include <LibWeb/Bindings/Wrappable.h>
#include <LibWeb/Bindings/WrapperWorld.h>
+#include <LibWeb/HTML/EventLoop/EventLoop.h>
#include <LibWeb/HTML/Scripting/Environments.h>
#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
#include <LibWeb/HTML/StructuredSerialize.h>
#include <LibWeb/HTML/Window.h>
#include <LibWeb/HTML/WindowProxy.h>
+#include <LibWeb/WebIDL/AbstractOperations.h>
+#include <LibWeb/WebIDL/CallbackType.h>
#include <LibWeb/WebIDL/DOMException.h>
#include <LibWeb/WebIDL/ExceptionOrUtils.h>
#include <LibWeb/WebIDL/Promise.h>
@@ -87,8 +90,12 @@ 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);
+void web_bindings_queue_a_microtask(void* realm, JSObject* function);
+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);
bool web_bindings_realm_is_window(void* realm);
-void web_bindings_with_temporary_execution_context(void* realm, void* context, void (*steps)(void*));
+void web_bindings_with_temporary_execution_context(void* realm, bool callbacks_enabled, void* context, void (*steps)(void*));
bool web_bindings_object_implements_interface(JSObject* object, u16 interface_name);
JSObject* web_bindings_create_dom_exception(void* realm, ReadonlyBytes name, FlatPtr message);
bool web_bindings_extract_an_origin(JSObject* object, void* ctx, void (*on_origin)(void*, URL::FFI::FfiOrigin const*));
@@ -133,9 +140,9 @@ bool web_bindings_realm_is_window(void* realm)
return HTML::window_from_global_object(static_cast<JS::Realm*>(realm)->global_object());
}
-void web_bindings_with_temporary_execution_context(void* realm, void* context, void (*steps)(void*))
+void web_bindings_with_temporary_execution_context(void* realm, bool callbacks_enabled, void* context, void (*steps)(void*))
{
- HTML::TemporaryExecutionContext execution_context { *static_cast<JS::Realm*>(realm) };
+ HTML::TemporaryExecutionContext execution_context { *static_cast<JS::Realm*>(realm), callbacks_enabled ? HTML::TemporaryExecutionContext::CallbacksEnabled::Yes : HTML::TemporaryExecutionContext::CallbacksEnabled::No };
steps(context);
}
@@ -287,6 +294,50 @@ JSObject* web_bindings_rejected_promise(void* current_realm, JSValue this_value,
auto promise = WebIDL::create_rejected_promise(promise_realm, JS::HostABI::value_from_abi(reason));
return JS::HostABI::object_to_abi(promise->promise().ptr());
}
+
+void web_bindings_queue_a_microtask(void* realm, JSObject* function)
+{
+ GC::Ref<JS::Realm> js_realm = *static_cast<JS::Realm*>(realm);
+ GC::Ref<JS::FunctionObject> steps = as<JS::FunctionObject>(*JS::HostABI::object_from_abi(function));
+ HTML::queue_a_microtask(nullptr, GC::create_function(GC::Heap::the(), [js_realm, steps] {
+ HTML::TemporaryExecutionContext execution_context { js_realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };
+ MUST(JS::call(steps->vm(), *steps, JS::js_undefined()));
+ }));
+}
+
+void* web_bindings_create_callback_function(JSObject* callable, bool returns_promise)
+{
+ auto& object = *JS::HostABI::object_from_abi(callable);
+ return GC::Heap::the().allocate<WebIDL::CallbackType>(object, HTML::incumbent_settings_object(), returns_promise ? WebIDL::OperationReturnsPromise::Yes : WebIDL::OperationReturnsPromise::No).ptr();
+}
+
+static GC::RootVector<JS::Value> callback_arguments(ReadonlySpan<JSValue> arguments)
+{
+ GC::RootVector<JS::Value> values;
+ values.ensure_capacity(arguments.size());
+ for (auto argument : arguments)
+ values.unchecked_append(JS::HostABI::value_from_abi(argument));
+ return values;
+}
+
+JSCompletion web_bindings_invoke_callback_function(void* callback, bool has_this_value, JSValue this_value, ReadonlySpan<JSValue> arguments)
+{
+ Optional<JS::Value> this_argument;
+ if (has_this_value)
+ this_argument = JS::HostABI::value_from_abi(this_value);
+ auto completion = WebIDL::invoke_callback(*static_cast<WebIDL::CallbackType*>(callback), this_argument, callback_arguments(arguments));
+ if (completion.is_error())
+ return JS::HostABI::throw_completion_to_abi(completion.value());
+ return JS::HostABI::normal_completion_to_abi(JS::HostABI::value_to_abi(completion.value()));
+}
+
+void* web_bindings_invoke_promise_callback_function(void* callback, bool has_this_value, JSValue this_value, ReadonlySpan<JSValue> arguments)
+{
+ Optional<JS::Value> this_argument;
+ if (has_this_value)
+ this_argument = JS::HostABI::value_from_abi(this_value);
+ return WebIDL::invoke_promise_callback(*static_cast<WebIDL::CallbackType*>(callback), this_argument, callback_arguments(arguments)).ptr();
+}
}
}
diff --git a/Libraries/LibWeb/FileAPI/Blob.cpp b/Libraries/LibWeb/FileAPI/Blob.cpp
index 9f23152df1d..9a7317831f4 100644
--- a/Libraries/LibWeb/FileAPI/Blob.cpp
+++ b/Libraries/LibWeb/FileAPI/Blob.cpp
@@ -62,9 +62,9 @@ bool web_blob_is_file(void* blob);
// Called by Bindings/Rust/src/file_api/blob.rs.
void web_blob_bytes_destroy(BlobBytes*);
JSObject* web_blob_get_stream(void* realm, ReadonlyBytes);
-JSObject* web_blob_text(void* realm, ReadonlyBytes);
-JSObject* web_blob_array_buffer(void* realm, ReadonlyBytes);
-JSObject* web_blob_bytes(void* realm, ReadonlyBytes);
+WebIDL::Promise* web_blob_text(void* realm, ReadonlyBytes);
+WebIDL::Promise* web_blob_array_buffer(void* realm, ReadonlyBytes);
+WebIDL::Promise* web_blob_bytes(void* realm, ReadonlyBytes);
JSCompletion web_blob_deserialize_byte_sequence(Bindings::RustSerializationReader*, BlobBytesABI* out_bytes);
}
@@ -191,7 +191,7 @@ JSObject* web_blob_get_stream(void* realm, ReadonlyBytes blob_bytes)
}
// https://w3c.github.io/FileAPI/#dom-blob-text
-JSObject* web_blob_text(void* realm, ReadonlyBytes blob_bytes)
+WebIDL::Promise* web_blob_text(void* realm, ReadonlyBytes blob_bytes)
{
auto& js_realm = *static_cast<JS::Realm*>(realm);
auto& vm = js_realm.vm();
@@ -205,11 +205,11 @@ JSObject* web_blob_text(void* realm, ReadonlyBytes blob_bytes)
auto text = TRY_OR_THROW_OOM(vm, TextCodec::utf8_decode_to_utf16(ReadonlyBytes { array_buffer.data_at(0), array_buffer.byte_length() }));
return JS::PrimitiveString::create(vm, move(text));
}));
- return JS::HostABI::object_to_abi(promise->promise().ptr());
+ return promise.ptr();
}
// https://w3c.github.io/FileAPI/#dom-blob-arraybuffer
-JSObject* web_blob_array_buffer(void* realm, ReadonlyBytes blob_bytes)
+WebIDL::Promise* web_blob_array_buffer(void* realm, ReadonlyBytes blob_bytes)
{
auto& js_realm = *static_cast<JS::Realm*>(realm);
@@ -221,11 +221,11 @@ JSObject* web_blob_array_buffer(void* realm, ReadonlyBytes blob_bytes)
return JS::ArrayBuffer::create(js_realm, MUST(ByteBuffer::copy(ReadonlyBytes { array_buffer.data_at(0), array_buffer.byte_length() })));
}));
- return JS::HostABI::object_to_abi(promise->promise().ptr());
+ return promise.ptr();
}
// https://w3c.github.io/FileAPI/#dom-blob-bytes
-JSObject* web_blob_bytes(void* realm, ReadonlyBytes blob_bytes)
+WebIDL::Promise* web_blob_bytes(void* realm, ReadonlyBytes blob_bytes)
{
auto& js_realm = *static_cast<JS::Realm*>(realm);
@@ -236,7 +236,7 @@ JSObject* web_blob_bytes(void* realm, ReadonlyBytes blob_bytes)
auto& array_buffer = static_cast<JS::ArrayBuffer&>(object);
return JS::Uint8Array::create(js_realm, array_buffer.byte_length(), array_buffer);
}));
- return JS::HostABI::object_to_abi(promise->promise().ptr());
+ return promise.ptr();
}
void web_blob_bytes_destroy(BlobBytes* bytes)
diff --git a/Libraries/LibWeb/WebGL/WebGLRenderingContextBase.cpp b/Libraries/LibWeb/WebGL/WebGLRenderingContextBase.cpp
index 6a2e9e591f4..5f7decf2d6d 100644
--- a/Libraries/LibWeb/WebGL/WebGLRenderingContextBase.cpp
+++ b/Libraries/LibWeb/WebGL/WebGLRenderingContextBase.cpp
@@ -549,7 +549,7 @@ TexImageSourceResult web_webgl_read_tex_image_pixels(u8 const* pixels, u32 width
void* web_webgl_make_xr_compatible(void* context)
{
- return static_cast<WebGLRenderingContextBase*>(context)->make_xr_compatible()->promise().ptr();
+ return static_cast<WebGLRenderingContextBase*>(context)->make_xr_compatible().ptr();
}
}
diff --git a/Meta/Generators/libweb_bindings/rust_bindings.py b/Meta/Generators/libweb_bindings/rust_bindings.py
index 4ee186917c6..1e23ffce712 100644
--- a/Meta/Generators/libweb_bindings/rust_bindings.py
+++ b/Meta/Generators/libweb_bindings/rust_bindings.py
@@ -55,7 +55,6 @@ from Generators.libweb_bindings.rust_types import is_implemented_in_rust
from Generators.libweb_bindings.rust_types import is_promise_type
from Generators.libweb_bindings.rust_types import rust_interface_path
from Generators.libweb_bindings.rust_types import rust_parameter_type
-from Generators.libweb_bindings.rust_types import rust_result_type
from Generators.libweb_bindings.rust_types import rust_type
from Generators.libweb_bindings.rust_usage import DefinitionUsage
from Generators.libweb_bindings.wrappers import wrapper_name
@@ -66,6 +65,8 @@ from Utils.webidl_parser import OperationParameter
# The extended attributes of an interface that the Rust bindings handle.
SUPPORTED_INTERFACE_EXTENDED_ATTRIBUTES = {
+ # NB: The asynchronous iterator prototype object of the interface has a "return" method.
+ "DefinesAsyncIteratorReturn",
"Experimental",
"Exposed",
"ImplementedIn",
@@ -100,6 +101,10 @@ def iterator_host_class_symbol(interface: Interface) -> str:
return f"web_bindings_{rust_module_name(interface)}_iterator_host_class"
+def async_iterator_host_class_symbol(interface: Interface) -> str:
+ return f"web_bindings_{rust_module_name(interface)}_async_iterator_host_class"
+
+
def interface_name_values(intrinsics: List[Interface]) -> Dict[str, int]:
"""The value of Web::Bindings::InterfaceName for each interface, which the Rust bindings pass the C++ bindings:
the interfaces in the order of the intrinsics, from 1, as 0 is Unknown."""
@@ -167,6 +172,18 @@ public:
static void initialize(JS::Realm&, JS::Object&);
}};
+"""
+ )
+ if rust_members(interface).async_iterator is not None:
+ out.write(
+ f"""// The class of the default asynchronous iterator objects of {interface.name}, whose cells the Rust bindings create.
+extern "C" JSHostClass const {async_iterator_host_class_symbol(interface)};
+
+struct {interface.name}AsyncIteratorPrototype {{
+public:
+ static void initialize(JS::Realm&, JS::Object&);
+}};
+
"""
)
@@ -290,6 +307,21 @@ void {interface.name}IteratorPrototype::initialize(JS::Realm& realm, JS::Object&
{initialize_iterator_prototype}(JS::HostABI::vm_to_abi(realm.vm()), &realm, JS::HostABI::object_to_abi(&object));
}}
+"""
+ )
+ if rust_members(interface).async_iterator is not None:
+ initialize_async_iterator_prototype = rust_entry_point_name(interface, "initialize_async_iterator_prototype")
+ out.write(
+ f"""extern "C" void {initialize_async_iterator_prototype}(JSVM*, void* realm, JSObject* prototype);
+
+constexpr JSHostClass {async_iterator_host_class_symbol(interface)} = JS::make_host_class(JS_HOST_CLASS_OBJECT, "{interface.name}AsyncIterator"sv,
+ nullptr, nullptr, nullptr, 0);
+
+void {interface.name}AsyncIteratorPrototype::initialize(JS::Realm& realm, JS::Object& object)
+{{
+ {initialize_async_iterator_prototype}(JS::HostABI::vm_to_abi(realm.vm()), &realm, JS::HostABI::object_to_abi(&object));
+}}
+
"""
)
@@ -346,11 +378,18 @@ JSObject* {function}(void* realm, u16 interface_name)
f'ensure_web_constructor<{interface.prototype_class}>(js_realm, "{interface.namespaced_name}"_utf16_fly_string)'
),
)
+ # NB: An interface has a pair iterator or an asynchronously iterable declaration, not both.
write_switch(
"web_bindings_ensure_web_iterator_prototype",
- [interface for interface in rust_interfaces if rust_members(interface).pair_iterator is not None],
+ [
+ interface
+ for interface in rust_interfaces
+ if rust_members(interface).pair_iterator is not None or rust_members(interface).async_iterator is not None
+ ],
lambda interface: (
- f'ensure_web_prototype<{interface.name}IteratorPrototype>(js_realm, "{interface.name}Iterator"_utf16_fly_string)'
+ f'ensure_web_prototype<{interface.name}AsyncIteratorPrototype>(js_realm, "{interface.name}AsyncIterator"_utf16_fly_string)'
+ if rust_members(interface).async_iterator is not None
+ else f'ensure_web_prototype<{interface.name}IteratorPrototype>(js_realm, "{interface.name}Iterator"_utf16_fly_string)'
),
)
@@ -453,12 +492,13 @@ def implementation_method_signatures(
)
for attribute in members.attributes:
what = f"{interface.name}.{attribute.attribute.name}"
- attribute_type = rust_type(attribute.attribute.type, context, what)
if not attribute.attribute.inherit:
+ result_type = rust_type(attribute.attribute.type, context, what, is_result=True)
signatures.append(
- f"fn {attribute.getter_method}(&self, cx: &mut CallContext) -> WebIdlResult<{attribute_type}>"
+ f"fn {attribute.getter_method}(&self, cx: &mut CallContext) -> WebIdlResult<{result_type}>"
)
if attribute.setter_method is not None:
+ attribute_type = rust_type(attribute.attribute.type, context, what)
signatures.append(
f"fn {attribute.setter_method}(&self, cx: &mut CallContext, value: {attribute_type}) -> "
"WebIdlResult<()>"
@@ -471,7 +511,7 @@ def implementation_method_signatures(
parameters = parameter_list(what, overload.operation.parameters)
signatures.append(
f"fn {overload.method}(&self, cx: &mut CallContext{parameters}) -> "
- f"WebIdlResult<{rust_result_type(overload.operation.return_type, context, what)}>"
+ f"WebIdlResult<{rust_type(overload.operation.return_type, context, what, is_result=True)}>"
)
if members.stringifier is not None and members.stringifier.defines_method:
signatures.append(f"fn {members.stringifier.method}(&self, cx: &mut CallContext) -> WebIdlResult<Utf16String>")
@@ -481,13 +521,25 @@ def implementation_method_signatures(
f"impl PairIterable with Key = {key_type} and Value = {value_type}: "
"fn value_pairs_to_iterate_over(&self) -> impl Deref<Target = [(Self::Key, Self::Value)]> + '_"
)
+ if members.async_iterator is not None:
+ what = f"the asynchronously iterable declaration of {interface.name}"
+ parameters = parameter_list(what, members.async_iterator.parameters)
+ signatures.append(
+ f"fn {members.async_iterator.method}(&self, cx: &mut CallContext{parameters}) -> "
+ "WebIdlResult<<Self as AsyncIterable>::IteratorState>"
+ )
+ signatures.append(
+ "impl AsyncIterable: fn get_the_next_iteration_result(cx: &CallContext, state: &Self::IteratorState) -> "
+ "WebIdlPromise, fn asynchronous_iterator_return(cx: &CallContext, state: &Self::IteratorState, value: "
+ "Value) -> WebIdlPromise"
+ )
if members.indexed_property_getter is not None:
getter = members.indexed_property_getter.operation
what = f"{interface.name}.{getter.operation.name}()"
parameters = parameter_list(what, getter.operation.parameters)
signatures.append(
f"fn {getter.method}(&self, cx: &mut CallContext{parameters}) -> "
- f"WebIdlResult<{rust_result_type(getter.operation.return_type, context, what)}>"
+ f"WebIdlResult<{rust_type(getter.operation.return_type, context, what, is_result=True)}>"
)
for operation_set in members.static_operation_sets:
for overload in operation_set.overloads:
@@ -495,7 +547,7 @@ def implementation_method_signatures(
parameters = parameter_list(what, overload.operation.parameters)
signatures.append(
f"fn {overload.method}(cx: &mut CallContext{parameters}) -> "
- f"WebIdlResult<{rust_result_type(overload.operation.return_type, context, what)}>"
+ f"WebIdlResult<{rust_type(overload.operation.return_type, context, what, is_result=True)}>"
)
return signatures
@@ -558,6 +610,86 @@ def write_rust_pair_iterator(out: TextIO, interface: Interface) -> None:
)
+def write_rust_async_iterator(out: TextIO, context: GenerationContext, interface: Interface) -> None:
+ """The classes of the default asynchronous iterator objects of the interface, the steps of its asynchronous
+ iterator prototype object, which the bindings runtime implements for every interface with a value asynchronously
+ iterable declaration, https://webidl.spec.whatwg.org/#es-asynchronous-iterator-prototype-object, and the steps of
+ its "values" method, https://webidl.spec.whatwg.org/#es-asynchronous-iterable"""
+ async_iterator = rust_members(interface).async_iterator
+ assert async_iterator is not None
+ define_return = ""
+ if async_iterator.defines_return:
+ define_return = (
+ ' define_operation(vm, realm, prototype, "return", '
+ "raw_native!(async_iterator_return::<Implementation>), 1);\n"
+ )
+ out.write(
+ f"""
+ /// The class of the cells of the default asynchronous iterator objects of the interface.
+ static ASYNC_ITERATOR_CELL_CLASS: EmbedderClass<DefaultAsyncIterator<Implementation>> = EmbedderClass::new("{interface.name} AsyncIterator");
+
+ unsafe extern "C" {{
+ static {async_iterator_host_class_symbol(interface)}: JSHostClass;
+ }}
+
+ impl DefaultAsyncIteratorClasses for Implementation {{
+ const ASYNC_ITERATOR_CELL_CLASS: &'static EmbedderClass<DefaultAsyncIterator<Self>> = &ASYNC_ITERATOR_CELL_CLASS;
+
+ fn async_iterator_class() -> &'static JSHostClass {{
+ // SAFETY: LibWeb defines the class of the default asynchronous iterator objects as constant data.
+ unsafe {{ &{async_iterator_host_class_symbol(interface)} }}
+ }}
+ }}
+
+ /// The steps of {interface.name}AsyncIteratorPrototype::initialize() of LibWeb's C++ bindings.
+ ///
+ /// # Safety
+ ///
+ /// The pointers must be the VM, a realm and the asynchronous iterator prototype object of the realm.
+ #[unsafe(no_mangle)]
+ pub unsafe extern "C" fn {rust_entry_point_name(interface, "initialize_async_iterator_prototype")}(
+ vm: *mut c_void,
+ realm: *mut c_void,
+ prototype: *mut c_void,
+ ) {{
+ // SAFETY: The caller passes live pointers.
+ let (vm, realm, prototype) = unsafe {{ entry_point_arguments(vm, realm, prototype) }};
+ define_to_string_tag(vm, prototype, "{interface.name} AsyncIterator");
+ define_operation(vm, realm, prototype, "next", raw_native!(async_iterator_next::<Implementation>), 0);
+{define_return} }}
+
+ /// The "values" and %Symbol.asyncIterator% methods of the interface prototype object,
+ /// https://webidl.spec.whatwg.org/#es-asynchronous-iterable
+ fn {async_iterator.function}(vm: &Vm) -> ThrowCompletionOr<Value> {{
+ // 1. Let jsValue be ? ToObject(this value).
+ // 2. If jsValue is a platform object, then perform a security check, passing jsValue, "%Symbol.asyncIterator%",
+ // and "method".
+ // 3. If jsValue does not implement definition, then throw a TypeError.
+ let (implementation, mut cx) = this_implementation(vm)?;
+
+ // 4. Let idlArgs be the result of converting arguments for an asynchronous iterator method given arguments.
+"""
+ )
+ write_parameter_conversions(
+ out, f"the asynchronously iterable declaration of {interface.name}", async_iterator.parameters, context
+ )
+ arguments = "".join(f", {rust_local_name(parameter.name)}" for parameter in async_iterator.parameters)
+ out.write(
+ f"""
+ // 5. Let iterator be a newly created default asynchronous iterator object for definition with jsValue as its
+ // target, "value" as its kind, and is finished set to false.
+ // 6. Run the asynchronous iterator initialization steps for definition with jsValue, iterator, and idlArgs, if
+ // any such steps exist.
+ let state = Implementation::{async_iterator.method}(&implementation, &mut cx{arguments})
+ .map_err(|exception| exception.throw(&cx))?;
+
+ // 7. Return iterator.
+ Ok(create_default_async_iterator::<Implementation>(&cx, state))
+ }}
+"""
+ )
+
+
def write_rust_interface(
out: TextIO, context: GenerationContext, module: Module, interface: Interface, interface_name_value: int
) -> None:
@@ -589,7 +721,7 @@ def write_rust_interface(
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_typed_array, to_unrestricted_double,
+ 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,
}};
@@ -600,10 +732,16 @@ def write_rust_interface(
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::{{
+ AsyncIterable, DefaultAsyncIterator, DefaultAsyncIteratorClasses, async_iterator_next, async_iterator_return,
+ create_default_async_iterator, define_async_iterator_properties,
+ }};
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::promise::WebIdlPromise;
use crate::bindings::structured_data;
use crate::bindings::{{CallContext, WebIdlResult}};
@@ -653,10 +791,19 @@ def write_rust_interface(
call = f"Implementation::{attribute.getter_method}(&implementation, &mut cx)"
if attribute.attribute.inherit:
call = inherited_attribute_getter_call(context, interface, attribute)
+ this_check = "this_implementation(vm)?"
+ if is_promise_type(attribute.attribute.type) and not attribute.attribute.type.nullable:
+ # https://webidl.spec.whatwg.org/#dfn-attribute-getter
+ this_check = """match this_implementation(vm) {
+ Ok(this) => this,
+ // If the attribute's type is a promise type, a this value that does not implement the interface rejects
+ // a new promise.
+ Err(throw) => return Ok(rejected_promise(vm, throw)),
+ }"""
out.write(
f"""
pub(super) fn {attribute.getter_function}(vm: &Vm) -> ThrowCompletionOr<Value> {{
- let (implementation, mut cx) = this_implementation(vm)?;
+ let (implementation, mut cx) = {this_check};
let result = {call}
.map_err(|exception| exception.throw(&cx))?;
{conversion}
@@ -698,6 +845,9 @@ def write_rust_interface(
if members.pair_iterator is not None:
write_rust_pair_iterator(out, interface)
+ if members.async_iterator is not None:
+ write_rust_async_iterator(out, context, interface)
+
for operation_set in members.static_operation_sets:
if len(operation_set.overloads) > 1:
raise UnsupportedByRustBindings(
@@ -781,6 +931,18 @@ def write_rust_interface(
"""
)
defined_property_names.extend(members.pair_iterator.function_names)
+ if members.async_iterator is not None:
+ out.write(
+ f""" define_async_iterator_properties(
+ vm,
+ realm,
+ prototype,
+ raw_native!({members.async_iterator.function}),
+ {members.async_iterator.length},
+ );
+"""
+ )
+ defined_property_names.append("values")
if members.constants:
out.write(" define_constants(vm, prototype, &CONSTANTS);\n")
defined_property_names.extend(constant.name for constant in members.constants)
@@ -1235,7 +1397,14 @@ def write_rust_operation(
operation = overload.operation
what = f"{interface.name}.{name}()"
steps = StringIO()
- steps.write(" let (implementation, mut cx) = this_implementation(vm)?;\n")
+ 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"));
+"""
+ )
+ else:
+ steps.write(" let (implementation, mut cx) = this_implementation(vm)?;\n")
write_argument_count_check(steps, name, overload.length)
if operation.parameters:
steps.write(" let type_error_realm_scope = vm.type_error_realm_scope(cx.realm());\n")
@@ -1253,10 +1422,7 @@ def write_rust_operation(
"""
)
else:
- if returns_promise:
- conversion = "result.to_js(&cx)"
- else:
- conversion = rust_to_js_value(operation.return_type, "result", "&cx", context, what)
+ conversion = rust_to_js_value(operation.return_type, "result", "&cx", context, what)
steps.write(
f""" let result = {call}
.map_err(|exception| exception.throw(&cx))?;
@@ -1351,6 +1517,7 @@ pub(crate) mod definitions {
};
use crate::bindings::CallContext;
+ use crate::bindings::callback::{CallbackFunction, PromiseCallbackFunction};
use crate::bindings::conversions::{
ArrayBufferView, BufferSource, BufferSourceRules, CppInterface, EmptyDictionary, FromJs, ToJs, UsvString,
buffer_source_if, dictionary_member, dictionary_object, enumeration_value_to_js, implements_cpp_interface,
@@ -1358,9 +1525,9 @@ pub(crate) mod definitions {
sequence_to_js, throw_no_union_types_matched, to_array_buffer_view, to_boolean, to_buffer_source,
to_cpp_interface,
to_dom_string, to_dom_string_treating_null_as_empty, to_double, to_enumeration_value, to_float, to_long,
- to_long_enforcing_range, to_long_long, to_long_long_enforcing_range, 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,
+ to_long_enforcing_range, to_long_long, 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::{
Interface, Ref, create_dictionary_object, implementation_if, implementation_of, set_dictionary_member,
diff --git a/Meta/Generators/libweb_bindings/rust_members.py b/Meta/Generators/libweb_bindings/rust_members.py
index 0f8f1e69ae8..f9fc9d14a43 100644
--- a/Meta/Generators/libweb_bindings/rust_members.py
+++ b/Meta/Generators/libweb_bindings/rust_members.py
@@ -27,12 +27,22 @@ from Utils.webidl_parser import Constructor
from Utils.webidl_parser import IDLType
from Utils.webidl_parser import Interface
from Utils.webidl_parser import Operation
+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"}
-SUPPORTED_OPERATION_EXTENDED_ATTRIBUTES = {"Default", "Exposed", "FIXME", "ImplementedAs", "NewObject", "SameObject"}
+# NB: The context of an operation that is [NeedsCallerRealm] has the current realm, not the realm of the object.
+SUPPORTED_OPERATION_EXTENDED_ATTRIBUTES = {
+ "Default",
+ "Exposed",
+ "FIXME",
+ "ImplementedAs",
+ "NeedsCallerRealm",
+ "NewObject",
+ "SameObject",
+}
SUPPORTED_STRINGIFIER_EXTENDED_ATTRIBUTES = {"Exposed"}
# The value of [Exposed] that the Rust bindings handle on a member: a member that only a Window has, which the
@@ -162,6 +172,25 @@ class RustPairIterator:
function_names = ["entries", "forEach", "keys", "values"]
+@dataclass
+class RustAsyncIterator:
+ """The value asynchronously iterable declaration of an interface, https://webidl.spec.whatwg.org/#idl-async-iterable,
+ whose asynchronous iterator initialization steps the implementation runs through its method
+ asynchronous_iterator_initialization_steps, and whose other steps it gives through its implementation of
+ AsyncIterable."""
+
+ parameters: List[OperationParameter]
+ # Whether the asynchronous iterator prototype object has a "return" method: [DefinesAsyncIteratorReturn].
+ defines_return: bool
+
+ function = "values_function"
+ method = "asynchronous_iterator_initialization_steps"
+
+ @property
+ def length(self) -> int:
+ return parameter_list_length(self.parameters)
+
+
@dataclass
class RustConstant:
name: str
@@ -193,6 +222,7 @@ class RustMembers:
stringifier: Optional[RustStringifier] = None
indexed_property_getter: Optional[RustIndexedPropertyGetter] = None
pair_iterator: Optional[RustPairIterator] = None
+ async_iterator: Optional[RustAsyncIterator] = None
constructors: List[RustConstructor] = field(default_factory=list)
constants: List[RustConstant] = field(default_factory=list)
# The regular attributes in the order of the IDL, as the prototype defines them: an attribute of `attributes`, or
@@ -218,6 +248,8 @@ class RustMembers:
names.append(self.indexed_property_getter.operation.operation.name)
if self.pair_iterator is not None:
names.extend(self.pair_iterator.function_names)
+ if self.async_iterator is not None:
+ names.append("values")
names.extend(constant.name for constant in self.constants)
return names
@@ -256,13 +288,19 @@ def rust_members(interface: Interface) -> RustMembers:
]
if any(special_operations):
fail("it has special operations other than an indexed property getter")
- if interface.async_iterable or interface.maplike or interface.setlike:
- fail("it is async iterable or a maplike or setlike")
+ if interface.maplike or interface.setlike:
+ fail("it is a maplike or setlike")
+ if interface.async_iterable is not None and interface.async_iterable.key_type is not None:
+ fail("it has a pair asynchronously iterable declaration")
has_value_iterator = interface.iterable is not None and interface.iterable.key_type is None
if interface.static_attributes:
fail("it has static attributes")
members = RustMembers()
+ if interface.async_iterable is not None:
+ members.async_iterator = RustAsyncIterator(
+ interface.async_iterable.parameters, "DefinesAsyncIteratorReturn" in interface.extended_attributes
+ )
if interface.iterable is not None and interface.iterable.key_type is not None:
members.pair_iterator = RustPairIterator(interface.iterable.key_type, interface.iterable.value_type)
diff --git a/Meta/Generators/libweb_bindings/rust_to_idl_value.py b/Meta/Generators/libweb_bindings/rust_to_idl_value.py
index 787a71d9533..6f51ff450fa 100644
--- a/Meta/Generators/libweb_bindings/rust_to_idl_value.py
+++ b/Meta/Generators/libweb_bindings/rust_to_idl_value.py
@@ -26,6 +26,7 @@ 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 inheriting_interfaces
from Generators.libweb_bindings.rust_types import is_named_union
+from Generators.libweb_bindings.rust_types import is_promise_type
from Generators.libweb_bindings.rust_types import is_sequence_of_cells
from Generators.libweb_bindings.rust_types import is_unnamed_union_of_cpp_interfaces
from Generators.libweb_bindings.rust_types import member_other_than_undefined
@@ -117,6 +118,8 @@ def rust_to_idl_value(
return f"to_boolean({value})"
if name == "any":
return f"ThrowCompletionOr::<Value>::Ok({value})"
+ if name == "object":
+ return f"to_object(vm, {value})"
if name in INTEGER_TYPES:
if "EnforceRange" in attributes:
return f"to_{name.replace(' ', '_')}_enforcing_range(vm, {value})"
@@ -141,6 +144,11 @@ def rust_to_idl_value(
enumeration = context.enumeration(idl_type)
if enumeration is not None:
return f"<{rust_enumeration_path(enumeration, context)}>::from_js(vm, {value})"
+ callback_function = context.callback_function(idl_type)
+ if callback_function is not None:
+ if is_promise_type(callback_function.return_type):
+ return f"PromiseCallbackFunction::from_js(vm, {value})"
+ return f"CallbackFunction::from_js(vm, {value})"
interface = rust_interface(idl_type, context)
if interface is not None:
if inheriting_interfaces(interface, context):
diff --git a/Meta/Generators/libweb_bindings/rust_types.py b/Meta/Generators/libweb_bindings/rust_types.py
index 4f6825422df..6dcd656b32c 100644
--- a/Meta/Generators/libweb_bindings/rust_types.py
+++ b/Meta/Generators/libweb_bindings/rust_types.py
@@ -377,6 +377,8 @@ def rust_type(idl_type: IDLType, context: GenerationContext, what: str, is_resul
if isinstance(idl_type, IDLParameterizedType):
if name == "sequence":
return f"Vec<{rust_type(idl_type.parameters[0], context, what, is_result)}>"
+ if name == "Promise" and is_result:
+ return "WebIdlPromise"
if name == "record":
key_type, value_type = idl_type.parameters
if key_type.name not in ("DOMString", "USVString"):
@@ -391,8 +393,13 @@ 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 context.callback_function(idl_type) is not None:
- return "Gc<FunctionObject>"
+ 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
+ # returns is a function that it created.
+ if is_result:
+ return "Gc<FunctionObject>"
+ return "PromiseCallbackFunction" if is_promise_type(callback_function.return_type) else "CallbackFunction"
interface = rust_interface(idl_type, context)
if interface is not None:
if inheriting_interfaces(interface, context) and not is_result:
@@ -425,14 +432,6 @@ def is_promise_type(idl_type: IDLType) -> bool:
return isinstance(idl_type, IDLParameterizedType) and idl_type.name == "Promise"
-def rust_result_type(idl_type: IDLType, context: GenerationContext, what: str) -> str:
- """The Rust type that the method of an operation returns. An operation that returns a promise type returns the
- promise object, which is the only place the Rust bindings handle a promise type in."""
- if is_promise_type(idl_type) and not idl_type.nullable:
- return "Gc<Object>"
- return rust_type(idl_type, context, what, is_result=True)
-
-
def holds_cells(
idl_type: IDLType, context: GenerationContext, enclosing_dictionary_names: FrozenSet[str] = frozenset()
) -> bool:
diff --git a/Meta/Generators/libweb_bindings/rust_usage.py b/Meta/Generators/libweb_bindings/rust_usage.py
index d175cd968d7..81cd157d995 100644
--- a/Meta/Generators/libweb_bindings/rust_usage.py
+++ b/Meta/Generators/libweb_bindings/rust_usage.py
@@ -102,6 +102,11 @@ class DefinitionUsage:
return [dictionary for dictionary in module.dictionaries if dictionary.name in self.cpp_dictionary_names]
def _collect_rust_dictionaries(self) -> None:
+ # NB: An implementation in Rust converts JS values to a dictionary marked [ImplementedIn=Rust] itself, as the
+ # constructor of ReadableStream converts its underlyingSource object to an UnderlyingSource.
+ for dictionary in self.context.dictionaries.values():
+ if dictionary.extended_attributes.get("ImplementedIn") == "Rust":
+ self._name_for_rust(IDLType(dictionary.name), from_js=True, to_js=False)
for module in self.context.modules:
interface = module.interface
if interface is None or not is_implemented_in_rust(interface):
@@ -124,6 +129,9 @@ class DefinitionUsage:
for constructor in members.constructors:
for parameter in constructor.constructor.parameters:
self._name_for_rust(parameter.type, from_js=True, to_js=False)
+ if members.async_iterator is not None:
+ for parameter in members.async_iterator.parameters:
+ self._name_for_rust(parameter.type, from_js=True, to_js=False)
def _name_for_rust(self, idl_type: IDLType, from_js: bool, to_js: bool) -> None:
if isinstance(idl_type, IDLUnionType):