Console.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707
  1. /*
  2. * Copyright (c) 2020, Emanuele Torre <torreemanuele6@gmail.com>
  3. * Copyright (c) 2020-2023, Linus Groh <linusg@serenityos.org>
  4. * Copyright (c) 2021-2022, Sam Atkins <atkinssj@serenityos.org>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include <AK/MemoryStream.h>
  9. #include <LibJS/Console.h>
  10. #include <LibJS/Print.h>
  11. #include <LibJS/Runtime/AbstractOperations.h>
  12. #include <LibJS/Runtime/Completion.h>
  13. #include <LibJS/Runtime/StringConstructor.h>
  14. #include <LibJS/Runtime/Temporal/Duration.h>
  15. #include <LibJS/Runtime/ThrowableStringBuilder.h>
  16. namespace JS {
  17. Console::Console(Realm& realm)
  18. : m_realm(realm)
  19. {
  20. }
  21. // 1.1.1. assert(condition, ...data), https://console.spec.whatwg.org/#assert
  22. ThrowCompletionOr<Value> Console::assert_()
  23. {
  24. auto& vm = realm().vm();
  25. // 1. If condition is true, return.
  26. auto condition = vm.argument(0).to_boolean();
  27. if (condition)
  28. return js_undefined();
  29. // 2. Let message be a string without any formatting specifiers indicating generically an assertion failure (such as "Assertion failed").
  30. auto message = PrimitiveString::create(vm, "Assertion failed"_string);
  31. // NOTE: Assemble `data` from the function arguments.
  32. MarkedVector<Value> data { vm.heap() };
  33. if (vm.argument_count() > 1) {
  34. data.ensure_capacity(vm.argument_count() - 1);
  35. for (size_t i = 1; i < vm.argument_count(); ++i) {
  36. data.append(vm.argument(i));
  37. }
  38. }
  39. // 3. If data is empty, append message to data.
  40. if (data.is_empty()) {
  41. data.append(message);
  42. }
  43. // 4. Otherwise:
  44. else {
  45. // 1. Let first be data[0].
  46. auto& first = data[0];
  47. // 2. If Type(first) is not String, then prepend message to data.
  48. if (!first.is_string()) {
  49. data.prepend(message);
  50. }
  51. // 3. Otherwise:
  52. else {
  53. // 1. Let concat be the concatenation of message, U+003A (:), U+0020 SPACE, and first.
  54. auto concat = TRY_OR_THROW_OOM(vm, String::formatted("{}: {}", message->utf8_string(), MUST(first.to_string(vm))));
  55. // 2. Set data[0] to concat.
  56. data[0] = PrimitiveString::create(vm, move(concat));
  57. }
  58. }
  59. // 5. Perform Logger("assert", data).
  60. if (m_client)
  61. TRY(m_client->logger(LogLevel::Assert, data));
  62. return js_undefined();
  63. }
  64. // 1.1.2. clear(), https://console.spec.whatwg.org/#clear
  65. Value Console::clear()
  66. {
  67. // 1. Empty the appropriate group stack.
  68. m_group_stack.clear();
  69. // 2. If possible for the environment, clear the console. (Otherwise, do nothing.)
  70. if (m_client)
  71. m_client->clear();
  72. return js_undefined();
  73. }
  74. // 1.1.3. debug(...data), https://console.spec.whatwg.org/#debug
  75. ThrowCompletionOr<Value> Console::debug()
  76. {
  77. // 1. Perform Logger("debug", data).
  78. if (m_client) {
  79. auto data = vm_arguments();
  80. return m_client->logger(LogLevel::Debug, data);
  81. }
  82. return js_undefined();
  83. }
  84. // 1.1.4. error(...data), https://console.spec.whatwg.org/#error
  85. ThrowCompletionOr<Value> Console::error()
  86. {
  87. // 1. Perform Logger("error", data).
  88. if (m_client) {
  89. auto data = vm_arguments();
  90. return m_client->logger(LogLevel::Error, data);
  91. }
  92. return js_undefined();
  93. }
  94. // 1.1.5. info(...data), https://console.spec.whatwg.org/#info
  95. ThrowCompletionOr<Value> Console::info()
  96. {
  97. // 1. Perform Logger("info", data).
  98. if (m_client) {
  99. auto data = vm_arguments();
  100. return m_client->logger(LogLevel::Info, data);
  101. }
  102. return js_undefined();
  103. }
  104. // 1.1.6. log(...data), https://console.spec.whatwg.org/#log
  105. ThrowCompletionOr<Value> Console::log()
  106. {
  107. // 1. Perform Logger("log", data).
  108. if (m_client) {
  109. auto data = vm_arguments();
  110. return m_client->logger(LogLevel::Log, data);
  111. }
  112. return js_undefined();
  113. }
  114. // 1.1.8. trace(...data), https://console.spec.whatwg.org/#trace
  115. ThrowCompletionOr<Value> Console::trace()
  116. {
  117. if (!m_client)
  118. return js_undefined();
  119. auto& vm = realm().vm();
  120. // 1. Let trace be some implementation-specific, potentially-interactive representation of the callstack from where this function was called.
  121. Console::Trace trace;
  122. auto& execution_context_stack = vm.execution_context_stack();
  123. // NOTE: -2 to skip the console.trace() execution context
  124. for (ssize_t i = execution_context_stack.size() - 2; i >= 0; --i) {
  125. auto const& function_name = execution_context_stack[i]->function_name;
  126. trace.stack.append(function_name.is_empty()
  127. ? "<anonymous>"_string
  128. : TRY_OR_THROW_OOM(vm, String::from_deprecated_string(function_name)));
  129. }
  130. // 2. Optionally, let formattedData be the result of Formatter(data), and incorporate formattedData as a label for trace.
  131. if (vm.argument_count() > 0) {
  132. auto data = vm_arguments();
  133. auto formatted_data = TRY(m_client->formatter(data));
  134. trace.label = TRY(value_vector_to_string(formatted_data));
  135. }
  136. // 3. Perform Printer("trace", « trace »).
  137. return m_client->printer(Console::LogLevel::Trace, trace);
  138. }
  139. // 1.1.9. warn(...data), https://console.spec.whatwg.org/#warn
  140. ThrowCompletionOr<Value> Console::warn()
  141. {
  142. // 1. Perform Logger("warn", data).
  143. if (m_client) {
  144. auto data = vm_arguments();
  145. return m_client->logger(LogLevel::Warn, data);
  146. }
  147. return js_undefined();
  148. }
  149. // 1.1.10. dir(item, options), https://console.spec.whatwg.org/#dir
  150. ThrowCompletionOr<Value> Console::dir()
  151. {
  152. auto& vm = realm().vm();
  153. // 1. Let object be item with generic JavaScript object formatting applied.
  154. // NOTE: Generic formatting is performed by ConsoleClient::printer().
  155. auto object = vm.argument(0);
  156. // 2. Perform Printer("dir", « object », options).
  157. if (m_client) {
  158. MarkedVector<Value> printer_arguments { vm.heap() };
  159. TRY_OR_THROW_OOM(vm, printer_arguments.try_append(object));
  160. return m_client->printer(LogLevel::Dir, move(printer_arguments));
  161. }
  162. return js_undefined();
  163. }
  164. static ThrowCompletionOr<String> label_or_fallback(VM& vm, StringView fallback)
  165. {
  166. return vm.argument_count() > 0
  167. ? vm.argument(0).to_string(vm)
  168. : TRY_OR_THROW_OOM(vm, String::from_utf8(fallback));
  169. }
  170. // 1.2.1. count(label), https://console.spec.whatwg.org/#count
  171. ThrowCompletionOr<Value> Console::count()
  172. {
  173. auto& vm = realm().vm();
  174. // NOTE: "default" is the default value in the IDL. https://console.spec.whatwg.org/#ref-for-count
  175. auto label = TRY(label_or_fallback(vm, "default"sv));
  176. // 1. Let map be the associated count map.
  177. auto& map = m_counters;
  178. // 2. If map[label] exists, set map[label] to map[label] + 1.
  179. if (auto found = map.find(label); found != map.end()) {
  180. map.set(label, found->value + 1);
  181. }
  182. // 3. Otherwise, set map[label] to 1.
  183. else {
  184. map.set(label, 1);
  185. }
  186. // 4. Let concat be the concatenation of label, U+003A (:), U+0020 SPACE, and ToString(map[label]).
  187. auto concat = TRY_OR_THROW_OOM(vm, String::formatted("{}: {}", label, map.get(label).value()));
  188. // 5. Perform Logger("count", « concat »).
  189. MarkedVector<Value> concat_as_vector { vm.heap() };
  190. concat_as_vector.append(PrimitiveString::create(vm, move(concat)));
  191. if (m_client)
  192. TRY(m_client->logger(LogLevel::Count, concat_as_vector));
  193. return js_undefined();
  194. }
  195. // 1.2.2. countReset(label), https://console.spec.whatwg.org/#countreset
  196. ThrowCompletionOr<Value> Console::count_reset()
  197. {
  198. auto& vm = realm().vm();
  199. // NOTE: "default" is the default value in the IDL. https://console.spec.whatwg.org/#ref-for-countreset
  200. auto label = TRY(label_or_fallback(vm, "default"sv));
  201. // 1. Let map be the associated count map.
  202. auto& map = m_counters;
  203. // 2. If map[label] exists, set map[label] to 0.
  204. if (auto found = map.find(label); found != map.end()) {
  205. map.set(label, 0);
  206. }
  207. // 3. Otherwise:
  208. else {
  209. // 1. Let message be a string without any formatting specifiers indicating generically
  210. // that the given label does not have an associated count.
  211. auto message = TRY_OR_THROW_OOM(vm, String::formatted("\"{}\" doesn't have a count", label));
  212. // 2. Perform Logger("countReset", « message »);
  213. MarkedVector<Value> message_as_vector { vm.heap() };
  214. message_as_vector.append(PrimitiveString::create(vm, move(message)));
  215. if (m_client)
  216. TRY(m_client->logger(LogLevel::CountReset, message_as_vector));
  217. }
  218. return js_undefined();
  219. }
  220. // 1.3.1. group(...data), https://console.spec.whatwg.org/#group
  221. ThrowCompletionOr<Value> Console::group()
  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"_string;
  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 expanded by default.
  239. // NOTE: This is handled in Printer.
  240. // 5. Perform Printer("group", « group »).
  241. if (m_client)
  242. TRY(m_client->printer(LogLevel::Group, group));
  243. // 6. Push group onto the appropriate group stack.
  244. m_group_stack.append(group);
  245. return js_undefined();
  246. }
  247. // 1.3.2. groupCollapsed(...data), https://console.spec.whatwg.org/#groupcollapsed
  248. ThrowCompletionOr<Value> Console::group_collapsed()
  249. {
  250. // 1. Let group be a new group.
  251. Group group;
  252. // 2. If data is not empty, let groupLabel be the result of Formatter(data).
  253. String group_label {};
  254. auto data = vm_arguments();
  255. if (!data.is_empty()) {
  256. auto formatted_data = TRY(m_client->formatter(data));
  257. group_label = TRY(value_vector_to_string(formatted_data));
  258. }
  259. // ... Otherwise, let groupLabel be an implementation-chosen label representing a group.
  260. else {
  261. group_label = "Group"_string;
  262. }
  263. // 3. Incorporate groupLabel as a label for group.
  264. group.label = group_label;
  265. // 4. Optionally, if the environment supports interactive groups, group should be collapsed by default.
  266. // NOTE: This is handled in Printer.
  267. // 5. Perform Printer("groupCollapsed", « group »).
  268. if (m_client)
  269. TRY(m_client->printer(LogLevel::GroupCollapsed, group));
  270. // 6. Push group onto the appropriate group stack.
  271. m_group_stack.append(group);
  272. return js_undefined();
  273. }
  274. // 1.3.3. groupEnd(), https://console.spec.whatwg.org/#groupend
  275. ThrowCompletionOr<Value> Console::group_end()
  276. {
  277. if (m_group_stack.is_empty())
  278. return js_undefined();
  279. // 1. Pop the last group from the group stack.
  280. m_group_stack.take_last();
  281. if (m_client)
  282. m_client->end_group();
  283. return js_undefined();
  284. }
  285. // 1.4.1. time(label), https://console.spec.whatwg.org/#time
  286. ThrowCompletionOr<Value> Console::time()
  287. {
  288. auto& vm = realm().vm();
  289. // NOTE: "default" is the default value in the IDL. https://console.spec.whatwg.org/#ref-for-time
  290. auto label = TRY(label_or_fallback(vm, "default"sv));
  291. // 1. If the associated timer table contains an entry with key label, return, optionally reporting
  292. // a warning to the console indicating that a timer with label `label` has already been started.
  293. if (m_timer_table.contains(label)) {
  294. if (m_client) {
  295. MarkedVector<Value> timer_already_exists_warning_message_as_vector { vm.heap() };
  296. auto message = TRY_OR_THROW_OOM(vm, String::formatted("Timer '{}' already exists.", label));
  297. timer_already_exists_warning_message_as_vector.append(PrimitiveString::create(vm, move(message)));
  298. TRY(m_client->printer(LogLevel::Warn, move(timer_already_exists_warning_message_as_vector)));
  299. }
  300. return js_undefined();
  301. }
  302. // 2. Otherwise, set the value of the entry with key label in the associated timer table to the current time.
  303. m_timer_table.set(label, Core::ElapsedTimer::start_new());
  304. return js_undefined();
  305. }
  306. // 1.4.2. timeLog(label, ...data), https://console.spec.whatwg.org/#timelog
  307. ThrowCompletionOr<Value> Console::time_log()
  308. {
  309. auto& vm = realm().vm();
  310. // NOTE: "default" is the default value in the IDL. https://console.spec.whatwg.org/#ref-for-timelog
  311. auto label = TRY(label_or_fallback(vm, "default"sv));
  312. // 1. Let timerTable be the associated timer table.
  313. // 2. Let startTime be timerTable[label].
  314. auto maybe_start_time = m_timer_table.find(label);
  315. // NOTE: Warn if the timer doesn't exist. Not part of the spec yet, but discussed here: https://github.com/whatwg/console/issues/134
  316. if (maybe_start_time == m_timer_table.end()) {
  317. if (m_client) {
  318. MarkedVector<Value> timer_does_not_exist_warning_message_as_vector { vm.heap() };
  319. auto message = TRY_OR_THROW_OOM(vm, String::formatted("Timer '{}' does not exist.", label));
  320. timer_does_not_exist_warning_message_as_vector.append(PrimitiveString::create(vm, move(message)));
  321. TRY(m_client->printer(LogLevel::Warn, move(timer_does_not_exist_warning_message_as_vector)));
  322. }
  323. return js_undefined();
  324. }
  325. auto start_time = maybe_start_time->value;
  326. // 3. Let duration be a string representing the difference between the current time and startTime, in an implementation-defined format.
  327. auto duration = TRY(format_time_since(start_time));
  328. // 4. Let concat be the concatenation of label, U+003A (:), U+0020 SPACE, and duration.
  329. auto concat = TRY_OR_THROW_OOM(vm, String::formatted("{}: {}", label, duration));
  330. // 5. Prepend concat to data.
  331. MarkedVector<Value> data { vm.heap() };
  332. data.ensure_capacity(vm.argument_count());
  333. data.append(PrimitiveString::create(vm, move(concat)));
  334. for (size_t i = 1; i < vm.argument_count(); ++i)
  335. data.append(vm.argument(i));
  336. // 6. Perform Printer("timeLog", data).
  337. if (m_client)
  338. TRY(m_client->printer(LogLevel::TimeLog, move(data)));
  339. return js_undefined();
  340. }
  341. // 1.4.3. timeEnd(label), https://console.spec.whatwg.org/#timeend
  342. ThrowCompletionOr<Value> Console::time_end()
  343. {
  344. auto& vm = realm().vm();
  345. // NOTE: "default" is the default value in the IDL. https://console.spec.whatwg.org/#ref-for-timeend
  346. auto label = TRY(label_or_fallback(vm, "default"sv));
  347. // 1. Let timerTable be the associated timer table.
  348. // 2. Let startTime be timerTable[label].
  349. auto maybe_start_time = m_timer_table.find(label);
  350. // NOTE: Warn if the timer doesn't exist. Not part of the spec yet, but discussed here: https://github.com/whatwg/console/issues/134
  351. if (maybe_start_time == m_timer_table.end()) {
  352. if (m_client) {
  353. MarkedVector<Value> timer_does_not_exist_warning_message_as_vector { vm.heap() };
  354. auto message = TRY_OR_THROW_OOM(vm, String::formatted("Timer '{}' does not exist.", label));
  355. timer_does_not_exist_warning_message_as_vector.append(PrimitiveString::create(vm, move(message)));
  356. TRY(m_client->printer(LogLevel::Warn, move(timer_does_not_exist_warning_message_as_vector)));
  357. }
  358. return js_undefined();
  359. }
  360. auto start_time = maybe_start_time->value;
  361. // 3. Remove timerTable[label].
  362. m_timer_table.remove(label);
  363. // 4. Let duration be a string representing the difference between the current time and startTime, in an implementation-defined format.
  364. auto duration = TRY(format_time_since(start_time));
  365. // 5. Let concat be the concatenation of label, U+003A (:), U+0020 SPACE, and duration.
  366. auto concat = TRY_OR_THROW_OOM(vm, String::formatted("{}: {}", label, duration));
  367. // 6. Perform Printer("timeEnd", « concat »).
  368. if (m_client) {
  369. MarkedVector<Value> concat_as_vector { vm.heap() };
  370. concat_as_vector.append(PrimitiveString::create(vm, move(concat)));
  371. TRY(m_client->printer(LogLevel::TimeEnd, move(concat_as_vector)));
  372. }
  373. return js_undefined();
  374. }
  375. MarkedVector<Value> Console::vm_arguments()
  376. {
  377. auto& vm = realm().vm();
  378. MarkedVector<Value> arguments { vm.heap() };
  379. arguments.ensure_capacity(vm.argument_count());
  380. for (size_t i = 0; i < vm.argument_count(); ++i) {
  381. arguments.append(vm.argument(i));
  382. }
  383. return arguments;
  384. }
  385. void Console::output_debug_message(LogLevel log_level, String const& output) const
  386. {
  387. switch (log_level) {
  388. case Console::LogLevel::Debug:
  389. dbgln("\033[32;1m(js debug)\033[0m {}", output);
  390. break;
  391. case Console::LogLevel::Error:
  392. dbgln("\033[32;1m(js error)\033[0m {}", output);
  393. break;
  394. case Console::LogLevel::Info:
  395. dbgln("\033[32;1m(js info)\033[0m {}", output);
  396. break;
  397. case Console::LogLevel::Log:
  398. dbgln("\033[32;1m(js log)\033[0m {}", output);
  399. break;
  400. case Console::LogLevel::Warn:
  401. dbgln("\033[32;1m(js warn)\033[0m {}", output);
  402. break;
  403. default:
  404. dbgln("\033[32;1m(js)\033[0m {}", output);
  405. break;
  406. }
  407. }
  408. void Console::report_exception(JS::Error const& exception, bool in_promise) const
  409. {
  410. if (m_client)
  411. m_client->report_exception(exception, in_promise);
  412. }
  413. ThrowCompletionOr<String> Console::value_vector_to_string(MarkedVector<Value> const& values)
  414. {
  415. auto& vm = realm().vm();
  416. ThrowableStringBuilder builder(vm);
  417. for (auto const& item : values) {
  418. if (!builder.is_empty())
  419. MUST_OR_THROW_OOM(builder.append(' '));
  420. MUST_OR_THROW_OOM(builder.append(TRY(item.to_string(vm))));
  421. }
  422. return builder.to_string();
  423. }
  424. ThrowCompletionOr<String> Console::format_time_since(Core::ElapsedTimer timer)
  425. {
  426. auto& vm = realm().vm();
  427. auto elapsed_ms = timer.elapsed_time().to_milliseconds();
  428. auto duration = TRY(Temporal::balance_duration(vm, 0, 0, 0, 0, elapsed_ms, 0, "0"_sbigint, "year"sv));
  429. auto append = [&](ThrowableStringBuilder& builder, auto format, auto number) -> ThrowCompletionOr<void> {
  430. if (!builder.is_empty())
  431. MUST_OR_THROW_OOM(builder.append(' '));
  432. MUST_OR_THROW_OOM(builder.appendff(format, number));
  433. return {};
  434. };
  435. ThrowableStringBuilder builder(vm);
  436. if (duration.days > 0)
  437. MUST_OR_THROW_OOM(append(builder, "{:.0} day(s)"sv, duration.days));
  438. if (duration.hours > 0)
  439. MUST_OR_THROW_OOM(append(builder, "{:.0} hour(s)"sv, duration.hours));
  440. if (duration.minutes > 0)
  441. MUST_OR_THROW_OOM(append(builder, "{:.0} minute(s)"sv, duration.minutes));
  442. if (duration.seconds > 0 || duration.milliseconds > 0) {
  443. double combined_seconds = duration.seconds + (0.001 * duration.milliseconds);
  444. MUST_OR_THROW_OOM(append(builder, "{:.3} seconds"sv, combined_seconds));
  445. }
  446. return builder.to_string();
  447. }
  448. // 2.1. Logger(logLevel, args), https://console.spec.whatwg.org/#logger
  449. ThrowCompletionOr<Value> ConsoleClient::logger(Console::LogLevel log_level, MarkedVector<Value> const& args)
  450. {
  451. auto& vm = m_console.realm().vm();
  452. // 1. If args is empty, return.
  453. if (args.is_empty())
  454. return js_undefined();
  455. // 2. Let first be args[0].
  456. auto first = args[0];
  457. // 3. Let rest be all elements following first in args.
  458. size_t rest_size = args.size() - 1;
  459. // 4. If rest is empty, perform Printer(logLevel, « first ») and return.
  460. if (rest_size == 0) {
  461. MarkedVector<Value> first_as_vector { vm.heap() };
  462. first_as_vector.append(first);
  463. return printer(log_level, move(first_as_vector));
  464. }
  465. // 5. Otherwise, perform Printer(logLevel, Formatter(args)).
  466. else {
  467. auto formatted = TRY(formatter(args));
  468. TRY(printer(log_level, formatted));
  469. }
  470. // 6. Return undefined.
  471. return js_undefined();
  472. }
  473. // 2.2. Formatter(args), https://console.spec.whatwg.org/#formatter
  474. ThrowCompletionOr<MarkedVector<Value>> ConsoleClient::formatter(MarkedVector<Value> const& args)
  475. {
  476. auto& realm = m_console.realm();
  477. auto& vm = realm.vm();
  478. // 1. If args’s size is 1, return args.
  479. if (args.size() == 1)
  480. return args;
  481. // 2. Let target be the first element of args.
  482. auto target = (!args.is_empty()) ? TRY(args.first().to_string(vm)) : String {};
  483. // 3. Let current be the second element of args.
  484. auto current = (args.size() > 1) ? args[1] : js_undefined();
  485. // 4. Find the first possible format specifier specifier, from the left to the right in target.
  486. auto find_specifier = [](StringView target) -> Optional<StringView> {
  487. size_t start_index = 0;
  488. while (start_index < target.length()) {
  489. auto maybe_index = target.find('%');
  490. if (!maybe_index.has_value())
  491. return {};
  492. auto index = maybe_index.value();
  493. if (index + 1 >= target.length())
  494. return {};
  495. switch (target[index + 1]) {
  496. case 'c':
  497. case 'd':
  498. case 'f':
  499. case 'i':
  500. case 'o':
  501. case 'O':
  502. case 's':
  503. return target.substring_view(index, 2);
  504. }
  505. start_index = index + 1;
  506. }
  507. return {};
  508. };
  509. auto maybe_specifier = find_specifier(target);
  510. // 5. If no format specifier was found, return args.
  511. if (!maybe_specifier.has_value()) {
  512. return args;
  513. }
  514. // 6. Otherwise:
  515. else {
  516. auto specifier = maybe_specifier.release_value();
  517. Optional<Value> converted;
  518. // 1. If specifier is %s, let converted be the result of Call(%String%, undefined, « current »).
  519. if (specifier == "%s"sv) {
  520. converted = TRY(call(vm, *realm.intrinsics().string_constructor(), js_undefined(), current));
  521. }
  522. // 2. If specifier is %d or %i:
  523. else if (specifier.is_one_of("%d"sv, "%i"sv)) {
  524. // 1. If Type(current) is Symbol, let converted be NaN
  525. if (current.is_symbol()) {
  526. converted = js_nan();
  527. }
  528. // 2. Otherwise, let converted be the result of Call(%parseInt%, undefined, « current, 10 »).
  529. else {
  530. converted = TRY(call(vm, *realm.intrinsics().parse_int_function(), js_undefined(), current, Value { 10 }));
  531. }
  532. }
  533. // 3. If specifier is %f:
  534. else if (specifier == "%f"sv) {
  535. // 1. If Type(current) is Symbol, let converted be NaN
  536. if (current.is_symbol()) {
  537. converted = js_nan();
  538. }
  539. // 2. Otherwise, let converted be the result of Call(% parseFloat %, undefined, « current »).
  540. else {
  541. converted = TRY(call(vm, *realm.intrinsics().parse_float_function(), js_undefined(), current));
  542. }
  543. }
  544. // 4. If specifier is %o, optionally let converted be current with optimally useful formatting applied.
  545. else if (specifier == "%o"sv) {
  546. // TODO: "Optimally-useful formatting"
  547. converted = current;
  548. }
  549. // 5. If specifier is %O, optionally let converted be current with generic JavaScript object formatting applied.
  550. else if (specifier == "%O"sv) {
  551. // TODO: "generic JavaScript object formatting"
  552. converted = current;
  553. }
  554. // 6. TODO: process %c
  555. else if (specifier == "%c"sv) {
  556. // NOTE: This has no spec yet. `%c` specifiers treat the argument as CSS styling for the log message.
  557. add_css_style_to_current_message(TRY(current.to_string(vm)));
  558. converted = PrimitiveString::create(vm, String {});
  559. }
  560. // 7. If any of the previous steps set converted, replace specifier in target with converted.
  561. if (converted.has_value())
  562. target = TRY_OR_THROW_OOM(vm, target.replace(specifier, TRY(converted->to_string(vm)), ReplaceMode::FirstOnly));
  563. }
  564. // 7. Let result be a list containing target together with the elements of args starting from the third onward.
  565. MarkedVector<Value> result { vm.heap() };
  566. result.ensure_capacity(args.size() - 1);
  567. result.empend(PrimitiveString::create(vm, move(target)));
  568. for (size_t i = 2; i < args.size(); ++i)
  569. result.unchecked_append(args[i]);
  570. // 8. Return Formatter(result).
  571. return formatter(result);
  572. }
  573. ThrowCompletionOr<String> ConsoleClient::generically_format_values(MarkedVector<Value> const& values)
  574. {
  575. AllocatingMemoryStream stream;
  576. auto& vm = m_console.realm().vm();
  577. PrintContext ctx { vm, stream, true };
  578. bool first = true;
  579. for (auto const& value : values) {
  580. if (!first)
  581. TRY_OR_THROW_OOM(vm, stream.write_until_depleted(" "sv.bytes()));
  582. TRY_OR_THROW_OOM(vm, JS::print(value, ctx));
  583. first = false;
  584. }
  585. // FIXME: Is it possible we could end up serializing objects to invalid UTF-8?
  586. return TRY_OR_THROW_OOM(vm, String::from_stream(stream, stream.used_buffer_size()));
  587. }
  588. }