diff --git a/js/rhino/src/org/mozilla/javascript/Interpreter.java b/js/rhino/src/org/mozilla/javascript/Interpreter.java index 03bc1f4ce1c..913ebf7d68c 100644 --- a/js/rhino/src/org/mozilla/javascript/Interpreter.java +++ b/js/rhino/src/org/mozilla/javascript/Interpreter.java @@ -637,11 +637,11 @@ public class Interpreter int fnType = scriptOrFn.getFunctionNode(fnIndex). getFunctionType(); // Only function expressions or function expression - // statements needs closure code creating new function + // statements need closure code creating new function // object on stack as function statements are initialized - // at script/function start - // In addition function expression can not present here - // at statement level, they must only present as expressions. + // at script/function start. + // In addition, function expressions can not be present here + // at statement level, they must only be present as expressions. if (fnType == FunctionNode.FUNCTION_EXPRESSION_STATEMENT) { addIndexOp(Icode_CLOSURE_STMT, fnIndex); } else { @@ -649,6 +649,17 @@ public class Interpreter throw Kit.codeBug(); } } + // For function statements or function expression statements + // in scripts, we need to ensure that the result of the script + // is the function if it is the last statement in the script. + // For example, eval("function () {}") should return a + // function, not undefined. + if (!itsInFunctionFlag) { + addIndexOp(Icode_CLOSURE_EXPR, fnIndex); + stackChange(1); + addIcode(Icode_POP_RESULT); + stackChange(-1); + } } break; diff --git a/js/rhino/toolsrc/org/mozilla/javascript/tools/shell/Main.java b/js/rhino/toolsrc/org/mozilla/javascript/tools/shell/Main.java index 1b97bfd4d5c..44e615bb246 100644 --- a/js/rhino/toolsrc/org/mozilla/javascript/tools/shell/Main.java +++ b/js/rhino/toolsrc/org/mozilla/javascript/tools/shell/Main.java @@ -365,7 +365,11 @@ public class Main lineno, null); if (script != null) { Object result = evaluateScript(script, cx, global); - if (result != Context.getUndefinedValue()) { + // Avoid printing out undefined or function definitions. + if (result != Context.getUndefinedValue() && + !(result instanceof Function && + source.trim().startsWith("function"))) + { try { ps.println(Context.toString(result)); } catch (RhinoException rex) {