Truly independent web browser
Meta+LibJS+LibWeb: Convert dictionaries and buffers in Rust bindings
Aliaksandr Kalenika887f9895281
diff --git a/Libraries/LibJS/Rust/src/api.rs b/Libraries/LibJS/Rust/src/api.rsindex 95383ad7c09..8535ac19797 100644--- a/Libraries/LibJS/Rust/src/api.rs+++ b/Libraries/LibJS/Rust/src/api.rs@@ -25,6 +25,10 @@ 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::data_view::{+ DataView, DataViewWithBufferWitness, get_view_byte_length, is_view_out_of_bounds,+ make_data_view_with_buffer_witness_record,+};pub use crate::runtime::error::ErrorKind;pub use crate::runtime::error_types::ErrorType;pub use crate::runtime::intrinsics::Intrinsics;diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rsindex cf71d3b5b97..f7843afad00 100644--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs@@ -11,8 +11,10 @@ use core::mem::MaybeUninit;use ak::{Utf16String, Utf16StringUnits, convert_valid_utf16_to_utf8, utf8_length_from_valid_utf16};use libjs_rust::api::{- ErrorKind, ErrorType, Gc, PrimitiveString, ThrowCompletionOr, TypedArrayBase, TypedArrayKind, Value, Vm,- to_well_formed,+ ArrayBuffer, ArrayBufferOrder, DataView, ErrorKind, ErrorType, Gc, Object, PrimitiveString, PropertyKey,+ ThrowCompletionOr, 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,};use crate::bindings::CallContext;@@ -80,6 +82,18 @@ pub(crate) fn to_usv_string(vm: &Vm, value: Value) -> ThrowCompletionOr<UsvStrinOk(UsvString(to_well_formed(&string)))}+/// A JS value converted to a boolean, https://webidl.spec.whatwg.org/#js-boolean+#[expect(+ clippy::unnecessary_wraps,+ reason = "the generated bindings convert every type with an expression that can throw"+)]+pub(crate) fn to_boolean(value: Value) -> ThrowCompletionOr<bool> {+ // 1. Let x be the result of computing ToBoolean(V).+ // 2. Return the IDL boolean value that is the one that represents the same truth value as the JavaScript Boolean+ // value x.+ Ok(value.to_boolean())+}+/// A JS value converted to a float, https://webidl.spec.whatwg.org/#js-float////// The identifier is the name of the parameter or member that the value is of, which the error names.@@ -134,26 +148,179 @@ pub(crate) fn to_typed_array(let Some(typed_array) = typed_array else {return vm.throw_completion(ErrorKind::TypeError, ErrorType::NotAnObjectOfType, &[&name]);};- let buffer = typed_array.viewed_array_buffer();+ check_buffer_of_buffer_source(vm, &typed_array.viewed_array_buffer(), name, rules)?;++ // 5. Return the IDL value of type T that is a reference to the same object as V.+ Ok(typed_array)+}- // 3. If the conversion is not to an IDL type associated with the [AllowShared] extended attribute, and- // IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is true, then throw a TypeError.+/// The steps that the conversions to the buffer source types share, which check the buffer of the value against the+/// extended attributes of the type whose name is given.+fn check_buffer_of_buffer_source(+ vm: &Vm,+ buffer: &ArrayBuffer,+ type_name: &str,+ rules: &BufferSourceRules,+) -> ThrowCompletionOr<()> {+ // If the conversion is not to an IDL type associated with the [AllowShared] extended attribute, and+ // IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is true, then throw a TypeError.if !rules.allow_shared && buffer.is_shared_array_buffer() {return vm.throw_completion(ErrorKind::TypeError, ErrorType::SharedArrayBuffer, &[]);}- // 4. If the conversion is not to an IDL type associated with the [AllowResizable] extended attribute, and- // IsFixedLengthArrayBuffer(V.[[ViewedArrayBuffer]]) is false, then throw a TypeError.+ // If the conversion is not to an IDL type associated with the [AllowResizable] extended attribute, and+ // IsFixedLengthArrayBuffer(V.[[ViewedArrayBuffer]]) is false, then throw a TypeError.if !rules.allow_resizable && !buffer.is_fixed_length() {return vm.throw_completion(ErrorKind::TypeError,ErrorType::NotAnObjectOfType,- &[&format!("fixed-length {name}")],+ &[&format!("fixed-length {type_name}")],);}+ Ok(())+}- // 5. Return the IDL value of type T that is a reference to the same object as V.- Ok(typed_array)+/// An IDL BufferSource value, https://webidl.spec.whatwg.org/#BufferSource+pub(crate) enum BufferSource {+ ArrayBuffer(Gc<ArrayBuffer>),+ DataView(Gc<DataView>),+ TypedArray(Gc<TypedArrayBase>),+}++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+ /// no bytes.+ ///+ /// # 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 {+ let (buffer, offset, length) = match self {+ Self::TypedArray(typed_array) => {+ let record = make_typed_array_with_buffer_witness_record(typed_array, ArrayBufferOrder::SeqCst);+ // AD-HOC: The WebIDL spec has not been updated for resizable ArrayBuffer objects. This check follows+ // the behavior of step 7 of the TypedArray.prototype.buffer getter.+ if is_typed_array_out_of_bounds(&record) {+ return function(&[]);+ }+ let length = typed_array_byte_length(&record) as usize;+ (+ typed_array.viewed_array_buffer(),+ typed_array.byte_offset() as usize,+ length,+ )+ }+ Self::DataView(view) => {+ let record = make_data_view_with_buffer_witness_record(*view, ArrayBufferOrder::SeqCst);+ // AD-HOC: The WebIDL spec has not been updated for resizable ArrayBuffer objects. This check follows+ // the behavior of step 7 of the DataView.prototype.buffer getter.+ if is_view_out_of_bounds(&record) {+ return function(&[]);+ }+ let length = get_view_byte_length(&record) as usize;+ (view.viewed_array_buffer(), view.byte_offset() as usize, length)+ }+ Self::ArrayBuffer(buffer) => (*buffer, 0, buffer.byte_length()),+ };++ // 7. If IsDetachedBuffer(jsArrayBuffer) is true, then return the empty byte sequence.+ if buffer.is_detached() || length == 0 {+ return function(&[]);+ }++ // NB: Another thread can write the bytes of a shared buffer at any time, so the function gets a copy of them.+ if buffer.is_shared_array_buffer() {+ return function(&buffer.copy_to_byte_buffer(offset, length));+ }+ let bytes = buffer.with_data_block(|data_block| data_block.data_at(offset));+ assert!(!bytes.is_null());+ // SAFETY: The buffer is not detached and holds `length` bytes from `offset`, which nothing writes while the+ // function runs, as the buffer is not shared and the caller keeps script from running.+ function(unsafe { core::slice::from_raw_parts(bytes, length) })+ }+}++/// 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-union+pub(crate) fn to_buffer_source(vm: &Vm, value: Value, rules: &BufferSourceRules) -> ThrowCompletionOr<BufferSource> {+ if value.is_object() {+ let object = value.as_object();++ // 6. If V is an Object, V has an [[ArrayBufferData]] internal slot, and IsSharedArrayBuffer(V) is false, then:+ // 1. If types includes ArrayBuffer, then return the result of converting V to ArrayBuffer.+ if let Some(buffer) = object.downcast::<ArrayBuffer>()+ && !buffer.is_shared_array_buffer()+ {+ check_buffer_of_buffer_source(vm, &buffer, "ArrayBuffer", rules)?;+ return Ok(BufferSource::ArrayBuffer(buffer));+ }++ // FIXME: 7. If V is an Object, V has an [[ArrayBufferData]] internal slot, and IsSharedArrayBuffer(V) is true,+ // then:++ // 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(BufferSource::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(BufferSource::TypedArray(typed_array));+ }+ }++ // 19. Throw a TypeError.+ vm.throw_completion_with_message(ErrorKind::TypeError, "No union types matched".to_string())+}++/// 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 {+ fn from_js(vm: &Vm, value: Value) -> ThrowCompletionOr<Self>;+}++/// A dictionary without required members, which has a value that no JS value was converted to: the default value+/// `{}` of a parameter.+pub(crate) trait EmptyDictionary {+ fn empty() -> Self;+}++/// The object that the members of a dictionary are read from, step 1 of https://webidl.spec.whatwg.org/#js-dictionary.+/// It is None for undefined and null, which convert to a dictionary without reading a member.+pub(crate) fn dictionary_object(vm: &Vm, value: Value, dictionary_name: &str) -> ThrowCompletionOr<Option<Gc<Object>>> {+ // 1. If V is not Undefined, Null, or an Object, then throw a TypeError.+ if value.is_object() {+ return Ok(Some(value.as_object()));+ }+ if value.is_nullish() {+ return Ok(None);+ }+ vm.throw_completion(ErrorKind::TypeError, ErrorType::NotAnObjectOfType, &[&dictionary_name])+}++/// The value of a member of a dictionary, if the object it is read from has one that is not undefined, steps 4.1.2+/// and 4.1.3 of https://webidl.spec.whatwg.org/#js-dictionary+pub(crate) fn dictionary_member(+ vm: &Vm,+ object: Option<Gc<Object>>,+ key: &PropertyKey,+) -> ThrowCompletionOr<Option<Value>> {+ // 2. If V is Undefined or Null, then let jsMemberValue be undefined.+ let Some(object) = object else {+ return Ok(None);+ };++ // 3. Otherwise, let jsMemberValue be ? Get(V, key).+ let value = object.get(vm, key)?;+ Ok((!value.is_undefined()).then_some(value))}/// An IDL value converted to a JS value, https://webidl.spec.whatwg.org/#js-type-mappingdiff --git a/Meta/CMake/libweb_generators.cmake b/Meta/CMake/libweb_generators.cmakeindex 99d6d25e4df..29f6b3ffa42 100644--- a/Meta/CMake/libweb_generators.cmake+++ b/Meta/CMake/libweb_generators.cmake@@ -314,6 +314,7 @@ function (generate_js_bindings target)"${LADYBIRD_SOURCE_DIR}/Meta/Generators/libweb_bindings/realms.py""${LADYBIRD_SOURCE_DIR}/Meta/Generators/libweb_bindings/rust_bindings.py""${LADYBIRD_SOURCE_DIR}/Meta/Generators/libweb_bindings/rust_names.py"+ "${LADYBIRD_SOURCE_DIR}/Meta/Generators/libweb_bindings/rust_to_idl_value.py""${LADYBIRD_SOURCE_DIR}/Meta/Generators/libweb_bindings/rust_to_js_value.py""${LADYBIRD_SOURCE_DIR}/Meta/Generators/libweb_bindings/rust_types.py""${LADYBIRD_SOURCE_DIR}/Meta/Generators/libweb_bindings/rust_usage.py"diff --git a/Meta/Generators/libweb_bindings/rust_bindings.py b/Meta/Generators/libweb_bindings/rust_bindings.pyindex 07b9097df4e..d57910817b0 100644--- a/Meta/Generators/libweb_bindings/rust_bindings.py+++ b/Meta/Generators/libweb_bindings/rust_bindings.py@@ -26,11 +26,12 @@ from Generators.libweb_bindings.overload_resolution import operation_overload_sefrom Generators.libweb_bindings.overload_resolution import parameter_list_lengthfrom Generators.libweb_bindings.rust_names import rust_identifierfrom Generators.libweb_bindings.rust_names import rust_local_name+from Generators.libweb_bindings.rust_to_idl_value import rust_default_value+from Generators.libweb_bindings.rust_to_idl_value import rust_to_idl_value+from Generators.libweb_bindings.rust_to_idl_value import write_dictionary_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_jsfrom Generators.libweb_bindings.rust_types import UnsupportedByRustBindings-from Generators.libweb_bindings.rust_types import rust_conversion_to_idl_value-from Generators.libweb_bindings.rust_types import rust_default_valuefrom Generators.libweb_bindings.rust_types import rust_module_pathfrom Generators.libweb_bindings.rust_types import rust_parameter_typefrom Generators.libweb_bindings.rust_types import rust_type@@ -315,7 +316,7 @@ def write_parameter_conversions(if unsupported:raise UnsupportedByRustBindings(f"{parameter_what} has the extended attributes {sorted(unsupported)}")name = rust_local_name(parameter.name)- conversion = rust_conversion_to_idl_value(+ conversion = rust_to_idl_value(parameter.type, parameter.extended_attributes, f"argument{index}", parameter.name, context, parameter_what)out.write(f" let argument{index} = vm.argument({index});\n")@@ -393,7 +394,8 @@ def write_rust_interface(}};use crate::bindings::conversions::{{- BufferSourceRules, ToJs, UsvString, to_dom_string, to_float, to_typed_array, to_usv_string,+ BufferSource, BufferSourceRules, EmptyDictionary, FromJs, ToJs, UsvString, to_boolean, to_buffer_source,+ to_dom_string, to_float, to_typed_array, to_usv_string,}};use crate::bindings::interface::{{construct_arguments, create_wrapper, define_attribute, define_interface_object_properties, define_operation,@@ -590,10 +592,15 @@ pub(crate) mod definitions {use std::sync::LazyLock;use ak::Utf16String;- use libjs_rust::api::{ErrorKind, ErrorType, Gc, Object, PropertyKey, ThrowCompletionOr, Value, Vm};+ use libjs_rust::api::{+ ErrorKind, ErrorType, Gc, Object, PropertyKey, ThrowCompletionOr, TypedArrayBase, TypedArrayKind, Value, Vm,+ };use crate::bindings::CallContext;- use crate::bindings::conversions::{ToJs, UsvString};+ use crate::bindings::conversions::{+ BufferSource, BufferSourceRules, EmptyDictionary, FromJs, ToJs, UsvString, dictionary_member,+ dictionary_object, to_boolean, to_buffer_source, to_dom_string, to_float, to_typed_array, to_usv_string,+ };use crate::bindings::interface::{create_dictionary_object, set_dictionary_member};""")@@ -604,9 +611,7 @@ pub(crate) mod definitions {f"The Rust bindings convert the dictionary {name}, which inherits from another dictionary")if directions.from_js:- raise UnsupportedByRustBindings(- f"The Rust bindings do not convert the dictionary {name} from a JS value yet"- )+ write_dictionary_from_js(out, context, dictionary)if directions.to_js:write_dictionary_to_js(out, context, dictionary)out.write("}\n")diff --git a/Meta/Generators/libweb_bindings/rust_to_idl_value.py b/Meta/Generators/libweb_bindings/rust_to_idl_value.pynew file mode 100644index 00000000000..62cae6ea0e4--- /dev/null+++ b/Meta/Generators/libweb_bindings/rust_to_idl_value.py@@ -0,0 +1,159 @@+# Copyright (c) 2026-present, the Ladybird developers.+#+# SPDX-License-Identifier: BSD-2-Clause++# The Rust expressions that convert JS values to IDL values, https://webidl.spec.whatwg.org/#js-type-mapping, for the+# 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 typing import TextIO+from typing import Union++from Generators.libweb_bindings.context import GenerationContext+from Generators.libweb_bindings.rust_names import rust_identifier+from Generators.libweb_bindings.rust_names import rust_local_name+from Generators.libweb_bindings.rust_types import DECIMAL_LITERAL+from Generators.libweb_bindings.rust_types import FLOATING_POINT_TYPES+from Generators.libweb_bindings.rust_types import TYPED_ARRAY_NAMES+from Generators.libweb_bindings.rust_types import UnsupportedByRustBindings+from Generators.libweb_bindings.rust_types import resolved_dictionary+from Generators.libweb_bindings.rust_types import runtime_union_type+from Generators.libweb_bindings.rust_types import rust_dictionary_path+from Generators.libweb_bindings.rust_types import rust_type+from Utils.webidl_parser import Dictionary+from Utils.webidl_parser import DictionaryMember+from Utils.webidl_parser import IDLType+from Utils.webidl_parser import OperationParameter+++def buffer_source_rules(idl_type: IDLType, parameter_attributes: dict[str, str]) -> str:+ attributes = {**idl_type.extended_attributes, **parameter_attributes}+ allow_shared = "true" if "AllowShared" in attributes else "false"+ allow_resizable = "true" if "AllowResizable" in attributes else "false"+ return f"&BufferSourceRules {{ allow_shared: {allow_shared}, allow_resizable: {allow_resizable} }}"+++def rust_to_idl_value(+ idl_type: IDLType,+ parameter_attributes: dict[str, str],+ value: str,+ identifier: str,+ context: GenerationContext,+ what: str,+) -> str:+ """An expression of type ThrowCompletionOr<T> that converts the JS value to the IDL value. The identifier is the+ name of the parameter or member that the value is of, which the errors of some conversions name."""+ rust_type(idl_type, context, what)+ name = idl_type.name+ if name == "DOMString":+ return f"to_dom_string(vm, {value})"+ if name == "USVString":+ return f"to_usv_string(vm, {value})"+ if name == "boolean":+ return f"to_boolean({value})"+ if name == "float":+ return f'to_float(vm, {value}, "{identifier}")'+ if name in TYPED_ARRAY_NAMES:+ rules = buffer_source_rules(idl_type, parameter_attributes)+ 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)})"+ dictionary = resolved_dictionary(idl_type, context)+ if dictionary is not None:+ return f"<{rust_dictionary_path(dictionary, context)}>::from_js(vm, {value})"+ raise UnsupportedByRustBindings(f"{what} has the type {idl_type}, which the Rust bindings do not convert to yet")+++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}")'+ if name == "boolean" and default_value in ("true", "false"):+ return default_value+ if name in FLOATING_POINT_TYPES and default_value is not None and DECIMAL_LITERAL.fullmatch(default_value):+ return f"{default_value}_{FLOATING_POINT_TYPES[name]}"+ dictionary = resolved_dictionary(member.type, context)+ if dictionary is not None and default_value == "{}":+ # NB: The C++ bindings do not run the conversion for a missing argument either, so the members of the default+ # value are not read from a JS object.+ return f"<{rust_dictionary_path(dictionary, context)}>::empty()"+ raise UnsupportedByRustBindings(+ f"{what} has the default value {default_value}, which the Rust bindings do not have"+ )+++def dictionary_can_be_empty(dictionary: Dictionary) -> bool:+ return not any(member.required for member in dictionary.members)+++def write_dictionary_from_js(out: TextIO, context: GenerationContext, dictionary: Dictionary) -> None:+ """The conversion of a JS value to the dictionary's struct, which reads the members in the order of the C+++ bindings, the lexicographical one that the parser puts them in. The struct is built by naming every field, so that+ one that does not match the members of the dictionary does not compile."""+ path = rust_dictionary_path(dictionary, context)+ keys = []+ conversions = []+ empty_fields = []+ for member in dictionary.members:+ what = f"{dictionary.name}.{member.name}"+ local = rust_local_name(member.name)+ key = f"{rust_identifier(member.name).removeprefix('r#').rstrip('_').upper()}_KEY"+ keys.append(+ f' static {key}: LazyLock<PropertyKey> = LazyLock::new(|| PropertyKey::from_utf8("{member.name}"));\n'+ )+ conversion = rust_to_idl_value(member.type, member.extended_attributes, "member", member.name, context, what)+ if member.required:+ missing = f"""return vm.throw_completion(+ ErrorKind::TypeError,+ ErrorType::MissingRequiredProperty,+ &[&"{member.name}"],+ )"""+ present = f"{conversion}?"+ elif member.default_value is not None:+ missing = rust_default_value(member, context, what)+ present = f"{conversion}?"+ empty_fields.append(f"{rust_identifier(member.name)}: {missing}")+ else:+ missing = "None"+ present = f"Some({conversion}?)"+ empty_fields.append(f"{rust_identifier(member.name)}: None")+ conversions.append(+ f""" let {local} = match dictionary_member(vm, object, &{key})? {{+ Some(member) => {present},+ None => {missing},+ }};+"""+ )+ fields = ", ".join(+ f"{rust_identifier(member.name)}: {rust_local_name(member.name)}" for member in dictionary.members+ )+ out.write(+ f"""+ /// The conversion of a JS value to the dictionary {dictionary.name}, https://webidl.spec.whatwg.org/#js-dictionary+ impl FromJs for {path} {{+ fn from_js(vm: &Vm, value: Value) -> ThrowCompletionOr<Self> {{+{"".join(keys)} let object = dictionary_object(vm, value, "{dictionary.name}")?;+{"".join(conversions)} Ok(Self {{ {fields} }})+ }}+ }}+"""+ )+ if dictionary_can_be_empty(dictionary):+ out.write(+ f"""+ impl EmptyDictionary for {path} {{+ fn empty() -> Self {{+ Self {{ {", ".join(empty_fields)} }}+ }}+ }}+"""+ )diff --git a/Meta/Generators/libweb_bindings/rust_types.py b/Meta/Generators/libweb_bindings/rust_types.pyindex 77c6def3ce0..6df5d0ee3a2 100644--- a/Meta/Generators/libweb_bindings/rust_types.py+++ b/Meta/Generators/libweb_bindings/rust_types.py@@ -2,8 +2,8 @@## SPDX-License-Identifier: BSD-2-Clause-# The Rust types of IDL values, and the Rust expressions that convert JS values to them, for the Rust bindings of the-# interfaces implemented in Rust. They cover the types that those interfaces use so far; every other type is an error.+# The Rust types of IDL values, for the Rust bindings of the interfaces implemented in Rust. They cover the types that+# those interfaces use so far; every other type is an error.import re@@ -14,6 +14,7 @@ from Generators.libweb_bindings.context import GenerationContextfrom Utils.utils import title_case_to_snake_casefrom Utils.webidl_parser import Dictionaryfrom Utils.webidl_parser import IDLType+from Utils.webidl_parser import IDLUnionTypefrom Utils.webidl_parser import OperationParameter# The typed arrays, whose names are the variants of the runtime's TypedArrayKind.@@ -38,6 +39,9 @@ SUPPORTED_TYPE_EXTENDED_ATTRIBUTES = {"AllowShared", "AllowResizable"}# The floating point types, with the Rust type of their values.FLOATING_POINT_TYPES = {"float": "f32"}+# 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"}+DECIMAL_LITERAL = re.compile(r"-?[0-9]+(\.[0-9]+)?([eE][-+]?[0-9]+)?")@@ -66,6 +70,32 @@ def rust_dictionary_path(dictionary: Dictionary, context: GenerationContext) ->raise RuntimeError(f"No module defines the dictionary {dictionary.name}")+def union_typedef_name(idl_type: IDLUnionType, context: GenerationContext, what: str) -> str:+ """The name of the typedef that names the union. The generator resolves typedefs before it converts types, and the+ Rust type of a union needs a name, so the typedef is found again by its type."""+ names = sorted(+ name+ for name, typedef in context.typedefs.items()+ if typedef.type.without_nullable() == idl_type.without_nullable()+ )+ if not names:+ raise UnsupportedByRustBindings(f"{what} has the union type {idl_type}, which no typedef names")+ if len(names) > 1:+ raise UnsupportedByRustBindings(f"{what} has the union type {idl_type}, which the typedefs {names} all name")+ return names[0]+++def runtime_union_type(idl_type: IDLType, context: GenerationContext) -> Optional[str]:+ """The type of the bindings runtime for the union, if it has one."""+ if not isinstance(idl_type, IDLUnionType):+ return None+ for name, runtime_type in RUNTIME_UNION_TYPES.items():+ typedef = context.typedefs.get(name)+ if typedef is not None and typedef.type.without_nullable() == idl_type.without_nullable():+ return runtime_type+ return None++def rust_type(idl_type: IDLType, context: GenerationContext, what: str) -> str:"""The Rust type of the IDL values of the type."""unsupported_attributes = set(idl_type.extended_attributes) - SUPPORTED_TYPE_EXTENDED_ATTRIBUTES@@ -91,6 +121,11 @@ 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)+ runtime_type = runtime_union_type(idl_type, context)+ if runtime_type is not None:+ return runtime_type+ if isinstance(idl_type, IDLUnionType):+ union_typedef_name(idl_type, context, what)raise UnsupportedByRustBindings(f"{what} has the type {idl_type}, which the Rust bindings do not convert yet")@@ -100,49 +135,3 @@ def rust_parameter_type(parameter: OperationParameter, context: GenerationContexif parameter.optional and parameter.default_value is None:return f"Option<{value_type}>"return value_type---def rust_conversion_to_idl_value(- idl_type: IDLType,- parameter_attributes: dict[str, str],- value: str,- identifier: str,- context: GenerationContext,- what: str,-) -> str:- """An expression of type ThrowCompletionOr<T> that converts the JS value to the IDL value. The identifier is the- name of the parameter or member that the value is of, which the errors of some conversions name."""- name = idl_type.name- if name == "DOMString":- return f"to_dom_string(vm, {value})"- if name == "USVString":- return f"to_usv_string(vm, {value})"- if name == "float":- return f'to_float(vm, {value}, "{identifier}")'- if name in TYPED_ARRAY_NAMES:- attributes = {**idl_type.extended_attributes, **parameter_attributes}- allow_shared = "true" if "AllowShared" in attributes else "false"- allow_resizable = "true" if "AllowResizable" in attributes else "false"- return (- f'to_typed_array(vm, {value}, TypedArrayKind::{name}, "{name}", '- f"&BufferSourceRules {{ allow_shared: {allow_shared}, allow_resizable: {allow_resizable} }})"- )- raise UnsupportedByRustBindings(f"{what} has the type {idl_type}, which the Rust bindings do not convert to yet")---def rust_default_value(parameter: OperationParameter, context: GenerationContext, what: str) -> str:- """An expression of the parameter's default value."""- name = parameter.type.name- default_value = parameter.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}")'- if name in FLOATING_POINT_TYPES and default_value is not None and DECIMAL_LITERAL.fullmatch(default_value):- return f"{default_value}_{FLOATING_POINT_TYPES[name]}"- raise UnsupportedByRustBindings(- f"{what} has the default value {default_value}, which the Rust bindings do not have"- )