DateConstructor.cpp 12 KB

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