Aboelnour Aboelnour - 21 days ago 6
Java Question

Generating an Abstract Syntax Tree for java source code using ANTLR

How Can I Generate an AST from java src code Using ANTLR?

any help?

Answer

OK, here is the steps:

  1. go to ANTLR Site and download the latest version now it's 3.4
  2. Download the Java.g and the JavaTreeParser.g files from here.
  3. Run the following commands:

    java -jar antlrTool Java.g
    java -jar antlrTool JavaTreeParser.g
    
  4. 5 files will be generated:

    1. Java.tokens
    2. JavaLexer.java
    3. JavaParser.java
    4. JavaTreeParser.g
    5. JavaTreeParser.tokens

use this java code to generate the Abstract Syntax Tree and to print it:

        String input = "public class HelloWord {"+
                   "public void print(String r){" +
                   "for(int i = 0;true;i+=2)" +
                   "System.out.println(r);" +
                   "}" +
                   "}";

    CharStream cs = new ANTLRStringStream(input);
    JavaLexer jl = new JavaLexer(cs);

    CommonTokenStream tokens = new CommonTokenStream();
    tokens.setTokenSource(jl);
    JavaParser jp = new JavaParser(tokens);
    RuleReturnScope result = jp.compilationUnit();
    CommonTree t = (CommonTree) result.getTree();

    CommonTreeNodeStream nodes = new CommonTreeNodeStream(t);

    nodes.setTokenStream(tokens);

    JavaTreeParser walker = new JavaTreeParser(nodes);

    System.out.println("\nWalk tree:\n");

    printTree(t,0);


    System.out.println(tokens.toString());

    }

public static void printTree(CommonTree t, int indent) {
    if ( t != null ) {
        StringBuffer sb = new StringBuffer(indent);
        for ( int i = 0; i < indent; i++ )
            sb = sb.append("   ");
        for ( int i = 0; i < t.getChildCount(); i++ ) {
            System.out.println(sb.toString() + t.getChild(i).toString());
            printTree((CommonTree)t.getChild(i), indent+1);
        }
    }
}