Asa*_*saf 12 c++ comments libclang
我正在编写一个实用程序,它应该解析C++(和C)头文件,提取结构,枚举,字段等,并根据提取的信息生成其他语言的代码.我决定使用libclang.
我正在使用a RecursiveASTVisitor,似乎我能够提取我需要的所有信息,除了评论.
我希望在每个声明(字段,结构,类,枚举)的上方出现注释,并在我用其他语言生成代码时添加其文本.
问题是我看到的所有使用注释的样本CxCursor和clang的C接口,我不知道如何CxCursor在我的上下文中获取.
那么 - 如何在仍然使用时提取注释RecursiveASTVisitor?
Asa*_*saf 13
随着更多的挖掘,我发现了这个:
对于任何相关的访问过的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只解析Doxygen样式注释.
| 归档时间: | 
 | 
| 查看次数: | 2106 次 | 
| 最近记录: |