Skip to content

Truly independent web browser

LibRegex: Parse patterns in a per-thread work zone

Andreas Kling4bd337e820df
diff --git a/AK/FFIHelpers.h b/AK/FFIHelpers.h
index a45f2ed9069..74d25b1d8f6 100644
--- a/AK/FFIHelpers.h
+++ b/AK/FFIHelpers.h
@@ -30,9 +30,13 @@ void ladybird_dealloc(void*, size_t alignment);
// Gives the memory the calling thread freed back to the system (see ak_kmalloc_collect()).
void ladybird_release_unused_allocator_memory();
-// Sets what ak_release_idle_thread_memory() calls. The function gives back the memory that the calling thread keeps
-// for its next jobs, and does nothing on a thread that keeps none.
-void ladybird_set_idle_thread_memory_release(void (*)());
+// Adds a function that ak_release_idle_thread_memory() calls. The function gives back the memory that the calling
+// thread keeps for its next jobs, and does nothing on a thread that keeps none. Adding a function a second time does
+// nothing.
+void ladybird_add_idle_thread_memory_release(void (*)());
+
+// Calls ak_release_idle_thread_memory().
+void ladybird_release_idle_thread_memory();
// For a thread that frees all of its memory when it ends: while one runs, what the allocator purges goes back to the
// system right away.
diff --git a/AK/Rust/src/lib.rs b/AK/Rust/src/lib.rs
index 58a5f5e68c3..10bf84d3aea 100644
--- a/AK/Rust/src/lib.rs
+++ b/AK/Rust/src/lib.rs
@@ -121,7 +121,8 @@ unsafe extern "C" {
) -> u8;
fn ladybird_encode_base64_to_utf16(data: *const u8, length: usize, url: bool, omit_padding: bool) -> usize;
fn ladybird_release_unused_allocator_memory();
- fn ladybird_set_idle_thread_memory_release(release: extern "C" fn());
+ fn ladybird_add_idle_thread_memory_release(release: extern "C" fn());
+ fn ladybird_release_idle_thread_memory();
fn ladybird_convert_to_decimal_exponential_form(
value: f64,
sign: *mut bool,
@@ -534,11 +535,18 @@ pub fn release_unused_allocator_memory() {
unsafe { ladybird_release_unused_allocator_memory() }
}
-/// Sets the function that a thread pool calls on a thread that goes idle. It gives back the memory that the calling
-/// thread keeps outside the allocator for its next jobs, and does nothing on a thread that keeps none.
-pub fn set_idle_thread_memory_release(release: extern "C" fn()) {
- // SAFETY: Any thread may set the function, which stays valid for as long as the process runs.
- unsafe { ladybird_set_idle_thread_memory_release(release) }
+/// Adds a function that a thread pool calls on a thread that goes idle (see `release_idle_thread_memory()`). It gives
+/// back the memory that the calling thread keeps outside the allocator for its next jobs, and does nothing on a thread
+/// that keeps none. Adding a function a second time does nothing.
+pub fn add_idle_thread_memory_release(release: extern "C" fn()) {
+ // SAFETY: Any thread may add a function, which stays valid for as long as the process runs.
+ unsafe { ladybird_add_idle_thread_memory_release(release) }
+}
+
+/// Calls all the functions added with `add_idle_thread_memory_release()` on the calling thread.
+pub fn release_idle_thread_memory() {
+ // SAFETY: Takes no arguments, and any thread may call it.
+ unsafe { ladybird_release_idle_thread_memory() }
}
/// Maps in, in one go, the pages of the room `vector` has past its elements for `additional` more, for writes about to
diff --git a/AK/kmalloc.cpp b/AK/kmalloc.cpp
index f20d5c5d3c8..0f7cd265f17 100644
--- a/AK/kmalloc.cpp
+++ b/AK/kmalloc.cpp
@@ -211,15 +211,31 @@ extern "C" void ladybird_did_end_short_lived_thread()
#endif
-static Atomic<void (*)(), AK::MemoryOrder::memory_order_relaxed> s_idle_thread_memory_release { nullptr };
+// NB: Each library that links a Rust crate with a per-thread pool has a copy of that pool, and each copy adds its own
+// release function.
+static Atomic<void (*)(), AK::MemoryOrder::memory_order_relaxed> s_idle_thread_memory_releases[8] {};
-extern "C" void ladybird_set_idle_thread_memory_release(void (*release)())
+extern "C" void ladybird_add_idle_thread_memory_release(void (*release)())
{
- s_idle_thread_memory_release.store(release);
+ for (auto& slot : s_idle_thread_memory_releases) {
+ void (*expected)() = nullptr;
+ if (slot.compare_exchange_strong(expected, release) || expected == release)
+ return;
+ }
+ VERIFY_NOT_REACHED();
}
void ak_release_idle_thread_memory()
{
- if (auto* release = s_idle_thread_memory_release.load())
+ for (auto& slot : s_idle_thread_memory_releases) {
+ auto* release = slot.load();
+ if (!release)
+ return;
release();
+ }
+}
+
+extern "C" void ladybird_release_idle_thread_memory()
+{
+ ak_release_idle_thread_memory();
}
diff --git a/AK/kmalloc.h b/AK/kmalloc.h
index b6ba185e65e..655138f0f24 100644
--- a/AK/kmalloc.h
+++ b/AK/kmalloc.h
@@ -32,7 +32,7 @@ void ak_kfree(void* ptr);
[[nodiscard]] size_t ak_kmalloc_usable_size(void const* ptr);
void ak_kmalloc_collect();
// Gives back the memory that the calling thread keeps outside the allocator for its next jobs, for a thread that goes
-// idle (see ladybird_set_idle_thread_memory_release()).
+// idle (see ladybird_add_idle_thread_memory_release()).
void ak_release_idle_thread_memory();
[[nodiscard]] inline void* kcalloc(size_t count, size_t size)
diff --git a/Libraries/LibJS/Rust/src/frontend_host.rs b/Libraries/LibJS/Rust/src/frontend_host.rs
index b6f4ef9f332..999e8002643 100644
--- a/Libraries/LibJS/Rust/src/frontend_host.rs
+++ b/Libraries/LibJS/Rust/src/frontend_host.rs
@@ -39,12 +39,7 @@ pub fn validate_regex(pattern: &[u16], flags: &[u16]) -> Result<(), RegexError>
sticky: has_flag(b'y'),
has_indices: has_flag(b'd'),
};
- // Converted the way LibRegex's rust_regex_compile converts a UTF-16 pattern, although ParsePattern only produces
- // ASCII.
- let pattern_characters = char::decode_utf16(parsed_pattern.iter().copied())
- .map(|character| character.unwrap_or(char::REPLACEMENT_CHARACTER))
- .collect();
- Regex::compile_chars(pattern_characters, compile_flags).map_err(|error| match error {
+ Regex::compile_utf16(&parsed_pattern, compile_flags, |error| match error {
ParseError::TooDeeplyNested => RegexError::OutOfStack,
error => RegexError::Invalid(format!("RegExp compile error: {error}")),
})?;
diff --git a/Libraries/LibJS/Rust/src/interpreter/vm.rs b/Libraries/LibJS/Rust/src/interpreter/vm.rs
index 75689611742..36c9fc3b57b 100644
--- a/Libraries/LibJS/Rust/src/interpreter/vm.rs
+++ b/Libraries/LibJS/Rust/src/interpreter/vm.rs
@@ -2565,7 +2565,7 @@ unsafe extern "C" fn sweep(context: *mut c_void) {
if vm.heap.get().is_some_and(Heap::is_returning_memory_to_system) {
crate::source_text::park_all_source_texts();
vm.regex_cache.clear();
- crate::work_zone::release_idle_memory();
+ ak::release_idle_thread_memory();
} else {
crate::source_text::park_idle_source_texts();
vm.regex_cache.remove_unused();
diff --git a/Libraries/LibJS/Rust/src/runtime/ecmascript_regex.rs b/Libraries/LibJS/Rust/src/runtime/ecmascript_regex.rs
index 4f5374500fc..8c4d712fe45 100644
--- a/Libraries/LibJS/Rust/src/runtime/ecmascript_regex.rs
+++ b/Libraries/LibJS/Rust/src/runtime/ecmascript_regex.rs
@@ -81,15 +81,12 @@ impl EcmaScriptRegex {
has_indices: flags.has_indices,
};
- // Converted as rust_regex_compile_latin1 and rust_regex_compile convert the pattern they are passed.
- let pattern_characters = match pattern {
- Utf16View::Ascii(bytes) | Utf16View::Latin1(bytes) => bytes.iter().map(|&byte| char::from(byte)).collect(),
- Utf16View::Utf16(code_units) => char::decode_utf16(code_units.iter().copied())
- .map(|character| character.unwrap_or(char::REPLACEMENT_CHARACTER))
- .collect(),
- };
-
- let regex = Regex::compile_chars(pattern_characters, rust_flags).map_err(|error| error.to_string())?;
+ let regex = match pattern {
+ Utf16View::Ascii(bytes) | Utf16View::Latin1(bytes) => {
+ Regex::compile_latin1(bytes, rust_flags, |error| error.to_string())
+ }
+ Utf16View::Utf16(code_units) => Regex::compile_utf16(code_units, rust_flags, |error| error.to_string()),
+ }?;
let named_groups = regex
.named_groups()
diff --git a/Libraries/LibJS/Rust/src/test_host.rs b/Libraries/LibJS/Rust/src/test_host.rs
index 0fb965f81d0..037151a2cb5 100644
--- a/Libraries/LibJS/Rust/src/test_host.rs
+++ b/Libraries/LibJS/Rust/src/test_host.rs
@@ -149,4 +149,7 @@ extern "C" fn ladybird_utf16_string_create_uninitialized(length: usize, has_lati
extern "C" fn ladybird_utf16_string_unref(_raw: usize) {}
#[unsafe(no_mangle)]
-extern "C" fn ladybird_set_idle_thread_memory_release(_release: extern "C" fn()) {}
+extern "C" fn ladybird_add_idle_thread_memory_release(_release: extern "C" fn()) {}
+
+#[unsafe(no_mangle)]
+extern "C" fn ladybird_release_idle_thread_memory() {}
diff --git a/Libraries/LibJS/Rust/src/work_zone.rs b/Libraries/LibJS/Rust/src/work_zone.rs
index cbcab1ea1b1..a2669c36b2f 100644
--- a/Libraries/LibJS/Rust/src/work_zone.rs
+++ b/Libraries/LibJS/Rust/src/work_zone.rs
@@ -32,7 +32,7 @@ thread_local! {
/// Runs `job` with the zone of the thread for its work data. Nothing that `job` returns can refer to the zone.
pub(crate) fn with_work_zone<R>(job: impl for<'zone> FnOnce(&'zone Zone) -> R) -> R {
let mut zone = SPARE_ZONE.take().unwrap_or_else(|| {
- ak::set_idle_thread_memory_release(release_idle_memory);
+ ak::add_idle_thread_memory_release(release_idle_memory);
Zone::new(LIMIT, c"JS parse work")
});
let mut size = 0;
@@ -50,7 +50,7 @@ pub(crate) fn with_work_zone<R>(job: impl for<'zone> FnOnce(&'zone Zone) -> R) -
}
/// Gives the memory of the zone of this thread back to the system. A thread pool calls this on a thread that goes idle
-/// (see `ak::set_idle_thread_memory_release()`).
-pub(crate) extern "C" fn release_idle_memory() {
+/// (see `ak::add_idle_thread_memory_release()`).
+extern "C" fn release_idle_memory() {
drop(SPARE_ZONE.take());
}
diff --git a/Libraries/LibRegex/Rust/src/ast.rs b/Libraries/LibRegex/Rust/src/ast.rs
index ddbd9b06797..f73fa2fb025 100644
--- a/Libraries/LibRegex/Rust/src/ast.rs
+++ b/Libraries/LibRegex/Rust/src/ast.rs
@@ -10,6 +10,9 @@
//! ECMAScript regex pattern, preserving all information needed for
//! compilation, optimization, and error reporting.
//!
+//! The tree lives in a zone (see `ak::Zone`): its lists are slices of the zone and its names are strings of the zone,
+//! so the tree has the lifetime `'z` of the zone and is plain data that is copied by value.
+//!
//! Spec:
//! - <https://tc39.es/ecma262/#sec-patterns>
//! - <https://tc39.es/ecma262/#sec-pattern-semantics>
@@ -19,14 +22,14 @@
/// Spec model: the `Pattern` grammar goal and the RegExp Record built from it.
/// - <https://tc39.es/ecma262/#sec-patterns>
/// - <https://tc39.es/ecma262/#sec-regexp-records>
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub struct Pattern {
- pub disjunction: Disjunction,
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct Pattern<'z> {
+ pub disjunction: Disjunction<'z>,
pub flags: Flags,
/// Total number of capture groups (not counting group 0).
pub capture_count: u32,
/// Named capture groups, in order of appearance.
- pub named_groups: Vec<NamedGroup>,
+ pub named_groups: &'z [NamedGroup<'z>],
}
/// A named capture group declaration.
@@ -34,9 +37,9 @@ pub struct Pattern {
/// Spec model: a named `GroupSpecifier` that later participates in named
/// backreference resolution.
/// <https://tc39.es/ecma262/#sec-patterns>
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub struct NamedGroup {
- pub name: String,
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct NamedGroup<'z> {
+ pub name: &'z str,
pub index: u32,
}
@@ -63,9 +66,9 @@ pub struct Flags {
///
/// Spec model: `Disjunction`.
/// <https://tc39.es/ecma262/#sec-compilesubpattern>
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub struct Disjunction {
- pub alternatives: Vec<Alternative>,
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct Disjunction<'z> {
+ pub alternatives: &'z [Alternative<'z>],
}
/// An alternative is a sequence of terms matched left-to-right.
@@ -74,18 +77,18 @@ pub struct Disjunction {
///
/// Spec model: `Alternative`.
/// <https://tc39.es/ecma262/#sec-compilesubpattern>
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub struct Alternative {
- pub terms: Vec<Term>,
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct Alternative<'z> {
+ pub terms: &'z [Term<'z>],
}
/// A single term in an alternative: an atom optionally followed by a quantifier.
///
/// Spec model: `Term`.
/// <https://tc39.es/ecma262/#sec-compilesubpattern>
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub struct Term {
- pub atom: Atom,
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct Term<'z> {
+ pub atom: Atom<'z>,
pub quantifier: Option<Quantifier>,
}
@@ -93,7 +96,7 @@ pub struct Term {
///
/// Spec model: the quantifier record produced by `CompileQuantifier`.
/// <https://tc39.es/ecma262/#sec-compilequantifier>
-#[derive(Debug, Clone, PartialEq, Eq)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Quantifier {
pub min: u32,
pub max: Option<u32>,
@@ -132,8 +135,8 @@ impl Quantifier {
/// represented as dedicated AST variants for easier downstream handling.
/// - <https://tc39.es/ecma262/#sec-compileatom>
/// - <https://tc39.es/ecma262/#sec-compileassertion>
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub enum Atom {
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Atom<'z> {
/// A literal character (as a u32 code point, to support WTF-16 lone surrogates).
/// `/a/` → `Literal(0x61)`
Literal(u32),
@@ -142,41 +145,41 @@ pub enum Atom {
Dot,
/// A character class like `[a-z]` or `[^0-9]`.
- CharacterClass(CharacterClass),
+ CharacterClass(CharacterClass<'z>),
/// A built-in character class escape: `\d`, `\D`, `\w`, `\W`, `\s`, `\S`.
BuiltinCharacterClass(BuiltinCharacterClass),
/// A Unicode property escape: `\p{Letter}`, `\P{Script=Greek}`.
- UnicodeProperty(UnicodeProperty),
+ UnicodeProperty(UnicodeProperty<'z>),
/// A capturing group: `(expr)` or `(?<name>expr)`.
- Group(Group),
+ Group(Group<'z>),
/// A non-capturing group: `(?:expr)`.
- NonCapturingGroup(NonCapturingGroup),
+ NonCapturingGroup(NonCapturingGroup<'z>),
/// A lookaround assertion: `(?=expr)`, `(?!expr)`, `(?<=expr)`, `(?<!expr)`.
- Lookaround(Lookaround),
+ Lookaround(Lookaround<'z>),
/// A backreference: `\1`, `\k<name>`.
- Backreference(Backreference),
+ Backreference(Backreference<'z>),
/// An assertion that matches a position, not a character.
Assertion(AssertionKind),
/// A modifier group that changes flags for its contents: `(?i:expr)`.
- ModifierGroup(ModifierGroup),
+ ModifierGroup(ModifierGroup<'z>),
}
/// A character class: `[abc]`, `[a-z]`, `[^0-9]`.
///
/// Spec model: `CharacterClass`.
/// <https://tc39.es/ecma262/#sec-compilecharacterclass>
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub struct CharacterClass {
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct CharacterClass<'z> {
pub negated: bool,
- pub body: CharacterClassBody,
+ pub body: CharacterClassBody<'z>,
}
/// The body of a character class, which differs between `/u`|`/v` mode and
@@ -186,21 +189,21 @@ pub struct CharacterClass {
/// `ClassSetExpression`.
/// - <https://tc39.es/ecma262/#sec-patterns>
/// - <https://tc39.es/ecma262/#sec-compilecharacterclass>
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub enum CharacterClassBody {
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum CharacterClassBody<'z> {
/// Legacy or `/u` mode: a flat list of ranges/chars.
- Ranges(Vec<CharacterClassRange>),
+ Ranges(&'z [CharacterClassRange<'z>]),
/// `/v` (unicode sets) mode: supports set operations.
- UnicodeSet(ClassSetExpression),
+ UnicodeSet(ClassSetExpression<'z>),
}
/// A single element in a `[...]` character class (legacy and `/u` mode).
///
/// Spec model: the pieces consumed by `CompileToCharSet`.
/// <https://tc39.es/ecma262/#sec-compiletocharset>
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub enum CharacterClassRange {
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum CharacterClassRange<'z> {
/// A single character (as u32 code point, to support WTF-16 lone surrogates).
Single(u32),
@@ -211,23 +214,23 @@ pub enum CharacterClassRange {
BuiltinClass(BuiltinCharacterClass),
/// A Unicode property escape inside `[...]`: `[\p{Letter}]`.
- UnicodeProperty(UnicodeProperty),
+ UnicodeProperty(UnicodeProperty<'z>),
}
/// Set operations for `/v` (unicode sets) mode character classes.
///
/// Spec model: `ClassSetExpression`.
/// <https://tc39.es/ecma262/#sec-compilecharacterclass>
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub enum ClassSetExpression {
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum ClassSetExpression<'z> {
/// A union of class set operands (the default when just listing items).
- Union(Vec<ClassSetOperand>),
+ Union(&'z [ClassSetOperand<'z>]),
/// Intersection: `[a-z&&[aeiou]]`.
- Intersection(Vec<ClassSetOperand>),
+ Intersection(&'z [ClassSetOperand<'z>]),
/// Subtraction: `[a-z--[aeiou]]`.
- Subtraction(Vec<ClassSetOperand>),
+ Subtraction(&'z [ClassSetOperand<'z>]),
}
/// An operand in a unicode sets class expression.
@@ -235,8 +238,8 @@ pub enum ClassSetExpression {
/// Spec model: `ClassSetOperand` and `ClassStringDisjunction`.
/// - <https://tc39.es/ecma262/#sec-patterns>
/// - <https://tc39.es/ecma262/#sec-compileclasssetstring>
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub enum ClassSetOperand {
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum ClassSetOperand<'z> {
/// A single character.
Char(u32),
@@ -244,16 +247,16 @@ pub enum ClassSetOperand {
Range(u32, u32),
/// A nested character class: `[a-z]` inside another class.
- NestedClass(CharacterClass),
+ NestedClass(CharacterClass<'z>),
/// A builtin class escape: `\d`, `\w`, etc.
BuiltinClass(BuiltinCharacterClass),
/// A Unicode property: `\p{Letter}`.
- UnicodeProperty(UnicodeProperty),
+ UnicodeProperty(UnicodeProperty<'z>),
/// A string literal in a class (v-flag): `\q{abc}`.
- StringLiteral(Vec<char>),
+ StringLiteral(&'z [char]),
}
/// Built-in character class escapes.
@@ -297,36 +300,36 @@ impl BuiltinCharacterClass {
/// - <https://tc39.es/ecma262/#sec-compiletocharset>
/// - <https://tc39.es/ecma262/#sec-runtime-semantics-unicodematchproperty-p>
/// - <https://tc39.es/ecma262/#sec-runtime-semantics-unicodematchpropertyvalue-p-v>
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub struct UnicodeProperty {
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct UnicodeProperty<'z> {
/// Whether this is `\P{...}` (negated) or `\p{...}`.
pub negated: bool,
/// The property name, e.g. `"Letter"`, `"Script"`.
- pub name: String,
+ pub name: &'z str,
/// The property value, if present, e.g. `"Greek"` in `\p{Script=Greek}`.
- pub value: Option<String>,
+ pub value: Option<&'z str>,
}
/// A capturing group: `(expr)` or `(?<name>expr)`.
///
/// Spec model: a capturing `Atom` with an optional `GroupSpecifier`.
/// <https://tc39.es/ecma262/#sec-compileatom>
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub struct Group {
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct Group<'z> {
/// 1-based capture index.
pub index: u32,
/// Optional group name for `(?<name>...)`.
- pub name: Option<String>,
- pub body: Disjunction,
+ pub name: Option<&'z str>,
+ pub body: Disjunction<'z>,
}
/// A non-capturing group: `(?:expr)`.
///
/// Spec model: the `(?: Disjunction )` branch of `Atom`.
/// <https://tc39.es/ecma262/#sec-compileatom>
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub struct NonCapturingGroup {
- pub body: Disjunction,
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct NonCapturingGroup<'z> {
+ pub body: Disjunction<'z>,
}
/// A lookaround assertion.
@@ -334,10 +337,10 @@ pub struct NonCapturingGroup {
/// Spec model: lookahead and lookbehind forms handled by
/// `Runtime Semantics: CompileAssertion`.
/// <https://tc39.es/ecma262/#sec-compileassertion>
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub struct Lookaround {
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct Lookaround<'z> {
pub kind: LookaroundKind,
- pub body: Disjunction,
+ pub body: Disjunction<'z>,
}
/// Spec model: the four lookaround assertion forms.
@@ -359,12 +362,12 @@ pub enum LookaroundKind {
/// Spec model: decimal and named backreference atoms.
/// - <https://tc39.es/ecma262/#sec-compileatom>
/// - <https://tc39.es/ecma262/#sec-backreference-matcher>
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub enum Backreference {
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Backreference<'z> {
/// `\1`, `\2`, etc. — numeric backreference.
Index(u32),
/// `\k<name>` — named backreference.
- Named(String),
+ Named(&'z str),
}
/// A zero-width assertion.
@@ -389,11 +392,11 @@ pub enum AssertionKind {
/// Spec model: modifier-scoped `Atom` forms that call `UpdateModifiers`.
/// - <https://tc39.es/ecma262/#sec-compileatom>
/// - <https://tc39.es/ecma262/#sec-updatemodifiers>
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub struct ModifierGroup {
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct ModifierGroup<'z> {
pub add_flags: ModifierFlags,
pub remove_flags: ModifierFlags,
- pub body: Disjunction,
+ pub body: Disjunction<'z>,
}
/// Flags that can be toggled in a modifier group.
diff --git a/Libraries/LibRegex/Rust/src/compiler.rs b/Libraries/LibRegex/Rust/src/compiler.rs
index e1ccb57ef2b..be814cff1f7 100644
--- a/Libraries/LibRegex/Rust/src/compiler.rs
+++ b/Libraries/LibRegex/Rust/src/compiler.rs
@@ -33,7 +33,7 @@ pub fn resolve_property(name: &str, value: Option<&str>) -> Option<ResolvedPrope
///
/// Spec entry point: `CompilePattern`.
/// <https://tc39.es/ecma262/#sec-compilepattern>
-pub fn compile(pattern: &Pattern) -> Result<Program, Error> {
+pub fn compile<'z>(pattern: &Pattern<'z>) -> Result<Program, Error<'z>> {
let mut compiler = Compiler::new(pattern);
compiler.compile_pattern(pattern);
if compiler.ran_out_of_stack.get() {
@@ -43,7 +43,7 @@ pub fn compile(pattern: &Pattern) -> Result<Program, Error> {
.named_groups
.iter()
.map(|ng| NamedGroupEntry {
- name: ng.name.clone(),
+ name: ng.name.to_string(),
index: ng.index,
})
.collect();
@@ -353,10 +353,10 @@ impl Compiler {
ClassSetOperand::UnicodeProperty(up) => {
if self.program.unicode_sets
&& !up.negated
- && libunicode_rust::character_types::is_string_property(&up.name)
+ && libunicode_rust::character_types::is_string_property(up.name)
{
let mut lengths = Self::singleton_length_set();
- for string in Self::get_string_property_strings(&up.name) {
+ for string in Self::get_string_property_strings(up.name) {
lengths.insert(string.len());
}
return lengths;
@@ -462,8 +462,8 @@ impl Compiler {
if self.is_out_of_stack() {
return;
}
- for alt in &disj.alternatives {
- for term in &alt.terms {
+ for alt in disj.alternatives {
+ for term in alt.terms {
self.collect_captures(&term.atom, out);
}
}
@@ -553,7 +553,7 @@ impl Compiler {
self.compile_term(&term);
return;
}
- self.emit_split_chain(&disj.alternatives, |s, alt| s.compile_alternative(alt));
+ self.emit_split_chain(disj.alternatives, |s, alt| s.compile_alternative(alt));
}
/// Lower `Alternative` in the current direction.
@@ -564,7 +564,7 @@ impl Compiler {
self.compile_term(term);
}
} else {
- for term in &alt.terms {
+ for term in alt.terms {
self.compile_term(term);
}
}
@@ -607,13 +607,13 @@ impl Compiler {
Atom::UnicodeProperty(up) => {
// String properties (e.g. Basic_Emoji) can match multi-character
// sequences and cannot use simple matching.
- if self.program.unicode_sets && libunicode_rust::character_types::is_string_property(&up.name) {
+ if self.program.unicode_sets && libunicode_rust::character_types::is_string_property(up.name) {
return None;
}
Some(SimpleMatch::UnicodeProperty(Box::new(UnicodePropertyData {
negated: up.negated,
- name: up.name.clone(),
- value: up.value.clone(),
+ name: up.name.to_string(),
+ value: up.value.map(str::to_string),
resolved: None, // Will be populated after compilation.
})))
}
@@ -625,14 +625,14 @@ impl Compiler {
/// term. This preserves semantics for single-term simple-match
/// alternatives while avoiding exponential backtracking in quantified
/// contexts such as `^(a|a?)+$`.
- fn try_merge_optional_alternatives(&self, disj: &Disjunction) -> Option<Term> {
- let [first, second] = disj.alternatives.as_slice() else {
+ fn try_merge_optional_alternatives<'z>(&self, disj: &Disjunction<'z>) -> Option<Term<'z>> {
+ let [first, second] = disj.alternatives else {
return None;
};
- let [first_term] = first.terms.as_slice() else {
+ let [first_term] = first.terms else {
return None;
};
- let [second_term] = second.terms.as_slice() else {
+ let [second_term] = second.terms else {
return None;
};
@@ -645,7 +645,7 @@ impl Compiler {
let optional = Quantifier::zero_or_one(true);
match (&first_term.quantifier, &second_term.quantifier) {
(None, Some(q)) | (Some(q), None) if *q == optional => Some(Term {
- atom: first_term.atom.clone(),
+ atom: first_term.atom,
quantifier: Some(optional),
}),
_ => None,
@@ -917,12 +917,12 @@ impl Compiler {
Atom::UnicodeProperty(up) => {
if self.program.unicode_sets
&& !up.negated
- && libunicode_rust::character_types::is_string_property(&up.name)
+ && libunicode_rust::character_types::is_string_property(up.name)
{
- self.emit_string_property_match(&up.name, up.value.as_deref());
+ self.emit_string_property_match(up.name, up.value);
return;
}
- self.emit_unicode_property(up.negated, &up.name, up.value.as_deref());
+ self.emit_unicode_property(up.negated, up.name, up.value);
}
Atom::Group(g) => {
@@ -969,7 +969,7 @@ impl Compiler {
self.emit(Instruction::Backref(*n));
}
Backreference::Named(name) => {
- self.emit(Instruction::BackrefNamed(name.clone()));
+ self.emit(Instruction::BackrefNamed(name.to_string()));
}
},
@@ -1050,7 +1050,7 @@ impl Compiler {
let mut has_builtin = false;
let split_surrogates = !self.program.unicode && !self.program.unicode_sets;
- for r in ranges {
+ for r in *ranges {
match r {
CharacterClassRange::Single(cp) => {
if split_surrogates && *cp > 0xFFFF {
@@ -1147,7 +1147,7 @@ impl Compiler {
self.emit(Instruction::BuiltinClass(*bc));
}
CharacterClassRange::UnicodeProperty(up) => {
- self.emit_unicode_property(up.negated, &up.name, up.value.as_deref());
+ self.emit_unicode_property(up.negated, up.name, up.value);
}
}
}
@@ -1167,20 +1167,20 @@ impl Compiler {
}),
ClassSetOperand::BuiltinClass(bc) => Some(SimpleMatch::BuiltinClass(*bc)),
ClassSetOperand::UnicodeProperty(up) => {
- if libunicode_rust::character_types::is_string_property(&up.name) {
+ if libunicode_rust::character_types::is_string_property(up.name) {
return None;
}
Some(SimpleMatch::UnicodeProperty(Box::new(UnicodePropertyData {
negated: up.negated,
- name: up.name.clone(),
- value: up.value.clone(),
+ name: up.name.to_string(),
+ value: up.value.map(str::to_string),
resolved: None,
})))
}
ClassSetOperand::NestedClass(cc) => match &cc.body {
CharacterClassBody::Ranges(ranges_vec) => {
let mut ranges = Vec::new();
- for r in ranges_vec {
+ for r in *ranges_vec {
match r {
CharacterClassRange::Single(cp) => {
ranges.push(CharRange { start: *cp, end: *cp });
@@ -1309,13 +1309,13 @@ impl Compiler {
matchers.push(SimpleMatch::BuiltinClass(*bc));
}
CharacterClassRange::UnicodeProperty(up) => {
- if libunicode_rust::character_types::is_string_property(&up.name) {
+ if libunicode_rust::character_types::is_string_property(up.name) {
return None;
}
matchers.push(SimpleMatch::UnicodeProperty(Box::new(UnicodePropertyData {
negated: up.negated,
- name: up.name.clone(),
- value: up.value.clone(),
+ name: up.name.to_string(),
+ value: up.value.map(str::to_string),
resolved: None,
})));
}
@@ -1373,7 +1373,7 @@ impl Compiler {
};
let mut ranges = Vec::new();
- for operand in operands {
+ for operand in *operands {
match operand {
ClassSetOperand::Char(c) => {
ranges.push(CharRange { start: *c, end: *c });
@@ -1383,7 +1383,7 @@ impl Compiler {
}
ClassSetOperand::NestedClass(cc) => match &cc.body {
CharacterClassBody::Ranges(class_ranges) => {
- for r in class_ranges {
+ for r in *class_ranges {
match r {
CharacterClassRange::Single(cp) => {
ranges.push(CharRange { start: *cp, end: *cp });
@@ -1617,12 +1617,12 @@ impl Compiler {
ClassSetOperand::UnicodeProperty(up) => {
if self.program.unicode_sets
&& !up.negated
- && libunicode_rust::character_types::is_string_property(&up.name)
+ && libunicode_rust::character_types::is_string_property(up.name)
{
if length == 1 {
- self.emit_unicode_property(up.negated, &up.name, up.value.as_deref());
+ self.emit_unicode_property(up.negated, up.name, up.value);
} else {
- let strings = Self::get_string_property_strings_of_length(&up.name, length);
+ let strings = Self::get_string_property_strings_of_length(up.name, length);
if strings.is_empty() {
self.emit(Instruction::Fail);
return;
@@ -1635,7 +1635,7 @@ impl Compiler {
self.emit(Instruction::Fail);
return;
}
- self.emit_unicode_property(up.negated, &up.name, up.value.as_deref());
+ self.emit_unicode_property(up.negated, up.name, up.value);
}
ClassSetOperand::StringLiteral(chars) => {
if chars.len() != length {
diff --git a/Libraries/LibRegex/Rust/src/ffi.rs b/Libraries/LibRegex/Rust/src/ffi.rs
index 566f9646cd7..0cb6f498daf 100644
--- a/Libraries/LibRegex/Rust/src/ffi.rs
+++ b/Libraries/LibRegex/Rust/src/ffi.rs
@@ -28,8 +28,8 @@ pub struct RustRegexFlags {
}
fn compile_pattern(
- pattern: Vec<char>,
flags: RustRegexFlags,
+ compile: impl FnOnce(Flags) -> Result<Regex, String>,
error_out: *mut *const u8,
error_len_out: *mut usize,
) -> *mut RustRegex {
@@ -44,11 +44,10 @@ fn compile_pattern(
has_indices: flags.has_indices,
};
- match Regex::compile_chars(pattern, flags) {
+ match compile(flags) {
Ok(regex) => Box::into_raw(Box::new(RustRegex(regex))),
- Err(e) => {
+ Err(msg) => {
if !error_out.is_null() && !error_len_out.is_null() {
- let msg = e.to_string();
let leaked = msg.into_boxed_str();
unsafe {
*error_len_out = leaked.len();
@@ -80,11 +79,12 @@ pub unsafe extern "C" fn rust_regex_compile(
}
let code_units = unsafe { ak::slice_from_raw_parts(pattern, pattern_len) };
- let pattern = char::decode_utf16(code_units.iter().copied())
- .map(|result| result.unwrap_or(char::REPLACEMENT_CHARACTER))
- .collect();
-
- compile_pattern(pattern, flags, error_out, error_len_out)
+ compile_pattern(
+ flags,
+ |flags| Regex::compile_utf16(code_units, flags, |error| error.to_string()),
+ error_out,
+ error_len_out,
+ )
}
/// Compile a regex pattern of Latin-1 code units. Returns an opaque handle, or null on error.
@@ -107,9 +107,12 @@ pub unsafe extern "C" fn rust_regex_compile_latin1(
}
let bytes = unsafe { ak::slice_from_raw_parts(pattern, pattern_len) };
- let pattern = bytes.iter().map(|byte| *byte as char).collect();
-
- compile_pattern(pattern, flags, error_out, error_len_out)
+ compile_pattern(
+ flags,
+ |flags| Regex::compile_latin1(bytes, flags, |error| error.to_string()),
+ error_out,
+ error_len_out,
+ )
}
/// Free an error string returned by `rust_regex_compile`.
diff --git a/Libraries/LibRegex/Rust/src/lib.rs b/Libraries/LibRegex/Rust/src/lib.rs
index 2721a61de10..ff65cfd7bdc 100644
--- a/Libraries/LibRegex/Rust/src/lib.rs
+++ b/Libraries/LibRegex/Rust/src/lib.rs
@@ -21,3 +21,4 @@ pub mod parser;
pub mod regex;
mod stack;
pub mod vm;
+mod work_zone;
diff --git a/Libraries/LibRegex/Rust/src/parser.rs b/Libraries/LibRegex/Rust/src/parser.rs
index ccfbefdd7fe..0176135aaab 100644
--- a/Libraries/LibRegex/Rust/src/parser.rs
+++ b/Libraries/LibRegex/Rust/src/parser.rs
@@ -6,11 +6,18 @@
//! ECMA-262 regular expression parser.
//!
-//! Parses a regex pattern string into an [`ast::Pattern`].
+//! Parses a regex pattern string into an [`ast::Pattern`], which it builds in a zone with all of its own work data.
//!
//! Spec:
//! - <https://tc39.es/ecma262/#sec-patterns>
//! - <https://tc39.es/ecma262/#sec-parsepattern>
+use core::cmp::Reverse;
+use core::fmt;
+
+use ak::Zone;
+use ak::ZoneMap;
+use ak::ZoneVec;
+
use crate::ast::*;
const MAX_BRACED_QUANTIFIER: u32 = i32::MAX as u32;
@@ -19,16 +26,13 @@ const MAX_BRACED_QUANTIFIER: u32 = i32::MAX as u32;
///
/// Spec entry point: `ParsePattern`.
/// <https://tc39.es/ecma262/#sec-parsepattern>
-pub fn parse(source: &str, flags: Flags) -> Result<Pattern, Error> {
- Parser::new(source, flags).parse()
-}
-
-pub fn parse_chars(source: Vec<char>, flags: Flags) -> Result<Pattern, Error> {
- Parser::new_from_chars(source, flags).parse()
+/// The tree, its names and the error are in `zone`.
+pub fn parse<'z>(zone: &'z Zone, source: &'z [char], flags: Flags) -> Result<Pattern<'z>, Error<'z>> {
+ Parser::new(zone, source, flags).parse()
}
/// Parse a flags string like `"gimsu"` into [`Flags`].
-pub fn parse_flags(s: &str) -> Result<Flags, Error> {
+pub fn parse_flags(s: &str) -> Result<Flags, Error<'_>> {
let mut flags = Flags::default();
for ch in s.chars() {
match ch {
@@ -40,29 +44,29 @@ pub fn parse_flags(s: &str) -> Result<Flags, Error> {
'v' if !flags.unicode_sets && !flags.unicode => flags.unicode_sets = true,
'y' if !flags.sticky => flags.sticky = true,
'd' if !flags.has_indices => flags.has_indices = true,
- _ => return Err(Error::InvalidFlags(s.to_string())),
+ _ => return Err(Error::InvalidFlags(s)),
}
}
Ok(flags)
}
-/// A parser error with a position in the source string.
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub enum Error {
+/// A parser error. The names it has are in the zone of the parse.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Error<'z> {
UnexpectedEnd,
UnexpectedChar(char),
InvalidEscape(char),
- InvalidFlags(String),
+ InvalidFlags(&'z str),
InvalidQuantifier,
InvalidCharacterClass,
InvalidCharacterRange(u32, u32),
InvalidUnicodeEscape,
- InvalidUnicodeProperty(String),
+ InvalidUnicodeProperty(&'z str),
InvalidBackreference(u32),
- InvalidNamedBackreference(String),
+ InvalidNamedBackreference(&'z str),
InvalidGroupName,
InvalidModifierFlags,
- DuplicateGroupName(String),
+ DuplicateGroupName(&'z str),
DuplicateFlag(char),
LoneTrailingBackslash,
UnmatchedParen,
@@ -72,8 +76,8 @@ pub enum Error {
TooDeeplyNested,
}
-impl std::fmt::Display for Error {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+impl fmt::Display for Error<'_> {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::UnexpectedEnd => write!(f, "unexpected end of pattern"),
Self::UnexpectedChar(c) => write!(f, "unexpected character '{c}'"),
@@ -82,9 +86,7 @@ impl std::fmt::Display for Error {
Self::InvalidQuantifier => write!(f, "invalid quantifier"),
Self::InvalidCharacterClass => write!(f, "invalid character class"),
Self::InvalidCharacterRange(lo, hi) => {
- let lo_str = char::from_u32(*lo).map_or_else(|| format!("\\u{{{lo:04X}}}"), |c| format!("{c}"));
- let hi_str = char::from_u32(*hi).map_or_else(|| format!("\\u{{{hi:04X}}}"), |c| format!("{c}"));
- write!(f, "invalid character range '{lo_str}'-'{hi_str}'")
+ write!(f, "invalid character range '{}'-'{}'", RangeEnd(*lo), RangeEnd(*hi))
}
Self::InvalidUnicodeEscape => write!(f, "invalid Unicode escape"),
Self::InvalidUnicodeProperty(p) => write!(f, "invalid Unicode property '{p}'"),
@@ -106,11 +108,25 @@ impl std::fmt::Display for Error {
}
}
-impl std::error::Error for Error {}
+impl core::error::Error for Error<'_> {}
+
+/// An end of a character range in an error: the character, or its code point for a lone surrogate.
+struct RangeEnd(u32);
+
+impl fmt::Display for RangeEnd {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match char::from_u32(self.0) {
+ Some(c) => write!(f, "{c}"),
+ None => write!(f, "\\u{{{:04X}}}", self.0),
+ }
+ }
+}
-struct Parser {
+struct Parser<'z> {
+ /// The zone that the tree and the work data of the parse go in.
+ zone: &'z Zone,
/// Source pattern as chars for easy random access.
- source: Vec<char>,
+ source: &'z [char],
/// Current position in `source`.
pos: usize,
/// Parsed flags.
@@ -122,31 +138,31 @@ struct Parser {
/// Whether any named groups exist in the pattern (from pre-scan).
has_any_named_groups: bool,
/// Named capture groups seen so far.
- named_groups: Vec<NamedGroup>,
- /// Stack of name sets for duplicate detection across alternatives.
- /// Each entry is the set of names used in the current alternative
- /// at that disjunction nesting level.
- alternative_name_stack: Vec<std::collections::HashSet<String>>,
+ named_groups: ZoneVec<'z, NamedGroup<'z>>,
+ /// The names of the named groups seen so far, in order, for duplicate detection across alternatives. A name is
+ /// visible to the groups after it unless an alternative of a disjunction that holds it has ended and the
+ /// disjunction has not: a name may repeat in another alternative of the same disjunction.
+ group_names: ZoneVec<'z, &'z str>,
+ /// For each group name seen so far, how many of the names in `group_names` with it are visible.
+ visible_group_names: ZoneMap<'z, &'z str, u32>,
/// True when parsing inside a negated character class (`[^...]`).
in_negated_class: bool,
}
-impl Parser {
- fn new(source: &str, flags: Flags) -> Self {
- Self::new_from_chars(source.chars().collect(), flags)
- }
-
- fn new_from_chars(chars: Vec<char>, flags: Flags) -> Self {
- let (total, has_named) = Self::prescan_captures(&chars);
+impl<'z> Parser<'z> {
+ fn new(zone: &'z Zone, source: &'z [char], flags: Flags) -> Self {
+ let (total, has_named) = Self::prescan_captures(source);
Self {
- source: chars,
+ zone,
+ source,
pos: 0,
flags,
next_capture_index: 1,
total_capture_count: total,
has_any_named_groups: has_named,
- named_groups: Vec::new(),
- alternative_name_stack: Vec::new(),
+ named_groups: ZoneVec::new_in(zone),
+ group_names: ZoneVec::new_in(zone),
+ visible_group_names: ZoneMap::new_in(zone),
in_negated_class: false,
}
}
@@ -194,7 +210,7 @@ impl Parser {
(count, has_named)
}
- fn parse(mut self) -> Result<Pattern, Error> {
+ fn parse(mut self) -> Result<Pattern<'z>, Error<'z>> {
let disjunction = self.parse_disjunction()?;
if self.pos < self.source.len() {
return Err(Error::UnexpectedChar(self.source[self.pos]));
@@ -202,34 +218,34 @@ impl Parser {
// Named backreferences can point forward, so validate them only after
// the whole pattern has been parsed and every group name is known.
- let group_names: std::collections::HashSet<&str> = self.named_groups.iter().map(|g| g.name.as_str()).collect();
- Self::validate_backrefs(&disjunction, &group_names)?;
+ self.validate_backrefs(&disjunction)?;
Ok(Pattern {
disjunction,
flags: self.flags,
capture_count: self.next_capture_index - 1,
- named_groups: self.named_groups,
+ named_groups: self.named_groups.into_slice(),
})
}
/// Apply the named-backreference early error after all group names have
/// been collected.
/// <https://tc39.es/ecma262/#sec-patterns-static-semantics-early-errors>
- fn validate_backrefs(disj: &Disjunction, group_names: &std::collections::HashSet<&str>) -> Result<(), Error> {
+ fn validate_backrefs(&self, disj: &Disjunction<'z>) -> Result<(), Error<'z>> {
if crate::stack::is_exhausted() {
return Err(Error::TooDeeplyNested);
}
- for alt in &disj.alternatives {
- for term in &alt.terms {
+ for alt in disj.alternatives {
+ for term in alt.terms {
match &term.atom {
- Atom::Backreference(Backreference::Named(name)) if !group_names.contains(name.as_str()) => {
- return Err(Error::InvalidNamedBackreference(name.clone()));
+ // NB: Each group name that was seen has an entry, visible or not.
+ Atom::Backreference(Backreference::Named(name)) if !self.visible_group_names.contains_key(name) => {
+ return Err(Error::InvalidNamedBackreference(name));
}
- Atom::Group(g) => Self::validate_backrefs(&g.body, group_names)?,
- Atom::NonCapturingGroup(g) => Self::validate_backrefs(&g.body, group_names)?,
- Atom::Lookaround(la) => Self::validate_backrefs(&la.body, group_names)?,
- Atom::ModifierGroup(mg) => Self::validate_backrefs(&mg.body, group_names)?,
+ Atom::Group(g) => self.validate_backrefs(&g.body)?,
+ Atom::NonCapturingGroup(g) => self.validate_backrefs(&g.body)?,
+ Atom::Lookaround(la) => self.validate_backrefs(&la.body)?,
+ Atom::ModifierGroup(mg) => self.validate_backrefs(&mg.body)?,
_ => {}
}
}
@@ -264,7 +280,7 @@ impl Parser {
}
}
- fn expect(&mut self, expected: char) -> Result<(), Error> {
+ fn expect(&mut self, expected: char) -> Result<(), Error<'z>> {
if self.eat(expected) {
Ok(())
} else {
@@ -290,34 +306,46 @@ impl Parser {
/// Parse `Disjunction`.
/// <https://tc39.es/ecma262/#sec-patterns>
- fn parse_disjunction(&mut self) -> Result<Disjunction, Error> {
+ fn parse_disjunction(&mut self) -> Result<Disjunction<'z>, Error<'z>> {
if crate::stack::is_exhausted() {
return Err(Error::TooDeeplyNested);
}
- let inherited = self.alternative_name_stack.last().cloned().unwrap_or_default();
- self.alternative_name_stack.push(inherited.clone());
- let mut alternatives = vec![self.parse_alternative()?];
+ // The group names of this disjunction start here. Those before `first_visible_name` are in alternatives that
+ // have ended, so the alternative that is parsed does not see them.
+ let first_name = self.group_names.len();
+ let mut first_visible_name = first_name;
+ let mut alternatives = ZoneVec::new_in(self.zone);
+ alternatives.push(self.parse_alternative()?);
while self.eat('|') {
- // Merge names from the just finished alternative into the parent scope so
- // parent knows these names exist and can reject duplicates from enclosing alternatives
- let committed = self.alternative_name_stack.last().cloned().unwrap_or_default();
- if let Some(outer) = self.alternative_name_stack.iter_mut().rev().nth(1) {
- outer.extend(committed.iter().cloned());
- }
-
- // Reset to only the names from outer scopes so the next alternative only sees
+ // Hide the names of the just finished alternative so the next alternative only sees
// names from outer scopes and not from its siblings
- if let Some(top) = self.alternative_name_stack.last_mut() {
- *top = inherited.clone();
+ for index in first_visible_name..self.group_names.len() {
+ self.change_group_name_visibility(index, false);
}
+ first_visible_name = self.group_names.len();
alternatives.push(self.parse_alternative()?);
}
- let final_names = self.alternative_name_stack.pop().unwrap_or_default();
- if let Some(outer) = self.alternative_name_stack.last_mut() {
- outer.extend(final_names.into_iter().filter(|n| !inherited.contains(n)));
+ // Show the names of all the alternatives again so the enclosing alternatives
+ // can reject duplicates of them
+ for index in first_name..first_visible_name {
+ self.change_group_name_visibility(index, true);
+ }
+ Ok(Disjunction {
+ alternatives: alternatives.into_slice(),
+ })
+ }
+
+ fn change_group_name_visibility(&mut self, index: usize, visible: bool) {
+ let count = self
+ .visible_group_names
+ .get_mut(&self.group_names[index])
+ .expect("each group name that was seen has an entry");
+ if visible {
+ *count += 1;
+ } else {
+ *count -= 1;
}
- Ok(Disjunction { alternatives })
}
// ---------------------------------------------------------------
@@ -326,12 +354,14 @@ impl Parser {
/// Parse `Alternative`.
/// <https://tc39.es/ecma262/#sec-patterns>
- fn parse_alternative(&mut self) -> Result<Alternative, Error> {
- let mut terms = Vec::new();
+ fn parse_alternative(&mut self) -> Result<Alternative<'z>, Error<'z>> {
+ let mut terms = ZoneVec::new_in(self.zone);
while let Some(term) = self.try_parse_term()? {
terms.push(term);
}
- Ok(Alternative { terms })
+ Ok(Alternative {
+ terms: terms.into_slice(),
+ })
}
// ---------------------------------------------------------------
@@ -340,7 +370,7 @@ impl Parser {
/// Parse `Term`, including its optional trailing quantifier.
/// <https://tc39.es/ecma262/#sec-compilesubpattern>
- fn try_parse_term(&mut self) -> Result<Option<Term>, Error> {
+ fn try_parse_term(&mut self) -> Result<Option<Term<'z>>, Error<'z>> {
let Some(atom) = self.try_parse_atom()? else {
return Ok(None);
};
@@ -384,7 +414,7 @@ impl Parser {
/// Parse `Quantifier`.
/// <https://tc39.es/ecma262/#sec-compilequantifier>
- fn try_parse_quantifier(&mut self) -> Result<Option<Quantifier>, Error> {
+ fn try_parse_quantifier(&mut self) -> Result<Option<Quantifier>, Error<'z>> {
let Some(ch) = self.peek() else {
return Ok(None);
};
@@ -421,7 +451,7 @@ impl Parser {
/// Try to parse `{n}`, `{n,}`, or `{n,m}`.
/// Returns `None` if the `{...}` isn't a valid quantifier (in which case
/// the `{` is treated as a literal in non-unicode mode).
- fn try_parse_braced_quantifier(&mut self) -> Result<Option<Quantifier>, Error> {
+ fn try_parse_braced_quantifier(&mut self) -> Result<Option<Quantifier>, Error<'z>> {
let start = self.pos;
self.pos += 1; // skip '{'
@@ -468,7 +498,7 @@ impl Parser {
/// - `Ok(Some(n))` if a valid u32 was parsed
///
/// Clamp braced quantifier bounds to 2^31 - 1 to match browser behavior.
- fn try_parse_decimal(&mut self) -> Result<Option<u32>, Error> {
+ fn try_parse_decimal(&mut self) -> Result<Option<u32>, Error<'z>> {
let start = self.pos;
let mut value: u32 = 0;
while let Some(ch) = self.peek() {
@@ -490,7 +520,7 @@ impl Parser {
/// Parse an `Atom`, `Assertion`, or literal source character.
/// - <https://tc39.es/ecma262/#sec-compileatom>
/// - <https://tc39.es/ecma262/#sec-compileassertion>
- fn try_parse_atom(&mut self) -> Result<Option<Atom>, Error> {
+ fn try_parse_atom(&mut self) -> Result<Option<Atom<'z>>, Error<'z>> {
let Some(ch) = self.peek() else {
return Ok(None);
};
@@ -580,7 +610,7 @@ impl Parser {
/// Parse `AtomEscape`.
/// <https://tc39.es/ecma262/#sec-compileatom>
- fn parse_atom_escape(&mut self) -> Result<Atom, Error> {
+ fn parse_atom_escape(&mut self) -> Result<Atom<'z>, Error<'z>> {
self.expect('\\')?;
let ch = self.advance().ok_or(Error::LoneTrailingBackslash)?;
@@ -603,7 +633,7 @@ impl Parser {
let prop = self.parse_unicode_property()?;
// String properties (e.g. Basic_Emoji) are only valid with /v flag,
// and cannot be negated with \P.
- if prop.1.is_none() && Self::is_string_property(&prop.0) {
+ if prop.1.is_none() && Self::is_string_property(prop.0) {
if !self.flags.unicode_sets {
return Err(Error::InvalidUnicodeProperty(prop.0));
}
@@ -807,7 +837,7 @@ impl Parser {
/// Parse a Unicode property escape payload.
/// - <https://tc39.es/ecma262/#sec-runtime-semantics-unicodematchproperty-p>
/// - <https://tc39.es/ecma262/#sec-runtime-semantics-unicodematchpropertyvalue-p-v>
- fn parse_unicode_property(&mut self) -> Result<(String, Option<String>), Error> {
+ fn parse_unicode_property(&mut self) -> Result<(&'z str, Option<&'z str>), Error<'z>> {
self.expect('{')?;
let name = self.parse_unicode_property_name()?;
let value = if self.eat('=') {
@@ -819,7 +849,7 @@ impl Parser {
// Validate against the ECMA-262 allow-list up front so later compiler
// and VM stages can assume the escape names already match spec.
- if !libunicode_rust::character_types::is_valid_ecma262_property(&name, value.as_deref()) {
+ if !libunicode_rust::character_types::is_valid_ecma262_property(name, value) {
return Err(Error::InvalidUnicodeProperty(name));
}
@@ -831,27 +861,27 @@ impl Parser {
libunicode_rust::character_types::is_string_property(name)
}
- fn parse_unicode_property_name(&mut self) -> Result<String, Error> {
- let mut name = String::new();
+ fn parse_unicode_property_name(&mut self) -> Result<&'z str, Error<'z>> {
+ let mut name = ZoneVec::new_in(self.zone);
while let Some(ch) = self.peek() {
if ch.is_ascii_alphanumeric() || ch == '_' {
- name.push(ch);
+ push_utf8(&mut name, ch);
self.advance();
} else {
break;
}
}
if name.is_empty() {
- return Err(Error::InvalidUnicodeProperty(String::new()));
+ return Err(Error::InvalidUnicodeProperty(""));
}
- Ok(name)
+ Ok(core::str::from_utf8(name.into_slice()).expect("the name is made of chars"))
}
// ---------------------------------------------------------------
// Hex/Unicode escapes
// ---------------------------------------------------------------
- fn parse_hex_escape(&mut self, digits: usize) -> Result<u32, Error> {
+ fn parse_hex_escape(&mut self, digits: usize) -> Result<u32, Error<'z>> {
let mut value: u32 = 0;
for _ in 0..digits {
let ch = self.advance().ok_or(Error::InvalidUnicodeEscape)?;
@@ -861,7 +891,7 @@ impl Parser {
Ok(value)
}
- fn parse_unicode_escape(&mut self) -> Result<u32, Error> {
+ fn parse_unicode_escape(&mut self) -> Result<u32, Error<'z>> {
if self.eat('{') {
// \u{HHHH...} — variable length, unicode mode.
if !self.unicode_aware() {
@@ -920,7 +950,7 @@ impl Parser {
/// modifier groups.
/// - <https://tc39.es/ecma262/#sec-compileatom>
/// - <https://tc39.es/ecma262/#sec-patterns-static-semantics-early-errors>
- fn parse_group(&mut self) -> Result<Atom, Error> {
+ fn parse_group(&mut self) -> Result<Atom<'z>, Error<'z>> {
self.expect('(')?;
if self.eat('?') {
@@ -977,20 +1007,15 @@ impl Parser {
// Duplicate names are allowed across alternatives of
// the same disjunction, but not within the same
// alternative.
- if let Some(current_alt_names) = self.alternative_name_stack.last()
- && current_alt_names.contains(&name)
- {
+ let visible_count = self.visible_group_names.entry(name).or_insert(0);
+ if *visible_count > 0 {
return Err(Error::DuplicateGroupName(name));
}
+ *visible_count += 1;
+ self.group_names.push(name);
let index = self.next_capture_index;
self.next_capture_index += 1;
- if let Some(top) = self.alternative_name_stack.last_mut() {
- top.insert(name.clone());
- }
- self.named_groups.push(NamedGroup {
- name: name.clone(),
- index,
- });
+ self.named_groups.push(NamedGroup { name, index });
let body = self.parse_disjunction()?;
self.expect(')')?;
Ok(Atom::Group(Group {
@@ -1032,13 +1057,13 @@ impl Parser {
/// Parse `RegExpIdentifierName` inside `(?<name>...)` and `\k<name>`.
/// <https://tc39.es/ecma262/#sec-patterns>
- fn parse_group_name(&mut self) -> Result<String, Error> {
- let mut name = String::new();
+ fn parse_group_name(&mut self) -> Result<&'z str, Error<'z>> {
+ let mut name = ZoneVec::new_in(self.zone);
let first = self.parse_group_name_char()?;
if !is_identifier_start_char(first) {
return Err(Error::InvalidGroupName);
}
- name.push(first);
+ push_utf8(&mut name, first);
while let Some(ch) = self.peek() {
if ch == '>' {
break;
@@ -1047,13 +1072,13 @@ impl Parser {
if !is_identifier_continue_char(ch) {
return Err(Error::InvalidGroupName);
}
- name.push(ch);
+ push_utf8(&mut name, ch);
}
- Ok(name)
+ Ok(core::str::from_utf8(name.into_slice()).expect("the name is made of chars"))
}
/// Parse a single character in a group name, handling \u escapes.
- fn parse_group_name_char(&mut self) -> Result<char, Error> {
+ fn parse_group_name_char(&mut self) -> Result<char, Error<'z>> {
let ch = self.advance().ok_or(Error::InvalidGroupName)?;
if ch == '\\' {
if self.eat('u') {
@@ -1085,7 +1110,7 @@ impl Parser {
}
/// Parse \uXXXX or \u{XXXX} in a group name context.
- fn parse_unicode_escape_in_name(&mut self) -> Result<u32, Error> {
+ fn parse_unicode_escape_in_name(&mut self) -> Result<u32, Error<'z>> {
if self.eat('{') {
// \u{XXXX}
let mut val = 0u32;
@@ -1120,7 +1145,7 @@ impl Parser {
/// Parse the flag delta in a modifier group before `UpdateModifiers`
/// applies it to the enclosed disjunction.
/// <https://tc39.es/ecma262/#sec-updatemodifiers>
- fn parse_modifier_flags(&mut self) -> Result<(ModifierFlags, ModifierFlags), Error> {
+ fn parse_modifier_flags(&mut self) -> Result<(ModifierFlags, ModifierFlags), Error<'z>> {
let mut add = ModifierFlags::default();
let mut removing = false;
let mut remove = ModifierFlags::default();
@@ -1181,7 +1206,7 @@ impl Parser {
/// Parse `CharacterClass`.
/// <https://tc39.es/ecma262/#sec-compilecharacterclass>
- fn parse_character_class(&mut self) -> Result<CharacterClass, Error> {
+ fn parse_character_class(&mut self) -> Result<CharacterClass<'z>, Error<'z>> {
if crate::stack::is_exhausted() {
return Err(Error::TooDeeplyNested);
}
@@ -1195,7 +1220,7 @@ impl Parser {
// while parsing nested class-set operands.
self.in_negated_class = negated;
let expr = if self.peek() == Some(']') {
- ClassSetExpression::Union(Vec::new())
+ ClassSetExpression::Union(&[])
} else {
self.parse_class_set_expression()?
};
@@ -1221,8 +1246,8 @@ impl Parser {
/// Parse the legacy and `/u` `ClassContents` forms that flatten into ranges
/// and single atoms.
/// <https://tc39.es/ecma262/#sec-compiletocharset>
- fn parse_class_ranges(&mut self) -> Result<Vec<CharacterClassRange>, Error> {
- let mut ranges = Vec::new();
+ fn parse_class_ranges(&mut self) -> Result<&'z [CharacterClassRange<'z>], Error<'z>> {
+ let mut ranges = ZoneVec::new_in(self.zone);
while self.peek() != Some(']') && !self.at_end() {
let first = self.parse_class_atom()?;
if self.eat('-') {
@@ -1255,10 +1280,10 @@ impl Parser {
ranges.push(first);
}
}
- Ok(ranges)
+ Ok(ranges.into_slice())
}
- fn parse_class_atom(&mut self) -> Result<CharacterClassRange, Error> {
+ fn parse_class_atom(&mut self) -> Result<CharacterClassRange<'z>, Error<'z>> {
let ch = self.peek().ok_or(Error::InvalidCharacterClass)?;
match ch {
'\\' => self.parse_class_escape(),
@@ -1271,7 +1296,7 @@ impl Parser {
/// Parse `ClassEscape`.
/// <https://tc39.es/ecma262/#sec-compiletocharset>
- fn parse_class_escape(&mut self) -> Result<CharacterClassRange, Error> {
+ fn parse_class_escape(&mut self) -> Result<CharacterClassRange<'z>, Error<'z>> {
self.expect('\\')?;
let ch = self.advance().ok_or(Error::LoneTrailingBackslash)?;
match ch {
@@ -1285,7 +1310,7 @@ impl Parser {
let negated = ch == 'P';
let prop = self.parse_unicode_property()?;
// String properties are only valid with /v flag, not /u.
- if prop.1.is_none() && Self::is_string_property(&prop.0) {
+ if prop.1.is_none() && Self::is_string_property(prop.0) {
if !self.flags.unicode_sets {
return Err(Error::InvalidUnicodeProperty(prop.0));
}
@@ -1397,7 +1422,7 @@ impl Parser {
/// Parse `/v` `ClassSetExpression`.
/// <https://tc39.es/ecma262/#sec-compilecharacterclass>
- fn parse_class_set_expression(&mut self) -> Result<ClassSetExpression, Error> {
+ fn parse_class_set_expression(&mut self) -> Result<ClassSetExpression<'z>, Error<'z>> {
let saved_negated = self.in_negated_class;
self.in_negated_class = false;
let first = self.parse_class_set_operand()?;
@@ -1413,7 +1438,8 @@ impl Parser {
if saved_negated {
Self::validate_no_string_operand(&first)?;
}
- let mut operands = vec![first];
+ let mut operands = ZoneVec::new_in(self.zone);
+ operands.push(first);
self.in_negated_class = false;
while self.peek_pair() == Some(('-', '-')) {
self.pos += 2; // consume '--'
@@ -1421,13 +1447,14 @@ impl Parser {
}
self.in_negated_class = saved_negated;
Self::validate_class_set_operation_operands(&operands)?;
- Ok(ClassSetExpression::Subtraction(operands))
+ Ok(ClassSetExpression::Subtraction(operands.into_slice()))
}
Some(('&', '&')) => {
// Same idea as subtraction above: a single expression level is
// either an intersection chain or something else, never both.
// Intersection: A&&B&&C
- let mut operands = vec![first];
+ let mut operands = ZoneVec::new_in(self.zone);
+ operands.push(first);
self.in_negated_class = false;
while self.peek_pair() == Some(('&', '&')) {
self.pos += 2; // consume '&&'
@@ -1438,33 +1465,34 @@ impl Parser {
}
self.in_negated_class = saved_negated;
Self::validate_class_set_operation_operands(&operands)?;
- Ok(ClassSetExpression::Intersection(operands))
+ Ok(ClassSetExpression::Intersection(operands.into_slice()))
}
_ => {
// Union (default): direct members of [^...] may not be string properties.
if saved_negated {
Self::validate_no_string_operand(&first)?;
}
- let mut operands = vec![first];
+ let mut operands = ZoneVec::new_in(self.zone);
+ operands.push(first);
while self.peek() != Some(']') && !self.at_end() {
operands.push(self.parse_class_set_operand()?);
}
- Ok(ClassSetExpression::Union(operands))
+ Ok(ClassSetExpression::Union(operands.into_slice()))
}
}
}
- fn validate_no_string_operand(operand: &ClassSetOperand) -> Result<(), Error> {
+ fn validate_no_string_operand(operand: &ClassSetOperand<'z>) -> Result<(), Error<'z>> {
if let ClassSetOperand::UnicodeProperty(up) = operand
&& !up.negated
- && Self::is_string_property(&up.name)
+ && Self::is_string_property(up.name)
{
- return Err(Error::InvalidUnicodeProperty(up.name.clone()));
+ return Err(Error::InvalidUnicodeProperty(up.name));
}
Ok(())
}
- fn validate_class_set_operation_operands(operands: &[ClassSetOperand]) -> Result<(), Error> {
+ fn validate_class_set_operation_operands(operands: &[ClassSetOperand<'z>]) -> Result<(), Error<'z>> {
if operands
.iter()
.any(|operand| matches!(operand, ClassSetOperand::Range(_, _)))
@@ -1479,13 +1507,13 @@ impl Parser {
/// - Intersection: may contain strings if ALL operands may contain strings
/// (i.e., no operand is "purely characters")
/// - Subtraction: may contain strings if the leftmost operand may contain strings
- fn class_set_expression_may_contain_strings(expr: &ClassSetExpression) -> Result<bool, Error> {
+ fn class_set_expression_may_contain_strings(expr: &ClassSetExpression<'z>) -> Result<bool, Error<'z>> {
if crate::stack::is_exhausted() {
return Err(Error::TooDeeplyNested);
}
match expr {
ClassSetExpression::Union(operands) => {
- for operand in operands {
+ for operand in *operands {
if Self::class_set_operand_may_contain_strings(operand)? {
return Ok(true);
}
@@ -1493,7 +1521,7 @@ impl Parser {
Ok(false)
}
ClassSetExpression::Intersection(operands) => {
- for operand in operands {
+ for operand in *operands {
if !Self::class_set_operand_may_contain_strings(operand)? {
return Ok(false);
}
@@ -1507,7 +1535,7 @@ impl Parser {
}
}
- fn class_set_operand_may_contain_strings(operand: &ClassSetOperand) -> Result<bool, Error> {
+ fn class_set_operand_may_contain_strings(operand: &ClassSetOperand<'z>) -> Result<bool, Error<'z>> {
Ok(match operand {
ClassSetOperand::NestedClass(class) => {
if class.negated {
@@ -1519,7 +1547,7 @@ impl Parser {
}
}
ClassSetOperand::UnicodeProperty(property) => {
- !property.negated && property.value.is_none() && Self::is_string_property(&property.name)
+ !property.negated && property.value.is_none() && Self::is_string_property(property.name)
}
ClassSetOperand::StringLiteral(chars) => chars.len() != 1,
ClassSetOperand::Char(_) | ClassSetOperand::Range(_, _) | ClassSetOperand::BuiltinClass(_) => false,
@@ -1529,7 +1557,7 @@ impl Parser {
/// Parse one `/v` `ClassSetOperand`.
/// - <https://tc39.es/ecma262/#sec-patterns>
/// - <https://tc39.es/ecma262/#sec-compileclasssetstring>
- fn parse_class_set_operand(&mut self) -> Result<ClassSetOperand, Error> {
+ fn parse_class_set_operand(&mut self) -> Result<ClassSetOperand<'z>, Error<'z>> {
let ch = self.peek().ok_or(Error::InvalidCharacterClass)?;
match ch {
'[' => {
@@ -1543,12 +1571,12 @@ impl Parser {
'q' => {
self.advance();
self.expect('{')?;
- let mut alternatives: Vec<Vec<char>> = Vec::new();
- let mut current = Vec::new();
+ let mut alternatives: ZoneVec<&'z [char]> = ZoneVec::new_in(self.zone);
+ let mut current = ZoneVec::new_in(self.zone);
while self.peek() != Some('}') && !self.at_end() {
let c = self.advance().ok_or(Error::UnexpectedEnd)?;
if c == '|' {
- alternatives.push(std::mem::take(&mut current));
+ alternatives.push(current.take().into_slice());
} else if matches!(c, '(' | ')' | '[' | ']' | '{' | '}' | '/' | '-') {
return Err(Error::InvalidCharacterClass);
} else if c == '\\' {
@@ -1559,7 +1587,7 @@ impl Parser {
current.push(c);
}
}
- alternatives.push(current);
+ alternatives.push(current.into_slice());
self.expect('}')?;
// In a negated class, \q{} may not contain multi-char strings.
@@ -1568,13 +1596,16 @@ impl Parser {
}
if alternatives.len() == 1 {
- Ok(ClassSetOperand::StringLiteral(alternatives.into_iter().next().unwrap()))
+ Ok(ClassSetOperand::StringLiteral(alternatives[0]))
} else {
// Multiple alternatives: wrap as a nested class with Union body.
// Sort longest-first so greedy matching prefers longer alternatives.
- alternatives.sort_by_key(|b| std::cmp::Reverse(b.len()));
- let operands: Vec<ClassSetOperand> =
- alternatives.into_iter().map(ClassSetOperand::StringLiteral).collect();
+ // Alternatives of the same length keep their order.
+ let mut sorted = ZoneVec::from_iter_in(alternatives.iter().copied().enumerate(), self.zone);
+ sorted.sort_unstable_by_key(|(index, chars)| (Reverse(chars.len()), *index));
+ let operands = self.zone.alloc_slice_from_iter(
+ sorted.iter().map(|(_, chars)| ClassSetOperand::StringLiteral(chars)),
+ );
Ok(ClassSetOperand::NestedClass(CharacterClass {
negated: false,
body: CharacterClassBody::UnicodeSet(ClassSetExpression::Union(operands)),
@@ -1611,7 +1642,7 @@ impl Parser {
let prop = self.parse_unicode_property()?;
// In v-mode, \P{string-property} is always forbidden.
// The [^...] negation check is handled at the expression level.
- if prop.1.is_none() && Self::is_string_property(&prop.0) && negated {
+ if prop.1.is_none() && Self::is_string_property(prop.0) && negated {
return Err(Error::InvalidUnicodeProperty(prop.0));
}
Ok(ClassSetOperand::UnicodeProperty(UnicodeProperty {
@@ -1652,7 +1683,7 @@ impl Parser {
/// Parse the restricted escape forms allowed when a `/v` class set operand
/// expects a single character.
/// <https://tc39.es/ecma262/#sec-patterns>
- fn parse_class_set_char_escape(&mut self) -> Result<u32, Error> {
+ fn parse_class_set_char_escape(&mut self) -> Result<u32, Error<'z>> {
let ch = self.advance().ok_or(Error::LoneTrailingBackslash)?;
match ch {
'n' => Ok('\n' as u32),
@@ -1694,7 +1725,7 @@ impl Parser {
}
/// After reading a character in a unicode-sets class, check if it's followed by `-` to form a range.
- fn try_parse_class_set_range(&mut self, first: u32) -> Result<ClassSetOperand, Error> {
+ fn try_parse_class_set_range(&mut self, first: u32) -> Result<ClassSetOperand<'z>, Error<'z>> {
if self.eat('-') {
if self.peek() == Some(']') || self.peek() == Some('-') || self.peek_pair() == Some(('&', '&')) {
// `-]`, `--`, and `-&&` do not start a character range here.
@@ -1758,6 +1789,11 @@ fn is_class_set_reserved_double_punctuator_char(ch: char) -> bool {
)
}
+/// Appends the UTF-8 of `ch` to `text`.
+fn push_utf8(text: &mut ZoneVec<'_, u8>, ch: char) {
+ text.extend_from_slice(ch.encode_utf8(&mut [0; 4]).as_bytes());
+}
+
fn is_modifier_flag(ch: char) -> bool {
matches!(ch, 'i' | 'm' | 's')
}
@@ -1775,7 +1811,7 @@ fn is_identifier_continue_char(ch: char) -> bool {
}
/// Extract a single code point from a class atom, for use in ranges.
-fn class_atom_to_code_point(atom: &CharacterClassRange) -> Result<u32, Error> {
+fn class_atom_to_code_point<'z>(atom: &CharacterClassRange<'z>) -> Result<u32, Error<'z>> {
match atom {
CharacterClassRange::Single(cp) => Ok(*cp),
CharacterClassRange::BuiltinClass(_) | CharacterClassRange::UnicodeProperty(_) => {
diff --git a/Libraries/LibRegex/Rust/src/regex.rs b/Libraries/LibRegex/Rust/src/regex.rs
index 9e6383fcc49..99871a40c4c 100644
--- a/Libraries/LibRegex/Rust/src/regex.rs
+++ b/Libraries/LibRegex/Rust/src/regex.rs
@@ -19,6 +19,8 @@ use crate::bytecode::append_code_point_wtf16;
use crate::compiler;
use crate::parser;
use crate::vm;
+use crate::work_zone::with_work_zone;
+use ak::Zone;
use std::cell::RefCell;
use std::collections::HashSet;
@@ -40,18 +42,44 @@ pub struct Regex {
}
impl Regex {
- /// Compile a regex pattern with the given flags.
- pub fn compile(pattern: &str, flags: Flags) -> Result<Self, parser::Error> {
- let parsed = parser::parse(pattern, flags)?;
- Self::compile_parsed(parsed, flags)
+ /// Compile a regex pattern with the given flags. If it does not compile, the result is what `error` makes of the
+ /// parser error, which lives only for the call of `error`.
+ pub fn compile<E>(pattern: &str, flags: Flags, error: impl FnOnce(parser::Error<'_>) -> E) -> Result<Self, E> {
+ with_work_zone(|zone| {
+ let source = zone.alloc_slice_from_iter(pattern.chars());
+ Self::compile_in_zone(zone, source, flags).map_err(error)
+ })
}
- pub fn compile_chars(pattern: Vec<char>, flags: Flags) -> Result<Self, parser::Error> {
- let parsed = parser::parse_chars(pattern, flags)?;
- Self::compile_parsed(parsed, flags)
+ /// Compile a regex pattern of UTF-16 code units, in which a lone surrogate is U+FFFD (see `compile()`).
+ pub fn compile_utf16<E>(
+ pattern: &[u16],
+ flags: Flags,
+ error: impl FnOnce(parser::Error<'_>) -> E,
+ ) -> Result<Self, E> {
+ with_work_zone(|zone| {
+ let source = zone.alloc_slice_from_iter(
+ char::decode_utf16(pattern.iter().copied())
+ .map(|character| character.unwrap_or(char::REPLACEMENT_CHARACTER)),
+ );
+ Self::compile_in_zone(zone, source, flags).map_err(error)
+ })
+ }
+
+ /// Compile a regex pattern of Latin-1 code units (see `compile()`).
+ pub fn compile_latin1<E>(
+ pattern: &[u8],
+ flags: Flags,
+ error: impl FnOnce(parser::Error<'_>) -> E,
+ ) -> Result<Self, E> {
+ with_work_zone(|zone| {
+ let source = zone.alloc_slice_from_iter(pattern.iter().map(|byte| char::from(*byte)));
+ Self::compile_in_zone(zone, source, flags).map_err(error)
+ })
}
- fn compile_parsed(parsed: Pattern, flags: Flags) -> Result<Self, parser::Error> {
+ fn compile_in_zone<'z>(zone: &'z Zone, source: &'z [char], flags: Flags) -> Result<Self, parser::Error<'z>> {
+ let parsed = parser::parse(zone, source, flags)?;
let mut program = compiler::compile(&parsed)?;
Self::resolve_properties(&mut program);
let required_literal_hint = extract_required_literal_hint(&parsed, flags);
@@ -647,7 +675,7 @@ struct RequiredLiteralAnalysis {
guaranteed_runs: Vec<Vec<u16>>,
}
-fn extract_required_literal_hint(pattern: &Pattern, flags: Flags) -> Option<vm::RequiredLiteralHint> {
+fn extract_required_literal_hint(pattern: &Pattern<'_>, flags: Flags) -> Option<vm::RequiredLiteralHint> {
let analysis = analyze_required_literal_disjunction(&pattern.disjunction, flags);
let literal = analysis.guaranteed_runs.into_iter().max_by_key(|run| run.len())?;
if literal.is_empty() {
@@ -669,7 +697,7 @@ fn extract_required_literal_hint(pattern: &Pattern, flags: Flags) -> Option<vm::
})
}
-fn analyze_required_literal_disjunction(disjunction: &Disjunction, flags: Flags) -> RequiredLiteralAnalysis {
+fn analyze_required_literal_disjunction(disjunction: &Disjunction<'_>, flags: Flags) -> RequiredLiteralAnalysis {
if crate::stack::is_exhausted() {
return RequiredLiteralAnalysis {
exact_literal: None,
@@ -712,12 +740,12 @@ fn analyze_required_literal_disjunction(disjunction: &Disjunction, flags: Flags)
}
}
-fn analyze_required_literal_alternative(alternative: &Alternative, flags: Flags) -> RequiredLiteralAnalysis {
+fn analyze_required_literal_alternative(alternative: &Alternative<'_>, flags: Flags) -> RequiredLiteralAnalysis {
let mut exact_literal = Some(Vec::new());
let mut current_run = Vec::new();
let mut guaranteed_runs = Vec::new();
- for term in &alternative.terms {
+ for term in alternative.terms {
let term_analysis = analyze_required_literal_term(term, flags);
if let Some(literal) = term_analysis.exact_literal.as_deref() {
if let Some(exact) = exact_literal.as_mut() {
@@ -750,7 +778,7 @@ fn analyze_required_literal_alternative(alternative: &Alternative, flags: Flags)
}
}
-fn analyze_required_literal_term(term: &Term, flags: Flags) -> RequiredLiteralAnalysis {
+fn analyze_required_literal_term(term: &Term<'_>, flags: Flags) -> RequiredLiteralAnalysis {
let atom_analysis = analyze_required_literal_atom(&term.atom, flags);
let Some(quantifier) = &term.quantifier else {
return atom_analysis;
@@ -785,7 +813,7 @@ fn analyze_required_literal_term(term: &Term, flags: Flags) -> RequiredLiteralAn
}
}
-fn analyze_required_literal_atom(atom: &Atom, flags: Flags) -> RequiredLiteralAnalysis {
+fn analyze_required_literal_atom(atom: &Atom<'_>, flags: Flags) -> RequiredLiteralAnalysis {
match atom {
Atom::Literal(cp) => literal_required_literal_analysis(*cp, flags),
Atom::Group(group) => analyze_required_literal_disjunction(&group.body, flags),
@@ -928,7 +956,7 @@ fn contains_literal_subslice(haystack: &[u16], needle: &[u16]) -> bool {
haystack.windows(needle.len()).any(|window| window == needle)
}
-fn extract_literal_u16(pattern: &Pattern, flags: Flags) -> Option<Vec<u16>> {
+fn extract_literal_u16(pattern: &Pattern<'_>, flags: Flags) -> Option<Vec<u16>> {
if flags.ignore_case && (flags.unicode || flags.unicode_sets) {
return None;
}
@@ -938,7 +966,7 @@ fn extract_literal_u16(pattern: &Pattern, flags: Flags) -> Option<Vec<u16>> {
let alternative = &pattern.disjunction.alternatives[0];
let mut literal = Vec::new();
- for term in &alternative.terms {
+ for term in alternative.terms {
if term.quantifier.is_some() {
return None;
}
@@ -954,12 +982,12 @@ fn extract_literal_u16(pattern: &Pattern, flags: Flags) -> Option<Vec<u16>> {
Some(literal)
}
-fn extract_literal_alternatives_u16(pattern: &Pattern, flags: Flags) -> Option<Vec<Vec<u16>>> {
+fn extract_literal_alternatives_u16(pattern: &Pattern<'_>, flags: Flags) -> Option<Vec<Vec<u16>>> {
if flags.ignore_case && (flags.unicode || flags.unicode_sets) {
return None;
}
- let alternatives = &pattern.disjunction.alternatives;
+ let alternatives = pattern.disjunction.alternatives;
if alternatives.len() < 2 || pattern.capture_count > 0 {
return None;
}
@@ -967,7 +995,7 @@ fn extract_literal_alternatives_u16(pattern: &Pattern, flags: Flags) -> Option<V
let mut literal_alternatives = Vec::with_capacity(alternatives.len());
for alternative in alternatives {
let mut literal = Vec::new();
- for term in &alternative.terms {
+ for term in alternative.terms {
if term.quantifier.is_some() {
return None;
}
@@ -991,7 +1019,7 @@ fn extract_literal_alternatives_u16(pattern: &Pattern, flags: Flags) -> Option<V
Some(literal_alternatives)
}
-fn extract_word_boundary_literal_u16(pattern: &Pattern, flags: Flags) -> Option<Vec<u16>> {
+fn extract_word_boundary_literal_u16(pattern: &Pattern<'_>, flags: Flags) -> Option<Vec<u16>> {
if flags.unicode || flags.unicode_sets || pattern.capture_count > 0 {
return None;
}
@@ -999,7 +1027,7 @@ fn extract_word_boundary_literal_u16(pattern: &Pattern, flags: Flags) -> Option<
return None;
}
- let terms = &pattern.disjunction.alternatives[0].terms;
+ let terms = pattern.disjunction.alternatives[0].terms;
if terms.len() < 3 {
return None;
}
diff --git a/Libraries/LibRegex/Rust/src/work_zone.rs b/Libraries/LibRegex/Rust/src/work_zone.rs
new file mode 100644
index 00000000000..1db16ca4526
--- /dev/null
+++ b/Libraries/LibRegex/Rust/src/work_zone.rs
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The memory for the work data of a regex compile: the parse of the pattern and its compile to a program. A thread
+//! that compiles regexes has one zone, and each compile on the thread puts all of its work data in it. What a compile
+//! keeps is copied out of the zone before the compile ends, and the zone is empty again.
+//!
+//! The zone keeps its memory when a compile ends, for the next compile on the thread, so compiles take no memory from
+//! the system and give none back. An outsized compile 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 compile can take. It is address space, which costs nothing before it is
+/// used, and it is far above what the largest pattern takes.
+const LIMIT: usize = 1 << 34;
+
+/// The most bytes of memory that the zone keeps for the next compile. Nearly all patterns need far less.
+const MAXIMUM_SPARE_SIZE: usize = 1024 * 1024;
+
+thread_local! {
+ /// The zone of this thread, while no compile has it.
+ static SPARE_ZONE: Cell<Option<Zone>> = const { Cell::new(None) };
+}
+
+/// Runs `job` with the zone of the thread for its work data. Nothing that `job` returns can refer to the zone.
+pub(crate) fn with_work_zone<R>(job: impl for<'zone> FnOnce(&'zone Zone) -> R) -> R {
+ let mut zone = SPARE_ZONE.take().unwrap_or_else(|| {
+ ak::add_idle_thread_memory_release(release_idle_memory);
+ Zone::new(LIMIT, c"Regex work")
+ });
+ let result = zone.scope(job);
+ // NB: Give back the memory of an outsized compile rather than keep it until the thread goes idle.
+ if zone.memory() > MAXIMUM_SPARE_SIZE {
+ zone.trim(MAXIMUM_SPARE_SIZE);
+ }
+ SPARE_ZONE.set(Some(zone));
+ result
+}
+
+/// Gives the memory of the zone of this thread back to the system. A thread pool calls this on a thread that goes idle
+/// (see `ak::add_idle_thread_memory_release()`).
+extern "C" fn release_idle_memory() {
+ drop(SPARE_ZONE.take());
+}
diff --git a/Libraries/LibURL/Rust/src/pattern/component.rs b/Libraries/LibURL/Rust/src/pattern/component.rs
index 7d344af414f..b19b1e4c91f 100644
--- a/Libraries/LibURL/Rust/src/pattern/component.rs
+++ b/Libraries/LibURL/Rust/src/pattern/component.rs
@@ -103,8 +103,9 @@ impl Component {
// 6. Let regular expression be RegExpCreate(regular expression string, flags). If this throws an exception, catch
// it, and throw a TypeError.
- let regex = Regex::compile(&regular_expression_string, flags)
- .map_err(|error| ErrorInfo::new(format!("RegExp compile error: {error}")))?;
+ let regex = Regex::compile(&regular_expression_string, flags, |error| {
+ ErrorInfo::new(format!("RegExp compile error: {error}"))
+ })?;
// 7. Let pattern string be the result of running generate a pattern string given part list and options.
let pattern_string = generate_a_pattern_string(&part_list, options);
diff --git a/Meta/Linters/check_rust_process_wide_state.py b/Meta/Linters/check_rust_process_wide_state.py
index f2c8fcbec6a..6d24149c181 100755
--- a/Meta/Linters/check_rust_process_wide_state.py
+++ b/Meta/Linters/check_rust_process_wide_state.py
@@ -43,6 +43,7 @@ ALLOWED = {
"Libraries/LibJS/JIT/Rust/src/lib.rs:BLOCKS": "per-thread count of the allocator of JIT unit tests, in the cargo test binary that has no runtime",
"Libraries/LibJS/JIT/Rust/src/lib.rs:COUNTING": "per-thread switch of the allocator of JIT unit tests, in the cargo test binary that has no runtime",
"Libraries/LibRegex/Rust/src/vm.rs:INTERRUPT_FLAG": "per-thread, and only libjs_rust's copy sets it; the copy of LibURL's crate has no VM to interrupt, so it only ever sees null",
+ "Libraries/LibRegex/Rust/src/work_zone.rs:SPARE_ZONE": "per-thread allocation pool; a second copy costs memory, never an answer",
"Libraries/LibWeb/HTML/Parser/Rust/src/fragment.rs:SPARE_TAPE": "per-thread allocation pool; a second copy costs memory, never an answer",
"Libraries/LibWeb/HTML/Parser/Rust/src/fragment.rs:TAG_NAMES": "immutable table of the C++ fly strings of tag names; each copy reads the same strings",
"Libraries/LibWeb/HTML/Parser/Rust/src/parser/test_host.rs:FAKE_DOM": "the fake DOM of tree builder unit tests, in the cargo test binary that has no C++ side",
diff --git a/Tests/LibJS/Runtime/builtins/RegExp/RegExp.js b/Tests/LibJS/Runtime/builtins/RegExp/RegExp.js
index 443cfb5608d..04eb976c7f9 100644
--- a/Tests/LibJS/Runtime/builtins/RegExp/RegExp.js
+++ b/Tests/LibJS/Runtime/builtins/RegExp/RegExp.js
@@ -965,13 +965,13 @@ test("string properties allowed as set operation operands in negated /v mode cla
test("deeply nested patterns throw instead of overflowing the stack", () => {
const message = "RegExp compile error: pattern is nested too deeply";
expect(() => {
- RegExp("(".repeat(100_000) + ")".repeat(100_000));
+ RegExp("(".repeat(1_000_000) + ")".repeat(1_000_000));
}).toThrowWithMessage(SyntaxError, message);
expect(() => {
- RegExp("(?:".repeat(100_000) + ")".repeat(100_000));
+ RegExp("(?:".repeat(1_000_000) + ")".repeat(1_000_000));
}).toThrowWithMessage(SyntaxError, message);
expect(() => {
- RegExp("[".repeat(100_000) + "]".repeat(100_000), "v");
+ RegExp("[".repeat(1_000_000) + "]".repeat(1_000_000), "v");
}).toThrowWithMessage(SyntaxError, message);
});
@@ -986,7 +986,7 @@ test("the most deeply nested pattern that compiles also runs", () => {
]) {
let deepest;
let low = 1;
- let high = 100_000;
+ let high = 1_000_000;
while (low + 1 < high) {
const middle = Math.floor((low + high) / 2);
try {