When using Java V1.8, there is a trick you can use to parse with the Nashorn implementation that comes out the box. By looking at the unit tests in the OpenSDK source code, you can see how to use the parser only, without doing all the extra compilation etc...
Options options = new Options("nashorn");
options.set("anon.functions", true);
options.set("parse.only", true);
options.set("scripting", true);
ErrorManager errors = new ErrorManager();
Context context = new Context(options, errors, Thread.currentThread().getContextClassLoader());
Source source = new Source("test", "var a = 10; var b = a + 1;" +
"function someFunction() { return b + 1; } ");
Parser parser = new Parser(context.getEnv(), source, errors);
FunctionNode functionNode = parser.parse();
Block block = functionNode.getBody();
List<Statement> statements = block.getStatements();
Once this code runs, you will have the Abstract Syntax Tree (AST) for the 3 expressions in the 'statements' list.
This can then be interpreted or manipulated to your needs.
The previous example works with following imports:
import jdk.nashorn.internal.ir.Block;
import jdk.nashorn.internal.ir.FunctionNode;
import jdk.nashorn.internal.ir.Statement;
import jdk.nashorn.internal.parser.Parser;
import jdk.nashorn.internal.runtime.Context;
import jdk.nashorn.internal.runtime.ErrorManager;
import jdk.nashorn.internal.runtime.Source;
import jdk.nashorn.internal.runtime.options.Options;
You might need to add an access rule to make jdk/nashorn/internal/**
accessible.
In my context, I am using Java Script as an expression language for my own Domain Specific Language (DSL) which I will then compile to Java classes at runtime and use. The AST lets me generate appropriate Java code that captures the intent of the Java Script expressions.
Nashorn is available with Java SE 8.
The link to information about getting the Nashorn source code is here:
https://wiki.openjdk.java.net/display/Nashorn/Building+Nashorn