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/Frontend/CompilerInstance.h"
235#include "clang/Frontend/FrontendAction.h"
236#include "clang/Frontend/FrontendActions.h"
237#include "clang/Lex/Preprocessor.h"
238#include "clang/Options/Options.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::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."));
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;
342 for (
const std::string &CLArg : CLArgs)
343 Argv.push_back(CLArg.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 for (
const std::string &Dep : FileDependents) {
361 NewArgs.push_back(
"-include");
362 NewArgs.push_back(Dep);
365 NewArgs.insert(NewArgs.begin() + 1,
"-w");
367 if (!llvm::is_contained(NewArgs,
"-x")) {
368 NewArgs.insert(NewArgs.begin() + 2,
"-x");
369 NewArgs.insert(NewArgs.begin() + 3,
"c++");
385 Loc = SM.getExpansionLoc(Loc);
389 std::pair<FileID, unsigned> Decomposed = SM.getDecomposedLoc(Loc);
390 File = SM.getFileEntryRefForID(Decomposed.first);
394 Line = SM.getLineNumber(Decomposed.first, Decomposed.second);
395 Column = SM.getColumnNumber(Decomposed.first, Decomposed.second);
398 explicit operator bool()
const {
return File !=
nullptr; }
409 return std::tie(
X.File,
X.Line,
X.Column) <
448 llvm_unreachable(
"invalid Entry kind");
456 return X.Loc == Y.
Loc &&
X.Name == Y.
Name;
462 return std::tie(
X.Loc,
X.Name) < std::tie(Y.
Loc, Y.
Name);
477class EntityMap :
public std::map<std::string, SmallVector<Entry, 2>> {
484 CurHeaderContents[*Loc.
File].push_back(HE);
488 for (
unsigned I = 0, N = Entries.size(); I != N; ++I) {
489 if (Entries[I].Kind == Kind && Entries[I].Loc == Loc)
494 Entry E = { Kind, Loc };
495 Entries.push_back(E);
499 for (
auto H = CurHeaderContents.begin(), HEnd = CurHeaderContents.end();
502 llvm::sort(H->second);
505 auto [KnownH, Inserted] = AllHeaderContents.insert(*H);
510 if (H->second == KnownH->second)
514 std::set_symmetric_difference(
515 H->second.begin(), H->second.end(), KnownH->second.begin(),
516 KnownH->second.end(),
520 CurHeaderContents.clear();
524 DenseMap<FileEntryRef, HeaderContents> CurHeaderContents;
525 DenseMap<FileEntryRef, HeaderContents> AllHeaderContents;
529 :
public RecursiveASTVisitor<CollectEntitiesVisitor> {
534 : SM(SM), Entities(Entities), PP(PP), PPTracker(PPTracker),
535 HadErrors(HadErrors) {}
564 SourceRange BlockRange = D->getSourceRange();
565 const char *LinkageLabel;
566 switch (D->getLanguage()) {
567 case LinkageSpecLanguageIDs::C:
568 LinkageLabel =
"extern \"C\" {}";
570 case LinkageSpecLanguageIDs::CXX:
571 LinkageLabel =
"extern \"C++\" {}";
574 if (!PPTracker.checkForIncludesInBlock(PP, BlockRange, LinkageLabel,
582 SourceRange BlockRange = D->getSourceRange();
583 std::string Label(
"namespace ");
584 Label += D->getName();
586 if (!PPTracker.checkForIncludesInBlock(PP, BlockRange, Label.c_str(),
595 if (!ND->getDeclContext()->isFileContext())
599 if (isa<NamespaceDecl>(ND) || isa<UsingDirectiveDecl>(ND) ||
600 isa<NamespaceAliasDecl>(ND) ||
601 isa<ClassTemplateSpecializationDecl>(ND) || isa<UsingDecl>(ND) ||
602 isa<ClassTemplateDecl>(ND) || isa<TemplateTypeParmDecl>(ND) ||
603 isa<TypeAliasTemplateDecl>(ND) || isa<UsingShadowDecl>(ND) ||
604 isa<FunctionDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
606 !cast<TagDecl>(ND)->isThisDeclarationADefinition()))
610 if (!ND->getDeclName())
615 llvm::raw_string_ostream OS(Name);
616 ND->printQualifiedName(OS);
620 Location Loc(SM, ND->getLocation());
640 Preprocessor &PP, StringRef InFile,
int &HadErrors)
641 : Entities(Entities), PPTracker(preprocessorTracker), PP(PP),
642 HadErrors(HadErrors) {
643 PPTracker.handlePreprocessorEntry(PP, InFile);
649 SourceManager &SM = Ctx.getSourceManager();
653 .TraverseDecl(Ctx.getTranslationUnitDecl());
656 for (
const auto &M : PP.macros()) {
657 Location Loc(SM, M.second.getLatest()->getLocation());
665 Entities.mergeCurHeaderContents();
680 : Entities(Entities), PPTracker(preprocessorTracker),
681 HadErrors(HadErrors) {}
684 std::unique_ptr<clang::ASTConsumer>
686 return std::make_unique<CollectEntitiesConsumer>(
687 Entities, PPTracker, CI.getPreprocessor(), InFile, HadErrors);
701 : Entities(Entities), PPTracker(preprocessorTracker),
702 HadErrors(HadErrors) {}
704 std::unique_ptr<FrontendAction>
create()
override {
705 return std::make_unique<CollectEntitiesAction>(Entities, PPTracker,
716 :
public RecursiveASTVisitor<CompileCheckVisitor> {
772 std::unique_ptr<clang::ASTConsumer>
774 return std::make_unique<CompileCheckConsumer>();
782 std::unique_ptr<FrontendAction>
create()
override {
783 return std::make_unique<CompileCheckAction>();
787int main(
int Argc,
const char **Argv) {
794 for (
int ArgIndex = 1; ArgIndex < Argc; ArgIndex++) {
800 cl::ParseCommandLineOptions(Argc, Argv,
"modularize.\n");
804 cl::PrintHelpMessage();
808 std::unique_ptr<ModularizeUtilities> ModUtil;
816 if (ModUtil->loadAllHeaderListsAndDependencies())
822 ModUtil->ProblemFileNames,
840 SmallString<256> PathBuf;
841 sys::fs::current_path(PathBuf);
842 std::unique_ptr<CompilationDatabase> Compilations;
844 new FixedCompilationDatabase(Twine(PathBuf),
CC1Arguments));
847 std::unique_ptr<PreprocessorTracker> PPTracker(
860 for (
auto &CompileCheckFile : ModUtil->HeaderFileNames) {
861 llvm::SmallVector<std::string, 32> CompileCheckFileArray;
862 CompileCheckFileArray.push_back(CompileCheckFile);
863 ClangTool CompileCheckTool(*Compilations, CompileCheckFileArray);
864 CompileCheckTool.appendArgumentsAdjuster(
866 int CompileCheckFileErrors = 0;
869 CompileCheckFileErrors |= CompileCheckTool.run(&CompileCheckFactory);
870 if (CompileCheckFileErrors != 0) {
871 ModUtil->addUniqueProblemFile(CompileCheckFile);
875 ModUtil->addNoCompileErrorsFile(CompileCheckFile);
880 ClangTool Tool(*Compilations,
882 Tool.appendArgumentsAdjuster(
885 HadErrors |= Tool.run(&Factory);
890 EntryBinArray EntryBins;
894 EntryBins.push_back(Array);
898 for (EntityMap::iterator E = Entities.begin(), EEnd = Entities.end();
901 if (E->second.size() == 1)
904 for (EntryBinArray::iterator CI = EntryBins.begin(), CE = EntryBins.end();
910 for (
unsigned I = 0, N = E->second.size(); I != N; ++I) {
911 EntryBins[E->second[I].Kind].push_back(E->second[I].Loc);
915 for (EntryBinArray::iterator DI = EntryBins.begin(), DE = EntryBins.end();
916 DI != DE; ++DI, ++KindIndex) {
917 int ECount = DI->size();
921 LocationArray::iterator FI = DI->begin();
923 errs() <<
"error: " << kindName <<
" '" << E->first
924 <<
"' defined at multiple locations:\n";
925 for (LocationArray::iterator FE = DI->end(); FI != FE; ++FI) {
926 errs() <<
" " << FI->File->getName() <<
":" << FI->Line <<
":"
927 << FI->Column <<
"\n";
928 ModUtil->addUniqueProblemFile(std::string(FI->File->getName()));
936 if (PPTracker->reportInconsistentMacros(errs()))
941 if (PPTracker->reportInconsistentConditionals(errs()))
951 if (H->second.empty()) {
952 errs() <<
"internal error: phantom header content mismatch\n";
957 ModUtil->addUniqueProblemFile(std::string(H->first.getName()));
958 errs() <<
"error: header '" << H->first.getName()
959 <<
"' has different contents depending on how it was included.\n";
960 for (
unsigned I = 0, N = H->second.size(); I != N; ++I) {
961 errs() <<
"note: '" << H->second[I].Name <<
"' in "
962 << H->second[I].Loc.File->getName() <<
" at "
963 << H->second[I].Loc.Line <<
":" << H->second[I].Loc.Column
964 <<
" not always provided\n";
969 ModUtil->displayProblemFiles();
970 ModUtil->displayGoodFiles();
971 ModUtil->displayCombinedFiles();
static clang::FrontendPluginRegistry::Add< clang::tidy::ClangTidyPluginAction > X("clang-tidy", "clang-tidy")
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< 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::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.
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.
static PreprocessorTracker * create(llvm::SmallVector< std::string, 32 > &Headers, bool DoBlockCheckHeaderListOnly)
===– 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)