Truly independent web browser
LibJS: Fold string constants with the runtime's string conversions
Shannon Booth07caacc15b8d
diff --git a/Libraries/LibJS/Rust/src/bytecode/codegen.rs b/Libraries/LibJS/Rust/src/bytecode/codegen.rsindex c01a5004994..b9b06c62623 100644--- a/Libraries/LibJS/Rust/src/bytecode/codegen.rs+++ b/Libraries/LibJS/Rust/src/bytecode/codegen.rs@@ -10063,7 +10063,7 @@ fn try_constant_loosely_equals(lhs: &ConstantValue, rhs: &ConstantValue) -> Opti// String == Number → compare number to ToNumber(string).match (lhs, rhs) {(ConstantValue::Number(n), ConstantValue::String(s)) | (ConstantValue::String(s), ConstantValue::Number(n)) => {- Some(*n == string_to_number(s))+ Some(*n == crate::host::string_to_number(&s.0))}// BigInt == Number or Number == BigInt: compare mathematical values.(ConstantValue::BigInt(b), ConstantValue::Number(n)) | (ConstantValue::Number(n), ConstantValue::BigInt(b)) => {@@ -10088,7 +10088,7 @@ fn try_constant_loosely_equals(lhs: &ConstantValue, rhs: &ConstantValue) -> Opti// BigInt == String or String == BigInt: parse string as BigInt per StringToBigInt.// If the string cannot be parsed, the result is false (not equal).(ConstantValue::BigInt(b), ConstantValue::String(s)) | (ConstantValue::String(s), ConstantValue::BigInt(b)) => {- match string_to_bigint(s) {+ match crate::host::string_to_bigint(&s.0) {Some(s_bi) => {let bi = parse_bigint(b)?;Some(bi == s_bi)@@ -10100,87 +10100,6 @@ fn try_constant_loosely_equals(lhs: &ConstantValue, rhs: &ConstantValue) -> Opti}}-#[derive(Clone, Copy)]-enum NonDecimalRadix {- Binary,- Octal,- Hexadecimal,-}--impl NonDecimalRadix {- fn as_u32(self) -> u32 {- match self {- Self::Binary => 2,- Self::Octal => 8,- Self::Hexadecimal => 16,- }- }-}--fn is_utf16_whitespace(code_unit: u16) -> bool {- char::from_u32(code_unit.into()).is_some_and(char::is_whitespace)-}--fn trim_utf16_whitespace(text: &[u16]) -> &[u16] {- let mut start = 0;- while start < text.len() && is_utf16_whitespace(text[start]) {- start += 1;- }-- let mut end = text.len();- while end > start && is_utf16_whitespace(text[end - 1]) {- end -= 1;- }-- &text[start..end]-}--fn strip_non_decimal_prefix_utf16(text: &[u16]) -> Option<(NonDecimalRadix, &[u16])> {- if text.len() < 3 || text[0] != b'0'.into() {- return None;- }-- let radix = match text[1] {- code_unit if code_unit == b'b'.into() || code_unit == b'B'.into() => NonDecimalRadix::Binary,- code_unit if code_unit == b'o'.into() || code_unit == b'O'.into() => NonDecimalRadix::Octal,- code_unit if code_unit == b'x'.into() || code_unit == b'X'.into() => NonDecimalRadix::Hexadecimal,- _ => return None,- };-- Some((radix, &text[2..]))-}--fn is_valid_non_decimal_digits_utf16(text: &[u16], radix: NonDecimalRadix) -> bool {- // Keep this JS-specific precheck even though parse_bytes() also validates:- // num-bigint accepts forms that are invalid in JS StringToNumber/StringToBigInt- // non-decimal parsing (for example a leading '+' and '_' separators).- // strip_non_decimal_prefix_utf16() guarantees that this suffix is non-empty.- debug_assert!(!text.is_empty());- match radix {- NonDecimalRadix::Binary => text- .iter()- .all(|&code_unit| code_unit == b'0'.into() || code_unit == b'1'.into()),- NonDecimalRadix::Octal => text- .iter()- .all(|&code_unit| (b'0'.into()..=b'7'.into()).contains(&code_unit)),- NonDecimalRadix::Hexadecimal => text.iter().all(|&code_unit| {- (b'0'.into()..=b'9'.into()).contains(&code_unit)- || (b'a'.into()..=b'f'.into()).contains(&code_unit)- || (b'A'.into()..=b'F'.into()).contains(&code_unit)- }),- }-}--fn ascii_code_units_to_bytes(text: &[u16]) -> Option<Vec<u8>> {- text.iter()- .map(|&code_unit| {- u8::try_from(code_unit)- .ok()- .and_then(|byte| byte.is_ascii().then_some(byte))- })- .collect()-}-fn ascii_code_units_to_string(text: &[u16]) -> Option<String> {text.iter().map(|&code_unit| {@@ -10191,66 +10110,10 @@ fn ascii_code_units_to_string(text: &[u16]) -> Option<String> {.collect()}-fn ascii_code_units_eq(text: &[u16], ascii: &[u8]) -> bool {- text.len() == ascii.len()- && text- .iter()- .zip(ascii)- .all(|(&code_unit, &byte)| code_unit == byte.into())-}--fn is_ascii_decimal_number_code_unit(code_unit: u16) -> bool {- (b'0'.into()..=b'9'.into()).contains(&code_unit)- || code_unit == b'.'.into()- || code_unit == b'e'.into()- || code_unit == b'E'.into()- || code_unit == b'+'.into()- || code_unit == b'-'.into()-}-fn bigint_literal_digits(literal: &Utf16String) -> &[u16] {literal.0.strip_suffix(&[b'n'.into()]).unwrap_or(literal.0.as_slice())}-/// Implements StringToBigInt per https://tc39.es/ecma262/#sec-stringtobigint.-/// Trims whitespace, handles optional sign (decimal only), and handles-/// 0b/0o/0x prefixes. Returns None if the string is not a valid-/// StringIntegerLiteral.-fn string_to_bigint(s: &Utf16String) -> Option<BigInt> {- use num_bigint::BigInt;- let s_trimmed = trim_utf16_whitespace(&s.0);- if s_trimmed.is_empty() {- return Some(BigInt::from(0));- }- // Check for non-decimal prefixes (no sign allowed).- if let Some((radix, rest)) = strip_non_decimal_prefix_utf16(s_trimmed) {- if !is_valid_non_decimal_digits_utf16(rest, radix) {- return None;- }- // Convert validated suffix digits using the parser.- let bytes = ascii_code_units_to_bytes(rest)?;- return BigInt::parse_bytes(&bytes, radix.as_u32());- }- // Decimal with optional sign. Only allow digits (no dots, no exponents).- let (is_negative, digits) = if let Some(rest) = s_trimmed.strip_prefix(&[b'-'.into()]) {- (true, rest)- } else if let Some(rest) = s_trimmed.strip_prefix(&[b'+'.into()]) {- (false, rest)- } else {- (false, s_trimmed)- };- if digits.is_empty()- || !digits- .iter()- .all(|code_unit| (b'0'.into()..=b'9'.into()).contains(code_unit))- {- return None;- }- let bytes = ascii_code_units_to_bytes(digits)?;- let bi = BigInt::parse_bytes(&bytes, 10)?;- Some(if is_negative { -bi } else { bi })-}-/// Constant-fold a binary operation on two BigInt operands.fn try_constant_fold_bigint_binary(generator: &mut Generator,@@ -10319,50 +10182,6 @@ fn try_constant_fold_bigint_binary(}}-/// Parse a non-decimal integer string via BigInt to f64, matching-/// UnsignedBigInteger::from_base() + to_double(). This avoids u64 overflow-/// for large literals like 0x10000000000000000.-fn bigint_digits_to_f64(digits: &[u16], radix: u32) -> f64 {- use num_bigint::BigUint;- let Some(bytes) = ascii_code_units_to_bytes(digits) else {- return f64::NAN;- };- match BigUint::parse_bytes(&bytes, radix) {- Some(n) => {- use num_traits::ToPrimitive;- n.to_f64().unwrap_or(f64::INFINITY)- }- None => f64::NAN,- }-}--// 7.1.4.1.1 StringToNumber ( str ), https://tc39.es/ecma262/#sec-stringtonumber-fn string_to_number(s: &Utf16String) -> f64 {- let trimmed = trim_utf16_whitespace(&s.0);- if trimmed.is_empty() {- return 0.0;- }- if ascii_code_units_eq(trimmed, b"Infinity") || ascii_code_units_eq(trimmed, b"+Infinity") {- return f64::INFINITY;- }- if ascii_code_units_eq(trimmed, b"-Infinity") {- return f64::NEG_INFINITY;- }- if let Some((radix, rest)) = strip_non_decimal_prefix_utf16(trimmed) {- if !is_valid_non_decimal_digits_utf16(rest, radix) {- return f64::NAN;- }- return bigint_digits_to_f64(rest, radix.as_u32());- }- if !trimmed.iter().copied().all(is_ascii_decimal_number_code_unit) {- return f64::NAN;- }- let Some(text) = ascii_code_units_to_string(trimmed) else {- return f64::NAN;- };- text.parse::<f64>().unwrap_or(f64::NAN)-}-/// Convert a constant value to a JS number for constant folding purposes.fn constant_to_number(val: &ConstantValue) -> Option<f64> {match val {@@ -10370,7 +10189,7 @@ fn constant_to_number(val: &ConstantValue) -> Option<f64> {ConstantValue::Boolean(b) => Some(if *b { 1.0 } else { 0.0 }),ConstantValue::Null => Some(0.0),ConstantValue::Undefined => Some(f64::NAN),- ConstantValue::String(s) => Some(string_to_number(s)),+ ConstantValue::String(s) => Some(crate::host::string_to_number(&s.0)),_ => None,}}@@ -10548,14 +10367,14 @@ fn try_constant_fold_binary(// using StringToBigInt, then compare the two BigInts.// If the string is not a valid StringIntegerLiteral,// the result is undefined (= false for all comparisons).- (ConstantValue::BigInt(b), ConstantValue::String(s)) => match string_to_bigint(s) {+ (ConstantValue::BigInt(b), ConstantValue::String(s)) => match crate::host::string_to_bigint(&s.0) {Some(rhs_bi) => {let lhs_bi = parse_bigint(b)?;Some(Some(lhs_bi.cmp(&rhs_bi)))}None => Some(None),},- (ConstantValue::String(s), ConstantValue::BigInt(b)) => match string_to_bigint(s) {+ (ConstantValue::String(s), ConstantValue::BigInt(b)) => match crate::host::string_to_bigint(&s.0) {Some(lhs_bi) => {let rhs_bi = parse_bigint(b)?;Some(Some(lhs_bi.cmp(&rhs_bi)))diff --git a/Libraries/LibJS/Rust/src/frontend_host.rs b/Libraries/LibJS/Rust/src/frontend_host.rsindex a39f28e9e4c..db55c75d383 100644--- a/Libraries/LibJS/Rust/src/frontend_host.rs+++ b/Libraries/LibJS/Rust/src/frontend_host.rs@@ -8,6 +8,7 @@use libregex_rust::ast::Flags;use libregex_rust::regex::Regex;+use num_bigint::BigInt;use crate::runtime::regexp_object::parse_regex_pattern;use crate::runtime::value::number_to_string;@@ -45,6 +46,16 @@ pub fn validate_regex(pattern: &[u16], flags: &[u16]) -> Result<(), String> {Ok(())}+/// StringToNumber(str), which the frontend uses to fold operations on string constants.+pub fn string_to_number(string: &[u16]) -> f64 {+ value_conversions::string_to_number(string)+}++/// StringToBigInt(str), which the frontend uses to fold operations on a string and a BigInt constant.+pub fn string_to_bigint(string: &[u16]) -> Option<BigInt> {+ value_conversions::string_to_bigint(string)+}+/// Number::exponentiate(base, exponent), which the frontend uses to fold `**`.pub fn exponentiate(base: f64, exponent: f64) -> f64 {value_conversions::exp_double(base, exponent)diff --git a/Libraries/LibJS/Rust/src/host.rs b/Libraries/LibJS/Rust/src/host.rsindex dbc3ab6b79c..fdf845e0650 100644--- a/Libraries/LibJS/Rust/src/host.rs+++ b/Libraries/LibJS/Rust/src/host.rs@@ -9,6 +9,8 @@//! The runtime implements them in frontend_host.rs. The cargo test binary, which//! builds the frontend without the runtime, uses the stand-ins in test_host.rs.+use num_bigint::BigInt;+use crate::ast::Utf16String;#[cfg(not(test))]@@ -28,6 +30,16 @@ pub fn validate_regex(pattern: &[u16], flags: &[u16]) -> Result<(), Utf16String>implementation::validate_regex(pattern, flags).map_err(|message| Utf16String(message.encode_utf16().collect()))}+/// StringToNumber(str), which the host implements.+pub fn string_to_number(string: &[u16]) -> f64 {+ implementation::string_to_number(string)+}++/// StringToBigInt(str), which the host implements. Returns None where the spec returns undefined.+pub fn string_to_bigint(string: &[u16]) -> Option<BigInt> {+ implementation::string_to_bigint(string)+}+/// Number::exponentiate(base, exponent), which the host implements.pub fn exponentiate(base: f64, exponent: f64) -> f64 {implementation::exponentiate(base, exponent)diff --git a/Libraries/LibJS/Rust/src/test_host.rs b/Libraries/LibJS/Rust/src/test_host.rsindex 6f6e15ab602..098cb932586 100644--- a/Libraries/LibJS/Rust/src/test_host.rs+++ b/Libraries/LibJS/Rust/src/test_host.rs@@ -12,6 +12,8 @@ use std::collections::HashMap;use std::sync::Mutex;use std::sync::atomic::AtomicU32;+use num_bigint::BigInt;+pub fn validate_regex(_pattern: &[u16], _flags: &[u16]) -> Result<(), String> {Ok(())}@@ -25,6 +27,14 @@ pub fn number_to_utf16(value: f64) -> Vec<u16> {text.encode_utf16().collect()}+pub fn string_to_number(_string: &[u16]) -> f64 {+ unimplemented!("no cargo test folds constants")+}++pub fn string_to_bigint(_string: &[u16]) -> Option<BigInt> {+ unimplemented!("no cargo test folds constants")+}+pub fn exponentiate(_base: f64, _exponent: f64) -> f64 {unimplemented!("no cargo test folds constants")}diff --git a/Tests/LibJS/Runtime/builtins/BigInt/bigint-basic.js b/Tests/LibJS/Runtime/builtins/BigInt/bigint-basic.jsindex b8fe03ff91f..751c0ed5435 100644--- a/Tests/LibJS/Runtime/builtins/BigInt/bigint-basic.js+++ b/Tests/LibJS/Runtime/builtins/BigInt/bigint-basic.js@@ -108,6 +108,9 @@ describe("correct behavior", () => {expect(1n == "0b10").toBeFalse();expect(1n == "0o2").toBeFalse();expect(1n == "0x2").toBeFalse();++ expect(1n == "1").toBeTrue();+ expect(1n == "\u00851").toBeFalse();});test("strong equality operators", () => {diff --git a/Tests/LibJS/Runtime/to-number-basic.js b/Tests/LibJS/Runtime/to-number-basic.jsindex 45095378394..6e753ed70b6 100644--- a/Tests/LibJS/Runtime/to-number-basic.js+++ b/Tests/LibJS/Runtime/to-number-basic.js@@ -65,6 +65,12 @@ test("space and space-like escapes", () => {expect(+" \r \t \n ").toBe(0);expect(+" \n \t Infinity \r ").toBe(Infinity);expect(+"\r \n1.23 \t\t\t \n").toBe(1.23);+ expect(+"1").toBe(1);+ expect(+"").toBe(0);+ expect("1" == 1).toBeTrue();+ expect("1" < 2).toBeTrue();+ expect(+"\u00851").toBeNaN();+ expect("\u00851" == 1).toBeFalse();});test("object literals", () => {