Skip to content

Truly independent web browser

LibJS: Compress the text of sources that nothing reads

Andreas Klingc8b525ec3f0a
diff --git a/Cargo.lock b/Cargo.lock
index 6b96cdbe5ec..555402973fb 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1869,6 +1869,7 @@ dependencies = [
"indexmap",
"ladybird_allocator",
"libc",
+ "libcompress_rust",
"libjs_abi",
"libjs_jit",
"libjs_runtime_macros",
diff --git a/Libraries/LibJS/Rust/Cargo.toml b/Libraries/LibJS/Rust/Cargo.toml
index 1344bc94456..5a1fb944fad 100644
--- a/Libraries/LibJS/Rust/Cargo.toml
+++ b/Libraries/LibJS/Rust/Cargo.toml
@@ -24,6 +24,7 @@ hashbrown = { version = "0.17.1", default-features = false }
indexmap = "2"
ladybird_allocator = { path = "../../RustAllocator", optional = true }
libc = "0.2"
+libcompress_rust = { path = "../../LibCompress/Rust" }
libjs_abi = { path = "../ABI" }
libjs_jit = { path = "../JIT/Rust", optional = true }
libjs_runtime_macros = { path = "macros" }
diff --git a/Libraries/LibJS/Rust/src/ast.rs b/Libraries/LibJS/Rust/src/ast.rs
index 847efdb970b..985f4d4d4e0 100644
--- a/Libraries/LibJS/Rust/src/ast.rs
+++ b/Libraries/LibJS/Rust/src/ast.rs
@@ -565,6 +565,8 @@ impl ScopeTable {
pub struct SyntaxTree {
/// What stays of the source once the tree is gone.
pub(crate) script: Arc<ScriptData>,
+ /// The text of the source, which stays as it is for as long as the tree holds it.
+ pub(crate) source: ak::Utf16String,
pub(crate) ast: Ast,
pub(crate) root: u32,
pub(crate) first_token_start: u32,
@@ -635,7 +637,7 @@ impl SyntaxTree {
}
fn source_text(&self) -> Utf16View<'_> {
- Utf16View::of_string(&self.script.positions.source)
+ Utf16View::of_string(&self.source)
}
pub(crate) fn source_units(&self, start: u32, end: u32) -> Utf16View<'_> {
diff --git a/Libraries/LibJS/Rust/src/bytecode/codegen/nodes.rs b/Libraries/LibJS/Rust/src/bytecode/codegen/nodes.rs
index 10828904151..228f71fb60c 100644
--- a/Libraries/LibJS/Rust/src/bytecode/codegen/nodes.rs
+++ b/Libraries/LibJS/Rust/src/bytecode/codegen/nodes.rs
@@ -228,7 +228,7 @@ impl SyntaxTree {
/// The text between two offsets of the source.
#[inline(always)]
pub(super) fn source_range_units(&self, start: u32, end: u32) -> Utf16View<'_> {
- Utf16View::of_string(&self.script.positions.source).substring_view(start as usize, (end - start) as usize)
+ Utf16View::of_string(&self.source).substring_view(start as usize, (end - start) as usize)
}
/// The text between the quotes of a string literal node.
diff --git a/Libraries/LibJS/Rust/src/bytecode/executable.rs b/Libraries/LibJS/Rust/src/bytecode/executable.rs
index ff402d2cadd..b6872aa093c 100644
--- a/Libraries/LibJS/Rust/src/bytecode/executable.rs
+++ b/Libraries/LibJS/Rust/src/bytecode/executable.rs
@@ -1692,7 +1692,8 @@ impl Executable {
return None;
}
let source_offset = source_offset.0 as usize;
- let view = crate::utf16::Utf16View::of_string(&positions.source);
+ let source = positions.source.get();
+ let view = crate::utf16::Utf16View::of_string(&source);
let start = source_offset.saturating_sub(LONGEST_TEXT);
let end = (source_offset + LONGEST_TEXT).min(view.length_in_code_units());
let units = view.substring_view(start, end - start).code_units().collect();
diff --git a/Libraries/LibJS/Rust/src/compile.rs b/Libraries/LibJS/Rust/src/compile.rs
index add3640799b..aa69e4e7f58 100644
--- a/Libraries/LibJS/Rust/src/compile.rs
+++ b/Libraries/LibJS/Rust/src/compile.rs
@@ -115,13 +115,7 @@ impl ParsedProgram {
/// first use.
pub fn ast_dump(&mut self) -> &str {
self.ast_dump.get_or_insert_with(|| {
- let source = &self
- .tree
- .as_ref()
- .expect("the program has a tree")
- .script
- .positions
- .source;
+ let source = &self.tree.as_ref().expect("the program has a tree").source;
let mut options = self.options;
options.keep_whole_tree = true;
let tree = parse_to_tree(source, &options)
diff --git a/Libraries/LibJS/Rust/src/embedding/source_code.rs b/Libraries/LibJS/Rust/src/embedding/source_code.rs
index c66196a7d13..c63ccf7be1a 100644
--- a/Libraries/LibJS/Rust/src/embedding/source_code.rs
+++ b/Libraries/LibJS/Rust/src/embedding/source_code.rs
@@ -14,7 +14,9 @@
use std::rc::Rc;
use crate::bytecode::executable::Executable;
-use crate::embedding::abi_types::{JSOwnedUtf16String, JSSourceCode, owned_utf16_string_from_abi};
+use crate::embedding::abi_types::{
+ JSOwnedUtf16String, JSSourceCode, owned_utf16_string_from_abi, owned_utf16_string_into_abi,
+};
use crate::embedding::execution_context::JSExecutionContext;
use crate::layout::execution_context::ExecutionContext;
use crate::source_code::SourceCode;
@@ -114,17 +116,17 @@ pub unsafe extern "C" fn js_source_code_filename_address(
core::ptr::from_ref(source_code.filename()).cast()
}
-/// SourceCode::code() as C++ returns it, by reference: the address of the source code's AK::Utf16String, which stays
-/// where it is, unchanged, for as long as the source code lives. Only the VM's thread may call this.
+/// SourceCode::code(): the code as an AK::Utf16String whose one reference the caller owns. The runtime may hold the
+/// code compressed, so there is no string of it to return by reference. Only the VM's thread may call this.
///
/// # Safety
///
/// `source_code` must be live source code.
#[unsafe(no_mangle)]
-pub unsafe extern "C" fn js_source_code_code_address(source_code: *const JSSourceCode) -> *const JSOwnedUtf16String {
+pub unsafe extern "C" fn js_source_code_code(source_code: *const JSSourceCode) -> JSOwnedUtf16String {
// SAFETY: The caller passes live source code.
let source_code = unsafe { source_code_from_abi(source_code) };
- core::ptr::from_ref(source_code.code()).cast()
+ owned_utf16_string_into_abi(source_code.code())
}
/// ExecutionContext::source_code(): the source code of the bytecode the context runs, or null if it runs none, as for a
diff --git a/Libraries/LibJS/Rust/src/interpreter/vm.rs b/Libraries/LibJS/Rust/src/interpreter/vm.rs
index 1cce7fb7dad..6e8074a7eef 100644
--- a/Libraries/LibJS/Rust/src/interpreter/vm.rs
+++ b/Libraries/LibJS/Rust/src/interpreter/vm.rs
@@ -2257,6 +2257,7 @@ unsafe extern "C" fn sweep(context: *mut c_void) {
let sweep = unsafe { Sweep::new(vm) };
vm.code_flushing.finish_pass(vm, &sweep);
crate::parser::release_idle_reparse_contexts();
+ crate::source_text::park_idle_source_texts();
vm.remove_dead_cells_from_weak_containers(&sweep);
vm.remove_dead_strings_from_weak_caches(&sweep);
vm.remove_dead_cells_from_property_lookup_caches(&sweep);
diff --git a/Libraries/LibJS/Rust/src/lib.rs b/Libraries/LibJS/Rust/src/lib.rs
index e75afe2a5fc..52e47a4215c 100644
--- a/Libraries/LibJS/Rust/src/lib.rs
+++ b/Libraries/LibJS/Rust/src/lib.rs
@@ -149,6 +149,7 @@ pub mod slice_block;
pub mod source_code;
#[cfg(not(test))]
pub mod source_range;
+pub mod source_text;
#[cfg(not(test))]
pub mod standard_output;
pub mod token;
diff --git a/Libraries/LibJS/Rust/src/parser/mod.rs b/Libraries/LibJS/Rust/src/parser/mod.rs
index a960766f0bb..71671ffa591 100644
--- a/Libraries/LibJS/Rust/src/parser/mod.rs
+++ b/Libraries/LibJS/Rust/src/parser/mod.rs
@@ -29,6 +29,7 @@ use crate::ast::ProgramType;
use crate::ast::Resolution;
use crate::ast::ScopeTable;
use crate::ast::SyntaxTree;
+use crate::source_text::SourceText;
use crate::u32_from_usize;
use base::Mode;
use base::Parser;
@@ -213,7 +214,7 @@ impl ScriptData {
/// The bytes of this source and of the tables that compile jobs read, and of the code kept for its functions so far.
pub(crate) fn memory_size(&self) -> usize {
size_of::<Self>()
- + crate::compile::utf16_string_memory_size(&self.positions.source)
+ + self.positions.source.memory_size()
+ self.index.memory_size()
+ self.names.memory_size()
+ self.positions.lines.memory_size()
@@ -227,6 +228,7 @@ impl ScriptData {
let (ast, node) = rows.expect("a top level compiles once")?;
let tree = SyntaxTree {
script: self.clone(),
+ source: self.positions.source.get(),
ast,
root: node,
first_token_start: 0,
@@ -255,6 +257,7 @@ impl ScriptData {
scopes: ScopeTable::default(),
function_scope_rows: Vec::new(),
});
+ let source = self.positions.source.get();
let (ast, node) = {
let mut context = self.reparse_context.lock().expect("a reparse does not panic");
if context.is_none() {
@@ -266,7 +269,7 @@ impl ScriptData {
}
self.reparse_context_idle_collections.store(0, Ordering::Relaxed);
let context = context.as_mut().expect("the context was just filled in");
- let result = match (context, self.positions.source.as_units()) {
+ let result = match (context, source.as_units()) {
(
ReparseContext::Narrow(parser),
ak::Utf16StringUnits::Ascii(units) | ak::Utf16StringUnits::Latin1(units),
@@ -294,6 +297,7 @@ impl ScriptData {
}?;
let tree = SyntaxTree {
script: self.clone(),
+ source,
ast,
root: node,
first_token_start: 0,
@@ -312,17 +316,15 @@ impl ScriptData {
fn make_reparse_context(&self) -> ReparseContext {
let module = self.program_type == ProgramType::Module;
let length = u32_from_usize(self.positions.source.length_in_code_units());
+ let is_wide = self.positions.source.is_wide();
let interner = Interner::with_names(self.names.parser_names());
// SAFETY: The context lives in this ScriptData, whose index stays where it is, since it is shared by an Arc,
// and never changes.
unsafe {
- match self.positions.source.as_units() {
- ak::Utf16StringUnits::Ascii(_) | ak::Utf16StringUnits::Latin1(_) => {
- ReparseContext::Narrow(Box::new(Parser::for_reparsing(module, interner, &self.index, length)))
- }
- ak::Utf16StringUnits::Utf16(_) => {
- ReparseContext::Wide(Box::new(Parser::for_reparsing(module, interner, &self.index, length)))
- }
+ if is_wide {
+ ReparseContext::Wide(Box::new(Parser::for_reparsing(module, interner, &self.index, length)))
+ } else {
+ ReparseContext::Narrow(Box::new(Parser::for_reparsing(module, interner, &self.index, length)))
}
}
}
@@ -387,7 +389,7 @@ pub struct ParseError {
/// What code needs of its source to report positions, which it keeps for as long as it lives. That can be long after the
/// rest of [`ScriptData`] is of no use to anything.
pub struct SourcePositions {
- pub(crate) source: ak::Utf16String,
+ pub(crate) source: Arc<SourceText>,
pub(crate) lines: LineTable,
}
@@ -665,7 +667,7 @@ pub fn parse_to_tree(source: &ak::Utf16String, options: &ParseOptions) -> Result
index: output.index,
names,
positions: Arc::new(SourcePositions {
- source: source.clone(),
+ source: SourceText::of(source),
lines: output.lines,
}),
program_type: options.program_type,
@@ -681,6 +683,7 @@ pub fn parse_to_tree(source: &ak::Utf16String, options: &ParseOptions) -> Result
});
let mut tree = SyntaxTree {
script,
+ source: source.clone(),
ast: output.ast,
root: output.root,
first_token_start: output.first_token_start,
diff --git a/Libraries/LibJS/Rust/src/runtime/abstract_operations.rs b/Libraries/LibJS/Rust/src/runtime/abstract_operations.rs
index 2964762afdb..903387e4371 100644
--- a/Libraries/LibJS/Rust/src/runtime/abstract_operations.rs
+++ b/Libraries/LibJS/Rust/src/runtime/abstract_operations.rs
@@ -1346,7 +1346,7 @@ fn compile_eval(
allow_super_constructor_call: in_derived_constructor,
in_class_field_initializer,
};
- let parsed = parse_eval(source_code.code(), context).map_err(|errors| {
+ let parsed = parse_eval(&source_code.code(), context).map_err(|errors| {
errors
.first()
.map(|error| format!("{} (line: {}, column: {})", error.message, error.line, error.column))
diff --git a/Libraries/LibJS/Rust/src/runtime/function_constructor.rs b/Libraries/LibJS/Rust/src/runtime/function_constructor.rs
index e2fc2943bf5..14c902d58fe 100644
--- a/Libraries/LibJS/Rust/src/runtime/function_constructor.rs
+++ b/Libraries/LibJS/Rust/src/runtime/function_constructor.rs
@@ -326,7 +326,7 @@ pub fn compile_dynamic_function(
) -> Result<Gc<SharedFunctionInstanceData>, ParserError> {
let source_code = SourceCode::create(Utf16String::default(), source_text.clone());
let description =
- crate::compile::parse_dynamic_function(source_code.code(), parameters_string, body_parse_string, kind)
+ crate::compile::parse_dynamic_function(&source_code.code(), parameters_string, body_parse_string, kind)
.and_then(crate::compile::ParsedDynamicFunction::into_description);
let description = match description {
Ok(description) => description,
diff --git a/Libraries/LibJS/Rust/src/runtime/intrinsics.rs b/Libraries/LibJS/Rust/src/runtime/intrinsics.rs
index c3475f9d975..01dc4ed02b3 100644
--- a/Libraries/LibJS/Rust/src/runtime/intrinsics.rs
+++ b/Libraries/LibJS/Rust/src/runtime/intrinsics.rs
@@ -856,7 +856,7 @@ pub(crate) fn parse_builtin_file<'vm>(
Utf16String::from_utf8("BuiltinFile"),
Utf16String::from_utf8(script_text),
);
- let parsed = crate::compile::parse_builtin_file(code.code());
+ let parsed = crate::compile::parse_builtin_file(&code.code());
Rc::new((code, parsed))
})
.clone()
diff --git a/Libraries/LibJS/Rust/src/runtime/source_text_module.rs b/Libraries/LibJS/Rust/src/runtime/source_text_module.rs
index 763d9e3a35f..3b803abbe5c 100644
--- a/Libraries/LibJS/Rust/src/runtime/source_text_module.rs
+++ b/Libraries/LibJS/Rust/src/runtime/source_text_module.rs
@@ -172,7 +172,7 @@ impl SourceTextModule {
host_defined: ForeignCellSlot,
line_number_offset: usize,
) -> Result<Gc<SourceTextModule>, Vec<ParserError>> {
- let parsed = parse(source_code.code(), ProgramType::Module, line_number_offset);
+ let parsed = parse(&source_code.code(), ProgramType::Module, line_number_offset);
if parsed.has_errors() {
return Err(ParserError::all_from_parsed_program(&parsed));
}
diff --git a/Libraries/LibJS/Rust/src/source_code.rs b/Libraries/LibJS/Rust/src/source_code.rs
index 78a01e86648..0cf91b70f11 100644
--- a/Libraries/LibJS/Rust/src/source_code.rs
+++ b/Libraries/LibJS/Rust/src/source_code.rs
@@ -8,31 +8,37 @@
//! recover their [[SourceText]].
use std::rc::Rc;
+use std::sync::Arc;
use ak::Utf16String;
+use crate::source_text::SourceText;
use crate::utf16::Utf16View;
pub struct SourceCode {
filename: Utf16String,
- code: Utf16String,
+ code: Arc<SourceText>,
}
impl SourceCode {
pub fn create(filename: Utf16String, code: Utf16String) -> Rc<SourceCode> {
- Rc::new(Self { filename, code })
+ Rc::new(Self {
+ filename,
+ code: SourceText::of(&code),
+ })
}
pub fn filename(&self) -> &Utf16String {
&self.filename
}
- pub fn code(&self) -> &Utf16String {
- &self.code
+ /// The code, which is decompressed first if nothing asked for it in a while (see [`SourceText`]).
+ pub fn code(&self) -> Utf16String {
+ self.code.get()
}
pub fn length_in_code_units(&self) -> usize {
- Utf16View::of_string(&self.code).length_in_code_units()
+ self.code.length_in_code_units()
}
pub fn source_text_from_offsets(&self, start_offset: usize, length: usize) -> Utf16String {
@@ -42,7 +48,7 @@ impl SourceCode {
assert!(start_offset <= usize::MAX - length);
- Utf16View::of_string(&self.code)
+ Utf16View::of_string(&self.code.get())
.substring_view(start_offset, length)
.to_utf16_string()
}
diff --git a/Libraries/LibJS/Rust/src/source_text.rs b/Libraries/LibJS/Rust/src/source_text.rs
new file mode 100644
index 00000000000..7fa7900c29b
--- /dev/null
+++ b/Libraries/LibJS/Rust/src/source_text.rs
@@ -0,0 +1,417 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The text of a source, which is parked while nothing reads it: a large text that nothing asked for in a while is
+//! compressed, and the next one to ask for it gets it decompressed.
+//!
+//! A source keeps its text for as long as it lives, to compile its functions when they are first called and to give
+//! them their [[SourceText]]. Most functions of a page compile while it loads or never, so after that the text is
+//! mostly dead weight, and for script-heavy pages it is the largest single thing the engine holds.
+//!
+//! Collections decide what to park: the sweep of a collection looks for texts that idled long enough and hands them to
+//! a thread that compresses them. A text that something asked for in the meantime stays as it is.
+//!
+//! Nothing may keep a reference into the text of a source across the calls of [`SourceText::get()`]: what a caller
+//! reads belongs to the string that the call gave it, and that string stays alive on its own.
+
+use std::collections::HashMap;
+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
+use std::sync::{Arc, Mutex, OnceLock, Weak};
+use std::time::{Duration, Instant};
+
+use ak::{Utf16String, Utf16StringUnits};
+use libcompress_rust::{Compressor, Decompressor, Format};
+
+/// The smallest text that is worth parking, in bytes.
+const SMALLEST_PARKED_TEXT_SIZE: usize = 10 * 1024;
+
+/// How long nothing has to ask for a text before it is parked.
+const IDLE_TIME_BEFORE_PARKING: Duration = Duration::from_secs(20);
+
+/// A parked text has to be at most this share of its size, or it stays as it is.
+const LARGEST_PARKED_SHARE: (usize, usize) = (3, 4);
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+enum Storage {
+ Ascii,
+ Latin1,
+ Utf16,
+}
+
+struct ParkedText {
+ /// The code units, each as its bytes in the order of this machine, compressed.
+ compressed: Box<[u8]>,
+ storage: Storage,
+}
+
+enum State {
+ Present(Utf16String),
+ Parked(ParkedText),
+}
+
+pub struct SourceText {
+ state: Mutex<State>,
+ length_in_code_units: usize,
+ /// Whether the text holds its code units in 16 bits each, which stays the same while it is parked.
+ is_wide: bool,
+ /// How often something asked for the text.
+ use_count: AtomicU64,
+ /// When something last asked for the text, in milliseconds since the first text was made.
+ last_use_time: AtomicU64,
+ /// Whether the text turned out to be better off as it is, so that no collection tries to park it again.
+ stays_present: AtomicBool,
+}
+
+/// A text that idled long enough, with what a thread needs to park it.
+struct ParkingCandidate {
+ source_text: Arc<SourceText>,
+ text: Utf16String,
+ use_count: u64,
+}
+
+#[derive(Default)]
+struct Registry {
+ /// The texts that can be parked.
+ texts: Vec<Weak<SourceText>>,
+ /// The texts that are present, by the identity of their strings, so that the holders of one string share one text.
+ present_by_identity: HashMap<usize, Weak<SourceText>>,
+}
+
+fn registry() -> &'static Mutex<Registry> {
+ static REGISTRY: OnceLock<Mutex<Registry>> = OnceLock::new();
+ REGISTRY.get_or_init(Mutex::default)
+}
+
+fn milliseconds_now() -> u64 {
+ static START: OnceLock<Instant> = OnceLock::new();
+ u64::try_from(START.get_or_init(Instant::now).elapsed().as_millis()).unwrap_or(u64::MAX)
+}
+
+fn storage_of(text: &Utf16String) -> (Storage, usize) {
+ match text.as_units() {
+ Utf16StringUnits::Ascii(units) => (Storage::Ascii, units.len()),
+ Utf16StringUnits::Latin1(units) => (Storage::Latin1, units.len()),
+ Utf16StringUnits::Utf16(units) => (Storage::Utf16, size_of_val(units)),
+ }
+}
+
+impl SourceText {
+ /// The text of a source that holds `text`. Sources made of one large string share one text, so that parking it frees
+ /// the string.
+ pub fn of(text: &Utf16String) -> Arc<Self> {
+ let (storage, size) = storage_of(text);
+ let make = || {
+ Arc::new(Self {
+ state: Mutex::new(State::Present(text.clone())),
+ length_in_code_units: if storage == Storage::Utf16 { size / 2 } else { size },
+ is_wide: storage == Storage::Utf16,
+ use_count: AtomicU64::new(0),
+ last_use_time: AtomicU64::new(milliseconds_now()),
+ stays_present: AtomicBool::new(false),
+ })
+ };
+ if size < SMALLEST_PARKED_TEXT_SIZE {
+ return make();
+ }
+ let identity = text.raw_identity();
+ let mut registry = registry().lock().expect("nothing panics with the registry");
+ if let Some(source_text) = registry.present_by_identity.get(&identity).and_then(Weak::upgrade) {
+ source_text.note_use();
+ return source_text;
+ }
+ let source_text = make();
+ registry.texts.push(Arc::downgrade(&source_text));
+ registry
+ .present_by_identity
+ .insert(identity, Arc::downgrade(&source_text));
+ source_text
+ }
+
+ fn note_use(&self) {
+ self.use_count.fetch_add(1, Ordering::Relaxed);
+ self.last_use_time.store(milliseconds_now(), Ordering::Relaxed);
+ }
+
+ /// The text, which is decompressed first if it is parked.
+ pub fn get(&self) -> Utf16String {
+ self.note_use();
+ let mut state = self.state.lock().expect("nothing panics with a text");
+ match &*state {
+ State::Present(text) => text.clone(),
+ State::Parked(parked) => {
+ let text = parked.unparked(self.length_in_code_units);
+ *state = State::Present(text.clone());
+ text
+ }
+ }
+ }
+
+ pub fn length_in_code_units(&self) -> usize {
+ self.length_in_code_units
+ }
+
+ /// Whether the text holds its code units in 16 bits each.
+ pub fn is_wide(&self) -> bool {
+ self.is_wide
+ }
+
+ /// The bytes that the text takes up right now.
+ pub fn memory_size(&self) -> usize {
+ match &*self.state.lock().expect("nothing panics with a text") {
+ State::Present(text) => storage_of(text).1,
+ State::Parked(parked) => parked.compressed.len(),
+ }
+ }
+
+ fn is_parked(&self) -> bool {
+ matches!(
+ &*self.state.lock().expect("nothing panics with a text"),
+ State::Parked(_)
+ )
+ }
+}
+
+impl ParkedText {
+ /// The parked form of `text`, or `None` if the text is better off as it is.
+ fn of(text: &Utf16String) -> Option<Self> {
+ let (storage, size) = storage_of(text);
+ let mut compressor = Compressor::new(Format::Deflate);
+ let mut compressed = match text.as_units() {
+ Utf16StringUnits::Ascii(units) | Utf16StringUnits::Latin1(units) => compressor.compress(units).ok()?,
+ Utf16StringUnits::Utf16(units) => {
+ // NB: A string of narrow code units comes back from Utf16String::from_utf16() with one byte for each,
+ // and the parser of a source goes by the width that the text had at first.
+ if units.iter().all(|&unit| unit <= 0xFF) {
+ return None;
+ }
+ let mut compressed = Vec::new();
+ for chunk in units.chunks(1 << 16) {
+ let bytes: Vec<u8> = chunk.iter().flat_map(|unit| unit.to_ne_bytes()).collect();
+ compressed.extend(compressor.compress(&bytes).ok()?);
+ }
+ compressed
+ }
+ };
+ compressed.extend(compressor.finish().ok()?);
+ if compressed.len() > size / LARGEST_PARKED_SHARE.1 * LARGEST_PARKED_SHARE.0 {
+ return None;
+ }
+ Some(Self {
+ compressed: compressed.into_boxed_slice(),
+ storage,
+ })
+ }
+
+ fn unparked(&self, length_in_code_units: usize) -> Utf16String {
+ let bytes = Decompressor::new(Format::Deflate)
+ .decompress(&self.compressed)
+ .expect("a parked text is what the compressor made of it")
+ .output;
+ let text = match self.storage {
+ Storage::Ascii => Utf16String::from_ascii(&bytes),
+ Storage::Latin1 => Utf16String::from_latin1(&bytes),
+ Storage::Utf16 => {
+ let units: Vec<u16> = bytes
+ .as_chunks::<2>()
+ .0
+ .iter()
+ .map(|bytes| u16::from_ne_bytes(*bytes))
+ .collect();
+ Utf16String::from_utf16(&units)
+ }
+ };
+ assert_eq!(storage_of(&text).0 == Storage::Utf16, self.storage == Storage::Utf16);
+ assert_eq!(
+ match text.as_units() {
+ Utf16StringUnits::Ascii(units) | Utf16StringUnits::Latin1(units) => units.len(),
+ Utf16StringUnits::Utf16(units) => units.len(),
+ },
+ length_in_code_units
+ );
+ text
+ }
+}
+
+impl ParkingCandidate {
+ /// Parks the text, unless something asked for it since it became a candidate.
+ fn park(self) {
+ let Some(parked) = ParkedText::of(&self.text) else {
+ // NB: The text never changes, so compressing it again would come to the same.
+ self.source_text.stays_present.store(true, Ordering::Relaxed);
+ return;
+ };
+ let identity = self.text.raw_identity();
+ let mut registry = registry().lock().expect("nothing panics with the registry");
+ let mut state = self.source_text.state.lock().expect("nothing panics with a text");
+ if self.source_text.use_count.load(Ordering::Relaxed) != self.use_count {
+ return;
+ }
+ // NB: The string can be freed once it is parked, and its identity can then become that of another string.
+ if registry
+ .present_by_identity
+ .get(&identity)
+ .is_some_and(|present| core::ptr::eq(present.as_ptr(), Arc::as_ptr(&self.source_text)))
+ {
+ registry.present_by_identity.remove(&identity);
+ }
+ *state = State::Parked(parked);
+ }
+}
+
+/// The texts that nothing asked for in `idle_time`.
+fn parking_candidates(idle_time: Duration) -> Vec<ParkingCandidate> {
+ let now = milliseconds_now();
+ let idle_time = u64::try_from(idle_time.as_millis()).unwrap_or(u64::MAX);
+ let mut candidates = Vec::new();
+ let mut registry = registry().lock().expect("nothing panics with the registry");
+ registry.texts.retain(|source_text| {
+ let Some(source_text) = source_text.upgrade() else {
+ return false;
+ };
+ if source_text.stays_present.load(Ordering::Relaxed) {
+ return false;
+ }
+ let use_count = source_text.use_count.load(Ordering::Relaxed);
+ if now.saturating_sub(source_text.last_use_time.load(Ordering::Relaxed)) < idle_time {
+ return true;
+ }
+ // NB: Something that holds the text is reading it.
+ let Ok(state) = source_text.state.try_lock() else {
+ return true;
+ };
+ if let State::Present(text) = &*state {
+ let text = text.clone();
+ drop(state);
+ candidates.push(ParkingCandidate {
+ source_text,
+ text,
+ use_count,
+ });
+ }
+ true
+ });
+ registry.present_by_identity.retain(|_, text| text.strong_count() > 0);
+ candidates
+}
+
+/// Parks every text that can be parked, whatever its age, before it returns, and returns how many it parked. Tests call
+/// this.
+pub fn park_all_source_texts_now() -> usize {
+ let candidates = parking_candidates(Duration::ZERO);
+ let source_texts: Vec<_> = candidates
+ .iter()
+ .map(|candidate| candidate.source_text.clone())
+ .collect();
+ for candidate in candidates {
+ candidate.park();
+ }
+ source_texts
+ .iter()
+ .filter(|source_text| source_text.is_parked())
+ .count()
+}
+
+/// Parks the texts that nothing asked for in a while, on a thread of their own. Collections call this.
+pub fn park_idle_source_texts() {
+ static IS_PARKING: AtomicBool = AtomicBool::new(false);
+ if IS_PARKING.swap(true, Ordering::Acquire) {
+ return;
+ }
+ let candidates = parking_candidates(IDLE_TIME_BEFORE_PARKING);
+ if candidates.is_empty() {
+ IS_PARKING.store(false, Ordering::Release);
+ return;
+ }
+ let park = move || {
+ for candidate in candidates {
+ candidate.park();
+ }
+ // NB: The allocator keeps what a thread freed until the thread allocates again, which this one never does.
+ ak::release_unused_allocator_memory();
+ IS_PARKING.store(false, Ordering::Release);
+ };
+ if std::thread::Builder::new()
+ .name("LibJS source parking".into())
+ .spawn(park)
+ .is_err()
+ {
+ IS_PARKING.store(false, Ordering::Release);
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// Parking looks at every text there is, so the tests that park take turns.
+ static TURN: Mutex<()> = Mutex::new(());
+
+ fn large_text(with: &str) -> String {
+ let mut text = String::new();
+ while text.len() < 4 * SMALLEST_PARKED_TEXT_SIZE {
+ text.push_str("function f() { return 'some text that repeats'; }\n");
+ }
+ text.push_str(with);
+ text
+ }
+
+ #[test]
+ fn a_parked_text_comes_back_as_it_was() {
+ let _turn = TURN.lock();
+ let latin1 = large_text("").bytes().chain([0xE9]).collect::<Vec<u8>>();
+ for text in [
+ Utf16String::from_utf8(&large_text("")),
+ Utf16String::from_latin1(&latin1),
+ Utf16String::from_utf8(&large_text("\u{2019}\u{1f600}")),
+ ] {
+ let source_text = SourceText::of(&text);
+ let size = source_text.memory_size();
+ park_all_source_texts_now();
+ assert!(source_text.is_parked());
+ assert!(source_text.memory_size() < size / 4);
+ let unparked = source_text.get();
+ assert!(!source_text.is_parked());
+ assert!(unparked == text);
+ assert_eq!(source_text.memory_size(), size);
+ assert_eq!(
+ source_text.is_wide(),
+ matches!(unparked.as_units(), Utf16StringUnits::Utf16(_))
+ );
+ }
+ }
+
+ #[test]
+ fn a_text_that_was_asked_for_meanwhile_stays_present() {
+ let _turn = TURN.lock();
+ let text = Utf16String::from_utf8(&large_text("meanwhile"));
+ let source_text = SourceText::of(&text);
+ let candidates = parking_candidates(Duration::ZERO);
+ source_text.get();
+ for candidate in candidates {
+ candidate.park();
+ }
+ assert!(!source_text.is_parked());
+ }
+
+ #[test]
+ fn holders_of_one_string_share_one_text() {
+ let _turn = TURN.lock();
+ let text = Utf16String::from_utf8(&large_text("shared"));
+ let source_text = SourceText::of(&text);
+ assert!(Arc::ptr_eq(&source_text, &SourceText::of(&text)));
+ park_all_source_texts_now();
+ assert!(source_text.is_parked());
+ assert!(!Arc::ptr_eq(&source_text, &SourceText::of(&source_text.get())));
+ }
+
+ #[test]
+ fn a_small_text_is_not_parked() {
+ let _turn = TURN.lock();
+ let source_text = SourceText::of(&Utf16String::from_utf8("let a = 1;"));
+ park_all_source_texts_now();
+ assert!(!source_text.is_parked());
+ }
+}
diff --git a/Libraries/LibJS/Rust/src/utilities/test_js/test_js_functions.rs b/Libraries/LibJS/Rust/src/utilities/test_js/test_js_functions.rs
index 2d6ef5fd995..ed5646fb4a9 100644
--- a/Libraries/LibJS/Rust/src/utilities/test_js/test_js_functions.rs
+++ b/Libraries/LibJS/Rust/src/utilities/test_js/test_js_functions.rs
@@ -54,6 +54,7 @@ pub const EXPOSED_GLOBAL_FUNCTIONS: &[(&str, RawNativeFunctionPointer)] = &[
("gc", raw_native!(collect_garbage)),
("flushCode", raw_native!(flush_code)),
("isCodeFlushed", raw_native!(is_code_flushed)),
+ ("parkSourceTexts", raw_native!(park_source_texts)),
(
"collectGarbageOnEveryAllocation",
raw_native!(collect_garbage_on_every_allocation),
@@ -148,6 +149,12 @@ fn flush_code(vm: &Vm) -> ThrowCompletionOr<Value> {
Ok(Value::UNDEFINED)
}
+/// Compresses every source text that is large enough for that, whatever its age, and returns how many there are.
+#[allow(clippy::unnecessary_wraps, reason = "native functions return a completion")]
+fn park_source_texts(_vm: &Vm) -> ThrowCompletionOr<Value> {
+ Ok(Value::from_f64(crate::source_text::park_all_source_texts_now() as f64))
+}
+
/// Whether the code of a function was flushed, and not compiled again yet.
fn is_code_flushed(vm: &Vm) -> ThrowCompletionOr<Value> {
let Some(function) = as_if::<EcmascriptFunctionObject>(vm.argument(0)) else {
diff --git a/Libraries/LibJS/ScriptCompilation.cpp b/Libraries/LibJS/ScriptCompilation.cpp
index 5b2fb057b9f..247b5c3e35b 100644
--- a/Libraries/LibJS/ScriptCompilation.cpp
+++ b/Libraries/LibJS/ScriptCompilation.cpp
@@ -83,7 +83,8 @@ Vector<Position> breakpoint_positions_for_source(SourceCode const& source_code,
static_cast<Vector<Position>*>(context)->append(reinterpret_cast<Position const*>(abi_positions), count);
},
};
- js_compile_breakpoint_positions_for_source(utf16_view_to_abi(source_code.code().utf16_view()), program_type_to_abi(program_type), line_number_offset, &sink);
+ auto code = source_code.code();
+ js_compile_breakpoint_positions_for_source(utf16_view_to_abi(code.utf16_view()), program_type_to_abi(program_type), line_number_offset, &sink);
return positions;
}
diff --git a/Libraries/LibJS/SourceCode.cpp b/Libraries/LibJS/SourceCode.cpp
index 77e2023146b..df5098afed7 100644
--- a/Libraries/LibJS/SourceCode.cpp
+++ b/Libraries/LibJS/SourceCode.cpp
@@ -32,9 +32,9 @@ Utf16String const& SourceCode::filename() const
return string_in_place_from_abi(js_source_code_filename_address(source_code_to_abi(*this)));
}
-Utf16String const& SourceCode::code() const
+Utf16String SourceCode::code() const
{
- return string_in_place_from_abi(js_source_code_code_address(source_code_to_abi(*this)));
+ return owned_utf16_string_from_abi(js_source_code_code(source_code_to_abi(*this)));
}
size_t SourceCode::length_in_code_units() const
@@ -48,7 +48,8 @@ Utf16String SourceCode::source_text_from_offsets(size_t start_offset, size_t len
return {};
VERIFY(start_offset <= NumericLimits<size_t>::max() - length);
- return Utf16String::from_utf16(code().utf16_view().substring_view(start_offset, length));
+ auto code = this->code();
+ return Utf16String::from_utf16(code.utf16_view().substring_view(start_offset, length));
}
void SourceCode::ref() const
diff --git a/Libraries/LibJS/SourceCode.h b/Libraries/LibJS/SourceCode.h
index 242877a1132..f37dc2ac073 100644
--- a/Libraries/LibJS/SourceCode.h
+++ b/Libraries/LibJS/SourceCode.h
@@ -32,7 +32,8 @@ public:
static NonnullRefPtr<SourceCode const> create(Utf16String filename, Utf16String code);
Utf16String const& filename() const;
- Utf16String const& code() const;
+ // NB: The runtime may hold the code compressed, so this is a string of its own, not a reference to one.
+ Utf16String code() const;
size_t length_in_code_units() const;
Utf16String source_text_from_offsets(size_t start_offset, size_t length) const;
diff --git a/Tests/LibJS/Runtime/source-text-parking.js b/Tests/LibJS/Runtime/source-text-parking.js
new file mode 100644
index 00000000000..b9e48d27d2b
--- /dev/null
+++ b/Tests/LibJS/Runtime/source-text-parking.js
@@ -0,0 +1,44 @@
+// The text of a large source that nothing read for a while is compressed, and decompressed when something reads it
+// again. parkSourceTexts() compresses every text that is large enough, and code must behave the same afterwards.
+
+// NB: Only large sources are parked, so the code under test comes from an eval of a long string.
+const padding = "/* padding */\n".repeat(2000);
+
+function evalLargeSource(code) {
+ return (0, eval)(`${padding}${code}\n${padding}`);
+}
+
+describe("parked source texts", () => {
+ test("a function compiles for the first time from a parked source", () => {
+ const outer = evalLargeSource("(function outer() { return function inner(a, b) { return a + b; }; })");
+ expect(parkSourceTexts()).toBeGreaterThan(0);
+ expect(outer()(1, 2)).toBe(3);
+ });
+
+ test("a function of a parked source has its source text", () => {
+ const f = evalLargeSource("(function named(a, b) { return 'caf\u00e9 \u2019 \ud83d\ude00'; })");
+ expect(parkSourceTexts()).toBeGreaterThan(0);
+ expect(f.toString()).toBe("function named(a, b) { return 'caf\u00e9 \u2019 \ud83d\ude00'; }");
+ expect(f()).toBe("caf\u00e9 \u2019 \ud83d\ude00");
+ });
+
+ test("an error thrown from a parked source reports its position", () => {
+ const f = evalLargeSource("(function thrower() {\n return undefinedName.property;\n})");
+ expect(parkSourceTexts()).toBeGreaterThan(0);
+ expect(f).toThrowWithMessage(ReferenceError, "'undefinedName' is not defined");
+ expect(parkSourceTexts()).toBeGreaterThan(0);
+ expect(f).toThrowWithMessage(ReferenceError, "'undefinedName' is not defined");
+ });
+
+ test("a text can be parked again after it was read", () => {
+ const outer = evalLargeSource(
+ "(function () { return [function a() { return 1; }, function b() { return 2; }]; })"
+ );
+ expect(parkSourceTexts()).toBeGreaterThan(0);
+ const [a, b] = outer();
+ expect(a()).toBe(1);
+ expect(parkSourceTexts()).toBeGreaterThan(0);
+ expect(b()).toBe(2);
+ expect(b.toString()).toBe("function b() { return 2; }");
+ });
+});