Advertisement
Fare9

name_ast_finder.cpp

Apr 22nd, 2020
468
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.98 KB | None | 0 0
  1. extern "C" {
  2. #include "clang-c/Index.h"
  3. }
  4. #include "llvm/Support/CommandLine.h"
  5. #include "llvm/Support/raw_ostream.h"
  6.  
  7. using namespace llvm;
  8.  
  9. static cl::opt<std::string> FileName(cl::Positional, cl::desc("Input File"), cl::Required);
  10.  
  11. /* Function callback for the AST */
  12. enum CXChildVisitResult visitNode (CXCursor cursor, CXCursor parent, CXClientData client_data);
  13.  
  14.  
  15. int
  16. main(int argc, char** argv)
  17. {
  18.     cl::ParseCommandLineOptions(argc, argv, "AST Traversal Name Extractor");
  19.     CXIndex index = clang_createIndex(0, 0);
  20.     const char *args[] = {
  21.         "-I/usr/include",
  22.         "-I."
  23.     };
  24.  
  25.     CXTranslationUnit translationUnit = clang_parseTranslationUnit(index, FileName.c_str(), args, 2, NULL, 0, CXTranslationUnit_None);
  26.     // get cursor for visiting AST tree
  27.     CXCursor cur = clang_getTranslationUnitCursor(translationUnit);
  28.     // Function to go through the whole
  29.     // AST tree, we have to give the callback
  30.     clang_visitChildren(cur, visitNode, NULL);
  31.     clang_disposeTranslationUnit(translationUnit);
  32.     clang_disposeIndex(index);
  33.     return 0;
  34. }
  35.  
  36.  
  37. enum CXChildVisitResult
  38. visitNode (CXCursor cursor, CXCursor parent, CXClientData client_data)
  39. /*
  40. *   Function to print every function declared
  41. *   and method name.
  42. */
  43. {
  44.     if (clang_getCursorKind(cursor) == CXCursor_CXXMethod ||
  45.         clang_getCursorKind(cursor) == CXCursor_FunctionDecl)
  46.     {
  47.         CXString name = clang_getCursorSpelling(cursor);
  48.         CXSourceLocation loc = clang_getCursorLocation(cursor);
  49.         CXString fName;
  50.         unsigned line = 0, col = 0;
  51.         clang_getPresumedLocation(loc, &fName, &line, &col);
  52.  
  53.         outs() << clang_getCString(fName) << ":"
  54.                << line << ":" << col << " declares "
  55.                << clang_getCString(name) << "\n";
  56.  
  57.         clang_disposeString(name);
  58.         clang_disposeString(fName);
  59.  
  60.         return CXChildVisit_Continue; // skip child nodes
  61.     }
  62.  
  63.     return CXChildVisit_Recurse; // go to children node
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement