From 7bd2eb8c44e35c9df5b8e81188ce7129d1ca3ef3 Mon Sep 17 00:00:00 2001 From: RBRi Date: Tue, 3 May 2022 05:11:54 +0200 Subject: [PATCH] improve log output of Callable's (#1213) Change console output to print output identifying Callables and other function objects using some identifying text and not just "null". Fixes https://github.com/mozilla/rhino/pull/1213 --- src/org/mozilla/javascript/NativeConsole.java | 29 ++++++++++++++++++- .../javascript/tests/NativeConsoleTest.java | 16 ++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) diff --git a/src/org/mozilla/javascript/NativeConsole.java b/src/org/mozilla/javascript/NativeConsole.java index 08223d8887..c709ff1616 100644 --- a/src/org/mozilla/javascript/NativeConsole.java +++ b/src/org/mozilla/javascript/NativeConsole.java @@ -325,7 +325,34 @@ private static String formatObj(Context cx, Scriptable scope, Object arg) { } try { - Object stringify = NativeJSON.stringify(cx, scope, arg, null, null); + // NativeJSON.stringify outputs Callable's as null, convert to string + // to make the output less confusing + final Callable replacer = + new Callable() { + @Override + public Object call( + Context callCx, + Scriptable callScope, + Scriptable callThisObj, + Object[] callArgs) { + Object value = callArgs[1]; + while (value instanceof Delegator) { + value = ((Delegator) value).getDelegee(); + } + if (value instanceof BaseFunction) { + StringBuilder sb = new StringBuilder(); + sb.append("function ") + .append(((BaseFunction) value).getFunctionName()) + .append("() {...}"); + return sb.toString(); + } + if (value instanceof Callable) { + return ScriptRuntime.toString(value); + } + return value; + } + }; + Object stringify = NativeJSON.stringify(cx, scope, arg, replacer, null); return ScriptRuntime.toString(stringify); } catch (EcmaError e) { if ("TypeError".equals(e.getName())) { diff --git a/testsrc/org/mozilla/javascript/tests/NativeConsoleTest.java b/testsrc/org/mozilla/javascript/tests/NativeConsoleTest.java index 81284baecd..daa5943a5e 100644 --- a/testsrc/org/mozilla/javascript/tests/NativeConsoleTest.java +++ b/testsrc/org/mozilla/javascript/tests/NativeConsoleTest.java @@ -361,6 +361,22 @@ public void print() { assertPrintMsg("console.error('abc', 123)", "abc 123"); } + @Test + public void printCallable() { + String js = "function foo() {}\n console.log(foo)"; + assertPrintMsg(js, "\"function foo() {...}\""); + + // suppress body + js = "function fooo() { var i = 0; }\n console.log(fooo)"; + assertPrintMsg(js, "\"function fooo() {...}\""); + + js = "console.log(/abc/i)"; + assertPrintMsg(js, "\"/abc/i\""); + + js = "function foo() {}\n" + "console.log([foo, /abc/])"; + assertPrintMsg(js, "[\"function foo() {...}\",\"/abc/\"]"); + } + @Test public void trace() { assertPrintMsg(