RelativeTimeFormat.cpp 15 KB

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