TimeZone.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. /*
  2. * Copyright (c) 2021, Linus Groh <linusg@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/DateTimeLexer.h>
  7. #include <LibJS/Runtime/AbstractOperations.h>
  8. #include <LibJS/Runtime/GlobalObject.h>
  9. #include <LibJS/Runtime/Temporal/TimeZone.h>
  10. #include <LibJS/Runtime/Temporal/TimeZoneConstructor.h>
  11. namespace JS::Temporal {
  12. // 11 Temporal.TimeZone Objects, https://tc39.es/proposal-temporal/#sec-temporal-timezone-objects
  13. TimeZone::TimeZone(String identifier, Object& prototype)
  14. : Object(prototype)
  15. , m_identifier(move(identifier))
  16. {
  17. }
  18. // 11.1.1 IsValidTimeZoneName ( timeZone ), https://tc39.es/proposal-temporal/#sec-isvalidtimezonename
  19. // NOTE: This is the minimum implementation of IsValidTimeZoneName, supporting only the "UTC" time zone.
  20. bool is_valid_time_zone_name(String const& time_zone)
  21. {
  22. // 1. Assert: Type(timeZone) is String.
  23. // 2. Let tzText be ! StringToCodePoints(timeZone).
  24. // 3. Let tzUpperText be the result of toUppercase(tzText), according to the Unicode Default Case Conversion algorithm.
  25. // 4. Let tzUpper be ! CodePointsToString(tzUpperText).
  26. auto tz_upper = time_zone.to_uppercase();
  27. // 5. If tzUpper and "UTC" are the same sequence of code points, return true.
  28. if (tz_upper == "UTC")
  29. return true;
  30. // 6. Return false.
  31. return false;
  32. }
  33. // 11.1.2 CanonicalizeTimeZoneName ( timeZone ), https://tc39.es/proposal-temporal/#sec-canonicalizetimezonename
  34. // NOTE: This is the minimum implementation of CanonicalizeTimeZoneName, supporting only the "UTC" time zone.
  35. String canonicalize_time_zone_name(String const& time_zone)
  36. {
  37. // 1. Assert: Type(timeZone) is String.
  38. // 2. Assert: ! IsValidTimeZoneName(timeZone) is true.
  39. VERIFY(is_valid_time_zone_name(time_zone));
  40. // 3. Return "UTC".
  41. return "UTC";
  42. }
  43. // 11.1.3 DefaultTimeZone ( ), https://tc39.es/proposal-temporal/#sec-defaulttimezone
  44. // NOTE: This is the minimum implementation of DefaultTimeZone, supporting only the "UTC" time zone.
  45. String default_time_zone()
  46. {
  47. // 1. Return "UTC".
  48. return "UTC";
  49. }
  50. // 11.6.2 CreateTemporalTimeZone ( identifier [ , newTarget ] ), https://tc39.es/proposal-temporal/#sec-temporal-createtemporaltimezone
  51. Object* create_temporal_time_zone(GlobalObject& global_object, String const& identifier, FunctionObject* new_target)
  52. {
  53. auto& vm = global_object.vm();
  54. // 1. If newTarget is not present, set it to %Temporal.TimeZone%.
  55. if (!new_target)
  56. new_target = global_object.temporal_time_zone_constructor();
  57. // 2. Let object be ? OrdinaryCreateFromConstructor(newTarget, "%Temporal.TimeZone.prototype%", « [[InitializedTemporalTimeZone]], [[Identifier]], [[OffsetNanoseconds]] »).
  58. // 3. Set object.[[Identifier]] to identifier.
  59. auto* object = ordinary_create_from_constructor<TimeZone>(global_object, *new_target, &GlobalObject::temporal_time_zone_prototype, identifier);
  60. if (vm.exception())
  61. return {};
  62. // 4. If identifier satisfies the syntax of a TimeZoneNumericUTCOffset (see 13.33), then
  63. if (is_valid_time_zone_numeric_utc_offset_syntax(identifier)) {
  64. // a. Set object.[[OffsetNanoseconds]] to ! ParseTimeZoneOffsetString(identifier).
  65. object->set_offset_nanoseconds(parse_time_zone_offset_string(global_object, identifier));
  66. }
  67. // 5. Else,
  68. else {
  69. // a. Assert: ! CanonicalizeTimeZoneName(identifier) is identifier.
  70. VERIFY(canonicalize_time_zone_name(identifier) == identifier);
  71. // b. Set object.[[OffsetNanoseconds]] to undefined.
  72. // NOTE: No-op.
  73. }
  74. // 6. Return object.
  75. return object;
  76. }
  77. // https://tc39.es/proposal-temporal/#prod-TimeZoneNumericUTCOffset
  78. static bool parse_time_zone_numeric_utc_offset_syntax(String const& offset_string, StringView& sign, StringView& hours, Optional<StringView>& minutes, Optional<StringView>& seconds, Optional<StringView>& fraction)
  79. {
  80. DateTimeLexer lexer(offset_string);
  81. auto sign_part = lexer.consume_sign();
  82. if (!sign_part.has_value())
  83. return false;
  84. sign = *sign_part;
  85. auto hours_part = lexer.consume_hours();
  86. if (!hours_part.has_value())
  87. return false;
  88. hours = *hours_part;
  89. if (!lexer.tell_remaining())
  90. return true;
  91. auto uses_separator = lexer.consume_specific(':');
  92. minutes = lexer.consume_minutes_or_seconds();
  93. if (!minutes.has_value())
  94. return false;
  95. if (!lexer.tell_remaining())
  96. return true;
  97. if (lexer.consume_specific(':') != uses_separator)
  98. return false;
  99. seconds = lexer.consume_minutes_or_seconds();
  100. if (!seconds.has_value())
  101. return false;
  102. if (!lexer.tell_remaining())
  103. return true;
  104. if (!lexer.consume_specific('.') && !lexer.consume_specific(','))
  105. return false;
  106. fraction = lexer.consume_fractional_seconds();
  107. return fraction.has_value();
  108. }
  109. bool is_valid_time_zone_numeric_utc_offset_syntax(String const& offset_string)
  110. {
  111. StringView discarded;
  112. Optional<StringView> optionally_discarded;
  113. // FIXME: This is very wasteful
  114. return parse_time_zone_numeric_utc_offset_syntax(offset_string, discarded, discarded, optionally_discarded, optionally_discarded, optionally_discarded);
  115. }
  116. // 11.6.8 ParseTimeZoneOffsetString ( offsetString ), https://tc39.es/proposal-temporal/#sec-temporal-parsetimezoneoffsetstring
  117. double parse_time_zone_offset_string(GlobalObject& global_object, String const& offset_string)
  118. {
  119. auto& vm = global_object.vm();
  120. // 1. Assert: Type(offsetString) is String.
  121. // 2. If offsetString does not satisfy the syntax of a TimeZoneNumericUTCOffset (see 13.33), then
  122. // a. Throw a RangeError exception.
  123. // 3. Let sign, hours, minutes, seconds, and fraction be the parts of offsetString produced respectively by the TimeZoneUTCOffsetSign, TimeZoneUTCOffsetHour, TimeZoneUTCOffsetMinute, TimeZoneUTCOffsetSecond, and TimeZoneUTCOffsetFraction productions, or undefined if not present.
  124. StringView sign_part;
  125. StringView hours_part;
  126. Optional<StringView> minutes_part;
  127. Optional<StringView> seconds_part;
  128. Optional<StringView> fraction_part;
  129. auto success = parse_time_zone_numeric_utc_offset_syntax(offset_string, sign_part, hours_part, minutes_part, seconds_part, fraction_part);
  130. if (!success) {
  131. vm.throw_exception<RangeError>(global_object, ErrorType::InvalidFormat, "TimeZone offset");
  132. return {};
  133. }
  134. // 4. If either hours or sign are undefined, throw a RangeError exception.
  135. // NOTE: Both of these checks are always false, due to the handling of Step 2
  136. double sign;
  137. // 5. If sign is the code unit 0x002D (HYPHEN-MINUS) or 0x2212 (MINUS SIGN), then
  138. if (sign_part.is_one_of("-", "\xE2\x88\x92")) {
  139. // a. Set sign to −1.
  140. sign = -1;
  141. }
  142. // 6. Else,
  143. else {
  144. // a. Set sign to 1.
  145. sign = 1;
  146. }
  147. // 7. Set hours to ! ToIntegerOrInfinity(hours).
  148. auto hours = Value(js_string(vm, hours_part)).to_integer_or_infinity(global_object);
  149. // 8. Set minutes to ! ToIntegerOrInfinity(minutes).
  150. auto minutes = Value(js_string(vm, minutes_part.value_or(""sv))).to_integer_or_infinity(global_object);
  151. // 9. Set seconds to ! ToIntegerOrInfinity(seconds).
  152. auto seconds = Value(js_string(vm, seconds_part.value_or(""sv))).to_integer_or_infinity(global_object);
  153. double nanoseconds;
  154. // 10. If fraction is not undefined, then
  155. if (fraction_part.has_value()) {
  156. // a. Set fraction to the string-concatenation of the previous value of fraction and the string "000000000".
  157. auto fraction = String::formatted("{}000000000", *fraction_part);
  158. // b. Let nanoseconds be the String value equal to the substring of fraction consisting of the code units with indices 0 (inclusive) through 9 (exclusive).
  159. // c. Set nanoseconds to ! ToIntegerOrInfinity(nanoseconds).
  160. nanoseconds = Value(js_string(vm, fraction_part->substring_view(0, 9))).to_integer_or_infinity(global_object);
  161. }
  162. // 11. Else,
  163. else {
  164. // a. Let nanoseconds be 0.
  165. nanoseconds = 0;
  166. }
  167. // 12. Return sign × (((hours × 60 + minutes) × 60 + seconds) × 10^9 + nanoseconds).
  168. return sign * (((hours * 60 + minutes) * 60 + seconds) * 1000000000 + nanoseconds);
  169. }
  170. // 11.6.9 FormatTimeZoneOffsetString ( offsetNanoseconds ), https://tc39.es/proposal-temporal/#sec-temporal-formattimezoneoffsetstring
  171. String format_time_zone_offset_string(double offset_nanoseconds)
  172. {
  173. auto offset = static_cast<i64>(offset_nanoseconds);
  174. // 1. Assert: offsetNanoseconds is an integer.
  175. VERIFY(offset == offset_nanoseconds);
  176. StringBuilder builder;
  177. // 2. If offsetNanoseconds ≥ 0, let sign be "+"; otherwise, let sign be "-".
  178. if (offset >= 0)
  179. builder.append('+');
  180. else
  181. builder.append('-');
  182. // 3. Let nanoseconds be abs(offsetNanoseconds) modulo 10^9.
  183. auto nanoseconds = abs(offset) % 1000000000;
  184. // 4. Let seconds be floor(offsetNanoseconds / 10^9) modulo 60.
  185. auto seconds = (offset / 1000000000) % 60;
  186. // 5. Let minutes be floor(offsetNanoseconds / (6 × 10^10)) modulo 60.
  187. auto minutes = (offset / 60000000000) % 60;
  188. // 6. Let hours be floor(offsetNanoseconds / (3.6 × 10^12)).
  189. auto hours = offset / 3600000000000;
  190. // 7. Let h be hours, formatted as a two-digit decimal number, padded to the left with a zero if necessary.
  191. builder.appendff("{:02}", hours);
  192. // 8. Let m be minutes, formatted as a two-digit decimal number, padded to the left with a zero if necessary.
  193. builder.appendff(":{:02}", minutes);
  194. // 9. Let s be seconds, formatted as a two-digit decimal number, padded to the left with a zero if necessary.
  195. // Handled by steps 10 & 11
  196. // 10. If nanoseconds ≠ 0, then
  197. if (nanoseconds != 0) {
  198. // a. Let fraction be nanoseconds, formatted as a nine-digit decimal number, padded to the left with zeroes if necessary.
  199. // b. Set fraction to the longest possible substring of fraction starting at position 0 and not ending with the code unit 0x0030 (DIGIT ZERO).
  200. // c. Let post be the string-concatenation of the code unit 0x003A (COLON), s, the code unit 0x002E (FULL STOP), and fraction.
  201. builder.appendff(":{:02}.{:9}", seconds, nanoseconds);
  202. }
  203. // 11. Else if seconds ≠ 0, then
  204. else if (seconds != 0) {
  205. // a. Let post be the string-concatenation of the code unit 0x003A (COLON) and s.
  206. builder.appendff(":{:02}", seconds);
  207. }
  208. // 12. Return the string-concatenation of sign, h, the code unit 0x003A (COLON), m, and post.
  209. return builder.to_string();
  210. }
  211. }