quickjs-pure 0.12.0

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

    // `String.prototype[Symbol.iterator]` walks the UTF-16 code units. `array::values`
    // already does exactly that when handed a string primitive โ€” see `element_at` โ€” so
    // the function is shared rather than reimplemented.
    if let Some(values_fn) = interp
        .realm
        .array_proto
        .own_property("values")
        .and_then(|property| property.value)
    {
        let key = interp
            .realm
            .well_known_key(crate::interp::WellKnown::Iterator);
        string_proto.define_key(&key, Property::data(values_fn));
    }

    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]`.
    let text = match args.first() {
        Some(value) => interp.to_js_string(value)?,
        None => String::new(),
    };
    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")?;
    let length = interp.read_field(&chunks, "length")?.to_number().max(0.0) as usize;
    let mut out = String::new();
    for index in 0..length {
        let chunk = interp.read_field(&chunks, &index.to_string())?;
        out.push_str(&interp.to_js_string(&chunk)?);
        if index + 1 < length {
            if let Some(value) = args.get(index + 1) {
                out.push_str(&interp.to_js_string(value)?);
            }
        }
    }
    Ok(interp.string(out))
}

fn from_char_code(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    // `fromCharCode` takes UTF-16 code units, so surrogates can be assembled by hand.
    let units: Vec<u16> = args
        .iter()
        .map(|value| (value.to_number() as i64 & 0xffff) as u16)
        .collect();
    // 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 {
        let code = value.to_number();
        if !(0.0..=0x10ffff as f64).contains(&code) {
            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: &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),
            _ => Err(interp.type_error("String method on a non-string")),
        },
        _ => Err(interp.type_error("String method on a non-string")),
    }
}

/// 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_int_or(args, 0, 0), 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_int_or(args, 0, 0);
    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_int_or(args, 0, 0), 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_int_or(args, 0, 0);
    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 = arg(args, 0).to_js_string();
    // 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_int_or(args, 1, 0).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 = arg(args, 0).to_js_string();
    // 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(),
        Some(value) => {
            let position = value.to_number();
            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)?;
    let needle = arg(args, 0).to_js_string();
    Ok(Value::Bool(text.contains(&needle)))
}

fn starts_with(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let text = text_of(interp, &this)?;
    let needle = arg(args, 0).to_js_string();
    let start = (arg_int_or(args, 1, 0).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)?;
    let needle = arg(args, 0).to_js_string();
    let end = match args.get(1) {
        None | Some(Value::Undefined) => text.len(),
        Some(value) => clamp(value.to_number(), 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 = text_of(interp, &this)?;
    let other = arg(args, 0).to_js_string();
    Ok(Value::Int(match text.cmp(&other) {
        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_int_or(args, 0, 0) as f64, text.len());
    let end = match args.get(1) {
        None | Some(Value::Undefined) => text.len(),
        Some(value) => clamp(value.to_number(), 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_int_or(args, 0, 0).max(0) as f64;
    let b = match args.get(1) {
        None | Some(Value::Undefined) => length,
        Some(value) => value.to_number().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_int_or(args, 0, 0) 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])))
}

fn split(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let text = text_of(interp, &this)?;
    if let Some(result) = symbol_dispatch(interp, &this, WellKnown::Split, args)? {
        return Ok(result);
    }
    let limit = match args.get(1) {
        None | Some(Value::Undefined) => usize::MAX,
        Some(value) => value.to_number().max(0.0) as usize,
    };
    let parts: Vec<Value> = match arg(args, 0) {
        // `"abc".split()` is `["abc"]`; `"".split()` is `[]`.
        Value::Undefined => {
            if text.is_empty() {
                Vec::new()
            } else {
                vec![interp.string(text)]
            }
        }
        // `ToString(separator)`, not "leave any other kind alone". An object separator runs
        // its `toString`, and if that answers an object `ToPrimitive` throws โ€” which is what
        // `transferred-to-number-separator-override-tostring-returns-regexp` asserts. The
        // `Symbol.split` dispatch above already handled a real RegExp.
        separator => {
            let separator = interp.to_js_string(&separator)?;
            if separator.is_empty() {
                text.chars()
                    .map(|character| interp.string(character.to_string()))
                    .collect()
            } else {
                text.split(&*separator)
                    .map(|part| interp.string(part.to_string()))
                    .collect()
            }
        }
    };
    let limited: Vec<Value> = parts.into_iter().take(limit).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 {
        text.push_str(&value.to_js_string());
    }
    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,
                    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.8, 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.
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)`.
fn match_method(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    if let Some(result) = symbol_dispatch(interp, &this, WellKnown::Match, args)? {
        return Ok(result);
    }
    // A plain string pattern matches itself once, and reports the index.
    let text = text_of(interp, &this)?;
    let pattern = arg(args, 0).to_js_string();
    let Some(offset) = text.find(&pattern) else {
        return Ok(Value::Null);
    };
    let array = interp.new_array(vec![interp.string(&pattern)]);
    interp.set_property(&array, "index", Value::Int(offset as i32))?;
    interp.set_property(&array, "input", interp.string(&text))?;
    Ok(Value::Object(array))
}

/// `String.prototype.matchAll(pattern)`.
fn match_all(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    if let Some(result) = symbol_dispatch(interp, &this, WellKnown::MatchAll, args)? {
        return Ok(result);
    }
    Err(interp.type_error("matchAll needs a global RegExp"))
}

/// `String.prototype.search(pattern)`.
fn search(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    if let Some(result) = symbol_dispatch(interp, &this, WellKnown::Search, args)? {
        return Ok(result);
    }
    let text = text_of(interp, &this)?;
    let pattern = arg(args, 0).to_js_string();
    Ok(match text.find(&pattern) {
        Some(offset) => Value::Int(offset as i32),
        None => Value::Int(-1),
    })
}

// ---------------------------------------------------------------------------
// 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)))
}

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))
}

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

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

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

fn repeat(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let text = text_of(interp, &this)?;
    let count = arg_number_int(args, 0);
    if count < 0 {
        return Err(interp.range_error("repeat count must not be negative"));
    }
    Ok(interp.string(text.repeat(count as usize)))
}

fn arg_number_int(args: &[Value], index: usize) -> i64 {
    arg(args, index).to_number() as i64
}

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> {
    let text = string_object(interp, &this)?.wtf8().clone();
    Ok(interp.string_wtf8(text))
}