我想用 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 comment\n";
}
};
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());
}