1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790
//! This module implements the global `RegExp` object.
//!
//! `The `RegExp` object is used for matching text with a pattern.
//!
//! More information:
//! - [ECMAScript reference][spec]
//! - [MDN documentation][mdn]
//!
//! [spec]: https://tc39.es/ecma262/#sec-regexp-constructor
//! [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
pub mod regexp_string_iterator;
use crate::{
builtins::{array::Array, string, BuiltIn},
context::StandardObjects,
gc::{empty_trace, Finalize, Trace},
object::{
internal_methods::get_prototype_from_constructor, ConstructorBuilder, FunctionBuilder,
JsObject, Object, ObjectData,
},
property::Attribute,
symbol::WellKnownSymbols,
value::{IntegerOrInfinity, JsValue},
BoaProfiler, Context, JsResult, JsString,
};
use regexp_string_iterator::RegExpStringIterator;
use regress::Regex;
use super::JsArgs;
#[cfg(test)]
mod tests;
/// The internal representation on a `RegExp` object.
#[derive(Debug, Clone, Finalize)]
pub struct RegExp {
/// Regex matcher.
matcher: Regex,
/// Update last_index, set if global or sticky flags are set.
use_last_index: bool,
/// Flag 's' - dot matches newline characters.
dot_all: bool,
/// Flag 'g'
global: bool,
/// Flag 'i' - ignore case.
ignore_case: bool,
/// Flag 'm' - '^' and '$' match beginning/end of line.
multiline: bool,
/// Flag 'y'
sticky: bool,
/// Flag 'u' - Unicode.
unicode: bool,
original_source: JsString,
original_flags: JsString,
}
// Only safe while regress::Regex doesn't implement Trace itself.
unsafe impl Trace for RegExp {
empty_trace!();
}
impl BuiltIn for RegExp {
const NAME: &'static str = "RegExp";
fn attribute() -> Attribute {
Attribute::WRITABLE | Attribute::NON_ENUMERABLE | Attribute::CONFIGURABLE
}
fn init(context: &mut Context) -> (&'static str, JsValue, Attribute) {
let _timer = BoaProfiler::global().start_event(Self::NAME, "init");
let get_species = FunctionBuilder::native(context, Self::get_species)
.name("get [Symbol.species]")
.constructable(false)
.build();
let flag_attributes = Attribute::CONFIGURABLE | Attribute::NON_ENUMERABLE;
let get_global = FunctionBuilder::native(context, Self::get_global)
.name("get global")
.constructable(false)
.build();
let get_ignore_case = FunctionBuilder::native(context, Self::get_ignore_case)
.name("get ignoreCase")
.constructable(false)
.build();
let get_multiline = FunctionBuilder::native(context, Self::get_multiline)
.name("get multiline")
.constructable(false)
.build();
let get_dot_all = FunctionBuilder::native(context, Self::get_dot_all)
.name("get dotAll")
.constructable(false)
.build();
let get_unicode = FunctionBuilder::native(context, Self::get_unicode)
.name("get unicode")
.constructable(false)
.build();
let get_sticky = FunctionBuilder::native(context, Self::get_sticky)
.name("get sticky")
.constructable(false)
.build();
let get_flags = FunctionBuilder::native(context, Self::get_flags)
.name("get flags")
.constructable(false)
.build();
let get_source = FunctionBuilder::native(context, Self::get_source)
.name("get source")
.constructable(false)
.build();
let regexp_object = ConstructorBuilder::with_standard_object(
context,
Self::constructor,
context.standard_objects().regexp_object().clone(),
)
.name(Self::NAME)
.length(Self::LENGTH)
.static_accessor(
WellKnownSymbols::species(),
Some(get_species),
None,
Attribute::CONFIGURABLE,
)
.property("lastIndex", 0, Attribute::all())
.method(Self::test, "test", 1)
.method(Self::exec, "exec", 1)
.method(Self::to_string, "toString", 0)
.method(
Self::r#match,
(WellKnownSymbols::match_(), "[Symbol.match]"),
1,
)
.method(
Self::match_all,
(WellKnownSymbols::match_all(), "[Symbol.matchAll]"),
1,
)
.method(
Self::replace,
(WellKnownSymbols::replace(), "[Symbol.replace]"),
2,
)
.method(
Self::search,
(WellKnownSymbols::search(), "[Symbol.search]"),
1,
)
.method(
Self::split,
(WellKnownSymbols::split(), "[Symbol.split]"),
2,
)
.accessor("global", Some(get_global), None, flag_attributes)
.accessor("ignoreCase", Some(get_ignore_case), None, flag_attributes)
.accessor("multiline", Some(get_multiline), None, flag_attributes)
.accessor("dotAll", Some(get_dot_all), None, flag_attributes)
.accessor("unicode", Some(get_unicode), None, flag_attributes)
.accessor("sticky", Some(get_sticky), None, flag_attributes)
.accessor("flags", Some(get_flags), None, flag_attributes)
.accessor("source", Some(get_source), None, flag_attributes)
.build();
// TODO: add them RegExp accessor properties
(Self::NAME, regexp_object.into(), Self::attribute())
}
}
impl RegExp {
/// The name of the object.
pub(crate) const NAME: &'static str = "RegExp";
/// The amount of arguments this function object takes.
pub(crate) const LENGTH: usize = 2;
/// `22.2.3.1 RegExp ( pattern, flags )`
///
/// More information:
/// - [ECMAScript reference][spec]
///
/// [spec]: https://tc39.es/ecma262/#sec-regexp-pattern-flags
pub(crate) fn constructor(
new_target: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
let pattern = args.get_or_undefined(0);
let flags = args.get_or_undefined(1);
// 1. Let patternIsRegExp be ? IsRegExp(pattern).
let pattern_is_regexp = if let JsValue::Object(obj) = &pattern {
if obj.is_regexp() {
Some(obj)
} else {
None
}
} else {
None
};
// 2. If NewTarget is undefined, then
// 3. Else, let newTarget be NewTarget.
if new_target.is_undefined() {
// a. Let newTarget be the active function object.
// b. If patternIsRegExp is true and flags is undefined, then
if let Some(pattern) = pattern_is_regexp {
if flags.is_undefined() {
// i. Let patternConstructor be ? Get(pattern, "constructor").
let pattern_constructor = pattern.get("constructor", context)?;
// ii. If SameValue(newTarget, patternConstructor) is true, return pattern.
if JsValue::same_value(new_target, &pattern_constructor) {
return Ok(pattern.clone().into());
}
}
}
}
// 4. If Type(pattern) is Object and pattern has a [[RegExpMatcher]] internal slot, then
// 6. Else,
let (p, f) = if let Some(pattern) = pattern_is_regexp {
let obj = pattern.borrow();
let regexp = obj.as_regexp().unwrap();
// a. Let P be pattern.[[OriginalSource]].
// b. If flags is undefined, let F be pattern.[[OriginalFlags]].
// c. Else, let F be flags.
if flags.is_undefined() {
(
JsValue::new(regexp.original_source.clone()),
JsValue::new(regexp.original_flags.clone()),
)
} else {
(JsValue::new(regexp.original_source.clone()), flags.clone())
}
} else {
// a. Let P be pattern.
// b. Let F be flags.
(pattern.clone(), flags.clone())
};
// 7. Let O be ? RegExpAlloc(newTarget).
let o = RegExp::alloc(new_target, &[], context)?;
// 8.Return ? RegExpInitialize(O, P, F).
RegExp::initialize(&o, &[p, f], context)
}
/// `22.2.3.2.1 RegExpAlloc ( newTarget )`
///
/// More information:
/// - [ECMAScript reference][spec]
///
/// [spec]: https://tc39.es/ecma262/#sec-regexpalloc
fn alloc(this: &JsValue, _: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
let proto = get_prototype_from_constructor(this, StandardObjects::regexp_object, context)?;
Ok(JsObject::new(Object::create(proto.into())).into())
}
/// `22.2.3.2.2 RegExpInitialize ( obj, pattern, flags )`
///
/// More information:
/// - [ECMAScript reference][spec]
///
/// [spec]: https://tc39.es/ecma262/#sec-regexpinitialize
fn initialize(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
let pattern = args.get_or_undefined(0);
let flags = args.get_or_undefined(1);
// 1. If pattern is undefined, let P be the empty String.
// 2. Else, let P be ? ToString(pattern).
let p = if pattern.is_undefined() {
JsString::new("")
} else {
pattern.to_string(context)?
};
// 3. If flags is undefined, let F be the empty String.
// 4. Else, let F be ? ToString(flags).
let f = if flags.is_undefined() {
JsString::new("")
} else {
flags.to_string(context)?
};
// 5. If F contains any code unit other than "g", "i", "m", "s", "u", or "y"
// or if it contains the same code unit more than once, throw a SyntaxError exception.
let mut global = false;
let mut ignore_case = false;
let mut multiline = false;
let mut dot_all = false;
let mut unicode = false;
let mut sticky = false;
for c in f.chars() {
match c {
'g' if global => {
return context.throw_syntax_error("RegExp flags contains multiple 'g'")
}
'g' => global = true,
'i' if ignore_case => {
return context.throw_syntax_error("RegExp flags contains multiple 'i'")
}
'i' => ignore_case = true,
'm' if multiline => {
return context.throw_syntax_error("RegExp flags contains multiple 'm'")
}
'm' => multiline = true,
's' if dot_all => {
return context.throw_syntax_error("RegExp flags contains multiple 's'")
}
's' => dot_all = true,
'u' if unicode => {
return context.throw_syntax_error("RegExp flags contains multiple 'u'")
}
'u' => unicode = true,
'y' if sticky => {
return context.throw_syntax_error("RegExp flags contains multiple 'y'")
}
'y' => sticky = true,
c => {
return context.throw_syntax_error(format!(
"RegExp flags contains unknown code unit '{}'",
c
))
}
}
}
// 12. Set obj.[[OriginalSource]] to P.
// 13. Set obj.[[OriginalFlags]] to F.
// 14. Set obj.[[RegExpMatcher]] to the Abstract Closure that evaluates parseResult by applying the semantics provided in 22.2.2 using patternCharacters as the pattern's List of SourceCharacter values and F as the flag parameters.
let matcher = match Regex::with_flags(&p, f.as_ref()) {
Err(error) => {
return Err(context
.construct_syntax_error(format!("failed to create matcher: {}", error.text)));
}
Ok(val) => val,
};
let regexp = RegExp {
matcher,
use_last_index: global || sticky,
dot_all,
global,
ignore_case,
multiline,
sticky,
unicode,
original_source: p,
original_flags: f,
};
this.set_data(ObjectData::reg_exp(Box::new(regexp)));
// 16. Return obj.
Ok(this.clone())
}
/// `22.2.3.2.4 RegExpCreate ( P, F )`
///
/// More information:
/// - [ECMAScript reference][spec]
///
/// [spec]: https://tc39.es/ecma262/#sec-regexpcreate
pub(crate) fn create(p: JsValue, f: JsValue, context: &mut Context) -> JsResult<JsValue> {
// 1. Let obj be ? RegExpAlloc(%RegExp%).
let obj = RegExp::alloc(
&context.global_object().get(RegExp::NAME, context)?,
&[],
context,
)?;
// 2. Return ? RegExpInitialize(obj, P, F).
RegExp::initialize(&obj, &[p, f], context)
}
/// `get RegExp [ @@species ]`
///
/// The `RegExp [ @@species ]` accessor property returns the RegExp constructor.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-get-regexp-@@species
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@species
fn get_species(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult<JsValue> {
// 1. Return the this value.
Ok(this.clone())
}
#[inline]
fn regexp_has_flag(this: &JsValue, flag: char, context: &mut Context) -> JsResult<JsValue> {
if let Some(object) = this.as_object() {
if let Some(regexp) = object.borrow().as_regexp() {
return Ok(JsValue::new(match flag {
'g' => regexp.global,
'm' => regexp.multiline,
's' => regexp.dot_all,
'i' => regexp.ignore_case,
'u' => regexp.unicode,
'y' => regexp.sticky,
_ => unreachable!(),
}));
}
if JsObject::equals(
&object,
&context.standard_objects().regexp_object().prototype,
) {
return Ok(JsValue::undefined());
}
}
let name = match flag {
'g' => "global",
'm' => "multiline",
's' => "dotAll",
'i' => "ignoreCase",
'u' => "unicode",
'y' => "sticky",
_ => unreachable!(),
};
context.throw_type_error(format!(
"RegExp.prototype.{} getter called on non-RegExp object",
name
))
}
/// `get RegExp.prototype.global`
///
/// The `global` property indicates whether or not the "`g`" flag is used with the regular expression.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-get-regexp.prototype.global
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/global
pub(crate) fn get_global(
this: &JsValue,
_: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
Self::regexp_has_flag(this, 'g', context)
}
/// `get RegExp.prototype.ignoreCase`
///
/// The `ignoreCase` property indicates whether or not the "`i`" flag is used with the regular expression.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-get-regexp.prototype.ignorecase
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/ignoreCase
pub(crate) fn get_ignore_case(
this: &JsValue,
_: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
Self::regexp_has_flag(this, 'i', context)
}
/// `get RegExp.prototype.multiline`
///
/// The multiline property indicates whether or not the "m" flag is used with the regular expression.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-get-regexp.prototype.multiline
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/multiline
pub(crate) fn get_multiline(
this: &JsValue,
_: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
Self::regexp_has_flag(this, 'm', context)
}
/// `get RegExp.prototype.dotAll`
///
/// The `dotAll` property indicates whether or not the "`s`" flag is used with the regular expression.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-get-regexp.prototype.dotAll
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/dotAll
pub(crate) fn get_dot_all(
this: &JsValue,
_: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
Self::regexp_has_flag(this, 's', context)
}
/// `get RegExp.prototype.unicode`
///
/// The unicode property indicates whether or not the "`u`" flag is used with a regular expression.
/// unicode is a read-only property of an individual regular expression instance.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-get-regexp.prototype.unicode
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/unicode
pub(crate) fn get_unicode(
this: &JsValue,
_: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
Self::regexp_has_flag(this, 'u', context)
}
/// `get RegExp.prototype.sticky`
///
/// This flag indicates that it matches only from the index indicated by the `lastIndex` property
/// of this regular expression in the target string (and does not attempt to match from any later indexes).
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-get-regexp.prototype.sticky
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/sticky
pub(crate) fn get_sticky(
this: &JsValue,
_: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
Self::regexp_has_flag(this, 'y', context)
}
/// `get RegExp.prototype.flags`
///
/// The `flags` property returns a string consisting of the [`flags`][flags] of the current regular expression object.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-get-regexp.prototype.flags
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/flags
/// [flags]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#Advanced_searching_with_flags_2
pub(crate) fn get_flags(
this: &JsValue,
_: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let R be the this value.
// 2. If Type(R) is not Object, throw a TypeError exception.
if let Some(object) = this.as_object() {
// 3. Let result be the empty String.
let mut result = String::new();
// 4. Let global be ! ToBoolean(? Get(R, "global")).
// 5. If global is true, append the code unit 0x0067 (LATIN SMALL LETTER G) as the last code unit of result.
if object.get("global", context)?.to_boolean() {
result.push('g');
}
// 6. Let ignoreCase be ! ToBoolean(? Get(R, "ignoreCase")).
// 7. If ignoreCase is true, append the code unit 0x0069 (LATIN SMALL LETTER I) as the last code unit of result.
if object.get("ignoreCase", context)?.to_boolean() {
result.push('i');
}
// 8. Let multiline be ! ToBoolean(? Get(R, "multiline")).
// 9. If multiline is true, append the code unit 0x006D (LATIN SMALL LETTER M) as the last code unit of result.
if object.get("multiline", context)?.to_boolean() {
result.push('m');
}
// 10. Let dotAll be ! ToBoolean(? Get(R, "dotAll")).
// 11. If dotAll is true, append the code unit 0x0073 (LATIN SMALL LETTER S) as the last code unit of result.
if object.get("dotAll", context)?.to_boolean() {
result.push('s');
}
// 12. Let unicode be ! ToBoolean(? Get(R, "unicode")).
// 13. If unicode is true, append the code unit 0x0075 (LATIN SMALL LETTER U) as the last code unit of result.
if object.get("unicode", context)?.to_boolean() {
result.push('u');
}
// 14. Let sticky be ! ToBoolean(? Get(R, "sticky")).
// 15. If sticky is true, append the code unit 0x0079 (LATIN SMALL LETTER Y) as the last code unit of result.
if object.get("sticky", context)?.to_boolean() {
result.push('y');
}
// 16. Return result.
return Ok(result.into());
}
context.throw_type_error("RegExp.prototype.flags getter called on non-object")
}
/// `get RegExp.prototype.source`
///
/// The `source` property returns a `String` containing the source text of the regexp object,
/// and it doesn't contain the two forward slashes on both sides and any flags.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-get-regexp.prototype.source
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/source
pub(crate) fn get_source(
this: &JsValue,
_: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let R be the this value.
// 2. If Type(R) is not Object, throw a TypeError exception.
if let Some(object) = this.as_object() {
let object = object.borrow();
match object.as_regexp() {
// 3. If R does not have an [[OriginalSource]] internal slot, then
None => {
// a. If SameValue(R, %RegExp.prototype%) is true, return "(?:)".
// b. Otherwise, throw a TypeError exception.
if JsValue::same_value(
this,
&JsValue::new(context.standard_objects().regexp_object().prototype()),
) {
Ok(JsValue::new("(?:)"))
} else {
context.throw_type_error(
"RegExp.prototype.source method called on incompatible value",
)
}
}
// 4. Assert: R has an [[OriginalFlags]] internal slot.
Some(re) => {
// 5. Let src be R.[[OriginalSource]].
// 6. Let flags be R.[[OriginalFlags]].
// 7. Return EscapeRegExpPattern(src, flags).
RegExp::escape_pattern(&re.original_source, &re.original_flags)
}
}
} else {
context.throw_type_error("RegExp.prototype.source method called on incompatible value")
}
}
/// `22.2.3.2.5 EscapeRegExpPattern ( P, F )`
///
/// More information:
/// - [ECMAScript reference][spec]
///
/// [spec]: https://tc39.es/ecma262/#sec-escaperegexppattern
fn escape_pattern(src: &str, _flags: &str) -> JsResult<JsValue> {
if src.is_empty() {
Ok(JsValue::new("(?:)"))
} else {
let mut s = String::from("");
for c in src.chars() {
match c {
'/' => s.push_str("\\/"),
'\n' => s.push_str("\\\\n"),
'\r' => s.push_str("\\\\r"),
_ => s.push(c),
}
}
Ok(JsValue::new(s))
}
}
/// `RegExp.prototype.test( string )`
///
/// The `test()` method executes a search for a match between a regular expression and a specified string.
///
/// Returns `true` or `false`.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-regexp.prototype.test
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test
pub(crate) fn test(
this: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let R be the this value.
// 2. If Type(R) is not Object, throw a TypeError exception.
if !this.is_object() {
return context
.throw_type_error("RegExp.prototype.test method called on incompatible value");
}
// 3. Let string be ? ToString(S).
let arg_str = args
.get(0)
.cloned()
.unwrap_or_default()
.to_string(context)?;
// 4. Let match be ? RegExpExec(R, string).
let m = Self::abstract_exec(this, arg_str, context)?;
// 5. If match is not null, return true; else return false.
if m.is_some() {
Ok(JsValue::new(true))
} else {
Ok(JsValue::new(false))
}
}
/// `RegExp.prototype.exec( string )`
///
/// The exec() method executes a search for a match in a specified string.
///
/// Returns a result array, or `null`.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-regexp.prototype.exec
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec
pub(crate) fn exec(
this: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let R be the this value.
// 2. Perform ? RequireInternalSlot(R, [[RegExpMatcher]]).
let obj = this.as_object().unwrap_or_default();
if !obj.is_regexp() {
return Err(
context.construct_type_error("RegExp.prototype.exec called with invalid value")
);
}
// 3. Let S be ? ToString(string).
let arg_str = args
.get(0)
.cloned()
.unwrap_or_default()
.to_string(context)?;
// 4. Return ? RegExpBuiltinExec(R, S).
if let Some(v) = Self::abstract_builtin_exec(obj, arg_str, context)? {
Ok(v.into())
} else {
Ok(JsValue::null())
}
}
/// `22.2.5.2.1 RegExpExec ( R, S )`
///
/// More information:
/// - [ECMAScript reference][spec]
///
/// [spec]: https://tc39.es/ecma262/#sec-regexpexec
pub(crate) fn abstract_exec(
this: &JsValue,
input: JsString,
context: &mut Context,
) -> JsResult<Option<JsObject>> {
// 1. Assert: Type(R) is Object.
let object = this
.as_object()
.ok_or_else(|| context.construct_type_error("RegExpExec called with invalid value"))?;
// 2. Assert: Type(S) is String.
// 3. Let exec be ? Get(R, "exec").
let exec = this.get_field("exec", context)?;
// 4. If IsCallable(exec) is true, then
if exec.is_function() {
// a. Let result be ? Call(exec, R, « S »).
let result = context.call(&exec, this, &[input.into()])?;
// b. If Type(result) is neither Object nor Null, throw a TypeError exception.
if !result.is_object() && !result.is_null() {
return Err(
context.construct_type_error("regexp exec returned neither object nor null")
);
}
// c. Return result.
return Ok(result.as_object());
}
// 5. Perform ? RequireInternalSlot(R, [[RegExpMatcher]]).
if !object.is_regexp() {
return Err(context.construct_type_error("RegExpExec called with invalid value"));
}
// 6. Return ? RegExpBuiltinExec(R, S).
Self::abstract_builtin_exec(object, input, context)
}
/// `22.2.5.2.2 RegExpBuiltinExec ( R, S )`
///
/// More information:
/// - [ECMAScript reference][spec]
///
/// [spec]: https://tc39.es/ecma262/#sec-regexpbuiltinexec
pub(crate) fn abstract_builtin_exec(
this: JsObject,
input: JsString,
context: &mut Context,
) -> JsResult<Option<JsObject>> {
// 1. Assert: R is an initialized RegExp instance.
let rx = {
let obj = this.borrow();
if let Some(rx) = obj.as_regexp() {
rx.clone()
} else {
return Err(
context.construct_type_error("RegExpBuiltinExec called with invalid value")
);
}
};
// 2. Assert: Type(S) is String.
// 3. Let length be the number of code units in S.
let length = input.encode_utf16().count();
// 4. Let lastIndex be ℝ(? ToLength(? Get(R, "lastIndex"))).
let mut last_index = this.get("lastIndex", context)?.to_length(context)?;
// 5. Let flags be R.[[OriginalFlags]].
let flags = &rx.original_flags;
// 6. If flags contains "g", let global be true; else let global be false.
let global = flags.contains('g');
// 7. If flags contains "y", let sticky be true; else let sticky be false.
let sticky = flags.contains('y');
// 8. If global is false and sticky is false, set lastIndex to 0.
if !global && !sticky {
last_index = 0;
}
// 9. Let matcher be R.[[RegExpMatcher]].
let matcher = &rx.matcher;
// 10. If flags contains "u", let fullUnicode be true; else let fullUnicode be false.
let unicode = flags.contains('u');
// 11. Let matchSucceeded be false.
// 12. Repeat, while matchSucceeded is false,
let match_value = loop {
// a. If lastIndex > length, then
if last_index > length {
// i. If global is true or sticky is true, then
if global || sticky {
// 1. Perform ? Set(R, "lastIndex", +0𝔽, true).
this.set("lastIndex", 0, true, context)?;
}
// ii. Return null.
return Ok(None);
}
// b. Let r be matcher(S, lastIndex).
// Check if last_index is a valid utf8 index into input.
let last_byte_index = match String::from_utf16(
&input.encode_utf16().take(last_index).collect::<Vec<u16>>(),
) {
Ok(s) => s.len(),
Err(_) => {
return Err(context.construct_type_error(
"Failed to get byte index from utf16 encoded string",
))
}
};
let r = matcher.find_from(&input, last_byte_index).next();
match r {
// c. If r is failure, then
None => {
// i. If sticky is true, then
if sticky {
// 1. Perform ? Set(R, "lastIndex", +0𝔽, true).
this.set("lastIndex", 0, true, context)?;
// 2. Return null.
return Ok(None);
}
// ii. Set lastIndex to AdvanceStringIndex(S, lastIndex, fullUnicode).
last_index = advance_string_index(input.clone(), last_index, unicode);
}
Some(m) => {
// c. If r is failure, then
// d. Else,
if m.start() != last_index {
// i. If sticky is true, then
if sticky {
// 1. Perform ? Set(R, "lastIndex", +0𝔽, true).
this.set("lastIndex", 0, true, context)?;
// 2. Return null.
return Ok(None);
}
// ii. Set lastIndex to AdvanceStringIndex(S, lastIndex, fullUnicode).
last_index = advance_string_index(input.clone(), last_index, unicode);
} else {
//i. Assert: r is a State.
//ii. Set matchSucceeded to true.
break m;
}
}
}
};
// 13. Let e be r's endIndex value.
let mut e = match_value.end();
// 14. If fullUnicode is true, then
if unicode {
// e is an index into the Input character list, derived from S, matched by matcher.
// Let eUTF be the smallest index into S that corresponds to the character at element e of Input.
// If e is greater than or equal to the number of elements in Input, then eUTF is the number of code units in S.
// b. Set e to eUTF.
e = input.split_at(e).0.encode_utf16().count();
}
// 15. If global is true or sticky is true, then
if global || sticky {
// a. Perform ? Set(R, "lastIndex", 𝔽(e), true).
this.set("lastIndex", e, true, context)?;
}
// 16. Let n be the number of elements in r's captures List. (This is the same value as 22.2.2.1's NcapturingParens.)
let n = match_value.captures.len();
// 17. Assert: n < 23^2 - 1.
debug_assert!(n < 23usize.pow(2) - 1);
// 18. Let A be ! ArrayCreate(n + 1).
// 19. Assert: The mathematical value of A's "length" property is n + 1.
let a = Array::array_create(n + 1, None, context)?;
// 20. Perform ! CreateDataPropertyOrThrow(A, "index", 𝔽(lastIndex)).
a.create_data_property_or_throw("index", match_value.start(), context)
.unwrap();
// 21. Perform ! CreateDataPropertyOrThrow(A, "input", S).
a.create_data_property_or_throw("input", input.clone(), context)
.unwrap();
// 22. Let matchedSubstr be the substring of S from lastIndex to e.
let matched_substr = if let Some(s) = input.get(match_value.range()) {
s
} else {
""
};
// 23. Perform ! CreateDataPropertyOrThrow(A, "0", matchedSubstr).
a.create_data_property_or_throw(0, matched_substr, context)
.unwrap();
// 24. If R contains any GroupName, then
// 25. Else,
let named_groups = match_value.named_groups();
let groups = if named_groups.clone().count() > 0 {
// a. Let groups be ! OrdinaryObjectCreate(null).
let groups = JsValue::new_object(context);
// Perform 27.f here
// f. If the ith capture of R was defined with a GroupName, then
// i. Let s be the CapturingGroupName of the corresponding RegExpIdentifierName.
// ii. Perform ! CreateDataPropertyOrThrow(groups, s, capturedValue).
for (name, range) in named_groups {
if let Some(range) = range {
let value = if let Some(s) = input.get(range.clone()) {
s
} else {
""
};
groups
.to_object(context)?
.create_data_property_or_throw(name, value, context)
.unwrap();
}
}
groups
} else {
// a. Let groups be undefined.
JsValue::undefined()
};
// 26. Perform ! CreateDataPropertyOrThrow(A, "groups", groups).
a.create_data_property_or_throw("groups", groups, context)
.unwrap();
// 27. For each integer i such that i ≥ 1 and i ≤ n, in ascending order, do
for i in 1..=n {
// a. Let captureI be ith element of r's captures List.
let capture = match_value.group(i);
let captured_value = match capture {
// b. If captureI is undefined, let capturedValue be undefined.
None => JsValue::undefined(),
// c. Else if fullUnicode is true, then
// d. Else,
Some(range) => {
if let Some(s) = input.get(range) {
s.into()
} else {
"".into()
}
}
};
// e. Perform ! CreateDataPropertyOrThrow(A, ! ToString(𝔽(i)), capturedValue).
a.create_data_property_or_throw(i, captured_value, context)
.unwrap();
}
// 28. Return A.
Ok(Some(a))
}
/// `RegExp.prototype[ @@match ]( string )`
///
/// This method retrieves the matches when matching a string against a regular expression.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-regexp.prototype-@@match
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@match
pub(crate) fn r#match(
this: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let rx be the this value.
// 2. If Type(rx) is not Object, throw a TypeError exception.
let rx = if let Some(rx) = this.as_object() {
rx
} else {
return Err(context.construct_type_error(
"RegExp.prototype.match method called on incompatible value",
));
};
// 3. Let S be ? ToString(string).
let arg_str = args
.get(0)
.cloned()
.unwrap_or_default()
.to_string(context)?;
// 4. Let global be ! ToBoolean(? Get(rx, "global")).
let global = rx.get("global", context)?.to_boolean();
// 5. If global is false, then
// 6. Else,
if !global {
// a. Return ? RegExpExec(rx, S).
if let Some(v) = Self::abstract_exec(&JsValue::new(rx), arg_str, context)? {
Ok(v.into())
} else {
Ok(JsValue::null())
}
} else {
// a. Assert: global is true.
// b. Let fullUnicode be ! ToBoolean(? Get(rx, "unicode")).
let unicode = rx.get("unicode", context)?.to_boolean();
// c. Perform ? Set(rx, "lastIndex", +0𝔽, true).
rx.set("lastIndex", 0, true, context)?;
// d. Let A be ! ArrayCreate(0).
let a = Array::array_create(0, None, context).unwrap();
// e. Let n be 0.
let mut n = 0;
// f. Repeat,
loop {
// i. Let result be ? RegExpExec(rx, S).
let result =
Self::abstract_exec(&JsValue::new(rx.clone()), arg_str.clone(), context)?;
// ii. If result is null, then
// iii. Else,
if let Some(result) = result {
// 1. Let matchStr be ? ToString(? Get(result, "0")).
let match_str = result.get("0", context)?.to_string(context)?;
// 2. Perform ! CreateDataPropertyOrThrow(A, ! ToString(𝔽(n)), matchStr).
a.create_data_property_or_throw(n, match_str.clone(), context)
.unwrap();
// 3. If matchStr is the empty String, then
if match_str.is_empty() {
// a. Let thisIndex be ℝ(? ToLength(? Get(rx, "lastIndex"))).
let this_index = rx.get("lastIndex", context)?.to_length(context)?;
// b. Let nextIndex be AdvanceStringIndex(S, thisIndex, fullUnicode).
let next_index = advance_string_index(arg_str.clone(), this_index, unicode);
// c. Perform ? Set(rx, "lastIndex", 𝔽(nextIndex), true).
rx.set("lastIndex", JsValue::new(next_index), true, context)?;
}
// 4. Set n to n + 1.
n += 1;
} else {
// 1. If n = 0, return null.
// 2. Return A.
if n == 0 {
return Ok(JsValue::null());
} else {
return Ok(a.into());
}
}
}
}
}
/// `RegExp.prototype.toString()`
///
/// Return a string representing the regular expression.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-regexp.prototype.tostring
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/toString
#[allow(clippy::wrong_self_convention)]
pub(crate) fn to_string(
this: &JsValue,
_: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
let (body, flags) = if let Some(object) = this.as_object() {
let object = object.borrow();
let regex = object.as_regexp().ok_or_else(|| {
context.construct_type_error(format!(
"Method RegExp.prototype.toString called on incompatible receiver {}",
this.display()
))
})?;
(regex.original_source.clone(), regex.original_flags.clone())
} else {
return context.throw_type_error(format!(
"Method RegExp.prototype.toString called on incompatible receiver {}",
this.display()
));
};
Ok(format!("/{}/{}", body, flags).into())
}
/// `RegExp.prototype[ @@matchAll ]( string )`
///
/// The `[@@matchAll]` method returns all matches of the regular expression against a string.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-regexp-prototype-matchall
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@matchAll
pub(crate) fn match_all(
this: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let R be the this value.
// 2. If Type(R) is not Object, throw a TypeError exception.
if !this.is_object() {
return context.throw_type_error(
"RegExp.prototype.match_all method called on incompatible value",
);
}
// 3. Let S be ? ToString(string).
let arg_str = args
.get(0)
.cloned()
.unwrap_or_default()
.to_string(context)?;
// 4. Let C be ? SpeciesConstructor(R, %RegExp%).
let c = this
.as_object()
.unwrap_or_default()
.species_constructor(context.global_object().get(RegExp::NAME, context)?, context)?;
// 5. Let flags be ? ToString(? Get(R, "flags")).
let flags = this.get_field("flags", context)?.to_string(context)?;
// 6. Let matcher be ? Construct(C, « R, flags »).
let matcher = c
.as_object()
.expect("SpeciesConstructor returned non Object")
.construct(&[this.clone(), flags.clone().into()], &c, context)?;
// 7. Let lastIndex be ? ToLength(? Get(R, "lastIndex")).
let last_index = this.get_field("lastIndex", context)?.to_length(context)?;
// 8. Perform ? Set(matcher, "lastIndex", lastIndex, true).
matcher.set_field("lastIndex", last_index, true, context)?;
// 9. If flags contains "g", let global be true.
// 10. Else, let global be false.
let global = flags.contains('g');
// 11. If flags contains "u", let fullUnicode be true.
// 12. Else, let fullUnicode be false.
let unicode = flags.contains('u');
// 13. Return ! CreateRegExpStringIterator(matcher, S, global, fullUnicode).
RegExpStringIterator::create_regexp_string_iterator(
&matcher, arg_str, global, unicode, context,
)
}
/// `RegExp.prototype [ @@replace ] ( string, replaceValue )`
///
/// The [@@replace]() method replaces some or all matches of a this pattern in a string by a replacement,
/// and returns the result of the replacement as a new string.
/// The replacement can be a string or a function to be called for each match.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-regexp.prototype-@@replace
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@replace
pub(crate) fn replace(
this: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let rx be the this value.
// 2. If Type(rx) is not Object, throw a TypeError exception.
let rx = if let Some(rx) = this.as_object() {
rx
} else {
return context.throw_type_error(
"RegExp.prototype[Symbol.replace] method called on incompatible value",
);
};
// 3. Let S be ? ToString(string).
let arg_str = args
.get(0)
.cloned()
.unwrap_or_default()
.to_string(context)?;
// 4. Let lengthS be the number of code unit elements in S.
let length_arg_str = arg_str.encode_utf16().count();
// 5. Let functionalReplace be IsCallable(replaceValue).
let mut replace_value = args.get_or_undefined(1).clone();
let functional_replace = replace_value.is_function();
// 6. If functionalReplace is false, then
if !functional_replace {
// a. Set replaceValue to ? ToString(replaceValue).
replace_value = replace_value.to_string(context)?.into();
}
// 7. Let global be ! ToBoolean(? Get(rx, "global")).
let global = rx.get("global", context)?.to_boolean();
// 8. If global is true, then
let mut unicode = false;
if global {
// a. Let fullUnicode be ! ToBoolean(? Get(rx, "unicode")).
unicode = rx.get("unicode", context)?.to_boolean();
// b. Perform ? Set(rx, "lastIndex", +0𝔽, true).
rx.set("lastIndex", 0, true, context)?;
}
// 9. Let results be a new empty List.
let mut results = Vec::new();
// 10. Let done be false.
// 11. Repeat, while done is false,
loop {
// a. Let result be ? RegExpExec(rx, S).
let result = Self::abstract_exec(&JsValue::new(rx.clone()), arg_str.clone(), context)?;
// b. If result is null, set done to true.
// c. Else,
if let Some(result) = result {
// i. Append result to the end of results.
results.push(result.clone());
// ii. If global is false, set done to true.
// iii. Else,
if !global {
break;
} else {
// 1. Let matchStr be ? ToString(? Get(result, "0")).
let match_str = result.get("0", context)?.to_string(context)?;
// 2. If matchStr is the empty String, then
if match_str.is_empty() {
// a. Let thisIndex be ℝ(? ToLength(? Get(rx, "lastIndex"))).
let this_index = rx.get("lastIndex", context)?.to_length(context)?;
// b. Let nextIndex be AdvanceStringIndex(S, thisIndex, fullUnicode).
let next_index = advance_string_index(arg_str.clone(), this_index, unicode);
// c. Perform ? Set(rx, "lastIndex", 𝔽(nextIndex), true).
rx.set("lastIndex", JsValue::new(next_index), true, context)?;
}
}
} else {
break;
}
}
// 12. Let accumulatedResult be the empty String.
let mut accumulated_result = JsString::new("");
// 13. Let nextSourcePosition be 0.
let mut next_source_position = 0;
// 14. For each element result of results, do
for result in results {
// a. Let resultLength be ? LengthOfArrayLike(result).
let result_length = result.length_of_array_like(context)? as isize;
// b. Let nCaptures be max(resultLength - 1, 0).
let n_captures = std::cmp::max(result_length - 1, 0);
// c. Let matched be ? ToString(? Get(result, "0")).
let matched = result.get("0", context)?.to_string(context)?;
// d. Let matchLength be the number of code units in matched.
let match_length = matched.encode_utf16().count();
// e. Let position be ? ToIntegerOrInfinity(? Get(result, "index")).
let position = result
.get("index", context)?
.to_integer_or_infinity(context)?;
// f. Set position to the result of clamping position between 0 and lengthS.
//position = position.
let position = match position {
IntegerOrInfinity::Integer(i) => {
if i < 0 {
0
} else if i as usize > length_arg_str {
length_arg_str
} else {
i as usize
}
}
IntegerOrInfinity::PositiveInfinity => length_arg_str,
IntegerOrInfinity::NegativeInfinity => 0,
};
// h. Let captures be a new empty List.
let mut captures = Vec::new();
// g. Let n be 1.
// i. Repeat, while n ≤ nCaptures,
for n in 1..=n_captures {
// i. Let capN be ? Get(result, ! ToString(𝔽(n))).
let mut cap_n = result.get(n.to_string(), context)?;
// ii. If capN is not undefined, then
if !cap_n.is_undefined() {
// 1. Set capN to ? ToString(capN).
cap_n = cap_n.to_string(context)?.into();
}
// iii. Append capN as the last element of captures.
captures.push(cap_n);
// iv. Set n to n + 1.
}
// j. Let namedCaptures be ? Get(result, "groups").
let mut named_captures = result.get("groups", context)?;
// k. If functionalReplace is true, then
// l. Else,
let replacement: JsString;
if functional_replace {
// i. Let replacerArgs be « matched ».
let mut replacer_args = vec![JsValue::new(matched)];
// ii. Append in List order the elements of captures to the end of the List replacerArgs.
replacer_args.extend(captures);
// iii. Append 𝔽(position) and S to replacerArgs.
replacer_args.push(position.into());
replacer_args.push(arg_str.clone().into());
// iv. If namedCaptures is not undefined, then
if !named_captures.is_undefined() {
// 1. Append namedCaptures as the last element of replacerArgs.
replacer_args.push(named_captures);
}
// v. Let replValue be ? Call(replaceValue, undefined, replacerArgs).
let repl_value =
context.call(&replace_value, &JsValue::undefined(), &replacer_args)?;
// vi. Let replacement be ? ToString(replValue).
replacement = repl_value.to_string(context)?;
} else {
// i. If namedCaptures is not undefined, then
if !named_captures.is_undefined() {
// 1. Set namedCaptures to ? ToObject(namedCaptures).
named_captures = named_captures.to_object(context)?.into();
}
// ii. Let replacement be ? GetSubstitution(matched, S, position, captures, namedCaptures, replaceValue).
replacement = string::get_substitution(
matched.to_string(),
arg_str.to_string(),
position,
captures,
named_captures,
replace_value.to_string(context)?,
context,
)?;
}
// m. If position ≥ nextSourcePosition, then
if position >= next_source_position {
// i. NOTE: position should not normally move backwards.
// If it does, it is an indication of an ill-behaving RegExp subclass
// or use of an access triggered side-effect to change the global flag or other characteristics of rx.
// In such cases, the corresponding substitution is ignored.
// ii. Set accumulatedResult to the string-concatenation of accumulatedResult,
// the substring of S from nextSourcePosition to position, and replacement.
accumulated_result = format!(
"{}{}{}",
accumulated_result,
arg_str.get(next_source_position..position).unwrap(),
replacement
)
.into();
// iii. Set nextSourcePosition to position + matchLength.
next_source_position = position + match_length;
}
}
// 15. If nextSourcePosition ≥ lengthS, return accumulatedResult.
if next_source_position >= length_arg_str {
return Ok(accumulated_result.into());
}
// 16. Return the string-concatenation of accumulatedResult and the substring of S from nextSourcePosition.
Ok(format!(
"{}{}",
accumulated_result,
arg_str.get(next_source_position..).unwrap()
)
.into())
}
/// `RegExp.prototype[ @@search ]( string )`
///
/// This method executes a search for a match between a this regular expression and a string.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-regexp.prototype-@@search
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@search
pub(crate) fn search(
this: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let rx be the this value.
// 2. If Type(rx) is not Object, throw a TypeError exception.
let rx = if let Some(rx) = this.as_object() {
rx
} else {
return Err(context.construct_type_error(
"RegExp.prototype[Symbol.search] method called on incompatible value",
));
};
// 3. Let S be ? ToString(string).
let arg_str = args
.get(0)
.cloned()
.unwrap_or_default()
.to_string(context)?;
// 4. Let previousLastIndex be ? Get(rx, "lastIndex").
let previous_last_index = rx.get("lastIndex", context)?;
// 5. If SameValue(previousLastIndex, +0𝔽) is false, then
if !JsValue::same_value(&previous_last_index, &JsValue::new(0)) {
// a. Perform ? Set(rx, "lastIndex", +0𝔽, true).
rx.set("lastIndex", 0, true, context)?;
}
// 6. Let result be ? RegExpExec(rx, S).
let result = Self::abstract_exec(&JsValue::new(rx.clone()), arg_str, context)?;
// 7. Let currentLastIndex be ? Get(rx, "lastIndex").
let current_last_index = rx.get("lastIndex", context)?;
// 8. If SameValue(currentLastIndex, previousLastIndex) is false, then
if !JsValue::same_value(¤t_last_index, &previous_last_index) {
// a. Perform ? Set(rx, "lastIndex", previousLastIndex, true).
rx.set("lastIndex", previous_last_index, true, context)?;
}
// 9. If result is null, return -1𝔽.
// 10. Return ? Get(result, "index").
if let Some(result) = result {
result.get("index", context)
} else {
Ok(JsValue::new(-1))
}
}
/// `RegExp.prototype [ @@split ] ( string, limit )`
///
/// The [@@split]() method splits a String object into an array of strings by separating the string into substrings.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-regexp.prototype-@@split
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@split
pub(crate) fn split(
this: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let rx be the this value.
// 2. If Type(rx) is not Object, throw a TypeError exception.
let rx = if let Some(rx) = this.as_object() {
rx
} else {
return Err(context.construct_type_error(
"RegExp.prototype.split method called on incompatible value",
));
};
// 3. Let S be ? ToString(string).
let arg_str = args
.get(0)
.cloned()
.unwrap_or_default()
.to_string(context)?;
// 4. Let C be ? SpeciesConstructor(rx, %RegExp%).
let constructor =
rx.species_constructor(context.global_object().get(RegExp::NAME, context)?, context)?;
// 5. Let flags be ? ToString(? Get(rx, "flags")).
let flags = rx.get("flags", context)?.to_string(context)?;
// 6. If flags contains "u", let unicodeMatching be true.
// 7. Else, let unicodeMatching be false.
let unicode = flags.contains('u');
// 8. If flags contains "y", let newFlags be flags.
// 9. Else, let newFlags be the string-concatenation of flags and "y".
let new_flags = if flags.contains('y') {
flags.to_string()
} else {
format!("{}{}", flags, 'y')
};
// 10. Let splitter be ? Construct(C, « rx, newFlags »).
let splitter = constructor
.as_object()
.expect("SpeciesConstructor returned non Object")
.construct(
&[JsValue::from(rx), new_flags.into()],
&constructor,
context,
)?;
// 11. Let A be ! ArrayCreate(0).
let a = Array::array_create(0, None, context).unwrap();
// 12. Let lengthA be 0.
let mut length_a = 0;
// 13. If limit is undefined, let lim be 2^32 - 1; else let lim be ℝ(? ToUint32(limit)).
let limit = args.get_or_undefined(1);
let lim = if limit.is_undefined() {
u32::MAX
} else {
limit.to_u32(context)?
};
// 14. If lim is 0, return A.
if lim == 0 {
return Ok(a.into());
}
// 15. Let size be the length of S.
let size = arg_str.encode_utf16().count();
// 16. If size is 0, then
if size == 0 {
// a. Let z be ? RegExpExec(splitter, S).
let result = Self::abstract_exec(&splitter, arg_str.clone(), context)?;
// b. If z is not null, return A.
if result.is_some() {
return Ok(a.into());
}
// c. Perform ! CreateDataPropertyOrThrow(A, "0", S).
a.create_data_property_or_throw(0, arg_str, context)
.unwrap();
// d. Return A.
return Ok(a.into());
}
// 17. Let p be 0.
// 18. Let q be p.
let mut p = 0;
let mut q = p;
// 19. Repeat, while q < size,
while q < size {
// a. Perform ? Set(splitter, "lastIndex", 𝔽(q), true).
splitter.set_field("lastIndex", JsValue::new(q), true, context)?;
// b. Let z be ? RegExpExec(splitter, S).
let result = Self::abstract_exec(&splitter, arg_str.clone(), context)?;
// c. If z is null, set q to AdvanceStringIndex(S, q, unicodeMatching).
// d. Else,
if let Some(result) = result {
// i. Let e be ℝ(? ToLength(? Get(splitter, "lastIndex"))).
let mut e = splitter
.get_field("lastIndex", context)?
.to_length(context)?;
// ii. Set e to min(e, size).
e = std::cmp::min(e, size);
// iii. If e = p, set q to AdvanceStringIndex(S, q, unicodeMatching).
// iv. Else,
if e == p {
q = advance_string_index(arg_str.clone(), q, unicode);
} else {
// 1. Let T be the substring of S from p to q.
let arg_str_substring = String::from_utf16_lossy(
&arg_str
.encode_utf16()
.skip(p)
.take(q - p)
.collect::<Vec<u16>>(),
);
// 2. Perform ! CreateDataPropertyOrThrow(A, ! ToString(𝔽(lengthA)), T).
a.create_data_property_or_throw(length_a, arg_str_substring, context)
.unwrap();
// 3. Set lengthA to lengthA + 1.
length_a += 1;
// 4. If lengthA = lim, return A.
if length_a == lim {
return Ok(a.into());
}
// 5. Set p to e.
p = e;
// 6. Let numberOfCaptures be ? LengthOfArrayLike(z).
let mut number_of_captures = result.length_of_array_like(context)? as isize;
// 7. Set numberOfCaptures to max(numberOfCaptures - 1, 0).
number_of_captures = if number_of_captures == 0 {
0
} else {
std::cmp::max(number_of_captures - 1, 0)
};
// 8. Let i be 1.
// 9. Repeat, while i ≤ numberOfCaptures,
for i in 1..=number_of_captures {
// a. Let nextCapture be ? Get(z, ! ToString(𝔽(i))).
let next_capture = result.get(i.to_string(), context)?;
// b. Perform ! CreateDataPropertyOrThrow(A, ! ToString(𝔽(lengthA)), nextCapture).
a.create_data_property_or_throw(length_a, next_capture, context)
.unwrap();
// d. Set lengthA to lengthA + 1.
length_a += 1;
// e. If lengthA = lim, return A.
if length_a == lim {
return Ok(a.into());
}
}
// 10. Set q to p.
q = p;
}
} else {
q = advance_string_index(arg_str.clone(), q, unicode);
}
}
// 20. Let T be the substring of S from p to size.
let arg_str_substring = String::from_utf16_lossy(
&arg_str
.encode_utf16()
.skip(p)
.take(size - p)
.collect::<Vec<u16>>(),
);
// 21. Perform ! CreateDataPropertyOrThrow(A, ! ToString(𝔽(lengthA)), T).
a.create_data_property_or_throw(length_a, arg_str_substring, context)
.unwrap();
// 22. Return A.
Ok(a.into())
}
}
/// `22.2.5.2.3 AdvanceStringIndex ( S, index, unicode )`
///
/// More information:
/// - [ECMAScript reference][spec]
///
/// [spec]: https://tc39.es/ecma262/#sec-advancestringindex
fn advance_string_index(s: JsString, index: usize, unicode: bool) -> usize {
// Regress only works with utf8, so this function differs from the spec.
// 1. Assert: index ≤ 2^53 - 1.
// 2. If unicode is false, return index + 1.
if !unicode {
return index + 1;
}
// 3. Let length be the number of code units in S.
let length = s.encode_utf16().count();
// 4. If index + 1 ≥ length, return index + 1.
if index + 1 > length {
return index + 1;
}
// 5. Let cp be ! CodePointAt(S, index).
let (_, offset, _) =
crate::builtins::string::code_point_at(s, index as i32).expect("Failed to get code point");
index + offset as usize
}