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

Cod*_*eak 4 java compiler-construction abstract-syntax-tree

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

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

Ira*_*ter 5

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

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

编辑3/29/2012 :(与使用ANTLR执行此操作的答案形成鲜明对比)

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

  (AST:GetComments <node>)
Run Code Online (Sandbox Code Playgroud)

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


Unn*_*ris 5

通过CompilationUnitgetCommentList方法获取的评论不会有评论正文。此外,在 AST 访问期间,不会访问评论。为了访问评论,我们为评论列表中的每个评论调用方法。accept

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

    comment.accept(new CommentVisitor(compilationUnit, classSource.split("\n")));
}
Run Code Online (Sandbox Code Playgroud)

可以使用一些简单的逻辑来获取评论的正文。在下面用于注释的 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) {

    }
}
Run Code Online (Sandbox Code Playgroud)

编辑:将源的分离移出访问者。