Skip to content

Truly independent web browser

Meta: Give a dictionary a representation in each language that names it

Aliaksandr Kalenik7122e2f805e3
diff --git a/Meta/CMake/libweb_generators.cmake b/Meta/CMake/libweb_generators.cmake
index 2bdc3b4564c..99d6d25e4df 100644
--- a/Meta/CMake/libweb_generators.cmake
+++ b/Meta/CMake/libweb_generators.cmake
@@ -313,7 +313,10 @@ function (generate_js_bindings target)
"${LADYBIRD_SOURCE_DIR}/Meta/Generators/libweb_bindings/overload_resolution.py"
"${LADYBIRD_SOURCE_DIR}/Meta/Generators/libweb_bindings/realms.py"
"${LADYBIRD_SOURCE_DIR}/Meta/Generators/libweb_bindings/rust_bindings.py"
+ "${LADYBIRD_SOURCE_DIR}/Meta/Generators/libweb_bindings/rust_names.py"
+ "${LADYBIRD_SOURCE_DIR}/Meta/Generators/libweb_bindings/rust_to_js_value.py"
"${LADYBIRD_SOURCE_DIR}/Meta/Generators/libweb_bindings/rust_types.py"
+ "${LADYBIRD_SOURCE_DIR}/Meta/Generators/libweb_bindings/rust_usage.py"
"${LADYBIRD_SOURCE_DIR}/Meta/Generators/libweb_bindings/security_checks.py"
"${LADYBIRD_SOURCE_DIR}/Meta/Generators/libweb_bindings/structured_serialize.py"
"${LADYBIRD_SOURCE_DIR}/Meta/Generators/libweb_bindings/to_idl_value.py"
diff --git a/Meta/Generators/generate_libweb_bindings.py b/Meta/Generators/generate_libweb_bindings.py
index 9e0278fbefb..600c6722abc 100644
--- a/Meta/Generators/generate_libweb_bindings.py
+++ b/Meta/Generators/generate_libweb_bindings.py
@@ -27,6 +27,7 @@ from Generators.libweb_bindings.intrinsics import write_exposed_interface_implem
from Generators.libweb_bindings.intrinsics import write_intrinsic_definitions_header
from Generators.libweb_bindings.intrinsics import write_intrinsic_definitions_implementation
from Generators.libweb_bindings.intrinsics import write_wrapper_factory_implementation
+from Generators.libweb_bindings.rust_usage import DefinitionUsage
from Generators.libweb_bindings.structured_serialize import write_structured_serialize_bindings_implementation
from Generators.libweb_bindings.to_idl_value import dictionaries_in_dependency_order
from Generators.libweb_bindings.to_idl_value import write_dictionary_conversion
@@ -102,7 +103,7 @@ def write_common_enumerations_header(out: TextIO, module: Module) -> None:
out.write("} // namespace Web::Bindings\n")
-def write_idl_header(out: TextIO, module: Module, context: GenerationContext) -> None:
+def write_idl_header(out: TextIO, module: Module, context: GenerationContext, usage: DefinitionUsage) -> None:
includes = GeneratedIncludes(local_type_names(module))
body = StringIO()
@@ -118,8 +119,8 @@ def write_idl_header(out: TextIO, module: Module, context: GenerationContext) ->
write_enumeration_declaration(body, enumeration, includes)
write_enumeration_to_javascript_value_declaration(body, enumeration, includes)
- # NB: The dictionaries of an interface implemented in Rust only exist in its Rust bindings.
- for dictionary in dictionaries_in_dependency_order(rust_bindings.cpp_dictionaries(module), context):
+ # NB: A dictionary that only the bindings of the interfaces implemented in Rust convert has no C++ representation.
+ for dictionary in dictionaries_in_dependency_order(usage.cpp_dictionaries(module), context):
write_dictionary_declaration(body, dictionary, includes, context)
write_dictionary_to_javascript_value_declaration(body, dictionary)
@@ -130,7 +131,7 @@ def write_idl_header(out: TextIO, module: Module, context: GenerationContext) ->
out.write("} // namespace Web::Bindings\n")
-def write_idl_implementation(out: TextIO, module: Module, context: GenerationContext) -> None:
+def write_idl_implementation(out: TextIO, module: Module, context: GenerationContext, usage: DefinitionUsage) -> None:
includes = GeneratedIncludes(local_type_names(module))
includes.add_binding(module.path.stem)
body = StringIO()
@@ -144,7 +145,7 @@ def write_idl_implementation(out: TextIO, module: Module, context: GenerationCon
write_enumeration_conversion(body, enumeration, includes)
write_enumeration_to_javascript_value_conversion(body, enumeration)
- for dictionary in rust_bindings.cpp_dictionaries(module):
+ for dictionary in usage.cpp_dictionaries(module):
write_dictionary_conversion(body, dictionary, includes, context)
write_dictionary_to_javascript_value_conversion(body, dictionary, includes, context)
@@ -175,7 +176,7 @@ def write_global_mixin_idl_header(out: TextIO, interface, context: GenerationCon
out.write("} // namespace Web::Bindings\n")
-def write_forward_header(out: TextIO, modules: List[Module]) -> None:
+def write_forward_header(out: TextIO, modules: List[Module], usage: DefinitionUsage) -> None:
out.write(
"""#pragma once
@@ -208,7 +209,7 @@ def write_forward_header(out: TextIO, modules: List[Module]) -> None:
"""
)
- dictionary_names = {dictionary.name for module in modules for dictionary in rust_bindings.cpp_dictionaries(module)}
+ dictionary_names = {dictionary.name for module in modules for dictionary in usage.cpp_dictionaries(module)}
out.write(
"""namespace Web::Bindings {
@@ -268,8 +269,11 @@ def main() -> int:
context = GenerationContext(modules)
modules = context.modules
+ usage = DefinitionUsage(context)
+ interface_sets = collect_interface_sets(modules)
+
try:
- rust_bindings.check_rust_bindings(context, modules)
+ rust_bindings.check_rust_bindings(context, usage, interface_sets.intrinsics)
except rust_bindings.UnsupportedByRustBindings as error:
print(f"error: {error}", file=sys.stderr)
return 1
@@ -282,16 +286,14 @@ def main() -> int:
implementation_path = output_directory / f"{path.stem}.cpp"
common_header_path = common_output_directory / f"{path.stem}.h"
- write_generated_file(header_path, write_idl_header, module, context)
- write_generated_file(implementation_path, write_idl_implementation, module, context)
+ write_generated_file(header_path, write_idl_header, module, context, usage)
+ write_generated_file(implementation_path, write_idl_implementation, module, context, usage)
write_generated_file(common_header_path, write_common_enumerations_header, module)
output_files.append(common_header_path)
output_files.append(header_path)
output_files.append(implementation_path)
- interface_sets = collect_interface_sets(modules)
-
intrinsic_definitions_header_path = output_directory / "IntrinsicDefinitions.h"
intrinsic_definitions_implementation_path = output_directory / "IntrinsicDefinitions.cpp"
@@ -323,7 +325,7 @@ def main() -> int:
output_files.append(exposed_interface_implementation_path)
forward_header_path = output_directory / "Forward.h"
- write_generated_file(forward_header_path, write_forward_header, modules)
+ write_generated_file(forward_header_path, write_forward_header, modules, usage)
output_files.append(forward_header_path)
for global_mixin_interface_name in (
@@ -349,7 +351,7 @@ def main() -> int:
rust_bindings_path = output_directory / "RustBindings.rs"
write_generated_file(
- rust_bindings_path, rust_bindings.write_rust_bindings, context, modules, interface_sets.intrinsics
+ rust_bindings_path, rust_bindings.write_rust_bindings, context, usage, interface_sets.intrinsics
)
output_files.append(rust_bindings_path)
diff --git a/Meta/Generators/libweb_bindings/rust_bindings.py b/Meta/Generators/libweb_bindings/rust_bindings.py
index 97404cb4d25..07b9097df4e 100644
--- a/Meta/Generators/libweb_bindings/rust_bindings.py
+++ b/Meta/Generators/libweb_bindings/rust_bindings.py
@@ -14,9 +14,9 @@
# 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.
+from io import StringIO
from typing import Dict
from typing import List
-from typing import Optional
from typing import TextIO
from Generators.libweb_bindings.context import GenerationContext
@@ -24,53 +24,29 @@ from Generators.libweb_bindings.includes import GeneratedIncludes
from Generators.libweb_bindings.overload_resolution import operation_length
from Generators.libweb_bindings.overload_resolution import operation_overload_sets
from Generators.libweb_bindings.overload_resolution import parameter_list_length
+from Generators.libweb_bindings.rust_names import rust_identifier
+from Generators.libweb_bindings.rust_names import rust_local_name
+from Generators.libweb_bindings.rust_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_types import UnsupportedByRustBindings
-from Generators.libweb_bindings.rust_types import check_type_is_supported
from Generators.libweb_bindings.rust_types import rust_conversion_to_idl_value
from Generators.libweb_bindings.rust_types import rust_default_value
+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.rust_usage import is_implemented_in_rust
from Generators.libweb_bindings.wrappers import wrapper_name
from Utils.utils import title_case_to_snake_case
from Utils.webidl_parser import Constructor
-from Utils.webidl_parser import Dictionary
-from Utils.webidl_parser import IDLType
from Utils.webidl_parser import Interface
from Utils.webidl_parser import Module
from Utils.webidl_parser import OperationParameter
-RUST_KEYWORDS = {
- "as", "async", "await", "break", "const", "continue", "crate", "dyn", "else", "enum", "extern", "false", "fn", "for",
- "if", "impl", "in", "let", "loop", "match", "mod", "move", "mut", "pub", "ref", "return", "self", "static",
- "struct", "super", "trait", "true", "type", "unsafe", "use", "where", "while", "abstract", "become", "box", "do",
- "final", "gen", "macro", "override", "priv", "try", "typeof", "unsized", "virtual", "yield",
-} # fmt: skip
-
# The extended attributes of an interface and of its members that the Rust bindings handle.
SUPPORTED_INTERFACE_EXTENDED_ATTRIBUTES = {"Exposed", "ImplementedIn", "SecureContext", "Experimental"}
SUPPORTED_MEMBER_EXTENDED_ATTRIBUTES = {"NewObject", "SameObject"}
-# Names that Rust does not accept as raw identifiers either.
-RUST_RESERVED_NAMES = {"self", "Self", "crate", "super"}
-
-
-def is_implemented_in_rust(interface: Optional[Interface]) -> bool:
- return interface is not None and interface.extended_attributes.get("ImplementedIn") == "Rust"
-
-
-def rust_identifier(name: str) -> str:
- identifier = title_case_to_snake_case(name).replace("-", "_")
- if identifier in RUST_RESERVED_NAMES:
- return f"{identifier}_"
- if identifier in RUST_KEYWORDS:
- return f"r#{identifier}"
- return identifier
-
-
-def rust_local_name(name: str) -> str:
- """The local variable that holds the IDL value of a parameter, which never clashes with the generated ones."""
- return f"idl_{rust_identifier(name).removeprefix('r#')}"
-
def rust_module_name(interface: Interface) -> str:
return title_case_to_snake_case(interface.name)
@@ -84,17 +60,9 @@ def wrapper_host_class_symbol(interface: Interface) -> str:
return f"web_bindings_{wrapper_name(interface)}_host_class"
-def implementation_module(interface: Interface) -> str:
- """The Rust module of the implementation and of the dictionaries of its IDL, which follows from the IDL path:
- Encoding/TextEncoder.idl names crate::encoding::text_encoder."""
- parts = interface.path.parts
- namespace = parts[parts.index("LibWeb") + 1]
- return f"crate::{title_case_to_snake_case(namespace)}::{rust_module_name(interface)}"
-
-
def implementation_path(interface: Interface) -> str:
"""The Rust path of the implementation: crate::encoding::text_encoder::TextEncoder for Encoding/TextEncoder.idl."""
- return f"{implementation_module(interface)}::{interface.name}"
+ return f"{rust_module_path(interface.path)}::{interface.name}"
def interface_name_values(intrinsics: List[Interface]) -> Dict[str, int]:
@@ -103,12 +71,9 @@ def interface_name_values(intrinsics: List[Interface]) -> Dict[str, int]:
return {interface.name: index for index, interface in enumerate(intrinsics, start=1)}
-def cpp_dictionaries(module: Module) -> List[Dictionary]:
- return [] if is_implemented_in_rust(module.interface) else list(module.dictionaries)
-
-
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."""
+ """Raises an error that names what the Rust bindings do not handle yet, for everything that the functions that
+ write the bindings do not reject themselves."""
def fail(message: str) -> None:
raise UnsupportedByRustBindings(f"{interface.path}: {interface.name} is [ImplementedIn=Rust], but {message}")
@@ -157,124 +122,36 @@ def check_interface_is_supported(interface: Interface, module: Module, context:
for operation in interface.regular_operations:
check_member_attributes(operation.name, operation.extended_attributes)
- def check_dictionaries_are_local(idl_type, what: str) -> None:
- for nested_type in [idl_type, *idl_type.nested_types()]:
- dictionary = context.dictionaries.get(nested_type.name)
- if dictionary is not None and dictionary not in module.dictionaries:
- fail(f"{what} uses {dictionary.name}, a dictionary of another module")
-
for attribute in interface.regular_attributes:
check_member_attributes(attribute.name, attribute.extended_attributes)
- check_dictionaries_are_local(attribute.type, f"{interface.name}.{attribute.name}")
if not attribute.readonly:
fail(f"its attribute {attribute.name} is not readonly")
- check_type_is_supported(attribute.type, context, f"{interface.name}.{attribute.name}")
-
- def check_parameters(what: str, parameters: List[OperationParameter]) -> None:
- for parameter in parameters:
- if parameter.variadic:
- fail(f"{what} has a variadic parameter")
- parameter_what = f"the parameter {parameter.name} of {what}"
- unsupported = set(parameter.extended_attributes) - {"AllowShared", "AllowResizable"}
- if unsupported:
- fail(f"{parameter_what} has the extended attributes {sorted(unsupported)}")
- check_type_is_supported(parameter.type, context, parameter_what)
- check_dictionaries_are_local(parameter.type, parameter_what)
- rust_conversion_to_idl_value(
- parameter.type, parameter.extended_attributes, "value", parameter.name, context, parameter_what
- )
- if parameter.optional and parameter.default_value is not None:
- rust_default_value(parameter, context, parameter_what)
-
- for constructor in interface.constructors:
- check_parameters(constructor_description(interface), constructor.parameters)
for name, operations in operation_overload_sets(interface).items():
if len(operations) > 1:
fail(f"its operation {name} is overloaded")
- operation = operations[0]
- what = f"{interface.name}.{name}()"
- check_type_is_supported(operation.return_type, context, what)
- check_dictionaries_are_local(operation.return_type, what)
- check_parameters(what, operation.parameters)
- for dictionary in module.dictionaries:
- if dictionary.parent_name:
- fail(f"its dictionary {dictionary.name} inherits from another dictionary")
- for member in dictionary.members:
- check_type_is_supported(member.type, context, f"{dictionary.name}.{member.name}")
- check_dictionaries_are_local(member.type, f"{dictionary.name}.{member.name}")
-
-
-def types_named_by_interface(interface: Interface) -> List[IDLType]:
- """Every type that the members of the interface name, which the C++ bindings of the interface convert."""
- types = []
- types.extend(attribute.type for attribute in interface.regular_attributes + interface.static_attributes)
- for operation in interface.regular_operations + interface.static_operations:
- types.append(operation.return_type)
- types.extend(parameter.type for parameter in operation.parameters)
- for constructor in interface.constructors:
- types.extend(parameter.type for parameter in constructor.parameters)
- special_operations = [
- interface.named_property_getter,
- interface.indexed_property_getter,
- interface.named_property_setter,
- interface.indexed_property_setter,
- interface.named_property_deleter,
- ]
- for special_operation in special_operations:
- if special_operation is not None:
- types.append(special_operation.return_type)
- types.extend(parameter.type for parameter in special_operation.parameters)
- if interface.stringifier is not None and interface.stringifier.attribute is not None:
- types.append(interface.stringifier.attribute.type)
- if interface.iterable is not None:
- types.extend([interface.iterable.key_type, interface.iterable.value_type])
- if interface.async_iterable is not None:
- types.extend([interface.async_iterable.key_type, interface.async_iterable.value_type])
- types.extend(parameter.type for parameter in interface.async_iterable.parameters)
- if interface.maplike is not None:
- types.extend([interface.maplike.key_type, interface.maplike.value_type])
- if interface.setlike is not None:
- types.append(interface.setlike.value_type)
- return [idl_type for idl_type in types if idl_type is not None]
-
-
-def check_rust_definitions_are_not_used_by_cpp(modules: List[Module]) -> None:
- """The interfaces implemented in Rust and their dictionaries only have a Rust representation, so the C++ bindings
- of other interfaces cannot convert them."""
- rust_names = set()
- for module in modules:
- if module.interface is not None and is_implemented_in_rust(module.interface):
- rust_names.add(module.interface.name)
- rust_names.update(dictionary.name for dictionary in module.dictionaries)
- if not rust_names:
+
+def check_cpp_does_not_name_rust_interfaces(context: GenerationContext, usage: DefinitionUsage) -> None:
+ """An interface implemented in Rust has no C++ implementation object, so the C++ bindings cannot convert it."""
+ rust_interfaces = {interface.name for interface in context.interfaces.values() if is_implemented_in_rust(interface)}
+ if not rust_interfaces:
return
- for module in modules:
- if is_implemented_in_rust(module.interface):
- continue
- definitions = []
- if module.interface is not None:
- definitions.extend(types_named_by_interface(module.interface))
- definitions.extend(typedef.type for typedef in module.typedefs)
- for dictionary in module.dictionaries:
- if dictionary.parent_name in rust_names:
- raise UnsupportedByRustBindings(
- f"{module.path}: {dictionary.name} inherits from {dictionary.parent_name}, which is implemented "
- "in Rust and has no C++ representation"
- )
- definitions.extend(member.type for member in dictionary.members)
- for callback_function in module.callback_functions:
- definitions.append(callback_function.return_type)
- definitions.extend(parameter.type for parameter in callback_function.parameters)
- for idl_type in definitions:
- for nested_type in [idl_type, *idl_type.nested_types()]:
- if nested_type.name in rust_names:
+
+ def check(path, types) -> None:
+ for idl_type in types:
+ for nested_type in idl_type.nested_types():
+ if nested_type.name in rust_interfaces:
raise UnsupportedByRustBindings(
- f"{module.path}: uses {nested_type.name}, which is implemented in Rust and has no C++ "
- "representation"
+ f"{path}: uses {nested_type.name}, which is implemented in Rust and has no C++ representation"
)
+ for module in context.modules:
+ if not is_implemented_in_rust(module.interface):
+ check(module.path, usage.types_named_by_cpp_module(module))
+ for dictionary in usage.cpp_dictionaries(module):
+ check(module.path, [member.type for member in dictionary.members])
+
# C++ side
@@ -432,6 +309,11 @@ def write_parameter_conversions(
) -> None:
for index, parameter in enumerate(parameters):
parameter_what = f"the parameter {parameter.name} of {what}"
+ if parameter.variadic:
+ raise UnsupportedByRustBindings(f"{parameter_what} is variadic")
+ unsupported = set(parameter.extended_attributes) - {"AllowShared", "AllowResizable"}
+ if unsupported:
+ raise UnsupportedByRustBindings(f"{parameter_what} has the extended attributes {sorted(unsupported)}")
name = rust_local_name(parameter.name)
conversion = rust_conversion_to_idl_value(
parameter.type, parameter.extended_attributes, f"argument{index}", parameter.name, context, parameter_what
@@ -493,9 +375,6 @@ def write_rust_interface(
out: TextIO, context: GenerationContext, module: Module, interface: Interface, interface_name_value: int
) -> None:
implementation = implementation_path(interface)
- dictionary_imports = "".join(
- f" use {implementation_module(interface)}::{dictionary.name};\n" for dictionary in module.dictionaries
- )
method_documentation = "".join(
f"/// - `{signature}`\n" for signature in implementation_method_signatures(context, interface)
)
@@ -506,11 +385,10 @@ def write_rust_interface(
#![allow(unused_imports)]
use core::ffi::c_void;
- use std::sync::LazyLock;
use ak::Utf16String;
use libjs_rust::api::{{
- EmbedderCell, EmbedderClass, EmbedderValue, ErrorKind, ErrorType, Gc, JSHostClass, Object, PropertyKey,
+ EmbedderCell, EmbedderClass, EmbedderValue, ErrorKind, ErrorType, Gc, JSHostClass, Object,
RawNativeFunctionResult, ThrowCompletionOr, TypedArrayBase, TypedArrayKind, Value, Vm, raw_native,
}};
@@ -518,25 +396,17 @@ def write_rust_interface(
BufferSourceRules, ToJs, UsvString, to_dom_string, to_float, to_typed_array, to_usv_string,
}};
use crate::bindings::interface::{{
- construct_arguments, create_dictionary_object, create_wrapper, define_attribute,
- define_interface_object_properties, define_operation, define_to_string_tag, entry_point_arguments,
- implementation_of, prototype_from_new_target, set_dictionary_member,
+ construct_arguments, create_wrapper, define_attribute, define_interface_object_properties, define_operation,
+ define_to_string_tag, entry_point_arguments, implementation_of, prototype_from_new_target,
set_interface_prototype_object_prototype, this_object,
}};
use crate::bindings::{{CallContext, WebIdlResult}};
use {implementation} as Implementation;
-{dictionary_imports}
+
/// Web::Bindings::InterfaceName::{interface.name}.
pub(crate) const INTERFACE_NAME: u16 = {interface_name_value};
-"""
- )
- for dictionary in module.dictionaries:
- write_rust_dictionary_conversion(out, context, dictionary)
-
- out.write(
- f"""
/// The class of the cells that hold the implementations of the interface.
static CELL_CLASS: EmbedderClass<Implementation> = EmbedderClass::new("{interface.name}");
@@ -563,13 +433,14 @@ def write_rust_interface(
for attribute in interface.regular_attributes:
getter = f"{rust_identifier(attribute.name).removeprefix('r#')}_getter"
+ conversion = rust_to_js_value(attribute.type, "result", "&cx", context, f"{interface.name}.{attribute.name}")
out.write(
f"""
fn {getter}(vm: &Vm) -> ThrowCompletionOr<Value> {{
let (implementation, mut cx) = this_implementation(vm)?;
let result = Implementation::{rust_identifier(attribute.name)}(&implementation, &mut cx)
.map_err(|exception| exception.throw(vm))?;
- result.to_js(&cx)
+ {conversion}
}}
"""
)
@@ -589,10 +460,11 @@ def write_rust_interface(
write_parameter_conversions(out, f"{interface.name}.{name}()", operation.parameters, context)
out.write(" drop(type_error_realm_scope);\n")
arguments = "".join(f", {rust_local_name(parameter.name)}" for parameter in operation.parameters)
+ conversion = rust_to_js_value(operation.return_type, "result", "&cx", context, f"{interface.name}.{name}()")
out.write(
f""" let result = Implementation::{function}(&implementation, &mut cx{arguments})
.map_err(|exception| exception.throw(vm))?;
- result.to_js(&cx)
+ {conversion}
}}
"""
)
@@ -703,77 +575,75 @@ def constructor_length(interface: Interface) -> int:
return min(parameter_list_length(constructor.parameters) for constructor in interface.constructors)
-def write_rust_dictionary_conversion(out: TextIO, context: GenerationContext, dictionary: Dictionary) -> None:
- """The conversion of the dictionary's struct, which the implementation defines with a field per member: the type
- of a required member or of one with a default value, and an Option of it otherwise. The fields are bound to locals
- with names of their own, so that a member can have any name, and the keys of the members are interned once."""
- fields = []
- keys = []
- conversions = []
- for member in dictionary.members:
- what = f"{dictionary.name}.{member.name}"
- member_type = rust_type(member.type, context, what)
- field = rust_identifier(member.name)
- local = rust_local_name(member.name)
- key = f"{rust_identifier(member.name).removeprefix('r#').rstrip('_').upper()}_KEY"
- keys.append(
- f' static {key}: LazyLock<PropertyKey> = LazyLock::new(|| PropertyKey::from_utf8("{member.name}"));\n'
- )
- always_present = member.required or member.default_value is not None
- if always_present:
- fields.append(f" // {field}: {member_type},\n")
- conversions.append(f" set_dictionary_member(cx, object, &{key}, {local}.to_js(cx)?)?;\n")
- else:
- fields.append(f" // {field}: Option<{member_type}>,\n")
- conversions.append(
- f""" if let Some(value) = {local} {{
- set_dictionary_member(cx, object, &{key}, value.to_js(cx)?)?;
- }}
-"""
- )
- bindings = ", ".join(
- f"{rust_identifier(member.name)}: {rust_local_name(member.name)}" for member in dictionary.members
- )
+def write_rust_definitions(out: TextIO, context: GenerationContext, usage: DefinitionUsage) -> None:
+ """The conversions of the dictionaries that the interfaces implemented in Rust name, each written once, whichever
+ interfaces name it."""
+ if not usage.rust_dictionaries:
+ return
out.write(
- f"""
- /// The conversion of the dictionary {dictionary.name}, a struct of the implementation's module with the fields:
-{"".join(fields)} impl ToJs for {dictionary.name} {{
- fn to_js(self, cx: &CallContext) -> ThrowCompletionOr<Value> {{
-{"".join(keys)} let {dictionary.name} {{ {bindings} }} = self;
- let object = create_dictionary_object(cx);
-{"".join(conversions)} Ok(Value::from_object(object))
- }}
- }}
-"""
- )
+ """
+/// 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;
-def check_rust_bindings(context: GenerationContext, modules: List[Module]) -> None:
- """Raises an error for every use of [ImplementedIn] that the bindings do not handle, before anything is written."""
- check_rust_definitions_are_not_used_by_cpp(modules)
- for module in 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":
+ use ak::Utf16String;
+ use libjs_rust::api::{ErrorKind, ErrorType, Gc, Object, PropertyKey, ThrowCompletionOr, Value, Vm};
+
+ use crate::bindings::CallContext;
+ use crate::bindings::conversions::{ToJs, UsvString};
+ use crate::bindings::interface::{create_dictionary_object, set_dictionary_member};
+"""
+ )
+ for name, directions in usage.rust_dictionaries.items():
+ dictionary = context.dictionaries[name]
+ if dictionary.parent_name:
raise UnsupportedByRustBindings(
- f"{interface.path}: {interface.name} is [ImplementedIn={implemented_in}], but the only value is Rust"
+ f"The Rust bindings convert the dictionary {name}, which inherits from another dictionary"
)
- if is_implemented_in_rust(interface):
- check_interface_is_supported(interface, module, context)
+ if directions.from_js:
+ raise UnsupportedByRustBindings(
+ f"The Rust bindings do not convert the dictionary {name} from a JS value yet"
+ )
+ if directions.to_js:
+ write_dictionary_to_js(out, context, dictionary)
+ out.write("}\n")
-def write_rust_bindings(out: TextIO, context: GenerationContext, modules: List[Module], intrinsics) -> None:
+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.
"""
)
+ write_rust_definitions(out, context, usage)
values = interface_name_values(intrinsics)
- for module in modules:
+ for module in context.modules:
interface = module.interface
if interface is None or not is_implemented_in_rust(interface):
continue
write_rust_interface(out, context, module, interface, values[interface.name])
+
+
+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."""
+ check_cpp_does_not_name_rust_interfaces(context, usage)
+ 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)
+ write_rust_bindings(StringIO(), context, usage, intrinsics)
diff --git a/Meta/Generators/libweb_bindings/rust_names.py b/Meta/Generators/libweb_bindings/rust_names.py
new file mode 100644
index 00000000000..b12f77f800a
--- /dev/null
+++ b/Meta/Generators/libweb_bindings/rust_names.py
@@ -0,0 +1,31 @@
+# Copyright (c) 2026-present, the Ladybird developers.
+#
+# SPDX-License-Identifier: BSD-2-Clause
+
+# The Rust names of IDL identifiers, for the Rust bindings of the interfaces implemented in Rust.
+
+from Utils.utils import title_case_to_snake_case
+
+RUST_KEYWORDS = {
+ "as", "async", "await", "break", "const", "continue", "crate", "dyn", "else", "enum", "extern", "false", "fn", "for",
+ "if", "impl", "in", "let", "loop", "match", "mod", "move", "mut", "pub", "ref", "return", "self", "static",
+ "struct", "super", "trait", "true", "type", "unsafe", "use", "where", "while", "abstract", "become", "box", "do",
+ "final", "gen", "macro", "override", "priv", "try", "typeof", "unsized", "virtual", "yield",
+} # fmt: skip
+
+# Names that Rust does not accept as raw identifiers either.
+RUST_RESERVED_NAMES = {"self", "Self", "crate", "super"}
+
+
+def rust_identifier(name: str) -> str:
+ identifier = title_case_to_snake_case(name).replace("-", "_")
+ if identifier in RUST_RESERVED_NAMES:
+ return f"{identifier}_"
+ if identifier in RUST_KEYWORDS:
+ return f"r#{identifier}"
+ return identifier
+
+
+def rust_local_name(name: str) -> str:
+ """The local variable that holds the IDL value of a parameter, which never clashes with the generated ones."""
+ return f"idl_{rust_identifier(name).removeprefix('r#')}"
diff --git a/Meta/Generators/libweb_bindings/rust_to_js_value.py b/Meta/Generators/libweb_bindings/rust_to_js_value.py
new file mode 100644
index 00000000000..25573918208
--- /dev/null
+++ b/Meta/Generators/libweb_bindings/rust_to_js_value.py
@@ -0,0 +1,75 @@
+# Copyright (c) 2026-present, the Ladybird developers.
+#
+# SPDX-License-Identifier: BSD-2-Clause
+
+# The Rust expressions that convert IDL values to JS values, https://webidl.spec.whatwg.org/#js-type-mapping, for the
+# Rust bindings of the interfaces implemented in Rust, as to_js_value.py writes the C++ ones. The bindings runtime
+# implements ToJs for the types whose conversion does not depend on the IDL type, and this module writes the
+# implementations for the definitions of the IDL.
+
+from typing import TextIO
+
+from Generators.libweb_bindings.context import GenerationContext
+from Generators.libweb_bindings.rust_names import rust_identifier
+from Generators.libweb_bindings.rust_names import rust_local_name
+from Generators.libweb_bindings.rust_types import rust_dictionary_path
+from Generators.libweb_bindings.rust_types import rust_type
+from Utils.webidl_parser import Dictionary
+from Utils.webidl_parser import IDLType
+
+
+def rust_to_js_value(
+ idl_type: IDLType, expression: str, call_context: str, context: GenerationContext, what: str
+) -> str:
+ """An expression of type ThrowCompletionOr<Value> that converts the IDL value to a JS value. The call context is an
+ expression of type &CallContext."""
+ rust_type(idl_type, context, what)
+ return f"{expression}.to_js({call_context})"
+
+
+def write_dictionary_to_js(out: TextIO, context: GenerationContext, dictionary: Dictionary) -> None:
+ """The conversion of the dictionary's struct, which the implementation defines with a field per member: the type
+ of a required member or of one with a default value, and an Option of it otherwise. The fields are bound to locals
+ with names of their own, so that a member can have any name, and the keys of the members are interned once."""
+ path = rust_dictionary_path(dictionary, context)
+ fields = []
+ keys = []
+ conversions = []
+ for member in dictionary.members:
+ what = f"{dictionary.name}.{member.name}"
+ member_type = rust_type(member.type, context, what)
+ field = rust_identifier(member.name)
+ local = rust_local_name(member.name)
+ key = f"{rust_identifier(member.name).removeprefix('r#').rstrip('_').upper()}_KEY"
+ keys.append(
+ f' static {key}: LazyLock<PropertyKey> = LazyLock::new(|| PropertyKey::from_utf8("{member.name}"));\n'
+ )
+ always_present = member.required or member.default_value is not None
+ if always_present:
+ conversion = rust_to_js_value(member.type, local, "cx", context, what)
+ fields.append(f" // {field}: {member_type},\n")
+ conversions.append(f" set_dictionary_member(cx, object, &{key}, {conversion}?)?;\n")
+ else:
+ conversion = rust_to_js_value(member.type, "value", "cx", context, what)
+ fields.append(f" // {field}: Option<{member_type}>,\n")
+ conversions.append(
+ f""" if let Some(value) = {local} {{
+ set_dictionary_member(cx, object, &{key}, {conversion}?)?;
+ }}
+"""
+ )
+ bindings = ", ".join(
+ f"{rust_identifier(member.name)}: {rust_local_name(member.name)}" for member in dictionary.members
+ )
+ out.write(
+ f"""
+ /// The conversion of the dictionary {dictionary.name}, a struct with the fields:
+{"".join(fields)} impl ToJs for {path} {{
+ fn to_js(self, cx: &CallContext) -> ThrowCompletionOr<Value> {{
+{"".join(keys)} let {path} {{ {bindings} }} = self;
+ let object = create_dictionary_object(cx);
+{"".join(conversions)} Ok(Value::from_object(object))
+ }}
+ }}
+"""
+ )
diff --git a/Meta/Generators/libweb_bindings/rust_types.py b/Meta/Generators/libweb_bindings/rust_types.py
index 2ceb4ef69ec..77c6def3ce0 100644
--- a/Meta/Generators/libweb_bindings/rust_types.py
+++ b/Meta/Generators/libweb_bindings/rust_types.py
@@ -7,9 +7,11 @@
import re
+from pathlib import Path
from typing import Optional
from Generators.libweb_bindings.context import GenerationContext
+from Utils.utils import title_case_to_snake_case
from Utils.webidl_parser import Dictionary
from Utils.webidl_parser import IDLType
from Utils.webidl_parser import OperationParameter
@@ -47,17 +49,30 @@ def resolved_dictionary(idl_type: IDLType, context: GenerationContext) -> Option
return context.dictionaries.get(idl_type.name)
-def check_type_is_supported(idl_type: IDLType, context: GenerationContext, what: str) -> None:
+def rust_module_path(idl_path: Path) -> str:
+ """The Rust module of the hand-written definitions of an IDL file, which follows from its path:
+ Encoding/TextEncoder.idl names crate::encoding::text_encoder."""
+ parts = idl_path.parts
+ namespace = parts[parts.index("LibWeb") + 1]
+ return f"crate::{title_case_to_snake_case(namespace)}::{title_case_to_snake_case(idl_path.stem)}"
+
+
+def rust_dictionary_path(dictionary: Dictionary, context: GenerationContext) -> str:
+ """The Rust path of the struct of a dictionary, which is in the module of the IDL file that defines the
+ dictionary: crate::encoding::text_encoder::TextEncoderEncodeIntoResult."""
+ for module in context.modules:
+ if any(defined.name == dictionary.name for defined in module.dictionaries):
+ return f"{rust_module_path(module.path)}::{dictionary.name}"
+ raise RuntimeError(f"No module defines the dictionary {dictionary.name}")
+
+
+def rust_type(idl_type: IDLType, context: GenerationContext, what: str) -> str:
+ """The Rust type of the IDL values of the type."""
unsupported_attributes = set(idl_type.extended_attributes) - SUPPORTED_TYPE_EXTENDED_ATTRIBUTES
if unsupported_attributes:
raise UnsupportedByRustBindings(f"{what} has extended attributes {sorted(unsupported_attributes)}")
if idl_type.nullable:
raise UnsupportedByRustBindings(f"{what} has the nullable type {idl_type}")
- rust_type(idl_type, context, what)
-
-
-def rust_type(idl_type: IDLType, context: GenerationContext, what: str) -> str:
- """The Rust type of the IDL values of the type."""
name = idl_type.name
if name == "DOMString":
return "Utf16String"
@@ -73,8 +88,9 @@ def rust_type(idl_type: IDLType, context: GenerationContext, what: str) -> str:
return "()"
if name in TYPED_ARRAY_NAMES:
return "Gc<TypedArrayBase>"
- if resolved_dictionary(idl_type, context) is not None:
- return name
+ dictionary = resolved_dictionary(idl_type, context)
+ if dictionary is not None:
+ return rust_dictionary_path(dictionary, context)
raise UnsupportedByRustBindings(f"{what} has the type {idl_type}, which the Rust bindings do not convert yet")
diff --git a/Meta/Generators/libweb_bindings/rust_usage.py b/Meta/Generators/libweb_bindings/rust_usage.py
new file mode 100644
index 00000000000..ca0445a479e
--- /dev/null
+++ b/Meta/Generators/libweb_bindings/rust_usage.py
@@ -0,0 +1,153 @@
+# Copyright (c) 2026-present, the Ladybird developers.
+#
+# SPDX-License-Identifier: BSD-2-Clause
+
+# Which language's bindings name which definition. An interface is implemented in one language, but a dictionary is
+# data that the bindings of both languages can convert, so it gets a representation in each language that names it,
+# wherever its IDL defines it.
+
+from dataclasses import dataclass
+from typing import Dict
+from typing import Iterable
+from typing import List
+from typing import Optional
+from typing import Set
+
+from Generators.libweb_bindings.context import GenerationContext
+from Utils.webidl_parser import Dictionary
+from Utils.webidl_parser import IDLType
+from Utils.webidl_parser import Interface
+from Utils.webidl_parser import Module
+
+
+def is_implemented_in_rust(interface: Optional[Interface]) -> bool:
+ return interface is not None and interface.extended_attributes.get("ImplementedIn") == "Rust"
+
+
+def types_named_by_interface(interface: Interface) -> List[IDLType]:
+ """Every type that the members of the interface name, which the bindings of the interface convert."""
+ types = []
+ types.extend(attribute.type for attribute in interface.regular_attributes + interface.static_attributes)
+ for operation in interface.regular_operations + interface.static_operations:
+ types.append(operation.return_type)
+ types.extend(parameter.type for parameter in operation.parameters)
+ for constructor in interface.constructors:
+ types.extend(parameter.type for parameter in constructor.parameters)
+ special_operations = [
+ interface.named_property_getter,
+ interface.indexed_property_getter,
+ interface.named_property_setter,
+ interface.indexed_property_setter,
+ interface.named_property_deleter,
+ ]
+ for special_operation in special_operations:
+ if special_operation is not None:
+ types.append(special_operation.return_type)
+ types.extend(parameter.type for parameter in special_operation.parameters)
+ if interface.stringifier is not None and interface.stringifier.attribute is not None:
+ types.append(interface.stringifier.attribute.type)
+ if interface.iterable is not None:
+ types.extend([interface.iterable.key_type, interface.iterable.value_type])
+ if interface.async_iterable is not None:
+ types.extend([interface.async_iterable.key_type, interface.async_iterable.value_type])
+ types.extend(parameter.type for parameter in interface.async_iterable.parameters)
+ if interface.maplike is not None:
+ types.extend([interface.maplike.key_type, interface.maplike.value_type])
+ if interface.setlike is not None:
+ types.append(interface.setlike.value_type)
+ return [idl_type for idl_type in types if idl_type is not None]
+
+
+@dataclass
+class ConversionDirections:
+ """The directions in which the Rust bindings convert a definition."""
+
+ from_js: bool = False
+ to_js: bool = False
+
+
+class DefinitionUsage:
+ def __init__(self, context: GenerationContext) -> None:
+ self.context = context
+ # The dictionaries that the interfaces implemented in Rust name, in the order of their first use.
+ self.rust_dictionaries: Dict[str, ConversionDirections] = {}
+ # The dictionaries that have a C++ representation.
+ self.cpp_dictionary_names: Set[str] = set()
+ self._collect_rust_dictionaries()
+ self._collect_cpp_dictionaries()
+
+ def cpp_dictionaries(self, module: Module) -> List[Dictionary]:
+ """The dictionaries of the module that the C++ bindings declare and convert."""
+ return [dictionary for dictionary in module.dictionaries if dictionary.name in self.cpp_dictionary_names]
+
+ def _collect_rust_dictionaries(self) -> None:
+ for module in self.context.modules:
+ interface = module.interface
+ if interface is None or not is_implemented_in_rust(interface):
+ continue
+ for attribute in interface.regular_attributes:
+ self._name_for_rust(attribute.type, from_js=not attribute.readonly, to_js=True)
+ for operation in interface.regular_operations:
+ self._name_for_rust(operation.return_type, from_js=False, to_js=True)
+ for parameter in operation.parameters:
+ self._name_for_rust(parameter.type, from_js=True, to_js=False)
+ for constructor in interface.constructors:
+ for parameter in constructor.parameters:
+ self._name_for_rust(parameter.type, from_js=True, to_js=False)
+
+ def _name_for_rust(self, idl_type: IDLType, from_js: bool, to_js: bool) -> None:
+ for nested_type in idl_type.nested_types():
+ dictionary = self.context.dictionaries.get(nested_type.name)
+ if dictionary is None:
+ continue
+ directions = self.rust_dictionaries.setdefault(dictionary.name, ConversionDirections())
+ if (directions.from_js or not from_js) and (directions.to_js or not to_js):
+ continue
+ directions.from_js = directions.from_js or from_js
+ directions.to_js = directions.to_js or to_js
+ for member in self._members_with_inherited(dictionary):
+ self._name_for_rust(member.type, from_js, to_js)
+
+ def _members_with_inherited(self, dictionary: Dictionary):
+ members = list(dictionary.members)
+ parent = self.context.dictionaries.get(dictionary.parent_name) if dictionary.parent_name else None
+ if parent is not None:
+ members.extend(self._members_with_inherited(parent))
+ return members
+
+ def _collect_cpp_dictionaries(self) -> None:
+ for module in self.context.modules:
+ if is_implemented_in_rust(module.interface):
+ continue
+ # NB: The C++ bindings declare and convert every dictionary of the modules that they generate, whether
+ # or not an interface names it, unless only the Rust bindings convert it.
+ for dictionary in module.dictionaries:
+ if dictionary.name not in self.rust_dictionaries:
+ self._name_for_cpp(dictionary.name)
+ self._name_types_for_cpp(self.types_named_by_cpp_module(module))
+
+ def types_named_by_cpp_module(self, module: Module) -> List[IDLType]:
+ """The types that the interface, typedefs and callback functions of a module of the C++ bindings name."""
+ types = []
+ if module.interface is not None:
+ types.extend(types_named_by_interface(module.interface))
+ types.extend(typedef.type for typedef in module.typedefs)
+ for callback_function in module.callback_functions:
+ types.append(callback_function.return_type)
+ types.extend(parameter.type for parameter in callback_function.parameters)
+ return types
+
+ def _name_types_for_cpp(self, types: Iterable[IDLType]) -> None:
+ for idl_type in types:
+ for nested_type in idl_type.nested_types():
+ if nested_type.name in self.context.dictionaries:
+ self._name_for_cpp(nested_type.name)
+
+ def _name_for_cpp(self, name: str) -> None:
+ if name in self.cpp_dictionary_names:
+ return
+ self.cpp_dictionary_names.add(name)
+ dictionary = self.context.dictionaries[name]
+ if dictionary.parent_name in self.context.dictionaries:
+ self._name_for_cpp(dictionary.parent_name)
+ self._name_types_for_cpp(member.type for member in dictionary.members)