From 68cd43d3f9eee4264baf30ee0d90c6d5a474c3ec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?= Date: Sun, 29 Apr 2018 22:22:32 +0200 Subject: [PATCH] clang-ast: add tool that uses libclang to output ast for a file --- tools/clang-ast.cpp | 90 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 tools/clang-ast.cpp diff --git a/tools/clang-ast.cpp b/tools/clang-ast.cpp new file mode 100644 index 000000000..5fa42486d --- /dev/null +++ b/tools/clang-ast.cpp @@ -0,0 +1,90 @@ +// Dump the AST for a file. +// +// Compile with: +// g++ `llvm-config-3.8 --cxxflags --ldflags` -lclang -o clang-ast clang-ast.cpp + +#include +#include +#include + +std::ostream& operator<<(std::ostream& stream, const CXString& str) +{ + stream << clang_getCString(str); + clang_disposeString(str); + return stream; +} + +int main(int argc, char **argv) +{ + CXIndex index = clang_createIndex(0, 0); + CXTranslationUnit unit = clang_parseTranslationUnit( + index, + "file1.cpp", argv, argc, + nullptr, 0, + CXTranslationUnit_None); + if (unit == nullptr) { + std::cerr << "Unable to parse translation unit. Quitting." << std::endl; + return EXIT_FAILURE; + } + + std::cout << "\n" + << "\n"; + + CXCursor cursor = clang_getTranslationUnitCursor(unit); + clang_visitChildren( + cursor, + [](CXCursor c, CXCursor parent, CXClientData client_data) { + switch (clang_getCursorKind(c)) { + case CXCursor_FunctionDecl: { + CXSourceLocation location = clang_getCursorLocation(c); + CXString filename; + unsigned int line, column; + clang_getPresumedLocation(location, &filename, &line, &column); + + std::cout << "\n"; + break; + } + + case CXCursor_CallExpr: { + CXSourceLocation location = clang_getCursorLocation(c); + CXString filename; + unsigned int line, column; + clang_getPresumedLocation(location, &filename, &line, &column); + + CXCursor ref = clang_getCursorReferenced(c); + CXSourceLocation locationRef = clang_getCursorLocation(ref); + CXString filenameRef; + unsigned int lineRef, columnRef; + clang_getPresumedLocation(locationRef, &filenameRef, &lineRef, &columnRef); + + std::cout << "\n"; + break; + } + break; + default: + break; + }; + + return CXChildVisit_Recurse; + }, + nullptr); + + std::cout << "\n"; + + clang_disposeTranslationUnit(unit); + clang_disposeIndex(index); + + return EXIT_SUCCESS; +}