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