quickjs-pure 0.15.3

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
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
//! `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),
        ("unicodeSets", unicode_sets),
        ("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::MatchAll,
            "[Symbol.matchAll]",
            symbol_match_all,
            1,
        ),
        (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)`.
///
/// §22.2.3.1 steps 2–3 are `IsRegExp(pattern)` and, when it answers true, `Get(pattern,
/// "source")` — **not** a read of the internal slot. That difference is observable: a plain
/// object whose `@@match` getter throws makes `new RegExp(obj, "")` throw, which is what
/// test262 `Symbol.matchAll/isregexp-this-throws` runs into on its way through the species
/// constructor. Reading `object.regexp()` made the constructor silently treat such an object
/// as a string pattern.
fn constructor(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    let pattern = arg(args, 0);
    let flags = arg(args, 1);
    let (source, flags) = if crate::builtins::string::is_regexp(interp, &pattern)? {
        let Value::Object(object) = &pattern else {
            return Err(interp.type_error("a regexp is not an object"));
        };
        let source = interp
            .get_property(object, "source")?
            .unwrap_or(Value::Undefined);
        let source = interp.to_js_string(&source)?;
        let flags = if matches!(flags, Value::Undefined) {
            let flags = interp
                .get_property(object, "flags")?
                .unwrap_or(Value::Undefined);
            interp.checked_to_string(&flags)?
        } else {
            interp.checked_to_string(&flags)?
        };
        (source, flags)
    } else {
        // `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`.
        let source = match &pattern {
            Value::Undefined => String::new(),
            other => interp.to_js_string(other)?,
        };
        let flags = if matches!(flags, Value::Undefined) {
            String::new()
        } else {
            interp.checked_to_string(&flags)?
        };
        (source, 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 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 = MatchInput::new(&data.regex, text);
    // 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 unit boundary —
    // what the reference does, and what makes `/(?:)/gu` with `lastIndex = 1` on `"🐱"`
    // report `index === 0`.
    if start > input.units_len() {
        if sticky_or_global {
            interp.set_property(object, "lastIndex", Value::Int(0))?;
        }
        return Ok(Value::Null);
    }
    let start = input.position(start);
    let found = data.regex.exec_at(&input.units, 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 under `u` advances by two.
    if sticky_or_global {
        let end = input.offset(found.end);
        interp.set_property(object, "lastIndex", Value::Int(end 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(input.slice(*start, *end)),
            None => Value::Undefined,
        });
    }
    let array = interp.new_array(elements);
    let index = input.offset(found.start);
    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(input.slice(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) = (input.offset(*start), input.offset(*end));
                    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 matcher's view of a string, and the bridge back to the code units a script sees.
///
/// Which unit the matcher consumes is decided by the pattern, not by the caller
/// ([`quickjs_regexp::Regex::per_code_unit`]):
///
/// * **No `u`/`v`.** A pattern is a sequence of UTF-16 code units, so `.` matches one unit,
///   a quantifier binds to one unit, and `[😀]` is a two-unit class. `units` is therefore the
///   string's code units, every offset the matcher reports is already a code-unit offset —
///   the unit `lastIndex`, `index`, `.length` and `d`'s pairs are expressed in — and
///   `unit_start` is the identity.
/// * **`u`/`v`.** A pattern is a sequence of code points, so `units` is the code points and
///   `unit_start` maps an offset back to code units.
///
/// Having one type for both is what keeps the four call sites (`exec`, `[Symbol.match]`,
/// `[Symbol.split]`, `[Symbol.replace]`) from each carrying their own copy of the mapping —
/// they had one, and `[Symbol.split]` was missing it entirely.
struct MatchInput {
    /// What the matcher consumes: code units, or code points.
    units: Vec<u32>,
    /// `unit_start[i]` is the code-unit offset of matcher position `i`, with one extra
    /// entry for the end.
    unit_start: Vec<usize>,
}

impl MatchInput {
    fn new(regex: &quickjs_regexp::Regex, text: &crate::value::Wtf8) -> Self {
        if regex.per_code_unit() {
            let units: Vec<u32> = text.to_units().into_iter().map(u32::from).collect();
            let unit_start = (0..=units.len()).collect();
            Self { units, unit_start }
        } else {
            let units = text.code_point_values();
            let mut unit_start = Vec::with_capacity(units.len() + 1);
            let mut count = 0;
            for point in &units {
                unit_start.push(count);
                count += if *point > 0xFFFF { 2 } else { 1 };
            }
            unit_start.push(count);
            Self { units, unit_start }
        }
    }

    /// How many positions the matcher can be at — code units, for both kinds of pattern,
    /// since that is what `lastIndex` is compared against.
    fn units_len(&self) -> usize {
        self.unit_start[self.unit_start.len() - 1]
    }

    /// The matcher position a code-unit offset starts at, rounded down to a boundary.
    ///
    /// The rounding is what makes a `lastIndex` in the middle of a surrogate pair land on
    /// the character that contains it instead of between two.
    fn position(&self, offset: usize) -> usize {
        self.unit_start
            .partition_point(|start| *start <= offset)
            .saturating_sub(1)
    }

    /// The code-unit offset of a matcher position.
    fn offset(&self, position: usize) -> usize {
        self.unit_start[position.min(self.unit_start.len() - 1)]
    }

    /// The text between two matcher positions.
    ///
    /// 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(&self, start: usize, end: usize) -> crate::value::Wtf8 {
        points_to_wtf8(self.units.get(start..end).unwrap_or_default())
    }
}

/// Code points (or code units) 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))
}

/// `RegExp.prototype.flags` — §22.2.4.8.
///
/// Every flag is `Get(R, name)`, one observable property read each, **not** a peek at the
/// internal slots. That is what makes `get-global-err` throw (the `global` getter is user
/// code) and what makes `builtin-success-g-set-lastindex` see `global: false` on a regexp
/// that *is* global — and, because `@@match` derives `global` from this string, what makes
/// it behave like the reference instead of like the slot.
///
/// The order below is the spec's canonical order (`dgimsuvy`), so the answer reads the same
/// as `RegExp.prototype.toString` builds it.
fn flags(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    let Some(object) = this.as_object().cloned() else {
        return Err(interp.type_error("flags called on a non-object"));
    };
    let mut out = String::with_capacity(8);
    for (name, letter) in [
        ("hasIndices", 'd'),
        ("global", 'g'),
        ("ignoreCase", 'i'),
        ("multiline", 'm'),
        ("dotAll", 's'),
        ("unicode", 'u'),
        ("unicodeSets", 'v'),
        ("sticky", 'y'),
    ] {
        let value = interp
            .get_property(&object, name)?
            .unwrap_or(Value::Undefined);
        if value.to_boolean() {
            out.push(letter);
        }
    }
    Ok(interp.string(out))
}

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 unicode_sets(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    flag_getter(interp, this, |flags| flags.unicode_sets)
}
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 — §22.2.7.2.
///
/// The global branch collects `ToString(result[0])`, **not** the result objects: `"aa".match(/a/g)`
/// is `["a","a"]`, an array of strings. It used to push the whole `exec` array, so every
/// global match came back as a nested array — visible to any `===` comparison against a
/// string, which is most of `S15.5.4.10_A2_*`.
fn symbol_match(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let Some(object) = this.as_object().cloned() else {
        return Err(interp.type_error("Symbol.match called on a non-object"));
    };
    let text = interp.checked_to_wtf8(&arg(args, 0))?;
    let text_value = interp.string_wtf8(text.clone());
    // §22.2.7.2 step 3 reads `flags` **before** it decides anything, and reads it once:
    // `global` and `unicode` are parsed out of that string rather than read as their own
    // properties. Reading `global`/`unicode` directly made `flags-tostring-error` and
    // `get-flags-err` unreachable — a regexp whose `flags` getter throws was silently
    // treated as non-global instead of throwing, and a subclass that overrides `flags`
    // was ignored entirely.
    let flags = interp
        .get_property(&object, "flags")?
        .unwrap_or(Value::Undefined);
    let flags = interp.checked_to_string(&flags)?;
    let is_global = flags.contains('g');
    let full_unicode = flags.contains('u') || flags.contains('v');
    if !is_global {
        return regexp_exec(interp, &Value::Object(object), &text_value);
    }
    interp.set_property(&object, "lastIndex", Value::Int(0))?;
    let units = text.to_units();
    let mut results = Vec::new();
    loop {
        let result = regexp_exec(interp, &Value::Object(object.clone()), &text_value)?;
        let Value::Object(hit) = result else {
            // `null` ends the walk; an empty `A` means the whole match failed.
            break;
        };
        let matched = interp.get_property(&hit, "0")?.unwrap_or(Value::Undefined);
        // `ToString(result[0])`, keeping the code units: a match can *be* half a surrogate
        // pair (`. ` without `u`), and the lossy `String` path turns that half into U+FFFD —
        // `"𠮷".match(/./g)` answered two replacement characters instead of the two halves.
        let matched = interp.checked_to_wtf8(&matched)?;
        let empty = matched.is_empty();
        results.push(interp.string_wtf8(matched));
        if empty {
            // An empty match leaves `lastIndex` where it was, so it is advanced by one
            // position — a code point rather than a unit under `u`.
            let next = interp
                .get_property(&object, "lastIndex")?
                .unwrap_or(Value::Int(0));
            let next = interp.to_js_number(&next)?;
            let next = advance_string_index(&units, next, full_unicode);
            interp.set_property(&object, "lastIndex", Value::Float(next))?;
        }
    }
    if results.is_empty() {
        return Ok(Value::Null);
    }
    Ok(Value::Object(interp.new_array(results)))
}

/// §22.2.7.3 `RegExp.prototype [ @@matchAll ] ( string )`.
///
/// Two things here are easy to get wrong and are both tested by test262:
///
/// * **`lastIndex` is read once, at creation, and shows up as a property *copy*.** The
///   species constructor is handed `(R, flags)` and would therefore carry `R`'s
///   `lastIndex` over, so the value is read here first, coerced with `ToLength`, and set on
///   the *clone* — `this-lastindex-cached.js` asserts that reassigning `R.lastIndex`
///   afterwards changes nothing.
/// * **`Symbol.match` is consulted through `IsRegExp`, not through the internal slot.**
///   `isregexp-called-once.js` installs a counting getter on `RegExp.prototype[@@match]`,
///   so the pattern's regexp-ness has to be probed exactly once.
///
/// Returning `string.matchAll(re)` for a string pattern works because this method exists:
/// the string method is specified to build a `RegExp` and then call *this*. The previous
/// error message ("matchAll needs a global RegExp") pointed the blame at the caller's
/// regexp, which was never the problem.
fn symbol_match_all(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let Some(object) = this.as_object().cloned() else {
        return Err(interp.type_error("Symbol.matchAll called on a non-object"));
    };
    let text = interp.checked_to_wtf8(&arg(args, 0))?;
    // A missing `%RegExp%` means the realm is half-built; `undefined` here would turn that
    // into a confusing "not a constructor" instead of the real problem.
    let default_constructor = match interp.realm.regexp_ctor.clone() {
        Some(constructor) => Value::Object(constructor),
        None => return Err(interp.type_error("the realm has no RegExp constructor")),
    };
    let constructor = interp.species_constructor(&object, default_constructor.clone())?;
    let flags = interp
        .get_property(&object, "flags")?
        .unwrap_or(Value::Undefined);
    let flags = interp.checked_to_string(&flags)?;
    let matcher = interp.construct(
        constructor,
        default_constructor,
        vec![Value::Object(object.clone()), interp.string(flags.clone())],
    )?;
    let Some(matcher) = matcher.as_object().cloned() else {
        return Err(interp.type_error("species constructor did not answer an object"));
    };
    // `IsRegExp` is **not** re-read here. `Construct(C, «R, flags»)` above already ran it
    // (the `RegExp` constructor's step 2) and that is the read `isregexp-called-once` counts;
    // doing it again here made the `@@match` getter fire twice. For the same reason a plain
    // object whose getter throws throws from the constructor — `isregexp-this-throws` passes
    // without a second probe. What is needed locally is only the internal-slot test, to
    // decide whether `lastIndex` belongs on the clone.
    let is_regexp = object.regexp().is_some();
    if is_regexp {
        // §22.2.7.3 MatchAllIterator steps 2.e–2.g. `ToLength` of a `lastIndex` that is an
        // object runs its `valueOf`, which is what `this-lastindex-cached.js` relies on.
        let cached = interp
            .get_property(&object, "lastIndex")?
            .unwrap_or(Value::Undefined);
        let cached = interp.to_js_number(&cached)?;
        let cached = to_length(cached);
        interp.set_property(&matcher, "lastIndex", Value::Float(cached))?;
    }
    // The two flags are read off the **coerced flag string**, not off the clone. A species
    // constructor that returns a regexp with a throwing `global` getter therefore never
    // runs it — `species-regexp-get-global-throws.js` asserts exactly that.
    let global = flags.contains('g');
    let full_unicode = flags.contains('u') || flags.contains('v');
    Ok(new_regexp_string_iterator(
        interp,
        matcher,
        text,
        global,
        full_unicode,
    ))
}

/// `%RegExpStringIteratorPrototype%`, created on first use.
///
/// It is installed lazily rather than at bootstrap because `RegExp` is installed before
/// `Iterator.prototype` exists in some embedders, and because the prototype needs the
/// realm's `%Object.prototype%` only.
fn regexp_string_iterator_proto(interp: &mut Interp<'_>) -> Gc<JsObject> {
    if let Some(proto) = interp.realm.iterator_protos.get(REGEXP_STRING_ITERATOR_TAG) {
        return proto.clone();
    }
    interp.new_iterator_prototype(REGEXP_STRING_ITERATOR_TAG, regexp_string_iterator_next)
}

const REGEXP_STRING_ITERATOR_TAG: &str = "RegExp String Iterator";

/// §22.2.9.1 CreateRegExpStringIterator — the object behind `[@@matchAll]`.
///
/// The state lives under non-enumerable "_"-prefixed properties, the same shape the array
/// iterators use. Two of the four are internal slots and two are the flags that decide how
/// `next` advances, so `Object.keys` on the iterator stays empty either way.
fn new_regexp_string_iterator(
    interp: &mut Interp<'_>,
    matcher: Gc<JsObject>,
    text: crate::value::Wtf8,
    global: bool,
    full_unicode: bool,
) -> Value {
    let proto = regexp_string_iterator_proto(interp);
    let object = interp.new_object(Some(proto));
    // Non-enumerable, so `Object.keys` on the iterator stays `[]` as the reference's does.
    // They are ordinary properties rather than true internal slots, which is the same trade
    // the array iterators make; `next` re-checks `_iterating` is *own*, so an object that
    // merely inherits from an iterator (`Object.create(iterator)`) is still a `TypeError`.
    let hidden = |value: Value| Property {
        value: Some(value),
        writable: true,
        enumerable: false,
        configurable: true,
        ..Property::default()
    };
    object.define("_iterating", hidden(Value::Bool(true)));
    object.define("_matcher", hidden(Value::Object(matcher)));
    object.define("_string", hidden(interp.string_wtf8(text)));
    object.define("_global", hidden(Value::Bool(global)));
    object.define("_fullUnicode", hidden(Value::Bool(full_unicode)));
    Value::Object(object)
}

/// §22.2.9.2.1 `%RegExpStringIteratorPrototype%.next()`.
///
/// Step order matters: the *matcher's* `exec` is looked up **each time** rather than once at
/// creation, so replacing `RegExp.prototype.exec` between two `next` calls is observed.
fn regexp_string_iterator_next(
    interp: &mut Interp<'_>,
    this: Value,
    _args: &[Value],
) -> JsResult<Value> {
    let Some(iterator) = this.as_object().cloned() else {
        return Err(interp.type_error("next called on a non-object"));
    };
    // §22.2.9.2.1 step 3: the slots have to be the object's *own*. A prototype-inherited
    // `_iterating` would let `Object.create(iterator).next()` walk the original's state,
    // which is exactly what `next-missing-internal-slots.js` forbids.
    let iterating = match iterator.own_property("_iterating") {
        Some(property) => property.value.unwrap_or(Value::Undefined),
        None => {
            return Err(
                interp.type_error("next called on an object that is not a RegExp String Iterator")
            );
        }
    };
    if !iterating.to_boolean() {
        return Ok(iterator_result(interp, Value::Undefined, true));
    }
    let matcher = interp
        .get_property(&iterator, "_matcher")?
        .unwrap_or(Value::Undefined);
    let text = interp
        .get_property(&iterator, "_string")?
        .unwrap_or(Value::Undefined);
    let global = interp
        .get_property(&iterator, "_global")?
        .unwrap_or(Value::Undefined)
        .to_boolean();
    let full_unicode = interp
        .get_property(&iterator, "_fullUnicode")?
        .unwrap_or(Value::Undefined)
        .to_boolean();
    let match_value = regexp_exec(interp, &matcher, &text)?;
    if matches!(match_value, Value::Null) {
        iterator.define_data("_iterating", Value::Bool(false));
        return Ok(iterator_result(interp, Value::Undefined, true));
    }
    if !global {
        iterator.define_data("_iterating", Value::Bool(false));
        return Ok(iterator_result(interp, match_value, false));
    }
    // "Global" means: match again from the advanced `lastIndex`. An empty match would leave
    // it where it is, so it is pushed forward by one — and the units it moves are code
    // points under `u`, which is what `u-advance-after-empty.js` checks on an astral pair.
    let empty = {
        let Value::Object(ref hit) = match_value else {
            return Err(interp.type_error("exec did not answer an array"));
        };
        let first = interp.get_property(hit, "0")?.unwrap_or(Value::Undefined);
        interp.to_js_string(&first)?.is_empty()
    };
    if empty {
        let matcher_object = match matcher.as_object() {
            Some(object) => object.clone(),
            None => return Err(interp.type_error("exec did not answer an array")),
        };
        let index = interp
            .get_property(&matcher_object, "lastIndex")?
            .unwrap_or(Value::Int(0));
        let index = interp.to_js_number(&index)?;
        let units = text
            .as_wtf8()
            .map(|text| text.to_units())
            .unwrap_or_default();
        let next = advance_string_index(&units, index, full_unicode);
        interp.set_property(&matcher_object, "lastIndex", Value::Float(next))?;
    }
    Ok(iterator_result(interp, match_value, false))
}

/// §7.1.20 `ToLength`, as a number rather than a `usize`.
///
/// Kept local rather than reusing `array`'s, which clamps to `MAX_SAFE_INTEGER` as an index
/// type: `lastIndex` is stored back into the regexp, so the exact double has to survive.
fn to_length(value: f64) -> f64 {
    if value.is_nan() || value <= 0.0 {
        return 0.0;
    }
    value.trunc().min(9_007_199_254_740_991.0)
}

/// §22.2.9.2.1 `AdvanceStringIndex(S, index, unicode)`.
///
/// The stride is one *unit* unless `fullUnicode`, in which case an index that lands on the
/// lead half of a surrogate pair skips both halves. `index + 1` is returned unchanged past
/// the end, so the caller's next `exec` fails and the iteration stops.
fn advance_string_index(units: &[u16], index: f64, unicode: bool) -> f64 {
    if !unicode || !index.is_finite() || index < 0.0 {
        return index + 1.0;
    }
    let start = index as usize;
    let Some(&lead) = units.get(start) else {
        return index + 1.0;
    };
    if !(0xD800..=0xDBFF).contains(&lead) {
        return index + 1.0;
    }
    match units.get(start + 1) {
        Some(&trail) if (0xDC00..=0xDFFF).contains(&trail) => index + 2.0,
        _ => index + 1.0,
    }
}

/// §7.4.14 `RegExpExec(R, S)` — the *generic* one, which is what every `@@` method uses.
///
/// A pattern whose `exec` is callable gets to answer for itself (that is how a subclass or a
/// duck-typed matcher participates), and only an `undefined` answer falls back to the
/// builtin. Requiring the result to be an object or `null` is a real check, not a formality:
/// `exec-return-type-invalid.js` asserts the `TypeError`.
pub(crate) fn regexp_exec(
    interp: &mut Interp<'_>,
    matcher: &Value,
    text: &Value,
) -> JsResult<Value> {
    let exec_fn = match matcher.as_object() {
        Some(object) => interp.get_property(object, "exec")?,
        None => None,
    };
    if let Some(exec_fn) = exec_fn
        && matches!(&exec_fn, Value::Object(function) if function.is_callable())
    {
        let result = interp.call_value(exec_fn, matcher.clone(), vec![text.clone()])?;
        return match result {
            Value::Object(_) | Value::Null => Ok(result),
            _ => Err(interp.type_error("exec must answer an object or null")),
        };
    }
    let Some(object) = matcher.as_object().cloned() else {
        return Err(interp.type_error("method called on a non-RegExp"));
    };
    let text = interp.checked_to_wtf8(text)?;
    exec_on(interp, &object, &text)
}

/// An `{value, done}` iterator result, created with the realm's `%Object.prototype%`.
fn iterator_result(interp: &mut Interp<'_>, value: Value, done: bool) -> Value {
    let proto = interp.realm.object_proto.clone();
    let result = interp.new_object(Some(proto));
    result.define_data("value", value);
    result.define_data("done", Value::Bool(done));
    Value::Object(result)
}

/// `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.
///
/// §22.2.6.14. This is the last of the `Symbol.*` family to stop scanning with the compiled
/// matcher directly, and it matters for the same reason `@@replace` did: a subclass or a
/// duck-typed object has to be able to answer for itself.
///
/// ```js
/// var r = /a/; r.exec = () => null; "abc".split(r)   // ["abc"], and exec ran
/// ```
///
/// Three details are easy to get wrong and each one has cases behind it:
///
/// * **`flags` gets a `y` appended** unless it already has one (step 8). The clone is
///   sticky so that `exec` anchors at `lastIndex`; without it a pattern without `g` would
///   match from anywhere and the bookkeeping below silently produces the wrong pieces.
/// * **`limit` is `ToUint32`, not a clamp.** `split(re, -1)` keeps everything because
///   `ToUint32(-1)` is 4294967295, while `split(re, 2**32)` is the empty array. The
///   previous code treated negatives as zero, which was wrong for exactly those inputs.
/// * **the scan resumes at `p`, not at the end of the match.** Only `p` moves; getting past
///   a zero-width match has to go through `AdvanceStringIndex`, which is the `e == p` branch.
fn symbol_split(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let Some(object) = this.as_object().cloned() else {
        return Err(interp.type_error("Symbol.split called on a non-object"));
    };
    // 4. `ToString(string)` comes before anything else is read off the regexp.
    let text = interp.checked_to_wtf8(&arg(args, 0))?;
    let units = text.to_units();
    // 5. `SpeciesConstructor(rx, %RegExp%)`.
    let default_constructor = match interp.realm.regexp_ctor.clone() {
        Some(constructor) => Value::Object(constructor),
        None => return Err(interp.type_error("the realm has no RegExp constructor")),
    };
    let constructor = interp.species_constructor(&object, default_constructor.clone())?;
    // 6-7. `flags` is `ToString(Get(rx, "flags"))` — the property, not the pattern's slots.
    let flags = interp
        .get_property(&object, "flags")?
        .unwrap_or(Value::Undefined);
    let flags = interp.checked_to_string(&flags)?;
    // 8. `unicodeMatching` is decided from the `flags` *string*, and `y` is appended when
    // absent so that `exec` anchors at `lastIndex`.
    let unicode_matching = flags.contains('u') || flags.contains('v');
    let sticky_flags = if flags.contains('y') {
        flags.clone()
    } else {
        format!("{flags}y")
    };
    // 9. `Construct(C, «rx, flags»)`. **`newTarget` is `C`, not `%RegExp%`**: passing the
    // default here made the clone a plain `RegExp` even when `C` was a subclass, so a
    // subclass's `exec` on its prototype was never reached — `@@split` then scanned with the
    // builtin matcher and quietly produced the right pieces for the wrong reason. Every
    // clone-routing probe (`split:exec-is-taken-from-...`) was blind to it until `exec` was
    // observed at the prototype rather than on the receiver.
    let splitter = interp.construct(
        constructor.clone(),
        constructor,
        vec![Value::Object(object), interp.string(sticky_flags)],
    )?;
    // `SpeciesCreate` answering a primitive would be a `TypeError` further down (the clone
    // has to carry a `lastIndex`); failing here names the real cause.
    let Some(splitter_object) = splitter.as_object().cloned() else {
        return Err(interp.type_error("species constructor did not answer an object"));
    };
    // 11-12. `lim` is `ToUint32(limit)`; a zero limit is the empty array *before* any match.
    let limit = match arg(args, 1) {
        Value::Undefined => u32::MAX,
        other => Value::Float(interp.to_js_number(&other)?).to_uint32(),
    };
    let mut parts: Vec<Value> = Vec::new();
    if limit == 0 {
        return Ok(Value::Object(interp.new_array(parts)));
    }
    let size = units.len();
    // 13. An empty subject still asks `exec` once — `"".split(/x/)` is `[""]`, but
    // `"".split(/(?:)/)` is `[]` because that match *succeeds*, so the algorithm returns
    // the (still empty) array instead of falling through to the tail.
    if size == 0 {
        let subject = interp.string_wtf8(text.clone());
        let result = regexp_exec(interp, &splitter, &subject)?;
        if matches!(result, Value::Null) {
            parts.push(interp.string_wtf8(text));
        }
        return Ok(Value::Object(interp.new_array(parts)));
    }
    let mut last = 0usize;
    let mut scan = 0usize;
    // 14. `scan` is `q`, the search position; `last` is `p`, the end of the previous match.
    while scan < size {
        // 14.a. `lastIndex` is written before every `exec`, through the property system so
        // that a clone with a setter (or a subclass) observes the write.
        interp.set_property(&splitter_object, "lastIndex", Value::Int(scan as i32))?;
        let subject = interp.string_wtf8(text.clone());
        let result = regexp_exec(interp, &splitter, &subject)?;
        let Value::Object(hit) = &result else {
            // 14.b. No match here: step the search position and try again.
            scan = advance_string_index(&units, scan as f64, unicode_matching) as usize;
            continue;
        };
        // 14.c. `e` is `ToLength(Get(splitter, "lastIndex"))`, clamped to the subject.
        let end = interp
            .get_property(&splitter_object, "lastIndex")?
            .unwrap_or(Value::Undefined);
        let end = to_length(interp.to_js_number(&end)?);
        let end = if end > size as f64 {
            size
        } else {
            end as usize
        };
        if end == last {
            // 14.c.iii. A zero-width match at `p` cannot split anything; stepping is what
            // keeps the loop finite.
            scan = advance_string_index(&units, scan as f64, unicode_matching) as usize;
            continue;
        }
        // 14.c.iv-v. Accept the piece before the match, then every capture group as-is (a
        // group that did not participate stays `undefined`).
        parts.push(interp.string_wtf8(crate::value::Wtf8::from_units(&units[last..scan])));
        if parts.len() as u32 == limit {
            return Ok(Value::Object(interp.new_array(parts)));
        }
        last = end;
        // 14.c.vi is `LengthOfArrayLike(z)` — the `length` *property*, so a hand-made `exec`
        // result is honoured exactly like the builtin array.
        let length = interp
            .get_property(hit, "length")?
            .unwrap_or(Value::Undefined);
        let length = to_length(interp.to_js_number(&length)?) as usize;
        for i in 1..length {
            let capture = interp
                .get_property(hit, &i.to_string())?
                .unwrap_or(Value::Undefined);
            parts.push(capture);
            if parts.len() as u32 == limit {
                return Ok(Value::Object(interp.new_array(parts)));
            }
        }
        // 14.c.vii. The search resumes at `p`, **not** at the end of the match.
        scan = last;
    }
    // 15. The tail, clamped in case `lastIndex` ran past the end of the subject.
    let last = last.min(size);
    parts.push(interp.string_wtf8(crate::value::Wtf8::from_units(&units[last..])));
    Ok(Value::Object(interp.new_array(parts)))
}

/// `RegExp.prototype[Symbol.replace]` — §22.2.6.11, the half `String.prototype.replace` and
/// `replaceAll` delegate to.
///
/// **Every match comes from `RegExpExec(R, S)`**, never from the internal matcher. That is
/// what lets a subclass or a duck-typed object answer for itself:
///
/// ```js
/// var r = /a/; r.exec = () => null; "abc".replace(r, "X")   // "abc", and exec ran once
/// ```
///
/// This function used to scan with the compiled matcher directly, so the observable
/// contract was wrong in three ways at once — `exec` was never called, `lastIndex` was
/// never written back, and `unicode`/`global` were read off the pattern's flags instead of
/// off the properties. Forty of the seventy `Symbol.replace` test262 cases failed on
/// exactly those three.
///
/// The step order is load-bearing and matches the spec literally, because the cases assert
/// it: `ToString(string)` (3), `IsCallable`+`ToString` of the replacement (5–7, so a bad
/// replacement throws *before* any property of the regexp is touched), `flags` (9),
/// `global` (10), and only then `unicode` (11.c) — which is read **only** in the global
/// branch, so a non-global regexp with a throwing `unicode` getter does not throw.
fn symbol_replace(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let Some(object) = this.as_object().cloned() else {
        return Err(interp.type_error("Symbol.replace called on a non-object"));
    };
    let matcher = Value::Object(object.clone());
    // 3. `ToString(string)`.
    let text = interp.checked_to_wtf8(&arg(args, 0))?;
    let units = text.to_units();
    // 5–7. A functional replacement is used as-is; anything else is coerced *now*, before the
    // regexp's own properties are read.
    let replacement = arg(args, 1);
    let functional = matches!(&replacement, Value::Object(o) if o.is_callable());
    let template = if functional {
        None
    } else {
        Some(interp.checked_to_wtf8(&replacement)?)
    };
    // 9. `ToString(Get(rx, "flags"))`. Read even when the value is later unused, because the
    // getter's side effects (and its throw) are observable.
    let flags = interp
        .get_property(&object, "flags")?
        .unwrap_or(Value::Undefined);
    let flags = interp.checked_to_string(&flags)?;
    // 10. `global` comes from the property, not `flags`. A regexp whose `global` was
    // redefined must follow the property — `coerce-global.js` walks `undefined`, `null`, `0`,
    // `""` and `NaN`, all of which are falsy but are not the same as "no `g` flag".
    let global = interp
        .get_property(&object, "global")?
        .unwrap_or(Value::Undefined)
        .to_boolean();
    // 11.a–11.d. `lastIndex` is zeroed before the loop, and `fullUnicode` is read from
    // `unicode` — only on this path. `v` counts as unicode for `AdvanceStringIndex`.
    let mut full_unicode = false;
    if global {
        let unicode = interp
            .get_property(&object, "unicode")?
            .unwrap_or(Value::Undefined)
            .to_boolean();
        let unicode_sets = if unicode {
            false
        } else {
            // §22.2.6.11 step 11.c reads `unicodeSets` only when `unicode` is false, and only
            // when the pattern has the `v` flag; `flags` already tells us that.
            flags.contains('v')
        };
        full_unicode = unicode || unicode_sets;
        interp.set_property(&object, "lastIndex", Value::Int(0))?;
    }
    // 12–13. Collect the matches.
    //
    // Each entry is the `RegExpExec` result as a *value* plus the pieces taken out of it, so
    // an `exec` that answers a plain object with a hand-made `index` is honoured exactly like
    // the builtin's array.
    struct Hit {
        result: Value,
        /// `ToString(result[0])`, in code units.
        matched: Vec<u16>,
        /// `ToIntegerOrInfinity(result.index)`, clamped into the string.
        position: usize,
        /// The capture values as `RegExpExec` reported them, still uncoerced.
        captures: Vec<Value>,
    }
    let mut hits: Vec<Hit> = Vec::new();
    loop {
        let subject = interp.string_wtf8(text.clone());
        let result = regexp_exec(interp, &matcher, &subject)?;
        let Value::Object(hit) = &result else {
            break;
        };
        let zero = interp.get_property(hit, "0")?.unwrap_or(Value::Undefined);
        let matched = interp.checked_to_wtf8(&zero)?.to_units();
        let index = interp
            .get_property(hit, "index")?
            .unwrap_or(Value::Undefined);
        let index = interp.to_js_number(&index)?;
        // A `lastIndex`/`index` past the end has no characters before it, but the text still
        // appends to the end rather than panicking — the spec's `ToLength` clamps it.
        let position = to_length(index) as usize;
        // §22.2.6.11 step 14.b.i is `LengthOfArrayLike(result)`, which reads the `length`
        // **property** — not the internal array length. A hand-made `exec` result is a plain
        // object, so `array_length()` answered `None` and every group vanished; a group whose
        // `toString` throws then never threw.
        let length = interp
            .get_property(hit, "length")?
            .unwrap_or(Value::Undefined);
        let length = to_length(interp.to_js_number(&length)?) as usize;
        let mut captures = Vec::with_capacity(length.saturating_sub(1));
        for i in 1..length {
            captures.push(
                interp
                    .get_property(hit, &i.to_string())?
                    .unwrap_or(Value::Undefined),
            );
        }
        hits.push(Hit {
            result,
            matched,
            position: position.min(units.len()),
            captures,
        });
        if !global {
            break;
        }
        // `matched` is empty exactly when `result[0]` is the empty string; then `lastIndex`
        // has to advance or the loop cannot end.
        if !hits.last().is_some_and(|h| h.matched.is_empty()) {
            continue;
        }
        let this_index = interp
            .get_property(&object, "lastIndex")?
            .unwrap_or(Value::Int(0));
        let this_index = interp.to_js_number(&this_index)?;
        let next = advance_string_index(&units, to_length(this_index), full_unicode);
        interp.set_property(&object, "lastIndex", Value::Float(next))?;
    }
    if hits.is_empty() {
        return Ok(interp.string_wtf8(text));
    }
    // 14. Assemble.
    let mut out: Vec<u16> = Vec::new();
    let mut next_source_position = 0usize;
    for hit in &hits {
        let start = next_source_position.max(hit.position);
        if start > units.len() {
            break;
        }
        out.extend_from_slice(&units[next_source_position..start]);
        let substituted = substitute_generic(
            interp,
            &replacement,
            template.as_ref(),
            &hit.result,
            &hit.matched,
            &hit.captures,
            &units,
            start,
        )?;
        out.extend_from_slice(&substituted);
        next_source_position = start + hit.matched.len();
    }
    if next_source_position < units.len() {
        out.extend_from_slice(&units[next_source_position..]);
    }
    Ok(interp.string_wtf8(crate::value::Wtf8::from_units(&out)))
}

/// Expand one match of `RegExp.prototype[@@replace]`.
///
/// Every capture is a **value** out of the `RegExpExec` result, `ToString`-ed here, rather
/// than a slice this function takes itself — an `exec` that returns `{ 0: ..., 1: { toString
/// throws } }` is observable, and `result-coerce-capture-err.js` asserts the throw.
#[allow(clippy::too_many_arguments)]
fn substitute_generic(
    interp: &mut Interp<'_>,
    replacement: &Value,
    template: Option<&crate::value::Wtf8>,
    result: &Value,
    matched: &[u16],
    captures: &[Value],
    units: &[u16],
    position: usize,
) -> JsResult<Vec<u16>> {
    // 14.c. A callable replacement gets the match, every group, the position and the string.
    if let Value::Object(function) = replacement
        && function.is_callable()
    {
        let mut args: Vec<Value> =
            vec![interp.string_wtf8(crate::value::Wtf8::from_units(matched))];
        args.extend(captures.iter().cloned());
        args.push(Value::Int(position as i32));
        args.push(interp.string_wtf8(crate::value::Wtf8::from_units(units)));
        // 14.c.ix: the *result* of the call is `ToString`-ed, keeping any unpaired surrogate
        // it produced.
        let outcome = interp.call_value(Value::Object(function.clone()), Value::Undefined, args)?;
        return Ok(interp.checked_to_wtf8(&outcome)?.to_units());
    }
    let Some(template) = template else {
        // A non-callable replacement was coerced by the caller; reaching here would mean the
        // two decisions disagreed.
        return Err(interp.type_error("replacement was neither callable nor coerced"));
    };
    // 14.d.ii: `namedCaptures` is `Get(result, "groups")`, and `undefined` means "no named
    // groups at all", which is what makes `$<y>` literal rather than empty.
    let named_captures = match result.as_object() {
        Some(hit) => interp
            .get_property(hit, "groups")?
            .unwrap_or(Value::Undefined),
        None => Value::Undefined,
    };
    let mut named: Vec<(String, Vec<u16>)> = Vec::new();
    let mut has_names = false;
    if let Value::Object(groups) = &named_captures {
        has_names = true;
        // The property *names* of the groups object, in insertion order, are the group names.
        for key in groups.own_property_keys() {
            let Some(name) = key.as_str().map(str::to_string) else {
                continue;
            };
            let value = interp
                .get_property(groups, &name)?
                .unwrap_or(Value::Undefined);
            // §22.1.3.19.1 step 2.c.d: an **undefined** capture is the *empty* string, not
            // `"undefined"`. The property exists on the groups object either way, so this is
            // a value test, not a presence test — `string-replace-undefined.js` walks a
            // pattern whose `thd` group never participates.
            let units = match value {
                Value::Undefined => Vec::new(),
                other => interp.checked_to_wtf8(&other)?.to_units(),
            };
            named.push((name, units));
        }
    }
    let mut owned: Vec<Option<Vec<u16>>> = Vec::with_capacity(captures.len() + 1);
    owned.push(Some(matched.to_vec()));
    for capture in captures {
        owned.push(match capture {
            Value::Undefined => None,
            other => Some(interp.checked_to_wtf8(other)?.to_units()),
        });
    }
    let mut out: Vec<u16> = Vec::new();
    get_substitution(
        &mut out,
        template,
        &Substitution {
            input: units,
            position,
            match_len: matched.len(),
            captures: &owned,
            names: has_names.then_some(named.as_slice()),
        },
    );
    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()
}