DurationFormat.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  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(GlobalObject& global_object, Value input)
  123. {
  124. auto& vm = global_object.vm();
  125. // 1. If Type(input) is not Object, throw a TypeError exception.
  126. if (!input.is_object())
  127. return vm.throw_completion<TypeError>(global_object, ErrorType::NotAnObject, input);
  128. auto& input_object = input.as_object();
  129. // 2. Let result be a new Record.
  130. Temporal::DurationRecord result;
  131. // 3. Let any be false.
  132. auto any = false;
  133. // 4. For each row in Table 1, except the header row, in table order, do
  134. for (auto const& duration_instances_component : duration_instances_components) {
  135. // a. Let valueSlot be the Value Slot value.
  136. auto value_slot = duration_instances_component.value_slot;
  137. // b. Let unit be the Unit value.
  138. auto unit = duration_instances_component.unit;
  139. // c. Let value be ? Get(input, unit).
  140. auto value = TRY(input_object.get(FlyString(unit)));
  141. double value_number;
  142. // d. If value is not undefined, then
  143. if (!value.is_undefined()) {
  144. // i. Set any to true.
  145. any = true;
  146. // ii. Set value to ? ToIntegerWithoutRounding(value).
  147. value_number = TRY(Temporal::to_integer_without_rounding(global_object, value, ErrorType::TemporalInvalidDurationPropertyValueNonIntegral, unit, value));
  148. }
  149. // e. Else,
  150. else {
  151. // i. Set value to 0.
  152. value_number = 0;
  153. }
  154. // f. Set the field of result whose name is valueSlot to value.
  155. result.*value_slot = value_number;
  156. }
  157. // 5. If any is false, throw a TypeError exception.
  158. if (!any)
  159. return vm.throw_completion<TypeError>(global_object, ErrorType::TemporalInvalidDurationLikeObject);
  160. // 6. Return result.
  161. return result;
  162. }
  163. // 1.1.4 DurationSign ( record ), https://tc39.es/proposal-intl-duration-format/#sec-durationsign
  164. i8 duration_sign(Temporal::DurationRecord const& record)
  165. {
  166. // 1. For each row in Table 1, except the header row, in table order, do
  167. for (auto const& duration_instances_component : duration_instances_components) {
  168. // a. Let valueSlot be the Value Slot value.
  169. auto value_slot = duration_instances_component.value_slot;
  170. // b. Let v be value of the valueSlot slot of record.
  171. auto value = record.*value_slot;
  172. // c. If v < 0, return -1.
  173. if (value < 0)
  174. return -1;
  175. // d. If v > 0, return 1.
  176. if (value > 0)
  177. return 1;
  178. }
  179. // 2. Return 0.
  180. return 0;
  181. }
  182. // 1.1.5 IsValidDurationRecord ( record ), https://tc39.es/proposal-intl-duration-format/#sec-isvaliddurationrecord
  183. bool is_valid_duration_record(Temporal::DurationRecord const& record)
  184. {
  185. // 1. Let sign be ! DurationSign(record).
  186. auto sign = duration_sign(record);
  187. // 2. For each row in Table 1, except the header row, in table order, do
  188. for (auto const& duration_instances_component : duration_instances_components) {
  189. // a. Let valueSlot be the Value Slot value.
  190. auto value_slot = duration_instances_component.value_slot;
  191. // b. Let v be value of the valueSlot slot of record.
  192. auto value = record.*value_slot;
  193. // c. If 𝔽(v) is not finite, return false.
  194. if (!isfinite(value))
  195. return false;
  196. // d. If v < 0 and sign > 0, return false.
  197. if (value < 0 && sign > 0)
  198. return false;
  199. // e. If v > 0 and sign < 0, return false.
  200. if (value > 0 && sign < 0)
  201. return false;
  202. }
  203. // 3. Return true.
  204. return true;
  205. }
  206. // 1.1.6 GetDurationUnitOptions ( unit, options, baseStyle, stylesList, digitalBase, prevStyle ), https://tc39.es/proposal-intl-duration-format/#sec-getdurationunitoptions
  207. ThrowCompletionOr<DurationUnitOptions> get_duration_unit_options(GlobalObject& global_object, String const& unit, Object const& options, StringView base_style, Span<StringView const> styles_list, StringView digital_base, Optional<String> const& previous_style)
  208. {
  209. auto& vm = global_object.vm();
  210. // 1. Let style be ? GetOption(options, unit, "string", stylesList, undefined).
  211. auto style_value = TRY(get_option(global_object, options, unit, OptionType::String, styles_list, Empty {}));
  212. // 2. Let displayDefault be "always".
  213. auto display_default = "always"sv;
  214. String style;
  215. // 3. If style is undefined, then
  216. if (style_value.is_undefined()) {
  217. // a. Set displayDefault to "auto".
  218. display_default = "auto"sv;
  219. // b. If baseStyle is "digital", then
  220. if (base_style == "digital"sv) {
  221. // i. Set style to digitalBase.
  222. style = digital_base;
  223. }
  224. // c. Else,
  225. else {
  226. // i. Set style to baseStyle.
  227. style = base_style;
  228. }
  229. } else {
  230. style = style_value.as_string().string();
  231. }
  232. // 4. Let displayField be the string-concatenation of unit and "Display".
  233. auto display_field = String::formatted("{}Display", unit);
  234. // 5. Let display be ? GetOption(options, displayField, "string", « "auto", "always" », displayDefault).
  235. auto display = TRY(get_option(global_object, options, display_field, OptionType::String, { "auto"sv, "always"sv }, display_default));
  236. // 6. If prevStyle is "numeric" or "2-digit", then
  237. if (previous_style == "numeric"sv || previous_style == "2-digit"sv) {
  238. // a. If style is not "numeric" or "2-digit", then
  239. if (style != "numeric"sv && style != "2-digit"sv) {
  240. // i. Throw a RangeError exception.
  241. return vm.throw_completion<RangeError>(global_object, ErrorType::IntlNonNumericOr2DigitAfterNumericOr2Digit);
  242. }
  243. // b. Else if unit is "minutes" or "seconds", then
  244. else if (unit == "minutes"sv || unit == "seconds"sv) {
  245. // i. Set style to "2-digit".
  246. style = "2-digit"sv;
  247. }
  248. }
  249. // 7. Return the Record { [[Style]]: style, [[Display]]: display }.
  250. return DurationUnitOptions { .style = move(style), .display = display.as_string().string() };
  251. }
  252. // FIXME: LibUnicode currently only exposes unit patterns converted to an ECMA402 NumberFormat-specific format,
  253. // since DurationFormat only needs a tiny subset of it, it's much easier to just convert it to the expected format
  254. // here, but at some point we should split the the NumberFormat exporter to export both formats of the data.
  255. static String convert_number_format_pattern_to_duration_format_template(Unicode::NumberFormat const& number_format)
  256. {
  257. auto result = number_format.zero_format.replace("{number}", "{0}", ReplaceMode::FirstOnly);
  258. for (size_t i = 0; i < number_format.identifiers.size(); ++i)
  259. result = result.replace(String::formatted("{{unitIdentifier:{}}}", i), number_format.identifiers[i], ReplaceMode::FirstOnly);
  260. return result;
  261. }
  262. // 1.1.7 PartitionDurationFormatPattern ( durationFormat, duration ), https://tc39.es/proposal-intl-duration-format/#sec-partitiondurationformatpattern
  263. ThrowCompletionOr<Vector<PatternPartition>> partition_duration_format_pattern(GlobalObject& global_object, DurationFormat const& duration_format, Temporal::DurationRecord const& duration)
  264. {
  265. auto& vm = global_object.vm();
  266. // 1. Let result be a new empty List.
  267. Vector<PatternPartition> result;
  268. // 2. For each row in Table 1, except the header row, in table order, do
  269. for (size_t i = 0; i < duration_instances_components.size(); ++i) {
  270. auto const& duration_instances_component = duration_instances_components[i];
  271. // a. Let styleSlot be the Style Slot value.
  272. auto style_slot = duration_instances_component.get_style_slot;
  273. decltype(DurationInstanceComponent::get_style_slot) next_style_slot = nullptr;
  274. // FIXME: Missing spec step - If this is not the last row
  275. if (i < duration_instances_components.size() - 1) {
  276. // b. Let nextStyleSlot be the Style Slot value of the next row.
  277. next_style_slot = duration_instances_components[i + 1].get_style_slot;
  278. }
  279. // c. Let displaySlot be the Display Slot value.
  280. auto display_slot = duration_instances_component.get_display_slot;
  281. // d. Let valueSlot be the Value Slot value.
  282. auto value_slot = duration_instances_component.value_slot;
  283. // e. Let unit be the Unit value.
  284. auto unit = duration_instances_component.unit;
  285. // f. Let style be the current value of the styleSlot slot of durationFormat.
  286. auto style = (duration_format.*style_slot)();
  287. DurationFormat::ValueStyle next_style = DurationFormat::ValueStyle::Long;
  288. // FIXME: Missing spec step - If this is not the last row
  289. if (next_style_slot) {
  290. // g. Let nextStyle be the current value of the nextStyleSlot slot of durationFormat.
  291. next_style = (duration_format.*next_style_slot)();
  292. }
  293. // h. Let nfOpts be ! OrdinaryObjectCreate(null).
  294. auto* number_format_options = Object::create(global_object, nullptr);
  295. // i. Let value be 0.
  296. auto value = Value(0);
  297. // j. Let done be false.
  298. auto done = false;
  299. // k. If unit is "seconds", "milliseconds" or "microseconds" and nextStyle is "numeric", then
  300. if (unit.is_one_of("seconds"sv, "milliseconds"sv, "microseconds"sv) && next_style == DurationFormat::ValueStyle::Numeric) {
  301. // i. Set value to duration.[[Microseconds]] + duration.[[Nanoseconds]] / 1000.
  302. auto value_number = duration.microseconds + (duration.nanoseconds / 1000);
  303. // ii. If unit is "seconds" or "milliseconds", then
  304. if (unit.is_one_of("seconds"sv, "milliseconds"sv)) {
  305. // 1. Set value to duration.[[Milliseconds]] + value / 1000.
  306. value_number = duration.milliseconds + (value_number / 1000);
  307. // 2. If unit is "seconds", then
  308. if (unit == "seconds"sv) {
  309. // a. Set value to duration.[[Seconds]] + value / 1000.
  310. value_number = duration.seconds + (value_number / 1000);
  311. }
  312. }
  313. value = Value(value_number);
  314. // iii. Perform ! CreateDataPropertyOrThrow(nfOpts, "maximumFractionDigits", durationFormat.[[FractionalDigits]]).
  315. MUST(number_format_options->create_data_property_or_throw(vm.names.maximumFractionDigits, duration_format.has_fractional_digits() ? Value(duration_format.fractional_digits()) : js_undefined()));
  316. // iv. Perform ! CreateDataPropertyOrThrow(nfOpts, "minimumFractionDigits", durationFormat.[[FractionalDigits]]).
  317. MUST(number_format_options->create_data_property_or_throw(vm.names.minimumFractionDigits, duration_format.has_fractional_digits() ? Value(duration_format.fractional_digits()) : js_undefined()));
  318. // v. Set done to true.
  319. done = true;
  320. }
  321. // l. Else,
  322. else {
  323. // i. Set value to the current value of the valueSlot slot of duration.
  324. value = Value(duration.*value_slot);
  325. }
  326. // m. If style is "2-digit", then
  327. if (style == DurationFormat::ValueStyle::TwoDigit) {
  328. // i. Perform ! CreateDataPropertyOrThrow(nfOpts, "minimumIntegerDigits", 2).
  329. MUST(number_format_options->create_data_property_or_throw(vm.names.minimumIntegerDigits, Value(2)));
  330. }
  331. // FIXME: Missing spec step - Let display be the current value of the displaySlot slot of durationFormat.
  332. auto display = (duration_format.*display_slot)();
  333. // n. If value is +0𝔽 or -0𝔽 and display is "auto", then
  334. if ((value.is_negative_zero() || value.is_positive_zero()) && display == DurationFormat::Display::Auto) {
  335. // i. Skip to the next iteration.
  336. continue;
  337. }
  338. // o. Let nf be ? Construct(%NumberFormat%, « durationFormat.[[Locale]], nfOpts »).
  339. 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)));
  340. // FIXME: durationFormat.[[NumberFormat]] is not a thing, the spec likely means 'nf' in this case
  341. // p. Let num be ! FormatNumeric(durationFormat.[[NumberFormat]], value).
  342. auto number = format_numeric(global_object, *number_format, value);
  343. // q. Let dataLocale be durationFormat.[[DataLocale]].
  344. auto const& data_locale = duration_format.data_locale();
  345. // r. Let dataLocaleData be the current value of the dataLocale slot of %DurationFormat%.[[LocaleData]].
  346. // s. If style is "2-digit" or "numeric", then
  347. if (style == DurationFormat::ValueStyle::TwoDigit || style == DurationFormat::ValueStyle::Numeric) {
  348. // i. Append the new Record { [[Type]]: unit, [[Value]]: num} to the end of result.
  349. result.append({ unit, number });
  350. // ii. If unit is "hours" or "minutes", then
  351. if (unit.is_one_of("hours"sv, "minutes"sv)) {
  352. // 1. Let separator be dataLocaleData.[[formats]].[[digital]].[[separator]].
  353. auto separator = Unicode::get_number_system_symbol(data_locale, duration_format.numbering_system(), Unicode::NumericSymbol::TimeSeparator).value_or(":"sv);
  354. // 2. Append the new Record { [[Type]]: "literal", [[Value]]: separator} to the end of result.
  355. result.append({ "literal", separator });
  356. }
  357. }
  358. // t. Else,
  359. else {
  360. // i. Let pr be ? Construct(%PluralRules%, « durationFormat.[[Locale]] »).
  361. // ii. Let prv be ! ResolvePlural(pr, value).
  362. // FIXME: Use ResolvePlural when Intl.PluralRules is implemented.
  363. auto formats = Unicode::get_unit_formats(data_locale, duration_instances_component.unit_singular, static_cast<Unicode::Style>(style));
  364. auto pattern = Unicode::select_pattern_with_plurality(formats, value.as_double()).release_value();
  365. // iii. Let template be the current value of the prv slot of the unit slot of the style slot of dataLocaleData.[[formats]].
  366. auto template_ = convert_number_format_pattern_to_duration_format_template(pattern);
  367. // FIXME: MakePartsList takes a list, not a string, so likely missing spec step: Let fv be ! PartitionNumberPattern(nf, value).
  368. auto formatted_value = partition_number_pattern(global_object, *number_format, value);
  369. // FIXME: Spec issue - see above, fv instead of num
  370. // iv. Let parts be ! MakePartsList(template, unit, num).
  371. auto parts = make_parts_list(template_, unit, formatted_value);
  372. // v. Let concat be an empty String.
  373. StringBuilder concat;
  374. // vi. For each element part in parts, in List order, do
  375. for (auto const& part : parts) {
  376. // 1. Set concat to the string-concatenation of concat and part.[[Value]].
  377. concat.append(part.value);
  378. // FIXME: It's not clear why this step is here, the unit is functional, it should not be part of the final formatted text
  379. // 2. If part has a [[Unit]] field, then
  380. // if (!part.unit.is_null()) {
  381. // // a. Set concat to the string-concatenation of concat and part.[[Unit]].
  382. // concat.append(part.unit);
  383. // }
  384. }
  385. // vii. Append the new Record { [[Type]]: unit, [[Value]]: concat } to the end of result.
  386. result.append({ unit, concat.build() });
  387. }
  388. // u. If done is true, then
  389. if (done) {
  390. // i. Stop iteration.
  391. break;
  392. }
  393. }
  394. // 3. Let lf be ? Construct(%ListFormat%, « durationFormat.[[Locale]] »).
  395. auto* list_format = static_cast<Intl::ListFormat*>(TRY(construct(global_object, *global_object.intl_list_format_constructor(), js_string(vm, duration_format.locale()))));
  396. // 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
  397. // so we try to hack something together from it that looks mostly right
  398. Vector<String> string_result;
  399. bool merge = false;
  400. for (size_t i = 0; i < result.size(); ++i) {
  401. auto const& part = result[i];
  402. if (part.type == "literal") {
  403. string_result.last() = String::formatted("{}{}", string_result.last(), part.value);
  404. merge = true;
  405. continue;
  406. }
  407. if (merge) {
  408. string_result.last() = String::formatted("{}{}", string_result.last(), part.value);
  409. merge = false;
  410. continue;
  411. }
  412. string_result.append(part.value);
  413. }
  414. // 4. Set result to ! CreatePartsFromList(lf, result).
  415. auto final_result = create_parts_from_list(*list_format, string_result);
  416. // 5. Return result.
  417. return final_result;
  418. }
  419. }