如何 link IASTComment 到 CDT ASTParser 中的 IASTDeclaration

How to link a IASTComment to a IASTDeclaration in CDT ASTParser

我正在使用 CDT ASTParser 来解析 C/C++ 源文件的一些内容。示例:

//Docs for function min
int min(int a[], int n) {
    //Comment here
}

int min1(){}

/*
Docs for function min2
*/
int min2(){}

通过使用ASTVisitor,我可以解析代码中的函数定义列表,但是我不知道如何"link"定义代码上面的IASTComment:

void handle(IASTTranslationUnit unit){
        unit.accept(new ASTVisitor() {
            { shouldVisitDeclarations = true; }

            @Override
            public int visit(IASTDeclaration declaration) {

                if (declaration instanceof IASTFunctionDefinition) {
                    IASTFunctionDefinition fnDefine = 
                            (IASTFunctionDefinition) declaration;
                    IASTFunctionDeclarator fnDeclare = fnDefine.getDeclarator();

                    System.out.printf("Function: %s, type: %s, comment: %s\n",
                            fnDeclare.getName().getRawSignature(),
                            fnDefine.getDeclSpecifier().getRawSignature(),
                            "Somehow get the comment above function define???"
                            );
                }
                return PROCESS_SKIP;
            }

            @Override
            public int visit(IASTComment comment) {
                System.out.println("Comment: " + comment.getRawSignature());
                return PROCESS_CONTINUE;
            }

        });

        for (IASTComment cmt: unit.getComments())
            System.out.println("Comment: " + cmt.getRawSignature());
    }

ASTVisitor class 中的 visit(IASTComment comment) 已弃用,IASTTranslationUnit.getComments() 方法只是 return 整个源文件中的注释列表,此处没有结构。
那么,如何将 link 的 IASTComment 对象获取到函数定义(如果有)?

您可以使用包 org.eclipse.cdt.internal.core.dom.rewrite.commenthandler 中的 ASTCommenter.getCommentedNodeMap(IASTTranslationUnit)。 方法 returns a NodeCommentMap 将注释映射到 AST 中的节点。可以将三种类型的评论分配给节点。在下面的示例中,方法声明是节点:

//this is a leading comment
void method() //this is a trailing comment
//this is a freestanding comment
{
...

NodeCommentMap.getOffsetIncludingComments(IASTNode)returns 节点的偏移量,包括其分配的前导注释。 NodeCommentMap.getEndOffsetIncludingComments(IASTNode) returns 节点的结束偏移量,包括其分配的尾随注释。 分配的独立评论必须由您自己处理。您可以使用 NodeCommentMap.getFreestandingCommentsForNode(IASTNode) 获取独立评论。至少我在 cdt 包中找不到任何默认方法。

如果您想了解更多信息,建议阅读以下 类:

中的文档
  • org.eclipse.cdt.internal.core.dom.rewrite.commenthandler.ASTCommenter
  • org.eclipse.cdt.core.parser.tests.rewrite.comenthandler.CommentHandlingTest
  • org.eclipse.cdt.internal.core.dom.rewrite.commenthandler.NodeCommenter

注意:其中大部分 packages/classes 是内部的。