RegExpObject.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  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>, String> 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 String::formatted(ErrorType::RegExpObjectRepeatedFlag.message(), ch);
  25. d = true;
  26. break;
  27. case 'g':
  28. if (g)
  29. return String::formatted(ErrorType::RegExpObjectRepeatedFlag.message(), ch);
  30. g = true;
  31. options |= regex::ECMAScriptFlags::Global;
  32. break;
  33. case 'i':
  34. if (i)
  35. return String::formatted(ErrorType::RegExpObjectRepeatedFlag.message(), ch);
  36. i = true;
  37. options |= regex::ECMAScriptFlags::Insensitive;
  38. break;
  39. case 'm':
  40. if (m)
  41. return String::formatted(ErrorType::RegExpObjectRepeatedFlag.message(), ch);
  42. m = true;
  43. options |= regex::ECMAScriptFlags::Multiline;
  44. break;
  45. case 's':
  46. if (s)
  47. return String::formatted(ErrorType::RegExpObjectRepeatedFlag.message(), ch);
  48. s = true;
  49. options |= regex::ECMAScriptFlags::SingleLine;
  50. break;
  51. case 'u':
  52. if (u)
  53. return String::formatted(ErrorType::RegExpObjectRepeatedFlag.message(), ch);
  54. u = true;
  55. options |= regex::ECMAScriptFlags::Unicode;
  56. break;
  57. case 'y':
  58. if (y)
  59. return String::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 String::formatted(ErrorType::RegExpObjectRepeatedFlag.message(), ch);
  72. v = true;
  73. options |= regex::ECMAScriptFlags::UnicodeSets;
  74. break;
  75. default:
  76. return String::formatted(ErrorType::RegExpObjectBadFlag.message(), ch);
  77. }
  78. }
  79. return options;
  80. }
  81. ErrorOr<String, ParseRegexPatternError> parse_regex_pattern(StringView pattern, bool unicode, bool unicode_sets)
  82. {
  83. if (unicode && unicode_sets)
  84. return ParseRegexPatternError { String::formatted(ErrorType::RegExpObjectIncompatibleFlags.message(), 'u', 'v') };
  85. auto utf16_pattern = AK::utf8_to_utf16(pattern);
  86. Utf16View utf16_pattern_view { utf16_pattern };
  87. StringBuilder builder;
  88. // If the Unicode flag is set, append each code point to the pattern. Otherwise, append each
  89. // code unit. But unlike the spec, multi-byte code units must be escaped for LibRegex to parse.
  90. for (size_t i = 0; i < utf16_pattern_view.length_in_code_units();) {
  91. if (unicode || unicode_sets) {
  92. auto code_point = code_point_at(utf16_pattern_view, i);
  93. builder.append_code_point(code_point.code_point);
  94. i += code_point.code_unit_count;
  95. continue;
  96. }
  97. u16 code_unit = utf16_pattern_view.code_unit_at(i);
  98. ++i;
  99. if (code_unit > 0x7f)
  100. builder.appendff("\\u{:04x}", code_unit);
  101. else
  102. builder.append_code_point(code_unit);
  103. }
  104. return builder.build();
  105. }
  106. ThrowCompletionOr<String> parse_regex_pattern(VM& vm, StringView pattern, bool unicode, bool unicode_sets)
  107. {
  108. auto result = parse_regex_pattern(pattern, unicode, unicode_sets);
  109. if (result.is_error())
  110. return vm.throw_completion<JS::SyntaxError>(result.release_error().error);
  111. return result.release_value();
  112. }
  113. RegExpObject* RegExpObject::create(Realm& realm)
  114. {
  115. return realm.heap().allocate<RegExpObject>(realm, *realm.intrinsics().regexp_prototype());
  116. }
  117. RegExpObject* RegExpObject::create(Realm& realm, Regex<ECMA262> regex, String pattern, String flags)
  118. {
  119. return realm.heap().allocate<RegExpObject>(realm, move(regex), move(pattern), move(flags), *realm.intrinsics().regexp_prototype());
  120. }
  121. RegExpObject::RegExpObject(Object& prototype)
  122. : Object(prototype)
  123. {
  124. }
  125. RegExpObject::RegExpObject(Regex<ECMA262> regex, String pattern, String flags, Object& prototype)
  126. : Object(prototype)
  127. , m_pattern(move(pattern))
  128. , m_flags(move(flags))
  129. , m_regex(move(regex))
  130. {
  131. VERIFY(m_regex->parser_result.error == regex::Error::NoError);
  132. }
  133. void RegExpObject::initialize(Realm& realm)
  134. {
  135. auto& vm = this->vm();
  136. Object::initialize(realm);
  137. define_direct_property(vm.names.lastIndex, Value(0), Attribute::Writable);
  138. }
  139. // 22.2.3.2.2 RegExpInitialize ( obj, pattern, flags ), https://tc39.es/ecma262/#sec-regexpinitialize
  140. ThrowCompletionOr<NonnullGCPtr<RegExpObject>> RegExpObject::regexp_initialize(VM& vm, Value pattern_value, Value flags_value)
  141. {
  142. // NOTE: This also contains changes adapted from https://arai-a.github.io/ecma262-compare/?pr=2418, which doesn't match the upstream spec anymore.
  143. // 1. If pattern is undefined, let P be the empty String.
  144. // 2. Else, let P be ? ToString(pattern).
  145. auto pattern = pattern_value.is_undefined()
  146. ? String::empty()
  147. : TRY(pattern_value.to_string(vm));
  148. // 3. If flags is undefined, let F be the empty String.
  149. // 4. Else, let F be ? ToString(flags).
  150. auto flags = flags_value.is_undefined()
  151. ? String::empty()
  152. : TRY(flags_value.to_string(vm));
  153. // 5. If F contains any code unit other than "d", "g", "i", "m", "s", "u", or "y" or if it contains the same code unit more than once, throw a SyntaxError exception.
  154. // 6. If F contains "i", let i be true; else let i be false.
  155. // 7. If F contains "m", let m be true; else let m be false.
  156. // 8. If F contains "s", let s be true; else let s be false.
  157. // 9. If F contains "u", let u be true; else let u be false.
  158. // 10. If F contains "v", let v be true; else let v be false.
  159. auto parsed_flags_or_error = regex_flags_from_string(flags);
  160. if (parsed_flags_or_error.is_error())
  161. return vm.throw_completion<SyntaxError>(parsed_flags_or_error.release_error());
  162. auto parsed_flags = parsed_flags_or_error.release_value();
  163. auto parsed_pattern = String::empty();
  164. if (!pattern.is_empty()) {
  165. bool unicode = parsed_flags.has_flag_set(regex::ECMAScriptFlags::Unicode);
  166. bool unicode_sets = parsed_flags.has_flag_set(regex::ECMAScriptFlags::UnicodeSets);
  167. // 11. If u is true, then
  168. // a. Let patternText be StringToCodePoints(P).
  169. // 12. Else,
  170. // 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.
  171. // 13. Let parseResult be ParsePattern(patternText, u, v).
  172. parsed_pattern = TRY(parse_regex_pattern(vm, pattern, unicode, unicode_sets));
  173. }
  174. // 14. If parseResult is a non-empty List of SyntaxError objects, throw a SyntaxError exception.
  175. Regex<ECMA262> regex(move(parsed_pattern), parsed_flags);
  176. if (regex.parser_result.error != regex::Error::NoError)
  177. return vm.throw_completion<SyntaxError>(ErrorType::RegExpCompileError, regex.error_string());
  178. // 15. Assert: parseResult is a Pattern Parse Node.
  179. VERIFY(regex.parser_result.error == regex::Error::NoError);
  180. // 16. Set obj.[[OriginalSource]] to P.
  181. m_pattern = move(pattern);
  182. // 17. Set obj.[[OriginalFlags]] to F.
  183. m_flags = move(flags);
  184. // 18. Let capturingGroupsCount be CountLeftCapturingParensWithin(parseResult).
  185. // 19. Let rer be the RegExp Record { [[IgnoreCase]]: i, [[Multiline]]: m, [[DotAll]]: s, [[Unicode]]: u, [[CapturingGroupsCount]]: capturingGroupsCount }.
  186. // 20. Set obj.[[RegExpRecord]] to rer.
  187. // 21. Set obj.[[RegExpMatcher]] to CompilePattern of parseResult with argument rer.
  188. m_regex = move(regex);
  189. // 22. Perform ? Set(obj, "lastIndex", +0𝔽, true).
  190. TRY(set(vm.names.lastIndex, Value(0), Object::ShouldThrowExceptions::Yes));
  191. // 23. Return obj.
  192. return NonnullGCPtr { *this };
  193. }
  194. // 22.2.3.2.5 EscapeRegExpPattern ( P, F ), https://tc39.es/ecma262/#sec-escaperegexppattern
  195. String RegExpObject::escape_regexp_pattern() const
  196. {
  197. // 1. Let S be a String in the form of a Pattern[~UnicodeMode] (Pattern[+UnicodeMode] if F contains "u") equivalent
  198. // to P interpreted as UTF-16 encoded Unicode code points (6.1.4), in which certain code points are escaped as
  199. // described below. S may or may not be identical to P; however, the Abstract Closure that would result from
  200. // evaluating S as a Pattern[~UnicodeMode] (Pattern[+UnicodeMode] if F contains "u") must behave identically to
  201. // the Abstract Closure given by the constructed object's [[RegExpMatcher]] internal slot. Multiple calls to
  202. // this abstract operation using the same values for P and F must produce identical results.
  203. // 2. The code points / or any LineTerminator occurring in the pattern shall be escaped in S as necessary to ensure
  204. // that the string-concatenation of "/", S, "/", and F can be parsed (in an appropriate lexical context) as a
  205. // RegularExpressionLiteral that behaves identically to the constructed regular expression. For example, if P is
  206. // "/", then S could be "\/" or "\u002F", among other possibilities, but not "/", because /// followed by F
  207. // would be parsed as a SingleLineComment rather than a RegularExpressionLiteral. If P is the empty String, this
  208. // specification can be met by letting S be "(?:)".
  209. // 3. Return S.
  210. if (m_pattern.is_empty())
  211. return "(?:)";
  212. // FIXME: Check the 'u' and 'v' flags and escape accordingly
  213. return m_pattern.replace("\n"sv, "\\n"sv, ReplaceMode::All).replace("\r"sv, "\\r"sv, ReplaceMode::All).replace(LINE_SEPARATOR_STRING, "\\u2028"sv, ReplaceMode::All).replace(PARAGRAPH_SEPARATOR_STRING, "\\u2029"sv, ReplaceMode::All).replace("/"sv, "\\/"sv, ReplaceMode::All);
  214. }
  215. // 22.2.3.2.4 RegExpCreate ( P, F ), https://tc39.es/ecma262/#sec-regexpcreate
  216. ThrowCompletionOr<NonnullGCPtr<RegExpObject>> regexp_create(VM& vm, Value pattern, Value flags)
  217. {
  218. auto& realm = *vm.current_realm();
  219. // 1. Let obj be ! RegExpAlloc(%RegExp%).
  220. auto regexp_object = MUST(regexp_alloc(vm, *realm.intrinsics().regexp_constructor()));
  221. // 2. Return ? RegExpInitialize(obj, P, F).
  222. return TRY(regexp_object->regexp_initialize(vm, pattern, flags));
  223. }
  224. // 22.2.3.2 RegExpAlloc ( newTarget ), https://tc39.es/ecma262/#sec-regexpalloc
  225. // 22.2.3.2 RegExpAlloc ( newTarget ), https://github.com/tc39/proposal-regexp-legacy-features#regexpalloc--newtarget-
  226. ThrowCompletionOr<NonnullGCPtr<RegExpObject>> regexp_alloc(VM& vm, FunctionObject& new_target)
  227. {
  228. // 1. Let obj be ? OrdinaryCreateFromConstructor(newTarget, "%RegExp.prototype%", « [[OriginalSource]], [[OriginalFlags]], [[RegExpRecord]], [[RegExpMatcher]] »).
  229. auto* regexp_object = TRY(ordinary_create_from_constructor<RegExpObject>(vm, new_target, &Intrinsics::regexp_prototype));
  230. // 2. Let thisRealm be the current Realm Record.
  231. auto& this_realm = *vm.current_realm();
  232. // 3. Set the value of obj’s [[Realm]] internal slot to thisRealm.
  233. regexp_object->set_realm(this_realm);
  234. // 4. If SameValue(newTarget, thisRealm.[[Intrinsics]].[[%RegExp%]]) is true, then
  235. auto* regexp_constructor = this_realm.intrinsics().regexp_constructor();
  236. if (same_value(&new_target, regexp_constructor)) {
  237. // i. Set the value of obj’s [[LegacyFeaturesEnabled]] internal slot to true.
  238. regexp_object->set_legacy_features_enabled(true);
  239. }
  240. // 5. Else,
  241. else {
  242. // i. Set the value of obj’s [[LegacyFeaturesEnabled]] internal slot to false.
  243. regexp_object->set_legacy_features_enabled(false);
  244. }
  245. // 6. Perform ! DefinePropertyOrThrow(obj, "lastIndex", PropertyDescriptor { [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false }).
  246. MUST(regexp_object->define_property_or_throw(vm.names.lastIndex, PropertyDescriptor { .writable = true, .enumerable = false, .configurable = false }));
  247. // 7. Return obj.
  248. return NonnullGCPtr { *regexp_object };
  249. }
  250. }