Skip to main content

php_std/
pcre.rs

1//! PHP's PCRE functions: `preg_match`, `preg_match_all`, `preg_replace`,
2//! `preg_split` and `preg_quote`, on PCRE2 10.44 with its JIT, the library
3//! and version PHP 8.5 bundles.
4//!
5//! | PHP | Rust |
6//! |---|---|
7//! | `preg_match($p, $s, $m, $flags, $offset)` | [`preg_match`] |
8//! | `preg_match($p, $s)` | [`preg_match_bare`] |
9//! | `preg_match_all($p, $s, $m, $flags, $offset)` | [`preg_match_all`] |
10//! | `preg_replace($p, $r, $s, $limit, $count)` | [`preg_replace`] |
11//! | `preg_split($p, $s, $limit, $flags)` | [`preg_split`] |
12//! | `preg_quote($s, $delimiter)` | [`preg_quote`] |
13//! | `preg_match($p, $s, $m) === 1` on a pattern compiled once | [`Regex::compiled`], [`Regex::captures`], [`Regex::is_match`] |
14//! | `preg_last_error()` / `preg_last_error_msg()` | [`PregError`] in every result |
15//!
16//! User patterns must behave exactly as in PHP, down to where
17//! `pcre.backtrack_limit` and the JIT stack run out, and only PCRE2 itself
18//! does that: `build.rs` compiles the sources PHP 8.5 bundles
19//! (`ext/pcre/pcre2lib`), and this module calls them as `ext/pcre/php_pcre.c`
20//! does. Patterns are delimited and take modifiers exactly as
21//! `pcre_get_compiled_regex_cache()` parses them (`/i m n s x A D r S X U u
22//! J`), then go through PHP's per-process cache of compiled patterns, which
23//! JIT-compiles them while `pcre.jit` is on (a JIT failure warns and turns it
24//! off for the process). Matches run with `pcre.backtrack_limit` and
25//! `pcre.recursion_limit` (their defaults) as the match and depth limits and
26//! the 32 KiB–192 KiB JIT stack, through `pcre2_jit_match()` when no UTF-8
27//! check is needed and `pcre2_match()` otherwise, and an empty match is
28//! retried with `PCRE2_NOTEMPTY_ATSTART | PCRE2_ANCHORED`, as PHP does.
29
30use std::collections::{HashMap, VecDeque};
31use std::fmt;
32use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering};
33use std::sync::{Arc, Mutex, OnceLock};
34
35mod compiled;
36mod engine;
37mod ffi;
38
39use engine::{Code, Session};
40use ffi::UNSET;
41
42pub use compiled::Captures;
43pub(crate) use engine::is_letter_or_number;
44
45/// The Unicode version of PCRE2's tables (PHP's "PCRE Unicode Version").
46pub const UNICODE_VERSION: &str = "15.0.0";
47
48/// Orders `preg_match_all()` results by group, as PHP's `PREG_PATTERN_ORDER`.
49pub const PREG_PATTERN_ORDER: i64 = 1;
50/// Orders `preg_match_all()` results by match, as PHP's `PREG_SET_ORDER`.
51pub const PREG_SET_ORDER: i64 = 2;
52/// Returns each match with its byte offset, as PHP's `PREG_OFFSET_CAPTURE`.
53pub const PREG_OFFSET_CAPTURE: i64 = 1 << 8;
54/// Reports unmatched groups as `null`, as PHP's `PREG_UNMATCHED_AS_NULL`.
55pub const PREG_UNMATCHED_AS_NULL: i64 = 1 << 9;
56/// Leaves empty pieces out of `preg_split()`, as PHP's `PREG_SPLIT_NO_EMPTY`.
57pub const PREG_SPLIT_NO_EMPTY: i64 = 1;
58/// Returns the delimiter's captured groups from `preg_split()` too, as PHP's `PREG_SPLIT_DELIM_CAPTURE`.
59pub const PREG_SPLIT_DELIM_CAPTURE: i64 = 2;
60/// Returns each `preg_split()` piece with its byte offset, as PHP's `PREG_SPLIT_OFFSET_CAPTURE`.
61pub const PREG_SPLIT_OFFSET_CAPTURE: i64 = 4;
62
63/// A PHP array key.
64#[derive(Debug, Clone, PartialEq, Eq, Hash)]
65pub enum Key {
66    /// An integer key.
67    Int(i64),
68    /// A string key, as bytes.
69    Str(Vec<u8>),
70}
71
72/// The PHP values the `preg_*` functions build.
73#[derive(Debug, Clone, PartialEq)]
74pub enum Value {
75    /// PHP `null`.
76    Null,
77    /// A PHP `bool`.
78    Bool(bool),
79    /// A PHP `int`.
80    Int(i64),
81    /// A PHP `string`, as bytes.
82    Str(Vec<u8>),
83    /// A PHP array.
84    Array(Array),
85}
86
87/// An ordered PHP array.
88#[derive(Debug, Clone, PartialEq, Default)]
89pub struct Array {
90    entries: Vec<(Key, Value)>,
91    next: i64,
92}
93
94impl Array {
95    /// An empty array.
96    pub fn new() -> Self {
97        Self::default()
98    }
99
100    /// The key-value pairs, in order.
101    pub fn entries(&self) -> &[(Key, Value)] {
102        &self.entries
103    }
104
105    /// The number of elements.
106    pub fn len(&self) -> usize {
107        self.entries.len()
108    }
109
110    /// Whether the array has no elements.
111    pub fn is_empty(&self) -> bool {
112        self.entries.is_empty()
113    }
114
115    /// Whether the keys are `0, 1, 2...` in order (`array_is_list`).
116    pub fn is_list(&self) -> bool {
117        self.entries.iter().enumerate().all(|(i, (k, _))| *k == Key::Int(i as i64))
118    }
119
120    /// The value at `key`, if any.
121    pub fn get(&self, key: &Key) -> Option<&Value> {
122        self.entries.iter().find(|(k, _)| k == key).map(|(_, v)| v)
123    }
124
125    /// `$array[] = $value`.
126    pub fn push(&mut self, value: Value) {
127        let k = self.next;
128        self.entries.push((Key::Int(k), value));
129        self.next = k + 1;
130    }
131
132    /// `$array[$key] = $value` (`zend_hash_update`): an existing key keeps
133    /// its position.
134    pub fn update(&mut self, key: Key, value: Value) {
135        if let Some(slot) = self.entries.iter_mut().find(|(k, _)| *k == key) {
136            slot.1 = value;
137            return;
138        }
139        self.insert_new(key, value);
140    }
141
142    /// `zend_hash_add`: only when the key is absent.
143    pub fn add(&mut self, key: Key, value: Value) -> bool {
144        if self.entries.iter().any(|(k, _)| *k == key) {
145            return false;
146        }
147        self.insert_new(key, value);
148        true
149    }
150
151    fn insert_new(&mut self, key: Key, value: Value) {
152        if let Key::Int(i) = key
153            && i >= self.next
154        {
155            self.next = i.saturating_add(1);
156        }
157        self.entries.push((key, value));
158    }
159}
160
161/// `preg_last_error()`.
162#[derive(Debug, Clone, Copy, PartialEq, Eq)]
163pub enum PregError {
164    /// `PREG_NO_ERROR`.
165    None,
166    /// `PREG_INTERNAL_ERROR`.
167    Internal,
168    /// `PREG_BACKTRACK_LIMIT_ERROR`: `pcre.backtrack_limit` was reached.
169    BacktrackLimit,
170    /// `PREG_RECURSION_LIMIT_ERROR`: `pcre.recursion_limit` was reached.
171    RecursionLimit,
172    /// `PREG_BAD_UTF8_ERROR`: the subject is not valid UTF-8.
173    BadUtf8,
174    /// `PREG_BAD_UTF8_OFFSET_ERROR`: the offset is inside a UTF-8 character.
175    BadUtf8Offset,
176    /// `PREG_JIT_STACKLIMIT_ERROR`: the JIT stack ran out.
177    JitStackLimit,
178}
179
180impl PregError {
181    /// The value of `preg_last_error()` (`PREG_*_ERROR`).
182    pub fn code(self) -> i64 {
183        self as i64
184    }
185
186    /// `preg_last_error_msg()`.
187    pub fn message(self) -> &'static str {
188        match self {
189            PregError::None => "No error",
190            PregError::Internal => "Internal error",
191            PregError::BacktrackLimit => "Backtrack limit exhausted",
192            PregError::RecursionLimit => "Recursion limit exhausted",
193            PregError::BadUtf8 => "Malformed UTF-8 characters, possibly incorrectly encoded",
194            PregError::BadUtf8Offset => "The offset did not correspond to the beginning of a valid UTF-8 code point",
195            PregError::JitStackLimit => "JIT stack limit exhausted",
196        }
197    }
198
199    /// `pcre_handle_exec_error()`.
200    fn from_pcre(code: i32) -> Self {
201        match code {
202            ffi::ERROR_MATCHLIMIT => PregError::BacktrackLimit,
203            ffi::ERROR_DEPTHLIMIT => PregError::RecursionLimit,
204            ffi::ERROR_BADUTFOFFSET => PregError::BadUtf8Offset,
205            ffi::ERROR_JIT_STACKLIMIT => PregError::JitStackLimit,
206            ffi::ERROR_UTF8_ERR21..=ffi::ERROR_UTF8_ERR1 => PregError::BadUtf8,
207            _ => PregError::Internal,
208        }
209    }
210
211    fn from_u8(v: u8) -> Self {
212        match v {
213            1 => PregError::Internal,
214            2 => PregError::BacktrackLimit,
215            3 => PregError::RecursionLimit,
216            4 => PregError::BadUtf8,
217            5 => PregError::BadUtf8Offset,
218            6 => PregError::JitStackLimit,
219            _ => PregError::None,
220        }
221    }
222}
223
224/// A `ValueError`/`TypeError` thrown for an invalid argument.
225#[derive(Debug, Clone, PartialEq, Eq)]
226pub struct ArgumentError {
227    class: &'static str,
228    message: String,
229}
230
231impl ArgumentError {
232    fn value(message: String) -> Self {
233        ArgumentError { class: "ValueError", message }
234    }
235
236    /// The PHP exception class.
237    pub fn php_class(&self) -> &'static str {
238        self.class
239    }
240}
241
242impl fmt::Display for ArgumentError {
243    /// Writes the message.
244    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
245        f.write_str(&self.message)
246    }
247}
248
249impl std::error::Error for ArgumentError {}
250
251/// What a `preg_*` call returned, with `preg_last_error()` and the last
252/// warning it emitted (`"preg_match(): Compilation failed: ..."`).
253#[derive(Debug, Clone, PartialEq)]
254pub struct Preg<T> {
255    /// The value the function returned.
256    pub value: T,
257    /// What `preg_last_error()` reports after the call.
258    pub error: PregError,
259    /// The last warning emitted, if any.
260    pub warning: Option<Vec<u8>>,
261}
262
263/// A pattern that `pcre_get_compiled_regex_cache()` rejected: the warning
264/// text, without the function name.
265#[derive(Debug, Clone, PartialEq, Eq)]
266pub struct CompileFailure {
267    /// The warning text.
268    pub message: Vec<u8>,
269}
270
271/// A compiled PHP regular expression (delimiters and modifiers included):
272/// a `pcre_cache_entry`.
273pub struct Regex {
274    code: Code,
275    /// `PREG_JIT`: the pattern has JIT code.
276    jit: bool,
277    /// The `u` modifier (`compile_options & PCRE2_UTF`): PHP decides on
278    /// UTF-8 checks and how far to step after an empty match from it, not
279    /// from a `(*UTF)` in the pattern.
280    php_utf: bool,
281    capture_count: u32,
282    /// Group number to name (`subpats_table`), when the pattern has names.
283    names: Option<Vec<Option<Vec<u8>>>>,
284}
285
286impl fmt::Debug for Regex {
287    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
288        f.debug_struct("Regex")
289            .field("jit", &self.jit)
290            .field("utf", &self.php_utf)
291            .field("capture_count", &self.capture_count)
292            .finish_non_exhaustive()
293    }
294}
295
296/// The ways PHP runs a pattern.
297#[derive(Clone, Copy, PartialEq, Eq)]
298enum Call {
299    /// `pcre2_jit_match(..., PCRE2_NO_UTF_CHECK)`, or for a pattern without
300    /// JIT code `pcre2_match(..., PCRE2_NO_UTF_CHECK)`.
301    Fast,
302    /// `pcre2_match(..., 0)` for a `/u` pattern and a subject not known to
303    /// be valid UTF-8: the UTF-8 check, then the JIT.
304    Checked,
305    /// `pcre2_match(..., PCRE2_NO_UTF_CHECK | PCRE2_NOTEMPTY_ATSTART |
306    /// PCRE2_ANCHORED)` after an empty match.
307    Retry,
308}
309
310impl Regex {
311    /// Parses the delimiters and modifiers of a PHP regex and compiles it
312    /// (`pcre_get_compiled_regex_cache()`), with JIT code while `pcre.jit`
313    /// is on. Unlike [`Regex::compiled`], it bypasses PHP's cache, and a
314    /// JIT failure leaves the pattern interpreted without a warning.
315    pub fn new(regex: &[u8]) -> Result<Regex, CompileFailure> {
316        let mut re = Self::compile(regex)?;
317        if globals().jit.load(Ordering::Relaxed) {
318            re.jit = re.code.jit_compile().unwrap_or(false);
319        }
320        Ok(re)
321    }
322
323    /// The delimiters, the modifiers and `pcre2_compile()`, without the JIT.
324    fn compile(regex: &[u8]) -> Result<Regex, CompileFailure> {
325        let fail = |m: String| Err(CompileFailure { message: m.into_bytes() });
326        let mut p = 0;
327        while p < regex.len() && is_c_space(regex[p]) {
328            p += 1;
329        }
330        if p >= regex.len() {
331            return fail("Empty regular expression".into());
332        }
333        let delimiter = regex[p];
334        p += 1;
335        if delimiter.is_ascii_alphanumeric() || delimiter == b'\\' || delimiter == 0 {
336            return fail("Delimiter must not be alphanumeric, backslash, or NUL byte".into());
337        }
338        let start_delimiter = delimiter;
339        let end_delimiter = match delimiter {
340            b'(' => b')',
341            b'[' => b']',
342            b'{' => b'}',
343            b'<' => b'>',
344            d => d,
345        };
346        let mut pp = p;
347        if start_delimiter == end_delimiter {
348            while pp < regex.len() {
349                if regex[pp] == b'\\' && pp + 1 < regex.len() {
350                    pp += 1;
351                } else if regex[pp] == end_delimiter {
352                    break;
353                }
354                pp += 1;
355            }
356        } else {
357            let mut brackets = 1;
358            while pp < regex.len() {
359                if regex[pp] == b'\\' && pp + 1 < regex.len() {
360                    pp += 1;
361                } else if regex[pp] == end_delimiter {
362                    brackets -= 1;
363                    if brackets <= 0 {
364                        break;
365                    }
366                } else if regex[pp] == start_delimiter {
367                    brackets += 1;
368                }
369                pp += 1;
370            }
371        }
372        if pp >= regex.len() {
373            let mut m = if start_delimiter == end_delimiter {
374                b"No ending delimiter '".to_vec()
375            } else {
376                b"No ending matching delimiter '".to_vec()
377            };
378            m.push(end_delimiter);
379            m.extend_from_slice(b"' found");
380            return Err(CompileFailure { message: m });
381        }
382        let pattern = &regex[p..pp];
383        let mut coptions = 0u32;
384        let mut eoptions = 0u32;
385        for &m in &regex[pp + 1..] {
386            match m {
387                b'i' => coptions |= ffi::CASELESS,
388                b'm' => coptions |= ffi::MULTILINE,
389                b'n' => coptions |= ffi::NO_AUTO_CAPTURE,
390                b's' => coptions |= ffi::DOTALL,
391                b'x' => coptions |= ffi::EXTENDED,
392                b'A' => coptions |= ffi::ANCHORED,
393                b'D' => coptions |= ffi::DOLLAR_ENDONLY,
394                b'r' => eoptions |= ffi::EXTRA_CASELESS_RESTRICT,
395                b'S' | b'X' | b' ' | b'\n' | b'\r' => {}
396                b'U' => coptions |= ffi::UNGREEDY,
397                b'u' => coptions |= ffi::UTF | ffi::UCP | ffi::NEVER_BACKSLASH_C,
398                b'J' => coptions |= ffi::DUPNAMES,
399                0 => return fail("NUL byte is not a valid modifier".into()),
400                c => {
401                    let mut msg = b"Unknown modifier '".to_vec();
402                    msg.push(c);
403                    msg.push(b'\'');
404                    return Err(CompileFailure { message: msg });
405                }
406            }
407        }
408        let code = Code::compile(pattern, coptions, eoptions).map_err(|e| {
409            let mut m = b"Compilation failed: ".to_vec();
410            if e.code == ffi::ERROR_BACKSLASH_C_CALLER_DISABLED {
411                m.extend_from_slice(b"using \\C is incompatible with the 'u' modifier");
412            } else {
413                m.extend_from_slice(&engine::error_message(e.code));
414            }
415            m.extend_from_slice(format!(" at offset {}", e.offset).as_bytes());
416            CompileFailure { message: m }
417        })?;
418        let capture_count = code.capture_count();
419        let named = code.names();
420        let names = (!named.is_empty()).then(|| {
421            let mut names = vec![None; capture_count as usize + 1];
422            for (group, name) in named {
423                if let Some(slot) = names.get_mut(group) {
424                    *slot = Some(name);
425                }
426            }
427            names
428        });
429        Ok(Regex { code, jit: false, php_utf: coptions & ffi::UTF != 0, capture_count, names })
430    }
431
432    /// The number of capturing groups.
433    pub fn capture_count(&self) -> u32 {
434        self.capture_count
435    }
436
437    /// The match data for the calls of one `preg_*` function.
438    fn session(&self) -> Session {
439        Session::new(&self.code, self.capture_count)
440    }
441
442    /// One `pcre2_match()`/`pcre2_jit_match()` call as PHP makes it: the
443    /// match count, `None` for no match, or the PCRE2 error.
444    fn call(&self, session: &mut Session, subject: &[u8], start: usize, call: Call) -> Result<Option<usize>, i32> {
445        let (jit, options) = match call {
446            Call::Fast => (self.jit, ffi::NO_UTF_CHECK),
447            Call::Checked => (false, 0),
448            Call::Retry => (false, ffi::NO_UTF_CHECK | ffi::NOTEMPTY_ATSTART | ffi::ANCHORED),
449        };
450        match session.run(&self.code, subject, start, options, jit) {
451            // "Matched, but too many substrings" cannot happen: the match
452            // data always has room for every group.
453            0 => Ok(Some(self.capture_count as usize + 1)),
454            n if n > 0 => Ok(Some(n as usize)),
455            ffi::ERROR_NOMATCH => Ok(None),
456            e => Err(e),
457        }
458    }
459
460    /// The first call of a `preg_*` function: `/u` patterns check the
461    /// subject first. `known_valid`: PHP already knows the subject string is
462    /// valid UTF-8 (`is_known_valid_utf8()`).
463    fn first_call(&self, known_valid: bool) -> Call {
464        if self.php_utf && !known_valid { Call::Checked } else { Call::Fast }
465    }
466
467    /// `calculate_unit_length()`.
468    fn unit_length(&self, subject: &[u8], at: usize) -> usize {
469        if self.php_utf {
470            let mut end = at + 1;
471            while end < subject.len() && subject[end] & 0xc0 == 0x80 {
472                end += 1;
473            }
474            end - at
475        } else {
476            1
477        }
478    }
479
480    /// `populate_subpat_array()` for the last match of `session`, which
481    /// set `count` groups.
482    fn populate_subpat_array(&self, out: &mut Array, subject: &[u8], session: &Session, count: usize, flags: i64) {
483        let offset_capture = flags & PREG_OFFSET_CAPTURE != 0;
484        let unmatched_as_null = flags & PREG_UNMATCHED_AS_NULL != 0;
485        let num_subpats = self.capture_count as usize + 1;
486        let ov = session.ovector(count);
487        let count = ov.len() / 2;
488        // Room for every group (named ones twice), as PHP sizes the array.
489        out.entries.reserve(if self.names.is_some() { 2 * num_subpats } else { num_subpats });
490        if let Some(names) = &self.names {
491            if offset_capture {
492                for i in 0..count {
493                    add_offset_pair(out, subject, ov[2 * i], ov[2 * i + 1], names[i].as_deref(), unmatched_as_null);
494                }
495                if unmatched_as_null {
496                    for name in &names[count..num_subpats] {
497                        add_offset_pair(out, subject, UNSET, UNSET, name.as_deref(), true);
498                    }
499                }
500            } else {
501                for i in 0..count {
502                    let val = match_value(subject, ov[2 * i], ov[2 * i + 1], unmatched_as_null);
503                    if let Some(name) = &names[i] {
504                        add_named(out, name, val.clone(), ov[2 * i] == UNSET);
505                    }
506                    out.push(val);
507                }
508                if unmatched_as_null {
509                    for name in &names[count..num_subpats] {
510                        if let Some(name) = name {
511                            out.add(Key::Str(name.clone()), Value::Null);
512                        }
513                        out.push(Value::Null);
514                    }
515                }
516            }
517        } else if offset_capture {
518            for i in 0..count {
519                add_offset_pair(out, subject, ov[2 * i], ov[2 * i + 1], None, unmatched_as_null);
520            }
521            if unmatched_as_null {
522                for _ in count..num_subpats {
523                    add_offset_pair(out, subject, UNSET, UNSET, None, true);
524                }
525            }
526        } else {
527            for i in 0..count {
528                out.push(match_value(subject, ov[2 * i], ov[2 * i + 1], unmatched_as_null));
529            }
530            if unmatched_as_null {
531                for _ in count..num_subpats {
532                    out.push(Value::Null);
533                }
534            }
535        }
536        if let Some(mark) = session.mark(&self.code) {
537            out.add(Key::Str(b"MARK".to_vec()), Value::Str(mark.to_vec()));
538        }
539    }
540}
541
542/// `PCRE_CACHE_SIZE`.
543const CACHE_SIZE: usize = 4096;
544
545/// PHP's per-process PCRE state: `pcre.jit` (switched off for good when a
546/// pattern fails to JIT-compile), `PCRE_G(error_code)` and the
547/// compiled-pattern cache, which keeps how each pattern was compiled.
548struct Globals {
549    jit: AtomicBool,
550    /// What `preg_last_error()` returns. Calls that never reach a pattern
551    /// (an empty array of patterns or subjects) leave it as the previous
552    /// call set it.
553    error: AtomicU8,
554    cache: Mutex<Cache>,
555    /// How many times the cache has evicted entries.
556    evictions: AtomicU64,
557}
558
559/// A cached regex, delimiters and modifiers included: the cache's key.
560type Source = Arc<[u8]>;
561
562#[derive(Default)]
563struct Cache {
564    order: VecDeque<Source>,
565    entries: HashMap<Source, Arc<Regex>>,
566}
567
568fn globals() -> &'static Globals {
569    static GLOBALS: OnceLock<Globals> = OnceLock::new();
570    GLOBALS.get_or_init(|| Globals {
571        jit: AtomicBool::new(true),
572        error: AtomicU8::new(0),
573        cache: Mutex::new(Cache::default()),
574        evictions: AtomicU64::new(0),
575    })
576}
577
578/// Sets `preg_last_error()`, returning the value.
579fn set_last_error(e: PregError) -> PregError {
580    globals().error.store(e as u8, Ordering::Relaxed);
581    e
582}
583
584/// `preg_last_error()`: the error of the last `preg_*` call that set one.
585pub fn preg_last_error() -> PregError {
586    PregError::from_u8(globals().error.load(Ordering::Relaxed))
587}
588
589/// A compiled pattern and the warning its JIT compilation emitted.
590type Cached = (Arc<Regex>, Option<Vec<u8>>);
591
592/// `pcre_get_compiled_regex_cache()`: the cached pattern, compiling it on
593/// a miss. `Err` carries the warning of a pattern that does not compile;
594/// `Ok` may carry the warning of a pattern the JIT could not compile, which
595/// switches the JIT off for the rest of the process, as PHP does.
596fn cached(func: &str, regex: &[u8]) -> Result<Cached, Vec<u8>> {
597    let g = globals();
598    if let Some(re) = recent(g, regex) {
599        return Ok((re, None));
600    }
601    let mut cache = match g.cache.lock() {
602        Ok(c) => c,
603        Err(poisoned) => poisoned.into_inner(),
604    };
605    if let Some((key, re)) = cache.entries.get_key_value(regex) {
606        remember(g, key, re);
607        return Ok((re.clone(), None));
608    }
609    let mut re = match Regex::compile(regex) {
610        Ok(re) => re,
611        Err(e) => {
612            set_last_error(PregError::Internal);
613            return Err(warn(func, e));
614        }
615    };
616    let mut warning = None;
617    if g.jit.load(Ordering::Relaxed) {
618        match re.code.jit_compile() {
619            Ok(jit) => re.jit = jit,
620            Err(ffi::ERROR_NOMEMORY) => {
621                warning = Some(
622                    format!(
623                        "{func}(): Allocation of JIT memory failed, PCRE JIT will be disabled. This is likely caused \
624                         by security restrictions. Either grant PHP permission to allocate executable memory, or set \
625                         pcre.jit=0"
626                    )
627                    .into_bytes(),
628                );
629                g.jit.store(false, Ordering::Relaxed);
630            }
631            Err(e) => {
632                let mut w = format!("{func}(): JIT compilation failed: ").into_bytes();
633                w.extend_from_slice(&engine::error_message(e));
634                warning = Some(w);
635                set_last_error(PregError::Internal);
636            }
637        }
638    }
639    if cache.entries.len() == CACHE_SIZE {
640        g.evictions.fetch_add(1, Ordering::Release);
641        for _ in 0..CACHE_SIZE / 8 {
642            if let Some(k) = cache.order.pop_front() {
643                cache.entries.remove(&k);
644            }
645        }
646    }
647    let re = Arc::new(re);
648    let key: Source = regex.into();
649    cache.order.push_back(key.clone());
650    cache.entries.insert(key.clone(), re.clone());
651    remember(g, &key, &re);
652    Ok((re, warning))
653}
654
655/// How many cache entries each thread remembers.
656const RECENT: usize = 16;
657
658/// The cache entries a thread used last, so that a hit takes neither the
659/// cache's lock nor a hash of the pattern. They stand for the entries of
660/// the shared cache, which never change while they are in it: the thread
661/// forgets them all when the shared cache evicts.
662struct Recent {
663    evictions: u64,
664    next: usize,
665    entries: [Option<(Source, Arc<Regex>)>; RECENT],
666}
667
668thread_local! {
669    static RECENT_ENTRIES: std::cell::RefCell<Recent> =
670        const { std::cell::RefCell::new(Recent { evictions: 0, next: 0, entries: [const { None }; RECENT] }) };
671}
672
673/// The thread's remembered entry for `regex`, if the shared cache still
674/// holds it.
675fn recent(g: &Globals, regex: &[u8]) -> Option<Arc<Regex>> {
676    RECENT_ENTRIES.with_borrow_mut(|r| {
677        let evictions = g.evictions.load(Ordering::Acquire);
678        if r.evictions != evictions {
679            *r = Recent { evictions, next: 0, entries: [const { None }; RECENT] };
680            return None;
681        }
682        r.entries.iter().flatten().find(|(k, _)| **k == *regex).map(|(_, re)| re.clone())
683    })
684}
685
686/// Remembers an entry of the shared cache (called with its lock held).
687fn remember(g: &Globals, key: &Source, re: &Arc<Regex>) {
688    RECENT_ENTRIES.with_borrow_mut(|r| {
689        let evictions = g.evictions.load(Ordering::Acquire);
690        if r.evictions != evictions {
691            *r = Recent { evictions, next: 0, entries: [const { None }; RECENT] };
692        }
693        let slot = r.next;
694        r.entries[slot] = Some((key.clone(), re.clone()));
695        r.next = (slot + 1) % RECENT;
696    })
697}
698
699/// What `ext/filter` does with a regular expression:
700/// `pcre_get_compiled_regex()` (PHP's cache), then `pcre2_match(re,
701/// subject, len, 0, 0, ...)`. The result is `None` when the regex does not
702/// compile, and comes with the warning of a compile or JIT failure.
703pub(crate) fn engine_match(func: &str, regex: &[u8], subject: &[u8]) -> (Option<bool>, Option<Vec<u8>>) {
704    match cached(func, regex) {
705        Err(w) => (None, Some(w)),
706        Ok((re, w)) => {
707            let mut session = re.session();
708            (Some(matches!(re.call(&mut session, subject, 0, Call::Checked), Ok(Some(_)))), w)
709        }
710    }
711}
712
713/// `isspace()` in the C locale.
714fn is_c_space(b: u8) -> bool {
715    matches!(b, b' ' | b'\t' | b'\n' | 0x0b | 0x0c | b'\r')
716}
717
718fn match_value(subject: &[u8], start: usize, end: usize, unmatched_as_null: bool) -> Value {
719    if start == UNSET {
720        if unmatched_as_null { Value::Null } else { Value::Str(Vec::new()) }
721    } else {
722        Value::Str(subject[start..end].to_vec())
723    }
724}
725
726fn pair(value: Value, offset: i64) -> Value {
727    let mut a = Array::new();
728    a.push(value);
729    a.push(Value::Int(offset));
730    Value::Array(a)
731}
732
733/// `add_named()`: a matched group overwrites, an unmatched one only fills
734/// a missing name.
735fn add_named(out: &mut Array, name: &[u8], val: Value, unmatched: bool) {
736    if !unmatched {
737        out.update(Key::Str(name.to_vec()), val);
738    } else {
739        out.add(Key::Str(name.to_vec()), val);
740    }
741}
742
743/// `add_offset_pair()`.
744fn add_offset_pair(
745    out: &mut Array,
746    subject: &[u8],
747    start: usize,
748    end: usize,
749    name: Option<&[u8]>,
750    unmatched_as_null: bool,
751) {
752    let p = if start == UNSET {
753        pair(if unmatched_as_null { Value::Null } else { Value::Str(Vec::new()) }, -1)
754    } else {
755        pair(Value::Str(subject[start..end].to_vec()), start as i64)
756    };
757    if let Some(name) = name {
758        add_named(out, name, p.clone(), start == UNSET);
759    }
760    out.push(p);
761}
762
763fn warn(func: &str, failure: CompileFailure) -> Vec<u8> {
764    let mut w = format!("{func}(): ").into_bytes();
765    w.extend_from_slice(&failure.message);
766    w
767}
768
769/// The result of [`preg_match`] and [`preg_match_all`]: the return value
770/// (`Int` or `Bool(false)`) and `$matches` (`None` when the pattern did not
771/// compile, which leaves `$matches` untouched).
772#[derive(Debug, Clone, PartialEq)]
773pub struct MatchResult {
774    /// The return value: the match count, or `false`.
775    pub result: Value,
776    /// `$matches`, or `None` when the pattern did not compile.
777    pub matches: Option<Array>,
778}
779
780/// `preg_match($pattern, $subject, $matches, $flags, $offset)`.
781pub fn preg_match(pattern: &[u8], subject: &[u8], flags: i64, offset: i64) -> Result<Preg<MatchResult>, ArgumentError> {
782    match_impl("preg_match", pattern, subject, false, true, flags, offset)
783}
784
785/// `preg_match($pattern, $subject)`: `preg_match()` without `$matches`.
786/// PHP then treats an empty match like the next match of
787/// `preg_match_all()`: it retries at the same position with
788/// `PCRE2_NOTEMPTY_ATSTART | PCRE2_ANCHORED`, and an error there (a limit)
789/// makes the result `false`. Passing `flags:` or `offset:` by name gives
790/// `preg_match()` a `$matches` to fill, so that is [`preg_match`].
791pub fn preg_match_bare(pattern: &[u8], subject: &[u8]) -> Result<Preg<Value>, ArgumentError> {
792    match_impl("preg_match", pattern, subject, false, false, 0, 0).map(|p| Preg {
793        value: p.value.result,
794        error: p.error,
795        warning: p.warning,
796    })
797}
798
799/// `preg_match_all($pattern, $subject, $matches, $flags, $offset)`.
800pub fn preg_match_all(
801    pattern: &[u8],
802    subject: &[u8],
803    flags: i64,
804    offset: i64,
805) -> Result<Preg<MatchResult>, ArgumentError> {
806    match_impl("preg_match_all", pattern, subject, true, true, flags, offset)
807}
808
809/// `php_do_pcre_match()` and `php_pcre_match_impl()`.
810fn match_impl(
811    func: &str,
812    pattern: &[u8],
813    subject: &[u8],
814    global: bool,
815    subpats: bool,
816    flags: i64,
817    start_offset: i64,
818) -> Result<Preg<MatchResult>, ArgumentError> {
819    let (re, jit_warning) = match cached(func, pattern) {
820        Ok(r) => r,
821        Err(w) => {
822            return Ok(Preg {
823                value: MatchResult { result: Value::Bool(false), matches: None },
824                error: PregError::Internal,
825                warning: Some(w),
826            });
827        }
828    };
829    if start_offset == i64::MIN {
830        return Err(ArgumentError::value(format!("{func}(): Argument #5 ($offset) must be greater than {}", i64::MIN)));
831    }
832    let mut matches = Array::new();
833    let mut subpats_order = if global { PREG_PATTERN_ORDER } else { 0 };
834    let mut offset_capture = false;
835    let mut unmatched_as_null = false;
836    if flags != 0 {
837        offset_capture = flags & PREG_OFFSET_CAPTURE != 0;
838        unmatched_as_null = flags & PREG_UNMATCHED_AS_NULL != 0;
839        if flags & 0xff != 0 {
840            subpats_order = flags & 0xff;
841            if (global && !(PREG_PATTERN_ORDER..=PREG_SET_ORDER).contains(&subpats_order))
842                || (!global && subpats_order != 0)
843            {
844                return Err(ArgumentError::value(format!("{func}(): Argument #4 ($flags) must be a PREG_* constant")));
845            }
846        }
847    }
848    let len = subject.len();
849    let mut start_offset2 = if start_offset < 0 {
850        if start_offset.unsigned_abs() <= len as u64 { len - start_offset.unsigned_abs() as usize } else { 0 }
851    } else {
852        start_offset as usize
853    };
854    let done = |result: Value, matches: Array, error: PregError, warning: Option<Vec<u8>>| {
855        Ok(Preg {
856            value: MatchResult { result, matches: Some(matches) },
857            error,
858            warning: warning.or(jit_warning.clone()),
859        })
860    };
861    if start_offset2 > len {
862        return done(Value::Bool(false), matches, set_last_error(PregError::Internal), None);
863    }
864    let num_subpats = re.capture_count as usize + 1;
865    let mut match_sets: Option<Vec<Array>> =
866        if global && subpats_order == PREG_PATTERN_ORDER { Some(vec![Array::new(); num_subpats]) } else { None };
867    let mut marks: Option<Array> = None;
868    let mut error = set_last_error(PregError::None);
869    let mut matched: i64 = 0;
870    let mut session = re.session();
871    // PHP's empty string is flagged as valid UTF-8; other subjects reach
872    // these functions without the flag.
873    let first = re.first_call(subject.is_empty());
874    let mut pending = Some(re.call(&mut session, subject, start_offset2, first));
875    loop {
876        let count = pending.take().unwrap_or_else(|| re.call(&mut session, subject, start_offset2, Call::Fast));
877        match count {
878            Ok(Some(count)) => {
879                matched += 1;
880                let ov = session.ovector(count);
881                let (ov0, ov1) = (ov[0], ov[1]);
882                // Without `$matches` nothing is recorded, and a single
883                // match goes on to the empty-match retry below.
884                if subpats {
885                    if ov1 < ov0 {
886                        let warning = Some(format!("{func}(): Get subpatterns list failed").into_bytes());
887                        return done(Value::Bool(false), matches, error, warning);
888                    }
889                    if global {
890                        if let Some(sets) = match_sets.as_mut() {
891                            let set_count = ov.len() / 2;
892                            for (i, set) in sets.iter_mut().enumerate().take(set_count) {
893                                if offset_capture {
894                                    add_offset_pair(set, subject, ov[2 * i], ov[2 * i + 1], None, unmatched_as_null);
895                                } else {
896                                    set.push(match_value(subject, ov[2 * i], ov[2 * i + 1], unmatched_as_null));
897                                }
898                            }
899                            if let Some(mark) = session.mark(&re.code) {
900                                marks
901                                    .get_or_insert_with(Array::new)
902                                    .add(Key::Int(matched - 1), Value::Str(mark.to_vec()));
903                            }
904                            for set in sets.iter_mut().take(num_subpats).skip(set_count) {
905                                if offset_capture {
906                                    add_offset_pair(set, subject, UNSET, UNSET, None, unmatched_as_null);
907                                } else if unmatched_as_null {
908                                    set.push(Value::Null);
909                                } else {
910                                    set.push(Value::Str(Vec::new()));
911                                }
912                            }
913                        } else {
914                            let mut set = Array::new();
915                            re.populate_subpat_array(&mut set, subject, &session, count, flags);
916                            matches.push(Value::Array(set));
917                        }
918                    } else {
919                        re.populate_subpat_array(&mut matches, subject, &session, count, flags);
920                        break;
921                    }
922                }
923                start_offset2 = ov1;
924                if start_offset2 == ov0 {
925                    match re.call(&mut session, subject, start_offset2, Call::Retry) {
926                        Ok(Some(count)) => {
927                            if !global {
928                                break;
929                            }
930                            pending = Some(Ok(Some(count)));
931                            continue;
932                        }
933                        Ok(None) => {
934                            if start_offset2 < len {
935                                start_offset2 += re.unit_length(subject, start_offset2);
936                            } else {
937                                break;
938                            }
939                        }
940                        Err(e) => {
941                            error = set_last_error(PregError::from_pcre(e));
942                            break;
943                        }
944                    }
945                }
946            }
947            Ok(None) => break,
948            Err(e) => {
949                error = set_last_error(PregError::from_pcre(e));
950                break;
951            }
952        }
953        if !global {
954            break;
955        }
956        if start_offset2 > len {
957            error = set_last_error(PregError::Internal);
958            break;
959        }
960    }
961    if let Some(sets) = match_sets {
962        for (i, set) in sets.into_iter().enumerate() {
963            if let Some(names) = &re.names
964                && let Some(name) = &names[i]
965            {
966                matches.update(Key::Str(name.clone()), Value::Array(set.clone()));
967            }
968            matches.push(Value::Array(set));
969        }
970        if let Some(marks) = marks {
971            matches.update(Key::Str(b"MARK".to_vec()), Value::Array(marks));
972        }
973    }
974    if error == PregError::None {
975        done(Value::Int(matched), matches, error, None)
976    } else {
977        done(Value::Bool(false), matches, error, None)
978    }
979}
980
981/// `preg_get_backref()`: a `\n`, `$n` or `${n}` reference at `walk`; the
982/// group number and the position after it.
983fn get_backref(r: &[u8], walk: usize) -> Option<(usize, usize)> {
984    let at = |i: usize| r.get(i).copied().unwrap_or(0);
985    if at(walk + 1) == 0 {
986        return None;
987    }
988    let mut w = walk;
989    let mut in_brace = false;
990    if at(w) == b'$' && at(w + 1) == b'{' {
991        in_brace = true;
992        w += 1;
993    }
994    w += 1;
995    let mut backref;
996    if at(w).is_ascii_digit() {
997        backref = usize::from(at(w) - b'0');
998        w += 1;
999    } else {
1000        return None;
1001    }
1002    if at(w) != 0 && at(w).is_ascii_digit() {
1003        backref = backref * 10 + usize::from(at(w) - b'0');
1004        w += 1;
1005    }
1006    if in_brace {
1007        if at(w) != b'}' {
1008            return None;
1009        }
1010        w += 1;
1011    }
1012    Some((backref, w))
1013}
1014
1015/// Expands a replacement template for one match (`php_pcre_replace_impl()`):
1016/// `ov` holds the pairs of the groups the match set.
1017fn expand_replacement(out: &mut Vec<u8>, replace: &[u8], subject: &[u8], ov: &[usize]) {
1018    let mut walk = 0;
1019    let mut walk_last = 0u8;
1020    while walk < replace.len() {
1021        let c = replace[walk];
1022        if c == b'\\' || c == b'$' {
1023            if walk_last == b'\\' {
1024                if let Some(last) = out.last_mut() {
1025                    *last = c;
1026                }
1027                walk += 1;
1028                walk_last = 0;
1029                continue;
1030            }
1031            if let Some((backref, next)) = get_backref(replace, walk) {
1032                if backref < ov.len() / 2 {
1033                    let (s, e) = (ov[2 * backref], ov[2 * backref + 1]);
1034                    if s != UNSET {
1035                        out.extend_from_slice(&subject[s..e]);
1036                    }
1037                }
1038                walk = next;
1039                continue;
1040            }
1041        }
1042        out.push(c);
1043        walk += 1;
1044        walk_last = c;
1045    }
1046}
1047
1048/// `php_pcre_replace_impl()`: `None` on error (`preg_last_error()` set in
1049/// `error`).
1050fn replace_impl(
1051    re: &Regex,
1052    subject: &[u8],
1053    replacement: &[u8],
1054    mut limit: usize,
1055    replace_count: &mut i64,
1056    error: &mut PregError,
1057) -> Option<Vec<u8>> {
1058    *error = set_last_error(PregError::None);
1059    let len = subject.len();
1060    let mut result: Option<Vec<u8>> = None;
1061    let mut last_end_offset = 0usize;
1062    let mut start_offset;
1063    let mut session = re.session();
1064    let mut count = re.call(&mut session, subject, 0, re.first_call(false));
1065    loop {
1066        let mut piece = last_end_offset;
1067        match count {
1068            Ok(Some(first)) if limit > 0 => {
1069                let mut n = first;
1070                loop {
1071                    let (ov0, ov1) = {
1072                        let ov = session.ovector(n);
1073                        (ov[0], ov[1])
1074                    };
1075                    if ov1 < ov0 {
1076                        *error = set_last_error(PregError::Internal);
1077                        return None;
1078                    }
1079                    *replace_count += 1;
1080                    let mut out = result.take().unwrap_or_default();
1081                    out.extend_from_slice(&subject[piece..ov0]);
1082                    expand_replacement(&mut out, replacement, subject, session.ovector(n));
1083                    result = Some(out);
1084                    limit -= 1;
1085                    start_offset = ov1;
1086                    last_end_offset = start_offset;
1087                    if start_offset == ov0 {
1088                        let retry = re.call(&mut session, subject, start_offset, Call::Retry);
1089                        piece = start_offset;
1090                        match retry {
1091                            Ok(Some(m)) if limit > 0 => {
1092                                n = m;
1093                                continue;
1094                            }
1095                            Ok(_) => {}
1096                            Err(_) if limit == 0 => {}
1097                            Err(e) => {
1098                                *error = set_last_error(PregError::from_pcre(e));
1099                                return None;
1100                            }
1101                        }
1102                        if start_offset < len {
1103                            start_offset += re.unit_length(subject, piece);
1104                        } else {
1105                            return Some(finish(result, subject, last_end_offset));
1106                        }
1107                    }
1108                    break;
1109                }
1110            }
1111            Ok(_) => return Some(finish(result, subject, last_end_offset)),
1112            Err(_) if limit == 0 => return Some(finish(result, subject, last_end_offset)),
1113            Err(e) => {
1114                *error = set_last_error(PregError::from_pcre(e));
1115                return None;
1116            }
1117        }
1118        count = re.call(&mut session, subject, start_offset, Call::Fast);
1119    }
1120}
1121
1122/// `not_matched:` the rest of the subject after the last match.
1123fn finish(result: Option<Vec<u8>>, subject: &[u8], last_end_offset: usize) -> Vec<u8> {
1124    match result {
1125        None => subject.to_vec(),
1126        Some(mut r) => {
1127            r.extend_from_slice(&subject[last_end_offset..]);
1128            r
1129        }
1130    }
1131}
1132
1133/// A `string|array` argument of `preg_replace()`.
1134#[derive(Debug, Clone, PartialEq)]
1135pub enum StrOrArray<'a> {
1136    /// A string.
1137    Str(&'a [u8]),
1138    /// An array of strings, with their keys.
1139    Array(Vec<(Key, Vec<u8>)>),
1140}
1141
1142/// What [`preg_replace`] returns: the result (`Str`, `Array` or `Null`) and
1143/// `$count`.
1144#[derive(Debug, Clone, PartialEq)]
1145pub struct ReplaceResult {
1146    /// The return value: a string, an array, or `null` on failure.
1147    pub result: Value,
1148    /// `$count`, the number of replacements.
1149    pub count: i64,
1150}
1151
1152/// The `$limit` argument as PHP uses it (a `size_t`).
1153fn limit_of(limit: i64) -> usize {
1154    limit as u64 as usize
1155}
1156
1157/// Runs one compiled-or-failed regex over a subject (`php_pcre_replace()`).
1158#[allow(clippy::too_many_arguments)]
1159fn replace_one(
1160    func: &str,
1161    regex: &[u8],
1162    subject: &[u8],
1163    replacement: &[u8],
1164    limit: i64,
1165    count: &mut i64,
1166    error: &mut PregError,
1167    warning: &mut Option<Vec<u8>>,
1168) -> Option<Vec<u8>> {
1169    match cached(func, regex) {
1170        Ok((re, jit_warning)) => {
1171            if jit_warning.is_some() {
1172                *warning = jit_warning;
1173            }
1174            replace_impl(&re, subject, replacement, limit_of(limit), count, error)
1175        }
1176        Err(w) => {
1177            *error = PregError::Internal;
1178            *warning = Some(w);
1179            None
1180        }
1181    }
1182}
1183
1184/// `preg_replace($pattern, $replacement, $subject, $limit, $count)`.
1185pub fn preg_replace(
1186    pattern: &StrOrArray<'_>,
1187    replacement: &StrOrArray<'_>,
1188    subject: &StrOrArray<'_>,
1189    limit: i64,
1190) -> Result<Preg<ReplaceResult>, ArgumentError> {
1191    if let (StrOrArray::Str(_), StrOrArray::Array(_)) = (pattern, replacement) {
1192        return Err(ArgumentError {
1193            class: "TypeError",
1194            message: "preg_replace(): Argument #1 ($pattern) must be of type array when argument #2 ($replacement) is an array, string given".into(),
1195        });
1196    }
1197    let mut error = preg_last_error();
1198    let mut warning = None;
1199    let mut count = 0i64;
1200    let in_subject =
1201        |subject: &[u8], count: &mut i64, error: &mut PregError, warning: &mut Option<Vec<u8>>| -> Option<Vec<u8>> {
1202            match pattern {
1203                StrOrArray::Str(p) => {
1204                    let StrOrArray::Str(r) = replacement else { unreachable!() };
1205                    replace_one("preg_replace", p, subject, r, limit, count, error, warning)
1206                }
1207                StrOrArray::Array(patterns) => {
1208                    let mut current = subject.to_vec();
1209                    let mut replace_idx = 0;
1210                    for (_, p) in patterns {
1211                        let r: &[u8] = match replacement {
1212                            StrOrArray::Str(r) => r,
1213                            StrOrArray::Array(rs) => {
1214                                let r = rs.get(replace_idx).map_or(&[][..], |(_, r)| r.as_slice());
1215                                replace_idx += 1;
1216                                r
1217                            }
1218                        };
1219                        current = replace_one("preg_replace", p, &current, r, limit, count, error, warning)?;
1220                    }
1221                    Some(current)
1222                }
1223            }
1224        };
1225    let result = match subject {
1226        StrOrArray::Str(s) => match in_subject(s, &mut count, &mut error, &mut warning) {
1227            Some(r) => Value::Str(r),
1228            None => Value::Null,
1229        },
1230        StrOrArray::Array(entries) => {
1231            let mut out = Array::new();
1232            for (k, s) in entries {
1233                if let Some(r) = in_subject(s, &mut count, &mut error, &mut warning) {
1234                    out.update(k.clone(), Value::Str(r));
1235                }
1236            }
1237            Value::Array(out)
1238        }
1239    };
1240    Ok(Preg { value: ReplaceResult { result, count }, error, warning })
1241}
1242
1243/// `preg_split($pattern, $subject, $limit, $flags)`: an array, or
1244/// `Bool(false)`.
1245pub fn preg_split(pattern: &[u8], subject: &[u8], limit: i64, flags: i64) -> Preg<Value> {
1246    let (re, warning) = match cached("preg_split", pattern) {
1247        Ok(r) => r,
1248        Err(w) => return Preg { value: Value::Bool(false), error: PregError::Internal, warning: Some(w) },
1249    };
1250    let no_empty = flags & PREG_SPLIT_NO_EMPTY != 0;
1251    let delim_capture = flags & PREG_SPLIT_DELIM_CAPTURE != 0;
1252    let offset_capture = flags & PREG_SPLIT_OFFSET_CAPTURE != 0;
1253    let mut out = Array::new();
1254    let len = subject.len();
1255    let mut start_offset = 0usize;
1256    let mut last_match_offset = 0usize;
1257    let mut error = set_last_error(PregError::None);
1258    let mut limit_val = limit;
1259    let piece = |out: &mut Array, s: usize, e: usize| {
1260        if offset_capture {
1261            add_offset_pair(out, subject, s, e, None, false);
1262        } else {
1263            out.push(match_value(subject, s, e, false));
1264        }
1265    };
1266    let mut run = true;
1267    if limit_val == -1 {
1268    } else if limit_val == 0 {
1269        limit_val = -1;
1270    } else if limit_val <= 1 {
1271        run = false;
1272    }
1273    if run {
1274        let mut session = re.session();
1275        let mut pending = Some(re.call(&mut session, subject, start_offset, re.first_call(false)));
1276        loop {
1277            let count = pending.take().unwrap_or_else(|| re.call(&mut session, subject, start_offset, Call::Fast));
1278            match count {
1279                Ok(Some(count)) => {
1280                    let ov = session.ovector(count);
1281                    let (ov0, ov1) = (ov[0], ov[1]);
1282                    if ov1 < ov0 {
1283                        error = set_last_error(PregError::Internal);
1284                        break;
1285                    }
1286                    if !no_empty || ov0 != last_match_offset {
1287                        piece(&mut out, last_match_offset, ov0);
1288                        if limit_val != -1 {
1289                            limit_val -= 1;
1290                        }
1291                    }
1292                    if delim_capture {
1293                        for i in 1..ov.len() / 2 {
1294                            if !no_empty || ov[2 * i] != ov[2 * i + 1] {
1295                                if ov[2 * i] == UNSET {
1296                                    if offset_capture {
1297                                        add_offset_pair(&mut out, subject, UNSET, UNSET, None, false);
1298                                    } else {
1299                                        out.push(Value::Str(Vec::new()));
1300                                    }
1301                                } else {
1302                                    piece(&mut out, ov[2 * i], ov[2 * i + 1]);
1303                                }
1304                            }
1305                        }
1306                    }
1307                    start_offset = ov1;
1308                    last_match_offset = ov1;
1309                    if start_offset == ov0 {
1310                        if limit_val != -1 && limit_val <= 1 {
1311                            break;
1312                        }
1313                        match re.call(&mut session, subject, start_offset, Call::Retry) {
1314                            Ok(Some(m)) => {
1315                                pending = Some(Ok(Some(m)));
1316                                continue;
1317                            }
1318                            Ok(None) => {
1319                                if start_offset < len {
1320                                    start_offset += re.unit_length(subject, start_offset);
1321                                } else {
1322                                    break;
1323                                }
1324                            }
1325                            Err(e) => {
1326                                error = set_last_error(PregError::from_pcre(e));
1327                                break;
1328                            }
1329                        }
1330                    }
1331                }
1332                Ok(None) => break,
1333                Err(e) => {
1334                    error = set_last_error(PregError::from_pcre(e));
1335                    break;
1336                }
1337            }
1338            if limit_val != -1 && limit_val <= 1 {
1339                break;
1340            }
1341        }
1342        if error != PregError::None {
1343            return Preg { value: Value::Bool(false), error, warning };
1344        }
1345    }
1346    let start = last_match_offset;
1347    if !no_empty || start < len {
1348        piece(&mut out, start, len);
1349    }
1350    Preg { value: Value::Array(out), error, warning }
1351}
1352
1353/// `preg_quote($str, $delimiter)`: only the first byte of the delimiter is
1354/// used.
1355pub fn preg_quote(s: &[u8], delimiter: Option<&[u8]>) -> Vec<u8> {
1356    let delim_char = delimiter.and_then(|d| d.first().copied()).unwrap_or(0);
1357    let mut out = Vec::with_capacity(s.len());
1358    for &c in s {
1359        match c {
1360            b'.' | b'\\' | b'+' | b'*' | b'?' | b'[' | b'^' | b']' | b'$' | b'(' | b')' | b'{' | b'}' | b'=' | b'!'
1361            | b'>' | b'<' | b'|' | b':' | b'-' | b'#' => {
1362                out.push(b'\\');
1363                out.push(c);
1364            }
1365            0 => out.extend_from_slice(b"\\000"),
1366            _ => {
1367                if c == delim_char {
1368                    out.push(b'\\');
1369                }
1370                out.push(c);
1371            }
1372        }
1373    }
1374    out
1375}
1376
1377#[cfg(test)]
1378mod tests {
1379    use super::*;
1380
1381    fn m(p: &str, s: &str) -> Value {
1382        let r = preg_match(p.as_bytes(), s.as_bytes(), 0, 0).unwrap();
1383        Value::Array(r.value.matches.unwrap())
1384    }
1385
1386    fn strs(v: &Value) -> Vec<String> {
1387        let Value::Array(a) = v else { panic!("not an array") };
1388        a.entries()
1389            .iter()
1390            .map(|(_, v)| match v {
1391                Value::Str(s) => String::from_utf8_lossy(s).into_owned(),
1392                other => format!("{other:?}"),
1393            })
1394            .collect()
1395    }
1396
1397    #[test]
1398    fn basic_matches() {
1399        assert_eq!(strs(&m("/a(b)c/", "xabcx")), ["abc", "b"]);
1400        assert_eq!(strs(&m("/(a|ab)(c|bcd)(d*)/", "abcd")), ["abcd", "a", "bcd", ""]);
1401        assert_eq!(strs(&m("/^(\\w+)\\((.+)\\)$/i", "count(x)")), ["count(x)", "count", "x"]);
1402        assert_eq!(strs(&m("/(a+)+b/", "aaab")), ["aaab", "aaa"]);
1403        assert_eq!(strs(&m("/a*?/", "aaa")), [""]);
1404        assert_eq!(strs(&m("/(?<y>\\d{4})-(?<m>\\d\\d)/", "on 2024-05")), ["2024-05", "2024", "2024", "05", "05"]);
1405        assert_eq!(strs(&m("/(a)|(b)/", "b")), ["b", "", "b"]);
1406        assert_eq!(strs(&m("/(?:(a)|b)+/", "ab")), ["ab", "a"]);
1407        assert_eq!(strs(&m("/(?=(\\w+))\\w/", "abc")), ["a", "abc"]);
1408        assert_eq!(strs(&m("/(?<=b)c/", "abc")), ["c"]);
1409        assert_eq!(strs(&m("/(a)(?1)/", "aa")), ["aa", "a"]);
1410        assert_eq!(strs(&m("/\\((?:[^()]|(?R))*\\)/", "x(a(b)c)y")), ["(a(b)c)"]);
1411        assert_eq!(strs(&m("/(?:x|(?:a\\Ka)*)+$/", "aaaa")), ["a"]);
1412        assert_eq!(strs(&m("/é+/u", "aéé")), ["éé"]);
1413        assert_eq!(strs(&m("/\\w+/u", "naïve!")), ["naïve"]);
1414        assert_eq!(strs(&m("/[[:alpha:]]+/", "ab1")), ["ab"]);
1415        assert_eq!(strs(&m("/(*MARK:A)x|(*MARK:B)y/", "y")), ["y", "B"]);
1416    }
1417
1418    #[test]
1419    fn match_all_and_replace() {
1420        let r = preg_match_all(b"/a*?/", b"aaa", 0, 0).unwrap();
1421        assert_eq!(r.value.result, Value::Int(7));
1422        let r = preg_replace(
1423            &StrOrArray::Str(b"/(\\w+) (\\w+)/"),
1424            &StrOrArray::Str(b"$2 ${1}\\\\"),
1425            &StrOrArray::Str(b"hello world"),
1426            -1,
1427        )
1428        .unwrap();
1429        assert_eq!(r.value.result, Value::Str(b"world hello\\".to_vec()));
1430        let r = preg_split(b"/\\s*/", b"a b", -1, PREG_SPLIT_NO_EMPTY);
1431        assert_eq!(strs(&r.value), ["a", "b"]);
1432        assert_eq!(preg_quote(b"a.b*c/\0", Some(b"/")), b"a\\.b\\*c\\/\\000".to_vec());
1433    }
1434
1435    #[test]
1436    fn limits() {
1437        let r = preg_match(b"/(?:\\D+|<\\d+>)*[!?]/", b"foobar foobar foobar", 0, 0).unwrap();
1438        assert_eq!((r.value.result, r.error), (Value::Bool(false), PregError::BacktrackLimit));
1439        let r = preg_match(b"/^(?:a|b)*$/", &b"ab".repeat(4096), 0, 0).unwrap();
1440        assert_eq!(r.error, PregError::JitStackLimit);
1441        let r = preg_match(b"/./u", b"\xff", 0, 0).unwrap();
1442        assert_eq!(r.error, PregError::BadUtf8);
1443    }
1444
1445    #[test]
1446    fn compile_failures() {
1447        let r = preg_match(b"/(abc/", b"x", 0, 0).unwrap();
1448        assert_eq!(r.value.result, Value::Bool(false));
1449        assert_eq!(
1450            r.warning.unwrap(),
1451            b"preg_match(): Compilation failed: missing closing parenthesis at offset 4".to_vec()
1452        );
1453        let r = preg_match(b"abc", b"x", 0, 0).unwrap();
1454        assert_eq!(
1455            r.warning.unwrap(),
1456            b"preg_match(): Delimiter must not be alphanumeric, backslash, or NUL byte".to_vec()
1457        );
1458        let r = preg_match(b"/abc/k", b"x", 0, 0).unwrap();
1459        assert_eq!(r.warning.unwrap(), b"preg_match(): Unknown modifier 'k'".to_vec());
1460        let r = preg_match(b"/\\C/u", b"x", 0, 0).unwrap();
1461        assert_eq!(
1462            r.warning.unwrap(),
1463            b"preg_match(): Compilation failed: using \\C is incompatible with the 'u' modifier at offset 2".to_vec()
1464        );
1465    }
1466
1467    /// A full cache evicts its oldest entries, and a thread that remembers
1468    /// one of them compiles it again, as PHP would.
1469    #[test]
1470    fn cache_evicts() {
1471        let first = Regex::compiled(b"/cache-evicts-first/").unwrap();
1472        assert!(Arc::ptr_eq(&first, &Regex::compiled(b"/cache-evicts-first/").unwrap()));
1473        for i in 0..CACHE_SIZE {
1474            Regex::compiled(format!("/cache-evicts-{i}/").as_bytes()).unwrap();
1475        }
1476        assert!(!Arc::ptr_eq(&first, &Regex::compiled(b"/cache-evicts-first/").unwrap()));
1477    }
1478}