ListFormat.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. /*
  2. * Copyright (c) 2021-2023, Tim Flynn <trflynn89@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibJS/Runtime/Array.h>
  7. #include <LibJS/Runtime/GlobalObject.h>
  8. #include <LibJS/Runtime/Intl/ListFormat.h>
  9. #include <LibJS/Runtime/IteratorOperations.h>
  10. #include <LibJS/Runtime/ThrowableStringBuilder.h>
  11. namespace JS::Intl {
  12. // 13 ListFormat Objects, https://tc39.es/ecma402/#listformat-objects
  13. ListFormat::ListFormat(Object& prototype)
  14. : Object(ConstructWithPrototypeTag::Tag, prototype)
  15. {
  16. }
  17. void ListFormat::set_type(StringView type)
  18. {
  19. if (type == "conjunction"sv) {
  20. m_type = Type::Conjunction;
  21. } else if (type == "disjunction"sv) {
  22. m_type = Type::Disjunction;
  23. } else if (type == "unit"sv) {
  24. m_type = Type::Unit;
  25. } else {
  26. VERIFY_NOT_REACHED();
  27. }
  28. }
  29. StringView ListFormat::type_string() const
  30. {
  31. switch (m_type) {
  32. case Type::Conjunction:
  33. return "conjunction"sv;
  34. case Type::Disjunction:
  35. return "disjunction"sv;
  36. case Type::Unit:
  37. return "unit"sv;
  38. default:
  39. VERIFY_NOT_REACHED();
  40. }
  41. }
  42. // 13.5.1 DeconstructPattern ( pattern, placeables ), https://tc39.es/ecma402/#sec-deconstructpattern
  43. ThrowCompletionOr<Vector<PatternPartition>> deconstruct_pattern(VM& vm, StringView pattern, Placeables placeables)
  44. {
  45. // 1. Let patternParts be ! PartitionPattern(pattern).
  46. auto pattern_parts = MUST_OR_THROW_OOM(partition_pattern(vm, pattern));
  47. // 2. Let result be a new empty List.
  48. Vector<PatternPartition> result {};
  49. // 3. For each Record { [[Type]], [[Value]] } patternPart of patternParts, do
  50. for (auto& pattern_part : pattern_parts) {
  51. // a. Let part be patternPart.[[Type]].
  52. auto part = pattern_part.type;
  53. // b. If part is "literal", then
  54. if (part == "literal"sv) {
  55. // i. Append Record { [[Type]]: "literal", [[Value]]: patternPart.[[Value]] } to result.
  56. TRY_OR_THROW_OOM(vm, result.try_append({ part, move(pattern_part.value) }));
  57. }
  58. // c. Else,
  59. else {
  60. // i. Assert: placeables has a field [[<part>]].
  61. // ii. Let subst be placeables.[[<part>]].
  62. auto subst = placeables.get(part);
  63. VERIFY(subst.has_value());
  64. MUST_OR_THROW_OOM(subst.release_value().visit(
  65. // iii. If Type(subst) is List, then
  66. [&](Vector<PatternPartition>& partition) -> ThrowCompletionOr<void> {
  67. // 1. For each element s of subst, do
  68. for (auto& element : partition) {
  69. // a. Append s to result.
  70. TRY_OR_THROW_OOM(vm, result.try_append(move(element)));
  71. }
  72. return {};
  73. },
  74. // iv. Else,
  75. [&](PatternPartition& partition) -> ThrowCompletionOr<void> {
  76. // 1. Append subst to result.
  77. TRY_OR_THROW_OOM(vm, result.try_append(move(partition)));
  78. return {};
  79. }));
  80. }
  81. }
  82. // 4. Return result.
  83. return result;
  84. }
  85. // 13.5.2 CreatePartsFromList ( listFormat, list ), https://tc39.es/ecma402/#sec-createpartsfromlist
  86. ThrowCompletionOr<Vector<PatternPartition>> create_parts_from_list(VM& vm, ListFormat const& list_format, Vector<String> const& list)
  87. {
  88. auto list_patterns = ::Locale::get_locale_list_patterns(list_format.locale(), list_format.type_string(), list_format.style());
  89. if (!list_patterns.has_value())
  90. return Vector<PatternPartition> {};
  91. // 1. Let size be the number of elements of list.
  92. auto size = list.size();
  93. // 2. If size is 0, then
  94. if (size == 0) {
  95. // a. Return a new empty List.
  96. return Vector<PatternPartition> {};
  97. }
  98. // 3. If size is 2, then
  99. if (size == 2) {
  100. // a. Let n be an index into listFormat.[[Templates]] based on listFormat.[[Locale]], list[0], and list[1].
  101. // b. Let pattern be listFormat.[[Templates]][n].[[Pair]].
  102. auto pattern = list_patterns->pair;
  103. // c. Let first be a new Record { [[Type]]: "element", [[Value]]: list[0] }.
  104. PatternPartition first { "element"sv, list[0] };
  105. // d. Let second be a new Record { [[Type]]: "element", [[Value]]: list[1] }.
  106. PatternPartition second { "element"sv, list[1] };
  107. // e. Let placeables be a new Record { [[0]]: first, [[1]]: second }.
  108. Placeables placeables;
  109. placeables.set("0"sv, move(first));
  110. placeables.set("1"sv, move(second));
  111. // f. Return ! DeconstructPattern(pattern, placeables).
  112. return MUST_OR_THROW_OOM(deconstruct_pattern(vm, pattern, move(placeables)));
  113. }
  114. // 4. Let last be a new Record { [[Type]]: "element", [[Value]]: list[size - 1] }.
  115. PatternPartition last { "element"sv, list[size - 1] };
  116. // 5. Let parts be « last ».
  117. Vector<PatternPartition> parts { move(last) };
  118. // The spec does not say to do this, but because size_t is unsigned, we need to take care not to wrap around 0.
  119. if (size == 1)
  120. return parts;
  121. // 6. Let i be size - 2.
  122. size_t i = size - 2;
  123. // 7. Repeat, while i ≥ 0,
  124. do {
  125. // a. Let head be a new Record { [[Type]]: "element", [[Value]]: list[i] }.
  126. PatternPartition head { "element"sv, list[i] };
  127. // b. Let n be an implementation-defined index into listFormat.[[Templates]] based on listFormat.[[Locale]], head, and parts.
  128. StringView pattern;
  129. // c. If i is 0, then
  130. if (i == 0) {
  131. // i. Let pattern be listFormat.[[Templates]][n].[[Start]].
  132. pattern = list_patterns->start;
  133. }
  134. // d. Else if i is less than size - 2, then
  135. else if (i < (size - 2)) {
  136. // i. Let pattern be listFormat.[[Templates]][n].[[Middle]].
  137. pattern = list_patterns->middle;
  138. }
  139. // e. Else,
  140. else {
  141. // i. Let pattern be listFormat.[[Templates]][n].[[End]].
  142. pattern = list_patterns->end;
  143. }
  144. // f. Let placeables be a new Record { [[0]]: head, [[1]]: parts }.
  145. Placeables placeables;
  146. placeables.set("0"sv, move(head));
  147. placeables.set("1"sv, move(parts));
  148. // g. Set parts to ! DeconstructPattern(pattern, placeables).
  149. parts = MUST_OR_THROW_OOM(deconstruct_pattern(vm, pattern, move(placeables)));
  150. // h. Decrement i by 1.
  151. } while (i-- != 0);
  152. // 8. Return parts.
  153. return parts;
  154. }
  155. // 13.5.3 FormatList ( listFormat, list ), https://tc39.es/ecma402/#sec-formatlist
  156. ThrowCompletionOr<String> format_list(VM& vm, ListFormat const& list_format, Vector<String> const& list)
  157. {
  158. // 1. Let parts be ! CreatePartsFromList(listFormat, list).
  159. auto parts = MUST_OR_THROW_OOM(create_parts_from_list(vm, list_format, list));
  160. // 2. Let result be an empty String.
  161. ThrowableStringBuilder result(vm);
  162. // 3. For each Record { [[Type]], [[Value]] } part in parts, do
  163. for (auto& part : parts) {
  164. // a. Set result to the string-concatenation of result and part.[[Value]].
  165. TRY(result.append(part.value));
  166. }
  167. // 4. Return result.
  168. return result.to_string();
  169. }
  170. // 13.5.4 FormatListToParts ( listFormat, list ), https://tc39.es/ecma402/#sec-formatlisttoparts
  171. ThrowCompletionOr<Array*> format_list_to_parts(VM& vm, ListFormat const& list_format, Vector<String> const& list)
  172. {
  173. auto& realm = *vm.current_realm();
  174. // 1. Let parts be ! CreatePartsFromList(listFormat, list).
  175. auto parts = MUST_OR_THROW_OOM(create_parts_from_list(vm, list_format, list));
  176. // 2. Let result be ! ArrayCreate(0).
  177. auto result = MUST(Array::create(realm, 0));
  178. // 3. Let n be 0.
  179. size_t n = 0;
  180. // 4. For each Record { [[Type]], [[Value]] } part in parts, do
  181. for (auto& part : parts) {
  182. // a. Let O be OrdinaryObjectCreate(%Object.prototype%).
  183. auto object = Object::create(realm, realm.intrinsics().object_prototype());
  184. // b. Perform ! CreateDataPropertyOrThrow(O, "type", part.[[Type]]).
  185. MUST(object->create_data_property_or_throw(vm.names.type, MUST_OR_THROW_OOM(PrimitiveString::create(vm, part.type))));
  186. // c. Perform ! CreateDataPropertyOrThrow(O, "value", part.[[Value]]).
  187. MUST(object->create_data_property_or_throw(vm.names.value, PrimitiveString::create(vm, move(part.value))));
  188. // d. Perform ! CreateDataPropertyOrThrow(result, ! ToString(n), O).
  189. MUST(result->create_data_property_or_throw(n, object));
  190. // e. Increment n by 1.
  191. ++n;
  192. }
  193. // 5. Return result.
  194. return result.ptr();
  195. }
  196. // 13.5.5 StringListFromIterable ( iterable ), https://tc39.es/ecma402/#sec-createstringlistfromiterable
  197. ThrowCompletionOr<Vector<String>> string_list_from_iterable(VM& vm, Value iterable)
  198. {
  199. // 1. If iterable is undefined, then
  200. if (iterable.is_undefined()) {
  201. // a. Return a new empty List.
  202. return Vector<String> {};
  203. }
  204. // 2. Let iteratorRecord be ? GetIterator(iterable, sync).
  205. auto iterator_record = TRY(get_iterator(vm, iterable, IteratorHint::Sync));
  206. // 3. Let list be a new empty List.
  207. Vector<String> list;
  208. // 4. Let next be true.
  209. GCPtr<Object> next;
  210. // 5. Repeat, while next is not false,
  211. do {
  212. // a. Set next to ? IteratorStep(iteratorRecord).
  213. next = TRY(iterator_step(vm, iterator_record));
  214. // b. If next is not false, then
  215. if (next != nullptr) {
  216. // i. Let nextValue be ? IteratorValue(next).
  217. auto next_value = TRY(iterator_value(vm, *next));
  218. // ii. If Type(nextValue) is not String, then
  219. if (!next_value.is_string()) {
  220. // 1. Let error be ThrowCompletion(a newly created TypeError object).
  221. auto error = vm.throw_completion<TypeError>(ErrorType::NotAString, next_value);
  222. // 2. Return ? IteratorClose(iteratorRecord, error).
  223. return iterator_close(vm, iterator_record, move(error));
  224. }
  225. // iii. Append nextValue to the end of the List list.
  226. TRY_OR_THROW_OOM(vm, list.try_append(TRY(next_value.as_string().utf8_string())));
  227. }
  228. } while (next != nullptr);
  229. // 6. Return list.
  230. return list;
  231. }
  232. }