从JAVA中提取AST并将AST打印到文件中

时间:2015-03-10 11:11:53

标签: java debugging abstract-syntax-tree extraction compilationunit

我是Java编程语言的初学者。我想从java源代码中提取AST并将AST打印到文件或标准输出。

我按照本教程学习如何使用AST。 http://www.programcreek.com/2011/01/a-complete-standalone-example-of-astparser/

所以根据我到目前为止的代码如下。

import java.util.HashSet;
import java.util.Set;

import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.ASTVisitor;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.SimpleName;
import org.eclipse.jdt.core.dom.VariableDeclarationFragment;

public class Test {
    public static void main(String args[]){
        ASTParser parser = ASTParser.newParser(AST.JLS3);
        parser.setSource("public class A { int i = 9;  \n int j; \n ArrayList<Integer> al = new ArrayList<Integer>();j=1000; }".toCharArray());
        //parser.setSource("/*abc*/".toCharArray());
        parser.setKind(ASTParser.K_COMPILATION_UNIT);
        //ASTNode node = parser.createAST(null);


        final CompilationUnit cu = (CompilationUnit) parser.createAST(null);

    }
}

我尝试使用以下代码段将其打印到标准输出,但它没有给出我预期的结果,

System.out.println(cu.getAST().toString());

如果有人可以帮我将AST打印到文件中,那将是一个很大的帮助。

提前致谢。

1 个答案:

答案 0 :(得分:3)

这是an example of transforming the AST to JSON。您可以修改JSONStyleASTPrinter.java文件以生成XML而不是JSON等。

基于How To Train the JDT Dragon combined.pdf的示例:

private void print(ASTNode node) {
    List properties = node.structuralPropertiesForType();
    for (Iterator iterator = properties.iterator(); iterator.hasNext();) {
        Object descriptor = iterator.next();
        if (descriptor instanceof SimplePropertyDescriptor) {
            SimplePropertyDescriptor simple = (SimplePropertyDescriptor) descriptor;
            Object value = node.getStructuralProperty(simple);
            System.out.println(simple.getId() + " (" + value.toString() + ")");
        } else if (descriptor instanceof ChildPropertyDescriptor) {
            ChildPropertyDescriptor child = (ChildPropertyDescriptor) descriptor;
            ASTNode childNode = (ASTNode) node.getStructuralProperty(child);
            if (childNode != null) {
                System.out.println("Child (" + child.getId() + ") {");
                print(childNode);
                System.out.println("}");
            }
        } else {
            ChildListPropertyDescriptor list = (ChildListPropertyDescriptor) descriptor;
            System.out.println("List (" + list.getId() + "){");
            print((List) node.getStructuralProperty(list));
            System.out.println("}");
        }
    }
}

private void print(List nodes) {
    for (Iterator iterator = nodes.iterator(); iterator.hasNext();) {
        print((ASTNode) iterator.next());
    }
}