DateTimeFormat.cpp 57 KB

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