Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8248387

Nashorn eval of named function returns null in Java 9+

    Details

    • Subcomponent:
    • Introduced In Version:
      9
    • CPU:
      x86_64
    • OS:
      linux

      Description

      ADDITIONAL SYSTEM INFORMATION :
      Tested on OSX, as well as debian linux.

      A DESCRIPTION OF THE PROBLEM :
      When evaluating a script containing a function in Nashorn, the behavior in Java 11 differs from that of Java 8.

      Calling eval on an anonymous function will return the invocable function, but if the function has been named it will instead return null. I cannot find any mention of this change in behavior in the documentation. This means user provided scripts that worked in Java 8 are not compatible with Java 11, if the user optionally decided to name their function.

      It appears the change was made in Java 9. I briefly tested it using the jjs tool:

      $ jjs -version
      nashorn 1.8.0_252
      jjs> function foo() {}
      function foo() {}
      jjs>

      Compare to
      $ jjs -version
      nashorn 11.0.7
      Warning: The jjs tool is planned to be removed from a future JDK release
      jjs> function foo() {}
      jjs>

      And in java 9:
      $ jjs -version
      nashorn 9
      jjs> function foo() {}
      jjs>

      REGRESSION : Last worked in version 8

      STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
      Using the nashorn ScriptEngine, eval "function foo() {}" and note that you get null back. Compare this to eval "function () {}", which does not return null.

      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      Expected result is the Java 8 behavior of both evals returning a ScriptObjectMirror of the provided function.
      ACTUAL -
      eval("function() {}") returns a ScriptObjectMirror.
      eval("function foo() {}") returns null.

      ---------- BEGIN SOURCE ----------
      import javax.script.ScriptEngine;
      import javax.script.ScriptEngineManager;

      public class NashornTest {

        public static void main(String[] args) throws Exception {
          ScriptEngine nashorn = new ScriptEngineManager().getEngineByName("nashorn");
          Object anonymous = nashorn.eval("function() {}");
          Object named = nashorn.eval("function foo() {}");

          if (named == null) {
            System.err.println("Named function evaled to null while anonymous evaled to "+anonymous);
            System.exit(1);
          }
        }
      }
      ---------- END SOURCE ----------

      FREQUENCY : always


        Attachments

          Activity

            People

            • Assignee:
              hannesw Hannes Wallnoefer
              Reporter:
              webbuggrp Webbug Group
            • Votes:
              0 Vote for this issue
              Watchers:
              3 Start watching this issue

              Dates

              • Created:
                Updated:
                Resolved: