1 ==========================================================
2 How to write RecursiveASTVisitor based ASTFrontendActions.
3 ==========================================================
8 In this tutorial you will learn how to create a FrontendAction that uses
9 a RecursiveASTVisitor to find CXXRecordDecl AST nodes with a specified
12 Creating a FrontendAction
13 =========================
15 When writing a clang based tool like a Clang Plugin or a standalone tool
16 based on LibTooling, the common entry point is the FrontendAction.
17 FrontendAction is an interface that allows execution of user specific
18 actions as part of the compilation. To run tools over the AST clang
19 provides the convenience interface ASTFrontendAction, which takes care
20 of executing the action. The only part left is to implement the
21 CreateASTConsumer method that returns an ASTConsumer per translation
26 class FindNamedClassAction : public clang::ASTFrontendAction {
28 virtual std::unique_ptr<clang::ASTConsumer> CreateASTConsumer(
29 clang::CompilerInstance &Compiler, llvm::StringRef InFile) {
30 return std::unique_ptr<clang::ASTConsumer>(
31 new FindNamedClassConsumer);
35 Creating an ASTConsumer
36 =======================
38 ASTConsumer is an interface used to write generic actions on an AST,
39 regardless of how the AST was produced. ASTConsumer provides many
40 different entry points, but for our use case the only one needed is
41 HandleTranslationUnit, which is called with the ASTContext for the
46 class FindNamedClassConsumer : public clang::ASTConsumer {
48 virtual void HandleTranslationUnit(clang::ASTContext &Context) {
49 // Traversing the translation unit decl via a RecursiveASTVisitor
50 // will visit all nodes in the AST.
51 Visitor.TraverseDecl(Context.getTranslationUnitDecl());
54 // A RecursiveASTVisitor implementation.
55 FindNamedClassVisitor Visitor;
58 Using the RecursiveASTVisitor
59 =============================
61 Now that everything is hooked up, the next step is to implement a
62 RecursiveASTVisitor to extract the relevant information from the AST.
64 The RecursiveASTVisitor provides hooks of the form bool
65 VisitNodeType(NodeType \*) for most AST nodes; the exception are TypeLoc
66 nodes, which are passed by-value. We only need to implement the methods
67 for the relevant node types.
69 Let's start by writing a RecursiveASTVisitor that visits all
74 class FindNamedClassVisitor
75 : public RecursiveASTVisitor<FindNamedClassVisitor> {
77 bool VisitCXXRecordDecl(CXXRecordDecl *Declaration) {
78 // For debugging, dumping the AST nodes will show which nodes are already
82 // The return value indicates whether we want the visitation to proceed.
83 // Return false to stop the traversal of the AST.
88 In the methods of our RecursiveASTVisitor we can now use the full power
89 of the Clang AST to drill through to the parts that are interesting for
90 us. For example, to find all class declaration with a certain name, we
91 can check for a specific qualified name:
95 bool VisitCXXRecordDecl(CXXRecordDecl *Declaration) {
96 if (Declaration->getQualifiedNameAsString() == "n::m::C")
101 Accessing the SourceManager and ASTContext
102 ==========================================
104 Some of the information about the AST, like source locations and global
105 identifier information, are not stored in the AST nodes themselves, but
106 in the ASTContext and its associated source manager. To retrieve them we
107 need to hand the ASTContext into our RecursiveASTVisitor implementation.
109 The ASTContext is available from the CompilerInstance during the call to
110 CreateASTConsumer. We can thus extract it there and hand it into our
111 freshly created FindNamedClassConsumer:
115 virtual std::unique_ptr<clang::ASTConsumer> CreateASTConsumer(
116 clang::CompilerInstance &Compiler, llvm::StringRef InFile) {
117 return std::unique_ptr<clang::ASTConsumer>(
118 new FindNamedClassConsumer(&Compiler.getASTContext()));
121 Now that the ASTContext is available in the RecursiveASTVisitor, we can
122 do more interesting things with AST nodes, like looking up their source
127 bool VisitCXXRecordDecl(CXXRecordDecl *Declaration) {
128 if (Declaration->getQualifiedNameAsString() == "n::m::C") {
129 // getFullLoc uses the ASTContext's SourceManager to resolve the source
130 // location and break it up into its line and column parts.
131 FullSourceLoc FullLocation = Context->getFullLoc(Declaration->getLocStart());
132 if (FullLocation.isValid())
133 llvm::outs() << "Found declaration at "
134 << FullLocation.getSpellingLineNumber() << ":"
135 << FullLocation.getSpellingColumnNumber() << "\n";
140 Putting it all together
141 =======================
143 Now we can combine all of the above into a small example program:
147 #include "clang/AST/ASTConsumer.h"
148 #include "clang/AST/RecursiveASTVisitor.h"
149 #include "clang/Frontend/CompilerInstance.h"
150 #include "clang/Frontend/FrontendAction.h"
151 #include "clang/Tooling/Tooling.h"
153 using namespace clang;
155 class FindNamedClassVisitor
156 : public RecursiveASTVisitor<FindNamedClassVisitor> {
158 explicit FindNamedClassVisitor(ASTContext *Context)
159 : Context(Context) {}
161 bool VisitCXXRecordDecl(CXXRecordDecl *Declaration) {
162 if (Declaration->getQualifiedNameAsString() == "n::m::C") {
163 FullSourceLoc FullLocation = Context->getFullLoc(Declaration->getLocStart());
164 if (FullLocation.isValid())
165 llvm::outs() << "Found declaration at "
166 << FullLocation.getSpellingLineNumber() << ":"
167 << FullLocation.getSpellingColumnNumber() << "\n";
176 class FindNamedClassConsumer : public clang::ASTConsumer {
178 explicit FindNamedClassConsumer(ASTContext *Context)
179 : Visitor(Context) {}
181 virtual void HandleTranslationUnit(clang::ASTContext &Context) {
182 Visitor.TraverseDecl(Context.getTranslationUnitDecl());
185 FindNamedClassVisitor Visitor;
188 class FindNamedClassAction : public clang::ASTFrontendAction {
190 virtual std::unique_ptr<clang::ASTConsumer> CreateASTConsumer(
191 clang::CompilerInstance &Compiler, llvm::StringRef InFile) {
192 return std::unique_ptr<clang::ASTConsumer>(
193 new FindNamedClassConsumer(&Compiler.getASTContext()));
197 int main(int argc, char **argv) {
199 clang::tooling::runToolOnCode(new FindNamedClassAction, argv[1]);
203 We store this into a file called FindClassDecls.cpp and create the
204 following CMakeLists.txt to link it:
208 add_clang_executable(find-class-decls FindClassDecls.cpp)
210 target_link_libraries(find-class-decls clangTooling)
212 When running this tool over a small code snippet it will output all
213 declarations of a class n::m::C it found:
217 $ ./bin/find-class-decls "namespace n { namespace m { class C {}; } }"
218 Found declaration at 1:29