Skip to content

Instantly share code, notes, and snippets.

@pstiasny
Created March 19, 2024 19:01
Show Gist options
  • Save pstiasny/2d067d9dced2c3aed2ca1b881f8b5bcc to your computer and use it in GitHub Desktop.
Save pstiasny/2d067d9dced2c3aed2ca1b881f8b5bcc to your computer and use it in GitHub Desktop.
dump declarations using clang Tooling API
cmake_minimum_required(VERSION 3.10)
# Set your project name and version
project(MyClangProject VERSION 1.0)
# Specify the C++ standard
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED True)
# add_link_options("-fuse-ld=lld")
set(NO_RTTI "-fno-rtti")
add_definitions(${NO_RTTI})
# Find LLVM
find_package(LLVM REQUIRED CONFIG)
message(STATUS "Found LLVM ${LLVM_PACKAGE_VERSION}")
message(STATUS "Using LLVMConfig.cmake in: ${LLVM_DIR}")
# Find Clang
find_package(Clang REQUIRED CONFIG)
message(STATUS "Found Clang")
# Add LLVM and Clang include directories
include_directories(${LLVM_INCLUDE_DIRS})
include_directories(${CLANG_INCLUDE_DIRS})
# Add LLVM and Clang definitions
add_definitions(${LLVM_DEFINITIONS})
# Your source files
set(SOURCE_FILES tool.cpp)
# Add the executable
add_executable(MyClangProject ${SOURCE_FILES})
install(TARGETS MyClangProject DESTINATION bin)
# Link LLVM and Clang libraries
llvm_map_components_to_libnames(llvm_libs Support core irreader AllTargetsCodeGens AllTargetsAsmParsers)
target_link_libraries(MyClangProject PRIVATE ${llvm_libs})
# If you're directly using Clang libraries, you might need to link them as well.
# This is an example to link against the Clang frontend and AST libraries.
target_link_libraries(MyClangProject PRIVATE
clangAPINotes
clangARCMigrate
clangAST
clangASTMatchers
clangAnalysis
clangAnalysisFlowSensitive
clangAnalysisFlowSensitiveModels
clangBasic
clangCodeGen
clangCrossTU
clangDependencyScanning
clangDirectoryWatcher
clangDriver
clangDynamicASTMatchers
clangEdit
clangExtractAPI
clangFormat
clangFrontend
clangFrontendTool
clangHandleCXX
clangHandleLLVM
clangIndex
clangIndexSerialization
clangInterpreter
clangLex
clangParse
clangRewrite
clangRewriteFrontend
clangSema
clangSerialization
clangStaticAnalyzerCheckers
clangStaticAnalyzerCore
clangStaticAnalyzerFrontend
clangSupport
clangTooling
clangToolingASTDiff
clangToolingCore
clangToolingInclusions
clangToolingInclusionsStdlib
clangToolingRefactoring
clangToolingSyntax
clangTransformer
)
#include "clang/AST/DeclGroup.h"
#include <clang/Tooling/CommonOptionsParser.h>
#include <clang/Tooling/Tooling.h>
#include <clang/Frontend/CompilerInstance.h>
#include <clang/Frontend/FrontendActions.h>
#include <llvm/Support/CommandLine.h>
#include <llvm/Support/raw_ostream.h>
#include <memory>
using namespace clang;
using namespace clang::tooling;
class MyASTConsumer : public ASTConsumer {
public:
explicit MyASTConsumer() {}
virtual void HandleTranslationUnit(ASTContext &Context) override {
// Here you can access the AST generated from the source code
llvm::outs() << "Translation unit processed.\n";
}
virtual bool HandleTopLevelDecl(DeclGroupRef decl_group) override {
llvm::outs() << "begin top level decl GROUP\n";
for (auto decl: decl_group) {
llvm::outs() << "begin top level decl\n";
decl->print(llvm::outs(), 4);
llvm::outs() << "\nend top level decl\n";
}
llvm::outs() << "end top level decl GROUP\n";
return true;
}
};
class MyFrontendAction : public ASTFrontendAction {
public:
virtual std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI, StringRef file) override {
return std::make_unique<MyASTConsumer>();
}
};
int main(int argc, const char **argv) {
llvm::cl::OptionCategory MyToolCategory("my-tool options");
llvm::Expected<CommonOptionsParser> optionsParserRes = CommonOptionsParser::create(
argc, argv, MyToolCategory);
if (auto E = optionsParserRes.takeError()) {
llvm::errs() << toString(std::move(E)) << "\n";
return 1;
}
ClangTool Tool(
optionsParserRes->getCompilations(),
optionsParserRes->getSourcePathList());
// Run the Clang Tool, creating a new FrontendAction.
int result = Tool.run(newFrontendActionFactory<MyFrontendAction>().get());
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment