Truly independent web browser
Meta+LibWeb: Convert integers with [EnforceRange] in the Rust bindings
Andreas Kling5194b152c502
diff --git a/Libraries/LibWeb/Bindings/Rust/src/ak_format.rs b/Libraries/LibWeb/Bindings/Rust/src/ak_format.rsnew file mode 100644index 00000000000..1dd4d0b28ad--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/ak_format.rs@@ -0,0 +1,89 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Numbers in the messages of exceptions, written as LibWeb's C++ wrote them.++use core::fmt::LowerExp;++/// The number as AK's formatter writes it for "{}", which the messages of the C++ had: the shortest digits that+/// read back as the number, in the notation of Number::toString() of ECMAScript.+pub(crate) fn ak_formatted(number: impl LowerExp) -> String {+ let scientific = format!("{number:e}");+ let (sign, scientific) = match scientific.strip_prefix('-') {+ Some(magnitude) => ("-", magnitude),+ None => ("", scientific.as_str()),+ };+ let (mantissa, exponent) = scientific+ .split_once('e')+ .expect("a number in scientific notation has an exponent");+ let exponent: i32 = exponent.parse().expect("the exponent is an integer");+ let digits: String = mantissa.chars().filter(|character| *character != '.').collect();+ let digit_count = i32::try_from(digits.len()).expect("a number has few digits");+ let zeros = |count: i32| "0".repeat(usize::try_from(count).expect("the count is not negative"));++ let unsigned = if !(-6..=20).contains(&exponent) {+ let (first, rest) = digits.split_at(1);+ let fraction = if rest.is_empty() {+ String::new()+ } else {+ format!(".{rest}")+ };+ let exponent_sign = if exponent < 0 { '-' } else { '+' };+ format!("{first}{fraction}e{exponent_sign}{}", exponent.unsigned_abs())+ } else if exponent < 0 {+ format!("0.{}{digits}", zeros(-exponent - 1))+ } else if digit_count <= exponent + 1 {+ format!("{digits}{}", zeros(exponent + 1 - digit_count))+ } else {+ let (integer, fraction) = digits.split_at(usize::try_from(exponent + 1).expect("the exponent is not negative"));+ format!("{integer}.{fraction}")+ };+ format!("{sign}{unsigned}")+}++#[cfg(test)]+mod tests {+ use super::ak_formatted;++ #[test]+ fn numbers_are_formatted_as_ak_formats_them() {+ // NB: What AK's "{}" wrote for these numbers, which a C++ program printed.+ let floats: [(f32, &str); 14] = [+ (-1.0, "-1"),+ (-0.5, "-0.5"),+ (-0.1, "-0.1"),+ (-1e30, "-1e+30"),+ (-1e-7, "-1e-7"),+ (-123_456_789.0, "-123456790"),+ (-3.402_823_5e38, "-3.4028235e+38"),+ (-1.175_494_4e-38, "-1.1754944e-38"),+ (-0.333_333_3, "-0.3333333"),+ (-16_777_217.0, "-16777216"),+ (-1e7, "-10000000"),+ (-1e16, "-10000000000000000"),+ (-100_000.0, "-100000"),+ (-0.0001, "-0.0001"),+ ];+ for (number, formatted) in floats {+ assert_eq!(ak_formatted(number), formatted);+ }+ let doubles: [(f64, &str); 10] = [+ (-1.0, "-1"),+ (-0.1, "-0.1"),+ (-1e300, "-1e+300"),+ (-1e-7, "-1e-7"),+ (-123_456_789.123, "-123456789.123"),+ (-1e21, "-1e+21"),+ (-1e22, "-1e+22"),+ (-0.0001, "-0.0001"),+ (-1e16, "-10000000000000000"),+ (-1e17, "-100000000000000000"),+ ];+ for (number, formatted) in doubles {+ assert_eq!(ak_formatted(number), formatted);+ }+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rsindex acc19d10794..c2c21d41829 100644--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs@@ -20,6 +20,7 @@ use libjs_rust::api::{to_well_formed, typed_array_byte_length,};+use crate::ak_format::ak_formatted;use crate::bindings::CallContext;use crate::bindings::interface::{Interface, Ref, create_dictionary_object, wrap};use crate::bindings::services::web_bindings_object_implements_interface;@@ -175,6 +176,81 @@ pub(crate) fn to_unsigned_long(vm: &Vm, value: Value) -> ThrowCompletionOr<u32>value.to_u32(vm)}+/// A JS value converted to an integer of the IDL type with [EnforceRange], whose bounds those are: steps 4 to 6 of+/// https://webidl.spec.whatwg.org/#abstract-opdef-converttoint, which throw the errors that WebIDL::convert_to_int()+/// of the C++ bindings throws.+fn to_integer_enforcing_range(vm: &Vm, value: Value, lower_bound: f64, upper_bound: f64) -> ThrowCompletionOr<f64> {+ // 4. Let x be ? ToNumber(V).+ // 5. If x is −0, then set x to +0.+ let x = value.to_double(vm)? + 0.0;++ // 6. If the conversion is to an IDL type associated with the [EnforceRange] extended attribute, then:+ // 1. If x is NaN, +∞, or −∞, then throw a TypeError.+ if !x.is_finite() {+ return vm.throw_completion(ErrorKind::TypeError, ErrorType::NumberIsNaNOrInfinity, &[]);+ }++ // 2. Set x to IntegerPart(x).+ let x = x.trunc() + 0.0;++ // 3. If x < lowerBound or x > upperBound, then throw a TypeError.+ if x < lower_bound || x > upper_bound {+ let message = format!(+ "Number '{}' is outside of allowed range of {} to {}",+ ak_formatted(x),+ ak_formatted(lower_bound),+ ak_formatted(upper_bound)+ );+ return vm.throw_completion_with_utf16_message(ErrorKind::TypeError, Utf16String::from_utf8(&message));+ }++ // 4. Return x.+ Ok(x)+}++/// The largest integer that a JS number represents unambiguously, the upper bound of a 64-bit integer type with+/// [EnforceRange].+const MAX_SAFE_INTEGER: f64 = 9_007_199_254_740_991.0;++/// A JS value converted to a long with [EnforceRange], https://webidl.spec.whatwg.org/#js-long+#[allow(+ clippy::cast_possible_truncation,+ reason = "the value is an integer within the bounds of the type"+)]+pub(crate) fn to_long_enforcing_range(vm: &Vm, value: Value) -> ThrowCompletionOr<i32> {+ Ok(to_integer_enforcing_range(vm, value, f64::from(i32::MIN), f64::from(i32::MAX))? as i32)+}++/// A JS value converted to an unsigned long with [EnforceRange], https://webidl.spec.whatwg.org/#js-unsigned-long+#[allow(+ clippy::cast_possible_truncation,+ clippy::cast_sign_loss,+ reason = "the value is an integer within the bounds of the type"+)]+pub(crate) fn to_unsigned_long_enforcing_range(vm: &Vm, value: Value) -> ThrowCompletionOr<u32> {+ Ok(to_integer_enforcing_range(vm, value, 0.0, f64::from(u32::MAX))? as u32)+}++/// A JS value converted to a long long with [EnforceRange], https://webidl.spec.whatwg.org/#js-long-long+#[allow(+ clippy::cast_possible_truncation,+ reason = "the value is an integer within the bounds of the type"+)]+pub(crate) fn to_long_long_enforcing_range(vm: &Vm, value: Value) -> ThrowCompletionOr<i64> {+ Ok(to_integer_enforcing_range(vm, value, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER)? as i64)+}++/// A JS value converted to an unsigned long long with [EnforceRange],+/// https://webidl.spec.whatwg.org/#js-unsigned-long-long+#[allow(+ clippy::cast_possible_truncation,+ clippy::cast_sign_loss,+ reason = "the value is an integer within the bounds of the type"+)]+pub(crate) fn to_unsigned_long_long_enforcing_range(vm: &Vm, value: Value) -> ThrowCompletionOr<u64> {+ Ok(to_integer_enforcing_range(vm, value, 0.0, MAX_SAFE_INTEGER)? as u64)+}+/// 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.///diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/canvas_path.rs b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_path.rsindex d6152cd445b..2e98711ff4d 100644--- a/Libraries/LibWeb/Bindings/Rust/src/html/canvas_path.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_path.rs@@ -11,10 +11,10 @@//! quadraticCurveTo(), arc() and ellipse() are floats, and those of the rest are doubles that become floats where//! they become points.-use core::fmt::LowerExp;-use libgfx_rust::{AffineTransform, FloatPoint, FloatSize};+use crate::ak_format::ak_formatted;+use crate::geometry::dom_point_read_only::DOMPointInit;/// The union (unrestricted double or DOMPointInit) of HTML/Canvas/CanvasPath.idl, a radius of roundRect(), whose@@ -171,42 +171,6 @@ impl From<CanvasPathError> for crate::bindings::Exception {}}-/// The number as AK's formatter writes it for "{}", which the messages of the C++ had: the shortest digits that-/// read back as the number, in the notation of Number::toString() of ECMAScript.-fn ak_formatted(number: impl LowerExp) -> String {- let scientific = format!("{number:e}");- let (sign, scientific) = match scientific.strip_prefix('-') {- Some(magnitude) => ("-", magnitude),- None => ("", scientific.as_str()),- };- let (mantissa, exponent) = scientific- .split_once('e')- .expect("a number in scientific notation has an exponent");- let exponent: i32 = exponent.parse().expect("the exponent is an integer");- let digits: String = mantissa.chars().filter(|character| *character != '.').collect();- let digit_count = i32::try_from(digits.len()).expect("a number has few digits");- let zeros = |count: i32| "0".repeat(usize::try_from(count).expect("the count is not negative"));-- let unsigned = if !(-6..=20).contains(&exponent) {- let (first, rest) = digits.split_at(1);- let fraction = if rest.is_empty() {- String::new()- } else {- format!(".{rest}")- };- let exponent_sign = if exponent < 0 { '-' } else { '+' };- format!("{first}{fraction}e{exponent_sign}{}", exponent.unsigned_abs())- } else if exponent < 0 {- format!("0.{}{digits}", zeros(-exponent - 1))- } else if digit_count <= exponent + 1 {- format!("{digits}{}", zeros(exponent + 1 - digit_count))- } else {- let (integer, fraction) = digits.split_at(usize::try_from(exponent + 1).expect("the exponent is not negative"));- format!("{integer}.{fraction}")- };- format!("{sign}{unsigned}")-}-fn point(x: f32, y: f32) -> FloatPoint {FloatPoint { x, y }}@@ -754,8 +718,8 @@ pub(crate) fn round_rect(#[cfg(test)]mod tests {use super::{- CanvasPathError, PathSink, RoundRectRadius, ak_formatted, arc, arc_to, close_path, ellipse, line_to, move_to,- rect, round_rect,+ CanvasPathError, PathSink, RoundRectRadius, arc, arc_to, close_path, ellipse, line_to, move_to, rect,+ round_rect,};use libgfx_rust::{AffineTransform, FloatPoint, FloatSize};@@ -852,45 +816,6 @@ mod tests {}}- #[test]- fn numbers_are_formatted_as_ak_formats_them() {- // NB: What AK's "{}" wrote for these numbers, which a C++ program printed.- let floats: [(f32, &str); 14] = [- (-1.0, "-1"),- (-0.5, "-0.5"),- (-0.1, "-0.1"),- (-1e30, "-1e+30"),- (-1e-7, "-1e-7"),- (-123_456_789.0, "-123456790"),- (-3.402_823_5e38, "-3.4028235e+38"),- (-1.175_494_4e-38, "-1.1754944e-38"),- (-0.333_333_3, "-0.3333333"),- (-16_777_217.0, "-16777216"),- (-1e7, "-10000000"),- (-1e16, "-10000000000000000"),- (-100_000.0, "-100000"),- (-0.0001, "-0.0001"),- ];- for (number, formatted) in floats {- assert_eq!(ak_formatted(number), formatted);- }- let doubles: [(f64, &str); 10] = [- (-1.0, "-1"),- (-0.1, "-0.1"),- (-1e300, "-1e+300"),- (-1e-7, "-1e-7"),- (-123_456_789.123, "-123456789.123"),- (-1e21, "-1e+21"),- (-1e22, "-1e+22"),- (-0.0001, "-0.0001"),- (-1e16, "-10000000000000000"),- (-1e17, "-100000000000000000"),- ];- for (number, formatted) in doubles {- assert_eq!(ak_formatted(number), formatted);- }- }-#[test]fn points_that_are_not_finite_are_ignored() {let mut path = RecordingPath::default();diff --git a/Libraries/LibWeb/Bindings/Rust/src/lib.rs b/Libraries/LibWeb/Bindings/Rust/src/lib.rsindex ebb0cdba843..c51bbcc43eb 100644--- a/Libraries/LibWeb/Bindings/Rust/src/lib.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/lib.rs@@ -22,6 +22,8 @@ mod rust_demangle;#[path = "../../../../RustPanic.rs"]mod rust_panic;+pub(crate) mod ak_format;+#[cfg(not(test))]#[allow(dead_code,diff --git a/Meta/Generators/libweb_bindings/rust_bindings.py b/Meta/Generators/libweb_bindings/rust_bindings.pyindex 2be1c4af103..4c9b8170461 100644--- a/Meta/Generators/libweb_bindings/rust_bindings.py+++ b/Meta/Generators/libweb_bindings/rust_bindings.py@@ -305,7 +305,7 @@ def write_parameter_conversions(parameter_what = f"the parameter {parameter.name} of {what}"if parameter.variadic:raise UnsupportedByRustBindings(f"{parameter_what} is variadic")- unsupported = set(parameter.extended_attributes) - {"AllowShared", "AllowResizable"}+ unsupported = set(parameter.extended_attributes) - {"AllowShared", "AllowResizable", "EnforceRange"}if unsupported:raise UnsupportedByRustBindings(f"{parameter_what} has the extended attributes {sorted(unsupported)}")name = rust_local_name(parameter.name)@@ -401,8 +401,9 @@ def write_rust_interface(ArrayBufferView, BufferSource, BufferSourceRules, CppInterface, EmptyDictionary, FromJs, ToJs, UsvString,implements_cpp_interface, record_to_js, rooted_sequence_to_js, sequence_from_js, sequence_to_js,to_array_buffer_view, to_boolean, to_buffer_source, to_cpp_interface, to_dom_string, to_double, 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,+ to_long, to_long_enforcing_range, to_long_long, to_long_long_enforcing_range, to_typed_array,+ to_unrestricted_double, to_unrestricted_float, to_unsigned_long, to_unsigned_long_enforcing_range,+ to_unsigned_long_long, to_unsigned_long_long_enforcing_range, to_usv_string,}};use crate::bindings::interface::{{Inherits, Interface, Ref, Wrapped, cell_class, construct_arguments, construct_wrapper, define_attribute,@@ -930,8 +931,9 @@ pub(crate) mod definitions {dictionary_member, dictionary_object, enumeration_value_to_js, implements_cpp_interface, iterator_method,record_to_js, rooted_sequence_to_js, sequence_from_iterable, sequence_from_js, sequence_to_js,throw_no_union_types_matched, to_array_buffer_view, to_boolean, to_buffer_source, to_cpp_interface,- to_dom_string, to_double, to_enumeration_value, 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,+ to_dom_string, to_double, to_enumeration_value, to_float, to_long, to_long_enforcing_range, to_long_long,+ to_long_long_enforcing_range, to_typed_array, to_unrestricted_double, to_unrestricted_float, to_unsigned_long,+ to_unsigned_long_enforcing_range, to_unsigned_long_long, to_unsigned_long_long_enforcing_range, to_usv_string,};use crate::bindings::interface::{Interface, Ref, create_dictionary_object, implementation_of, 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.pyindex 328631a3e0c..a441be57ff1 100644--- a/Meta/Generators/libweb_bindings/rust_to_idl_value.py+++ b/Meta/Generators/libweb_bindings/rust_to_idl_value.py@@ -67,6 +67,11 @@ def rust_to_idl_value(name of the parameter or member that the value is of, which the errors of some conversions name."""rust_type(idl_type, context, what)name = idl_type.name+ attributes = {**idl_type.extended_attributes, **parameter_attributes}+ if "EnforceRange" in attributes and (idl_type.nullable or name not in INTEGER_TYPES):+ raise UnsupportedByRustBindings(+ f"{what} has the type {idl_type} with [EnforceRange], which the Rust bindings only handle on integer types"+ )# https://webidl.spec.whatwg.org/#js-nullable-typeif idl_type.nullable:inner_type = idl_type.without_nullable()@@ -91,6 +96,8 @@ def rust_to_idl_value(if name == "boolean":return f"to_boolean({value})"if name in INTEGER_TYPES:+ if "EnforceRange" in attributes:+ return f"to_{name.replace(' ', '_')}_enforcing_range(vm, {value})"return f"to_{name.replace(' ', '_')}(vm, {value})"if name == "float":return f'to_float(vm, {value}, "{identifier}")'diff --git a/Meta/Generators/libweb_bindings/rust_types.py b/Meta/Generators/libweb_bindings/rust_types.pyindex 2c70d80a981..3b63d730fb0 100644--- a/Meta/Generators/libweb_bindings/rust_types.py+++ b/Meta/Generators/libweb_bindings/rust_types.py@@ -41,7 +41,7 @@ TYPED_ARRAY_NAMES = {}# The extended attributes of a type or a parameter that the Rust bindings handle.-SUPPORTED_TYPE_EXTENDED_ATTRIBUTES = {"AllowShared", "AllowResizable"}+SUPPORTED_TYPE_EXTENDED_ATTRIBUTES = {"AllowShared", "AllowResizable", "EnforceRange"}# The integer types, with the Rust type of their values.INTEGER_TYPES = {"long": "i32", "unsigned long": "u32", "long long": "i64", "unsigned long long": "u64"}