ANTLR:通过stringtemplate将修改后的AST转换为java源代码

时间:2013-12-03 06:39:59

标签: java antlr pretty-print abstract-syntax-tree stringtemplate

我使用来自ANTLR wiki的语法Java.g为Java源文件生成词法分析器和解析器。然后使用以下代码生成abstract syntax tree (AST)

    ANTLRInputStream input = new ANTLRInputStream(new FileInputStream(fileName));
    JavaLexer lexer = new JavaLexer(input);     // create lexer
    // create a buffer of tokens pulled from the lexer
    CommonTokenStream tokens = new CommonTokenStream(lexer);
    JavaParser parser = new JavaParser(tokens); // create parser
    JavaParser.javaSource_return r = parser.javaSource();   // parse rule 'javaSource'
    /*RuleReturnScope result = parser.compilationUnit();
    CommonTree t = (CommonTree) result.getTree();*/
    // WALK TREE
    // get the tree from the return structure for rule prog
    CommonTree t = (CommonTree)r.getTree();

然后修改AST。例如,替换"文件文件=新文件(filepath,fileType);"至 " S3Object _file = new S3Object(_fileName);"通过修改AST节点。在此之后,我想将此AST转换为java源代码。我修改JavaTreeParser.g并编写一个stringtemplate并使用以下方法获取java源代码:

    FileReader groupFileR = new FileReader("src/com/googlecode/zcg/templates/JavaTemplate.stg");
    StringTemplateGroup templates = new StringTemplateGroup(groupFileR);
    groupFileR.close();
    // create a stream of tree nodes from AST built by parser
    CommonTreeNodeStream nodes = new CommonTreeNodeStream(t);
    // tell it where it can find the token objects
    nodes.setTokenStream(tokens);
    JavaTreeParser walker = new JavaTreeParser(nodes); // create the tree Walker
    walker.setTemplateLib(templates); // where to find templates
    // invoke rule prog, passing in information from parser
    JavaTreeParser.javaSource_return r2 = walker.javaSource();

    // EMIT BYTE CODES
    // get template from return values struct
    StringTemplate output = (StringTemplate)r2.getTemplate(); 
    System.out.println(output.toString()); // render full template

如果我没有修改AST,它将正确获取java源代码,但在我修改AST后,它没有获得正确的java源代码(AST被正确修改)。例如,如果我输入以下源代码并转换为AST,则修改"文件文件=新文件(filepath,fileType);" to" S3Object _file = new S3Object(_fileName);":

public void methodname(String address){
    String filepath = "file";
    int fileType = 3;       
    File file = new File(filepath, fileType);
}

结果将如下:

public void methodname( String address)
  { 
     String filepath="file";
     int fileType=3;
     methodname (Stringaddress){Stringfilepath;//it's not  what I wanted
  }

我做错了吗?我有更合适的方法来解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

遗憾的是,我不建议通过重写抽象语法树来完成源代码翻译;尝试使用解析树。如果我记得ANTLR 3也可以轻松生成。 叔