js-date-time-format.cc 83.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
// Copyright 2018 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef V8_INTL_SUPPORT
#error Internationalization is expected to be enabled.
#endif  // V8_INTL_SUPPORT

#include "src/objects/js-date-time-format.h"

11 12
#include <algorithm>
#include <map>
13 14
#include <memory>
#include <string>
15
#include <utility>
16 17
#include <vector>

Yang Guo's avatar
Yang Guo committed
18
#include "src/date/date.h"
19
#include "src/execution/isolate.h"
20 21 22
#include "src/heap/factory.h"
#include "src/objects/intl-objects.h"
#include "src/objects/js-date-time-format-inl.h"
23
#include "src/objects/managed-inl.h"
24
#include "src/objects/option-utils.h"
25
#include "unicode/calendar.h"
26
#include "unicode/dtitvfmt.h"
27
#include "unicode/dtptngen.h"
28
#include "unicode/fieldpos.h"
29
#include "unicode/gregocal.h"
30 31 32 33 34 35 36 37
#include "unicode/smpdtfmt.h"
#include "unicode/unistr.h"

namespace v8 {
namespace internal {

namespace {

38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
std::string ToHourCycleString(JSDateTimeFormat::HourCycle hc) {
  switch (hc) {
    case JSDateTimeFormat::HourCycle::kH11:
      return "h11";
    case JSDateTimeFormat::HourCycle::kH12:
      return "h12";
    case JSDateTimeFormat::HourCycle::kH23:
      return "h23";
    case JSDateTimeFormat::HourCycle::kH24:
      return "h24";
    case JSDateTimeFormat::HourCycle::kUndefined:
      return "";
    default:
      UNREACHABLE();
  }
}

55 56 57 58 59 60 61 62
JSDateTimeFormat::HourCycle ToHourCycle(const std::string& hc) {
  if (hc == "h11") return JSDateTimeFormat::HourCycle::kH11;
  if (hc == "h12") return JSDateTimeFormat::HourCycle::kH12;
  if (hc == "h23") return JSDateTimeFormat::HourCycle::kH23;
  if (hc == "h24") return JSDateTimeFormat::HourCycle::kH24;
  return JSDateTimeFormat::HourCycle::kUndefined;
}

63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
JSDateTimeFormat::HourCycle ToHourCycle(UDateFormatHourCycle hc) {
  switch (hc) {
    case UDAT_HOUR_CYCLE_11:
      return JSDateTimeFormat::HourCycle::kH11;
    case UDAT_HOUR_CYCLE_12:
      return JSDateTimeFormat::HourCycle::kH12;
    case UDAT_HOUR_CYCLE_23:
      return JSDateTimeFormat::HourCycle::kH23;
    case UDAT_HOUR_CYCLE_24:
      return JSDateTimeFormat::HourCycle::kH24;
    default:
      return JSDateTimeFormat::HourCycle::kUndefined;
  }
}

78 79
Maybe<JSDateTimeFormat::HourCycle> GetHourCycle(Isolate* isolate,
                                                Handle<JSReceiver> options,
80
                                                const char* method_name) {
81
  return GetStringOption<JSDateTimeFormat::HourCycle>(
82
      isolate, options, "hourCycle", method_name, {"h11", "h12", "h23", "h24"},
83 84 85 86 87
      {JSDateTimeFormat::HourCycle::kH11, JSDateTimeFormat::HourCycle::kH12,
       JSDateTimeFormat::HourCycle::kH23, JSDateTimeFormat::HourCycle::kH24},
      JSDateTimeFormat::HourCycle::kUndefined);
}

88 89 90
class PatternMap {
 public:
  PatternMap(std::string pattern, std::string value)
91
      : pattern(std::move(pattern)), value(std::move(value)) {}
92
  virtual ~PatternMap() = default;
93 94 95 96 97 98 99
  std::string pattern;
  std::string value;
};

class PatternItem {
 public:
  PatternItem(const std::string property, std::vector<PatternMap> pairs,
100
              std::vector<const char*> allowed_values)
101 102 103
      : property(std::move(property)),
        pairs(std::move(pairs)),
        allowed_values(allowed_values) {}
104
  virtual ~PatternItem() = default;
105 106 107 108 109

  const std::string property;
  // It is important for the pattern in the pairs from longer one to shorter one
  // if the longer one contains substring of an shorter one.
  std::vector<PatternMap> pairs;
110
  std::vector<const char*> allowed_values;
111 112
};

113
static std::vector<PatternItem> BuildPatternItems() {
114 115 116 117
  const std::vector<const char*> kLongShort = {"long", "short"};
  const std::vector<const char*> kNarrowLongShort = {"narrow", "long", "short"};
  const std::vector<const char*> k2DigitNumeric = {"2-digit", "numeric"};
  const std::vector<const char*> kNarrowLongShort2DigitNumeric = {
118
      "narrow", "long", "short", "2-digit", "numeric"};
119
  std::vector<PatternItem> items = {
120
      PatternItem("weekday",
121 122 123 124 125 126
                  {{"EEEEE", "narrow"},
                   {"EEEE", "long"},
                   {"EEE", "short"},
                   {"ccccc", "narrow"},
                   {"cccc", "long"},
                   {"ccc", "short"}},
127
                  kNarrowLongShort),
128 129
      PatternItem("era",
                  {{"GGGGG", "narrow"}, {"GGGG", "long"}, {"GGG", "short"}},
130
                  kNarrowLongShort),
131
      PatternItem("year", {{"yy", "2-digit"}, {"y", "numeric"}},
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
                  k2DigitNumeric)};
  // Sometimes we get L instead of M for month - standalone name.
  items.push_back(PatternItem("month",
                              {{"MMMMM", "narrow"},
                               {"MMMM", "long"},
                               {"MMM", "short"},
                               {"MM", "2-digit"},
                               {"M", "numeric"},
                               {"LLLLL", "narrow"},
                               {"LLLL", "long"},
                               {"LLL", "short"},
                               {"LL", "2-digit"},
                               {"L", "numeric"}},
                              kNarrowLongShort2DigitNumeric));
  items.push_back(PatternItem("day", {{"dd", "2-digit"}, {"d", "numeric"}},
                              k2DigitNumeric));
148 149 150 151 152 153 154 155
  items.push_back(PatternItem("dayPeriod",
                              {{"BBBBB", "narrow"},
                               {"bbbbb", "narrow"},
                               {"BBBB", "long"},
                               {"bbbb", "long"},
                               {"B", "short"},
                               {"b", "short"}},
                              kNarrowLongShort));
156 157 158 159 160 161 162 163 164 165 166 167 168 169
  items.push_back(PatternItem("hour",
                              {{"HH", "2-digit"},
                               {"H", "numeric"},
                               {"hh", "2-digit"},
                               {"h", "numeric"},
                               {"kk", "2-digit"},
                               {"k", "numeric"},
                               {"KK", "2-digit"},
                               {"K", "numeric"}},
                              k2DigitNumeric));
  items.push_back(PatternItem("minute", {{"mm", "2-digit"}, {"m", "numeric"}},
                              k2DigitNumeric));
  items.push_back(PatternItem("second", {{"ss", "2-digit"}, {"s", "numeric"}},
                              k2DigitNumeric));
170 171 172 173 174 175 176 177 178 179 180 181

    const std::vector<const char*> kTimezone = {"long",        "short",
                                                "longOffset",  "shortOffset",
                                                "longGeneric", "shortGeneric"};
    items.push_back(PatternItem("timeZoneName",
                                {{"zzzz", "long"},
                                 {"z", "short"},
                                 {"OOOO", "longOffset"},
                                 {"O", "shortOffset"},
                                 {"vvvv", "longGeneric"},
                                 {"v", "shortGeneric"}},
                                kTimezone));
Frank Tang's avatar
Frank Tang committed
182
    return items;
183 184
}

185 186 187
class PatternItems {
 public:
  PatternItems() : data(BuildPatternItems()) {}
188
  virtual ~PatternItems() = default;
189 190 191 192 193 194 195 196 197 198 199 200
  const std::vector<PatternItem>& Get() const { return data; }

 private:
  const std::vector<PatternItem> data;
};

static const std::vector<PatternItem>& GetPatternItems() {
  static base::LazyInstance<PatternItems>::type items =
      LAZY_INSTANCE_INITIALIZER;
  return items.Pointer()->Get();
}

201 202 203
class PatternData {
 public:
  PatternData(const std::string property, std::vector<PatternMap> pairs,
204
              std::vector<const char*> allowed_values)
205
      : property(std::move(property)), allowed_values(allowed_values) {
206 207 208 209
    for (const auto& pair : pairs) {
      map.insert(std::make_pair(pair.value, pair.pattern));
    }
  }
210
  virtual ~PatternData() = default;
211 212 213

  const std::string property;
  std::map<const std::string, const std::string> map;
214
  std::vector<const char*> allowed_values;
215 216
};

217
const std::vector<PatternData> CreateCommonData(const PatternData& hour_data) {
218
  std::vector<PatternData> build;
219 220 221 222
  for (const PatternItem& item : GetPatternItems()) {
    if (item.property == "hour") {
      build.push_back(hour_data);
    } else {
223 224 225 226 227 228 229
      build.push_back(
          PatternData(item.property, item.pairs, item.allowed_values));
    }
  }
  return build;
}

230 231
const std::vector<PatternData> CreateData(const char* digit2,
                                          const char* numeric) {
232 233 234
  return CreateCommonData(
      PatternData("hour", {{digit2, "2-digit"}, {numeric, "numeric"}},
                  {"2-digit", "numeric"}));
235 236
}

237 238 239 240 241 242 243 244 245 246 247
// According to "Date Field Symbol Table" in
// http://userguide.icu-project.org/formatparse/datetime
// Symbol | Meaning              | Example(s)
//   h      hour in am/pm (1~12)    h    7
//                                  hh   07
//   H      hour in day (0~23)      H    0
//                                  HH   00
//   k      hour in day (1~24)      k    24
//                                  kk   24
//   K      hour in am/pm (0~11)    K    0
//                                  KK   00
248 249 250 251

class Pattern {
 public:
  Pattern(const char* d1, const char* d2) : data(CreateData(d1, d2)) {}
252
  virtual ~Pattern() = default;
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
  virtual const std::vector<PatternData>& Get() const { return data; }

 private:
  std::vector<PatternData> data;
};

#define DEFFINE_TRAIT(name, d1, d2)              \
  struct name {                                  \
    static void Construct(void* allocated_ptr) { \
      new (allocated_ptr) Pattern(d1, d2);       \
    }                                            \
  };
DEFFINE_TRAIT(H11Trait, "KK", "K")
DEFFINE_TRAIT(H12Trait, "hh", "h")
DEFFINE_TRAIT(H23Trait, "HH", "H")
DEFFINE_TRAIT(H24Trait, "kk", "k")
DEFFINE_TRAIT(HDefaultTrait, "jj", "j")
#undef DEFFINE_TRAIT

272 273
const std::vector<PatternData>& GetPatternData(
    JSDateTimeFormat::HourCycle hour_cycle) {
274
  switch (hour_cycle) {
275
    case JSDateTimeFormat::HourCycle::kH11: {
276 277 278 279
      static base::LazyInstance<Pattern, H11Trait>::type h11 =
          LAZY_INSTANCE_INITIALIZER;
      return h11.Pointer()->Get();
    }
280
    case JSDateTimeFormat::HourCycle::kH12: {
281 282 283 284
      static base::LazyInstance<Pattern, H12Trait>::type h12 =
          LAZY_INSTANCE_INITIALIZER;
      return h12.Pointer()->Get();
    }
285
    case JSDateTimeFormat::HourCycle::kH23: {
286 287 288 289
      static base::LazyInstance<Pattern, H23Trait>::type h23 =
          LAZY_INSTANCE_INITIALIZER;
      return h23.Pointer()->Get();
    }
290
    case JSDateTimeFormat::HourCycle::kH24: {
291 292 293 294
      static base::LazyInstance<Pattern, H24Trait>::type h24 =
          LAZY_INSTANCE_INITIALIZER;
      return h24.Pointer()->Get();
    }
295
    case JSDateTimeFormat::HourCycle::kUndefined: {
296 297 298 299
      static base::LazyInstance<Pattern, HDefaultTrait>::type hDefault =
          LAZY_INSTANCE_INITIALIZER;
      return hDefault.Pointer()->Get();
    }
300 301
    default:
      UNREACHABLE();
302 303 304
  }
}

305
std::string GetGMTTzID(const std::string& input) {
306 307 308 309 310 311 312
  std::string ret = "Etc/GMT";
  switch (input.length()) {
    case 8:
      if (input[7] == '0') return ret + '0';
      break;
    case 9:
      if ((input[7] == '+' || input[7] == '-') &&
313
          base::IsInRange(input[8], '0', '9')) {
314 315 316 317 318
        return ret + input[7] + input[8];
      }
      break;
    case 10:
      if ((input[7] == '+' || input[7] == '-') && (input[8] == '1') &&
319
          base::IsInRange(input[9], '0', '4')) {
320 321 322 323 324 325 326 327 328 329
        return ret + input[7] + input[8] + input[9];
      }
      break;
  }
  return "";
}

// Locale independenty version of isalpha for ascii range. This will return
// false if the ch is alpha but not in ascii range.
bool IsAsciiAlpha(char ch) {
330
  return base::IsInRange(ch, 'A', 'Z') || base::IsInRange(ch, 'a', 'z');
331 332 333 334 335
}

// Locale independent toupper for ascii range. This will not return İ (dotted I)
// for i under Turkish locale while std::toupper may.
char LocaleIndependentAsciiToUpper(char ch) {
336
  return (base::IsInRange(ch, 'a', 'z')) ? (ch - 'a' + 'A') : ch;
337 338 339 340
}

// Locale independent tolower for ascii range.
char LocaleIndependentAsciiToLower(char ch) {
341
  return (base::IsInRange(ch, 'A', 'Z')) ? (ch - 'A' + 'a') : ch;
342 343 344 345 346 347 348
}

// Returns titlecased location, bueNos_airES -> Buenos_Aires
// or ho_cHi_minH -> Ho_Chi_Minh. It is locale-agnostic and only
// deals with ASCII only characters.
// 'of', 'au' and 'es' are special-cased and lowercased.
// ICU's timezone parsing is case sensitive, but ECMAScript is case insensitive
349
std::string ToTitleCaseTimezoneLocation(const std::string& input) {
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
  std::string title_cased;
  int word_length = 0;
  for (char ch : input) {
    // Convert first char to upper case, the rest to lower case
    if (IsAsciiAlpha(ch)) {
      title_cased += word_length == 0 ? LocaleIndependentAsciiToUpper(ch)
                                      : LocaleIndependentAsciiToLower(ch);
      word_length++;
    } else if (ch == '_' || ch == '-' || ch == '/') {
      // Special case Au/Es/Of to be lower case.
      if (word_length == 2) {
        size_t pos = title_cased.length() - 2;
        std::string substr = title_cased.substr(pos, 2);
        if (substr == "Of" || substr == "Es" || substr == "Au") {
          title_cased[pos] = LocaleIndependentAsciiToLower(title_cased[pos]);
        }
      }
      title_cased += ch;
      word_length = 0;
    } else {
      // Invalid input
      return std::string();
    }
  }
374

375 376 377
  return title_cased;
}

378 379 380 381 382
class SpecialTimeZoneMap {
 public:
  SpecialTimeZoneMap() {
    Add("America/Argentina/ComodRivadavia");
    Add("America/Knox_IN");
383
    Add("Antarctica/DumontDUrville");
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416
    Add("Antarctica/McMurdo");
    Add("Australia/ACT");
    Add("Australia/LHI");
    Add("Australia/NSW");
    Add("Brazil/DeNoronha");
    Add("Chile/EasterIsland");
    Add("GB");
    Add("GB-Eire");
    Add("Mexico/BajaNorte");
    Add("Mexico/BajaSur");
    Add("NZ");
    Add("NZ-CHAT");
    Add("W-SU");
  }

  std::string Find(const std::string& id) {
    auto it = map_.find(id);
    if (it != map_.end()) {
      return it->second;
    }
    return "";
  }

 private:
  void Add(const char* id) {
    std::string upper(id);
    transform(upper.begin(), upper.end(), upper.begin(),
              LocaleIndependentAsciiToUpper);
    map_.insert({upper, id});
  }
  std::map<std::string, std::string> map_;
};

417 418
}  // namespace

419 420
// Return the time zone id which match ICU's expectation of title casing
// return empty string when error.
421
std::string JSDateTimeFormat::CanonicalizeTimeZoneID(const std::string& input) {
422 423 424
  std::string upper = input;
  transform(upper.begin(), upper.end(), upper.begin(),
            LocaleIndependentAsciiToUpper);
425 426 427 428 429 430 431 432
  if (upper.length() == 3) {
    if (upper == "GMT") return "UTC";
    // For id such as "CET", return upper case.
    return upper;
  } else if (upper.length() == 7 && '0' <= upper[3] && upper[3] <= '9') {
    // For id such as "CST6CDT", return upper case.
    return upper;
  } else if (upper.length() > 3) {
433 434 435 436 437 438 439 440
    if (memcmp(upper.c_str(), "ETC", 3) == 0) {
      if (upper == "ETC/UTC" || upper == "ETC/GMT" || upper == "ETC/UCT") {
        return "UTC";
      }
      if (strncmp(upper.c_str(), "ETC/GMT", 7) == 0) {
        return GetGMTTzID(input);
      }
    } else if (memcmp(upper.c_str(), "GMT", 3) == 0) {
441
      if (upper == "GMT0" || upper == "GMT+0" || upper == "GMT-0") {
442 443 444 445
        return "UTC";
      }
    } else if (memcmp(upper.c_str(), "US/", 3) == 0) {
      std::string title = ToTitleCaseTimezoneLocation(input);
446 447 448 449
      if (title.length() >= 2) {
        // Change "Us/" to "US/"
        title[1] = 'S';
      }
450
      return title;
451
    } else if (strncmp(upper.c_str(), "SYSTEMV/", 8) == 0) {
452 453
      upper.replace(0, 8, "SystemV/");
      return upper;
454
    }
455 456
  }
  // We expect only _, '-' and / beside ASCII letters.
457 458 459 460 461 462 463

  static base::LazyInstance<SpecialTimeZoneMap>::type special_time_zone_map =
      LAZY_INSTANCE_INITIALIZER;

  std::string special_case = special_time_zone_map.Pointer()->Find(upper);
  if (!special_case.empty()) {
    return special_case;
464
  }
465
  return ToTitleCaseTimezoneLocation(input);
466 467
}

468
namespace {
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
Handle<String> DateTimeStyleAsString(Isolate* isolate,
                                     JSDateTimeFormat::DateTimeStyle style) {
  switch (style) {
    case JSDateTimeFormat::DateTimeStyle::kFull:
      return ReadOnlyRoots(isolate).full_string_handle();
    case JSDateTimeFormat::DateTimeStyle::kLong:
      return ReadOnlyRoots(isolate).long_string_handle();
    case JSDateTimeFormat::DateTimeStyle::kMedium:
      return ReadOnlyRoots(isolate).medium_string_handle();
    case JSDateTimeFormat::DateTimeStyle::kShort:
      return ReadOnlyRoots(isolate).short_string_handle();
    case JSDateTimeFormat::DateTimeStyle::kUndefined:
      UNREACHABLE();
  }
}

485 486 487 488 489 490 491 492 493 494
int FractionalSecondDigitsFromPattern(const std::string& pattern) {
  int result = 0;
  for (size_t i = 0; i < pattern.length() && result < 3; i++) {
    if (pattern[i] == 'S') {
      result++;
    }
  }
  return result;
}

495 496
}  // namespace

497 498
Handle<Object> JSDateTimeFormat::TimeZoneId(Isolate* isolate,
                                            const icu::TimeZone& tz) {
499 500 501
  Factory* factory = isolate->factory();
  icu::UnicodeString time_zone;
  tz.getID(time_zone);
502
  UErrorCode status = U_ZERO_ERROR;
503
  icu::UnicodeString canonical_time_zone;
504
  icu::TimeZone::getCanonicalID(time_zone, canonical_time_zone, status);
505
  Handle<Object> timezone_value;
506
  if (U_SUCCESS(status)) {
507 508 509 510 511
    // In CLDR (http://unicode.org/cldr/trac/ticket/9943), Etc/UTC is made
    // a separate timezone ID from Etc/GMT even though they're still the same
    // timezone. We have Etc/UTC because 'UTC', 'Etc/Universal',
    // 'Etc/Zulu' and others are turned to 'Etc/UTC' by ICU. Etc/GMT comes
    // from Etc/GMT0, Etc/GMT+0, Etc/GMT-0, Etc/Greenwich.
512
    // ecma402#sec-canonicalizetimezonename step 3
513 514
    if (canonical_time_zone == UNICODE_STRING_SIMPLE("Etc/UTC") ||
        canonical_time_zone == UNICODE_STRING_SIMPLE("Etc/GMT")) {
515
      timezone_value = factory->UTC_string();
516
    } else {
517 518 519
      ASSIGN_RETURN_ON_EXCEPTION_VALUE(
          isolate, timezone_value, Intl::ToString(isolate, canonical_time_zone),
          Handle<Object>());
520 521 522
    }
  } else {
    // Somehow on Windows we will reach here.
523
    timezone_value = factory->undefined_value();
524
  }
525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594
  return timezone_value;
}

namespace {
Handle<String> GetCalendar(Isolate* isolate,
                           const icu::SimpleDateFormat& simple_date_format,
                           bool is_alt_calendar = false) {
  // getType() returns legacy calendar type name instead of LDML/BCP47 calendar
  // key values. intl.js maps them to BCP47 values for key "ca".
  // TODO(jshin): Consider doing it here, instead.
  std::string calendar_str = simple_date_format.getCalendar()->getType();

  // Maps ICU calendar names to LDML/BCP47 types for key 'ca'.
  // See typeMap section in third_party/icu/source/data/misc/keyTypeData.txt
  // and
  // http://www.unicode.org/repos/cldr/tags/latest/common/bcp47/calendar.xml
  if (calendar_str == "gregorian") {
    if (is_alt_calendar) {
      calendar_str = "iso8601";
    } else {
      calendar_str = "gregory";
    }
  } else if (calendar_str == "ethiopic-amete-alem") {
    calendar_str = "ethioaa";
  } else if (calendar_str == "islamic") {
    if (is_alt_calendar) {
      calendar_str = "islamic-rgsa";
    }
  }
  return isolate->factory()->NewStringFromAsciiChecked(calendar_str.c_str());
}

Handle<Object> GetTimeZone(Isolate* isolate,
                           const icu::SimpleDateFormat& simple_date_format) {
  return JSDateTimeFormat::TimeZoneId(
      isolate, simple_date_format.getCalendar()->getTimeZone());
}
}  // namespace

Handle<String> JSDateTimeFormat::Calendar(
    Isolate* isolate, Handle<JSDateTimeFormat> date_time_format) {
  return GetCalendar(isolate,
                     *(date_time_format->icu_simple_date_format().raw()),
                     date_time_format->alt_calendar());
}

Handle<Object> JSDateTimeFormat::TimeZone(
    Isolate* isolate, Handle<JSDateTimeFormat> date_time_format) {
  return GetTimeZone(isolate,
                     *(date_time_format->icu_simple_date_format().raw()));
}

// ecma402 #sec-intl.datetimeformat.prototype.resolvedoptions
MaybeHandle<JSObject> JSDateTimeFormat::ResolvedOptions(
    Isolate* isolate, Handle<JSDateTimeFormat> date_time_format) {
  Factory* factory = isolate->factory();
  // 4. Let options be ! ObjectCreate(%ObjectPrototype%).
  Handle<JSObject> options = factory->NewJSObject(isolate->object_function());

  Handle<Object> resolved_obj;

  Handle<String> locale = Handle<String>(date_time_format->locale(), isolate);
  DCHECK(!date_time_format->icu_locale().is_null());
  DCHECK_NOT_NULL(date_time_format->icu_locale().raw());
  icu::Locale* icu_locale = date_time_format->icu_locale().raw();

  icu::SimpleDateFormat* icu_simple_date_format =
      date_time_format->icu_simple_date_format().raw();
  Handle<Object> timezone =
      JSDateTimeFormat::TimeZone(isolate, date_time_format);
595

596 597 598 599
  // Ugly hack. ICU doesn't expose numbering system in any way, so we have
  // to assume that for given locale NumberingSystem constructor produces the
  // same digits as NumberFormat/Calendar would.
  // Tracked by https://unicode-org.atlassian.net/browse/ICU-13431
600
  std::string numbering_system = Intl::GetNumberingSystem(*icu_locale);
601

602 603 604 605
  icu::UnicodeString pattern_unicode;
  icu_simple_date_format->toPattern(pattern_unicode);
  std::string pattern;
  pattern_unicode.toUTF8String(pattern);
606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623

  // 5. For each row of Table 6, except the header row, in table order, do
  // Table 6: Resolved Options of DateTimeFormat Instances
  //  Internal Slot          Property
  //    [[Locale]]           "locale"
  //    [[Calendar]]         "calendar"
  //    [[NumberingSystem]]  "numberingSystem"
  //    [[TimeZone]]         "timeZone"
  //    [[HourCycle]]        "hourCycle"
  //                         "hour12"
  //    [[Weekday]]          "weekday"
  //    [[Era]]              "era"
  //    [[Year]]             "year"
  //    [[Month]]            "month"
  //    [[Day]]              "day"
  //    [[Hour]]             "hour"
  //    [[Minute]]           "minute"
  //    [[Second]]           "second"
624
  //    [[FractionalSecondDigits]]     "fractionalSecondDigits"
625
  //    [[TimeZoneName]]     "timeZoneName"
Frank Tang's avatar
Frank Tang committed
626 627 628 629 630
  Maybe<bool> maybe_create_locale = JSReceiver::CreateDataProperty(
      isolate, options, factory->locale_string(), locale, Just(kDontThrow));
  DCHECK(maybe_create_locale.FromJust());
  USE(maybe_create_locale);

631 632
  Handle<String> calendar =
      JSDateTimeFormat::Calendar(isolate, date_time_format);
Frank Tang's avatar
Frank Tang committed
633
  Maybe<bool> maybe_create_calendar = JSReceiver::CreateDataProperty(
634
      isolate, options, factory->calendar_string(), calendar, Just(kDontThrow));
Frank Tang's avatar
Frank Tang committed
635 636 637
  DCHECK(maybe_create_calendar.FromJust());
  USE(maybe_create_calendar);

638
  if (!numbering_system.empty()) {
Frank Tang's avatar
Frank Tang committed
639 640 641 642 643 644 645 646
    Maybe<bool> maybe_create_numbering_system = JSReceiver::CreateDataProperty(
        isolate, options, factory->numberingSystem_string(),
        factory->NewStringFromAsciiChecked(numbering_system.c_str()),
        Just(kDontThrow));
    DCHECK(maybe_create_numbering_system.FromJust());
    USE(maybe_create_numbering_system);
  }
  Maybe<bool> maybe_create_time_zone = JSReceiver::CreateDataProperty(
647
      isolate, options, factory->timeZone_string(), timezone, Just(kDontThrow));
Frank Tang's avatar
Frank Tang committed
648 649
  DCHECK(maybe_create_time_zone.FromJust());
  USE(maybe_create_time_zone);
650 651

  // 5.b.i. Let hc be dtf.[[HourCycle]].
652
  HourCycle hc = date_time_format->hour_cycle();
653

654
  if (hc != HourCycle::kUndefined) {
Frank Tang's avatar
Frank Tang committed
655 656 657 658 659
    Maybe<bool> maybe_create_hour_cycle = JSReceiver::CreateDataProperty(
        isolate, options, factory->hourCycle_string(),
        date_time_format->HourCycleAsString(), Just(kDontThrow));
    DCHECK(maybe_create_hour_cycle.FromJust());
    USE(maybe_create_hour_cycle);
660 661
    switch (hc) {
      //  ii. If hc is "h11" or "h12", let v be true.
662
      case HourCycle::kH11:
Frank Tang's avatar
Frank Tang committed
663 664 665 666 667 668 669
      case HourCycle::kH12: {
        Maybe<bool> maybe_create_hour12 = JSReceiver::CreateDataProperty(
            isolate, options, factory->hour12_string(), factory->true_value(),
            Just(kDontThrow));
        DCHECK(maybe_create_hour12.FromJust());
        USE(maybe_create_hour12);
      } break;
670
      // iii. Else if, hc is "h23" or "h24", let v be false.
671
      case HourCycle::kH23:
Frank Tang's avatar
Frank Tang committed
672 673 674 675 676 677 678
      case HourCycle::kH24: {
        Maybe<bool> maybe_create_hour12 = JSReceiver::CreateDataProperty(
            isolate, options, factory->hour12_string(), factory->false_value(),
            Just(kDontThrow));
        DCHECK(maybe_create_hour12.FromJust());
        USE(maybe_create_hour12);
      } break;
679
      // iv. Else, let v be undefined.
680
      case HourCycle::kUndefined:
681 682
        break;
    }
683 684
  }

685 686 687 688 689 690
  // If dateStyle and timeStyle are undefined, then internal slots
  // listed in "Table 1: Components of date and time formats" will be set
  // in Step 33.f.iii.1 of InitializeDateTimeFormat
  if (date_time_format->date_style() == DateTimeStyle::kUndefined &&
      date_time_format->time_style() == DateTimeStyle::kUndefined) {
    for (const auto& item : GetPatternItems()) {
691 692 693 694 695 696 697 698 699 700 701 702
      // fractionalSecondsDigits need to be added before timeZoneName
      if (item.property == "timeZoneName") {
        int fsd = FractionalSecondDigitsFromPattern(pattern);
        if (fsd > 0) {
          Maybe<bool> maybe_create_fractional_seconds_digits =
              JSReceiver::CreateDataProperty(
                  isolate, options, factory->fractionalSecondDigits_string(),
                  factory->NewNumberFromInt(fsd), Just(kDontThrow));
          DCHECK(maybe_create_fractional_seconds_digits.FromJust());
          USE(maybe_create_fractional_seconds_digits);
        }
      }
703 704
      for (const auto& pair : item.pairs) {
        if (pattern.find(pair.pattern) != std::string::npos) {
Frank Tang's avatar
Frank Tang committed
705 706 707 708 709 710 711
          Maybe<bool> maybe_create_property = JSReceiver::CreateDataProperty(
              isolate, options,
              factory->NewStringFromAsciiChecked(item.property.c_str()),
              factory->NewStringFromAsciiChecked(pair.value.c_str()),
              Just(kDontThrow));
          DCHECK(maybe_create_property.FromJust());
          USE(maybe_create_property);
712 713
          break;
        }
714 715 716 717
      }
    }
  }

718 719
  // dateStyle
  if (date_time_format->date_style() != DateTimeStyle::kUndefined) {
Frank Tang's avatar
Frank Tang committed
720 721 722 723 724 725
    Maybe<bool> maybe_create_date_style = JSReceiver::CreateDataProperty(
        isolate, options, factory->dateStyle_string(),
        DateTimeStyleAsString(isolate, date_time_format->date_style()),
        Just(kDontThrow));
    DCHECK(maybe_create_date_style.FromJust());
    USE(maybe_create_date_style);
726 727 728 729
  }

  // timeStyle
  if (date_time_format->time_style() != DateTimeStyle::kUndefined) {
Frank Tang's avatar
Frank Tang committed
730 731 732 733 734 735
    Maybe<bool> maybe_create_time_style = JSReceiver::CreateDataProperty(
        isolate, options, factory->timeStyle_string(),
        DateTimeStyleAsString(isolate, date_time_format->time_style()),
        Just(kDontThrow));
    DCHECK(maybe_create_time_style.FromJust());
    USE(maybe_create_time_style);
736
  }
737 738 739
  return options;
}

740 741 742 743 744
namespace {

// ecma402/#sec-formatdatetime
// FormatDateTime( dateTimeFormat, x )
MaybeHandle<String> FormatDateTime(Isolate* isolate,
745
                                   const icu::SimpleDateFormat& date_format,
746 747 748 749 750 751 752 753
                                   double x) {
  double date_value = DateCache::TimeClip(x);
  if (std::isnan(date_value)) {
    THROW_NEW_ERROR(isolate, NewRangeError(MessageTemplate::kInvalidTimeValue),
                    String);
  }

  icu::UnicodeString result;
754
  date_format.format(date_value, result);
755

756
  return Intl::ToString(isolate, result);
757 758 759 760 761 762 763
}

}  // namespace

// ecma402/#sec-datetime-format-functions
// DateTime Format Functions
MaybeHandle<String> JSDateTimeFormat::DateTimeFormat(
764
    Isolate* isolate, Handle<JSDateTimeFormat> date_time_format,
765 766 767 768 769 770 771 772 773 774 775 776 777 778
    Handle<Object> date) {
  // 2. Assert: Type(dtf) is Object and dtf has an [[InitializedDateTimeFormat]]
  // internal slot.

  // 3. If date is not provided or is undefined, then
  double x;
  if (date->IsUndefined()) {
    // 3.a Let x be Call(%Date_now%, undefined).
    x = JSDate::CurrentTimeValue(isolate);
  } else {
    // 4. Else,
    //    a. Let x be ? ToNumber(date).
    ASSIGN_RETURN_ON_EXCEPTION(isolate, date, Object::ToNumber(isolate, date),
                               String);
Frank Tang's avatar
Frank Tang committed
779
    DCHECK(date->IsNumber());
780 781 782
    x = date->Number();
  }
  // 5. Return FormatDateTime(dtf, x).
783
  icu::SimpleDateFormat* format =
784
      date_time_format->icu_simple_date_format().raw();
785
  return FormatDateTime(isolate, *format, x);
786 787 788 789 790 791 792 793 794 795 796 797 798
}

namespace {
Isolate::ICUObjectCacheType ConvertToCacheType(
    JSDateTimeFormat::DefaultsOption type) {
  switch (type) {
    case JSDateTimeFormat::DefaultsOption::kDate:
      return Isolate::ICUObjectCacheType::kDefaultSimpleDateFormatForDate;
    case JSDateTimeFormat::DefaultsOption::kTime:
      return Isolate::ICUObjectCacheType::kDefaultSimpleDateFormatForTime;
    case JSDateTimeFormat::DefaultsOption::kAll:
      return Isolate::ICUObjectCacheType::kDefaultSimpleDateFormat;
  }
799
}
800
}  // namespace
801 802 803

MaybeHandle<String> JSDateTimeFormat::ToLocaleDateTime(
    Isolate* isolate, Handle<Object> date, Handle<Object> locales,
804
    Handle<Object> options, RequiredOption required, DefaultsOption defaults,
805
    const char* method_name) {
806 807
  Isolate::ICUObjectCacheType cache_type = ConvertToCacheType(defaults);

808 809 810 811 812
  Factory* factory = isolate->factory();
  // 1. Let x be ? thisTimeValue(this value);
  if (!date->IsJSDate()) {
    THROW_NEW_ERROR(isolate,
                    NewTypeError(MessageTemplate::kMethodInvokedOnWrongType,
813
                                 factory->Date_string()),
814 815 816
                    String);
  }

817
  double const x = Handle<JSDate>::cast(date)->value().Number();
818 819
  // 2. If x is NaN, return "Invalid Date"
  if (std::isnan(x)) {
820
    return factory->Invalid_Date_string();
821 822
  }

823 824 825 826 827
  // We only cache the instance when locales is a string/undefined and
  // options is undefined, as that is the only case when the specified
  // side-effects of examining those arguments are unobservable.
  bool can_cache = (locales->IsString() || locales->IsUndefined(isolate)) &&
                   options->IsUndefined(isolate);
828 829 830 831
  if (can_cache) {
    // Both locales and options are undefined, check the cache.
    icu::SimpleDateFormat* cached_icu_simple_date_format =
        static_cast<icu::SimpleDateFormat*>(
832
            isolate->get_cached_icu_object(cache_type, locales));
833 834 835 836
    if (cached_icu_simple_date_format != nullptr) {
      return FormatDateTime(isolate, *cached_icu_simple_date_format, x);
    }
  }
837 838 839 840 841 842 843
  // 3. Let options be ? ToDateTimeOptions(options, required, defaults).
  Handle<JSObject> internal_options;
  ASSIGN_RETURN_ON_EXCEPTION(
      isolate, internal_options,
      ToDateTimeOptions(isolate, options, required, defaults), String);

  // 4. Let dateFormat be ? Construct(%DateTimeFormat%, « locales, options »).
844
  Handle<JSFunction> constructor = Handle<JSFunction>(
845 846
      JSFunction::cast(
          isolate->context().native_context().intl_date_time_format_function()),
847
      isolate);
848
  Handle<Map> map;
849
  ASSIGN_RETURN_ON_EXCEPTION(
850 851
      isolate, map,
      JSFunction::GetDerivedMap(isolate, constructor, constructor), String);
852 853 854
  Handle<JSDateTimeFormat> date_time_format;
  ASSIGN_RETURN_ON_EXCEPTION(
      isolate, date_time_format,
855 856
      JSDateTimeFormat::New(isolate, map, locales, internal_options,
                            method_name),
857
      String);
858

859 860
  if (can_cache) {
    isolate->set_icu_object_in_cache(
861 862 863
        cache_type, locales,
        std::static_pointer_cast<icu::UMemory>(
            date_time_format->icu_simple_date_format().get()));
864
  }
865
  // 5. Return FormatDateTime(dateFormat, x).
866
  icu::SimpleDateFormat* format =
867
      date_time_format->icu_simple_date_format().raw();
868
  return FormatDateTime(isolate, *format, x);
869 870 871 872 873
}

namespace {

Maybe<bool> IsPropertyUndefined(Isolate* isolate, Handle<JSObject> options,
874
                                Handle<String> property) {
875 876 877 878
  // i. Let prop be the property name.
  // ii. Let value be ? Get(options, prop).
  Handle<Object> value;
  ASSIGN_RETURN_ON_EXCEPTION_VALUE(
879
      isolate, value, Object::GetPropertyOrElement(isolate, options, property),
880 881 882 883 884
      Nothing<bool>());
  return Just(value->IsUndefined(isolate));
}

Maybe<bool> NeedsDefault(Isolate* isolate, Handle<JSObject> options,
885
                         const std::vector<Handle<String>>& props) {
886 887 888 889
  bool needs_default = true;
  for (const auto& prop : props) {
    //  i. Let prop be the property name.
    // ii. Let value be ? Get(options, prop)
890
    Maybe<bool> maybe_undefined = IsPropertyUndefined(isolate, options, prop);
891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907
    MAYBE_RETURN(maybe_undefined, Nothing<bool>());
    // iii. If value is not undefined, let needDefaults be false.
    if (!maybe_undefined.FromJust()) {
      needs_default = false;
    }
  }
  return Just(needs_default);
}

Maybe<bool> CreateDefault(Isolate* isolate, Handle<JSObject> options,
                          const std::vector<std::string>& props) {
  Factory* factory = isolate->factory();
  // i. Perform ? CreateDataPropertyOrThrow(options, prop, "numeric").
  for (const auto& prop : props) {
    MAYBE_RETURN(
        JSReceiver::CreateDataProperty(
            isolate, options, factory->NewStringFromAsciiChecked(prop.c_str()),
908
            factory->numeric_string(), Just(kThrowOnError)),
909 910 911 912 913 914 915 916 917
        Nothing<bool>());
  }
  return Just(true);
}

}  // namespace

// ecma-402/#sec-todatetimeoptions
MaybeHandle<JSObject> JSDateTimeFormat::ToDateTimeOptions(
918 919
    Isolate* isolate, Handle<Object> input_options, RequiredOption required,
    DefaultsOption defaults) {
920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940
  Factory* factory = isolate->factory();
  // 1. If options is undefined, let options be null; otherwise let options be ?
  //    ToObject(options).
  Handle<JSObject> options;
  if (input_options->IsUndefined(isolate)) {
    options = factory->NewJSObjectWithNullProto();
  } else {
    Handle<JSReceiver> options_obj;
    ASSIGN_RETURN_ON_EXCEPTION(isolate, options_obj,
                               Object::ToObject(isolate, input_options),
                               JSObject);
    // 2. Let options be ObjectCreate(options).
    ASSIGN_RETURN_ON_EXCEPTION(isolate, options,
                               JSObject::ObjectCreate(isolate, options_obj),
                               JSObject);
  }

  // 3. Let needDefaults be true.
  bool needs_default = true;

  // 4. If required is "date" or "any", then
941
  if (required == RequiredOption::kAny || required == RequiredOption::kDate) {
942
    // a. For each of the property names "weekday", "year", "month",
943 944 945 946 947
    // "day", do
    std::vector<Handle<String>> list(
        {factory->weekday_string(), factory->year_string()});
    list.push_back(factory->month_string());
    list.push_back(factory->day_string());
948 949 950 951 952 953
    Maybe<bool> maybe_needs_default = NeedsDefault(isolate, options, list);
    MAYBE_RETURN(maybe_needs_default, Handle<JSObject>());
    needs_default = maybe_needs_default.FromJust();
  }

  // 5. If required is "time" or "any", then
954
  if (required == RequiredOption::kAny || required == RequiredOption::kTime) {
955 956 957
    // a. For each of the property names "dayPeriod", "hour", "minute",
    // "second", "fractionalSecondDigits", do
    std::vector<Handle<String>> list;
958
    list.push_back(factory->dayPeriod_string());
959 960 961
    list.push_back(factory->hour_string());
    list.push_back(factory->minute_string());
    list.push_back(factory->second_string());
962
    list.push_back(factory->fractionalSecondDigits_string());
963 964 965 966 967
    Maybe<bool> maybe_needs_default = NeedsDefault(isolate, options, list);
    MAYBE_RETURN(maybe_needs_default, Handle<JSObject>());
    needs_default &= maybe_needs_default.FromJust();
  }

968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005
  // 6. Let dateStyle be ? Get(options, "dateStyle").
  Maybe<bool> maybe_datestyle_undefined =
      IsPropertyUndefined(isolate, options, factory->dateStyle_string());
  MAYBE_RETURN(maybe_datestyle_undefined, Handle<JSObject>());
  // 7. Let timeStyle be ? Get(options, "timeStyle").
  Maybe<bool> maybe_timestyle_undefined =
      IsPropertyUndefined(isolate, options, factory->timeStyle_string());
  MAYBE_RETURN(maybe_timestyle_undefined, Handle<JSObject>());
  // 8. If dateStyle is not undefined or timeStyle is not undefined, let
  // needDefaults be false.
  if (!maybe_datestyle_undefined.FromJust() ||
      !maybe_timestyle_undefined.FromJust()) {
    needs_default = false;
  }
  // 9. If required is "date" and timeStyle is not undefined,
  if (required == RequiredOption::kDate &&
      !maybe_timestyle_undefined.FromJust()) {
    //  a. Throw a TypeError exception.
    THROW_NEW_ERROR(
        isolate,
        NewTypeError(MessageTemplate::kInvalid,
                     factory->NewStringFromStaticChars("option"),
                     factory->NewStringFromStaticChars("timeStyle")),
        JSObject);
  }
  // 10. If required is "time" and dateStyle is not undefined,
  if (required == RequiredOption::kTime &&
      !maybe_datestyle_undefined.FromJust()) {
    //  a. Throw a TypeError exception.
    THROW_NEW_ERROR(
        isolate,
        NewTypeError(MessageTemplate::kInvalid,
                     factory->NewStringFromStaticChars("option"),
                     factory->NewStringFromStaticChars("dateStyle")),
        JSObject);
  }

  // 11. If needDefaults is true and defaults is either "date" or "all", then
1006
  if (needs_default) {
1007
    if (defaults == DefaultsOption::kAll || defaults == DefaultsOption::kDate) {
1008 1009 1010 1011
      // a. For each of the property names "year", "month", "day", do)
      const std::vector<std::string> list({"year", "month", "day"});
      MAYBE_RETURN(CreateDefault(isolate, options, list), Handle<JSObject>());
    }
1012
    // 12. If needDefaults is true and defaults is either "time" or "all", then
1013
    if (defaults == DefaultsOption::kAll || defaults == DefaultsOption::kTime) {
1014 1015 1016 1017 1018
      // a. For each of the property names "hour", "minute", "second", do
      const std::vector<std::string> list({"hour", "minute", "second"});
      MAYBE_RETURN(CreateDefault(isolate, options, list), Handle<JSObject>());
    }
  }
1019
  // 13. Return options.
1020 1021 1022
  return options;
}

1023 1024
MaybeHandle<JSDateTimeFormat> JSDateTimeFormat::UnwrapDateTimeFormat(
    Isolate* isolate, Handle<JSReceiver> format_holder) {
1025
  Handle<Context> native_context =
1026
      Handle<Context>(isolate->context().native_context(), isolate);
1027 1028 1029
  Handle<JSFunction> constructor = Handle<JSFunction>(
      JSFunction::cast(native_context->intl_date_time_format_function()),
      isolate);
1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050
  Handle<Object> dtf;
  ASSIGN_RETURN_ON_EXCEPTION(
      isolate, dtf,
      Intl::LegacyUnwrapReceiver(isolate, format_holder, constructor,
                                 format_holder->IsJSDateTimeFormat()),
      JSDateTimeFormat);
  // 2. If Type(dtf) is not Object or dtf does not have an
  //    [[InitializedDateTimeFormat]] internal slot, then
  if (!dtf->IsJSDateTimeFormat()) {
    // a. Throw a TypeError exception.
    THROW_NEW_ERROR(isolate,
                    NewTypeError(MessageTemplate::kIncompatibleMethodReceiver,
                                 isolate->factory()->NewStringFromAsciiChecked(
                                     "UnwrapDateTimeFormat"),
                                 format_holder),
                    JSDateTimeFormat);
  }
  // 3. Return dtf.
  return Handle<JSDateTimeFormat>::cast(dtf);
}

1051 1052
std::unique_ptr<icu::TimeZone> JSDateTimeFormat::CreateTimeZone(
    const char* timezone) {
1053 1054 1055 1056 1057 1058
  // Create time zone as specified by the user. We have to re-create time zone
  // since calendar takes ownership.
  if (timezone == nullptr) {
    // 19.a. Else / Let timeZone be DefaultTimeZone().
    return std::unique_ptr<icu::TimeZone>(icu::TimeZone::createDefault());
  }
1059
  std::string canonicalized = CanonicalizeTimeZoneID(timezone);
1060 1061 1062 1063 1064
  if (canonicalized.empty()) return std::unique_ptr<icu::TimeZone>();
  std::unique_ptr<icu::TimeZone> tz(
      icu::TimeZone::createTimeZone(canonicalized.c_str()));
  // 18.b If the result of IsValidTimeZoneName(timeZone) is false, then
  // i. Throw a RangeError exception.
1065
  if (!Intl::IsValidTimeZoneName(*tz)) return std::unique_ptr<icu::TimeZone>();
1066 1067 1068
  return tz;
}

1069 1070
namespace {

1071 1072 1073 1074 1075 1076 1077 1078 1079
class CalendarCache {
 public:
  icu::Calendar* CreateCalendar(const icu::Locale& locale, icu::TimeZone* tz) {
    icu::UnicodeString tz_id;
    tz->getID(tz_id);
    std::string key;
    tz_id.toUTF8String<std::string>(key);
    key += ":";
    key += locale.getName();
1080

1081 1082 1083 1084 1085 1086 1087
    base::MutexGuard guard(&mutex_);
    auto it = map_.find(key);
    if (it != map_.end()) {
      delete tz;
      return it->second->clone();
    }
    // Create a calendar using locale, and apply time zone to it.
1088
    UErrorCode status = U_ZERO_ERROR;
1089 1090
    std::unique_ptr<icu::Calendar> calendar(
        icu::Calendar::createInstance(tz, locale, status));
Frank Tang's avatar
Frank Tang committed
1091 1092
    DCHECK(U_SUCCESS(status));
    DCHECK_NOT_NULL(calendar.get());
1093 1094 1095 1096 1097

    if (calendar->getDynamicClassID() ==
        icu::GregorianCalendar::getStaticClassID()) {
      icu::GregorianCalendar* gc =
          static_cast<icu::GregorianCalendar*>(calendar.get());
1098
      status = U_ZERO_ERROR;
1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109
      // The beginning of ECMAScript time, namely -(2**53)
      const double start_of_time = -9007199254740992;
      gc->setGregorianChange(start_of_time, status);
      DCHECK(U_SUCCESS(status));
    }

    if (map_.size() > 8) {  // Cache at most 8 calendars.
      map_.clear();
    }
    map_[key].reset(calendar.release());
    return map_[key]->clone();
1110
  }
1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121

 private:
  std::map<std::string, std::unique_ptr<icu::Calendar>> map_;
  base::Mutex mutex_;
};

icu::Calendar* CreateCalendar(Isolate* isolate, const icu::Locale& icu_locale,
                              icu::TimeZone* tz) {
  static base::LazyInstance<CalendarCache>::type calendar_cache =
      LAZY_INSTANCE_INITIALIZER;
  return calendar_cache.Pointer()->CreateCalendar(icu_locale, tz);
1122 1123
}

Frank Tang's avatar
Frank Tang committed
1124
icu::UnicodeString ReplaceHourCycleInPattern(icu::UnicodeString pattern,
1125
                                             JSDateTimeFormat::HourCycle hc) {
Frank Tang's avatar
Frank Tang committed
1126 1127
  char16_t replacement;
  switch (hc) {
1128
    case JSDateTimeFormat::HourCycle::kUndefined:
Frank Tang's avatar
Frank Tang committed
1129
      return pattern;
1130
    case JSDateTimeFormat::HourCycle::kH11:
Frank Tang's avatar
Frank Tang committed
1131 1132
      replacement = 'K';
      break;
1133
    case JSDateTimeFormat::HourCycle::kH12:
Frank Tang's avatar
Frank Tang committed
1134 1135
      replacement = 'h';
      break;
1136
    case JSDateTimeFormat::HourCycle::kH23:
Frank Tang's avatar
Frank Tang committed
1137 1138
      replacement = 'H';
      break;
1139
    case JSDateTimeFormat::HourCycle::kH24:
Frank Tang's avatar
Frank Tang committed
1140 1141 1142 1143 1144
      replacement = 'k';
      break;
  }
  bool replace = true;
  icu::UnicodeString result;
1145
  char16_t last = u'\0';
Frank Tang's avatar
Frank Tang committed
1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159
  for (int32_t i = 0; i < pattern.length(); i++) {
    char16_t ch = pattern.charAt(i);
    switch (ch) {
      case '\'':
        replace = !replace;
        result.append(ch);
        break;
      case 'H':
        V8_FALLTHROUGH;
      case 'h':
        V8_FALLTHROUGH;
      case 'K':
        V8_FALLTHROUGH;
      case 'k':
1160 1161 1162 1163
        // If the previous field is a day, add a space before the hour.
        if (replace && last == u'd') {
          result.append(' ');
        }
Frank Tang's avatar
Frank Tang committed
1164 1165 1166 1167 1168 1169
        result.append(replace ? replacement : ch);
        break;
      default:
        result.append(ch);
        break;
    }
1170
    last = ch;
Frank Tang's avatar
Frank Tang committed
1171 1172 1173 1174
  }
  return result;
}

1175
std::unique_ptr<icu::SimpleDateFormat> CreateICUDateFormat(
1176
    const icu::Locale& icu_locale, const icu::UnicodeString& skeleton,
1177
    icu::DateTimePatternGenerator* generator, JSDateTimeFormat::HourCycle hc) {
1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188
  // See https://github.com/tc39/ecma402/issues/225 . The best pattern
  // generation needs to be done in the base locale according to the
  // current spec however odd it may be. See also crbug.com/826549 .
  // This is a temporary work-around to get v8's external behavior to match
  // the current spec, but does not follow the spec provisions mentioned
  // in the above Ecma 402 issue.
  // TODO(jshin): The spec may need to be revised because using the base
  // locale for the pattern match is not quite right. Moreover, what to
  // do with 'related year' part when 'chinese/dangi' calendar is specified
  // has to be discussed. Revisit once the spec is clarified/revised.
  icu::UnicodeString pattern;
1189
  UErrorCode status = U_ZERO_ERROR;
1190 1191
  pattern = generator->getBestPattern(skeleton, UDATPG_MATCH_HOUR_FIELD_LENGTH,
                                      status);
Frank Tang's avatar
Frank Tang committed
1192
  pattern = ReplaceHourCycleInPattern(pattern, hc);
Frank Tang's avatar
Frank Tang committed
1193
  DCHECK(U_SUCCESS(status));
1194 1195 1196 1197 1198 1199 1200 1201

  // Make formatter from skeleton. Calendar and numbering system are added
  // to the locale as Unicode extension (if they were specified at all).
  status = U_ZERO_ERROR;
  std::unique_ptr<icu::SimpleDateFormat> date_format(
      new icu::SimpleDateFormat(pattern, icu_locale, status));
  if (U_FAILURE(status)) return std::unique_ptr<icu::SimpleDateFormat>();

Frank Tang's avatar
Frank Tang committed
1202
  DCHECK_NOT_NULL(date_format.get());
1203 1204 1205
  return date_format;
}

1206 1207
class DateFormatCache {
 public:
1208 1209
  icu::SimpleDateFormat* Create(const icu::Locale& icu_locale,
                                const icu::UnicodeString& skeleton,
Frank Tang's avatar
Frank Tang committed
1210
                                icu::DateTimePatternGenerator* generator,
1211
                                JSDateTimeFormat::HourCycle hc) {
1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225
    std::string key;
    skeleton.toUTF8String<std::string>(key);
    key += ":";
    key += icu_locale.getName();

    base::MutexGuard guard(&mutex_);
    auto it = map_.find(key);
    if (it != map_.end()) {
      return static_cast<icu::SimpleDateFormat*>(it->second->clone());
    }

    if (map_.size() > 8) {  // Cache at most 8 DateFormats.
      map_.clear();
    }
1226
    std::unique_ptr<icu::SimpleDateFormat> instance(
Frank Tang's avatar
Frank Tang committed
1227
        CreateICUDateFormat(icu_locale, skeleton, generator, hc));
1228 1229
    if (instance.get() == nullptr) return nullptr;
    map_[key] = std::move(instance);
1230 1231 1232 1233 1234 1235 1236 1237 1238 1239
    return static_cast<icu::SimpleDateFormat*>(map_[key]->clone());
  }

 private:
  std::map<std::string, std::unique_ptr<icu::SimpleDateFormat>> map_;
  base::Mutex mutex_;
};

std::unique_ptr<icu::SimpleDateFormat> CreateICUDateFormatFromCache(
    const icu::Locale& icu_locale, const icu::UnicodeString& skeleton,
1240
    icu::DateTimePatternGenerator* generator, JSDateTimeFormat::HourCycle hc) {
1241 1242 1243
  static base::LazyInstance<DateFormatCache>::type cache =
      LAZY_INSTANCE_INITIALIZER;
  return std::unique_ptr<icu::SimpleDateFormat>(
Frank Tang's avatar
Frank Tang committed
1244
      cache.Pointer()->Create(icu_locale, skeleton, generator, hc));
1245 1246
}

1247 1248 1249 1250 1251 1252 1253 1254
icu::UnicodeString SkeletonFromDateFormat(
    const icu::SimpleDateFormat& icu_date_format) {
  icu::UnicodeString pattern;
  pattern = icu_date_format.toPattern(pattern);

  UErrorCode status = U_ZERO_ERROR;
  icu::UnicodeString skeleton =
      icu::DateTimePatternGenerator::staticGetSkeleton(pattern, status);
Frank Tang's avatar
Frank Tang committed
1255
  DCHECK(U_SUCCESS(status));
1256 1257 1258 1259 1260 1261 1262
  return skeleton;
}

icu::DateIntervalFormat* LazyCreateDateIntervalFormat(
    Isolate* isolate, Handle<JSDateTimeFormat> date_time_format) {
  Managed<icu::DateIntervalFormat> managed_format =
      date_time_format->icu_date_interval_format();
1263 1264
  if (managed_format.get()) {
    return managed_format.raw();
1265 1266
  }
  icu::SimpleDateFormat* icu_simple_date_format =
1267
      date_time_format->icu_simple_date_format().raw();
1268
  UErrorCode status = U_ZERO_ERROR;
1269 1270 1271 1272 1273 1274 1275 1276 1277

  icu::Locale loc = *(date_time_format->icu_locale().raw());
  // We need to pass in the hc to DateIntervalFormat by using Unicode 'hc'
  // extension.
  std::string hcString = ToHourCycleString(date_time_format->hour_cycle());
  if (!hcString.empty()) {
    loc.setUnicodeKeywordValue("hc", hcString, status);
  }

1278
  std::unique_ptr<icu::DateIntervalFormat> date_interval_format(
1279
      icu::DateIntervalFormat::createInstance(
1280
          SkeletonFromDateFormat(*icu_simple_date_format), loc, status));
1281 1282 1283 1284 1285 1286 1287 1288
  if (U_FAILURE(status)) {
    return nullptr;
  }
  date_interval_format->setTimeZone(icu_simple_date_format->getTimeZone());
  Handle<Managed<icu::DateIntervalFormat>> managed_interval_format =
      Managed<icu::DateIntervalFormat>::FromUniquePtr(
          isolate, 0, std::move(date_interval_format));
  date_time_format->set_icu_date_interval_format(*managed_interval_format);
1289
  return (*managed_interval_format).raw();
1290 1291
}

1292 1293
JSDateTimeFormat::HourCycle HourCycleFromPattern(
    const icu::UnicodeString pattern) {
1294 1295 1296 1297 1298 1299 1300 1301
  bool in_quote = false;
  for (int32_t i = 0; i < pattern.length(); i++) {
    char16_t ch = pattern[i];
    switch (ch) {
      case '\'':
        in_quote = !in_quote;
        break;
      case 'K':
1302
        if (!in_quote) return JSDateTimeFormat::HourCycle::kH11;
1303 1304
        break;
      case 'h':
1305
        if (!in_quote) return JSDateTimeFormat::HourCycle::kH12;
1306 1307
        break;
      case 'H':
1308
        if (!in_quote) return JSDateTimeFormat::HourCycle::kH23;
1309 1310
        break;
      case 'k':
1311
        if (!in_quote) return JSDateTimeFormat::HourCycle::kH24;
1312 1313
        break;
    }
1314
  }
1315
  return JSDateTimeFormat::HourCycle::kUndefined;
1316 1317
}

1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334
icu::DateFormat::EStyle DateTimeStyleToEStyle(
    JSDateTimeFormat::DateTimeStyle style) {
  switch (style) {
    case JSDateTimeFormat::DateTimeStyle::kFull:
      return icu::DateFormat::EStyle::kFull;
    case JSDateTimeFormat::DateTimeStyle::kLong:
      return icu::DateFormat::EStyle::kLong;
    case JSDateTimeFormat::DateTimeStyle::kMedium:
      return icu::DateFormat::EStyle::kMedium;
    case JSDateTimeFormat::DateTimeStyle::kShort:
      return icu::DateFormat::EStyle::kShort;
    case JSDateTimeFormat::DateTimeStyle::kUndefined:
      UNREACHABLE();
  }
}

icu::UnicodeString ReplaceSkeleton(const icu::UnicodeString input,
1335
                                   JSDateTimeFormat::HourCycle hc) {
1336 1337 1338
  icu::UnicodeString result;
  char16_t to;
  switch (hc) {
1339
    case JSDateTimeFormat::HourCycle::kH11:
1340 1341
      to = 'K';
      break;
1342
    case JSDateTimeFormat::HourCycle::kH12:
1343 1344
      to = 'h';
      break;
1345
    case JSDateTimeFormat::HourCycle::kH23:
1346 1347
      to = 'H';
      break;
1348
    case JSDateTimeFormat::HourCycle::kH24:
1349 1350
      to = 'k';
      break;
1351
    case JSDateTimeFormat::HourCycle::kUndefined:
1352 1353 1354 1355
      UNREACHABLE();
  }
  for (int32_t i = 0; i < input.length(); i++) {
    switch (input[i]) {
1356 1357
      // We need to skip 'a', 'b', 'B' here due to
      // https://unicode-org.atlassian.net/browse/ICU-20437
1358
      case 'a':
1359 1360 1361 1362
        V8_FALLTHROUGH;
      case 'b':
        V8_FALLTHROUGH;
      case 'B':
1363 1364 1365
        // ignore
        break;
      case 'h':
1366
        V8_FALLTHROUGH;
1367
      case 'H':
1368
        V8_FALLTHROUGH;
1369
      case 'K':
1370
        V8_FALLTHROUGH;
1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383
      case 'k':
        result += to;
        break;
      default:
        result += input[i];
        break;
    }
  }
  return result;
}

std::unique_ptr<icu::SimpleDateFormat> DateTimeStylePattern(
    JSDateTimeFormat::DateTimeStyle date_style,
1384
    JSDateTimeFormat::DateTimeStyle time_style, icu::Locale& icu_locale,
1385
    JSDateTimeFormat::HourCycle hc, icu::DateTimePatternGenerator* generator) {
1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398
  std::unique_ptr<icu::SimpleDateFormat> result;
  if (date_style != JSDateTimeFormat::DateTimeStyle::kUndefined) {
    if (time_style != JSDateTimeFormat::DateTimeStyle::kUndefined) {
      result.reset(reinterpret_cast<icu::SimpleDateFormat*>(
          icu::DateFormat::createDateTimeInstance(
              DateTimeStyleToEStyle(date_style),
              DateTimeStyleToEStyle(time_style), icu_locale)));
    } else {
      result.reset(reinterpret_cast<icu::SimpleDateFormat*>(
          icu::DateFormat::createDateInstance(DateTimeStyleToEStyle(date_style),
                                              icu_locale)));
      // For instance without time, we do not need to worry about the hour cycle
      // impact so we can return directly.
1399 1400 1401
      if (result.get() != nullptr) {
        return result;
      }
1402 1403 1404 1405 1406 1407 1408 1409 1410 1411
    }
  } else {
    if (time_style != JSDateTimeFormat::DateTimeStyle::kUndefined) {
      result.reset(reinterpret_cast<icu::SimpleDateFormat*>(
          icu::DateFormat::createTimeInstance(DateTimeStyleToEStyle(time_style),
                                              icu_locale)));
    } else {
      UNREACHABLE();
    }
  }
1412 1413 1414 1415 1416 1417 1418

  UErrorCode status = U_ZERO_ERROR;
  // Somehow we fail to create the instance.
  if (result.get() == nullptr) {
    // Fallback to the locale without "nu".
    if (!icu_locale.getUnicodeKeywordValue<std::string>("nu", status).empty()) {
      status = U_ZERO_ERROR;
1419 1420
      icu_locale.setUnicodeKeywordValue("nu", nullptr, status);
      return DateTimeStylePattern(date_style, time_style, icu_locale, hc,
1421 1422 1423 1424 1425 1426
                                  generator);
    }
    status = U_ZERO_ERROR;
    // Fallback to the locale without "hc".
    if (!icu_locale.getUnicodeKeywordValue<std::string>("hc", status).empty()) {
      status = U_ZERO_ERROR;
1427 1428
      icu_locale.setUnicodeKeywordValue("hc", nullptr, status);
      return DateTimeStylePattern(date_style, time_style, icu_locale, hc,
1429 1430 1431 1432 1433 1434
                                  generator);
    }
    status = U_ZERO_ERROR;
    // Fallback to the locale without "ca".
    if (!icu_locale.getUnicodeKeywordValue<std::string>("ca", status).empty()) {
      status = U_ZERO_ERROR;
1435 1436
      icu_locale.setUnicodeKeywordValue("ca", nullptr, status);
      return DateTimeStylePattern(date_style, time_style, icu_locale, hc,
1437 1438 1439 1440
                                  generator);
    }
    return nullptr;
  }
1441 1442 1443
  icu::UnicodeString pattern;
  pattern = result->toPattern(pattern);

1444
  status = U_ZERO_ERROR;
1445 1446
  icu::UnicodeString skeleton =
      icu::DateTimePatternGenerator::staticGetSkeleton(pattern, status);
Frank Tang's avatar
Frank Tang committed
1447
  DCHECK(U_SUCCESS(status));
1448 1449 1450 1451 1452 1453

  // If the skeleton match the HourCycle, we just return it.
  if (hc == HourCycleFromPattern(pattern)) {
    return result;
  }

1454
  return CreateICUDateFormatFromCache(icu_locale, ReplaceSkeleton(skeleton, hc),
Frank Tang's avatar
Frank Tang committed
1455
                                      generator, hc);
1456 1457
}

1458 1459 1460
class DateTimePatternGeneratorCache {
 public:
  // Return a clone copy that the caller have to free.
1461 1462
  icu::DateTimePatternGenerator* CreateGenerator(Isolate* isolate,
                                                 const icu::Locale& locale) {
1463
    std::string key(locale.getName());
1464 1465
    base::MutexGuard guard(&mutex_);
    auto it = map_.find(key);
1466
    icu::DateTimePatternGenerator* orig;
1467
    if (it != map_.end()) {
1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485
      DCHECK(it->second != nullptr);
      orig = it->second.get();
    } else {
      UErrorCode status = U_ZERO_ERROR;
      orig = icu::DateTimePatternGenerator::createInstance(locale, status);
      // It may not be an U_MEMORY_ALLOCATION_ERROR.
      // Fallback to use "root".
      if (U_FAILURE(status)) {
        status = U_ZERO_ERROR;
        orig = icu::DateTimePatternGenerator::createInstance("root", status);
      }
      if (U_SUCCESS(status) && orig != nullptr) {
        map_[key].reset(orig);
      } else {
        DCHECK(status == U_MEMORY_ALLOCATION_ERROR);
        V8::FatalProcessOutOfMemory(
            isolate, "DateTimePatternGeneratorCache::CreateGenerator");
      }
1486
    }
1487 1488 1489 1490
    icu::DateTimePatternGenerator* clone = orig ? orig->clone() : nullptr;
    if (clone == nullptr) {
      V8::FatalProcessOutOfMemory(
          isolate, "DateTimePatternGeneratorCache::CreateGenerator");
1491
    }
1492
    return clone;
1493 1494 1495 1496 1497 1498 1499
  }

 private:
  std::map<std::string, std::unique_ptr<icu::DateTimePatternGenerator>> map_;
  base::Mutex mutex_;
};

1500 1501 1502 1503 1504
}  // namespace

enum FormatMatcherOption { kBestFit, kBasic };

// ecma402/#sec-initializedatetimeformat
1505 1506
MaybeHandle<JSDateTimeFormat> JSDateTimeFormat::New(
    Isolate* isolate, Handle<Map> map, Handle<Object> locales,
1507
    Handle<Object> input_options, const char* service) {
1508
  Factory* factory = isolate->factory();
1509 1510 1511 1512 1513 1514
  // 1. Let requestedLocales be ? CanonicalizeLocaleList(locales).
  Maybe<std::vector<std::string>> maybe_requested_locales =
      Intl::CanonicalizeLocaleList(isolate, locales);
  MAYBE_RETURN(maybe_requested_locales, Handle<JSDateTimeFormat>());
  std::vector<std::string> requested_locales =
      maybe_requested_locales.FromJust();
1515 1516 1517 1518 1519 1520 1521 1522
  // 2. Let options be ? ToDateTimeOptions(options, "any", "date").
  Handle<JSObject> options;
  ASSIGN_RETURN_ON_EXCEPTION(
      isolate, options,
      JSDateTimeFormat::ToDateTimeOptions(
          isolate, input_options, RequiredOption::kAny, DefaultsOption::kDate),
      JSDateTimeFormat);

1523 1524 1525
  // 4. Let matcher be ? GetOption(options, "localeMatcher", "string",
  // « "lookup", "best fit" », "best fit").
  // 5. Set opt.[[localeMatcher]] to matcher.
1526 1527 1528 1529
  Maybe<Intl::MatcherOption> maybe_locale_matcher =
      Intl::GetLocaleMatcher(isolate, options, service);
  MAYBE_RETURN(maybe_locale_matcher, MaybeHandle<JSDateTimeFormat>());
  Intl::MatcherOption locale_matcher = maybe_locale_matcher.FromJust();
1530 1531 1532

  std::unique_ptr<char[]> calendar_str = nullptr;
  std::unique_ptr<char[]> numbering_system_str = nullptr;
1533 1534 1535
  const std::vector<const char*> empty_values = {};
  // 6. Let calendar be ? GetOption(options, "calendar",
  //    "string", undefined, undefined).
1536
  Maybe<bool> maybe_calendar = GetStringOption(
1537 1538 1539 1540 1541 1542 1543 1544 1545 1546
      isolate, options, "calendar", empty_values, service, &calendar_str);
  MAYBE_RETURN(maybe_calendar, MaybeHandle<JSDateTimeFormat>());
  if (maybe_calendar.FromJust() && calendar_str != nullptr) {
    icu::Locale default_locale;
    if (!Intl::IsWellFormedCalendar(calendar_str.get())) {
      THROW_NEW_ERROR(
          isolate,
          NewRangeError(MessageTemplate::kInvalid, factory->calendar_string(),
                        factory->NewStringFromAsciiChecked(calendar_str.get())),
          JSDateTimeFormat);
1547 1548 1549
    }
  }

1550 1551 1552 1553 1554 1555
  // 8. Let numberingSystem be ? GetOption(options, "numberingSystem",
  //    "string", undefined, undefined).
  Maybe<bool> maybe_numberingSystem = Intl::GetNumberingSystem(
      isolate, options, service, &numbering_system_str);
  MAYBE_RETURN(maybe_numberingSystem, MaybeHandle<JSDateTimeFormat>());

1556 1557 1558
  // 6. Let hour12 be ? GetOption(options, "hour12", "boolean", undefined,
  // undefined).
  bool hour12;
1559
  Maybe<bool> maybe_get_hour12 =
1560
      GetBoolOption(isolate, options, "hour12", service, &hour12);
1561 1562 1563 1564
  MAYBE_RETURN(maybe_get_hour12, Handle<JSDateTimeFormat>());

  // 7. Let hourCycle be ? GetOption(options, "hourCycle", "string", « "h11",
  // "h12", "h23", "h24" », undefined).
1565
  Maybe<HourCycle> maybe_hour_cycle = GetHourCycle(isolate, options, service);
1566
  MAYBE_RETURN(maybe_hour_cycle, MaybeHandle<JSDateTimeFormat>());
1567
  HourCycle hour_cycle = maybe_hour_cycle.FromJust();
1568

1569 1570 1571
  // 8. If hour12 is not undefined, then
  if (maybe_get_hour12.FromJust()) {
    // a. Let hourCycle be null.
1572
    hour_cycle = HourCycle::kUndefined;
1573 1574 1575
  }
  // 9. Set opt.[[hc]] to hourCycle.

1576 1577 1578
  // ecma402/#sec-intl.datetimeformat-internal-slots
  // The value of the [[RelevantExtensionKeys]] internal slot is
  // « "ca", "nu", "hc" ».
1579
  std::set<std::string> relevant_extension_keys = {"nu", "ca", "hc"};
1580

1581 1582 1583 1584
  // 10. Let localeData be %DateTimeFormat%.[[LocaleData]].
  // 11. Let r be ResolveLocale( %DateTimeFormat%.[[AvailableLocales]],
  //     requestedLocales, opt, %DateTimeFormat%.[[RelevantExtensionKeys]],
  //     localeData).
1585
  //
1586
  Maybe<Intl::ResolvedLocale> maybe_resolve_locale = Intl::ResolveLocale(
1587 1588
      isolate, JSDateTimeFormat::GetAvailableLocales(), requested_locales,
      locale_matcher, relevant_extension_keys);
1589 1590 1591 1592 1593
  if (maybe_resolve_locale.IsNothing()) {
    THROW_NEW_ERROR(isolate, NewRangeError(MessageTemplate::kIcuError),
                    JSDateTimeFormat);
  }
  Intl::ResolvedLocale r = maybe_resolve_locale.FromJust();
1594 1595

  icu::Locale icu_locale = r.icu_locale;
1596 1597
  DCHECK(!icu_locale.isBogus());

1598
  UErrorCode status = U_ZERO_ERROR;
1599 1600 1601 1602 1603
  if (calendar_str != nullptr) {
    auto ca_extension_it = r.extensions.find("ca");
    if (ca_extension_it != r.extensions.end() &&
        ca_extension_it->second != calendar_str.get()) {
      icu_locale.setUnicodeKeywordValue("ca", nullptr, status);
Frank Tang's avatar
Frank Tang committed
1604
      DCHECK(U_SUCCESS(status));
1605 1606 1607 1608 1609 1610 1611
    }
  }
  if (numbering_system_str != nullptr) {
    auto nu_extension_it = r.extensions.find("nu");
    if (nu_extension_it != r.extensions.end() &&
        nu_extension_it->second != numbering_system_str.get()) {
      icu_locale.setUnicodeKeywordValue("nu", nullptr, status);
Frank Tang's avatar
Frank Tang committed
1612
      DCHECK(U_SUCCESS(status));
1613 1614 1615 1616 1617 1618 1619
    }
  }

  // Need to keep a copy of icu_locale which not changing "ca", "nu", "hc"
  // by option.
  icu::Locale resolved_locale(icu_locale);

1620 1621
  if (calendar_str != nullptr &&
      Intl::IsValidCalendar(icu_locale, calendar_str.get())) {
1622
    icu_locale.setUnicodeKeywordValue("ca", calendar_str.get(), status);
Frank Tang's avatar
Frank Tang committed
1623
    DCHECK(U_SUCCESS(status));
1624
  }
1625 1626 1627
  bool alt_calendar =
      strstr(icu_locale.getName(), "calendar=iso8601") != nullptr ||
      strstr(icu_locale.getName(), "calendar=islamic-rgsa") != nullptr;
1628

1629 1630
  if (numbering_system_str != nullptr &&
      Intl::IsValidNumberingSystem(numbering_system_str.get())) {
1631
    icu_locale.setUnicodeKeywordValue("nu", numbering_system_str.get(), status);
Frank Tang's avatar
Frank Tang committed
1632
    DCHECK(U_SUCCESS(status));
1633 1634
  }

1635 1636 1637
  static base::LazyInstance<DateTimePatternGeneratorCache>::type
      generator_cache = LAZY_INSTANCE_INITIALIZER;

1638
  std::unique_ptr<icu::DateTimePatternGenerator> generator(
1639
      generator_cache.Pointer()->CreateGenerator(isolate, icu_locale));
1640 1641

  // 15.Let hcDefault be dataLocaleData.[[hourCycle]].
1642
  HourCycle hc_default = ToHourCycle(generator->getDefaultHourCycle(status));
Frank Tang's avatar
Frank Tang committed
1643
  DCHECK(U_SUCCESS(status));
1644 1645

  // 16.Let hc be r.[[hc]].
1646 1647
  HourCycle hc = HourCycle::kUndefined;
  if (hour_cycle == HourCycle::kUndefined) {
1648 1649
    auto hc_extension_it = r.extensions.find("hc");
    if (hc_extension_it != r.extensions.end()) {
1650
      hc = ToHourCycle(hc_extension_it->second.c_str());
1651
    }
1652 1653 1654 1655
  } else {
    hc = hour_cycle;
  }
  // 17. If hc is null, then
1656
  if (hc == HourCycle::kUndefined) {
1657 1658
    // a. Set hc to hcDefault.
    hc = hc_default;
1659 1660
  }

1661 1662 1663 1664 1665
  // 18. If hour12 is not undefined, then
  if (maybe_get_hour12.FromJust()) {
    // a. If hour12 is true, then
    if (hour12) {
      // i. If hcDefault is "h11" or "h23", then
1666
      if (hc_default == HourCycle::kH11 || hc_default == HourCycle::kH23) {
1667
        // 1. Set hc to "h11".
1668
        hc = HourCycle::kH11;
1669 1670 1671
        // ii. Else,
      } else {
        // 1. Set hc to "h12".
1672
        hc = HourCycle::kH12;
1673 1674 1675 1676
      }
      // b. Else,
    } else {
      // ii. If hcDefault is "h11" or "h23", then
1677
      if (hc_default == HourCycle::kH11 || hc_default == HourCycle::kH23) {
1678
        // 1. Set hc to "h23".
1679
        hc = HourCycle::kH23;
1680 1681 1682
        // iii. Else,
      } else {
        // 1. Set hc to "h24".
1683
        hc = HourCycle::kH24;
1684
      }
1685 1686
    }
  }
1687

1688 1689
  // 17. Let timeZone be ? Get(options, "timeZone").
  std::unique_ptr<char[]> timezone = nullptr;
1690
  Maybe<bool> maybe_timezone = GetStringOption(
1691 1692 1693
      isolate, options, "timeZone", empty_values, service, &timezone);
  MAYBE_RETURN(maybe_timezone, Handle<JSDateTimeFormat>());

1694 1695
  std::unique_ptr<icu::TimeZone> tz =
      JSDateTimeFormat::CreateTimeZone(timezone.get());
1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716
  if (tz.get() == nullptr) {
    THROW_NEW_ERROR(
        isolate,
        NewRangeError(MessageTemplate::kInvalidTimeZone,
                      factory->NewStringFromAsciiChecked(timezone.get())),
        JSDateTimeFormat);
  }

  std::unique_ptr<icu::Calendar> calendar(
      CreateCalendar(isolate, icu_locale, tz.release()));

  // 18.b If the result of IsValidTimeZoneName(timeZone) is false, then
  // i. Throw a RangeError exception.
  if (calendar.get() == nullptr) {
    THROW_NEW_ERROR(
        isolate,
        NewRangeError(MessageTemplate::kInvalidTimeZone,
                      factory->NewStringFromAsciiChecked(timezone.get())),
        JSDateTimeFormat);
  }

1717 1718 1719 1720
  DateTimeStyle date_style = DateTimeStyle::kUndefined;
  DateTimeStyle time_style = DateTimeStyle::kUndefined;
  std::unique_ptr<icu::SimpleDateFormat> icu_date_format;

1721 1722 1723 1724
  // 28. For each row of Table 1, except the header row, do
  bool has_hour_option = false;
  std::string skeleton;
  for (const PatternData& item : GetPatternData(hc)) {
1725 1726 1727 1728
    // Need to read fractionalSecondDigits before reading the timeZoneName
    if (item.property == "timeZoneName") {
      // Let _value_ be ? GetNumberOption(options, "fractionalSecondDigits", 1,
      // 3, *undefined*). The *undefined* is represented by value 0 here.
1729
      Maybe<int> maybe_fsd = GetNumberOption(
1730 1731 1732 1733 1734 1735 1736 1737
          isolate, options, factory->fractionalSecondDigits_string(), 1, 3, 0);
      MAYBE_RETURN(maybe_fsd, MaybeHandle<JSDateTimeFormat>());
      // Convert fractionalSecondDigits to skeleton.
      int fsd = maybe_fsd.FromJust();
      for (int i = 0; i < fsd; i++) {
        skeleton += "S";
      }
    }
1738 1739 1740 1741 1742
    std::unique_ptr<char[]> input;
    // i. Let prop be the name given in the Property column of the row.
    // ii. Let value be ? GetOption(options, prop, "string", « the strings
    // given in the Values column of the row », undefined).
    Maybe<bool> maybe_get_option =
1743 1744
        GetStringOption(isolate, options, item.property.c_str(),
                        item.allowed_values, service, &input);
1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762
    MAYBE_RETURN(maybe_get_option, Handle<JSDateTimeFormat>());
    if (maybe_get_option.FromJust()) {
      if (item.property == "hour") {
        has_hour_option = true;
      }
      DCHECK_NOT_NULL(input.get());
      // iii. Set opt.[[<prop>]] to value.
      skeleton += item.map.find(input.get())->second;
    }
  }

  // 29. Let matcher be ? GetOption(options, "formatMatcher", "string", «
  // "basic", "best fit" », "best fit").
  // We implement only best fit algorithm, but still need to check
  // if the formatMatcher values are in range.
  // c. Let matcher be ? GetOption(options, "formatMatcher", "string",
  //     «  "basic", "best fit" », "best fit").
  Maybe<FormatMatcherOption> maybe_format_matcher =
1763
      GetStringOption<FormatMatcherOption>(
1764 1765 1766 1767 1768 1769 1770 1771
          isolate, options, "formatMatcher", service, {"best fit", "basic"},
          {FormatMatcherOption::kBestFit, FormatMatcherOption::kBasic},
          FormatMatcherOption::kBestFit);
  MAYBE_RETURN(maybe_format_matcher, MaybeHandle<JSDateTimeFormat>());
  // TODO(ftang): uncomment the following line and handle format_matcher.
  // FormatMatcherOption format_matcher = maybe_format_matcher.FromJust();

  // 32. Let dateStyle be ? GetOption(options, "dateStyle", "string", «
1772
  // "full", "long", "medium", "short" », undefined).
1773
  Maybe<DateTimeStyle> maybe_date_style = GetStringOption<DateTimeStyle>(
1774 1775 1776 1777 1778 1779
      isolate, options, "dateStyle", service,
      {"full", "long", "medium", "short"},
      {DateTimeStyle::kFull, DateTimeStyle::kLong, DateTimeStyle::kMedium,
       DateTimeStyle::kShort},
      DateTimeStyle::kUndefined);
  MAYBE_RETURN(maybe_date_style, MaybeHandle<JSDateTimeFormat>());
1780
  // 33. Set dateTimeFormat.[[DateStyle]] to dateStyle.
1781 1782
  date_style = maybe_date_style.FromJust();

1783
  // 34. Let timeStyle be ? GetOption(options, "timeStyle", "string", «
1784
  // "full", "long", "medium", "short" »).
1785
  Maybe<DateTimeStyle> maybe_time_style = GetStringOption<DateTimeStyle>(
1786 1787 1788 1789 1790 1791 1792
      isolate, options, "timeStyle", service,
      {"full", "long", "medium", "short"},
      {DateTimeStyle::kFull, DateTimeStyle::kLong, DateTimeStyle::kMedium,
       DateTimeStyle::kShort},
      DateTimeStyle::kUndefined);
  MAYBE_RETURN(maybe_time_style, MaybeHandle<JSDateTimeFormat>());

1793
  // 35. Set dateTimeFormat.[[TimeStyle]] to timeStyle.
1794 1795
  time_style = maybe_time_style.FromJust();

1796 1797 1798 1799 1800 1801 1802 1803
  // 36. If timeStyle is not undefined, then
  HourCycle dateTimeFormatHourCycle = HourCycle::kUndefined;
  if (time_style != DateTimeStyle::kUndefined) {
    // a. Set dateTimeFormat.[[HourCycle]] to hc.
    dateTimeFormatHourCycle = hc;
  }

  // 37. If dateStyle or timeStyle are not undefined, then
1804 1805
  if (date_style != DateTimeStyle::kUndefined ||
      time_style != DateTimeStyle::kUndefined) {
1806 1807 1808 1809 1810 1811
    // a. For each row in Table 1, except the header row, do
    //    i. Let prop be the name given in the Property column of the row.
    //   ii. Let p be opt.[[<prop>]].
    //  iii. If p is not undefined, then
    //      1. Throw a TypeError exception.
    if (skeleton.length() > 0) {
1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837
      std::string prop;
      for (const auto& item : GetPatternItems()) {
        for (const auto& pair : item.pairs) {
          if (skeleton.find(pair.pattern) != std::string::npos) {
            prop.assign(item.property);
            break;
          }
        }
        if (!prop.empty()) {
          break;
        }
      }
      if (prop.empty() && skeleton.find("S") != std::string::npos) {
        prop.assign("fractionalSecondDigits");
      }
      if (!prop.empty()) {
        THROW_NEW_ERROR(
            isolate,
            NewTypeError(MessageTemplate::kCantSetOptionXWhenYIsUsed,
                         factory->NewStringFromAsciiChecked(prop.c_str()),
                         date_style != DateTimeStyle::kUndefined
                             ? factory->dateStyle_string()
                             : factory->timeStyle_string()),
            JSDateTimeFormat);
      }
      UNREACHABLE();
1838 1839 1840
    }
    // b. Let pattern be DateTimeStylePattern(dateStyle, timeStyle,
    // dataLocaleData, hc).
1841 1842 1843
    isolate->CountUsage(
        v8::Isolate::UseCounterFeature::kDateTimeFormatDateTimeStyle);

1844 1845 1846
    icu_date_format =
        DateTimeStylePattern(date_style, time_style, icu_locale,
                             dateTimeFormatHourCycle, generator.get());
1847 1848 1849 1850
    if (icu_date_format.get() == nullptr) {
      THROW_NEW_ERROR(isolate, NewRangeError(MessageTemplate::kIcuError),
                      JSDateTimeFormat);
    }
1851 1852 1853 1854 1855 1856 1857 1858 1859
  } else {
    // e. If dateTimeFormat.[[Hour]] is not undefined, then
    if (has_hour_option) {
      // v. Set dateTimeFormat.[[HourCycle]] to hc.
      dateTimeFormatHourCycle = hc;
    } else {
      // f. Else,
      // Set dateTimeFormat.[[HourCycle]] to undefined.
      dateTimeFormatHourCycle = HourCycle::kUndefined;
1860
    }
1861
    icu::UnicodeString skeleton_ustr(skeleton.c_str());
1862 1863
    icu_date_format = CreateICUDateFormatFromCache(
        icu_locale, skeleton_ustr, generator.get(), dateTimeFormatHourCycle);
1864 1865 1866
    if (icu_date_format.get() == nullptr) {
      // Remove extensions and try again.
      icu_locale = icu::Locale(icu_locale.getBaseName());
1867 1868
      icu_date_format = CreateICUDateFormatFromCache(
          icu_locale, skeleton_ustr, generator.get(), dateTimeFormatHourCycle);
1869
      if (icu_date_format.get() == nullptr) {
1870 1871
        THROW_NEW_ERROR(isolate, NewRangeError(MessageTemplate::kIcuError),
                        JSDateTimeFormat);
1872 1873
      }
    }
1874
  }
1875

1876 1877 1878 1879 1880
  // The creation of Calendar depends on timeZone so we have to put 13 after 17.
  // Also icu_date_format is not created until here.
  // 13. Set dateTimeFormat.[[Calendar]] to r.[[ca]].
  icu_date_format->adoptCalendar(calendar.release());

1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894
  // 12.1.1 InitializeDateTimeFormat ( dateTimeFormat, locales, options )
  //
  // Steps 8-9 set opt.[[hc]] to value *other than undefined*
  // if "hour12" is set or "hourCycle" is set in the option.
  //
  // 9.2.6 ResolveLocale (... )
  // Step 8.h / 8.i and 8.k
  //
  // An hour12 option always overrides an hourCycle option.
  // Additionally hour12 and hourCycle both clear out any existing Unicode
  // extension key in the input locale.
  //
  // See details in https://github.com/tc39/test262/pull/2035
  if (maybe_get_hour12.FromJust() ||
1895
      maybe_hour_cycle.FromJust() != HourCycle::kUndefined) {
1896 1897
    auto hc_extension_it = r.extensions.find("hc");
    if (hc_extension_it != r.extensions.end()) {
1898 1899
      if (dateTimeFormatHourCycle !=
          ToHourCycle(hc_extension_it->second.c_str())) {
1900
        // Remove -hc- if it does not agree with what we used.
1901
        status = U_ZERO_ERROR;
1902
        resolved_locale.setUnicodeKeywordValue("hc", nullptr, status);
Frank Tang's avatar
Frank Tang committed
1903
        DCHECK(U_SUCCESS(status));
1904 1905 1906 1907
      }
    }
  }

1908 1909 1910 1911 1912
  Maybe<std::string> maybe_locale_str = Intl::ToLanguageTag(resolved_locale);
  MAYBE_RETURN(maybe_locale_str, MaybeHandle<JSDateTimeFormat>());
  Handle<String> locale_str = isolate->factory()->NewStringFromAsciiChecked(
      maybe_locale_str.FromJust().c_str());

1913 1914
  Handle<Managed<icu::Locale>> managed_locale =
      Managed<icu::Locale>::FromRawPtr(isolate, 0, icu_locale.clone());
1915

1916 1917
  Handle<Managed<icu::SimpleDateFormat>> managed_format =
      Managed<icu::SimpleDateFormat>::FromUniquePtr(isolate, 0,
1918
                                                    std::move(icu_date_format));
1919 1920 1921

  Handle<Managed<icu::DateIntervalFormat>> managed_interval_format =
      Managed<icu::DateIntervalFormat>::FromRawPtr(isolate, 0, nullptr);
1922

1923 1924 1925
  // Now all properties are ready, so we can allocate the result object.
  Handle<JSDateTimeFormat> date_time_format = Handle<JSDateTimeFormat>::cast(
      isolate->factory()->NewFastOrSlowJSObjectFromMap(map));
1926
  DisallowGarbageCollection no_gc;
1927 1928 1929 1930 1931 1932 1933
  date_time_format->set_flags(0);
  if (date_style != DateTimeStyle::kUndefined) {
    date_time_format->set_date_style(date_style);
  }
  if (time_style != DateTimeStyle::kUndefined) {
    date_time_format->set_time_style(time_style);
  }
1934
  date_time_format->set_hour_cycle(dateTimeFormatHourCycle);
1935
  date_time_format->set_alt_calendar(alt_calendar);
1936
  date_time_format->set_locale(*locale_str);
1937 1938 1939
  date_time_format->set_icu_locale(*managed_locale);
  date_time_format->set_icu_simple_date_format(*managed_format);
  date_time_format->set_icu_date_interval_format(*managed_interval_format);
1940 1941
  return date_time_format;
}
1942

1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954
namespace {

// The list comes from third_party/icu/source/i18n/unicode/udat.h.
// They're mapped to DateTimeFormat components listed at
// https://tc39.github.io/ecma402/#sec-datetimeformat-abstracts .
Handle<String> IcuDateFieldIdToDateType(int32_t field_id, Isolate* isolate) {
  switch (field_id) {
    case -1:
      return isolate->factory()->literal_string();
    case UDAT_YEAR_FIELD:
    case UDAT_EXTENDED_YEAR_FIELD:
      return isolate->factory()->year_string();
1955 1956
    case UDAT_YEAR_NAME_FIELD:
      return isolate->factory()->yearName_string();
1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975
    case UDAT_MONTH_FIELD:
    case UDAT_STANDALONE_MONTH_FIELD:
      return isolate->factory()->month_string();
    case UDAT_DATE_FIELD:
      return isolate->factory()->day_string();
    case UDAT_HOUR_OF_DAY1_FIELD:
    case UDAT_HOUR_OF_DAY0_FIELD:
    case UDAT_HOUR1_FIELD:
    case UDAT_HOUR0_FIELD:
      return isolate->factory()->hour_string();
    case UDAT_MINUTE_FIELD:
      return isolate->factory()->minute_string();
    case UDAT_SECOND_FIELD:
      return isolate->factory()->second_string();
    case UDAT_DAY_OF_WEEK_FIELD:
    case UDAT_DOW_LOCAL_FIELD:
    case UDAT_STANDALONE_DAY_FIELD:
      return isolate->factory()->weekday_string();
    case UDAT_AM_PM_FIELD:
1976 1977
    case UDAT_AM_PM_MIDNIGHT_NOON_FIELD:
    case UDAT_FLEXIBLE_DAY_PERIOD_FIELD:
1978
      return isolate->factory()->dayPeriod_string();
1979 1980 1981 1982 1983 1984 1985 1986 1987 1988
    case UDAT_TIMEZONE_FIELD:
    case UDAT_TIMEZONE_RFC_FIELD:
    case UDAT_TIMEZONE_GENERIC_FIELD:
    case UDAT_TIMEZONE_SPECIAL_FIELD:
    case UDAT_TIMEZONE_LOCALIZED_GMT_OFFSET_FIELD:
    case UDAT_TIMEZONE_ISO_FIELD:
    case UDAT_TIMEZONE_ISO_LOCAL_FIELD:
      return isolate->factory()->timeZoneName_string();
    case UDAT_ERA_FIELD:
      return isolate->factory()->era_string();
1989 1990
    case UDAT_FRACTIONAL_SECOND_FIELD:
      return isolate->factory()->fractionalSecond_string();
1991 1992
    case UDAT_RELATED_YEAR_FIELD:
      return isolate->factory()->relatedYear_string();
1993 1994 1995

    case UDAT_QUARTER_FIELD:
    case UDAT_STANDALONE_QUARTER_FIELD:
1996 1997 1998 1999 2000 2001 2002 2003 2004
    default:
      // Other UDAT_*_FIELD's cannot show up because there is no way to specify
      // them via options of Intl.DateTimeFormat.
      UNREACHABLE();
  }
}

}  // namespace

2005
MaybeHandle<JSArray> JSDateTimeFormat::FormatToParts(
2006
    Isolate* isolate, Handle<JSDateTimeFormat> date_time_format,
2007
    double date_value, bool output_source) {
2008 2009
  Factory* factory = isolate->factory();
  icu::SimpleDateFormat* format =
2010
      date_time_format->icu_simple_date_format().raw();
Frank Tang's avatar
Frank Tang committed
2011
  DCHECK_NOT_NULL(format);
2012 2013 2014 2015 2016 2017 2018

  icu::UnicodeString formatted;
  icu::FieldPositionIterator fp_iter;
  icu::FieldPosition fp;
  UErrorCode status = U_ZERO_ERROR;
  format->format(date_value, formatted, &fp_iter, status);
  if (U_FAILURE(status)) {
2019
    THROW_NEW_ERROR(isolate, NewTypeError(MessageTemplate::kIcuError), JSArray);
2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036
  }

  Handle<JSArray> result = factory->NewJSArray(0);
  int32_t length = formatted.length();
  if (length == 0) return result;

  int index = 0;
  int32_t previous_end_pos = 0;
  Handle<String> substring;
  while (fp_iter.next(fp)) {
    int32_t begin_pos = fp.getBeginIndex();
    int32_t end_pos = fp.getEndIndex();

    if (previous_end_pos < begin_pos) {
      ASSIGN_RETURN_ON_EXCEPTION(
          isolate, substring,
          Intl::ToString(isolate, formatted, previous_end_pos, begin_pos),
2037
          JSArray);
2038 2039 2040 2041 2042 2043 2044 2045 2046
      if (output_source) {
        Intl::AddElement(isolate, result, index,
                         IcuDateFieldIdToDateType(-1, isolate), substring,
                         isolate->factory()->source_string(),
                         isolate->factory()->shared_string());
      } else {
        Intl::AddElement(isolate, result, index,
                         IcuDateFieldIdToDateType(-1, isolate), substring);
      }
2047 2048 2049 2050
      ++index;
    }
    ASSIGN_RETURN_ON_EXCEPTION(
        isolate, substring,
2051
        Intl::ToString(isolate, formatted, begin_pos, end_pos), JSArray);
2052 2053 2054 2055 2056 2057 2058 2059 2060 2061
    if (output_source) {
      Intl::AddElement(isolate, result, index,
                       IcuDateFieldIdToDateType(fp.getField(), isolate),
                       substring, isolate->factory()->source_string(),
                       isolate->factory()->shared_string());
    } else {
      Intl::AddElement(isolate, result, index,
                       IcuDateFieldIdToDateType(fp.getField(), isolate),
                       substring);
    }
2062 2063 2064 2065 2066 2067
    previous_end_pos = end_pos;
    ++index;
  }
  if (previous_end_pos < length) {
    ASSIGN_RETURN_ON_EXCEPTION(
        isolate, substring,
2068
        Intl::ToString(isolate, formatted, previous_end_pos, length), JSArray);
2069 2070 2071 2072 2073 2074 2075 2076 2077
    if (output_source) {
      Intl::AddElement(isolate, result, index,
                       IcuDateFieldIdToDateType(-1, isolate), substring,
                       isolate->factory()->source_string(),
                       isolate->factory()->shared_string());
    } else {
      Intl::AddElement(isolate, result, index,
                       IcuDateFieldIdToDateType(-1, isolate), substring);
    }
2078 2079 2080 2081
  }
  JSObject::ValidateElements(*result);
  return result;
}
2082

2083
const std::set<std::string>& JSDateTimeFormat::GetAvailableLocales() {
2084
  return Intl::GetAvailableLocalesForDateFormat();
2085 2086
}

2087 2088
Handle<String> JSDateTimeFormat::HourCycleAsString() const {
  switch (hour_cycle()) {
2089
    case HourCycle::kUndefined:
2090
      return GetReadOnlyRoots().undefined_string_handle();
2091
    case HourCycle::kH11:
2092
      return GetReadOnlyRoots().h11_string_handle();
2093
    case HourCycle::kH12:
2094
      return GetReadOnlyRoots().h12_string_handle();
2095
    case HourCycle::kH23:
2096
      return GetReadOnlyRoots().h23_string_handle();
2097
    case HourCycle::kH24:
2098 2099 2100 2101 2102 2103
      return GetReadOnlyRoots().h24_string_handle();
    default:
      UNREACHABLE();
  }
}

2104 2105
namespace {

2106 2107 2108 2109
Maybe<bool> AddPartForFormatRange(
    Isolate* isolate, Handle<JSArray> array, const icu::UnicodeString& string,
    int32_t index, int32_t field, int32_t start, int32_t end,
    const Intl::FormatRangeSourceTracker& tracker) {
2110 2111 2112 2113 2114 2115 2116
  Handle<String> substring;
  ASSIGN_RETURN_ON_EXCEPTION_VALUE(isolate, substring,
                                   Intl::ToString(isolate, string, start, end),
                                   Nothing<bool>());
  Intl::AddElement(isolate, array, index,
                   IcuDateFieldIdToDateType(field, isolate), substring,
                   isolate->factory()->source_string(),
2117
                   Intl::SourceString(isolate, tracker.GetSource(start, end)));
2118 2119 2120
  return Just(true);
}

2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139
MaybeHandle<String> FormattedToString(Isolate* isolate,
                                      const icu::FormattedValue& formatted,
                                      bool* outputRange) {
  UErrorCode status = U_ZERO_ERROR;
  icu::UnicodeString result = formatted.toString(status);
  if (U_FAILURE(status)) {
    THROW_NEW_ERROR(isolate, NewTypeError(MessageTemplate::kIcuError), String);
  }
  *outputRange = false;
  icu::ConstrainedFieldPosition cfpos;
  while (formatted.nextPosition(cfpos, status)) {
    if (cfpos.getCategory() == UFIELD_CATEGORY_DATE_INTERVAL_SPAN) {
      *outputRange = true;
      break;
    }
  }
  return Intl::ToString(isolate, result);
}

2140 2141 2142
// A helper function to convert the FormattedDateInterval to a
// MaybeHandle<JSArray> for the implementation of formatRangeToParts.
MaybeHandle<JSArray> FormattedDateIntervalToJSArray(
2143
    Isolate* isolate, const icu::FormattedValue& formatted, bool* outputRange) {
2144
  UErrorCode status = U_ZERO_ERROR;
2145
  icu::UnicodeString result = formatted.toString(status);
2146

2147 2148 2149 2150 2151
  Factory* factory = isolate->factory();
  Handle<JSArray> array = factory->NewJSArray(0);
  icu::ConstrainedFieldPosition cfpos;
  int index = 0;
  int32_t previous_end_pos = 0;
2152
  Intl::FormatRangeSourceTracker tracker;
2153
  *outputRange = false;
2154 2155 2156 2157 2158 2159 2160
  while (formatted.nextPosition(cfpos, status)) {
    int32_t category = cfpos.getCategory();
    int32_t field = cfpos.getField();
    int32_t start = cfpos.getStart();
    int32_t limit = cfpos.getLimit();

    if (category == UFIELD_CATEGORY_DATE_INTERVAL_SPAN) {
Frank Tang's avatar
Frank Tang committed
2161
      DCHECK_LE(field, 2);
2162
      *outputRange = true;
2163 2164
      tracker.Add(field, start, limit);
    } else {
Frank Tang's avatar
Frank Tang committed
2165
      DCHECK(category == UFIELD_CATEGORY_DATE);
2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196
      if (start > previous_end_pos) {
        // Add "literal" from the previous end position to the start if
        // necessary.
        Maybe<bool> maybe_added =
            AddPartForFormatRange(isolate, array, result, index, -1,
                                  previous_end_pos, start, tracker);
        MAYBE_RETURN(maybe_added, Handle<JSArray>());
        previous_end_pos = start;
        index++;
      }
      Maybe<bool> maybe_added = AddPartForFormatRange(
          isolate, array, result, index, field, start, limit, tracker);
      MAYBE_RETURN(maybe_added, Handle<JSArray>());
      previous_end_pos = limit;
      ++index;
    }
  }
  int32_t end = result.length();
  // Add "literal" in the end if necessary.
  if (end > previous_end_pos) {
    Maybe<bool> maybe_added = AddPartForFormatRange(
        isolate, array, result, index, -1, previous_end_pos, end, tracker);
    MAYBE_RETURN(maybe_added, Handle<JSArray>());
  }

  if (U_FAILURE(status)) {
    THROW_NEW_ERROR(isolate, NewTypeError(MessageTemplate::kIcuError), JSArray);
  }

  JSObject::ValidateElements(*array);
  return array;
2197 2198
}

2199
// The shared code between formatRange and formatRangeToParts
2200 2201 2202 2203 2204
template <typename T,
          MaybeHandle<T> (*F)(Isolate*, const icu::FormattedValue&, bool*)>
MaybeHandle<T> FormatRangeCommon(Isolate* isolate,
                                 Handle<JSDateTimeFormat> date_time_format,
                                 double x, double y, bool* outputRange) {
2205 2206 2207
  // Track newer feature formateRange and formatRangeToParts
  isolate->CountUsage(v8::Isolate::UseCounterFeature::kDateTimeFormatRange);

2208 2209 2210 2211 2212 2213
  // #sec-partitiondatetimerangepattern
  // 1. Let x be TimeClip(x).
  x = DateCache::TimeClip(x);
  // 2. If x is NaN, throw a RangeError exception.
  if (std::isnan(x)) {
    THROW_NEW_ERROR(isolate, NewRangeError(MessageTemplate::kInvalidTimeValue),
2214
                    T);
2215 2216 2217 2218 2219 2220
  }
  // 3. Let y be TimeClip(y).
  y = DateCache::TimeClip(y);
  // 4. If y is NaN, throw a RangeError exception.
  if (std::isnan(y)) {
    THROW_NEW_ERROR(isolate, NewRangeError(MessageTemplate::kInvalidTimeValue),
2221
                    T);
2222 2223
  }

2224 2225 2226 2227 2228
  icu::DateIntervalFormat* format =
      LazyCreateDateIntervalFormat(isolate, date_time_format);
  if (format == nullptr) {
    THROW_NEW_ERROR(isolate, NewTypeError(MessageTemplate::kIcuError), T);
  }
2229

2230
  UErrorCode status = U_ZERO_ERROR;
2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241

  icu::SimpleDateFormat* date_format =
      date_time_format->icu_simple_date_format().raw();
  const icu::Calendar* calendar = date_format->getCalendar();
  std::unique_ptr<icu::Calendar> c1(calendar->clone());
  std::unique_ptr<icu::Calendar> c2(calendar->clone());
  c1->setTime(x, status);
  c2->setTime(y, status);
  // We need to format by Calendar because we need the Gregorian change
  // adjustment already in the SimpleDateFormat to set the correct value of date
  // older than Oct 15, 1582.
2242
  icu::FormattedDateInterval formatted =
2243
      format->formatToValue(*c1, *c2, status);
2244 2245 2246
  if (U_FAILURE(status)) {
    THROW_NEW_ERROR(isolate, NewTypeError(MessageTemplate::kIcuError), T);
  }
2247
  return F(isolate, formatted, outputRange);
2248
}
2249

2250 2251 2252 2253 2254
}  // namespace

MaybeHandle<String> JSDateTimeFormat::FormatRange(
    Isolate* isolate, Handle<JSDateTimeFormat> date_time_format, double x,
    double y) {
2255
  bool outputRange = true;
2256 2257
  MaybeHandle<String> ret = FormatRangeCommon<String, FormattedToString>(
      isolate, date_time_format, x, y, &outputRange);
2258 2259 2260 2261 2262
  if (outputRange) {
    return ret;
  }
  return FormatDateTime(isolate,
                        *(date_time_format->icu_simple_date_format().raw()), x);
2263 2264 2265 2266 2267
}

MaybeHandle<JSArray> JSDateTimeFormat::FormatRangeToParts(
    Isolate* isolate, Handle<JSDateTimeFormat> date_time_format, double x,
    double y) {
2268 2269
  bool outputRange = true;
  MaybeHandle<JSArray> ret =
2270 2271
      FormatRangeCommon<JSArray, FormattedDateIntervalToJSArray>(
          isolate, date_time_format, x, y, &outputRange);
2272 2273 2274 2275
  if (outputRange) {
    return ret;
  }
  return JSDateTimeFormat::FormatToParts(isolate, date_time_format, x, true);
2276 2277
}

2278 2279
}  // namespace internal
}  // namespace v8