Truly independent web browser
LibJS: Let the parser and the resolver read only views of kept data
Andreas Kling655f39ff0d0c
diff --git a/Libraries/LibJS/Rust/src/bytecode/codegen/scope.rs b/Libraries/LibJS/Rust/src/bytecode/codegen/scope.rsindex fd0d1c97077..0e676e21b90 100644--- a/Libraries/LibJS/Rust/src/bytecode/codegen/scope.rs+++ b/Libraries/LibJS/Rust/src/bytecode/codegen/scope.rs@@ -1691,7 +1691,7 @@ impl Generator<'_> {self.context.scope.scope_resolutions- .push(crate::parser::resolve::outer_entry(row, name, resolution));+ .push(crate::parser::outer_entry(row, name, resolution));}}@@ -1714,7 +1714,7 @@ impl Generator<'_> {self.context.scope.scope_resolutions- .push(crate::parser::resolve::outer_entry(row, name, resolution));+ .push(crate::parser::outer_entry(row, name, resolution));continue;}let scope = &mut self.context.scope;@@ -1728,7 +1728,7 @@ impl Generator<'_> {resolution.set_is_inside_scope_with_eval();scope.scope_resolutions- .push(crate::parser::resolve::outer_entry(row, name, resolution));+ .push(crate::parser::outer_entry(row, name, resolution));}continue;};@@ -1738,7 +1738,7 @@ impl Generator<'_> {}scope.scope_resolutions- .push(crate::parser::resolve::outer_entry(row, name, resolution));+ .push(crate::parser::outer_entry(row, name, resolution));}let mut resolution = Resolution::default();if unbound.is_inside_scope_with_eval() || has_direct_eval {@@ -1753,11 +1753,7 @@ impl Generator<'_> {self.context.scope.scope_resolutions- .push(crate::parser::resolve::outer_entry(- row,- Name(N_DOT_UNBOUND),- resolution,- ));+ .push(crate::parser::outer_entry(row, Name(N_DOT_UNBOUND), resolution));}/// What the function at `row` captures of scopes inside this function has to be noted while those are around.@@ -1781,7 +1777,7 @@ impl Generator<'_> {}scope.scope_resolutions- .push(crate::parser::resolve::outer_entry(row, name, resolution));+ .push(crate::parser::outer_entry(row, name, resolution));}}diff --git a/Libraries/LibJS/Rust/src/compile.rs b/Libraries/LibJS/Rust/src/compile.rsindex 508c64c3c67..c74ad2c0134 100644--- a/Libraries/LibJS/Rust/src/compile.rs+++ b/Libraries/LibJS/Rust/src/compile.rs@@ -310,9 +310,6 @@ pub fn compile_parsed_program_off_thread(parsed: ParsedProgram) -> CompiledProgr);let (program_type, has_top_level_await) = (parsed.program_type, parsed.has_top_level_await);let code = parsed.into_code(true);-- code.script.index.prepare_for_reparsing();-let declarations_size = match &code.declarations {CompiledProgramDeclarations::Script(declarations) => declarations.memory_size(),CompiledProgramDeclarations::Module(declarations) => declarations.memory_size(),diff --git a/Libraries/LibJS/Rust/src/parser/base.rs b/Libraries/LibJS/Rust/src/parser/base.rsindex 3484a29d97c..a816cd5448b 100644--- a/Libraries/LibJS/Rust/src/parser/base.rs+++ b/Libraries/LibJS/Rust/src/parser/base.rs@@ -373,7 +373,7 @@ pub struct Parser<'a, 'k, U: Unit> {pub(crate) if_start: u32,pub(crate) retain_next_function: bool,/// While reparsing: what the first parse found out about the functions of the source.- first_pass_index: *const FunctionIndex,+ first_pass_index: Option<FunctionIndexView<'k>>,/// While reparsing: where the function being reparsed starts over.pub(crate) reparse_target: u32,pub(crate) with_depth: u32,@@ -500,20 +500,16 @@ impl<'a: 'k, 'k, U: Unit> Parser<'a, 'k, U> {}/// A parser that parses one function again, knowing what the first parse of its source found, with its work data in- /// `zone`. The names of the source with their states, and the index the parser writes to, come from the reparse- /// context of the source: the names and the states in place, and the index until the parse ends (see- /// `end_reparse()`). Its source comes with the function.- ///- /// # Safety- /// `first_pass_index` must stay valid and unchanged for as long as the parser reparses functions.+ /// `zone`. The names of the source with their states come from the reparse context of the source, and the parser+ /// works with them in place. Its source comes with the function.#[allow(clippy::too_many_arguments)]- pub(crate) unsafe fn for_reparsing(+ pub(crate) fn for_reparsing(zone: &'a Zone,module: bool,interner: Interner<'k>,names: &'k mut [NameState],stamp: u32,- first_pass_index: &FunctionIndex,+ first_pass_index: FunctionIndexView<'k>,source_length: u32,estimated_nodes: usize,validate_regex: ValidateRegex,@@ -532,7 +528,7 @@ impl<'a: 'k, 'k, U: Unit> Parser<'a, 'k, U> {validate_regex,);parser.stamp = stamp;- parser.first_pass_index = first_pass_index;+ parser.first_pass_index = Some(first_pass_index);parser}@@ -616,7 +612,7 @@ impl<'a: 'k, 'k, U: Unit> Parser<'a, 'k, U> {class_start: 0,if_start: 0,retain_next_function: false,- first_pass_index: core::ptr::null(),+ first_pass_index: None,reparse_target: NONE,with_depth: 0,names_used_in_with: ZoneVec::new_in(zone),@@ -694,7 +690,7 @@ impl<'a: 'k, 'k, U: Unit> Parser<'a, 'k, U> {pub(crate) fn parse_top_level_rows(&mut self,context: ProgramContext,- index: &FunctionIndex,+ index: FunctionIndexView<'a>,) -> Result<(Ast<'a>, u32), super::OutOfStack> {// NB: The rows are those of the tree, and marks, which some code has many of.let nodes = self.ast.tag.len();@@ -705,12 +701,11 @@ impl<'a: 'k, 'k, U: Unit> Parser<'a, 'k, U> {(self.first_token_start, self.strict, self.has_top_level_await);self.finish_reparse();self.export_names.clear();- // NB: The first pass index is only read until the end of this function.- self.first_pass_index = index;+ self.first_pass_index = Some(index);self.tracks_scopes = false;self.marks = true;let node = self.reparse_program(context);- self.first_pass_index = core::ptr::null();+ self.first_pass_index = None;let error = self.err.take();let rows = std::mem::replace(&mut self.ast, tree);self.eval_referenced_private_names = private_names;@@ -2245,12 +2240,13 @@ impl<'a: 'k, 'k, U: Unit> Parser<'a, 'k, U> {#[inline(always)]pub(crate) fn is_reparsing(&self) -> bool {- !self.first_pass_index.is_null()+ self.first_pass_index.is_some()}- fn first_pass_index(&self) -> &'a FunctionIndex {- // SAFETY: A parser that reparses functions has an index, which for_reparsing() requires to stay valid.- unsafe { &*self.first_pass_index }+ #[inline(always)]+ fn first_pass_index(&self) -> FunctionIndexView<'k> {+ self.first_pass_index+ .expect("a parser that parses functions again has their index")}/// Reads from `source` from now on, where offset `offset` is at the first unit, and `length` is that of the wholediff --git a/Libraries/LibJS/Rust/src/parser/columns.rs b/Libraries/LibJS/Rust/src/parser/columns.rsindex 8e9781447e8..c37d184a2ae 100644--- a/Libraries/LibJS/Rust/src/parser/columns.rs+++ b/Libraries/LibJS/Rust/src/parser/columns.rs@@ -11,7 +11,6 @@//! Names and literals are not copied: an identifier operand is an interned name id, and a literal is its source offset.use std::cell::Cell;-use std::sync::OnceLock;use ak::Zone;use ak::ZoneVec;@@ -262,49 +261,51 @@ pub struct AstMarks {pub scopes: u32,}-/// What a function leaves behind once its tree is gone, one row per function, as columns. The first parse of a source-/// builds it in its work zone (see [`FunctionIndexBuilder`]) and keeps a copy at its final size.-#[derive(Default)]-pub struct FunctionIndex {- pub start: Box<[u32]>,+/// What a function leaves behind once its tree is gone, one row per function, as columns, which is how parses read it.+/// The first parse of a source builds it in its work zone (see [`FunctionIndexBuilder`]), and a copy of it stays with+/// the source (see `FunctionIndex`).+#[derive(Clone, Copy)]+pub struct FunctionIndexView<'t> {+ pub start: &'t [u32],/// Where parsing the function starts over. This is what tells two functions apart that start at the same offset,/// and for the code of a class that runs as a function, the offset of the class element or the class.- pub params_start: Box<[u32]>,- pub end: Box<[u32]>,- pub flags: Box<[u32]>,- pub length: Box<[u32]>,- pub parameter_count: Box<[u32]>,+ pub params_start: &'t [u32],+ pub end: &'t [u32],+ pub flags: &'t [u32],+ pub length: &'t [u32],+ pub parameter_count: &'t [u32],/// What the function's code may do, as parser context bits.- pub ctx: Box<[u16]>,+ pub ctx: &'t [u16],/// The function's own name, if it has one.- pub name: Box<[u32]>,+ pub name: &'t [u32],/// Where each function's captures start in `capture_names`, and how many it has.- pub capture_start: Box<[u32]>,- pub capture_count: Box<[u32]>,+ pub capture_start: &'t [u32],+ pub capture_count: &'t [u32],/// What each function captures of the function around it, which is all that reparsing that function needs to know/// about a function it skips. A name that only passes through on its way further out is not in here: it is a capture/// of the outer function that it passes through.- pub capture_names: Box<[u32]>,+ pub capture_names: &'t [u32],/// The rows by `params_start`, unless that is the order they are in. It often is not, as an arrow function only gets- /// its row after its parameters, and so after the functions in them. Worked out once functions get parsed again.- pub(super) rows_by_params_start: OnceLock<Vec<u32>>,+ /// its row after its parameters, and so after the functions in them.+ pub rows_by_params_start: &'t [u32],/// What is left of the bindings of each function for code that goes without a resolver, as a pool of bytes: the/// number of bindings of the function itself that come up before their declaration and those, the number of scopes/// inside the function with bindings that have to exist when the scope starts and those scopes, then a bitmap of/// which of the other bindings of the function itself are captured, in the order of their declarations. A scope is/// the distance from the scope before it, the number of bindings and those. A function with nothing to say has no/// bytes.- pub summaries: Box<[u8]>,- pub summary_start: Box<[u32]>,+ pub summaries: &'t [u8],+ pub summary_start: &'t [u32],/// A bit for every name of the source that anything declares, which all other names are free everywhere.- pub declared_names: Box<[u64]>,+ pub declared_names: &'t [u64],/// Where the summary of the top level ends, which is the first thing in the pool.pub program_summary_end: u32,/// Whether the top level has a direct `eval`, so that names may mean more than they seem to there.pub program_has_direct_eval: bool,}-/// The function index that the first parse of a source builds in its work zone. See [`FunctionIndex`] for the columns.+/// The function index that the first parse of a source builds in its work zone. See [`FunctionIndexView`] for the+/// columns.pub struct FunctionIndexBuilder<'z> {pub start: ZoneVec<'z, u32>,pub params_start: ZoneVec<'z, u32>,@@ -347,52 +348,44 @@ impl<'z> FunctionIndexBuilder<'z> {}}- /// A copy of the index, at its final size.- pub fn to_kept(&self) -> FunctionIndex {- FunctionIndex {- start: Box::from(self.start.as_slice()),- params_start: Box::from(self.params_start.as_slice()),- end: Box::from(self.end.as_slice()),- flags: Box::from(self.flags.as_slice()),- length: Box::from(self.length.as_slice()),- parameter_count: Box::from(self.parameter_count.as_slice()),- ctx: Box::from(self.ctx.as_slice()),- name: Box::from(self.name.as_slice()),- capture_start: Box::from(self.capture_start.as_slice()),- capture_count: Box::from(self.capture_count.as_slice()),- capture_names: Box::from(self.capture_names.as_slice()),- rows_by_params_start: OnceLock::new(),- summaries: Box::from(self.summaries.as_slice()),- summary_start: Box::from(self.summary_start.as_slice()),- declared_names: Box::from(self.declared_names.as_slice()),+ /// The index as it is when the parse is done, with the rows sorted by where parsing them starts over.+ pub fn finish(self) -> FunctionIndexView<'z> {+ let zone = self.start.zone();+ let params_start = self.params_start.into_slice();+ let rows_by_params_start: &[u32] = if params_start.is_sorted() {+ &[]+ } else {+ let rows = zone.alloc_slice_from_iter(0..u32_from_usize(params_start.len()));+ // NB: Rows that start over at the same offset keep their order.+ rows.sort_unstable_by_key(|&row| (params_start[row as usize], row));+ rows+ };+ FunctionIndexView {+ start: self.start.into_slice(),+ params_start,+ end: self.end.into_slice(),+ flags: self.flags.into_slice(),+ length: self.length.into_slice(),+ parameter_count: self.parameter_count.into_slice(),+ ctx: self.ctx.into_slice(),+ name: self.name.into_slice(),+ capture_start: self.capture_start.into_slice(),+ capture_count: self.capture_count.into_slice(),+ capture_names: self.capture_names.into_slice(),+ rows_by_params_start,+ summaries: self.summaries.into_slice(),+ summary_start: self.summary_start.into_slice(),+ declared_names: self.declared_names.into_slice(),program_summary_end: self.program_summary_end,program_has_direct_eval: self.program_has_direct_eval,}}}-impl FunctionIndex {- /// Gets the function at each offset ready to be found, for whatever parses a source off the main thread to do before- /// handing it over, as this takes a while for a large source.- pub fn prepare_for_reparsing(&self) {- self.rows_by_params_start();- }-- fn rows_by_params_start(&self) -> &[u32] {- self.rows_by_params_start.get_or_init(|| {- if self.params_start.is_sorted() {- return Vec::new();- }- let mut rows: Vec<u32> = (0..u32_from_usize(self.params_start.len())).collect();- // NB: A stable sort, as the rows are nearly in order, which it makes use of.- rows.sort_by_key(|&row| self.params_start[row as usize]);- rows- })- }-+impl FunctionIndexView<'_> {/// Where lookups for what comes after the function of `row` start out.pub fn position_after_row(&self, row: usize) -> usize {- let rows = self.rows_by_params_start();+ let rows = self.rows_by_params_start;if rows.is_empty() {return row + 1;}@@ -403,7 +396,7 @@ impl FunctionIndex {/// The row of the function that starts over at `params_start`. Lookups follow the source, so that the answer is mostly/// right where the last one left `cursor`.pub fn row_at_params_start(&self, params_start: u32, cursor: &Cell<usize>) -> Option<u32> {- let rows = self.rows_by_params_start();+ let rows = self.rows_by_params_start;let row_at = |position: usize| {if rows.is_empty() {(position < self.params_start.len()).then(|| u32_from_usize(position))@@ -472,24 +465,6 @@ impl FunctionIndex {.map_or(self.summaries.len(), |&end| end as usize);(start, end)}-- pub fn memory_size(&self) -> usize {- let u32_columns = [- &self.start,- &self.params_start,- &self.end,- &self.flags,- &self.length,- &self.parameter_count,- &self.name,- &self.capture_start,- &self.capture_count,- &self.capture_names,- ];- let sorted_rows = self.rows_by_params_start.get().map_or(0, Vec::capacity);- (u32_columns.iter().map(|column| column.len()).sum::<usize>() + sorted_rows) * size_of::<u32>()- + self.ctx.len() * size_of::<u16>()- }}pub mod function_flag {diff --git a/Libraries/LibJS/Rust/src/parser/enclosing.rs b/Libraries/LibJS/Rust/src/parser/enclosing.rsnew file mode 100644index 00000000000..2610c02a3f9--- /dev/null+++ b/Libraries/LibJS/Rust/src/parser/enclosing.rs@@ -0,0 +1,137 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! What the code that a compile job compiled leaves for the functions nested in it, which get compiled later: how the+//! names that they capture resolve (see `resolve.rs`, which works it out for a program).++use super::columns::NONE;+use super::resolve::outer_key;+use super::token::N_DOT_UNBOUND;+use crate::ast::Name;+use crate::ast::Resolution;+use crate::ast::SyntaxTree;+use std::sync::Arc;++/// What a name means from inside a function that a tree did not hold the code of, by function row and name.+#[derive(Clone)]+pub struct OuterResolutions {+ entries: Arc<[(u64, Resolution)]>,+}++impl OuterResolutions {+ /// The resolutions of `entries`, unless there are none (see `new()`).+ pub(crate) fn of_entries(entries: &mut [(u64, Resolution)]) -> Option<Self> {+ (!entries.is_empty()).then(|| Self::new(entries))+ }++ /// The resolutions of `entries`, which get sorted, and of which the first for a name is the one that counts.+ fn new(entries: &mut [(u64, Resolution)]) -> Self {+ if !entries.is_sorted_by_key(|&(key, _)| key) {+ entries.sort_by_key(|&(key, _)| key);+ }+ let mut count = 0;+ for index in 0..entries.len() {+ if count == 0 || entries[count - 1].0 != entries[index].0 {+ entries[count] = entries[index];+ count += 1;+ }+ }+ Self {+ entries: Arc::from(&entries[..count]),+ }+ }++ fn get(&self, row: u32, name: Name) -> Option<Resolution> {+ let key = outer_key(row, name);+ let position = self.entries.binary_search_by_key(&key, |&(key, _)| key).ok()?;+ Some(self.entries[position].1)+ }+}++/// An entry of the resolutions for the function at `row`.+pub(crate) fn outer_entry(row: u32, name: Name, resolution: Resolution) -> (u64, Resolution) {+ (outer_key(row, name), resolution)+}++/// Code that a compile job compiled, as seen by the functions nested in it, which get compiled later.+pub struct EnclosingCode {+ /// The row of the function, or NONE for a program.+ row: u32,+ /// What the functions nested in this code see of it, unless it has none.+ resolutions: Option<OuterResolutions>,+ parent: Option<Arc<EnclosingCode>>,+ /// Whether what this code leaves unbound can go through a direct `eval` of its own.+ has_direct_eval: bool,+}++impl EnclosingCode {+ pub(crate) fn of_program(tree: &SyntaxTree<'_>) -> Arc<Self> {+ Arc::new(Self {+ row: NONE,+ resolutions: tree.outer_resolutions.clone(),+ parent: None,+ has_direct_eval: true,+ })+ }++ /// The code of the function at `row`, from what it found out about what is nested in it itself.+ pub(crate) fn of_function(+ row: u32,+ entries: &mut [(u64, Resolution)],+ parent: &Arc<Self>,+ has_direct_eval: bool,+ ) -> Arc<Self> {+ Arc::new(Self {+ row,+ resolutions: Some(OuterResolutions::new(entries)),+ parent: Some(parent.clone()),+ has_direct_eval,+ })+ }++ /// What `name` means in the function at `row`, nested in this code, if it is free there.+ pub(crate) fn resolution_in_function(+ self: &Arc<Self>,+ script: &super::ScriptData,+ row: u32,+ name: Name,+ ) -> Resolution {+ let mut code = Some(self);+ let mut function = row;+ let mut is_inside_scope_with_eval = false;+ let mut outermost_unbound_name = Resolution::default();+ while let Some(enclosing) = code {+ let resolutions = enclosing+ .resolutions+ .as_ref()+ .expect("code that a function is nested in has resolutions for it");+ if let Some(mut resolution) = resolutions.get(function, name) {+ if is_inside_scope_with_eval {+ resolution.set_is_inside_scope_with_eval();+ }+ return resolution;+ }+ // NB: The name goes through all the scopes of this code that are around the function. Only the outermost+ // code has the last word on it, and other code only matters if it has an `eval`.+ if enclosing.has_direct_eval || enclosing.parent.is_none() {+ outermost_unbound_name = resolutions+ .get(function, Name(N_DOT_UNBOUND))+ .expect("the code around a function resolved what it does not bind");+ is_inside_scope_with_eval |= outermost_unbound_name.is_inside_tree_scope_with_eval();+ }+ function = enclosing.row;+ code = enclosing.parent.as_ref();+ }+ // NB: No scope around the function binds the name.+ if script.is_global_name_used_in_with(name) {+ outermost_unbound_name.clear_is_global();+ }+ if is_inside_scope_with_eval {+ outermost_unbound_name.set_is_inside_scope_with_eval();+ }+ outermost_unbound_name+ }+}diff --git a/Libraries/LibJS/Rust/src/parser/kept.rs b/Libraries/LibJS/Rust/src/parser/kept.rsindex 988373ef06b..a49e73896bc 100644--- a/Libraries/LibJS/Rust/src/parser/kept.rs+++ b/Libraries/LibJS/Rust/src/parser/kept.rs@@ -7,6 +7,7 @@//! What the first parse of a source keeps on the heap, at its final size, for the compile jobs that come later, maybe//! on other threads.+use super::columns::FunctionIndexView;use super::intern::Interner;use super::intern::LongRow;use super::intern::NameTables;@@ -74,3 +75,107 @@ impl KeptNames {}}}++/// The function index of a source, which its first parse keeps at its final size. See `FunctionIndexView` for the+/// columns.+#[derive(Default)]+pub struct FunctionIndex {+ pub start: Box<[u32]>,+ pub params_start: Box<[u32]>,+ pub end: Box<[u32]>,+ pub flags: Box<[u32]>,+ pub length: Box<[u32]>,+ pub parameter_count: Box<[u32]>,+ pub ctx: Box<[u16]>,+ pub name: Box<[u32]>,+ pub capture_start: Box<[u32]>,+ pub capture_count: Box<[u32]>,+ pub capture_names: Box<[u32]>,+ pub rows_by_params_start: Box<[u32]>,+ pub summaries: Box<[u8]>,+ pub summary_start: Box<[u32]>,+ pub declared_names: Box<[u64]>,+ pub program_summary_end: u32,+ pub program_has_direct_eval: bool,+}++impl FunctionIndex {+ /// A copy of `index`.+ pub(crate) fn of(index: &FunctionIndexView<'_>) -> Self {+ Self {+ start: index.start.into(),+ params_start: index.params_start.into(),+ end: index.end.into(),+ flags: index.flags.into(),+ length: index.length.into(),+ parameter_count: index.parameter_count.into(),+ ctx: index.ctx.into(),+ name: index.name.into(),+ capture_start: index.capture_start.into(),+ capture_count: index.capture_count.into(),+ capture_names: index.capture_names.into(),+ rows_by_params_start: index.rows_by_params_start.into(),+ summaries: index.summaries.into(),+ summary_start: index.summary_start.into(),+ declared_names: index.declared_names.into(),+ program_summary_end: index.program_summary_end,+ program_has_direct_eval: index.program_has_direct_eval,+ }+ }++ #[inline(always)]+ pub(crate) fn view(&self) -> FunctionIndexView<'_> {+ FunctionIndexView {+ start: &self.start,+ params_start: &self.params_start,+ end: &self.end,+ flags: &self.flags,+ length: &self.length,+ parameter_count: &self.parameter_count,+ ctx: &self.ctx,+ name: &self.name,+ capture_start: &self.capture_start,+ capture_count: &self.capture_count,+ capture_names: &self.capture_names,+ rows_by_params_start: &self.rows_by_params_start,+ summaries: &self.summaries,+ summary_start: &self.summary_start,+ declared_names: &self.declared_names,+ program_summary_end: self.program_summary_end,+ program_has_direct_eval: self.program_has_direct_eval,+ }+ }++ /// Whether anything in the source declares `name`.+ #[inline(always)]+ pub fn is_declared_anywhere(&self, name: u32) -> bool {+ self.view().is_declared_anywhere(name)+ }++ /// Where the summary of the function at `row` is in the pool.+ #[inline(always)]+ pub fn summary_range(&self, row: u32) -> (usize, usize) {+ self.view().summary_range(row)+ }++ pub fn memory_size(&self) -> usize {+ let u32_columns = [+ &self.start,+ &self.params_start,+ &self.end,+ &self.flags,+ &self.length,+ &self.parameter_count,+ &self.name,+ &self.capture_start,+ &self.capture_count,+ &self.capture_names,+ &self.rows_by_params_start,+ &self.summary_start,+ ];+ u32_columns.iter().map(|column| column.len()).sum::<usize>() * size_of::<u32>()+ + self.ctx.len() * size_of::<u16>()+ + self.summaries.len()+ + self.declared_names.len() * size_of::<u64>()+ }+}diff --git a/Libraries/LibJS/Rust/src/parser/mod.rs b/Libraries/LibJS/Rust/src/parser/mod.rsindex a4b641030b9..a7549a9e728 100644--- a/Libraries/LibJS/Rust/src/parser/mod.rs+++ b/Libraries/LibJS/Rust/src/parser/mod.rs@@ -14,6 +14,7 @@pub(crate) mod base;pub(crate) mod columns;+mod enclosing;pub(crate) mod expr;mod intern;mod kept;@@ -39,16 +40,18 @@ use base::Mode;use base::Parser;use columns::Ast;use columns::AstColumns;-use columns::FunctionIndex;+use columns::FunctionIndexBuilder;use columns::function_flag;use core::sync::atomic::AtomicBool;use core::sync::atomic::AtomicU8;use core::sync::atomic::AtomicUsize;use core::sync::atomic::Ordering;+pub(crate) use enclosing::EnclosingCode;+pub(crate) use enclosing::OuterResolutions;+pub(crate) use enclosing::outer_entry;use intern::Interner;+use kept::FunctionIndex;use kept::KeptNames;-pub(crate) use resolve::EnclosingCode;-pub(crate) use resolve::OuterResolutions;use std::sync::Arc;use std::sync::Mutex;use std::sync::Weak;@@ -280,21 +283,17 @@ impl ScriptData {let estimated_nodes = whole_function_nodes.min(1 << 16);let needs_padding = self.index.flags[row_index] & function_flag::REACHES_SOURCE_END != 0;let name_count = context.names.len();- // SAFETY: The index of this ScriptData stays where it is, since the ScriptData is shared by an Arc, and never- // changes.- let mut parser = unsafe {- Parser::for_reparsing(- zone,- self.program_type == ProgramType::Module,- Interner::of_tables(zone, context.names.tables_mut()),- &mut context.name_states,- context.stamp,- &self.index,- u32_from_usize(source.len()),- estimated_nodes,- validate_regex,- )- };+ let mut parser = Parser::for_reparsing(+ zone,+ self.program_type == ProgramType::Module,+ Interner::of_tables(zone, context.names.tables_mut()),+ &mut context.name_states,+ context.stamp,+ self.index.view(),+ u32_from_usize(source.len()),+ estimated_nodes,+ validate_regex,+ );parser.ast.likely_most_nodes = whole_function_nodes;parser.tracks_scopes = false;parser.marks = true;@@ -587,9 +586,9 @@ fn parse_code_units<'z, U: Unit + Default, R>(return Ok(None);}let lines = LineTable::new(zone, units, options.initial_line_number);- let index = parser.index.to_kept();+ let index = core::mem::replace(&mut parser.index, FunctionIndexBuilder::with_capacity(zone, 0)).finish();let top_level_rows = parser- .parse_top_level_rows(options.program_context(), &index)+ .parse_top_level_rows(options.program_context(), index).map(|(rows, node)| (rows.into_columns(), node));let default_export_name = Name(parser.interner.intern_bytes(b"*default*"));let default_constructor_parameter_name = Name(parser.interner.intern_bytes(b"args"));@@ -601,7 +600,7 @@ fn parse_code_units<'z, U: Unit + Default, R>(let eval_referenced_private_names =zone.alloc_slice_from_iter(parser.eval_referenced_private_names.iter().map(|&name| Name(name)));let script = Arc::new(ScriptData {- index,+ index: FunctionIndex::of(&index),names,positions: Arc::new(SourcePositions {source: SourceText::of(source),@@ -640,7 +639,15 @@ fn parse_code_units<'z, U: Unit + Default, R>(suppress_globals: options.suppress_globals,},);- Ok(Some(job(&resolved.apply_to(tree), top_level_rows)))+ let tree = SyntaxTree {+ resolutions: resolved.resolutions,+ scopes: resolved.scopes,+ program_scope_row: resolved.program_scope_row,+ function_scope_rows: resolved.function_scope_rows,+ outer_resolutions: OuterResolutions::of_entries(resolved.outer_entries),+ ..tree+ };+ Ok(Some(job(&tree, top_level_rows)))}/// Parses `source` at the width of its storage, in one job with the work zone of the thread for all of its work data.diff --git a/Libraries/LibJS/Rust/src/parser/resolve.rs b/Libraries/LibJS/Rust/src/parser/resolve.rsindex 285057cee81..822c09db803 100644--- a/Libraries/LibJS/Rust/src/parser/resolve.rs+++ b/Libraries/LibJS/Rust/src/parser/resolve.rs@@ -14,8 +14,9 @@//! A tree only holds the code of one compile job, so this only walks that code. A function nested in it is not in the//! tree, but what its names resolve to depends on the scopes around it, and those are here now and gone by the time it//! gets compiled. So every such function leaves a reference behind for each name that it captures, which resolves like-//! any other, and the results stay around as [`OuterResolutions`] for when it does get compiled. A name it uses that the-//! code around it binds further out is a capture of a function further out. [`EnclosingCode`] links them up.+//! any other, and the results stay around as `OuterResolutions` (see `enclosing.rs`) for when it does get compiled. A+//! name it uses that the code around it binds further out is a capture of a function further out. `EnclosingCode` links+//! them up.use super::base::SCOPE_ROW_EVAL_IN_FUNCTION;use super::base::SCOPE_ROW_POISONED;@@ -33,7 +34,6 @@ use crate::ast::*;use crate::u32_from_usize;use ak::Zone;use ak::ZoneVec;-use std::sync::Arc;#[derive(Clone, Copy, PartialEq, Eq)]enum FrameKind {@@ -419,126 +419,6 @@ pub(super) struct ResolveOptions {pub(super) suppress_globals: bool,}-/// What a name means from inside a function that a tree did not hold the code of, by function row and name.-#[derive(Clone)]-pub struct OuterResolutions {- entries: Arc<[(u64, Resolution)]>,-}--impl OuterResolutions {- fn key(row: u32, name: Name) -> u64 {- u64::from(row) << 32 | u64::from(name.0)- }-- /// The resolutions of `entries`, which get sorted, and of which the first for a name is the one that counts.- fn new(entries: &mut [(u64, Resolution)]) -> Self {- if !entries.is_sorted_by_key(|&(key, _)| key) {- entries.sort_by_key(|&(key, _)| key);- }- let mut count = 0;- for index in 0..entries.len() {- if count == 0 || entries[count - 1].0 != entries[index].0 {- entries[count] = entries[index];- count += 1;- }- }- Self {- entries: Arc::from(&entries[..count]),- }- }-- fn get(&self, row: u32, name: Name) -> Option<Resolution> {- let key = Self::key(row, name);- let position = self.entries.binary_search_by_key(&key, |&(key, _)| key).ok()?;- Some(self.entries[position].1)- }-}--/// An entry of the resolutions for the function at `row`.-pub(crate) fn outer_entry(row: u32, name: Name, resolution: Resolution) -> (u64, Resolution) {- (OuterResolutions::key(row, name), resolution)-}--/// Code that a compile job compiled, as seen by the functions nested in it, which get compiled later.-pub struct EnclosingCode {- /// The row of the function, or NONE for a program.- row: u32,- /// What the functions nested in this code see of it, unless it has none.- resolutions: Option<OuterResolutions>,- parent: Option<Arc<EnclosingCode>>,- /// Whether what this code leaves unbound can go through a direct `eval` of its own.- has_direct_eval: bool,-}--impl EnclosingCode {- pub(crate) fn of_program(tree: &SyntaxTree<'_>) -> Arc<Self> {- Arc::new(Self {- row: NONE,- resolutions: tree.outer_resolutions.clone(),- parent: None,- has_direct_eval: true,- })- }-- /// The code of the function at `row`, from what it found out about what is nested in it itself.- pub(crate) fn of_function(- row: u32,- entries: &mut [(u64, Resolution)],- parent: &Arc<Self>,- has_direct_eval: bool,- ) -> Arc<Self> {- Arc::new(Self {- row,- resolutions: Some(OuterResolutions::new(entries)),- parent: Some(parent.clone()),- has_direct_eval,- })- }-- /// What `name` means in the function at `row`, nested in this code, if it is free there.- pub(crate) fn resolution_in_function(- self: &Arc<Self>,- script: &super::ScriptData,- row: u32,- name: Name,- ) -> Resolution {- let mut code = Some(self);- let mut function = row;- let mut is_inside_scope_with_eval = false;- let mut outermost_unbound_name = Resolution::default();- while let Some(enclosing) = code {- let resolutions = enclosing- .resolutions- .as_ref()- .expect("code that a function is nested in has resolutions for it");- if let Some(mut resolution) = resolutions.get(function, name) {- if is_inside_scope_with_eval {- resolution.set_is_inside_scope_with_eval();- }- return resolution;- }- // NB: The name goes through all the scopes of this code that are around the function. Only the outermost- // code has the last word on it, and other code only matters if it has an `eval`.- if enclosing.has_direct_eval || enclosing.parent.is_none() {- outermost_unbound_name = resolutions- .get(function, Name(N_DOT_UNBOUND))- .expect("the code around a function resolved what it does not bind");- is_inside_scope_with_eval |= outermost_unbound_name.is_inside_tree_scope_with_eval();- }- function = enclosing.row;- code = enclosing.parent.as_ref();- }- // NB: No scope around the function binds the name.- if script.is_global_name_used_in_with(name) {- outermost_unbound_name.clear_is_global();- }- if is_inside_scope_with_eval {- outermost_unbound_name.set_is_inside_scope_with_eval();- }- outermost_unbound_name- }-}-/// The scope table that a resolver fills in.struct ScopeColumns<'z> {rows: ZoneVec<'z, ScopeRow>,@@ -546,30 +426,20 @@ struct ScopeColumns<'z> {annexb_function_names: ZoneVec<'z, Name>,}-/// What resolving found out about a tree, in the work zone.+/// What resolving found out about a tree, in the work zone, for the tree to refer to.pub(super) struct Resolved<'z> {- resolutions: &'z [Resolution],- scopes: ScopeTable<'z>,- program_scope_row: u32,- function_scope_rows: &'z [(u32, u32)],- /// The resolutions for the functions nested in the tree, as (key, resolution).- outer_entries: &'z mut [(u64, Resolution)],+ pub(super) resolutions: &'z [Resolution],+ pub(super) scopes: ScopeTable<'z>,+ pub(super) program_scope_row: u32,+ pub(super) function_scope_rows: &'z [(u32, u32)],+ /// The resolutions for the functions nested in the tree, as (key, resolution), with keys from `outer_key()`. Every+ /// function nested in the code leaves a reference behind, so that without any there are none.+ pub(super) outer_entries: &'z mut [(u64, Resolution)],}-impl<'z> Resolved<'z> {- /// `tree` with what resolving found out about it.- pub(super) fn apply_to(self, tree: SyntaxTree<'z>) -> SyntaxTree<'z> {- // NB: Every function nested in the code leaves a reference behind, so that without any there are none.- let outer_resolutions = (!self.outer_entries.is_empty()).then(|| OuterResolutions::new(self.outer_entries));- SyntaxTree {- resolutions: self.resolutions,- scopes: self.scopes,- program_scope_row: self.program_scope_row,- function_scope_rows: self.function_scope_rows,- outer_resolutions,- ..tree- }- }+/// The key of the resolution of `name` for the function at `row`.+pub(crate) fn outer_key(row: u32, name: Name) -> u64 {+ u64::from(row) << 32 | u64::from(name.0)}struct Resolver<'t, 'z> {@@ -640,7 +510,7 @@ impl<'t, 'z> Resolver<'t, 'z> {let outer_entries = self.zone.alloc_slice_from_iter(self.outer_references.iter()- .map(|&(row, name, node)| (OuterResolutions::key(row, name), resolutions[node as usize])),+ .map(|&(row, name, node)| (outer_key(row, name), resolutions[node as usize])),);let scopes = self.scopes;Resolved {