Skip to content

Truly independent web browser

Meta+LibJS+LibWeb: Convert unions and containers in Rust bindings

Aliaksandr Kalenik7165a9f1274b
diff --git a/Libraries/LibJS/Rust/src/api.rs b/Libraries/LibJS/Rust/src/api.rs
index 8535ac19797..f625eb5aeb1 100644
--- a/Libraries/LibJS/Rust/src/api.rs
+++ b/Libraries/LibJS/Rust/src/api.rs
@@ -21,6 +21,7 @@ pub use crate::layout::value::Value;
pub use crate::layout_forward::{RawNativeFunctionPointer, RawNativeFunctionResult};
pub use crate::raw_native;
pub use crate::runtime::abstract_operations::get_function_realm;
+pub use crate::runtime::array::Array;
pub use crate::runtime::array_buffer::{
ArrayBuffer, DataBlock, Order as ArrayBufferOrder, Shared as ArrayBufferShared,
};
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs
index e5e8b633ad0..ee0e83a665c 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs
@@ -11,13 +11,14 @@ use core::mem::MaybeUninit;
use ak::{Utf16String, Utf16StringUnits, convert_valid_utf16_to_utf8, utf8_length_from_valid_utf16};
use libjs_rust::api::{
- ArrayBuffer, ArrayBufferOrder, DataView, ErrorKind, ErrorType, Gc, Object, PrimitiveString, PropertyKey,
+ Array, 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;
+use crate::bindings::interface::create_dictionary_object;
/// A USVString, a string without lone surrogates. Its UTF-16 code units are always well-formed.
pub(crate) struct UsvString(Utf16String);
@@ -73,6 +74,12 @@ impl UsvString {
}
}
+impl From<UsvString> for Utf16String {
+ fn from(string: UsvString) -> Self {
+ string.0
+ }
+}
+
/// A JS value converted to a DOMString, https://webidl.spec.whatwg.org/#es-DOMString
pub(crate) fn to_dom_string(vm: &Vm, value: Value) -> ThrowCompletionOr<Utf16String> {
value.to_utf16_string(vm)
@@ -377,3 +384,59 @@ impl ToJs for Gc<TypedArrayBase> {
Ok(Value::from_object(self))
}
}
+
+/// An IDL sequence converted to a JS value, https://webidl.spec.whatwg.org/#js-sequence, with the conversion of its
+/// elements.
+pub(crate) fn sequence_to_js<T>(
+ cx: &CallContext,
+ sequence: Vec<T>,
+ mut element_to_js: impl FnMut(T) -> ThrowCompletionOr<Value>,
+) -> ThrowCompletionOr<Value> {
+ // 1. Let n be the length of S.
+ // 2. Let A be a new Array object created as if by the expression [].
+ let array = Array::create(cx.vm(), cx.realm(), sequence.len() as u64, None)?;
+
+ // 3. Initialize i to be 0.
+ // 4. While i < n:
+ for (index, element) in sequence.into_iter().enumerate() {
+ // 1. Let V be the value in S at index i.
+ // 2. Let E be the result of converting V to a JavaScript value.
+ let element = element_to_js(element)?;
+
+ // 3. Let P be the result of calling ! ToString(i).
+ // 4. Perform ! CreateDataPropertyOrThrow(A, P, E).
+ // 5. Set i to i + 1.
+ let index = u32::try_from(index).expect("an array of the length of the sequence was created");
+ array.create_data_property(cx.vm(), &PropertyKey::from(index), element, None, None)?;
+ }
+
+ // 5. Return A.
+ Ok(Value::from_object(array))
+}
+
+/// An IDL record converted to a JS value, https://webidl.spec.whatwg.org/#js-record, with the conversion of its
+/// values. The entries of the record are in the order of the Vec.
+pub(crate) fn record_to_js<K: Into<Utf16String>, V>(
+ cx: &CallContext,
+ record: Vec<(K, V)>,
+ mut value_to_js: impl FnMut(V) -> ThrowCompletionOr<Value>,
+) -> ThrowCompletionOr<Value> {
+ // 1. Let result be OrdinaryObjectCreate(%Object.prototype%).
+ let result = create_dictionary_object(cx);
+
+ // 2. For each key → value of D:
+ for (key, value) in record {
+ // 1. Let jsKey be key converted to a JavaScript value.
+ let key = PropertyKey::from_utf16_string(&key.into());
+
+ // 2. Let jsValue be value converted to a JavaScript value.
+ let value = value_to_js(value)?;
+
+ // 3. Let created be ! CreateDataProperty(result, jsKey, jsValue).
+ // 4. Assert: created is true.
+ result.create_data_property(cx.vm(), &key, value, None, None)?;
+ }
+
+ // 3. Return result.
+ Ok(Value::from_object(result))
+}
diff --git a/Meta/Generators/libweb_bindings/rust_bindings.py b/Meta/Generators/libweb_bindings/rust_bindings.py
index d57910817b0..88f95762112 100644
--- a/Meta/Generators/libweb_bindings/rust_bindings.py
+++ b/Meta/Generators/libweb_bindings/rust_bindings.py
@@ -29,8 +29,10 @@ from 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_js
+from Generators.libweb_bindings.rust_to_idl_value import write_union_from_js
from Generators.libweb_bindings.rust_to_js_value import rust_to_js_value
from Generators.libweb_bindings.rust_to_js_value import write_dictionary_to_js
+from Generators.libweb_bindings.rust_to_js_value import write_union_to_js
from Generators.libweb_bindings.rust_types import UnsupportedByRustBindings
from Generators.libweb_bindings.rust_types import rust_module_path
from Generators.libweb_bindings.rust_types import rust_parameter_type
@@ -394,8 +396,8 @@ def write_rust_interface(
}};
use crate::bindings::conversions::{{
- BufferSource, BufferSourceRules, EmptyDictionary, FromJs, ToJs, UsvString, to_boolean, to_buffer_source,
- to_dom_string, to_float, to_typed_array, to_usv_string,
+ BufferSource, BufferSourceRules, EmptyDictionary, FromJs, ToJs, UsvString, record_to_js, sequence_to_js,
+ 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,
@@ -578,9 +580,9 @@ def constructor_length(interface: Interface) -> int:
def write_rust_definitions(out: TextIO, context: GenerationContext, usage: DefinitionUsage) -> None:
- """The conversions of the dictionaries that the interfaces implemented in Rust name, each written once, whichever
- interfaces name it."""
- if not usage.rust_dictionaries:
+ """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:
return
out.write(
"""
@@ -599,7 +601,8 @@ pub(crate) mod definitions {
use crate::bindings::CallContext;
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,
+ dictionary_object, record_to_js, sequence_to_js, 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};
"""
@@ -614,6 +617,11 @@ pub(crate) mod definitions {
write_dictionary_from_js(out, context, dictionary)
if directions.to_js:
write_dictionary_to_js(out, context, dictionary)
+ for union_type, directions in usage.rust_unions.items():
+ if directions.from_js:
+ write_union_from_js(out, context, union_type)
+ if directions.to_js:
+ write_union_to_js(out, context, union_type)
out.write("}\n")
diff --git a/Meta/Generators/libweb_bindings/rust_to_idl_value.py b/Meta/Generators/libweb_bindings/rust_to_idl_value.py
index 62cae6ea0e4..6120b95f264 100644
--- a/Meta/Generators/libweb_bindings/rust_to_idl_value.py
+++ b/Meta/Generators/libweb_bindings/rust_to_idl_value.py
@@ -16,15 +16,22 @@ 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 is_named_union
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 Generators.libweb_bindings.rust_types import rust_union_path
+from Generators.libweb_bindings.rust_types import rust_union_variant
from Utils.webidl_parser import Dictionary
from Utils.webidl_parser import DictionaryMember
+from Utils.webidl_parser import IDLParameterizedType
from Utils.webidl_parser import IDLType
+from Utils.webidl_parser import IDLUnionType
from Utils.webidl_parser import OperationParameter
+STRING_TYPES = ("DOMString", "USVString")
+
def buffer_source_rules(idl_type: IDLType, parameter_attributes: dict[str, str]) -> str:
attributes = {**idl_type.extended_attributes, **parameter_attributes}
@@ -45,6 +52,10 @@ def rust_to_idl_value(
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 idl_type.nullable or isinstance(idl_type, IDLParameterizedType):
+ raise UnsupportedByRustBindings(
+ f"{what} has the type {idl_type}, which the Rust bindings do not convert to yet"
+ )
if name == "DOMString":
return f"to_dom_string(vm, {value})"
if name == "USVString":
@@ -61,9 +72,30 @@ def rust_to_idl_value(
dictionary = resolved_dictionary(idl_type, context)
if dictionary is not None:
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)
+ 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
+ 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
+ else:
+ 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
+
+
def rust_default_value(
member: Union[OperationParameter, DictionaryMember], context: GenerationContext, what: str
) -> str:
@@ -86,6 +118,15 @@ 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()"
+ 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)
+ if dictionary_type is not None:
+ dictionary = context.dictionaries[dictionary_type.name]
+ union_path = rust_union_path(member.type, context, what)
+ return (
+ f"{union_path}::{rust_union_variant(dictionary_type)}"
+ f"(<{rust_dictionary_path(dictionary, context)}>::empty())"
+ )
raise UnsupportedByRustBindings(
f"{what} has the default value {default_value}, which the Rust bindings do not have"
)
@@ -157,3 +198,48 @@ def write_dictionary_from_js(out: TextIO, context: GenerationContext, dictionary
}}
"""
)
+
+
+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-union
+ that 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)
+ steps = []
+ if dictionary_type is not None:
+ dictionary_path = rust_dictionary_path(context.dictionaries[dictionary_type.name], context)
+ 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.
+ // 13. If V is an Object, then:
+ // 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)?));
+ }}
+"""
+ )
+ if string_type is not None:
+ conversion = rust_to_idl_value(string_type, {}, "value", "value", context, what)
+ steps.append(
+ f""" // 17. If types includes a string type, then return the result of converting V to that type.
+ Ok(Self::{rust_union_variant(string_type)}({conversion}?))
+"""
+ )
+ else:
+ steps.append(
+ """ // 19. Throw a TypeError.
+ vm.throw_completion_with_message(ErrorKind::TypeError, "No union types matched".to_string())
+"""
+ )
+ out.write(
+ f"""
+ /// The conversion of a JS value to the union {union_type}, https://webidl.spec.whatwg.org/#js-union
+ impl FromJs for {path} {{
+ fn from_js(vm: &Vm, value: Value) -> ThrowCompletionOr<Self> {{
+{"".join(steps)} }}
+ }}
+"""
+ )
diff --git a/Meta/Generators/libweb_bindings/rust_to_js_value.py b/Meta/Generators/libweb_bindings/rust_to_js_value.py
index 25573918208..7d1e4f088f8 100644
--- a/Meta/Generators/libweb_bindings/rust_to_js_value.py
+++ b/Meta/Generators/libweb_bindings/rust_to_js_value.py
@@ -12,21 +12,70 @@ from typing import TextIO
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 member_other_than_undefined
from Generators.libweb_bindings.rust_types import rust_dictionary_path
from Generators.libweb_bindings.rust_types import rust_type
+from Generators.libweb_bindings.rust_types import rust_union_path
+from Generators.libweb_bindings.rust_types import rust_union_variant
from Utils.webidl_parser import Dictionary
+from Utils.webidl_parser import IDLParameterizedType
from Utils.webidl_parser import IDLType
+from Utils.webidl_parser import IDLUnionType
def rust_to_js_value(
idl_type: IDLType, expression: str, call_context: str, context: GenerationContext, what: str
) -> str:
"""An expression of type ThrowCompletionOr<Value> that converts the IDL value to a JS value. The call context is an
- expression of type &CallContext."""
+ expression of type &CallContext. Nullable types and unions with undefined both have an Option as their Rust type,
+ so the conversion follows from the IDL type and not from the Rust one."""
rust_type(idl_type, context, what)
+
+ def inner(inner_type: IDLType) -> str:
+ return rust_to_js_value(inner_type, "value", call_context, context, what)
+
+ # https://webidl.spec.whatwg.org/#js-nullable-type
+ if idl_type.nullable:
+ return f"""match {expression} {{
+ Some(value) => {inner(idl_type.without_nullable())},
+ None => Ok(Value::NULL),
+ }}"""
+ optional_member = member_other_than_undefined(idl_type)
+ if optional_member is not None:
+ return f"""match {expression} {{
+ Some(value) => {inner(optional_member)},
+ None => Ok(Value::UNDEFINED),
+ }}"""
+ if isinstance(idl_type, IDLParameterizedType) and idl_type.name == "sequence":
+ return f"sequence_to_js({call_context}, {expression}, |value| {inner(idl_type.parameters[0])})"
+ if isinstance(idl_type, IDLParameterizedType) and idl_type.name == "record":
+ return f"record_to_js({call_context}, {expression}, |value| {inner(idl_type.parameters[1])})"
return f"{expression}.to_js({call_context})"
+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."""
+ what = f"the union {union_type}"
+ path = rust_union_path(union_type, context, what)
+ arms = "".join(
+ f""" Self::{rust_union_variant(member_type)}(value) => {rust_to_js_value(member_type, "value", "cx", context, what)},
+"""
+ for member_type in union_type.flattened_member_types()
+ )
+ out.write(
+ f"""
+ /// The conversion of the union {union_type}, https://webidl.spec.whatwg.org/#js-union
+ impl ToJs for {path} {{
+ fn to_js(self, cx: &CallContext) -> ThrowCompletionOr<Value> {{
+ match self {{
+{arms} }}
+ }}
+ }}
+"""
+ )
+
+
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 type
of a required member or of one with a default value, and an Option of it otherwise. The fields are bound to locals
diff --git a/Meta/Generators/libweb_bindings/rust_types.py b/Meta/Generators/libweb_bindings/rust_types.py
index 6df5d0ee3a2..d91fde2390e 100644
--- a/Meta/Generators/libweb_bindings/rust_types.py
+++ b/Meta/Generators/libweb_bindings/rust_types.py
@@ -13,6 +13,7 @@ from typing import Optional
from Generators.libweb_bindings.context import GenerationContext
from Utils.utils import title_case_to_snake_case
from Utils.webidl_parser import Dictionary
+from Utils.webidl_parser import IDLParameterizedType
from Utils.webidl_parser import IDLType
from Utils.webidl_parser import IDLUnionType
from Utils.webidl_parser import OperationParameter
@@ -96,14 +97,55 @@ def runtime_union_type(idl_type: IDLType, context: GenerationContext) -> Optiona
return None
+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:
+ return None
+ others = [member for member in idl_type.member_types if member.name != "undefined"]
+ return others[0] if len(others) == 1 else None
+
+
+def is_named_union(idl_type: IDLType, context: GenerationContext) -> bool:
+ """Whether the Rust type of the union is an enum that the module of the typedef of the union defines."""
+ return (
+ isinstance(idl_type, IDLUnionType)
+ and runtime_union_type(idl_type, context) is None
+ and member_other_than_undefined(idl_type) is None
+ )
+
+
+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."""
+ return member_type.name.replace(" ", "")
+
+
+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."""
+ name = union_typedef_name(idl_type, context, what)
+ for module in context.modules:
+ if any(typedef.name == name for typedef in module.typedefs):
+ return f"{rust_module_path(module.path)}::{name}"
+ raise RuntimeError(f"No module defines the typedef {name}")
+
+
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
if unsupported_attributes:
raise UnsupportedByRustBindings(f"{what} has extended attributes {sorted(unsupported_attributes)}")
if idl_type.nullable:
- raise UnsupportedByRustBindings(f"{what} has the nullable type {idl_type}")
+ return f"Option<{rust_type(idl_type.without_nullable(), context, what)}>"
name = idl_type.name
+ if isinstance(idl_type, IDLParameterizedType):
+ if name == "sequence":
+ return f"Vec<{rust_type(idl_type.parameters[0], context, what)}>"
+ if name == "record":
+ key_type, value_type = idl_type.parameters
+ if key_type.name not in ("DOMString", "USVString"):
+ 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":
@@ -124,8 +166,13 @@ def rust_type(idl_type: IDLType, context: GenerationContext, what: str) -> str:
runtime_type = runtime_union_type(idl_type, context)
if runtime_type is not None:
return runtime_type
+ optional_member = member_other_than_undefined(idl_type)
+ if optional_member is not None:
+ return f"Option<{rust_type(optional_member, context, what)}>"
if isinstance(idl_type, IDLUnionType):
- union_typedef_name(idl_type, context, what)
+ for member_type in idl_type.flattened_member_types():
+ 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")
diff --git a/Meta/Generators/libweb_bindings/rust_usage.py b/Meta/Generators/libweb_bindings/rust_usage.py
index ca0445a479e..6ae0cb1c98d 100644
--- a/Meta/Generators/libweb_bindings/rust_usage.py
+++ b/Meta/Generators/libweb_bindings/rust_usage.py
@@ -14,8 +14,11 @@ from typing import Optional
from typing import Set
from Generators.libweb_bindings.context import GenerationContext
+from Generators.libweb_bindings.rust_types import is_named_union
+from Generators.libweb_bindings.rust_types import runtime_union_type
from Utils.webidl_parser import Dictionary
from Utils.webidl_parser import IDLType
+from Utils.webidl_parser import IDLUnionType
from Utils.webidl_parser import Interface
from Utils.webidl_parser import Module
@@ -71,6 +74,8 @@ class DefinitionUsage:
self.context = context
# The dictionaries that the interfaces implemented in Rust name, in the order of their first use.
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 dictionaries that have a C++ representation.
self.cpp_dictionary_names: Set[str] = set()
self._collect_rust_dictionaries()
@@ -96,17 +101,31 @@ class DefinitionUsage:
self._name_for_rust(parameter.type, from_js=True, to_js=False)
def _name_for_rust(self, idl_type: IDLType, from_js: bool, to_js: bool) -> None:
- for nested_type in idl_type.nested_types():
- dictionary = self.context.dictionaries.get(nested_type.name)
- if dictionary is None:
- continue
- directions = self.rust_dictionaries.setdefault(dictionary.name, ConversionDirections())
- if (directions.from_js or not from_js) and (directions.to_js or not to_js):
- continue
- directions.from_js = directions.from_js or from_js
- directions.to_js = directions.to_js or to_js
- for member in self._members_with_inherited(dictionary):
- self._name_for_rust(member.type, from_js, to_js)
+ if isinstance(idl_type, IDLUnionType):
+ # NB: The bindings runtime converts the unions that it has a type for as a whole.
+ if runtime_union_type(idl_type, self.context) is not None:
+ return
+ if is_named_union(idl_type, self.context):
+ union_type = idl_type.without_nullable()
+ assert isinstance(union_type, IDLUnionType)
+ directions = self.rust_unions.setdefault(union_type, ConversionDirections())
+ directions.from_js = directions.from_js or from_js
+ directions.to_js = directions.to_js or to_js
+ for member_type in idl_type.flattened_member_types():
+ self._name_for_rust(member_type, from_js, to_js)
+ return
+ for child_type in idl_type.child_types():
+ self._name_for_rust(child_type, from_js, to_js)
+ dictionary = self.context.dictionaries.get(idl_type.name)
+ if dictionary is None:
+ return
+ directions = self.rust_dictionaries.setdefault(dictionary.name, ConversionDirections())
+ if (directions.from_js or not from_js) and (directions.to_js or not to_js):
+ return
+ directions.from_js = directions.from_js or from_js
+ directions.to_js = directions.to_js or to_js
+ for member in self._members_with_inherited(dictionary):
+ self._name_for_rust(member.type, from_js, to_js)
def _members_with_inherited(self, dictionary: Dictionary):
members = list(dictionary.members)