Truly independent web browser
LibRegex: Compile patterns in the work zone
Andreas Klingf6a446080279
diff --git a/Libraries/LibRegex/Rust/src/compiler.rs b/Libraries/LibRegex/Rust/src/compiler.rsindex be814cff1f7..143a9308ade 100644--- a/Libraries/LibRegex/Rust/src/compiler.rs+++ b/Libraries/LibRegex/Rust/src/compiler.rs@@ -7,16 +7,21 @@//! Bytecode compiler: AST -> Program.//!//! Compiles the parsed regex AST into a concrete instruction stream for the-//! backtracking VM.+//! backtracking VM. The program and all the work data of the compile are in the+//! zone of the compile (see `ak::Zone`).//!//! Spec://! - <https://tc39.es/ecma262/#sec-pattern-semantics>//! - <https://tc39.es/ecma262/#sec-compilepattern>+use core::cell::Cell;++use ak::Zone;+use ak::ZoneVec;+use libunicode_rust::character_types::ResolvedProperty;+use crate::ast::*;-use crate::bytecode::*;use crate::parser::Error;-use std::cell::Cell;-use std::collections::BTreeSet;+use crate::zone_program::*;/// Resolve a Unicode property name/value pair to an ICU enum ID./// Returns None if the property could not be resolved (falls back to@@ -29,45 +34,45 @@ pub fn resolve_property(name: &str, value: Option<&str>) -> Option<ResolvedPropelibunicode_rust::character_types::resolve_property(name, value)}-/// Compile a parsed pattern into a bytecode program.+/// Compile a parsed pattern into a bytecode program, which is in `zone`.////// Spec entry point: `CompilePattern`./// <https://tc39.es/ecma262/#sec-compilepattern>-pub fn compile<'z>(pattern: &Pattern<'z>) -> Result<Program, Error<'z>> {- let mut compiler = Compiler::new(pattern);+pub fn compile<'z>(zone: &'z Zone, pattern: &Pattern<'z>) -> Result<ZoneProgram<'z>, Error<'z>> {+ let mut compiler = Compiler::new(zone, pattern);compiler.compile_pattern(pattern);if compiler.ran_out_of_stack.get() {return Err(Error::TooDeeplyNested);}- compiler.program.named_groups = pattern- .named_groups- .iter()- .map(|ng| NamedGroupEntry {- name: ng.name.to_string(),- index: ng.index,- })- .collect();- // NB: Nothing adds to a program once it is compiled, so it keeps no room to grow.- compiler.program.instructions.shrink_to_fit();- Ok(compiler.program)+ Ok(ZoneProgram {+ instructions: compiler.instructions.into_slice(),+ capture_count: pattern.capture_count,+ register_count: compiler.register_count,+ unicode: compiler.unicode,+ unicode_sets: compiler.unicode_sets,+ ignore_case: pattern.flags.ignore_case,+ multiline: pattern.flags.multiline,+ dot_all: pattern.flags.dot_all,+ named_groups: pattern.named_groups,+ })}-const fn char_range(start: u32, end: u32) -> CharRange {- CharRange { start, end }+const fn char_range(start: u32, end: u32) -> CodePointRange {+ CodePointRange { start, end }}/// `\d`: <https://tc39.es/ecma262/#sec-compiletocharset>-const DIGIT_RANGES: &[CharRange] = &[char_range(0x30, 0x39)];-const NON_DIGIT_RANGES: &[CharRange] = &[char_range(0, 0x2F), char_range(0x3A, 0x10FFFF)];+const DIGIT_RANGES: &[CodePointRange] = &[char_range(0x30, 0x39)];+const NON_DIGIT_RANGES: &[CodePointRange] = &[char_range(0, 0x2F), char_range(0x3A, 0x10FFFF)];/// `\w` without the u and v flags is the ASCII WordCharacters: <https://tc39.es/ecma262/#sec-wordcharacters>-const WORD_RANGES: &[CharRange] = &[+const WORD_RANGES: &[CodePointRange] = &[char_range(0x30, 0x39),char_range(0x41, 0x5A),char_range(0x5F, 0x5F),char_range(0x61, 0x7A),];-const NON_WORD_RANGES: &[CharRange] = &[+const NON_WORD_RANGES: &[CodePointRange] = &[char_range(0, 0x2F),char_range(0x3A, 0x40),char_range(0x5B, 0x5E),@@ -77,7 +82,7 @@ const NON_WORD_RANGES: &[CharRange] = &[/// `\s` is WhiteSpace and LineTerminator: <https://tc39.es/ecma262/#sec-white-space>,/// <https://tc39.es/ecma262/#sec-line-terminators>-const WHITESPACE_RANGES: &[CharRange] = &[+const WHITESPACE_RANGES: &[CodePointRange] = &[char_range(0x09, 0x0D),char_range(0x20, 0x20),char_range(0xA0, 0xA0),@@ -89,7 +94,7 @@ const WHITESPACE_RANGES: &[CharRange] = &[char_range(0x3000, 0x3000),char_range(0xFEFF, 0xFEFF),];-const NON_WHITESPACE_RANGES: &[CharRange] = &[+const NON_WHITESPACE_RANGES: &[CodePointRange] = &[char_range(0, 0x08),char_range(0x0E, 0x1F),char_range(0x21, 0x9F),@@ -104,11 +109,12 @@ const NON_WHITESPACE_RANGES: &[CharRange] = &[];/// Sorts `ranges` and merges the ones that overlap or touch, which the binary search of the VM relies on.-fn normalize_char_ranges(ranges: &mut Vec<CharRange>) {- ranges.sort_by_key(|range| range.start);+fn normalize_char_ranges(ranges: &mut ZoneVec<'_, CodePointRange>) {+ // NB: Ranges with the same start always merge, so their order does not matter.+ ranges.sort_unstable_by_key(|range| range.start);let mut merged_count = 0;for index in 0..ranges.len() {- let range = ranges[index].clone();+ let range = ranges[index];if merged_count > 0 {let last = &mut ranges[merged_count - 1];if range.start <= last.end.saturating_add(1) {@@ -122,8 +128,47 @@ fn normalize_char_ranges(ranges: &mut Vec<CharRange>) {ranges.truncate(merged_count);}-struct Compiler {- program: Program,+/// The multi-codepoint strings of a string property, from its packed data (see+/// `Compiler::string_property_data()`), in order.+fn packed_strings(data: &[u32]) -> impl Iterator<Item = &[u32]> {+ // Parse packed format: [count, len1, cp1..., len2, cp2..., ...]+ let mut remaining = data.first().map_or(0, |count| *count as usize);+ let mut offset = 1;+ core::iter::from_fn(move || {+ if remaining == 0 || offset >= data.len() {+ return None;+ }+ remaining -= 1;+ let len = data[offset] as usize;+ offset += 1;+ if offset + len > data.len() {+ remaining = 0;+ return None;+ }+ let string = &data[offset..offset + len];+ offset += len;+ Some(string)+ })+}++/// Adds `length` to `lengths`, which has each length one time.+fn add_length(lengths: &mut ZoneVec<'_, usize>, length: usize) {+ if !lengths.contains(&length) {+ lengths.push(length);+ }+}++struct Compiler<'z> {+ /// The zone that the program and the work data of the compile go in.+ zone: &'z Zone,+ /// The bytecode instructions.+ instructions: ZoneVec<'z, ZoneInstruction<'z>>,+ /// Total number of registers needed (2 per capture group + 2 for group 0, then the internal ones).+ register_count: u32,+ /// Whether Unicode mode is enabled (affects surrogate pair decoding).+ unicode: bool,+ /// Whether v-flag (unicode sets) mode is enabled.+ unicode_sets: bool,/// Effective flags (affected by modifier groups).effective_ignore_case: bool,effective_multiline: bool,@@ -134,9 +179,13 @@ struct Compiler {backward: bool,/// Set when a pass stopped short of a nested group or class because the stack ran low, which fails the compile.ran_out_of_stack: Cell<bool>,+ /// Room for the capture registers of an atom, which each use clears.+ capture_registers: ZoneVec<'z, u32>,+ /// The packed strings of each string property that the compile has fetched, with its name.+ string_properties: ZoneVec<'z, (&'z str, &'z [u32])>,}-impl Compiler {+impl<'z> Compiler<'z> {/// Whether a pass has to stop short of recursing into a nested group or class, which fails the compile.fn is_out_of_stack(&self) -> bool {if crate::stack::is_exhausted() {@@ -153,8 +202,12 @@ impl Compiler {/// mode. But matching a class with ranges then checks every code point that is not in them against the case/// closure of each range, which would make the large ranges of \s, of the negated builtins, and of negated classes/// slower than matching the builtins themselves.- fn legacy_builtin_class_ranges(&self, class: BuiltinCharacterClass, negated: bool) -> Option<&'static [CharRange]> {- if self.program.unicode || self.program.unicode_sets {+ fn legacy_builtin_class_ranges(+ &self,+ class: BuiltinCharacterClass,+ negated: bool,+ ) -> Option<&'static [CodePointRange]> {+ if self.unicode || self.unicode_sets {return None;}if self.effective_ignore_case@@ -172,198 +225,234 @@ impl Compiler {})}- fn new(pattern: &Pattern) -> Self {+ fn new(zone: &'z Zone, pattern: &Pattern<'z>) -> Self {// Registers: 0-1 for group 0, then 2 per capture group.let register_count = 2 + pattern.capture_count * 2;Self {- program: Program {- instructions: Vec::new(),- capture_count: pattern.capture_count,- register_count,- unicode: pattern.flags.unicode || pattern.flags.unicode_sets,- unicode_sets: pattern.flags.unicode_sets,- ignore_case: pattern.flags.ignore_case,- multiline: pattern.flags.multiline,- dot_all: pattern.flags.dot_all,- named_groups: Vec::new(),- },+ zone,+ instructions: ZoneVec::new_in(zone),+ register_count,+ unicode: pattern.flags.unicode || pattern.flags.unicode_sets,+ unicode_sets: pattern.flags.unicode_sets,effective_ignore_case: pattern.flags.ignore_case,effective_multiline: pattern.flags.multiline,effective_dot_all: pattern.flags.dot_all,next_internal_reg: register_count,backward: false,ran_out_of_stack: Cell::new(false),+ capture_registers: ZoneVec::new_in(zone),+ string_properties: ZoneVec::new_in(zone),}}- /// Fetch multi-codepoint strings for a Unicode string property via FFI.- /// Returns empty Vec if the property is not a string property.+ /// Fetch the multi-codepoint strings of a Unicode string property via FFI, packed as+ /// [count, len1, cp1..., len2, cp2..., ...] (see `packed_strings()`).+ /// Returns nothing if the property is not a string property.////// These are the string-valued members that `/v` character classes can/// match atomically, as described by `CompileClassSetString`./// <https://tc39.es/ecma262/#sec-compileclasssetstring>- fn get_string_property_strings(name: &str) -> Vec<Vec<u32>> {- let buf = libunicode_rust::character_types::get_string_property_data(name);- if buf.is_empty() {- return Vec::new();+ fn string_property_data(&mut self, name: &'z str) -> &'z [u32] {+ if let Some((_, data)) = self.string_properties.iter().find(|(known, _)| *known == name) {+ return data;}-- // Parse packed format: [count, len1, cp1..., len2, cp2..., ...]- let count = buf[0] as usize;- let mut strings = Vec::with_capacity(count);- let mut offset = 1;- for _ in 0..count {- if offset >= buf.len() {- break;- }- let len = buf[offset] as usize;- offset += 1;- if offset + len > buf.len() {- break;- }- strings.push(buf[offset..offset + len].to_vec());- offset += len;- }- strings- }-- fn get_string_property_strings_of_length(name: &str, len: usize) -> Vec<Vec<u32>> {- Self::get_string_property_strings(name)- .into_iter()- .filter(|string| string.len() == len)- .collect()+ let needed = libunicode_rust::character_types::get_string_property_data(name, &mut []);+ let buffer = self.zone.alloc_slice_fill(needed, 0);+ let written = libunicode_rust::character_types::get_string_property_data(name, buffer);+ let data: &'z [u32] = if written == 0 || written > needed {+ &[]+ } else {+ &buffer[..written]+ };+ self.string_properties.push((name, data));+ data}/// Emit code for a Unicode string property match./// Compiles as: (longest_multi_cp_string | ... | shortest_multi_cp_string | single_cp_property)/// This ensures longest match is tried first (v-flag semantics)./// <https://tc39.es/ecma262/#sec-compileclasssetstring>- fn emit_string_property_match(&mut self, name: &str, value: Option<&str>) {- let mut strings = Self::get_string_property_strings(name);- if strings.is_empty() {+ fn emit_string_property_match(&mut self, name: &'z str, value: Option<&'z str>) {+ let data = self.string_property_data(name);+ let mut lengths = ZoneVec::new_in(self.zone);+ for string in packed_strings(data) {+ add_length(&mut lengths, string.len());+ }+ if lengths.is_empty() {// Not a string property or no multi-cp strings; just emit regular property match.self.emit_unicode_property(false, name, value);return;}- // Sort longest-first for greedy longest-match semantics.- strings.sort_by_key(|s| std::cmp::Reverse(s.len()));+ // Sort longest-first for greedy longest-match semantics. Strings of the same length keep their order.+ lengths.sort_unstable_by(|a, b| b.cmp(a));- // Pack strings into a flat vec: [len, cp0, cp1, ..., len, cp0, ...]- let mut packed = Vec::new();- for string in &strings {- let s = if self.backward {- string.iter().rev().copied().collect::<Vec<_>>()- } else {- string.clone()- };- packed.push(s.len() as u32);- packed.extend_from_slice(&s);+ // Pack strings into a flat list: [len, cp0, cp1, ..., len, cp0, ...]+ let packed_len = packed_strings(data).map(|string| string.len() + 1).sum();+ let mut packed = ZoneVec::with_capacity_in(packed_len, self.zone);+ for length in &lengths {+ for string in packed_strings(data).filter(|string| string.len() == *length) {+ packed.push(string.len() as u32);+ if self.backward {+ packed.extend(string.iter().rev());+ } else {+ packed.extend_from_slice(string);+ }+ }}- let property_data = UnicodePropertyData {- negated: false,- name: name.to_string(),- value: value.map(|v| v.to_string()),- resolved: None,- };-- self.emit(Instruction::StringPropertyMatch {- strings: packed.into_boxed_slice(),- property: Box::new(property_data),+ self.emit(ZoneInstruction::StringPropertyMatch {+ strings: packed.into_slice(),+ property: self.zone.alloc(UnicodeProperty {+ negated: false,+ name,+ value,+ }),});}- fn emit_unicode_property(&mut self, negated: bool, name: &str, value: Option<&str>) {- self.emit(Instruction::UnicodeProperty(Box::new(UnicodePropertyData {- negated,- name: name.to_string(),- value: value.map(|v| v.to_string()),- resolved: None,- })));+ fn emit_unicode_property(&mut self, negated: bool, name: &'z str, value: Option<&'z str>) {+ let property = self.zone.alloc(UnicodeProperty { negated, name, value });+ self.emit(ZoneInstruction::UnicodeProperty(property));}fn emit_char_string(&mut self, chars: &[char]) {- let iter: Box<dyn Iterator<Item = &char>> = if self.backward {- Box::new(chars.iter().rev())+ if self.backward {+ for c in chars.iter().rev() {+ self.emit_char_maybe_case_fold(*c as u32);+ }} else {- Box::new(chars.iter())- };- for c in iter {- self.emit_char_maybe_case_fold(*c as u32);+ for c in chars {+ self.emit_char_maybe_case_fold(*c as u32);+ }}}fn emit_code_point_string(&mut self, string: &[u32]) {- let iter: Box<dyn Iterator<Item = &u32>> = if self.backward {- Box::new(string.iter().rev())+ if self.backward {+ for cp in string.iter().rev() {+ self.emit_char_maybe_case_fold(*cp);+ }} else {- Box::new(string.iter())- };- for cp in iter {- self.emit_char_maybe_case_fold(*cp);+ for cp in string {+ self.emit_char_maybe_case_fold(*cp);+ }}}- fn singleton_length_set() -> BTreeSet<usize> {- [1usize].into_iter().collect()+ /// Whether `expr` matches strings of `length` code points.+ fn class_set_expression_has_length(&mut self, expr: &ClassSetExpression<'z>, length: usize) -> bool {+ if self.is_out_of_stack() {+ return false;+ }+ match expr {+ ClassSetExpression::Union(operands) => operands+ .iter()+ .any(|operand| self.class_set_operand_has_length(operand, length)),+ ClassSetExpression::Intersection(operands) => {+ !operands.is_empty()+ && operands+ .iter()+ .all(|operand| self.class_set_operand_has_length(operand, length))+ }+ ClassSetExpression::Subtraction(operands) => operands+ .first()+ .is_some_and(|operand| self.class_set_operand_has_length(operand, length)),+ }+ }++ /// Whether `operand` matches strings of `length` code points.+ fn class_set_operand_has_length(&mut self, operand: &ClassSetOperand<'z>, length: usize) -> bool {+ match operand {+ ClassSetOperand::Char(_) | ClassSetOperand::Range(_, _) | ClassSetOperand::BuiltinClass(_) => length == 1,+ ClassSetOperand::NestedClass(cc) => {+ if cc.negated {+ return length == 1;+ }+ match &cc.body {+ CharacterClassBody::Ranges(_) => length == 1,+ CharacterClassBody::UnicodeSet(expr) => self.class_set_expression_has_length(expr, length),+ }+ }+ ClassSetOperand::UnicodeProperty(up) => {+ if self.unicode_sets && !up.negated && libunicode_rust::character_types::is_string_property(up.name) {+ return length == 1+ || packed_strings(self.string_property_data(up.name)).any(|string| string.len() == length);+ }+ length == 1+ }+ ClassSetOperand::StringLiteral(chars) => chars.len() == length,+ }}- fn class_set_expression_lengths(&self, expr: &ClassSetExpression) -> BTreeSet<usize> {+ /// Adds the lengths of the strings that `expr` matches to `lengths`, which has each length one time.+ fn collect_class_set_expression_lengths(+ &mut self,+ expr: &ClassSetExpression<'z>,+ lengths: &mut ZoneVec<'z, usize>,+ ) {if self.is_out_of_stack() {- return BTreeSet::new();+ return;}match expr {- ClassSetExpression::Union(operands) => operands.iter().fold(BTreeSet::new(), |mut lengths, operand| {- lengths.extend(self.class_set_operand_lengths(operand));- lengths- }),+ ClassSetExpression::Union(operands) => {+ for operand in *operands {+ self.collect_class_set_operand_lengths(operand, lengths);+ }+ }ClassSetExpression::Intersection(operands) => {let Some((first, rest)) = operands.split_first() else {- return BTreeSet::new();+ return;};- let mut lengths = self.class_set_operand_lengths(first);- for operand in rest {- let operand_lengths = self.class_set_operand_lengths(operand);- lengths.retain(|len| operand_lengths.contains(len));+ // NB: A length that is in `lengths` already stays, as the union with the lengths of the intersection.+ let first_new = lengths.len();+ self.collect_class_set_operand_lengths(first, lengths);+ let mut index = first_new;+ while index < lengths.len() {+ let length = lengths[index];+ if rest+ .iter()+ .all(|operand| self.class_set_operand_has_length(operand, length))+ {+ index += 1;+ } else {+ lengths.swap_remove(index);+ }+ }+ }+ ClassSetExpression::Subtraction(operands) => {+ if let Some(first) = operands.first() {+ self.collect_class_set_operand_lengths(first, lengths);}- lengths}- ClassSetExpression::Subtraction(operands) => operands- .first()- .map(|operand| self.class_set_operand_lengths(operand))- .unwrap_or_default(),}}- fn class_set_operand_lengths(&self, operand: &ClassSetOperand) -> BTreeSet<usize> {+ /// Adds the lengths of the strings that `operand` matches to `lengths`, which has each length one time.+ fn collect_class_set_operand_lengths(&mut self, operand: &ClassSetOperand<'z>, lengths: &mut ZoneVec<'z, usize>) {match operand {ClassSetOperand::Char(_) | ClassSetOperand::Range(_, _) | ClassSetOperand::BuiltinClass(_) => {- Self::singleton_length_set()+ add_length(lengths, 1);}ClassSetOperand::NestedClass(cc) => {if cc.negated {- return Self::singleton_length_set();+ add_length(lengths, 1);+ return;}match &cc.body {- CharacterClassBody::Ranges(_) => Self::singleton_length_set(),- CharacterClassBody::UnicodeSet(expr) => self.class_set_expression_lengths(expr),+ CharacterClassBody::Ranges(_) => add_length(lengths, 1),+ CharacterClassBody::UnicodeSet(expr) => self.collect_class_set_expression_lengths(expr, lengths),}}ClassSetOperand::UnicodeProperty(up) => {- if self.program.unicode_sets- && !up.negated- && 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) {- lengths.insert(string.len());+ add_length(lengths, 1);+ if self.unicode_sets && !up.negated && libunicode_rust::character_types::is_string_property(up.name) {+ for string in packed_strings(self.string_property_data(up.name)) {+ add_length(lengths, string.len());}- return lengths;}- Self::singleton_length_set()}- ClassSetOperand::StringLiteral(chars) => [chars.len()].into_iter().collect(),+ ClassSetOperand::StringLiteral(chars) => add_length(lengths, chars.len()),}}@@ -382,18 +471,18 @@ impl Compiler {return;}- let mut jump_to_end = Vec::new();+ // NB: Until the end is known, each jump to the end jumps to the one before it, and the first one to u32::MAX.+ let mut last_jump_to_end = u32::MAX;for (i, item) in items.iter().enumerate() {if i < items.len() - 1 {- let split = self.emit(Instruction::Split {+ let split = self.emit(ZoneInstruction::Split {prefer: self.current_offset() + 1,other: u32::MAX,});compile_one(self, item);- let jmp = self.emit(Instruction::Jump(u32::MAX));- jump_to_end.push(jmp);+ last_jump_to_end = self.emit(ZoneInstruction::Jump(last_jump_to_end));let next = self.current_offset();- self.program.instructions[split as usize] = Instruction::Split {+ self.instructions[split as usize] = ZoneInstruction::Split {prefer: split + 1,other: next,};@@ -402,8 +491,12 @@ impl Compiler {}}let end = self.current_offset();- for jmp in jump_to_end {- self.program.instructions[jmp as usize] = Instruction::Jump(end);+ while last_jump_to_end != u32::MAX {+ let ZoneInstruction::Jump(previous_jump_to_end) = self.instructions[last_jump_to_end as usize] else {+ unreachable!("a jump to the end of a split chain is a jump");+ };+ self.instructions[last_jump_to_end as usize] = ZoneInstruction::Jump(end);+ last_jump_to_end = previous_jump_to_end;}}@@ -416,55 +509,58 @@ impl Compiler {let lower = ch.to_lowercase().next().unwrap_or(ch) as u32;let upper = ch.to_uppercase().next().unwrap_or(ch) as u32;if lower != upper {- self.emit(Instruction::CharNoCase(cp, cp));+ self.emit(ZoneInstruction::CharNoCase(cp, cp));return;}}- self.emit(Instruction::Char(cp));+ self.emit(ZoneInstruction::Char(cp));}fn alloc_register(&mut self) -> u32 {let reg = self.next_internal_reg;self.next_internal_reg += 1;- self.program.register_count = self.next_internal_reg;+ self.register_count = self.next_internal_reg;reg}- fn emit(&mut self, inst: Instruction) -> u32 {- self.program.emit(inst)+ fn emit(&mut self, inst: ZoneInstruction<'z>) -> u32 {+ let idx = self.current_offset();+ self.instructions.push(inst);+ idx}fn current_offset(&self) -> u32 {- self.program.current_offset()+ self.instructions.len() as u32}- /// Collect all capture group indices inside an atom (recursively).- fn collect_captures(&self, atom: &Atom, out: &mut Vec<u32>) {+ /// Collect the capture register indices (start and end) of all capture groups inside an atom (recursively).+ fn collect_capture_registers(&self, atom: &Atom<'z>, out: &mut ZoneVec<'z, u32>) {match atom {Atom::Group(g) => {- out.push(g.index);- self.collect_captures_in_disjunction(&g.body, out);+ out.push(g.index * 2);+ out.push(g.index * 2 + 1);+ self.collect_capture_registers_in_disjunction(&g.body, out);}Atom::NonCapturingGroup(g) => {- self.collect_captures_in_disjunction(&g.body, out);+ self.collect_capture_registers_in_disjunction(&g.body, out);}Atom::ModifierGroup(mg) => {- self.collect_captures_in_disjunction(&mg.body, out);+ self.collect_capture_registers_in_disjunction(&mg.body, out);}Atom::Lookaround(la) => {- self.collect_captures_in_disjunction(&la.body, out);+ self.collect_capture_registers_in_disjunction(&la.body, out);}_ => {}}}- fn collect_captures_in_disjunction(&self, disj: &Disjunction, out: &mut Vec<u32>) {+ fn collect_capture_registers_in_disjunction(&self, disj: &Disjunction<'z>, out: &mut ZoneVec<'z, u32>) {if self.is_out_of_stack() {return;}for alt in disj.alternatives {for term in alt.terms {- self.collect_captures(&term.atom, out);+ self.collect_capture_registers(&term.atom, out);}}}@@ -473,30 +569,31 @@ impl Compiler {/// Per ECMA-262 RepeatMatcher step 2.d, captures must be reset to/// undefined at the start of each quantifier iteration./// <https://tc39.es/ecma262/#sec-runtime-semantics-repeatmatcher-abstract-operation>- fn emit_clear_captures(&mut self, atom: &Atom) {- for idx in self.capture_registers(atom) {- self.emit(Instruction::ClearRegister(idx));+ fn emit_clear_captures(&mut self, atom: &Atom<'z>) {+ let mut registers = self.capture_registers.take();+ registers.clear();+ if !matches!(atom, Atom::Lookaround(_) | Atom::Assertion(_)) {+ self.collect_capture_registers(atom, &mut registers);}+ for reg in ®isters {+ self.emit(ZoneInstruction::ClearRegister(*reg));+ }+ self.capture_registers = registers;}/// Collect all capture register indices (start and end) for captures inside an atom./// Returns empty for intrinsically zero-width atoms (lookarounds, assertions)/// since their captures should NOT be cleared on zero-width ProgressCheck.- fn capture_registers(&self, atom: &Atom) -> Vec<u32> {+ fn capture_registers(&self, atom: &Atom<'z>) -> &'z [u32] {if matches!(atom, Atom::Lookaround(_) | Atom::Assertion(_)) {- return Vec::new();- }- let mut captures = Vec::new();- self.collect_captures(atom, &mut captures);- let mut regs = Vec::new();- for idx in captures {- regs.push(idx * 2);- regs.push(idx * 2 + 1);+ return &[];}- regs+ let mut regs = ZoneVec::new_in(self.zone);+ self.collect_capture_registers(atom, &mut regs);+ regs.into_slice()}- fn disjunction_can_be_zero_width(&self, disjunction: &Disjunction) -> bool {+ fn disjunction_can_be_zero_width(&self, disjunction: &Disjunction<'z>) -> bool {if self.is_out_of_stack() {return true;}@@ -506,11 +603,11 @@ impl Compiler {.any(|alternative| self.alternative_can_be_zero_width(alternative))}- fn alternative_can_be_zero_width(&self, alternative: &Alternative) -> bool {+ fn alternative_can_be_zero_width(&self, alternative: &Alternative<'z>) -> bool {alternative.terms.iter().all(|term| self.term_can_be_zero_width(term))}- fn term_can_be_zero_width(&self, term: &Term) -> bool {+ fn term_can_be_zero_width(&self, term: &Term<'z>) -> bool {match &term.quantifier {Some(quantifier) if quantifier.min == 0 => true,_ => self.atom_can_be_zero_width(&term.atom),@@ -518,7 +615,7 @@ impl Compiler {}/// Returns true if the given atom could potentially match zero characters.- fn atom_can_be_zero_width(&self, atom: &Atom) -> bool {+ fn atom_can_be_zero_width(&self, atom: &Atom<'z>) -> bool {match atom {Atom::Literal(_)| Atom::Dot@@ -534,18 +631,18 @@ impl Compiler {/// Lower `Pattern` to the concrete program entry sequence./// <https://tc39.es/ecma262/#sec-compilepattern>- fn compile_pattern(&mut self, pattern: &Pattern) {+ fn compile_pattern(&mut self, pattern: &Pattern<'z>) {// Save start of match (group 0).- self.emit(Instruction::Save(0));+ self.emit(ZoneInstruction::Save(0));self.compile_disjunction(&pattern.disjunction);// Save end of match (group 0).- self.emit(Instruction::Save(1));- self.emit(Instruction::Match);+ self.emit(ZoneInstruction::Save(1));+ self.emit(ZoneInstruction::Match);}/// Lower `Disjunction` to a chain of split/jump choice points./// <https://tc39.es/ecma262/#sec-compilesubpattern>- fn compile_disjunction(&mut self, disj: &Disjunction) {+ fn compile_disjunction(&mut self, disj: &Disjunction<'z>) {if self.is_out_of_stack() {return;}@@ -558,7 +655,7 @@ impl Compiler {/// Lower `Alternative` in the current direction./// <https://tc39.es/ecma262/#sec-compilesubpattern>- fn compile_alternative(&mut self, alt: &Alternative) {+ fn compile_alternative(&mut self, alt: &Alternative<'z>) {if self.backward {for term in alt.terms.iter().rev() {self.compile_term(term);@@ -572,34 +669,34 @@ impl Compiler {/// Lower `Term`, delegating to either `CompileAtom` or the quantified path./// <https://tc39.es/ecma262/#sec-compilesubpattern>- fn compile_term(&mut self, term: &Term) {+ fn compile_term(&mut self, term: &Term<'z>) {match &term.quantifier {None => self.compile_atom(&term.atom),Some(q) => self.compile_quantified(&term.atom, q),}}- /// Try to extract a SimpleMatch for an atom (for optimized greedy/lazy loops).- fn try_simple_match(&self, atom: &Atom) -> Option<SimpleMatch> {+ /// Try to extract a ZoneSimpleMatch for an atom (for optimized greedy/lazy loops).+ fn try_simple_match(&self, atom: &Atom<'z>) -> Option<ZoneSimpleMatch<'z>> {match atom {- Atom::Dot => Some(SimpleMatch::AnyChar {+ Atom::Dot => Some(ZoneSimpleMatch::AnyChar {dot_all: self.effective_dot_all,}),Atom::Literal(c) => {// Don't use simple match for supplementary chars in non-unicode mode// (they need surrogate pair splitting).- if *c > 0xFFFF && !self.program.unicode && !self.program.unicode_sets {+ if *c > 0xFFFF && !self.unicode && !self.unicode_sets {return None;}if self.effective_ignore_case {let lo = *c;let hi = *c; // VM will use case_fold_eq- Some(SimpleMatch::CharNoCase(lo, hi))+ Some(ZoneSimpleMatch::CharNoCase(lo, hi))} else {- Some(SimpleMatch::Char(*c))+ Some(ZoneSimpleMatch::Char(*c))}}- Atom::BuiltinCharacterClass(class) => Some(SimpleMatch::BuiltinClass(*class)),+ Atom::BuiltinCharacterClass(class) => Some(ZoneSimpleMatch::BuiltinClass(*class)),Atom::CharacterClass(cc) => match &cc.body {CharacterClassBody::Ranges(ranges_vec) => self.try_simple_match_for_ranges(ranges_vec, cc.negated),CharacterClassBody::UnicodeSet(expr) => self.try_simple_match_for_unicode_set(expr, cc.negated),@@ -607,15 +704,10 @@ 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.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.to_string(),- value: up.value.map(str::to_string),- resolved: None, // Will be populated after compilation.- })))+ Some(ZoneSimpleMatch::UnicodeProperty(self.zone.alloc(*up)))}_ => None,}@@ -625,7 +717,7 @@ 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<'z>(&self, disj: &Disjunction<'z>) -> Option<Term<'z>> {+ fn try_merge_optional_alternatives(&self, disj: &Disjunction<'z>) -> Option<Term<'z>> {let [first, second] = disj.alternatives else {return None;};@@ -636,27 +728,29 @@ impl Compiler {return None;};+ let optional = Quantifier::zero_or_one(true);+ match (&first_term.quantifier, &second_term.quantifier) {+ (None, Some(q)) | (Some(q), None) if *q == optional => {}+ _ => return None,+ }+let first_match = self.try_simple_match(&first_term.atom)?;let second_match = self.try_simple_match(&second_term.atom)?;if first_match != second_match {return None;}- 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,- quantifier: Some(optional),- }),- _ => None,- }+ Some(Term {+ atom: first_term.atom,+ quantifier: Some(optional),+ })}/// Lower a quantified atom using the same observable behavior as/// `CompileQuantifier` plus `RepeatMatcher`./// - <https://tc39.es/ecma262/#sec-compilequantifier>/// - <https://tc39.es/ecma262/#sec-runtime-semantics-repeatmatcher-abstract-operation>- fn compile_quantified(&mut self, atom: &Atom, q: &Quantifier) {+ fn compile_quantified(&mut self, atom: &Atom<'z>, q: &Quantifier) {// Try to use optimized GreedyLoop/LazyLoop for simple character matchers.if let Some(matcher) = self.try_simple_match(atom) {match q.max {@@ -668,13 +762,13 @@ impl Compiler {}_ => {if q.greedy {- self.emit(Instruction::GreedyLoop {+ self.emit(ZoneInstruction::GreedyLoop {matcher,min: q.min,max: q.max,});} else {- self.emit(Instruction::LazyLoop {+ self.emit(ZoneInstruction::LazyLoop {matcher,min: q.min,max: q.max,@@ -696,20 +790,20 @@ impl Compiler {None};- self.emit(Instruction::RepeatStart { counter_reg });+ self.emit(ZoneInstruction::RepeatStart { counter_reg });let body_start = self.current_offset();if let Some(reg) = progress_reg {- self.emit(Instruction::Save(reg));+ self.emit(ZoneInstruction::Save(reg));}self.emit_clear_captures(atom);self.compile_atom(atom);if let Some(reg) = progress_reg {- self.emit(Instruction::ProgressCheck {+ self.emit(ZoneInstruction::ProgressCheck {reg,clear_captures: self.capture_registers(atom),});}- self.emit(Instruction::RepeatCheck {+ self.emit(ZoneInstruction::RepeatCheck {counter_reg,min: q.min,max: q.max,@@ -748,45 +842,45 @@ impl Compiler {let progress_reg = Some(self.alloc_register());if q.greedy {// Split: prefer body, other skip.- let split = self.emit(Instruction::Split {+ let split = self.emit(ZoneInstruction::Split {prefer: self.current_offset() + 1,other: u32::MAX,});if let Some(reg) = progress_reg {- self.emit(Instruction::Save(reg));+ self.emit(ZoneInstruction::Save(reg));}self.emit_clear_captures(atom);self.compile_atom(atom);if let Some(reg) = progress_reg {- self.emit(Instruction::ProgressCheck {+ self.emit(ZoneInstruction::ProgressCheck {reg,clear_captures: self.capture_registers(atom),});}let after = self.current_offset();- self.program.instructions[split as usize] = Instruction::Split {+ self.instructions[split as usize] = ZoneInstruction::Split {prefer: split + 1,other: after,};} else {// Lazy: prefer skip, other body.- let split = self.emit(Instruction::Split {+ let split = self.emit(ZoneInstruction::Split {prefer: u32::MAX,other: self.current_offset() + 1,});if let Some(reg) = progress_reg {- self.emit(Instruction::Save(reg));+ self.emit(ZoneInstruction::Save(reg));}self.emit_clear_captures(atom);self.compile_atom(atom);if let Some(reg) = progress_reg {- self.emit(Instruction::ProgressCheck {+ self.emit(ZoneInstruction::ProgressCheck {reg,clear_captures: self.capture_registers(atom),});}let after = self.current_offset();- self.program.instructions[split as usize] = Instruction::Split {+ self.instructions[split as usize] = ZoneInstruction::Split {prefer: after,other: split + 1,};@@ -804,46 +898,46 @@ impl Compiler {let loop_start = self.current_offset();if q.greedy {- let split = self.emit(Instruction::Split {+ let split = self.emit(ZoneInstruction::Split {prefer: self.current_offset() + 1,other: u32::MAX,});if can_be_zero_width {- self.emit(Instruction::Save(progress_reg));+ self.emit(ZoneInstruction::Save(progress_reg));}self.emit_clear_captures(atom);self.compile_atom(atom);if can_be_zero_width {- self.emit(Instruction::ProgressCheck {+ self.emit(ZoneInstruction::ProgressCheck {reg: progress_reg,clear_captures: self.capture_registers(atom),});}- self.emit(Instruction::Jump(loop_start));+ self.emit(ZoneInstruction::Jump(loop_start));let after = self.current_offset();- self.program.instructions[split as usize] = Instruction::Split {+ self.instructions[split as usize] = ZoneInstruction::Split {prefer: split + 1,other: after,};} else {- let split = self.emit(Instruction::Split {+ let split = self.emit(ZoneInstruction::Split {prefer: u32::MAX,other: self.current_offset() + 1,});if can_be_zero_width {- self.emit(Instruction::Save(progress_reg));+ self.emit(ZoneInstruction::Save(progress_reg));}self.emit_clear_captures(atom);self.compile_atom(atom);if can_be_zero_width {- self.emit(Instruction::ProgressCheck {+ self.emit(ZoneInstruction::ProgressCheck {reg: progress_reg,clear_captures: self.capture_registers(atom),});}- self.emit(Instruction::Jump(loop_start));+ self.emit(ZoneInstruction::Jump(loop_start));let after = self.current_offset();- self.program.instructions[split as usize] = Instruction::Split {+ self.instructions[split as usize] = ZoneInstruction::Split {prefer: after,other: split + 1,};@@ -852,13 +946,13 @@ impl Compiler {}}- fn compile_counted_optional_repetitions(&mut self, atom: &Atom, optional_count: u32, greedy: bool) {+ fn compile_counted_optional_repetitions(&mut self, atom: &Atom<'z>, optional_count: u32, greedy: bool) {let counter_reg = self.alloc_register();- self.emit(Instruction::RepeatStart { counter_reg });+ self.emit(ZoneInstruction::RepeatStart { counter_reg });// min is always 0 here: this function only emits the optional tail of a {min,max}// quantifier; the required `min` repetitions have already been emitted by the caller.- let check = self.emit(Instruction::RepeatCheck {+ let check = self.emit(ZoneInstruction::RepeatCheck {counter_reg,min: 0,max: Some(optional_count),@@ -866,42 +960,42 @@ impl Compiler {greedy,});- let skip_body = self.emit(Instruction::Jump(u32::MAX));+ let skip_body = self.emit(ZoneInstruction::Jump(u32::MAX));let body_start = self.current_offset();self.emit_clear_captures(atom);self.compile_atom(atom);- self.emit(Instruction::Jump(check));+ self.emit(ZoneInstruction::Jump(check));- self.program.instructions[check as usize] = Instruction::RepeatCheck {+ self.instructions[check as usize] = ZoneInstruction::RepeatCheck {counter_reg,min: 0,max: Some(optional_count),body: body_start,greedy,};- self.program.instructions[skip_body as usize] = Instruction::Jump(self.current_offset());+ self.instructions[skip_body as usize] = ZoneInstruction::Jump(self.current_offset());}/// Lower an `Atom` or assertion-like atom to bytecode./// - <https://tc39.es/ecma262/#sec-compileatom>/// - <https://tc39.es/ecma262/#sec-compileassertion>- fn compile_atom(&mut self, atom: &Atom) {+ fn compile_atom(&mut self, atom: &Atom<'z>) {match atom {Atom::Literal(c) => {// In non-unicode mode, supplementary characters (>0xFFFF) must be// split into their UTF-16 surrogate pair halves.- if *c > 0xFFFF && !self.program.unicode && !self.program.unicode_sets {+ if *c > 0xFFFF && !self.unicode && !self.unicode_sets {let hi = ((*c - 0x10000) >> 10) + 0xD800;let lo = ((*c - 0x10000) & 0x3FF) + 0xDC00;- self.emit(Instruction::Char(hi));- self.emit(Instruction::Char(lo));+ self.emit(ZoneInstruction::Char(hi));+ self.emit(ZoneInstruction::Char(lo));} else {self.emit_char_maybe_case_fold(*c);}}Atom::Dot => {- self.emit(Instruction::AnyChar {+ self.emit(ZoneInstruction::AnyChar {dot_all: self.effective_dot_all,});}@@ -911,14 +1005,11 @@ impl Compiler {}Atom::BuiltinCharacterClass(bc) => {- self.emit(Instruction::BuiltinClass(*bc));+ self.emit(ZoneInstruction::BuiltinClass(*bc));}Atom::UnicodeProperty(up) => {- if self.program.unicode_sets- && !up.negated- && libunicode_rust::character_types::is_string_property(up.name)- {+ if self.unicode_sets && !up.negated && libunicode_rust::character_types::is_string_property(up.name) {self.emit_string_property_match(up.name, up.value);return;}@@ -930,9 +1021,9 @@ impl Compiler {let save_end = g.index * 2 + 1;// Clear captures inside this group before entering// (ECMA-262 requires captures to reset on each iteration).- self.emit(Instruction::Save(save_start));+ self.emit(ZoneInstruction::Save(save_start));self.compile_disjunction(&g.body);- self.emit(Instruction::Save(save_end));+ self.emit(ZoneInstruction::Save(save_end));}Atom::NonCapturingGroup(g) => {@@ -946,7 +1037,7 @@ impl Compiler {LookaroundKind::LookbehindPositive => (true, false),LookaroundKind::LookbehindNegative => (false, false),};- let look_start = self.emit(Instruction::LookStart {+ let look_start = self.emit(ZoneInstruction::LookStart {positive,forward,end: u32::MAX,@@ -958,37 +1049,37 @@ impl Compiler {self.backward = !forward;self.compile_disjunction(&la.body);self.backward = saved_backward;- self.emit(Instruction::LookEnd);+ self.emit(ZoneInstruction::LookEnd);let end = self.current_offset();// Patch the end offset.- self.program.instructions[look_start as usize] = Instruction::LookStart { positive, forward, end };+ self.instructions[look_start as usize] = ZoneInstruction::LookStart { positive, forward, end };}Atom::Backreference(br) => match br {Backreference::Index(n) => {- self.emit(Instruction::Backref(*n));+ self.emit(ZoneInstruction::Backref(*n));}Backreference::Named(name) => {- self.emit(Instruction::BackrefNamed(name.to_string()));+ self.emit(ZoneInstruction::BackrefNamed(name));}},Atom::Assertion(kind) => match kind {AssertionKind::StartOfInput => {- self.emit(Instruction::AssertStart {+ self.emit(ZoneInstruction::AssertStart {multiline: self.effective_multiline,});}AssertionKind::EndOfInput => {- self.emit(Instruction::AssertEnd {+ self.emit(ZoneInstruction::AssertEnd {multiline: self.effective_multiline,});}AssertionKind::WordBoundary => {- self.emit(Instruction::AssertWordBoundary);+ self.emit(ZoneInstruction::AssertWordBoundary);}AssertionKind::NonWordBoundary => {- self.emit(Instruction::AssertNonWordBoundary);+ self.emit(ZoneInstruction::AssertNonWordBoundary);}},@@ -1014,7 +1105,7 @@ impl Compiler {} else {None};- self.emit(Instruction::PushModifiers {+ self.emit(ZoneInstruction::PushModifiers {ignore_case,multiline,dot_all,@@ -1036,34 +1127,34 @@ impl Compiler {self.effective_ignore_case = saved_ignore_case;self.effective_multiline = saved_multiline;self.effective_dot_all = saved_dot_all;- self.emit(Instruction::PopModifiers);+ self.emit(ZoneInstruction::PopModifiers);}}}/// Lower `CharacterClass`./// <https://tc39.es/ecma262/#sec-compilecharacterclass>- fn compile_character_class(&mut self, cc: &CharacterClass) {+ fn compile_character_class(&mut self, cc: &CharacterClass<'z>) {match &cc.body {CharacterClassBody::Ranges(ranges) => {- let mut char_ranges = Vec::new();+ let mut char_ranges = ZoneVec::new_in(self.zone);let mut has_builtin = false;- let split_surrogates = !self.program.unicode && !self.program.unicode_sets;+ let split_surrogates = !self.unicode && !self.unicode_sets;for r in *ranges {match r {CharacterClassRange::Single(cp) => {if split_surrogates && *cp > 0xFFFF {let hi = ((*cp - 0x10000) >> 10) + 0xD800;let lo = ((*cp - 0x10000) & 0x3FF) + 0xDC00;- char_ranges.push(CharRange { start: hi, end: hi });- char_ranges.push(CharRange { start: lo, end: lo });+ char_ranges.push(CodePointRange { start: hi, end: hi });+ char_ranges.push(CodePointRange { start: lo, end: lo });} else {- char_ranges.push(CharRange { start: *cp, end: *cp });+ char_ranges.push(CodePointRange { start: *cp, end: *cp });}}CharacterClassRange::Range(lo, hi) => {- char_ranges.push(CharRange { start: *lo, end: *hi });+ char_ranges.push(CodePointRange { start: *lo, end: *hi });}CharacterClassRange::BuiltinClass(class)if let Some(builtin_ranges) = self.legacy_builtin_class_ranges(*class, cc.negated) =>@@ -1083,8 +1174,8 @@ impl Compiler {} else {// Sort and merge ranges for binary search in the VM.normalize_char_ranges(&mut char_ranges);- self.emit(Instruction::CharClass {- ranges: CharRanges::new(char_ranges),+ self.emit(ZoneInstruction::CharClass {+ ranges: char_ranges.into_slice(),negated: cc.negated,});}@@ -1095,7 +1186,7 @@ impl Compiler {}}- fn compile_complex_class(&mut self, ranges: &[CharacterClassRange], negated: bool) {+ fn compile_complex_class(&mut self, ranges: &[CharacterClassRange<'z>], negated: bool) {// For classes containing builtin escapes like [\d\w], we emit// a split-based disjunction of each component.// For negated classes with a single builtin, emit the negated builtin directly.@@ -1104,47 +1195,47 @@ impl Compiler {if ranges.len() == 1&& let CharacterClassRange::BuiltinClass(bc) = &ranges[0]{- self.emit(Instruction::BuiltinClass(bc.negated()));+ self.emit(ZoneInstruction::BuiltinClass(bc.negated()));return;}// General case: [^\d\w] = (?!\d|\w).let forward = !self.backward;- let look_start = self.emit(Instruction::LookStart {+ let look_start = self.emit(ZoneInstruction::LookStart {positive: false,forward,end: u32::MAX,});self.compile_class_components_as_disjunction(ranges);- self.emit(Instruction::LookEnd);+ self.emit(ZoneInstruction::LookEnd);let end = self.current_offset();- self.program.instructions[look_start as usize] = Instruction::LookStart {+ self.instructions[look_start as usize] = ZoneInstruction::LookStart {positive: false,forward,end,};- self.emit(Instruction::AnyChar { dot_all: true });+ self.emit(ZoneInstruction::AnyChar { dot_all: true });} else {self.compile_class_components_as_disjunction(ranges);}}- fn compile_class_components_as_disjunction(&mut self, ranges: &[CharacterClassRange]) {+ fn compile_class_components_as_disjunction(&mut self, ranges: &[CharacterClassRange<'z>]) {self.emit_split_chain(ranges, |s, r| s.compile_class_component(r));}- fn compile_class_component(&mut self, range: &CharacterClassRange) {+ fn compile_class_component(&mut self, range: &CharacterClassRange<'z>) {match range {CharacterClassRange::Single(cp) => {self.emit_char_maybe_case_fold(*cp);}CharacterClassRange::Range(lo, hi) => {- self.emit(Instruction::CharClass {- ranges: CharRanges::new(vec![CharRange { start: *lo, end: *hi }]),+ self.emit(ZoneInstruction::CharClass {+ ranges: self.zone.alloc_slice_copy(&[CodePointRange { start: *lo, end: *hi }]),negated: false,});}CharacterClassRange::BuiltinClass(bc) => {- self.emit(Instruction::BuiltinClass(*bc));+ self.emit(ZoneInstruction::BuiltinClass(*bc));}CharacterClassRange::UnicodeProperty(up) => {self.emit_unicode_property(up.negated, up.name, up.value);@@ -1152,68 +1243,58 @@ impl Compiler {}}- /// Try to extract a `SimpleMatch` for a single `ClassSetOperand` in the context of+ /// Try to extract a `ZoneSimpleMatch` for a single `ClassSetOperand` in the context of/// a `LazyLoop`/`GreedyLoop`. Returns `None` for operands that require multi-character/// matching (string literals) or set operations that can't be represented as a simple test.- fn try_simple_match_for_operand(operand: &ClassSetOperand) -> Option<SimpleMatch> {+ fn try_simple_match_for_operand(&self, operand: &ClassSetOperand<'z>) -> Option<ZoneSimpleMatch<'z>> {if crate::stack::is_exhausted() {return None;}match operand {- ClassSetOperand::Char(c) => Some(SimpleMatch::Char(*c)),- ClassSetOperand::Range(lo, hi) => Some(SimpleMatch::CharClass {- ranges: CharRanges::new(vec![CharRange { start: *lo, end: *hi }]),+ ClassSetOperand::Char(c) => Some(ZoneSimpleMatch::Char(*c)),+ ClassSetOperand::Range(lo, hi) => Some(ZoneSimpleMatch::CharClass {+ ranges: self.zone.alloc_slice_copy(&[CodePointRange { start: *lo, end: *hi }]),negated: false,}),- ClassSetOperand::BuiltinClass(bc) => Some(SimpleMatch::BuiltinClass(*bc)),+ ClassSetOperand::BuiltinClass(bc) => Some(ZoneSimpleMatch::BuiltinClass(*bc)),ClassSetOperand::UnicodeProperty(up) => {if libunicode_rust::character_types::is_string_property(up.name) {return None;}- Some(SimpleMatch::UnicodeProperty(Box::new(UnicodePropertyData {- negated: up.negated,- name: up.name.to_string(),- value: up.value.map(str::to_string),- resolved: None,- })))+ Some(ZoneSimpleMatch::UnicodeProperty(self.zone.alloc(*up)))}ClassSetOperand::NestedClass(cc) => match &cc.body {CharacterClassBody::Ranges(ranges_vec) => {- let mut ranges = Vec::new();+ let mut ranges = ZoneVec::new_in(self.zone);for r in *ranges_vec {match r {CharacterClassRange::Single(cp) => {- ranges.push(CharRange { start: *cp, end: *cp });+ ranges.push(CodePointRange { start: *cp, end: *cp });}CharacterClassRange::Range(lo, hi) => {- ranges.push(CharRange { start: *lo, end: *hi });+ ranges.push(CodePointRange { start: *lo, end: *hi });}_ => return None,}}normalize_char_ranges(&mut ranges);- Some(SimpleMatch::CharClass {- ranges: CharRanges::new(ranges),+ Some(ZoneSimpleMatch::CharClass {+ ranges: ranges.into_slice(),negated: cc.negated,})}CharacterClassBody::UnicodeSet(inner_expr) => {+ let ClassSetExpression::Union(inner_operands) = inner_expr else {+ return None;+ };if cc.negated {- let ClassSetExpression::Union(inner_operands) = inner_expr else {+ // NB: Only a single matcher can be negated.+ let [inner_operand] = inner_operands else {return None;};- let matchers: Option<Vec<SimpleMatch>> =- inner_operands.iter().map(Self::try_simple_match_for_operand).collect();- let matchers = matchers?;- Self::build_union_simple_match_negated(matchers)+ self.negate_simple_match(self.try_simple_match_for_operand(inner_operand)?)} else {- let ClassSetExpression::Union(inner_operands) = inner_expr else {- return None;- };- let matchers: Option<Vec<SimpleMatch>> =- inner_operands.iter().map(Self::try_simple_match_for_operand).collect();- let matchers = matchers?;- Self::build_union_simple_match(matchers)+ self.try_simple_match_for_union(inner_operands)}}},@@ -1221,40 +1302,51 @@ impl Compiler {}}- fn build_union_simple_match(matchers: Vec<SimpleMatch>) -> Option<SimpleMatch> {- let mut iter = matchers.into_iter();- let first = iter.next()?;- Some(iter.fold(first, |acc, m| SimpleMatch::Union(Box::new(acc), Box::new(m))))+ /// The union of the simple matchers of `operands`, folded from the left, if each operand has one.+ fn try_simple_match_for_union(&self, operands: &[ClassSetOperand<'z>]) -> Option<ZoneSimpleMatch<'z>> {+ let mut union = None;+ for operand in operands {+ let matcher = self.try_simple_match_for_operand(operand)?;+ union = Some(self.add_to_union(union, matcher));+ }+ union+ }++ /// `matcher`, or the union of `union` and `matcher` if there is a union so far.+ fn add_to_union(&self, union: Option<ZoneSimpleMatch<'z>>, matcher: ZoneSimpleMatch<'z>) -> ZoneSimpleMatch<'z> {+ match union {+ Some(union) => ZoneSimpleMatch::Union(self.zone.alloc(union), self.zone.alloc(matcher)),+ None => matcher,+ }}- fn negate_simple_match(matcher: SimpleMatch) -> Option<SimpleMatch> {+ fn negate_simple_match(&self, matcher: ZoneSimpleMatch<'z>) -> Option<ZoneSimpleMatch<'z>> {match matcher {- SimpleMatch::CharClass { ranges, negated } => Some(SimpleMatch::CharClass {+ ZoneSimpleMatch::CharClass { ranges, negated } => Some(ZoneSimpleMatch::CharClass {ranges,negated: !negated,}),- SimpleMatch::UnicodeProperty(mut data) => {- data.negated = !data.negated;- Some(SimpleMatch::UnicodeProperty(data))+ ZoneSimpleMatch::UnicodeProperty(data) => {+ Some(ZoneSimpleMatch::UnicodeProperty(self.zone.alloc(UnicodeProperty {+ negated: !data.negated,+ ..*data+ })))}_ => None,}}- fn build_union_simple_match_negated(matchers: Vec<SimpleMatch>) -> Option<SimpleMatch> {- if matchers.len() == 1 {- return Self::negate_simple_match(matchers.into_iter().next().unwrap());- }- None- }-- /// Try to build a `SimpleMatch` for a `CharacterClassBody::Ranges`.+ /// Try to build a `ZoneSimpleMatch` for a `CharacterClassBody::Ranges`.////// If all elements are plain chars/ranges, returns a single `CharClass`./// If the class is non-negated and contains builtins or Unicode properties,/// collects plain ranges into one `CharClass` and each builtin/property into its- /// own `SimpleMatch`, then folds them into a `Union`.- fn try_simple_match_for_ranges(&self, ranges_vec: &[CharacterClassRange], negated: bool) -> Option<SimpleMatch> {+ /// own `ZoneSimpleMatch`, then folds them into a `Union`.+ fn try_simple_match_for_ranges(+ &self,+ ranges_vec: &[CharacterClassRange<'z>],+ negated: bool,+ ) -> Option<ZoneSimpleMatch<'z>> {let has_complex = ranges_vec.iter().any(|r| match r {CharacterClassRange::BuiltinClass(class) => self.legacy_builtin_class_ranges(*class, negated).is_none(),CharacterClassRange::UnicodeProperty(_) => true,@@ -1262,17 +1354,17 @@ impl Compiler {});if !has_complex {- let mut ranges = Vec::new();+ let mut ranges = ZoneVec::new_in(self.zone);for r in ranges_vec {match r {CharacterClassRange::Single(c) => {- if *c > 0xFFFF && !self.program.unicode && !self.program.unicode_sets {+ if *c > 0xFFFF && !self.unicode && !self.unicode_sets {return None;}- ranges.push(CharRange { start: *c, end: *c });+ ranges.push(CodePointRange { start: *c, end: *c });}CharacterClassRange::Range(lo, hi) => {- ranges.push(CharRange { start: *lo, end: *hi });+ ranges.push(CodePointRange { start: *lo, end: *hi });}CharacterClassRange::BuiltinClass(class) => {ranges.extend_from_slice(self.legacy_builtin_class_ranges(*class, negated)?);@@ -1281,8 +1373,8 @@ impl Compiler {}}normalize_char_ranges(&mut ranges);- return Some(SimpleMatch::CharClass {- ranges: CharRanges::new(ranges),+ return Some(ZoneSimpleMatch::CharClass {+ ranges: ranges.into_slice(),negated,});}@@ -1291,58 +1383,56 @@ impl Compiler {return None;}- let mut plain_ranges: Vec<CharRange> = Vec::new();- let mut matchers: Vec<SimpleMatch> = Vec::new();+ let mut plain_ranges = ZoneVec::new_in(self.zone);+ let mut union = None;for r in ranges_vec {match r {CharacterClassRange::Single(c) => {- if *c > 0xFFFF && !self.program.unicode && !self.program.unicode_sets {+ if *c > 0xFFFF && !self.unicode && !self.unicode_sets {return None;}- plain_ranges.push(CharRange { start: *c, end: *c });+ plain_ranges.push(CodePointRange { start: *c, end: *c });}CharacterClassRange::Range(lo, hi) => {- plain_ranges.push(CharRange { start: *lo, end: *hi });+ plain_ranges.push(CodePointRange { start: *lo, end: *hi });}CharacterClassRange::BuiltinClass(bc) => {- matchers.push(SimpleMatch::BuiltinClass(*bc));+ union = Some(self.add_to_union(union, ZoneSimpleMatch::BuiltinClass(*bc)));}CharacterClassRange::UnicodeProperty(up) => {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.to_string(),- value: up.value.map(str::to_string),- resolved: None,- })));+ union = Some(self.add_to_union(union, ZoneSimpleMatch::UnicodeProperty(self.zone.alloc(*up))));}}}if !plain_ranges.is_empty() {normalize_char_ranges(&mut plain_ranges);- matchers.push(SimpleMatch::CharClass {- ranges: CharRanges::new(plain_ranges),+ let plain = ZoneSimpleMatch::CharClass {+ ranges: plain_ranges.into_slice(),negated: false,- });+ };+ union = Some(self.add_to_union(union, plain));}- Self::build_union_simple_match(matchers)+ union}- /// Try to build a `SimpleMatch` for a `/v`-mode character class `UnicodeSet` body.+ /// Try to build a `ZoneSimpleMatch` for a `/v`-mode character class `UnicodeSet` body.///- /// For unions that can't be collapsed into a flat range set, we try to build a `SimpleMatch::Union`+ /// For unions that can't be collapsed into a flat range set, we try to build a `ZoneSimpleMatch::Union`/// so that quantifiers can still use the optimized `GreedyLoop`/`LazyLoop` path.- fn try_simple_match_for_unicode_set(&self, expr: &ClassSetExpression, negated: bool) -> Option<SimpleMatch> {- if let Some(ranges) = Self::try_extract_union_ranges(expr) {- let mut sorted = ranges;- normalize_char_ranges(&mut sorted);- return Some(SimpleMatch::CharClass {- ranges: CharRanges::new(sorted),+ fn try_simple_match_for_unicode_set(+ &self,+ expr: &ClassSetExpression<'z>,+ negated: bool,+ ) -> Option<ZoneSimpleMatch<'z>> {+ if let Some(ranges) = self.try_extract_union_ranges(expr) {+ return Some(ZoneSimpleMatch::CharClass {+ ranges: ranges.into_slice(),negated,});}@@ -1359,65 +1449,73 @@ impl Compiler {return None;}- let matchers: Option<Vec<SimpleMatch>> = operands.iter().map(Self::try_simple_match_for_operand).collect();- let matchers = matchers?;- Self::build_union_simple_match(matchers)+ self.try_simple_match_for_union(operands)}- fn try_extract_union_ranges(expr: &ClassSetExpression) -> Option<Vec<CharRange>> {- if crate::stack::is_exhausted() {+ /// The sorted and merged ranges of a union of plain characters and ranges.+ fn try_extract_union_ranges(&self, expr: &ClassSetExpression<'z>) -> Option<ZoneVec<'z, CodePointRange>> {+ let mut ranges = ZoneVec::new_in(self.zone);+ if !Self::collect_union_ranges(expr, &mut ranges) {return None;}+ normalize_char_ranges(&mut ranges);+ Some(ranges)+ }++ /// Adds the ranges of a union of plain characters and ranges to `ranges`, and returns whether `expr` is one.+ fn collect_union_ranges(expr: &ClassSetExpression<'z>, ranges: &mut ZoneVec<'z, CodePointRange>) -> bool {+ if crate::stack::is_exhausted() {+ return false;+ }let ClassSetExpression::Union(operands) = expr else {- return None;+ return false;};- let mut ranges = Vec::new();for operand in *operands {match operand {ClassSetOperand::Char(c) => {- ranges.push(CharRange { start: *c, end: *c });+ ranges.push(CodePointRange { start: *c, end: *c });}ClassSetOperand::Range(lo, hi) => {- ranges.push(CharRange { start: *lo, end: *hi });+ ranges.push(CodePointRange { start: *lo, end: *hi });}ClassSetOperand::NestedClass(cc) => match &cc.body {CharacterClassBody::Ranges(class_ranges) => {for r in *class_ranges {match r {CharacterClassRange::Single(cp) => {- ranges.push(CharRange { start: *cp, end: *cp });+ ranges.push(CodePointRange { start: *cp, end: *cp });}CharacterClassRange::Range(lo, hi) => {- ranges.push(CharRange { start: *lo, end: *hi });+ ranges.push(CodePointRange { start: *lo, end: *hi });}CharacterClassRange::BuiltinClass(_) | CharacterClassRange::UnicodeProperty(_) => {- return None;+ return false;}}}if cc.negated {- return None;+ return false;}}CharacterClassBody::UnicodeSet(inner_expr) => {if cc.negated {- return None;+ return false;+ }+ if !Self::collect_union_ranges(inner_expr, ranges) {+ return false;}- let inner = Self::try_extract_union_ranges(inner_expr)?;- ranges.extend(inner);}},ClassSetOperand::BuiltinClass(_)| ClassSetOperand::UnicodeProperty(_)| ClassSetOperand::StringLiteral(_) => {- return None;+ return false;}}}- normalize_char_ranges(&mut ranges);- Some(ranges)+ true}/// Lower a `/v` character class expression.@@ -1426,19 +1524,19 @@ impl Compiler {/// once class operands may match strings, complementing them is no longer/// a simple single-code-point set operation./// <https://tc39.es/ecma262/#sec-compilecharacterclass>- fn compile_unicode_set_class(&mut self, expr: &ClassSetExpression, negated: bool) {+ fn compile_unicode_set_class(&mut self, expr: &ClassSetExpression<'z>, negated: bool) {if matches!(expr, ClassSetExpression::Union(operands) if operands.is_empty()) {if negated {- self.emit(Instruction::AnyChar { dot_all: true });+ self.emit(ZoneInstruction::AnyChar { dot_all: true });} else {- self.emit(Instruction::Fail);+ self.emit(ZoneInstruction::Fail);}return;}- if let Some(ranges) = Self::try_extract_union_ranges(expr) {- self.emit(Instruction::CharClass {- ranges: CharRanges::new(ranges),+ if let Some(ranges) = self.try_extract_union_ranges(expr) {+ self.emit(ZoneInstruction::CharClass {+ ranges: ranges.into_slice(),negated,});return;@@ -1446,20 +1544,20 @@ impl Compiler {if negated {let forward = !self.backward;- let look_start = self.emit(Instruction::LookStart {+ let look_start = self.emit(ZoneInstruction::LookStart {positive: false,forward,end: u32::MAX,});self.compile_class_set_expression(expr);- self.emit(Instruction::LookEnd);+ self.emit(ZoneInstruction::LookEnd);let end = self.current_offset();- self.program.instructions[look_start as usize] = Instruction::LookStart {+ self.instructions[look_start as usize] = ZoneInstruction::LookStart {positive: false,forward,end,};- self.emit(Instruction::AnyChar { dot_all: true });+ self.emit(ZoneInstruction::AnyChar { dot_all: true });} else {self.compile_class_set_expression(expr);}@@ -1468,32 +1566,35 @@ impl Compiler {/// Lower `ClassSetExpression`./// - <https://tc39.es/ecma262/#sec-compilecharacterclass>/// - <https://tc39.es/ecma262/#sec-compileclasssetstring>- fn compile_class_set_expression(&mut self, expr: &ClassSetExpression) {+ fn compile_class_set_expression(&mut self, expr: &ClassSetExpression<'z>) {// NB: Compile each exact match length separately, longest first, so// intersection/subtraction only compare equal-length alternatives.- let mut lengths: Vec<_> = self.class_set_expression_lengths(expr).into_iter().collect();+ let mut lengths = ZoneVec::new_in(self.zone);+ self.collect_class_set_expression_lengths(expr, &mut lengths);lengths.sort_unstable_by(|a, b| b.cmp(a));if lengths.is_empty() {- self.emit(Instruction::Fail);+ self.emit(ZoneInstruction::Fail);return;}self.emit_split_chain(&lengths, |s, len| s.compile_class_set_expression_at_length(expr, *len));}- fn compile_class_set_expression_at_length(&mut self, expr: &ClassSetExpression, length: usize) {+ fn compile_class_set_expression_at_length(&mut self, expr: &ClassSetExpression<'z>, length: usize) {if self.is_out_of_stack() {return;}match expr {ClassSetExpression::Union(operands) => {- let filtered: Vec<&ClassSetOperand> = operands- .iter()- .filter(|operand| self.class_set_operand_lengths(operand).contains(&length))- .collect();+ let mut filtered = ZoneVec::new_in(self.zone);+ for operand in *operands {+ if self.class_set_operand_has_length(operand, length) {+ filtered.push(operand);+ }+ }if filtered.is_empty() {- self.emit(Instruction::Fail);+ self.emit(ZoneInstruction::Fail);return;}self.emit_split_chain(&filtered, |s, operand| {@@ -1502,20 +1603,20 @@ impl Compiler {}ClassSetExpression::Intersection(operands) => {let Some((first, rest)) = operands.split_first() else {- self.emit(Instruction::Fail);+ self.emit(ZoneInstruction::Fail);return;};self.compile_class_set_operand_at_length(first, length);for operand in rest {- if !self.class_set_operand_lengths(operand).contains(&length) {- self.emit(Instruction::Fail);+ if !self.class_set_operand_has_length(operand, length) {+ self.emit(ZoneInstruction::Fail);return;}// NB: In backward mode the already-consumed text sits to// the right of the current position, so these checks need// to flip from lookbehind to lookahead.let forward = self.backward;- let look_start = self.emit(Instruction::LookStart {+ let look_start = self.emit(ZoneInstruction::LookStart {positive: true,forward,end: u32::MAX,@@ -1524,9 +1625,9 @@ impl Compiler {self.backward = !forward;self.compile_class_set_operand_at_length(operand, length);self.backward = saved_backward;- self.emit(Instruction::LookEnd);+ self.emit(ZoneInstruction::LookEnd);let end = self.current_offset();- self.program.instructions[look_start as usize] = Instruction::LookStart {+ self.instructions[look_start as usize] = ZoneInstruction::LookStart {positive: true,forward,end,@@ -1535,16 +1636,16 @@ impl Compiler {}ClassSetExpression::Subtraction(operands) => {let Some((first, rest)) = operands.split_first() else {- self.emit(Instruction::Fail);+ self.emit(ZoneInstruction::Fail);return;};self.compile_class_set_operand_at_length(first, length);for operand in rest {- if !self.class_set_operand_lengths(operand).contains(&length) {+ if !self.class_set_operand_has_length(operand, length) {continue;}let forward = self.backward;- let look_start = self.emit(Instruction::LookStart {+ let look_start = self.emit(ZoneInstruction::LookStart {positive: false,forward,end: u32::MAX,@@ -1553,9 +1654,9 @@ impl Compiler {self.backward = !forward;self.compile_class_set_operand_at_length(operand, length);self.backward = saved_backward;- self.emit(Instruction::LookEnd);+ self.emit(ZoneInstruction::LookEnd);let end = self.current_offset();- self.program.instructions[look_start as usize] = Instruction::LookStart {+ self.instructions[look_start as usize] = ZoneInstruction::LookStart {positive: false,forward,end,@@ -1565,29 +1666,29 @@ impl Compiler {}}- fn compile_class_set_operand_at_length(&mut self, operand: &ClassSetOperand, length: usize) {+ fn compile_class_set_operand_at_length(&mut self, operand: &ClassSetOperand<'z>, length: usize) {match operand {ClassSetOperand::Char(c) => {if length != 1 {- self.emit(Instruction::Fail);+ self.emit(ZoneInstruction::Fail);return;}self.emit_char_maybe_case_fold(*c);}ClassSetOperand::Range(lo, hi) => {if length != 1 {- self.emit(Instruction::Fail);+ self.emit(ZoneInstruction::Fail);return;}- self.emit(Instruction::CharClass {- ranges: CharRanges::new(vec![CharRange { start: *lo, end: *hi }]),+ self.emit(ZoneInstruction::CharClass {+ ranges: self.zone.alloc_slice_copy(&[CodePointRange { start: *lo, end: *hi }]),negated: false,});}ClassSetOperand::NestedClass(cc) => {if cc.negated {if length != 1 {- self.emit(Instruction::Fail);+ self.emit(ZoneInstruction::Fail);return;}self.compile_character_class(cc);@@ -1597,7 +1698,7 @@ impl Compiler {match &cc.body {CharacterClassBody::Ranges(_) => {if length != 1 {- self.emit(Instruction::Fail);+ self.emit(ZoneInstruction::Fail);return;}self.compile_character_class(cc);@@ -1609,22 +1710,23 @@ impl Compiler {}ClassSetOperand::BuiltinClass(bc) => {if length != 1 {- self.emit(Instruction::Fail);+ self.emit(ZoneInstruction::Fail);return;}- self.emit(Instruction::BuiltinClass(*bc));+ self.emit(ZoneInstruction::BuiltinClass(*bc));}ClassSetOperand::UnicodeProperty(up) => {- if self.program.unicode_sets- && !up.negated- && libunicode_rust::character_types::is_string_property(up.name)- {+ if self.unicode_sets && !up.negated && libunicode_rust::character_types::is_string_property(up.name) {if length == 1 {self.emit_unicode_property(up.negated, up.name, up.value);} else {- let strings = Self::get_string_property_strings_of_length(up.name, length);+ let data = self.string_property_data(up.name);+ let strings = ZoneVec::from_iter_in(+ packed_strings(data).filter(|string| string.len() == length),+ self.zone,+ );if strings.is_empty() {- self.emit(Instruction::Fail);+ self.emit(ZoneInstruction::Fail);return;}self.emit_split_chain(&strings, |s, string| s.emit_code_point_string(string));@@ -1632,14 +1734,14 @@ impl Compiler {return;}if length != 1 {- self.emit(Instruction::Fail);+ self.emit(ZoneInstruction::Fail);return;}self.emit_unicode_property(up.negated, up.name, up.value);}ClassSetOperand::StringLiteral(chars) => {if chars.len() != length {- self.emit(Instruction::Fail);+ self.emit(ZoneInstruction::Fail);return;}self.emit_char_string(chars);diff --git a/Libraries/LibRegex/Rust/src/copy_out.rs b/Libraries/LibRegex/Rust/src/copy_out.rsnew file mode 100644index 00000000000..c13286e7394--- /dev/null+++ b/Libraries/LibRegex/Rust/src/copy_out.rs@@ -0,0 +1,165 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The copy of what a regex keeps of its compile, out of the zone of the compile and at its final size: the program+//! that the VM runs and the literals that let a search skip the VM.++use crate::ast::UnicodeProperty;+use crate::bytecode::CharRange;+use crate::bytecode::CharRanges;+use crate::bytecode::Instruction;+use crate::bytecode::NamedGroupEntry;+use crate::bytecode::Program;+use crate::bytecode::SimpleMatch;+use crate::bytecode::UnicodePropertyData;+use crate::compiler;+use crate::literal_hints::RequiredLiteral;+use crate::vm;+use crate::zone_program::CodePointRange;+use crate::zone_program::ZoneInstruction;+use crate::zone_program::ZoneProgram;+use crate::zone_program::ZoneSimpleMatch;++pub(crate) fn program(program: &ZoneProgram<'_>) -> Program {+ let mut instructions = Vec::with_capacity(program.instructions.len());+ instructions.extend(program.instructions.iter().map(instruction));+ let mut named_groups = Vec::with_capacity(program.named_groups.len());+ named_groups.extend(program.named_groups.iter().map(|group| NamedGroupEntry {+ name: group.name.to_string(),+ index: group.index,+ }));+ Program {+ instructions,+ capture_count: program.capture_count,+ register_count: program.register_count,+ unicode: program.unicode,+ unicode_sets: program.unicode_sets,+ ignore_case: program.ignore_case,+ multiline: program.multiline,+ dot_all: program.dot_all,+ named_groups,+ }+}++fn instruction(instruction: &ZoneInstruction<'_>) -> Instruction {+ match *instruction {+ ZoneInstruction::Char(cp) => Instruction::Char(cp),+ ZoneInstruction::CharNoCase(lhs, rhs) => Instruction::CharNoCase(lhs, rhs),+ ZoneInstruction::AnyChar { dot_all } => Instruction::AnyChar { dot_all },+ ZoneInstruction::CharClass { ranges, negated } => Instruction::CharClass {+ ranges: char_ranges(ranges),+ negated,+ },+ ZoneInstruction::BuiltinClass(class) => Instruction::BuiltinClass(class),+ ZoneInstruction::UnicodeProperty(property) => Instruction::UnicodeProperty(unicode_property(property)),+ ZoneInstruction::Jump(target) => Instruction::Jump(target),+ ZoneInstruction::Split { prefer, other } => Instruction::Split { prefer, other },+ ZoneInstruction::Save(reg) => Instruction::Save(reg),+ ZoneInstruction::ClearRegister(reg) => Instruction::ClearRegister(reg),+ ZoneInstruction::AssertStart { multiline } => Instruction::AssertStart { multiline },+ ZoneInstruction::AssertEnd { multiline } => Instruction::AssertEnd { multiline },+ ZoneInstruction::AssertWordBoundary => Instruction::AssertWordBoundary,+ ZoneInstruction::AssertNonWordBoundary => Instruction::AssertNonWordBoundary,+ ZoneInstruction::Match => Instruction::Match,+ ZoneInstruction::Fail => Instruction::Fail,+ ZoneInstruction::Backref(index) => Instruction::Backref(index),+ ZoneInstruction::BackrefNamed(name) => Instruction::BackrefNamed(name.to_string()),+ ZoneInstruction::RepeatStart { counter_reg } => Instruction::RepeatStart { counter_reg },+ ZoneInstruction::RepeatCheck {+ counter_reg,+ min,+ max,+ body,+ greedy,+ } => Instruction::RepeatCheck {+ counter_reg,+ min,+ max,+ body,+ greedy,+ },+ ZoneInstruction::LookStart { positive, forward, end } => Instruction::LookStart { positive, forward, end },+ ZoneInstruction::LookEnd => Instruction::LookEnd,+ ZoneInstruction::PushModifiers {+ ignore_case,+ multiline,+ dot_all,+ } => Instruction::PushModifiers {+ ignore_case,+ multiline,+ dot_all,+ },+ ZoneInstruction::PopModifiers => Instruction::PopModifiers,+ ZoneInstruction::StringPropertyMatch { strings, property } => Instruction::StringPropertyMatch {+ strings: strings.into(),+ property: unicode_property(property),+ },+ ZoneInstruction::ProgressCheck { reg, clear_captures } => Instruction::ProgressCheck {+ reg,+ clear_captures: clear_captures.to_vec(),+ },+ ZoneInstruction::GreedyLoop { matcher, min, max } => Instruction::GreedyLoop {+ matcher: simple_match(&matcher),+ min,+ max,+ },+ ZoneInstruction::LazyLoop { matcher, min, max } => Instruction::LazyLoop {+ matcher: simple_match(&matcher),+ min,+ max,+ },+ }+}++fn simple_match(matcher: &ZoneSimpleMatch<'_>) -> SimpleMatch {+ match *matcher {+ ZoneSimpleMatch::AnyChar { dot_all } => SimpleMatch::AnyChar { dot_all },+ ZoneSimpleMatch::Char(cp) => SimpleMatch::Char(cp),+ ZoneSimpleMatch::CharNoCase(lhs, rhs) => SimpleMatch::CharNoCase(lhs, rhs),+ ZoneSimpleMatch::CharClass { ranges, negated } => SimpleMatch::CharClass {+ ranges: char_ranges(ranges),+ negated,+ },+ ZoneSimpleMatch::BuiltinClass(class) => SimpleMatch::BuiltinClass(class),+ ZoneSimpleMatch::UnicodeProperty(property) => SimpleMatch::UnicodeProperty(unicode_property(property)),+ ZoneSimpleMatch::Union(lhs, rhs) => {+ SimpleMatch::Union(Box::new(simple_match(lhs)), Box::new(simple_match(rhs)))+ }+ }+}++fn char_ranges(ranges: &[CodePointRange]) -> CharRanges {+ let mut copy = Vec::with_capacity(ranges.len());+ copy.extend(ranges.iter().map(|range| CharRange {+ start: range.start,+ end: range.end,+ }));+ CharRanges::new(copy)+}++/// The data of a Unicode property match, with the property resolved to an ICU enum ID. This allows O(1) trie lookups+/// at match time instead of string-based resolution.+fn unicode_property(property: &UnicodeProperty<'_>) -> Box<UnicodePropertyData> {+ Box::new(UnicodePropertyData {+ negated: property.negated,+ name: property.name.to_string(),+ value: property.value.map(str::to_string),+ resolved: compiler::resolve_property(property.name, property.value),+ })+}++pub(crate) fn required_literal_hint(hint: &RequiredLiteral<'_>) -> vm::RequiredLiteralHint {+ vm::RequiredLiteralHint {+ literal: hint.literal.to_vec(),+ ascii_case_insensitive: hint.ascii_case_insensitive,+ }+}++pub(crate) fn literal_alternatives(alternatives: &[&[u16]]) -> Vec<Vec<u16>> {+ let mut copy = Vec::with_capacity(alternatives.len());+ copy.extend(alternatives.iter().map(|alternative| alternative.to_vec()));+ copy+}diff --git a/Libraries/LibRegex/Rust/src/lib.rs b/Libraries/LibRegex/Rust/src/lib.rsindex ff65cfd7bdc..0d71512682a 100644--- a/Libraries/LibRegex/Rust/src/lib.rs+++ b/Libraries/LibRegex/Rust/src/lib.rs@@ -16,9 +16,12 @@ mod rust_panic;pub mod ast;pub mod bytecode;pub mod compiler;+mod copy_out;pub mod ffi;+pub mod literal_hints;pub mod parser;pub mod regex;mod stack;pub mod vm;mod work_zone;+pub mod zone_program;diff --git a/Libraries/LibRegex/Rust/src/literal_hints.rs b/Libraries/LibRegex/Rust/src/literal_hints.rsnew file mode 100644index 00000000000..d8f8be270f1--- /dev/null+++ b/Libraries/LibRegex/Rust/src/literal_hints.rs@@ -0,0 +1,530 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The literals of a pattern that let a search skip the VM: a literal that each match contains, and the literal, the+//! `\bliteral\b` and the literal alternatives that a whole pattern can be. They come from the syntax tree, and they+//! and the work data of their search are in the zone of the compile.++use ak::Zone;+use ak::ZoneMap;+use ak::ZoneVec;++use crate::ast::Alternative;+use crate::ast::AssertionKind;+use crate::ast::Atom;+use crate::ast::Disjunction;+use crate::ast::Flags;+use crate::ast::Pattern;+use crate::ast::Term;++const MAX_REQUIRED_LITERAL_RUNS: usize = 16;+const MAX_REQUIRED_LITERAL_CODE_UNITS: usize = 64;++/// A literal that each match of a pattern contains.+#[derive(Debug, Clone, Copy)]+pub struct RequiredLiteral<'z> {+ pub literal: &'z [u16],+ pub ascii_case_insensitive: bool,+}++#[inline(always)]+pub fn is_ascii_word_code_unit(ch: u16) -> bool {+ matches!(ch, 0x30..=0x39 | 0x41..=0x5A | 0x5F | 0x61..=0x7A)+}++/// Encode a Unicode code point as WTF-16 into `out`.+/// Returns `None` if the code point is out of range (> U+10FFFF).+fn append_code_point_wtf16(out: &mut ZoneVec<'_, u16>, cp: u32) -> Option<()> {+ if cp <= 0xFFFF {+ out.push(cp as u16);+ return Some(());+ }+ if cp > 0x10FFFF {+ return None;+ }+ let cp = cp - 0x10000;+ out.push(0xD800 | ((cp >> 10) as u16));+ out.push(0xDC00 | ((cp & 0x3FF) as u16));+ Some(())+}++/// A run of code units of the literals of a required literal analysis: `len` of its units from `start` on.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+struct Run {+ start: usize,+ len: usize,+}++impl Run {+ fn units(self, units: &[u16]) -> &[u16] {+ &units[self.start..self.start + self.len]+ }+}++/// The search for a literal that each match contains.+///+/// The analysis of a node of the syntax tree gives its exact literal, if each match of the node is that literal, and+/// its guaranteed runs, literals that each match of the node contains. The exact literal of a node is all the code+/// units that its analysis adds to `units`, so the exact literals of the terms of an alternative add up to the exact+/// literal of the alternative where they are, and the units of a node that no run refers to any more are dropped.+struct RequiredLiteralAnalysis<'z> {+ zone: &'z Zone,+ flags: Flags,+ /// The code units of the literals, which the runs are parts of.+ units: ZoneVec<'z, u16>,+ /// The guaranteed runs of the nodes that are being analyzed, the ones of the innermost node last.+ runs: ZoneVec<'z, Run>,+ /// Room for the common runs of the alternatives of a disjunction.+ common_runs: ZoneVec<'z, Run>,+ /// Room for the windows of a run that are in another run.+ matches: ZoneVec<'z, usize>,+}++pub fn extract_required_literal_hint<'z>(+ zone: &'z Zone,+ pattern: &Pattern<'z>,+ flags: Flags,+) -> Option<RequiredLiteral<'z>> {+ let mut analysis = RequiredLiteralAnalysis {+ zone,+ flags,+ units: ZoneVec::new_in(zone),+ runs: ZoneVec::new_in(zone),+ common_runs: ZoneVec::new_in(zone),+ matches: ZoneVec::new_in(zone),+ };+ analysis.analyze_disjunction(&pattern.disjunction);+ let run = *analysis.runs.iter().max_by_key(|run| run.len)?;+ let literal = run.units(analysis.units.into_slice());+ if literal.is_empty() {+ return None;+ }++ let ascii_case_insensitive = if flags.ignore_case {+ if flags.unicode || flags.unicode_sets || literal.iter().any(|ch| *ch > 0x7F) {+ return None;+ }+ true+ } else {+ false+ };++ Some(RequiredLiteral {+ literal,+ ascii_case_insensitive,+ })+}++impl<'z> RequiredLiteralAnalysis<'z> {+ /// The exact literal of the units from `start` on.+ fn exact_from(&self, start: usize) -> Run {+ Run {+ start,+ len: self.units.len() - start,+ }+ }++ fn exact_units(&self, exact: Option<Run>) -> Option<&[u16]> {+ exact.map(|run| run.units(&self.units))+ }++ /// Each analysis returns the exact literal of its node, and leaves the guaranteed runs of the node after the runs+ /// that were there.+ fn analyze_disjunction(&mut self, disjunction: &Disjunction<'z>) -> Option<Run> {+ if crate::stack::is_exhausted() {+ return None;+ }+ let first_run = self.runs.len();+ let Some((first, rest)) = disjunction.alternatives.split_first() else {+ return Some(self.exact_from(self.units.len()));+ };++ let mut exact_literal = self.analyze_alternative(first);+ // NB: The runs of the other alternatives are parts of the runs of the first one, so their units can go.+ let end_of_first = self.units.len();+ for alternative in rest {+ let first_other_run = self.runs.len();+ let other_exact_literal = self.analyze_alternative(alternative);+ if self.exact_units(exact_literal) != self.exact_units(other_exact_literal) {+ exact_literal = None;+ }+ self.intersect_required_literal_runs(first_run, first_other_run);+ self.units.truncate(end_of_first);+ if self.runs.len() == first_run && exact_literal.is_none() {+ break;+ }+ }++ if let Some(literal) = exact_literal+ && literal.len != 0+ {+ self.runs.push(literal);+ }++ self.prune_required_literal_runs(first_run);+ exact_literal+ }++ fn analyze_alternative(&mut self, alternative: &Alternative<'z>) -> Option<Run> {+ let first_run = self.runs.len();+ let start = self.units.len();+ let mut is_exact = true;+ let mut current_run_start = start;++ for term in alternative.terms {+ let term_start = self.units.len();+ let first_term_run = self.runs.len();+ if self.analyze_required_literal_term(term).is_some() {+ // NB: The exact literal of the term continues the current run where it is, and covers its runs.+ self.runs.truncate(first_term_run);+ continue;+ }++ is_exact = false;+ if term_start != current_run_start {+ self.runs.push(Run {+ start: current_run_start,+ len: term_start - current_run_start,+ });+ }+ current_run_start = self.units.len();+ }++ if self.units.len() != current_run_start {+ let current_run = self.exact_from(current_run_start);+ self.runs.push(current_run);+ }++ let exact_literal = is_exact.then(|| self.exact_from(start));+ if let Some(literal) = exact_literal+ && literal.len != 0+ {+ self.runs.push(literal);+ }++ self.prune_required_literal_runs(first_run);+ exact_literal+ }++ fn analyze_required_literal_term(&mut self, term: &Term<'z>) -> Option<Run> {+ let start = self.units.len();+ let first_run = self.runs.len();+ let atom_exact_literal = self.analyze_required_literal_atom(&term.atom);+ let Some(quantifier) = &term.quantifier else {+ return atom_exact_literal;+ };+ if quantifier.min == 0 {+ self.runs.truncate(first_run);+ self.units.truncate(start);+ return None;+ }++ let mut exact_literal = None;+ if let Some(literal) = atom_exact_literal {+ let repeated_len = literal.len.saturating_mul(quantifier.min as usize);+ // NB: The literal is the last of the units, so its repetitions follow it.+ let repeated_guaranteed_run = Run {+ start: literal.start,+ len: repeated_len.min(MAX_REQUIRED_LITERAL_CODE_UNITS),+ };+ for index in literal.len..repeated_guaranteed_run.len {+ let unit = self.units[literal.start + index - literal.len];+ self.units.push(unit);+ }+ // Preserve exact-literal tracking only while the full literal fits in the+ // retained hint budget. Longer exact runs still contribute via prefixes.+ if quantifier.max == Some(quantifier.min)+ && literal+ .len+ .checked_mul(quantifier.min as usize)+ .is_some_and(|len| len <= MAX_REQUIRED_LITERAL_CODE_UNITS)+ {+ exact_literal = Some(repeated_guaranteed_run);+ }+ if repeated_guaranteed_run.len != 0 {+ self.runs.push(repeated_guaranteed_run);+ }+ }++ self.prune_required_literal_runs(first_run);+ exact_literal+ }++ fn analyze_required_literal_atom(&mut self, atom: &Atom<'z>) -> Option<Run> {+ match atom {+ Atom::Literal(cp) => self.analyze_literal(*cp),+ Atom::Group(group) => self.analyze_disjunction(&group.body),+ Atom::NonCapturingGroup(group) => self.analyze_disjunction(&group.body),+ Atom::ModifierGroup(group) => {+ if group.add_flags.ignore_case || group.remove_flags.ignore_case {+ None+ } else {+ self.analyze_disjunction(&group.body)+ }+ }+ Atom::Assertion(_) | Atom::Lookaround(_) => Some(self.exact_from(self.units.len())),+ Atom::Dot+ | Atom::CharacterClass(_)+ | Atom::BuiltinCharacterClass(_)+ | Atom::UnicodeProperty(_)+ | Atom::Backreference(_) => None,+ }+ }++ fn analyze_literal(&mut self, cp: u32) -> Option<Run> {+ if is_unsafe_unicode_literal(cp, self.flags) {+ return None;+ }++ let start = self.units.len();+ append_code_point_wtf16(&mut self.units, cp)?;+ let literal = self.exact_from(start);+ self.runs.push(literal);+ Some(literal)+ }++ /// Replaces the runs from `first_run` on, which are the runs of one node up to `first_other_run` and those of+ /// another node from there on, with the runs that both nodes are sure to have. Those are parts of the runs of+ /// the first node.+ fn intersect_required_literal_runs(&mut self, first_run: usize, first_other_run: usize) {+ let Self {+ zone,+ units,+ runs,+ common_runs,+ matches,+ ..+ } = self;+ let units = units.as_slice();+ let zone: &Zone = zone;+ let mut windows = ZoneMap::new_in(zone);+ common_runs.clear();+ for left in &runs[first_run..first_other_run] {+ for right in &runs[first_other_run..] {+ maximal_common_substrings(units, *left, *right, common_runs, matches, &mut windows);+ }+ }+ prune_required_literal_runs(units, common_runs, 0);+ runs.truncate(first_run);+ runs.extend_from_slice(common_runs);+ }++ fn prune_required_literal_runs(&mut self, first_run: usize) {+ prune_required_literal_runs(&self.units, &mut self.runs, first_run);+ }+}++/// Adds the longest substrings of `lhs` that are in `rhs` to `out`, as runs of `lhs`.+fn maximal_common_substrings<'a>(+ units: &'a [u16],+ lhs: Run,+ rhs: Run,+ out: &mut ZoneVec<'_, Run>,+ matches: &mut ZoneVec<'_, usize>,+ windows: &mut ZoneMap<'_, &'a [u16], Option<usize>>,+) {+ let max_len = lhs.len.min(rhs.len).min(MAX_REQUIRED_LITERAL_CODE_UNITS);+ let lhs_is_shorter = lhs.len <= rhs.len;+ let (shorter, longer) = if lhs_is_shorter { (lhs, rhs) } else { (rhs, lhs) };+ let first_substring = out.len();++ for len in (1..=max_len).rev() {+ // Required-literal hints keep at most 64 code units, so intersect+ // fixed-size windows instead of walking every start-position pair.+ // NB: Each window that both runs have gives one start in `lhs`, the first one.+ windows.clear();+ for (offset, window) in shorter.units(units).windows(len).enumerate() {+ windows.entry(window).or_insert(Some(shorter.start + offset));+ }+ matches.clear();+ for (offset, window) in longer.units(units).windows(len).enumerate() {+ if let Some(pending) = windows.get_mut(&window)+ && let Some(start) = pending.take()+ {+ matches.push(if lhs_is_shorter { start } else { longer.start + offset });+ }+ }++ matches.sort_unstable_by(|lhs, rhs| units[*lhs..*lhs + len].cmp(&units[*rhs..*rhs + len]));+ for start in matches.iter() {+ let candidate = Run { start: *start, len };+ if out[first_substring..]+ .iter()+ .any(|existing| contains_literal_subslice(existing.units(units), candidate.units(units)))+ {+ continue;+ }+ out.push(candidate);+ if out.len() - first_substring == MAX_REQUIRED_LITERAL_RUNS {+ return;+ }+ }+ }+ prune_required_literal_runs(units, out, first_substring);+}++/// Sorts the runs from `first_run` on, longest first, and keeps the first ones that no run before them contains.+fn prune_required_literal_runs(units: &[u16], runs: &mut ZoneVec<'_, Run>, first_run: usize) {+ // NB: Runs that are the same are equal in each way that counts, so their order does not matter.+ runs[first_run..].sort_unstable_by(|lhs, rhs| {+ rhs.len+ .cmp(&lhs.len)+ .then_with(|| lhs.units(units).cmp(rhs.units(units)))+ });++ let mut pruned_count = first_run;+ for index in first_run..runs.len() {+ let run = runs[index];+ if run.len == 0 {+ continue;+ }+ if runs[first_run..pruned_count]+ .iter()+ .any(|existing| contains_literal_subslice(existing.units(units), run.units(units)))+ {+ continue;+ }+ runs[pruned_count] = run;+ pruned_count += 1;+ if pruned_count - first_run == MAX_REQUIRED_LITERAL_RUNS {+ break;+ }+ }+ runs.truncate(pruned_count);+}++fn contains_literal_subslice(haystack: &[u16], needle: &[u16]) -> bool {+ if needle.is_empty() {+ return true;+ }+ if needle.len() > haystack.len() {+ return false;+ }+ haystack.windows(needle.len()).any(|window| window == needle)+}++pub fn extract_literal_u16<'z>(zone: &'z Zone, pattern: &Pattern<'z>, flags: Flags) -> Option<&'z [u16]> {+ if flags.ignore_case && (flags.unicode || flags.unicode_sets) {+ return None;+ }+ if pattern.disjunction.alternatives.len() != 1 {+ return None;+ }++ let alternative = &pattern.disjunction.alternatives[0];+ let mut literal = ZoneVec::new_in(zone);+ for term in alternative.terms {+ if term.quantifier.is_some() {+ return None;+ }+ let Atom::Literal(cp) = term.atom else {+ return None;+ };+ if is_unsafe_unicode_literal(cp, flags) {+ return None;+ }+ append_code_point_wtf16(&mut literal, cp)?;+ }++ Some(literal.into_slice())+}++pub fn extract_literal_alternatives_u16<'z>(+ zone: &'z Zone,+ pattern: &Pattern<'z>,+ flags: Flags,+) -> Option<&'z [&'z [u16]]> {+ if flags.ignore_case && (flags.unicode || flags.unicode_sets) {+ return None;+ }++ let alternatives = pattern.disjunction.alternatives;+ if alternatives.len() < 2 || pattern.capture_count > 0 {+ return None;+ }++ let mut literal_alternatives = ZoneVec::with_capacity_in(alternatives.len(), zone);+ for alternative in alternatives {+ let mut literal = ZoneVec::new_in(zone);+ for term in alternative.terms {+ if term.quantifier.is_some() {+ return None;+ }+ let Atom::Literal(cp) = term.atom else {+ return None;+ };+ if is_unsafe_unicode_literal(cp, flags) {+ return None;+ }+ if flags.ignore_case && cp > 0x7F {+ return None;+ }+ append_code_point_wtf16(&mut literal, cp)?;+ }+ if literal.is_empty() {+ return None;+ }+ literal_alternatives.push(&*literal.into_slice());+ }++ Some(literal_alternatives.into_slice())+}++pub fn extract_word_boundary_literal_u16<'z>(zone: &'z Zone, pattern: &Pattern<'z>, flags: Flags) -> Option<&'z [u16]> {+ if flags.unicode || flags.unicode_sets || pattern.capture_count > 0 {+ return None;+ }+ if pattern.disjunction.alternatives.len() != 1 {+ return None;+ }++ let terms = pattern.disjunction.alternatives[0].terms;+ if terms.len() < 3 {+ return None;+ }++ let first_term = terms.first()?;+ let last_term = terms.last()?;+ if first_term.quantifier.is_some() || last_term.quantifier.is_some() {+ return None;+ }+ if !matches!(first_term.atom, Atom::Assertion(AssertionKind::WordBoundary)) {+ return None;+ }+ if !matches!(last_term.atom, Atom::Assertion(AssertionKind::WordBoundary)) {+ return None;+ }++ let mut literal = ZoneVec::new_in(zone);+ for term in &terms[1..terms.len() - 1] {+ if term.quantifier.is_some() {+ return None;+ }+ let Atom::Literal(cp) = term.atom else {+ return None;+ };+ if is_unsafe_unicode_literal(cp, flags) {+ return None;+ }+ if flags.ignore_case && cp > 0x7F {+ return None;+ }+ append_code_point_wtf16(&mut literal, cp)?;+ }++ if literal.is_empty() {+ return None;+ }+ if !is_ascii_word_code_unit(*literal.first()?) || !is_ascii_word_code_unit(*literal.last()?) {+ return None;+ }++ Some(literal.into_slice())+}++fn is_unsafe_unicode_literal(cp: u32, flags: Flags) -> bool {+ (flags.unicode || flags.unicode_sets) && (0xD800..=0xDFFF).contains(&cp)+}diff --git a/Libraries/LibRegex/Rust/src/regex.rs b/Libraries/LibRegex/Rust/src/regex.rsindex 99871a40c4c..e616be61715 100644--- a/Libraries/LibRegex/Rust/src/regex.rs+++ b/Libraries/LibRegex/Rust/src/regex.rs@@ -7,22 +7,17 @@/// High-level regex API.////// This is the main entry point for using the regex engine.-use crate::ast::Alternative;-use crate::ast::Atom;-use crate::ast::Disjunction;use crate::ast::Flags;-use crate::ast::Pattern;-use crate::ast::Term;-use crate::bytecode::Instruction;use crate::bytecode::NamedGroupEntry;-use crate::bytecode::append_code_point_wtf16;use crate::compiler;+use crate::copy_out;+use crate::literal_hints;+use crate::literal_hints::is_ascii_word_code_unit;use crate::parser;use crate::vm;use crate::work_zone::with_work_zone;use ak::Zone;use std::cell::RefCell;-use std::collections::HashSet;/// A compiled regular expression.pub struct Regex {@@ -80,14 +75,20 @@ impl Regex {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);- let hints = vm::analyze_pattern(&program, required_literal_hint);-- let literal_u16 = extract_literal_u16(&parsed, flags);- let word_boundary_literal_u16 = extract_word_boundary_literal_u16(&parsed, flags);- let literal_alt_u16 = extract_literal_alternatives_u16(&parsed, flags);+ let zone_program = compiler::compile(zone, &parsed)?;+ let required_literal_hint = literal_hints::extract_required_literal_hint(zone, &parsed, flags);+ let literal_u16 = literal_hints::extract_literal_u16(zone, &parsed, flags);+ let word_boundary_literal_u16 = literal_hints::extract_word_boundary_literal_u16(zone, &parsed, flags);+ let literal_alt_u16 = literal_hints::extract_literal_alternatives_u16(zone, &parsed, flags);++ let program = copy_out::program(&zone_program);+ let hints = vm::analyze_pattern(+ &program,+ required_literal_hint.as_ref().map(copy_out::required_literal_hint),+ );+ let literal_u16 = literal_u16.map(<[u16]>::to_vec);+ let word_boundary_literal_u16 = word_boundary_literal_u16.map(<[u16]>::to_vec);+ let literal_alt_u16 = literal_alt_u16.map(copy_out::literal_alternatives);Ok(Self {program,@@ -508,40 +509,6 @@ impl Regex {count}- /// Post-process the program to resolve Unicode property names to ICU enum IDs.- /// This allows O(1) trie lookups at match time instead of string-based resolution.- fn resolve_properties(program: &mut crate::bytecode::Program) {- fn resolve_data(data: &mut crate::bytecode::UnicodePropertyData) {- if data.resolved.is_none() {- data.resolved = compiler::resolve_property(&data.name, data.value.as_deref());- }- }- fn resolve_simple_match(matcher: &mut crate::bytecode::SimpleMatch) {- match matcher {- crate::bytecode::SimpleMatch::UnicodeProperty(data) => resolve_data(data),- crate::bytecode::SimpleMatch::Union(lhs, rhs) => {- resolve_simple_match(lhs);- resolve_simple_match(rhs);- }- _ => {}- }- }- for inst in &mut program.instructions {- match inst {- Instruction::UnicodeProperty(data) => {- resolve_data(data);- }- Instruction::StringPropertyMatch { property, .. } => {- resolve_data(property);- }- Instruction::GreedyLoop { matcher, .. } | Instruction::LazyLoop { matcher, .. } => {- resolve_simple_match(matcher);- }- _ => {}- }- }- }-/// Get the number of capture groups (not counting group 0).pub fn capture_count(&self) -> u32 {self.program.capture_count@@ -595,11 +562,6 @@ fn is_ascii_alpha(ch: u16) -> bool {matches!(ch, 0x41..=0x5A | 0x61..=0x7A)}-#[inline(always)]-fn is_ascii_word_code_unit(ch: u16) -> bool {- matches!(ch, 0x30..=0x39 | 0x41..=0x5A | 0x5F | 0x61..=0x7A)-}-#[inline(always)]fn fold_ascii_for_compare(ch: u16) -> u16 {match ch {@@ -665,415 +627,3 @@ fn has_ascii_word_boundaries_at<I: vm::Input>(input: I, match_start: usize, matclet right_is_word = match_end < input.len() && is_ascii_word_code_unit(input.code_unit(match_end));!left_is_word && !right_is_word}--const MAX_REQUIRED_LITERAL_RUNS: usize = 16;-const MAX_REQUIRED_LITERAL_CODE_UNITS: usize = 64;--#[derive(Default)]-struct RequiredLiteralAnalysis {- exact_literal: Option<Vec<u16>>,- guaranteed_runs: Vec<Vec<u16>>,-}--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() {- return None;- }-- let ascii_case_insensitive = if flags.ignore_case {- if flags.unicode || flags.unicode_sets || literal.iter().any(|ch| *ch > 0x7F) {- return None;- }- true- } else {- false- };-- Some(vm::RequiredLiteralHint {- literal,- ascii_case_insensitive,- })-}--fn analyze_required_literal_disjunction(disjunction: &Disjunction<'_>, flags: Flags) -> RequiredLiteralAnalysis {- if crate::stack::is_exhausted() {- return RequiredLiteralAnalysis {- exact_literal: None,- guaranteed_runs: Vec::new(),- };- }- let mut analyses = disjunction- .alternatives- .iter()- .map(|alternative| analyze_required_literal_alternative(alternative, flags));-- let Some(first_analysis) = analyses.next() else {- return RequiredLiteralAnalysis {- exact_literal: Some(Vec::new()),- guaranteed_runs: Vec::new(),- };- };-- let mut exact_literal = first_analysis.exact_literal.clone();- let mut guaranteed_runs = first_analysis.guaranteed_runs;- for analysis in analyses {- if exact_literal.as_deref() != analysis.exact_literal.as_deref() {- exact_literal = None;- }- guaranteed_runs = intersect_required_literal_runs(&guaranteed_runs, &analysis.guaranteed_runs);- if guaranteed_runs.is_empty() && exact_literal.is_none() {- break;- }- }-- if let Some(ref literal) = exact_literal- && !literal.is_empty()- {- guaranteed_runs.push(literal.clone());- }-- RequiredLiteralAnalysis {- exact_literal,- guaranteed_runs: prune_required_literal_runs(guaranteed_runs),- }-}--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 {- 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() {- exact.extend_from_slice(literal);- }- current_run.extend_from_slice(literal);- continue;- }-- exact_literal = None;- if !current_run.is_empty() {- guaranteed_runs.push(std::mem::take(&mut current_run));- }- guaranteed_runs.extend(term_analysis.guaranteed_runs);- }-- if !current_run.is_empty() {- guaranteed_runs.push(current_run);- }-- if let Some(ref literal) = exact_literal- && !literal.is_empty()- {- guaranteed_runs.push(literal.clone());- }-- RequiredLiteralAnalysis {- exact_literal,- guaranteed_runs: prune_required_literal_runs(guaranteed_runs),- }-}--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;- };- if quantifier.min == 0 {- return RequiredLiteralAnalysis::default();- }-- let repeated_guaranteed_run = atom_analysis- .exact_literal- .as_deref()- .map(|literal| repeat_literal_prefix(literal, quantifier.min));- let exact_literal = if quantifier.max == Some(quantifier.min) {- atom_analysis- .exact_literal- .as_deref()- .and_then(|literal| repeat_literal_exact(literal, quantifier.min))- } else {- None- };-- let mut guaranteed_runs = atom_analysis.guaranteed_runs;- if let Some(literal) = repeated_guaranteed_run- && !literal.is_empty()- {- guaranteed_runs.push(literal);- }-- RequiredLiteralAnalysis {- exact_literal,- guaranteed_runs: prune_required_literal_runs(guaranteed_runs),- }-}--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),- Atom::NonCapturingGroup(group) => analyze_required_literal_disjunction(&group.body, flags),- Atom::ModifierGroup(group) => {- if group.add_flags.ignore_case || group.remove_flags.ignore_case {- RequiredLiteralAnalysis::default()- } else {- analyze_required_literal_disjunction(&group.body, flags)- }- }- Atom::Assertion(_) | Atom::Lookaround(_) => RequiredLiteralAnalysis {- exact_literal: Some(Vec::new()),- guaranteed_runs: Vec::new(),- },- Atom::Dot- | Atom::CharacterClass(_)- | Atom::BuiltinCharacterClass(_)- | Atom::UnicodeProperty(_)- | Atom::Backreference(_) => RequiredLiteralAnalysis::default(),- }-}--fn literal_required_literal_analysis(cp: u32, flags: Flags) -> RequiredLiteralAnalysis {- if is_unsafe_unicode_literal(cp, flags) {- return RequiredLiteralAnalysis::default();- }-- let mut literal = Vec::new();- if append_code_point_wtf16(&mut literal, cp).is_none() {- return RequiredLiteralAnalysis::default();- }-- RequiredLiteralAnalysis {- exact_literal: Some(literal.clone()),- guaranteed_runs: vec![literal],- }-}--fn intersect_required_literal_runs(lhs: &[Vec<u16>], rhs: &[Vec<u16>]) -> Vec<Vec<u16>> {- let mut common_runs = Vec::new();- for left in lhs {- for right in rhs {- common_runs.extend(maximal_common_substrings(left, right));- }- }- prune_required_literal_runs(common_runs)-}--fn maximal_common_substrings(lhs: &[u16], rhs: &[u16]) -> Vec<Vec<u16>> {- let max_len = lhs.len().min(rhs.len()).min(MAX_REQUIRED_LITERAL_CODE_UNITS);- let (shorter, longer) = if lhs.len() <= rhs.len() { (lhs, rhs) } else { (rhs, lhs) };-- let mut substrings: Vec<Vec<u16>> = Vec::new();- for len in (1..=max_len).rev() {- // Required-literal hints keep at most 64 code units, so intersect- // fixed-size windows instead of walking every start-position pair.- let shorter_windows: HashSet<Vec<u16>> = shorter.windows(len).map(|window| window.to_vec()).collect();- let mut matches = HashSet::new();- for window in longer.windows(len) {- if shorter_windows.contains(window) {- matches.insert(window.to_vec());- }- }-- let mut matches: Vec<_> = matches.into_iter().collect();- matches.sort();- for candidate in matches {- if substrings- .iter()- .any(|existing| contains_literal_subslice(existing, &candidate))- {- continue;- }- substrings.push(candidate);- if substrings.len() == MAX_REQUIRED_LITERAL_RUNS {- return substrings;- }- }- }- prune_required_literal_runs(substrings)-}--fn repeat_literal_exact(literal: &[u16], repeat_count: u32) -> Option<Vec<u16>> {- let total_len = literal.len().checked_mul(repeat_count as usize)?;- // Preserve exact-literal tracking only while the full literal fits in the- // retained hint budget. Longer exact runs still contribute via prefixes.- if total_len > MAX_REQUIRED_LITERAL_CODE_UNITS {- return None;- }- let mut repeated = Vec::with_capacity(total_len);- for _ in 0..repeat_count {- repeated.extend_from_slice(literal);- }- Some(repeated)-}--fn repeat_literal_prefix(literal: &[u16], repeat_count: u32) -> Vec<u16> {- let mut repeated = Vec::new();- if literal.is_empty() {- return repeated;- }-- repeated.reserve(MAX_REQUIRED_LITERAL_CODE_UNITS.min(literal.len().saturating_mul(repeat_count as usize)));- for _ in 0..repeat_count {- for code_unit in literal {- if repeated.len() == MAX_REQUIRED_LITERAL_CODE_UNITS {- return repeated;- }- repeated.push(*code_unit);- }- }- repeated-}--fn prune_required_literal_runs(mut runs: Vec<Vec<u16>>) -> Vec<Vec<u16>> {- runs.retain(|run| !run.is_empty());- runs.sort_by(|lhs, rhs| rhs.len().cmp(&lhs.len()).then_with(|| lhs.cmp(rhs)));-- let mut pruned: Vec<Vec<u16>> = Vec::new();- 'outer: for run in runs {- if pruned.iter().any(|existing| contains_literal_subslice(existing, &run)) {- continue;- }- pruned.push(run);- if pruned.len() == MAX_REQUIRED_LITERAL_RUNS {- break 'outer;- }- }- pruned-}--fn contains_literal_subslice(haystack: &[u16], needle: &[u16]) -> bool {- if needle.is_empty() {- return true;- }- if needle.len() > haystack.len() {- return false;- }- haystack.windows(needle.len()).any(|window| window == needle)-}--fn extract_literal_u16(pattern: &Pattern<'_>, flags: Flags) -> Option<Vec<u16>> {- if flags.ignore_case && (flags.unicode || flags.unicode_sets) {- return None;- }- if pattern.disjunction.alternatives.len() != 1 {- return None;- }-- let alternative = &pattern.disjunction.alternatives[0];- let mut literal = Vec::new();- for term in alternative.terms {- if term.quantifier.is_some() {- return None;- }- let Atom::Literal(cp) = term.atom else {- return None;- };- if is_unsafe_unicode_literal(cp, flags) {- return None;- }- append_code_point_wtf16(&mut literal, cp)?;- }-- Some(literal)-}--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;- if alternatives.len() < 2 || pattern.capture_count > 0 {- return None;- }-- let mut literal_alternatives = Vec::with_capacity(alternatives.len());- for alternative in alternatives {- let mut literal = Vec::new();- for term in alternative.terms {- if term.quantifier.is_some() {- return None;- }- let Atom::Literal(cp) = term.atom else {- return None;- };- if is_unsafe_unicode_literal(cp, flags) {- return None;- }- if flags.ignore_case && cp > 0x7F {- return None;- }- append_code_point_wtf16(&mut literal, cp)?;- }- if literal.is_empty() {- return None;- }- literal_alternatives.push(literal);- }-- Some(literal_alternatives)-}--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;- }- if pattern.disjunction.alternatives.len() != 1 {- return None;- }-- let terms = pattern.disjunction.alternatives[0].terms;- if terms.len() < 3 {- return None;- }-- let first_term = terms.first()?;- let last_term = terms.last()?;- if first_term.quantifier.is_some() || last_term.quantifier.is_some() {- return None;- }- if !matches!(- first_term.atom,- Atom::Assertion(crate::ast::AssertionKind::WordBoundary)- ) {- return None;- }- if !matches!(last_term.atom, Atom::Assertion(crate::ast::AssertionKind::WordBoundary)) {- return None;- }-- let mut literal = Vec::new();- for term in &terms[1..terms.len() - 1] {- if term.quantifier.is_some() {- return None;- }- let Atom::Literal(cp) = term.atom else {- return None;- };- if is_unsafe_unicode_literal(cp, flags) {- return None;- }- if flags.ignore_case && cp > 0x7F {- return None;- }- append_code_point_wtf16(&mut literal, cp)?;- }-- if literal.is_empty() {- return None;- }- if !is_ascii_word_code_unit(*literal.first()?) || !is_ascii_word_code_unit(*literal.last()?) {- return None;- }-- Some(literal)-}--fn is_unsafe_unicode_literal(cp: u32, flags: Flags) -> bool {- (flags.unicode || flags.unicode_sets) && (0xD800..=0xDFFF).contains(&cp)-}diff --git a/Libraries/LibRegex/Rust/src/zone_program.rs b/Libraries/LibRegex/Rust/src/zone_program.rsnew file mode 100644index 00000000000..15d5fccc396--- /dev/null+++ b/Libraries/LibRegex/Rust/src/zone_program.rs@@ -0,0 +1,186 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The program that the compiler makes of a pattern, in the zone of the compile.+//!+//! It has the instructions of the program that the VM runs (see `bytecode::Program`), but its lists and names are+//! slices and strings of the zone, so it is plain data with the lifetime `'z` of the zone. What a compile keeps is a+//! copy of it at its final size, outside of the zone.++use crate::ast::BuiltinCharacterClass;+use crate::ast::NamedGroup;+use crate::ast::UnicodeProperty;++/// A compiled regex program in a zone.+///+/// Spec model: the internal matcher produced by `CompilePattern`.+/// <https://tc39.es/ecma262/#sec-compilepattern>+#[derive(Debug, Clone, Copy)]+pub struct ZoneProgram<'z> {+ /// The bytecode instructions.+ pub instructions: &'z [ZoneInstruction<'z>],+ /// Number of capture groups (not counting group 0).+ pub capture_count: u32,+ /// Total number of registers needed (2 per capture group + 2 for group 0).+ pub register_count: u32,+ /// Whether Unicode mode is enabled (affects surrogate pair decoding).+ pub unicode: bool,+ /// Whether v-flag (unicode sets) mode is enabled.+ pub unicode_sets: bool,+ /// Base ignore_case flag from pattern flags.+ pub ignore_case: bool,+ /// Base multiline flag from pattern flags.+ pub multiline: bool,+ /// Base dot_all flag from pattern flags.+ pub dot_all: bool,+ /// Named capture groups, in order of appearance.+ pub named_groups: &'z [NamedGroup<'z>],+}++/// A single bytecode instruction, as `bytecode::Instruction` has it, with the variable data in the zone.+/// <https://tc39.es/ecma262/#sec-pattern-semantics>+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum ZoneInstruction<'z> {+ /// Match a single character (u32 code point, supports WTF-16 lone surrogates).+ Char(u32),++ /// Match a single character, case-insensitive (u32 code points).+ CharNoCase(u32, u32),++ /// Match any character (`.`). If `dot_all` is true, matches newlines too.+ AnyChar { dot_all: bool },++ /// Match a character in a set of ranges, which are sorted. `negated` inverts the match.+ CharClass {+ ranges: &'z [CodePointRange],+ negated: bool,+ },++ /// Match a built-in character class (\d, \w, \s and negations).+ BuiltinClass(BuiltinCharacterClass),++ /// Match a Unicode property (by reference to keep the instruction small).+ UnicodeProperty(&'z UnicodeProperty<'z>),++ /// Unconditional jump to target instruction.+ Jump(u32),++ /// Split execution: try `prefer` first, backtrack to `other`.+ Split { prefer: u32, other: u32 },++ /// Save current input position to register `reg`.+ Save(u32),++ /// Clear register `reg` to -1 (no match).+ ClearRegister(u32),++ /// Assert start of input (or line if multiline).+ AssertStart { multiline: bool },++ /// Assert end of input (or line if multiline).+ AssertEnd { multiline: bool },++ /// Assert word boundary.+ AssertWordBoundary,++ /// Assert non-word boundary.+ AssertNonWordBoundary,++ /// Match succeeded.+ Match,++ /// Fail — force backtrack.+ Fail,++ /// Backreference: match the same string as capture group `index`.+ Backref(u32),++ /// Named backreference.+ BackrefNamed(&'z str),++ /// Begin a repetition counter at register `counter_reg`.+ RepeatStart { counter_reg: u32 },++ /// Check repetition: if counter < max, increment and jump to `body`.+ RepeatCheck {+ counter_reg: u32,+ min: u32,+ max: Option<u32>,+ body: u32,+ greedy: bool,+ },++ /// Lookahead/lookbehind assertion.+ LookStart { positive: bool, forward: bool, end: u32 },++ /// End of a lookaround body.+ LookEnd,++ /// Push modifier flags onto the modifier stack.+ PushModifiers {+ ignore_case: Option<bool>,+ multiline: Option<bool>,+ dot_all: Option<bool>,+ },++ /// Pop modifier flags from the modifier stack.+ PopModifiers,++ /// Atomically match one string from a Unicode string property.+ StringPropertyMatch {+ /// Multi-codepoint strings, sorted longest first and packed as:+ /// [len, cp0, cp1, ..., len, cp0, ...]+ strings: &'z [u32],+ /// Fallback for single-codepoint matches.+ property: &'z UnicodeProperty<'z>,+ },++ /// Progress check: save position at `reg`, fail if no progress since last visit.+ ProgressCheck { reg: u32, clear_captures: &'z [u32] },++ /// Greedy loop for simple character matchers.+ GreedyLoop {+ matcher: ZoneSimpleMatch<'z>,+ min: u32,+ max: Option<u32>,+ },++ /// Lazy loop for simple character matchers.+ LazyLoop {+ matcher: ZoneSimpleMatch<'z>,+ min: u32,+ max: Option<u32>,+ },+}++/// A simple character matcher for optimized greedy/lazy loops, as `bytecode::SimpleMatch` has it.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum ZoneSimpleMatch<'z> {+ /// Any character (`.`), with dot_all flag.+ AnyChar { dot_all: bool },+ /// A single character.+ Char(u32),+ /// Case-insensitive character.+ CharNoCase(u32, u32),+ /// Character class (set of sorted ranges), negated flag.+ CharClass {+ ranges: &'z [CodePointRange],+ negated: bool,+ },+ /// Built-in class (\d, \w, \s, etc.)+ BuiltinClass(BuiltinCharacterClass),+ /// Unicode property (\p{...}, \P{...}).+ UnicodeProperty(&'z UnicodeProperty<'z>),+ /// Union of two matchers: matches if either alternative matches.+ Union(&'z ZoneSimpleMatch<'z>, &'z ZoneSimpleMatch<'z>),+}++/// A range of code points of a character class, both ends included.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct CodePointRange {+ pub start: u32,+ pub end: u32,+}diff --git a/Libraries/LibUnicode/Rust/src/character_types.rs b/Libraries/LibUnicode/Rust/src/character_types.rsindex f3fa9542104..7de57315687 100644--- a/Libraries/LibUnicode/Rust/src/character_types.rs+++ b/Libraries/LibUnicode/Rust/src/character_types.rs@@ -217,25 +217,16 @@ pub fn is_valid_ecma262_property(name: &str, value: Option<&str>) -> bool {unsafe { unicode_is_valid_ecma262_property(name.as_ptr(), name.len(), value_ptr, value_len) }}-pub fn get_string_property_data(name: &str) -> Vec<u32> {- // SAFETY: Passing a null output buffer with zero capacity is the API's- // documented query mode, and `name` remains valid during the call.- let needed = unsafe { unicode_get_string_property_data(name.as_ptr(), name.len(), std::ptr::null_mut(), 0) };- if needed == 0 {- return Vec::new();- }-- let mut buffer = vec![0u32; needed as usize];-- // SAFETY: `buffer` has room for `needed` elements and the C++ helper- // writes at most that many u32 values.- let written = unsafe { unicode_get_string_property_data(name.as_ptr(), name.len(), buffer.as_mut_ptr(), needed) };- if written == 0 || written > needed {- return Vec::new();- }-- buffer.truncate(written as usize);- buffer+/// The multi-code-point strings of the string property `name`, packed as [count, len1, cp1..., len2, cp2..., ...],+/// or nothing if `name` is not a string property. Writes them to `out` if they fit, and returns how many values they+/// are.+pub fn get_string_property_data(name: &str, out: &mut [u32]) -> usize {+ let capacity = out.len().min(u32::MAX as usize) as u32;++ // SAFETY: `name` remains valid for the duration of this call, `out` is+ // writable for `capacity` elements, and the C++ helper writes at most that+ // many (none if they do not all fit).+ unsafe { unicode_get_string_property_data(name.as_ptr(), name.len(), out.as_mut_ptr(), capacity) as usize }}#[inline(always)]