RegExpObject.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. /*
  2. * Copyright (c) 2020, Matthew Olsson <mattco@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Function.h>
  7. #include <LibJS/Runtime/AbstractOperations.h>
  8. #include <LibJS/Runtime/GlobalObject.h>
  9. #include <LibJS/Runtime/PrimitiveString.h>
  10. #include <LibJS/Runtime/RegExpConstructor.h>
  11. #include <LibJS/Runtime/RegExpObject.h>
  12. #include <LibJS/Runtime/StringPrototype.h>
  13. #include <LibJS/Runtime/Value.h>
  14. #include <LibJS/Token.h>
  15. namespace JS {
  16. Result<regex::RegexOptions<ECMAScriptFlags>, DeprecatedString> regex_flags_from_string(StringView flags)
  17. {
  18. bool d = false, g = false, i = false, m = false, s = false, u = false, y = false, v = false;
  19. auto options = RegExpObject::default_flags;
  20. for (auto ch : flags) {
  21. switch (ch) {
  22. case 'd':
  23. if (d)
  24. return DeprecatedString::formatted(ErrorType::RegExpObjectRepeatedFlag.message(), ch);
  25. d = true;
  26. break;
  27. case 'g':
  28. if (g)
  29. return DeprecatedString::formatted(ErrorType::RegExpObjectRepeatedFlag.message(), ch);
  30. g = true;
  31. options |= regex::ECMAScriptFlags::Global;
  32. break;
  33. case 'i':
  34. if (i)
  35. return DeprecatedString::formatted(ErrorType::RegExpObjectRepeatedFlag.message(), ch);
  36. i = true;
  37. options |= regex::ECMAScriptFlags::Insensitive;
  38. break;
  39. case 'm':
  40. if (m)
  41. return DeprecatedString::formatted(ErrorType::RegExpObjectRepeatedFlag.message(), ch);
  42. m = true;
  43. options |= regex::ECMAScriptFlags::Multiline;
  44. break;
  45. case 's':
  46. if (s)
  47. return DeprecatedString::formatted(ErrorType::RegExpObjectRepeatedFlag.message(), ch);
  48. s = true;
  49. options |= regex::ECMAScriptFlags::SingleLine;
  50. break;
  51. case 'u':
  52. if (u)
  53. return DeprecatedString::formatted(ErrorType::RegExpObjectRepeatedFlag.message(), ch);
  54. u = true;
  55. options |= regex::ECMAScriptFlags::Unicode;
  56. break;
  57. case 'y':
  58. if (y)
  59. return DeprecatedString::formatted(ErrorType::RegExpObjectRepeatedFlag.message(), ch);
  60. y = true;
  61. // Now for the more interesting flag, 'sticky' actually unsets 'global', part of which is the default.
  62. options.reset_flag(regex::ECMAScriptFlags::Global);
  63. // "What's the difference between sticky and global, then", that's simple.
  64. // all the other flags imply 'global', and the "global" flag implies 'stateful';
  65. // however, the "sticky" flag does *not* imply 'global', only 'stateful'.
  66. options |= (regex::ECMAScriptFlags)regex::AllFlags::Internal_Stateful;
  67. options |= regex::ECMAScriptFlags::Sticky;
  68. break;
  69. case 'v':
  70. if (v)
  71. return DeprecatedString::formatted(ErrorType::RegExpObjectRepeatedFlag.message(), ch);
  72. v = true;
  73. options |= regex::ECMAScriptFlags::UnicodeSets;
  74. break;
  75. default:
  76. return DeprecatedString::formatted(ErrorType::RegExpObjectBadFlag.message(), ch);
  77. }
  78. }
  79. return options;
  80. }
  81. // 22.2.3.4 Static Semantics: ParsePattern ( patternText, u, v ), https://tc39.es/ecma262/#sec-parsepattern
  82. ErrorOr<DeprecatedString, ParseRegexPatternError> parse_regex_pattern(StringView pattern, bool unicode, bool unicode_sets)
  83. {
  84. if (unicode && unicode_sets)
  85. return ParseRegexPatternError { DeprecatedString::formatted(ErrorType::RegExpObjectIncompatibleFlags.message(), 'u', 'v') };
  86. auto utf16_pattern_result = AK::utf8_to_utf16(pattern);
  87. if (utf16_pattern_result.is_error())
  88. return ParseRegexPatternError { "Out of memory"sv };
  89. auto utf16_pattern = utf16_pattern_result.release_value();
  90. Utf16View utf16_pattern_view { utf16_pattern };
  91. StringBuilder builder;
  92. // If the Unicode flag is set, append each code point to the pattern. Otherwise, append each
  93. // code unit. But unlike the spec, multi-byte code units must be escaped for LibRegex to parse.
  94. auto previous_code_unit_was_backslash = false;
  95. for (size_t i = 0; i < utf16_pattern_view.length_in_code_units();) {
  96. if (unicode || unicode_sets) {
  97. auto code_point = code_point_at(utf16_pattern_view, i);
  98. builder.append_code_point(code_point.code_point);
  99. i += code_point.code_unit_count;
  100. continue;
  101. }
  102. u16 code_unit = utf16_pattern_view.code_unit_at(i);
  103. ++i;
  104. if (code_unit > 0x7f) {
  105. // Incorrectly escaping this code unit will result in a wildly different regex than intended
  106. // as we're converting <c> to <\uhhhh>, which would turn into <\\uhhhh> if (incorrectly) escaped again,
  107. // leading to a matcher for the literal string "\uhhhh" instead of the intended code unit <c>.
  108. // As such, we're going to remove the (invalid) backslash and pretend it never existed.
  109. if (!previous_code_unit_was_backslash)
  110. builder.append('\\');
  111. builder.appendff("u{:04x}", code_unit);
  112. } else {
  113. builder.append_code_point(code_unit);
  114. }
  115. if (code_unit == '\\')
  116. previous_code_unit_was_backslash = !previous_code_unit_was_backslash;
  117. else
  118. previous_code_unit_was_backslash = false;
  119. }
  120. return builder.to_deprecated_string();
  121. }
  122. // 22.2.3.4 Static Semantics: ParsePattern ( patternText, u, v ), https://tc39.es/ecma262/#sec-parsepattern
  123. ThrowCompletionOr<DeprecatedString> parse_regex_pattern(VM& vm, StringView pattern, bool unicode, bool unicode_sets)
  124. {
  125. auto result = parse_regex_pattern(pattern, unicode, unicode_sets);
  126. if (result.is_error())
  127. return vm.throw_completion<JS::SyntaxError>(result.release_error().error);
  128. return result.release_value();
  129. }
  130. NonnullGCPtr<RegExpObject> RegExpObject::create(Realm& realm)
  131. {
  132. return realm.heap().allocate<RegExpObject>(realm, realm.intrinsics().regexp_prototype());
  133. }
  134. NonnullGCPtr<RegExpObject> RegExpObject::create(Realm& realm, Regex<ECMA262> regex, DeprecatedString pattern, DeprecatedString flags)
  135. {
  136. return realm.heap().allocate<RegExpObject>(realm, move(regex), move(pattern), move(flags), realm.intrinsics().regexp_prototype());
  137. }
  138. RegExpObject::RegExpObject(Object& prototype)
  139. : Object(ConstructWithPrototypeTag::Tag, prototype)
  140. {
  141. }
  142. RegExpObject::RegExpObject(Regex<ECMA262> regex, DeprecatedString pattern, DeprecatedString flags, Object& prototype)
  143. : Object(ConstructWithPrototypeTag::Tag, prototype)
  144. , m_pattern(move(pattern))
  145. , m_flags(move(flags))
  146. , m_regex(move(regex))
  147. {
  148. VERIFY(m_regex->parser_result.error == regex::Error::NoError);
  149. }
  150. void RegExpObject::initialize(Realm& realm)
  151. {
  152. auto& vm = this->vm();
  153. Base::initialize(realm);
  154. define_direct_property(vm.names.lastIndex, Value(0), Attribute::Writable);
  155. }
  156. // 22.2.3.3 RegExpInitialize ( obj, pattern, flags ), https://tc39.es/ecma262/#sec-regexpinitialize
  157. ThrowCompletionOr<NonnullGCPtr<RegExpObject>> RegExpObject::regexp_initialize(VM& vm, Value pattern_value, Value flags_value)
  158. {
  159. // 1. If pattern is undefined, let P be the empty String.
  160. // 2. Else, let P be ? ToString(pattern).
  161. auto pattern = pattern_value.is_undefined()
  162. ? DeprecatedString::empty()
  163. : TRY(pattern_value.to_deprecated_string(vm));
  164. // 3. If flags is undefined, let F be the empty String.
  165. // 4. Else, let F be ? ToString(flags).
  166. auto flags = flags_value.is_undefined()
  167. ? DeprecatedString::empty()
  168. : TRY(flags_value.to_deprecated_string(vm));
  169. // 5. If F contains any code unit other than "d", "g", "i", "m", "s", "u", "v", or "y", or if F contains any code unit more than once, throw a SyntaxError exception.
  170. // 6. If F contains "i", let i be true; else let i be false.
  171. // 7. If F contains "m", let m be true; else let m be false.
  172. // 8. If F contains "s", let s be true; else let s be false.
  173. // 9. If F contains "u", let u be true; else let u be false.
  174. // 10. If F contains "v", let v be true; else let v be false.
  175. auto parsed_flags_or_error = regex_flags_from_string(flags);
  176. if (parsed_flags_or_error.is_error())
  177. return vm.throw_completion<SyntaxError>(parsed_flags_or_error.release_error());
  178. auto parsed_flags = parsed_flags_or_error.release_value();
  179. auto parsed_pattern = DeprecatedString::empty();
  180. if (!pattern.is_empty()) {
  181. bool unicode = parsed_flags.has_flag_set(regex::ECMAScriptFlags::Unicode);
  182. bool unicode_sets = parsed_flags.has_flag_set(regex::ECMAScriptFlags::UnicodeSets);
  183. // 11. If u is true or v is true, then
  184. // a. Let patternText be StringToCodePoints(P).
  185. // 12. Else,
  186. // a. Let patternText be the result of interpreting each of P's 16-bit elements as a Unicode BMP code point. UTF-16 decoding is not applied to the elements.
  187. // 13. Let parseResult be ParsePattern(patternText, u, v).
  188. parsed_pattern = TRY(parse_regex_pattern(vm, pattern, unicode, unicode_sets));
  189. }
  190. // 14. If parseResult is a non-empty List of SyntaxError objects, throw a SyntaxError exception.
  191. Regex<ECMA262> regex(move(parsed_pattern), parsed_flags);
  192. if (regex.parser_result.error != regex::Error::NoError)
  193. return vm.throw_completion<SyntaxError>(ErrorType::RegExpCompileError, regex.error_string());
  194. // 15. Assert: parseResult is a Pattern Parse Node.
  195. VERIFY(regex.parser_result.error == regex::Error::NoError);
  196. // 16. Set obj.[[OriginalSource]] to P.
  197. m_pattern = move(pattern);
  198. // 17. Set obj.[[OriginalFlags]] to F.
  199. m_flags = move(flags);
  200. // 18. Let capturingGroupsCount be CountLeftCapturingParensWithin(parseResult).
  201. // 19. Let rer be the RegExp Record { [[IgnoreCase]]: i, [[Multiline]]: m, [[DotAll]]: s, [[Unicode]]: u, [[CapturingGroupsCount]]: capturingGroupsCount }.
  202. // 20. Set obj.[[RegExpRecord]] to rer.
  203. // 21. Set obj.[[RegExpMatcher]] to CompilePattern of parseResult with argument rer.
  204. m_regex = move(regex);
  205. // 22. Perform ? Set(obj, "lastIndex", +0𝔽, true).
  206. TRY(set(vm.names.lastIndex, Value(0), Object::ShouldThrowExceptions::Yes));
  207. // 23. Return obj.
  208. return NonnullGCPtr { *this };
  209. }
  210. // 22.2.6.13.1 EscapeRegExpPattern ( P, F ), https://tc39.es/ecma262/#sec-escaperegexppattern
  211. DeprecatedString RegExpObject::escape_regexp_pattern() const
  212. {
  213. // 1. Let S be a String in the form of a Pattern[~UnicodeMode] (Pattern[+UnicodeMode] if F contains "u") equivalent
  214. // to P interpreted as UTF-16 encoded Unicode code points (6.1.4), in which certain code points are escaped as
  215. // described below. S may or may not be identical to P; however, the Abstract Closure that would result from
  216. // evaluating S as a Pattern[~UnicodeMode] (Pattern[+UnicodeMode] if F contains "u") must behave identically to
  217. // the Abstract Closure given by the constructed object's [[RegExpMatcher]] internal slot. Multiple calls to
  218. // this abstract operation using the same values for P and F must produce identical results.
  219. // 2. The code points / or any LineTerminator occurring in the pattern shall be escaped in S as necessary to ensure
  220. // that the string-concatenation of "/", S, "/", and F can be parsed (in an appropriate lexical context) as a
  221. // RegularExpressionLiteral that behaves identically to the constructed regular expression. For example, if P is
  222. // "/", then S could be "\/" or "\u002F", among other possibilities, but not "/", because /// followed by F
  223. // would be parsed as a SingleLineComment rather than a RegularExpressionLiteral. If P is the empty String, this
  224. // specification can be met by letting S be "(?:)".
  225. // 3. Return S.
  226. if (m_pattern.is_empty())
  227. return "(?:)";
  228. // FIXME: Check the 'u' and 'v' flags and escape accordingly
  229. StringBuilder builder;
  230. auto pattern = Utf8View { m_pattern };
  231. auto escaped = false;
  232. for (auto code_point : pattern) {
  233. if (escaped) {
  234. escaped = false;
  235. builder.append_code_point('\\');
  236. builder.append_code_point(code_point);
  237. continue;
  238. }
  239. if (code_point == '\\') {
  240. escaped = true;
  241. continue;
  242. }
  243. switch (code_point) {
  244. case '/':
  245. builder.append("\\/"sv);
  246. break;
  247. case '\n':
  248. builder.append("\\n"sv);
  249. break;
  250. case '\r':
  251. builder.append("\\r"sv);
  252. break;
  253. case LINE_SEPARATOR:
  254. builder.append("\\u2028"sv);
  255. break;
  256. case PARAGRAPH_SEPARATOR:
  257. builder.append("\\u2029"sv);
  258. break;
  259. default:
  260. builder.append_code_point(code_point);
  261. break;
  262. }
  263. }
  264. return builder.to_deprecated_string();
  265. }
  266. // 22.2.3.1 RegExpCreate ( P, F ), https://tc39.es/ecma262/#sec-regexpcreate
  267. ThrowCompletionOr<NonnullGCPtr<RegExpObject>> regexp_create(VM& vm, Value pattern, Value flags)
  268. {
  269. auto& realm = *vm.current_realm();
  270. // 1. Let obj be ! RegExpAlloc(%RegExp%).
  271. auto regexp_object = MUST(regexp_alloc(vm, realm.intrinsics().regexp_constructor()));
  272. // 2. Return ? RegExpInitialize(obj, P, F).
  273. return TRY(regexp_object->regexp_initialize(vm, pattern, flags));
  274. }
  275. // 22.2.3.2 RegExpAlloc ( newTarget ), https://tc39.es/ecma262/#sec-regexpalloc
  276. // 22.2.3.2 RegExpAlloc ( newTarget ), https://github.com/tc39/proposal-regexp-legacy-features#regexpalloc--newtarget-
  277. ThrowCompletionOr<NonnullGCPtr<RegExpObject>> regexp_alloc(VM& vm, FunctionObject& new_target)
  278. {
  279. // 1. Let obj be ? OrdinaryCreateFromConstructor(newTarget, "%RegExp.prototype%", « [[OriginalSource]], [[OriginalFlags]], [[RegExpRecord]], [[RegExpMatcher]] »).
  280. auto regexp_object = TRY(ordinary_create_from_constructor<RegExpObject>(vm, new_target, &Intrinsics::regexp_prototype));
  281. // 2. Let thisRealm be the current Realm Record.
  282. auto& this_realm = *vm.current_realm();
  283. // 3. Set the value of obj’s [[Realm]] internal slot to thisRealm.
  284. regexp_object->set_realm(this_realm);
  285. // 4. If SameValue(newTarget, thisRealm.[[Intrinsics]].[[%RegExp%]]) is true, then
  286. if (same_value(&new_target, this_realm.intrinsics().regexp_constructor())) {
  287. // i. Set the value of obj’s [[LegacyFeaturesEnabled]] internal slot to true.
  288. regexp_object->set_legacy_features_enabled(true);
  289. }
  290. // 5. Else,
  291. else {
  292. // i. Set the value of obj’s [[LegacyFeaturesEnabled]] internal slot to false.
  293. regexp_object->set_legacy_features_enabled(false);
  294. }
  295. // 6. Perform ! DefinePropertyOrThrow(obj, "lastIndex", PropertyDescriptor { [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false }).
  296. MUST(regexp_object->define_property_or_throw(vm.names.lastIndex, PropertyDescriptor { .writable = true, .enumerable = false, .configurable = false }));
  297. // 7. Return obj.
  298. return regexp_object;
  299. }
  300. }