DateTimeFormat.cpp 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181
  1. /*
  2. * Copyright (c) 2021-2023, Tim Flynn <trflynn89@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Find.h>
  7. #include <AK/IterationDecision.h>
  8. #include <AK/NumericLimits.h>
  9. #include <AK/Utf16View.h>
  10. #include <LibJS/Runtime/AbstractOperations.h>
  11. #include <LibJS/Runtime/Array.h>
  12. #include <LibJS/Runtime/Date.h>
  13. #include <LibJS/Runtime/Intl/DateTimeFormat.h>
  14. #include <LibJS/Runtime/Intl/NumberFormat.h>
  15. #include <LibJS/Runtime/Intl/NumberFormatConstructor.h>
  16. #include <LibJS/Runtime/NativeFunction.h>
  17. #include <LibJS/Runtime/ThrowableStringBuilder.h>
  18. #include <LibJS/Runtime/Utf16String.h>
  19. #include <LibLocale/Locale.h>
  20. #include <LibLocale/NumberFormat.h>
  21. #include <math.h>
  22. namespace JS::Intl {
  23. static Crypto::SignedBigInteger const s_one_million_bigint { 1'000'000 };
  24. // 11 DateTimeFormat Objects, https://tc39.es/ecma402/#datetimeformat-objects
  25. DateTimeFormat::DateTimeFormat(Object& prototype)
  26. : Object(ConstructWithPrototypeTag::Tag, prototype)
  27. {
  28. }
  29. void DateTimeFormat::visit_edges(Cell::Visitor& visitor)
  30. {
  31. Base::visit_edges(visitor);
  32. if (m_bound_format)
  33. visitor.visit(m_bound_format);
  34. }
  35. DateTimeFormat::Style DateTimeFormat::style_from_string(StringView style)
  36. {
  37. if (style == "full"sv)
  38. return Style::Full;
  39. if (style == "long"sv)
  40. return Style::Long;
  41. if (style == "medium"sv)
  42. return Style::Medium;
  43. if (style == "short"sv)
  44. return Style::Short;
  45. VERIFY_NOT_REACHED();
  46. }
  47. StringView DateTimeFormat::style_to_string(Style style)
  48. {
  49. switch (style) {
  50. case Style::Full:
  51. return "full"sv;
  52. case Style::Long:
  53. return "long"sv;
  54. case Style::Medium:
  55. return "medium"sv;
  56. case Style::Short:
  57. return "short"sv;
  58. default:
  59. VERIFY_NOT_REACHED();
  60. }
  61. }
  62. // 11.5.1 DateTimeStyleFormat ( dateStyle, timeStyle, styles ), https://tc39.es/ecma402/#sec-date-time-style-format
  63. ThrowCompletionOr<Optional<::Locale::CalendarPattern>> date_time_style_format(VM& vm, 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) -> ThrowCompletionOr<Optional<::Locale::CalendarPattern>> {
  68. auto formats = TRY_OR_THROW_OOM(vm, ::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 OptionalNone {};
  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 = MUST_OR_THROW_OOM(get_pattern(::Locale::CalendarFormatType::Time, date_time_format.time_style()));
  88. if (!pattern.has_value())
  89. return OptionalNone {};
  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 = MUST_OR_THROW_OOM(get_pattern(::Locale::CalendarFormatType::Date, date_time_format.date_style()));
  97. if (!pattern.has_value())
  98. return OptionalNone {};
  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 = MUST_OR_THROW_OOM(get_pattern(::Locale::CalendarFormatType::DateTime, date_time_format.date_style()));
  116. if (!connector.has_value())
  117. return OptionalNone {};
  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 = TRY_OR_THROW_OOM(vm, connector->pattern.replace("{0}"sv, time_format.pattern, ReplaceMode::FirstOnly));
  120. pattern = TRY_OR_THROW_OOM(vm, 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 = TRY_OR_THROW_OOM(vm, connector->pattern.replace("{0}"sv, *time_format.pattern12, ReplaceMode::FirstOnly));
  127. pattern12 = TRY_OR_THROW_OOM(vm, 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 = TRY_OR_THROW_OOM(vm, ::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 ThrowCompletionOr<Optional<StringView>> resolve_day_period(VM& vm, 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 = TRY_OR_THROW_OOM(vm, ::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 TRY_OR_THROW_OOM(vm, ::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. TRY_OR_THROW_OOM(vm, result.try_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 = MUST_OR_THROW_OOM(format_numeric(vm, *number_format3, Value(value)));
  454. // iv. Append a new Record { [[Type]]: "fractionalSecond", [[Value]]: fv } as the last element of result.
  455. TRY_OR_THROW_OOM(vm, result.try_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 = MUST_OR_THROW_OOM(resolve_day_period(vm, data_locale, date_time_format.calendar(), style, pattern_parts, local_time));
  464. if (symbol.has_value())
  465. formatted_value = TRY_OR_THROW_OOM(vm, String::from_utf8(*symbol));
  466. // iii. Append a new Record { [[Type]]: p, [[Value]]: fv } as the last element of the list result.
  467. TRY_OR_THROW_OOM(vm, result.try_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 = TRY_OR_THROW_OOM(vm, ::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. TRY_OR_THROW_OOM(vm, result.try_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 = MUST_OR_THROW_OOM(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 = MUST_OR_THROW_OOM(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 = TRY_OR_THROW_OOM(vm, 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 = TRY_OR_THROW_OOM(vm, ::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 = TRY_OR_THROW_OOM(vm, ::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 = TRY_OR_THROW_OOM(vm, ::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 = TRY_OR_THROW_OOM(vm, String::from_utf8(*symbol));
  550. else
  551. formatted_value = TRY_OR_THROW_OOM(vm, 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. TRY_OR_THROW_OOM(vm, result.try_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 = TRY_OR_THROW_OOM(vm, ::Locale::get_calendar_day_period_symbol(data_locale, date_time_format.calendar(), ::Locale::CalendarPatternStyle::Short, ::Locale::DayPeriod::PM));
  569. formatted_value = TRY_OR_THROW_OOM(vm, 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 = TRY_OR_THROW_OOM(vm, ::Locale::get_calendar_day_period_symbol(data_locale, date_time_format.calendar(), ::Locale::CalendarPatternStyle::Short, ::Locale::DayPeriod::AM));
  575. formatted_value = TRY_OR_THROW_OOM(vm, 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. TRY_OR_THROW_OOM(vm, result.try_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. TRY_OR_THROW_OOM(vm, result.try_append({ "literal"sv, TRY_OR_THROW_OOM(vm, 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 = MUST_OR_THROW_OOM(partition_pattern(vm, 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. ThrowableStringBuilder result(vm);
  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. TRY(result.append(part.value));
  632. }
  633. // 4. Return result.
  634. return result.to_string();
  635. }
  636. // 11.5.8 FormatDateTimeToParts ( dateTimeFormat, x ), https://tc39.es/ecma402/#sec-formatdatetimetoparts
  637. ThrowCompletionOr<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.ptr();
  661. }
  662. template<typename Callback>
  663. ThrowCompletionOr<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 (TRY(callback(static_cast<u8>(time1.era), static_cast<u8>(time2.era), ::Locale::CalendarRangePattern::Field::Era)) == IterationDecision::Break)
  667. return {};
  668. if (TRY(callback(time1.year, time2.year, ::Locale::CalendarRangePattern::Field::Year)) == IterationDecision::Break)
  669. return {};
  670. if (TRY(callback(time1.month, time2.month, ::Locale::CalendarRangePattern::Field::Month)) == IterationDecision::Break)
  671. return {};
  672. if (TRY(callback(time1.day, time2.day, ::Locale::CalendarRangePattern::Field::Day)) == IterationDecision::Break)
  673. return {};
  674. if (TRY(callback(time1.hour, time2.hour, ::Locale::CalendarRangePattern::Field::AmPm)) == IterationDecision::Break)
  675. return {};
  676. if (TRY(callback(time1.hour, time2.hour, ::Locale::CalendarRangePattern::Field::DayPeriod)) == IterationDecision::Break)
  677. return {};
  678. if (TRY(callback(time1.hour, time2.hour, ::Locale::CalendarRangePattern::Field::Hour)) == IterationDecision::Break)
  679. return {};
  680. if (TRY(callback(time1.minute, time2.minute, ::Locale::CalendarRangePattern::Field::Minute)) == IterationDecision::Break)
  681. return {};
  682. if (TRY(callback(time1.second, time2.second, ::Locale::CalendarRangePattern::Field::Second)) == IterationDecision::Break)
  683. return {};
  684. if (TRY(callback(time1.millisecond, time2.millisecond, ::Locale::CalendarRangePattern::Field::FractionalSecondDigits)) == IterationDecision::Break)
  685. return {};
  686. return {};
  687. }
  688. template<typename Callback>
  689. ThrowCompletionOr<void> for_each_range_pattern_with_source(::Locale::CalendarRangePattern& pattern, Callback&& callback)
  690. {
  691. TRY(callback(pattern.start_range, "startRange"sv));
  692. TRY(callback(pattern.separator, "shared"sv));
  693. TRY(callback(pattern.end_range, "endRange"sv));
  694. return {};
  695. }
  696. // 11.5.9 PartitionDateTimeRangePattern ( dateTimeFormat, x, y ), https://tc39.es/ecma402/#sec-partitiondatetimerangepattern
  697. ThrowCompletionOr<Vector<PatternPartitionWithSource>> partition_date_time_range_pattern(VM& vm, DateTimeFormat& date_time_format, double start, double end)
  698. {
  699. // 1. Let x be TimeClip(x).
  700. start = time_clip(start);
  701. // 2. If x is NaN, throw a RangeError exception.
  702. if (isnan(start))
  703. return vm.throw_completion<RangeError>(ErrorType::IntlInvalidTime);
  704. // 3. Let y be TimeClip(y).
  705. end = time_clip(end);
  706. // 4. If y is NaN, throw a RangeError exception.
  707. if (isnan(end))
  708. return vm.throw_completion<RangeError>(ErrorType::IntlInvalidTime);
  709. // 5. Let tm1 be ToLocalTime(ℤ(ℝ(x) × 10^6), dateTimeFormat.[[Calendar]], dateTimeFormat.[[TimeZone]]).
  710. auto start_bigint = Crypto::SignedBigInteger { start }.multiplied_by(s_one_million_bigint);
  711. auto start_local_time = TRY(to_local_time(vm, start_bigint, date_time_format.calendar(), date_time_format.time_zone()));
  712. // 6. Let tm2 be ToLocalTime(ℤ(ℝ(y) × 10^6), dateTimeFormat.[[Calendar]], dateTimeFormat.[[TimeZone]]).
  713. auto end_bigint = Crypto::SignedBigInteger { end }.multiplied_by(s_one_million_bigint);
  714. auto end_local_time = TRY(to_local_time(vm, end_bigint, date_time_format.calendar(), date_time_format.time_zone()));
  715. // 7. Let rangePatterns be dateTimeFormat.[[RangePatterns]].
  716. auto range_patterns = date_time_format.range_patterns();
  717. // 8. Let rangePattern be undefined.
  718. Optional<::Locale::CalendarRangePattern> range_pattern;
  719. // 9. Let dateFieldsPracticallyEqual be true.
  720. bool date_fields_practically_equal = true;
  721. // 10. Let patternContainsLargerDateField be false.
  722. bool pattern_contains_larger_date_field = false;
  723. // 11. While dateFieldsPracticallyEqual is true and patternContainsLargerDateField is false, repeat for each row of Table 4 in order, except the header row:
  724. TRY(for_each_range_pattern_field(start_local_time, end_local_time, [&](auto start_value, auto end_value, auto field_name) -> ThrowCompletionOr<IterationDecision> {
  725. // a. Let fieldName be the name given in the Range Pattern Field column of the row.
  726. // b. If rangePatterns has a field [[<fieldName>]], let rp be rangePatterns.[[<fieldName>]]; else let rp be undefined.
  727. Optional<::Locale::CalendarRangePattern> pattern;
  728. for (auto const& range : range_patterns) {
  729. if (range.field == field_name) {
  730. pattern = range;
  731. break;
  732. }
  733. }
  734. // c. If rangePattern is not undefined and rp is undefined, then
  735. if (range_pattern.has_value() && !pattern.has_value()) {
  736. // i. Set patternContainsLargerDateField to true.
  737. pattern_contains_larger_date_field = true;
  738. }
  739. // d. Else,
  740. else {
  741. // i. Let rangePattern be rp.
  742. range_pattern = pattern;
  743. switch (field_name) {
  744. // ii. If fieldName is equal to [[AmPm]], then
  745. case ::Locale::CalendarRangePattern::Field::AmPm: {
  746. // 1. Let v1 be tm1.[[Hour]].
  747. // 2. Let v2 be tm2.[[Hour]].
  748. // 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
  749. if ((start_value > 11 && end_value <= 11) || (start_value <= 11 && end_value > 11)) {
  750. // a. Set dateFieldsPracticallyEqual to false.
  751. date_fields_practically_equal = false;
  752. }
  753. break;
  754. }
  755. // iii. Else if fieldName is equal to [[DayPeriod]], then
  756. case ::Locale::CalendarRangePattern::Field::DayPeriod: {
  757. // 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.
  758. auto start_period = TRY_OR_THROW_OOM(vm, ::Locale::get_calendar_day_period_symbol_for_hour(date_time_format.data_locale(), date_time_format.calendar(), ::Locale::CalendarPatternStyle::Short, start_value));
  759. // 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.
  760. auto end_period = TRY_OR_THROW_OOM(vm, ::Locale::get_calendar_day_period_symbol_for_hour(date_time_format.data_locale(), date_time_format.calendar(), ::Locale::CalendarPatternStyle::Short, end_value));
  761. // 3. If v1 is not equal to v2, then
  762. if (start_period != end_period) {
  763. // a. Set dateFieldsPracticallyEqual to false.
  764. date_fields_practically_equal = false;
  765. }
  766. break;
  767. }
  768. // iv. Else if fieldName is equal to [[FractionalSecondDigits]], then
  769. case ::Locale::CalendarRangePattern::Field::FractionalSecondDigits: {
  770. // 1. Let fractionalSecondDigits be dateTimeFormat.[[FractionalSecondDigits]].
  771. Optional<u8> fractional_second_digits;
  772. if (date_time_format.has_fractional_second_digits())
  773. fractional_second_digits = date_time_format.fractional_second_digits();
  774. // 2. If fractionalSecondDigits is undefined, then
  775. if (!fractional_second_digits.has_value()) {
  776. // a. Set fractionalSecondDigits to 3.
  777. fractional_second_digits = 3;
  778. }
  779. // 3. Let v1 be tm1.[[Millisecond]].
  780. // 4. Let v2 be tm2.[[Millisecond]].
  781. // 5. Let v1 be floor(v1 × 10( fractionalSecondDigits - 3 )).
  782. start_value = floor(start_value * pow(10, static_cast<int>(*fractional_second_digits) - 3));
  783. // 6. Let v2 be floor(v2 × 10( fractionalSecondDigits - 3 )).
  784. end_value = floor(end_value * pow(10, static_cast<int>(*fractional_second_digits) - 3));
  785. // 7. If v1 is not equal to v2, then
  786. if (start_value != end_value) {
  787. // a. Set dateFieldsPracticallyEqual to false.
  788. date_fields_practically_equal = false;
  789. }
  790. break;
  791. }
  792. // v. Else,
  793. default: {
  794. // 1. Let v1 be tm1.[[<fieldName>]].
  795. // 2. Let v2 be tm2.[[<fieldName>]].
  796. // 3. If v1 is not equal to v2, then
  797. if (start_value != end_value) {
  798. // a. Set dateFieldsPracticallyEqual to false.
  799. date_fields_practically_equal = false;
  800. }
  801. break;
  802. }
  803. }
  804. }
  805. if (date_fields_practically_equal && !pattern_contains_larger_date_field)
  806. return IterationDecision::Continue;
  807. return IterationDecision::Break;
  808. }));
  809. // 12. If dateFieldsPracticallyEqual is true, then
  810. if (date_fields_practically_equal) {
  811. // a. Let pattern be dateTimeFormat.[[Pattern]].
  812. auto const& pattern = date_time_format.pattern();
  813. // b. Let patternParts be PartitionPattern(pattern).
  814. auto pattern_parts = MUST_OR_THROW_OOM(partition_pattern(vm, pattern));
  815. // c. Let result be ? FormatDateTimePattern(dateTimeFormat, patternParts, x, undefined).
  816. auto raw_result = TRY(format_date_time_pattern(vm, date_time_format, move(pattern_parts), start, nullptr));
  817. auto result = MUST_OR_THROW_OOM(PatternPartitionWithSource::create_from_parent_list(vm, move(raw_result)));
  818. // d. For each Record { [[Type]], [[Value]] } r in result, do
  819. for (auto& part : result) {
  820. // i. Set r.[[Source]] to "shared".
  821. part.source = "shared"sv;
  822. }
  823. // e. Return result.
  824. return result;
  825. }
  826. // 13. Let result be a new empty List.
  827. Vector<PatternPartitionWithSource> result;
  828. // 14. If rangePattern is undefined, then
  829. if (!range_pattern.has_value()) {
  830. // a. Let rangePattern be rangePatterns.[[Default]].
  831. range_pattern = TRY_OR_THROW_OOM(vm, ::Locale::get_calendar_default_range_format(date_time_format.data_locale(), date_time_format.calendar()));
  832. // Non-standard, range_pattern will be empty if Unicode data generation is disabled.
  833. if (!range_pattern.has_value())
  834. return result;
  835. // Non-standard, LibUnicode leaves the CLDR's {0} and {1} partitions in the default patterns
  836. // to be replaced at runtime with the DateTimeFormat object's pattern.
  837. auto const& pattern = date_time_format.pattern();
  838. if (range_pattern->start_range.contains("{0}"sv)) {
  839. range_pattern->start_range = TRY_OR_THROW_OOM(vm, range_pattern->start_range.replace("{0}"sv, pattern, ReplaceMode::FirstOnly));
  840. range_pattern->end_range = TRY_OR_THROW_OOM(vm, range_pattern->end_range.replace("{1}"sv, pattern, ReplaceMode::FirstOnly));
  841. } else {
  842. range_pattern->start_range = TRY_OR_THROW_OOM(vm, range_pattern->start_range.replace("{1}"sv, pattern, ReplaceMode::FirstOnly));
  843. range_pattern->end_range = TRY_OR_THROW_OOM(vm, range_pattern->end_range.replace("{0}"sv, pattern, ReplaceMode::FirstOnly));
  844. }
  845. // FIXME: The above is not sufficient. For example, if the start date is days before the end date, and only the timeStyle
  846. // option is provided, the resulting range will not include the differing dates. We will likely need to implement
  847. // step 3 here: https://unicode.org/reports/tr35/tr35-dates.html#intervalFormats
  848. }
  849. // 15. For each Record { [[Pattern]], [[Source]] } rangePatternPart in rangePattern.[[PatternParts]], do
  850. TRY(for_each_range_pattern_with_source(*range_pattern, [&](auto const& pattern, auto source) -> ThrowCompletionOr<void> {
  851. // a. Let pattern be rangePatternPart.[[Pattern]].
  852. // b. Let source be rangePatternPart.[[Source]].
  853. // c. If source is "startRange" or "shared", then
  854. // i. Let z be x.
  855. // d. Else,
  856. // i. Let z be y.
  857. auto time = ((source == "startRange") || (source == "shared")) ? start : end;
  858. // e. Let patternParts be PartitionPattern(pattern).
  859. auto pattern_parts = MUST_OR_THROW_OOM(partition_pattern(vm, pattern));
  860. // f. Let partResult be ? FormatDateTimePattern(dateTimeFormat, patternParts, z, rangePattern).
  861. auto raw_part_result = TRY(format_date_time_pattern(vm, date_time_format, move(pattern_parts), time, &range_pattern.value()));
  862. auto part_result = MUST_OR_THROW_OOM(PatternPartitionWithSource::create_from_parent_list(vm, move(raw_part_result)));
  863. // g. For each Record { [[Type]], [[Value]] } r in partResult, do
  864. for (auto& part : part_result) {
  865. // i. Set r.[[Source]] to source.
  866. part.source = source;
  867. }
  868. // h. Add all elements in partResult to result in order.
  869. TRY_OR_THROW_OOM(vm, result.try_extend(move(part_result)));
  870. return {};
  871. }));
  872. // 16. Return result.
  873. return result;
  874. }
  875. // 11.5.10 FormatDateTimeRange ( dateTimeFormat, x, y ), https://tc39.es/ecma402/#sec-formatdatetimerange
  876. ThrowCompletionOr<String> format_date_time_range(VM& vm, DateTimeFormat& date_time_format, double start, double end)
  877. {
  878. // 1. Let parts be ? PartitionDateTimeRangePattern(dateTimeFormat, x, y).
  879. auto parts = TRY(partition_date_time_range_pattern(vm, date_time_format, start, end));
  880. // 2. Let result be the empty String.
  881. ThrowableStringBuilder result(vm);
  882. // 3. For each Record { [[Type]], [[Value]], [[Source]] } part in parts, do
  883. for (auto& part : parts) {
  884. // a. Set result to the string-concatenation of result and part.[[Value]].
  885. TRY(result.append(part.value));
  886. }
  887. // 4. Return result.
  888. return result.to_string();
  889. }
  890. // 11.5.11 FormatDateTimeRangeToParts ( dateTimeFormat, x, y ), https://tc39.es/ecma402/#sec-formatdatetimerangetoparts
  891. ThrowCompletionOr<Array*> format_date_time_range_to_parts(VM& vm, DateTimeFormat& date_time_format, double start, double end)
  892. {
  893. auto& realm = *vm.current_realm();
  894. // 1. Let parts be ? PartitionDateTimeRangePattern(dateTimeFormat, x, y).
  895. auto parts = TRY(partition_date_time_range_pattern(vm, date_time_format, start, end));
  896. // 2. Let result be ! ArrayCreate(0).
  897. auto result = MUST(Array::create(realm, 0));
  898. // 3. Let n be 0.
  899. size_t n = 0;
  900. // 4. For each Record { [[Type]], [[Value]], [[Source]] } part in parts, do
  901. for (auto& part : parts) {
  902. // a. Let O be OrdinaryObjectCreate(%ObjectPrototype%).
  903. auto object = Object::create(realm, realm.intrinsics().object_prototype());
  904. // b. Perform ! CreateDataPropertyOrThrow(O, "type", part.[[Type]]).
  905. MUST(object->create_data_property_or_throw(vm.names.type, PrimitiveString::create(vm, part.type)));
  906. // c. Perform ! CreateDataPropertyOrThrow(O, "value", part.[[Value]]).
  907. MUST(object->create_data_property_or_throw(vm.names.value, PrimitiveString::create(vm, move(part.value))));
  908. // d. Perform ! CreateDataPropertyOrThrow(O, "source", part.[[Source]]).
  909. MUST(object->create_data_property_or_throw(vm.names.source, PrimitiveString::create(vm, part.source)));
  910. // e. Perform ! CreateDataProperty(result, ! ToString(n), O).
  911. MUST(result->create_data_property_or_throw(n, object));
  912. // f. Increment n by 1.
  913. ++n;
  914. }
  915. // 5. Return result.
  916. return result.ptr();
  917. }
  918. // 11.5.12 ToLocalTime ( epochNs, calendar, timeZone ), https://tc39.es/ecma402/#sec-tolocaltime
  919. ThrowCompletionOr<LocalTime> to_local_time(VM& vm, Crypto::SignedBigInteger const& epoch_ns, StringView calendar, StringView time_zone)
  920. {
  921. // 1. Let offsetNs be GetNamedTimeZoneOffsetNanoseconds(timeZone, epochNs).
  922. auto offset_ns = get_named_time_zone_offset_nanoseconds(time_zone, epoch_ns);
  923. // NOTE: Unlike the spec, we still perform the below computations with BigInts until we are ready
  924. // to divide the number by 10^6. The spec expects an MV here. If we try to use i64, we will
  925. // overflow; if we try to use a double, we lose quite a bit of accuracy.
  926. // 2. Let tz be ℝ(epochNs) + offsetNs.
  927. auto zoned_time_ns = epoch_ns.plus(Crypto::SignedBigInteger { offset_ns });
  928. // 3. If calendar is "gregory", then
  929. if (calendar == "gregory"sv) {
  930. auto zoned_time_ms = zoned_time_ns.divided_by(s_one_million_bigint).quotient;
  931. auto zoned_time = floor(zoned_time_ms.to_double(Crypto::UnsignedBigInteger::RoundingMode::ECMAScriptNumberValueFor));
  932. auto year = year_from_time(zoned_time);
  933. // a. Return a record with fields calculated from tz according to Table 8.
  934. return LocalTime {
  935. // WeekDay(𝔽(floor(tz / 10^6)))
  936. .weekday = week_day(zoned_time),
  937. // Let year be YearFromTime(𝔽(floor(tz / 10^6))). If year < 1𝔽, return "BC", else return "AD".
  938. .era = year < 1 ? ::Locale::Era::BC : ::Locale::Era::AD,
  939. // YearFromTime(𝔽(floor(tz / 10^6)))
  940. .year = year,
  941. // undefined.
  942. .related_year = js_undefined(),
  943. // undefined.
  944. .year_name = js_undefined(),
  945. // MonthFromTime(𝔽(floor(tz / 10^6)))
  946. .month = month_from_time(zoned_time),
  947. // DateFromTime(𝔽(floor(tz / 10^6)))
  948. .day = date_from_time(zoned_time),
  949. // HourFromTime(𝔽(floor(tz / 10^6)))
  950. .hour = hour_from_time(zoned_time),
  951. // MinFromTime(𝔽(floor(tz / 10^6)))
  952. .minute = min_from_time(zoned_time),
  953. // SecFromTime(𝔽(floor(tz / 10^6)))
  954. .second = sec_from_time(zoned_time),
  955. // msFromTime(𝔽(floor(tz / 10^6)))
  956. .millisecond = ms_from_time(zoned_time),
  957. };
  958. }
  959. // 4. Else,
  960. // 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.
  961. // FIXME: Implement this when non-Gregorian calendars are supported by LibUnicode.
  962. return vm.throw_completion<InternalError>(ErrorType::NotImplemented, "Non-Gregorian calendars"sv);
  963. }
  964. }