DateConstructor.cpp 9.7 KB

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