How to extract comments and match to declaration with RecursiveASTVisitor in libclang c++?

老子叫甜甜 提交于 2019-12-03 06:47:10

With some more digging up, I found this:

For any relevant visited Decl (VisitXXXDecl), I can do this:

virtual bool VisitDecl(Decl* d)
{
    ASTContext& ctx = d->getASTContext();
    SourceManager& sm = ctx.getSourceManager();

    const RawComment* rc = d->getASTContext().getRawCommentForDeclNoCache(d);
    if (rc)
    {
        //Found comment!
        SourceRange range = rc->getSourceRange();

        PresumedLoc startPos = sm.getPresumedLoc(range.getBegin());
        PresumedLoc endPos = sm.getPresumedLoc(range.getEnd());

        std::string raw = rc->getRawText(sm);
        std::string brief = rc->getBriefText(ctx);

        // ... Do something with positions or comments
    }

    // ...
}

Note that this identifies (as far as I could see...) comments which are in the line(s) above (and adjacent!) to the current declaration in the code, and which are in one of the following formats:

  • /// Comment
  • /** Comment */
  • //! Comment

For example, in the following case:

/// A field with a long long comment
/// A two-liner
long long LongLongData;

raw will be:

/// A field with a long long comment
    /// A two-liner

And brief will be:

A field with a long long comment A two-liner

Either way, it's good enough for my needs.

The above answer is perfect. But to make the API getRawCommentForDeclNoCache return normal comments like // or /* you need to provide option "-fparse-all-comments" while invoking clang. Because by default clang parses only Doxygen style comments.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!