DateConstructor.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. /*
  2. * Copyright (c) 2020, 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 Value parse_simplified_iso8601(GlobalObject& global_object, 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. year = -absolute_year.value();
  58. return true;
  59. }
  60. return lex_n_digits(4, year);
  61. };
  62. auto lex_month = [&]() { return lex_n_digits(2, month) && *month >= 1 && *month <= 12; };
  63. auto lex_day = [&]() { return lex_n_digits(2, day) && *day >= 1 && *day <= 31; };
  64. auto lex_date = [&]() { return lex_year() && (!lexer.consume_specific('-') || (lex_month() && (!lexer.consume_specific('-') || lex_day()))); };
  65. auto lex_hours_minutes = [&](Optional<int>& out_h, Optional<int>& out_m) {
  66. Optional<int> h;
  67. Optional<int> m;
  68. if (lex_n_digits(2, h) && *h >= 0 && *h <= 24 && lexer.consume_specific(':') && lex_n_digits(2, m) && *m >= 0 && *m <= 59) {
  69. out_h = move(h);
  70. out_m = move(m);
  71. return true;
  72. }
  73. return false;
  74. };
  75. auto lex_seconds = [&]() { return lex_n_digits(2, seconds) && *seconds >= 0 && *seconds <= 59; };
  76. auto lex_milliseconds = [&]() {
  77. // Date.parse() is allowed to accept an arbitrary number of implementation-defined formats.
  78. // Milliseconds are parsed slightly different as other engines allow effectively any number of digits here.
  79. // We require at least one digit and only use the first three.
  80. auto digits_read = 0;
  81. int result = 0;
  82. while (!lexer.is_eof() && is_ascii_digit(lexer.peek())) {
  83. char ch = lexer.consume();
  84. if (digits_read < 3)
  85. result = 10 * result + ch - '0';
  86. ++digits_read;
  87. }
  88. if (digits_read == 0)
  89. return false;
  90. // If we got less than three digits pretend we have trailing zeros.
  91. while (digits_read < 3) {
  92. result *= 10;
  93. ++digits_read;
  94. }
  95. milliseconds = result;
  96. return true;
  97. };
  98. auto lex_seconds_milliseconds = [&]() { return lex_seconds() && (!lexer.consume_specific('.') || lex_milliseconds()); };
  99. auto lex_timezone = [&]() {
  100. if (lexer.consume_specific('+')) {
  101. timezone = '+';
  102. return lex_hours_minutes(timezone_hours, timezone_minutes);
  103. }
  104. if (lexer.consume_specific('-')) {
  105. timezone = '-';
  106. return lex_hours_minutes(timezone_hours, timezone_minutes);
  107. }
  108. if (lexer.consume_specific('Z'))
  109. timezone = 'Z';
  110. return true;
  111. };
  112. auto lex_time = [&]() { return lex_hours_minutes(hours, minutes) && (!lexer.consume_specific(':') || lex_seconds_milliseconds()) && lex_timezone(); };
  113. if (!lex_date() || (lexer.consume_specific('T') && !lex_time()) || !lexer.is_eof()) {
  114. return js_nan();
  115. }
  116. // We parsed a valid date simplified ISO 8601 string.
  117. VERIFY(year.has_value()); // A valid date string always has at least a year.
  118. 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));
  119. auto time_ms = static_cast<double>(time.to_milliseconds());
  120. // https://tc39.es/ecma262/#sec-date.parse:
  121. // "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."
  122. if (!timezone.has_value() && hours.has_value())
  123. time_ms = utc_time(time_ms);
  124. if (timezone == '-')
  125. time_ms += *timezone_hours * 3'600'000 + *timezone_minutes * 60'000;
  126. else if (timezone == '+')
  127. time_ms -= *timezone_hours * 3'600'000 + *timezone_minutes * 60'000;
  128. return time_clip(global_object, Value(time_ms));
  129. }
  130. static Value parse_date_string(GlobalObject& global_object, String const& date_string)
  131. {
  132. auto value = parse_simplified_iso8601(global_object, date_string);
  133. if (value.is_finite_number())
  134. return value;
  135. // Date.parse() is allowed to accept an arbitrary number of implementation-defined formats.
  136. // Parse formats of this type: "Wed Apr 17 23:08:53 +0000 2019"
  137. auto maybe_datetime = Core::DateTime::parse("%a %b %e %T %z %Y", date_string);
  138. if (maybe_datetime.has_value())
  139. return Value(1000.0 * maybe_datetime.value().timestamp());
  140. return js_nan();
  141. }
  142. DateConstructor::DateConstructor(GlobalObject& global_object)
  143. : NativeFunction(vm().names.Date.as_string(), *global_object.function_prototype())
  144. {
  145. }
  146. void DateConstructor::initialize(GlobalObject& global_object)
  147. {
  148. auto& vm = this->vm();
  149. NativeFunction::initialize(global_object);
  150. // 21.4.3.3 Date.prototype, https://tc39.es/ecma262/#sec-date.prototype
  151. define_direct_property(vm.names.prototype, global_object.date_prototype(), 0);
  152. u8 attr = Attribute::Writable | Attribute::Configurable;
  153. define_native_function(vm.names.now, now, 0, attr);
  154. define_native_function(vm.names.parse, parse, 1, attr);
  155. define_native_function(vm.names.UTC, utc, 7, attr);
  156. define_direct_property(vm.names.length, Value(7), Attribute::Configurable);
  157. }
  158. // 21.4.2.1 Date ( ...values ), https://tc39.es/ecma262/#sec-date
  159. ThrowCompletionOr<Value> DateConstructor::call()
  160. {
  161. // 1. If NewTarget is undefined, then
  162. // a. Let now be the time value (UTC) identifying the current time.
  163. auto now = AK::Time::now_realtime().to_milliseconds();
  164. // b. Return ToDateString(now).
  165. return js_string(vm(), to_date_string(now));
  166. }
  167. // 21.4.2.1 Date ( ...values ), https://tc39.es/ecma262/#sec-date
  168. ThrowCompletionOr<Object*> DateConstructor::construct(FunctionObject& new_target)
  169. {
  170. auto& vm = this->vm();
  171. auto& global_object = this->global_object();
  172. Value date_value;
  173. // 2. Let numberOfArgs be the number of elements in values.
  174. // 3. If numberOfArgs = 0, then
  175. if (vm.argument_count() == 0) {
  176. // a. Let dv be the time value (UTC) identifying the current time.
  177. auto now = AK::Time::now_realtime().to_milliseconds();
  178. date_value = Value(static_cast<double>(now));
  179. }
  180. // 4. Else if numberOfArgs = 1, then
  181. else if (vm.argument_count() == 1) {
  182. // a. Let value be values[0].
  183. auto value = vm.argument(0);
  184. Value time_value;
  185. // b. If Type(value) is Object and value has a [[DateValue]] internal slot, then
  186. if (value.is_object() && is<Date>(value.as_object())) {
  187. // i. Let tv be ! thisTimeValue(value).
  188. time_value = MUST(this_time_value(global_object, value));
  189. }
  190. // c. Else,
  191. else {
  192. // i. Let v be ? ToPrimitive(value).
  193. auto primitive = TRY(value.to_primitive(global_object));
  194. // ii. If Type(v) is String, then
  195. if (primitive.is_string()) {
  196. // 1. Assert: The next step never returns an abrupt completion because Type(v) is String.
  197. // 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).
  198. time_value = parse_date_string(global_object, primitive.as_string().string());
  199. }
  200. // iii. Else,
  201. else {
  202. // 1. Let tv be ? ToNumber(v).
  203. time_value = TRY(primitive.to_number(global_object));
  204. }
  205. }
  206. // d. Let dv be TimeClip(tv).
  207. date_value = time_clip(global_object, time_value);
  208. }
  209. // 5. Else,
  210. else {
  211. // a. Assert: numberOfArgs ≥ 2.
  212. // b. Let y be ? ToNumber(values[0]).
  213. auto year = TRY(vm.argument(0).to_number(global_object));
  214. // c. Let m be ? ToNumber(values[1]).
  215. auto month = TRY(vm.argument(1).to_number(global_object));
  216. auto arg_or = [&vm, &global_object](size_t i, i32 fallback) -> ThrowCompletionOr<Value> {
  217. return vm.argument_count() > i ? vm.argument(i).to_number(global_object) : Value(fallback);
  218. };
  219. // d. If numberOfArgs > 2, let dt be ? ToNumber(values[2]); else let dt be 1𝔽.
  220. auto date = TRY(arg_or(2, 1));
  221. // e. If numberOfArgs > 3, let h be ? ToNumber(values[3]); else let h be +0𝔽.
  222. auto hours = TRY(arg_or(3, 0));
  223. // f. If numberOfArgs > 4, let min be ? ToNumber(values[4]); else let min be +0𝔽.
  224. auto minutes = TRY(arg_or(4, 0));
  225. // g. If numberOfArgs > 5, let s be ? ToNumber(values[5]); else let s be +0𝔽.
  226. auto seconds = TRY(arg_or(5, 0));
  227. // h. If numberOfArgs > 6, let milli be ? ToNumber(values[6]); else let milli be +0𝔽.
  228. auto milliseconds = TRY(arg_or(6, 0));
  229. // i. If y is NaN, let yr be NaN.
  230. // j. Else,
  231. if (!year.is_nan()) {
  232. // i. Let yi be ! ToIntegerOrInfinity(y).
  233. auto year_double = MUST(year.to_integer_or_infinity(global_object));
  234. // ii. If 0 ≤ yi ≤ 99, let yr be 1900𝔽 + 𝔽(yi); otherwise, let yr be y.
  235. if (0 <= year_double && year_double <= 99)
  236. year = Value(1900 + year_double);
  237. }
  238. // k. Let finalDate be MakeDate(MakeDay(yr, m, dt), MakeTime(h, min, s, milli)).
  239. auto day = make_day(global_object, year, month, date);
  240. auto time = make_time(global_object, hours, minutes, seconds, milliseconds);
  241. auto final_date = make_date(day, time);
  242. // l. Let dv be TimeClip(UTC(finalDate)).
  243. date_value = time_clip(global_object, Value(utc_time(final_date.as_double())));
  244. }
  245. // 6. Let O be ? OrdinaryCreateFromConstructor(NewTarget, "%Date.prototype%", « [[DateValue]] »).
  246. // 7. Set O.[[DateValue]] to dv.
  247. // 8. Return O.
  248. return TRY(ordinary_create_from_constructor<Date>(global_object, new_target, &GlobalObject::date_prototype, date_value.as_double()));
  249. }
  250. // 21.4.3.1 Date.now ( ), https://tc39.es/ecma262/#sec-date.now
  251. JS_DEFINE_NATIVE_FUNCTION(DateConstructor::now)
  252. {
  253. struct timeval tv;
  254. gettimeofday(&tv, nullptr);
  255. return Value(floor(tv.tv_sec * 1000.0 + tv.tv_usec / 1000.0));
  256. }
  257. // 21.4.3.2 Date.parse ( string ), https://tc39.es/ecma262/#sec-date.parse
  258. JS_DEFINE_NATIVE_FUNCTION(DateConstructor::parse)
  259. {
  260. if (!vm.argument_count())
  261. return js_nan();
  262. auto date_string = TRY(vm.argument(0).to_string(global_object));
  263. return parse_date_string(global_object, date_string);
  264. }
  265. // 21.4.3.4 Date.UTC ( year [ , month [ , date [ , hours [ , minutes [ , seconds [ , ms ] ] ] ] ] ] ), https://tc39.es/ecma262/#sec-date.utc
  266. JS_DEFINE_NATIVE_FUNCTION(DateConstructor::utc)
  267. {
  268. auto arg_or = [&vm, &global_object](size_t i, i32 fallback) -> ThrowCompletionOr<Value> {
  269. return vm.argument_count() > i ? vm.argument(i).to_number(global_object) : Value(fallback);
  270. };
  271. // 1. Let y be ? ToNumber(year).
  272. auto year = TRY(vm.argument(0).to_number(global_object));
  273. // 2. If month is present, let m be ? ToNumber(month); else let m be +0𝔽.
  274. auto month = TRY(arg_or(1, 0));
  275. // 3. If date is present, let dt be ? ToNumber(date); else let dt be 1𝔽.
  276. auto date = TRY(arg_or(2, 1));
  277. // 4. If hours is present, let h be ? ToNumber(hours); else let h be +0𝔽.
  278. auto hours = TRY(arg_or(3, 0));
  279. // 5. If minutes is present, let min be ? ToNumber(minutes); else let min be +0𝔽.
  280. auto minutes = TRY(arg_or(4, 0));
  281. // 6. If seconds is present, let s be ? ToNumber(seconds); else let s be +0𝔽.
  282. auto seconds = TRY(arg_or(5, 0));
  283. // 7. If ms is present, let milli be ? ToNumber(ms); else let milli be +0𝔽.
  284. auto milliseconds = TRY(arg_or(6, 0));
  285. // 8. If y is NaN, let yr be NaN.
  286. // 9. Else,
  287. if (!year.is_nan()) {
  288. // a. Let yi be ! ToIntegerOrInfinity(y).
  289. auto year_double = MUST(year.to_integer_or_infinity(global_object));
  290. // b. If 0 ≤ yi ≤ 99, let yr be 1900𝔽 + 𝔽(yi); otherwise, let yr be y.
  291. if (0 <= year_double && year_double <= 99)
  292. year = Value(1900 + year_double);
  293. }
  294. // 10. Return TimeClip(MakeDate(MakeDay(yr, m, dt), MakeTime(h, min, s, milli))).
  295. auto day = make_day(global_object, year, month, date);
  296. auto time = make_time(global_object, hours, minutes, seconds, milliseconds);
  297. return time_clip(global_object, make_date(day, time));
  298. }
  299. }