DateConstructor.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. /*
  2. * Copyright (c) 2020, Linus Groh <mail@linusgroh.de>
  3. * Copyright (c) 2020, Nico Weber <thakis@chromium.org>
  4. * Copyright (c) 2021, Petróczi Zoltán <petroczizoltan@tutanota.com>
  5. * All rights reserved.
  6. *
  7. * Redistribution and use in source and binary forms, with or without
  8. * modification, are permitted provided that the following conditions are met:
  9. *
  10. * 1. Redistributions of source code must retain the above copyright notice, this
  11. * list of conditions and the following disclaimer.
  12. *
  13. * 2. Redistributions in binary form must reproduce the above copyright notice,
  14. * this list of conditions and the following disclaimer in the documentation
  15. * and/or other materials provided with the distribution.
  16. *
  17. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  18. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  19. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  20. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  21. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  22. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  23. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  24. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  25. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  26. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  27. */
  28. #include <AK/GenericLexer.h>
  29. #include <LibCore/DateTime.h>
  30. #include <LibJS/Runtime/Date.h>
  31. #include <LibJS/Runtime/DateConstructor.h>
  32. #include <LibJS/Runtime/GlobalObject.h>
  33. #include <LibJS/Runtime/VM.h>
  34. #include <ctype.h>
  35. #include <sys/time.h>
  36. #include <time.h>
  37. namespace JS {
  38. static Value parse_simplified_iso8601(const String& iso_8601)
  39. {
  40. // Date.parse() is allowed to accept many formats. We strictly only accept things matching
  41. // http://www.ecma-international.org/ecma-262/#sec-date-time-string-format
  42. GenericLexer lexer(iso_8601);
  43. auto lex_n_digits = [&](size_t n, int& out) {
  44. if (lexer.tell_remaining() < n)
  45. return false;
  46. int r = 0;
  47. for (size_t i = 0; i < n; ++i) {
  48. char ch = lexer.consume();
  49. if (!isdigit(ch))
  50. return false;
  51. r = 10 * r + ch - '0';
  52. }
  53. out = r;
  54. return true;
  55. };
  56. int year = -1, month = -1, day = -1;
  57. int hours = -1, minutes = -1, seconds = -1, milliseconds = -1;
  58. char timezone = -1;
  59. int timezone_hours = -1, timezone_minutes = -1;
  60. auto lex_year = [&]() {
  61. if (lexer.consume_specific('+'))
  62. return lex_n_digits(6, year);
  63. if (lexer.consume_specific('-')) {
  64. int absolute_year;
  65. if (!lex_n_digits(6, absolute_year))
  66. return false;
  67. year = -absolute_year;
  68. return true;
  69. }
  70. return lex_n_digits(4, year);
  71. };
  72. auto lex_month = [&]() { return lex_n_digits(2, month) && month >= 1 && month <= 12; };
  73. auto lex_day = [&]() { return lex_n_digits(2, day) && day >= 1 && day <= 31; };
  74. auto lex_date = [&]() { return lex_year() && (!lexer.consume_specific('-') || (lex_month() && (!lexer.consume_specific('-') || lex_day()))); };
  75. auto lex_hours_minutes = [&](int& out_h, int& out_m) {
  76. int h, m;
  77. if (lex_n_digits(2, h) && h >= 0 && h <= 24 && lexer.consume_specific(':') && lex_n_digits(2, m) && m >= 0 && m <= 59) {
  78. out_h = h;
  79. out_m = m;
  80. return true;
  81. }
  82. return false;
  83. };
  84. auto lex_seconds = [&]() { return lex_n_digits(2, seconds) && seconds >= 0 && seconds <= 59; };
  85. auto lex_milliseconds = [&]() { return lex_n_digits(3, milliseconds); };
  86. auto lex_seconds_milliseconds = [&]() { return lex_seconds() && (!lexer.consume_specific('.') || lex_milliseconds()); };
  87. auto lex_timezone = [&]() {
  88. if (lexer.consume_specific('+')) {
  89. timezone = '+';
  90. return lex_hours_minutes(timezone_hours, timezone_minutes);
  91. }
  92. if (lexer.consume_specific('-')) {
  93. timezone = '-';
  94. return lex_hours_minutes(timezone_hours, timezone_minutes);
  95. }
  96. if (lexer.consume_specific('Z'))
  97. timezone = 'Z';
  98. return true;
  99. };
  100. auto lex_time = [&]() { return lex_hours_minutes(hours, minutes) && (!lexer.consume_specific(':') || lex_seconds_milliseconds()) && lex_timezone(); };
  101. if (!lex_date() || (lexer.consume_specific('T') && !lex_time()) || !lexer.is_eof()) {
  102. return js_nan();
  103. }
  104. // We parsed a valid date simplified ISO 8601 string. Values not present in the string are -1.
  105. VERIFY(year != -1); // A valid date string always has at least a year.
  106. struct tm tm = {};
  107. tm.tm_year = year - 1900;
  108. tm.tm_mon = month == -1 ? 0 : month - 1;
  109. tm.tm_mday = day == -1 ? 1 : day;
  110. tm.tm_hour = hours == -1 ? 0 : hours;
  111. tm.tm_min = minutes == -1 ? 0 : minutes;
  112. tm.tm_sec = seconds == -1 ? 0 : seconds;
  113. // http://www.ecma-international.org/ecma-262/#sec-date.parse:
  114. // "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."
  115. time_t timestamp;
  116. if (timezone != -1 || hours == -1)
  117. timestamp = timegm(&tm);
  118. else
  119. timestamp = mktime(&tm);
  120. if (timezone == '-')
  121. timestamp += (timezone_hours * 60 + timezone_minutes) * 60;
  122. else if (timezone == '+')
  123. timestamp -= (timezone_hours * 60 + timezone_minutes) * 60;
  124. // FIXME: reject timestamp if resulting value wouldn't fit in a double
  125. if (milliseconds == -1)
  126. milliseconds = 0;
  127. return Value(1000.0 * timestamp + milliseconds);
  128. }
  129. DateConstructor::DateConstructor(GlobalObject& global_object)
  130. : NativeFunction(vm().names.Date, *global_object.function_prototype())
  131. {
  132. }
  133. void DateConstructor::initialize(GlobalObject& global_object)
  134. {
  135. auto& vm = this->vm();
  136. NativeFunction::initialize(global_object);
  137. define_property(vm.names.prototype, global_object.date_prototype(), 0);
  138. define_property(vm.names.length, Value(7), Attribute::Configurable);
  139. define_native_function(vm.names.now, now, 0, Attribute::Writable | Attribute::Configurable);
  140. define_native_function(vm.names.parse, parse, 1, Attribute::Writable | Attribute::Configurable);
  141. define_native_function(vm.names.UTC, utc, 1, Attribute::Writable | Attribute::Configurable);
  142. }
  143. DateConstructor::~DateConstructor()
  144. {
  145. }
  146. Value DateConstructor::call()
  147. {
  148. auto date = construct(*this);
  149. if (!date.is_object())
  150. return {};
  151. return js_string(heap(), static_cast<Date&>(date.as_object()).string());
  152. }
  153. Value DateConstructor::construct(Function&)
  154. {
  155. auto& vm = this->vm();
  156. if (vm.argument_count() == 0) {
  157. struct timeval tv;
  158. gettimeofday(&tv, nullptr);
  159. auto datetime = Core::DateTime::now();
  160. auto milliseconds = static_cast<u16>(tv.tv_usec / 1000);
  161. return Date::create(global_object(), datetime, milliseconds);
  162. }
  163. auto create_invalid_date = [this]() {
  164. auto datetime = Core::DateTime::from_timestamp(static_cast<time_t>(0));
  165. auto milliseconds = static_cast<u16>(0);
  166. return Date::create(global_object(), 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. auto datetime = Core::DateTime::from_timestamp(static_cast<time_t>(value_as_double / 1000));
  182. auto milliseconds = static_cast<u16>(fmod(value_as_double, 1000));
  183. return Date::create(global_object(), datetime, milliseconds);
  184. }
  185. // A date/time in components, in local time.
  186. auto arg_or = [&vm, this](size_t i, i32 fallback) { return vm.argument_count() > i ? vm.argument(i).to_number(global_object()) : Value(fallback); };
  187. auto year_value = vm.argument(0).to_number(global_object());
  188. if (vm.exception())
  189. return {};
  190. if (!year_value.is_finite_number()) {
  191. return create_invalid_date();
  192. }
  193. auto year = year_value.as_i32();
  194. auto month_index_value = vm.argument(1).to_number(global_object());
  195. if (vm.exception())
  196. return {};
  197. if (!month_index_value.is_finite_number()) {
  198. return create_invalid_date();
  199. }
  200. auto month_index = month_index_value.as_i32();
  201. auto day_value = arg_or(2, 1);
  202. if (vm.exception())
  203. return {};
  204. if (!day_value.is_finite_number()) {
  205. return create_invalid_date();
  206. }
  207. auto day = day_value.as_i32();
  208. auto hours_value = arg_or(3, 0);
  209. if (vm.exception())
  210. return {};
  211. if (!hours_value.is_finite_number()) {
  212. return create_invalid_date();
  213. }
  214. auto hours = hours_value.as_i32();
  215. auto minutes_value = arg_or(4, 0);
  216. if (vm.exception())
  217. return {};
  218. if (!minutes_value.is_finite_number()) {
  219. return create_invalid_date();
  220. }
  221. auto minutes = minutes_value.as_i32();
  222. auto seconds_value = arg_or(5, 0);
  223. if (vm.exception())
  224. return {};
  225. if (!seconds_value.is_finite_number()) {
  226. return create_invalid_date();
  227. }
  228. auto seconds = seconds_value.as_i32();
  229. auto milliseconds_value = arg_or(6, 0);
  230. if (vm.exception())
  231. return {};
  232. if (!milliseconds_value.is_finite_number()) {
  233. return create_invalid_date();
  234. }
  235. auto milliseconds = milliseconds_value.as_i32();
  236. seconds += milliseconds / 1000;
  237. milliseconds %= 1000;
  238. if (milliseconds < 0) {
  239. seconds -= 1;
  240. milliseconds += 1000;
  241. }
  242. if (year >= 0 && year <= 99)
  243. year += 1900;
  244. int month = month_index + 1;
  245. auto datetime = Core::DateTime::create(year, month, day, hours, minutes, seconds);
  246. return Date::create(global_object(), datetime, milliseconds);
  247. }
  248. JS_DEFINE_NATIVE_FUNCTION(DateConstructor::now)
  249. {
  250. struct timeval tv;
  251. gettimeofday(&tv, nullptr);
  252. return Value(tv.tv_sec * 1000.0 + tv.tv_usec / 1000.0);
  253. }
  254. JS_DEFINE_NATIVE_FUNCTION(DateConstructor::parse)
  255. {
  256. if (!vm.argument_count())
  257. return js_nan();
  258. auto iso_8601 = vm.argument(0).to_string(global_object);
  259. if (vm.exception())
  260. return {};
  261. return parse_simplified_iso8601(iso_8601);
  262. }
  263. JS_DEFINE_NATIVE_FUNCTION(DateConstructor::utc)
  264. {
  265. auto arg_or = [&vm, &global_object](size_t i, i32 fallback) { return vm.argument_count() > i ? vm.argument(i).to_i32(global_object) : fallback; };
  266. int year = vm.argument(0).to_i32(global_object);
  267. if (year >= 0 && year <= 99)
  268. year += 1900;
  269. struct tm tm = {};
  270. tm.tm_year = year - 1900;
  271. tm.tm_mon = arg_or(1, 0); // 0-based in both tm and JavaScript
  272. tm.tm_mday = arg_or(2, 1);
  273. tm.tm_hour = arg_or(3, 0);
  274. tm.tm_min = arg_or(4, 0);
  275. tm.tm_sec = arg_or(5, 0);
  276. // timegm() doesn't read tm.tm_wday and tm.tm_yday, no need to fill them in.
  277. int milliseconds = arg_or(6, 0);
  278. return Value(1000.0 * timegm(&tm) + milliseconds);
  279. }
  280. }