DateConstructor.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. /*
  2. * Copyright (c) 2020-2023, Linus Groh <linusg@serenityos.org>
  3. * Copyright (c) 2020, Nico Weber <thakis@chromium.org>
  4. * Copyright (c) 2021, Petróczi Zoltán <petroczizoltan@tutanota.com>
  5. * Copyright (c) 2022, Tim Flynn <trflynn89@serenityos.org>
  6. *
  7. * SPDX-License-Identifier: BSD-2-Clause
  8. */
  9. #include <AK/CharacterTypes.h>
  10. #include <AK/GenericLexer.h>
  11. #include <AK/Time.h>
  12. #include <LibCore/DateTime.h>
  13. #include <LibJS/Runtime/AbstractOperations.h>
  14. #include <LibJS/Runtime/Date.h>
  15. #include <LibJS/Runtime/DateConstructor.h>
  16. #include <LibJS/Runtime/DatePrototype.h>
  17. #include <LibJS/Runtime/GlobalObject.h>
  18. #include <LibJS/Runtime/VM.h>
  19. #include <LibJS/Runtime/ValueInlines.h>
  20. #include <sys/time.h>
  21. #include <time.h>
  22. namespace JS {
  23. GC_DEFINE_ALLOCATOR(DateConstructor);
  24. // 21.4.3.2 Date.parse ( string ), https://tc39.es/ecma262/#sec-date.parse
  25. static double parse_simplified_iso8601(ByteString const& iso_8601)
  26. {
  27. // 21.4.1.15 Date Time String Format, https://tc39.es/ecma262/#sec-date-time-string-format
  28. GenericLexer lexer(iso_8601);
  29. auto lex_n_digits = [&](size_t n, Optional<int>& out) {
  30. if (lexer.tell_remaining() < n)
  31. return false;
  32. int r = 0;
  33. for (size_t i = 0; i < n; ++i) {
  34. char ch = lexer.consume();
  35. if (!is_ascii_digit(ch))
  36. return false;
  37. r = 10 * r + ch - '0';
  38. }
  39. out = r;
  40. return true;
  41. };
  42. Optional<int> year;
  43. Optional<int> month;
  44. Optional<int> day;
  45. Optional<int> hours;
  46. Optional<int> minutes;
  47. Optional<int> seconds;
  48. Optional<int> milliseconds;
  49. Optional<char> timezone;
  50. Optional<int> timezone_hours;
  51. Optional<int> timezone_minutes;
  52. auto lex_year = [&]() {
  53. if (lexer.consume_specific('+'))
  54. return lex_n_digits(6, year);
  55. if (lexer.consume_specific('-')) {
  56. Optional<int> absolute_year;
  57. if (!lex_n_digits(6, absolute_year))
  58. return false;
  59. // The representation of the year 0 as -000000 is invalid.
  60. if (absolute_year.value() == 0)
  61. return false;
  62. year = -absolute_year.value();
  63. return true;
  64. }
  65. return lex_n_digits(4, year);
  66. };
  67. auto lex_month = [&]() { return lex_n_digits(2, month) && *month >= 1 && *month <= 12; };
  68. auto lex_day = [&]() { return lex_n_digits(2, day) && *day >= 1 && *day <= 31; };
  69. auto lex_date = [&]() { return lex_year() && (!lexer.consume_specific('-') || (lex_month() && (!lexer.consume_specific('-') || lex_day()))); };
  70. auto lex_hours_minutes = [&](Optional<int>& out_h, Optional<int>& out_m) {
  71. Optional<int> h;
  72. Optional<int> m;
  73. if (lex_n_digits(2, h) && *h >= 0 && *h <= 24 && lexer.consume_specific(':') && lex_n_digits(2, m) && *m >= 0 && *m <= 59) {
  74. out_h = move(h);
  75. out_m = move(m);
  76. return true;
  77. }
  78. return false;
  79. };
  80. auto lex_seconds = [&]() { return lex_n_digits(2, seconds) && *seconds >= 0 && *seconds <= 59; };
  81. auto lex_milliseconds = [&]() {
  82. // Date.parse() is allowed to accept an arbitrary number of implementation-defined formats.
  83. // Milliseconds are parsed slightly different as other engines allow effectively any number of digits here.
  84. // We require at least one digit and only use the first three.
  85. auto digits_read = 0;
  86. int result = 0;
  87. while (!lexer.is_eof() && is_ascii_digit(lexer.peek())) {
  88. char ch = lexer.consume();
  89. if (digits_read < 3)
  90. result = 10 * result + ch - '0';
  91. ++digits_read;
  92. }
  93. if (digits_read == 0)
  94. return false;
  95. // If we got less than three digits pretend we have trailing zeros.
  96. while (digits_read < 3) {
  97. result *= 10;
  98. ++digits_read;
  99. }
  100. milliseconds = result;
  101. return true;
  102. };
  103. auto lex_seconds_milliseconds = [&]() { return lex_seconds() && (!lexer.consume_specific('.') || lex_milliseconds()); };
  104. auto lex_timezone = [&]() {
  105. if (lexer.consume_specific('+')) {
  106. timezone = '+';
  107. return lex_hours_minutes(timezone_hours, timezone_minutes);
  108. }
  109. if (lexer.consume_specific('-')) {
  110. timezone = '-';
  111. return lex_hours_minutes(timezone_hours, timezone_minutes);
  112. }
  113. if (lexer.consume_specific('Z'))
  114. timezone = 'Z';
  115. return true;
  116. };
  117. auto lex_time = [&]() { return lex_hours_minutes(hours, minutes) && (!lexer.consume_specific(':') || lex_seconds_milliseconds()) && lex_timezone(); };
  118. if (!lex_date() || (lexer.consume_specific('T') && !lex_time()) || !lexer.is_eof()) {
  119. return NAN;
  120. }
  121. // We parsed a valid date simplified ISO 8601 string.
  122. VERIFY(year.has_value()); // A valid date string always has at least a year.
  123. auto time = AK::UnixDateTime::from_unix_time_parts(*year, month.value_or(1), day.value_or(1), hours.value_or(0), minutes.value_or(0), seconds.value_or(0), milliseconds.value_or(0));
  124. auto time_ms = static_cast<double>(time.milliseconds_since_epoch());
  125. // https://tc39.es/ecma262/#sec-date.parse:
  126. // "When the UTC offset representation is absent, date-only forms are interpreted as a UTC time and date-time forms are interpreted as a local time."
  127. if (!timezone.has_value() && hours.has_value())
  128. time_ms = utc_time(time_ms);
  129. if (timezone == '-')
  130. time_ms += *timezone_hours * 3'600'000 + *timezone_minutes * 60'000;
  131. else if (timezone == '+')
  132. time_ms -= *timezone_hours * 3'600'000 + *timezone_minutes * 60'000;
  133. return time_clip(time_ms);
  134. }
  135. static double parse_date_string(VM& vm, ByteString const& date_string)
  136. {
  137. if (date_string.is_empty())
  138. return NAN;
  139. auto value = parse_simplified_iso8601(date_string);
  140. if (isfinite(value))
  141. return value;
  142. // Date.parse() is allowed to accept an arbitrary number of implementation-defined formats.
  143. // FIXME: Exactly what timezone and which additional formats we should support is unclear.
  144. // Both Chrome and Firefox seem to support "4/17/2019 11:08 PM +0000" with most parts
  145. // being optional, however this is not clearly documented anywhere.
  146. static constexpr auto extra_formats = AK::Array {
  147. "%a%t%b%t%d%t%Y%t%T%tGMT%z%t(%+)"sv, // "Tue Nov 07 2023 10:05:55 GMT-0500 (Eastern Standard Time)"
  148. "%a,%t%d%t%b%t%Y%t%T%t%Z"sv, // "Tue, 07 Nov 2023 15:05:55 GMT"
  149. "%a%t%b%t%e%t%T%t%z%t%Y"sv, // "Wed Apr 17 23:08:53 +0000 2019"
  150. "%m/%e/%Y"sv, // "4/17/2019"
  151. "%m/%e/%Y%t%R%t%z"sv, // "12/05/2022 10:00 -0800"
  152. "%Y/%m/%e%t%R"sv, // "2014/11/14 13:05"
  153. "%Y-%m-%e%t%R"sv, // "2014-11-14 13:05"
  154. "%B%t%e,%t%Y"sv, // "June 5, 2023"
  155. "%B%t%e,%t%Y%t%T"sv, // "June 5, 2023 17:00:00"
  156. "%b%t%d%t%Y%t%Z"sv, // "Jan 01 1970 GMT"
  157. "%a%t%b%t%e%t%T%t%Y%t%z"sv, // "Wed Apr 17 23:08:53 2019 +0000"
  158. "%Y-%m-%e%t%R%z"sv, // "2021-07-01 03:00Z"
  159. "%a,%t%e%t%b%t%Y%t%T%t%z"sv, // "Wed, 17 Jan 2024 11:36:34 +0000"
  160. "%a%t%b%t%e%t%Y%t%T%tGMT%t%x%t(%+)"sv, // "Sun Jan 21 2024 21:11:31 GMT 0100 (Central European Standard Time)"
  161. "%Y-%m-%e%t%T"sv, // "2024-01-15 00:00:01"
  162. "%a%t%b%t%e%t%Y%t%T%t%Z"sv, // "Tue Nov 07 2023 10:05:55 UTC"
  163. "%a%t%b%t%e%t%T%t%Y"sv, // "Wed Apr 17 23:08:53 2019"
  164. "%a%t%b%t%e%t%Y%t%T"sv, // "Wed Apr 17 2019 23:08:53"
  165. "%Y-%m-%eT%T%X%z"sv, // "2024-01-26T22:10:11.306+0000"
  166. "%m/%e/%Y,%t%T%t%p"sv, // "1/27/2024, 9:28:30 AM"
  167. "%Y-%m-%e"sv, // "2024-1-15"
  168. "%Y-%m-%e%t%T%tGMT%z"sv, // "2024-07-05 00:00:00 GMT-0800"
  169. "%d%t%B%t%Y"sv, // "01 February 2013"
  170. "%d%t%B%t%Y%t%R"sv, // "01 February 2013 08:00"
  171. "%d%t%b%t%Y"sv, // "01 Jan 2000"
  172. "%d%t%b%t%Y%t%R"sv, // "01 Jan 2000 08:00"
  173. "%A,%t%B%t%e,%t%Y,%t%R%t%Z"sv, // "Tuesday, October 29, 2024, 18:00 UTC"
  174. "%B%t%d%t%Y%t%T%t%z"sv, // "November 19 2024 00:00:00 +0900"
  175. "%a%t%b%t%e%t%Y"sv // "Wed Nov 20 2024"
  176. };
  177. for (auto const& format : extra_formats) {
  178. auto maybe_datetime = Core::DateTime::parse(format, date_string);
  179. if (maybe_datetime.has_value())
  180. return 1000.0 * maybe_datetime->timestamp();
  181. }
  182. vm.host_unrecognized_date_string(date_string);
  183. return NAN;
  184. }
  185. DateConstructor::DateConstructor(Realm& realm)
  186. : NativeFunction(realm.vm().names.Date.as_string(), realm.intrinsics().function_prototype())
  187. {
  188. }
  189. void DateConstructor::initialize(Realm& realm)
  190. {
  191. auto& vm = this->vm();
  192. Base::initialize(realm);
  193. // 21.4.3.3 Date.prototype, https://tc39.es/ecma262/#sec-date.prototype
  194. define_direct_property(vm.names.prototype, realm.intrinsics().date_prototype(), 0);
  195. u8 attr = Attribute::Writable | Attribute::Configurable;
  196. define_native_function(realm, vm.names.now, now, 0, attr);
  197. define_native_function(realm, vm.names.parse, parse, 1, attr);
  198. define_native_function(realm, vm.names.UTC, utc, 7, attr);
  199. define_direct_property(vm.names.length, Value(7), Attribute::Configurable);
  200. }
  201. // 21.4.2.1 Date ( ...values ), https://tc39.es/ecma262/#sec-date
  202. ThrowCompletionOr<Value> DateConstructor::call()
  203. {
  204. // 1. If NewTarget is undefined, then
  205. // a. Let now be the time value (UTC) identifying the current time.
  206. auto now = AK::UnixDateTime::now().milliseconds_since_epoch();
  207. // b. Return ToDateString(now).
  208. return PrimitiveString::create(vm(), to_date_string(now));
  209. }
  210. // 21.4.2.1 Date ( ...values ), https://tc39.es/ecma262/#sec-date
  211. ThrowCompletionOr<GC::Ref<Object>> DateConstructor::construct(FunctionObject& new_target)
  212. {
  213. auto& vm = this->vm();
  214. double date_value;
  215. // 2. Let numberOfArgs be the number of elements in values.
  216. // 3. If numberOfArgs = 0, then
  217. if (vm.argument_count() == 0) {
  218. // a. Let dv be the time value (UTC) identifying the current time.
  219. auto now = AK::UnixDateTime::now().milliseconds_since_epoch();
  220. date_value = static_cast<double>(now);
  221. }
  222. // 4. Else if numberOfArgs = 1, then
  223. else if (vm.argument_count() == 1) {
  224. // a. Let value be values[0].
  225. auto value = vm.argument(0);
  226. double time_value;
  227. // b. If Type(value) is Object and value has a [[DateValue]] internal slot, then
  228. if (value.is_object() && is<Date>(value.as_object())) {
  229. // i. Let tv be ! thisTimeValue(value).
  230. time_value = MUST(this_time_value(vm, value));
  231. }
  232. // c. Else,
  233. else {
  234. // i. Let v be ? ToPrimitive(value).
  235. auto primitive = TRY(value.to_primitive(vm));
  236. // ii. If Type(v) is String, then
  237. if (primitive.is_string()) {
  238. // 1. Assert: The next step never returns an abrupt completion because Type(v) is String.
  239. // 2. Let tv be the result of parsing v as a date, in exactly the same manner as for the parse method (21.4.3.2).
  240. time_value = parse_date_string(vm, primitive.as_string().byte_string());
  241. }
  242. // iii. Else,
  243. else {
  244. // 1. Let tv be ? ToNumber(v).
  245. time_value = TRY(primitive.to_number(vm)).as_double();
  246. }
  247. }
  248. // d. Let dv be TimeClip(tv).
  249. date_value = time_clip(time_value);
  250. }
  251. // 5. Else,
  252. else {
  253. // a. Assert: numberOfArgs ≥ 2.
  254. // b. Let y be ? ToNumber(values[0]).
  255. auto year = TRY(vm.argument(0).to_number(vm)).as_double();
  256. // c. Let m be ? ToNumber(values[1]).
  257. auto month = TRY(vm.argument(1).to_number(vm)).as_double();
  258. auto arg_or = [&vm](size_t i, double fallback) -> ThrowCompletionOr<double> {
  259. return vm.argument_count() > i ? TRY(vm.argument(i).to_number(vm)).as_double() : fallback;
  260. };
  261. // d. If numberOfArgs > 2, let dt be ? ToNumber(values[2]); else let dt be 1𝔽.
  262. auto date = TRY(arg_or(2, 1));
  263. // e. If numberOfArgs > 3, let h be ? ToNumber(values[3]); else let h be +0𝔽.
  264. auto hours = TRY(arg_or(3, 0));
  265. // f. If numberOfArgs > 4, let min be ? ToNumber(values[4]); else let min be +0𝔽.
  266. auto minutes = TRY(arg_or(4, 0));
  267. // g. If numberOfArgs > 5, let s be ? ToNumber(values[5]); else let s be +0𝔽.
  268. auto seconds = TRY(arg_or(5, 0));
  269. // h. If numberOfArgs > 6, let milli be ? ToNumber(values[6]); else let milli be +0𝔽.
  270. auto milliseconds = TRY(arg_or(6, 0));
  271. // i. If y is NaN, let yr be NaN.
  272. // j. Else,
  273. if (!isnan(year)) {
  274. // i. Let yi be ! ToIntegerOrInfinity(y).
  275. auto year_integer = to_integer_or_infinity(year);
  276. // ii. If 0 ≤ yi ≤ 99, let yr be 1900𝔽 + 𝔽(yi); otherwise, let yr be y.
  277. if (0 <= year_integer && year_integer <= 99)
  278. year = 1900 + year_integer;
  279. }
  280. // k. Let finalDate be MakeDate(MakeDay(yr, m, dt), MakeTime(h, min, s, milli)).
  281. auto day = make_day(year, month, date);
  282. auto time = make_time(hours, minutes, seconds, milliseconds);
  283. auto final_date = make_date(day, time);
  284. // l. Let dv be TimeClip(UTC(finalDate)).
  285. date_value = time_clip(utc_time(final_date));
  286. }
  287. // 6. Let O be ? OrdinaryCreateFromConstructor(NewTarget, "%Date.prototype%", « [[DateValue]] »).
  288. // 7. Set O.[[DateValue]] to dv.
  289. // 8. Return O.
  290. return TRY(ordinary_create_from_constructor<Date>(vm, new_target, &Intrinsics::date_prototype, date_value));
  291. }
  292. // 21.4.3.1 Date.now ( ), https://tc39.es/ecma262/#sec-date.now
  293. JS_DEFINE_NATIVE_FUNCTION(DateConstructor::now)
  294. {
  295. struct timeval tv;
  296. gettimeofday(&tv, nullptr);
  297. return Value(floor(tv.tv_sec * 1000.0 + tv.tv_usec / 1000.0));
  298. }
  299. // 21.4.3.2 Date.parse ( string ), https://tc39.es/ecma262/#sec-date.parse
  300. JS_DEFINE_NATIVE_FUNCTION(DateConstructor::parse)
  301. {
  302. if (!vm.argument_count())
  303. return js_nan();
  304. auto date_string = TRY(vm.argument(0).to_byte_string(vm));
  305. return Value(parse_date_string(vm, date_string));
  306. }
  307. // 21.4.3.4 Date.UTC ( year [ , month [ , date [ , hours [ , minutes [ , seconds [ , ms ] ] ] ] ] ] ), https://tc39.es/ecma262/#sec-date.utc
  308. JS_DEFINE_NATIVE_FUNCTION(DateConstructor::utc)
  309. {
  310. auto arg_or = [&vm](size_t i, double fallback) -> ThrowCompletionOr<double> {
  311. return vm.argument_count() > i ? TRY(vm.argument(i).to_number(vm)).as_double() : fallback;
  312. };
  313. // 1. Let y be ? ToNumber(year).
  314. auto year = TRY(vm.argument(0).to_number(vm)).as_double();
  315. // 2. If month is present, let m be ? ToNumber(month); else let m be +0𝔽.
  316. auto month = TRY(arg_or(1, 0));
  317. // 3. If date is present, let dt be ? ToNumber(date); else let dt be 1𝔽.
  318. auto date = TRY(arg_or(2, 1));
  319. // 4. If hours is present, let h be ? ToNumber(hours); else let h be +0𝔽.
  320. auto hours = TRY(arg_or(3, 0));
  321. // 5. If minutes is present, let min be ? ToNumber(minutes); else let min be +0𝔽.
  322. auto minutes = TRY(arg_or(4, 0));
  323. // 6. If seconds is present, let s be ? ToNumber(seconds); else let s be +0𝔽.
  324. auto seconds = TRY(arg_or(5, 0));
  325. // 7. If ms is present, let milli be ? ToNumber(ms); else let milli be +0𝔽.
  326. auto milliseconds = TRY(arg_or(6, 0));
  327. // 8. If y is NaN, let yr be NaN.
  328. // 9. Else,
  329. if (!isnan(year)) {
  330. // a. Let yi be ! ToIntegerOrInfinity(y).
  331. auto year_integer = to_integer_or_infinity(year);
  332. // b. If 0 ≤ yi ≤ 99, let yr be 1900𝔽 + 𝔽(yi); otherwise, let yr be y.
  333. if (0 <= year_integer && year_integer <= 99)
  334. year = 1900 + year_integer;
  335. }
  336. // 10. Return TimeClip(MakeDate(MakeDay(yr, m, dt), MakeTime(h, min, s, milli))).
  337. auto day = make_day(year, month, date);
  338. auto time = make_time(hours, minutes, seconds, milliseconds);
  339. return Value(time_clip(make_date(day, time)));
  340. }
  341. }