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