Skip to main content

quickjs/builtins/
regexp.rs

1//! `RegExp` and `RegExp.prototype`.
2//!
3//! The engine lives in [`crate::regexp`]; this module is the JavaScript-facing half: the
4//! constructor, the compiled-pattern cache, `lastIndex`, and `exec`.
5//!
6//! `exec` is where most of the observable semantics live. A `g` or `y` pattern advances
7//! `lastIndex`, a failed match resets it to zero, and the returned array carries the
8//! captured groups plus `index`, `input` and (for the `d` flag) `indices`.
9
10use crate::builtins::substitution::{Substitution, get_substitution};
11use crate::builtins::{arg, define_method};
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        ("dotAll", dot_all),
60        ("hasIndices", has_indices),
61    ] {
62        let getter = interp.new_native(name, 0, getter);
63        prototype.define(
64            name,
65            Property {
66                getter: Some(Value::Object(getter)),
67                enumerable: false,
68                configurable: true,
69                ..Property::default()
70            },
71        );
72    }
73
74    // `RegExp.escape` is a static: it is on the constructor, not the prototype.
75    define_method(&constructor, "escape", 1, escape, interp);
76
77    // `Symbol.match` and friends are what `String.prototype.match` looks up; without them
78    // a regexp is not recognised as a pattern by those methods.
79    install_symbol_methods(interp, &prototype, &constructor);
80    interp.realm.regexp_proto = Some(prototype.clone());
81    interp.realm.regexp_ctor = Some(constructor.clone());
82    constructor
83}
84
85fn install_symbol_methods(
86    interp: &mut Interp<'_>,
87    prototype: &Gc<JsObject>,
88    constructor: &Gc<JsObject>,
89) {
90    use crate::interp::WellKnown;
91    for (which, name, func, length) in [
92        (
93            WellKnown::Match,
94            "[Symbol.match]",
95            symbol_match as crate::object::NativeFn,
96            1,
97        ),
98        (WellKnown::Replace, "[Symbol.replace]", symbol_replace, 2),
99        (WellKnown::Search, "[Symbol.search]", symbol_search, 1),
100        (WellKnown::Split, "[Symbol.split]", symbol_split, 2),
101    ] {
102        let method = interp.new_native(name, length, func);
103        prototype.define_key(
104            &interp.realm.well_known_key(which),
105            Property::with_attributes(Value::Object(method), true, false),
106        );
107    }
108    let _ = constructor;
109}
110
111/// `RegExp.escape(string)`: escape `string` so it can be used as a literal pattern.
112///
113/// Two things make this more than a backslash loop:
114///
115/// * **The first character is escaped differently.** A leading ASCII letter or digit
116///   becomes `\xNN`, because `"1"` after a `\0` or `\c` would otherwise be read as part
117///   of the preceding escape rather than as a digit.
118/// * **Most characters need no escape at all.** Only the syntax characters, `/`, the
119///   control escapes, a fixed list of other punctuators, whitespace, line terminators and
120///   lone surrogates are touched; everything else — including all non-ASCII letters — is
121///   copied through, because a literal character in a pattern is already literal outside
122///   syntax positions.
123///
124/// Note `\s`'s set is reused for "whitespace or line terminator" (see
125/// [`quickjs_regexp::is_space`]) rather than restated, so the two cannot drift.
126fn escape(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
127    let arg = arg(args, 0);
128    // Not `ToString`: the spec is explicit that a non-string is a TypeError rather than
129    // being coerced, so `RegExp.escape(1)` throws instead of returning `"1"`.
130    if !matches!(arg, Value::String(_)) {
131        return Err(interp.type_error("not a string"));
132    }
133    let source = interp.checked_to_wtf8(&arg)?.code_point_values();
134    let mut out: Vec<u32> = Vec::with_capacity(source.len());
135    for (position, cp) in source.iter().enumerate() {
136        // `escaped` is empty exactly at the first code point, since every branch below
137        // emits at least one code unit.
138        let leading = position == 0;
139        encode_for_regexp_escape(*cp, leading, &mut out);
140    }
141    Ok(interp.string_wtf8(points_to_wtf8(&out)))
142}
143
144/// The per-code-point half of `RegExp.escape`: `EncodeForRegExpEscape`, plus the leading
145/// alphanumeric rule that the caller knows about and this does not.
146fn encode_for_regexp_escape(c: u32, leading: bool, out: &mut Vec<u32>) {
147    let backslash = u32::from(b'\\');
148    // A leading ASCII letter or digit is always hex-escaped: it may otherwise be read as
149    // part of a preceding `\0…` or `\c…`.
150    let ascii_alnum = matches!(c, 0x30..=0x39 | 0x41..=0x5A | 0x61..=0x7A);
151    if leading && ascii_alnum {
152        push_hex_escape(c, out);
153        return;
154    }
155    // SyntaxCharacter, plus `/` — the one character a pattern literal would terminate on.
156    if matches!(
157        c,
158        0x2E | 0x2A | 0x2B | 0x3F | 0x5E | 0x24 | 0x7C // . * + ? ^ $ |
159        | 0x28 | 0x29 | 0x5B | 0x5D | 0x7B | 0x7D    // ( ) [ ] { }
160        | 0x5C | 0x2F // \ /
161    ) {
162        out.push(backslash);
163        out.push(c);
164        return;
165    }
166    // The five control escapes that have a short spelling.
167    if let Some(letter) = match c {
168        0x09 => Some('t'),
169        0x0A => Some('n'),
170        0x0B => Some('v'),
171        0x0C => Some('f'),
172        0x0D => Some('r'),
173        _ => None,
174    } {
175        out.push(backslash);
176        out.push(u32::from(letter as u8));
177        return;
178    }
179    // `otherPunctuators` from the spec, then whitespace, line terminators and lone
180    // surrogates: all of these become `\xNN` or `\uNNNN`.
181    let other_punctuator = matches!(
182        c,
183        0x2C | 0x2D | 0x3D | 0x3C | 0x3E | 0x23 | 0x26 | 0x21 // , - = < > # & !
184        | 0x25 | 0x3A | 0x3B | 0x40 | 0x7E | 0x27 | 0x60 | 0x22 // % : ; @ ~ ' ` "
185    );
186    if other_punctuator || quickjs_regexp::is_space(c) || (0xD800..=0xDFFF).contains(&c) {
187        if c <= 0xFF {
188            push_hex_escape(c, out);
189        } else {
190            // `\uNNNN`, per code unit. Every code point in this branch is below 0x10000
191            // (the spaces, the line separators, the surrogates), so one unit is enough;
192            // anything astral falls through to the literal case below.
193            out.push(backslash);
194            out.push(u32::from(b'u'));
195            for shift in [12, 8, 4, 0] {
196                out.push(u32::from(hex_digit((c >> shift) & 0xF)));
197            }
198        }
199        return;
200    }
201    // Everything else is already literal in a pattern, so it is copied through.
202    out.push(c);
203}
204
205/// `\xNN` for a code point below 0x100.
206fn push_hex_escape(c: u32, out: &mut Vec<u32>) {
207    out.push(u32::from(b'\\'));
208    out.push(u32::from(b'x'));
209    out.push(u32::from(hex_digit((c >> 4) & 0xF)));
210    out.push(u32::from(hex_digit(c & 0xF)));
211}
212
213/// Lowercase hex, which is the case both `\x` and `\u` escapes are expected in.
214fn hex_digit(nibble: u32) -> u8 {
215    match nibble {
216        0..=9 => b'0' + nibble as u8,
217        _ => b'a' + (nibble as u8 - 10),
218    }
219}
220
221/// `new RegExp(pattern, flags)`.
222fn constructor(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
223    let pattern = arg(args, 0);
224    let flags = arg(args, 1);
225    // `new RegExp(existingRegExp)` copies the pattern and flags.
226    let (source, flags) = match &pattern {
227        Value::Object(object) if object.regexp().is_some() => {
228            let data = object.regexp().expect("checked");
229            let flags = if matches!(flags, Value::Undefined) {
230                data.flags.clone()
231            } else {
232                interp.to_js_string(&flags)?
233            };
234            (data.source.clone(), flags)
235        }
236        // `RegExpCreate(undefined, flags)`: the *pattern* is empty, the flags are not.
237        // Dropping them made `new RegExp(x, "g")` a non-global regexp, so
238        // `"asdf".replace(new RegExp(undefined, "g"), "1")` replaced once rather than five
239        // times — test262's `replace/S15.5.4.11_A1_T17`. `ToString(flags)` happens whether
240        // or not the pattern is undefined, so it is spelled the same as the arm below.
241        Value::Undefined => (
242            String::new(),
243            if matches!(flags, Value::Undefined) {
244                String::new()
245            } else {
246                interp.to_js_string(&flags)?
247            },
248        ),
249        other => (
250            interp.to_js_string(other)?,
251            if matches!(flags, Value::Undefined) {
252                String::new()
253            } else {
254                interp.to_js_string(&flags)?
255            },
256        ),
257    };
258    let object = allocate(interp)?;
259    Ok(Value::Object(initialise(interp, object, &source, &flags)?))
260}
261
262/// `RegExp.prototype.exec(string)`.
263fn exec(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
264    let Some(object) = this.as_object() else {
265        return Err(interp.type_error("RegExp.prototype.exec called on a non-object"));
266    };
267    let text = interp.checked_to_wtf8(&arg(args, 0))?;
268    exec_on(interp, object, &text)
269}
270
271/// The shared implementation of `exec`, used by the `String` methods as well.
272pub fn exec_on(
273    interp: &mut Interp<'_>,
274    object: &Gc<JsObject>,
275    text: &crate::value::Wtf8,
276) -> JsResult<Value> {
277    let Some(data) = object.regexp() else {
278        return Err(interp.type_error("method called on a non-RegExp"));
279    };
280    let sticky_or_global = data.regex.flags.global || data.regex.flags.sticky;
281    let mut start = if sticky_or_global {
282        let index = interp.get_property(object, "lastIndex")?;
283        let index = interp.to_js_number(&index.unwrap_or(Value::Int(0)))?;
284        if !index.is_finite() || index < 0.0 {
285            interp.set_property(object, "lastIndex", Value::Int(0))?;
286            return Ok(Value::Null);
287        }
288        index as usize
289    } else {
290        0
291    };
292    let input: Vec<u32> = text.code_point_values();
293    // `lastIndex`, `index` and the `d` flag's pairs all count **UTF-16 code units**, while the
294    // matcher works in characters. `unit_start[i]` is the code-unit offset of character `i`,
295    // with one extra entry for the end, so the two unit systems convert both ways.
296    let mut unit_start = Vec::with_capacity(input.len() + 1);
297    let mut units = 0;
298    for character in &input {
299        unit_start.push(units);
300        units += if *character > 0xFFFF { 2 } else { 1 };
301    }
302    unit_start.push(units);
303    // A `lastIndex` inside a surrogate pair has no character of its own; it belongs to the
304    // character that contains it, which is the same as rounding down to a code point
305    // boundary — what the reference does, and what makes `/(?:)/gu` with `lastIndex = 1` on
306    // `"🐱"` report `index === 0`.
307    if start > units {
308        if sticky_or_global {
309            interp.set_property(object, "lastIndex", Value::Int(0))?;
310        }
311        return Ok(Value::Null);
312    }
313    start = unit_start
314        .partition_point(|offset| *offset <= start)
315        .saturating_sub(1);
316    let found = data.regex.exec_at(&input, start);
317    let Some(found) = found else {
318        if sticky_or_global {
319            interp.set_property(object, "lastIndex", Value::Int(0))?;
320        }
321        return Ok(Value::Null);
322    };
323    // `lastIndex` moves to the end of the match, in code units — not characters, which is
324    // why an astral match advances by two.
325    if sticky_or_global {
326        let units = unit_start[found.end.min(unit_start.len() - 1)];
327        interp.set_property(object, "lastIndex", Value::Int(units as i32))?;
328    }
329    // The result array: the whole match, then one element per group. A group that did not
330    // participate is `undefined`, not a hole.
331    let mut elements: Vec<Value> = Vec::with_capacity(found.captures.len());
332    for capture in &found.captures {
333        elements.push(match capture {
334            Some((start, end)) => interp.string_wtf8(slice(&input, *start, *end)),
335            None => Value::Undefined,
336        });
337    }
338    let array = interp.new_array(elements);
339    let index = unit_start[found.start.min(unit_start.len() - 1)];
340    let input_value = interp.string_wtf8(text.clone());
341    interp.set_property(&array, "index", Value::Int(index as i32))?;
342    interp.set_property(&array, "input", input_value.clone())?;
343    // `m.groups`: a null-prototype object mapping each *named* group to its capture, or
344    // `undefined` when the pattern has no named groups at all — which is what the spec
345    // says, and what `m.groups === undefined` tests check.
346    //
347    // The object has a `null` prototype (`Object.create(null)`), so `m.groups.toString`
348    // is `undefined` and a group named `toString` does not collide with `Object.prototype`.
349    let groups = if data.regex.names.is_empty() {
350        Value::Undefined
351    } else {
352        let groups = interp.new_object(None);
353        for (name, index) in &data.regex.names {
354            let value = match found.captures.get(*index).copied().flatten() {
355                Some((start, end)) => interp.string_wtf8(slice(&input, start, end)),
356                None => Value::Undefined,
357            };
358            interp.set_property(&groups, name, value)?;
359        }
360        Value::Object(groups)
361    };
362    interp.set_property(&array, "groups", groups)?;
363    if data.regex.flags.has_indices {
364        let mut pairs = Vec::with_capacity(found.captures.len());
365        for capture in &found.captures {
366            pairs.push(match capture {
367                Some((start, end)) => {
368                    let (start, end) = (
369                        unit_start[(*start).min(unit_start.len() - 1)],
370                        unit_start[(*end).min(unit_start.len() - 1)],
371                    );
372                    let pair =
373                        interp.new_array(vec![Value::Int(start as i32), Value::Int(end as i32)]);
374                    Value::Object(pair)
375                }
376                None => Value::Undefined,
377            });
378        }
379        let indices = interp.new_array(pairs);
380        interp.set_property(&array, "indices", Value::Object(indices))?;
381    }
382    Ok(Value::Object(array))
383}
384
385/// The text of `input[start..end]`, in code points.
386///
387/// Built through UTF-16 so that a lone surrogate survives: collecting code points into a
388/// `String` would turn one into U+FFFD, and then `exec` would report different text than
389/// the input it was given.
390fn slice(input: &[u32], start: usize, end: usize) -> crate::value::Wtf8 {
391    points_to_wtf8(input.get(start..end).unwrap_or_default())
392}
393
394/// Code points to WTF-8, keeping a lone surrogate instead of replacing it.
395fn points_to_wtf8(points: &[u32]) -> crate::value::Wtf8 {
396    let mut units = Vec::with_capacity(points.len());
397    for point in points {
398        if *point > 0xFFFF {
399            let value = point - 0x10000;
400            units.push(0xD800 + (value >> 10) as u16);
401            units.push(0xDC00 + (value & 0x3FF) as u16);
402        } else {
403            units.push(*point as u16);
404        }
405    }
406    crate::value::Wtf8::from_units(&units)
407}
408
409/// `RegExp.prototype.test(string)`.
410fn test(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
411    let result = exec(interp, this, args)?;
412    Ok(Value::Bool(!matches!(result, Value::Null)))
413}
414
415fn to_string(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
416    let Some(object) = this.as_object() else {
417        return Err(interp.type_error("RegExp.prototype.toString called on a non-object"));
418    };
419    let Some(data) = object.regexp() else {
420        return Err(interp.type_error("RegExp.prototype.toString called on a non-RegExp"));
421    };
422    let source = if data.source.is_empty() {
423        "(?:)".to_string()
424    } else {
425        data.source.clone()
426    };
427    Ok(interp.string(format!("/{source}/{}", data.flags)))
428}
429
430fn source(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
431    let data = data_of(interp, &this)?;
432    // An empty pattern reports `(?:)` so that `/` + source + `/` parses again.
433    let text = if data.source.is_empty() {
434        "(?:)".to_string()
435    } else {
436        data.source.clone()
437    };
438    Ok(interp.string(&text))
439}
440
441fn flags(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
442    let data = data_of(interp, &this)?;
443    Ok(interp.string(&data.flags))
444}
445
446fn data_of(interp: &mut Interp<'_>, this: &Value) -> JsResult<RegExpData> {
447    match this.as_object().and_then(|object| object.regexp()) {
448        Some(data) => Ok(data.clone()),
449        None => Err(interp.type_error("method called on a non-RegExp")),
450    }
451}
452
453/// One of the boolean flag accessors.
454fn flag_getter(interp: &mut Interp<'_>, this: Value, pick: fn(&Flags) -> bool) -> JsResult<Value> {
455    let data = data_of(interp, &this)?;
456    Ok(Value::Bool(pick(&data.regex.flags)))
457}
458
459fn global(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
460    flag_getter(interp, this, |flags| flags.global)
461}
462fn ignore_case(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
463    flag_getter(interp, this, |flags| flags.ignore_case)
464}
465fn multiline(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
466    flag_getter(interp, this, |flags| flags.multiline)
467}
468fn sticky(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
469    flag_getter(interp, this, |flags| flags.sticky)
470}
471fn unicode(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
472    flag_getter(interp, this, |flags| flags.unicode)
473}
474fn dot_all(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
475    flag_getter(interp, this, |flags| flags.dot_all)
476}
477fn has_indices(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
478    flag_getter(interp, this, |flags| flags.has_indices)
479}
480
481// -- the Symbol methods ------------------------------------------------------
482//
483// These are what `String.prototype.match` and friends dispatch to. Each one re-reads the
484// pattern's flags through the object's own properties, as the spec does, so a subclass
485// that overrides `lastIndex` keeps working.
486
487/// `String.prototype.match`'s hook.
488fn symbol_match(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
489    let Some(object) = this.as_object() else {
490        return Err(interp.type_error("Symbol.match called on a non-object"));
491    };
492    let text = interp.checked_to_wtf8(&arg(args, 0))?;
493    let is_global = interp
494        .get_property(object, "global")?
495        .unwrap_or(Value::Undefined)
496        .to_boolean();
497    if !is_global {
498        return exec_on(interp, object, &text);
499    }
500    interp.set_property(object, "lastIndex", Value::Int(0))?;
501    let mut results = Vec::new();
502    let input: Vec<u32> = text.code_point_values();
503    loop {
504        let result = exec_on(interp, object, &text)?;
505        if matches!(result, Value::Null) {
506            break;
507        }
508        let Value::Object(array) = &result else {
509            break;
510        };
511        let matched = interp.get_property(array, "0")?.unwrap_or(Value::Undefined);
512        let empty = interp.to_js_string(&matched)?.is_empty();
513        results.push(result);
514        if empty {
515            let next = interp
516                .get_property(object, "lastIndex")?
517                .unwrap_or(Value::Int(0));
518            let next = interp.to_js_number(&next)? as usize + 1;
519            interp.set_property(object, "lastIndex", Value::Int(next as i32))?;
520            if next > input.len() {
521                break;
522            }
523        }
524    }
525    if results.is_empty() {
526        return Ok(Value::Null);
527    }
528    Ok(Value::Object(interp.new_array(results)))
529}
530
531/// `String.prototype.search`'s hook: the index of the first match, or -1.
532fn symbol_search(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
533    let Some(object) = this.as_object() else {
534        return Err(interp.type_error("Symbol.search called on a non-object"));
535    };
536    let text = interp.checked_to_wtf8(&arg(args, 0))?;
537    // `search` ignores the caller's `lastIndex`: it always looks from the start, and
538    // leaves the property alone afterwards.
539    interp.set_property(object, "lastIndex", Value::Int(0))?;
540    let result = exec_on(interp, object, &text)?;
541    match result {
542        Value::Null => Ok(Value::Int(-1)),
543        Value::Object(array) => Ok(interp
544            .get_property(&array, "index")?
545            .unwrap_or(Value::Int(-1))),
546        other => Ok(other),
547    }
548}
549
550/// `String.prototype.split`'s hook.
551fn symbol_split(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
552    let Some(object) = this.as_object() else {
553        return Err(interp.type_error("Symbol.split called on a non-object"));
554    };
555    let text = interp.checked_to_wtf8(&arg(args, 0))?;
556    let limit = match arg(args, 1) {
557        Value::Undefined => u32::MAX,
558        other => {
559            let number = interp.to_js_number(&other)?;
560            if number.is_nan() || number < 0.0 {
561                0
562            } else {
563                number as u32
564            }
565        }
566    };
567    if limit == 0 {
568        return Ok(Value::Object(interp.new_array(Vec::new())));
569    }
570    let data = data_of(interp, &Value::Object(object.clone()))?;
571    let input: Vec<u32> = text.code_point_values();
572    let mut parts: Vec<Value> = Vec::new();
573    let mut last = 0usize;
574    let mut scan = 0usize;
575    while scan <= input.len() {
576        let Some(found) = data.regex.exec_at(&input, scan) else {
577            break;
578        };
579        // A zero-length match cannot split anything, and taking it would loop forever.
580        if found.end == found.start {
581            scan = found.start + 1;
582            continue;
583        }
584        parts.push(interp.string_wtf8(slice(&input, last, found.start)));
585        if parts.len() as u32 >= limit {
586            return Ok(Value::Object(interp.new_array(parts)));
587        }
588        for group in found.captures.iter().skip(1) {
589            parts.push(match group {
590                Some((start, end)) => interp.string_wtf8(slice(&input, *start, *end)),
591                None => Value::Undefined,
592            });
593            if parts.len() as u32 >= limit {
594                return Ok(Value::Object(interp.new_array(parts)));
595            }
596        }
597        last = found.end;
598        scan = found.end;
599    }
600    parts.push(interp.string_wtf8(slice(&input, last, input.len())));
601    Ok(Value::Object(interp.new_array(parts)))
602}
603
604/// `RegExp.prototype[Symbol.replace]` — §22.2.6.11, the half `String.prototype.replace` and
605/// `replaceAll` delegate to.
606fn symbol_replace(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
607    let Some(object) = this.as_object() else {
608        return Err(interp.type_error("Symbol.replace called on a non-object"));
609    };
610    let text = interp.checked_to_wtf8(&arg(args, 0))?;
611    let replacement = arg(args, 1);
612    let is_global = interp
613        .get_property(object, "global")?
614        .unwrap_or(Value::Undefined)
615        .to_boolean();
616    let data = data_of(interp, &Value::Object(object.clone()))?;
617    // The matcher is character-based; every index a script sees is a code unit. `unit_start`
618    // bridges the two, with an extra entry for the end (§22.1 counts UTF-16 units).
619    let input: Vec<u32> = text.code_point_values();
620    let units = text.to_units();
621    let mut unit_start = Vec::with_capacity(input.len() + 1);
622    let mut at = 0usize;
623    for character in &input {
624        unit_start.push(at);
625        at += if *character > 0xFFFF { 2 } else { 1 };
626    }
627    unit_start.push(at);
628    let to_units = |position: usize| unit_start[position.min(unit_start.len() - 1)];
629    let mut out: Vec<u16> = Vec::new();
630    let mut last = 0usize;
631    let mut scan = 0usize;
632    let mut replaced = false;
633    while scan <= input.len() {
634        let Some(found) = data.regex.exec_at(&input, scan) else {
635            break;
636        };
637        out.extend_from_slice(&units[to_units(last)..to_units(found.start)]);
638        let substituted = substitute(
639            interp,
640            &replacement,
641            &input,
642            &units,
643            &unit_start,
644            &found,
645            &data.regex.names,
646        )?;
647        out.extend_from_slice(&substituted);
648        last = found.end;
649        let empty = found.start == found.end;
650        scan = if empty { found.end + 1 } else { found.end };
651        replaced = true;
652        if !is_global {
653            break;
654        }
655        if empty && found.end >= input.len() {
656            break;
657        }
658    }
659    if !replaced {
660        return Ok(interp.string_wtf8(text.clone()));
661    }
662    out.extend_from_slice(&units[to_units(last)..]);
663    Ok(interp.string_wtf8(crate::value::Wtf8::from_units(&out)))
664}
665
666/// Apply a replacement: a function receives the match and its groups, a string has its
667/// `$&`, `$n`, `$<name>`, `` $` ``, `$'` and `$$` expanded by the shared
668/// [`get_substitution`], which is also what `String.prototype.replace{,All}` use — one
669/// implementation so the two cannot disagree about `$`.
670#[allow(clippy::too_many_arguments)]
671fn substitute(
672    interp: &mut Interp<'_>,
673    replacement: &Value,
674    input: &[u32],
675    units: &[u16],
676    unit_start: &[usize],
677    found: &crate::regexp::Match,
678    names: &[(String, usize)],
679) -> JsResult<Vec<u16>> {
680    let to_units = |position: usize| unit_start[position.min(unit_start.len() - 1)];
681    let start = to_units(found.start);
682    let end = to_units(found.end);
683    if let Value::Object(function) = replacement
684        && function.is_callable()
685    {
686        let mut args: Vec<Value> = vec![interp.string_wtf8(slice(input, found.start, found.end))];
687        for group in found.captures.iter().skip(1) {
688            args.push(match group {
689                Some((start, end)) => interp.string_wtf8(slice(input, *start, *end)),
690                None => Value::Undefined,
691            });
692        }
693        // `position` is a code unit offset; the matched text is the match itself rather than
694        // a re-slice, so a match that split a surrogate pair keeps both halves.
695        args.push(Value::Int(start as i32));
696        args.push(interp.string_wtf8(crate::value::Wtf8::from_units(units)));
697        let result = interp.call_value(Value::Object(function.clone()), Value::Undefined, args)?;
698        // The function's result keeps any unpaired surrogate it produced.
699        return Ok(interp.checked_to_wtf8(&result)?.to_units());
700    }
701    let template = interp.checked_to_wtf8(replacement)?;
702    // The captures in code units, capture 0 being the whole match: the shared expansion
703    // indexes `input` with them.
704    let captures: Vec<Option<(usize, usize)>> = found
705        .captures
706        .iter()
707        .map(|group| group.map(|(start, end)| (to_units(start), to_units(end))))
708        .collect();
709    let mut out: Vec<u16> = Vec::new();
710    get_substitution(
711        &mut out,
712        &template,
713        &Substitution {
714            input: units,
715            position: start,
716            match_len: end - start,
717            captures: &captures,
718            // `None` when the pattern has no named groups at all, which is a different rule
719            // from "no group by that name" — see `Substitution::names`.
720            names: (!names.is_empty()).then_some(names),
721        },
722    );
723    Ok(out)
724}
725
726/// Build a `RegExp` object for `source`/`flags`, reusing an existing one when the same
727/// pattern was compiled before.
728pub fn new_regexp(interp: &mut Interp<'_>, source: &str, flags: &str) -> JsResult<Gc<JsObject>> {
729    let prototype = default_prototype(interp);
730    let object = interp.new_object(Some(prototype));
731    initialise(interp, object, source, flags)
732}
733
734/// The realm's `%RegExp.prototype%`.
735fn default_prototype(interp: &Interp<'_>) -> Gc<JsObject> {
736    interp
737        .realm
738        .regexp_proto
739        .clone()
740        .unwrap_or_else(|| interp.realm.object_proto.clone())
741}
742
743/// `RegExpAlloc(new.target)` — the empty object `new RegExp` fills in.
744///
745/// The prototype comes from `new.target` through `OrdinaryCreateFromConstructor`, which is
746/// what makes `class RE extends RegExp` an instance of `RE`: the derived constructor's
747/// `super()` runs this same native, and a fixed `%RegExp.prototype%` here produced a plain
748/// `RegExp`, so a subclass's override of `@@replace` was never reached.
749fn allocate(interp: &mut Interp<'_>) -> JsResult<Gc<JsObject>> {
750    let fallback = default_prototype(interp);
751    interp.new_ctor_instance(fallback)
752}
753
754/// `RegExpInitialize(object, source, flags)`: compile the pattern and install the matcher.
755fn initialise(
756    interp: &mut Interp<'_>,
757    object: Gc<JsObject>,
758    source: &str,
759    flags: &str,
760) -> JsResult<Gc<JsObject>> {
761    let Some(parsed) = Flags::parse(flags) else {
762        return Err(invalid_pattern(interp, String::new(), "flags"));
763    };
764    let regex = match Regex::compile(source, parsed) {
765        Ok(regex) => regex,
766        Err(error) => {
767            // The reference reports the engine's own message, not a generic one.
768            return Err(invalid_pattern(interp, error.message, ""));
769        }
770    };
771    object.set_regexp(RegExpData {
772        regex: std::rc::Rc::new(regex),
773        source: source.to_string(),
774        flags: parsed.as_flag_string(),
775    });
776    object.define(
777        "lastIndex",
778        Property::with_attributes(Value::Int(0), true, false),
779    );
780    Ok(object)
781}
782
783/// The `SyntaxError` a malformed pattern raises.
784///
785/// The two forms the reference uses: a bad flag string reports `invalid regular expression
786/// flags`, and a bad pattern reports the engine's own message.
787fn invalid_pattern(interp: &Interp<'_>, message: String, flags: &str) -> crate::interp::Signal {
788    let text = if flags.is_empty() {
789        message
790    } else {
791        "invalid regular expression flags".to_string()
792    };
793    crate::interp::Signal::Throw(interp.make_error("SyntaxError", &text))
794}
795
796/// Whether `value` is a `RegExp` object.
797pub fn is_regexp(object: &Gc<JsObject>) -> bool {
798    object.regexp().is_some()
799}