DateConstructor.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. /*
  2. * Copyright (c) 2020-2022, 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(String 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::Time::from_timestamp(*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.to_milliseconds());
  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 double parse_date_string(String const& date_string)
  134. {
  135. auto value = parse_simplified_iso8601(date_string);
  136. if (isfinite(value))
  137. return value;
  138. // Date.parse() is allowed to accept an arbitrary number of implementation-defined formats.
  139. // Parse formats of this type: "Wed Apr 17 23:08:53 +0000 2019"
  140. auto maybe_datetime = Core::DateTime::parse("%a %b %e %T %z %Y"sv, date_string);
  141. if (maybe_datetime.has_value())
  142. return 1000.0 * maybe_datetime->timestamp();
  143. return NAN;
  144. }
  145. DateConstructor::DateConstructor(Realm& realm)
  146. : NativeFunction(vm().names.Date.as_string(), *realm.global_object().function_prototype())
  147. {
  148. }
  149. void DateConstructor::initialize(Realm& realm)
  150. {
  151. auto& vm = this->vm();
  152. NativeFunction::initialize(realm);
  153. // 21.4.3.3 Date.prototype, https://tc39.es/ecma262/#sec-date.prototype
  154. define_direct_property(vm.names.prototype, realm.global_object().date_prototype(), 0);
  155. u8 attr = Attribute::Writable | Attribute::Configurable;
  156. define_native_function(vm.names.now, now, 0, attr);
  157. define_native_function(vm.names.parse, parse, 1, attr);
  158. define_native_function(vm.names.UTC, utc, 7, attr);
  159. define_direct_property(vm.names.length, Value(7), Attribute::Configurable);
  160. }
  161. // 21.4.2.1 Date ( ...values ), https://tc39.es/ecma262/#sec-date
  162. ThrowCompletionOr<Value> DateConstructor::call()
  163. {
  164. // 1. If NewTarget is undefined, then
  165. // a. Let now be the time value (UTC) identifying the current time.
  166. auto now = AK::Time::now_realtime().to_milliseconds();
  167. // b. Return ToDateString(now).
  168. return js_string(vm(), to_date_string(now));
  169. }
  170. // 21.4.2.1 Date ( ...values ), https://tc39.es/ecma262/#sec-date
  171. ThrowCompletionOr<Object*> DateConstructor::construct(FunctionObject& new_target)
  172. {
  173. auto& vm = this->vm();
  174. auto& global_object = this->global_object();
  175. double date_value;
  176. // 2. Let numberOfArgs be the number of elements in values.
  177. // 3. If numberOfArgs = 0, then
  178. if (vm.argument_count() == 0) {
  179. // a. Let dv be the time value (UTC) identifying the current time.
  180. auto now = AK::Time::now_realtime().to_milliseconds();
  181. date_value = static_cast<double>(now);
  182. }
  183. // 4. Else if numberOfArgs = 1, then
  184. else if (vm.argument_count() == 1) {
  185. // a. Let value be values[0].
  186. auto value = vm.argument(0);
  187. double time_value;
  188. // b. If Type(value) is Object and value has a [[DateValue]] internal slot, then
  189. if (value.is_object() && is<Date>(value.as_object())) {
  190. // i. Let tv be ! thisTimeValue(value).
  191. time_value = MUST(this_time_value(global_object, value));
  192. }
  193. // c. Else,
  194. else {
  195. // i. Let v be ? ToPrimitive(value).
  196. auto primitive = TRY(value.to_primitive(global_object));
  197. // ii. If Type(v) is String, then
  198. if (primitive.is_string()) {
  199. // 1. Assert: The next step never returns an abrupt completion because Type(v) is String.
  200. // 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).
  201. time_value = parse_date_string(primitive.as_string().string());
  202. }
  203. // iii. Else,
  204. else {
  205. // 1. Let tv be ? ToNumber(v).
  206. time_value = TRY(primitive.to_number(global_object)).as_double();
  207. }
  208. }
  209. // d. Let dv be TimeClip(tv).
  210. date_value = time_clip(time_value);
  211. }
  212. // 5. Else,
  213. else {
  214. // a. Assert: numberOfArgs ≥ 2.
  215. // b. Let y be ? ToNumber(values[0]).
  216. auto year = TRY(vm.argument(0).to_number(global_object)).as_double();
  217. // c. Let m be ? ToNumber(values[1]).
  218. auto month = TRY(vm.argument(1).to_number(global_object)).as_double();
  219. auto arg_or = [&vm, &global_object](size_t i, double fallback) -> ThrowCompletionOr<double> {
  220. return vm.argument_count() > i ? TRY(vm.argument(i).to_number(global_object)).as_double() : fallback;
  221. };
  222. // d. If numberOfArgs > 2, let dt be ? ToNumber(values[2]); else let dt be 1𝔽.
  223. auto date = TRY(arg_or(2, 1));
  224. // e. If numberOfArgs > 3, let h be ? ToNumber(values[3]); else let h be +0𝔽.
  225. auto hours = TRY(arg_or(3, 0));
  226. // f. If numberOfArgs > 4, let min be ? ToNumber(values[4]); else let min be +0𝔽.
  227. auto minutes = TRY(arg_or(4, 0));
  228. // g. If numberOfArgs > 5, let s be ? ToNumber(values[5]); else let s be +0𝔽.
  229. auto seconds = TRY(arg_or(5, 0));
  230. // h. If numberOfArgs > 6, let milli be ? ToNumber(values[6]); else let milli be +0𝔽.
  231. auto milliseconds = TRY(arg_or(6, 0));
  232. // i. If y is NaN, let yr be NaN.
  233. // j. Else,
  234. if (!isnan(year)) {
  235. // i. Let yi be ! ToIntegerOrInfinity(y).
  236. auto year_integer = to_integer_or_infinity(year);
  237. // ii. If 0 ≤ yi ≤ 99, let yr be 1900𝔽 + 𝔽(yi); otherwise, let yr be y.
  238. if (0 <= year_integer && year_integer <= 99)
  239. year = 1900 + year_integer;
  240. }
  241. // k. Let finalDate be MakeDate(MakeDay(yr, m, dt), MakeTime(h, min, s, milli)).
  242. auto day = make_day(year, month, date);
  243. auto time = make_time(hours, minutes, seconds, milliseconds);
  244. auto final_date = make_date(day, time);
  245. // l. Let dv be TimeClip(UTC(finalDate)).
  246. date_value = time_clip(utc_time(final_date));
  247. }
  248. // 6. Let O be ? OrdinaryCreateFromConstructor(NewTarget, "%Date.prototype%", « [[DateValue]] »).
  249. // 7. Set O.[[DateValue]] to dv.
  250. // 8. Return O.
  251. return TRY(ordinary_create_from_constructor<Date>(global_object, new_target, &GlobalObject::date_prototype, date_value));
  252. }
  253. // 21.4.3.1 Date.now ( ), https://tc39.es/ecma262/#sec-date.now
  254. JS_DEFINE_NATIVE_FUNCTION(DateConstructor::now)
  255. {
  256. struct timeval tv;
  257. gettimeofday(&tv, nullptr);
  258. return Value(floor(tv.tv_sec * 1000.0 + tv.tv_usec / 1000.0));
  259. }
  260. // 21.4.3.2 Date.parse ( string ), https://tc39.es/ecma262/#sec-date.parse
  261. JS_DEFINE_NATIVE_FUNCTION(DateConstructor::parse)
  262. {
  263. if (!vm.argument_count())
  264. return js_nan();
  265. auto date_string = TRY(vm.argument(0).to_string(global_object));
  266. return Value(parse_date_string(date_string));
  267. }
  268. // 21.4.3.4 Date.UTC ( year [ , month [ , date [ , hours [ , minutes [ , seconds [ , ms ] ] ] ] ] ] ), https://tc39.es/ecma262/#sec-date.utc
  269. JS_DEFINE_NATIVE_FUNCTION(DateConstructor::utc)
  270. {
  271. auto arg_or = [&vm, &global_object](size_t i, double fallback) -> ThrowCompletionOr<double> {
  272. return vm.argument_count() > i ? TRY(vm.argument(i).to_number(global_object)).as_double() : fallback;
  273. };
  274. // 1. Let y be ? ToNumber(year).
  275. auto year = TRY(vm.argument(0).to_number(global_object)).as_double();
  276. // 2. If month is present, let m be ? ToNumber(month); else let m be +0𝔽.
  277. auto month = TRY(arg_or(1, 0));
  278. // 3. If date is present, let dt be ? ToNumber(date); else let dt be 1𝔽.
  279. auto date = TRY(arg_or(2, 1));
  280. // 4. If hours is present, let h be ? ToNumber(hours); else let h be +0𝔽.
  281. auto hours = TRY(arg_or(3, 0));
  282. // 5. If minutes is present, let min be ? ToNumber(minutes); else let min be +0𝔽.
  283. auto minutes = TRY(arg_or(4, 0));
  284. // 6. If seconds is present, let s be ? ToNumber(seconds); else let s be +0𝔽.
  285. auto seconds = TRY(arg_or(5, 0));
  286. // 7. If ms is present, let milli be ? ToNumber(ms); else let milli be +0𝔽.
  287. auto milliseconds = TRY(arg_or(6, 0));
  288. // 8. If y is NaN, let yr be NaN.
  289. // 9. Else,
  290. if (!isnan(year)) {
  291. // a. Let yi be ! ToIntegerOrInfinity(y).
  292. auto year_integer = to_integer_or_infinity(year);
  293. // b. If 0 ≤ yi ≤ 99, let yr be 1900𝔽 + 𝔽(yi); otherwise, let yr be y.
  294. if (0 <= year_integer && year_integer <= 99)
  295. year = 1900 + year_integer;
  296. }
  297. // 10. Return TimeClip(MakeDate(MakeDay(yr, m, dt), MakeTime(h, min, s, milli))).
  298. auto day = make_day(year, month, date);
  299. auto time = make_time(hours, minutes, seconds, milliseconds);
  300. return Value(time_clip(make_date(day, time)));
  301. }
  302. }