问题描述
我正在编写一个实用程序,该实用程序应该解析C ++(和C)头文件,提取结构,枚举,字段等,并根据提取的信息以其他语言生成代码.我决定为此使用libclang.
I am writing a utility which is supposed to parse C++ (and C) header files, extract the structs, enums, fields etc. and generate code in other languages based on the extracted information. I decided to use libclang for this.
我正在使用RecursiveASTVisitor
,看来我能够提取我需要的所有信息,但注释除外.
I'm using a RecursiveASTVisitor
and it seems I'm able to extract all the information I need, except for comments.
我想读取每条声明(字段,结构,类,枚举)上方的注释,并在生成其他语言的代码时添加其文本.
I want to have the comment which appears right above every declaration (field, struct, class, enum) read, and add its text when I generate the code in other languages.
问题是我看到的所有使用注释的示例都使用CxCursor
和clang的C接口,而我不知道如何在上下文中获取CxCursor
.
The problem is that all the samples I saw which use comments use CxCursor
and the C interface for clang, and I have no idea how to get the CxCursor
in my context.
那么-我如何在仍使用RecursiveASTVisitor
的情况下提取注释?
So - how can I extract comments while still using RecursiveASTVisitor
?
推荐答案
通过进一步挖掘,我发现了这一点:
With some more digging up, I found this:
对于任何相关的访问的Decl(VisitXXXDecl
),我可以这样做:
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
/// 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
无论哪种方式,都足以满足我的需求.
Either way, it's good enough for my needs.
这篇关于如何使用libclang c ++中的RecursiveASTVisitor提取注释并与声明匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!