Skip to content

Truly independent web browser

LibJS: Move the parser core into a crate of its own

Andreas Kling7f20829194d4
diff --git a/Cargo.lock b/Cargo.lock
index 2e8f541706b..89d38d67ff8 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1938,6 +1938,14 @@ dependencies = [
"libjs_runtime_macros",
]
+[[package]]
+name = "libjs_parser"
+version = "0.1.0"
+dependencies = [
+ "ak",
+ "libunicode_rust",
+]
+
[[package]]
name = "libjs_runtime_macros"
version = "0.1.0"
@@ -1965,6 +1973,7 @@ dependencies = [
"libcompress_rust",
"libjs_abi",
"libjs_jit",
+ "libjs_parser",
"libjs_runtime_macros",
"libregex_rust",
"libunicode_rust",
diff --git a/Cargo.toml b/Cargo.toml
index 15bcd81e691..dd943317cec 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -10,6 +10,7 @@ members = [
"Libraries/LibIPC/Rust",
"Libraries/LibJS/ABI",
"Libraries/LibJS/JIT/Rust",
+ "Libraries/LibJS/Parser/Rust",
"Libraries/LibJS/Rust",
"Libraries/LibJS/Rust/embedding_headers",
"Libraries/LibJS/Rust/macros",
diff --git a/Libraries/LibJS/CMakeLists.txt b/Libraries/LibJS/CMakeLists.txt
index 8559c214525..4b0004a27f6 100644
--- a/Libraries/LibJS/CMakeLists.txt
+++ b/Libraries/LibJS/CMakeLists.txt
@@ -19,6 +19,10 @@ set(LIBJS_RUST_FEATURES ${LIBJS_RUST_FEATURES} PARENT_SCOPE)
add_subdirectory(Rust)
+# The core of the parser, a pure Rust crate that keeps all the work data of a parse in a zone. Its unit tests run
+# without the rest of LibJS.
+test_rust_crate(MANIFEST_PATH Parser/Rust/Cargo.toml CRATE_NAME libjs_parser)
+
# The optimizing JIT's compiler, a pure Rust crate that only works on plain data. Its unit tests run without the rest of
# LibJS.
if (ENABLE_JS_JIT)
diff --git a/Libraries/LibJS/Parser/Rust/Cargo.toml b/Libraries/LibJS/Parser/Rust/Cargo.toml
new file mode 100644
index 00000000000..289795739c3
--- /dev/null
+++ b/Libraries/LibJS/Parser/Rust/Cargo.toml
@@ -0,0 +1,16 @@
+[package]
+name = "libjs_parser"
+version = "0.1.0"
+edition = "2024"
+
+[lib]
+crate-type = ["rlib"]
+
+# After changing dependencies, regenerate the Flatpak sources:
+# python3 Meta/CMake/flatpak/generate-cargo-sources.py
+[dependencies]
+ak = { path = "../../../../AK/Rust" }
+libunicode_rust = { path = "../../../LibUnicode/Rust", default-features = false }
+
+[lints]
+workspace = true
diff --git a/Libraries/LibJS/Rust/src/parser/base.rs b/Libraries/LibJS/Parser/Rust/src/base.rs
similarity index 99%
rename from Libraries/LibJS/Rust/src/parser/base.rs
rename to Libraries/LibJS/Parser/Rust/src/base.rs
index d96bb8e80ee..dc37fbd6753 100644
--- a/Libraries/LibJS/Rust/src/parser/base.rs
+++ b/Libraries/LibJS/Parser/Rust/src/base.rs
@@ -50,7 +50,7 @@ pub enum Mode {
#[derive(Clone, Copy, Default)]
#[repr(C)]
-pub(crate) struct NameState {
+pub struct NameState {
use_head: u32,
use_scope: u32,
decl_head: u32,
@@ -231,20 +231,24 @@ pub struct PendingError<'z> {
pub(crate) struct ZoneText<'z>(ZoneVec<'z, u8>);
impl<'z> ZoneText<'z> {
+ #[inline]
pub(crate) fn new(zone: &'z Zone) -> Self {
Self(ZoneVec::new_in(zone))
}
+ #[inline]
pub(crate) fn push_str(&mut self, text: &str) {
self.0.extend_from_slice(text.as_bytes());
}
+ #[inline]
pub(crate) fn finish(self) -> &'z str {
core::str::from_utf8(self.0.into_slice()).expect("the text is made of strings")
}
}
impl fmt::Write for ZoneText<'_> {
+ #[inline]
fn write_str(&mut self, text: &str) -> fmt::Result {
self.push_str(text);
Ok(())
@@ -268,16 +272,16 @@ impl fmt::Display for LossyText<'_> {
/// What the first parse of a top level went by, which parsing it again has to go by too.
#[derive(Clone, Copy)]
-pub(crate) struct ProgramContext {
- pub(crate) context: u32,
- pub(crate) starts_in_strict_mode: bool,
- pub(crate) initiated_by_eval: bool,
+pub struct ProgramContext {
+ pub context: u32,
+ pub starts_in_strict_mode: bool,
+ pub initiated_by_eval: bool,
/// Whether no name means a global binding.
- pub(crate) has_no_globals: bool,
+ pub has_no_globals: bool,
}
/// The state of a name that no scope declares or uses.
-pub(crate) const UNUSED_NAME: NameState = NameState {
+pub const UNUSED_NAME: NameState = NameState {
use_head: NONE,
use_scope: NONE,
decl_head: NONE,
@@ -292,7 +296,7 @@ pub struct Parser<'a, 'k, U: Unit> {
/// Where in `rows_by_params_start` the last lookup ended up.
row_cursor: core::cell::Cell<usize>,
/// Whether the tree is one for a sweep: rows get marks, and change their tag where a mark is about them.
- pub(crate) marks: bool,
+ pub marks: bool,
/// The row in the index of the code of a class that was parsed last, and what it knows of that code by now.
pub(crate) pseudo_function_row: u32,
pub(crate) pseudo_function_flags: u32,
@@ -302,9 +306,9 @@ pub struct Parser<'a, 'k, U: Unit> {
/// Whether the list of arguments that was parsed last is evaluated into an array for a sweep.
pub(crate) arguments_in_array: bool,
/// How many arguments a sweep can keep as separate operands before putting them into an array.
- pub(crate) inline_argument_limit: usize,
+ pub inline_argument_limit: usize,
/// Whether anything uses what scopes declare and what code refers to, which a sweep with a summary does not.
- pub(crate) tracks_scopes: bool,
+ pub tracks_scopes: bool,
pub(crate) validate_regex: ValidateRegex,
/// How many bindings of the function being parsed have a place in its summary.
pub(crate) summary_ordinal: u32,
@@ -336,7 +340,7 @@ pub struct Parser<'a, 'k, U: Unit> {
pub(crate) ctx: u32,
pub(crate) labels: ZoneVec<'a, Label>,
pub(crate) labels_base: u32,
- pub(crate) stack_limit: usize,
+ pub stack_limit: usize,
recursion_depth: u32,
pub(crate) potential_arrow_at: u32,
pub(crate) cover_error: u32,
@@ -436,7 +440,7 @@ const MAX_RECURSION_DEPTH: u32 = 2000;
/// chain in a loop, so the recursion limit does not apply to it.
pub(crate) const MAX_SUBSCRIPT_CHAIN_LENGTH: u32 = 10000;
-pub(crate) const RECURSION_LIMIT_MESSAGE: &str = "Maximum parser recursion depth exceeded";
+pub const RECURSION_LIMIT_MESSAGE: &str = "Maximum parser recursion depth exceeded";
/// A function could not be parsed or compiled, because the stack that is left does not hold it.
#[derive(Clone, Copy, Debug)]
@@ -454,7 +458,7 @@ impl<'a: 'k, 'k, U: Unit> Parser<'a, 'k, U> {
///
/// # Safety
/// `source` must be followed by at least 64 units of zeros within the same allocation.
- pub(super) unsafe fn new(
+ pub unsafe fn new(
zone: &'a Zone,
source: &'a [U],
module: bool,
@@ -519,7 +523,7 @@ impl<'a: 'k, 'k, U: Unit> Parser<'a, 'k, U> {
/// `zone`. The names of the source with their states come from the reparse context of the source, and the parser
/// works with them in place. Its source comes with the function.
#[allow(clippy::too_many_arguments)]
- pub(crate) fn for_reparsing(
+ pub fn for_reparsing(
zone: &'a Zone,
module: bool,
interner: Interner<'k>,
@@ -699,7 +703,7 @@ impl<'a: 'k, 'k, U: Unit> Parser<'a, 'k, 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(
+ pub fn parse_top_level_rows(
&mut self,
context: ProgramContext,
index: FunctionIndexView<'a>,
@@ -789,6 +793,7 @@ impl<'a: 'k, 'k, U: Unit> Parser<'a, 'k, U> {
/// Writes out the summaries of all functions, now that all of their scopes closed.
fn group_summaries(&mut self) {
+ #[inline]
fn write_varint(bytes: &mut ZoneVec<'_, u8>, mut value: u32) {
while value >= 0x80 {
bytes.push(value as u8 | 0x80);
@@ -2269,14 +2274,14 @@ impl<'a: 'k, 'k, U: Unit> Parser<'a, 'k, U> {
/// # Safety
/// What the lexer may read of the source, up to `length` and the padding after it if it gets that far, must stay
/// valid for as long as the parser reads it.
- pub(crate) unsafe fn set_reparse_source(&mut self, source: *const U, offset: u32, length: u32) {
+ pub unsafe fn set_reparse_source(&mut self, source: *const U, offset: u32, length: u32) {
self.src = source.wrapping_sub(offset as usize);
self.len = length;
}
/// Ends the parse of a function again, whether it went well or not. Gives back the tree, and the stamp for the
/// reparse context, whose name states are clean again.
- pub(crate) fn end_reparse(mut self) -> (Ast<'a>, u32) {
+ pub fn end_reparse(mut self) -> (Ast<'a>, u32) {
self.finish_reparse();
(self.ast, self.stamp)
}
@@ -2320,7 +2325,7 @@ impl<'a: 'k, 'k, U: Unit> Parser<'a, 'k, U> {
/// Parses one function again, on its own, from where the first parse found it. The functions nested in it get
/// skipped by what the first parse recorded about them, so that nothing is parsed further than one level down.
/// Returns the function's node, or the element of its class if the function is the code of a class.
- pub(crate) fn reparse_function(&mut self, row: u32) -> u32 {
+ pub fn reparse_function(&mut self, row: u32) -> u32 {
use function_flag::*;
let index = self.first_pass_index();
let row_index = row as usize;
diff --git a/Libraries/LibJS/Rust/src/parser/columns.rs b/Libraries/LibJS/Parser/Rust/src/columns.rs
similarity index 99%
rename from Libraries/LibJS/Rust/src/parser/columns.rs
rename to Libraries/LibJS/Parser/Rust/src/columns.rs
index a347e4195c6..9556dd2aa9d 100644
--- a/Libraries/LibJS/Rust/src/parser/columns.rs
+++ b/Libraries/LibJS/Parser/Rust/src/columns.rs
@@ -224,6 +224,7 @@ impl<'z> Ast<'z> {
}
/// The columns, for as long as the zone holds them.
+ #[inline]
pub fn into_columns(self) -> AstColumns<'z> {
AstColumns {
tag: self.tag.into_slice(),
@@ -384,6 +385,7 @@ impl<'z> FunctionIndexBuilder<'z> {
impl FunctionIndexView<'_> {
/// Where lookups for what comes after the function of `row` start out.
+ #[inline]
pub fn position_after_row(&self, row: usize) -> usize {
let rows = self.rows_by_params_start;
if rows.is_empty() {
diff --git a/Libraries/LibJS/Rust/src/parser/escapes.rs b/Libraries/LibJS/Parser/Rust/src/escapes.rs
similarity index 100%
rename from Libraries/LibJS/Rust/src/parser/escapes.rs
rename to Libraries/LibJS/Parser/Rust/src/escapes.rs
diff --git a/Libraries/LibJS/Rust/src/parser/expr.rs b/Libraries/LibJS/Parser/Rust/src/expr.rs
similarity index 100%
rename from Libraries/LibJS/Rust/src/parser/expr.rs
rename to Libraries/LibJS/Parser/Rust/src/expr.rs
diff --git a/Libraries/LibJS/Rust/src/parser/intern.rs b/Libraries/LibJS/Parser/Rust/src/intern.rs
similarity index 95%
rename from Libraries/LibJS/Rust/src/parser/intern.rs
rename to Libraries/LibJS/Parser/Rust/src/intern.rs
index d064cb2595c..db1737b71f1 100644
--- a/Libraries/LibJS/Rust/src/parser/intern.rs
+++ b/Libraries/LibJS/Parser/Rust/src/intern.rs
@@ -9,7 +9,7 @@
//!
//! The tables of an interner are slices. Those of a first parse are in its work zone, and the ones that it outgrows
//! stay there until the parse ends. The reparse context of a source keeps the names of the source in tables of its own
-//! (see `KeptNames`), and each parse of a function again interns its names with those tables in place.
+//! (see `KeptNames` in LibJS), and each parse of a function again interns its names with those tables in place.
use super::token::{KEYWORDS, SPECIAL_NAMES};
use ak::Zone;
@@ -19,14 +19,14 @@ pub const NONE: u32 = u32::MAX;
#[derive(Clone, Copy)]
#[repr(C, align(32))]
-pub(super) struct Row {
+pub struct Row {
k0: u64,
k1: u64,
id: u32,
}
#[derive(Clone, Copy)]
-pub(super) struct LongRow {
+pub struct LongRow {
hash: u64,
id: u32,
}
@@ -52,25 +52,25 @@ pub struct Interner<'z> {
}
/// The tables of an interner, all of which are written, for a copy of them that stays around.
-pub(super) struct NameTables<'t> {
- pub(super) rows: &'t [Row],
- pub(super) shift: u32,
- pub(super) count: u32,
- pub(super) long_rows: &'t [LongRow],
- pub(super) long_count: u32,
- pub(super) text: &'t [u8],
- pub(super) spans: &'t [(u32, u32)],
+pub struct NameTables<'t> {
+ pub rows: &'t [Row],
+ pub shift: u32,
+ pub count: u32,
+ pub long_rows: &'t [LongRow],
+ pub long_count: u32,
+ pub text: &'t [u8],
+ pub spans: &'t [(u32, u32)],
}
/// Tables that an interner can work with in place (see `Interner::of_tables()`).
-pub(super) struct NameTablesMut<'t> {
- pub(super) rows: &'t mut [Row],
- pub(super) shift: u32,
- pub(super) count: u32,
- pub(super) long_rows: &'t mut [LongRow],
- pub(super) long_count: u32,
- pub(super) text: &'t mut [u8],
- pub(super) spans: &'t mut [(u32, u32)],
+pub struct NameTablesMut<'t> {
+ pub rows: &'t mut [Row],
+ pub shift: u32,
+ pub count: u32,
+ pub long_rows: &'t mut [LongRow],
+ pub long_count: u32,
+ pub text: &'t mut [u8],
+ pub spans: &'t mut [(u32, u32)],
}
/// Makes room for `more` values after the first `len` of `list`. A list that is too short for them moves to new memory
@@ -227,7 +227,8 @@ impl<'z> Interner<'z> {
}
/// The tables, at the size they have, to copy. The table of short names is left out.
- pub(super) fn tables(&self) -> NameTables<'_> {
+ #[inline]
+ pub fn tables(&self) -> NameTables<'_> {
NameTables {
rows: self.rows,
shift: self.shift,
@@ -242,7 +243,7 @@ impl<'z> Interner<'z> {
/// An interner with `tables` in place. The text and the span of a name that they do not have go to `zone`, and so
/// do the rows when they grow, so that the tables never refer to the zone. But the row of such a name is written
/// into `tables` first, so that they stay as they were only if no name is new.
- pub(super) fn of_tables(zone: &'z Zone, tables: NameTablesMut<'z>) -> Self {
+ pub fn of_tables(zone: &'z Zone, tables: NameTablesMut<'z>) -> Self {
Self {
zone,
short: &mut [],
@@ -258,6 +259,8 @@ impl<'z> Interner<'z> {
}
}
+ // NB: An interner is never empty: it starts with the names that every interner has.
+ #[allow(clippy::len_without_is_empty)]
pub fn len(&self) -> usize {
self.len as usize
}
diff --git a/Libraries/LibJS/Rust/src/parser/lexer.rs b/Libraries/LibJS/Parser/Rust/src/lexer.rs
similarity index 99%
rename from Libraries/LibJS/Rust/src/parser/lexer.rs
rename to Libraries/LibJS/Parser/Rust/src/lexer.rs
index 5dbcf5b3e02..a159e6380e7 100644
--- a/Libraries/LibJS/Rust/src/parser/lexer.rs
+++ b/Libraries/LibJS/Parser/Rust/src/lexer.rs
@@ -25,6 +25,7 @@ static KEYWORD_KINDS: [T; 36] = keyword_kinds();
// https://tc39.es/ecma262/#prod-IdentifierStartChar
// IdentifierStartChar :: UnicodeIDStart | $ | _
+#[inline]
pub fn is_id_start(c: u32) -> bool {
if c < 128 {
return (c as u8).is_ascii_alphabetic() || c == 0x24 || c == 0x5F;
@@ -34,6 +35,7 @@ pub fn is_id_start(c: u32) -> bool {
// https://tc39.es/ecma262/#prod-IdentifierPartChar
// IdentifierPartChar :: UnicodeIDContinue | $
+#[inline]
pub fn is_id_continue(c: u32) -> bool {
if c < 128 {
return (c as u8).is_ascii_alphanumeric() || c == 0x24 || c == 0x5F;
@@ -41,10 +43,12 @@ pub fn is_id_continue(c: u32) -> bool {
matches!(c, 0x200C | 0x200D) || libunicode_rust::character_types::code_point_has_identifier_continue_property(c)
}
+#[inline]
fn is_unicode_whitespace(c: u32) -> bool {
matches!(c, 0xA0 | 0xFEFF | 0x1680 | 0x2000..=0x200A | 0x202F | 0x205F | 0x3000)
}
+#[inline]
fn hex_value(c: u32) -> Option<u32> {
char::from_u32(c)?.to_digit(16)
}
diff --git a/Libraries/LibJS/Parser/Rust/src/lib.rs b/Libraries/LibJS/Parser/Rust/src/lib.rs
new file mode 100644
index 00000000000..1629b2ddda0
--- /dev/null
+++ b/Libraries/LibJS/Parser/Rust/src/lib.rs
@@ -0,0 +1,31 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The core of the LibJS parser: the lexer, the parser, the interner of names, the columns of the syntax tree and the
+//! resolver.
+//!
+//! A parse job has all of its work data in one zone (see `ak::Zone`), which the code that starts the job hands it. What
+//! the job keeps of its results is copied out of the zone by that code, which is also what reaches the runtime for the
+//! parser (see `base::ValidateRegex`).
+
+pub mod base;
+pub mod columns;
+pub mod escapes;
+mod expr;
+pub mod intern;
+mod lexer;
+pub mod resolve;
+mod stmt;
+pub mod token;
+pub mod tree;
+pub mod unit;
+
+/// Convert a `usize` to `u32`, panicking if the value exceeds `u32::MAX`.
+/// Prefer this over `as u32` which silently truncates on 64-bit platforms.
+#[inline]
+pub fn u32_from_usize(value: usize) -> u32 {
+ u32::try_from(value).expect("value exceeds u32::MAX")
+}
diff --git a/Libraries/LibJS/Rust/src/parser/resolve.rs b/Libraries/LibJS/Parser/Rust/src/resolve.rs
similarity index 98%
rename from Libraries/LibJS/Rust/src/parser/resolve.rs
rename to Libraries/LibJS/Parser/Rust/src/resolve.rs
index 02fda7b6595..63e4deb3134 100644
--- a/Libraries/LibJS/Rust/src/parser/resolve.rs
+++ b/Libraries/LibJS/Parser/Rust/src/resolve.rs
@@ -14,9 +14,9 @@
//! A tree only holds the code of one compile job, so this only walks that code. A function nested in it is not in the
//! tree, but what its names resolve to depends on the scopes around it, and those are here now and gone by the time it
//! gets compiled. So every such function leaves a reference behind for each name that it captures, which resolves like
-//! any other, and the results stay around as `OuterResolutions` (see `enclosing.rs`) for when it does get compiled. A
-//! name it uses that the code around it binds further out is a capture of a function further out. `EnclosingCode` links
-//! them up.
+//! any other, and the results stay around as `OuterResolutions` (see `enclosing.rs` in LibJS) for when it does get
+//! compiled. A name it uses that the code around it binds further out is a capture of a function further out.
+//! `EnclosingCode` links them up.
use super::base::SCOPE_ROW_EVAL_IN_FUNCTION;
use super::base::SCOPE_ROW_POISONED;
@@ -416,25 +416,26 @@ struct BoundName {
/// 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>,
+pub struct ScriptView<'t> {
+ pub index: FunctionIndexView<'t>,
/// The name of an anonymous default export.
- pub(crate) default_export_name: Name,
- pub(crate) is_module: bool,
+ pub default_export_name: Name,
+ pub 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],
+ pub global_names_used_in_with: &'t [u32],
}
impl ScriptView<'_> {
- pub(crate) fn is_global_name_used_in_with(&self, name: Name) -> bool {
+ #[inline]
+ pub 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,
- pub(super) suppress_globals: bool,
+pub struct ResolveOptions {
+ pub initiated_by_eval: bool,
+ pub suppress_globals: bool,
}
/// The scope table that a resolver fills in.
@@ -445,18 +446,18 @@ struct ScopeColumns<'z> {
}
/// What resolving found out about a tree, in the work zone, for the tree to refer to.
-pub(super) struct Resolved<'z> {
- pub(super) resolutions: &'z [Resolution],
- pub(super) scopes: ScopeTable<'z>,
- pub(super) program_scope_row: u32,
- pub(super) function_scope_rows: &'z [(u32, u32)],
+pub struct Resolved<'z> {
+ pub resolutions: &'z [Resolution],
+ pub scopes: ScopeTable<'z>,
+ pub program_scope_row: u32,
+ pub function_scope_rows: &'z [(u32, u32)],
/// The resolutions for the functions nested in the tree, as (key, resolution), with keys from `outer_key()`. Every
/// function nested in the code leaves a reference behind, so that without any there are none.
- pub(super) outer_entries: &'z mut [(u64, Resolution)],
+ pub outer_entries: &'z mut [(u64, Resolution)],
}
/// The key of the resolution of `name` for the function at `row`.
-pub(crate) fn outer_key(row: u32, name: Name) -> u64 {
+pub fn outer_key(row: u32, name: Name) -> u64 {
u64::from(row) << 32 | u64::from(name.0)
}
@@ -549,7 +550,7 @@ 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>(
+pub fn resolve_program<'z>(
zone: &'z Zone,
tree: &TreeView<'_>,
script: &ScriptView<'_>,
diff --git a/Libraries/LibJS/Rust/src/parser/stmt.rs b/Libraries/LibJS/Parser/Rust/src/stmt.rs
similarity index 100%
rename from Libraries/LibJS/Rust/src/parser/stmt.rs
rename to Libraries/LibJS/Parser/Rust/src/stmt.rs
diff --git a/Libraries/LibJS/Rust/src/parser/token.rs b/Libraries/LibJS/Parser/Rust/src/token.rs
similarity index 100%
rename from Libraries/LibJS/Rust/src/parser/token.rs
rename to Libraries/LibJS/Parser/Rust/src/token.rs
diff --git a/Libraries/LibJS/Rust/src/parser/tree.rs b/Libraries/LibJS/Parser/Rust/src/tree.rs
similarity index 73%
rename from Libraries/LibJS/Rust/src/parser/tree.rs
rename to Libraries/LibJS/Parser/Rust/src/tree.rs
index 45e74e1c537..6255bb21be5 100644
--- a/Libraries/LibJS/Rust/src/parser/tree.rs
+++ b/Libraries/LibJS/Parser/Rust/src/tree.rs
@@ -5,7 +5,8 @@
*/
//! 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.
+//! resolver reads the tree through [`TreeView`], and the `SyntaxTree` of LibJS wraps it with what is kept of the
+//! source.
use super::columns::AstColumns;
use super::columns::tag;
@@ -55,7 +56,7 @@ pub enum PatternMode {
/// 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);
+pub struct Name(pub u32);
// =============================================================================
// Resolution
@@ -64,7 +65,7 @@ pub struct Name(pub(crate) u32);
/// 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);
+pub struct Resolution(pub u32);
impl Resolution {
const LOCAL_TYPE_MASK: u32 = 0b11;
@@ -79,10 +80,10 @@ impl Resolution {
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 const MAX_LOCAL_INDEX: u32 = u32::MAX >> Self::LOCAL_INDEX_SHIFT;
#[inline]
- pub(crate) fn set_local(&mut self, binding: LocalBinding) {
+ pub fn set_local(&mut self, binding: LocalBinding) {
let local_type = match binding.local_type {
LocalType::Argument => Self::LOCAL_ARGUMENT,
LocalType::Variable => Self::LOCAL_VARIABLE,
@@ -93,64 +94,64 @@ impl Resolution {
}
#[inline]
- pub(crate) fn set_declaration_kind(&mut self, kind: DeclarationKind) {
+ pub 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) {
+ pub fn set_is_global(&mut self) {
self.0 |= Self::IS_GLOBAL;
}
#[inline]
- pub(crate) fn set_is_inside_scope_with_eval(&mut self) {
+ pub 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 {
+ pub 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) {
+ pub 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 {
+ pub 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) {
+ pub fn clear_is_global(&mut self) {
self.0 &= !Self::IS_GLOBAL;
}
#[inline]
- pub(crate) fn set_is_hoisted(&mut self) {
+ pub fn set_is_hoisted(&mut self) {
self.0 |= Self::IS_HOISTED;
}
#[inline]
- pub(crate) fn is_hoisted(self) -> bool {
+ pub 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) {
+ pub fn set_is_declared_function(&mut self) {
self.0 |= Self::IS_DECLARED_FUNCTION;
}
#[inline]
- pub(crate) fn is_declared_function(self) -> bool {
+ pub fn is_declared_function(self) -> bool {
self.0 & Self::IS_DECLARED_FUNCTION != 0
}
#[inline]
- pub(crate) fn local_type(self) -> Option<LocalType> {
+ pub 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),
@@ -159,12 +160,12 @@ impl Resolution {
}
#[inline]
- pub(crate) fn local_index(self) -> u32 {
+ pub fn local_index(self) -> u32 {
self.0 >> Self::LOCAL_INDEX_SHIFT
}
#[inline]
- pub(crate) fn declaration_kind(self) -> Option<DeclarationKind> {
+ pub 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),
@@ -174,7 +175,7 @@ impl Resolution {
}
#[inline]
- pub(crate) fn is_global(self) -> bool {
+ pub fn is_global(self) -> bool {
self.0 & Self::IS_GLOBAL != 0
}
}
@@ -186,10 +187,10 @@ pub struct LocalVariable {
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)>,
+ pub 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,
+ pub enclosing_loops: u32,
}
/// A resolved local binding: the operand type and index assigned by scope analysis.
@@ -201,44 +202,44 @@ pub struct LocalBinding {
/// 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,
+pub struct ColumnRange {
+ pub start: u32,
+ pub end: u32,
}
impl ColumnRange {
- pub(crate) fn of<T>(self, column: &[T]) -> &[T] {
+ pub 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,
+pub struct ScopeRow {
+ pub local_variables: ColumnRange,
+ pub annexb_function_names: ColumnRange,
+ pub non_local_var_count: u32,
+ pub non_local_var_count_for_parameter_expressions: u32,
+ pub has_function_scope_data: bool,
+ pub has_function_named_arguments: bool,
+ pub has_argument_parameter: bool,
+ pub has_lexically_declared_arguments: bool,
+ pub uses_this: bool,
+ pub uses_this_from_environment: bool,
+ pub contains_direct_call_to_eval: bool,
+ pub 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,
+ pub 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> {
+pub 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],
+ pub rows: &'t [ScopeRow],
+ pub local_variables: &'t [LocalVariable],
+ pub annexb_function_names: &'t [Name],
}
// =============================================================================
@@ -248,49 +249,49 @@ pub(crate) struct ScopeTable<'t> {
/// 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],
+ pub ast: AstColumns<'t>,
+ pub root: u32,
+ pub first_token_start: u32,
+ pub is_strict_mode: bool,
+ pub has_top_level_await: bool,
+ pub 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>,
+ pub resolutions: &'t [Resolution],
+ pub scopes: ScopeTable<'t>,
/// The row of the program in `scopes`.
- pub(crate) program_scope_row: u32,
+ pub 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)],
+ pub function_scope_rows: &'t [(u32, u32)],
}
impl TreeView<'_> {
#[inline]
- pub(crate) fn tag(&self, node: u32) -> u8 {
+ pub fn tag(&self, node: u32) -> u8 {
self.ast.tag[node as usize]
}
#[inline]
- pub(crate) fn a(&self, node: u32) -> u32 {
+ pub fn a(&self, node: u32) -> u32 {
self.ast.a[node as usize]
}
#[inline]
- pub(crate) fn b(&self, node: u32) -> u32 {
+ pub fn b(&self, node: u32) -> u32 {
self.ast.b[node as usize]
}
#[inline]
- pub(crate) fn pos(&self, node: u32) -> u32 {
+ pub fn pos(&self, node: u32) -> u32 {
self.ast.pos[node as usize]
}
#[inline]
- pub(crate) fn extra(&self, index: u32) -> u32 {
+ pub fn extra(&self, index: u32) -> u32 {
self.ast.extra[index as usize]
}
#[inline]
- pub(crate) fn list(&self, start: u32) -> &[u32] {
+ pub 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]
@@ -298,27 +299,27 @@ impl TreeView<'_> {
/// Where the block statement at `node` ends.
#[inline]
- pub(crate) fn end_of_block(&self, node: u32) -> u32 {
+ pub 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 {
+ pub fn block_end(&self, list: u32) -> u32 {
self.extra(list + 1 + self.extra(list))
}
#[inline]
- pub(crate) fn resolution(&self, node: u32) -> Resolution {
+ pub fn resolution(&self, node: u32) -> Resolution {
self.resolutions[node as usize]
}
#[inline]
- pub(crate) fn scope_row(&self, row: u32) -> &ScopeRow {
+ pub fn scope_row(&self, row: u32) -> &ScopeRow {
&self.scopes.rows[row as usize]
}
- pub(crate) fn function_scope(&self, function: u32) -> &ScopeRow {
+ pub fn function_scope(&self, function: u32) -> &ScopeRow {
let index = self
.function_scope_rows
.binary_search_by_key(&function, |&(node, _)| node)
@@ -328,12 +329,12 @@ impl TreeView<'_> {
/// What scope analysis found out about the program.
#[inline]
- pub(crate) fn program_scope(&self) -> &ScopeRow {
+ pub 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 {
+ pub 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 {
@@ -358,7 +359,7 @@ impl TreeView<'_> {
/// 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 {
+ pub 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;
@@ -391,7 +392,7 @@ fn is_optional_chain_link(node_tag: u8) -> bool {
}
/// Whether a link of an optional chain with this tag is an optional one.
-pub(crate) fn is_optional_link(node_tag: u8) -> bool {
+pub fn is_optional_link(node_tag: u8) -> bool {
matches!(
node_tag,
tag::OPT_MEMBER | tag::OPT_INDEX | tag::OPT_PRIVATE_MEMBER | tag::OPT_CALL
diff --git a/Libraries/LibJS/Rust/src/parser/unit.rs b/Libraries/LibJS/Parser/Rust/src/unit.rs
similarity index 97%
rename from Libraries/LibJS/Rust/src/parser/unit.rs
rename to Libraries/LibJS/Parser/Rust/src/unit.rs
index 7a8bf1b9027..472e0e964d6 100644
--- a/Libraries/LibJS/Rust/src/parser/unit.rs
+++ b/Libraries/LibJS/Parser/Rust/src/unit.rs
@@ -16,6 +16,9 @@ pub trait Unit: Copy + Eq + 'static {
const WIDE: bool;
fn code(self) -> u32;
/// Loads a block of units as bytes.
+ ///
+ /// # Safety
+ /// A whole block of units must be readable at `p`.
unsafe fn load(p: *const Self) -> Block;
}
@@ -90,7 +93,7 @@ fn first_bytes(word: u64, len: usize) -> u64 {
/// The first 16 narrowed units with everything from `len` on cleared, as two little-endian words.
#[inline(always)]
-pub unsafe fn key_of(x: Block, len: usize) -> (u64, u64) {
+pub(crate) unsafe fn key_of(x: Block, len: usize) -> (u64, u64) {
let (k0, k1) = unsafe { block::first_words(x) };
if len <= 8 {
(first_bytes(k0, len), 0)
@@ -99,7 +102,8 @@ pub unsafe fn key_of(x: Block, len: usize) -> (u64, u64) {
}
}
-pub use block::{BLOCK, Block, eq_mask, high_mask, ident_mask};
+pub use block::Block;
+pub(crate) use block::{BLOCK, eq_mask, high_mask, ident_mask};
#[cfg(all(target_arch = "x86_64", target_feature = "avx2"))]
mod block {
diff --git a/Libraries/LibJS/Rust/Cargo.toml b/Libraries/LibJS/Rust/Cargo.toml
index 3a60afcbc60..724d137dd2f 100644
--- a/Libraries/LibJS/Rust/Cargo.toml
+++ b/Libraries/LibJS/Rust/Cargo.toml
@@ -27,6 +27,7 @@ libc = "0.2"
libcompress_rust = { path = "../../LibCompress/Rust" }
libjs_abi = { path = "../ABI" }
libjs_jit = { path = "../JIT/Rust", optional = true }
+libjs_parser = { path = "../Parser/Rust" }
libjs_runtime_macros = { path = "macros" }
memchr = "2"
libregex_rust = { path = "../../LibRegex/Rust", default-features = false }
diff --git a/Libraries/LibJS/Rust/src/ast.rs b/Libraries/LibJS/Rust/src/ast.rs
index 17f8d06a2fe..2f9987cf181 100644
--- a/Libraries/LibJS/Rust/src/ast.rs
+++ b/Libraries/LibJS/Rust/src/ast.rs
@@ -18,28 +18,28 @@ use ak::Utf16String;
use crate::parser::FunctionRow;
use crate::parser::OuterResolutions;
use crate::parser::ScriptData;
-use crate::parser::columns::NONE;
-use crate::parser::columns::function_flag;
-use crate::parser::columns::tag;
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;
+use libjs_parser::columns::NONE;
+use libjs_parser::columns::function_flag;
+use libjs_parser::columns::tag;
+use libjs_parser::token::N_PROTO;
+use libjs_parser::token::T;
+pub use libjs_parser::tree::DeclarationKind;
+pub use libjs_parser::tree::LocalBinding;
+pub use libjs_parser::tree::LocalType;
+pub use libjs_parser::tree::LocalVarKind;
+pub use libjs_parser::tree::LocalVariable;
+pub use libjs_parser::tree::Name;
+pub use libjs_parser::tree::PatternMode;
+pub(crate) use libjs_parser::tree::Resolution;
+pub(crate) use libjs_parser::tree::ScopeRow;
+pub(crate) use libjs_parser::tree::ScopeTable;
+pub use libjs_parser::tree::TreeView;
+use libjs_parser::tree::is_optional_link;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Position {
diff --git a/Libraries/LibJS/Rust/src/breakpoint_positions.rs b/Libraries/LibJS/Rust/src/breakpoint_positions.rs
index 7bdf29c5bda..9678fb82015 100644
--- a/Libraries/LibJS/Rust/src/breakpoint_positions.rs
+++ b/Libraries/LibJS/Rust/src/breakpoint_positions.rs
@@ -13,8 +13,8 @@ use crate::compile::FunctionPayload;
use crate::compile::compile_function;
use crate::compile::compile_parsed_program_off_thread;
use crate::compile::parse;
-use crate::parser::base::DEFAULT_STACK_BUDGET;
-use crate::parser::stack_limit_for_budget;
+use libjs_parser::base::DEFAULT_STACK_BUDGET;
+use libjs_parser::base::stack_limit_for_budget;
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct BreakpointPosition {
diff --git a/Libraries/LibJS/Rust/src/bytecode/codegen/constructs.rs b/Libraries/LibJS/Rust/src/bytecode/codegen/constructs.rs
index f71ddce014a..2695f629c3c 100644
--- a/Libraries/LibJS/Rust/src/bytecode/codegen/constructs.rs
+++ b/Libraries/LibJS/Rust/src/bytecode/codegen/constructs.rs
@@ -26,11 +26,11 @@ use crate::bytecode::executable_data::PendingLiteralValueKind;
use crate::bytecode::instruction::typed as op;
use crate::bytecode::operand::*;
use crate::bytecode::source_map::SourceOffset;
-use crate::parser::OutOfStack;
-use crate::parser::columns::tag;
use crate::parser::literals::EscapeMode;
use crate::u32_from_usize;
use crate::utf16::Utf16StringBuilder;
+use libjs_parser::base::OutOfStack;
+use libjs_parser::columns::tag;
use super::bindings::*;
use super::context::Generator;
diff --git a/Libraries/LibJS/Rust/src/bytecode/codegen/mod.rs b/Libraries/LibJS/Rust/src/bytecode/codegen/mod.rs
index dd614faa6db..f4573b76e16 100644
--- a/Libraries/LibJS/Rust/src/bytecode/codegen/mod.rs
+++ b/Libraries/LibJS/Rust/src/bytecode/codegen/mod.rs
@@ -36,11 +36,11 @@ use crate::bytecode::executable_data::ExecutableData;
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 libjs_parser::base::OutOfStack;
use nodes::NodeId;
pub use stream::DisposableResourceKind;
@@ -76,7 +76,7 @@ pub fn compile_function(
generator.begin_function_scope(row);
let function = NodeId(node);
let flags = script.index.flags[row.0 as usize];
- use crate::parser::columns::function_flag::*;
+ use libjs_parser::columns::function_flag::*;
let swept = if flags & FIELD_INITIALIZER != 0 {
generator.sweep_field_initializer(function)
} else if flags & STATIC_BLOCK != 0 {
diff --git a/Libraries/LibJS/Rust/src/bytecode/codegen/nodes.rs b/Libraries/LibJS/Rust/src/bytecode/codegen/nodes.rs
index 8934b38f941..05bc8ed0fd6 100644
--- a/Libraries/LibJS/Rust/src/bytecode/codegen/nodes.rs
+++ b/Libraries/LibJS/Rust/src/bytecode/codegen/nodes.rs
@@ -18,15 +18,15 @@ use crate::ast::Name;
use crate::ast::SyntaxTree;
use crate::ast::UnaryOp;
use crate::ast::UpdateOp;
-use crate::parser::columns::NONE;
-use crate::parser::columns::tag;
use crate::parser::literals;
pub(super) use crate::parser::literals::EscapeMode;
pub(super) use crate::parser::literals::StringLiteralText;
use crate::parser::literals::has_escape_sequence;
-use crate::parser::token::T;
use crate::utf16::Utf16View;
use ak::Utf16String;
+use libjs_parser::columns::NONE;
+use libjs_parser::columns::tag;
+use libjs_parser::token::T;
/// A node of the tree. Zero stands for no node.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
diff --git a/Libraries/LibJS/Rust/src/bytecode/codegen/scope.rs b/Libraries/LibJS/Rust/src/bytecode/codegen/scope.rs
index 0e676e21b90..20e54ee1d20 100644
--- a/Libraries/LibJS/Rust/src/bytecode/codegen/scope.rs
+++ b/Libraries/LibJS/Rust/src/bytecode/codegen/scope.rs
@@ -33,15 +33,15 @@ use crate::bytecode::operand::*;
use crate::bytecode::source_map::SourceOffset;
use crate::parser::EnclosingCode;
use crate::parser::FunctionRow;
-use crate::parser::columns::NONE;
-use crate::parser::columns::function_flag;
-use crate::parser::token::N_ARGUMENTS;
-use crate::parser::token::N_DOT_NEW_TARGET;
-use crate::parser::token::N_DOT_SUPER;
-use crate::parser::token::N_DOT_THIS;
-use crate::parser::token::N_DOT_UNBOUND;
use crate::slice_block::SliceBlock;
use crate::u32_from_usize;
+use libjs_parser::columns::NONE;
+use libjs_parser::columns::function_flag;
+use libjs_parser::token::N_ARGUMENTS;
+use libjs_parser::token::N_DOT_NEW_TARGET;
+use libjs_parser::token::N_DOT_SUPER;
+use libjs_parser::token::N_DOT_THIS;
+use libjs_parser::token::N_DOT_UNBOUND;
use super::EnclosingEnvironmentScope;
use super::bindings::*;
@@ -1685,7 +1685,7 @@ impl Generator<'_> {
resolution.set_is_inside_scope_with_eval();
let names = index.capture_names[captures..captures + capture_count]
.iter()
- .map(|&capture| Name(capture & !crate::parser::base::USE_IN_WITH))
+ .map(|&capture| Name(capture & !libjs_parser::base::USE_IN_WITH))
.chain(std::iter::once(Name(N_DOT_UNBOUND)));
for name in names {
self.context
@@ -1704,7 +1704,7 @@ impl Generator<'_> {
let captures = index.capture_start[row as usize] as usize;
let capture_count = index.capture_count[row as usize] as usize;
for &capture in &index.capture_names[captures..captures + capture_count] {
- let name = Name(capture & !crate::parser::base::USE_IN_WITH);
+ let name = Name(capture & !libjs_parser::base::USE_IN_WITH);
if matches!(name.0, N_DOT_THIS | N_DOT_NEW_TARGET | N_DOT_SUPER) {
continue;
}
@@ -1762,7 +1762,7 @@ impl Generator<'_> {
let captures = index.capture_start[row as usize] as usize;
let capture_count = index.capture_count[row as usize] as usize;
for &capture in &index.capture_names[captures..captures + capture_count] {
- let name = Name(capture & !crate::parser::base::USE_IN_WITH);
+ let name = Name(capture & !libjs_parser::base::USE_IN_WITH);
let scope = &mut self.context.scope;
let Some(binding) = scope.binding_of(name) else {
continue;
diff --git a/Libraries/LibJS/Rust/src/bytecode/codegen/sweep.rs b/Libraries/LibJS/Rust/src/bytecode/codegen/sweep.rs
index de809822f08..e5c08cc18e5 100644
--- a/Libraries/LibJS/Rust/src/bytecode/codegen/sweep.rs
+++ b/Libraries/LibJS/Rust/src/bytecode/codegen/sweep.rs
@@ -23,12 +23,12 @@ use crate::bytecode::instruction::typed as op;
use crate::bytecode::operand::IdentifierTableIndex;
use crate::bytecode::operand::Operand;
use crate::bytecode::source_map::SourceOffset;
-use crate::parser::OutOfStack;
-use crate::parser::columns::NONE;
-use crate::parser::columns::function_flag;
-use crate::parser::columns::tag;
-use crate::parser::token::N_ARGUMENTS;
-use crate::parser::token::N_PROTO;
+use libjs_parser::base::OutOfStack;
+use libjs_parser::columns::NONE;
+use libjs_parser::columns::function_flag;
+use libjs_parser::columns::tag;
+use libjs_parser::token::N_ARGUMENTS;
+use libjs_parser::token::N_PROTO;
use super::context::Generator;
use super::nodes::*;
@@ -689,7 +689,7 @@ pub(super) fn is_anonymous_function_definition(tree: &SyntaxTree<'_>, expression
/// The operator of a logical assignment, by the token that it is.
fn logical_operator_of_assignment(token: u8) -> crate::ast::LogicalOp {
- use crate::parser::token::T;
+ use libjs_parser::token::T;
if token == T::LogAndAssign as u8 {
crate::ast::LogicalOp::And
} else if token == T::LogOrAssign as u8 {
diff --git a/Libraries/LibJS/Rust/src/compile.rs b/Libraries/LibJS/Rust/src/compile.rs
index c74ad2c0134..e627fda0bb2 100644
--- a/Libraries/LibJS/Rust/src/compile.rs
+++ b/Libraries/LibJS/Rust/src/compile.rs
@@ -31,7 +31,6 @@ use crate::bytecode::executable_data::ExecutableData;
use crate::bytecode::executable_data::PendingSharedFunctionData;
use crate::parser::EnclosingCode;
use crate::parser::FunctionRow;
-use crate::parser::OutOfStack;
use crate::parser::ParseError;
use crate::parser::ParseOptions;
use crate::parser::ScriptData;
@@ -41,6 +40,7 @@ use crate::parser::with_parsed_tree;
use crate::utf16::Utf16View;
use crate::work_zone::with_work_zone;
use ak::Utf16String;
+use libjs_parser::base::OutOfStack;
use std::collections::HashSet;
use std::sync::Arc;
use std::sync::Mutex;
@@ -246,7 +246,7 @@ pub fn compile_script(parsed: ParsedProgram) -> CompiledScript {
fn stack_limit_of_this_thread() -> usize {
match crate::parser::vm_stack_limit_of_this_thread() {
Some(limit) => limit.saturating_add(STACK_FOR_SMALL_WALKS),
- None => crate::parser::stack_limit_for_budget(crate::parser::base::DEFAULT_STACK_BUDGET),
+ None => libjs_parser::base::stack_limit_for_budget(libjs_parser::base::DEFAULT_STACK_BUDGET),
}
}
@@ -1301,7 +1301,7 @@ pub(crate) fn pending_function_of_row(
enclosing_environment_scope: Option<Arc<bytecode::codegen::EnclosingEnvironmentScope>>,
enclosing_code: &Arc<EnclosingCode>,
) -> PendingSharedFunctionData {
- use crate::parser::columns::function_flag;
+ use libjs_parser::columns::function_flag;
let index = &script.index;
let at = row as usize;
let flags = index.flags[at];
@@ -1663,7 +1663,7 @@ fn collect_var_scoped_declarations(tree: &SyntaxTree<'_>) -> VarScopedDeclaratio
#[cfg(test)]
mod tests {
use super::*;
- use crate::parser::stack_limit_for_budget;
+ use libjs_parser::base::stack_limit_for_budget;
const SOURCE: &str = "function outer() { return function inner() { return 1; }; }";
diff --git a/Libraries/LibJS/Rust/src/lib.rs b/Libraries/LibJS/Rust/src/lib.rs
index f11262c92ec..23e413bf8de 100644
--- a/Libraries/LibJS/Rust/src/lib.rs
+++ b/Libraries/LibJS/Rust/src/lib.rs
@@ -41,7 +41,8 @@
//! - `token.rs` — Token types
//! - `tokenize.rs` — Tokens of a source without parsing it, for syntax highlighting
//! - `lexer.rs` — Tokenizer: UTF-16 input → Token stream, for tokenize.rs
-//! - `parser/` — The parser, the columns of its syntax tree, scope analysis and identifier resolution
+//! - `parser/` — Parse jobs and what is kept of them; the parser, the columns of its syntax tree, scope analysis and
+//! identifier resolution are the `libjs_parser` crate (Libraries/LibJS/Parser/Rust)
//! - `ast.rs` — The syntax tree and the typed views that everything after the parser reads it through
//! - `bytecode/` — Bytecode generator, instruction types, and dumper
//! - `breakpoint_positions.rs` — Where in a source a debugger can stop
@@ -171,11 +172,7 @@ mod work_zone;
#[cfg(test)]
mod test_host;
-/// Convert a `usize` to `u32`, panicking if the value exceeds `u32::MAX`.
-/// Prefer this over `as u32` which silently truncates on 64-bit platforms.
-pub(crate) fn u32_from_usize(value: usize) -> u32 {
- u32::try_from(value).expect("value exceeds u32::MAX")
-}
+pub(crate) use libjs_parser::u32_from_usize;
#[cfg(not(test))]
mod layout_static_assertions {
diff --git a/Libraries/LibJS/Rust/src/parser/enclosing.rs b/Libraries/LibJS/Rust/src/parser/enclosing.rs
index 2610c02a3f9..fc22c93dc63 100644
--- a/Libraries/LibJS/Rust/src/parser/enclosing.rs
+++ b/Libraries/LibJS/Rust/src/parser/enclosing.rs
@@ -7,12 +7,12 @@
//! What the code that a compile job compiled leaves for the functions nested in it, which get compiled later: how the
//! names that they capture resolve (see `resolve.rs`, which works it out for a program).
-use super::columns::NONE;
-use super::resolve::outer_key;
-use super::token::N_DOT_UNBOUND;
use crate::ast::Name;
use crate::ast::Resolution;
use crate::ast::SyntaxTree;
+use libjs_parser::columns::NONE;
+use libjs_parser::resolve::outer_key;
+use libjs_parser::token::N_DOT_UNBOUND;
use std::sync::Arc;
/// What a name means from inside a function that a tree did not hold the code of, by function row and name.
diff --git a/Libraries/LibJS/Rust/src/parser/kept.rs b/Libraries/LibJS/Rust/src/parser/kept.rs
index a49e73896bc..f5d51abd92e 100644
--- a/Libraries/LibJS/Rust/src/parser/kept.rs
+++ b/Libraries/LibJS/Rust/src/parser/kept.rs
@@ -7,13 +7,13 @@
//! What the first parse of a source keeps on the heap, at its final size, for the compile jobs that come later, maybe
//! on other threads.
-use super::columns::FunctionIndexView;
-use super::intern::Interner;
-use super::intern::LongRow;
-use super::intern::NameTables;
-use super::intern::NameTablesMut;
-use super::intern::Row;
use ak::Zone;
+use libjs_parser::columns::FunctionIndexView;
+use libjs_parser::intern::Interner;
+use libjs_parser::intern::LongRow;
+use libjs_parser::intern::NameTables;
+use libjs_parser::intern::NameTablesMut;
+use libjs_parser::intern::Row;
use std::sync::OnceLock;
/// The tables of an interner on the heap, at the size they have, which the reparse context of a source keeps.
diff --git a/Libraries/LibJS/Rust/src/parser/literals.rs b/Libraries/LibJS/Rust/src/parser/literals.rs
index 3cc5bee54ea..5a5eeb3bc2e 100644
--- a/Libraries/LibJS/Rust/src/parser/literals.rs
+++ b/Libraries/LibJS/Rust/src/parser/literals.rs
@@ -7,10 +7,10 @@
//! Turning the source text of literals into their values. The lexer only validates literals, and a value gets computed
//! when something needs it.
-pub use super::escapes::EscapeMode;
-use super::escapes::decode_escape_sequences;
use crate::utf16::Utf16View;
use ak::Utf16String;
+pub use libjs_parser::escapes::EscapeMode;
+use libjs_parser::escapes::decode_escape_sequences;
const fn ch(c: u8) -> u16 {
c as u16
diff --git a/Libraries/LibJS/Rust/src/parser/mod.rs b/Libraries/LibJS/Rust/src/parser/mod.rs
index 5db6d14c944..e5569196606 100644
--- a/Libraries/LibJS/Rust/src/parser/mod.rs
+++ b/Libraries/LibJS/Rust/src/parser/mod.rs
@@ -7,25 +7,23 @@
//! The JavaScript parser. Lexing is driven by the parser, the syntax tree is a set of flat columns, and scope analysis
//! happens while parsing, with no map per scope. [`crate::ast`] is how everything after the parser reads the tree.
//!
+//! The parser itself is the `libjs_parser` crate, which does all of its work in the work zone of its thread. This
+//! starts the parse jobs, and copies what they keep out of the zone.
+//!
//! 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, 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;
mod enclosing;
-pub(crate) mod escapes;
-pub(crate) mod expr;
-mod intern;
mod kept;
-mod lexer;
pub(crate) mod literals;
-pub(crate) mod resolve;
-mod stmt;
-pub(crate) mod token;
-pub(crate) mod tree;
-pub(crate) mod unit;
+
+use libjs_parser::base;
+use libjs_parser::columns;
+use libjs_parser::intern;
+use libjs_parser::resolve;
+use libjs_parser::unit;
use crate::ast::Name;
use crate::ast::NameTable;
@@ -40,10 +38,9 @@ use crate::work_zone::with_work_zone;
use ak::Zone;
use ak::ZoneVec;
use base::Mode;
-pub use base::OutOfStack;
+use base::OutOfStack;
use base::Parser;
use base::SOURCE_PADDING;
-pub use base::stack_limit_for_budget;
use columns::Ast;
use columns::AstColumns;
use columns::FunctionIndexBuilder;