RelativeTimeFormat.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. /*
  2. * Copyright (c) 2022-2023, Tim Flynn <trflynn89@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibJS/Runtime/AbstractOperations.h>
  7. #include <LibJS/Runtime/Array.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/PluralRules.h>
  12. #include <LibJS/Runtime/Intl/RelativeTimeFormat.h>
  13. #include <LibJS/Runtime/ThrowableStringBuilder.h>
  14. namespace JS::Intl {
  15. // 17 RelativeTimeFormat Objects, https://tc39.es/ecma402/#relativetimeformat-objects
  16. RelativeTimeFormat::RelativeTimeFormat(Object& prototype)
  17. : Object(ConstructWithPrototypeTag::Tag, 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<::Locale::TimeUnit> singular_relative_time_unit(VM& vm, StringView unit)
  51. {
  52. // 1. Assert: Type(unit) is String.
  53. // 2. If unit is "seconds", return "second".
  54. if (unit == "seconds"sv)
  55. return ::Locale::TimeUnit::Second;
  56. // 3. If unit is "minutes", return "minute".
  57. if (unit == "minutes"sv)
  58. return ::Locale::TimeUnit::Minute;
  59. // 4. If unit is "hours", return "hour".
  60. if (unit == "hours"sv)
  61. return ::Locale::TimeUnit::Hour;
  62. // 5. If unit is "days", return "day".
  63. if (unit == "days"sv)
  64. return ::Locale::TimeUnit::Day;
  65. // 6. If unit is "weeks", return "week".
  66. if (unit == "weeks"sv)
  67. return ::Locale::TimeUnit::Week;
  68. // 7. If unit is "months", return "month".
  69. if (unit == "months"sv)
  70. return ::Locale::TimeUnit::Month;
  71. // 8. If unit is "quarters", return "quarter".
  72. if (unit == "quarters"sv)
  73. return ::Locale::TimeUnit::Quarter;
  74. // 9. If unit is "years", return "year".
  75. if (unit == "years"sv)
  76. return ::Locale::TimeUnit::Year;
  77. // 10. If unit is not one of "second", "minute", "hour", "day", "week", "month", "quarter", or "year", throw a RangeError exception.
  78. // 11. Return unit.
  79. if (auto time_unit = ::Locale::time_unit_from_string(unit); time_unit.has_value())
  80. return *time_unit;
  81. return vm.throw_completion<RangeError>(ErrorType::IntlInvalidUnit, unit);
  82. }
  83. // 17.5.2 PartitionRelativeTimePattern ( relativeTimeFormat, value, unit ), https://tc39.es/ecma402/#sec-PartitionRelativeTimePattern
  84. ThrowCompletionOr<Vector<PatternPartitionWithUnit>> partition_relative_time_pattern(VM& vm, RelativeTimeFormat& relative_time_format, double value, StringView unit)
  85. {
  86. // 1. Assert: relativeTimeFormat has an [[InitializedRelativeTimeFormat]] internal slot.
  87. // 2. Assert: Type(value) is Number.
  88. // 3. Assert: Type(unit) is String.
  89. // 4. If value is NaN, +∞𝔽, or -∞𝔽, throw a RangeError exception.
  90. if (!Value(value).is_finite_number())
  91. return vm.throw_completion<RangeError>(ErrorType::IntlNumberIsNaNOrInfinity);
  92. // 5. Let unit be ? SingularRelativeTimeUnit(unit).
  93. auto time_unit = TRY(singular_relative_time_unit(vm, unit));
  94. // 6. Let localeData be %RelativeTimeFormat%.[[LocaleData]].
  95. // 7. Let dataLocale be relativeTimeFormat.[[DataLocale]].
  96. auto const& data_locale = relative_time_format.data_locale();
  97. // 8. Let fields be localeData.[[<dataLocale>]].
  98. // 9. Let style be relativeTimeFormat.[[Style]].
  99. auto style = relative_time_format.style();
  100. // NOTE: The next steps form a "key" based on combining various formatting options into a string,
  101. // then filtering the large set of locale data down to the pattern we are looking for. Instead,
  102. // LibUnicode expects the individual options as enumeration values, and returns the couple of
  103. // patterns that match those options.
  104. auto find_patterns_for_tense_or_number = [&](StringView tense_or_number) -> ThrowCompletionOr<Vector<::Locale::RelativeTimeFormat>> {
  105. // 10. If style is equal to "short", then
  106. // a. Let entry be the string-concatenation of unit and "-short".
  107. // 11. Else if style is equal to "narrow", then
  108. // a. Let entry be the string-concatenation of unit and "-narrow".
  109. // 12. Else,
  110. // a. Let entry be unit.
  111. auto patterns = TRY_OR_THROW_OOM(vm, ::Locale::get_relative_time_format_patterns(data_locale, time_unit, tense_or_number, style));
  112. // 13. If fields doesn't have a field [[<entry>]], then
  113. if (patterns.is_empty()) {
  114. // a. Let entry be unit.
  115. // NOTE: In the CLDR, the lack of "short" or "narrow" in the key implies "long".
  116. patterns = TRY_OR_THROW_OOM(vm, ::Locale::get_relative_time_format_patterns(data_locale, time_unit, tense_or_number, ::Locale::Style::Long));
  117. }
  118. // 14. Let patterns be fields.[[<entry>]].
  119. return patterns;
  120. };
  121. // 15. Let numeric be relativeTimeFormat.[[Numeric]].
  122. // 16. If numeric is equal to "auto", then
  123. if (relative_time_format.numeric() == RelativeTimeFormat::Numeric::Auto) {
  124. // a. Let valueString be ToString(value).
  125. auto value_string = MUST(Value(value).to_string(vm));
  126. // b. If patterns has a field [[<valueString>]], then
  127. if (auto patterns = MUST_OR_THROW_OOM(find_patterns_for_tense_or_number(value_string)); !patterns.is_empty()) {
  128. VERIFY(patterns.size() == 1);
  129. // i. Let result be patterns.[[<valueString>]].
  130. auto result = TRY_OR_THROW_OOM(vm, String::from_utf8(patterns[0].pattern));
  131. // ii. Return a List containing the Record { [[Type]]: "literal", [[Value]]: result }.
  132. Vector<PatternPartitionWithUnit> result_list;
  133. TRY_OR_THROW_OOM(vm, result_list.try_empend("literal"sv, move(result)));
  134. return result_list;
  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 = MUST_OR_THROW_OOM(find_patterns_for_tense_or_number(tense));
  152. // 20. Let fv be ! PartitionNumberPattern(relativeTimeFormat.[[NumberFormat]], value).
  153. auto value_partitions = MUST_OR_THROW_OOM(partition_number_pattern(vm, relative_time_format.number_format(), Value(value)));
  154. // 21. Let pr be ! ResolvePlural(relativeTimeFormat.[[PluralRules]], value).[[PluralCategory]].
  155. auto plurality = MUST_OR_THROW_OOM(resolve_plural(vm, 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.plural_category; });
  158. if (pattern == patterns.end())
  159. return Vector<PatternPartitionWithUnit> {};
  160. // 23. Return ! MakePartsList(pattern, unit, fv).
  161. return MUST_OR_THROW_OOM(make_parts_list(vm, pattern->pattern, ::Locale::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. ThrowCompletionOr<Vector<PatternPartitionWithUnit>> make_parts_list(VM& vm, StringView pattern, StringView unit, Vector<PatternPartition> parts)
  165. {
  166. // 1. Let patternParts be PartitionPattern(pattern).
  167. auto pattern_parts = MUST_OR_THROW_OOM(partition_pattern(vm, 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. TRY_OR_THROW_OOM(vm, result.try_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. TRY_OR_THROW_OOM(vm, result.try_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(VM& vm, 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(vm, relative_time_format, value, unit));
  196. // 2. Let result be an empty String.
  197. ThrowableStringBuilder result(vm);
  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. MUST_OR_THROW_OOM(result.append(part.value));
  202. }
  203. // 4. Return result.
  204. return result.to_string();
  205. }
  206. // 17.5.5 FormatRelativeTimeToParts ( relativeTimeFormat, value, unit ), https://tc39.es/ecma402/#sec-FormatRelativeTimeToParts
  207. ThrowCompletionOr<Array*> format_relative_time_to_parts(VM& vm, RelativeTimeFormat& relative_time_format, double value, StringView unit)
  208. {
  209. auto& realm = *vm.current_realm();
  210. // 1. Let parts be ? PartitionRelativeTimePattern(relativeTimeFormat, value, unit).
  211. auto parts = TRY(partition_relative_time_pattern(vm, relative_time_format, value, unit));
  212. // 2. Let result be ! ArrayCreate(0).
  213. auto result = MUST(Array::create(realm, 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(realm, realm.intrinsics().object_prototype());
  220. // b. Perform ! CreateDataPropertyOrThrow(O, "type", part.[[Type]]).
  221. MUST(object->create_data_property_or_throw(vm.names.type, MUST_OR_THROW_OOM(PrimitiveString::create(vm, part.type))));
  222. // c. Perform ! CreateDataPropertyOrThrow(O, "value", part.[[Value]]).
  223. MUST(object->create_data_property_or_throw(vm.names.value, PrimitiveString::create(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, MUST_OR_THROW_OOM(PrimitiveString::create(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.ptr();
  236. }
  237. }