quickjs-pure 0.13.0

Embeddable JavaScript engine written in pure Rust (QuickJS-compatible)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
//! `RegExp` and `RegExp.prototype`.
//!
//! The engine lives in [`crate::regexp`]; this module is the JavaScript-facing half: the
//! constructor, the compiled-pattern cache, `lastIndex`, and `exec`.
//!
//! `exec` is where most of the observable semantics live. A `g` or `y` pattern advances
//! `lastIndex`, a failed match resets it to zero, and the returned array carries the
//! captured groups plus `index`, `input` and (for the `d` flag) `indices`.

use crate::builtins::substitution::{Substitution, get_substitution};
use crate::builtins::{arg, define_method, install_species_accessor};
use crate::interp::{Interp, JsResult};
use crate::object::{JsObject, Property};
use crate::regexp::{Flags, Regex};
use crate::value::Value;
use js_gc::Gc;

/// The compiled pattern an object of `ObjectKind::RegExp` carries.
///
/// Boxed through `Rc` because a `RegExp` object is shared by every reference to it and
/// the pattern is immutable once compiled.
#[derive(Clone)]
pub struct RegExpData {
    /// The compiled pattern, shared between `exec` calls.
    pub regex: std::rc::Rc<Regex>,
    /// Pattern source as written, which `.source` reports.
    pub source: String,
    /// The flags, in canonical order.
    pub flags: String,
}

/// Install `RegExp` and its prototype methods.
pub fn install(interp: &mut Interp<'_>, object_proto: &Gc<JsObject>) -> Gc<JsObject> {
    let prototype = interp.new_object(Some(object_proto.clone()));
    let constructor = interp.new_native_constructor("RegExp", 2, constructor);
    constructor.define(
        "prototype",
        Property::with_attributes(Value::Object(prototype.clone()), false, false),
    );
    prototype.define(
        "constructor",
        Property::with_attributes(Value::Object(constructor.clone()), true, false),
    );

    define_method(&prototype, "exec", 1, exec, interp);
    define_method(&prototype, "test", 1, test, interp);
    define_method(&prototype, "toString", 0, to_string, interp);
    for (name, getter) in [
        (
            "source",
            source as fn(&mut Interp<'_>, Value, &[Value]) -> JsResult<Value>,
        ),
        ("flags", flags),
        ("global", global),
        ("ignoreCase", ignore_case),
        ("multiline", multiline),
        ("sticky", sticky),
        ("unicode", unicode),
        ("dotAll", dot_all),
        ("hasIndices", has_indices),
    ] {
        let getter = interp.new_native(name, 0, getter);
        prototype.define(
            name,
            Property {
                getter: Some(Value::Object(getter)),
                enumerable: false,
                configurable: true,
                ..Property::default()
            },
        );
    }

    // `RegExp.escape` is a static: it is on the constructor, not the prototype.
    define_method(&constructor, "escape", 1, escape, interp);
    install_species_accessor(&constructor, interp);

    // `Symbol.match` and friends are what `String.prototype.match` looks up; without them
    // a regexp is not recognised as a pattern by those methods.
    install_symbol_methods(interp, &prototype, &constructor);
    interp.realm.regexp_proto = Some(prototype.clone());
    interp.realm.regexp_ctor = Some(constructor.clone());
    constructor
}

fn install_symbol_methods(
    interp: &mut Interp<'_>,
    prototype: &Gc<JsObject>,
    constructor: &Gc<JsObject>,
) {
    use crate::interp::WellKnown;
    for (which, name, func, length) in [
        (
            WellKnown::Match,
            "[Symbol.match]",
            symbol_match as crate::object::NativeFn,
            1,
        ),
        (WellKnown::Replace, "[Symbol.replace]", symbol_replace, 2),
        (WellKnown::Search, "[Symbol.search]", symbol_search, 1),
        (WellKnown::Split, "[Symbol.split]", symbol_split, 2),
    ] {
        let method = interp.new_native(name, length, func);
        prototype.define_key(
            &interp.realm.well_known_key(which),
            Property::with_attributes(Value::Object(method), true, false),
        );
    }
    let _ = constructor;
}

/// `RegExp.escape(string)`: escape `string` so it can be used as a literal pattern.
///
/// Two things make this more than a backslash loop:
///
/// * **The first character is escaped differently.** A leading ASCII letter or digit
///   becomes `\xNN`, because `"1"` after a `\0` or `\c` would otherwise be read as part
///   of the preceding escape rather than as a digit.
/// * **Most characters need no escape at all.** Only the syntax characters, `/`, the
///   control escapes, a fixed list of other punctuators, whitespace, line terminators and
///   lone surrogates are touched; everything else — including all non-ASCII letters — is
///   copied through, because a literal character in a pattern is already literal outside
///   syntax positions.
///
/// Note `\s`'s set is reused for "whitespace or line terminator" (see
/// [`quickjs_regexp::is_space`]) rather than restated, so the two cannot drift.
fn escape(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    let arg = arg(args, 0);
    // Not `ToString`: the spec is explicit that a non-string is a TypeError rather than
    // being coerced, so `RegExp.escape(1)` throws instead of returning `"1"`.
    if !matches!(arg, Value::String(_)) {
        return Err(interp.type_error("not a string"));
    }
    let source = interp.checked_to_wtf8(&arg)?.code_point_values();
    let mut out: Vec<u32> = Vec::with_capacity(source.len());
    for (position, cp) in source.iter().enumerate() {
        // `escaped` is empty exactly at the first code point, since every branch below
        // emits at least one code unit.
        let leading = position == 0;
        encode_for_regexp_escape(*cp, leading, &mut out);
    }
    Ok(interp.string_wtf8(points_to_wtf8(&out)))
}

/// The per-code-point half of `RegExp.escape`: `EncodeForRegExpEscape`, plus the leading
/// alphanumeric rule that the caller knows about and this does not.
fn encode_for_regexp_escape(c: u32, leading: bool, out: &mut Vec<u32>) {
    let backslash = u32::from(b'\\');
    // A leading ASCII letter or digit is always hex-escaped: it may otherwise be read as
    // part of a preceding `\0…` or `\c…`.
    let ascii_alnum = matches!(c, 0x30..=0x39 | 0x41..=0x5A | 0x61..=0x7A);
    if leading && ascii_alnum {
        push_hex_escape(c, out);
        return;
    }
    // SyntaxCharacter, plus `/` — the one character a pattern literal would terminate on.
    if matches!(
        c,
        0x2E | 0x2A | 0x2B | 0x3F | 0x5E | 0x24 | 0x7C // . * + ? ^ $ |
        | 0x28 | 0x29 | 0x5B | 0x5D | 0x7B | 0x7D    // ( ) [ ] { }
        | 0x5C | 0x2F // \ /
    ) {
        out.push(backslash);
        out.push(c);
        return;
    }
    // The five control escapes that have a short spelling.
    if let Some(letter) = match c {
        0x09 => Some('t'),
        0x0A => Some('n'),
        0x0B => Some('v'),
        0x0C => Some('f'),
        0x0D => Some('r'),
        _ => None,
    } {
        out.push(backslash);
        out.push(u32::from(letter as u8));
        return;
    }
    // `otherPunctuators` from the spec, then whitespace, line terminators and lone
    // surrogates: all of these become `\xNN` or `\uNNNN`.
    let other_punctuator = matches!(
        c,
        0x2C | 0x2D | 0x3D | 0x3C | 0x3E | 0x23 | 0x26 | 0x21 // , - = < > # & !
        | 0x25 | 0x3A | 0x3B | 0x40 | 0x7E | 0x27 | 0x60 | 0x22 // % : ; @ ~ ' ` "
    );
    if other_punctuator || quickjs_regexp::is_space(c) || (0xD800..=0xDFFF).contains(&c) {
        if c <= 0xFF {
            push_hex_escape(c, out);
        } else {
            // `\uNNNN`, per code unit. Every code point in this branch is below 0x10000
            // (the spaces, the line separators, the surrogates), so one unit is enough;
            // anything astral falls through to the literal case below.
            out.push(backslash);
            out.push(u32::from(b'u'));
            for shift in [12, 8, 4, 0] {
                out.push(u32::from(hex_digit((c >> shift) & 0xF)));
            }
        }
        return;
    }
    // Everything else is already literal in a pattern, so it is copied through.
    out.push(c);
}

/// `\xNN` for a code point below 0x100.
fn push_hex_escape(c: u32, out: &mut Vec<u32>) {
    out.push(u32::from(b'\\'));
    out.push(u32::from(b'x'));
    out.push(u32::from(hex_digit((c >> 4) & 0xF)));
    out.push(u32::from(hex_digit(c & 0xF)));
}

/// Lowercase hex, which is the case both `\x` and `\u` escapes are expected in.
fn hex_digit(nibble: u32) -> u8 {
    match nibble {
        0..=9 => b'0' + nibble as u8,
        _ => b'a' + (nibble as u8 - 10),
    }
}

/// `new RegExp(pattern, flags)`.
fn constructor(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    let pattern = arg(args, 0);
    let flags = arg(args, 1);
    // `new RegExp(existingRegExp)` copies the pattern and flags.
    let (source, flags) = match &pattern {
        Value::Object(object) if object.regexp().is_some() => {
            let data = object.regexp().expect("checked");
            let flags = if matches!(flags, Value::Undefined) {
                data.flags.clone()
            } else {
                interp.to_js_string(&flags)?
            };
            (data.source.clone(), flags)
        }
        // `RegExpCreate(undefined, flags)`: the *pattern* is empty, the flags are not.
        // Dropping them made `new RegExp(x, "g")` a non-global regexp, so
        // `"asdf".replace(new RegExp(undefined, "g"), "1")` replaced once rather than five
        // times — test262's `replace/S15.5.4.11_A1_T17`. `ToString(flags)` happens whether
        // or not the pattern is undefined, so it is spelled the same as the arm below.
        Value::Undefined => (
            String::new(),
            if matches!(flags, Value::Undefined) {
                String::new()
            } else {
                interp.to_js_string(&flags)?
            },
        ),
        other => (
            interp.to_js_string(other)?,
            if matches!(flags, Value::Undefined) {
                String::new()
            } else {
                interp.to_js_string(&flags)?
            },
        ),
    };
    let object = allocate(interp)?;
    Ok(Value::Object(initialise(interp, object, &source, &flags)?))
}

/// `RegExp.prototype.exec(string)`.
fn exec(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let Some(object) = this.as_object() else {
        return Err(interp.type_error("RegExp.prototype.exec called on a non-object"));
    };
    let text = interp.checked_to_wtf8(&arg(args, 0))?;
    exec_on(interp, object, &text)
}

/// The shared implementation of `exec`, used by the `String` methods as well.
pub fn exec_on(
    interp: &mut Interp<'_>,
    object: &Gc<JsObject>,
    text: &crate::value::Wtf8,
) -> JsResult<Value> {
    let Some(data) = object.regexp() else {
        return Err(interp.type_error("method called on a non-RegExp"));
    };
    let sticky_or_global = data.regex.flags.global || data.regex.flags.sticky;
    let mut start = if sticky_or_global {
        let index = interp.get_property(object, "lastIndex")?;
        let index = interp.to_js_number(&index.unwrap_or(Value::Int(0)))?;
        if !index.is_finite() || index < 0.0 {
            interp.set_property(object, "lastIndex", Value::Int(0))?;
            return Ok(Value::Null);
        }
        index as usize
    } else {
        0
    };
    let input: Vec<u32> = text.code_point_values();
    // `lastIndex`, `index` and the `d` flag's pairs all count **UTF-16 code units**, while the
    // matcher works in characters. `unit_start[i]` is the code-unit offset of character `i`,
    // with one extra entry for the end, so the two unit systems convert both ways.
    let mut unit_start = Vec::with_capacity(input.len() + 1);
    let mut units = 0;
    for character in &input {
        unit_start.push(units);
        units += if *character > 0xFFFF { 2 } else { 1 };
    }
    unit_start.push(units);
    // A `lastIndex` inside a surrogate pair has no character of its own; it belongs to the
    // character that contains it, which is the same as rounding down to a code point
    // boundary — what the reference does, and what makes `/(?:)/gu` with `lastIndex = 1` on
    // `"🐱"` report `index === 0`.
    if start > units {
        if sticky_or_global {
            interp.set_property(object, "lastIndex", Value::Int(0))?;
        }
        return Ok(Value::Null);
    }
    start = unit_start
        .partition_point(|offset| *offset <= start)
        .saturating_sub(1);
    let found = data.regex.exec_at(&input, start);
    let Some(found) = found else {
        if sticky_or_global {
            interp.set_property(object, "lastIndex", Value::Int(0))?;
        }
        return Ok(Value::Null);
    };
    // `lastIndex` moves to the end of the match, in code units — not characters, which is
    // why an astral match advances by two.
    if sticky_or_global {
        let units = unit_start[found.end.min(unit_start.len() - 1)];
        interp.set_property(object, "lastIndex", Value::Int(units as i32))?;
    }
    // The result array: the whole match, then one element per group. A group that did not
    // participate is `undefined`, not a hole.
    let mut elements: Vec<Value> = Vec::with_capacity(found.captures.len());
    for capture in &found.captures {
        elements.push(match capture {
            Some((start, end)) => interp.string_wtf8(slice(&input, *start, *end)),
            None => Value::Undefined,
        });
    }
    let array = interp.new_array(elements);
    let index = unit_start[found.start.min(unit_start.len() - 1)];
    let input_value = interp.string_wtf8(text.clone());
    interp.set_property(&array, "index", Value::Int(index as i32))?;
    interp.set_property(&array, "input", input_value.clone())?;
    // `m.groups`: a null-prototype object mapping each *named* group to its capture, or
    // `undefined` when the pattern has no named groups at all — which is what the spec
    // says, and what `m.groups === undefined` tests check.
    //
    // The object has a `null` prototype (`Object.create(null)`), so `m.groups.toString`
    // is `undefined` and a group named `toString` does not collide with `Object.prototype`.
    let groups = if data.regex.names.is_empty() {
        Value::Undefined
    } else {
        let groups = interp.new_object(None);
        for (name, index) in &data.regex.names {
            let value = match found.captures.get(*index).copied().flatten() {
                Some((start, end)) => interp.string_wtf8(slice(&input, start, end)),
                None => Value::Undefined,
            };
            interp.set_property(&groups, name, value)?;
        }
        Value::Object(groups)
    };
    interp.set_property(&array, "groups", groups)?;
    if data.regex.flags.has_indices {
        let mut pairs = Vec::with_capacity(found.captures.len());
        for capture in &found.captures {
            pairs.push(match capture {
                Some((start, end)) => {
                    let (start, end) = (
                        unit_start[(*start).min(unit_start.len() - 1)],
                        unit_start[(*end).min(unit_start.len() - 1)],
                    );
                    let pair =
                        interp.new_array(vec![Value::Int(start as i32), Value::Int(end as i32)]);
                    Value::Object(pair)
                }
                None => Value::Undefined,
            });
        }
        let indices = interp.new_array(pairs);
        interp.set_property(&array, "indices", Value::Object(indices))?;
    }
    Ok(Value::Object(array))
}

/// The text of `input[start..end]`, in code points.
///
/// Built through UTF-16 so that a lone surrogate survives: collecting code points into a
/// `String` would turn one into U+FFFD, and then `exec` would report different text than
/// the input it was given.
fn slice(input: &[u32], start: usize, end: usize) -> crate::value::Wtf8 {
    points_to_wtf8(input.get(start..end).unwrap_or_default())
}

/// Code points to WTF-8, keeping a lone surrogate instead of replacing it.
fn points_to_wtf8(points: &[u32]) -> crate::value::Wtf8 {
    let mut units = Vec::with_capacity(points.len());
    for point in points {
        if *point > 0xFFFF {
            let value = point - 0x10000;
            units.push(0xD800 + (value >> 10) as u16);
            units.push(0xDC00 + (value & 0x3FF) as u16);
        } else {
            units.push(*point as u16);
        }
    }
    crate::value::Wtf8::from_units(&units)
}

/// `RegExp.prototype.test(string)`.
fn test(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let result = exec(interp, this, args)?;
    Ok(Value::Bool(!matches!(result, Value::Null)))
}

fn to_string(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    let Some(object) = this.as_object() else {
        return Err(interp.type_error("RegExp.prototype.toString called on a non-object"));
    };
    let Some(data) = object.regexp() else {
        return Err(interp.type_error("RegExp.prototype.toString called on a non-RegExp"));
    };
    let source = if data.source.is_empty() {
        "(?:)".to_string()
    } else {
        data.source.clone()
    };
    Ok(interp.string(format!("/{source}/{}", data.flags)))
}

fn source(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    let data = data_of(interp, &this)?;
    // An empty pattern reports `(?:)` so that `/` + source + `/` parses again.
    let text = if data.source.is_empty() {
        "(?:)".to_string()
    } else {
        data.source.clone()
    };
    Ok(interp.string(&text))
}

fn flags(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    let data = data_of(interp, &this)?;
    Ok(interp.string(&data.flags))
}

fn data_of(interp: &mut Interp<'_>, this: &Value) -> JsResult<RegExpData> {
    match this.as_object().and_then(|object| object.regexp()) {
        Some(data) => Ok(data.clone()),
        None => Err(interp.type_error("method called on a non-RegExp")),
    }
}

/// One of the boolean flag accessors.
fn flag_getter(interp: &mut Interp<'_>, this: Value, pick: fn(&Flags) -> bool) -> JsResult<Value> {
    let data = data_of(interp, &this)?;
    Ok(Value::Bool(pick(&data.regex.flags)))
}

fn global(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    flag_getter(interp, this, |flags| flags.global)
}
fn ignore_case(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    flag_getter(interp, this, |flags| flags.ignore_case)
}
fn multiline(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    flag_getter(interp, this, |flags| flags.multiline)
}
fn sticky(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    flag_getter(interp, this, |flags| flags.sticky)
}
fn unicode(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    flag_getter(interp, this, |flags| flags.unicode)
}
fn dot_all(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    flag_getter(interp, this, |flags| flags.dot_all)
}
fn has_indices(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    flag_getter(interp, this, |flags| flags.has_indices)
}

// -- the Symbol methods ------------------------------------------------------
//
// These are what `String.prototype.match` and friends dispatch to. Each one re-reads the
// pattern's flags through the object's own properties, as the spec does, so a subclass
// that overrides `lastIndex` keeps working.

/// `String.prototype.match`'s hook.
fn symbol_match(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let Some(object) = this.as_object() else {
        return Err(interp.type_error("Symbol.match called on a non-object"));
    };
    let text = interp.checked_to_wtf8(&arg(args, 0))?;
    let is_global = interp
        .get_property(object, "global")?
        .unwrap_or(Value::Undefined)
        .to_boolean();
    if !is_global {
        return exec_on(interp, object, &text);
    }
    interp.set_property(object, "lastIndex", Value::Int(0))?;
    let mut results = Vec::new();
    let input: Vec<u32> = text.code_point_values();
    loop {
        let result = exec_on(interp, object, &text)?;
        if matches!(result, Value::Null) {
            break;
        }
        let Value::Object(array) = &result else {
            break;
        };
        let matched = interp.get_property(array, "0")?.unwrap_or(Value::Undefined);
        let empty = interp.to_js_string(&matched)?.is_empty();
        results.push(result);
        if empty {
            let next = interp
                .get_property(object, "lastIndex")?
                .unwrap_or(Value::Int(0));
            let next = interp.to_js_number(&next)? as usize + 1;
            interp.set_property(object, "lastIndex", Value::Int(next as i32))?;
            if next > input.len() {
                break;
            }
        }
    }
    if results.is_empty() {
        return Ok(Value::Null);
    }
    Ok(Value::Object(interp.new_array(results)))
}

/// `String.prototype.search`'s hook: the index of the first match, or -1.
fn symbol_search(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let Some(object) = this.as_object() else {
        return Err(interp.type_error("Symbol.search called on a non-object"));
    };
    let text = interp.checked_to_wtf8(&arg(args, 0))?;
    // `search` ignores the caller's `lastIndex`: it always looks from the start, and
    // leaves the property alone afterwards.
    interp.set_property(object, "lastIndex", Value::Int(0))?;
    let result = exec_on(interp, object, &text)?;
    match result {
        Value::Null => Ok(Value::Int(-1)),
        Value::Object(array) => Ok(interp
            .get_property(&array, "index")?
            .unwrap_or(Value::Int(-1))),
        other => Ok(other),
    }
}

/// `String.prototype.split`'s hook.
fn symbol_split(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let Some(object) = this.as_object() else {
        return Err(interp.type_error("Symbol.split called on a non-object"));
    };
    let text = interp.checked_to_wtf8(&arg(args, 0))?;
    let limit = match arg(args, 1) {
        Value::Undefined => u32::MAX,
        other => {
            let number = interp.to_js_number(&other)?;
            if number.is_nan() || number < 0.0 {
                0
            } else {
                number as u32
            }
        }
    };
    if limit == 0 {
        return Ok(Value::Object(interp.new_array(Vec::new())));
    }
    let data = data_of(interp, &Value::Object(object.clone()))?;
    let input: Vec<u32> = text.code_point_values();
    let mut parts: Vec<Value> = Vec::new();
    let mut last = 0usize;
    let mut scan = 0usize;
    while scan <= input.len() {
        let Some(found) = data.regex.exec_at(&input, scan) else {
            break;
        };
        // A zero-length match cannot split anything, and taking it would loop forever.
        if found.end == found.start {
            scan = found.start + 1;
            continue;
        }
        parts.push(interp.string_wtf8(slice(&input, last, found.start)));
        if parts.len() as u32 >= limit {
            return Ok(Value::Object(interp.new_array(parts)));
        }
        for group in found.captures.iter().skip(1) {
            parts.push(match group {
                Some((start, end)) => interp.string_wtf8(slice(&input, *start, *end)),
                None => Value::Undefined,
            });
            if parts.len() as u32 >= limit {
                return Ok(Value::Object(interp.new_array(parts)));
            }
        }
        last = found.end;
        scan = found.end;
    }
    parts.push(interp.string_wtf8(slice(&input, last, input.len())));
    Ok(Value::Object(interp.new_array(parts)))
}

/// `RegExp.prototype[Symbol.replace]` — §22.2.6.11, the half `String.prototype.replace` and
/// `replaceAll` delegate to.
fn symbol_replace(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let Some(object) = this.as_object() else {
        return Err(interp.type_error("Symbol.replace called on a non-object"));
    };
    let text = interp.checked_to_wtf8(&arg(args, 0))?;
    let replacement = arg(args, 1);
    let is_global = interp
        .get_property(object, "global")?
        .unwrap_or(Value::Undefined)
        .to_boolean();
    let data = data_of(interp, &Value::Object(object.clone()))?;
    // The matcher is character-based; every index a script sees is a code unit. `unit_start`
    // bridges the two, with an extra entry for the end (§22.1 counts UTF-16 units).
    let input: Vec<u32> = text.code_point_values();
    let units = text.to_units();
    let mut unit_start = Vec::with_capacity(input.len() + 1);
    let mut at = 0usize;
    for character in &input {
        unit_start.push(at);
        at += if *character > 0xFFFF { 2 } else { 1 };
    }
    unit_start.push(at);
    let to_units = |position: usize| unit_start[position.min(unit_start.len() - 1)];
    let mut out: Vec<u16> = Vec::new();
    let mut last = 0usize;
    let mut scan = 0usize;
    let mut replaced = false;
    while scan <= input.len() {
        let Some(found) = data.regex.exec_at(&input, scan) else {
            break;
        };
        out.extend_from_slice(&units[to_units(last)..to_units(found.start)]);
        let substituted = substitute(
            interp,
            &replacement,
            &input,
            &units,
            &unit_start,
            &found,
            &data.regex.names,
        )?;
        out.extend_from_slice(&substituted);
        last = found.end;
        let empty = found.start == found.end;
        scan = if empty { found.end + 1 } else { found.end };
        replaced = true;
        if !is_global {
            break;
        }
        if empty && found.end >= input.len() {
            break;
        }
    }
    if !replaced {
        return Ok(interp.string_wtf8(text.clone()));
    }
    out.extend_from_slice(&units[to_units(last)..]);
    Ok(interp.string_wtf8(crate::value::Wtf8::from_units(&out)))
}

/// Apply a replacement: a function receives the match and its groups, a string has its
/// `$&`, `$n`, `$<name>`, `` $` ``, `$'` and `$$` expanded by the shared
/// [`get_substitution`], which is also what `String.prototype.replace{,All}` use — one
/// implementation so the two cannot disagree about `$`.
#[allow(clippy::too_many_arguments)]
fn substitute(
    interp: &mut Interp<'_>,
    replacement: &Value,
    input: &[u32],
    units: &[u16],
    unit_start: &[usize],
    found: &crate::regexp::Match,
    names: &[(String, usize)],
) -> JsResult<Vec<u16>> {
    let to_units = |position: usize| unit_start[position.min(unit_start.len() - 1)];
    let start = to_units(found.start);
    let end = to_units(found.end);
    if let Value::Object(function) = replacement
        && function.is_callable()
    {
        let mut args: Vec<Value> = vec![interp.string_wtf8(slice(input, found.start, found.end))];
        for group in found.captures.iter().skip(1) {
            args.push(match group {
                Some((start, end)) => interp.string_wtf8(slice(input, *start, *end)),
                None => Value::Undefined,
            });
        }
        // `position` is a code unit offset; the matched text is the match itself rather than
        // a re-slice, so a match that split a surrogate pair keeps both halves.
        args.push(Value::Int(start as i32));
        args.push(interp.string_wtf8(crate::value::Wtf8::from_units(units)));
        let result = interp.call_value(Value::Object(function.clone()), Value::Undefined, args)?;
        // The function's result keeps any unpaired surrogate it produced.
        return Ok(interp.checked_to_wtf8(&result)?.to_units());
    }
    let template = interp.checked_to_wtf8(replacement)?;
    // The captures in code units, capture 0 being the whole match: the shared expansion
    // indexes `input` with them.
    let captures: Vec<Option<(usize, usize)>> = found
        .captures
        .iter()
        .map(|group| group.map(|(start, end)| (to_units(start), to_units(end))))
        .collect();
    let mut out: Vec<u16> = Vec::new();
    get_substitution(
        &mut out,
        &template,
        &Substitution {
            input: units,
            position: start,
            match_len: end - start,
            captures: &captures,
            // `None` when the pattern has no named groups at all, which is a different rule
            // from "no group by that name" — see `Substitution::names`.
            names: (!names.is_empty()).then_some(names),
        },
    );
    Ok(out)
}

/// Build a `RegExp` object for `source`/`flags`, reusing an existing one when the same
/// pattern was compiled before.
pub fn new_regexp(interp: &mut Interp<'_>, source: &str, flags: &str) -> JsResult<Gc<JsObject>> {
    let prototype = default_prototype(interp);
    let object = interp.new_object(Some(prototype));
    initialise(interp, object, source, flags)
}

/// The realm's `%RegExp.prototype%`.
fn default_prototype(interp: &Interp<'_>) -> Gc<JsObject> {
    interp
        .realm
        .regexp_proto
        .clone()
        .unwrap_or_else(|| interp.realm.object_proto.clone())
}

/// `RegExpAlloc(new.target)` — the empty object `new RegExp` fills in.
///
/// The prototype comes from `new.target` through `OrdinaryCreateFromConstructor`, which is
/// what makes `class RE extends RegExp` an instance of `RE`: the derived constructor's
/// `super()` runs this same native, and a fixed `%RegExp.prototype%` here produced a plain
/// `RegExp`, so a subclass's override of `@@replace` was never reached.
fn allocate(interp: &mut Interp<'_>) -> JsResult<Gc<JsObject>> {
    let fallback = default_prototype(interp);
    interp.new_ctor_instance(fallback)
}

/// `RegExpInitialize(object, source, flags)`: compile the pattern and install the matcher.
fn initialise(
    interp: &mut Interp<'_>,
    object: Gc<JsObject>,
    source: &str,
    flags: &str,
) -> JsResult<Gc<JsObject>> {
    let Some(parsed) = Flags::parse(flags) else {
        return Err(invalid_pattern(interp, String::new(), "flags"));
    };
    let regex = match Regex::compile(source, parsed) {
        Ok(regex) => regex,
        Err(error) => {
            // The reference reports the engine's own message, not a generic one.
            return Err(invalid_pattern(interp, error.message, ""));
        }
    };
    object.set_regexp(RegExpData {
        regex: std::rc::Rc::new(regex),
        source: source.to_string(),
        flags: parsed.as_flag_string(),
    });
    object.define(
        "lastIndex",
        Property::with_attributes(Value::Int(0), true, false),
    );
    Ok(object)
}

/// The `SyntaxError` a malformed pattern raises.
///
/// The two forms the reference uses: a bad flag string reports `invalid regular expression
/// flags`, and a bad pattern reports the engine's own message.
fn invalid_pattern(interp: &Interp<'_>, message: String, flags: &str) -> crate::interp::Signal {
    let text = if flags.is_empty() {
        message
    } else {
        "invalid regular expression flags".to_string()
    };
    crate::interp::Signal::Throw(interp.make_error("SyntaxError", &text))
}

/// Whether `value` is a `RegExp` object.
pub fn is_regexp(object: &Gc<JsObject>) -> bool {
    object.regexp().is_some()
}