DurationFormat.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  1. /*
  2. * Copyright (c) 2022, Idan Horowitz <idan.horowitz@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibJS/Runtime/AbstractOperations.h>
  7. #include <LibJS/Runtime/GlobalObject.h>
  8. #include <LibJS/Runtime/Intl/DurationFormat.h>
  9. #include <LibJS/Runtime/Intl/ListFormat.h>
  10. #include <LibJS/Runtime/Intl/ListFormatConstructor.h>
  11. #include <LibJS/Runtime/Intl/NumberFormatConstructor.h>
  12. #include <LibJS/Runtime/Intl/PluralRules.h>
  13. #include <LibJS/Runtime/Intl/PluralRulesConstructor.h>
  14. #include <LibJS/Runtime/Intl/RelativeTimeFormat.h>
  15. #include <LibJS/Runtime/Temporal/AbstractOperations.h>
  16. namespace JS::Intl {
  17. // 1 DurationFormat Objects, https://tc39.es/proposal-intl-duration-format/#durationformat-objects
  18. DurationFormat::DurationFormat(Object& prototype)
  19. : Object(prototype)
  20. {
  21. }
  22. DurationFormat::Style DurationFormat::style_from_string(StringView style)
  23. {
  24. if (style == "long"sv)
  25. return Style::Long;
  26. if (style == "short"sv)
  27. return Style::Short;
  28. if (style == "narrow"sv)
  29. return Style::Narrow;
  30. if (style == "digital"sv)
  31. return Style::Digital;
  32. VERIFY_NOT_REACHED();
  33. }
  34. StringView DurationFormat::style_to_string(Style style)
  35. {
  36. switch (style) {
  37. case Style::Long:
  38. return "long"sv;
  39. case Style::Short:
  40. return "short"sv;
  41. case Style::Narrow:
  42. return "narrow"sv;
  43. case Style::Digital:
  44. return "digital"sv;
  45. default:
  46. VERIFY_NOT_REACHED();
  47. }
  48. }
  49. DurationFormat::ValueStyle DurationFormat::date_style_from_string(StringView date_style)
  50. {
  51. if (date_style == "long"sv)
  52. return ValueStyle::Long;
  53. if (date_style == "short"sv)
  54. return ValueStyle::Short;
  55. if (date_style == "narrow"sv)
  56. return ValueStyle::Narrow;
  57. VERIFY_NOT_REACHED();
  58. }
  59. DurationFormat::ValueStyle DurationFormat::time_style_from_string(StringView time_style)
  60. {
  61. if (time_style == "long"sv)
  62. return ValueStyle::Long;
  63. if (time_style == "short"sv)
  64. return ValueStyle::Short;
  65. if (time_style == "narrow"sv)
  66. return ValueStyle::Narrow;
  67. if (time_style == "numeric"sv)
  68. return ValueStyle::Numeric;
  69. if (time_style == "2-digit"sv)
  70. return ValueStyle::TwoDigit;
  71. VERIFY_NOT_REACHED();
  72. }
  73. DurationFormat::ValueStyle DurationFormat::sub_second_style_from_string(StringView sub_second_style)
  74. {
  75. if (sub_second_style == "long"sv)
  76. return ValueStyle::Long;
  77. if (sub_second_style == "short"sv)
  78. return ValueStyle::Short;
  79. if (sub_second_style == "narrow"sv)
  80. return ValueStyle::Narrow;
  81. if (sub_second_style == "numeric"sv)
  82. return ValueStyle::Numeric;
  83. VERIFY_NOT_REACHED();
  84. }
  85. DurationFormat::Display DurationFormat::display_from_string(StringView display)
  86. {
  87. if (display == "auto"sv)
  88. return Display::Auto;
  89. if (display == "always"sv)
  90. return Display::Always;
  91. VERIFY_NOT_REACHED();
  92. }
  93. StringView DurationFormat::value_style_to_string(ValueStyle value_style)
  94. {
  95. switch (value_style) {
  96. case ValueStyle::Long:
  97. return "long"sv;
  98. case ValueStyle::Short:
  99. return "short"sv;
  100. case ValueStyle::Narrow:
  101. return "narrow"sv;
  102. case ValueStyle::Numeric:
  103. return "numeric"sv;
  104. case ValueStyle::TwoDigit:
  105. return "2-digit"sv;
  106. default:
  107. VERIFY_NOT_REACHED();
  108. }
  109. }
  110. StringView DurationFormat::display_to_string(Display display)
  111. {
  112. switch (display) {
  113. case Display::Auto:
  114. return "auto"sv;
  115. case Display::Always:
  116. return "always"sv;
  117. default:
  118. VERIFY_NOT_REACHED();
  119. }
  120. }
  121. // 1.1.3 ToDurationRecord ( input ), https://tc39.es/proposal-intl-duration-format/#sec-todurationrecord
  122. ThrowCompletionOr<Temporal::DurationRecord> to_duration_record(VM& vm, Value input)
  123. {
  124. // 1. If Type(input) is not Object, throw a TypeError exception.
  125. if (!input.is_object())
  126. return vm.throw_completion<TypeError>(ErrorType::NotAnObject, input);
  127. auto& input_object = input.as_object();
  128. // 2. Let result be a new Record.
  129. Temporal::DurationRecord result;
  130. // 3. Let any be false.
  131. auto any = false;
  132. // 4. For each row in Table 1, except the header row, in table order, do
  133. for (auto const& duration_instances_component : duration_instances_components) {
  134. // a. Let valueSlot be the Value Slot value.
  135. auto value_slot = duration_instances_component.value_slot;
  136. // b. Let unit be the Unit value.
  137. auto unit = duration_instances_component.unit;
  138. // c. Let value be ? Get(input, unit).
  139. auto value = TRY(input_object.get(FlyString(unit)));
  140. double value_number;
  141. // d. If value is not undefined, then
  142. if (!value.is_undefined()) {
  143. // i. Set any to true.
  144. any = true;
  145. // ii. Set value to ? ToIntegerWithoutRounding(value).
  146. value_number = TRY(Temporal::to_integer_without_rounding(vm, value, ErrorType::TemporalInvalidDurationPropertyValueNonIntegral, unit, value));
  147. }
  148. // e. Else,
  149. else {
  150. // i. Set value to 0.
  151. value_number = 0;
  152. }
  153. // f. Set the field of result whose name is valueSlot to value.
  154. result.*value_slot = value_number;
  155. }
  156. // 5. If any is false, throw a TypeError exception.
  157. if (!any)
  158. return vm.throw_completion<TypeError>(ErrorType::TemporalInvalidDurationLikeObject);
  159. // 6. Return result.
  160. return result;
  161. }
  162. // 1.1.4 DurationSign ( record ), https://tc39.es/proposal-intl-duration-format/#sec-durationsign
  163. i8 duration_sign(Temporal::DurationRecord const& record)
  164. {
  165. // 1. For each row in Table 1, except the header row, in table order, do
  166. for (auto const& duration_instances_component : duration_instances_components) {
  167. // a. Let valueSlot be the Value Slot value.
  168. auto value_slot = duration_instances_component.value_slot;
  169. // b. Let v be value of the valueSlot slot of record.
  170. auto value = record.*value_slot;
  171. // c. If v < 0, return -1.
  172. if (value < 0)
  173. return -1;
  174. // d. If v > 0, return 1.
  175. if (value > 0)
  176. return 1;
  177. }
  178. // 2. Return 0.
  179. return 0;
  180. }
  181. // 1.1.5 IsValidDurationRecord ( record ), https://tc39.es/proposal-intl-duration-format/#sec-isvaliddurationrecord
  182. bool is_valid_duration_record(Temporal::DurationRecord const& record)
  183. {
  184. // 1. Let sign be ! DurationSign(record).
  185. auto sign = duration_sign(record);
  186. // 2. For each row in Table 1, except the header row, in table order, do
  187. for (auto const& duration_instances_component : duration_instances_components) {
  188. // a. Let valueSlot be the Value Slot value.
  189. auto value_slot = duration_instances_component.value_slot;
  190. // b. Let v be value of the valueSlot slot of record.
  191. auto value = record.*value_slot;
  192. // c. If 𝔽(v) is not finite, return false.
  193. if (!isfinite(value))
  194. return false;
  195. // d. If v < 0 and sign > 0, return false.
  196. if (value < 0 && sign > 0)
  197. return false;
  198. // e. If v > 0 and sign < 0, return false.
  199. if (value > 0 && sign < 0)
  200. return false;
  201. }
  202. // 3. Return true.
  203. return true;
  204. }
  205. // 1.1.6 GetDurationUnitOptions ( unit, options, baseStyle, stylesList, digitalBase, prevStyle ), https://tc39.es/proposal-intl-duration-format/#sec-getdurationunitoptions
  206. ThrowCompletionOr<DurationUnitOptions> get_duration_unit_options(VM& vm, String const& unit, Object const& options, StringView base_style, Span<StringView const> styles_list, StringView digital_base, Optional<String> const& previous_style)
  207. {
  208. // 1. Let style be ? GetOption(options, unit, "string", stylesList, undefined).
  209. auto style_value = TRY(get_option(vm, options, unit, OptionType::String, styles_list, Empty {}));
  210. // 2. Let displayDefault be "always".
  211. auto display_default = "always"sv;
  212. String style;
  213. // 3. If style is undefined, then
  214. if (style_value.is_undefined()) {
  215. // a. Set displayDefault to "auto".
  216. display_default = "auto"sv;
  217. // b. If baseStyle is "digital", then
  218. if (base_style == "digital"sv) {
  219. // i. Set style to digitalBase.
  220. style = digital_base;
  221. }
  222. // c. Else,
  223. else {
  224. // i. Set style to baseStyle.
  225. style = base_style;
  226. }
  227. } else {
  228. style = style_value.as_string().string();
  229. }
  230. // 4. Let displayField be the string-concatenation of unit and "Display".
  231. auto display_field = String::formatted("{}Display", unit);
  232. // 5. Let display be ? GetOption(options, displayField, "string", « "auto", "always" », displayDefault).
  233. auto display = TRY(get_option(vm, options, display_field, OptionType::String, { "auto"sv, "always"sv }, display_default));
  234. // 6. If prevStyle is "numeric" or "2-digit", then
  235. if (previous_style == "numeric"sv || previous_style == "2-digit"sv) {
  236. // a. If style is not "numeric" or "2-digit", then
  237. if (style != "numeric"sv && style != "2-digit"sv) {
  238. // i. Throw a RangeError exception.
  239. return vm.throw_completion<RangeError>(ErrorType::IntlNonNumericOr2DigitAfterNumericOr2Digit);
  240. }
  241. // b. Else if unit is "minutes" or "seconds", then
  242. else if (unit == "minutes"sv || unit == "seconds"sv) {
  243. // i. Set style to "2-digit".
  244. style = "2-digit"sv;
  245. }
  246. }
  247. // 7. Return the Record { [[Style]]: style, [[Display]]: display }.
  248. return DurationUnitOptions { .style = move(style), .display = display.as_string().string() };
  249. }
  250. // FIXME: LibUnicode currently only exposes unit patterns converted to an ECMA402 NumberFormat-specific format,
  251. // since DurationFormat only needs a tiny subset of it, it's much easier to just convert it to the expected format
  252. // here, but at some point we should split the the NumberFormat exporter to export both formats of the data.
  253. static String convert_number_format_pattern_to_duration_format_template(Unicode::NumberFormat const& number_format)
  254. {
  255. auto result = number_format.zero_format.replace("{number}"sv, "{0}"sv, ReplaceMode::FirstOnly);
  256. for (size_t i = 0; i < number_format.identifiers.size(); ++i)
  257. result = result.replace(String::formatted("{{unitIdentifier:{}}}", i), number_format.identifiers[i], ReplaceMode::FirstOnly);
  258. return result;
  259. }
  260. // 1.1.7 PartitionDurationFormatPattern ( durationFormat, duration ), https://tc39.es/proposal-intl-duration-format/#sec-partitiondurationformatpattern
  261. ThrowCompletionOr<Vector<PatternPartition>> partition_duration_format_pattern(VM& vm, DurationFormat const& duration_format, Temporal::DurationRecord const& duration)
  262. {
  263. auto& realm = *vm.current_realm();
  264. auto& global_object = realm.global_object();
  265. // 1. Let result be a new empty List.
  266. Vector<PatternPartition> result;
  267. // 2. For each row in Table 1, except the header row, in table order, do
  268. for (size_t i = 0; i < duration_instances_components.size(); ++i) {
  269. auto const& duration_instances_component = duration_instances_components[i];
  270. // a. Let styleSlot be the Style Slot value.
  271. auto style_slot = duration_instances_component.get_style_slot;
  272. decltype(DurationInstanceComponent::get_style_slot) next_style_slot = nullptr;
  273. // FIXME: Missing spec step - If this is not the last row
  274. if (i < duration_instances_components.size() - 1) {
  275. // b. Let nextStyleSlot be the Style Slot value of the next row.
  276. next_style_slot = duration_instances_components[i + 1].get_style_slot;
  277. }
  278. // c. Let displaySlot be the Display Slot value.
  279. auto display_slot = duration_instances_component.get_display_slot;
  280. // d. Let valueSlot be the Value Slot value.
  281. auto value_slot = duration_instances_component.value_slot;
  282. // e. Let unit be the Unit value.
  283. auto unit = duration_instances_component.unit;
  284. // f. Let style be the current value of the styleSlot slot of durationFormat.
  285. auto style = (duration_format.*style_slot)();
  286. DurationFormat::ValueStyle next_style = DurationFormat::ValueStyle::Long;
  287. // FIXME: Missing spec step - If this is not the last row
  288. if (next_style_slot) {
  289. // g. Let nextStyle be the current value of the nextStyleSlot slot of durationFormat.
  290. next_style = (duration_format.*next_style_slot)();
  291. }
  292. // h. Let nfOpts be ! OrdinaryObjectCreate(null).
  293. auto* number_format_options = Object::create(realm, nullptr);
  294. // i. Let value be 0.
  295. auto value = Value(0);
  296. // j. Let done be false.
  297. auto done = false;
  298. // k. If unit is "seconds", "milliseconds" or "microseconds" and nextStyle is "numeric", then
  299. if (unit.is_one_of("seconds"sv, "milliseconds"sv, "microseconds"sv) && next_style == DurationFormat::ValueStyle::Numeric) {
  300. // i. Set value to duration.[[Microseconds]] + duration.[[Nanoseconds]] / 1000.
  301. auto value_number = duration.microseconds + (duration.nanoseconds / 1000);
  302. // ii. If unit is "seconds" or "milliseconds", then
  303. if (unit.is_one_of("seconds"sv, "milliseconds"sv)) {
  304. // 1. Set value to duration.[[Milliseconds]] + value / 1000.
  305. value_number = duration.milliseconds + (value_number / 1000);
  306. // 2. If unit is "seconds", then
  307. if (unit == "seconds"sv) {
  308. // a. Set value to duration.[[Seconds]] + value / 1000.
  309. value_number = duration.seconds + (value_number / 1000);
  310. }
  311. }
  312. value = Value(value_number);
  313. // iii. Perform ! CreateDataPropertyOrThrow(nfOpts, "maximumFractionDigits", durationFormat.[[FractionalDigits]]).
  314. MUST(number_format_options->create_data_property_or_throw(vm.names.maximumFractionDigits, duration_format.has_fractional_digits() ? Value(duration_format.fractional_digits()) : js_undefined()));
  315. // iv. Perform ! CreateDataPropertyOrThrow(nfOpts, "minimumFractionDigits", durationFormat.[[FractionalDigits]]).
  316. MUST(number_format_options->create_data_property_or_throw(vm.names.minimumFractionDigits, duration_format.has_fractional_digits() ? Value(duration_format.fractional_digits()) : js_undefined()));
  317. // v. Set done to true.
  318. done = true;
  319. }
  320. // l. Else,
  321. else {
  322. // i. Set value to the current value of the valueSlot slot of duration.
  323. value = Value(duration.*value_slot);
  324. }
  325. // m. If style is "2-digit", then
  326. if (style == DurationFormat::ValueStyle::TwoDigit) {
  327. // i. Perform ! CreateDataPropertyOrThrow(nfOpts, "minimumIntegerDigits", 2).
  328. MUST(number_format_options->create_data_property_or_throw(vm.names.minimumIntegerDigits, Value(2)));
  329. }
  330. // FIXME: Missing spec step - Let display be the current value of the displaySlot slot of durationFormat.
  331. auto display = (duration_format.*display_slot)();
  332. // n. If value is +0𝔽 or -0𝔽 and display is "auto", then
  333. if ((value.is_negative_zero() || value.is_positive_zero()) && display == DurationFormat::Display::Auto) {
  334. // i. Skip to the next iteration.
  335. continue;
  336. }
  337. // o. Let nf be ? Construct(%NumberFormat%, « durationFormat.[[Locale]], nfOpts »).
  338. auto* number_format = static_cast<Intl::NumberFormat*>(TRY(construct(global_object, *global_object.intl_number_format_constructor(), js_string(vm, duration_format.locale()), number_format_options)));
  339. // FIXME: durationFormat.[[NumberFormat]] is not a thing, the spec likely means 'nf' in this case
  340. // p. Let num be ! FormatNumeric(durationFormat.[[NumberFormat]], value).
  341. auto number = format_numeric(vm, *number_format, value);
  342. // q. Let dataLocale be durationFormat.[[DataLocale]].
  343. auto const& data_locale = duration_format.data_locale();
  344. // r. Let dataLocaleData be the current value of the dataLocale slot of %DurationFormat%.[[LocaleData]].
  345. // s. If style is "2-digit" or "numeric", then
  346. if (style == DurationFormat::ValueStyle::TwoDigit || style == DurationFormat::ValueStyle::Numeric) {
  347. // i. Append the new Record { [[Type]]: unit, [[Value]]: num} to the end of result.
  348. result.append({ unit, number });
  349. // ii. If unit is "hours" or "minutes", then
  350. if (unit.is_one_of("hours"sv, "minutes"sv)) {
  351. // 1. Let separator be dataLocaleData.[[formats]].[[digital]].[[separator]].
  352. auto separator = Unicode::get_number_system_symbol(data_locale, duration_format.numbering_system(), Unicode::NumericSymbol::TimeSeparator).value_or(":"sv);
  353. // 2. Append the new Record { [[Type]]: "literal", [[Value]]: separator} to the end of result.
  354. result.append({ "literal"sv, separator });
  355. }
  356. }
  357. // t. Else,
  358. else {
  359. // i. Let pr be ? Construct(%PluralRules%, « durationFormat.[[Locale]] »).
  360. auto* plural_rules = TRY(construct(global_object, *global_object.intl_plural_rules_constructor(), js_string(vm, duration_format.locale())));
  361. // ii. Let prv be ! ResolvePlural(pr, value).
  362. auto plurality = resolve_plural(static_cast<PluralRules&>(*plural_rules), value);
  363. auto formats = Unicode::get_unit_formats(data_locale, duration_instances_component.unit_singular, static_cast<Unicode::Style>(style));
  364. auto pattern = formats.find_if([&](auto& p) { return p.plurality == plurality; });
  365. if (pattern == formats.end())
  366. continue;
  367. // iii. Let template be the current value of the prv slot of the unit slot of the style slot of dataLocaleData.[[formats]].
  368. auto template_ = convert_number_format_pattern_to_duration_format_template(*pattern);
  369. // FIXME: MakePartsList takes a list, not a string, so likely missing spec step: Let fv be ! PartitionNumberPattern(nf, value).
  370. auto formatted_value = partition_number_pattern(vm, *number_format, value);
  371. // FIXME: Spec issue - see above, fv instead of num
  372. // iv. Let parts be ! MakePartsList(template, unit, num).
  373. auto parts = make_parts_list(template_, unit, formatted_value);
  374. // v. Let concat be an empty String.
  375. StringBuilder concat;
  376. // vi. For each element part in parts, in List order, do
  377. for (auto const& part : parts) {
  378. // 1. Set concat to the string-concatenation of concat and part.[[Value]].
  379. concat.append(part.value);
  380. // FIXME: It's not clear why this step is here, the unit is functional, it should not be part of the final formatted text
  381. // 2. If part has a [[Unit]] field, then
  382. // if (!part.unit.is_null()) {
  383. // // a. Set concat to the string-concatenation of concat and part.[[Unit]].
  384. // concat.append(part.unit);
  385. // }
  386. }
  387. // vii. Append the new Record { [[Type]]: unit, [[Value]]: concat } to the end of result.
  388. result.append({ unit, concat.build() });
  389. }
  390. // u. If done is true, then
  391. if (done) {
  392. // i. Stop iteration.
  393. break;
  394. }
  395. }
  396. // 3. Let lf be ? Construct(%ListFormat%, « durationFormat.[[Locale]] »).
  397. auto* list_format = static_cast<Intl::ListFormat*>(TRY(construct(global_object, *global_object.intl_list_format_constructor(), js_string(vm, duration_format.locale()))));
  398. // FIXME: CreatePartsFromList expects a list of strings and creates a list of Pattern Partition records, but we already created a list of Pattern Partition records
  399. // so we try to hack something together from it that looks mostly right
  400. Vector<String> string_result;
  401. bool merge = false;
  402. for (size_t i = 0; i < result.size(); ++i) {
  403. auto const& part = result[i];
  404. if (part.type == "literal") {
  405. string_result.last() = String::formatted("{}{}", string_result.last(), part.value);
  406. merge = true;
  407. continue;
  408. }
  409. if (merge) {
  410. string_result.last() = String::formatted("{}{}", string_result.last(), part.value);
  411. merge = false;
  412. continue;
  413. }
  414. string_result.append(part.value);
  415. }
  416. // 4. Set result to ! CreatePartsFromList(lf, result).
  417. auto final_result = create_parts_from_list(*list_format, string_result);
  418. // 5. Return result.
  419. return final_result;
  420. }
  421. }