Skip to content

Truly independent web browser

Meta+LibWeb: Add a Rust backend to the WebIDL bindings generator

Aliaksandr Kalenik3dd00f399588
diff --git a/Libraries/LibWeb/Bindings/Rust/build.rs b/Libraries/LibWeb/Bindings/Rust/build.rs
new file mode 100644
index 00000000000..09be68dd504
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/build.rs
@@ -0,0 +1,32 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Finds the Rust bindings of the interfaces implemented in Rust, which Meta/Generators/generate_libweb_bindings.py
+//! writes to Bindings/RustBindings.rs in the build directory of LibWeb. A build of LibWeb names that file in
+//! LIBWEB_RUST_BINDINGS (Libraries/LibWeb/CMakeLists.txt). Building the crate on its own, as cargo test and cargo
+//! clippy do, leaves the bindings out and compiles the implementations without them. rustc tracks the file itself, as
+//! the crate includes it.
+
+use std::env;
+use std::path::PathBuf;
+
+fn main() {
+ println!("cargo:rerun-if-changed=build.rs");
+ println!("cargo:rustc-check-cfg=cfg(web_idl_bindings)");
+ println!("cargo:rerun-if-env-changed=LIBWEB_RUST_BINDINGS");
+ let Some(bindings) = env::var_os("LIBWEB_RUST_BINDINGS") else {
+ return;
+ };
+ let bindings = PathBuf::from(bindings);
+ assert!(
+ bindings.is_file(),
+ "LIBWEB_RUST_BINDINGS names {}, which does not exist; a build of LibWeb generates the bindings before it builds \
+ the crate",
+ bindings.display()
+ );
+ println!("cargo:rustc-cfg=web_idl_bindings");
+ println!("cargo:rustc-env=LIBWEB_RUST_BINDINGS={}", bindings.display());
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs
new file mode 100644
index 00000000000..c6a6afefe87
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs
@@ -0,0 +1,171 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Conversions between JS values and the Rust types of IDL values,
+//! https://webidl.spec.whatwg.org/#es-type-mapping
+
+use core::mem::MaybeUninit;
+
+use ak::{Utf16String, Utf16StringUnits, convert_valid_utf16_to_utf8, utf8_length_from_valid_utf16};
+use libjs_rust::api::{
+ ErrorKind, ErrorType, Gc, PrimitiveString, ThrowCompletionOr, TypedArrayBase, TypedArrayKind, Value, Vm,
+ to_well_formed,
+};
+
+use crate::bindings::CallContext;
+
+/// A USVString, a string without lone surrogates. Its UTF-16 code units are always well-formed.
+pub(crate) struct UsvString(Utf16String);
+
+impl UsvString {
+ pub(crate) fn from_ascii(string: &[u8]) -> Self {
+ Self(Utf16String::from_ascii(string))
+ }
+
+ pub(crate) fn units(&self) -> Utf16StringUnits<'_> {
+ self.0.as_units()
+ }
+
+ pub(crate) fn length_in_code_units(&self) -> usize {
+ self.0.length_in_code_units()
+ }
+
+ pub(crate) fn utf8_length(&self) -> usize {
+ match self.units() {
+ Utf16StringUnits::Ascii(bytes) => bytes.len(),
+ Utf16StringUnits::Utf16(code_units) => utf8_length_from_valid_utf16(code_units),
+ }
+ }
+
+ /// Writes the string's UTF-8 encoding to the start of `output`, which need not be initialized, and returns the
+ /// number of bytes written.
+ ///
+ /// # Safety
+ ///
+ /// `output` must have room for the encoding: utf8_length() bytes, or three bytes per code unit. The encoding is
+ /// written without checking that, as measuring it first would cost a pass over the string.
+ pub(crate) unsafe fn encode_utf8(&self, output: &mut [MaybeUninit<u8>]) -> usize {
+ match self.units() {
+ Utf16StringUnits::Ascii(bytes) => {
+ output[..bytes.len()].write_copy_of_slice(bytes);
+ bytes.len()
+ }
+ Utf16StringUnits::Utf16(code_units) => {
+ debug_assert!(output.len() >= utf8_length_from_valid_utf16(code_units));
+ // SAFETY: A USVString is well-formed, and the caller gives the output room for its encoding.
+ unsafe { convert_valid_utf16_to_utf8(code_units, output) }
+ }
+ }
+ }
+
+ pub(crate) fn into_utf16_string(self) -> Utf16String {
+ self.0
+ }
+}
+
+/// A JS value converted to a DOMString, https://webidl.spec.whatwg.org/#es-DOMString
+pub(crate) fn to_dom_string(vm: &Vm, value: Value) -> ThrowCompletionOr<Utf16String> {
+ value.to_utf16_string(vm)
+}
+
+/// A JS value converted to a USVString, https://webidl.spec.whatwg.org/#es-USVString
+pub(crate) fn to_usv_string(vm: &Vm, value: Value) -> ThrowCompletionOr<UsvString> {
+ // 1. Let string be the result of converting V to a DOMString.
+ let string = to_dom_string(vm, value)?;
+
+ // 2. Return an IDL USVString value that is the result of converting string to a sequence of scalar values.
+ Ok(UsvString(to_well_formed(&string)))
+}
+
+/// What the extended attributes of a buffer source type allow, https://webidl.spec.whatwg.org/#es-buffer-source-types
+pub(crate) struct BufferSourceRules {
+ pub(crate) allow_shared: bool,
+ pub(crate) allow_resizable: bool,
+}
+
+/// A JS value converted to an IDL typed array value of the kind, whose name is the type's name.
+pub(crate) fn to_typed_array(
+ vm: &Vm,
+ value: Value,
+ kind: TypedArrayKind,
+ name: &str,
+ rules: &BufferSourceRules,
+) -> ThrowCompletionOr<Gc<TypedArrayBase>> {
+ // 1. Let T be the IDL type V is being converted to.
+ // 2. If V is not an Object, or V does not have a [[TypedArrayName]] internal slot with a value equal to T's name,
+ // then throw a TypeError.
+ let typed_array = value
+ .is_object()
+ .then(|| value.as_object().downcast::<TypedArrayBase>())
+ .flatten()
+ .filter(|typed_array| typed_array.kind() == kind);
+ let Some(typed_array) = typed_array else {
+ return vm.throw_completion(ErrorKind::TypeError, ErrorType::NotAnObjectOfType, &[&name]);
+ };
+ let buffer = typed_array.viewed_array_buffer();
+
+ // 3. If the conversion is not to an IDL type associated with the [AllowShared] extended attribute, and
+ // IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is true, then throw a TypeError.
+ if !rules.allow_shared && buffer.is_shared_array_buffer() {
+ return vm.throw_completion(ErrorKind::TypeError, ErrorType::SharedArrayBuffer, &[]);
+ }
+
+ // 4. If the conversion is not to an IDL type associated with the [AllowResizable] extended attribute, and
+ // IsFixedLengthArrayBuffer(V.[[ViewedArrayBuffer]]) is false, then throw a TypeError.
+ if !rules.allow_resizable && !buffer.is_fixed_length() {
+ return vm.throw_completion(
+ ErrorKind::TypeError,
+ ErrorType::NotAnObjectOfType,
+ &[&format!("fixed-length {name}")],
+ );
+ }
+
+ // 5. Return the IDL value of type T that is a reference to the same object as V.
+ Ok(typed_array)
+}
+
+/// An IDL value converted to a JS value, https://webidl.spec.whatwg.org/#js-type-mapping
+pub(crate) trait ToJs {
+ fn to_js(self, cx: &CallContext) -> ThrowCompletionOr<Value>;
+}
+
+impl ToJs for () {
+ fn to_js(self, _: &CallContext) -> ThrowCompletionOr<Value> {
+ Ok(Value::UNDEFINED)
+ }
+}
+
+impl ToJs for bool {
+ fn to_js(self, _: &CallContext) -> ThrowCompletionOr<Value> {
+ Ok(Value::from_bool(self))
+ }
+}
+
+/// https://webidl.spec.whatwg.org/#js-unsigned-long-long
+impl ToJs for u64 {
+ fn to_js(self, _: &CallContext) -> ThrowCompletionOr<Value> {
+ #[allow(clippy::cast_precision_loss, reason = "the spec converts to the closest double")]
+ Ok(Value::from_f64(self as f64))
+ }
+}
+
+impl ToJs for Utf16String {
+ fn to_js(self, cx: &CallContext) -> ThrowCompletionOr<Value> {
+ Ok(Value::from_string(PrimitiveString::create(cx.vm(), self)))
+ }
+}
+
+impl ToJs for UsvString {
+ fn to_js(self, cx: &CallContext) -> ThrowCompletionOr<Value> {
+ self.into_utf16_string().to_js(cx)
+ }
+}
+
+impl ToJs for Gc<TypedArrayBase> {
+ fn to_js(self, _: &CallContext) -> ThrowCompletionOr<Value> {
+ Ok(Value::from_object(self))
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/generated.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/generated.rs
new file mode 100644
index 00000000000..c90b1ecfe3c
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/generated.rs
@@ -0,0 +1,10 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The bindings of the interfaces implemented in Rust, which Meta/Generators/generate_libweb_bindings.py writes to
+//! Bindings/RustBindings.rs in the build directory of LibWeb.
+
+include!(env!("LIBWEB_RUST_BINDINGS"));
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/interface.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/interface.rs
new file mode 100644
index 00000000000..74a8d787326
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/interface.rs
@@ -0,0 +1,246 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! What the generated bindings of an interface do with its wrappers, its interface object and its interface prototype
+//! object, https://webidl.spec.whatwg.org/#es-interfaces
+//!
+//! A wrapper of an interface implemented in Rust is a platform object of the interface's wrapper class, which LibWeb's
+//! C++ bindings define. Its host data holds the cell of its implementation, and its wrappable slot stays empty, so the
+//! C++ bindings treat it like a platform object without a wrappable.
+
+use core::ffi::c_void;
+use core::ptr::NonNull;
+
+use libjs_rust::api::{
+ Attribute, EmbedderCell, EmbedderClass, EmbedderValue, ErrorKind, ErrorType, FunctionObject, Gc, HostObject,
+ JSHostClass, Object, PrimitiveString, PropertyAttributes, PropertyKey, RawNativeFunctionPointer, Realm,
+ ThrowCompletionOr, Value, Vm, get_function_realm, host_class_of, host_data_of,
+};
+
+use crate::bindings::CallContext;
+use crate::bindings::services::web_bindings_ensure_web_prototype;
+
+/// The object an attribute or an operation of an interface runs on, if it is a wrapper of the interface, with the
+/// object's realm. A nullish this value stands for the global object of the current realm.
+pub(crate) fn this_object(
+ vm: &Vm,
+ wrapper_class: &'static JSHostClass,
+ interface_name: &str,
+) -> ThrowCompletionOr<(Gc<Object>, Gc<Realm>)> {
+ let mut this_value = vm.this_value();
+ if this_value.is_nullish() {
+ let current_realm = vm.current_realm().expect("a native function runs in a realm");
+ this_value = Value::from_object(current_realm.global_object());
+ }
+ if this_value.is_object() {
+ let object = this_value.as_object();
+ if host_class_of(&object).is_some_and(|host_class| core::ptr::eq(host_class, wrapper_class)) {
+ return Ok((object, object.shape().realm()));
+ }
+ }
+ vm.throw_completion(ErrorKind::TypeError, ErrorType::NotAnObjectOfType, &[&interface_name])
+}
+
+pub(crate) fn implementation_of<T: EmbedderValue>(
+ wrapper: Gc<Object>,
+ cell_class: &'static EmbedderClass<T>,
+) -> Gc<EmbedderCell<T>> {
+ let host_data = host_data_of(&wrapper).expect("a wrapper holds the cell of its implementation");
+ // SAFETY: The wrapper is a host object of the interface's wrapper class, whose host data the bindings set to a
+ // cell of the interface's implementation.
+ unsafe { cell_class.downcast(host_data) }.expect("a wrapper holds the cell of its implementation")
+}
+
+/// The interface prototype object of the interface in the realm.
+pub(crate) fn interface_prototype_object(realm: Gc<Realm>, interface_name: u16) -> Gc<Object> {
+ // SAFETY: The realm is live, and the interface is implemented in Rust.
+ let prototype = unsafe { web_bindings_ensure_web_prototype(realm.as_ptr().cast(), interface_name) };
+ let prototype = NonNull::new(prototype.cast::<Object>()).expect("the realm has the interface prototype object");
+ // SAFETY: LibWeb returns the live prototype.
+ unsafe { Gc::from_non_null(prototype) }
+}
+
+/// The prototype of an object that newTarget constructs, steps 3.2 and 3.3 of internally creating a new object
+/// implementing the interface, https://webidl.spec.whatwg.org/#internally-create-a-new-object-implementing-the-interface
+pub(crate) fn prototype_from_new_target(
+ vm: &Vm,
+ new_target: Gc<Object>,
+ interface_name: u16,
+) -> ThrowCompletionOr<Gc<Object>> {
+ // 3.2. Let prototype be ? Get(newTarget, "prototype").
+ let prototype = new_target.get(vm, &vm.names.prototype)?;
+
+ // 3.3. If Type(prototype) is not Object, then:
+ if prototype.is_object() {
+ return Ok(prototype.as_object());
+ }
+ // 1. Let targetRealm be ? GetFunctionRealm(newTarget).
+ let new_target = new_target
+ .downcast::<FunctionObject>()
+ .expect("the new target of a construction is a constructor");
+ let target_realm = get_function_realm(vm, new_target)?;
+ // 2. Set prototype to the interface prototype object for interface in targetRealm.
+ Ok(interface_prototype_object(target_realm, interface_name))
+}
+
+/// A new wrapper of the interface in the realm, whose host data holds the implementation.
+pub(crate) fn create_wrapper<T: EmbedderValue>(
+ vm: &Vm,
+ realm: Gc<Realm>,
+ wrapper_class: &'static JSHostClass,
+ prototype: Gc<Object>,
+ implementation: Gc<EmbedderCell<T>>,
+) -> Gc<HostObject> {
+ // SAFETY: The wrapper class's hooks expect no wrappable, and the host data is a live cell.
+ unsafe {
+ HostObject::create(
+ vm,
+ realm,
+ wrapper_class,
+ Some(prototype),
+ None,
+ Some(implementation.as_non_null().cast()),
+ )
+ }
+}
+
+/// Unwraps the raw arguments that LibWeb's C++ bindings pass the entry points that initialize the interface object and
+/// the interface prototype object, which run before any binding of the interface. The C++ bindings pass the runtime's
+/// VM and cells, as JS::HostABI::vm_to_abi() and object_to_abi() do.
+///
+/// # Safety
+///
+/// The pointers must be the live VM, a live realm and a live object.
+pub(crate) unsafe fn entry_point_arguments<'vm>(
+ vm: *mut c_void,
+ realm: *mut c_void,
+ object: *mut c_void,
+) -> (&'vm Vm, Gc<Realm>, Gc<Object>) {
+ let realm = NonNull::new(realm.cast::<Realm>()).expect("C++ passes a realm");
+ let object = NonNull::new(object.cast::<Object>()).expect("C++ passes an object");
+ // SAFETY: The caller guarantees that the pointers are live.
+ unsafe { (&*vm.cast::<Vm>(), Gc::from_non_null(realm), Gc::from_non_null(object)) }
+}
+
+/// Unwraps the raw arguments that LibWeb's C++ bindings pass the entry point that constructs an object.
+///
+/// # Safety
+///
+/// The pointers must be the live VM and the live new target of a construction.
+pub(crate) unsafe fn construct_arguments<'vm>(vm: *mut c_void, new_target: *mut c_void) -> (&'vm Vm, Gc<Object>) {
+ let new_target = NonNull::new(new_target.cast::<Object>()).expect("a construction has a new target");
+ // SAFETY: The caller guarantees that the pointers are live.
+ unsafe { (&*vm.cast::<Vm>(), Gc::from_non_null(new_target)) }
+}
+
+/// Gives the interface prototype object its [[Prototype]], %Object.prototype%. The Rust bindings do not handle
+/// interfaces that inherit from another interface yet.
+pub(crate) fn set_interface_prototype_object_prototype(vm: &Vm, realm: Gc<Realm>, prototype: Gc<Object>) {
+ prototype.set_prototype(vm, Some(realm.intrinsics().object_prototype(vm)));
+}
+
+/// Defines a regular attribute on the interface prototype object, https://webidl.spec.whatwg.org/#es-attributes
+pub(crate) fn define_attribute(
+ vm: &Vm,
+ realm: Gc<Realm>,
+ prototype: Gc<Object>,
+ name: &str,
+ getter: RawNativeFunctionPointer,
+ setter: RawNativeFunctionPointer,
+) {
+ prototype.define_native_accessor(
+ vm,
+ realm,
+ &PropertyKey::from_utf8(name),
+ getter,
+ setter,
+ PropertyAttributes::new(Attribute::ENUMERABLE | Attribute::CONFIGURABLE),
+ );
+}
+
+/// Defines a regular operation on the interface prototype object, https://webidl.spec.whatwg.org/#es-operations
+pub(crate) fn define_operation(
+ vm: &Vm,
+ realm: Gc<Realm>,
+ prototype: Gc<Object>,
+ name: &str,
+ behaviour: RawNativeFunctionPointer,
+ length: i32,
+) {
+ prototype.define_native_function(
+ vm,
+ realm,
+ &PropertyKey::from_utf8(name),
+ behaviour,
+ length,
+ PropertyAttributes::new(Attribute::WRITABLE | Attribute::ENUMERABLE | Attribute::CONFIGURABLE),
+ None,
+ );
+}
+
+/// Defines @@toStringTag on the interface prototype object, https://webidl.spec.whatwg.org/#es-interface-prototype-object
+pub(crate) fn define_to_string_tag(vm: &Vm, prototype: Gc<Object>, name: &str) {
+ prototype.define_direct_property(
+ vm,
+ &PropertyKey::from(vm.well_known_symbols().to_string_tag),
+ ascii_string(vm, name),
+ PropertyAttributes::new(Attribute::CONFIGURABLE),
+ );
+}
+
+/// Defines the "length", "name" and "prototype" properties of the interface object,
+/// https://webidl.spec.whatwg.org/#es-interface-call
+pub(crate) fn define_interface_object_properties(
+ vm: &Vm,
+ realm: Gc<Realm>,
+ constructor: Gc<Object>,
+ name: &str,
+ length: i32,
+ interface_name: u16,
+) {
+ constructor.define_direct_property(
+ vm,
+ &vm.names.length,
+ Value::from_f64(f64::from(length)),
+ PropertyAttributes::new(Attribute::CONFIGURABLE),
+ );
+ constructor.define_direct_property(
+ vm,
+ &vm.names.name,
+ ascii_string(vm, name),
+ PropertyAttributes::new(Attribute::CONFIGURABLE),
+ );
+ let prototype = interface_prototype_object(realm, interface_name);
+ constructor.define_direct_property(
+ vm,
+ &vm.names.prototype,
+ Value::from_object(prototype),
+ PropertyAttributes::new(0),
+ );
+}
+
+fn ascii_string(vm: &Vm, string: &str) -> Value {
+ Value::from_string(PrimitiveString::create_from_ascii(vm, string.as_bytes()))
+}
+
+/// A new object for a dictionary value, https://webidl.spec.whatwg.org/#js-dictionary
+pub(crate) fn create_dictionary_object(cx: &CallContext) -> Gc<Object> {
+ // 1. Let O be OrdinaryObjectCreate(%Object.prototype%).
+ let object_prototype = cx.realm().intrinsics().object_prototype(cx.vm());
+ Object::create(cx.vm(), cx.realm(), Some(object_prototype))
+}
+
+/// Stores a member of a dictionary value in its object, step 3.2.3 of https://webidl.spec.whatwg.org/#js-dictionary
+pub(crate) fn set_dictionary_member(
+ cx: &CallContext,
+ object: Gc<Object>,
+ key: &PropertyKey,
+ value: Value,
+) -> ThrowCompletionOr<()> {
+ // 3. Perform ! CreateDataPropertyOrThrow(O, key, value).
+ object.create_data_property(cx.vm(), key, value, None, None)?;
+ Ok(())
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/mod.rs
new file mode 100644
index 00000000000..dcd99056185
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/mod.rs
@@ -0,0 +1,80 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The runtime of the WebIDL bindings that Meta/Generators/generate_libweb_bindings.py writes in Rust, for the
+//! interfaces that their IDL marks [ImplementedIn=Rust]. The bindings of such an interface are the native functions,
+//! constructor and prototype of the interface, which call the methods of the interface's implementation in this
+//! crate: one per constructor, attribute and operation, whose signatures the generated bindings document. A dictionary
+//! of the interface's IDL is a struct next to the implementation, whose fields are the dictionary's members; the
+//! bindings convert it.
+//!
+//! Values and cells live in locals while a binding runs, which the collector scans; a binding that gathers values in
+//! a container keeps them in a MarkedVec.
+
+pub(crate) mod conversions;
+#[cfg(web_idl_bindings)]
+pub(crate) mod generated;
+pub(crate) mod interface;
+pub(crate) mod services;
+
+use ak::Utf16String;
+use libjs_rust::api::{ErrorKind, Gc, Realm, Throw, ThrowCompletionOr, Vm};
+
+/// What the bindings pass the implementation of an interface: the VM, and the realm that the implementation creates
+/// its results in. For an attribute or an operation, that is the realm of the object it runs on; for a constructor,
+/// the current realm.
+pub(crate) struct CallContext<'vm> {
+ vm: &'vm Vm,
+ realm: Gc<Realm>,
+}
+
+impl<'vm> CallContext<'vm> {
+ pub(crate) fn new(vm: &'vm Vm, realm: Gc<Realm>) -> Self {
+ Self { vm, realm }
+ }
+
+ pub(crate) fn vm(&self) -> &'vm Vm {
+ self.vm
+ }
+
+ pub(crate) fn realm(&self) -> Gc<Realm> {
+ self.realm
+ }
+}
+
+/// An exception that the implementation of an interface throws.
+pub(crate) enum Exception {
+ /// A value that JavaScript code threw.
+ Thrown(Throw),
+ /// A simple exception with the message, which the bindings create in the current realm.
+ TypeError(Utf16String),
+ RangeError(Utf16String),
+}
+
+impl From<Throw> for Exception {
+ fn from(throw: Throw) -> Self {
+ Self::Thrown(throw)
+ }
+}
+
+impl Exception {
+ pub(crate) fn throw(self, vm: &Vm) -> Throw {
+ match self {
+ Self::Thrown(throw) => throw,
+ Self::TypeError(message) => thrown(vm.throw_completion_with_utf16_message(ErrorKind::TypeError, message)),
+ Self::RangeError(message) => thrown(vm.throw_completion_with_utf16_message(ErrorKind::RangeError, message)),
+ }
+ }
+}
+
+fn thrown(completion: ThrowCompletionOr<()>) -> Throw {
+ match completion {
+ Err(throw) => throw,
+ Ok(()) => unreachable!("throwing a completion throws"),
+ }
+}
+
+pub(crate) type WebIdlResult<T> = Result<T, Exception>;
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/services.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/services.rs
new file mode 100644
index 00000000000..fe313b0fbe2
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/services.rs
@@ -0,0 +1,17 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The services of LibWeb's C++ bindings that the Rust bindings use, which the bindings generator defines in
+//! Bindings/IntrinsicDefinitions.cpp.
+
+use core::ffi::c_void;
+
+unsafe extern "C" {
+ /// The interface prototype object of the interface in the realm, which the realm's intrinsics create on first use.
+ /// The realm and the object are the runtime's cells, and the interface name is a Web::Bindings::InterfaceName of an
+ /// interface implemented in Rust.
+ pub(crate) fn web_bindings_ensure_web_prototype(realm: *mut c_void, interface_name: u16) -> *mut c_void;
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/lib.rs b/Libraries/LibWeb/Bindings/Rust/src/lib.rs
index 85bc80f4fc6..0c3a4274fca 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/lib.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/lib.rs
@@ -4,13 +4,14 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-//! The Rust code of LibWeb that runs on the LibJS runtime. The crate is the Rust part of LibWeb's library: it depends
-//! on the runtime and on libweb_rust, and the library links its archive, so that the runtime is in a process once and
-//! this crate reaches it as any Rust code reaches a crate it depends on.
+//! The Rust code of LibWeb that runs on the LibJS runtime: the WebIDL bindings of the interfaces implemented in Rust,
+//! and those implementations. The crate is the Rust part of LibWeb's library: it depends on the runtime and on
+//! libweb_rust, and the library links its archive, so that the runtime is in a process once and this crate reaches it
+//! as any Rust code reaches a crate it depends on.
//!
//! The crate's tests cover the code that does not touch the runtime. A test binary keeps every extern "C" function of
//! every crate it links, so linking the runtime would make it link every C function the runtime imports as well; the
-//! runtime and libweb_rust are left out of the tests instead, as the runtime's own crate leaves out its engine.
+//! modules that use the runtime are left out of the tests instead, as the runtime's own crate leaves out its engine.
#[cfg(feature = "allocator")]
extern crate ladybird_allocator;
@@ -21,9 +22,14 @@ mod rust_demangle;
#[path = "../../../../RustPanic.rs"]
mod rust_panic;
-// NB: Only C++ calls into the runtime and into libweb_rust so far, so nothing in this crate names them. Linking them
-// keeps their extern "C" functions in the static library.
#[cfg(not(test))]
-extern crate libjs_rust;
+#[allow(
+ dead_code,
+ reason = "the generated bindings use only the conversions their interfaces need"
+)]
+pub(crate) mod bindings;
+
+// NB: Only C++ calls into libweb_rust, so nothing in this crate names it. Linking it keeps its extern "C" functions in
+// the static library.
#[cfg(not(test))]
extern crate libweb_rust;
diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txt
index e02127bc313..ef45793dd16 100644
--- a/Libraries/LibWeb/CMakeLists.txt
+++ b/Libraries/LibWeb/CMakeLists.txt
@@ -1196,6 +1196,8 @@ import_rust_crate(
FEATURES ${LIBJS_RUST_FEATURES}
# The copy of libgfx_rust in this crate, which TestRustCrateCopies reaches by name.
KEEP_SYMBOLS ladybird_gfx_register_rust_crate_copy
+ # The bindings of the interfaces implemented in Rust, which generating the bindings writes and the crate includes.
+ ENVIRONMENT "LIBWEB_RUST_BINDINGS=${CMAKE_CURRENT_BINARY_DIR}/Bindings/RustBindings.rs"
)
# The headers that the build script of libweb_rust, which the archive bundles, writes.
sync_rust_crate_ffi_headers(
@@ -1269,3 +1271,5 @@ if (HAS_FONTCONFIG)
endif()
generate_js_bindings(LibWeb)
+# The bindings crate includes the Rust bindings that generating the bindings writes.
+add_dependencies(libweb_bindings_rust-build generate_bindings)
diff --git a/Meta/CMake/libweb_generators.cmake b/Meta/CMake/libweb_generators.cmake
index 7fd0a961747..2bdc3b4564c 100644
--- a/Meta/CMake/libweb_generators.cmake
+++ b/Meta/CMake/libweb_generators.cmake
@@ -312,6 +312,8 @@ function (generate_js_bindings target)
"${LADYBIRD_SOURCE_DIR}/Meta/Generators/libweb_bindings/operations.py"
"${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_types.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"
@@ -373,8 +375,11 @@ function (generate_js_bindings target)
set(LIBWEB_ALL_PARSED_IDL_FILES_ARGUMENT "@${CMAKE_CURRENT_BINARY_DIR}/all_parsed_idl_files.txt")
endif()
+ # The bindings of the interfaces implemented in Rust, which libweb_bindings_rust includes.
+ set(rust_bindings_source "${CMAKE_CURRENT_BINARY_DIR}/Bindings/RustBindings.rs")
+
add_custom_command(
- OUTPUT ${LIBWEB_ALL_BINDINGS_SOURCES} ${LIBWEB_ALL_COMMON_BINDINGS_HEADERS} ${exposed_interface_sources}
+ OUTPUT ${LIBWEB_ALL_BINDINGS_SOURCES} ${LIBWEB_ALL_COMMON_BINDINGS_HEADERS} ${exposed_interface_sources} ${rust_bindings_source}
COMMAND "${CMAKE_COMMAND}" -E make_directory "Bindings"
COMMAND "${Python3_EXECUTABLE}" "${bindings_generator}" -o "Bindings"
--common-output-path "${LIBWEB_COMMON_BINDINGS_DIRECTORY}"
@@ -386,7 +391,7 @@ function (generate_js_bindings target)
DEPENDS ${bindings_generator_dependencies} ${LIBWEB_ALL_IDL_FILES} ${LIBWEB_ALL_PARSED_IDL_FILES}
)
- add_custom_target(generate_bindings DEPENDS ${LIBWEB_ALL_BINDINGS_SOURCES} ${LIBWEB_ALL_COMMON_BINDINGS_HEADERS})
+ add_custom_target(generate_bindings DEPENDS ${LIBWEB_ALL_BINDINGS_SOURCES} ${LIBWEB_ALL_COMMON_BINDINGS_HEADERS} ${rust_bindings_source})
add_dependencies(ladybird_codegen_accumulator generate_bindings)
add_dependencies(${target} generate_bindings)
add_dependencies(generate_bindings ${generated_idl_targets})
diff --git a/Meta/CMake/rust_crate.cmake b/Meta/CMake/rust_crate.cmake
index 4ccbd145427..9d1ff249876 100644
--- a/Meta/CMake/rust_crate.cmake
+++ b/Meta/CMake/rust_crate.cmake
@@ -5,11 +5,12 @@ set(RUSTC_TARGET_FLAGS -Dwarnings ${RUSTC_TARGET_CPU_FLAGS} ${RUSTC_TARGET_FRAME
list(JOIN RUSTC_TARGET_FLAGS " " RUSTC_TARGET_FLAGS)
# import_rust_crate(MANIFEST_PATH path/to/Cargo.toml CRATE_NAME name [PANIC_UNWIND] [NO_DEFAULT_FEATURES]
-# [FEATURES feature...] [KEEP_SYMBOLS symbol...])
+# [FEATURES feature...] [KEEP_SYMBOLS symbol...] [ENVIRONMENT VARIABLE=value...])
#
# Builds a Rust static library crate using cargo and creates an IMPORTED target.
# MANIFEST_PATH is relative to CMAKE_CURRENT_SOURCE_DIR.
# NO_DEFAULT_FEATURES builds the crate with only the FEATURES given, without its default ones.
+# ENVIRONMENT sets variables in the environment of cargo, for the build script of the crate to read.
# KEEP_SYMBOLS names entry points that only dlsym() reaches. A link only takes the archive members
# something references, and a debug build gives a lone function a member of its own, so these have
# to be asked for or they are left out.
@@ -18,7 +19,7 @@ list(JOIN RUSTC_TARGET_FLAGS " " RUSTC_TARGET_FLAGS)
# https://github.com/corrosion-rs/corrosion/issues/206
# https://github.com/corrosion-rs/corrosion/issues/624
function(import_rust_crate)
- cmake_parse_arguments(PARSE_ARGV 0 ARG "PANIC_UNWIND;NO_DEFAULT_FEATURES" "MANIFEST_PATH;CRATE_NAME;FFI_OUTPUT_DIR;FFI_HEADER" "FEATURES;FFI_HEADERS;KEEP_SYMBOLS")
+ cmake_parse_arguments(PARSE_ARGV 0 ARG "PANIC_UNWIND;NO_DEFAULT_FEATURES" "MANIFEST_PATH;CRATE_NAME;FFI_OUTPUT_DIR;FFI_HEADER" "FEATURES;FFI_HEADERS;KEEP_SYMBOLS;ENVIRONMENT")
if (NOT ARG_FFI_OUTPUT_DIR)
set(ARG_FFI_OUTPUT_DIR "${CMAKE_CURRENT_BINARY_DIR}")
@@ -39,6 +40,7 @@ function(import_rust_crate)
if (ARG_PANIC_UNWIND)
list(APPEND cargo_env "CARGO_PROFILE_RELEASE_PANIC=unwind")
endif()
+ list(APPEND cargo_env ${ARG_ENVIRONMENT})
set(cargo_feature_flags "")
if (ARG_NO_DEFAULT_FEATURES)
diff --git a/Meta/Generators/generate_libweb_bindings.py b/Meta/Generators/generate_libweb_bindings.py
index aa92527dd6f..9e0278fbefb 100644
--- a/Meta/Generators/generate_libweb_bindings.py
+++ b/Meta/Generators/generate_libweb_bindings.py
@@ -17,6 +17,7 @@ from typing import TextIO
sys.path.append(str(Path(__file__).resolve().parent.parent))
from Generators.libweb_bindings import interfaces
+from Generators.libweb_bindings import rust_bindings
from Generators.libweb_bindings.context import GenerationContext
from Generators.libweb_bindings.global_mixins import write_global_mixin_header
from Generators.libweb_bindings.includes import GeneratedIncludes
@@ -108,13 +109,17 @@ def write_idl_header(out: TextIO, module: Module, context: GenerationContext) ->
if module.enumerations:
includes.add(f"LibWebCommon/Bindings/{module.path.stem}.h")
- interfaces.write_declaration(body, includes, context, module.interface)
+ if module.interface is not None and rust_bindings.is_implemented_in_rust(module.interface):
+ rust_bindings.write_cpp_declaration(body, includes, module.interface)
+ else:
+ interfaces.write_declaration(body, includes, context, module.interface)
for enumeration in module.enumerations:
write_enumeration_declaration(body, enumeration, includes)
write_enumeration_to_javascript_value_declaration(body, enumeration, includes)
- for dictionary in dictionaries_in_dependency_order(module.dictionaries, context):
+ # 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):
write_dictionary_declaration(body, dictionary, includes, context)
write_dictionary_to_javascript_value_declaration(body, dictionary)
@@ -130,13 +135,16 @@ def write_idl_implementation(out: TextIO, module: Module, context: GenerationCon
includes.add_binding(module.path.stem)
body = StringIO()
- interfaces.write_implementation(body, includes, context, module.interface)
+ if module.interface is not None and rust_bindings.is_implemented_in_rust(module.interface):
+ rust_bindings.write_cpp_implementation(body, includes, context, module.interface)
+ else:
+ interfaces.write_implementation(body, includes, context, module.interface)
for enumeration in module.enumerations:
write_enumeration_conversion(body, enumeration, includes)
write_enumeration_to_javascript_value_conversion(body, enumeration)
- for dictionary in module.dictionaries:
+ for dictionary in rust_bindings.cpp_dictionaries(module):
write_dictionary_conversion(body, dictionary, includes, context)
write_dictionary_to_javascript_value_conversion(body, dictionary, includes, context)
@@ -178,7 +186,7 @@ def write_forward_header(out: TextIO, modules: List[Module]) -> None:
for module in modules:
interface = module.interface
- if interface is None or interface.is_namespace:
+ if interface is None or interface.is_namespace or rust_bindings.is_implemented_in_rust(interface):
continue
namespace_name = cpp_namespace_for_module_path(interface.path)
@@ -200,7 +208,7 @@ def write_forward_header(out: TextIO, modules: List[Module]) -> None:
"""
)
- dictionary_names = {dictionary.name for module in modules for dictionary in module.dictionaries}
+ dictionary_names = {dictionary.name for module in modules for dictionary in rust_bindings.cpp_dictionaries(module)}
out.write(
"""namespace Web::Bindings {
@@ -260,6 +268,12 @@ def main() -> int:
context = GenerationContext(modules)
modules = context.modules
+ try:
+ rust_bindings.check_rust_bindings(context, modules)
+ except rust_bindings.UnsupportedByRustBindings as error:
+ print(f"error: {error}", file=sys.stderr)
+ return 1
+
output_files: List[Path] = []
for module in modules:
@@ -333,6 +347,12 @@ def main() -> int:
write_generated_file(wrapper_factory_implementation_path, write_wrapper_factory_implementation, interface_sets)
output_files.append(wrapper_factory_implementation_path)
+ rust_bindings_path = output_directory / "RustBindings.rs"
+ write_generated_file(
+ rust_bindings_path, rust_bindings.write_rust_bindings, context, modules, interface_sets.intrinsics
+ )
+ output_files.append(rust_bindings_path)
+
structured_serialize_bindings_implementation_path = output_directory / "StructuredSerializeBindings.cpp"
write_generated_file(
structured_serialize_bindings_implementation_path,
diff --git a/Meta/Generators/libweb_bindings/intrinsics.py b/Meta/Generators/libweb_bindings/intrinsics.py
index 4d5f678fa96..5be9851830f 100644
--- a/Meta/Generators/libweb_bindings/intrinsics.py
+++ b/Meta/Generators/libweb_bindings/intrinsics.py
@@ -15,6 +15,10 @@ from Generators.libweb_bindings.named_and_indexed_properties import create_named
from Generators.libweb_bindings.named_and_indexed_properties import interface_supports_named_properties
from Generators.libweb_bindings.named_and_indexed_properties import named_properties_object_name
from Generators.libweb_bindings.overload_resolution import parameter_list_length
+from Generators.libweb_bindings.rust_bindings import interface_name_values
+from Generators.libweb_bindings.rust_bindings import is_implemented_in_rust
+from Generators.libweb_bindings.rust_bindings import write_ensure_web_prototype_declaration
+from Generators.libweb_bindings.rust_bindings import write_ensure_web_prototype_implementation
from Generators.libweb_bindings.wrappers import create_wrapper_function_name
from Generators.libweb_bindings.wrappers import interface_needs_wrapper as wrapper_interface_needs_wrapper
from Utils.utils import title_case_to_snake_case
@@ -206,6 +210,7 @@ def write_intrinsic_definitions_header(out: TextIO, interface_sets: InterfaceSet
"""#pragma once
#include <AK/Types.h>
+#include <LibJS/HostObjectABI.h>
namespace Web::Bindings {
@@ -214,14 +219,18 @@ enum class InterfaceName : u16 {
"""
)
- for index, interface in enumerate(interface_sets.intrinsics, start=1):
- out.write(f" {interface.name} = {index},\n")
+ for name, value in interface_name_values(interface_sets.intrinsics).items():
+ out.write(f" {name} = {value},\n")
out.write(
"""};
bool is_exposed(InterfaceName, JS::Realm&);
-
+"""
+ )
+ write_ensure_web_prototype_declaration(out)
+ out.write(
+ """
}
"""
)
@@ -315,6 +324,8 @@ bool is_exposed(InterfaceName name, JS::Realm& realm)
write_interface_creation(out, interface)
write_iterator_prototype_creation(out, interface)
+ write_ensure_web_prototype_implementation(out, interface_sets.intrinsics)
+
out.write(
"""}
"""
@@ -680,7 +691,12 @@ def interface_inherits_from(
def write_wrapper_factory_implementation(out: TextIO, interface_sets: InterfaceSets) -> None:
- interfaces = [interface for interface in interface_sets.intrinsics if wrapper_interface_needs_wrapper(interface)]
+ # NB: The implementation of an interface implemented in Rust is not a Wrappable, so it never reaches the factory.
+ interfaces = [
+ interface
+ for interface in interface_sets.intrinsics
+ if wrapper_interface_needs_wrapper(interface) and not is_implemented_in_rust(interface)
+ ]
out.write(
"""#include <AK/Assertions.h>
#include <LibJS/Runtime/Realm.h>
diff --git a/Meta/Generators/libweb_bindings/rust_bindings.py b/Meta/Generators/libweb_bindings/rust_bindings.py
new file mode 100644
index 00000000000..7d75d47ed3b
--- /dev/null
+++ b/Meta/Generators/libweb_bindings/rust_bindings.py
@@ -0,0 +1,736 @@
+# 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.
+
+from typing import Dict
+from typing import List
+from typing import Optional
+from typing import TextIO
+
+from Generators.libweb_bindings.context import GenerationContext
+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_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_parameter_type
+from Generators.libweb_bindings.rust_types import rust_type
+from Generators.libweb_bindings.wrappers import wrapper_name
+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 Interface
+from Utils.webidl_parser import Module
+
+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)
+
+
+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 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}"
+
+
+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 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."""
+
+ def fail(message: str) -> None:
+ raise UnsupportedByRustBindings(f"{interface.path}: {interface.name} is [ImplementedIn=Rust], but {message}")
+
+ unsupported_attributes = set(interface.extended_attributes) - SUPPORTED_INTERFACE_EXTENDED_ATTRIBUTES
+ if unsupported_attributes:
+ fail(f"the Rust bindings do not handle its extended attributes {sorted(unsupported_attributes)}")
+ if interface.is_namespace or interface.is_callback_interface:
+ fail("it is not a regular interface")
+ if interface.parent_name:
+ fail("it inherits from another interface")
+ special_operations = [
+ interface.named_property_getter,
+ interface.indexed_property_getter,
+ interface.named_property_setter,
+ interface.indexed_property_setter,
+ interface.named_property_deleter,
+ ]
+ if any(special_operations) or interface.stringifier is not None:
+ fail("it has special operations")
+ if interface.iterable or interface.async_iterable or interface.maplike or interface.setlike:
+ fail("it is iterable or a maplike or setlike")
+ if interface.static_attributes or interface.static_operations or interface.constants:
+ fail("it has static members or constants")
+ if len(interface.constructors) > 1:
+ fail("it has more than one constructor")
+ for constructor in interface.constructors:
+ if constructor.parameters:
+ fail("its constructor has parameters")
+ if constructor.extended_attributes:
+ fail(
+ "the Rust bindings do not handle the extended attributes "
+ f"{sorted(constructor.extended_attributes)} of its constructor"
+ )
+ if module.enumerations or module.callback_functions:
+ fail("its module defines enumerations or callback functions")
+
+ for other in context.interfaces.values():
+ if other.parent_name == interface.name:
+ fail(f"{other.name} inherits from it")
+
+ def check_member_attributes(member_name: str, extended_attributes: dict) -> None:
+ unsupported = set(extended_attributes) - SUPPORTED_MEMBER_EXTENDED_ATTRIBUTES
+ if unsupported:
+ fail(f"the Rust bindings do not handle the extended attributes {sorted(unsupported)} of {member_name}")
+
+ # NB: operation_overload_sets() leaves out the operations marked [FIXME], which C++ defines as unimplemented.
+ 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}")
+
+ 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)
+ for parameter in operation.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", context, parameter_what
+ )
+ if parameter.optional and parameter.default_value is not None:
+ rust_default_value(parameter, context, parameter_what)
+
+ 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:
+ 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:
+ raise UnsupportedByRustBindings(
+ f"{module.path}: uses {nested_type.name}, which is implemented in Rust and has no C++ "
+ "representation"
+ )
+
+
+# C++ side
+
+
+def write_cpp_declaration(out: TextIO, includes: GeneratedIncludes, interface: Interface) -> None:
+ includes.add("LibJS/HostObjectABI.h")
+ includes.add("LibJS/Runtime/NativeFunction.h")
+ includes.add("LibJS/Runtime/Object.h")
+ includes.add("LibWeb/Bindings/InterfaceObject.h")
+ out.write(
+ f"""// The class of the wrappers of {interface.name}, whose implementation is in Rust.
+extern "C" 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&);
+}};
+
+"""
+ )
+
+
+def write_cpp_implementation(
+ out: TextIO, includes: GeneratedIncludes, context: GenerationContext, interface: Interface
+) -> None:
+ 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_binding(interface.implemented_name)
+
+ 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")
+ 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 interface.constructors:
+ out.write(f"JSCompletion {construct}(JSVM*, JSObject* constructor, JSObject* new_target);\n")
+ 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,
+ nullptr, nullptr, nullptr, JS_HOST_CLASS_IS_PLATFORM_OBJECT);
+
+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")
+
+
+def write_ensure_web_prototype_declaration(out: TextIO) -> None:
+ out.write(
+ """
+// The interface prototype 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);
+"""
+ )
+
+
+def write_ensure_web_prototype_implementation(out: TextIO, intrinsics: List[Interface]) -> None:
+ out.write(
+ """
+JSObject* web_bindings_ensure_web_prototype(void* realm, u16 interface_name)
+{
+ [[maybe_unused]] auto& js_realm = *static_cast<JS::Realm*>(realm);
+ switch (static_cast<InterfaceName>(interface_name)) {
+"""
+ )
+ for interface in intrinsics:
+ if not is_implemented_in_rust(interface):
+ continue
+ out.write(
+ f""" case InterfaceName::{interface.name}:
+ return JS::HostABI::object_to_abi(&ensure_web_prototype<{interface.prototype_class}>(js_realm, "{interface.namespaced_name}"_utf16_fly_string));
+"""
+ )
+ out.write(
+ """ default:
+ VERIFY_NOT_REACHED();
+ }
+}
+"""
+ )
+
+
+# Rust side
+
+
+def write_parameter_conversions(out: TextIO, interface: Interface, operation_name: str, parameters, context) -> None:
+ for index, parameter in enumerate(parameters):
+ what = f"the parameter {parameter.name} of {interface.name}.{operation_name}()"
+ name = rust_local_name(parameter.name)
+ conversion = rust_conversion_to_idl_value(
+ parameter.type, parameter.extended_attributes, f"argument{index}", context, what
+ )
+ 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, 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) -> List[str]:
+ """The methods the implementation of the interface defines, which the bindings call."""
+ signatures = []
+ if interface.constructors:
+ signatures.append("fn construct(cx: &mut CallContext) -> WebIdlResult<Self>")
+ for attribute in interface.regular_attributes:
+ what = f"{interface.name}.{attribute.name}"
+ signatures.append(
+ f"fn {rust_identifier(attribute.name)}(&self, cx: &mut CallContext) -> "
+ f"WebIdlResult<{rust_type(attribute.type, context, what)}>"
+ )
+ for name, operations in operation_overload_sets(interface).items():
+ operation = operations[0]
+ what = f"{interface.name}.{name}()"
+ parameters = "".join(
+ f", {rust_identifier(parameter.name)}: {rust_parameter_type(parameter, context, what)}"
+ for parameter in operation.parameters
+ )
+ signatures.append(
+ f"fn {rust_identifier(name)}(&self, cx: &mut CallContext{parameters}) -> "
+ f"WebIdlResult<{rust_type(operation.return_type, context, what)}>"
+ )
+ return signatures
+
+
+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)
+ )
+ 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)} {{
+ #![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,
+ RawNativeFunctionResult, ThrowCompletionOr, TypedArrayBase, TypedArrayKind, Value, Vm, raw_native,
+ }};
+
+ use crate::bindings::conversions::{{
+ BufferSourceRules, ToJs, UsvString, to_dom_string, 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,
+ 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}");
+
+ impl EmbedderValue for Implementation {{
+ const CLASS: &'static EmbedderClass<Self> = &CELL_CLASS;
+ }}
+
+ unsafe extern "C" {{
+ static {wrapper_host_class_symbol(interface)}: JSHostClass;
+ }}
+
+ fn wrapper_class() -> &'static JSHostClass {{
+ // SAFETY: LibWeb defines the class of the wrappers as constant data.
+ unsafe {{ &{wrapper_host_class_symbol(interface)} }}
+ }}
+
+ /// The implementation that an attribute or an operation runs on, and the context it runs in.
+ fn this_implementation(vm: &Vm) -> ThrowCompletionOr<(Gc<EmbedderCell<Implementation>>, CallContext<'_>)> {{
+ let (object, realm) = this_object(vm, wrapper_class(), "{interface.namespaced_name}")?;
+ Ok((implementation_of(object, &CELL_CLASS), CallContext::new(vm, realm)))
+ }}
+"""
+ )
+
+ for attribute in interface.regular_attributes:
+ getter = f"{rust_identifier(attribute.name).removeprefix('r#')}_getter"
+ 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)
+ }}
+"""
+ )
+
+ for name, operations in operation_overload_sets(interface).items():
+ operation = operations[0]
+ function = rust_identifier(name)
+ out.write(
+ f"""
+ fn {function.removeprefix("r#")}_function(vm: &Vm) -> ThrowCompletionOr<Value> {{
+ let (implementation, mut cx) = this_implementation(vm)?;
+"""
+ )
+ required_argument_count = operation_length(operation)
+ if required_argument_count == 1:
+ out.write(
+ f""" if vm.argument_count() < 1 {{
+ return vm.throw_completion(ErrorKind::TypeError, ErrorType::BadArgCountOne, &[&"{name}"]);
+ }}
+"""
+ )
+ elif required_argument_count > 1:
+ out.write(
+ f""" if vm.argument_count() < {required_argument_count} {{
+ return vm.throw_completion(
+ ErrorKind::TypeError,
+ ErrorType::BadArgCountMany,
+ &[&"{name}", &{required_argument_count}],
+ );
+ }}
+"""
+ )
+ if operation.parameters:
+ out.write(" let type_error_realm_scope = vm.type_error_realm_scope(cx.realm());\n")
+ write_parameter_conversions(out, interface, 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)
+ out.write(
+ f""" let result = Implementation::{function}(&implementation, &mut cx{arguments})
+ .map_err(|exception| exception.throw(vm))?;
+ result.to_js(&cx)
+ }}
+"""
+ )
+
+ 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);
+"""
+ )
+ for attribute in interface.regular_attributes:
+ getter = f"{rust_identifier(attribute.name).removeprefix('r#')}_getter"
+ out.write(f' define_attribute(vm, realm, prototype, "{attribute.name}", raw_native!({getter}), None);\n')
+ for name, operations in operation_overload_sets(interface).items():
+ function = f"{rust_identifier(name).removeprefix('r#')}_function"
+ length = operation_length(operations[0])
+ out.write(f' define_operation(vm, realm, prototype, "{name}", raw_native!({function}), {length});\n')
+ 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}", {constructor_length(interface)}, INTERFACE_NAME);
+ }}
+"""
+ )
+
+ if interface.constructors:
+ out.write(
+ f"""
+ /// The steps of {interface.constructor_class}::construct() of LibWeb's C++ bindings, which internally create a
+ /// new object implementing the interface, https://webidl.spec.whatwg.org/#internally-create-a-new-object-implementing-the-interface
+ ///
+ /// # 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) }};
+ let construct = || -> 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)?;
+ let mut cx = CallContext::new(vm, realm);
+ let implementation = Implementation::construct(&mut cx).map_err(|exception| exception.throw(vm))?;
+ let implementation = CELL_CLASS.allocate(vm, implementation);
+ Ok(Value::from_object(create_wrapper(vm, realm, wrapper_class(), prototype, implementation)))
+ }};
+ RawNativeFunctionResult::from_completion(construct())
+ }}
+"""
+ )
+ out.write("}\n")
+
+
+def constructor_length(interface: Interface) -> int:
+ if not interface.constructors:
+ return 0
+ 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
+ )
+ 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))
+ }}
+ }}
+"""
+ )
+
+
+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":
+ 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)
+
+
+def write_rust_bindings(out: TextIO, context: GenerationContext, modules: List[Module], intrinsics) -> 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)
+ for module in 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])
diff --git a/Meta/Generators/libweb_bindings/rust_types.py b/Meta/Generators/libweb_bindings/rust_types.py
new file mode 100644
index 00000000000..3d17fb7de2b
--- /dev/null
+++ b/Meta/Generators/libweb_bindings/rust_types.py
@@ -0,0 +1,113 @@
+# Copyright (c) 2026-present, the Ladybird developers.
+#
+# SPDX-License-Identifier: BSD-2-Clause
+
+# The Rust types of IDL values, and the Rust expressions that convert JS values to them, for the Rust bindings of the
+# interfaces implemented in Rust. They cover the types that those interfaces use so far; every other type is an error.
+
+from typing import Optional
+
+from Generators.libweb_bindings.context import GenerationContext
+from Utils.webidl_parser import Dictionary
+from Utils.webidl_parser import IDLType
+from Utils.webidl_parser import OperationParameter
+
+# The typed arrays, whose names are the variants of the runtime's TypedArrayKind.
+TYPED_ARRAY_NAMES = {
+ "Int8Array",
+ "Uint8Array",
+ "Uint8ClampedArray",
+ "Int16Array",
+ "Uint16Array",
+ "Int32Array",
+ "Uint32Array",
+ "BigInt64Array",
+ "BigUint64Array",
+ "Float16Array",
+ "Float32Array",
+ "Float64Array",
+}
+
+# The extended attributes of a type or a parameter that the Rust bindings handle.
+SUPPORTED_TYPE_EXTENDED_ATTRIBUTES = {"AllowShared", "AllowResizable"}
+
+
+class UnsupportedByRustBindings(Exception):
+ pass
+
+
+def resolved_dictionary(idl_type: IDLType, context: GenerationContext) -> Optional[Dictionary]:
+ return context.dictionaries.get(idl_type.name)
+
+
+def check_type_is_supported(idl_type: IDLType, context: GenerationContext, what: str) -> None:
+ 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"
+ if name == "USVString":
+ return "UsvString"
+ if name == "boolean":
+ return "bool"
+ if name == "unsigned long long":
+ return "u64"
+ if name == "undefined":
+ return "()"
+ if name in TYPED_ARRAY_NAMES:
+ return "Gc<TypedArrayBase>"
+ if resolved_dictionary(idl_type, context) is not None:
+ return name
+ raise UnsupportedByRustBindings(f"{what} has the type {idl_type}, which the Rust bindings do not convert yet")
+
+
+def rust_parameter_type(parameter: OperationParameter, context: GenerationContext, what: str) -> str:
+ """The Rust type the implementation receives for the parameter."""
+ value_type = rust_type(parameter.type, context, what)
+ if parameter.optional and parameter.default_value is None:
+ return f"Option<{value_type}>"
+ return value_type
+
+
+def rust_conversion_to_idl_value(
+ idl_type: IDLType, parameter_attributes: dict[str, str], value: str, context: GenerationContext, what: str
+) -> str:
+ """An expression of type ThrowCompletionOr<T> that converts the JS value to the IDL value."""
+ name = idl_type.name
+ if name == "DOMString":
+ return f"to_dom_string(vm, {value})"
+ if name == "USVString":
+ return f"to_usv_string(vm, {value})"
+ if name in TYPED_ARRAY_NAMES:
+ attributes = {**idl_type.extended_attributes, **parameter_attributes}
+ allow_shared = "true" if "AllowShared" in attributes else "false"
+ allow_resizable = "true" if "AllowResizable" in attributes else "false"
+ return (
+ f'to_typed_array(vm, {value}, TypedArrayKind::{name}, "{name}", '
+ f"&BufferSourceRules {{ allow_shared: {allow_shared}, allow_resizable: {allow_resizable} }})"
+ )
+ raise UnsupportedByRustBindings(f"{what} has the type {idl_type}, which the Rust bindings do not convert to yet")
+
+
+def rust_default_value(parameter: OperationParameter, context: GenerationContext, what: str) -> str:
+ """An expression of the parameter's default value."""
+ name = parameter.type.name
+ default_value = parameter.default_value
+ if name in ("DOMString", "USVString") and default_value is not None and default_value.startswith('"'):
+ string = default_value[1:-1]
+ if not string.isascii() or "\\" in string:
+ raise UnsupportedByRustBindings(f"{what} has the default value {default_value}")
+ if name == "USVString":
+ return f'UsvString::from_ascii(b"{string}")'
+ return f'Utf16String::from_ascii(b"{string}")'
+ raise UnsupportedByRustBindings(
+ f"{what} has the default value {default_value}, which the Rust bindings do not have"
+ )
diff --git a/Meta/Utils/webidl_parser.py b/Meta/Utils/webidl_parser.py
index 383da03d58c..419ac052056 100644
--- a/Meta/Utils/webidl_parser.py
+++ b/Meta/Utils/webidl_parser.py
@@ -39,6 +39,7 @@ ALLOWED_EXTENDED_ATTRIBUTES = frozenset(
"Global",
"HTMLConstructor",
"ImplementedAs",
+ "ImplementedIn",
"ImplementedInBindings",
"InvalidValueDefault",
"LegacyFactoryFunction",