DateTimeFormat.cpp 58 KB

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