DateConstructor.cpp 11 KB

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