如何在libclangc++中提取注释并使用RecursiveASTVisitor匹配声明

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

本文关键字:RecursiveASTVisitor 声明 注释 libclangc++ 提取      更新时间:2023-10-16

我正在编写一个实用程序,该实用程序应该解析c++(和C)头文件,提取结构体,枚举,字段等,并根据提取的信息生成其他语言的代码。我决定使用libclang。

我正在使用RecursiveASTVisitor,似乎我能够提取我需要的所有信息,除了注释。

我想有出现在每个声明(字段,结构,类,枚举)的正上方的注释读取,并在我生成其他语言的代码时添加其文本。

问题是我看到的所有使用注释的示例都使用CxCursor和C接口clang,我不知道如何在我的上下文中获得CxCursor

那么-我如何提取注释,而仍然使用RecursiveASTVisitor ?

经过进一步的挖掘,我发现了这个:

对于任何相关的访问Decl (VisitXXXDecl),我可以这样做:

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
    }
    // ...
}

请注意,这识别(据我所见…)注释,这些注释位于代码中当前声明的上方(或相邻)行,并且是以下格式之一:

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

例如:

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

raw将是:

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

brief将是:

A field with a long long comment A two-liner

不管怎样,都能满足我的需要。

上面的答案是完美的。但是要使API getRawCommentForDeclNoCache// or /*一样返回正常的注释,您需要在调用clang时提供选项"-fparse-all-comments"。因为clang默认只解析氧样式的注释

相关文章:
  • 没有找到相关文章