4

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

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

4

5 回答 5

5

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

Java 前端是编译器语言前端(C、C++、C#、COBOL、JavaScript 等)家族的成员,所有这些都受DMS 软件再造工具包支持。DMS 旨在处理语言以进行转换,因此可以捕获注释、布局和格式,以尽可能地重新生成保留原始布局的代码。

编辑 2012 年 3 月 29 日:(与使用 ANTLR 执行此操作的答案相反)

要获得对 DMS 中 AST 节点的评论,请调用 DMS(类似lisp)函数

  (AST:GetComments <node>)

它提供对与 AST 节点关联的评论数组的访问。可以查询此数组的长度(可能为空),或者对于每个数组元素,查询以下任何属性:(AST:Get... FileIndex, Line, Column, EndLine, EndColumn, String (exact Unicode comment)内容)。

于 2010-06-11T03:28:05.413 回答
4

通过CompilationUnitgetCommentList方法获得的评论不会有评论体。在和 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) {

    }
}

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

于 2012-03-27T07:21:18.307 回答
1

只是为了记录。现在有了 Java 8,您就有了一个完整的界面,可以在这里使用注释和文档详细信息。

于 2015-04-14T11:44:02.353 回答
0

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

于 2010-06-11T03:00:59.587 回答
0

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

于 2012-01-04T12:22:40.550 回答