#include <assert.h>
#include <fstream>
#include <iostream>
#include <memory>
#include <set>
#include <stack>
#include <string>
#include <vector>
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/FrontendActions.h"
#include "clang/Lex/HeaderSearchOptions.h"
#include "clang/Lex/PPCallbacks.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Tooling/CommonOptionsParser.h"
#include "clang/Tooling/CompilationDatabase.h"
#include "clang/Tooling/Refactoring.h"
#include "clang/Tooling/Tooling.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
using clang::HeaderSearchOptions;
using clang::tooling::CommonOptionsParser;
using llvm::sys::fs::real_path;
using llvm::SmallVector;
using std::set;
using std::stack;
using std::string;
using std::vector;
namespace {
class IncludeFinderPPCallbacks : public clang::PPCallbacks {
public:
IncludeFinderPPCallbacks(clang::SourceManager* source_manager,
string* main_source_file,
set<string>* source_file_paths,
const HeaderSearchOptions* header_search_options);
void FileChanged(clang::SourceLocation ,
clang::PPCallbacks::FileChangeReason reason,
clang::SrcMgr::CharacteristicKind ,
clang::FileID ) override;
void AddFile(const string& path);
void InclusionDirective(clang::SourceLocation hash_loc,
const clang::Token& include_tok,
llvm::StringRef file_name,
bool is_angled,
clang::CharSourceRange range,
clang::OptionalFileEntryRef file,
llvm::StringRef search_path,
llvm::StringRef relative_path,
const clang::Module* SuggestedModule,
bool ModuleImported,
clang::SrcMgr::CharacteristicKind
) override;
void EndOfMainFile() override;
private:
string DoubleSlashSystemHeaders(const string& search_path,
const string& relative_path) const;
clang::SourceManager* const source_manager_;
#if !defined(NDEBUG)
string* const main_source_file_;
#endif
set<string>* const source_file_paths_;
set<string> system_header_prefixes_;
string last_inclusion_directive_;
stack<string> current_files_;
};
IncludeFinderPPCallbacks::IncludeFinderPPCallbacks(
clang::SourceManager* source_manager,
string* main_source_file,
set<string>* source_file_paths,
const HeaderSearchOptions* header_search_options)
: source_manager_(source_manager),
#if !defined(NDEBUG)
main_source_file_(main_source_file),
#endif
source_file_paths_(source_file_paths) {
for (const auto& prefix : header_search_options->SystemHeaderPrefixes) {
system_header_prefixes_.insert(prefix.Prefix);
}
for (const auto& entry : header_search_options->UserEntries) {
switch (entry.Group) {
case clang::frontend::System:
case clang::frontend::ExternCSystem:
case clang::frontend::CSystem:
case clang::frontend::CXXSystem:
case clang::frontend::ObjCSystem:
case clang::frontend::ObjCXXSystem:
case clang::frontend::After:
system_header_prefixes_.insert(entry.Path);
break;
default:
break;
}
}
}
void IncludeFinderPPCallbacks::FileChanged(
clang::SourceLocation ,
clang::PPCallbacks::FileChangeReason reason,
clang::SrcMgr::CharacteristicKind ,
clang::FileID ) {
if (reason == clang::PPCallbacks::EnterFile) {
if (!last_inclusion_directive_.empty()) {
current_files_.push(last_inclusion_directive_);
} else {
current_files_.push(std::string(
source_manager_
->getFileEntryRefForID(source_manager_->getMainFileID())
->getName()));
}
} else if (reason == ExitFile) {
current_files_.pop();
}
}
void IncludeFinderPPCallbacks::AddFile(const string& path) {
source_file_paths_->insert(path);
}
void IncludeFinderPPCallbacks::InclusionDirective(
clang::SourceLocation hash_loc,
const clang::Token& include_tok,
llvm::StringRef file_name,
bool is_angled,
clang::CharSourceRange range,
clang::OptionalFileEntryRef file,
llvm::StringRef search_path,
llvm::StringRef relative_path,
const clang::Module* SuggestedModule,
bool ModuleImported,
clang::SrcMgr::CharacteristicKind
) {
if (!file)
return;
assert(!current_files_.top().empty());
const clang::OptionalDirectoryEntryRef search_path_entry =
source_manager_->getFileManager().getOptionalDirectoryRef(search_path);
const clang::OptionalFileEntryRef current_file_entry =
source_manager_->getFileManager().getOptionalFileRef(
current_files_.top().c_str());
const clang::OptionalDirectoryEntryRef current_file_parent_entry =
current_file_entry
? clang::OptionalDirectoryEntryRef(current_file_entry->getDir())
: clang::OptionalDirectoryEntryRef(std::nullopt);
if (search_path_entry == current_file_parent_entry) {
string parent =
llvm::sys::path::parent_path(current_files_.top().c_str()).str();
if (parent.empty() || parent == "/")
parent = ".";
last_inclusion_directive_ =
DoubleSlashSystemHeaders(parent, relative_path.str());
} else if (!search_path.empty()) {
last_inclusion_directive_ =
DoubleSlashSystemHeaders(search_path.str(), relative_path.str());
} else {
last_inclusion_directive_ = file_name.str();
}
AddFile(last_inclusion_directive_);
}
string IncludeFinderPPCallbacks::DoubleSlashSystemHeaders(
const string& search_path,
const string& relative_path) const {
const bool is_system_header =
system_header_prefixes_.find(search_path) !=
system_header_prefixes_.end();
return search_path + (is_system_header ? "//" : "/") + relative_path;
}
void IncludeFinderPPCallbacks::EndOfMainFile() {
clang::OptionalFileEntryRef main_file =
source_manager_->getFileEntryRefForID(source_manager_->getMainFileID());
assert(main_file.has_value());
SmallVector<char, 100> main_source_file_real_path;
SmallVector<char, 100> main_file_name_real_path;
assert(!real_path(*main_source_file_, main_source_file_real_path));
assert(!real_path(main_file->getName(), main_file_name_real_path));
assert(main_source_file_real_path == main_file_name_real_path);
AddFile(std::string(main_file->getName()));
}
class CompilationIndexerAction : public clang::PreprocessorFrontendAction {
public:
CompilationIndexerAction() {}
void ExecuteAction() override;
void Preprocess();
void EndSourceFileAction() override;
private:
string main_source_file_;
set<string> source_file_paths_;
};
void CompilationIndexerAction::ExecuteAction() {
auto inputs = getCompilerInstance().getFrontendOpts().Inputs;
assert(inputs.size() == 1);
main_source_file_ = std::string(inputs[0].getFile());
Preprocess();
}
void CompilationIndexerAction::Preprocess() {
clang::Preprocessor& preprocessor = getCompilerInstance().getPreprocessor();
preprocessor.addPPCallbacks(std::make_unique<IncludeFinderPPCallbacks>(
&getCompilerInstance().getSourceManager(), &main_source_file_,
&source_file_paths_, &getCompilerInstance().getHeaderSearchOpts()));
preprocessor.getDiagnostics().setIgnoreAllWarnings(true);
preprocessor.SetSuppressIncludeNotFoundError(true);
preprocessor.EnterMainSourceFile();
clang::Token token;
do {
preprocessor.Lex(token);
} while (token.isNot(clang::tok::eof));
}
void CompilationIndexerAction::EndSourceFileAction() {
std::ofstream out(main_source_file_ + ".filepaths");
for (const string& path : source_file_paths_) {
out << path << std::endl;
}
}
}
static llvm::cl::extrahelp common_help(CommonOptionsParser::HelpMessage);
int main(int argc, const char* argv[]) {
llvm::cl::OptionCategory category("TranslationUnitGenerator Tool");
auto ExpectedParser = CommonOptionsParser::create(
argc, argv, category, llvm::cl::OneOrMore, nullptr);
if (!ExpectedParser) {
llvm::errs() << ExpectedParser.takeError();
return 1;
}
CommonOptionsParser& options = ExpectedParser.get();
std::unique_ptr<clang::tooling::FrontendActionFactory> frontend_factory =
clang::tooling::newFrontendActionFactory<CompilationIndexerAction>();
clang::tooling::ClangTool tool(options.getCompilations(),
options.getSourcePathList());
return tool.run(frontend_factory.get());
}