Debian Codegraph @

js/src/jsdate.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 /*
8 * JS date methods.
9 *
10 * "For example, OS/360 devotes 26 bytes of the permanently
11 * resident date-turnover routine to the proper handling of
12 * December 31 on leap years (when it is Day 366). That
13 * might have been left to the operator."
14 *
15 * Frederick Brooks, 'The Second-System Effect'.
16 */
17
18 #include "jsdate.h"
19
20 #include "mozilla/Atomics.h"
21 #include "mozilla/Casting.h"
22 #include "mozilla/FloatingPoint.h"
23 #include "mozilla/MathAlgorithms.h"
24 #include "mozilla/TextUtils.h"
25
26 #include <algorithm>
27 #include <cstring>
28 #include <iterator>
29 #include <math.h>
30 #include <string.h>
31
32 #include "jsapi.h"
33 #include "jsfriendapi.h"
34 #include "jsnum.h"
35 #include "jstypes.h"
36
37 #ifdef JS_HAS_INTL_API
38 # include "builtin/temporal/Instant.h"
39 #endif
40 #include "jit/InlinableNatives.h"
41 #include "js/CallAndConstruct.h" // JS::IsCallable
42 #include "js/Conversions.h"
43 #include "js/Date.h"
44 #include "js/friend/ErrorMessages.h" // js::GetErrorMessage, JSMSG_*
45 #include "js/LocaleSensitive.h"
46 #include "js/Object.h" // JS::GetBuiltinClass
47 #include "js/PropertySpec.h"
48 #include "js/Wrapper.h"
49 #include "util/DifferentialTesting.h"
50 #include "util/StringBuilder.h"
51 #include "util/Text.h"
52 #include "vm/DateObject.h"
53 #include "vm/DateTime.h"
54 #include "vm/GlobalObject.h"
55 #include "vm/Interpreter.h"
56 #include "vm/JSContext.h"
57 #include "vm/JSObject.h"
58 #include "vm/StringType.h"
59 #include "vm/Time.h"
60
61 #include "vm/Compartment-inl.h" // For js::UnwrapAndTypeCheckThis
62 #include "vm/GeckoProfiler-inl.h"
63 #include "vm/JSObject-inl.h"
64
65 using namespace js;
66
67 using mozilla::Atomic;
68 using mozilla::BitwiseCast;
69 using mozilla::IsAsciiAlpha;
70 using mozilla::IsAsciiDigit;
71 using mozilla::IsAsciiLowercaseAlpha;
72 using mozilla::NumbersAreIdentical;
73 using mozilla::Relaxed;
74
75 using JS::AutoCheckCannotGC;
76 using JS::ClippedTime;
77 using JS::GenericNaN;
78 using JS::GetBuiltinClass;
79 using JS::TimeClip;
80 using JS::ToInteger;
81
82 // When this value is non-zero, we'll round the time by this resolution.
83 static Atomic<uint32_t, Relaxed> sResolutionUsec;
84 // This is not implemented yet, but we will use this to know to jitter the time
85 // in the JS shell
86 static Atomic<bool, Relaxed> sJitter;
87 // The callback we will use for the Gecko implementation of Timer
88 // Clamping/Jittering
89 static Atomic<JS::ReduceMicrosecondTimePrecisionCallback, Relaxed>
90 sReduceMicrosecondTimePrecisionCallback;
91
92 namespace {
93
94 class DateTimeHelper {
95 private:
96 #if !JS_HAS_INTL_API
97 static int equivalentYearForDST(int year);
98 static bool isRepresentableAsTime32(int64_t t);
99 static int32_t daylightSavingTA(DateTimeInfo::ForceUTC forceUTC, int64_t t);
100 static int32_t adjustTime(DateTimeInfo::ForceUTC forceUTC, int64_t date);
101 static PRMJTime toPRMJTime(DateTimeInfo::ForceUTC forceUTC, int64_t localTime,
102 int64_t utcTime);
103 #endif
104
105 public:
106 static int32_t getTimeZoneOffset(DateTimeInfo::ForceUTC forceUTC,
107 int64_t epochMilliseconds,
108 DateTimeInfo::TimeZoneOffset offset);
109
110 static JSString* timeZoneComment(JSContext* cx,
111 DateTimeInfo::ForceUTC forceUTC,
112 const char* locale, int64_t utcTime,
113 int64_t localTime);
114 #if !JS_HAS_INTL_API
115 static size_t formatTime(DateTimeInfo::ForceUTC forceUTC, char* buf,
116 size_t buflen, const char* fmt, int64_t utcTime,
117 int64_t localTime);
118 #endif
119 };
120
121 } // namespace
122
123 static DateTimeInfo::ForceUTC ForceUTC(const Realm* realm) {
124 return realm->creationOptions().forceUTC() ? DateTimeInfo::ForceUTC::Yes
125 : DateTimeInfo::ForceUTC::No;
126 }
127
128 /**
129 * 5.2.5 Mathematical Operations
130 *
131 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
132 */
133 static inline double PositiveModulo(double dividend, double divisor) {
134 MOZ_ASSERT(divisor > 0);
135 MOZ_ASSERT(std::isfinite(divisor));
136
137 double result = fmod(dividend, divisor);
138 if (result < 0) {
139 result += divisor;
140 }
141 return result + (+0.0);
142 }
143
144 template <typename T>
145 static inline std::enable_if_t<std::is_integral_v<T>, int32_t> PositiveModulo(
146 T dividend, int32_t divisor) {
147 MOZ_ASSERT(divisor > 0);
148
149 int32_t result = dividend % divisor;
150 if (result < 0) {
151 result += divisor;
152 }
153 return result;
154 }
155
156 template <typename T>
157 static constexpr T FloorDiv(T dividend, int32_t divisor) {
158 MOZ_ASSERT(divisor > 0);
159
160 T quotient = dividend / divisor;
161 T remainder = dividend % divisor;
162 if (remainder < 0) {
163 quotient -= 1;
164 }
165 return quotient;
166 }
167
168 #ifdef DEBUG
169 /**
170 * 21.4.1.1 Time Values and Time Range
171 *
172 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
173 */
174 static inline bool IsTimeValue(double t) {
175 if (std::isnan(t)) {
176 return true;
177 }
178 return IsInteger(t) && StartOfTime <= t && t <= EndOfTime;
179 }
180 #endif
181
182 /**
183 * Time value with local time zone offset applied.
184 */
185 static inline bool IsLocalTimeValue(double t) {
186 if (std::isnan(t)) {
187 return true;
188 }
189 return IsInteger(t) && (StartOfTime - msPerDay) < t &&
190 t < (EndOfTime + msPerDay);
191 }
192
193 /**
194 * 21.4.1.3 Day ( t )
195 *
196 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
197 */
198 static inline int32_t Day(int64_t t) {
199 MOZ_ASSERT(IsLocalTimeValue(t));
200 return int32_t(FloorDiv(t, msPerDay));
201 }
202
203 /**
204 * 21.4.1.4 TimeWithinDay ( t )
205 *
206 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
207 */
208 static int32_t TimeWithinDay(int64_t t) {
209 MOZ_ASSERT(IsLocalTimeValue(t));
210 return PositiveModulo(t, msPerDay);
211 }
212
213 /**
214 * 21.4.1.5 DaysInYear ( y )
215 * 21.4.1.10 InLeapYear ( t )
216 *
217 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
218 */
219 static inline bool IsLeapYear(double year) {
220 MOZ_ASSERT(IsInteger(year));
221 return fmod(year, 4) == 0 && (fmod(year, 100) != 0 || fmod(year, 400) == 0);
222 }
223
224 static constexpr bool IsLeapYear(int32_t year) {
225 MOZ_ASSERT(mozilla::Abs(year) <= 2'000'000);
226
227 // From: https://www.youtube.com/watch?v=0s9F4QWAl-E&t=1790s
228 int32_t d = (year % 100 != 0) ? 4 : 16;
229 return (year & (d - 1)) == 0;
230 }
231
232 /**
233 * 21.4.1.6 DayFromYear ( y )
234 *
235 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
236 */
237 static inline double DayFromYear(double y) {
238 // Steps 1-7.
239 return 365 * (y - 1970) + floor((y - 1969) / 4.0) -
240 floor((y - 1901) / 100.0) + floor((y - 1601) / 400.0);
241 }
242
243 static constexpr int32_t DayFromYear(int32_t y) {
244 MOZ_ASSERT(mozilla::Abs(y) <= 2'000'000);
245
246 // Steps 1-7.
247 return 365 * (y - 1970) + FloorDiv((y - 1969), 4) -
248 FloorDiv((y - 1901), 100) + FloorDiv((y - 1601), 400);
249 }
250
251 /**
252 * 21.4.1.7 TimeFromYear ( y )
253 *
254 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
255 */
256 static inline double TimeFromYear(double y) {
257 return ::DayFromYear(y) * msPerDay;
258 }
259
260 static inline int64_t TimeFromYear(int32_t y) {
261 return ::DayFromYear(y) * int64_t(msPerDay);
262 }
263
264 /*
265 * This function returns the year, month and day corresponding to a given
266 * time value. The implementation closely follows (w.r.t. types and variable
267 * names) the algorithm shown in Figure 12 of [1].
268 *
269 * A key point of the algorithm is that it works on the so called
270 * Computational calendar where years run from March to February -- this
271 * largely avoids complications with leap years. The algorithm finds the
272 * date in the Computational calendar and then maps it to the Gregorian
273 * calendar.
274 *
275 * [1] Neri C, Schneider L., "Euclidean affine functions and their
276 * application to calendar algorithms."
277 * Softw Pract Exper. 2023;53(4):937-970. doi: 10.1002/spe.3172
278 * https://onlinelibrary.wiley.com/doi/full/10.1002/spe.3172
279 */
280 YearMonthDay js::ToYearMonthDay(int64_t time) {
281 // Calendar cycles repeat every 400 years in the Gregorian calendar: a
282 // leap day is added every 4 years, removed every 100 years and added
283 // every 400 years. The number of days in 400 years is cycleInDays.
284 constexpr uint32_t cycleInYears = 400;
285 constexpr uint32_t cycleInDays = cycleInYears * 365 + (cycleInYears / 4) -
286 (cycleInYears / 100) + (cycleInYears / 400);
287 static_assert(cycleInDays == 146097, "Wrong calculation of cycleInDays.");
288
289 // The natural epoch for the Computational calendar is 0000/Mar/01 and
290 // there are rataDie1970Jan1 = 719468 days from this date to 1970/Jan/01,
291 // the epoch used by ES2024, 21.4.1.1.
292 constexpr uint32_t rataDie1970Jan1 = 719468;
293
294 constexpr uint32_t maxU32 = std::numeric_limits<uint32_t>::max();
295
296 // Let N_U be the number of days since the 1970/Jan/01. This function sets
297 // N = N_U + K, where K = rataDie1970Jan1 + s * cycleInDays and s is an
298 // integer number (to be chosen). Then, it evaluates 4 * N + 3 on uint32_t
299 // operands so that N must be positive and, to prevent overflow,
300 // 4 * N + 3 <= maxU32 <=> N <= (maxU32 - 3) / 4.
301 // Therefore, we must have 0 <= N_U + K <= (maxU32 - 3) / 4 or, in other
302 // words, N_U must be in [minDays, maxDays] = [-K, (maxU32 - 3) / 4 - K].
303 // Notice that this interval moves cycleInDays positions to the left when
304 // s is incremented. We chose s to get the interval's mid-point as close
305 // as possible to 0. For this, we wish to have:
306 // K ~= (maxU32 - 3) / 4 - K <=> 2 * K ~= (maxU32 - 3) / 4 <=>
307 // K ~= (maxU32 - 3) / 8 <=>
308 // rataDie1970Jan1 + s * cycleInDays ~= (maxU32 - 3) / 8 <=>
309 // s ~= ((maxU32 - 3) / 8 - rataDie1970Jan1) / cycleInDays ~= 3669.8.
310 // Therefore, we chose s = 3670. The shift and correction constants
311 // (see [1]) are then:
312 constexpr uint32_t s = 3670;
313 constexpr uint32_t K = rataDie1970Jan1 + s * cycleInDays;
314 constexpr uint32_t L = s * cycleInYears;
315
316 // [minDays, maxDays] correspond to a date range from -1'468'000/Mar/01 to
317 // 1'471'805/Jun/05.
318 constexpr int32_t minDays = -int32_t(K);
319 constexpr int32_t maxDays = (maxU32 - 3) / 4 - K;
320 static_assert(minDays == -536'895'458, "Wrong calculation of minDays or K.");
321 static_assert(maxDays == 536'846'365, "Wrong calculation of maxDays or K.");
322
323 // These are hard limits for the algorithm and far greater than the
324 // range [-8.64e15, 8.64e15] required by ES2024 21.4.1.1. Callers must
325 // ensure this function is not called out of the hard limits and,
326 // preferably, not outside the ES2024 limits.
327 constexpr int64_t minTime = minDays * int64_t(msPerDay);
328 [[maybe_unused]] constexpr int64_t maxTime = maxDays * int64_t(msPerDay);
329 MOZ_ASSERT(minTime <= time && time <= maxTime);
330
331 // Since time is the number of milliseconds since the epoch, 1970/Jan/01,
332 // one might expect N_U = time / uint64_t(msPerDay) is the number of days
333 // since epoch. There's a catch tough. Consider, for instance, half day
334 // before the epoch, that is, t = -0.5 * msPerDay. This falls on
335 // 1969/Dec/31 and should correspond to N_U = -1 but the above gives
336 // N_U = 0. Indeed, t / msPerDay = -0.5 but integer division truncates
337 // towards 0 (C++ [expr.mul]/4) and not towards -infinity as needed, so
338 // that time / uint64_t(msPerDay) = 0. To workaround this issue we perform
339 // the division on positive operands so that truncations towards 0 and
340 // -infinity are equivalent. For this, set u = time - minTime, which is
341 // positive as asserted above. Then, perform the division u / msPerDay and
342 // to the result add minTime / msPerDay = minDays to cancel the
343 // subtraction of minTime.
344 const uint64_t u = uint64_t(time - minTime);
345 const int32_t N_U = int32_t(u / uint64_t(msPerDay)) + minDays;
346 MOZ_ASSERT(minDays <= N_U && N_U <= maxDays);
347
348 const uint32_t N = uint32_t(N_U) + K;
349
350 // Some magic numbers have been explained above but, unfortunately,
351 // others with no precise interpretation do appear. They mostly come
352 // from numerical approximations of Euclidean affine functions (see [1])
353 // which are faster for the CPU to calculate. Unfortunately, no compiler
354 // can do these optimizations.
355
356 // Century C and year of the century N_C:
357 const uint32_t N_1 = 4 * N + 3;
358 const uint32_t C = N_1 / 146097;
359 const uint32_t N_C = N_1 % 146097 / 4;
360
361 // Year of the century Z and day of the year N_Y:
362 const uint32_t N_2 = 4 * N_C + 3;
363 const uint64_t P_2 = uint64_t(2939745) * N_2;
364 const uint32_t Z = uint32_t(P_2 / 4294967296);
365 const uint32_t N_Y = uint32_t(P_2 % 4294967296) / 2939745 / 4;
366
367 // Year Y:
368 const uint32_t Y = 100 * C + Z;
369
370 // Month M and day D.
371 // The expression for N_3 has been adapted to account for the difference
372 // between month numbers in ES5 15.9.1.4 (from 0 to 11) and [1] (from 1
373 // to 12). This is done by subtracting 65536 from the original
374 // expression so that M decreases by 1 and so does M_G further down.
375 const uint32_t N_3 = 2141 * N_Y + 132377; // 132377 = 197913 - 65536
376 const uint32_t M = N_3 / 65536;
377 const uint32_t D = N_3 % 65536 / 2141;
378
379 // Map from Computational to Gregorian calendar. Notice also the year
380 // correction and the type change and that Jan/01 is day 306 of the
381 // Computational calendar, cf. Table 1. [1]
382 constexpr uint32_t daysFromMar01ToJan01 = 306;
383 const uint32_t J = N_Y >= daysFromMar01ToJan01;
384 const int32_t Y_G = int32_t((Y - L) + J);
385 const int32_t M_G = int32_t(J ? M - 12 : M);
386 const int32_t D_G = int32_t(D + 1);
387
388 return {Y_G, M_G, D_G};
389 }
390
391 /**
392 * 21.4.1.8 YearFromTime ( t )
393 *
394 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
395 */
396 static int32_t YearFromTime(int64_t t) {
397 MOZ_ASSERT(IsLocalTimeValue(t));
398 return ToYearMonthDay(t).year;
399 }
400
401 /**
402 * 21.4.1.9 DayWithinYear ( t )
403 *
404 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
405 */
406 static double DayWithinYear(int64_t t, double year) {
407 MOZ_ASSERT(::YearFromTime(t) == year);
408 return Day(t) - ::DayFromYear(year);
409 }
410
411 /**
412 * 21.4.1.11 MonthFromTime ( t )
413 *
414 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
415 */
416 static int32_t MonthFromTime(int64_t t) {
417 MOZ_ASSERT(IsLocalTimeValue(t));
418 return ToYearMonthDay(t).month;
419 }
420
421 /**
422 * 21.4.1.12 DateFromTime ( t )
423 *
424 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
425 */
426 static int32_t DateFromTime(int64_t t) {
427 MOZ_ASSERT(IsLocalTimeValue(t));
428 return ToYearMonthDay(t).day;
429 }
430
431 /**
432 * 21.4.1.13 WeekDay ( t )
433 *
434 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
435 */
436 static int32_t WeekDay(int64_t t) {
437 MOZ_ASSERT(IsLocalTimeValue(t));
438
439 int32_t result = (Day(t) + 4) % 7;
440 if (result < 0) {
441 result += 7;
442 }
443 return result;
444 }
445
446 static inline int DayFromMonth(int month, bool isLeapYear) {
447 /*
448 * The following array contains the day of year for the first day of
449 * each month, where index 0 is January, and day 0 is January 1.
450 */
451 static const int firstDayOfMonth[2][13] = {
452 {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365},
453 {0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366}};
454
455 MOZ_ASSERT(0 <= month && month <= 12);
456 return firstDayOfMonth[isLeapYear][month];
457 }
458
459 template <typename T>
460 static inline int DayFromMonth(T month, bool isLeapYear) = delete;
461
462 /**
463 * 21.4.1.28 MakeDay ( year, month, date )
464 *
465 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
466 */
467 static double MakeDay(double year, double month, double date) {
468 // Step 1.
469 if (!std::isfinite(year) || !std::isfinite(month) || !std::isfinite(date)) {
470 return GenericNaN();
471 }
472
473 // Steps 2-4.
474 double y = ToInteger(year);
475 double m = ToInteger(month);
476 double dt = ToInteger(date);
477
478 static constexpr int32_t maxYears = 1'000'000;
479 static constexpr int32_t maxMonths = 1'000'000 * 12;
480 static constexpr int32_t maxDate = 100'000'000;
481
482 // Use integer math if possible, because it avoids some notoriously slow
483 // functions like `fmod`.
484 if (MOZ_LIKELY(std::abs(y) <= maxYears && std::abs(m) <= maxMonths &&
485 std::abs(dt) <= maxDate)) {
486 int32_t year = mozilla::AssertedCast<int32_t>(y);
487 int32_t month = mozilla::AssertedCast<int32_t>(m);
488 int32_t date = mozilla::AssertedCast<int32_t>(dt);
489
490 static_assert(maxMonths % 12 == 0,
491 "maxYearMonths expects maxMonths is divisible by 12");
492
493 static constexpr int32_t maxYearMonths = maxYears + (maxMonths / 12);
494 static constexpr int32_t maxYearDay = DayFromYear(maxYearMonths);
495 static constexpr int32_t minYearDay = DayFromYear(-maxYearMonths);
496 static constexpr int32_t daysInLeapYear = 366;
497 static constexpr int32_t maxDay = maxYearDay + daysInLeapYear + maxDate;
498 static constexpr int32_t minDay = minYearDay + daysInLeapYear - maxDate;
499
500 static_assert(maxYearMonths == 2'000'000);
501 static_assert(maxYearDay == 729'765'472);
502 static_assert(minYearDay == -731'204'528);
503 static_assert(maxDay == maxYearDay + daysInLeapYear + maxDate);
504 static_assert(minDay == minYearDay + daysInLeapYear - maxDate);
505
506 // Step 5.
507 int32_t ym = year + FloorDiv(month, 12);
508 MOZ_ASSERT(std::abs(ym) <= maxYearMonths);
509
510 // Step 6. (Implicit)
511
512 // Step 7.
513 int32_t mn = PositiveModulo(month, 12);
514
515 // Step 8.
516 bool leap = IsLeapYear(ym);
517 int32_t yearday = ::DayFromYear(ym);
518 int32_t monthday = DayFromMonth(mn, leap);
519 MOZ_ASSERT(minYearDay <= yearday && yearday <= maxYearDay);
520
521 // Step 9.
522 int32_t day = yearday + monthday + date - 1;
523 MOZ_ASSERT(minDay <= day && day <= maxDay);
524 return day;
525 }
526
527 // Step 5.
528 double ym = y + floor(m / 12);
529
530 // Step 6.
531 if (!std::isfinite(ym)) {
532 return GenericNaN();
533 }
534
535 // Step 7.
536 int mn = int(PositiveModulo(m, 12));
537
538 // Step 8.
539 bool leap = IsLeapYear(ym);
540 double yearday = floor(TimeFromYear(ym) / msPerDay);
541 double monthday = DayFromMonth(mn, leap);
542
543 // Step 9.
544 return yearday + monthday + dt - 1;
545 }
546
547 /**
548 * 21.4.1.29 MakeDate ( day, time )
549 *
550 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
551 */
552 static inline double MakeDate(double day, double time) {
553 // Step 1.
554 if (!std::isfinite(day) || !std::isfinite(time)) {
555 return GenericNaN();
556 }
557
558 // Steps 2-4.
559 return day * msPerDay + time;
560 }
561
562 JS_PUBLIC_API double JS::MakeDate(double year, unsigned month, unsigned day) {
563 MOZ_ASSERT(month <= 11);
564 MOZ_ASSERT(day >= 1 && day <= 31);
565
566 return ::MakeDate(MakeDay(year, month, day), 0);
567 }
568
569 JS_PUBLIC_API double JS::MakeDate(double year, unsigned month, unsigned day,
570 double time) {
571 MOZ_ASSERT(month <= 11);
572 MOZ_ASSERT(day >= 1 && day <= 31);
573
574 return ::MakeDate(MakeDay(year, month, day), time);
575 }
576
577 JS_PUBLIC_API double JS::YearFromTime(double time) {
578 const auto clipped = TimeClip(time);
579 if (!clipped.isValid()) {
580 return GenericNaN();
581 }
582 int64_t tv;
583 MOZ_ALWAYS_TRUE(mozilla::NumberEqualsInt64(clipped.toDouble(), &tv));
584 return ::YearFromTime(tv);
585 }
586
587 JS_PUBLIC_API double JS::MonthFromTime(double time) {
588 const auto clipped = TimeClip(time);
589 if (!clipped.isValid()) {
590 return GenericNaN();
591 }
592 int64_t tv;
593 MOZ_ALWAYS_TRUE(mozilla::NumberEqualsInt64(clipped.toDouble(), &tv));
594 return ::MonthFromTime(tv);
595 }
596
597 JS_PUBLIC_API double JS::DayFromTime(double time) {
598 const auto clipped = TimeClip(time);
599 if (!clipped.isValid()) {
600 return GenericNaN();
601 }
602 int64_t tv;
603 MOZ_ALWAYS_TRUE(mozilla::NumberEqualsInt64(clipped.toDouble(), &tv));
604 return DateFromTime(tv);
605 }
606
607 JS_PUBLIC_API double JS::DayFromYear(double year) {
608 return ::DayFromYear(year);
609 }
610
611 JS_PUBLIC_API double JS::DayWithinYear(double time, double year) {
612 const auto clipped = TimeClip(time);
613 if (!clipped.isValid()) {
614 return GenericNaN();
615 }
616 int64_t tv;
617 MOZ_ALWAYS_TRUE(mozilla::NumberEqualsInt64(clipped.toDouble(), &tv));
618 return ::DayWithinYear(tv, year);
619 }
620
621 JS_PUBLIC_API void JS::SetReduceMicrosecondTimePrecisionCallback(
622 JS::ReduceMicrosecondTimePrecisionCallback callback) {
623 sReduceMicrosecondTimePrecisionCallback = callback;
624 }
625
626 JS_PUBLIC_API JS::ReduceMicrosecondTimePrecisionCallback
627 JS::GetReduceMicrosecondTimePrecisionCallback() {
628 return sReduceMicrosecondTimePrecisionCallback;
629 }
630
631 JS_PUBLIC_API void JS::SetTimeResolutionUsec(uint32_t resolution, bool jitter) {
632 sResolutionUsec = resolution;
633 sJitter = jitter;
634 }
635
636 #if JS_HAS_INTL_API
637 int32_t DateTimeHelper::getTimeZoneOffset(DateTimeInfo::ForceUTC forceUTC,
638 int64_t epochMilliseconds,
639 DateTimeInfo::TimeZoneOffset offset) {
640 MOZ_ASSERT_IF(offset == DateTimeInfo::TimeZoneOffset::UTC,
641 IsTimeValue(epochMilliseconds));
642 MOZ_ASSERT_IF(offset == DateTimeInfo::TimeZoneOffset::Local,
643 IsLocalTimeValue(epochMilliseconds));
644
645 return DateTimeInfo::getOffsetMilliseconds(forceUTC, epochMilliseconds,
646 offset);
647 }
648 #else
649 /*
650 * Find a year for which any given date will fall on the same weekday.
651 *
652 * This function should be used with caution when used other than
653 * for determining DST; it hasn't been proven not to produce an
654 * incorrect year for times near year boundaries.
655 */
656 int DateTimeHelper::equivalentYearForDST(int year) {
657 /*
658 * Years and leap years on which Jan 1 is a Sunday, Monday, etc.
659 *
660 * yearStartingWith[0][i] is an example non-leap year where
661 * Jan 1 appears on Sunday (i == 0), Monday (i == 1), etc.
662 *
663 * yearStartingWith[1][i] is an example leap year where
664 * Jan 1 appears on Sunday (i == 0), Monday (i == 1), etc.
665 *
666 * Keep two different mappings, one for past years (< 1970), and a
667 * different one for future years (> 2037).
668 */
669 static const int pastYearStartingWith[2][7] = {
670 {1978, 1973, 1974, 1975, 1981, 1971, 1977},
671 {1984, 1996, 1980, 1992, 1976, 1988, 1972}};
672 static const int futureYearStartingWith[2][7] = {
673 {2034, 2035, 2030, 2031, 2037, 2027, 2033},
674 {2012, 2024, 2036, 2020, 2032, 2016, 2028}};
675
676 int day = int(::DayFromYear(year) + 4) % 7;
677 if (day < 0) {
678 day += 7;
679 }
680
681 const auto& yearStartingWith =
682 year < 1970 ? pastYearStartingWith : futureYearStartingWith;
683 return yearStartingWith[IsLeapYear(year)][day];
684 }
685
686 // Return true if |t| is representable as a 32-bit time_t variable, that means
687 // the year is in [1970, 2038).
688 bool DateTimeHelper::isRepresentableAsTime32(int64_t t) {
689 return 0 <= t && t < 2145916800000;
690 }
691
692 /* ES5 15.9.1.8. */
693 int32_t DateTimeHelper::daylightSavingTA(DateTimeInfo::ForceUTC forceUTC,
694 int64_t t) {
695 /*
696 * If earlier than 1970 or after 2038, potentially beyond the ken of
697 * many OSes, map it to an equivalent year before asking.
698 */
699 if (!isRepresentableAsTime32(t)) {
700 auto [year, month, day] = ToYearMonthDay(t);
701
702 int equivalentYear = equivalentYearForDST(year);
703 double equivalentDay = MakeDay(equivalentYear, month, day);
704 double equivalentDate = MakeDate(equivalentDay, TimeWithinDay(t));
705
706 MOZ_ALWAYS_TRUE(mozilla::NumberEqualsInt64(equivalentDate, &t));
707 }
708
709 return DateTimeInfo::getDSTOffsetMilliseconds(forceUTC, t);
710 }
711
712 int32_t DateTimeHelper::adjustTime(DateTimeInfo::ForceUTC forceUTC,
713 int64_t date) {
714 int32_t localTZA = DateTimeInfo::localTZA(forceUTC);
715 int32_t t = daylightSavingTA(forceUTC, date) + localTZA;
716 return (localTZA >= 0) ? (t % msPerDay) : -((msPerDay - t) % msPerDay);
717 }
718
719 int32_t DateTimeHelper::getTimeZoneOffset(DateTimeInfo::ForceUTC forceUTC,
720 int64_t epochMilliseconds,
721 DateTimeInfo::TimeZoneOffset offset) {
722 MOZ_ASSERT_IF(offset == DateTimeInfo::TimeZoneOffset::UTC,
723 IsTimeValue(epochMilliseconds));
724 MOZ_ASSERT_IF(offset == DateTimeInfo::TimeZoneOffset::Local,
725 IsLocalTimeValue(epochMilliseconds));
726
727 if (offset == DateTimeInfo::TimeZoneOffset::UTC) {
728 return adjustTime(forceUTC, epochMilliseconds);
729 }
730
731 // Following the ES2017 specification creates undesirable results at DST
732 // transitions. For example when transitioning from PST to PDT,
733 // |new Date(2016,2,13,2,0,0).toTimeString()| returns the string value
734 // "01:00:00 GMT-0800 (PST)" instead of "03:00:00 GMT-0700 (PDT)". Follow
735 // V8 and subtract one hour before computing the offset.
736 // Spec bug: https://bugs.ecmascript.org/show_bug.cgi?id=4007
737
738 return adjustTime(forceUTC, epochMilliseconds -
739 int64_t(DateTimeInfo::localTZA(forceUTC)) -
740 int64_t(msPerHour));
741 }
742 #endif /* JS_HAS_INTL_API */
743
744 /**
745 * 21.4.1.25 LocalTime ( t )
746 *
747 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
748 */
749 static int64_t LocalTime(DateTimeInfo::ForceUTC forceUTC, double t) {
750 MOZ_ASSERT(std::isfinite(t));
751 MOZ_ASSERT(IsTimeValue(t));
752
753 // Steps 1-4.
754 int32_t offsetMs = DateTimeHelper::getTimeZoneOffset(
755 forceUTC, static_cast<int64_t>(t), DateTimeInfo::TimeZoneOffset::UTC);
756 MOZ_ASSERT(std::abs(offsetMs) < msPerDay);
757
758 // Step 5.
759 return static_cast<int64_t>(t) + offsetMs;
760 }
761
762 /**
763 * 21.4.1.26 UTC ( t )
764 *
765 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
766 */
767 static double UTC(DateTimeInfo::ForceUTC forceUTC, double t) {
768 // Step 1.
769 if (!std::isfinite(t)) {
770 return GenericNaN();
771 }
772
773 // Return early when |t| is outside the valid local time value limits.
774 if (!IsLocalTimeValue(t)) {
775 return GenericNaN();
776 }
777
778 // Steps 2-5.
779 int32_t offsetMs = DateTimeHelper::getTimeZoneOffset(
780 forceUTC, static_cast<int64_t>(t), DateTimeInfo::TimeZoneOffset::Local);
781 MOZ_ASSERT(std::abs(offsetMs) < msPerDay);
782
783 // Step 6.
784 return static_cast<double>(static_cast<int64_t>(t) - offsetMs);
785 }
786
787 /**
788 * 21.4.1.14 HourFromTime ( t )
789 *
790 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
791 */
792 static int32_t HourFromTime(int64_t t) {
793 MOZ_ASSERT(IsLocalTimeValue(t));
794 return PositiveModulo(FloorDiv(t, msPerHour), HoursPerDay);
795 }
796
797 /**
798 * 21.4.1.15 MinFromTime ( t )
799 *
800 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
801 */
802 static int32_t MinFromTime(int64_t t) {
803 MOZ_ASSERT(IsLocalTimeValue(t));
804 return PositiveModulo(FloorDiv(t, msPerMinute), MinutesPerHour);
805 }
806
807 /**
808 * 21.4.1.16 SecFromTime ( t )
809 *
810 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
811 */
812 static int32_t SecFromTime(int64_t t) {
813 MOZ_ASSERT(IsLocalTimeValue(t));
814 return PositiveModulo(FloorDiv(t, msPerSecond), SecondsPerMinute);
815 }
816
817 /**
818 * 21.4.1.17 msFromTime ( t )
819 *
820 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
821 */
822 static int32_t msFromTime(int64_t t) {
823 MOZ_ASSERT(IsLocalTimeValue(t));
824 return PositiveModulo(t, msPerSecond);
825 }
826
827 HourMinuteSecond js::ToHourMinuteSecond(int64_t epochMilliseconds) {
828 MOZ_ASSERT(IsLocalTimeValue(epochMilliseconds));
829
830 int32_t hour = HourFromTime(epochMilliseconds);
831 MOZ_ASSERT(0 <= hour && hour < HoursPerDay);
832
833 int32_t minute = MinFromTime(epochMilliseconds);
834 MOZ_ASSERT(0 <= minute && minute < MinutesPerHour);
835
836 int32_t second = SecFromTime(epochMilliseconds);
837 MOZ_ASSERT(0 <= minute && minute < SecondsPerMinute);
838
839 return {hour, minute, second};
840 }
841
842 /**
843 * 21.4.1.27 MakeTime ( hour, min, sec, ms )
844 *
845 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
846 */
847 static double MakeTime(double hour, double min, double sec, double ms) {
848 // Step 1.
849 if (!std::isfinite(hour) || !std::isfinite(min) || !std::isfinite(sec) ||
850 !std::isfinite(ms)) {
851 return GenericNaN();
852 }
853
854 // Step 2.
855 double h = ToInteger(hour);
856
857 // Step 3.
858 double m = ToInteger(min);
859
860 // Step 4.
861 double s = ToInteger(sec);
862
863 // Step 5.
864 double milli = ToInteger(ms);
865
866 // Step 6.
867 return h * msPerHour + m * msPerMinute + s * msPerSecond + milli;
868 }
869
870 /**
871 * 21.4.1.30 MakeFullYear ( year )
872 *
873 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
874 */
875 static double MakeFullYear(double year) {
876 // Step 1.
877 if (std::isnan(year)) {
878 return year;
879 }
880
881 // Step 2.
882 double truncated = ToInteger(year);
883
884 // Step 3.
885 if (0 <= truncated && truncated <= 99) {
886 return 1900 + truncated;
887 }
888
889 // Step 4.
890 return truncated;
891 }
892
893 /**
894 * end of ECMA 'support' functions
895 */
896
897 /**
898 * 21.4.3.4 Date.UTC ( year [ , month [ , date [ , hours [ , minutes [ , seconds
899 * [ , ms ] ] ] ] ] ] )
900 *
901 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
902 */
903 static bool date_UTC(JSContext* cx, unsigned argc, Value* vp) {
904 AutoJSMethodProfilerEntry pseudoFrame(cx, "Date", "UTC");
905 CallArgs args = CallArgsFromVp(argc, vp);
906
907 // Step 1.
908 double y;
909 if (!ToNumber(cx, args.get(0), &y)) {
910 return false;
911 }
912
913 // Step 2.
914 double m;
915 if (args.length() >= 2) {
916 if (!ToNumber(cx, args[1], &m)) {
917 return false;
918 }
919 } else {
920 m = 0;
921 }
922
923 // Step 3.
924 double dt;
925 if (args.length() >= 3) {
926 if (!ToNumber(cx, args[2], &dt)) {
927 return false;
928 }
929 } else {
930 dt = 1;
931 }
932
933 // Step 4.
934 double h;
935 if (args.length() >= 4) {
936 if (!ToNumber(cx, args[3], &h)) {
937 return false;
938 }
939 } else {
940 h = 0;
941 }
942
943 // Step 5.
944 double min;
945 if (args.length() >= 5) {
946 if (!ToNumber(cx, args[4], &min)) {
947 return false;
948 }
949 } else {
950 min = 0;
951 }
952
953 // Step 6.
954 double s;
955 if (args.length() >= 6) {
956 if (!ToNumber(cx, args[5], &s)) {
957 return false;
958 }
959 } else {
960 s = 0;
961 }
962
963 // Step 7.
964 double milli;
965 if (args.length() >= 7) {
966 if (!ToNumber(cx, args[6], &milli)) {
967 return false;
968 }
969 } else {
970 milli = 0;
971 }
972
973 // Step 8.
974 double yr = MakeFullYear(y);
975
976 // Step 9.
977 ClippedTime time =
978 TimeClip(MakeDate(MakeDay(yr, m, dt), MakeTime(h, min, s, milli)));
979 args.rval().set(TimeValue(time));
980 return true;
981 }
982
983 /*
984 * Read and convert decimal digits from s[*i] into *result
985 * while *i < limit.
986 *
987 * Succeed if any digits are converted. Advance *i only
988 * as digits are consumed.
989 */
990 template <typename CharT>
991 static bool ParseDigits(size_t* result, const CharT* s, size_t* i,
992 size_t limit) {
993 size_t init = *i;
994 *result = 0;
995 while (*i < limit && ('0' <= s[*i] && s[*i] <= '9')) {
996 *result *= 10;
997 *result += (s[*i] - '0');
998 ++(*i);
999 }
1000 return *i != init;
1001 }
1002
1003 /*
1004 * Read and convert decimal digits to the right of a decimal point,
1005 * representing a fractional integer, from s[*i] into *result
1006 * while *i < limit, up to 3 digits. Consumes any digits beyond 3
1007 * without affecting the result.
1008 *
1009 * Succeed if any digits are converted. Advance *i only
1010 * as digits are consumed.
1011 */
1012 template <typename CharT>
1013 static bool ParseFractional(int* result, const CharT* s, size_t* i,
1014 size_t limit) {
1015 int factor = 100;
1016 size_t init = *i;
1017 *result = 0;
1018 for (; *i < limit && ('0' <= s[*i] && s[*i] <= '9'); ++(*i)) {
1019 if (*i - init >= 3) {
1020 // If we're past 3 digits, do nothing with it, but continue to
1021 // consume the remainder of the digits
1022 continue;
1023 }
1024 *result += (s[*i] - '0') * factor;
1025 factor /= 10;
1026 }
1027 return *i != init;
1028 }
1029
1030 /*
1031 * Read and convert exactly n decimal digits from s[*i]
1032 * to s[min(*i+n,limit)] into *result.
1033 *
1034 * Succeed if exactly n digits are converted. Advance *i only
1035 * on success.
1036 */
1037 template <typename CharT>
1038 static bool ParseDigitsN(size_t n, size_t* result, const CharT* s, size_t* i,
1039 size_t limit) {
1040 size_t init = *i;
1041
1042 if (ParseDigits(result, s, i, std::min(limit, init + n))) {
1043 return (*i - init) == n;
1044 }
1045
1046 *i = init;
1047 return false;
1048 }
1049
1050 /*
1051 * Read and convert n or less decimal digits from s[*i]
1052 * to s[min(*i+n,limit)] into *result.
1053 *
1054 * Succeed only if greater than zero but less than or equal to n digits are
1055 * converted. Advance *i only on success.
1056 */
1057 template <typename CharT>
1058 static bool ParseDigitsNOrLess(size_t n, size_t* result, const CharT* s,
1059 size_t* i, size_t limit) {
1060 size_t init = *i;
1061
1062 if (ParseDigits(result, s, i, std::min(limit, init + n))) {
1063 return ((*i - init) > 0) && ((*i - init) <= n);
1064 }
1065
1066 *i = init;
1067 return false;
1068 }
1069
1070 /*
1071 * Parse a string according to the formats specified in the standard:
1072 *
1073 * https://tc39.es/ecma262/#sec-date-time-string-format
1074 * https://tc39.es/ecma262/#sec-expanded-years
1075 *
1076 * These formats are based upon a simplification of the ISO 8601 Extended
1077 * Format. As per the spec omitted month and day values are defaulted to '01',
1078 * omitted HH:mm:ss values are defaulted to '00' and an omitted sss field is
1079 * defaulted to '000'.
1080 *
1081 * For cross compatibility we allow the following extensions.
1082 *
1083 * These are:
1084 *
1085 * One or more decimal digits for milliseconds:
1086 * The specification requires exactly three decimal digits for
1087 * the fractional part but we allow for one or more digits.
1088 *
1089 * Time zone specifier without ':':
1090 * We allow the time zone to be specified without a ':' character.
1091 * E.g. "T19:00:00+0700" is equivalent to "T19:00:00+07:00".
1092 *
1093 * Date part:
1094 *
1095 * Year:
1096 * YYYY (eg 1997)
1097 *
1098 * Year and month:
1099 * YYYY-MM (eg 1997-07)
1100 *
1101 * Complete date:
1102 * YYYY-MM-DD (eg 1997-07-16)
1103 *
1104 * Time part:
1105 *
1106 * Hours and minutes:
1107 * Thh:mmTZD (eg T19:20+01:00)
1108 *
1109 * Hours, minutes and seconds:
1110 * Thh:mm:ssTZD (eg T19:20:30+01:00)
1111 *
1112 * Hours, minutes, seconds and a decimal fraction of a second:
1113 * Thh:mm:ss.sssTZD (eg T19:20:30.45+01:00)
1114 *
1115 * where:
1116 *
1117 * YYYY = four-digit year or six digit year as +YYYYYY or -YYYYYY
1118 * MM = two-digit month (01=January, etc.)
1119 * DD = two-digit day of month (01 through 31)
1120 * hh = two digits of hour (00 through 24) (am/pm NOT allowed)
1121 * mm = two digits of minute (00 through 59)
1122 * ss = two digits of second (00 through 59)
1123 * sss = one or more digits representing a decimal fraction of a second
1124 * TZD = time zone designator (Z or +hh:mm or -hh:mm or missing for local)
1125 */
1126 template <typename CharT>
1127 static bool ParseISOStyleDate(DateTimeInfo::ForceUTC forceUTC, const CharT* s,
1128 size_t length, ClippedTime* result) {
1129 size_t i = 0;
1130 int tzMul = 1;
1131 int dateMul = 1;
1132 size_t year = 1970;
1133 size_t month = 1;
1134 size_t day = 1;
1135 size_t hour = 0;
1136 size_t min = 0;
1137 size_t sec = 0;
1138 int msec = 0;
1139 bool isLocalTime = false;
1140 size_t tzHour = 0;
1141 size_t tzMin = 0;
1142
1143 #define PEEK(ch) (i < length && s[i] == ch)
1144
1145 #define NEED(ch) \
1146 if (i >= length || s[i] != ch) { \
1147 return false; \
1148 } else { \
1149 ++i; \
1150 }
1151
1152 #define DONE_DATE_UNLESS(ch) \
1153 if (i >= length || s[i] != ch) { \
1154 goto done_date; \
1155 } else { \
1156 ++i; \
1157 }
1158
1159 #define DONE_UNLESS(ch) \
1160 if (i >= length || s[i] != ch) { \
1161 goto done; \
1162 } else { \
1163 ++i; \
1164 }
1165
1166 #define NEED_NDIGITS(n, field) \
1167 if (!ParseDigitsN(n, &field, s, &i, length)) { \
1168 return false; \
1169 }
1170
1171 if (PEEK('+') || PEEK('-')) {
1172 if (PEEK('-')) {
1173 dateMul = -1;
1174 }
1175 ++i;
1176 NEED_NDIGITS(6, year);
1177
1178 // https://tc39.es/ecma262/#sec-expanded-years
1179 // -000000 is not a valid expanded year.
1180 if (year == 0 && dateMul == -1) {
1181 return false;
1182 }
1183 } else {
1184 NEED_NDIGITS(4, year);
1185 }
1186 DONE_DATE_UNLESS('-');
1187 NEED_NDIGITS(2, month);
1188 DONE_DATE_UNLESS('-');
1189 NEED_NDIGITS(2, day);
1190
1191 done_date:
1192 if (PEEK('T')) {
1193 ++i;
1194 } else {
1195 goto done;
1196 }
1197
1198 NEED_NDIGITS(2, hour);
1199 NEED(':');
1200 NEED_NDIGITS(2, min);
1201
1202 if (PEEK(':')) {
1203 ++i;
1204 NEED_NDIGITS(2, sec);
1205 if (PEEK('.')) {
1206 ++i;
1207 if (!ParseFractional(&msec, s, &i, length)) {
1208 return false;
1209 }
1210 }
1211 }
1212
1213 if (PEEK('Z')) {
1214 ++i;
1215 } else if (PEEK('+') || PEEK('-')) {
1216 if (PEEK('-')) {
1217 tzMul = -1;
1218 }
1219 ++i;
1220 NEED_NDIGITS(2, tzHour);
1221 /*
1222 * Non-standard extension to the ISO date format (permitted by ES5):
1223 * allow "-0700" as a time zone offset, not just "-07:00".
1224 */
1225 if (PEEK(':')) {
1226 ++i;
1227 }
1228 NEED_NDIGITS(2, tzMin);
1229 } else {
1230 isLocalTime = true;
1231 }
1232
1233 done:
1234 if (year > 275943 // ceil(1e8/365) + 1970
1235 || month == 0 || month > 12 || day == 0 || day > 31 || hour > 24 ||
1236 (hour == 24 && (min > 0 || sec > 0 || msec > 0)) || min > 59 ||
1237 sec > 59 || tzHour > 23 || tzMin > 59) {
1238 return false;
1239 }
1240
1241 if (i != length) {
1242 return false;
1243 }
1244
1245 month -= 1; /* convert month to 0-based */
1246
1247 double date = MakeDate(MakeDay(dateMul * int32_t(year), month, day),
1248 MakeTime(hour, min, sec, msec));
1249
1250 if (isLocalTime) {
1251 date = UTC(forceUTC, date);
1252 } else {
1253 date -=
1254 tzMul * (int32_t(tzHour) * msPerHour + int32_t(tzMin) * msPerMinute);
1255 }
1256
1257 *result = TimeClip(date);
1258 return NumbersAreIdentical(date, result->toDouble());
1259
1260 #undef PEEK
1261 #undef NEED
1262 #undef DONE_UNLESS
1263 #undef NEED_NDIGITS
1264 }
1265
1266 /**
1267 * Non-ISO years < 100 get fixed up, to allow 2-digit year formats.
1268 * year < 50 becomes 2000-2049, 50-99 becomes 1950-1999.
1269 */
1270 static int FixupYear(int year) {
1271 if (year < 50) {
1272 year += 2000;
1273 } else if (year >= 50 && year < 100) {
1274 year += 1900;
1275 }
1276 return year;
1277 }
1278
1279 template <typename CharT>
1280 static bool MatchesKeyword(const CharT* s, size_t len, const char* keyword) {
1281 while (len > 0) {
1282 MOZ_ASSERT(IsAsciiAlpha(*s));
1283 MOZ_ASSERT(IsAsciiLowercaseAlpha(*keyword) || *keyword == '\0');
1284
1285 if (unicode::ToLowerCase(static_cast<Latin1Char>(*s)) != *keyword) {
1286 return false;
1287 }
1288
1289 ++s, ++keyword;
1290 --len;
1291 }
1292
1293 return *keyword == '\0';
1294 }
1295
1296 static constexpr const char* const month_prefixes[] = {
1297 "jan", "feb", "mar", "apr", "may", "jun",
1298 "jul", "aug", "sep", "oct", "nov", "dec",
1299 };
1300
1301 /**
1302 * Given a string s of length >= 3, checks if it begins,
1303 * case-insensitive, with the given lower case prefix.
1304 */
1305 template <typename CharT>
1306 static bool StartsWithMonthPrefix(const CharT* s, const char* prefix) {
1307 MOZ_ASSERT(strlen(prefix) == 3);
1308
1309 for (size_t i = 0; i < 3; ++i) {
1310 MOZ_ASSERT(IsAsciiAlpha(*s));
1311 MOZ_ASSERT(IsAsciiLowercaseAlpha(*prefix));
1312
1313 if (unicode::ToLowerCase(static_cast<Latin1Char>(*s)) != *prefix) {
1314 return false;
1315 }
1316
1317 ++s, ++prefix;
1318 }
1319
1320 return true;
1321 }
1322
1323 template <typename CharT>
1324 static bool IsMonthName(const CharT* s, size_t len, int* mon) {
1325 // Month abbreviations < 3 chars are not accepted.
1326 if (len < 3) {
1327 return false;
1328 }
1329
1330 for (size_t m = 0; m < std::size(month_prefixes); ++m) {
1331 if (StartsWithMonthPrefix(s, month_prefixes[m])) {
1332 // Use numeric value.
1333 *mon = m + 1;
1334 return true;
1335 }
1336 }
1337
1338 return false;
1339 }
1340
1341 /*
1342 * Try to parse the following date formats:
1343 * dd-MMM-yyyy
1344 * dd-MMM-yy
1345 * MMM-dd-yyyy
1346 * MMM-dd-yy
1347 * yyyy-MMM-dd
1348 * yy-MMM-dd
1349 *
1350 * Returns true and fills all out parameters when successfully parsed
1351 * dashed-date. Otherwise returns false and leaves out parameters untouched.
1352 */
1353 template <typename CharT>
1354 static bool TryParseDashedDatePrefix(const CharT* s, size_t length,
1355 size_t* indexOut, int* yearOut,
1356 int* monOut, int* mdayOut) {
1357 size_t i = *indexOut;
1358
1359 size_t pre = i;
1360 size_t mday;
1361 if (!ParseDigitsNOrLess(6, &mday, s, &i, length)) {
1362 return false;
1363 }
1364 size_t mdayDigits = i - pre;
1365
1366 if (i >= length || s[i] != '-') {
1367 return false;
1368 }
1369 ++i;
1370
1371 int mon = 0;
1372 if (*monOut == -1) {
1373 // If month wasn't already set by ParseDate, it must be in the middle of
1374 // this format, let's look for it
1375 size_t start = i;
1376 for (; i < length; i++) {
1377 if (!IsAsciiAlpha(s[i])) {
1378 break;
1379 }
1380 }
1381
1382 if (!IsMonthName(s + start, i - start, &mon)) {
1383 return false;
1384 }
1385
1386 if (i >= length || s[i] != '-') {
1387 return false;
1388 }
1389 ++i;
1390 }
1391
1392 pre = i;
1393 size_t year;
1394 if (!ParseDigitsNOrLess(6, &year, s, &i, length)) {
1395 return false;
1396 }
1397 size_t yearDigits = i - pre;
1398
1399 if (i < length && IsAsciiDigit(s[i])) {
1400 return false;
1401 }
1402
1403 // Swap the mday and year if the year wasn't specified in full.
1404 if (mday > 31 && year <= 31 && yearDigits < 4) {
1405 std::swap(mday, year);
1406 std::swap(mdayDigits, yearDigits);
1407 }
1408
1409 if (mday > 31 || mdayDigits > 2) {
1410 return false;
1411 }
1412
1413 year = FixupYear(year);
1414
1415 *indexOut = i;
1416 *yearOut = year;
1417 if (*monOut == -1) {
1418 *monOut = mon;
1419 }
1420 *mdayOut = mday;
1421 return true;
1422 }
1423
1424 /*
1425 * Try to parse dates in the style of YYYY-MM-DD which do not conform to
1426 * the formal standard from ParseISOStyleDate. This includes cases such as
1427 *
1428 * - Year does not have 4 digits
1429 * - Month or mday has 1 digit
1430 * - Space in between date and time, rather than a 'T'
1431 *
1432 * Regarding the last case, this function only parses out the date, returning
1433 * to ParseDate to finish parsing the time and timezone, if present.
1434 *
1435 * Returns true and fills all out parameters when successfully parsed
1436 * dashed-date. Otherwise returns false and leaves out parameters untouched.
1437 */
1438 template <typename CharT>
1439 static bool TryParseDashedNumericDatePrefix(const CharT* s, size_t length,
1440 size_t* indexOut, int* yearOut,
1441 int* monOut, int* mdayOut) {
1442 size_t i = *indexOut;
1443
1444 size_t first;
1445 if (!ParseDigitsNOrLess(6, &first, s, &i, length)) {
1446 return false;
1447 }
1448
1449 if (i >= length || s[i] != '-') {
1450 return false;
1451 }
1452 ++i;
1453
1454 size_t second;
1455 if (!ParseDigitsNOrLess(2, &second, s, &i, length)) {
1456 return false;
1457 }
1458
1459 if (i >= length || s[i] != '-') {
1460 return false;
1461 }
1462 ++i;
1463
1464 size_t third;
1465 if (!ParseDigitsNOrLess(6, &third, s, &i, length)) {
1466 return false;
1467 }
1468
1469 int year;
1470 int mon = -1;
1471 int mday = -1;
1472
1473 // 1 or 2 digits for the first number is tricky; 1-12 means it's a month, 0 or
1474 // >31 means it's a year, and 13-31 is invalid due to ambiguity.
1475 if (first >= 1 && first <= 12) {
1476 mon = first;
1477 } else if (first == 0 || first > 31) {
1478 year = first;
1479 } else {
1480 return false;
1481 }
1482
1483 if (mon < 0) {
1484 // If month hasn't been set yet, it's definitely the 2nd number
1485 mon = second;
1486 } else {
1487 // If it has, the next number is the mday
1488 mday = second;
1489 }
1490
1491 if (mday < 0) {
1492 // The third number is probably the mday...
1493 mday = third;
1494 } else {
1495 // But otherwise, it's the year
1496 year = third;
1497 }
1498
1499 if (mon < 1 || mon > 12 || mday < 1 || mday > 31) {
1500 return false;
1501 }
1502
1503 year = FixupYear(year);
1504
1505 *indexOut = i;
1506 *yearOut = year;
1507 *monOut = mon;
1508 *mdayOut = mday;
1509 return true;
1510 }
1511
1512 struct CharsAndAction {
1513 const char* chars;
1514 int action;
1515 };
1516
1517 static constexpr CharsAndAction keywords[] = {
1518 // clang-format off
1519 // AM/PM
1520 { "am", -1 },
1521 { "pm", -2 },
1522 // Time zone abbreviations.
1523 { "gmt", 10000 + 0 },
1524 { "z", 10000 + 0 },
1525 { "ut", 10000 + 0 },
1526 { "utc", 10000 + 0 },
1527 { "est", 10000 + 5 * 60 },
1528 { "edt", 10000 + 4 * 60 },
1529 { "cst", 10000 + 6 * 60 },
1530 { "cdt", 10000 + 5 * 60 },
1531 { "mst", 10000 + 7 * 60 },
1532 { "mdt", 10000 + 6 * 60 },
1533 { "pst", 10000 + 8 * 60 },
1534 { "pdt", 10000 + 7 * 60 },
1535 // clang-format on
1536 };
1537
1538 template <size_t N>
1539 static constexpr size_t MinKeywordLength(const CharsAndAction (&keywords)[N]) {
1540 size_t min = size_t(-1);
1541 for (const CharsAndAction& keyword : keywords) {
1542 min = std::min(min, std::char_traits<char>::length(keyword.chars));
1543 }
1544 return min;
1545 }
1546
1547 template <typename CharT>
1548 static bool ParseDate(JSContext* cx, DateTimeInfo::ForceUTC forceUTC,
1549 const CharT* s, size_t length, ClippedTime* result) {
1550 if (length == 0) {
1551 return false;
1552 }
1553
1554 if (ParseISOStyleDate(forceUTC, s, length, result)) {
1555 return true;
1556 }
1557
1558 // Collect telemetry on how often Date.parse enters implementation defined
1559 // code. This can be removed in the future, see Bug 1944630.
1560 cx->runtime()->setUseCounter(cx->global(), JSUseCounter::DATEPARSE_IMPL_DEF);
1561
1562 size_t index = 0;
1563 int mon = -1;
1564 bool seenMonthName = false;
1565
1566 // Before we begin, we need to scrub any words from the beginning of the
1567 // string up to the first number, recording the month if we encounter it
1568 for (; index < length; index++) {
1569 int c = s[index];
1570
1571 if (strchr(" ,.-/", c)) {
1572 continue;
1573 }
1574 if (!IsAsciiAlpha(c)) {
1575 break;
1576 }
1577
1578 size_t start = index;
1579 index++;
1580 for (; index < length; index++) {
1581 if (!IsAsciiAlpha(s[index])) {
1582 break;
1583 }
1584 }
1585
1586 if (index >= length) {
1587 return false;
1588 }
1589
1590 if (IsMonthName(s + start, index - start, &mon)) {
1591 seenMonthName = true;
1592 // If the next digit is a number, we need to break so it
1593 // gets parsed as mday
1594 if (IsAsciiDigit(s[index])) {
1595 break;
1596 }
1597 } else if (!strchr(" ,.-/", s[index])) {
1598 // We're only allowing the above delimiters after the day of
1599 // week to prevent things such as "foo_1" from being parsed
1600 // as a date, which may break software which uses this function
1601 // to determine whether or not something is a date.
1602 return false;
1603 }
1604 }
1605
1606 int year = -1;
1607 int mday = -1;
1608 int hour = -1;
1609 int min = -1;
1610 int sec = -1;
1611 int msec = 0;
1612 int tzOffset = -1;
1613
1614 // One of '+', '-', ':', '/', or 0 (the default value).
1615 int prevc = 0;
1616
1617 bool seenPlusMinus = false;
1618 bool seenFullYear = false;
1619 bool negativeYear = false;
1620 // Includes "GMT", "UTC", "UT", and "Z" timezone keywords
1621 bool seenGmtAbbr = false;
1622
1623 // Try parsing the leading dashed-date.
1624 //
1625 // If successfully parsed, index is updated to the end of the date part,
1626 // and year, mon, mday are set to the date.
1627 // Continue parsing optional time + tzOffset parts.
1628 //
1629 // Otherwise, this is no-op.
1630 bool isDashedDate =
1631 TryParseDashedDatePrefix(s, length, &index, &year, &mon, &mday) ||
1632 TryParseDashedNumericDatePrefix(s, length, &index, &year, &mon, &mday);
1633
1634 if (isDashedDate && index < length && strchr("T:+", s[index])) {
1635 return false;
1636 }
1637
1638 while (index < length) {
1639 int c = s[index];
1640 index++;
1641
1642 // Normalize U+202F (NARROW NO-BREAK SPACE). This character appears between
1643 // the AM/PM markers for |date.toLocaleString("en")|. We have to normalize
1644 // it for backward compatibility reasons.
1645 if (c == 0x202F) {
1646 c = ' ';
1647 }
1648
1649 if ((c == '+' || c == '-') &&
1650 // Reject + or - after timezone (still allowing for negative year)
1651 ((seenPlusMinus && year != -1) ||
1652 // Reject timezones like "1995-09-26 -04:30" (if the - is right up
1653 // against the previous number, it will get parsed as a time,
1654 // see the other comment below)
1655 (year != -1 && hour == -1 && !seenGmtAbbr &&
1656 !IsAsciiDigit(s[index - 2])))) {
1657 return false;
1658 }
1659
1660 // Spaces, ASCII control characters, periods, and commas are simply ignored.
1661 if (c <= ' ' || c == '.' || c == ',') {
1662 continue;
1663 }
1664
1665 // Parse delimiter characters. Save them to the side for future use.
1666 if (c == '/' || c == ':' || c == '+') {
1667 prevc = c;
1668 continue;
1669 }
1670
1671 // Dashes are delimiters if they're immediately followed by a number field.
1672 // If they're not followed by a number field, they're simply ignored.
1673 if (c == '-') {
1674 if (index < length && IsAsciiDigit(s[index])) {
1675 prevc = c;
1676 }
1677 continue;
1678 }
1679
1680 // Skip over comments -- text inside matching parentheses. (Comments
1681 // themselves may contain comments as long as all the parentheses properly
1682 // match up. And apparently comments, including nested ones, may validly be
1683 // terminated by end of input...)
1684 if (c == '(') {
1685 int depth = 1;
1686 while (index < length) {
1687 c = s[index];
1688 index++;
1689 if (c == '(') {
1690 depth++;
1691 } else if (c == ')') {
1692 if (--depth <= 0) {
1693 break;
1694 }
1695 }
1696 }
1697 continue;
1698 }
1699
1700 // Parse a number field.
1701 if (IsAsciiDigit(c)) {
1702 size_t partStart = index - 1;
1703 uint32_t u = c - '0';
1704 while (index < length) {
1705 c = s[index];
1706 if (!IsAsciiDigit(c)) {
1707 break;
1708 }
1709 u = u * 10 + (c - '0');
1710 index++;
1711 }
1712 size_t partLength = index - partStart;
1713
1714 // See above for why we have to normalize U+202F.
1715 if (c == 0x202F) {
1716 c = ' ';
1717 }
1718
1719 int n = int(u);
1720
1721 /*
1722 * Allow TZA before the year, so 'Wed Nov 05 21:49:11 GMT-0800 1997'
1723 * works.
1724 *
1725 * Uses of seenPlusMinus allow ':' in TZA, so Java no-timezone style
1726 * of GMT+4:30 works.
1727 */
1728
1729 if (prevc == '-' && (tzOffset != 0 || seenPlusMinus) && partLength >= 4 &&
1730 year < 0) {
1731 // Parse as a negative, possibly zero-padded year if
1732 // 1. the preceding character is '-',
1733 // 2. the TZA is not 'GMT' (tested by |tzOffset != 0|),
1734 // 3. or a TZA was already parsed |seenPlusMinus == true|,
1735 // 4. the part length is at least 4 (to parse '-08' as a TZA),
1736 // 5. and we did not already parse a year |year < 0|.
1737 year = n;
1738 seenFullYear = true;
1739 negativeYear = true;
1740 } else if ((prevc == '+' || prevc == '-') &&
1741 // "1995-09-26-04:30" needs to be parsed as a time,
1742 // not a time zone
1743 (seenGmtAbbr || hour != -1)) {
1744 /* Make ':' case below change tzOffset. */
1745 seenPlusMinus = true;
1746
1747 /* offset */
1748 if (n < 24 && partLength <= 2) {
1749 n = n * 60; /* EG. "GMT-3" */
1750 } else {
1751 n = n % 100 + n / 100 * 60; /* eg "GMT-0430" */
1752 }
1753
1754 if (prevc == '+') /* plus means east of GMT */
1755 n = -n;
1756
1757 // Reject if not preceded by 'GMT' or if a time zone offset
1758 // was already parsed.
1759 if (tzOffset != 0 && tzOffset != -1) {
1760 return false;
1761 }
1762
1763 tzOffset = n;
1764 } else if (prevc == '/' && mon >= 0 && mday >= 0 && year < 0) {
1765 if (c <= ' ' || c == ',' || c == '/' || index >= length) {
1766 year = n;
1767 } else {
1768 return false;
1769 }
1770 } else if (c == ':') {
1771 if (hour < 0) {
1772 hour = /*byte*/ n;
1773 } else if (min < 0) {
1774 min = /*byte*/ n;
1775 } else {
1776 return false;
1777 }
1778 } else if (c == '/') {
1779 /*
1780 * Until it is determined that mon is the actual month, keep
1781 * it as 1-based rather than 0-based.
1782 */
1783 if (mon < 0) {
1784 mon = /*byte*/ n;
1785 } else if (mday < 0) {
1786 mday = /*byte*/ n;
1787 } else {
1788 return false;
1789 }
1790 } else if (index < length && c != ',' && c > ' ' && c != '-' &&
1791 c != '(' &&
1792 // Allow '.' as a delimiter until seconds have been parsed
1793 // (this allows the decimal for milliseconds)
1794 (c != '.' || sec != -1) &&
1795 // Allow zulu time e.g. "09/26/1995 16:00Z", or
1796 // '+' directly after time e.g. 00:00+0500
1797 !(hour != -1 && strchr("Zz+", c)) &&
1798 // Allow month or AM/PM directly after a number
1799 (!IsAsciiAlpha(c) ||
1800 (mon != -1 && !(strchr("AaPp", c) && index < length - 1 &&
1801 strchr("Mm", s[index + 1]))))) {
1802 return false;
1803 } else if (seenPlusMinus && n < 60) { /* handle GMT-3:30 */
1804 if (tzOffset < 0) {
1805 tzOffset -= n;
1806 } else {
1807 tzOffset += n;
1808 }
1809 } else if (hour >= 0 && min < 0) {
1810 min = /*byte*/ n;
1811 } else if (prevc == ':' && min >= 0 && sec < 0) {
1812 sec = /*byte*/ n;
1813 if (c == '.') {
1814 index++;
1815 if (!ParseFractional(&msec, s, &index, length)) {
1816 return false;
1817 }
1818 }
1819 } else if (mon < 0) {
1820 mon = /*byte*/ n;
1821 } else if (mon >= 0 && mday < 0) {
1822 mday = /*byte*/ n;
1823 } else if (mon >= 0 && mday >= 0 && year < 0) {
1824 year = n;
1825 seenFullYear = partLength >= 4;
1826 } else {
1827 return false;
1828 }
1829
1830 prevc = 0;
1831 continue;
1832 }
1833
1834 // Parse fields that are words: ASCII letters spelling out in English AM/PM,
1835 // day of week, month, or an extremely limited set of legacy time zone
1836 // abbreviations.
1837 if (IsAsciiAlpha(c)) {
1838 size_t start = index - 1;
1839 while (index < length) {
1840 c = s[index];
1841 if (!IsAsciiAlpha(c)) {
1842 break;
1843 }
1844 index++;
1845 }
1846
1847 // There must be at least as many letters as in the shortest keyword.
1848 constexpr size_t MinLength = MinKeywordLength(keywords);
1849 if (index - start < MinLength) {
1850 return false;
1851 }
1852
1853 // Record a month if it is a month name. Note that some numbers are
1854 // initially treated as months; if a numeric field has already been
1855 // interpreted as a month, store that value to the actually appropriate
1856 // date component and set the month here.
1857 int tryMonth;
1858 if (IsMonthName(s + start, index - start, &tryMonth)) {
1859 if (seenMonthName) {
1860 // Overwrite the previous month name
1861 mon = tryMonth;
1862 prevc = 0;
1863 continue;
1864 }
1865
1866 seenMonthName = true;
1867
1868 if (mon < 0) {
1869 mon = tryMonth;
1870 } else if (mday < 0) {
1871 mday = mon;
1872 mon = tryMonth;
1873 } else if (year < 0) {
1874 if (mday > 0) {
1875 // If the date is of the form f l month, then when month is
1876 // reached we have f in mon and l in mday. In order to be
1877 // consistent with the f month l and month f l forms, we need to
1878 // swap so that f is in mday and l is in year.
1879 year = mday;
1880 mday = mon;
1881 } else {
1882 year = mon;
1883 }
1884 mon = tryMonth;
1885 } else {
1886 return false;
1887 }
1888
1889 prevc = 0;
1890 continue;
1891 }
1892
1893 size_t k = std::size(keywords);
1894 while (k-- > 0) {
1895 const CharsAndAction& keyword = keywords[k];
1896
1897 // If the field doesn't match the keyword, try the next one.
1898 if (!MatchesKeyword(s + start, index - start, keyword.chars)) {
1899 continue;
1900 }
1901
1902 int action = keyword.action;
1903
1904 if (action == 10000) {
1905 seenGmtAbbr = true;
1906 }
1907
1908 // Perform action tests from smallest action values to largest.
1909
1910 // Adjust a previously-specified hour for AM/PM accordingly (taking care
1911 // to treat 12:xx AM as 00:xx, 12:xx PM as 12:xx).
1912 if (action < 0) {
1913 MOZ_ASSERT(action == -1 || action == -2);
1914 if (hour > 12 || hour < 0) {
1915 return false;
1916 }
1917
1918 if (action == -1 && hour == 12) {
1919 hour = 0;
1920 } else if (action == -2 && hour != 12) {
1921 hour += 12;
1922 }
1923
1924 break;
1925 }
1926
1927 // Finally, record a time zone offset.
1928 MOZ_ASSERT(action >= 10000);
1929 tzOffset = action - 10000;
1930 break;
1931 }
1932
1933 if (k == size_t(-1)) {
1934 return false;
1935 }
1936
1937 prevc = 0;
1938 continue;
1939 }
1940
1941 // Any other character fails to parse.
1942 return false;
1943 }
1944
1945 // Handle cases where the input is a single number. Single numbers >= 1000
1946 // are handled by the spec (ParseISOStyleDate), so we don't need to account
1947 // for that here.
1948 if (mon != -1 && year < 0 && mday < 0) {
1949 // Reject 13-31 for Chrome parity
1950 if (mon >= 13 && mon <= 31) {
1951 return false;
1952 }
1953
1954 mday = 1;
1955 if (mon >= 1 && mon <= 12) {
1956 // 1-12 is parsed as a month with the year defaulted to 2001
1957 // (again, for Chrome parity)
1958 year = 2001;
1959 } else {
1960 year = FixupYear(mon);
1961 mon = 1;
1962 }
1963 }
1964
1965 if (year < 0 || mon < 0 || mday < 0) {
1966 return false;
1967 }
1968
1969 if (!isDashedDate) {
1970 // NOTE: TryParseDashedDatePrefix already handles the following fixup.
1971
1972 /*
1973 * Case 1. The input string contains an English month name.
1974 * The form of the string can be month f l, or f month l, or
1975 * f l month which each evaluate to the same date.
1976 * If f and l are both greater than or equal to 100 the date
1977 * is invalid.
1978 *
1979 * The year is taken to be either l, f if f > 31, or whichever
1980 * is set to zero.
1981 *
1982 * Case 2. The input string is of the form "f/m/l" where f, m and l are
1983 * integers, e.g. 7/16/45. mon, mday and year values are adjusted
1984 * to achieve Chrome compatibility.
1985 *
1986 * a. If 0 < f <= 12 and 0 < l <= 31, f/m/l is interpreted as
1987 * month/day/year.
1988 * b. If 31 < f and 0 < m <= 12 and 0 < l <= 31 f/m/l is
1989 * interpreted as year/month/day
1990 */
1991 if (seenMonthName) {
1992 if (mday >= 100 && mon >= 100) {
1993 return false;
1994 }
1995
1996 if (year > 0 && (mday == 0 || mday > 31) && !seenFullYear) {
1997 int temp = year;
1998 year = mday;
1999 mday = temp;
2000 }
2001
2002 if (mday <= 0 || mday > 31) {
2003 return false;
2004 }
2005
2006 } else if (0 < mon && mon <= 12 && 0 < mday && mday <= 31) {
2007 /* (a) month/day/year */
2008 } else {
2009 /* (b) year/month/day */
2010 if (mon > 31 && mday <= 12 && year <= 31 && !seenFullYear) {
2011 int temp = year;
2012 year = mon;
2013 mon = mday;
2014 mday = temp;
2015 } else {
2016 return false;
2017 }
2018 }
2019
2020 year = FixupYear(year);
2021
2022 if (negativeYear) {
2023 year = -year;
2024 }
2025 }
2026
2027 mon -= 1; /* convert month to 0-based */
2028 if (sec < 0) {
2029 sec = 0;
2030 }
2031 if (min < 0) {
2032 min = 0;
2033 }
2034 if (hour < 0) {
2035 hour = 0;
2036 }
2037
2038 double date =
2039 MakeDate(MakeDay(year, mon, mday), MakeTime(hour, min, sec, msec));
2040
2041 if (tzOffset == -1) { /* no time zone specified, have to use local */
2042 date = UTC(forceUTC, date);
2043 } else {
2044 date += double(tzOffset) * msPerMinute;
2045 }
2046
2047 *result = TimeClip(date);
2048 return true;
2049 }
2050
2051 static bool ParseDate(JSContext* cx, DateTimeInfo::ForceUTC forceUTC,
2052 const JSLinearString* s, ClippedTime* result) {
2053 AutoCheckCannotGC nogc;
2054 // Collect telemetry on how often Date.parse is being used.
2055 // This can be removed in the future, see Bug 1944630.
2056 cx->runtime()->setUseCounter(cx->global(), JSUseCounter::DATEPARSE);
2057 return s->hasLatin1Chars() ? ParseDate(cx, forceUTC, s->latin1Chars(nogc),
2058 s->length(), result)
2059 : ParseDate(cx, forceUTC, s->twoByteChars(nogc),
2060 s->length(), result);
2061 }
2062
2063 /**
2064 * 21.4.3.2 Date.parse ( string )
2065 *
2066 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
2067 */
2068 static bool date_parse(JSContext* cx, unsigned argc, Value* vp) {
2069 AutoJSMethodProfilerEntry pseudoFrame(cx, "Date", "parse");
2070
2071 CallArgs args = CallArgsFromVp(argc, vp);
2072 if (args.length() == 0) {
2073 args.rval().setNaN();
2074 return true;
2075 }
2076
2077 JSString* str = ToString<CanGC>(cx, args[0]);
2078 if (!str) {
2079 return false;
2080 }
2081
2082 JSLinearString* linearStr = str->ensureLinear(cx);
2083 if (!linearStr) {
2084 return false;
2085 }
2086
2087 ClippedTime result;
2088 if (!ParseDate(cx, ForceUTC(cx->realm()), linearStr, &result)) {
2089 args.rval().setNaN();
2090 return true;
2091 }
2092
2093 args.rval().set(TimeValue(result));
2094 return true;
2095 }
2096
2097 static ClippedTime NowAsMillis(JSContext* cx) {
2098 if (js::SupportDifferentialTesting()) {
2099 return TimeClip(0);
2100 }
2101
2102 double now = PRMJ_Now();
2103 bool clampAndJitter = cx->realm()->behaviors().clampAndJitterTime();
2104 if (clampAndJitter && sReduceMicrosecondTimePrecisionCallback) {
2105 now = sReduceMicrosecondTimePrecisionCallback(
2106 now, cx->realm()->behaviors().reduceTimerPrecisionCallerType().value(),
2107 cx);
2108 } else if (clampAndJitter && sResolutionUsec) {
2109 double clamped = floor(now / sResolutionUsec) * sResolutionUsec;
2110
2111 if (sJitter) {
2112 // Calculate a random midpoint for jittering. In the browser, we are
2113 // adversarial: Web Content may try to calculate the midpoint themselves
2114 // and use that to bypass it's security. In the JS Shell, we are not
2115 // adversarial, we want to jitter the time to recreate the operating
2116 // environment, but we do not concern ourselves with trying to prevent an
2117 // attacker from calculating the midpoint themselves. So we use a very
2118 // simple, very fast CRC with a hardcoded seed.
2119
2120 uint64_t midpoint = BitwiseCast<uint64_t>(clamped);
2121 midpoint ^= 0x0F00DD1E2BAD2DED; // XOR in a 'secret'
2122 // MurmurHash3 internal component from
2123 // https://searchfox.org/mozilla-central/rev/61d400da1c692453c2dc2c1cf37b616ce13dea5b/dom/canvas/MurmurHash3.cpp#85
2124 midpoint ^= midpoint >> 33;
2125 midpoint *= uint64_t{0xFF51AFD7ED558CCD};
2126 midpoint ^= midpoint >> 33;
2127 midpoint *= uint64_t{0xC4CEB9FE1A85EC53};
2128 midpoint ^= midpoint >> 33;
2129 midpoint %= sResolutionUsec;
2130
2131 if (now > clamped + midpoint) { // We're jittering up to the next step
2132 now = clamped + sResolutionUsec;
2133 } else { // We're staying at the clamped value
2134 now = clamped;
2135 }
2136 } else { // No jitter, only clamping
2137 now = clamped;
2138 }
2139 }
2140
2141 return TimeClip(now / PRMJ_USEC_PER_MSEC);
2142 }
2143
2144 JS::ClippedTime js::DateNow(JSContext* cx) { return NowAsMillis(cx); }
2145
2146 static bool date_now(JSContext* cx, unsigned argc, Value* vp) {
2147 AutoJSMethodProfilerEntry pseudoFrame(cx, "Date", "now");
2148 CallArgs args = CallArgsFromVp(argc, vp);
2149 args.rval().set(TimeValue(NowAsMillis(cx)));
2150 return true;
2151 }
2152
2153 DateTimeInfo::ForceUTC DateObject::forceUTC() const {
2154 return ForceUTC(realm());
2155 }
2156
2157 void DateObject::setUTCTime(ClippedTime t) {
2158 for (size_t ind = COMPONENTS_START_SLOT; ind < RESERVED_SLOTS; ind++) {
2159 setReservedSlot(ind, UndefinedValue());
2160 }
2161
2162 setFixedSlot(UTC_TIME_SLOT, TimeValue(t));
2163 }
2164
2165 void DateObject::setUTCTime(ClippedTime t, MutableHandleValue vp) {
2166 setUTCTime(t);
2167 vp.set(TimeValue(t));
2168 }
2169
2170 void DateObject::fillLocalTimeSlots() {
2171 const int32_t utcTZOffset =
2172 DateTimeInfo::utcToLocalStandardOffsetSeconds(forceUTC());
2173
2174 /* Check if the cache is already populated. */
2175 if (!getReservedSlot(LOCAL_TIME_SLOT).isUndefined() &&
2176 getReservedSlot(UTC_TIME_ZONE_OFFSET_SLOT).toInt32() == utcTZOffset) {
2177 return;
2178 }
2179
2180 /* Remember time zone used to generate the local cache. */
2181 setReservedSlot(UTC_TIME_ZONE_OFFSET_SLOT, Int32Value(utcTZOffset));
2182
2183 double utcTime = UTCTime().toDouble();
2184
2185 if (!std::isfinite(utcTime)) {
2186 for (size_t ind = COMPONENTS_START_SLOT; ind < RESERVED_SLOTS; ind++) {
2187 setReservedSlot(ind, DoubleValue(utcTime));
2188 }
2189 return;
2190 }
2191
2192 int64_t localTime = LocalTime(forceUTC(), utcTime);
2193
2194 setReservedSlot(LOCAL_TIME_SLOT, DoubleValue(localTime));
2195
2196 const auto [year, month, day] = ToYearMonthDay(localTime);
2197
2198 setReservedSlot(LOCAL_YEAR_SLOT, Int32Value(year));
2199 setReservedSlot(LOCAL_MONTH_SLOT, Int32Value(month));
2200 setReservedSlot(LOCAL_DATE_SLOT, Int32Value(day));
2201
2202 int weekday = WeekDay(localTime);
2203 setReservedSlot(LOCAL_DAY_SLOT, Int32Value(weekday));
2204
2205 int64_t yearStartTime = TimeFromYear(year);
2206 uint64_t yearTime = uint64_t(localTime - yearStartTime);
2207 int32_t yearSeconds = int32_t(yearTime / msPerSecond);
2208 setReservedSlot(LOCAL_SECONDS_INTO_YEAR_SLOT, Int32Value(yearSeconds));
2209 }
2210
2211 /**
2212 * 21.4.4.10 Date.prototype.getTime ( )
2213 *
2214 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
2215 */
2216 static bool date_getTime(JSContext* cx, unsigned argc, Value* vp) {
2217 CallArgs args = CallArgsFromVp(argc, vp);
2218
2219 // Steps 1-2.
2220 auto* unwrapped = UnwrapAndTypeCheckThis<DateObject>(cx, args, "getTime");
2221 if (!unwrapped) {
2222 return false;
2223 }
2224
2225 // Step 3.
2226 args.rval().set(unwrapped->UTCTime());
2227 return true;
2228 }
2229
2230 /**
2231 * B.2.3.1 Date.prototype.getYear ( )
2232 *
2233 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
2234 */
2235 static bool date_getYear(JSContext* cx, unsigned argc, Value* vp) {
2236 CallArgs args = CallArgsFromVp(argc, vp);
2237
2238 // Steps 1-2.
2239 auto* unwrapped = UnwrapAndTypeCheckThis<DateObject>(cx, args, "getYear");
2240 if (!unwrapped) {
2241 return false;
2242 }
2243
2244 // Steps 3-5.
2245 unwrapped->fillLocalTimeSlots();
2246
2247 Value yearVal = unwrapped->localYear();
2248 if (yearVal.isInt32()) {
2249 int year = yearVal.toInt32() - 1900;
2250 args.rval().setInt32(year);
2251 } else {
2252 args.rval().set(yearVal);
2253 }
2254 return true;
2255 }
2256
2257 /**
2258 * 21.4.4.4 Date.prototype.getFullYear ( )
2259 *
2260 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
2261 */
2262 static bool date_getFullYear(JSContext* cx, unsigned argc, Value* vp) {
2263 CallArgs args = CallArgsFromVp(argc, vp);
2264
2265 // Steps 1-2.
2266 auto* unwrapped = UnwrapAndTypeCheckThis<DateObject>(cx, args, "getFullYear");
2267 if (!unwrapped) {
2268 return false;
2269 }
2270
2271 // Steps 3-5.
2272 unwrapped->fillLocalTimeSlots();
2273
2274 args.rval().set(unwrapped->localYear());
2275 return true;
2276 }
2277
2278 /**
2279 * 21.4.4.18 Date.prototype.getUTCMonth ( )
2280 *
2281 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
2282 */
2283 static bool date_getUTCFullYear(JSContext* cx, unsigned argc, Value* vp) {
2284 CallArgs args = CallArgsFromVp(argc, vp);
2285
2286 // Steps 1-2.
2287 auto* unwrapped =
2288 UnwrapAndTypeCheckThis<DateObject>(cx, args, "getUTCFullYear");
2289 if (!unwrapped) {
2290 return false;
2291 }
2292
2293 // Step 3.
2294 double t = unwrapped->UTCTime().toDouble();
2295 MOZ_ASSERT(IsTimeValue(t));
2296
2297 // Step 4.
2298 if (std::isnan(t)) {
2299 args.rval().setNaN();
2300 return true;
2301 }
2302 int64_t tv = static_cast<int64_t>(t);
2303
2304 // Step 5.
2305 args.rval().setInt32(::YearFromTime(tv));
2306 return true;
2307 }
2308
2309 /**
2310 * 21.4.4.8 Date.prototype.getMonth ( )
2311 *
2312 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
2313 */
2314 static bool date_getMonth(JSContext* cx, unsigned argc, Value* vp) {
2315 CallArgs args = CallArgsFromVp(argc, vp);
2316
2317 // Steps 1-2.
2318 auto* unwrapped = UnwrapAndTypeCheckThis<DateObject>(cx, args, "getMonth");
2319 if (!unwrapped) {
2320 return false;
2321 }
2322
2323 // Steps 3-5.
2324 unwrapped->fillLocalTimeSlots();
2325
2326 args.rval().set(unwrapped->localMonth());
2327 return true;
2328 }
2329
2330 /**
2331 * 21.4.4.18 Date.prototype.getUTCMonth ( )
2332 *
2333 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
2334 */
2335 static bool date_getUTCMonth(JSContext* cx, unsigned argc, Value* vp) {
2336 CallArgs args = CallArgsFromVp(argc, vp);
2337
2338 // Steps 1-2.
2339 auto* unwrapped = UnwrapAndTypeCheckThis<DateObject>(cx, args, "getUTCMonth");
2340 if (!unwrapped) {
2341 return false;
2342 }
2343
2344 // Step 3.
2345 double t = unwrapped->UTCTime().toDouble();
2346 MOZ_ASSERT(IsTimeValue(t));
2347
2348 // Step 4.
2349 if (std::isnan(t)) {
2350 args.rval().setNaN();
2351 return true;
2352 }
2353 int64_t tv = static_cast<int64_t>(t);
2354
2355 // Step 5.
2356 args.rval().setInt32(::MonthFromTime(tv));
2357 return true;
2358 }
2359
2360 /**
2361 * 21.4.4.2 Date.prototype.getDate ( )
2362 *
2363 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
2364 */
2365 static bool date_getDate(JSContext* cx, unsigned argc, Value* vp) {
2366 CallArgs args = CallArgsFromVp(argc, vp);
2367
2368 // Steps 1-2.
2369 auto* unwrapped = UnwrapAndTypeCheckThis<DateObject>(cx, args, "getDate");
2370 if (!unwrapped) {
2371 return false;
2372 }
2373
2374 // Steps 3-5.
2375 unwrapped->fillLocalTimeSlots();
2376
2377 args.rval().set(unwrapped->localDate());
2378 return true;
2379 }
2380
2381 /**
2382 * 21.4.4.12 Date.prototype.getUTCDate ( )
2383 *
2384 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
2385 */
2386 static bool date_getUTCDate(JSContext* cx, unsigned argc, Value* vp) {
2387 CallArgs args = CallArgsFromVp(argc, vp);
2388
2389 // Steps 1-2.
2390 auto* unwrapped = UnwrapAndTypeCheckThis<DateObject>(cx, args, "getUTCDate");
2391 if (!unwrapped) {
2392 return false;
2393 }
2394
2395 // Step 3.
2396 double t = unwrapped->UTCTime().toDouble();
2397 MOZ_ASSERT(IsTimeValue(t));
2398
2399 // Step 4.
2400 if (std::isnan(t)) {
2401 args.rval().setNaN();
2402 return true;
2403 }
2404 int64_t tv = static_cast<int64_t>(t);
2405
2406 // Step 5.
2407 args.rval().setInt32(DateFromTime(tv));
2408 return true;
2409 }
2410
2411 /**
2412 * 21.4.4.3 Date.prototype.getDay ( )
2413 *
2414 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
2415 */
2416 static bool date_getDay(JSContext* cx, unsigned argc, Value* vp) {
2417 CallArgs args = CallArgsFromVp(argc, vp);
2418
2419 // Steps 1-2.
2420 auto* unwrapped = UnwrapAndTypeCheckThis<DateObject>(cx, args, "getDay");
2421 if (!unwrapped) {
2422 return false;
2423 }
2424
2425 // Steps 3-5.
2426 unwrapped->fillLocalTimeSlots();
2427
2428 args.rval().set(unwrapped->localDay());
2429 return true;
2430 }
2431
2432 /**
2433 * 21.4.4.13 Date.prototype.getUTCDay ( )
2434 *
2435 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
2436 */
2437 static bool date_getUTCDay(JSContext* cx, unsigned argc, Value* vp) {
2438 CallArgs args = CallArgsFromVp(argc, vp);
2439
2440 // Steps 1-2.
2441 auto* unwrapped = UnwrapAndTypeCheckThis<DateObject>(cx, args, "getUTCDay");
2442 if (!unwrapped) {
2443 return false;
2444 }
2445
2446 // Step 3.
2447 double t = unwrapped->UTCTime().toDouble();
2448 MOZ_ASSERT(IsTimeValue(t));
2449
2450 // Step 4.
2451 if (std::isnan(t)) {
2452 args.rval().setNaN();
2453 return true;
2454 }
2455 int64_t tv = static_cast<int64_t>(t);
2456
2457 // Step 5.
2458 args.rval().setInt32(WeekDay(tv));
2459 return true;
2460 }
2461
2462 /**
2463 * 21.4.4.5 Date.prototype.getHours ( )
2464 *
2465 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
2466 */
2467 static bool date_getHours(JSContext* cx, unsigned argc, Value* vp) {
2468 CallArgs args = CallArgsFromVp(argc, vp);
2469
2470 // Steps 1-2.
2471 auto* unwrapped = UnwrapAndTypeCheckThis<DateObject>(cx, args, "getHours");
2472 if (!unwrapped) {
2473 return false;
2474 }
2475
2476 // Steps 3-5.
2477 unwrapped->fillLocalTimeSlots();
2478
2479 // Note: localSecondsIntoYear is guaranteed to return an
2480 // int32 or NaN after the call to fillLocalTimeSlots.
2481 Value yearSeconds = unwrapped->localSecondsIntoYear();
2482 if (yearSeconds.isDouble()) {
2483 MOZ_ASSERT(std::isnan(yearSeconds.toDouble()));
2484 args.rval().set(yearSeconds);
2485 } else {
2486 args.rval().setInt32((yearSeconds.toInt32() / SecondsPerHour) %
2487 HoursPerDay);
2488 }
2489 return true;
2490 }
2491
2492 /**
2493 * 21.4.4.15 Date.prototype.getUTCHours ( )
2494 *
2495 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
2496 */
2497 static bool date_getUTCHours(JSContext* cx, unsigned argc, Value* vp) {
2498 CallArgs args = CallArgsFromVp(argc, vp);
2499
2500 // Steps 1-2.
2501 auto* unwrapped = UnwrapAndTypeCheckThis<DateObject>(cx, args, "getUTCHours");
2502 if (!unwrapped) {
2503 return false;
2504 }
2505
2506 // Step 3.
2507 double t = unwrapped->UTCTime().toDouble();
2508 MOZ_ASSERT(IsTimeValue(t));
2509
2510 // Step 4.
2511 if (std::isnan(t)) {
2512 args.rval().setNaN();
2513 return true;
2514 }
2515 int64_t tv = static_cast<int64_t>(t);
2516
2517 // Step 5.
2518 args.rval().setInt32(HourFromTime(tv));
2519 return true;
2520 }
2521
2522 /**
2523 * 21.4.4.7 Date.prototype.getMinutes ( )
2524 *
2525 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
2526 */
2527 static bool date_getMinutes(JSContext* cx, unsigned argc, Value* vp) {
2528 CallArgs args = CallArgsFromVp(argc, vp);
2529
2530 // Steps 1-2.
2531 auto* unwrapped = UnwrapAndTypeCheckThis<DateObject>(cx, args, "getMinutes");
2532 if (!unwrapped) {
2533 return false;
2534 }
2535
2536 // Steps 3-5.
2537 unwrapped->fillLocalTimeSlots();
2538
2539 // Note: localSecondsIntoYear is guaranteed to return an
2540 // int32 or NaN after the call to fillLocalTimeSlots.
2541 Value yearSeconds = unwrapped->localSecondsIntoYear();
2542 if (yearSeconds.isDouble()) {
2543 MOZ_ASSERT(std::isnan(yearSeconds.toDouble()));
2544 args.rval().set(yearSeconds);
2545 } else {
2546 args.rval().setInt32((yearSeconds.toInt32() / SecondsPerMinute) %
2547 MinutesPerHour);
2548 }
2549 return true;
2550 }
2551
2552 /**
2553 * 21.4.4.17 Date.prototype.getUTCMinutes ( )
2554 *
2555 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
2556 */
2557 static bool date_getUTCMinutes(JSContext* cx, unsigned argc, Value* vp) {
2558 CallArgs args = CallArgsFromVp(argc, vp);
2559
2560 // Steps 1-2.
2561 auto* unwrapped =
2562 UnwrapAndTypeCheckThis<DateObject>(cx, args, "getUTCMinutes");
2563 if (!unwrapped) {
2564 return false;
2565 }
2566
2567 // Step 3.
2568 double t = unwrapped->UTCTime().toDouble();
2569 MOZ_ASSERT(IsTimeValue(t));
2570
2571 // Step 4.
2572 if (std::isnan(t)) {
2573 args.rval().setNaN();
2574 return true;
2575 }
2576 int64_t tv = static_cast<int64_t>(t);
2577
2578 // Step 5.
2579 args.rval().setInt32(MinFromTime(tv));
2580 return true;
2581 }
2582
2583 /**
2584 * 21.4.4.9 Date.prototype.getSeconds ( )
2585 *
2586 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
2587 */
2588 static bool date_getSeconds(JSContext* cx, unsigned argc, Value* vp) {
2589 CallArgs args = CallArgsFromVp(argc, vp);
2590
2591 // Steps 1-2.
2592 auto* unwrapped = UnwrapAndTypeCheckThis<DateObject>(cx, args, "getSeconds");
2593 if (!unwrapped) {
2594 return false;
2595 }
2596
2597 // Steps 3-5.
2598 unwrapped->fillLocalTimeSlots();
2599
2600 // Note: localSecondsIntoYear is guaranteed to return an
2601 // int32 or NaN after the call to fillLocalTimeSlots.
2602 Value yearSeconds = unwrapped->localSecondsIntoYear();
2603 if (yearSeconds.isDouble()) {
2604 MOZ_ASSERT(std::isnan(yearSeconds.toDouble()));
2605 args.rval().set(yearSeconds);
2606 } else {
2607 args.rval().setInt32(yearSeconds.toInt32() % SecondsPerMinute);
2608 }
2609 return true;
2610 }
2611
2612 /**
2613 * 21.4.4.19 Date.prototype.getUTCSeconds ( )
2614 *
2615 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
2616 */
2617 static bool date_getUTCSeconds(JSContext* cx, unsigned argc, Value* vp) {
2618 CallArgs args = CallArgsFromVp(argc, vp);
2619
2620 // Steps 1-2.
2621 auto* unwrapped =
2622 UnwrapAndTypeCheckThis<DateObject>(cx, args, "getUTCSeconds");
2623 if (!unwrapped) {
2624 return false;
2625 }
2626
2627 // Step 3.
2628 double t = unwrapped->UTCTime().toDouble();
2629 MOZ_ASSERT(IsTimeValue(t));
2630
2631 // Step 4.
2632 if (std::isnan(t)) {
2633 args.rval().setNaN();
2634 return true;
2635 }
2636 int64_t tv = static_cast<int64_t>(t);
2637
2638 // Step 5.
2639 args.rval().setInt32(SecFromTime(tv));
2640 return true;
2641 }
2642
2643 /*
2644 * Date.getMilliseconds is mapped to getUTCMilliseconds. As long as no
2645 * supported time zone has a fractional-second component, the differences in
2646 * their specifications aren't observable.
2647 *
2648 * The 'tz' database explicitly does not support fractional-second time zones.
2649 * For example the Netherlands observed Amsterdam Mean Time, estimated to be
2650 * UT +00:19:32.13, from 1909 to 1937, but in tzdata AMT is defined as exactly
2651 * UT +00:19:32.
2652 */
2653
2654 /**
2655 * 21.4.4.6 Date.prototype.getMilliseconds ( )
2656 * 21.4.4.16 Date.prototype.getUTCMilliseconds ( )
2657 *
2658 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
2659 */
2660 static bool getMilliseconds(JSContext* cx, unsigned argc, Value* vp,
2661 const char* methodName) {
2662 CallArgs args = CallArgsFromVp(argc, vp);
2663
2664 // Steps 1-2.
2665 auto* unwrapped = UnwrapAndTypeCheckThis<DateObject>(cx, args, methodName);
2666 if (!unwrapped) {
2667 return false;
2668 }
2669
2670 // Step 3.
2671 double t = unwrapped->UTCTime().toDouble();
2672 MOZ_ASSERT(IsTimeValue(t));
2673
2674 // Step 4.
2675 if (std::isnan(t)) {
2676 args.rval().setNaN();
2677 return true;
2678 }
2679 int64_t tv = static_cast<int64_t>(t);
2680
2681 // Step 5.
2682 args.rval().setInt32(msFromTime(tv));
2683 return true;
2684 }
2685
2686 static bool date_getMilliseconds(JSContext* cx, unsigned argc, Value* vp) {
2687 return getMilliseconds(cx, argc, vp, "getMilliseconds");
2688 }
2689
2690 static bool date_getUTCMilliseconds(JSContext* cx, unsigned argc, Value* vp) {
2691 return getMilliseconds(cx, argc, vp, "getUTCMilliseconds");
2692 }
2693
2694 /**
2695 * 21.4.4.11 Date.prototype.getTimezoneOffset ( )
2696 *
2697 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
2698 */
2699 static bool date_getTimezoneOffset(JSContext* cx, unsigned argc, Value* vp) {
2700 CallArgs args = CallArgsFromVp(argc, vp);
2701
2702 // Steps 1-2.
2703 auto* unwrapped =
2704 UnwrapAndTypeCheckThis<DateObject>(cx, args, "getTimezoneOffset");
2705 if (!unwrapped) {
2706 return false;
2707 }
2708
2709 // Steps 3-5.
2710 unwrapped->fillLocalTimeSlots();
2711
2712 double utctime = unwrapped->UTCTime().toDouble();
2713 double localtime = unwrapped->localTime().toDouble();
2714
2715 /*
2716 * Return the time zone offset in minutes for the current locale that is
2717 * appropriate for this time. This value would be a constant except for
2718 * daylight savings time.
2719 */
2720 double result = (utctime - localtime) / double(msPerMinute);
2721 args.rval().setNumber(result);
2722 return true;
2723 }
2724
2725 /**
2726 * 21.4.4.27 Date.prototype.setTime ( time )
2727 *
2728 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
2729 */
2730 static bool date_setTime(JSContext* cx, unsigned argc, Value* vp) {
2731 CallArgs args = CallArgsFromVp(argc, vp);
2732
2733 // Steps 1-2.
2734 Rooted<DateObject*> unwrapped(
2735 cx, UnwrapAndTypeCheckThis<DateObject>(cx, args, "setTime"));
2736 if (!unwrapped) {
2737 return false;
2738 }
2739
2740 // Step 3.
2741 double result;
2742 if (!ToNumber(cx, args.get(0), &result)) {
2743 return false;
2744 }
2745
2746 // Steps 4-6.
2747 unwrapped->setUTCTime(TimeClip(result), args.rval());
2748 return true;
2749 }
2750
2751 /**
2752 * 21.4.4.23 Date.prototype.setMilliseconds ( ms )
2753 *
2754 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
2755 */
2756 static bool date_setMilliseconds(JSContext* cx, unsigned argc, Value* vp) {
2757 CallArgs args = CallArgsFromVp(argc, vp);
2758
2759 // Steps 1-2.
2760 Rooted<DateObject*> unwrapped(
2761 cx, UnwrapAndTypeCheckThis<DateObject>(cx, args, "setMilliseconds"));
2762 if (!unwrapped) {
2763 return false;
2764 }
2765
2766 // Step 3.
2767 double t = unwrapped->UTCTime().toDouble();
2768 MOZ_ASSERT(IsTimeValue(t));
2769
2770 // Step 4.
2771 double ms;
2772 if (!ToNumber(cx, args.get(0), &ms)) {
2773 return false;
2774 }
2775
2776 // Step 5.
2777 if (std::isnan(t)) {
2778 args.rval().setNaN();
2779 return true;
2780 }
2781
2782 // Step 6.
2783 int64_t tv = LocalTime(unwrapped->forceUTC(), t);
2784
2785 // Step 7.
2786 double time =
2787 MakeTime(HourFromTime(tv), MinFromTime(tv), SecFromTime(tv), ms);
2788
2789 // Step 8.
2790 ClippedTime u = TimeClip(UTC(unwrapped->forceUTC(), MakeDate(Day(tv), time)));
2791
2792 // Steps 9-10.
2793 unwrapped->setUTCTime(u, args.rval());
2794 return true;
2795 }
2796
2797 /**
2798 * 21.4.4.31 Date.prototype.setUTCMilliseconds ( ms )
2799 *
2800 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
2801 */
2802 static bool date_setUTCMilliseconds(JSContext* cx, unsigned argc, Value* vp) {
2803 CallArgs args = CallArgsFromVp(argc, vp);
2804
2805 // Steps 1-2.
2806 Rooted<DateObject*> unwrapped(
2807 cx, UnwrapAndTypeCheckThis<DateObject>(cx, args, "setUTCMilliseconds"));
2808 if (!unwrapped) {
2809 return false;
2810 }
2811
2812 // Step 3.
2813 double t = unwrapped->UTCTime().toDouble();
2814 MOZ_ASSERT(IsTimeValue(t));
2815
2816 // Step 4.
2817 double milli;
2818 if (!ToNumber(cx, args.get(0), &milli)) {
2819 return false;
2820 }
2821
2822 // Step 5.
2823 if (std::isnan(t)) {
2824 args.rval().setNaN();
2825 return true;
2826 }
2827 int64_t tv = static_cast<int64_t>(t);
2828
2829 // Step 6.
2830 double time =
2831 MakeTime(HourFromTime(tv), MinFromTime(tv), SecFromTime(tv), milli);
2832
2833 // Step 7.
2834 ClippedTime v = TimeClip(MakeDate(Day(tv), time));
2835
2836 // Steps 8-9.
2837 unwrapped->setUTCTime(v, args.rval());
2838 return true;
2839 }
2840
2841 /**
2842 * 21.4.4.26 Date.prototype.setSeconds ( sec [ , ms ] )
2843 *
2844 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
2845 */
2846 static bool date_setSeconds(JSContext* cx, unsigned argc, Value* vp) {
2847 CallArgs args = CallArgsFromVp(argc, vp);
2848
2849 // Steps 1-2.
2850 Rooted<DateObject*> unwrapped(
2851 cx, UnwrapAndTypeCheckThis<DateObject>(cx, args, "setSeconds"));
2852 if (!unwrapped) {
2853 return false;
2854 }
2855
2856 // Step 3.
2857 double t = unwrapped->UTCTime().toDouble();
2858 MOZ_ASSERT(IsTimeValue(t));
2859
2860 // Step 4.
2861 double s;
2862 if (!ToNumber(cx, args.get(0), &s)) {
2863 return false;
2864 }
2865
2866 // Step 5.
2867 double milli;
2868 if (args.length() > 1 && !ToNumber(cx, args[1], &milli)) {
2869 return false;
2870 }
2871
2872 // Step 6.
2873 if (std::isnan(t)) {
2874 args.rval().setNaN();
2875 return true;
2876 }
2877
2878 // Step 7.
2879 int64_t tv = LocalTime(unwrapped->forceUTC(), t);
2880
2881 // Step 8.
2882 if (args.length() <= 1) {
2883 milli = msFromTime(tv);
2884 }
2885
2886 // Step 9.
2887 double date =
2888 MakeDate(Day(tv), MakeTime(HourFromTime(tv), MinFromTime(tv), s, milli));
2889
2890 // Step 10.
2891 ClippedTime u = TimeClip(UTC(unwrapped->forceUTC(), date));
2892
2893 // Steps 11-12.
2894 unwrapped->setUTCTime(u, args.rval());
2895 return true;
2896 }
2897
2898 /**
2899 * 21.4.4.34 Date.prototype.setUTCSeconds ( sec [ , ms ] )
2900 *
2901 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
2902 */
2903 static bool date_setUTCSeconds(JSContext* cx, unsigned argc, Value* vp) {
2904 CallArgs args = CallArgsFromVp(argc, vp);
2905
2906 // Steps 1-2.
2907 Rooted<DateObject*> unwrapped(
2908 cx, UnwrapAndTypeCheckThis<DateObject>(cx, args, "setUTCSeconds"));
2909 if (!unwrapped) {
2910 return false;
2911 }
2912
2913 // Step 3.
2914 double t = unwrapped->UTCTime().toDouble();
2915 MOZ_ASSERT(IsTimeValue(t));
2916
2917 // Step 4.
2918 double s;
2919 if (!ToNumber(cx, args.get(0), &s)) {
2920 return false;
2921 }
2922
2923 // Step 5.
2924 double milli;
2925 if (args.length() > 1 && !ToNumber(cx, args[1], &milli)) {
2926 return false;
2927 }
2928
2929 // Step 6.
2930 if (std::isnan(t)) {
2931 args.rval().setNaN();
2932 return true;
2933 }
2934 int64_t tv = static_cast<int64_t>(t);
2935
2936 // Step 7.
2937 if (args.length() <= 1) {
2938 milli = msFromTime(tv);
2939 }
2940
2941 // Step 8.
2942 double date =
2943 MakeDate(Day(tv), MakeTime(HourFromTime(tv), MinFromTime(tv), s, milli));
2944
2945 // Step 9.
2946 ClippedTime v = TimeClip(date);
2947
2948 // Steps 10-11.
2949 unwrapped->setUTCTime(v, args.rval());
2950 return true;
2951 }
2952
2953 /**
2954 * 21.4.4.24 Date.prototype.setMinutes ( min [ , sec [ , ms ] ] )
2955 *
2956 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
2957 */
2958 static bool date_setMinutes(JSContext* cx, unsigned argc, Value* vp) {
2959 CallArgs args = CallArgsFromVp(argc, vp);
2960
2961 // Steps 1-2.
2962 Rooted<DateObject*> unwrapped(
2963 cx, UnwrapAndTypeCheckThis<DateObject>(cx, args, "setMinutes"));
2964 if (!unwrapped) {
2965 return false;
2966 }
2967
2968 // Step 3.
2969 double t = unwrapped->UTCTime().toDouble();
2970 MOZ_ASSERT(IsTimeValue(t));
2971
2972 // Step 4.
2973 double m;
2974 if (!ToNumber(cx, args.get(0), &m)) {
2975 return false;
2976 }
2977
2978 // Step 5.
2979 double s;
2980 if (args.length() > 1 && !ToNumber(cx, args[1], &s)) {
2981 return false;
2982 }
2983
2984 // Step 6.
2985 double milli;
2986 if (args.length() > 2 && !ToNumber(cx, args[2], &milli)) {
2987 return false;
2988 }
2989
2990 // Step 7.
2991 if (std::isnan(t)) {
2992 args.rval().setNaN();
2993 return true;
2994 }
2995
2996 // Step 8.
2997 int64_t tv = LocalTime(unwrapped->forceUTC(), t);
2998
2999 // Step 9.
3000 if (args.length() <= 1) {
3001 s = SecFromTime(tv);
3002 }
3003
3004 // Step 10.
3005 if (args.length() <= 2) {
3006 milli = msFromTime(tv);
3007 }
3008
3009 // Step 11.
3010 double date = MakeDate(Day(tv), MakeTime(HourFromTime(tv), m, s, milli));
3011
3012 // Step 12.
3013 ClippedTime u = TimeClip(UTC(unwrapped->forceUTC(), date));
3014
3015 // Steps 13-14.
3016 unwrapped->setUTCTime(u, args.rval());
3017 return true;
3018 }
3019
3020 /**
3021 * 21.4.4.32 Date.prototype.setUTCMinutes ( min [ , sec [ , ms ] ] )
3022 *
3023 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
3024 */
3025 static bool date_setUTCMinutes(JSContext* cx, unsigned argc, Value* vp) {
3026 CallArgs args = CallArgsFromVp(argc, vp);
3027
3028 // Steps 1-2.
3029 Rooted<DateObject*> unwrapped(
3030 cx, UnwrapAndTypeCheckThis<DateObject>(cx, args, "setUTCMinutes"));
3031 if (!unwrapped) {
3032 return false;
3033 }
3034
3035 // Step 3.
3036 double t = unwrapped->UTCTime().toDouble();
3037 MOZ_ASSERT(IsTimeValue(t));
3038
3039 // Step 4.
3040 double m;
3041 if (!ToNumber(cx, args.get(0), &m)) {
3042 return false;
3043 }
3044
3045 // Step 5.
3046 double s;
3047 if (args.length() > 1 && !ToNumber(cx, args[1], &s)) {
3048 return false;
3049 }
3050
3051 // Step 6.
3052 double milli;
3053 if (args.length() > 2 && !ToNumber(cx, args[2], &milli)) {
3054 return false;
3055 }
3056
3057 // Step 7.
3058 if (std::isnan(t)) {
3059 args.rval().setNaN();
3060 return true;
3061 }
3062 int64_t tv = static_cast<int64_t>(t);
3063
3064 // Step 8.
3065 if (args.length() <= 1) {
3066 s = SecFromTime(tv);
3067 }
3068
3069 // Step 9.
3070 if (args.length() <= 2) {
3071 milli = msFromTime(tv);
3072 }
3073
3074 // Step 10.
3075 double date = MakeDate(Day(tv), MakeTime(HourFromTime(tv), m, s, milli));
3076
3077 // Step 11.
3078 ClippedTime v = TimeClip(date);
3079
3080 // Steps 12-13.
3081 unwrapped->setUTCTime(v, args.rval());
3082 return true;
3083 }
3084
3085 /**
3086 * 21.4.4.22 Date.prototype.setHours ( hour [ , min [ , sec [ , ms ] ] ] )
3087 *
3088 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
3089 */
3090 static bool date_setHours(JSContext* cx, unsigned argc, Value* vp) {
3091 CallArgs args = CallArgsFromVp(argc, vp);
3092
3093 // Steps 1-2.
3094 Rooted<DateObject*> unwrapped(
3095 cx, UnwrapAndTypeCheckThis<DateObject>(cx, args, "setHours"));
3096 if (!unwrapped) {
3097 return false;
3098 }
3099
3100 // Step 3.
3101 double t = unwrapped->UTCTime().toDouble();
3102 MOZ_ASSERT(IsTimeValue(t));
3103
3104 // Step 4.
3105 double h;
3106 if (!ToNumber(cx, args.get(0), &h)) {
3107 return false;
3108 }
3109
3110 // Step 5.
3111 double m;
3112 if (args.length() > 1 && !ToNumber(cx, args[1], &m)) {
3113 return false;
3114 }
3115
3116 // Step 6.
3117 double s;
3118 if (args.length() > 2 && !ToNumber(cx, args[2], &s)) {
3119 return false;
3120 }
3121
3122 // Step 7.
3123 double milli;
3124 if (args.length() > 3 && !ToNumber(cx, args[3], &milli)) {
3125 return false;
3126 }
3127
3128 // Step 8.
3129 if (std::isnan(t)) {
3130 args.rval().setNaN();
3131 return true;
3132 }
3133
3134 // Step 9.
3135 int64_t tv = LocalTime(unwrapped->forceUTC(), t);
3136
3137 // Step 10.
3138 if (args.length() <= 1) {
3139 m = MinFromTime(tv);
3140 }
3141
3142 // Step 11.
3143 if (args.length() <= 2) {
3144 s = SecFromTime(tv);
3145 }
3146
3147 // Step 12.
3148 if (args.length() <= 3) {
3149 milli = msFromTime(tv);
3150 }
3151
3152 // Step 13.
3153 double date = MakeDate(Day(tv), MakeTime(h, m, s, milli));
3154
3155 // Step 14.
3156 ClippedTime u = TimeClip(UTC(unwrapped->forceUTC(), date));
3157
3158 // Steps 15-16.
3159 unwrapped->setUTCTime(u, args.rval());
3160 return true;
3161 }
3162
3163 /**
3164 * 21.4.4.30 Date.prototype.setUTCHours ( hour [ , min [ , sec [ , ms ] ] ] )
3165 *
3166 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
3167 */
3168 static bool date_setUTCHours(JSContext* cx, unsigned argc, Value* vp) {
3169 CallArgs args = CallArgsFromVp(argc, vp);
3170
3171 // Steps 1-2.
3172 Rooted<DateObject*> unwrapped(
3173 cx, UnwrapAndTypeCheckThis<DateObject>(cx, args, "setUTCHours"));
3174 if (!unwrapped) {
3175 return false;
3176 }
3177
3178 // Step 3.
3179 double t = unwrapped->UTCTime().toDouble();
3180 MOZ_ASSERT(IsTimeValue(t));
3181
3182 // Step 4.
3183 double h;
3184 if (!ToNumber(cx, args.get(0), &h)) {
3185 return false;
3186 }
3187
3188 // Step 5.
3189 double m;
3190 if (args.length() > 1 && !ToNumber(cx, args[1], &m)) {
3191 return false;
3192 }
3193
3194 // Step 6.
3195 double s;
3196 if (args.length() > 2 && !ToNumber(cx, args[2], &s)) {
3197 return false;
3198 }
3199
3200 // Step 7.
3201 double milli;
3202 if (args.length() > 3 && !ToNumber(cx, args[3], &milli)) {
3203 return false;
3204 }
3205
3206 // Step 8.
3207 if (std::isnan(t)) {
3208 args.rval().setNaN();
3209 return true;
3210 }
3211 int64_t tv = static_cast<int64_t>(t);
3212
3213 // Step 9.
3214 if (args.length() <= 1) {
3215 m = MinFromTime(tv);
3216 }
3217
3218 // Step 10.
3219 if (args.length() <= 2) {
3220 s = SecFromTime(tv);
3221 }
3222
3223 // Step 11.
3224 if (args.length() <= 3) {
3225 milli = msFromTime(tv);
3226 }
3227
3228 // Step 12.
3229 double date = MakeDate(Day(tv), MakeTime(h, m, s, milli));
3230
3231 // Step 13.
3232 ClippedTime v = TimeClip(date);
3233
3234 // Steps 14-15.
3235 unwrapped->setUTCTime(v, args.rval());
3236 return true;
3237 }
3238
3239 /**
3240 * 21.4.4.20 Date.prototype.setDate ( date )
3241 *
3242 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
3243 */
3244 static bool date_setDate(JSContext* cx, unsigned argc, Value* vp) {
3245 CallArgs args = CallArgsFromVp(argc, vp);
3246
3247 // Steps 1-2.
3248 Rooted<DateObject*> unwrapped(
3249 cx, UnwrapAndTypeCheckThis<DateObject>(cx, args, "setDate"));
3250 if (!unwrapped) {
3251 return false;
3252 }
3253
3254 // Step 3.
3255 double t = unwrapped->UTCTime().toDouble();
3256 MOZ_ASSERT(IsTimeValue(t));
3257
3258 // Step 4.
3259 double dt;
3260 if (!ToNumber(cx, args.get(0), &dt)) {
3261 return false;
3262 }
3263
3264 // Step 5.
3265 if (std::isnan(t)) {
3266 args.rval().setNaN();
3267 return true;
3268 }
3269
3270 // Step 6.
3271 int64_t tv = LocalTime(unwrapped->forceUTC(), t);
3272
3273 // Step 7.
3274 double newDate = MakeDate(
3275 MakeDay(::YearFromTime(tv), ::MonthFromTime(tv), dt), TimeWithinDay(tv));
3276
3277 // Step 8.
3278 ClippedTime u = TimeClip(UTC(unwrapped->forceUTC(), newDate));
3279
3280 // Steps 9-10.
3281 unwrapped->setUTCTime(u, args.rval());
3282 return true;
3283 }
3284
3285 /**
3286 * 21.4.4.28 Date.prototype.setUTCDate ( date )
3287 *
3288 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
3289 */
3290 static bool date_setUTCDate(JSContext* cx, unsigned argc, Value* vp) {
3291 CallArgs args = CallArgsFromVp(argc, vp);
3292
3293 // Steps 1-2.
3294 Rooted<DateObject*> unwrapped(
3295 cx, UnwrapAndTypeCheckThis<DateObject>(cx, args, "setUTCDate"));
3296 if (!unwrapped) {
3297 return false;
3298 }
3299
3300 // Step 3.
3301 double t = unwrapped->UTCTime().toDouble();
3302 MOZ_ASSERT(IsTimeValue(t));
3303
3304 // Step 4.
3305 double dt;
3306 if (!ToNumber(cx, args.get(0), &dt)) {
3307 return false;
3308 }
3309
3310 // Step 5.
3311 if (std::isnan(t)) {
3312 args.rval().setNaN();
3313 return true;
3314 }
3315 int64_t tv = static_cast<int64_t>(t);
3316
3317 // Step 6.
3318 double newDate = MakeDate(
3319 MakeDay(::YearFromTime(tv), ::MonthFromTime(tv), dt), TimeWithinDay(tv));
3320
3321 // Step 7.
3322 ClippedTime v = TimeClip(newDate);
3323
3324 // Steps 8-9.
3325 unwrapped->setUTCTime(v, args.rval());
3326 return true;
3327 }
3328
3329 /**
3330 * 21.4.4.25 Date.prototype.setMonth ( month [ , date ] )
3331 *
3332 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
3333 */
3334 static bool date_setMonth(JSContext* cx, unsigned argc, Value* vp) {
3335 CallArgs args = CallArgsFromVp(argc, vp);
3336
3337 // Steps 1-2.
3338 Rooted<DateObject*> unwrapped(
3339 cx, UnwrapAndTypeCheckThis<DateObject>(cx, args, "setMonth"));
3340 if (!unwrapped) {
3341 return false;
3342 }
3343
3344 // Step 3.
3345 double t = unwrapped->UTCTime().toDouble();
3346 MOZ_ASSERT(IsTimeValue(t));
3347
3348 // Step 4.
3349 double m;
3350 if (!ToNumber(cx, args.get(0), &m)) {
3351 return false;
3352 }
3353
3354 // Step 5.
3355 double dt;
3356 if (args.length() > 1 && !ToNumber(cx, args[1], &dt)) {
3357 return false;
3358 }
3359
3360 // Step 6.
3361 if (std::isnan(t)) {
3362 args.rval().setNaN();
3363 return true;
3364 }
3365
3366 // Step 7.
3367 int64_t tv = LocalTime(unwrapped->forceUTC(), t);
3368
3369 // Step 8.
3370 if (args.length() <= 1) {
3371 dt = DateFromTime(tv);
3372 }
3373
3374 // Step 9.
3375 double newDate =
3376 MakeDate(MakeDay(::YearFromTime(tv), m, dt), TimeWithinDay(tv));
3377
3378 // Step 10
3379 ClippedTime u = TimeClip(UTC(unwrapped->forceUTC(), newDate));
3380
3381 // Steps 11-12.
3382 unwrapped->setUTCTime(u, args.rval());
3383 return true;
3384 }
3385
3386 /**
3387 * 21.4.4.33 Date.prototype.setUTCMonth ( month [ , date ] )
3388 *
3389 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
3390 */
3391 static bool date_setUTCMonth(JSContext* cx, unsigned argc, Value* vp) {
3392 CallArgs args = CallArgsFromVp(argc, vp);
3393
3394 // Steps 1-2.
3395 Rooted<DateObject*> unwrapped(
3396 cx, UnwrapAndTypeCheckThis<DateObject>(cx, args, "setUTCMonth"));
3397 if (!unwrapped) {
3398 return false;
3399 }
3400
3401 // Step 3.
3402 double t = unwrapped->UTCTime().toDouble();
3403 MOZ_ASSERT(IsTimeValue(t));
3404
3405 // Step 4.
3406 double m;
3407 if (!ToNumber(cx, args.get(0), &m)) {
3408 return false;
3409 }
3410
3411 // Step 5.
3412 double dt;
3413 if (args.length() > 1 && !ToNumber(cx, args[1], &dt)) {
3414 return false;
3415 }
3416
3417 // Step 6.
3418 if (std::isnan(t)) {
3419 args.rval().setNaN();
3420 return true;
3421 }
3422 int64_t tv = static_cast<int64_t>(t);
3423
3424 // Step 7.
3425 if (args.length() <= 1) {
3426 dt = DateFromTime(tv);
3427 }
3428
3429 // Step 8.
3430 double newDate =
3431 MakeDate(MakeDay(::YearFromTime(tv), m, dt), TimeWithinDay(tv));
3432
3433 // Step 9.
3434 ClippedTime v = TimeClip(newDate);
3435
3436 // Steps 10-11.
3437 unwrapped->setUTCTime(v, args.rval());
3438 return true;
3439 }
3440
3441 /**
3442 * 21.4.4.21 Date.prototype.setFullYear ( year [ , month [ , date ] ] )
3443 *
3444 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
3445 */
3446 static bool date_setFullYear(JSContext* cx, unsigned argc, Value* vp) {
3447 CallArgs args = CallArgsFromVp(argc, vp);
3448
3449 // Steps 1-2.
3450 Rooted<DateObject*> unwrapped(
3451 cx, UnwrapAndTypeCheckThis<DateObject>(cx, args, "setFullYear"));
3452 if (!unwrapped) {
3453 return false;
3454 }
3455
3456 // Step 3.
3457 double t = unwrapped->UTCTime().toDouble();
3458 MOZ_ASSERT(IsTimeValue(t));
3459
3460 // Step 4.
3461 double y;
3462 if (!ToNumber(cx, args.get(0), &y)) {
3463 return false;
3464 }
3465
3466 // Step 5.
3467 int64_t tv;
3468 if (std::isnan(t)) {
3469 tv = 0;
3470 } else {
3471 tv = LocalTime(unwrapped->forceUTC(), t);
3472 }
3473
3474 // Step 6.
3475 double m;
3476 if (args.length() <= 1) {
3477 m = MonthFromTime(tv);
3478 } else {
3479 if (!ToNumber(cx, args[1], &m)) {
3480 return false;
3481 }
3482 }
3483
3484 // Step 7.
3485 double dt;
3486 if (args.length() <= 2) {
3487 dt = DateFromTime(tv);
3488 } else {
3489 if (!ToNumber(cx, args[2], &dt)) {
3490 return false;
3491 }
3492 }
3493
3494 // Step 8.
3495 double newDate = MakeDate(MakeDay(y, m, dt), TimeWithinDay(tv));
3496
3497 // Step 9.
3498 ClippedTime u = TimeClip(UTC(unwrapped->forceUTC(), newDate));
3499
3500 // Steps 10-11.
3501 unwrapped->setUTCTime(u, args.rval());
3502 return true;
3503 }
3504
3505 /**
3506 * 21.4.4.29 Date.prototype.setUTCFullYear ( year [ , month [ , date ] ] )
3507 *
3508 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
3509 */
3510 static bool date_setUTCFullYear(JSContext* cx, unsigned argc, Value* vp) {
3511 CallArgs args = CallArgsFromVp(argc, vp);
3512
3513 // Steps 1-2.
3514 Rooted<DateObject*> unwrapped(
3515 cx, UnwrapAndTypeCheckThis<DateObject>(cx, args, "setUTCFullYear"));
3516 if (!unwrapped) {
3517 return false;
3518 }
3519
3520 // Step 3.
3521 double t = unwrapped->UTCTime().toDouble();
3522 MOZ_ASSERT(IsTimeValue(t));
3523
3524 // Step 4.
3525 int64_t tv;
3526 if (std::isnan(t)) {
3527 tv = 0;
3528 } else {
3529 tv = static_cast<int64_t>(t);
3530 }
3531
3532 // Step 5.
3533 double y;
3534 if (!ToNumber(cx, args.get(0), &y)) {
3535 return false;
3536 }
3537
3538 // Step 6.
3539 double m;
3540 if (args.length() <= 1) {
3541 m = MonthFromTime(tv);
3542 } else {
3543 if (!ToNumber(cx, args[1], &m)) {
3544 return false;
3545 }
3546 }
3547
3548 // Step 7.
3549 double dt;
3550 if (args.length() <= 2) {
3551 dt = DateFromTime(tv);
3552 } else {
3553 if (!ToNumber(cx, args[2], &dt)) {
3554 return false;
3555 }
3556 }
3557
3558 // Step 8.
3559 double newDate = MakeDate(MakeDay(y, m, dt), TimeWithinDay(tv));
3560
3561 // Step 9.
3562 ClippedTime v = TimeClip(newDate);
3563
3564 // Steps 10-11.
3565 unwrapped->setUTCTime(v, args.rval());
3566 return true;
3567 }
3568
3569 /**
3570 * B.2.3.2 Date.prototype.setYear ( year )
3571 *
3572 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
3573 */
3574 static bool date_setYear(JSContext* cx, unsigned argc, Value* vp) {
3575 CallArgs args = CallArgsFromVp(argc, vp);
3576
3577 // Steps 1-2.
3578 Rooted<DateObject*> unwrapped(
3579 cx, UnwrapAndTypeCheckThis<DateObject>(cx, args, "setYear"));
3580 if (!unwrapped) {
3581 return false;
3582 }
3583
3584 // Step 3.
3585 double t = unwrapped->UTCTime().toDouble();
3586 MOZ_ASSERT(IsTimeValue(t));
3587
3588 // Step 4.
3589 double y;
3590 if (!ToNumber(cx, args.get(0), &y)) {
3591 return false;
3592 }
3593
3594 // Step 5.
3595 int64_t tv;
3596 if (std::isnan(t)) {
3597 tv = 0;
3598 } else {
3599 tv = LocalTime(unwrapped->forceUTC(), t);
3600 }
3601
3602 // Step 6.
3603 double yyyy = MakeFullYear(y);
3604
3605 // Step 7.
3606 double day = MakeDay(yyyy, ::MonthFromTime(tv), DateFromTime(tv));
3607
3608 // Step 8.
3609 double date = MakeDate(day, TimeWithinDay(tv));
3610
3611 // Step 9.
3612 ClippedTime u = TimeClip(UTC(unwrapped->forceUTC(), date));
3613
3614 // Steps 10-11.
3615 unwrapped->setUTCTime(u, args.rval());
3616 return true;
3617 }
3618
3619 /**
3620 * Simple date formatter for toISOString, toUTCString, and FormatDate.
3621 */
3622 class DateFormatter {
3623 // Longest possible string is 36 characters. Round up to the next multiple of
3624 // sixteen.
3625 static constexpr size_t BufferLength = 48;
3626
3627 char buffer_[BufferLength] = {};
3628 char* ptr_ = buffer_;
3629
3630 size_t written() const { return size_t(ptr_ - buffer_); }
3631
3632 static constexpr uint32_t powerOfTen(uint32_t exp) {
3633 uint32_t result = 1;
3634 while (exp--) {
3635 result *= 10;
3636 }
3637 return result;
3638 }
3639
3640 // Add |N| digits, padded with zeroes.
3641 template <uint32_t N>
3642 void digits(uint32_t value) {
3643 static_assert(1 <= N && N <= 6);
3644 MOZ_ASSERT(written() + N <= BufferLength);
3645
3646 constexpr uint32_t divisor = powerOfTen(N - 1);
3647 MOZ_ASSERT(value < divisor * 10);
3648
3649 uint32_t quot = value / divisor;
3650 [[maybe_unused]] uint32_t rem = value % divisor;
3651
3652 *ptr_++ = char('0' + quot);
3653 if constexpr (N > 1) {
3654 digits<N - 1>(rem);
3655 }
3656 }
3657
3658 // Constants for toString and toUTCString.
3659 static constexpr char const days[][4] = {
3660 "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
3661 };
3662 static constexpr char const months[][4] = {
3663 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3664 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
3665 };
3666
3667 public:
3668 std::string_view string() const { return {buffer_, written()}; }
3669
3670 auto& literal(char ch) {
3671 MOZ_ASSERT(written() + 1 <= BufferLength);
3672 *ptr_++ = ch;
3673 return *this;
3674 }
3675
3676 template <size_t N>
3677 auto& literal(const char (&str)[N]) {
3678 static_assert(N > 0);
3679 size_t length = N - 1;
3680 MOZ_ASSERT(written() + length <= BufferLength);
3681 std::memcpy(ptr_, str, length);
3682 ptr_ += length;
3683 return *this;
3684 }
3685
3686 auto& year(int32_t value) {
3687 MOZ_ASSERT(-999'999 <= value && value <= 999'999);
3688 if (value < 0) {
3689 literal('-');
3690 value = std::abs(value);
3691 }
3692 if (value <= 9999) {
3693 digits<4>(value);
3694 } else if (value <= 99999) {
3695 digits<5>(value);
3696 } else {
3697 digits<6>(value);
3698 }
3699 return *this;
3700 }
3701
3702 auto& isoYear(int32_t value) {
3703 MOZ_ASSERT(-999'999 <= value && value <= 999'999);
3704 if (0 <= value && value <= 9999) {
3705 digits<4>(value);
3706 } else {
3707 literal(value < 0 ? '-' : '+');
3708 digits<6>(std::abs(value));
3709 }
3710 return *this;
3711 }
3712
3713 auto& month(int32_t value) {
3714 MOZ_ASSERT(1 <= value && value <= 12);
3715 digits<2>(value);
3716 return *this;
3717 }
3718
3719 auto& day(int32_t value) {
3720 MOZ_ASSERT(1 <= value && value <= 31);
3721 digits<2>(value);
3722 return *this;
3723 }
3724
3725 auto& hour(int32_t value) {
3726 MOZ_ASSERT(0 <= value && value <= 23);
3727 digits<2>(value);
3728 return *this;
3729 }
3730
3731 auto& minute(int32_t value) {
3732 MOZ_ASSERT(0 <= value && value <= 59);
3733 digits<2>(value);
3734 return *this;
3735 }
3736
3737 auto& second(int32_t value) {
3738 MOZ_ASSERT(0 <= value && value <= 59);
3739 digits<2>(value);
3740 return *this;
3741 }
3742
3743 auto& time(int32_t h, int32_t m, int32_t s) {
3744 return hour(h).literal(':').minute(m).literal(':').second(s);
3745 }
3746
3747 auto& millisecond(int32_t value) {
3748 MOZ_ASSERT(0 <= value && value <= 999);
3749 digits<3>(value);
3750 return *this;
3751 }
3752
3753 auto& monthName(int32_t value) {
3754 MOZ_ASSERT(0 <= value && value < 12);
3755 return literal(months[value]);
3756 }
3757
3758 auto& weekDay(int32_t value) {
3759 MOZ_ASSERT(0 <= value && value < 7);
3760 return literal(days[value]);
3761 }
3762
3763 auto& timeZoneOffset(int32_t value) {
3764 MOZ_ASSERT(-2400 < value && value < 2400);
3765 literal(value < 0 ? '-' : '+');
3766 digits<4>(std::abs(value));
3767 return *this;
3768 }
3769 };
3770
3771 /**
3772 * 21.4.4.43 Date.prototype.toUTCString ( )
3773 *
3774 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
3775 */
3776 static bool date_toUTCString(JSContext* cx, unsigned argc, Value* vp) {
3777 AutoJSMethodProfilerEntry pseudoFrame(cx, "Date.prototype", "toUTCString");
3778 CallArgs args = CallArgsFromVp(argc, vp);
3779
3780 // Steps 1-2.
3781 auto* unwrapped = UnwrapAndTypeCheckThis<DateObject>(cx, args, "toUTCString");
3782 if (!unwrapped) {
3783 return false;
3784 }
3785
3786 // Step 3.
3787 double utctime = unwrapped->UTCTime().toDouble();
3788 MOZ_ASSERT(IsTimeValue(utctime));
3789
3790 // Step 4.
3791 if (std::isnan(utctime)) {
3792 args.rval().setString(cx->names().Invalid_Date_);
3793 return true;
3794 }
3795 int64_t epochMilliseconds = static_cast<int64_t>(utctime);
3796
3797 // Steps 5-11.
3798 auto [year, month, day] = ToYearMonthDay(epochMilliseconds);
3799 auto [hour, minute, second] = ToHourMinuteSecond(epochMilliseconds);
3800
3801 DateFormatter fmt{};
3802 fmt.weekDay(WeekDay(epochMilliseconds))
3803 .literal(", ")
3804 .day(day)
3805 .literal(' ')
3806 .monthName(month)
3807 .literal(' ')
3808 .year(year)
3809 .literal(' ')
3810 .time(hour, minute, second)
3811 .literal(" GMT");
3812
3813 JSString* str = NewStringCopy<CanGC>(cx, fmt.string());
3814 if (!str) {
3815 return false;
3816 }
3817
3818 args.rval().setString(str);
3819 return true;
3820 }
3821
3822 /**
3823 * 21.4.4.36 Date.prototype.toISOString ( )
3824 *
3825 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
3826 */
3827 static bool date_toISOString(JSContext* cx, unsigned argc, Value* vp) {
3828 AutoJSMethodProfilerEntry pseudoFrame(cx, "Date.prototype", "toISOString");
3829 CallArgs args = CallArgsFromVp(argc, vp);
3830
3831 // Steps 1-2.
3832 auto* unwrapped = UnwrapAndTypeCheckThis<DateObject>(cx, args, "toISOString");
3833 if (!unwrapped) {
3834 return false;
3835 }
3836
3837 // Steps 3 and 5.
3838 double utctime = unwrapped->UTCTime().toDouble();
3839 MOZ_ASSERT(IsTimeValue(utctime));
3840
3841 // Step 4.
3842 if (!std::isfinite(utctime)) {
3843 JS_ReportErrorNumberASCII(cx, js::GetErrorMessage, nullptr,
3844 JSMSG_INVALID_DATE);
3845 return false;
3846 }
3847 int64_t epochMilliseconds = static_cast<int64_t>(utctime);
3848
3849 // Step 6. (Not applicable in our implementation.)
3850
3851 // Step 7.
3852 auto [year, month, day] = ToYearMonthDay(epochMilliseconds);
3853 auto [hour, minute, second] = ToHourMinuteSecond(epochMilliseconds);
3854
3855 DateFormatter fmt{};
3856 fmt.isoYear(year)
3857 .literal('-')
3858 .month(month + 1)
3859 .literal('-')
3860 .day(day)
3861 .literal('T')
3862 .time(hour, minute, second)
3863 .literal('.')
3864 .millisecond(msFromTime(epochMilliseconds))
3865 .literal('Z');
3866
3867 JSString* str = NewStringCopy<CanGC>(cx, fmt.string());
3868 if (!str) {
3869 return false;
3870 }
3871 args.rval().setString(str);
3872 return true;
3873 }
3874
3875 /**
3876 * 21.4.4.37 Date.prototype.toJSON ( key )
3877 *
3878 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
3879 */
3880 static bool date_toJSON(JSContext* cx, unsigned argc, Value* vp) {
3881 AutoJSMethodProfilerEntry pseudoFrame(cx, "Date.prototype", "toJSON");
3882 CallArgs args = CallArgsFromVp(argc, vp);
3883
3884 // Step 1.
3885 RootedObject obj(cx, ToObject(cx, args.thisv()));
3886 if (!obj) {
3887 return false;
3888 }
3889
3890 // Step 2.
3891 RootedValue tv(cx, ObjectValue(*obj));
3892 if (!ToPrimitive(cx, JSTYPE_NUMBER, &tv)) {
3893 return false;
3894 }
3895
3896 // Step 3.
3897 if (tv.isDouble() && !std::isfinite(tv.toDouble())) {
3898 args.rval().setNull();
3899 return true;
3900 }
3901
3902 // Step 4.
3903 RootedValue toISO(cx);
3904 if (!GetProperty(cx, obj, obj, cx->names().toISOString, &toISO)) {
3905 return false;
3906 }
3907
3908 if (!IsCallable(toISO)) {
3909 JS_ReportErrorNumberASCII(cx, js::GetErrorMessage, nullptr,
3910 JSMSG_BAD_TOISOSTRING_PROP);
3911 return false;
3912 }
3913
3914 return Call(cx, toISO, obj, args.rval());
3915 }
3916
3917 #if JS_HAS_INTL_API
3918 JSString* DateTimeHelper::timeZoneComment(JSContext* cx,
3919 DateTimeInfo::ForceUTC forceUTC,
3920 const char* locale, int64_t utcTime,
3921 int64_t localTime) {
3922 MOZ_ASSERT(IsTimeValue(utcTime));
3923 MOZ_ASSERT(IsLocalTimeValue(localTime));
3924
3925 char16_t tzbuf[100];
3926 tzbuf[0] = ' ';
3927 tzbuf[1] = '(';
3928
3929 char16_t* timeZoneStart = tzbuf + 2;
3930 constexpr size_t remainingSpace =
3931 std::size(tzbuf) - 2 - 1; // for the trailing ')'
3932
3933 if (!DateTimeInfo::timeZoneDisplayName(forceUTC, timeZoneStart,
3934 remainingSpace, utcTime, locale)) {
3935 JS_ReportOutOfMemory(cx);
3936 return nullptr;
3937 }
3938
3939 // Reject if the result string is empty.
3940 size_t len = js_strlen(timeZoneStart);
3941 if (len == 0) {
3942 return cx->names().empty_;
3943 }
3944
3945 // Parenthesize the returned display name.
3946 timeZoneStart[len] = ')';
3947
3948 return NewStringCopyN<CanGC>(cx, tzbuf, 2 + len + 1);
3949 }
3950 #else
3951 /* Interface to PRMJTime date struct. */
3952 PRMJTime DateTimeHelper::toPRMJTime(DateTimeInfo::ForceUTC forceUTC,
3953 int64_t localTime, int64_t utcTime) {
3954 auto [year, month, day] = ToYearMonthDay(localTime);
3955 auto [hour, minute, second] = ToHourMinuteSecond(localTime);
3956
3957 PRMJTime prtm;
3958 prtm.tm_usec = int32_t(msFromTime(localTime)) * 1000;
3959 prtm.tm_sec = int8_t(second);
3960 prtm.tm_min = int8_t(minute);
3961 prtm.tm_hour = int8_t(hour);
3962 prtm.tm_mday = int8_t(day);
3963 prtm.tm_mon = int8_t(month);
3964 prtm.tm_wday = int8_t(WeekDay(localTime));
3965 prtm.tm_year = year;
3966 prtm.tm_yday = int16_t(::DayWithinYear(localTime, year));
3967 prtm.tm_isdst = (daylightSavingTA(forceUTC, utcTime) != 0);
3968
3969 return prtm;
3970 }
3971
3972 size_t DateTimeHelper::formatTime(DateTimeInfo::ForceUTC forceUTC, char* buf,
3973 size_t buflen, const char* fmt,
3974 int64_t utcTime, int64_t localTime) {
3975 PRMJTime prtm = toPRMJTime(forceUTC, localTime, utcTime);
3976
3977 // If an equivalent year was used to compute the date/time components, use
3978 // the same equivalent year to determine the time zone name and offset in
3979 // PRMJ_FormatTime(...).
3980 int timeZoneYear = isRepresentableAsTime32(utcTime)
3981 ? prtm.tm_year
3982 : equivalentYearForDST(prtm.tm_year);
3983
3984 int32_t offsetInSeconds = FloorDiv(localTime - utcTime, msPerSecond);
3985
3986 return PRMJ_FormatTime(buf, buflen, fmt, &prtm, timeZoneYear,
3987 offsetInSeconds);
3988 }
3989
3990 JSString* DateTimeHelper::timeZoneComment(JSContext* cx,
3991 DateTimeInfo::ForceUTC forceUTC,
3992 const char* locale, int64_t utcTime,
3993 int64_t localTime) {
3994 char tzbuf[100];
3995
3996 size_t tzlen =
3997 formatTime(forceUTC, tzbuf, sizeof tzbuf, " (%Z)", utcTime, localTime);
3998 if (tzlen != 0) {
3999 // Decide whether to use the resulting time zone string.
4000 //
4001 // Reject it if it contains any non-ASCII or non-printable characters.
4002 // It's then likely in some other character encoding, and we probably
4003 // won't display it correctly.
4004 bool usetz = true;
4005 for (size_t i = 0; i < tzlen; i++) {
4006 char16_t c = tzbuf[i];
4007 if (!IsAsciiPrintable(c)) {
4008 usetz = false;
4009 break;
4010 }
4011 }
4012
4013 // Also reject it if it's not parenthesized or if it's ' ()'.
4014 if (tzbuf[0] != ' ' || tzbuf[1] != '(' || tzbuf[2] == ')') {
4015 usetz = false;
4016 }
4017
4018 if (usetz) {
4019 return NewStringCopyN<CanGC>(cx, tzbuf, tzlen);
4020 }
4021 }
4022
4023 return cx->names().empty_;
4024 }
4025 #endif /* JS_HAS_INTL_API */
4026
4027 enum class FormatSpec { DateTime, Date, Time };
4028
4029 static bool FormatDate(JSContext* cx, DateTimeInfo::ForceUTC forceUTC,
4030 const char* locale, double utcTime, FormatSpec format,
4031 MutableHandleValue rval) {
4032 MOZ_ASSERT(IsTimeValue(utcTime));
4033
4034 if (!std::isfinite(utcTime)) {
4035 rval.setString(cx->names().Invalid_Date_);
4036 return true;
4037 }
4038
4039 int64_t epochMilliseconds = static_cast<int64_t>(utcTime);
4040 int64_t localTime = LocalTime(forceUTC, utcTime);
4041
4042 int offset = 0;
4043 RootedString timeZoneComment(cx);
4044 if (format == FormatSpec::DateTime || format == FormatSpec::Time) {
4045 // Offset from GMT in minutes. The offset includes daylight savings,
4046 // if it applies.
4047 int32_t minutes = int32_t(localTime - epochMilliseconds) / msPerMinute;
4048
4049 // Map 510 minutes to 0830 hours.
4050 offset = (minutes / 60) * 100 + minutes % 60;
4051
4052 // Print as "Wed Nov 05 1997 19:38:03 GMT-0800 (PST)".
4053 //
4054 // The TZA is printed as 'GMT-0800' rather than as 'PST' to avoid
4055 // operating-system dependence on strftime (which PRMJ_FormatTime
4056 // calls, for %Z only.) win32 prints PST as 'Pacific Standard Time.'
4057 // This way we always know what we're getting, and can parse it if
4058 // we produce it. The OS time zone string is included as a comment.
4059 //
4060 // When ICU is used to retrieve the time zone string, the localized
4061 // 'long' name format from CLDR is used. For example when the default
4062 // locale is "en-US", PST is displayed as 'Pacific Standard Time', but
4063 // when it is "ru", 'Тихоокеанское стандартное время' is used. This
4064 // also means the time zone string may not fit into Latin-1.
4065
4066 // Get a time zone string from the OS or ICU to include as a comment.
4067 timeZoneComment = DateTimeHelper::timeZoneComment(
4068 cx, forceUTC, locale, epochMilliseconds, localTime);
4069 if (!timeZoneComment) {
4070 return false;
4071 }
4072 }
4073
4074 DateFormatter fmt{};
4075 switch (format) {
4076 case FormatSpec::DateTime: {
4077 /* Tue Oct 31 2000 09:41:40 GMT-0800 */
4078 auto [year, month, day] = ToYearMonthDay(localTime);
4079 auto [hour, minute, second] = ToHourMinuteSecond(localTime);
4080
4081 fmt.weekDay(WeekDay(localTime))
4082 .literal(' ')
4083 .monthName(month)
4084 .literal(' ')
4085 .day(day)
4086 .literal(' ')
4087 .year(year)
4088 .literal(' ')
4089 .time(hour, minute, second)
4090 .literal(" GMT")
4091 .timeZoneOffset(offset);
4092 break;
4093 }
4094 case FormatSpec::Date: {
4095 /* Tue Oct 31 2000 */
4096 auto [year, month, day] = ToYearMonthDay(localTime);
4097
4098 fmt.weekDay(WeekDay(localTime))
4099 .literal(' ')
4100 .monthName(month)
4101 .literal(' ')
4102 .day(day)
4103 .literal(' ')
4104 .year(year);
4105 break;
4106 }
4107 case FormatSpec::Time:
4108 /* 09:41:40 GMT-0800 */
4109 auto [hour, minute, second] = ToHourMinuteSecond(localTime);
4110 fmt.time(hour, minute, second).literal(" GMT").timeZoneOffset(offset);
4111 break;
4112 }
4113
4114 RootedString str(cx, NewStringCopy<CanGC>(cx, fmt.string()));
4115 if (!str) {
4116 return false;
4117 }
4118
4119 // Append the time zone string if present.
4120 if (timeZoneComment && !timeZoneComment->empty()) {
4121 str = js::ConcatStrings<CanGC>(cx, str, timeZoneComment);
4122 if (!str) {
4123 return false;
4124 }
4125 }
4126
4127 rval.setString(str);
4128 return true;
4129 }
4130
4131 #if !JS_HAS_INTL_API
4132 static bool ToLocaleFormatHelper(JSContext* cx, DateObject* unwrapped,
4133 const char* format, MutableHandleValue rval) {
4134 DateTimeInfo::ForceUTC forceUTC = unwrapped->forceUTC();
4135 double utcTime = unwrapped->UTCTime().toDouble();
4136
4137 const char* locale = unwrapped->realm()->getLocale();
4138 if (!locale) {
4139 return false;
4140 }
4141
4142 char buf[100];
4143 if (!std::isfinite(utcTime)) {
4144 strcpy(buf, "InvalidDate");
4145 } else {
4146 MOZ_ASSERT(IsTimeValue(utcTime));
4147
4148 int64_t epochMilliseconds = static_cast<int64_t>(utcTime);
4149 int64_t localTime = static_cast<int64_t>(LocalTime(forceUTC, utcTime));
4150
4151 /* Let PRMJTime format it. */
4152 size_t result_len = DateTimeHelper::formatTime(
4153 forceUTC, buf, sizeof buf, format, epochMilliseconds, localTime);
4154
4155 /* If it failed, default to toString. */
4156 if (result_len == 0) {
4157 return FormatDate(cx, forceUTC, locale, utcTime, FormatSpec::DateTime,
4158 rval);
4159 }
4160
4161 /* Hacked check against undesired 2-digit year 00/00/00 form. */
4162 if (strcmp(format, "%x") == 0 && result_len >= 6 &&
4163 /* Format %x means use OS settings, which may have 2-digit yr, so
4164 hack end of 3/11/22 or 11.03.22 or 11Mar22 to use 4-digit yr...*/
4165 !IsAsciiDigit(buf[result_len - 3]) &&
4166 IsAsciiDigit(buf[result_len - 2]) &&
4167 IsAsciiDigit(buf[result_len - 1]) &&
4168 /* ...but not if starts with 4-digit year, like 2022/3/11. */
4169 !(IsAsciiDigit(buf[0]) && IsAsciiDigit(buf[1]) &&
4170 IsAsciiDigit(buf[2]) && IsAsciiDigit(buf[3]))) {
4171 int year = int(::YearFromTime(localTime));
4172 snprintf(buf + (result_len - 2), (sizeof buf) - (result_len - 2), "%d",
4173 year);
4174 }
4175 }
4176
4177 if (cx->runtime()->localeCallbacks &&
4178 cx->runtime()->localeCallbacks->localeToUnicode) {
4179 return cx->runtime()->localeCallbacks->localeToUnicode(cx, buf, rval);
4180 }
4181
4182 JSString* str = NewStringCopyZ<CanGC>(cx, buf);
4183 if (!str) {
4184 return false;
4185 }
4186 rval.setString(str);
4187 return true;
4188 }
4189
4190 /**
4191 * 21.4.4.39 Date.prototype.toLocaleString ( [ reserved1 [ , reserved2 ] ] )
4192 *
4193 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
4194 */
4195 static bool date_toLocaleString(JSContext* cx, unsigned argc, Value* vp) {
4196 AutoJSMethodProfilerEntry pseudoFrame(cx, "Date.prototype", "toLocaleString");
4197 CallArgs args = CallArgsFromVp(argc, vp);
4198
4199 auto* unwrapped =
4200 UnwrapAndTypeCheckThis<DateObject>(cx, args, "toLocaleString");
4201 if (!unwrapped) {
4202 return false;
4203 }
4204
4205 /*
4206 * Use '%#c' for windows, because '%c' is backward-compatible and non-y2k
4207 * with msvc; '%#c' requests that a full year be used in the result string.
4208 */
4209 static const char format[] =
4210 # if defined(_WIN32)
4211 "%#c"
4212 # else
4213 "%c"
4214 # endif
4215 ;
4216
4217 return ToLocaleFormatHelper(cx, unwrapped, format, args.rval());
4218 }
4219
4220 /**
4221 * 21.4.4.38 Date.prototype.toLocaleDateString ( [ reserved1 [ , reserved2 ] ] )
4222 *
4223 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
4224 */
4225 static bool date_toLocaleDateString(JSContext* cx, unsigned argc, Value* vp) {
4226 AutoJSMethodProfilerEntry pseudoFrame(cx, "Date.prototype",
4227 "toLocaleDateString");
4228 CallArgs args = CallArgsFromVp(argc, vp);
4229
4230 auto* unwrapped =
4231 UnwrapAndTypeCheckThis<DateObject>(cx, args, "toLocaleDateString");
4232 if (!unwrapped) {
4233 return false;
4234 }
4235
4236 /*
4237 * Use '%#x' for windows, because '%x' is backward-compatible and non-y2k
4238 * with msvc; '%#x' requests that a full year be used in the result string.
4239 */
4240 static const char format[] =
4241 # if defined(_WIN32)
4242 "%#x"
4243 # else
4244 "%x"
4245 # endif
4246 ;
4247
4248 return ToLocaleFormatHelper(cx, unwrapped, format, args.rval());
4249 }
4250
4251 /**
4252 * 21.4.4.40 Date.prototype.toLocaleTimeString ( [ reserved1 [ , reserved2 ] ] )
4253 *
4254 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
4255 */
4256 static bool date_toLocaleTimeString(JSContext* cx, unsigned argc, Value* vp) {
4257 AutoJSMethodProfilerEntry pseudoFrame(cx, "Date.prototype",
4258 "toLocaleTimeString");
4259 CallArgs args = CallArgsFromVp(argc, vp);
4260
4261 auto* unwrapped =
4262 UnwrapAndTypeCheckThis<DateObject>(cx, args, "toLocaleTimeString");
4263 if (!unwrapped) {
4264 return false;
4265 }
4266
4267 return ToLocaleFormatHelper(cx, unwrapped, "%X", args.rval());
4268 }
4269 #endif /* !JS_HAS_INTL_API */
4270
4271 /**
4272 * 21.4.4.42 Date.prototype.toTimeString ( )
4273 *
4274 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
4275 */
4276 static bool date_toTimeString(JSContext* cx, unsigned argc, Value* vp) {
4277 AutoJSMethodProfilerEntry pseudoFrame(cx, "Date.prototype", "toTimeString");
4278 CallArgs args = CallArgsFromVp(argc, vp);
4279
4280 // Steps 1-2.
4281 auto* unwrapped =
4282 UnwrapAndTypeCheckThis<DateObject>(cx, args, "toTimeString");
4283 if (!unwrapped) {
4284 return false;
4285 }
4286
4287 // Steps 3-6.
4288 const char* locale = unwrapped->realm()->getLocale();
4289 if (!locale) {
4290 return false;
4291 }
4292 return FormatDate(cx, unwrapped->forceUTC(), locale,
4293 unwrapped->UTCTime().toDouble(), FormatSpec::Time,
4294 args.rval());
4295 }
4296
4297 /**
4298 * 21.4.4.35 Date.prototype.toDateString ( )
4299 *
4300 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
4301 */
4302 static bool date_toDateString(JSContext* cx, unsigned argc, Value* vp) {
4303 AutoJSMethodProfilerEntry pseudoFrame(cx, "Date.prototype", "toDateString");
4304 CallArgs args = CallArgsFromVp(argc, vp);
4305
4306 // Steps 1-2.
4307 auto* unwrapped =
4308 UnwrapAndTypeCheckThis<DateObject>(cx, args, "toDateString");
4309 if (!unwrapped) {
4310 return false;
4311 }
4312
4313 // Steps 3-6.
4314 const char* locale = unwrapped->realm()->getLocale();
4315 if (!locale) {
4316 return false;
4317 }
4318 return FormatDate(cx, unwrapped->forceUTC(), locale,
4319 unwrapped->UTCTime().toDouble(), FormatSpec::Date,
4320 args.rval());
4321 }
4322
4323 static bool date_toSource(JSContext* cx, unsigned argc, Value* vp) {
4324 AutoJSMethodProfilerEntry pseudoFrame(cx, "Date.prototype", "toSource");
4325 CallArgs args = CallArgsFromVp(argc, vp);
4326
4327 auto* unwrapped = UnwrapAndTypeCheckThis<DateObject>(cx, args, "toSource");
4328 if (!unwrapped) {
4329 return false;
4330 }
4331
4332 JSStringBuilder sb(cx);
4333 if (!sb.append("(new Date(") ||
4334 !NumberValueToStringBuilder(unwrapped->UTCTime(), sb) ||
4335 !sb.append("))")) {
4336 return false;
4337 }
4338
4339 JSString* str = sb.finishString();
4340 if (!str) {
4341 return false;
4342 }
4343 args.rval().setString(str);
4344 return true;
4345 }
4346
4347 /**
4348 * 21.4.4.41 Date.prototype.toString ( )
4349 *
4350 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
4351 */
4352 static bool date_toString(JSContext* cx, unsigned argc, Value* vp) {
4353 AutoJSMethodProfilerEntry pseudoFrame(cx, "Date.prototype", "toString");
4354 CallArgs args = CallArgsFromVp(argc, vp);
4355
4356 // Steps 1-2.
4357 auto* unwrapped = UnwrapAndTypeCheckThis<DateObject>(cx, args, "toString");
4358 if (!unwrapped) {
4359 return false;
4360 }
4361
4362 // Steps 3-4.
4363 const char* locale = unwrapped->realm()->getLocale();
4364 if (!locale) {
4365 return false;
4366 }
4367 return FormatDate(cx, unwrapped->forceUTC(), locale,
4368 unwrapped->UTCTime().toDouble(), FormatSpec::DateTime,
4369 args.rval());
4370 }
4371
4372 /**
4373 * 21.4.4.44 Date.prototype.valueOf ( )
4374 *
4375 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
4376 */
4377 bool js::date_valueOf(JSContext* cx, unsigned argc, Value* vp) {
4378 CallArgs args = CallArgsFromVp(argc, vp);
4379
4380 // Steps 1-2.
4381 auto* unwrapped = UnwrapAndTypeCheckThis<DateObject>(cx, args, "valueOf");
4382 if (!unwrapped) {
4383 return false;
4384 }
4385
4386 // Step 3.
4387 args.rval().set(unwrapped->UTCTime());
4388 return true;
4389 }
4390
4391 /**
4392 * 21.4.4.45 Date.prototype [ %Symbol.toPrimitive% ] ( hint )
4393 *
4394 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
4395 */
4396 bool js::date_toPrimitive(JSContext* cx, unsigned argc, Value* vp) {
4397 CallArgs args = CallArgsFromVp(argc, vp);
4398
4399 // Steps 1-2.
4400 if (!args.thisv().isObject()) {
4401 ReportIncompatible(cx, args);
4402 return false;
4403 }
4404
4405 // Steps 3-5.
4406 JSType hint;
4407 if (!GetFirstArgumentAsTypeHint(cx, args, &hint)) {
4408 return false;
4409 }
4410 if (hint == JSTYPE_UNDEFINED) {
4411 hint = JSTYPE_STRING;
4412 }
4413
4414 // Step 6.
4415 RootedObject obj(cx, &args.thisv().toObject());
4416 return OrdinaryToPrimitive(cx, obj, hint, args.rval());
4417 }
4418
4419 #if JS_HAS_INTL_API
4420 /**
4421 * Date.prototype.toTemporalInstant ( )
4422 */
4423 static bool date_toTemporalInstant(JSContext* cx, unsigned argc, Value* vp) {
4424 CallArgs args = CallArgsFromVp(argc, vp);
4425
4426 // Steps 1-2.
4427 auto* unwrapped =
4428 UnwrapAndTypeCheckThis<DateObject>(cx, args, "toTemporalInstant");
4429 if (!unwrapped) {
4430 return false;
4431 }
4432
4433 // Step 3.
4434 double t = unwrapped->UTCTime().toDouble();
4435 MOZ_ASSERT(IsTimeValue(t));
4436
4437 // Step 4.
4438 if (std::isnan(t)) {
4439 JS_ReportErrorNumberASCII(cx, js::GetErrorMessage, nullptr,
4440 JSMSG_INVALID_DATE);
4441 return false;
4442 }
4443 int64_t tv = static_cast<int64_t>(t);
4444
4445 auto epochNs = temporal::EpochNanoseconds::fromMilliseconds(tv);
4446 MOZ_ASSERT(temporal::IsValidEpochNanoseconds(epochNs));
4447
4448 // Step 5.
4449 auto* result = temporal::CreateTemporalInstant(cx, epochNs);
4450 if (!result) {
4451 return false;
4452 }
4453 args.rval().setObject(*result);
4454 return true;
4455 }
4456 #endif /* JS_HAS_INTL_API */
4457
4458 static const JSFunctionSpec date_static_methods[] = {
4459 JS_FN("UTC", date_UTC, 7, 0),
4460 JS_FN("parse", date_parse, 1, 0),
4461 JS_FN("now", date_now, 0, 0),
4462 JS_FS_END,
4463 };
4464
4465 static const JSFunctionSpec date_methods[] = {
4466 JS_INLINABLE_FN("getTime", date_getTime, 0, 0, DateGetTime),
4467 JS_FN("getTimezoneOffset", date_getTimezoneOffset, 0, 0),
4468 JS_FN("getYear", date_getYear, 0, 0),
4469 JS_INLINABLE_FN("getFullYear", date_getFullYear, 0, 0, DateGetFullYear),
4470 JS_FN("getUTCFullYear", date_getUTCFullYear, 0, 0),
4471 JS_INLINABLE_FN("getMonth", date_getMonth, 0, 0, DateGetMonth),
4472 JS_FN("getUTCMonth", date_getUTCMonth, 0, 0),
4473 JS_INLINABLE_FN("getDate", date_getDate, 0, 0, DateGetDate),
4474 JS_FN("getUTCDate", date_getUTCDate, 0, 0),
4475 JS_INLINABLE_FN("getDay", date_getDay, 0, 0, DateGetDay),
4476 JS_FN("getUTCDay", date_getUTCDay, 0, 0),
4477 JS_INLINABLE_FN("getHours", date_getHours, 0, 0, DateGetHours),
4478 JS_FN("getUTCHours", date_getUTCHours, 0, 0),
4479 JS_INLINABLE_FN("getMinutes", date_getMinutes, 0, 0, DateGetMinutes),
4480 JS_FN("getUTCMinutes", date_getUTCMinutes, 0, 0),
4481 JS_INLINABLE_FN("getSeconds", date_getSeconds, 0, 0, DateGetSeconds),
4482 JS_FN("getUTCSeconds", date_getUTCSeconds, 0, 0),
4483 JS_FN("getMilliseconds", date_getMilliseconds, 0, 0),
4484 JS_FN("getUTCMilliseconds", date_getUTCMilliseconds, 0, 0),
4485 JS_FN("setTime", date_setTime, 1, 0),
4486 JS_FN("setYear", date_setYear, 1, 0),
4487 JS_FN("setFullYear", date_setFullYear, 3, 0),
4488 JS_FN("setUTCFullYear", date_setUTCFullYear, 3, 0),
4489 JS_FN("setMonth", date_setMonth, 2, 0),
4490 JS_FN("setUTCMonth", date_setUTCMonth, 2, 0),
4491 JS_FN("setDate", date_setDate, 1, 0),
4492 JS_FN("setUTCDate", date_setUTCDate, 1, 0),
4493 JS_FN("setHours", date_setHours, 4, 0),
4494 JS_FN("setUTCHours", date_setUTCHours, 4, 0),
4495 JS_FN("setMinutes", date_setMinutes, 3, 0),
4496 JS_FN("setUTCMinutes", date_setUTCMinutes, 3, 0),
4497 JS_FN("setSeconds", date_setSeconds, 2, 0),
4498 JS_FN("setUTCSeconds", date_setUTCSeconds, 2, 0),
4499 JS_FN("setMilliseconds", date_setMilliseconds, 1, 0),
4500 JS_FN("setUTCMilliseconds", date_setUTCMilliseconds, 1, 0),
4501 JS_FN("toUTCString", date_toUTCString, 0, 0),
4502 #if JS_HAS_INTL_API
4503 JS_FN("toTemporalInstant", date_toTemporalInstant, 0, 0),
4504 JS_SELF_HOSTED_FN("toLocaleString", "Date_toLocaleString", 0, 0),
4505 JS_SELF_HOSTED_FN("toLocaleDateString", "Date_toLocaleDateString", 0, 0),
4506 JS_SELF_HOSTED_FN("toLocaleTimeString", "Date_toLocaleTimeString", 0, 0),
4507 #else
4508 JS_FN("toLocaleString", date_toLocaleString, 0, 0),
4509 JS_FN("toLocaleDateString", date_toLocaleDateString, 0, 0),
4510 JS_FN("toLocaleTimeString", date_toLocaleTimeString, 0, 0),
4511 #endif
4512 JS_FN("toDateString", date_toDateString, 0, 0),
4513 JS_FN("toTimeString", date_toTimeString, 0, 0),
4514 JS_FN("toISOString", date_toISOString, 0, 0),
4515 JS_FN("toJSON", date_toJSON, 1, 0),
4516 JS_FN("toSource", date_toSource, 0, 0),
4517 JS_FN("toString", date_toString, 0, 0),
4518 JS_INLINABLE_FN("valueOf", date_valueOf, 0, 0, DateGetTime),
4519 JS_SYM_FN(toPrimitive, date_toPrimitive, 1, JSPROP_READONLY),
4520 JS_FS_END,
4521 };
4522
4523 static bool NewDateObject(JSContext* cx, const CallArgs& args, ClippedTime t) {
4524 MOZ_ASSERT(args.isConstructing());
4525
4526 RootedObject proto(cx);
4527 if (!GetPrototypeFromBuiltinConstructor(cx, args, JSProto_Date, &proto)) {
4528 return false;
4529 }
4530
4531 JSObject* obj = NewDateObjectMsec(cx, t, proto);
4532 if (!obj) {
4533 return false;
4534 }
4535
4536 args.rval().setObject(*obj);
4537 return true;
4538 }
4539
4540 /**
4541 * 21.4.4.41.4 ToDateString ( tv )
4542 *
4543 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
4544 */
4545 static bool ToDateString(JSContext* cx, const CallArgs& args, ClippedTime t) {
4546 const char* locale = cx->realm()->getLocale();
4547 if (!locale) {
4548 return false;
4549 }
4550 return FormatDate(cx, ForceUTC(cx->realm()), locale, t.toDouble(),
4551 FormatSpec::DateTime, args.rval());
4552 }
4553
4554 /**
4555 * 21.4.2.1 Date ( ...values )
4556 *
4557 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
4558 */
4559 static bool DateNoArguments(JSContext* cx, const CallArgs& args) {
4560 MOZ_ASSERT(args.isConstructing());
4561 MOZ_ASSERT(args.length() == 0);
4562
4563 // Step 3.
4564 ClippedTime now = NowAsMillis(cx);
4565
4566 // Steps 6-8.
4567 return NewDateObject(cx, args, now);
4568 }
4569
4570 /**
4571 * 21.4.2.1 Date ( ...values )
4572 *
4573 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
4574 */
4575 static bool DateOneArgument(JSContext* cx, const CallArgs& args) {
4576 MOZ_ASSERT(args.isConstructing());
4577 MOZ_ASSERT(args.length() == 1);
4578
4579 // Step 4.a.
4580 MutableHandle<Value> value = args[0];
4581
4582 // Step 4.b.
4583 if (value.isObject()) {
4584 RootedObject obj(cx, &value.toObject());
4585
4586 ESClass cls;
4587 if (!GetBuiltinClass(cx, obj, &cls)) {
4588 return false;
4589 }
4590
4591 if (cls == ESClass::Date) {
4592 RootedValue unboxed(cx);
4593 if (!Unbox(cx, obj, &unboxed)) {
4594 return false;
4595 }
4596
4597 // Steps 6-8.
4598 return NewDateObject(cx, args, TimeClip(unboxed.toNumber()));
4599 }
4600 }
4601
4602 // Step 4.c.i.
4603 if (!ToPrimitive(cx, value)) {
4604 return false;
4605 }
4606
4607 // Steps 4.c.ii-iii.
4608 ClippedTime t;
4609 if (value.isString()) {
4610 JSLinearString* linearStr = value.toString()->ensureLinear(cx);
4611 if (!linearStr) {
4612 return false;
4613 }
4614
4615 if (!ParseDate(cx, ForceUTC(cx->realm()), linearStr, &t)) {
4616 t = ClippedTime::invalid();
4617 }
4618 } else {
4619 double d;
4620 if (!ToNumber(cx, value, &d)) {
4621 return false;
4622 }
4623 t = TimeClip(d);
4624 }
4625
4626 // Steps 6-8.
4627 return NewDateObject(cx, args, t);
4628 }
4629
4630 /**
4631 * 21.4.2.1 Date ( ...values )
4632 *
4633 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
4634 */
4635 static bool DateMultipleArguments(JSContext* cx, const CallArgs& args) {
4636 // Step 5.a.
4637 MOZ_ASSERT(args.isConstructing());
4638 MOZ_ASSERT(args.length() >= 2);
4639
4640 // Step 5.b.
4641 double y;
4642 if (!ToNumber(cx, args[0], &y)) {
4643 return false;
4644 }
4645
4646 // Step 5.c.
4647 double m;
4648 if (!ToNumber(cx, args[1], &m)) {
4649 return false;
4650 }
4651
4652 // Step 5.d.
4653 double dt;
4654 if (args.length() >= 3) {
4655 if (!ToNumber(cx, args[2], &dt)) {
4656 return false;
4657 }
4658 } else {
4659 dt = 1;
4660 }
4661
4662 // Step 5.e.
4663 double h;
4664 if (args.length() >= 4) {
4665 if (!ToNumber(cx, args[3], &h)) {
4666 return false;
4667 }
4668 } else {
4669 h = 0;
4670 }
4671
4672 // Step 5.f.
4673 double min;
4674 if (args.length() >= 5) {
4675 if (!ToNumber(cx, args[4], &min)) {
4676 return false;
4677 }
4678 } else {
4679 min = 0;
4680 }
4681
4682 // Step 5.g.
4683 double s;
4684 if (args.length() >= 6) {
4685 if (!ToNumber(cx, args[5], &s)) {
4686 return false;
4687 }
4688 } else {
4689 s = 0;
4690 }
4691
4692 // Step 5.h.
4693 double milli;
4694 if (args.length() >= 7) {
4695 if (!ToNumber(cx, args[6], &milli)) {
4696 return false;
4697 }
4698 } else {
4699 milli = 0;
4700 }
4701
4702 // Step 5.i.
4703 double yr = MakeFullYear(y);
4704
4705 // Step 5.j.
4706 double finalDate = MakeDate(MakeDay(yr, m, dt), MakeTime(h, min, s, milli));
4707
4708 // Steps 5.k and 6-8.
4709 return NewDateObject(cx, args,
4710 TimeClip(UTC(ForceUTC(cx->realm()), finalDate)));
4711 }
4712
4713 /**
4714 * 21.4.2.1 Date ( ...values )
4715 *
4716 * ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0
4717 */
4718 static bool DateConstructor(JSContext* cx, unsigned argc, Value* vp) {
4719 AutoJSConstructorProfilerEntry pseudoFrame(cx, "Date");
4720 CallArgs args = CallArgsFromVp(argc, vp);
4721
4722 // Step 1.
4723 if (!args.isConstructing()) {
4724 return ToDateString(cx, args, NowAsMillis(cx));
4725 }
4726
4727 // Step 2.
4728 unsigned numberOfArgs = args.length();
4729
4730 // Steps 3 and 6-8.
4731 if (numberOfArgs == 0) {
4732 return DateNoArguments(cx, args);
4733 }
4734
4735 // Steps 4 and 6-8.
4736 if (numberOfArgs == 1) {
4737 return DateOneArgument(cx, args);
4738 }
4739
4740 // Steps 5-8.
4741 return DateMultipleArguments(cx, args);
4742 }
4743
4744 static bool FinishDateClassInit(JSContext* cx, HandleObject ctor,
4745 HandleObject proto) {
4746 /*
4747 * Date.prototype.toGMTString has the same initial value as
4748 * Date.prototype.toUTCString.
4749 */
4750 RootedValue toUTCStringFun(cx);
4751 RootedId toUTCStringId(cx, NameToId(cx->names().toUTCString));
4752 RootedId toGMTStringId(cx, NameToId(cx->names().toGMTString));
4753 return NativeGetProperty(cx, proto.as<NativeObject>(), toUTCStringId,
4754 &toUTCStringFun) &&
4755 NativeDefineDataProperty(cx, proto.as<NativeObject>(), toGMTStringId,
4756 toUTCStringFun, 0);
4757 }
4758
4759 static const ClassSpec DateObjectClassSpec = {
4760 GenericCreateConstructor<DateConstructor, 7, gc::AllocKind::FUNCTION>,
4761 GenericCreatePrototype<DateObject>,
4762 date_static_methods,
4763 nullptr,
4764 date_methods,
4765 nullptr,
4766 FinishDateClassInit,
4767 };
4768
4769 const JSClass DateObject::class_ = {
4770 "Date",
4771 JSCLASS_HAS_RESERVED_SLOTS(RESERVED_SLOTS) |
4772 JSCLASS_HAS_CACHED_PROTO(JSProto_Date),
4773 JS_NULL_CLASS_OPS,
4774 &DateObjectClassSpec,
4775 };
4776
4777 const JSClass DateObject::protoClass_ = {
4778 "Date.prototype",
4779 JSCLASS_HAS_CACHED_PROTO(JSProto_Date),
4780 JS_NULL_CLASS_OPS,
4781 &DateObjectClassSpec,
4782 };
4783
4784 JSObject* js::NewDateObjectMsec(JSContext* cx, ClippedTime t,
4785 HandleObject proto /* = nullptr */) {
4786 DateObject* obj = NewObjectWithClassProto<DateObject>(cx, proto);
4787 if (!obj) {
4788 return nullptr;
4789 }
4790 obj->setUTCTime(t);
4791 return obj;
4792 }
4793
4794 JS_PUBLIC_API JSObject* JS::NewDateObject(JSContext* cx, ClippedTime time) {
4795 AssertHeapIsIdle();
4796 CHECK_THREAD(cx);
4797 return NewDateObjectMsec(cx, time);
4798 }
4799
4800 JS_PUBLIC_API JSObject* js::NewDateObject(JSContext* cx, int year, int mon,
4801 int mday, int hour, int min,
4802 int sec) {
4803 MOZ_ASSERT(mon < 12);
4804 double msec_time =
4805 MakeDate(MakeDay(year, mon, mday), MakeTime(hour, min, sec, 0.0));
4806 return NewDateObjectMsec(cx, TimeClip(UTC(ForceUTC(cx->realm()), msec_time)));
4807 }
4808
4809 JS_PUBLIC_API bool js::DateIsValid(JSContext* cx, HandleObject obj,
4810 bool* isValid) {
4811 ESClass cls;
4812 if (!GetBuiltinClass(cx, obj, &cls)) {
4813 return false;
4814 }
4815
4816 if (cls != ESClass::Date) {
4817 *isValid = false;
4818 return true;
4819 }
4820
4821 RootedValue unboxed(cx);
4822 if (!Unbox(cx, obj, &unboxed)) {
4823 return false;
4824 }
4825
4826 *isValid = !std::isnan(unboxed.toNumber());
4827 return true;
4828 }
4829
4830 JS_PUBLIC_API JSObject* JS::NewDateObject(JSContext* cx, int year, int mon,
4831 int mday, int hour, int min,
4832 int sec) {
4833 AssertHeapIsIdle();
4834 CHECK_THREAD(cx);
4835 return js::NewDateObject(cx, year, mon, mday, hour, min, sec);
4836 }
4837
4838 JS_PUBLIC_API bool JS::ObjectIsDate(JSContext* cx, Handle<JSObject*> obj,
4839 bool* isDate) {
4840 cx->check(obj);
4841
4842 ESClass cls;
4843 if (!GetBuiltinClass(cx, obj, &cls)) {
4844 return false;
4845 }
4846
4847 *isDate = cls == ESClass::Date;
4848 return true;
4849 }
4850
4851 JS_PUBLIC_API bool js::DateGetMsecSinceEpoch(JSContext* cx, HandleObject obj,
4852 double* msecsSinceEpoch) {
4853 ESClass cls;
4854 if (!GetBuiltinClass(cx, obj, &cls)) {
4855 return false;
4856 }
4857
4858 if (cls != ESClass::Date) {
4859 *msecsSinceEpoch = 0;
4860 return true;
4861 }
4862
4863 RootedValue unboxed(cx);
4864 if (!Unbox(cx, obj, &unboxed)) {
4865 return false;
4866 }
4867
4868 *msecsSinceEpoch = unboxed.toNumber();
4869 return true;
4870 }
4871
4872 JS_PUBLIC_API bool JS::IsISOStyleDate(JSContext* cx,
4873 const JS::Latin1Chars& str) {
4874 ClippedTime result;
4875 return ParseISOStyleDate(ForceUTC(cx->realm()), str.begin().get(),
4876 str.length(), &result);
4877 }