Console.cpp 24 KB

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