簡體   English   中英

如何從java編譯器樹api生成注釋生成的ast?

[英]How to access comments from the java compiler tree api generated ast?

我已經使用java編譯器樹api為java源文件生成ast。 但是,我無法訪問源文件中的注釋。

到目前為止,我一直無法找到從源文件中提取注釋的方法..有沒有辦法使用編譯器api或其他工具?

我們的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>)

它提供對與AST節點相關的注釋數組的訪問。 可以查詢此數組的長度(可能為null),或者對於每個數組元素,請求以下任何屬性:(AST:Get ... FileIndex,Line,Column,EndLine,EndColumn,String(確切的Unicode注釋)內容)。

通過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) {

    }
}

編輯:將源分離移出訪問者。

僅供記錄。 現在使用Java 8,您可以在此處使用完整的界面來閱讀注釋和文檔詳細信息。

您可能會使用其他工具,例如ANTLR的Java語法。 javac沒有用於評論,並且很可能完全丟棄它們。 構建IDE等工具的解析器更有可能在其AST中保留注釋。

通過使用getsourceposition()和一些字符串操作(不需要正則表達式)來解決問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM