Skip to content

Truly independent web browser

Meta+LibWeb: Convert integers and plain JS values in the Rust bindings

Aliaksandr Kalenikde00e92314f0
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs
index d2eb4e7dcee..25638c0cda9 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs
@@ -118,6 +118,85 @@ pub(crate) fn to_boolean(value: Value) -> ThrowCompletionOr<bool> {
Ok(value.to_boolean())
}
+/// A JS value converted to a long, https://webidl.spec.whatwg.org/#js-long
+pub(crate) fn to_long(vm: &Vm, value: Value) -> ThrowCompletionOr<i32> {
+ // 1. Let x be ? ConvertToInt(V, 32, "signed"), which is ToInt32 without the extended attributes that change it.
+ // 2. Return the IDL long value that represents the same numeric value as x.
+ value.to_i32(vm)
+}
+
+/// A JS value converted to an unsigned long, https://webidl.spec.whatwg.org/#js-unsigned-long
+pub(crate) fn to_unsigned_long(vm: &Vm, value: Value) -> ThrowCompletionOr<u32> {
+ // 1. Let x be ? ConvertToInt(V, 32, "unsigned"), which is ToUint32 without the extended attributes that change
+ // it.
+ // 2. Return the IDL unsigned long value that represents the same numeric value as x.
+ value.to_u32(vm)
+}
+
+/// The number that https://webidl.spec.whatwg.org/#abstract-opdef-converttoint has after step 10 for a bit length of
+/// 64, as WebIDL::convert_to_int() of the C++ bindings computes it.
+///
+/// FIXME: The C++ bindings do the arithmetic in doubles, which cannot represent most integers near 2^64, so a
+/// negative number does not wrap around to the integer the spec asks for: -1 becomes 2^64. The Rust bindings
+/// do the same, so that an interface behaves the same in either language, until both are corrected together.
+fn to_number_modulo_two_to_the_64(vm: &Vm, value: Value) -> ThrowCompletionOr<f64> {
+ const TWO_TO_THE_64: f64 = 18_446_744_073_709_551_616.0;
+
+ // 4. Let x be ? ToNumber(V).
+ // 5. If x is −0, then set x to +0.
+ let x = value.to_double(vm)?;
+
+ // 8. If x is NaN, +0, +∞, or −∞, then return +0.
+ if x.is_nan() || x == 0.0 || x.is_infinite() {
+ return Ok(0.0);
+ }
+
+ // 9. Set x to IntegerPart(x).
+ let x = x.trunc();
+
+ // 10. Set x to x modulo 2^bitLength.
+ let remainder = x % TWO_TO_THE_64;
+ Ok(if remainder < 0.0 {
+ remainder + TWO_TO_THE_64
+ } else {
+ remainder
+ })
+}
+
+/// A JS value converted to a long long, https://webidl.spec.whatwg.org/#js-long-long
+pub(crate) fn to_long_long(vm: &Vm, value: Value) -> ThrowCompletionOr<i64> {
+ const TWO_TO_THE_63: f64 = 9_223_372_036_854_775_808.0;
+ const TWO_TO_THE_64: f64 = 18_446_744_073_709_551_616.0;
+
+ // 1. Let x be ? ConvertToInt(V, 64, "signed").
+ let x = to_number_modulo_two_to_the_64(vm, value)?;
+
+ // 11. If signedness is "signed" and x ≥ 2^(bitLength − 1), then return x − 2^(bitLength).
+ // NB: The C++ bindings compare with the largest long long, which is 2^63 as a double, and with greater than.
+ let x = if x > TWO_TO_THE_63 { x - TWO_TO_THE_64 } else { x };
+
+ // 2. Return the IDL long long value that represents the same numeric value as x.
+ #[allow(
+ clippy::cast_possible_truncation,
+ reason = "x is an integer of at most 2^63, which saturates"
+ )]
+ Ok(x as i64)
+}
+
+/// A JS value converted to an unsigned long long, https://webidl.spec.whatwg.org/#js-unsigned-long-long
+pub(crate) fn to_unsigned_long_long(vm: &Vm, value: Value) -> ThrowCompletionOr<u64> {
+ // 1. Let x be ? ConvertToInt(V, 64, "unsigned").
+ let x = to_number_modulo_two_to_the_64(vm, value)?;
+
+ // 2. Return the IDL unsigned long long value that represents the same numeric value as x.
+ #[allow(
+ clippy::cast_possible_truncation,
+ clippy::cast_sign_loss,
+ reason = "x is an integer from 0 to 2^64, which saturates"
+ )]
+ Ok(x as u64)
+}
+
/// A JS value converted to a float, https://webidl.spec.whatwg.org/#js-float
///
/// The identifier is the name of the parameter or member that the value is of, which the error names.
@@ -147,6 +226,27 @@ pub(crate) fn to_float(vm: &Vm, value: Value, identifier: &str) -> ThrowCompleti
Ok(y)
}
+/// A JS value converted to an unrestricted float, https://webidl.spec.whatwg.org/#js-unrestricted-float
+pub(crate) fn to_unrestricted_float(vm: &Vm, value: Value) -> ThrowCompletionOr<f32> {
+ // 1. Let x be ? ToNumber(V).
+ let x = value.to_double(vm)?;
+
+ // 2. If x is NaN, then return the IDL unrestricted float value that represents the IEEE 754 NaN value with the
+ // bit pattern 0x7fc00000.
+ // 3. Let S be the set of finite IEEE 754 single-precision floating point values except −0, but with two special
+ // values added: 2^128 and −2^128.
+ // 4. Let y be the number in S that is closest to x, selecting the number with an even significand if there are two
+ // equally close values. (The two special values 2^128 and −2^128 are considered to have even significands for
+ // this purpose.)
+ // 5. If y is 2^128, return +∞.
+ // 6. If y is −2^128, return −∞.
+ // 7. If y is +0 and x is negative, return −0.
+ // 8. Return y.
+ // NB: Rounding x to the nearest float gives an infinity where step 4 gives one of the two special values.
+ #[allow(clippy::cast_possible_truncation, reason = "the spec rounds to the closest float")]
+ Ok(x as f32)
+}
+
/// A JS value converted to an unrestricted double, https://webidl.spec.whatwg.org/#js-unrestricted-double
pub(crate) fn to_unrestricted_double(vm: &Vm, value: Value) -> ThrowCompletionOr<f64> {
// 1. Let x be ? ToNumber(V).
@@ -373,6 +473,43 @@ impl ToJs for bool {
}
}
+/// https://webidl.spec.whatwg.org/#js-any
+impl ToJs for Value {
+ fn to_js(self, _: &CallContext) -> ThrowCompletionOr<Value> {
+ Ok(self)
+ }
+}
+
+/// An object converted to a JS value: https://webidl.spec.whatwg.org/#js-object, and what an implementation returns
+/// for a promise type, https://webidl.spec.whatwg.org/#js-promise, which is the promise object.
+impl ToJs for Gc<Object> {
+ fn to_js(self, _: &CallContext) -> ThrowCompletionOr<Value> {
+ Ok(Value::from_object(self))
+ }
+}
+
+/// https://webidl.spec.whatwg.org/#js-long
+impl ToJs for i32 {
+ fn to_js(self, _: &CallContext) -> ThrowCompletionOr<Value> {
+ Ok(Value::from_i32(self))
+ }
+}
+
+/// https://webidl.spec.whatwg.org/#js-unsigned-long
+impl ToJs for u32 {
+ fn to_js(self, _: &CallContext) -> ThrowCompletionOr<Value> {
+ Ok(Value::from_f64(f64::from(self)))
+ }
+}
+
+/// https://webidl.spec.whatwg.org/#js-long-long
+impl ToJs for i64 {
+ 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))
+ }
+}
+
/// https://webidl.spec.whatwg.org/#js-unsigned-long-long
impl ToJs for u64 {
fn to_js(self, _: &CallContext) -> ThrowCompletionOr<Value> {
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/interface.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/interface.rs
index 9f017e17598..3e42934f9a9 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/interface.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/interface.rs
@@ -22,14 +22,15 @@ use core::ptr::NonNull;
use libjs_rust::api::{
Attribute, EmbedderCell, EmbedderClass, EmbedderValue, ErrorKind, ErrorType, FunctionObject, Gc, HostObject,
- JSHostClass, Object, PrimitiveString, PropertyAttributes, PropertyKey, RawNativeFunctionPointer, Realm,
+ JSHostClass, Object, PrimitiveString, PropertyAttributes, PropertyKey, RawNativeFunctionPointer, Realm, Throw,
ThrowCompletionOr, Trace, Value, Vm, get_function_realm, host_data_of, is_host_instance_of,
};
use crate::bindings::CallContext;
use crate::bindings::realm_data::wrapper_world_of;
use crate::bindings::services::{
- web_bindings_ensure_web_prototype, web_bindings_rust_wrapper_for, web_bindings_set_rust_wrapper,
+ web_bindings_ensure_web_prototype, web_bindings_rejected_promise, web_bindings_rust_wrapper_for,
+ web_bindings_set_rust_wrapper,
};
/// What an implementation can tell the bindings about its objects, as a C++ implementation object does by overriding
@@ -240,6 +241,18 @@ fn create_wrapper<T: Interface>(vm: &Vm, realm: Gc<Realm>, prototype: Gc<Object>
}
}
+/// What an operation that returns a promise type returns in place of throwing: a promise rejected with what its
+/// steps threw, https://webidl.spec.whatwg.org/#dfn-create-operation-function
+pub(crate) fn rejected_promise(vm: &Vm, throw: Throw) -> Value {
+ let current_realm = vm.current_realm().expect("a native function runs in a realm");
+ // SAFETY: The realm is live, and the values are live while the native function runs.
+ let promise =
+ unsafe { web_bindings_rejected_promise(current_realm.as_ptr().cast(), vm.this_value().0, throw.value().0) };
+ let promise = NonNull::new(promise.cast::<Object>()).expect("LibWeb returns the promise");
+ // SAFETY: LibWeb returns a live promise.
+ Value::from_object(unsafe { Gc::from_non_null(promise) })
+}
+
/// 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.
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/services.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/services.rs
index 981d20b8698..61531a49bd0 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/services.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/services.rs
@@ -25,4 +25,12 @@ unsafe extern "C" {
/// Makes `wrapper` the wrapper that the world of its realm, which is not a main world, holds for the cell.
pub(crate) fn web_bindings_set_rust_wrapper(realm: *mut c_void, cell: *mut c_void, wrapper: *mut c_void);
+
+ /// A promise rejected with the reason, in the realm of the this value of an operation that ran in the current
+ /// realm: the realm of the object, or the current realm for a value that is not an object.
+ pub(crate) fn web_bindings_rejected_promise(
+ current_realm: *mut c_void,
+ this_value: u64,
+ reason: u64,
+ ) -> *mut c_void;
}
diff --git a/Libraries/LibWeb/Bindings/RustBindingsServices.cpp b/Libraries/LibWeb/Bindings/RustBindingsServices.cpp
index 4b890392b00..77cd692e3b2 100644
--- a/Libraries/LibWeb/Bindings/RustBindingsServices.cpp
+++ b/Libraries/LibWeb/Bindings/RustBindingsServices.cpp
@@ -9,6 +9,7 @@
#include <LibJS/Runtime/Realm.h>
#include <LibWeb/Bindings/RustInterface.h>
#include <LibWeb/Bindings/WrapperWorld.h>
+#include <LibWeb/WebIDL/Promise.h>
// What the Rust bindings of the interfaces implemented in Rust ask of LibWeb's C++ bindings, declared on the Rust
// side in Libraries/LibWeb/Bindings/Rust/src/bindings/services.rs.
@@ -23,6 +24,7 @@ extern "C" {
void* web_bindings_wrapper_world(void* realm, bool* is_main_world);
JSObject* web_bindings_rust_wrapper_for(void* realm, void* cell);
void web_bindings_set_rust_wrapper(void* realm, void* cell, JSObject* wrapper);
+JSObject* web_bindings_rejected_promise(void* current_realm, JSValue this_value, JSValue reason);
void* web_bindings_wrapper_world(void* realm, bool* is_main_world)
{
@@ -43,6 +45,17 @@ void web_bindings_set_rust_wrapper(void* realm, void* cell, JSObject* wrapper)
auto& host_object = as<JS::HostObject>(*JS::HostABI::object_from_abi(wrapper));
host_defined_wrapper_world(*static_cast<JS::Realm*>(realm)).set_rust_wrapper(*static_cast<RustInterfaceCell*>(cell), host_object);
}
+
+JSObject* web_bindings_rejected_promise(void* current_realm, JSValue this_value, JSValue reason)
+{
+ auto& realm = *static_cast<JS::Realm*>(current_realm);
+ auto promise_realm_this_value = JS::HostABI::value_from_abi(this_value);
+ if (promise_realm_this_value.is_nullish())
+ promise_realm_this_value = &realm.global_object();
+ auto& promise_realm = this_value_realm(realm, promise_realm_this_value);
+ auto promise = WebIDL::create_rejected_promise(promise_realm, JS::HostABI::value_from_abi(reason));
+ return JS::HostABI::object_to_abi(promise->promise().ptr());
+}
}
}
diff --git a/Meta/Generators/libweb_bindings/rust_bindings.py b/Meta/Generators/libweb_bindings/rust_bindings.py
index 4444486473a..fdd68f5a6e2 100644
--- a/Meta/Generators/libweb_bindings/rust_bindings.py
+++ b/Meta/Generators/libweb_bindings/rust_bindings.py
@@ -14,6 +14,8 @@
# A wrapper is a platform object whose host data holds a GC cell of the implementation. Its wrappable slot stays
# empty, so the C++ bindings see a platform object without a C++ implementation object.
+import textwrap
+
from io import StringIO
from typing import Dict
from typing import List
@@ -23,6 +25,7 @@ from Generators.libweb_bindings.context import GenerationContext
from Generators.libweb_bindings.includes import GeneratedIncludes
from Generators.libweb_bindings.rust_members import RustConstructor
from Generators.libweb_bindings.rust_members import RustMembers
+from Generators.libweb_bindings.rust_members import RustOperation
from Generators.libweb_bindings.rust_members import rust_members
from Generators.libweb_bindings.rust_names import rust_identifier
from Generators.libweb_bindings.rust_names import rust_local_name
@@ -36,8 +39,10 @@ from Generators.libweb_bindings.rust_to_js_value import write_dictionary_to_js
from Generators.libweb_bindings.rust_to_js_value import write_union_to_js
from Generators.libweb_bindings.rust_types import UnsupportedByRustBindings
from Generators.libweb_bindings.rust_types import is_implemented_in_rust
+from Generators.libweb_bindings.rust_types import is_promise_type
from Generators.libweb_bindings.rust_types import rust_interface_path
from Generators.libweb_bindings.rust_types import rust_parameter_type
+from Generators.libweb_bindings.rust_types import rust_result_type
from Generators.libweb_bindings.rust_types import rust_type
from Generators.libweb_bindings.rust_usage import DefinitionUsage
from Generators.libweb_bindings.wrappers import wrapper_name
@@ -329,7 +334,7 @@ def implementation_method_signatures(
parameters = parameter_list(what, overload.operation.parameters)
signatures.append(
f"fn {overload.method}(&self, cx: &mut CallContext{parameters}) -> "
- f"WebIdlResult<{rust_type(overload.operation.return_type, context, what)}>"
+ f"WebIdlResult<{rust_result_type(overload.operation.return_type, context, what)}>"
)
return signatures
@@ -358,14 +363,15 @@ def write_rust_interface(
use crate::bindings::conversions::{{
BufferSource, BufferSourceRules, EmptyDictionary, FromJs, ToJs, UsvString, record_to_js,
- rooted_sequence_to_js, sequence_to_js, to_boolean, to_buffer_source, to_dom_string, to_float, to_typed_array,
- to_unrestricted_double, to_usv_string,
+ rooted_sequence_to_js, sequence_to_js, to_boolean, to_buffer_source, to_dom_string, to_float, to_long,
+ to_long_long, to_typed_array, to_unrestricted_double, to_unrestricted_float, to_unsigned_long,
+ to_unsigned_long_long, to_usv_string,
}};
use crate::bindings::interface::{{
Interface, Ref, Wrapped, construct_arguments, construct_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,
- to_interface,
+ implementation_of, prototype_from_new_target, rejected_promise, set_interface_prototype_object_prototype,
+ this_object, to_interface,
}};
use crate::bindings::{{CallContext, WebIdlResult}};
@@ -417,28 +423,8 @@ def write_rust_interface(
)
for operation_set in members.operation_sets:
- name = operation_set.name
- overload = operation_set.overloads[0]
- operation = overload.operation
- out.write(
- f"""
- fn {operation_set.function}(vm: &Vm) -> ThrowCompletionOr<Value> {{
- let (implementation, mut cx) = this_implementation(vm)?;
-"""
- )
- write_argument_count_check(out, name, overload.length)
- if operation.parameters:
- out.write(" let type_error_realm_scope = vm.type_error_realm_scope(cx.realm());\n")
- 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::{overload.method}(&implementation, &mut cx{arguments})
- .map_err(|exception| exception.throw(vm))?;
- {conversion}
- }}
-"""
+ write_rust_operation(
+ out, context, interface, operation_set.name, operation_set.function, operation_set.overloads[0]
)
out.write(
@@ -525,6 +511,49 @@ def write_rust_interface(
out.write("}\n")
+def write_rust_operation(
+ out: TextIO, context: GenerationContext, interface: Interface, name: str, function: str, overload: RustOperation
+) -> None:
+ """The native function of the steps of an operation, in the order of the C++ bindings: the this value is checked,
+ then the arguments are counted and converted, with the type errors of the conversions in the realm of the object."""
+ operation = overload.operation
+ what = f"{interface.name}.{name}()"
+ steps = StringIO()
+ steps.write(" let (implementation, mut cx) = this_implementation(vm)?;\n")
+ write_argument_count_check(steps, name, overload.length)
+ if operation.parameters:
+ steps.write(" let type_error_realm_scope = vm.type_error_realm_scope(cx.realm());\n")
+ write_parameter_conversions(steps, what, operation.parameters, context)
+ steps.write(" drop(type_error_realm_scope);\n")
+ arguments = "".join(f", {rust_local_name(parameter.name)}" for parameter in operation.parameters)
+ returns_promise = is_promise_type(operation.return_type) and not operation.return_type.nullable
+ if returns_promise:
+ conversion = "result.to_js(&cx)"
+ else:
+ conversion = rust_to_js_value(operation.return_type, "result", "&cx", context, what)
+ steps.write(
+ f""" let result = Implementation::{overload.method}(&implementation, &mut cx{arguments})
+ .map_err(|exception| exception.throw(vm))?;
+ {conversion}
+"""
+ )
+
+ out.write(f"\n fn {function}(vm: &Vm) -> ThrowCompletionOr<Value> {{\n")
+ if returns_promise:
+ # NB: The C++ bindings run everything, the check of the this value included, inside these steps.
+ out.write(
+ f""" // An exception that the steps of an operation with a promise type throw rejects a new promise,
+ // https://webidl.spec.whatwg.org/#dfn-create-operation-function
+ let steps = || -> ThrowCompletionOr<Value> {{
+{textwrap.indent(steps.getvalue(), " ")} }};
+ steps().or_else(|throw| Ok(rejected_promise(vm, throw)))
+"""
+ )
+ else:
+ out.write(steps.getvalue())
+ out.write(" }\n")
+
+
def write_rust_constructor(
out: TextIO, context: GenerationContext, interface: Interface, constructor: RustConstructor
) -> None:
@@ -576,7 +605,8 @@ pub(crate) mod definitions {
use crate::bindings::conversions::{
BufferSource, BufferSourceRules, EmptyDictionary, FromJs, ToJs, UsvString, dictionary_member,
dictionary_object, record_to_js, rooted_sequence_to_js, sequence_to_js, to_boolean, to_buffer_source,
- to_dom_string, to_float, to_typed_array, to_unrestricted_double, to_usv_string,
+ to_dom_string, to_float, to_long, to_long_long, to_typed_array, to_unrestricted_double,
+ to_unrestricted_float, to_unsigned_long, to_unsigned_long_long, to_usv_string,
};
use crate::bindings::interface::{Ref, create_dictionary_object, set_dictionary_member, to_interface};
"""
diff --git a/Meta/Generators/libweb_bindings/rust_to_idl_value.py b/Meta/Generators/libweb_bindings/rust_to_idl_value.py
index 11e1d6ba485..27187c92ebb 100644
--- a/Meta/Generators/libweb_bindings/rust_to_idl_value.py
+++ b/Meta/Generators/libweb_bindings/rust_to_idl_value.py
@@ -14,6 +14,7 @@ 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 DECIMAL_LITERAL
from Generators.libweb_bindings.rust_types import FLOATING_POINT_TYPES
+from Generators.libweb_bindings.rust_types import INTEGER_TYPES
from Generators.libweb_bindings.rust_types import TYPED_ARRAY_NAMES
from Generators.libweb_bindings.rust_types import UnsupportedByRustBindings
from Generators.libweb_bindings.rust_types import is_named_union
@@ -21,6 +22,7 @@ from Generators.libweb_bindings.rust_types import member_other_than_undefined
from Generators.libweb_bindings.rust_types import resolved_dictionary
from Generators.libweb_bindings.rust_types import runtime_union_type
from Generators.libweb_bindings.rust_types import rust_dictionary_path
+from Generators.libweb_bindings.rust_types import rust_integer_literal
from Generators.libweb_bindings.rust_types import rust_interface
from Generators.libweb_bindings.rust_types import rust_interface_path
from Generators.libweb_bindings.rust_types import rust_type
@@ -75,8 +77,12 @@ def rust_to_idl_value(
return f"to_usv_string(vm, {value})"
if name == "boolean":
return f"to_boolean({value})"
+ if name in INTEGER_TYPES:
+ return f"to_{name.replace(' ', '_')}(vm, {value})"
if name == "float":
return f'to_float(vm, {value}, "{identifier}")'
+ if name == "unrestricted float":
+ return f"to_unrestricted_float(vm, {value})"
if name == "unrestricted double":
return f"to_unrestricted_double(vm, {value})"
if name in TYPED_ARRAY_NAMES:
@@ -131,6 +137,10 @@ def rust_default_value(
return default_value
if name in FLOATING_POINT_TYPES and default_value is not None and DECIMAL_LITERAL.fullmatch(default_value):
return f"{default_value}_{FLOATING_POINT_TYPES[name]}"
+ if name in INTEGER_TYPES:
+ integer_literal = rust_integer_literal(default_value, name)
+ if integer_literal is not None:
+ return integer_literal
dictionary = resolved_dictionary(member.type, context)
if dictionary is not None and default_value == "{}":
# NB: The C++ bindings do not run the conversion for a missing argument either, so the members of the default
diff --git a/Meta/Generators/libweb_bindings/rust_to_js_value.py b/Meta/Generators/libweb_bindings/rust_to_js_value.py
index b70ea2e2dfd..066f31800d0 100644
--- a/Meta/Generators/libweb_bindings/rust_to_js_value.py
+++ b/Meta/Generators/libweb_bindings/rust_to_js_value.py
@@ -12,9 +12,9 @@ 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 holds_cells
from Generators.libweb_bindings.rust_types import member_other_than_undefined
from Generators.libweb_bindings.rust_types import rust_dictionary_path
-from Generators.libweb_bindings.rust_types import rust_interface
from Generators.libweb_bindings.rust_types import rust_type
from Generators.libweb_bindings.rust_types import rust_union_path
from Generators.libweb_bindings.rust_types import rust_union_variant
@@ -49,10 +49,9 @@ def rust_to_js_value(
}}"""
if isinstance(idl_type, IDLParameterizedType) and idl_type.name == "sequence":
element_type = idl_type.parameters[0]
- # NB: The conversion of an object of an interface can create its wrapper, and the elements after it must
- # live through that.
- holds_cells = rust_interface(element_type.without_nullable(), context) is not None
- function = "rooted_sequence_to_js" if holds_cells else "sequence_to_js"
+ # NB: The conversion of an element can allocate, as that of an object of an interface does for its wrapper,
+ # and the elements after it must live through that.
+ function = "rooted_sequence_to_js" if holds_cells(element_type, context) else "sequence_to_js"
return f"{function}({call_context}, {expression}, |value| {inner(element_type)})"
if isinstance(idl_type, IDLParameterizedType) and idl_type.name == "record":
return f"record_to_js({call_context}, {expression}, |value| {inner(idl_type.parameters[1])})"
diff --git a/Meta/Generators/libweb_bindings/rust_types.py b/Meta/Generators/libweb_bindings/rust_types.py
index 93985d8ac83..fad96b54f9b 100644
--- a/Meta/Generators/libweb_bindings/rust_types.py
+++ b/Meta/Generators/libweb_bindings/rust_types.py
@@ -38,19 +38,49 @@ TYPED_ARRAY_NAMES = {
# The extended attributes of a type or a parameter that the Rust bindings handle.
SUPPORTED_TYPE_EXTENDED_ATTRIBUTES = {"AllowShared", "AllowResizable"}
+# The integer types, with the Rust type of their values.
+INTEGER_TYPES = {"long": "i32", "unsigned long": "u32", "long long": "i64", "unsigned long long": "u64"}
+
# The floating point types, with the Rust type of their values.
-FLOATING_POINT_TYPES = {"float": "f32", "unrestricted double": "f64"}
+FLOATING_POINT_TYPES = {"float": "f32", "unrestricted float": "f32", "unrestricted double": "f64"}
# The unions that the bindings runtime has a type for, by the name of the typedef that names the union.
RUNTIME_UNION_TYPES = {"BufferSource": "BufferSource"}
DECIMAL_LITERAL = re.compile(r"-?[0-9]+(\.[0-9]+)?([eE][-+]?[0-9]+)?")
+# https://webidl.spec.whatwg.org/#prod-integer
+INTEGER_LITERAL = re.compile(r"-?([1-9][0-9]*|0[Xx][0-9A-Fa-f]+|0[0-7]*)")
+
class UnsupportedByRustBindings(Exception):
pass
+def rust_integer_literal(literal: Optional[str], idl_type_name: str) -> Optional[str]:
+ """The Rust literal of the value of an integer token of the IDL, or None if the token is not one or its value is
+ not one of the integer type."""
+ if literal is None or not INTEGER_LITERAL.fullmatch(literal):
+ return None
+ digits = literal.removeprefix("-")
+ if digits[:2] in ("0x", "0X"):
+ magnitude = int(digits, 16)
+ elif digits.startswith("0"):
+ magnitude = int(digits, 8)
+ else:
+ magnitude = int(digits, 10)
+ integer = -magnitude if literal.startswith("-") else magnitude
+ rust_integer_type = INTEGER_TYPES[idl_type_name]
+ bits = int(rust_integer_type[1:])
+ if rust_integer_type.startswith("u"):
+ lowest, highest = 0, 2**bits - 1
+ else:
+ lowest, highest = -(2 ** (bits - 1)), 2 ** (bits - 1) - 1
+ if not lowest <= integer <= highest:
+ return None
+ return f"{integer}_{rust_integer_type}"
+
+
def is_implemented_in_rust(interface: Optional[Interface]) -> bool:
return interface is not None and interface.extended_attributes.get("ImplementedIn") == "Rust"
@@ -171,12 +201,16 @@ def rust_type(idl_type: IDLType, context: GenerationContext, what: str) -> str:
return "UsvString"
if name == "boolean":
return "bool"
- if name == "unsigned long long":
- return "u64"
+ if name in INTEGER_TYPES:
+ return INTEGER_TYPES[name]
if name in FLOATING_POINT_TYPES:
return FLOATING_POINT_TYPES[name]
if name == "undefined":
return "()"
+ if name == "any":
+ return "Value"
+ if name == "object":
+ return "Gc<Object>"
if name in TYPED_ARRAY_NAMES:
return "Gc<TypedArrayBase>"
if context.callback_function(idl_type) is not None:
@@ -200,6 +234,29 @@ def rust_type(idl_type: IDLType, context: GenerationContext, what: str) -> str:
raise UnsupportedByRustBindings(f"{what} has the type {idl_type}, which the Rust bindings do not convert yet")
+def is_promise_type(idl_type: IDLType) -> bool:
+ return isinstance(idl_type, IDLParameterizedType) and idl_type.name == "Promise"
+
+
+def rust_result_type(idl_type: IDLType, context: GenerationContext, what: str) -> str:
+ """The Rust type that the method of an operation returns. An operation that returns a promise type returns the
+ promise object, which is the only place the Rust bindings handle a promise type in."""
+ if is_promise_type(idl_type) and not idl_type.nullable:
+ return "Gc<Object>"
+ return rust_type(idl_type, context, what)
+
+
+def holds_cells(idl_type: IDLType, context: GenerationContext) -> bool:
+ """Whether the Rust type of the IDL values of the type is or can hold a cell, which a Vec would hide from the
+ collector."""
+ idl_type = idl_type.without_nullable()
+ if isinstance(idl_type, (IDLParameterizedType, IDLUnionType)):
+ return False
+ if idl_type.name in ("any", "object") or idl_type.name in TYPED_ARRAY_NAMES:
+ return True
+ return context.callback_function(idl_type) is not None or rust_interface(idl_type, context) is not None
+
+
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)