1 /*
2 * Copyright (c) 2021-2024 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "ecmascript/js_date_time_format.h"
17
18 #include "ecmascript/checkpoint/thread_state_transition.h"
19 #include "ecmascript/intl/locale_helper.h"
20 #include "ecmascript/global_env.h"
21 #include "ecmascript/js_date.h"
22 #include "ecmascript/js_function.h"
23 #include "ecmascript/js_intl.h"
24 #include "ecmascript/object_factory-inl.h"
25
26 namespace panda::ecmascript {
27 struct CommonDateFormatPart {
28 int32_t fField = 0;
29 int32_t fBeginIndex = 0; // NOLINT(misc-non-private-member-variables-in-classes)
30 int32_t fEndIndex = 0; // NOLINT(misc-non-private-member-variables-in-classes)
31 int32_t index = 0; // NOLINT(misc-non-private-member-variables-in-classes)
32 bool isPreExist = false;
33
34 CommonDateFormatPart() = default;
CommonDateFormatPartpanda::ecmascript::CommonDateFormatPart35 CommonDateFormatPart(int32_t fField, int32_t fBeginIndex, int32_t fEndIndex, int32_t index, bool isPreExist)
36 : fField(fField), fBeginIndex(fBeginIndex), fEndIndex(fEndIndex), index(index), isPreExist(isPreExist)
37 {
38 }
39
40 ~CommonDateFormatPart() = default;
41
42 DEFAULT_COPY_SEMANTIC(CommonDateFormatPart);
43 DEFAULT_MOVE_SEMANTIC(CommonDateFormatPart);
44 };
45
46 namespace {
47 const std::vector<std::string> ICU_LONG_SHORT = {
48 "long", "short",
49 "longOffset", "shortOffset",
50 "longGeneric", "shortGeneric"
51 };
52 const std::vector<std::string> ICU_NARROW_LONG_SHORT = {"narrow", "long", "short"};
53 const std::vector<std::string> ICU2_DIGIT_NUMERIC = {"2-digit", "numeric"};
54 const std::vector<std::string> ICU_NARROW_LONG_SHORT2_DIGIT_NUMERIC = {"narrow", "long", "short", "2-digit", "numeric"};
55 const std::vector<IcuPatternEntry> ICU_WEEKDAY_PE = {
56 {"EEEEE", "narrow"}, {"EEEE", "long"}, {"EEE", "short"},
57 {"ccccc", "narrow"}, {"cccc", "long"}, {"ccc", "short"}
58 };
59 const std::vector<IcuPatternEntry> ICU_ERA_PE = {{"GGGGG", "narrow"}, {"GGGG", "long"}, {"GGG", "short"}};
60 const std::vector<IcuPatternEntry> ICU_YEAR_PE = {{"yy", "2-digit"}, {"y", "numeric"}};
61 const std::vector<IcuPatternEntry> ICU_MONTH_PE = {
62 {"MMMMM", "narrow"}, {"MMMM", "long"}, {"MMM", "short"}, {"MM", "2-digit"}, {"M", "numeric"},
63 {"LLLLL", "narrow"}, {"LLLL", "long"}, {"LLL", "short"}, {"LL", "2-digit"}, {"L", "numeric"}
64 };
65 const std::vector<IcuPatternEntry> ICU_DAY_PE = {{"dd", "2-digit"}, {"d", "numeric"}};
66 const std::vector<IcuPatternEntry> ICU_DAY_PERIOD_PE = {
67 {"BBBBB", "narrow"}, {"bbbbb", "narrow"}, {"BBBB", "long"},
68 {"bbbb", "long"}, {"B", "short"}, {"b", "short"}
69 };
70 const std::vector<IcuPatternEntry> ICU_HOUR_PE = {
71 {"HH", "2-digit"}, {"H", "numeric"}, {"hh", "2-digit"}, {"h", "numeric"},
72 {"kk", "2-digit"}, {"k", "numeric"}, {"KK", "2-digit"}, {"K", "numeric"}
73 };
74 const std::vector<IcuPatternEntry> ICU_MINUTE_PE = {{"mm", "2-digit"}, {"m", "numeric"}};
75 const std::vector<IcuPatternEntry> ICU_SECOND_PE = {{"ss", "2-digit"}, {"s", "numeric"}};
76 const std::vector<IcuPatternEntry> ICU_YIME_ZONE_NAME_PE = {
77 {"zzzz", "long"}, {"z", "short"},
78 {"OOOO", "longOffset"}, {"O", "shortOffset"},
79 {"vvvv", "longGeneric"}, {"v", "shortGeneric"}
80 };
81
82 const std::map<char16_t, HourCycleOption> HOUR_CYCLE_MAP = {
83 {'K', HourCycleOption::H11},
84 {'h', HourCycleOption::H12},
85 {'H', HourCycleOption::H23},
86 {'k', HourCycleOption::H24}
87 };
88 const std::map<std::string, HourCycleOption> TO_HOUR_CYCLE_MAP = {
89 {"h11", HourCycleOption::H11},
90 {"h12", HourCycleOption::H12},
91 {"h23", HourCycleOption::H23},
92 {"h24", HourCycleOption::H24}
93 };
94
95 // The value of the [[RelevantExtensionKeys]] internal slot is « "ca", "nu", "hc" ».
96 const std::set<std::string> RELEVANT_EXTENSION_KEYS = {"nu", "ca", "hc"};
97 }
98
GetIcuLocale() const99 icu::Locale *JSDateTimeFormat::GetIcuLocale() const
100 {
101 ASSERT(GetLocaleIcu().IsJSNativePointer());
102 auto result = JSNativePointer::Cast(GetLocaleIcu().GetTaggedObject())->GetExternalPointer();
103 return reinterpret_cast<icu::Locale *>(result);
104 }
105
106 /* static */
SetIcuLocale(JSThread * thread,JSHandle<JSDateTimeFormat> obj,const icu::Locale & icuLocale,const NativePointerCallback & callback)107 void JSDateTimeFormat::SetIcuLocale(JSThread *thread, JSHandle<JSDateTimeFormat> obj,
108 const icu::Locale &icuLocale, const NativePointerCallback &callback)
109 {
110 EcmaVM *ecmaVm = thread->GetEcmaVM();
111 ObjectFactory *factory = ecmaVm->GetFactory();
112 icu::Locale *icuPointer = ecmaVm->GetNativeAreaAllocator()->New<icu::Locale>(icuLocale);
113 ASSERT(icuPointer != nullptr);
114 JSTaggedValue data = obj->GetLocaleIcu();
115 if (data.IsHeapObject() && data.IsJSNativePointer()) {
116 JSNativePointer *native = JSNativePointer::Cast(data.GetTaggedObject());
117 native->ResetExternalPointer(thread, icuPointer);
118 return;
119 }
120 JSHandle<JSNativePointer> pointer = factory->NewJSNativePointer(icuPointer, callback, ecmaVm);
121 obj->SetLocaleIcu(thread, pointer.GetTaggedValue());
122 }
123
FreeIcuLocale(void * env,void * pointer,void * data)124 void JSDateTimeFormat::FreeIcuLocale([[maybe_unused]] void *env, void *pointer, void *data)
125 {
126 if (pointer == nullptr) {
127 return;
128 }
129 auto icuLocale = reinterpret_cast<icu::Locale *>(pointer);
130 icuLocale->~Locale();
131 if (data != nullptr) {
132 reinterpret_cast<EcmaVM *>(data)->GetNativeAreaAllocator()->FreeBuffer(pointer);
133 }
134 }
135
GetIcuSimpleDateFormat() const136 icu::SimpleDateFormat *JSDateTimeFormat::GetIcuSimpleDateFormat() const
137 {
138 ASSERT(GetSimpleDateTimeFormatIcu().IsJSNativePointer());
139 auto result = JSNativePointer::Cast(GetSimpleDateTimeFormatIcu().GetTaggedObject())->GetExternalPointer();
140 return reinterpret_cast<icu::SimpleDateFormat *>(result);
141 }
142
143 /* static */
SetIcuSimpleDateFormat(JSThread * thread,JSHandle<JSDateTimeFormat> obj,const icu::SimpleDateFormat & icuSimpleDateTimeFormat,const NativePointerCallback & callback)144 void JSDateTimeFormat::SetIcuSimpleDateFormat(JSThread *thread, JSHandle<JSDateTimeFormat> obj,
145 const icu::SimpleDateFormat &icuSimpleDateTimeFormat, const NativePointerCallback &callback)
146 {
147 EcmaVM *ecmaVm = thread->GetEcmaVM();
148 ObjectFactory *factory = ecmaVm->GetFactory();
149 icu::SimpleDateFormat *icuPointer =
150 ecmaVm->GetNativeAreaAllocator()->New<icu::SimpleDateFormat>(icuSimpleDateTimeFormat);
151 ASSERT(icuPointer != nullptr);
152 JSTaggedValue data = obj->GetSimpleDateTimeFormatIcu();
153 if (data.IsHeapObject() && data.IsJSNativePointer()) {
154 JSNativePointer *native = JSNativePointer::Cast(data.GetTaggedObject());
155 native->ResetExternalPointer(thread, icuPointer);
156 return;
157 }
158 // According to the observed native memory, we give an approximate native binding value.
159 constexpr static size_t icuBindingNativeSize = 64 * 1024;
160 JSHandle<JSNativePointer> pointer = factory->NewJSNativePointer(icuPointer, callback, ecmaVm,
161 false, icuBindingNativeSize);
162 obj->SetSimpleDateTimeFormatIcu(thread, pointer.GetTaggedValue());
163 }
164
FreeSimpleDateFormat(void * env,void * pointer,void * data)165 void JSDateTimeFormat::FreeSimpleDateFormat([[maybe_unused]] void *env, void *pointer, void *data)
166 {
167 if (pointer == nullptr) {
168 return;
169 }
170 auto icuSimpleDateFormat = reinterpret_cast<icu::SimpleDateFormat *>(pointer);
171 icuSimpleDateFormat->~SimpleDateFormat();
172 if (data != nullptr) {
173 reinterpret_cast<EcmaVM *>(data)->GetNativeAreaAllocator()->FreeBuffer(pointer);
174 }
175 }
176
ToValueString(JSThread * thread,const Value value)177 JSHandle<EcmaString> JSDateTimeFormat::ToValueString(JSThread *thread, const Value value)
178 {
179 auto globalConst = thread->GlobalConstants();
180 JSMutableHandle<EcmaString> result(thread, JSTaggedValue::Undefined());
181 switch (value) {
182 case Value::SHARED:
183 result.Update(globalConst->GetHandledSharedString().GetTaggedValue());
184 break;
185 case Value::START_RANGE:
186 result.Update(globalConst->GetHandledStartRangeString().GetTaggedValue());
187 break;
188 case Value::END_RANGE:
189 result.Update(globalConst->GetHandledEndRangeString().GetTaggedValue());
190 break;
191 default:
192 LOG_ECMA(FATAL) << "this branch is unreachable";
193 UNREACHABLE();
194 }
195 return result;
196 }
197
DateTimeStyleToEStyle(DateTimeStyleOption style)198 icu::DateFormat::EStyle DateTimeStyleToEStyle(DateTimeStyleOption style)
199 {
200 switch (style) {
201 case DateTimeStyleOption::FULL: {
202 return icu::DateFormat::kFull;
203 }
204 case DateTimeStyleOption::LONG: {
205 return icu::DateFormat::kLong;
206 }
207 case DateTimeStyleOption::MEDIUM: {
208 return icu::DateFormat::kMedium;
209 }
210 case DateTimeStyleOption::SHORT: {
211 return icu::DateFormat::kShort;
212 }
213 case DateTimeStyleOption::UNDEFINED: {
214 return icu::DateFormat::kNone;
215 }
216 default: {
217 return icu::DateFormat::kNone;
218 }
219 }
220 }
221
HourCycleFromPattern(const icu::UnicodeString pattern)222 HourCycleOption HourCycleFromPattern(const icu::UnicodeString pattern)
223 {
224 bool inQuote = false;
225 for (int32_t i = 0; i < pattern.length(); i++) {
226 char16_t ch = pattern[i];
227 switch (ch) {
228 case '\'':
229 inQuote = !inQuote;
230 break;
231 case 'K':
232 if (!inQuote) {
233 return HourCycleOption::H11;
234 }
235 break;
236 case 'h':
237 if (!inQuote) {
238 return HourCycleOption::H12;
239 }
240 break;
241 case 'H':
242 if (!inQuote) {
243 return HourCycleOption::H23;
244 }
245 break;
246 case 'k':
247 if (!inQuote) {
248 return HourCycleOption::H24;
249 }
250 break;
251 default : {
252 break;
253 }
254 }
255 }
256 return HourCycleOption::UNDEFINED;
257 }
258
ReplaceSkeleton(const icu::UnicodeString input,HourCycleOption hc)259 icu::UnicodeString ReplaceSkeleton(const icu::UnicodeString input, HourCycleOption hc)
260 {
261 icu::UnicodeString result;
262 char16_t to;
263 switch (hc) {
264 case HourCycleOption::H11:
265 to = 'K';
266 break;
267 case HourCycleOption::H12:
268 to = 'h';
269 break;
270 case HourCycleOption::H23:
271 to = 'H';
272 break;
273 case HourCycleOption::H24:
274 to = 'k';
275 break;
276 default:
277 UNREACHABLE();
278 break;
279 }
280 int inputLength = input.length();
281 for (int32_t i = 0; i < inputLength; ++i) {
282 switch (input[i]) {
283 case 'a':
284 case 'b':
285 case 'B':
286 break;
287 case 'h':
288 case 'H':
289 case 'k':
290 case 'K':
291 result += to;
292 break;
293 default:
294 result += input[i];
295 break;
296 }
297 }
298 return result;
299 }
300
DateTimeStylePattern(DateTimeStyleOption dateStyle,DateTimeStyleOption timeStyle,icu::Locale & icuLocale,HourCycleOption hc,icu::DateTimePatternGenerator * generator)301 std::unique_ptr<icu::SimpleDateFormat> DateTimeStylePattern(DateTimeStyleOption dateStyle,
302 DateTimeStyleOption timeStyle,
303 icu::Locale &icuLocale,
304 HourCycleOption hc,
305 icu::DateTimePatternGenerator *generator)
306 {
307 std::unique_ptr<icu::SimpleDateFormat> result;
308 icu::DateFormat::EStyle icuDateStyle = DateTimeStyleToEStyle(dateStyle);
309 icu::DateFormat::EStyle icuTimeStyle = DateTimeStyleToEStyle(timeStyle);
310 result.reset(reinterpret_cast<icu::SimpleDateFormat *>(
311 icu::DateFormat::createDateTimeInstance(icuDateStyle, icuTimeStyle, icuLocale)));
312 UErrorCode status = U_ZERO_ERROR;
313 icu::UnicodeString pattern("");
314 pattern = result->toPattern(pattern);
315 icu::UnicodeString skeleton = icu::DateTimePatternGenerator::staticGetSkeleton(pattern, status);
316 ASSERT_PRINT(U_SUCCESS(status), "staticGetSkeleton failed");
317 if (hc == HourCycleFromPattern(pattern)) {
318 return result;
319 }
320 skeleton = ReplaceSkeleton(skeleton, hc);
321 pattern = generator->getBestPattern(skeleton, UDATPG_MATCH_HOUR_FIELD_LENGTH, status);
322 result = std::make_unique<icu::SimpleDateFormat>(pattern, icuLocale, status);
323 return result;
324 }
325
326 // 13.1.1 InitializeDateTimeFormat (dateTimeFormat, locales, options)
327 // NOLINTNEXTLINE(readability-function-size)
InitializeDateTimeFormat(JSThread * thread,const JSHandle<JSDateTimeFormat> & dateTimeFormat,const JSHandle<JSTaggedValue> & locales,const JSHandle<JSTaggedValue> & options,IcuCacheType type)328 JSHandle<JSDateTimeFormat> JSDateTimeFormat::InitializeDateTimeFormat(JSThread *thread,
329 const JSHandle<JSDateTimeFormat> &dateTimeFormat,
330 const JSHandle<JSTaggedValue> &locales,
331 const JSHandle<JSTaggedValue> &options,
332 IcuCacheType type)
333 {
334 EcmaVM *ecmaVm = thread->GetEcmaVM();
335 ObjectFactory *factory = ecmaVm->GetFactory();
336 const GlobalEnvConstants *globalConst = thread->GlobalConstants();
337
338 // 1. Let requestedLocales be ? CanonicalizeLocaleList(locales).
339 JSHandle<TaggedArray> requestedLocales = intl::LocaleHelper::CanonicalizeLocaleList(thread, locales);
340 RETURN_HANDLE_IF_ABRUPT_COMPLETION(JSDateTimeFormat, thread);
341
342 // 2. Let options be ? ToDateTimeOptions(options, "any", "date").
343 JSHandle<JSObject> dateTimeOptions;
344 if (options->IsUndefined()) {
345 dateTimeOptions = factory->CreateNullJSObject();
346 } else {
347 dateTimeOptions = JSTaggedValue::ToObject(thread, options);
348 RETURN_HANDLE_IF_ABRUPT_COMPLETION(JSDateTimeFormat, thread);
349 }
350
351 // 4. Let matcher be ? GetOption(options, "localeMatcher", "string", « "lookup", "best fit" », "best fit").
352 auto matcher = JSLocale::GetOptionOfString<LocaleMatcherOption>(
353 thread, dateTimeOptions, globalConst->GetHandledLocaleMatcherString(),
354 {LocaleMatcherOption::LOOKUP, LocaleMatcherOption::BEST_FIT}, {"lookup", "best fit"},
355 LocaleMatcherOption::BEST_FIT);
356 RETURN_HANDLE_IF_ABRUPT_COMPLETION(JSDateTimeFormat, thread);
357
358 // 6. Let calendar be ? GetOption(options, "calendar", "string", undefined, undefined).
359 JSHandle<JSTaggedValue> calendar =
360 JSLocale::GetOption(thread, dateTimeOptions, globalConst->GetHandledCalendarString(), OptionType::STRING,
361 globalConst->GetHandledUndefined(), globalConst->GetHandledUndefined());
362 RETURN_HANDLE_IF_ABRUPT_COMPLETION(JSDateTimeFormat, thread);
363 dateTimeFormat->SetCalendar(thread, calendar);
364
365 // 7. If calendar is not undefined, then
366 // a. If calendar does not match the Unicode Locale Identifier type nonterminal, throw a RangeError exception.
367 std::string calendarStr;
368 if (!calendar->IsUndefined()) {
369 JSHandle<EcmaString> calendarEcmaStr = JSHandle<EcmaString>::Cast(calendar);
370 calendarStr = intl::LocaleHelper::ConvertToStdString(calendarEcmaStr);
371 if (!JSLocale::IsNormativeCalendar(calendarStr)) {
372 THROW_RANGE_ERROR_AND_RETURN(thread, "invalid calendar", dateTimeFormat);
373 }
374 }
375
376 // 9. Let numberingSystem be ? GetOption(options, "numberingSystem", "string", undefined, undefined).
377 JSHandle<JSTaggedValue> numberingSystem =
378 JSLocale::GetOption(thread, dateTimeOptions, globalConst->GetHandledNumberingSystemString(), OptionType::STRING,
379 globalConst->GetHandledUndefined(), globalConst->GetHandledUndefined());
380 RETURN_HANDLE_IF_ABRUPT_COMPLETION(JSDateTimeFormat, thread);
381 dateTimeFormat->SetNumberingSystem(thread, numberingSystem);
382
383 // 10. If numberingSystem is not undefined, then
384 // a. If numberingSystem does not match the Unicode Locale Identifier type nonterminal, throw a RangeError
385 // exception.
386 std::string nsStr;
387 if (!numberingSystem->IsUndefined()) {
388 JSHandle<EcmaString> nsEcmaStr = JSHandle<EcmaString>::Cast(numberingSystem);
389 nsStr = intl::LocaleHelper::ConvertToStdString(nsEcmaStr);
390 if (!JSLocale::IsNormativeNumberingSystem(nsStr)) {
391 THROW_RANGE_ERROR_AND_RETURN(thread, "invalid numberingSystem", dateTimeFormat);
392 }
393 }
394
395 // 12. Let hour12 be ? GetOption(options, "hour12", "boolean", undefined, undefined).
396 JSHandle<JSTaggedValue> hour12 =
397 JSLocale::GetOption(thread, dateTimeOptions, globalConst->GetHandledHour12String(), OptionType::BOOLEAN,
398 globalConst->GetHandledUndefined(), globalConst->GetHandledUndefined());
399 RETURN_HANDLE_IF_ABRUPT_COMPLETION(JSDateTimeFormat, thread);
400
401 // 13. Let hourCycle be ? GetOption(options, "hourCycle", "string", « "h11", "h12", "h23", "h24" », undefined).
402 auto hourCycle = JSLocale::GetOptionOfString<HourCycleOption>(
403 thread, dateTimeOptions, globalConst->GetHandledHourCycleString(),
404 {HourCycleOption::H11, HourCycleOption::H12, HourCycleOption::H23, HourCycleOption::H24},
405 {"h11", "h12", "h23", "h24"}, HourCycleOption::UNDEFINED);
406 RETURN_HANDLE_IF_ABRUPT_COMPLETION(JSDateTimeFormat, thread);
407
408 // 14. If hour12 is not undefined, then
409 // a. Let hourCycle be null.
410 if (!hour12->IsUndefined()) {
411 hourCycle = HourCycleOption::UNDEFINED;
412 }
413
414 // 16. Let localeData be %DateTimeFormat%.[[LocaleData]].
415 JSHandle<TaggedArray> availableLocales = (requestedLocales->GetLength() == 0) ? factory->EmptyArray() :
416 GainAvailableLocales(thread);
417
418 // 17. Let r be ResolveLocale(%DateTimeFormat%.[[AvailableLocales]], requestedLocales, opt, %DateTimeFormat%
419 // .[[RelevantExtensionKeys]], localeData).
420 ResolvedLocale resolvedLocale =
421 JSLocale::ResolveLocale(thread, availableLocales, requestedLocales, matcher, RELEVANT_EXTENSION_KEYS);
422
423 // 18. Set icuLocale to r.[[locale]].
424 icu::Locale icuLocale = resolvedLocale.localeData;
425 ASSERT_PRINT(!icuLocale.isBogus(), "icuLocale is bogus");
426 UErrorCode status = U_ZERO_ERROR;
427
428 if (numberingSystem->IsUndefined() || !JSLocale::IsWellNumberingSystem(nsStr)) {
429 std::string numberingSystemStr = JSLocale::GetNumberingSystem(icuLocale);
430 auto result = factory->NewFromStdString(numberingSystemStr);
431 dateTimeFormat->SetNumberingSystem(thread, result);
432 }
433
434 // Set resolvedIcuLocaleCopy to a copy of icuLocale.
435 // Set icuLocale.[[ca]] to calendar.
436 // Set icuLocale.[[nu]] to numberingSystem.
437 icu::Locale resolvedIcuLocaleCopy(icuLocale);
438 if (!calendar->IsUndefined() && JSLocale::IsWellCalendar(icuLocale, calendarStr)) {
439 icuLocale.setUnicodeKeywordValue("ca", calendarStr, status);
440 }
441 if (!numberingSystem->IsUndefined() && JSLocale::IsWellNumberingSystem(nsStr)) {
442 icuLocale.setUnicodeKeywordValue("nu", nsStr, status);
443 }
444
445 // 24. Let timeZone be ? Get(options, "timeZone").
446 OperationResult operationResult =
447 JSObject::GetProperty(thread, dateTimeOptions, globalConst->GetHandledTimeZoneString());
448 RETURN_HANDLE_IF_ABRUPT_COMPLETION(JSDateTimeFormat, thread);
449 dateTimeFormat->SetTimeZone(thread, operationResult.GetValue());
450
451 // 25. If timeZone is not undefined, then
452 // a. Let timeZone be ? ToString(timeZone).
453 // b. If the result of IsValidTimeZoneName(timeZone) is false, then
454 // i. Throw a RangeError exception.
455 std::unique_ptr<icu::TimeZone> icuTimeZone;
456 if (!operationResult.GetValue()->IsUndefined()) {
457 JSHandle<EcmaString> timezone = JSTaggedValue::ToString(thread, operationResult.GetValue());
458 RETURN_HANDLE_IF_ABRUPT_COMPLETION(JSDateTimeFormat, thread);
459 icuTimeZone = ConstructTimeZone(intl::LocaleHelper::ConvertToStdString(timezone));
460 if (icuTimeZone == nullptr) {
461 THROW_RANGE_ERROR_AND_RETURN(thread, "invalid timeZone", dateTimeFormat);
462 }
463 } else {
464 // 26. Else,
465 // a. Let timeZone be DefaultTimeZone().
466 icuTimeZone = std::unique_ptr<icu::TimeZone>(icu::TimeZone::createDefault());
467 }
468
469 // 36.a. Let hcDefault be dataLocaleData.[[hourCycle]].
470 std::unique_ptr<icu::DateTimePatternGenerator> generator;
471 {
472 ThreadNativeScope nativeScope(thread);
473 generator.reset(icu::DateTimePatternGenerator::createInstance(icuLocale, status));
474 }
475 if (U_FAILURE(status) || generator == nullptr) {
476 if (status == UErrorCode::U_MISSING_RESOURCE_ERROR) {
477 THROW_REFERENCE_ERROR_AND_RETURN(thread, "can not find icu data resources", dateTimeFormat);
478 }
479 THROW_RANGE_ERROR_AND_RETURN(thread, "create icu::DateTimePatternGenerator failed", dateTimeFormat);
480 }
481 HourCycleOption hcDefault = OptionToHourCycle(generator->getDefaultHourCycle(status));
482 // b. Let hc be dateTimeFormat.[[HourCycle]].
483 HourCycleOption hc = hourCycle;
484 if (hourCycle == HourCycleOption::UNDEFINED
485 && resolvedLocale.extensions.find("hc") != resolvedLocale.extensions.end()) {
486 hc = OptionToHourCycle(resolvedLocale.extensions.find("hc")->second);
487 }
488 // c. If hc is null, then
489 // i. Set hc to hcDefault.
490 if (hc == HourCycleOption::UNDEFINED) {
491 hc = hcDefault;
492 }
493 // d. If hour12 is not undefined, then
494 if (!hour12->IsUndefined()) {
495 // i. If hour12 is true, then
496 if (JSTaggedValue::SameValue(hour12.GetTaggedValue(), JSTaggedValue::True())) {
497 // 1. If hcDefault is "h11" or "h23", then
498 if (hcDefault == HourCycleOption::H11 || hcDefault == HourCycleOption::H23) {
499 // a. Set hc to "h11".
500 hc = HourCycleOption::H11;
501 } else {
502 // 2. Else,
503 // a. Set hc to "h12".
504 hc = HourCycleOption::H12;
505 }
506 } else {
507 // ii. Else,
508 // 2. If hcDefault is "h11" or "h23", then
509 if (hcDefault == HourCycleOption::H11 || hcDefault == HourCycleOption::H23) {
510 // a. Set hc to "h23".
511 hc = HourCycleOption::H23;
512 } else {
513 // 3. Else,
514 // a. Set hc to "h24".
515 hc = HourCycleOption::H24;
516 }
517 }
518 }
519
520 // Set isHourDefined be false when dateTimeFormat.[[Hour]] is not undefined.
521 bool isHourDefined = false;
522
523 // 29. For each row of Table 6, except the header row, in table order, do
524 // a. Let prop be the name given in the Property column of the row.
525 // b. Let value be ? GetOption(options, prop, "string", « the strings given in the Values column of the
526 // row », undefined).
527 // c. Set opt.[[<prop>]] to value.
528 std::string skeleton;
529 std::vector<IcuPatternDesc> data = GetIcuPatternDesc(hc);
530 int32_t explicitFormatComponents = 0;
531 std::vector<std::string> skeletonOpts;
532 for (const IcuPatternDesc &item : data) {
533 // prop be [[TimeZoneName]]
534 if (item.property == "timeZoneName") {
535 // b. If prop is "fractionalSecondDigits", then
536 // i. Let value be ? GetNumberOption(options, "fractionalSecondDigits", 1, 3, undefined).
537 int secondDigitsString = JSLocale::GetNumberOption(thread, dateTimeOptions,
538 globalConst->GetHandledFractionalSecondDigitsString(),
539 1, 3, 0);
540 skeleton.append(secondDigitsString, 'S');
541 // e. If value is not undefined, then
542 // i. Set hasExplicitFormatComponents to true.
543 if (secondDigitsString > 0) {
544 explicitFormatComponents = 1;
545 skeletonOpts.emplace_back(item.property);
546 }
547 }
548 JSHandle<JSTaggedValue> property(thread, factory->NewFromStdString(item.property).GetTaggedValue());
549 std::string value;
550 bool isFind = JSLocale::GetOptionOfString(thread, dateTimeOptions, property, item.allowedValues, &value);
551 RETURN_HANDLE_IF_ABRUPT_COMPLETION(JSDateTimeFormat, thread);
552 if (isFind) {
553 skeletonOpts.emplace_back(item.property);
554 explicitFormatComponents = 1;
555 skeleton += item.map.find(value)->second;
556 // [[Hour]] is defined.
557 isHourDefined = (item.property == "hour") ? true : isHourDefined;
558 }
559 }
560
561 // 13.1.3 BasicFormatMatcher (options, formats)
562 [[maybe_unused]] auto formatMatcher = JSLocale::GetOptionOfString<FormatMatcherOption>(
563 thread, dateTimeOptions, globalConst->GetHandledFormatMatcherString(),
564 {FormatMatcherOption::BASIC, FormatMatcherOption::BEST_FIT}, {"basic", "best fit"},
565 FormatMatcherOption::BEST_FIT);
566 RETURN_HANDLE_IF_ABRUPT_COMPLETION(JSDateTimeFormat, thread);
567
568 // Let dateStyle be ? GetOption(options, "string", «"full", "long", "medium", "short"», undefined).
569 // Set dateTimeFormat.[[dateStyle]]
570 auto dateStyle = JSLocale::GetOptionOfString<DateTimeStyleOption>(
571 thread, dateTimeOptions, globalConst->GetHandledDateStyleString(),
572 {DateTimeStyleOption::FULL, DateTimeStyleOption::LONG, DateTimeStyleOption::MEDIUM, DateTimeStyleOption::SHORT},
573 {"full", "long", "medium", "short"}, DateTimeStyleOption::UNDEFINED);
574 RETURN_HANDLE_IF_ABRUPT_COMPLETION(JSDateTimeFormat, thread);
575 dateTimeFormat->SetDateStyle(dateStyle);
576
577 // Let timeStyle be ? GetOption(options, "string", «"full", "long", "medium", "short"», undefined).
578 // Set dateTimeFormat.[[timeStyle]]
579 auto timeStyle = JSLocale::GetOptionOfString<DateTimeStyleOption>(
580 thread, dateTimeOptions, globalConst->GetHandledTimeStyleString(),
581 {DateTimeStyleOption::FULL, DateTimeStyleOption::LONG, DateTimeStyleOption::MEDIUM, DateTimeStyleOption::SHORT},
582 {"full", "long", "medium", "short"}, DateTimeStyleOption::UNDEFINED);
583 RETURN_HANDLE_IF_ABRUPT_COMPLETION(JSDateTimeFormat, thread);
584 dateTimeFormat->SetTimeStyle(timeStyle);
585
586 HourCycleOption dtfHourCycle = HourCycleOption::UNDEFINED;
587
588 if (timeStyle != DateTimeStyleOption::UNDEFINED) {
589 // Set dateTimeFormat.[[HourCycle]] to hc.
590 dtfHourCycle = hc;
591 }
592
593 if (dateStyle == DateTimeStyleOption::UNDEFINED
594 && timeStyle == DateTimeStyleOption::UNDEFINED) {
595 ToDateTimeSkeleton(thread, skeletonOpts, skeleton, hc, RequiredOption::ANY, DefaultsOption::DATE);
596 RETURN_HANDLE_IF_ABRUPT_COMPLETION(JSDateTimeFormat, thread);
597 // If dateTimeFormat.[[Hour]] is defined, then
598 if (isHourDefined) {
599 // e. Set dateTimeFormat.[[HourCycle]] to hc.
600 dtfHourCycle = hc;
601 } else {
602 // 37. Else,
603 // a. Set dateTimeFormat.[[HourCycle]] to undefined.
604 dtfHourCycle = HourCycleOption::UNDEFINED;
605 }
606 }
607
608 // Set dateTimeFormat.[[hourCycle]].
609 dateTimeFormat->SetHourCycle(dtfHourCycle);
610
611 // Set dateTimeFormat.[[icuLocale]].
612 JSDateTimeFormat::SetIcuLocale(thread, dateTimeFormat, icuLocale, JSDateTimeFormat::FreeIcuLocale);
613
614 // Creates a Calendar using the given timezone and given locale.
615 // Set dateTimeFormat.[[icuSimpleDateFormat]].
616 icu::UnicodeString dtfSkeleton(skeleton.c_str());
617 status = U_ZERO_ERROR;
618 icu::UnicodeString pattern = ChangeHourCyclePattern(
619 generator.get()->getBestPattern(dtfSkeleton, UDATPG_MATCH_HOUR_FIELD_LENGTH, status), dtfHourCycle);
620 ASSERT_PRINT((U_SUCCESS(status) != 0), "get best pattern failed");
621 auto simpleDateFormatIcu(std::make_unique<icu::SimpleDateFormat>(pattern, icuLocale, status));
622 if (dateStyle != DateTimeStyleOption::UNDEFINED || timeStyle != DateTimeStyleOption::UNDEFINED) {
623 if (explicitFormatComponents != 0) {
624 THROW_TYPE_ERROR_AND_RETURN(thread, "Invalid option : option", dateTimeFormat);
625 }
626 simpleDateFormatIcu = DateTimeStylePattern(dateStyle, timeStyle, icuLocale,
627 hc, generator.get());
628 }
629 if (U_FAILURE(status) != 0) {
630 simpleDateFormatIcu = std::unique_ptr<icu::SimpleDateFormat>();
631 }
632 ASSERT_PRINT(simpleDateFormatIcu != nullptr, "invalid icuSimpleDateFormat");
633 std::unique_ptr<icu::Calendar> calendarPtr = BuildCalendar(icuLocale, *icuTimeZone);
634 ASSERT_PRINT(calendarPtr != nullptr, "invalid calendar");
635 simpleDateFormatIcu->adoptCalendar(calendarPtr.release());
636 if (type != IcuCacheType::NOT_CACHE) {
637 std::string cacheEntry =
638 locales->IsUndefined() ? "" : EcmaStringAccessor(locales.GetTaggedValue()).ToStdString();
639 auto& intlCache = ecmaVm->GetIntlCache();
640 switch (type) {
641 case IcuCacheType::DEFAULT:
642 intlCache.SetIcuFormatterToCache(IcuFormatterType::SIMPLE_DATE_FORMAT_DEFAULT,
643 cacheEntry, simpleDateFormatIcu.release(), JSDateTimeFormat::FreeSimpleDateFormat);
644 break;
645 case IcuCacheType::DATE:
646 intlCache.SetIcuFormatterToCache(IcuFormatterType::SIMPLE_DATE_FORMAT_DATE,
647 cacheEntry, simpleDateFormatIcu.release(), JSDateTimeFormat::FreeSimpleDateFormat);
648 break;
649 case IcuCacheType::TIME:
650 intlCache.SetIcuFormatterToCache(IcuFormatterType::SIMPLE_DATE_FORMAT_TIME,
651 cacheEntry, simpleDateFormatIcu.release(), JSDateTimeFormat::FreeSimpleDateFormat);
652 break;
653 default:
654 UNREACHABLE();
655 }
656 } else {
657 SetIcuSimpleDateFormat(thread, dateTimeFormat, *simpleDateFormatIcu, JSDateTimeFormat::FreeSimpleDateFormat);
658 }
659
660 // Set dateTimeFormat.[[iso8601]].
661 bool iso8601 = strstr(icuLocale.getName(), "calendar=iso8601") != nullptr;
662 dateTimeFormat->SetIso8601(thread, JSTaggedValue(iso8601));
663
664 // Set dateTimeFormat.[[locale]].
665 if (!hour12->IsUndefined() || hourCycle != HourCycleOption::UNDEFINED) {
666 if ((resolvedLocale.extensions.find("hc") != resolvedLocale.extensions.end()) &&
667 (dtfHourCycle != OptionToHourCycle((resolvedLocale.extensions.find("hc")->second)))) {
668 resolvedIcuLocaleCopy.setUnicodeKeywordValue("hc", nullptr, status);
669 ASSERT_PRINT(U_SUCCESS(status), "resolvedIcuLocaleCopy set hc failed");
670 }
671 }
672 JSHandle<EcmaString> localeStr = intl::LocaleHelper::ToLanguageTag(thread, resolvedIcuLocaleCopy);
673 RETURN_HANDLE_IF_ABRUPT_COMPLETION(JSDateTimeFormat, thread);
674 dateTimeFormat->SetLocale(thread, localeStr.GetTaggedValue());
675
676 // Set dateTimeFormat.[[boundFormat]].
677 dateTimeFormat->SetBoundFormat(thread, JSTaggedValue::Undefined());
678
679 // 39. Return dateTimeFormat.
680 return dateTimeFormat;
681 }
682
GetCachedIcuSimpleDateFormat(JSThread * thread,const JSHandle<JSTaggedValue> & locales,IcuFormatterType type)683 icu::SimpleDateFormat *JSDateTimeFormat::GetCachedIcuSimpleDateFormat(JSThread *thread,
684 const JSHandle<JSTaggedValue> &locales,
685 IcuFormatterType type)
686 {
687 std::string cacheEntry = locales->IsUndefined() ? "" : EcmaStringAccessor(locales.GetTaggedValue()).ToStdString();
688 void *cachedSimpleDateFormat = thread->GetEcmaVM()->GetIntlCache().GetIcuFormatterFromCache(type, cacheEntry);
689 if (cachedSimpleDateFormat != nullptr) {
690 return reinterpret_cast<icu::SimpleDateFormat*>(cachedSimpleDateFormat);
691 }
692 return nullptr;
693 }
694
695 // 13.1.2 ToDateTimeOptions (options, required, defaults)
ToDateTimeOptions(JSThread * thread,const JSHandle<JSTaggedValue> & options,const RequiredOption & required,const DefaultsOption & defaults)696 JSHandle<JSObject> JSDateTimeFormat::ToDateTimeOptions(JSThread *thread, const JSHandle<JSTaggedValue> &options,
697 const RequiredOption &required, const DefaultsOption &defaults)
698 {
699 EcmaVM *ecmaVm = thread->GetEcmaVM();
700 ObjectFactory *factory = ecmaVm->GetFactory();
701
702 // 1. If options is undefined, let options be null; otherwise let options be ? ToObject(options).
703 JSHandle<JSObject> optionsResult(thread, JSTaggedValue::Null());
704 if (!options->IsUndefined()) {
705 optionsResult = JSTaggedValue::ToObject(thread, options);
706 RETURN_HANDLE_IF_ABRUPT_COMPLETION(JSObject, thread);
707 }
708
709 // 2. Let options be ObjectCreate(options).
710 optionsResult = JSObject::ObjectCreate(thread, optionsResult);
711
712 // 3. Let needDefaults be true.
713 bool needDefaults = true;
714
715 // 4. If required is "date" or "any", then
716 // a. For each of the property names "weekday", "year", "month", "day", do
717 // i. Let prop be the property name.
718 // ii. Let value be ? Get(options, prop).
719 // iii. If value is not undefined, let needDefaults be false.
720 auto globalConst = thread->GlobalConstants();
721 if (required == RequiredOption::DATE || required == RequiredOption::ANY) {
722 JSHandle<TaggedArray> array = factory->NewTaggedArray(CAPACITY_4);
723 array->Set(thread, 0, globalConst->GetHandledWeekdayString());
724 array->Set(thread, 1, globalConst->GetHandledYearString());
725 array->Set(thread, 2, globalConst->GetHandledMonthString()); // 2 means the third slot
726 array->Set(thread, 3, globalConst->GetHandledDayString()); // 3 means the fourth slot
727 JSMutableHandle<JSTaggedValue> key(thread, JSTaggedValue::Undefined());
728 uint32_t len = array->GetLength();
729 for (uint32_t i = 0; i < len; i++) {
730 key.Update(array->Get(thread, i));
731 OperationResult operationResult = JSObject::GetProperty(thread, optionsResult, key);
732 RETURN_HANDLE_IF_ABRUPT_COMPLETION(JSObject, thread);
733 if (!operationResult.GetValue()->IsUndefined()) {
734 needDefaults = false;
735 }
736 }
737 }
738
739 // 5. If required is "time" or "any", then
740 // a. For each of the property names "dayPeriod", "hour", "minute", "second", "fractionalSecondDigits", do
741 // i. Let prop be the property name.
742 // ii. Let value be ? Get(options, prop).
743 // iii. If value is not undefined, let needDefaults be false.
744 if (required == RequiredOption::TIME || required == RequiredOption::ANY) {
745 JSHandle<TaggedArray> array = factory->NewTaggedArray(CAPACITY_5);
746 array->Set(thread, 0, globalConst->GetHandledDayPeriodString());
747 array->Set(thread, 1, globalConst->GetHandledHourString());
748 array->Set(thread, 2, globalConst->GetHandledMinuteString()); // 2 means the second slot
749 array->Set(thread, 3, globalConst->GetHandledSecondString()); // 3 means the third slot
750 array->Set(thread, 4, globalConst->GetHandledFractionalSecondDigitsString()); // 4 means the fourth slot
751 JSMutableHandle<JSTaggedValue> key(thread, JSTaggedValue::Undefined());
752 uint32_t len = array->GetLength();
753 for (uint32_t i = 0; i < len; i++) {
754 key.Update(array->Get(thread, i));
755 OperationResult operationResult = JSObject::GetProperty(thread, optionsResult, key);
756 RETURN_HANDLE_IF_ABRUPT_COMPLETION(JSObject, thread);
757 if (!operationResult.GetValue()->IsUndefined()) {
758 needDefaults = false;
759 }
760 }
761 }
762
763 // Let dateStyle/timeStyle be ? Get(options, "dateStyle"/"timeStyle").
764 OperationResult dateStyleResult =
765 JSObject::GetProperty(thread, optionsResult, globalConst->GetHandledDateStyleString());
766 RETURN_HANDLE_IF_ABRUPT_COMPLETION(JSObject, thread);
767 JSHandle<JSTaggedValue> dateStyle = dateStyleResult.GetValue();
768 OperationResult timeStyleResult =
769 JSObject::GetProperty(thread, optionsResult, globalConst->GetHandledTimeStyleString());
770 RETURN_HANDLE_IF_ABRUPT_COMPLETION(JSObject, thread);
771 JSHandle<JSTaggedValue> timeStyle = timeStyleResult.GetValue();
772
773 // If dateStyle is not undefined or timeStyle is not undefined, let needDefaults be false.
774 if (!dateStyle->IsUndefined() || !timeStyle->IsUndefined()) {
775 needDefaults = false;
776 }
777
778 // If required is "date"/"time" and timeStyle is not undefined, throw a TypeError exception.
779 if (required == RequiredOption::DATE && !timeStyle->IsUndefined()) {
780 THROW_TYPE_ERROR_AND_RETURN(thread, "timeStyle is not undefined", optionsResult);
781 }
782 if (required == RequiredOption::TIME && !dateStyle->IsUndefined()) {
783 THROW_TYPE_ERROR_AND_RETURN(thread, "dateStyle is not undefined", optionsResult);
784 }
785
786 // 6. If needDefaults is true and defaults is either "date" or "all", then
787 // a. For each of the property names "year", "month", "day", do
788 // i. Perform ? CreateDataPropertyOrThrow(options, prop, "numeric").
789 if (needDefaults && (defaults == DefaultsOption::DATE || defaults == DefaultsOption::ALL)) {
790 JSHandle<TaggedArray> array = factory->NewTaggedArray(CAPACITY_3);
791 array->Set(thread, 0, globalConst->GetHandledYearString());
792 array->Set(thread, 1, globalConst->GetHandledMonthString());
793 array->Set(thread, 2, globalConst->GetHandledDayString()); // 2 means the third slot
794 JSMutableHandle<JSTaggedValue> key(thread, JSTaggedValue::Undefined());
795 uint32_t len = array->GetLength();
796 for (uint32_t i = 0; i < len; i++) {
797 key.Update(array->Get(thread, i));
798 JSObject::CreateDataPropertyOrThrow(thread, optionsResult, key, globalConst->GetHandledNumericString());
799 RETURN_HANDLE_IF_ABRUPT_COMPLETION(JSObject, thread);
800 }
801 }
802
803 // 7. If needDefaults is true and defaults is either "time" or "all", then
804 // a. For each of the property names "hour", "minute", "second", do
805 // i. Perform ? CreateDataPropertyOrThrow(options, prop, "numeric").
806 if (needDefaults && (defaults == DefaultsOption::TIME || defaults == DefaultsOption::ALL)) {
807 JSHandle<TaggedArray> array = factory->NewTaggedArray(CAPACITY_3);
808 array->Set(thread, 0, globalConst->GetHandledHourString());
809 array->Set(thread, 1, globalConst->GetHandledMinuteString());
810 array->Set(thread, 2, globalConst->GetHandledSecondString()); // 2 means the third slot
811 JSMutableHandle<JSTaggedValue> key(thread, JSTaggedValue::Undefined());
812 uint32_t len = array->GetLength();
813 for (uint32_t i = 0; i < len; i++) {
814 key.Update(array->Get(thread, i));
815 JSObject::CreateDataPropertyOrThrow(thread, optionsResult, key, globalConst->GetHandledNumericString());
816 RETURN_HANDLE_IF_ABRUPT_COMPLETION(JSObject, thread);
817 }
818 }
819
820 // 8. Return options.
821 return optionsResult;
822 }
823
ToDateTimeSkeleton(JSThread * thread,const std::vector<std::string> & options,std::string & skeleton,HourCycleOption hc,const RequiredOption & required,const DefaultsOption & defaults)824 void JSDateTimeFormat::ToDateTimeSkeleton(JSThread *thread, const std::vector<std::string> &options,
825 std::string &skeleton, HourCycleOption hc,
826 const RequiredOption &required, const DefaultsOption &defaults)
827 {
828 EcmaVM *ecmaVm = thread->GetEcmaVM();
829 ObjectFactory *factory = ecmaVm->GetFactory();
830
831 // 1. Let needDefaults be true.
832 bool needDefaults = true;
833
834 // 2. If required is "date" or "any", then
835 // a. For each of the property names "weekday", "year", "month", "day", do
836 // i. Let prop be the property name.
837 // ii. Let value be ? Get(options, prop).
838 // iii. If value is not undefined, let needDefaults be false.
839 auto globalConst = thread->GlobalConstants();
840 if (required == RequiredOption::DATE || required == RequiredOption::ANY) {
841 JSHandle<TaggedArray> array = factory->NewTaggedArray(CAPACITY_4);
842 array->Set(thread, 0, globalConst->GetHandledWeekdayString());
843 array->Set(thread, 1, globalConst->GetHandledYearString());
844 array->Set(thread, 2, globalConst->GetHandledMonthString()); // 2 means the third slot
845 array->Set(thread, 3, globalConst->GetHandledDayString()); // 3 means the fourth slot
846 JSMutableHandle<JSTaggedValue> key(thread, JSTaggedValue::Undefined());
847 uint32_t len = array->GetLength();
848 for (uint32_t i = 0; i < len; i++) {
849 key.Update(array->Get(thread, i));
850 std::string result = EcmaStringAccessor(key.GetTaggedValue()).ToStdString();
851 auto it = std::find(options.begin(), options.end(), result);
852 if (it != options.end()) {
853 needDefaults = false;
854 break;
855 }
856 }
857 }
858
859 // 3. If required is "time" or "any", then
860 // a. For each of the property names "dayPeriod", "hour", "minute", "second", "fractionalSecondDigits", do
861 // i. Let prop be the property name.
862 // ii. Let value be ? Get(options, prop).
863 // iii. If value is not undefined, let needDefaults be false.
864 if (required == RequiredOption::TIME || required == RequiredOption::ANY) {
865 JSHandle<TaggedArray> array = factory->NewTaggedArray(CAPACITY_5);
866 array->Set(thread, 0, globalConst->GetHandledDayPeriodString());
867 array->Set(thread, 1, globalConst->GetHandledHourString());
868 array->Set(thread, 2, globalConst->GetHandledMinuteString()); // 2 means the second slot
869 array->Set(thread, 3, globalConst->GetHandledSecondString()); // 3 means the third slot
870 array->Set(thread, 4, globalConst->GetHandledFractionalSecondDigitsString()); // 4 means the fourth slot
871 JSMutableHandle<JSTaggedValue> key(thread, JSTaggedValue::Undefined());
872 uint32_t len = array->GetLength();
873 for (uint32_t i = 0; i < len; i++) {
874 key.Update(array->Get(thread, i));
875 std::string result = EcmaStringAccessor(key.GetTaggedValue()).ToStdString();
876 auto it = std::find(options.begin(), options.end(), result);
877 if (it != options.end()) {
878 needDefaults = false;
879 break;
880 }
881 }
882 }
883
884 // 4. If needDefaults is true and defaults is either "date" or "all", then
885 // skeleton += "year", "month", "day"
886 if (needDefaults && (defaults == DefaultsOption::DATE || defaults == DefaultsOption::ALL)) {
887 skeleton += "yMd";
888 }
889
890 // 5. If needDefaults is true and defaults is either "time" or "all", then
891 // skeleton += "hour", "minute", "second"
892 if (needDefaults && (defaults == DefaultsOption::TIME || defaults == DefaultsOption::ALL)) {
893 switch (hc) {
894 case HourCycleOption::H12:
895 skeleton += "hms";
896 break;
897 case HourCycleOption::H23:
898 case HourCycleOption::UNDEFINED:
899 skeleton += "Hms";
900 break;
901 case HourCycleOption::H11:
902 skeleton += "Kms";
903 break;
904 case HourCycleOption::H24:
905 skeleton += "kms";
906 break;
907 default:
908 break;
909 }
910 }
911 }
912
913 // 13.1.7 FormatDateTime(dateTimeFormat, x)
FormatDateTime(JSThread * thread,const JSHandle<JSDateTimeFormat> & dateTimeFormat,double x)914 JSHandle<EcmaString> JSDateTimeFormat::FormatDateTime(JSThread *thread,
915 const JSHandle<JSDateTimeFormat> &dateTimeFormat, double x)
916 {
917 icu::SimpleDateFormat *simpleDateFormat = dateTimeFormat->GetIcuSimpleDateFormat();
918 JSHandle<EcmaString> res = FormatDateTime(thread, simpleDateFormat, x);
919 RETURN_HANDLE_IF_ABRUPT_COMPLETION(EcmaString, thread);
920 return res;
921 }
922
FormatDateTime(JSThread * thread,const icu::SimpleDateFormat * simpleDateFormat,double x)923 JSHandle<EcmaString> JSDateTimeFormat::FormatDateTime(JSThread *thread,
924 const icu::SimpleDateFormat *simpleDateFormat, double x)
925 {
926 // 1. Let parts be ? PartitionDateTimePattern(dateTimeFormat, x).
927 double xValue = JSDate::TimeClip(x);
928 if (std::isnan(xValue)) {
929 THROW_RANGE_ERROR_AND_RETURN(thread, "Invalid time value", thread->GetEcmaVM()->GetFactory()->GetEmptyString());
930 }
931
932 // 2. Let result be the empty String.
933 icu::UnicodeString result;
934
935 // 3. Set result to the string-concatenation of result and part.[[Value]].
936 {
937 ThreadNativeScope nativeScope(thread);
938 simpleDateFormat->format(xValue, result);
939 }
940
941 // 4. Return result.
942 return intl::LocaleHelper::UStringToString(thread, result);
943 }
944
945 // 13.1.8 FormatDateTimeToParts (dateTimeFormat, x)
FormatDateTimeToParts(JSThread * thread,const JSHandle<JSDateTimeFormat> & dateTimeFormat,double x)946 JSHandle<JSArray> JSDateTimeFormat::FormatDateTimeToParts(JSThread *thread,
947 const JSHandle<JSDateTimeFormat> &dateTimeFormat, double x)
948 {
949 icu::SimpleDateFormat *simpleDateFormat = dateTimeFormat->GetIcuSimpleDateFormat();
950 ASSERT(simpleDateFormat != nullptr);
951 UErrorCode status = U_ZERO_ERROR;
952 icu::FieldPositionIterator fieldPositionIter;
953 icu::UnicodeString formattedParts;
954 {
955 ThreadNativeScope nativeScope(thread);
956 simpleDateFormat->format(x, formattedParts, &fieldPositionIter, status);
957 }
958 if (U_FAILURE(status) != 0) {
959 THROW_TYPE_ERROR_AND_RETURN(thread, "format failed", thread->GetEcmaVM()->GetFactory()->NewJSArray());
960 }
961
962 // 2. Let result be ArrayCreate(0).
963 JSHandle<JSArray> result(JSArray::ArrayCreate(thread, JSTaggedNumber(0)));
964 RETURN_HANDLE_IF_ABRUPT_COMPLETION(JSArray, thread);
965 if (formattedParts.isBogus()) {
966 return result;
967 }
968
969 // 3. Let n be 0.
970 int32_t index = 0;
971 int32_t preEdgePos = 0;
972 std::vector<CommonDateFormatPart> parts;
973 icu::FieldPosition fieldPosition;
974 while (fieldPositionIter.next(fieldPosition)) {
975 int32_t fField = fieldPosition.getField();
976 int32_t fBeginIndex = fieldPosition.getBeginIndex();
977 int32_t fEndIndex = fieldPosition.getEndIndex();
978 if (preEdgePos < fBeginIndex) {
979 parts.emplace_back(CommonDateFormatPart(fField, preEdgePos, fBeginIndex, index, true));
980 ++index;
981 }
982 parts.emplace_back(CommonDateFormatPart(fField, fBeginIndex, fEndIndex, index, false));
983 preEdgePos = fEndIndex;
984 ++index;
985 }
986 int32_t length = formattedParts.length();
987 if (preEdgePos < length) {
988 parts.emplace_back(CommonDateFormatPart(-1, preEdgePos, length, index, true));
989 }
990 JSMutableHandle<EcmaString> substring(thread, JSTaggedValue::Undefined());
991
992 // 4. For each part in parts, do
993 for (auto part : parts) {
994 substring.Update(intl::LocaleHelper::UStringToString(thread, formattedParts, part.fBeginIndex,
995 part.fEndIndex).GetTaggedValue());
996 RETURN_HANDLE_IF_ABRUPT_COMPLETION(JSArray, thread);
997 // Let O be ObjectCreate(%ObjectPrototype%).
998 // Perform ! CreateDataPropertyOrThrow(O, "type", part.[[Type]]).
999 // Perform ! CreateDataPropertyOrThrow(O, "value", part.[[Value]]).
1000 // Perform ! CreateDataProperty(result, ! ToString(n), O).
1001 if (part.isPreExist) {
1002 JSLocale::PutElement(thread, part.index, result, ConvertFieldIdToDateType(thread, -1),
1003 JSHandle<JSTaggedValue>::Cast(substring));
1004 } else {
1005 JSLocale::PutElement(thread, part.index, result, ConvertFieldIdToDateType(thread, part.fField),
1006 JSHandle<JSTaggedValue>::Cast(substring));
1007 }
1008 }
1009
1010 // 5. Return result.
1011 return result;
1012 }
1013
1014 // 13.1.10 UnwrapDateTimeFormat(dtf)
UnwrapDateTimeFormat(JSThread * thread,const JSHandle<JSTaggedValue> & dateTimeFormat)1015 JSHandle<JSTaggedValue> JSDateTimeFormat::UnwrapDateTimeFormat(JSThread *thread,
1016 const JSHandle<JSTaggedValue> &dateTimeFormat)
1017 {
1018 // 1. Assert: Type(dtf) is Object.
1019 ASSERT_PRINT(dateTimeFormat->IsJSObject(), "dateTimeFormat is not object");
1020
1021 // 2. If dateTimeFormat does not have an [[InitializedDateTimeFormat]] internal slot
1022 // and ? InstanceofOperator(dateTimeFormat, %DateTimeFormat%) is true, then
1023 // a. Let dateTimeFormat be ? Get(dateTimeFormat, %Intl%.[[FallbackSymbol]]).
1024 JSHandle<GlobalEnv> env = thread->GetEcmaVM()->GetGlobalEnv();
1025 bool isInstanceOf = JSFunction::OrdinaryHasInstance(thread, env->GetDateTimeFormatFunction(), dateTimeFormat);
1026 RETURN_VALUE_IF_ABRUPT_COMPLETION(thread, dateTimeFormat);
1027 if (!dateTimeFormat->IsJSDateTimeFormat() && isInstanceOf) {
1028 JSHandle<JSTaggedValue> key(thread, JSHandle<JSIntl>::Cast(env->GetIntlFunction())->GetFallbackSymbol());
1029 OperationResult operationResult = JSTaggedValue::GetProperty(thread, dateTimeFormat, key);
1030 RETURN_VALUE_IF_ABRUPT_COMPLETION(thread, dateTimeFormat);
1031 return operationResult.GetValue();
1032 }
1033
1034 // 3. Perform ? RequireInternalSlot(dateTimeFormat, [[InitializedDateTimeFormat]]).
1035 if (!dateTimeFormat->IsJSDateTimeFormat()) {
1036 THROW_TYPE_ERROR_AND_RETURN(thread, "is not JSDateTimeFormat",
1037 JSHandle<JSTaggedValue>(thread, JSTaggedValue::Exception()));
1038 }
1039
1040 // 4. Return dateTimeFormat.
1041 return dateTimeFormat;
1042 }
1043
ToHourCycleEcmaString(JSThread * thread,HourCycleOption hc)1044 JSHandle<JSTaggedValue> ToHourCycleEcmaString(JSThread *thread, HourCycleOption hc)
1045 {
1046 JSMutableHandle<JSTaggedValue> result(thread, JSTaggedValue::Undefined());
1047 auto globalConst = thread->GlobalConstants();
1048 switch (hc) {
1049 case HourCycleOption::H11:
1050 result.Update(globalConst->GetHandledH11String().GetTaggedValue());
1051 break;
1052 case HourCycleOption::H12:
1053 result.Update(globalConst->GetHandledH12String().GetTaggedValue());
1054 break;
1055 case HourCycleOption::H23:
1056 result.Update(globalConst->GetHandledH23String().GetTaggedValue());
1057 break;
1058 case HourCycleOption::H24:
1059 result.Update(globalConst->GetHandledH24String().GetTaggedValue());
1060 break;
1061 default:
1062 LOG_ECMA(FATAL) << "this branch is unreachable";
1063 UNREACHABLE();
1064 }
1065 return result;
1066 }
1067
ToDateTimeStyleEcmaString(JSThread * thread,DateTimeStyleOption style)1068 JSHandle<JSTaggedValue> ToDateTimeStyleEcmaString(JSThread *thread, DateTimeStyleOption style)
1069 {
1070 JSMutableHandle<JSTaggedValue> result(thread, JSTaggedValue::Undefined());
1071 auto globalConst = thread->GlobalConstants();
1072 switch (style) {
1073 case DateTimeStyleOption::FULL:
1074 result.Update(globalConst->GetHandledFullString().GetTaggedValue());
1075 break;
1076 case DateTimeStyleOption::LONG:
1077 result.Update(globalConst->GetHandledLongString().GetTaggedValue());
1078 break;
1079 case DateTimeStyleOption::MEDIUM:
1080 result.Update(globalConst->GetHandledMediumString().GetTaggedValue());
1081 break;
1082 case DateTimeStyleOption::SHORT:
1083 result.Update(globalConst->GetHandledShortString().GetTaggedValue());
1084 break;
1085 default:
1086 LOG_ECMA(FATAL) << "this branch is unreachable";
1087 UNREACHABLE();
1088 }
1089 return result;
1090 }
1091
1092 // 13.4.5 Intl.DateTimeFormat.prototype.resolvedOptions ()
ResolvedOptions(JSThread * thread,const JSHandle<JSDateTimeFormat> & dateTimeFormat,const JSHandle<JSObject> & options)1093 void JSDateTimeFormat::ResolvedOptions(JSThread *thread, const JSHandle<JSDateTimeFormat> &dateTimeFormat,
1094 const JSHandle<JSObject> &options)
1095 { // Table 8: Resolved Options of DateTimeFormat Instances
1096 // Internal Slot Property
1097 // [[Locale]] "locale"
1098 // [[Calendar]] "calendar"
1099 // [[NumberingSystem]] "numberingSystem"
1100 // [[TimeZone]] "timeZone"
1101 // [[HourCycle]] "hourCycle"
1102 // "hour12"
1103 // [[Weekday]] "weekday"
1104 // [[Era]] "era"
1105 // [[Year]] "year"
1106 // [[Month]] "month"
1107 // [[Day]] "day"
1108 // [[Hour]] "hour"
1109 // [[Minute]] "minute"
1110 // [[Second]] "second"
1111 // [[TimeZoneName]] "timeZoneName"
1112 auto globalConst = thread->GlobalConstants();
1113 ObjectFactory *factory = thread->GetEcmaVM()->GetFactory();
1114
1115 // 5. For each row of Table 8, except the header row, in table order, do
1116 // Let p be the Property value of the current row.
1117 // [[Locale]]
1118 JSHandle<JSTaggedValue> locale(thread, dateTimeFormat->GetLocale());
1119 JSHandle<JSTaggedValue> property = globalConst->GetHandledLocaleString();
1120 JSObject::CreateDataPropertyOrThrow(thread, options, property, locale);
1121 RETURN_IF_ABRUPT_COMPLETION(thread);
1122 // [[Calendar]]
1123 JSMutableHandle<JSTaggedValue> calendarValue(thread, dateTimeFormat->GetCalendar());
1124 icu::SimpleDateFormat *icuSimpleDateFormat = dateTimeFormat->GetIcuSimpleDateFormat();
1125 const icu::Calendar *calendar = icuSimpleDateFormat->getCalendar();
1126 std::string icuCalendar = calendar->getType();
1127 if (icuCalendar == "gregorian") {
1128 if (dateTimeFormat->GetIso8601().IsTrue()) {
1129 calendarValue.Update(globalConst->GetHandledIso8601String().GetTaggedValue());
1130 } else {
1131 calendarValue.Update(globalConst->GetHandledGregoryString().GetTaggedValue());
1132 }
1133 } else if (icuCalendar == "ethiopic-amete-alem") {
1134 calendarValue.Update(globalConst->GetHandledEthioaaString().GetTaggedValue());
1135 } else if (icuCalendar.length() != 0) {
1136 calendarValue.Update(factory->NewFromStdString(icuCalendar).GetTaggedValue());
1137 }
1138 property = globalConst->GetHandledCalendarString();
1139 JSObject::CreateDataPropertyOrThrow(thread, options, property, calendarValue);
1140 RETURN_IF_ABRUPT_COMPLETION(thread);
1141 // [[NumberingSystem]]
1142 JSHandle<JSTaggedValue> numberingSystem(thread, dateTimeFormat->GetNumberingSystem());
1143 if (numberingSystem->IsUndefined()) {
1144 numberingSystem = globalConst->GetHandledLatnString();
1145 }
1146 property = globalConst->GetHandledNumberingSystemString();
1147 JSObject::CreateDataPropertyOrThrow(thread, options, property, numberingSystem);
1148 RETURN_IF_ABRUPT_COMPLETION(thread);
1149 // [[TimeZone]]
1150 JSMutableHandle<JSTaggedValue> timezoneValue(thread, dateTimeFormat->GetTimeZone());
1151 const icu::TimeZone &icuTZ = calendar->getTimeZone();
1152 icu::UnicodeString timezone;
1153 icuTZ.getID(timezone);
1154 UErrorCode status = U_ZERO_ERROR;
1155 icu::UnicodeString canonicalTimezone;
1156 icu::TimeZone::getCanonicalID(timezone, canonicalTimezone, status);
1157 if (U_SUCCESS(status) != 0) {
1158 if ((canonicalTimezone == UNICODE_STRING_SIMPLE("Etc/UTC")) != 0 ||
1159 (canonicalTimezone == UNICODE_STRING_SIMPLE("Etc/GMT")) != 0) {
1160 timezoneValue.Update(globalConst->GetUTCString());
1161 } else {
1162 timezoneValue.Update(intl::LocaleHelper::UStringToString(thread, canonicalTimezone).GetTaggedValue());
1163 }
1164 }
1165 property = globalConst->GetHandledTimeZoneString();
1166 JSObject::CreateDataPropertyOrThrow(thread, options, property, timezoneValue);
1167 RETURN_IF_ABRUPT_COMPLETION(thread);
1168 // [[HourCycle]]
1169 // For web compatibility reasons, if the property "hourCycle" is set, the "hour12" property should be set to true
1170 // when "hourCycle" is "h11" or "h12", or to false when "hourCycle" is "h23" or "h24".
1171 // i. Let hc be dtf.[[HourCycle]].
1172 JSHandle<JSTaggedValue> hcValue;
1173 HourCycleOption hc = dateTimeFormat->GetHourCycle();
1174 if (hc != HourCycleOption::UNDEFINED) {
1175 property = globalConst->GetHandledHourCycleString();
1176 hcValue = ToHourCycleEcmaString(thread, dateTimeFormat->GetHourCycle());
1177 JSObject::CreateDataPropertyOrThrow(thread, options, property, hcValue);
1178 RETURN_IF_ABRUPT_COMPLETION(thread);
1179 if (hc == HourCycleOption::H11 || hc == HourCycleOption::H12) {
1180 JSHandle<JSTaggedValue> trueValue(thread, JSTaggedValue::True());
1181 hcValue = trueValue;
1182 } else if (hc == HourCycleOption::H23 || hc == HourCycleOption::H24) {
1183 JSHandle<JSTaggedValue> falseValue(thread, JSTaggedValue::False());
1184 hcValue = falseValue;
1185 }
1186 property = globalConst->GetHandledHour12String();
1187 JSObject::CreateDataPropertyOrThrow(thread, options, property, hcValue);
1188 RETURN_IF_ABRUPT_COMPLETION(thread);
1189 }
1190 // [[DateStyle]], [[TimeStyle]].
1191 if (dateTimeFormat->GetDateStyle() == DateTimeStyleOption::UNDEFINED &&
1192 dateTimeFormat->GetTimeStyle() == DateTimeStyleOption::UNDEFINED) {
1193 icu::UnicodeString patternUnicode;
1194 icuSimpleDateFormat->toPattern(patternUnicode);
1195 std::string pattern;
1196 patternUnicode.toUTF8String(pattern);
1197 for (const auto &item : BuildIcuPatternDescs()) {
1198 // fractionalSecondsDigits need to be added before timeZoneName.
1199 if (item.property == "timeZoneName") {
1200 int tmpResult = count(pattern.begin(), pattern.end(), 'S');
1201 int fsd = (tmpResult >= STRING_LENGTH_3) ? STRING_LENGTH_3 : tmpResult;
1202 if (fsd > 0) {
1203 JSHandle<JSTaggedValue> fsdValue(thread, JSTaggedValue(fsd));
1204 property = globalConst->GetHandledFractionalSecondDigitsString();
1205 JSObject::CreateDataPropertyOrThrow(thread, options, property, fsdValue);
1206 RETURN_IF_ABRUPT_COMPLETION(thread);
1207 }
1208 }
1209 for (const auto &pair : item.pairs) {
1210 if (pattern.find(pair.first) != std::string::npos) {
1211 hcValue = JSHandle<JSTaggedValue>::Cast(factory->NewFromStdString(pair.second));
1212 property = JSHandle<JSTaggedValue>::Cast(factory->NewFromStdString(item.property));
1213 JSObject::CreateDataPropertyOrThrow(thread, options, property, hcValue);
1214 RETURN_IF_ABRUPT_COMPLETION(thread);
1215 break;
1216 }
1217 }
1218 }
1219 }
1220 if (dateTimeFormat->GetDateStyle() != DateTimeStyleOption::UNDEFINED) {
1221 property = globalConst->GetHandledDateStyleString();
1222 hcValue = ToDateTimeStyleEcmaString(thread, dateTimeFormat->GetDateStyle());
1223 JSObject::CreateDataPropertyOrThrow(thread, options, property, hcValue);
1224 RETURN_IF_ABRUPT_COMPLETION(thread);
1225 }
1226 if (dateTimeFormat->GetTimeStyle() != DateTimeStyleOption::UNDEFINED) {
1227 property = globalConst->GetHandledTimeStyleString();
1228 hcValue = ToDateTimeStyleEcmaString(thread, dateTimeFormat->GetTimeStyle());
1229 JSObject::CreateDataPropertyOrThrow(thread, options, property, hcValue);
1230 RETURN_IF_ABRUPT_COMPLETION(thread);
1231 }
1232 }
1233
1234 // Use dateInterval(x, y) construct datetimeformatrange
ConstructDTFRange(JSThread * thread,const JSHandle<JSDateTimeFormat> & dtf,double x,double y)1235 icu::FormattedDateInterval JSDateTimeFormat::ConstructDTFRange(JSThread *thread, const JSHandle<JSDateTimeFormat> &dtf,
1236 double x, double y)
1237 {
1238 std::unique_ptr<icu::DateIntervalFormat> dateIntervalFormat(ConstructDateIntervalFormat(dtf));
1239 if (dateIntervalFormat == nullptr) {
1240 icu::FormattedDateInterval emptyValue;
1241 THROW_TYPE_ERROR_AND_RETURN(thread, "create dateIntervalFormat failed", emptyValue);
1242 }
1243 UErrorCode status = U_ZERO_ERROR;
1244 icu::DateInterval dateInterval(x, y);
1245 icu::FormattedDateInterval formatted = dateIntervalFormat->formatToValue(dateInterval, status);
1246 return formatted;
1247 }
1248
NormDateTimeRange(JSThread * thread,const JSHandle<JSDateTimeFormat> & dtf,double x,double y)1249 JSHandle<EcmaString> JSDateTimeFormat::NormDateTimeRange(JSThread *thread, const JSHandle<JSDateTimeFormat> &dtf,
1250 double x, double y)
1251 {
1252 ObjectFactory *factory = thread->GetEcmaVM()->GetFactory();
1253 JSHandle<EcmaString> result = factory->GetEmptyString();
1254 // 1. Let x be TimeClip(x).
1255 x = JSDate::TimeClip(x);
1256 // 2. If x is NaN, throw a RangeError exception.
1257 if (std::isnan(x)) {
1258 THROW_RANGE_ERROR_AND_RETURN(thread, "x is NaN", result);
1259 }
1260 // 3. Let y be TimeClip(y).
1261 y = JSDate::TimeClip(y);
1262 // 4. If y is NaN, throw a RangeError exception.
1263 if (std::isnan(y)) {
1264 THROW_RANGE_ERROR_AND_RETURN(thread, "y is NaN", result);
1265 }
1266
1267 icu::FormattedDateInterval formatted = ConstructDTFRange(thread, dtf, x, y);
1268 RETURN_HANDLE_IF_ABRUPT_COMPLETION(EcmaString, thread);
1269
1270 // Formatted to string.
1271 bool outputRange = false;
1272 UErrorCode status = U_ZERO_ERROR;
1273 icu::UnicodeString formatResult = formatted.toString(status);
1274 if (U_FAILURE(status) != 0) {
1275 THROW_TYPE_ERROR_AND_RETURN(thread, "format to string failed",
1276 thread->GetEcmaVM()->GetFactory()->GetEmptyString());
1277 }
1278 icu::ConstrainedFieldPosition cfpos;
1279 while (formatted.nextPosition(cfpos, status) != 0) {
1280 if (cfpos.getCategory() == UFIELD_CATEGORY_DATE_INTERVAL_SPAN) {
1281 outputRange = true;
1282 break;
1283 }
1284 }
1285 result = intl::LocaleHelper::UStringToString(thread, formatResult);
1286 if (!outputRange) {
1287 return FormatDateTime(thread, dtf, x);
1288 }
1289 return result;
1290 }
1291
NormDateTimeRangeToParts(JSThread * thread,const JSHandle<JSDateTimeFormat> & dtf,double x,double y)1292 JSHandle<JSArray> JSDateTimeFormat::NormDateTimeRangeToParts(JSThread *thread, const JSHandle<JSDateTimeFormat> &dtf,
1293 double x, double y)
1294 {
1295 JSHandle<JSArray> result(JSArray::ArrayCreate(thread, JSTaggedNumber(0)));
1296 RETURN_HANDLE_IF_ABRUPT_COMPLETION(JSArray, thread);
1297 // 1. Let x be TimeClip(x).
1298 x = JSDate::TimeClip(x);
1299 // 2. If x is NaN, throw a RangeError exception.
1300 if (std::isnan(x)) {
1301 THROW_RANGE_ERROR_AND_RETURN(thread, "x is invalid time value", result);
1302 }
1303 // 3. Let y be TimeClip(y).
1304 y = JSDate::TimeClip(y);
1305 // 4. If y is NaN, throw a RangeError exception.
1306 if (std::isnan(y)) {
1307 THROW_RANGE_ERROR_AND_RETURN(thread, "y is invalid time value", result);
1308 }
1309
1310 icu::FormattedDateInterval formatted = ConstructDTFRange(thread, dtf, x, y);
1311 RETURN_HANDLE_IF_ABRUPT_COMPLETION(JSArray, thread);
1312 return ConstructFDateIntervalToJSArray(thread, formatted);
1313 }
1314
GainAvailableLocales(JSThread * thread)1315 JSHandle<TaggedArray> JSDateTimeFormat::GainAvailableLocales(JSThread *thread)
1316 {
1317 JSHandle<GlobalEnv> env = thread->GetEcmaVM()->GetGlobalEnv();
1318 JSHandle<JSTaggedValue> dateTimeFormatLocales = env->GetDateTimeFormatLocales();
1319 const char *key = "calendar";
1320 const char *path = nullptr;
1321 if (dateTimeFormatLocales->IsUndefined()) {
1322 std::vector<std::string> availableStringLocales = intl::LocaleHelper::GetAvailableLocales(thread, key, path);
1323 JSHandle<TaggedArray> availableLocales = JSLocale::ConstructLocaleList(thread, availableStringLocales);
1324 env->SetDateTimeFormatLocales(thread, availableLocales);
1325 return availableLocales;
1326 }
1327 return JSHandle<TaggedArray>::Cast(dateTimeFormatLocales);
1328 }
1329
ConstructFDateIntervalToJSArray(JSThread * thread,const icu::FormattedDateInterval & formatted)1330 JSHandle<JSArray> JSDateTimeFormat::ConstructFDateIntervalToJSArray(JSThread *thread,
1331 const icu::FormattedDateInterval &formatted)
1332 {
1333 UErrorCode status = U_ZERO_ERROR;
1334 icu::UnicodeString formattedValue = formatted.toTempString(status);
1335 // Let result be ArrayCreate(0).
1336 JSHandle<JSArray> array(JSArray::ArrayCreate(thread, JSTaggedNumber(0)));
1337 RETURN_HANDLE_IF_ABRUPT_COMPLETION(JSArray, thread);
1338 // Let index be 0.
1339 int index = 0;
1340 int32_t preEndPos = 0;
1341 // 2: number of elements
1342 std::array<int32_t, 2> begin {};
1343 std::array<int32_t, 2> end {}; // 2: number of elements
1344 begin[0] = begin[1] = end[0] = end[1] = 0;
1345 std::vector<CommonDateFormatPart> parts;
1346
1347 /**
1348 * From ICU header file document @unumberformatter.h
1349 * Sets a constraint on the field category.
1350 *
1351 * When this instance of ConstrainedFieldPosition is passed to FormattedValue#nextPosition,
1352 * positions are skipped unless they have the given category.
1353 *
1354 * Any previously set constraints are cleared.
1355 *
1356 * For example, to loop over only the number-related fields:
1357 *
1358 * ConstrainedFieldPosition cfpo;
1359 * cfpo.constrainCategory(UFIELDCATEGORY_NUMBER_FORMAT);
1360 * while (fmtval.nextPosition(cfpo, status)) {
1361 * // handle the number-related field position
1362 * }
1363 */
1364 JSMutableHandle<EcmaString> substring(thread, JSTaggedValue::Undefined());
1365 icu::ConstrainedFieldPosition cfpos;
1366 while (formatted.nextPosition(cfpos, status)) {
1367 int32_t fCategory = cfpos.getCategory();
1368 int32_t fField = cfpos.getField();
1369 int32_t fStart = cfpos.getStart();
1370 int32_t fLimit = cfpos.getLimit();
1371
1372 // 2 means the number of elements in category
1373 if (fCategory == UFIELD_CATEGORY_DATE_INTERVAL_SPAN && (fField == 0 || fField == 1)) {
1374 begin[fField] = fStart;
1375 end[fField] = fLimit;
1376 }
1377 if (fCategory == UFIELD_CATEGORY_DATE) {
1378 if (preEndPos < fStart) {
1379 parts.emplace_back(CommonDateFormatPart(fField, preEndPos, fStart, index, true));
1380 index++;
1381 }
1382 parts.emplace_back(CommonDateFormatPart(fField, fStart, fLimit, index, false));
1383 preEndPos = fLimit;
1384 ++index;
1385 }
1386 }
1387 if (U_FAILURE(status) != 0) {
1388 THROW_TYPE_ERROR_AND_RETURN(thread, "format date interval error", array);
1389 }
1390 int32_t length = formattedValue.length();
1391 if (length > preEndPos) {
1392 parts.emplace_back(CommonDateFormatPart(-1, preEndPos, length, index, true));
1393 }
1394 for (auto part : parts) {
1395 substring.Update(intl::LocaleHelper::UStringToString(thread, formattedValue, part.fBeginIndex,
1396 part.fEndIndex).GetTaggedValue());
1397 RETURN_HANDLE_IF_ABRUPT_COMPLETION(JSArray, thread);
1398 JSHandle<JSObject> element;
1399 if (part.isPreExist) {
1400 element = JSLocale::PutElement(thread, part.index, array, ConvertFieldIdToDateType(thread, -1),
1401 JSHandle<JSTaggedValue>::Cast(substring));
1402 } else {
1403 element = JSLocale::PutElement(thread, part.index, array, ConvertFieldIdToDateType(thread, part.fField),
1404 JSHandle<JSTaggedValue>::Cast(substring));
1405 }
1406 RETURN_HANDLE_IF_ABRUPT_COMPLETION(JSArray, thread);
1407 JSHandle<JSTaggedValue> value = JSHandle<JSTaggedValue>::Cast(
1408 ToValueString(thread, TrackValue(part.fBeginIndex, part.fEndIndex, begin, end)));
1409 JSObject::SetProperty(thread, element, thread->GlobalConstants()->GetHandledSourceString(), value, true);
1410 RETURN_HANDLE_IF_ABRUPT_COMPLETION(JSArray, thread);
1411 }
1412 return array;
1413 }
1414
TrackValue(int32_t beginning,int32_t ending,std::array<int32_t,2> begin,std::array<int32_t,2> end)1415 Value JSDateTimeFormat::TrackValue(int32_t beginning, int32_t ending,
1416 std::array<int32_t, 2> begin, std::array<int32_t, 2> end) // 2: number of elements
1417 {
1418 Value value = Value::SHARED;
1419 if ((begin[0] <= beginning) && (beginning <= end[0]) && (begin[0] <= ending) && (ending <= end[0])) {
1420 value = Value::START_RANGE;
1421 } else if ((begin[1] <= beginning) && (beginning <= end[1]) && (begin[1] <= ending) && (ending <= end[1])) {
1422 value = Value::END_RANGE;
1423 }
1424 return value;
1425 }
1426
BuildIcuPatternDescs()1427 std::vector<IcuPatternDesc> BuildIcuPatternDescs()
1428 {
1429 static const std::vector<IcuPatternDesc> items = {
1430 IcuPatternDesc("weekday", ICU_WEEKDAY_PE, ICU_NARROW_LONG_SHORT),
1431 IcuPatternDesc("era", ICU_ERA_PE, ICU_NARROW_LONG_SHORT),
1432 IcuPatternDesc("year", ICU_YEAR_PE, ICU2_DIGIT_NUMERIC),
1433 IcuPatternDesc("month", ICU_MONTH_PE, ICU_NARROW_LONG_SHORT2_DIGIT_NUMERIC),
1434 IcuPatternDesc("day", ICU_DAY_PE, ICU2_DIGIT_NUMERIC),
1435 IcuPatternDesc("dayPeriod", ICU_DAY_PERIOD_PE, ICU_NARROW_LONG_SHORT),
1436 IcuPatternDesc("hour", ICU_HOUR_PE, ICU2_DIGIT_NUMERIC),
1437 IcuPatternDesc("minute", ICU_MINUTE_PE, ICU2_DIGIT_NUMERIC),
1438 IcuPatternDesc("second", ICU_SECOND_PE, ICU2_DIGIT_NUMERIC),
1439 IcuPatternDesc("timeZoneName", ICU_YIME_ZONE_NAME_PE, ICU_LONG_SHORT)
1440 };
1441 return items;
1442 }
1443
InitializePattern(const IcuPatternDesc & hourData)1444 std::vector<IcuPatternDesc> InitializePattern(const IcuPatternDesc &hourData)
1445 {
1446 std::vector<IcuPatternDesc> result;
1447 std::vector<IcuPatternDesc> items = BuildIcuPatternDescs();
1448 std::vector<IcuPatternDesc>::iterator item = items.begin();
1449 while (item != items.end()) {
1450 if (item->property != "hour") {
1451 result.emplace_back(IcuPatternDesc(item->property, item->pairs, item->allowedValues));
1452 } else {
1453 result.emplace_back(hourData);
1454 }
1455 ++item;
1456 }
1457 return result;
1458 }
1459
GetIcuPatternDesc(const HourCycleOption & hourCycle)1460 std::vector<IcuPatternDesc> JSDateTimeFormat::GetIcuPatternDesc(const HourCycleOption &hourCycle)
1461 {
1462 if (hourCycle == HourCycleOption::H11) {
1463 Pattern h11("KK", "K");
1464 return h11.Get();
1465 } else if (hourCycle == HourCycleOption::H12) {
1466 Pattern h12("hh", "h");
1467 return h12.Get();
1468 } else if (hourCycle == HourCycleOption::H23) {
1469 Pattern h23("HH", "H");
1470 return h23.Get();
1471 } else if (hourCycle == HourCycleOption::H24) {
1472 Pattern h24("kk", "k");
1473 return h24.Get();
1474 } else if (hourCycle == HourCycleOption::UNDEFINED) {
1475 Pattern pattern("jj", "j");
1476 return pattern.Get();
1477 }
1478 LOG_ECMA(FATAL) << "this branch is unreachable";
1479 UNREACHABLE();
1480 }
1481
ChangeHourCyclePattern(const icu::UnicodeString & pattern,HourCycleOption hc)1482 icu::UnicodeString JSDateTimeFormat::ChangeHourCyclePattern(const icu::UnicodeString &pattern, HourCycleOption hc)
1483 {
1484 if (hc == HourCycleOption::UNDEFINED || hc == HourCycleOption::EXCEPTION) {
1485 return pattern;
1486 }
1487 icu::UnicodeString result;
1488 char16_t key = u'\0';
1489 auto mapIter = std::find_if(HOUR_CYCLE_MAP.begin(), HOUR_CYCLE_MAP.end(),
1490 [hc](const std::map<char16_t, HourCycleOption>::value_type item) {
1491 return item.second == hc;
1492 });
1493 if (mapIter != HOUR_CYCLE_MAP.end()) {
1494 key = mapIter->first;
1495 }
1496 bool needChange = true;
1497 char16_t last = u'\0';
1498 for (int32_t i = 0; i < pattern.length(); i++) {
1499 char16_t ch = pattern.charAt(i);
1500 if (ch == '\'') {
1501 needChange = !needChange;
1502 result.append(ch);
1503 } else if (HOUR_CYCLE_MAP.find(ch) != HOUR_CYCLE_MAP.end()) {
1504 result = (needChange && last == u'd') ? result.append(' ') : result;
1505 result.append(needChange ? key : ch);
1506 } else {
1507 result.append(ch);
1508 }
1509 last = ch;
1510 }
1511 return result;
1512 }
1513
CreateICUSimpleDateFormat(const icu::Locale & icuLocale,const icu::UnicodeString & skeleton,icu::DateTimePatternGenerator * gn,HourCycleOption hc)1514 std::unique_ptr<icu::SimpleDateFormat> JSDateTimeFormat::CreateICUSimpleDateFormat(const icu::Locale &icuLocale,
1515 const icu::UnicodeString &skeleton,
1516 icu::DateTimePatternGenerator *gn,
1517 HourCycleOption hc)
1518 {
1519 // See https://github.com/tc39/ecma402/issues/225
1520 UErrorCode status = U_ZERO_ERROR;
1521 icu::UnicodeString pattern = ChangeHourCyclePattern(
1522 gn->getBestPattern(skeleton, UDATPG_MATCH_HOUR_FIELD_LENGTH, status), hc);
1523 ASSERT_PRINT((U_SUCCESS(status) != 0), "get best pattern failed");
1524
1525 status = U_ZERO_ERROR;
1526 auto dateFormat(std::make_unique<icu::SimpleDateFormat>(pattern, icuLocale, status));
1527 if (U_FAILURE(status) != 0) {
1528 return std::unique_ptr<icu::SimpleDateFormat>();
1529 }
1530 ASSERT_PRINT(dateFormat != nullptr, "dateFormat failed");
1531 return dateFormat;
1532 }
1533
BuildCalendar(const icu::Locale & locale,const icu::TimeZone & timeZone)1534 std::unique_ptr<icu::Calendar> JSDateTimeFormat::BuildCalendar(const icu::Locale &locale, const icu::TimeZone &timeZone)
1535 {
1536 UErrorCode status = U_ZERO_ERROR;
1537 std::unique_ptr<icu::Calendar> calendar(icu::Calendar::createInstance(timeZone, locale, status));
1538 if (U_FAILURE(status) || calendar == nullptr) {
1539 return nullptr;
1540 }
1541 ASSERT_PRINT(U_SUCCESS(status), "buildCalendar failed");
1542 ASSERT_PRINT(calendar.get() != nullptr, "calendar is nullptr");
1543
1544 /**
1545 * Return the class ID for this class.
1546 *
1547 * This is useful only for comparing to a return value from getDynamicClassID(). For example:
1548 *
1549 * Base* polymorphic_pointer = createPolymorphicObject();
1550 * if (polymorphic_pointer->getDynamicClassID() ==
1551 * Derived::getStaticClassID()) ...
1552 */
1553 if (calendar->getDynamicClassID() == icu::GregorianCalendar::getStaticClassID()) {
1554 auto gregorianCalendar = static_cast<icu::GregorianCalendar *>(calendar.get());
1555 // ECMAScript start time, value = -(2**53)
1556 const double beginTime = -9007199254740992;
1557 gregorianCalendar->setGregorianChange(beginTime, status);
1558 ASSERT(U_SUCCESS(status));
1559 }
1560 return calendar;
1561 }
1562
ConstructTimeZone(const std::string & timezone)1563 std::unique_ptr<icu::TimeZone> JSDateTimeFormat::ConstructTimeZone(const std::string &timezone)
1564 {
1565 if (timezone.empty()) {
1566 return std::unique_ptr<icu::TimeZone>();
1567 }
1568 std::string canonicalized = ConstructFormattedTimeZoneID(timezone);
1569
1570 std::unique_ptr<icu::TimeZone> tz(icu::TimeZone::createTimeZone(canonicalized.c_str()));
1571 if (!JSLocale::IsValidTimeZoneName(*tz)) {
1572 return std::unique_ptr<icu::TimeZone>();
1573 }
1574 return tz;
1575 }
1576
GetSpecialTimeZoneMap()1577 std::map<std::string, std::string> JSDateTimeFormat::GetSpecialTimeZoneMap()
1578 {
1579 std::vector<std::string> specialTimeZones = {
1580 "America/Argentina/ComodRivadavia",
1581 "America/Knox_IN",
1582 "Antarctica/McMurdo",
1583 "Australia/ACT",
1584 "Australia/LHI",
1585 "Australia/NSW",
1586 "Antarctica/DumontDUrville",
1587 "Brazil/DeNoronha",
1588 "CET",
1589 "CST6CDT",
1590 "Chile/EasterIsland",
1591 "EET",
1592 "EST",
1593 "EST5EDT",
1594 "GB",
1595 "GB-Eire",
1596 "HST",
1597 "MET",
1598 "MST",
1599 "MST7MDT",
1600 "Mexico/BajaNorte",
1601 "Mexico/BajaSur",
1602 "NZ",
1603 "NZ-CHAT",
1604 "PRC",
1605 "PST8PDT",
1606 "ROC",
1607 "ROK",
1608 "UCT",
1609 "W-SU",
1610 "WET"};
1611 std::map<std::string, std::string> map;
1612 for (const auto &item : specialTimeZones) {
1613 std::string upper(item);
1614 transform(upper.begin(), upper.end(), upper.begin(), toupper);
1615 map.emplace(upper, item);
1616 }
1617 return map;
1618 }
1619
ConstructFormattedTimeZoneID(const std::string & input)1620 std::string JSDateTimeFormat::ConstructFormattedTimeZoneID(const std::string &input)
1621 {
1622 std::string result = input;
1623 transform(result.begin(), result.end(), result.begin(), toupper);
1624 std::map<std::string, std::string> map = JSDateTimeFormat::GetSpecialTimeZoneMap();
1625 auto it = map.find(result);
1626 if (it != map.end()) {
1627 return it->second;
1628 }
1629 static const std::vector<std::string> tzStyleEntry = {
1630 "GMT", "ETC/UTC", "ETC/UCT", "GMT0", "ETC/GMT", "GMT+0", "GMT-0"
1631 };
1632 if (result.find("SYSTEMV/") == 0) {
1633 result.replace(0, STRING_LENGTH_8, "SystemV/");
1634 } else if (result.find("US/") == 0) {
1635 result = (result.length() == STRING_LENGTH_3) ? result : "US/" + ToTitleCaseTimezonePosition(
1636 input.substr(STRING_LENGTH_3));
1637 } else if (result.find("ETC/GMT") == 0 && result.length() > STRING_LENGTH_7) {
1638 result = ConstructGMTTimeZoneID(input);
1639 } else if (count(tzStyleEntry.begin(), tzStyleEntry.end(), result)) {
1640 result = "UTC";
1641 } else if (result.length() == STRING_LENGTH_3) {
1642 return result;
1643 } else {
1644 return ToTitleCaseTimezonePosition(result);
1645 }
1646
1647 return result;
1648 }
1649
ToTitleCaseFunction(const std::string & input)1650 std::string JSDateTimeFormat::ToTitleCaseFunction(const std::string &input)
1651 {
1652 std::string result(input);
1653 transform(result.begin(), result.end(), result.begin(), tolower);
1654 result[0] = static_cast<int8_t>(toupper(result[0]));
1655 return result;
1656 }
1657
ToTitleCaseTimezonePosition(const std::string & input)1658 std::string JSDateTimeFormat::ToTitleCaseTimezonePosition(const std::string &input)
1659 {
1660 std::vector<std::string> titleEntry;
1661 std::vector<std::string> charEntry;
1662 uint32_t leftPosition = 0;
1663 uint32_t titleLength = 0;
1664 for (size_t i = 0; i < input.length(); i++) {
1665 if (input[i] == '_' || input[i] == '-' || input[i] == '/') {
1666 std::string s(1, input[i]);
1667 charEntry.emplace_back(s);
1668 titleLength = i - leftPosition;
1669 titleEntry.emplace_back(input.substr(leftPosition, titleLength));
1670 leftPosition = i + 1;
1671 } else if (JSLocale::IsAsciiAlpha(input[i]) || input[i] == '\\') {
1672 continue;
1673 } else {
1674 return std::string();
1675 }
1676 }
1677 ASSERT(input.length() >= static_cast<size_t>(leftPosition));
1678 titleEntry.emplace_back(input.substr(leftPosition, input.length() - leftPosition));
1679 std::string result;
1680 size_t len = titleEntry.size();
1681 if (len == 0) {
1682 return ToTitleCaseFunction(input);
1683 }
1684 for (size_t i = 0; i < len - 1; i++) {
1685 std::string titleValue = ToTitleCaseFunction(titleEntry[i]);
1686 if (titleValue == "Of" || titleValue == "Es" || titleValue == "Au") {
1687 titleValue[0] = static_cast<int8_t>(tolower(titleValue[0]));
1688 }
1689 result = result + titleValue + charEntry[i];
1690 }
1691 result = result + ToTitleCaseFunction(titleEntry[len - 1]);
1692 return result;
1693 }
1694
ConstructGMTTimeZoneID(const std::string & input)1695 std::string JSDateTimeFormat::ConstructGMTTimeZoneID(const std::string &input)
1696 {
1697 if (input.length() < STRING_LENGTH_8 || input.length() > STRING_LENGTH_10) {
1698 return "";
1699 }
1700 std::string ret = "Etc/GMT";
1701 int timeZoneOffsetFlag = 7; // The offset of time zone flag, to match RegExp starting with the correct string
1702 if (regex_match(input.substr(timeZoneOffsetFlag), std::regex("[+-][1][0-4]")) ||
1703 (regex_match(input.substr(timeZoneOffsetFlag), std::regex("[+-][0-9]")) ||
1704 input.substr(timeZoneOffsetFlag) == "0")) {
1705 return ret + input.substr(timeZoneOffsetFlag);
1706 }
1707 return "";
1708 }
1709
ToHourCycleString(HourCycleOption hc)1710 std::string JSDateTimeFormat::ToHourCycleString(HourCycleOption hc)
1711 {
1712 auto mapIter = std::find_if(TO_HOUR_CYCLE_MAP.begin(), TO_HOUR_CYCLE_MAP.end(),
1713 [hc](const std::map<std::string, HourCycleOption>::value_type item) {
1714 return item.second == hc;
1715 });
1716 if (mapIter != TO_HOUR_CYCLE_MAP.end()) {
1717 return mapIter->first;
1718 }
1719 return "";
1720 }
1721
OptionToHourCycle(const std::string & hc)1722 HourCycleOption JSDateTimeFormat::OptionToHourCycle(const std::string &hc)
1723 {
1724 auto iter = TO_HOUR_CYCLE_MAP.find(hc);
1725 if (iter != TO_HOUR_CYCLE_MAP.end()) {
1726 return iter->second;
1727 }
1728 return HourCycleOption::UNDEFINED;
1729 }
1730
OptionToHourCycle(UDateFormatHourCycle hc)1731 HourCycleOption JSDateTimeFormat::OptionToHourCycle(UDateFormatHourCycle hc)
1732 {
1733 HourCycleOption hcOption = HourCycleOption::UNDEFINED;
1734 switch (hc) {
1735 case UDAT_HOUR_CYCLE_11:
1736 hcOption = HourCycleOption::H11;
1737 break;
1738 case UDAT_HOUR_CYCLE_12:
1739 hcOption = HourCycleOption::H12;
1740 break;
1741 case UDAT_HOUR_CYCLE_23:
1742 hcOption = HourCycleOption::H23;
1743 break;
1744 case UDAT_HOUR_CYCLE_24:
1745 hcOption = HourCycleOption::H24;
1746 break;
1747 default:
1748 LOG_ECMA(FATAL) << "this branch is unreachable";
1749 UNREACHABLE();
1750 }
1751 return hcOption;
1752 }
1753
ConvertFieldIdToDateType(JSThread * thread,int32_t fieldId)1754 JSHandle<JSTaggedValue> JSDateTimeFormat::ConvertFieldIdToDateType(JSThread *thread, int32_t fieldId)
1755 {
1756 JSMutableHandle<JSTaggedValue> result(thread, JSTaggedValue::Undefined());
1757 auto globalConst = thread->GlobalConstants();
1758 if (fieldId == -1) {
1759 result.Update(globalConst->GetHandledLiteralString().GetTaggedValue());
1760 } else if (fieldId == UDAT_YEAR_FIELD || fieldId == UDAT_EXTENDED_YEAR_FIELD) {
1761 result.Update(globalConst->GetHandledYearString().GetTaggedValue());
1762 } else if (fieldId == UDAT_YEAR_NAME_FIELD) {
1763 result.Update(globalConst->GetHandledYearNameString().GetTaggedValue());
1764 } else if (fieldId == UDAT_MONTH_FIELD || fieldId == UDAT_STANDALONE_MONTH_FIELD) {
1765 result.Update(globalConst->GetHandledMonthString().GetTaggedValue());
1766 } else if (fieldId == UDAT_DATE_FIELD) {
1767 result.Update(globalConst->GetHandledDayString().GetTaggedValue());
1768 } else if (fieldId == UDAT_HOUR_OF_DAY1_FIELD ||
1769 fieldId == UDAT_HOUR_OF_DAY0_FIELD || fieldId == UDAT_HOUR1_FIELD || fieldId == UDAT_HOUR0_FIELD) {
1770 result.Update(globalConst->GetHandledHourString().GetTaggedValue());
1771 } else if (fieldId == UDAT_MINUTE_FIELD) {
1772 result.Update(globalConst->GetHandledMinuteString().GetTaggedValue());
1773 } else if (fieldId == UDAT_SECOND_FIELD) {
1774 result.Update(globalConst->GetHandledSecondString().GetTaggedValue());
1775 } else if (fieldId == UDAT_DAY_OF_WEEK_FIELD || fieldId == UDAT_DOW_LOCAL_FIELD ||
1776 fieldId == UDAT_STANDALONE_DAY_FIELD) {
1777 result.Update(globalConst->GetHandledWeekdayString().GetTaggedValue());
1778 } else if (fieldId == UDAT_AM_PM_FIELD || fieldId == UDAT_AM_PM_MIDNIGHT_NOON_FIELD ||
1779 fieldId == UDAT_FLEXIBLE_DAY_PERIOD_FIELD) {
1780 result.Update(globalConst->GetHandledDayPeriodString().GetTaggedValue());
1781 } else if (fieldId == UDAT_TIMEZONE_FIELD || fieldId == UDAT_TIMEZONE_RFC_FIELD ||
1782 fieldId == UDAT_TIMEZONE_GENERIC_FIELD || fieldId == UDAT_TIMEZONE_SPECIAL_FIELD ||
1783 fieldId == UDAT_TIMEZONE_LOCALIZED_GMT_OFFSET_FIELD || fieldId == UDAT_TIMEZONE_ISO_FIELD ||
1784 fieldId == UDAT_TIMEZONE_ISO_LOCAL_FIELD) {
1785 result.Update(globalConst->GetHandledTimeZoneNameString().GetTaggedValue());
1786 } else if (fieldId == UDAT_ERA_FIELD) {
1787 result.Update(globalConst->GetHandledEraString().GetTaggedValue());
1788 } else if (fieldId == UDAT_FRACTIONAL_SECOND_FIELD) {
1789 result.Update(globalConst->GetHandledFractionalSecondString().GetTaggedValue());
1790 } else if (fieldId == UDAT_RELATED_YEAR_FIELD) {
1791 result.Update(globalConst->GetHandledRelatedYearString().GetTaggedValue());
1792 } else if (fieldId == UDAT_QUARTER_FIELD || fieldId == UDAT_STANDALONE_QUARTER_FIELD) {
1793 LOG_ECMA(FATAL) << "this branch is unreachable";
1794 UNREACHABLE();
1795 }
1796 return result;
1797 }
1798
ConstructDateIntervalFormat(const JSHandle<JSDateTimeFormat> & dtf)1799 std::unique_ptr<icu::DateIntervalFormat> JSDateTimeFormat::ConstructDateIntervalFormat(
1800 const JSHandle<JSDateTimeFormat> &dtf)
1801 {
1802 icu::SimpleDateFormat *icuSimpleDateFormat = dtf->GetIcuSimpleDateFormat();
1803 icu::Locale locale = *(dtf->GetIcuLocale());
1804 std::string hcString = ToHourCycleString(dtf->GetHourCycle());
1805 UErrorCode status = U_ZERO_ERROR;
1806 // Sets the Unicode value for a Unicode keyword.
1807 if (!hcString.empty()) {
1808 locale.setUnicodeKeywordValue("hc", hcString, status);
1809 }
1810 icu::UnicodeString pattern;
1811 // Return a pattern string describing this date format.
1812 pattern = icuSimpleDateFormat->toPattern(pattern);
1813 // Utility to return a unique skeleton from a given pattern.
1814 icu::UnicodeString skeleton = icu::DateTimePatternGenerator::staticGetSkeleton(pattern, status);
1815 // Construct a DateIntervalFormat from skeleton and a given locale.
1816 std::unique_ptr<icu::DateIntervalFormat> dateIntervalFormat(
1817 icu::DateIntervalFormat::createInstance(skeleton, locale, status));
1818 if (U_FAILURE(status)) {
1819 return nullptr;
1820 }
1821 dateIntervalFormat->setTimeZone(icuSimpleDateFormat->getTimeZone());
1822 return dateIntervalFormat;
1823 }
1824 } // namespace panda::ecmascript
1825