Skip to content

Truly independent web browser

LibJS: Build and resolve the tree of a parse in the work zone

Andreas Kling825bddf92f82
diff --git a/Libraries/LibJS/Rust/src/ast.rs b/Libraries/LibJS/Rust/src/ast.rs
index 4ae632c0d50..38dcf4522ab 100644
--- a/Libraries/LibJS/Rust/src/ast.rs
+++ b/Libraries/LibJS/Rust/src/ast.rs
@@ -17,7 +17,7 @@ use ak::Utf16String;
use crate::parser::FunctionRow;
use crate::parser::OuterResolutions;
use crate::parser::ScriptData;
-use crate::parser::columns::Ast;
+use crate::parser::columns::AstColumns;
use crate::parser::columns::NONE;
use crate::parser::columns::function_flag;
use crate::parser::columns::tag;
@@ -492,22 +492,6 @@ pub struct LocalBinding {
pub index: u32,
}
-/// A `var` binding that needs initialization during function entry.
-#[derive(Clone, Copy)]
-pub struct VarToInit {
- pub name: Name,
- pub is_parameter: bool,
- pub is_function_name: bool,
- /// If the scope analysis optimized this var to a local, stores the binding info.
- pub local: Option<LocalBinding>,
-}
-
-/// A function declaration that needs hoisting: its index among the children of the scope.
-#[derive(Clone, Copy)]
-pub struct FunctionToInit {
- pub child_index: u32,
-}
-
/// A range of one of the columns of scope analysis results.
#[derive(Clone, Copy, Default)]
pub(crate) struct ColumnRange {
@@ -525,8 +509,6 @@ impl ColumnRange {
#[derive(Clone, Copy, Default)]
pub(crate) struct ScopeRow {
pub(crate) local_variables: ColumnRange,
- pub(crate) vars_to_initialize: ColumnRange,
- pub(crate) functions_to_initialize: ColumnRange,
pub(crate) annexb_function_names: ColumnRange,
pub(crate) non_local_var_count: u32,
pub(crate) non_local_var_count_for_parameter_expressions: u32,
@@ -544,24 +526,12 @@ pub(crate) struct ScopeRow {
}
/// The results of scope analysis, which are the same for the whole life of a tree.
-#[derive(Default)]
-pub(crate) struct ScopeTable {
+#[derive(Clone, Copy, Default)]
+pub(crate) struct ScopeTable<'t> {
/// One per function of the function index, then one per static block, then the program's.
- pub(crate) rows: Vec<ScopeRow>,
- pub(crate) local_variables: Vec<LocalVariable>,
- pub(crate) vars_to_initialize: Vec<VarToInit>,
- pub(crate) functions_to_initialize: Vec<FunctionToInit>,
- pub(crate) annexb_function_names: Vec<Name>,
-}
-
-impl ScopeTable {
- pub(crate) fn clear(&mut self) {
- self.rows.clear();
- self.local_variables.clear();
- self.vars_to_initialize.clear();
- self.functions_to_initialize.clear();
- self.annexb_function_names.clear();
- }
+ pub(crate) rows: &'t [ScopeRow],
+ pub(crate) local_variables: &'t [LocalVariable],
+ pub(crate) annexb_function_names: &'t [Name],
}
// =============================================================================
@@ -571,29 +541,31 @@ impl ScopeTable {
/// What a compile job works from: the tree of the code it compiles, and the results of scope analysis on that code. The
/// tree of a program holds its top-level code and the functions it is likely to call right away, and the tree of a
/// function holds that function, in both cases with nothing but a function node for every other function nested in it.
-pub struct SyntaxTree {
+///
+/// The tree is made of slices in the work zone of the compile job, and lives no longer than the job.
+pub struct SyntaxTree<'t> {
/// 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) ast: AstColumns<'t>,
pub(crate) root: u32,
pub(crate) first_token_start: u32,
pub(crate) is_strict_mode: bool,
pub(crate) has_top_level_await: bool,
- pub(crate) eval_referenced_private_names: Vec<Name>,
+ pub(crate) eval_referenced_private_names: &'t [Name],
/// The resolution of the identifier at each node, if there is one.
- pub(crate) resolutions: Vec<Resolution>,
- pub(crate) scopes: ScopeTable,
+ pub(crate) resolutions: &'t [Resolution],
+ pub(crate) scopes: ScopeTable<'t>,
/// The row of the program in `scopes`.
pub(crate) program_scope_row: u32,
/// The row in `scopes` of each function node of the tree whose code the tree holds, sorted by node.
- pub(crate) function_scope_rows: Vec<(u32, u32)>,
+ pub(crate) function_scope_rows: &'t [(u32, u32)],
/// What scope analysis found out for the functions that the code of the tree goes on to compile.
pub(crate) outer_resolutions: Option<OuterResolutions>,
}
-impl SyntaxTree {
+impl SyntaxTree<'_> {
fn tag(&self, node: u32) -> u8 {
self.ast.tag[node as usize]
}
@@ -1119,12 +1091,12 @@ macro_rules! impl_sequence_into_iterator {
/// A view that one list item of the tree turns into.
pub trait ListItem<'a>: Sized {
type Context: Copy;
- fn read(tree: &'a SyntaxTree, node: u32, context: Self::Context) -> Self;
+ fn read(tree: &'a SyntaxTree<'a>, node: u32, context: Self::Context) -> Self;
}
/// A list of the tree, read as views of type `T`.
pub struct List<'a, T: ListItem<'a>> {
- tree: &'a SyntaxTree,
+ tree: &'a SyntaxTree<'a>,
items: &'a [u32],
context: T::Context,
item_type: PhantomData<T>,
@@ -1139,11 +1111,11 @@ impl<'a, T: ListItem<'a>> Clone for List<'a, T> {
impl<'a, T: ListItem<'a>> Copy for List<'a, T> {}
impl<'a, T: ListItem<'a>> List<'a, T> {
- fn new(tree: &'a SyntaxTree, start: u32, context: T::Context) -> Self {
+ fn new(tree: &'a SyntaxTree<'a>, start: u32, context: T::Context) -> Self {
Self::of_items(tree, tree.list(start), context)
}
- fn of_items(tree: &'a SyntaxTree, items: &'a [u32], context: T::Context) -> Self {
+ fn of_items(tree: &'a SyntaxTree<'a>, items: &'a [u32], context: T::Context) -> Self {
Self {
tree,
items,
@@ -1183,21 +1155,21 @@ impl<'a, T: ListItem<'a>> IntoIterator for &List<'a, T> {
impl<'a> ListItem<'a> for Expression<'a> {
type Context = ();
- fn read(tree: &'a SyntaxTree, node: u32, _: ()) -> Self {
+ fn read(tree: &'a SyntaxTree<'a>, node: u32, _: ()) -> Self {
Expression::new(tree, node)
}
}
impl<'a> ListItem<'a> for Option<Expression<'a>> {
type Context = ();
- fn read(tree: &'a SyntaxTree, node: u32, _: ()) -> Self {
+ fn read(tree: &'a SyntaxTree<'a>, node: u32, _: ()) -> Self {
(tree.tag(node) != tag::HOLE).then(|| Expression::new(tree, node))
}
}
impl<'a> ListItem<'a> for Statement<'a> {
type Context = ();
- fn read(tree: &'a SyntaxTree, node: u32, _: ()) -> Self {
+ fn read(tree: &'a SyntaxTree<'a>, node: u32, _: ()) -> Self {
Statement::new(tree, node)
}
}
@@ -1209,7 +1181,7 @@ impl<'a> ListItem<'a> for Statement<'a> {
/// An identifier reference or binding name, with what scope analysis found out about it.
#[derive(Clone, Copy)]
pub struct Identifier<'a> {
- tree: &'a SyntaxTree,
+ tree: &'a SyntaxTree<'a>,
pub name: Name,
offset: u32,
pub local_type: Option<LocalType>,
@@ -1220,7 +1192,7 @@ pub struct Identifier<'a> {
}
impl<'a> Identifier<'a> {
- fn new(tree: &'a SyntaxTree, name: Name, offset: u32, resolution: Resolution) -> Self {
+ fn new(tree: &'a SyntaxTree<'a>, name: Name, offset: u32, resolution: Resolution) -> Self {
Self {
tree,
name,
@@ -1248,7 +1220,7 @@ impl<'a> Identifier<'a> {
#[derive(Clone, Copy)]
pub struct PrivateIdentifier<'a> {
- tree: &'a SyntaxTree,
+ tree: &'a SyntaxTree<'a>,
name: Name,
offset: u32,
}
@@ -1329,7 +1301,7 @@ pub struct FunctionData<'a> {
#[derive(Clone, Copy)]
pub struct FunctionParameters<'a> {
- tree: &'a SyntaxTree,
+ tree: &'a SyntaxTree<'a>,
parameters: &'a [u32],
/// Where the names of parameters count as being.
first_position: u32,
@@ -1338,7 +1310,7 @@ pub struct FunctionParameters<'a> {
}
impl<'a> FunctionParameters<'a> {
- fn empty(tree: &'a SyntaxTree) -> Self {
+ fn empty(tree: &'a SyntaxTree<'a>) -> Self {
Self {
tree,
parameters: &[],
@@ -1417,7 +1389,7 @@ pub struct ClassData<'a> {
/// The elements of a class, other than its constructor.
#[derive(Clone, Copy)]
pub struct ClassElements<'a> {
- tree: &'a SyntaxTree,
+ tree: &'a SyntaxTree<'a>,
elements: &'a [u32],
constructor_index: Option<usize>,
class_start: u32,
@@ -1445,7 +1417,7 @@ impl<'a> Sequence for ClassElements<'a> {
#[derive(Clone, Copy)]
pub struct ClassElementNode<'a> {
- tree: &'a SyntaxTree,
+ tree: &'a SyntaxTree<'a>,
node: u32,
class_start: u32,
}
@@ -1565,7 +1537,7 @@ pub struct BindingPattern<'a> {
}
impl<'a> BindingPattern<'a> {
- pub(crate) fn new(tree: &'a SyntaxTree, node: u32, mode: PatternMode) -> Self {
+ pub(crate) fn new(tree: &'a SyntaxTree<'a>, node: u32, mode: PatternMode) -> Self {
let is_array = tree.tag(node) == tag::ARRAY_PATTERN;
Self {
kind: if is_array {
@@ -1601,7 +1573,7 @@ pub enum BindingEntryName<'a> {
/// The key of a property in a pattern, which refers to no binding.
#[derive(Clone, Copy)]
pub struct PropertyKey<'a> {
- tree: &'a SyntaxTree,
+ tree: &'a SyntaxTree<'a>,
node: u32,
}
@@ -1641,7 +1613,7 @@ pub enum BindingEntryAlias<'a> {
MemberExpression(Expression<'a>),
}
-fn pattern_alias(tree: &SyntaxTree, value: u32, mode: PatternMode) -> BindingEntryAlias<'_> {
+fn pattern_alias<'a>(tree: &'a SyntaxTree<'a>, value: u32, mode: PatternMode) -> BindingEntryAlias<'a> {
match tree.tag(value) {
tag::ARRAY_PATTERN | tag::OBJECT_PATTERN => {
BindingEntryAlias::BindingPattern(BindingPattern::new(tree, value, mode))
@@ -1662,7 +1634,7 @@ fn pattern_alias(tree: &SyntaxTree, value: u32, mode: PatternMode) -> BindingEnt
impl<'a> ListItem<'a> for BindingEntry<'a> {
type Context = (bool, PatternMode);
- fn read(tree: &'a SyntaxTree, item: u32, (is_array, mode): Self::Context) -> Self {
+ fn read(tree: &'a SyntaxTree<'a>, item: u32, (is_array, mode): Self::Context) -> Self {
let item_tag = tree.tag(item);
if item_tag == tag::HOLE {
return BindingEntry {
@@ -1732,7 +1704,7 @@ impl<'a> ListItem<'a> for BindingEntry<'a> {
#[derive(Clone, Copy)]
pub struct ObjectProperty<'a> {
- tree: &'a SyntaxTree,
+ tree: &'a SyntaxTree<'a>,
offset: u32,
pub property_type: ObjectPropertyType,
pub key: Expression<'a>,
@@ -1751,7 +1723,7 @@ impl<'a> ListItem<'a> for ObjectProperty<'a> {
/// Where the object starts.
type Context = u32;
- fn read(tree: &'a SyntaxTree, property: u32, object_start: u32) -> Self {
+ fn read(tree: &'a SyntaxTree<'a>, property: u32, object_start: u32) -> Self {
let property_tag = tree.tag(property);
let (a, b) = (tree.a(property), tree.b(property));
match property_tag {
@@ -1821,7 +1793,7 @@ pub struct CallArgument<'a> {
impl<'a> ListItem<'a> for CallArgument<'a> {
type Context = ();
- fn read(tree: &'a SyntaxTree, argument: u32, _: ()) -> Self {
+ fn read(tree: &'a SyntaxTree<'a>, argument: u32, _: ()) -> Self {
let is_spread = tree.tag(argument) == tag::SPREAD;
CallArgument {
value: Expression::new(tree, if is_spread { tree.a(argument) } else { argument }),
@@ -1893,7 +1865,7 @@ pub enum OptionalChainReference<'a> {
#[derive(Clone, Copy)]
pub struct OptionalChainData<'a> {
- tree: &'a SyntaxTree,
+ tree: &'a SyntaxTree<'a>,
node: u32,
}
@@ -1921,7 +1893,7 @@ impl<'a> OptionalChainData<'a> {
/// The chain reaches down to its innermost optional link, and what is below that is its base. Returns the base and
/// the links, outermost first.
- pub(crate) fn links(tree: &SyntaxTree, node: u32) -> (u32, Vec<u32>) {
+ pub(crate) fn links(tree: &SyntaxTree<'_>, node: u32) -> (u32, Vec<u32>) {
let mut links = Vec::new();
let mut base = node;
let mut remaining_optional_links = 0;
@@ -2029,7 +2001,7 @@ pub struct TemplateElementContext {
impl<'a> ListItem<'a> for TemplateElement<'a> {
type Context = TemplateElementContext;
- fn read(tree: &'a SyntaxTree, node: u32, context: TemplateElementContext) -> Self {
+ fn read(tree: &'a SyntaxTree<'a>, node: u32, context: TemplateElementContext) -> Self {
TemplateElement(if tree.tag(node) == tag::TEMPLATE_CHUNK {
Expression::with_form(
tree,
@@ -2050,7 +2022,7 @@ pub struct TemplateElement<'a>(pub Expression<'a>);
#[derive(Clone, Copy)]
pub struct TemplateLiteralData<'a> {
- tree: &'a SyntaxTree,
+ tree: &'a SyntaxTree<'a>,
items: &'a [u32],
pub expressions: List<'a, TemplateElement<'a>>,
}
@@ -2067,7 +2039,7 @@ impl TemplateLiteralData<'_> {
}
}
-fn template_chunk_units(tree: &SyntaxTree, chunk: u32) -> Utf16View<'_> {
+fn template_chunk_units<'a>(tree: &'a SyntaxTree<'a>, chunk: u32) -> Utf16View<'a> {
let start = tree.a(chunk);
tree.source_units(start, start + (tree.b(chunk) >> 1))
}
@@ -2078,7 +2050,7 @@ fn template_chunk_units(tree: &SyntaxTree, chunk: u32) -> Utf16View<'_> {
#[derive(Clone, Copy)]
pub struct VariableDeclarator<'a> {
- tree: &'a SyntaxTree,
+ tree: &'a SyntaxTree<'a>,
offset: u32,
pub target: VariableDeclaratorTarget<'a>,
pub init: Option<Expression<'a>>,
@@ -2100,7 +2072,7 @@ impl<'a> ListItem<'a> for VariableDeclarator<'a> {
/// Where the declaration starts.
type Context = u32;
- fn read(tree: &'a SyntaxTree, declarator: u32, offset: u32) -> Self {
+ fn read(tree: &'a SyntaxTree<'a>, declarator: u32, offset: u32) -> Self {
let (target, init) = (tree.a(declarator), tree.b(declarator));
VariableDeclarator {
tree,
@@ -2231,7 +2203,7 @@ pub struct TryStatementData<'a> {
#[derive(Clone, Copy)]
pub struct CatchClause<'a> {
- tree: &'a SyntaxTree,
+ tree: &'a SyntaxTree<'a>,
offset: u32,
pub parameter: Option<CatchBinding<'a>>,
pub body: Statement<'a>,
@@ -2257,7 +2229,7 @@ pub struct SwitchStatementData<'a> {
#[derive(Clone, Copy)]
pub struct SwitchCase<'a> {
- tree: &'a SyntaxTree,
+ tree: &'a SyntaxTree<'a>,
offset: u32,
pub scope: Scope<'a>,
pub test: Option<Expression<'a>>,
@@ -2272,7 +2244,7 @@ impl SwitchCase<'_> {
impl<'a> ListItem<'a> for SwitchCase<'a> {
type Context = ();
- fn read(tree: &'a SyntaxTree, case: u32, _: ()) -> Self {
+ fn read(tree: &'a SyntaxTree<'a>, case: u32, _: ()) -> Self {
let test = tree.a(case);
SwitchCase {
tree,
@@ -2285,7 +2257,7 @@ impl<'a> ListItem<'a> for SwitchCase<'a> {
#[derive(Clone, Copy)]
pub struct ImportStatementData<'a> {
- tree: &'a SyntaxTree,
+ tree: &'a SyntaxTree<'a>,
node: u32,
}
@@ -2315,7 +2287,7 @@ impl ImportStatementData<'_> {
#[derive(Clone, Copy)]
pub struct ExportStatementData<'a> {
- tree: &'a SyntaxTree,
+ tree: &'a SyntaxTree<'a>,
node: u32,
pub statement: Option<Statement<'a>>,
pub is_default_export: bool,
@@ -2452,14 +2424,14 @@ impl<'a> Sequence for ScopeChildren<'a> {
/// A scope with statements of its own: a program, a function body, a block or a case of a switch.
#[derive(Clone, Copy)]
pub struct Scope<'a> {
- tree: &'a SyntaxTree,
+ tree: &'a SyntaxTree<'a>,
pub children: ScopeChildren<'a>,
/// What scope analysis found out if this is the scope of a function, a static block or a program.
row: Option<&'a ScopeRow>,
}
impl<'a> Scope<'a> {
- fn new(tree: &'a SyntaxTree, children: ScopeChildren<'a>) -> Self {
+ fn new(tree: &'a SyntaxTree<'a>, children: ScopeChildren<'a>) -> Self {
Self {
tree,
children,
@@ -2467,11 +2439,11 @@ impl<'a> Scope<'a> {
}
}
- fn of_list(tree: &'a SyntaxTree, list: u32) -> Self {
+ fn of_list(tree: &'a SyntaxTree<'a>, list: u32) -> Self {
Self::new(tree, ScopeChildren::List(List::new(tree, list, ())))
}
- fn of_function(tree: &'a SyntaxTree, children: ScopeChildren<'a>, row: &'a ScopeRow) -> Self {
+ fn of_function(tree: &'a SyntaxTree<'a>, children: ScopeChildren<'a>, row: &'a ScopeRow) -> Self {
Self {
tree,
children,
@@ -2481,14 +2453,14 @@ impl<'a> Scope<'a> {
pub fn local_variables(&self) -> &'a [LocalVariable] {
self.row
- .map_or(&[], |row| row.local_variables.of(&self.tree.scopes.local_variables))
+ .map_or(&[], |row| row.local_variables.of(self.tree.scopes.local_variables))
}
/// Function names hoisted from inner blocks via Annex B.3.3. The FDI should create `var` bindings initialized to
/// `undefined` for each name.
pub fn annexb_function_names(&self) -> &'a [Name] {
self.row.map_or(&[], |row| {
- row.annexb_function_names.of(&self.tree.scopes.annexb_function_names)
+ row.annexb_function_names.of(self.tree.scopes.annexb_function_names)
})
}
@@ -2539,7 +2511,7 @@ enum ExpressionForm {
#[derive(Clone, Copy)]
pub struct Expression<'a> {
- tree: &'a SyntaxTree,
+ tree: &'a SyntaxTree<'a>,
node: u32,
form: ExpressionForm,
}
@@ -2722,14 +2694,14 @@ pub(crate) const ASSIGNMENT_OPERATORS: [AssignmentOp; 16] = [
impl<'a> Expression<'a> {
/// The expression at `node`, which a pair of parentheses leaves as it is.
- pub(crate) fn new(tree: &'a SyntaxTree, mut node: u32) -> Self {
+ pub(crate) fn new(tree: &'a SyntaxTree<'a>, mut node: u32) -> Self {
while tree.tag(node) == tag::PAREN {
node = tree.a(node);
}
Self::with_form(tree, node, ExpressionForm::Node)
}
- fn with_form(tree: &'a SyntaxTree, node: u32, form: ExpressionForm) -> Self {
+ fn with_form(tree: &'a SyntaxTree<'a>, node: u32, form: ExpressionForm) -> Self {
Self { tree, node, form }
}
@@ -2998,7 +2970,7 @@ enum StatementForm {
#[derive(Clone, Copy)]
pub struct Statement<'a> {
- tree: &'a SyntaxTree,
+ tree: &'a SyntaxTree<'a>,
node: u32,
form: StatementForm,
}
@@ -3047,11 +3019,11 @@ pub enum StatementKind<'a> {
}
impl<'a> Statement<'a> {
- pub(crate) fn new(tree: &'a SyntaxTree, node: u32) -> Self {
+ pub(crate) fn new(tree: &'a SyntaxTree<'a>, node: u32) -> Self {
Self::with_form(tree, node, StatementForm::Node)
}
- fn with_form(tree: &'a SyntaxTree, node: u32, form: StatementForm) -> Self {
+ fn with_form(tree: &'a SyntaxTree<'a>, node: u32, form: StatementForm) -> Self {
Self { tree, node, form }
}
diff --git a/Libraries/LibJS/Rust/src/ast_dump.rs b/Libraries/LibJS/Rust/src/ast_dump.rs
index 1bd9c9dd222..0cce77bba0e 100644
--- a/Libraries/LibJS/Rust/src/ast_dump.rs
+++ b/Libraries/LibJS/Rust/src/ast_dump.rs
@@ -60,7 +60,7 @@ struct DumpState<'a> {
is_root: bool,
use_color: bool,
output: Option<&'a RefCell<String>>,
- tree: &'a SyntaxTree,
+ tree: &'a SyntaxTree<'a>,
}
fn print_node(state: &DumpState, text: &str) {
@@ -269,7 +269,7 @@ fn dump_labeled_statement(label: &str, statement: &Statement, is_last: bool, sta
// Entry point
// ============================================================================
-pub fn dump_program_to_string(tree: &SyntaxTree) -> String {
+pub fn dump_program_to_string(tree: &SyntaxTree<'_>) -> String {
let output = RefCell::new(String::new());
let state = DumpState {
prefix: String::new(),
diff --git a/Libraries/LibJS/Rust/src/bytecode/codegen/constructs.rs b/Libraries/LibJS/Rust/src/bytecode/codegen/constructs.rs
index 43b84ccb2c0..f71ddce014a 100644
--- a/Libraries/LibJS/Rust/src/bytecode/codegen/constructs.rs
+++ b/Libraries/LibJS/Rust/src/bytecode/codegen/constructs.rs
@@ -59,7 +59,7 @@ use crate::parser::literals::raw_template_value;
const FIRST_ROW_OF_REPARSED_FUNCTION: usize = 1;
/// The name of a field whose key is not computed, which a computed key gets only when the class is defined.
-fn class_field_name(tree: &SyntaxTree, field: NodeId) -> Option<ak::Utf16String> {
+fn class_field_name(tree: &SyntaxTree<'_>, field: NodeId) -> Option<ak::Utf16String> {
if tree.node_tag(field) == tag::COMPUTED_CLASS_FIELD {
return None;
}
@@ -220,8 +220,8 @@ impl Generator<'_> {
let is_value_of_computed_key = next_row != 0
&& mark_row != 0
&& match tree.ast.tag[mark_row - 1] {
- tag::MARK_COMPUTED_KEY => next_tag(&tree.ast.tag, next_row - 1) == tag::COMPUTED_PROPERTY,
- tag::MARK_KEY => next_tag(&tree.ast.tag, next_row - 1) == tag::PROPERTY,
+ tag::MARK_COMPUTED_KEY => next_tag(tree.ast.tag, next_row - 1) == tag::COMPUTED_PROPERTY,
+ tag::MARK_KEY => next_tag(tree.ast.tag, next_row - 1) == tag::PROPERTY,
_ => false,
};
let computed_name = if data.name.is_some() {
@@ -2064,7 +2064,7 @@ pub(super) fn literal_initializer(generator: &Generator<'_>, initializer: NodeId
}
/// Whether a parameter has anything that gets evaluated in it.
-fn parameter_has_expression(tree: &SyntaxTree, parameter: NodeId) -> bool {
+fn parameter_has_expression(tree: &SyntaxTree<'_>, parameter: NodeId) -> bool {
let target = match tree.node_tag(parameter) {
tag::ASSIGN_PATTERN => return true,
tag::REST => NodeId(tree.node_a(parameter)),
@@ -2076,7 +2076,7 @@ fn parameter_has_expression(tree: &SyntaxTree, parameter: NodeId) -> bool {
/// Calls `callback` with each of the BoundNames of `target`, an identifier or a binding pattern, in the order of the
/// source.
-fn for_each_bound_name(tree: &SyntaxTree, target: NodeId, callback: &mut impl FnMut(Name)) {
+fn for_each_bound_name(tree: &SyntaxTree<'_>, target: NodeId, callback: &mut impl FnMut(Name)) {
match tree.node_tag(target) {
tag::ARRAY_PATTERN | tag::OBJECT_PATTERN => {
for item in tree.node_list(tree.node_a(target)).iter() {
@@ -2097,6 +2097,6 @@ fn for_each_bound_name(tree: &SyntaxTree, target: NodeId, callback: &mut impl Fn
/// What a function has for parameters.
#[inline(always)]
-fn parameters_of(tree: &SyntaxTree, function: NodeId) -> NodeList<'_> {
+fn parameters_of<'a>(tree: &'a SyntaxTree<'a>, function: NodeId) -> NodeList<'a> {
tree.node_list(tree.extra_at(tree.node_a(function)))
}
diff --git a/Libraries/LibJS/Rust/src/bytecode/codegen/context.rs b/Libraries/LibJS/Rust/src/bytecode/codegen/context.rs
index ffcf28d0caf..062745eb018 100644
--- a/Libraries/LibJS/Rust/src/bytecode/codegen/context.rs
+++ b/Libraries/LibJS/Rust/src/bytecode/codegen/context.rs
@@ -95,7 +95,7 @@ thread_local! {
/// The state of generating code for one function.
pub struct Generator<'t> {
- pub(super) tree: &'t SyntaxTree,
+ pub(super) tree: &'t SyntaxTree<'t>,
pub(super) context: ManuallyDrop<Box<CodegenContext>>,
pub(super) current_source_offset: SourceOffset,
@@ -176,7 +176,7 @@ impl Drop for Generator<'_> {
}
impl<'t> Generator<'t> {
- pub(super) fn new(tree: &'t SyntaxTree, enclosing_code: Arc<EnclosingCode>, stack_limit: usize) -> Self {
+ pub(super) fn new(tree: &'t SyntaxTree<'t>, enclosing_code: Arc<EnclosingCode>, stack_limit: usize) -> Self {
let mut context = SPARE_CONTEXT.take().unwrap_or_default();
context.names.begin_compile(&tree.script);
Self {
diff --git a/Libraries/LibJS/Rust/src/bytecode/codegen/mod.rs b/Libraries/LibJS/Rust/src/bytecode/codegen/mod.rs
index a3d6616f6a9..dd614faa6db 100644
--- a/Libraries/LibJS/Rust/src/bytecode/codegen/mod.rs
+++ b/Libraries/LibJS/Rust/src/bytecode/codegen/mod.rs
@@ -37,6 +37,8 @@ use crate::bytecode::executable_data::PrecompiledFunction;
use crate::bytecode::instruction::typed as op;
use crate::parser::EnclosingCode;
use crate::parser::OutOfStack;
+use crate::parser::TopLevelRows;
+use ak::Zone;
use context::Generator;
pub use environment::EnclosingEnvironmentScope;
use nodes::NodeId;
@@ -52,8 +54,9 @@ pub(crate) fn inline_argument_limit(builtin_abstract_operations_enabled: bool) -
}
}
-/// Compiles the function at `row`, which gets parsed again for that.
+/// Compiles the function at `row`, which gets parsed again for that, into a tree in `zone`.
pub fn compile_function(
+ zone: &Zone,
script: &Arc<crate::parser::ScriptData>,
row: crate::parser::FunctionRow,
enclosing_environment_scope: Option<Arc<EnclosingEnvironmentScope>>,
@@ -62,55 +65,55 @@ pub fn compile_function(
stack_limit: usize,
) -> Result<PrecompiledFunction, OutOfStack> {
let (tree, node) = script.reparse_for_sweep(
+ zone,
row,
stack_limit,
inline_argument_limit(builtin_abstract_operations_enabled),
)?;
- let result = {
- let mut generator = Generator::new(&tree, enclosing_code.clone(), stack_limit);
- generator.enclosing_environment_scope = enclosing_environment_scope;
- generator.builtin_abstract_operations_enabled = builtin_abstract_operations_enabled;
- generator.begin_function_scope(row);
- let function = NodeId(node);
- let flags = script.index.flags[row.0 as usize];
- use crate::parser::columns::function_flag::*;
- let swept = if flags & FIELD_INITIALIZER != 0 {
- generator.sweep_field_initializer(function)
- } else if flags & STATIC_BLOCK != 0 {
- generator.sweep_static_block(function)
- } else if flags & DEFAULT_CONSTRUCTOR != 0 {
- generator.current_source_offset =
- crate::bytecode::source_map::SourceOffset(script.index.start[row.0 as usize]);
- generator.generate_default_constructor(flags & DERIVED_CONSTRUCTOR != 0);
- Ok(())
- } else {
- generator.sweep_parameter_names(function);
- generator
- .sweep_parameters(function)
- .and_then(|()| sweep::sweep_function_body(&mut generator, function))
- };
- swept.map(|()| generator.finish_function())
+ let mut generator = Generator::new(&tree, enclosing_code.clone(), stack_limit);
+ generator.enclosing_environment_scope = enclosing_environment_scope;
+ generator.builtin_abstract_operations_enabled = builtin_abstract_operations_enabled;
+ generator.begin_function_scope(row);
+ let function = NodeId(node);
+ let flags = script.index.flags[row.0 as usize];
+ use crate::parser::columns::function_flag::*;
+ let swept = if flags & FIELD_INITIALIZER != 0 {
+ generator.sweep_field_initializer(function)
+ } else if flags & STATIC_BLOCK != 0 {
+ generator.sweep_static_block(function)
+ } else if flags & DEFAULT_CONSTRUCTOR != 0 {
+ generator.current_source_offset = crate::bytecode::source_map::SourceOffset(script.index.start[row.0 as usize]);
+ generator.generate_default_constructor(flags & DERIVED_CONSTRUCTOR != 0);
+ Ok(())
+ } else {
+ generator.sweep_parameter_names(function);
+ generator
+ .sweep_parameters(function)
+ .and_then(|()| sweep::sweep_function_body(&mut generator, function))
};
- tree.give_back_memory();
- result
+ swept.map(|()| generator.finish_function())
}
/// What a compile needs to know of a program, which `compile.rs` works out.
pub struct ProgramInput<'a> {
- pub tree: &'a Arc<SyntaxTree>,
+ pub tree: &'a SyntaxTree<'a>,
+ /// The rows of the top level of the tree for a sweep, which its parse made.
+ pub top_level_rows: TopLevelRows<'a>,
pub strict: bool,
/// Whether the program is a module with top-level await, which runs like an async function.
pub is_async_module: bool,
- pub eager_compile_direct_iifes: bool,
pub enclosing_environment_scope: Option<Arc<EnclosingEnvironmentScope>>,
pub stack_limit: usize,
}
/// Compiles the script, module or eval that is the program of the tree in `input`, from the rows that its parse left.
+/// The functions that the program calls right away are marked for an eager compile, which is up to the caller, as it
+/// is a job of its own for each of them (see `crate::compile::compile_function()`).
pub fn compile_program(input: &ProgramInput<'_>) -> Result<ExecutableData, OutOfStack> {
let parsed = input.tree;
let script = &parsed.script;
- let (tree, node) = script.take_top_level_rows()?;
+ let (rows, node) = input.top_level_rows?;
+ let tree = script.tree_of_rows(rows, node);
let kind = if script.program_type == crate::ast::ProgramType::Module {
scope::ProgramKind::Module
} else if script.program_context.has_no_globals {
@@ -118,41 +121,29 @@ pub fn compile_program(input: &ProgramInput<'_>) -> Result<ExecutableData, OutOf
} else {
scope::ProgramKind::Script
};
- let compiled = {
- let mut generator = Generator::new(&tree, EnclosingCode::of_program(parsed), input.stack_limit);
- generator.strict = input.strict;
- generator.eager_compile_direct_iifes = input.eager_compile_direct_iifes;
- generator.enclosing_environment_scope = input.enclosing_environment_scope.clone();
- if input.is_async_module {
- generator.enclosing_function_kind = FunctionKind::Async;
- }
- generator.context.annexb_function_names.extend_from_slice(
- parsed
- .program_scope()
- .annexb_function_names
- .of(&parsed.scopes.annexb_function_names),
- );
- generator.begin_program_scope(kind, input.is_async_module);
- sweep::sweep_program(&mut generator, NodeId(node)).map(|()| generator.finish_function())
- };
- tree.give_back_memory();
- let mut executable = Arc::into_inner(compiled?.executable).expect("nothing else holds on to new code");
- for pending in executable.shared_function_data.iter_mut() {
- if pending.should_eager_compile {
- pending.precompiled_function =
- crate::compile::compile_function(&pending.description.payload, false, input.stack_limit)
- .ok()
- .map(Arc::new);
- }
+ let mut generator = Generator::new(&tree, EnclosingCode::of_program(parsed), input.stack_limit);
+ generator.strict = input.strict;
+ generator.eager_compile_direct_iifes = true;
+ generator.enclosing_environment_scope = input.enclosing_environment_scope.clone();
+ if input.is_async_module {
+ generator.enclosing_function_kind = FunctionKind::Async;
}
- Ok(executable)
+ generator.context.annexb_function_names.extend_from_slice(
+ parsed
+ .program_scope()
+ .annexb_function_names
+ .of(parsed.scopes.annexb_function_names),
+ );
+ generator.begin_program_scope(kind, input.is_async_module);
+ sweep::sweep_program(&mut generator, NodeId(node))?;
+ let compiled = generator.finish_function();
+ Ok(Arc::into_inner(compiled.executable).expect("nothing else holds on to new code"))
}
/// The code of a program that nests too deeply to generate code for it with the stack there is. Running it throws, like
/// a function does that is too deep to compile.
-pub fn compile_program_too_deep_to_generate(tree: &Arc<SyntaxTree>) -> ExecutableData {
- let tree_ref: &SyntaxTree = tree;
- let mut generator = Generator::new(tree_ref, EnclosingCode::of_program(tree_ref), 0);
+pub fn compile_program_too_deep_to_generate(tree: &SyntaxTree<'_>) -> ExecutableData {
+ let mut generator = Generator::new(tree, EnclosingCode::of_program(tree), 0);
generator.begin_program_scope(scope::ProgramKind::Script, true);
let exception = generator.temporary();
let error_string = generator.intern_string_text(crate::utf16::Utf16View::Utf16(utf16!(
diff --git a/Libraries/LibJS/Rust/src/bytecode/codegen/names.rs b/Libraries/LibJS/Rust/src/bytecode/codegen/names.rs
index 7a9384deabb..71e113a0fee 100644
--- a/Libraries/LibJS/Rust/src/bytecode/codegen/names.rs
+++ b/Libraries/LibJS/Rust/src/bytecode/codegen/names.rs
@@ -128,7 +128,7 @@ impl ScriptNames {
}
#[inline(always)]
- fn facts_of(&mut self, tree: &SyntaxTree, name: Name) -> NameFacts {
+ fn facts_of(&mut self, tree: &SyntaxTree<'_>, name: Name) -> NameFacts {
let index = name.0 as usize;
if index >= self.facts.len() || self.facts[index].hash == 0 {
return self.learn(tree, name);
@@ -137,7 +137,7 @@ impl ScriptNames {
}
#[cold]
- fn learn(&mut self, tree: &SyntaxTree, name: Name) -> NameFacts {
+ fn learn(&mut self, tree: &SyntaxTree<'_>, name: Name) -> NameFacts {
let index = name.0 as usize;
if index >= self.facts.len() {
let unknown = NameFacts {
@@ -155,7 +155,7 @@ impl ScriptNames {
}
#[inline(always)]
- fn fly_string(&mut self, tree: &SyntaxTree, name: Name) -> &Utf16FlyString {
+ fn fly_string(&mut self, tree: &SyntaxTree<'_>, name: Name) -> &Utf16FlyString {
let index = name.0 as usize;
if index >= self.fly_strings.len() {
self.fly_strings.resize((index + 1).next_power_of_two(), None);
@@ -267,7 +267,7 @@ impl Table {
}
#[inline(always)]
- fn intern_name(&mut self, tree: &SyntaxTree, name: Name, hash: u64) -> u32 {
+ fn intern_name(&mut self, tree: &SyntaxTree<'_>, name: Name, hash: u64) -> u32 {
let entries = &self.entries;
let text = tree.name_text(name);
let found = self.index_of.find(hash, |index| match &entries[index as usize] {
@@ -285,7 +285,7 @@ impl Table {
}
}
- fn intern_text(&mut self, tree: &SyntaxTree, script_names: &mut ScriptNames, text: Utf16View<'_>) -> u32 {
+ fn intern_text(&mut self, tree: &SyntaxTree<'_>, script_names: &mut ScriptNames, text: Utf16View<'_>) -> u32 {
let hash = hash_of_units(text);
let entries = &self.entries;
let found = self.index_of.find(hash, |index| match &entries[index as usize] {
@@ -319,7 +319,7 @@ pub(super) struct NameTables {
macro_rules! define_intern_methods {
($name_method:ident, $text_method:ident, $index_type:ident, $table:ident, $slot_field:ident) => {
#[inline(always)]
- pub(super) fn $name_method(&mut self, tree: &SyntaxTree, name: Name) -> $index_type {
+ pub(super) fn $name_method(&mut self, tree: &SyntaxTree<'_>, name: Name) -> $index_type {
let index = self.name_indices.slot_of(name).$slot_field;
if index != NO_INDEX {
return $index_type(index);
@@ -330,7 +330,7 @@ macro_rules! define_intern_methods {
$index_type(index)
}
- pub(super) fn $text_method(&mut self, tree: &SyntaxTree, text: Utf16View<'_>) -> $index_type {
+ pub(super) fn $text_method(&mut self, tree: &SyntaxTree<'_>, text: Utf16View<'_>) -> $index_type {
$index_type(self.$table.intern_text(tree, &mut self.script_names, text))
}
};
@@ -356,12 +356,12 @@ impl NameTables {
identifiers,
identifier
);
- pub(super) fn intern_string_text(&mut self, tree: &SyntaxTree, text: Utf16View<'_>) -> StringTableIndex {
+ pub(super) fn intern_string_text(&mut self, tree: &SyntaxTree<'_>, text: Utf16View<'_>) -> StringTableIndex {
StringTableIndex(self.strings.intern_text(tree, &mut self.script_names, text))
}
#[inline(always)]
- pub(super) fn intern_property_key(&mut self, tree: &SyntaxTree, name: Name) -> PropertyKeyTableIndex {
+ pub(super) fn intern_property_key(&mut self, tree: &SyntaxTree<'_>, name: Name) -> PropertyKeyTableIndex {
let index = self.name_indices.slot_of(name).property_key;
if index != NO_INDEX {
return PropertyKeyTableIndex(index);
@@ -375,7 +375,11 @@ impl NameTables {
PropertyKeyTableIndex(index)
}
- pub(super) fn intern_property_key_text(&mut self, tree: &SyntaxTree, text: Utf16View<'_>) -> PropertyKeyTableIndex {
+ pub(super) fn intern_property_key_text(
+ &mut self,
+ tree: &SyntaxTree<'_>,
+ text: Utf16View<'_>,
+ ) -> PropertyKeyTableIndex {
let index = self.property_keys.intern_text(tree, &mut self.script_names, text);
if text == utf16!("length") {
self.length_property_key = Some(index);
@@ -384,7 +388,7 @@ impl NameTables {
}
#[inline(always)]
- pub(super) fn class_of(&mut self, tree: &SyntaxTree, name: Name) -> NameClass {
+ pub(super) fn class_of(&mut self, tree: &SyntaxTree<'_>, name: Name) -> NameClass {
self.script_names.facts_of(tree, name).class
}
@@ -396,7 +400,7 @@ impl NameTables {
/// The text of an entry of the identifier table as a fly string, which is what environment scopes know names by.
pub(super) fn identifier_fly_string(
&mut self,
- tree: &SyntaxTree,
+ tree: &SyntaxTree<'_>,
identifier: IdentifierTableIndex,
) -> Utf16FlyString {
match &self.identifiers.entries[identifier.0 as usize] {
@@ -412,7 +416,7 @@ impl NameTables {
}
/// The fly string of a name, which only takes the global table once per name of a script on this thread.
- pub(super) fn fly_string_of(&mut self, tree: &SyntaxTree, name: Name) -> Utf16FlyString {
+ pub(super) fn fly_string_of(&mut self, tree: &SyntaxTree<'_>, name: Name) -> Utf16FlyString {
self.script_names.fly_string(tree, name).clone()
}
@@ -430,7 +434,7 @@ impl NameTables {
/// strings, which few executables have, on their own.
pub(super) fn take_tables(
&mut self,
- tree: &SyntaxTree,
+ tree: &SyntaxTree<'_>,
block: &mut SliceBlockBuilder,
link_block: &mut SliceBlockBuilder,
) -> (
diff --git a/Libraries/LibJS/Rust/src/bytecode/codegen/nodes.rs b/Libraries/LibJS/Rust/src/bytecode/codegen/nodes.rs
index 228f71fb60c..8934b38f941 100644
--- a/Libraries/LibJS/Rust/src/bytecode/codegen/nodes.rs
+++ b/Libraries/LibJS/Rust/src/bytecode/codegen/nodes.rs
@@ -153,7 +153,7 @@ pub(super) struct TryData {
pub(super) finalizer: Option<NodeId>,
}
-impl SyntaxTree {
+impl SyntaxTree<'_> {
#[inline(always)]
pub(super) fn node_tag(&self, node: NodeId) -> u8 {
self.ast.tag[node.index()]
diff --git a/Libraries/LibJS/Rust/src/bytecode/codegen/scope.rs b/Libraries/LibJS/Rust/src/bytecode/codegen/scope.rs
index 8e65551a878..fd0d1c97077 100644
--- a/Libraries/LibJS/Rust/src/bytecode/codegen/scope.rs
+++ b/Libraries/LibJS/Rust/src/bytecode/codegen/scope.rs
@@ -1699,7 +1699,7 @@ impl Generator<'_> {
fn note_function_resolutions(&mut self, row: u32) {
let has_direct_eval = self.has_direct_eval();
let unbound = self.unbound_resolution();
- let tree: &SyntaxTree = self.tree;
+ let tree: &SyntaxTree<'_> = self.tree;
let index = &tree.script.index;
let captures = index.capture_start[row as usize] as usize;
let capture_count = index.capture_count[row as usize] as usize;
@@ -2030,7 +2030,7 @@ impl Generator<'_> {
/// Finishes the function: what the functions nested in it need, what the function object needs, and the code.
pub(super) fn finish_function(&mut self) -> PrecompiledFunction {
- let tree: &SyntaxTree = self.tree;
+ let tree: &SyntaxTree<'_> = self.tree;
let script = &tree.script;
let index = &script.index;
let row = self.context.scope.row;
diff --git a/Libraries/LibJS/Rust/src/bytecode/codegen/sweep.rs b/Libraries/LibJS/Rust/src/bytecode/codegen/sweep.rs
index 5ccaa6e9c39..de809822f08 100644
--- a/Libraries/LibJS/Rust/src/bytecode/codegen/sweep.rs
+++ b/Libraries/LibJS/Rust/src/bytecode/codegen/sweep.rs
@@ -103,10 +103,10 @@ impl Generator<'_> {
/// Goes through the rows from `first_row` up to `end_row`, which are all of some piece of code.
pub(super) fn sweep_rows(&mut self, first_row: usize, end_row: usize) -> Result<(), OutOfStack> {
let tree = self.tree;
- let tags = &tree.ast.tag[..];
- let positions = &tree.ast.pos[..];
- let a_column = &tree.ast.a[..];
- let b_column = &tree.ast.b[..];
+ let tags = tree.ast.tag;
+ let positions = tree.ast.pos;
+ let a_column = tree.ast.a;
+ let b_column = tree.ast.b;
let mut declaration_kind = DeclarationKind::Var;
let mut declared_ident = None;
let mut declared_resource = None;
@@ -587,7 +587,7 @@ impl Generator<'_> {
/// value. Its rows go from `row` up to `next_row`.
pub(super) fn name_of_anonymous_definition(&mut self, row: usize, next_row: usize) -> Option<IdentifierTableIndex> {
let tree = self.tree;
- let tags = &tree.ast.tag[..];
+ let tags = tree.ast.tag;
if let Some(name) = self.context.stream.pending_function_name.take() {
return Some(name);
}
@@ -622,7 +622,7 @@ impl Generator<'_> {
}
/// Whether the function expression at `row` is what the code around it calls, directly or through `call` or `apply`.
-fn is_called_right_away(tree: &SyntaxTree, row: usize) -> bool {
+fn is_called_right_away(tree: &SyntaxTree<'_>, row: usize) -> bool {
let mut next = row + 1;
while tree.ast.tag[next] == tag::PAREN {
next += 1;
@@ -638,7 +638,7 @@ fn is_called_right_away(tree: &SyntaxTree, row: usize) -> bool {
}
/// Whether `key` of a property is what makes a property set the prototype.
-fn is_proto_key(tree: &SyntaxTree, key: NodeId) -> bool {
+fn is_proto_key(tree: &SyntaxTree<'_>, key: NodeId) -> bool {
match tree.node_tag(key) {
tag::IDENT_KEY => tree.node_a(key) == N_PROTO,
tag::STR_KEY => tree.string_literal_text(key).view() == crate::utf16::Utf16View::Ascii(b"__proto__"),
@@ -647,19 +647,19 @@ fn is_proto_key(tree: &SyntaxTree, key: NodeId) -> bool {
}
/// Whether the function at `function` has no name of its own.
-pub(super) fn is_anonymous(tree: &SyntaxTree, function: NodeId) -> bool {
+pub(super) fn is_anonymous(tree: &SyntaxTree<'_>, function: NodeId) -> bool {
tree.script.index.name[tree.node_b(function) as usize] == NONE
}
/// https://tc39.es/ecma262/#sec-static-semantics-isfunctiondefinition
#[inline(always)]
-fn is_function_definition(tree: &SyntaxTree, expression: NodeId) -> bool {
+fn is_function_definition(tree: &SyntaxTree<'_>, expression: NodeId) -> bool {
matches!(tree.node_tag(expression), tag::FUNCTION | tag::CLASS)
}
/// https://tc39.es/ecma262/#sec-static-semantics-hasname
#[inline(always)]
-fn has_name(tree: &SyntaxTree, expression: NodeId) -> bool {
+fn has_name(tree: &SyntaxTree<'_>, expression: NodeId) -> bool {
match tree.node_tag(expression) {
tag::FUNCTION => !is_anonymous(tree, expression),
tag::CLASS => tree.node_a(expression) != NONE,
@@ -668,7 +668,7 @@ fn has_name(tree: &SyntaxTree, expression: NodeId) -> bool {
}
/// https://tc39.es/ecma262/#sec-isanonymousfunctiondefinition
-pub(super) fn is_anonymous_function_definition(tree: &SyntaxTree, expression: NodeId) -> bool {
+pub(super) fn is_anonymous_function_definition(tree: &SyntaxTree<'_>, expression: NodeId) -> bool {
// NB: IsFunctionDefinition and HasName of a ParenthesizedExpression are those of the expression in it.
let expression = tree.skip_parens(expression);
diff --git a/Libraries/LibJS/Rust/src/compile.rs b/Libraries/LibJS/Rust/src/compile.rs
index aa69e4e7f58..508c64c3c67 100644
--- a/Libraries/LibJS/Rust/src/compile.rs
+++ b/Libraries/LibJS/Rust/src/compile.rs
@@ -35,9 +35,11 @@ use crate::parser::OutOfStack;
use crate::parser::ParseError;
use crate::parser::ParseOptions;
use crate::parser::ScriptData;
+use crate::parser::TopLevelRows;
use crate::parser::check_syntax;
-use crate::parser::parse_to_tree;
+use crate::parser::with_parsed_tree;
use crate::utf16::Utf16View;
+use crate::work_zone::with_work_zone;
use ak::Utf16String;
use std::collections::HashSet;
use std::sync::Arc;
@@ -53,7 +55,6 @@ const _: fn() = || {
assert_send::<CompiledModule>();
assert_send_and_sync::<bytecode::executable_data::PrecompiledFunction>();
assert_send_and_sync::<ExecutableData>();
- assert_send_and_sync::<SyntaxTree>();
assert_send_and_sync::<ScriptData>();
};
@@ -63,34 +64,31 @@ const _: fn() = || {
/// A parsed program (script or module) that can be compiled later.
/// Contains no GC references, so it can safely be transferred between threads.
+///
+/// The tree of a program lives only as long as the job of its parse, so the parse of a program without errors compiles
+/// its top-level code right away, and this holds that code. All that compiling it later does is compile the functions
+/// that it calls right away, if the caller wants them compiled now.
pub struct ParsedProgram {
- /// The tree, unless the program has errors.
- pub(crate) tree: Option<Arc<SyntaxTree>>,
+ /// The code of the program, unless the program has errors.
+ code: Option<TopLevelCode>,
pub(crate) program_type: ast::ProgramType,
pub(crate) is_strict_mode: bool,
pub(crate) has_top_level_await: bool,
pub(crate) errors: Vec<ParseError>,
pub(crate) ast_dump: Option<String>,
+ source: Utf16String,
options: ParseOptions,
}
-impl ParsedProgram {
- fn from_tree(tree: SyntaxTree, options: ParseOptions) -> Self {
- Self {
- program_type: tree.program_type(),
- is_strict_mode: tree.is_strict_mode(),
- has_top_level_await: tree.has_top_level_await(),
- tree: Some(Arc::new(tree)),
- errors: Vec::new(),
- ast_dump: None,
- options,
- }
- }
-
- pub(crate) fn tree(&self) -> &Arc<SyntaxTree> {
- self.tree.as_ref().expect("a program without errors has a tree")
- }
+/// The top-level code of a program and its declarations, which the parse of the program compiles in its job.
+struct TopLevelCode {
+ /// The code, in which the functions that it calls right away are marked for an eager compile.
+ executable: ExecutableData,
+ declarations: CompiledProgramDeclarations,
+ script: Arc<ScriptData>,
+}
+impl ParsedProgram {
pub fn has_errors(&self) -> bool {
!self.errors.is_empty()
}
@@ -115,18 +113,25 @@ 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").source;
let mut options = self.options;
options.keep_whole_tree = true;
- let tree = parse_to_tree(source, &options)
+ with_parsed_tree(&self.source, &options, |tree, _| ast_dump::dump_program_to_string(tree))
.ok()
- .expect("a program without errors parses the same way again");
- ast_dump::dump_program_to_string(&Arc::new(tree))
+ .expect("a program without errors parses the same way again")
})
}
+
+ /// The code of a program without errors, with the functions that it calls right away compiled now if
+ /// `compile_direct_iifes`.
+ fn into_code(self, compile_direct_iifes: bool) -> TopLevelCode {
+ let mut code = self.code.expect("a program without errors has code");
+ finish_top_level_code(&mut code.executable, compile_direct_iifes);
+ code
+ }
}
-/// Lex and parse a script or module, then run scope analysis on it.
+/// Lex and parse a script or module, then run scope analysis on it, and compile its top-level code if it has no
+/// errors, all in one job.
///
/// Errors are reported through the returned program rather than by failing,
/// so check [`ParsedProgram::has_errors()`] before compiling it. Lines are
@@ -140,17 +145,41 @@ pub fn parse(source: &ak::Utf16String, program_type: ProgramType, initial_line_n
};
let mut options = ParseOptions::new(program_type);
options.initial_line_number = crate::u32_from_usize(initial_line_number);
- match parse_to_tree(source, &options) {
- Ok(tree) => ParsedProgram::from_tree(tree, options),
- Err(errors) => ParsedProgram {
- tree: None,
- program_type,
- is_strict_mode: false,
- has_top_level_await: false,
- errors,
- ast_dump: None,
- options,
- },
+ let parsed = with_parsed_tree(source, &options, |tree, top_level_rows| {
+ let has_top_level_await = tree.has_top_level_await();
+ let declarations = match program_type {
+ ProgramType::Script => CompiledProgramDeclarations::Script(Arc::new(collect_script_declarations(tree))),
+ ProgramType::Module => CompiledProgramDeclarations::Module(Arc::new(collect_module_declarations(tree))),
+ };
+ let code = TopLevelCode {
+ executable: compile_program(
+ tree,
+ top_level_rows,
+ ProgramOptions {
+ strict: has_top_level_await || tree.is_strict_mode(),
+ is_async_module: has_top_level_await,
+ },
+ ),
+ declarations,
+ script: tree.script.clone(),
+ };
+ (code, tree.is_strict_mode(), has_top_level_await)
+ });
+ let (code, is_strict_mode, has_top_level_await, errors) = match parsed {
+ Ok((code, is_strict_mode, has_top_level_await)) => {
+ (Some(code), is_strict_mode, has_top_level_await, Vec::new())
+ }
+ Err(errors) => (None, false, false, errors),
+ };
+ ParsedProgram {
+ code,
+ program_type,
+ is_strict_mode,
+ has_top_level_await,
+ errors,
+ ast_dump: None,
+ source: source.clone(),
+ options,
}
}
@@ -176,7 +205,7 @@ enum CompiledProgramDeclarations {
}
/// The scope of the program of `tree`.
-fn program_scope(tree: &SyntaxTree) -> ast::Scope<'_> {
+fn program_scope<'a>(tree: &'a SyntaxTree<'a>) -> ast::Scope<'a> {
let StatementKind::Program(data) = tree.program().kind() else {
unreachable!("the root of a tree is a program");
};
@@ -202,21 +231,12 @@ pub fn compile_script(parsed: ParsedProgram) -> CompiledScript {
!parsed.has_errors(),
"compile_script() needs a script without parse errors"
);
-
- let tree = parsed.tree().clone();
- let executable = Arc::new(compile_program(
- &tree,
- ProgramOptions {
- strict: parsed.is_strict_mode,
- is_async_module: false,
- eager_compile_direct_iifes: false,
- },
- ));
-
- let declarations = Arc::new(collect_script_declarations(&tree));
-
+ let code = parsed.into_code(false);
+ let CompiledProgramDeclarations::Script(declarations) = code.declarations else {
+ unreachable!("a script has the declarations of a script");
+ };
CompiledScript {
- executable,
+ executable: Arc::new(code.executable),
declarations,
}
}
@@ -230,23 +250,47 @@ fn stack_limit_of_this_thread() -> usize {
}
}
+/// Compiles the functions that `executable`, the top-level code of a program, calls right away if `compile_direct_iifes`,
+/// and otherwise leaves them to compile when they are first called.
+fn finish_top_level_code(executable: &mut ExecutableData, compile_direct_iifes: bool) {
+ let stack_limit = stack_limit_of_this_thread();
+ // NB: Each function compiles in a job of its own (see `compile_function()`), after the job of the parse of the
+ // program is done, so that jobs never nest.
+ for pending in executable.shared_function_data.iter_mut() {
+ if !pending.should_eager_compile {
+ continue;
+ }
+ if compile_direct_iifes {
+ pending.precompiled_function = compile_function(&pending.description.payload, false, stack_limit)
+ .ok()
+ .map(Arc::new);
+ } else {
+ pending.should_eager_compile = false;
+ }
+ }
+}
+
/// What the kinds of programs differ in, as far as generating their code goes.
#[derive(Clone, Copy)]
struct ProgramOptions {
strict: bool,
/// Whether the program is a module with top-level await, which runs like an async function.
is_async_module: bool,
- eager_compile_direct_iifes: bool,
}
-/// Generates the code of the program of `tree`.
-fn compile_program(tree: &Arc<SyntaxTree>, options: ProgramOptions) -> ExecutableData {
+/// Generates the code of the program of `tree` from the rows of its top level. The functions that it calls right away
+/// are marked for an eager compile, which is up to the caller.
+fn compile_program<'z>(
+ tree: &SyntaxTree<'z>,
+ top_level_rows: TopLevelRows<'z>,
+ options: ProgramOptions,
+) -> ExecutableData {
let is_module = options.is_async_module || tree.program_type() == ProgramType::Module;
let input = bytecode::codegen::ProgramInput {
tree,
+ top_level_rows,
strict: options.strict,
is_async_module: options.is_async_module,
- eager_compile_direct_iifes: options.eager_compile_direct_iifes,
enclosing_environment_scope: is_module.then(|| module_environment_scope(&program_scope(tree))),
stack_limit: stack_limit_of_this_thread(),
};
@@ -264,34 +308,22 @@ pub fn compile_parsed_program_off_thread(parsed: ParsedProgram) -> CompiledProgr
!parsed.has_errors(),
"compile_parsed_program_off_thread() needs a program without parse errors"
);
- let tree = parsed.tree().clone();
- let executable = Arc::new(compile_program(
- &tree,
- ProgramOptions {
- strict: parsed.has_top_level_await || parsed.is_strict_mode,
- is_async_module: parsed.has_top_level_await,
- eager_compile_direct_iifes: true,
- },
- ));
- let declarations = match parsed.program_type {
- ProgramType::Script => CompiledProgramDeclarations::Script(Arc::new(collect_script_declarations(&tree))),
- ProgramType::Module => CompiledProgramDeclarations::Module(Arc::new(collect_module_declarations(&tree))),
- };
+ let (program_type, has_top_level_await) = (parsed.program_type, parsed.has_top_level_await);
+ let code = parsed.into_code(true);
- tree.script.index.prepare_for_reparsing();
+ code.script.index.prepare_for_reparsing();
- let declarations_size = match &declarations {
+ let declarations_size = match &code.declarations {
CompiledProgramDeclarations::Script(declarations) => declarations.memory_size(),
CompiledProgramDeclarations::Module(declarations) => declarations.memory_size(),
};
-
CompiledProgram {
- program_type: parsed.program_type,
- has_top_level_await: parsed.has_top_level_await,
- top_level_size: executable.memory_size() + declarations_size,
- executable,
- declarations,
- script: tree.script.clone(),
+ program_type,
+ has_top_level_await,
+ top_level_size: code.executable.memory_size() + declarations_size,
+ executable: Arc::new(code.executable),
+ declarations: code.declarations,
+ script: code.script,
}
}
@@ -615,9 +647,10 @@ pub struct EvalContext {
pub in_class_field_initializer: bool,
}
-/// The code of an eval, parsed and analyzed without errors.
+/// The code of an eval, parsed and analyzed without errors, which its parse also compiled, as the tree of the code
+/// lives only as long as the job of the parse.
pub struct ParsedEval {
- pub(crate) tree: Arc<SyntaxTree>,
+ compiled: CompiledEval,
}
/// Parses the code of an eval, or returns its syntax errors and then its early errors.
@@ -629,8 +662,22 @@ pub fn parse_eval(source: &ak::Utf16String, context: EvalContext) -> Result<Pars
options.allow_super_property_lookup = context.allow_super_property_lookup;
options.allow_super_constructor_call = context.allow_super_constructor_call;
options.in_class_field_initializer = context.in_class_field_initializer;
- Ok(ParsedEval {
- tree: Arc::new(parse_to_tree(source, &options)?),
+ with_parsed_tree(source, &options, |tree, top_level_rows| {
+ let mut executable = compile_program(
+ tree,
+ top_level_rows,
+ ProgramOptions {
+ strict: tree.is_strict_mode(),
+ is_async_module: false,
+ },
+ );
+ finish_top_level_code(&mut executable, false);
+ ParsedEval {
+ compiled: CompiledEval {
+ executable: Arc::new(executable),
+ declarations: collect_eval_declarations(tree),
+ },
+ }
})
}
@@ -642,20 +689,7 @@ pub struct CompiledEval {
/// Compiles the code of an eval.
pub fn compile_eval(parsed: ParsedEval) -> CompiledEval {
- let tree = parsed.tree;
- let executable = Arc::new(compile_program(
- &tree,
- ProgramOptions {
- strict: tree.is_strict_mode(),
- is_async_module: false,
- eager_compile_direct_iifes: false,
- },
- ));
- let declarations = collect_eval_declarations(&tree);
- CompiledEval {
- executable,
- declarations,
- }
+ parsed.compiled
}
// =============================================================================
@@ -745,7 +779,7 @@ impl ModuleDeclarations {
}
/// Collects what ParseModule records from a module's top-level scope.
-pub fn collect_module_declarations(tree: &Arc<SyntaxTree>) -> ModuleDeclarations {
+pub fn collect_module_declarations(tree: &SyntaxTree<'_>) -> ModuleDeclarations {
use ast::ExportEntryKind;
let scope = &program_scope(tree);
@@ -957,18 +991,12 @@ pub fn compile_module(parsed: ParsedProgram) -> CompiledModule {
parsed.program_type == ProgramType::Module && !parsed.has_errors(),
"compile_module() needs a module without parse errors"
);
- let tree = parsed.tree().clone();
- let declarations = Arc::new(collect_module_declarations(&tree));
- let executable = Arc::new(compile_program(
- &tree,
- ProgramOptions {
- strict: true,
- is_async_module: parsed.has_top_level_await,
- eager_compile_direct_iifes: false,
- },
- ));
+ let code = parsed.into_code(false);
+ let CompiledProgramDeclarations::Module(declarations) = code.declarations else {
+ unreachable!("a module has the declarations of a module");
+ };
CompiledModule {
- executable,
+ executable: Arc::new(code.executable),
declarations,
}
}
@@ -978,9 +1006,9 @@ pub fn compile_module(parsed: ParsedProgram) -> CompiledModule {
// =============================================================================
/// The source of a function that CreateDynamicFunction (new Function() and its relatives) builds, parsed and analyzed
-/// without errors.
+/// without errors, and what its parse found of the function, as the tree lives only as long as the job of the parse.
pub struct ParsedDynamicFunction {
- pub(crate) tree: Arc<SyntaxTree>,
+ description: Result<SharedFunctionDescription, Vec<ParseError>>,
}
// 20.2.1.1.1 CreateDynamicFunction ( constructor, newTarget, kind, parameterArgs, bodyArg ), https://tc39.es/ecma262/#sec-createdynamicfunction
@@ -1038,56 +1066,67 @@ pub fn parse_dynamic_function(
let mut options = ParseOptions::new(ProgramType::Script);
options.suppress_globals = true;
Ok(ParsedDynamicFunction {
- tree: Arc::new(parse_to_tree(full_source, &options)?),
+ description: with_parsed_tree(full_source, &options, |tree, _| describe_dynamic_function(tree))?,
})
}
impl ParsedDynamicFunction {
/// Describes the function the source defines.
pub fn into_description(self) -> Result<SharedFunctionDescription, Vec<ParseError>> {
- // The program is a single ExpressionStatement wrapping a FunctionExpression.
- let function_id = program_scope(&self.tree)
- .children
- .iter()
- .find_map(|child| match child.kind() {
- StatementKind::FunctionDeclaration(function_declaration) => Some(function_declaration.function_id),
- StatementKind::Expression(expression) => match expression.kind() {
- ast::ExpressionKind::Function(function_id) => Some(function_id),
- _ => None,
- },
+ self.description
+ }
+}
+
+/// Describes the function that the source of a dynamic function defines.
+fn describe_dynamic_function(tree: &SyntaxTree<'_>) -> Result<SharedFunctionDescription, Vec<ParseError>> {
+ // The program is a single ExpressionStatement wrapping a FunctionExpression.
+ let function_id = program_scope(tree)
+ .children
+ .iter()
+ .find_map(|child| match child.kind() {
+ StatementKind::FunctionDeclaration(function_declaration) => Some(function_declaration.function_id),
+ StatementKind::Expression(expression) => match expression.kind() {
+ ast::ExpressionKind::Function(function_id) => Some(function_id),
_ => None,
- });
- let Some(function_id) = function_id else {
- return Err(vec![ParseError {
- message: "Failed to parse dynamic function".to_string(),
- line: 0,
- column: 0,
- }]);
- };
+ },
+ _ => None,
+ });
+ let Some(function_id) = function_id else {
+ return Err(vec![ParseError {
+ message: "Failed to parse dynamic function".to_string(),
+ line: 0,
+ column: 0,
+ }]);
+ };
- let is_strict = self.tree.function(function_id).is_strict_mode;
- Ok(describe_shared_function(
- &self.tree,
- function_id,
- is_strict,
- None,
- None,
- &EnclosingCode::of_program(&self.tree),
- ))
- }
+ let is_strict = tree.function(function_id).is_strict_mode;
+ Ok(describe_shared_function(
+ tree,
+ function_id,
+ is_strict,
+ None,
+ None,
+ &EnclosingCode::of_program(tree),
+ ))
}
// =============================================================================
// Builtin files
// =============================================================================
+/// A file of builtin functions written in JavaScript, parsed: what its parse found of the named functions that it
+/// declares at its top level, in source order.
+pub struct ParsedBuiltinFile {
+ functions: Vec<SharedFunctionDescription>,
+}
+
/// Parses a file of builtin functions written in JavaScript, which is strict code, and runs scope analysis on it.
/// Builtin files ship with the engine, so a syntax error in one stops the process.
-pub fn parse_builtin_file(source: &ak::Utf16String) -> ParsedProgram {
+pub fn parse_builtin_file(source: &ak::Utf16String) -> ParsedBuiltinFile {
let mut options = ParseOptions::new(ProgramType::Script);
options.starts_in_strict_mode = true;
- match parse_to_tree(source, &options) {
- Ok(tree) => ParsedProgram::from_tree(tree, options),
+ match with_parsed_tree(source, &options, |tree, _| describe_named_functions(tree)) {
+ Ok(functions) => ParsedBuiltinFile { functions },
Err(errors) => {
let errors: Vec<String> = errors
.iter()
@@ -1098,9 +1137,8 @@ pub fn parse_builtin_file(source: &ak::Utf16String) -> ParsedProgram {
}
}
-/// Describes the named functions that a parsed builtin file declares at its top level, in source order.
-pub fn describe_builtin_file_functions(parsed: &ParsedProgram) -> Vec<SharedFunctionDescription> {
- let tree = parsed.tree();
+/// Describes the named functions that the program of `tree` declares at its top level, in source order.
+fn describe_named_functions(tree: &SyntaxTree<'_>) -> Vec<SharedFunctionDescription> {
let enclosing_code = EnclosingCode::of_program(tree);
let mut descriptions = Vec::new();
for child in &program_scope(tree).children {
@@ -1120,6 +1158,28 @@ pub fn describe_builtin_file_functions(parsed: &ParsedProgram) -> Vec<SharedFunc
descriptions
}
+/// Describes the named functions that a parsed builtin file declares at its top level, in source order. Each call
+/// gives the functions payloads of their own.
+pub fn describe_builtin_file_functions(parsed: &ParsedBuiltinFile) -> Vec<SharedFunctionDescription> {
+ parsed
+ .functions
+ .iter()
+ .map(|description| {
+ let payload = &description.payload;
+ SharedFunctionDescription {
+ payload: Arc::new(FunctionPayload {
+ script: payload.script.clone(),
+ row: payload.row,
+ enclosing_environment_scope: payload.enclosing_environment_scope.clone(),
+ enclosing_code: payload.enclosing_code.clone(),
+ compiled: Mutex::new(None),
+ }),
+ ..description.clone()
+ }
+ })
+ .collect()
+}
+
// =============================================================================
// Shared function data
// =============================================================================
@@ -1195,7 +1255,7 @@ impl SharedFunctionDescription {
/// Describes a function of `tree`, whose code does not have to be in the tree.
pub fn describe_shared_function(
- tree: &SyntaxTree,
+ tree: &SyntaxTree<'_>,
function: FunctionId,
is_strict: bool,
name_override: Option<ak::Utf16FlyString>,
@@ -1282,7 +1342,7 @@ pub(crate) fn pending_function_of_row(
impl PendingSharedFunctionData {
/// Describes a function of `tree` that an executable creates.
pub fn new(
- tree: &SyntaxTree,
+ tree: &SyntaxTree<'_>,
function: FunctionId,
name_override: Option<ak::Utf16FlyString>,
enclosing_environment_scope: Option<Arc<bytecode::codegen::EnclosingEnvironmentScope>>,
@@ -1346,14 +1406,17 @@ pub fn compile_function(
}
let stack_limit = stack_limit.saturating_add(STACK_FOR_SMALL_WALKS);
- let compiled = bytecode::codegen::compile_function(
- &payload.script,
- payload.row,
- payload.enclosing_environment_scope.clone(),
- &payload.enclosing_code,
- builtin_abstract_operations_enabled,
- stack_limit,
- )?;
+ let compiled = with_work_zone(|zone| {
+ bytecode::codegen::compile_function(
+ zone,
+ &payload.script,
+ payload.row,
+ payload.enclosing_environment_scope.clone(),
+ &payload.enclosing_code,
+ builtin_abstract_operations_enabled,
+ stack_limit,
+ )
+ })?;
// NB: Code with builtin abstract operations is only for the builtins of the engine, whatever asked for it.
if payload.script.retains_compiled_functions() && !builtin_abstract_operations_enabled {
@@ -1429,7 +1492,7 @@ impl ScriptDeclarations {
}
/// Collect what GlobalDeclarationInstantiation needs from a script's top-level scope.
-pub fn collect_script_declarations(tree: &Arc<SyntaxTree>) -> ScriptDeclarations {
+pub fn collect_script_declarations(tree: &SyntaxTree<'_>) -> ScriptDeclarations {
use ast::DeclarationKind;
let scope = program_scope(tree);
@@ -1469,7 +1532,7 @@ pub fn collect_script_declarations(tree: &Arc<SyntaxTree>) -> ScriptDeclarations
}
/// Collect what EvalDeclarationInstantiation needs from an eval script's top-level scope.
-pub fn collect_eval_declarations(tree: &Arc<SyntaxTree>) -> EvalDeclarations {
+pub fn collect_eval_declarations(tree: &SyntaxTree<'_>) -> EvalDeclarations {
let declarations = collect_var_scoped_declarations(tree);
EvalDeclarations {
is_strict: tree.is_strict_mode(),
@@ -1494,7 +1557,7 @@ struct VarScopedDeclarations {
/// initializations, var-scoped names, annex B names, and lexical bindings.
///
/// Shared by both script and eval declaration instantiation.
-fn collect_var_scoped_declarations(tree: &Arc<SyntaxTree>) -> VarScopedDeclarations {
+fn collect_var_scoped_declarations(tree: &SyntaxTree<'_>) -> VarScopedDeclarations {
use ast::DeclarationKind;
let scope = program_scope(tree);
@@ -1757,16 +1820,6 @@ mod tests {
assert!(payload.retained_code().is_some());
}
- #[test]
- fn code_of_an_eval_does_not_keep_its_script_alive() {
- let parsed = parse_eval(&Utf16String::from_utf8("1 + 1"), EvalContext::default())
- .ok()
- .expect("the source parses");
- let script = Arc::downgrade(&parsed.tree.script);
- let _compiled = compile_eval(parsed);
- assert!(script.upgrade().is_none());
- }
-
#[test]
fn a_source_that_stops_compiling_lets_go_of_its_reparse_context() {
let program = compile(SOURCE);
diff --git a/Libraries/LibJS/Rust/src/parser/base.rs b/Libraries/LibJS/Rust/src/parser/base.rs
index d8a6e8c8618..4e4f5ac269e 100644
--- a/Libraries/LibJS/Rust/src/parser/base.rs
+++ b/Libraries/LibJS/Rust/src/parser/base.rs
@@ -235,9 +235,10 @@ pub(crate) const UNUSED_NAME: NameState = NameState {
stamp: 0,
};
-/// A parser, whose work data is in a zone. It lives as long as one parse job: the first parse of a source, or the
-/// parse of one function again.
-pub struct Parser<'a, U: Unit> {
+/// A parser, whose work data is in a zone for `'a`. It lives as long as one parse job: the first parse of a source, or
+/// the parse of one function again, which borrows the names of the source and their states from its reparse context for
+/// `'k`.
+pub struct Parser<'a, 'k, U: Unit> {
pub(crate) zone: &'a Zone,
/// Where in `rows_by_params_start` the last lookup ended up.
row_cursor: core::cell::Cell<usize>,
@@ -274,9 +275,9 @@ pub struct Parser<'a, U: Unit> {
pub(crate) prev_start: u32,
pub(crate) regex_body_end: u32,
pub(crate) name_buffer: ZoneVec<'a, u8>,
- pub interner: Interner<'a>,
+ pub interner: Interner<'k>,
- pub ast: Ast,
+ pub ast: Ast<'a>,
pub index: FunctionIndex,
pub(crate) scratch: ZoneVec<'a, u32>,
pub(crate) mode: Mode,
@@ -306,7 +307,7 @@ pub struct Parser<'a, U: Unit> {
/// The state of each name, by its id. A parse of a function again has the states of its reparse context, which
/// are all clean when it starts and ends.
- pub(crate) names: &'a mut [NameState],
+ pub(crate) names: &'k mut [NameState],
pub(crate) uses: ZoneVec<'a, UseRow>,
pub(crate) decls: ZoneVec<'a, DeclRow>,
pub(crate) scopes: ZoneVec<'a, Scope>,
@@ -389,7 +390,7 @@ pub(crate) const MAX_SUBSCRIPT_CHAIN_LENGTH: u32 = 10000;
pub(crate) const RECURSION_LIMIT_MESSAGE: &str = "Maximum parser recursion depth exceeded";
-impl<'a, U: Unit> Parser<'a, U> {
+impl<'a: 'k, 'k, U: Unit> Parser<'a, 'k, U> {
/// A parser for the first parse of `source`, with its work data in `zone`.
///
/// # Safety
@@ -469,12 +470,13 @@ impl<'a, U: Unit> Parser<'a, U> {
pub(crate) unsafe fn for_reparsing(
zone: &'a Zone,
module: bool,
- interner: Interner<'a>,
- names: &'a mut [NameState],
+ interner: Interner<'k>,
+ names: &'k mut [NameState],
stamp: u32,
index: FunctionIndex,
first_pass_index: &FunctionIndex,
source_length: u32,
+ estimated_nodes: usize,
) -> Self {
let mut parser = Self::with_capacities(
zone,
@@ -485,7 +487,7 @@ impl<'a, U: Unit> Parser<'a, U> {
interner,
names,
index,
- 256,
+ estimated_nodes,
256,
);
parser.stamp = stamp;
@@ -500,8 +502,8 @@ impl<'a, U: Unit> Parser<'a, U> {
length: usize,
module: bool,
mode: Mode,
- interner: Interner<'a>,
- names: &'a mut [NameState],
+ interner: Interner<'k>,
+ names: &'k mut [NameState],
index: FunctionIndex,
estimated_nodes: usize,
estimated_uses: usize,
@@ -534,7 +536,7 @@ impl<'a, U: Unit> Parser<'a, U> {
regex_body_end: 0,
name_buffer: ZoneVec::new_in(zone),
interner,
- ast: Ast::with_capacity(estimated_nodes),
+ ast: Ast::with_capacity(zone, estimated_nodes),
index,
scratch: ZoneVec::with_capacity_in(estimated_uses.min(4096), zone),
mode,
@@ -647,8 +649,13 @@ impl<'a, U: Unit> Parser<'a, U> {
}
/// Goes through the top level once more with marks for a sweep, past all functions, after a parse that went well.
- pub(crate) fn parse_top_level_rows(&mut self, context: ProgramContext) -> Result<(Ast, u32), super::OutOfStack> {
- let tree = std::mem::replace(&mut self.ast, Ast::with_capacity(256));
+ pub(crate) fn parse_top_level_rows(
+ &mut self,
+ context: ProgramContext,
+ ) -> Result<(Ast<'a>, u32), super::OutOfStack> {
+ // NB: The rows are those of the tree, and marks.
+ let rows = Ast::with_capacity(self.zone, self.ast.tag.len());
+ let tree = std::mem::replace(&mut self.ast, rows);
let private_names = self.eval_referenced_private_names.take();
let (first_token_start, strict, has_top_level_await) =
(self.first_token_start, self.strict, self.has_top_level_await);
@@ -2210,7 +2217,7 @@ impl<'a, U: Unit> Parser<'a, U> {
/// Ends the parse of a function again, whether it went well or not. Gives back the tree, and the index and the stamp
/// for the reparse context, whose name states are clean again.
- pub(crate) fn end_reparse(mut self) -> (Ast, FunctionIndex, u32) {
+ pub(crate) fn end_reparse(mut self) -> (Ast<'a>, FunctionIndex, u32) {
self.finish_reparse();
(self.ast, self.index, self.stamp)
}
diff --git a/Libraries/LibJS/Rust/src/parser/columns.rs b/Libraries/LibJS/Rust/src/parser/columns.rs
index 2d12368a11c..9a4f7137720 100644
--- a/Libraries/LibJS/Rust/src/parser/columns.rs
+++ b/Libraries/LibJS/Rust/src/parser/columns.rs
@@ -13,6 +13,9 @@
use std::cell::Cell;
use std::sync::OnceLock;
+use ak::Zone;
+use ak::ZoneVec;
+
use crate::u32_from_usize;
pub const NONE: u32 = u32::MAX;
@@ -118,32 +121,33 @@ pub mod tag {
pub const CALL_DIRECT_EVAL: u8 = 239; pub const CALL_DIRECT_EVAL_ARRAY: u8 = 240;
}
-pub struct Ast {
- pub tag: Vec<u8>,
- pub pos: Vec<u32>,
- pub a: Vec<u32>,
- pub b: Vec<u32>,
- pub extra: Vec<u32>,
+/// The tree that a parse makes, as columns that grow in the work zone of the parse.
+pub struct Ast<'z> {
+ pub tag: ZoneVec<'z, u8>,
+ pub pos: ZoneVec<'z, u32>,
+ pub a: ZoneVec<'z, u32>,
+ pub b: ZoneVec<'z, u32>,
+ pub extra: ZoneVec<'z, u32>,
/// One row per binding of every scope.
- pub binding_name: Vec<u32>,
- pub binding_flags: Vec<u32>,
+ pub binding_name: ZoneVec<'z, u32>,
+ pub binding_flags: ZoneVec<'z, u32>,
/// One row per scope that has bindings: where its bindings start, and its flags.
- pub scope_first_binding: Vec<u32>,
- pub scope_flags: Vec<u32>,
+ pub scope_first_binding: ZoneVec<'z, u32>,
+ pub scope_flags: ZoneVec<'z, u32>,
}
-impl Ast {
- pub fn with_capacity(nodes: usize) -> Self {
+impl<'z> Ast<'z> {
+ pub fn with_capacity(zone: &'z Zone, nodes: usize) -> Self {
let mut ast = Self {
- tag: Vec::with_capacity(nodes),
- pos: Vec::with_capacity(nodes),
- a: Vec::with_capacity(nodes),
- b: Vec::with_capacity(nodes),
- extra: Vec::with_capacity(nodes / 2),
- binding_name: Vec::new(),
- binding_flags: Vec::new(),
- scope_first_binding: Vec::new(),
- scope_flags: Vec::new(),
+ tag: ZoneVec::with_capacity_in(nodes, zone),
+ pos: ZoneVec::with_capacity_in(nodes, zone),
+ a: ZoneVec::with_capacity_in(nodes, zone),
+ b: ZoneVec::with_capacity_in(nodes, zone),
+ extra: ZoneVec::with_capacity_in(nodes / 2, zone),
+ binding_name: ZoneVec::new_in(zone),
+ binding_flags: ZoneVec::new_in(zone),
+ scope_first_binding: ZoneVec::new_in(zone),
+ scope_flags: ZoneVec::new_in(zone),
};
// Node zero stands for "no node" and for what failed to parse, and so does offset zero for "no list".
ast.push(tag::INVALID, 0, 0, 0);
@@ -151,16 +155,6 @@ impl Ast {
ast
}
- /// Goes back to what a new tree starts with, keeping the memory.
- pub fn reset(&mut self) {
- self.truncate(&AstMarks {
- nodes: 1,
- extra: 1,
- bindings: 0,
- scopes: 0,
- });
- }
-
#[inline(always)]
pub fn push(&mut self, tag: u8, pos: u32, a: u32, b: u32) -> u32 {
let index = self.tag.len();
@@ -184,11 +178,11 @@ impl Ast {
#[cold]
fn grow(&mut self) {
let wanted = self.tag.capacity().max(1024);
- self.tag.reserve_exact(wanted);
+ self.tag.reserve(wanted);
let capacity = self.tag.capacity();
- self.pos.reserve_exact(capacity - self.pos.len());
- self.a.reserve_exact(capacity - self.a.len());
- self.b.reserve_exact(capacity - self.b.len());
+ self.pos.reserve(capacity - self.pos.len());
+ self.a.reserve(capacity - self.a.len());
+ self.b.reserve(capacity - self.b.len());
}
pub fn truncate(&mut self, marks: &AstMarks) {
@@ -211,6 +205,35 @@ impl Ast {
scopes: self.scope_flags.len() as u32,
}
}
+
+ /// The columns, for as long as the zone holds them.
+ pub fn into_columns(self) -> AstColumns<'z> {
+ AstColumns {
+ tag: self.tag.into_slice(),
+ pos: self.pos.into_slice(),
+ a: self.a.into_slice(),
+ b: self.b.into_slice(),
+ extra: self.extra.into_slice(),
+ binding_name: self.binding_name.into_slice(),
+ binding_flags: self.binding_flags.into_slice(),
+ scope_first_binding: self.scope_first_binding.into_slice(),
+ scope_flags: self.scope_flags.into_slice(),
+ }
+ }
+}
+
+/// The columns of a tree that is done, which is how everything after the parser reads it.
+#[derive(Clone, Copy)]
+pub struct AstColumns<'t> {
+ pub tag: &'t [u8],
+ pub pos: &'t [u32],
+ pub a: &'t [u32],
+ pub b: &'t [u32],
+ pub extra: &'t [u32],
+ pub binding_name: &'t [u32],
+ pub binding_flags: &'t [u32],
+ pub scope_first_binding: &'t [u32],
+ pub scope_flags: &'t [u32],
}
#[derive(Clone, Copy)]
diff --git a/Libraries/LibJS/Rust/src/parser/expr.rs b/Libraries/LibJS/Rust/src/parser/expr.rs
index bddfdf1c337..a49b9d86acc 100644
--- a/Libraries/LibJS/Rust/src/parser/expr.rs
+++ b/Libraries/LibJS/Rust/src/parser/expr.rs
@@ -52,7 +52,7 @@ pub(crate) fn is_name_like(kind: T) -> bool {
kind == T::Name || kind == T::EscapedKeyword || kind as u8 >= T::KIn as u8
}
-impl<U: Unit> Parser<'_, U> {
+impl<'a: 'k, 'k, U: Unit> Parser<'a, 'k, U> {
pub(crate) fn parse_expression(&mut self, no_in: bool, cover_ok: bool) -> u32 {
let start = self.tok_start;
let first = self.parse_assign(no_in, cover_ok);
diff --git a/Libraries/LibJS/Rust/src/parser/lexer.rs b/Libraries/LibJS/Rust/src/parser/lexer.rs
index 46a5ac22052..9ada4aa2efc 100644
--- a/Libraries/LibJS/Rust/src/parser/lexer.rs
+++ b/Libraries/LibJS/Rust/src/parser/lexer.rs
@@ -50,7 +50,7 @@ fn hex_value(c: u32) -> Option<u32> {
char::from_u32(c)?.to_digit(16)
}
-impl<U: Unit> Parser<'_, U> {
+impl<'a: 'k, 'k, U: Unit> Parser<'a, 'k, U> {
/// The unit at `index`, which may be in the padding after the source.
#[inline(always)]
pub fn at(&self, index: usize) -> u32 {
diff --git a/Libraries/LibJS/Rust/src/parser/mod.rs b/Libraries/LibJS/Rust/src/parser/mod.rs
index 601a6693350..e0c1795e4a5 100644
--- a/Libraries/LibJS/Rust/src/parser/mod.rs
+++ b/Libraries/LibJS/Rust/src/parser/mod.rs
@@ -8,8 +8,9 @@
//! happens while parsing, with no map per scope. [`crate::ast`] is how everything after the parser reads the tree.
//!
//! A source is parsed once for all of its early errors. That leaves a [`ScriptData`], which is all that is kept of the
-//! source, and the tree of its top-level code. A function is parsed again on its own when it is first called. Its tree
-//! lives as long as the compile job that needs it, and nested functions are skipped by what the first parse recorded.
+//! source, and the tree of its top-level code, which lives as long as the job of the parse, so the work that needs it is
+//! part of that job. A function is parsed again on its own when it is first called. Its tree lives as long as the
+//! compile job that needs it, and nested functions are skipped by what the first parse recorded.
pub(crate) mod base;
pub(crate) mod columns;
@@ -26,7 +27,6 @@ use crate::ast::Name;
use crate::ast::NameTable;
use crate::ast::Position;
use crate::ast::ProgramType;
-use crate::ast::Resolution;
use crate::ast::ScopeTable;
use crate::ast::SyntaxTree;
use crate::source_text::SourceText;
@@ -37,6 +37,7 @@ use ak::ZoneVec;
use base::Mode;
use base::Parser;
use columns::Ast;
+use columns::AstColumns;
use columns::FunctionIndex;
use columns::function_flag;
use core::sync::atomic::AtomicBool;
@@ -47,7 +48,6 @@ use intern::Interner;
use intern::KeptNames;
pub(crate) use resolve::EnclosingCode;
pub(crate) use resolve::OuterResolutions;
-use std::cell::Cell;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::Weak;
@@ -122,8 +122,6 @@ pub struct ScriptData {
pub(crate) positions: Arc<SourcePositions>,
pub(crate) program_type: ProgramType,
pub(crate) program_context: base::ProgramContext,
- /// The rows of the top level with marks, or that they did not fit the stack, until the compile of the top level.
- top_level_rows: Mutex<Option<TopLevelRows>>,
pub(crate) default_export_name: Name,
pub(crate) default_constructor_parameter_name: Name,
/// The undeclared names that something in a `with` uses, which are not simply globals, sorted.
@@ -139,56 +137,6 @@ pub struct ScriptData {
retained_code_size: AtomicUsize,
}
-/// The memory of the tree of a function that a compile job is done with, for the next one on the thread.
-struct SpareTreeMemory {
- ast: Ast,
- resolutions: Vec<Resolution>,
- scopes: ScopeTable,
- function_scope_rows: Vec<(u32, u32)>,
-}
-
-/// What a parse of a function again is for.
-struct Reparse {
- /// The memory for the tree.
- ast: Ast,
- row: FunctionRow,
- stack_limit: usize,
- inline_argument_limit: usize,
-}
-
-/// The most nodes of a tree whose memory stays around.
-const MAXIMUM_SPARE_NODES: usize = 1 << 16;
-
-thread_local! {
- static SPARE_TREE_MEMORY: Cell<Option<SpareTreeMemory>> = const { Cell::new(None) };
-}
-
-impl SyntaxTree {
- /// Leaves the memory of this tree, which is one of a function, to the next one parsed on the thread.
- pub(crate) fn give_back_memory(self) {
- if self.ast.tag.capacity() > MAXIMUM_SPARE_NODES {
- return;
- }
- let Self {
- mut ast,
- mut resolutions,
- mut scopes,
- mut function_scope_rows,
- ..
- } = self;
- ast.reset();
- resolutions.clear();
- scopes.clear();
- function_scope_rows.clear();
- SPARE_TREE_MEMORY.set(Some(SpareTreeMemory {
- ast,
- resolutions,
- scopes,
- function_scope_rows,
- }));
- }
-}
-
/// A function could not be parsed or compiled, because the stack that is left does not hold it.
#[derive(Clone, Copy, Debug)]
pub struct OutOfStack;
@@ -238,44 +186,37 @@ impl ScriptData {
+ self.retained_code_size.load(Ordering::Relaxed)
}
- /// The rows of the top level for a sweep, which the parse of the source left here for its one compile.
- pub(crate) fn take_top_level_rows(self: &Arc<Self>) -> Result<(SyntaxTree, u32), OutOfStack> {
- let rows = self.top_level_rows.lock().expect("nothing panics with the rows").take();
- let (ast, node) = rows.expect("a top level compiles once")?;
- let tree = SyntaxTree {
+ /// A tree of `columns` with the node `root`, for a sweep, which goes by the summary of the first parse: nothing
+ /// in it is resolved.
+ pub(crate) fn tree_of_rows<'t>(self: &Arc<Self>, columns: AstColumns<'t>, root: u32) -> SyntaxTree<'t> {
+ SyntaxTree {
script: self.clone(),
source: self.positions.source.get(),
- ast,
- root: node,
+ ast: columns,
+ root,
first_token_start: 0,
is_strict_mode: false,
has_top_level_await: false,
- eval_referenced_private_names: Vec::new(),
- resolutions: Vec::new(),
+ eval_referenced_private_names: &[],
+ resolutions: &[],
scopes: ScopeTable::default(),
program_scope_row: 0,
- function_scope_rows: Vec::new(),
+ function_scope_rows: &[],
outer_resolutions: None,
- };
- Ok((tree, node))
+ }
}
- /// Parses the function at `row` again into a tree for a sweep, which goes by the summary of the first parse: nothing
- /// keeps track of scopes.
- pub(crate) fn reparse_for_sweep(
+ /// Parses the function at `row` again into a tree in `zone` for a sweep, which goes by the summary of the first
+ /// parse: nothing keeps track of scopes.
+ pub(crate) fn reparse_for_sweep<'z>(
self: &Arc<Self>,
+ zone: &'z Zone,
row: FunctionRow,
stack_limit: usize,
inline_argument_limit: usize,
- ) -> Result<(SyntaxTree, u32), OutOfStack> {
- let memory = SPARE_TREE_MEMORY.take().unwrap_or_else(|| SpareTreeMemory {
- ast: Ast::with_capacity(256),
- resolutions: Vec::new(),
- scopes: ScopeTable::default(),
- function_scope_rows: Vec::new(),
- });
+ ) -> Result<(SyntaxTree<'z>, u32), OutOfStack> {
let source = self.positions.source.get();
- let (ast, node) = with_work_zone(|zone| {
+ let (ast, node) = {
let mut context = self.reparse_context.lock().expect("a reparse does not panic");
if context.is_none() {
*context = Some(self.make_reparse_context(zone));
@@ -286,38 +227,19 @@ impl ScriptData {
}
self.reparse_context_idle_collections.store(0, Ordering::Relaxed);
let context = context.as_mut().expect("the context was just filled in");
- let reparse = Reparse {
- ast: memory.ast,
- row,
- stack_limit,
- inline_argument_limit,
- };
let result = match source.as_units() {
ak::Utf16StringUnits::Ascii(units) | ak::Utf16StringUnits::Latin1(units) => {
- self.reparse_code_units(zone, context, units, reparse)
+ self.reparse_code_units(zone, context, units, row, stack_limit, inline_argument_limit)
+ }
+ ak::Utf16StringUnits::Utf16(units) => {
+ self.reparse_code_units(zone, context, units, row, stack_limit, inline_argument_limit)
}
- ak::Utf16StringUnits::Utf16(units) => self.reparse_code_units(zone, context, units, reparse),
};
// NB: Collections counted on while the context was held, and it was not idle then.
self.reparse_context_idle_collections.store(0, Ordering::Relaxed);
result
- })?;
- let tree = SyntaxTree {
- script: self.clone(),
- source,
- ast,
- root: node,
- first_token_start: 0,
- is_strict_mode: false,
- has_top_level_await: false,
- eval_referenced_private_names: Vec::new(),
- resolutions: memory.resolutions,
- scopes: memory.scopes,
- program_scope_row: 0,
- function_scope_rows: memory.function_scope_rows,
- outer_resolutions: None,
- };
- Ok((tree, node))
+ }?;
+ Ok((self.tree_of_rows(ast.into_columns(), node), node))
}
/// A reparse context, whose tables are worked out in `zone` and copied out at their final size.
@@ -335,14 +257,20 @@ impl ScriptData {
/// Bytes after a function are real source, so that it can be read in place. What the lexer sees of a function that
/// comes too close to the end of the source for that gets copied, with the padding that the end of the source has
/// to have.
- fn reparse_code_units<U: Unit + Default>(
+ fn reparse_code_units<'z, U: Unit + Default>(
&self,
- zone: &Zone,
+ zone: &'z Zone,
context: &mut ReparseContext,
source: &[U],
- reparse: Reparse,
- ) -> Result<(Ast, u32), OutOfStack> {
- let row_index = reparse.row.0 as usize;
+ row: FunctionRow,
+ stack_limit: usize,
+ inline_argument_limit: usize,
+ ) -> Result<(Ast<'z>, u32), OutOfStack> {
+ let row_index = row.0 as usize;
+ // NB: A tree of the whole function is the most it is likely to have, as the tree skips the code of nested
+ // functions. It starts with room for at most as many nodes as the work zone keeps memory for.
+ let length = (self.index.end[row_index] - self.index.start[row_index]) as usize;
+ let estimated_nodes = (length / 3 + 16).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
@@ -357,11 +285,12 @@ impl ScriptData {
core::mem::take(&mut context.index),
&self.index,
u32_from_usize(source.len()),
+ estimated_nodes,
)
};
parser.tracks_scopes = false;
parser.marks = true;
- parser.inline_argument_limit = reparse.inline_argument_limit;
+ parser.inline_argument_limit = inline_argument_limit;
// SAFETY: The source outlives the parse, and the first parse found out that the lexer stays clear of its end
// unless the tail is what it reads.
unsafe {
@@ -375,9 +304,8 @@ impl ScriptData {
parser.set_reparse_source(source.as_ptr(), 0, u32_from_usize(source.len()));
}
}
- parser.stack_limit = reparse.stack_limit;
- parser.ast = reparse.ast;
- let node = parser.reparse_function(reparse.row.0);
+ parser.stack_limit = stack_limit;
+ let node = parser.reparse_function(row.0);
let error = parser.err.take();
// NB: The tables of the context, and the name states that cover them, stay as they are only if no name is new.
assert_eq!(
@@ -596,48 +524,35 @@ impl ParseOptions {
}
}
-/// What parsing a source without errors leaves behind.
-/// The rows of a top level with marks, and the row of the program.
-type TopLevelRows = Result<(Ast, u32), OutOfStack>;
+/// The rows of a top level with marks for a sweep, and the row of the program, or that they did not fit the stack.
+pub(crate) type TopLevelRows<'z> = Result<(AstColumns<'z>, u32), OutOfStack>;
-/// What a parse is for, which decides whether there is any use in rows for a sweep.
+/// What a parse is for, which decides whether there is any use in a tree.
#[derive(Clone, Copy, PartialEq, Eq)]
enum ParsePurpose {
Compile,
CheckSyntax,
}
-struct ParserOutput {
- ast: Ast,
- top_level_rows: Option<TopLevelRows>,
- index: FunctionIndex,
- /// The names of the source, with the two that a compile adds, for a parse that is for a compile.
- names: Option<(NameTable, Name, Name)>,
- root: u32,
- first_token_start: u32,
- is_strict_mode: bool,
- has_top_level_await: bool,
- eval_referenced_private_names: Vec<Name>,
- /// Sorted, without duplicates.
- global_names_used_in_with: Vec<u32>,
- lines: LineTable,
-}
-
-/// 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],
+/// Parses `units`, the code units of `source`, from a copy of them in `zone` that is followed by the padding the lexer
+/// needs. A parse for a compile runs `job` on the tree of the source and the rows of its top level, in the zone.
+fn parse_code_units<'z, U: Unit + Default, R>(
+ zone: &'z Zone,
+ source: &ak::Utf16String,
+ units: &[U],
options: &ParseOptions,
purpose: ParsePurpose,
-) -> Result<ParserOutput, Vec<ParseError>> {
- 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());
+ job: impl FnOnce(&SyntaxTree<'z>, TopLevelRows<'z>) -> R,
+) -> Result<Option<R>, Vec<ParseError>> {
+ let mut padded = ZoneVec::with_capacity_in(units.len() + SOURCE_PADDING, zone);
+ padded.extend_from_slice(units);
+ padded.resize(units.len() + SOURCE_PADDING, U::default());
+ let padded = padded.into_slice();
// SAFETY: The source is followed by the padding.
let mut parser = unsafe {
Parser::new(
zone,
- &padded[..source.len()],
+ &padded[..units.len()],
options.program_type == ProgramType::Module,
if options.keep_whole_tree {
Mode::Full
@@ -650,111 +565,104 @@ 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(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())));
+ let lines = LineTable::new(zone, units, options.initial_line_number);
+ let position = lines.position(error.pos.min(u32_from_usize(units.len())));
return Err(vec![ParseError {
message: error.message,
line: position.line,
column: position.column,
}]);
}
- let top_level_rows =
- (purpose == ParsePurpose::Compile).then(|| parser.parse_top_level_rows(options.program_context()));
- let names = (purpose == ParsePurpose::Compile).then(|| {
- let default_export_name = Name(parser.interner.intern_bytes(b"*default*"));
- let default_constructor_parameter_name = Name(parser.interner.intern_bytes(b"args"));
- let interner = &parser.interner;
- let names = NameTable::from_parser_names((0..interner.len()).map(|name| interner.text(u32_from_usize(name))));
- (names, default_export_name, default_constructor_parameter_name)
- });
+ if purpose == ParsePurpose::CheckSyntax {
+ return Ok(None);
+ }
+ let lines = LineTable::new(zone, units, options.initial_line_number);
+ let top_level_rows = parser
+ .parse_top_level_rows(options.program_context())
+ .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"));
+ let interner = &parser.interner;
+ let names = NameTable::from_parser_names((0..interner.len()).map(|name| interner.text(u32_from_usize(name))));
let mut global_names_used_in_with = parser.global_names_used_in_with.take();
global_names_used_in_with.sort_unstable();
global_names_used_in_with.dedup();
- let output = ParserOutput {
- top_level_rows,
- root,
- first_token_start: parser.first_token_start,
- is_strict_mode: parser.strict,
- has_top_level_await: parser.has_top_level_await,
- ast: parser.ast,
- index: parser.index,
- eval_referenced_private_names: parser
- .eval_referenced_private_names
- .iter()
- .map(|&name| Name(name))
- .collect(),
- global_names_used_in_with: global_names_used_in_with.to_vec(),
- lines,
- names,
- };
- Ok(output)
-}
-
-/// 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>> {
- with_work_zone(|zone| match source.as_units() {
- ak::Utf16StringUnits::Ascii(units) | ak::Utf16StringUnits::Latin1(units) => {
- parse_code_units(zone, 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.
-pub fn parse_to_tree(source: &ak::Utf16String, options: &ParseOptions) -> Result<SyntaxTree, Vec<ParseError>> {
- let mut output = parse_source(source, options, ParsePurpose::Compile)?;
- let (names, default_export_name, default_constructor_parameter_name) =
- output.names.take().expect("a parse for a compile gives the names");
- output.index.shrink_to_fit();
+ let eval_referenced_private_names =
+ zone.alloc_slice_from_iter(parser.eval_referenced_private_names.iter().map(|&name| Name(name)));
+ let mut index = parser.index;
+ index.shrink_to_fit();
let script = Arc::new(ScriptData {
- index: output.index,
+ index,
names,
positions: Arc::new(SourcePositions {
source: SourceText::of(source),
- lines: output.lines,
+ lines,
}),
program_type: options.program_type,
program_context: options.program_context(),
- top_level_rows: Mutex::new(output.top_level_rows),
default_export_name,
default_constructor_parameter_name,
- global_names_used_in_with: output.global_names_used_in_with,
+ global_names_used_in_with: global_names_used_in_with.to_vec(),
reparse_context: Mutex::new(None),
reparse_context_idle_collections: AtomicU8::new(0),
retains_compiled_functions: AtomicBool::new(false),
retained_code_size: AtomicUsize::new(0),
});
- let mut tree = SyntaxTree {
+ let tree = SyntaxTree {
script,
source: source.clone(),
- ast: output.ast,
- root: output.root,
- first_token_start: output.first_token_start,
- is_strict_mode: output.is_strict_mode,
- has_top_level_await: options.program_type == ProgramType::Module && output.has_top_level_await,
- eval_referenced_private_names: output.eval_referenced_private_names,
- resolutions: Vec::new(),
+ ast: parser.ast.into_columns(),
+ root,
+ first_token_start: parser.first_token_start,
+ is_strict_mode: parser.strict,
+ has_top_level_await: options.program_type == ProgramType::Module && parser.has_top_level_await,
+ eval_referenced_private_names,
+ resolutions: &[],
scopes: ScopeTable::default(),
program_scope_row: 0,
- function_scope_rows: Vec::new(),
+ function_scope_rows: &[],
outer_resolutions: None,
};
- resolve::resolve_program(
- &mut tree,
+ let resolved = resolve::resolve_program(
+ zone,
+ &tree,
&resolve::ResolveOptions {
initiated_by_eval: options.initiated_by_eval,
suppress_globals: options.suppress_globals,
},
);
- Ok(tree)
+ Ok(Some(job(&resolved.apply_to(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.
+fn parse_source<R>(
+ source: &ak::Utf16String,
+ options: &ParseOptions,
+ purpose: ParsePurpose,
+ job: impl for<'z> FnOnce(&SyntaxTree<'z>, TopLevelRows<'z>) -> R,
+) -> Result<Option<R>, Vec<ParseError>> {
+ with_work_zone(|zone| match source.as_units() {
+ ak::Utf16StringUnits::Ascii(units) | ak::Utf16StringUnits::Latin1(units) => {
+ parse_code_units(zone, source, units, options, purpose, job)
+ }
+ ak::Utf16StringUnits::Utf16(units) => parse_code_units(zone, source, units, options, purpose, job),
+ })
+}
+
+/// Parses `source` into a tree of its top-level code with its identifiers resolved, and runs `job` on the tree and the
+/// rows of its top level for a sweep. The tree lives only as long as the job of the parse, so `job` is the rest of the
+/// work that needs it.
+pub fn with_parsed_tree<R>(
+ source: &ak::Utf16String,
+ options: &ParseOptions,
+ job: impl for<'z> FnOnce(&SyntaxTree<'z>, TopLevelRows<'z>) -> R,
+) -> Result<R, Vec<ParseError>> {
+ parse_source(source, options, ParsePurpose::Compile, job)
+ .map(|result| result.expect("a parse for a compile runs its job"))
}
/// Parses `source` for its syntax errors alone.
pub fn check_syntax(source: &ak::Utf16String, options: &ParseOptions) -> Result<(), Vec<ParseError>> {
- parse_source(source, options, ParsePurpose::CheckSyntax).map(|_| ())
+ parse_source(source, options, ParsePurpose::CheckSyntax, |_, _| ()).map(|_| ())
}
diff --git a/Libraries/LibJS/Rust/src/parser/resolve.rs b/Libraries/LibJS/Rust/src/parser/resolve.rs
index 73d4676cb33..285057cee81 100644
--- a/Libraries/LibJS/Rust/src/parser/resolve.rs
+++ b/Libraries/LibJS/Rust/src/parser/resolve.rs
@@ -31,15 +31,10 @@ use super::token::N_DOT_THIS;
use super::token::N_DOT_UNBOUND;
use crate::ast::*;
use crate::u32_from_usize;
-use std::cell::Cell;
+use ak::Zone;
+use ak::ZoneVec;
use std::sync::Arc;
-/// The most entries that a table keeps its memory for when the next resolver takes over.
-const MAXIMUM_SPARE_CAPACITY: usize = 1 << 16;
-
-/// The most entries that the lists of a frame keep their memory for when the next scope takes over.
-const MAXIMUM_SPARE_FRAME_CAPACITY: usize = 1 << 12;
-
#[derive(Clone, Copy, PartialEq, Eq)]
enum FrameKind {
Program,
@@ -100,7 +95,7 @@ impl Group {
}
}
- fn add_node(&mut self, links: &mut Vec<NodeLink>, node: u32) {
+ fn add_node(&mut self, links: &mut ZoneVec<'_, NodeLink>, node: u32) {
let link = LinkId(u32_from_usize(links.len()));
links.push(NodeLink {
node,
@@ -182,15 +177,13 @@ struct ScopedName {
/// What the open scopes know of each name. A scope that knows a name has an entry for it, and the entries of a name form
/// a chain from the innermost scope outward, which starts at `innermost[name]`. Names are small numbers, so finding what
-/// the innermost scopes know of a name takes no hashing. When no scope is open, every chain is empty, so the same table
-/// serves every compile on a thread, of whichever script.
-#[derive(Default)]
-struct ScopedNames {
- innermost: Vec<ScopedNameId>,
- entries: Vec<ScopedName>,
+/// the innermost scopes know of a name takes no hashing.
+struct ScopedNames<'z> {
+ innermost: ZoneVec<'z, ScopedNameId>,
+ entries: ZoneVec<'z, ScopedName>,
}
-impl ScopedNames {
+impl ScopedNames<'_> {
fn get(&self, id: ScopedNameId) -> &ScopedName {
&self.entries[id.0 as usize]
}
@@ -235,7 +228,7 @@ impl ScopedNames {
}
/// The entry of `name` in `frame`, which is new if the scope did not know the name yet.
- fn find_or_add(&mut self, name: Name, frame: &mut Frame) -> ScopedNameId {
+ fn find_or_add(&mut self, name: Name, frame: &mut Frame<'_>) -> ScopedNameId {
let index = name.0 as usize;
if index >= self.innermost.len() {
self.innermost.resize(index + 1, ScopedNameId::NONE);
@@ -279,7 +272,7 @@ impl ScopedNames {
}
/// Forgets what `frame`, the innermost scope, knows.
- fn remove_scope(&mut self, frame: &Frame) {
+ fn remove_scope(&mut self, frame: &Frame<'_>) {
let mut id = frame.first_name;
while id != ScopedNameId::NONE {
let entry = *self.get(id);
@@ -288,7 +281,7 @@ impl ScopedNames {
}
}
- fn touch_variable(&mut self, name: Name, frame: &mut Frame) {
+ fn touch_variable(&mut self, name: Name, frame: &mut Frame<'_>) {
let id = self.find_or_add(name, frame);
let entry = self.get_mut(id);
if !entry.is_in_variable_order {
@@ -298,7 +291,7 @@ impl ScopedNames {
}
/// The group of `name` in `frame`.
- fn group_for<'f>(&mut self, name: Name, frame: &'f mut Frame) -> &'f mut Group {
+ fn group_for<'f>(&mut self, name: Name, frame: &'f mut Frame<'_>) -> &'f mut Group {
let id = self.find_or_add(name, frame);
let entry = self.get_mut(id);
if entry.group == NONE {
@@ -316,7 +309,7 @@ impl ScopedNames {
}
/// One scope on the way down the tree.
-struct Frame {
+struct Frame<'z> {
kind: FrameKind,
/// How many scopes are around this one.
depth: u32,
@@ -326,16 +319,16 @@ struct Frame {
row_flags: u32,
function_flags: u32,
rest_name: Option<Name>,
- groups: Vec<Group>,
+ groups: ZoneVec<'z, Group>,
/// What nested scopes passed on, which goes behind the scope's own groups.
- groups_from_nested_scopes: Vec<Group>,
- functions_to_hoist: Vec<Name>,
+ groups_from_nested_scopes: ZoneVec<'z, Group>,
+ functions_to_hoist: ZoneVec<'z, Name>,
/// What nested scopes passed on, which goes behind the scope's own functions.
- functions_hoisted_from_nested_scopes: Vec<Name>,
+ functions_hoisted_from_nested_scopes: ZoneVec<'z, Name>,
/// The names of the scope in the order the code declares them, with repeats left out.
- variable_order: Vec<Name>,
- local_variables: Vec<LocalVariable>,
- annexb_function_names: Vec<Name>,
+ variable_order: ZoneVec<'z, Name>,
+ local_variables: ZoneVec<'z, LocalVariable>,
+ annexb_function_names: ZoneVec<'z, Name>,
/// Where the block of this scope starts and ends, if the scope is a block.
block_offsets: Option<(u32, u32)>,
/// How many loops this scope is in the body of, counting those around the function it is in.
@@ -346,8 +339,8 @@ struct Frame {
creates_environment: bool,
}
-impl Frame {
- fn new() -> Self {
+impl<'z> Frame<'z> {
+ fn new(zone: &'z Zone) -> Self {
Self {
kind: FrameKind::Block,
depth: 0,
@@ -356,13 +349,13 @@ impl Frame {
row_flags: 0,
function_flags: 0,
rest_name: None,
- groups: Vec::new(),
- groups_from_nested_scopes: Vec::new(),
- functions_to_hoist: Vec::new(),
- functions_hoisted_from_nested_scopes: Vec::new(),
- variable_order: Vec::new(),
- local_variables: Vec::new(),
- annexb_function_names: Vec::new(),
+ groups: ZoneVec::new_in(zone),
+ groups_from_nested_scopes: ZoneVec::new_in(zone),
+ functions_to_hoist: ZoneVec::new_in(zone),
+ functions_hoisted_from_nested_scopes: ZoneVec::new_in(zone),
+ variable_order: ZoneVec::new_in(zone),
+ local_variables: ZoneVec::new_in(zone),
+ annexb_function_names: ZoneVec::new_in(zone),
block_offsets: None,
loop_depth: 0,
code_of_class_row: None,
@@ -391,12 +384,6 @@ impl Frame {
self.creates_environment = false;
}
- /// Whether this frame is better left to the allocator than kept for the next scope, after a very large scope.
- fn keeps_too_much_memory(&self) -> bool {
- self.groups.capacity() + self.groups_from_nested_scopes.capacity() + self.variable_order.capacity()
- > MAXIMUM_SPARE_FRAME_CAPACITY
- }
-
fn is_top_level(&self) -> bool {
matches!(
self.kind,
@@ -419,20 +406,6 @@ impl Frame {
}
}
-/// The memory of a resolver, which stays around for the next one on the thread.
-#[derive(Default)]
-struct ResolverMemory {
- names: ScopedNames,
- frames: Vec<Frame>,
- spare_frames: Vec<Frame>,
- links: Vec<NodeLink>,
- bound_names: Vec<BoundName>,
-}
-
-thread_local! {
- static SPARE_RESOLVER_MEMORY: Cell<ResolverMemory> = Cell::default();
-}
-
/// A name that a pattern binds, with the node that holds its resolution.
#[derive(Clone, Copy)]
struct BoundName {
@@ -458,13 +431,19 @@ impl OuterResolutions {
}
/// The resolutions of `entries`, which get sorted, and of which the first for a name is the one that counts.
- fn new(entries: &mut Vec<(u64, Resolution)>) -> Self {
+ fn new(entries: &mut [(u64, Resolution)]) -> Self {
if !entries.is_sorted_by_key(|&(key, _)| key) {
entries.sort_by_key(|&(key, _)| key);
}
- entries.dedup_by_key(|&mut (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.as_slice()),
+ entries: Arc::from(&entries[..count]),
}
}
@@ -492,7 +471,7 @@ pub struct EnclosingCode {
}
impl EnclosingCode {
- pub(crate) fn of_program(tree: &SyntaxTree) -> Arc<Self> {
+ pub(crate) fn of_program(tree: &SyntaxTree<'_>) -> Arc<Self> {
Arc::new(Self {
row: NONE,
resolutions: tree.outer_resolutions.clone(),
@@ -504,7 +483,7 @@ impl EnclosingCode {
/// 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 Vec<(u64, Resolution)>,
+ entries: &mut [(u64, Resolution)],
parent: &Arc<Self>,
has_direct_eval: bool,
) -> Arc<Self> {
@@ -560,52 +539,55 @@ impl EnclosingCode {
}
}
-/// What the tree of a function needs of the code around it.
-struct OutsideOfTree<'a> {
- row: u32,
- enclosing: &'a Arc<EnclosingCode>,
+/// The scope table that a resolver fills in.
+struct ScopeColumns<'z> {
+ rows: ZoneVec<'z, ScopeRow>,
+ local_variables: ZoneVec<'z, LocalVariable>,
+ annexb_function_names: ZoneVec<'z, Name>,
}
-/// What resolving leaves in the tree.
-struct ResolverResults {
- resolutions: Vec<Resolution>,
- scopes: ScopeTable,
- function_scope_rows: Vec<(u32, u32)>,
+/// What resolving found out about a tree, in the work zone.
+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)],
}
-impl ResolverResults {
- /// The empty columns of `tree`, which are for the results.
- fn take_memory_of(tree: &mut SyntaxTree) -> Self {
- Self {
- resolutions: std::mem::take(&mut tree.resolutions),
- scopes: std::mem::take(&mut tree.scopes),
- function_scope_rows: std::mem::take(&mut tree.function_scope_rows),
+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
}
}
-
- fn hand_over_to(self, tree: &mut SyntaxTree) {
- tree.resolutions = self.resolutions;
- tree.scopes = self.scopes;
- tree.function_scope_rows = self.function_scope_rows;
- }
}
-struct Resolver<'t> {
- tree: &'t SyntaxTree,
- resolutions: Vec<Resolution>,
- scopes: ScopeTable,
- function_scope_rows: Vec<(u32, u32)>,
- names: ScopedNames,
- frames: Vec<Frame>,
- spare_frames: Vec<Frame>,
- links: Vec<NodeLink>,
+struct Resolver<'t, 'z> {
+ tree: &'t SyntaxTree<'t>,
+ zone: &'z Zone,
+ resolutions: ZoneVec<'z, Resolution>,
+ scopes: ScopeColumns<'z>,
+ function_scope_rows: ZoneVec<'z, (u32, u32)>,
+ names: ScopedNames<'z>,
+ frames: ZoneVec<'z, Frame<'z>>,
+ spare_frames: ZoneVec<'z, Frame<'z>>,
+ links: ZoneVec<'z, NodeLink>,
/// The memory for the next list of names that a pattern or parameter list binds.
- bound_names: Vec<BoundName>,
+ bound_names: ZoneVec<'z, BoundName>,
/// The references that stand for names of functions that get compiled later, as (row, name, node).
- outer_references: Vec<(u32, Name, u32)>,
- outside_of_tree: Option<OutsideOfTree<'t>>,
+ outer_references: ZoneVec<'z, (u32, Name, u32)>,
/// The links of the chains of operators being walked, see [`Resolver::expression()`].
- chain_links: Vec<u32>,
+ chain_links: ZoneVec<'z, u32>,
/// How many loops the code being walked is in the body of.
loop_depth: u32,
is_module: bool,
@@ -613,23 +595,34 @@ struct Resolver<'t> {
suppress_globals: bool,
}
-impl<'t> Resolver<'t> {
- fn new(tree: &'t SyntaxTree, results: ResolverResults, outside_of_tree: Option<OutsideOfTree<'t>>) -> Self {
- let memory = SPARE_RESOLVER_MEMORY.take();
- let mut resolutions = results.resolutions;
+impl<'t, 'z> Resolver<'t, 'z> {
+ fn new(zone: &'z Zone, tree: &'t SyntaxTree<'t>) -> Self {
+ // NB: Each function that the tree does not hold leaves a reference behind for each name that it captures and
+ // one more, see `note_free_names_of_function()`. This counts those of every function in the script, which
+ // is enough for nearly all trees.
+ let index = &tree.script.index;
+ let outer_reference_count = index.capture_names.len() + index.start.len();
+ let mut resolutions = ZoneVec::with_capacity_in(tree.ast.tag.len() + outer_reference_count, zone);
resolutions.resize(tree.ast.tag.len(), Resolution::default());
Self {
+ zone,
resolutions,
- scopes: results.scopes,
- function_scope_rows: results.function_scope_rows,
- names: memory.names,
- frames: memory.frames,
- spare_frames: memory.spare_frames,
- links: memory.links,
- bound_names: memory.bound_names,
- outer_references: Vec::new(),
- outside_of_tree,
- chain_links: Vec::new(),
+ scopes: ScopeColumns {
+ rows: ZoneVec::new_in(zone),
+ local_variables: ZoneVec::new_in(zone),
+ annexb_function_names: ZoneVec::new_in(zone),
+ },
+ function_scope_rows: ZoneVec::new_in(zone),
+ names: ScopedNames {
+ innermost: ZoneVec::new_in(zone),
+ entries: ZoneVec::new_in(zone),
+ },
+ frames: ZoneVec::new_in(zone),
+ spare_frames: ZoneVec::new_in(zone),
+ links: ZoneVec::new_in(zone),
+ bound_names: ZoneVec::new_in(zone),
+ outer_references: ZoneVec::with_capacity_in(outer_reference_count, zone),
+ chain_links: ZoneVec::new_in(zone),
loop_depth: 0,
is_module: tree.script.program_type == ProgramType::Module,
initiated_by_eval: false,
@@ -638,64 +631,43 @@ impl<'t> Resolver<'t> {
}
}
- /// Leaves the memory of this resolver to the next one on the thread. Every scope is closed by now, which also means
- /// that the chains of [`ScopedNames`] are empty.
- fn give_back_memory(&mut self) {
+ /// What the resolver found out.
+ fn finish(self) -> Resolved<'z> {
assert!(self.frames.is_empty());
- self.names.entries.clear();
- self.links.clear();
- self.bound_names.clear();
- self.names.entries.shrink_to(MAXIMUM_SPARE_CAPACITY);
- self.links.shrink_to(MAXIMUM_SPARE_CAPACITY);
- SPARE_RESOLVER_MEMORY.set(ResolverMemory {
- names: std::mem::take(&mut self.names),
- frames: std::mem::take(&mut self.frames),
- spare_frames: std::mem::take(&mut self.spare_frames),
- links: std::mem::take(&mut self.links),
- bound_names: std::mem::take(&mut self.bound_names),
- });
- }
-
- /// Hands the results over to the tree.
- fn finish(mut self) -> (ResolverResults, Option<OuterResolutions>) {
- self.give_back_memory();
- self.function_scope_rows.sort_unstable_by_key(|&(node, _)| node);
- // NB: Every function nested in the code leaves a reference behind, so that without any there are none.
- let outer_resolutions = (!self.outer_references.is_empty()).then(|| {
- let mut entries = self
- .outer_references
+ let function_scope_rows = self.function_scope_rows.into_slice();
+ function_scope_rows.sort_unstable_by_key(|&(node, _)| node);
+ let resolutions = self.resolutions.into_slice();
+ let outer_entries = self.zone.alloc_slice_from_iter(
+ self.outer_references
.iter()
- .map(|&(row, name, node)| (OuterResolutions::key(row, name), self.resolutions[node as usize]))
- .collect();
- OuterResolutions::new(&mut entries)
- });
- (
- ResolverResults {
- resolutions: self.resolutions,
- scopes: self.scopes,
- function_scope_rows: self.function_scope_rows,
+ .map(|&(row, name, node)| (OuterResolutions::key(row, name), resolutions[node as usize])),
+ );
+ let scopes = self.scopes;
+ Resolved {
+ program_scope_row: u32_from_usize(scopes.rows.len()) - 1,
+ resolutions,
+ scopes: ScopeTable {
+ rows: scopes.rows.into_slice(),
+ local_variables: scopes.local_variables.into_slice(),
+ annexb_function_names: scopes.annexb_function_names.into_slice(),
},
- outer_resolutions,
- )
+ function_scope_rows,
+ outer_entries,
+ }
}
}
-/// Fills in the resolution column and the scope table of the tree of a program that the parser just finished.
-pub(super) fn resolve_program(tree: &mut SyntaxTree, options: &ResolveOptions) {
- let results = ResolverResults::take_memory_of(tree);
- let readable_tree: &SyntaxTree = tree;
- let mut resolver = Resolver::new(readable_tree, results, None);
+/// Resolves the identifiers of the tree of a program that the parser just finished, with the work data and the results
+/// in `zone`.
+pub(super) fn resolve_program<'z>(zone: &'z Zone, tree: &SyntaxTree<'_>, options: &ResolveOptions) -> Resolved<'z> {
+ let mut resolver = Resolver::new(zone, tree);
resolver.initiated_by_eval = options.initiated_by_eval;
resolver.suppress_globals = options.suppress_globals;
- let root = resolver.tree.root;
- resolver.program(root);
- let (results, outer_resolutions) = resolver.finish();
- tree.program_scope_row = u32_from_usize(results.scopes.rows.len()) - 1;
- results.hand_over_to(tree);
- tree.outer_resolutions = outer_resolutions;
+ resolver.program(tree.root);
+ resolver.finish()
}
-impl<'t> Resolver<'t> {
+impl<'t, 'z> Resolver<'t, 'z> {
// === Tree access ===
fn tag(&self, node: u32) -> u8 {
@@ -735,7 +707,7 @@ impl<'t> Resolver<'t> {
// === Scopes ===
- fn merge_row(&mut self, frame: &mut Frame, row: u32) {
+ fn merge_row(&mut self, frame: &mut Frame<'z>, row: u32) {
if row == NONE {
return;
}
@@ -756,8 +728,9 @@ impl<'t> Resolver<'t> {
}
/// A frame for a new scope of `kind` inside the open ones, which is yet to be pushed.
- fn new_frame(&mut self, kind: FrameKind) -> Frame {
- let mut frame = self.spare_frames.pop().unwrap_or_else(Frame::new);
+ fn new_frame(&mut self, kind: FrameKind) -> Frame<'z> {
+ let zone = self.zone;
+ let mut frame = self.spare_frames.pop().unwrap_or_else(|| Frame::new(zone));
frame.reset(kind, u32_from_usize(self.frames.len()));
frame.loop_depth = self.loop_depth;
frame
@@ -769,7 +742,7 @@ impl<'t> Resolver<'t> {
self.frames.push(frame);
}
- fn top(&mut self) -> &mut Frame {
+ fn top(&mut self) -> &mut Frame<'z> {
self.frames.last_mut().expect("there is an open scope")
}
@@ -784,11 +757,11 @@ impl<'t> Resolver<'t> {
/// An empty list for the names that a pattern or parameter list binds, for [`Self::give_back_bound_names()`] after.
/// Patterns nest, in which case the inner one has to allocate.
- fn take_bound_names(&mut self) -> Vec<BoundName> {
- std::mem::take(&mut self.bound_names)
+ fn take_bound_names(&mut self) -> ZoneVec<'z, BoundName> {
+ self.bound_names.take()
}
- fn give_back_bound_names(&mut self, mut bound: Vec<BoundName>) {
+ fn give_back_bound_names(&mut self, mut bound: ZoneVec<'z, BoundName>) {
bound.clear();
self.bound_names = bound;
}
@@ -816,7 +789,7 @@ impl<'t> Resolver<'t> {
fn close_frame(&mut self, children: &[u32]) -> ScopeRow {
let mut frame = self.frames.pop().expect("there is an open scope");
- let mut nested_groups = std::mem::take(&mut frame.groups_from_nested_scopes);
+ let mut nested_groups = frame.groups_from_nested_scopes.take();
for nested in &nested_groups {
let id = self.names.find_or_add(nested.name, &mut frame);
let entry = self.names.get_mut(id);
@@ -835,7 +808,7 @@ impl<'t> Resolver<'t> {
nested_groups.clear();
frame.groups_from_nested_scopes = nested_groups;
- let mut groups = std::mem::take(&mut frame.groups);
+ let mut groups = frame.groups.take();
let mut passed_on_count = 0;
for index in 0..groups.len() {
let mut group = groups[index];
@@ -862,10 +835,9 @@ impl<'t> Resolver<'t> {
if let Some(row) = frame.code_of_class_row {
self.note_free_names_of_class_code(row, &mut groups);
}
+ // NB: What leaves the program is unbound, and nothing resolves it further.
if let Some(parent) = self.frames.last_mut() {
parent.groups_from_nested_scopes.extend_from_slice(&groups);
- } else {
- self.resolve_outside_of_tree(&groups);
}
groups.clear();
frame.groups = groups;
@@ -886,9 +858,7 @@ impl<'t> Resolver<'t> {
self.build_function_scope_data(&mut frame, children, &mut row);
}
self.names.remove_scope(&frame);
- if !frame.keeps_too_much_memory() {
- self.spare_frames.push(frame);
- }
+ self.spare_frames.push(frame);
row
}
@@ -929,7 +899,7 @@ impl<'t> Resolver<'t> {
/// The code of a class that runs as a function has no captures of its own: it is in the tree of the code around it,
/// so that its free names are the groups that leave its scope.
- fn note_free_names_of_class_code(&mut self, row: u32, groups: &mut Vec<Group>) {
+ fn note_free_names_of_class_code(&mut self, row: u32, groups: &mut ZoneVec<'_, Group>) {
let mut has_unbound_name = false;
for group in groups.iter_mut() {
has_unbound_name |= group.name == Name(N_DOT_UNBOUND);
@@ -946,31 +916,8 @@ impl<'t> Resolver<'t> {
}
}
- /// Resolves what leaves the function that the tree holds, as the code around it did when it got compiled.
- fn resolve_outside_of_tree(&mut self, groups: &[Group]) {
- let Some(outside) = &self.outside_of_tree else {
- return;
- };
- let (row, enclosing) = (outside.row, outside.enclosing);
- for group in groups {
- let outer = enclosing.resolution_in_function(&self.tree.script, row, group.name);
- for node in group.nodes(&self.links) {
- let resolution = &mut self.resolutions[node as usize];
- if outer.is_inside_scope_with_eval() {
- resolution.set_is_inside_scope_with_eval();
- }
- if outer.is_global() && !resolution.is_inside_scope_with_eval() {
- resolution.set_is_global();
- }
- if let Some(kind) = outer.declaration_kind() {
- resolution.set_declaration_kind(kind);
- }
- }
- }
- }
-
/// Resolves a group in a scope, and returns whether it goes on to the scope around it.
- fn resolve_group(&mut self, frame: &mut Frame, group: &mut Group) -> bool {
+ fn resolve_group(&mut self, frame: &mut Frame<'z>, group: &mut Group) -> bool {
let name = group.name;
let flags = self.names.get(group.scoped_name).binding_flags;
let is_function = frame.kind == FrameKind::Function;
@@ -1108,7 +1055,7 @@ impl<'t> Resolver<'t> {
}
/// Adds a local to the function or static block around a scope, or to the program if there is neither.
- fn add_local_variable(&mut self, frame: &mut Frame, group: &Group, mut variable: LocalVariable) -> Option<u32> {
+ fn add_local_variable(&mut self, frame: &mut Frame<'z>, group: &Group, mut variable: LocalVariable) -> Option<u32> {
let holder = if frame.holds_locals() {
frame
} else if let Some(function) = self.frames.iter_mut().rev().find(|frame| frame.holds_locals()) {
@@ -1132,11 +1079,11 @@ impl<'t> Resolver<'t> {
}
// https://tc39.es/ecma262/#sec-block-level-function-declarations-web-legacy-compatibility-semantics
- fn hoist_functions(&mut self, frame: &mut Frame) {
+ fn hoist_functions(&mut self, frame: &mut Frame<'_>) {
if frame.functions_to_hoist.is_empty() && frame.functions_hoisted_from_nested_scopes.is_empty() {
return;
}
- let mut functions = std::mem::take(&mut frame.functions_to_hoist);
+ let mut functions = frame.functions_to_hoist.take();
functions.append(&mut frame.functions_hoisted_from_nested_scopes);
for &name in &functions {
if self.names.blocks_hoisted_function(name, frame.depth) {
@@ -1173,37 +1120,14 @@ impl<'t> Resolver<'t> {
}
// https://tc39.es/ecma262/#sec-functiondeclarationinstantiation
- fn build_function_scope_data(&mut self, frame: &mut Frame, children: &[u32], row: &mut ScopeRow) {
- let mut has_function_declarations = false;
+ fn build_function_scope_data(&mut self, frame: &mut Frame<'z>, children: &[u32], row: &mut ScopeRow) {
for (index, &child) in children.iter().enumerate() {
if let Some(name) = self.declared_function_name(child) {
let id = self.names.find_or_add(name, frame);
self.names.get_mut(id).last_function_position = u32_from_usize(index);
- has_function_declarations = true;
- }
- }
- let first_function = self.scopes.functions_to_initialize.len();
- if has_function_declarations {
- for (index, &child) in children.iter().enumerate() {
- if let Some(name) = self.declared_function_name(child)
- && self
- .names
- .find(name, frame.depth)
- .map(|entry| entry.last_function_position)
- == Some(u32_from_usize(index))
- {
- self.scopes.functions_to_initialize.push(FunctionToInit {
- child_index: u32_from_usize(index),
- });
- }
}
}
- row.functions_to_initialize = ColumnRange {
- start: u32_from_usize(first_function),
- end: u32_from_usize(self.scopes.functions_to_initialize.len()),
- };
- let first_var = self.scopes.vars_to_initialize.len();
for &name in &frame.variable_order {
let entry = self
.names
@@ -1214,25 +1138,13 @@ impl<'t> Resolver<'t> {
continue;
}
let is_parameter = flags & decl::PARAMETER != 0;
- let local = entry.local;
- let is_function_name = entry.last_function_position != NONE;
- if local.is_none() {
+ if entry.local.is_none() {
row.non_local_var_count_for_parameter_expressions += 1;
if !is_parameter {
row.non_local_var_count += 1;
}
}
- self.scopes.vars_to_initialize.push(VarToInit {
- name,
- is_parameter,
- is_function_name,
- local,
- });
}
- row.vars_to_initialize = ColumnRange {
- start: u32_from_usize(first_var),
- end: u32_from_usize(self.scopes.vars_to_initialize.len()),
- };
let arguments_name = Name(N_ARGUMENTS);
let arguments_entry = self.names.find(arguments_name, frame.depth);
@@ -1800,7 +1712,7 @@ impl<'t> Resolver<'t> {
}
}
- fn pattern(&mut self, node: u32, mode: PatternMode, bound: &mut Vec<BoundName>) {
+ fn pattern(&mut self, node: u32, mode: PatternMode, bound: &mut ZoneVec<'_, BoundName>) {
let is_array = self.tag(node) == tag::ARRAY_PATTERN;
for &item in self.list(self.a(node)) {
self.pattern_entry(item, is_array, mode, bound);
@@ -1808,7 +1720,7 @@ impl<'t> Resolver<'t> {
}
/// The target of a pattern's entry, which is an alias of the entry's name.
- fn pattern_alias(&mut self, value: u32, mode: PatternMode, bound: &mut Vec<BoundName>) {
+ fn pattern_alias(&mut self, value: u32, mode: PatternMode, bound: &mut ZoneVec<'_, BoundName>) {
match self.tag(value) {
tag::ARRAY_PATTERN | tag::OBJECT_PATTERN => self.pattern(value, mode, bound),
tag::IDENT if mode == PatternMode::Binding => bound.push(BoundName {
@@ -1819,7 +1731,7 @@ impl<'t> Resolver<'t> {
}
}
- fn pattern_entry(&mut self, item: u32, is_array: bool, mode: PatternMode, bound: &mut Vec<BoundName>) {
+ fn pattern_entry(&mut self, item: u32, is_array: bool, mode: PatternMode, bound: &mut ZoneVec<'_, BoundName>) {
let item_tag = self.tag(item);
if item_tag == tag::HOLE {
return;
@@ -2033,7 +1945,7 @@ impl<'t> Resolver<'t> {
}
}
-fn append_to_column<T: Copy>(column: &mut Vec<T>, items: &[T]) -> ColumnRange {
+fn append_to_column<T: Copy>(column: &mut ZoneVec<'_, T>, items: &[T]) -> ColumnRange {
let start = u32_from_usize(column.len());
column.extend_from_slice(items);
ColumnRange {
diff --git a/Libraries/LibJS/Rust/src/parser/stmt.rs b/Libraries/LibJS/Rust/src/parser/stmt.rs
index 7eb83459fe9..8f453c6aaa4 100644
--- a/Libraries/LibJS/Rust/src/parser/stmt.rs
+++ b/Libraries/LibJS/Rust/src/parser/stmt.rs
@@ -55,7 +55,7 @@ impl VarKind {
}
}
-impl<U: Unit> Parser<'_, U> {
+impl<'a: 'k, 'k, U: Unit> Parser<'a, 'k, U> {
pub(crate) fn parse_statement_list_item(&mut self, top_level: bool) -> u32 {
self.parse_statement(Context::List, top_level)
}
diff --git a/Libraries/LibJS/Rust/src/runtime/intrinsics.rs b/Libraries/LibJS/Rust/src/runtime/intrinsics.rs
index 01dc4ed02b3..e0d8d2dce6d 100644
--- a/Libraries/LibJS/Rust/src/runtime/intrinsics.rs
+++ b/Libraries/LibJS/Rust/src/runtime/intrinsics.rs
@@ -842,9 +842,9 @@ pub(crate) fn parse_builtin_file<'vm>(
script_text: &'static str,
) -> MarkedVec<'vm, Gc<SharedFunctionInstanceData>> {
// Every realm on this thread declares the same builtin files, so each is parsed once and its parse shared.
- type ParsedBuiltinFile = (Rc<SourceCode>, crate::compile::ParsedProgram);
+ type BuiltinFile = (Rc<SourceCode>, crate::compile::ParsedBuiltinFile);
thread_local! {
- static PARSED_BUILTIN_FILES: RefCell<HashMap<(usize, usize), Rc<ParsedBuiltinFile>>> =
+ static PARSED_BUILTIN_FILES: RefCell<HashMap<(usize, usize), Rc<BuiltinFile>>> =
RefCell::new(HashMap::new());
}
let parsed_file = PARSED_BUILTIN_FILES.with(|files| {
diff --git a/Libraries/LibJS/Rust/src/work_zone.rs b/Libraries/LibJS/Rust/src/work_zone.rs
index 772568c3670..cbcab1ea1b1 100644
--- a/Libraries/LibJS/Rust/src/work_zone.rs
+++ b/Libraries/LibJS/Rust/src/work_zone.rs
@@ -4,27 +4,28 @@
* 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 memory for the work data of a parse job: the first parse of a source, or the compile of a function, which parses
+//! it again. A thread that parses has one zone, and each job on the thread puts all of its work data in it. What a job
+//! keeps is copied out of the zone before the job 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()`).
+//! The zone keeps its memory when a job ends, for the next job on the thread, so jobs take no memory from the system
+//! and give none back. An outsized job 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
+/// The most bytes that the work data of one job 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;
+/// The most bytes of memory that the zone keeps for the next job, about what a tree of 2^16 nodes takes with the
+/// data of scope analysis. Nearly all jobs need less.
+const MAXIMUM_SPARE_SIZE: usize = 2 * 1024 * 1024;
thread_local! {
- /// The zone of this thread, while no parse has it.
+ /// The zone of this thread, while no job has it.
static SPARE_ZONE: Cell<Option<Zone>> = const { Cell::new(None) };
}
@@ -40,7 +41,7 @@ pub(crate) fn with_work_zone<R>(job: impl for<'zone> FnOnce(&'zone Zone) -> R) -
size = zone.used();
result
});
- // NB: Give back the memory of an outsized parse rather than keep it until the thread goes idle.
+ // NB: Give back the memory of an outsized job rather than keep it until the thread goes idle.
if size > MAXIMUM_SPARE_SIZE {
zone.trim(MAXIMUM_SPARE_SIZE);
}