I went through this tutorial http://clang.llvm.org/docs/LibASTMatchersTutorial.html and found some pretty helpful stuff there, this is what I came up with:
I had to rename my file from IFoo.h
to IFoo.hpp
to be detected as Cxx and not C code.
I had to call my program with -x c++
to have my IFoo.h
file being recognized as C++ code rather than C code (clang interprets *.h
files as C by default:
~/Development/llvm-build/bin/mytool ~/IFoo.h -- -x c++
This is my code to dump all virtual functions from the provided class:
// Declares clang::SyntaxOnlyAction.
#include "clang/Frontend/FrontendActions.h"
#include "clang/Tooling/CommonOptionsParser.h"
#include "clang/Tooling/Tooling.h"
#include "clang/ASTMatchers/ASTMatchers.h"
// Declares llvm::cl::extrahelp.
#include "llvm/Support/CommandLine.h"
#include "clang/ASTMatchers/ASTMatchers.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include <cstdio>
using namespace clang;
using namespace clang::ast_matchers;
using namespace clang::tooling;
using namespace llvm;
DeclarationMatcher methodMatcher = methodDecl(isVirtual()).bind("methods");
class MethodPrinter : public MatchFinder::MatchCallback {
public :
virtual void run(const MatchFinder::MatchResult &Result) {
if (const CXXMethodDecl *md = Result.Nodes.getNodeAs<clang::CXXMethodDecl>("methods")) {
md->dump();
}
}
};
// CommonOptionsParser declares HelpMessage with a description of the common
// command-line options related to the compilation database and input files.
// It's nice to have this help message in all tools.
static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage);
// A help message for this specific tool can be added afterwards.
static cl::extrahelp MoreHelp("
More help text...");
int main(int argc, const char **argv) {
cl::OptionCategory cat("myname", "mydescription");
CommonOptionsParser optionsParser(argc, argv, cat, 0);
ClangTool tool(optionsParser.getCompilations(), optionsParser.getSourcePathList());
MethodPrinter printer;
MatchFinder finder;
finder.addMatcher(methodMatcher, &printer);
return tool.run(newFrontendActionFactory(&finder));
}
The output looks like this, when passed the IFoo.h
file:
CXXDestructorDecl 0x1709c30 <~/IFoo.h:5:3, col:20> ~IFoo 'void (void)' virtual
`-CompoundStmt 0x1758128 <col:19, col:20>
CXXMethodDecl 0x1757e60 <~/IFoo.h:6:3, col:24> bar 'void (void)' virtual pure
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…