DateConstructor.cpp 13 KB

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