如何从java编译器树api生成注释生成的ast?

时间:2010-06-11 01:55:28

标签: java compiler-construction abstract-syntax-tree

我使用java编译器树api为java源文件生成ast。但是,我无法访问源文件中的注释。

到目前为止,我一直无法找到从源文件中提取注释的方法..有没有办法使用编译器api或其他工具?

5 个答案:

答案 0 :(得分:5)

我们的SD Java Front End是一个构建AST(以及可选的符号表)的Java解析器。它直接在树节点上捕获注释。

Java前端是一系列编译器语言前端(C,C ++,C#,COBOL,JavaScript,......)的成员,所有这些都由DMS Software Reengineering Toolkit支持。 DMS旨在处理语言以进行转换,因此可以捕获注释,布局和格式,以便尽可能地保留原始布局的代码重新生成。

EDIT 3/29/2012 :(与使用ANTLR执行此操作的回答相比)

要在DMS中的AST节点上发表评论,可以调用DMS(类似于lisp的)函数

  (AST:GetComments <node>)

,提供对与AST节点关联的注释数组的访问。可以查询此数组的长度(可能为null),或者对于每个数组元素,请求以下任何属性:(AST:Get ... FileIndex,Line,Column,EndLine,EndColumn,String(确切的Unicode注释)含量)。

答案 1 :(得分:4)

通过 CompilationUnit getCommentList方法获得的评论不会有评论正文。在AST访问期间也不会访问评论。为了访问评论,我们为评论列表中的每条评论调用accept方法。

for (Comment comment : (List<Comment>) compilationUnit.getCommentList()) {

    comment.accept(new CommentVisitor(compilationUnit, classSource.split("\n")));
}

可以使用一些简单的逻辑获得注释的主体。在下面的AST Visitor中,我们需要在初始化期间指定Complied类单元和类的源代码。

import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.ASTVisitor;
import org.eclipse.jdt.core.dom.BlockComment;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.LineComment;

public class CommentVisitor extends ASTVisitor {

    CompilationUnit compilationUnit;

    private String[] source;

    public CommentVisitor(CompilationUnit compilationUnit, String[] source) {

        super();
        this.compilationUnit = compilationUnit;
        this.source = source;
    }

    public boolean visit(LineComment node) {

        int startLineNumber = compilationUnit.getLineNumber(node.getStartPosition()) - 1;
        String lineComment = source[startLineNumber].trim();

        System.out.println(lineComment);

        return true;
    }

    public boolean visit(BlockComment node) {

        int startLineNumber = compilationUnit.getLineNumber(node.getStartPosition()) - 1;
        int endLineNumber = compilationUnit.getLineNumber(node.getStartPosition() + node.getLength()) - 1;

        StringBuffer blockComment = new StringBuffer();

        for (int lineCount = startLineNumber ; lineCount<= endLineNumber; lineCount++) {

            String blockCommentLine = source[lineCount].trim();
            blockComment.append(blockCommentLine);
            if (lineCount != endLineNumber) {
                blockComment.append("\n");
            }
        }

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

        return true;
    }

    public void preVisit(ASTNode node) {

    }
}

编辑:移动了来自访问者的源的分割。

答案 2 :(得分:1)

仅供记录。现在使用Java 8,您可以使用完整的界面来处理注释和文档详细信息here

答案 3 :(得分:0)

您可能会使用其他工具,例如ANTLR的Java语法。 javac对评论没有用处,可能会完全丢弃它们。构建IDE等工具的解析器更有可能在其AST中保留注释。

答案 4 :(得分:0)

通过使用getsourceposition()和一些字符串操作(不需要正则表达式)来管理解决问题