Truly independent web browser
LibJS: Reduce parser setup overhead for small sources
Andreas Kling0c8560c50d08
diff --git a/Libraries/LibJS/Rust/src/ast.rs b/Libraries/LibJS/Rust/src/ast.rsindex 214665ab095..4340c97dd5a 100644--- a/Libraries/LibJS/Rust/src/ast.rs+++ b/Libraries/LibJS/Rust/src/ast.rs@@ -285,6 +285,19 @@ pub(crate) struct NameTable {}impl NameTable {+ pub(crate) fn from_parser_names<'a>(names: impl ExactSizeIterator<Item = &'a [u8]> + Clone) -> Self {+ let ascii_bytes = names.clone().filter(|name| name.is_ascii()).map(<[u8]>::len).sum();+ let mut table = Self {+ spans: Vec::with_capacity(names.len()),+ ascii_text: Vec::with_capacity(ascii_bytes),+ ..Self::default()+ };+ for name in names {+ table.push(name);+ }+ table+ }+pub(crate) fn memory_size(&self) -> usize {self.spans.capacity() * size_of::<NameSpan>()+ self.ascii_text.capacity()diff --git a/Libraries/LibJS/Rust/src/parser/base.rs b/Libraries/LibJS/Rust/src/parser/base.rsindex c77c0b01bb6..06de1b63dc8 100644--- a/Libraries/LibJS/Rust/src/parser/base.rs+++ b/Libraries/LibJS/Rust/src/parser/base.rs@@ -353,10 +353,10 @@ impl<'a, U: Unit> Parser<'a, U> {/// `source` must be followed by at least 64 units of zeros within the same allocation.pub unsafe fn new(source: &'a [U], module: bool, mode: Mode) -> Self {let estimated_nodes = match mode {- Mode::Lazy => (source.len() / 3 + 1024).min(1 << 16),- Mode::Full => source.len() / 3 + 1024,+ Mode::Lazy => (source.len() / 3 + 16).min(1 << 16),+ Mode::Full => source.len() / 3 + 16,};- let estimated_functions = source.len() / 128 + 16;+ let estimated_functions = source.len() / 128;let mut parser = Self::with_capacities(source.as_ptr(),source.len(),@@ -365,7 +365,7 @@ impl<'a, U: Unit> Parser<'a, U> {Interner::new(source.len()),estimated_nodes,estimated_functions,- 1 << 16,+ (source.len() / 8 + 16).min(1 << 16),);if source.len() >= u32::MAX as usize - 64 {parser.len = 0;@@ -451,7 +451,7 @@ impl<'a, U: Unit> Parser<'a, U> {prev_end: 0,prev_start: 0,regex_body_end: 0,- name_buffer: Vec::with_capacity(256),+ name_buffer: Vec::new(),interner,ast: Ast::with_capacity(estimated_nodes),index: FunctionIndex {@@ -482,7 +482,7 @@ impl<'a, U: Unit> Parser<'a, U> {module,strict: module,ctx: if module { ctx::CAN_AWAIT } else { 0 },- labels: Vec::with_capacity(64),+ labels: Vec::new(),labels_base: 0,stack_limit: 0,recursion_depth: 0,@@ -506,7 +506,7 @@ impl<'a, U: Unit> Parser<'a, U> {],uses: Vec::with_capacity(estimated_uses),decls: Vec::with_capacity(estimated_uses / 16),- scopes: Vec::with_capacity(256),+ scopes: Vec::with_capacity((length / 64 + 1).min(256)),cur_scope: 0,cur_func: 0,next_scope: 1,diff --git a/Libraries/LibJS/Rust/src/parser/intern.rs b/Libraries/LibJS/Rust/src/parser/intern.rsindex 5c80da11020..08faf19d62a 100644--- a/Libraries/LibJS/Rust/src/parser/intern.rs+++ b/Libraries/LibJS/Rust/src/parser/intern.rs@@ -8,6 +8,7 @@//! 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};+use std::sync::OnceLock;pub const NONE: u32 = u32::MAX;@@ -56,6 +57,7 @@ fn hash_bytes(bytes: &[u8]) -> u64 {}/// The key of a name of at most 16 bytes: its bytes in order, as two little-endian words.+/// Names ending in NUL use the full-text table, since zero padding would erase their length.#[inline(always)]fn key_from_bytes(bytes: &[u8]) -> (u64, u64) {let word_at = |at: usize| u64::from_le_bytes(bytes[at..at + 8].try_into().unwrap());@@ -76,8 +78,35 @@ fn key_from_bytes(bytes: &[u8]) -> (u64, u64) {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)+ let wanted = (source_len / 16).clamp(1 << 8, 1 << 22).next_power_of_two();+ // OPTIMIZATION: Tiny scripts, such as repeated evals, do not amortize the setup of a direct table for two-byte+ // names.+ let short = if source_len >= 1 << 16 {+ vec![NONE; 1 << 16]+ } else {+ Vec::new()+ };+ let long_rows = (source_len / 128).clamp(1 << 4, 1 << 10).next_power_of_two();+ if wanted == 1 << 8 && long_rows == 1 << 4 {+ // OPTIMIZATION: Every parser starts with the same reserved names. Copy their tables for small sources+ // instead of interning all of them again, which is more work than parsing many eval strings.+ static INITIAL: OnceLock<Interner> = OnceLock::new();+ let initial = INITIAL.get_or_init(|| Self::with_tables(Vec::new(), 1 << 8, 1 << 4, 512));+ let mut interner = Self {+ short,+ rows: initial.rows.clone(),+ shift: initial.shift,+ count: initial.count,+ long_rows: initial.long_rows.clone(),+ long_count: initial.long_count,+ text: Vec::with_capacity(512),+ spans: Vec::with_capacity(1 << 7),+ };+ interner.text.extend_from_slice(&initial.text);+ interner.spans.extend_from_slice(&initial.spans);+ return interner;+ }+ Self::with_tables(short, wanted, long_rows, (source_len / 8).max(512))}fn with_tables(short: Vec<u32>, rows: usize, long_rows: usize, text_capacity: usize) -> Self {@@ -115,7 +144,7 @@ impl Interner {let mut interner = Self::empty(Vec::new(), rows, 1 << 4, names.len() * 8);let mask = rows - 1;for name in names {- if name.len() > 16 {+ if name.len() > 16 || name.last() == Some(&0) {interner.intern_bytes(name);continue;}@@ -217,7 +246,7 @@ impl Interner {/// Interns any name, given as UTF-8.pub fn intern_bytes(&mut self, bytes: &[u8]) -> u32 {- if bytes.len() <= 16 {+ if bytes.len() <= 16 && bytes.last() != Some(&0) {let (k0, k1) = key_from_bytes(bytes);return self.intern_key(k0, k1, bytes.len());}@@ -255,3 +284,52 @@ impl Interner {id}}++#[cfg(test)]+mod tests {+ use super::Interner;++ #[test]+ fn trailing_nuls_preserve_name_identity() {+ // Exercise the prepared small interner, the general fallback, and the direct short-name table.+ for source_len in [0, 20_000, 65_536] {+ for reverse in [false, true] {+ let mut interner = Interner::new(source_len);+ let mut expected = Vec::new();+ for prefix in [+ b"".as_slice(),+ b"a",+ b"ab",+ b"in",+ b"\0a",+ b"a\0b",+ b"abcdefgh",+ b"abcdefghijklmnop",+ ] {+ for index in 0..=17 - prefix.len() {+ let padding = if reverse { 17 - prefix.len() - index } else { index };+ let mut name = prefix.to_vec();+ name.resize(prefix.len() + padding, 0);+ let id = interner.intern_bytes(&name);+ assert_eq!(interner.text(id), name);+ expected.push((name, id));+ }+ }++ // Grow the tables before looking up the names again.+ for index in 0..512 {+ interner.intern_bytes(format!("extra_name_{index}").as_bytes());+ }+ for (name, id) in &expected {+ assert_eq!(interner.intern_bytes(name), *id);+ }++ let mut reparsed = Interner::with_names((0..interner.len()).map(|id| interner.text(id as u32)));+ for (name, id) in &expected {+ assert_eq!(reparsed.intern_bytes(name), *id);+ assert_eq!(reparsed.text(*id), name);+ }+ }+ }+ }+}diff --git a/Libraries/LibJS/Rust/src/parser/mod.rs b/Libraries/LibJS/Rust/src/parser/mod.rsindex c845154aeb5..554a78ed3f1 100644--- a/Libraries/LibJS/Rust/src/parser/mod.rs+++ b/Libraries/LibJS/Rust/src/parser/mod.rs@@ -628,10 +628,8 @@ pub fn parse_to_tree(source: &ak::Utf16String, options: &ParseOptions) -> Resultlet mut output = parse_source(source, options, ParsePurpose::Compile)?;let default_export_name = Name(output.interner.intern_bytes(b"*default*"));let default_constructor_parameter_name = Name(output.interner.intern_bytes(b"args"));- let mut names = NameTable::default();- for name in 0..output.interner.len() {- names.push(output.interner.text(u32_from_usize(name)));- }+ let names =+ NameTable::from_parser_names((0..output.interner.len()).map(|name| output.interner.text(u32_from_usize(name))));let mut global_names_used_in_with = output.global_names_used_in_with;global_names_used_in_with.sort_unstable();global_names_used_in_with.dedup();diff --git a/Tests/LibJS/Runtime/modules/basic-modules.js b/Tests/LibJS/Runtime/modules/basic-modules.jsindex 528ccbb47c7..e04189dfb57 100644--- a/Tests/LibJS/Runtime/modules/basic-modules.js+++ b/Tests/LibJS/Runtime/modules/basic-modules.js@@ -204,6 +204,25 @@ describe("in- and exports", () => {expectModulePassed("./empty-string-export-after-functions.mjs");});+ test("string module names preserve trailing NULs", () => {+ const result = expectModulePassed("./trailing-nul-export-names.mjs");+ expect(result.a).toBe(1);+ expect(result["a\0"]).toBe(2);+ expect(result["a\0\0"]).toBe(3);+ expect(result.ab).toBe(1);+ expect(result["ab\0"]).toBe(2);+ expect(result["ab\0\0"]).toBe(3);+ expect(result.b).toBe(4);+ expect(result["b\0\0"]).toBe(2);+ expect(result[""]).toBe(1);+ expect(result["\0"]).toBe(2);+ expect(result["\0\0"]).toBe(3);+ expect(result["only\0\0"]).toBe(3);+ expect(result).not.toHaveProperty("only");+ expect(result.readB()).toBe(4);+ expectModulePassed("./trailing-nul-import-names.mjs");+ });+test("can combine string and default exports", () => {expectModulePassed("./string-import-namespace.mjs");});diff --git a/Tests/LibJS/Runtime/modules/trailing-nul-export-names.mjs b/Tests/LibJS/Runtime/modules/trailing-nul-export-names.mjsnew file mode 100644index 00000000000..caf62455fe5--- /dev/null+++ b/Tests/LibJS/Runtime/modules/trailing-nul-export-names.mjs@@ -0,0 +1,18 @@+const a = 1;+const two = 2;+const three = 3;++export { a, two as "a\u0000", three as "a\u0000\u0000" };+export { a as "ab", two as "ab\u0000", three as "ab\u0000\u0000" };+export { a as "", two as "\u0000", three as "\u0000\u0000" };+export { three as "only\u0000\u0000" };++// Intern the NUL-containing name before the matching identifier. A lazy reparse+// of readB must still find the identifier's original ID.+export { two as "b\u0000\u0000", b };+const b = 4;+export function readB() {+ return b;+}++export const passed = true;diff --git a/Tests/LibJS/Runtime/modules/trailing-nul-import-names.mjs b/Tests/LibJS/Runtime/modules/trailing-nul-import-names.mjsnew file mode 100644index 00000000000..afade4539bf--- /dev/null+++ b/Tests/LibJS/Runtime/modules/trailing-nul-import-names.mjs@@ -0,0 +1,26 @@+import {+ a,+ "a\u0000" as oneNul,+ "a\u0000\u0000" as twoNuls,+ "ab\u0000" as twoByteName,+ b,+ "b\u0000\u0000" as nulBeforeIdentifier,+ "" as empty,+ "\u0000" as nul,+ "\u0000\u0000" as justNuls,+ "only\u0000\u0000" as only,+ readB,+} from "./trailing-nul-export-names.mjs";++export const passed =+ a === 1 &&+ oneNul === 2 &&+ twoNuls === 3 &&+ twoByteName === 2 &&+ b === 4 &&+ nulBeforeIdentifier === 2 &&+ empty === 1 &&+ nul === 2 &&+ justNuls === 3 &&+ only === 3 &&+ readB() === 4;