Skip to content

Instantly share code, notes, and snippets.

@ek0
Created May 27, 2025 02:26
Show Gist options
  • Save ek0/d694a02d7cf3a65d390dad907c3933bd to your computer and use it in GitHub Desktop.
Save ek0/d694a02d7cf3a65d390dad907c3933bd to your computer and use it in GitHub Desktop.
#include <clang/AST/ASTConsumer.h>
#include <clang/AST/RecursiveASTVisitor.h>
#include <clang/Frontend/FrontendAction.h>
#include <clang/Frontend/FrontendActions.h>
#include <clang/Tooling/CommonOptionsParser.h>
#include <clang/Tooling/Tooling.h>
#include <llvm/Support/CommandLine.h>
#include <llvm/Support/MemoryBuffer.h>
#include <filesystem>
#include <fstream>
#include <iostream>
class ScopeExtractorVisitor
: public clang::RecursiveASTVisitor<ScopeExtractorVisitor> {
public:
ScopeExtractorVisitor(clang::SourceManager &manager) : manager_(manager) {}
bool VisitFunctionDecl(clang::FunctionDecl *FD) {
// Process function declarations here
return true;
}
bool VisitCompoundStmt(clang::CompoundStmt *CS) {
clang::SourceLocation start = CS->getBeginLoc();
clang::SourceLocation end = CS->getEndLoc();
if (start.isValid() && end.isValid()) {
clang::SourceRange range(start, end);
llvm::StringRef sourceText = clang::Lexer::getSourceText(
clang::CharSourceRange::getTokenRange(range), manager_,
clang::LangOptions(), 0);
llvm::outs() << "Scope: << " << "(" << start.printToString(manager_)
<< ", " << end.printToString(manager_)
<< ")\n"
<< sourceText << "\n---\n";
}
return true; // continue traversal
}
private:
clang::SourceManager &manager_;
};
class ScopeExtractorConsumer : public clang::ASTConsumer {
public:
ScopeExtractorConsumer(clang::SourceManager &manager)
: manager_(manager), visitor_(manager_) {}
void HandleTranslationUnit(clang::ASTContext &Context) override {
visitor_.TraverseDecl(Context.getTranslationUnitDecl());
}
private:
// Keep a reference to the source manager.
clang::SourceManager &manager_;
ScopeExtractorVisitor visitor_;
};
class ScopeExtractorAction : public clang::ASTFrontendAction {
public:
std::unique_ptr<clang::ASTConsumer> CreateASTConsumer(
clang::CompilerInstance &CI, llvm::StringRef file) override {
return std::make_unique<ScopeExtractorConsumer>(CI.getSourceManager());
}
};
static llvm::cl::OptionCategory XplorerToolCategory("Xplorer tool options");
int main(int argc, const char **argv) {
if (argc != 2) {
std::cerr << "tool.exe <filename>" << std::endl;
return -1;
}
auto file_or = llvm::MemoryBuffer::getFile(argv[1], true);
auto file = std::move(file_or.get());
clang::tooling::runToolOnCode(std::make_unique<ScopeExtractorAction>(),
file->getBuffer());
return 0;
// return Tool.run(
// clang::tooling::newFrontendActionFactory<ScopeExtractorAction>().get());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment