Skip to content

Truly independent web browser

LibJS: Give the resolver a plain view of the tree

Andreas Klinga5de7f6a0215
diff --git a/Libraries/LibJS/Rust/src/ast.rs b/Libraries/LibJS/Rust/src/ast.rs
index 38dcf4522ab..17f8d06a2fe 100644
--- a/Libraries/LibJS/Rust/src/ast.rs
+++ b/Libraries/LibJS/Rust/src/ast.rs
@@ -10,6 +10,7 @@
//! is only read from the source once something asks for its value.
use std::marker::PhantomData;
+use std::ops::Deref;
use std::sync::Arc;
use ak::Utf16String;
@@ -17,7 +18,6 @@ use ak::Utf16String;
use crate::parser::FunctionRow;
use crate::parser::OuterResolutions;
use crate::parser::ScriptData;
-use crate::parser::columns::AstColumns;
use crate::parser::columns::NONE;
use crate::parser::columns::function_flag;
use crate::parser::columns::tag;
@@ -25,6 +25,18 @@ use crate::parser::literals;
use crate::parser::literals::EscapeMode;
use crate::parser::token::N_PROTO;
use crate::parser::token::T;
+pub use crate::parser::tree::DeclarationKind;
+pub use crate::parser::tree::LocalBinding;
+pub use crate::parser::tree::LocalType;
+pub use crate::parser::tree::LocalVarKind;
+pub use crate::parser::tree::LocalVariable;
+pub use crate::parser::tree::Name;
+pub use crate::parser::tree::PatternMode;
+pub(crate) use crate::parser::tree::Resolution;
+pub(crate) use crate::parser::tree::ScopeRow;
+pub(crate) use crate::parser::tree::ScopeTable;
+pub use crate::parser::tree::TreeView;
+use crate::parser::tree::is_optional_link;
use crate::u32_from_usize;
use crate::utf16::Utf16StringBuilder;
use crate::utf16::Utf16View;
@@ -125,14 +137,6 @@ pub enum AssignmentOp {
// Kind enums
// =============================================================================
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-#[repr(u8)]
-pub enum DeclarationKind {
- Var = 1,
- Let = 2,
- Const = 3,
-}
-
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum FunctionKind {
@@ -166,13 +170,6 @@ pub enum MetaPropertyType {
ImportMeta,
}
-/// Scope analysis result: how this identifier is resolved.
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-pub enum LocalType {
- Argument,
- Variable,
-}
-
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum ClassMethodKind {
@@ -245,26 +242,10 @@ pub enum ForInOfKind {
ForAwaitOf,
}
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-#[repr(u8)]
-pub enum LocalVarKind {
- Var = 0,
- LetOrConst = 1,
- Function = 2,
- ArgumentsObject = 3,
- CatchClauseParameter = 4,
- /// A parameter that a binding pattern binds.
- PatternParameter = 5,
-}
-
// =============================================================================
// Names
// =============================================================================
-/// An interned name of a [`SyntaxTree`]. Equal names of a tree have equal ids.
-#[derive(Clone, Copy, Debug, Hash, Eq, PartialEq)]
-pub struct Name(pub(crate) u32);
-
#[derive(Clone, Copy)]
struct NameSpan {
start: u32,
@@ -366,174 +347,6 @@ impl NameTable {
}
}
-// =============================================================================
-// Resolution
-// =============================================================================
-
-/// What scope analysis found out about one identifier, packed into a `u32` of the tree's resolution column. An
-/// identifier that it did not look at has the value zero.
-#[derive(Clone, Copy, Default)]
-pub(crate) struct Resolution(pub(crate) u32);
-
-impl Resolution {
- const LOCAL_TYPE_MASK: u32 = 0b11;
- const LOCAL_ARGUMENT: u32 = 1;
- const LOCAL_VARIABLE: u32 = 2;
- const DECLARATION_KIND_SHIFT: u32 = 2;
- const DECLARATION_KIND_MASK: u32 = 0b11 << Self::DECLARATION_KIND_SHIFT;
- const IS_GLOBAL: u32 = 1 << 4;
- const IS_INSIDE_SCOPE_WITH_EVAL: u32 = 1 << 5;
- const IS_HOISTED: u32 = 1 << 6;
- const IS_DECLARED_FUNCTION: u32 = 1 << 7;
- const IS_INSIDE_TREE_SCOPE_WITH_EVAL: u32 = 1 << 8;
- const LOCAL_INDEX_SHIFT: u32 = 9;
- /// A binding with a higher index stays in its environment.
- pub(crate) const MAX_LOCAL_INDEX: u32 = u32::MAX >> Self::LOCAL_INDEX_SHIFT;
-
- pub(crate) fn set_local(&mut self, binding: LocalBinding) {
- let local_type = match binding.local_type {
- LocalType::Argument => Self::LOCAL_ARGUMENT,
- LocalType::Variable => Self::LOCAL_VARIABLE,
- };
- self.0 = (self.0 & !Self::LOCAL_TYPE_MASK & ((1 << Self::LOCAL_INDEX_SHIFT) - 1))
- | local_type
- | (binding.index << Self::LOCAL_INDEX_SHIFT);
- }
-
- pub(crate) fn set_declaration_kind(&mut self, kind: DeclarationKind) {
- self.0 = (self.0 & !Self::DECLARATION_KIND_MASK) | ((kind as u32) << Self::DECLARATION_KIND_SHIFT);
- }
-
- pub(crate) fn set_is_global(&mut self) {
- self.0 |= Self::IS_GLOBAL;
- }
-
- pub(crate) fn set_is_inside_scope_with_eval(&mut self) {
- self.0 |= Self::IS_INSIDE_SCOPE_WITH_EVAL;
- }
-
- pub(crate) fn is_inside_scope_with_eval(self) -> bool {
- self.0 & Self::IS_INSIDE_SCOPE_WITH_EVAL != 0
- }
-
- /// Whether a scope with an eval around the identifier is one of the tree being resolved.
- pub(crate) fn set_is_inside_tree_scope_with_eval(&mut self) {
- self.0 |= Self::IS_INSIDE_TREE_SCOPE_WITH_EVAL;
- }
-
- pub(crate) fn is_inside_tree_scope_with_eval(self) -> bool {
- self.0 & Self::IS_INSIDE_TREE_SCOPE_WITH_EVAL != 0
- }
-
- pub(crate) fn clear_is_global(&mut self) {
- self.0 &= !Self::IS_GLOBAL;
- }
-
- pub(crate) fn set_is_hoisted(&mut self) {
- self.0 |= Self::IS_HOISTED;
- }
-
- pub(crate) fn is_hoisted(self) -> bool {
- self.0 & Self::IS_HOISTED != 0
- }
-
- /// Marks the resolution of a function node as being that of the name of its declaration.
- pub(crate) fn set_is_declared_function(&mut self) {
- self.0 |= Self::IS_DECLARED_FUNCTION;
- }
-
- pub(crate) fn is_declared_function(self) -> bool {
- self.0 & Self::IS_DECLARED_FUNCTION != 0
- }
-
- pub(crate) fn local_type(self) -> Option<LocalType> {
- match self.0 & Self::LOCAL_TYPE_MASK {
- Self::LOCAL_ARGUMENT => Some(LocalType::Argument),
- Self::LOCAL_VARIABLE => Some(LocalType::Variable),
- _ => None,
- }
- }
-
- pub(crate) fn local_index(self) -> u32 {
- self.0 >> Self::LOCAL_INDEX_SHIFT
- }
-
- pub(crate) fn declaration_kind(self) -> Option<DeclarationKind> {
- match (self.0 & Self::DECLARATION_KIND_MASK) >> Self::DECLARATION_KIND_SHIFT {
- 1 => Some(DeclarationKind::Var),
- 2 => Some(DeclarationKind::Let),
- 3 => Some(DeclarationKind::Const),
- _ => None,
- }
- }
-
- pub(crate) fn is_global(self) -> bool {
- self.0 & Self::IS_GLOBAL != 0
- }
-}
-
-/// A local that scope analysis gave a function, a static block or a program.
-#[derive(Clone, Copy)]
-pub struct LocalVariable {
- pub name: Name,
- pub kind: LocalVarKind,
- pub is_mutable: bool,
- /// Where the block that declares it starts and ends, if a block does.
- pub(crate) scope_offsets: Option<(u32, u32)>,
- /// How many loops of its function the scope that declares it is in the body of, which is how often that scope can
- /// start again.
- pub(crate) enclosing_loops: u32,
-}
-
-/// A resolved local binding: the operand type and index assigned by scope analysis.
-#[derive(Clone, Copy, Debug)]
-pub struct LocalBinding {
- pub local_type: LocalType,
- pub index: u32,
-}
-
-/// A range of one of the columns of scope analysis results.
-#[derive(Clone, Copy, Default)]
-pub(crate) struct ColumnRange {
- pub(crate) start: u32,
- pub(crate) end: u32,
-}
-
-impl ColumnRange {
- pub(crate) fn of<T>(self, column: &[T]) -> &[T] {
- &column[self.start as usize..self.end as usize]
- }
-}
-
-/// What scope analysis found out about a function, a static block or a program.
-#[derive(Clone, Copy, Default)]
-pub(crate) struct ScopeRow {
- pub(crate) local_variables: ColumnRange,
- pub(crate) annexb_function_names: ColumnRange,
- pub(crate) non_local_var_count: u32,
- pub(crate) non_local_var_count_for_parameter_expressions: u32,
- pub(crate) has_function_scope_data: bool,
- pub(crate) has_function_named_arguments: bool,
- pub(crate) has_argument_parameter: bool,
- pub(crate) has_lexically_declared_arguments: bool,
- pub(crate) uses_this: bool,
- pub(crate) uses_this_from_environment: bool,
- pub(crate) contains_direct_call_to_eval: bool,
- pub(crate) contains_access_to_arguments_object: bool,
- /// Whether the code of the scope, which is everything but what its declaration instantiation does, can change the
- /// running environment. The code of nested functions has its own.
- pub(crate) creates_environment: bool,
-}
-
-/// The results of scope analysis, which are the same for the whole life of a tree.
-#[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: &'t [ScopeRow],
- pub(crate) local_variables: &'t [LocalVariable],
- pub(crate) annexb_function_names: &'t [Name],
-}
-
// =============================================================================
// The tree
// =============================================================================
@@ -548,60 +361,22 @@ pub struct SyntaxTree<'t> {
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: 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: &'t [Name],
- /// The resolution of the identifier at each node, if there is one.
- 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: &'t [(u32, u32)],
+ /// The tree itself, and what scope analysis found out about it.
+ pub(crate) view: TreeView<'t>,
/// 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<'_> {
- fn tag(&self, node: u32) -> u8 {
- self.ast.tag[node as usize]
- }
+impl<'t> Deref for SyntaxTree<'t> {
+ type Target = TreeView<'t>;
- pub(crate) fn a(&self, node: u32) -> u32 {
- self.ast.a[node as usize]
- }
-
- pub(crate) fn b(&self, node: u32) -> u32 {
- self.ast.b[node as usize]
- }
-
- fn pos(&self, node: u32) -> u32 {
- self.ast.pos[node as usize]
- }
-
- fn extra(&self, index: u32) -> u32 {
- self.ast.extra[index as usize]
- }
-
- fn list(&self, start: u32) -> &[u32] {
- let start = start as usize;
- let count = self.ast.extra[start] as usize;
- &self.ast.extra[start + 1..start + 1 + count]
- }
-
- /// Where the code after a block starts, given the list of the block's statements.
- /// Where the block statement at `node` ends.
- pub(crate) fn end_of_block(&self, node: u32) -> u32 {
- self.block_end(self.a(node))
- }
-
- fn block_end(&self, list: u32) -> u32 {
- self.extra(list + 1 + self.extra(list))
+ #[inline(always)]
+ fn deref(&self) -> &TreeView<'t> {
+ &self.view
}
+}
+impl SyntaxTree<'_> {
fn range(&self, offset: u32) -> SourceRange {
let position = self.script.positions.lines.position(offset);
SourceRange {
@@ -630,10 +405,6 @@ impl SyntaxTree<'_> {
self.script.names.text(name)
}
- fn resolution(&self, node: u32) -> Resolution {
- self.resolutions[node as usize]
- }
-
fn identifier(&self, name: Name, offset: u32, node: u32) -> Identifier<'_> {
Identifier::new(self, name, offset, self.resolution(node))
}
@@ -679,18 +450,6 @@ impl SyntaxTree<'_> {
Statement::new(self, self.root)
}
- fn scope_row(&self, row: u32) -> &ScopeRow {
- &self.scopes.rows[row as usize]
- }
-
- pub(crate) fn function_scope(&self, function: u32) -> &ScopeRow {
- let index = self
- .function_scope_rows
- .binary_search_by_key(&function, |&(node, _)| node)
- .expect("the tree holds the code of the function");
- self.scope_row(self.function_scope_rows[index].1)
- }
-
fn string_units(&self, node: u32) -> Utf16View<'_> {
self.source_units(self.pos(node) + 1, self.a(node) - 1)
}
@@ -808,30 +567,6 @@ impl SyntaxTree<'_> {
}
}
- /// Whether the pattern at `node` has a computed key or an initializer, nested patterns included.
- pub(crate) fn pattern_contains_expression(&self, node: u32) -> bool {
- self.list(self.a(node)).iter().any(|&item| {
- let item_tag = self.tag(item);
- if item_tag == tag::COMPUTED_PROPERTY {
- return true;
- }
- let mut value = match item_tag {
- tag::HOLE => return false,
- tag::REST => self.a(item),
- tag::PROPERTY | tag::SHORTHAND => self.b(item),
- _ => item,
- };
- if matches!(self.tag(value), tag::ASSIGN_PATTERN | tag::ASSIGN_BASE) {
- if self.b(value) != 0 {
- return true;
- }
- value = self.a(value);
- }
- matches!(self.tag(value), tag::ARRAY_PATTERN | tag::OBJECT_PATTERN)
- && self.pattern_contains_expression(value)
- })
- }
-
fn function_kind(&self, function: u32) -> FunctionKind {
let flags = self.script.index.flags[self.b(function) as usize];
FunctionKind::from_async_generator(flags & function_flag::ASYNC != 0, flags & function_flag::GENERATOR != 0)
@@ -851,11 +586,6 @@ impl SyntaxTree<'_> {
}
}
- /// What scope analysis found out about the program.
- pub(crate) fn program_scope(&self) -> &ScopeRow {
- self.scope_row(self.program_scope_row)
- }
-
/// The row of the function behind `id`.
pub fn function_row(&self, id: FunctionId) -> FunctionRow {
let (node, extra_of_row) = match id.source {
@@ -1522,14 +1252,6 @@ pub enum ClassElement<'a> {
// Binding patterns
// =============================================================================
-#[derive(Clone, Copy, PartialEq, Eq)]
-pub enum PatternMode {
- /// The pattern of a declaration, a parameter or a catch clause.
- Binding,
- /// The target of a destructuring assignment.
- Assignment,
-}
-
#[derive(Clone, Copy)]
pub struct BindingPattern<'a> {
pub kind: BindingPatternKind,
@@ -1870,43 +1592,10 @@ pub struct OptionalChainData<'a> {
}
impl<'a> OptionalChainData<'a> {
- fn is_link(tag: u8) -> bool {
- matches!(
- tag,
- tag::MEMBER
- | tag::INDEX
- | tag::PRIVATE_MEMBER
- | tag::CALL
- | tag::OPT_MEMBER
- | tag::OPT_INDEX
- | tag::OPT_PRIVATE_MEMBER
- | tag::OPT_CALL
- )
- }
-
- fn is_optional(tag: u8) -> bool {
- matches!(
- tag,
- tag::OPT_MEMBER | tag::OPT_INDEX | tag::OPT_PRIVATE_MEMBER | tag::OPT_CALL
- )
- }
-
- /// 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>) {
+ /// The base of the chain and its links, outermost first (see `TreeView::optional_chain()`).
+ fn links(tree: &SyntaxTree<'_>, node: u32) -> (u32, Vec<u32>) {
let mut links = Vec::new();
- let mut base = node;
- let mut remaining_optional_links = 0;
- let mut probe = node;
- while Self::is_link(tree.tag(probe)) {
- remaining_optional_links += u32::from(Self::is_optional(tree.tag(probe)));
- probe = tree.a(probe);
- }
- while remaining_optional_links > 0 {
- remaining_optional_links -= u32::from(Self::is_optional(tree.tag(base)));
- links.push(base);
- base = tree.a(base);
- }
+ let base = tree.optional_chain(node, |link| links.push(link));
(base, links)
}
@@ -1922,7 +1611,7 @@ impl<'a> OptionalChainData<'a> {
.into_iter()
.map(|link| {
let link_tag = tree.tag(link);
- let mode = if Self::is_optional(link_tag) {
+ let mode = if is_optional_link(link_tag) {
OptionalChainMode::Optional
} else {
OptionalChainMode::NotOptional
diff --git a/Libraries/LibJS/Rust/src/parser/mod.rs b/Libraries/LibJS/Rust/src/parser/mod.rs
index 643150a056a..33e89583694 100644
--- a/Libraries/LibJS/Rust/src/parser/mod.rs
+++ b/Libraries/LibJS/Rust/src/parser/mod.rs
@@ -24,6 +24,7 @@ pub(crate) mod literals;
pub(crate) mod resolve;
mod stmt;
pub(crate) mod token;
+pub(crate) mod tree;
pub(crate) mod unit;
use crate::ast::Name;
@@ -32,6 +33,7 @@ use crate::ast::Position;
use crate::ast::ProgramType;
use crate::ast::ScopeTable;
use crate::ast::SyntaxTree;
+use crate::ast::TreeView;
use crate::source_text::SourceText;
use crate::u32_from_usize;
use crate::work_zone::with_work_zone;
@@ -202,16 +204,18 @@ impl ScriptData {
SyntaxTree {
script: self.clone(),
source: self.positions.source.get(),
- ast: columns,
- root,
- first_token_start: 0,
- is_strict_mode: false,
- has_top_level_await: false,
- eval_referenced_private_names: &[],
- resolutions: &[],
- scopes: ScopeTable::default(),
- program_scope_row: 0,
- function_scope_rows: &[],
+ view: TreeView {
+ ast: columns,
+ root,
+ first_token_start: 0,
+ is_strict_mode: false,
+ has_top_level_await: false,
+ eval_referenced_private_names: &[],
+ resolutions: &[],
+ scopes: ScopeTable::default(),
+ program_scope_row: 0,
+ function_scope_rows: &[],
+ },
outer_resolutions: None,
}
}
@@ -339,6 +343,16 @@ impl ScriptData {
pub(crate) fn is_global_name_used_in_with(&self, name: Name) -> bool {
self.global_names_used_in_with.binary_search(&name.0).is_ok()
}
+
+ /// What the resolver reads of this source.
+ fn resolver_view(&self) -> resolve::ScriptView<'_> {
+ resolve::ScriptView {
+ index: self.index.view(),
+ default_export_name: self.default_export_name,
+ is_module: self.program_type == ProgramType::Module,
+ global_names_used_in_with: &self.global_names_used_in_with,
+ }
+ }
}
pub struct ParseError {
@@ -617,9 +631,7 @@ fn parse_code_units<'z, U: Unit + Default, R>(
retains_compiled_functions: AtomicBool::new(false),
retained_code_size: AtomicUsize::new(0),
});
- let tree = SyntaxTree {
- script,
- source: source.clone(),
+ let view = TreeView {
ast: parser.ast.into_columns(),
root,
first_token_start: parser.first_token_start,
@@ -630,23 +642,27 @@ fn parse_code_units<'z, U: Unit + Default, R>(
scopes: ScopeTable::default(),
program_scope_row: 0,
function_scope_rows: &[],
- outer_resolutions: None,
};
let resolved = resolve::resolve_program(
zone,
- &tree,
+ &view,
+ &script.resolver_view(),
&resolve::ResolveOptions {
initiated_by_eval: options.initiated_by_eval,
suppress_globals: options.suppress_globals,
},
);
let tree = SyntaxTree {
- resolutions: resolved.resolutions,
- scopes: resolved.scopes,
- program_scope_row: resolved.program_scope_row,
- function_scope_rows: resolved.function_scope_rows,
+ script,
+ source: source.clone(),
+ view: TreeView {
+ resolutions: resolved.resolutions,
+ scopes: resolved.scopes,
+ program_scope_row: resolved.program_scope_row,
+ function_scope_rows: resolved.function_scope_rows,
+ ..view
+ },
outer_resolutions: OuterResolutions::of_entries(resolved.outer_entries),
- ..tree
};
Ok(Some(job(&tree, top_level_rows)))
}
diff --git a/Libraries/LibJS/Rust/src/parser/resolve.rs b/Libraries/LibJS/Rust/src/parser/resolve.rs
index 822c09db803..02fda7b6595 100644
--- a/Libraries/LibJS/Rust/src/parser/resolve.rs
+++ b/Libraries/LibJS/Rust/src/parser/resolve.rs
@@ -22,6 +22,7 @@ use super::base::SCOPE_ROW_EVAL_IN_FUNCTION;
use super::base::SCOPE_ROW_POISONED;
use super::base::USE_IN_WITH;
use super::base::decl;
+use super::columns::FunctionIndexView;
use super::columns::NONE;
use super::columns::function_flag;
use super::columns::tag;
@@ -30,7 +31,7 @@ use super::token::N_DOT_NEW_TARGET;
use super::token::N_DOT_SUPER;
use super::token::N_DOT_THIS;
use super::token::N_DOT_UNBOUND;
-use crate::ast::*;
+use super::tree::*;
use crate::u32_from_usize;
use ak::Zone;
use ak::ZoneVec;
@@ -413,6 +414,23 @@ struct BoundName {
name: Name,
}
+/// What the resolver reads of what is kept of the source of a tree.
+#[derive(Clone, Copy)]
+pub(crate) struct ScriptView<'t> {
+ pub(crate) index: FunctionIndexView<'t>,
+ /// The name of an anonymous default export.
+ pub(crate) default_export_name: Name,
+ pub(crate) is_module: bool,
+ /// The undeclared names that something in a `with` uses, which are not simply globals, sorted.
+ pub(crate) global_names_used_in_with: &'t [u32],
+}
+
+impl ScriptView<'_> {
+ pub(crate) fn is_global_name_used_in_with(&self, name: Name) -> bool {
+ self.global_names_used_in_with.binary_search(&name.0).is_ok()
+ }
+}
+
/// How identifiers resolve, which the code around the program decides.
pub(super) struct ResolveOptions {
pub(super) initiated_by_eval: bool,
@@ -443,7 +461,8 @@ pub(crate) fn outer_key(row: u32, name: Name) -> u64 {
}
struct Resolver<'t, 'z> {
- tree: &'t SyntaxTree<'t>,
+ tree: &'t TreeView<'t>,
+ script: ScriptView<'t>,
zone: &'z Zone,
resolutions: ZoneVec<'z, Resolution>,
scopes: ScopeColumns<'z>,
@@ -466,11 +485,11 @@ struct Resolver<'t, 'z> {
}
impl<'t, 'z> Resolver<'t, 'z> {
- fn new(zone: &'z Zone, tree: &'t SyntaxTree<'t>) -> Self {
+ fn new(zone: &'z Zone, tree: &'t TreeView<'t>, script: ScriptView<'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 index = &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());
@@ -494,10 +513,11 @@ impl<'t, 'z> Resolver<'t, 'z> {
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,
+ is_module: script.is_module,
initiated_by_eval: false,
suppress_globals: false,
tree,
+ script,
}
}
@@ -529,8 +549,13 @@ impl<'t, 'z> Resolver<'t, 'z> {
/// 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);
+pub(super) fn resolve_program<'z>(
+ zone: &'z Zone,
+ tree: &TreeView<'_>,
+ script: &ScriptView<'_>,
+ options: &ResolveOptions,
+) -> Resolved<'z> {
+ let mut resolver = Resolver::new(zone, tree, *script);
resolver.initiated_by_eval = options.initiated_by_eval;
resolver.suppress_globals = options.suppress_globals;
resolver.program(tree.root);
@@ -743,7 +768,7 @@ impl<'t, 'z> Resolver<'t, 'z> {
/// What a function that is compiled later can see of the code around it comes down to the same references that
/// the function itself would have left in that code, had it been in the tree.
fn note_free_names_of_function(&mut self, row: u32) {
- let index = &self.tree.script.index;
+ let index = &self.script.index;
let captures = index.capture_start[row as usize] as usize;
let count = index.capture_count[row as usize] as usize;
for &capture in &index.capture_names[captures..captures + count] {
@@ -830,7 +855,7 @@ impl<'t, 'z> Resolver<'t, 'z> {
// are used in one is known by name.
let used_in_with = (group.used_inside_with_statement && name != Name(N_DOT_UNBOUND))
|| flags & decl::USED_IN_WITH != 0
- || self.tree.script.is_global_name_used_in_with(name);
+ || self.script.is_global_name_used_in_with(name);
if !used_in_with && !is_module_declaration && !self.initiated_by_eval && !self.suppress_globals {
for node in group.nodes(&self.links) {
let resolution = &mut self.resolutions[node as usize];
@@ -1116,9 +1141,9 @@ impl<'t, 'z> Resolver<'t, 'z> {
tag::EXPORT_DEFAULT => {
let inner_tag = self.tag(a);
if inner_tag == tag::FUNCTION && b != 0 {
- let name = self.tree.script.index.name[self.b(a) as usize];
+ let name = self.script.index.name[self.b(a) as usize];
if name == NONE {
- let default_name = self.tree.script.default_export_name;
+ let default_name = self.script.default_export_name;
let id = self.names.find_or_add(default_name, &mut self.frames[0]);
let entry = self.names.get_mut(id);
entry.binding_flags = decl::LEXICAL;
@@ -1275,7 +1300,7 @@ impl<'t, 'z> Resolver<'t, 'z> {
fn function_declaration(&mut self, function: u32, name: u32) {
let name = if name == NONE {
- self.tree.script.default_export_name
+ self.script.default_export_name
} else {
Name(name)
};
@@ -1316,7 +1341,7 @@ impl<'t, 'z> Resolver<'t, 'z> {
fn function_code(&mut self, node: u32, name: Option<Name>) {
let tree = self.a(node);
let row = self.b(node);
- let flags = self.tree.script.index.flags[row as usize];
+ let flags = self.script.index.flags[row as usize];
let parameters = self.list(self.extra(tree));
let body = self.extra(tree + 1);
let scope_row = self.extra(tree + 3);
@@ -1701,9 +1726,9 @@ impl<'t, 'z> Resolver<'t, 'z> {
| tag::IMPORT_META
| tag::PRIVATE_NAME => {}
tag::FUNCTION => {
- let flags = self.tree.script.index.flags[b as usize];
+ let flags = self.script.index.flags[b as usize];
let is_method = flags & function_flag::METHOD != 0;
- let name = self.tree.script.index.name[b as usize];
+ let name = self.script.index.name[b as usize];
if !is_method && name != NONE && flags & function_flag::NAME_UNUSED == 0 {
self.note_creates_environment();
}
@@ -1802,9 +1827,13 @@ impl<'t, 'z> Resolver<'t, 'z> {
}
fn optional_chain(&mut self, node: u32) {
- let (base, links) = OptionalChainData::links(self.tree, node);
+ let start = self.chain_links.len();
+ let tree = self.tree;
+ let base = tree.optional_chain(node, |link| self.chain_links.push(link));
self.expression(base);
- for &link in links.iter().rev() {
+ // NB: The links go innermost first.
+ while self.chain_links.len() > start {
+ let link = self.chain_links.pop().expect("a link was pushed");
let b = self.b(link);
match self.tag(link) {
tag::CALL | tag::OPT_CALL => self.arguments(b),
diff --git a/Libraries/LibJS/Rust/src/parser/tree.rs b/Libraries/LibJS/Rust/src/parser/tree.rs
new file mode 100644
index 00000000000..45e74e1c537
--- /dev/null
+++ b/Libraries/LibJS/Rust/src/parser/tree.rs
@@ -0,0 +1,399 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The tree of a parse as plain data: its columns and what scope analysis found out about it, all in slices. The
+//! resolver reads the tree through [`TreeView`], and the syntax tree of `ast.rs` wraps it with what is kept of the source.
+
+use super::columns::AstColumns;
+use super::columns::tag;
+
+// =============================================================================
+// Kind enums
+// =============================================================================
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+#[repr(u8)]
+pub enum DeclarationKind {
+ Var = 1,
+ Let = 2,
+ Const = 3,
+}
+
+/// Scope analysis result: how this identifier is resolved.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum LocalType {
+ Argument,
+ Variable,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+#[repr(u8)]
+pub enum LocalVarKind {
+ Var = 0,
+ LetOrConst = 1,
+ Function = 2,
+ ArgumentsObject = 3,
+ CatchClauseParameter = 4,
+ /// A parameter that a binding pattern binds.
+ PatternParameter = 5,
+}
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+pub enum PatternMode {
+ /// The pattern of a declaration, a parameter or a catch clause.
+ Binding,
+ /// The target of a destructuring assignment.
+ Assignment,
+}
+
+// =============================================================================
+// Names
+// =============================================================================
+
+/// An interned name of a source. Equal names of a source have equal ids.
+#[derive(Clone, Copy, Debug, Hash, Eq, PartialEq)]
+pub struct Name(pub(crate) u32);
+
+// =============================================================================
+// Resolution
+// =============================================================================
+
+/// What scope analysis found out about one identifier, packed into a `u32` of the tree's resolution column. An
+/// identifier that it did not look at has the value zero.
+#[derive(Clone, Copy, Default)]
+pub(crate) struct Resolution(pub(crate) u32);
+
+impl Resolution {
+ const LOCAL_TYPE_MASK: u32 = 0b11;
+ const LOCAL_ARGUMENT: u32 = 1;
+ const LOCAL_VARIABLE: u32 = 2;
+ const DECLARATION_KIND_SHIFT: u32 = 2;
+ const DECLARATION_KIND_MASK: u32 = 0b11 << Self::DECLARATION_KIND_SHIFT;
+ const IS_GLOBAL: u32 = 1 << 4;
+ const IS_INSIDE_SCOPE_WITH_EVAL: u32 = 1 << 5;
+ const IS_HOISTED: u32 = 1 << 6;
+ const IS_DECLARED_FUNCTION: u32 = 1 << 7;
+ const IS_INSIDE_TREE_SCOPE_WITH_EVAL: u32 = 1 << 8;
+ const LOCAL_INDEX_SHIFT: u32 = 9;
+ /// A binding with a higher index stays in its environment.
+ pub(crate) const MAX_LOCAL_INDEX: u32 = u32::MAX >> Self::LOCAL_INDEX_SHIFT;
+
+ #[inline]
+ pub(crate) fn set_local(&mut self, binding: LocalBinding) {
+ let local_type = match binding.local_type {
+ LocalType::Argument => Self::LOCAL_ARGUMENT,
+ LocalType::Variable => Self::LOCAL_VARIABLE,
+ };
+ self.0 = (self.0 & !Self::LOCAL_TYPE_MASK & ((1 << Self::LOCAL_INDEX_SHIFT) - 1))
+ | local_type
+ | (binding.index << Self::LOCAL_INDEX_SHIFT);
+ }
+
+ #[inline]
+ pub(crate) fn set_declaration_kind(&mut self, kind: DeclarationKind) {
+ self.0 = (self.0 & !Self::DECLARATION_KIND_MASK) | ((kind as u32) << Self::DECLARATION_KIND_SHIFT);
+ }
+
+ #[inline]
+ pub(crate) fn set_is_global(&mut self) {
+ self.0 |= Self::IS_GLOBAL;
+ }
+
+ #[inline]
+ pub(crate) fn set_is_inside_scope_with_eval(&mut self) {
+ self.0 |= Self::IS_INSIDE_SCOPE_WITH_EVAL;
+ }
+
+ #[inline]
+ pub(crate) fn is_inside_scope_with_eval(self) -> bool {
+ self.0 & Self::IS_INSIDE_SCOPE_WITH_EVAL != 0
+ }
+
+ /// Whether a scope with an eval around the identifier is one of the tree being resolved.
+ #[inline]
+ pub(crate) fn set_is_inside_tree_scope_with_eval(&mut self) {
+ self.0 |= Self::IS_INSIDE_TREE_SCOPE_WITH_EVAL;
+ }
+
+ #[inline]
+ pub(crate) fn is_inside_tree_scope_with_eval(self) -> bool {
+ self.0 & Self::IS_INSIDE_TREE_SCOPE_WITH_EVAL != 0
+ }
+
+ #[inline]
+ pub(crate) fn clear_is_global(&mut self) {
+ self.0 &= !Self::IS_GLOBAL;
+ }
+
+ #[inline]
+ pub(crate) fn set_is_hoisted(&mut self) {
+ self.0 |= Self::IS_HOISTED;
+ }
+
+ #[inline]
+ pub(crate) fn is_hoisted(self) -> bool {
+ self.0 & Self::IS_HOISTED != 0
+ }
+
+ /// Marks the resolution of a function node as being that of the name of its declaration.
+ #[inline]
+ pub(crate) fn set_is_declared_function(&mut self) {
+ self.0 |= Self::IS_DECLARED_FUNCTION;
+ }
+
+ #[inline]
+ pub(crate) fn is_declared_function(self) -> bool {
+ self.0 & Self::IS_DECLARED_FUNCTION != 0
+ }
+
+ #[inline]
+ pub(crate) fn local_type(self) -> Option<LocalType> {
+ match self.0 & Self::LOCAL_TYPE_MASK {
+ Self::LOCAL_ARGUMENT => Some(LocalType::Argument),
+ Self::LOCAL_VARIABLE => Some(LocalType::Variable),
+ _ => None,
+ }
+ }
+
+ #[inline]
+ pub(crate) fn local_index(self) -> u32 {
+ self.0 >> Self::LOCAL_INDEX_SHIFT
+ }
+
+ #[inline]
+ pub(crate) fn declaration_kind(self) -> Option<DeclarationKind> {
+ match (self.0 & Self::DECLARATION_KIND_MASK) >> Self::DECLARATION_KIND_SHIFT {
+ 1 => Some(DeclarationKind::Var),
+ 2 => Some(DeclarationKind::Let),
+ 3 => Some(DeclarationKind::Const),
+ _ => None,
+ }
+ }
+
+ #[inline]
+ pub(crate) fn is_global(self) -> bool {
+ self.0 & Self::IS_GLOBAL != 0
+ }
+}
+
+/// A local that scope analysis gave a function, a static block or a program.
+#[derive(Clone, Copy)]
+pub struct LocalVariable {
+ pub name: Name,
+ pub kind: LocalVarKind,
+ pub is_mutable: bool,
+ /// Where the block that declares it starts and ends, if a block does.
+ pub(crate) scope_offsets: Option<(u32, u32)>,
+ /// How many loops of its function the scope that declares it is in the body of, which is how often that scope can
+ /// start again.
+ pub(crate) enclosing_loops: u32,
+}
+
+/// A resolved local binding: the operand type and index assigned by scope analysis.
+#[derive(Clone, Copy, Debug)]
+pub struct LocalBinding {
+ pub local_type: LocalType,
+ pub index: u32,
+}
+
+/// A range of one of the columns of scope analysis results.
+#[derive(Clone, Copy, Default)]
+pub(crate) struct ColumnRange {
+ pub(crate) start: u32,
+ pub(crate) end: u32,
+}
+
+impl ColumnRange {
+ pub(crate) fn of<T>(self, column: &[T]) -> &[T] {
+ &column[self.start as usize..self.end as usize]
+ }
+}
+
+/// What scope analysis found out about a function, a static block or a program.
+#[derive(Clone, Copy, Default)]
+pub(crate) struct ScopeRow {
+ pub(crate) local_variables: ColumnRange,
+ pub(crate) annexb_function_names: ColumnRange,
+ pub(crate) non_local_var_count: u32,
+ pub(crate) non_local_var_count_for_parameter_expressions: u32,
+ pub(crate) has_function_scope_data: bool,
+ pub(crate) has_function_named_arguments: bool,
+ pub(crate) has_argument_parameter: bool,
+ pub(crate) has_lexically_declared_arguments: bool,
+ pub(crate) uses_this: bool,
+ pub(crate) uses_this_from_environment: bool,
+ pub(crate) contains_direct_call_to_eval: bool,
+ pub(crate) contains_access_to_arguments_object: bool,
+ /// Whether the code of the scope, which is everything but what its declaration instantiation does, can change the
+ /// running environment. The code of nested functions has its own.
+ pub(crate) creates_environment: bool,
+}
+
+/// The results of scope analysis, which are the same for the whole life of a tree.
+#[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: &'t [ScopeRow],
+ pub(crate) local_variables: &'t [LocalVariable],
+ pub(crate) annexb_function_names: &'t [Name],
+}
+
+// =============================================================================
+// The tree
+// =============================================================================
+
+/// The tree of the code of a compile job and the results of scope analysis on that code, as slices of plain data.
+#[derive(Clone, Copy)]
+pub struct TreeView<'t> {
+ 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: &'t [Name],
+ /// The resolution of the identifier at each node, if there is one.
+ 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: &'t [(u32, u32)],
+}
+
+impl TreeView<'_> {
+ #[inline]
+ pub(crate) fn tag(&self, node: u32) -> u8 {
+ self.ast.tag[node as usize]
+ }
+
+ #[inline]
+ pub(crate) fn a(&self, node: u32) -> u32 {
+ self.ast.a[node as usize]
+ }
+
+ #[inline]
+ pub(crate) fn b(&self, node: u32) -> u32 {
+ self.ast.b[node as usize]
+ }
+
+ #[inline]
+ pub(crate) fn pos(&self, node: u32) -> u32 {
+ self.ast.pos[node as usize]
+ }
+
+ #[inline]
+ pub(crate) fn extra(&self, index: u32) -> u32 {
+ self.ast.extra[index as usize]
+ }
+
+ #[inline]
+ pub(crate) fn list(&self, start: u32) -> &[u32] {
+ let start = start as usize;
+ let count = self.ast.extra[start] as usize;
+ &self.ast.extra[start + 1..start + 1 + count]
+ }
+
+ /// Where the block statement at `node` ends.
+ #[inline]
+ pub(crate) fn end_of_block(&self, node: u32) -> u32 {
+ self.block_end(self.a(node))
+ }
+
+ /// Where the code after a block starts, given the list of the block's statements.
+ #[inline]
+ pub(crate) fn block_end(&self, list: u32) -> u32 {
+ self.extra(list + 1 + self.extra(list))
+ }
+
+ #[inline]
+ pub(crate) fn resolution(&self, node: u32) -> Resolution {
+ self.resolutions[node as usize]
+ }
+
+ #[inline]
+ pub(crate) fn scope_row(&self, row: u32) -> &ScopeRow {
+ &self.scopes.rows[row as usize]
+ }
+
+ pub(crate) fn function_scope(&self, function: u32) -> &ScopeRow {
+ let index = self
+ .function_scope_rows
+ .binary_search_by_key(&function, |&(node, _)| node)
+ .expect("the tree holds the code of the function");
+ self.scope_row(self.function_scope_rows[index].1)
+ }
+
+ /// What scope analysis found out about the program.
+ #[inline]
+ pub(crate) fn program_scope(&self) -> &ScopeRow {
+ self.scope_row(self.program_scope_row)
+ }
+
+ /// Whether the pattern at `node` has a computed key or an initializer, nested patterns included.
+ pub(crate) fn pattern_contains_expression(&self, node: u32) -> bool {
+ self.list(self.a(node)).iter().any(|&item| {
+ let item_tag = self.tag(item);
+ if item_tag == tag::COMPUTED_PROPERTY {
+ return true;
+ }
+ let mut value = match item_tag {
+ tag::HOLE => return false,
+ tag::REST => self.a(item),
+ tag::PROPERTY | tag::SHORTHAND => self.b(item),
+ _ => item,
+ };
+ if matches!(self.tag(value), tag::ASSIGN_PATTERN | tag::ASSIGN_BASE) {
+ if self.b(value) != 0 {
+ return true;
+ }
+ value = self.a(value);
+ }
+ matches!(self.tag(value), tag::ARRAY_PATTERN | tag::OBJECT_PATTERN)
+ && self.pattern_contains_expression(value)
+ })
+ }
+
+ /// The optional chain at `node`, which reaches down to its innermost optional link, and what is below that is its
+ /// base. Hands the links to `push_link`, outermost first, and returns the base.
+ pub(crate) fn optional_chain(&self, node: u32, mut push_link: impl FnMut(u32)) -> u32 {
+ let mut base = node;
+ let mut remaining_optional_links = 0;
+ let mut probe = node;
+ while is_optional_chain_link(self.tag(probe)) {
+ remaining_optional_links += u32::from(is_optional_link(self.tag(probe)));
+ probe = self.a(probe);
+ }
+ while remaining_optional_links > 0 {
+ remaining_optional_links -= u32::from(is_optional_link(self.tag(base)));
+ push_link(base);
+ base = self.a(base);
+ }
+ base
+ }
+}
+
+/// Whether a node of this tag can be a link of an optional chain.
+fn is_optional_chain_link(node_tag: u8) -> bool {
+ matches!(
+ node_tag,
+ tag::MEMBER
+ | tag::INDEX
+ | tag::PRIVATE_MEMBER
+ | tag::CALL
+ | tag::OPT_MEMBER
+ | tag::OPT_INDEX
+ | tag::OPT_PRIVATE_MEMBER
+ | tag::OPT_CALL
+ )
+}
+
+/// Whether a link of an optional chain with this tag is an optional one.
+pub(crate) fn is_optional_link(node_tag: u8) -> bool {
+ matches!(
+ node_tag,
+ tag::OPT_MEMBER | tag::OPT_INDEX | tag::OPT_PRIVATE_MEMBER | tag::OPT_CALL
+ )
+}