Nathan Devery
Nathan Devery

Reputation: 51

Nashorn Abstract Syntax Tree Traversal

I am attempting to parse this Javascript via Nashorn:

function someFunction() { return b + 1 };

and navigate to all of the statements. This including statements inside the function.

The code below just prints: "function {U%}someFunction = [] function {U%}someFunction()"

How do I "get inside" the function node to it's body "return b + 1"? I presume I need to traverse the tree with a visitor and get the child node?

I have been following the second answer to the following question: Javascript parser for Java

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;

import java.util.List;

public class Main {

    public static void main(String[] args){
        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   = Source.sourceFor("test", "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();

        for(Statement statement: statements){
            System.out.println(statement);
        }
    }
}

Upvotes: 4

Views: 985

Answers (1)

A. Sundararajan
A. Sundararajan

Reputation: 4405

Using private/internal implementation classes of nashorn engine is not a good idea. With security manager on, you'll get access exception. With jdk9 and beyond, you'll get module access error w/without security manager (as jdk.nashorn.internal.* packages not exported from nashorn module).

You've two options to parse javascript using nashorn:

To use Parser API, you need to use jdk9+.

  • For jdk8, you can use parser.js

    load("nashorn:parser.js");

and call "parse" function from script. This function returns a JSON object that represents AST of the script parsed.

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

Upvotes: 4

Related Questions