我想用clang AST解析自定义标签。以下是我的编译单元输入的简单说明。
#include <stdio.h>
int main() {
// my-tags tag_A, tag_B
printf("helloworld");
return 0;
}
如何在my-tags
之后获取这些标签?
在阅读了clang用户手册后,我意识到-Wdocumentation
、-fparse-all-comments
甚至-fcomment-block-commands
都可以满足我的要求。然而,当我在compile_commands.json
中添加其中一个标志时,ASTContext.Comments.empty()
仍然输出True
。我在下面附上我的compile_commands.json
和我的clang AST前端代码以供参考。
// compile_commands.json
[
{
"directory": "/home/my/project/target/directory",
"arguments": ["/usr/local/bin/clang", "-c", "-std=c++14", "-Qunused-arguments", "-m64", "-fparse-all-comments", "-I/usr/include", "-I/usr/local/lib/clang/10.0.0/include", "-o", "build/.objs/input/linux/x86_64/release/target/target.cpp.o", "target/target.cpp"],
"file": "target/target.cpp"
}
]
// CommentParser.cpp
class MyPrinter : public MatchFinder::MatchCallback {
public:
virtual void run(const MatchFinder::MatchResult &Result) {
ASTContext *Context = Result.Context;
SourceManager& sm = Context->getSourceManager();
if (!Context->Comments.empty())
llvm::outs() << "There is no parsed commentn";
}
};
int main(int argc, const char **argv) {
// CommonOptionsParser OptionsParser(argc, argv, MyToolCategory);
std::string err;
std::unique_ptr<CompilationDatabase> cd = CompilationDatabase::autoDetectFromSource("/home/my/project/target/directory/compile_commands.json", err);
ClangTool Tool(*cd, cd->getAllFiles());
MyPrinter Printer;
MatchFinder Finder;
StatementMatcher functionMatcher =
callExpr(callee(functionDecl(hasName("pthread_mutex_lock")))).bind("functions");
Finder.addMatcher(functionMatcher, &Printer);
return Tool.run(newFrontendActionFactory(&Finder).get());
}
-fparse-all-comments
适用于我。
也许你可以试着不使用LibASTMatcher。
代码示例:
virtual void HandleTranslationUnit(clang::ASTContext& context) {
auto comments = context.Comments.getCommentsInFile(
context.getSourceManager().getMainFileID());
llvm::outs() << context.Comments.empty() << "n";
...
for (auto it = comments->begin(); it != comments->end(); it++) {
clang::RawComment* comment = it->second;
std::string source = comment->getFormattedText(context.getSourceManager(),
context.getDiagnostics());
llvm::outs() << source << "n";
}
}
参考:https://clang.llvm.org/docs/RAVFrontendAction.html