Diag);
StringRef toFilename = lines[idx+2];
- const FileEntry *origFE = FileMgr->getFile(fromFilename);
+ llvm::ErrorOr<const FileEntry *> origFE = FileMgr->getFile(fromFilename);
if (!origFE) {
if (ignoreIfFilesChanged)
continue;
return report("File does not exist: " + fromFilename, Diag);
}
- const FileEntry *newFE = FileMgr->getFile(toFilename);
+ llvm::ErrorOr<const FileEntry *> newFE = FileMgr->getFile(toFilename);
if (!newFE) {
if (ignoreIfFilesChanged)
continue;
return report("File does not exist: " + toFilename, Diag);
}
- if ((uint64_t)origFE->getModificationTime() != timeModified) {
+ if ((uint64_t)(*origFE)->getModificationTime() != timeModified) {
if (ignoreIfFilesChanged)
continue;
return report("File was modified: " + fromFilename, Diag);
}
- pairs.push_back(std::make_pair(origFE, newFE));
+ pairs.push_back(std::make_pair(*origFE, *newFE));
}
for (unsigned i = 0, e = pairs.size(); i != e; ++i)
newOut.write(mem->getBufferStart(), mem->getBufferSize());
newOut.close();
- const FileEntry *newE = FileMgr->getFile(tempPath);
- remap(origFE, newE);
- infoOut << newE->getName() << '\n';
+ auto newE = FileMgr->getFile(tempPath);
+ if (newE) {
+ remap(origFE, *newE);
+ infoOut << (*newE)->getName() << '\n';
+ }
}
}
}
const FileEntry *FileRemapper::getOriginalFile(StringRef filePath) {
- const FileEntry *file = FileMgr->getFile(filePath);
+ const FileEntry *file = nullptr;
+ if (auto fileOrErr = FileMgr->getFile(filePath))
+ file = *fileOrErr;
// If we are updating a file that overridden an original file,
// actually update the original file.
llvm::DenseMap<const FileEntry *, const FileEntry *>::iterator
StringRef Val = ValueString->getValue(ValueStorage);
if (Key == "file") {
- const FileEntry *FE = FileMgr.getFile(Val);
- if (!FE)
+ auto FE = FileMgr.getFile(Val);
+ if (FE)
+ Entry.File = *FE;
+ else
Ignore = true;
- Entry.File = FE;
} else if (Key == "offset") {
if (Val.getAsInteger(10, Entry.Offset))
Ignore = true;
// disk again
// FIXME: We definitely want to re-use the existing MemoryBuffer, rather
// than mmap the files several times.
- const FileEntry *Entry =
+ auto Entry =
ToFileManager.getFile(Cache->OrigEntry->getName());
// FIXME: The filename may be a virtual name that does probably not
// point to a valid file and we get no Entry here. In this case try with
// the memory buffer below.
if (Entry)
- ToID = ToSM.createFileID(Entry, *ToIncludeLoc,
+ ToID = ToSM.createFileID(*Entry, *ToIncludeLoc,
FromSLoc.getFile().getFileCharacteristic());
}
}
if (!TopHeaderNames.empty()) {
for (std::vector<std::string>::iterator
I = TopHeaderNames.begin(), E = TopHeaderNames.end(); I != E; ++I) {
- if (const FileEntry *FE = FileMgr.getFile(*I))
- TopHeaders.insert(FE);
+ if (auto FE = FileMgr.getFile(*I))
+ TopHeaders.insert(*FE);
}
TopHeaderNames.clear();
}
IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
new DiagnosticOptions);
SourceMgr = llvm::make_unique<SourceManager>(*Diagnostics, *FileMgr);
- FileID ID = SourceMgr->createFileID(FileMgr->getFile(FileName),
+ FileID ID = SourceMgr->createFileID(*FileMgr->getFile(FileName),
SourceLocation(), clang::SrcMgr::C_User);
assert(ID.isValid());
SourceMgr->setMainFileID(ID);
if (D.isLocationAvailable()) {
D.getLocation(Filename, Line, Column);
if (Line > 0) {
- const FileEntry *FE = FileMgr.getFile(Filename);
+ auto FE = FileMgr.getFile(Filename);
if (!FE)
FE = FileMgr.getFile(D.getAbsolutePath());
if (FE) {
// If -gcolumn-info was not used, Column will be 0. This upsets the
// source manager, so pass 1 if Column is not set.
- DILoc = SourceMgr.translateFileLineCol(FE, Line, Column ? Column : 1);
+ DILoc = SourceMgr.translateFileLineCol(*FE, Line, Column ? Column : 1);
}
}
BadDebugInfo = DILoc.isInvalid();
// Rebuild the StoredDiagnostic.
if (SD.Filename.empty())
continue;
- const FileEntry *FE = FileMgr.getFile(SD.Filename);
+ auto FE = FileMgr.getFile(SD.Filename);
if (!FE)
continue;
SourceLocation FileLoc;
auto ItFileID = PreambleSrcLocCache.find(SD.Filename);
if (ItFileID == PreambleSrcLocCache.end()) {
- FileID FID = SrcMgr.translateFile(FE);
+ FileID FID = SrcMgr.translateFile(*FE);
FileLoc = SrcMgr.getLocForStartOfFile(FID);
PreambleSrcLocCache[SD.Filename] = FileLoc;
} else {
StringRef PCHInclude = PPOpts.ImplicitPCHInclude;
FileManager &FileMgr = CI.getFileManager();
- const DirectoryEntry *PCHDir = FileMgr.getDirectory(PCHInclude);
+ auto PCHDir = FileMgr.getDirectory(PCHInclude);
if (!PCHDir) {
MDC->addFile(PCHInclude);
return;
std::error_code EC;
SmallString<128> DirNative;
- llvm::sys::path::native(PCHDir->getName(), DirNative);
+ llvm::sys::path::native((*PCHDir)->getName(), DirNative);
llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
SimpleASTReaderListener Validator(CI.getPreprocessor());
for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
// Remap files in the source manager (with other files).
for (const auto &RF : InitOpts.RemappedFiles) {
// Find the file that we're mapping to.
- const FileEntry *ToFile = FileMgr.getFile(RF.second);
+ auto ToFile = FileMgr.getFile(RF.second);
if (!ToFile) {
Diags.Report(diag::err_fe_remap_missing_to_file) << RF.first << RF.second;
continue;
// Create the file entry for the file that we're mapping from.
const FileEntry *FromFile =
- FileMgr.getVirtualFile(RF.first, ToFile->getSize(), 0);
+ FileMgr.getVirtualFile(RF.first, (*ToFile)->getSize(), 0);
if (!FromFile) {
Diags.Report(diag::err_fe_remap_missing_from_file) << RF.first;
continue;
// Override the contents of the "from" file with the contents of
// the "to" file.
- SourceMgr.overrideFileContents(FromFile, ToFile);
+ SourceMgr.overrideFileContents(FromFile, *ToFile);
}
SourceMgr.setOverridenFilesKeepOriginalName(
unsigned Column) {
// Tell the source manager to chop off the given file at a specific
// line and column.
- const FileEntry *Entry = PP.getFileManager().getFile(Filename);
+ auto Entry = PP.getFileManager().getFile(Filename);
if (!Entry) {
PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
<< Filename;
}
// Truncate the named file at the given line/column.
- PP.SetCodeCompletionPoint(Entry, Line, Column);
+ PP.SetCodeCompletionPoint(*Entry, Line, Column);
return false;
}
// Figure out where to get and map in the main file.
if (InputFile != "-") {
- const FileEntry *File = FileMgr.getFile(InputFile, /*OpenFile=*/true);
- if (!File) {
+ auto FileOrErr = FileMgr.getFile(InputFile, /*OpenFile=*/true);
+ if (!FileOrErr) {
Diags.Report(diag::err_fe_error_reading) << InputFile;
return false;
}
+ auto File = *FileOrErr;
// The natural SourceManager infrastructure can't currently handle named
// pipes, but we would at least like to accept them for the main
llvm::sys::path::append(PublicFilename, "module.modulemap");
else
return nullptr;
- return FileMgr.getFile(PublicFilename);
+ if (auto FE = FileMgr.getFile(PublicFilename))
+ return *FE;
+ return nullptr;
}
/// Compile a module file for the given module, using the options
if (Source != ModuleCache && !Module) {
Module = PP->getHeaderSearchInfo().lookupModule(ModuleName, true,
!IsInclusionDirective);
+ auto ModuleFile = FileMgr->getFile(ModuleFileName);
if (!Module || !Module->getASTFile() ||
- FileMgr->getFile(ModuleFileName) != Module->getASTFile()) {
+ !ModuleFile || (*ModuleFile != Module->getASTFile())) {
// Error out if Module does not refer to the file in the prebuilt
// module path.
getDiagnostics().Report(ModuleNameLoc, diag::err_module_prebuilt)
.Default(false))
continue;
- const FileEntry *Header = FileMgr.getFile(Dir->path());
+ auto Header = FileMgr.getFile(Dir->path());
// FIXME: This shouldn't happen unless there is a file system race. Is
// that worth diagnosing?
if (!Header)
// If this header is marked 'unavailable' in this module, don't include
// it.
- if (ModMap.isHeaderUnavailableInModule(Header, Module))
+ if (ModMap.isHeaderUnavailableInModule(*Header, Module))
continue;
// Compute the relative path from the directory to this file.
llvm::sys::path::append(RelativeHeader, *It);
// Include this header as part of the umbrella directory.
- Module->addTopHeader(Header);
+ Module->addTopHeader(*Header);
addHeaderInclude(RelativeHeader, Includes, LangOpts, Module->IsExternC);
}
// the module map, rather than adding it after the fact.
StringRef OriginalModuleMapName = CI.getFrontendOpts().OriginalModuleMap;
if (!OriginalModuleMapName.empty()) {
- auto *OriginalModuleMap =
+ auto OriginalModuleMap =
CI.getFileManager().getFile(OriginalModuleMapName,
/*openFile*/ true);
if (!OriginalModuleMap) {
<< OriginalModuleMapName;
return nullptr;
}
- if (OriginalModuleMap != CI.getSourceManager().getFileEntryForID(
+ if (*OriginalModuleMap != CI.getSourceManager().getFileEntryForID(
CI.getSourceManager().getMainFileID())) {
M->IsInferred = true;
CI.getPreprocessor().getHeaderSearchInfo().getModuleMap()
- .setInferredModuleAllowedBy(M, OriginalModuleMap);
+ .setInferredModuleAllowedBy(M, *OriginalModuleMap);
}
}
// Set up embedding for any specified files. Do this before we load any
// source files, including the primary module map for the compilation.
for (const auto &F : CI.getFrontendOpts().ModulesEmbedFiles) {
- if (const auto *FE = CI.getFileManager().getFile(F, /*openFile*/true))
- CI.getSourceManager().setFileIsTransient(FE);
+ if (auto FE = CI.getFileManager().getFile(F, /*openFile*/true))
+ CI.getSourceManager().setFileIsTransient(*FE);
else
CI.getDiagnostics().Report(diag::err_modules_embed_file_not_found) << F;
}
PreprocessorOptions &PPOpts = CI.getPreprocessorOpts();
StringRef PCHInclude = PPOpts.ImplicitPCHInclude;
std::string SpecificModuleCachePath = CI.getSpecificModuleCachePath();
- if (const DirectoryEntry *PCHDir = FileMgr.getDirectory(PCHInclude)) {
+ if (auto PCHDir = FileMgr.getDirectory(PCHInclude)) {
std::error_code EC;
SmallString<128> DirNative;
- llvm::sys::path::native(PCHDir->getName(), DirNative);
+ llvm::sys::path::native((*PCHDir)->getName(), DirNative);
bool Found = false;
llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC),
// If we were asked to load any module map files, do so now.
for (const auto &Filename : CI.getFrontendOpts().ModuleMapFiles) {
- if (auto *File = CI.getFileManager().getFile(Filename))
+ if (auto File = CI.getFileManager().getFile(Filename))
CI.getPreprocessor().getHeaderSearchInfo().loadModuleMapFile(
- File, /*IsSystem*/false);
+ *File, /*IsSystem*/false);
else
CI.getDiagnostics().Report(diag::err_module_map_not_found) << Filename;
}
}
// If the directory exists, add it.
- if (const DirectoryEntry *DE = FM.getDirectory(MappedPathStr)) {
+ if (auto DE = FM.getDirectory(MappedPathStr)) {
IncludePath.push_back(
- std::make_pair(Group, DirectoryLookup(DE, Type, isFramework)));
+ std::make_pair(Group, DirectoryLookup(*DE, Type, isFramework)));
return true;
}
// Check to see if this is an apple-style headermap (which are not allowed to
// be frameworks).
if (!isFramework) {
- if (const FileEntry *FE = FM.getFile(MappedPathStr)) {
- if (const HeaderMap *HM = Headers.CreateHeaderMap(FE)) {
+ if (auto FE = FM.getFile(MappedPathStr)) {
+ if (const HeaderMap *HM = Headers.CreateHeaderMap(*FE)) {
// It is a headermap, add it to the search path.
IncludePath.push_back(
std::make_pair(Group,
// Set up the builtin include directory in the module map.
SmallString<128> P = StringRef(HSOpts.ResourceDir);
llvm::sys::path::append(P, "include");
- if (const DirectoryEntry *Dir = HS.getFileMgr().getDirectory(P))
- HS.getModuleMap().setBuiltinIncludeDir(Dir);
+ if (auto Dir = HS.getFileMgr().getDirectory(P))
+ HS.getModuleMap().setBuiltinIncludeDir(*Dir);
}
Init.Realize(Lang);
SourceManager &SourceMgr = Clang->getSourceManager();
for (auto &Filename : PreambleDepCollector->getDependencies()) {
- const FileEntry *File = Clang->getFileManager().getFile(Filename);
- if (!File || File == SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()))
+ auto FileOrErr = Clang->getFileManager().getFile(Filename);
+ if (!FileOrErr ||
+ *FileOrErr == SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()))
continue;
+ auto File = *FileOrErr;
if (time_t ModTime = File->getModificationTime()) {
FilesInPreamble[File->getName()] =
PrecompiledPreamble::PreambleFileHash::createForFile(File->getSize(),
void visitModuleFile(StringRef Filename,
serialization::ModuleKind Kind) override {
- auto *File = CI.getFileManager().getFile(Filename);
+ auto File = CI.getFileManager().getFile(Filename);
assert(File && "missing file for loaded module?");
// Only rewrite each module file once.
- if (!Rewritten.insert(File).second)
+ if (!Rewritten.insert(*File).second)
return;
serialization::ModuleFile *MF =
- CI.getModuleManager()->getModuleManager().lookup(File);
- assert(File && "missing module file for loaded module?");
+ CI.getModuleManager()->getModuleManager().lookup(*File);
+ assert(MF && "missing module file for loaded module?");
// Not interested in PCH / preambles.
if (!MF->isModule())
void TextDiagnostic::emitFilename(StringRef Filename, const SourceManager &SM) {
SmallVector<char, 128> AbsoluteFilename;
if (DiagOpts->AbsolutePath) {
- const DirectoryEntry *Dir = SM.getFileManager().getDirectory(
+ auto Dir = SM.getFileManager().getDirectory(
llvm::sys::path::parent_path(Filename));
if (Dir) {
// We want to print a simplified absolute path, i. e. without "dots".
// on Windows we can just use llvm::sys::path::remove_dots(), because,
// on that system, both aforementioned paths point to the same place.
#ifdef _WIN32
- SmallString<4096> DirName = Dir->getName();
+ SmallString<4096> DirName = (*Dir)->getName();
llvm::sys::fs::make_absolute(DirName);
llvm::sys::path::native(DirName);
llvm::sys::path::remove_dots(DirName, /* remove_dot_dot */ true);
#else
- StringRef DirName = SM.getFileManager().getCanonicalName(Dir);
+ StringRef DirName = SM.getFileManager().getCanonicalName(*Dir);
#endif
llvm::sys::path::append(AbsoluteFilename, DirName,
llvm::sys::path::filename(Filename));
if (Dest.empty())
return nullptr;
- return FM.getFile(Dest);
+ if (auto File = FM.getFile(Dest))
+ return *File;
+ return nullptr;
}
StringRef HeaderMapImpl::lookupFilename(StringRef Filename,
std::string Parent = llvm::sys::path::parent_path(ModuleMapPath);
if (Parent.empty())
Parent = ".";
- auto *Dir = FileMgr.getDirectory(Parent);
+ auto Dir = FileMgr.getDirectory(Parent);
if (!Dir)
return {};
- auto DirName = FileMgr.getCanonicalName(Dir);
+ auto DirName = FileMgr.getCanonicalName(*Dir);
auto FileName = llvm::sys::path::filename(ModuleMapPath);
llvm::hash_code Hash =
SmallString<128> FrameworkDirName;
FrameworkDirName += SearchDirs[Idx].getFrameworkDir()->getName();
llvm::sys::path::append(FrameworkDirName, SearchName + ".framework");
- if (const DirectoryEntry *FrameworkDir
- = FileMgr.getDirectory(FrameworkDirName)) {
+ if (auto FrameworkDir = FileMgr.getDirectory(FrameworkDirName)) {
bool IsSystem
= SearchDirs[Idx].getDirCharacteristic() != SrcMgr::C_User;
- Module = loadFrameworkModule(ModuleName, FrameworkDir, IsSystem);
+ Module = loadFrameworkModule(ModuleName, *FrameworkDir, IsSystem);
if (Module)
break;
}
ModuleMap::KnownHeader *SuggestedModule) {
// If we have a module map that might map this header, load it and
// check whether we'll have a suggestion for a module.
- const FileEntry *File = getFileMgr().getFile(FileName, /*OpenFile=*/true);
+ auto File = getFileMgr().getFile(FileName, /*OpenFile=*/true);
if (!File)
return nullptr;
// If there is a module that corresponds to this header, suggest it.
- if (!findUsableModuleForHeader(File, Dir ? Dir : File->getDir(),
+ if (!findUsableModuleForHeader(*File, Dir ? Dir : (*File)->getDir(),
RequestingModule, SuggestedModule,
IsSystemHeaderDir))
return nullptr;
- return File;
+ return *File;
}
/// LookupFile - Lookup the specified file in this search path, returning it
Filename = StringRef(MappedName.begin(), MappedName.size());
HasBeenMapped = true;
Result = HM->LookupFile(Filename, HS.getFileMgr());
+ } else if (auto Res = HS.getFileMgr().getFile(Dest)) {
+ Result = *Res;
} else {
- Result = HS.getFileMgr().getFile(Dest);
+ Result = nullptr;
}
if (Result) {
//
// Similar issues occur when a top-level framework has moved into an
// embedded framework.
- const DirectoryEntry *TopFrameworkDir = FileMgr.getDirectory(DirName);
- DirName = FileMgr.getCanonicalName(TopFrameworkDir);
+ const DirectoryEntry *TopFrameworkDir = nullptr;
+ if (auto TopFrameworkDirOrErr = FileMgr.getDirectory(DirName))
+ TopFrameworkDir = *TopFrameworkDirOrErr;
+
+ if (TopFrameworkDir)
+ DirName = FileMgr.getCanonicalName(TopFrameworkDir);
do {
// Get the parent directory name.
DirName = llvm::sys::path::parent_path(DirName);
break;
// Determine whether this directory exists.
- const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
+ auto Dir = FileMgr.getDirectory(DirName);
if (!Dir)
break;
// framework.
if (llvm::sys::path::extension(DirName) == ".framework") {
SubmodulePath.push_back(llvm::sys::path::stem(DirName));
- TopFrameworkDir = Dir;
+ TopFrameworkDir = *Dir;
}
} while (true);
HS.IncrementFrameworkLookupCount();
// If the framework dir doesn't exist, we fail.
- const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName);
+ auto Dir = FileMgr.getDirectory(FrameworkName);
if (!Dir) return nullptr;
// Otherwise, if it does, remember that this is the right direntry for this
}
FrameworkName.append(Filename.begin()+SlashPos+1, Filename.end());
- const FileEntry *FE = FileMgr.getFile(FrameworkName,
- /*OpenFile=*/!SuggestedModule);
+
+ const FileEntry *FE = nullptr;
+ if (auto File = FileMgr.getFile(FrameworkName, /*OpenFile=*/!SuggestedModule))
+ FE = *File;
+
if (!FE) {
// Check "/System/Library/Frameworks/Cocoa.framework/PrivateHeaders/file.h"
const char *Private = "Private";
SearchPath->insert(SearchPath->begin()+OrigSize, Private,
Private+strlen(Private));
- FE = FileMgr.getFile(FrameworkName, /*OpenFile=*/!SuggestedModule);
+ if (auto File = FileMgr.getFile(FrameworkName,
+ /*OpenFile=*/!SuggestedModule))
+ FE = *File;
}
// If we found the header and are allowed to suggest a module, do so now.
bool FoundFramework = false;
do {
// Determine whether this directory exists.
- const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkPath);
+ auto Dir = FileMgr.getDirectory(FrameworkPath);
if (!Dir)
break;
++NumSubFrameworkLookups;
// If the framework dir doesn't exist, we fail.
- const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName);
+ auto Dir = FileMgr.getDirectory(FrameworkName);
if (!Dir) return nullptr;
// Otherwise, if it does, remember that this is the right direntry for this
// framework.
- CacheLookup.second.Directory = Dir;
+ CacheLookup.second.Directory = *Dir;
}
const FileEntry *FE = nullptr;
}
HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
- if (!(FE = FileMgr.getFile(HeadersFilename, /*OpenFile=*/true))) {
+ if (auto File = FileMgr.getFile(HeadersFilename, /*OpenFile=*/true))
+ FE = *File;
+
+ if (!FE) {
// Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h"
HeadersFilename = FrameworkName;
HeadersFilename += "PrivateHeaders/";
}
HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
- if (!(FE = FileMgr.getFile(HeadersFilename, /*OpenFile=*/true)))
+ if (auto File = FileMgr.getFile(HeadersFilename, /*OpenFile=*/true))
+ FE = *File;
+
+ if (!FE)
return nullptr;
}
return false;
// Determine whether this directory exists.
- const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
+ auto Dir = FileMgr.getDirectory(DirName);
if (!Dir)
return false;
// Try to load the module map file in this directory.
- switch (loadModuleMapFile(Dir, IsSystem,
- llvm::sys::path::extension(Dir->getName()) ==
+ switch (loadModuleMapFile(*Dir, IsSystem,
+ llvm::sys::path::extension((*Dir)->getName()) ==
".framework")) {
case LMM_NewlyLoaded:
case LMM_AlreadyLoaded:
}
// If we hit the top of our search, we're done.
- if (Dir == Root)
+ if (*Dir == Root)
return false;
// Keep track of all of the directories we checked, so we can mark them as
// having module maps if we eventually do find a module map.
- FixUpDirectories.push_back(Dir);
+ FixUpDirectories.push_back(*Dir);
} while (true);
}
llvm::sys::path::append(PrivateFilename, "module.private.modulemap");
else
return nullptr;
- return FileMgr.getFile(PrivateFilename);
+ if (auto File = FileMgr.getFile(PrivateFilename))
+ return *File;
+ return nullptr;
}
bool HeaderSearch::loadModuleMapFile(const FileEntry *File, bool IsSystem,
// Find the directory for the module. For frameworks, that may require going
// up from the 'Modules' directory.
const DirectoryEntry *Dir = nullptr;
- if (getHeaderSearchOpts().ModuleMapFileHomeIsCwd)
- Dir = FileMgr.getDirectory(".");
- else {
+ if (getHeaderSearchOpts().ModuleMapFileHomeIsCwd) {
+ if (auto DirOrErr = FileMgr.getDirectory("."))
+ Dir = *DirOrErr;
+ } else {
if (!OriginalModuleMapFile.empty()) {
// We're building a preprocessed module map. Find or invent the directory
// that it originally occupied.
- Dir = FileMgr.getDirectory(
+ auto DirOrErr = FileMgr.getDirectory(
llvm::sys::path::parent_path(OriginalModuleMapFile));
- if (!Dir) {
+ if (DirOrErr) {
+ Dir = *DirOrErr;
+ } else {
auto *FakeFile = FileMgr.getVirtualFile(OriginalModuleMapFile, 0, 0);
Dir = FakeFile->getDir();
}
if (llvm::sys::path::filename(DirName) == "Modules") {
DirName = llvm::sys::path::parent_path(DirName);
if (DirName.endswith(".framework"))
- Dir = FileMgr.getDirectory(DirName);
+ if (auto DirOrErr = FileMgr.getDirectory(DirName))
+ Dir = *DirOrErr;
// FIXME: This assert can fail if there's a race between the above check
// and the removal of the directory.
assert(Dir && "parent must exist");
if (IsFramework)
llvm::sys::path::append(ModuleMapFileName, "Modules");
llvm::sys::path::append(ModuleMapFileName, "module.modulemap");
- if (const FileEntry *F = FileMgr.getFile(ModuleMapFileName))
- return F;
+ if (auto F = FileMgr.getFile(ModuleMapFileName))
+ return *F;
// Continue to allow module.map
ModuleMapFileName = Dir->getName();
llvm::sys::path::append(ModuleMapFileName, "module.map");
- return FileMgr.getFile(ModuleMapFileName);
+ if (auto F = FileMgr.getFile(ModuleMapFileName))
+ return *F;
+ return nullptr;
}
Module *HeaderSearch::loadFrameworkModule(StringRef Name,
HeaderSearch::LoadModuleMapResult
HeaderSearch::loadModuleMapFile(StringRef DirName, bool IsSystem,
bool IsFramework) {
- if (const DirectoryEntry *Dir = FileMgr.getDirectory(DirName))
- return loadModuleMapFile(Dir, IsSystem, IsFramework);
+ if (auto Dir = FileMgr.getDirectory(DirName))
+ return loadModuleMapFile(*Dir, IsSystem, IsFramework);
return LMM_NoDirectory;
}
if (llvm::sys::path::extension(Dir->path()) != ".framework")
continue;
- const DirectoryEntry *FrameworkDir =
+ auto FrameworkDir =
FileMgr.getDirectory(Dir->path());
if (!FrameworkDir)
continue;
// Load this framework module.
- loadFrameworkModule(llvm::sys::path::stem(Dir->path()), FrameworkDir,
+ loadFrameworkModule(llvm::sys::path::stem(Dir->path()), *FrameworkDir,
IsSystem);
}
continue;
SmallString<128> FullPathName(Directory->getName());
auto GetFile = [&](StringRef Filename) -> const FileEntry * {
- auto *File = SourceMgr.getFileManager().getFile(Filename);
+ auto File = SourceMgr.getFileManager().getFile(Filename);
if (!File ||
- (Header.Size && File->getSize() != *Header.Size) ||
- (Header.ModTime && File->getModificationTime() != *Header.ModTime))
+ (Header.Size && (*File)->getSize() != *Header.Size) ||
+ (Header.ModTime && (*File)->getModificationTime() != *Header.ModTime))
return nullptr;
- return File;
+ return *File;
};
auto GetFrameworkFile = [&]() -> const FileEntry * {
// supplied by Clang. Find that builtin header.
SmallString<128> Path;
llvm::sys::path::append(Path, BuiltinIncludeDir->getName(), Header.FileName);
- auto *File = SourceMgr.getFileManager().getFile(Path);
+ auto File = SourceMgr.getFileManager().getFile(Path);
if (!File)
return false;
auto Role = headerKindToRole(Header.Kind);
- Module::Header H = {Path.str(), File};
+ Module::Header H = {Path.str(), *File};
addHeader(Mod, H, Role);
return true;
}
break;
// Resolve the parent path to a directory entry.
- Dir = SourceMgr.getFileManager().getDirectory(DirName);
+ if (auto DirEntry = SourceMgr.getFileManager().getDirectory(DirName))
+ Dir = *DirEntry;
+ else
+ Dir = nullptr;
} while (Dir);
return {};
}
break;
// Resolve the parent path to a directory entry.
- Dir = SourceMgr.getFileManager().getDirectory(DirName);
+ if (auto DirEntry = SourceMgr.getFileManager().getDirectory(DirName))
+ Dir = *DirEntry;
+ else
+ Dir = nullptr;
} while (Dir);
return false;
if (llvm::sys::path::has_parent_path(FrameworkDirName)) {
// Figure out the parent path.
StringRef Parent = llvm::sys::path::parent_path(FrameworkDirName);
- if (const DirectoryEntry *ParentDir = FileMgr.getDirectory(Parent)) {
+ if (auto ParentDir = FileMgr.getDirectory(Parent)) {
// Check whether we have already looked into the parent directory
// for a module map.
llvm::DenseMap<const DirectoryEntry *, InferredDirectory>::const_iterator
- inferred = InferredDirectories.find(ParentDir);
+ inferred = InferredDirectories.find(*ParentDir);
if (inferred == InferredDirectories.end()) {
// We haven't looked here before. Load a module map, if there is
// one.
bool IsFrameworkDir = Parent.endswith(".framework");
if (const FileEntry *ModMapFile =
- HeaderInfo.lookupModuleMapFile(ParentDir, IsFrameworkDir)) {
- parseModuleMapFile(ModMapFile, Attrs.IsSystem, ParentDir);
- inferred = InferredDirectories.find(ParentDir);
+ HeaderInfo.lookupModuleMapFile(*ParentDir, IsFrameworkDir)) {
+ parseModuleMapFile(ModMapFile, Attrs.IsSystem, *ParentDir);
+ inferred = InferredDirectories.find(*ParentDir);
}
if (inferred == InferredDirectories.end())
inferred = InferredDirectories.insert(
- std::make_pair(ParentDir, InferredDirectory())).first;
+ std::make_pair(*ParentDir, InferredDirectory())).first;
}
if (inferred->second.InferModules) {
// Look for an umbrella header.
SmallString<128> UmbrellaName = StringRef(FrameworkDir->getName());
llvm::sys::path::append(UmbrellaName, "Headers", ModuleName + ".h");
- const FileEntry *UmbrellaHeader = FileMgr.getFile(UmbrellaName);
+ auto UmbrellaHeader = FileMgr.getFile(UmbrellaName);
// FIXME: If there's no umbrella header, we could probably scan the
// framework to load *everything*. But, it's not clear that this is a good
//
// The "Headers/" component of the name is implied because this is
// a framework module.
- setUmbrellaHeader(Result, UmbrellaHeader, ModuleName + ".h");
+ setUmbrellaHeader(Result, *UmbrellaHeader, ModuleName + ".h");
// export *
Result->Exports.push_back(Module::ExportDecl(nullptr, true));
if (!StringRef(Dir->path()).endswith(".framework"))
continue;
- if (const DirectoryEntry *SubframeworkDir =
+ if (auto SubframeworkDir =
FileMgr.getDirectory(Dir->path())) {
// Note: as an egregious but useful hack, we use the real path here and
// check whether it is actually a subdirectory of the parent directory.
// This will not be the case if the 'subframework' is actually a symlink
// out to a top-level framework.
- StringRef SubframeworkDirName = FileMgr.getCanonicalName(SubframeworkDir);
+ StringRef SubframeworkDirName =
+ FileMgr.getCanonicalName(*SubframeworkDir);
bool FoundParent = false;
do {
// Get the parent directory name.
if (SubframeworkDirName.empty())
break;
- if (FileMgr.getDirectory(SubframeworkDirName) == FrameworkDir) {
- FoundParent = true;
- break;
+ if (auto SubDir = FileMgr.getDirectory(SubframeworkDirName)) {
+ if (*SubDir == FrameworkDir) {
+ FoundParent = true;
+ break;
+ }
}
} while (true);
continue;
// FIXME: Do we want to warn about subframeworks without umbrella headers?
- inferFrameworkModule(SubframeworkDir, Attrs, Result);
+ inferFrameworkModule(*SubframeworkDir, Attrs, Result);
}
}
llvm::sys::path::append(ModuleMapFileName, FileName);
FileNameRef = ModuleMapFileName;
}
- if (const FileEntry *File = SourceMgr.getFileManager().getFile(FileNameRef))
+ if (auto File = SourceMgr.getFileManager().getFile(FileNameRef))
Map.parseModuleMapFile(
- File, /*IsSystem=*/false,
+ *File, /*IsSystem=*/false,
Map.HeaderInfo.getHeaderSearchOpts().ModuleMapFileHomeIsCwd
? Directory
- : File->getDir(),
+ : (*File)->getDir(),
FileID(), nullptr, ExternLoc);
}
// Look for this file.
const DirectoryEntry *Dir = nullptr;
- if (llvm::sys::path::is_absolute(DirName))
- Dir = SourceMgr.getFileManager().getDirectory(DirName);
- else {
+ if (llvm::sys::path::is_absolute(DirName)) {
+ if (auto D = SourceMgr.getFileManager().getDirectory(DirName))
+ Dir = *D;
+ } else {
SmallString<128> PathName;
PathName = Directory->getName();
llvm::sys::path::append(PathName, DirName);
- Dir = SourceMgr.getFileManager().getDirectory(PathName);
+ if (auto D = SourceMgr.getFileManager().getDirectory(PathName))
+ Dir = *D;
}
if (!Dir) {
SourceMgr.getFileManager().getVirtualFileSystem();
for (llvm::vfs::recursive_directory_iterator I(FS, Dir->getName(), EC), E;
I != E && !EC; I.increment(EC)) {
- if (const FileEntry *FE = SourceMgr.getFileManager().getFile(I->path())) {
+ if (auto FE = SourceMgr.getFileManager().getFile(I->path())) {
- Module::Header Header = {I->path(), FE};
+ Module::Header Header = {I->path(), *FE};
Headers.push_back(std::move(Header));
}
}
BuildSystemModule = getCurrentModule()->IsSystem;
} else if ((FileEnt =
SourceMgr.getFileEntryForID(SourceMgr.getMainFileID())))
- Includers.push_back(std::make_pair(FileEnt, FileMgr.getDirectory(".")));
+ Includers.push_back(std::make_pair(FileEnt, *FileMgr.getDirectory(".")));
} else {
Includers.push_back(std::make_pair(FileEnt, FileEnt->getDir()));
}
// Give the clients a chance to recover.
SmallString<128> RecoveryPath;
if (Callbacks->FileNotFound(Filename, RecoveryPath)) {
- if (const DirectoryEntry *DE = FileMgr.getDirectory(RecoveryPath)) {
+ if (auto DE = FileMgr.getDirectory(RecoveryPath)) {
// Add the recovery path to the list of search paths.
- DirectoryLookup DL(DE, SrcMgr::C_User, false);
+ DirectoryLookup DL(*DE, SrcMgr::C_User, false);
HeaderInfo.AddSearchPath(DL, isAngled);
// Try the lookup again, skipping the cache.
StringRef FilePath = File->getDir()->getName();
StringRef Path = FilePath;
while (!Path.empty()) {
- if (const DirectoryEntry *CurDir = FM.getDirectory(Path)) {
- if (CurDir == Dir) {
+ if (auto CurDir = FM.getDirectory(Path)) {
+ if (*CurDir == Dir) {
Result = FilePath.substr(Path.size());
llvm::sys::path::append(Result,
llvm::sys::path::filename(File->getName()));
.Default(false))
continue;
- if (const FileEntry *Header = getFileManager().getFile(Entry->path()))
- if (!getSourceManager().hasFileInfo(Header)) {
- if (!ModMap.isHeaderInUnavailableModule(Header)) {
+ if (auto Header = getFileManager().getFile(Entry->path()))
+ if (!getSourceManager().hasFileInfo(*Header)) {
+ if (!ModMap.isHeaderInUnavailableModule(*Header)) {
// Find the relative path that would access this header.
SmallString<128> RelativePath;
- computeRelativePath(FileMgr, Dir, Header, RelativePath);
+ computeRelativePath(FileMgr, Dir, *Header, RelativePath);
Diag(StartLoc, diag::warn_uncovered_module_header)
<< Mod.getFullModuleName() << RelativePath;
}
// Determine whether the actual files are equivalent.
FileManager &FileMgr = Reader.getFileManager();
auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
- if (!Key.Imported)
- return FileMgr.getFile(Key.Filename);
+ if (!Key.Imported) {
+ if (auto File = FileMgr.getFile(Key.Filename))
+ return *File;
+ return nullptr;
+ }
std::string Resolved = Key.Filename;
Reader.ResolveImportedPath(M, Resolved);
- return FileMgr.getFile(Resolved);
+ if (auto File = FileMgr.getFile(Resolved))
+ return *File;
+ return nullptr;
};
const FileEntry *FEA = GetFile(a);
// FIXME: This is not always the right filename-as-written, but we're not
// going to use this information to rebuild the module, so it doesn't make
// a lot of difference.
- Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
+ Module::Header H = { key.Filename, *FileMgr.getFile(Filename) };
ModMap.addHeader(Mod, H, HeaderRole, /*Imported*/true);
HFI.isModuleHeader |= !(HeaderRole & ModuleMap::TextualHeader);
}
bool Transient = FI.Transient;
StringRef Filename = FI.Filename;
- const FileEntry *File = FileMgr.getFile(Filename, /*OpenFile=*/false);
+ const FileEntry *File = nullptr;
+ if (auto FE = FileMgr.getFile(Filename, /*OpenFile=*/false))
+ File = *FE;
+
// If we didn't find the file, resolve it relative to the
// original directory from which this AST file was created.
if (File == nullptr && !F.OriginalDir.empty() && !F.BaseDirectory.empty() &&
std::string Resolved = resolveFileRelativeToOriginalDir(
Filename, F.OriginalDir, F.BaseDirectory);
if (!Resolved.empty())
- File = FileMgr.getFile(Resolved);
+ if (auto FE = FileMgr.getFile(Resolved))
+ File = *FE;
}
// For an overridden file, create a virtual file with the stored
// Don't emit module relocation error if we have -fno-validate-pch
if (!PP.getPreprocessorOpts().DisablePCHValidation &&
F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule) {
- const DirectoryEntry *BuildDir =
- PP.getFileManager().getDirectory(Blob);
- if (!BuildDir || BuildDir != M->Directory) {
+ auto BuildDir = PP.getFileManager().getDirectory(Blob);
+ if (!BuildDir || *BuildDir != M->Directory) {
if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
Diag(diag::err_imported_module_relocated)
<< F.ModuleName << Blob << M->Directory->getName();
assert(M->Name == F.ModuleName && "found module with different name");
// Check the primary module map file.
- const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
- if (StoredModMap == nullptr || StoredModMap != ModMap) {
+ auto StoredModMap = FileMgr.getFile(F.ModuleMapPath);
+ if (!StoredModMap || *StoredModMap != ModMap) {
assert(ModMap && "found module is missing module map file");
assert(ImportedBy && "top-level import should be verified");
if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
// FIXME: we should use input files rather than storing names.
std::string Filename = ReadPath(F, Record, Idx);
- const FileEntry *F =
- FileMgr.getFile(Filename, false, false);
- if (F == nullptr) {
+ auto F = FileMgr.getFile(Filename, false, false);
+ if (!F) {
if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
Error("could not find file '" + Filename +"' referenced by AST file");
return OutOfDate;
}
- AdditionalStoredMaps.insert(F);
+ AdditionalStoredMaps.insert(*F);
}
// Check any additional module map files (e.g. module.private.modulemap)
case SUBMODULE_UMBRELLA_HEADER: {
std::string Filename = Blob;
ResolveImportedPath(F, Filename);
- if (auto *Umbrella = PP.getFileManager().getFile(Filename)) {
+ if (auto Umbrella = PP.getFileManager().getFile(Filename)) {
if (!CurrentModule->getUmbrellaHeader())
- ModMap.setUmbrellaHeader(CurrentModule, Umbrella, Blob);
- else if (CurrentModule->getUmbrellaHeader().Entry != Umbrella) {
+ ModMap.setUmbrellaHeader(CurrentModule, *Umbrella, Blob);
+ else if (CurrentModule->getUmbrellaHeader().Entry != *Umbrella) {
if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
Error("mismatched umbrella headers in submodule");
return OutOfDate;
case SUBMODULE_UMBRELLA_DIR: {
std::string Dirname = Blob;
ResolveImportedPath(F, Dirname);
- if (auto *Umbrella = PP.getFileManager().getDirectory(Dirname)) {
+ if (auto Umbrella = PP.getFileManager().getDirectory(Dirname)) {
if (!CurrentModule->getUmbrellaDir())
- ModMap.setUmbrellaDir(CurrentModule, Umbrella, Blob);
- else if (CurrentModule->getUmbrellaDir().Entry != Umbrella) {
+ ModMap.setUmbrellaDir(CurrentModule, *Umbrella, Blob);
+ else if (CurrentModule->getUmbrellaDir().Entry != *Umbrella) {
if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
Error("mismatched umbrella directories in submodule");
return OutOfDate;
StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
const FileEntry *File = nullptr;
if (!FullFileName.empty())
- File = PP.getFileManager().getFile(FullFileName);
+ if (auto FE = PP.getFileManager().getFile(FullFileName))
+ File = *FE;
// FIXME: Stable encoding
InclusionDirective::InclusionKind Kind
Idx += Length;
// Find the imported module file.
- const FileEntry *DependsOnFile
+ auto DependsOnFile
= FileMgr.getFile(ImportedFile, /*OpenFile=*/false,
/*CacheFailure=*/false);
// Save the information in ImportedModuleFileInfo so we can verify after
// loading all pcms.
ImportedModuleFiles.insert(std::make_pair(
- DependsOnFile, ImportedModuleFileInfo(StoredSize, StoredModTime,
- StoredSignature)));
+ *DependsOnFile, ImportedModuleFileInfo(StoredSize, StoredModTime,
+ StoredSignature)));
// Record the dependency.
- unsigned DependsOnID = getModuleFileInfo(DependsOnFile).ID;
+ unsigned DependsOnID = getModuleFileInfo(*DependsOnFile).ID;
getModuleFileInfo(File).Dependencies.push_back(DependsOnID);
}
}
// If we can't find the module file, skip it.
- const FileEntry *ModuleFile = FileMgr.getFile(D->path());
+ auto ModuleFile = FileMgr.getFile(D->path());
if (!ModuleFile)
continue;
// Load this module file.
- if (llvm::Error Err = Builder.loadModuleFile(ModuleFile))
+ if (llvm::Error Err = Builder.loadModuleFile(*ModuleFile))
return Err;
}
using namespace serialization;
ModuleFile *ModuleManager::lookupByFileName(StringRef Name) const {
- const FileEntry *Entry = FileMgr.getFile(Name, /*OpenFile=*/false,
- /*CacheFailure=*/false);
+ auto Entry = FileMgr.getFile(Name, /*OpenFile=*/false,
+ /*CacheFailure=*/false);
if (Entry)
- return lookup(Entry);
+ return lookup(*Entry);
return nullptr;
}
std::unique_ptr<llvm::MemoryBuffer>
ModuleManager::lookupBuffer(StringRef Name) {
- const FileEntry *Entry = FileMgr.getFile(Name, /*OpenFile=*/false,
- /*CacheFailure=*/false);
- return std::move(InMemoryBuffers[Entry]);
+ auto Entry = FileMgr.getFile(Name, /*OpenFile=*/false,
+ /*CacheFailure=*/false);
+ if (!Entry)
+ return nullptr;
+ return std::move(InMemoryBuffers[*Entry]);
}
static bool checkSignature(ASTFileSignature Signature,
// Open the file immediately to ensure there is no race between stat'ing and
// opening the file.
- File = FileMgr.getFile(FileName, /*OpenFile=*/true, /*CacheFailure=*/false);
- if (!File)
+ auto FileOrErr = FileMgr.getFile(FileName, /*OpenFile=*/true,
+ /*CacheFailure=*/false);
+ if (!FileOrErr) {
+ File = nullptr;
return false;
+ }
+ File = *FileOrErr;
if ((ExpectedSize && ExpectedSize != File->getSize()) ||
(ExpectedModTime && ExpectedModTime != File->getModificationTime()))
bool Replacement::apply(Rewriter &Rewrite) const {
SourceManager &SM = Rewrite.getSourceMgr();
- const FileEntry *Entry = SM.getFileManager().getFile(FilePath);
+ auto Entry = SM.getFileManager().getFile(FilePath);
if (!Entry)
return false;
- FileID ID = SM.getOrCreateFileID(Entry, SrcMgr::C_User);
+ FileID ID = SM.getOrCreateFileID(*Entry, SrcMgr::C_User);
const SourceLocation Start =
SM.getLocForStartOfFile(ID).
getLocWithOffset(ReplacementRange.getOffset());
Rewriter Rewrite(SourceMgr, LangOptions());
InMemoryFileSystem->addFile(
"<stdin>", 0, llvm::MemoryBuffer::getMemBuffer(Code, "<stdin>"));
- FileID ID = SourceMgr.createFileID(Files.getFile("<stdin>"), SourceLocation(),
+ FileID ID = SourceMgr.createFileID(*Files.getFile("<stdin>"),
+ SourceLocation(),
clang::SrcMgr::C_User);
for (auto I = Replaces.rbegin(), E = Replaces.rend(); I != E; ++I) {
Replacement Replace("<stdin>", I->getOffset(), I->getLength(),
std::map<std::string, Replacements> Result;
llvm::SmallPtrSet<const FileEntry *, 16> ProcessedFileEntries;
for (const auto &Entry : FileToReplaces) {
- const FileEntry *FE = FileMgr.getFile(Entry.first);
+ auto FE = FileMgr.getFile(Entry.first);
if (!FE)
llvm::errs() << "File path " << Entry.first << " is invalid.\n";
- else if (ProcessedFileEntries.insert(FE).second)
+ else if (ProcessedFileEntries.insert(*FE).second)
Result[Entry.first] = std::move(Entry.second);
}
return Result;
const std::string &FilePath = FileAndReplaces.first;
auto &CurReplaces = FileAndReplaces.second;
- const FileEntry *Entry = Files.getFile(FilePath);
+ const FileEntry *Entry = nullptr;
+ if (auto File = Files.getFile(FilePath))
+ Entry = *File;
+
FileID ID = SM.getOrCreateFileID(Entry, SrcMgr::C_User);
StringRef Code = SM.getBufferData(ID);
SourceManager &Sources, FileManager &Files,
llvm::vfs::InMemoryFileSystem *MemFS) {
MemFS->addFileNoOwn(FileName, 0, Source);
- return Sources.createFileID(Files.getFile(FileName), SourceLocation(),
+ auto File = Files.getFile(FileName);
+ return Sources.createFileID(File ? *File : nullptr, SourceLocation(),
SrcMgr::C_User);
}
llvm::Error ParseSource(const std::string &Path, CompilerInstance &CI,
ASTConsumer &Consumer) {
SourceManager &SM = CI.getSourceManager();
- const FileEntry *FE = CI.getFileManager().getFile(Path);
+ auto FE = CI.getFileManager().getFile(Path);
if (!FE) {
return llvm::make_error<llvm::StringError>(
llvm::Twine("Couldn't open ", Path), std::error_code());
}
- SM.setMainFileID(SM.createFileID(FE, SourceLocation(), SrcMgr::C_User));
+ SM.setMainFileID(SM.createFileID(*FE, SourceLocation(), SrcMgr::C_User));
ParseAST(CI.getPreprocessor(), &Consumer, CI.getASTContext());
return llvm::Error::success();
}
bool forAllRanges(const SourceManager &SM,
llvm::function_ref<void(SourceRange R)> Callback) override {
- const FileEntry *FE = SM.getFileManager().getFile(Range.FileName);
- FileID FID = FE ? SM.translateFile(FE) : FileID();
+ auto FE = SM.getFileManager().getFile(Range.FileName);
+ FileID FID = FE ? SM.translateFile(*FE) : FileID();
if (!FE || FID.isInvalid()) {
llvm::errs() << "error: -selection=" << Range.FileName
<< ":... : given file is not in the target TU\n";
bool TestSelectionRangesInFile::foreachRange(
const SourceManager &SM,
llvm::function_ref<void(SourceRange)> Callback) const {
- const FileEntry *FE = SM.getFileManager().getFile(Filename);
- FileID FID = FE ? SM.translateFile(FE) : FileID();
+ auto FE = SM.getFileManager().getFile(Filename);
+ FileID FID = FE ? SM.translateFile(*FE) : FileID();
if (!FE || FID.isInvalid()) {
llvm::errs() << "error: -selection=test:" << Filename
<< " : given file is not in the target TU";
Tool.applyAllReplacements(Rewrite);
for (const auto &File : Files) {
- const auto *Entry = FileMgr.getFile(File);
- const auto ID = Sources.getOrCreateFileID(Entry, SrcMgr::C_User);
+ auto Entry = FileMgr.getFile(File);
+ const auto ID = Sources.getOrCreateFileID(*Entry, SrcMgr::C_User);
Rewrite.getEditBuffer(ID).write(outs());
}
}
ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
FileManager &FMgr = CXXUnit->getFileManager();
- return const_cast<FileEntry *>(FMgr.getFile(file_name));
+ auto File = FMgr.getFile(file_name);
+ if (!File)
+ return nullptr;
+ return const_cast<FileEntry *>(*File);
}
const char *clang_getFileContents(CXTranslationUnit TU, CXFile file,
PreprocessorOptions &PPOpts = CI.getPreprocessorOpts();
if (!PPOpts.ImplicitPCHInclude.empty()) {
- DataConsumer->importedPCH(
- CI.getFileManager().getFile(PPOpts.ImplicitPCHInclude));
+ auto File = CI.getFileManager().getFile(PPOpts.ImplicitPCHInclude);
+ if (File)
+ DataConsumer->importedPCH(*File);
}
DataConsumer->setASTContext(CI.getASTContext());
if (Unit->getOriginalSourceFileName().empty())
DataConsumer.enteredMainFile(nullptr);
+ else if (auto MainFile = FileMgr.getFile(Unit->getOriginalSourceFileName()))
+ DataConsumer.enteredMainFile(*MainFile);
else
- DataConsumer.enteredMainFile(
- FileMgr.getFile(Unit->getOriginalSourceFileName()));
+ DataConsumer.enteredMainFile(nullptr);
DataConsumer.setASTContext(Unit->getASTContext());
DataConsumer.startedTranslationUnit();
EXPECT_NE(*fileFoo, *fileBar);
}
-// getFile() returns NULL if neither a real file nor a virtual file
+// getFile() returns an error if neither a real file nor a virtual file
// exists at the given path.
-TEST_F(FileManagerTest, getFileReturnsNULLForNonexistentFile) {
+TEST_F(FileManagerTest, getFileReturnsErrorForNonexistentFile) {
// Inject a fake foo.cpp into the file system.
auto statCache = llvm::make_unique<FakeStatCache>();
statCache->InjectDirectory(".", 41);
auto file = manager.getFile("xyz.txt");
ASSERT_FALSE(file);
+ ASSERT_EQ(file.getError(), std::errc::no_such_file_or_directory);
+
+ statCache->InjectDirectory("MyDirectory", 49);
+ auto readingDirAsFile = manager.getFile("MyDirectory");
+ ASSERT_FALSE(readingDirAsFile);
+ ASSERT_EQ(readingDirAsFile.getError(), std::errc::is_a_directory);
+
+ auto readingFileAsDir = manager.getDirectory("foo.cpp");
+ ASSERT_FALSE(readingFileAsDir);
+ ASSERT_EQ(readingFileAsDir.getError(), std::errc::not_a_directory);
}
// The following tests apply to Unix-like system only.
Manager.setStatCache(std::move(statCache));
// Check for real path.
- const FileEntry *file = Manager.getFile("/tmp/test", /*OpenFile=*/false);
- ASSERT_TRUE(file != nullptr);
- ASSERT_TRUE(file->isValid());
+ auto file = Manager.getFile("/tmp/test", /*OpenFile=*/false);
+ ASSERT_TRUE(file);
+ ASSERT_TRUE((*file)->isValid());
SmallString<64> ExpectedResult = CustomWorkingDir;
llvm::sys::path::append(ExpectedResult, "tmp", "test");
- EXPECT_EQ(file->tryGetRealPathName(), ExpectedResult);
+ EXPECT_EQ((*file)->tryGetRealPathName(), ExpectedResult);
}
} // anonymous namespace
void addSearchDir(llvm::StringRef Dir) {
VFS->addFile(Dir, 0, llvm::MemoryBuffer::getMemBuffer(""), /*User=*/None,
/*Group=*/None, llvm::sys::fs::file_type::directory_file);
- const DirectoryEntry *DE = FileMgr.getDirectory(Dir);
+ auto DE = FileMgr.getDirectory(Dir);
assert(DE);
- auto DL = DirectoryLookup(DE, SrcMgr::C_User, /*isFramework=*/false);
+ auto DL = DirectoryLookup(*DE, SrcMgr::C_User, /*isFramework=*/false);
Search.AddSearchPath(DL, /*isAngled=*/false);
}
// Add header's parent path to search path.
StringRef SearchPath = llvm::sys::path::parent_path(HeaderPath);
- const DirectoryEntry *DE = FileMgr.getDirectory(SearchPath);
- DirectoryLookup DL(DE, SrcMgr::C_User, false);
+ auto DE = FileMgr.getDirectory(SearchPath);
+ DirectoryLookup DL(*DE, SrcMgr::C_User, false);
HeaderInfo.AddSearchPath(DL, IsSystemHeader);
}
llvm::raw_fd_ostream OutStream(FD, true);
OutStream << Content;
OutStream.close();
- const FileEntry *File = Context.Files.getFile(Path);
- assert(File != nullptr);
+ auto File = Context.Files.getFile(Path);
+ assert(File);
StringRef Found =
TemporaryFiles.insert(std::make_pair(Name, Path.str())).first->second;
assert(Found == Path);
(void)Found;
- return Context.Sources.createFileID(File, SourceLocation(), SrcMgr::C_User);
+ return Context.Sources.createFileID(*File, SourceLocation(),
+ SrcMgr::C_User);
}
std::string getFileContentFromDisk(llvm::StringRef Name) {
llvm::MemoryBuffer::getMemBuffer(Content);
InMemoryFileSystem->addFile(Name, 0, std::move(Source));
- const FileEntry *Entry = Files.getFile(Name);
- assert(Entry != nullptr);
- return Sources.createFileID(Entry, SourceLocation(), SrcMgr::C_User);
+ auto Entry = Files.getFile(Name);
+ assert(Entry);
+ return Sources.createFileID(*Entry, SourceLocation(), SrcMgr::C_User);
}
// FIXME: this code is mostly a duplicate of
llvm::raw_fd_ostream OutStream(FD, true);
OutStream << Content;
OutStream.close();
- const FileEntry *File = Files.getFile(Path);
- assert(File != nullptr);
+ auto File = Files.getFile(Path);
+ assert(File);
StringRef Found =
TemporaryFiles.insert(std::make_pair(Name, Path.str())).first->second;
assert(Found == Path);
(void)Found;
- return Sources.createFileID(File, SourceLocation(), SrcMgr::C_User);
+ return Sources.createFileID(*File, SourceLocation(), SrcMgr::C_User);
}
SourceLocation getLocation(FileID ID, unsigned Line, unsigned Column) {