RegExpObject.cpp 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  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/GlobalObject.h>
  8. #include <LibJS/Runtime/PrimitiveString.h>
  9. #include <LibJS/Runtime/RegExpObject.h>
  10. #include <LibJS/Runtime/StringPrototype.h>
  11. #include <LibJS/Runtime/Value.h>
  12. #include <LibJS/Token.h>
  13. namespace JS {
  14. Result<regex::RegexOptions<ECMAScriptFlags>, String> regex_flags_from_string(StringView flags)
  15. {
  16. bool d = false, g = false, i = false, m = false, s = false, u = false, y = false;
  17. auto options = RegExpObject::default_flags;
  18. for (auto ch : flags) {
  19. switch (ch) {
  20. case 'd':
  21. if (d)
  22. return String::formatted(ErrorType::RegExpObjectRepeatedFlag.message(), ch);
  23. d = true;
  24. break;
  25. case 'g':
  26. if (g)
  27. return String::formatted(ErrorType::RegExpObjectRepeatedFlag.message(), ch);
  28. g = true;
  29. options |= regex::ECMAScriptFlags::Global;
  30. break;
  31. case 'i':
  32. if (i)
  33. return String::formatted(ErrorType::RegExpObjectRepeatedFlag.message(), ch);
  34. i = true;
  35. options |= regex::ECMAScriptFlags::Insensitive;
  36. break;
  37. case 'm':
  38. if (m)
  39. return String::formatted(ErrorType::RegExpObjectRepeatedFlag.message(), ch);
  40. m = true;
  41. options |= regex::ECMAScriptFlags::Multiline;
  42. break;
  43. case 's':
  44. if (s)
  45. return String::formatted(ErrorType::RegExpObjectRepeatedFlag.message(), ch);
  46. s = true;
  47. options |= regex::ECMAScriptFlags::SingleLine;
  48. break;
  49. case 'u':
  50. if (u)
  51. return String::formatted(ErrorType::RegExpObjectRepeatedFlag.message(), ch);
  52. u = true;
  53. options |= regex::ECMAScriptFlags::Unicode;
  54. break;
  55. case 'y':
  56. if (y)
  57. return String::formatted(ErrorType::RegExpObjectRepeatedFlag.message(), ch);
  58. y = true;
  59. // Now for the more interesting flag, 'sticky' actually unsets 'global', part of which is the default.
  60. options.reset_flag(regex::ECMAScriptFlags::Global);
  61. // "What's the difference between sticky and global, then", that's simple.
  62. // all the other flags imply 'global', and the "global" flag implies 'stateful';
  63. // however, the "sticky" flag does *not* imply 'global', only 'stateful'.
  64. options |= (regex::ECMAScriptFlags)regex::AllFlags::Internal_Stateful;
  65. options |= regex::ECMAScriptFlags::Sticky;
  66. break;
  67. default:
  68. return String::formatted(ErrorType::RegExpObjectBadFlag.message(), ch);
  69. }
  70. }
  71. return options;
  72. }
  73. String parse_regex_pattern(StringView pattern, bool unicode)
  74. {
  75. auto utf16_pattern = AK::utf8_to_utf16(pattern);
  76. Utf16View utf16_pattern_view { utf16_pattern };
  77. StringBuilder builder;
  78. // If the Unicode flag is set, append each code point to the pattern. Otherwise, append each
  79. // code unit. But unlike the spec, multi-byte code units must be escaped for LibRegex to parse.
  80. for (size_t i = 0; i < utf16_pattern_view.length_in_code_units();) {
  81. if (unicode) {
  82. auto code_point = code_point_at(utf16_pattern_view, i);
  83. builder.append_code_point(code_point.code_point);
  84. i += code_point.code_unit_count;
  85. continue;
  86. }
  87. u16 code_unit = utf16_pattern_view.code_unit_at(i);
  88. ++i;
  89. if (code_unit > 0x7f)
  90. builder.appendff("\\u{:04x}", code_unit);
  91. else
  92. builder.append_code_point(code_unit);
  93. }
  94. return builder.build();
  95. }
  96. RegExpObject* RegExpObject::create(GlobalObject& global_object)
  97. {
  98. return global_object.heap().allocate<RegExpObject>(global_object, *global_object.regexp_prototype());
  99. }
  100. RegExpObject* RegExpObject::create(GlobalObject& global_object, Regex<ECMA262> regex, String pattern, String flags)
  101. {
  102. return global_object.heap().allocate<RegExpObject>(global_object, move(regex), move(pattern), move(flags), *global_object.regexp_prototype());
  103. }
  104. RegExpObject::RegExpObject(Object& prototype)
  105. : Object(prototype)
  106. {
  107. }
  108. RegExpObject::RegExpObject(Regex<ECMA262> regex, String pattern, String flags, Object& prototype)
  109. : Object(prototype)
  110. , m_pattern(move(pattern))
  111. , m_flags(move(flags))
  112. , m_regex(move(regex))
  113. {
  114. VERIFY(m_regex->parser_result.error == regex::Error::NoError);
  115. }
  116. void RegExpObject::initialize(GlobalObject& global_object)
  117. {
  118. auto& vm = this->vm();
  119. Object::initialize(global_object);
  120. define_direct_property(vm.names.lastIndex, Value(0), Attribute::Writable);
  121. }
  122. // 22.2.3.2.2 RegExpInitialize ( obj, pattern, flags ), https://tc39.es/ecma262/#sec-regexpinitialize
  123. ThrowCompletionOr<RegExpObject*> RegExpObject::regexp_initialize(GlobalObject& global_object, Value pattern, Value flags)
  124. {
  125. auto& vm = global_object.vm();
  126. String f;
  127. if (flags.is_undefined()) {
  128. f = String::empty();
  129. } else {
  130. f = TRY(flags.to_string(global_object));
  131. }
  132. String original_pattern;
  133. String parsed_pattern;
  134. if (pattern.is_undefined()) {
  135. original_pattern = String::empty();
  136. parsed_pattern = String::empty();
  137. } else {
  138. original_pattern = TRY(pattern.to_string(global_object));
  139. bool unicode = f.find('u').has_value();
  140. parsed_pattern = parse_regex_pattern(original_pattern, unicode);
  141. }
  142. auto parsed_flags_or_error = regex_flags_from_string(f);
  143. if (parsed_flags_or_error.is_error())
  144. return vm.throw_completion<SyntaxError>(global_object, parsed_flags_or_error.release_error());
  145. Regex<ECMA262> regex(move(parsed_pattern), parsed_flags_or_error.release_value());
  146. if (regex.parser_result.error != regex::Error::NoError)
  147. return vm.throw_completion<SyntaxError>(global_object, ErrorType::RegExpCompileError, regex.error_string());
  148. m_pattern = move(original_pattern);
  149. m_flags = move(f);
  150. m_regex = move(regex);
  151. TRY(set(vm.names.lastIndex, Value(0), Object::ShouldThrowExceptions::Yes));
  152. return this;
  153. }
  154. // 22.2.3.2.5 EscapeRegExpPattern ( P, F ), https://tc39.es/ecma262/#sec-escaperegexppattern
  155. String RegExpObject::escape_regexp_pattern() const
  156. {
  157. if (m_pattern.is_empty())
  158. return "(?:)";
  159. // FIXME: Check u flag and escape accordingly
  160. return m_pattern.replace("\n", "\\n", ReplaceMode::All).replace("\r", "\\r", ReplaceMode::All).replace(LINE_SEPARATOR_STRING, "\\u2028", ReplaceMode::All).replace(PARAGRAPH_SEPARATOR_STRING, "\\u2029", ReplaceMode::All).replace("/", "\\/", ReplaceMode::All);
  161. }
  162. // 22.2.3.2.4 RegExpCreate ( P, F ), https://tc39.es/ecma262/#sec-regexpcreate
  163. ThrowCompletionOr<RegExpObject*> regexp_create(GlobalObject& global_object, Value pattern, Value flags)
  164. {
  165. auto* regexp_object = RegExpObject::create(global_object);
  166. return TRY(regexp_object->regexp_initialize(global_object, pattern, flags));
  167. }
  168. }