230#include "clang/AST/ASTConsumer.h"
231#include "clang/AST/ASTContext.h"
232#include "clang/AST/RecursiveASTVisitor.h"
233#include "clang/Basic/SourceManager.h"
234#include "clang/Driver/Options.h"
235#include "clang/Frontend/CompilerInstance.h"
236#include "clang/Frontend/FrontendAction.h"
237#include "clang/Frontend/FrontendActions.h"
238#include "clang/Lex/Preprocessor.h"
239#include "clang/Tooling/CompilationDatabase.h"
240#include "clang/Tooling/Tooling.h"
241#include "llvm/Option/Arg.h"
242#include "llvm/Option/ArgList.h"
243#include "llvm/Option/OptTable.h"
244#include "llvm/Option/Option.h"
245#include "llvm/Support/CommandLine.h"
246#include "llvm/Support/FileSystem.h"
247#include "llvm/Support/MemoryBuffer.h"
248#include "llvm/Support/Path.h"
255using namespace clang;
256using namespace clang::driver;
257using namespace clang::driver::options;
260using namespace llvm::opt;
264static cl::list<std::string>
266 cl::desc(
"<list of one or more header list files>"),
270static cl::list<std::string>
272 cl::desc(
"<arguments to be passed to front end>..."));
276 "prefix", cl::init(
""),
278 "Prepend header file paths with this prefix."
280 " the files are considered to be relative to the header list file."));
285 "module-map-path", cl::init(
""),
286 cl::desc(
"Turn on module map output and specify output path or file name."
287 " If no path is specified and if prefix option is specified,"
288 " use prefix for file path."));
293 "problem-files-list", cl::init(
""),
295 "List of files with compilation or modularization problems for"
296 " assistant mode. This will be excluded."));
299static cl::opt<std::string>
301 cl::desc(
"Specify the name of the root module."));
308BlockCheckHeaderListOnly(
"block-check-header-list-only", cl::init(
false),
309cl::desc(
"Only warn if #include directives are inside extern or namespace"
310 " blocks if the included header is in the header list."));
313static cl::list<std::string>
315 cl::value_desc(
"path"));
319 cl::desc(
"Don't do the coverage check."));
324cl::desc(
"Only do the coverage check."));
329cl::desc(
"Display lists of good files (no compile errors), problem files,"
330 " and a combined list with problem files preceded by a '#'."));
339 llvm::opt::Visibility VisibilityMask(options::CC1Option);
340 unsigned MissingArgIndex, MissingArgCount;
341 SmallVector<const char *, 256> Argv;
342 for (
auto I = CLArgs.begin(),
E = CLArgs.end(); I !=
E; ++I)
343 Argv.push_back(I->c_str());
344 InputArgList
Args = getDriverOptTable().ParseArgs(
345 Argv, MissingArgIndex, MissingArgCount, VisibilityMask);
346 std::vector<std::string> Inputs =
Args.getAllArgValues(OPT_INPUT);
353static ArgumentsAdjuster
355 return [&Dependencies](
const CommandLineArguments &
Args,
359 CommandLineArguments NewArgs(
Args);
360 if (
int Count = FileDependents.size()) {
361 for (
int Index = 0; Index < Count; ++Index) {
362 NewArgs.push_back(
"-include");
363 std::string File(std::string(
"\"") + FileDependents[Index] +
365 NewArgs.push_back(FileDependents[Index]);
369 NewArgs.insert(NewArgs.begin() + 1,
"-w");
371 if (!llvm::is_contained(NewArgs,
"-x")) {
372 NewArgs.insert(NewArgs.begin() + 2,
"-x");
373 NewArgs.insert(NewArgs.begin() + 3,
"c++");
389 Loc = SM.getExpansionLoc(
Loc);
393 std::pair<FileID, unsigned> Decomposed = SM.getDecomposedLoc(
Loc);
394 File = SM.getFileEntryRefForID(Decomposed.first);
398 Line = SM.getLineNumber(Decomposed.first, Decomposed.second);
399 Column = SM.getColumnNumber(Decomposed.first, Decomposed.second);
402 operator bool()
const {
return File !=
nullptr; }
413 if (
X.File != Y.
File)
414 return X.File < Y.
File;
415 if (
X.Line != Y.
Line)
416 return X.Line < Y.
Line;
455 llvm_unreachable(
"invalid Entry kind");
463 return X.Loc == Y.
Loc &&
X.Name == Y.
Name;
484class EntityMap :
public std::map<std::string, SmallVector<Entry, 2>> {
491 CurHeaderContents[*
Loc.File].push_back(HE);
494 SmallVector<Entry, 2> &Entries = (*this)[
Name];
495 for (
unsigned I = 0, N = Entries.size(); I != N; ++I) {
502 Entries.push_back(
E);
506 for (
auto H = CurHeaderContents.begin(), HEnd = CurHeaderContents.end();
509 llvm::sort(H->second);
512 auto KnownH = AllHeaderContents.find(H->first);
513 if (KnownH == AllHeaderContents.end()) {
515 AllHeaderContents.insert(*H);
520 if (H->second == KnownH->second)
524 std::set_symmetric_difference(
525 H->second.begin(), H->second.end(), KnownH->second.begin(),
526 KnownH->second.end(),
530 CurHeaderContents.clear();
534 DenseMap<FileEntryRef, HeaderContents> CurHeaderContents;
535 DenseMap<FileEntryRef, HeaderContents> AllHeaderContents;
539 :
public RecursiveASTVisitor<CollectEntitiesVisitor> {
544 : SM(SM), Entities(Entities), PP(PP), PPTracker(PPTracker),
545 HadErrors(HadErrors) {}
574 SourceRange BlockRange = D->getSourceRange();
575 const char *LinkageLabel;
576 switch (D->getLanguage()) {
577 case LinkageSpecLanguageIDs::C:
578 LinkageLabel =
"extern \"C\" {}";
580 case LinkageSpecLanguageIDs::CXX:
581 LinkageLabel =
"extern \"C++\" {}";
592 SourceRange BlockRange = D->getSourceRange();
593 std::string
Label(
"namespace ");
594 Label += D->getName();
605 if (!ND->getDeclContext()->isFileContext())
609 if (isa<NamespaceDecl>(ND) || isa<UsingDirectiveDecl>(ND) ||
610 isa<NamespaceAliasDecl>(ND) ||
611 isa<ClassTemplateSpecializationDecl>(ND) || isa<UsingDecl>(ND) ||
612 isa<ClassTemplateDecl>(ND) || isa<TemplateTypeParmDecl>(ND) ||
613 isa<TypeAliasTemplateDecl>(ND) || isa<UsingShadowDecl>(ND) ||
614 isa<FunctionDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
616 !cast<TagDecl>(ND)->isThisDeclarationADefinition()))
620 if (!ND->getDeclName())
625 llvm::raw_string_ostream
OS(
Name);
626 ND->printQualifiedName(
OS);
651 Preprocessor &PP, StringRef InFile,
int &HadErrors)
652 : Entities(Entities), PPTracker(preprocessorTracker), PP(PP),
653 HadErrors(HadErrors) {
660 SourceManager &SM = Ctx.getSourceManager();
664 .TraverseDecl(Ctx.getTranslationUnitDecl());
667 for (Preprocessor::macro_iterator
M = PP.macro_begin(),
668 MEnd = PP.macro_end();
693 : Entities(Entities), PPTracker(preprocessorTracker),
694 HadErrors(HadErrors) {}
697 std::unique_ptr<clang::ASTConsumer>
699 return std::make_unique<CollectEntitiesConsumer>(
700 Entities, PPTracker,
CI.getPreprocessor(), InFile, HadErrors);
714 : Entities(Entities), PPTracker(preprocessorTracker),
715 HadErrors(HadErrors) {}
717 std::unique_ptr<FrontendAction>
create()
override {
718 return std::make_unique<CollectEntitiesAction>(Entities, PPTracker,
785 std::unique_ptr<clang::ASTConsumer>
787 return std::make_unique<CompileCheckConsumer>();
795 std::unique_ptr<FrontendAction>
create()
override {
796 return std::make_unique<CompileCheckAction>();
800int main(
int Argc,
const char **Argv) {
807 for (
int ArgIndex = 1; ArgIndex < Argc; ArgIndex++) {
813 cl::ParseCommandLineOptions(Argc, Argv,
"modularize.\n");
817 cl::PrintHelpMessage();
821 std::unique_ptr<ModularizeUtilities> ModUtil;
829 if (ModUtil->loadAllHeaderListsAndDependencies())
835 ModUtil->ProblemFileNames,
853 SmallString<256> PathBuf;
854 sys::fs::current_path(PathBuf);
855 std::unique_ptr<CompilationDatabase> Compilations;
857 new FixedCompilationDatabase(Twine(PathBuf),
CC1Arguments));
860 std::unique_ptr<PreprocessorTracker> PPTracker(
862 BlockCheckHeaderListOnly));
873 for (
auto &CompileCheckFile : ModUtil->HeaderFileNames) {
874 llvm::SmallVector<std::string, 32> CompileCheckFileArray;
875 CompileCheckFileArray.push_back(CompileCheckFile);
876 ClangTool CompileCheckTool(*Compilations, CompileCheckFileArray);
877 CompileCheckTool.appendArgumentsAdjuster(
879 int CompileCheckFileErrors = 0;
882 CompileCheckFileErrors |= CompileCheckTool.run(&CompileCheckFactory);
883 if (CompileCheckFileErrors != 0) {
884 ModUtil->addUniqueProblemFile(CompileCheckFile);
888 ModUtil->addNoCompileErrorsFile(CompileCheckFile);
893 ClangTool Tool(*Compilations,
895 Tool.appendArgumentsAdjuster(
898 HadErrors |= Tool.run(&Factory);
901 typedef SmallVector<Location, 8> LocationArray;
902 typedef SmallVector<LocationArray, Entry::EK_NumberOfKinds> EntryBinArray;
903 EntryBinArray EntryBins;
907 EntryBins.push_back(Array);
911 for (EntityMap::iterator
E = Entities.begin(), EEnd = Entities.end();
914 if (
E->second.size() == 1)
917 for (EntryBinArray::iterator
CI = EntryBins.begin(),
CE = EntryBins.end();
923 for (
unsigned I = 0, N =
E->second.size(); I != N; ++I) {
924 EntryBins[
E->second[I].Kind].push_back(
E->second[I].Loc);
928 for (EntryBinArray::iterator DI = EntryBins.begin(), DE = EntryBins.end();
929 DI != DE; ++DI, ++KindIndex) {
930 int ECount = DI->size();
934 LocationArray::iterator FI = DI->begin();
936 errs() <<
"error: " << kindName <<
" '" <<
E->first
937 <<
"' defined at multiple locations:\n";
938 for (LocationArray::iterator FE = DI->end(); FI != FE; ++FI) {
939 errs() <<
" " << FI->File->getName() <<
":" << FI->Line <<
":"
940 << FI->Column <<
"\n";
941 ModUtil->addUniqueProblemFile(std::string(FI->File->getName()));
949 if (PPTracker->reportInconsistentMacros(errs()))
954 if (PPTracker->reportInconsistentConditionals(errs()))
964 if (H->second.empty()) {
965 errs() <<
"internal error: phantom header content mismatch\n";
970 ModUtil->addUniqueProblemFile(std::string(H->first.getName()));
971 errs() <<
"error: header '" << H->first.getName()
972 <<
"' has different contents depending on how it was included.\n";
973 for (
unsigned I = 0, N = H->second.size(); I != N; ++I) {
974 errs() <<
"note: '" << H->second[I].Name <<
"' in "
975 << H->second[I].Loc.File->getName() <<
" at "
976 << H->second[I].Loc.Line <<
":" << H->second[I].Loc.Column
977 <<
" not always provided\n";
982 ModUtil->displayProblemFiles();
983 ModUtil->displayGoodFiles();
984 ModUtil->displayCombinedFiles();
llvm::SmallString< 256U > Name
ModularizeUtilities class definition.
static cl::list< std::string > IncludePaths("I", cl::desc("Include path for coverage check."), cl::value_desc("path"))
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< 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 '#'."))
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."))
std::vector< HeaderEntry > HeaderContents
static cl::opt< bool > CoverageCheckOnly("coverage-check-only", cl::init(false), cl::desc("Only do the coverage check."))
static cl::opt< std::string > RootModule("root-module", cl::init(""), cl::desc("Specify the name of the root module."))
static cl::opt< bool > NoCoverageCheck("no-coverage-check", cl::desc("Don't do the coverage check."))
static ArgumentsAdjuster getModularizeArgumentsAdjuster(DependencyMap &Dependencies)
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::list< std::string > ListFileNames(cl::Positional, cl::value_desc("list"), cl::desc("<list of one or more header list files>"), cl::CommaSeparated)
int main(int Argc, const char **Argv)
static std::string findInputFile(const CommandLineArguments &CLArgs)
static cl::list< std::string > CC1Arguments(cl::ConsumeAfter, cl::desc("<arguments to be passed to front end>..."))
Common definitions for Modularize.
llvm::SmallVector< std::string, 4 > DependentsVector
bool createModuleMap(llvm::StringRef ModuleMapPath, llvm::ArrayRef< std::string > HeaderFileNames, llvm::ArrayRef< std::string > ProblemFileNames, DependencyMap &Dependencies, llvm::StringRef HeaderPrefix, llvm::StringRef RootModuleName)
Create the module map file.
llvm::StringMap< DependentsVector > DependencyMap
Macro expansions and preprocessor conditional consistency checker.
const google::protobuf::Message & M
std::unique_ptr< CompilerInvocation > CI
llvm::raw_string_ostream OS
std::unique_ptr< clang::ASTConsumer > CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override
CollectEntitiesAction(EntityMap &Entities, PreprocessorTracker &preprocessorTracker, int &HadErrors)
CollectEntitiesConsumer(EntityMap &Entities, PreprocessorTracker &preprocessorTracker, Preprocessor &PP, StringRef InFile, int &HadErrors)
void HandleTranslationUnit(ASTContext &Ctx) override
~CollectEntitiesConsumer() override
bool TraverseStmt(Stmt *S)
bool VisitNamespaceDecl(const NamespaceDecl *D)
bool TraverseConstructorInitializer(CXXCtorInitializer *Init)
bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS)
bool TraverseTemplateArguments(ArrayRef< TemplateArgument >)
bool TraverseTypeLoc(TypeLoc TL)
bool TraverseDeclarationNameInfo(DeclarationNameInfo NameInfo)
CollectEntitiesVisitor(SourceManager &SM, EntityMap &Entities, Preprocessor &PP, PreprocessorTracker &PPTracker, int &HadErrors)
bool TraverseTemplateArgument(const TemplateArgument &Arg)
bool VisitNamedDecl(NamedDecl *ND)
bool TraverseType(QualType T)
bool TraverseTemplateArgumentLoc(const TemplateArgumentLoc &ArgLoc)
bool TraverseLambdaCapture(LambdaExpr *LE, const LambdaCapture *C, Expr *Init)
bool VisitLinkageSpecDecl(LinkageSpecDecl *D)
bool TraverseNestedNameSpecifier(NestedNameSpecifier *NNS)
bool TraverseTemplateName(TemplateName Template)
std::unique_ptr< clang::ASTConsumer > CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override
void HandleTranslationUnit(ASTContext &Ctx) override
CompileCheckFrontendActionFactory()
std::unique_ptr< FrontendAction > create() override
bool TraverseStmt(Stmt *S)
bool TraverseType(QualType T)
bool TraverseDeclarationNameInfo(DeclarationNameInfo NameInfo)
bool TraverseTypeLoc(TypeLoc TL)
bool TraverseTemplateArguments(ArrayRef< TemplateArgument >)
bool TraverseTemplateArgument(const TemplateArgument &Arg)
bool VisitLinkageSpecDecl(LinkageSpecDecl *D)
bool VisitNamespaceDecl(const NamespaceDecl *D)
bool TraverseNestedNameSpecifier(NestedNameSpecifier *NNS)
bool TraverseTemplateArgumentLoc(const TemplateArgumentLoc &ArgLoc)
bool TraverseLambdaCapture(LambdaExpr *LE, const LambdaCapture *C, Expr *Init)
bool VisitNamedDecl(NamedDecl *ND)
bool TraverseTemplateName(TemplateName Template)
bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS)
bool TraverseConstructorInitializer(CXXCtorInitializer *Init)
void mergeCurHeaderContents()
void add(const std::string &Name, enum Entry::EntryKind Kind, Location Loc)
DenseMap< FileEntryRef, HeaderContents > HeaderContentMismatches
std::unique_ptr< FrontendAction > create() override
ModularizeFrontendActionFactory(EntityMap &Entities, PreprocessorTracker &preprocessorTracker, int &HadErrors)
static std::string getCanonicalPath(llvm::StringRef FilePath)
Convert header path to canonical form.
static ModularizeUtilities * createModularizeUtilities(std::vector< std::string > &InputPaths, llvm::StringRef Prefix, llvm::StringRef ProblemFilesListPath)
Create instance of ModularizeUtilities.
Preprocessor tracker for modularize.
virtual bool checkForIncludesInBlock(clang::Preprocessor &PP, clang::SourceRange BlockSourceRange, const char *BlockIdentifierMessage, llvm::raw_ostream &OS)=0
virtual void handlePreprocessorEntry(clang::Preprocessor &PP, llvm::StringRef RootHeaderFile)=0
static PreprocessorTracker * create(llvm::SmallVector< std::string, 32 > &Headers, bool DoBlockCheckHeaderListOnly)
virtual void handlePreprocessorExit()=0
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
Some operations such as code completion produce a set of candidates.
enum Entry::EntryKind Kind
friend bool operator<=(const Location &X, const Location &Y)
friend bool operator==(const Location &X, const Location &Y)
friend bool operator>=(const Location &X, const Location &Y)
Location(SourceManager &SM, SourceLocation Loc)
friend bool operator<(const Location &X, const Location &Y)
friend bool operator!=(const Location &X, const Location &Y)
OptionalFileEntryRef File
friend bool operator>(const Location &X, const Location &Y)