Skip to main content

quickjs/builtins/
regexp.rs

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