quickjs-pure 0.17.16

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
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
//! `String` and `String.prototype`.
//!
//! String indexing and `length` count UTF-16 code units, not characters, because
//! that is what a script observes: `"🐱".length` is `2`. The methods here work on
//! `char`s where the spec is character-based and on code units where it is not, and
//! the two places that difference shows up (`charAt`/`charCodeAt` versus
//! `codePointAt`) are called out where they occur.

use crate::builtins::substitution::{Substitution, get_substitution};
use crate::builtins::{arg, arg_integer_or, define_method};
use crate::interp::{Interp, JsResult, WellKnown};
use crate::normalize::{Form, normalize as normalize_text};
use crate::object::{JsObject, Property};
use crate::value::Value;
use js_gc::Gc;

/// Install `String` and its prototype methods.
/// `%String.prototype%[@@iterator]`.
fn string_iterator(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    crate::builtins::array::string_iterator(interp, this)
}

pub fn install(interp: &mut Interp<'_>, string_proto: &Gc<JsObject>) {
    for (name, length, func) in [
        ("charAt", 1, char_at as crate::object::NativeFn),
        ("charCodeAt", 1, char_code_at),
        ("codePointAt", 1, code_point_at),
        ("indexOf", 1, index_of),
        ("lastIndexOf", 1, last_index_of),
        ("includes", 1, includes),
        ("startsWith", 1, starts_with),
        ("endsWith", 1, ends_with),
        ("slice", 2, slice),
        ("substring", 2, substring),
        ("substr", 2, substr),
        ("split", 2, split),
        ("match", 1, match_method),
        ("matchAll", 1, match_all),
        ("search", 1, search),
        ("concat", 1, concat),
        ("toUpperCase", 0, to_upper_case),
        ("toLowerCase", 0, to_lower_case),
        ("normalize", 0, normalize),
        ("isWellFormed", 0, is_well_formed),
        ("toWellFormed", 0, to_well_formed),
        ("trim", 0, trim),
        ("trimStart", 0, trim_start),
        ("trimEnd", 0, trim_end),
        ("repeat", 1, repeat),
        ("padStart", 1, pad_start),
        ("padEnd", 1, pad_end),
        ("toString", 0, to_string),
        ("valueOf", 0, to_string),
        ("at", 1, at),
        ("replace", 2, replace),
        ("replaceAll", 2, replace_all),
        ("localeCompare", 1, locale_compare),
        // Locale-insensitive by specification: §22.1.3.24 says the result "must be derived
        // according to the locale-insensitive case mappings in the Unicode Character
        // Database", which is exactly what `toLowerCase`/`toUpperCase` do here. Taking the
        // locale argument and ignoring it is the required behaviour, not a shortcut — the
        // reference ignores it too (`"I".toLocaleLowerCase("tr")` is `"i"` there).
        //
        // These two were missing outright, which turned 52 test262 cases into
        // `TypeError: undefined is not a function`. Found by `scripts/builtin-surface.py`.
        ("toLocaleLowerCase", 0, to_lower_case),
        ("toLocaleUpperCase", 0, to_upper_case),
        // Annex B §B.2.3.2 — no test262 coverage at all, so they are here for parity with
        // the reference's surface rather than to move a number.
        ("anchor", 1, anchor),
        ("big", 1, big),
        ("blink", 1, blink),
        ("bold", 1, bold),
        ("fixed", 1, fixed),
        ("fontcolor", 1, fontcolor),
        ("fontsize", 1, fontsize),
        ("italics", 1, italics),
        ("link", 1, link),
        ("small", 1, small),
        ("strike", 1, strike),
        ("sub", 1, sub),
        ("sup", 1, sup),
    ] {
        define_method(string_proto, name, length, func, interp);
    }

    // Annex B's `trimLeft`/`trimRight` are the *same function objects* as
    // `trimStart`/`trimEnd` (§22.1.3.31: "the same function object as"), so they are
    // aliased from what was just defined rather than defined again — `define_method`
    // makes a fresh function per name, which would give `===` false.
    for (alias, original) in [("trimLeft", "trimStart"), ("trimRight", "trimEnd")] {
        if let Some(property) = string_proto.own_property(original) {
            string_proto.define(alias, property);
        }
    }

    // §22.1.3: `String.prototype` has an own `length` of 0, attributes
    // { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }. Without it
    // `String.prototype.length` fell through to the boxed-string getter and answered
    // `undefined`. Configurable is the one attribute the spec sets to true here, and the
    // reference agrees — checked, because "all three false" is the reflex.
    string_proto.define("length", Property::name_or_length(Value::Int(0)));

    // `String.prototype[Symbol.iterator]` walks the UTF-16 code units. The array iterator
    // already does exactly that when handed a string primitive — see `element_at` — so the
    // machinery is shared rather than reimplemented, but the *prototype* must not be:
    // `%StringIteratorPrototype%` is a distinct object whose `@@toStringTag` reads
    // `"String Iterator"`. Sharing `Array.prototype.values` outright made
    // `Object.getPrototypeOf(""[Symbol.iterator]())` literally
    // `%ArrayIteratorPrototype%`, so a string iterator reported `[object Array Iterator]`
    // and `StringIteratorPrototype/Symbol.toStringTag.js` had nothing to point at.
    let string_iterator = interp.new_native("[Symbol.iterator]", 0, string_iterator);
    let key = interp
        .realm
        .well_known_key(crate::interp::WellKnown::Iterator);
    string_proto.define_key(
        &key,
        Property::with_attributes(Value::Object(string_iterator), true, false),
    );

    let constructor = interp.new_native_constructor("String", 1, constructor);
    constructor.define(
        "prototype",
        Property::with_attributes(Value::Object(string_proto.clone()), false, false),
    );
    string_proto.define(
        "constructor",
        Property::with_attributes(Value::Object(constructor.clone()), true, false),
    );
    for (name, length, func) in [
        ("fromCharCode", 1, from_char_code as crate::object::NativeFn),
        ("fromCodePoint", 1, from_code_point),
        ("raw", 1, raw as crate::object::NativeFn),
    ] {
        define_method(&constructor, name, length, func, interp);
    }
    let global = interp.realm.global.clone();
    global.define(
        "String",
        Property::with_attributes(Value::Object(constructor), true, false),
    );
}

fn constructor(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    // `String(x)` converts; `new String(x)` boxes. The constructor is reached both
    // ways, and the difference is whether `this` is an object.
    //
    // The conversion has to be `ToString`, not the built-in's own `to_js_string`:
    // an object argument goes through `ToPrimitive`, so `String(err)` gives
    // `"Error: m"` — `Error.prototype.toString` — instead of `[object Object]`.
    // §22.1.1.1 steps 2–3: with no argument the answer is `""`; with a **Symbol
    // primitive** it is `SymbolDescriptiveString`; otherwise `ToString`, which means an
    // `Object(Symbol())` is a `TypeError` because its `ToPrimitive` yields the symbol
    // (`String/symbol-wrapping`, `indexOf/searchstring-tostring-errors`).
    let text = match args.first() {
        None => String::new(),
        Some(Value::Symbol(symbol)) => {
            // §22.1.1.1 step 4: the symbolic string is only for the *call* form. With a
            // `new.target` a Symbol argument is a `TypeError` (`String/symbol-wrapping`
            // asserts `new String(Symbol(…))` throws while `String(Symbol(…))` does not).
            if matches!(this, Value::Object(_)) {
                return Err(interp.type_error("cannot convert a Symbol to a string"));
            }
            match symbol.description() {
                Some(text) => format!("Symbol({text})"),
                None => "Symbol()".to_string(),
            }
        }
        Some(value) => interp.to_string_strict(value)?,
    };
    let value = interp.string(text);
    // `new String(x)` boxes: the receiver is a String *exotic* object, so it needs the
    // text itself plus the `length` and index properties described in §10.4.3.4.
    // Filling only `_value` left `new String("ab").length` `undefined` and made every
    // `Array.prototype` method called on a box see an array-like of length 0.
    if let (Value::Object(object), Value::String(text)) = (&this, &value) {
        interp.init_string_wrapper(object, text);
        return Ok(this);
    }
    Ok(value)
}

/// `String.raw(template, …values)`.
///
/// The leading argument is the call site's template object, and the *raw* chunks are the
/// source text before escape processing — so `String.raw`a\tb`` keeps the backslash and
/// the `t`. A substitution is inserted verbatim, with no `ToString` beyond the one the
/// concatenation does.
fn raw(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    let template = arg(args, 0);
    // `ToObject` refuses `undefined`/`null`, which is what makes `String.raw()` throw.
    let chunks = interp.read_field(&template, "raw")?;
    // §22.1.2.4 step 4: `? ToLength(? Get(raw, "length"))` — a Symbol there is a
    // `TypeError` (`template-length-is-symbol-throws`), and `to_number` answered `NaN`.
    let raw_length = interp.read_field(&chunks, "length")?;
    let length = interp.to_js_number(&raw_length)?;
    let length = if length.is_nan() || length <= 0.0 {
        0
    } else {
        length.min(9_007_199_254_740_991.0) as usize
    };
    // The pieces are **code units**, not a `String`: `String.raw` keeps a CRLF exactly as
    // written in the template, and the result must also keep an unpaired surrogate intact
    // (`raw/special-characters`).
    let mut units: Vec<u16> = Vec::new();
    for index in 0..length {
        let chunk = interp.read_field(&chunks, &index.to_string())?;
        units.extend_from_slice(&interp.checked_to_wtf8(&chunk)?.to_units());
        if index + 1 < length
            && let Some(value) = args.get(index + 1)
        {
            // A Symbol substitution is a `TypeError` (`returns-abrupt-from-substitution-symbol`).
            units.extend_from_slice(&interp.checked_to_wtf8(value)?.to_units());
        }
    }
    Ok(interp.string_wtf8(crate::value::Wtf8::from_units(&units)))
}

fn from_char_code(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    // §22.1.2.1 step 3 is `ToUint16(ToNumber(next))`, and each half is observable:
    // `ToNumber` runs `ToPrimitive` (so a throwing `valueOf` propagates, and a BigInt is a
    // `TypeError`), and `ToUint16` is a **modulo 2^16**, which is why `Infinity` becomes
    // `0` rather than `65535` — `as i64` saturated it (`fromCharCode/S9.7_A1`).
    let mut units: Vec<u16> = Vec::with_capacity(args.len());
    for value in args {
        units.push(to_uint16(interp, value)?);
    }
    // Not `String::from_utf16_lossy`: a unit with no partner is a legal JS string, and
    // replacing it with U+FFFD is exactly the bug this representation exists to avoid.
    Ok(interp.string_wtf8(crate::value::Wtf8::from_units(&units)))
}

fn from_code_point(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    let mut units = Vec::with_capacity(args.len());
    for value in args {
        // §22.1.2.2 step 4.a: `? ToNumber(next)` first — a Symbol is a `TypeError` *before*
        // the range check can answer a `RangeError` (`argument-is-Symbol`), and a throwing
        // `valueOf` propagates (`argument-not-coercible`).
        let code = interp.to_js_number(value)?;
        // Step 4.c: an integral value in range. A fraction is a `RangeError`
        // (`argument-is-not-integer`), not a truncation.
        if !(0.0..=0x10ffff as f64).contains(&code) || code.fract() != 0.0 {
            return Err(interp.range_error("invalid code point"));
        }
        let code = code as u32;
        // A code point in the surrogate range is not a `char`, but it is a legal argument
        // here: the spec's only rejection is the range check above.
        if (0xd800..0xe000).contains(&code) {
            units.push(code as u16);
        } else {
            let mut buffer = [0u16; 2];
            units.extend_from_slice(
                char::from_u32(code)
                    .unwrap_or('\u{fffd}')
                    .encode_utf16(&mut buffer),
            );
        }
    }
    Ok(interp.string_wtf8(crate::value::Wtf8::from_units(&units)))
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/// The receiver text, or a `TypeError` when `this` is neither a string nor a box.
/// The text a string method operates on: `RequireObjectCoercible` then `ToString`.
///
/// This is **not** a brand check. §22.1's methods all say
///
/// ```text
/// 1. Let O be ? RequireObjectCoercible(this value).
/// 2. Let S be ? ToString(O).
/// ```
///
/// so `String.prototype.trim.call(123)` is `"123"` and `.call({toString(){return " a "}})`
/// trims that object. Only `toString` and `valueOf` do `thisStringValue`, and they are the
/// two methods that do *not* come through here. Treating every method as a brand check made
/// 116 test262 cases fail with `TypeError: String method on a non-string`.
fn text_of(interp: &mut Interp<'_>, this: &Value) -> JsResult<String> {
    Ok(require_string(interp, this)?.to_string_lossy().into_owned())
}

/// The receiver's code units without flattening an unpaired surrogate.
///
/// The "at" family indexes code units, so it must not read through a lossy `String`: a
/// `0xFFFD` where the string holds `0xD800` would give wrong indices.
fn wtf8_of(interp: &mut Interp<'_>, this: &Value) -> JsResult<crate::value::Wtf8> {
    Ok(require_string(interp, this)?.wtf8().clone())
}

/// `RequireObjectCoercible(this)` followed by `ToString`, as the WTF-8 form.
///
/// `null` and `undefined` are refused; everything else converts, including an object whose
/// `toString`/`valueOf` answers something else. A Symbol has no string form, so it is a
/// `TypeError` too — that is `ToString`'s own rule, not a brand check.
fn require_string(
    interp: &mut Interp<'_>,
    this: &Value,
) -> JsResult<js_gc::Gc<crate::value::JsString>> {
    if matches!(this, Value::Undefined | Value::Null) {
        // `RequireObjectCoercible`'s message names the receiver, and both spellings are
        // compared verbatim by test262.
        let what = if matches!(this, Value::Null) {
            "null"
        } else {
            "undefined"
        };
        return Err(interp.type_error(format!("cannot convert {what} to a string")));
    }
    // A primitive string needs no conversion, so keep the object and its cached units.
    if let Value::String(text) = this {
        return Ok(text.clone());
    }
    // A boxed string converts through `ToPrimitive`, which finds `_value` through
    // `toString` — the same path `String(Object("ab"))` takes — so no special case.
    let text = interp.checked_to_wtf8(this)?;
    Ok(js_gc::Gc::new(
        interp.heap,
        crate::value::JsString::from_wtf8(text),
    ))
}

/// The receiver's string object, so a caller can use its cached code units.
///
/// Only the two brand-checking methods use this: `String.prototype.toString` and
/// `valueOf` both run `thisStringValue`, which refuses anything whose `_value` is not
/// already a string. `String.prototype.toString.call(123)` is a `TypeError`, unlike
/// `String.prototype.trim.call(123)`.
fn string_object(
    interp: &mut Interp<'_>,
    this: &Value,
) -> Result<js_gc::Gc<crate::value::JsString>, crate::interp::Signal> {
    match this {
        Value::String(text) => Ok(text.clone()),
        // A boxed string carries the primitive in `_value`.
        Value::Object(object) => match interp.internal_get(object, "_value") {
            Some(Value::String(text)) => Ok(text),
            // `ToString(this)`, **not** a brand check. `charCodeAt` and the rest of
            // §22.1.3 are generic: `String.prototype.charCodeAt.call({toString(){throw e}})`
            // has to run that `toString` and report *its* error, which
            // `S15.5.4.5_A4` asserts character by character. A brand check here answered
            // "String method on a non-string" for every one of the five cases.
            _ => generic_string(interp, this),
        },
        _ => generic_string(interp, this),
    }
}

/// `RequireObjectCoercible(this)` then `ToString(this)`.
fn generic_string(
    interp: &mut Interp<'_>,
    this: &Value,
) -> Result<js_gc::Gc<crate::value::JsString>, crate::interp::Signal> {
    if matches!(this, Value::Undefined | Value::Null) {
        return Err(interp.type_error("String method called on null or undefined"));
    }
    let text = interp.checked_to_wtf8(this)?;
    Ok(js_gc::Gc::new(
        interp.heap,
        crate::value::JsString::from_wtf8(text),
    ))
}

/// The UTF-16 code units of `text`, which is what index arithmetic counts.
fn units(text: &crate::value::Wtf8) -> Vec<u16> {
    text.to_units()
}

/// Rebuild a string from code units, keeping unpaired surrogates intact.
fn from_units(units: &[u16]) -> crate::value::Wtf8 {
    crate::value::Wtf8::from_units(units)
}

/// Normalise a possibly negative start/end index for a code-unit range.
fn clamp(index: f64, length: usize) -> usize {
    if index.is_nan() {
        return 0;
    }
    if index < 0.0 {
        let from_end = length as f64 + index;
        if from_end < 0.0 { 0 } else { from_end as usize }
    } else if index > length as f64 {
        length
    } else {
        index as usize
    }
}

// ---------------------------------------------------------------------------
// Character access
// ---------------------------------------------------------------------------

fn char_at(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let text = units(&wtf8_of(interp, &this)?);
    // A negative index is out of range, not clamped to zero: `"a".charAt(-1)` is
    // `""`, which is different from `"a".charAt(0)`.
    let Some(index) = unit_index(arg_integer_or(interp, args, 0, 0.0)? as i64, text.len()) else {
        return Ok(interp.string(String::new()));
    };
    Ok(interp.string_wtf8(from_units(&text[index..index + 1])))
}

/// A non-negative index into a string of `length` code units, or `None`.
///
/// The "at" family all treat a negative index as absent rather than wrapping, which
/// is what separates them from `slice` and `at`.
fn unit_index(index: i64, length: usize) -> Option<usize> {
    if index < 0 || index as usize >= length {
        None
    } else {
        Some(index as usize)
    }
}

fn char_code_at(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    // Straight at the receiver's cached units rather than through a decoded copy: this is
    // the operation a `for` loop over a string repeats, so it has to be `O(1)`.
    let object = string_object(interp, &this)?;
    let index = arg_integer_or(interp, args, 0, 0.0)? as i64;
    if index < 0 {
        return Ok(Value::Float(f64::NAN));
    }
    Ok(match object.code_unit_at(index as usize) {
        Some(unit) => Value::Int(unit as i32),
        None => Value::Float(f64::NAN),
    })
}

fn code_point_at(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let text = units(&wtf8_of(interp, &this)?);
    let Some(index) = unit_index(arg_integer_or(interp, args, 0, 0.0)? as i64, text.len()) else {
        return Ok(Value::Undefined);
    };
    let first = text[index];
    // A high surrogate followed by a low one is a single code point; anything else
    // is the unit itself.
    if (0xd800..0xdc00).contains(&first)
        && let Some(second) = text.get(index + 1).copied()
        && (0xdc00..0xe000).contains(&second)
    {
        let combined = 0x10000 + ((first as u32 - 0xd800) << 10) + (second as u32 - 0xdc00);
        return Ok(Value::Int(combined as i32));
    }
    Ok(Value::Int(first as i32))
}

fn at(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let text = units(&wtf8_of(interp, &this)?);
    let raw = arg_integer_or(interp, args, 0, 0.0)? as i64;
    let index = if raw < 0 {
        text.len() as i64 + raw
    } else {
        raw
    };
    if index < 0 || index as usize >= text.len() {
        return Ok(Value::Undefined);
    }
    Ok(interp.string_wtf8(from_units(&text[index as usize..index as usize + 1])))
}

// ---------------------------------------------------------------------------
// Searching
// ---------------------------------------------------------------------------

fn index_of(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let text = text_of(interp, &this)?;
    let needle = interp.to_string_strict(&arg(args, 0))?;
    // A negative start does *not* count from the end here, unlike `slice`: it clamps
    // to zero, so `"aaa".indexOf("a", -1)` is `0`.
    let start = ((arg_integer_or(interp, args, 1, 0.0)? as i64).max(0) as usize).min(text.len());
    // Searching from `start` on the *byte* offset is safe because a UTF-8 boundary
    // that is not a character boundary cannot match a whole needle.
    let found = text
        .get(start..)
        .and_then(|tail| tail.find(&needle))
        .map(|offset| text[..start].len() + offset);
    Ok(Value::Int(match found {
        Some(offset) => text[..offset].chars().map(char::len_utf16).sum::<usize>() as i32,
        None => -1,
    }))
}

fn last_index_of(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let text = text_of(interp, &this)?;
    let needle = interp.to_string_strict(&arg(args, 0))?;
    // The second argument caps where a match may *start*, not where it may end: a
    // negative position clamps to zero, so `"aaa".lastIndexOf("a", -Infinity)` still
    // finds the match at 0.
    let limit = match args.get(1) {
        None | Some(Value::Undefined) => text.len(),
        // `ToNumber(position)`: an object runs `ToPrimitive`, and a Symbol is a
        // `TypeError` — `value.to_number()` answered `NaN` for an object and for a Symbol
        // alike, so a throwing `valueOf` was swallowed
        // (`lastIndexOf/S15.5.4.8_A4_T1`, `…_T2`).
        Some(value) => {
            let position = interp.to_js_number(value)?;
            if position.is_nan() {
                text.len()
            } else if position < 0.0 {
                0
            } else {
                (position as usize).min(text.len())
            }
        }
    };
    // Search the candidate start positions from `limit` downwards.
    let found = (0..=limit)
        .rev()
        .find(|start| text[*start..].starts_with(&needle));
    Ok(Value::Int(match found {
        Some(offset) => text[..offset].chars().map(char::len_utf16).sum::<usize>() as i32,
        None => -1,
    }))
}

fn includes(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let text = text_of(interp, &this)?;
    // §22.1.3.7 step 2: `RequireObjectCoercible` already happened; then the *search*
    // string is converted, then `position`. The old version stopped after the needle and
    // ignored `position` entirely, so `"word".includes("w", 5)` answered `true`.
    // §22.1.3.x step 2: `IsRegExp(searchString)` is checked first, and a true answer is a
    // `TypeError` — the three "does not accept a regexp" methods. It is `IsRegExp`, not the
    // internal slot, so `@@match` is consulted and its getter can throw
    // (`startsWith|endsWith|includes/return-abrupt-from-searchstring-regexp-test`).
    let needle_value = arg(args, 0);
    if is_regexp(interp, &needle_value)? {
        return Err(interp.type_error("searchString may not be a RegExp"));
    }

    let needle = interp.to_string_strict(&needle_value)?;
    // §22.1.3.7 step 8: `min(max(position, 0), len)` — clamped, not rejected. `Infinity`
    // therefore becomes `len`, where an empty needle still matches (`str.includes("",
    // Infinity)` is `true`), so the later test has to allow `start == len`.
    let start = ((arg_integer_or(interp, args, 1, 0.0)? as i64).max(0) as usize).min(text.len());
    Ok(Value::Bool(text[start..].contains(&needle)))
}

fn starts_with(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let text = text_of(interp, &this)?;
    // §22.1.3.x step 2: `IsRegExp(searchString)` is checked first, and a true answer is a
    // `TypeError` — the three "does not accept a regexp" methods. It is `IsRegExp`, not the
    // internal slot, so `@@match` is consulted and its getter can throw
    // (`startsWith|endsWith|includes/return-abrupt-from-searchstring-regexp-test`).
    let needle_value = arg(args, 0);
    if is_regexp(interp, &needle_value)? {
        return Err(interp.type_error("searchString may not be a RegExp"));
    }

    let needle = interp.to_string_strict(&needle_value)?;
    let start = ((arg_integer_or(interp, args, 1, 0.0)? as i64).max(0) as usize).min(text.len());
    Ok(Value::Bool(
        text.get(start..)
            .is_some_and(|tail| tail.starts_with(&needle)),
    ))
}

fn ends_with(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let text = text_of(interp, &this)?;
    // §22.1.3.x step 2: `IsRegExp(searchString)` is checked first, and a true answer is a
    // `TypeError` — the three "does not accept a regexp" methods. It is `IsRegExp`, not the
    // internal slot, so `@@match` is consulted and its getter can throw
    // (`startsWith|endsWith|includes/return-abrupt-from-searchstring-regexp-test`).
    let needle_value = arg(args, 0);
    if is_regexp(interp, &needle_value)? {
        return Err(interp.type_error("searchString may not be a RegExp"));
    }

    let needle = interp.to_string_strict(&needle_value)?;
    // `ToIntegerOrInfinity`, not a raw `to_number`: an object `endPosition` has to run its
    // `valueOf`. `clamp` then treats `NaN` as "the whole string", which is what
    // `ToIntegerOrInfinity` giving 0 followed by the `min(text.length, …)` clamp
    // effectively means here.
    let end = match args.get(1) {
        None | Some(Value::Undefined) => text.len(),
        Some(_) => clamp(arg_integer_or(interp, args, 1, 0.0)?, text.len()),
    };
    Ok(Value::Bool(
        text.get(..end).is_some_and(|head| head.ends_with(&needle)),
    ))
}

fn locale_compare(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let text = wtf8_of(interp, &this)?;
    let other = interp.checked_to_wtf8(&arg(args, 0))?;
    // §22.1.3.10 says two things: the *order* is implementation-defined, and strings that
    // are **canonically equivalent** must compare equal. The second is testable and the first
    // is not, so NFC is the whole of what this does — no locale data, because there is no
    // locale here to have data for. Comparing the normalized forms makes `"o\u0308"` and
    // `"ö"` one value and leaves every other pair in code-unit order
    // (`localeCompare/15.5.4.9_CE` is a list of canonical equivalences).
    let left = crate::normalize::normalize(&text, crate::normalize::Form::Nfc);
    let right = crate::normalize::normalize(&other, crate::normalize::Form::Nfc);
    Ok(Value::Int(match left.to_units().cmp(&right.to_units()) {
        std::cmp::Ordering::Less => -1,
        std::cmp::Ordering::Equal => 0,
        std::cmp::Ordering::Greater => 1,
    }))
}

// ---------------------------------------------------------------------------
// Slicing
// ---------------------------------------------------------------------------

fn slice(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let text = units(&wtf8_of(interp, &this)?);
    let start = clamp(
        arg_integer_or(interp, args, 0, 0.0)? as i64 as f64,
        text.len(),
    );
    let end = match args.get(1) {
        None | Some(Value::Undefined) => text.len(),
        // `ToIntegerOrInfinity(end)`, through `ToNumber` — `value.to_number()` skipped
        // `ToPrimitive` and swallowed a throwing `valueOf`
        // (`slice/S15.5.4.13_A1_T13`).
        Some(_) => clamp(arg_integer_or(interp, args, 1, 0.0)?, text.len()),
    };
    Ok(interp.string_wtf8(from_units(if start < end {
        &text[start..end]
    } else {
        &[]
    })))
}

fn substring(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let text = units(&wtf8_of(interp, &this)?);
    // `substring` clamps to `[0, length]` and swaps its arguments when start > end;
    // it does not accept negative indices, which is the whole difference from `slice`.
    let length = text.len() as f64;
    let a = (arg_integer_or(interp, args, 0, 0.0)? as i64).max(0) as f64;
    // `ToIntegerOrInfinity(end)`, i.e. through `ToNumber` — a `Value::to_number` on an
    // object answers `NaN` without running its `valueOf`, so `substring(0, new
    // Boolean(2))` came back as the empty string (`S15.5.4.15_A3_T11` and the J4 family).
    let b = match args.get(1) {
        None | Some(Value::Undefined) => length,
        Some(_) => arg_integer_or(interp, args, 1, 0.0)?.max(0.0),
    };
    let (start, end) = if a.is_nan() || b.is_nan() {
        (0, 0)
    } else {
        let a = a.min(length);
        let b = b.min(length);
        if a <= b {
            (a as usize, b as usize)
        } else {
            (b as usize, a as usize)
        }
    };
    Ok(interp.string_wtf8(from_units(&text[start..end])))
}

fn substr(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let text = units(&wtf8_of(interp, &this)?);
    let length = text.len();
    let start = clamp(arg_integer_or(interp, args, 0, 0.0)? as i64 as f64, length);
    let count = match args.get(1) {
        None | Some(Value::Undefined) => length - start,
        Some(value) => value.to_number().max(0.0) as usize,
    };
    let end = (start + count).min(length);
    Ok(interp.string_wtf8(from_units(&text[start..end])))
}

/// §22.1.3.23 `String.prototype.split ( separator, limit )`.
///
/// The order of the four conversions is the entire specification here, and every
/// `separator-override-*` / `limit-*` case in test262 is checking one edge of it:
///
/// ```text
/// 1  RequireObjectCoercible(this)
/// 2  GetMethod(separator, @@split) → Call(splitter, separator, « O, limit »)
/// 3  S   = ToString(O)
/// 4  lim = ToUint32(limit)          ← **before** ToString(separator)
/// 5  R   = ToString(separator)
/// 6  lim = 0            → []
/// 7  separator undefined → [S]      ← even when S is ""
/// 9  R is empty         → one element per code point
/// ```
///
/// Three of those were wrong here, and none of them is visible without a test that plants
/// a throwing `@@split`, `toString` or `valueOf` somewhere specific.
fn split(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    // Step 1. Before anything else: `split.call(undefined, x)` is a TypeError even when
    // `x` carries a `@@split`.
    if matches!(this, Value::Undefined | Value::Null) {
        return Err(interp.type_error("cannot convert undefined or null to object"));
    }
    let separator = arg(args, 0);
    let limit_arg = arg(args, 1);
    // Step 2: `GetMethod(separator, @@split)`, and this runs **before** `ToString(this)` —
    // so a receiver whose `toString` throws is untouched when the separator supplies a
    // splitter of its own (`this-value-tostring-error`).
    //
    // `undefined`/`null` mean "no method", not "throwing method": GetMethod normalises the
    // two, and anything else present must be callable.
    //
    // Only an **object** separator is asked. The specification spells this as one
    // `GetMethod(separator, @@split)`, whose `GetV` would box a primitive and find a
    // `@@split` planted on `String.prototype` — but every engine skips it, and
    // `cstm-split-on-{string,number,boolean,bigint}-primitive` assert exactly that a
    // throwing getter there is never reached. An object separator is still consulted, which
    // is what `cstm-split-get-err` / `cstm-split-invocation` / `cstm-split-is-null` cover.
    if separator.as_object().is_some() {
        let key = interp.realm.well_known_key(crate::interp::WellKnown::Split);
        let splitter = interp.read_field_key(&separator, &key)?;
        match splitter {
            Value::Undefined | Value::Null => {}
            Value::Object(function) if function.is_callable() => {
                return interp.call_value(
                    Value::Object(function),
                    separator,
                    vec![this.clone(), limit_arg],
                );
            }
            _ => return Err(interp.type_error("Symbol.split is not a function")),
        }
    }
    // Step 3.
    let text = require_string(interp, &this)?;
    let text = text.wtf8();
    // Step 4: `ToUint32(limit)`. Not `Value::to_number` (which is a total conversion and
    // never runs `valueOf`), and not a clamp at zero: `2**32` wraps to `0`, which is what
    // makes `"".split("", 2**32)` empty (`separator-undef-limit-zero`).
    let limit = match &limit_arg {
        Value::Undefined => u32::MAX,
        value => Value::Float(interp.to_js_number(value)?).to_uint32(),
    };
    // Step 5: `ToString(separator)` — **not** `RequireObjectCoercible`, so
    // `"gnulluna".split(null)` splits on the four characters `null`.
    let separator = match &separator {
        Value::Undefined => None,
        value => Some(crate::builtins::to_string_wtf8(interp, value)?),
    };
    // Step 6.
    if limit == 0 {
        let array = interp.new_array(Vec::new());
        return Ok(Value::Object(array));
    }
    let parts: Vec<Value> = match separator {
        // Step 7: `[S]`, including the empty string — `"".split()` is `[""]`, not `[]`.
        None => vec![interp.string_wtf8(text.clone())],
        // Step 9: one element per code point, so an astral character is not split in two.
        Some(separator) if separator.is_empty() => text
            .code_points()
            .into_iter()
            .map(|point| interp.string_wtf8(point))
            .collect(),
        Some(separator) => {
            // Steps 10–13: a plain substring search. `slice_units` keeps unpaired
            // surrogates intact, which a `String`-based split could not.
            let mut parts = Vec::new();
            let length = separator.utf16_len();
            let total = text.utf16_len();
            let mut start = 0;
            let mut at = 0;
            while at + length <= total {
                if text.slice_units(at, at + length) == separator {
                    parts.push(interp.string_wtf8(text.slice_units(start, at)));
                    start = at + length;
                    at = start;
                } else {
                    at += 1;
                }
            }
            parts.push(interp.string_wtf8(text.slice_units(start, total)));
            parts
        }
    };
    let limited: Vec<Value> = parts.into_iter().take(limit as usize).collect();
    let array = interp.new_array(limited);
    Ok(Value::Object(array))
}

fn concat(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let mut text = text_of(interp, &this)?;
    for value in args {
        // `ToString`, not `Value::to_js_string`: the total convertor renders an object as
        // `[object Object]` without running `ToPrimitive`, so `"".concat(Object(Symbol()))`
        // answered `[object Object]` where `Symbol.prototype.toString` should have been
        // consulted. `to_string_strict` is the spec operation (and refuses a bare symbol).
        text.push_str(&interp.to_string_strict(value)?);
    }
    Ok(interp.string(text))
}

/// `String.prototype.replace(searchValue, replaceValue)` — §22.1.3.18.
fn replace(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    replace_shared(interp, this, args, false)
}

/// `String.prototype.replaceAll(searchValue, replaceValue)` — §22.1.3.19.
///
/// Differs from `replace` in exactly two places, both of them in the shared body: a
/// `RegExp` without `g` is a `TypeError` instead of replacing once, and the search loops.
fn replace_all(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    replace_shared(interp, this, args, true)
}

/// The steps `replace` and `replaceAll` share, with `every` deciding the loop.
///
/// **The order of the observable steps is the point, and it is not the order the code reads
/// in**: `RequireObjectCoercible(this)`, then `IsRegExp` and the `g` check, then
/// `GetMethod(searchValue, @@replace)`, and only *then* `ToString(this)`, then
/// `ToString(searchValue)`, then `ToString(replaceValue)`. test262 counts each conversion
/// separately (`searchValue-tostring-abrupt.js`), so converting the receiver up front — as
/// this did before — both converts something the spec has not asked for yet and, on a
/// poisoned receiver, throws from the wrong step.
fn replace_shared(
    interp: &mut Interp<'_>,
    this: Value,
    args: &[Value],
    every: bool,
) -> JsResult<Value> {
    // Step 1. The receiver is only *checked* here; its conversion waits for step 3.
    require_object_coercible(interp, &this)?;
    // Step 2a-b. `replaceAll` refuses a non-global `RegExp` before anything else happens,
    // `@@replace` lookup included: `searchValue-flags-no-g-throws.js` poisons both `this`
    // and `replaceValue` to prove no conversion ran first.
    let search_value = arg(args, 0);
    if every && !search_value.is_nullish() && is_regexp(interp, &search_value)? {
        let flags = match search_value.as_object() {
            Some(object) => interp
                .get_property(object, "flags")?
                .unwrap_or(Value::Undefined),
            None => Value::Undefined,
        };
        // `RequireObjectCoercible(flags)`: a `RegExp` whose `flags` was deleted throws a
        // `TypeError` about conversion, not about the missing `g`.
        if flags.is_nullish() {
            return Err(interp.type_error("cannot convert to object"));
        }
        let flags = interp.checked_to_wtf8(&flags)?;
        if !flags.to_units().contains(&u16::from(b'g')) {
            return Err(interp.type_error("regexp must have the 'g' flag"));
        }
    }
    // Step 2c. Exactly two arguments reach `@@replace`, whether or not the caller passed
    // them: `''.replace(searchValue)` calls it with `(this, undefined)`.
    let call_args = [search_value.clone(), arg(args, 1)];
    if let Some(result) = symbol_dispatch(interp, &this, WellKnown::Replace, &call_args)? {
        return Ok(result);
    }
    // Step 3. Now the receiver converts. Its *units* are taken, not a `String`: the loop
    // indexes code units and the output is rebuilt from them, so an unpaired surrogate has
    // to survive the round trip.
    let text = require_string(interp, &this)?.units_cached();
    // Step 4.
    let pattern = interp.checked_to_wtf8(&search_value)?.to_units();
    // Step 5-6: a callable replacement is called, and only a non-callable one is converted
    // — but that conversion happens even when nothing matches
    // (`replaceValue-evaluation-order.js` counts exactly one `toString` on a receiver the
    // pattern never matches).
    let replace_value = arg(args, 1);
    let function = match &replace_value {
        Value::Object(object) if object.is_callable() => Some(Value::Object(object.clone())),
        _ => None,
    };
    let template = match &function {
        Some(_) => None,
        None => Some(interp.checked_to_wtf8(&replace_value)?),
    };
    let mut out: Vec<u16> = Vec::with_capacity(text.len());
    let mut end_of_last_match = 0usize;
    let mut first = true;
    loop {
        let position = if pattern.is_empty() {
            // An empty pattern matches at every index, the end included, and the step is one
            // *code unit* — which is why `"🐱".replaceAll("", "-")` inserts between the two
            // halves of the pair.
            if first {
                Some(0)
            } else if end_of_last_match >= text.len() {
                None
            } else {
                Some(end_of_last_match + 1)
            }
        } else {
            find_units(&text, &pattern, end_of_last_match)
        };
        let Some(position) = position else {
            break;
        };
        out.extend_from_slice(&text[end_of_last_match..position]);
        match (&function, &template) {
            (Some(function), _) => {
                let matched = crate::value::Wtf8::from_units(
                    text.get(position..position + pattern.len())
                        .unwrap_or_default(),
                );
                let result = interp.call_value(
                    function.clone(),
                    Value::Undefined,
                    vec![
                        interp.string_wtf8(matched),
                        Value::Int(position as i32),
                        interp.string_wtf8(crate::value::Wtf8::from_units(&text)),
                    ],
                )?;
                out.extend_from_slice(&interp.checked_to_wtf8(&result)?.to_units());
            }
            (None, Some(template)) => get_substitution(
                &mut out,
                template,
                &Substitution {
                    input: &text,
                    matched: text
                        .get(position..position + pattern.len())
                        .unwrap_or_default(),
                    position,
                    match_len: pattern.len(),
                    // A string pattern has no capture groups, which is what makes `$1` and
                    // `$<name>` literal text rather than empty expansions.
                    captures: &[],
                    names: None,
                },
            ),
            (None, None) => unreachable!("a replacement is either callable or converted"),
        }
        end_of_last_match = position + pattern.len();
        first = false;
        if !every {
            break;
        }
    }
    // Nothing matched: the receiver comes back as it was, not rebuilt.
    if first {
        return Ok(interp.string_wtf8(crate::value::Wtf8::from_units(&text)));
    }
    out.extend_from_slice(text.get(end_of_last_match..).unwrap_or_default());
    Ok(interp.string_wtf8(crate::value::Wtf8::from_units(&out)))
}

/// `StringIndexOf` over code units, starting at `from`.
fn find_units(text: &[u16], pattern: &[u16], from: usize) -> Option<usize> {
    // `windows` over the haystack rather than a two-pointer scan: this runs once per match,
    // not once per character, and the slice comparison compiles to a `memcmp`.
    if pattern.is_empty() || pattern.len() > text.len() || from > text.len() - pattern.len() {
        return None;
    }
    text[from..]
        .windows(pattern.len())
        .position(|window| window == pattern)
        .map(|offset| from + offset)
}

/// `IsRegExp` — §7.2.6, which is *not* the internal-slot test.
///
/// `@@match` overrides the answer: an object with `[Symbol.match]: false` is not a regexp
/// for `replaceAll`'s purposes even when it is one, and a plain object with
/// `[Symbol.match]: true` is. Reading the slot first would make
/// `searchValue-get-flags-abrupt.js`'s plain-object cases unreachable.
pub(crate) fn is_regexp(interp: &mut Interp<'_>, value: &Value) -> JsResult<bool> {
    let Some(object) = value.as_object() else {
        return Ok(false);
    };
    let matcher =
        interp.get_property_key(object, &interp.realm.well_known_key(WellKnown::Match))?;
    if let Some(matcher) = matcher
        && !matches!(matcher, Value::Undefined)
    {
        return Ok(matcher.to_boolean());
    }
    Ok(object.regexp().is_some())
}

/// `RequireObjectCoercible` — refuses the two nullish values and nothing else.
fn require_object_coercible(interp: &Interp<'_>, value: &Value) -> JsResult<()> {
    match value {
        Value::Null => Err(interp.type_error("cannot convert null to a string")),
        Value::Undefined => Err(interp.type_error("cannot convert undefined to a string")),
        _ => Ok(()),
    }
}

/// Hand `args` to the pattern's `Symbol.replace`-style method, when it has one.
///
/// This is how a `RegExp` (or any object that opts in) gets to define what `replace` and
/// friends mean, and it is why `String.prototype.split` needs no regexp knowledge of its
/// own.
fn symbol_dispatch(
    interp: &mut Interp<'_>,
    this: &Value,
    which: WellKnown,
    args: &[Value],
) -> JsResult<Option<Value>> {
    let pattern = arg(args, 0);
    let Some(object) = pattern.as_object() else {
        return Ok(None);
    };
    let method = interp.get_property_key(object, &interp.realm.well_known_key(which))?;
    let Some(method) = method else {
        return Ok(None);
    };
    if matches!(method, Value::Undefined | Value::Null) {
        return Ok(None);
    }
    let mut call_args: Vec<Value> = vec![this.clone()];
    call_args.extend(args.iter().skip(1).cloned());
    let result = interp.call_value(method, pattern, call_args)?;
    Ok(Some(result))
}

/// `String.prototype.match(pattern)`.
///
/// §22.2.6.8, followed step for step, because the order decides which user code runs:
/// `@@match` is consulted *before* `ToString(this)`, the regexp is created from
/// `undefined` (so `"abc".match()` is `[""]`), and the dispatch then runs again on it (so a
/// subclass's override is reached).
fn match_method(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    require_object_coercible(interp, &this)?;
    let pattern = arg(args, 0);
    if !matches!(pattern, Value::Undefined | Value::Null)
        && let Some(result) = symbol_dispatch(interp, &this, WellKnown::Match, args)?
    {
        return Ok(result);
    }
    let text = text_of(interp, &this)?;
    let text = interp.string(text);
    invoke_builtin_dispatch(interp, WellKnown::Match, pattern, text, false)
}

/// `String.prototype.matchAll(pattern)`.
///
/// §22.2.6.9. The `g` check is the part that used to be missing, and it is why
/// `"a1".matchAll(/\d/)` must be a `TypeError` even though `RegExp.prototype[@@matchAll]`
/// itself accepts a non-global pattern: the *string* method requires the flag, and it
/// requires it **before** looking up `@@matchAll`.
fn match_all(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    require_object_coercible(interp, &this)?;
    let pattern = arg(args, 0);
    if !matches!(pattern, Value::Undefined | Value::Null) {
        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 flags = interp
                .get_property(object, "flags")?
                .unwrap_or(Value::Undefined);
            require_object_coercible(interp, &flags)?;
            let flags = interp.to_js_string(&flags)?;
            if !flags.contains('g') {
                return Err(interp.type_error("regexp must have the 'g' flag"));
            }
        }
        if let Some(result) = symbol_dispatch(interp, &this, WellKnown::MatchAll, args)? {
            return Ok(result);
        }
    }
    let text = text_of(interp, &this)?;
    let text = interp.string(text);
    invoke_builtin_dispatch(interp, WellKnown::MatchAll, pattern, text, true)
}

/// `String.prototype.search(pattern)`.
fn search(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    require_object_coercible(interp, &this)?;
    let pattern = arg(args, 0);
    if !matches!(pattern, Value::Undefined | Value::Null)
        && let Some(result) = symbol_dispatch(interp, &this, WellKnown::Search, args)?
    {
        return Ok(result);
    }
    let text = text_of(interp, &this)?;
    let text = interp.string(text);
    invoke_builtin_dispatch(interp, WellKnown::Search, pattern, text, false)
}

/// The last step of `match`/`matchAll`/`search`: `Invoke(RegExpCreate(P, flags), @@which, «S»)`.
///
/// `flags` is `""` except for `matchAll`, which forces `"g"` — that is what makes
/// `"a1b2".matchAll("\\d")` yield two matches from a *string* pattern.
fn invoke_builtin_dispatch(
    interp: &mut Interp<'_>,
    which: WellKnown,
    pattern: Value,
    text: Value,
    force_global: bool,
) -> JsResult<Value> {
    let source = match pattern {
        Value::Undefined => String::new(),
        other => interp.to_js_string(&other)?,
    };
    let flags = if force_global { "g" } else { "" };
    let regexp = crate::builtins::regexp::new_regexp(interp, &source, flags)?;
    let key = interp.realm.well_known_key(which);
    let method = interp.get_property_key(&regexp, &key)?;
    let Some(Value::Object(method)) = method else {
        return Err(interp.type_error("RegExp.prototype has no such symbol method"));
    };
    interp.call_value(Value::Object(method), Value::Object(regexp), vec![text])
}

// ---------------------------------------------------------------------------
// Case, whitespace, repetition
// ---------------------------------------------------------------------------

/// `String.prototype.normalize([form])` — the four Unicode Normalization Forms.
///
/// The argument is read *after* the receiver is converted, because §22.1.3.13 does
/// `RequireObjectCoercible`, then `ToString`, then `ToString(form)`: `"x".normalize({toString
/// (){throw …}})` therefore throws from the receiver's conversion first, and
/// `null.normalize(bad)` is a TypeError about the receiver rather than a RangeError.
fn normalize(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    // Not `text_of`: a receiver may hold an unpaired surrogate, which normalization carries
    // through rather than flattening to U+FFFD.
    let text = wtf8_of(interp, &this)?;
    let form = match arg(args, 0) {
        // `undefined` — written, or absent — means NFC. The spec's default is on the
        // parameter, so it is the *value* that matters, not how many arguments arrived.
        Value::Undefined => Form::Nfc,
        value => {
            // `checked_to_wtf8` is `ToString`, which refuses a Symbol; `to_js_string` is
            // `String()`, which turns one into `"Symbol(…)"` and would make
            // `normalize(Symbol())` a RangeError instead of the TypeError it must be.
            let name = interp.checked_to_wtf8(&value)?;
            // A form holding an unpaired surrogate has no `&str` form, so it can never name
            // one of the four and falls through to the same RangeError.
            match name.as_str().and_then(Form::parse) {
                Some(form) => form,
                // The message is the reference's; the spec gives none, and a script that
                // catches this only looks at `name`.
                None => return Err(interp.range_error("bad normalization form")),
            }
        }
    };
    Ok(interp.string_wtf8(normalize_text(&text, form)))
}

/// `String.prototype.isWellFormed()` — §22.1.3.10.
///
/// The only question is whether the string has an unpaired surrogate, which is exactly what
/// [`crate::value::Wtf8::is_valid`] records when the string is built.
fn is_well_formed(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    Ok(Value::Bool(wtf8_of(interp, &this)?.is_valid()))
}

/// `String.prototype.toWellFormed()` — §22.1.3.30: every unpaired surrogate becomes U+FFFD.
///
/// The replacement is per *code point*, not per code unit: a valid pair is one code point and
/// must survive whole. Mapping the units would replace both halves of every astral character,
/// which is why this goes through `code_point_values` rather than `to_units`.
fn to_well_formed(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    let text = wtf8_of(interp, &this)?;
    if text.is_valid() {
        // Already well-formed: nothing to replace, and no reason to rebuild the bytes.
        return Ok(interp.string_wtf8(text));
    }
    let points: Vec<u32> = text
        .code_point_values()
        .iter()
        .map(|&point| match point {
            0xD800..=0xDFFF => 0xFFFD,
            other => other,
        })
        .collect();
    Ok(interp.string_wtf8(crate::value::Wtf8::from_code_points(&points)))
}

/// Annex B `CreateHTML(this, tag, attribute, value)` (§B.2.3.2).
///
/// The escaping is one-sided on purpose: the *tag* and the *attribute name* are literals
/// from each method, never escaped, while the attribute *value* has every `"` replaced by
/// `&quot;` — nothing else, not `<`, not `&`. `"x".anchor('a"b')` is
/// `<a name="a&quot;b">x</a>` in the reference and here.
///
/// One deliberate difference from the reference: `"x".link()` (no argument) yields
/// `<a>x</a>` here, because step 3 of `CreateHTML` says an `undefined` value means the
/// attribute is omitted. The reference throws "null or undefined are forbidden" — a
/// deviation nobody noticed because test262 has zero tests for this family, which is also
/// why these are recorded as parity work rather than as a fix.
fn create_html(
    interp: &mut Interp<'_>,
    this: &Value,
    tag: &str,
    attribute: Option<&str>,
    value: Option<&Value>,
) -> JsResult<Value> {
    let text = text_of(interp, this)?;
    let mut result = format!("<{tag}");
    if let (Some(attribute), Some(value)) = (attribute, value) {
        if !matches!(value, Value::Undefined) {
            let value = interp.to_js_string(value)?;
            result.push_str(&format!(
                " {attribute}=\"{}\"",
                value.replace('"', "&quot;")
            ));
        }
    }
    result.push('>');
    result.push_str(&text);
    result.push_str(&format!("</{tag}>"));
    Ok(interp.string(result))
}

fn anchor(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    create_html(interp, &this, "a", Some("name"), Some(&arg(args, 0)))
}

fn big(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    create_html(interp, &this, "big", None, None)
}

fn blink(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    create_html(interp, &this, "blink", None, None)
}

fn bold(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    create_html(interp, &this, "b", None, None)
}

fn fixed(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    create_html(interp, &this, "tt", None, None)
}

fn fontcolor(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    create_html(interp, &this, "font", Some("color"), Some(&arg(args, 0)))
}

fn fontsize(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    create_html(interp, &this, "font", Some("size"), Some(&arg(args, 0)))
}

fn italics(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    create_html(interp, &this, "i", None, None)
}

fn link(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    create_html(interp, &this, "a", Some("href"), Some(&arg(args, 0)))
}

fn small(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    create_html(interp, &this, "small", None, None)
}

fn strike(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    create_html(interp, &this, "strike", None, None)
}

fn sub(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    create_html(interp, &this, "sub", None, None)
}

fn sup(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    create_html(interp, &this, "sup", None, None)
}

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

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

/// Whether `c` is in ECMAScript's `WhiteSpace ∪ LineTerminator` (§11.2, §11.3).
///
/// **Deliberately not `char::is_whitespace`**, which is Unicode `White_Space`. The two sets
/// differ in both directions and each difference is a test262 case:
///
/// * `U+FEFF` (ZWNBSP) is ECMAScript WhiteSpace (it is in the *Other* category there) but
///   not `White_Space`, so `char::is_whitespace` left it in place where `trim` must remove it;
/// * `U+0085` (NEL) *is* `White_Space` but is not ECMAScript whitespace, so the standard
///   library removed it where `trim` must keep it.
///
/// `U+180E` (Mongolian vowel separator) left the set in Unicode 6.3 and both agree on
/// excluding it today.
fn is_js_whitespace(c: char) -> bool {
    matches!(
        c,
        '\u{0009}'            // TAB
        | '\u{000A}'          // LF
        | '\u{000B}'          // VT
        | '\u{000C}'          // FF
        | '\u{000D}'          // CR
        | '\u{0020}'          // SP
        | '\u{00A0}'          // NBSP
        | '\u{1680}'          // OGHAM SPACE MARK
        | '\u{2000}'
            ..='\u{200A}' // EN QUAD .. HAIR SPACE
        | '\u{2028}'          // LS
        | '\u{2029}'          // PS
        | '\u{202F}'          // NARROW NBSP
        | '\u{205F}'          // MEDIUM MATHEMATICAL SPACE
        | '\u{3000}'          // IDEOGRAPHIC SPACE
        | '\u{FEFF}' // ZWNBSP
    )
}

fn trim(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    let text = text_of(interp, &this)?;
    Ok(interp.string(text.trim_matches(is_js_whitespace).to_string()))
}

fn trim_start(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    let text = text_of(interp, &this)?;
    Ok(interp.string(text.trim_start_matches(is_js_whitespace).to_string()))
}

fn trim_end(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    let text = text_of(interp, &this)?;
    Ok(interp.string(text.trim_end_matches(is_js_whitespace).to_string()))
}

fn repeat(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let text = text_of(interp, &this)?;
    // §22.1.3.18 step 3 is `ToIntegerOrInfinity(count)`, which is observable: a Symbol is a
    // `TypeError` and a throwing `valueOf` propagates
    // (`return-abrupt-from-count-as-symbol`, `return-abrupt-from-count`). A raw
    // `arg_number_int` answered `NaN` for both and repeated zero times.
    let number = arg_integer_or(interp, args, 0, 0.0)?;
    if number < 0.0 || number.is_infinite() {
        // A negative count and an infinite one are both `RangeError`
        // (`count-is-infinity-throws`).
        return Err(interp.range_error("repeat count must be positive and finite"));
    }
    let count = number as usize;
    // `String.prototype.repeat` must not build an impossible string.
    if !text.is_empty() && count.saturating_mul(text.len()) > (1 << 30) {
        return Err(interp.range_error("repeated string is too long"));
    }
    Ok(interp.string(text.repeat(count)))
}

fn pad_start(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    pad(interp, this, args, true)
}

fn pad_end(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    pad(interp, this, args, false)
}

fn pad(interp: &mut Interp<'_>, this: Value, args: &[Value], at_start: bool) -> JsResult<Value> {
    // §22.1.3.17 converts in a fixed order — `ToString(this)`, `ToLength(maxLength)`,
    // `ToString(fillString)` — and each conversion is observable, so an object with a
    // `valueOf` or `toString` has to be consulted rather than read as a primitive.
    let text = wtf8_of(interp, &this)?;
    let target = match arg(args, 0) {
        Value::Undefined => 0,
        value => {
            // `ToLength`: `ToIntegerOrInfinity` clamped into `[0, 2^53-1]`. A NaN arriving
            // from an unhelpful `valueOf` casts to 0, which is the same answer.
            let number = interp.to_js_number(&value)?;
            number.trunc().clamp(0.0, 9007199254740991.0) as usize
        }
    };
    let filler = match args.get(1) {
        None | Some(Value::Undefined) => crate::value::Wtf8::new(" "),
        // `ToString`, which refuses a Symbol — `to_js_string` would have produced
        // `"Symbol()"` as the filler and padded with it.
        Some(value) => interp.checked_to_wtf8(value)?,
    };
    let current = text.utf16_len();
    if target <= current || filler.is_empty() {
        return Ok(interp.string_wtf8(text));
    }
    let needed = target - current;
    if needed > crate::value::JS_STRING_LEN_MAX {
        return Err(interp.range_error("invalid string length"));
    }
    // The padding is cut at a *code unit* boundary, so half of a surrogate pair is a legal
    // result: `'abc'.padStart(6, '\uD83D\uDCA9')` ends in a lone high surrogate, which the
    // reference produces and `String::from_utf16_lossy` would have turned into U+FFFD.
    let filler_units = filler.to_units();
    let mut padding = Vec::with_capacity(needed);
    while padding.len() < needed {
        let take = (needed - padding.len()).min(filler_units.len());
        padding.extend_from_slice(&filler_units[..take]);
    }
    let mut joined = Vec::with_capacity(current + needed);
    if at_start {
        joined.extend_from_slice(&padding);
    }
    joined.extend_from_slice(&text.to_units());
    if !at_start {
        joined.extend_from_slice(&padding);
    }
    // `Wtf8::from_units` folds a surrogate pair that happens to meet at the seam, which is
    // exactly what the concatenation means: the units are adjacent, so they *are* a pair.
    Ok(interp.string_wtf8(crate::value::Wtf8::from_units(&joined)))
}

/// `String.prototype.toString` and `valueOf`: `thisStringValue`, a real brand check.
///
/// These two are the *only* `String.prototype` methods that refuse a non-string receiver
/// (§22.1.3.28): `String.prototype.toString.call(123)` is a `TypeError` while
/// `String.prototype.trim.call(123)` is `"123"`.
///
/// They also have to be the brand check for a mechanical reason: they are what
/// `ToPrimitive` calls on a boxed string, so routing them through `ToString` would ask
/// `ToPrimitive` for the string while already inside `ToPrimitive` — unbounded recursion,
/// which is how the process aborted before this was split apart.
fn to_string(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    // A **brand check**, which is why this cannot go through `string_object` (the generic
    // `ToString` path): it is what `ToPrimitive` reaches for a boxed string, so converting
    // here would ask `ToPrimitive` for the string from inside `ToPrimitive`.
    let text = match &this {
        Value::String(text) => text.clone(),
        Value::Object(object) => match interp.internal_get(object, "_value") {
            Some(Value::String(text)) => text,
            _ => return Err(interp.type_error("String.prototype.toString requires a string")),
        },
        _ => return Err(interp.type_error("String.prototype.toString requires a string")),
    };
    let text = text.wtf8().clone();
    Ok(interp.string_wtf8(text))
}

/// §7.1.11 `ToUint16`, through `ToNumber`.
///
/// `ToNumber` is the observable half (`ToPrimitive`, and a `TypeError` for a BigInt), and
/// the modulo is the other: `ToUint16(Infinity)` is `0`, and `-1` is `65535`.
fn to_uint16(interp: &mut Interp<'_>, value: &Value) -> JsResult<u16> {
    let number = interp.to_js_number(value)?;
    if !number.is_finite() {
        return Ok(0);
    }
    let modulo = number.trunc().rem_euclid(65536.0);
    Ok(modulo as u16)
}