DateConstructor.cpp 14 KB

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