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