DateConstructor.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include <AK/CharacterTypes.h>
  9. #include <AK/GenericLexer.h>
  10. #include <LibCore/DateTime.h>
  11. #include <LibJS/Runtime/AbstractOperations.h>
  12. #include <LibJS/Runtime/Date.h>
  13. #include <LibJS/Runtime/DateConstructor.h>
  14. #include <LibJS/Runtime/GlobalObject.h>
  15. #include <LibJS/Runtime/VM.h>
  16. #include <sys/time.h>
  17. #include <time.h>
  18. namespace JS {
  19. // 21.4.3.2 Date.parse ( string ), https://tc39.es/ecma262/#sec-date.parse
  20. static Value parse_simplified_iso8601(const String& iso_8601)
  21. {
  22. // 21.4.1.15 Date Time String Format, https://tc39.es/ecma262/#sec-date-time-string-format
  23. GenericLexer lexer(iso_8601);
  24. auto lex_n_digits = [&](size_t n, Optional<int>& out) {
  25. if (lexer.tell_remaining() < n)
  26. return false;
  27. int r = 0;
  28. for (size_t i = 0; i < n; ++i) {
  29. char ch = lexer.consume();
  30. if (!is_ascii_digit(ch))
  31. return false;
  32. r = 10 * r + ch - '0';
  33. }
  34. out = r;
  35. return true;
  36. };
  37. Optional<int> year;
  38. Optional<int> month;
  39. Optional<int> day;
  40. Optional<int> hours;
  41. Optional<int> minutes;
  42. Optional<int> seconds;
  43. Optional<int> milliseconds;
  44. Optional<char> timezone;
  45. Optional<int> timezone_hours;
  46. Optional<int> timezone_minutes;
  47. auto lex_year = [&]() {
  48. if (lexer.consume_specific('+'))
  49. return lex_n_digits(6, year);
  50. if (lexer.consume_specific('-')) {
  51. Optional<int> absolute_year;
  52. if (!lex_n_digits(6, absolute_year))
  53. return false;
  54. year = -absolute_year.value();
  55. return true;
  56. }
  57. return lex_n_digits(4, year);
  58. };
  59. auto lex_month = [&]() { return lex_n_digits(2, month) && *month >= 1 && *month <= 12; };
  60. auto lex_day = [&]() { return lex_n_digits(2, day) && *day >= 1 && *day <= 31; };
  61. auto lex_date = [&]() { return lex_year() && (!lexer.consume_specific('-') || (lex_month() && (!lexer.consume_specific('-') || lex_day()))); };
  62. auto lex_hours_minutes = [&](Optional<int>& out_h, Optional<int>& out_m) {
  63. Optional<int> h;
  64. Optional<int> m;
  65. if (lex_n_digits(2, h) && *h >= 0 && *h <= 24 && lexer.consume_specific(':') && lex_n_digits(2, m) && *m >= 0 && *m <= 59) {
  66. out_h = move(h);
  67. out_m = move(m);
  68. return true;
  69. }
  70. return false;
  71. };
  72. auto lex_seconds = [&]() { return lex_n_digits(2, seconds) && *seconds >= 0 && *seconds <= 59; };
  73. auto lex_milliseconds = [&]() { return lex_n_digits(3, milliseconds); };
  74. auto lex_seconds_milliseconds = [&]() { return lex_seconds() && (!lexer.consume_specific('.') || lex_milliseconds()); };
  75. auto lex_timezone = [&]() {
  76. if (lexer.consume_specific('+')) {
  77. timezone = '+';
  78. return lex_hours_minutes(timezone_hours, timezone_minutes);
  79. }
  80. if (lexer.consume_specific('-')) {
  81. timezone = '-';
  82. return lex_hours_minutes(timezone_hours, timezone_minutes);
  83. }
  84. if (lexer.consume_specific('Z'))
  85. timezone = 'Z';
  86. return true;
  87. };
  88. auto lex_time = [&]() { return lex_hours_minutes(hours, minutes) && (!lexer.consume_specific(':') || lex_seconds_milliseconds()) && lex_timezone(); };
  89. if (!lex_date() || (lexer.consume_specific('T') && !lex_time()) || !lexer.is_eof()) {
  90. return js_nan();
  91. }
  92. // We parsed a valid date simplified ISO 8601 string.
  93. VERIFY(year.has_value()); // A valid date string always has at least a year.
  94. struct tm tm = {};
  95. tm.tm_year = *year - 1900;
  96. tm.tm_mon = !month.has_value() ? 0 : *month - 1;
  97. tm.tm_mday = day.value_or(1);
  98. tm.tm_hour = hours.value_or(0);
  99. tm.tm_min = minutes.value_or(0);
  100. tm.tm_sec = seconds.value_or(0);
  101. // https://tc39.es/ecma262/#sec-date.parse:
  102. // "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."
  103. time_t timestamp;
  104. if (timezone.has_value() || !hours.has_value())
  105. timestamp = timegm(&tm);
  106. else
  107. timestamp = mktime(&tm);
  108. if (timezone == '-')
  109. timestamp += (*timezone_hours * 60 + *timezone_minutes) * 60;
  110. else if (timezone == '+')
  111. timestamp -= (*timezone_hours * 60 + *timezone_minutes) * 60;
  112. // FIXME: reject timestamp if resulting value wouldn't fit in a double
  113. return Value(1000.0 * timestamp + milliseconds.value_or(0));
  114. }
  115. static Value parse_date_string(String const& date_string)
  116. {
  117. auto value = parse_simplified_iso8601(date_string);
  118. if (value.is_finite_number())
  119. return value;
  120. // Date.parse() is allowed to accept an arbitrary number of implementation-defined formats.
  121. // Parse formats of this type: "Wed Apr 17 23:08:53 +0000 2019"
  122. auto maybe_datetime = Core::DateTime::parse("%a %b %e %T %z %Y", date_string);
  123. if (maybe_datetime.has_value())
  124. return Value(1000.0 * maybe_datetime.value().timestamp());
  125. return js_nan();
  126. }
  127. DateConstructor::DateConstructor(GlobalObject& global_object)
  128. : NativeFunction(vm().names.Date.as_string(), *global_object.function_prototype())
  129. {
  130. }
  131. void DateConstructor::initialize(GlobalObject& global_object)
  132. {
  133. auto& vm = this->vm();
  134. NativeFunction::initialize(global_object);
  135. // 21.4.3.3 Date.prototype, https://tc39.es/ecma262/#sec-date.prototype
  136. define_direct_property(vm.names.prototype, global_object.date_prototype(), 0);
  137. u8 attr = Attribute::Writable | Attribute::Configurable;
  138. define_native_function(vm.names.now, now, 0, attr);
  139. define_native_function(vm.names.parse, parse, 1, attr);
  140. define_native_function(vm.names.UTC, utc, 1, attr);
  141. define_direct_property(vm.names.length, Value(7), Attribute::Configurable);
  142. }
  143. DateConstructor::~DateConstructor()
  144. {
  145. }
  146. struct DatetimeAndMilliseconds {
  147. Core::DateTime datetime;
  148. i16 milliseconds { 0 };
  149. };
  150. static DatetimeAndMilliseconds now()
  151. {
  152. struct timeval tv;
  153. gettimeofday(&tv, nullptr);
  154. auto datetime = Core::DateTime::now();
  155. auto milliseconds = static_cast<i16>(tv.tv_usec / 1000);
  156. return { datetime, milliseconds };
  157. }
  158. // 21.4.2.1 Date ( ...values ), https://tc39.es/ecma262/#sec-date
  159. ThrowCompletionOr<Value> DateConstructor::call()
  160. {
  161. auto [datetime, milliseconds] = JS::now();
  162. auto* date = Date::create(global_object(), datetime, milliseconds, false);
  163. return js_string(heap(), date->string());
  164. }
  165. // 21.4.2.1 Date ( ...values ), https://tc39.es/ecma262/#sec-date
  166. ThrowCompletionOr<Object*> DateConstructor::construct(FunctionObject& new_target)
  167. {
  168. auto& vm = this->vm();
  169. auto& global_object = this->global_object();
  170. if (vm.argument_count() == 0) {
  171. auto [datetime, milliseconds] = JS::now();
  172. return TRY(ordinary_create_from_constructor<Date>(global_object, new_target, &GlobalObject::date_prototype, datetime, milliseconds, false));
  173. }
  174. auto create_invalid_date = [&global_object, &new_target]() -> ThrowCompletionOr<Date*> {
  175. auto datetime = Core::DateTime::create(1970, 1, 1, 0, 0, 0);
  176. auto milliseconds = static_cast<i16>(0);
  177. return ordinary_create_from_constructor<Date>(global_object, new_target, &GlobalObject::date_prototype, datetime, milliseconds, true);
  178. };
  179. if (vm.argument_count() == 1) {
  180. auto value = vm.argument(0);
  181. if (value.is_string())
  182. value = parse_date_string(value.as_string().string());
  183. else
  184. value = TRY(value.to_number(global_object));
  185. if (!value.is_finite_number())
  186. return TRY(create_invalid_date());
  187. // A timestamp since the epoch, in UTC.
  188. double value_as_double = value.as_double();
  189. if (value_as_double > Date::time_clip)
  190. return TRY(create_invalid_date());
  191. auto datetime = Core::DateTime::from_timestamp(static_cast<time_t>(value_as_double / 1000));
  192. auto milliseconds = static_cast<i16>(fmod(value_as_double, 1000));
  193. return TRY(ordinary_create_from_constructor<Date>(global_object, new_target, &GlobalObject::date_prototype, datetime, milliseconds, false));
  194. }
  195. // A date/time in components, in local time.
  196. auto arg_or = [&vm, &global_object](size_t i, i32 fallback) -> ThrowCompletionOr<Value> {
  197. return vm.argument_count() > i ? vm.argument(i).to_number(global_object) : Value(fallback);
  198. };
  199. auto year_value = TRY(vm.argument(0).to_number(global_object));
  200. if (!year_value.is_finite_number())
  201. return TRY(create_invalid_date());
  202. auto year = year_value.as_i32();
  203. auto month_index_value = TRY(vm.argument(1).to_number(global_object));
  204. if (!month_index_value.is_finite_number())
  205. return TRY(create_invalid_date());
  206. auto month_index = month_index_value.as_i32();
  207. auto day_value = TRY(arg_or(2, 1));
  208. if (!day_value.is_finite_number())
  209. return TRY(create_invalid_date());
  210. auto day = day_value.as_i32();
  211. auto hours_value = TRY(arg_or(3, 0));
  212. if (!hours_value.is_finite_number())
  213. return TRY(create_invalid_date());
  214. auto hours = hours_value.as_i32();
  215. auto minutes_value = TRY(arg_or(4, 0));
  216. if (!minutes_value.is_finite_number())
  217. return TRY(create_invalid_date());
  218. auto minutes = minutes_value.as_i32();
  219. auto seconds_value = TRY(arg_or(5, 0));
  220. if (!seconds_value.is_finite_number())
  221. return TRY(create_invalid_date());
  222. auto seconds = seconds_value.as_i32();
  223. auto milliseconds_value = TRY(arg_or(6, 0));
  224. if (!milliseconds_value.is_finite_number())
  225. return TRY(create_invalid_date());
  226. auto milliseconds = milliseconds_value.as_i32();
  227. seconds += milliseconds / 1000;
  228. milliseconds %= 1000;
  229. if (milliseconds < 0) {
  230. seconds -= 1;
  231. milliseconds += 1000;
  232. }
  233. if (year >= 0 && year <= 99)
  234. year += 1900;
  235. int month = month_index + 1;
  236. auto datetime = Core::DateTime::create(year, month, day, hours, minutes, seconds);
  237. auto time = datetime.timestamp() * 1000.0 + milliseconds;
  238. if (time > Date::time_clip)
  239. return TRY(create_invalid_date());
  240. return TRY(ordinary_create_from_constructor<Date>(global_object, new_target, &GlobalObject::date_prototype, datetime, milliseconds, false));
  241. }
  242. // 21.4.3.1 Date.now ( ), https://tc39.es/ecma262/#sec-date.now
  243. JS_DEFINE_NATIVE_FUNCTION(DateConstructor::now)
  244. {
  245. struct timeval tv;
  246. gettimeofday(&tv, nullptr);
  247. return Value(floor(tv.tv_sec * 1000.0 + tv.tv_usec / 1000.0));
  248. }
  249. // 21.4.3.2 Date.parse ( string ), https://tc39.es/ecma262/#sec-date.parse
  250. JS_DEFINE_NATIVE_FUNCTION(DateConstructor::parse)
  251. {
  252. if (!vm.argument_count())
  253. return js_nan();
  254. auto date_string = TRY(vm.argument(0).to_string(global_object));
  255. return parse_date_string(date_string);
  256. }
  257. // 21.4.3.4 Date.UTC ( year [ , month [ , date [ , hours [ , minutes [ , seconds [ , ms ] ] ] ] ] ] ), https://tc39.es/ecma262/#sec-date.utc
  258. JS_DEFINE_NATIVE_FUNCTION(DateConstructor::utc)
  259. {
  260. auto arg_or = [&vm, &global_object](size_t i, i32 fallback) -> ThrowCompletionOr<i32> {
  261. return vm.argument_count() > i ? vm.argument(i).to_i32(global_object) : fallback;
  262. };
  263. int year = TRY(vm.argument(0).to_i32(global_object));
  264. if (year >= 0 && year <= 99)
  265. year += 1900;
  266. struct tm tm = {};
  267. tm.tm_year = year - 1900;
  268. tm.tm_mon = TRY(arg_or(1, 0)); // 0-based in both tm and JavaScript
  269. tm.tm_mday = TRY(arg_or(2, 1));
  270. tm.tm_hour = TRY(arg_or(3, 0));
  271. tm.tm_min = TRY(arg_or(4, 0));
  272. tm.tm_sec = TRY(arg_or(5, 0));
  273. // timegm() doesn't read tm.tm_wday and tm.tm_yday, no need to fill them in.
  274. int milliseconds = TRY(arg_or(6, 0));
  275. return Value(1000.0 * timegm(&tm) + milliseconds);
  276. }
  277. }