DateConstructor.cpp 9.8 KB

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