Truly independent web browser
Meta+LibWeb: Support Blob and File in the Rust bindings
Shannon Booth8524892be9cb
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rsindex 2ca0c01bc5d..d93fea34dfd 100644--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs@@ -13,7 +13,7 @@ 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, Must, Object,+ Array, ArrayBuffer, ArrayBufferOrder, DataView, ErrorKind, ErrorType, FunctionObject, Gc, MarkedVec, 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,@@ -229,7 +229,7 @@ fn to_integer_enforcing_range(vm: &Vm, value: Value, lower_bound: f64, upper_bou}/// The largest integer that a JS number represents unambiguously, the upper bound of a 64-bit integer type with-/// [EnforceRange].+/// [EnforceRange] or [Clamp].const MAX_SAFE_INTEGER: f64 = 9_007_199_254_740_991.0;/// A JS value converted to a long with [EnforceRange], https://webidl.spec.whatwg.org/#js-long@@ -271,6 +271,35 @@ pub(crate) fn to_unsigned_long_long_enforcing_range(vm: &Vm, value: Value) -> ThOk(to_integer_enforcing_range(vm, value, 0.0, MAX_SAFE_INTEGER)? as u64)}+/// A JS value converted to an integer of the IDL type with [Clamp], whose bounds those are: steps 4, 5, 7 and 8 of+/// https://webidl.spec.whatwg.org/#abstract-opdef-converttoint+fn to_integer_clamping(vm: &Vm, value: Value, lower_bound: f64, upper_bound: f64) -> ThrowCompletionOr<f64> {+ // 4. Let x be ? ToNumber(V).+ // 5. If x is −0, then set x to +0.+ let x = value.to_double(vm)? + 0.0;++ // 7. If x is not NaN and the conversion is to an IDL type associated with the [Clamp] extended attribute, then:+ if !x.is_nan() {+ // 1. Set x to min(max(x, lowerBound), upperBound).+ // 2. Round x to the nearest integer, choosing the even integer if it lies halfway between two, and+ // choosing +0 rather than −0.+ // 3. Return x.+ return Ok(x.clamp(lower_bound, upper_bound).round_ties_even() + 0.0);+ }++ // 8. If x is NaN, +0, +∞, or −∞, then return +0.+ Ok(0.0)+}++/// A JS value converted to a long long with [Clamp], https://webidl.spec.whatwg.org/#js-long-long+#[allow(+ clippy::cast_possible_truncation,+ reason = "the value is an integer within the bounds of the type"+)]+pub(crate) fn to_long_long_clamping(vm: &Vm, value: Value) -> ThrowCompletionOr<i64> {+ Ok(to_integer_clamping(vm, value, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER)? as i64)+}+/// The number that https://webidl.spec.whatwg.org/#abstract-opdef-converttoint has after step 10 for a bit length of/// 64, as WebIDL::convert_to_int() of the C++ bindings computes it.///@@ -472,7 +501,8 @@ fn check_buffer_of_buffer_source(}/// An IDL BufferSource value, https://webidl.spec.whatwg.org/#BufferSource-#[derive(Clone, Copy)]+#[derive(Clone, Copy, Trace)]+#[gc(crate = libjs_rust)]pub(crate) enum BufferSource {ArrayBuffer(Gc<ArrayBuffer>),DataView(Gc<DataView>),@@ -630,40 +660,52 @@ impl ArrayBufferView {/// 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> {- if value.is_object() {- let object = value.as_object();+ if value.is_object()+ && let Some(buffer_source) = buffer_source_if(vm, value.as_object(), rules)?+ {+ return Ok(buffer_source);+ }- // 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));- }+ // 20. Throw a TypeError.+ throw_no_union_types_matched(vm)+}- // FIXME: 7. If V is an Object, V has an [[ArrayBufferData]] internal slot, and IsSharedArrayBuffer(V) is true,- // then:+/// An object converted to a BufferSource if it is one, 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 buffer_source_if(+ vm: &Vm,+ object: Gc<Object>,+ rules: &BufferSourceRules,+) -> ThrowCompletionOr<Option<BufferSource>> {+ // 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(Some(BufferSource::ArrayBuffer(buffer)));+ }- // 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));- }+ // FIXME: 7. If V is an Object, V has an [[ArrayBufferData]] internal slot, and IsSharedArrayBuffer(V) is true,+ // then:- // 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));- }+ // 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(Some(BufferSource::DataView(view)));}- // 20. Throw a TypeError.- throw_no_union_types_matched(vm)+ // 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(Some(BufferSource::TypedArray(typed_array)));+ }++ Ok(None)}/// A JS value converted to an ArrayBufferView, with the steps of the conversion to a union type that apply to the@@ -704,13 +746,32 @@ pub(crate) fn throw_no_union_types_matched<T>(vm: &Vm) -> ThrowCompletionOr<T> {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>(+/// Where an IDL sequence keeps its elements: a Vec, which hides cells from the collector, so its elements hold none,+/// or a MarkedVec, which keeps them alive while the rest are converted and for as long as the sequence lives.+pub(crate) trait SequenceStorage<T> {+ fn append(&mut self, value: T);+}++impl<T> SequenceStorage<T> for Vec<T> {+ fn append(&mut self, value: T) {+ self.push(value);+ }+}++impl<T: Trace + Clone + 'static> SequenceStorage<T> for MarkedVec<'_, T> {+ fn append(&mut self, value: T) {+ self.push(value);+ }+}++/// A JS value converted to an IDL sequence in `sequence`, https://webidl.spec.whatwg.org/#js-sequence, with the+/// conversion of its elements.+pub(crate) fn sequence_from_js<T, S: SequenceStorage<T>>(vm: &Vm,value: Value,+ sequence: S,element_from_js: impl FnMut(Value) -> ThrowCompletionOr<T>,-) -> ThrowCompletionOr<Vec<T>> {+) -> ThrowCompletionOr<S> {// 1. If V is not an Object, throw a TypeError.if !value.is_object() {return vm.throw_completion(ErrorKind::TypeError, ErrorType::NotAnObject, &[&value]);@@ -723,7 +784,7 @@ pub(crate) fn sequence_from_js<T>(};// 4. Return the result of creating a sequence from V and method.- sequence_from_iterable(vm, value, method, element_from_js)+ sequence_from_iterable(vm, value, method, sequence, element_from_js)}/// ? GetMethod(V, %Symbol.iterator%), which decides whether a JS value converts to a sequence type.@@ -731,27 +792,27 @@ pub(crate) fn iterator_method(vm: &Vm, value: Value) -> ThrowCompletionOr<Optionvalue.get_method(vm, &PropertyKey::from(vm.well_known_symbols().iterator))}-/// An IDL sequence created from an iterable and its iterator getter method,+/// An IDL sequence in `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>(+pub(crate) fn sequence_from_iterable<T, S: SequenceStorage<T>>(vm: &Vm,iterable: Value,method: Gc<FunctionObject>,+ mut sequence: S,mut element_from_js: impl FnMut(Value) -> ThrowCompletionOr<T>,-) -> ThrowCompletionOr<Vec<T>> {+) -> ThrowCompletionOr<S> {// 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)?);+ sequence.append(element_from_js(next)?);}Ok(sequence)}diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/structured_data.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/structured_data.rsindex 558e10530fc..c55f786a10b 100644--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/structured_data.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/structured_data.rs@@ -20,6 +20,7 @@ use core::ffi::c_void;use core::marker::PhantomData;use core::ptr::NonNull;+use ak::Utf16String;use libjs_rust::api::{RawNativeFunctionResult, ThrowCompletionOr, Value};use crate::bindings::interface::{Interface, allocate, cell_from_abi, realm_arguments, wrap};@@ -30,10 +31,18 @@ unsafe extern "C" {fn web_bindings_serialize_u32(serialized: *mut c_void, value: u32);fn web_bindings_serialize_f64(serialized: *mut c_void, value: f64);fn web_bindings_serialize_bool(serialized: *mut c_void, value: bool);+ fn web_bindings_serialize_i64(serialized: *mut c_void, value: i64);+ fn web_bindings_serialize_utf16_string(serialized: *mut c_void, string: usize);+ fn web_bindings_serialize_bytes(serialized: *mut c_void, bytes: ak::Span<'_, u8>);fn web_bindings_deserialize_value(serialized: *mut c_void) -> RawNativeFunctionResult;fn web_bindings_deserialize_u32(serialized: *mut c_void, out_value: &mut u32) -> RawNativeFunctionResult;fn web_bindings_deserialize_f64(serialized: *mut c_void, out_value: &mut f64) -> RawNativeFunctionResult;fn web_bindings_deserialize_bool(serialized: *mut c_void, out_value: &mut bool) -> RawNativeFunctionResult;+ fn web_bindings_deserialize_i64(serialized: *mut c_void, out_value: &mut i64) -> RawNativeFunctionResult;+ fn web_bindings_deserialize_utf16_string(+ serialized: *mut c_void,+ out_string: &mut usize,+ ) -> RawNativeFunctionResult;fn web_bindings_serialize_inline_object_header(serialized: *mut c_void, interface_name: u16);fn web_bindings_deserialize_inline_object_header(serialized: *mut c_void,@@ -77,6 +86,21 @@ impl SerializationWriter<'_> {unsafe { web_bindings_serialize_bool(self.raw.as_ptr(), value) };}+ pub(crate) fn write_i64(&mut self, value: i64) {+ // SAFETY: The writer is lent for the steps.+ unsafe { web_bindings_serialize_i64(self.raw.as_ptr(), value) };+ }++ pub(crate) fn write_utf16_string(&mut self, string: &Utf16String) {+ // SAFETY: The writer is lent for the steps, and the call borrows the string.+ unsafe { web_bindings_serialize_utf16_string(self.raw.as_ptr(), string.raw_identity()) };+ }++ pub(crate) fn write_bytes(&mut self, bytes: &[u8]) {+ // SAFETY: The writer is lent for the steps, and the call borrows the bytes.+ unsafe { web_bindings_serialize_bytes(self.raw.as_ptr(), ak::Span::new(bytes)) };+ }+/// Writes the record of a serializable object in place, as StructuredSerializeInternal writes it, but without/// giving the object a position in the memory of the serialization, which a format that predates the/// sub-serialization of the object has none for.@@ -141,6 +165,21 @@ impl SerializationReader<'_> {unsafe { web_bindings_deserialize_bool(self.raw.as_ptr(), &mut value) }.into_completion()?;Ok(value)}++ pub(crate) fn read_i64(&mut self) -> WebIdlResult<i64> {+ let mut value = 0;+ // SAFETY: The reader is lent for the steps.+ unsafe { web_bindings_deserialize_i64(self.raw.as_ptr(), &mut value) }.into_completion()?;+ Ok(value)+ }++ pub(crate) fn read_utf16_string(&mut self) -> WebIdlResult<Utf16String> {+ let mut string = 0;+ // SAFETY: The reader is lent for the steps.+ unsafe { web_bindings_deserialize_utf16_string(self.raw.as_ptr(), &mut string) }.into_completion()?;+ // SAFETY: LibWeb hands over the string it read.+ Ok(unsafe { Utf16String::from_raw_owned(string) })+ }}/// An interface that is serializable, [Serializable] in its IDL.diff --git a/Libraries/LibWeb/Bindings/RustBindingsServices.cpp b/Libraries/LibWeb/Bindings/RustBindingsServices.cppindex 3594709ed85..6918b4661bc 100644--- a/Libraries/LibWeb/Bindings/RustBindingsServices.cpp+++ b/Libraries/LibWeb/Bindings/RustBindingsServices.cpp@@ -94,10 +94,15 @@ JSCompletion web_bindings_serialize_value(RustSerializationWriter*, JSValue);void web_bindings_serialize_u32(RustSerializationWriter*, u32);void web_bindings_serialize_f64(RustSerializationWriter*, double);void web_bindings_serialize_bool(RustSerializationWriter*, bool);+void web_bindings_serialize_i64(RustSerializationWriter*, i64);+void web_bindings_serialize_utf16_string(RustSerializationWriter*, FlatPtr string);+void web_bindings_serialize_bytes(RustSerializationWriter*, ReadonlyBytes);JSCompletion web_bindings_deserialize_value(RustSerializationReader*);JSCompletion web_bindings_deserialize_u32(RustSerializationReader*, u32* out_value);JSCompletion web_bindings_deserialize_f64(RustSerializationReader*, double* out_value);JSCompletion web_bindings_deserialize_bool(RustSerializationReader*, bool* out_value);+JSCompletion web_bindings_deserialize_i64(RustSerializationReader*, i64* out_value);+JSCompletion web_bindings_deserialize_utf16_string(RustSerializationReader*, FlatPtr* out_string);void web_bindings_serialize_inline_object_header(RustSerializationWriter*, u16 interface_name);JSCompletion web_bindings_deserialize_inline_object_header(RustSerializationReader*, u16 interface_name);@@ -186,6 +191,21 @@ void web_bindings_serialize_bool(RustSerializationWriter* writer, bool value)writer->serialized.encode(value);}+void web_bindings_serialize_i64(RustSerializationWriter* writer, i64 value)+{+ writer->serialized.encode(value);+}++void web_bindings_serialize_utf16_string(RustSerializationWriter* writer, FlatPtr string)+{+ writer->serialized.encode(Utf16String::from_raw(string));+}++void web_bindings_serialize_bytes(RustSerializationWriter* writer, ReadonlyBytes bytes)+{+ writer->serialized.encode(bytes);+}+// StructuredDeserialize of a value that the serialized form of an object holds, https://html.spec.whatwg.org/multipage/structured-data.html#sub-deserializationJSCompletion web_bindings_deserialize_value(RustSerializationReader* reader){@@ -207,6 +227,19 @@ JSCompletion web_bindings_deserialize_bool(RustSerializationReader* reader, boolreturn deserialize_plain_value(reader, out_value);}+JSCompletion web_bindings_deserialize_i64(RustSerializationReader* reader, i64* out_value)+{+ return deserialize_plain_value(reader, out_value);+}++JSCompletion web_bindings_deserialize_utf16_string(RustSerializationReader* reader, FlatPtr* out_string)+{+ Utf16String string;+ auto result = deserialize_plain_value(reader, &string);+ *out_string = move(string).into_raw();+ return result;+}+// The record of a serializable object of the interface as StructuredSerializeInternal starts it, for an object that// steps serialize in place, without a position in the memory of the serialization.void web_bindings_serialize_inline_object_header(RustSerializationWriter* writer, u16 interface_name)diff --git a/Meta/Generators/libweb_bindings/rust_bindings.py b/Meta/Generators/libweb_bindings/rust_bindings.pyindex 4e96d05b077..fb74a08271d 100644--- a/Meta/Generators/libweb_bindings/rust_bindings.py+++ b/Meta/Generators/libweb_bindings/rust_bindings.py@@ -395,6 +395,7 @@ def write_parameter_conversions(unsupported = set(parameter.extended_attributes) - {"AllowShared","AllowResizable",+ "Clamp","EnforceRange","LegacyNullToEmptyString",}@@ -402,7 +403,13 @@ def write_parameter_conversions(raise UnsupportedByRustBindings(f"{parameter_what} has the extended attributes {sorted(unsupported)}")name = rust_local_name(parameter.name)conversion = rust_to_idl_value(- parameter.type, parameter.extended_attributes, f"argument{index}", parameter.name, context, parameter_what+ parameter.type,+ parameter.extended_attributes,+ f"argument{index}",+ parameter.name,+ context,+ parameter_what,+ is_parameter=True,)out.write(f" let argument{index} = vm.argument({index});\n")if parameter.optional and parameter.default_value is not None:@@ -569,8 +576,8 @@ def write_rust_interface(use ak::Utf16String;use libjs_rust::api::{{- ArrayBuffer, DataView, EmbedderClass, ErrorKind, ErrorType, FunctionObject, Gc, JSHostClass, Object,- PropertyKey, RawNativeFunctionResult, ThrowCompletionOr, TypedArrayBase, TypedArrayKind, Value, Vm,+ ArrayBuffer, DataView, EmbedderClass, ErrorKind, ErrorType, FunctionObject, Gc, JSHostClass, MarkedVec,+ Object, PropertyKey, RawNativeFunctionResult, ThrowCompletionOr, TypedArrayBase, TypedArrayKind, Value, Vm,is_host_instance_of, raw_native,}};@@ -580,8 +587,9 @@ def write_rust_interface(sequence_to_js, to_array_buffer_view, to_boolean, to_buffer_source, to_cpp_interface,to_cpp_interface_in_union, to_dom_string,to_dom_string_treating_null_as_empty, to_double, to_float, to_long, to_long_enforcing_range, to_long_long,- to_long_long_enforcing_range, to_typed_array, to_unrestricted_double, to_unrestricted_float, to_unsigned_long,- to_unsigned_long_enforcing_range, to_unsigned_long_long, to_unsigned_long_long_enforcing_range, to_usv_string,+ to_long_long_clamping, 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,}};use crate::bindings::interface::{{Inherits, Interface, Ref, Wrapped, cell_class, construct_arguments, construct_wrapper, create_dictionary_object,@@ -1343,16 +1351,18 @@ pub(crate) mod definitions {use crate::bindings::CallContext;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_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,+ buffer_source_if, dictionary_member, dictionary_object, enumeration_value_to_js, implements_cpp_interface,+ iterator_method, 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,to_unrestricted_float, to_unsigned_long, to_unsigned_long_enforcing_range, to_unsigned_long_long,to_unsigned_long_long_enforcing_range, to_usv_string,};use crate::bindings::interface::{- Interface, Ref, create_dictionary_object, implementation_of, set_dictionary_member, to_interface,+ Interface, Ref, create_dictionary_object, implementation_if, implementation_of, set_dictionary_member,+ to_interface,};""")diff --git a/Meta/Generators/libweb_bindings/rust_to_idl_value.py b/Meta/Generators/libweb_bindings/rust_to_idl_value.pyindex 21647fdcda4..787a71d9533 100644--- a/Meta/Generators/libweb_bindings/rust_to_idl_value.py+++ b/Meta/Generators/libweb_bindings/rust_to_idl_value.py@@ -24,11 +24,14 @@ from Generators.libweb_bindings.rust_types import UnsupportedByRustBindingsfrom Generators.libweb_bindings.rust_types import cpp_interfacefrom Generators.libweb_bindings.rust_types import cpp_interface_name_constantfrom Generators.libweb_bindings.rust_types import holds_cells+from Generators.libweb_bindings.rust_types import inheriting_interfacesfrom Generators.libweb_bindings.rust_types import is_named_union+from Generators.libweb_bindings.rust_types import is_sequence_of_cellsfrom Generators.libweb_bindings.rust_types import is_unnamed_union_of_cpp_interfacesfrom 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_type+from Generators.libweb_bindings.rust_types import rust_any_interface_pathfrom Generators.libweb_bindings.rust_types import rust_dictionary_pathfrom Generators.libweb_bindings.rust_types import rust_enumeration_pathfrom Generators.libweb_bindings.rust_types import rust_enumeration_variant@@ -38,6 +41,7 @@ from Generators.libweb_bindings.rust_types import rust_interface_pathfrom 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_variant+from Generators.libweb_bindings.rust_types import union_member_typesfrom Utils.webidl_parser import Dictionaryfrom Utils.webidl_parser import DictionaryMemberfrom Utils.webidl_parser import Enumeration@@ -63,16 +67,20 @@ def rust_to_idl_value(identifier: str,context: GenerationContext,what: str,+ is_parameter: bool = False,) -> 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 of the parameter or member that the value is of, which the errors of some conversions name. The value of a+ parameter can be a sequence of values that are or can hold cells, rust_parameter_type()."""rust_type(idl_type, context, what)name = idl_type.nameattributes = {**idl_type.extended_attributes, **parameter_attributes}- if "EnforceRange" in attributes and (idl_type.nullable or name not in INTEGER_TYPES):- raise UnsupportedByRustBindings(- f"{what} has the type {idl_type} with [EnforceRange], which the Rust bindings only handle on integer types"- )+ for integer_attribute in ("Clamp", "EnforceRange"):+ if integer_attribute in attributes and (idl_type.nullable or name not in INTEGER_TYPES):+ raise UnsupportedByRustBindings(+ f"{what} has the type {idl_type} with [{integer_attribute}], which the Rust bindings only handle on "+ "integer types"+ )if "LegacyNullToEmptyString" in attributes and (idl_type.nullable or name != "DOMString"):raise UnsupportedByRustBindings(f"{what} has the type {idl_type} with [LegacyNullToEmptyString], which applies to DOMString only"@@ -88,8 +96,11 @@ 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":+ if is_parameter and is_sequence_of_cells(idl_type, context):+ element = rust_to_idl_value(idl_type.parameters[0], {}, "value", identifier, context, what)+ return f"sequence_from_js(vm, {value}, MarkedVec::new(vm), |value| {element})"element = rust_sequence_element_to_idl_value(idl_type, identifier, context, what)- return f"sequence_from_js(vm, {value}, |value| {element})"+ return f"sequence_from_js(vm, {value}, Vec::new(), |value| {element})"if isinstance(idl_type, IDLParameterizedType) and idl_type.name == "record":return rust_record_to_idl_value(idl_type, value, identifier, context, what)if isinstance(idl_type, IDLParameterizedType):@@ -109,6 +120,8 @@ def rust_to_idl_value(if name in INTEGER_TYPES:if "EnforceRange" in attributes:return f"to_{name.replace(' ', '_')}_enforcing_range(vm, {value})"+ if "Clamp" in attributes:+ return f"to_{name.replace(' ', '_')}_clamping(vm, {value})"return f"to_{name.replace(' ', '_')}(vm, {value})"if name == "float":return f'to_float(vm, {value}, "{identifier}")'@@ -130,6 +143,11 @@ def rust_to_idl_value(return f"<{rust_enumeration_path(enumeration, context)}>::from_js(vm, {value})"interface = rust_interface(idl_type, context)if interface is not None:+ if inheriting_interfaces(interface, context):+ raise UnsupportedByRustBindings(+ f"{what} has the type {idl_type}, an interface that others inherit from, which the Rust bindings only "+ "convert to as a member of a union yet"+ )return f"to_interface::<{rust_interface_path(interface)}>(vm, {value})"interface = cpp_interface(idl_type, context)if interface is not None:@@ -196,6 +214,7 @@ class UnionMembers:numeric_type: Optional[IDLType] = Nonesequence_type: Optional[IDLParameterizedType] = Nonerecord_type: Optional[IDLParameterizedType] = None+ buffer_source_type: Optional[IDLType] = Nonetyped_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)@@ -203,8 +222,10 @@ class UnionMembers: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 members.dictionary_type is None:+ for member_type in union_member_types(union_type, context):+ if runtime_union_type(member_type, context) == "BufferSource" and members.buffer_source_type is None:+ members.buffer_source_type = member_type+ elif resolved_dictionary(member_type, context) is not None and members.dictionary_type is None:members.dictionary_type = member_typeelif member_type.name in STRING_TYPES and members.string_type is None:members.string_type = member_type@@ -432,6 +453,7 @@ def write_union_from_js(out: TextIO, context: GenerationContext, union_type: IDLor members.sequence_type is not Noneor members.record_type is not Noneor members.interface_types+ or members.buffer_source_type is not None):if dictionary_conversion is not None:steps.append(@@ -452,6 +474,28 @@ def write_union_from_js(out: TextIO, context: GenerationContext, union_type: IDL// reference to the object V.""")+ if rust_interface(interface_type, context) is not None and inheriting_interfaces(interface, context):+ # NB: A wrapper of the interface wraps an object of the interface or of one that inherits from it,+ # which the variant holds as such.+ interface_path = rust_interface_path(interface)+ any_interface_path = rust_any_interface_path(interface)+ steps.append(+ f""" if is_host_instance_of(&value.as_object(), <{interface_path} as Interface>::wrapper_class()) {{+"""+ )+ for implementing in [interface] + inheriting_interfaces(interface, context):+ steps.append(+ f""" if let Some(object) = implementation_if::<{rust_interface_path(implementing)}>(value.as_object()) {{+ return Ok(Self::{rust_union_variant(interface_type)}({any_interface_path}::{implementing.name}(object)));+ }}+"""+ )+ steps.append(+ """ unreachable!("a wrapper of the interface wraps an object of it or of an interface that inherits from it");+ }+"""+ )+ continueif rust_interface(interface_type, context) is not None:interface_path = rust_interface_path(interface)steps.append(@@ -467,6 +511,22 @@ def write_union_from_js(out: TextIO, context: GenerationContext, union_type: IDLlet object = unsafe {{ CppInterface::from_wrapper(value.as_object()) }};return Ok(Self::{rust_union_variant(interface_type)}(object));}}+"""+ )+ if members.buffer_source_type is not None:+ rules = buffer_source_rules(members.buffer_source_type, {})+ steps.append(+ f""" // 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.+ // 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.+ // 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(buffer_source) = buffer_source_if(vm, value.as_object(), {rules})? {{+ return Ok(Self::BufferSource(buffer_source));+ }}""")for typed_array_type in members.typed_array_types:@@ -491,7 +551,7 @@ def write_union_from_js(out: TextIO, context: GenerationContext, union_type: IDL// 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})?));+ return Ok(Self::Sequence(sequence_from_iterable(vm, value, method, Vec::new(), |value| {element})?));}}""")diff --git a/Meta/Generators/libweb_bindings/rust_types.py b/Meta/Generators/libweb_bindings/rust_types.pyindex 5241e834ab6..4f6825422df 100644--- a/Meta/Generators/libweb_bindings/rust_types.py+++ b/Meta/Generators/libweb_bindings/rust_types.py@@ -41,7 +41,13 @@ TYPED_ARRAY_NAMES = {}# The extended attributes of a type or a parameter that the Rust bindings handle.-SUPPORTED_TYPE_EXTENDED_ATTRIBUTES = {"AllowShared", "AllowResizable", "EnforceRange", "LegacyNullToEmptyString"}+SUPPORTED_TYPE_EXTENDED_ATTRIBUTES = {+ "AllowShared",+ "AllowResizable",+ "Clamp",+ "EnforceRange",+ "LegacyNullToEmptyString",+}# The integer types, with the Rust type of their values.INTEGER_TYPES = {"long": "i32", "unsigned long": "u32", "long long": "i64", "unsigned long long": "u64"}@@ -169,6 +175,13 @@ def rust_interface_path(interface: Interface) -> str:return f"{rust_module_path(interface.path)}::{interface.name}"+def rust_any_interface_path(interface: Interface) -> str:+ """The Rust path of the enum of an object of an interface that others inherit from, which is an object of the+ interface or of any of those, with a variant for each that is named after its interface:+ crate::file_api::blob::AnyBlob for FileAPI/Blob.idl."""+ return f"{rust_module_path(interface.path)}::Any{interface.name}"++def rust_dictionary_path(dictionary: Dictionary, context: GenerationContext) -> str:"""The Rust path of the struct of a dictionary, which is in the module of the IDL file that defines thedictionary: crate::encoding::text_encoder::TextEncoderEncodeIntoResult."""@@ -274,6 +287,18 @@ def runtime_union_type(idl_type: IDLType, context: GenerationContext) -> Optionareturn None+def union_member_types(idl_type: IDLUnionType, context: GenerationContext) -> List[IDLType]:+ """The flattened member types of the union, except that a union the bindings runtime has a type for is one+ member, as BufferSource is in (BufferSource or Blob or USVString)."""+ member_types: List[IDLType] = []+ for member_type in idl_type.member_types:+ if isinstance(member_type, IDLUnionType) and runtime_union_type(member_type, context) is None:+ member_types.extend(union_member_types(member_type, context))+ else:+ member_types.append(member_type)+ return member_types++def member_other_than_undefined(idl_type: IDLType) -> Optional[IDLType]:"""The other member of a union of a type and undefined, whose IDL values are those of the type or nothing."""if not isinstance(idl_type, IDLUnionType) or idl_type.nullable or len(idl_type.member_types) != 2:@@ -373,10 +398,7 @@ def rust_type(idl_type: IDLType, context: GenerationContext, what: str, is_resulif inheriting_interfaces(interface, context) and not is_result:# NB: An object of such a type is a cell of any of several classes, which Ref<T> cannot express. An object# that an implementation returns is one of exactly the interface, whose cell it created.- raise UnsupportedByRustBindings(- f"{what} has the type {idl_type}, an interface that others inherit from, which the Rust bindings do "- "not convert yet"- )+ return rust_any_interface_path(interface)return f"Ref<{rust_interface_path(interface)}>"if cpp_interface(idl_type, context) is not None or is_unnamed_union_of_cpp_interfaces(idl_type, context):return "CppInterface"@@ -393,7 +415,7 @@ def rust_type(idl_type: IDLType, context: GenerationContext, what: str, is_resulif optional_member is not None:return f"Option<{rust_type(optional_member, context, what)}>"if isinstance(idl_type, IDLUnionType):- for member_type in idl_type.flattened_member_types():+ for member_type in union_member_types(idl_type, context):rust_type(member_type, context, what)return rust_union_path(idl_type, context, what)raise UnsupportedByRustBindings(f"{what} has the type {idl_type}, which the Rust bindings do not convert yet")@@ -447,9 +469,24 @@ def holds_cells()+def is_sequence_of_cells(idl_type: IDLType, context: GenerationContext) -> bool:+ """Whether the type is a sequence whose elements are or can hold cells, which the bindings gather in a MarkedVec+ for a parameter."""+ return (+ isinstance(idl_type, IDLParameterizedType)+ and idl_type.name == "sequence"+ and not idl_type.nullable+ and holds_cells(idl_type.parameters[0], context)+ )++def rust_parameter_type(parameter: OperationParameter, context: GenerationContext, what: str) -> str:"""The Rust type the implementation receives for the parameter."""- value_type = rust_type(parameter.type, context, what)+ if is_sequence_of_cells(parameter.type, context):+ assert isinstance(parameter.type, IDLParameterizedType)+ value_type = f"MarkedVec<'_, {rust_type(parameter.type.parameters[0], context, what)}>"+ else:+ value_type = rust_type(parameter.type, context, what)if parameter.optional and parameter.default_value is None:return f"Option<{value_type}>"return value_type