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; +}