ListFormat.cpp 9.2 KB

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