DateTimeFormat.cpp 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267
  1. /*
  2. * Copyright (c) 2021-2023, Tim Flynn <trflynn89@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Find.h>
  7. #include <AK/IterationDecision.h>
  8. #include <AK/NumericLimits.h>
  9. #include <AK/Utf16View.h>
  10. #include <LibJS/Runtime/AbstractOperations.h>
  11. #include <LibJS/Runtime/Array.h>
  12. #include <LibJS/Runtime/Date.h>
  13. #include <LibJS/Runtime/Intl/DateTimeFormat.h>
  14. #include <LibJS/Runtime/Intl/NumberFormat.h>
  15. #include <LibJS/Runtime/Intl/NumberFormatConstructor.h>
  16. #include <LibJS/Runtime/NativeFunction.h>
  17. #include <LibJS/Runtime/ThrowableStringBuilder.h>
  18. #include <LibJS/Runtime/Utf16String.h>
  19. #include <LibLocale/Locale.h>
  20. #include <LibLocale/NumberFormat.h>
  21. #include <math.h>
  22. namespace JS::Intl {
  23. static Crypto::SignedBigInteger const s_one_million_bigint { 1'000'000 };
  24. // 11 DateTimeFormat Objects, https://tc39.es/ecma402/#datetimeformat-objects
  25. DateTimeFormat::DateTimeFormat(Object& prototype)
  26. : Object(ConstructWithPrototypeTag::Tag, prototype)
  27. {
  28. }
  29. void DateTimeFormat::visit_edges(Cell::Visitor& visitor)
  30. {
  31. Base::visit_edges(visitor);
  32. if (m_bound_format)
  33. visitor.visit(m_bound_format);
  34. }
  35. DateTimeFormat::Style DateTimeFormat::style_from_string(StringView style)
  36. {
  37. if (style == "full"sv)
  38. return Style::Full;
  39. if (style == "long"sv)
  40. return Style::Long;
  41. if (style == "medium"sv)
  42. return Style::Medium;
  43. if (style == "short"sv)
  44. return Style::Short;
  45. VERIFY_NOT_REACHED();
  46. }
  47. StringView DateTimeFormat::style_to_string(Style style)
  48. {
  49. switch (style) {
  50. case Style::Full:
  51. return "full"sv;
  52. case Style::Long:
  53. return "long"sv;
  54. case Style::Medium:
  55. return "medium"sv;
  56. case Style::Short:
  57. return "short"sv;
  58. default:
  59. VERIFY_NOT_REACHED();
  60. }
  61. }
  62. // 11.5.1 ToDateTimeOptions ( options, required, defaults ), https://tc39.es/ecma402/#sec-todatetimeoptions
  63. ThrowCompletionOr<Object*> to_date_time_options(VM& vm, Value options_value, OptionRequired required, OptionDefaults defaults)
  64. {
  65. auto& realm = *vm.current_realm();
  66. // 1. If options is undefined, let options be null; otherwise let options be ? ToObject(options).
  67. Object* options = nullptr;
  68. if (!options_value.is_undefined())
  69. options = TRY(options_value.to_object(vm));
  70. // 2. Let options be OrdinaryObjectCreate(options).
  71. options = Object::create(realm, options);
  72. // 3. Let needDefaults be true.
  73. bool needs_defaults = true;
  74. // 4. If required is "date" or "any", then
  75. if ((required == OptionRequired::Date) || (required == OptionRequired::Any)) {
  76. // a. For each property name prop of « "weekday", "year", "month", "day" », do
  77. for (auto const& property : AK::Array { vm.names.weekday, vm.names.year, vm.names.month, vm.names.day }) {
  78. // i. Let value be ? Get(options, prop).
  79. auto value = TRY(options->get(property));
  80. // ii. If value is not undefined, let needDefaults be false.
  81. if (!value.is_undefined())
  82. needs_defaults = false;
  83. }
  84. }
  85. // 5. If required is "time" or "any", then
  86. if ((required == OptionRequired::Time) || (required == OptionRequired::Any)) {
  87. // a. For each property name prop of « "dayPeriod", "hour", "minute", "second", "fractionalSecondDigits" », do
  88. for (auto const& property : AK::Array { vm.names.dayPeriod, vm.names.hour, vm.names.minute, vm.names.second, vm.names.fractionalSecondDigits }) {
  89. // i. Let value be ? Get(options, prop).
  90. auto value = TRY(options->get(property));
  91. // ii. If value is not undefined, let needDefaults be false.
  92. if (!value.is_undefined())
  93. needs_defaults = false;
  94. }
  95. }
  96. // 6. Let dateStyle be ? Get(options, "dateStyle").
  97. auto date_style = TRY(options->get(vm.names.dateStyle));
  98. // 7. Let timeStyle be ? Get(options, "timeStyle").
  99. auto time_style = TRY(options->get(vm.names.timeStyle));
  100. // 8. If dateStyle is not undefined or timeStyle is not undefined, let needDefaults be false.
  101. if (!date_style.is_undefined() || !time_style.is_undefined())
  102. needs_defaults = false;
  103. // 9. If required is "date" and timeStyle is not undefined, then
  104. if ((required == OptionRequired::Date) && !time_style.is_undefined()) {
  105. // a. Throw a TypeError exception.
  106. return vm.throw_completion<TypeError>(ErrorType::IntlInvalidDateTimeFormatOption, "timeStyle"sv, "date"sv);
  107. }
  108. // 10. If required is "time" and dateStyle is not undefined, then
  109. if ((required == OptionRequired::Time) && !date_style.is_undefined()) {
  110. // a. Throw a TypeError exception.
  111. return vm.throw_completion<TypeError>(ErrorType::IntlInvalidDateTimeFormatOption, "dateStyle"sv, "time"sv);
  112. }
  113. // 11. If needDefaults is true and defaults is either "date" or "all", then
  114. if (needs_defaults && ((defaults == OptionDefaults::Date) || (defaults == OptionDefaults::All))) {
  115. // a. For each property name prop of « "year", "month", "day" », do
  116. for (auto const& property : AK::Array { vm.names.year, vm.names.month, vm.names.day }) {
  117. // i. Perform ? CreateDataPropertyOrThrow(options, prop, "numeric").
  118. TRY(options->create_data_property_or_throw(property, PrimitiveString::create(vm, "numeric"sv)));
  119. }
  120. }
  121. // 12. If needDefaults is true and defaults is either "time" or "all", then
  122. if (needs_defaults && ((defaults == OptionDefaults::Time) || (defaults == OptionDefaults::All))) {
  123. // a. For each property name prop of « "hour", "minute", "second" », do
  124. for (auto const& property : AK::Array { vm.names.hour, vm.names.minute, vm.names.second }) {
  125. // i. Perform ? CreateDataPropertyOrThrow(options, prop, "numeric").
  126. TRY(options->create_data_property_or_throw(property, PrimitiveString::create(vm, "numeric"sv)));
  127. }
  128. }
  129. // 13. Return options.
  130. return options;
  131. }
  132. // 11.5.2 DateTimeStyleFormat ( dateStyle, timeStyle, styles ), https://tc39.es/ecma402/#sec-date-time-style-format
  133. ThrowCompletionOr<Optional<::Locale::CalendarPattern>> date_time_style_format(VM& vm, StringView data_locale, DateTimeFormat& date_time_format)
  134. {
  135. ::Locale::CalendarPattern time_format {};
  136. ::Locale::CalendarPattern date_format {};
  137. auto get_pattern = [&](auto type, auto style) -> ThrowCompletionOr<Optional<::Locale::CalendarPattern>> {
  138. auto formats = TRY_OR_THROW_OOM(vm, ::Locale::get_calendar_format(data_locale, date_time_format.calendar(), type));
  139. if (formats.has_value()) {
  140. switch (style) {
  141. case DateTimeFormat::Style::Full:
  142. return formats->full_format;
  143. case DateTimeFormat::Style::Long:
  144. return formats->long_format;
  145. case DateTimeFormat::Style::Medium:
  146. return formats->medium_format;
  147. case DateTimeFormat::Style::Short:
  148. return formats->short_format;
  149. }
  150. }
  151. return OptionalNone {};
  152. };
  153. // 1. If timeStyle is not undefined, then
  154. if (date_time_format.has_time_style()) {
  155. // a. Assert: timeStyle is one of "full", "long", "medium", or "short".
  156. // b. Let timeFormat be styles.[[TimeFormat]].[[<timeStyle>]].
  157. auto pattern = MUST_OR_THROW_OOM(get_pattern(::Locale::CalendarFormatType::Time, date_time_format.time_style()));
  158. if (!pattern.has_value())
  159. return OptionalNone {};
  160. time_format = pattern.release_value();
  161. }
  162. // 2. If dateStyle is not undefined, then
  163. if (date_time_format.has_date_style()) {
  164. // a. Assert: dateStyle is one of "full", "long", "medium", or "short".
  165. // b. Let dateFormat be styles.[[DateFormat]].[[<dateStyle>]].
  166. auto pattern = MUST_OR_THROW_OOM(get_pattern(::Locale::CalendarFormatType::Date, date_time_format.date_style()));
  167. if (!pattern.has_value())
  168. return OptionalNone {};
  169. date_format = pattern.release_value();
  170. }
  171. // 3. If dateStyle is not undefined and timeStyle is not undefined, then
  172. if (date_time_format.has_date_style() && date_time_format.has_time_style()) {
  173. // a. Let format be a new Record.
  174. ::Locale::CalendarPattern format {};
  175. // b. Add to format all fields from dateFormat except [[pattern]] and [[rangePatterns]].
  176. format.for_each_calendar_field_zipped_with(date_format, [](auto& format_field, auto const& date_format_field, auto) {
  177. format_field = date_format_field;
  178. });
  179. // c. Add to format all fields from timeFormat except [[pattern]], [[rangePatterns]], [[pattern12]], and [[rangePatterns12]], if present.
  180. format.for_each_calendar_field_zipped_with(time_format, [](auto& format_field, auto const& time_format_field, auto) {
  181. if (time_format_field.has_value())
  182. format_field = time_format_field;
  183. });
  184. // d. Let connector be styles.[[DateTimeFormat]].[[<dateStyle>]].
  185. auto connector = MUST_OR_THROW_OOM(get_pattern(::Locale::CalendarFormatType::DateTime, date_time_format.date_style()));
  186. if (!connector.has_value())
  187. return OptionalNone {};
  188. // e. Let pattern be the string connector with the substring "{0}" replaced with timeFormat.[[pattern]] and the substring "{1}" replaced with dateFormat.[[pattern]].
  189. auto pattern = TRY_OR_THROW_OOM(vm, connector->pattern.replace("{0}"sv, time_format.pattern, ReplaceMode::FirstOnly));
  190. pattern = TRY_OR_THROW_OOM(vm, pattern.replace("{1}"sv, date_format.pattern, ReplaceMode::FirstOnly));
  191. // f. Set format.[[pattern]] to pattern.
  192. format.pattern = move(pattern);
  193. // g. If timeFormat has a [[pattern12]] field, then
  194. if (time_format.pattern12.has_value()) {
  195. // i. Let pattern12 be the string connector with the substring "{0}" replaced with timeFormat.[[pattern12]] and the substring "{1}" replaced with dateFormat.[[pattern]].
  196. auto pattern12 = TRY_OR_THROW_OOM(vm, connector->pattern.replace("{0}"sv, *time_format.pattern12, ReplaceMode::FirstOnly));
  197. pattern12 = TRY_OR_THROW_OOM(vm, pattern12.replace("{1}"sv, date_format.pattern, ReplaceMode::FirstOnly));
  198. // ii. Set format.[[pattern12]] to pattern12.
  199. format.pattern12 = move(pattern12);
  200. }
  201. // NOTE: Our implementation of steps h-j differ from the spec. LibUnicode does not attach range patterns to the
  202. // format pattern; rather, lookups for range patterns are performed separately based on the format pattern's
  203. // skeleton. So we form a new skeleton here and defer the range pattern lookups.
  204. format.skeleton = TRY_OR_THROW_OOM(vm, ::Locale::combine_skeletons(date_format.skeleton, time_format.skeleton));
  205. // k. Return format.
  206. return format;
  207. }
  208. // 4. If timeStyle is not undefined, then
  209. if (date_time_format.has_time_style()) {
  210. // a. Return timeFormat.
  211. return time_format;
  212. }
  213. // 5. Assert: dateStyle is not undefined.
  214. VERIFY(date_time_format.has_date_style());
  215. // 6. Return dateFormat.
  216. return date_format;
  217. }
  218. // 11.5.3 BasicFormatMatcher ( options, formats ), https://tc39.es/ecma402/#sec-basicformatmatcher
  219. Optional<::Locale::CalendarPattern> basic_format_matcher(::Locale::CalendarPattern const& options, Vector<::Locale::CalendarPattern> formats)
  220. {
  221. // 1. Let removalPenalty be 120.
  222. constexpr int removal_penalty = 120;
  223. // 2. Let additionPenalty be 20.
  224. constexpr int addition_penalty = 20;
  225. // 3. Let longLessPenalty be 8.
  226. constexpr int long_less_penalty = 8;
  227. // 4. Let longMorePenalty be 6.
  228. constexpr int long_more_penalty = 6;
  229. // 5. Let shortLessPenalty be 6.
  230. constexpr int short_less_penalty = 6;
  231. // 6. Let shortMorePenalty be 3.
  232. constexpr int short_more_penalty = 3;
  233. // 7. Let offsetPenalty be 1.
  234. constexpr int offset_penalty = 1;
  235. // 8. Let bestScore be -Infinity.
  236. int best_score = NumericLimits<int>::min();
  237. // 9. Let bestFormat be undefined.
  238. Optional<::Locale::CalendarPattern> best_format;
  239. // 10. Assert: Type(formats) is List.
  240. // 11. For each element format of formats, do
  241. for (auto& format : formats) {
  242. // a. Let score be 0.
  243. int score = 0;
  244. // b. For each property name property shown in Table 6, do
  245. format.for_each_calendar_field_zipped_with(options, [&](auto const& format_prop, auto const& options_prop, auto type) {
  246. using ValueType = typename RemoveReference<decltype(options_prop)>::ValueType;
  247. // i. If options has a field [[<property>]], let optionsProp be options.[[<property>]]; else let optionsProp be undefined.
  248. // ii. If format has a field [[<property>]], let formatProp be format.[[<property>]]; else let formatProp be undefined.
  249. // iii. If optionsProp is undefined and formatProp is not undefined, decrease score by additionPenalty.
  250. if (!options_prop.has_value() && format_prop.has_value()) {
  251. score -= addition_penalty;
  252. }
  253. // iv. Else if optionsProp is not undefined and formatProp is undefined, decrease score by removalPenalty.
  254. else if (options_prop.has_value() && !format_prop.has_value()) {
  255. score -= removal_penalty;
  256. }
  257. // v. Else if property is "timeZoneName", then
  258. else if (type == ::Locale::CalendarPattern::Field::TimeZoneName) {
  259. // This is needed to avoid a compile error. Although we only enter this branch for TimeZoneName,
  260. // the lambda we are in will be generated with property types other than CalendarPatternStyle.
  261. auto compare_prop = [](auto prop, auto test) { return prop == static_cast<ValueType>(test); };
  262. // 1. If optionsProp is "short" or "shortGeneric", then
  263. if (compare_prop(options_prop, ::Locale::CalendarPatternStyle::Short) || compare_prop(options_prop, ::Locale::CalendarPatternStyle::ShortGeneric)) {
  264. // a. If formatProp is "shortOffset", decrease score by offsetPenalty.
  265. if (compare_prop(format_prop, ::Locale::CalendarPatternStyle::ShortOffset))
  266. score -= offset_penalty;
  267. // b. Else if formatProp is "longOffset", decrease score by (offsetPenalty + shortMorePenalty).
  268. else if (compare_prop(format_prop, ::Locale::CalendarPatternStyle::LongOffset))
  269. score -= offset_penalty + short_more_penalty;
  270. // c. Else if optionsProp is "short" and formatProp is "long", decrease score by shortMorePenalty.
  271. else if (compare_prop(options_prop, ::Locale::CalendarPatternStyle::Short) || compare_prop(format_prop, ::Locale::CalendarPatternStyle::Long))
  272. score -= short_more_penalty;
  273. // d. Else if optionsProp is "shortGeneric" and formatProp is "longGeneric", decrease score by shortMorePenalty.
  274. else if (compare_prop(options_prop, ::Locale::CalendarPatternStyle::ShortGeneric) || compare_prop(format_prop, ::Locale::CalendarPatternStyle::LongGeneric))
  275. score -= short_more_penalty;
  276. // e. Else if optionsProp ≠ formatProp, decrease score by removalPenalty.
  277. else if (options_prop != format_prop)
  278. score -= removal_penalty;
  279. }
  280. // 2. Else if optionsProp is "shortOffset" and formatProp is "longOffset", decrease score by shortMorePenalty.
  281. else if (compare_prop(options_prop, ::Locale::CalendarPatternStyle::ShortOffset) || compare_prop(format_prop, ::Locale::CalendarPatternStyle::LongOffset)) {
  282. score -= short_more_penalty;
  283. }
  284. // 3. Else if optionsProp is "long" or "longGeneric", then
  285. else if (compare_prop(options_prop, ::Locale::CalendarPatternStyle::Long) || compare_prop(options_prop, ::Locale::CalendarPatternStyle::LongGeneric)) {
  286. // a. If formatProp is "longOffset", decrease score by offsetPenalty.
  287. if (compare_prop(format_prop, ::Locale::CalendarPatternStyle::LongOffset))
  288. score -= offset_penalty;
  289. // b. Else if formatProp is "shortOffset", decrease score by (offsetPenalty + longLessPenalty).
  290. else if (compare_prop(format_prop, ::Locale::CalendarPatternStyle::ShortOffset))
  291. score -= offset_penalty + long_less_penalty;
  292. // c. Else if optionsProp is "long" and formatProp is "short", decrease score by longLessPenalty.
  293. else if (compare_prop(options_prop, ::Locale::CalendarPatternStyle::Long) || compare_prop(format_prop, ::Locale::CalendarPatternStyle::Short))
  294. score -= long_less_penalty;
  295. // d. Else if optionsProp is "longGeneric" and formatProp is "shortGeneric", decrease score by longLessPenalty.
  296. else if (compare_prop(options_prop, ::Locale::CalendarPatternStyle::LongGeneric) || compare_prop(format_prop, ::Locale::CalendarPatternStyle::ShortGeneric))
  297. score -= long_less_penalty;
  298. // e. Else if optionsProp ≠ formatProp, decrease score by removalPenalty.
  299. else if (options_prop != format_prop)
  300. score -= removal_penalty;
  301. }
  302. // 4. Else if optionsProp is "longOffset" and formatProp is "shortOffset", decrease score by longLessPenalty.
  303. else if (compare_prop(options_prop, ::Locale::CalendarPatternStyle::LongOffset) || compare_prop(format_prop, ::Locale::CalendarPatternStyle::ShortOffset)) {
  304. score -= long_less_penalty;
  305. }
  306. // 5. Else if optionsProp ≠ formatProp, decrease score by removalPenalty.
  307. else if (options_prop != format_prop) {
  308. score -= removal_penalty;
  309. }
  310. }
  311. // vi. Else if optionsProp ≠ formatProp, then
  312. else if (options_prop != format_prop) {
  313. using ValuesType = Conditional<IsIntegral<ValueType>, AK::Array<u8, 3>, AK::Array<::Locale::CalendarPatternStyle, 5>>;
  314. ValuesType values {};
  315. // 1. If property is "fractionalSecondDigits", then
  316. if constexpr (IsIntegral<ValueType>) {
  317. // a. Let values be « 1𝔽, 2𝔽, 3𝔽 ».
  318. values = { 1, 2, 3 };
  319. }
  320. // 2. Else,
  321. else {
  322. // a. Let values be « "2-digit", "numeric", "narrow", "short", "long" ».
  323. values = {
  324. ::Locale::CalendarPatternStyle::TwoDigit,
  325. ::Locale::CalendarPatternStyle::Numeric,
  326. ::Locale::CalendarPatternStyle::Narrow,
  327. ::Locale::CalendarPatternStyle::Short,
  328. ::Locale::CalendarPatternStyle::Long,
  329. };
  330. }
  331. // 3. Let optionsPropIndex be the index of optionsProp within values.
  332. auto options_prop_index = static_cast<int>(find_index(values.begin(), values.end(), *options_prop));
  333. // 4. Let formatPropIndex be the index of formatProp within values.
  334. auto format_prop_index = static_cast<int>(find_index(values.begin(), values.end(), *format_prop));
  335. // 5. Let delta be max(min(formatPropIndex - optionsPropIndex, 2), -2).
  336. int delta = max(min(format_prop_index - options_prop_index, 2), -2);
  337. // 6. If delta = 2, decrease score by longMorePenalty.
  338. if (delta == 2)
  339. score -= long_more_penalty;
  340. // 7. Else if delta = 1, decrease score by shortMorePenalty.
  341. else if (delta == 1)
  342. score -= short_more_penalty;
  343. // 8. Else if delta = -1, decrease score by shortLessPenalty.
  344. else if (delta == -1)
  345. score -= short_less_penalty;
  346. // 9. Else if delta = -2, decrease score by longLessPenalty.
  347. else if (delta == -2)
  348. score -= long_less_penalty;
  349. }
  350. });
  351. // c. If score > bestScore, then
  352. if (score > best_score) {
  353. // i. Let bestScore be score.
  354. best_score = score;
  355. // ii. Let bestFormat be format.
  356. best_format = format;
  357. }
  358. }
  359. if (!best_format.has_value())
  360. return {};
  361. // Non-standard, if the user provided options that differ from the best format's options, keep
  362. // the user's options. This is expected by TR-35:
  363. //
  364. // It is not necessary to supply dateFormatItems with skeletons for every field length; fields
  365. // in the skeleton and pattern are expected to be expanded in parallel to handle a request.
  366. // https://unicode.org/reports/tr35/tr35-dates.html#Matching_Skeletons
  367. //
  368. // Rather than generating an prohibitively large amount of nearly-duplicate patterns, which only
  369. // differ by field length, we expand the field lengths here.
  370. best_format->for_each_calendar_field_zipped_with(options, [&](auto& best_format_field, auto const& option_field, auto field_type) {
  371. switch (field_type) {
  372. case ::Locale::CalendarPattern::Field::FractionalSecondDigits:
  373. if ((best_format_field.has_value() || best_format->second.has_value()) && option_field.has_value())
  374. best_format_field = option_field;
  375. break;
  376. case ::Locale::CalendarPattern::Field::Hour:
  377. case ::Locale::CalendarPattern::Field::Minute:
  378. case ::Locale::CalendarPattern::Field::Second:
  379. break;
  380. default:
  381. if (best_format_field.has_value() && option_field.has_value())
  382. best_format_field = option_field;
  383. break;
  384. }
  385. });
  386. // 12. Return bestFormat.
  387. return best_format;
  388. }
  389. // 11.5.4 BestFitFormatMatcher ( options, formats ), https://tc39.es/ecma402/#sec-bestfitformatmatcher
  390. Optional<::Locale::CalendarPattern> best_fit_format_matcher(::Locale::CalendarPattern const& options, Vector<::Locale::CalendarPattern> formats)
  391. {
  392. // When the BestFitFormatMatcher abstract operation is called with two arguments options and formats, it performs
  393. // implementation dependent steps, which should return a set of component representations that a typical user of
  394. // the selected locale would perceive as at least as good as the one returned by BasicFormatMatcher.
  395. return basic_format_matcher(options, move(formats));
  396. }
  397. struct StyleAndValue {
  398. StringView name {};
  399. ::Locale::CalendarPatternStyle style {};
  400. i32 value { 0 };
  401. };
  402. static Optional<StyleAndValue> find_calendar_field(StringView name, ::Locale::CalendarPattern const& options, ::Locale::CalendarPattern const* range_options, LocalTime const& local_time)
  403. {
  404. auto make_style_and_value = [](auto name, auto style, auto fallback_style, auto value) {
  405. if (style.has_value())
  406. return StyleAndValue { name, *style, static_cast<i32>(value) };
  407. return StyleAndValue { name, fallback_style, static_cast<i32>(value) };
  408. };
  409. constexpr auto weekday = "weekday"sv;
  410. constexpr auto era = "era"sv;
  411. constexpr auto year = "year"sv;
  412. constexpr auto month = "month"sv;
  413. constexpr auto day = "day"sv;
  414. constexpr auto hour = "hour"sv;
  415. constexpr auto minute = "minute"sv;
  416. constexpr auto second = "second"sv;
  417. Optional<::Locale::CalendarPatternStyle> empty;
  418. if (name == weekday)
  419. return make_style_and_value(weekday, range_options ? range_options->weekday : empty, *options.weekday, local_time.weekday);
  420. if (name == era)
  421. return make_style_and_value(era, range_options ? range_options->era : empty, *options.era, local_time.era);
  422. if (name == year)
  423. return make_style_and_value(year, range_options ? range_options->year : empty, *options.year, local_time.year);
  424. if (name == month)
  425. return make_style_and_value(month, range_options ? range_options->month : empty, *options.month, local_time.month);
  426. if (name == day)
  427. return make_style_and_value(day, range_options ? range_options->day : empty, *options.day, local_time.day);
  428. if (name == hour)
  429. return make_style_and_value(hour, range_options ? range_options->hour : empty, *options.hour, local_time.hour);
  430. if (name == minute)
  431. return make_style_and_value(minute, range_options ? range_options->minute : empty, *options.minute, local_time.minute);
  432. if (name == second)
  433. return make_style_and_value(second, range_options ? range_options->second : empty, *options.second, local_time.second);
  434. return {};
  435. }
  436. static ThrowCompletionOr<Optional<StringView>> resolve_day_period(VM& vm, StringView locale, StringView calendar, ::Locale::CalendarPatternStyle style, Span<PatternPartition const> pattern_parts, LocalTime local_time)
  437. {
  438. // Use the "noon" day period if the locale has it, but only if the time is either exactly 12:00.00 or would be displayed as such.
  439. if (local_time.hour == 12) {
  440. auto it = find_if(pattern_parts.begin(), pattern_parts.end(), [&](auto const& part) {
  441. if (part.type == "minute"sv && local_time.minute != 0)
  442. return true;
  443. if (part.type == "second"sv && local_time.second != 0)
  444. return true;
  445. if (part.type == "fractionalSecondDigits"sv && local_time.millisecond != 0)
  446. return true;
  447. return false;
  448. });
  449. if (it == pattern_parts.end()) {
  450. auto noon_symbol = TRY_OR_THROW_OOM(vm, ::Locale::get_calendar_day_period_symbol(locale, calendar, style, ::Locale::DayPeriod::Noon));
  451. if (noon_symbol.has_value())
  452. return *noon_symbol;
  453. }
  454. }
  455. return TRY_OR_THROW_OOM(vm, ::Locale::get_calendar_day_period_symbol_for_hour(locale, calendar, style, local_time.hour));
  456. }
  457. // 11.5.6 FormatDateTimePattern ( dateTimeFormat, patternParts, x, rangeFormatOptions ), https://tc39.es/ecma402/#sec-formatdatetimepattern
  458. ThrowCompletionOr<Vector<PatternPartition>> format_date_time_pattern(VM& vm, DateTimeFormat& date_time_format, Vector<PatternPartition> pattern_parts, double time, ::Locale::CalendarPattern const* range_format_options)
  459. {
  460. auto& realm = *vm.current_realm();
  461. // 1. Let x be TimeClip(x).
  462. time = time_clip(time);
  463. // 2. If x is NaN, throw a RangeError exception.
  464. if (isnan(time))
  465. return vm.throw_completion<RangeError>(ErrorType::IntlInvalidTime);
  466. // 3. Let locale be dateTimeFormat.[[Locale]].
  467. auto const& locale = date_time_format.locale();
  468. auto const& data_locale = date_time_format.data_locale();
  469. auto construct_number_format = [&](auto& options) -> ThrowCompletionOr<NumberFormat*> {
  470. auto number_format = TRY(construct(vm, *realm.intrinsics().intl_number_format_constructor(), PrimitiveString::create(vm, locale), options));
  471. return static_cast<NumberFormat*>(number_format.ptr());
  472. };
  473. // 4. Let nfOptions be OrdinaryObjectCreate(null).
  474. auto number_format_options = Object::create(realm, nullptr);
  475. // 5. Perform ! CreateDataPropertyOrThrow(nfOptions, "useGrouping", false).
  476. MUST(number_format_options->create_data_property_or_throw(vm.names.useGrouping, Value(false)));
  477. // 6. Let nf be ? Construct(%NumberFormat%, « locale, nfOptions »).
  478. auto* number_format = TRY(construct_number_format(number_format_options));
  479. // 7. Let nf2Options be OrdinaryObjectCreate(null).
  480. auto number_format_options2 = Object::create(realm, nullptr);
  481. // 8. Perform ! CreateDataPropertyOrThrow(nf2Options, "minimumIntegerDigits", 2).
  482. MUST(number_format_options2->create_data_property_or_throw(vm.names.minimumIntegerDigits, Value(2)));
  483. // 9. Perform ! CreateDataPropertyOrThrow(nf2Options, "useGrouping", false).
  484. MUST(number_format_options2->create_data_property_or_throw(vm.names.useGrouping, Value(false)));
  485. // 10. Let nf2 be ? Construct(%NumberFormat%, « locale, nf2Options »).
  486. auto* number_format2 = TRY(construct_number_format(number_format_options2));
  487. // 11. Let fractionalSecondDigits be dateTimeFormat.[[FractionalSecondDigits]].
  488. Optional<u8> fractional_second_digits;
  489. NumberFormat* number_format3 = nullptr;
  490. // 12. If fractionalSecondDigits is not undefined, then
  491. if (date_time_format.has_fractional_second_digits()) {
  492. fractional_second_digits = date_time_format.fractional_second_digits();
  493. // a. Let nf3Options be OrdinaryObjectCreate(null).
  494. auto number_format_options3 = Object::create(realm, nullptr);
  495. // b. Perform ! CreateDataPropertyOrThrow(nf3Options, "minimumIntegerDigits", fractionalSecondDigits).
  496. MUST(number_format_options3->create_data_property_or_throw(vm.names.minimumIntegerDigits, Value(*fractional_second_digits)));
  497. // c. Perform ! CreateDataPropertyOrThrow(nf3Options, "useGrouping", false).
  498. MUST(number_format_options3->create_data_property_or_throw(vm.names.useGrouping, Value(false)));
  499. // d. Let nf3 be ? Construct(%NumberFormat%, « locale, nf3Options »).
  500. number_format3 = TRY(construct_number_format(number_format_options3));
  501. }
  502. // 13. Let tm be ToLocalTime(ℤ(ℝ(x) × 10^6), dateTimeFormat.[[Calendar]], dateTimeFormat.[[TimeZone]]).
  503. auto time_bigint = Crypto::SignedBigInteger { time }.multiplied_by(s_one_million_bigint);
  504. auto local_time = TRY(to_local_time(vm, time_bigint, date_time_format.calendar(), date_time_format.time_zone()));
  505. // 14. Let result be a new empty List.
  506. Vector<PatternPartition> result;
  507. // 15. For each Record { [[Type]], [[Value]] } patternPart in patternParts, do
  508. for (auto& pattern_part : pattern_parts) {
  509. // a. Let p be patternPart.[[Type]].
  510. auto part = pattern_part.type;
  511. // b. If p is "literal", then
  512. if (part == "literal"sv) {
  513. // i. Append a new Record { [[Type]]: "literal", [[Value]]: patternPart.[[Value]] } as the last element of the list result.
  514. result.append({ "literal"sv, move(pattern_part.value) });
  515. }
  516. // c. Else if p is equal to "fractionalSecondDigits", then
  517. else if (part == "fractionalSecondDigits"sv) {
  518. // i. Let v be tm.[[Millisecond]].
  519. auto value = local_time.millisecond;
  520. // ii. Let v be floor(v × 10^(fractionalSecondDigits - 3)).
  521. value = floor(value * pow(10, static_cast<int>(*fractional_second_digits) - 3));
  522. // iii. Let fv be FormatNumeric(nf3, v).
  523. auto formatted_value = MUST_OR_THROW_OOM(format_numeric(vm, *number_format3, Value(value)));
  524. // iv. Append a new Record { [[Type]]: "fractionalSecond", [[Value]]: fv } as the last element of result.
  525. result.append({ "fractionalSecond"sv, move(formatted_value) });
  526. }
  527. // d. Else if p is equal to "dayPeriod", then
  528. else if (part == "dayPeriod"sv) {
  529. String formatted_value;
  530. // i. Let f be the value of dateTimeFormat's internal slot whose name is the Internal Slot column of the matching row.
  531. auto style = date_time_format.day_period();
  532. // ii. Let fv be a String value representing the day period of tm in the form given by f; the String value depends upon the implementation and the effective locale of dateTimeFormat.
  533. auto symbol = MUST_OR_THROW_OOM(resolve_day_period(vm, data_locale, date_time_format.calendar(), style, pattern_parts, local_time));
  534. if (symbol.has_value())
  535. formatted_value = TRY_OR_THROW_OOM(vm, String::from_utf8(*symbol));
  536. // iii. Append a new Record { [[Type]]: p, [[Value]]: fv } as the last element of the list result.
  537. result.append({ "dayPeriod"sv, move(formatted_value) });
  538. }
  539. // e. Else if p is equal to "timeZoneName", then
  540. else if (part == "timeZoneName"sv) {
  541. // i. Let f be dateTimeFormat.[[TimeZoneName]].
  542. auto style = date_time_format.time_zone_name();
  543. // ii. Let v be dateTimeFormat.[[TimeZone]].
  544. auto const& value = date_time_format.time_zone();
  545. // iii. Let fv be a String value representing v in the form given by f; the String value depends upon the implementation and the effective locale of dateTimeFormat.
  546. // The String value may also depend on the value of the [[InDST]] field of tm if f is "short", "long", "shortOffset", or "longOffset".
  547. // If the implementation does not have a localized representation of f, then use the String value of v itself.
  548. auto formatted_value = TRY_OR_THROW_OOM(vm, ::Locale::format_time_zone(data_locale, value, style, local_time.time_since_epoch()));
  549. // iv. Append a new Record { [[Type]]: p, [[Value]]: fv } as the last element of the list result.
  550. result.append({ "timeZoneName"sv, move(formatted_value) });
  551. }
  552. // f. Else if p matches a Property column of the row in Table 6, then
  553. else if (auto style_and_value = find_calendar_field(part, date_time_format, range_format_options, local_time); style_and_value.has_value()) {
  554. String formatted_value;
  555. // i. If rangeFormatOptions is not undefined, let f be the value of rangeFormatOptions's field whose name matches p.
  556. // ii. Else, let f be the value of dateTimeFormat's internal slot whose name is the Internal Slot column of the matching row.
  557. // NOTE: find_calendar_field handles resolving rangeFormatOptions and dateTimeFormat fields.
  558. auto style = style_and_value->style;
  559. // iii. Let v be the value of tm's field whose name is the Internal Slot column of the matching row.
  560. auto value = style_and_value->value;
  561. // iv. If p is "year" and v ≤ 0, let v be 1 - v.
  562. if ((part == "year"sv) && (value <= 0))
  563. value = 1 - value;
  564. // v. If p is "month", increase v by 1.
  565. if (part == "month"sv)
  566. ++value;
  567. if (part == "hour"sv) {
  568. auto hour_cycle = date_time_format.hour_cycle();
  569. // vi. If p is "hour" and dateTimeFormat.[[HourCycle]] is "h11" or "h12", then
  570. if ((hour_cycle == ::Locale::HourCycle::H11) || (hour_cycle == ::Locale::HourCycle::H12)) {
  571. // 1. Let v be v modulo 12.
  572. value = value % 12;
  573. // 2. If v is 0 and dateTimeFormat.[[HourCycle]] is "h12", let v be 12.
  574. if ((value == 0) && (hour_cycle == ::Locale::HourCycle::H12))
  575. value = 12;
  576. }
  577. // vii. If p is "hour" and dateTimeFormat.[[HourCycle]] is "h24", then
  578. if (hour_cycle == ::Locale::HourCycle::H24) {
  579. // 1. If v is 0, let v be 24.
  580. if (value == 0)
  581. value = 24;
  582. }
  583. }
  584. switch (style) {
  585. // viii. If f is "numeric", then
  586. case ::Locale::CalendarPatternStyle::Numeric:
  587. // 1. Let fv be FormatNumeric(nf, v).
  588. formatted_value = MUST_OR_THROW_OOM(format_numeric(vm, *number_format, Value(value)));
  589. break;
  590. // ix. Else if f is "2-digit", then
  591. case ::Locale::CalendarPatternStyle::TwoDigit:
  592. // 1. Let fv be FormatNumeric(nf2, v).
  593. formatted_value = MUST_OR_THROW_OOM(format_numeric(vm, *number_format2, Value(value)));
  594. // 2. If the "length" property of fv is greater than 2, let fv be the substring of fv containing the last two characters.
  595. // NOTE: The first length check here isn't enough, but lets us avoid UTF-16 transcoding when the formatted value is ASCII.
  596. if (formatted_value.bytes_as_string_view().length() > 2) {
  597. auto utf16_formatted_value = TRY(Utf16String::create(vm, formatted_value));
  598. if (utf16_formatted_value.length_in_code_units() > 2)
  599. formatted_value = TRY_OR_THROW_OOM(vm, utf16_formatted_value.substring_view(utf16_formatted_value.length_in_code_units() - 2).to_utf8());
  600. }
  601. break;
  602. // x. Else if f is "narrow", "short", or "long", then let fv be a String value representing v in the form given by f; the String value depends upon the implementation and the effective locale and calendar of dateTimeFormat.
  603. // If p is "month" and rangeFormatOptions is undefined, then the String value may also depend on whether dateTimeFormat.[[Day]] is undefined.
  604. // If p is "month" and rangeFormatOptions is not undefined, then the String value may also depend on whether rangeFormatOptions.[[day]] is undefined.
  605. // If p is "era" and rangeFormatOptions is undefined, then the String value may also depend on whether dateTimeFormat.[[Era]] is undefined.
  606. // If p is "era" and rangeFormatOptions is not undefined, then the String value may also depend on whether rangeFormatOptions.[[era]] is undefined.
  607. // If the implementation does not have a localized representation of f, then use the String value of v itself.
  608. case ::Locale::CalendarPatternStyle::Narrow:
  609. case ::Locale::CalendarPatternStyle::Short:
  610. case ::Locale::CalendarPatternStyle::Long: {
  611. Optional<StringView> symbol;
  612. if (part == "era"sv)
  613. symbol = TRY_OR_THROW_OOM(vm, ::Locale::get_calendar_era_symbol(data_locale, date_time_format.calendar(), style, static_cast<::Locale::Era>(value)));
  614. else if (part == "month"sv)
  615. symbol = TRY_OR_THROW_OOM(vm, ::Locale::get_calendar_month_symbol(data_locale, date_time_format.calendar(), style, static_cast<::Locale::Month>(value - 1)));
  616. else if (part == "weekday"sv)
  617. symbol = TRY_OR_THROW_OOM(vm, ::Locale::get_calendar_weekday_symbol(data_locale, date_time_format.calendar(), style, static_cast<::Locale::Weekday>(value)));
  618. if (symbol.has_value())
  619. formatted_value = TRY_OR_THROW_OOM(vm, String::from_utf8(*symbol));
  620. else
  621. formatted_value = TRY_OR_THROW_OOM(vm, String::number(value));
  622. break;
  623. }
  624. default:
  625. VERIFY_NOT_REACHED();
  626. }
  627. // xi. Append a new Record { [[Type]]: p, [[Value]]: fv } as the last element of the list result.
  628. result.append({ style_and_value->name, move(formatted_value) });
  629. }
  630. // g. Else if p is equal to "ampm", then
  631. else if (part == "ampm"sv) {
  632. String formatted_value;
  633. // i. Let v be tm.[[Hour]].
  634. auto value = local_time.hour;
  635. // ii. If v is greater than 11, then
  636. if (value > 11) {
  637. // 1. Let fv be an implementation and locale dependent String value representing "post meridiem".
  638. auto symbol = TRY_OR_THROW_OOM(vm, ::Locale::get_calendar_day_period_symbol(data_locale, date_time_format.calendar(), ::Locale::CalendarPatternStyle::Short, ::Locale::DayPeriod::PM));
  639. formatted_value = TRY_OR_THROW_OOM(vm, String::from_utf8(symbol.value_or("PM"sv)));
  640. }
  641. // iii. Else,
  642. else {
  643. // 1. Let fv be an implementation and locale dependent String value representing "ante meridiem".
  644. auto symbol = TRY_OR_THROW_OOM(vm, ::Locale::get_calendar_day_period_symbol(data_locale, date_time_format.calendar(), ::Locale::CalendarPatternStyle::Short, ::Locale::DayPeriod::AM));
  645. formatted_value = TRY_OR_THROW_OOM(vm, String::from_utf8(symbol.value_or("AM"sv)));
  646. }
  647. // iv. Append a new Record { [[Type]]: "dayPeriod", [[Value]]: fv } as the last element of the list result.
  648. result.append({ "dayPeriod"sv, move(formatted_value) });
  649. }
  650. // h. Else if p is equal to "relatedYear", then
  651. else if (part == "relatedYear"sv) {
  652. // i. Let v be tm.[[RelatedYear]].
  653. // ii. Let fv be FormatNumeric(nf, v).
  654. // iii. Append a new Record { [[Type]]: "relatedYear", [[Value]]: fv } as the last element of the list result.
  655. // FIXME: Implement this when relatedYear is supported.
  656. }
  657. // i. Else if p is equal to "yearName", then
  658. else if (part == "yearName"sv) {
  659. // i. Let v be tm.[[YearName]].
  660. // ii. Let fv be an implementation and locale dependent String value representing v.
  661. // iii. Append a new Record { [[Type]]: "yearName", [[Value]]: fv } as the last element of the list result.
  662. // FIXME: Implement this when yearName is supported.
  663. }
  664. // Non-standard, TR-35 requires the decimal separator before injected {fractionalSecondDigits} partitions
  665. // to adhere to the selected locale. This depends on other generated data, so it is deferred to here.
  666. else if (part == "decimal"sv) {
  667. auto decimal_symbol = TRY_OR_THROW_OOM(vm, ::Locale::get_number_system_symbol(data_locale, date_time_format.numbering_system(), ::Locale::NumericSymbol::Decimal)).value_or("."sv);
  668. result.append({ "literal"sv, TRY_OR_THROW_OOM(vm, String::from_utf8(decimal_symbol)) });
  669. }
  670. // j. Else,
  671. else {
  672. // i. Let unknown be an implementation-, locale-, and numbering system-dependent String based on x and p.
  673. // ii. Append a new Record { [[Type]]: "unknown", [[Value]]: unknown } as the last element of result.
  674. // LibUnicode doesn't generate any "unknown" patterns.
  675. VERIFY_NOT_REACHED();
  676. }
  677. }
  678. // 16. Return result.
  679. return result;
  680. }
  681. // 11.5.7 PartitionDateTimePattern ( dateTimeFormat, x ), https://tc39.es/ecma402/#sec-partitiondatetimepattern
  682. ThrowCompletionOr<Vector<PatternPartition>> partition_date_time_pattern(VM& vm, DateTimeFormat& date_time_format, double time)
  683. {
  684. // 1. Let patternParts be PartitionPattern(dateTimeFormat.[[Pattern]]).
  685. auto pattern_parts = MUST_OR_THROW_OOM(partition_pattern(vm, date_time_format.pattern()));
  686. // 2. Let result be ? FormatDateTimePattern(dateTimeFormat, patternParts, x, undefined).
  687. auto result = TRY(format_date_time_pattern(vm, date_time_format, move(pattern_parts), time, nullptr));
  688. // 3. Return result.
  689. return result;
  690. }
  691. // 11.5.8 FormatDateTime ( dateTimeFormat, x ), https://tc39.es/ecma402/#sec-formatdatetime
  692. ThrowCompletionOr<String> format_date_time(VM& vm, DateTimeFormat& date_time_format, double time)
  693. {
  694. // 1. Let parts be ? PartitionDateTimePattern(dateTimeFormat, x).
  695. auto parts = TRY(partition_date_time_pattern(vm, date_time_format, time));
  696. // 2. Let result be the empty String.
  697. ThrowableStringBuilder result(vm);
  698. // 3. For each Record { [[Type]], [[Value]] } part in parts, do
  699. for (auto& part : parts) {
  700. // a. Set result to the string-concatenation of result and part.[[Value]].
  701. TRY(result.append(part.value));
  702. }
  703. // 4. Return result.
  704. return result.to_string();
  705. }
  706. // 11.5.9 FormatDateTimeToParts ( dateTimeFormat, x ), https://tc39.es/ecma402/#sec-formatdatetimetoparts
  707. ThrowCompletionOr<Array*> format_date_time_to_parts(VM& vm, DateTimeFormat& date_time_format, double time)
  708. {
  709. auto& realm = *vm.current_realm();
  710. // 1. Let parts be ? PartitionDateTimePattern(dateTimeFormat, x).
  711. auto parts = TRY(partition_date_time_pattern(vm, date_time_format, time));
  712. // 2. Let result be ! ArrayCreate(0).
  713. auto result = MUST(Array::create(realm, 0));
  714. // 3. Let n be 0.
  715. size_t n = 0;
  716. // 4. For each Record { [[Type]], [[Value]] } part in parts, do
  717. for (auto& part : parts) {
  718. // a. Let O be OrdinaryObjectCreate(%Object.prototype%).
  719. auto object = Object::create(realm, realm.intrinsics().object_prototype());
  720. // b. Perform ! CreateDataPropertyOrThrow(O, "type", part.[[Type]]).
  721. MUST(object->create_data_property_or_throw(vm.names.type, PrimitiveString::create(vm, part.type)));
  722. // c. Perform ! CreateDataPropertyOrThrow(O, "value", part.[[Value]]).
  723. MUST(object->create_data_property_or_throw(vm.names.value, PrimitiveString::create(vm, move(part.value))));
  724. // d. Perform ! CreateDataProperty(result, ! ToString(n), O).
  725. MUST(result->create_data_property_or_throw(n, object));
  726. // e. Increment n by 1.
  727. ++n;
  728. }
  729. // 5. Return result.
  730. return result.ptr();
  731. }
  732. template<typename Callback>
  733. ThrowCompletionOr<void> for_each_range_pattern_field(LocalTime const& time1, LocalTime const& time2, Callback&& callback)
  734. {
  735. // Table 4: Range pattern fields, https://tc39.es/ecma402/#table-datetimeformat-rangepatternfields
  736. if (TRY(callback(static_cast<u8>(time1.era), static_cast<u8>(time2.era), ::Locale::CalendarRangePattern::Field::Era)) == IterationDecision::Break)
  737. return {};
  738. if (TRY(callback(time1.year, time2.year, ::Locale::CalendarRangePattern::Field::Year)) == IterationDecision::Break)
  739. return {};
  740. if (TRY(callback(time1.month, time2.month, ::Locale::CalendarRangePattern::Field::Month)) == IterationDecision::Break)
  741. return {};
  742. if (TRY(callback(time1.day, time2.day, ::Locale::CalendarRangePattern::Field::Day)) == IterationDecision::Break)
  743. return {};
  744. if (TRY(callback(time1.hour, time2.hour, ::Locale::CalendarRangePattern::Field::AmPm)) == IterationDecision::Break)
  745. return {};
  746. if (TRY(callback(time1.hour, time2.hour, ::Locale::CalendarRangePattern::Field::DayPeriod)) == IterationDecision::Break)
  747. return {};
  748. if (TRY(callback(time1.hour, time2.hour, ::Locale::CalendarRangePattern::Field::Hour)) == IterationDecision::Break)
  749. return {};
  750. if (TRY(callback(time1.minute, time2.minute, ::Locale::CalendarRangePattern::Field::Minute)) == IterationDecision::Break)
  751. return {};
  752. if (TRY(callback(time1.second, time2.second, ::Locale::CalendarRangePattern::Field::Second)) == IterationDecision::Break)
  753. return {};
  754. if (TRY(callback(time1.millisecond, time2.millisecond, ::Locale::CalendarRangePattern::Field::FractionalSecondDigits)) == IterationDecision::Break)
  755. return {};
  756. return {};
  757. }
  758. template<typename Callback>
  759. ThrowCompletionOr<void> for_each_range_pattern_with_source(::Locale::CalendarRangePattern& pattern, Callback&& callback)
  760. {
  761. TRY(callback(pattern.start_range, "startRange"sv));
  762. TRY(callback(pattern.separator, "shared"sv));
  763. TRY(callback(pattern.end_range, "endRange"sv));
  764. return {};
  765. }
  766. // 11.5.10 PartitionDateTimeRangePattern ( dateTimeFormat, x, y ), https://tc39.es/ecma402/#sec-partitiondatetimerangepattern
  767. ThrowCompletionOr<Vector<PatternPartitionWithSource>> partition_date_time_range_pattern(VM& vm, DateTimeFormat& date_time_format, double start, double end)
  768. {
  769. // 1. Let x be TimeClip(x).
  770. start = time_clip(start);
  771. // 2. If x is NaN, throw a RangeError exception.
  772. if (isnan(start))
  773. return vm.throw_completion<RangeError>(ErrorType::IntlInvalidTime);
  774. // 3. Let y be TimeClip(y).
  775. end = time_clip(end);
  776. // 4. If y is NaN, throw a RangeError exception.
  777. if (isnan(end))
  778. return vm.throw_completion<RangeError>(ErrorType::IntlInvalidTime);
  779. // 5. Let tm1 be ToLocalTime(ℤ(ℝ(x) × 10^6), dateTimeFormat.[[Calendar]], dateTimeFormat.[[TimeZone]]).
  780. auto start_bigint = Crypto::SignedBigInteger { start }.multiplied_by(s_one_million_bigint);
  781. auto start_local_time = TRY(to_local_time(vm, start_bigint, date_time_format.calendar(), date_time_format.time_zone()));
  782. // 6. Let tm2 be ToLocalTime(ℤ(ℝ(y) × 10^6), dateTimeFormat.[[Calendar]], dateTimeFormat.[[TimeZone]]).
  783. auto end_bigint = Crypto::SignedBigInteger { end }.multiplied_by(s_one_million_bigint);
  784. auto end_local_time = TRY(to_local_time(vm, end_bigint, date_time_format.calendar(), date_time_format.time_zone()));
  785. // 7. Let rangePatterns be dateTimeFormat.[[RangePatterns]].
  786. auto range_patterns = date_time_format.range_patterns();
  787. // 8. Let rangePattern be undefined.
  788. Optional<::Locale::CalendarRangePattern> range_pattern;
  789. // 9. Let dateFieldsPracticallyEqual be true.
  790. bool date_fields_practically_equal = true;
  791. // 10. Let patternContainsLargerDateField be false.
  792. bool pattern_contains_larger_date_field = false;
  793. // 11. While dateFieldsPracticallyEqual is true and patternContainsLargerDateField is false, repeat for each row of Table 4 in order, except the header row:
  794. TRY(for_each_range_pattern_field(start_local_time, end_local_time, [&](auto start_value, auto end_value, auto field_name) -> ThrowCompletionOr<IterationDecision> {
  795. // a. Let fieldName be the name given in the Range Pattern Field column of the row.
  796. // b. If rangePatterns has a field [[<fieldName>]], let rp be rangePatterns.[[<fieldName>]]; else let rp be undefined.
  797. Optional<::Locale::CalendarRangePattern> pattern;
  798. for (auto const& range : range_patterns) {
  799. if (range.field == field_name) {
  800. pattern = range;
  801. break;
  802. }
  803. }
  804. // c. If rangePattern is not undefined and rp is undefined, then
  805. if (range_pattern.has_value() && !pattern.has_value()) {
  806. // i. Set patternContainsLargerDateField to true.
  807. pattern_contains_larger_date_field = true;
  808. }
  809. // d. Else,
  810. else {
  811. // i. Let rangePattern be rp.
  812. range_pattern = pattern;
  813. switch (field_name) {
  814. // ii. If fieldName is equal to [[AmPm]], then
  815. case ::Locale::CalendarRangePattern::Field::AmPm: {
  816. // 1. Let v1 be tm1.[[Hour]].
  817. // 2. Let v2 be tm2.[[Hour]].
  818. // 3. If v1 is greater than 11 and v2 less or equal than 11, or v1 is less or equal than 11 and v2 is greater than 11, then
  819. if ((start_value > 11 && end_value <= 11) || (start_value <= 11 && end_value > 11)) {
  820. // a. Set dateFieldsPracticallyEqual to false.
  821. date_fields_practically_equal = false;
  822. }
  823. break;
  824. }
  825. // iii. Else if fieldName is equal to [[DayPeriod]], then
  826. case ::Locale::CalendarRangePattern::Field::DayPeriod: {
  827. // 1. Let v1 be a String value representing the day period of tm1; the String value depends upon the implementation and the effective locale of dateTimeFormat.
  828. auto start_period = TRY_OR_THROW_OOM(vm, ::Locale::get_calendar_day_period_symbol_for_hour(date_time_format.data_locale(), date_time_format.calendar(), ::Locale::CalendarPatternStyle::Short, start_value));
  829. // 2. Let v2 be a String value representing the day period of tm2; the String value depends upon the implementation and the effective locale of dateTimeFormat.
  830. auto end_period = TRY_OR_THROW_OOM(vm, ::Locale::get_calendar_day_period_symbol_for_hour(date_time_format.data_locale(), date_time_format.calendar(), ::Locale::CalendarPatternStyle::Short, end_value));
  831. // 3. If v1 is not equal to v2, then
  832. if (start_period != end_period) {
  833. // a. Set dateFieldsPracticallyEqual to false.
  834. date_fields_practically_equal = false;
  835. }
  836. break;
  837. }
  838. // iv. Else if fieldName is equal to [[FractionalSecondDigits]], then
  839. case ::Locale::CalendarRangePattern::Field::FractionalSecondDigits: {
  840. // 1. Let fractionalSecondDigits be dateTimeFormat.[[FractionalSecondDigits]].
  841. Optional<u8> fractional_second_digits;
  842. if (date_time_format.has_fractional_second_digits())
  843. fractional_second_digits = date_time_format.fractional_second_digits();
  844. // 2. If fractionalSecondDigits is undefined, then
  845. if (!fractional_second_digits.has_value()) {
  846. // a. Set fractionalSecondDigits to 3.
  847. fractional_second_digits = 3;
  848. }
  849. // 3. Let v1 be tm1.[[Millisecond]].
  850. // 4. Let v2 be tm2.[[Millisecond]].
  851. // 5. Let v1 be floor(v1 × 10( fractionalSecondDigits - 3 )).
  852. start_value = floor(start_value * pow(10, static_cast<int>(*fractional_second_digits) - 3));
  853. // 6. Let v2 be floor(v2 × 10( fractionalSecondDigits - 3 )).
  854. end_value = floor(end_value * pow(10, static_cast<int>(*fractional_second_digits) - 3));
  855. // 7. If v1 is not equal to v2, then
  856. if (start_value != end_value) {
  857. // a. Set dateFieldsPracticallyEqual to false.
  858. date_fields_practically_equal = false;
  859. }
  860. break;
  861. }
  862. // v. Else,
  863. default: {
  864. // 1. Let v1 be tm1.[[<fieldName>]].
  865. // 2. Let v2 be tm2.[[<fieldName>]].
  866. // 3. If v1 is not equal to v2, then
  867. if (start_value != end_value) {
  868. // a. Set dateFieldsPracticallyEqual to false.
  869. date_fields_practically_equal = false;
  870. }
  871. break;
  872. }
  873. }
  874. }
  875. if (date_fields_practically_equal && !pattern_contains_larger_date_field)
  876. return IterationDecision::Continue;
  877. return IterationDecision::Break;
  878. }));
  879. // 12. If dateFieldsPracticallyEqual is true, then
  880. if (date_fields_practically_equal) {
  881. // a. Let pattern be dateTimeFormat.[[Pattern]].
  882. auto const& pattern = date_time_format.pattern();
  883. // b. Let patternParts be PartitionPattern(pattern).
  884. auto pattern_parts = MUST_OR_THROW_OOM(partition_pattern(vm, pattern));
  885. // c. Let result be ? FormatDateTimePattern(dateTimeFormat, patternParts, x, undefined).
  886. auto raw_result = TRY(format_date_time_pattern(vm, date_time_format, move(pattern_parts), start, nullptr));
  887. auto result = MUST_OR_THROW_OOM(PatternPartitionWithSource::create_from_parent_list(vm, move(raw_result)));
  888. // d. For each Record { [[Type]], [[Value]] } r in result, do
  889. for (auto& part : result) {
  890. // i. Set r.[[Source]] to "shared".
  891. part.source = "shared"sv;
  892. }
  893. // e. Return result.
  894. return result;
  895. }
  896. // 13. Let result be a new empty List.
  897. Vector<PatternPartitionWithSource> result;
  898. // 14. If rangePattern is undefined, then
  899. if (!range_pattern.has_value()) {
  900. // a. Let rangePattern be rangePatterns.[[Default]].
  901. range_pattern = TRY_OR_THROW_OOM(vm, ::Locale::get_calendar_default_range_format(date_time_format.data_locale(), date_time_format.calendar()));
  902. // Non-standard, range_pattern will be empty if Unicode data generation is disabled.
  903. if (!range_pattern.has_value())
  904. return result;
  905. // Non-standard, LibUnicode leaves the CLDR's {0} and {1} partitions in the default patterns
  906. // to be replaced at runtime with the DateTimeFormat object's pattern.
  907. auto const& pattern = date_time_format.pattern();
  908. if (range_pattern->start_range.contains("{0}"sv)) {
  909. range_pattern->start_range = TRY_OR_THROW_OOM(vm, range_pattern->start_range.replace("{0}"sv, pattern, ReplaceMode::FirstOnly));
  910. range_pattern->end_range = TRY_OR_THROW_OOM(vm, range_pattern->end_range.replace("{1}"sv, pattern, ReplaceMode::FirstOnly));
  911. } else {
  912. range_pattern->start_range = TRY_OR_THROW_OOM(vm, range_pattern->start_range.replace("{1}"sv, pattern, ReplaceMode::FirstOnly));
  913. range_pattern->end_range = TRY_OR_THROW_OOM(vm, range_pattern->end_range.replace("{0}"sv, pattern, ReplaceMode::FirstOnly));
  914. }
  915. // FIXME: The above is not sufficient. For example, if the start date is days before the end date, and only the timeStyle
  916. // option is provided, the resulting range will not include the differing dates. We will likely need to implement
  917. // step 3 here: https://unicode.org/reports/tr35/tr35-dates.html#intervalFormats
  918. }
  919. // 15. For each Record { [[Pattern]], [[Source]] } rangePatternPart in rangePattern.[[PatternParts]], do
  920. TRY(for_each_range_pattern_with_source(*range_pattern, [&](auto const& pattern, auto source) -> ThrowCompletionOr<void> {
  921. // a. Let pattern be rangePatternPart.[[Pattern]].
  922. // b. Let source be rangePatternPart.[[Source]].
  923. // c. If source is "startRange" or "shared", then
  924. // i. Let z be x.
  925. // d. Else,
  926. // i. Let z be y.
  927. auto time = ((source == "startRange") || (source == "shared")) ? start : end;
  928. // e. Let patternParts be PartitionPattern(pattern).
  929. auto pattern_parts = MUST_OR_THROW_OOM(partition_pattern(vm, pattern));
  930. // f. Let partResult be ? FormatDateTimePattern(dateTimeFormat, patternParts, z, rangePattern).
  931. auto raw_part_result = TRY(format_date_time_pattern(vm, date_time_format, move(pattern_parts), time, &range_pattern.value()));
  932. auto part_result = MUST_OR_THROW_OOM(PatternPartitionWithSource::create_from_parent_list(vm, move(raw_part_result)));
  933. // g. For each Record { [[Type]], [[Value]] } r in partResult, do
  934. for (auto& part : part_result) {
  935. // i. Set r.[[Source]] to source.
  936. part.source = source;
  937. }
  938. // h. Add all elements in partResult to result in order.
  939. result.extend(move(part_result));
  940. return {};
  941. }));
  942. // 16. Return result.
  943. return result;
  944. }
  945. // 11.5.11 FormatDateTimeRange ( dateTimeFormat, x, y ), https://tc39.es/ecma402/#sec-formatdatetimerange
  946. ThrowCompletionOr<String> format_date_time_range(VM& vm, DateTimeFormat& date_time_format, double start, double end)
  947. {
  948. // 1. Let parts be ? PartitionDateTimeRangePattern(dateTimeFormat, x, y).
  949. auto parts = TRY(partition_date_time_range_pattern(vm, date_time_format, start, end));
  950. // 2. Let result be the empty String.
  951. ThrowableStringBuilder result(vm);
  952. // 3. For each Record { [[Type]], [[Value]], [[Source]] } part in parts, do
  953. for (auto& part : parts) {
  954. // a. Set result to the string-concatenation of result and part.[[Value]].
  955. TRY(result.append(part.value));
  956. }
  957. // 4. Return result.
  958. return result.to_string();
  959. }
  960. // 11.5.12 FormatDateTimeRangeToParts ( dateTimeFormat, x, y ), https://tc39.es/ecma402/#sec-formatdatetimerangetoparts
  961. ThrowCompletionOr<Array*> format_date_time_range_to_parts(VM& vm, DateTimeFormat& date_time_format, double start, double end)
  962. {
  963. auto& realm = *vm.current_realm();
  964. // 1. Let parts be ? PartitionDateTimeRangePattern(dateTimeFormat, x, y).
  965. auto parts = TRY(partition_date_time_range_pattern(vm, date_time_format, start, end));
  966. // 2. Let result be ! ArrayCreate(0).
  967. auto result = MUST(Array::create(realm, 0));
  968. // 3. Let n be 0.
  969. size_t n = 0;
  970. // 4. For each Record { [[Type]], [[Value]], [[Source]] } part in parts, do
  971. for (auto& part : parts) {
  972. // a. Let O be OrdinaryObjectCreate(%ObjectPrototype%).
  973. auto object = Object::create(realm, realm.intrinsics().object_prototype());
  974. // b. Perform ! CreateDataPropertyOrThrow(O, "type", part.[[Type]]).
  975. MUST(object->create_data_property_or_throw(vm.names.type, PrimitiveString::create(vm, part.type)));
  976. // c. Perform ! CreateDataPropertyOrThrow(O, "value", part.[[Value]]).
  977. MUST(object->create_data_property_or_throw(vm.names.value, PrimitiveString::create(vm, move(part.value))));
  978. // d. Perform ! CreateDataPropertyOrThrow(O, "source", part.[[Source]]).
  979. MUST(object->create_data_property_or_throw(vm.names.source, PrimitiveString::create(vm, part.source)));
  980. // e. Perform ! CreateDataProperty(result, ! ToString(n), O).
  981. MUST(result->create_data_property_or_throw(n, object));
  982. // f. Increment n by 1.
  983. ++n;
  984. }
  985. // 5. Return result.
  986. return result.ptr();
  987. }
  988. // 11.5.13 ToLocalTime ( epochNs, calendar, timeZone ), https://tc39.es/ecma402/#sec-tolocaltime
  989. ThrowCompletionOr<LocalTime> to_local_time(VM& vm, Crypto::SignedBigInteger const& epoch_ns, StringView calendar, StringView time_zone)
  990. {
  991. // 1. Let offsetNs be GetNamedTimeZoneOffsetNanoseconds(timeZone, epochNs).
  992. auto offset_ns = get_named_time_zone_offset_nanoseconds(time_zone, epoch_ns);
  993. // NOTE: Unlike the spec, we still perform the below computations with BigInts until we are ready
  994. // to divide the number by 10^6. The spec expects an MV here. If we try to use i64, we will
  995. // overflow; if we try to use a double, we lose quite a bit of accuracy.
  996. // 2. Let tz be ℝ(epochNs) + offsetNs.
  997. auto zoned_time_ns = epoch_ns.plus(Crypto::SignedBigInteger { offset_ns });
  998. // 3. If calendar is "gregory", then
  999. if (calendar == "gregory"sv) {
  1000. auto zoned_time_ms = zoned_time_ns.divided_by(s_one_million_bigint).quotient;
  1001. auto zoned_time = floor(zoned_time_ms.to_double(Crypto::UnsignedBigInteger::RoundingMode::ECMAScriptNumberValueFor));
  1002. auto year = year_from_time(zoned_time);
  1003. // a. Return a record with fields calculated from tz according to Table 8.
  1004. return LocalTime {
  1005. // WeekDay(𝔽(floor(tz / 10^6)))
  1006. .weekday = week_day(zoned_time),
  1007. // Let year be YearFromTime(𝔽(floor(tz / 10^6))). If year < 1𝔽, return "BC", else return "AD".
  1008. .era = year < 1 ? ::Locale::Era::BC : ::Locale::Era::AD,
  1009. // YearFromTime(𝔽(floor(tz / 10^6)))
  1010. .year = year,
  1011. // undefined.
  1012. .related_year = js_undefined(),
  1013. // undefined.
  1014. .year_name = js_undefined(),
  1015. // MonthFromTime(𝔽(floor(tz / 10^6)))
  1016. .month = month_from_time(zoned_time),
  1017. // DateFromTime(𝔽(floor(tz / 10^6)))
  1018. .day = date_from_time(zoned_time),
  1019. // HourFromTime(𝔽(floor(tz / 10^6)))
  1020. .hour = hour_from_time(zoned_time),
  1021. // MinFromTime(𝔽(floor(tz / 10^6)))
  1022. .minute = min_from_time(zoned_time),
  1023. // SecFromTime(𝔽(floor(tz / 10^6)))
  1024. .second = sec_from_time(zoned_time),
  1025. // msFromTime(𝔽(floor(tz / 10^6)))
  1026. .millisecond = ms_from_time(zoned_time),
  1027. };
  1028. }
  1029. // 4. Else,
  1030. // a. Return a record with the fields of Column 1 of Table 8 calculated from tz for the given calendar. The calculations should use best available information about the specified calendar.
  1031. // FIXME: Implement this when non-Gregorian calendars are supported by LibUnicode.
  1032. return vm.throw_completion<InternalError>(ErrorType::NotImplemented, "Non-Gregorian calendars"sv);
  1033. }
  1034. }