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 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 = MatchInput::new(&data.regex, text);
294    // A `lastIndex` inside a surrogate pair has no character of its own; it belongs to the
295    // character that contains it, which is the same as rounding down to a unit boundary —
296    // what the reference does, and what makes `/(?:)/gu` with `lastIndex = 1` on `"🐱"`
297    // report `index === 0`.
298    if start > input.units_len() {
299        if sticky_or_global {
300            interp.set_property(object, "lastIndex", Value::Int(0))?;
301        }
302        return Ok(Value::Null);
303    }
304    let start = input.position(start);
305    let found = data.regex.exec_at(&input.units, start);
306    let Some(found) = found else {
307        if sticky_or_global {
308            interp.set_property(object, "lastIndex", Value::Int(0))?;
309        }
310        return Ok(Value::Null);
311    };
312    // `lastIndex` moves to the end of the match, in code units — not characters, which is
313    // why an astral match under `u` advances by two.
314    if sticky_or_global {
315        let end = input.offset(found.end);
316        interp.set_property(object, "lastIndex", Value::Int(end as i32))?;
317    }
318    // The result array: the whole match, then one element per group. A group that did not
319    // participate is `undefined`, not a hole.
320    let mut elements: Vec<Value> = Vec::with_capacity(found.captures.len());
321    for capture in &found.captures {
322        elements.push(match capture {
323            Some((start, end)) => interp.string_wtf8(input.slice(*start, *end)),
324            None => Value::Undefined,
325        });
326    }
327    let array = interp.new_array(elements);
328    let index = input.offset(found.start);
329    let input_value = interp.string_wtf8(text.clone());
330    interp.set_property(&array, "index", Value::Int(index as i32))?;
331    interp.set_property(&array, "input", input_value.clone())?;
332    // `m.groups`: a null-prototype object mapping each *named* group to its capture, or
333    // `undefined` when the pattern has no named groups at all — which is what the spec
334    // says, and what `m.groups === undefined` tests check.
335    //
336    // The object has a `null` prototype (`Object.create(null)`), so `m.groups.toString`
337    // is `undefined` and a group named `toString` does not collide with `Object.prototype`.
338    let groups = if data.regex.names.is_empty() {
339        Value::Undefined
340    } else {
341        let groups = interp.new_object(None);
342        for (name, index) in &data.regex.names {
343            let value = match found.captures.get(*index).copied().flatten() {
344                Some((start, end)) => interp.string_wtf8(input.slice(start, end)),
345                None => Value::Undefined,
346            };
347            interp.set_property(&groups, name, value)?;
348        }
349        Value::Object(groups)
350    };
351    interp.set_property(&array, "groups", groups)?;
352    if data.regex.flags.has_indices {
353        let mut pairs = Vec::with_capacity(found.captures.len());
354        for capture in &found.captures {
355            pairs.push(match capture {
356                Some((start, end)) => {
357                    let (start, end) = (input.offset(*start), input.offset(*end));
358                    let pair =
359                        interp.new_array(vec![Value::Int(start as i32), Value::Int(end as i32)]);
360                    Value::Object(pair)
361                }
362                None => Value::Undefined,
363            });
364        }
365        let indices = interp.new_array(pairs);
366        interp.set_property(&array, "indices", Value::Object(indices))?;
367    }
368    Ok(Value::Object(array))
369}
370
371/// The matcher's view of a string, and the bridge back to the code units a script sees.
372///
373/// Which unit the matcher consumes is decided by the pattern, not by the caller
374/// ([`quickjs_regexp::Regex::per_code_unit`]):
375///
376/// * **No `u`/`v`.** A pattern is a sequence of UTF-16 code units, so `.` matches one unit,
377///   a quantifier binds to one unit, and `[😀]` is a two-unit class. `units` is therefore the
378///   string's code units, every offset the matcher reports is already a code-unit offset —
379///   the unit `lastIndex`, `index`, `.length` and `d`'s pairs are expressed in — and
380///   `unit_start` is the identity.
381/// * **`u`/`v`.** A pattern is a sequence of code points, so `units` is the code points and
382///   `unit_start` maps an offset back to code units.
383///
384/// Having one type for both is what keeps the four call sites (`exec`, `[Symbol.match]`,
385/// `[Symbol.split]`, `[Symbol.replace]`) from each carrying their own copy of the mapping —
386/// they had one, and `[Symbol.split]` was missing it entirely.
387struct MatchInput {
388    /// What the matcher consumes: code units, or code points.
389    units: Vec<u32>,
390    /// `unit_start[i]` is the code-unit offset of matcher position `i`, with one extra
391    /// entry for the end.
392    unit_start: Vec<usize>,
393}
394
395impl MatchInput {
396    fn new(regex: &quickjs_regexp::Regex, text: &crate::value::Wtf8) -> Self {
397        if regex.per_code_unit() {
398            let units: Vec<u32> = text.to_units().into_iter().map(u32::from).collect();
399            let unit_start = (0..=units.len()).collect();
400            Self { units, unit_start }
401        } else {
402            let units = text.code_point_values();
403            let mut unit_start = Vec::with_capacity(units.len() + 1);
404            let mut count = 0;
405            for point in &units {
406                unit_start.push(count);
407                count += if *point > 0xFFFF { 2 } else { 1 };
408            }
409            unit_start.push(count);
410            Self { units, unit_start }
411        }
412    }
413
414    /// How many positions the matcher can be at — code units, for both kinds of pattern,
415    /// since that is what `lastIndex` is compared against.
416    fn units_len(&self) -> usize {
417        self.unit_start[self.unit_start.len() - 1]
418    }
419
420    /// The matcher position a code-unit offset starts at, rounded down to a boundary.
421    ///
422    /// The rounding is what makes a `lastIndex` in the middle of a surrogate pair land on
423    /// the character that contains it instead of between two.
424    fn position(&self, offset: usize) -> usize {
425        self.unit_start
426            .partition_point(|start| *start <= offset)
427            .saturating_sub(1)
428    }
429
430    /// The code-unit offset of a matcher position.
431    fn offset(&self, position: usize) -> usize {
432        self.unit_start[position.min(self.unit_start.len() - 1)]
433    }
434
435    /// The text between two matcher positions.
436    ///
437    /// Built through UTF-16 so that a lone surrogate survives: collecting code points into a
438    /// `String` would turn one into U+FFFD, and then `exec` would report different text than
439    /// the input it was given.
440    fn slice(&self, start: usize, end: usize) -> crate::value::Wtf8 {
441        points_to_wtf8(self.units.get(start..end).unwrap_or_default())
442    }
443}
444
445/// Code points (or code units) to WTF-8, keeping a lone surrogate instead of replacing it.
446fn points_to_wtf8(points: &[u32]) -> crate::value::Wtf8 {
447    let mut units = Vec::with_capacity(points.len());
448    for point in points {
449        if *point > 0xFFFF {
450            let value = point - 0x10000;
451            units.push(0xD800 + (value >> 10) as u16);
452            units.push(0xDC00 + (value & 0x3FF) as u16);
453        } else {
454            units.push(*point as u16);
455        }
456    }
457    crate::value::Wtf8::from_units(&units)
458}
459
460/// `RegExp.prototype.test(string)`.
461fn test(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
462    let result = exec(interp, this, args)?;
463    Ok(Value::Bool(!matches!(result, Value::Null)))
464}
465
466fn to_string(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
467    let Some(object) = this.as_object() else {
468        return Err(interp.type_error("RegExp.prototype.toString called on a non-object"));
469    };
470    let Some(data) = object.regexp() else {
471        return Err(interp.type_error("RegExp.prototype.toString called on a non-RegExp"));
472    };
473    let source = if data.source.is_empty() {
474        "(?:)".to_string()
475    } else {
476        data.source.clone()
477    };
478    Ok(interp.string(format!("/{source}/{}", data.flags)))
479}
480
481fn source(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
482    let data = data_of(interp, &this)?;
483    // An empty pattern reports `(?:)` so that `/` + source + `/` parses again.
484    let text = if data.source.is_empty() {
485        "(?:)".to_string()
486    } else {
487        data.source.clone()
488    };
489    Ok(interp.string(&text))
490}
491
492fn flags(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
493    let data = data_of(interp, &this)?;
494    Ok(interp.string(&data.flags))
495}
496
497fn data_of(interp: &mut Interp<'_>, this: &Value) -> JsResult<RegExpData> {
498    match this.as_object().and_then(|object| object.regexp()) {
499        Some(data) => Ok(data.clone()),
500        None => Err(interp.type_error("method called on a non-RegExp")),
501    }
502}
503
504/// One of the boolean flag accessors.
505fn flag_getter(interp: &mut Interp<'_>, this: Value, pick: fn(&Flags) -> bool) -> JsResult<Value> {
506    let data = data_of(interp, &this)?;
507    Ok(Value::Bool(pick(&data.regex.flags)))
508}
509
510fn global(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
511    flag_getter(interp, this, |flags| flags.global)
512}
513fn ignore_case(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
514    flag_getter(interp, this, |flags| flags.ignore_case)
515}
516fn multiline(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
517    flag_getter(interp, this, |flags| flags.multiline)
518}
519fn sticky(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
520    flag_getter(interp, this, |flags| flags.sticky)
521}
522fn unicode(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
523    flag_getter(interp, this, |flags| flags.unicode)
524}
525fn dot_all(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
526    flag_getter(interp, this, |flags| flags.dot_all)
527}
528fn has_indices(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
529    flag_getter(interp, this, |flags| flags.has_indices)
530}
531
532// -- the Symbol methods ------------------------------------------------------
533//
534// These are what `String.prototype.match` and friends dispatch to. Each one re-reads the
535// pattern's flags through the object's own properties, as the spec does, so a subclass
536// that overrides `lastIndex` keeps working.
537
538/// `String.prototype.match`'s hook.
539fn symbol_match(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
540    let Some(object) = this.as_object() else {
541        return Err(interp.type_error("Symbol.match called on a non-object"));
542    };
543    let text = interp.checked_to_wtf8(&arg(args, 0))?;
544    let is_global = interp
545        .get_property(object, "global")?
546        .unwrap_or(Value::Undefined)
547        .to_boolean();
548    if !is_global {
549        return exec_on(interp, object, &text);
550    }
551    interp.set_property(object, "lastIndex", Value::Int(0))?;
552    let mut results = Vec::new();
553    let input = MatchInput::new(
554        &data_of(interp, &Value::Object(object.clone()))?.regex,
555        &text,
556    );
557    loop {
558        let result = exec_on(interp, object, &text)?;
559        if matches!(result, Value::Null) {
560            break;
561        }
562        let Value::Object(array) = &result else {
563            break;
564        };
565        let matched = interp.get_property(array, "0")?.unwrap_or(Value::Undefined);
566        let empty = interp.to_js_string(&matched)?.is_empty();
567        results.push(result);
568        if empty {
569            let next = interp
570                .get_property(object, "lastIndex")?
571                .unwrap_or(Value::Int(0));
572            let next = interp.to_js_number(&next)? as usize + 1;
573            interp.set_property(object, "lastIndex", Value::Int(next as i32))?;
574            if next > input.units_len() {
575                break;
576            }
577        }
578    }
579    if results.is_empty() {
580        return Ok(Value::Null);
581    }
582    Ok(Value::Object(interp.new_array(results)))
583}
584
585/// `String.prototype.search`'s hook: the index of the first match, or -1.
586fn symbol_search(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
587    let Some(object) = this.as_object() else {
588        return Err(interp.type_error("Symbol.search called on a non-object"));
589    };
590    let text = interp.checked_to_wtf8(&arg(args, 0))?;
591    // `search` ignores the caller's `lastIndex`: it always looks from the start, and
592    // leaves the property alone afterwards.
593    interp.set_property(object, "lastIndex", Value::Int(0))?;
594    let result = exec_on(interp, object, &text)?;
595    match result {
596        Value::Null => Ok(Value::Int(-1)),
597        Value::Object(array) => Ok(interp
598            .get_property(&array, "index")?
599            .unwrap_or(Value::Int(-1))),
600        other => Ok(other),
601    }
602}
603
604/// `String.prototype.split`'s hook.
605fn symbol_split(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
606    let Some(object) = this.as_object() else {
607        return Err(interp.type_error("Symbol.split called on a non-object"));
608    };
609    let text = interp.checked_to_wtf8(&arg(args, 0))?;
610    let limit = match arg(args, 1) {
611        Value::Undefined => u32::MAX,
612        other => {
613            let number = interp.to_js_number(&other)?;
614            if number.is_nan() || number < 0.0 {
615                0
616            } else {
617                number as u32
618            }
619        }
620    };
621    if limit == 0 {
622        return Ok(Value::Object(interp.new_array(Vec::new())));
623    }
624    let data = data_of(interp, &Value::Object(object.clone()))?;
625    let input = MatchInput::new(&data.regex, &text);
626    let mut parts: Vec<Value> = Vec::new();
627    let mut last = 0usize;
628    let mut scan = 0usize;
629    while scan <= input.units.len() {
630        let Some(found) = data.regex.exec_at(&input.units, scan) else {
631            break;
632        };
633        // A zero-length match cannot split anything, and taking it would loop forever.
634        if found.end == found.start {
635            scan = found.start + 1;
636            continue;
637        }
638        parts.push(interp.string_wtf8(input.slice(last, found.start)));
639        if parts.len() as u32 >= limit {
640            return Ok(Value::Object(interp.new_array(parts)));
641        }
642        for group in found.captures.iter().skip(1) {
643            parts.push(match group {
644                Some((start, end)) => interp.string_wtf8(input.slice(*start, *end)),
645                None => Value::Undefined,
646            });
647            if parts.len() as u32 >= limit {
648                return Ok(Value::Object(interp.new_array(parts)));
649            }
650        }
651        last = found.end;
652        scan = found.end;
653    }
654    parts.push(interp.string_wtf8(input.slice(last, input.units.len())));
655    Ok(Value::Object(interp.new_array(parts)))
656}
657
658/// `RegExp.prototype[Symbol.replace]` — §22.2.6.11, the half `String.prototype.replace` and
659/// `replaceAll` delegate to.
660fn symbol_replace(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
661    let Some(object) = this.as_object() else {
662        return Err(interp.type_error("Symbol.replace called on a non-object"));
663    };
664    let text = interp.checked_to_wtf8(&arg(args, 0))?;
665    let replacement = arg(args, 1);
666    let is_global = interp
667        .get_property(object, "global")?
668        .unwrap_or(Value::Undefined)
669        .to_boolean();
670    let data = data_of(interp, &Value::Object(object.clone()))?;
671    let input = MatchInput::new(&data.regex, &text);
672    // The string's own code units, which is what the output is assembled in.
673    let units = text.to_units();
674    let mut out: Vec<u16> = Vec::new();
675    let mut last = 0usize;
676    let mut scan = 0usize;
677    let mut replaced = false;
678    while scan <= input.units.len() {
679        let Some(found) = data.regex.exec_at(&input.units, scan) else {
680            break;
681        };
682        out.extend_from_slice(&units[input.offset(last)..input.offset(found.start)]);
683        let substituted = substitute(
684            interp,
685            &replacement,
686            &input,
687            &units,
688            &found,
689            &data.regex.names,
690        )?;
691        out.extend_from_slice(&substituted);
692        last = found.end;
693        let empty = found.start == found.end;
694        scan = if empty { found.end + 1 } else { found.end };
695        replaced = true;
696        if !is_global {
697            break;
698        }
699        if empty && found.end >= input.units.len() {
700            break;
701        }
702    }
703    if !replaced {
704        return Ok(interp.string_wtf8(text.clone()));
705    }
706    out.extend_from_slice(&units[input.offset(last)..]);
707    Ok(interp.string_wtf8(crate::value::Wtf8::from_units(&out)))
708}
709
710/// Apply a replacement: a function receives the match and its groups, a string has its
711/// `$&`, `$n`, `$<name>`, `` $` ``, `$'` and `$$` expanded by the shared
712/// [`get_substitution`], which is also what `String.prototype.replace{,All}` use — one
713/// implementation so the two cannot disagree about `$`.
714#[allow(clippy::too_many_arguments)]
715fn substitute(
716    interp: &mut Interp<'_>,
717    replacement: &Value,
718    input: &MatchInput,
719    units: &[u16],
720    found: &crate::regexp::Match,
721    names: &[(String, usize)],
722) -> JsResult<Vec<u16>> {
723    let start = input.offset(found.start);
724    let end = input.offset(found.end);
725    if let Value::Object(function) = replacement
726        && function.is_callable()
727    {
728        let mut args: Vec<Value> = vec![interp.string_wtf8(input.slice(found.start, found.end))];
729        for group in found.captures.iter().skip(1) {
730            args.push(match group {
731                Some((start, end)) => interp.string_wtf8(input.slice(*start, *end)),
732                None => Value::Undefined,
733            });
734        }
735        // `position` is a code unit offset; the matched text is the match itself rather than
736        // a re-slice, so a match that split a surrogate pair keeps both halves.
737        args.push(Value::Int(start as i32));
738        args.push(interp.string_wtf8(crate::value::Wtf8::from_units(units)));
739        let result = interp.call_value(Value::Object(function.clone()), Value::Undefined, args)?;
740        // The function's result keeps any unpaired surrogate it produced.
741        return Ok(interp.checked_to_wtf8(&result)?.to_units());
742    }
743    let template = interp.checked_to_wtf8(replacement)?;
744    // The captures in code units, capture 0 being the whole match: the shared expansion
745    // indexes `input` with them.
746    let captures: Vec<Option<(usize, usize)>> = found
747        .captures
748        .iter()
749        .map(|group| group.map(|(start, end)| (input.offset(start), input.offset(end))))
750        .collect();
751    let mut out: Vec<u16> = Vec::new();
752    get_substitution(
753        &mut out,
754        &template,
755        &Substitution {
756            input: units,
757            position: start,
758            match_len: end - start,
759            captures: &captures,
760            // `None` when the pattern has no named groups at all, which is a different rule
761            // from "no group by that name" — see `Substitution::names`.
762            names: (!names.is_empty()).then_some(names),
763        },
764    );
765    Ok(out)
766}
767
768/// Build a `RegExp` object for `source`/`flags`, reusing an existing one when the same
769/// pattern was compiled before.
770pub fn new_regexp(interp: &mut Interp<'_>, source: &str, flags: &str) -> JsResult<Gc<JsObject>> {
771    let prototype = default_prototype(interp);
772    let object = interp.new_object(Some(prototype));
773    initialise(interp, object, source, flags)
774}
775
776/// The realm's `%RegExp.prototype%`.
777fn default_prototype(interp: &Interp<'_>) -> Gc<JsObject> {
778    interp
779        .realm
780        .regexp_proto
781        .clone()
782        .unwrap_or_else(|| interp.realm.object_proto.clone())
783}
784
785/// `RegExpAlloc(new.target)` — the empty object `new RegExp` fills in.
786///
787/// The prototype comes from `new.target` through `OrdinaryCreateFromConstructor`, which is
788/// what makes `class RE extends RegExp` an instance of `RE`: the derived constructor's
789/// `super()` runs this same native, and a fixed `%RegExp.prototype%` here produced a plain
790/// `RegExp`, so a subclass's override of `@@replace` was never reached.
791fn allocate(interp: &mut Interp<'_>) -> JsResult<Gc<JsObject>> {
792    let fallback = default_prototype(interp);
793    interp.new_ctor_instance(fallback)
794}
795
796/// `RegExpInitialize(object, source, flags)`: compile the pattern and install the matcher.
797fn initialise(
798    interp: &mut Interp<'_>,
799    object: Gc<JsObject>,
800    source: &str,
801    flags: &str,
802) -> JsResult<Gc<JsObject>> {
803    let Some(parsed) = Flags::parse(flags) else {
804        return Err(invalid_pattern(interp, String::new(), "flags"));
805    };
806    let regex = match Regex::compile(source, parsed) {
807        Ok(regex) => regex,
808        Err(error) => {
809            // The reference reports the engine's own message, not a generic one.
810            return Err(invalid_pattern(interp, error.message, ""));
811        }
812    };
813    object.set_regexp(RegExpData {
814        regex: std::rc::Rc::new(regex),
815        source: source.to_string(),
816        flags: parsed.as_flag_string(),
817    });
818    object.define(
819        "lastIndex",
820        Property::with_attributes(Value::Int(0), true, false),
821    );
822    Ok(object)
823}
824
825/// The `SyntaxError` a malformed pattern raises.
826///
827/// The two forms the reference uses: a bad flag string reports `invalid regular expression
828/// flags`, and a bad pattern reports the engine's own message.
829fn invalid_pattern(interp: &Interp<'_>, message: String, flags: &str) -> crate::interp::Signal {
830    let text = if flags.is_empty() {
831        message
832    } else {
833        "invalid regular expression flags".to_string()
834    };
835    crate::interp::Signal::Throw(interp.make_error("SyntaxError", &text))
836}
837
838/// Whether `value` is a `RegExp` object.
839pub fn is_regexp(object: &Gc<JsObject>) -> bool {
840    object.regexp().is_some()
841}