Search code examples
javascriptjavanashorn

nashorn JS: execute AST string?


Given a string that represents a Nashorn AST, can that string then be executed

In JDK 8, an AST can be obtained by calling parse(String) using load("nashorn:parser.js"), how would one do the reverse: AST to execution?


Solution

  • You've to write your own AST to pretty printer converter for AST returned by JDK8's parser.js.

    Note that there is a Java Parser API in jdk9 (https://docs.oracle.com/javase/9/docs/api/jdk/nashorn/api/tree/class-use/Parser.html). For the AST from this parser, there is a "pretty printer" sample script here:

    http://hg.openjdk.java.net/jdk9/dev/nashorn/file/17cc754c8936/samples/prettyprinter.js