Truly independent web browser
Meta+LibJS+LibWeb: Convert views and sequences in the Rust bindings
Aliaksandr Kalenik4d127b1482a2
diff --git a/Libraries/LibJS/Rust/src/api.rs b/Libraries/LibJS/Rust/src/api.rsindex 8793562f111..5e23708f78e 100644--- a/Libraries/LibJS/Rust/src/api.rs+++ b/Libraries/LibJS/Rust/src/api.rs@@ -33,6 +33,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::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.rsindex 25638c0cda9..e4ae98d9add 100644--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs@@ -12,9 +12,10 @@ use core::mem::MaybeUninit;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, get_view_byte_length,- is_typed_array_out_of_bounds, is_view_out_of_bounds, make_data_view_with_buffer_witness_record,- make_typed_array_with_buffer_witness_record, to_well_formed, typed_array_byte_length,+ 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,};use crate::bindings::CallContext;@@ -106,6 +107,43 @@ pub(crate) fn to_usv_string(vm: &Vm, value: Value) -> ThrowCompletionOr<UsvStrinOk(UsvString(to_well_formed(&string)))}+/// The value of an enumeration that a JS value names, https://webidl.spec.whatwg.org/#js-enumeration: the index of+/// the string that the value converts to among the values of the enumeration, which are ASCII.+pub(crate) fn to_enumeration_value(+ vm: &Vm,+ value: Value,+ enumeration_name: &str,+ enumeration_values: &[&str],+) -> ThrowCompletionOr<usize> {+ // 1. Let S be the result of calling ? ToString(V).+ let string = value.to_utf16_string(vm)?;++ // 2. If S is not one of E's enumeration values, then throw a TypeError.+ // 3. Return the enumeration value of type E that is equal to S.+ let index = enumeration_values+ .iter()+ .position(|enumeration_value| match string.as_units() {+ Utf16StringUnits::Ascii(units) => units == enumeration_value.as_bytes(),+ Utf16StringUnits::Utf16(units) => units.iter().copied().eq(enumeration_value.bytes().map(u16::from)),+ });+ match index {+ Some(index) => Ok(index),+ None => vm.throw_completion(+ ErrorKind::TypeError,+ ErrorType::InvalidEnumerationValue,+ &[&string, &enumeration_name],+ ),+ }+}++/// A value of an enumeration converted to a JS value, https://webidl.spec.whatwg.org/#js-enumeration+pub(crate) fn enumeration_value_to_js(cx: &CallContext, enumeration_value: &str) -> Value {+ Value::from_string(PrimitiveString::create_from_ascii(+ cx.vm(),+ enumeration_value.as_bytes(),+ ))+}+/// A JS value converted to a boolean, https://webidl.spec.whatwg.org/#js-boolean#[expect(clippy::unnecessary_wraps,@@ -314,12 +352,29 @@ fn check_buffer_of_buffer_source(}/// An IDL BufferSource value, https://webidl.spec.whatwg.org/#BufferSource+#[derive(Clone, Copy)]pub(crate) enum BufferSource {ArrayBuffer(Gc<ArrayBuffer>),DataView(Gc<DataView>),TypedArray(Gc<TypedArrayBase>),}+/// An IDL ArrayBufferView value, https://webidl.spec.whatwg.org/#ArrayBufferView+#[derive(Clone, Copy)]+pub(crate) enum ArrayBufferView {+ DataView(Gc<DataView>),+ TypedArray(Gc<TypedArrayBase>),+}++impl From<ArrayBufferView> for BufferSource {+ fn from(view: ArrayBufferView) -> Self {+ match view {+ ArrayBufferView::DataView(view) => Self::DataView(view),+ ArrayBufferView::TypedArray(typed_array) => Self::TypedArray(typed_array),+ }+ }+}+impl BufferSource {/// Calls the function with the bytes that the buffer source holds, https://webidl.spec.whatwg.org/#dfn-get-buffer-source-copy,/// without copying them unless their buffer is shared. A detached buffer and a view that is out of bounds hold@@ -375,6 +430,17 @@ impl BufferSource {}}+impl ArrayBufferView {+ /// # Safety+ ///+ /// The function must not run script or allocate a cell, either of which could detach, resize or free the buffer+ /// that the bytes are in.+ pub(crate) unsafe fn with_bytes<R>(&self, function: impl FnOnce(&[u8]) -> R) -> R {+ // SAFETY: The caller keeps the function from running script and from allocating.+ unsafe { BufferSource::from(*self).with_bytes(function) }+ }+}+/// A JS value converted to a BufferSource, with the steps of the conversion to a union type that apply to the buffer/// source types, https://webidl.spec.whatwg.org/#js-unionpub(crate) fn to_buffer_source(vm: &Vm, value: Value, rules: &BufferSourceRules) -> ThrowCompletionOr<BufferSource> {@@ -410,10 +476,100 @@ pub(crate) fn to_buffer_source(vm: &Vm, value: Value, rules: &BufferSourceRules)}}+ // 19. Throw a TypeError.+ throw_no_union_types_matched(vm)+}++/// A JS value converted to an ArrayBufferView, with the steps of the conversion to a union type that apply to the+/// types of the views, https://webidl.spec.whatwg.org/#js-union+pub(crate) fn to_array_buffer_view(+ vm: &Vm,+ value: Value,+ rules: &BufferSourceRules,+) -> ThrowCompletionOr<ArrayBufferView> {+ if value.is_object() {+ let object = value.as_object();++ // 8. If V is an Object and V has a [[DataView]] internal slot, then:+ // 1. If types includes DataView, then return the result of converting V to DataView.+ if let Some(view) = object.downcast::<DataView>() {+ check_buffer_of_buffer_source(vm, &view.viewed_array_buffer(), "DataView", rules)?;+ return Ok(ArrayBufferView::DataView(view));+ }++ // 9. If V is an Object and V has a [[TypedArrayName]] internal slot, then:+ // 1. If types includes a typed array type whose name is the value of V's [[TypedArrayName]] internal slot,+ // then return the result of converting V to that type.+ if let Some(typed_array) = object.downcast::<TypedArrayBase>() {+ let type_name = format!("{:?}", typed_array.kind());+ check_buffer_of_buffer_source(vm, &typed_array.viewed_array_buffer(), &type_name, rules)?;+ return Ok(ArrayBufferView::TypedArray(typed_array));+ }+ }++ // 19. Throw a TypeError.+ throw_no_union_types_matched(vm)+}++/// The last step of the conversion of a JS value to a union type, https://webidl.spec.whatwg.org/#js-union, with+/// the message of the C++ bindings.+pub(crate) fn throw_no_union_types_matched<T>(vm: &Vm) -> ThrowCompletionOr<T> {// 19. Throw a TypeError.vm.throw_completion_with_message(ErrorKind::TypeError, "No union types matched".to_string())}+/// A JS value converted to an IDL sequence, https://webidl.spec.whatwg.org/#js-sequence, with the conversion of its+/// elements. The elements are in a Vec, which hides cells from the collector, so their type holds none.+pub(crate) fn sequence_from_js<T>(+ vm: &Vm,+ value: Value,+ element_from_js: impl FnMut(Value) -> ThrowCompletionOr<T>,+) -> ThrowCompletionOr<Vec<T>> {+ // 1. If V is not an Object, throw a TypeError.+ if !value.is_object() {+ return vm.throw_completion(ErrorKind::TypeError, ErrorType::NotAnObject, &[&value]);+ }++ // 2. Let method be ? GetMethod(V, %Symbol.iterator%).+ // 3. If method is undefined, throw a TypeError.+ let Some(method) = iterator_method(vm, value)? else {+ return vm.throw_completion(ErrorKind::TypeError, ErrorType::NotIterable, &[&value]);+ };++ // 4. Return the result of creating a sequence from V and method.+ sequence_from_iterable(vm, value, method, element_from_js)+}++/// ? GetMethod(V, %Symbol.iterator%), which decides whether a JS value converts to a sequence type.+pub(crate) fn iterator_method(vm: &Vm, value: Value) -> ThrowCompletionOr<Option<Gc<FunctionObject>>> {+ value.get_method(vm, &PropertyKey::from(vm.well_known_symbols().iterator))+}++/// An IDL sequence created from an iterable and its iterator getter method,+/// https://webidl.spec.whatwg.org/#create-sequence-from-iterable+pub(crate) fn sequence_from_iterable<T>(+ vm: &Vm,+ iterable: Value,+ method: Gc<FunctionObject>,+ mut element_from_js: impl FnMut(Value) -> ThrowCompletionOr<T>,+) -> ThrowCompletionOr<Vec<T>> {+ // 1. Let iteratorRecord be ? GetIteratorFromMethod(iterable, method).+ let iterator_record = get_iterator_from_method_impl(vm, iterable, method)?;++ // 2. Initialize i to be 0.+ // 3. Repeat+ let mut sequence = Vec::new();+ // 1. Let next be ? IteratorStepValue(iteratorRecord).+ // 2. If next is done, then return an IDL sequence value of type sequence<T> of length i, where the value of the+ // element at index j is Sj.+ while let Some(next) = iterator_step_value(vm, &iterator_record)? {+ // 3. Initialize Si to the result of converting next to an IDL value of type T.+ // 4. Set i to i + 1.+ sequence.push(element_from_js(next)?);+ }+ Ok(sequence)+}+/// 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 {diff --git a/Meta/Generators/libweb_bindings/rust_bindings.py b/Meta/Generators/libweb_bindings/rust_bindings.pyindex 5bc4656e72d..de4e7b8187e 100644--- a/Meta/Generators/libweb_bindings/rust_bindings.py+++ b/Meta/Generators/libweb_bindings/rust_bindings.py@@ -34,9 +34,11 @@ from Generators.libweb_bindings.rust_overloads import write_constructor_overloadfrom Generators.libweb_bindings.rust_to_idl_value import rust_default_valuefrom Generators.libweb_bindings.rust_to_idl_value import rust_to_idl_valuefrom Generators.libweb_bindings.rust_to_idl_value import write_dictionary_from_js+from Generators.libweb_bindings.rust_to_idl_value import write_enumeration_from_jsfrom Generators.libweb_bindings.rust_to_idl_value import write_union_from_jsfrom Generators.libweb_bindings.rust_to_js_value import rust_to_js_valuefrom Generators.libweb_bindings.rust_to_js_value import write_dictionary_to_js+from Generators.libweb_bindings.rust_to_js_value import write_enumeration_to_jsfrom Generators.libweb_bindings.rust_to_js_value import write_union_to_jsfrom Generators.libweb_bindings.rust_types import UnsupportedByRustBindingsfrom Generators.libweb_bindings.rust_types import inheriting_interfaces@@ -96,8 +98,8 @@ def check_interface_is_supported(interface: Interface, module: Module, context:fail("it is not a regular interface")if interface.parent_name and not is_implemented_in_rust(context.interfaces.get(interface.parent_name)):fail(f"it inherits from {interface.parent_name}, which is not implemented in Rust")- if module.enumerations or module.callback_functions:- fail("its module defines enumerations or callback functions")+ if module.callback_functions:+ fail("its module defines callback functions")for other in inheriting_interfaces(interface, context):if not is_implemented_in_rust(other):@@ -406,10 +408,10 @@ def write_rust_interface(}};use crate::bindings::conversions::{{- BufferSource, BufferSourceRules, EmptyDictionary, FromJs, ToJs, UsvString, record_to_js,- rooted_sequence_to_js, sequence_to_js, to_boolean, to_buffer_source, to_dom_string, to_float, to_long,- to_long_long, to_typed_array, to_unrestricted_double, to_unrestricted_float, to_unsigned_long,- to_unsigned_long_long, to_usv_string,+ ArrayBufferView, BufferSource, BufferSourceRules, EmptyDictionary, FromJs, ToJs, UsvString, record_to_js,+ rooted_sequence_to_js, sequence_from_js, sequence_to_js, to_array_buffer_view, to_boolean, to_buffer_source,+ to_dom_string, to_float, to_long, to_long_long, to_typed_array, to_unrestricted_double,+ to_unrestricted_float, to_unsigned_long, to_unsigned_long_long, to_usv_string,}};use crate::bindings::interface::{{Inherits, Interface, Ref, Wrapped, construct_arguments, construct_wrapper, define_attribute,@@ -660,6 +662,11 @@ def write_rust_attribute_setter(the this value is checked, and a missing value is undefined instead of an error."""name = attribute.attribute.namewhat = f"{interface.name}.{name}"+ if context.enumeration(attribute.attribute.type) is not None:+ # NB: The setter of such an attribute ignores a value that is not one of the enumeration's instead of throwing.+ raise UnsupportedByRustBindings(+ f"{what} is not read only and has an enumeration type, which the Rust bindings do not handle yet"+ )conversion = rust_to_idl_value(attribute.attribute.type, attribute.attribute.extended_attributes, "value", name, context, what)@@ -753,7 +760,7 @@ def write_rust_constructor(def write_rust_definitions(out: TextIO, context: GenerationContext, usage: DefinitionUsage) -> None:"""The conversions of the dictionaries and unions that the interfaces implemented in Rust name, each written once,whichever interfaces name it."""- if not usage.rust_dictionaries and not usage.rust_unions:+ if not usage.rust_dictionaries and not usage.rust_unions and not usage.rust_enumerations:returnout.write("""@@ -771,9 +778,11 @@ pub(crate) mod definitions {use crate::bindings::CallContext;use crate::bindings::conversions::{- BufferSource, BufferSourceRules, EmptyDictionary, FromJs, ToJs, UsvString, dictionary_member,- dictionary_object, record_to_js, rooted_sequence_to_js, sequence_to_js, to_boolean, to_buffer_source,- to_dom_string, to_float, to_long, to_long_long, to_typed_array, to_unrestricted_double,+ ArrayBufferView, BufferSource, BufferSourceRules, EmptyDictionary, FromJs, ToJs, UsvString,+ dictionary_member, dictionary_object, enumeration_value_to_js, iterator_method, record_to_js,+ rooted_sequence_to_js, sequence_from_iterable, sequence_from_js, sequence_to_js,+ throw_no_union_types_matched, to_array_buffer_view, to_boolean, to_buffer_source, to_dom_string,+ to_enumeration_value, to_float, to_long, to_long_long, to_typed_array, to_unrestricted_double,to_unrestricted_float, to_unsigned_long, to_unsigned_long_long, to_usv_string,};use crate::bindings::interface::{Ref, create_dictionary_object, set_dictionary_member, to_interface};@@ -789,6 +798,12 @@ pub(crate) mod definitions {write_dictionary_from_js(out, context, dictionary)if directions.to_js:write_dictionary_to_js(out, context, dictionary)+ for name, directions in usage.rust_enumerations.items():+ enumeration = context.enumerations[name]+ if directions.from_js:+ write_enumeration_from_js(out, context, enumeration)+ if directions.to_js:+ write_enumeration_to_js(out, context, enumeration)for union_type, directions in usage.rust_unions.items():if directions.from_js:write_union_from_js(out, context, union_type)diff --git a/Meta/Generators/libweb_bindings/rust_to_idl_value.py b/Meta/Generators/libweb_bindings/rust_to_idl_value.pyindex 27187c92ebb..0d71d2bb0e1 100644--- a/Meta/Generators/libweb_bindings/rust_to_idl_value.py+++ b/Meta/Generators/libweb_bindings/rust_to_idl_value.py@@ -6,6 +6,10 @@# Rust bindings of the interfaces implemented in Rust, as to_idl_value.py writes the C++ ones. The conversions run in# the order of the C++ bindings and throw their errors, so that an interface behaves the same in either language.+from dataclasses import dataclass+from dataclasses import field+from typing import List+from typing import Optionalfrom typing import TextIOfrom typing import Union@@ -17,11 +21,14 @@ from Generators.libweb_bindings.rust_types import FLOATING_POINT_TYPESfrom Generators.libweb_bindings.rust_types import INTEGER_TYPESfrom Generators.libweb_bindings.rust_types import TYPED_ARRAY_NAMESfrom Generators.libweb_bindings.rust_types import UnsupportedByRustBindings+from Generators.libweb_bindings.rust_types import holds_cellsfrom Generators.libweb_bindings.rust_types import is_named_unionfrom Generators.libweb_bindings.rust_types import member_other_than_undefinedfrom Generators.libweb_bindings.rust_types import resolved_dictionaryfrom Generators.libweb_bindings.rust_types import runtime_union_typefrom Generators.libweb_bindings.rust_types import rust_dictionary_path+from Generators.libweb_bindings.rust_types import rust_enumeration_path+from Generators.libweb_bindings.rust_types import rust_enumeration_variantfrom Generators.libweb_bindings.rust_types import rust_integer_literalfrom Generators.libweb_bindings.rust_types import rust_interfacefrom Generators.libweb_bindings.rust_types import rust_interface_path@@ -30,6 +37,7 @@ from Generators.libweb_bindings.rust_types import rust_union_pathfrom Generators.libweb_bindings.rust_types import rust_union_variantfrom Utils.webidl_parser import Dictionaryfrom Utils.webidl_parser import DictionaryMember+from Utils.webidl_parser import Enumerationfrom Utils.webidl_parser import IDLParameterizedTypefrom Utils.webidl_parser import IDLTypefrom Utils.webidl_parser import IDLUnionType@@ -67,6 +75,9 @@ def rust_to_idl_value()inner = rust_to_idl_value(inner_type, parameter_attributes, value, identifier, context, what)return f"if {value}.is_nullish() {{ Ok(None) }} else {{ {inner}.map(Some) }}"+ 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):raise UnsupportedByRustBindings(f"{what} has the type {idl_type}, which the Rust bindings do not convert to yet"@@ -90,6 +101,11 @@ def rust_to_idl_value(return f'to_typed_array(vm, {value}, TypedArrayKind::{name}, "{name}", {rules})'if runtime_union_type(idl_type, context) == "BufferSource":return f"to_buffer_source(vm, {value}, {buffer_source_rules(idl_type, parameter_attributes)})"+ if runtime_union_type(idl_type, context) == "ArrayBufferView":+ return f"to_array_buffer_view(vm, {value}, {buffer_source_rules(idl_type, parameter_attributes)})"+ enumeration = context.enumeration(idl_type)+ if enumeration is not None:+ return f"<{rust_enumeration_path(enumeration, context)}>::from_js(vm, {value})"interface = rust_interface(idl_type, context)if interface is not None:return f"to_interface::<{rust_interface_path(interface)}>(vm, {value})"@@ -98,26 +114,63 @@ def rust_to_idl_value(return f"<{rust_dictionary_path(dictionary, context)}>::from_js(vm, {value})"if isinstance(idl_type, IDLUnionType) and is_named_union(idl_type, context):union_members_by_kind(idl_type, context, what)+ # NB: The conversion of a named union is written once, for every parameter of its type.+ allowances = sorted(set(parameter_attributes) & {"AllowShared", "AllowResizable"})+ if allowances:+ raise UnsupportedByRustBindings(+ f"{what} has the extended attributes {allowances} on the union type {idl_type}, which the Rust "+ "bindings only handle on the members of the union"+ )return f"<{rust_union_path(idl_type, context, what)}>::from_js(vm, {value})"raise UnsupportedByRustBindings(f"{what} has the type {idl_type}, which the Rust bindings do not convert to yet")-def union_members_by_kind(union_type: IDLUnionType, context: GenerationContext, what: str):- """The dictionary type and the string type among the members of a union, which are the kinds of member that the- Rust bindings distinguish between when they convert a JS value to a union."""- dictionary_type = None- string_type = None+def rust_sequence_element_to_idl_value(+ sequence_type: IDLParameterizedType, identifier: str, context: GenerationContext, what: str+) -> str:+ """The conversion of the JS value `value` to an element of the sequence type."""+ element_type = sequence_type.parameters[0]+ if holds_cells(element_type, context):+ # NB: The elements are gathered in a Vec, which hides cells from the collector while the rest are converted.+ raise UnsupportedByRustBindings(+ f"{what} has the type {sequence_type}, a sequence of values that are or can hold cells, which the Rust "+ "bindings do not convert to yet"+ )+ return rust_to_idl_value(element_type, {}, "value", identifier, context, what)+++@dataclass+class UnionMembers:+ """The members of a union by the kinds that the Rust bindings distinguish between when they convert a JS value to+ the union."""++ dictionary_type: Optional[IDLType] = None+ string_type: Optional[IDLType] = None+ sequence_type: Optional[IDLParameterizedType] = None+ typed_array_types: List[IDLType] = field(default_factory=list)+++def union_members_by_kind(union_type: IDLUnionType, context: GenerationContext, what: str) -> UnionMembers:+ members = UnionMembers()for member_type in union_type.flattened_member_types():- if resolved_dictionary(member_type, context) is not None and dictionary_type is None:- dictionary_type = member_type- elif member_type.name in STRING_TYPES and string_type is None:- string_type = member_type+ if resolved_dictionary(member_type, context) is not None and members.dictionary_type is None:+ members.dictionary_type = member_type+ elif member_type.name in STRING_TYPES and members.string_type is None:+ members.string_type = member_type+ elif member_type.name in TYPED_ARRAY_NAMES:+ members.typed_array_types.append(member_type)+ elif (+ isinstance(member_type, IDLParameterizedType)+ and member_type.name == "sequence"+ and members.sequence_type is None+ ):+ members.sequence_type = member_typeelse:raise UnsupportedByRustBindings(f"{what} has the union type {union_type}, and the Rust bindings do not convert a JS value to a "f"union with the member {member_type} yet")- return dictionary_type, string_type+ return membersdef rust_default_value(@@ -146,8 +199,12 @@ def rust_default_value(# NB: The C++ bindings do not run the conversion for a missing argument either, so the members of the default# value are not read from a JS object.return f"<{rust_dictionary_path(dictionary, context)}>::empty()"+ enumeration = context.enumeration(member.type)+ if enumeration is not None and default_value is not None and default_value[1:-1] in enumeration.values:+ variant = rust_enumeration_variant(default_value[1:-1], enumeration)+ return f"{rust_enumeration_path(enumeration, context)}::{variant}"if isinstance(member.type, IDLUnionType) and is_named_union(member.type, context) and default_value == "{}":- dictionary_type, _ = union_members_by_kind(member.type, context, what)+ dictionary_type = union_members_by_kind(member.type, context, what).dictionary_typeif dictionary_type is not None:dictionary = context.dictionaries[dictionary_type.name]union_path = rust_union_path(member.type, context, what)@@ -228,15 +285,91 @@ def write_dictionary_from_js(out: TextIO, context: GenerationContext, dictionary)+def write_enumeration_from_js(out: TextIO, context: GenerationContext, enumeration: Enumeration) -> None:+ """The conversion of a JS value to the enum of an enumeration, which the module of its IDL file defines with a+ variant for each value, named as the C++ bindings name theirs."""+ values = ", ".join(f'"{value}"' for value in enumeration.values)+ arms = "".join(+ f" {index} => Self::{rust_enumeration_variant(value, enumeration)},\n"+ for index, value in enumerate(enumeration.values)+ )+ out.write(+ f"""+ /// The conversion of a JS value to the enumeration {enumeration.name},+ /// https://webidl.spec.whatwg.org/#js-enumeration+ impl FromJs for {rust_enumeration_path(enumeration, context)} {{+ fn from_js(vm: &Vm, value: Value) -> ThrowCompletionOr<Self> {{+ Ok(match to_enumeration_value(vm, value, "{enumeration.name}", &[{values}])? {{+{arms} _ => unreachable!("the value is one of the values of the enumeration"),+ }})+ }}+ }}+"""+ )++def write_union_from_js(out: TextIO, context: GenerationContext, union_type: IDLUnionType) -> None:"""The conversion of a JS value to the enum of a union, with the steps of https://webidl.spec.whatwg.org/#js-unionthat apply to its members, in the order of the C++ bindings."""what = f"the union {union_type}"path = rust_union_path(union_type, context, what)- dictionary_type, string_type = union_members_by_kind(union_type, context, what)+ members = union_members_by_kind(union_type, context, what)+ dictionary_type = members.dictionary_type+ string_type = members.string_typesteps = []+ dictionary_conversion = Noneif dictionary_type is not None:dictionary_path = rust_dictionary_path(context.dictionaries[dictionary_type.name], context)+ dictionary_conversion = (+ f"Ok(Self::{rust_union_variant(dictionary_type)}(<{dictionary_path}>::from_js(vm, value)?))"+ )+ if members.typed_array_types or members.sequence_type is not None:+ if dictionary_conversion is not None:+ steps.append(+ f""" // 3. If V is null or undefined, then:+ // 1. If types includes a dictionary type, then return the result of converting V to that+ // dictionary type.+ if value.is_nullish() {{+ return {dictionary_conversion};+ }}+"""+ )+ steps.append(" if value.is_object() {\n")+ for typed_array_type in members.typed_array_types:+ name = typed_array_type.name+ conversion = rust_to_idl_value(typed_array_type, {}, "value", "value", context, what)+ steps.append(+ f""" // 9. If V is an Object and V has a [[TypedArrayName]] internal slot, then:+ // 1. If types includes a typed array type whose name is the value of V's [[TypedArrayName]]+ // internal slot, then return the result of converting V to that type.+ let typed_array = value.as_object().downcast::<TypedArrayBase>();+ if typed_array.is_some_and(|typed_array| typed_array.kind() == TypedArrayKind::{name}) {{+ return Ok(Self::{rust_union_variant(typed_array_type)}({conversion}?));+ }}+"""+ )+ if members.sequence_type is not None:+ element = rust_sequence_element_to_idl_value(members.sequence_type, "value", context, what)+ steps.append(+ f""" // 11. If V is an Object, then:+ // 2. If types includes a sequence type, then:+ // 1. Let method be ? GetMethod(V, %Symbol.iterator%).+ // 2. If method is not undefined, return the result of creating a sequence of that type from+ // V and method.+ if let Some(method) = iterator_method(vm, value)? {{+ return Ok(Self::Sequence(sequence_from_iterable(vm, value, method, |value| {element})?));+ }}+"""+ )+ if dictionary_conversion is not None:+ steps.append(+ f""" // 4. If types includes a dictionary type, then return the result of converting V to that+ // dictionary type.+ return {dictionary_conversion};+"""+ )+ steps.append(" }\n")+ elif dictionary_conversion is not None:steps.append(f""" // 3. If V is null or undefined, then:// 1. If types includes a dictionary type, then return the result of converting V to that@@ -245,7 +378,7 @@ def write_union_from_js(out: TextIO, context: GenerationContext, union_type: IDL// 4. If types includes a dictionary type, then return the result of converting V to that// dictionary type.if value.is_nullish() || value.is_object() {{- return Ok(Self::{rust_union_variant(dictionary_type)}(<{dictionary_path}>::from_js(vm, value)?));+ return {dictionary_conversion};}}""")@@ -259,7 +392,7 @@ def write_union_from_js(out: TextIO, context: GenerationContext, union_type: IDLelse:steps.append(""" // 19. Throw a TypeError.- vm.throw_completion_with_message(ErrorKind::TypeError, "No union types matched".to_string())+ throw_no_union_types_matched(vm)""")out.write(diff --git a/Meta/Generators/libweb_bindings/rust_to_js_value.py b/Meta/Generators/libweb_bindings/rust_to_js_value.pyindex 066f31800d0..83abb54fe45 100644--- a/Meta/Generators/libweb_bindings/rust_to_js_value.py+++ b/Meta/Generators/libweb_bindings/rust_to_js_value.py@@ -12,13 +12,17 @@ from typing import TextIOfrom Generators.libweb_bindings.context import GenerationContextfrom Generators.libweb_bindings.rust_names import rust_identifierfrom Generators.libweb_bindings.rust_names import rust_local_name+from Generators.libweb_bindings.rust_types import UnsupportedByRustBindingsfrom Generators.libweb_bindings.rust_types import holds_cellsfrom Generators.libweb_bindings.rust_types import member_other_than_undefinedfrom Generators.libweb_bindings.rust_types import rust_dictionary_path+from Generators.libweb_bindings.rust_types import rust_enumeration_path+from Generators.libweb_bindings.rust_types import rust_enumeration_variantfrom Generators.libweb_bindings.rust_types import rust_typefrom Generators.libweb_bindings.rust_types import rust_union_pathfrom Generators.libweb_bindings.rust_types import rust_union_variantfrom Utils.webidl_parser import Dictionary+from Utils.webidl_parser import Enumerationfrom Utils.webidl_parser import IDLParameterizedTypefrom Utils.webidl_parser import IDLTypefrom Utils.webidl_parser import IDLUnionType@@ -54,10 +58,39 @@ def rust_to_js_value(function = "rooted_sequence_to_js" if holds_cells(element_type, context) else "sequence_to_js"return f"{function}({call_context}, {expression}, |value| {inner(element_type)})"if isinstance(idl_type, IDLParameterizedType) and idl_type.name == "record":- return f"record_to_js({call_context}, {expression}, |value| {inner(idl_type.parameters[1])})"+ value_type = idl_type.parameters[1]+ if holds_cells(value_type, context):+ # NB: The entries are in a Vec, which hides the values from the collector while those before them are+ # converted.+ raise UnsupportedByRustBindings(+ f"{what} has the type {idl_type}, a record of values that are or can hold cells, which the Rust "+ "bindings do not convert yet"+ )+ return f"record_to_js({call_context}, {expression}, |value| {inner(value_type)})"return f"{expression}.to_js({call_context})"+def write_enumeration_to_js(out: TextIO, context: GenerationContext, enumeration: Enumeration) -> None:+ """The conversion of the enum of an enumeration, which matches every variant, so that an enum that does not match+ the values of the enumeration does not compile."""+ arms = "".join(+ f' Self::{rust_enumeration_variant(value, enumeration)} => "{value}",\n'+ for value in enumeration.values+ )+ out.write(+ f"""+ /// The conversion of the enumeration {enumeration.name}, https://webidl.spec.whatwg.org/#js-enumeration+ impl ToJs for {rust_enumeration_path(enumeration, context)} {{+ fn to_js(self, cx: &CallContext) -> ThrowCompletionOr<Value> {{+ let enumeration_value = match self {{+{arms} }};+ Ok(enumeration_value_to_js(cx, enumeration_value))+ }}+ }}+"""+ )++def write_union_to_js(out: TextIO, context: GenerationContext, union_type: IDLUnionType) -> None:"""The conversion of the enum of a union, which the module of its typedef defines with a variant for each member,named as the type of the member and holding its IDL value."""@@ -81,6 +114,17 @@ def write_union_to_js(out: TextIO, context: GenerationContext, union_type: IDLUn)+def has_sequence_of_cells(idl_type: IDLType, context: GenerationContext) -> bool:+ """Whether the IDL values of the type have a sequence of values that are or can hold cells, however deep in the+ type the sequence is."""+ return any(+ isinstance(nested_type, IDLParameterizedType)+ and nested_type.name == "sequence"+ and holds_cells(nested_type, context)+ for nested_type in idl_type.nested_types()+ )++def write_dictionary_to_js(out: TextIO, context: GenerationContext, dictionary: Dictionary) -> None:"""The conversion of the dictionary's struct, which the implementation defines with a field per member: the typeof a required member or of one with a default value, and an Option of it otherwise. The fields are bound to locals@@ -92,6 +136,13 @@ def write_dictionary_to_js(out: TextIO, context: GenerationContext, dictionary:for member in dictionary.members:what = f"{dictionary.name}.{member.name}"member_type = rust_type(member.type, context, what)+ if has_sequence_of_cells(member.type, context):+ # NB: A sequence is kept alive from where its conversion starts, which is after the object of the+ # dictionary is created and the members before this one are converted.+ raise UnsupportedByRustBindings(+ f"{what} has the type {member.type}, with a sequence of values that are or can hold cells, which the "+ "Rust bindings do not convert from a member of a dictionary yet"+ )field = rust_identifier(member.name)local = rust_local_name(member.name)key = f"{rust_identifier(member.name).removeprefix('r#').rstrip('_').upper()}_KEY"diff --git a/Meta/Generators/libweb_bindings/rust_types.py b/Meta/Generators/libweb_bindings/rust_types.pyindex 26bd5631f80..f8fe4521b05 100644--- a/Meta/Generators/libweb_bindings/rust_types.py+++ b/Meta/Generators/libweb_bindings/rust_types.py@@ -8,12 +8,16 @@import refrom pathlib import Path+from typing import FrozenSet+from typing import Iterablefrom typing import Listfrom typing import Optionalfrom Generators.libweb_bindings.context import GenerationContext+from Utils.utils import string_to_cpp_enum_namefrom Utils.utils import title_case_to_snake_casefrom Utils.webidl_parser import Dictionary+from Utils.webidl_parser import Enumerationfrom Utils.webidl_parser import IDLParameterizedTypefrom Utils.webidl_parser import IDLTypefrom Utils.webidl_parser import IDLUnionType@@ -45,8 +49,19 @@ INTEGER_TYPES = {"long": "i32", "unsigned long": "u32", "long long": "i64", "uns# The floating point types, with the Rust type of their values.FLOATING_POINT_TYPES = {"float": "f32", "unrestricted float": "f32", "unrestricted double": "f64"}+# The types whose values are plain data, with the Rust type of their values. None of these Rust types is or holds a+# cell, which holds_cells() relies on.+PLAIN_DATA_TYPES = {+ "DOMString": "Utf16String",+ "USVString": "UsvString",+ "boolean": "bool",+ "undefined": "()",+ **INTEGER_TYPES,+ **FLOATING_POINT_TYPES,+}+# The unions that the bindings runtime has a type for, by the name of the typedef that names the union.-RUNTIME_UNION_TYPES = {"BufferSource": "BufferSource"}+RUNTIME_UNION_TYPES = {"ArrayBufferView": "ArrayBufferView", "BufferSource": "BufferSource"}DECIMAL_LITERAL = re.compile(r"-?[0-9]+(\.[0-9]+)?([eE][-+]?[0-9]+)?")@@ -183,10 +198,32 @@ 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 name of the type of the member."""+ """The variant of a member of a union in the enum of the union, which has the name of the type of the member. A+ union has at most one sequence type, whose variant is Sequence."""+ if isinstance(member_type, IDLParameterizedType) and member_type.name == "sequence":+ return "Sequence"return member_type.name.replace(" ", "")+def rust_enumeration_path(enumeration: Enumeration, context: GenerationContext) -> str:+ """The Rust path of the enum of an enumeration, which is in the module of the IDL file that defines the+ enumeration: crate::web_gl::web_gl_rendering_context::WebGLPowerPreference."""+ return f"{rust_module_path(enumeration.path)}::{enumeration.name}"+++def rust_enumeration_variant(value: str, enumeration: Enumeration) -> str:+ """The variant of a value of an enumeration in the enum of the enumeration, which the C++ bindings name the same+ way."""+ variant = string_to_cpp_enum_name(value)+ is_plain = value.isascii() and value.isprintable() and '"' not in value and "\\" not in value+ if not is_plain or not re.fullmatch(r"[A-Z][A-Za-z0-9]*", variant) or variant == "Self":+ raise UnsupportedByRustBindings(+ f"The value {value!r} of the enumeration {enumeration.name} has no name that the Rust bindings can give "+ "its variant"+ )+ return variant++def rust_union_path(idl_type: IDLUnionType, context: GenerationContext, what: str) -> str:"""The Rust path of the enum of a union, which is in the module of the IDL file whose typedef names the union:crate::url_pattern::url_pattern::URLPatternInput."""@@ -214,18 +251,8 @@ def rust_type(idl_type: IDLType, context: GenerationContext, what: str) -> str:raise UnsupportedByRustBindings(f"{what} has a record with keys of the type {key_type}")return f"Vec<({rust_type(key_type, context, what)}, {rust_type(value_type, context, what)})>"raise UnsupportedByRustBindings(f"{what} has the type {idl_type}, which the Rust bindings do not convert yet")- if name == "DOMString":- return "Utf16String"- if name == "USVString":- return "UsvString"- if name == "boolean":- return "bool"- if name in INTEGER_TYPES:- return INTEGER_TYPES[name]- if name in FLOATING_POINT_TYPES:- return FLOATING_POINT_TYPES[name]- if name == "undefined":- return "()"+ if name in PLAIN_DATA_TYPES:+ return PLAIN_DATA_TYPES[name]if name == "any":return "Value"if name == "object":@@ -246,6 +273,9 @@ def rust_type(idl_type: IDLType, context: GenerationContext, what: str) -> str:dictionary = resolved_dictionary(idl_type, context)if dictionary is not None:return rust_dictionary_path(dictionary, context)+ enumeration = context.enumeration(idl_type)+ if enumeration is not None:+ return rust_enumeration_path(enumeration, context)runtime_type = runtime_union_type(idl_type, context)if runtime_type is not None:return runtime_type@@ -271,15 +301,40 @@ def rust_result_type(idl_type: IDLType, context: GenerationContext, what: str) -return rust_type(idl_type, context, what)-def holds_cells(idl_type: IDLType, context: GenerationContext) -> bool:+def holds_cells(+ idl_type: IDLType, context: GenerationContext, enclosing_dictionary_names: FrozenSet[str] = frozenset()+) -> bool:"""Whether the Rust type of the IDL values of the type is or can hold a cell, which a Vec would hide from the- collector."""- idl_type = idl_type.without_nullable()- if isinstance(idl_type, (IDLParameterizedType, IDLUnionType)):+ collector. Only plain data, and what is made of nothing but plain data, holds none: a type that this function+ does not know holds one."""++ def any_holds_cells(idl_types: Iterable[IDLType]) -> bool:+ return any(holds_cells(inner_type, context, enclosing_dictionary_names) for inner_type in idl_types)++ if isinstance(idl_type, IDLUnionType):+ if runtime_union_type(idl_type, context) is not None:+ # NB: The bindings runtime defines the types of its unions by hand, so nothing checks them against the+ # members of the unions.+ return True+ return any_holds_cells(idl_type.flattened_member_types())+ if isinstance(idl_type, IDLParameterizedType):+ if idl_type.name in ("sequence", "record"):+ return any_holds_cells(idl_type.parameters)+ return True+ if idl_type.name in PLAIN_DATA_TYPES or context.enumeration(idl_type) is not None:return False- if idl_type.name in ("any", "object") or idl_type.name in TYPED_ARRAY_NAMES:+ dictionary = resolved_dictionary(idl_type, context)+ if dictionary is None:return True- return context.callback_function(idl_type) is not None or rust_interface(idl_type, context) is not None+ if dictionary.name in enclosing_dictionary_names:+ # NB: A dictionary that names itself, as it can through a sequence, holds a cell only if a member outside of+ # that cycle does.+ return False+ return any(+ holds_cells(member.type, context, enclosing_dictionary_names | {dictionary.name})+ for inherited_dictionary in context.dictionary_inheritance_stack(dictionary)+ for member in inherited_dictionary.members+ )def rust_parameter_type(parameter: OperationParameter, context: GenerationContext, what: str) -> str:diff --git a/Meta/Generators/libweb_bindings/rust_usage.py b/Meta/Generators/libweb_bindings/rust_usage.pyindex 8a8d28c3072..d9f88a73ba1 100644--- a/Meta/Generators/libweb_bindings/rust_usage.py+++ b/Meta/Generators/libweb_bindings/rust_usage.py@@ -75,6 +75,8 @@ class DefinitionUsage:self.rust_dictionaries: Dict[str, ConversionDirections] = {}# The unions that the interfaces implemented in Rust name and that have an enum of their own, by their type.self.rust_unions: Dict[IDLUnionType, ConversionDirections] = {}+ # The enumerations that the interfaces implemented in Rust name.+ self.rust_enumerations: Dict[str, ConversionDirections] = {}# The dictionaries that have a C++ representation.self.cpp_dictionary_names: Set[str] = set()self._collect_rust_dictionaries()@@ -118,6 +120,11 @@ class DefinitionUsage:returnfor child_type in idl_type.child_types():self._name_for_rust(child_type, from_js, to_js)+ if idl_type.name in self.context.enumerations:+ directions = self.rust_enumerations.setdefault(idl_type.name, ConversionDirections())+ directions.from_js = directions.from_js or from_js+ directions.to_js = directions.to_js or to_js+ returndictionary = self.context.dictionaries.get(idl_type.name)if dictionary is None:return