DateConstructor.cpp 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  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. auto date = construct(*this);
  129. if (!date.is_object())
  130. return {};
  131. return js_string(heap(), static_cast<Date&>(date.as_object()).string());
  132. }
  133. Value DateConstructor::construct(Function&)
  134. {
  135. auto& vm = this->vm();
  136. if (vm.argument_count() == 0) {
  137. struct timeval tv;
  138. gettimeofday(&tv, nullptr);
  139. auto datetime = Core::DateTime::now();
  140. auto milliseconds = static_cast<u16>(tv.tv_usec / 1000);
  141. return Date::create(global_object(), datetime, milliseconds);
  142. }
  143. auto create_invalid_date = [this]() {
  144. auto datetime = Core::DateTime::from_timestamp(static_cast<time_t>(0));
  145. auto milliseconds = static_cast<u16>(0);
  146. return Date::create(global_object(), datetime, milliseconds, true);
  147. };
  148. if (vm.argument_count() == 1) {
  149. auto value = vm.argument(0);
  150. if (value.is_string())
  151. value = parse_simplified_iso8601(value.as_string().string());
  152. else
  153. value = value.to_number(global_object());
  154. if (vm.exception())
  155. return {};
  156. if (!value.is_finite_number()) {
  157. return create_invalid_date();
  158. }
  159. // A timestamp since the epoch, in UTC.
  160. double value_as_double = value.as_double();
  161. auto datetime = Core::DateTime::from_timestamp(static_cast<time_t>(value_as_double / 1000));
  162. auto milliseconds = static_cast<u16>(fmod(value_as_double, 1000));
  163. return Date::create(global_object(), datetime, milliseconds);
  164. }
  165. // A date/time in components, in local time.
  166. auto arg_or = [&vm, this](size_t i, i32 fallback) { return vm.argument_count() > i ? vm.argument(i).to_number(global_object()) : Value(fallback); };
  167. auto year_value = vm.argument(0).to_number(global_object());
  168. if (vm.exception())
  169. return {};
  170. if (!year_value.is_finite_number()) {
  171. return create_invalid_date();
  172. }
  173. auto year = year_value.as_i32();
  174. auto month_index_value = vm.argument(1).to_number(global_object());
  175. if (vm.exception())
  176. return {};
  177. if (!month_index_value.is_finite_number()) {
  178. return create_invalid_date();
  179. }
  180. auto month_index = month_index_value.as_i32();
  181. auto day_value = arg_or(2, 1);
  182. if (vm.exception())
  183. return {};
  184. if (!day_value.is_finite_number()) {
  185. return create_invalid_date();
  186. }
  187. auto day = day_value.as_i32();
  188. auto hours_value = arg_or(3, 0);
  189. if (vm.exception())
  190. return {};
  191. if (!hours_value.is_finite_number()) {
  192. return create_invalid_date();
  193. }
  194. auto hours = hours_value.as_i32();
  195. auto minutes_value = arg_or(4, 0);
  196. if (vm.exception())
  197. return {};
  198. if (!minutes_value.is_finite_number()) {
  199. return create_invalid_date();
  200. }
  201. auto minutes = minutes_value.as_i32();
  202. auto seconds_value = arg_or(5, 0);
  203. if (vm.exception())
  204. return {};
  205. if (!seconds_value.is_finite_number()) {
  206. return create_invalid_date();
  207. }
  208. auto seconds = seconds_value.as_i32();
  209. auto milliseconds_value = arg_or(6, 0);
  210. if (vm.exception())
  211. return {};
  212. if (!milliseconds_value.is_finite_number()) {
  213. return create_invalid_date();
  214. }
  215. auto milliseconds = milliseconds_value.as_i32();
  216. seconds += milliseconds / 1000;
  217. milliseconds %= 1000;
  218. if (milliseconds < 0) {
  219. seconds -= 1;
  220. milliseconds += 1000;
  221. }
  222. if (year >= 0 && year <= 99)
  223. year += 1900;
  224. int month = month_index + 1;
  225. auto datetime = Core::DateTime::create(year, month, day, hours, minutes, seconds);
  226. return Date::create(global_object(), datetime, milliseconds);
  227. }
  228. JS_DEFINE_NATIVE_FUNCTION(DateConstructor::now)
  229. {
  230. struct timeval tv;
  231. gettimeofday(&tv, nullptr);
  232. return Value(tv.tv_sec * 1000.0 + tv.tv_usec / 1000.0);
  233. }
  234. JS_DEFINE_NATIVE_FUNCTION(DateConstructor::parse)
  235. {
  236. if (!vm.argument_count())
  237. return js_nan();
  238. auto iso_8601 = vm.argument(0).to_string(global_object);
  239. if (vm.exception())
  240. return {};
  241. return parse_simplified_iso8601(iso_8601);
  242. }
  243. JS_DEFINE_NATIVE_FUNCTION(DateConstructor::utc)
  244. {
  245. auto arg_or = [&vm, &global_object](size_t i, i32 fallback) { return vm.argument_count() > i ? vm.argument(i).to_i32(global_object) : fallback; };
  246. int year = vm.argument(0).to_i32(global_object);
  247. if (year >= 0 && year <= 99)
  248. year += 1900;
  249. struct tm tm = {};
  250. tm.tm_year = year - 1900;
  251. tm.tm_mon = arg_or(1, 0); // 0-based in both tm and JavaScript
  252. tm.tm_mday = arg_or(2, 1);
  253. tm.tm_hour = arg_or(3, 0);
  254. tm.tm_min = arg_or(4, 0);
  255. tm.tm_sec = arg_or(5, 0);
  256. // timegm() doesn't read tm.tm_wday and tm.tm_yday, no need to fill them in.
  257. int milliseconds = arg_or(6, 0);
  258. return Value(1000.0 * timegm(&tm) + milliseconds);
  259. }
  260. }