Debian Codegraph @

js/src/builtin/temporal/Duration.cpp

raw
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * vim: set ts=8 sts=2 et sw=2 tw=80:
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 #include "builtin/temporal/Duration.h"
8
9 #include "mozilla/Assertions.h"
10 #include "mozilla/Casting.h"
11 #include "mozilla/CheckedInt.h"
12 #include "mozilla/FloatingPoint.h"
13 #include "mozilla/Maybe.h"
14
15 #include <algorithm>
16 #include <cmath>
17 #include <cstdlib>
18 #include <initializer_list>
19 #include <stdint.h>
20 #include <type_traits>
21 #include <utility>
22
23 #include "jsnum.h"
24 #include "jspubtd.h"
25 #include "NamespaceImports.h"
26
27 #include "builtin/intl/DurationFormat.h"
28 #include "builtin/temporal/Calendar.h"
29 #include "builtin/temporal/CalendarFields.h"
30 #include "builtin/temporal/Instant.h"
31 #include "builtin/temporal/Int128.h"
32 #include "builtin/temporal/Int96.h"
33 #include "builtin/temporal/PlainDate.h"
34 #include "builtin/temporal/PlainDateTime.h"
35 #include "builtin/temporal/PlainTime.h"
36 #include "builtin/temporal/Temporal.h"
37 #include "builtin/temporal/TemporalParser.h"
38 #include "builtin/temporal/TemporalRoundingMode.h"
39 #include "builtin/temporal/TemporalTypes.h"
40 #include "builtin/temporal/TemporalUnit.h"
41 #include "builtin/temporal/TimeZone.h"
42 #include "builtin/temporal/ZonedDateTime.h"
43 #include "gc/AllocKind.h"
44 #include "gc/Barrier.h"
45 #include "gc/GCEnum.h"
46 #include "js/CallArgs.h"
47 #include "js/CallNonGenericMethod.h"
48 #include "js/Class.h"
49 #include "js/Conversions.h"
50 #include "js/ErrorReport.h"
51 #include "js/friend/ErrorMessages.h"
52 #include "js/Printer.h"
53 #include "js/PropertyDescriptor.h"
54 #include "js/PropertySpec.h"
55 #include "js/RootingAPI.h"
56 #include "js/Value.h"
57 #include "util/StringBuilder.h"
58 #include "vm/BytecodeUtil.h"
59 #include "vm/GlobalObject.h"
60 #include "vm/JSAtomState.h"
61 #include "vm/JSContext.h"
62 #include "vm/JSObject.h"
63 #include "vm/PlainObject.h"
64 #include "vm/StringType.h"
65
66 #include "vm/JSObject-inl.h"
67 #include "vm/NativeObject-inl.h"
68 #include "vm/ObjectOperations-inl.h"
69
70 using namespace js;
71 using namespace js::temporal;
72
73 static inline bool IsDuration(Handle<Value> v) {
74 return v.isObject() && v.toObject().is<DurationObject>();
75 }
76
77 #ifdef DEBUG
78 static bool IsIntegerOrInfinity(double d) {
79 return IsInteger(d) || std::isinf(d);
80 }
81
82 static bool IsIntegerOrInfinityDuration(const Duration& duration) {
83 const auto& [years, months, weeks, days, hours, minutes, seconds,
84 milliseconds, microseconds, nanoseconds] = duration;
85
86 // Integers exceeding the Number range are represented as infinity.
87
88 return IsIntegerOrInfinity(years) && IsIntegerOrInfinity(months) &&
89 IsIntegerOrInfinity(weeks) && IsIntegerOrInfinity(days) &&
90 IsIntegerOrInfinity(hours) && IsIntegerOrInfinity(minutes) &&
91 IsIntegerOrInfinity(seconds) && IsIntegerOrInfinity(milliseconds) &&
92 IsIntegerOrInfinity(microseconds) && IsIntegerOrInfinity(nanoseconds);
93 }
94
95 static bool IsIntegerDuration(const Duration& duration) {
96 const auto& [years, months, weeks, days, hours, minutes, seconds,
97 milliseconds, microseconds, nanoseconds] = duration;
98
99 return IsInteger(years) && IsInteger(months) && IsInteger(weeks) &&
100 IsInteger(days) && IsInteger(hours) && IsInteger(minutes) &&
101 IsInteger(seconds) && IsInteger(milliseconds) &&
102 IsInteger(microseconds) && IsInteger(nanoseconds);
103 }
104 #endif
105
106 /**
107 * DurationSign ( duration )
108 */
109 int32_t js::temporal::DurationSign(const Duration& duration) {
110 MOZ_ASSERT(IsIntegerOrInfinityDuration(duration));
111
112 const auto& [years, months, weeks, days, hours, minutes, seconds,
113 milliseconds, microseconds, nanoseconds] = duration;
114
115 // Step 1.
116 for (auto v : {years, months, weeks, days, hours, minutes, seconds,
117 milliseconds, microseconds, nanoseconds}) {
118 // Step 1.a.
119 if (v < 0) {
120 return -1;
121 }
122
123 // Step 1.b.
124 if (v > 0) {
125 return 1;
126 }
127 }
128
129 // Step 2.
130 return 0;
131 }
132
133 /**
134 * DateDurationSign ( dateDuration )
135 */
136 int32_t js::temporal::DateDurationSign(const DateDuration& duration) {
137 const auto& [years, months, weeks, days] = duration;
138
139 // Step 1.
140 for (auto v : {years, months, weeks, days}) {
141 // Step 1.a.
142 if (v < 0) {
143 return -1;
144 }
145
146 // Step 1.b.
147 if (v > 0) {
148 return 1;
149 }
150 }
151
152 // Step 2.
153 return 0;
154 }
155
156 /**
157 * InternalDurationSign ( internalDuration )
158 */
159 static int32_t InternalDurationSign(const InternalDuration& duration) {
160 MOZ_ASSERT(IsValidDuration(duration));
161
162 if (int32_t sign = DateDurationSign(duration.date)) {
163 return sign;
164 }
165 return TimeDurationSign(duration.time);
166 }
167
168 /**
169 * Create a time duration from a nanoseconds amount.
170 */
171 static TimeDuration TimeDurationFromNanoseconds(const Int96& nanoseconds) {
172 // Split into seconds and nanoseconds.
173 auto [seconds, nanos] = nanoseconds / ToNanoseconds(TemporalUnit::Second);
174
175 return {{seconds, nanos}};
176 }
177
178 /**
179 * Create a time duration from a nanoseconds amount. Return Nothing if the value
180 * is too large.
181 */
182 static mozilla::Maybe<TimeDuration> TimeDurationFromNanoseconds(
183 double nanoseconds) {
184 MOZ_ASSERT(IsInteger(nanoseconds));
185
186 if (auto int96 = Int96::fromInteger(nanoseconds)) {
187 // The number of time duration seconds must not exceed `2**53 - 1`.
188 constexpr auto limit =
189 Int96{uint64_t(1) << 53} * ToNanoseconds(TemporalUnit::Second);
190
191 if (int96->abs() < limit) {
192 return mozilla::Some(TimeDurationFromNanoseconds(*int96));
193 }
194 }
195 return mozilla::Nothing();
196 }
197
198 /**
199 * Create a time duration from a microseconds amount.
200 */
201 static TimeDuration TimeDurationFromMicroseconds(const Int96& microseconds) {
202 // Split into seconds and microseconds.
203 auto [seconds, micros] = microseconds / ToMicroseconds(TemporalUnit::Second);
204
205 // Scale microseconds to nanoseconds.
206 int32_t nanos = micros * int32_t(ToNanoseconds(TemporalUnit::Microsecond));
207
208 return {{seconds, nanos}};
209 }
210
211 /**
212 * Create a time duration from a microseconds amount. Return Nothing if the
213 * value is too large.
214 */
215 static mozilla::Maybe<TimeDuration> TimeDurationFromMicroseconds(
216 double microseconds) {
217 MOZ_ASSERT(IsInteger(microseconds));
218
219 if (auto int96 = Int96::fromInteger(microseconds)) {
220 // The number of time duration seconds must not exceed `2**53 - 1`.
221 constexpr auto limit =
222 Int96{uint64_t(1) << 53} * ToMicroseconds(TemporalUnit::Second);
223
224 if (int96->abs() < limit) {
225 return mozilla::Some(TimeDurationFromMicroseconds(*int96));
226 }
227 }
228 return mozilla::Nothing();
229 }
230
231 /**
232 * Create a time duration from a duration. Return Nothing if any duration
233 * value is too large.
234 */
235 static mozilla::Maybe<TimeDuration> TimeDurationFromDuration(
236 const Duration& duration) {
237 do {
238 auto nanoseconds = TimeDurationFromNanoseconds(duration.nanoseconds);
239 if (!nanoseconds) {
240 break;
241 }
242 MOZ_ASSERT(IsValidTimeDuration(*nanoseconds));
243
244 auto microseconds = TimeDurationFromMicroseconds(duration.microseconds);
245 if (!microseconds) {
246 break;
247 }
248 MOZ_ASSERT(IsValidTimeDuration(*microseconds));
249
250 // Overflows for millis/seconds/minutes/hours/days always result in an
251 // invalid time duration.
252
253 int64_t milliseconds;
254 if (!mozilla::NumberEqualsInt64(duration.milliseconds, &milliseconds)) {
255 break;
256 }
257
258 int64_t seconds;
259 if (!mozilla::NumberEqualsInt64(duration.seconds, &seconds)) {
260 break;
261 }
262
263 int64_t minutes;
264 if (!mozilla::NumberEqualsInt64(duration.minutes, &minutes)) {
265 break;
266 }
267
268 int64_t hours;
269 if (!mozilla::NumberEqualsInt64(duration.hours, &hours)) {
270 break;
271 }
272
273 int64_t days;
274 if (!mozilla::NumberEqualsInt64(duration.days, &days)) {
275 break;
276 }
277
278 // Compute the overall amount of milliseconds.
279 mozilla::CheckedInt64 millis = days;
280 millis *= 24;
281 millis += hours;
282 millis *= 60;
283 millis += minutes;
284 millis *= 60;
285 millis += seconds;
286 millis *= 1000;
287 millis += milliseconds;
288 if (!millis.isValid()) {
289 break;
290 }
291
292 auto milli = TimeDuration::fromMilliseconds(millis.value());
293 if (!IsValidTimeDuration(milli)) {
294 break;
295 }
296
297 // Compute the overall time duration.
298 auto result = milli + *microseconds + *nanoseconds;
299 if (!IsValidTimeDuration(result)) {
300 break;
301 }
302
303 return mozilla::Some(result);
304 } while (false);
305
306 return mozilla::Nothing();
307 }
308
309 /**
310 * TimeDurationFromComponents ( hours, minutes, seconds, milliseconds,
311 * microseconds, nanoseconds )
312 */
313 static TimeDuration TimeDurationFromComponents(double hours, double minutes,
314 double seconds,
315 double milliseconds,
316 double microseconds,
317 double nanoseconds) {
318 MOZ_ASSERT(IsInteger(hours));
319 MOZ_ASSERT(IsInteger(minutes));
320 MOZ_ASSERT(IsInteger(seconds));
321 MOZ_ASSERT(IsInteger(milliseconds));
322 MOZ_ASSERT(IsInteger(microseconds));
323 MOZ_ASSERT(IsInteger(nanoseconds));
324
325 // Steps 1-3.
326 mozilla::CheckedInt64 millis = int64_t(hours);
327 millis *= 60;
328 millis += int64_t(minutes);
329 millis *= 60;
330 millis += int64_t(seconds);
331 millis *= 1000;
332 millis += int64_t(milliseconds);
333 MOZ_ASSERT(millis.isValid());
334
335 auto timeDuration = TimeDuration::fromMilliseconds(millis.value());
336
337 // Step 4.
338 auto micros = Int96::fromInteger(microseconds);
339 MOZ_ASSERT(micros);
340
341 timeDuration += TimeDurationFromMicroseconds(*micros);
342
343 // Step 5.
344 auto nanos = Int96::fromInteger(nanoseconds);
345 MOZ_ASSERT(nanos);
346
347 timeDuration += TimeDurationFromNanoseconds(*nanos);
348
349 // Step 6.
350 MOZ_ASSERT(IsValidTimeDuration(timeDuration));
351
352 // Step 7.
353 return timeDuration;
354 }
355
356 /**
357 * TimeDurationFromComponents ( hours, minutes, seconds, milliseconds,
358 * microseconds, nanoseconds )
359 */
360 TimeDuration js::temporal::TimeDurationFromComponents(
361 const Duration& duration) {
362 MOZ_ASSERT(IsValidDuration(duration));
363
364 return ::TimeDurationFromComponents(
365 duration.hours, duration.minutes, duration.seconds, duration.milliseconds,
366 duration.microseconds, duration.nanoseconds);
367 }
368
369 /**
370 * Add24HourDaysToTimeDuration ( d, days )
371 */
372 static bool Add24HourDaysToTimeDuration(JSContext* cx, const TimeDuration& d,
373 int64_t days, TimeDuration* result) {
374 MOZ_ASSERT(IsValidTimeDuration(d));
375
376 // Step 1.
377 if (days > TimeDuration::max().toDays()) {
378 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
379 JSMSG_TEMPORAL_DURATION_INVALID_NORMALIZED_TIME);
380 return false;
381 }
382
383 auto timeDurationDays = TimeDuration::fromDays(days);
384 if (!IsValidTimeDuration(timeDurationDays)) {
385 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
386 JSMSG_TEMPORAL_DURATION_INVALID_NORMALIZED_TIME);
387 return false;
388 }
389
390 // Step 2.
391 auto sum = d + timeDurationDays;
392 if (!IsValidTimeDuration(sum)) {
393 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
394 JSMSG_TEMPORAL_DURATION_INVALID_NORMALIZED_TIME);
395 return false;
396 }
397
398 // Step 3.
399 *result = sum;
400 return true;
401 }
402
403 /**
404 * ToInternalDurationRecordWith24HourDays ( duration )
405 */
406 InternalDuration js::temporal::ToInternalDurationRecordWith24HourDays(
407 const Duration& duration) {
408 MOZ_ASSERT(IsValidDuration(duration));
409
410 // Step 1.
411 auto timeDuration = TimeDurationFromComponents(duration);
412
413 // Step 2. (Inlined Add24HourDaysToTimeDuration)
414 timeDuration += TimeDuration::fromDays(int64_t(duration.days));
415
416 // Step 3.
417 auto dateDuration = DateDuration{
418 int64_t(duration.years),
419 int64_t(duration.months),
420 int64_t(duration.weeks),
421 0,
422 };
423
424 // Step 4. (Inlined CombineDateAndTimeDuration)
425 return InternalDuration{dateDuration, timeDuration};
426 }
427
428 /**
429 * ToDateDurationRecordWithoutTime ( duration )
430 */
431 DateDuration js::temporal::ToDateDurationRecordWithoutTime(
432 const Duration& duration) {
433 // Step 1.
434 auto internalDuration = ToInternalDurationRecordWith24HourDays(duration);
435
436 // Step 2.
437 int64_t days = internalDuration.time.toDays();
438
439 // Step 3.
440 auto result = DateDuration{
441 internalDuration.date.years,
442 internalDuration.date.months,
443 internalDuration.date.weeks,
444 days,
445 };
446 MOZ_ASSERT(IsValidDuration(result));
447
448 return result;
449 }
450
451 /**
452 * TemporalDurationFromInternal ( internalDuration, largestUnit )
453 */
454 static Duration TemporalDurationFromInternal(const TimeDuration& timeDuration,
455 TemporalUnit largestUnit) {
456 MOZ_ASSERT(IsValidTimeDuration(timeDuration));
457 MOZ_ASSERT(largestUnit <= TemporalUnit::Second,
458 "fallible fractional seconds units");
459
460 auto [seconds, nanoseconds] = timeDuration.denormalize();
461
462 // Step 1.
463 int64_t days = 0;
464 int64_t hours = 0;
465 int64_t minutes = 0;
466 int64_t milliseconds = 0;
467 int64_t microseconds = 0;
468
469 // Steps 2-3. (Not applicable in our implementation.)
470 //
471 // We don't need to convert to positive numbers, because integer division
472 // truncates and the %-operator has modulo semantics.
473
474 // Steps 4-11.
475 switch (largestUnit) {
476 // Step 4.
477 case TemporalUnit::Year:
478 case TemporalUnit::Month:
479 case TemporalUnit::Week:
480 case TemporalUnit::Day: {
481 // Step 4.a.
482 microseconds = nanoseconds / 1000;
483
484 // Step 4.b.
485 nanoseconds = nanoseconds % 1000;
486
487 // Step 4.c.
488 milliseconds = microseconds / 1000;
489
490 // Step 4.d.
491 microseconds = microseconds % 1000;
492
493 // Steps 4.e-f. (Not applicable)
494 MOZ_ASSERT(std::abs(milliseconds) <= 999);
495
496 // Step 4.g.
497 minutes = seconds / 60;
498
499 // Step 4.h.
500 seconds = seconds % 60;
501
502 // Step 4.i.
503 hours = minutes / 60;
504
505 // Step 4.j.
506 minutes = minutes % 60;
507
508 // Step 4.k.
509 days = hours / 24;
510
511 // Step 4.l.
512 hours = hours % 24;
513
514 break;
515 }
516
517 // Step 5.
518 case TemporalUnit::Hour: {
519 // Step 5.a.
520 microseconds = nanoseconds / 1000;
521
522 // Step 5.b.
523 nanoseconds = nanoseconds % 1000;
524
525 // Step 5.c.
526 milliseconds = microseconds / 1000;
527
528 // Step 5.d.
529 microseconds = microseconds % 1000;
530
531 // Steps 5.e-f. (Not applicable)
532 MOZ_ASSERT(std::abs(milliseconds) <= 999);
533
534 // Step 5.g.
535 minutes = seconds / 60;
536
537 // Step 5.h.
538 seconds = seconds % 60;
539
540 // Step 5.i.
541 hours = minutes / 60;
542
543 // Step 5.j.
544 minutes = minutes % 60;
545
546 break;
547 }
548
549 case TemporalUnit::Minute: {
550 // Step 6.a.
551 microseconds = nanoseconds / 1000;
552
553 // Step 6.b.
554 nanoseconds = nanoseconds % 1000;
555
556 // Step 6.c.
557 milliseconds = microseconds / 1000;
558
559 // Step 6.d.
560 microseconds = microseconds % 1000;
561
562 // Steps 6.e-f. (Not applicable)
563 MOZ_ASSERT(std::abs(milliseconds) <= 999);
564
565 // Step 6.g.
566 minutes = seconds / 60;
567
568 // Step 6.h.
569 seconds = seconds % 60;
570
571 break;
572 }
573
574 // Step 7.
575 case TemporalUnit::Second: {
576 // Step 7.a.
577 microseconds = nanoseconds / 1000;
578
579 // Step 7.b.
580 nanoseconds = nanoseconds % 1000;
581
582 // Step 7.c.
583 milliseconds = microseconds / 1000;
584
585 // Step 7.d.
586 microseconds = microseconds % 1000;
587
588 // Steps 7.e-f. (Not applicable)
589 MOZ_ASSERT(std::abs(milliseconds) <= 999);
590
591 break;
592 }
593
594 // Steps 8-11. (Not applicable in our implementation)
595 case TemporalUnit::Millisecond:
596 case TemporalUnit::Microsecond:
597 case TemporalUnit::Nanosecond:
598 case TemporalUnit::Auto:
599 MOZ_CRASH("Unexpected temporal unit");
600 }
601
602 // Step 12.
603 auto result = Duration{
604 0,
605 0,
606 0,
607 double(days),
608 double(hours),
609 double(minutes),
610 double(seconds),
611 double(milliseconds),
612 double(microseconds),
613 double(nanoseconds),
614 };
615 MOZ_ASSERT(IsValidDuration(result));
616 return result;
617 }
618
619 /**
620 * TemporalDurationFromInternal ( internalDuration, largestUnit )
621 */
622 bool js::temporal::TemporalDurationFromInternal(
623 JSContext* cx, const TimeDuration& timeDuration, TemporalUnit largestUnit,
624 Duration* result) {
625 MOZ_ASSERT(IsValidTimeDuration(timeDuration));
626
627 auto [seconds, nanoseconds] = timeDuration.denormalize();
628
629 // Steps 1-3. (Not applicable in our implementation.)
630 //
631 // We don't need to convert to positive numbers, because integer division
632 // truncates and the %-operator has modulo semantics.
633
634 // Steps 4-10.
635 switch (largestUnit) {
636 // Steps 4-7.
637 case TemporalUnit::Year:
638 case TemporalUnit::Month:
639 case TemporalUnit::Week:
640 case TemporalUnit::Day:
641 case TemporalUnit::Hour:
642 case TemporalUnit::Minute:
643 case TemporalUnit::Second:
644 *result = ::TemporalDurationFromInternal(timeDuration, largestUnit);
645 return true;
646
647 // Step 8.
648 case TemporalUnit::Millisecond: {
649 // Valid time durations must be below |limit|.
650 constexpr auto limit = TimeDuration::max().toMilliseconds() + 1;
651
652 // The largest possible milliseconds value whose double representation
653 // doesn't exceed the time duration limit.
654 constexpr auto max = int64_t(0x7cff'ffff'ffff'fdff);
655
656 // Assert |max| is the maximum allowed milliseconds value.
657 static_assert(double(max) < double(limit));
658 static_assert(double(max + 1) >= double(limit));
659
660 static_assert((TimeDuration::max().seconds + 1) *
661 ToMilliseconds(TemporalUnit::Second) <=
662 INT64_MAX,
663 "total number duration milliseconds fits into int64");
664
665 // Step 8.a.
666 int64_t microseconds = nanoseconds / 1000;
667
668 // Step 8.b.
669 nanoseconds = nanoseconds % 1000;
670
671 // Step 8.c.
672 int64_t milliseconds = microseconds / 1000;
673 MOZ_ASSERT(std::abs(milliseconds) <= 999);
674
675 // Step 8.d.
676 microseconds = microseconds % 1000;
677
678 auto millis =
679 (seconds * ToMilliseconds(TemporalUnit::Second)) + milliseconds;
680 if (std::abs(millis) > max) {
681 JS_ReportErrorNumberASCII(
682 cx, GetErrorMessage, nullptr,
683 JSMSG_TEMPORAL_DURATION_INVALID_NORMALIZED_TIME);
684 return false;
685 }
686
687 // Step 11.
688 *result = {0,
689 0,
690 0,
691 0,
692 0,
693 0,
694 0,
695 double(millis),
696 double(microseconds),
697 double(nanoseconds)};
698 MOZ_ASSERT(IsValidDuration(*result));
699 return true;
700 }
701
702 // Step 9.
703 case TemporalUnit::Microsecond: {
704 // Valid time durations must be below |limit|.
705 constexpr auto limit =
706 Uint128{TimeDuration::max().toMicroseconds()} + Uint128{1};
707
708 // The largest possible microseconds value whose double representation
709 // doesn't exceed the time duration limit.
710 constexpr auto max =
711 (Uint128{0x1e8} << 64) + Uint128{0x47ff'ffff'fff7'ffff};
712 static_assert(max < limit);
713
714 // Assert |max| is the maximum allowed microseconds value.
715 MOZ_ASSERT(double(max) < double(limit));
716 MOZ_ASSERT(double(max + Uint128{1}) >= double(limit));
717
718 // Step 9.a.
719 int64_t microseconds = nanoseconds / 1000;
720 MOZ_ASSERT(std::abs(microseconds) <= 999'999);
721
722 // Step 9.b.
723 nanoseconds = nanoseconds % 1000;
724
725 auto micros =
726 (Int128{seconds} * Int128{ToMicroseconds(TemporalUnit::Second)}) +
727 Int128{microseconds};
728 if (micros.abs() > max) {
729 JS_ReportErrorNumberASCII(
730 cx, GetErrorMessage, nullptr,
731 JSMSG_TEMPORAL_DURATION_INVALID_NORMALIZED_TIME);
732 return false;
733 }
734
735 // Step 11.
736 *result = {0, 0, 0, 0, 0, 0, 0, 0, double(micros), double(nanoseconds)};
737 MOZ_ASSERT(IsValidDuration(*result));
738 return true;
739 }
740
741 // Step 10.
742 case TemporalUnit::Nanosecond: {
743 // Valid time durations must be below |limit|.
744 constexpr auto limit =
745 Uint128{TimeDuration::max().toNanoseconds()} + Uint128{1};
746
747 // The largest possible nanoseconds value whose double representation
748 // doesn't exceed the time duration limit.
749 constexpr auto max =
750 (Uint128{0x77359} << 64) + Uint128{0x3fff'ffff'dfff'ffff};
751 static_assert(max < limit);
752
753 // Assert |max| is the maximum allowed nanoseconds value.
754 MOZ_ASSERT(double(max) < double(limit));
755 MOZ_ASSERT(double(max + Uint128{1}) >= double(limit));
756
757 MOZ_ASSERT(std::abs(nanoseconds) <= 999'999'999);
758
759 auto nanos =
760 (Int128{seconds} * Int128{ToNanoseconds(TemporalUnit::Second)}) +
761 Int128{nanoseconds};
762 if (nanos.abs() > max) {
763 JS_ReportErrorNumberASCII(
764 cx, GetErrorMessage, nullptr,
765 JSMSG_TEMPORAL_DURATION_INVALID_NORMALIZED_TIME);
766 return false;
767 }
768
769 // Step 11.
770 *result = {0, 0, 0, 0, 0, 0, 0, 0, 0, double(nanos)};
771 MOZ_ASSERT(IsValidDuration(*result));
772 return true;
773 }
774
775 case TemporalUnit::Auto:
776 break;
777 }
778 MOZ_CRASH("Unexpected temporal unit");
779 }
780
781 /**
782 * TemporalDurationFromInternal ( internalDuration, largestUnit )
783 */
784 bool js::temporal::TemporalDurationFromInternal(
785 JSContext* cx, const InternalDuration& internalDuration,
786 TemporalUnit largestUnit, Duration* result) {
787 MOZ_ASSERT(IsValidDuration(internalDuration.date));
788 MOZ_ASSERT(IsValidTimeDuration(internalDuration.time));
789
790 // Steps 1-11.
791 Duration duration;
792 if (!TemporalDurationFromInternal(cx, internalDuration.time, largestUnit,
793 &duration)) {
794 return false;
795 }
796 MOZ_ASSERT(IsValidDuration(duration));
797
798 // Step 12.
799 auto days = mozilla::CheckedInt64(internalDuration.date.days) +
800 mozilla::AssertedCast<int64_t>(duration.days);
801 MOZ_ASSERT(days.isValid(), "valid duration days can't overflow");
802
803 *result = {
804 double(internalDuration.date.years),
805 double(internalDuration.date.months),
806 double(internalDuration.date.weeks),
807 double(days.value()),
808 duration.hours,
809 duration.minutes,
810 duration.seconds,
811 duration.milliseconds,
812 duration.microseconds,
813 duration.nanoseconds,
814 };
815 return ThrowIfInvalidDuration(cx, *result);
816 }
817
818 /**
819 * TimeDurationFromEpochNanosecondsDifference ( one, two )
820 */
821 TimeDuration js::temporal::TimeDurationFromEpochNanosecondsDifference(
822 const EpochNanoseconds& one, const EpochNanoseconds& two) {
823 MOZ_ASSERT(IsValidEpochNanoseconds(one));
824 MOZ_ASSERT(IsValidEpochNanoseconds(two));
825
826 // Step 1.
827 auto result = one - two;
828
829 // Step 2.
830 MOZ_ASSERT(IsValidEpochDuration(result));
831
832 // Step 3.
833 return result.to<TimeDuration>();
834 }
835
836 #ifdef DEBUG
837 /**
838 * IsValidDuration ( years, months, weeks, days, hours, minutes, seconds,
839 * milliseconds, microseconds, nanoseconds )
840 */
841 bool js::temporal::IsValidDuration(const Duration& duration) {
842 MOZ_ASSERT(IsIntegerOrInfinityDuration(duration));
843
844 const auto& [years, months, weeks, days, hours, minutes, seconds,
845 milliseconds, microseconds, nanoseconds] = duration;
846
847 // Step 1.
848 int32_t sign = 0;
849
850 // Step 2.
851 for (auto v : {years, months, weeks, days, hours, minutes, seconds,
852 milliseconds, microseconds, nanoseconds}) {
853 // Step 2.a.
854 if (!std::isfinite(v)) {
855 return false;
856 }
857
858 // Step 2.b.
859 if (v < 0) {
860 // Step 2.b.i.
861 if (sign > 0) {
862 return false;
863 }
864
865 // Step 2.b.ii.
866 sign = -1;
867 }
868
869 // Step 2.c.
870 else if (v > 0) {
871 // Step 2.c.i.
872 if (sign < 0) {
873 return false;
874 }
875
876 // Step 2.c.ii.
877 sign = 1;
878 }
879 }
880
881 // Step 3.
882 if (std::abs(years) >= double(int64_t(1) << 32)) {
883 return false;
884 }
885
886 // Step 4.
887 if (std::abs(months) >= double(int64_t(1) << 32)) {
888 return false;
889 }
890
891 // Step 5.
892 if (std::abs(weeks) >= double(int64_t(1) << 32)) {
893 return false;
894 }
895
896 // Steps 6-8.
897 if (!TimeDurationFromDuration(duration)) {
898 return false;
899 }
900
901 // Step 9.
902 return true;
903 }
904
905 /**
906 * IsValidDuration ( years, months, weeks, days, hours, minutes, seconds,
907 * milliseconds, microseconds, nanoseconds )
908 */
909 bool js::temporal::IsValidDuration(const DateDuration& duration) {
910 return IsValidDuration(duration.toDuration());
911 }
912
913 /**
914 * IsValidDuration ( years, months, weeks, days, hours, minutes, seconds,
915 * milliseconds, microseconds, nanoseconds )
916 */
917 bool js::temporal::IsValidDuration(const InternalDuration& duration) {
918 if (!IsValidTimeDuration(duration.time)) {
919 return false;
920 }
921
922 auto d = duration.date.toDuration();
923 auto [seconds, nanoseconds] = duration.time.denormalize();
924 d.seconds = double(seconds);
925 d.nanoseconds = double(nanoseconds);
926
927 return IsValidDuration(d);
928 }
929 #endif
930
931 static bool ThrowInvalidDurationPart(JSContext* cx, double value,
932 const char* name, unsigned errorNumber) {
933 ToCStringBuf cbuf;
934 const char* numStr = NumberToCString(&cbuf, value);
935
936 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, errorNumber, name,
937 numStr);
938 return false;
939 }
940
941 /**
942 * IsValidDuration ( years, months, weeks, days, hours, minutes, seconds,
943 * milliseconds, microseconds, nanoseconds )
944 */
945 bool js::temporal::ThrowIfInvalidDuration(JSContext* cx,
946 const Duration& duration) {
947 MOZ_ASSERT(IsIntegerOrInfinityDuration(duration));
948
949 const auto& [years, months, weeks, days, hours, minutes, seconds,
950 milliseconds, microseconds, nanoseconds] = duration;
951
952 // Step 1.
953 int32_t sign = DurationSign(duration);
954
955 auto throwIfInvalid = [&](double v, const char* name) {
956 // Step 2.a.
957 if (!std::isfinite(v)) {
958 return ThrowInvalidDurationPart(
959 cx, v, name, JSMSG_TEMPORAL_DURATION_INVALID_NON_FINITE);
960 }
961
962 // Steps 2.b-c.
963 if ((v < 0 && sign > 0) || (v > 0 && sign < 0)) {
964 return ThrowInvalidDurationPart(cx, v, name,
965 JSMSG_TEMPORAL_DURATION_INVALID_SIGN);
966 }
967
968 return true;
969 };
970
971 auto throwIfTooLarge = [&](double v, const char* name) {
972 if (std::abs(v) >= double(int64_t(1) << 32)) {
973 return ThrowInvalidDurationPart(
974 cx, v, name, JSMSG_TEMPORAL_DURATION_INVALID_NON_FINITE);
975 }
976 return true;
977 };
978
979 // Step 2.
980 if (!throwIfInvalid(years, "years")) {
981 return false;
982 }
983 if (!throwIfInvalid(months, "months")) {
984 return false;
985 }
986 if (!throwIfInvalid(weeks, "weeks")) {
987 return false;
988 }
989 if (!throwIfInvalid(days, "days")) {
990 return false;
991 }
992 if (!throwIfInvalid(hours, "hours")) {
993 return false;
994 }
995 if (!throwIfInvalid(minutes, "minutes")) {
996 return false;
997 }
998 if (!throwIfInvalid(seconds, "seconds")) {
999 return false;
1000 }
1001 if (!throwIfInvalid(milliseconds, "milliseconds")) {
1002 return false;
1003 }
1004 if (!throwIfInvalid(microseconds, "microseconds")) {
1005 return false;
1006 }
1007 if (!throwIfInvalid(nanoseconds, "nanoseconds")) {
1008 return false;
1009 }
1010
1011 // Step 3.
1012 if (!throwIfTooLarge(years, "years")) {
1013 return false;
1014 }
1015
1016 // Step 4.
1017 if (!throwIfTooLarge(months, "months")) {
1018 return false;
1019 }
1020
1021 // Step 5.
1022 if (!throwIfTooLarge(weeks, "weeks")) {
1023 return false;
1024 }
1025
1026 // Steps 6-8.
1027 if (!TimeDurationFromDuration(duration)) {
1028 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
1029 JSMSG_TEMPORAL_DURATION_INVALID_NORMALIZED_TIME);
1030 return false;
1031 }
1032
1033 MOZ_ASSERT(IsValidDuration(duration));
1034
1035 // Step 9.
1036 return true;
1037 }
1038
1039 /**
1040 * DefaultTemporalLargestUnit ( duration )
1041 */
1042 static TemporalUnit DefaultTemporalLargestUnit(const Duration& duration) {
1043 MOZ_ASSERT(IsIntegerDuration(duration));
1044
1045 // Step 1.
1046 if (duration.years != 0) {
1047 return TemporalUnit::Year;
1048 }
1049
1050 // Step 2.
1051 if (duration.months != 0) {
1052 return TemporalUnit::Month;
1053 }
1054
1055 // Step 3.
1056 if (duration.weeks != 0) {
1057 return TemporalUnit::Week;
1058 }
1059
1060 // Step 4.
1061 if (duration.days != 0) {
1062 return TemporalUnit::Day;
1063 }
1064
1065 // Step 5.
1066 if (duration.hours != 0) {
1067 return TemporalUnit::Hour;
1068 }
1069
1070 // Step 6.
1071 if (duration.minutes != 0) {
1072 return TemporalUnit::Minute;
1073 }
1074
1075 // Step 7.
1076 if (duration.seconds != 0) {
1077 return TemporalUnit::Second;
1078 }
1079
1080 // Step 8.
1081 if (duration.milliseconds != 0) {
1082 return TemporalUnit::Millisecond;
1083 }
1084
1085 // Step 9.
1086 if (duration.microseconds != 0) {
1087 return TemporalUnit::Microsecond;
1088 }
1089
1090 // Step 10.
1091 return TemporalUnit::Nanosecond;
1092 }
1093
1094 /**
1095 * CreateTemporalDuration ( years, months, weeks, days, hours, minutes, seconds,
1096 * milliseconds, microseconds, nanoseconds [ , newTarget ] )
1097 */
1098 static DurationObject* CreateTemporalDuration(JSContext* cx,
1099 const CallArgs& args,
1100 const Duration& duration) {
1101 const auto& [years, months, weeks, days, hours, minutes, seconds,
1102 milliseconds, microseconds, nanoseconds] = duration;
1103
1104 // Step 1.
1105 if (!ThrowIfInvalidDuration(cx, duration)) {
1106 return nullptr;
1107 }
1108
1109 // Steps 2-3.
1110 Rooted<JSObject*> proto(cx);
1111 if (!GetPrototypeFromBuiltinConstructor(cx, args, JSProto_Duration, &proto)) {
1112 return nullptr;
1113 }
1114
1115 auto* object = NewObjectWithClassProto<DurationObject>(cx, proto);
1116 if (!object) {
1117 return nullptr;
1118 }
1119
1120 // Steps 4-13.
1121 // Add zero to convert -0 to +0.
1122 object->setFixedSlot(DurationObject::YEARS_SLOT, NumberValue(years + (+0.0)));
1123 object->setFixedSlot(DurationObject::MONTHS_SLOT,
1124 NumberValue(months + (+0.0)));
1125 object->setFixedSlot(DurationObject::WEEKS_SLOT, NumberValue(weeks + (+0.0)));
1126 object->setFixedSlot(DurationObject::DAYS_SLOT, NumberValue(days + (+0.0)));
1127 object->setFixedSlot(DurationObject::HOURS_SLOT, NumberValue(hours + (+0.0)));
1128 object->setFixedSlot(DurationObject::MINUTES_SLOT,
1129 NumberValue(minutes + (+0.0)));
1130 object->setFixedSlot(DurationObject::SECONDS_SLOT,
1131 NumberValue(seconds + (+0.0)));
1132 object->setFixedSlot(DurationObject::MILLISECONDS_SLOT,
1133 NumberValue(milliseconds + (+0.0)));
1134 object->setFixedSlot(DurationObject::MICROSECONDS_SLOT,
1135 NumberValue(microseconds + (+0.0)));
1136 object->setFixedSlot(DurationObject::NANOSECONDS_SLOT,
1137 NumberValue(nanoseconds + (+0.0)));
1138
1139 // Step 14.
1140 return object;
1141 }
1142
1143 /**
1144 * CreateTemporalDuration ( years, months, weeks, days, hours, minutes, seconds,
1145 * milliseconds, microseconds, nanoseconds [ , newTarget ] )
1146 */
1147 DurationObject* js::temporal::CreateTemporalDuration(JSContext* cx,
1148 const Duration& duration) {
1149 const auto& [years, months, weeks, days, hours, minutes, seconds,
1150 milliseconds, microseconds, nanoseconds] = duration;
1151
1152 MOZ_ASSERT(IsInteger(years));
1153 MOZ_ASSERT(IsInteger(months));
1154 MOZ_ASSERT(IsInteger(weeks));
1155 MOZ_ASSERT(IsInteger(days));
1156 MOZ_ASSERT(IsInteger(hours));
1157 MOZ_ASSERT(IsInteger(minutes));
1158 MOZ_ASSERT(IsInteger(seconds));
1159 MOZ_ASSERT(IsInteger(milliseconds));
1160 MOZ_ASSERT(IsInteger(microseconds));
1161 MOZ_ASSERT(IsInteger(nanoseconds));
1162
1163 // Step 1.
1164 if (!ThrowIfInvalidDuration(cx, duration)) {
1165 return nullptr;
1166 }
1167
1168 // Steps 2-3.
1169 auto* object = NewBuiltinClassInstance<DurationObject>(cx);
1170 if (!object) {
1171 return nullptr;
1172 }
1173
1174 // Steps 4-13.
1175 // Add zero to convert -0 to +0.
1176 object->setFixedSlot(DurationObject::YEARS_SLOT, NumberValue(years + (+0.0)));
1177 object->setFixedSlot(DurationObject::MONTHS_SLOT,
1178 NumberValue(months + (+0.0)));
1179 object->setFixedSlot(DurationObject::WEEKS_SLOT, NumberValue(weeks + (+0.0)));
1180 object->setFixedSlot(DurationObject::DAYS_SLOT, NumberValue(days + (+0.0)));
1181 object->setFixedSlot(DurationObject::HOURS_SLOT, NumberValue(hours + (+0.0)));
1182 object->setFixedSlot(DurationObject::MINUTES_SLOT,
1183 NumberValue(minutes + (+0.0)));
1184 object->setFixedSlot(DurationObject::SECONDS_SLOT,
1185 NumberValue(seconds + (+0.0)));
1186 object->setFixedSlot(DurationObject::MILLISECONDS_SLOT,
1187 NumberValue(milliseconds + (+0.0)));
1188 object->setFixedSlot(DurationObject::MICROSECONDS_SLOT,
1189 NumberValue(microseconds + (+0.0)));
1190 object->setFixedSlot(DurationObject::NANOSECONDS_SLOT,
1191 NumberValue(nanoseconds + (+0.0)));
1192
1193 // Step 14.
1194 return object;
1195 }
1196
1197 /**
1198 * ToIntegerIfIntegral ( argument )
1199 */
1200 static bool ToIntegerIfIntegral(JSContext* cx, const char* name,
1201 Handle<Value> argument, double* num) {
1202 // Step 1.
1203 double d;
1204 if (!JS::ToNumber(cx, argument, &d)) {
1205 return false;
1206 }
1207
1208 // Step 2.
1209 if (!js::IsInteger(d)) {
1210 ToCStringBuf cbuf;
1211 const char* numStr = NumberToCString(&cbuf, d);
1212
1213 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
1214 JSMSG_TEMPORAL_DURATION_NOT_INTEGER, numStr,
1215 name);
1216 return false;
1217 }
1218
1219 // Step 3.
1220 *num = d;
1221 return true;
1222 }
1223
1224 /**
1225 * ToIntegerIfIntegral ( argument )
1226 */
1227 static bool ToIntegerIfIntegral(JSContext* cx, Handle<PropertyName*> name,
1228 Handle<Value> argument, double* result) {
1229 // Step 1.
1230 double d;
1231 if (!JS::ToNumber(cx, argument, &d)) {
1232 return false;
1233 }
1234
1235 // Step 2.
1236 if (!js::IsInteger(d)) {
1237 if (auto nameStr = js::QuoteString(cx, name)) {
1238 ToCStringBuf cbuf;
1239 const char* numStr = NumberToCString(&cbuf, d);
1240
1241 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
1242 JSMSG_TEMPORAL_DURATION_NOT_INTEGER, numStr,
1243 nameStr.get());
1244 }
1245 return false;
1246 }
1247
1248 // Step 3.
1249 *result = d;
1250 return true;
1251 }
1252
1253 /**
1254 * ToTemporalPartialDurationRecord ( temporalDurationLike )
1255 */
1256 static bool ToTemporalPartialDurationRecord(
1257 JSContext* cx, Handle<JSObject*> temporalDurationLike, Duration* result) {
1258 // Steps 1-3. (Not applicable in our implementation.)
1259
1260 Rooted<Value> value(cx);
1261 bool any = false;
1262
1263 auto getDurationProperty = [&](Handle<PropertyName*> name, double* num) {
1264 if (!GetProperty(cx, temporalDurationLike, temporalDurationLike, name,
1265 &value)) {
1266 return false;
1267 }
1268
1269 if (!value.isUndefined()) {
1270 any = true;
1271
1272 if (!ToIntegerIfIntegral(cx, name, value, num)) {
1273 return false;
1274 }
1275 }
1276 return true;
1277 };
1278
1279 // Steps 4-23.
1280 if (!getDurationProperty(cx->names().days, &result->days)) {
1281 return false;
1282 }
1283 if (!getDurationProperty(cx->names().hours, &result->hours)) {
1284 return false;
1285 }
1286 if (!getDurationProperty(cx->names().microseconds, &result->microseconds)) {
1287 return false;
1288 }
1289 if (!getDurationProperty(cx->names().milliseconds, &result->milliseconds)) {
1290 return false;
1291 }
1292 if (!getDurationProperty(cx->names().minutes, &result->minutes)) {
1293 return false;
1294 }
1295 if (!getDurationProperty(cx->names().months, &result->months)) {
1296 return false;
1297 }
1298 if (!getDurationProperty(cx->names().nanoseconds, &result->nanoseconds)) {
1299 return false;
1300 }
1301 if (!getDurationProperty(cx->names().seconds, &result->seconds)) {
1302 return false;
1303 }
1304 if (!getDurationProperty(cx->names().weeks, &result->weeks)) {
1305 return false;
1306 }
1307 if (!getDurationProperty(cx->names().years, &result->years)) {
1308 return false;
1309 }
1310
1311 // Step 24.
1312 if (!any) {
1313 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
1314 JSMSG_TEMPORAL_DURATION_MISSING_UNIT);
1315 return false;
1316 }
1317
1318 // Step 25.
1319 return true;
1320 }
1321
1322 /**
1323 * ToTemporalDuration ( item )
1324 */
1325 bool js::temporal::ToTemporalDuration(JSContext* cx, Handle<Value> item,
1326 Duration* result) {
1327 // Steps 1 and 3-15.
1328 if (item.isObject()) {
1329 Rooted<JSObject*> itemObj(cx, &item.toObject());
1330
1331 // Step 1.
1332 if (auto* duration = itemObj->maybeUnwrapIf<DurationObject>()) {
1333 *result = ToDuration(duration);
1334 return true;
1335 }
1336
1337 // Step 3. (Reordered)
1338 Duration duration = {};
1339
1340 // Steps 4-14.
1341 if (!ToTemporalPartialDurationRecord(cx, itemObj, &duration)) {
1342 return false;
1343 }
1344
1345 // Step 15.
1346 if (!ThrowIfInvalidDuration(cx, duration)) {
1347 return false;
1348 }
1349
1350 *result = duration;
1351 return true;
1352 }
1353
1354 // Step 2.a.
1355 if (!item.isString()) {
1356 ReportValueError(cx, JSMSG_UNEXPECTED_TYPE, JSDVG_IGNORE_STACK, item,
1357 nullptr, "not a string");
1358 return false;
1359 }
1360 Rooted<JSString*> string(cx, item.toString());
1361
1362 // Step 2.b.
1363 return ParseTemporalDurationString(cx, string, result);
1364 }
1365
1366 /**
1367 * DateDurationDays ( dateDuration, plainRelativeTo )
1368 */
1369 static bool DateDurationDays(JSContext* cx, const DateDuration& duration,
1370 Handle<PlainDate> plainRelativeTo,
1371 int64_t* result) {
1372 MOZ_ASSERT(IsValidDuration(duration));
1373
1374 auto [years, months, weeks, days] = duration;
1375
1376 // Step 1.
1377 auto yearsMonthsWeeksDuration = DateDuration{years, months, weeks};
1378
1379 // Step 2.
1380 if (yearsMonthsWeeksDuration == DateDuration{}) {
1381 *result = days;
1382 return true;
1383 }
1384
1385 // Moved from caller.
1386 if (!plainRelativeTo) {
1387 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
1388 JSMSG_TEMPORAL_DURATION_UNCOMPARABLE,
1389 "relativeTo");
1390 return false;
1391 }
1392
1393 // Step 3.
1394 ISODate later;
1395 if (!CalendarDateAdd(cx, plainRelativeTo.calendar(), plainRelativeTo,
1396 yearsMonthsWeeksDuration, TemporalOverflow::Constrain,
1397 &later)) {
1398 return false;
1399 }
1400
1401 // Step 4.
1402 int32_t epochDays1 = MakeDay(plainRelativeTo);
1403 MOZ_ASSERT(MinEpochDay <= epochDays1 && epochDays1 <= MaxEpochDay);
1404
1405 // Step 5.
1406 int32_t epochDays2 = MakeDay(later);
1407 MOZ_ASSERT(MinEpochDay <= epochDays2 && epochDays2 <= MaxEpochDay);
1408
1409 // Step 4.
1410 int32_t yearsMonthsWeeksInDay = epochDays2 - epochDays1;
1411
1412 // Step 5.
1413 *result = days + yearsMonthsWeeksInDay;
1414 return true;
1415 }
1416
1417 static bool NumberToStringBuilder(JSContext* cx, double num,
1418 JSStringBuilder& sb) {
1419 MOZ_ASSERT(IsInteger(num));
1420 MOZ_ASSERT(num >= 0);
1421 MOZ_ASSERT(num < DOUBLE_INTEGRAL_PRECISION_LIMIT);
1422
1423 ToCStringBuf cbuf;
1424 size_t length;
1425 const char* numStr = NumberToCString(&cbuf, num, &length);
1426
1427 return sb.append(numStr, length);
1428 }
1429
1430 static Duration AbsoluteDuration(const Duration& duration) {
1431 return {
1432 std::abs(duration.years), std::abs(duration.months),
1433 std::abs(duration.weeks), std::abs(duration.days),
1434 std::abs(duration.hours), std::abs(duration.minutes),
1435 std::abs(duration.seconds), std::abs(duration.milliseconds),
1436 std::abs(duration.microseconds), std::abs(duration.nanoseconds),
1437 };
1438 }
1439
1440 /**
1441 * FormatFractionalSeconds ( subSecondNanoseconds, precision )
1442 */
1443 [[nodiscard]] static bool FormatFractionalSeconds(JSStringBuilder& result,
1444 int32_t subSecondNanoseconds,
1445 Precision precision) {
1446 MOZ_ASSERT(0 <= subSecondNanoseconds && subSecondNanoseconds < 1'000'000'000);
1447 MOZ_ASSERT(precision != Precision::Minute());
1448
1449 // Steps 1-2.
1450 if (precision == Precision::Auto()) {
1451 // Step 1.a.
1452 if (subSecondNanoseconds == 0) {
1453 return true;
1454 }
1455
1456 // Step 3. (Reordered)
1457 if (!result.append('.')) {
1458 return false;
1459 }
1460
1461 // Steps 1.b-c.
1462 int32_t k = 100'000'000;
1463 do {
1464 if (!result.append(char('0' + (subSecondNanoseconds / k)))) {
1465 return false;
1466 }
1467 subSecondNanoseconds %= k;
1468 k /= 10;
1469 } while (subSecondNanoseconds);
1470 } else {
1471 // Step 2.a.
1472 uint8_t p = precision.value();
1473 if (p == 0) {
1474 return true;
1475 }
1476
1477 // Step 3. (Reordered)
1478 if (!result.append('.')) {
1479 return false;
1480 }
1481
1482 // Steps 2.b-c.
1483 int32_t k = 100'000'000;
1484 for (uint8_t i = 0; i < precision.value(); i++) {
1485 if (!result.append(char('0' + (subSecondNanoseconds / k)))) {
1486 return false;
1487 }
1488 subSecondNanoseconds %= k;
1489 k /= 10;
1490 }
1491 }
1492
1493 return true;
1494 }
1495
1496 /**
1497 * TemporalDurationToString ( duration, precision )
1498 */
1499 static JSString* TemporalDurationToString(JSContext* cx,
1500 const Duration& duration,
1501 Precision precision) {
1502 MOZ_ASSERT(IsValidDuration(duration));
1503 MOZ_ASSERT(precision != Precision::Minute());
1504
1505 // Fast path for zero durations.
1506 if (duration == Duration{} &&
1507 (precision == Precision::Auto() || precision.value() == 0)) {
1508 return NewStringCopyZ<CanGC>(cx, "PT0S");
1509 }
1510
1511 // Convert to absolute values up front. This is okay to do, because when the
1512 // duration is valid, all components have the same sign.
1513 const auto& [years, months, weeks, days, hours, minutes, seconds,
1514 milliseconds, microseconds, nanoseconds] =
1515 AbsoluteDuration(duration);
1516
1517 // Years to seconds parts are all safe integers for valid durations.
1518 MOZ_ASSERT(years < DOUBLE_INTEGRAL_PRECISION_LIMIT);
1519 MOZ_ASSERT(months < DOUBLE_INTEGRAL_PRECISION_LIMIT);
1520 MOZ_ASSERT(weeks < DOUBLE_INTEGRAL_PRECISION_LIMIT);
1521 MOZ_ASSERT(days < DOUBLE_INTEGRAL_PRECISION_LIMIT);
1522 MOZ_ASSERT(hours < DOUBLE_INTEGRAL_PRECISION_LIMIT);
1523 MOZ_ASSERT(minutes < DOUBLE_INTEGRAL_PRECISION_LIMIT);
1524 MOZ_ASSERT(seconds < DOUBLE_INTEGRAL_PRECISION_LIMIT);
1525
1526 // Step 1.
1527 int32_t sign = DurationSign(duration);
1528
1529 // Steps 2 and 7.
1530 JSStringBuilder result(cx);
1531
1532 // Step 14. (Reordered)
1533 if (sign < 0) {
1534 if (!result.append('-')) {
1535 return nullptr;
1536 }
1537 }
1538
1539 // Step 15. (Reordered)
1540 if (!result.append('P')) {
1541 return nullptr;
1542 }
1543
1544 // Step 3.
1545 if (years != 0) {
1546 if (!NumberToStringBuilder(cx, years, result)) {
1547 return nullptr;
1548 }
1549 if (!result.append('Y')) {
1550 return nullptr;
1551 }
1552 }
1553
1554 // Step 4.
1555 if (months != 0) {
1556 if (!NumberToStringBuilder(cx, months, result)) {
1557 return nullptr;
1558 }
1559 if (!result.append('M')) {
1560 return nullptr;
1561 }
1562 }
1563
1564 // Step 5.
1565 if (weeks != 0) {
1566 if (!NumberToStringBuilder(cx, weeks, result)) {
1567 return nullptr;
1568 }
1569 if (!result.append('W')) {
1570 return nullptr;
1571 }
1572 }
1573
1574 // Step 6.
1575 if (days != 0) {
1576 if (!NumberToStringBuilder(cx, days, result)) {
1577 return nullptr;
1578 }
1579 if (!result.append('D')) {
1580 return nullptr;
1581 }
1582 }
1583
1584 // Step 7. (Moved above)
1585
1586 // Steps 10-11. (Reordered)
1587 bool zeroMinutesAndHigher = years == 0 && months == 0 && weeks == 0 &&
1588 days == 0 && hours == 0 && minutes == 0;
1589
1590 // Step 12.
1591 auto secondsDuration = TimeDurationFromComponents(
1592 0.0, 0.0, seconds, milliseconds, microseconds, nanoseconds);
1593
1594 // Steps 8-9, 13, and 16.
1595 bool hasSecondsPart = (secondsDuration != TimeDuration{}) ||
1596 zeroMinutesAndHigher || precision != Precision::Auto();
1597 if (hours != 0 || minutes != 0 || hasSecondsPart) {
1598 // Step 16. (Reordered)
1599 if (!result.append('T')) {
1600 return nullptr;
1601 }
1602
1603 // Step 8.
1604 if (hours != 0) {
1605 if (!NumberToStringBuilder(cx, hours, result)) {
1606 return nullptr;
1607 }
1608 if (!result.append('H')) {
1609 return nullptr;
1610 }
1611 }
1612
1613 // Step 9.
1614 if (minutes != 0) {
1615 if (!NumberToStringBuilder(cx, minutes, result)) {
1616 return nullptr;
1617 }
1618 if (!result.append('M')) {
1619 return nullptr;
1620 }
1621 }
1622
1623 // Step 13.
1624 if (hasSecondsPart) {
1625 // Step 13.a.
1626 if (!NumberToStringBuilder(cx, double(secondsDuration.seconds), result)) {
1627 return nullptr;
1628 }
1629
1630 // Step 13.b.
1631 if (!FormatFractionalSeconds(result, secondsDuration.nanoseconds,
1632 precision)) {
1633 return nullptr;
1634 }
1635
1636 // Step 13.c.
1637 if (!result.append('S')) {
1638 return nullptr;
1639 }
1640 }
1641 }
1642
1643 // Steps 14-16. (Moved above)
1644
1645 // Step 17.
1646 return result.finishString();
1647 }
1648
1649 /**
1650 * GetTemporalRelativeToOption ( options )
1651 */
1652 static bool GetTemporalRelativeToOption(
1653 JSContext* cx, Handle<JSObject*> options,
1654 MutableHandle<PlainDate> plainRelativeTo,
1655 MutableHandle<ZonedDateTime> zonedRelativeTo) {
1656 // Default initialize both return values.
1657 plainRelativeTo.set(PlainDate{});
1658 zonedRelativeTo.set(ZonedDateTime{});
1659
1660 // Step 1.
1661 Rooted<Value> value(cx);
1662 if (!GetProperty(cx, options, options, cx->names().relativeTo, &value)) {
1663 return false;
1664 }
1665
1666 // Step 2.
1667 if (value.isUndefined()) {
1668 return true;
1669 }
1670
1671 // Step 3.
1672 auto offsetBehaviour = OffsetBehaviour::Option;
1673
1674 // Step 4.
1675 auto matchBehaviour = MatchBehaviour::MatchExactly;
1676
1677 // Steps 5-6.
1678 EpochNanoseconds epochNanoseconds;
1679 Rooted<TimeZoneValue> timeZone(cx);
1680 Rooted<CalendarValue> calendar(cx);
1681 if (value.isObject()) {
1682 Rooted<JSObject*> obj(cx, &value.toObject());
1683
1684 // Step 5.a.
1685 if (auto* zonedDateTime = obj->maybeUnwrapIf<ZonedDateTimeObject>()) {
1686 auto epochNs = zonedDateTime->epochNanoseconds();
1687 Rooted<TimeZoneValue> timeZone(cx, zonedDateTime->timeZone());
1688 Rooted<CalendarValue> calendar(cx, zonedDateTime->calendar());
1689
1690 if (!timeZone.wrap(cx)) {
1691 return false;
1692 }
1693 if (!calendar.wrap(cx)) {
1694 return false;
1695 }
1696
1697 // Step 5.a.i.
1698 zonedRelativeTo.set(ZonedDateTime{epochNs, timeZone, calendar});
1699 return true;
1700 }
1701
1702 // Step 5.b.
1703 if (auto* plainDate = obj->maybeUnwrapIf<PlainDateObject>()) {
1704 auto date = plainDate->date();
1705
1706 Rooted<CalendarValue> calendar(cx, plainDate->calendar());
1707 if (!calendar.wrap(cx)) {
1708 return false;
1709 }
1710
1711 // Step 5.b.i.
1712 plainRelativeTo.set(PlainDate{date, calendar});
1713 return true;
1714 }
1715
1716 // Step 5.c.
1717 if (auto* dateTime = obj->maybeUnwrapIf<PlainDateTimeObject>()) {
1718 auto date = dateTime->date();
1719
1720 Rooted<CalendarValue> calendar(cx, dateTime->calendar());
1721 if (!calendar.wrap(cx)) {
1722 return false;
1723 }
1724
1725 // Steps 5.c.i-ii.
1726 plainRelativeTo.set(PlainDate{date, calendar});
1727 return true;
1728 }
1729
1730 // Step 5.d.
1731 if (!GetTemporalCalendarWithISODefault(cx, obj, &calendar)) {
1732 return false;
1733 }
1734
1735 // Step 5.e.
1736 Rooted<CalendarFields> fields(cx);
1737 if (!PrepareCalendarFields(cx, calendar, obj,
1738 {
1739 CalendarField::Year,
1740 CalendarField::Month,
1741 CalendarField::MonthCode,
1742 CalendarField::Day,
1743 CalendarField::Hour,
1744 CalendarField::Minute,
1745 CalendarField::Second,
1746 CalendarField::Millisecond,
1747 CalendarField::Microsecond,
1748 CalendarField::Nanosecond,
1749 CalendarField::Offset,
1750 CalendarField::TimeZone,
1751 },
1752 &fields)) {
1753 return false;
1754 }
1755
1756 // Step 5.f.
1757 ISODateTime dateTime;
1758 if (!InterpretTemporalDateTimeFields(
1759 cx, calendar, fields, TemporalOverflow::Constrain, &dateTime)) {
1760 return false;
1761 }
1762
1763 // Step 5.g.
1764 timeZone = fields.timeZone();
1765
1766 // Step 5.h.
1767 auto offset = fields.offset();
1768
1769 // Step 5.j.
1770 if (!fields.has(CalendarField::Offset)) {
1771 offsetBehaviour = OffsetBehaviour::Wall;
1772 }
1773
1774 // Step 7.
1775 if (!timeZone) {
1776 // Steps 7.a-b.
1777 return CreateTemporalDate(cx, dateTime.date, calendar, plainRelativeTo);
1778 }
1779
1780 // Steps 8-9.
1781 int64_t offsetNs = 0;
1782 if (offsetBehaviour == OffsetBehaviour::Option) {
1783 // Step 8.a.
1784 offsetNs = int64_t(offset);
1785 }
1786
1787 // Step 10.
1788 if (!InterpretISODateTimeOffset(
1789 cx, dateTime, offsetBehaviour, offsetNs, timeZone,
1790 TemporalDisambiguation::Compatible, TemporalOffset::Reject,
1791 matchBehaviour, &epochNanoseconds)) {
1792 return false;
1793 }
1794 } else {
1795 // Step 6.a.
1796 if (!value.isString()) {
1797 ReportValueError(cx, JSMSG_UNEXPECTED_TYPE, JSDVG_IGNORE_STACK, value,
1798 nullptr, "not a string");
1799 return false;
1800 }
1801 Rooted<JSString*> string(cx, value.toString());
1802
1803 // Step 6.b.
1804 Rooted<ParsedZonedDateTime> parsed(cx);
1805 if (!ParseTemporalRelativeToString(cx, string, &parsed)) {
1806 return false;
1807 }
1808
1809 // Steps 6.c-e. (Not applicable in our implementation.)
1810
1811 // Step 6.f.
1812 if (parsed.timeZoneAnnotation()) {
1813 // Step 6.f.i.
1814 if (!ToTemporalTimeZone(cx, parsed.timeZoneAnnotation(), &timeZone)) {
1815 return false;
1816 }
1817
1818 // Steps 6.f.ii-iii.
1819 if (parsed.isUTC()) {
1820 offsetBehaviour = OffsetBehaviour::Exact;
1821 } else if (!parsed.hasOffset()) {
1822 offsetBehaviour = OffsetBehaviour::Wall;
1823 }
1824
1825 // Step 6.f.iv.
1826 matchBehaviour = MatchBehaviour::MatchMinutes;
1827 } else {
1828 MOZ_ASSERT(!timeZone);
1829 }
1830
1831 // Steps 6.g-i.
1832 if (parsed.calendar()) {
1833 if (!CanonicalizeCalendar(cx, parsed.calendar(), &calendar)) {
1834 return false;
1835 }
1836 } else {
1837 calendar.set(CalendarValue(CalendarId::ISO8601));
1838 }
1839
1840 // Step 7.
1841 if (!timeZone) {
1842 // Steps 7.a-b.
1843 return CreateTemporalDate(cx, parsed.dateTime().date, calendar,
1844 plainRelativeTo);
1845 }
1846
1847 // Steps 8-9.
1848 int64_t offsetNs;
1849 if (offsetBehaviour == OffsetBehaviour::Option) {
1850 MOZ_ASSERT(parsed.hasOffset());
1851
1852 // Step 8.a.
1853 offsetNs = parsed.timeZoneOffset();
1854 } else {
1855 // Step 9.
1856 offsetNs = 0;
1857 }
1858
1859 // Step 10.
1860 if (parsed.isStartOfDay()) {
1861 if (!InterpretISODateTimeOffset(
1862 cx, parsed.dateTime().date, offsetBehaviour, offsetNs, timeZone,
1863 TemporalDisambiguation::Compatible, TemporalOffset::Reject,
1864 matchBehaviour, &epochNanoseconds)) {
1865 return false;
1866 }
1867 } else {
1868 if (!InterpretISODateTimeOffset(
1869 cx, parsed.dateTime(), offsetBehaviour, offsetNs, timeZone,
1870 TemporalDisambiguation::Compatible, TemporalOffset::Reject,
1871 matchBehaviour, &epochNanoseconds)) {
1872 return false;
1873 }
1874 }
1875 }
1876 MOZ_ASSERT(IsValidEpochNanoseconds(epochNanoseconds));
1877
1878 // Steps 11-12.
1879 zonedRelativeTo.set(ZonedDateTime{epochNanoseconds, timeZone, calendar});
1880 return true;
1881 }
1882
1883 /**
1884 * RoundTimeDurationToIncrement ( d, increment, roundingMode )
1885 */
1886 static TimeDuration RoundTimeDurationToIncrement(
1887 const TimeDuration& duration, const TemporalUnit unit, Increment increment,
1888 TemporalRoundingMode roundingMode) {
1889 MOZ_ASSERT(IsValidTimeDuration(duration));
1890 MOZ_ASSERT(unit >= TemporalUnit::Day);
1891 MOZ_ASSERT_IF(unit >= TemporalUnit::Hour,
1892 increment <= MaximumTemporalDurationRoundingIncrement(unit));
1893
1894 auto divisor = Int128{ToNanoseconds(unit)} * Int128{increment.value()};
1895 MOZ_ASSERT(divisor > Int128{0});
1896 MOZ_ASSERT_IF(unit >= TemporalUnit::Hour,
1897 divisor <= Int128{ToNanoseconds(TemporalUnit::Day)});
1898
1899 auto totalNanoseconds = duration.toNanoseconds();
1900 auto rounded =
1901 RoundNumberToIncrement(totalNanoseconds, divisor, roundingMode);
1902 return TimeDuration::fromNanoseconds(rounded);
1903 }
1904
1905 /**
1906 * TotalTimeDuration ( timeDuration, unit )
1907 */
1908 double js::temporal::TotalTimeDuration(const TimeDuration& duration,
1909 TemporalUnit unit) {
1910 MOZ_ASSERT(IsValidTimeDuration(duration));
1911 MOZ_ASSERT(unit >= TemporalUnit::Day);
1912
1913 auto numerator = duration.toNanoseconds();
1914 auto denominator = Int128{ToNanoseconds(unit)};
1915 return FractionToDouble(numerator, denominator);
1916 }
1917
1918 /**
1919 * RoundTimeDuration ( duration, increment, unit, roundingMode )
1920 */
1921 static bool RoundTimeDuration(JSContext* cx, const TimeDuration& duration,
1922 Increment increment, TemporalUnit unit,
1923 TemporalRoundingMode roundingMode,
1924 TimeDuration* result) {
1925 MOZ_ASSERT(IsValidTimeDuration(duration));
1926 MOZ_ASSERT(increment <= Increment::max());
1927 MOZ_ASSERT(unit > TemporalUnit::Day);
1928
1929 // Step 1-2.
1930 auto rounded =
1931 RoundTimeDurationToIncrement(duration, unit, increment, roundingMode);
1932 if (!IsValidTimeDuration(rounded)) {
1933 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
1934 JSMSG_TEMPORAL_DURATION_INVALID_NORMALIZED_TIME);
1935 return false;
1936 }
1937 *result = rounded;
1938 return true;
1939 }
1940
1941 /**
1942 * RoundTimeDuration ( duration, increment, unit, roundingMode )
1943 */
1944 TimeDuration js::temporal::RoundTimeDuration(
1945 const TimeDuration& duration, Increment increment, TemporalUnit unit,
1946 TemporalRoundingMode roundingMode) {
1947 MOZ_ASSERT(IsValidTimeDuration(duration));
1948 MOZ_ASSERT(increment <= Increment::max());
1949 MOZ_ASSERT(unit > TemporalUnit::Day);
1950
1951 auto result =
1952 RoundTimeDurationToIncrement(duration, unit, increment, roundingMode);
1953 MOZ_ASSERT(IsValidTimeDuration(result));
1954
1955 return result;
1956 }
1957
1958 #ifdef DEBUG
1959 /**
1960 * Return true if the input is within the valid epoch nanoseconds limits with a
1961 * time zone offset applied, i.e. it's smaller than ±(8.64 × 10^21 + nsPerDay).
1962 */
1963 static bool IsValidLocalNanoseconds(const EpochNanoseconds& epochNanoseconds) {
1964 MOZ_ASSERT(0 <= epochNanoseconds.nanoseconds &&
1965 epochNanoseconds.nanoseconds <= 999'999'999);
1966
1967 // Time zone offsets can't exceed 24 hours.
1968 constexpr auto oneDay = EpochDuration::fromDays(1);
1969
1970 // Exclusive limits.
1971 constexpr auto min = EpochNanoseconds::min() - oneDay;
1972 constexpr auto max = EpochNanoseconds::max() + oneDay;
1973
1974 return min < epochNanoseconds && epochNanoseconds < max;
1975 }
1976 #endif
1977
1978 enum class UnsignedRoundingMode {
1979 Zero,
1980 Infinity,
1981 HalfZero,
1982 HalfInfinity,
1983 HalfEven
1984 };
1985
1986 /**
1987 * GetUnsignedRoundingMode ( roundingMode, sign )
1988 */
1989 static UnsignedRoundingMode GetUnsignedRoundingMode(
1990 TemporalRoundingMode roundingMode, bool isNegative) {
1991 switch (roundingMode) {
1992 case TemporalRoundingMode::Ceil:
1993 return isNegative ? UnsignedRoundingMode::Zero
1994 : UnsignedRoundingMode::Infinity;
1995 case TemporalRoundingMode::Floor:
1996 return isNegative ? UnsignedRoundingMode::Infinity
1997 : UnsignedRoundingMode::Zero;
1998 case TemporalRoundingMode::Expand:
1999 return UnsignedRoundingMode::Infinity;
2000 case TemporalRoundingMode::Trunc:
2001 return UnsignedRoundingMode::Zero;
2002 case TemporalRoundingMode::HalfCeil:
2003 return isNegative ? UnsignedRoundingMode::HalfZero
2004 : UnsignedRoundingMode::HalfInfinity;
2005 case TemporalRoundingMode::HalfFloor:
2006 return isNegative ? UnsignedRoundingMode::HalfInfinity
2007 : UnsignedRoundingMode::HalfZero;
2008 case TemporalRoundingMode::HalfExpand:
2009 return UnsignedRoundingMode::HalfInfinity;
2010 case TemporalRoundingMode::HalfTrunc:
2011 return UnsignedRoundingMode::HalfZero;
2012 case TemporalRoundingMode::HalfEven:
2013 return UnsignedRoundingMode::HalfEven;
2014 }
2015 MOZ_CRASH("invalid rounding mode");
2016 }
2017
2018 struct DurationNudge {
2019 InternalDuration duration;
2020 EpochNanoseconds epochNs;
2021 double total = 0;
2022 bool didExpandCalendarUnit = false;
2023 };
2024
2025 /**
2026 * NudgeToCalendarUnit ( sign, duration, destEpochNs, isoDateTime, timeZone,
2027 * calendar, increment, unit, roundingMode )
2028 */
2029 static bool NudgeToCalendarUnit(JSContext* cx, const InternalDuration& duration,
2030 const EpochNanoseconds& destEpochNs,
2031 const ISODateTime& isoDateTime,
2032 Handle<TimeZoneValue> timeZone,
2033 Handle<CalendarValue> calendar,
2034 Increment increment, TemporalUnit unit,
2035 TemporalRoundingMode roundingMode,
2036 DurationNudge* result) {
2037 MOZ_ASSERT(IsValidDuration(duration));
2038 MOZ_ASSERT_IF(timeZone, IsValidEpochNanoseconds(destEpochNs));
2039 MOZ_ASSERT_IF(!timeZone, IsValidLocalNanoseconds(destEpochNs));
2040 MOZ_ASSERT(ISODateTimeWithinLimits(isoDateTime));
2041 MOZ_ASSERT(unit <= TemporalUnit::Day);
2042
2043 int32_t sign = InternalDurationSign(duration) < 0 ? -1 : 1;
2044
2045 // Steps 1-4.
2046 int64_t r1;
2047 int64_t r2;
2048 DateDuration startDuration;
2049 DateDuration endDuration;
2050 if (unit == TemporalUnit::Year) {
2051 // Step 1.a.
2052 int64_t years = RoundNumberToIncrement(duration.date.years, increment,
2053 TemporalRoundingMode::Trunc);
2054
2055 // Step 1.b.
2056 r1 = years;
2057
2058 // Step 1.c.
2059 r2 = years + int64_t(increment.value()) * sign;
2060
2061 // Step 1.d.
2062 startDuration = {r1};
2063
2064 // Step 1.e.
2065 endDuration = {r2};
2066 } else if (unit == TemporalUnit::Month) {
2067 // Step 2.a.
2068 int64_t months = RoundNumberToIncrement(duration.date.months, increment,
2069 TemporalRoundingMode::Trunc);
2070
2071 // Step 2.b.
2072 r1 = months;
2073
2074 // Step 2.c.
2075 r2 = months + int64_t(increment.value()) * sign;
2076
2077 // Step 2.d.
2078 startDuration = {duration.date.years, r1};
2079
2080 // Step 2.e.
2081 endDuration = {duration.date.years, r2};
2082 } else if (unit == TemporalUnit::Week) {
2083 // Step 3.a.
2084 auto yearsMonths = DateDuration{duration.date.years, duration.date.months};
2085
2086 // Step 3.b.
2087 ISODate weeksStart;
2088 if (!CalendarDateAdd(cx, calendar, isoDateTime.date, yearsMonths,
2089 TemporalOverflow::Constrain, &weeksStart)) {
2090 return false;
2091 }
2092 MOZ_ASSERT(ISODateWithinLimits(weeksStart));
2093
2094 // Step 3.c.
2095 ISODate weeksEnd;
2096 if (!BalanceISODate(cx, weeksStart, duration.date.days, &weeksEnd)) {
2097 return false;
2098 }
2099 MOZ_ASSERT(ISODateWithinLimits(weeksEnd));
2100
2101 // Step 3.d.
2102 DateDuration untilResult;
2103 if (!CalendarDateUntil(cx, calendar, weeksStart, weeksEnd,
2104 TemporalUnit::Week, &untilResult)) {
2105 return false;
2106 }
2107
2108 // Step 3.e.
2109 int64_t weeks =
2110 RoundNumberToIncrement(duration.date.weeks + untilResult.weeks,
2111 increment, TemporalRoundingMode::Trunc);
2112
2113 // Step 3.f.
2114 r1 = weeks;
2115
2116 // Step 3.g.
2117 r2 = weeks + int64_t(increment.value()) * sign;
2118
2119 // Step 3.h.
2120 startDuration = {duration.date.years, duration.date.months, r1};
2121
2122 // Step 3.i.
2123 endDuration = {duration.date.years, duration.date.months, r2};
2124 } else {
2125 // Step 4.a.
2126 MOZ_ASSERT(unit == TemporalUnit::Day);
2127
2128 // Step 4.b.
2129 int64_t days = RoundNumberToIncrement(duration.date.days, increment,
2130 TemporalRoundingMode::Trunc);
2131
2132 // Step 4.c.
2133 r1 = days;
2134
2135 // Step 4.d.
2136 r2 = days + int64_t(increment.value()) * sign;
2137
2138 // Step 4.e.
2139 startDuration = {duration.date.years, duration.date.months,
2140 duration.date.weeks, r1};
2141
2142 // Step 4.f.
2143 endDuration = {duration.date.years, duration.date.months,
2144 duration.date.weeks, r2};
2145 }
2146 MOZ_ASSERT(IsValidDuration(startDuration));
2147 MOZ_ASSERT(IsValidDuration(endDuration));
2148
2149 // Step 5.
2150 MOZ_ASSERT_IF(sign > 0, r1 >= 0 && r1 < r2);
2151
2152 // Step 6.
2153 MOZ_ASSERT_IF(sign < 0, r1 <= 0 && r1 > r2);
2154
2155 // Step 7.
2156 ISODate start;
2157 if (!CalendarDateAdd(cx, calendar, isoDateTime.date, startDuration,
2158 TemporalOverflow::Constrain, &start)) {
2159 return false;
2160 }
2161
2162 // Step 8.
2163 ISODate end;
2164 if (!CalendarDateAdd(cx, calendar, isoDateTime.date, endDuration,
2165 TemporalOverflow::Constrain, &end)) {
2166 return false;
2167 }
2168
2169 // Step 9.
2170 auto startDateTime = ISODateTime{start, isoDateTime.time};
2171 MOZ_ASSERT(ISODateTimeWithinLimits(startDateTime));
2172
2173 // Step 10.
2174 auto endDateTime = ISODateTime{end, isoDateTime.time};
2175 MOZ_ASSERT(ISODateTimeWithinLimits(endDateTime));
2176
2177 // Steps 11-12.
2178 EpochNanoseconds startEpochNs;
2179 EpochNanoseconds endEpochNs;
2180 if (!timeZone) {
2181 // Step 11.a.
2182 startEpochNs = GetUTCEpochNanoseconds(startDateTime);
2183
2184 // Step 11.b.
2185 endEpochNs = GetUTCEpochNanoseconds(endDateTime);
2186 } else {
2187 // Step 12.a.
2188 if (!GetEpochNanosecondsFor(cx, timeZone, startDateTime,
2189 TemporalDisambiguation::Compatible,
2190 &startEpochNs)) {
2191 return false;
2192 }
2193
2194 // Step 12.b.
2195 if (!GetEpochNanosecondsFor(cx, timeZone, endDateTime,
2196 TemporalDisambiguation::Compatible,
2197 &endEpochNs)) {
2198 return false;
2199 }
2200 }
2201
2202 // Steps 13-14.
2203 MOZ_ASSERT_IF(sign > 0,
2204 startEpochNs <= destEpochNs && destEpochNs <= endEpochNs);
2205 MOZ_ASSERT_IF(sign < 0,
2206 endEpochNs <= destEpochNs && destEpochNs <= startEpochNs);
2207
2208 // Step 15.
2209 MOZ_ASSERT(startEpochNs != endEpochNs);
2210
2211 // Step 16.
2212 auto numerator = (destEpochNs - startEpochNs).toNanoseconds();
2213 auto denominator = (endEpochNs - startEpochNs).toNanoseconds();
2214 MOZ_ASSERT(denominator != Int128{0});
2215 MOZ_ASSERT(numerator.abs() <= denominator.abs());
2216 MOZ_ASSERT_IF(denominator > Int128{0}, numerator >= Int128{0});
2217 MOZ_ASSERT_IF(denominator < Int128{0}, numerator <= Int128{0});
2218
2219 // Ensure |numerator| and |denominator| are both non-negative to simplify the
2220 // following computations.
2221 if (denominator < Int128{0}) {
2222 numerator = -numerator;
2223 denominator = -denominator;
2224 }
2225
2226 // Steps 17-19.
2227 //
2228 // |total| must only be computed when called from Duration.prototype.total,
2229 // which always passes "trunc" rounding mode with an increment of one.
2230 double total = mozilla::UnspecifiedNaN<double>();
2231 if (roundingMode == TemporalRoundingMode::Trunc &&
2232 increment == Increment{1}) {
2233 // total = r1 + progress × increment × sign
2234 // = r1 + (numerator / denominator) × increment × sign
2235 // = r1 + (numerator × increment × sign) / denominator
2236 // = (r1 × denominator + numerator × increment × sign) / denominator
2237 //
2238 // Computing `n` can't overflow, because:
2239 // - For years, months, and weeks, `abs(r1) ≤ 2^32`.
2240 // - For days, `abs(r1) < ⌈(2^53) / (24 * 60 * 60)⌉`.
2241 // - `denominator` and `numerator` are below-or-equal `2 × 8.64 × 10^21`.
2242 // - And finally `increment ≤ 10^9`.
2243 auto n = Int128{r1} * denominator + numerator * Int128{sign};
2244 total = FractionToDouble(n, denominator);
2245 }
2246
2247 // Steps 20-21.
2248 auto unsignedRoundingMode = GetUnsignedRoundingMode(roundingMode, sign < 0);
2249
2250 // Steps 22-23. (Inlined ApplyUnsignedRoundingMode)
2251 //
2252 // clang-format off
2253 //
2254 // ApplyUnsignedRoundingMode, steps 1-16.
2255 //
2256 // `total = r1` iff `progress = 0`. And `progress = 0` iff `numerator = 0`.
2257 //
2258 // d1 = total - r1
2259 // = (r1 × denominator + numerator × increment × sign) / denominator - r1
2260 // = (numerator × increment × sign) / denominator
2261 //
2262 // d2 = r2 - total
2263 // = r1 + increment - (r1 × denominator + numerator × increment × sign) / denominator
2264 // = (increment × denominator - numerator × increment × sign) / denominator
2265 //
2266 // d1 < d2
2267 // ⇔ (numerator × increment × sign) / denominator < (increment × denominator - numerator × increment × sign) / denominator
2268 // ⇔ (numerator × increment × sign) < (increment × denominator - numerator × increment × sign)
2269 // ⇔ (numerator × sign) < (denominator - numerator × sign)
2270 // ⇔ (2 × numerator × sign) < denominator
2271 //
2272 // cardinality = (r1 / (r2 – r1)) modulo 2
2273 // = (r1 / (r1 + increment - r1)) modulo 2
2274 // = (r1 / increment) modulo 2
2275 //
2276 // clang-format on
2277 bool didExpandCalendarUnit;
2278 if (numerator == denominator) {
2279 didExpandCalendarUnit = true;
2280 } else if (numerator == Int128{0}) {
2281 didExpandCalendarUnit = false;
2282 } else if (unsignedRoundingMode == UnsignedRoundingMode::Zero) {
2283 didExpandCalendarUnit = false;
2284 } else if (unsignedRoundingMode == UnsignedRoundingMode::Infinity) {
2285 didExpandCalendarUnit = true;
2286 } else if (numerator + numerator < denominator) {
2287 didExpandCalendarUnit = false;
2288 } else if (numerator + numerator > denominator) {
2289 didExpandCalendarUnit = true;
2290 } else if (unsignedRoundingMode == UnsignedRoundingMode::HalfZero) {
2291 didExpandCalendarUnit = false;
2292 } else if (unsignedRoundingMode == UnsignedRoundingMode::HalfInfinity) {
2293 didExpandCalendarUnit = true;
2294 } else if ((r1 / increment.value()) % 2 == 0) {
2295 didExpandCalendarUnit = false;
2296 } else {
2297 didExpandCalendarUnit = true;
2298 }
2299
2300 // Steps 24-28.
2301 auto resultDuration = didExpandCalendarUnit ? endDuration : startDuration;
2302 auto resultEpochNs = didExpandCalendarUnit ? endEpochNs : startEpochNs;
2303 *result = {{resultDuration, {}}, resultEpochNs, total, didExpandCalendarUnit};
2304 return true;
2305 }
2306
2307 #ifdef DEBUG
2308 static bool IsValidTimeFromDateTimeDuration(const TimeDuration& timeDuration) {
2309 // Time zone adjustment can't exceed 24 hours.
2310 constexpr auto oneDay = EpochDuration::fromDays(1);
2311
2312 // Time zone adjusted nsMinInstant and nsMaxInstant.
2313 constexpr auto min = EpochNanoseconds::min() - oneDay;
2314 constexpr auto max = EpochNanoseconds::max() + oneDay;
2315
2316 // Maximum duration between two date-time points.
2317 constexpr auto maxDuration = (max - min).to<TimeDuration>();
2318 static_assert(maxDuration == TimeDuration::fromDays(200'000'002));
2319
2320 // If |timeDuration| is a duration between two date-times within the valid
2321 // limits, the duration can't exceed the duration between time zone adjusted
2322 // nsMinInstant and nsMaxInstant.
2323 return timeDuration.abs() < maxDuration;
2324 }
2325 #endif
2326
2327 /**
2328 * NudgeToZonedTime ( sign, duration, isoDateTime, timeZone, calendar,
2329 * increment, unit, roundingMode )
2330 */
2331 static bool NudgeToZonedTime(JSContext* cx, const InternalDuration& duration,
2332 const ISODateTime& isoDateTime,
2333 Handle<TimeZoneValue> timeZone,
2334 Handle<CalendarValue> calendar,
2335 Increment increment, TemporalUnit unit,
2336 TemporalRoundingMode roundingMode,
2337 DurationNudge* result) {
2338 MOZ_ASSERT(IsValidDuration(duration));
2339 MOZ_ASSERT(IsValidTimeFromDateTimeDuration(duration.time));
2340 MOZ_ASSERT(ISODateTimeWithinLimits(isoDateTime));
2341 MOZ_ASSERT(unit >= TemporalUnit::Hour);
2342
2343 int32_t sign = InternalDurationSign(duration) < 0 ? -1 : 1;
2344
2345 // Step 1.
2346 ISODate start;
2347 if (!CalendarDateAdd(cx, calendar, isoDateTime.date, duration.date,
2348 TemporalOverflow::Constrain, &start)) {
2349 return false;
2350 }
2351
2352 // Step 2.
2353 auto startDateTime = ISODateTime{start, isoDateTime.time};
2354 MOZ_ASSERT(ISODateTimeWithinLimits(startDateTime));
2355
2356 // Step 3.
2357 auto end = BalanceISODate(start, sign);
2358
2359 // Step 4.
2360 auto endDateTime = ISODateTime{end, isoDateTime.time};
2361 if (!ISODateTimeWithinLimits(endDateTime)) {
2362 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
2363 JSMSG_TEMPORAL_PLAIN_DATE_TIME_INVALID);
2364 return false;
2365 }
2366
2367 // Step 5.
2368 EpochNanoseconds startEpochNs;
2369 if (!GetEpochNanosecondsFor(cx, timeZone, startDateTime,
2370 TemporalDisambiguation::Compatible,
2371 &startEpochNs)) {
2372 return false;
2373 }
2374
2375 // Step 6.
2376 EpochNanoseconds endEpochNs;
2377 if (!GetEpochNanosecondsFor(cx, timeZone, endDateTime,
2378 TemporalDisambiguation::Compatible,
2379 &endEpochNs)) {
2380 return false;
2381 }
2382
2383 // Step 7.
2384 auto daySpan =
2385 TimeDurationFromEpochNanosecondsDifference(endEpochNs, startEpochNs);
2386 MOZ_ASSERT(daySpan.abs() <= TimeDuration::fromDays(2),
2387 "maximum day length for repeated days");
2388
2389 // Step 8.
2390 MOZ_ASSERT(TimeDurationSign(daySpan) == sign);
2391
2392 // Steps 9-10.
2393 //
2394 // RoundTimeDurationToIncrement is infallible |duration.time| is a valid
2395 // date-time duration.
2396 auto roundedTime = RoundTimeDurationToIncrement(duration.time, unit,
2397 increment, roundingMode);
2398 MOZ_ASSERT(IsValidTimeDuration(roundedTime));
2399
2400 // Step 11. (Inlined AddTimeDuration)
2401 auto beyondDaySpan = roundedTime - daySpan;
2402 MOZ_ASSERT(IsValidTimeDuration(beyondDaySpan));
2403
2404 // Steps 12-13.
2405 bool didRoundBeyondDay;
2406 int32_t dayDelta;
2407 EpochNanoseconds nudgedEpochNs;
2408 if (TimeDurationSign(beyondDaySpan) != -sign) {
2409 // Step 12.a.
2410 didRoundBeyondDay = true;
2411
2412 // Step 12.b.
2413 dayDelta = sign;
2414
2415 // Step 12.c.
2416 //
2417 // This call to RoundTimeDurationToIncrement is also infallible.
2418 roundedTime = RoundTimeDurationToIncrement(beyondDaySpan, unit, increment,
2419 roundingMode);
2420 MOZ_ASSERT(IsValidTimeDuration(roundedTime));
2421
2422 // Step 12.d. (Inlined AddTimeDurationToEpochNanoseconds)
2423 nudgedEpochNs = endEpochNs + roundedTime.to<EpochDuration>();
2424 } else {
2425 // Step 13.a.
2426 didRoundBeyondDay = false;
2427
2428 // Step 13.b.
2429 dayDelta = 0;
2430
2431 // Step 13.c. (Inlined AddTimeDurationToEpochNanoseconds)
2432 nudgedEpochNs = startEpochNs + roundedTime.to<EpochDuration>();
2433 }
2434
2435 // Step 14.
2436 auto dateDuration = DateDuration{
2437 duration.date.years,
2438 duration.date.months,
2439 duration.date.weeks,
2440 duration.date.days + dayDelta,
2441 };
2442 MOZ_ASSERT(IsValidDuration(dateDuration));
2443
2444 // Step 15.
2445 MOZ_ASSERT(DateDurationSign(dateDuration) * TimeDurationSign(roundedTime) >=
2446 0);
2447 auto resultDuration = InternalDuration{dateDuration, roundedTime};
2448
2449 // Step 16.
2450 *result = {
2451 resultDuration,
2452 nudgedEpochNs,
2453 mozilla::UnspecifiedNaN<double>(),
2454 didRoundBeyondDay,
2455 };
2456 return true;
2457 }
2458
2459 /**
2460 * NudgeToDayOrTime ( duration, destEpochNs, largestUnit, increment,
2461 * smallestUnit, roundingMode )
2462 */
2463 static DurationNudge NudgeToDayOrTime(const InternalDuration& duration,
2464 const EpochNanoseconds& destEpochNs,
2465 TemporalUnit largestUnit,
2466 Increment increment,
2467 TemporalUnit smallestUnit,
2468 TemporalRoundingMode roundingMode) {
2469 MOZ_ASSERT(IsValidDuration(duration));
2470 MOZ_ASSERT(IsValidLocalNanoseconds(destEpochNs));
2471 MOZ_ASSERT(smallestUnit >= TemporalUnit::Day);
2472
2473 // Step 1. (Inlined Add24HourDaysToTimeDuration)
2474 auto timeDuration =
2475 duration.time + TimeDuration::fromDays(duration.date.days);
2476 MOZ_ASSERT(IsValidTimeDuration(timeDuration));
2477 MOZ_ASSERT(IsValidTimeFromDateTimeDuration(timeDuration));
2478
2479 // Steps 2-3.
2480 //
2481 // RoundTimeDurationToIncrement is infallible |timeDuration| is a valid
2482 // date-time duration.
2483 auto roundedTime = RoundTimeDurationToIncrement(timeDuration, smallestUnit,
2484 increment, roundingMode);
2485 MOZ_ASSERT(IsValidTimeDuration(roundedTime));
2486
2487 // Step 4. (Inlined AddTimeDuration)
2488 auto diffTime = roundedTime - timeDuration;
2489 MOZ_ASSERT(IsValidTimeDuration(diffTime));
2490
2491 // Step 5.
2492 int64_t wholeDays = timeDuration.toDays();
2493
2494 // Step 6.
2495 int64_t roundedWholeDays = roundedTime.toDays();
2496
2497 // Step 7.
2498 int64_t dayDelta = roundedWholeDays - wholeDays;
2499
2500 // Step 8.
2501 int32_t dayDeltaSign = dayDelta < 0 ? -1 : dayDelta > 0 ? 1 : 0;
2502
2503 // Step 9.
2504 bool didExpandDays = dayDeltaSign == TimeDurationSign(timeDuration);
2505
2506 // Step 10. (Inlined AddTimeDurationToEpochNanoseconds)
2507 auto nudgedEpochNs = destEpochNs + diffTime.to<EpochDuration>();
2508
2509 // Step 11.
2510 int64_t days = 0;
2511
2512 // Step 12.
2513 auto remainder = roundedTime;
2514
2515 // Step 13.
2516 if (largestUnit <= TemporalUnit::Day) {
2517 // Step 13.a.
2518 days = roundedWholeDays;
2519
2520 // Step 13.b.
2521 remainder = roundedTime - TimeDuration::fromDays(roundedWholeDays);
2522 MOZ_ASSERT(IsValidTimeDuration(remainder));
2523 }
2524
2525 // Step 14.
2526 auto dateDuration = DateDuration{
2527 duration.date.years,
2528 duration.date.months,
2529 duration.date.weeks,
2530 days,
2531 };
2532 MOZ_ASSERT(IsValidDuration(dateDuration));
2533
2534 // Step 15.
2535 MOZ_ASSERT(DateDurationSign(dateDuration) * TimeDurationSign(remainder) >= 0);
2536 auto resultDuration = InternalDuration{dateDuration, remainder};
2537
2538 // Step 16.
2539 return {resultDuration, nudgedEpochNs, mozilla::UnspecifiedNaN<double>(),
2540 didExpandDays};
2541 }
2542
2543 /**
2544 * BubbleRelativeDuration ( sign, duration, nudgedEpochNs, isoDateTime,
2545 * timeZone, calendar, largestUnit, smallestUnit )
2546 */
2547 static bool BubbleRelativeDuration(
2548 JSContext* cx, const InternalDuration& duration, const DurationNudge& nudge,
2549 const ISODateTime& isoDateTime, Handle<TimeZoneValue> timeZone,
2550 Handle<CalendarValue> calendar, TemporalUnit largestUnit,
2551 TemporalUnit smallestUnit, InternalDuration* result) {
2552 MOZ_ASSERT(IsValidDuration(duration));
2553 MOZ_ASSERT(IsValidDuration(nudge.duration));
2554 MOZ_ASSERT(ISODateTimeWithinLimits(isoDateTime));
2555 MOZ_ASSERT(largestUnit <= TemporalUnit::Day);
2556 MOZ_ASSERT(smallestUnit <= TemporalUnit::Day);
2557 MOZ_ASSERT(largestUnit <= smallestUnit);
2558
2559 int32_t sign = InternalDurationSign(duration) < 0 ? -1 : 1;
2560
2561 // Step 1.
2562 if (smallestUnit == largestUnit) {
2563 *result = nudge.duration;
2564 return true;
2565 }
2566 MOZ_ASSERT(smallestUnit != TemporalUnit::Year);
2567
2568 // Steps 2-6.
2569 auto dateDuration = nudge.duration.date;
2570 auto timeDuration = nudge.duration.time;
2571 auto unit = smallestUnit;
2572 while (unit > largestUnit) {
2573 using TemporalUnitType = std::underlying_type_t<TemporalUnit>;
2574
2575 static_assert(static_cast<TemporalUnitType>(TemporalUnit::Auto) == 0,
2576 "TemporalUnit::Auto has value zero");
2577 MOZ_ASSERT(unit > TemporalUnit::Auto, "can subtract unit by one");
2578
2579 // Steps 4, 6.a, and 6.c.
2580 unit = static_cast<TemporalUnit>(static_cast<TemporalUnitType>(unit) - 1);
2581 MOZ_ASSERT(TemporalUnit::Year <= unit && unit <= TemporalUnit::Week);
2582
2583 // Step 6.b.
2584 if (unit != TemporalUnit::Week || largestUnit == TemporalUnit::Week) {
2585 // Steps 6.b.i-iii.
2586 DateDuration endDuration;
2587 if (unit == TemporalUnit::Year) {
2588 // Step 6.b.i.1.
2589 int64_t years = dateDuration.years + sign;
2590
2591 // Step 6.b.i.2.
2592 endDuration = {years};
2593 } else if (unit == TemporalUnit::Month) {
2594 // Step 6.b.ii.1.
2595 int64_t months = dateDuration.months + sign;
2596
2597 // Step 6.b.ii.2.
2598 endDuration = {dateDuration.years, months};
2599 } else {
2600 // Step 6.b.iii.1.
2601 MOZ_ASSERT(unit == TemporalUnit::Week);
2602
2603 // Step 6.b.iii.2.
2604 int64_t weeks = dateDuration.weeks + sign;
2605
2606 // Step 6.b.iii.3.
2607 endDuration = {dateDuration.years, dateDuration.months, weeks};
2608 }
2609 MOZ_ASSERT(IsValidDuration(endDuration));
2610
2611 // Steps 6.b.iv.
2612 ISODate end;
2613 if (!CalendarDateAdd(cx, calendar, isoDateTime.date, endDuration,
2614 TemporalOverflow::Constrain, &end)) {
2615 return false;
2616 }
2617
2618 // Steps 6.b.v.
2619 auto endDateTime = ISODateTime{end, isoDateTime.time};
2620 MOZ_ASSERT(ISODateTimeWithinLimits(endDateTime));
2621
2622 // Steps 6.b.vi-vii.
2623 EpochNanoseconds endEpochNs;
2624 if (!timeZone) {
2625 endEpochNs = GetUTCEpochNanoseconds(endDateTime);
2626 } else {
2627 if (!GetEpochNanosecondsFor(cx, timeZone, endDateTime,
2628 TemporalDisambiguation::Compatible,
2629 &endEpochNs)) {
2630 return false;
2631 }
2632 }
2633
2634 // Step 6.b.viii.
2635 //
2636 // NB: |nudge.epochNs| can be outside the valid epoch nanoseconds limits.
2637 auto beyondEnd = nudge.epochNs - endEpochNs;
2638
2639 // Step 6.b.ix.
2640 int32_t beyondEndSign = beyondEnd < EpochDuration{} ? -1
2641 : beyondEnd > EpochDuration{} ? 1
2642 : 0;
2643
2644 // Steps 6.b.x-xi.
2645 if (beyondEndSign != -sign) {
2646 dateDuration = endDuration;
2647 timeDuration = {};
2648 } else {
2649 break;
2650 }
2651 }
2652
2653 // Step 6.c. (Moved above)
2654 }
2655
2656 // Step 7.
2657 *result = {dateDuration, timeDuration};
2658 return true;
2659 }
2660
2661 /**
2662 * RoundRelativeDuration ( duration, destEpochNs, isoDateTime, timeZone,
2663 * calendar, largestUnit, increment, smallestUnit, roundingMode )
2664 */
2665 bool js::temporal::RoundRelativeDuration(
2666 JSContext* cx, const InternalDuration& duration,
2667 const EpochNanoseconds& destEpochNs, const ISODateTime& isoDateTime,
2668 Handle<TimeZoneValue> timeZone, Handle<CalendarValue> calendar,
2669 TemporalUnit largestUnit, Increment increment, TemporalUnit smallestUnit,
2670 TemporalRoundingMode roundingMode, InternalDuration* result) {
2671 MOZ_ASSERT(IsValidDuration(duration));
2672 MOZ_ASSERT_IF(timeZone, IsValidEpochNanoseconds(destEpochNs));
2673 MOZ_ASSERT_IF(!timeZone, IsValidLocalNanoseconds(destEpochNs));
2674 MOZ_ASSERT(ISODateTimeWithinLimits(isoDateTime));
2675 MOZ_ASSERT(largestUnit <= smallestUnit);
2676
2677 // Steps 1-3.
2678 bool irregularLengthUnit = (smallestUnit < TemporalUnit::Day) ||
2679 (timeZone && smallestUnit == TemporalUnit::Day);
2680
2681 // Step 4. (Not applicable in our implementation.)
2682
2683 // Steps 5-7.
2684 DurationNudge nudge;
2685 if (irregularLengthUnit) {
2686 // Step 5.a.
2687 if (!NudgeToCalendarUnit(cx, duration, destEpochNs, isoDateTime, timeZone,
2688 calendar, increment, smallestUnit, roundingMode,
2689 &nudge)) {
2690 return false;
2691 }
2692 } else if (timeZone) {
2693 // Step 6.a.
2694 if (!NudgeToZonedTime(cx, duration, isoDateTime, timeZone, calendar,
2695 increment, smallestUnit, roundingMode, &nudge)) {
2696 return false;
2697 }
2698 } else {
2699 // Step 7.a.
2700 nudge = NudgeToDayOrTime(duration, destEpochNs, largestUnit, increment,
2701 smallestUnit, roundingMode);
2702 }
2703
2704 // Step 8.
2705 auto nudgedDuration = nudge.duration;
2706
2707 // Step 9.
2708 if (nudge.didExpandCalendarUnit && smallestUnit != TemporalUnit::Week) {
2709 // Step 9.a. (Inlined LargerOfTwoTemporalUnits)
2710 auto startUnit = std::min(smallestUnit, TemporalUnit::Day);
2711
2712 // Step 9.b.
2713 if (!BubbleRelativeDuration(cx, duration, nudge, isoDateTime, timeZone,
2714 calendar, largestUnit, startUnit,
2715 &nudgedDuration)) {
2716 return false;
2717 }
2718 }
2719
2720 // Step 10.
2721 *result = nudgedDuration;
2722 return true;
2723 }
2724
2725 /**
2726 * TotalRelativeDuration ( duration, destEpochNs, isoDateTime, timeZone,
2727 * calendar, unit )
2728 */
2729 bool js::temporal::TotalRelativeDuration(JSContext* cx,
2730 const InternalDuration& duration,
2731 const EpochNanoseconds& destEpochNs,
2732 const ISODateTime& isoDateTime,
2733 JS::Handle<TimeZoneValue> timeZone,
2734 JS::Handle<CalendarValue> calendar,
2735 TemporalUnit unit, double* result) {
2736 MOZ_ASSERT(IsValidDuration(duration));
2737 MOZ_ASSERT_IF(timeZone, IsValidEpochNanoseconds(destEpochNs));
2738 MOZ_ASSERT_IF(!timeZone, IsValidLocalNanoseconds(destEpochNs));
2739 MOZ_ASSERT(ISODateTimeWithinLimits(isoDateTime));
2740 MOZ_ASSERT(unit <= TemporalUnit::Day);
2741 MOZ_ASSERT_IF(unit == TemporalUnit::Day, timeZone);
2742
2743 // Steps 1.a-b.
2744 DurationNudge nudge;
2745 if (!NudgeToCalendarUnit(cx, duration, destEpochNs, isoDateTime, timeZone,
2746 calendar, Increment{1}, unit,
2747 TemporalRoundingMode::Trunc, &nudge)) {
2748 return false;
2749 }
2750
2751 // Step 1.c.
2752 *result = nudge.total;
2753 return true;
2754 }
2755
2756 /**
2757 * AddDurations ( operation, duration, other )
2758 */
2759 static bool AddDurations(JSContext* cx, TemporalAddDuration operation,
2760 const CallArgs& args) {
2761 auto* durationObj = &args.thisv().toObject().as<DurationObject>();
2762 auto duration = ToDuration(durationObj);
2763
2764 // Step 1.
2765 Duration other;
2766 if (!ToTemporalDuration(cx, args.get(0), &other)) {
2767 return false;
2768 }
2769
2770 // Step 2.
2771 if (operation == TemporalAddDuration::Subtract) {
2772 other = other.negate();
2773 }
2774
2775 // Step 3.
2776 auto largestUnit1 = DefaultTemporalLargestUnit(duration);
2777
2778 // Step 4.
2779 auto largestUnit2 = DefaultTemporalLargestUnit(other);
2780
2781 // Step 5.
2782 auto largestUnit = std::min(largestUnit1, largestUnit2);
2783
2784 // Step 6.
2785 if (largestUnit <= TemporalUnit::Week) {
2786 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
2787 JSMSG_TEMPORAL_DURATION_UNCOMPARABLE,
2788 "relativeTo");
2789 return false;
2790 }
2791
2792 // Step 7.
2793 auto d1 = ToInternalDurationRecordWith24HourDays(duration).time;
2794
2795 // Step 8.
2796 auto d2 = ToInternalDurationRecordWith24HourDays(other).time;
2797
2798 // Step 9. (Inline AddTimeDuration)
2799 auto timeResult = d1 + d2;
2800 if (!IsValidTimeDuration(timeResult)) {
2801 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
2802 JSMSG_TEMPORAL_DURATION_INVALID_NORMALIZED_TIME);
2803 return false;
2804 }
2805
2806 // Steps 10-11.
2807 Duration resultDuration;
2808 if (!TemporalDurationFromInternal(cx, timeResult, largestUnit,
2809 &resultDuration)) {
2810 return false;
2811 }
2812 MOZ_ASSERT(IsValidDuration(resultDuration));
2813
2814 auto* obj = CreateTemporalDuration(cx, resultDuration);
2815 if (!obj) {
2816 return false;
2817 }
2818
2819 args.rval().setObject(*obj);
2820 return true;
2821 }
2822
2823 /**
2824 * Temporal.Duration ( [ years [ , months [ , weeks [ , days [ , hours [ ,
2825 * minutes [ , seconds [ , milliseconds [ , microseconds [ , nanoseconds ] ] ] ]
2826 * ] ] ] ] ] ] )
2827 */
2828 static bool DurationConstructor(JSContext* cx, unsigned argc, Value* vp) {
2829 CallArgs args = CallArgsFromVp(argc, vp);
2830
2831 // Step 1.
2832 if (!ThrowIfNotConstructing(cx, args, "Temporal.Duration")) {
2833 return false;
2834 }
2835
2836 // Step 2.
2837 double years = 0;
2838 if (args.hasDefined(0) &&
2839 !ToIntegerIfIntegral(cx, "years", args[0], &years)) {
2840 return false;
2841 }
2842
2843 // Step 3.
2844 double months = 0;
2845 if (args.hasDefined(1) &&
2846 !ToIntegerIfIntegral(cx, "months", args[1], &months)) {
2847 return false;
2848 }
2849
2850 // Step 4.
2851 double weeks = 0;
2852 if (args.hasDefined(2) &&
2853 !ToIntegerIfIntegral(cx, "weeks", args[2], &weeks)) {
2854 return false;
2855 }
2856
2857 // Step 5.
2858 double days = 0;
2859 if (args.hasDefined(3) && !ToIntegerIfIntegral(cx, "days", args[3], &days)) {
2860 return false;
2861 }
2862
2863 // Step 6.
2864 double hours = 0;
2865 if (args.hasDefined(4) &&
2866 !ToIntegerIfIntegral(cx, "hours", args[4], &hours)) {
2867 return false;
2868 }
2869
2870 // Step 7.
2871 double minutes = 0;
2872 if (args.hasDefined(5) &&
2873 !ToIntegerIfIntegral(cx, "minutes", args[5], &minutes)) {
2874 return false;
2875 }
2876
2877 // Step 8.
2878 double seconds = 0;
2879 if (args.hasDefined(6) &&
2880 !ToIntegerIfIntegral(cx, "seconds", args[6], &seconds)) {
2881 return false;
2882 }
2883
2884 // Step 9.
2885 double milliseconds = 0;
2886 if (args.hasDefined(7) &&
2887 !ToIntegerIfIntegral(cx, "milliseconds", args[7], &milliseconds)) {
2888 return false;
2889 }
2890
2891 // Step 10.
2892 double microseconds = 0;
2893 if (args.hasDefined(8) &&
2894 !ToIntegerIfIntegral(cx, "microseconds", args[8], &microseconds)) {
2895 return false;
2896 }
2897
2898 // Step 11.
2899 double nanoseconds = 0;
2900 if (args.hasDefined(9) &&
2901 !ToIntegerIfIntegral(cx, "nanoseconds", args[9], &nanoseconds)) {
2902 return false;
2903 }
2904
2905 // Step 12.
2906 auto* duration = CreateTemporalDuration(
2907 cx, args,
2908 {years, months, weeks, days, hours, minutes, seconds, milliseconds,
2909 microseconds, nanoseconds});
2910 if (!duration) {
2911 return false;
2912 }
2913
2914 args.rval().setObject(*duration);
2915 return true;
2916 }
2917
2918 /**
2919 * Temporal.Duration.from ( item )
2920 */
2921 static bool Duration_from(JSContext* cx, unsigned argc, Value* vp) {
2922 CallArgs args = CallArgsFromVp(argc, vp);
2923
2924 // Step 1.
2925 Duration result;
2926 if (!ToTemporalDuration(cx, args.get(0), &result)) {
2927 return false;
2928 }
2929
2930 auto* obj = CreateTemporalDuration(cx, result);
2931 if (!obj) {
2932 return false;
2933 }
2934
2935 args.rval().setObject(*obj);
2936 return true;
2937 }
2938
2939 /**
2940 * Temporal.Duration.compare ( one, two [ , options ] )
2941 */
2942 static bool Duration_compare(JSContext* cx, unsigned argc, Value* vp) {
2943 CallArgs args = CallArgsFromVp(argc, vp);
2944
2945 // Step 1.
2946 Duration one;
2947 if (!ToTemporalDuration(cx, args.get(0), &one)) {
2948 return false;
2949 }
2950
2951 // Step 2.
2952 Duration two;
2953 if (!ToTemporalDuration(cx, args.get(1), &two)) {
2954 return false;
2955 }
2956
2957 // Steps 3-4.
2958 Rooted<PlainDate> plainRelativeTo(cx);
2959 Rooted<ZonedDateTime> zonedRelativeTo(cx);
2960 if (args.hasDefined(2)) {
2961 // Step 3.
2962 Rooted<JSObject*> options(
2963 cx, RequireObjectArg(cx, "options", "compare", args[2]));
2964 if (!options) {
2965 return false;
2966 }
2967
2968 // Step 4.
2969 if (!GetTemporalRelativeToOption(cx, options, &plainRelativeTo,
2970 &zonedRelativeTo)) {
2971 return false;
2972 }
2973 MOZ_ASSERT(!plainRelativeTo || !zonedRelativeTo);
2974 }
2975
2976 // Step 5.
2977 if (one == two) {
2978 args.rval().setInt32(0);
2979 return true;
2980 }
2981
2982 // Steps 6-9. (Not applicable in our implementation.)
2983
2984 // Step 10.
2985 auto duration1 = ToInternalDurationRecord(one);
2986
2987 // Step 11.
2988 auto duration2 = ToInternalDurationRecord(two);
2989
2990 // Step 12.
2991 if (zonedRelativeTo &&
2992 (duration1.date != DateDuration{} || duration2.date != DateDuration{})) {
2993 // Steps 12.a-b. (Not applicable in our implementation.)
2994
2995 // Step 12.c.
2996 EpochNanoseconds after1;
2997 if (!AddZonedDateTime(cx, zonedRelativeTo, duration1, &after1)) {
2998 return false;
2999 }
3000
3001 // Step 12.d.
3002 EpochNanoseconds after2;
3003 if (!AddZonedDateTime(cx, zonedRelativeTo, duration2, &after2)) {
3004 return false;
3005 }
3006
3007 // Steps 12.e-g.
3008 args.rval().setInt32(after1 < after2 ? -1 : after1 > after2 ? 1 : 0);
3009 return true;
3010 }
3011
3012 // Steps 13.a-b and 14.a.
3013 int64_t days1;
3014 if (!DateDurationDays(cx, duration1.date, plainRelativeTo, &days1)) {
3015 return false;
3016 }
3017
3018 // Steps 13.a, 13.c, and 14.b.
3019 int64_t days2;
3020 if (!DateDurationDays(cx, duration2.date, plainRelativeTo, &days2)) {
3021 return false;
3022 }
3023
3024 // Step 15.
3025 auto timeDuration1 = duration1.time;
3026 if (!Add24HourDaysToTimeDuration(cx, duration1.time, days1, &timeDuration1)) {
3027 return false;
3028 }
3029
3030 // Step 16.
3031 auto timeDuration2 = duration2.time;
3032 if (!Add24HourDaysToTimeDuration(cx, duration2.time, days2, &timeDuration2)) {
3033 return false;
3034 }
3035
3036 // Step 17.
3037 args.rval().setInt32(CompareTimeDuration(timeDuration1, timeDuration2));
3038 return true;
3039 }
3040
3041 /**
3042 * get Temporal.Duration.prototype.years
3043 */
3044 static bool Duration_years(JSContext* cx, const CallArgs& args) {
3045 // Step 3.
3046 auto* duration = &args.thisv().toObject().as<DurationObject>();
3047 args.rval().setNumber(duration->years());
3048 return true;
3049 }
3050
3051 /**
3052 * get Temporal.Duration.prototype.years
3053 */
3054 static bool Duration_years(JSContext* cx, unsigned argc, Value* vp) {
3055 // Steps 1-2.
3056 CallArgs args = CallArgsFromVp(argc, vp);
3057 return CallNonGenericMethod<IsDuration, Duration_years>(cx, args);
3058 }
3059
3060 /**
3061 * get Temporal.Duration.prototype.months
3062 */
3063 static bool Duration_months(JSContext* cx, const CallArgs& args) {
3064 // Step 3.
3065 auto* duration = &args.thisv().toObject().as<DurationObject>();
3066 args.rval().setNumber(duration->months());
3067 return true;
3068 }
3069
3070 /**
3071 * get Temporal.Duration.prototype.months
3072 */
3073 static bool Duration_months(JSContext* cx, unsigned argc, Value* vp) {
3074 // Steps 1-2.
3075 CallArgs args = CallArgsFromVp(argc, vp);
3076 return CallNonGenericMethod<IsDuration, Duration_months>(cx, args);
3077 }
3078
3079 /**
3080 * get Temporal.Duration.prototype.weeks
3081 */
3082 static bool Duration_weeks(JSContext* cx, const CallArgs& args) {
3083 // Step 3.
3084 auto* duration = &args.thisv().toObject().as<DurationObject>();
3085 args.rval().setNumber(duration->weeks());
3086 return true;
3087 }
3088
3089 /**
3090 * get Temporal.Duration.prototype.weeks
3091 */
3092 static bool Duration_weeks(JSContext* cx, unsigned argc, Value* vp) {
3093 // Steps 1-2.
3094 CallArgs args = CallArgsFromVp(argc, vp);
3095 return CallNonGenericMethod<IsDuration, Duration_weeks>(cx, args);
3096 }
3097
3098 /**
3099 * get Temporal.Duration.prototype.days
3100 */
3101 static bool Duration_days(JSContext* cx, const CallArgs& args) {
3102 // Step 3.
3103 auto* duration = &args.thisv().toObject().as<DurationObject>();
3104 args.rval().setNumber(duration->days());
3105 return true;
3106 }
3107
3108 /**
3109 * get Temporal.Duration.prototype.days
3110 */
3111 static bool Duration_days(JSContext* cx, unsigned argc, Value* vp) {
3112 // Steps 1-2.
3113 CallArgs args = CallArgsFromVp(argc, vp);
3114 return CallNonGenericMethod<IsDuration, Duration_days>(cx, args);
3115 }
3116
3117 /**
3118 * get Temporal.Duration.prototype.hours
3119 */
3120 static bool Duration_hours(JSContext* cx, const CallArgs& args) {
3121 // Step 3.
3122 auto* duration = &args.thisv().toObject().as<DurationObject>();
3123 args.rval().setNumber(duration->hours());
3124 return true;
3125 }
3126
3127 /**
3128 * get Temporal.Duration.prototype.hours
3129 */
3130 static bool Duration_hours(JSContext* cx, unsigned argc, Value* vp) {
3131 // Steps 1-2.
3132 CallArgs args = CallArgsFromVp(argc, vp);
3133 return CallNonGenericMethod<IsDuration, Duration_hours>(cx, args);
3134 }
3135
3136 /**
3137 * get Temporal.Duration.prototype.minutes
3138 */
3139 static bool Duration_minutes(JSContext* cx, const CallArgs& args) {
3140 // Step 3.
3141 auto* duration = &args.thisv().toObject().as<DurationObject>();
3142 args.rval().setNumber(duration->minutes());
3143 return true;
3144 }
3145
3146 /**
3147 * get Temporal.Duration.prototype.minutes
3148 */
3149 static bool Duration_minutes(JSContext* cx, unsigned argc, Value* vp) {
3150 // Steps 1-2.
3151 CallArgs args = CallArgsFromVp(argc, vp);
3152 return CallNonGenericMethod<IsDuration, Duration_minutes>(cx, args);
3153 }
3154
3155 /**
3156 * get Temporal.Duration.prototype.seconds
3157 */
3158 static bool Duration_seconds(JSContext* cx, const CallArgs& args) {
3159 // Step 3.
3160 auto* duration = &args.thisv().toObject().as<DurationObject>();
3161 args.rval().setNumber(duration->seconds());
3162 return true;
3163 }
3164
3165 /**
3166 * get Temporal.Duration.prototype.seconds
3167 */
3168 static bool Duration_seconds(JSContext* cx, unsigned argc, Value* vp) {
3169 // Steps 1-2.
3170 CallArgs args = CallArgsFromVp(argc, vp);
3171 return CallNonGenericMethod<IsDuration, Duration_seconds>(cx, args);
3172 }
3173
3174 /**
3175 * get Temporal.Duration.prototype.milliseconds
3176 */
3177 static bool Duration_milliseconds(JSContext* cx, const CallArgs& args) {
3178 // Step 3.
3179 auto* duration = &args.thisv().toObject().as<DurationObject>();
3180 args.rval().setNumber(duration->milliseconds());
3181 return true;
3182 }
3183
3184 /**
3185 * get Temporal.Duration.prototype.milliseconds
3186 */
3187 static bool Duration_milliseconds(JSContext* cx, unsigned argc, Value* vp) {
3188 // Steps 1-2.
3189 CallArgs args = CallArgsFromVp(argc, vp);
3190 return CallNonGenericMethod<IsDuration, Duration_milliseconds>(cx, args);
3191 }
3192
3193 /**
3194 * get Temporal.Duration.prototype.microseconds
3195 */
3196 static bool Duration_microseconds(JSContext* cx, const CallArgs& args) {
3197 // Step 3.
3198 auto* duration = &args.thisv().toObject().as<DurationObject>();
3199 args.rval().setNumber(duration->microseconds());
3200 return true;
3201 }
3202
3203 /**
3204 * get Temporal.Duration.prototype.microseconds
3205 */
3206 static bool Duration_microseconds(JSContext* cx, unsigned argc, Value* vp) {
3207 // Steps 1-2.
3208 CallArgs args = CallArgsFromVp(argc, vp);
3209 return CallNonGenericMethod<IsDuration, Duration_microseconds>(cx, args);
3210 }
3211
3212 /**
3213 * get Temporal.Duration.prototype.nanoseconds
3214 */
3215 static bool Duration_nanoseconds(JSContext* cx, const CallArgs& args) {
3216 // Step 3.
3217 auto* duration = &args.thisv().toObject().as<DurationObject>();
3218 args.rval().setNumber(duration->nanoseconds());
3219 return true;
3220 }
3221
3222 /**
3223 * get Temporal.Duration.prototype.nanoseconds
3224 */
3225 static bool Duration_nanoseconds(JSContext* cx, unsigned argc, Value* vp) {
3226 // Steps 1-2.
3227 CallArgs args = CallArgsFromVp(argc, vp);
3228 return CallNonGenericMethod<IsDuration, Duration_nanoseconds>(cx, args);
3229 }
3230
3231 /**
3232 * get Temporal.Duration.prototype.sign
3233 */
3234 static bool Duration_sign(JSContext* cx, const CallArgs& args) {
3235 auto duration = ToDuration(&args.thisv().toObject().as<DurationObject>());
3236
3237 // Step 3.
3238 args.rval().setInt32(DurationSign(duration));
3239 return true;
3240 }
3241
3242 /**
3243 * get Temporal.Duration.prototype.sign
3244 */
3245 static bool Duration_sign(JSContext* cx, unsigned argc, Value* vp) {
3246 // Steps 1-2.
3247 CallArgs args = CallArgsFromVp(argc, vp);
3248 return CallNonGenericMethod<IsDuration, Duration_sign>(cx, args);
3249 }
3250
3251 /**
3252 * get Temporal.Duration.prototype.blank
3253 */
3254 static bool Duration_blank(JSContext* cx, const CallArgs& args) {
3255 auto duration = ToDuration(&args.thisv().toObject().as<DurationObject>());
3256
3257 // Steps 3-4.
3258 args.rval().setBoolean(duration == Duration{});
3259 return true;
3260 }
3261
3262 /**
3263 * get Temporal.Duration.prototype.blank
3264 */
3265 static bool Duration_blank(JSContext* cx, unsigned argc, Value* vp) {
3266 // Steps 1-2.
3267 CallArgs args = CallArgsFromVp(argc, vp);
3268 return CallNonGenericMethod<IsDuration, Duration_blank>(cx, args);
3269 }
3270
3271 /**
3272 * Temporal.Duration.prototype.with ( temporalDurationLike )
3273 */
3274 static bool Duration_with(JSContext* cx, const CallArgs& args) {
3275 // Absent values default to the corresponding values of |this| object.
3276 auto duration = ToDuration(&args.thisv().toObject().as<DurationObject>());
3277
3278 // Steps 3-23.
3279 Rooted<JSObject*> temporalDurationLike(
3280 cx, RequireObjectArg(cx, "temporalDurationLike", "with", args.get(0)));
3281 if (!temporalDurationLike) {
3282 return false;
3283 }
3284 if (!ToTemporalPartialDurationRecord(cx, temporalDurationLike, &duration)) {
3285 return false;
3286 }
3287
3288 // Step 24.
3289 auto* result = CreateTemporalDuration(cx, duration);
3290 if (!result) {
3291 return false;
3292 }
3293
3294 args.rval().setObject(*result);
3295 return true;
3296 }
3297
3298 /**
3299 * Temporal.Duration.prototype.with ( temporalDurationLike )
3300 */
3301 static bool Duration_with(JSContext* cx, unsigned argc, Value* vp) {
3302 // Steps 1-2.
3303 CallArgs args = CallArgsFromVp(argc, vp);
3304 return CallNonGenericMethod<IsDuration, Duration_with>(cx, args);
3305 }
3306
3307 /**
3308 * Temporal.Duration.prototype.negated ( )
3309 */
3310 static bool Duration_negated(JSContext* cx, const CallArgs& args) {
3311 auto duration = ToDuration(&args.thisv().toObject().as<DurationObject>());
3312
3313 // Step 3.
3314 auto* result = CreateTemporalDuration(cx, duration.negate());
3315 if (!result) {
3316 return false;
3317 }
3318
3319 args.rval().setObject(*result);
3320 return true;
3321 }
3322
3323 /**
3324 * Temporal.Duration.prototype.negated ( )
3325 */
3326 static bool Duration_negated(JSContext* cx, unsigned argc, Value* vp) {
3327 // Steps 1-2.
3328 CallArgs args = CallArgsFromVp(argc, vp);
3329 return CallNonGenericMethod<IsDuration, Duration_negated>(cx, args);
3330 }
3331
3332 /**
3333 * Temporal.Duration.prototype.abs ( )
3334 */
3335 static bool Duration_abs(JSContext* cx, const CallArgs& args) {
3336 auto duration = ToDuration(&args.thisv().toObject().as<DurationObject>());
3337
3338 // Step 3.
3339 auto* result = CreateTemporalDuration(cx, AbsoluteDuration(duration));
3340 if (!result) {
3341 return false;
3342 }
3343
3344 args.rval().setObject(*result);
3345 return true;
3346 }
3347
3348 /**
3349 * Temporal.Duration.prototype.abs ( )
3350 */
3351 static bool Duration_abs(JSContext* cx, unsigned argc, Value* vp) {
3352 // Steps 1-2.
3353 CallArgs args = CallArgsFromVp(argc, vp);
3354 return CallNonGenericMethod<IsDuration, Duration_abs>(cx, args);
3355 }
3356
3357 /**
3358 * Temporal.Duration.prototype.add ( other )
3359 */
3360 static bool Duration_add(JSContext* cx, const CallArgs& args) {
3361 // Step 3.
3362 return AddDurations(cx, TemporalAddDuration::Add, args);
3363 }
3364
3365 /**
3366 * Temporal.Duration.prototype.add ( other )
3367 */
3368 static bool Duration_add(JSContext* cx, unsigned argc, Value* vp) {
3369 // Steps 1-2.
3370 CallArgs args = CallArgsFromVp(argc, vp);
3371 return CallNonGenericMethod<IsDuration, Duration_add>(cx, args);
3372 }
3373
3374 /**
3375 * Temporal.Duration.prototype.subtract ( other )
3376 */
3377 static bool Duration_subtract(JSContext* cx, const CallArgs& args) {
3378 // Step 3.
3379 return AddDurations(cx, TemporalAddDuration::Subtract, args);
3380 }
3381
3382 /**
3383 * Temporal.Duration.prototype.subtract ( other )
3384 */
3385 static bool Duration_subtract(JSContext* cx, unsigned argc, Value* vp) {
3386 // Steps 1-2.
3387 CallArgs args = CallArgsFromVp(argc, vp);
3388 return CallNonGenericMethod<IsDuration, Duration_subtract>(cx, args);
3389 }
3390
3391 /**
3392 * Temporal.Duration.prototype.round ( roundTo )
3393 */
3394 static bool Duration_round(JSContext* cx, const CallArgs& args) {
3395 auto duration = ToDuration(&args.thisv().toObject().as<DurationObject>());
3396
3397 // Step 17. (Reordered)
3398 auto existingLargestUnit = DefaultTemporalLargestUnit(duration);
3399
3400 // Steps 3-25.
3401 auto smallestUnit = TemporalUnit::Auto;
3402 TemporalUnit largestUnit;
3403 auto roundingMode = TemporalRoundingMode::HalfExpand;
3404 auto roundingIncrement = Increment{1};
3405 Rooted<PlainDate> plainRelativeTo(cx);
3406 Rooted<ZonedDateTime> zonedRelativeTo(cx);
3407 if (args.get(0).isString()) {
3408 // Step 4. (Not applicable in our implementation.)
3409
3410 // Steps 6-14. (Not applicable)
3411
3412 // Step 15.
3413 Rooted<JSString*> paramString(cx, args[0].toString());
3414 if (!GetTemporalUnitValuedOption(
3415 cx, paramString, TemporalUnitKey::SmallestUnit,
3416 TemporalUnitGroup::DateTime, &smallestUnit)) {
3417 return false;
3418 }
3419
3420 // Step 16. (Not applicable)
3421
3422 // Step 17. (Moved above)
3423
3424 // Step 18.
3425 auto defaultLargestUnit = std::min(existingLargestUnit, smallestUnit);
3426
3427 // Step 19. (Not applicable)
3428
3429 // Step 19.a. (Not applicable)
3430
3431 // Step 19.b.
3432 largestUnit = defaultLargestUnit;
3433
3434 // Steps 20-25. (Not applicable)
3435 } else {
3436 // Steps 3 and 5.
3437 Rooted<JSObject*> options(
3438 cx, RequireObjectArg(cx, "roundTo", "round", args.get(0)));
3439 if (!options) {
3440 return false;
3441 }
3442
3443 // Step 6.
3444 bool smallestUnitPresent = true;
3445
3446 // Step 7.
3447 bool largestUnitPresent = true;
3448
3449 // Steps 8-9.
3450 //
3451 // Inlined GetTemporalUnitValuedOption and GetOption so we can more easily
3452 // detect an absent "largestUnit" value.
3453 Rooted<Value> largestUnitValue(cx);
3454 if (!GetProperty(cx, options, options, cx->names().largestUnit,
3455 &largestUnitValue)) {
3456 return false;
3457 }
3458
3459 if (!largestUnitValue.isUndefined()) {
3460 Rooted<JSString*> largestUnitStr(cx, JS::ToString(cx, largestUnitValue));
3461 if (!largestUnitStr) {
3462 return false;
3463 }
3464
3465 largestUnit = TemporalUnit::Auto;
3466 if (!GetTemporalUnitValuedOption(
3467 cx, largestUnitStr, TemporalUnitKey::LargestUnit,
3468 TemporalUnitGroup::DateTime, &largestUnit)) {
3469 return false;
3470 }
3471 }
3472
3473 // Steps 10-12.
3474 if (!GetTemporalRelativeToOption(cx, options, &plainRelativeTo,
3475 &zonedRelativeTo)) {
3476 return false;
3477 }
3478 MOZ_ASSERT(!plainRelativeTo || !zonedRelativeTo);
3479
3480 // Step 13.
3481 if (!GetRoundingIncrementOption(cx, options, &roundingIncrement)) {
3482 return false;
3483 }
3484
3485 // Step 14.
3486 if (!GetRoundingModeOption(cx, options, &roundingMode)) {
3487 return false;
3488 }
3489
3490 // Step 15.
3491 if (!GetTemporalUnitValuedOption(cx, options, TemporalUnitKey::SmallestUnit,
3492 TemporalUnitGroup::DateTime,
3493 &smallestUnit)) {
3494 return false;
3495 }
3496
3497 // Step 16.
3498 if (smallestUnit == TemporalUnit::Auto) {
3499 // Step 16.a.
3500 smallestUnitPresent = false;
3501
3502 // Step 16.b.
3503 smallestUnit = TemporalUnit::Nanosecond;
3504 }
3505
3506 // Step 17. (Moved above)
3507
3508 // Step 18.
3509 auto defaultLargestUnit = std::min(existingLargestUnit, smallestUnit);
3510
3511 // Steps 19-20.
3512 if (largestUnitValue.isUndefined()) {
3513 // Step 19.a.
3514 largestUnitPresent = false;
3515
3516 // Step 19.b.
3517 largestUnit = defaultLargestUnit;
3518 } else if (largestUnit == TemporalUnit::Auto) {
3519 // Step 20.a
3520 largestUnit = defaultLargestUnit;
3521 }
3522
3523 // Step 21.
3524 if (!smallestUnitPresent && !largestUnitPresent) {
3525 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
3526 JSMSG_TEMPORAL_DURATION_MISSING_UNIT_SPECIFIER);
3527 return false;
3528 }
3529
3530 // Step 22.
3531 if (largestUnit > smallestUnit) {
3532 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
3533 JSMSG_TEMPORAL_INVALID_UNIT_RANGE);
3534 return false;
3535 }
3536
3537 // Steps 23-24.
3538 if (smallestUnit > TemporalUnit::Day) {
3539 // Step 23.
3540 auto maximum = MaximumTemporalDurationRoundingIncrement(smallestUnit);
3541
3542 // Step 24.
3543 if (!ValidateTemporalRoundingIncrement(cx, roundingIncrement, maximum,
3544 false)) {
3545 return false;
3546 }
3547 }
3548
3549 // Step 25.
3550 if (roundingIncrement > Increment{1} && largestUnit != smallestUnit &&
3551 smallestUnit <= TemporalUnit::Day) {
3552 Int32ToCStringBuf cbuf;
3553 const char* numStr =
3554 Int32ToCString(&cbuf, int32_t(roundingIncrement.value()));
3555
3556 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
3557 JSMSG_INVALID_OPTION_VALUE, "roundingIncrement",
3558 numStr);
3559 return false;
3560 }
3561 }
3562
3563 // Step 26.
3564 if (zonedRelativeTo) {
3565 // Step 26.a.
3566 auto internalDuration = ToInternalDurationRecord(duration);
3567
3568 // Steps 26.b-d. (Not applicable in our implementation.)
3569
3570 // Step 26.e.
3571 EpochNanoseconds targetEpochNs;
3572 if (!AddZonedDateTime(cx, zonedRelativeTo, internalDuration,
3573 &targetEpochNs)) {
3574 return false;
3575 }
3576
3577 // Step 26.f.
3578 if (!DifferenceZonedDateTimeWithRounding(cx, zonedRelativeTo, targetEpochNs,
3579 {
3580 smallestUnit,
3581 largestUnit,
3582 roundingMode,
3583 roundingIncrement,
3584 },
3585 &internalDuration)) {
3586 return false;
3587 }
3588
3589 // Step 26.g.
3590 largestUnit = std::max(largestUnit, TemporalUnit::Hour);
3591
3592 // Step 26.h
3593 Duration result;
3594 if (!TemporalDurationFromInternal(cx, internalDuration, largestUnit,
3595 &result)) {
3596 return false;
3597 }
3598
3599 auto* obj = CreateTemporalDuration(cx, result);
3600 if (!obj) {
3601 return false;
3602 }
3603
3604 args.rval().setObject(*obj);
3605 return true;
3606 }
3607
3608 // Step 27.
3609 if (plainRelativeTo) {
3610 // Step 27.a.
3611 auto internalDuration = ToInternalDurationRecordWith24HourDays(duration);
3612
3613 // Step 27.b.
3614 auto targetTime = AddTime(Time{}, internalDuration.time);
3615
3616 // Step 27.c.
3617 auto calendar = plainRelativeTo.calendar();
3618
3619 // Step 27.d.
3620 auto dateDuration = DateDuration{
3621 internalDuration.date.years,
3622 internalDuration.date.months,
3623 internalDuration.date.weeks,
3624 targetTime.days,
3625 };
3626 MOZ_ASSERT(IsValidDuration(dateDuration));
3627
3628 // 27.e.
3629 ISODate targetDate;
3630 if (!CalendarDateAdd(cx, calendar, plainRelativeTo, dateDuration,
3631 TemporalOverflow::Constrain, &targetDate)) {
3632 return false;
3633 }
3634
3635 // Step 27.f.
3636 auto isoDateTime = ISODateTime{plainRelativeTo, {}};
3637
3638 // Step 27.g.
3639 auto targetDateTime = ISODateTime{targetDate, targetTime.time};
3640
3641 // DifferencePlainDateTimeWithRounding, step 2.
3642 if (!ISODateTimeWithinLimits(isoDateTime) ||
3643 !ISODateTimeWithinLimits(targetDateTime)) {
3644 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
3645 JSMSG_TEMPORAL_PLAIN_DATE_TIME_INVALID);
3646 return false;
3647 }
3648
3649 // Step 27.h.
3650 if (!DifferencePlainDateTimeWithRounding(cx, isoDateTime, targetDateTime,
3651 calendar,
3652 {
3653 smallestUnit,
3654 largestUnit,
3655 roundingMode,
3656 roundingIncrement,
3657 },
3658 &internalDuration)) {
3659 return false;
3660 }
3661
3662 // Step 27.i
3663 Duration result;
3664 if (!TemporalDurationFromInternal(cx, internalDuration, largestUnit,
3665 &result)) {
3666 return false;
3667 }
3668
3669 auto* obj = CreateTemporalDuration(cx, result);
3670 if (!obj) {
3671 return false;
3672 }
3673
3674 args.rval().setObject(*obj);
3675 return true;
3676 }
3677
3678 // Step 28.
3679 if (existingLargestUnit < TemporalUnit::Day ||
3680 largestUnit < TemporalUnit::Day) {
3681 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
3682 JSMSG_TEMPORAL_DURATION_UNCOMPARABLE,
3683 "relativeTo");
3684 return false;
3685 }
3686
3687 // Step 29.
3688 MOZ_ASSERT(smallestUnit >= TemporalUnit::Day);
3689
3690 // Step 30.
3691 auto internalDuration = ToInternalDurationRecordWith24HourDays(duration);
3692 MOZ_ASSERT(internalDuration.date == DateDuration{});
3693
3694 // Steps 31-32.
3695 if (smallestUnit == TemporalUnit::Day) {
3696 // Steps 31.a-b.
3697 constexpr auto nsPerDay = ToNanoseconds(TemporalUnit::Day);
3698 auto rounded =
3699 RoundNumberToIncrement(internalDuration.time.toNanoseconds(), nsPerDay,
3700 roundingIncrement, roundingMode);
3701 MOZ_ASSERT(Int128{INT64_MIN} <= rounded && rounded <= Int128{INT64_MAX},
3702 "rounded days fits in int64");
3703 auto days = static_cast<int64_t>(rounded);
3704
3705 // Step 31.c. (Inlined CreateDateDurationRecord)
3706 if (std::abs(days) > TimeDuration::max().toDays()) {
3707 JS_ReportErrorNumberASCII(
3708 cx, GetErrorMessage, nullptr,
3709 JSMSG_TEMPORAL_DURATION_INVALID_NORMALIZED_TIME);
3710 return false;
3711 }
3712 auto dateDuration = DateDuration{0, 0, 0, days};
3713 MOZ_ASSERT(IsValidDuration(dateDuration));
3714
3715 // Step 31.d.
3716 internalDuration = {dateDuration, {}};
3717 } else {
3718 // Step 32.a.
3719 TimeDuration timeDuration;
3720 if (!RoundTimeDuration(cx, internalDuration.time, roundingIncrement,
3721 smallestUnit, roundingMode, &timeDuration)) {
3722 return false;
3723 }
3724
3725 // Step 32.b.
3726 internalDuration = {{}, timeDuration};
3727 }
3728
3729 // Step 32.
3730 Duration result;
3731 if (!TemporalDurationFromInternal(cx, internalDuration, largestUnit,
3732 &result)) {
3733 return false;
3734 }
3735
3736 auto* obj = CreateTemporalDuration(cx, result);
3737 if (!obj) {
3738 return false;
3739 }
3740
3741 args.rval().setObject(*obj);
3742 return true;
3743 }
3744
3745 /**
3746 * Temporal.Duration.prototype.round ( options )
3747 */
3748 static bool Duration_round(JSContext* cx, unsigned argc, Value* vp) {
3749 // Steps 1-2.
3750 CallArgs args = CallArgsFromVp(argc, vp);
3751 return CallNonGenericMethod<IsDuration, Duration_round>(cx, args);
3752 }
3753
3754 /**
3755 * Temporal.Duration.prototype.total ( totalOf )
3756 */
3757 static bool Duration_total(JSContext* cx, const CallArgs& args) {
3758 auto* durationObj = &args.thisv().toObject().as<DurationObject>();
3759 auto duration = ToDuration(durationObj);
3760
3761 // Steps 3-10.
3762 Rooted<PlainDate> plainRelativeTo(cx);
3763 Rooted<ZonedDateTime> zonedRelativeTo(cx);
3764 auto unit = TemporalUnit::Auto;
3765 if (args.get(0).isString()) {
3766 // Step 4. (Not applicable in our implementation.)
3767
3768 // Steps 6-9. (Implicit)
3769 MOZ_ASSERT(!plainRelativeTo && !zonedRelativeTo);
3770
3771 // Step 10.
3772 Rooted<JSString*> paramString(cx, args[0].toString());
3773 if (!GetTemporalUnitValuedOption(cx, paramString, TemporalUnitKey::Unit,
3774 TemporalUnitGroup::DateTime, &unit)) {
3775 return false;
3776 }
3777 } else {
3778 // Steps 3 and 5.
3779 Rooted<JSObject*> totalOf(
3780 cx, RequireObjectArg(cx, "totalOf", "total", args.get(0)));
3781 if (!totalOf) {
3782 return false;
3783 }
3784
3785 // Steps 6-9.
3786 if (!GetTemporalRelativeToOption(cx, totalOf, &plainRelativeTo,
3787 &zonedRelativeTo)) {
3788 return false;
3789 }
3790 MOZ_ASSERT(!plainRelativeTo || !zonedRelativeTo);
3791
3792 // Step 10.
3793 if (!GetTemporalUnitValuedOption(cx, totalOf, TemporalUnitKey::Unit,
3794 TemporalUnitGroup::DateTime, &unit)) {
3795 return false;
3796 }
3797
3798 if (unit == TemporalUnit::Auto) {
3799 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
3800 JSMSG_TEMPORAL_MISSING_OPTION, "unit");
3801 return false;
3802 }
3803 }
3804
3805 // Steps 11-13.
3806 double total;
3807 if (zonedRelativeTo) {
3808 // Step 11.a.
3809 auto internalDuration = ToInternalDurationRecord(duration);
3810
3811 // Steps 11.b-d. (Not applicable in our implementation.)
3812
3813 // Step 11.e.
3814 EpochNanoseconds targetEpochNs;
3815 if (!AddZonedDateTime(cx, zonedRelativeTo, internalDuration,
3816 &targetEpochNs)) {
3817 return false;
3818 }
3819
3820 // Step 11.f.
3821 if (!DifferenceZonedDateTimeWithTotal(cx, zonedRelativeTo, targetEpochNs,
3822 unit, &total)) {
3823 return false;
3824 }
3825 } else if (plainRelativeTo) {
3826 // Step 12.a.
3827 auto internalDuration = ToInternalDurationRecordWith24HourDays(duration);
3828
3829 // Step 12.b.
3830 auto targetTime = AddTime(Time{}, internalDuration.time);
3831
3832 // Step 12.c.
3833 auto calendar = plainRelativeTo.calendar();
3834
3835 // Step 12.d.
3836 auto dateDuration = DateDuration{
3837 internalDuration.date.years,
3838 internalDuration.date.months,
3839 internalDuration.date.weeks,
3840 targetTime.days,
3841 };
3842 MOZ_ASSERT(IsValidDuration(dateDuration));
3843
3844 // Step 12.e.
3845 ISODate targetDate;
3846 if (!CalendarDateAdd(cx, calendar, plainRelativeTo, dateDuration,
3847 TemporalOverflow::Constrain, &targetDate)) {
3848 return false;
3849 }
3850
3851 // Step 12.f.
3852 auto isoDateTime = ISODateTime{plainRelativeTo, {}};
3853
3854 // Step 12.g.
3855 auto targetDateTime = ISODateTime{targetDate, targetTime.time};
3856
3857 // DifferencePlainDateTimeWithTotal, step 2.
3858 if (!ISODateTimeWithinLimits(isoDateTime) ||
3859 !ISODateTimeWithinLimits(targetDateTime)) {
3860 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
3861 JSMSG_TEMPORAL_PLAIN_DATE_TIME_INVALID);
3862 return false;
3863 }
3864
3865 // Step 12.h.
3866 if (!DifferencePlainDateTimeWithTotal(cx, isoDateTime, targetDateTime,
3867 calendar, unit, &total)) {
3868 return false;
3869 }
3870 } else {
3871 // Steps 13.a-b.
3872 if (duration.years != 0 || duration.months != 0 || duration.weeks != 0 ||
3873 unit < TemporalUnit::Day) {
3874 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
3875 JSMSG_TEMPORAL_DURATION_UNCOMPARABLE,
3876 "relativeTo");
3877 return false;
3878 }
3879
3880 // Step 13.c.
3881 auto internalDuration = ToInternalDurationRecordWith24HourDays(duration);
3882
3883 // Step 13.d.
3884 total = TotalTimeDuration(internalDuration.time, unit);
3885 }
3886
3887 // Step 14.
3888 args.rval().setNumber(total);
3889 return true;
3890 }
3891
3892 /**
3893 * Temporal.Duration.prototype.total ( totalOf )
3894 */
3895 static bool Duration_total(JSContext* cx, unsigned argc, Value* vp) {
3896 // Steps 1-2.
3897 CallArgs args = CallArgsFromVp(argc, vp);
3898 return CallNonGenericMethod<IsDuration, Duration_total>(cx, args);
3899 }
3900
3901 /**
3902 * Temporal.Duration.prototype.toString ( [ options ] )
3903 */
3904 static bool Duration_toString(JSContext* cx, const CallArgs& args) {
3905 auto duration = ToDuration(&args.thisv().toObject().as<DurationObject>());
3906
3907 // Steps 3-9.
3908 SecondsStringPrecision precision = {Precision::Auto(),
3909 TemporalUnit::Nanosecond, Increment{1}};
3910 auto roundingMode = TemporalRoundingMode::Trunc;
3911 if (args.hasDefined(0)) {
3912 // Step 3.
3913 Rooted<JSObject*> options(
3914 cx, RequireObjectArg(cx, "options", "toString", args[0]));
3915 if (!options) {
3916 return false;
3917 }
3918
3919 // Steps 4-5.
3920 auto digits = Precision::Auto();
3921 if (!GetTemporalFractionalSecondDigitsOption(cx, options, &digits)) {
3922 return false;
3923 }
3924
3925 // Step 6.
3926 if (!GetRoundingModeOption(cx, options, &roundingMode)) {
3927 return false;
3928 }
3929
3930 // Step 7.
3931 auto smallestUnit = TemporalUnit::Auto;
3932 if (!GetTemporalUnitValuedOption(cx, options, TemporalUnitKey::SmallestUnit,
3933 TemporalUnitGroup::Time, &smallestUnit)) {
3934 return false;
3935 }
3936
3937 // Step 8.
3938 if (smallestUnit == TemporalUnit::Hour ||
3939 smallestUnit == TemporalUnit::Minute) {
3940 const char* smallestUnitStr =
3941 smallestUnit == TemporalUnit::Hour ? "hour" : "minute";
3942 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
3943 JSMSG_TEMPORAL_INVALID_UNIT_OPTION,
3944 smallestUnitStr, "smallestUnit");
3945 return false;
3946 }
3947
3948 // Step 9.
3949 precision = ToSecondsStringPrecision(smallestUnit, digits);
3950 }
3951 MOZ_ASSERT(precision.unit >= TemporalUnit::Minute);
3952
3953 // Steps 10-16.
3954 auto roundedDuration = duration;
3955 if (precision.unit != TemporalUnit::Nanosecond ||
3956 precision.increment != Increment{1}) {
3957 // Step 11.
3958 auto largestUnit = DefaultTemporalLargestUnit(duration);
3959
3960 // Step 12.
3961 auto internalDuration = ToInternalDurationRecord(duration);
3962
3963 // Step 13.
3964 TimeDuration timeDuration;
3965 if (!RoundTimeDuration(cx, internalDuration.time, precision.increment,
3966 precision.unit, roundingMode, &timeDuration)) {
3967 return false;
3968 }
3969
3970 // Step 14.
3971 internalDuration = {internalDuration.date, timeDuration};
3972
3973 // Step 15.
3974 auto roundedLargestUnit = std::min(largestUnit, TemporalUnit::Second);
3975
3976 // Step 16.
3977 if (!TemporalDurationFromInternal(cx, internalDuration, roundedLargestUnit,
3978 &roundedDuration)) {
3979 return false;
3980 }
3981 MOZ_ASSERT(IsValidDuration(roundedDuration));
3982 }
3983
3984 // Steps 10.a. and 17.
3985 JSString* str =
3986 TemporalDurationToString(cx, roundedDuration, precision.precision);
3987 if (!str) {
3988 return false;
3989 }
3990
3991 args.rval().setString(str);
3992 return true;
3993 }
3994
3995 /**
3996 * Temporal.Duration.prototype.toString ( [ options ] )
3997 */
3998 static bool Duration_toString(JSContext* cx, unsigned argc, Value* vp) {
3999 // Steps 1-2.
4000 CallArgs args = CallArgsFromVp(argc, vp);
4001 return CallNonGenericMethod<IsDuration, Duration_toString>(cx, args);
4002 }
4003
4004 /**
4005 * Temporal.Duration.prototype.toJSON ( )
4006 */
4007 static bool Duration_toJSON(JSContext* cx, const CallArgs& args) {
4008 auto duration = ToDuration(&args.thisv().toObject().as<DurationObject>());
4009
4010 // Step 3.
4011 JSString* str = TemporalDurationToString(cx, duration, Precision::Auto());
4012 if (!str) {
4013 return false;
4014 }
4015
4016 args.rval().setString(str);
4017 return true;
4018 }
4019
4020 /**
4021 * Temporal.Duration.prototype.toJSON ( )
4022 */
4023 static bool Duration_toJSON(JSContext* cx, unsigned argc, Value* vp) {
4024 // Steps 1-2.
4025 CallArgs args = CallArgsFromVp(argc, vp);
4026 return CallNonGenericMethod<IsDuration, Duration_toJSON>(cx, args);
4027 }
4028
4029 /**
4030 * Temporal.Duration.prototype.toLocaleString ( [ locales [ , options ] ] )
4031 */
4032 static bool Duration_toLocaleString(JSContext* cx, const CallArgs& args) {
4033 // Steps 3-7.
4034 return TemporalDurationToLocaleString(cx, args);
4035 }
4036
4037 /**
4038 * Temporal.Duration.prototype.toLocaleString ( [ locales [ , options ] ] )
4039 */
4040 static bool Duration_toLocaleString(JSContext* cx, unsigned argc, Value* vp) {
4041 // Steps 1-2.
4042 CallArgs args = CallArgsFromVp(argc, vp);
4043 return CallNonGenericMethod<IsDuration, Duration_toLocaleString>(cx, args);
4044 }
4045
4046 /**
4047 * Temporal.Duration.prototype.valueOf ( )
4048 */
4049 static bool Duration_valueOf(JSContext* cx, unsigned argc, Value* vp) {
4050 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_CANT_CONVERT_TO,
4051 "Duration", "primitive type");
4052 return false;
4053 }
4054
4055 const JSClass DurationObject::class_ = {
4056 "Temporal.Duration",
4057 JSCLASS_HAS_RESERVED_SLOTS(DurationObject::SLOT_COUNT) |
4058 JSCLASS_HAS_CACHED_PROTO(JSProto_Duration),
4059 JS_NULL_CLASS_OPS,
4060 &DurationObject::classSpec_,
4061 };
4062
4063 const JSClass& DurationObject::protoClass_ = PlainObject::class_;
4064
4065 static const JSFunctionSpec Duration_methods[] = {
4066 JS_FN("from", Duration_from, 1, 0),
4067 JS_FN("compare", Duration_compare, 2, 0),
4068 JS_FS_END,
4069 };
4070
4071 static const JSFunctionSpec Duration_prototype_methods[] = {
4072 JS_FN("with", Duration_with, 1, 0),
4073 JS_FN("negated", Duration_negated, 0, 0),
4074 JS_FN("abs", Duration_abs, 0, 0),
4075 JS_FN("add", Duration_add, 1, 0),
4076 JS_FN("subtract", Duration_subtract, 1, 0),
4077 JS_FN("round", Duration_round, 1, 0),
4078 JS_FN("total", Duration_total, 1, 0),
4079 JS_FN("toString", Duration_toString, 0, 0),
4080 JS_FN("toJSON", Duration_toJSON, 0, 0),
4081 JS_FN("toLocaleString", Duration_toLocaleString, 0, 0),
4082 JS_FN("valueOf", Duration_valueOf, 0, 0),
4083 JS_FS_END,
4084 };
4085
4086 static const JSPropertySpec Duration_prototype_properties[] = {
4087 JS_PSG("years", Duration_years, 0),
4088 JS_PSG("months", Duration_months, 0),
4089 JS_PSG("weeks", Duration_weeks, 0),
4090 JS_PSG("days", Duration_days, 0),
4091 JS_PSG("hours", Duration_hours, 0),
4092 JS_PSG("minutes", Duration_minutes, 0),
4093 JS_PSG("seconds", Duration_seconds, 0),
4094 JS_PSG("milliseconds", Duration_milliseconds, 0),
4095 JS_PSG("microseconds", Duration_microseconds, 0),
4096 JS_PSG("nanoseconds", Duration_nanoseconds, 0),
4097 JS_PSG("sign", Duration_sign, 0),
4098 JS_PSG("blank", Duration_blank, 0),
4099 JS_STRING_SYM_PS(toStringTag, "Temporal.Duration", JSPROP_READONLY),
4100 JS_PS_END,
4101 };
4102
4103 const ClassSpec DurationObject::classSpec_ = {
4104 GenericCreateConstructor<DurationConstructor, 0, gc::AllocKind::FUNCTION>,
4105 GenericCreatePrototype<DurationObject>,
4106 Duration_methods,
4107 nullptr,
4108 Duration_prototype_methods,
4109 Duration_prototype_properties,
4110 nullptr,
4111 ClassSpec::DontDefineConstructor,
4112 };