2

私は 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をファイルに出力するのを手伝ってくれるなら、それは大きな助けになるでしょう.

前もって感謝します。

4

1 に答える 1

3

AST を JSON に変換する例を次に示します。ファイルを変更して、JSONStyleASTPrinter.javaJSON などの代わりに XML を生成できます。

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());
    }
}
于 2015-09-09T08:22:38.740 に答える