ListFormat.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. /*
  2. * Copyright (c) 2021, Tim Flynn <trflynn89@pm.me>
  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. #include <LibUnicode/Locale.h>
  12. namespace JS::Intl {
  13. // 13 ListFomat Objects, https://tc39.es/ecma402/#listformat-objects
  14. ListFormat::ListFormat(Object& prototype)
  15. : Object(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. void ListFormat::set_style(StringView style)
  44. {
  45. if (style == "narrow"sv) {
  46. m_style = Style::Narrow;
  47. } else if (style == "short"sv) {
  48. m_style = Style::Short;
  49. } else if (style == "long"sv) {
  50. m_style = Style::Long;
  51. } else {
  52. VERIFY_NOT_REACHED();
  53. }
  54. }
  55. StringView ListFormat::style_string() const
  56. {
  57. switch (m_style) {
  58. case Style::Narrow:
  59. return "narrow"sv;
  60. case Style::Short:
  61. return "short"sv;
  62. case Style::Long:
  63. return "long"sv;
  64. default:
  65. VERIFY_NOT_REACHED();
  66. }
  67. }
  68. // 13.1.1 DeconstructPattern ( pattern, placeables ), https://tc39.es/ecma402/#sec-deconstructpattern
  69. Vector<PatternPartition> deconstruct_pattern(StringView pattern, Placeables placeables)
  70. {
  71. // 1. Let patternParts be PartitionPattern(pattern).
  72. auto pattern_parts = partition_pattern(pattern);
  73. // 2. Let result be a new empty List.
  74. Vector<PatternPartition> result {};
  75. // 3. For each Record { [[Type]], [[Value]] } patternPart of patternParts, do
  76. for (auto& pattern_part : pattern_parts) {
  77. // a. Let part be patternPart.[[Type]].
  78. auto part = pattern_part.type;
  79. // b. If part is "literal", then
  80. if (part == "literal"sv) {
  81. // i. Append Record { [[Type]]: "literal", [[Value]]: patternPart.[[Value]] } to result.
  82. result.append({ part, move(pattern_part.value) });
  83. }
  84. // c. Else,
  85. else {
  86. // i. Assert: placeables has a field [[<part>]].
  87. // ii. Let subst be placeables.[[<part>]].
  88. auto subst = placeables.get(part);
  89. VERIFY(subst.has_value());
  90. subst.release_value().visit(
  91. // iii. If Type(subst) is List, then
  92. [&](Vector<PatternPartition>& partition) {
  93. // 1. For each element s of subst, do
  94. for (auto& element : partition) {
  95. // a. Append s to result.
  96. result.append(move(element));
  97. }
  98. },
  99. // iv. Else,
  100. [&](PatternPartition& partition) {
  101. // 1. Append subst to result.
  102. result.append(move(partition));
  103. });
  104. }
  105. }
  106. // 4. Return result.
  107. return result;
  108. }
  109. // 13.1.2 CreatePartsFromList ( listFormat, list ), https://tc39.es/ecma402/#sec-createpartsfromlist
  110. Vector<PatternPartition> create_parts_from_list(ListFormat const& list_format, Vector<String> const& list)
  111. {
  112. auto list_patterns = Unicode::get_locale_list_patterns(list_format.locale(), list_format.type_string(), list_format.style_string());
  113. if (!list_patterns.has_value())
  114. return {};
  115. // 1. Let size be the number of elements of list.
  116. auto size = list.size();
  117. // 2. If size is 0, then
  118. if (size == 0) {
  119. // a. Return a new empty List.
  120. return {};
  121. }
  122. // 3. If size is 2, then
  123. if (size == 2) {
  124. // a. Let n be an index into listFormat.[[Templates]] based on listFormat.[[Locale]], list[0], and list[1].
  125. // b. Let pattern be listFormat.[[Templates]][n].[[Pair]].
  126. auto pattern = list_patterns->pair;
  127. // c. Let first be a new Record { [[Type]]: "element", [[Value]]: list[0] }.
  128. PatternPartition first { "element"sv, list[0] };
  129. // d. Let second be a new Record { [[Type]]: "element", [[Value]]: list[1] }.
  130. PatternPartition second { "element"sv, list[1] };
  131. // e. Let placeables be a new Record { [[0]]: first, [[1]]: second }.
  132. Placeables placeables;
  133. placeables.set("0"sv, move(first));
  134. placeables.set("1"sv, move(second));
  135. // f. Return DeconstructPattern(pattern, placeables).
  136. return deconstruct_pattern(pattern, move(placeables));
  137. }
  138. // 4. Let last be a new Record { [[Type]]: "element", [[Value]]: list[size - 1] }.
  139. PatternPartition last { "element"sv, list[size - 1] };
  140. // 5. Let parts be « last ».
  141. Vector<PatternPartition> parts { move(last) };
  142. // The spec does not say to do this, but because size_t is unsigned, we need to take care not to wrap around 0.
  143. if (size == 1)
  144. return parts;
  145. // 6. Let i be size - 2.
  146. size_t i = size - 2;
  147. // 7. Repeat, while i ≥ 0,
  148. do {
  149. // a. Let head be a new Record { [[Type]]: "element", [[Value]]: list[i] }.
  150. PatternPartition head { "element"sv, list[i] };
  151. // b. Let n be an implementation-defined index into listFormat.[[Templates]] based on listFormat.[[Locale]], head, and parts.
  152. StringView pattern;
  153. // c. If i is 0, then
  154. if (i == 0) {
  155. // i. Let pattern be listFormat.[[Templates]][n].[[Start]].
  156. pattern = list_patterns->start;
  157. }
  158. // d. Else if i is less than size - 2, then
  159. else if (i < (size - 2)) {
  160. // i. Let pattern be listFormat.[[Templates]][n].[[Middle]].
  161. pattern = list_patterns->middle;
  162. }
  163. // e. Else,
  164. else {
  165. // i. Let pattern be listFormat.[[Templates]][n].[[End]].
  166. pattern = list_patterns->end;
  167. }
  168. // f. Let placeables be a new Record { [[0]]: head, [[1]]: parts }.
  169. Placeables placeables;
  170. placeables.set("0"sv, move(head));
  171. placeables.set("1"sv, move(parts));
  172. // g. Set parts to DeconstructPattern(pattern, placeables).
  173. parts = deconstruct_pattern(pattern, move(placeables));
  174. // h. Decrement i by 1.
  175. } while (i-- != 0);
  176. // 8. Return parts.
  177. return parts;
  178. }
  179. // 13.1.3 FormatList ( listFormat, list ), https://tc39.es/ecma402/#sec-formatlist
  180. String format_list(ListFormat const& list_format, Vector<String> const& list)
  181. {
  182. // 1. Let parts be CreatePartsFromList(listFormat, list).
  183. auto parts = create_parts_from_list(list_format, list);
  184. // 2. Let result be an empty String.
  185. StringBuilder result;
  186. // 3. For each Record { [[Type]], [[Value]] } part in parts, do
  187. for (auto& part : parts) {
  188. // a. Set result to the string-concatenation of result and part.[[Value]].
  189. result.append(move(part.value));
  190. }
  191. // 4. Return result.
  192. return result.build();
  193. }
  194. // 13.1.4 FormatListToParts ( listFormat, list ), https://tc39.es/ecma402/#sec-formatlisttoparts
  195. Array* format_list_to_parts(GlobalObject& global_object, ListFormat const& list_format, Vector<String> const& list)
  196. {
  197. auto& vm = global_object.vm();
  198. // 1. Let parts be CreatePartsFromList(listFormat, list).
  199. auto parts = create_parts_from_list(list_format, list);
  200. // 2. Let result be ArrayCreate(0).
  201. auto* result = MUST(Array::create(global_object, 0));
  202. // 3. Let n be 0.
  203. size_t n = 0;
  204. // 4. For each Record { [[Type]], [[Value]] } part in parts, do
  205. for (auto& part : parts) {
  206. // a. Let O be OrdinaryObjectCreate(%Object.prototype%).
  207. auto* object = Object::create(global_object, global_object.object_prototype());
  208. // b. Perform ! CreateDataPropertyOrThrow(O, "type", part.[[Type]]).
  209. MUST(object->create_data_property_or_throw(vm.names.type, js_string(vm, part.type)));
  210. // c. Perform ! CreateDataPropertyOrThrow(O, "value", part.[[Value]]).
  211. MUST(object->create_data_property_or_throw(vm.names.value, js_string(vm, move(part.value))));
  212. // d. Perform ! CreateDataPropertyOrThrow(result, ! ToString(n), O).
  213. MUST(result->create_data_property_or_throw(n, object));
  214. // e. Increment n by 1.
  215. ++n;
  216. }
  217. // 5. Return result.
  218. return result;
  219. }
  220. // 13.1.5 StringListFromIterable ( iterable ), https://tc39.es/ecma402/#sec-createstringlistfromiterable
  221. ThrowCompletionOr<Vector<String>> string_list_from_iterable(GlobalObject& global_object, Value iterable)
  222. {
  223. auto& vm = global_object.vm();
  224. // 1. If iterable is undefined, then
  225. if (iterable.is_undefined()) {
  226. // a. Return a new empty List.
  227. return Vector<String> {};
  228. }
  229. // 2. Let iteratorRecord be ? GetIterator(iterable).
  230. auto* iterator_record = TRY(get_iterator(global_object, iterable));
  231. // 3. Let list be a new empty List.
  232. Vector<String> list;
  233. // 4. Let next be true.
  234. Object* next = nullptr;
  235. // 5. Repeat, while next is not false,
  236. do {
  237. // a. Set next to ? IteratorStep(iteratorRecord).
  238. next = TRY(iterator_step(global_object, *iterator_record));
  239. // b. If next is not false, then
  240. if (next != nullptr) {
  241. // i. Let nextValue be ? IteratorValue(next).
  242. auto next_value = TRY(iterator_value(global_object, *next));
  243. // ii. If Type(nextValue) is not String, then
  244. if (!next_value.is_string()) {
  245. // 1. Let error be ThrowCompletion(a newly created TypeError object).
  246. auto error = vm.throw_completion<TypeError>(global_object, ErrorType::NotAString, next_value);
  247. // 2. Return ? IteratorClose(iteratorRecord, error).
  248. return iterator_close(*iterator_record, move(error));
  249. }
  250. // iii. Append nextValue to the end of the List list.
  251. list.append(next_value.as_string().string());
  252. }
  253. } while (next != nullptr);
  254. // 6. Return list.
  255. return list;
  256. }
  257. }