Console.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. /*
  2. * Copyright (c) 2020, Emanuele Torre <torreemanuele6@gmail.com>
  3. * Copyright (c) 2020-2021, Linus Groh <linusg@serenityos.org>
  4. * Copyright (c) 2021, Sam Atkins <atkinssj@serenityos.org>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include <LibJS/Console.h>
  9. #include <LibJS/Runtime/GlobalObject.h>
  10. #include <LibJS/Runtime/Temporal/Duration.h>
  11. namespace JS {
  12. Console::Console(GlobalObject& global_object)
  13. : m_global_object(global_object)
  14. {
  15. }
  16. VM& Console::vm()
  17. {
  18. return m_global_object.vm();
  19. }
  20. // 1.1.3. debug(...data), https://console.spec.whatwg.org/#debug
  21. ThrowCompletionOr<Value> Console::debug()
  22. {
  23. // 1. Perform Logger("debug", data).
  24. if (m_client) {
  25. auto data = vm_arguments();
  26. return m_client->logger(LogLevel::Debug, data);
  27. }
  28. return js_undefined();
  29. }
  30. // 1.1.4. error(...data), https://console.spec.whatwg.org/#error
  31. ThrowCompletionOr<Value> Console::error()
  32. {
  33. // 1. Perform Logger("error", data).
  34. if (m_client) {
  35. auto data = vm_arguments();
  36. return m_client->logger(LogLevel::Error, data);
  37. }
  38. return js_undefined();
  39. }
  40. // 1.1.5. info(...data), https://console.spec.whatwg.org/#info
  41. ThrowCompletionOr<Value> Console::info()
  42. {
  43. // 1. Perform Logger("info", data).
  44. if (m_client) {
  45. auto data = vm_arguments();
  46. return m_client->logger(LogLevel::Info, data);
  47. }
  48. return js_undefined();
  49. }
  50. // 1.1.6. log(...data), https://console.spec.whatwg.org/#log
  51. ThrowCompletionOr<Value> Console::log()
  52. {
  53. // 1. Perform Logger("log", data).
  54. if (m_client) {
  55. auto data = vm_arguments();
  56. return m_client->logger(LogLevel::Log, data);
  57. }
  58. return js_undefined();
  59. }
  60. // 1.1.9. warn(...data), https://console.spec.whatwg.org/#warn
  61. ThrowCompletionOr<Value> Console::warn()
  62. {
  63. // 1. Perform Logger("warn", data).
  64. if (m_client) {
  65. auto data = vm_arguments();
  66. return m_client->logger(LogLevel::Warn, data);
  67. }
  68. return js_undefined();
  69. }
  70. // 1.1.2. clear(), https://console.spec.whatwg.org/#clear
  71. Value Console::clear()
  72. {
  73. // 1. Empty the appropriate group stack.
  74. m_group_stack.clear();
  75. // 2. If possible for the environment, clear the console. (Otherwise, do nothing.)
  76. if (m_client)
  77. m_client->clear();
  78. return js_undefined();
  79. }
  80. // 1.1.8. trace(...data), https://console.spec.whatwg.org/#trace
  81. ThrowCompletionOr<Value> Console::trace()
  82. {
  83. if (!m_client)
  84. return js_undefined();
  85. // 1. Let trace be some implementation-specific, potentially-interactive representation of the callstack from where this function was called.
  86. Console::Trace trace;
  87. auto& execution_context_stack = vm().execution_context_stack();
  88. // NOTE: -2 to skip the console.trace() execution context
  89. for (ssize_t i = execution_context_stack.size() - 2; i >= 0; --i) {
  90. auto& function_name = execution_context_stack[i]->function_name;
  91. trace.stack.append(function_name.is_empty() ? "<anonymous>" : function_name);
  92. }
  93. // 2. Optionally, let formattedData be the result of Formatter(data), and incorporate formattedData as a label for trace.
  94. if (vm().argument_count() > 0) {
  95. StringBuilder builder;
  96. auto data = vm_arguments();
  97. auto formatted_data = TRY(m_client->formatter(data));
  98. trace.label = TRY(value_vector_to_string(formatted_data));
  99. }
  100. // 3. Perform Printer("trace", « trace »).
  101. return m_client->printer(Console::LogLevel::Trace, trace);
  102. }
  103. // 1.2.1. count(label), https://console.spec.whatwg.org/#count
  104. ThrowCompletionOr<Value> Console::count()
  105. {
  106. // NOTE: "default" is the default value in the IDL. https://console.spec.whatwg.org/#ref-for-count
  107. auto label = vm().argument_count() ? TRY(vm().argument(0).to_string(global_object())) : "default";
  108. // 1. Let map be the associated count map.
  109. auto& map = m_counters;
  110. // 2. If map[label] exists, set map[label] to map[label] + 1.
  111. if (auto found = map.find(label); found != map.end()) {
  112. map.set(label, found->value + 1);
  113. }
  114. // 3. Otherwise, set map[label] to 1.
  115. else {
  116. map.set(label, 1);
  117. }
  118. // 4. Let concat be the concatenation of label, U+003A (:), U+0020 SPACE, and ToString(map[label]).
  119. String concat = String::formatted("{}: {}", label, map.get(label).value());
  120. // 5. Perform Logger("count", « concat »).
  121. MarkedVector<Value> concat_as_vector { global_object().heap() };
  122. concat_as_vector.append(js_string(vm(), concat));
  123. if (m_client)
  124. TRY(m_client->logger(LogLevel::Count, concat_as_vector));
  125. return js_undefined();
  126. }
  127. // 1.2.2. countReset(label), https://console.spec.whatwg.org/#countreset
  128. ThrowCompletionOr<Value> Console::count_reset()
  129. {
  130. // NOTE: "default" is the default value in the IDL. https://console.spec.whatwg.org/#ref-for-countreset
  131. auto label = vm().argument_count() ? TRY(vm().argument(0).to_string(global_object())) : "default";
  132. // 1. Let map be the associated count map.
  133. auto& map = m_counters;
  134. // 2. If map[label] exists, set map[label] to 0.
  135. if (auto found = map.find(label); found != map.end()) {
  136. map.set(label, 0);
  137. }
  138. // 3. Otherwise:
  139. else {
  140. // 1. Let message be a string without any formatting specifiers indicating generically
  141. // that the given label does not have an associated count.
  142. auto message = String::formatted("\"{}\" doesn't have a count", label);
  143. // 2. Perform Logger("countReset", « message »);
  144. MarkedVector<Value> message_as_vector { global_object().heap() };
  145. message_as_vector.append(js_string(vm(), message));
  146. if (m_client)
  147. TRY(m_client->logger(LogLevel::CountReset, message_as_vector));
  148. }
  149. return js_undefined();
  150. }
  151. // 1.1.1. assert(condition, ...data), https://console.spec.whatwg.org/#assert
  152. ThrowCompletionOr<Value> Console::assert_()
  153. {
  154. // 1. If condition is true, return.
  155. auto condition = vm().argument(0).to_boolean();
  156. if (condition)
  157. return js_undefined();
  158. // 2. Let message be a string without any formatting specifiers indicating generically an assertion failure (such as "Assertion failed").
  159. auto message = js_string(vm(), "Assertion failed");
  160. // NOTE: Assemble `data` from the function arguments.
  161. MarkedVector<Value> data { global_object().heap() };
  162. if (vm().argument_count() > 1) {
  163. data.ensure_capacity(vm().argument_count() - 1);
  164. for (size_t i = 1; i < vm().argument_count(); ++i) {
  165. data.append(vm().argument(i));
  166. }
  167. }
  168. // 3. If data is empty, append message to data.
  169. if (data.is_empty()) {
  170. data.append(message);
  171. }
  172. // 4. Otherwise:
  173. else {
  174. // 1. Let first be data[0].
  175. auto& first = data[0];
  176. // 2. If Type(first) is not String, then prepend message to data.
  177. if (!first.is_string()) {
  178. data.prepend(message);
  179. }
  180. // 3. Otherwise:
  181. else {
  182. // 1. Let concat be the concatenation of message, U+003A (:), U+0020 SPACE, and first.
  183. auto concat = js_string(vm(), String::formatted("{}: {}", message->string(), first.to_string(global_object()).value()));
  184. // 2. Set data[0] to concat.
  185. data[0] = concat;
  186. }
  187. }
  188. // 5. Perform Logger("assert", data).
  189. if (m_client)
  190. TRY(m_client->logger(LogLevel::Assert, data));
  191. return js_undefined();
  192. }
  193. // 1.3.1. group(...data), https://console.spec.whatwg.org/#group
  194. ThrowCompletionOr<Value> Console::group()
  195. {
  196. // 1. Let group be a new group.
  197. Group group;
  198. // 2. If data is not empty, let groupLabel be the result of Formatter(data).
  199. String group_label;
  200. auto data = vm_arguments();
  201. if (!data.is_empty()) {
  202. auto formatted_data = TRY(m_client->formatter(data));
  203. group_label = TRY(value_vector_to_string(formatted_data));
  204. }
  205. // ... Otherwise, let groupLabel be an implementation-chosen label representing a group.
  206. else {
  207. group_label = "Group";
  208. }
  209. // 3. Incorporate groupLabel as a label for group.
  210. group.label = group_label;
  211. // 4. Optionally, if the environment supports interactive groups, group should be expanded by default.
  212. // NOTE: This is handled in Printer.
  213. // 5. Perform Printer("group", « group »).
  214. if (m_client)
  215. TRY(m_client->printer(LogLevel::Group, group));
  216. // 6. Push group onto the appropriate group stack.
  217. m_group_stack.append(group);
  218. return js_undefined();
  219. }
  220. // 1.3.2. groupCollapsed(...data), https://console.spec.whatwg.org/#groupcollapsed
  221. ThrowCompletionOr<Value> Console::group_collapsed()
  222. {
  223. // 1. Let group be a new group.
  224. Group group;
  225. // 2. If data is not empty, let groupLabel be the result of Formatter(data).
  226. String group_label;
  227. auto data = vm_arguments();
  228. if (!data.is_empty()) {
  229. auto formatted_data = TRY(m_client->formatter(data));
  230. group_label = TRY(value_vector_to_string(formatted_data));
  231. }
  232. // ... Otherwise, let groupLabel be an implementation-chosen label representing a group.
  233. else {
  234. group_label = "Group";
  235. }
  236. // 3. Incorporate groupLabel as a label for group.
  237. group.label = group_label;
  238. // 4. Optionally, if the environment supports interactive groups, group should be collapsed by default.
  239. // NOTE: This is handled in Printer.
  240. // 5. Perform Printer("groupCollapsed", « group »).
  241. if (m_client)
  242. TRY(m_client->printer(LogLevel::GroupCollapsed, group));
  243. // 6. Push group onto the appropriate group stack.
  244. m_group_stack.append(group);
  245. return js_undefined();
  246. }
  247. // 1.3.3. groupEnd(), https://console.spec.whatwg.org/#groupend
  248. ThrowCompletionOr<Value> Console::group_end()
  249. {
  250. if (m_group_stack.is_empty())
  251. return js_undefined();
  252. // 1. Pop the last group from the group stack.
  253. m_group_stack.take_last();
  254. if (m_client)
  255. m_client->end_group();
  256. return js_undefined();
  257. }
  258. // 1.4.1. time(label), https://console.spec.whatwg.org/#time
  259. ThrowCompletionOr<Value> Console::time()
  260. {
  261. // NOTE: "default" is the default value in the IDL. https://console.spec.whatwg.org/#ref-for-time
  262. auto label = vm().argument_count() ? TRY(vm().argument(0).to_string(global_object())) : "default";
  263. // 1. If the associated timer table contains an entry with key label, return, optionally reporting
  264. // a warning to the console indicating that a timer with label `label` has already been started.
  265. if (m_timer_table.contains(label)) {
  266. if (m_client) {
  267. MarkedVector<Value> timer_already_exists_warning_message_as_vector { global_object().heap() };
  268. timer_already_exists_warning_message_as_vector.append(js_string(vm(), String::formatted("Timer '{}' already exists.", label)));
  269. TRY(m_client->printer(LogLevel::Warn, move(timer_already_exists_warning_message_as_vector)));
  270. }
  271. return js_undefined();
  272. }
  273. // 2. Otherwise, set the value of the entry with key label in the associated timer table to the current time.
  274. m_timer_table.set(label, Core::ElapsedTimer::start_new());
  275. return js_undefined();
  276. }
  277. // 1.4.2. timeLog(label, ...data), https://console.spec.whatwg.org/#timelog
  278. ThrowCompletionOr<Value> Console::time_log()
  279. {
  280. // NOTE: "default" is the default value in the IDL. https://console.spec.whatwg.org/#ref-for-timelog
  281. auto label = vm().argument_count() ? TRY(vm().argument(0).to_string(global_object())) : "default";
  282. // 1. Let timerTable be the associated timer table.
  283. // 2. Let startTime be timerTable[label].
  284. auto maybe_start_time = m_timer_table.find(label);
  285. // NOTE: Warn if the timer doesn't exist. Not part of the spec yet, but discussed here: https://github.com/whatwg/console/issues/134
  286. if (maybe_start_time == m_timer_table.end()) {
  287. if (m_client) {
  288. MarkedVector<Value> timer_does_not_exist_warning_message_as_vector { global_object().heap() };
  289. timer_does_not_exist_warning_message_as_vector.append(js_string(vm(), String::formatted("Timer '{}' does not exist.", label)));
  290. TRY(m_client->printer(LogLevel::Warn, move(timer_does_not_exist_warning_message_as_vector)));
  291. }
  292. return js_undefined();
  293. }
  294. auto start_time = maybe_start_time->value;
  295. // 3. Let duration be a string representing the difference between the current time and startTime, in an implementation-defined format.
  296. auto duration = TRY(format_time_since(start_time));
  297. // 4. Let concat be the concatenation of label, U+003A (:), U+0020 SPACE, and duration.
  298. auto concat = String::formatted("{}: {}", label, duration);
  299. // 5. Prepend concat to data.
  300. MarkedVector<Value> data { global_object().heap() };
  301. data.ensure_capacity(vm().argument_count());
  302. data.append(js_string(vm(), concat));
  303. for (size_t i = 1; i < vm().argument_count(); ++i)
  304. data.append(vm().argument(i));
  305. // 6. Perform Printer("timeLog", data).
  306. if (m_client)
  307. TRY(m_client->printer(LogLevel::TimeLog, move(data)));
  308. return js_undefined();
  309. }
  310. // 1.4.3. timeEnd(label), https://console.spec.whatwg.org/#timeend
  311. ThrowCompletionOr<Value> Console::time_end()
  312. {
  313. // NOTE: "default" is the default value in the IDL. https://console.spec.whatwg.org/#ref-for-timeend
  314. auto label = vm().argument_count() ? TRY(vm().argument(0).to_string(global_object())) : "default";
  315. // 1. Let timerTable be the associated timer table.
  316. // 2. Let startTime be timerTable[label].
  317. auto maybe_start_time = m_timer_table.find(label);
  318. // NOTE: Warn if the timer doesn't exist. Not part of the spec yet, but discussed here: https://github.com/whatwg/console/issues/134
  319. if (maybe_start_time == m_timer_table.end()) {
  320. if (m_client) {
  321. MarkedVector<Value> timer_does_not_exist_warning_message_as_vector { global_object().heap() };
  322. timer_does_not_exist_warning_message_as_vector.append(js_string(vm(), String::formatted("Timer '{}' does not exist.", label)));
  323. TRY(m_client->printer(LogLevel::Warn, move(timer_does_not_exist_warning_message_as_vector)));
  324. }
  325. return js_undefined();
  326. }
  327. auto start_time = maybe_start_time->value;
  328. // 3. Remove timerTable[label].
  329. m_timer_table.remove(label);
  330. // 4. Let duration be a string representing the difference between the current time and startTime, in an implementation-defined format.
  331. auto duration = TRY(format_time_since(start_time));
  332. // 5. Let concat be the concatenation of label, U+003A (:), U+0020 SPACE, and duration.
  333. auto concat = String::formatted("{}: {}", label, duration);
  334. // 6. Perform Printer("timeEnd", « concat »).
  335. if (m_client) {
  336. MarkedVector<Value> concat_as_vector { global_object().heap() };
  337. concat_as_vector.append(js_string(vm(), concat));
  338. TRY(m_client->printer(LogLevel::TimeEnd, move(concat_as_vector)));
  339. }
  340. return js_undefined();
  341. }
  342. MarkedVector<Value> Console::vm_arguments()
  343. {
  344. MarkedVector<Value> arguments { global_object().heap() };
  345. arguments.ensure_capacity(vm().argument_count());
  346. for (size_t i = 0; i < vm().argument_count(); ++i) {
  347. arguments.append(vm().argument(i));
  348. }
  349. return arguments;
  350. }
  351. void Console::output_debug_message([[maybe_unused]] LogLevel log_level, [[maybe_unused]] String output) const
  352. {
  353. #ifdef __serenity__
  354. switch (log_level) {
  355. case Console::LogLevel::Debug:
  356. dbgln("\033[32;1m(js debug)\033[0m {}", output);
  357. break;
  358. case Console::LogLevel::Error:
  359. dbgln("\033[32;1m(js error)\033[0m {}", output);
  360. break;
  361. case Console::LogLevel::Info:
  362. dbgln("\033[32;1m(js info)\033[0m {}", output);
  363. break;
  364. case Console::LogLevel::Log:
  365. dbgln("\033[32;1m(js log)\033[0m {}", output);
  366. break;
  367. case Console::LogLevel::Warn:
  368. dbgln("\033[32;1m(js warn)\033[0m {}", output);
  369. break;
  370. default:
  371. dbgln("\033[32;1m(js)\033[0m {}", output);
  372. break;
  373. }
  374. #endif
  375. }
  376. ThrowCompletionOr<String> Console::value_vector_to_string(MarkedVector<Value> const& values)
  377. {
  378. StringBuilder builder;
  379. for (auto const& item : values) {
  380. if (!builder.is_empty())
  381. builder.append(' ');
  382. builder.append(TRY(item.to_string(global_object())));
  383. }
  384. return builder.to_string();
  385. }
  386. ThrowCompletionOr<String> Console::format_time_since(Core::ElapsedTimer timer)
  387. {
  388. auto elapsed_ms = timer.elapsed_time().to_milliseconds();
  389. auto duration = TRY(Temporal::balance_duration(global_object(), 0, 0, 0, 0, elapsed_ms, 0, "0"_sbigint, "year"));
  390. auto append = [&](StringBuilder& builder, auto format, auto... number) {
  391. if (!builder.is_empty())
  392. builder.append(' ');
  393. builder.appendff(format, number...);
  394. };
  395. StringBuilder builder;
  396. if (duration.days > 0)
  397. append(builder, "{:.0} day(s)", duration.days);
  398. if (duration.hours > 0)
  399. append(builder, "{:.0} hour(s)", duration.hours);
  400. if (duration.minutes > 0)
  401. append(builder, "{:.0} minute(s)", duration.minutes);
  402. if (duration.seconds > 0 || duration.milliseconds > 0) {
  403. double combined_seconds = duration.seconds + (0.001 * duration.milliseconds);
  404. append(builder, "{:.3} seconds", combined_seconds);
  405. }
  406. return builder.to_string();
  407. }
  408. VM& ConsoleClient::vm()
  409. {
  410. return global_object().vm();
  411. }
  412. // 2.1. Logger(logLevel, args), https://console.spec.whatwg.org/#logger
  413. ThrowCompletionOr<Value> ConsoleClient::logger(Console::LogLevel log_level, MarkedVector<Value> const& args)
  414. {
  415. auto& global_object = this->global_object();
  416. // 1. If args is empty, return.
  417. if (args.is_empty())
  418. return js_undefined();
  419. // 2. Let first be args[0].
  420. auto first = args[0];
  421. // 3. Let rest be all elements following first in args.
  422. size_t rest_size = args.size() - 1;
  423. // 4. If rest is empty, perform Printer(logLevel, « first ») and return.
  424. if (rest_size == 0) {
  425. MarkedVector<Value> first_as_vector { global_object.heap() };
  426. first_as_vector.append(first);
  427. return printer(log_level, move(first_as_vector));
  428. }
  429. // 5. If first does not contain any format specifiers, perform Printer(logLevel, args).
  430. if (!TRY(first.to_string(global_object)).contains('%')) {
  431. TRY(printer(log_level, args));
  432. } else {
  433. // 6. Otherwise, perform Printer(logLevel, Formatter(args)).
  434. auto formatted = TRY(formatter(args));
  435. TRY(printer(log_level, formatted));
  436. }
  437. // 7. Return undefined.
  438. return js_undefined();
  439. }
  440. // 2.2. Formatter(args), https://console.spec.whatwg.org/#formatter
  441. ThrowCompletionOr<MarkedVector<Value>> ConsoleClient::formatter(MarkedVector<Value> const& args)
  442. {
  443. // TODO: Actually implement formatting
  444. return args;
  445. }
  446. }