Skip to main content

quickjs/builtins/
regexp.rs

1//! `RegExp` and `RegExp.prototype`.
2//!
3//! The engine lives in [`crate::regexp`]; this module is the JavaScript-facing half: the
4//! constructor, the compiled-pattern cache, `lastIndex`, and `exec`.
5//!
6//! `exec` is where most of the observable semantics live. A `g` or `y` pattern advances
7//! `lastIndex`, a failed match resets it to zero, and the returned array carries the
8//! captured groups plus `index`, `input` and (for the `d` flag) `indices`.
9
10use crate::builtins::substitution::{Substitution, get_substitution};
11use crate::builtins::{arg, define_method, install_species_accessor};
12use crate::interp::{Interp, JsResult};
13use crate::object::{JsObject, Property};
14use crate::regexp::{Flags, Regex};
15use crate::value::Value;
16use js_gc::Gc;
17
18/// The compiled pattern an object of `ObjectKind::RegExp` carries.
19///
20/// Boxed through `Rc` because a `RegExp` object is shared by every reference to it and
21/// the pattern is immutable once compiled.
22#[derive(Clone)]
23pub struct RegExpData {
24    /// The compiled pattern, shared between `exec` calls.
25    pub regex: std::rc::Rc<Regex>,
26    /// Pattern source as written, which `.source` reports.
27    pub source: String,
28    /// The flags, in canonical order.
29    pub flags: String,
30}
31
32/// Install `RegExp` and its prototype methods.
33pub fn install(interp: &mut Interp<'_>, object_proto: &Gc<JsObject>) -> Gc<JsObject> {
34    let prototype = interp.new_object(Some(object_proto.clone()));
35    let constructor = interp.new_native_constructor("RegExp", 2, constructor);
36    constructor.define(
37        "prototype",
38        Property::with_attributes(Value::Object(prototype.clone()), false, false),
39    );
40    prototype.define(
41        "constructor",
42        Property::with_attributes(Value::Object(constructor.clone()), true, false),
43    );
44
45    define_method(&prototype, "exec", 1, exec, interp);
46    define_method(&prototype, "test", 1, test, interp);
47    define_method(&prototype, "toString", 0, to_string, interp);
48    for (name, getter) in [
49        (
50            "source",
51            source as fn(&mut Interp<'_>, Value, &[Value]) -> JsResult<Value>,
52        ),
53        ("flags", flags),
54        ("global", global),
55        ("ignoreCase", ignore_case),
56        ("multiline", multiline),
57        ("sticky", sticky),
58        ("unicode", unicode),
59        ("unicodeSets", unicode_sets),
60        ("dotAll", dot_all),
61        ("hasIndices", has_indices),
62    ] {
63        // `get unicodeSets`, not `unicodeSets`: §22.2.6's accessors are named with the
64        // `get ` prefix, which `RegExp/prototype/unicodeSets/name` checks. The prefix is a
65        // property of the *function*, applied here because `new_native` takes the bare name.
66        let getter = interp.new_native(format!("get {name}"), 0, getter);
67        prototype.define(
68            name,
69            Property {
70                getter: Some(Value::Object(getter)),
71                enumerable: false,
72                configurable: true,
73                ..Property::default()
74            },
75        );
76    }
77
78    // `RegExp.escape` is a static: it is on the constructor, not the prototype.
79    define_method(&constructor, "escape", 1, escape, interp);
80    install_species_accessor(&constructor, interp);
81
82    // `Symbol.match` and friends are what `String.prototype.match` looks up; without them
83    // a regexp is not recognised as a pattern by those methods.
84    install_symbol_methods(interp, &prototype, &constructor);
85    interp.realm.regexp_proto = Some(prototype.clone());
86    interp.realm.regexp_ctor = Some(constructor.clone());
87    constructor
88}
89
90fn install_symbol_methods(
91    interp: &mut Interp<'_>,
92    prototype: &Gc<JsObject>,
93    constructor: &Gc<JsObject>,
94) {
95    use crate::interp::WellKnown;
96    for (which, name, func, length) in [
97        (
98            WellKnown::Match,
99            "[Symbol.match]",
100            symbol_match as crate::object::NativeFn,
101            1,
102        ),
103        (WellKnown::Replace, "[Symbol.replace]", symbol_replace, 2),
104        (
105            WellKnown::MatchAll,
106            "[Symbol.matchAll]",
107            symbol_match_all,
108            1,
109        ),
110        (WellKnown::Search, "[Symbol.search]", symbol_search, 1),
111        (WellKnown::Split, "[Symbol.split]", symbol_split, 2),
112    ] {
113        let method = interp.new_native(name, length, func);
114        prototype.define_key(
115            &interp.realm.well_known_key(which),
116            Property::with_attributes(Value::Object(method), true, false),
117        );
118    }
119    let _ = constructor;
120}
121
122/// `RegExp.escape(string)`: escape `string` so it can be used as a literal pattern.
123///
124/// Two things make this more than a backslash loop:
125///
126/// * **The first character is escaped differently.** A leading ASCII letter or digit
127///   becomes `\xNN`, because `"1"` after a `\0` or `\c` would otherwise be read as part
128///   of the preceding escape rather than as a digit.
129/// * **Most characters need no escape at all.** Only the syntax characters, `/`, the
130///   control escapes, a fixed list of other punctuators, whitespace, line terminators and
131///   lone surrogates are touched; everything else — including all non-ASCII letters — is
132///   copied through, because a literal character in a pattern is already literal outside
133///   syntax positions.
134///
135/// Note `\s`'s set is reused for "whitespace or line terminator" (see
136/// [`quickjs_regexp::is_space`]) rather than restated, so the two cannot drift.
137fn escape(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
138    let arg = arg(args, 0);
139    // Not `ToString`: the spec is explicit that a non-string is a TypeError rather than
140    // being coerced, so `RegExp.escape(1)` throws instead of returning `"1"`.
141    if !matches!(arg, Value::String(_)) {
142        return Err(interp.type_error("not a string"));
143    }
144    let source = interp.checked_to_wtf8(&arg)?.code_point_values();
145    let mut out: Vec<u32> = Vec::with_capacity(source.len());
146    for (position, cp) in source.iter().enumerate() {
147        // `escaped` is empty exactly at the first code point, since every branch below
148        // emits at least one code unit.
149        let leading = position == 0;
150        encode_for_regexp_escape(*cp, leading, &mut out);
151    }
152    Ok(interp.string_wtf8(points_to_wtf8(&out)))
153}
154
155/// The per-code-point half of `RegExp.escape`: `EncodeForRegExpEscape`, plus the leading
156/// alphanumeric rule that the caller knows about and this does not.
157fn encode_for_regexp_escape(c: u32, leading: bool, out: &mut Vec<u32>) {
158    let backslash = u32::from(b'\\');
159    // A leading ASCII letter or digit is always hex-escaped: it may otherwise be read as
160    // part of a preceding `\0…` or `\c…`.
161    let ascii_alnum = matches!(c, 0x30..=0x39 | 0x41..=0x5A | 0x61..=0x7A);
162    if leading && ascii_alnum {
163        push_hex_escape(c, out);
164        return;
165    }
166    // SyntaxCharacter, plus `/` — the one character a pattern literal would terminate on.
167    if matches!(
168        c,
169        0x2E | 0x2A | 0x2B | 0x3F | 0x5E | 0x24 | 0x7C // . * + ? ^ $ |
170        | 0x28 | 0x29 | 0x5B | 0x5D | 0x7B | 0x7D    // ( ) [ ] { }
171        | 0x5C | 0x2F // \ /
172    ) {
173        out.push(backslash);
174        out.push(c);
175        return;
176    }
177    // The five control escapes that have a short spelling.
178    if let Some(letter) = match c {
179        0x09 => Some('t'),
180        0x0A => Some('n'),
181        0x0B => Some('v'),
182        0x0C => Some('f'),
183        0x0D => Some('r'),
184        _ => None,
185    } {
186        out.push(backslash);
187        out.push(u32::from(letter as u8));
188        return;
189    }
190    // `otherPunctuators` from the spec, then whitespace, line terminators and lone
191    // surrogates: all of these become `\xNN` or `\uNNNN`.
192    let other_punctuator = matches!(
193        c,
194        0x2C | 0x2D | 0x3D | 0x3C | 0x3E | 0x23 | 0x26 | 0x21 // , - = < > # & !
195        | 0x25 | 0x3A | 0x3B | 0x40 | 0x7E | 0x27 | 0x60 | 0x22 // % : ; @ ~ ' ` "
196    );
197    if other_punctuator || quickjs_regexp::is_space(c) || (0xD800..=0xDFFF).contains(&c) {
198        if c <= 0xFF {
199            push_hex_escape(c, out);
200        } else {
201            // `\uNNNN`, per code unit. Every code point in this branch is below 0x10000
202            // (the spaces, the line separators, the surrogates), so one unit is enough;
203            // anything astral falls through to the literal case below.
204            out.push(backslash);
205            out.push(u32::from(b'u'));
206            for shift in [12, 8, 4, 0] {
207                out.push(u32::from(hex_digit((c >> shift) & 0xF)));
208            }
209        }
210        return;
211    }
212    // Everything else is already literal in a pattern, so it is copied through.
213    out.push(c);
214}
215
216/// `\xNN` for a code point below 0x100.
217fn push_hex_escape(c: u32, out: &mut Vec<u32>) {
218    out.push(u32::from(b'\\'));
219    out.push(u32::from(b'x'));
220    out.push(u32::from(hex_digit((c >> 4) & 0xF)));
221    out.push(u32::from(hex_digit(c & 0xF)));
222}
223
224/// Lowercase hex, which is the case both `\x` and `\u` escapes are expected in.
225fn hex_digit(nibble: u32) -> u8 {
226    match nibble {
227        0..=9 => b'0' + nibble as u8,
228        _ => b'a' + (nibble as u8 - 10),
229    }
230}
231
232/// `new RegExp(pattern, flags)`.
233///
234/// §22.2.3.1 steps 2–3 are `IsRegExp(pattern)` and, when it answers true, `Get(pattern,
235/// "source")` — **not** a read of the internal slot. That difference is observable: a plain
236/// object whose `@@match` getter throws makes `new RegExp(obj, "")` throw, which is what
237/// test262 `Symbol.matchAll/isregexp-this-throws` runs into on its way through the species
238/// constructor. Reading `object.regexp()` made the constructor silently treat such an object
239/// as a string pattern.
240fn constructor(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
241    let pattern = arg(args, 0);
242    let flags = arg(args, 1);
243    let (source, flags) = if crate::builtins::string::is_regexp(interp, &pattern)? {
244        let Value::Object(object) = &pattern else {
245            return Err(interp.type_error("a regexp is not an object"));
246        };
247        let source = interp
248            .get_property(object, "source")?
249            .unwrap_or(Value::Undefined);
250        let source = interp.to_js_string(&source)?;
251        let flags = if matches!(flags, Value::Undefined) {
252            let flags = interp
253                .get_property(object, "flags")?
254                .unwrap_or(Value::Undefined);
255            interp.checked_to_string(&flags)?
256        } else {
257            interp.checked_to_string(&flags)?
258        };
259        (source, flags)
260    } else {
261        // `RegExpCreate(undefined, flags)`: the *pattern* is empty, the flags are not.
262        // Dropping them made `new RegExp(x, "g")` a non-global regexp, so
263        // `"asdf".replace(new RegExp(undefined, "g"), "1")` replaced once rather than five
264        // times — test262's `replace/S15.5.4.11_A1_T17`.
265        let source = match &pattern {
266            Value::Undefined => String::new(),
267            other => interp.to_js_string(other)?,
268        };
269        let flags = if matches!(flags, Value::Undefined) {
270            String::new()
271        } else {
272            interp.checked_to_string(&flags)?
273        };
274        (source, flags)
275    };
276    let object = allocate(interp)?;
277    Ok(Value::Object(initialise(interp, object, &source, &flags)?))
278}
279
280/// `RegExp.prototype.exec(string)`.
281fn exec(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
282    let Some(object) = this.as_object() else {
283        return Err(interp.type_error("RegExp.prototype.exec called on a non-object"));
284    };
285    let text = interp.checked_to_wtf8(&arg(args, 0))?;
286    exec_on(interp, object, &text)
287}
288
289/// The shared implementation of `exec`, used by the `String` methods as well.
290pub fn exec_on(
291    interp: &mut Interp<'_>,
292    object: &Gc<JsObject>,
293    text: &crate::value::Wtf8,
294) -> JsResult<Value> {
295    let Some(data) = object.regexp() else {
296        return Err(interp.type_error("method called on a non-RegExp"));
297    };
298    let sticky_or_global = data.regex.flags.global || data.regex.flags.sticky;
299    let start = if sticky_or_global {
300        // §22.2.6.2 step 4.b: `ToLength(Get(R, "lastIndex"))`. `ToLength` is **not** a
301        // range check — it clamps: `NaN` (so `undefined`, `null`, a throwing `valueOf` that
302        // answers `NaN`) becomes `0`, a negative value becomes `0`, and a fraction is
303        // truncated. Only `+Infinity` survives as "past the end", which the length check
304        // below turns into a `null` result.
305        let index = interp.get_property(object, "lastIndex")?;
306        let index = interp.to_js_number(&index.unwrap_or(Value::Int(0)))?;
307        let index = if index.is_nan() || index < 0.0 {
308            0.0
309        } else if index.is_infinite() {
310            // Anything at or past `2^53` is past the end of any string.
311            f64::INFINITY
312        } else {
313            index.trunc()
314        };
315        if !index.is_finite() {
316            interp.set_property(object, "lastIndex", Value::Int(0))?;
317            return Ok(Value::Null);
318        }
319        index as usize
320    } else {
321        0
322    };
323    let input = MatchInput::new(&data.regex, text);
324    // A `lastIndex` inside a surrogate pair has no character of its own; it belongs to the
325    // character that contains it, which is the same as rounding down to a unit boundary —
326    // what the reference does, and what makes `/(?:)/gu` with `lastIndex = 1` on `"🐱"`
327    // report `index === 0`.
328    if start > input.units_len() {
329        if sticky_or_global {
330            interp.set_property(object, "lastIndex", Value::Int(0))?;
331        }
332        return Ok(Value::Null);
333    }
334    let start = input.position(start);
335    let found = data.regex.exec_at(&input.units, start);
336    let Some(found) = found else {
337        if sticky_or_global {
338            interp.set_property(object, "lastIndex", Value::Int(0))?;
339        }
340        return Ok(Value::Null);
341    };
342    // `lastIndex` moves to the end of the match, in code units — not characters, which is
343    // why an astral match under `u` advances by two.
344    if sticky_or_global {
345        let end = input.offset(found.end);
346        interp.set_property(object, "lastIndex", Value::Int(end as i32))?;
347    }
348    // The result array: the whole match, then one element per group. A group that did not
349    // participate is `undefined`, not a hole.
350    let mut elements: Vec<Value> = Vec::with_capacity(found.captures.len());
351    for capture in &found.captures {
352        elements.push(match capture {
353            Some((start, end)) => interp.string_wtf8(input.slice(*start, *end)),
354            None => Value::Undefined,
355        });
356    }
357    let array = interp.new_array(elements);
358    let index = input.offset(found.start);
359    let input_value = interp.string_wtf8(text.clone());
360    interp.set_property(&array, "index", Value::Int(index as i32))?;
361    interp.set_property(&array, "input", input_value.clone())?;
362    // `m.groups`: a null-prototype object mapping each *named* group to its capture, or
363    // `undefined` when the pattern has no named groups at all — which is what the spec
364    // says, and what `m.groups === undefined` tests check.
365    //
366    // The object has a `null` prototype (`Object.create(null)`), so `m.groups.toString`
367    // is `undefined` and a group named `toString` does not collide with `Object.prototype`.
368    let groups = if data.regex.names.is_empty() {
369        Value::Undefined
370    } else {
371        let groups = interp.new_object(None);
372        for (name, index) in &data.regex.names {
373            let value = match found.captures.get(*index).copied().flatten() {
374                Some((start, end)) => interp.string_wtf8(input.slice(start, end)),
375                None => Value::Undefined,
376            };
377            interp.set_property(&groups, name, value)?;
378        }
379        Value::Object(groups)
380    };
381    interp.set_property(&array, "groups", groups)?;
382    if data.regex.flags.has_indices {
383        let mut pairs = Vec::with_capacity(found.captures.len());
384        for capture in &found.captures {
385            pairs.push(match capture {
386                Some((start, end)) => {
387                    let (start, end) = (input.offset(*start), input.offset(*end));
388                    let pair =
389                        interp.new_array(vec![Value::Int(start as i32), Value::Int(end as i32)]);
390                    Value::Object(pair)
391                }
392                None => Value::Undefined,
393            });
394        }
395        let indices = interp.new_array(pairs);
396        interp.set_property(&array, "indices", Value::Object(indices))?;
397    }
398    Ok(Value::Object(array))
399}
400
401/// The matcher's view of a string, and the bridge back to the code units a script sees.
402///
403/// Which unit the matcher consumes is decided by the pattern, not by the caller
404/// ([`quickjs_regexp::Regex::per_code_unit`]):
405///
406/// * **No `u`/`v`.** A pattern is a sequence of UTF-16 code units, so `.` matches one unit,
407///   a quantifier binds to one unit, and `[😀]` is a two-unit class. `units` is therefore the
408///   string's code units, every offset the matcher reports is already a code-unit offset —
409///   the unit `lastIndex`, `index`, `.length` and `d`'s pairs are expressed in — and
410///   `unit_start` is the identity.
411/// * **`u`/`v`.** A pattern is a sequence of code points, so `units` is the code points and
412///   `unit_start` maps an offset back to code units.
413///
414/// Having one type for both is what keeps the four call sites (`exec`, `[Symbol.match]`,
415/// `[Symbol.split]`, `[Symbol.replace]`) from each carrying their own copy of the mapping —
416/// they had one, and `[Symbol.split]` was missing it entirely.
417struct MatchInput {
418    /// What the matcher consumes: code units, or code points.
419    units: Vec<u32>,
420    /// `unit_start[i]` is the code-unit offset of matcher position `i`, with one extra
421    /// entry for the end.
422    unit_start: Vec<usize>,
423}
424
425impl MatchInput {
426    fn new(regex: &quickjs_regexp::Regex, text: &crate::value::Wtf8) -> Self {
427        if regex.per_code_unit() {
428            let units: Vec<u32> = text.to_units().into_iter().map(u32::from).collect();
429            let unit_start = (0..=units.len()).collect();
430            Self { units, unit_start }
431        } else {
432            let units = text.code_point_values();
433            let mut unit_start = Vec::with_capacity(units.len() + 1);
434            let mut count = 0;
435            for point in &units {
436                unit_start.push(count);
437                count += if *point > 0xFFFF { 2 } else { 1 };
438            }
439            unit_start.push(count);
440            Self { units, unit_start }
441        }
442    }
443
444    /// How many positions the matcher can be at — code units, for both kinds of pattern,
445    /// since that is what `lastIndex` is compared against.
446    fn units_len(&self) -> usize {
447        self.unit_start[self.unit_start.len() - 1]
448    }
449
450    /// The matcher position a code-unit offset starts at, rounded down to a boundary.
451    ///
452    /// The rounding is what makes a `lastIndex` in the middle of a surrogate pair land on
453    /// the character that contains it instead of between two.
454    fn position(&self, offset: usize) -> usize {
455        self.unit_start
456            .partition_point(|start| *start <= offset)
457            .saturating_sub(1)
458    }
459
460    /// The code-unit offset of a matcher position.
461    fn offset(&self, position: usize) -> usize {
462        self.unit_start[position.min(self.unit_start.len() - 1)]
463    }
464
465    /// The text between two matcher positions.
466    ///
467    /// Built through UTF-16 so that a lone surrogate survives: collecting code points into a
468    /// `String` would turn one into U+FFFD, and then `exec` would report different text than
469    /// the input it was given.
470    fn slice(&self, start: usize, end: usize) -> crate::value::Wtf8 {
471        points_to_wtf8(self.units.get(start..end).unwrap_or_default())
472    }
473}
474
475/// Code points (or code units) to WTF-8, keeping a lone surrogate instead of replacing it.
476fn points_to_wtf8(points: &[u32]) -> crate::value::Wtf8 {
477    let mut units = Vec::with_capacity(points.len());
478    for point in points {
479        if *point > 0xFFFF {
480            let value = point - 0x10000;
481            units.push(0xD800 + (value >> 10) as u16);
482            units.push(0xDC00 + (value & 0x3FF) as u16);
483        } else {
484            units.push(*point as u16);
485        }
486    }
487    crate::value::Wtf8::from_units(&units)
488}
489
490/// `RegExp.prototype.test(string)`.
491fn test(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
492    let result = exec(interp, this, args)?;
493    Ok(Value::Bool(!matches!(result, Value::Null)))
494}
495
496fn to_string(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
497    let Some(object) = this.as_object() else {
498        return Err(interp.type_error("RegExp.prototype.toString called on a non-object"));
499    };
500    let Some(data) = object.regexp() else {
501        return Err(interp.type_error("RegExp.prototype.toString called on a non-RegExp"));
502    };
503    let source = if data.source.is_empty() {
504        "(?:)".to_string()
505    } else {
506        data.source.clone()
507    };
508    Ok(interp.string(format!("/{source}/{}", data.flags)))
509}
510
511fn source(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
512    // §22.2.6.13: `RegExp.prototype` has no pattern, and the spec has it answer `"(?:)"`
513    // rather than throw — which is also what keeps `/` + source + `/` re-parseable.
514    if is_regexp_prototype(interp, &this) {
515        return Ok(interp.string("(?:)"));
516    }
517    let data = data_of(interp, &this)?;
518    // An empty pattern reports `(?:)` so that `/` + source + `/` parses again.
519    if data.source.is_empty() {
520        return Ok(interp.string("(?:)"));
521    }
522    // Section 22.2.6.13 `EscapeRegExpPattern`: exactly three characters would break the
523    // `/source/flags` round trip, so they are escaped and nothing else is. A slash becomes
524    // a backslash followed by a slash; a line feed and a carriage return each become a
525    // backslash followed by the letter. Everything else is reported verbatim, non-ASCII
526    // included — a surrogate pair survives as the pair, which is what `source/value-u`
527    // re-parses.
528    let mut text = String::with_capacity(data.source.len());
529    for c in data.source.chars() {
530        match c {
531            '/' => text.push_str("\\/"),
532            '\n' => text.push_str("\\n"),
533            '\r' => text.push_str("\\r"),
534            _ => text.push(c),
535        }
536    }
537    let text = text;
538    Ok(interp.string(&text))
539}
540
541/// `RegExp.prototype.flags` — §22.2.4.8.
542///
543/// Every flag is `Get(R, name)`, one observable property read each, **not** a peek at the
544/// internal slots. That is what makes `get-global-err` throw (the `global` getter is user
545/// code) and what makes `builtin-success-g-set-lastindex` see `global: false` on a regexp
546/// that *is* global — and, because `@@match` derives `global` from this string, what makes
547/// it behave like the reference instead of like the slot.
548///
549/// The order below is the spec's canonical order (`dgimsuvy`), so the answer reads the same
550/// as `RegExp.prototype.toString` builds it.
551fn flags(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
552    let Some(object) = this.as_object().cloned() else {
553        return Err(interp.type_error("flags called on a non-object"));
554    };
555    let mut out = String::with_capacity(8);
556    for (name, letter) in [
557        ("hasIndices", 'd'),
558        ("global", 'g'),
559        ("ignoreCase", 'i'),
560        ("multiline", 'm'),
561        ("dotAll", 's'),
562        ("unicode", 'u'),
563        ("unicodeSets", 'v'),
564        ("sticky", 'y'),
565    ] {
566        let value = interp
567            .get_property(&object, name)?
568            .unwrap_or(Value::Undefined);
569        if value.to_boolean() {
570            out.push(letter);
571        }
572    }
573    Ok(interp.string(out))
574}
575
576fn data_of(interp: &mut Interp<'_>, this: &Value) -> JsResult<RegExpData> {
577    match this.as_object().and_then(|object| object.regexp()) {
578        Some(data) => Ok(data.clone()),
579        None => Err(interp.type_error("method called on a non-RegExp")),
580    }
581}
582
583/// Every `RegExp.prototype` accessor starts here (§22.2.6.4's preamble).
584///
585/// `RegExp.prototype` is deliberately **not** a `RegExp`: it has no `[[OriginalSource]]`
586/// and no `[[OriginalFlags]]`, and the spec says so explicitly so that the getters answer
587/// the "no pattern" values (`undefined` for a flag, `"(?:)"` for `source`, `""` for
588/// `flags`) instead of throwing. Anything else without the internal slot is a `TypeError`.
589fn is_regexp_prototype(interp: &Interp<'_>, this: &Value) -> bool {
590    let Some(object) = this.as_object() else {
591        return false;
592    };
593    let Some(proto) = interp.realm.regexp_proto.as_ref() else {
594        return false;
595    };
596    object.ptr_eq(proto)
597}
598
599/// One of the boolean flag accessors.
600fn flag_getter(interp: &mut Interp<'_>, this: Value, pick: fn(&Flags) -> bool) -> JsResult<Value> {
601    if is_regexp_prototype(interp, &this) {
602        return Ok(Value::Undefined);
603    }
604    let data = data_of(interp, &this)?;
605    Ok(Value::Bool(pick(&data.regex.flags)))
606}
607
608fn global(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
609    flag_getter(interp, this, |flags| flags.global)
610}
611fn ignore_case(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
612    flag_getter(interp, this, |flags| flags.ignore_case)
613}
614fn multiline(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
615    flag_getter(interp, this, |flags| flags.multiline)
616}
617fn sticky(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
618    flag_getter(interp, this, |flags| flags.sticky)
619}
620fn unicode(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
621    flag_getter(interp, this, |flags| flags.unicode)
622}
623fn unicode_sets(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
624    flag_getter(interp, this, |flags| flags.unicode_sets)
625}
626fn dot_all(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
627    flag_getter(interp, this, |flags| flags.dot_all)
628}
629fn has_indices(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
630    flag_getter(interp, this, |flags| flags.has_indices)
631}
632
633// -- the Symbol methods ------------------------------------------------------
634//
635// These are what `String.prototype.match` and friends dispatch to. Each one re-reads the
636// pattern's flags through the object's own properties, as the spec does, so a subclass
637// that overrides `lastIndex` keeps working.
638
639/// `String.prototype.match`'s hook — §22.2.7.2.
640///
641/// The global branch collects `ToString(result[0])`, **not** the result objects: `"aa".match(/a/g)`
642/// is `["a","a"]`, an array of strings. It used to push the whole `exec` array, so every
643/// global match came back as a nested array — visible to any `===` comparison against a
644/// string, which is most of `S15.5.4.10_A2_*`.
645fn symbol_match(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
646    let Some(object) = this.as_object().cloned() else {
647        return Err(interp.type_error("Symbol.match called on a non-object"));
648    };
649    let text = interp.checked_to_wtf8(&arg(args, 0))?;
650    let text_value = interp.string_wtf8(text.clone());
651    // §22.2.7.2 step 3 reads `flags` **before** it decides anything, and reads it once:
652    // `global` and `unicode` are parsed out of that string rather than read as their own
653    // properties. Reading `global`/`unicode` directly made `flags-tostring-error` and
654    // `get-flags-err` unreachable — a regexp whose `flags` getter throws was silently
655    // treated as non-global instead of throwing, and a subclass that overrides `flags`
656    // was ignored entirely.
657    let flags = interp
658        .get_property(&object, "flags")?
659        .unwrap_or(Value::Undefined);
660    let flags = interp.checked_to_string(&flags)?;
661    let is_global = flags.contains('g');
662    let full_unicode = flags.contains('u') || flags.contains('v');
663    if !is_global {
664        return regexp_exec(interp, &Value::Object(object), &text_value);
665    }
666    interp.set_property(&object, "lastIndex", Value::Int(0))?;
667    let units = text.to_units();
668    let mut results = Vec::new();
669    loop {
670        let result = regexp_exec(interp, &Value::Object(object.clone()), &text_value)?;
671        let Value::Object(hit) = result else {
672            // `null` ends the walk; an empty `A` means the whole match failed.
673            break;
674        };
675        let matched = interp.get_property(&hit, "0")?.unwrap_or(Value::Undefined);
676        // `ToString(result[0])`, keeping the code units: a match can *be* half a surrogate
677        // pair (`. ` without `u`), and the lossy `String` path turns that half into U+FFFD —
678        // `"𠮷".match(/./g)` answered two replacement characters instead of the two halves.
679        let matched = interp.checked_to_wtf8(&matched)?;
680        let empty = matched.is_empty();
681        results.push(interp.string_wtf8(matched));
682        if empty {
683            // An empty match leaves `lastIndex` where it was, so it is advanced by one
684            // position — a code point rather than a unit under `u`.
685            let next = interp
686                .get_property(&object, "lastIndex")?
687                .unwrap_or(Value::Int(0));
688            let next = interp.to_js_number(&next)?;
689            let next = advance_string_index(&units, next, full_unicode);
690            interp.set_property(&object, "lastIndex", Value::Float(next))?;
691        }
692    }
693    if results.is_empty() {
694        return Ok(Value::Null);
695    }
696    Ok(Value::Object(interp.new_array(results)))
697}
698
699/// §22.2.7.3 `RegExp.prototype [ @@matchAll ] ( string )`.
700///
701/// Two things here are easy to get wrong and are both tested by test262:
702///
703/// * **`lastIndex` is read once, at creation, and shows up as a property *copy*.** The
704///   species constructor is handed `(R, flags)` and would therefore carry `R`'s
705///   `lastIndex` over, so the value is read here first, coerced with `ToLength`, and set on
706///   the *clone* — `this-lastindex-cached.js` asserts that reassigning `R.lastIndex`
707///   afterwards changes nothing.
708/// * **`Symbol.match` is consulted through `IsRegExp`, not through the internal slot.**
709///   `isregexp-called-once.js` installs a counting getter on `RegExp.prototype[@@match]`,
710///   so the pattern's regexp-ness has to be probed exactly once.
711///
712/// Returning `string.matchAll(re)` for a string pattern works because this method exists:
713/// the string method is specified to build a `RegExp` and then call *this*. The previous
714/// error message ("matchAll needs a global RegExp") pointed the blame at the caller's
715/// regexp, which was never the problem.
716fn symbol_match_all(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
717    let Some(object) = this.as_object().cloned() else {
718        return Err(interp.type_error("Symbol.matchAll called on a non-object"));
719    };
720    let text = interp.checked_to_wtf8(&arg(args, 0))?;
721    // A missing `%RegExp%` means the realm is half-built; `undefined` here would turn that
722    // into a confusing "not a constructor" instead of the real problem.
723    let default_constructor = match interp.realm.regexp_ctor.clone() {
724        Some(constructor) => Value::Object(constructor),
725        None => return Err(interp.type_error("the realm has no RegExp constructor")),
726    };
727    let constructor = interp.species_constructor(&object, default_constructor.clone())?;
728    let flags = interp
729        .get_property(&object, "flags")?
730        .unwrap_or(Value::Undefined);
731    let flags = interp.checked_to_string(&flags)?;
732    let matcher = interp.construct(
733        constructor,
734        default_constructor,
735        vec![Value::Object(object.clone()), interp.string(flags.clone())],
736    )?;
737    let Some(matcher) = matcher.as_object().cloned() else {
738        return Err(interp.type_error("species constructor did not answer an object"));
739    };
740    // `IsRegExp` is **not** re-read here. `Construct(C, «R, flags»)` above already ran it
741    // (the `RegExp` constructor's step 2) and that is the read `isregexp-called-once` counts;
742    // doing it again here made the `@@match` getter fire twice. For the same reason a plain
743    // object whose getter throws throws from the constructor — `isregexp-this-throws` passes
744    // without a second probe. What is needed locally is only the internal-slot test, to
745    // decide whether `lastIndex` belongs on the clone.
746    let is_regexp = object.regexp().is_some();
747    if is_regexp {
748        // §22.2.7.3 MatchAllIterator steps 2.e–2.g. `ToLength` of a `lastIndex` that is an
749        // object runs its `valueOf`, which is what `this-lastindex-cached.js` relies on.
750        let cached = interp
751            .get_property(&object, "lastIndex")?
752            .unwrap_or(Value::Undefined);
753        let cached = interp.to_js_number(&cached)?;
754        let cached = to_length(cached);
755        interp.set_property(&matcher, "lastIndex", Value::Float(cached))?;
756    }
757    // The two flags are read off the **coerced flag string**, not off the clone. A species
758    // constructor that returns a regexp with a throwing `global` getter therefore never
759    // runs it — `species-regexp-get-global-throws.js` asserts exactly that.
760    let global = flags.contains('g');
761    let full_unicode = flags.contains('u') || flags.contains('v');
762    Ok(new_regexp_string_iterator(
763        interp,
764        matcher,
765        text,
766        global,
767        full_unicode,
768    ))
769}
770
771/// `%RegExpStringIteratorPrototype%`, created on first use.
772///
773/// It is installed lazily rather than at bootstrap because `RegExp` is installed before
774/// `Iterator.prototype` exists in some embedders, and because the prototype needs the
775/// realm's `%Object.prototype%` only.
776fn regexp_string_iterator_proto(interp: &mut Interp<'_>) -> Gc<JsObject> {
777    if let Some(proto) = interp.realm.iterator_protos.get(REGEXP_STRING_ITERATOR_TAG) {
778        return proto.clone();
779    }
780    interp.new_iterator_prototype(REGEXP_STRING_ITERATOR_TAG, regexp_string_iterator_next)
781}
782
783const REGEXP_STRING_ITERATOR_TAG: &str = "RegExp String Iterator";
784
785/// §22.2.9.1 CreateRegExpStringIterator — the object behind `[@@matchAll]`.
786///
787/// The state lives under non-enumerable "_"-prefixed properties, the same shape the array
788/// iterators use. Two of the four are internal slots and two are the flags that decide how
789/// `next` advances, so `Object.keys` on the iterator stays empty either way.
790fn new_regexp_string_iterator(
791    interp: &mut Interp<'_>,
792    matcher: Gc<JsObject>,
793    text: crate::value::Wtf8,
794    global: bool,
795    full_unicode: bool,
796) -> Value {
797    let proto = regexp_string_iterator_proto(interp);
798    let object = interp.new_object(Some(proto));
799    // Non-enumerable, so `Object.keys` on the iterator stays `[]` as the reference's does.
800    // They are ordinary properties rather than true internal slots, which is the same trade
801    // the array iterators make; `next` re-checks `_iterating` is *own*, so an object that
802    // merely inherits from an iterator (`Object.create(iterator)`) is still a `TypeError`.
803    let hidden = |value: Value| Property {
804        value: Some(value),
805        writable: true,
806        enumerable: false,
807        configurable: true,
808        ..Property::default()
809    };
810    object.define("_iterating", hidden(Value::Bool(true)));
811    object.define("_matcher", hidden(Value::Object(matcher)));
812    object.define("_string", hidden(interp.string_wtf8(text)));
813    object.define("_global", hidden(Value::Bool(global)));
814    object.define("_fullUnicode", hidden(Value::Bool(full_unicode)));
815    Value::Object(object)
816}
817
818/// §22.2.9.2.1 `%RegExpStringIteratorPrototype%.next()`.
819///
820/// Step order matters: the *matcher's* `exec` is looked up **each time** rather than once at
821/// creation, so replacing `RegExp.prototype.exec` between two `next` calls is observed.
822fn regexp_string_iterator_next(
823    interp: &mut Interp<'_>,
824    this: Value,
825    _args: &[Value],
826) -> JsResult<Value> {
827    let Some(iterator) = this.as_object().cloned() else {
828        return Err(interp.type_error("next called on a non-object"));
829    };
830    // §22.2.9.2.1 step 3: the slots have to be the object's *own*. A prototype-inherited
831    // `_iterating` would let `Object.create(iterator).next()` walk the original's state,
832    // which is exactly what `next-missing-internal-slots.js` forbids.
833    let iterating = match iterator.own_property("_iterating") {
834        Some(property) => property.value.unwrap_or(Value::Undefined),
835        None => {
836            return Err(
837                interp.type_error("next called on an object that is not a RegExp String Iterator")
838            );
839        }
840    };
841    if !iterating.to_boolean() {
842        return Ok(iterator_result(interp, Value::Undefined, true));
843    }
844    let matcher = interp
845        .get_property(&iterator, "_matcher")?
846        .unwrap_or(Value::Undefined);
847    let text = interp
848        .get_property(&iterator, "_string")?
849        .unwrap_or(Value::Undefined);
850    let global = interp
851        .get_property(&iterator, "_global")?
852        .unwrap_or(Value::Undefined)
853        .to_boolean();
854    let full_unicode = interp
855        .get_property(&iterator, "_fullUnicode")?
856        .unwrap_or(Value::Undefined)
857        .to_boolean();
858    let match_value = regexp_exec(interp, &matcher, &text)?;
859    if matches!(match_value, Value::Null) {
860        iterator.define_data("_iterating", Value::Bool(false));
861        return Ok(iterator_result(interp, Value::Undefined, true));
862    }
863    if !global {
864        iterator.define_data("_iterating", Value::Bool(false));
865        return Ok(iterator_result(interp, match_value, false));
866    }
867    // "Global" means: match again from the advanced `lastIndex`. An empty match would leave
868    // it where it is, so it is pushed forward by one — and the units it moves are code
869    // points under `u`, which is what `u-advance-after-empty.js` checks on an astral pair.
870    let empty = {
871        let Value::Object(ref hit) = match_value else {
872            return Err(interp.type_error("exec did not answer an array"));
873        };
874        let first = interp.get_property(hit, "0")?.unwrap_or(Value::Undefined);
875        interp.to_js_string(&first)?.is_empty()
876    };
877    if empty {
878        let matcher_object = match matcher.as_object() {
879            Some(object) => object.clone(),
880            None => return Err(interp.type_error("exec did not answer an array")),
881        };
882        let index = interp
883            .get_property(&matcher_object, "lastIndex")?
884            .unwrap_or(Value::Int(0));
885        let index = interp.to_js_number(&index)?;
886        let units = text
887            .as_wtf8()
888            .map(|text| text.to_units())
889            .unwrap_or_default();
890        let next = advance_string_index(&units, index, full_unicode);
891        interp.set_property(&matcher_object, "lastIndex", Value::Float(next))?;
892    }
893    Ok(iterator_result(interp, match_value, false))
894}
895
896/// §7.1.20 `ToLength`, as a number rather than a `usize`.
897///
898/// Kept local rather than reusing `array`'s, which clamps to `MAX_SAFE_INTEGER` as an index
899/// type: `lastIndex` is stored back into the regexp, so the exact double has to survive.
900fn to_length(value: f64) -> f64 {
901    if value.is_nan() || value <= 0.0 {
902        return 0.0;
903    }
904    value.trunc().min(9_007_199_254_740_991.0)
905}
906
907/// §22.2.9.2.1 `AdvanceStringIndex(S, index, unicode)`.
908///
909/// The stride is one *unit* unless `fullUnicode`, in which case an index that lands on the
910/// lead half of a surrogate pair skips both halves. `index + 1` is returned unchanged past
911/// the end, so the caller's next `exec` fails and the iteration stops.
912fn advance_string_index(units: &[u16], index: f64, unicode: bool) -> f64 {
913    if !unicode || !index.is_finite() || index < 0.0 {
914        return index + 1.0;
915    }
916    let start = index as usize;
917    let Some(&lead) = units.get(start) else {
918        return index + 1.0;
919    };
920    if !(0xD800..=0xDBFF).contains(&lead) {
921        return index + 1.0;
922    }
923    match units.get(start + 1) {
924        Some(&trail) if (0xDC00..=0xDFFF).contains(&trail) => index + 2.0,
925        _ => index + 1.0,
926    }
927}
928
929/// §7.4.14 `RegExpExec(R, S)` — the *generic* one, which is what every `@@` method uses.
930///
931/// A pattern whose `exec` is callable gets to answer for itself (that is how a subclass or a
932/// duck-typed matcher participates), and only an `undefined` answer falls back to the
933/// builtin. Requiring the result to be an object or `null` is a real check, not a formality:
934/// `exec-return-type-invalid.js` asserts the `TypeError`.
935pub(crate) fn regexp_exec(
936    interp: &mut Interp<'_>,
937    matcher: &Value,
938    text: &Value,
939) -> JsResult<Value> {
940    let exec_fn = match matcher.as_object() {
941        Some(object) => interp.get_property(object, "exec")?,
942        None => None,
943    };
944    if let Some(exec_fn) = exec_fn
945        && matches!(&exec_fn, Value::Object(function) if function.is_callable())
946    {
947        let result = interp.call_value(exec_fn, matcher.clone(), vec![text.clone()])?;
948        return match result {
949            Value::Object(_) | Value::Null => Ok(result),
950            _ => Err(interp.type_error("exec must answer an object or null")),
951        };
952    }
953    let Some(object) = matcher.as_object().cloned() else {
954        return Err(interp.type_error("method called on a non-RegExp"));
955    };
956    let text = interp.checked_to_wtf8(text)?;
957    exec_on(interp, &object, &text)
958}
959
960/// An `{value, done}` iterator result, created with the realm's `%Object.prototype%`.
961fn iterator_result(interp: &mut Interp<'_>, value: Value, done: bool) -> Value {
962    let proto = interp.realm.object_proto.clone();
963    let result = interp.new_object(Some(proto));
964    result.define_data("value", value);
965    result.define_data("done", Value::Bool(done));
966    Value::Object(result)
967}
968
969/// `String.prototype.search`'s hook: the index of the first match, or -1.
970///
971/// §22.2.6.13. Step 5 delegates to `RegExpExec`, not to the compiled matcher — the same
972/// correction `@@replace` (§4.40) and `@@split` (§4.41) needed, and this was the last member
973/// of the family still scanning directly. The visible consequence is that a receiver which
974/// is not a `RegExp` must still work, because `RegExpExec` only insists on an `exec`:
975///
976/// ```js
977/// RegExp.prototype[Symbol.search].call({exec: () => ({index: 2})}, "abc")   // 2
978/// ```
979///
980/// It failed 5 of the 23 cases in `RegExp/prototype/Symbol.search`, and the error was
981/// `method called on a non-RegExp` — blaming the caller for using the hook the spec says to.
982///
983/// **`lastIndex` is read, not just written.** The obvious implementation resets it with one
984/// `Set`; the spec reads it first and only writes when it is not already `0`, which is
985/// observable through a getter/setter pair, and `lastindex-no-restore` counts both:
986///
987/// * `lastIndexReads == 2` — once here, once inside `exec`'s own `[[Get]]`;
988/// * `lastIndexWrites == 0` when it started at `0`, `== 1` when it did not.
989///
990/// Getting this wrong is invisible without an accessor, which is exactly why the test uses
991/// one. A poisoned getter must also propagate (`get-lastindex-err`).
992fn symbol_search(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
993    let Some(object) = this.as_object().cloned() else {
994        return Err(interp.type_error("Symbol.search called on a non-object"));
995    };
996    let text = arg(args, 0);
997    // §22.2.6.13 steps 4–8, in order. Every one of them is observable, and
998    // `lastindex-no-restore` counts the reads and writes through a getter/setter pair:
999    //
1000    //   4. previousLastIndex = Get(rx, "lastIndex")      // read 1
1001    //   5. if previousLastIndex is not 0: Set(rx, 0)
1002    //   6. result = RegExpExec(rx, S)                    // may read again
1003    //   7. currentLastIndex = Get(rx, "lastIndex")       // read 2
1004    //   8. if currentLastIndex is not previousLastIndex: Set(rx, previousLastIndex)
1005    //
1006    // So a `lastIndex` of 0 is *never written*, one of 420 is written twice when `exec`
1007    // leaves it alone — and the restore in step 8 is what makes `search` non-destructive.
1008    // Resetting up front and not restoring (the obvious reading) gets every one of those
1009    // wrong, and looks correct until an accessor is watching.
1010    let previous = interp.get_property(&object, "lastIndex")?;
1011    let previous_is_zero = matches!(previous, Some(Value::Int(0)) | None);
1012    if !previous_is_zero {
1013        interp.set_property(&object, "lastIndex", Value::Int(0))?;
1014    }
1015    let result = regexp_exec(interp, &this, &text)?;
1016    let current = interp.get_property(&object, "lastIndex")?;
1017    let unchanged = match (&current, &previous) {
1018        (Some(a), Some(b)) => a.same_value(b),
1019        (None, None) => true,
1020        _ => false,
1021    };
1022    if !unchanged {
1023        let restore = previous.clone().unwrap_or(Value::Undefined);
1024        interp.set_property(&object, "lastIndex", restore)?;
1025    }
1026    let Value::Object(array) = result else {
1027        // `null` means "no match"; a broken `exec` already threw inside `regexp_exec`.
1028        return Ok(Value::Int(-1));
1029    };
1030    Ok(interp
1031        .get_property(&array, "index")?
1032        .unwrap_or(Value::Int(-1)))
1033}
1034
1035/// `String.prototype.split`'s hook.
1036///
1037/// §22.2.6.14. This is the last of the `Symbol.*` family to stop scanning with the compiled
1038/// matcher directly, and it matters for the same reason `@@replace` did: a subclass or a
1039/// duck-typed object has to be able to answer for itself.
1040///
1041/// ```js
1042/// var r = /a/; r.exec = () => null; "abc".split(r)   // ["abc"], and exec ran
1043/// ```
1044///
1045/// Three details are easy to get wrong and each one has cases behind it:
1046///
1047/// * **`flags` gets a `y` appended** unless it already has one (step 8). The clone is
1048///   sticky so that `exec` anchors at `lastIndex`; without it a pattern without `g` would
1049///   match from anywhere and the bookkeeping below silently produces the wrong pieces.
1050/// * **`limit` is `ToUint32`, not a clamp.** `split(re, -1)` keeps everything because
1051///   `ToUint32(-1)` is 4294967295, while `split(re, 2**32)` is the empty array. The
1052///   previous code treated negatives as zero, which was wrong for exactly those inputs.
1053/// * **the scan resumes at `p`, not at the end of the match.** Only `p` moves; getting past
1054///   a zero-width match has to go through `AdvanceStringIndex`, which is the `e == p` branch.
1055fn symbol_split(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
1056    let Some(object) = this.as_object().cloned() else {
1057        return Err(interp.type_error("Symbol.split called on a non-object"));
1058    };
1059    // 4. `ToString(string)` comes before anything else is read off the regexp.
1060    let text = interp.checked_to_wtf8(&arg(args, 0))?;
1061    let units = text.to_units();
1062    // 5. `SpeciesConstructor(rx, %RegExp%)`.
1063    let default_constructor = match interp.realm.regexp_ctor.clone() {
1064        Some(constructor) => Value::Object(constructor),
1065        None => return Err(interp.type_error("the realm has no RegExp constructor")),
1066    };
1067    let constructor = interp.species_constructor(&object, default_constructor.clone())?;
1068    // 6-7. `flags` is `ToString(Get(rx, "flags"))` — the property, not the pattern's slots.
1069    let flags = interp
1070        .get_property(&object, "flags")?
1071        .unwrap_or(Value::Undefined);
1072    let flags = interp.checked_to_string(&flags)?;
1073    // 8. `unicodeMatching` is decided from the `flags` *string*, and `y` is appended when
1074    // absent so that `exec` anchors at `lastIndex`.
1075    let unicode_matching = flags.contains('u') || flags.contains('v');
1076    let sticky_flags = if flags.contains('y') {
1077        flags.clone()
1078    } else {
1079        format!("{flags}y")
1080    };
1081    // 9. `Construct(C, «rx, flags»)`. **`newTarget` is `C`, not `%RegExp%`**: passing the
1082    // default here made the clone a plain `RegExp` even when `C` was a subclass, so a
1083    // subclass's `exec` on its prototype was never reached — `@@split` then scanned with the
1084    // builtin matcher and quietly produced the right pieces for the wrong reason. Every
1085    // clone-routing probe (`split:exec-is-taken-from-...`) was blind to it until `exec` was
1086    // observed at the prototype rather than on the receiver.
1087    let splitter = interp.construct(
1088        constructor.clone(),
1089        constructor,
1090        vec![Value::Object(object), interp.string(sticky_flags)],
1091    )?;
1092    // `SpeciesCreate` answering a primitive would be a `TypeError` further down (the clone
1093    // has to carry a `lastIndex`); failing here names the real cause.
1094    let Some(splitter_object) = splitter.as_object().cloned() else {
1095        return Err(interp.type_error("species constructor did not answer an object"));
1096    };
1097    // 11-12. `lim` is `ToUint32(limit)`; a zero limit is the empty array *before* any match.
1098    let limit = match arg(args, 1) {
1099        Value::Undefined => u32::MAX,
1100        other => Value::Float(interp.to_js_number(&other)?).to_uint32(),
1101    };
1102    let mut parts: Vec<Value> = Vec::new();
1103    if limit == 0 {
1104        return Ok(Value::Object(interp.new_array(parts)));
1105    }
1106    let size = units.len();
1107    // 13. An empty subject still asks `exec` once — `"".split(/x/)` is `[""]`, but
1108    // `"".split(/(?:)/)` is `[]` because that match *succeeds*, so the algorithm returns
1109    // the (still empty) array instead of falling through to the tail.
1110    if size == 0 {
1111        let subject = interp.string_wtf8(text.clone());
1112        let result = regexp_exec(interp, &splitter, &subject)?;
1113        if matches!(result, Value::Null) {
1114            parts.push(interp.string_wtf8(text));
1115        }
1116        return Ok(Value::Object(interp.new_array(parts)));
1117    }
1118    let mut last = 0usize;
1119    let mut scan = 0usize;
1120    // 14. `scan` is `q`, the search position; `last` is `p`, the end of the previous match.
1121    while scan < size {
1122        // 14.a. `lastIndex` is written before every `exec`, through the property system so
1123        // that a clone with a setter (or a subclass) observes the write.
1124        interp.set_property(&splitter_object, "lastIndex", Value::Int(scan as i32))?;
1125        let subject = interp.string_wtf8(text.clone());
1126        let result = regexp_exec(interp, &splitter, &subject)?;
1127        let Value::Object(hit) = &result else {
1128            // 14.b. No match here: step the search position and try again.
1129            scan = advance_string_index(&units, scan as f64, unicode_matching) as usize;
1130            continue;
1131        };
1132        // 14.c. `e` is `ToLength(Get(splitter, "lastIndex"))`, clamped to the subject.
1133        let end = interp
1134            .get_property(&splitter_object, "lastIndex")?
1135            .unwrap_or(Value::Undefined);
1136        let end = to_length(interp.to_js_number(&end)?);
1137        let end = if end > size as f64 {
1138            size
1139        } else {
1140            end as usize
1141        };
1142        if end == last {
1143            // 14.c.iii. A zero-width match at `p` cannot split anything; stepping is what
1144            // keeps the loop finite.
1145            scan = advance_string_index(&units, scan as f64, unicode_matching) as usize;
1146            continue;
1147        }
1148        // 14.c.iv-v. Accept the piece before the match, then every capture group as-is (a
1149        // group that did not participate stays `undefined`).
1150        parts.push(interp.string_wtf8(crate::value::Wtf8::from_units(&units[last..scan])));
1151        if parts.len() as u32 == limit {
1152            return Ok(Value::Object(interp.new_array(parts)));
1153        }
1154        last = end;
1155        // 14.c.vi is `LengthOfArrayLike(z)` — the `length` *property*, so a hand-made `exec`
1156        // result is honoured exactly like the builtin array.
1157        let length = interp
1158            .get_property(hit, "length")?
1159            .unwrap_or(Value::Undefined);
1160        let length = to_length(interp.to_js_number(&length)?) as usize;
1161        for i in 1..length {
1162            let capture = interp
1163                .get_property(hit, &i.to_string())?
1164                .unwrap_or(Value::Undefined);
1165            parts.push(capture);
1166            if parts.len() as u32 == limit {
1167                return Ok(Value::Object(interp.new_array(parts)));
1168            }
1169        }
1170        // 14.c.vii. The search resumes at `p`, **not** at the end of the match.
1171        scan = last;
1172    }
1173    // 15. The tail, clamped in case `lastIndex` ran past the end of the subject.
1174    let last = last.min(size);
1175    parts.push(interp.string_wtf8(crate::value::Wtf8::from_units(&units[last..])));
1176    Ok(Value::Object(interp.new_array(parts)))
1177}
1178
1179/// `RegExp.prototype[Symbol.replace]` — §22.2.6.11, the half `String.prototype.replace` and
1180/// `replaceAll` delegate to.
1181///
1182/// **Every match comes from `RegExpExec(R, S)`**, never from the internal matcher. That is
1183/// what lets a subclass or a duck-typed object answer for itself:
1184///
1185/// ```js
1186/// var r = /a/; r.exec = () => null; "abc".replace(r, "X")   // "abc", and exec ran once
1187/// ```
1188///
1189/// This function used to scan with the compiled matcher directly, so the observable
1190/// contract was wrong in three ways at once — `exec` was never called, `lastIndex` was
1191/// never written back, and `unicode`/`global` were read off the pattern's flags instead of
1192/// off the properties. Forty of the seventy `Symbol.replace` test262 cases failed on
1193/// exactly those three.
1194///
1195/// The step order is load-bearing and matches the spec literally, because the cases assert
1196/// it: `ToString(string)` (3), `IsCallable`+`ToString` of the replacement (5–7, so a bad
1197/// replacement throws *before* any property of the regexp is touched), `flags` (9),
1198/// `global` (10), and only then `unicode` (11.c) — which is read **only** in the global
1199/// branch, so a non-global regexp with a throwing `unicode` getter does not throw.
1200fn symbol_replace(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
1201    let Some(object) = this.as_object().cloned() else {
1202        return Err(interp.type_error("Symbol.replace called on a non-object"));
1203    };
1204    let matcher = Value::Object(object.clone());
1205    // 3. `ToString(string)`.
1206    let text = interp.checked_to_wtf8(&arg(args, 0))?;
1207    let units = text.to_units();
1208    // 5–7. A functional replacement is used as-is; anything else is coerced *now*, before the
1209    // regexp's own properties are read.
1210    let replacement = arg(args, 1);
1211    let functional = matches!(&replacement, Value::Object(o) if o.is_callable());
1212    let template = if functional {
1213        None
1214    } else {
1215        Some(interp.checked_to_wtf8(&replacement)?)
1216    };
1217    // 9. `ToString(Get(rx, "flags"))`. Read even when the value is later unused, because the
1218    // getter's side effects (and its throw) are observable.
1219    let flags = interp
1220        .get_property(&object, "flags")?
1221        .unwrap_or(Value::Undefined);
1222    let flags = interp.checked_to_string(&flags)?;
1223    // 10. `global` comes from the property, not `flags`. A regexp whose `global` was
1224    // redefined must follow the property — `coerce-global.js` walks `undefined`, `null`, `0`,
1225    // `""` and `NaN`, all of which are falsy but are not the same as "no `g` flag".
1226    let global = interp
1227        .get_property(&object, "global")?
1228        .unwrap_or(Value::Undefined)
1229        .to_boolean();
1230    // 11.a–11.d. `lastIndex` is zeroed before the loop, and `fullUnicode` is read from
1231    // `unicode` — only on this path. `v` counts as unicode for `AdvanceStringIndex`.
1232    let mut full_unicode = false;
1233    if global {
1234        let unicode = interp
1235            .get_property(&object, "unicode")?
1236            .unwrap_or(Value::Undefined)
1237            .to_boolean();
1238        let unicode_sets = if unicode {
1239            false
1240        } else {
1241            // §22.2.6.11 step 11.c reads `unicodeSets` only when `unicode` is false, and only
1242            // when the pattern has the `v` flag; `flags` already tells us that.
1243            flags.contains('v')
1244        };
1245        full_unicode = unicode || unicode_sets;
1246        interp.set_property(&object, "lastIndex", Value::Int(0))?;
1247    }
1248    // 12–13. Collect the matches.
1249    //
1250    // Each entry is the `RegExpExec` result as a *value* plus the pieces taken out of it, so
1251    // an `exec` that answers a plain object with a hand-made `index` is honoured exactly like
1252    // the builtin's array.
1253    struct Hit {
1254        result: Value,
1255        /// `ToString(result[0])`, in code units.
1256        matched: Vec<u16>,
1257        /// `ToIntegerOrInfinity(result.index)`, clamped into the string.
1258        position: usize,
1259        /// The capture values as `RegExpExec` reported them, still uncoerced.
1260        captures: Vec<Value>,
1261    }
1262    let mut hits: Vec<Hit> = Vec::new();
1263    loop {
1264        let subject = interp.string_wtf8(text.clone());
1265        let result = regexp_exec(interp, &matcher, &subject)?;
1266        let Value::Object(hit) = &result else {
1267            break;
1268        };
1269        let zero = interp.get_property(hit, "0")?.unwrap_or(Value::Undefined);
1270        let matched = interp.checked_to_wtf8(&zero)?.to_units();
1271        let index = interp
1272            .get_property(hit, "index")?
1273            .unwrap_or(Value::Undefined);
1274        let index = interp.to_js_number(&index)?;
1275        // A `lastIndex`/`index` past the end has no characters before it, but the text still
1276        // appends to the end rather than panicking — the spec's `ToLength` clamps it.
1277        let position = to_length(index) as usize;
1278        // §22.2.6.11 step 14.b.i is `LengthOfArrayLike(result)`, which reads the `length`
1279        // **property** — not the internal array length. A hand-made `exec` result is a plain
1280        // object, so `array_length()` answered `None` and every group vanished; a group whose
1281        // `toString` throws then never threw.
1282        let length = interp
1283            .get_property(hit, "length")?
1284            .unwrap_or(Value::Undefined);
1285        let length = to_length(interp.to_js_number(&length)?) as usize;
1286        let mut captures = Vec::with_capacity(length.saturating_sub(1));
1287        for i in 1..length {
1288            captures.push(
1289                interp
1290                    .get_property(hit, &i.to_string())?
1291                    .unwrap_or(Value::Undefined),
1292            );
1293        }
1294        hits.push(Hit {
1295            result,
1296            matched,
1297            position: position.min(units.len()),
1298            captures,
1299        });
1300        if !global {
1301            break;
1302        }
1303        // `matched` is empty exactly when `result[0]` is the empty string; then `lastIndex`
1304        // has to advance or the loop cannot end.
1305        if !hits.last().is_some_and(|h| h.matched.is_empty()) {
1306            continue;
1307        }
1308        let this_index = interp
1309            .get_property(&object, "lastIndex")?
1310            .unwrap_or(Value::Int(0));
1311        let this_index = interp.to_js_number(&this_index)?;
1312        let next = advance_string_index(&units, to_length(this_index), full_unicode);
1313        interp.set_property(&object, "lastIndex", Value::Float(next))?;
1314    }
1315    if hits.is_empty() {
1316        return Ok(interp.string_wtf8(text));
1317    }
1318    // 14. Assemble.
1319    let mut out: Vec<u16> = Vec::new();
1320    let mut next_source_position = 0usize;
1321    for hit in &hits {
1322        let start = next_source_position.max(hit.position);
1323        if start > units.len() {
1324            break;
1325        }
1326        out.extend_from_slice(&units[next_source_position..start]);
1327        let substituted = substitute_generic(
1328            interp,
1329            &replacement,
1330            template.as_ref(),
1331            &hit.result,
1332            &hit.matched,
1333            &hit.captures,
1334            &units,
1335            start,
1336        )?;
1337        out.extend_from_slice(&substituted);
1338        next_source_position = start + hit.matched.len();
1339    }
1340    if next_source_position < units.len() {
1341        out.extend_from_slice(&units[next_source_position..]);
1342    }
1343    Ok(interp.string_wtf8(crate::value::Wtf8::from_units(&out)))
1344}
1345
1346/// Expand one match of `RegExp.prototype[@@replace]`.
1347///
1348/// Every capture is a **value** out of the `RegExpExec` result, `ToString`-ed here, rather
1349/// than a slice this function takes itself — an `exec` that returns `{ 0: ..., 1: { toString
1350/// throws } }` is observable, and `result-coerce-capture-err.js` asserts the throw.
1351#[allow(clippy::too_many_arguments)]
1352fn substitute_generic(
1353    interp: &mut Interp<'_>,
1354    replacement: &Value,
1355    template: Option<&crate::value::Wtf8>,
1356    result: &Value,
1357    matched: &[u16],
1358    captures: &[Value],
1359    units: &[u16],
1360    position: usize,
1361) -> JsResult<Vec<u16>> {
1362    // 14.c. A callable replacement gets the match, every group, the position and the string.
1363    if let Value::Object(function) = replacement
1364        && function.is_callable()
1365    {
1366        let mut args: Vec<Value> =
1367            vec![interp.string_wtf8(crate::value::Wtf8::from_units(matched))];
1368        args.extend(captures.iter().cloned());
1369        args.push(Value::Int(position as i32));
1370        args.push(interp.string_wtf8(crate::value::Wtf8::from_units(units)));
1371        // 14.c.ix: the *result* of the call is `ToString`-ed, keeping any unpaired surrogate
1372        // it produced.
1373        let outcome = interp.call_value(Value::Object(function.clone()), Value::Undefined, args)?;
1374        return Ok(interp.checked_to_wtf8(&outcome)?.to_units());
1375    }
1376    let Some(template) = template else {
1377        // A non-callable replacement was coerced by the caller; reaching here would mean the
1378        // two decisions disagreed.
1379        return Err(interp.type_error("replacement was neither callable nor coerced"));
1380    };
1381    // 14.d.ii: `namedCaptures` is `Get(result, "groups")`, and `undefined` means "no named
1382    // groups at all", which is what makes `$<y>` literal rather than empty.
1383    let named_captures = match result.as_object() {
1384        Some(hit) => interp
1385            .get_property(hit, "groups")?
1386            .unwrap_or(Value::Undefined),
1387        None => Value::Undefined,
1388    };
1389    let mut named: Vec<(String, Vec<u16>)> = Vec::new();
1390    let mut has_names = false;
1391    if let Value::Object(groups) = &named_captures {
1392        has_names = true;
1393        // The property *names* of the groups object, in insertion order, are the group names.
1394        for key in groups.own_property_keys() {
1395            let Some(name) = key.as_str().map(str::to_string) else {
1396                continue;
1397            };
1398            let value = interp
1399                .get_property(groups, &name)?
1400                .unwrap_or(Value::Undefined);
1401            // §22.1.3.19.1 step 2.c.d: an **undefined** capture is the *empty* string, not
1402            // `"undefined"`. The property exists on the groups object either way, so this is
1403            // a value test, not a presence test — `string-replace-undefined.js` walks a
1404            // pattern whose `thd` group never participates.
1405            let units = match value {
1406                Value::Undefined => Vec::new(),
1407                other => interp.checked_to_wtf8(&other)?.to_units(),
1408            };
1409            named.push((name, units));
1410        }
1411    }
1412    let mut owned: Vec<Option<Vec<u16>>> = Vec::with_capacity(captures.len() + 1);
1413    owned.push(Some(matched.to_vec()));
1414    for capture in captures {
1415        owned.push(match capture {
1416            Value::Undefined => None,
1417            other => Some(interp.checked_to_wtf8(other)?.to_units()),
1418        });
1419    }
1420    let mut out: Vec<u16> = Vec::new();
1421    get_substitution(
1422        &mut out,
1423        template,
1424        &Substitution {
1425            input: units,
1426            position,
1427            match_len: matched.len(),
1428            captures: &owned,
1429            names: has_names.then_some(named.as_slice()),
1430        },
1431    );
1432    Ok(out)
1433}
1434
1435/// Build a `RegExp` object for `source`/`flags`, reusing an existing one when the same
1436/// pattern was compiled before.
1437pub fn new_regexp(interp: &mut Interp<'_>, source: &str, flags: &str) -> JsResult<Gc<JsObject>> {
1438    let prototype = default_prototype(interp);
1439    let object = interp.new_object(Some(prototype));
1440    initialise(interp, object, source, flags)
1441}
1442
1443/// The realm's `%RegExp.prototype%`.
1444fn default_prototype(interp: &Interp<'_>) -> Gc<JsObject> {
1445    interp
1446        .realm
1447        .regexp_proto
1448        .clone()
1449        .unwrap_or_else(|| interp.realm.object_proto.clone())
1450}
1451
1452/// `RegExpAlloc(new.target)` — the empty object `new RegExp` fills in.
1453///
1454/// The prototype comes from `new.target` through `OrdinaryCreateFromConstructor`, which is
1455/// what makes `class RE extends RegExp` an instance of `RE`: the derived constructor's
1456/// `super()` runs this same native, and a fixed `%RegExp.prototype%` here produced a plain
1457/// `RegExp`, so a subclass's override of `@@replace` was never reached.
1458fn allocate(interp: &mut Interp<'_>) -> JsResult<Gc<JsObject>> {
1459    let fallback = default_prototype(interp);
1460    interp.new_ctor_instance(fallback)
1461}
1462
1463/// `RegExpInitialize(object, source, flags)`: compile the pattern and install the matcher.
1464fn initialise(
1465    interp: &mut Interp<'_>,
1466    object: Gc<JsObject>,
1467    source: &str,
1468    flags: &str,
1469) -> JsResult<Gc<JsObject>> {
1470    let Some(parsed) = Flags::parse(flags) else {
1471        return Err(invalid_pattern(interp, String::new(), "flags"));
1472    };
1473    let regex = match Regex::compile(source, parsed) {
1474        Ok(regex) => regex,
1475        Err(error) => {
1476            // The reference reports the engine's own message, not a generic one.
1477            return Err(invalid_pattern(interp, error.message, ""));
1478        }
1479    };
1480    object.set_regexp(RegExpData {
1481        regex: std::rc::Rc::new(regex),
1482        source: source.to_string(),
1483        flags: parsed.as_flag_string(),
1484    });
1485    // §22.2.5 step 12: `{[[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false}`.
1486    // `with_attributes` ties `configurable` to `writable`, so it made `lastIndex` both
1487    // writable *and* configurable — and a configurable property can be deleted, which is
1488    // how `delete regExpProxy.lastIndex` and `getOwnPropertyDescriptor` both caught it.
1489    object.define(
1490        "lastIndex",
1491        Property {
1492            value: Some(Value::Int(0)),
1493            writable: true,
1494            enumerable: false,
1495            configurable: false,
1496            ..Property::default()
1497        },
1498    );
1499    Ok(object)
1500}
1501
1502/// The `SyntaxError` a malformed pattern raises.
1503///
1504/// The two forms the reference uses: a bad flag string reports `invalid regular expression
1505/// flags`, and a bad pattern reports the engine's own message.
1506fn invalid_pattern(interp: &Interp<'_>, message: String, flags: &str) -> crate::interp::Signal {
1507    let text = if flags.is_empty() {
1508        message
1509    } else {
1510        "invalid regular expression flags".to_string()
1511    };
1512    crate::interp::Signal::Throw(interp.make_error("SyntaxError", &text))
1513}
1514
1515/// Whether `value` is a `RegExp` object.
1516pub fn is_regexp(object: &Gc<JsObject>) -> bool {
1517    object.regexp().is_some()
1518}