DateConstructor.cpp 10 KB

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