RelativeTimeFormat.cpp 13 KB

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