DateConstructor.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  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/CharacterTypes.h>
  9. #include <AK/GenericLexer.h>
  10. #include <AK/Time.h>
  11. #include <LibCore/DateTime.h>
  12. #include <LibJS/Runtime/AbstractOperations.h>
  13. #include <LibJS/Runtime/Date.h>
  14. #include <LibJS/Runtime/DateConstructor.h>
  15. #include <LibJS/Runtime/GlobalObject.h>
  16. #include <LibJS/Runtime/VM.h>
  17. #include <sys/time.h>
  18. #include <time.h>
  19. namespace JS {
  20. // 21.4.3.2 Date.parse ( string ), https://tc39.es/ecma262/#sec-date.parse
  21. static Value parse_simplified_iso8601(GlobalObject& global_object, const String& iso_8601)
  22. {
  23. // 21.4.1.15 Date Time String Format, https://tc39.es/ecma262/#sec-date-time-string-format
  24. GenericLexer lexer(iso_8601);
  25. auto lex_n_digits = [&](size_t n, Optional<int>& out) {
  26. if (lexer.tell_remaining() < n)
  27. return false;
  28. int r = 0;
  29. for (size_t i = 0; i < n; ++i) {
  30. char ch = lexer.consume();
  31. if (!is_ascii_digit(ch))
  32. return false;
  33. r = 10 * r + ch - '0';
  34. }
  35. out = r;
  36. return true;
  37. };
  38. Optional<int> year;
  39. Optional<int> month;
  40. Optional<int> day;
  41. Optional<int> hours;
  42. Optional<int> minutes;
  43. Optional<int> seconds;
  44. Optional<int> milliseconds;
  45. Optional<char> timezone;
  46. Optional<int> timezone_hours;
  47. Optional<int> timezone_minutes;
  48. auto lex_year = [&]() {
  49. if (lexer.consume_specific('+'))
  50. return lex_n_digits(6, year);
  51. if (lexer.consume_specific('-')) {
  52. Optional<int> absolute_year;
  53. if (!lex_n_digits(6, absolute_year))
  54. return false;
  55. year = -absolute_year.value();
  56. return true;
  57. }
  58. return lex_n_digits(4, year);
  59. };
  60. auto lex_month = [&]() { return lex_n_digits(2, month) && *month >= 1 && *month <= 12; };
  61. auto lex_day = [&]() { return lex_n_digits(2, day) && *day >= 1 && *day <= 31; };
  62. auto lex_date = [&]() { return lex_year() && (!lexer.consume_specific('-') || (lex_month() && (!lexer.consume_specific('-') || lex_day()))); };
  63. auto lex_hours_minutes = [&](Optional<int>& out_h, Optional<int>& out_m) {
  64. Optional<int> h;
  65. Optional<int> m;
  66. if (lex_n_digits(2, h) && *h >= 0 && *h <= 24 && lexer.consume_specific(':') && lex_n_digits(2, m) && *m >= 0 && *m <= 59) {
  67. out_h = move(h);
  68. out_m = move(m);
  69. return true;
  70. }
  71. return false;
  72. };
  73. auto lex_seconds = [&]() { return lex_n_digits(2, seconds) && *seconds >= 0 && *seconds <= 59; };
  74. auto lex_milliseconds = [&]() { return lex_n_digits(3, milliseconds); };
  75. auto lex_seconds_milliseconds = [&]() { return lex_seconds() && (!lexer.consume_specific('.') || lex_milliseconds()); };
  76. auto lex_timezone = [&]() {
  77. if (lexer.consume_specific('+')) {
  78. timezone = '+';
  79. return lex_hours_minutes(timezone_hours, timezone_minutes);
  80. }
  81. if (lexer.consume_specific('-')) {
  82. timezone = '-';
  83. return lex_hours_minutes(timezone_hours, timezone_minutes);
  84. }
  85. if (lexer.consume_specific('Z'))
  86. timezone = 'Z';
  87. return true;
  88. };
  89. auto lex_time = [&]() { return lex_hours_minutes(hours, minutes) && (!lexer.consume_specific(':') || lex_seconds_milliseconds()) && lex_timezone(); };
  90. if (!lex_date() || (lexer.consume_specific('T') && !lex_time()) || !lexer.is_eof()) {
  91. return js_nan();
  92. }
  93. // We parsed a valid date simplified ISO 8601 string.
  94. VERIFY(year.has_value()); // A valid date string always has at least a year.
  95. auto time = AK::Time::from_timestamp(*year, month.value_or(1), day.value_or(1), hours.value_or(0), minutes.value_or(0), seconds.value_or(0), milliseconds.value_or(0));
  96. auto time_ms = static_cast<double>(time.to_milliseconds());
  97. // https://tc39.es/ecma262/#sec-date.parse:
  98. // "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."
  99. if (!timezone.has_value() && hours.has_value())
  100. time_ms += local_tza(time_ms, false);
  101. if (timezone == '-')
  102. time_ms += *timezone_hours * 3'600'000 + *timezone_minutes * 60'000;
  103. else if (timezone == '+')
  104. time_ms -= *timezone_hours * 3'600'000 + *timezone_minutes * 60'000;
  105. return time_clip(global_object, Value(time_ms));
  106. }
  107. static Value parse_date_string(GlobalObject& global_object, String const& date_string)
  108. {
  109. auto value = parse_simplified_iso8601(global_object, date_string);
  110. if (value.is_finite_number())
  111. return value;
  112. // Date.parse() is allowed to accept an arbitrary number of implementation-defined formats.
  113. // Parse formats of this type: "Wed Apr 17 23:08:53 +0000 2019"
  114. auto maybe_datetime = Core::DateTime::parse("%a %b %e %T %z %Y", date_string);
  115. if (maybe_datetime.has_value())
  116. return Value(1000.0 * maybe_datetime.value().timestamp());
  117. return js_nan();
  118. }
  119. DateConstructor::DateConstructor(GlobalObject& global_object)
  120. : NativeFunction(vm().names.Date.as_string(), *global_object.function_prototype())
  121. {
  122. }
  123. void DateConstructor::initialize(GlobalObject& global_object)
  124. {
  125. auto& vm = this->vm();
  126. NativeFunction::initialize(global_object);
  127. // 21.4.3.3 Date.prototype, https://tc39.es/ecma262/#sec-date.prototype
  128. define_direct_property(vm.names.prototype, global_object.date_prototype(), 0);
  129. u8 attr = Attribute::Writable | Attribute::Configurable;
  130. define_native_function(vm.names.now, now, 0, attr);
  131. define_native_function(vm.names.parse, parse, 1, attr);
  132. define_native_function(vm.names.UTC, utc, 7, attr);
  133. define_direct_property(vm.names.length, Value(7), Attribute::Configurable);
  134. }
  135. DateConstructor::~DateConstructor()
  136. {
  137. }
  138. struct DatetimeAndMilliseconds {
  139. Core::DateTime datetime;
  140. i16 milliseconds { 0 };
  141. };
  142. static DatetimeAndMilliseconds now()
  143. {
  144. struct timeval tv;
  145. gettimeofday(&tv, nullptr);
  146. auto datetime = Core::DateTime::now();
  147. auto milliseconds = static_cast<i16>(tv.tv_usec / 1000);
  148. return { datetime, milliseconds };
  149. }
  150. // 21.4.2.1 Date ( ...values ), https://tc39.es/ecma262/#sec-date
  151. ThrowCompletionOr<Value> DateConstructor::call()
  152. {
  153. auto [datetime, milliseconds] = JS::now();
  154. auto* date = Date::create(global_object(), datetime, milliseconds, false);
  155. return js_string(heap(), date->string());
  156. }
  157. // 21.4.2.1 Date ( ...values ), https://tc39.es/ecma262/#sec-date
  158. ThrowCompletionOr<Object*> DateConstructor::construct(FunctionObject& new_target)
  159. {
  160. auto& vm = this->vm();
  161. auto& global_object = this->global_object();
  162. if (vm.argument_count() == 0) {
  163. auto [datetime, milliseconds] = JS::now();
  164. return TRY(ordinary_create_from_constructor<Date>(global_object, new_target, &GlobalObject::date_prototype, datetime, milliseconds, false));
  165. }
  166. auto create_invalid_date = [&global_object, &new_target]() -> ThrowCompletionOr<Date*> {
  167. auto datetime = Core::DateTime::create(1970, 1, 1, 0, 0, 0);
  168. auto milliseconds = static_cast<i16>(0);
  169. return ordinary_create_from_constructor<Date>(global_object, new_target, &GlobalObject::date_prototype, datetime, milliseconds, true);
  170. };
  171. if (vm.argument_count() == 1) {
  172. auto value = vm.argument(0);
  173. if (value.is_string())
  174. value = parse_date_string(global_object, value.as_string().string());
  175. else
  176. value = TRY(value.to_number(global_object));
  177. if (!value.is_finite_number())
  178. return TRY(create_invalid_date());
  179. // A timestamp since the epoch, in UTC.
  180. double value_as_double = value.as_double();
  181. if (value_as_double > Date::time_clip)
  182. return TRY(create_invalid_date());
  183. auto datetime = Core::DateTime::from_timestamp(static_cast<time_t>(value_as_double / 1000));
  184. auto milliseconds = static_cast<i16>(fmod(value_as_double, 1000));
  185. return TRY(ordinary_create_from_constructor<Date>(global_object, new_target, &GlobalObject::date_prototype, datetime, milliseconds, false));
  186. }
  187. // A date/time in components, in local time.
  188. auto arg_or = [&vm, &global_object](size_t i, i32 fallback) -> ThrowCompletionOr<Value> {
  189. return vm.argument_count() > i ? vm.argument(i).to_number(global_object) : Value(fallback);
  190. };
  191. auto year_value = TRY(vm.argument(0).to_number(global_object));
  192. if (!year_value.is_finite_number())
  193. return TRY(create_invalid_date());
  194. auto year = year_value.as_i32();
  195. auto month_index_value = TRY(vm.argument(1).to_number(global_object));
  196. if (!month_index_value.is_finite_number())
  197. return TRY(create_invalid_date());
  198. auto month_index = month_index_value.as_i32();
  199. auto day_value = TRY(arg_or(2, 1));
  200. if (!day_value.is_finite_number())
  201. return TRY(create_invalid_date());
  202. auto day = day_value.as_i32();
  203. auto hours_value = TRY(arg_or(3, 0));
  204. if (!hours_value.is_finite_number())
  205. return TRY(create_invalid_date());
  206. auto hours = hours_value.as_i32();
  207. auto minutes_value = TRY(arg_or(4, 0));
  208. if (!minutes_value.is_finite_number())
  209. return TRY(create_invalid_date());
  210. auto minutes = minutes_value.as_i32();
  211. auto seconds_value = TRY(arg_or(5, 0));
  212. if (!seconds_value.is_finite_number())
  213. return TRY(create_invalid_date());
  214. auto seconds = seconds_value.as_i32();
  215. auto milliseconds_value = TRY(arg_or(6, 0));
  216. if (!milliseconds_value.is_finite_number())
  217. return TRY(create_invalid_date());
  218. auto milliseconds = milliseconds_value.as_i32();
  219. seconds += milliseconds / 1000;
  220. milliseconds %= 1000;
  221. if (milliseconds < 0) {
  222. seconds -= 1;
  223. milliseconds += 1000;
  224. }
  225. if (year >= 0 && year <= 99)
  226. year += 1900;
  227. int month = month_index + 1;
  228. auto datetime = Core::DateTime::create(year, month, day, hours, minutes, seconds);
  229. auto time = datetime.timestamp() * 1000.0 + milliseconds;
  230. if (time > Date::time_clip)
  231. return TRY(create_invalid_date());
  232. return TRY(ordinary_create_from_constructor<Date>(global_object, new_target, &GlobalObject::date_prototype, datetime, milliseconds, false));
  233. }
  234. // 21.4.3.1 Date.now ( ), https://tc39.es/ecma262/#sec-date.now
  235. JS_DEFINE_NATIVE_FUNCTION(DateConstructor::now)
  236. {
  237. struct timeval tv;
  238. gettimeofday(&tv, nullptr);
  239. return Value(floor(tv.tv_sec * 1000.0 + tv.tv_usec / 1000.0));
  240. }
  241. // 21.4.3.2 Date.parse ( string ), https://tc39.es/ecma262/#sec-date.parse
  242. JS_DEFINE_NATIVE_FUNCTION(DateConstructor::parse)
  243. {
  244. if (!vm.argument_count())
  245. return js_nan();
  246. auto date_string = TRY(vm.argument(0).to_string(global_object));
  247. return parse_date_string(global_object, date_string);
  248. }
  249. // 21.4.3.4 Date.UTC ( year [ , month [ , date [ , hours [ , minutes [ , seconds [ , ms ] ] ] ] ] ] ), https://tc39.es/ecma262/#sec-date.utc
  250. JS_DEFINE_NATIVE_FUNCTION(DateConstructor::utc)
  251. {
  252. auto arg_or = [&vm, &global_object](size_t i, i32 fallback) -> ThrowCompletionOr<Value> {
  253. return vm.argument_count() > i ? vm.argument(i).to_number(global_object) : Value(fallback);
  254. };
  255. // 1. Let y be ? ToNumber(year).
  256. auto year = TRY(vm.argument(0).to_number(global_object));
  257. // 2. If month is present, let m be ? ToNumber(month); else let m be +0𝔽.
  258. auto month = TRY(arg_or(1, 0));
  259. // 3. If date is present, let dt be ? ToNumber(date); else let dt be 1𝔽.
  260. auto date = TRY(arg_or(2, 1));
  261. // 4. If hours is present, let h be ? ToNumber(hours); else let h be +0𝔽.
  262. auto hours = TRY(arg_or(3, 0));
  263. // 5. If minutes is present, let min be ? ToNumber(minutes); else let min be +0𝔽.
  264. auto minutes = TRY(arg_or(4, 0));
  265. // 6. If seconds is present, let s be ? ToNumber(seconds); else let s be +0𝔽.
  266. auto seconds = TRY(arg_or(5, 0));
  267. // 7. If ms is present, let milli be ? ToNumber(ms); else let milli be +0𝔽.
  268. auto milliseconds = TRY(arg_or(6, 0));
  269. // 8. If y is NaN, let yr be NaN.
  270. // 9. Else,
  271. if (!year.is_nan()) {
  272. // a. Let yi be ! ToIntegerOrInfinity(y).
  273. auto year_double = MUST(year.to_integer_or_infinity(global_object));
  274. // b. If 0 ≤ yi ≤ 99, let yr be 1900𝔽 + 𝔽(yi); otherwise, let yr be y.
  275. if (0 <= year_double && year_double <= 99)
  276. year = Value(1900 + year_double);
  277. }
  278. // 10. Return TimeClip(MakeDate(MakeDay(yr, m, dt), MakeTime(h, min, s, milli))).
  279. auto day = make_day(global_object, year, month, date);
  280. auto time = make_time(global_object, hours, minutes, seconds, milliseconds);
  281. return time_clip(global_object, make_date(day, time));
  282. }
  283. }