PrimitiveString.cpp 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. /*
  2. * Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2022, Linus Groh <linusg@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/CharacterTypes.h>
  8. #include <AK/Utf16View.h>
  9. #include <AK/Utf8View.h>
  10. #include <LibJS/Runtime/AbstractOperations.h>
  11. #include <LibJS/Runtime/GlobalObject.h>
  12. #include <LibJS/Runtime/PrimitiveString.h>
  13. #include <LibJS/Runtime/PropertyKey.h>
  14. #include <LibJS/Runtime/ThrowableStringBuilder.h>
  15. #include <LibJS/Runtime/VM.h>
  16. #include <LibJS/Runtime/Value.h>
  17. namespace JS {
  18. PrimitiveString::PrimitiveString(PrimitiveString& lhs, PrimitiveString& rhs)
  19. : m_is_rope(true)
  20. , m_lhs(&lhs)
  21. , m_rhs(&rhs)
  22. {
  23. }
  24. PrimitiveString::PrimitiveString(DeprecatedString string)
  25. : m_utf8_string(move(string))
  26. {
  27. }
  28. PrimitiveString::PrimitiveString(Utf16String string)
  29. : m_utf16_string(move(string))
  30. {
  31. }
  32. PrimitiveString::~PrimitiveString()
  33. {
  34. if (has_utf8_string())
  35. vm().string_cache().remove(*m_utf8_string);
  36. }
  37. void PrimitiveString::visit_edges(Cell::Visitor& visitor)
  38. {
  39. Cell::visit_edges(visitor);
  40. if (m_is_rope) {
  41. visitor.visit(m_lhs);
  42. visitor.visit(m_rhs);
  43. }
  44. }
  45. bool PrimitiveString::is_empty() const
  46. {
  47. if (m_is_rope) {
  48. // NOTE: We never make an empty rope string.
  49. return false;
  50. }
  51. if (has_utf16_string())
  52. return m_utf16_string->is_empty();
  53. if (has_utf8_string())
  54. return m_utf8_string->is_empty();
  55. VERIFY_NOT_REACHED();
  56. }
  57. ThrowCompletionOr<DeprecatedString> PrimitiveString::deprecated_string() const
  58. {
  59. TRY(resolve_rope_if_needed());
  60. if (!has_utf8_string()) {
  61. VERIFY(has_utf16_string());
  62. m_utf8_string = TRY(m_utf16_string->to_utf8(vm()));
  63. }
  64. return *m_utf8_string;
  65. }
  66. ThrowCompletionOr<Utf16String> PrimitiveString::utf16_string() const
  67. {
  68. TRY(resolve_rope_if_needed());
  69. if (!has_utf16_string()) {
  70. VERIFY(has_utf8_string());
  71. m_utf16_string = TRY(Utf16String::create(vm(), *m_utf8_string));
  72. }
  73. return *m_utf16_string;
  74. }
  75. ThrowCompletionOr<Utf16View> PrimitiveString::utf16_string_view() const
  76. {
  77. (void)TRY(utf16_string());
  78. return m_utf16_string->view();
  79. }
  80. ThrowCompletionOr<Optional<Value>> PrimitiveString::get(VM& vm, PropertyKey const& property_key) const
  81. {
  82. if (property_key.is_symbol())
  83. return Optional<Value> {};
  84. if (property_key.is_string()) {
  85. if (property_key.as_string() == vm.names.length.as_string()) {
  86. auto length = TRY(utf16_string()).length_in_code_units();
  87. return Value(static_cast<double>(length));
  88. }
  89. }
  90. auto index = canonical_numeric_index_string(property_key, CanonicalIndexMode::IgnoreNumericRoundtrip);
  91. if (!index.is_index())
  92. return Optional<Value> {};
  93. auto str = TRY(utf16_string_view());
  94. auto length = str.length_in_code_units();
  95. if (length <= index.as_index())
  96. return Optional<Value> {};
  97. return create(vm, TRY(Utf16String::create(vm, str.substring_view(index.as_index(), 1))));
  98. }
  99. NonnullGCPtr<PrimitiveString> PrimitiveString::create(VM& vm, Utf16String string)
  100. {
  101. if (string.is_empty())
  102. return vm.empty_string();
  103. if (string.length_in_code_units() == 1) {
  104. u16 code_unit = string.code_unit_at(0);
  105. if (is_ascii(code_unit))
  106. return vm.single_ascii_character_string(static_cast<u8>(code_unit));
  107. }
  108. return vm.heap().allocate_without_realm<PrimitiveString>(move(string));
  109. }
  110. NonnullGCPtr<PrimitiveString> PrimitiveString::create(VM& vm, DeprecatedString string)
  111. {
  112. if (string.is_empty())
  113. return vm.empty_string();
  114. if (string.length() == 1) {
  115. auto ch = static_cast<u8>(string.characters()[0]);
  116. if (is_ascii(ch))
  117. return vm.single_ascii_character_string(ch);
  118. }
  119. auto& string_cache = vm.string_cache();
  120. auto it = string_cache.find(string);
  121. if (it == string_cache.end()) {
  122. auto new_string = vm.heap().allocate_without_realm<PrimitiveString>(string);
  123. string_cache.set(move(string), new_string);
  124. return *new_string;
  125. }
  126. return *it->value;
  127. }
  128. NonnullGCPtr<PrimitiveString> PrimitiveString::create(VM& vm, PrimitiveString& lhs, PrimitiveString& rhs)
  129. {
  130. // We're here to concatenate two strings into a new rope string.
  131. // However, if any of them are empty, no rope is required.
  132. bool lhs_empty = lhs.is_empty();
  133. bool rhs_empty = rhs.is_empty();
  134. if (lhs_empty && rhs_empty)
  135. return vm.empty_string();
  136. if (lhs_empty)
  137. return rhs;
  138. if (rhs_empty)
  139. return lhs;
  140. return vm.heap().allocate_without_realm<PrimitiveString>(lhs, rhs);
  141. }
  142. ThrowCompletionOr<void> PrimitiveString::resolve_rope_if_needed() const
  143. {
  144. if (!m_is_rope)
  145. return {};
  146. auto& vm = this->vm();
  147. // NOTE: Special case for two concatenated UTF-16 strings.
  148. // This is here as an optimization, although I'm unsure how valuable it is.
  149. if (m_lhs->has_utf16_string() && m_rhs->has_utf16_string()) {
  150. auto const& lhs_string = m_lhs->m_utf16_string.value();
  151. auto const& rhs_string = m_rhs->m_utf16_string.value();
  152. Utf16Data combined;
  153. TRY_OR_THROW_OOM(vm, combined.try_ensure_capacity(lhs_string.length_in_code_units() + rhs_string.length_in_code_units()));
  154. combined.extend(lhs_string.string());
  155. combined.extend(rhs_string.string());
  156. m_utf16_string = TRY(Utf16String::create(vm, move(combined)));
  157. m_is_rope = false;
  158. m_lhs = nullptr;
  159. m_rhs = nullptr;
  160. return {};
  161. }
  162. // This vector will hold all the pieces of the rope that need to be assembled
  163. // into the resolved string.
  164. Vector<PrimitiveString const*> pieces;
  165. // NOTE: We traverse the rope tree without using recursion, since we'd run out of
  166. // stack space quickly when handling a long sequence of unresolved concatenations.
  167. Vector<PrimitiveString const*> stack;
  168. TRY_OR_THROW_OOM(vm, stack.try_append(m_rhs));
  169. TRY_OR_THROW_OOM(vm, stack.try_append(m_lhs));
  170. while (!stack.is_empty()) {
  171. auto const* current = stack.take_last();
  172. if (current->m_is_rope) {
  173. TRY_OR_THROW_OOM(vm, stack.try_append(current->m_rhs));
  174. TRY_OR_THROW_OOM(vm, stack.try_append(current->m_lhs));
  175. continue;
  176. }
  177. TRY_OR_THROW_OOM(vm, pieces.try_append(current));
  178. }
  179. // Now that we have all the pieces, we can concatenate them using a StringBuilder.
  180. ThrowableStringBuilder builder(vm);
  181. // We keep track of the previous piece in order to handle surrogate pairs spread across two pieces.
  182. PrimitiveString const* previous = nullptr;
  183. for (auto const* current : pieces) {
  184. if (!previous) {
  185. // This is the very first piece, just append it and continue.
  186. TRY(builder.append(TRY(current->deprecated_string())));
  187. previous = current;
  188. continue;
  189. }
  190. // Get the UTF-8 representations for both strings.
  191. auto previous_string_as_utf8 = TRY(previous->deprecated_string());
  192. auto current_string_as_utf8 = TRY(current->deprecated_string());
  193. // NOTE: Now we need to look at the end of the previous string and the start
  194. // of the current string, to see if they should be combined into a surrogate.
  195. // Surrogates encoded as UTF-8 are 3 bytes.
  196. if ((previous_string_as_utf8.length() < 3) || (current_string_as_utf8.length() < 3)) {
  197. TRY(builder.append(TRY(current->deprecated_string())));
  198. previous = current;
  199. continue;
  200. }
  201. // Might the previous string end with a UTF-8 encoded surrogate?
  202. if ((static_cast<u8>(previous_string_as_utf8[previous_string_as_utf8.length() - 3]) & 0xf0) != 0xe0) {
  203. // If not, just append the current string and continue.
  204. TRY(builder.append(TRY(current->deprecated_string())));
  205. previous = current;
  206. continue;
  207. }
  208. // Might the current string begin with a UTF-8 encoded surrogate?
  209. if ((static_cast<u8>(current_string_as_utf8[0]) & 0xf0) != 0xe0) {
  210. // If not, just append the current string and continue.
  211. TRY(builder.append(TRY(current->deprecated_string())));
  212. previous = current;
  213. continue;
  214. }
  215. auto high_surrogate = *Utf8View(previous_string_as_utf8.substring_view(previous_string_as_utf8.length() - 3)).begin();
  216. auto low_surrogate = *Utf8View(current_string_as_utf8).begin();
  217. if (!Utf16View::is_high_surrogate(high_surrogate) || !Utf16View::is_low_surrogate(low_surrogate)) {
  218. TRY(builder.append(TRY(current->deprecated_string())));
  219. previous = current;
  220. continue;
  221. }
  222. // Remove 3 bytes from the builder and replace them with the UTF-8 encoded code point.
  223. builder.trim(3);
  224. TRY(builder.append_code_point(Utf16View::decode_surrogate_pair(high_surrogate, low_surrogate)));
  225. // Append the remaining part of the current string.
  226. TRY(builder.append(current_string_as_utf8.substring_view(3)));
  227. previous = current;
  228. }
  229. m_utf8_string = builder.to_deprecated_string();
  230. m_is_rope = false;
  231. m_lhs = nullptr;
  232. m_rhs = nullptr;
  233. return {};
  234. }
  235. }