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."));
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 (
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);
487 SmallVector<Entry, 2> &Entries = (*this)[Name];
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 (Preprocessor::macro_iterator M = PP.macro_begin(),
657 MEnd = PP.macro_end();
659 Location Loc(SM, M->second.getLatest()->getLocation());
667 Entities.mergeCurHeaderContents();
682 : Entities(Entities), PPTracker(preprocessorTracker),
683 HadErrors(HadErrors) {}
686 std::unique_ptr<clang::ASTConsumer>
688 return std::make_unique<CollectEntitiesConsumer>(
689 Entities, PPTracker, CI.getPreprocessor(), InFile, HadErrors);
703 : Entities(Entities), PPTracker(preprocessorTracker),
704 HadErrors(HadErrors) {}
706 std::unique_ptr<FrontendAction>
create()
override {
707 return std::make_unique<CollectEntitiesAction>(Entities, PPTracker,
718 :
public RecursiveASTVisitor<CompileCheckVisitor> {
774 std::unique_ptr<clang::ASTConsumer>
776 return std::make_unique<CompileCheckConsumer>();
784 std::unique_ptr<FrontendAction>
create()
override {
785 return std::make_unique<CompileCheckAction>();
789int main(
int Argc,
const char **Argv) {
796 for (
int ArgIndex = 1; ArgIndex < Argc; ArgIndex++) {
802 cl::ParseCommandLineOptions(Argc, Argv,
"modularize.\n");
806 cl::PrintHelpMessage();
810 std::unique_ptr<ModularizeUtilities> ModUtil;
818 if (ModUtil->loadAllHeaderListsAndDependencies())
824 ModUtil->ProblemFileNames,
842 SmallString<256> PathBuf;
843 sys::fs::current_path(PathBuf);
844 std::unique_ptr<CompilationDatabase> Compilations;
846 new FixedCompilationDatabase(Twine(PathBuf),
CC1Arguments));
849 std::unique_ptr<PreprocessorTracker> PPTracker(
862 for (
auto &CompileCheckFile : ModUtil->HeaderFileNames) {
863 llvm::SmallVector<std::string, 32> CompileCheckFileArray;
864 CompileCheckFileArray.push_back(CompileCheckFile);
865 ClangTool CompileCheckTool(*Compilations, CompileCheckFileArray);
866 CompileCheckTool.appendArgumentsAdjuster(
868 int CompileCheckFileErrors = 0;
871 CompileCheckFileErrors |= CompileCheckTool.run(&CompileCheckFactory);
872 if (CompileCheckFileErrors != 0) {
873 ModUtil->addUniqueProblemFile(CompileCheckFile);
877 ModUtil->addNoCompileErrorsFile(CompileCheckFile);
882 ClangTool Tool(*Compilations,
884 Tool.appendArgumentsAdjuster(
887 HadErrors |= Tool.run(&Factory);
890 typedef SmallVector<Location, 8> LocationArray;
891 typedef SmallVector<LocationArray, Entry::EK_NumberOfKinds> EntryBinArray;
892 EntryBinArray EntryBins;
896 EntryBins.push_back(Array);
900 for (EntityMap::iterator E = Entities.begin(), EEnd = Entities.end();
903 if (E->second.size() == 1)
906 for (EntryBinArray::iterator CI = EntryBins.begin(), CE = EntryBins.end();
912 for (
unsigned I = 0, N = E->second.size(); I != N; ++I) {
913 EntryBins[E->second[I].Kind].push_back(E->second[I].Loc);
917 for (EntryBinArray::iterator DI = EntryBins.begin(), DE = EntryBins.end();
918 DI != DE; ++DI, ++KindIndex) {
919 int ECount = DI->size();
923 LocationArray::iterator FI = DI->begin();
925 errs() <<
"error: " << kindName <<
" '" << E->first
926 <<
"' defined at multiple locations:\n";
927 for (LocationArray::iterator FE = DI->end(); FI != FE; ++FI) {
928 errs() <<
" " << FI->File->getName() <<
":" << FI->Line <<
":"
929 << FI->Column <<
"\n";
930 ModUtil->addUniqueProblemFile(std::string(FI->File->getName()));
938 if (PPTracker->reportInconsistentMacros(errs()))
943 if (PPTracker->reportInconsistentConditionals(errs()))
953 if (H->second.empty()) {
954 errs() <<
"internal error: phantom header content mismatch\n";
959 ModUtil->addUniqueProblemFile(std::string(H->first.getName()));
960 errs() <<
"error: header '" << H->first.getName()
961 <<
"' has different contents depending on how it was included.\n";
962 for (
unsigned I = 0, N = H->second.size(); I != N; ++I) {
963 errs() <<
"note: '" << H->second[I].Name <<
"' in "
964 << H->second[I].Loc.File->getName() <<
" at "
965 << H->second[I].Loc.Line <<
":" << H->second[I].Loc.Column
966 <<
" not always provided\n";
971 ModUtil->displayProblemFiles();
972 ModUtil->displayGoodFiles();
973 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)