RelativeTimeFormat.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. /*
  2. * Copyright (c) 2022, Tim Flynn <trflynn89@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/StringBuilder.h>
  7. #include <LibJS/Runtime/AbstractOperations.h>
  8. #include <LibJS/Runtime/Array.h>
  9. #include <LibJS/Runtime/GlobalObject.h>
  10. #include <LibJS/Runtime/Intl/NumberFormat.h>
  11. #include <LibJS/Runtime/Intl/NumberFormatConstructor.h>
  12. #include <LibJS/Runtime/Intl/PluralRules.h>
  13. #include <LibJS/Runtime/Intl/RelativeTimeFormat.h>
  14. namespace JS::Intl {
  15. // 17 RelativeTimeFormat Objects, https://tc39.es/ecma402/#relativetimeformat-objects
  16. RelativeTimeFormat::RelativeTimeFormat(Object& prototype)
  17. : Object(prototype)
  18. {
  19. }
  20. void RelativeTimeFormat::visit_edges(Cell::Visitor& visitor)
  21. {
  22. Base::visit_edges(visitor);
  23. if (m_number_format)
  24. visitor.visit(m_number_format);
  25. if (m_plural_rules)
  26. visitor.visit(m_plural_rules);
  27. }
  28. void RelativeTimeFormat::set_numeric(StringView numeric)
  29. {
  30. if (numeric == "always"sv) {
  31. m_numeric = Numeric::Always;
  32. } else if (numeric == "auto"sv) {
  33. m_numeric = Numeric::Auto;
  34. } else {
  35. VERIFY_NOT_REACHED();
  36. }
  37. }
  38. StringView RelativeTimeFormat::numeric_string() const
  39. {
  40. switch (m_numeric) {
  41. case Numeric::Always:
  42. return "always"sv;
  43. case Numeric::Auto:
  44. return "auto"sv;
  45. default:
  46. VERIFY_NOT_REACHED();
  47. }
  48. }
  49. // 17.5.1 SingularRelativeTimeUnit ( unit ), https://tc39.es/ecma402/#sec-singularrelativetimeunit
  50. ThrowCompletionOr<Unicode::TimeUnit> singular_relative_time_unit(GlobalObject& global_object, StringView unit)
  51. {
  52. auto& vm = global_object.vm();
  53. // 1. Assert: Type(unit) is String.
  54. // 2. If unit is "seconds", return "second".
  55. if (unit == "seconds"sv)
  56. return Unicode::TimeUnit::Second;
  57. // 3. If unit is "minutes", return "minute".
  58. if (unit == "minutes"sv)
  59. return Unicode::TimeUnit::Minute;
  60. // 4. If unit is "hours", return "hour".
  61. if (unit == "hours"sv)
  62. return Unicode::TimeUnit::Hour;
  63. // 5. If unit is "days", return "day".
  64. if (unit == "days"sv)
  65. return Unicode::TimeUnit::Day;
  66. // 6. If unit is "weeks", return "week".
  67. if (unit == "weeks"sv)
  68. return Unicode::TimeUnit::Week;
  69. // 7. If unit is "months", return "month".
  70. if (unit == "months"sv)
  71. return Unicode::TimeUnit::Month;
  72. // 8. If unit is "quarters", return "quarter".
  73. if (unit == "quarters"sv)
  74. return Unicode::TimeUnit::Quarter;
  75. // 9. If unit is "years", return "year".
  76. if (unit == "years"sv)
  77. return Unicode::TimeUnit::Year;
  78. // 10. If unit is not one of "second", "minute", "hour", "day", "week", "month", "quarter", or "year", throw a RangeError exception.
  79. // 11. Return unit.
  80. if (auto time_unit = Unicode::time_unit_from_string(unit); time_unit.has_value())
  81. return *time_unit;
  82. return vm.throw_completion<RangeError>(global_object, ErrorType::IntlInvalidUnit, unit);
  83. }
  84. // 17.5.2 PartitionRelativeTimePattern ( relativeTimeFormat, value, unit ), https://tc39.es/ecma402/#sec-PartitionRelativeTimePattern
  85. ThrowCompletionOr<Vector<PatternPartitionWithUnit>> partition_relative_time_pattern(GlobalObject& global_object, RelativeTimeFormat& relative_time_format, double value, StringView unit)
  86. {
  87. auto& vm = global_object.vm();
  88. // 1. Assert: relativeTimeFormat has an [[InitializedRelativeTimeFormat]] internal slot.
  89. // 2. Assert: Type(value) is Number.
  90. // 3. Assert: Type(unit) is String.
  91. // 4. If value is NaN, +∞𝔽, or -∞𝔽, throw a RangeError exception.
  92. if (!Value(value).is_finite_number())
  93. return vm.throw_completion<RangeError>(global_object, ErrorType::IntlNumberIsNaNOrInfinity);
  94. // 5. Let unit be ? SingularRelativeTimeUnit(unit).
  95. auto time_unit = TRY(singular_relative_time_unit(global_object, unit));
  96. // 6. Let localeData be %RelativeTimeFormat%.[[LocaleData]].
  97. // 7. Let dataLocale be relativeTimeFormat.[[DataLocale]].
  98. auto const& data_locale = relative_time_format.data_locale();
  99. // 8. Let fields be localeData.[[<dataLocale>]].
  100. // 9. Let style be relativeTimeFormat.[[Style]].
  101. auto style = relative_time_format.style();
  102. // NOTE: The next steps form a "key" based on combining various formatting options into a string,
  103. // then filtering the large set of locale data down to the pattern we are looking for. Instead,
  104. // LibUnicode expects the individual options as enumeration values, and returns the couple of
  105. // patterns that match those options.
  106. auto find_patterns_for_tense_or_number = [&](StringView tense_or_number) {
  107. // 10. If style is equal to "short", then
  108. // a. Let entry be the string-concatenation of unit and "-short".
  109. // 11. Else if style is equal to "narrow", then
  110. // a. Let entry be the string-concatenation of unit and "-narrow".
  111. // 12. Else,
  112. // a. Let entry be unit.
  113. auto patterns = Unicode::get_relative_time_format_patterns(data_locale, time_unit, tense_or_number, style);
  114. // 13. If fields doesn't have a field [[<entry>]], then
  115. if (patterns.is_empty()) {
  116. // a. Let entry be unit.
  117. // NOTE: In the CLDR, the lack of "short" or "narrow" in the key implies "long".
  118. patterns = Unicode::get_relative_time_format_patterns(data_locale, time_unit, tense_or_number, Unicode::Style::Long);
  119. }
  120. // 14. Let patterns be fields.[[<entry>]].
  121. return patterns;
  122. };
  123. // 15. Let numeric be relativeTimeFormat.[[Numeric]].
  124. // 16. If numeric is equal to "auto", then
  125. if (relative_time_format.numeric() == RelativeTimeFormat::Numeric::Auto) {
  126. // a. Let valueString be ToString(value).
  127. auto value_string = MUST(Value(value).to_string(global_object));
  128. // b. If patterns has a field [[<valueString>]], then
  129. if (auto patterns = find_patterns_for_tense_or_number(value_string); !patterns.is_empty()) {
  130. VERIFY(patterns.size() == 1);
  131. // i. Let result be patterns.[[<valueString>]].
  132. auto result = patterns[0].pattern.to_string();
  133. // ii. Return a List containing the Record { [[Type]]: "literal", [[Value]]: result }.
  134. return Vector<PatternPartitionWithUnit> { { "literal"sv, move(result) } };
  135. }
  136. }
  137. // 17. If value is -0𝔽 or if value is less than 0, then
  138. StringView tense;
  139. if (Value(value).is_negative_zero() || (value < 0)) {
  140. // a. Let tl be "past".
  141. tense = "past"sv;
  142. // FIXME: The spec does not say to do this, but nothing makes sense after this with a negative value.
  143. value = fabs(value);
  144. }
  145. // 18. Else,
  146. else {
  147. // a. Let tl be "future".
  148. tense = "future"sv;
  149. }
  150. // 19. Let po be patterns.[[<tl>]].
  151. auto patterns = find_patterns_for_tense_or_number(tense);
  152. // 20. Let fv be ! PartitionNumberPattern(relativeTimeFormat.[[NumberFormat]], value).
  153. auto value_partitions = partition_number_pattern(global_object, relative_time_format.number_format(), Value(value));
  154. // 21. Let pr be ! ResolvePlural(relativeTimeFormat.[[PluralRules]], value).
  155. auto plurality = resolve_plural(global_object, relative_time_format.plural_rules(), Value(value));
  156. // 22. Let pattern be po.[[<pr>]].
  157. auto pattern = patterns.find_if([&](auto& p) { return p.plurality == plurality; });
  158. if (pattern == patterns.end())
  159. return Vector<PatternPartitionWithUnit> {};
  160. // 23. Return ! MakePartsList(pattern, unit, fv).
  161. return make_parts_list(pattern->pattern, Unicode::time_unit_to_string(time_unit), move(value_partitions));
  162. }
  163. // 17.5.3 MakePartsList ( pattern, unit, parts ), https://tc39.es/ecma402/#sec-makepartslist
  164. Vector<PatternPartitionWithUnit> make_parts_list(StringView pattern, StringView unit, Vector<PatternPartition> parts)
  165. {
  166. // 1. Let patternParts be PartitionPattern(pattern).
  167. auto pattern_parts = partition_pattern(pattern);
  168. // 2. Let result be a new empty List.
  169. Vector<PatternPartitionWithUnit> result;
  170. // 3. For each Record { [[Type]], [[Value]] } patternPart in patternParts, do
  171. for (auto& pattern_part : pattern_parts) {
  172. // a. If patternPart.[[Type]] is "literal", then
  173. if (pattern_part.type == "literal"sv) {
  174. // i. Append Record { [[Type]]: "literal", [[Value]]: patternPart.[[Value]], [[Unit]]: empty } to result.
  175. result.empend("literal"sv, move(pattern_part.value));
  176. }
  177. // b. Else,
  178. else {
  179. // i. Assert: patternPart.[[Type]] is "0".
  180. VERIFY(pattern_part.type == "0"sv);
  181. // ii. For each Record { [[Type]], [[Value]] } part in parts, do
  182. for (auto& part : parts) {
  183. // 1. Append Record { [[Type]]: part.[[Type]], [[Value]]: part.[[Value]], [[Unit]]: unit } to result.
  184. result.empend(part.type, move(part.value), unit);
  185. }
  186. }
  187. }
  188. // 4. Return result.
  189. return result;
  190. }
  191. // 17.5.4 FormatRelativeTime ( relativeTimeFormat, value, unit ), https://tc39.es/ecma402/#sec-FormatRelativeTime
  192. ThrowCompletionOr<String> format_relative_time(GlobalObject& global_object, RelativeTimeFormat& relative_time_format, double value, StringView unit)
  193. {
  194. // 1. Let parts be ? PartitionRelativeTimePattern(relativeTimeFormat, value, unit).
  195. auto parts = TRY(partition_relative_time_pattern(global_object, relative_time_format, value, unit));
  196. // 2. Let result be an empty String.
  197. StringBuilder result;
  198. // 3. For each Record { [[Type]], [[Value]], [[Unit]] } part in parts, do
  199. for (auto& part : parts) {
  200. // a. Set result to the string-concatenation of result and part.[[Value]].
  201. result.append(move(part.value));
  202. }
  203. // 4. Return result.
  204. return result.build();
  205. }
  206. // 17.5.5 FormatRelativeTimeToParts ( relativeTimeFormat, value, unit ), https://tc39.es/ecma402/#sec-FormatRelativeTimeToParts
  207. ThrowCompletionOr<Array*> format_relative_time_to_parts(GlobalObject& global_object, RelativeTimeFormat& relative_time_format, double value, StringView unit)
  208. {
  209. auto& vm = global_object.vm();
  210. // 1. Let parts be ? PartitionRelativeTimePattern(relativeTimeFormat, value, unit).
  211. auto parts = TRY(partition_relative_time_pattern(global_object, relative_time_format, value, unit));
  212. // 2. Let result be ! ArrayCreate(0).
  213. auto* result = MUST(Array::create(global_object, 0));
  214. // 3. Let n be 0.
  215. size_t n = 0;
  216. // 4. For each Record { [[Type]], [[Value]], [[Unit]] } part in parts, do
  217. for (auto& part : parts) {
  218. // a. Let O be OrdinaryObjectCreate(%Object.prototype%).
  219. auto* object = Object::create(global_object, global_object.object_prototype());
  220. // b. Perform ! CreateDataPropertyOrThrow(O, "type", part.[[Type]]).
  221. MUST(object->create_data_property_or_throw(vm.names.type, js_string(vm, part.type)));
  222. // c. Perform ! CreateDataPropertyOrThrow(O, "value", part.[[Value]]).
  223. MUST(object->create_data_property_or_throw(vm.names.value, js_string(vm, move(part.value))));
  224. // d. If part.[[Unit]] is not empty, then
  225. if (!part.unit.is_empty()) {
  226. // i. Perform ! CreateDataPropertyOrThrow(O, "unit", part.[[Unit]]).
  227. MUST(object->create_data_property_or_throw(vm.names.unit, js_string(vm, part.unit)));
  228. }
  229. // e. Perform ! CreateDataPropertyOrThrow(result, ! ToString(n), O).
  230. MUST(result->create_data_property_or_throw(n, object));
  231. // f. Increment n by 1.
  232. ++n;
  233. }
  234. // 5. Return result.
  235. return result;
  236. }
  237. }