// headerlist.txt
#include "Modularize.h"
#include "ModularizeUtilities.h"
#include "PreprocessorTracker.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Driver/Options.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/FrontendAction.h"
#include "clang/Frontend/FrontendActions.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Tooling/CompilationDatabase.h"
#include "clang/Tooling/Tooling.h"
#include "llvm/Option/Arg.h"
#include "llvm/Option/ArgList.h"
#include "llvm/Option/OptTable.h"
#include "llvm/Option/Option.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include <algorithm>
#include <iterator>
#include <map>
#include <string>
#include <vector>
using namespace clang;
using namespace clang::driver;
using namespace clang::driver::options;
using namespace clang::tooling;
using namespace llvm;
using namespace llvm::opt;
using namespace Modularize;
static cl::list<std::string>
ListFileNames(cl::Positional, cl::value_desc("list"),
cl::desc("<list of one or more header list files>"),
cl::CommaSeparated);
static cl::list<std::string>
CC1Arguments(cl::ConsumeAfter,
cl::desc("<arguments to be passed to front end>..."));
static cl::opt<std::string> HeaderPrefix(
"prefix", cl::init(""),
cl::desc(
"Prepend header file paths with this prefix."
" If not specified,"
" the files are considered to be relative to the header list file."));
static cl::opt<std::string> ModuleMapPath(
"module-map-path", cl::init(""),
cl::desc("Turn on module map output and specify output path or file name."
" If no path is specified and if prefix option is specified,"
" use prefix for file path."));
static cl::opt<std::string> ProblemFilesList(
"problem-files-list", cl::init(""),
cl::desc(
"List of files with compilation or modularization problems for"
" assistant mode. This will be excluded."));
static cl::opt<std::string>
RootModule("root-module", cl::init(""),
cl::desc("Specify the name of the root module."));
static cl::opt<bool>
BlockCheckHeaderListOnly("block-check-header-list-only", cl::init(false),
cl::desc("Only warn if #include directives are inside extern or namespace"
" blocks if the included header is in the header list."));
static cl::list<std::string>
IncludePaths("I", cl::desc("Include path for coverage check."),
cl::value_desc("path"));
static cl::opt<bool> NoCoverageCheck("no-coverage-check",
cl::desc("Don't do the coverage check."));
static cl::opt<bool>
CoverageCheckOnly("coverage-check-only", cl::init(false),
cl::desc("Only do the coverage check."));
static cl::opt<bool>
DisplayFileLists("display-file-lists", cl::init(false),
cl::desc("Display lists of good files (no compile errors), problem files,"
" and a combined list with problem files preceded by a '#'."));
const char *Argv0;
std::string CommandLine;
static std::string findInputFile(const CommandLineArguments &CLArgs) {
llvm::opt::Visibility VisibilityMask(options::CC1Option);
unsigned MissingArgIndex, MissingArgCount;
SmallVector<const char *, 256> Argv;
for (auto I = CLArgs.begin(), E = CLArgs.end(); I != E; ++I)
Argv.push_back(I->c_str());
InputArgList Args = getDriverOptTable().ParseArgs(
Argv, MissingArgIndex, MissingArgCount, VisibilityMask);
std::vector<std::string> Inputs = Args.getAllArgValues(OPT_INPUT);
return ModularizeUtilities::getCanonicalPath(Inputs.back());
}
static ArgumentsAdjuster
getModularizeArgumentsAdjuster(DependencyMap &Dependencies) {
return [&Dependencies](const CommandLineArguments &Args,
StringRef ) {
std::string InputFile = findInputFile(Args);
DependentsVector &FileDependents = Dependencies[InputFile];
CommandLineArguments NewArgs(Args);
if (int Count = FileDependents.size()) {
for (int Index = 0; Index < Count; ++Index) {
NewArgs.push_back("-include");
std::string File(std::string("\"") + FileDependents[Index] +
std::string("\""));
NewArgs.push_back(FileDependents[Index]);
}
}
NewArgs.insert(NewArgs.begin() + 1, "-w");
if (!llvm::is_contained(NewArgs, "-x")) {
NewArgs.insert(NewArgs.begin() + 2, "-x");
NewArgs.insert(NewArgs.begin() + 3, "c++");
}
return NewArgs;
};
}
struct Location {
OptionalFileEntryRef File;
unsigned Line, Column;
Location() : File(), Line(), Column() {}
Location(SourceManager &SM, SourceLocation Loc) : File(), Line(), Column() {
Loc = SM.getExpansionLoc(Loc);
if (Loc.isInvalid())
return;
std::pair<FileID, unsigned> Decomposed = SM.getDecomposedLoc(Loc);
File = SM.getFileEntryRefForID(Decomposed.first);
if (!File)
return;
Line = SM.getLineNumber(Decomposed.first, Decomposed.second);
Column = SM.getColumnNumber(Decomposed.first, Decomposed.second);
}
operator bool() const { return File != nullptr; }
friend bool operator==(const Location &X, const Location &Y) {
return X.File == Y.File && X.Line == Y.Line && X.Column == Y.Column;
}
friend bool operator!=(const Location &X, const Location &Y) {
return !(X == Y);
}
friend bool operator<(const Location &X, const Location &Y) {
if (X.File != Y.File)
return X.File < Y.File;
if (X.Line != Y.Line)
return X.Line < Y.Line;
return X.Column < Y.Column;
}
friend bool operator>(const Location &X, const Location &Y) { return Y < X; }
friend bool operator<=(const Location &X, const Location &Y) {
return !(Y < X);
}
friend bool operator>=(const Location &X, const Location &Y) {
return !(X < Y);
}
};
struct Entry {
enum EntryKind {
EK_Tag,
EK_Value,
EK_Macro,
EK_NumberOfKinds
} Kind;
Location Loc;
StringRef getKindName() { return getKindName(Kind); }
static StringRef getKindName(EntryKind kind);
};
StringRef Entry::getKindName(Entry::EntryKind kind) {
switch (kind) {
case EK_Tag:
return "tag";
case EK_Value:
return "value";
case EK_Macro:
return "macro";
case EK_NumberOfKinds:
break;
}
llvm_unreachable("invalid Entry kind");
}
struct HeaderEntry {
std::string Name;
Location Loc;
friend bool operator==(const HeaderEntry &X, const HeaderEntry &Y) {
return X.Loc == Y.Loc && X.Name == Y.Name;
}
friend bool operator!=(const HeaderEntry &X, const HeaderEntry &Y) {
return !(X == Y);
}
friend bool operator<(const HeaderEntry &X, const HeaderEntry &Y) {
return X.Loc < Y.Loc || (X.Loc == Y.Loc && X.Name < Y.Name);
}
friend bool operator>(const HeaderEntry &X, const HeaderEntry &Y) {
return Y < X;
}
friend bool operator<=(const HeaderEntry &X, const HeaderEntry &Y) {
return !(Y < X);
}
friend bool operator>=(const HeaderEntry &X, const HeaderEntry &Y) {
return !(X < Y);
}
};
typedef std::vector<HeaderEntry> HeaderContents;
class EntityMap : public std::map<std::string, SmallVector<Entry, 2>> {
public:
DenseMap<FileEntryRef, HeaderContents> HeaderContentMismatches;
void add(const std::string &Name, enum Entry::EntryKind Kind, Location Loc) {
HeaderEntry HE = { Name, Loc };
CurHeaderContents[*Loc.File].push_back(HE);
SmallVector<Entry, 2> &Entries = (*this)[Name];
for (unsigned I = 0, N = Entries.size(); I != N; ++I) {
if (Entries[I].Kind == Kind && Entries[I].Loc == Loc)
return;
}
Entry E = { Kind, Loc };
Entries.push_back(E);
}
void mergeCurHeaderContents() {
for (auto H = CurHeaderContents.begin(), HEnd = CurHeaderContents.end();
H != HEnd; ++H) {
llvm::sort(H->second);
auto KnownH = AllHeaderContents.find(H->first);
if (KnownH == AllHeaderContents.end()) {
AllHeaderContents.insert(*H);
continue;
}
if (H->second == KnownH->second)
continue;
std::set_symmetric_difference(
H->second.begin(), H->second.end(), KnownH->second.begin(),
KnownH->second.end(),
std::back_inserter(HeaderContentMismatches[H->first]));
}
CurHeaderContents.clear();
}
private:
DenseMap<FileEntryRef, HeaderContents> CurHeaderContents;
DenseMap<FileEntryRef, HeaderContents> AllHeaderContents;
};
class CollectEntitiesVisitor
: public RecursiveASTVisitor<CollectEntitiesVisitor> {
public:
CollectEntitiesVisitor(SourceManager &SM, EntityMap &Entities,
Preprocessor &PP, PreprocessorTracker &PPTracker,
int &HadErrors)
: SM(SM), Entities(Entities), PP(PP), PPTracker(PPTracker),
HadErrors(HadErrors) {}
bool TraverseStmt(Stmt *S) { return true; }
bool TraverseType(QualType T) { return true; }
bool TraverseTypeLoc(TypeLoc TL) { return true; }
bool TraverseNestedNameSpecifier(NestedNameSpecifier *NNS) { return true; }
bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS) {
return true;
}
bool TraverseDeclarationNameInfo(DeclarationNameInfo NameInfo) {
return true;
}
bool TraverseTemplateName(TemplateName Template) { return true; }
bool TraverseTemplateArgument(const TemplateArgument &Arg) { return true; }
bool TraverseTemplateArgumentLoc(const TemplateArgumentLoc &ArgLoc) {
return true;
}
bool TraverseTemplateArguments(ArrayRef<TemplateArgument>) { return true; }
bool TraverseConstructorInitializer(CXXCtorInitializer *Init) { return true; }
bool TraverseLambdaCapture(LambdaExpr *LE, const LambdaCapture *C,
Expr *Init) {
return true;
}
bool VisitLinkageSpecDecl(LinkageSpecDecl *D) {
if (!D->hasBraces())
return true;
SourceRange BlockRange = D->getSourceRange();
const char *LinkageLabel;
switch (D->getLanguage()) {
case LinkageSpecLanguageIDs::C:
LinkageLabel = "extern \"C\" {}";
break;
case LinkageSpecLanguageIDs::CXX:
LinkageLabel = "extern \"C++\" {}";
break;
}
if (!PPTracker.checkForIncludesInBlock(PP, BlockRange, LinkageLabel,
errs()))
HadErrors = 1;
return true;
}
bool VisitNamespaceDecl(const NamespaceDecl *D) {
SourceRange BlockRange = D->getSourceRange();
std::string Label("namespace ");
Label += D->getName();
Label += " {}";
if (!PPTracker.checkForIncludesInBlock(PP, BlockRange, Label.c_str(),
errs()))
HadErrors = 1;
return true;
}
bool VisitNamedDecl(NamedDecl *ND) {
if (!ND->getDeclContext()->isFileContext())
return true;
if (isa<NamespaceDecl>(ND) || isa<UsingDirectiveDecl>(ND) ||
isa<NamespaceAliasDecl>(ND) ||
isa<ClassTemplateSpecializationDecl>(ND) || isa<UsingDecl>(ND) ||
isa<ClassTemplateDecl>(ND) || isa<TemplateTypeParmDecl>(ND) ||
isa<TypeAliasTemplateDecl>(ND) || isa<UsingShadowDecl>(ND) ||
isa<FunctionDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
(isa<TagDecl>(ND) &&
!cast<TagDecl>(ND)->isThisDeclarationADefinition()))
return true;
if (!ND->getDeclName())
return true;
std::string Name;
llvm::raw_string_ostream OS(Name);
ND->printQualifiedName(OS);
OS.flush();
if (Name.empty())
return true;
Location Loc(SM, ND->getLocation());
if (!Loc)
return true;
Entities.add(Name, isa<TagDecl>(ND) ? Entry::EK_Tag : Entry::EK_Value, Loc);
return true;
}
private:
SourceManager &SM;
EntityMap &Entities;
Preprocessor &PP;
PreprocessorTracker &PPTracker;
int &HadErrors;
};
class CollectEntitiesConsumer : public ASTConsumer {
public:
CollectEntitiesConsumer(EntityMap &Entities,
PreprocessorTracker &preprocessorTracker,
Preprocessor &PP, StringRef InFile, int &HadErrors)
: Entities(Entities), PPTracker(preprocessorTracker), PP(PP),
HadErrors(HadErrors) {
PPTracker.handlePreprocessorEntry(PP, InFile);
}
~CollectEntitiesConsumer() override { PPTracker.handlePreprocessorExit(); }
void HandleTranslationUnit(ASTContext &Ctx) override {
SourceManager &SM = Ctx.getSourceManager();
CollectEntitiesVisitor(SM, Entities, PP, PPTracker, HadErrors)
.TraverseDecl(Ctx.getTranslationUnitDecl());
for (Preprocessor::macro_iterator M = PP.macro_begin(),
MEnd = PP.macro_end();
M != MEnd; ++M) {
Location Loc(SM, M->second.getLatest()->getLocation());
if (!Loc)
continue;
Entities.add(M->first->getName().str(), Entry::EK_Macro, Loc);
}
Entities.mergeCurHeaderContents();
}
private:
EntityMap &Entities;
PreprocessorTracker &PPTracker;
Preprocessor &PP;
int &HadErrors;
};
class CollectEntitiesAction : public SyntaxOnlyAction {
public:
CollectEntitiesAction(EntityMap &Entities,
PreprocessorTracker &preprocessorTracker,
int &HadErrors)
: Entities(Entities), PPTracker(preprocessorTracker),
HadErrors(HadErrors) {}
protected:
std::unique_ptr<clang::ASTConsumer>
CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override {
return std::make_unique<CollectEntitiesConsumer>(
Entities, PPTracker, CI.getPreprocessor(), InFile, HadErrors);
}
private:
EntityMap &Entities;
PreprocessorTracker &PPTracker;
int &HadErrors;
};
class ModularizeFrontendActionFactory : public FrontendActionFactory {
public:
ModularizeFrontendActionFactory(EntityMap &Entities,
PreprocessorTracker &preprocessorTracker,
int &HadErrors)
: Entities(Entities), PPTracker(preprocessorTracker),
HadErrors(HadErrors) {}
std::unique_ptr<FrontendAction> create() override {
return std::make_unique<CollectEntitiesAction>(Entities, PPTracker,
HadErrors);
}
private:
EntityMap &Entities;
PreprocessorTracker &PPTracker;
int &HadErrors;
};
class CompileCheckVisitor
: public RecursiveASTVisitor<CompileCheckVisitor> {
public:
CompileCheckVisitor() {}
bool TraverseStmt(Stmt *S) { return true; }
bool TraverseType(QualType T) { return true; }
bool TraverseTypeLoc(TypeLoc TL) { return true; }
bool TraverseNestedNameSpecifier(NestedNameSpecifier *NNS) { return true; }
bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS) {
return true;
}
bool TraverseDeclarationNameInfo(DeclarationNameInfo NameInfo) {
return true;
}
bool TraverseTemplateName(TemplateName Template) { return true; }
bool TraverseTemplateArgument(const TemplateArgument &Arg) { return true; }
bool TraverseTemplateArgumentLoc(const TemplateArgumentLoc &ArgLoc) {
return true;
}
bool TraverseTemplateArguments(ArrayRef<TemplateArgument>) { return true; }
bool TraverseConstructorInitializer(CXXCtorInitializer *Init) { return true; }
bool TraverseLambdaCapture(LambdaExpr *LE, const LambdaCapture *C,
Expr *Init) {
return true;
}
bool VisitLinkageSpecDecl(LinkageSpecDecl *D) {
return true;
}
bool VisitNamespaceDecl(const NamespaceDecl *D) {
return true;
}
bool VisitNamedDecl(NamedDecl *ND) {
return true;
}
};
class CompileCheckConsumer : public ASTConsumer {
public:
CompileCheckConsumer() {}
void HandleTranslationUnit(ASTContext &Ctx) override {
CompileCheckVisitor().TraverseDecl(Ctx.getTranslationUnitDecl());
}
};
class CompileCheckAction : public SyntaxOnlyAction {
public:
CompileCheckAction() {}
protected:
std::unique_ptr<clang::ASTConsumer>
CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override {
return std::make_unique<CompileCheckConsumer>();
}
};
class CompileCheckFrontendActionFactory : public FrontendActionFactory {
public:
CompileCheckFrontendActionFactory() {}
std::unique_ptr<FrontendAction> create() override {
return std::make_unique<CompileCheckAction>();
}
};
int main(int Argc, const char **Argv) {
Argv0 = Argv[0];
CommandLine = std::string(sys::path::stem(sys::path::filename(Argv0)));
for (int ArgIndex = 1; ArgIndex < Argc; ArgIndex++) {
CommandLine.append(" ");
CommandLine.append(Argv[ArgIndex]);
}
cl::ParseCommandLineOptions(Argc, Argv, "modularize.\n");
if (ListFileNames.size() == 0) {
cl::PrintHelpMessage();
return 1;
}
std::unique_ptr<ModularizeUtilities> ModUtil;
int HadErrors = 0;
ModUtil.reset(
ModularizeUtilities::createModularizeUtilities(
ListFileNames, HeaderPrefix, ProblemFilesList));
if (ModUtil->loadAllHeaderListsAndDependencies())
HadErrors = 1;
if (ModuleMapPath.length() != 0) {
if (!createModuleMap(ModuleMapPath, ModUtil->HeaderFileNames,
ModUtil->ProblemFileNames,
ModUtil->Dependencies, HeaderPrefix, RootModule))
return 1;
return 0;
}
if (!NoCoverageCheck && ModUtil->HasModuleMap) {
if (ModUtil->doCoverageCheck(IncludePaths, CommandLine))
HadErrors = 1;
}
if (CoverageCheckOnly)
return HadErrors;
SmallString<256> PathBuf;
sys::fs::current_path(PathBuf);
std::unique_ptr<CompilationDatabase> Compilations;
Compilations.reset(
new FixedCompilationDatabase(Twine(PathBuf), CC1Arguments));
std::unique_ptr<PreprocessorTracker> PPTracker(
PreprocessorTracker::create(ModUtil->HeaderFileNames,
BlockCheckHeaderListOnly));
EntityMap Entities;
if (DisplayFileLists) {
for (auto &CompileCheckFile : ModUtil->HeaderFileNames) {
llvm::SmallVector<std::string, 32> CompileCheckFileArray;
CompileCheckFileArray.push_back(CompileCheckFile);
ClangTool CompileCheckTool(*Compilations, CompileCheckFileArray);
CompileCheckTool.appendArgumentsAdjuster(
getModularizeArgumentsAdjuster(ModUtil->Dependencies));
int CompileCheckFileErrors = 0;
CompileCheckFrontendActionFactory CompileCheckFactory;
CompileCheckFileErrors |= CompileCheckTool.run(&CompileCheckFactory);
if (CompileCheckFileErrors != 0) {
ModUtil->addUniqueProblemFile(CompileCheckFile);
HadErrors |= 1;
}
else
ModUtil->addNoCompileErrorsFile(CompileCheckFile);
}
}
ClangTool Tool(*Compilations,
(DisplayFileLists ? ModUtil->GoodFileNames : ModUtil->HeaderFileNames));
Tool.appendArgumentsAdjuster(
getModularizeArgumentsAdjuster(ModUtil->Dependencies));
ModularizeFrontendActionFactory Factory(Entities, *PPTracker, HadErrors);
HadErrors |= Tool.run(&Factory);
typedef SmallVector<Location, 8> LocationArray;
typedef SmallVector<LocationArray, Entry::EK_NumberOfKinds> EntryBinArray;
EntryBinArray EntryBins;
int KindIndex;
for (KindIndex = 0; KindIndex < Entry::EK_NumberOfKinds; ++KindIndex) {
LocationArray Array;
EntryBins.push_back(Array);
}
for (EntityMap::iterator E = Entities.begin(), EEnd = Entities.end();
E != EEnd; ++E) {
if (E->second.size() == 1)
continue;
for (EntryBinArray::iterator CI = EntryBins.begin(), CE = EntryBins.end();
CI != CE; ++CI) {
CI->clear();
}
for (unsigned I = 0, N = E->second.size(); I != N; ++I) {
EntryBins[E->second[I].Kind].push_back(E->second[I].Loc);
}
int KindIndex = 0;
for (EntryBinArray::iterator DI = EntryBins.begin(), DE = EntryBins.end();
DI != DE; ++DI, ++KindIndex) {
int ECount = DI->size();
if (ECount <= 1)
continue;
LocationArray::iterator FI = DI->begin();
StringRef kindName = Entry::getKindName((Entry::EntryKind)KindIndex);
errs() << "error: " << kindName << " '" << E->first
<< "' defined at multiple locations:\n";
for (LocationArray::iterator FE = DI->end(); FI != FE; ++FI) {
errs() << " " << FI->File->getName() << ":" << FI->Line << ":"
<< FI->Column << "\n";
ModUtil->addUniqueProblemFile(std::string(FI->File->getName()));
}
HadErrors = 1;
}
}
if (PPTracker->reportInconsistentMacros(errs()))
HadErrors = 1;
if (PPTracker->reportInconsistentConditionals(errs()))
HadErrors = 1;
for (auto H = Entities.HeaderContentMismatches.begin(),
HEnd = Entities.HeaderContentMismatches.end();
H != HEnd; ++H) {
if (H->second.empty()) {
errs() << "internal error: phantom header content mismatch\n";
continue;
}
HadErrors = 1;
ModUtil->addUniqueProblemFile(std::string(H->first.getName()));
errs() << "error: header '" << H->first.getName()
<< "' has different contents depending on how it was included.\n";
for (unsigned I = 0, N = H->second.size(); I != N; ++I) {
errs() << "note: '" << H->second[I].Name << "' in "
<< H->second[I].Loc.File->getName() << " at "
<< H->second[I].Loc.Line << ":" << H->second[I].Loc.Column
<< " not always provided\n";
}
}
if (DisplayFileLists) {
ModUtil->displayProblemFiles();
ModUtil->displayGoodFiles();
ModUtil->displayCombinedFiles();
}
return HadErrors;
}