Skip to content

Truly independent web browser

Meta+LibJS+LibWeb: Support the URL interfaces in the Rust bindings

Shannon Booth27b51c189542
diff --git a/Libraries/LibJS/Rust/src/api.rs b/Libraries/LibJS/Rust/src/api.rs
index 0be07108e71..1fb763d45f2 100644
--- a/Libraries/LibJS/Rust/src/api.rs
+++ b/Libraries/LibJS/Rust/src/api.rs
@@ -23,12 +23,12 @@ pub use crate::layout::host_class::JSHostClass;
pub use crate::layout::value::Value;
pub use crate::layout_forward::{RawNativeFunctionPointer, RawNativeFunctionResult};
pub use crate::raw_native;
-pub use crate::runtime::abstract_operations::get_function_realm;
+pub use crate::runtime::abstract_operations::{call, get_function_realm};
pub use crate::runtime::array::Array;
pub use crate::runtime::array_buffer::{
ArrayBuffer, DataBlock, Order as ArrayBufferOrder, Shared as ArrayBufferShared,
};
-pub use crate::runtime::completion::{Throw, ThrowCompletionOr};
+pub use crate::runtime::completion::{Must, Throw, ThrowCompletionOr};
pub use crate::runtime::data_view::{
DataView, DataViewWithBufferWitness, get_view_byte_length, is_view_out_of_bounds,
make_data_view_with_buffer_witness_record,
@@ -36,7 +36,7 @@ pub use crate::runtime::data_view::{
pub use crate::runtime::error::ErrorKind;
pub use crate::runtime::error_types::ErrorType;
pub use crate::runtime::intrinsics::Intrinsics;
-pub use crate::runtime::iterator::{get_iterator_from_method_impl, iterator_step_value};
+pub use crate::runtime::iterator::{create_iterator_result_object, get_iterator_from_method_impl, iterator_step_value};
pub use crate::runtime::native_function::RawNativeFunction;
pub use crate::runtime::object::Object;
pub use crate::runtime::primitive_string::PrimitiveString;
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs
index 1ae99ddd009..f6cff471959 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs
@@ -13,8 +13,8 @@ use std::borrow::Cow;
use ak::{Utf16String, Utf16StringUnits, convert_valid_utf16_to_utf8, utf8_length_from_valid_utf16};
use libjs_rust::api::{
- Array, ArrayBuffer, ArrayBufferOrder, DataView, ErrorKind, ErrorType, FunctionObject, Gc, Object, PrimitiveString,
- PropertyKey, Root, ThrowCompletionOr, Trace, TypedArrayBase, TypedArrayKind, Value, Vm,
+ Array, ArrayBuffer, ArrayBufferOrder, DataView, ErrorKind, ErrorType, FunctionObject, Gc, Must, Object,
+ PrimitiveString, PropertyKey, Root, ThrowCompletionOr, Trace, TypedArrayBase, TypedArrayKind, Value, Vm,
get_iterator_from_method_impl, get_view_byte_length, is_typed_array_out_of_bounds, is_view_out_of_bounds,
iterator_step_value, make_data_view_with_buffer_witness_record, make_typed_array_with_buffer_witness_record,
to_well_formed, typed_array_byte_length,
@@ -26,7 +26,7 @@ use crate::bindings::interface::{Interface, Ref, create_dictionary_object, wrap}
use crate::bindings::services::web_bindings_object_implements_interface;
/// A USVString, a string without lone surrogates. Its UTF-16 code units are always well-formed.
-#[derive(Clone)]
+#[derive(Clone, Eq, PartialEq)]
pub(crate) struct UsvString(Utf16String);
impl UsvString {
@@ -746,6 +746,60 @@ pub(crate) fn sequence_from_iterable<T>(
Ok(sequence)
}
+/// A JS value converted to an IDL record, https://webidl.spec.whatwg.org/#js-record, with the conversions of its keys
+/// and values. The entries are in a Vec in the order of the record, which hides cells from the collector, so their
+/// types hold none.
+pub(crate) fn record_from_js<K: PartialEq, V>(
+ vm: &Vm,
+ value: Value,
+ mut key_from_js: impl FnMut(Value) -> ThrowCompletionOr<K>,
+ mut value_from_js: impl FnMut(Value) -> ThrowCompletionOr<V>,
+) -> ThrowCompletionOr<Vec<(K, V)>> {
+ // 1. If O is not an Object, throw a TypeError.
+ if !value.is_object() {
+ return vm.throw_completion(ErrorKind::TypeError, ErrorType::NotAnObject, &[&value]);
+ }
+ let object = value.as_object();
+
+ // 2. Let result be a new empty instance of record<K, V>.
+ let mut result: Vec<(K, V)> = Vec::new();
+
+ // 3. Let keys be ? O.[[OwnPropertyKeys]]().
+ let keys = object.internal_own_property_keys(vm)?;
+
+ // 4. For each key of keys:
+ for index in 0..keys.len() {
+ let key = keys.get(index).expect("the index is in bounds");
+ let property_key = PropertyKey::from_value(vm, key).must();
+
+ // 1. Let desc be ? O.[[GetOwnProperty]](key).
+ let descriptor = object.internal_get_own_property(vm, &property_key)?;
+
+ // 2. If desc is not undefined and desc.[[Enumerable]] is true:
+ if !descriptor.is_some_and(|descriptor| descriptor.enumerable == Some(true)) {
+ continue;
+ }
+
+ // 1. Let typedKey be key converted to an IDL value of type K.
+ let typed_key = key_from_js(key)?;
+
+ // 2. Let value be ? Get(O, key).
+ let value = object.get(vm, &property_key)?;
+
+ // 3. Let typedValue be value converted to an IDL value of type V.
+ let typed_value = value_from_js(value)?;
+
+ // 4. Set result[typedKey] to typedValue.
+ match result.iter_mut().find(|(existing_key, _)| *existing_key == typed_key) {
+ Some(entry) => entry.1 = typed_value,
+ None => result.push((typed_key, typed_value)),
+ }
+ }
+
+ // 5. Return result.
+ Ok(result)
+}
+
/// The types of the IDL definitions that a JS value converts to, with the conversions that the generated bindings
/// write for them.
pub(crate) trait FromJs: Sized {
@@ -942,6 +996,26 @@ pub(crate) fn to_cpp_interface(
vm.throw_completion(ErrorKind::TypeError, ErrorType::NotAnObjectOfType, &[&name])
}
+/// A JS value converted to a union of interfaces that LibWeb implements in C++, which the values of their
+/// Web::Bindings::InterfaceName name, https://webidl.spec.whatwg.org/#js-union
+pub(crate) fn to_cpp_interface_in_union(
+ vm: &Vm,
+ value: Value,
+ interface_names: &[u16],
+) -> ThrowCompletionOr<CppInterface> {
+ // 5. If V is a platform object, then:
+ // 1. If types includes an interface type that V implements, then return the IDL value that is a reference to
+ // the object V.
+ if value.is_object()
+ && interface_names
+ .iter()
+ .any(|interface_name| implements_cpp_interface(value.as_object(), *interface_name))
+ {
+ return Ok(CppInterface(value.as_object()));
+ }
+ throw_no_union_types_matched(vm)
+}
+
/// https://webidl.spec.whatwg.org/#js-interface
impl ToJs for CppInterface {
fn to_js(self, _: &CallContext) -> ThrowCompletionOr<Value> {
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/iterable.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/iterable.rs
new file mode 100644
index 00000000000..54f7dcf700e
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/iterable.rs
@@ -0,0 +1,325 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The pair iterators of the interfaces implemented in Rust, https://webidl.spec.whatwg.org/#idl-iterable
+
+use core::cell::Cell;
+use core::ops::Deref;
+use core::ptr::NonNull;
+
+use libjs_rust::api::{
+ Array, Attribute, EmbedderCell, EmbedderClass, EmbedderValue, ErrorKind, ErrorType, Gc, HostObject, JSHostClass,
+ Object, PropertyAttributes, PropertyKey, RawNativeFunctionPointer, Realm, ThrowCompletionOr, Trace, Value, Vm,
+ call, create_iterator_result_object, host_data_of, is_host_instance_of,
+};
+
+use crate::bindings::CallContext;
+use crate::bindings::conversions::ToJs;
+use crate::bindings::interface::{Interface, Ref, define_operation, implementation_of, this_object};
+use crate::bindings::services::web_bindings_ensure_web_iterator_prototype;
+
+// https://webidl.spec.whatwg.org/#default-iterator-object-kind
+#[derive(Clone, Copy)]
+pub(crate) enum IterationKind {
+ Key,
+ Value,
+ KeyAndValue,
+}
+
+/// A default iterator object, https://webidl.spec.whatwg.org/#dfn-default-iterator-object, which is the host data of
+/// a host object of the iterator class of its interface.
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct DefaultIterator<T: Interface> {
+ target: Ref<T>,
+ #[gc(untraced)]
+ kind: IterationKind,
+ #[gc(untraced)]
+ index: Cell<usize>,
+}
+
+/// What the implementation of an interface with a pair iterator implements: its value pairs to iterate over, with
+/// the Rust types of the key and value types of the iterable declaration.
+pub(crate) trait PairIterable: Interface {
+ type Key: ToJs + Clone;
+ type Value: ToJs + Clone;
+
+ // https://webidl.spec.whatwg.org/#dfn-value-pairs-to-iterate-over
+ fn value_pairs_to_iterate_over(&self) -> impl Deref<Target = [(Self::Key, Self::Value)]> + '_;
+}
+
+/// What the generated bindings of an interface with a pair iterator define: the classes of its default iterator
+/// objects.
+pub(crate) trait DefaultIteratorClasses: PairIterable {
+ /// The class of the cells of the default iterator objects of the interface.
+ const ITERATOR_CELL_CLASS: &'static EmbedderClass<DefaultIterator<Self>>;
+
+ /// The class of the default iterator objects of the interface.
+ fn iterator_class() -> &'static JSHostClass;
+}
+
+impl<T: DefaultIteratorClasses> EmbedderValue for DefaultIterator<T> {
+ const CLASS: &'static EmbedderClass<Self> = T::ITERATOR_CELL_CLASS;
+}
+
+/// Defines the iteration methods of an interface with a pair iterator on its interface prototype object,
+/// https://webidl.spec.whatwg.org/#define-the-iteration-methods
+pub(crate) fn define_pair_iterator_properties(
+ vm: &Vm,
+ realm: Gc<Realm>,
+ prototype: Gc<Object>,
+ entries: RawNativeFunctionPointer,
+ for_each: RawNativeFunctionPointer,
+ keys: RawNativeFunctionPointer,
+ values: RawNativeFunctionPointer,
+) {
+ define_operation(vm, realm, prototype, "entries", entries, 0);
+ define_operation(vm, realm, prototype, "forEach", for_each, 1);
+ define_operation(vm, realm, prototype, "keys", keys, 0);
+ define_operation(vm, realm, prototype, "values", values, 0);
+
+ // https://webidl.spec.whatwg.org/#es-iterator
+ prototype.define_direct_property(
+ vm,
+ &PropertyKey::from(vm.well_known_symbols().iterator),
+ prototype.get_without_side_effects(vm, &vm.names.entries),
+ PropertyAttributes::new(Attribute::CONFIGURABLE | Attribute::WRITABLE),
+ );
+}
+
+/// A newly created default iterator object for the interface, with the object as its target, the kind, and index set
+/// to 0, in the realm of the call context.
+pub(crate) fn create_default_iterator<T: DefaultIteratorClasses>(
+ cx: &CallContext,
+ target: Ref<T>,
+ kind: IterationKind,
+) -> Value {
+ let vm = cx.vm();
+ let realm = cx.realm();
+ let iterator = T::ITERATOR_CELL_CLASS.allocate(
+ vm,
+ DefaultIterator {
+ target,
+ kind,
+ index: Cell::new(0),
+ },
+ );
+ // SAFETY: The realm is live, and the interface has a pair iterator.
+ 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::iterator_class(),
+ Some(Gc::from_non_null(prototype)),
+ None,
+ Some(iterator.as_non_null().cast()),
+ )
+ };
+ Value::from_object(object.upcast::<Object>())
+}
+
+/// The "next" method of the iterator prototype object of the interface,
+/// https://webidl.spec.whatwg.org/#es-iterator-prototype-object
+pub(crate) fn iterator_next<T: DefaultIteratorClasses>(vm: &Vm) -> ThrowCompletionOr<Value> {
+ // 1. Let interface be the interface for which the iterator prototype object exists.
+ // 2. Let thisValue be the this value.
+ // 3. Let object be ? ToObject(thisValue).
+ let object = vm.this_value().to_object(vm)?;
+
+ // 4. 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 iterator object is not a platform object.
+
+ // 5. If object is not a default iterator object for interface, then throw a TypeError.
+ let Some(iterator) = default_iterator_of::<T>(object) else {
+ let name = format!("{}Iterator", T::NAME);
+ return vm.throw_completion(ErrorKind::TypeError, ErrorType::NotAnObjectOfType, &[&name]);
+ };
+ let realm = object.shape().realm();
+
+ // 6. Let index be object's index.
+ let index = iterator.index.get();
+
+ // 7. Let kind be object's kind.
+ let kind = iterator.kind;
+
+ let pair = {
+ // 8. Let values be object's target's value pairs to iterate over.
+ let values = iterator.target.value_pairs_to_iterate_over();
+
+ // 9. Let len be the length of values.
+ let len = values.len();
+
+ // 10. If index is greater than or equal to len, then return CreateIteratorResultObject(undefined, true).
+ if index >= len {
+ return Ok(Value::from_object(create_iterator_result_object(
+ vm,
+ realm,
+ Value::UNDEFINED,
+ true,
+ )));
+ }
+
+ // 11. Let pair be the entry in values at index index.
+ values[index].clone()
+ };
+
+ // 12. Set object's index to index + 1.
+ iterator.index.set(index + 1);
+
+ // 13. Return the iterator result for pair and kind.
+ let cx = CallContext::new(vm, realm);
+ iterator_result(&cx, pair, kind)
+}
+
+fn default_iterator_of<T: DefaultIteratorClasses>(object: Gc<Object>) -> Option<Gc<EmbedderCell<DefaultIterator<T>>>> {
+ if !is_host_instance_of(&object, T::iterator_class()) {
+ return None;
+ }
+ let host_data = host_data_of(&object).expect("a default iterator object holds its cell");
+ // SAFETY: The object is a host object of the iterator class, whose host data is the cell of a default iterator.
+ unsafe { T::ITERATOR_CELL_CLASS.downcast(host_data) }
+}
+
+/// https://webidl.spec.whatwg.org/#iterator-result
+fn iterator_result<K: ToJs, V: ToJs>(cx: &CallContext, pair: (K, V), kind: IterationKind) -> ThrowCompletionOr<Value> {
+ let (key, value) = pair;
+ let result = match kind {
+ // 1. Let result be a value determined by the value of kind:
+ // -> "key"
+ // 1. Let idlKey be pair's key.
+ // 2. Let key be the result of converting idlKey to a JavaScript value.
+ // 3. result is key.
+ IterationKind::Key => key.to_js(cx)?,
+ // -> "value"
+ // 1. Let idlValue be pair's value.
+ // 2. Let value be the result of converting idlValue to a JavaScript value.
+ // 3. result is value.
+ IterationKind::Value => value.to_js(cx)?,
+ // -> "key+value"
+ // 1. Let idlKey be pair's key.
+ // 2. Let idlValue be pair's value.
+ // 3. Let key be the result of converting idlKey to a JavaScript value.
+ // 4. Let value be the result of converting idlValue to a JavaScript value.
+ // 5. Let array be ! ArrayCreate(2).
+ // 6. Perform ! CreateDataPropertyOrThrow(array, "0", key).
+ // 7. Perform ! CreateDataPropertyOrThrow(array, "1", value).
+ // 8. result is array.
+ IterationKind::KeyAndValue => {
+ let key = key.to_js(cx)?;
+ let value = value.to_js(cx)?;
+ Value::from_object(Array::create_from(cx.vm(), cx.realm(), &[key, value]).upcast::<Object>())
+ }
+ };
+
+ // 2. Return CreateIteratorResultObject(result, false).
+ Ok(Value::from_object(create_iterator_result_object(
+ cx.vm(),
+ cx.realm(),
+ result,
+ false,
+ )))
+}
+
+/// The steps of the %Symbol.iterator% and "entries" methods of the interface prototype object,
+/// https://webidl.spec.whatwg.org/#define-the-iteration-methods
+pub(crate) fn entries<T: DefaultIteratorClasses>(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.iterator%", and
+ // "method".
+ // 3. If jsValue does not implement definition, then throw a TypeError.
+ let (js_value, realm) = this_object(vm, T::wrapper_class(), T::NAME)?;
+
+ // 4. Return a newly created default iterator object for definition, with jsValue as its target, "key+value" as its
+ // kind, and index set to 0.
+ Ok(create_default_iterator(
+ &CallContext::new(vm, realm),
+ implementation_of::<T>(js_value),
+ IterationKind::KeyAndValue,
+ ))
+}
+
+/// The steps of the "keys" method of the interface prototype object,
+/// https://webidl.spec.whatwg.org/#define-the-iteration-methods
+pub(crate) fn keys<T: DefaultIteratorClasses>(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, "keys", and "method".
+ // 3. If jsValue does not implement definition, then throw a TypeError.
+ let (js_value, realm) = this_object(vm, T::wrapper_class(), T::NAME)?;
+
+ // 4. Return a newly created default iterator object for definition, with jsValue as its target, "key" as its kind,
+ // and index set to 0.
+ Ok(create_default_iterator(
+ &CallContext::new(vm, realm),
+ implementation_of::<T>(js_value),
+ IterationKind::Key,
+ ))
+}
+
+/// The steps of the "values" method of the interface prototype object,
+/// https://webidl.spec.whatwg.org/#define-the-iteration-methods
+pub(crate) fn values<T: DefaultIteratorClasses>(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, "values", and "method".
+ // 3. If jsValue does not implement definition, then throw a TypeError.
+ let (js_value, realm) = this_object(vm, T::wrapper_class(), T::NAME)?;
+
+ // 4. Return a newly created default iterator object for definition, with jsValue as its target, "value" as its
+ // kind, and index set to 0.
+ Ok(create_default_iterator(
+ &CallContext::new(vm, realm),
+ implementation_of::<T>(js_value),
+ IterationKind::Value,
+ ))
+}
+
+/// The steps of the "forEach" method of the interface prototype object,
+/// https://webidl.spec.whatwg.org/#define-the-iteration-methods
+pub(crate) fn for_each<T: DefaultIteratorClasses>(vm: &Vm) -> ThrowCompletionOr<Value> {
+ let callback = vm.argument(0);
+ let this_arg = vm.argument(1);
+
+ // 1. Let jsValue be ? ToObject(this value).
+ // 2. If jsValue is a platform object, then perform a security check, passing jsValue, "forEach", and "method".
+ // 3. If jsValue does not implement definition, then throw a TypeError.
+ let (js_value, realm) = this_object(vm, T::wrapper_class(), T::NAME)?;
+ let cx = CallContext::new(vm, realm);
+
+ // 4. Let idlCallback be callback, converted to a Function.
+ if !callback.is_function() {
+ return vm.throw_completion(ErrorKind::TypeError, ErrorType::NotAFunction, &[&callback]);
+ }
+
+ // 5. Let idlObject be the IDL interface type value that represents a reference to jsValue.
+ let idl_object = implementation_of::<T>(js_value);
+
+ // 6. Let pairs be idlObject's list of value pairs to iterate over.
+ // 7. Let i be 0.
+ let mut i = 0;
+
+ // 8. While i < pairs's size:
+ while i < idl_object.value_pairs_to_iterate_over().len() {
+ // 1. Let pair be pairs[i].
+ let (key, value) = idl_object.value_pairs_to_iterate_over()[i].clone();
+
+ // 2. Invoke idlCallback with « pair's value, pair's key, idlObject » and with thisArg as the callback this
+ // value.
+ let value = value.to_js(&cx)?;
+ let key = key.to_js(&cx)?;
+ call(vm, callback, this_arg, &[value, key, Value::from_object(js_value)])?;
+
+ // 3. Set pairs to idlObject's current list of value pairs to iterate over. (It might have changed.)
+ // 4. Set i to i + 1.
+ i += 1;
+ }
+
+ Ok(Value::UNDEFINED)
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/mod.rs
index 368f0ad332e..d12ede36115 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/mod.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/mod.rs
@@ -18,6 +18,7 @@ pub(crate) mod conversions;
#[cfg(web_idl_bindings)]
pub(crate) mod generated;
pub(crate) mod interface;
+pub(crate) mod iterable;
pub(crate) mod realm_data;
pub(crate) mod services;
pub(crate) mod structured_data;
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/services.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/services.rs
index b35482b4e67..b7d5f5c0a93 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/services.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/services.rs
@@ -18,6 +18,9 @@ unsafe extern "C" {
/// The interface object of the interface in the realm, likewise.
pub(crate) fn web_bindings_ensure_web_constructor(realm: *mut c_void, interface_name: u16) -> *mut c_void;
+ /// The iterator prototype object of the interface in the realm, likewise, for an interface with a pair iterator.
+ pub(crate) fn web_bindings_ensure_web_iterator_prototype(realm: *mut c_void, interface_name: u16) -> *mut c_void;
+
/// The wrapper world of the realm, a cell that the realm keeps alive, and whether it is the main world of its
/// agent.
pub(crate) fn web_bindings_wrapper_world(realm: *mut c_void, is_main_world: *mut bool) -> *mut c_void;
diff --git a/Meta/Generators/libweb_bindings/rust_bindings.py b/Meta/Generators/libweb_bindings/rust_bindings.py
index 56a041e7be9..4e96d05b077 100644
--- a/Meta/Generators/libweb_bindings/rust_bindings.py
+++ b/Meta/Generators/libweb_bindings/rust_bindings.py
@@ -17,9 +17,11 @@
import textwrap
from io import StringIO
+from typing import Callable
from typing import Dict
from typing import List
from typing import TextIO
+from typing import Tuple
from Generators.libweb_bindings.context import GenerationContext
from Generators.libweb_bindings.includes import GeneratedIncludes
@@ -30,6 +32,7 @@ from Generators.libweb_bindings.rust_members import RustConstructor
from Generators.libweb_bindings.rust_members import RustMembers
from Generators.libweb_bindings.rust_members import RustOperation
from Generators.libweb_bindings.rust_members import RustOperationSet
+from Generators.libweb_bindings.rust_members import RustPairIterator
from Generators.libweb_bindings.rust_members import rust_members
from Generators.libweb_bindings.rust_names import rust_identifier
from Generators.libweb_bindings.rust_names import rust_local_name
@@ -46,6 +49,7 @@ from Generators.libweb_bindings.rust_to_js_value import write_enumeration_to_js
from Generators.libweb_bindings.rust_to_js_value import write_union_to_js
from Generators.libweb_bindings.rust_types import UnsupportedByRustBindings
from Generators.libweb_bindings.rust_types import cpp_interface_name_constant
+from Generators.libweb_bindings.rust_types import holds_cells
from Generators.libweb_bindings.rust_types import inheriting_interfaces
from Generators.libweb_bindings.rust_types import is_implemented_in_rust
from Generators.libweb_bindings.rust_types import is_promise_type
@@ -92,6 +96,10 @@ def wrapper_host_class_symbol(interface: Interface) -> str:
return f"web_bindings_{wrapper_name(interface)}_host_class"
+def iterator_host_class_symbol(interface: Interface) -> str:
+ return f"web_bindings_{rust_module_name(interface)}_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."""
@@ -149,6 +157,18 @@ public:
"""
)
+ if rust_members(interface).pair_iterator is not None:
+ out.write(
+ f"""// The class of the default iterator objects of {interface.name}, whose cells the Rust bindings create.
+extern "C" JSHostClass const {iterator_host_class_symbol(interface)};
+
+struct {interface.name}IteratorPrototype {{
+public:
+ static void initialize(JS::Realm&, JS::Object&);
+}};
+
+"""
+ )
def write_cpp_implementation(
@@ -257,6 +277,21 @@ JS::ThrowCompletionOr<GC::Ref<JS::Object>> {interface.constructor_class}::constr
f' return constructor.vm().throw_completion<JS::TypeError>(JS::ErrorType::NotAConstructor, "{interface.name}");\n'
)
out.write("}\n\n")
+ if rust_members(interface).pair_iterator is not None:
+ initialize_iterator_prototype = rust_entry_point_name(interface, "initialize_iterator_prototype")
+ out.write(
+ f"""extern "C" void {initialize_iterator_prototype}(JSVM*, void* realm, JSObject* prototype);
+
+constexpr JSHostClass {iterator_host_class_symbol(interface)} = JS::make_host_class(JS_HOST_CLASS_OBJECT, "{interface.name}Iterator"sv,
+ nullptr, nullptr, nullptr, 0);
+
+void {interface.name}IteratorPrototype::initialize(JS::Realm& realm, JS::Object& object)
+{{
+ {initialize_iterator_prototype}(JS::HostABI::vm_to_abi(realm.vm()), &realm, JS::HostABI::object_to_abi(&object));
+}}
+
+"""
+ )
def write_ensure_web_prototype_declaration(out: TextIO) -> None:
@@ -266,53 +301,57 @@ def write_ensure_web_prototype_declaration(out: TextIO) -> None:
// Rust bindings.
extern "C" JSObject* web_bindings_ensure_web_prototype(void* realm, u16 interface_name);
extern "C" JSObject* web_bindings_ensure_web_constructor(void* realm, u16 interface_name);
+extern "C" JSObject* web_bindings_ensure_web_iterator_prototype(void* realm, u16 interface_name);
"""
)
def write_ensure_web_prototype_implementation(out: TextIO, intrinsics: List[Interface]) -> None:
- out.write(
- """
-JSObject* web_bindings_ensure_web_prototype(void* realm, u16 interface_name)
-{
- [[maybe_unused]] auto& js_realm = *static_cast<JS::Realm*>(realm);
- switch (static_cast<InterfaceName>(interface_name)) {
-"""
- )
- for interface in intrinsics:
- if not is_implemented_in_rust(interface):
- continue
+ rust_interfaces = [interface for interface in intrinsics if is_implemented_in_rust(interface)]
+
+ def write_switch(function: str, interfaces: List[Interface], object_of: Callable[[Interface], str]) -> None:
out.write(
- f""" case InterfaceName::{interface.name}:
- return JS::HostABI::object_to_abi(&ensure_web_prototype<{interface.prototype_class}>(js_realm, "{interface.namespaced_name}"_utf16_fly_string));
+ f"""
+JSObject* {function}(void* realm, u16 interface_name)
+{{
+ [[maybe_unused]] auto& js_realm = *static_cast<JS::Realm*>(realm);
+ switch (static_cast<InterfaceName>(interface_name)) {{
"""
)
- out.write(
- """ default:
- VERIFY_NOT_REACHED();
- }
-}
-
-JSObject* web_bindings_ensure_web_constructor(void* realm, u16 interface_name)
-{
- [[maybe_unused]] auto& js_realm = *static_cast<JS::Realm*>(realm);
- switch (static_cast<InterfaceName>(interface_name)) {
+ for interface in interfaces:
+ out.write(
+ f""" case InterfaceName::{interface.name}:
+ return JS::HostABI::object_to_abi(&{object_of(interface)});
"""
- )
- for interface in intrinsics:
- if not is_implemented_in_rust(interface):
- continue
+ )
out.write(
- f""" case InterfaceName::{interface.name}:
- return JS::HostABI::object_to_abi(&ensure_web_constructor<{interface.prototype_class}>(js_realm, "{interface.namespaced_name}"_utf16_fly_string));
-"""
- )
- out.write(
- """ default:
+ """ default:
VERIFY_NOT_REACHED();
}
}
"""
+ )
+
+ write_switch(
+ "web_bindings_ensure_web_prototype",
+ rust_interfaces,
+ lambda interface: (
+ f'ensure_web_prototype<{interface.prototype_class}>(js_realm, "{interface.namespaced_name}"_utf16_fly_string)'
+ ),
+ )
+ write_switch(
+ "web_bindings_ensure_web_constructor",
+ rust_interfaces,
+ lambda interface: (
+ f'ensure_web_constructor<{interface.prototype_class}>(js_realm, "{interface.namespaced_name}"_utf16_fly_string)'
+ ),
+ )
+ write_switch(
+ "web_bindings_ensure_web_iterator_prototype",
+ [interface for interface in rust_interfaces if rust_members(interface).pair_iterator is not None],
+ lambda interface: (
+ f'ensure_web_prototype<{interface.name}IteratorPrototype>(js_realm, "{interface.name}Iterator"_utf16_fly_string)'
+ ),
)
@@ -425,8 +464,14 @@ def implementation_method_signatures(
f"fn {overload.method}(&self, cx: &mut CallContext{parameters}) -> "
f"WebIdlResult<{rust_result_type(overload.operation.return_type, context, what)}>"
)
- if members.stringifier is not None:
+ if members.stringifier is not None and members.stringifier.defines_method:
signatures.append(f"fn {members.stringifier.method}(&self, cx: &mut CallContext) -> WebIdlResult<Utf16String>")
+ if members.pair_iterator is not None:
+ key_type, value_type = pair_iterator_types(context, interface, members.pair_iterator)
+ signatures.append(
+ 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.indexed_property_getter is not None:
getter = members.indexed_property_getter.operation
what = f"{interface.name}.{getter.operation.name}()"
@@ -446,6 +491,64 @@ def implementation_method_signatures(
return signatures
+def pair_iterator_types(
+ context: GenerationContext, interface: Interface, pair_iterator: RustPairIterator
+) -> Tuple[str, str]:
+ what = f"the pair iterator of {interface.name}"
+ for idl_type in (pair_iterator.key_type, pair_iterator.value_type):
+ if holds_cells(idl_type, context):
+ raise UnsupportedByRustBindings(
+ f"{interface.path}: {what} iterates over {idl_type}, a type whose values are or can hold cells, which "
+ "the Rust bindings do not handle yet"
+ )
+ return (
+ rust_type(pair_iterator.key_type, context, what, is_result=True),
+ rust_type(pair_iterator.value_type, context, what, is_result=True),
+ )
+
+
+def write_rust_pair_iterator(out: TextIO, interface: Interface) -> None:
+ """The classes of the default iterator objects of the interface, and the steps of its iterator prototype object,
+ which the bindings runtime implements for every interface with a pair iterator,
+ https://webidl.spec.whatwg.org/#es-iterator-prototype-object"""
+ out.write(
+ f"""
+ /// The class of the cells of the default iterator objects of the interface.
+ static ITERATOR_CELL_CLASS: EmbedderClass<DefaultIterator<Implementation>> = EmbedderClass::new("{interface.name} Iterator");
+
+ unsafe extern "C" {{
+ static {iterator_host_class_symbol(interface)}: JSHostClass;
+ }}
+
+ impl DefaultIteratorClasses for Implementation {{
+ const ITERATOR_CELL_CLASS: &'static EmbedderClass<DefaultIterator<Self>> = &ITERATOR_CELL_CLASS;
+
+ fn iterator_class() -> &'static JSHostClass {{
+ // SAFETY: LibWeb defines the class of the default iterator objects as constant data.
+ unsafe {{ &{iterator_host_class_symbol(interface)} }}
+ }}
+ }}
+
+ /// The steps of {interface.name}IteratorPrototype::initialize() of LibWeb's C++ bindings.
+ ///
+ /// # Safety
+ ///
+ /// The pointers must be the VM, a realm and the iterator prototype object of the realm.
+ #[unsafe(no_mangle)]
+ pub unsafe extern "C" fn {rust_entry_point_name(interface, "initialize_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_operation(vm, realm, prototype, "next", raw_native!(iterator_next::<Implementation>), 0);
+ define_to_string_tag(vm, prototype, "{interface.name} Iterator");
+ }}
+"""
+ )
+
+
def write_rust_interface(
out: TextIO, context: GenerationContext, module: Module, interface: Interface, interface_name_value: int
) -> None:
@@ -473,8 +576,9 @@ def write_rust_interface(
use crate::bindings::conversions::{{
ArrayBufferView, BufferSource, BufferSourceRules, CppInterface, EmptyDictionary, FromJs, ToJs, UsvString,
- implements_cpp_interface, record_to_js, rooted_sequence_to_js, sequence_from_js, sequence_to_js,
- to_array_buffer_view, to_boolean, to_buffer_source, to_cpp_interface, to_dom_string,
+ 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_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,
@@ -486,6 +590,10 @@ 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::iterable::{{
+ DefaultIterator, DefaultIteratorClasses, define_pair_iterator_properties, entries, for_each, iterator_next, keys,
+ values,
+ }};
use crate::bindings::structured_data;
use crate::bindings::{{CallContext, WebIdlResult}};
@@ -577,6 +685,9 @@ def write_rust_interface(
write_rust_operation(out, context, interface, getter_set.name, getter_set.function, getter)
write_rust_item_value(out, context, interface, getter)
+ if members.pair_iterator is not None:
+ write_rust_pair_iterator(out, interface)
+
for operation_set in members.static_operation_sets:
if len(operation_set.overloads) > 1:
raise UnsupportedByRustBindings(
@@ -646,6 +757,20 @@ def write_rust_interface(
defined_property_names.append(getter_set.name)
if members.indexed_property_getter.has_value_iterator:
out.write(" define_value_iterator_properties(vm, realm, prototype);\n")
+ if members.pair_iterator is not None:
+ out.write(
+ """ define_pair_iterator_properties(
+ vm,
+ realm,
+ prototype,
+ raw_native!(entries::<Implementation>),
+ raw_native!(for_each::<Implementation>),
+ raw_native!(keys::<Implementation>),
+ raw_native!(values::<Implementation>),
+ );
+"""
+ )
+ defined_property_names.extend(members.pair_iterator.function_names)
if members.constants:
out.write(" define_constants(vm, prototype, &CONSTANTS);\n")
defined_property_names.extend(constant.name for constant in members.constants)
@@ -1219,7 +1344,7 @@ pub(crate) mod definitions {
use crate::bindings::conversions::{
ArrayBufferView, BufferSource, BufferSourceRules, CppInterface, EmptyDictionary, FromJs, ToJs, UsvString,
dictionary_member, dictionary_object, enumeration_value_to_js, implements_cpp_interface, iterator_method,
- record_to_js, rooted_sequence_to_js, sequence_from_iterable, sequence_from_js, sequence_to_js,
+ record_from_js, record_to_js, rooted_sequence_to_js, sequence_from_iterable, sequence_from_js, sequence_to_js,
throw_no_union_types_matched, to_array_buffer_view, to_boolean, to_buffer_source, to_cpp_interface,
to_dom_string, to_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,
diff --git a/Meta/Generators/libweb_bindings/rust_members.py b/Meta/Generators/libweb_bindings/rust_members.py
index 12f44f9e6e2..0f8f1e69ae8 100644
--- a/Meta/Generators/libweb_bindings/rust_members.py
+++ b/Meta/Generators/libweb_bindings/rust_members.py
@@ -24,6 +24,7 @@ from Generators.libweb_bindings.rust_types import UnsupportedByRustBindings
from Generators.libweb_bindings.rust_types import idl_integer_value
from Utils.webidl_parser import Attribute
from Utils.webidl_parser import Constructor
+from Utils.webidl_parser import IDLType
from Utils.webidl_parser import Interface
from Utils.webidl_parser import Operation
@@ -117,15 +118,25 @@ class RustOperationSet:
@dataclass
class RustStringifier:
- """The stringifier of an interface, which the implementation runs through its method to_string,
- https://webidl.spec.whatwg.org/#es-stringifier"""
+ """The stringifier of an interface, https://webidl.spec.whatwg.org/#es-stringifier: an operation, which the
+ implementation runs through its method to_string, or an attribute, whose getter method it runs."""
# Whether only a Window has the stringifier.
is_window_only: bool
+ # The getter method of the attribute, for a stringifier that is an attribute.
+ attribute_getter_method: Optional[str] = None
- method = "to_string"
function = "to_string_function"
+ @property
+ def method(self) -> str:
+ return self.attribute_getter_method or "to_string"
+
+ @property
+ def defines_method(self) -> bool:
+ """Whether the implementation has a method for the stringifier of its own, rather than an attribute getter."""
+ return self.attribute_getter_method is None
+
@dataclass
class RustIndexedPropertyGetter:
@@ -139,6 +150,18 @@ class RustIndexedPropertyGetter:
has_value_iterator: bool
+@dataclass
+class RustPairIterator:
+ """The pair iterator of an interface, https://webidl.spec.whatwg.org/#dfn-pair-iterator, whose value pairs to
+ iterate over the implementation gives through its implementation of PairIterable."""
+
+ key_type: IDLType
+ value_type: IDLType
+
+ # The names of the functions that the interface prototype object holds, in the order of the C++ bindings.
+ function_names = ["entries", "forEach", "keys", "values"]
+
+
@dataclass
class RustConstant:
name: str
@@ -169,6 +192,7 @@ class RustMembers:
static_operation_sets: List[RustOperationSet] = field(default_factory=list)
stringifier: Optional[RustStringifier] = None
indexed_property_getter: Optional[RustIndexedPropertyGetter] = None
+ pair_iterator: Optional[RustPairIterator] = 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
@@ -192,6 +216,8 @@ class RustMembers:
names.append("toString")
if self.indexed_property_getter is not None:
names.append(self.indexed_property_getter.operation.operation.name)
+ if self.pair_iterator is not None:
+ names.extend(self.pair_iterator.function_names)
names.extend(constant.name for constant in self.constants)
return names
@@ -233,12 +259,12 @@ def rust_members(interface: Interface) -> RustMembers:
if interface.async_iterable or interface.maplike or interface.setlike:
fail("it is async iterable or a maplike or setlike")
has_value_iterator = interface.iterable is not None and interface.iterable.key_type is None
- if interface.iterable is not None and not has_value_iterator:
- fail("it declares a pair iterator, which the Rust bindings do not handle yet")
if interface.static_attributes:
fail("it has static attributes")
members = RustMembers()
+ 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)
getter = interface.indexed_property_getter
if has_value_iterator and getter is None:
@@ -265,14 +291,15 @@ def rust_members(interface: Interface) -> RustMembers:
if interface.stringifier is not None:
stringifier = interface.stringifier
- if stringifier.attribute is not None:
- fail("its stringifier is an attribute, which the Rust bindings do not handle yet")
check_extended_attributes(
"its stringifier", stringifier.extended_attributes, SUPPORTED_STRINGIFIER_EXTENDED_ATTRIBUTES
)
check_exposure("its stringifier", stringifier.extended_attributes)
+ attribute_getter_method = None
+ if stringifier.attribute is not None:
+ attribute_getter_method = method_of(stringifier.attribute.name, stringifier.attribute.extended_attributes)
members.stringifier = RustStringifier(
- stringifier.extended_attributes.get("Exposed") == SUPPORTED_MEMBER_EXPOSURE
+ stringifier.extended_attributes.get("Exposed") == SUPPORTED_MEMBER_EXPOSURE, attribute_getter_method
)
constructor_attributes = {"ImplementedAs"} if len(interface.constructors) > 1 else set()
@@ -374,7 +401,7 @@ def rust_members(interface: Interface) -> RustMembers:
for overload in operation_set.overloads
if not overload.is_default_to_json
)
- if members.stringifier is not None:
+ if members.stringifier is not None and members.stringifier.defines_method:
methods.append(members.stringifier.method)
if members.indexed_property_getter is not None:
methods.append(members.indexed_property_getter.operation.method)
diff --git a/Meta/Generators/libweb_bindings/rust_to_idl_value.py b/Meta/Generators/libweb_bindings/rust_to_idl_value.py
index 9f37fbad2b3..21647fdcda4 100644
--- a/Meta/Generators/libweb_bindings/rust_to_idl_value.py
+++ b/Meta/Generators/libweb_bindings/rust_to_idl_value.py
@@ -25,6 +25,7 @@ from Generators.libweb_bindings.rust_types import cpp_interface
from Generators.libweb_bindings.rust_types import cpp_interface_name_constant
from Generators.libweb_bindings.rust_types import holds_cells
from Generators.libweb_bindings.rust_types import is_named_union
+from Generators.libweb_bindings.rust_types import is_unnamed_union_of_cpp_interfaces
from Generators.libweb_bindings.rust_types import member_other_than_undefined
from Generators.libweb_bindings.rust_types import resolved_dictionary
from Generators.libweb_bindings.rust_types import runtime_union_type
@@ -89,6 +90,8 @@ def rust_to_idl_value(
if isinstance(idl_type, IDLParameterizedType) and idl_type.name == "sequence":
element = rust_sequence_element_to_idl_value(idl_type, identifier, context, what)
return f"sequence_from_js(vm, {value}, |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):
raise UnsupportedByRustBindings(
f"{what} has the type {idl_type}, which the Rust bindings do not convert to yet"
@@ -101,6 +104,8 @@ def rust_to_idl_value(
return f"to_usv_string(vm, {value})"
if name == "boolean":
return f"to_boolean({value})"
+ if name == "any":
+ return f"ThrowCompletionOr::<Value>::Ok({value})"
if name in INTEGER_TYPES:
if "EnforceRange" in attributes:
return f"to_{name.replace(' ', '_')}_enforcing_range(vm, {value})"
@@ -129,6 +134,12 @@ def rust_to_idl_value(
interface = cpp_interface(idl_type, context)
if interface is not None:
return f'to_cpp_interface(vm, {value}, {cpp_interface_name_constant(interface)}, "{interface.name}")'
+ if is_unnamed_union_of_cpp_interfaces(idl_type, context):
+ interface_names = ", ".join(
+ cpp_interface_name_constant(context.interfaces[member_type.name])
+ for member_type in idl_type.flattened_member_types()
+ )
+ return f"to_cpp_interface_in_union(vm, {value}, &[{interface_names}])"
dictionary = resolved_dictionary(idl_type, context)
if dictionary is not None:
return f"<{rust_dictionary_path(dictionary, context)}>::from_js(vm, {value})"
@@ -159,6 +170,22 @@ def rust_sequence_element_to_idl_value(
return rust_to_idl_value(element_type, {}, "value", identifier, context, what)
+def rust_record_to_idl_value(
+ record_type: IDLParameterizedType, value: str, identifier: str, context: GenerationContext, what: str
+) -> str:
+ """The conversion of the JS value to the record type."""
+ key_type, value_type = record_type.parameters
+ if holds_cells(value_type, context):
+ # NB: The entries are gathered in a Vec, which hides cells from the collector while the rest are converted.
+ raise UnsupportedByRustBindings(
+ f"{what} has the type {record_type}, a record of values that are or can hold cells, which the Rust "
+ "bindings do not convert to yet"
+ )
+ key = rust_to_idl_value(key_type, {}, "key", identifier, context, what)
+ record_value = rust_to_idl_value(value_type, {}, "value", identifier, context, what)
+ return f"record_from_js(vm, {value}, |key| {key}, |value| {record_value})"
+
+
@dataclass
class UnionMembers:
"""The members of a union by the kinds that the Rust bindings distinguish between when they convert a JS value to
@@ -168,6 +195,7 @@ class UnionMembers:
string_type: Optional[IDLType] = None
numeric_type: Optional[IDLType] = None
sequence_type: Optional[IDLParameterizedType] = None
+ record_type: Optional[IDLParameterizedType] = None
typed_array_types: List[IDLType] = field(default_factory=list)
# The interfaces, implemented in either language, in the order of the union.
interface_types: List[IDLType] = field(default_factory=list)
@@ -194,6 +222,12 @@ def union_members_by_kind(union_type: IDLUnionType, context: GenerationContext,
and members.sequence_type is None
):
members.sequence_type = member_type
+ elif (
+ isinstance(member_type, IDLParameterizedType)
+ and member_type.name == "record"
+ and members.record_type is None
+ ):
+ members.record_type = member_type
else:
raise UnsupportedByRustBindings(
f"{what} has the union type {union_type}, and the Rust bindings do not convert a JS value to a "
@@ -211,19 +245,27 @@ def rust_numeric_literal(literal: Optional[str], idl_type_name: str) -> Optional
return None
+def rust_string_literal(default_value: Optional[str], idl_type_name: str, what: str) -> Optional[str]:
+ """The Rust expression of a string of the IDL, if the default value is one, as a value of the string type."""
+ if idl_type_name not in STRING_TYPES or default_value is None or not default_value.startswith('"'):
+ return None
+ string = default_value[1:-1]
+ if not string.isascii() or "\\" in string:
+ raise UnsupportedByRustBindings(f"{what} has the default value {default_value}")
+ if idl_type_name == "USVString":
+ return f'UsvString::from_ascii(b"{string}")'
+ return f'Utf16String::from_ascii(b"{string}")'
+
+
def rust_default_value(
member: Union[OperationParameter, DictionaryMember], context: GenerationContext, what: str
) -> str:
"""An expression of the default value of the parameter or of the dictionary member."""
name = member.type.name
default_value = member.default_value
- if name in ("DOMString", "USVString") and default_value is not None and default_value.startswith('"'):
- string = default_value[1:-1]
- if not string.isascii() or "\\" in string:
- raise UnsupportedByRustBindings(f"{what} has the default value {default_value}")
- if name == "USVString":
- return f'UsvString::from_ascii(b"{string}")'
- return f'Utf16String::from_ascii(b"{string}")'
+ string_literal = rust_string_literal(default_value, name, what)
+ if string_literal is not None:
+ return string_literal
if name == "boolean" and default_value in ("true", "false"):
return default_value
numeric_literal = rust_numeric_literal(default_value, name)
@@ -248,6 +290,10 @@ def rust_default_value(
f"{union_path}::{rust_union_variant(dictionary_type)}"
f"(<{rust_dictionary_path(dictionary, context)}>::empty())"
)
+ string_type = union_members.string_type
+ string_literal = None if string_type is None else rust_string_literal(default_value, string_type.name, what)
+ if string_type is not None and string_literal is not None:
+ return f"{union_path}::{rust_union_variant(string_type)}({string_literal})"
# NB: A number is a value of the numeric member that the conversion to the union takes, as the C++ bindings
# take the default value of such a union to be.
numeric_type = union_members.numeric_type
@@ -381,7 +427,12 @@ def write_union_from_js(out: TextIO, context: GenerationContext, union_type: IDL
dictionary_conversion = (
f"Ok(Self::{rust_union_variant(dictionary_type)}(<{dictionary_path}>::from_js(vm, value)?))"
)
- if members.typed_array_types or members.sequence_type is not None or members.interface_types:
+ if (
+ members.typed_array_types
+ or members.sequence_type is not None
+ or members.record_type is not None
+ or members.interface_types
+ ):
if dictionary_conversion is not None:
steps.append(
f""" // 4. If V is null or undefined, then:
@@ -449,6 +500,14 @@ def write_union_from_js(out: TextIO, context: GenerationContext, union_type: IDL
f""" // 4. If types includes a dictionary type, then return the result of converting V to that
// dictionary type.
return {dictionary_conversion};
+"""
+ )
+ elif members.record_type is not None:
+ conversion = rust_record_to_idl_value(members.record_type, "value", "value", context, what)
+ steps.append(
+ f""" // 5. If types includes a record type, then return the result of converting V to that record
+ // type.
+ return Ok(Self::{rust_union_variant(members.record_type)}({conversion}?));
"""
)
steps.append(" }\n")
diff --git a/Meta/Generators/libweb_bindings/rust_types.py b/Meta/Generators/libweb_bindings/rust_types.py
index 778392b5777..5241e834ab6 100644
--- a/Meta/Generators/libweb_bindings/rust_types.py
+++ b/Meta/Generators/libweb_bindings/rust_types.py
@@ -201,6 +201,9 @@ def idl_type_name(idl_type: IDLType, what: str) -> str:
UnrestrictedDoubleSequence for sequence<unrestricted double>."""
if isinstance(idl_type, IDLUnionType):
name = "Or".join(idl_type_name(member_type, what) for member_type in idl_type.member_types)
+ elif isinstance(idl_type, IDLParameterizedType) and idl_type.name == "record":
+ key_type, value_type = idl_type.parameters
+ name = f"{idl_type_name(key_type, what)}{idl_type_name(value_type, what)}Record"
elif isinstance(idl_type, IDLParameterizedType):
if idl_type.name != "sequence":
raise UnsupportedByRustBindings(f"{what} has the type {idl_type}, which the Rust bindings have no name for")
@@ -291,9 +294,12 @@ def is_named_union(idl_type: IDLType, context: GenerationContext) -> bool:
def rust_union_variant(member_type: IDLType) -> str:
"""The variant of a member of a union in the enum of the union, which has the type name of the member, such as
- DOMString or UnrestrictedDouble. A union has at most one sequence type, whose variant is Sequence."""
+ DOMString or UnrestrictedDouble. A union has at most one sequence type and one record type, whose variants are
+ Sequence and Record."""
if isinstance(member_type, IDLParameterizedType) and member_type.name == "sequence":
return "Sequence"
+ if isinstance(member_type, IDLParameterizedType) and member_type.name == "record":
+ return "Record"
return idl_type_name(member_type, f"the union member {member_type}")