代码之家  ›  专栏  ›  技术社区  ›  phibao37

如何在CDT ASTParser中将IASTComment链接到IASTDeclaration

  •  3
  • phibao37  · 技术社区  · 9 年前

    我正在使用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,我可以解析代码中的函数定义列表,但我不知道如何在定义代码上方“链接”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());
        }
    

    这个 visit(IASTComment comment) ASTVisitor类中的已弃用,并且 IASTTranslationUnit.getComments() 方法只返回整个源文件中的注释列表,这里没有结构。
    那么,如何获取链接到函数定义的IASTComment对象(如果有)?

    1 回复  |  直到 9 年前
        1
  •  5
  •   lolung    8 年前

    您可以使用 ASTCommenter.getCommentedNodeMap(IASTTranslationUnit) 在包装中 org.eclipse.cdt.internal.core.dom.rewrite.commenthandler . 该方法返回 NodeCommentMap 其将注释映射到AST中的节点。有三种类型的注释可以分配给节点。在下面的示例中,declaration方法是节点:

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

    NodeCommentMap.getOffsetIncludingComments(IASTNode) 返回节点的偏移量,包括其指定的前导注释。 NodeCommentMap.getEndOffsetIncludingComments(IASTNode) 返回节点的结束偏移量,包括其指定的尾随注释。 指定的独立评论必须由您自己处理。您可以使用 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

    注意:大多数包/类都是内部的。