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