DateTimeFormat.cpp 61 KB

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