Truly independent web browser
Meta+LibWeb: Resolve operation overloads in the Rust bindings
Aliaksandr Kalenik2f7a4b63c129
diff --git a/Meta/Generators/libweb_bindings/rust_bindings.py b/Meta/Generators/libweb_bindings/rust_bindings.pyindex 3a910f4a4ec..566165d850d 100644--- a/Meta/Generators/libweb_bindings/rust_bindings.py+++ b/Meta/Generators/libweb_bindings/rust_bindings.py@@ -31,6 +31,7 @@ from Generators.libweb_bindings.rust_members import rust_membersfrom Generators.libweb_bindings.rust_names import rust_identifierfrom Generators.libweb_bindings.rust_names import rust_local_namefrom Generators.libweb_bindings.rust_overloads import write_constructor_overload_resolution+from Generators.libweb_bindings.rust_overloads import write_operation_overload_resolutionfrom 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@@ -404,15 +405,17 @@ def write_rust_interface(use ak::Utf16String;use libjs_rust::api::{{- EmbedderClass, ErrorKind, ErrorType, FunctionObject, Gc, JSHostClass, Object, RawNativeFunctionResult,- ThrowCompletionOr, TypedArrayBase, TypedArrayKind, Value, Vm, raw_native,+ ArrayBuffer, DataView, EmbedderClass, ErrorKind, ErrorType, FunctionObject, Gc, JSHostClass, Object,+ RawNativeFunctionResult, ThrowCompletionOr, TypedArrayBase, TypedArrayKind, Value, Vm, is_host_instance_of,+ raw_native,}};use crate::bindings::conversions::{{ArrayBufferView, BufferSource, BufferSourceRules, CppInterface, 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_cpp_interface, 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,+ implements_cpp_interface, record_to_js, rooted_sequence_to_js, sequence_from_js, sequence_to_js,+ to_array_buffer_view, to_boolean, to_buffer_source, to_cpp_interface, to_dom_string, 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,@@ -480,8 +483,20 @@ def write_rust_interface(write_rust_attribute_setter(out, context, interface, attribute)for operation_set in members.operation_sets:- write_rust_operation(- out, context, interface, operation_set.name, operation_set.function, operation_set.overloads[0]+ name = operation_set.name+ if len(operation_set.overloads) == 1:+ write_rust_operation(out, context, interface, name, operation_set.function, operation_set.overloads[0])+ continue+ for overload in operation_set.overloads:+ write_rust_operation(out, context, interface, name, overload.steps_function, overload)+ write_operation_overload_resolution(+ out,+ context,+ interface,+ name,+ operation_set.function,+ [overload.operation for overload in operation_set.overloads],+ [overload.steps_function for overload in operation_set.overloads],)out.write(diff --git a/Meta/Generators/libweb_bindings/rust_members.py b/Meta/Generators/libweb_bindings/rust_members.pyindex a0db833e69c..35cee23bf35 100644--- a/Meta/Generators/libweb_bindings/rust_members.py+++ b/Meta/Generators/libweb_bindings/rust_members.py@@ -69,6 +69,12 @@ class RustOperation:def length(self) -> int:return operation_length(self.operation)+ @property+ def steps_function(self) -> str:+ """The generated function of the steps of the operation, when the operation is one of several overloads that+ the function of the prototype chooses between."""+ return f"{generated_function_stem(self.method)}_steps"+@dataclassclass RustOperationSet:@@ -224,7 +230,14 @@ def rust_members(interface: Interface) -> RustMembers:overload_sets = operation_overload_sets(interface)for name, operations in overload_sets.items():if len(operations) > 1:- fail(f"its operation {name} is overloaded")+ # NB: As for constructors, the IDL names the Rust method of every overload.+ if not all("ImplementedAs" in operation.extended_attributes for operation in operations):+ fail(+ f"its operation {name} is overloaded, and not all of the overloads name their Rust method with "+ "[ImplementedAs]"+ )+ if any(operation.return_type_is_promise() for operation in operations):+ fail(f"its operation {name} is overloaded and returns a promise type")overloads = [RustOperation(operation, method_of(name, operation.extended_attributes)) for operation in operations]diff --git a/Meta/Generators/libweb_bindings/rust_overloads.py b/Meta/Generators/libweb_bindings/rust_overloads.pyindex 7c15b48e620..1fb616d2367 100644--- a/Meta/Generators/libweb_bindings/rust_overloads.py+++ b/Meta/Generators/libweb_bindings/rust_overloads.py@@ -2,8 +2,8 @@## SPDX-License-Identifier: BSD-2-Clause-# The choice between the overloads of a constructor of an interface implemented in Rust, with the overload resolution-# algorithm, https://webidl.spec.whatwg.org/#dfn-overload-resolution-algorithm+# The choice between the overloads of a constructor or of an operation of an interface implemented in Rust, with the+# overload resolution algorithm, https://webidl.spec.whatwg.org/#dfn-overload-resolution-algorithm## The C++ bindings pass the effective overload set to WebIDL::resolve_overload() of# Libraries/LibWeb/WebIDL/OverloadResolution.cpp, which tests the argument at the distinguishing index against the@@ -15,18 +15,27 @@ from dataclasses import dataclassfrom typing import Callablefrom typing import Listfrom typing import Optional+from typing import Sequencefrom typing import TextIO+from typing import Unionfrom Generators.libweb_bindings.context import GenerationContextfrom Generators.libweb_bindings.overload_resolution import EffectiveOverloadItemfrom Generators.libweb_bindings.overload_resolution import Optionalityfrom Generators.libweb_bindings.overload_resolution import compute_the_effective_overload_setfrom Generators.libweb_bindings.overload_resolution import resolve_distinguishing_argument_index+from Generators.libweb_bindings.rust_types import TYPED_ARRAY_NAMESfrom Generators.libweb_bindings.rust_types import UnsupportedByRustBindings+from Generators.libweb_bindings.rust_types import cpp_interface+from Generators.libweb_bindings.rust_types import cpp_interface_name_constant+from Generators.libweb_bindings.rust_types import rust_interface+from Generators.libweb_bindings.rust_types import rust_interface_path+from Utils.webidl_parser import Constructorfrom Utils.webidl_parser import IDLParameterizedTypefrom Utils.webidl_parser import IDLTypefrom Utils.webidl_parser import IDLUnionTypefrom Utils.webidl_parser import Interface+from Utils.webidl_parser import OperationSTRING_TYPES = {"ByteString", "DOMString", "USVString"}INTEGER_TYPES = {@@ -42,32 +51,41 @@ INTEGER_TYPES = {FLOATING_POINT_TYPES = {"float", "double", "unrestricted float", "unrestricted double"}+# What an entry of the effective overload set makes a step do: nothing, select the entry, or select it if a+# condition on the argument holds, which is a Rust expression.+NO_MATCH = None+ALWAYS = ""++@dataclassclass OverloadResolutionStep:description: str# The test of the argument at the distinguishing index, or None for a step that every argument reaches.argument_test: Optional[str]# Whether an entry of the effective overload set with the type and the optionality at the distinguishing index- # makes the step select the entry.- entry_matches: Callable[[IDLType, Optionality], bool]+ # makes the step select the entry: NO_MATCH, ALWAYS, or the condition on the argument under which it does.+ entry_condition: Callable[[IDLType, Optionality], Optional[str]]def is_plain(idl_type: IDLType) -> bool:return not isinstance(idl_type, (IDLUnionType, IDLParameterizedType))-def type_or_flattened_member_matches(idl_type: IDLType, matches: Callable[[IDLType], bool]) -> bool:- """has_overload_with_argument_type_or_subtype_matching() of OverloadResolution.cpp, for one entry."""- if matches(idl_type):- return True+def type_and_flattened_members(idl_type: IDLType) -> List[IDLType]:+ """The types that has_overload_with_argument_type_or_subtype_matching() of OverloadResolution.cpp tests for one+ entry."""if isinstance(idl_type, IDLUnionType):- return any(matches(member_type) for member_type in idl_type.flattened_member_types())- return False+ return [idl_type, *idl_type.flattened_member_types()]+ return [idl_type]+++def type_or_flattened_member_matches(idl_type: IDLType, matches: Callable[[IDLType], bool]) -> bool:+ return any(matches(member_type) for member_type in type_and_flattened_members(idl_type))def overload_resolution_steps(context: GenerationContext) -> List[OverloadResolutionStep]:- """The sub-steps of step 12 of the algorithm that resolve_overload() runs when the argument at the distinguishing- index is not an object that a step for interfaces, buffers, functions or sequences would take, in its order."""+ """The sub-steps of step 12 of the algorithm that resolve_overload() runs, in its order, without the ones for+ functions and sequences and for the type object, which check_type_at_distinguishing_index() keeps out."""def is_dictionary(idl_type: IDLType) -> bool:return is_plain(idl_type) and context.dictionary(idl_type) is not None@@ -90,19 +108,77 @@ def overload_resolution_steps(context: GenerationContext) -> List[OverloadResolureturn any(member_type.nullable for member_type in idl_type.flattened_member_types())return False- def with_members(matches: Callable[[IDLType], bool]) -> Callable[[IDLType, Optionality], bool]:- return lambda idl_type, _: type_or_flattened_member_matches(idl_type, matches)+ def when(matches: bool) -> Optional[str]:+ return ALWAYS if matches else NO_MATCH++ def with_members(matches: Callable[[IDLType], bool]) -> Callable[[IDLType, Optionality], Optional[str]]:+ return lambda idl_type, _: when(type_or_flattened_member_matches(idl_type, matches))++ def implemented_interface(idl_type: IDLType, _: Optionality) -> Optional[str]:+ """The condition under which the platform object that the argument is implements an interface of the type."""+ tests = []+ for member_type in type_and_flattened_members(idl_type):+ if not is_plain(member_type):+ continue+ interface = cpp_interface(member_type, context)+ if interface is not None:+ tests.append(f"implements_cpp_interface(value.as_object(), {cpp_interface_name_constant(interface)})")+ interface = rust_interface(member_type, context)+ if interface is not None:+ wrapper_class = f"<{rust_interface_path(interface)}>::wrapper_class()"+ tests.append(f"is_host_instance_of(&value.as_object(), {wrapper_class})")+ return "\n || ".join(tests) if tests else NO_MATCH++ def typed_array_of_kind(idl_type: IDLType, _: Optionality) -> Optional[str]:+ """The condition under which the typed array that the argument is has the name of a typed array type of the+ type."""+ names = [+ member_type.name+ for member_type in type_and_flattened_members(idl_type)+ if is_plain(member_type) and member_type.name in TYPED_ARRAY_NAMES+ ]+ if not names:+ return NO_MATCH+ if set(names) == TYPED_ARRAY_NAMES:+ return ALWAYS+ kinds = " | ".join(f"TypedArrayKind::{name}" for name in names)+ return (+ "value.as_object().downcast::<TypedArrayBase>()"+ f".is_some_and(|typed_array| matches!(typed_array.kind(), {kinds}))"+ )return [OverloadResolutionStep("The argument is undefined, and an overload has an optional argument there.","value.is_undefined()",- lambda _, optionality: optionality == Optionality.Optional,+ lambda _, optionality: when(optionality == Optionality.Optional),),OverloadResolutionStep("The argument is null or undefined, and an overload takes a nullable type or a dictionary there.","value.is_nullish()",- lambda idl_type, _: nullable_or_dictionary(idl_type),+ lambda idl_type, _: when(nullable_or_dictionary(idl_type)),+ ),+ OverloadResolutionStep(+ "The argument is a platform object, and an overload takes an interface that it implements there.",+ "value.is_object() && value.as_object().is_platform_object()",+ implemented_interface,+ ),+ # NB: resolve_overload() takes a SharedArrayBuffer for an ArrayBuffer here, which the conversion of the+ # argument then rejects.+ OverloadResolutionStep(+ "The argument is an ArrayBuffer, and an overload takes one there.",+ "value.is_object() && value.as_object().downcast::<ArrayBuffer>().is_some()",+ with_members(is_named("ArrayBuffer")),+ ),+ OverloadResolutionStep(+ "The argument is a DataView, and an overload takes one there.",+ "value.is_object() && value.as_object().downcast::<DataView>().is_some()",+ with_members(is_named("DataView")),+ ),+ OverloadResolutionStep(+ "The argument is a typed array, and an overload takes one with its name there.",+ "value.is_object() && value.as_object().downcast::<TypedArrayBase>().is_some()",+ typed_array_of_kind,),OverloadResolutionStep("The argument is an object, and an overload takes a dictionary there.",@@ -147,21 +223,23 @@ def overload_resolution_steps(context: GenerationContext) -> List[OverloadResoluOverloadResolutionStep("An overload takes any there.",None,- lambda idl_type, _: is_named("any")(idl_type),+ lambda idl_type, _: when(is_named("any")(idl_type)),),]def check_type_at_distinguishing_index(idl_type: IDLType, context: GenerationContext, what: str) -> None:"""Rejects the types that the steps of resolve_overload() which are not written out here would take an argument- for: those for platform objects, buffers, functions and sequences, which test the object that the argument is."""+ for: those for functions and sequences, and the type object, which every step for an object takes."""member_types = idl_type.flattened_member_types() if isinstance(idl_type, IDLUnionType) else [idl_type]for member_type in member_types:handled = is_plain(member_type) and (context.dictionary(member_type) is not Noneor context.enumeration(member_type) is not None- or member_type.name in STRING_TYPES | INTEGER_TYPES | FLOATING_POINT_TYPES- or member_type.name in ("boolean", "bigint", "any")+ or cpp_interface(member_type, context) is not None+ or rust_interface(member_type, context) is not None+ or member_type.name in STRING_TYPES | INTEGER_TYPES | FLOATING_POINT_TYPES | TYPED_ARRAY_NAMES+ or member_type.name in ("boolean", "bigint", "any", "ArrayBuffer", "DataView"))if not handled:raise UnsupportedByRustBindings(@@ -176,7 +254,7 @@ def write_resolution_at_distinguishing_index(interface: Interface,entries: List[EffectiveOverloadItem],argument_count: int,- steps_functions: List[str],+ call_for: Callable[[int], str],what: str,) -> None:index = resolve_distinguishing_argument_index(interface, entries, argument_count, context)@@ -184,56 +262,76 @@ def write_resolution_at_distinguishing_index(check_type_at_distinguishing_index(entry.types[index], context, what)out.write(f" let value = vm.argument({index});\n")for step in overload_resolution_steps(context):- # NB: The first entry that a step matches is the one that it keeps.- selected = next(- (entry for entry in entries if step.entry_matches(entry.types[index], entry.optionality_values[index])),- None,- )- if selected is None:+ # NB: The first entry that a step matches is the one that it keeps. An entry that only matches under a+ # condition on the argument leaves the entries after it to the step when the condition does not hold.+ selections = []+ for entry in entries:+ condition = step.entry_condition(entry.types[index], entry.optionality_values[index])+ if condition is NO_MATCH:+ continue+ selections.append((condition, call_for(entry.callable_id)))+ if condition == ALWAYS:+ break+ if not selections:continue- call = f"{steps_functions[selected.callable_id]}(vm, new_target)"if step.argument_test is None:- out.write(f" // {step.description}\n {call}\n")+ assert selections[0][0] == ALWAYS+ out.write(f" // {step.description}\n {selections[0][1]}\n")return- out.write(- f""" // {step.description}+ if selections[0][0] == ALWAYS:+ out.write(+ f""" // {step.description}if {step.argument_test} {{- return {call};+ return {selections[0][1]};}}"""- )+ )+ continue+ out.write(f" // {step.description}\n if {step.argument_test} {{\n")+ for condition, call in selections:+ if condition == ALWAYS:+ out.write(f" return {call};\n")+ else:+ out.write(+ f""" if {condition} {{+ return {call};+ }}+"""+ )+ out.write(" }\n")out.write(" vm.throw_completion(ErrorKind::TypeError, ErrorType::OverloadResolutionFailed, &[])\n")-def write_constructor_overload_resolution(- out: TextIO, context: GenerationContext, interface: Interface, steps_functions: List[str]+def write_overload_resolution(+ out: TextIO,+ context: GenerationContext,+ interface: Interface,+ overloads: Sequence[Union[Constructor, Operation]],+ signature: str,+ documentation: str,+ call_for: Callable[[int], str],+ what: str,) -> None:- """Writes the function that chooses the constructor for the arguments of a construction. The function of the- steps of each constructor is named in the order of the constructors of the interface."""- what = f"The constructors of {interface.name}"+ """Writes the function with the signature that chooses between the overloads for the arguments of a call.+ `call_for` gives the call of the steps of the overload at a position among the overloads."""maximum_argument_count = 0entries_by_argument_count: dict[int, List[EffectiveOverloadItem]] = {}- for entry in compute_the_effective_overload_set(interface.constructors):+ for entry in compute_the_effective_overload_set(overloads):maximum_argument_count = max(maximum_argument_count, len(entry.types))entries_by_argument_count.setdefault(len(entry.types), []).append(entry)out.write(f"""- /// Chooses the constructor for the arguments of a construction, with the steps of the overload resolution- /// algorithm that can select one of the constructors of the interface,- /// https://webidl.spec.whatwg.org/#dfn-overload-resolution-algorithm- fn construct(vm: &Vm, new_target: Gc<Object>) -> ThrowCompletionOr<Value> {{+{documentation} {signature} {{match vm.argument_count().min({maximum_argument_count}) {{""")for argument_count, entries in sorted(entries_by_argument_count.items()):if len(entries) == 1:- out.write(f" {argument_count} => {steps_functions[entries[0].callable_id]}(vm, new_target),\n")+ out.write(f" {argument_count} => {call_for(entries[0].callable_id)},\n")continueout.write(f" {argument_count} => {{\n")- write_resolution_at_distinguishing_index(- out, context, interface, entries, argument_count, steps_functions, what- )+ write_resolution_at_distinguishing_index(out, context, interface, entries, argument_count, call_for, what)out.write(" }\n")out.write(""" _ => vm.throw_completion(ErrorKind::TypeError, ErrorType::OverloadResolutionFailed, &[]),@@ -241,3 +339,49 @@ def write_constructor_overload_resolution(}""")+++def write_constructor_overload_resolution(+ out: TextIO, context: GenerationContext, interface: Interface, steps_functions: List[str]+) -> None:+ """Writes the function that chooses the constructor for the arguments of a construction. The function of the+ steps of each constructor is named in the order of the constructors of the interface."""+ write_overload_resolution(+ out,+ context,+ interface,+ interface.constructors,+ "fn construct(vm: &Vm, new_target: Gc<Object>) -> ThrowCompletionOr<Value>",+ """ /// Chooses the constructor for the arguments of a construction, with the steps of the overload resolution+ /// algorithm that can select one of the constructors of the interface,+ /// https://webidl.spec.whatwg.org/#dfn-overload-resolution-algorithm+""",+ lambda callable_id: f"{steps_functions[callable_id]}(vm, new_target)",+ f"The constructors of {interface.name}",+ )+++def write_operation_overload_resolution(+ out: TextIO,+ context: GenerationContext,+ interface: Interface,+ name: str,+ function: str,+ operations: List[Operation],+ steps_functions: List[str],+) -> None:+ """Writes the native function of an overloaded operation, which chooses the overload for the arguments of a call.+ The function of the steps of each overload is named in the order of the overloads. Like the C++ bindings, it does+ not look at the this value, which the steps of the chosen overload check."""+ write_overload_resolution(+ out,+ context,+ interface,+ operations,+ f"fn {function}(vm: &Vm) -> ThrowCompletionOr<Value>",+ f""" /// Chooses the overload of {name}() for the arguments of a call, with the steps of the overload resolution+ /// algorithm that can select one of them, https://webidl.spec.whatwg.org/#dfn-overload-resolution-algorithm+""",+ lambda callable_id: f"{steps_functions[callable_id]}(vm)",+ f"The overloads of {interface.name}.{name}()",+ )