From 7f4e82bf030d9fb0d95b9066b4ca126dcad9c484 Mon Sep 17 00:00:00 2001 From: Peterlits Zo Date: Tue, 24 Nov 2026 17:53:58 +0800 Subject: [PATCH] fix(console): preserve non-string first arguments Only treat string first arguments as format strings and add regression coverage for non-string values. Fixes boa-dev/boa#5687. --- core/wintertc/src/console/mod.rs | 16 ++++++++++---- core/wintertc/src/console/tests.rs | 35 ++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 4 deletions(-) diff --git a/core/wintertc/src/console/mod.rs b/core/wintertc/src/console/mod.rs index e658261502c..53d2c0be893 100644 --- a/core/wintertc/src/console/mod.rs +++ b/core/wintertc/src/console/mod.rs @@ -191,6 +191,8 @@ impl Logger for NullLogger { } /// This represents the `console` formatter. +/// +/// See Also: https://console.spec.whatwg.org/ fn formatter(data: &[JsValue], context: &mut Context) -> JsResult { fn to_string(value: &JsValue, _context: &mut Context) -> String { match value.variant() { @@ -203,12 +205,18 @@ fn formatter(data: &[JsValue], context: &mut Context) -> JsResult { [] => Ok(String::new()), [val] => Ok(to_string(val, context)), data => { + // Only strings are format strings. Otherwises do not format it. + let Some(target) = data[0].as_string() else { + return Ok(data + .iter() + .map(|value| to_string(value, context)) + .collect::>() + .join(" ")); + }; + let mut formatted = String::new(); let mut arg_index = 1; - let target = data - .get_or_undefined(0) - .to_string(context)? - .to_std_string_escaped(); + let target = target.to_std_string_escaped(); let mut chars = target.chars(); while let Some(c) = chars.next() { if c == '%' { diff --git a/core/wintertc/src/console/tests.rs b/core/wintertc/src/console/tests.rs index 12c1d73cb47..c8c0311c9d7 100644 --- a/core/wintertc/src/console/tests.rs +++ b/core/wintertc/src/console/tests.rs @@ -417,6 +417,41 @@ fn console_log_date() { ); } +#[test] +fn console_log_non_string_first_argument() { + let mut context = Context::default(); + let logger = RecordingLogger::default(); + Console::register_with_logger(logger.clone(), &mut context).unwrap(); + + run_test_actions_with( + [TestAction::run(indoc! {r#" + console.log([], { hello: 'world' }); + console.log({ hello: 'world' }, 'tail'); + console.log(Symbol('test'), 'tail'); + console.log(['%s'], 'tail'); + console.log(null, undefined, false, 42, 1n); + const array = []; + Object.defineProperty(array, 'toString', { + value() { throw new Error('must not call toString'); } + }); + console.log(array, 'tail'); + "#})], + &mut context, + ); + + assert_eq!( + *logger.log.borrow(), + indoc! {r#" + [] { hello: "world" } + { hello: "world" } tail + Symbol(test) tail + [ "%s" ] tail + null undefined false 42 1n + [] tail + "#} + ); +} + #[test] fn trace_with_stack_trace() { let mut context = Context::default();