DurationFormat.cpp 21 KB

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