DateTimeFormat.cpp 61 KB

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