Skip to content

Truly independent web browser

134 KB
Raw Blame
# Copyright (c) 2026-present, the Ladybird developers.
#
# SPDX-License-Identifier: BSD-2-Clause

# The bindings of the interfaces that their IDL marks [ImplementedIn=Rust]. Their attributes, operations, constructor
# and interface objects are Rust code in libweb_bindings_rust, which this module writes to Bindings/RustBindings.rs,
# and the implementation of each interface is a Rust type in that crate, whose methods the bindings call: one per
# constructor, attribute and operation, with the signatures the generated bindings document. The bindings reach the
# runtime through the embedding API of the libjs_rust crate. LibWeb's C++
# bindings still create the interface object and the interface prototype object of every interface and expose them on
# the globals; for an interface implemented in Rust they call into the Rust bindings to initialize them and to
# construct objects, and they define the class of its wrappers.
#
# 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.
#
# A regular attribute or operation of an interface implemented in C++ can be [ImplementedIn=Rust] as well. Its
# bindings are Rust code that calls a function of the Rust module of the interface's IDL file, which receives the
# wrapper of the object it runs on, and the C++ bindings call into the Rust bindings to define it on the interface
# prototype object.

import textwrap

from io import StringIO
from typing import Callable
from typing import Dict
from typing import List
from typing import Optional
from typing import TextIO
from typing import Tuple

from Generators.libweb_bindings.context import GenerationContext
from Generators.libweb_bindings.includes import GeneratedIncludes
from Generators.libweb_bindings.json_conversions import write_rust_dictionary_json_conversions
from Generators.libweb_bindings.operations import idl_type_is_json_type
from Generators.libweb_bindings.operations import operation_is_default_to_json
from Generators.libweb_bindings.rust_members import RustAttribute
from Generators.libweb_bindings.rust_members import RustConstructor
from Generators.libweb_bindings.rust_members import RustIndexedPropertyGetter
from Generators.libweb_bindings.rust_members import RustIndexedPropertySetter
from Generators.libweb_bindings.rust_members import RustMembers
from Generators.libweb_bindings.rust_members import RustNamedProperties
from Generators.libweb_bindings.rust_members import RustOperation
from Generators.libweb_bindings.rust_members import RustOperationSet
from Generators.libweb_bindings.rust_members import RustPairIterator
from Generators.libweb_bindings.rust_members import rust_members
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_overloads import write_operation_overload_resolution
from Generators.libweb_bindings.rust_structured_serialize import write_rust_serializable_dispatch
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_any_interface_from_js
from Generators.libweb_bindings.rust_to_idl_value import write_dictionary_from_js
from Generators.libweb_bindings.rust_to_idl_value import write_enumeration_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_enumeration_to_js
from Generators.libweb_bindings.rust_to_js_value import write_union_to_js
from Generators.libweb_bindings.rust_types import CPP_PARENT_INTERFACES
from Generators.libweb_bindings.rust_types import UnsupportedByRustBindings
from Generators.libweb_bindings.rust_types import cpp_ancestor
from Generators.libweb_bindings.rust_types import cpp_interface_name_constant
from Generators.libweb_bindings.rust_types import holds_cells
from Generators.libweb_bindings.rust_types import inheriting_interfaces
from Generators.libweb_bindings.rust_types import is_implemented_in_rust
from Generators.libweb_bindings.rust_types import is_promise_type
from Generators.libweb_bindings.rust_types import rust_implemented_members
from Generators.libweb_bindings.rust_types import rust_interface_path
from Generators.libweb_bindings.rust_types import rust_member_definition_entry_point
from Generators.libweb_bindings.rust_types import rust_module_path
from Generators.libweb_bindings.rust_types import rust_parameter_type
from Generators.libweb_bindings.rust_types import rust_type
from Generators.libweb_bindings.rust_usage import DefinitionUsage
from Generators.libweb_bindings.wrappers import wrapper_host_class_name
from Generators.libweb_bindings.wrappers import wrapper_name
from Utils.utils import title_case_to_snake_case
from Utils.webidl_parser import Attribute
from Utils.webidl_parser import Interface
from Utils.webidl_parser import Module
from Utils.webidl_parser import OperationParameter

# The extended attributes of an interface that the Rust bindings handle.
SUPPORTED_INTERFACE_EXTENDED_ATTRIBUTES = {
    # NB: The asynchronous iterator prototype object of the interface has a "return" method.
    "DefinesAsyncIteratorReturn",
    "Experimental",
    "Exposed",
    "ImplementedIn",
    # NB: The C++ bindings expose the interface object under the aliases on the Window, whatever the language of the
    #     interface.
    "LegacyWindowAlias",
    # NB: The C++ bindings define the interface object of such an interface on the namespace object, whatever the
    #     language of the interface.
    "LegacyNamespace",
    # NB: The C++ bindings only leave the interface object of such an interface off the global object.
    "LegacyNoInterfaceObject",
    "LegacyOverrideBuiltIns",
    "NavigatorCompatibilityMode",
    "SecureContext",
    # NB: The implementation implements structured_data::Serializable or structured_data::Transferable, whose steps
    #     crate::html::structured_serialize runs.
    "Serializable",
    "Transferable",
}

# The extended attributes of a namespace that the Rust bindings handle.
SUPPORTED_NAMESPACE_EXTENDED_ATTRIBUTES = {
    "Exposed",
    "ImplementedIn",
    # NB: The implementation finishes the namespace object through its function initialize().
    "WithInitializer",
}


def rust_module_name(interface: Interface) -> str:
    return title_case_to_snake_case(interface.name)


def rust_entry_point_name(interface: Interface, entry_point: str) -> str:
    return f"web_rust_{rust_module_name(interface)}_{entry_point}"


def wrapper_host_class_symbol(interface: Interface) -> str:
    return f"web_bindings_{wrapper_name(interface)}_host_class"


def iterator_host_class_symbol(interface: Interface) -> str:
    return f"web_bindings_{rust_module_name(interface)}_iterator_host_class"


def async_iterator_host_class_symbol(interface: Interface) -> str:
    return f"web_bindings_{rust_module_name(interface)}_async_iterator_host_class"


def interface_name_values(intrinsics: List[Interface]) -> Dict[str, int]:
    """The value of Web::Bindings::InterfaceName for each interface, which the Rust bindings pass the C++ bindings:
    the interfaces in the order of the intrinsics, from 1, as 0 is Unknown."""
    return {interface.name: index for index, interface in enumerate(intrinsics, start=1)}


def check_interface_is_supported(interface: Interface, module: Module, context: GenerationContext) -> None:
    """Raises an error that names what the Rust bindings do not handle yet about the interface as a whole. Its members
    are the business of rust_members(), and its types that of the functions that write the bindings."""

    def fail(message: str) -> None:
        raise UnsupportedByRustBindings(f"{interface.path}: {interface.name} is [ImplementedIn=Rust], but {message}")

    supported_attributes = (
        SUPPORTED_NAMESPACE_EXTENDED_ATTRIBUTES if interface.is_namespace else SUPPORTED_INTERFACE_EXTENDED_ATTRIBUTES
    )
    unsupported_attributes = set(interface.extended_attributes) - supported_attributes
    if unsupported_attributes:
        fail(f"the Rust bindings do not handle its extended attributes {sorted(unsupported_attributes)}")
    if interface.is_callback_interface:
        fail("it is a callback interface")
    parent = context.interfaces.get(interface.parent_name)
    if (
        interface.parent_name
        and not is_implemented_in_rust(parent)
        and interface.parent_name not in CPP_PARENT_INTERFACES
    ):
        fail(
            f"it inherits from {interface.parent_name}, which is neither implemented in Rust nor one of {CPP_PARENT_INTERFACES}"
        )

    for other in inheriting_interfaces(interface, context):
        if not is_implemented_in_rust(other):
            fail(f"{other.name}, which is not implemented in Rust, inherits from it")

    rust_members(interface)


# C++ side


def write_cpp_declaration(out: TextIO, includes: GeneratedIncludes, interface: Interface) -> None:
    if interface.is_namespace:
        includes.add("LibJS/Runtime/Object.h")
        out.write(
            f"""struct {interface.namespace_class} {{
    static void initialize(JS::Realm&, JS::Object&);
}};

"""
        )
        return
    includes.add("LibJS/HostObjectABI.h")
    includes.add("LibJS/Runtime/NativeFunction.h")
    includes.add("LibJS/Runtime/Object.h")
    includes.add("LibWeb/Bindings/InterfaceObject.h")
    includes.add("LibWeb/Export.h")
    out.write(
        f"""// The class of the wrappers of {interface.name}, whose implementation is in Rust, which code outside LibWeb names
// as well when it asks whether an object is a wrapper of the interface.
extern "C" WEB_API JSHostClass const {wrapper_host_class_symbol(interface)};

struct {interface.constructor_class} {{
public:
    static void initialize(JS::Realm&, JS::NativeFunction&);
    static JS::ThrowCompletionOr<GC::Ref<JS::Object>> construct(JS::HostFunction&, JS::FunctionObject&);
}};

struct {interface.prototype_class} {{
public:
    static void initialize(JS::Realm&, JS::Object&);
}};

"""
    )
    if rust_members(interface).pair_iterator is not None:
        out.write(
            f"""// The class of the default iterator objects of {interface.name}, whose cells the Rust bindings create.
extern "C" JSHostClass const {iterator_host_class_symbol(interface)};

struct {interface.name}IteratorPrototype {{
public:
    static void initialize(JS::Realm&, JS::Object&);
}};

"""
        )
    if rust_members(interface).async_iterator is not None:
        out.write(
            f"""// The class of the default asynchronous iterator objects of {interface.name}, whose cells the Rust bindings create.
extern "C" JSHostClass const {async_iterator_host_class_symbol(interface)};

struct {interface.name}AsyncIteratorPrototype {{
public:
    static void initialize(JS::Realm&, JS::Object&);
}};

"""
        )


def write_cpp_named_properties(
    out: TextIO,
    includes: GeneratedIncludes,
    interface: Interface,
    parent_host_class: str,
    named_properties: RustNamedProperties,
) -> None:
    """The legacy platform object functions of a wrapper of an interface that supports named properties, which call the
    entry points of the Rust bindings, and the host class of the wrappers."""
    includes.add("AK/Utf16FlyString.h")
    includes.add("LibWeb/Bindings/PlatformObject.h")
    includes.add("LibWeb/WebIDL/ExceptionOr.h")
    name = wrapper_name(interface)
    legacy_info = f"{name}_legacy_platform_object_info"
    setter = named_properties.setter
    deleter = named_properties.deleter
    info_fields = [
        "    .supports_named_properties = true,\n",
    ]
    if setter is not None:
        info_fields.append("    .has_named_property_setter = true,\n")
    if deleter is not None:
        info_fields.append("    .has_named_property_deleter = true,\n")
    if "LegacyOverrideBuiltIns" in interface.extended_attributes:
        info_fields.append("    .has_legacy_override_built_ins_interface_extended_attribute = true,\n")
    if setter is not None and setter.operation.name:
        info_fields.append("    .named_property_setter_has_identifier = true,\n")
    if deleter is not None and deleter.operation.name:
        info_fields.append("    .named_property_deleter_has_identifier = true,\n")
    info_fields.append(f"    .named_item_value = {name}_named_item_value,\n")
    setter_hooks_and_entry_points = named_property_setter_hooks_and_entry_points(interface, setter)
    info_fields.extend(f"    .{hook} = {name}_{hook},\n" for hook, _ in setter_hooks_and_entry_points)
    if deleter is not None:
        info_fields.append(f"    .delete_value = {name}_delete_value,\n")
    info_fields.append(f"    .supported_property_names = {name}_supported_property_names,\n")

    out.write(
        f"""
}}

static JS::Value {name}_named_item_value(JS::HostObject const& wrapper, WrapperWorld&, JS::Realm& realm, Utf16FlyString const& name)
{{
    JSValue value {{}};
    if (!{named_item_value_entry_point(interface)}(JS::HostABI::vm_to_abi(realm.vm()), &realm, JS::HostABI::object_to_abi(const_cast<JS::HostObject*>(&wrapper)), name.raw_identity(), &value))
        return JS::js_undefined();
    return JS::HostABI::value_from_abi(value);
}}

static Vector<Utf16FlyString> {name}_supported_property_names(JS::HostObject const& wrapper)
{{
    auto& realm = wrapper.shape().realm();
    Vector<Utf16FlyString> names;
    {supported_property_names_entry_point(interface)}(JS::HostABI::vm_to_abi(realm.vm()), &realm, JS::HostABI::object_to_abi(const_cast<JS::HostObject*>(&wrapper)), &names, [](void* names, FlatPtr name) {{
        static_cast<Vector<Utf16FlyString>*>(names)->append(Utf16FlyString::adopt_raw(name));
    }});
    return names;
}}
"""
    )
    for hook, entry_point in setter_hooks_and_entry_points:
        out.write(
            f"""
static WebIDL::ExceptionOr<void> {name}_{hook}(JS::HostObject& wrapper, JS::Realm& realm, Utf16FlyString const& name, JS::Value value)
{{
    TRY(JS::HostABI::completion_from_abi<JS::Value>({entry_point}(JS::HostABI::vm_to_abi(realm.vm()), &realm, JS::HostABI::object_to_abi(&wrapper), name.raw_identity(), JS::HostABI::value_to_abi(value))));
    return {{}};
}}
"""
        )
    if deleter is not None:
        # NB: An anonymous deleter's Rust method reports no failed deletion.
        deletion_result = "NotRelevant" if deleter.operation.name else "DidNotFail"
        out.write(
            f"""
static WebIDL::ExceptionOr<NamedPropertyDeletionResult> {name}_delete_value(JS::HostObject& wrapper, Utf16FlyString const& name)
{{
    auto& realm = wrapper.shape().realm();
    TRY(JS::HostABI::completion_from_abi<JS::Value>({delete_value_entry_point(interface)}(JS::HostABI::vm_to_abi(realm.vm()), &realm, JS::HostABI::object_to_abi(&wrapper), name.raw_identity())));
    return NamedPropertyDeletionResult::{deletion_result};
}}
"""
        )
    out.write(
        f"""
static constexpr LegacyPlatformObjectInfo {legacy_info} {{
{"".join(info_fields)}}};

// The wrappers are legacy platform objects, whose named properties the Rust bindings read, set and delete: their
// implementation is a cell in their host data, not an implementation object in their wrappable slot, so their
// LegacyPlatformObjectInfo gives their supported property names as well.
constexpr JSHostClass {wrapper_host_class_symbol(interface)} = JS::make_host_class(JS_HOST_CLASS_OBJECT, "{interface.name}"sv,
    &{parent_host_class}, &legacy_platform_object_hooks, &{legacy_info},
    platform_object_host_class_flags | JS_HOST_CLASS_NOT_CACHEABLE_FOR_PROPERTY_ABSENCE);
"""
    )


def write_cpp_implementation(
    out: TextIO, includes: GeneratedIncludes, context: GenerationContext, interface: Interface
) -> None:
    if interface.is_namespace:
        includes.add("LibJS/HostClassBuilder.h")
        includes.add("LibJS/Runtime/Realm.h")
        includes.add_binding(interface.implemented_name)
        initialize_namespace = rust_entry_point_name(interface, "initialize_namespace")
        out.write(
            f"""extern "C" void {initialize_namespace}(JSVM*, void* realm, JSObject* object);

void {interface.namespace_class}::initialize(JS::Realm& realm, JS::Object& object)
{{
    {initialize_namespace}(JS::HostABI::vm_to_abi(realm.vm()), &realm, JS::HostABI::object_to_abi(&object));
}}

"""
        )
        return
    includes.add("LibJS/HostClassBuilder.h")
    includes.add("LibJS/Runtime/Error.h")
    includes.add("LibJS/Runtime/HostFunction.h")
    includes.add("LibJS/Runtime/Realm.h")
    includes.add("LibWeb/Bindings/RustInterface.h")
    includes.add_binding(interface.implemented_name)
    parent = context.interfaces.get(interface.parent_name)
    if parent is not None:
        includes.add_binding(parent.implemented_name)
        parent_host_class = (
            wrapper_host_class_symbol(parent) if is_implemented_in_rust(parent) else wrapper_host_class_name(parent)
        )
    else:
        parent_host_class = "web_bindings_rust_interface_wrapper_host_class"
    has_cpp_ancestor = cpp_ancestor(interface, context) is not None
    if has_cpp_ancestor:
        includes.add("LibWeb/Bindings/PlatformObject.h")

    initialize_prototype = rust_entry_point_name(interface, "initialize_prototype")
    initialize_constructor = rust_entry_point_name(interface, "initialize_constructor")
    construct = rust_entry_point_name(interface, "construct")
    # NB: An interface that inherits indexed properties reads them through the entry point of the interface defining them.
    indexed_interface = rust_interface_with_indexed_properties(interface, context)
    supports_indexed_properties = indexed_interface is not None
    has_indexed_property_setter = rust_members(interface).indexed_property_setter is not None
    named_properties = rust_members(interface).named_properties
    if has_indexed_property_setter and inheriting_interfaces(interface, context):
        raise UnsupportedByRustBindings(
            f"{interface.path}: {interface.name} has an indexed property setter and others inherit from it, which the "
            "Rust bindings do not handle yet"
        )
    if named_properties is not None and inheriting_interfaces(interface, context):
        raise UnsupportedByRustBindings(
            f"{interface.path}: {interface.name} supports named properties and others inherit from it, which the "
            "Rust bindings do not handle yet"
        )
    out.write(
        f"""extern "C" {{

// The entry points of the Rust bindings of {interface.name}.
void {initialize_prototype}(JSVM*, void* realm, JSObject* prototype);
void {initialize_constructor}(JSVM*, void* realm, JSObject* constructor);
"""
    )
    if supports_indexed_properties:
        out.write(
            f"bool {item_value_entry_point(indexed_interface)}(JSVM*, void* realm, JSObject* wrapper, size_t index, "
            "JSValue* out_value);\n"
        )
    if has_indexed_property_setter:
        out.writelines(
            f"JSCompletion {entry_point}(JSVM*, void* realm, JSObject* wrapper, u32 index, JSValue value);\n"
            for entry_point in indexed_property_setter_entry_points(interface)
        )
    if named_properties is not None:
        out.write(
            f"bool {named_item_value_entry_point(interface)}(JSVM*, void* realm, JSObject* wrapper, FlatPtr name, "
            "JSValue* out_value);\n"
            f"void {supported_property_names_entry_point(interface)}(JSVM*, void* realm, JSObject* wrapper, "
            "void* names, void (*append)(void* names, FlatPtr name));\n"
        )
        out.writelines(
            f"JSCompletion {entry_point}(JSVM*, void* realm, JSObject* wrapper, FlatPtr name, JSValue value);\n"
            for _, entry_point in named_property_setter_hooks_and_entry_points(interface, named_properties.setter)
        )
        if named_properties.deleter is not None:
            out.write(
                f"JSCompletion {delete_value_entry_point(interface)}(JSVM*, void* realm, JSObject* wrapper, "
                "FlatPtr name);\n"
            )
    if interface.constructors:
        out.write(f"JSCompletion {construct}(JSVM*, JSObject* constructor, JSObject* new_target);\n")
    if has_cpp_ancestor:
        if supports_indexed_properties or named_properties is not None:
            raise UnsupportedByRustBindings(
                f"{interface.path}: {interface.name} supports indexed or named properties and inherits from an "
                "interface implemented in C++, which the Rust bindings do not handle yet"
            )
        indexed_ancestor = cpp_ancestor_with_indexed_properties(interface, context)
        if indexed_ancestor is None:
            out.write(
                f"""
}}

// The wrappers hold the cell of their object as host data and, for an interface that inherits from one implemented in
// C++, the C++ object it owns as their wrappable, which the hooks keep alive.
constexpr JSHostClass {wrapper_host_class_symbol(interface)} = JS::make_host_class(JS_HOST_CLASS_OBJECT, "{interface.name}"sv,
    &{parent_host_class}, &platform_object_hooks, nullptr, platform_object_host_class_flags);
"""
            )
        else:
            legacy_info = f"{wrapper_name(interface)}_legacy_platform_object_info"
            out.write(
                f"""
}}

static constexpr LegacyPlatformObjectInfo {legacy_info} {{
    .supports_indexed_properties = true,
    .item_value = {wrapper_name(indexed_ancestor)}_item_value,
}};

// The wrappers hold the cell of their object as host data and the C++ object it owns as their wrappable, whose indexed
// properties the C++ bindings of the ancestor read.
constexpr JSHostClass {wrapper_host_class_symbol(interface)} = JS::make_host_class(JS_HOST_CLASS_OBJECT, "{interface.name}"sv,
    &{parent_host_class}, &indexed_legacy_platform_object_hooks, &{legacy_info},
    platform_object_host_class_flags | JS_HOST_CLASS_NOT_CACHEABLE_FOR_INDEXED_PROPERTY_ABSENCE);
"""
            )
    elif named_properties is not None:
        write_cpp_named_properties(out, includes, interface, parent_host_class, named_properties)
    elif not supports_indexed_properties:
        out.write(
            f"""
}}

// The wrappers are platform objects with ordinary internal methods: their implementation is a cell in their host data,
// not an implementation object in their wrappable slot, so they need none of the hooks and flags through which a
// wrapper keeps its implementation object alive, and the engine's own property caches apply to them.
constexpr JSHostClass {wrapper_host_class_symbol(interface)} = JS::make_host_class(JS_HOST_CLASS_OBJECT, "{interface.name}"sv,
    &{parent_host_class}, nullptr, nullptr, JS_HOST_CLASS_IS_PLATFORM_OBJECT);
"""
        )
    else:
        includes.add("LibWeb/Bindings/PlatformObject.h")
        legacy_info = f"{wrapper_name(interface)}_legacy_platform_object_info"
        setter_functions = ""
        has_setter_info = ""
        setter_info = ""
        if has_indexed_property_setter:
            includes.add("LibWeb/WebIDL/ExceptionOr.h")
            has_setter_info = "    .has_indexed_property_setter = true,\n"
            for hook, entry_point in zip(
                ("set_value_of_new_indexed_property", "set_value_of_existing_indexed_property"),
                indexed_property_setter_entry_points(interface),
            ):
                function = f"{wrapper_name(interface)}_{hook}"
                setter_functions += f"""static WebIDL::ExceptionOr<void> {function}(JS::HostObject& wrapper, JS::Realm& realm, u32 index, JS::Value value)
{{
    TRY(JS::HostABI::completion_from_abi<JS::Value>({entry_point}(JS::HostABI::vm_to_abi(realm.vm()), &realm, JS::HostABI::object_to_abi(&wrapper), index, JS::HostABI::value_to_abi(value))));
    return {{}};
}}

"""
                setter_info += f"    .{hook} = {function},\n"
        out.write(
            f"""
}}

static Optional<JS::Value> {wrapper_name(interface)}_item_value(JS::HostObject const& wrapper, WrapperWorld&, JS::Realm& realm, size_t index)
{{
    JSValue value {{}};
    if (!{item_value_entry_point(indexed_interface)}(JS::HostABI::vm_to_abi(realm.vm()), &realm, JS::HostABI::object_to_abi(const_cast<JS::HostObject*>(&wrapper)), index, &value))
        return {{}};
    return JS::HostABI::value_from_abi(value);
}}

{setter_functions}static constexpr LegacyPlatformObjectInfo {legacy_info} {{
    .supports_indexed_properties = true,
{has_setter_info}    .item_value = {wrapper_name(interface)}_item_value,
{setter_info}}};

// The wrappers are legacy platform objects, whose indexed properties the Rust bindings read: their implementation is a
// cell in their host data, not an implementation object in their wrappable slot.
constexpr JSHostClass {wrapper_host_class_symbol(interface)} = JS::make_host_class(JS_HOST_CLASS_OBJECT, "{interface.name}"sv,
    &{parent_host_class}, &indexed_legacy_platform_object_hooks, &{legacy_info},
    platform_object_host_class_flags | JS_HOST_CLASS_NOT_CACHEABLE_FOR_INDEXED_PROPERTY_ABSENCE);
"""
        )
    out.write(
        f"""
void {interface.prototype_class}::initialize(JS::Realm& realm, JS::Object& object)
{{
    {initialize_prototype}(JS::HostABI::vm_to_abi(realm.vm()), &realm, JS::HostABI::object_to_abi(&object));
}}

void {interface.constructor_class}::initialize(JS::Realm& realm, JS::NativeFunction& object)
{{
    {initialize_constructor}(JS::HostABI::vm_to_abi(realm.vm()), &realm, JS::HostABI::object_to_abi(&object));
}}

JS::ThrowCompletionOr<GC::Ref<JS::Object>> {interface.constructor_class}::construct([[maybe_unused]] JS::HostFunction& constructor, [[maybe_unused]] JS::FunctionObject& new_target)
{{
"""
    )
    if interface.constructors:
        out.write(
            f"""    auto object = TRY(JS::HostABI::completion_from_abi<JS::Value>({construct}(JS::HostABI::vm_to_abi(constructor.vm()), JS::HostABI::object_to_abi(&constructor), JS::HostABI::object_to_abi(&new_target))));
    return GC::Ref {{ object.as_object() }};
"""
        )
    else:
        out.write(
            f'    return constructor.vm().throw_completion<JS::TypeError>(JS::ErrorType::NotAConstructor, "{interface.name}");\n'
        )
    out.write("}\n\n")
    if rust_members(interface).pair_iterator is not None:
        initialize_iterator_prototype = rust_entry_point_name(interface, "initialize_iterator_prototype")
        out.write(
            f"""extern "C" void {initialize_iterator_prototype}(JSVM*, void* realm, JSObject* prototype);

constexpr JSHostClass {iterator_host_class_symbol(interface)} = JS::make_host_class(JS_HOST_CLASS_OBJECT, "{interface.name}Iterator"sv,
    nullptr, nullptr, nullptr, 0);

void {interface.name}IteratorPrototype::initialize(JS::Realm& realm, JS::Object& object)
{{
    {initialize_iterator_prototype}(JS::HostABI::vm_to_abi(realm.vm()), &realm, JS::HostABI::object_to_abi(&object));
}}

"""
        )
    if rust_members(interface).async_iterator is not None:
        initialize_async_iterator_prototype = rust_entry_point_name(interface, "initialize_async_iterator_prototype")
        out.write(
            f"""extern "C" void {initialize_async_iterator_prototype}(JSVM*, void* realm, JSObject* prototype);

constexpr JSHostClass {async_iterator_host_class_symbol(interface)} = JS::make_host_class(JS_HOST_CLASS_OBJECT, "{interface.name}AsyncIterator"sv,
    nullptr, nullptr, nullptr, 0);

void {interface.name}AsyncIteratorPrototype::initialize(JS::Realm& realm, JS::Object& object)
{{
    {initialize_async_iterator_prototype}(JS::HostABI::vm_to_abi(realm.vm()), &realm, JS::HostABI::object_to_abi(&object));
}}

"""
        )


def write_ensure_web_prototype_declaration(out: TextIO) -> None:
    out.write(
        """
// The interface prototype object and the interface object of an interface implemented in Rust in the realm, for the
// Rust bindings.
extern "C" JSObject* web_bindings_ensure_web_prototype(void* realm, u16 interface_name);
extern "C" JSObject* web_bindings_ensure_web_constructor(void* realm, u16 interface_name);
extern "C" JSObject* web_bindings_ensure_web_iterator_prototype(void* realm, u16 interface_name);

// Defines the unforgeable attributes of an interface implemented in C++ on the wrapper of an object of an interface
// implemented in Rust that inherits from it.
extern "C" void web_bindings_define_unforgeable_attributes(void* realm, JSObject* wrapper, u16 interface_name);
"""
    )


def has_unforgeable_attributes(interface: Interface) -> bool:
    return any("LegacyUnforgeable" in attribute.extended_attributes for attribute in interface.regular_attributes)


def write_ensure_web_prototype_implementation(out: TextIO, intrinsics: List[Interface]) -> None:
    rust_interfaces = [
        interface for interface in intrinsics if is_implemented_in_rust(interface) and not interface.is_namespace
    ]
    # NB: The interface prototype object and the interface object of an interface implemented in Rust have those of the
    #     interface it inherits from as their prototype, which can be an interface implemented in C++.
    cpp_parent_names = {
        interface.parent_name for interface in rust_interfaces if interface.parent_name in CPP_PARENT_INTERFACES
    }
    prototype_interfaces = rust_interfaces + [
        interface for interface in intrinsics if interface.name in cpp_parent_names
    ]

    def write_switch(function: str, interfaces: List[Interface], object_of: Callable[[Interface], str]) -> None:
        out.write(
            f"""
JSObject* {function}(void* realm, u16 interface_name)
{{
    [[maybe_unused]] auto& js_realm = *static_cast<JS::Realm*>(realm);
    switch (static_cast<InterfaceName>(interface_name)) {{
"""
        )
        out.writelines(
            f"""    case InterfaceName::{interface.name}:
        return JS::HostABI::object_to_abi(&{object_of(interface)});
"""
            for interface in interfaces
        )
        out.write(
            """    default:
        VERIFY_NOT_REACHED();
    }
}
"""
        )

    write_switch(
        "web_bindings_ensure_web_prototype",
        prototype_interfaces,
        lambda interface: (
            f'ensure_web_prototype<{interface.prototype_class}>(js_realm, "{interface.namespaced_name}"_utf16_fly_string)'
        ),
    )
    write_switch(
        "web_bindings_ensure_web_constructor",
        prototype_interfaces,
        lambda interface: (
            f'ensure_web_constructor<{interface.prototype_class}>(js_realm, "{interface.namespaced_name}"_utf16_fly_string)'
        ),
    )
    # NB: An interface has a pair iterator or an asynchronously iterable declaration, not both.
    write_switch(
        "web_bindings_ensure_web_iterator_prototype",
        [
            interface
            for interface in rust_interfaces
            if rust_members(interface).pair_iterator is not None or rust_members(interface).async_iterator is not None
        ],
        lambda interface: (
            f'ensure_web_prototype<{interface.name}AsyncIteratorPrototype>(js_realm, "{interface.name}AsyncIterator"_utf16_fly_string)'
            if rust_members(interface).async_iterator is not None
            else f'ensure_web_prototype<{interface.name}IteratorPrototype>(js_realm, "{interface.name}Iterator"_utf16_fly_string)'
        ),
    )

    out.write(
        """
void web_bindings_define_unforgeable_attributes(void* realm, JSObject* wrapper, u16 interface_name)
{
    [[maybe_unused]] auto& js_realm = *static_cast<JS::Realm*>(realm);
    [[maybe_unused]] auto& object = *JS::HostABI::object_from_abi(wrapper);
    switch (static_cast<InterfaceName>(interface_name)) {
"""
    )
    out.writelines(
        f"""    case InterfaceName::{interface.name}:
        {interface.prototype_class}::define_unforgeable_attributes(js_realm, object);
        return;
"""
        for interface in intrinsics
        if interface.name in cpp_parent_names and has_unforgeable_attributes(interface)
    )
    out.write(
        """    default:
        VERIFY_NOT_REACHED();
    }
}
"""
    )


# Rust side


def constructor_description(interface: Interface) -> str:
    return f"the constructor of {interface.name}"


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."""
    if required_argument_count == 1:
        out.write(
            f"""        if vm.argument_count() < 1 {{
            return vm.throw_completion(ErrorKind::TypeError, ErrorType::BadArgCountOne, &[&"{function_name}"]);
        }}
"""
        )
    elif required_argument_count > 1:
        out.write(
            f"""        if vm.argument_count() < {required_argument_count} {{
            return vm.throw_completion(
                ErrorKind::TypeError,
                ErrorType::BadArgCountMany,
                &[&"{function_name}", &{required_argument_count}],
            );
        }}
"""
        )


def write_parameter_conversions(
    out: TextIO, what: str, parameters: List[OperationParameter], context: GenerationContext
) -> None:
    for index, parameter in enumerate(parameters):
        parameter_what = f"the parameter {parameter.name} of {what}"
        unsupported = set(parameter.extended_attributes) - {
            "AllowShared",
            "AllowResizable",
            "Clamp",
            "EnforceRange",
            "LegacyNullToEmptyString",
        }
        if unsupported:
            raise UnsupportedByRustBindings(f"{parameter_what} has the extended attributes {sorted(unsupported)}")
        name = rust_local_name(parameter.name)
        if parameter.variadic:
            # NB: A variadic parameter takes every remaining argument, so it is always the last parameter.
            conversion = rust_to_idl_value(
                parameter.type, parameter.extended_attributes, "argument", parameter.name, context, parameter_what
            )
            keeps_cells_alive = holds_cells(parameter.type, context)
            storage = "MarkedVec::new(vm)" if keeps_cells_alive else "Vec::new()"
            mutability = "" if keeps_cells_alive else "mut "
            out.write(
                f"""        let {mutability}{name} = {storage};
        for index in {index}..vm.argument_count() {{
            let argument = vm.argument(index);
            {name}.push({conversion}?);
        }}
"""
            )
            continue
        conversion = rust_to_idl_value(
            parameter.type,
            parameter.extended_attributes,
            f"argument{index}",
            parameter.name,
            context,
            parameter_what,
            keeps_cells_alive=True,
        )
        out.write(f"        let argument{index} = vm.argument({index});\n")
        if parameter.optional and parameter.default_value is not None:
            out.write(
                f"""        let {name} = if argument{index}.is_undefined() {{
            {rust_default_value(parameter, context, parameter_what)}
        }} else {{
            {conversion}?
        }};
"""
            )
        elif parameter.optional:
            out.write(
                f"""        let {name} = if argument{index}.is_undefined() {{
            None
        }} else {{
            Some({conversion}?)
        }};
"""
            )
        else:
            out.write(f"        let {name} = {conversion}?;\n")


def implementation_method_signatures(
    context: GenerationContext, interface: Interface, members: RustMembers
) -> List[str]:
    """The methods the implementation of the interface defines, which the bindings call."""

    def parameter_list(what: str, parameters: List[OperationParameter]) -> str:
        return "".join(
            f", {rust_identifier(parameter.name)}: {rust_parameter_type(parameter, context, what)}"
            for parameter in parameters
        )

    signatures = []
    for constructor in members.constructors:
        parameters = parameter_list(constructor_description(interface), constructor.constructor.parameters)
        signatures.append(
            f"fn {constructor.method}(cx: &mut CallContext{parameters}) -> WebIdlResult<impl ConstructedObject<Self>>"
        )
    for attribute in members.attributes:
        what = f"{interface.name}.{attribute.attribute.name}"
        if attribute.event_type is not None:
            # NB: The bindings get and set an event handler on the EventTarget that the object owns, unless the IDL
            #     names the method of the setter.
            if attribute.setter_method is not None:
                signatures.append(f"fn {attribute.setter_method}(&self, cx: &mut CallContext, value: Value)")
            continue
        if not attribute.attribute.inherit:
            result_type = (
                "Value"
                if attribute.returns_js_value
                else rust_type(attribute.attribute.type, context, what, is_result=True)
            )
            signatures.append(
                f"fn {attribute.getter_method}(&self, cx: &mut CallContext) -> WebIdlResult<{result_type}>"
            )
        if attribute.setter_method is not None:
            attribute_type = rust_type(attribute.attribute.type, context, what)
            signatures.append(
                f"fn {attribute.setter_method}(&self, cx: &mut CallContext, value: {attribute_type}) -> "
                "WebIdlResult<()>"
            )
    for operation_set in members.operation_sets:
        written_methods = set()
        for overload in operation_set.overloads:
            if overload.is_default_to_json or overload.method in written_methods:
                continue
            written_methods.add(overload.method)
            what = f"{interface.name}.{operation_set.name}()"
            if overload.implementation_parameters is not None:
                parameters = "".join(
                    f", {rust_identifier(parameter.name)}: "
                    + (
                        f"Option<{rust_parameter_type(parameter, context, what)}>"
                        if index == overload.omitted_parameter_index
                        else rust_parameter_type(parameter, context, what)
                    )
                    for index, parameter in enumerate(overload.implementation_parameters)
                )
            else:
                parameters = parameter_list(what, overload.operation.parameters)
            if "CreatesPromise" in overload.operation.extended_attributes:
                signatures.append(
                    f"fn {overload.method}(&self, cx: &mut CallContext, promise: WebIdlPromise{parameters}) -> WebIdlResult<()>"
                )
            else:
                signatures.append(
                    f"fn {overload.method}(&self, cx: &mut CallContext{parameters}) -> "
                    f"WebIdlResult<{rust_type(overload.operation.return_type, context, what, is_result=True)}>"
                )
    if members.stringifier is not None and members.stringifier.defines_method:
        signatures.append(f"fn {members.stringifier.method}(&self, cx: &mut CallContext) -> WebIdlResult<Utf16String>")
    if members.pair_iterator is not None:
        key_type, value_type = pair_iterator_types(context, interface, members.pair_iterator)
        signatures.append(
            f"impl PairIterable with Key = {key_type} and Value = {value_type}: "
            "fn value_pairs_to_iterate_over(target: &Self::Target) -> impl Deref<Target = [(Self::Key, Self::Value)]> + '_"
        )
    if members.setlike is not None:
        signatures.append("impl Setlike: fn set_entries(&self, cx: &CallContext) -> Gc<Set>")
        if members.setlike.writable_operations:
            signatures.append("impl WritableSetlike: fn set_add, fn set_remove, fn set_clear")
    if members.maplike is not None:
        signatures.append("impl Maplike: fn map_entries(&self, cx: &CallContext) -> Gc<Map>")
        if members.maplike.writable_operations:
            signatures.append("impl WritableMaplike: fn map_set, fn map_remove, fn map_clear")
    if members.async_iterator is not None:
        what = f"the asynchronously iterable declaration of {interface.name}"
        parameters = parameter_list(what, members.async_iterator.parameters)
        signatures.append(
            f"fn {members.async_iterator.method}(&self, cx: &mut CallContext{parameters}) -> "
            "WebIdlResult<<Self as AsyncIterable>::IteratorState>"
        )
        signatures.append(
            "impl AsyncIterable: fn get_the_next_iteration_result(cx: &CallContext, state: &Self::IteratorState) -> "
            "WebIdlPromise, fn asynchronous_iterator_return(cx: &CallContext, state: &Self::IteratorState, value: "
            "Value) -> WebIdlPromise"
        )
    if members.indexed_property_getter is not None:
        getter = members.indexed_property_getter.operation
        what = f"{interface.name}.{getter.operation.name}()"
        parameters = parameter_list(what, getter.operation.parameters)
        signatures.append(
            f"fn {getter.method}(&self, cx: &mut CallContext{parameters}) -> "
            f"WebIdlResult<{rust_type(getter.operation.return_type, context, what, is_result=True)}>"
        )
    if members.indexed_property_setter is not None:
        what = f"the indexed property setter of {interface.name}"
        value_type = rust_parameter_type(members.indexed_property_setter.value_parameter, context, what)
        for method in ("set_value_of_new_indexed_property", "set_value_of_existing_indexed_property"):
            signatures.append(
                f"fn {method}(&self, cx: &mut CallContext, index: u32, value: {value_type}) -> WebIdlResult<()>"
            )
    if members.named_properties is not None:
        named_properties = members.named_properties
        getter = named_properties.getter
        if not getter.operation.name:
            what = f"the named property getter of {interface.name}"
            signatures.append(
                f"fn {getter.method}(&self, cx: &mut CallContext, name: Utf16String) -> "
                f"WebIdlResult<{rust_type(getter.operation.return_type, context, what, is_result=True)}>"
            )
        setter = named_properties.setter
        if setter is not None and not setter.operation.name:
            what = f"the named property setter of {interface.name}"
            value_type = rust_parameter_type(setter.operation.parameters[1], context, what)
            signatures.extend(
                f"fn {hook}(&self, cx: &mut CallContext, name: Utf16String, value: {value_type}) -> WebIdlResult<()>"
                for hook, _ in named_property_setter_hooks_and_entry_points(interface, setter)
            )
        deleter = named_properties.deleter
        if deleter is not None and not deleter.operation.name:
            signatures.append(
                f"fn {deleter.method}(&self, cx: &mut CallContext, name: Utf16String) -> WebIdlResult<()>"
            )
        signatures.append("fn supported_property_names(&self, cx: &mut CallContext) -> Vec<Utf16String>")
    for attribute in members.static_attributes:
        what = f"{interface.name}.{attribute.attribute.name}"
        result_type = (
            "Value"
            if attribute.returns_js_value
            else rust_type(attribute.attribute.type, context, what, is_result=True)
        )
        signatures.append(f"fn {attribute.getter_method}(cx: &mut CallContext) -> WebIdlResult<{result_type}>")
    for operation_set in members.static_operation_sets:
        for overload in operation_set.overloads:
            what = f"{interface.name}.{operation_set.name}()"
            parameters = parameter_list(what, overload.operation.parameters)
            if "CreatesPromise" in overload.operation.extended_attributes:
                signatures.append(
                    f"fn {overload.method}(cx: &mut CallContext, promise: WebIdlPromise{parameters}) -> WebIdlResult<()>"
                )
            else:
                signatures.append(
                    f"fn {overload.method}(cx: &mut CallContext{parameters}) -> "
                    f"WebIdlResult<{rust_type(overload.operation.return_type, context, what, is_result=True)}>"
                )
    return signatures


def pair_iterator_types(
    context: GenerationContext, interface: Interface, pair_iterator: RustPairIterator
) -> Tuple[str, str]:
    what = f"the pair iterator of {interface.name}"
    # NB: The iteration steps convert a copy of a pair, which is on the stack where the collector finds its cells.
    return (
        rust_type(pair_iterator.key_type, context, what, is_result=True),
        rust_type(pair_iterator.value_type, context, what, is_result=True),
    )


def write_rust_collection_declaration(
    out: TextIO, context: GenerationContext, interface: Interface, members: RustMembers
) -> None:
    """The value check of the operations that the bindings define for a setlike or maplike declaration."""
    what = f"the value type of the declaration of {interface.name}"
    if members.setlike is not None:
        conversion = rust_to_idl_value(members.setlike.value_type, {}, "value", "value", context, what)
        out.write(
            f"""
    impl crate::bindings::setlike::SetlikeDeclaration for Implementation {{
        fn check_value(vm: &Vm, value: Value) -> ThrowCompletionOr<()> {{
            {conversion}?;
            Ok(())
        }}
    }}
"""
        )
    if members.maplike is not None and "set" in members.maplike.writable_operations:
        conversion = rust_to_idl_value(members.maplike.value_type, {}, "value", "value", context, what)
        out.write(
            f"""
    impl crate::bindings::maplike::MaplikeDeclaration for Implementation {{
        fn check_value(vm: &Vm, value: Value) -> ThrowCompletionOr<()> {{
            {conversion}?;
            Ok(())
        }}
    }}
"""
        )


def write_rust_collection_properties(out: TextIO, members: RustMembers, defined_property_names: list[str]) -> None:
    """Defines the properties of a setlike or maplike declaration on the interface prototype object."""

    def define_writable_operations(module: str, prefix: str, operations: list[str], lengths: dict[str, int]) -> None:
        for name in operations:
            out.write(
                f'        define_operation(vm, realm, prototype, "{name}", '
                f"raw_native!(crate::bindings::{module}::{prefix}_{name}::<Implementation>), {lengths[name]});\n"
            )
        defined_property_names.extend(operations)

    if members.setlike is not None:
        out.write(
            """        crate::bindings::setlike::define_setlike_properties(
            vm,
            realm,
            prototype,
            raw_native!(crate::bindings::setlike::set_size::<Implementation>),
            raw_native!(crate::bindings::setlike::set_iterator_entries::<Implementation>),
            raw_native!(crate::bindings::setlike::set_for_each::<Implementation>),
            raw_native!(crate::bindings::setlike::set_has::<Implementation>),
            raw_native!(crate::bindings::setlike::set_iterator_values::<Implementation>),
        );
"""
        )
        defined_property_names.extend(members.setlike.function_names)
        define_writable_operations(
            "setlike", "set", members.setlike.writable_operations, {"add": 1, "delete": 1, "clear": 0}
        )
    if members.maplike is not None:
        out.write(
            """        crate::bindings::maplike::define_maplike_properties(
            vm,
            realm,
            prototype,
            raw_native!(crate::bindings::maplike::map_size::<Implementation>),
            raw_native!(crate::bindings::maplike::map_iterator_entries::<Implementation>),
            raw_native!(crate::bindings::maplike::map_iterator_keys::<Implementation>),
            raw_native!(crate::bindings::maplike::map_iterator_values::<Implementation>),
            raw_native!(crate::bindings::maplike::map_for_each::<Implementation>),
            raw_native!(crate::bindings::maplike::map_get::<Implementation>),
            raw_native!(<Implementation as crate::bindings::maplike::Maplike>::has),
        );
"""
        )
        defined_property_names.extend(members.maplike.function_names)
        define_writable_operations(
            "maplike", "map", members.maplike.writable_operations, {"set": 2, "delete": 1, "clear": 0}
        )


def write_rust_pair_iterator(out: TextIO, interface: Interface) -> None:
    """The classes of the default iterator objects of the interface, and the steps of its iterator prototype object,
    which the bindings runtime implements for every interface with a pair iterator,
    https://webidl.spec.whatwg.org/#es-iterator-prototype-object"""
    out.write(
        f"""
    /// The class of the cells of the default iterator objects of the interface.
    static ITERATOR_CELL_CLASS: EmbedderClass<DefaultIterator<Implementation>> = EmbedderClass::new("{interface.name} Iterator");

    unsafe extern "C" {{
        static {iterator_host_class_symbol(interface)}: JSHostClass;
    }}

    impl DefaultIteratorClasses for Implementation {{
        const ITERATOR_CELL_CLASS: &'static EmbedderClass<DefaultIterator<Self>> = &ITERATOR_CELL_CLASS;

        fn iterator_class() -> &'static JSHostClass {{
            // SAFETY: LibWeb defines the class of the default iterator objects as constant data.
            unsafe {{ &{iterator_host_class_symbol(interface)} }}
        }}
    }}

    /// The steps of {interface.name}IteratorPrototype::initialize() of LibWeb's C++ bindings.
    ///
    /// # Safety
    ///
    /// The pointers must be the VM, a realm and the iterator prototype object of the realm.
    #[unsafe(no_mangle)]
    pub unsafe extern "C" fn {rust_entry_point_name(interface, "initialize_iterator_prototype")}(
        vm: *mut c_void,
        realm: *mut c_void,
        prototype: *mut c_void,
    ) {{
        // SAFETY: The caller passes live pointers.
        let (vm, realm, prototype) = unsafe {{ entry_point_arguments(vm, realm, prototype) }};
        define_operation(vm, realm, prototype, "next", raw_native!(iterator_next::<Implementation>), 0);
        define_to_string_tag(vm, prototype, "{interface.name} Iterator");
    }}
"""
    )


def write_rust_async_iterator(out: TextIO, context: GenerationContext, interface: Interface) -> None:
    """The classes of the default asynchronous iterator objects of the interface, the steps of its asynchronous
    iterator prototype object, which the bindings runtime implements for every interface with a value asynchronously
    iterable declaration, https://webidl.spec.whatwg.org/#es-asynchronous-iterator-prototype-object, and the steps of
    its "values" method, https://webidl.spec.whatwg.org/#es-asynchronous-iterable"""
    async_iterator = rust_members(interface).async_iterator
    assert async_iterator is not None
    define_return = ""
    if async_iterator.defines_return:
        define_return = (
            '        define_operation(vm, realm, prototype, "return", '
            "raw_native!(async_iterator_return::<Implementation>), 1);\n"
        )
    out.write(
        f"""
    /// The class of the cells of the default asynchronous iterator objects of the interface.
    static ASYNC_ITERATOR_CELL_CLASS: EmbedderClass<DefaultAsyncIterator<Implementation>> = EmbedderClass::new("{interface.name} AsyncIterator");

    unsafe extern "C" {{
        static {async_iterator_host_class_symbol(interface)}: JSHostClass;
    }}

    impl DefaultAsyncIteratorClasses for Implementation {{
        const ASYNC_ITERATOR_CELL_CLASS: &'static EmbedderClass<DefaultAsyncIterator<Self>> = &ASYNC_ITERATOR_CELL_CLASS;

        fn async_iterator_class() -> &'static JSHostClass {{
            // SAFETY: LibWeb defines the class of the default asynchronous iterator objects as constant data.
            unsafe {{ &{async_iterator_host_class_symbol(interface)} }}
        }}
    }}

    /// The steps of {interface.name}AsyncIteratorPrototype::initialize() of LibWeb's C++ bindings.
    ///
    /// # Safety
    ///
    /// The pointers must be the VM, a realm and the asynchronous iterator prototype object of the realm.
    #[unsafe(no_mangle)]
    pub unsafe extern "C" fn {rust_entry_point_name(interface, "initialize_async_iterator_prototype")}(
        vm: *mut c_void,
        realm: *mut c_void,
        prototype: *mut c_void,
    ) {{
        // SAFETY: The caller passes live pointers.
        let (vm, realm, prototype) = unsafe {{ entry_point_arguments(vm, realm, prototype) }};
        define_to_string_tag(vm, prototype, "{interface.name} AsyncIterator");
        define_operation(vm, realm, prototype, "next", raw_native!(async_iterator_next::<Implementation>), 0);
{define_return}    }}

    /// The "values" and %Symbol.asyncIterator% methods of the interface prototype object,
    /// https://webidl.spec.whatwg.org/#es-asynchronous-iterable
    fn {async_iterator.function}(vm: &Vm) -> ThrowCompletionOr<Value> {{
        // 1. Let jsValue be ? ToObject(this value).
        // 2. If jsValue is a platform object, then perform a security check, passing jsValue, "values", and "method".
        // 3. If jsValue does not implement definition, then throw a TypeError.
        let (implementation, mut cx) = this_implementation(vm, "values", SecurityCheckType::Method)?;

        // 4. Let idlArgs be the result of converting arguments for an asynchronous iterator method given arguments.
"""
    )
    write_parameter_conversions(
        out, f"the asynchronously iterable declaration of {interface.name}", async_iterator.parameters, context
    )
    arguments = "".join(f", {rust_local_name(parameter.name)}" for parameter in async_iterator.parameters)
    out.write(
        f"""
        // 5. Let iterator be a newly created default asynchronous iterator object for definition with jsValue as its
        //    target, "value" as its kind, and is finished set to false.
        // 6. Run the asynchronous iterator initialization steps for definition with jsValue, iterator, and idlArgs, if
        //    any such steps exist.
        let state = Implementation::{async_iterator.method}(&implementation, &mut cx{arguments})
            .map_err(|exception| exception.throw_in_current_realm(cx.vm()))?;

        // 7. Return iterator.
        Ok(create_default_async_iterator::<Implementation>(&cx, state))
    }}
"""
    )


# The context of an attribute or an operation that is [NeedsCallerRealm], whose results are created in the current realm.
CALLER_REALM_CONTEXT = (
    '        let mut cx = CallContext::new(vm, vm.current_realm().expect("a native function runs in a realm"));\n'
)

RUST_BINDINGS_IMPORTS = """    #![allow(unused_imports)]

    use core::ffi::c_void;

    use ak::{Utf16FlyString, Utf16String};
    use libjs_rust::api::{
        ArrayBuffer, DataView, EmbedderClass, ErrorKind, ErrorType, FunctionObject, Gc, JSHostClass, MarkedVec,
        Object, PropertyKey, RawNativeFunctionResult, ShouldThrowExceptions, ThrowCompletionOr, TypedArrayBase, TypedArrayKind, Value, Vm,
        is_host_instance_of, raw_native,
    };

    use crate::bindings::conversions::{
        ArrayBufferView, BufferSource, BufferSourceRules, ByteString, CppInterface, EmptyDictionary, FromJs, ToJs, UsvString,
        frozen_array_to_js, implements_cpp_interface, iterator_method, record_from_js, record_to_js, rooted_sequence_to_js,
        sequence_from_js, sequence_to_js, to_array_buffer_view, to_boolean, to_buffer_source, to_byte_string, 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_clamping, to_long_long_enforcing_range, to_object, to_promise, to_shared_array_buffer, to_typed_array,
        to_unrestricted_double, to_unrestricted_float, to_unsigned_long, to_unsigned_long_clamping, to_unsigned_short,
        to_unsigned_long_enforcing_range,
        to_unsigned_long_long, to_unsigned_long_long_enforcing_range, to_usv_string, to_window_proxy,
        window_proxy_from_object, window_proxy_to_js,
    };
    use crate::bindings::interface::{
        Inherits, Interface, Ref, Wrapped, cell_class, construct_arguments, construct_wrapper, create_dictionary_object,
        define_attribute, define_cached_attribute, define_constants, define_indexed_properties_iterator,
        define_interface_object_properties, define_operation, define_to_string_tag, define_unimplemented_property,
        define_value_iterator_properties, entry_point_arguments, implementation_if, implementation_of,
        SecurityCheckType, prototype_from_new_target, realm_is_secure_context, realm_is_window, set_dictionary_member,
        set_interface_prototype_object_prototype, this_cpp_object, this_object, to_interface,
    };
    use crate::bindings::async_iterable::{
        AsyncIterable, DefaultAsyncIterator, DefaultAsyncIteratorClasses, async_iterator_next, async_iterator_return,
        create_default_async_iterator, define_async_iterator_properties,
    };
    use crate::bindings::iterable::{
        DefaultIterator, DefaultIteratorClasses, define_pair_iterator_properties, entries, for_each, iterator_next, keys,
        values,
    };
    use crate::bindings::callback::{CallbackFunction, CallbackInterface, PromiseCallbackFunction};
    use crate::bindings::event_target::{event_handler_attribute, set_event_handler_attribute};
    use crate::bindings::global_object::window_or_worker_global_scope_from_global_object;
    use crate::bindings::promise::{WebIdlPromise, create_rejected_promise};
    use crate::bindings::{CallContext, WebIdlResult, with_custom_element_reactions};
"""


def write_rust_operation_set(
    out: TextIO,
    context: GenerationContext,
    interface: Interface,
    operation_set: RustOperationSet,
    write_steps: Callable[[TextIO, GenerationContext, Interface, str, str, RustOperation], None],
) -> None:
    """The native function of an operation, which `write_steps` writes for one overload, and which chooses between the
    overloads of an overloaded operation."""
    name = operation_set.name
    if len(operation_set.overloads) == 1:
        write_steps(out, context, interface, name, operation_set.function, operation_set.overloads[0])
        return
    for overload in operation_set.overloads:
        write_steps(out, context, interface, name, overload.steps_function, overload)
    returns_promise = operation_set.overloads[0].operation.return_type_is_promise()
    resolution = operation_set.function
    if returns_promise:
        resolution = f"{operation_set.function.removesuffix('_function')}_overload_resolution"
    write_operation_overload_resolution(
        out,
        context,
        interface,
        name,
        resolution,
        [overload.operation for overload in operation_set.overloads],
        [overload.steps_function for overload in operation_set.overloads],
    )
    if returns_promise:
        out.write(
            f"""
    fn {operation_set.function}(vm: &Vm) -> ThrowCompletionOr<Value> {{
        // An exception that the overload resolution of an operation with a promise type throws rejects a new promise,
        // https://webidl.spec.whatwg.org/#dfn-create-operation-function
        {resolution}(vm).or_else(|throw| {{
            let realm = vm.current_realm().expect("a native function runs in a realm");
            Ok(Value::from_object(create_rejected_promise(vm, realm, throw.value()).promise()))
        }})
    }}
"""
        )


def write_rust_attributes(
    out: TextIO, context: GenerationContext, interface: Interface, attributes: List[RustAttribute]
) -> None:
    """The native functions of the getters and the setters of the attributes."""
    for attribute in attributes:
        name = attribute.attribute.name
        if attribute.event_type is not None:
            write_rust_event_handler_attribute(out, attribute)
            continue
        conversion = (
            "Ok(result)"
            if attribute.returns_js_value
            else rust_to_js_value(attribute.attribute.type, "result", "&cx", context, f"{interface.name}.{name}")
        )
        call = f"Implementation::{attribute.getter_method}(&implementation, &mut cx)"
        if attribute.attribute.inherit:
            call = inherited_attribute_getter_call(context, interface, attribute)
        this_check = f'this_implementation(vm, "{name}", SecurityCheckType::Getter)?'
        if is_promise_type(attribute.attribute.type) and not attribute.attribute.type.nullable:
            # https://webidl.spec.whatwg.org/#dfn-attribute-getter
            this_check = f"""match this_implementation(vm, "{name}", SecurityCheckType::Getter) {{
            Ok(this) => this,
            // If the attribute's type is a promise type, a this value that does not implement the interface rejects
            // a new promise.
            Err(throw) => {{
                let realm = vm.current_realm().expect("a native function runs in a realm");
                return Ok(Value::from_object(create_rejected_promise(vm, realm, throw.value()).promise()));
            }}
        }}"""
        receiver = "(implementation, mut cx)"
        caller_realm_context = ""
        if "NeedsCallerRealm" in attribute.attribute.extended_attributes:
            receiver = "(implementation, _)"
            caller_realm_context = CALLER_REALM_CONTEXT
        out.write(
            f"""
    pub(super) fn {attribute.getter_function}(vm: &Vm) -> ThrowCompletionOr<Value> {{
        let {receiver} = {this_check};
{caller_realm_context}        let result = {call}
            .map_err(|exception| exception.throw_in_current_realm(cx.vm()))?;
        {conversion}
    }}
"""
        )
        if attribute.setter_method is not None:
            write_rust_attribute_setter(out, context, interface, attribute)
        elif attribute.put_forwards is not None:
            write_rust_put_forwards_setter(out, attribute)


def write_rust_interface(
    out: TextIO, context: GenerationContext, module: Module, interface: Interface, interface_name_value: int
) -> None:
    implementation = rust_interface_path(interface)
    members = rust_members(interface)
    parent = context.interfaces.get(interface.parent_name)
    if parent is None:
        inherited_interface_name = "None"
    elif is_implemented_in_rust(parent):
        inherited_interface_name = f"Some(super::{rust_module_name(parent)}::INTERFACE_NAME)"
    else:
        inherited_interface_name = f"Some({cpp_interface_name_constant(parent)})"
    cpp_ancestor = parent
    while cpp_ancestor is not None and is_implemented_in_rust(cpp_ancestor):
        cpp_ancestor = context.interfaces.get(cpp_ancestor.parent_name)
    unforgeable_attributes_interface = (
        f"Some({cpp_interface_name_constant(cpp_ancestor)})"
        if cpp_ancestor is not None and has_unforgeable_attributes(cpp_ancestor)
        else "None"
    )
    method_documentation = "".join(
        f"/// - `{signature}`\n" for signature in implementation_method_signatures(context, interface, members)
    )
    out.write(
        f"""
/// The bindings of {interface.name}, which call these methods of its implementation, {implementation}:
{method_documentation}pub(crate) mod {rust_module_name(interface)} {{
{RUST_BINDINGS_IMPORTS}
    use {implementation} as Implementation;

    /// Web::Bindings::InterfaceName::{interface.name}.
    pub(crate) const INTERFACE_NAME: u16 = {interface_name_value};

    /// The class of the cells of the objects of the interface.
    static CELL_CLASS: EmbedderClass<Wrapped<Implementation>> = cell_class("{interface.name}");

    unsafe extern "C" {{
        static {wrapper_host_class_symbol(interface)}: JSHostClass;
    }}

    impl Interface for Implementation {{
        const CELL_CLASS: &'static EmbedderClass<Wrapped<Self>> = &CELL_CLASS;
        const INTERFACE_NAME: u16 = INTERFACE_NAME;
        const NAME: &'static str = "{interface.namespaced_name}";
        const UNFORGEABLE_ATTRIBUTES_INTERFACE: Option<u16> = {unforgeable_attributes_interface};

        fn wrapper_class() -> &'static JSHostClass {{
            // SAFETY: LibWeb defines the class of the wrappers as constant data.
            unsafe {{ &{wrapper_host_class_symbol(interface)} }}
        }}
    }}

"""
    )
    write_this_implementation(out, context, interface)

    defined_property_names: List[str] = []
    recorded_unimplemented_names: List[str] = []

    if members.constants:
        constants = "".join(f'        ("{constant.name}", {constant.value}.0),\n' for constant in members.constants)
        out.write(
            f"""
    /// The constants of the interface, which its interface object and its interface prototype object both have.
    static CONSTANTS: [(&str, f64); {len(members.constants)}] = [
{constants}    ];
"""
        )

    write_rust_attributes(out, context, interface, members.attributes)

    if interface.name == "CSSStyleProperties":
        write_css_property_accessors(out)

    for operation_set in members.operation_sets:
        if len(operation_set.overloads) == 1 and operation_set.overloads[0].is_default_to_json:
            write_default_to_json(out, context, interface, operation_set.function)
            continue
        write_rust_operation_set(out, context, interface, operation_set, write_rust_operation)

    if members.stringifier is not None:
        write_rust_stringifier(out, members.stringifier.function, members.stringifier.method)

    if members.indexed_property_getter is not None:
        getter = members.indexed_property_getter.operation
        if getter.operation.name:
            getter_set = RustOperationSet(getter.operation.name, [getter])
            write_rust_operation(out, context, interface, getter_set.name, getter_set.function, getter)
        write_rust_item_value(out, context, interface, members.indexed_property_getter)

    if members.indexed_property_setter is not None:
        write_rust_indexed_property_setter(out, context, interface, members.indexed_property_setter)

    if members.named_properties is not None:
        write_rust_named_properties(out, context, interface, members.named_properties)

    if members.pair_iterator is not None:
        write_rust_pair_iterator(out, interface)

    write_rust_collection_declaration(out, context, interface, members)

    if members.async_iterator is not None:
        write_rust_async_iterator(out, context, interface)

    for attribute in members.static_attributes:
        write_rust_static_attribute_getter(out, context, interface, attribute)

    for operation_set in members.static_operation_sets:
        write_rust_operation_set(out, context, interface, operation_set, write_rust_static_operation)

    out.write(
        f"""
    /// The steps of {interface.prototype_class}::initialize() of LibWeb's C++ bindings.
    ///
    /// # Safety
    ///
    /// The pointers must be the VM, a realm and the interface prototype object of the realm.
    #[unsafe(no_mangle)]
    pub unsafe extern "C" fn {rust_entry_point_name(interface, "initialize_prototype")}(
        vm: *mut c_void,
        realm: *mut c_void,
        prototype: *mut c_void,
    ) {{
        // SAFETY: The caller passes live pointers.
        let (vm, realm, prototype) = unsafe {{ entry_point_arguments(vm, realm, prototype) }};
        set_interface_prototype_object_prototype(vm, realm, prototype, {inherited_interface_name});
"""
    )
    # NB: The properties are defined in the order of the C++ bindings: the attributes, the operations, the operations
    #     that are not implemented, then the constants.
    for attribute in members.attributes_in_order:
        if isinstance(attribute, str):
            out.write(f'        define_unimplemented_property(vm, prototype, "{attribute}");\n')
            recorded_unimplemented_names.append(attribute)
            continue
        name = attribute.attribute.name
        getter = f"raw_native!({attribute.getter_function})"
        is_secure_context_only = "SecureContext" in attribute.attribute.extended_attributes
        if attribute.is_cached:
            definition = f'define_cached_attribute(vm, realm, prototype, "{name}", {getter});'
            out.write(
                member_exposure_definition(
                    definition,
                    secure_context_only=is_secure_context_only,
                    exposure_condition=attribute.exposure_condition,
                )
            )
            defined_property_names.append(name)
            continue
        has_setter = not attribute.attribute.readonly or attribute.put_forwards is not None
        setter = f"raw_native!({attribute.setter_function})" if has_setter else "None"
        definition = f'define_attribute(vm, realm, prototype, "{name}", {getter}, {setter});'
        out.write(
            member_exposure_definition(
                definition, secure_context_only=is_secure_context_only, exposure_condition=attribute.exposure_condition
            )
        )
        defined_property_names.append(name)
    if interface.name == "CSSStyleProperties":
        out.write(
            "        Implementation::define_property_accessors(vm, realm, prototype, property_getter, property_setter);\n"
        )
    for operation_set in members.operation_sets:
        name = operation_set.name
        function = operation_set.function
        length = operation_set.length
        definition = f'define_operation(vm, realm, prototype, "{name}", raw_native!({function}), {length});'
        out.write(
            member_exposure_definition(
                definition,
                secure_context_only=operation_set.is_secure_context_only,
                exposure_condition=operation_set.exposure_condition,
            )
        )
        defined_property_names.append(name)
    for name in members.unimplemented_operation_names:
        out.write(f'        define_unimplemented_property(vm, prototype, "{name}");\n')
        recorded_unimplemented_names.append(name)
    if members.stringifier is not None:
        function = members.stringifier.function
        definition = f'define_operation(vm, realm, prototype, "toString", raw_native!({function}), 0);'
        out.write(member_exposure_definition(definition, exposure_condition=members.stringifier.exposure_condition))
        defined_property_names.append("toString")
    if members.indexed_property_getter is not None:
        getter = members.indexed_property_getter.operation
        if getter.operation.name:
            getter_set = RustOperationSet(getter.operation.name, [getter])
            out.write(
                f'        define_operation(vm, realm, prototype, "{getter_set.name}", raw_native!({getter_set.function}), '
                f"{getter_set.length});\n"
            )
            defined_property_names.append(getter_set.name)
        out.write("        define_indexed_properties_iterator(vm, realm, prototype);\n")
        if members.indexed_property_getter.has_value_iterator:
            out.write("        define_value_iterator_properties(vm, realm, prototype);\n")
    if members.pair_iterator is not None:
        out.write(
            """        define_pair_iterator_properties(
            vm,
            realm,
            prototype,
            raw_native!(entries::<Implementation>),
            raw_native!(for_each::<Implementation>),
            raw_native!(keys::<Implementation>),
            raw_native!(values::<Implementation>),
        );
"""
        )
        defined_property_names.extend(members.pair_iterator.function_names)
    write_rust_collection_properties(out, members, defined_property_names)
    if members.async_iterator is not None:
        out.write(
            f"""        define_async_iterator_properties(
            vm,
            realm,
            prototype,
            raw_native!({members.async_iterator.function}),
            {members.async_iterator.length},
        );
"""
        )
        defined_property_names.append("values")
    if members.constants:
        out.write("        define_constants(vm, prototype, &CONSTANTS);\n")
        defined_property_names.extend(constant.name for constant in members.constants)
    # NB: A member that rust_members() accepts and nothing above defines would be missing from the prototype without
    #     any error, so the two are compared.
    assert defined_property_names == members.property_names(), (
        f"{interface.name}: the bindings define {defined_property_names}, its members are {members.property_names()}"
    )
    assert recorded_unimplemented_names == members.unimplemented_property_names()
    out.write(
        f"""        define_to_string_tag(vm, prototype, "{interface.namespaced_name}");
    }}

    /// The steps of {interface.constructor_class}::initialize() of LibWeb's C++ bindings.
    ///
    /// # Safety
    ///
    /// The pointers must be the VM, a realm and the interface object of the realm.
    #[unsafe(no_mangle)]
    pub unsafe extern "C" fn {rust_entry_point_name(interface, "initialize_constructor")}(
        vm: *mut c_void,
        realm: *mut c_void,
        constructor: *mut c_void,
    ) {{
        // SAFETY: The caller passes live pointers.
        let (vm, realm, constructor) = unsafe {{ entry_point_arguments(vm, realm, constructor) }};
        define_interface_object_properties(vm, realm, constructor, "{interface.name}", {members.constructor_length}, INTERFACE_NAME, {inherited_interface_name});
"""
    )
    if members.constants:
        out.write("        define_constants(vm, constructor, &CONSTANTS);\n")
    for attribute in members.static_attributes:
        definition = (
            f'define_attribute(vm, realm, constructor, "{attribute.attribute.name}", '
            f"raw_native!({attribute.getter_function}), None);"
        )
        out.write(
            member_exposure_definition(
                definition,
                secure_context_only="SecureContext" in attribute.attribute.extended_attributes,
                exposure_condition=attribute.exposure_condition,
            )
        )
    for operation_set in members.static_operation_sets:
        name = operation_set.name
        definition = (
            f'define_operation(vm, realm, constructor, "{name}", raw_native!({operation_set.function}), '
            f"{operation_set.length});"
        )
        out.write(
            member_exposure_definition(
                definition,
                secure_context_only=operation_set.is_secure_context_only,
                exposure_condition=operation_set.exposure_condition,
            )
        )
    out.write("    }\n")

    for constructor in members.constructors:
        write_rust_constructor(out, context, interface, constructor)
    if len(members.constructors) > 1:
        steps_functions = [constructor.steps_function for constructor in members.constructors]
        write_constructor_overload_resolution(out, context, interface, steps_functions)
    if members.constructors:
        out.write(
            f"""
    /// {interface.constructor_class}::construct() of LibWeb's C++ bindings.
    ///
    /// # Safety
    ///
    /// The pointers must be the VM, the interface object and the new target of a construction.
    #[unsafe(no_mangle)]
    pub unsafe extern "C" fn {rust_entry_point_name(interface, "construct")}(
        vm: *mut c_void,
        _constructor: *mut c_void,
        new_target: *mut c_void,
    ) -> RawNativeFunctionResult {{
        // SAFETY: The caller passes the VM and the new target.
        let (vm, new_target) = unsafe {{ construct_arguments(vm, new_target) }};
        RawNativeFunctionResult::from_completion(construct(vm, new_target))
    }}
"""
        )
    out.write("}\n")


def namespace_function_signatures(context: GenerationContext, interface: Interface, members: RustMembers) -> List[str]:
    """The functions the implementation of the namespace defines, which the bindings call."""
    signatures = []
    for attribute in members.attributes:
        what = f"{interface.name}.{attribute.attribute.name}"
        result_type = (
            "Value"
            if attribute.returns_js_value
            else rust_type(attribute.attribute.type, context, what, is_result=True)
        )
        signatures.append(f"fn {attribute.getter_method}(cx: &mut CallContext) -> WebIdlResult<{result_type}>")
    for operation_set in members.operation_sets:
        for overload in operation_set.overloads:
            what = f"{interface.name}.{operation_set.name}()"
            parameters = "".join(
                f", {rust_identifier(parameter.name)}: {rust_parameter_type(parameter, context, what)}"
                for parameter in overload.operation.parameters
            )
            signatures.append(
                f"fn {overload.method}(cx: &mut CallContext{parameters}) -> "
                f"WebIdlResult<{rust_type(overload.operation.return_type, context, what, is_result=True)}>"
            )
    if "WithInitializer" in interface.extended_attributes:
        signatures.append("fn initialize(cx: &mut CallContext, namespace_object: Gc<Object>)")
    return signatures


# https://webidl.spec.whatwg.org/#namespace-object
def write_rust_namespace(out: TextIO, context: GenerationContext, interface: Interface) -> None:
    """The bindings of a namespace, whose attributes and operations run in the current realm, as static operations
    do."""
    implementation = rust_interface_path(interface)
    members = rust_members(interface)
    if members.attributes_in_order != members.attributes or members.unimplemented_operation_names:
        raise UnsupportedByRustBindings(
            f"{interface.path}: the namespace {interface.name} has members marked [FIXME], which the Rust bindings do "
            "not record on a namespace object yet"
        )
    if members.constants:
        raise UnsupportedByRustBindings(
            f"{interface.path}: the namespace {interface.name} has constants, which the Rust bindings do not handle yet"
        )
    for attribute in members.attributes:
        if attribute.setter_method is not None:
            raise UnsupportedByRustBindings(
                f"{interface.path}: the attribute {attribute.attribute.name} of the namespace {interface.name} is not "
                "read only, which the Rust bindings do not handle yet"
            )
    function_documentation = "".join(
        f"/// - `{signature}`\n" for signature in namespace_function_signatures(context, interface, members)
    )
    out.write(
        f"""
/// The bindings of the namespace {interface.name}, which call these functions of its implementation, {implementation}:
{function_documentation}pub(crate) mod {rust_module_name(interface)} {{
{RUST_BINDINGS_IMPORTS}
    use {implementation} as Implementation;
"""
    )
    for attribute in members.attributes:
        what = f"{interface.name}.{attribute.attribute.name}"
        conversion = (
            "Ok(result)"
            if attribute.returns_js_value
            else rust_to_js_value(attribute.attribute.type, "result", "&cx", context, what)
        )
        out.write(
            f"""
    fn {attribute.getter_function}(vm: &Vm) -> ThrowCompletionOr<Value> {{
        let mut cx = CallContext::new(vm, vm.current_realm().expect("a native function runs in a realm"));
        let result = Implementation::{attribute.getter_method}(&mut cx)
            .map_err(|exception| exception.throw_in_current_realm(cx.vm()))?;
        {conversion}
    }}
"""
        )
    for operation_set in members.operation_sets:
        write_rust_operation_set(out, context, interface, operation_set, write_rust_static_operation)

    out.write(
        f"""
    /// The steps of {interface.namespace_class}::initialize() of LibWeb's C++ bindings.
    ///
    /// # Safety
    ///
    /// The pointers must be the VM, a realm and the namespace object of the realm.
    #[unsafe(no_mangle)]
    pub unsafe extern "C" fn {rust_entry_point_name(interface, "initialize_namespace")}(
        vm: *mut c_void,
        realm: *mut c_void,
        object: *mut c_void,
    ) {{
        // SAFETY: The caller passes live pointers.
        let (vm, realm, object) = unsafe {{ entry_point_arguments(vm, realm, object) }};
        // The class string of a namespace object is the namespace's identifier.
        define_to_string_tag(vm, object, "{interface.name}");
"""
    )
    for attribute in members.attributes:
        out.write(
            f'        define_attribute(vm, realm, object, "{attribute.attribute.name}", '
            f"raw_native!({attribute.getter_function}), None);\n"
        )
    for operation_set in members.operation_sets:
        definition = (
            f'define_operation(vm, realm, object, "{operation_set.name}", raw_native!({operation_set.function}), '
            f"{operation_set.length});"
        )
        out.write(
            member_exposure_definition(
                definition,
                secure_context_only=operation_set.is_secure_context_only,
                exposure_condition=operation_set.exposure_condition,
            )
        )
    if "WithInitializer" in interface.extended_attributes:
        out.write("        Implementation::initialize(&mut CallContext::new(vm, realm), object);\n")
    out.write("    }\n}\n")


def member_exposure_definition(
    definition: str, *, secure_context_only: bool = False, exposure_condition: Optional[str] = None
) -> str:
    """Defines a member on the interface or prototype object when it is exposed in the realm."""
    conditions = []
    if secure_context_only:
        conditions.append("realm_is_secure_context(realm)")
    if exposure_condition is not None:
        conditions.append(exposure_condition)
    if not conditions:
        return f"        {definition}\n"
    return f"""        if {" && ".join(conditions)} {{
            {definition}
        }}
"""


def write_default_to_json(out: TextIO, context: GenerationContext, interface: Interface, function: str) -> None:
    """The native function of a [Default] toJSON operation, which runs the default toJSON steps, in the order of the C++
    bindings, https://webidl.spec.whatwg.org/#default-tojson-steps"""
    values = StringIO()
    # NB: The inheritance stack of the interface has the interface on top and the one it inherits from at the bottom,
    #     and collecting the attribute values of the stack pops it, https://webidl.spec.whatwg.org/#collect-attribute-values-of-an-inheritance-stack
    #     so the attributes of the interfaces that others inherit from are collected first.
    for interface_in_chain in reversed(context.inheritance_stack(interface)):
        if not any(operation_is_default_to_json(operation) for operation in interface_in_chain.regular_operations):
            continue
        if not is_implemented_in_rust(interface_in_chain):
            raise UnsupportedByRustBindings(
                f"{interface.path}: {interface.name} inherits a [Default] toJSON() from {interface_in_chain.name}, "
                "which is not implemented in Rust"
            )
        module = "" if interface_in_chain.name == interface.name else f"super::{rust_module_name(interface_in_chain)}::"
        for attribute in rust_members(interface_in_chain).attributes:
            if not idl_type_is_json_type(attribute.attribute.type, context):
                continue
            # NB: Only the attributes that are exposed in the realm are collected.
            definition = (
                f"let value = {module}{attribute.getter_function}(vm)?; "
                f'set_dictionary_member(&cx, result, &PropertyKey::from_utf8("{attribute.attribute.name}"), value)?;'
            )
            values.write(
                member_exposure_definition(
                    definition,
                    secure_context_only="SecureContext" in attribute.attribute.extended_attributes,
                    exposure_condition=attribute.exposure_condition,
                )
            )
    out.write(
        f"""
    fn {function}(vm: &Vm) -> ThrowCompletionOr<Value> {{
        this_implementation(vm, "toJSON", SecurityCheckType::Method)?;
        let realm = vm.current_realm().expect("a native function runs in a realm");
        let cx = CallContext::new(vm, realm);
        // 4. Let result be OrdinaryObjectCreate(%Object.prototype%).
        let result = create_dictionary_object(&cx);
        // 5. For each key → value of map:
{values.getvalue()}        // 6. Return result.
        Ok(Value::from_object(result))
    }}
"""
    )


def cpp_ancestor_with_indexed_properties(interface: Interface, context: GenerationContext) -> Optional[Interface]:
    """The nearest ancestor implemented in C++ that declares an indexed property getter."""
    ancestor = cpp_ancestor(interface, context)
    while ancestor is not None:
        if ancestor.indexed_property_getter is not None:
            return ancestor
        ancestor = context.interfaces.get(ancestor.parent_name)
    return None


def rust_interface_with_indexed_properties(interface: Interface, context: GenerationContext) -> Optional[Interface]:
    """The interface implemented in Rust that defines the indexed properties of the interface: itself or the closest
    ancestor implemented in Rust that has them, if any."""
    candidate: Optional[Interface] = interface
    while candidate is not None and is_implemented_in_rust(candidate):
        if rust_members(candidate).indexed_property_getter is not None:
            return candidate
        candidate = context.interfaces.get(candidate.parent_name)
    return None


def item_value_entry_point(interface: Interface) -> str:
    return rust_entry_point_name(interface, "item_value")


def named_item_value_entry_point(interface: Interface) -> str:
    return rust_entry_point_name(interface, "named_item_value")


def supported_property_names_entry_point(interface: Interface) -> str:
    return rust_entry_point_name(interface, "supported_property_names")


def named_property_setter_hooks_and_entry_points(
    interface: Interface, setter: Optional[RustOperation]
) -> List[Tuple[str, str]]:
    """The functions of LegacyPlatformObjectInfo that set a named property, each with the entry point of the Rust
    bindings that it calls."""
    if setter is None:
        return []
    hooks = ["set_value_of_named_property"]
    if not setter.operation.name:
        hooks = ["set_value_of_new_named_property", "set_value_of_existing_named_property"]
    return [(hook, rust_entry_point_name(interface, hook)) for hook in hooks]


def delete_value_entry_point(interface: Interface) -> str:
    return rust_entry_point_name(interface, "delete_value")


def write_rust_item_value(
    out: TextIO, context: GenerationContext, interface: Interface, indexed_property_getter: RustIndexedPropertyGetter
) -> None:
    """The entry point through which the internal methods of a legacy platform object that LibWeb's C++ defines read
    an indexed property of a wrapper of the interface, which has a value if the index is a supported property index,
    https://webidl.spec.whatwg.org/#legacy-platform-object-getownproperty"""
    getter = indexed_property_getter.operation
    return_type = getter.operation.return_type
    implementation = "implementation_of::<Implementation>(wrapper)"
    if inheriting_interfaces(interface, context):
        implementation = "receiver_of(wrapper)"
    what = f"the indexed property getter of {interface.name}"
    conversion = rust_to_js_value(return_type.without_nullable(), "value", "&cx", context, what)
    if return_type.nullable:
        value_steps = f"""let Ok(Some(value)) = Implementation::{getter.method}(&implementation, &mut cx, index) else {{
            return false;
        }};"""
    else:
        # NB: A getter that does not return a nullable type has no value for an index that is not a supported one.
        value_steps = f"""let Ok(length) = Implementation::{indexed_property_getter.length_method}(&implementation, &mut cx) else {{
            return false;
        }};
        if index >= length {{
            return false;
        }}
        let Ok(value) = Implementation::{getter.method}(&implementation, &mut cx, index) else {{
            return false;
        }};"""
    out.write(
        f"""
    /// The value of the indexed property of the wrapper, which LibWeb's C++ asks for, if the index is a supported
    /// property index.
    ///
    /// # Safety
    ///
    /// The pointers must be the VM, a live realm and a live wrapper of the interface.
    #[unsafe(no_mangle)]
    pub unsafe extern "C" fn {item_value_entry_point(interface)}(
        vm: *mut c_void,
        realm: *mut c_void,
        wrapper: *mut c_void,
        index: usize,
        out_value: &mut u64,
    ) -> bool {{
        // SAFETY: The caller passes live pointers.
        let (vm, realm, wrapper) = unsafe {{ entry_point_arguments(vm, realm, wrapper) }};
        let Ok(index) = u32::try_from(index) else {{
            return false;
        }};
        let implementation = {implementation};
        let mut cx = CallContext::new(vm, realm);
        {value_steps}
        let value = {conversion}.expect("converting an object to a JS value does not throw");
        *out_value = value.to_raw();
        true
    }}
"""
    )


def indexed_property_setter_entry_points(interface: Interface) -> List[str]:
    return [
        rust_entry_point_name(interface, "set_value_of_new_indexed_property"),
        rust_entry_point_name(interface, "set_value_of_existing_indexed_property"),
    ]


def write_rust_indexed_property_setter(
    out: TextIO, context: GenerationContext, interface: Interface, setter: RustIndexedPropertySetter
) -> None:
    """The entry points through which the internal methods of a legacy platform object that LibWeb's C++ defines run the
    steps of the indexed property setter, https://webidl.spec.whatwg.org/#invoke-indexed-setter"""
    parameter = setter.value_parameter
    what = f"the indexed property setter of {interface.name}"
    conversion = rust_to_idl_value(
        parameter.type,
        parameter.extended_attributes,
        "value",
        parameter.name,
        context,
        what,
        keeps_cells_alive=True,
    )
    out.writelines(
        f"""
    /// The steps of the indexed property setter, which LibWeb's C++ runs on the wrapper.
    ///
    /// # Safety
    ///
    /// The pointers must be the VM, a live realm and a live wrapper of the interface.
    #[unsafe(no_mangle)]
    pub unsafe extern "C" fn {entry_point}(
        vm: *mut c_void,
        realm: *mut c_void,
        wrapper: *mut c_void,
        index: u32,
        value: u64,
    ) -> RawNativeFunctionResult {{
        // SAFETY: The caller passes live pointers.
        let (vm, realm, wrapper) = unsafe {{ entry_point_arguments(vm, realm, wrapper) }};
        // SAFETY: The caller passes the raw bits of a value.
        let value = unsafe {{ Value::from_raw(value) }};
        let steps = || -> ThrowCompletionOr<Value> {{
            let implementation = implementation_of::<Implementation>(wrapper);
            let mut cx = CallContext::new(vm, realm);
            let value = {conversion}?;
            Implementation::{method}(&implementation, &mut cx, index, value)
                .map_err(|exception| exception.throw_in_current_realm(cx.vm()))?;
            Ok(Value::UNDEFINED)
        }};
        RawNativeFunctionResult::from_completion(steps())
    }}
"""
        for method, entry_point in zip(
            ("set_value_of_new_indexed_property", "set_value_of_existing_indexed_property"),
            indexed_property_setter_entry_points(interface),
        )
    )


def write_rust_named_properties(
    out: TextIO, context: GenerationContext, interface: Interface, named_properties: RustNamedProperties
) -> None:
    """The entry points through which the internal methods of a legacy platform object that LibWeb's C++ defines read,
    set and delete the named properties of a wrapper of the interface, and list its supported property names,
    https://webidl.spec.whatwg.org/#dfn-legacy-platform-object"""
    getter = named_properties.getter
    what = f"the named property getter of {interface.name}"
    return_type = getter.operation.return_type
    getter_result = "Ok(value)"
    # NB: A getter with an identifier gives None for the names that are not supported property names.
    if getter.operation.name:
        return_type = return_type.without_nullable()
        getter_result = "Ok(Some(value))"
    conversion = rust_to_js_value(return_type, "value", "&cx", context, what)
    out.write(
        f"""
    /// The value of the named property of the wrapper, which LibWeb's C++ asks for, if the name is a supported
    /// property name.
    ///
    /// # Safety
    ///
    /// The pointers must be the VM, a live realm and a live wrapper of the interface, and the name a live
    /// AK::Utf16FlyString.
    #[unsafe(no_mangle)]
    pub unsafe extern "C" fn {named_item_value_entry_point(interface)}(
        vm: *mut c_void,
        realm: *mut c_void,
        wrapper: *mut c_void,
        name: usize,
        out_value: &mut u64,
    ) -> bool {{
        // SAFETY: The caller passes live pointers.
        let (vm, realm, wrapper) = unsafe {{ entry_point_arguments(vm, realm, wrapper) }};
        // SAFETY: The caller passes a live fly string.
        let name = Utf16String::from(unsafe {{ Utf16FlyString::from_raw_borrowed(name) }});
        let implementation = implementation_of::<Implementation>(wrapper);
        let mut cx = CallContext::new(vm, realm);
        let {getter_result} = Implementation::{getter.method}(&implementation, &mut cx, name) else {{
            return false;
        }};
        let value = {conversion}.expect("converting a named property value to a JS value does not throw");
        *out_value = value.to_raw();
        true
    }}

    /// Calls `append` with each of the supported property names of the wrapper, an AK::Utf16FlyString whose reference
    /// it transfers.
    ///
    /// # Safety
    ///
    /// The pointers must be the VM, a live realm and a live wrapper of the interface, and `append` must accept `names`.
    #[unsafe(no_mangle)]
    pub unsafe extern "C" fn {supported_property_names_entry_point(interface)}(
        vm: *mut c_void,
        realm: *mut c_void,
        wrapper: *mut c_void,
        names: *mut c_void,
        append: unsafe extern "C" fn(*mut c_void, usize),
    ) {{
        // SAFETY: The caller passes live pointers.
        let (vm, realm, wrapper) = unsafe {{ entry_point_arguments(vm, realm, wrapper) }};
        let implementation = implementation_of::<Implementation>(wrapper);
        let mut cx = CallContext::new(vm, realm);
        for name in Implementation::supported_property_names(&implementation, &mut cx) {{
            // SAFETY: The caller's append takes the reference that into_raw() gives up.
            unsafe {{ append(names, Utf16FlyString::from_utf16_string(&name).into_raw()) }};
        }}
    }}
"""
    )
    if named_properties.setter is not None:
        setter = named_properties.setter
        what = f"the named property setter of {interface.name}"
        value_parameter = setter.operation.parameters[1]
        value_conversion = rust_to_idl_value(
            value_parameter.type,
            value_parameter.extended_attributes,
            "value",
            value_parameter.name,
            context,
            what,
            keeps_cells_alive=True,
        )
        for hook, entry_point in named_property_setter_hooks_and_entry_points(interface, setter):
            method = setter.method if setter.operation.name else hook
            call = f"Implementation::{method}(&implementation, &mut cx, name, idl_value)"
            if "CEReactions" in setter.operation.extended_attributes:
                call = with_ce_reactions(call)
            out.write(
                f"""
    /// Sets the named property of the wrapper, https://webidl.spec.whatwg.org/#invoke-named-setter
    ///
    /// # Safety
    ///
    /// The pointers must be the VM, a live realm and a live wrapper of the interface, and the name a live
    /// AK::Utf16FlyString.
    #[unsafe(no_mangle)]
    pub unsafe extern "C" fn {entry_point}(
        vm: *mut c_void,
        realm: *mut c_void,
        wrapper: *mut c_void,
        name: usize,
        value: u64,
    ) -> RawNativeFunctionResult {{
        // SAFETY: The caller passes live pointers.
        let (vm, realm, wrapper) = unsafe {{ entry_point_arguments(vm, realm, wrapper) }};
        // SAFETY: The caller passes a live fly string.
        let name = Utf16String::from(unsafe {{ Utf16FlyString::from_raw_borrowed(name) }});
        // SAFETY: The caller passes a live value.
        let value = unsafe {{ Value::from_raw(value) }};
        let implementation = implementation_of::<Implementation>(wrapper);
        let mut cx = CallContext::new(vm, realm);
        let steps = || -> ThrowCompletionOr<Value> {{
            let idl_value = {value_conversion}?;
            {call}
                .map_err(|exception| exception.throw_in_current_realm(cx.vm()))?;
            Ok(Value::UNDEFINED)
        }};
        RawNativeFunctionResult::from_completion(steps())
    }}
"""
            )
    if named_properties.deleter is not None:
        deleter = named_properties.deleter
        call = f"Implementation::{deleter.method}(&implementation, &mut cx, name)"
        if "CEReactions" in deleter.operation.extended_attributes:
            call = with_ce_reactions(call)
        out.write(
            f"""
    /// Deletes the named property of the wrapper, https://webidl.spec.whatwg.org/#legacy-platform-object-delete
    ///
    /// # Safety
    ///
    /// The pointers must be the VM, a live realm and a live wrapper of the interface, and the name a live
    /// AK::Utf16FlyString.
    #[unsafe(no_mangle)]
    pub unsafe extern "C" fn {delete_value_entry_point(interface)}(
        vm: *mut c_void,
        realm: *mut c_void,
        wrapper: *mut c_void,
        name: usize,
    ) -> RawNativeFunctionResult {{
        // SAFETY: The caller passes live pointers.
        let (vm, realm, wrapper) = unsafe {{ entry_point_arguments(vm, realm, wrapper) }};
        // SAFETY: The caller passes a live fly string.
        let name = Utf16String::from(unsafe {{ Utf16FlyString::from_raw_borrowed(name) }});
        let implementation = implementation_of::<Implementation>(wrapper);
        let mut cx = CallContext::new(vm, realm);
        let result = {call}
            .map(|()| Value::UNDEFINED)
            .map_err(|exception| exception.throw_in_current_realm(cx.vm()));
        RawNativeFunctionResult::from_completion(result)
    }}
"""
        )


def write_rust_stringifier(out: TextIO, function: str, method: str) -> None:
    """The native function of the stringifier, which calls the method of the implementation,
    https://webidl.spec.whatwg.org/#es-stringifier"""
    out.write(
        f"""
    fn {function}(vm: &Vm) -> ThrowCompletionOr<Value> {{
        let (implementation, mut cx) = this_implementation(vm, "toString", SecurityCheckType::Method)?;
        let result = Implementation::{method}(&implementation, &mut cx)
            .map_err(|exception| exception.throw_in_current_realm(cx.vm()))?;
        result.to_js(&cx)
    }}
"""
    )


def write_rust_static_attribute_getter(
    out: TextIO, context: GenerationContext, interface: Interface, attribute: RustAttribute
) -> None:
    """The native function of the getter of a static attribute, which runs in the current realm,
    https://webidl.spec.whatwg.org/#dfn-attribute-getter"""
    what = f"{interface.name}.{attribute.attribute.name}"
    conversion = (
        "Ok(result)"
        if attribute.returns_js_value
        else rust_to_js_value(attribute.attribute.type, "result", "&cx", context, what)
    )
    out.write(
        f"""
    fn {attribute.getter_function}(vm: &Vm) -> ThrowCompletionOr<Value> {{
        let mut cx = CallContext::new(vm, vm.current_realm().expect("a native function runs in a realm"));
        let result = Implementation::{attribute.getter_method}(&mut cx)
            .map_err(|exception| exception.throw_in_current_realm(cx.vm()))?;
        {conversion}
    }}
"""
    )


def write_rust_static_operation(
    out: TextIO, context: GenerationContext, interface: Interface, name: str, function: str, overload: RustOperation
) -> None:
    """The native function of a static operation, which runs in the current realm, in the order of the C++ bindings:
    the arguments are counted, then converted, https://webidl.spec.whatwg.org/#es-operations"""
    operation = overload.operation
    what = f"{interface.name}.{name}()"
    steps = StringIO()
    steps.write('        let realm = vm.current_realm().expect("a native function runs in a realm");\n')
    write_argument_count_check(steps, name, overload.length)
    write_parameter_conversions(steps, what, operation.parameters, context)
    arguments = "".join(f", {rust_local_name(parameter.name)}" for parameter in operation.parameters)
    steps.write("        let mut cx = CallContext::new(vm, realm);\n")
    creates_promise = "CreatesPromise" in operation.extended_attributes
    promise_argument = ", promise" if creates_promise else ""
    call = f"Implementation::{overload.method}(&mut cx{promise_argument}{arguments})"
    if creates_promise:
        conversion = rust_to_js_value(operation.return_type, "promise", "&cx", context, what)
        steps.write(
            f"""        let promise = crate::bindings::promise::create_promise(cx.vm(), cx.realm());
        {call}
            .map_err(|exception| exception.throw_in_current_realm(cx.vm()))?;
        {conversion}
"""
        )
    elif operation.return_type.name == "undefined" and not operation.return_type.nullable:
        steps.write(
            f"""        {call}
            .map_err(|exception| exception.throw_in_current_realm(cx.vm()))?;
        Ok(Value::UNDEFINED)
"""
        )
    else:
        conversion = rust_to_js_value(operation.return_type, "result", "&cx", context, what)
        steps.write(
            f"""        let result = {call}
            .map_err(|exception| exception.throw_in_current_realm(cx.vm()))?;
        {conversion}
"""
        )
    out.write(f"\n    fn {function}(vm: &Vm) -> ThrowCompletionOr<Value> {{\n")
    if is_promise_type(operation.return_type) and not operation.return_type.nullable:
        out.write(
            f"""        // An exception that the steps of an operation with a promise type throw rejects a new promise,
        // https://webidl.spec.whatwg.org/#dfn-create-operation-function
        let steps = || -> ThrowCompletionOr<Value> {{
{textwrap.indent(steps.getvalue(), "    ")}        }};
        steps().or_else(|throw| {{
            let realm = vm.current_realm().expect("a native function runs in a realm");
            Ok(Value::from_object(create_rejected_promise(vm, realm, throw.value()).promise()))
        }})
"""
        )
    else:
        out.write(steps.getvalue())
    out.write("    }\n")


def write_this_implementation(out: TextIO, context: GenerationContext, interface: Interface) -> None:
    """The function that finds what an attribute or an operation of the interface runs on. For an interface that
    others inherit from, that is an object of any of them, which the implementation of each reaches the inherited
    part of through Inherits."""
    inheriting = inheriting_interfaces(interface, context)
    if not inheriting:
        out.write(
            """
    /// The object that an attribute or an operation runs on, and the context it runs in.
    fn this_implementation<'vm>(
        vm: &'vm Vm,
        identifier: &str,
        check_type: SecurityCheckType,
    ) -> ThrowCompletionOr<(Ref<Implementation>, CallContext<'vm>)> {
        let (object, realm) = this_object(vm, Implementation::wrapper_class(), Implementation::NAME, identifier, check_type)?;
        Ok((implementation_of(object), CallContext::new(vm, realm)))
    }
"""
        )
        return

    variants = f"        {interface.name}(Ref<Implementation>),\n"
    arms = f"""                Self::{interface.name}(object) => {{
                    let object: &Implementation = object;
                    object
                }}
"""
    choices = f"""        if let Some(object) = implementation_if::<Implementation>(object) {{
            return Receiver::{interface.name}(object);
        }}
"""
    for other in inheriting:
        path = rust_interface_path(other)
        variants += f"        {other.name}(Ref<{path}>),\n"
        # NB: An interface reaches the part of an interface it does not inherit from directly through the ones between.
        steps = f"                    let object: &{path} = object;\n"
        ancestor = other
        while ancestor.name != interface.name:
            next_ancestor = context.interfaces[ancestor.parent_name]
            next_path = "Implementation" if next_ancestor.name == interface.name else rust_interface_path(next_ancestor)
            step = f"<{rust_interface_path(ancestor)} as Inherits<{next_path}>>::parent(object)"
            # NB: The last step is the value of the arm.
            if next_ancestor.name == interface.name:
                steps += f"                    {step}\n"
            else:
                steps += f"                    let object = {step};\n"
            ancestor = next_ancestor
        arms += f"""                Self::{other.name}(object) => {{
{steps}                }}
"""
        choices += f"""        if let Some(object) = implementation_if::<{path}>(object) {{
            return Receiver::{other.name}(object);
        }}
"""
    out.write(
        f"""
    /// The object that an attribute or an operation of the interface runs on: an object of the interface, or of an
    /// interface that inherits from it.
    enum Receiver {{
{variants}    }}

    impl core::ops::Deref for Receiver {{
        type Target = Implementation;

        fn deref(&self) -> &Implementation {{
            match self {{
{arms}            }}
        }}
    }}

    /// The object that a wrapper of the interface wraps.
    fn receiver_of(object: Gc<Object>) -> Receiver {{
{choices}        unreachable!("a wrapper of the interface wraps an object of it or of an interface that inherits from it")
    }}

    /// The object that an attribute or an operation runs on, and the context it runs in.
    fn this_implementation<'vm>(
        vm: &'vm Vm,
        identifier: &str,
        check_type: SecurityCheckType,
    ) -> ThrowCompletionOr<(Receiver, CallContext<'vm>)> {{
        let (object, realm) = this_object(vm, Implementation::wrapper_class(), Implementation::NAME, identifier, check_type)?;
        Ok((receiver_of(object), CallContext::new(vm, realm)))
    }}
"""
    )


def write_rust_event_handler_attribute(out: TextIO, attribute: RustAttribute) -> None:
    """The getter and the setter of an event handler IDL attribute, which get and set the event handler of the C++
    EventTarget that the object owns, https://html.spec.whatwg.org/multipage/webappapis.html#event-handler-idl-attributes
    The setter calls the method of the implementation that the IDL names instead, which sets the event handler itself."""
    out.write(
        f"""
    pub(super) fn {attribute.getter_function}(vm: &Vm) -> ThrowCompletionOr<Value> {{
        let (implementation, _) = this_implementation(vm, "{attribute.attribute.name}", SecurityCheckType::Getter)?;
        let object: &Implementation = &implementation;
        Ok(event_handler_attribute(object, "{attribute.event_type}"))
    }}
"""
    )
    if attribute.setter_method is not None:
        out.write(
            f"""
    fn {attribute.setter_function}(vm: &Vm) -> ThrowCompletionOr<Value> {{
        let value = vm.argument(0);
        let (implementation, mut cx) = this_implementation(vm, "{attribute.attribute.name}", SecurityCheckType::Setter)?;
        Implementation::{attribute.setter_method}(&implementation, &mut cx, value);
        Ok(Value::UNDEFINED)
    }}
"""
        )
        return
    out.write(
        f"""
    fn {attribute.setter_function}(vm: &Vm) -> ThrowCompletionOr<Value> {{
        let value = vm.argument(0);
        let (implementation, _) = this_implementation(vm, "{attribute.attribute.name}", SecurityCheckType::Setter)?;
        let object: &Implementation = &implementation;
        set_event_handler_attribute(object, "{attribute.event_type}", value);
        Ok(Value::UNDEFINED)
    }}
"""
    )


def inherited_attribute_getter_call(context: GenerationContext, interface: Interface, attribute: RustAttribute) -> str:
    """The call of the getter of an attribute that the interface redeclares with inherit, whose getter is that of the
    interface it inherits the attribute from, https://webidl.spec.whatwg.org/#dfn-inherit-getter. The implementation
    reaches the part that the getter runs on through Inherits."""
    name = attribute.attribute.name
    receiver = "&*implementation"
    path = rust_interface_path(interface)
    ancestor = context.interfaces.get(interface.parent_name)
    while ancestor is not None:
        ancestor_path = rust_interface_path(ancestor)
        receiver = f"<{path} as Inherits<{ancestor_path}>>::parent({receiver})"
        for ancestor_attribute in rust_members(ancestor).attributes:
            if ancestor_attribute.attribute.name == name and not ancestor_attribute.attribute.inherit:
                return f"{ancestor_path}::{ancestor_attribute.getter_method}({receiver}, &mut cx)"
        path = ancestor_path
        ancestor = context.interfaces.get(ancestor.parent_name)
    raise UnsupportedByRustBindings(
        f"{interface.path}: {interface.name} inherits the attribute {name}, which no interface it inherits from declares"
    )


def write_css_property_accessors(out: TextIO) -> None:
    """The getter and the setter of the accessors of CSSStyleProperties, one for each CSS property, which behave as a
    [CEReactions, LegacyNullToEmptyString] attribute of type CSSOMString does:
    https://drafts.csswg.org/cssom/#dom-cssstyleproperties-camel_cased_attribute"""
    out.write(
        """
    fn property_getter(vm: &Vm, property: &crate::css::css_style_properties::CSSPropertyAccessor) -> ThrowCompletionOr<Value> {
        let (implementation, mut cx) = this_implementation(vm, property.property_name(), SecurityCheckType::Getter)?;
        let result = Implementation::property_value(&implementation, &mut cx, property)
            .map_err(|exception| exception.throw_in_current_realm(cx.vm()))?;
        result.to_js(&cx)
    }

    fn property_setter(vm: &Vm, property: &crate::css::css_style_properties::CSSPropertyAccessor) -> ThrowCompletionOr<Value> {
        let value = vm.argument(0);
        let (implementation, mut cx) = this_implementation(vm, property.property_name(), SecurityCheckType::Setter)?;
        let idl_value = to_dom_string_treating_null_as_empty(vm, value)?;
        with_custom_element_reactions(|| Implementation::set_property_value(&implementation, &mut cx, property, idl_value))
            .map_err(|exception| exception.throw_in_current_realm(cx.vm()))?;
        Ok(Value::UNDEFINED)
    }
"""
    )


def with_ce_reactions(call: str) -> str:
    """The call of the steps of a [CEReactions] construct, whose exception the caller rethrows after the reactions ran:
    https://html.spec.whatwg.org/multipage/custom-elements.html#cereactions"""
    return f"with_custom_element_reactions(|| {call})"


def write_rust_attribute_setter(
    out: TextIO, context: GenerationContext, interface: Interface, attribute: RustAttribute
) -> None:
    """The native function of the setter of an attribute, in the order of the C++ bindings: the value is read before
    the this value is checked, and a missing value is undefined instead of an error."""
    name = attribute.attribute.name
    what = f"{interface.name}.{name}"
    conversion = rust_to_idl_value(
        attribute.attribute.type, attribute.attribute.extended_attributes, "value", name, context, what
    )
    if context.enumeration(attribute.attribute.type) is not None:
        # NB: The setter of an attribute of an enumeration type ignores a value that is not one of the enumeration's,
        #     https://webidl.spec.whatwg.org/#dfn-attribute-setter, and, as the C++ bindings do, a value whose
        #     conversion throws.
        conversion = f"""let Ok(idl_value) = {conversion} else {{
            return Ok(Value::UNDEFINED);
        }};"""
    else:
        conversion = f"let idl_value = {conversion}?;"
    receiver = "(implementation, mut cx)"
    caller_realm_context = ""
    if "NeedsCallerRealm" in attribute.attribute.extended_attributes:
        receiver = "(implementation, _)"
        caller_realm_context = CALLER_REALM_CONTEXT
    call = f"Implementation::{attribute.setter_method}(&implementation, &mut cx, idl_value)"
    if "CEReactions" in attribute.attribute.extended_attributes:
        call = with_ce_reactions(call)
    out.write(
        f"""
    fn {attribute.setter_function}(vm: &Vm) -> ThrowCompletionOr<Value> {{
        let value = vm.argument(0);
        let {receiver} = this_implementation(vm, "{attribute.attribute.name}", SecurityCheckType::Setter)?;
{caller_realm_context}        {conversion}
        {call}
            .map_err(|exception| exception.throw_in_current_realm(cx.vm()))?;
        Ok(Value::UNDEFINED)
    }}
"""
    )


def write_rust_put_forwards_setter(out: TextIO, attribute: RustAttribute) -> None:
    """The native function of the setter of a [PutForwards] attribute, which sets the attribute that it names on the
    value of the attribute: https://webidl.spec.whatwg.org/#dfn-attribute-setter"""
    out.write(
        f"""
    fn {attribute.setter_function}(vm: &Vm) -> ThrowCompletionOr<Value> {{
        let value = vm.argument(0);
        let (object, _) = this_object(vm, Implementation::wrapper_class(), Implementation::NAME, "{attribute.attribute.name}", SecurityCheckType::Setter)?;
        let receiver = object.get(vm, &PropertyKey::from_utf8("{attribute.attribute.name}"))?;
        if !receiver.is_object() {{
            return vm.throw_completion(ErrorKind::TypeError, ErrorType::NotAnObject, &[&"{attribute.attribute.name}"]);
        }}
        receiver.as_object().set(
            vm,
            &PropertyKey::from_utf8("{attribute.put_forwards}"),
            value,
            ShouldThrowExceptions::No,
        )?;
        Ok(Value::UNDEFINED)
    }}
"""
    )


def write_rust_operation(
    out: TextIO, context: GenerationContext, interface: Interface, name: str, function: str, overload: RustOperation
) -> None:
    """The native function of the steps of an operation, in the order of the C++ bindings: the this value is checked,
    then the arguments are counted and converted, with the type errors of the conversions in the realm of the object."""
    operation = overload.operation
    what = f"{interface.name}.{name}()"
    steps = StringIO()
    if "NeedsCallerRealm" in operation.extended_attributes:
        steps.write(
            f'        let (implementation, _) = this_implementation(vm, "{operation.name}", SecurityCheckType::Method)?;\n'
            f"{CALLER_REALM_CONTEXT}"
        )
    else:
        steps.write(
            f'        let (implementation, mut cx) = this_implementation(vm, "{operation.name}", SecurityCheckType::Method)?;\n'
        )
    write_argument_count_check(steps, name, overload.length)
    write_parameter_conversions(steps, what, operation.parameters, context)
    arguments = "".join(f", {rust_local_name(parameter.name)}" for parameter in operation.parameters)
    returns_promise = is_promise_type(operation.return_type) and not operation.return_type.nullable
    if overload.implementation_parameters is not None:
        arguments = ""
        for index, parameter in enumerate(overload.implementation_parameters):
            argument = rust_local_name(parameter.name)
            if index == overload.omitted_parameter_index:
                argument = f"Some({argument})" if parameter in operation.parameters else "None"
            arguments += f", {argument}"
    creates_promise = "CreatesPromise" in operation.extended_attributes
    promise_argument = ", promise" if creates_promise else ""
    call = f"Implementation::{overload.method}(&implementation, &mut cx{promise_argument}{arguments})"
    if "CEReactions" in operation.extended_attributes:
        if returns_promise:
            raise UnsupportedByRustBindings(f"{what} returns a promise and is [CEReactions]")
        call = with_ce_reactions(call)
    if creates_promise:
        conversion = rust_to_js_value(operation.return_type, "promise", "&cx", context, what)
        steps.write(
            f"""        let promise = crate::bindings::promise::create_promise(cx.vm(), cx.realm());
        {call}
            .map_err(|exception| exception.throw_in_current_realm(cx.vm()))?;
        {conversion}
"""
        )
    elif operation.return_type.name == "undefined" and not operation.return_type.nullable:
        # NB: An operation that returns nothing has no result to name, and the conversion of nothing is undefined.
        steps.write(
            f"""        {call}
            .map_err(|exception| exception.throw_in_current_realm(cx.vm()))?;
        Ok(Value::UNDEFINED)
"""
        )
    else:
        conversion = rust_to_js_value(operation.return_type, "result", "&cx", context, what)
        steps.write(
            f"""        let result = {call}
            .map_err(|exception| exception.throw_in_current_realm(cx.vm()))?;
        {conversion}
"""
        )

    out.write(f"\n    fn {function}(vm: &Vm) -> ThrowCompletionOr<Value> {{\n")
    if returns_promise:
        # NB: The C++ bindings run everything, the check of the this value included, inside these steps.
        out.write(
            f"""        // An exception that the steps of an operation with a promise type throw rejects a new promise,
        // https://webidl.spec.whatwg.org/#dfn-create-operation-function
        let steps = || -> ThrowCompletionOr<Value> {{
{textwrap.indent(steps.getvalue(), "    ")}        }};
        steps().or_else(|throw| {{
            let realm = vm.current_realm().expect("a native function runs in a realm");
            Ok(Value::from_object(create_rejected_promise(vm, realm, throw.value()).promise()))
        }})
"""
        )
    else:
        out.write(steps.getvalue())
    out.write("    }\n")


def write_rust_constructor(
    out: TextIO, context: GenerationContext, interface: Interface, constructor: RustConstructor
) -> 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."""
    parameters = constructor.constructor.parameters
    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 {constructor.steps_function}(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)?;
"""
    )
    write_argument_count_check(out, interface.name, constructor.length)
    write_parameter_conversions(out, constructor_description(interface), parameters, context)
    arguments = "".join(f", {rust_local_name(parameter.name)}" for parameter in parameters)
    out.write(
        f"""        let mut cx = CallContext::new(vm, realm);
        let implementation =
            Implementation::{constructor.method}(&mut cx{arguments}).map_err(|exception| exception.throw_in_current_realm(cx.vm()))?;
        Ok(Value::from_object(construct_wrapper::<Implementation>(vm, realm, prototype, implementation)))
    }}
"""
    )


def write_cpp_interface_names(out: TextIO, usage: DefinitionUsage, interface_name_values: Dict[str, int]) -> None:
    """The values by which the bindings ask LibWeb whether an object implements an interface that it implements in
    C++."""
    if not usage.cpp_interfaces_named_by_rust:
        return
    out.write(
        """
/// Web::Bindings::InterfaceName of the interfaces that LibWeb implements in C++ and that the interfaces implemented in
/// Rust name.
pub(crate) mod cpp_interface_names {
"""
    )
    for name, interface in sorted(usage.cpp_interfaces_named_by_rust.items()):
        if name not in interface_name_values:
            raise UnsupportedByRustBindings(
                f"An interface implemented in Rust names {name}, which has no Web::Bindings::InterfaceName"
            )
        constant = cpp_interface_name_constant(interface).rpartition("::")[2]
        out.write(f"    pub(crate) const {constant}: u16 = {interface_name_values[name]};\n")
    out.write("}\n")


def write_rust_definitions(out: TextIO, context: GenerationContext, usage: DefinitionUsage) -> None:
    """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
        and not usage.rust_enumerations
        and not usage.rust_any_interfaces
    ):
        return
    out.write(
        """
/// The conversions of the definitions that the interfaces implemented in Rust name, whose types the modules of their
/// IDL files define next to the implementations.
pub(crate) mod definitions {
    #![allow(unused_imports)]

    use std::sync::LazyLock;

    use ak::Utf16String;
    use libjs_rust::api::{
        ErrorKind, ErrorType, Gc, JSONObject, MarkedVec, Object, PropertyKey, ThrowCompletionOr, TypedArrayBase, TypedArrayKind, Utf16View,
        Value, Vm, is_host_instance_of,
    };

    use crate::bindings::CallContext;
    use crate::bindings::callback::{CallbackFunction, CallbackInterface, PromiseCallbackFunction};
    use crate::bindings::conversions::{
        ArrayBufferView, BufferSource, BufferSourceRules, BufferSourceTypes, ByteString, CppInterface, EmptyDictionary, FromJs, ToJs, UsvString,
        buffer_source_if, dictionary_member, dictionary_object, enumeration_value_to_js, implements_cpp_interface,
        frozen_array_to_js, 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_byte_string, 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_object, to_shared_array_buffer, to_typed_array,
        to_unrestricted_double, to_unrestricted_float, to_unsigned_long, to_unsigned_long_clamping, to_unsigned_short,
        to_unsigned_long_enforcing_range,
        to_unsigned_long_long, to_unsigned_long_long_enforcing_range, to_usv_string, to_window_proxy,
        window_proxy_from_object, window_proxy_to_js,
    };
    use crate::bindings::interface::{
        Interface, Ref, create_dictionary_object, implementation_if, implementation_of, set_dictionary_member,
        to_interface,
    };
    use crate::bindings::new_global_object::{run_in_a_new_global_object, serialize_to_json_in_a_new_global_object};
"""
    )
    for name, directions in usage.rust_dictionaries.items():
        dictionary = context.dictionaries[name]
        if directions.from_js:
            write_dictionary_from_js(out, context, dictionary)
        if directions.to_js:
            write_dictionary_to_js(out, context, dictionary)
        write_rust_dictionary_json_conversions(out, context, dictionary)
    for name, directions in usage.rust_enumerations.items():
        enumeration = context.enumerations[name]
        if directions.from_js:
            write_enumeration_from_js(out, context, enumeration)
        if directions.to_js:
            write_enumeration_to_js(out, context, enumeration)
    for interface in usage.rust_any_interfaces.values():
        write_any_interface_from_js(out, interface, context)
    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")


def write_rust_bindings(
    out: TextIO, context: GenerationContext, usage: DefinitionUsage, intrinsics: List[Interface]
) -> None:
    out.write(
        """// Generated by Meta/Generators/generate_libweb_bindings.py -- DO NOT EDIT
//
// The bindings of the interfaces that are implemented in Rust.
"""
    )
    values = interface_name_values(intrinsics)
    write_cpp_interface_names(out, usage, values)
    write_rust_definitions(out, context, usage)
    for module in context.modules:
        interface = module.interface
        if rust_implemented_members(interface) is not None:
            assert interface is not None
            write_rust_members_of_cpp_interface(out, context, interface)
            continue
        if interface is None or not is_implemented_in_rust(interface):
            continue
        if interface.is_namespace:
            write_rust_namespace(out, context, interface)
        else:
            write_rust_interface(out, context, module, interface, values[interface.name])
    write_rust_serializable_dispatch(out, intrinsics, values)
    write_rust_wrap_for_cpp(out, context, usage)


def write_rust_members_of_cpp_interface(out: TextIO, context: GenerationContext, interface: Interface) -> None:
    """The bindings of the members of an interface implemented in C++ that are [ImplementedIn=Rust]. The functions of
    the Rust module of the interface's IDL file implement them, and receive the wrapper of the object they run on. The
    C++ bindings call an entry point for each to define it on the interface prototype object, in the order of the
    IDL."""
    rust_members_of_interface = rust_implemented_members(interface)
    assert rust_members_of_interface is not None
    members = rust_members(rust_members_of_interface)
    implementation = rust_module_path(interface.path)
    method_documentation = "".join(
        f"/// - `{signature.replace('&self', 'this: &CppInterface')}`\n"
        for signature in implementation_method_signatures(context, rust_members_of_interface, members)
    )
    out.write(
        f"""
/// The bindings of the members of {interface.name} that are implemented in Rust, which call these functions of
/// {implementation}:
{method_documentation}pub(crate) mod {rust_module_name(interface)} {{
{RUST_BINDINGS_IMPORTS}
    use {implementation} as Implementation;

    /// The wrapper of the object that an attribute or an operation runs on, and the context it runs in.
    fn this_implementation<'vm>(
        vm: &'vm Vm,
        identifier: &str,
        check_type: SecurityCheckType,
    ) -> ThrowCompletionOr<(CppInterface, CallContext<'vm>)> {{
        let (object, realm) = this_cpp_object(vm, {cpp_interface_name_constant(interface)}, "{interface.namespaced_name}", identifier, check_type)?;
        // SAFETY: The object is a wrapper of an object that implements the interface.
        Ok((unsafe {{ CppInterface::from_wrapper(object) }}, CallContext::new(vm, realm)))
    }}
"""
    )
    write_rust_attributes(out, context, rust_members_of_interface, members.attributes)
    for attribute in members.attributes:
        name = attribute.attribute.name
        getter = f"raw_native!({attribute.getter_function})"
        if attribute.is_cached:
            definition = f'define_cached_attribute(vm, realm, prototype, "{name}", {getter});'
        else:
            has_setter = not attribute.attribute.readonly or attribute.put_forwards is not None
            setter = f"raw_native!({attribute.setter_function})" if has_setter else "None"
            definition = f'define_attribute(vm, realm, prototype, "{name}", {getter}, {setter});'
        out.write(
            f"""
    /// Defines {interface.name}.{name} on the interface prototype object.
    ///
    /// # Safety
    ///
    /// The pointers must be the VM, a realm and the interface prototype object of the realm.
    #[unsafe(no_mangle)]
    pub unsafe extern "C" fn {rust_member_definition_entry_point(interface, attribute.attribute)}(
        vm: *mut c_void,
        realm: *mut c_void,
        prototype: *mut c_void,
    ) {{
        // SAFETY: The caller passes live pointers.
        let (vm, realm, prototype) = unsafe {{ entry_point_arguments(vm, realm, prototype) }};
        {definition}
    }}
"""
        )
    for operation_set in members.operation_sets:
        write_rust_operation_set(out, context, rust_members_of_interface, operation_set, write_rust_operation)
        out.write(
            f"""
    /// Defines {interface.name}.{operation_set.name}() on the interface prototype object.
    ///
    /// # Safety
    ///
    /// The pointers must be the VM, a realm and the interface prototype object of the realm.
    #[unsafe(no_mangle)]
    pub unsafe extern "C" fn {rust_member_definition_entry_point(interface, operation_set.overloads[0].operation)}(
        vm: *mut c_void,
        realm: *mut c_void,
        prototype: *mut c_void,
    ) {{
        // SAFETY: The caller passes live pointers.
        let (vm, realm, prototype) = unsafe {{ entry_point_arguments(vm, realm, prototype) }};
        define_operation(vm, realm, prototype, "{operation_set.name}", raw_native!({operation_set.function}), {operation_set.length});
    }}
"""
        )
    out.write("}\n")


def write_rust_wrap_for_cpp(out: TextIO, context: GenerationContext, usage: DefinitionUsage) -> None:
    """The entry point through which the C++ bindings of the interfaces that name an interface implemented in Rust
    wrap an object of it, which C++ code holds as the cell of the object."""
    documentation = """
/// The wrapper of an object of an interface implemented in Rust in the wrapper world of the realm, for the C++
/// bindings of the interfaces that name the interface.
///
/// # Safety
///
/// The pointers must be the VM, a live realm, and the live cell of an object of the interface.
#[unsafe(no_mangle)]
"""
    # NB: The C++ object that such an object owns is wrapped by the object's interface too.
    wrapped_interfaces = dict(usage.rust_interfaces_named_by_cpp)
    for interface in context.interfaces.values():
        if is_implemented_in_rust(interface) and cpp_ancestor(interface, context) is not None:
            wrapped_interfaces[interface.name] = interface

    if not wrapped_interfaces:
        out.write(
            f"""{documentation}pub unsafe extern "C" fn web_rust_bindings_wrap(
    _vm: *mut core::ffi::c_void,
    _realm: *mut core::ffi::c_void,
    _interface_name: u16,
    _cell: *mut core::ffi::c_void,
) -> *mut core::ffi::c_void {{
    unreachable!("LibWeb's C++ bindings name no interface that is implemented in Rust")
}}
"""
        )
        return

    def arm(interface: Interface) -> str:
        inheriting = inheriting_interfaces(interface, context)
        if not inheriting:
            return f"""        {rust_module_name(interface)}::INTERFACE_NAME => {{
            // SAFETY: The caller passes the cell of an object of the interface.
            wrap(&cx, unsafe {{ cell_from_abi::<{rust_interface_path(interface)}>(cell) }})
        }}
"""
        # NB: C++ names an object of an interface that others inherit from by that interface, whichever of them the
        #     object is.
        choices = "".join(
            f"""            // SAFETY: The caller passes a live cell.
            if let Some(object) = unsafe {{ cell_if_abi::<{rust_interface_path(candidate)}>(cell) }} {{
                break 'wrapper wrap(&cx, object);
            }}
"""
            for candidate in [interface] + inheriting
        )
        return f"""        {rust_module_name(interface)}::INTERFACE_NAME => 'wrapper: {{
{choices}            unreachable!("C++ passes the cell of an object of the interface or of one that inherits from it")
        }}
"""

    arms = "".join(arm(interface) for _, interface in sorted(wrapped_interfaces.items()))
    out.write(
        f"""{documentation}pub unsafe extern "C" fn web_rust_bindings_wrap(
    vm: *mut core::ffi::c_void,
    realm: *mut core::ffi::c_void,
    interface_name: u16,
    cell: *mut core::ffi::c_void,
) -> *mut core::ffi::c_void {{
    use crate::bindings::CallContext;
    #[allow(unused_imports)]
    use crate::bindings::interface::{{cell_from_abi, cell_if_abi, realm_arguments, wrap}};

    // SAFETY: The caller passes the VM and a live realm.
    let (vm, realm) = unsafe {{ realm_arguments(vm, realm) }};
    let cx = CallContext::new(vm, realm);
    let wrapper = match interface_name {{
{arms}        _ => unreachable!("LibWeb's C++ bindings name no other interface that is implemented in Rust"),
    }};
    wrapper.as_ptr().cast()
}}
"""
    )


def check_rust_bindings(context: GenerationContext, usage: DefinitionUsage, intrinsics: List[Interface]) -> None:
    """Raises an error for every use of [ImplementedIn] that the bindings do not handle, before anything is written.
    The functions that write the Rust bindings reject the types and the definitions that they do not handle
    themselves, so the bindings are written once to find those."""
    for module in context.modules:
        interface = module.interface
        if interface is None:
            continue
        implemented_in = interface.extended_attributes.get("ImplementedIn")
        if implemented_in is not None and implemented_in != "Rust":
            raise UnsupportedByRustBindings(
                f"{interface.path}: {interface.name} is [ImplementedIn={implemented_in}], but the only value is Rust"
            )
        if is_implemented_in_rust(interface):
            check_interface_is_supported(interface, module, context)
        check_rust_members_of_interface(interface)
    write_rust_bindings(StringIO(), context, usage, intrinsics)


def check_rust_members_of_interface(interface: Interface) -> None:
    """Raises an error for a member marked [ImplementedIn] that the bindings do not handle: so far, only the regular
    attributes and operations of an interface implemented in C++ that is not a global interface can be."""

    def fail(member: str, message: str) -> None:
        raise UnsupportedByRustBindings(
            f"{interface.path}: {interface.name}.{member} is [ImplementedIn=Rust], but {message}"
        )

    for member in interface.static_attributes + interface.static_operations:
        if "ImplementedIn" in member.extended_attributes:
            fail(member.name, "the Rust bindings implement no static member of an interface implemented in C++ yet")
    has_default_to_json = any(operation_is_default_to_json(operation) for operation in interface.regular_operations)
    rust_operation_names = set()
    for member in interface.regular_attributes + interface.regular_operations:
        implemented_in = member.extended_attributes.get("ImplementedIn")
        if implemented_in is None:
            continue
        if implemented_in != "Rust":
            fail(member.name, "the only value is Rust")
        if is_implemented_in_rust(interface):
            fail(member.name, "the interface is implemented in Rust as a whole")
        if interface.is_namespace or "Global" in interface.extended_attributes:
            fail(member.name, "the interface is a namespace or a global interface")
        if "LegacyUnforgeable" in member.extended_attributes:
            fail(member.name, "it is [LegacyUnforgeable]")
        if isinstance(member, Attribute) and has_default_to_json:
            fail(member.name, "the default toJSON() of the interface reads its attributes through the C++ bindings")
        if not isinstance(member, Attribute):
            rust_operation_names.add(member.name)
    for operation in interface.regular_operations:
        if operation.name in rust_operation_names and operation.extended_attributes.get("ImplementedIn") != "Rust":
            fail(operation.name, "not all of its overloads are")