Skip to content

Truly independent web browser

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


from typing import TextIO

from Generators.libweb_bindings.arguments import write_operation_parameter_conversions
from Generators.libweb_bindings.context import GenerationContext
from Generators.libweb_bindings.cpp_types import add_header_includes_for_idl_type
from Generators.libweb_bindings.cpp_types import fully_qualified_name_for_interface
from Generators.libweb_bindings.cpp_types import idl_identifier_cpp_name
from Generators.libweb_bindings.cpp_types import is_string_type
from Generators.libweb_bindings.cpp_types import libweb_include_path
from Generators.libweb_bindings.glue_headers import bindings_glue_header_for_interface
from Generators.libweb_bindings.includes import GeneratedIncludes
from Generators.libweb_bindings.overload_resolution import operation_callback_names
from Generators.libweb_bindings.overload_resolution import parameter_list_length
from Generators.libweb_bindings.to_idl_value import type_check_idl_value
from Generators.libweb_bindings.to_js_value import to_javascript_value
from Utils.utils import make_name_acceptable_cpp
from Utils.utils import title_case_to_snake_case
from Utils.webidl_parser import Interface


def iterator_implementation_header_for_interface(interface: Interface) -> str:
    return libweb_include_path(interface.path.with_name(f"{interface.implemented_name}Iterator.h"))


def async_iterator_implementation_header_for_interface(interface: Interface) -> str:
    return libweb_include_path(interface.path.with_name(f"{interface.implemented_name}AsyncIterator.h"))


def write_iterator_prototype_declaration(out: TextIO, interface: Interface) -> None:
    if interface.iterable is None or interface.iterable.key_type is None:
        return

    out.write(
        f"""struct {interface.name}IteratorPrototype {{
    static void initialize(JS::Realm&, JS::Object&);

private:
    JS_DECLARE_NATIVE_FUNCTION(next);
}};

"""
    )


def write_async_iterator_prototype_declaration(out: TextIO, interface: Interface) -> None:
    if interface.async_iterable is None:
        return

    out.write(
        f"""struct {interface.name}AsyncIteratorPrototype {{
    static void initialize(JS::Realm&, JS::Object&);

private:
    JS_DECLARE_NATIVE_FUNCTION(next);
    {"JS_DECLARE_NATIVE_FUNCTION(return_);" if "DefinesAsyncIteratorReturn" in interface.extended_attributes else ""}
}};

"""
    )


def define_the_pair_iterable_declaration(
    out: TextIO,
    includes: GeneratedIncludes,
    interface: Interface,
) -> None:
    if interface.iterable is None or interface.iterable.key_type is None:
        return

    out.write(
        """    object.define_native_function(realm, vm.names.entries, entries, 0, default_attributes);
    object.define_native_function(realm, vm.names.forEach, for_each, 1, default_attributes);
    object.define_native_function(realm, vm.names.keys, keys, 0, default_attributes);
    object.define_native_function(realm, vm.names.values, values, 0, default_attributes);

    object.define_direct_property(vm.well_known_symbol_iterator(), object.get_without_side_effects(vm.names.entries), JS::Attribute::Configurable | JS::Attribute::Writable);

"""
    )


def define_the_async_iterable_declaration(
    out: TextIO,
    interface: Interface,
) -> None:
    if interface.async_iterable is None:
        return

    out.write(
        f"""    object.define_native_function(realm, vm.names.values, values, {parameter_list_length(interface.async_iterable.parameters)}, default_attributes);
    object.define_direct_property(vm.well_known_symbol_async_iterator(), object.get_without_side_effects(vm.names.values), JS::Attribute::Configurable | JS::Attribute::Writable);

"""
    )


def define_the_maplike_declaration(
    out: TextIO,
    includes: GeneratedIncludes,
    interface: Interface,
) -> None:
    if interface.maplike is None:
        return

    includes.add("LibJS/Runtime/Map.h")
    out.write(
        """    object.define_native_accessor(realm, vm.names.size, get_size, nullptr, JS::Attribute::Enumerable | JS::Attribute::Configurable);
    object.define_native_function(realm, vm.names.entries, entries, 0, default_attributes);
    object.define_direct_property(vm.well_known_symbol_iterator(), object.get_without_side_effects(vm.names.entries), JS::Attribute::Configurable | JS::Attribute::Writable);
    object.define_native_function(realm, vm.names.keys, keys, 0, default_attributes);
    object.define_native_function(realm, vm.names.values, values, 0, default_attributes);
    object.define_native_function(realm, vm.names.forEach, for_each, 1, default_attributes);
    object.define_native_function(realm, vm.names.get, get, 1, default_attributes);
    object.define_native_function(realm, vm.names.has, has, 1, default_attributes);
"""
    )
    if not interface.maplike.readonly:
        operation_callbacks = operation_callback_names(interface)
        if "set" not in operation_callbacks:
            out.write("    object.define_native_function(realm, vm.names.set, set, 2, default_attributes);\n")
        out.write(
            """    object.define_native_function(realm, vm.names.delete_, delete_, 1, default_attributes);
    object.define_native_function(realm, vm.names.clear, clear, 0, default_attributes);
"""
        )
    out.write("\n")


def define_the_setlike_declaration(
    out: TextIO,
    includes: GeneratedIncludes,
    interface: Interface,
) -> None:
    if interface.setlike is None:
        return

    includes.add("LibJS/Runtime/Set.h")
    operation_callbacks = operation_callback_names(interface)
    out.write(
        """    object.define_native_accessor(realm, vm.names.size, get_size, nullptr, JS::Attribute::Enumerable | JS::Attribute::Configurable);
    object.define_native_function(realm, vm.names.entries, entries, 0, default_attributes);
    object.define_native_function(realm, vm.names.keys, values, 0, default_attributes);
    object.define_native_function(realm, vm.names.values, values, 0, default_attributes);
    object.define_direct_property(vm.well_known_symbol_iterator(), object.get_without_side_effects(vm.names.values), JS::Attribute::Configurable | JS::Attribute::Writable);
    object.define_native_function(realm, vm.names.forEach, for_each, 1, default_attributes);
    object.define_native_function(realm, vm.names.has, has, 1, default_attributes);
"""
    )
    if not interface.setlike.readonly:
        if "add" not in operation_callbacks:
            out.write("    object.define_native_function(realm, vm.names.add, add, 1, default_attributes);\n")
        if "delete_" not in operation_callbacks:
            out.write("    object.define_native_function(realm, vm.names.delete_, delete_, 1, default_attributes);\n")
        if "clear" not in operation_callbacks:
            out.write("    object.define_native_function(realm, vm.names.clear, clear, 0, default_attributes);\n")
    out.write("\n")


# https://webidl.spec.whatwg.org/#js-iterable
def write_pair_iterable_declaration_functions(
    out: TextIO,
    context: GenerationContext,
    includes: GeneratedIncludes,
    interface: Interface,
) -> None:
    if interface.iterable is None or interface.iterable.key_type is None:
        return

    includes.add("LibJS/Runtime/AbstractOperations.h")
    includes.add("LibJS/Runtime/Error.h")
    includes.add("LibJS/Runtime/ValueInlines.h")
    includes.add("AK/IterationDecision.h")
    includes.add("AK/Optional.h")
    includes.add("LibWeb/WebIDL/ExceptionOrUtils.h")
    includes.add(iterator_implementation_header_for_interface(interface))
    add_header_includes_for_idl_type(interface.iterable.key_type, includes, context)
    add_header_includes_for_idl_type(interface.iterable.value_type, includes, context)

    out.write(f"""JS_DEFINE_NATIVE_FUNCTION({interface.prototype_class}::entries)
{{
    auto& realm = *vm.current_realm();
    auto this_value = vm.this_value();
    if (this_value.is_nullish())
        this_value = &realm.global_object();

    // 1. Let jsValue be ? ToObject(this value).
    // 2. If jsValue is a platform object, then perform a security check, passing jsValue, "%Symbol.iterator%", and "method".
    // 3. If jsValue does not implement definition, then throw a TypeError.
    auto* this_impl = TRY(impl_from(vm, this_value, u"%Symbol.iterator%"sv, HTML::SecurityCheckType::Method));
    [[maybe_unused]] auto& this_object_realm = this_value.as_object().shape().realm();

    // 4. Return a newly created default iterator object for definition, with jsValue as its target, "key+value" as its kind, and index set to 0.
    return TRY(WebIDL::throw_dom_exception_if_needed(vm, realm, [&] {{ return {fully_qualified_name_for_interface(interface)}Iterator::create(this_object_realm, *this_impl, JS::Object::PropertyKind::KeyAndValue); }}));
}}

JS_DEFINE_NATIVE_FUNCTION({interface.prototype_class}::keys)
{{
    auto& realm = *vm.current_realm();
    auto this_value = vm.this_value();
    if (this_value.is_nullish())
        this_value = &realm.global_object();

    // 1. Let jsValue be ? ToObject(this value).
    // 2. If jsValue is a platform object, then perform a security check, passing jsValue, "keys", and "method".
    // 3. If jsValue does not implement definition, then throw a TypeError.
    auto* this_impl = TRY(impl_from(vm, this_value, u"keys"sv, HTML::SecurityCheckType::Method));
    [[maybe_unused]] auto& this_object_realm = this_value.as_object().shape().realm();

    // 4. Return a newly created default iterator object for definition, with jsValue as its target, "key" as its kind, and index set to 0.
    return TRY(WebIDL::throw_dom_exception_if_needed(vm, realm, [&] {{ return {fully_qualified_name_for_interface(interface)}Iterator::create(this_object_realm, *this_impl, JS::Object::PropertyKind::Key); }}));
}}

JS_DEFINE_NATIVE_FUNCTION({interface.prototype_class}::values)
{{
    auto& realm = *vm.current_realm();
    auto this_value = vm.this_value();
    if (this_value.is_nullish())
        this_value = &realm.global_object();

    // 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.
    auto* this_impl = TRY(impl_from(vm, this_value, u"values"sv, HTML::SecurityCheckType::Method));
    [[maybe_unused]] auto& this_object_realm = this_value.as_object().shape().realm();

    // 4. Return a newly created default iterator object for definition, with jsValue as its target, "value" as its kind, and index set to 0.
    return TRY(WebIDL::throw_dom_exception_if_needed(vm, realm, [&] {{ return {fully_qualified_name_for_interface(interface)}Iterator::create(this_object_realm, *this_impl, JS::Object::PropertyKind::Value); }}));
}}

JS_DEFINE_NATIVE_FUNCTION({interface.prototype_class}::for_each)
{{
    [[maybe_unused]] auto& realm = *vm.current_realm();
    auto this_value = vm.this_value();
    if (this_value.is_nullish())
        this_value = &realm.global_object();
    auto* this_impl = TRY(impl_from(vm, this_value, u"forEach"sv, HTML::SecurityCheckType::Method));
    [[maybe_unused]] auto& this_object_realm = this_value.as_object().shape().realm();

    auto callback = vm.argument(0);
    if (!callback.is_function())
        return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAFunction, callback);

    Optional<JS::Completion> callback_exception;
    this_impl->for_each([&](auto key, auto value) -> IterationDecision {{
        JS::Value wrapped_key = {to_javascript_value(interface.iterable.key_type, "key", includes, context, "this_object_realm")};
        JS::Value wrapped_value = {to_javascript_value(interface.iterable.value_type, "value", includes, context, "this_object_realm")};
        auto completion = JS::call(vm, callback.as_function(), vm.argument(1), wrapped_value, wrapped_key, this_value);
        if (completion.is_error()) {{
            callback_exception = completion.release_error();
            return IterationDecision::Break;
        }}
        return IterationDecision::Continue;
    }});
    if (callback_exception.has_value())
        return callback_exception.release_value();

    return JS::js_undefined();
}}

""")


def write_iterator_prototype_implementation(
    out: TextIO,
    includes: GeneratedIncludes,
    interface: Interface,
) -> None:
    if interface.iterable is None or interface.iterable.key_type is None:
        return

    includes.add("LibJS/Runtime/Error.h")
    includes.add("LibJS/Runtime/HostObject.h")
    includes.add("LibJS/Runtime/PrimitiveString.h")
    includes.add("LibJS/Runtime/ValueInlines.h")
    includes.add("LibWeb/WebIDL/ExceptionOrUtils.h")
    includes.add(iterator_implementation_header_for_interface(interface))

    iterator_interface_name = f"{interface.name}Iterator"
    out.write(f"""void {interface.name}IteratorPrototype::initialize(JS::Realm& realm, JS::Object& object)
{{
    auto& vm = realm.vm();
    object.define_native_function(realm, vm.names.next, next, 0, JS::Attribute::Writable | JS::Attribute::Enumerable | JS::Attribute::Configurable);
    object.define_direct_property(vm.well_known_symbol_to_string_tag(), JS::PrimitiveString::create(vm, "{interface.name} Iterator"_utf16), JS::Attribute::Configurable);
}}

static JS::ThrowCompletionOr<{fully_qualified_name_for_interface(interface)}Iterator*> {make_name_acceptable_cpp(title_case_to_snake_case(iterator_interface_name))}_impl_from(JS::VM& vm)
{{
    auto this_object = TRY(vm.this_value().to_object(vm));
    auto* iterator = JS::host_data_if<{fully_qualified_name_for_interface(interface)}Iterator>(*this_object);
    if (!iterator) {{
        // NB: This runs after the check above, which no Window or Location object passes.
        TRY(HTML::perform_a_security_check(vm, this_object, u"next"sv, HTML::SecurityCheckType::Method));
        return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "{iterator_interface_name}");
    }}
    return iterator;
}}

JS_DEFINE_NATIVE_FUNCTION({interface.name}IteratorPrototype::next)
{{
    auto& realm = *vm.current_realm();
    auto this_value = vm.this_value();
    auto* impl = TRY({make_name_acceptable_cpp(title_case_to_snake_case(iterator_interface_name))}_impl_from(vm));
    [[maybe_unused]] auto& this_object_realm = this_value.as_object().shape().realm();
    return TRY(WebIDL::throw_dom_exception_if_needed(vm, realm, [&] {{ return impl->next(this_object_realm); }}));
}}

""")


def write_async_iterable_declaration_functions(
    out: TextIO,
    context: GenerationContext,
    includes: GeneratedIncludes,
    interface: Interface,
) -> None:
    if interface.async_iterable is None:
        return
    if interface.async_iterable.key_type is not None:
        raise RuntimeError(f"Unsupported pair async iterable declaration on '{interface.name}'")

    includes.add("LibWeb/WebIDL/ExceptionOrUtils.h")
    includes.add(async_iterator_implementation_header_for_interface(interface))

    add_header_includes_for_idl_type(interface.async_iterable.value_type, includes, context)
    if "ImplementedInBindings" in interface.async_iterable.extended_attributes:
        includes.add(bindings_glue_header_for_interface(interface))

    out.write(
        f"""JS_DEFINE_NATIVE_FUNCTION({interface.prototype_class}::values)
{{
    [[maybe_unused]] auto& realm = *vm.current_realm();
    auto this_value = vm.this_value();
    if (this_value.is_nullish())
        this_value = &realm.global_object();
    auto* impl = TRY(impl_from(vm, this_value, u"values"sv, HTML::SecurityCheckType::Method));
    [[maybe_unused]] auto& this_object_realm = this_value.as_object().shape().realm();

"""
    )
    write_operation_parameter_conversions(out, interface.async_iterable.parameters, includes, context)

    arguments = ", ".join(idl_identifier_cpp_name(parameter) for parameter in interface.async_iterable.parameters)
    if arguments:
        arguments = f", {arguments}"

    create_iterator = f"{fully_qualified_name_for_interface(interface)}AsyncIterator::create(this_object_realm, JS::Object::PropertyKind::Value, *impl"
    if "ImplementedInBindings" in interface.async_iterable.extended_attributes:
        create_iterator = "Web::Bindings::values(this_object_realm, *impl"

    out.write(
        f"""    return TRY(WebIDL::throw_dom_exception_if_needed(vm, realm, [&] {{ return {create_iterator}{arguments}); }}));
}}

"""
    )


def write_async_iterator_prototype_implementation(
    out: TextIO,
    includes: GeneratedIncludes,
    interface: Interface,
) -> None:
    if interface.async_iterable is None:
        return

    includes.add("AK/StringView.h")
    includes.add("LibJS/Runtime/PrimitiveString.h")
    includes.add("LibWeb/WebIDL/ExceptionOrUtils.h")
    includes.add("LibWeb/WebIDL/AsyncIterator.h")
    includes.add(async_iterator_implementation_header_for_interface(interface))

    out.write(
        f"""void {interface.name}AsyncIteratorPrototype::initialize(JS::Realm& realm, JS::Object& object)
{{
    auto& vm = realm.vm();
    object.define_direct_property(vm.well_known_symbol_to_string_tag(), JS::PrimitiveString::create(vm, "{interface.name} AsyncIterator"_utf16), JS::Attribute::Configurable);

    object.define_native_function(realm, vm.names.next, next, 0, JS::default_attributes);
    {"object.define_native_function(realm, vm.names.return_, return_, 1, JS::default_attributes);" if "DefinesAsyncIteratorReturn" in interface.extended_attributes else ""}
}}

JS_DEFINE_NATIVE_FUNCTION({interface.name}AsyncIteratorPrototype::next)
{{
    auto& realm = *vm.current_realm();

    return TRY(WebIDL::throw_dom_exception_if_needed(vm, realm, [&] {{
        return WebIDL::AsyncIterator::next<{fully_qualified_name_for_interface(interface)}AsyncIterator>(realm, "{interface.name}AsyncIterator"sv);
    }}));
}}
"""
    )

    if "DefinesAsyncIteratorReturn" in interface.extended_attributes:
        out.write(f"""
JS_DEFINE_NATIVE_FUNCTION({interface.name}AsyncIteratorPrototype::return_)
{{
    auto& realm = *vm.current_realm();

    auto value = vm.argument(0);

    return TRY(WebIDL::throw_dom_exception_if_needed(vm, realm, [&] {{
        return WebIDL::AsyncIterator::return_<{fully_qualified_name_for_interface(interface)}AsyncIterator>(realm, "{interface.name}AsyncIterator"sv, value);
    }}));
}}
""")


def write_maplike_declaration_functions(
    out: TextIO,
    context: GenerationContext,
    includes: GeneratedIncludes,
    interface: Interface,
) -> None:
    if interface.maplike is None:
        return

    includes.add("LibJS/Runtime/AbstractOperations.h")
    includes.add("LibJS/Runtime/Error.h")
    includes.add("LibJS/Runtime/Map.h")
    includes.add("LibJS/Runtime/MapIterator.h")
    includes.add("LibJS/Runtime/ValueInlines.h")
    includes.add("LibWeb/WebIDL/ExceptionOrUtils.h")
    includes.add(bindings_glue_header_for_interface(interface))

    if not is_string_type(interface.maplike.key_type.name):
        raise RuntimeError(f"Unsupported maplike key type '{interface.maplike.key_type.name}' on '{interface.name}'")

    out.write(f"""// https://webidl.spec.whatwg.org/#js-map-size
JS_DEFINE_NATIVE_FUNCTION({interface.prototype_class}::get_size)
{{
    auto& realm = *vm.current_realm();
    auto this_value = vm.this_value();
    if (this_value.is_nullish())
        this_value = &realm.global_object();

    // 1. Let O be the this value, implementation-checked against A with identifier "size" and type "getter".
    auto* this_impl = TRY(impl_from(vm, this_value, u"size"sv, HTML::SecurityCheckType::Getter));
    [[maybe_unused]] auto& this_object_realm = this_value.as_object().shape().realm();

    // 2. Let map be the map entries of the IDL value that represents a reference to O.
    GC::Ref<JS::Map> map = map_entries(this_object_realm, *this_impl);

    // 3. Return map’s size, converted to a JavaScript value.
    return map->map_size();
}}

// https://webidl.spec.whatwg.org/#js-map-entries
JS_DEFINE_NATIVE_FUNCTION({interface.prototype_class}::entries)
{{
    auto& realm = *vm.current_realm();
    auto this_value = vm.this_value();
    if (this_value.is_nullish())
        this_value = &realm.global_object();

    // 1. Let O be the this value, implementation-checked against A with identifier "entries" and type "method".
    auto* this_impl = TRY(impl_from(vm, this_value, u"entries"sv, HTML::SecurityCheckType::Method));
    auto& this_object_realm = this_value.as_object().shape().realm();

    // 2. Let map be the map entries of the IDL value that represents a reference to O.
    GC::Ref<JS::Map> map = map_entries(this_object_realm, *this_impl);

    // 3. Return the result of creating a map iterator from map with kind "key+value".
    return JS::MapIterator::create(this_object_realm, *map, JS::Object::PropertyKind::KeyAndValue);
}}

// https://webidl.spec.whatwg.org/#js-map-keys
JS_DEFINE_NATIVE_FUNCTION({interface.prototype_class}::keys)
{{
    auto& realm = *vm.current_realm();
    auto this_value = vm.this_value();
    if (this_value.is_nullish())
        this_value = &realm.global_object();

    // 1. Let O be the this value, implementation-checked against A with identifier "keys" and type "method".
    auto* this_impl = TRY(impl_from(vm, this_value, u"keys"sv, HTML::SecurityCheckType::Method));
    auto& this_object_realm = this_value.as_object().shape().realm();

    // 2. Let map be the map entries of the IDL value that represents a reference to O.
    GC::Ref<JS::Map> map = map_entries(this_object_realm, *this_impl);

    // 3. Return the result of creating a map iterator from map with kind "key".
    return JS::MapIterator::create(this_object_realm, *map, JS::Object::PropertyKind::Key);
}}

// https://webidl.spec.whatwg.org/#js-map-values
JS_DEFINE_NATIVE_FUNCTION({interface.prototype_class}::values)
{{
    auto& realm = *vm.current_realm();
    auto this_value = vm.this_value();
    if (this_value.is_nullish())
        this_value = &realm.global_object();

    // 1. Let O be the this value, implementation-checked against A with identifier "values" and type "method".
    auto* this_impl = TRY(impl_from(vm, this_value, u"values"sv, HTML::SecurityCheckType::Method));
    auto& this_object_realm = this_value.as_object().shape().realm();

    // 2. Let map be the map entries of the IDL value that represents a reference to O.
    GC::Ref<JS::Map> map = map_entries(this_object_realm, *this_impl);

    // 3. Return the result of creating a map iterator from map with kind "value".
    return JS::MapIterator::create(this_object_realm, *map, JS::Object::PropertyKind::Value);
}}

// https://webidl.spec.whatwg.org/#js-map-forEach
JS_DEFINE_NATIVE_FUNCTION({interface.prototype_class}::for_each)
{{
    auto& realm = *vm.current_realm();
    auto this_value = vm.this_value();
    if (this_value.is_nullish())
        this_value = &realm.global_object();

    // 1. Let O be the this value, implementation-checked against A with identifier "forEach" and type "method".
    auto* this_impl = TRY(impl_from(vm, this_value, u"forEach"sv, HTML::SecurityCheckType::Method));
    auto& this_object_realm = this_value.as_object().shape().realm();

    // 2. Let map be the map entries of the IDL value that represents a reference to O.
    GC::Ref<JS::Map> map = map_entries(this_object_realm, *this_impl);

    // 3. Let callbackFn be the first argument passed to the function, or undefined if not supplied.
    auto callback = vm.argument(0);

    // 4. If IsCallable(callbackFn) is false, throw a TypeError.
    if (!callback.is_function())
        return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAFunction, callback);

    // 5. Let thisArg be the second argument passed to the function, or undefined if not supplied.
    auto this_arg = vm.argument(1);

    // 6. For each key → value of map:
    TRY(map->for_each_entry([&](JS::Value key, JS::Value value) -> JS::ThrowCompletionOr<void> {{
        // 1. Let jsKey and jsValue be key and value converted to a JavaScript value.
        // 2. Perform ? Call(callbackFn, thisArg, « jsValue, jsKey, O »).
        TRY(JS::call(vm, callback.as_function(), this_arg, value, key, this_value));
        return {{}};
    }}));

    // 7. Return undefined.
    return JS::js_undefined();
}}

// https://webidl.spec.whatwg.org/#js-map-get
JS_DEFINE_NATIVE_FUNCTION({interface.prototype_class}::get)
{{
    [[maybe_unused]] auto& realm = *vm.current_realm();
    auto this_value = vm.this_value();
    if (this_value.is_nullish())
        this_value = &realm.global_object();

    // 1. Let O be the this value, implementation-checked against A with identifier "get" and type "method".
    auto* this_impl = TRY(impl_from(vm, this_value, u"get"sv, HTML::SecurityCheckType::Method));
    auto& this_object_realm = this_value.as_object().shape().realm();

    // 3. Let keyType be the key type specified in the maplike declaration.
    // 4. Let keyArg be the first argument passed to this function, or undefined if not supplied.
    // 5. Let key be keyArg converted to an IDL value of type keyType.
    auto key_arg = vm.argument(0);
    auto key = TRY(key_arg.to_utf16_string(vm));

    // FIXME: 6. If key is -0, set key to +0.

    // 7. If map[key] exists, then return map[key], converted to a JavaScript value.
    auto result = map_get(this_object_realm, *this_impl, key);
    return result.value_or(JS::js_undefined());
}}

// https://webidl.spec.whatwg.org/#js-map-has
JS_DEFINE_NATIVE_FUNCTION({interface.prototype_class}::has)
{{
    [[maybe_unused]] auto& realm = *vm.current_realm();
    auto this_value = vm.this_value();
    if (this_value.is_nullish())
        this_value = &realm.global_object();

    // 1. Let O be the this value, implementation-checked against A with identifier "has" and type "method".
    auto* this_impl = TRY(impl_from(vm, this_value, u"has"sv, HTML::SecurityCheckType::Method));

    // 3. Let keyType be the key type specified in the maplike declaration.
    // 4. Let keyArg be the first argument passed to this function, or undefined if not supplied.
    // 5. Let key be keyArg converted to an IDL value of type keyType.
    auto key_arg = vm.argument(0);
    auto key = TRY(key_arg.to_utf16_string(vm));

    // FIXME: 6. If key is -0, set key to +0.

    // 7. If map[key] exists, then return true; otherwise return false.
    return map_has(*this_impl, key);
}}
""")

    # If A does not declare a member with identifier "set", and A was declared with a read–write maplike declaration,
    # then there must exist a set data property on A’s interface prototype object with the following characteristics:
    if "set" not in operation_callback_names(interface) and not interface.maplike.readonly:
        out.write(f"""// https://webidl.spec.whatwg.org/#js-map-set
JS_DEFINE_NATIVE_FUNCTION({interface.prototype_class}::set)
{{
    auto& realm = *vm.current_realm();
    auto this_value = vm.this_value();
    if (this_value.is_nullish())
        this_value = &realm.global_object();

    // 1. Let O be the this value, implementation-checked against A with identifier "set" and type "method".
    auto* this_impl = TRY(impl_from(vm, this_value, u"set"sv, HTML::SecurityCheckType::Method));
    auto& this_object_realm = this_value.as_object().shape().realm();

    // 3. Let keyType be the key type specified in the maplike declaration, and valueType be the value type.
    // 4. Let keyArg be the first argument passed to this function, or undefined if not supplied.
    // 5. Let key be keyArg converted to an IDL value of type keyType.
    auto key_arg = vm.argument(0);
    auto key = TRY(key_arg.to_utf16_string(vm));

    // FIXME: 6. If key is -0, set key to +0.

    // 7. Let valueArg be the second argument passed to this function, or undefined if not supplied.
    // 8. Let value be valueArg converted to an IDL value of type valueType.
    auto value = vm.argument(1);
    {type_check_idl_value(interface.maplike.value_type, "value", includes, context, interface.name)}

    // 9. Set map[key] to value.
    TRY(WebIDL::throw_dom_exception_if_needed(vm, realm, [&] {{ return Web::Bindings::set(this_object_realm, *this_impl, key, value); }}));

    // 10. Return O.
    return vm.this_value();
}}

""")

    # If A does not declare a member with identifier "delete", and A was declared with a read–write maplike declaration,
    # then there must exist a delete data property on A’s interface prototype object with the following characteristics:
    if "delete_" not in operation_callback_names(interface) and not interface.maplike.readonly:
        out.write(f"""// https://webidl.spec.whatwg.org/#js-map-delete
JS_DEFINE_NATIVE_FUNCTION({interface.prototype_class}::delete_)
{{
    auto& realm = *vm.current_realm();
    auto this_value = vm.this_value();
    if (this_value.is_nullish())
        this_value = &realm.global_object();

    // 1. Let O be the this value, implementation-checked against A with identifier "delete" and type "method".
    auto* this_impl = TRY(impl_from(vm, this_value, u"delete"sv, HTML::SecurityCheckType::Method));

    // 3. Let keyType be the key type specified in the maplike declaration.
    // 4. Let keyArg be the first argument passed to this function, or undefined if not supplied.
    // 5. Let key be keyArg converted to an IDL value of type keyType.
    auto key_arg = vm.argument(0);
    auto key = TRY(key_arg.to_utf16_string(vm));

    // FIXME: 6. If key is -0, set key to +0.

    // 7. Let retVal be true if map[key] exists, or else false.
    // 8. Remove map[key].
    auto result = map_remove(*this_impl, key);

    // 9. Return retVal.
    return result;
}}

""")

    # If A does not declare a member with identifier "clear", and A was declared with a read–write maplike declaration,
    # then there must exist a clear data property on A’s interface prototype object with the following characteristics:
    if "clear" not in operation_callback_names(interface) and not interface.maplike.readonly:
        out.write(f"""// https://webidl.spec.whatwg.org/#js-map-delete
JS_DEFINE_NATIVE_FUNCTION({interface.prototype_class}::clear)
{{
    auto& realm = *vm.current_realm();
    auto this_value = vm.this_value();
    if (this_value.is_nullish())
        this_value = &realm.global_object();

    // 1. Let O be the this value, implementation-checked against A with identifier "clear" and type "method".
    auto* this_impl = TRY(impl_from(vm, this_value, u"clear"sv, HTML::SecurityCheckType::Method));

    // 3. Clear map.
    // NOTE: The map is preserved because there may be existing iterators, currently suspended, iterating over it.
    map_clear(*this_impl);

    // 4. Return undefined.
    return JS::js_undefined();
}}

""")


def write_setlike_declaration_functions(
    out: TextIO,
    context: GenerationContext,
    includes: GeneratedIncludes,
    interface: Interface,
) -> None:
    if interface.setlike is None:
        return

    includes.add("LibJS/Runtime/AbstractOperations.h")
    includes.add("LibJS/Runtime/Error.h")
    includes.add("LibJS/Runtime/Set.h")
    includes.add("LibJS/Runtime/SetIterator.h")
    includes.add("LibJS/Runtime/ValueInlines.h")
    includes.add("LibWeb/WebIDL/ExceptionOrUtils.h")
    includes.add("LibWeb/Bindings/WrapperWorld.h")
    includes.add(bindings_glue_header_for_interface(interface))

    out.write(f"""// https://webidl.spec.whatwg.org/#js-set-size
JS_DEFINE_NATIVE_FUNCTION({interface.prototype_class}::get_size)
{{
    auto& realm = *vm.current_realm();
    auto this_value = vm.this_value();
    if (this_value.is_nullish())
        this_value = &realm.global_object();

    // 1. Let O be the this value, implementation-checked against A with identifier "size" and type "getter".
    auto* this_impl = TRY(impl_from(vm, this_value, u"size"sv, HTML::SecurityCheckType::Getter));
    auto& this_object_realm = this_value.as_object().shape().realm();
    auto& wrapper_world = host_defined_wrapper_world(this_object_realm);

    // 2. Let set be the set entries of the IDL value that represents a reference to O.
    GC::Ref<JS::Set> set = setlike_entries(this_object_realm, wrapper_world, *this_impl);

    // 3. Return set’s size, converted to a JavaScript value.
    return set->set_size();
}}

// https://webidl.spec.whatwg.org/#js-set-entries
JS_DEFINE_NATIVE_FUNCTION({interface.prototype_class}::entries)
{{
    auto& realm = *vm.current_realm();
    auto this_value = vm.this_value();
    if (this_value.is_nullish())
        this_value = &realm.global_object();

    // 1. Let O be the this value, implementation-checked against A with identifier "entries" and type "method".
    auto* this_impl = TRY(impl_from(vm, this_value, u"entries"sv, HTML::SecurityCheckType::Method));
    auto& this_object_realm = this_value.as_object().shape().realm();
    auto& wrapper_world = host_defined_wrapper_world(this_object_realm);

    // 2. Let set be the set entries of the IDL value that represents a reference to O.
    GC::Ref<JS::Set> set = setlike_entries(this_object_realm, wrapper_world, *this_impl);

    // 3. Return the result of creating a set iterator from set with kind "key+value".
    return JS::SetIterator::create(realm, *set, JS::Object::PropertyKind::KeyAndValue);
}}

// https://webidl.spec.whatwg.org/#js-set-values
JS_DEFINE_NATIVE_FUNCTION({interface.prototype_class}::values)
{{
    auto& realm = *vm.current_realm();
    auto this_value = vm.this_value();
    if (this_value.is_nullish())
        this_value = &realm.global_object();

    // 1. Let O be the this value, implementation-checked against A with identifier "values" and type "method".
    auto* this_impl = TRY(impl_from(vm, this_value, u"values"sv, HTML::SecurityCheckType::Method));
    auto& this_object_realm = this_value.as_object().shape().realm();
    auto& wrapper_world = host_defined_wrapper_world(this_object_realm);

    // 2. Let set be the set entries of the IDL value that represents a reference to O.
    GC::Ref<JS::Set> set = setlike_entries(this_object_realm, wrapper_world, *this_impl);

    // 3. Return the result of creating a set iterator from set with kind "value".
    return JS::SetIterator::create(realm, *set, JS::Object::PropertyKind::Value);
}}

// https://webidl.spec.whatwg.org/#js-set-forEach
JS_DEFINE_NATIVE_FUNCTION({interface.prototype_class}::for_each)
{{
    auto& realm = *vm.current_realm();
    auto this_value = vm.this_value();
    if (this_value.is_nullish())
        this_value = &realm.global_object();

    // 1. Let O be the this value, implementation-checked against A with identifier "forEach" and type "method".
    auto* this_impl = TRY(impl_from(vm, this_value, u"forEach"sv, HTML::SecurityCheckType::Method));
    auto& this_object_realm = this_value.as_object().shape().realm();
    auto& wrapper_world = host_defined_wrapper_world(this_object_realm);

    // 2. Let set be the set entries of the IDL value that represents a reference to O.
    GC::Ref<JS::Set> set = setlike_entries(this_object_realm, wrapper_world, *this_impl);

    // 3. Let callbackFn be the first argument passed to the function, or undefined if not supplied.
    // 4. If IsCallable(callbackFn) is false, throw a TypeError.
    auto callback = vm.argument(0);
    if (!callback.is_function())
        return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAFunction, callback);

    // 5. Let thisArg be the second argument passed to the function, or undefined if not supplied.
    auto this_arg = vm.argument(1);

    // 6. For each value of set:
    TRY(set->for_each_value([&](JS::Value value) -> JS::ThrowCompletionOr<void> {{
        // 1. Let jsValue be value converted to a JavaScript value.

        // 2. Perform ? Call(callbackFn, thisArg, « jsValue, jsValue, O»).
        TRY(JS::call(vm, callback.as_function(), this_arg, value, value, this_value));
        return {{}};
    }}));

    // 7. Return undefined.
    return JS::js_undefined();
}}

// https://webidl.spec.whatwg.org/#js-set-has
JS_DEFINE_NATIVE_FUNCTION({interface.prototype_class}::has)
{{

    // 1. Let O be the this value, implementation-checked against A with identifier "has" and type "method".
    auto* this_impl = TRY(impl_from(vm, u"has"sv, HTML::SecurityCheckType::Method));

    // 3. Let valueType be the value type specified in the setlike declaration.
    // 4. Let valueArg be the first argument passed to this function, or undefined if not supplied.
    // 5. Let value be valueArg converted to an IDL value of type valueType.
    // FIXME: 6. If value is -0, set value to +0.
    auto value = vm.argument(0);
    {type_check_idl_value(interface.setlike.value_type, "value", includes, context, interface.name)}

    // 7. If set contains value, then return true, otherwise return false.
    return setlike_has(*this_impl, value);
}}

""")

    # If A does not declare a member with identifier "add", and A was declared with a read–write setlike declaration,
    # then there must exist an add data property on A’s interface prototype object with the following characteristics:
    if "add" not in operation_callback_names(interface) and not interface.setlike.readonly:
        out.write(f"""// https://webidl.spec.whatwg.org/#js-set-add
JS_DEFINE_NATIVE_FUNCTION({interface.prototype_class}::add)
{{

    // 1. Let O be the this value, implementation-checked against A with identifier "add" and type "method".
    auto* this_impl = TRY(impl_from(vm, u"add"sv, HTML::SecurityCheckType::Method));

    // 3. Let valueType be the value type specified in the setlike declaration.
    // 4. Let valueArg be the first argument passed to this function, or undefined if not supplied.
    // 5. Let value be valueArg converted to an IDL value of type valueType.
    // FIXME: 6. If value is -0, set value to +0.
    auto value = vm.argument(0);
    {type_check_idl_value(interface.setlike.value_type, "value", includes, context, interface.name)}

    // 6. Append value to set.
    setlike_add(*this_impl, value);
    setlike_on_set_modified_from_js(*this_impl);

    return vm.this_value();
}}

""")

    # If A does not declare a member with identifier "delete", and A was declared with a read–write setlike declaration,
    # then there must exist a delete data property on A’s interface prototype object with the following characteristics:
    if "delete_" not in operation_callback_names(interface) and not interface.setlike.readonly:
        out.write(f"""// https://webidl.spec.whatwg.org/#js-set-delete
JS_DEFINE_NATIVE_FUNCTION({interface.prototype_class}::delete_)
{{

    // 1. Let O be the this value, implementation-checked against A with identifier "delete" and type "method".
    auto* this_impl = TRY(impl_from(vm, u"delete"sv, HTML::SecurityCheckType::Method));

    // 3. Let valueType be the value type specified in the setlike declaration.
    // 4. Let valueArg be the first argument passed to this function, or undefined if not supplied.
    // 5. Let value be valueArg converted to an IDL value of type valueType.
    // 6. FIXME: If value is -0, set value to +0.
    auto value = vm.argument(0);
    {type_check_idl_value(interface.setlike.value_type, "value", includes, context, interface.name)}

    // 7. Let retVal be true if set contains value, or else false.
    // 8. Remove value from set.
    auto result = setlike_remove(*this_impl, value);
    setlike_on_set_modified_from_js(*this_impl);

    // 9. Return retVal.
    return result;
}}

""")

    # If A does not declare a member with identifier "clear", and A was declared with a read–write setlike declaration,
    # then there must exist a clear data property on A’s interface prototype object with the following characteristics:
    if "clear" not in operation_callback_names(interface) and not interface.setlike.readonly:
        out.write(f"""// https://webidl.spec.whatwg.org/#js-set-clear
JS_DEFINE_NATIVE_FUNCTION({interface.prototype_class}::clear)
{{

    // 1. Let O be the this value, implementation-checked against A with identifier "clear" and type "method".
    auto* this_impl = TRY(impl_from(vm, u"clear"sv, HTML::SecurityCheckType::Method));

    // 3. Empty set.
    // NOTE: Note: The set is preserved because there may be existing iterators, currently suspended, iterating over it.
    setlike_clear(*this_impl);
    setlike_on_set_modified_from_js(*this_impl);

    // 4. Return undefined.
    return JS::js_undefined();
}}

""")