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