RegExpObject.cpp 15 KB

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