Skip to content

Truly independent web browser

Meta+LibWeb: Resolve constructor overloads in the Rust bindings

Aliaksandr Kalenikf14fe617960e
diff --git a/Libraries/LibWeb/WebIDL/OverloadResolution.cpp b/Libraries/LibWeb/WebIDL/OverloadResolution.cpp
index 02479fa8630..0a5391903dd 100644
--- a/Libraries/LibWeb/WebIDL/OverloadResolution.cpp
+++ b/Libraries/LibWeb/WebIDL/OverloadResolution.cpp
@@ -71,6 +71,8 @@ static bool has_overload_with_argument_type_or_subtype_matching(EffectiveOverloa
}
// https://webidl.spec.whatwg.org/#es-overloads
+// NB: Meta/Generators/libweb_bindings/rust_overloads.py writes the steps of this function out for the overloads of the
+// interfaces implemented in Rust, so a change to its steps has to be made there as well.
JS::ThrowCompletionOr<ResolvedOverload> resolve_overload(JS::VM& vm, EffectiveOverloadSet& overloads, ReadonlySpan<StringView> dictionary_types)
{
auto is_dictionary = [&dictionary_types](Type const& type) {
diff --git a/Meta/CMake/libweb_generators.cmake b/Meta/CMake/libweb_generators.cmake
index 29f6b3ffa42..1da198c65d8 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_overloads.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"
diff --git a/Meta/Generators/libweb_bindings/rust_bindings.py b/Meta/Generators/libweb_bindings/rust_bindings.py
index 88f95762112..b02c75bd0e1 100644
--- a/Meta/Generators/libweb_bindings/rust_bindings.py
+++ b/Meta/Generators/libweb_bindings/rust_bindings.py
@@ -14,6 +14,8 @@
# A wrapper is a platform object whose host data holds a GC cell of the implementation. Its wrappable slot stays
# empty, so the C++ bindings see a platform object without a C++ implementation object.
+import re
+
from io import StringIO
from typing import Dict
from typing import List
@@ -26,6 +28,7 @@ from Generators.libweb_bindings.overload_resolution import operation_overload_se
from Generators.libweb_bindings.overload_resolution import parameter_list_length
from Generators.libweb_bindings.rust_names import rust_identifier
from Generators.libweb_bindings.rust_names import rust_local_name
+from Generators.libweb_bindings.rust_overloads import write_constructor_overload_resolution
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
@@ -46,6 +49,8 @@ from Utils.webidl_parser import Interface
from Utils.webidl_parser import Module
from Utils.webidl_parser import OperationParameter
+RUST_METHOD_NAME = re.compile(r"[a-z][a-z0-9_]*")
+
# The extended attributes of an interface and of its members that the Rust bindings handle.
SUPPORTED_INTERFACE_EXTENDED_ATTRIBUTES = {"Exposed", "ImplementedIn", "SecureContext", "Experimental"}
SUPPORTED_MEMBER_EXTENDED_ATTRIBUTES = {"NewObject", "SameObject"}
@@ -101,14 +106,22 @@ def check_interface_is_supported(interface: Interface, module: Module, context:
fail("it is iterable or a maplike or setlike")
if interface.static_attributes or interface.static_operations or interface.constants:
fail("it has static members or constants")
- if len(interface.constructors) > 1:
- fail("it has more than one constructor")
+ constructor_attributes = {"ImplementedAs"} if len(interface.constructors) > 1 else set()
for constructor in interface.constructors:
- if constructor.extended_attributes:
+ unsupported_attributes = set(constructor.extended_attributes) - constructor_attributes
+ if unsupported_attributes:
fail(
"the Rust bindings do not handle the extended attributes "
- f"{sorted(constructor.extended_attributes)} of its constructor"
+ f"{sorted(unsupported_attributes)} of its constructor"
)
+ if len(interface.constructors) > 1:
+ # NB: Rust has no overloading, and a name made up from the position of a constructor in the IDL would swap
+ # two overloads silently when the IDL is reordered, so the IDL names the method of every overload.
+ methods = [constructor.extended_attributes.get("ImplementedAs") for constructor in interface.constructors]
+ if not all(method is not None and RUST_METHOD_NAME.fullmatch(method) for method in methods):
+ fail("its constructors are overloaded, and not all of them name their Rust method with [ImplementedAs]")
+ if len(set(methods)) != len(methods):
+ fail(f"its constructors name the same Rust method with [ImplementedAs] more than once: {methods}")
if module.enumerations or module.callback_functions:
fail("its module defines enumerations or callback functions")
@@ -284,6 +297,22 @@ def constructor_description(interface: Interface) -> str:
return f"the constructor of {interface.name}"
+def constructor_method_name(interface: Interface, constructor: Constructor) -> str:
+ """The method of the implementation that the steps of the constructor call. The constructors of an overloaded set
+ name theirs in the IDL."""
+ if len(interface.constructors) > 1:
+ return constructor.extended_attributes["ImplementedAs"]
+ return "construct"
+
+
+def constructor_steps_function(interface: Interface, constructor: Constructor) -> str:
+ """The generated function of the steps of the constructor. The function `construct` is what the entry point of
+ a construction calls: the steps of the only constructor, or the choice between the overloads."""
+ if len(interface.constructors) > 1:
+ return f"{constructor_method_name(interface, constructor)}_steps"
+ return "construct"
+
+
def write_argument_count_check(out: TextIO, function_name: str, required_argument_count: int) -> None:
"""Throws the errors of the C++ bindings for a call with too few arguments, which name the operation, or the
interface for a constructor."""
@@ -356,7 +385,8 @@ def implementation_method_signatures(context: GenerationContext, interface: Inte
signatures = []
for constructor in interface.constructors:
parameters = parameter_list(constructor_description(interface), constructor.parameters)
- signatures.append(f"fn construct(cx: &mut CallContext{parameters}) -> WebIdlResult<Self>")
+ method = constructor_method_name(interface, constructor)
+ signatures.append(f"fn {method}(cx: &mut CallContext{parameters}) -> WebIdlResult<Self>")
for attribute in interface.regular_attributes:
what = f"{interface.name}.{attribute.name}"
signatures.append(
@@ -522,6 +552,9 @@ def write_rust_interface(
for constructor in interface.constructors:
write_rust_constructor(out, context, interface, constructor)
+ if len(interface.constructors) > 1:
+ steps_functions = [constructor_steps_function(interface, constructor) for constructor in interface.constructors]
+ write_constructor_overload_resolution(out, context, interface, steps_functions)
if interface.constructors:
out.write(
f"""
@@ -550,11 +583,12 @@ def write_rust_constructor(
) -> None:
"""The steps of a constructor in the order of the C++ bindings: the prototype of the new object is read from the
new target before the arguments are counted and converted, and the conversions throw in the current realm."""
+ method = constructor_method_name(interface, constructor)
out.write(
- """
+ f"""
/// The constructor steps of the interface, which internally create a new object implementing the interface,
/// https://webidl.spec.whatwg.org/#internally-create-a-new-object-implementing-the-interface
- fn construct(vm: &Vm, new_target: Gc<Object>) -> ThrowCompletionOr<Value> {
+ fn {constructor_steps_function(interface, constructor)}(vm: &Vm, new_target: Gc<Object>) -> ThrowCompletionOr<Value> {{
let realm = vm.current_realm().expect("a construction runs in a realm");
let prototype = prototype_from_new_target(vm, new_target, INTERFACE_NAME)?;
"""
@@ -565,7 +599,7 @@ def write_rust_constructor(
out.write(
f""" let mut cx = CallContext::new(vm, realm);
let implementation =
- Implementation::construct(&mut cx{arguments}).map_err(|exception| exception.throw(vm))?;
+ Implementation::{method}(&mut cx{arguments}).map_err(|exception| exception.throw(vm))?;
let implementation = CELL_CLASS.allocate(vm, implementation);
Ok(Value::from_object(create_wrapper(vm, realm, wrapper_class(), prototype, implementation)))
}}
diff --git a/Meta/Generators/libweb_bindings/rust_overloads.py b/Meta/Generators/libweb_bindings/rust_overloads.py
new file mode 100644
index 00000000000..7c15b48e620
--- /dev/null
+++ b/Meta/Generators/libweb_bindings/rust_overloads.py
@@ -0,0 +1,243 @@
+# Copyright (c) 2026-present, the Ladybird developers.
+#
+# 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 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
+# types of the overloads when it runs. The types are known here, so the Rust bindings get only the tests that can
+# select an overload, in the order of that function and with its results, including where it differs from the
+# algorithm. The steps below follow it one by one; a change to either has to be made to both.
+
+from dataclasses import dataclass
+from typing import Callable
+from typing import List
+from typing import Optional
+from typing import TextIO
+
+from Generators.libweb_bindings.context import GenerationContext
+from Generators.libweb_bindings.overload_resolution import EffectiveOverloadItem
+from Generators.libweb_bindings.overload_resolution import Optionality
+from Generators.libweb_bindings.overload_resolution import compute_the_effective_overload_set
+from Generators.libweb_bindings.overload_resolution import resolve_distinguishing_argument_index
+from Generators.libweb_bindings.rust_types import UnsupportedByRustBindings
+from Utils.webidl_parser import IDLParameterizedType
+from Utils.webidl_parser import IDLType
+from Utils.webidl_parser import IDLUnionType
+from Utils.webidl_parser import Interface
+
+STRING_TYPES = {"ByteString", "DOMString", "USVString"}
+INTEGER_TYPES = {
+ "byte",
+ "octet",
+ "short",
+ "unsigned short",
+ "long",
+ "unsigned long",
+ "long long",
+ "unsigned long long",
+}
+FLOATING_POINT_TYPES = {"float", "double", "unrestricted float", "unrestricted double"}
+
+
+@dataclass
+class 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]
+
+
+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
+ if isinstance(idl_type, IDLUnionType):
+ return any(matches(member_type) for member_type in idl_type.flattened_member_types())
+ return False
+
+
+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."""
+
+ def is_dictionary(idl_type: IDLType) -> bool:
+ return is_plain(idl_type) and context.dictionary(idl_type) is not None
+
+ def is_string(idl_type: IDLType) -> bool:
+ return is_plain(idl_type) and (idl_type.name in STRING_TYPES or context.enumeration(idl_type) is not None)
+
+ def is_numeric(idl_type: IDLType) -> bool:
+ return is_plain(idl_type) and idl_type.name in INTEGER_TYPES | FLOATING_POINT_TYPES
+
+ def is_named(name: str) -> Callable[[IDLType], bool]:
+ return lambda idl_type: is_plain(idl_type) and idl_type.name == name
+
+ def nullable_or_dictionary(idl_type: IDLType) -> bool:
+ if idl_type.nullable or is_dictionary(idl_type):
+ return True
+ # NB: resolve_overload() asks whether the union is a dictionary for each of its members, where the algorithm
+ # asks whether the member is one, so a dictionary inside a union does not match here.
+ if isinstance(idl_type, IDLUnionType):
+ return 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)
+
+ return [
+ OverloadResolutionStep(
+ "The argument is undefined, and an overload has an optional argument there.",
+ "value.is_undefined()",
+ lambda _, optionality: 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),
+ ),
+ OverloadResolutionStep(
+ "The argument is an object, and an overload takes a dictionary there.",
+ "value.is_object()",
+ with_members(is_dictionary),
+ ),
+ OverloadResolutionStep(
+ "The argument is a Boolean, and an overload takes a boolean there.",
+ "value.is_boolean()",
+ with_members(is_named("boolean")),
+ ),
+ OverloadResolutionStep(
+ "The argument is a Number, and an overload takes a numeric type there.",
+ "value.is_number()",
+ with_members(is_numeric),
+ ),
+ OverloadResolutionStep(
+ "The argument is a BigInt, and an overload takes a bigint there.",
+ "value.is_bigint()",
+ with_members(is_named("bigint")),
+ ),
+ OverloadResolutionStep(
+ "An overload takes a string type there.",
+ None,
+ with_members(is_string),
+ ),
+ OverloadResolutionStep(
+ "An overload takes a numeric type there.",
+ None,
+ with_members(is_numeric),
+ ),
+ OverloadResolutionStep(
+ "An overload takes a boolean there.",
+ None,
+ with_members(is_named("boolean")),
+ ),
+ OverloadResolutionStep(
+ "An overload takes a bigint there.",
+ None,
+ with_members(is_named("bigint")),
+ ),
+ OverloadResolutionStep(
+ "An overload takes any there.",
+ None,
+ lambda idl_type, _: 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."""
+ 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 None
+ or 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")
+ )
+ if not handled:
+ raise UnsupportedByRustBindings(
+ f"{what} are told apart by an argument of the type {idl_type}, and the Rust bindings do not resolve "
+ f"overloads by the type {member_type} yet"
+ )
+
+
+def write_resolution_at_distinguishing_index(
+ out: TextIO,
+ context: GenerationContext,
+ interface: Interface,
+ entries: List[EffectiveOverloadItem],
+ argument_count: int,
+ steps_functions: List[str],
+ what: str,
+) -> None:
+ index = resolve_distinguishing_argument_index(interface, entries, argument_count, context)
+ for entry in entries:
+ 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:
+ 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")
+ return
+ out.write(
+ f""" // {step.description}
+ if {step.argument_test} {{
+ return {call};
+ }}
+"""
+ )
+ 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]
+) -> 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}"
+ maximum_argument_count = 0
+ entries_by_argument_count: dict[int, List[EffectiveOverloadItem]] = {}
+ for entry in compute_the_effective_overload_set(interface.constructors):
+ 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> {{
+ 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")
+ continue
+ out.write(f" {argument_count} => {{\n")
+ write_resolution_at_distinguishing_index(
+ out, context, interface, entries, argument_count, steps_functions, what
+ )
+ out.write(" }\n")
+ out.write(
+ """ _ => vm.throw_completion(ErrorKind::TypeError, ErrorType::OverloadResolutionFailed, &[]),
+ }
+ }
+"""
+ )