-
-
Notifications
You must be signed in to change notification settings - Fork 415
/
Copy pathmod.rs
2797 lines (2455 loc) · 111 KB
/
mod.rs
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
//! Boa's implementation of ECMAScript's global `String` object.
//!
//! The `String` global object is a constructor for strings or a sequence of characters.
//!
//! More information:
//! - [ECMAScript reference][spec]
//! - [MDN documentation][mdn]
//!
//! [spec]: https://tc39.es/ecma262/#sec-string-object
//! [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String
use crate::{
builtins::{Array, BuiltInObject, Number, RegExp},
context::intrinsics::{Intrinsics, StandardConstructor, StandardConstructors},
error::JsNativeError,
js_string,
object::{internal_methods::get_prototype_from_constructor, JsObject},
property::{Attribute, PropertyDescriptor},
realm::Realm,
string::{CodePoint, StaticJsStrings},
symbol::JsSymbol,
value::IntegerOrInfinity,
Context, JsArgs, JsResult, JsString, JsValue,
};
use boa_macros::utf16;
use boa_profiler::Profiler;
use icu_normalizer::{ComposingNormalizer, DecomposingNormalizer};
use std::cmp::{max, min};
use super::{BuiltInBuilder, BuiltInConstructor, IntrinsicObject};
mod string_iterator;
pub(crate) use string_iterator::StringIterator;
#[cfg(feature = "annex-b")]
pub use crate::{js_str, JsStr};
/// The set of normalizers required for the `String.prototype.normalize` function.
#[derive(Debug)]
pub(crate) struct StringNormalizers {
pub(crate) nfc: ComposingNormalizer,
pub(crate) nfkc: ComposingNormalizer,
pub(crate) nfd: DecomposingNormalizer,
pub(crate) nfkd: DecomposingNormalizer,
}
#[cfg(test)]
mod tests;
#[derive(Clone, Copy, Eq, PartialEq)]
pub(crate) enum Placement {
Start,
End,
}
/// Helper function to check if a `char` is trimmable.
pub(crate) const fn is_trimmable_whitespace(c: char) -> bool {
// The rust implementation of `trim` does not regard the same characters whitespace as ecma standard does
//
// Rust uses \p{White_Space} by default, which also includes:
// `\u{0085}' (next line)
// And does not include:
// '\u{FEFF}' (zero width non-breaking space)
// Explicit whitespace: https://tc39.es/ecma262/#sec-white-space
matches!(
c,
'\u{0009}' | '\u{000B}' | '\u{000C}' | '\u{0020}' | '\u{00A0}' | '\u{FEFF}' |
// Unicode Space_Separator category
'\u{1680}' | '\u{2000}'
..='\u{200A}' | '\u{202F}' | '\u{205F}' | '\u{3000}' |
// Line terminators: https://tc39.es/ecma262/#sec-line-terminators
'\u{000A}' | '\u{000D}' | '\u{2028}' | '\u{2029}'
)
}
/// JavaScript `String` implementation.
#[derive(Debug, Clone, Copy)]
pub(crate) struct String;
impl IntrinsicObject for String {
fn init(realm: &Realm) {
let _timer = Profiler::global().start_event(std::any::type_name::<Self>(), "init");
let trim_start = BuiltInBuilder::callable(realm, Self::trim_start)
.length(0)
.name(js_string!("trimStart"))
.build();
let trim_end = BuiltInBuilder::callable(realm, Self::trim_end)
.length(0)
.name(js_string!("trimEnd"))
.build();
#[cfg(feature = "annex-b")]
let trim_left = trim_start.clone();
#[cfg(feature = "annex-b")]
let trim_right = trim_end.clone();
let attribute = Attribute::READONLY | Attribute::NON_ENUMERABLE | Attribute::PERMANENT;
let builder = BuiltInBuilder::from_standard_constructor::<Self>(realm)
.property(js_string!("length"), 0, attribute)
.property(
js_string!("trimStart"),
trim_start,
Attribute::WRITABLE | Attribute::NON_ENUMERABLE | Attribute::CONFIGURABLE,
)
.property(
js_string!("trimEnd"),
trim_end,
Attribute::WRITABLE | Attribute::NON_ENUMERABLE | Attribute::CONFIGURABLE,
)
.static_method(Self::raw, js_string!("raw"), 1)
.static_method(Self::from_char_code, js_string!("fromCharCode"), 1)
.static_method(Self::from_code_point, js_string!("fromCodePoint"), 1)
.method(Self::char_at, js_string!("charAt"), 1)
.method(Self::char_code_at, js_string!("charCodeAt"), 1)
.method(Self::code_point_at, js_string!("codePointAt"), 1)
.method(Self::to_string, js_string!("toString"), 0)
.method(Self::concat, js_string!("concat"), 1)
.method(Self::repeat, js_string!("repeat"), 1)
.method(Self::slice, js_string!("slice"), 2)
.method(Self::starts_with, js_string!("startsWith"), 1)
.method(Self::ends_with, js_string!("endsWith"), 1)
.method(Self::includes, js_string!("includes"), 1)
.method(Self::index_of, js_string!("indexOf"), 1)
.method(Self::is_well_formed, js_string!("isWellFormed"), 0)
.method(Self::last_index_of, js_string!("lastIndexOf"), 1)
.method(Self::locale_compare, js_string!("localeCompare"), 1)
.method(Self::r#match, js_string!("match"), 1)
.method(Self::normalize, js_string!("normalize"), 0)
.method(Self::pad_end, js_string!("padEnd"), 1)
.method(Self::pad_start, js_string!("padStart"), 1)
.method(Self::trim, js_string!("trim"), 0)
.method(Self::to_case::<false>, js_string!("toLowerCase"), 0)
.method(Self::to_case::<true>, js_string!("toUpperCase"), 0)
.method(Self::to_well_formed, js_string!("toWellFormed"), 0)
.method(
Self::to_locale_case::<false>,
js_string!("toLocaleLowerCase"),
0,
)
.method(
Self::to_locale_case::<true>,
js_string!("toLocaleUpperCase"),
0,
)
.method(Self::substring, js_string!("substring"), 2)
.method(Self::split, js_string!("split"), 2)
.method(Self::value_of, js_string!("valueOf"), 0)
.method(Self::match_all, js_string!("matchAll"), 1)
.method(Self::replace, js_string!("replace"), 2)
.method(Self::replace_all, js_string!("replaceAll"), 2)
.method(Self::iterator, JsSymbol::iterator(), 0)
.method(Self::search, js_string!("search"), 1)
.method(Self::at, js_string!("at"), 1);
#[cfg(feature = "annex-b")]
let builder = {
builder
.property(
js_string!("trimLeft"),
trim_left,
Attribute::WRITABLE | Attribute::NON_ENUMERABLE | Attribute::CONFIGURABLE,
)
.property(
js_string!("trimRight"),
trim_right,
Attribute::WRITABLE | Attribute::NON_ENUMERABLE | Attribute::CONFIGURABLE,
)
.method(Self::substr, js_string!("substr"), 2)
.method(Self::anchor, js_string!("anchor"), 1)
.method(Self::big, js_string!("big"), 0)
.method(Self::blink, js_string!("blink"), 0)
.method(Self::bold, js_string!("bold"), 0)
.method(Self::fixed, js_string!("fixed"), 0)
.method(Self::fontcolor, js_string!("fontcolor"), 1)
.method(Self::fontsize, js_string!("fontsize"), 1)
.method(Self::italics, js_string!("italics"), 0)
.method(Self::link, js_string!("link"), 1)
.method(Self::small, js_string!("small"), 0)
.method(Self::strike, js_string!("strike"), 0)
.method(Self::sub, js_string!("sub"), 0)
.method(Self::sup, js_string!("sup"), 0)
};
builder.build();
}
fn get(intrinsics: &Intrinsics) -> JsObject {
Self::STANDARD_CONSTRUCTOR(intrinsics.constructors()).constructor()
}
}
impl BuiltInObject for String {
const NAME: JsString = StaticJsStrings::STRING;
}
impl BuiltInConstructor for String {
const LENGTH: usize = 1;
const P: usize = 36;
const SP: usize = 3;
const STANDARD_CONSTRUCTOR: fn(&StandardConstructors) -> &StandardConstructor =
StandardConstructors::string;
/// Constructor `String( value )`
///
/// <https://tc39.es/ecma262/#sec-string-constructor-string-value>
fn constructor(
new_target: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// This value is used by console.log and other routines to match Object type
// to its Javascript Identifier (global constructor method name)
let string = match args.first() {
// 2. Else,
// a. If NewTarget is undefined and Type(value) is Symbol, return SymbolDescriptiveString(value).
Some(JsValue::Symbol(ref sym)) if new_target.is_undefined() => {
return Ok(sym.descriptive_string().into())
}
// b. Let s be ? ToString(value).
Some(value) => value.to_string(context)?,
// 1. If value is not present, let s be the empty String.
None => js_string!(),
};
// 3. If NewTarget is undefined, return s.
if new_target.is_undefined() {
return Ok(string.into());
}
let prototype =
get_prototype_from_constructor(new_target, StandardConstructors::string, context)?;
// 4. Return ! StringCreate(s, ? GetPrototypeFromConstructor(NewTarget, "%String.prototype%")).
Ok(Self::string_create(string, prototype, context).into())
}
}
impl String {
/// JavaScript strings must be between `0` and less than positive `Infinity` and cannot be a negative number.
/// The range of allowed values can be described like this: `[0, +∞)`.
///
/// The resulting string can also not be larger than the maximum string size,
/// which can differ in JavaScript engines. In Boa it is `2^32 - 1`
pub(crate) const MAX_STRING_LENGTH: usize = u32::MAX as usize;
/// Abstract function `StringCreate( value, prototype )`.
///
/// Call this function if you want to create a `String` exotic object.
///
/// More information:
/// - [ECMAScript reference][spec]
///
/// [spec]: https://tc39.es/ecma262/#sec-stringcreate
fn string_create(value: JsString, prototype: JsObject, context: &mut Context) -> JsObject {
// 7. Let length be the number of code unit elements in value.
let len = value.len();
// 1. Let S be ! MakeBasicObject(« [[Prototype]], [[Extensible]], [[StringData]] »).
// 2. Set S.[[Prototype]] to prototype.
// 3. Set S.[[StringData]] to value.
// 4. Set S.[[GetOwnProperty]] as specified in 10.4.3.1.
// 5. Set S.[[DefineOwnProperty]] as specified in 10.4.3.2.
// 6. Set S.[[OwnPropertyKeys]] as specified in 10.4.3.3.
let s =
JsObject::from_proto_and_data_with_shared_shape(context.root_shape(), prototype, value);
// 8. Perform ! DefinePropertyOrThrow(S, "length", PropertyDescriptor { [[Value]]: 𝔽(length),
// [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }).
s.define_property_or_throw(
StaticJsStrings::LENGTH,
PropertyDescriptor::builder()
.value(len)
.writable(false)
.enumerable(false)
.configurable(false),
context,
)
.expect("length definition for a new string must not fail");
// 9. Return S.
s
}
/// Abstract operation `thisStringValue( value )`
///
/// More information:
/// - [ECMAScript reference][spec]
///
/// [spec]: https://tc39.es/ecma262/#thisstringvalue
fn this_string_value(this: &JsValue) -> JsResult<JsString> {
// 1. If Type(value) is String, return value.
this.as_string()
.cloned()
// 2. If Type(value) is Object and value has a [[StringData]] internal slot, then
// a. Let s be value.[[StringData]].
// b. Assert: Type(s) is String.
// c. Return s.
.or_else(|| {
this.as_object()
.and_then(|obj| obj.downcast_ref::<JsString>().as_deref().cloned())
})
// 3. Throw a TypeError exception.
.ok_or_else(|| {
JsNativeError::typ()
.with_message("'this' is not a string")
.into()
})
}
/// `String.fromCodePoint(num1[, ...[, numN]])`
///
/// The static `String.fromCodePoint()` method returns a string created by using the specified sequence of code points.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-string.fromcodepoint
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCodePoint
pub(crate) fn from_code_point(
_: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let result be the empty String.
let mut result = Vec::with_capacity(args.len());
let mut buf = [0; 2];
// 2. For each element next of codePoints, do
for arg in args {
// a. Let nextCP be ? ToNumber(next).
let nextcp = arg.to_number(context)?;
// b. If ! IsIntegralNumber(nextCP) is false, throw a RangeError exception.
if !Number::is_float_integer(nextcp) {
return Err(JsNativeError::range()
.with_message(format!("codepoint `{nextcp}` is not an integer"))
.into());
}
// c. If ℝ(nextCP) < 0 or ℝ(nextCP) > 0x10FFFF, throw a RangeError exception.
if nextcp < 0.0 || nextcp > f64::from(0x0010_FFFF) {
return Err(JsNativeError::range()
.with_message(format!("codepoint `{nextcp}` outside of Unicode range"))
.into());
}
// SAFETY:
// - `nextcp` is not NaN (by the call to `is_float_integer`).
// - `nextcp` is not infinite (by the call to `is_float_integer`).
// - `nextcp` is in the u32 range (by the check above).
let nextcp = unsafe { nextcp.to_int_unchecked::<u32>() };
// d. Set result to the string-concatenation of result and ! UTF16EncodeCodePoint(ℝ(nextCP)).
result.extend_from_slice(match u16::try_from(nextcp) {
Ok(ref cp) => std::slice::from_ref(cp),
Err(_) => char::from_u32(nextcp)
.expect("u32 is in range and cannot be a surrogate by the conversion above")
.encode_utf16(&mut buf),
});
}
// 3. Assert: If codePoints is empty, then result is the empty String.
// 4. Return result.
Ok(js_string!(&result[..]).into())
}
/// `String.raw( template, ...substitutions )`
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-string.raw
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/raw
pub(crate) fn raw(_: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
let substitutions = args.get(1..).unwrap_or_default();
// 1. Let numberOfSubstitutions be the number of elements in substitutions.
let number_of_substitutions = substitutions.len() as u64;
// 2. Let cooked be ? ToObject(template).
let cooked = args.get_or_undefined(0).to_object(context)?;
// 3. Let raw be ? ToObject(? Get(cooked, "raw")).
let raw = cooked.get(js_string!("raw"), context)?.to_object(context)?;
// 4. Let literalSegments be ? LengthOfArrayLike(raw).
let literal_segments = raw.length_of_array_like(context)?;
// 5. If literalSegments ≤ 0, return the empty String.
// This is not <= because a `usize` is always positive.
if literal_segments == 0 {
return Ok(js_string!().into());
}
// 6. Let stringElements be a new empty List.
let mut string_elements = vec![];
// 7. Let nextIndex be 0.
let mut next_index = 0;
// 8. Repeat,
loop {
// a. Let nextKey be ! ToString(𝔽(nextIndex)).
let next_key = next_index;
// b. Let nextSeg be ? ToString(? Get(raw, nextKey)).
let next_seg = raw.get(next_key, context)?.to_string(context)?;
// c. Append the code unit elements of nextSeg to the end of stringElements.
string_elements.extend(next_seg.iter());
// d. If nextIndex + 1 = literalSegments, then
if next_index + 1 == literal_segments {
// i. Return the String value whose code units are the elements in the List stringElements.
// If stringElements has no elements, the empty String is returned.
return Ok(js_string!(&string_elements[..]).into());
}
// e. If nextIndex < numberOfSubstitutions, let next be substitutions[nextIndex].
let next = if next_index < number_of_substitutions {
substitutions.get_or_undefined(next_index as usize).clone()
// f. Else, let next be the empty String.
} else {
js_string!().into()
};
// g. Let nextSub be ? ToString(next).
let next_sub = next.to_string(context)?;
// h. Append the code unit elements of nextSub to the end of stringElements.
string_elements.extend(next_sub.iter());
// i. Set nextIndex to nextIndex + 1.
next_index += 1;
}
}
/// `String.fromCharCode(...codeUnits)`
///
/// Construct a `String` from one or more code points (as numbers).
/// More information:
/// - [ECMAScript reference][spec]
///
/// [spec]: https://tc39.es/ecma262/multipage/text-processing.html#sec-string.fromcharcode
pub(crate) fn from_char_code(
_: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let result be the empty String.
let mut result = Vec::new();
// 2. For each element next of codeUnits, do
for next in args {
// a. Let nextCU be the code unit whose numeric value is ℝ(? ToUint16(next)).
let next_cu = next.to_uint16(context)?;
// b. Set result to the string-concatenation of result and nextCU.
result.push(next_cu);
}
// 3. Return result.
Ok(js_string!(&result[..]).into())
}
/// `String.prototype.toString ( )`
///
/// More information:
/// - [ECMAScript reference][spec]
///
/// [spec]: https://tc39.es/ecma262/#sec-string.prototype.tostring
#[allow(clippy::wrong_self_convention)]
pub(crate) fn to_string(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult<JsValue> {
// 1. Return ? thisStringValue(this value).
Ok(Self::this_string_value(this)?.into())
}
/// `String.prototype.charAt( index )`
///
/// The `String` object's `charAt()` method returns a new string consisting of the single UTF-16 code unit located at the specified offset into the string.
///
/// Characters in a string are indexed from left to right. The index of the first character is `0`,
/// and the index of the last character—in a string called `stringName`—is `stringName.length - 1`.
/// If the `index` you supply is out of this range, JavaScript returns an empty string.
///
/// If no index is provided to `charAt()`, the default is `0`.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-string.prototype.charat
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charAt
pub(crate) fn char_at(
this: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let O be ? RequireObjectCoercible(this value).
let this = this.require_object_coercible()?;
// 2. Let S be ? ToString(O).
let string = this.to_string(context)?;
// 3. Let position be ? ToIntegerOrInfinity(pos).
let position = args.get_or_undefined(0).to_integer_or_infinity(context)?;
match position {
// 4. Let size be the length of S.
// 6. Return the substring of S from position to position + 1.
IntegerOrInfinity::Integer(i) if i >= 0 && i < string.len() as i64 => {
let i = i as usize;
Ok(js_string!(string.get_expect(i..=i)).into())
}
// 5. If position < 0 or position ≥ size, return the empty String.
_ => Ok(js_string!().into()),
}
}
/// `String.prototype.at ( index )`
///
/// This String object's `at()` method returns a String consisting of the single UTF-16 code unit located at the specified position.
/// Returns undefined if the given index cannot be found.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/proposal-relative-indexing-method/#sec-string.prototype.at
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/at
pub(crate) fn at(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
// 1. Let O be ? RequireObjectCoercible(this value).
let this = this.require_object_coercible()?;
// 2. Let S be ? ToString(O).
let s = this.to_string(context)?;
// 3. Let len be the length of S.
let len = s.len() as i64;
// 4. Let relativeIndex be ? ToIntegerOrInfinity(index).
let relative_index = args.get_or_undefined(0).to_integer_or_infinity(context)?;
let k = match relative_index {
// 5. If relativeIndex ≥ 0, then
// a. Let k be relativeIndex.
IntegerOrInfinity::Integer(i) if i >= 0 && i < len => i as usize,
// 6. Else,
// a. Let k be len + relativeIndex.
IntegerOrInfinity::Integer(i) if i < 0 && (-i) <= len => (len + i) as usize,
// 7. If k < 0 or k ≥ len, return undefined.
_ => return Ok(JsValue::undefined()),
};
// 8. Return the substring of S from k to k + 1.
Ok(js_string!(s.get_expect(k..=k)).into())
}
/// `String.prototype.codePointAt( index )`
///
/// The `codePointAt()` method returns an integer between `0` to `1114111` (`0x10FFFF`) representing the UTF-16 code unit at the given index.
///
/// If no UTF-16 surrogate pair begins at the index, the code point at the index is returned.
///
/// `codePointAt()` returns `undefined` if the given index is less than `0`, or if it is equal to or greater than the `length` of the string.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-string.prototype.codepointat
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/codePointAt
pub(crate) fn code_point_at(
this: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let O be ? RequireObjectCoercible(this value).
let this = this.require_object_coercible()?;
// 2. Let S be ? ToString(O).
let string = this.to_string(context)?;
// 3. Let position be ? ToIntegerOrInfinity(pos).
let position = args.get_or_undefined(0).to_integer_or_infinity(context)?;
match position {
// 4. Let size be the length of S.
IntegerOrInfinity::Integer(i) if i >= 0 && i < string.len() as i64 => {
// 6. Let cp be ! CodePointAt(S, position).
// 7. Return 𝔽(cp.[[CodePoint]]).
Ok(string
.code_point_at(usize::try_from(i).expect("already checked that i >= 0"))
.as_u32()
.into())
}
// 5. If position < 0 or position ≥ size, return undefined.
_ => Ok(JsValue::undefined()),
}
}
/// `String.prototype.charCodeAt( index )`
///
/// The `charCodeAt()` method returns an integer between `0` and `65535` representing the UTF-16 code unit at the given index.
///
/// Unicode code points range from `0` to `1114111` (`0x10FFFF`). The first 128 Unicode code points are a direct match of the ASCII character encoding.
///
/// `charCodeAt()` returns `NaN` if the given index is less than `0`, or if it is equal to or greater than the `length` of the string.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-string.prototype.charcodeat
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charCodeAt
pub(crate) fn char_code_at(
this: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let O be ? RequireObjectCoercible(this value).
let this = this.require_object_coercible()?;
// 2. Let S be ? ToString(O).
let string = this.to_string(context)?;
// 3. Let position be ? ToIntegerOrInfinity(pos).
let position = args.get_or_undefined(0).to_integer_or_infinity(context)?;
match position {
// 4. Let size be the length of S.
IntegerOrInfinity::Integer(i) if i >= 0 => {
// 6. Return the Number value for the numeric value of the code unit at index position within the String S.
Ok(string
.get(i as usize)
.map_or_else(JsValue::nan, JsValue::from))
}
// 5. If position < 0 or position ≥ size, return NaN.
_ => Ok(JsValue::nan()),
}
}
/// `String.prototype.concat( str1[, ...strN] )`
///
/// The `concat()` method concatenates the string arguments to the calling string and returns a new string.
///
/// Changes to the original string or the returned string don't affect the other.
///
/// If the arguments are not of the type string, they are converted to string values before concatenating.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-string.prototype.concat
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/concat
pub(crate) fn concat(
this: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let O be ? RequireObjectCoercible(this value).
let this = this.require_object_coercible()?;
// 2. Let S be ? ToString(O).
let mut string = this.to_string(context)?;
// 3. Let R be S.
// 4. For each element next of args, do
for arg in args {
// a. Let nextString be ? ToString(next).
// b. Set R to the string-concatenation of R and nextString.
string = js_string!(&string, &arg.to_string(context)?);
}
// 5. Return R.
Ok(JsValue::new(string))
}
/// `String.prototype.repeat( count )`
///
/// The `repeat()` method constructs and returns a new string which contains the specified number of
/// copies of the string on which it was called, concatenated together.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-string.prototype.repeat
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat
pub(crate) fn repeat(
this: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let O be ? RequireObjectCoercible(this value).
let this = this.require_object_coercible()?;
// 2. Let S be ? ToString(O).
let string = this.to_string(context)?;
let len = string.len();
// 3. Let n be ? ToIntegerOrInfinity(count).
match args.get_or_undefined(0).to_integer_or_infinity(context)? {
IntegerOrInfinity::Integer(n)
if n > 0 && (n as usize) * len <= Self::MAX_STRING_LENGTH =>
{
if string.is_empty() {
return Ok(js_string!().into());
}
let n = n as usize;
let mut result = Vec::with_capacity(n);
std::iter::repeat(string.as_str())
.take(n)
.for_each(|s| result.push(s));
// 6. Return the String value that is made from n copies of S appended together.
Ok(JsString::concat_array(&result).into())
}
// 5. If n is 0, return the empty String.
IntegerOrInfinity::Integer(0) => Ok(js_string!().into()),
// 4. If n < 0 or n is +∞, throw a RangeError exception.
_ => Err(JsNativeError::range()
.with_message(
"repeat count must be a positive finite number \
that doesn't overflow the maximum string length (2^32 - 1)",
)
.into()),
}
}
/// `String.prototype.slice( beginIndex [, endIndex] )`
///
/// The `slice()` method extracts a section of a string and returns it as a new string, without modifying the original string.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-string.prototype.slice
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice
pub(crate) fn slice(
this: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let O be ? RequireObjectCoercible(this value).
let this = this.require_object_coercible()?;
// 2. Let S be ? ToString(O).
let string = this.to_string(context)?;
// 3. Let len be the length of S.
let len = string.len() as i64;
// 4. Let intStart be ? ToIntegerOrInfinity(start).
let from = match args.get_or_undefined(0).to_integer_or_infinity(context)? {
// 6. Else if intStart < 0, let from be max(len + intStart, 0).
IntegerOrInfinity::Integer(i) if i < 0 => max(len + i, 0),
// 7. Else, let from be min(intStart, len).
IntegerOrInfinity::Integer(i) => min(i, len),
IntegerOrInfinity::PositiveInfinity => len,
// 5. If intStart is -∞, let from be 0.
IntegerOrInfinity::NegativeInfinity => 0,
} as usize;
// 8. If end is undefined, let intEnd be len; else let intEnd be ? ToIntegerOrInfinity(end).
let to = match args
.get(1)
.filter(|end| !end.is_undefined())
.map(|end| end.to_integer_or_infinity(context))
.transpose()?
.unwrap_or(IntegerOrInfinity::Integer(len))
{
// 10. Else if intEnd < 0, let to be max(len + intEnd, 0).
IntegerOrInfinity::Integer(i) if i < 0 => max(len + i, 0),
// 11. Else, let to be min(intEnd, len).
IntegerOrInfinity::Integer(i) => min(i, len),
IntegerOrInfinity::PositiveInfinity => len,
// 9. If intEnd is -∞, let to be 0.
IntegerOrInfinity::NegativeInfinity => 0,
} as usize;
// 12. If from ≥ to, return the empty String.
if from >= to {
Ok(js_string!().into())
} else {
// 13. Return the substring of S from from to to.
Ok(js_string!(string.get_expect(from..to)).into())
}
}
/// `String.prototype.startWith( searchString[, position] )`
///
/// The `startsWith()` method determines whether a string begins with the characters of a specified string, returning `true` or `false` as appropriate.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-string.prototype.startswith
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith
pub(crate) fn starts_with(
this: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let O be ? RequireObjectCoercible(this value).
let this = this.require_object_coercible()?;
// 2. Let S be ? ToString(O).
let string = this.to_string(context)?;
let search_string = args.get_or_undefined(0);
// 3. Let isRegExp be ? IsRegExp(searchString).
// 4. If isRegExp is true, throw a TypeError exception.
if RegExp::is_reg_exp(search_string, context)?.is_some() {
return Err(JsNativeError::typ().with_message(
"First argument to String.prototype.startsWith must not be a regular expression",
).into());
}
// 5. Let searchStr be ? ToString(searchString).
let search_string = search_string.to_string(context)?;
// 6. Let len be the length of S.
let len = string.len() as i64;
// 7. If position is undefined, let pos be 0; else let pos be ? ToIntegerOrInfinity(position).
let pos = match args.get_or_undefined(1) {
&JsValue::Undefined => IntegerOrInfinity::Integer(0),
position => position.to_integer_or_infinity(context)?,
};
// 8. Let start be the result of clamping pos between 0 and len.
let start = pos.clamp_finite(0, len) as usize;
// 9. Let searchLength be the length of searchStr.
let search_length = search_string.len();
// 10. If searchLength = 0, return true.
if search_length == 0 {
return Ok(JsValue::new(true));
}
// 11. Let end be start + searchLength.
let end = start + search_length;
// 12. If end > len, return false.
if end > len as usize {
Ok(JsValue::new(false))
} else {
// 13. Let substring be the substring of S from start to end.
// 14. Return ! SameValueNonNumeric(substring, searchStr).
// `SameValueNonNumeric` forwards to `==`, so directly check
// equality to avoid converting to `JsValue`
Ok(JsValue::new(search_string == string.get_expect(start..end)))
}
}
/// `String.prototype.endsWith( searchString[, length] )`
///
/// The `endsWith()` method determines whether a string ends with the characters of a specified string, returning `true` or `false` as appropriate.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-string.prototype.endswith
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
pub(crate) fn ends_with(
this: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let O be ? RequireObjectCoercible(this value).
let this = this.require_object_coercible()?;
// 2. Let S be ? ToString(O).
let string = this.to_string(context)?;
let search_str = match args.get_or_undefined(0) {
// 3. Let isRegExp be ? IsRegExp(searchString).
// 4. If isRegExp is true, throw a TypeError exception.
search_string if RegExp::is_reg_exp(search_string, context)?.is_some() => {
return Err(JsNativeError::typ().with_message(
"First argument to String.prototype.endsWith must not be a regular expression",
).into());
}
// 5. Let searchStr be ? ToString(searchString).
search_string => search_string.to_string(context)?,
};
// 6. Let len be the length of S.
let len = string.len() as i64;
// 7. If endPosition is undefined, let pos be len; else let pos be ? ToIntegerOrInfinity(endPosition).
let end = match args.get_or_undefined(1) {
end_position if end_position.is_undefined() => IntegerOrInfinity::Integer(len),
end_position => end_position.to_integer_or_infinity(context)?,
};
// 8. Let end be the result of clamping pos between 0 and len.
let end = end.clamp_finite(0, len) as usize;
// 9. Let searchLength be the length of searchStr.
let search_length = search_str.len();
// 10. If searchLength = 0, return true.
if search_length == 0 {
return Ok(true.into());
}
// 11. Let start be end - searchLength.
if let Some(start) = end.checked_sub(search_length) {
// 13. Let substring be the substring of S from start to end.
// 14. Return ! SameValueNonNumeric(substring, searchStr).
// `SameValueNonNumeric` forwards to `==`, so directly check
// equality to avoid converting to `JsValue`
Ok(JsValue::new(search_str == string.get_expect(start..end)))
} else {
// 12. If start < 0, return false.
Ok(false.into())
}
}
/// `String.prototype.includes( searchString[, position] )`
///
/// The `includes()` method determines whether one string may be found within another string, returning `true` or `false` as appropriate.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-string.prototype.includes
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes
pub(crate) fn includes(
this: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let O be ? RequireObjectCoercible(this value).
let this = this.require_object_coercible()?;
// 2. Let S be ? ToString(O).
let string = this.to_string(context)?;
let search_str = match args.get_or_undefined(0) {
// 3. Let isRegExp be ? IsRegExp(searchString).
search_string if RegExp::is_reg_exp(search_string, context)?.is_some() => {
return Err(JsNativeError::typ().with_message(
// 4. If isRegExp is true, throw a TypeError exception.
"First argument to String.prototype.includes must not be a regular expression",
).into());
}
// 5. Let searchStr be ? ToString(searchString).
search_string => search_string.to_string(context)?,
};
// 6. Let pos be ? ToIntegerOrInfinity(position).
// 7. Assert: If position is undefined, then pos is 0.
let pos = args.get_or_undefined(1).to_integer_or_infinity(context)?;
// 8. Let len be the length of S.
// 9. Let start be the result of clamping pos between 0 and len.
let start = pos.clamp_finite(0, string.len() as i64) as usize;
// 10. Let index be ! StringIndexOf(S, searchStr, start).
// 11. If index is not -1, return true.
// 12. Return false.
Ok(string.index_of(search_str.as_str(), start).is_some().into())
}
/// `String.prototype.replace( regexp|substr, newSubstr|function )`
///
/// The `replace()` method returns a new string with some or all matches of a `pattern` replaced by a `replacement`.
///
/// The `pattern` can be a string or a `RegExp`, and the `replacement` can be a string or a function to be called for each match.
/// If `pattern` is a string, only the first occurrence will be replaced.
///
/// The original string is left unchanged.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-string.prototype.replace