ListFormat.cpp 10 KB

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