16 #include "clang/Basic/SourceManager.h"
17 #include "clang/Driver/Options.h"
18 #include "clang/Frontend/CompilerInstance.h"
19 #include "clang/Frontend/FrontendActions.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/Support/FileUtilities.h"
23 #include "llvm/Support/MemoryBuffer.h"
24 #include "llvm/Support/Path.h"
25 #include "llvm/Support/raw_ostream.h"
28 using namespace clang;
30 using namespace Modularize;
35 class ModuleMapTargetOptions :
public clang::TargetOptions {
37 ModuleMapTargetOptions() { Triple = llvm::sys::getDefaultTargetTriple(); }
44 ModularizeUtilities::ModularizeUtilities(std::vector<std::string> &InputPaths,
45 llvm::StringRef Prefix,
46 llvm::StringRef ProblemFilesListPath)
48 ProblemFilesPath(ProblemFilesListPath), HasModuleMap(false),
49 MissingHeaderCount(0),
51 LangOpts(new LangOptions()), DiagIDs(new DiagnosticIDs()),
52 DiagnosticOpts(new DiagnosticOptions()),
53 DC(llvm::errs(), DiagnosticOpts.get()),
55 new DiagnosticsEngine(DiagIDs, DiagnosticOpts.get(), &DC, false)),
56 TargetOpts(new ModuleMapTargetOptions()),
57 Target(TargetInfo::CreateTargetInfo(*Diagnostics, TargetOpts)),
58 FileMgr(new FileManager(FileSystemOpts)),
59 SourceMgr(new SourceManager(*Diagnostics, *FileMgr, false)),
60 HeaderInfo(new HeaderSearch(std::make_shared<HeaderSearchOptions>(),
67 std::vector<std::string> &InputPaths, llvm::StringRef Prefix,
68 llvm::StringRef ProblemFilesListPath) {
77 llvm::StringRef InputPath = *I;
79 if (InputPath.endswith(
".modulemap")) {
87 errs() <<
"modularize: error: Unable to get header list '" << InputPath
88 <<
"': " << EC.message() <<
'\n';
97 errs() <<
"modularize: error: Unable to get problem header list '" <<
ProblemFilesPath
98 <<
"': " << EC.message() <<
'\n';
102 return std::error_code();
121 for (ModuleMapIndex = 0; ModuleMapIndex < ModuleMapCount; ++ModuleMapIndex) {
122 std::unique_ptr<clang::ModuleMap> &ModMap =
ModuleMaps[ModuleMapIndex];
126 std::error_code LocalEC = Checker->doChecks();
127 if (LocalEC.value() > 0)
135 llvm::StringRef InputPath) {
138 SmallString<256> HeaderDirectory(InputPath);
139 llvm::sys::path::remove_filename(HeaderDirectory);
140 SmallString<256> CurrentDirectory;
141 llvm::sys::fs::current_path(CurrentDirectory);
148 ErrorOr<std::unique_ptr<MemoryBuffer>> listBuffer =
149 MemoryBuffer::getFile(InputPath);
150 if (std::error_code EC = listBuffer.getError())
154 SmallVector<StringRef, 32>
Strings;
155 listBuffer.get()->getBuffer().split(Strings,
"\n", -1,
false);
158 for (SmallVectorImpl<StringRef>::iterator I = Strings.begin(),
161 StringRef
Line = I->trim();
163 if (Line.empty() || (Line[0] ==
'#'))
165 std::pair<StringRef, StringRef> TargetAndDependents = Line.split(
':');
166 SmallString<256> HeaderFileName;
168 if (llvm::sys::path::is_absolute(TargetAndDependents.first))
169 llvm::sys::path::native(TargetAndDependents.first, HeaderFileName);
171 if (HeaderDirectory.size() != 0)
172 HeaderFileName = HeaderDirectory;
174 HeaderFileName = CurrentDirectory;
175 llvm::sys::path::append(HeaderFileName, TargetAndDependents.first);
176 llvm::sys::path::native(HeaderFileName);
180 SmallVector<StringRef, 4> DependentsList;
181 TargetAndDependents.second.split(DependentsList,
" ", -1,
false);
182 int Count = DependentsList.size();
183 for (
int Index = 0; Index < Count; ++Index) {
184 SmallString<256> Dependent;
185 if (llvm::sys::path::is_absolute(DependentsList[Index]))
186 Dependent = DependentsList[Index];
188 if (HeaderDirectory.size() != 0)
189 Dependent = HeaderDirectory;
191 Dependent = CurrentDirectory;
192 llvm::sys::path::append(Dependent, DependentsList[Index]);
194 llvm::sys::path::native(Dependent);
203 return std::error_code();
208 llvm::StringRef InputPath) {
211 SmallString<256> HeaderDirectory(InputPath);
212 llvm::sys::path::remove_filename(HeaderDirectory);
213 SmallString<256> CurrentDirectory;
214 llvm::sys::fs::current_path(CurrentDirectory);
221 ErrorOr<std::unique_ptr<MemoryBuffer>> listBuffer =
222 MemoryBuffer::getFile(InputPath);
223 if (std::error_code EC = listBuffer.getError())
227 SmallVector<StringRef, 32>
Strings;
228 listBuffer.get()->getBuffer().split(Strings,
"\n", -1,
false);
231 for (SmallVectorImpl<StringRef>::iterator I = Strings.begin(),
234 StringRef
Line = I->trim();
236 if (Line.empty() || (Line[0] ==
'#'))
238 SmallString<256> HeaderFileName;
240 if (llvm::sys::path::is_absolute(Line))
241 llvm::sys::path::native(Line, HeaderFileName);
243 if (HeaderDirectory.size() != 0)
244 HeaderFileName = HeaderDirectory;
246 HeaderFileName = CurrentDirectory;
247 llvm::sys::path::append(HeaderFileName, Line);
248 llvm::sys::path::native(HeaderFileName);
255 return std::error_code();
260 llvm::StringRef InputPath) {
262 const FileEntry *ModuleMapEntry =
263 SourceMgr->getFileManager().getFile(InputPath);
266 if (!ModuleMapEntry) {
267 llvm::errs() <<
"error: File \"" << InputPath <<
"\" not found.\n";
268 return std::error_code(1, std::generic_category());
276 const DirectoryEntry *Dir = ModuleMapEntry->getDir();
277 StringRef DirName(Dir->getName());
278 if (llvm::sys::path::filename(DirName) ==
"Modules") {
279 DirName = llvm::sys::path::parent_path(DirName);
280 if (DirName.endswith(
".framework"))
281 Dir =
FileMgr->getDirectory(DirName);
284 assert(Dir &&
"parent must exist");
287 std::unique_ptr<ModuleMap> ModMap;
292 if (ModMap->parseModuleMapFile(ModuleMapEntry,
false, Dir)) {
293 return std::error_code(1, std::generic_category());
303 return std::error_code(1, std::generic_category());
313 return std::error_code(1, std::generic_category());
315 return std::error_code();
322 for (ModuleMap::module_iterator I = ModMap->module_begin(),
323 E = ModMap->module_end();
345 for (
auto MI = Mod.submodule_begin(), MIEnd = Mod.submodule_end();
349 if (
const FileEntry *UmbrellaHeader = Mod.getUmbrellaHeader().Entry) {
356 else if (
const DirectoryEntry *UmbrellaDir = Mod.getUmbrellaDir().Entry) {
358 if (Mod.Headers->size() == 0) {
370 int NormalHeaderCount = Mod.Headers[clang::Module::HK_Normal].size();
372 for (
int Index = 0; Index < NormalHeaderCount; ++Index) {
375 const clang::Module::Header &Header(
376 Mod.Headers[clang::Module::HK_Normal][Index]);
381 int MissingCountThisModule = Mod.MissingHeaders.size();
383 for (
int Index = 0; Index < MissingCountThisModule; ++Index) {
384 std::string MissingFile = Mod.MissingHeaders[Index].FileName;
385 SourceLocation
Loc = Mod.MissingHeaders[Index].FileNameLoc;
387 <<
": error : Header not found: " << MissingFile <<
"\n";
399 SmallString<256>
Directory(UmbrellaDirName);
402 llvm::sys::fs::file_status Status;
403 for (llvm::sys::fs::directory_iterator I(Directory.str(), EC), E; I != E;
407 std::string
File(I->path());
409 llvm::sys::fs::file_type Type = Status.type();
411 if (Type == llvm::sys::fs::file_type::directory_file) {
421 Dependents.push_back(HeaderPath);
429 SmallString<128> Buffer;
430 llvm::sys::path::const_iterator B = llvm::sys::path::begin(Path),
431 E = llvm::sys::path::end(Path);
433 if (B->compare(
".") == 0) {
435 else if (B->compare(
"..") == 0)
436 llvm::sys::path::remove_filename(Buffer);
438 llvm::sys::path::append(Buffer, *B);
441 if (Path.endswith(
"/") || Path.endswith(
"\\"))
442 Buffer.append(1, Path.back());
443 return Buffer.c_str();
452 std::replace(Tmp.begin(), Tmp.end(),
'\\',
'/');
454 if (Tmp2.startswith(
"./"))
455 Tmp = Tmp2.substr(2);
465 StringRef Extension = llvm::sys::path::extension(FileName);
466 if (Extension.size() == 0)
468 if (Extension.equals_lower(
".h"))
470 if (Extension.equals_lower(
".inc"))
482 sys::path::remove_filename(Directory);
483 if (Directory.size() == 0)
485 return Directory.str();
494 if (TestFilePath == FilePath)
497 ProblemFileNames.push_back(FilePath);
509 errs() <<
"\nThese are the files with possible errors:\n\n";
511 errs() << ProblemFile <<
"\n";
517 errs() <<
"\nThese are the files with no detected errors:\n\n";
521 if (ProblemFile == GoodFile) {
527 errs() << GoodFile <<
"\n";
534 "\nThese are the combined files, with problem files preceded by #:\n\n";
538 if (ProblemFile ==
File) {
543 errs() << (Good ?
"" :
"#") <<
File <<
"\n";
ModularizeUtilities(std::vector< std::string > &InputPaths, llvm::StringRef Prefix, llvm::StringRef ProblemFilesListPath)
Constructor.
SourceLocation Loc
'#' location in the include directive
void displayGoodFiles()
List files with no problems.
DependencyMap Dependencies
Map of top-level header file dependencies.
std::error_code doCoverageCheck(std::vector< std::string > &IncludePaths, llvm::ArrayRef< std::string > CommandLine)
Do coverage checks.
llvm::IntrusiveRefCntPtr< clang::DiagnosticsEngine > Diagnostics
Diagnostic engine.
static std::string getCanonicalPath(llvm::StringRef FilePath)
Convert header path to canonical form.
llvm::SmallVector< std::string, 4 > DependentsVector
void displayCombinedFiles()
List files with problem files commented out.
std::error_code loadProblemHeaderList(llvm::StringRef InputPath)
Load problem header list.
static std::string getDirectoryFromPath(llvm::StringRef Path)
Get directory path component from file path.
bool HasModuleMap
True if we have module maps.
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."))
std::error_code loadSingleHeaderListsAndDependencies(llvm::StringRef InputPath)
Load single header list and dependencies.
llvm::IntrusiveRefCntPtr< clang::TargetInfo > Target
Target information.
static ModularizeUtilities * createModularizeUtilities(std::vector< std::string > &InputPaths, llvm::StringRef Prefix, llvm::StringRef ProblemFilesListPath)
Create instance of ModularizeUtilities.
llvm::IntrusiveRefCntPtr< clang::FileManager > FileMgr
File system manager.
clang::TextDiagnosticPrinter DC
Diagnostic consumer.
std::unique_ptr< clang::HeaderSearch > HeaderInfo
Header search manager.
std::vector< HeaderHandle > Path
ModularizeUtilities class definition.
std::shared_ptr< clang::LangOptions > LangOpts
Options controlling the language variant.
bool collectModuleMapHeaders(clang::ModuleMap *ModMap)
Collect module Map headers.
llvm::StringRef ProblemFilesPath
The path of problem files list file.
static cl::opt< std::string > Directory(cl::Positional, cl::Required, cl::desc("<Search Root Directory>"))
Definitions for CoverageChecker.
int MissingHeaderCount
Missing header count.
std::error_code loadModuleMap(llvm::StringRef InputPath)
Load single module map and extract header file list.
static std::unique_ptr< CoverageChecker > createCoverageChecker(llvm::StringRef ModuleMapPath, std::vector< std::string > &IncludePaths, llvm::ArrayRef< std::string > CommandLine, clang::ModuleMap *ModuleMap)
Create instance of CoverageChecker.
std::error_code loadAllHeaderListsAndDependencies()
Load header list and dependencies.
llvm::SmallVector< std::string, 32 > ProblemFileNames
List of header files with problems.
llvm::SmallVector< std::string, 32 > GoodFileNames
List of header files with no problems during the first pass, that is, no compile errors.
Modularize utilities class.
llvm::SmallVector< std::string, 32 > HeaderFileNames
List of top-level header files.
llvm::IntrusiveRefCntPtr< clang::SourceManager > SourceMgr
Source manager.
static cl::list< std::string > IncludePaths("I", cl::desc("Include path for coverage check."), cl::ZeroOrMore, cl::value_desc("path"))
llvm::StringRef HeaderPrefix
The header prefix.
bool collectModuleHeaders(const clang::Module &Mod)
Collect referenced headers from one module.
std::vector< std::unique_ptr< clang::ModuleMap > > ModuleMaps
bool collectUmbrellaHeaders(llvm::StringRef UmbrellaDirName, DependentsVector &Dependents)
Collect headers from an umbrella directory.
void addUniqueProblemFile(std::string FilePath)
Add unique problem file.
void displayProblemFiles()
List problem files.
std::vector< std::string > InputFilePaths
The input file paths.
static std::string replaceDotDot(StringRef Path)
static bool isHeader(llvm::StringRef FileName)
Check for header file extension.
void addNoCompileErrorsFile(std::string FilePath)
Add file with no compile errors.