RegExpObject.cpp 14 KB

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