Truly independent web browser
LibJS: Add a lexer that scans blocks of code units
Andreas Klinge35f8920fcdc
diff --git a/Libraries/LibJS/Rust/src/parser/intern.rs b/Libraries/LibJS/Rust/src/parser/intern.rsnew file mode 100644index 00000000000..4e979194e6e--- /dev/null+++ b/Libraries/LibJS/Rust/src/parser/intern.rs@@ -0,0 +1,230 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Name interning. An identifier's bytes up to 16 long are its own key, so a lookup is one multiply and a compare of+//! two words, with no text compare. Names of one or two bytes, which is most of minified code, skip even that.++use super::token::{KEYWORDS, SPECIAL_NAMES};++pub const NONE: u32 = u32::MAX;++#[derive(Clone, Copy)]+#[repr(C, align(32))]+struct Row {+ k0: u64,+ k1: u64,+ id: u32,+}++#[derive(Clone, Copy)]+struct LongRow {+ hash: u64,+ id: u32,+}++pub struct Interner {+ short: Vec<u32>,+ rows: Vec<Row>,+ shift: u32,+ count: u32,+ long_rows: Vec<LongRow>,+ long_count: u32,+ /// Each name's text, in UTF-8.+ text: Vec<u8>,+ spans: Vec<(u32, u32)>,+}++#[inline(always)]+fn hash_key(k0: u64, k1: u64) -> u64 {+ (k0 ^ k1.rotate_left(29)).wrapping_mul(0x9E37_79B9_7F4A_7C15) ^ k1.wrapping_mul(0xC2B2_AE3D_27D4_EB4F)+}++fn hash_bytes(bytes: &[u8]) -> u64 {+ let mut h = bytes.len() as u64;+ let (chunks, remainder) = bytes.as_chunks::<8>();+ for chunk in chunks {+ h = (h ^ u64::from_le_bytes(*chunk)).wrapping_mul(0x9E37_79B9_7F4A_7C15);+ h ^= h >> 29;+ }+ for &b in remainder {+ h = (h ^ b as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15);+ }+ h ^ (h >> 32)+}++fn key_from_bytes(bytes: &[u8]) -> (u64, u64) {+ let mut buffer = [0u8; 16];+ buffer[..bytes.len()].copy_from_slice(bytes);+ (+ u64::from_le_bytes(buffer[..8].try_into().unwrap()),+ u64::from_le_bytes(buffer[8..].try_into().unwrap()),+ )+}++impl Interner {+ pub fn new(source_len: usize) -> Self {+ let wanted = (source_len / 16).clamp(1 << 10, 1 << 22).next_power_of_two();+ Self::with_tables(vec![NONE; 1 << 16], wanted, 1 << 10, source_len / 8)+ }++ fn with_tables(short: Vec<u32>, rows: usize, long_rows: usize, text_capacity: usize) -> Self {+ let mut interner = Self {+ short,+ rows: vec![Row { k0: 0, k1: 0, id: NONE }; rows],+ shift: 64 - rows.trailing_zeros(),+ count: 0,+ long_rows: vec![LongRow { hash: 0, id: NONE }; long_rows],+ long_count: 0,+ text: Vec::with_capacity(text_capacity),+ spans: Vec::with_capacity(rows / 2),+ };+ for (word, _) in KEYWORDS {+ interner.intern_bytes(word.as_bytes());+ }+ for word in SPECIAL_NAMES {+ interner.intern_bytes(word.as_bytes());+ }+ for pseudo in [".this", ".new.target", ".super", ".unbound"] {+ interner.intern_bytes(pseudo.as_bytes());+ }+ interner+ }++ /// An interner that gives the names of an earlier parse the ids they had, sized to stay around with a source of any+ /// size. `names` yields them in id order, and starts with the names that every interner starts with.+ pub fn with_names<'a>(names: impl ExactSizeIterator<Item = &'a [u8]>) -> Self {+ let rows = (names.len() * 2).next_power_of_two();+ let mut interner = Self::with_tables(Vec::new(), rows, 1 << 4, names.len() * 8);+ for (id, name) in names.enumerate() {+ let interned = interner.intern_bytes(name);+ debug_assert_eq!(interned as usize, id);+ }+ interner+ }++ pub fn len(&self) -> usize {+ self.spans.len()+ }++ pub fn text(&self, id: u32) -> &[u8] {+ let (start, len) = self.spans[id as usize];+ &self.text[start as usize..(start + len) as usize]+ }++ fn add_name(&mut self, bytes: &[u8]) -> u32 {+ let id = self.spans.len() as u32;+ self.spans.push((self.text.len() as u32, bytes.len() as u32));+ self.text.extend_from_slice(bytes);+ id+ }++ /// Interns a name of at most 16 bytes, given as its key.+ #[inline(always)]+ pub fn intern_key(&mut self, k0: u64, k1: u64, len: usize) -> u32 {+ if len <= 2 && !self.short.is_empty() {+ let id = self.short[k0 as usize];+ if id != NONE {+ return id;+ }+ return self.add_short(k0, len);+ }+ let mask = self.rows.len() - 1;+ let mut index = (hash_key(k0, k1) >> self.shift) as usize;+ loop {+ // SAFETY: The index is masked to the table.+ let row = unsafe { self.rows.get_unchecked(index) };+ // NB: The empty name has the key of an empty row.+ if row.id == NONE {+ return self.insert_key(k0, k1, len, index);+ }+ if row.k0 == k0 && row.k1 == k1 {+ return row.id;+ }+ index = (index + 1) & mask;+ }+ }++ #[cold]+ #[inline(never)]+ fn add_short(&mut self, k0: u64, len: usize) -> u32 {+ let bytes = k0.to_le_bytes();+ let id = self.add_name(&bytes[..len]);+ self.short[k0 as usize] = id;+ id+ }++ #[inline(never)]+ fn insert_key(&mut self, k0: u64, k1: u64, len: usize, index: usize) -> u32 {+ let mut bytes = [0u8; 16];+ bytes[..8].copy_from_slice(&k0.to_le_bytes());+ bytes[8..].copy_from_slice(&k1.to_le_bytes());+ let id = self.add_name(&bytes[..len]);+ self.rows[index] = Row { k0, k1, id };+ self.count += 1;+ if self.count as usize * 2 > self.rows.len() {+ self.grow();+ }+ id+ }++ #[cold]+ fn grow(&mut self) {+ let new_len = self.rows.len() * 2;+ let old = std::mem::replace(&mut self.rows, vec![Row { k0: 0, k1: 0, id: NONE }; new_len]);+ self.shift -= 1;+ let mask = new_len - 1;+ for row in old {+ if row.id == NONE {+ continue;+ }+ let mut index = (hash_key(row.k0, row.k1) >> self.shift) as usize;+ while self.rows[index].id != NONE {+ index = (index + 1) & mask;+ }+ self.rows[index] = row;+ }+ }++ /// Interns any name, given as UTF-8.+ pub fn intern_bytes(&mut self, bytes: &[u8]) -> u32 {+ if bytes.len() <= 16 {+ let (k0, k1) = key_from_bytes(bytes);+ return self.intern_key(k0, k1, bytes.len());+ }+ let hash = hash_bytes(bytes);+ let mut mask = self.long_rows.len() - 1;+ let mut index = hash as usize & mask;+ loop {+ let row = self.long_rows[index];+ if row.id == NONE {+ break;+ }+ if row.hash == hash && self.text(row.id) == bytes {+ return row.id;+ }+ index = (index + 1) & mask;+ }+ let id = self.add_name(bytes);+ self.long_rows[index] = LongRow { hash, id };+ self.long_count += 1;+ if self.long_count as usize * 2 > self.long_rows.len() {+ let new_len = self.long_rows.len() * 2;+ let old = std::mem::replace(&mut self.long_rows, vec![LongRow { hash: 0, id: NONE }; new_len]);+ mask = new_len - 1;+ for row in old {+ if row.id == NONE {+ continue;+ }+ let mut index = row.hash as usize & mask;+ while self.long_rows[index].id != NONE {+ index = (index + 1) & mask;+ }+ self.long_rows[index] = row;+ }+ }+ id+ }+}diff --git a/Libraries/LibJS/Rust/src/parser/lexer.rs b/Libraries/LibJS/Rust/src/parser/lexer.rsnew file mode 100644index 00000000000..0be03c5010f--- /dev/null+++ b/Libraries/LibJS/Rust/src/parser/lexer.rs@@ -0,0 +1,971 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The tokenizer. It runs on demand, one token ahead of the parser, because `/` and `}` mean different things depending+//! on where the parser is. No value is computed for numbers or strings here: a literal is validated and left in the+//! source, and only code that gets compiled reads it again.++use super::base::Parser;+use super::token::*;+use super::unit::*;++const fn keyword_kinds() -> [T; 36] {+ let mut kinds = [T::Eof; 36];+ let mut i = 0;+ while i < 36 {+ kinds[i] = KEYWORDS[i].1;+ i += 1;+ }+ kinds+}+static KEYWORD_KINDS: [T; 36] = keyword_kinds();++// https://tc39.es/ecma262/#prod-IdentifierStartChar+// IdentifierStartChar :: UnicodeIDStart | $ | _+pub fn is_id_start(c: u32) -> bool {+ if c < 128 {+ return (c as u8).is_ascii_alphabetic() || c == 0x24 || c == 0x5F;+ }+ libunicode_rust::character_types::code_point_has_identifier_start_property(c)+}++// https://tc39.es/ecma262/#prod-IdentifierPartChar+// IdentifierPartChar :: UnicodeIDContinue | $+pub fn is_id_continue(c: u32) -> bool {+ if c < 128 {+ return (c as u8).is_ascii_alphanumeric() || c == 0x24 || c == 0x5F;+ }+ matches!(c, 0x200C | 0x200D) || libunicode_rust::character_types::code_point_has_identifier_continue_property(c)+}++fn is_unicode_whitespace(c: u32) -> bool {+ matches!(c, 0xA0 | 0xFEFF | 0x1680 | 0x2000..=0x200A | 0x202F | 0x205F | 0x3000)+}++fn hex_value(c: u32) -> Option<u32> {+ char::from_u32(c)?.to_digit(16)+}++impl<U: Unit> Parser<'_, U> {+ /// The unit at `index`, which may be in the padding after the source.+ #[inline(always)]+ pub fn at(&self, index: usize) -> u32 {+ // SAFETY: The lexer never goes further than one block into the padding.+ unsafe { (*self.src.add(index)).code() }+ }++ #[inline(always)]+ fn block(&self, index: usize) -> Block {+ // SAFETY: As for at().+ unsafe { U::load(self.src.add(index)) }+ }++ #[inline(always)]+ pub(crate) fn next(&mut self) {+ self.prev_end = self.tok_end;+ self.prev_start = self.tok_start;+ self.lex();+ }++ #[inline(always)]+ fn token(&mut self, kind: T, end: usize) {+ self.tok = kind;+ self.tok_end = end as u32;+ self.pos = end as u32;+ }++ pub(crate) fn lex(&mut self) {+ let mut p = self.pos as usize;+ let mut newline = false;+ let c = loop {+ let c = self.at(p);+ match c {+ 0x20 | 0x09 | 0x0B | 0x0C => p += 1,+ 0x0A | 0x0D => {+ newline = true;+ p += 1;+ }+ 0x2F => {+ let d = self.at(p + 1);+ if d == 0x2F {+ p = self.skip_line_comment(p + 2);+ } else if d == 0x2A {+ match self.skip_block_comment(p + 2) {+ Some((end, had_newline)) => {+ p = end;+ newline |= had_newline;+ }+ None => {+ self.fail(self.len, "Unterminated multi-line comment");+ return;+ }+ }+ } else {+ break c;+ }+ }+ 0x3C if !self.module && self.at(p + 1) == 0x21 && self.at(p + 2) == 0x2D && self.at(p + 3) == 0x2D => {+ p = self.skip_line_comment(p + 4);+ }+ 0x2D if !self.module+ && (newline || self.tok_end == 0)+ && self.at(p + 1) == 0x2D+ && self.at(p + 2) == 0x3E =>+ {+ p = self.skip_line_comment(p + 3);+ }+ _ if c >= 0x80 => {+ if c == 0x2028 || c == 0x2029 {+ newline = true;+ p += 1;+ } else if is_unicode_whitespace(c) {+ p += 1;+ } else {+ break c;+ }+ }+ _ => break c,+ }+ };+ self.nl_before = newline;+ self.tok_start = p as u32;++ if c >= 0x80 {+ self.lex_identifier_slow(p, false);+ return;+ }+ match c as u8 {+ b'a'..=b'z' | b'A'..=b'Z' | b'_' | b'$' => self.lex_identifier(p),+ b'0'..=b'9' => self.lex_number(p),+ b'"' | b'\'' => self.lex_string(p, c as u8),+ b'`' => self.token(T::Backtick, p + 1),+ b'(' => self.token(T::LParen, p + 1),+ b')' => self.token(T::RParen, p + 1),+ b'{' => self.token(T::LBrace, p + 1),+ b'}' => self.token(T::RBrace, p + 1),+ b'[' => self.token(T::LBracket, p + 1),+ b']' => self.token(T::RBracket, p + 1),+ b';' => self.token(T::Semi, p + 1),+ b',' => self.token(T::Comma, p + 1),+ b':' => self.token(T::Colon, p + 1),+ b'~' => self.token(T::Tilde, p + 1),+ b'.' => {+ let d = self.at(p + 1);+ if (0x30..=0x39).contains(&d) {+ self.lex_number(p);+ } else if d == 0x2E && self.at(p + 2) == 0x2E {+ self.token(T::Ellipsis, p + 3);+ } else {+ self.token(T::Dot, p + 1);+ }+ }+ b'=' => {+ if self.at(p + 1) == 0x3D {+ if self.at(p + 2) == 0x3D {+ self.token(T::EqEqEq, p + 3);+ } else {+ self.token(T::EqEq, p + 2);+ }+ } else if self.at(p + 1) == 0x3E {+ self.token(T::Arrow, p + 2);+ } else {+ self.token(T::Assign, p + 1);+ }+ }+ b'!' => {+ if self.at(p + 1) == 0x3D {+ if self.at(p + 2) == 0x3D {+ self.token(T::NotEqEq, p + 3);+ } else {+ self.token(T::NotEq, p + 2);+ }+ } else {+ self.token(T::Not, p + 1);+ }+ }+ b'+' => match self.at(p + 1) {+ 0x2B => self.token(T::Inc, p + 2),+ 0x3D => self.token(T::AddAssign, p + 2),+ _ => self.token(T::Plus, p + 1),+ },+ b'-' => match self.at(p + 1) {+ 0x2D => self.token(T::Dec, p + 2),+ 0x3D => self.token(T::SubAssign, p + 2),+ _ => self.token(T::Minus, p + 1),+ },+ b'*' => {+ if self.at(p + 1) == 0x2A {+ if self.at(p + 2) == 0x3D {+ self.token(T::ExpAssign, p + 3);+ } else {+ self.token(T::StarStar, p + 2);+ }+ } else if self.at(p + 1) == 0x3D {+ self.token(T::MulAssign, p + 2);+ } else {+ self.token(T::Star, p + 1);+ }+ }+ b'/' => {+ if self.at(p + 1) == 0x3D {+ self.token(T::DivAssign, p + 2);+ } else {+ self.token(T::Slash, p + 1);+ }+ }+ b'%' => {+ if self.at(p + 1) == 0x3D {+ self.token(T::ModAssign, p + 2);+ } else {+ self.token(T::Percent, p + 1);+ }+ }+ b'<' => {+ if self.at(p + 1) == 0x3C {+ if self.at(p + 2) == 0x3D {+ self.token(T::ShlAssign, p + 3);+ } else {+ self.token(T::Shl, p + 2);+ }+ } else if self.at(p + 1) == 0x3D {+ self.token(T::Le, p + 2);+ } else {+ self.token(T::Lt, p + 1);+ }+ }+ b'>' => {+ if self.at(p + 1) == 0x3E {+ if self.at(p + 2) == 0x3E {+ if self.at(p + 3) == 0x3D {+ self.token(T::UShrAssign, p + 4);+ } else {+ self.token(T::UShr, p + 3);+ }+ } else if self.at(p + 2) == 0x3D {+ self.token(T::ShrAssign, p + 3);+ } else {+ self.token(T::Shr, p + 2);+ }+ } else if self.at(p + 1) == 0x3D {+ self.token(T::Ge, p + 2);+ } else {+ self.token(T::Gt, p + 1);+ }+ }+ b'&' => {+ if self.at(p + 1) == 0x26 {+ if self.at(p + 2) == 0x3D {+ self.token(T::LogAndAssign, p + 3);+ } else {+ self.token(T::LogAnd, p + 2);+ }+ } else if self.at(p + 1) == 0x3D {+ self.token(T::AndAssign, p + 2);+ } else {+ self.token(T::BitAnd, p + 1);+ }+ }+ b'|' => {+ if self.at(p + 1) == 0x7C {+ if self.at(p + 2) == 0x3D {+ self.token(T::LogOrAssign, p + 3);+ } else {+ self.token(T::LogOr, p + 2);+ }+ } else if self.at(p + 1) == 0x3D {+ self.token(T::OrAssign, p + 2);+ } else {+ self.token(T::BitOr, p + 1);+ }+ }+ b'^' => {+ if self.at(p + 1) == 0x3D {+ self.token(T::XorAssign, p + 2);+ } else {+ self.token(T::BitXor, p + 1);+ }+ }+ b'?' => {+ let d = self.at(p + 1);+ if d == 0x3F {+ if self.at(p + 2) == 0x3D {+ self.token(T::NullishAssign, p + 3);+ } else {+ self.token(T::Nullish, p + 2);+ }+ } else if d == 0x2E && !(0x30..=0x39).contains(&self.at(p + 2)) {+ self.token(T::QDot, p + 2);+ } else {+ self.token(T::Question, p + 1);+ }+ }+ b'#' => self.lex_identifier_slow(p + 1, true),+ b'\\' => self.lex_identifier_slow(p, false),+ 0 if p >= self.len as usize => {+ self.tok = T::Eof;+ self.tok_end = p as u32;+ self.pos = p as u32;+ }+ _ => {+ self.tok_start = p as u32;+ self.token(T::Invalid, p + 1);+ }+ }+ }++ fn skip_line_comment(&mut self, start: usize) -> usize {+ let mut p = start;+ let len = self.len as usize;+ loop {+ let x = self.block(p);+ // SAFETY: The block came from a load.+ let mut mask = unsafe { eq_mask(x, b'\n') | eq_mask(x, b'\r') };+ if U::WIDE {+ // SAFETY: As above.+ mask |= unsafe { high_mask(x) };+ }+ while mask != 0 {+ let q = p + mask.trailing_zeros() as usize;+ let c = self.at(q);+ if c == 0x0A || c == 0x0D || c == 0x2028 || c == 0x2029 {+ return q.min(len);+ }+ mask &= mask - 1;+ }+ p += BLOCK;+ if p >= len {+ return len;+ }+ }+ }++ fn skip_block_comment(&mut self, start: usize) -> Option<(usize, bool)> {+ let mut p = start;+ let len = self.len as usize;+ let mut newline = false;+ loop {+ let x = self.block(p);+ // SAFETY: The block came from a load.+ let mut mask = unsafe {+ let mut mask = eq_mask(x, b'*') | eq_mask(x, b'\n') | eq_mask(x, b'\r');+ if U::WIDE {+ mask |= high_mask(x);+ }+ mask+ };+ while mask != 0 {+ let q = p + mask.trailing_zeros() as usize;+ match self.at(q) {+ 0x2A => {+ if self.at(q + 1) == 0x2F && q + 1 < len {+ return Some((q + 2, newline));+ }+ }+ 0x0A | 0x0D | 0x2028 | 0x2029 => newline = true,+ _ => {}+ }+ mask &= mask - 1;+ }+ p += BLOCK;+ if p >= len {+ return None;+ }+ }+ }++ #[inline(always)]+ fn lex_identifier(&mut self, p: usize) {+ let x = self.block(p);+ // SAFETY: The block came from a load.+ let n = unsafe { (!ident_mask(x)).trailing_zeros() } as usize;+ let stop = self.at(p + n);+ if n > 16 || n == BLOCK || stop >= 0x80 || stop == 0x5C {+ self.lex_identifier_long(p);+ return;+ }+ // SAFETY: As above.+ let (k0, k1) = unsafe { key_of(x, n) };+ let id = self.interner.intern_key(k0, k1, n);+ self.tok_name = id;+ self.tok_escaped = false;+ self.tok = if id < KEYWORD_COUNT {+ KEYWORD_KINDS[id as usize]+ } else {+ T::Name+ };+ self.tok_end = (p + n) as u32;+ self.pos = (p + n) as u32;+ }++ /// An ASCII name of more than 16 units, or the start of something the slow path has to look at.+ #[inline(never)]+ fn lex_identifier_long(&mut self, p: usize) {+ let mut q = p;+ loop {+ // SAFETY: The block came from a load.+ let n = unsafe { (!ident_mask(self.block(q))).trailing_zeros() } as usize;+ q += n;+ if n < BLOCK {+ break;+ }+ }+ let stop = self.at(q);+ if stop >= 0x80 || stop == 0x5C {+ self.lex_identifier_slow(p, false);+ return;+ }+ self.name_buffer.clear();+ for i in p..q {+ let c = self.at(i) as u8;+ self.name_buffer.push(c);+ }+ let id = self.interner.intern_bytes(&self.name_buffer);+ self.tok_name = id;+ self.tok_escaped = false;+ self.tok = if id < KEYWORD_COUNT {+ KEYWORD_KINDS[id as usize]+ } else {+ T::Name+ };+ self.tok_end = q as u32;+ self.pos = q as u32;+ }++ fn code_point_at(&self, p: usize) -> (u32, usize) {+ let c = self.at(p);+ if U::WIDE && (0xD800..0xDC00).contains(&c) {+ let d = self.at(p + 1);+ if (0xDC00..0xE000).contains(&d) {+ return (0x10000 + ((c - 0xD800) << 10) + (d - 0xDC00), 2);+ }+ }+ (c, 1)+ }++ /// `\uXXXX` or `\u{X...}` from the `u`. Returns the code point and the position after it.+ fn read_unicode_escape(&self, p: usize) -> Option<(u32, usize)> {+ if self.at(p) != 0x75 {+ return None;+ }+ if self.at(p + 1) == 0x7B {+ let mut q = p + 2;+ let mut value = 0u32;+ let mut digits = 0;+ while let Some(digit) = hex_value(self.at(q)) {+ value = value * 16 + digit;+ if value > 0x10FFFF {+ return None;+ }+ digits += 1;+ q += 1;+ }+ if digits == 0 || self.at(q) != 0x7D {+ return None;+ }+ Some((value, q + 1))+ } else {+ let mut value = 0;+ for i in 1..=4 {+ value = value * 16 + hex_value(self.at(p + i))?;+ }+ Some((value, p + 5))+ }+ }++ #[inline(never)]+ fn lex_identifier_slow(&mut self, start: usize, private: bool) {+ let mut p = start;+ let mut escaped = false;+ let mut first = true;+ let mut buffer = std::mem::take(&mut self.name_buffer);+ buffer.clear();+ loop {+ let (mut c, width) = self.code_point_at(p);+ let mut next = p + width;+ if c == 0x5C {+ let Some((value, after)) = self.read_unicode_escape(p + 1) else {+ self.fail(p as u32, "Malformed unicode escape sequence");+ break;+ };+ c = value;+ next = after;+ escaped = true;+ let valid = if first { is_id_start(c) } else { is_id_continue(c) };+ if !valid {+ self.fail(p as u32, "Invalid escaped identifier character");+ break;+ }+ } else if !(if first { is_id_start(c) } else { is_id_continue(c) }) {+ break;+ }+ let mut encoded = [0u8; 4];+ let ch = char::from_u32(c).unwrap_or('\u{FFFD}');+ buffer.extend_from_slice(ch.encode_utf8(&mut encoded).as_bytes());+ first = false;+ p = next;+ }+ if self.err.is_some() {+ self.name_buffer = buffer;+ return;+ }+ if first {+ self.name_buffer = buffer;+ self.fail(p as u32, "Illegal character");+ return;+ }+ let id = self.interner.intern_bytes(&buffer);+ self.name_buffer = buffer;+ self.tok_name = id;+ self.tok_escaped = escaped;+ self.tok = if private {+ T::PrivateName+ } else if id < KEYWORD_COUNT {+ if escaped {+ T::EscapedKeyword+ } else {+ KEYWORD_KINDS[id as usize]+ }+ } else {+ T::Name+ };+ self.tok_end = p as u32;+ self.pos = p as u32;+ }++ #[inline(never)]+ fn lex_number(&mut self, start: usize) {+ let mut p = start;+ let first = self.at(p);+ let mut kind = T::Num;+ self.tok_legacy = false;+ let radix = if first == 0x30 {+ match self.at(p + 1) | 0x20 {+ 0x78 => 16,+ 0x6F => 8,+ 0x62 => 2,+ _ => 10,+ }+ } else {+ 10+ };+ if radix != 10 {+ p += 2;+ if !self.scan_digits(&mut p, radix, true) {+ return;+ }+ if self.at(p) == 0x6E {+ kind = T::BigInt;+ p += 1;+ }+ } else if first == 0x30 && (0x30..=0x39).contains(&self.at(p + 1)) {+ // Legacy octal, or a decimal with a leading zero.+ self.tok_legacy = true;+ let mut octal = true;+ while (0x30..=0x39).contains(&self.at(p)) {+ if self.at(p) >= 0x38 {+ octal = false;+ }+ p += 1;+ }+ if self.at(p) == 0x5F {+ self.fail(+ p as u32,+ "Numeric literal must not be immediately followed by identifier",+ );+ return;+ }+ if !octal && !self.scan_fraction_and_exponent(&mut p) {+ return;+ }+ } else {+ if first != 0x2E {+ if !self.scan_digits(&mut p, 10, true) {+ return;+ }+ if first == 0x30 && p != start + 1 {+ self.fail(+ start as u32,+ "Numeric literal must not be immediately followed by identifier",+ );+ return;+ }+ if self.at(p) == 0x6E {+ kind = T::BigInt;+ p += 1;+ }+ }+ if kind == T::Num && !self.scan_fraction_and_exponent(&mut p) {+ return;+ }+ }+ let (c, _) = self.code_point_at(p);+ if is_id_start(c) || (0x30..=0x39).contains(&c) || c == 0x5C {+ self.fail(+ p as u32,+ "Numeric literal must not be immediately followed by identifier",+ );+ return;+ }+ self.token(kind, p);+ }++ fn scan_fraction_and_exponent(&mut self, p: &mut usize) -> bool {+ if self.at(*p) == 0x2E {+ *p += 1;+ if (0x30..=0x39).contains(&self.at(*p)) && !self.scan_digits(p, 10, true) {+ return false;+ }+ if self.at(*p) == 0x5F {+ self.fail(+ *p as u32,+ "Numeric literal must not be immediately followed by identifier",+ );+ return false;+ }+ }+ if self.at(*p) | 0x20 == 0x65 {+ *p += 1;+ if matches!(self.at(*p), 0x2B | 0x2D) {+ *p += 1;+ }+ if !self.scan_digits(p, 10, true) {+ return false;+ }+ }+ true+ }++ fn scan_digits(&mut self, p: &mut usize, radix: u32, separators: bool) -> bool {+ let start = *p;+ let mut last_separator = false;+ loop {+ let c = self.at(*p);+ if c == 0x5F && separators {+ if last_separator || *p == start {+ self.fail(+ *p as u32,+ "Numeric literal must not be immediately followed by identifier",+ );+ return false;+ }+ last_separator = true;+ *p += 1;+ continue;+ }+ match char::from_u32(c).and_then(|ch| ch.to_digit(radix)) {+ Some(_) => {+ last_separator = false;+ *p += 1;+ }+ None => break,+ }+ }+ if last_separator {+ self.fail(+ *p as u32,+ "Numeric literal must not be immediately followed by identifier",+ );+ return false;+ }+ if *p == start {+ self.fail(start as u32, "Invalid numeric literal");+ return false;+ }+ true+ }++ #[inline(always)]+ fn lex_string(&mut self, start: usize, quote: u8) {+ self.tok_legacy = false;+ self.tok_escaped = false;+ let len = self.len as usize;+ let mut p = start + 1;+ loop {+ let x = self.block(p);+ // SAFETY: The block came from a load.+ let mask = unsafe { eq_mask(x, quote) | eq_mask(x, b'\\') | eq_mask(x, b'\n') | eq_mask(x, b'\r') };+ if mask == 0 {+ p += BLOCK;+ if p >= len {+ self.fail(start as u32, "Unterminated string literal");+ return;+ }+ continue;+ }+ p += mask.trailing_zeros() as usize;+ let c = self.at(p);+ if c == quote as u32 {+ self.token(T::Str, p + 1);+ return;+ }+ if c == 0x5C {+ self.tok_escaped = true;+ match self.skip_escape(p + 1) {+ Some(after) => p = after,+ None => return,+ }+ } else {+ self.fail(start as u32, "Unterminated string literal");+ return;+ }+ }+ }++ /// Validates a string escape from the unit after the backslash, and returns the position after it.+ #[inline(never)]+ fn skip_escape(&mut self, p: usize) -> Option<usize> {+ let c = self.at(p);+ match c {+ 0x0D => Some(if self.at(p + 1) == 0x0A { p + 2 } else { p + 1 }),+ 0x78 => {+ if hex_value(self.at(p + 1)).is_some() && hex_value(self.at(p + 2)).is_some() {+ Some(p + 3)+ } else {+ self.fail(p as u32, "Malformed hexadecimal escape sequence");+ None+ }+ }+ 0x75 => match self.read_unicode_escape(p) {+ Some((_, after)) => Some(after),+ None => {+ self.fail(p as u32, "Malformed unicode escape sequence");+ None+ }+ },+ 0x30..=0x37 => {+ let next = self.at(p + 1);+ if c == 0x30 && !(0x30..=0x39).contains(&next) {+ return Some(p + 1);+ }+ self.tok_legacy = true;+ let mut q = p + 1;+ if (0x30..=0x37).contains(&self.at(q)) {+ q += 1;+ if c <= 0x33 && (0x30..=0x37).contains(&self.at(q)) {+ q += 1;+ }+ }+ Some(q)+ }+ 0x38 | 0x39 => {+ self.tok_legacy = true;+ Some(p + 1)+ }+ 0 if p >= self.len as usize => {+ self.fail(p as u32, "Unterminated string literal");+ None+ }+ _ => Some(p + self.code_point_at(p).1),+ }+ }++ /// Reads template characters from `self.pos`. Returns whether the chunk ended the template, and whether it has an+ /// escape that only a tagged template may contain, and leaves `self.pos` after the closing `` ` `` or `${`.+ pub(crate) fn read_template_chunk(&mut self) -> (bool, bool) {+ let len = self.len as usize;+ let mut p = self.pos as usize;+ let mut invalid = false;+ loop {+ let x = self.block(p);+ // SAFETY: The block came from a load.+ let mask = unsafe { eq_mask(x, b'`') | eq_mask(x, b'$') | eq_mask(x, b'\\') };+ if mask == 0 {+ p += BLOCK;+ if p >= len {+ break;+ }+ continue;+ }+ p += mask.trailing_zeros() as usize;+ if p >= len {+ break;+ }+ match self.at(p) {+ 0x60 => {+ self.pos = (p + 1) as u32;+ return (true, invalid);+ }+ 0x24 => {+ if self.at(p + 1) == 0x7B {+ self.pos = (p + 2) as u32;+ return (false, invalid);+ }+ p += 1;+ }+ _ => {+ let c = self.at(p + 1);+ match c {+ 0x30 if !(0x30..=0x39).contains(&self.at(p + 2)) => p += 2,+ 0x30..=0x39 => {+ invalid = true;+ p += 2;+ }+ 0x78 => {+ if hex_value(self.at(p + 2)).is_some() && hex_value(self.at(p + 3)).is_some() {+ p += 4;+ } else {+ invalid = true;+ p += 2;+ }+ }+ 0x75 => match self.read_unicode_escape(p + 1) {+ Some((_, after)) => p = after,+ None => {+ invalid = true;+ p += 2;+ }+ },+ 0x0D if self.at(p + 2) == 0x0A => p += 3,+ _ => p += 1 + self.code_point_at(p + 1).1,+ }+ }+ }+ }+ self.fail(self.tok_start, "Unterminated template literal");+ (true, false)+ }++ /// Reads a regular expression literal in place of the `/` or `/=` token.+ pub(crate) fn rescan_regex(&mut self) {+ let start = self.tok_start as usize;+ let len = self.len as usize;+ let mut p = start + 1;+ let mut in_class = false;+ loop {+ if p >= len {+ self.fail(start as u32, "Unterminated regular expression literal");+ return;+ }+ let c = self.at(p);+ match c {+ 0x0A | 0x0D | 0x2028 | 0x2029 => {+ self.fail(start as u32, "Unterminated regular expression literal");+ return;+ }+ 0x5C => {+ let d = self.at(p + 1);+ if matches!(d, 0x0A | 0x0D | 0x2028 | 0x2029) {+ self.fail(start as u32, "Unterminated regular expression literal");+ return;+ }+ p += 2;+ continue;+ }+ 0x5B => in_class = true,+ 0x5D => in_class = false,+ 0x2F if !in_class => break,+ _ => {}+ }+ p += 1;+ }+ self.regex_body_end = p as u32;+ p += 1;+ let flags_start = p;+ loop {+ let (c, width) = self.code_point_at(p);+ if c == 0x5C {+ self.fail(p as u32, "Invalid regular expression flags");+ return;+ }+ if !is_id_continue(c) {+ break;+ }+ p += width;+ }+ let units_of = |parser: &Self, start: usize, end: usize| -> Vec<u16> {+ (start..end).map(|i| parser.at(i) as u16).collect()+ };+ let flags = units_of(self, flags_start, p);+ let mut seen = [false; 128];+ for &flag in &flags {+ if flag >= 128 || !b"dgimsuvy".contains(&(flag as u8)) {+ let flag = char::from_u32(flag as u32).unwrap_or('?');+ self.fail_with(self.tok_start, format!("Invalid RegExp flag '{flag}'"));+ return;+ }+ if seen[flag as usize] {+ let flag = flag as u8 as char;+ self.fail_with(self.tok_start, format!("Repeated RegExp flag '{flag}'"));+ return;+ }+ seen[flag as usize] = true;+ }+ let pattern = units_of(self, start + 1, self.regex_body_end as usize);+ if let Err(message) = crate::host::validate_regex(&pattern, &flags) {+ self.fail_with(start as u32, String::from_utf16_lossy(&message.to_utf16()));+ return;+ }+ self.token(T::Regex, p);+ }++ /// Whether the directive prologue at `start` contains "use strict". This looks ahead in the source so that the+ /// rest of the prologue is parsed knowing it.+ pub(crate) fn has_use_strict_directive(&mut self, start: usize) -> bool {+ let mut p = start;+ loop {+ p = self.skip_trivia_raw(p).0;+ let quote = self.at(p);+ if quote != 0x22 && quote != 0x27 {+ return false;+ }+ let content = p + 1;+ let mut q = content;+ loop {+ let c = self.at(q);+ if c == quote {+ break;+ }+ if q >= self.len as usize || c == 0x0A || c == 0x0D {+ return false;+ }+ q += if c == 0x5C { 2 } else { 1 };+ }+ let is_use_strict = q - content == 10 && (0..10).all(|i| self.at(content + i) == b"use strict"[i] as u32);+ let (after, newline) = self.skip_trivia_raw(q + 1);+ let next = self.at(after);+ if is_use_strict {+ if next == 0x3B || next == 0x7D || after >= self.len as usize {+ return true;+ }+ let continues = matches!(+ next as u8 as char,+ '(' | '`' | '.' | '[' | '+' | '-' | '/' | '*' | '%' | '<' | '>' | '=' | ',' | '?' | '^' | '&' | '|'+ ) && next < 0x80+ || (next == 0x21 && self.at(after + 1) == 0x3D);+ return newline && !continues;+ }+ p = after;+ if next == 0x3B {+ p += 1;+ }+ }+ }++ fn skip_trivia_raw(&mut self, start: usize) -> (usize, bool) {+ let mut p = start;+ let mut newline = false;+ loop {+ let c = self.at(p);+ match c {+ 0x20 | 0x09 | 0x0B | 0x0C => p += 1,+ 0x0A | 0x0D | 0x2028 | 0x2029 => {+ newline = true;+ p += 1;+ }+ 0x2F if self.at(p + 1) == 0x2F => p = self.skip_line_comment(p + 2),+ 0x2F if self.at(p + 1) == 0x2A => match self.skip_block_comment(p + 2) {+ Some((end, had_newline)) => {+ p = end;+ newline |= had_newline;+ }+ None => return (p, newline),+ },+ _ if c >= 0x80 && is_unicode_whitespace(c) => p += 1,+ _ => return (p, newline),+ }+ }+ }+}diff --git a/Libraries/LibJS/Rust/src/parser/literals.rs b/Libraries/LibJS/Rust/src/parser/literals.rsnew file mode 100644index 00000000000..7752bfe0628--- /dev/null+++ b/Libraries/LibJS/Rust/src/parser/literals.rs@@ -0,0 +1,296 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Turning the source text of literals into their values. The lexer only validates literals, and a value gets computed+//! when something needs it.++use crate::utf16::Utf16View;+use ak::Utf16String;++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.+ pub(crate) failed: bool,+}++/// 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`).+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));+ }+ i += 1;+ }+ 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);+ }+}++pub(crate) fn raw_template_value(raw: Utf16View<'_>) -> Utf16String {+ let mut result = Vec::with_capacity(raw.length_in_code_units());+ let mut i = 0;+ while i < raw.length_in_code_units() {+ if raw.code_unit_at(i) == ch(b'\r') {+ result.push(ch(b'\n'));+ if i + 1 < raw.length_in_code_units() && raw.code_unit_at(i + 1) == ch(b'\n') {+ i += 1;+ }+ } else {+ result.push(raw.code_unit_at(i));+ }+ i += 1;+ }+ Utf16String::from_utf16(&result)+}++pub(crate) fn parse_numeric_value(value: Utf16View<'_>) -> f64 {+ let s: String = value+ .code_units()+ .filter(|&c| c != '_' as u16)+ .map(|c| c as u8 as char)+ .collect();++ if s.starts_with("0x") || s.starts_with("0X") {+ parse_integer_with_radix(&s[2..], 16)+ } else if s.starts_with("0o") || s.starts_with("0O") {+ parse_integer_with_radix(&s[2..], 8)+ } else if s.starts_with("0b") || s.starts_with("0B") {+ parse_integer_with_radix(&s[2..], 2)+ } else if s.starts_with('0') && s.len() > 1 && s.as_bytes()[1].is_ascii_digit() {+ let digits = &s[1..];+ if digits.bytes().all(|b| (b'0'..=b'7').contains(&b)) {+ parse_integer_with_radix(digits, 8)+ } else {+ s.parse::<f64>().unwrap_or(f64::NAN)+ }+ } else {+ s.parse::<f64>().unwrap_or(f64::NAN)+ }+}++fn parse_integer_with_radix(digits: &str, radix: u32) -> f64 {+ if let Ok(v) = u64::from_str_radix(digits, radix) {+ return v as f64;+ }+ let mut result: f64 = 0.0;+ for ch in digits.chars() {+ let digit = ch.to_digit(radix);+ if let Some(d) = digit {+ result = result * (radix as f64) + (d as f64);+ }+ }+ result+}diff --git a/Libraries/LibJS/Rust/src/parser/token.rs b/Libraries/LibJS/Rust/src/parser/token.rsnew file mode 100644index 00000000000..76bf7c14528--- /dev/null+++ b/Libraries/LibJS/Rust/src/parser/token.rs@@ -0,0 +1,148 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Token kinds, and the names that have fixed ids so that a token's kind falls out of interning its text.++#[repr(u8)]+#[derive(Clone, Copy, PartialEq, Eq, Debug)]+#[rustfmt::skip]+pub enum T {+ Eof, Name, PrivateName, Num, BigInt, Str, Backtick, Regex, EscapedKeyword, Invalid,+ LBrace, RBrace, LParen, RParen, LBracket, RBracket, Semi, Comma, Dot, QDot, Question, Colon, Arrow, Ellipsis,+ // Assignment operators, in the order of the assignment node tags.+ Assign, AddAssign, SubAssign, MulAssign, DivAssign, ModAssign, ExpAssign, ShlAssign, ShrAssign, UShrAssign,+ AndAssign, OrAssign, XorAssign, LogAndAssign, LogOrAssign, NullishAssign,+ Inc, Dec, Not, Tilde,+ // Binary operators, in the order of the binary node tags.+ Nullish, LogOr, LogAnd, BitOr, BitXor, BitAnd, EqEq, NotEq, EqEqEq, NotEqEq, Lt, Gt, Le, Ge, Shl, Shr, UShr,+ Plus, Minus, Star, Slash, Percent, StarStar, KIn, KInstanceof,+ // Keywords.+ KBreak, KCase, KCatch, KClass, KConst, KContinue, KDebugger, KDefault, KDelete, KDo, KElse, KEnum, KExport,+ KExtends, KFalse, KFinally, KFor, KFunction, KIf, KImport, KNew, KNull, KReturn, KSuper, KSwitch, KThis,+ KThrow, KTrue, KTry, KTypeof, KVar, KVoid, KWhile, KWith,+}++/// What error messages call a token kind.+#[rustfmt::skip]+const TOKEN_NAMES: &[&str] = &[+ "Eof", "Identifier", "PrivateIdentifier", "NumericLiteral", "BigIntLiteral", "StringLiteral", "TemplateLiteralStart",+ "RegexLiteral", "EscapedKeyword", "Invalid",+ "CurlyOpen", "CurlyClose", "ParenOpen", "ParenClose", "BracketOpen", "BracketClose", "Semicolon", "Comma", "Period",+ "QuestionMarkPeriod", "QuestionMark", "Colon", "Arrow", "TripleDot",+ "Equals", "PlusEquals", "MinusEquals", "AsteriskEquals", "SlashEquals", "PercentEquals", "DoubleAsteriskEquals",+ "ShiftLeftEquals", "ShiftRightEquals", "UnsignedShiftRightEquals", "AmpersandEquals", "PipeEquals", "CaretEquals",+ "DoubleAmpersandEquals", "DoublePipeEquals", "DoubleQuestionMarkEquals",+ "PlusPlus", "MinusMinus", "ExclamationMark", "Tilde",+ "DoubleQuestionMark", "DoublePipe", "DoubleAmpersand", "Pipe", "Caret", "Ampersand", "EqualsEquals",+ "ExclamationMarkEquals", "EqualsEqualsEquals", "ExclamationMarkEqualsEquals", "LessThan", "GreaterThan",+ "LessThanEquals", "GreaterThanEquals", "ShiftLeft", "ShiftRight", "UnsignedShiftRight", "Plus", "Minus", "Asterisk",+ "Slash", "Percent", "DoubleAsterisk", "In", "Instanceof",+ "Break", "Case", "Catch", "Class", "Const", "Continue", "Debugger", "Default", "Delete", "Do", "Else", "Enum", "Export",+ "Extends", "BoolLiteral", "Finally", "For", "Function", "If", "Import", "New", "NullLiteral", "Return", "Super", "Switch",+ "This", "Throw", "BoolLiteral", "Try", "Typeof", "Var", "Void", "While", "With",+];++impl T {+ /// How error messages spell a token that the grammar wants.+ pub fn spelling(self) -> &'static str {+ match self {+ T::LBrace => "'{'",+ T::RBrace => "'}'",+ T::LParen => "'('",+ T::RParen => "')'",+ T::LBracket => "'['",+ T::RBracket => "']'",+ T::Semi => "';'",+ T::Comma => "','",+ T::Colon => "':'",+ T::Arrow => "'=>'",+ T::Assign => "'='",+ T::KWhile => "'while'",+ _ => TOKEN_NAMES[self as usize],+ }+ }+}++/// The reserved words. A name's id is its index here, so ids below `KEYWORD_COUNT` are keywords.+#[rustfmt::skip]+pub const KEYWORDS: [(&str, T); 36] = [+ ("in", T::KIn), ("instanceof", T::KInstanceof),+ ("break", T::KBreak), ("case", T::KCase), ("catch", T::KCatch), ("class", T::KClass), ("const", T::KConst),+ ("continue", T::KContinue), ("debugger", T::KDebugger), ("default", T::KDefault), ("delete", T::KDelete),+ ("do", T::KDo), ("else", T::KElse), ("enum", T::KEnum), ("export", T::KExport), ("extends", T::KExtends),+ ("false", T::KFalse), ("finally", T::KFinally), ("for", T::KFor), ("function", T::KFunction), ("if", T::KIf),+ ("import", T::KImport), ("new", T::KNew), ("null", T::KNull), ("return", T::KReturn), ("super", T::KSuper),+ ("switch", T::KSwitch), ("this", T::KThis), ("throw", T::KThrow), ("true", T::KTrue), ("try", T::KTry),+ ("typeof", T::KTypeof), ("var", T::KVar), ("void", T::KVoid), ("while", T::KWhile), ("with", T::KWith),+];+pub const KEYWORD_COUNT: u32 = KEYWORDS.len() as u32;++/// Names the grammar looks at, after the keywords. Every id from `FIRST_PLAIN_NAME` on is an ordinary name, so one+/// compare clears an identifier of all reserved word checks.+#[rustfmt::skip]+pub const SPECIAL_NAMES: [&str; 27] = [+ "implements", "interface", "let", "package", "private", "protected", "public", "static", "yield",+ "await", "eval", "arguments", "async", "of", "get", "set", "as", "from", "target", "meta", "constructor",+ "prototype", "__proto__", "using", "accessor", "defer", "source",+];+pub const N_IMPLEMENTS: u32 = KEYWORD_COUNT;+pub const N_LET: u32 = KEYWORD_COUNT + 2;+pub const N_STATIC: u32 = KEYWORD_COUNT + 7;+pub const N_YIELD: u32 = KEYWORD_COUNT + 8;+pub const N_AWAIT: u32 = KEYWORD_COUNT + 9;+pub const N_EVAL: u32 = KEYWORD_COUNT + 10;+pub const N_ARGUMENTS: u32 = KEYWORD_COUNT + 11;+pub const N_ASYNC: u32 = KEYWORD_COUNT + 12;+pub const N_OF: u32 = KEYWORD_COUNT + 13;+pub const N_GET: u32 = KEYWORD_COUNT + 14;+pub const N_SET: u32 = KEYWORD_COUNT + 15;+pub const N_AS: u32 = KEYWORD_COUNT + 16;+pub const N_FROM: u32 = KEYWORD_COUNT + 17;+pub const N_TARGET: u32 = KEYWORD_COUNT + 18;+pub const N_META: u32 = KEYWORD_COUNT + 19;+pub const N_CONSTRUCTOR: u32 = KEYWORD_COUNT + 20;+pub const N_PROTOTYPE: u32 = KEYWORD_COUNT + 21;+pub const N_PROTO: u32 = KEYWORD_COUNT + 22;+pub const N_USING: u32 = KEYWORD_COUNT + 23;+/// Pseudo names: they cannot be spelled, and `this`, `new.target` and `super` use them to flow through scope analysis+/// as ordinary free names, which is what makes an arrow function's use of them a capture.+pub const N_DOT_THIS: u32 = KEYWORD_COUNT + SPECIAL_NAMES.len() as u32;+pub const N_DOT_NEW_TARGET: u32 = N_DOT_THIS + 1;+pub const N_DOT_SUPER: u32 = N_DOT_THIS + 2;+/// What a function that gets compiled later would make of a name that no scope around it binds.+pub const N_DOT_UNBOUND: u32 = N_DOT_THIS + 3;+pub const FIRST_PLAIN_NAME: u32 = N_DOT_THIS + 4;++/// Binary operator precedence by token kind, zero for everything else.+pub const fn build_precedence() -> [u8; 256] {+ let mut p = [0u8; 256];+ p[T::Nullish as usize] = 1;+ p[T::LogOr as usize] = 1;+ p[T::LogAnd as usize] = 2;+ p[T::BitOr as usize] = 3;+ p[T::BitXor as usize] = 4;+ p[T::BitAnd as usize] = 5;+ p[T::EqEq as usize] = 6;+ p[T::NotEq as usize] = 6;+ p[T::EqEqEq as usize] = 6;+ p[T::NotEqEq as usize] = 6;+ p[T::Lt as usize] = 7;+ p[T::Gt as usize] = 7;+ p[T::Le as usize] = 7;+ p[T::Ge as usize] = 7;+ p[T::KIn as usize] = 7;+ p[T::KInstanceof as usize] = 7;+ p[T::Shl as usize] = 8;+ p[T::Shr as usize] = 8;+ p[T::UShr as usize] = 8;+ p[T::Plus as usize] = 9;+ p[T::Minus as usize] = 9;+ p[T::Star as usize] = 10;+ p[T::Slash as usize] = 10;+ p[T::Percent as usize] = 10;+ p+}+pub static PRECEDENCE: [u8; 256] = build_precedence();diff --git a/Libraries/LibJS/Rust/src/parser/unit.rs b/Libraries/LibJS/Rust/src/parser/unit.rsnew file mode 100644index 00000000000..7a8bf1b9027--- /dev/null+++ b/Libraries/LibJS/Rust/src/parser/unit.rs@@ -0,0 +1,326 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Input code units. Source text is either 8-bit Latin-1 or 16-bit UTF-16, and the lexer is generic over the two.+//!+//! Every scan works on a block of code units narrowed to bytes, where anything above 0xFE saturates to 0xFF. ASCII stays+//! exact, so the classification is the same for both widths, and an ASCII identifier's narrowed bytes are its interning+//! key whatever the input width was. A block is 32 units with AVX2 and 16 units otherwise; the lexer only knows `BLOCK`.+//!+//! The source must be followed by at least 64 units of zero padding, so blocks may read past its end.++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;+}++impl Unit for u8 {+ const WIDE: bool = false;+ #[inline(always)]+ fn code(self) -> u32 {+ self as u32+ }+ #[inline(always)]+ unsafe fn load(p: *const u8) -> Block {+ unsafe { block::load_narrow(p) }+ }+}++impl Unit for u16 {+ const WIDE: bool = true;+ #[inline(always)]+ fn code(self) -> u32 {+ self as u32+ }+ #[inline(always)]+ unsafe fn load(p: *const u16) -> Block {+ unsafe { block::load_wide(p) }+ }+}++#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]+const fn ident_tables() -> ([u8; 16], [u8; 16]) {+ const B0: u8 = 1; // '$'+ const B1: u8 = 2; // digits+ const B2: u8 = 4; // A-O, a-o+ const B3: u8 = 8; // P-Z, p-z+ const B4: u8 = 16; // '_'+ let mut lo = [0u8; 16];+ let mut hi = [0u8; 16];+ hi[2] = B0;+ hi[3] = B1;+ hi[4] = B2;+ hi[5] = B3 | B4;+ hi[6] = B2;+ hi[7] = B3;+ lo[4] |= B0;+ let mut i = 0;+ while i < 16 {+ if i <= 9 {+ lo[i] |= B1;+ }+ if i >= 1 {+ lo[i] |= B2;+ }+ if i <= 10 {+ lo[i] |= B3;+ }+ i += 1;+ }+ lo[15] |= B4;+ (lo, hi)+}+#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]+const IDENT_TABLES: ([u8; 16], [u8; 16]) = ident_tables();++/// A word with its bytes from `len` on cleared.+#[inline(always)]+fn first_bytes(word: u64, len: usize) -> u64 {+ if len >= 8 {+ word+ } else {+ word & ((1u64 << (len * 8)) - 1)+ }+}++/// The first 16 narrowed units with everything from `len` on cleared, as two little-endian words.+#[inline(always)]+pub unsafe fn key_of(x: Block, len: usize) -> (u64, u64) {+ let (k0, k1) = unsafe { block::first_words(x) };+ if len <= 8 {+ (first_bytes(k0, len), 0)+ } else {+ (k0, first_bytes(k1, len - 8))+ }+}++pub use block::{BLOCK, Block, eq_mask, high_mask, ident_mask};++#[cfg(all(target_arch = "x86_64", target_feature = "avx2"))]+mod block {+ use super::IDENT_TABLES;+ use core::arch::x86_64::*;++ pub const BLOCK: usize = 32;+ pub type Block = __m256i;++ #[inline(always)]+ pub unsafe fn load_narrow(p: *const u8) -> Block {+ unsafe { _mm256_loadu_si256(p as *const __m256i) }+ }++ #[inline(always)]+ pub unsafe fn load_wide(p: *const u16) -> Block {+ unsafe {+ #[cfg(target_feature = "avx512bw")]+ {+ _mm512_cvtusepi16_epi8(_mm512_loadu_si512(p as *const _))+ }+ #[cfg(not(target_feature = "avx512bw"))]+ {+ let cap = _mm256_set1_epi16(0xFF);+ let a = _mm256_min_epu16(_mm256_loadu_si256(p as *const __m256i), cap);+ let b = _mm256_min_epu16(_mm256_loadu_si256(p.add(16) as *const __m256i), cap);+ _mm256_permute4x64_epi64::<0b11011000>(_mm256_packus_epi16(a, b))+ }+ }+ }++ /// One bit per unit of the block: whether it is an ASCII identifier part.+ #[inline(always)]+ pub unsafe fn ident_mask(x: Block) -> u32 {+ unsafe {+ let lo_table = _mm256_broadcastsi128_si256(_mm_loadu_si128(IDENT_TABLES.0.as_ptr() as *const __m128i));+ let hi_table = _mm256_broadcastsi128_si256(_mm_loadu_si128(IDENT_TABLES.1.as_ptr() as *const __m128i));+ let hi_index = _mm256_and_si256(_mm256_srli_epi16::<4>(x), _mm256_set1_epi8(0x0F));+ let lo = _mm256_shuffle_epi8(lo_table, x);+ let hi = _mm256_shuffle_epi8(hi_table, hi_index);+ let none = _mm256_cmpeq_epi8(_mm256_and_si256(lo, hi), _mm256_setzero_si256());+ !(_mm256_movemask_epi8(none) as u32)+ }+ }++ #[inline(always)]+ pub unsafe fn eq_mask(x: Block, byte: u8) -> u32 {+ unsafe { _mm256_movemask_epi8(_mm256_cmpeq_epi8(x, _mm256_set1_epi8(byte as i8))) as u32 }+ }++ /// The units at or above 0x80.+ #[inline(always)]+ pub unsafe fn high_mask(x: Block) -> u32 {+ unsafe { _mm256_movemask_epi8(x) as u32 }+ }++ #[inline(always)]+ pub unsafe fn first_words(x: Block) -> (u64, u64) {+ unsafe {+ let low = _mm256_castsi256_si128(x);+ (_mm_cvtsi128_si64(low) as u64, _mm_extract_epi64::<1>(low) as u64)+ }+ }+}++#[cfg(all(target_arch = "x86_64", not(target_feature = "avx2")))]+mod block {+ use super::IDENT_TABLES;+ use core::arch::x86_64::*;++ pub const BLOCK: usize = 16;+ pub type Block = __m128i;++ #[inline(always)]+ pub unsafe fn load_narrow(p: *const u8) -> Block {+ unsafe { _mm_loadu_si128(p as *const __m128i) }+ }++ #[inline(always)]+ pub unsafe fn load_wide(p: *const u16) -> Block {+ unsafe {+ let cap = _mm_set1_epi16(0xFF);+ let a = _mm_min_epu16(_mm_loadu_si128(p as *const __m128i), cap);+ let b = _mm_min_epu16(_mm_loadu_si128(p.add(8) as *const __m128i), cap);+ _mm_packus_epi16(a, b)+ }+ }++ /// One bit per unit of the block: whether it is an ASCII identifier part.+ #[inline(always)]+ pub unsafe fn ident_mask(x: Block) -> u32 {+ unsafe {+ let lo_table = _mm_loadu_si128(IDENT_TABLES.0.as_ptr() as *const __m128i);+ let hi_table = _mm_loadu_si128(IDENT_TABLES.1.as_ptr() as *const __m128i);+ let hi_index = _mm_and_si128(_mm_srli_epi16::<4>(x), _mm_set1_epi8(0x0F));+ let lo = _mm_shuffle_epi8(lo_table, x);+ let hi = _mm_shuffle_epi8(hi_table, hi_index);+ let none = _mm_cmpeq_epi8(_mm_and_si128(lo, hi), _mm_setzero_si128());+ !(_mm_movemask_epi8(none) as u32) & 0xFFFF+ }+ }++ #[inline(always)]+ pub unsafe fn eq_mask(x: Block, byte: u8) -> u32 {+ unsafe { _mm_movemask_epi8(_mm_cmpeq_epi8(x, _mm_set1_epi8(byte as i8))) as u32 }+ }++ /// The units at or above 0x80.+ #[inline(always)]+ pub unsafe fn high_mask(x: Block) -> u32 {+ unsafe { _mm_movemask_epi8(x) as u32 }+ }++ #[inline(always)]+ pub unsafe fn first_words(x: Block) -> (u64, u64) {+ unsafe { (_mm_cvtsi128_si64(x) as u64, _mm_extract_epi64::<1>(x) as u64) }+ }+}++#[cfg(target_arch = "aarch64")]+mod block {+ use super::IDENT_TABLES;+ use core::arch::aarch64::*;++ pub const BLOCK: usize = 16;+ pub type Block = uint8x16_t;++ #[inline(always)]+ pub unsafe fn load_narrow(p: *const u8) -> Block {+ unsafe { vld1q_u8(p) }+ }++ #[inline(always)]+ pub unsafe fn load_wide(p: *const u16) -> Block {+ unsafe { vcombine_u8(vqmovn_u16(vld1q_u16(p)), vqmovn_u16(vld1q_u16(p.add(8)))) }+ }++ /// One bit per byte, from a vector whose bytes are all ones or all zeros.+ #[inline(always)]+ unsafe fn bits_of(x: Block) -> u32 {+ const BITS: [u8; 16] = [1, 2, 4, 8, 16, 32, 64, 128, 1, 2, 4, 8, 16, 32, 64, 128];+ unsafe {+ let masked = vandq_u8(x, vld1q_u8(BITS.as_ptr()));+ vaddv_u8(vget_low_u8(masked)) as u32 | (vaddv_u8(vget_high_u8(masked)) as u32) << 8+ }+ }++ /// One bit per unit of the block: whether it is an ASCII identifier part.+ #[inline(always)]+ pub unsafe fn ident_mask(x: Block) -> u32 {+ unsafe {+ let lo = vqtbl1q_u8(vld1q_u8(IDENT_TABLES.0.as_ptr()), vandq_u8(x, vdupq_n_u8(0x0F)));+ let hi = vqtbl1q_u8(vld1q_u8(IDENT_TABLES.1.as_ptr()), vshrq_n_u8::<4>(x));+ bits_of(vtstq_u8(lo, hi))+ }+ }++ #[inline(always)]+ pub unsafe fn eq_mask(x: Block, byte: u8) -> u32 {+ unsafe { bits_of(vceqq_u8(x, vdupq_n_u8(byte))) }+ }++ /// The units at or above 0x80.+ #[inline(always)]+ pub unsafe fn high_mask(x: Block) -> u32 {+ unsafe { bits_of(vcgeq_u8(x, vdupq_n_u8(0x80))) }+ }++ #[inline(always)]+ pub unsafe fn first_words(x: Block) -> (u64, u64) {+ unsafe {+ let words = vreinterpretq_u64_u8(x);+ (vgetq_lane_u64::<0>(words), vgetq_lane_u64::<1>(words))+ }+ }+}++#[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))]+mod block {+ pub const BLOCK: usize = 16;+ pub type Block = [u8; 16];++ #[inline(always)]+ pub unsafe fn load_narrow(p: *const u8) -> Block {+ unsafe { core::ptr::read_unaligned(p as *const Block) }+ }++ #[inline(always)]+ pub unsafe fn load_wide(p: *const u16) -> Block {+ core::array::from_fn(|i| unsafe { core::ptr::read_unaligned(p.add(i)) }.min(0xFF) as u8)+ }++ #[inline(always)]+ fn bits_of(x: Block, test: impl Fn(u8) -> bool) -> u32 {+ x.iter()+ .enumerate()+ .fold(0, |bits, (i, &byte)| bits | (test(byte) as u32) << i)+ }++ /// One bit per unit of the block: whether it is an ASCII identifier part.+ #[inline(always)]+ pub unsafe fn ident_mask(x: Block) -> u32 {+ bits_of(x, |c| c.is_ascii_alphanumeric() || c == b'$' || c == b'_')+ }++ #[inline(always)]+ pub unsafe fn eq_mask(x: Block, byte: u8) -> u32 {+ bits_of(x, |c| c == byte)+ }++ /// The units at or above 0x80.+ #[inline(always)]+ pub unsafe fn high_mask(x: Block) -> u32 {+ bits_of(x, |c| c >= 0x80)+ }++ #[inline(always)]+ pub unsafe fn first_words(x: Block) -> (u64, u64) {+ (+ u64::from_le_bytes(x[..8].try_into().unwrap()),+ u64::from_le_bytes(x[8..].try_into().unwrap()),+ )+ }+}