简体   繁体   中英

How to find all the occurrences of a Javascript function using Java and Rhino

I need to search for all the occurrences of a particular Javascript function in a Javascript file using Java and Rhino. I have succeeded in browsing all the occurrences of function calls using the Visitor pattern (see code below), but I have not been able to retrieve the name of the function been called. Which is the correct way to do it?

package it.dss.javascriptParser;


import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;

import org.mozilla.javascript.Parser;
import org.mozilla.javascript.ast.AstNode;
import org.mozilla.javascript.ast.FunctionCall;
import org.mozilla.javascript.ast.NodeVisitor;

public class JavascriptParser {

public static void main(String[] args) throws IOException {
    class Printer implements NodeVisitor {

        public boolean visit(AstNode node) {
            if (node instanceof FunctionCall) {
                              // How do I get the name of the function being called?

            }
            return true;
        }
    }

    String file = "/dss2.js";
    Reader reader = new FileReader(file);
    try {
        AstNode node = new Parser().parse(reader, file, 1);
        node.visit(new Printer());
    } finally {
        reader.close();
    }
}
}

FunctionCall class represents just invocation of function, its target is function name (org.mozilla.javascript.ast.Name).

To get name of invoked function use:

AstNode target = ((FunctionCall) node).getTarget();
Name name = (Name) target;
System.out.println(name.getIdentifier());

From the FunctionCall you can retrieve the function name by doing the following:

((FunctionCall) node).getTarget().getEnclosingFunction().getFunctionName();

Note: Anonymous functions will return null .

Given the function name and the visitor pattern you can easily find out the occurrences of any named function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM