使用clang Libtooling API打印完全限定类型的参数(ParmVarDecl)或字段(FieldDecl)的步骤如下:
#include "clang/AST/AST.h"
#include "clang/ASTMatchers/ASTMatchers.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/Tooling/CommonOptionsParser.h"
#include "clang/Tooling/Tooling.h"
#include "llvm/Support/CommandLine.h"
class MyASTConsumer : public clang::ASTConsumer {
public:
virtual bool HandleTopLevelDecl(clang::DeclGroupRef DG) {
for (clang::DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) {
clang::Decl *D = *I;
if (clang::ParmVarDecl *PVD = llvm::dyn_cast<clang::ParmVarDecl>(D)) {
// 处理参数(ParmVarDecl)
llvm::outs() << "参数类型: " << PVD->getType().getAsString() << "\n";
} else if (clang::FieldDecl *FD = llvm::dyn_cast<clang::FieldDecl>(D)) {
// 处理字段(FieldDecl)
llvm::outs() << "字段类型: " << FD->getType().getAsString() << "\n";
}
}
return true;
}
};
class MyASTMatcher : public clang::ast_matchers::MatchFinder::MatchCallback {
public:
virtual void run(const clang::ast_matchers::MatchFinder::MatchResult &Result) {
if (const clang::ParmVarDecl *PVD = Result.Nodes.getNodeAs<clang::ParmVarDecl>("parmVarDecl")) {
// 匹配到参数(ParmVarDecl)
llvm::outs() << "参数类型: " << PVD->getType().getAsString() << "\n";
} else if (const clang::FieldDecl *FD = Result.Nodes.getNodeAs<clang::FieldDecl>("fieldDecl")) {
// 匹配到字段(FieldDecl)
llvm::outs() << "字段类型: " << FD->getType().getAsString() << "\n";
}
}
};
int main(int argc, const char **argv) {
clang::tooling::CommonOptionsParser OptionsParser(argc, argv);
clang::tooling::ClangTool Tool(OptionsParser.getCompilations(), OptionsParser.getSourcePathList());
MyASTConsumer Consumer;
Tool.setASTConsumer(&Consumer);
MyASTMatcher Matcher;
clang::ast_matchers::MatchFinder Finder;
Finder.addMatcher(clang::ast_matchers::parmVarDecl().bind("parmVarDecl"), &Matcher);
Finder.addMatcher(clang::ast_matchers::fieldDecl().bind("fieldDecl"), &Matcher);
return Tool.run(clang::tooling::newFrontendActionFactory(&Finder).get());
}
这是一个使用clang Libtooling API打印完全限定类型的参数(ParmVarDecl)或字段(FieldDecl)的示例代码。你可以根据实际需求进行修改和扩展。
没有搜到相关的沙龙
领取专属 10元无门槛券
手把手带您无忧上云