RAVFrontendAction.rst 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. ==========================================================
  2. How to write RecursiveASTVisitor based ASTFrontendActions.
  3. ==========================================================
  4. Introduction
  5. ============
  6. In this tutorial you will learn how to create a FrontendAction that uses
  7. a RecursiveASTVisitor to find CXXRecordDecl AST nodes with a specified
  8. name.
  9. Creating a FrontendAction
  10. =========================
  11. When writing a clang based tool like a Clang Plugin or a standalone tool
  12. based on LibTooling, the common entry point is the FrontendAction.
  13. FrontendAction is an interface that allows execution of user specific
  14. actions as part of the compilation. To run tools over the AST clang
  15. provides the convenience interface ASTFrontendAction, which takes care
  16. of executing the action. The only part left is to implement the
  17. CreateASTConsumer method that returns an ASTConsumer per translation
  18. unit.
  19. ::
  20. class FindNamedClassAction : public clang::ASTFrontendAction {
  21. public:
  22. virtual std::unique_ptr<clang::ASTConsumer> CreateASTConsumer(
  23. clang::CompilerInstance &Compiler, llvm::StringRef InFile) {
  24. return std::unique_ptr<clang::ASTConsumer>(
  25. new FindNamedClassConsumer);
  26. }
  27. };
  28. Creating an ASTConsumer
  29. =======================
  30. ASTConsumer is an interface used to write generic actions on an AST,
  31. regardless of how the AST was produced. ASTConsumer provides many
  32. different entry points, but for our use case the only one needed is
  33. HandleTranslationUnit, which is called with the ASTContext for the
  34. translation unit.
  35. ::
  36. class FindNamedClassConsumer : public clang::ASTConsumer {
  37. public:
  38. virtual void HandleTranslationUnit(clang::ASTContext &Context) {
  39. // Traversing the translation unit decl via a RecursiveASTVisitor
  40. // will visit all nodes in the AST.
  41. Visitor.TraverseDecl(Context.getTranslationUnitDecl());
  42. }
  43. private:
  44. // A RecursiveASTVisitor implementation.
  45. FindNamedClassVisitor Visitor;
  46. };
  47. Using the RecursiveASTVisitor
  48. =============================
  49. Now that everything is hooked up, the next step is to implement a
  50. RecursiveASTVisitor to extract the relevant information from the AST.
  51. The RecursiveASTVisitor provides hooks of the form bool
  52. VisitNodeType(NodeType \*) for most AST nodes; the exception are TypeLoc
  53. nodes, which are passed by-value. We only need to implement the methods
  54. for the relevant node types.
  55. Let's start by writing a RecursiveASTVisitor that visits all
  56. CXXRecordDecl's.
  57. ::
  58. class FindNamedClassVisitor
  59. : public RecursiveASTVisitor<FindNamedClassVisitor> {
  60. public:
  61. bool VisitCXXRecordDecl(CXXRecordDecl *Declaration) {
  62. // For debugging, dumping the AST nodes will show which nodes are already
  63. // being visited.
  64. Declaration->dump();
  65. // The return value indicates whether we want the visitation to proceed.
  66. // Return false to stop the traversal of the AST.
  67. return true;
  68. }
  69. };
  70. In the methods of our RecursiveASTVisitor we can now use the full power
  71. of the Clang AST to drill through to the parts that are interesting for
  72. us. For example, to find all class declaration with a certain name, we
  73. can check for a specific qualified name:
  74. ::
  75. bool VisitCXXRecordDecl(CXXRecordDecl *Declaration) {
  76. if (Declaration->getQualifiedNameAsString() == "n::m::C")
  77. Declaration->dump();
  78. return true;
  79. }
  80. Accessing the SourceManager and ASTContext
  81. ==========================================
  82. Some of the information about the AST, like source locations and global
  83. identifier information, are not stored in the AST nodes themselves, but
  84. in the ASTContext and its associated source manager. To retrieve them we
  85. need to hand the ASTContext into our RecursiveASTVisitor implementation.
  86. The ASTContext is available from the CompilerInstance during the call to
  87. CreateASTConsumer. We can thus extract it there and hand it into our
  88. freshly created FindNamedClassConsumer:
  89. ::
  90. virtual std::unique_ptr<clang::ASTConsumer> CreateASTConsumer(
  91. clang::CompilerInstance &Compiler, llvm::StringRef InFile) {
  92. return std::unique_ptr<clang::ASTConsumer>(
  93. new FindNamedClassConsumer(&Compiler.getASTContext()));
  94. }
  95. Now that the ASTContext is available in the RecursiveASTVisitor, we can
  96. do more interesting things with AST nodes, like looking up their source
  97. locations:
  98. ::
  99. bool VisitCXXRecordDecl(CXXRecordDecl *Declaration) {
  100. if (Declaration->getQualifiedNameAsString() == "n::m::C") {
  101. // getFullLoc uses the ASTContext's SourceManager to resolve the source
  102. // location and break it up into its line and column parts.
  103. FullSourceLoc FullLocation = Context->getFullLoc(Declaration->getBeginLoc());
  104. if (FullLocation.isValid())
  105. llvm::outs() << "Found declaration at "
  106. << FullLocation.getSpellingLineNumber() << ":"
  107. << FullLocation.getSpellingColumnNumber() << "\n";
  108. }
  109. return true;
  110. }
  111. Putting it all together
  112. =======================
  113. Now we can combine all of the above into a small example program:
  114. ::
  115. #include "clang/AST/ASTConsumer.h"
  116. #include "clang/AST/RecursiveASTVisitor.h"
  117. #include "clang/Frontend/CompilerInstance.h"
  118. #include "clang/Frontend/FrontendAction.h"
  119. #include "clang/Tooling/Tooling.h"
  120. using namespace clang;
  121. class FindNamedClassVisitor
  122. : public RecursiveASTVisitor<FindNamedClassVisitor> {
  123. public:
  124. explicit FindNamedClassVisitor(ASTContext *Context)
  125. : Context(Context) {}
  126. bool VisitCXXRecordDecl(CXXRecordDecl *Declaration) {
  127. if (Declaration->getQualifiedNameAsString() == "n::m::C") {
  128. FullSourceLoc FullLocation = Context->getFullLoc(Declaration->getBeginLoc());
  129. if (FullLocation.isValid())
  130. llvm::outs() << "Found declaration at "
  131. << FullLocation.getSpellingLineNumber() << ":"
  132. << FullLocation.getSpellingColumnNumber() << "\n";
  133. }
  134. return true;
  135. }
  136. private:
  137. ASTContext *Context;
  138. };
  139. class FindNamedClassConsumer : public clang::ASTConsumer {
  140. public:
  141. explicit FindNamedClassConsumer(ASTContext *Context)
  142. : Visitor(Context) {}
  143. virtual void HandleTranslationUnit(clang::ASTContext &Context) {
  144. Visitor.TraverseDecl(Context.getTranslationUnitDecl());
  145. }
  146. private:
  147. FindNamedClassVisitor Visitor;
  148. };
  149. class FindNamedClassAction : public clang::ASTFrontendAction {
  150. public:
  151. virtual std::unique_ptr<clang::ASTConsumer> CreateASTConsumer(
  152. clang::CompilerInstance &Compiler, llvm::StringRef InFile) {
  153. return std::unique_ptr<clang::ASTConsumer>(
  154. new FindNamedClassConsumer(&Compiler.getASTContext()));
  155. }
  156. };
  157. int main(int argc, char **argv) {
  158. if (argc > 1) {
  159. clang::tooling::runToolOnCode(std::make_unique<FindNamedClassAction>(), argv[1]);
  160. }
  161. }
  162. We store this into a file called FindClassDecls.cpp and create the
  163. following CMakeLists.txt to link it:
  164. ::
  165. add_clang_executable(find-class-decls FindClassDecls.cpp)
  166. target_link_libraries(find-class-decls clangTooling)
  167. When running this tool over a small code snippet it will output all
  168. declarations of a class n::m::C it found:
  169. ::
  170. $ ./bin/find-class-decls "namespace n { namespace m { class C {}; } }"
  171. Found declaration at 1:29