Truly independent web browser
LibJS: Compare string literal keys in the parser without a copy
Andreas Kling3c1bdbae147a
diff --git a/Libraries/LibJS/Rust/src/parser/escapes.rs b/Libraries/LibJS/Rust/src/parser/escapes.rsnew file mode 100644index 00000000000..f24faaa2c0c--- /dev/null+++ b/Libraries/LibJS/Rust/src/parser/escapes.rs@@ -0,0 +1,233 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The escape sequences of string literals and templates. The lexer only validates them, and their value gets worked+//! out when something needs it, one code unit at a time, into whatever the caller keeps it in.++use super::unit::Unit;++const fn ch(c: u8) -> u16 {+ c as u16+}++#[derive(Clone, Copy, PartialEq, Eq)]+pub enum EscapeMode {+ /// Tagged template literals: invalid escapes produce `undefined` cooked value.+ TaggedTemplate,+ /// String literals: invalid escapes emit syntax errors, legacy octals are tracked.+ StringLiteral,+}++/// Unified escape sequence processor for both string and template literals, which hands each code unit of the value to+/// `push`.+///+/// In `TaggedTemplate` mode, the result is true when an invalid escape is encountered (the cooked value becomes+/// `undefined`), and the code units up to it are all that were pushed.+#[inline]+pub fn decode_escape_sequences<U: Unit>(input: &[U], mode: EscapeMode, mut push: impl FnMut(u16)) -> bool {+ let at = |index: usize| input[index].code() as u16;+ let mut i = 0;++ const N: u16 = ch(b'n');+ const R: u16 = ch(b'r');+ const T: u16 = ch(b't');+ const B: u16 = ch(b'b');+ const F: u16 = ch(b'f');+ const V: u16 = ch(b'v');+ const ZERO: u16 = ch(b'0');+ const ONE: u16 = ch(b'1');+ const SEVEN: u16 = ch(b'7');+ const EIGHT: u16 = ch(b'8');+ const NINE: u16 = ch(b'9');+ const X: u16 = ch(b'x');+ const U: u16 = ch(b'u');+ const LF: u16 = ch(b'\n');+ const CR: u16 = ch(b'\r');+ const LS: u16 = 0x2028;+ const PS: u16 = 0x2029;++ while i < input.len() {+ if at(i) == b'\\' as u16 && i + 1 < input.len() {+ i += 1;+ match at(i) {+ N => push(ch(b'\n')),+ R => push(ch(b'\r')),+ T => push(ch(b'\t')),+ B => push(8),+ F => push(12),+ V => push(11),+ ZERO => {+ if mode == EscapeMode::TaggedTemplate {+ if i + 1 < input.len() && (is_octal_char(at(i + 1)) || at(i + 1) == EIGHT || at(i + 1) == NINE)+ {+ return true;+ }+ push(0);+ } else if i + 1 < input.len() && is_octal_char(at(i + 1)) {+ let (val, consumed) = parse_octal_escape(input, i);+ push(val);+ i += consumed;+ } else {+ push(0);+ }+ }+ ONE..=SEVEN => {+ if mode == EscapeMode::TaggedTemplate {+ return true;+ }+ let (val, consumed) = parse_octal_escape(input, i);+ push(val);+ i += consumed;+ }+ EIGHT | NINE => {+ if mode == EscapeMode::TaggedTemplate {+ return true;+ }+ push(at(i));+ }+ X => {+ if let Some((advance, ch)) = parse_hex_escape(input, i) {+ push(ch);+ i += advance;+ } else if mode == EscapeMode::TaggedTemplate {+ return true;+ } else {+ push(at(i));+ }+ }+ U => {+ if let Some((advance, code_point)) = parse_unicode_escape(input, i) {+ if code_point > 0xFFFF {+ let adjusted = code_point - 0x10000;+ push((0xD800 | ((adjusted >> 10) & 0x3FF)) as u16);+ push((0xDC00 | (adjusted & 0x3FF)) as u16);+ } else {+ push(code_point as u16);+ }+ i += advance;+ } else if mode == EscapeMode::TaggedTemplate {+ return true;+ } else {+ push(at(i));+ }+ }+ LF => { /* line continuation */ }+ CR => {+ if i + 1 < input.len() && at(i + 1) == LF {+ i += 1;+ }+ }+ LS | PS => { /* skip LS/PS */ }+ c => push(c),+ }+ } else if at(i) == ch(b'\r') {+ // Normalize \r\n and bare \r to \n per spec (12.9.6).+ push(ch(b'\n'));+ if i + 1 < input.len() && at(i + 1) == ch(b'\n') {+ i += 1;+ }+ } else {+ push(at(i));+ }+ i += 1;+ }+ false+}++/// Whether the value of a string literal, from the text between its quotes, is `text`, which is ASCII.+pub fn string_literal_equals<U: Unit>(units: &[U], text: &str) -> bool {+ debug_assert!(text.is_ascii());+ let text = text.as_bytes();+ if !units.iter().any(|unit| unit.code() == u32::from(b'\\')) {+ return units.len() == text.len()+ && units+ .iter()+ .zip(text)+ .all(|(unit, &byte)| unit.code() == u32::from(byte));+ }+ let mut length = 0;+ let mut is_equal = true;+ decode_escape_sequences(units, EscapeMode::StringLiteral, |unit| {+ is_equal &= text.get(length).is_some_and(|&byte| u16::from(byte) == unit);+ length += 1;+ });+ is_equal && length == text.len()+}++fn hex_digit(c: u16) -> Option<u16> {+ match c {+ 0x30..=0x39 => Some(c - 0x30),+ 0x41..=0x46 => Some(c - 0x41 + 10),+ 0x61..=0x66 => Some(c - 0x61 + 10),+ _ => None,+ }+}++fn is_octal_char(c: u16) -> bool {+ c >= ch(b'0') && c <= ch(b'7')+}++fn parse_octal_escape<U: Unit>(inner: &[U], i: usize) -> (u16, usize) {+ let at = |index: usize| inner[index].code() as u16;+ let first = (at(i) - ch(b'0')) as u32;+ let mut value = first;+ let mut consumed = 0;++ if i + 1 < inner.len() && is_octal_char(at(i + 1)) {+ value = value * 8 + (at(i + 1) - ch(b'0')) as u32;+ consumed = 1;++ if i + 2 < inner.len() && is_octal_char(at(i + 2)) && first <= 3 {+ value = value * 8 + (at(i + 2) - ch(b'0')) as u32;+ consumed = 2;+ }+ }+ (value as u16, consumed)+}++fn parse_hex_escape<U: Unit>(raw: &[U], i: usize) -> Option<(usize, u16)> {+ let at = |index: usize| raw[index].code() as u16;+ if i + 2 >= raw.len() {+ return None;+ }+ let high = hex_digit(at(i + 1))?;+ let low = hex_digit(at(i + 2))?;+ Some((2, high * 16 + low))+}++fn parse_unicode_escape<U: Unit>(raw: &[U], i: usize) -> Option<(usize, u32)> {+ let at = |index: usize| raw[index].code() as u16;+ if i + 1 >= raw.len() {+ return None;+ }+ if at(i + 1) == ch(b'{') {+ let mut j = i + 2;+ let mut value: u32 = 0;+ let mut digits = 0;+ while j < raw.len() && at(j) != ch(b'}') {+ let d = hex_digit(at(j))? as u32;+ value = value * 16 + d;+ if value > 0x10FFFF {+ return None;+ }+ digits += 1;+ j += 1;+ }+ if j >= raw.len() || digits == 0 {+ return None;+ }+ Some((j - i, value))+ } else {+ if i + 4 >= raw.len() {+ return None;+ }+ let d0 = hex_digit(at(i + 1))? as u32;+ let d1 = hex_digit(at(i + 2))? as u32;+ let d2 = hex_digit(at(i + 3))? as u32;+ let d3 = hex_digit(at(i + 4))? as u32;+ Some((4, (d0 << 12) | (d1 << 8) | (d2 << 4) | d3))+ }+}diff --git a/Libraries/LibJS/Rust/src/parser/expr.rs b/Libraries/LibJS/Rust/src/parser/expr.rsindex a49b9d86acc..b6eb7d579e1 100644--- a/Libraries/LibJS/Rust/src/parser/expr.rs+++ b/Libraries/LibJS/Rust/src/parser/expr.rs@@ -1109,7 +1109,7 @@ impl<'a: 'k, 'k, U: Unit> Parser<'a, 'k, U> {// NB: The name of the property is the value of the string, which escape sequences spell out as well.let start = self.ast.pos[key as usize] as usize + 1;let units = self.source_view(start, key_end as usize - 1);- super::literals::string_literal_text(units).view() == "__proto__"+ super::escapes::string_literal_equals(units, "__proto__")}_ => false,}diff --git a/Libraries/LibJS/Rust/src/parser/lexer.rs b/Libraries/LibJS/Rust/src/parser/lexer.rsindex 60e3703c479..5dbcf5b3e02 100644--- a/Libraries/LibJS/Rust/src/parser/lexer.rs+++ b/Libraries/LibJS/Rust/src/parser/lexer.rs@@ -11,7 +11,6 @@use super::base::Parser;use super::token::*;use super::unit::*;-use crate::utf16::Utf16View;const fn keyword_kinds() -> [T; 36] {let mut kinds = [T::Eof; 36];@@ -59,10 +58,10 @@ impl<'a: 'k, 'k, U: Unit> Parser<'a, 'k, U> {}/// The source text from `start` up to `end`.- pub(crate) fn source_view(&self, start: usize, end: usize) -> Utf16View<'_> {+ pub(crate) fn source_view(&self, start: usize, end: usize) -> &[U] {debug_assert!(start <= end && end <= self.len as usize);// SAFETY: The range is within the source.- U::view(unsafe { ak::slice_from_raw_parts(self.src.add(start), end - start) })+ unsafe { ak::slice_from_raw_parts(self.src.add(start), end - start) }}#[inline(always)]diff --git a/Libraries/LibJS/Rust/src/parser/literals.rs b/Libraries/LibJS/Rust/src/parser/literals.rsindex c621bba445e..3cc5bee54ea 100644--- a/Libraries/LibJS/Rust/src/parser/literals.rs+++ b/Libraries/LibJS/Rust/src/parser/literals.rs@@ -7,6 +7,8 @@//! Turning the source text of literals into their values. The lexer only validates literals, and a value gets computed//! when something needs it.+pub use super::escapes::EscapeMode;+use super::escapes::decode_escape_sequences;use crate::utf16::Utf16View;use ak::Utf16String;@@ -14,14 +16,6 @@ const fn ch(c: u8) -> u16 {c as u16}-#[derive(Clone, Copy, PartialEq, Eq)]-pub enum EscapeMode {- /// Tagged template literals: invalid escapes produce `undefined` cooked value.- TaggedTemplate,- /// String literals: invalid escapes emit syntax errors, legacy octals are tracked.- StringLiteral,-}-pub(crate) struct EscapeResult {pub(crate) value: Utf16String,/// Tagged template encountered an invalid escape.@@ -63,214 +57,18 @@ pub(crate) fn string_literal_text(units: Utf16View<'_>) -> StringLiteralText<'_>}}-/// Unified escape sequence processor for both string and template literals.-///-/// In `TaggedTemplate` mode, `failed` is true when an invalid escape is-/// encountered (the cooked value becomes `undefined`).+/// The value of the text of a string literal or a template, see [`decode_escape_sequences()`].pub(crate) fn process_escape_sequences_impl(input: Utf16View<'_>, mode: EscapeMode) -> EscapeResult {let mut result = Vec::with_capacity(input.length_in_code_units());- let mut i = 0;-- const N: u16 = ch(b'n');- const R: u16 = ch(b'r');- const T: u16 = ch(b't');- const B: u16 = ch(b'b');- const F: u16 = ch(b'f');- const V: u16 = ch(b'v');- const ZERO: u16 = ch(b'0');- const ONE: u16 = ch(b'1');- const SEVEN: u16 = ch(b'7');- const EIGHT: u16 = ch(b'8');- const NINE: u16 = ch(b'9');- const X: u16 = ch(b'x');- const U: u16 = ch(b'u');- const LF: u16 = ch(b'\n');- const CR: u16 = ch(b'\r');- const LS: u16 = 0x2028;- const PS: u16 = 0x2029;-- while i < input.length_in_code_units() {- if input.code_unit_at(i) == b'\\' as u16 && i + 1 < input.length_in_code_units() {- i += 1;- match input.code_unit_at(i) {- N => result.push(ch(b'\n')),- R => result.push(ch(b'\r')),- T => result.push(ch(b'\t')),- B => result.push(8),- F => result.push(12),- V => result.push(11),- ZERO => {- if mode == EscapeMode::TaggedTemplate {- if i + 1 < input.length_in_code_units()- && (is_octal_char(input.code_unit_at(i + 1))- || input.code_unit_at(i + 1) == EIGHT- || input.code_unit_at(i + 1) == NINE)- {- return EscapeResult {- value: Utf16String::from_utf16(&result),- failed: true,- };- }- result.push(0);- } else if i + 1 < input.length_in_code_units() && is_octal_char(input.code_unit_at(i + 1)) {- let (val, consumed) = parse_octal_escape(input, i);- result.push(val);- i += consumed;- } else {- result.push(0);- }- }- ONE..=SEVEN => {- if mode == EscapeMode::TaggedTemplate {- return EscapeResult {- value: Utf16String::from_utf16(&result),- failed: true,- };- }- let (val, consumed) = parse_octal_escape(input, i);- result.push(val);- i += consumed;- }- EIGHT | NINE => {- if mode == EscapeMode::TaggedTemplate {- return EscapeResult {- value: Utf16String::from_utf16(&result),- failed: true,- };- }- result.push(input.code_unit_at(i));- }- X => {- if let Some((advance, ch)) = parse_hex_escape(input, i) {- result.push(ch);- i += advance;- } else if mode == EscapeMode::TaggedTemplate {- return EscapeResult {- value: Utf16String::from_utf16(&result),- failed: true,- };- } else {- result.push(input.code_unit_at(i));- }- }- U => {- if let Some((advance, code_point)) = parse_unicode_escape(input, i) {- push_code_point(&mut result, code_point);- i += advance;- } else if mode == EscapeMode::TaggedTemplate {- return EscapeResult {- value: Utf16String::from_utf16(&result),- failed: true,- };- } else {- result.push(input.code_unit_at(i));- }- }- LF => { /* line continuation */ }- CR => {- if i + 1 < input.length_in_code_units() && input.code_unit_at(i + 1) == LF {- i += 1;- }- }- LS | PS => { /* skip LS/PS */ }- c => result.push(c),- }- } else if input.code_unit_at(i) == ch(b'\r') {- // Normalize \r\n and bare \r to \n per spec (12.9.6).- result.push(ch(b'\n'));- if i + 1 < input.length_in_code_units() && input.code_unit_at(i + 1) == ch(b'\n') {- i += 1;- }- } else {- result.push(input.code_unit_at(i));+ let failed = match input {+ Utf16View::Ascii(units) | Utf16View::Latin1(units) => {+ decode_escape_sequences(units, mode, |unit| result.push(unit))}- i += 1;- }+ Utf16View::Utf16(units) => decode_escape_sequences(units, mode, |unit| result.push(unit)),+ };EscapeResult {value: Utf16String::from_utf16(&result),- failed: false,- }-}--fn hex_digit(c: u16) -> Option<u16> {- match c {- 0x30..=0x39 => Some(c - 0x30),- 0x41..=0x46 => Some(c - 0x41 + 10),- 0x61..=0x66 => Some(c - 0x61 + 10),- _ => None,- }-}--fn is_octal_char(c: u16) -> bool {- c >= ch(b'0') && c <= ch(b'7')-}--fn parse_octal_escape(inner: Utf16View<'_>, i: usize) -> (u16, usize) {- let first = (inner.code_unit_at(i) - ch(b'0')) as u32;- let mut value = first;- let mut consumed = 0;-- if i + 1 < inner.length_in_code_units() && is_octal_char(inner.code_unit_at(i + 1)) {- value = value * 8 + (inner.code_unit_at(i + 1) - ch(b'0')) as u32;- consumed = 1;-- if i + 2 < inner.length_in_code_units() && is_octal_char(inner.code_unit_at(i + 2)) && first <= 3 {- value = value * 8 + (inner.code_unit_at(i + 2) - ch(b'0')) as u32;- consumed = 2;- }- }- (value as u16, consumed)-}--fn parse_hex_escape(raw: Utf16View<'_>, i: usize) -> Option<(usize, u16)> {- if i + 2 >= raw.length_in_code_units() {- return None;- }- let high = hex_digit(raw.code_unit_at(i + 1))?;- let low = hex_digit(raw.code_unit_at(i + 2))?;- Some((2, high * 16 + low))-}--fn parse_unicode_escape(raw: Utf16View<'_>, i: usize) -> Option<(usize, u32)> {- if i + 1 >= raw.length_in_code_units() {- return None;- }- if raw.code_unit_at(i + 1) == ch(b'{') {- let mut j = i + 2;- let mut value: u32 = 0;- let mut digits = 0;- while j < raw.length_in_code_units() && raw.code_unit_at(j) != ch(b'}') {- let d = hex_digit(raw.code_unit_at(j))? as u32;- value = value * 16 + d;- if value > 0x10FFFF {- return None;- }- digits += 1;- j += 1;- }- if j >= raw.length_in_code_units() || digits == 0 {- return None;- }- Some((j - i, value))- } else {- if i + 4 >= raw.length_in_code_units() {- return None;- }- let d0 = hex_digit(raw.code_unit_at(i + 1))? as u32;- let d1 = hex_digit(raw.code_unit_at(i + 2))? as u32;- let d2 = hex_digit(raw.code_unit_at(i + 3))? as u32;- let d3 = hex_digit(raw.code_unit_at(i + 4))? as u32;- Some((4, (d0 << 12) | (d1 << 8) | (d2 << 4) | d3))- }-}--fn push_code_point(result: &mut Vec<u16>, code_point: u32) {- if code_point > 0xFFFF {- let adjusted = code_point - 0x10000;- result.push((0xD800 | ((adjusted >> 10) & 0x3FF)) as u16);- result.push((0xDC00 | (adjusted & 0x3FF)) as u16);- } else {- result.push(code_point as u16);+ failed,}}diff --git a/Libraries/LibJS/Rust/src/parser/mod.rs b/Libraries/LibJS/Rust/src/parser/mod.rsindex a7549a9e728..643150a056a 100644--- a/Libraries/LibJS/Rust/src/parser/mod.rs+++ b/Libraries/LibJS/Rust/src/parser/mod.rs@@ -15,6 +15,7 @@pub(crate) mod base;pub(crate) mod columns;mod enclosing;+pub(crate) mod escapes;pub(crate) mod expr;mod intern;mod kept;diff --git a/Libraries/LibJS/Rust/src/parser/stmt.rs b/Libraries/LibJS/Rust/src/parser/stmt.rsindex 300dbc99bb4..35d4de46daa 100644--- a/Libraries/LibJS/Rust/src/parser/stmt.rs+++ b/Libraries/LibJS/Rust/src/parser/stmt.rs@@ -1465,7 +1465,7 @@ impl<'a: 'k, 'k, U: Unit> Parser<'a, 'k, U> {// NB: The name of the property is the value of the string, which escape sequences spell out as well.let start = self.ast.pos[key as usize] as usize + 1;let units = self.source_view(start, self.ast.a[key as usize] as usize - 1);- super::literals::string_literal_text(units).view() == text+ super::escapes::string_literal_equals(units, text)}_ => false,}diff --git a/Libraries/LibJS/Rust/src/parser/unit.rs b/Libraries/LibJS/Rust/src/parser/unit.rsindex c23e6db0903..7a8bf1b9027 100644--- a/Libraries/LibJS/Rust/src/parser/unit.rs+++ b/Libraries/LibJS/Rust/src/parser/unit.rs@@ -12,14 +12,11 @@//!//! The source must be followed by at least 64 units of zero padding, so blocks may read past its end.-use crate::utf16::Utf16View;-pub trait Unit: Copy + Eq + 'static {const WIDE: bool;fn code(self) -> u32;/// Loads a block of units as bytes.unsafe fn load(p: *const Self) -> Block;- fn view(units: &[Self]) -> Utf16View<'_>;}impl Unit for u8 {@@ -32,10 +29,6 @@ impl Unit for u8 {unsafe fn load(p: *const u8) -> Block {unsafe { block::load_narrow(p) }}- #[inline(always)]- fn view(units: &[u8]) -> Utf16View<'_> {- Utf16View::Latin1(units)- }}impl Unit for u16 {@@ -48,10 +41,6 @@ impl Unit for u16 {unsafe fn load(p: *const u16) -> Block {unsafe { block::load_wide(p) }}- #[inline(always)]- fn view(units: &[u16]) -> Utf16View<'_> {- Utf16View::Utf16(units)- }}#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]