PlainTime.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655
  1. /*
  2. * Copyright (c) 2021, Idan Horowitz <idan.horowitz@serenityos.org>
  3. * Copyright (c) 2021-2022, Linus Groh <linusg@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <LibJS/Runtime/AbstractOperations.h>
  8. #include <LibJS/Runtime/Date.h>
  9. #include <LibJS/Runtime/GlobalObject.h>
  10. #include <LibJS/Runtime/Object.h>
  11. #include <LibJS/Runtime/Temporal/AbstractOperations.h>
  12. #include <LibJS/Runtime/Temporal/Calendar.h>
  13. #include <LibJS/Runtime/Temporal/Duration.h>
  14. #include <LibJS/Runtime/Temporal/Instant.h>
  15. #include <LibJS/Runtime/Temporal/PlainDateTime.h>
  16. #include <LibJS/Runtime/Temporal/PlainTime.h>
  17. #include <LibJS/Runtime/Temporal/PlainTimeConstructor.h>
  18. #include <LibJS/Runtime/Temporal/TimeZone.h>
  19. #include <LibJS/Runtime/Temporal/ZonedDateTime.h>
  20. namespace JS::Temporal {
  21. // 4 Temporal.PlainTime Objects, https://tc39.es/proposal-temporal/#sec-temporal-plaintime-objects
  22. PlainTime::PlainTime(u8 iso_hour, u8 iso_minute, u8 iso_second, u16 iso_millisecond, u16 iso_microsecond, u16 iso_nanosecond, Calendar& calendar, Object& prototype)
  23. : Object(prototype)
  24. , m_iso_hour(iso_hour)
  25. , m_iso_minute(iso_minute)
  26. , m_iso_second(iso_second)
  27. , m_iso_millisecond(iso_millisecond)
  28. , m_iso_microsecond(iso_microsecond)
  29. , m_iso_nanosecond(iso_nanosecond)
  30. , m_calendar(calendar)
  31. {
  32. }
  33. void PlainTime::visit_edges(Visitor& visitor)
  34. {
  35. Base::visit_edges(visitor);
  36. visitor.visit(&m_calendar);
  37. }
  38. // 4.5.1 DifferenceTime ( h1, min1, s1, ms1, mus1, ns1, h2, min2, s2, ms2, mus2, ns2 ), https://tc39.es/proposal-temporal/#sec-temporal-differencetime
  39. TimeDurationRecord difference_time(u8 hour1, u8 minute1, u8 second1, u16 millisecond1, u16 microsecond1, u16 nanosecond1, u8 hour2, u8 minute2, u8 second2, u16 millisecond2, u16 microsecond2, u16 nanosecond2)
  40. {
  41. // 1. Let hours be h2 - h1.
  42. auto hours = hour2 - hour1;
  43. // 2. Let minutes be min2 - min1.
  44. auto minutes = minute2 - minute1;
  45. // 3. Let seconds be s2 - s1.
  46. auto seconds = second2 - second1;
  47. // 4. Let milliseconds be ms2 - ms1.
  48. auto milliseconds = millisecond2 - millisecond1;
  49. // 5. Let microseconds be mus2 - mus1.
  50. auto microseconds = microsecond2 - microsecond1;
  51. // 6. Let nanoseconds be ns2 - ns1.
  52. auto nanoseconds = nanosecond2 - nanosecond1;
  53. // 7. Let sign be ! DurationSign(0, 0, 0, 0, hours, minutes, seconds, milliseconds, microseconds, nanoseconds).
  54. auto sign = duration_sign(0, 0, 0, 0, hours, minutes, seconds, milliseconds, microseconds, nanoseconds);
  55. // 8. Let bt be ! BalanceTime(hours × sign, minutes × sign, seconds × sign, milliseconds × sign, microseconds × sign, nanoseconds × sign).
  56. auto bt = balance_time(hours * sign, minutes * sign, seconds * sign, milliseconds * sign, microseconds * sign, nanoseconds * sign);
  57. // 9. Return ! CreateTimeDurationRecord(bt.[[Days]] × sign, bt.[[Hour]] × sign, bt.[[Minute]] × sign, bt.[[Second]] × sign, bt.[[Millisecond]] × sign, bt.[[Microsecond]] × sign, bt.[[Nanosecond]] × sign).
  58. return create_time_duration_record(static_cast<double>(bt.days * sign), static_cast<double>(bt.hour * sign), static_cast<double>(bt.minute * sign), static_cast<double>(bt.second * sign), static_cast<double>(bt.millisecond * sign), static_cast<double>(bt.microsecond * sign), static_cast<double>(bt.nanosecond * sign));
  59. }
  60. // 4.5.2 ToTemporalTime ( item [ , overflow ] ), https://tc39.es/proposal-temporal/#sec-temporal-totemporaltime
  61. ThrowCompletionOr<PlainTime*> to_temporal_time(GlobalObject& global_object, Value item, Optional<StringView> overflow)
  62. {
  63. auto& vm = global_object.vm();
  64. // 1. If overflow is not present, set overflow to "constrain".
  65. if (!overflow.has_value())
  66. overflow = "constrain"sv;
  67. // 2. Assert: overflow is either "constrain" or "reject".
  68. VERIFY(overflow == "constrain"sv || overflow == "reject"sv);
  69. Optional<TemporalTime> result;
  70. // 3. If Type(item) is Object, then
  71. if (item.is_object()) {
  72. auto& item_object = item.as_object();
  73. // a. If item has an [[InitializedTemporalTime]] internal slot, then
  74. if (is<PlainTime>(item_object)) {
  75. // i. Return item.
  76. return &static_cast<PlainTime&>(item_object);
  77. }
  78. // b. If item has an [[InitializedTemporalZonedDateTime]] internal slot, then
  79. if (is<ZonedDateTime>(item_object)) {
  80. auto& zoned_date_time = static_cast<ZonedDateTime&>(item_object);
  81. // i. Let instant be ! CreateTemporalInstant(item.[[Nanoseconds]]).
  82. auto* instant = create_temporal_instant(global_object, zoned_date_time.nanoseconds()).release_value();
  83. // ii. Set plainDateTime to ? BuiltinTimeZoneGetPlainDateTimeFor(item.[[TimeZone]], instant, item.[[Calendar]]).
  84. auto* plain_date_time = TRY(builtin_time_zone_get_plain_date_time_for(global_object, &zoned_date_time.time_zone(), *instant, zoned_date_time.calendar()));
  85. // iii. Return ! CreateTemporalTime(plainDateTime.[[ISOHour]], plainDateTime.[[ISOMinute]], plainDateTime.[[ISOSecond]], plainDateTime.[[ISOMillisecond]], plainDateTime.[[ISOMicrosecond]], plainDateTime.[[ISONanosecond]]).
  86. return TRY(create_temporal_time(global_object, plain_date_time->iso_hour(), plain_date_time->iso_minute(), plain_date_time->iso_second(), plain_date_time->iso_millisecond(), plain_date_time->iso_microsecond(), plain_date_time->iso_nanosecond()));
  87. }
  88. // c. If item has an [[InitializedTemporalDateTime]] internal slot, then
  89. if (is<PlainDateTime>(item_object)) {
  90. auto& plain_date_time = static_cast<PlainDateTime&>(item_object);
  91. // i. Return ! CreateTemporalTime(item.[[ISOHour]], item.[[ISOMinute]], item.[[ISOSecond]], item.[[ISOMillisecond]], item.[[ISOMicrosecond]], item.[[ISONanosecond]]).
  92. return TRY(create_temporal_time(global_object, plain_date_time.iso_hour(), plain_date_time.iso_minute(), plain_date_time.iso_second(), plain_date_time.iso_millisecond(), plain_date_time.iso_microsecond(), plain_date_time.iso_nanosecond()));
  93. }
  94. // d. Let calendar be ? GetTemporalCalendarWithISODefault(item).
  95. auto* calendar = TRY(get_temporal_calendar_with_iso_default(global_object, item_object));
  96. // e. If ? ToString(calendar) is not "iso8601", then
  97. auto calendar_identifier = TRY(Value(calendar).to_string(global_object));
  98. if (calendar_identifier != "iso8601"sv) {
  99. // i. Throw a RangeError exception.
  100. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidCalendarIdentifier, calendar_identifier);
  101. }
  102. // f. Let result be ? ToTemporalTimeRecord(item).
  103. auto unregulated_result = TRY(to_temporal_time_record(global_object, item_object));
  104. // g. Set result to ? RegulateTime(result.[[Hour]], result.[[Minute]], result.[[Second]], result.[[Millisecond]], result.[[Microsecond]], result.[[Nanosecond]], overflow).
  105. result = TRY(regulate_time(global_object, *unregulated_result.hour, *unregulated_result.minute, *unregulated_result.second, *unregulated_result.millisecond, *unregulated_result.microsecond, *unregulated_result.nanosecond, *overflow));
  106. }
  107. // 4. Else,
  108. else {
  109. // a. Let string be ? ToString(item).
  110. auto string = TRY(item.to_string(global_object));
  111. // b. Let result be ? ParseTemporalTimeString(string).
  112. result = TRY(parse_temporal_time_string(global_object, string));
  113. // c. Assert: IsValidTime(result.[[Hour]], result.[[Minute]], result.[[Second]], result.[[Millisecond]], result.[[Microsecond]], result.[[Nanosecond]]) is true.
  114. VERIFY(is_valid_time(result->hour, result->minute, result->second, result->millisecond, result->microsecond, result->nanosecond));
  115. // d. If result.[[Calendar]] is not one of undefined or "iso8601", then
  116. if (result->calendar.has_value() && *result->calendar != "iso8601"sv) {
  117. // i. Throw a RangeError exception.
  118. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidCalendarIdentifier, *result->calendar);
  119. }
  120. }
  121. // 5. Return ! CreateTemporalTime(result.[[Hour]], result.[[Minute]], result.[[Second]], result.[[Millisecond]], result.[[Microsecond]], result.[[Nanosecond]]).
  122. return MUST(create_temporal_time(global_object, result->hour, result->minute, result->second, result->millisecond, result->microsecond, result->nanosecond));
  123. }
  124. // 4.5.3 RegulateTime ( hour, minute, second, millisecond, microsecond, nanosecond, overflow ), https://tc39.es/proposal-temporal/#sec-temporal-regulatetime
  125. ThrowCompletionOr<TemporalTime> regulate_time(GlobalObject& global_object, double hour, double minute, double second, double millisecond, double microsecond, double nanosecond, StringView overflow)
  126. {
  127. auto& vm = global_object.vm();
  128. // 1. Assert: hour, minute, second, millisecond, microsecond and nanosecond are integers.
  129. // NOTE: As the spec is currently written this assertion can fail, these are either integers _or_ infinity.
  130. // See https://github.com/tc39/proposal-temporal/issues/1672.
  131. // 2. Assert: overflow is either "constrain" or "reject".
  132. // NOTE: Asserted by the VERIFY_NOT_REACHED at the end
  133. // 3. If overflow is "constrain", then
  134. if (overflow == "constrain"sv) {
  135. // a. Return ! ConstrainTime(hour, minute, second, millisecond, microsecond, nanosecond).
  136. return constrain_time(hour, minute, second, millisecond, microsecond, nanosecond);
  137. }
  138. // 4. If overflow is "reject", then
  139. if (overflow == "reject"sv) {
  140. // a. If IsValidTime(hour, minute, second, millisecond, microsecond, nanosecond) is false, throw a RangeError exception.
  141. if (!is_valid_time(hour, minute, second, millisecond, microsecond, nanosecond))
  142. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidPlainTime);
  143. // b. Return the Record { [[Hour]]: hour, [[Minute]]: minute, [[Second]]: second, [[Millisecond]]: millisecond, [[Microsecond]]: microsecond, [[Nanosecond]]: nanosecond }.
  144. return TemporalTime { .hour = static_cast<u8>(hour), .minute = static_cast<u8>(minute), .second = static_cast<u8>(second), .millisecond = static_cast<u16>(millisecond), .microsecond = static_cast<u16>(microsecond), .nanosecond = static_cast<u16>(nanosecond) };
  145. }
  146. VERIFY_NOT_REACHED();
  147. }
  148. // 4.5.4 IsValidTime ( hour, minute, second, millisecond, microsecond, nanosecond ), https://tc39.es/proposal-temporal/#sec-temporal-isvalidtime
  149. bool is_valid_time(double hour, double minute, double second, double millisecond, double microsecond, double nanosecond)
  150. {
  151. // 1. If hour < 0 or hour > 23, then
  152. if (hour > 23) {
  153. // a. Return false.
  154. return false;
  155. }
  156. // 2. If minute < 0 or minute > 59, then
  157. if (minute > 59) {
  158. // a. Return false.
  159. return false;
  160. }
  161. // 3. If second < 0 or second > 59, then
  162. if (second > 59) {
  163. // a. Return false.
  164. return false;
  165. }
  166. // 4. If millisecond < 0 or millisecond > 999, then
  167. if (millisecond > 999) {
  168. // a. Return false.
  169. return false;
  170. }
  171. // 5. If microsecond < 0 or microsecond > 999, then
  172. if (microsecond > 999) {
  173. // a. Return false.
  174. return false;
  175. }
  176. // 6. If nanosecond < 0 or nanosecond > 999, then
  177. if (nanosecond > 999) {
  178. // a. Return false.
  179. return false;
  180. }
  181. // 7. Return true.
  182. return true;
  183. }
  184. // 4.5.5 BalanceTime ( hour, minute, second, millisecond, microsecond, nanosecond ), https://tc39.es/proposal-temporal/#sec-temporal-balancetime
  185. DaysAndTime balance_time(double hour, double minute, double second, double millisecond, double microsecond, double nanosecond)
  186. {
  187. // 1. Assert: hour, minute, second, millisecond, microsecond, and nanosecond are integers.
  188. VERIFY(hour == trunc(hour) && minute == trunc(minute) && second == trunc(second) && millisecond == trunc(millisecond) && microsecond == trunc(microsecond) && nanosecond == trunc(nanosecond));
  189. // 2. Set microsecond to microsecond + floor(nanosecond / 1000).
  190. microsecond += floor(nanosecond / 1000);
  191. // 3. Set nanosecond to nanosecond modulo 1000.
  192. nanosecond = modulo(nanosecond, 1000);
  193. // 4. Set millisecond to millisecond + floor(microsecond / 1000).
  194. millisecond += floor(microsecond / 1000);
  195. // 5. Set microsecond to microsecond modulo 1000.
  196. microsecond = modulo(microsecond, 1000);
  197. // 6. Set second to second + floor(millisecond / 1000).
  198. second += floor(millisecond / 1000);
  199. // 7. Set millisecond to millisecond modulo 1000.
  200. millisecond = modulo(millisecond, 1000);
  201. // 8. Set minute to minute + floor(second / 60).
  202. minute += floor(second / 60);
  203. // 9. Set second to second modulo 60.
  204. second = modulo(second, 60);
  205. // 10. Set hour to hour + floor(minute / 60).
  206. hour += floor(minute / 60);
  207. // 11. Set minute to minute modulo 60.
  208. minute = modulo(minute, 60);
  209. // 12. Let days be floor(hour / 24).
  210. auto days = floor(hour / 24);
  211. // 13. Set hour to hour modulo 24.
  212. hour = modulo(hour, 24);
  213. // 14. Return the Record { [[Days]]: days, [[Hour]]: hour, [[Minute]]: minute, [[Second]]: second, [[Millisecond]]: millisecond, [[Microsecond]]: microsecond, [[Nanosecond]]: nanosecond }.
  214. return DaysAndTime {
  215. .days = static_cast<i32>(days),
  216. .hour = static_cast<u8>(hour),
  217. .minute = static_cast<u8>(minute),
  218. .second = static_cast<u8>(second),
  219. .millisecond = static_cast<u16>(millisecond),
  220. .microsecond = static_cast<u16>(microsecond),
  221. .nanosecond = static_cast<u16>(nanosecond),
  222. };
  223. }
  224. // 4.5.6 ConstrainTime ( hour, minute, second, millisecond, microsecond, nanosecond ), https://tc39.es/proposal-temporal/#sec-temporal-constraintime
  225. TemporalTime constrain_time(double hour, double minute, double second, double millisecond, double microsecond, double nanosecond)
  226. {
  227. // 1. Assert: hour, minute, second, millisecond, microsecond, and nanosecond are integers.
  228. // 2. Set hour to the result of clamping hour between 0 and 23.
  229. hour = clamp(hour, 0, 23);
  230. // 3. Set minute to the result of clamping minute between 0 and 59.
  231. minute = clamp(minute, 0, 59);
  232. // 4. Set second to the result of clamping second between 0 and 59.
  233. second = clamp(second, 0, 59);
  234. // 5. Set millisecond to the result of clamping millisecond between 0 and 999.
  235. millisecond = clamp(millisecond, 0, 999);
  236. // 6. Set microsecond to the result of clamping microsecond between 0 and 999.
  237. microsecond = clamp(microsecond, 0, 999);
  238. // 7. Set nanosecond to the result of clamping nanosecond between 0 and 999.
  239. nanosecond = clamp(nanosecond, 0, 999);
  240. // 8. Return the Record { [[Hour]]: hour, [[Minute]]: minute, [[Second]]: second, [[Millisecond]]: millisecond, [[Microsecond]]: microsecond, [[Nanosecond]]: nanosecond }.
  241. return TemporalTime { .hour = static_cast<u8>(hour), .minute = static_cast<u8>(minute), .second = static_cast<u8>(second), .millisecond = static_cast<u16>(millisecond), .microsecond = static_cast<u16>(microsecond), .nanosecond = static_cast<u16>(nanosecond) };
  242. }
  243. // 4.5.7 CreateTemporalTime ( hour, minute, second, millisecond, microsecond, nanosecond [ , newTarget ] ), https://tc39.es/proposal-temporal/#sec-temporal-createtemporaltime
  244. ThrowCompletionOr<PlainTime*> create_temporal_time(GlobalObject& global_object, u8 hour, u8 minute, u8 second, u16 millisecond, u16 microsecond, u16 nanosecond, FunctionObject const* new_target)
  245. {
  246. auto& vm = global_object.vm();
  247. // 1. Assert: hour, minute, second, millisecond, microsecond and nanosecond are integers.
  248. // 2. If IsValidTime(hour, minute, second, millisecond, microsecond, nanosecond) is false, throw a RangeError exception.
  249. if (!is_valid_time(hour, minute, second, millisecond, microsecond, nanosecond))
  250. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidPlainTime);
  251. // 3. If newTarget is not present, set newTarget to %Temporal.PlainTime%.
  252. if (!new_target)
  253. new_target = global_object.temporal_plain_time_constructor();
  254. // 4. Let object be ? OrdinaryCreateFromConstructor(newTarget, "%Temporal.PlainTime.prototype%", « [[InitializedTemporalTime]], [[ISOHour]], [[ISOMinute]], [[ISOSecond]], [[ISOMillisecond]], [[ISOMicrosecond]], [[ISONanosecond]], [[Calendar]] »).
  255. // 5. Set object.[[ISOHour]] to hour.
  256. // 6. Set object.[[ISOMinute]] to minute.
  257. // 7. Set object.[[ISOSecond]] to second.
  258. // 8. Set object.[[ISOMillisecond]] to millisecond.
  259. // 9. Set object.[[ISOMicrosecond]] to microsecond.
  260. // 10. Set object.[[ISONanosecond]] to nanosecond.
  261. // 11. Set object.[[Calendar]] to ! GetISO8601Calendar().
  262. auto* object = TRY(ordinary_create_from_constructor<PlainTime>(global_object, *new_target, &GlobalObject::temporal_plain_time_prototype, hour, minute, second, millisecond, microsecond, nanosecond, *get_iso8601_calendar(global_object)));
  263. // 12. Return object.
  264. return object;
  265. }
  266. // 4.5.8 ToTemporalTimeRecord ( temporalTimeLike [ , completeness ] ), https://tc39.es/proposal-temporal/#sec-temporal-totemporaltimerecord
  267. ThrowCompletionOr<UnregulatedTemporalTime> to_temporal_time_record(GlobalObject& global_object, Object const& temporal_time_like, ToTemporalTimeRecordCompleteness completeness)
  268. {
  269. auto& vm = global_object.vm();
  270. // 1. If completeness is not present, set completeness to complete.
  271. // 2. Let result be the Record { [[Hour]]: undefined, [[Minute]]: undefined, [[Second]]: undefined, [[Millisecond]]: undefined, [[Microsecond]]: undefined, [[Nanosecond]]: undefined }.
  272. auto result = UnregulatedTemporalTime {};
  273. // 3. Let any be false.
  274. auto any = false;
  275. // 4. For each row of Table 3, except the header row, in table order, do
  276. for (auto& [internal_slot, property] : temporal_time_like_properties<UnregulatedTemporalTime, Optional<double>>(vm)) {
  277. // a. Let property be the Property value of the current row.
  278. // b. Let value be ? Get(temporalTimeLike, property).
  279. auto value = TRY(temporal_time_like.get(property));
  280. // c. If value is not undefined, set any to true.
  281. if (!value.is_undefined())
  282. any = true;
  283. // d. If value is not undefined or completeness is complete, then
  284. if (!value.is_undefined() || completeness == ToTemporalTimeRecordCompleteness::Complete) {
  285. // i. Set value to ? ToIntegerThrowOnInfinity(value).
  286. auto value_number = TRY(to_integer_throw_on_infinity(global_object, value, ErrorType::TemporalPropertyMustBeFinite));
  287. // ii. Set result's internal slot whose name is the Internal Slot value of the current row to value.
  288. result.*internal_slot = value_number;
  289. }
  290. }
  291. // 5. If any is false, then
  292. if (!any) {
  293. // a. Throw a TypeError exception.
  294. return vm.throw_completion<TypeError>(global_object, ErrorType::TemporalInvalidPlainTimeLikeObject);
  295. }
  296. // 6. Return result.
  297. return result;
  298. }
  299. // 4.5.9 TemporalTimeToString ( hour, minute, second, millisecond, microsecond, nanosecond, precision ), https://tc39.es/proposal-temporal/#sec-temporal-temporaltimetostring
  300. String temporal_time_to_string(u8 hour, u8 minute, u8 second, u16 millisecond, u16 microsecond, u16 nanosecond, Variant<StringView, u8> const& precision)
  301. {
  302. // 1. Assert: hour, minute, second, millisecond, microsecond and nanosecond are integers.
  303. // 2. Let hour be ToZeroPaddedDecimalString(hour, 2).
  304. // 3. Let minute be ToZeroPaddedDecimalString(minute, 2).
  305. // 4. Let seconds be ! FormatSecondsStringPart(second, millisecond, microsecond, nanosecond, precision).
  306. auto seconds = format_seconds_string_part(second, millisecond, microsecond, nanosecond, precision);
  307. // 5. Return the string-concatenation of hour, the code unit 0x003A (COLON), minute, and seconds.
  308. return String::formatted("{:02}:{:02}{}", hour, minute, seconds);
  309. }
  310. // 4.5.10 CompareTemporalTime ( h1, min1, s1, ms1, mus1, ns1, h2, min2, s2, ms2, mus2, ns2 ), https://tc39.es/proposal-temporal/#sec-temporal-comparetemporaltime
  311. i8 compare_temporal_time(u8 hour1, u8 minute1, u8 second1, u16 millisecond1, u16 microsecond1, u16 nanosecond1, u8 hour2, u8 minute2, u8 second2, u16 millisecond2, u16 microsecond2, u16 nanosecond2)
  312. {
  313. // 1. Assert: h1, min1, s1, ms1, mus1, ns1, h2, min2, s2, ms2, mus2, and ns2 are integers.
  314. // 2. If h1 > h2, return 1.
  315. if (hour1 > hour2)
  316. return 1;
  317. // 3. If h1 < h2, return -1.
  318. if (hour1 < hour2)
  319. return -1;
  320. // 4. If min1 > min2, return 1.
  321. if (minute1 > minute2)
  322. return 1;
  323. // 5. If min1 < min2, return -1.
  324. if (minute1 < minute2)
  325. return -1;
  326. // 6. If s1 > s2, return 1.
  327. if (second1 > second2)
  328. return 1;
  329. // 7. If s1 < s2, return -1.
  330. if (second1 < second2)
  331. return -1;
  332. // 8. If ms1 > ms2, return 1.
  333. if (millisecond1 > millisecond2)
  334. return 1;
  335. // 9. If ms1 < ms2, return -1.
  336. if (millisecond1 < millisecond2)
  337. return -1;
  338. // 10. If mus1 > mus2, return 1.
  339. if (microsecond1 > microsecond2)
  340. return 1;
  341. // 11. If mus1 < mus2, return -1.
  342. if (microsecond1 < microsecond2)
  343. return -1;
  344. // 12. If ns1 > ns2, return 1.
  345. if (nanosecond1 > nanosecond2)
  346. return 1;
  347. // 13. If ns1 < ns2, return -1.
  348. if (nanosecond1 < nanosecond2)
  349. return -1;
  350. // 14. Return 0.
  351. return 0;
  352. }
  353. // 4.5.11 AddTime ( hour, minute, second, millisecond, microsecond, nanosecond, hours, minutes, seconds, milliseconds, microseconds, nanoseconds ), https://tc39.es/proposal-temporal/#sec-temporal-addtime
  354. DaysAndTime add_time(u8 hour, u8 minute, u8 second, u16 millisecond, u16 microsecond, u16 nanosecond, double hours, double minutes, double seconds, double milliseconds, double microseconds, double nanoseconds)
  355. {
  356. // 1. Assert: hour, minute, second, millisecond, microsecond, nanosecond, hours, minutes, seconds, milliseconds, microseconds, and nanoseconds are integers.
  357. VERIFY(hours == trunc(hours) && minutes == trunc(minutes) && seconds == trunc(seconds) && milliseconds == trunc(milliseconds) && microseconds == trunc(microseconds) && nanoseconds == trunc(nanoseconds));
  358. // 2. Let hour be hour + hours.
  359. auto hour_ = hour + hours;
  360. // 3. Let minute be minute + minutes.
  361. auto minute_ = minute + minutes;
  362. // 4. Let second be second + seconds.
  363. auto second_ = second + seconds;
  364. // 5. Let millisecond be millisecond + milliseconds.
  365. auto millisecond_ = millisecond + milliseconds;
  366. // 6. Let microsecond be microsecond + microseconds.
  367. auto microsecond_ = microsecond + microseconds;
  368. // 7. Let nanosecond be nanosecond + nanoseconds.
  369. auto nanosecond_ = nanosecond + nanoseconds;
  370. // 8. Return ! BalanceTime(hour, minute, second, millisecond, microsecond, nanosecond).
  371. return balance_time(hour_, minute_, second_, millisecond_, microsecond_, nanosecond_);
  372. }
  373. // 4.5.12 RoundTime ( hour, minute, second, millisecond, microsecond, nanosecond, increment, unit, roundingMode [ , dayLengthNs ] ), https://tc39.es/proposal-temporal/#sec-temporal-roundtime
  374. DaysAndTime round_time(u8 hour, u8 minute, u8 second, u16 millisecond, u16 microsecond, u16 nanosecond, u64 increment, StringView unit, StringView rounding_mode, Optional<double> day_length_ns)
  375. {
  376. // 1. Assert: hour, minute, second, millisecond, microsecond, nanosecond, and increment are integers.
  377. // 2. Let fractionalSecond be nanosecond × 10-9 + microsecond × 10-6 + millisecond × 10-3 + second.
  378. double fractional_second = nanosecond * 0.000000001 + microsecond * 0.000001 + millisecond * 0.001 + second;
  379. double quantity;
  380. // 3. If unit is "day", then
  381. if (unit == "day"sv) {
  382. // a. If dayLengthNs is not present, set dayLengthNs to nsPerDay.
  383. if (!day_length_ns.has_value())
  384. day_length_ns = ns_per_day;
  385. // b. Let quantity be (((((hour × 60 + minute) × 60 + second) × 1000 + millisecond) × 1000 + microsecond) × 1000 + nanosecond) / dayLengthNs.
  386. quantity = (((((hour * 60 + minute) * 60 + second) * 1000 + millisecond) * 1000 + microsecond) * 1000 + nanosecond) / *day_length_ns;
  387. }
  388. // 4. Else if unit is "hour", then
  389. else if (unit == "hour"sv) {
  390. // a. Let quantity be (fractionalSecond / 60 + minute) / 60 + hour.
  391. quantity = (fractional_second / 60 + minute) / 60 + hour;
  392. }
  393. // 5. Else if unit is "minute", then
  394. else if (unit == "minute"sv) {
  395. // a. Let quantity be fractionalSecond / 60 + minute.
  396. quantity = fractional_second / 60 + minute;
  397. }
  398. // 6. Else if unit is "second", then
  399. else if (unit == "second"sv) {
  400. // a. Let quantity be fractionalSecond.
  401. quantity = fractional_second;
  402. }
  403. // 7. Else if unit is "millisecond", then
  404. else if (unit == "millisecond"sv) {
  405. // a. Let quantity be nanosecond × 10-6 + microsecond × 10-3 + millisecond.
  406. quantity = nanosecond * 0.000001 + 0.001 * microsecond + millisecond;
  407. }
  408. // 8. Else if unit is "microsecond", then
  409. else if (unit == "microsecond"sv) {
  410. // a. Let quantity be nanosecond × 10-3 + microsecond.
  411. quantity = nanosecond * 0.001 + microsecond;
  412. }
  413. // 9. Else,
  414. else {
  415. // a. Assert: unit is "nanosecond".
  416. VERIFY(unit == "nanosecond"sv);
  417. // b. Let quantity be nanosecond.
  418. quantity = nanosecond;
  419. }
  420. // 10. Let result be RoundNumberToIncrement(quantity, increment, roundingMode).
  421. auto result = round_number_to_increment(quantity, increment, rounding_mode);
  422. // If unit is "day", then
  423. if (unit == "day"sv) {
  424. // a. Return the Record { [[Days]]: result, [[Hour]]: 0, [[Minute]]: 0, [[Second]]: 0, [[Millisecond]]: 0, [[Microsecond]]: 0, [[Nanosecond]]: 0 }.
  425. return DaysAndTime { .days = (i32)result, .hour = 0, .minute = 0, .second = 0, .millisecond = 0, .microsecond = 0, .nanosecond = 0 };
  426. }
  427. // 12. If unit is "hour", then
  428. if (unit == "hour"sv) {
  429. // a. Return ! BalanceTime(result, 0, 0, 0, 0, 0).
  430. return balance_time(result, 0, 0, 0, 0, 0);
  431. }
  432. // 13. If unit is "minute", then
  433. if (unit == "minute"sv) {
  434. // a. Return ! BalanceTime(hour, result, 0, 0, 0, 0).
  435. return balance_time(hour, result, 0, 0, 0, 0);
  436. }
  437. // 14. If unit is "second", then
  438. if (unit == "second"sv) {
  439. // a. Return ! BalanceTime(hour, minute, result, 0, 0, 0).
  440. return balance_time(hour, minute, result, 0, 0, 0);
  441. }
  442. // 15. If unit is "millisecond", then
  443. if (unit == "millisecond"sv) {
  444. // a. Return ! BalanceTime(hour, minute, second, result, 0, 0).
  445. return balance_time(hour, minute, second, result, 0, 0);
  446. }
  447. // 16. If unit is "microsecond", then
  448. if (unit == "microsecond"sv) {
  449. // a. Return ! BalanceTime(hour, minute, second, millisecond, result, 0).
  450. return balance_time(hour, minute, second, millisecond, result, 0);
  451. }
  452. // 17. Assert: unit is "nanosecond".
  453. VERIFY(unit == "nanosecond"sv);
  454. // 18. Return ! BalanceTime(hour, minute, second, millisecond, microsecond, result).
  455. return balance_time(hour, minute, second, millisecond, microsecond, result);
  456. }
  457. // 4.5.13 DifferenceTemporalPlainTime ( operation, temporalTime, other, options ), https://tc39.es/proposal-temporal/#sec-temporal-differencetemporalplaintime
  458. ThrowCompletionOr<Duration*> difference_temporal_plain_time(GlobalObject& global_object, DifferenceOperation operation, PlainTime const& temporal_time, Value other_value, Value options_value)
  459. {
  460. auto& vm = global_object.vm();
  461. // 1. If operation is since, let sign be -1. Otherwise, let sign be 1.
  462. i8 sign = operation == DifferenceOperation::Since ? -1 : 1;
  463. // 2. Set other to ? ToTemporalTime(other).
  464. auto* other = TRY(to_temporal_time(global_object, other_value));
  465. // 3. Set options to ? GetOptionsObject(options).
  466. auto const* options = TRY(get_options_object(global_object, options_value));
  467. // 4. Let smallestUnit be ? GetTemporalUnit(options, "smallestUnit", time, "nanosecond").
  468. auto smallest_unit = TRY(get_temporal_unit(global_object, *options, vm.names.smallestUnit, UnitGroup::Time, { "nanosecond"sv }));
  469. // 5. Let largestUnit be ? GetTemporalUnit(options, "largestUnit", time, "auto").
  470. auto largest_unit = TRY(get_temporal_unit(global_object, *options, vm.names.largestUnit, UnitGroup::Time, { "auto"sv }));
  471. // 6. If largestUnit is "auto", set largestUnit to "hour".
  472. if (largest_unit == "auto"sv)
  473. largest_unit = "hour"sv;
  474. // 7. If LargerOfTwoTemporalUnits(largestUnit, smallestUnit) is not largestUnit, throw a RangeError exception.
  475. if (larger_of_two_temporal_units(*largest_unit, *smallest_unit) != largest_unit)
  476. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidUnitRange, *smallest_unit, *largest_unit);
  477. // 8. Let roundingMode be ? ToTemporalRoundingMode(options, "trunc").
  478. auto rounding_mode = TRY(to_temporal_rounding_mode(global_object, *options, "trunc"sv));
  479. // 9. If operation is since, then
  480. if (operation == DifferenceOperation::Since) {
  481. // a. Set roundingMode to ! NegateTemporalRoundingMode(roundingMode).
  482. rounding_mode = negate_temporal_rounding_mode(rounding_mode);
  483. }
  484. // 10. Let maximum be ! MaximumTemporalDurationRoundingIncrement(smallestUnit).
  485. auto maximum = maximum_temporal_duration_rounding_increment(*smallest_unit);
  486. // 11. Let roundingIncrement be ? ToTemporalRoundingIncrement(options, maximum, false).
  487. auto rounding_increment = TRY(to_temporal_rounding_increment(global_object, *options, Optional<double>(maximum), false));
  488. // 12. Let result be ! DifferenceTime(temporalTime.[[ISOHour]], temporalTime.[[ISOMinute]], temporalTime.[[ISOSecond]], temporalTime.[[ISOMillisecond]], temporalTime.[[ISOMicrosecond]], temporalTime.[[ISONanosecond]], other.[[ISOHour]], other.[[ISOMinute]], other.[[ISOSecond]], other.[[ISOMillisecond]], other.[[ISOMicrosecond]], other.[[ISONanosecond]]).
  489. auto result = difference_time(temporal_time.iso_hour(), temporal_time.iso_minute(), temporal_time.iso_second(), temporal_time.iso_millisecond(), temporal_time.iso_microsecond(), temporal_time.iso_nanosecond(), other->iso_hour(), other->iso_minute(), other->iso_second(), other->iso_millisecond(), other->iso_microsecond(), other->iso_nanosecond());
  490. // 13. Set result to (? RoundDuration(0, 0, 0, 0, result.[[Hours]], result.[[Minutes]], result.[[Seconds]], result.[[Milliseconds]], result.[[Microseconds]], result.[[Nanoseconds]], roundingIncrement, smallestUnit, roundingMode)).[[DurationRecord]].
  491. auto rounded_result = TRY(round_duration(global_object, 0, 0, 0, 0, result.hours, result.minutes, result.seconds, result.milliseconds, result.microseconds, result.nanoseconds, rounding_increment, *smallest_unit, rounding_mode)).duration_record;
  492. // 14. Set result to ? BalanceDuration(0, result.[[Hours]], result.[[Minutes]], result.[[Seconds]], result.[[Milliseconds]], result.[[Microseconds]], result.[[Nanoseconds]], largestUnit).
  493. result = MUST(balance_duration(global_object, 0, rounded_result.hours, rounded_result.minutes, rounded_result.seconds, rounded_result.milliseconds, rounded_result.microseconds, Crypto::SignedBigInteger { (i32)rounded_result.nanoseconds }, *largest_unit));
  494. // 15. Return ! CreateTemporalDuration(0, 0, 0, 0, sign × result.[[Hours]], sign × result.[[Minutes]], sign × result.[[Seconds]], sign × result.[[Milliseconds]], sign × result.[[Microseconds]], sign × result.[[Nanoseconds]]).
  495. return MUST(create_temporal_duration(global_object, 0, 0, 0, 0, sign * result.hours, sign * result.minutes, sign * result.seconds, sign * result.milliseconds, sign * result.microseconds, sign * result.nanoseconds));
  496. }
  497. // 4.5.14 AddDurationToOrSubtractDurationFromPlainTime ( operation, temporalTime, temporalDurationLike ), https://tc39.es/proposal-temporal/#sec-temporal-adddurationtoorsubtractdurationfromplaintime
  498. ThrowCompletionOr<PlainTime*> add_duration_to_or_subtract_duration_from_plain_time(GlobalObject& global_object, ArithmeticOperation operation, PlainTime const& temporal_time, Value temporal_duration_like)
  499. {
  500. // 1. If operation is subtract, let sign be -1. Otherwise, let sign be 1.
  501. i8 sign = operation == ArithmeticOperation::Subtract ? -1 : 1;
  502. // 2. Let duration be ? ToTemporalDurationRecord(temporalDurationLike).
  503. auto duration = TRY(to_temporal_duration_record(global_object, temporal_duration_like));
  504. // 3. Let result be ! AddTime(temporalTime.[[ISOHour]], temporalTime.[[ISOMinute]], temporalTime.[[ISOSecond]], temporalTime.[[ISOMillisecond]], temporalTime.[[ISOMicrosecond]], temporalTime.[[ISONanosecond]], sign × duration.[[Hours]], sign × duration.[[Minutes]], sign × duration.[[Seconds]], sign × duration.[[Milliseconds]], sign × duration.[[Microseconds]], sign × duration.[[Nanoseconds]]).
  505. auto result = add_time(temporal_time.iso_hour(), temporal_time.iso_minute(), temporal_time.iso_second(), temporal_time.iso_millisecond(), temporal_time.iso_microsecond(), temporal_time.iso_nanosecond(), sign * duration.hours, sign * duration.minutes, sign * duration.seconds, sign * duration.milliseconds, sign * duration.microseconds, sign * duration.nanoseconds);
  506. // 4. Assert: IsValidTime(result.[[Hour]], result.[[Minute]], result.[[Second]], result.[[Millisecond]], result.[[Microsecond]], result.[[Nanosecond]]) is true.
  507. VERIFY(is_valid_time(result.hour, result.minute, result.second, result.millisecond, result.microsecond, result.nanosecond));
  508. // 5. Return ! CreateTemporalTime(result.[[Hour]], result.[[Minute]], result.[[Second]], result.[[Millisecond]], result.[[Microsecond]], result.[[Nanosecond]]).
  509. return MUST(create_temporal_time(global_object, result.hour, result.minute, result.second, result.millisecond, result.microsecond, result.nanosecond));
  510. }
  511. }