summaryrefslogtreecommitdiff
path: root/deps/v8/src/objects/js-duration-format.cc
blob: 4b15db7fe3488da83b0cbe1f409737187c1f9748 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
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
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
// Copyright 2022 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-duration-format.h"

#include <map>
#include <memory>
#include <string>
#include <string_view>

#include "src/execution/isolate.h"
#include "src/heap/factory.h"
#include "src/objects/intl-objects.h"
#include "src/objects/js-duration-format-inl.h"
#include "src/objects/js-number-format.h"
#include "src/objects/js-temporal-objects.h"
#include "src/objects/managed-inl.h"
#include "src/objects/objects-inl.h"
#include "src/objects/option-utils.h"
#include "unicode/listformatter.h"
#include "unicode/locid.h"
#include "unicode/numberformatter.h"
#include "unicode/ulistformatter.h"
#include "unicode/unumberformatter.h"

namespace v8 {
namespace internal {

using temporal::DurationRecord;

namespace {

// #sec-getdurationunitoptions
enum class StylesList { k3Styles, k4Styles, k5Styles };
enum class UnitKind { kMinutesOrSeconds, kOthers };
struct DurationUnitOptions {
  JSDurationFormat::FieldStyle style;
  JSDurationFormat::Display display;
};
Maybe<DurationUnitOptions> GetDurationUnitOptions(
    Isolate* isolate, const char* unit, const char* display_field,
    Handle<JSReceiver> options, JSDurationFormat::Style base_style,
    StylesList styles_list, JSDurationFormat::FieldStyle prev_style,
    UnitKind unit_kind, const char* method_name) {
  JSDurationFormat::FieldStyle style;
  JSDurationFormat::FieldStyle digital_base;
  // 1. Let style be ? GetOption(options, unit, "string", stylesList,
  // undefined).
  switch (styles_list) {
    case StylesList::k3Styles:
      // For years, months, weeks, days
      MAYBE_ASSIGN_RETURN_ON_EXCEPTION_VALUE(
          isolate, style,
          GetStringOption<JSDurationFormat::FieldStyle>(
              isolate, options, unit, method_name, {"long", "short", "narrow"},
              {JSDurationFormat::FieldStyle::kLong,
               JSDurationFormat::FieldStyle::kShort,
               JSDurationFormat::FieldStyle::kNarrow},
              JSDurationFormat::FieldStyle::kUndefined),
          Nothing<DurationUnitOptions>());
      digital_base = JSDurationFormat::FieldStyle::kShort;
      break;
    case StylesList::k4Styles:
      // For milliseconds, microseconds, nanoseconds
      MAYBE_ASSIGN_RETURN_ON_EXCEPTION_VALUE(
          isolate, style,
          GetStringOption<JSDurationFormat::FieldStyle>(
              isolate, options, unit, method_name,
              {"long", "short", "narrow", "numeric"},
              {JSDurationFormat::FieldStyle::kLong,
               JSDurationFormat::FieldStyle::kShort,
               JSDurationFormat::FieldStyle::kNarrow,
               JSDurationFormat::FieldStyle::kNumeric},
              JSDurationFormat::FieldStyle::kUndefined),
          Nothing<DurationUnitOptions>());
      digital_base = JSDurationFormat::FieldStyle::kNumeric;
      break;
    case StylesList::k5Styles:
      // For hours, minutes, seconds
      MAYBE_ASSIGN_RETURN_ON_EXCEPTION_VALUE(
          isolate, style,
          GetStringOption<JSDurationFormat::FieldStyle>(
              isolate, options, unit, method_name,
              {"long", "short", "narrow", "numeric", "2-digit"},
              {JSDurationFormat::FieldStyle::kLong,
               JSDurationFormat::FieldStyle::kShort,
               JSDurationFormat::FieldStyle::kNarrow,
               JSDurationFormat::FieldStyle::kNumeric,
               JSDurationFormat::FieldStyle::k2Digit},
              JSDurationFormat::FieldStyle::kUndefined),
          Nothing<DurationUnitOptions>());
      digital_base = JSDurationFormat::FieldStyle::kNumeric;
      break;
  }

  // 2. Let displayDefault be "always".
  JSDurationFormat::Display display_default =
      JSDurationFormat::Display::kAlways;
  // 3. If style is undefined, then
  if (style == JSDurationFormat::FieldStyle::kUndefined) {
    // a. If baseStyle is "digital", then
    if (base_style == JSDurationFormat::Style::kDigital) {
      // i. If unit is not one of "hours", "minutes", or "seconds", then
      if (styles_list != StylesList::k5Styles) {
        DCHECK_NE(0, strcmp(unit, "hours"));
        DCHECK_NE(0, strcmp(unit, "minutes"));
        DCHECK_NE(0, strcmp(unit, "seconds"));
        // a. Set displayDefault to "auto".
        display_default = JSDurationFormat::Display::kAuto;
      }
      // ii. Set style to digitalBase.
      style = digital_base;
      // b. Else
    } else {
      // i. Set displayDefault to "auto".
      display_default = JSDurationFormat::Display::kAuto;
      // ii. if prevStyle is "numeric" or "2-digit", then
      if (prev_style == JSDurationFormat::FieldStyle::kNumeric ||
          prev_style == JSDurationFormat::FieldStyle::k2Digit) {
        // 1. Set style to "numeric".
        style = JSDurationFormat::FieldStyle::kNumeric;
        // iii. Else,
      } else {
        // 1. Set style to baseStyle.
        switch (base_style) {
          case JSDurationFormat::Style::kLong:
            style = JSDurationFormat::FieldStyle::kLong;
            break;
          case JSDurationFormat::Style::kShort:
            style = JSDurationFormat::FieldStyle::kShort;
            break;
          case JSDurationFormat::Style::kNarrow:
            style = JSDurationFormat::FieldStyle::kNarrow;
            break;
          default:
            UNREACHABLE();
        }
      }
    }
  }
  // 4. Let displayField be the string-concatenation of unit and "Display".
  // 5. Let display be ? GetOption(options, displayField, "string", « "auto",
  // "always" », displayDefault).
  JSDurationFormat::Display display;
  MAYBE_ASSIGN_RETURN_ON_EXCEPTION_VALUE(
      isolate, display,
      GetStringOption<JSDurationFormat::Display>(
          isolate, options, display_field, method_name, {"auto", "always"},
          {JSDurationFormat::Display::kAuto,
           JSDurationFormat::Display::kAlways},
          display_default),
      Nothing<DurationUnitOptions>());
  // 6. If prevStyle is "numeric" or "2-digit", then
  if (prev_style == JSDurationFormat::FieldStyle::kNumeric ||
      prev_style == JSDurationFormat::FieldStyle::k2Digit) {
    // a. If style is not "numeric" or "2-digit", then
    if (style != JSDurationFormat::FieldStyle::kNumeric &&
        style != JSDurationFormat::FieldStyle::k2Digit) {
      // i. Throw a RangeError exception.
      // b. Else if unit is "minutes" or "seconds", then
    } else if (unit_kind == UnitKind::kMinutesOrSeconds) {
      CHECK(strcmp(unit, "minutes") == 0 || strcmp(unit, "seconds") == 0);
      // i. Set style to "2-digit".
      style = JSDurationFormat::FieldStyle::k2Digit;
    }
  }
  // 7. Return the Record { [[Style]]: style, [[Display]]: display }.
  return Just(DurationUnitOptions({style, display}));
}

}  // namespace
MaybeHandle<JSDurationFormat> JSDurationFormat::New(
    Isolate* isolate, Handle<Map> map, Handle<Object> locales,
    Handle<Object> input_options) {
  Factory* factory = isolate->factory();
  const char* method_name = "Intl.DurationFormat";

  // 3. Let requestedLocales be ? CanonicalizeLocaleList(locales).
  std::vector<std::string> requested_locales;
  MAYBE_ASSIGN_RETURN_ON_EXCEPTION_VALUE(
      isolate, requested_locales,
      Intl::CanonicalizeLocaleList(isolate, locales),
      Handle<JSDurationFormat>());

  // 4. Let options be ? GetOptionsObject(options).
  Handle<JSReceiver> options;
  ASSIGN_RETURN_ON_EXCEPTION(
      isolate, options, GetOptionsObject(isolate, input_options, method_name),
      JSDurationFormat);

  // 5. Let matcher be ? GetOption(options, "localeMatcher", "string", «
  // "lookup", "best fit" », "best fit").
  Intl::MatcherOption matcher;
  MAYBE_ASSIGN_RETURN_ON_EXCEPTION_VALUE(
      isolate, matcher, Intl::GetLocaleMatcher(isolate, options, method_name),
      Handle<JSDurationFormat>());

  // 6. Let numberingSystem be ? GetOption(options, "numberingSystem", "string",
  // undefined, undefined).
  //
  // 7. If numberingSystem is not undefined, then
  //
  // a. If numberingSystem does not match the Unicode Locale Identifier type
  // nonterminal, throw a RangeError exception.
  // Note: The matching test and throw in Step 7-a is throw inside
  // Intl::GetNumberingSystem.
  std::unique_ptr<char[]> numbering_system_str = nullptr;
  bool get;
  MAYBE_ASSIGN_RETURN_ON_EXCEPTION_VALUE(
      isolate, get,
      Intl::GetNumberingSystem(isolate, options, method_name,
                               &numbering_system_str),
      Handle<JSDurationFormat>());

  // 8. Let opt be the Record { [[localeMatcher]]: matcher, [[nu]]:
  // numberingSystem }.
  // 9. Let r be ResolveLocale(%DurationFormat%.[[AvailableLocales]],
  // requestedLocales, opt, %DurationFormat%.[[RelevantExtensionKeys]],
  // %DurationFormat%.[[LocaleData]]).
  std::set<std::string> relevant_extension_keys{"nu"};
  Intl::ResolvedLocale r;
  MAYBE_ASSIGN_RETURN_ON_EXCEPTION_VALUE(
      isolate, r,
      Intl::ResolveLocale(isolate, JSDurationFormat::GetAvailableLocales(),
                          requested_locales, matcher, relevant_extension_keys),
      Handle<JSDurationFormat>());

  // 10. Let locale be r.[[locale]].
  icu::Locale r_locale = r.icu_locale;
  UErrorCode status = U_ZERO_ERROR;
  // 11. Set durationFormat.[[Locale]] to locale.
  // 12. Set durationFormat.[[NumberingSystem]] to r.[[nu]].
  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()) {
      r_locale.setUnicodeKeywordValue("nu", nullptr, status);
      DCHECK(U_SUCCESS(status));
    }
  }
  icu::Locale icu_locale = r_locale;
  if (numbering_system_str != nullptr &&
      Intl::IsValidNumberingSystem(numbering_system_str.get())) {
    r_locale.setUnicodeKeywordValue("nu", numbering_system_str.get(), status);
    DCHECK(U_SUCCESS(status));
  }
  std::string numbering_system = Intl::GetNumberingSystem(r_locale);

  // 13. Let style be ? GetOption(options, "style", "string", « "long", "short",
  // "narrow", "digital" », "long").
  Style style;
  MAYBE_ASSIGN_RETURN_ON_EXCEPTION_VALUE(
      isolate, style,
      GetStringOption<Style>(
          isolate, options, "style", method_name,
          {"long", "short", "narrow", "digital"},
          {Style::kLong, Style::kShort, Style::kNarrow, Style::kDigital},
          Style::kShort),
      Handle<JSDurationFormat>());

  // 14. Set durationFormat.[[Style]] to style.
  // 15. Set durationFormat.[[DataLocale]] to r.[[dataLocale]].
  Handle<Managed<icu::Locale>> managed_locale =
      Managed<icu::Locale>::FromRawPtr(isolate, 0, icu_locale.clone());
  // 16. Let prevStyle be the empty String.
  FieldStyle prev_style = FieldStyle::kUndefined;
  // 17. For each row of Table 1, except the header row, in table order, do
  //   a. Let styleSlot be the Style Slot value of the current row.
  //   b. Let displaySlot be the Display Slot value of the current row.
  //   c. Let unit be the Unit value.
  //   d. Let valueList be the Values value.
  //   e. Let digitalBase be the Digital Default value.
  //   f. Let unitOptions be ? GetDurationUnitOptions(unit, options, style,
  //      valueList, digitalBase, prevStyle).
  //      of durationFormat to unitOptions.[[Style]].
  //   h. Set the value of the
  //      displaySlot slot of durationFormat to unitOptions.[[Display]].
  //   i. If unit is one of "hours", "minutes", "seconds", "milliseconds",
  //      or "microseconds", then
  //      i. Set prevStyle to unitOptions.[[Style]].
  //   g. Set the value of the styleSlot slot
  DurationUnitOptions years_option;
  DurationUnitOptions months_option;
  DurationUnitOptions weeks_option;
  DurationUnitOptions days_option;
  DurationUnitOptions hours_option;
  DurationUnitOptions minutes_option;
  DurationUnitOptions seconds_option;
  DurationUnitOptions milliseconds_option;
  DurationUnitOptions microseconds_option;
  DurationUnitOptions nanoseconds_option;

#define CALL_GET_DURATION_UNIT_OPTIONS(u, sl, uk)                           \
  MAYBE_ASSIGN_RETURN_ON_EXCEPTION_VALUE(                                   \
      isolate, u##_option,                                                  \
      GetDurationUnitOptions(isolate, #u, #u "Display", options, style, sl, \
                             prev_style, uk, method_name),                  \
      Handle<JSDurationFormat>());
  CALL_GET_DURATION_UNIT_OPTIONS(years, StylesList::k3Styles, UnitKind::kOthers)
  CALL_GET_DURATION_UNIT_OPTIONS(months, StylesList::k3Styles,
                                 UnitKind::kOthers)
  CALL_GET_DURATION_UNIT_OPTIONS(weeks, StylesList::k3Styles, UnitKind::kOthers)
  CALL_GET_DURATION_UNIT_OPTIONS(days, StylesList::k3Styles, UnitKind::kOthers)
  CALL_GET_DURATION_UNIT_OPTIONS(hours, StylesList::k5Styles, UnitKind::kOthers)
  prev_style = hours_option.style;
  CALL_GET_DURATION_UNIT_OPTIONS(minutes, StylesList::k5Styles,
                                 UnitKind::kMinutesOrSeconds)
  prev_style = minutes_option.style;
  CALL_GET_DURATION_UNIT_OPTIONS(seconds, StylesList::k5Styles,
                                 UnitKind::kMinutesOrSeconds)
  prev_style = seconds_option.style;
  CALL_GET_DURATION_UNIT_OPTIONS(milliseconds, StylesList::k4Styles,
                                 UnitKind::kOthers)
  prev_style = milliseconds_option.style;
  CALL_GET_DURATION_UNIT_OPTIONS(microseconds, StylesList::k4Styles,
                                 UnitKind::kOthers)
  prev_style = microseconds_option.style;
  CALL_GET_DURATION_UNIT_OPTIONS(nanoseconds, StylesList::k4Styles,
                                 UnitKind::kOthers)
#undef CALL_GET_DURATION_UNIT_OPTIONS
  // 18. Set durationFormat.[[FractionalDigits]] to ? GetNumberOption(options,
  // "fractionalDigits", 0, 9, undefined).
  int fractional_digits;
  MAYBE_ASSIGN_RETURN_ON_EXCEPTION_VALUE(
      isolate, fractional_digits,
      GetNumberOption(isolate, options, factory->fractionalDigits_string(), 0,
                      9, 0),
      Handle<JSDurationFormat>());

  icu::number::LocalizedNumberFormatter fmt =
      icu::number::UnlocalizedNumberFormatter()
          .roundingMode(UNUM_ROUND_HALFUP)
          .locale(icu_locale);
  if (!numbering_system.empty() && numbering_system != "latn") {
    fmt = fmt.adoptSymbols(icu::NumberingSystem::createInstanceByName(
        numbering_system.c_str(), status));
    DCHECK(U_SUCCESS(status));
  }
  Handle<Managed<icu::number::LocalizedNumberFormatter>>
      managed_number_formatter =
          Managed<icu::number::LocalizedNumberFormatter>::FromRawPtr(
              isolate, 0, new icu::number::LocalizedNumberFormatter(fmt));

  // 19. Return durationFormat.
  Handle<JSDurationFormat> duration_format = Handle<JSDurationFormat>::cast(
      factory->NewFastOrSlowJSObjectFromMap(map));
  duration_format->set_style_flags(0);
  duration_format->set_display_flags(0);
  duration_format->set_style(style);
  duration_format->set_years_style(years_option.style);
  duration_format->set_months_style(months_option.style);
  duration_format->set_weeks_style(weeks_option.style);
  duration_format->set_days_style(days_option.style);
  duration_format->set_hours_style(hours_option.style);
  duration_format->set_minutes_style(minutes_option.style);
  duration_format->set_seconds_style(seconds_option.style);
  duration_format->set_milliseconds_style(milliseconds_option.style);
  duration_format->set_microseconds_style(microseconds_option.style);
  duration_format->set_nanoseconds_style(nanoseconds_option.style);

  duration_format->set_years_display(years_option.display);
  duration_format->set_months_display(months_option.display);
  duration_format->set_weeks_display(weeks_option.display);
  duration_format->set_days_display(days_option.display);
  duration_format->set_hours_display(hours_option.display);
  duration_format->set_minutes_display(minutes_option.display);
  duration_format->set_seconds_display(seconds_option.display);
  duration_format->set_milliseconds_display(milliseconds_option.display);
  duration_format->set_microseconds_display(microseconds_option.display);
  duration_format->set_nanoseconds_display(nanoseconds_option.display);

  duration_format->set_fractional_digits(fractional_digits);

  duration_format->set_icu_locale(*managed_locale);
  duration_format->set_icu_number_formatter(*managed_number_formatter);

  return duration_format;
}

namespace {

Handle<String> StyleToString(Isolate* isolate, JSDurationFormat::Style style) {
  switch (style) {
    case JSDurationFormat::Style::kLong:
      return ReadOnlyRoots(isolate).long_string_handle();
    case JSDurationFormat::Style::kShort:
      return ReadOnlyRoots(isolate).short_string_handle();
    case JSDurationFormat::Style::kNarrow:
      return ReadOnlyRoots(isolate).narrow_string_handle();
    case JSDurationFormat::Style::kDigital:
      return ReadOnlyRoots(isolate).digital_string_handle();
  }
}

Handle<String> StyleToString(Isolate* isolate,
                             JSDurationFormat::FieldStyle style) {
  switch (style) {
    case JSDurationFormat::FieldStyle::kLong:
      return ReadOnlyRoots(isolate).long_string_handle();
    case JSDurationFormat::FieldStyle::kShort:
      return ReadOnlyRoots(isolate).short_string_handle();
    case JSDurationFormat::FieldStyle::kNarrow:
      return ReadOnlyRoots(isolate).narrow_string_handle();
    case JSDurationFormat::FieldStyle::kNumeric:
      return ReadOnlyRoots(isolate).numeric_string_handle();
    case JSDurationFormat::FieldStyle::k2Digit:
      return ReadOnlyRoots(isolate).two_digit_string_handle();
    case JSDurationFormat::FieldStyle::kUndefined:
      UNREACHABLE();
  }
}

Handle<String> DisplayToString(Isolate* isolate,
                               JSDurationFormat::Display display) {
  switch (display) {
    case JSDurationFormat::Display::kAuto:
      return ReadOnlyRoots(isolate).auto_string_handle();
    case JSDurationFormat::Display::kAlways:
      return ReadOnlyRoots(isolate).always_string_handle();
  }
}

}  // namespace

Handle<JSObject> JSDurationFormat::ResolvedOptions(
    Isolate* isolate, Handle<JSDurationFormat> format) {
  Factory* factory = isolate->factory();
  Handle<JSObject> options = factory->NewJSObject(isolate->object_function());

  Handle<String> locale = factory->NewStringFromAsciiChecked(
      Intl::ToLanguageTag(*format->icu_locale().raw()).FromJust().c_str());
  UErrorCode status = U_ZERO_ERROR;
  icu::UnicodeString skeleton =
      format->icu_number_formatter().raw()->toSkeleton(status);
  DCHECK(U_SUCCESS(status));

  Handle<String> numbering_system;
  CHECK(Intl::ToString(isolate,
                       JSNumberFormat::NumberingSystemFromSkeleton(skeleton))
            .ToHandle(&numbering_system));

  Handle<Smi> fractional_digits =
      handle(Smi::FromInt(format->fractional_digits()), isolate);

  bool created;

#define OUTPUT_PROPERTY(s, f)                                           \
  MAYBE_ASSIGN_RETURN_ON_EXCEPTION_VALUE(                               \
      isolate, created,                                                 \
      JSReceiver::CreateDataProperty(isolate, options, factory->s(), f, \
                                     Just(kDontThrow)),                 \
      Handle<JSObject>());                                              \
  CHECK(created);
#define OUTPUT_STYLE_PROPERTY(p) \
  OUTPUT_PROPERTY(p##_string, StyleToString(isolate, format->p##_style()))
#define OUTPUT_DISPLAY_PROPERTY(p)   \
  OUTPUT_PROPERTY(p##Display_string, \
                  DisplayToString(isolate, format->p##_display()))
#define OUTPUT_STYLE_AND_DISPLAY_PROPERTIES(p) \
  OUTPUT_STYLE_PROPERTY(p);                    \
  OUTPUT_DISPLAY_PROPERTY(p);

  OUTPUT_PROPERTY(locale_string, locale);
  OUTPUT_PROPERTY(style_string, StyleToString(isolate, format->style()));

  OUTPUT_STYLE_AND_DISPLAY_PROPERTIES(years);
  OUTPUT_STYLE_AND_DISPLAY_PROPERTIES(months);
  OUTPUT_STYLE_AND_DISPLAY_PROPERTIES(weeks);
  OUTPUT_STYLE_AND_DISPLAY_PROPERTIES(days);
  OUTPUT_STYLE_AND_DISPLAY_PROPERTIES(hours);
  OUTPUT_STYLE_AND_DISPLAY_PROPERTIES(minutes);
  OUTPUT_STYLE_AND_DISPLAY_PROPERTIES(seconds);
  OUTPUT_STYLE_AND_DISPLAY_PROPERTIES(milliseconds);
  OUTPUT_STYLE_AND_DISPLAY_PROPERTIES(microseconds);
  OUTPUT_STYLE_AND_DISPLAY_PROPERTIES(nanoseconds);

  OUTPUT_PROPERTY(fractionalDigits_string, fractional_digits);
  OUTPUT_PROPERTY(numberingSystem_string, numbering_system);
#undef OUTPUT_PROPERTY
#undef OUTPUT_STYLE_PROPERTY
#undef OUTPUT_DISPLAY_PROPERTY
#undef OUTPUT_STYLE_AND_DISPLAY_PROPERTIES

  return options;
}

namespace {

UNumberUnitWidth ToUNumberUnitWidth(JSDurationFormat::FieldStyle style) {
  switch (style) {
    case JSDurationFormat::FieldStyle::kShort:
      return UNumberUnitWidth::UNUM_UNIT_WIDTH_SHORT;
    case JSDurationFormat::FieldStyle::kLong:
      return UNumberUnitWidth::UNUM_UNIT_WIDTH_FULL_NAME;
    case JSDurationFormat::FieldStyle::kNarrow:
      return UNumberUnitWidth::UNUM_UNIT_WIDTH_NARROW;
    default:
      UNREACHABLE();
  }
}

void Output(std::vector<icu::UnicodeString>* out, double value,
            const icu::number::LocalizedNumberFormatter& fmt) {
  UErrorCode status = U_ZERO_ERROR;
  out->push_back(fmt.formatDouble(value, status).toString(status));
  CHECK(U_SUCCESS(status));
}

void Output3Styles(std::vector<icu::UnicodeString>* out,
                   std::vector<std::string>* types, const char* type,
                   double value, JSDurationFormat::Display display,
                   const icu::number::LocalizedNumberFormatter& fmt) {
  if (value == 0 && display == JSDurationFormat::Display::kAuto) return;
  types->push_back(type);
  Output(out, value, fmt);
}

void Output4Styles(std::vector<icu::UnicodeString>* out,
                   std::vector<std::string>* types, const char* type,
                   double value, JSDurationFormat::Display display,
                   JSDurationFormat::FieldStyle style,
                   const icu::number::LocalizedNumberFormatter& fmt,
                   icu::MeasureUnit unit) {
  if (value == 0 && display == JSDurationFormat::Display::kAuto) return;
  if (style == JSDurationFormat::FieldStyle::kNumeric) {
    types->push_back(type);
    return Output(out, value, fmt);
  }
  Output3Styles(out, types, type, value, display,
                fmt.unit(unit).unitWidth(ToUNumberUnitWidth(style)));
}
void Output5Styles(std::vector<icu::UnicodeString>* out,
                   std::vector<std::string>* types, const char* type,
                   double value, JSDurationFormat::Display display,
                   JSDurationFormat::FieldStyle style,
                   const icu::number::LocalizedNumberFormatter& fmt,
                   icu::MeasureUnit unit) {
  if (value == 0 && display == JSDurationFormat::Display::kAuto) return;
  if (style == JSDurationFormat::FieldStyle::k2Digit) {
    types->push_back(type);
    return Output(out, value,
                  fmt.integerWidth(icu::number::IntegerWidth::zeroFillTo(2)));
  }
  Output4Styles(out, types, type, value, display, style, fmt, unit);
}

void DurationRecordToListOfStrings(
    std::vector<icu::UnicodeString>* out, std::vector<std::string>* types,
    Handle<JSDurationFormat> df,
    const icu::number::LocalizedNumberFormatter& fmt,
    const DurationRecord& record) {
  // The handling of "2-digit" or "numeric" style of
  // step l.i.6.c.i-ii "Let separator be
  // dataLocaleData.[[digitalFormat]].[[separator]]." and
  // "Append the new Record { [[Type]]: "literal", [[Value]]: separator} to the
  // end of result." are not implemented following the spec due to unresolved
  // issues in
  // https://github.com/tc39/proposal-intl-duration-format/issues/55
  Output3Styles(out, types, "years", record.years, df->years_display(),
                fmt.unit(icu::MeasureUnit::getYear())
                    .unitWidth(ToUNumberUnitWidth(df->years_style())));
  Output3Styles(out, types, "months", record.months, df->months_display(),
                fmt.unit(icu::MeasureUnit::getMonth())
                    .unitWidth(ToUNumberUnitWidth(df->months_style())));
  Output3Styles(out, types, "weeks", record.weeks, df->weeks_display(),
                fmt.unit(icu::MeasureUnit::getWeek())
                    .unitWidth(ToUNumberUnitWidth(df->weeks_style())));
  Output3Styles(out, types, "days", record.time_duration.days,
                df->days_display(),
                fmt.unit(icu::MeasureUnit::getDay())
                    .unitWidth(ToUNumberUnitWidth(df->days_style())));
  Output5Styles(out, types, "hours", record.time_duration.hours,
                df->hours_display(), df->hours_style(), fmt,
                icu::MeasureUnit::getHour());
  Output5Styles(out, types, "minutes", record.time_duration.minutes,
                df->minutes_display(), df->minutes_style(), fmt,
                icu::MeasureUnit::getMinute());
  int32_t fractional_digits = df->fractional_digits();
  if (df->milliseconds_style() == JSDurationFormat::FieldStyle::kNumeric) {
    // a. Set value to value + duration.[[Milliseconds]] / 10^3 +
    // duration.[[Microseconds]] / 10^6 + duration.[[Nanoseconds]] / 10^9.
    double value = record.time_duration.seconds +
                   record.time_duration.milliseconds / 1e3 +
                   record.time_duration.microseconds / 1e6 +
                   record.time_duration.nanoseconds / 1e9;
    Output5Styles(out, types, "seconds", value, df->seconds_display(),
                  df->seconds_style(),
                  fmt.precision(icu::number::Precision::minMaxFraction(
                      fractional_digits, fractional_digits)),
                  icu::MeasureUnit::getSecond());
    return;
  }
  Output5Styles(out, types, "seconds", record.time_duration.seconds,
                df->seconds_display(), df->seconds_style(), fmt,
                icu::MeasureUnit::getSecond());

  if (df->microseconds_style() == JSDurationFormat::FieldStyle::kNumeric) {
    // a. Set value to value + duration.[[Microseconds]] / 10^3 +
    // duration.[[Nanoseconds]] / 10^6.
    double value = record.time_duration.milliseconds +
                   record.time_duration.microseconds / 1e3 +
                   record.time_duration.nanoseconds / 1e6;
    Output4Styles(out, types, "milliseconds", value, df->milliseconds_display(),
                  df->milliseconds_style(),
                  fmt.precision(icu::number::Precision::minMaxFraction(
                      fractional_digits, fractional_digits)),
                  icu::MeasureUnit::getMillisecond());
    return;
  }
  Output4Styles(out, types, "milliseconds", record.time_duration.milliseconds,
                df->milliseconds_display(), df->milliseconds_style(), fmt,
                icu::MeasureUnit::getMillisecond());

  if (df->nanoseconds_style() == JSDurationFormat::FieldStyle::kNumeric) {
    // a. Set value to value + duration.[[Nanoseconds]] / 10^3.
    double value = record.time_duration.microseconds +
                   record.time_duration.nanoseconds / 1e3;
    Output4Styles(out, types, "microseconds", value, df->microseconds_display(),
                  df->microseconds_style(),
                  fmt.precision(icu::number::Precision::minMaxFraction(
                      fractional_digits, fractional_digits)),
                  icu::MeasureUnit::getMicrosecond());
    return;
  }
  Output4Styles(out, types, "microseconds", record.time_duration.microseconds,
                df->microseconds_display(), df->microseconds_style(), fmt,
                icu::MeasureUnit::getMicrosecond());

  Output4Styles(out, types, "nanoseconds", record.time_duration.nanoseconds,
                df->nanoseconds_display(), df->nanoseconds_style(), fmt,
                icu::MeasureUnit::getNanosecond());
}

UListFormatterWidth StyleToWidth(JSDurationFormat::Style style) {
  switch (style) {
    case JSDurationFormat::Style::kLong:
      return ULISTFMT_WIDTH_WIDE;
    case JSDurationFormat::Style::kShort:
      return ULISTFMT_WIDTH_SHORT;
    case JSDurationFormat::Style::kNarrow:
    case JSDurationFormat::Style::kDigital:
      return ULISTFMT_WIDTH_NARROW;
  }
  UNREACHABLE();
}

template <typename T,
          MaybeHandle<T> (*Format)(Isolate*, const icu::FormattedValue&,
                                   const std::vector<std::string>&)>
MaybeHandle<T> PartitionDurationFormatPattern(Isolate* isolate,
                                              Handle<JSDurationFormat> df,
                                              const DurationRecord& record,
                                              const char* method_name) {
  // 4. Let lfOpts be ! OrdinaryObjectCreate(null).
  // 5. Perform ! CreateDataPropertyOrThrow(lfOpts, "type", "unit").
  UListFormatterType type = ULISTFMT_TYPE_UNITS;
  // 6. Let listStyle be durationFormat.[[Style]].
  // 7. If listStyle is "digital", then
  // a. Set listStyle to "narrow".
  // 8. Perform ! CreateDataPropertyOrThrow(lfOpts, "style", listStyle).
  UListFormatterWidth list_style = StyleToWidth(df->style());
  // 9. Let lf be ! Construct(%ListFormat%, « durationFormat.[[Locale]], lfOpts
  // »).
  UErrorCode status = U_ZERO_ERROR;
  icu::Locale icu_locale = *df->icu_locale().raw();
  std::unique_ptr<icu::ListFormatter> formatter(
      icu::ListFormatter::createInstance(icu_locale, type, list_style, status));
  CHECK(U_SUCCESS(status));

  std::vector<icu::UnicodeString> list;
  std::vector<std::string> types;

  DurationRecordToListOfStrings(&list, &types, df,
                                *(df->icu_number_formatter().raw()), record);

  icu::FormattedList formatted = formatter->formatStringsToValue(
      list.data(), static_cast<int32_t>(list.size()), status);
  CHECK(U_SUCCESS(status));
  return Format(isolate, formatted, types);
}

// #sec-todurationrecord
// ToDurationRecord is almost the same as temporal::ToPartialDuration
// except:
// 1) In the beginning it will throw RangeError if the type of input is String,
// 2) In the end it will throw RangeError if IsValidDurationRecord return false.
Maybe<DurationRecord> ToDurationRecord(Isolate* isolate, Handle<Object> input,
                                       const DurationRecord& default_value) {
  // 1-a. If Type(input) is String, throw a RangeError exception.
  if (input->IsString()) {
    THROW_NEW_ERROR_RETURN_VALUE(
        isolate,
        NewRangeError(MessageTemplate::kInvalid,
                      isolate->factory()->object_string(), input),
        Nothing<DurationRecord>());
  }
  // Step 1-b - 23. Same as ToTemporalPartialDurationRecord.
  DurationRecord record;
  MAYBE_ASSIGN_RETURN_ON_EXCEPTION_VALUE(
      isolate, record,
      temporal::ToPartialDuration(isolate, input, default_value),
      Nothing<DurationRecord>());
  // 24. If IsValidDurationRecord(result) is false, throw a RangeError
  // exception.
  if (!temporal::IsValidDuration(isolate, record)) {
    THROW_NEW_ERROR_RETURN_VALUE(
        isolate,
        NewRangeError(MessageTemplate::kInvalid,
                      isolate->factory()->object_string(), input),
        Nothing<DurationRecord>());
  }
  return Just(record);
}

template <typename T,
          MaybeHandle<T> (*Format)(Isolate*, const icu::FormattedValue&,
                                   const std::vector<std::string>&)>
MaybeHandle<T> FormatCommon(Isolate* isolate, Handle<JSDurationFormat> df,
                            Handle<Object> duration, const char* method_name) {
  // 1. Let df be this value.
  // 2. Perform ? RequireInternalSlot(df, [[InitializedDurationFormat]]).
  // 3. Let record be ? ToDurationRecord(duration).
  DurationRecord record;
  MAYBE_ASSIGN_RETURN_ON_EXCEPTION_VALUE(
      isolate, record,
      ToDurationRecord(isolate, duration, {0, 0, 0, {0, 0, 0, 0, 0, 0, 0}}),
      Handle<T>());
  // 5. Let parts be ! PartitionDurationFormatPattern(df, record).
  return PartitionDurationFormatPattern<T, Format>(isolate, df, record,
                                                   method_name);
}

}  // namespace

MaybeHandle<String> FormattedToString(Isolate* isolate,
                                      const icu::FormattedValue& formatted,
                                      const std::vector<std::string>&) {
  return Intl::FormattedToString(isolate, formatted);
}

MaybeHandle<JSArray> FormattedListToJSArray(
    Isolate* isolate, const icu::FormattedValue& formatted,
    const std::vector<std::string>& types) {
  Factory* factory = isolate->factory();
  Handle<JSArray> array = factory->NewJSArray(0);
  icu::ConstrainedFieldPosition cfpos;
  cfpos.constrainCategory(UFIELD_CATEGORY_LIST);
  int index = 0;
  int type_index = 0;
  UErrorCode status = U_ZERO_ERROR;
  icu::UnicodeString string = formatted.toString(status);
  Handle<String> substring;
  while (formatted.nextPosition(cfpos, status) && U_SUCCESS(status)) {
    ASSIGN_RETURN_ON_EXCEPTION(
        isolate, substring,
        Intl::ToString(isolate, string, cfpos.getStart(), cfpos.getLimit()),
        JSArray);
    Handle<String> type_string = factory->literal_string();
    if (cfpos.getField() == ULISTFMT_ELEMENT_FIELD) {
      type_string =
          factory->NewStringFromAsciiChecked(types[type_index].c_str());
      type_index++;
    }
    Intl::AddElement(isolate, array, index++, type_string, substring);
  }
  if (U_FAILURE(status)) {
    THROW_NEW_ERROR(isolate, NewTypeError(MessageTemplate::kIcuError), JSArray);
  }
  JSObject::ValidateElements(*array);
  return array;
}

MaybeHandle<String> JSDurationFormat::Format(Isolate* isolate,
                                             Handle<JSDurationFormat> df,
                                             Handle<Object> duration) {
  const char* method_name = "Intl.DurationFormat.prototype.format";
  return FormatCommon<String, FormattedToString>(isolate, df, duration,
                                                 method_name);
}

MaybeHandle<JSArray> JSDurationFormat::FormatToParts(
    Isolate* isolate, Handle<JSDurationFormat> df, Handle<Object> duration) {
  const char* method_name = "Intl.DurationFormat.prototype.formatToParts";
  return FormatCommon<JSArray, FormattedListToJSArray>(isolate, df, duration,
                                                       method_name);
}

const std::set<std::string>& JSDurationFormat::GetAvailableLocales() {
  return JSNumberFormat::GetAvailableLocales();
}

}  // namespace internal
}  // namespace v8