Skip to content

Commit 019211b

Browse files
trflynn89linusg
authored andcommitted
LibJS: Consolidate sources of system time zone to one location in Date
This is a normative change in the ECMA-262 spec. See: tc39/ecma262@43fd5f2 For the most part, these AOs are hoisted from Temporal. Note that despite being a normative change, the expectation is that this change does not result in any behavior differences.
1 parent e952dca commit 019211b

File tree

3 files changed

+293
-18
lines changed

3 files changed

+293
-18
lines changed

Userland/Libraries/LibJS/Runtime/Date.cpp

Lines changed: 262 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -11,11 +11,16 @@
1111
#include <LibJS/Runtime/AbstractOperations.h>
1212
#include <LibJS/Runtime/Date.h>
1313
#include <LibJS/Runtime/GlobalObject.h>
14+
#include <LibJS/Runtime/Temporal/ISO8601.h>
1415
#include <LibTimeZone/TimeZone.h>
1516
#include <time.h>
1617

1718
namespace JS {
1819

20+
static Crypto::SignedBigInteger const s_one_billion_bigint { 1'000'000'000 };
21+
static Crypto::SignedBigInteger const s_one_million_bigint { 1'000'000 };
22+
static Crypto::SignedBigInteger const s_one_thousand_bigint { 1'000 };
23+
1924
Date* Date::create(Realm& realm, double date_value)
2025
{
2126
return realm.heap().allocate<Date>(realm, date_value, *realm.intrinsics().date_prototype());
@@ -265,6 +270,7 @@ u8 week_day(double t)
265270
}
266271

267272
// 21.4.1.7 LocalTZA ( t, isUTC ), https://tc39.es/ecma262/#sec-local-time-zone-adjustment
273+
// FIXME: Remove this when ECMA-402 is synced with https://github.com/tc39/ecma262/commit/43fd5f25357333d8340bfb486b8f0738e6d0d0cb.
268274
double local_tza(double time, [[maybe_unused]] bool is_utc, Optional<StringView> time_zone_override)
269275
{
270276
// The time_zone_override parameter is non-standard, but allows callers to override the system
@@ -285,21 +291,160 @@ double local_tza(double time, [[maybe_unused]] bool is_utc, Optional<StringView>
285291
return maybe_offset.has_value() ? static_cast<double>(maybe_offset->seconds) * 1000 : 0;
286292
}
287293

288-
// 21.4.1.8 LocalTime ( t ), https://tc39.es/ecma262/#sec-localtime
294+
// 21.4.1.7 GetUTCEpochNanoseconds ( year, month, day, hour, minute, second, millisecond, microsecond, nanosecond ), https://tc39.es/ecma262/#sec-getutcepochnanoseconds
295+
Crypto::SignedBigInteger get_utc_epoch_nanoseconds(i32 year, u8 month, u8 day, u8 hour, u8 minute, u8 second, u16 millisecond, u16 microsecond, u16 nanosecond)
296+
{
297+
// 1. Let date be MakeDay(𝔽(year), 𝔽(month - 1), 𝔽(day)).
298+
auto date = make_day(year, month - 1, day);
299+
300+
// 2. Let time be MakeTime(𝔽(hour), 𝔽(minute), 𝔽(second), 𝔽(millisecond)).
301+
auto time = make_time(hour, minute, second, millisecond);
302+
303+
// 3. Let ms be MakeDate(date, time).
304+
auto ms = make_date(date, time);
305+
306+
// 4. Assert: ms is an integral Number.
307+
VERIFY(ms == trunc(ms));
308+
309+
// 5. Return ℤ(ℝ(ms) × 10^6 + microsecond × 10^3 + nanosecond).
310+
auto result = Crypto::SignedBigInteger { ms }.multiplied_by(s_one_million_bigint);
311+
result = result.plus(Crypto::SignedBigInteger { static_cast<i32>(microsecond) }.multiplied_by(s_one_thousand_bigint));
312+
result = result.plus(Crypto::SignedBigInteger { static_cast<i32>(nanosecond) });
313+
return result;
314+
}
315+
316+
static i64 clip_bigint_to_sane_time(Crypto::SignedBigInteger const& value)
317+
{
318+
static Crypto::SignedBigInteger const min_bigint { NumericLimits<i64>::min() };
319+
static Crypto::SignedBigInteger const max_bigint { NumericLimits<i64>::max() };
320+
321+
// The provided epoch (nano)seconds value is potentially out of range for AK::Time and subsequently
322+
// get_time_zone_offset(). We can safely assume that the TZDB has no useful information that far
323+
// into the past and future anyway, so clamp it to the i64 range.
324+
if (value < min_bigint)
325+
return NumericLimits<i64>::min();
326+
if (value > max_bigint)
327+
return NumericLimits<i64>::max();
328+
329+
// FIXME: Can we do this without string conversion?
330+
return value.to_base(10).to_int<i64>().value();
331+
}
332+
333+
// 21.4.1.8 GetNamedTimeZoneEpochNanoseconds ( timeZoneIdentifier, year, month, day, hour, minute, second, millisecond, microsecond, nanosecond ), https://tc39.es/ecma262/#sec-getnamedtimezoneepochnanoseconds
334+
Vector<Crypto::SignedBigInteger> get_named_time_zone_epoch_nanoseconds(StringView time_zone_identifier, i32 year, u8 month, u8 day, u8 hour, u8 minute, u8 second, u16 millisecond, u16 microsecond, u16 nanosecond)
335+
{
336+
auto local_nanoseconds = get_utc_epoch_nanoseconds(year, month, day, hour, minute, second, millisecond, microsecond, nanosecond);
337+
auto local_time = Time::from_nanoseconds(clip_bigint_to_sane_time(local_nanoseconds));
338+
339+
// FIXME: LibTimeZone does not behave exactly as the spec expects. It does not consider repeated or skipped time points.
340+
auto offset = TimeZone::get_time_zone_offset(time_zone_identifier, local_time);
341+
342+
// Can only fail if the time zone identifier is invalid, which cannot be the case here.
343+
VERIFY(offset.has_value());
344+
345+
return { local_nanoseconds.plus(Crypto::SignedBigInteger { offset->seconds }.multiplied_by(s_one_billion_bigint)) };
346+
}
347+
348+
// 21.4.1.9 GetNamedTimeZoneOffsetNanoseconds ( timeZoneIdentifier, epochNanoseconds ), https://tc39.es/ecma262/#sec-getnamedtimezoneoffsetnanoseconds
349+
i64 get_named_time_zone_offset_nanoseconds(StringView time_zone_identifier, Crypto::SignedBigInteger const& epoch_nanoseconds)
350+
{
351+
// Only called with validated time zone identifier as argument.
352+
auto time_zone = TimeZone::time_zone_from_string(time_zone_identifier);
353+
VERIFY(time_zone.has_value());
354+
355+
// Since Time::from_seconds() and Time::from_nanoseconds() both take an i64, converting to
356+
// seconds first gives us a greater range. The TZDB doesn't have sub-second offsets.
357+
auto seconds = epoch_nanoseconds.divided_by(s_one_billion_bigint).quotient;
358+
auto time = Time::from_seconds(clip_bigint_to_sane_time(seconds));
359+
360+
auto offset = TimeZone::get_time_zone_offset(*time_zone, time);
361+
VERIFY(offset.has_value());
362+
363+
return offset->seconds * 1'000'000'000;
364+
}
365+
366+
// 21.4.1.10 DefaultTimeZone ( ), https://tc39.es/ecma262/#sec-defaulttimezone
367+
StringView default_time_zone()
368+
{
369+
return TimeZone::current_time_zone();
370+
}
371+
372+
// 21.4.1.11 LocalTime ( t ), https://tc39.es/ecma262/#sec-localtime
289373
double local_time(double time)
290374
{
291-
// 1. Return t + LocalTZA(t, true).
292-
return time + local_tza(time, true);
375+
// 1. Let localTimeZone be DefaultTimeZone().
376+
auto local_time_zone = default_time_zone();
377+
378+
double offset_nanoseconds { 0 };
379+
380+
// 2. If IsTimeZoneOffsetString(localTimeZone) is true, then
381+
if (is_time_zone_offset_string(local_time_zone)) {
382+
// a. Let offsetNs be ParseTimeZoneOffsetString(localTimeZone).
383+
offset_nanoseconds = parse_time_zone_offset_string(local_time_zone);
384+
}
385+
// 3. Else,
386+
else {
387+
// a. Let offsetNs be GetNamedTimeZoneOffsetNanoseconds(localTimeZone, ℤ(ℝ(t) × 10^6)).
388+
auto time_bigint = Crypto::SignedBigInteger { time }.multiplied_by(s_one_million_bigint);
389+
offset_nanoseconds = get_named_time_zone_offset_nanoseconds(local_time_zone, time_bigint);
390+
}
391+
392+
// 4. Let offsetMs be truncate(offsetNs / 10^6).
393+
auto offset_milliseconds = trunc(offset_nanoseconds / 1e6);
394+
395+
// 5. Return t + 𝔽(offsetMs).
396+
return time + offset_milliseconds;
293397
}
294398

295-
// 21.4.1.9 UTC ( t ), https://tc39.es/ecma262/#sec-utc-t
399+
// 21.4.1.12 UTC ( t ), https://tc39.es/ecma262/#sec-utc-t
296400
double utc_time(double time)
297401
{
298-
// 1. Return t - LocalTZA(t, false).
299-
return time - local_tza(time, false);
402+
// 1. Let localTimeZone be DefaultTimeZone().
403+
auto local_time_zone = default_time_zone();
404+
405+
double offset_nanoseconds { 0 };
406+
407+
// 2. If IsTimeZoneOffsetString(localTimeZone) is true, then
408+
if (is_time_zone_offset_string(local_time_zone)) {
409+
// a. Let offsetNs be ParseTimeZoneOffsetString(localTimeZone).
410+
offset_nanoseconds = parse_time_zone_offset_string(local_time_zone);
411+
}
412+
// 3. Else,
413+
else {
414+
// a. Let possibleInstants be GetNamedTimeZoneEpochNanoseconds(localTimeZone, ℝ(YearFromTime(t)), ℝ(MonthFromTime(t)) + 1, ℝ(DateFromTime(t)), ℝ(HourFromTime(t)), ℝ(MinFromTime(t)), ℝ(SecFromTime(t)), ℝ(msFromTime(t)), 0, 0).
415+
auto possible_instants = get_named_time_zone_epoch_nanoseconds(local_time_zone, year_from_time(time), month_from_time(time) + 1, date_from_time(time), hour_from_time(time), min_from_time(time), sec_from_time(time), ms_from_time(time), 0, 0);
416+
417+
// b. NOTE: The following steps ensure that when t represents local time repeating multiple times at a negative time zone transition (e.g. when the daylight saving time ends or the time zone offset is decreased due to a time zone rule change) or skipped local time at a positive time zone transition (e.g. when the daylight saving time starts or the time zone offset is increased due to a time zone rule change), t is interpreted using the time zone offset before the transition.
418+
Crypto::SignedBigInteger disambiguated_instant;
419+
420+
// c. If possibleInstants is not empty, then
421+
if (!possible_instants.is_empty()) {
422+
// i. Let disambiguatedInstant be possibleInstants[0].
423+
disambiguated_instant = move(possible_instants.first());
424+
}
425+
// d. Else,
426+
else {
427+
// i. NOTE: t represents a local time skipped at a positive time zone transition (e.g. due to daylight saving time starting or a time zone rule change increasing the UTC offset).
428+
// ii. Let possibleInstantsBefore be GetNamedTimeZoneEpochNanoseconds(localTimeZone, ℝ(YearFromTime(tBefore)), ℝ(MonthFromTime(tBefore)) + 1, ℝ(DateFromTime(tBefore)), ℝ(HourFromTime(tBefore)), ℝ(MinFromTime(tBefore)), ℝ(SecFromTime(tBefore)), ℝ(msFromTime(tBefore)), 0, 0), where tBefore is the largest integral Number < t for which possibleInstantsBefore is not empty (i.e., tBefore represents the last local time before the transition).
429+
// iii. Let disambiguatedInstant be the last element of possibleInstantsBefore.
430+
431+
// FIXME: This branch currently cannot be reached with our implementation, because LibTimeZone does not handle skipped time points.
432+
// When GetNamedTimeZoneEpochNanoseconds is updated to use a LibTimeZone API which does handle them, implement these steps.
433+
VERIFY_NOT_REACHED();
434+
}
435+
436+
// e. Let offsetNs be GetNamedTimeZoneOffsetNanoseconds(localTimeZone, disambiguatedInstant).
437+
offset_nanoseconds = get_named_time_zone_offset_nanoseconds(local_time_zone, disambiguated_instant);
438+
}
439+
440+
// 4. Let offsetMs be truncate(offsetNs / 10^6).
441+
auto offset_milliseconds = trunc(offset_nanoseconds / 1e6);
442+
443+
// 5. Return t - 𝔽(offsetMs).
444+
return time - offset_milliseconds;
300445
}
301446

302-
// 21.4.1.11 MakeTime ( hour, min, sec, ms ), https://tc39.es/ecma262/#sec-maketime
447+
// 21.4.1.14 MakeTime ( hour, min, sec, ms ), https://tc39.es/ecma262/#sec-maketime
303448
double make_time(double hour, double min, double sec, double ms)
304449
{
305450
// 1. If hour is not finite or min is not finite or sec is not finite or ms is not finite, return NaN.
@@ -334,7 +479,7 @@ double time_within_day(double time)
334479
return modulo(time, ms_per_day);
335480
}
336481

337-
// 21.4.1.12 MakeDay ( year, month, date ), https://tc39.es/ecma262/#sec-makeday
482+
// 21.4.1.15 MakeDay ( year, month, date ), https://tc39.es/ecma262/#sec-makeday
338483
double make_day(double year, double month, double date)
339484
{
340485
// 1. If year is not finite or month is not finite or date is not finite, return NaN.
@@ -367,7 +512,7 @@ double make_day(double year, double month, double date)
367512
return day(static_cast<double>(t)) + dt - 1;
368513
}
369514

370-
// 21.4.1.13 MakeDate ( day, time ), https://tc39.es/ecma262/#sec-makedate
515+
// 21.4.1.16 MakeDate ( day, time ), https://tc39.es/ecma262/#sec-makedate
371516
double make_date(double day, double time)
372517
{
373518
// 1. If day is not finite or time is not finite, return NaN.
@@ -385,7 +530,7 @@ double make_date(double day, double time)
385530
return tv;
386531
}
387532

388-
// 21.4.1.14 TimeClip ( time ), https://tc39.es/ecma262/#sec-timeclip
533+
// 21.4.1.17 TimeClip ( time ), https://tc39.es/ecma262/#sec-timeclip
389534
double time_clip(double time)
390535
{
391536
// 1. If time is not finite, return NaN.
@@ -400,4 +545,111 @@ double time_clip(double time)
400545
return to_integer_or_infinity(time);
401546
}
402547

548+
// 21.4.1.19.1 IsTimeZoneOffsetString ( offsetString ), https://tc39.es/ecma262/#sec-istimezoneoffsetstring
549+
bool is_time_zone_offset_string(StringView offset_string)
550+
{
551+
// 1. Let parseResult be ParseText(StringToCodePoints(offsetString), UTCOffset).
552+
auto parse_result = Temporal::parse_iso8601(Temporal::Production::TimeZoneNumericUTCOffset, offset_string);
553+
554+
// 2. If parseResult is a List of errors, return false.
555+
// 3. Return true.
556+
return parse_result.has_value();
557+
}
558+
559+
// 21.4.1.19.2 ParseTimeZoneOffsetString ( offsetString ), https://tc39.es/ecma262/#sec-parsetimezoneoffsetstring
560+
double parse_time_zone_offset_string(StringView offset_string)
561+
{
562+
// 1. Let parseResult be ParseText(StringToCodePoints(offsetString), UTCOffset).
563+
auto parse_result = Temporal::parse_iso8601(Temporal::Production::TimeZoneNumericUTCOffset, offset_string);
564+
565+
// 2. Assert: parseResult is not a List of errors.
566+
VERIFY(parse_result.has_value());
567+
568+
// 3. Assert: parseResult contains a TemporalSign Parse Node.
569+
VERIFY(parse_result->time_zone_utc_offset_sign.has_value());
570+
571+
// 4. Let parsedSign be the source text matched by the TemporalSign Parse Node contained within parseResult.
572+
auto parsed_sign = *parse_result->time_zone_utc_offset_sign;
573+
i8 sign { 0 };
574+
575+
// 5. If parsedSign is the single code point U+002D (HYPHEN-MINUS) or U+2212 (MINUS SIGN), then
576+
if (parsed_sign.is_one_of("-"sv, "\xE2\x88\x92"sv)) {
577+
// a. Let sign be -1.
578+
sign = -1;
579+
}
580+
// 6. Else,
581+
else {
582+
// a. Let sign be 1.
583+
sign = 1;
584+
}
585+
586+
// 7. NOTE: Applications of StringToNumber below do not lose precision, since each of the parsed values is guaranteed to be a sufficiently short string of decimal digits.
587+
588+
// 8. Assert: parseResult contains an Hour Parse Node.
589+
VERIFY(parse_result->time_zone_utc_offset_hour.has_value());
590+
591+
// 9. Let parsedHours be the source text matched by the Hour Parse Node contained within parseResult.
592+
auto parsed_hours = *parse_result->time_zone_utc_offset_hour;
593+
594+
// 10. Let hours be ℝ(StringToNumber(CodePointsToString(parsedHours))).
595+
auto hours = string_to_number(parsed_hours)->as_double();
596+
597+
double minutes { 0 };
598+
double seconds { 0 };
599+
double nanoseconds { 0 };
600+
601+
// 11. If parseResult does not contain a MinuteSecond Parse Node, then
602+
if (!parse_result->time_zone_utc_offset_minute.has_value()) {
603+
// a. Let minutes be 0.
604+
minutes = 0;
605+
}
606+
// 12. Else,
607+
else {
608+
// a. Let parsedMinutes be the source text matched by the first MinuteSecond Parse Node contained within parseResult.
609+
auto parsed_minutes = *parse_result->time_zone_utc_offset_minute;
610+
611+
// b. Let minutes be ℝ(StringToNumber(CodePointsToString(parsedMinutes))).
612+
minutes = string_to_number(parsed_minutes)->as_double();
613+
}
614+
615+
// 13. If parseResult does not contain two MinuteSecond Parse Nodes, then
616+
if (!parse_result->time_zone_utc_offset_second.has_value()) {
617+
// a. Let seconds be 0.
618+
seconds = 0;
619+
}
620+
// 14. Else,
621+
else {
622+
// a. Let parsedSeconds be the source text matched by the second secondSecond Parse Node contained within parseResult.
623+
auto parsed_seconds = *parse_result->time_zone_utc_offset_second;
624+
625+
// b. Let seconds be ℝ(StringToNumber(CodePointsToString(parsedSeconds))).
626+
seconds = string_to_number(parsed_seconds)->as_double();
627+
}
628+
629+
// 15. If parseResult does not contain a TemporalDecimalFraction Parse Node, then
630+
if (!parse_result->time_zone_utc_offset_fraction.has_value()) {
631+
// a. Let nanoseconds be 0.
632+
nanoseconds = 0;
633+
}
634+
// 16. Else,
635+
else {
636+
// a. Let parsedFraction be the source text matched by the TemporalDecimalFraction Parse Node contained within parseResult.
637+
auto parsed_fraction = *parse_result->time_zone_utc_offset_fraction;
638+
639+
// b. Let fraction be the string-concatenation of CodePointsToString(parsedFraction) and "000000000".
640+
auto fraction = String::formatted("{}000000000", parsed_fraction);
641+
642+
// c. Let nanosecondsString be the substring of fraction from 1 to 10.
643+
auto nanoseconds_string = fraction.substring_view(1, 9);
644+
645+
// d. Let nanoseconds be ℝ(StringToNumber(nanosecondsString)).
646+
nanoseconds = string_to_number(nanoseconds_string)->as_double();
647+
}
648+
649+
// 17. Return sign × (((hours × 60 + minutes) × 60 + seconds) × 10^9 + nanoseconds).
650+
// NOTE: Using scientific notation (1e9) ensures the result of this expression is a double,
651+
// which is important - otherwise it's all integers and the result overflows!
652+
return sign * (((hours * 60 + minutes) * 60 + seconds) * 1e9 + nanoseconds);
653+
}
654+
403655
}

Userland/Libraries/LibJS/Runtime/Date.h

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,10 @@ u8 sec_from_time(double);
6363
u16 ms_from_time(double);
6464
u8 week_day(double);
6565
double local_tza(double time, bool is_utc, Optional<StringView> time_zone_override = {});
66+
Crypto::SignedBigInteger get_utc_epoch_nanoseconds(i32 year, u8 month, u8 day, u8 hour, u8 minute, u8 second, u16 millisecond, u16 microsecond, u16 nanosecond);
67+
Vector<Crypto::SignedBigInteger> get_named_time_zone_epoch_nanoseconds(StringView time_zone_identifier, i32 year, u8 month, u8 day, u8 hour, u8 minute, u8 second, u16 millisecond, u16 microsecond, u16 nanosecond);
68+
i64 get_named_time_zone_offset_nanoseconds(StringView time_zone_identifier, Crypto::SignedBigInteger const& epoch_nanoseconds);
69+
StringView default_time_zone();
6670
double local_time(double time);
6771
double utc_time(double time);
6872
double day(double);
@@ -71,5 +75,7 @@ double make_time(double hour, double min, double sec, double ms);
7175
double make_day(double year, double month, double date);
7276
double make_date(double day, double time);
7377
double time_clip(double time);
78+
bool is_time_zone_offset_string(StringView offset_string);
79+
double parse_time_zone_offset_string(StringView offset_string);
7480

7581
}

0 commit comments

Comments
 (0)