Skip to content

Commit

Permalink
improve log output of Callable's (#1213)
Browse files Browse the repository at this point in the history
Change console output to print output identifying Callables and other function objects using some identifying text and not just "null".

Fixes #1213
  • Loading branch information
rbri authored May 3, 2022
1 parent 49fa793 commit 7bd2eb8
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 1 deletion.
29 changes: 28 additions & 1 deletion src/org/mozilla/javascript/NativeConsole.java
Original file line number Diff line number Diff line change
Expand Up @@ -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())) {
Expand Down
16 changes: 16 additions & 0 deletions testsrc/org/mozilla/javascript/tests/NativeConsoleTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down

0 comments on commit 7bd2eb8

Please sign in to comment.