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