Java 解析Beanshell代码

Java 解析Beanshell代码,java,parsing,beanshell,javacc,Java,Parsing,Beanshell,Javacc,我正在尝试为用beanshell编写的代码编写一个基本的静态代码分析工具,该工具将执行一些基本检查,如未使用的变量、方法,以及可能永远不会计算为true的条件 我已经尝试使用beanshell源代码发行版附带的解析器,如以下几个示例所示: import java.io.FileInputStream; import java.io.IOException; import bsh.ParseException; import bsh.Parser; import bsh.SimpleNode;

我正在尝试为用beanshell编写的代码编写一个基本的静态代码分析工具,该工具将执行一些基本检查,如未使用的变量、方法,以及可能永远不会计算为true的条件

我已经尝试使用beanshell源代码发行版附带的解析器,如以下几个示例所示:

import java.io.FileInputStream;
import java.io.IOException;

import bsh.ParseException;
import bsh.Parser;
import bsh.SimpleNode;

public class FindUnusedVariablesTask {

    String sourseFilePath;

    public FindUnusedVariablesTask(String sourseFilePath) {            
        this.sourseFilePath = sourseFilePath;
    }


    public String perform() throws ParseException, IOException {
        FileInputStream sourceStream = new FileInputStream(sourseFilePath);
        Parser p = new Parser(sourceStream);

        while (!p.Line()) {
            SimpleNode node = p.popNode();
            System.out.println(node.getText());
            for (int i=0; i<node.jjtGetNumChildren(); i++)
                System.out.println(node.getChild(i).getText());
        }
        sourceStream.close();
        return "";
    }
}
结果如下:

f1 ( ) { 
( ) 
{ 

String f2 ( String x ) { 
String 
( String x ) 
{ 

基本上我只得到解析的方法声明。我找不到在中访问已解析语句的方法。如何做到这一点?

BeanShell解析器生成AST。一般来说,AST的结构可以相当深入。上面给出的代码只在AST的1层深处显示

尝试递归遍历(我没有DeVKIT,因此将其视为伪代码):

导入bsh.Node//你也需要这个
公共字符串perform()引发ParseException,IOException{
FileInputStream sourceStream=新的FileInputStream(sourseFilePath);
Parser p=新的解析器(sourceStream);
而(!p.Line()){
递归打印(p.popNode(),“”);
}
sourceStream.close();
返回“”;
}
公共无效递归打印(节点,字符串前缀)
{
System.out.println(前缀+节点.getText());

对于(int i=0;iBeanShell解析器生成AST。一般来说,AST的结构可能相当深。上面给出的代码看起来只深入AST的一层

尝试递归遍历(我没有DeVKIT,因此将其视为伪代码):

import bsh.Node;//您也需要这个
公共字符串perform()引发ParseException,IOException{
FileInputStream sourceStream=新的FileInputStream(sourseFilePath);
Parser p=新的解析器(sourceStream);
而(!p.Line()){
递归打印(p.popNode(),“”);
}
sourceStream.close();
返回“”;
}
公共无效递归打印(节点,字符串前缀)
{
System.out.println(前缀+节点.getText());

对于(int i=0;我完全忘记了我必须在节点上递归。非常感谢!我完全忘记了我必须在节点上递归。非常感谢!
f1 ( ) { 
( ) 
{ 

String f2 ( String x ) { 
String 
( String x ) 
{ 
import bsh.Node; //you need this as well

public String perform() throws ParseException, IOException {
    FileInputStream sourceStream = new FileInputStream(sourseFilePath);
    Parser p = new Parser(sourceStream);

    while (!p.Line()) {
        recursive_print(p.popNode(), "");
    }

    sourceStream.close();
    return "";
}

public void recursive_print(Node node, String prefix)
{
    System.out.println(prefix + node.getText());
    for (int i=0; i<node.jjtGetNumChildren(); i++)
        recursive_print(node.getChild(i), prefix+"  ");
}