RelativeTimeFormat.cpp 11 KB

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