Skip to content

Truly independent web browser

LibJS: Give the first parse of a source a work zone

Andreas Kling11cba0dcba27
diff --git a/Libraries/LibJS/Rust/src/interpreter/vm.rs b/Libraries/LibJS/Rust/src/interpreter/vm.rs
index 87025034cc1..79249ae3bff 100644
--- a/Libraries/LibJS/Rust/src/interpreter/vm.rs
+++ b/Libraries/LibJS/Rust/src/interpreter/vm.rs
@@ -2425,6 +2425,7 @@ unsafe extern "C" fn sweep(context: *mut c_void) {
if vm.heap.get().is_some_and(Heap::is_returning_memory_to_system) {
crate::source_text::park_all_source_texts();
crate::runtime::regexp_prototype::clear_regex_cache();
+ crate::work_zone::release_idle_memory();
} else {
crate::source_text::park_idle_source_texts();
}
diff --git a/Libraries/LibJS/Rust/src/lib.rs b/Libraries/LibJS/Rust/src/lib.rs
index e2ce34c6c7a..f11262c92ec 100644
--- a/Libraries/LibJS/Rust/src/lib.rs
+++ b/Libraries/LibJS/Rust/src/lib.rs
@@ -166,6 +166,7 @@ pub mod unicode;
pub mod utf16;
#[cfg(not(test))]
pub mod utilities;
+mod work_zone;
#[cfg(test)]
mod test_host;
diff --git a/Libraries/LibJS/Rust/src/parser/mod.rs b/Libraries/LibJS/Rust/src/parser/mod.rs
index 3b42441ef71..fc916bcdcbd 100644
--- a/Libraries/LibJS/Rust/src/parser/mod.rs
+++ b/Libraries/LibJS/Rust/src/parser/mod.rs
@@ -31,6 +31,9 @@ use crate::ast::ScopeTable;
use crate::ast::SyntaxTree;
use crate::source_text::SourceText;
use crate::u32_from_usize;
+use crate::work_zone::with_work_zone;
+use ak::Zone;
+use ak::ZoneVec;
use base::Mode;
use base::Parser;
use columns::Ast;
@@ -415,9 +418,10 @@ impl LineTable {
(self.line_starts.capacity() + self.low_surrogates.capacity()) * size_of::<u32>()
}
- fn new<U: Unit>(source: &[U], initial_line_number: u32) -> Self {
- let mut line_starts = vec![0];
- let mut low_surrogates = Vec::new();
+ /// The table of `source`, which is worked out in `zone` and copied out at its final size.
+ fn new<U: Unit>(zone: &Zone, source: &[U], initial_line_number: u32) -> Self {
+ let mut line_starts = ZoneVec::from_slice_in(&[0], zone);
+ let mut low_surrogates = ZoneVec::new_in(zone);
let mut index = 0;
while index < source.len() {
let code_unit = source[index].code();
@@ -448,8 +452,8 @@ impl LineTable {
[] => false,
};
Self {
- line_starts,
- low_surrogates,
+ line_starts: line_starts.to_vec(),
+ low_surrogates: low_surrogates.to_vec(),
source_length: u32_from_usize(source.len()),
ends_with_lone_line_terminator,
initial_line_number,
@@ -597,13 +601,14 @@ struct ParserOutput {
lines: LineTable,
}
-/// Parses `source`, from a copy of it that is followed by the padding the lexer needs for as long as the parse takes.
+/// Parses `source`, from a copy of it in `zone` that is followed by the padding the lexer needs.
fn parse_code_units<U: Unit + Default>(
+ zone: &Zone,
source: &[U],
options: &ParseOptions,
purpose: ParsePurpose,
) -> Result<ParserOutput, Vec<ParseError>> {
- let mut padded = Vec::with_capacity(source.len() + SOURCE_PADDING);
+ let mut padded = ZoneVec::with_capacity_in(source.len() + SOURCE_PADDING, zone);
padded.extend_from_slice(source);
padded.resize(source.len() + SOURCE_PADDING, U::default());
// SAFETY: The source is followed by the padding.
@@ -622,7 +627,7 @@ fn parse_code_units<U: Unit + Default>(
parser.initiated_by_eval = options.initiated_by_eval;
parser.add_context(options.program_context().context);
let root = parser.parse_program();
- let lines = LineTable::new(source, options.initial_line_number);
+ let lines = LineTable::new(zone, source, options.initial_line_number);
if let Some(error) = parser.err.take() {
let position = lines.position(error.pos.min(u32_from_usize(source.len())));
return Err(vec![ParseError {
@@ -648,18 +653,18 @@ fn parse_code_units<U: Unit + Default>(
})
}
-/// Parses `source` at the width of its storage.
+/// Parses `source` at the width of its storage, with the work zone of the thread for the work data of the parse.
fn parse_source(
source: &ak::Utf16String,
options: &ParseOptions,
purpose: ParsePurpose,
) -> Result<ParserOutput, Vec<ParseError>> {
- match source.as_units() {
+ with_work_zone(|zone| match source.as_units() {
ak::Utf16StringUnits::Ascii(units) | ak::Utf16StringUnits::Latin1(units) => {
- parse_code_units(units, options, purpose)
+ parse_code_units(zone, units, options, purpose)
}
- ak::Utf16StringUnits::Utf16(units) => parse_code_units(units, options, purpose),
- }
+ ak::Utf16StringUnits::Utf16(units) => parse_code_units(zone, units, options, purpose),
+ })
}
/// Parses `source` into a tree of its top-level code with its identifiers resolved.
diff --git a/Libraries/LibJS/Rust/src/test_host.rs b/Libraries/LibJS/Rust/src/test_host.rs
index 747f3190830..18af4db1f46 100644
--- a/Libraries/LibJS/Rust/src/test_host.rs
+++ b/Libraries/LibJS/Rust/src/test_host.rs
@@ -147,3 +147,6 @@ extern "C" fn ladybird_utf16_string_create_uninitialized(length: usize, has_lati
#[unsafe(no_mangle)]
extern "C" fn ladybird_utf16_string_unref(_raw: usize) {}
+
+#[unsafe(no_mangle)]
+extern "C" fn ladybird_set_idle_thread_memory_release(_release: extern "C" fn()) {}
diff --git a/Libraries/LibJS/Rust/src/work_zone.rs b/Libraries/LibJS/Rust/src/work_zone.rs
new file mode 100644
index 00000000000..772568c3670
--- /dev/null
+++ b/Libraries/LibJS/Rust/src/work_zone.rs
@@ -0,0 +1,55 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The memory for the work data of a parse. A thread that parses has one zone, and each parse on the thread puts all of
+//! its work data in it. What a parse keeps is copied out of the zone before the parse ends, and the zone is empty again.
+//!
+//! The zone keeps its memory when a parse ends, for the next parse on the thread, so parses take no memory from the
+//! system and give none back. An outsized parse is the one exception: it gives back what is past the size that the
+//! zone keeps. All of the memory goes back when the thread goes idle (see `release_idle_memory()`).
+
+use std::cell::Cell;
+
+use ak::Zone;
+
+/// The most bytes that the work data of one parse can take. It is address space, which costs nothing before it is
+/// used, and it is far above what the largest source takes.
+const LIMIT: usize = 1 << 34;
+
+/// The most bytes of memory that the zone keeps for the next parse, about what a tree of 2^16 nodes takes. Nearly all
+/// parses need less.
+const MAXIMUM_SPARE_SIZE: usize = 1024 * 1024;
+
+thread_local! {
+ /// The zone of this thread, while no parse has it.
+ static SPARE_ZONE: Cell<Option<Zone>> = const { Cell::new(None) };
+}
+
+/// Runs `job` with the zone of the thread for its work data. Nothing that `job` returns can refer to the zone.
+pub(crate) fn with_work_zone<R>(job: impl for<'zone> FnOnce(&'zone Zone) -> R) -> R {
+ let mut zone = SPARE_ZONE.take().unwrap_or_else(|| {
+ ak::set_idle_thread_memory_release(release_idle_memory);
+ Zone::new(LIMIT, c"JS parse work")
+ });
+ let mut size = 0;
+ let result = zone.scope(|zone| {
+ let result = job(zone);
+ size = zone.used();
+ result
+ });
+ // NB: Give back the memory of an outsized parse rather than keep it until the thread goes idle.
+ if size > MAXIMUM_SPARE_SIZE {
+ zone.trim(MAXIMUM_SPARE_SIZE);
+ }
+ SPARE_ZONE.set(Some(zone));
+ result
+}
+
+/// Gives the memory of the zone of this thread back to the system. A thread pool calls this on a thread that goes idle
+/// (see `ak::set_idle_thread_memory_release()`).
+pub(crate) extern "C" fn release_idle_memory() {
+ drop(SPARE_ZONE.take());
+}