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
//! This module implements the 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 #[cfg(test)] mod tests; use super::function::make_constructor_fn; use crate::{ builtins::{ object::{Object, ObjectKind}, property::Property, regexp::{make_regexp, match_all as regexp_match_all, r#match as regexp_match}, value::{ResultValue, Value, ValueData}, }, exec::Interpreter, }; use regex::Regex; use std::{ cmp::{max, min}, f64::NAN, ops::Deref, }; /// [[Construct]] - Creates a new instance `this` /// /// [[Call]] - Returns a new native `string` /// <https://tc39.es/ecma262/#sec-string-constructor-string-value> pub fn make_string(this: &mut Value, args: &[Value], _: &mut Interpreter) -> ResultValue { // This value is used by console.log and other routines to match Obexpecty"failed to parse argument for String method"pe // to its Javascript Identifier (global constructor method name) let s = args.get(0).unwrap_or(&Value::string("")).clone(); let length_str = s.to_string().chars().count(); this.set_field_slice("length", Value::from(length_str as i32)); this.set_kind(ObjectKind::String); this.set_internal_slot("StringData", s); let arg = match args.get(0) { Some(v) => v.clone(), None => Value::undefined(), }; if arg.is_undefined() { return Ok(Value::from(String::new())); } Ok(Value::from(arg.to_string())) } /// Get the string value to a primitive string pub fn to_string(this: &mut Value, _: &[Value], _: &mut Interpreter) -> ResultValue { // Get String from String Object and send it back as a new value let primitive_val = this.get_internal_slot("StringData"); Ok(Value::from(format!("{}", primitive_val))) } /// `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 fn char_at(this: &mut Value, args: &[Value], ctx: &mut Interpreter) -> ResultValue { // First we get it the actual string a private field stored on the object only the engine has access to. // Then we convert it into a Rust String by wrapping it in from_value let primitive_val = ctx.value_to_rust_string(this); let pos = i32::from( args.get(0) .expect("failed to get argument for String method"), ); // Calling .len() on a string would give the wrong result, as they are bytes not the number of // unicode code points // Note that this is an O(N) operation (because UTF-8 is complex) while getting the number of // bytes is an O(1) operation. let length = primitive_val.chars().count(); // We should return an empty string is pos is out of range if pos >= length as i32 || pos < 0 { return Ok(Value::from(String::new())); } Ok(Value::from( primitive_val .chars() .nth(pos as usize) .expect("failed to get value"), )) } /// `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 fn char_code_at(this: &mut Value, args: &[Value], ctx: &mut Interpreter) -> ResultValue { // First we get it the actual string a private field stored on the object only the engine has access to. // Then we convert it into a Rust String by wrapping it in from_value let primitive_val: String = ctx.value_to_rust_string(this); // Calling .len() on a string would give the wrong result, as they are bytes not the number of unicode code points // Note that this is an O(N) operation (because UTF-8 is complex) while getting the number of bytes is an O(1) operation. let length = primitive_val.chars().count(); let pos = i32::from( args.get(0) .expect("failed to get argument for String method"), ); if pos >= length as i32 || pos < 0 { return Ok(Value::from(NAN)); } let utf16_val = primitive_val .encode_utf16() .nth(pos as usize) .expect("failed to get utf16 value"); // If there is no element at that index, the result is NaN // TODO: We currently don't have NaN Ok(Value::from(f64::from(utf16_val))) } /// `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 fn concat(this: &mut Value, args: &[Value], ctx: &mut Interpreter) -> ResultValue { // First we get it the actual string a private field stored on the object only the engine has access to. // Then we convert it into a Rust String by wrapping it in from_value let mut new_str = ctx.value_to_rust_string(this); for arg in args { let concat_str = String::from(arg); new_str.push_str(&concat_str); } Ok(Value::from(new_str)) } /// `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 fn repeat(this: &mut Value, args: &[Value], ctx: &mut Interpreter) -> ResultValue { // First we get it the actual string a private field stored on the object only the engine has access to. // Then we convert it into a Rust String by wrapping it in from_value let primitive_val: String = ctx.value_to_rust_string(this); let repeat_times = usize::from( args.get(0) .expect("failed to get argument for String method"), ); Ok(Value::from(primitive_val.repeat(repeat_times))) } /// `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 fn slice(this: &mut Value, args: &[Value], ctx: &mut Interpreter) -> ResultValue { // First we get it the actual string a private field stored on the object only the engine has access to. // Then we convert it into a Rust String by wrapping it in from_value let primitive_val: String = ctx.value_to_rust_string(this); let start = i32::from( args.get(0) .expect("failed to get argument for String method"), ); let end = i32::from(args.get(1).expect("failed to get argument in slice")); // Calling .len() on a string would give the wrong result, as they are bytes not the number of unicode code points // Note that this is an O(N) operation (because UTF-8 is complex) while getting the number of bytes is an O(1) operation. let length: i32 = primitive_val.chars().count() as i32; let from: i32 = if start < 0 { max(length.wrapping_add(start), 0) } else { min(start, length) }; let to: i32 = if end < 0 { max(length.wrapping_add(end), 0) } else { min(end, length) }; let span = max(to.wrapping_sub(from), 0); let mut new_str = String::new(); for i in from..from.wrapping_add(span) { new_str.push( primitive_val .chars() .nth(i as usize) .expect("Could not get nth char"), ); } Ok(Value::from(new_str)) } /// `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 fn starts_with(this: &mut Value, args: &[Value], ctx: &mut Interpreter) -> ResultValue { // First we get it the actual string a private field stored on the object only the engine has access to. // Then we convert it into a Rust String by wrapping it in from_value let primitive_val: String = ctx.value_to_rust_string(this); // TODO: Should throw TypeError if pattern is regular expression let search_string = String::from( args.get(0) .expect("failed to get argument for String method"), ); let length: i32 = primitive_val.chars().count() as i32; let search_length: i32 = search_string.chars().count() as i32; // If less than 2 args specified, position is 'undefined', defaults to 0 let position: i32 = if args.len() < 2 { 0 } else { i32::from(args.get(1).expect("failed to get arg")) }; let start = min(max(position, 0), length); let end = start.wrapping_add(search_length); if end > length { Ok(Value::from(false)) } else { // Only use the part of the string from "start" let this_string: String = primitive_val.chars().skip(start as usize).collect(); Ok(Value::from(this_string.starts_with(&search_string))) } } /// `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 fn ends_with(this: &mut Value, args: &[Value], ctx: &mut Interpreter) -> ResultValue { // First we get it the actual string a private field stored on the object only the engine has access to. // Then we convert it into a Rust String by wrapping it in from_value let primitive_val: String = ctx.value_to_rust_string(this); // TODO: Should throw TypeError if search_string is regular expression let search_string = String::from( args.get(0) .expect("failed to get argument for String method"), ); let length: i32 = primitive_val.chars().count() as i32; let search_length: i32 = search_string.chars().count() as i32; // If less than 2 args specified, end_position is 'undefined', defaults to // length of this let end_position: i32 = if args.len() < 2 { length } else { i32::from(args.get(1).expect("Could not get argumetn")) }; let end = min(max(end_position, 0), length); let start = end.wrapping_sub(search_length); if start < 0 { Ok(Value::from(false)) } else { // Only use the part of the string up to "end" let this_string: String = primitive_val.chars().take(end as usize).collect(); Ok(Value::from(this_string.ends_with(&search_string))) } } /// `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 fn includes(this: &mut Value, args: &[Value], ctx: &mut Interpreter) -> ResultValue { // First we get it the actual string a private field stored on the object only the engine has access to. // Then we convert it into a Rust String by wrapping it in from_value let primitive_val: String = ctx.value_to_rust_string(this); // TODO: Should throw TypeError if search_string is regular expression let search_string = String::from( args.get(0) .expect("failed to get argument for String method"), ); let length: i32 = primitive_val.chars().count() as i32; // If less than 2 args specified, position is 'undefined', defaults to 0 let position: i32 = if args.len() < 2 { 0 } else { i32::from(args.get(1).expect("Could not get argument")) }; let start = min(max(position, 0), length); // Take the string from "this" and use only the part of it after "start" let this_string: String = primitive_val.chars().skip(start as usize).collect(); Ok(Value::from(this_string.contains(&search_string))) } /// Return either the string itself or the string of the regex equivalent fn get_regex_string(value: &Value) -> String { match value.deref() { ValueData::String(ref body) => body.into(), ValueData::Object(ref obj) => { let slots = &obj.borrow().internal_slots; if slots.get("RegExpMatcher").is_some() { // first argument is another `RegExp` object, so copy its pattern and flags if let Some(body) = slots.get("OriginalSource") { return String::from(r#body); } } "undefined".to_string() } _ => "undefined".to_string(), } } /// `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 /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace pub fn replace(this: &mut Value, args: &[Value], ctx: &mut Interpreter) -> ResultValue { // TODO: Support Symbol replacer let primitive_val: String = ctx.value_to_rust_string(this); if args.is_empty() { return Ok(Value::from(primitive_val)); } let regex_body = get_regex_string(args.get(0).expect("Value needed")); let re = Regex::new(®ex_body).expect("unable to convert regex to regex object"); let mat = re.find(&primitive_val).expect("unable to find value"); let caps = re .captures(&primitive_val) .expect("unable to get capture groups from text"); let replace_value = if args.len() > 1 { // replace_object could be a string or function or not exist at all let replace_object: &Value = args.get(1).expect("second argument expected"); match replace_object.deref() { ValueData::String(val) => { // https://tc39.es/ecma262/#table-45 let mut result: String = val.to_string(); let re = Regex::new(r"\$(\d)").unwrap(); if val.find("$$").is_some() { result = val.replace("$$", "$") } if val.find("$`").is_some() { let start_of_match = mat.start(); let slice = &primitive_val[..start_of_match]; result = val.replace("$`", slice); } if val.find("$'").is_some() { let end_of_match = mat.end(); let slice = &primitive_val[end_of_match..]; result = val.replace("$'", slice); } if val.find("$&").is_some() { // get matched value let matched = caps.get(0).expect("cannot get matched value"); result = val.replace("$&", matched.as_str()); } // Capture $1, $2, $3 etc if re.is_match(&result) { let mat_caps = re.captures(&result).unwrap(); let group_str = mat_caps.get(1).unwrap().as_str(); let group_int = group_str.parse::<usize>().unwrap(); result = re .replace(result.as_str(), caps.get(group_int).unwrap().as_str()) .to_string() } result } ValueData::Object(_) => { // This will return the matched substring first, then captured parenthesized groups later let mut results: Vec<Value> = caps .iter() .map(|capture| Value::from(capture.unwrap().as_str())) .collect(); // Returns the starting byte offset of the match let start = caps .get(0) .expect("Unable to get Byte offset from string for match") .start(); results.push(Value::from(start)); // Push the whole string being examined results.push(Value::from(primitive_val.to_string())); let result = ctx.call(&replace_object, this, &results).unwrap(); ctx.value_to_rust_string(&result) } _ => "undefined".to_string(), } } else { "undefined".to_string() }; Ok(Value::from(primitive_val.replacen( &mat.as_str(), &replace_value, 1, ))) } /// `String.prototype.indexOf( searchValue[, fromIndex] )` /// /// The `indexOf()` method returns the index within the calling `String` object of the first occurrence of the specified value, starting the search at `fromIndex`. /// /// Returns -1 if the value is not found. /// /// More information: /// - [ECMAScript reference][spec] /// - [MDN documentation][mdn] /// /// [spec]: https://tc39.es/ecma262/#sec-string.prototype.indexof /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf pub fn index_of(this: &mut Value, args: &[Value], ctx: &mut Interpreter) -> ResultValue { // First we get it the actual string a private field stored on the object only the engine has access to. // Then we convert it into a Rust String by wrapping it in from_value let primitive_val: String = ctx.value_to_rust_string(this); // TODO: Should throw TypeError if search_string is regular expression let search_string = String::from( args.get(0) .expect("failed to get argument for String method"), ); let length: i32 = primitive_val.chars().count() as i32; // If less than 2 args specified, position is 'undefined', defaults to 0 let position: i32 = if args.len() < 2 { 0 } else { i32::from(args.get(1).expect("Could not get argument")) }; let start = min(max(position, 0), length); // Here cannot use the &str method "find", because this returns the byte // index: we need to return the char index in the JS String // Instead, iterate over the part we're checking until the slice we're // checking "starts with" the search string for index in start..length { let this_string: String = primitive_val.chars().skip(index as usize).collect(); if this_string.starts_with(&search_string) { // Explicitly return early with the index value return Ok(Value::from(index)); } } // Didn't find a match, so return -1 Ok(Value::from(-1)) } /// `String.prototype.lastIndexOf( searchValue[, fromIndex] )` /// /// The `lastIndexOf()` method returns the index within the calling `String` object of the last occurrence of the specified value, searching backwards from `fromIndex`. /// /// Returns -1 if the value is not found. /// /// More information: /// - [ECMAScript reference][spec] /// - [MDN documentation][mdn] /// /// [spec]: https://tc39.es/ecma262/#sec-string.prototype.lastindexof /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf pub fn last_index_of(this: &mut Value, args: &[Value], ctx: &mut Interpreter) -> ResultValue { // First we get it the actual string a private field stored on the object only the engine has access to. // Then we convert it into a Rust String by wrapping it in from_value let primitive_val: String = ctx.value_to_rust_string(this); // TODO: Should throw TypeError if search_string is regular expression let search_string = String::from( args.get(0) .expect("failed to get argument for String method"), ); let length: i32 = primitive_val.chars().count() as i32; // If less than 2 args specified, position is 'undefined', defaults to 0 let position: i32 = if args.len() < 2 { 0 } else { i32::from(args.get(1).expect("Could not get argument")) }; let start = min(max(position, 0), length); // Here cannot use the &str method "rfind", because this returns the last // byte index: we need to return the last char index in the JS String // Instead, iterate over the part we're checking keeping track of the higher // index we found that "starts with" the search string let mut highest_index: i32 = -1; for index in start..length { let this_string: String = primitive_val.chars().skip(index as usize).collect(); if this_string.starts_with(&search_string) { highest_index = index; } } // This will still be -1 if no matches were found, else with be >= 0 Ok(Value::from(highest_index)) } /// `String.prototype.match( regexp )` /// /// The `match()` method retrieves the result of matching a **string** against a [`regular expression`][regex]. /// /// More information: /// - [ECMAScript reference][spec] /// - [MDN documentation][mdn] /// /// [spec]: https://tc39.es/ecma262/#sec-string.prototype.match /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match /// [regex]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions pub fn r#match(this: &mut Value, args: &[Value], ctx: &mut Interpreter) -> ResultValue { let mut re = make_regexp(&mut Value::from(Object::default()), &[args[0].clone()], ctx)?; regexp_match(&mut re, ctx.value_to_rust_string(this), ctx) } /// Abstract method `StringPad`. /// /// Performs the actual string padding for padStart/End. /// <https://tc39.es/ecma262/#sec-stringpad/> fn string_pad( primitive: String, max_length: i32, fill_string: Option<String>, at_start: bool, ) -> ResultValue { let primitive_length = primitive.len() as i32; if max_length <= primitive_length { return Ok(Value::from(primitive)); } let filler = match fill_string { Some(filler) => filler, None => String::from(" "), }; if filler == "" { return Ok(Value::from(primitive)); } let fill_len = max_length.wrapping_sub(primitive_length); let mut fill_str = String::new(); while fill_str.len() < fill_len as usize { fill_str.push_str(&filler); } // Cut to size max_length let concat_fill_str: String = fill_str.chars().take(fill_len as usize).collect(); if at_start { Ok(Value::from(format!("{}{}", concat_fill_str, &primitive))) } else { Ok(Value::from(format!("{}{}", primitive, &concat_fill_str))) } } /// `String.prototype.padEnd( targetLength[, padString] )` /// /// The `padEnd()` method pads the current string with a given string (repeated, if needed) so that the resulting string reaches a given length. /// /// The padding is applied from the end of the current string. /// /// More information: /// - [ECMAScript reference][spec] /// - [MDN documentation][mdn] /// /// [spec]: https://tc39.es/ecma262/#sec-string.prototype.padend /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padEnd pub fn pad_end(this: &mut Value, args: &[Value], ctx: &mut Interpreter) -> ResultValue { let primitive_val: String = ctx.value_to_rust_string(this); if args.is_empty() { return Err(Value::from("padEnd requires maxLength argument")); } let max_length = i32::from( args.get(0) .expect("failed to get argument for String method"), ); let fill_string: Option<String> = match args.len() { 1 => None, _ => Some(String::from(args.get(1).expect("Could not get argument"))), }; string_pad(primitive_val, max_length, fill_string, false) } /// `String.prototype.padStart( targetLength [, padString] )` /// /// The `padStart()` method pads the current string with another string (multiple times, if needed) until the resulting string reaches the given length. /// /// The padding is applied from the start of the current string. /// /// More information: /// - [ECMAScript reference][spec] /// - [MDN documentation][mdn] /// /// [spec]: https://tc39.es/ecma262/#sec-string.prototype.padstart /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart pub fn pad_start(this: &mut Value, args: &[Value], ctx: &mut Interpreter) -> ResultValue { let primitive_val: String = ctx.value_to_rust_string(this); if args.is_empty() { return Err(Value::from("padStart requires maxLength argument")); } let max_length = i32::from( args.get(0) .expect("failed to get argument for String method"), ); let fill_string: Option<String> = match args.len() { 1 => None, _ => Some(String::from(args.get(1).expect("Could not get argument"))), }; string_pad(primitive_val, max_length, fill_string, true) } /// Helper function to check if a `char` is trimmable. 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) match c { // Explicit whitespace: https://tc39.es/ecma262/#sec-white-space '\u{0009}' | '\u{000B}' | '\u{000C}' | '\u{0020}' | '\u{00A0}' | '\u{FEFF}' | // Unicode Space_Seperator 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}' => true, _ => false, } } /// String.prototype.trim() /// /// The `trim()` method removes whitespace from both ends of a string. /// /// Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.) and all the line terminator characters (LF, CR, etc.). /// /// More information: /// - [ECMAScript reference][spec] /// - [MDN documentation][mdn] /// /// [spec]: https://tc39.es/ecma262/#sec-string.prototype.trim /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/trim pub fn trim(this: &mut Value, _: &[Value], ctx: &mut Interpreter) -> ResultValue { let this_str: String = ctx.value_to_rust_string(this); Ok(Value::from(this_str.trim_matches(is_trimmable_whitespace))) } /// `String.prototype.trimStart()` /// /// The `trimStart()` method removes whitespace from the beginning of a string. /// /// Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.) and all the line terminator characters (LF, CR, etc.). /// /// More information: /// - [ECMAScript reference][spec] /// - [MDN documentation][mdn] /// /// [spec]: https://tc39.es/ecma262/#sec-string.prototype.trimstart /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/trimStart pub fn trim_start(this: &mut Value, _: &[Value], ctx: &mut Interpreter) -> ResultValue { let this_str: String = ctx.value_to_rust_string(this); Ok(Value::from( this_str.trim_start_matches(is_trimmable_whitespace), )) } /// String.prototype.trimEnd() /// /// The `trimEnd()` method removes whitespace from the end of a string. /// /// Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.) and all the line terminator characters (LF, CR, etc.). /// /// More information: /// - [ECMAScript reference][spec] /// - [MDN documentation][mdn] /// /// [spec]: https://tc39.es/ecma262/#sec-string.prototype.trimend /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/trimEnd pub fn trim_end(this: &mut Value, _: &[Value], ctx: &mut Interpreter) -> ResultValue { let this_str: String = ctx.value_to_rust_string(this); Ok(Value::from( this_str.trim_end_matches(is_trimmable_whitespace), )) } /// `String.prototype.toLowerCase()` /// /// The `toLowerCase()` method returns the calling string value converted to lower case. /// /// More information: /// - [ECMAScript reference][spec] /// - [MDN documentation][mdn] /// /// [spec]: https://tc39.es/ecma262/#sec-string.prototype.tolowercase /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLowerCase pub fn to_lowercase(this: &mut Value, _: &[Value], ctx: &mut Interpreter) -> ResultValue { // First we get it the actual string a private field stored on the object only the engine has access to. // Then we convert it into a Rust String by wrapping it in from_value let this_str: String = ctx.value_to_rust_string(this); // The Rust String is mapped to uppercase using the builtin .to_lowercase(). // There might be corner cases where it does not behave exactly like Javascript expects Ok(Value::from(this_str.to_lowercase())) } /// `String.prototype.toUpperCase()` /// /// The `toUpperCase()` method returns the calling string value converted to uppercase. /// /// The value will be **converted** to a string if it isn't one /// /// More information: /// - [ECMAScript reference][spec] /// - [MDN documentation][mdn] /// /// [spec]: https://tc39.es/ecma262/#sec-string.prototype.toUppercase /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase pub fn to_uppercase(this: &mut Value, _: &[Value], ctx: &mut Interpreter) -> ResultValue { // First we get it the actual string a private field stored on the object only the engine has access to. // Then we convert it into a Rust String by wrapping it in from_value let this_str: String = ctx.value_to_rust_string(this); // The Rust String is mapped to uppercase using the builtin .to_uppercase(). // There might be corner cases where it does not behave exactly like Javascript expects Ok(Value::from(this_str.to_uppercase())) } /// `String.prototype.substring( indexStart[, indexEnd] )` /// /// The `substring()` method returns the part of the `string` between the start and end indexes, or to the end of the string. /// /// More information: /// - [ECMAScript reference][spec] /// - [MDN documentation][mdn] /// /// [spec]: https://tc39.es/ecma262/#sec-string.prototype.substring /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substring pub fn substring(this: &mut Value, args: &[Value], ctx: &mut Interpreter) -> ResultValue { // First we get it the actual string a private field stored on the object only the engine has access to. // Then we convert it into a Rust String by wrapping it in from_value let primitive_val: String = ctx.value_to_rust_string(this); // If no args are specified, start is 'undefined', defaults to 0 let start = if args.is_empty() { 0 } else { i32::from( args.get(0) .expect("failed to get argument for String method"), ) }; let length: i32 = primitive_val.chars().count() as i32; // If less than 2 args specified, end is the length of the this object converted to a String let end = if args.len() < 2 { length } else { i32::from(args.get(1).expect("Could not get argument")) }; // Both start and end args replaced by 0 if they were negative // or by the length of the String if they were greater let final_start = min(max(start, 0), length); let final_end = min(max(end, 0), length); // Start and end are swapped if start is greater than end let from = min(final_start, final_end) as usize; let to = max(final_start, final_end) as usize; // Extract the part of the string contained between the start index and the end index // where start is guaranteed to be smaller or equals to end let extracted_string: String = primitive_val .chars() .skip(from) .take(to.wrapping_sub(from)) .collect(); Ok(Value::from(extracted_string)) } /// `String.prototype.substr( start[, length] )` /// /// The `substr()` method returns a portion of the string, starting at the specified index and extending for a given number of characters afterward. /// /// More information: /// - [ECMAScript reference][spec] /// - [MDN documentation][mdn] /// /// [spec]: https://tc39.es/ecma262/#sec-string.prototype.substr /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr /// <https://tc39.es/ecma262/#sec-string.prototype.substr> pub fn substr(this: &mut Value, args: &[Value], ctx: &mut Interpreter) -> ResultValue { // First we get it the actual string a private field stored on the object only the engine has access to. // Then we convert it into a Rust String by wrapping it in from_value let primitive_val: String = ctx.value_to_rust_string(this); // If no args are specified, start is 'undefined', defaults to 0 let mut start = if args.is_empty() { 0 } else { i32::from( args.get(0) .expect("failed to get argument for String method"), ) }; let length: i32 = primitive_val.chars().count() as i32; // If less than 2 args specified, end is +infinity, the maximum number value. // Using i32::max_value() should be safe because the final length used is at most // the number of code units from start to the end of the string, // which should always be smaller or equals to both +infinity and i32::max_value let end = if args.len() < 2 { i32::max_value() } else { i32::from(args.get(1).expect("Could not get argument")) }; // If start is negative it become the number of code units from the end of the string if start < 0 { start = max(length.wrapping_add(start), 0); } // length replaced by 0 if it was negative // or by the number of code units from start to the end of the string if it was greater let result_length = min(max(end, 0), length.wrapping_sub(start)); // If length is negative we return an empty string // otherwise we extract the part of the string from start and is length code units long if result_length <= 0 { Ok(Value::from("".to_string())) } else { let extracted_string: String = primitive_val .chars() .skip(start as usize) .take(result_length as usize) .collect(); Ok(Value::from(extracted_string)) } } /// String.prototype.valueOf() /// /// The `valueOf()` method returns the primitive value of a `String` object. /// /// More information: /// - [ECMAScript reference][spec] /// - [MDN documentation][mdn] /// /// [spec]: https://tc39.es/ecma262/#sec-string.prototype.value_of /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/valueOf pub fn value_of(this: &mut Value, args: &[Value], ctx: &mut Interpreter) -> ResultValue { // Use the to_string method because it is specified to do the same thing in this case to_string(this, args, ctx) } /// `String.prototype.matchAll( regexp )` /// /// The `matchAll()` method returns an iterator of all results matching a string against a [`regular expression`][regex], including [capturing groups][cg]. /// /// More information: /// - [ECMAScript reference][spec] /// - [MDN documentation][mdn] /// /// [spec]: https://tc39.es/ecma262/#sec-string.prototype.matchall /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/matchAll /// [regex]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions /// [cg]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Groups_and_Ranges // TODO: update this method to return iterator pub fn match_all(this: &mut Value, args: &[Value], ctx: &mut Interpreter) -> ResultValue { let mut re: Value = match args.get(0) { Some(arg) => { if arg.is_null() { make_regexp( &mut Value::from(Object::default()), &[ Value::from(ctx.value_to_rust_string(arg)), Value::from(String::from("g")), ], ctx, ) } else if arg.is_undefined() { make_regexp( &mut Value::from(Object::default()), &[Value::undefined(), Value::from(String::from("g"))], ctx, ) } else { Ok(arg.clone()) } } None => make_regexp( &mut Value::from(Object::default()), &[Value::from(String::new()), Value::from("g")], ctx, ), }?; regexp_match_all(&mut re, ctx.value_to_rust_string(this)) } /// Create a new `String` object. pub fn create(global: &Value) -> Value { // Create prototype let prototype = Value::new_object(Some(global)); let length = Property::default().value(Value::from(0)); prototype.set_property_slice("length", length); make_builtin_fn!(char_at, named "charAt", with length 1, of prototype); make_builtin_fn!(char_code_at, named "charCodeAt", with length 1, of prototype); make_builtin_fn!(to_string, named "toString", of prototype); make_builtin_fn!(concat, named "concat", with length 1, of prototype); make_builtin_fn!(repeat, named "repeat", with length 1, of prototype); make_builtin_fn!(slice, named "slice", with length 2, of prototype); make_builtin_fn!(starts_with, named "startsWith", with length 1, of prototype); make_builtin_fn!(ends_with, named "endsWith", with length 1, of prototype); make_builtin_fn!(includes, named "includes", with length 1, of prototype); make_builtin_fn!(index_of, named "indexOf", with length 1, of prototype); make_builtin_fn!(last_index_of, named "lastIndexOf", with length 1, of prototype); make_builtin_fn!(r#match, named "match", with length 1, of prototype); make_builtin_fn!(pad_end, named "padEnd", with length 1, of prototype); make_builtin_fn!(pad_start, named "padStart", with length 1, of prototype); make_builtin_fn!(trim, named "trim", of prototype); make_builtin_fn!(trim_start, named "trimStart", of prototype); make_builtin_fn!(to_lowercase, named "toLowerCase", of prototype); make_builtin_fn!(to_uppercase, named "toUpperCase", of prototype); make_builtin_fn!(substring, named "substring", with length 2, of prototype); make_builtin_fn!(substr, named "substr", with length 2, of prototype); make_builtin_fn!(value_of, named "valueOf", of prototype); make_builtin_fn!(match_all, named "matchAll", with length 1, of prototype); make_builtin_fn!(replace, named "replace", with length 2, of prototype); make_constructor_fn(make_string, global, prototype) } /// Initialise the `String` object on the global object. #[inline] pub fn init(global: &Value) { global.set_field_slice("String", create(global)); }