Nashorn Parser API on JDK 8

Finding a Java / JDK API for parsing JavaScript (including Nashorn Extensions) I came across this Gist , which, according to a built-in comment, requires JDK 9 to start. Is there a reliable way to do the same on current or planned releases of JDK 8?

+6
source share
2 answers

The Nashorn Parser API ( http://openjdk.java.net/jeps/236 ) is a specific jdk9 API. The jdk8 or jdk8 update supports the script parser function.

loads ("Nashorn: parser.js");

and call the parsing function from the script. This function returns a JSON object that represents the AST for the script.

See this sample: http://hg.openjdk.java.net/jdk8u/jdk8u-dev/nashorn/file/bfea11f8c8f2/samples/astviewer.js

+8
source

While you can definitely use the parser using the Nashorn JavaScript code, it is even nicer in Java to use it through the JAVA API

import jdk.nashorn.api.scripting.ScriptUtils; import jdk.nashorn.internal.runtime.Context; import jdk.nashorn.internal.runtime.ECMAException; import jdk.nashorn.internal.runtime.ErrorManager; import jdk.nashorn.internal.runtime.options.Options; // set up the environment Options options = new Options("nashorn"); options.set("anon.functions", true); options.set("parse.only", true); options.set("scripting", true); ErrorManager errors = new ErrorManager(); Context contextm = new Context(options, errors, Thread.currentThread().getContextClassLoader()); Context.setGlobal(contextm.createGlobal()); // then for each bit of parsing String parseTree = ScriptUtils.parse(some_code_string, "nashorn", false); 
-1
source

Source: https://habr.com/ru/post/984023/


All Articles