1 //===--- ModuleMap.cpp - Describe the layout of modules ---------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the ModuleMap implementation, which describes the layout
11 // of a module as it relates to headers.
13 //===----------------------------------------------------------------------===//
14 #include "clang/Lex/ModuleMap.h"
15 #include "clang/Basic/CharInfo.h"
16 #include "clang/Basic/Diagnostic.h"
17 #include "clang/Basic/DiagnosticOptions.h"
18 #include "clang/Basic/FileManager.h"
19 #include "clang/Basic/TargetInfo.h"
20 #include "clang/Basic/TargetOptions.h"
21 #include "clang/Lex/HeaderSearch.h"
22 #include "clang/Lex/LexDiagnostic.h"
23 #include "clang/Lex/Lexer.h"
24 #include "clang/Lex/LiteralSupport.h"
25 #include "llvm/ADT/StringRef.h"
26 #include "llvm/ADT/StringSwitch.h"
27 #include "llvm/Support/Allocator.h"
28 #include "llvm/Support/FileSystem.h"
29 #include "llvm/Support/Host.h"
30 #include "llvm/Support/Path.h"
31 #include "llvm/Support/raw_ostream.h"
33 #if defined(LLVM_ON_UNIX)
36 using namespace clang;
39 ModuleMap::resolveExport(Module *Mod,
40 const Module::UnresolvedExportDecl &Unresolved,
41 bool Complain) const {
42 // We may have just a wildcard.
43 if (Unresolved.Id.empty()) {
44 assert(Unresolved.Wildcard && "Invalid unresolved export");
45 return Module::ExportDecl(nullptr, true);
48 // Resolve the module-id.
49 Module *Context = resolveModuleId(Unresolved.Id, Mod, Complain);
51 return Module::ExportDecl();
53 return Module::ExportDecl(Context, Unresolved.Wildcard);
56 Module *ModuleMap::resolveModuleId(const ModuleId &Id, Module *Mod,
57 bool Complain) const {
58 // Find the starting module.
59 Module *Context = lookupModuleUnqualified(Id[0].first, Mod);
62 Diags.Report(Id[0].second, diag::err_mmap_missing_module_unqualified)
63 << Id[0].first << Mod->getFullModuleName();
68 // Dig into the module path.
69 for (unsigned I = 1, N = Id.size(); I != N; ++I) {
70 Module *Sub = lookupModuleQualified(Id[I].first, Context);
73 Diags.Report(Id[I].second, diag::err_mmap_missing_module_qualified)
74 << Id[I].first << Context->getFullModuleName()
75 << SourceRange(Id[0].second, Id[I-1].second);
86 ModuleMap::ModuleMap(SourceManager &SourceMgr, DiagnosticsEngine &Diags,
87 const LangOptions &LangOpts, const TargetInfo *Target,
88 HeaderSearch &HeaderInfo)
89 : SourceMgr(SourceMgr), Diags(Diags), LangOpts(LangOpts), Target(Target),
90 HeaderInfo(HeaderInfo), BuiltinIncludeDir(nullptr),
91 CompilingModule(nullptr), SourceModule(nullptr) {}
93 ModuleMap::~ModuleMap() {
94 for (llvm::StringMap<Module *>::iterator I = Modules.begin(),
101 void ModuleMap::setTarget(const TargetInfo &Target) {
102 assert((!this->Target || this->Target == &Target) &&
103 "Improper target override");
104 this->Target = &Target;
107 /// \brief "Sanitize" a filename so that it can be used as an identifier.
108 static StringRef sanitizeFilenameAsIdentifier(StringRef Name,
109 SmallVectorImpl<char> &Buffer) {
113 if (!isValidIdentifier(Name)) {
114 // If we don't already have something with the form of an identifier,
115 // create a buffer with the sanitized name.
117 if (isDigit(Name[0]))
118 Buffer.push_back('_');
119 Buffer.reserve(Buffer.size() + Name.size());
120 for (unsigned I = 0, N = Name.size(); I != N; ++I) {
121 if (isIdentifierBody(Name[I]))
122 Buffer.push_back(Name[I]);
124 Buffer.push_back('_');
127 Name = StringRef(Buffer.data(), Buffer.size());
130 while (llvm::StringSwitch<bool>(Name)
131 #define KEYWORD(Keyword,Conditions) .Case(#Keyword, true)
132 #define ALIAS(Keyword, AliasOf, Conditions) .Case(Keyword, true)
133 #include "clang/Basic/TokenKinds.def"
135 if (Name.data() != Buffer.data())
136 Buffer.append(Name.begin(), Name.end());
137 Buffer.push_back('_');
138 Name = StringRef(Buffer.data(), Buffer.size());
144 /// \brief Determine whether the given file name is the name of a builtin
145 /// header, supplied by Clang to replace, override, or augment existing system
147 static bool isBuiltinHeader(StringRef FileName) {
148 return llvm::StringSwitch<bool>(FileName)
149 .Case("float.h", true)
150 .Case("iso646.h", true)
151 .Case("limits.h", true)
152 .Case("stdalign.h", true)
153 .Case("stdarg.h", true)
154 .Case("stdbool.h", true)
155 .Case("stddef.h", true)
156 .Case("stdint.h", true)
157 .Case("tgmath.h", true)
158 .Case("unwind.h", true)
162 ModuleMap::HeadersMap::iterator
163 ModuleMap::findKnownHeader(const FileEntry *File) {
164 HeadersMap::iterator Known = Headers.find(File);
165 if (Known == Headers.end() && File->getDir() == BuiltinIncludeDir &&
166 isBuiltinHeader(llvm::sys::path::filename(File->getName()))) {
167 HeaderInfo.loadTopLevelSystemModules();
168 return Headers.find(File);
173 ModuleMap::KnownHeader
174 ModuleMap::findHeaderInUmbrellaDirs(const FileEntry *File,
175 SmallVectorImpl<const DirectoryEntry *> &IntermediateDirs) {
176 const DirectoryEntry *Dir = File->getDir();
177 assert(Dir && "file in no directory");
179 // Note: as an egregious but useful hack we use the real path here, because
180 // frameworks moving from top-level frameworks to embedded frameworks tend
181 // to be symlinked from the top-level location to the embedded location,
182 // and we need to resolve lookups as if we had found the embedded location.
183 StringRef DirName = SourceMgr.getFileManager().getCanonicalName(Dir);
185 // Keep walking up the directory hierarchy, looking for a directory with
186 // an umbrella header.
188 auto KnownDir = UmbrellaDirs.find(Dir);
189 if (KnownDir != UmbrellaDirs.end())
190 return KnownHeader(KnownDir->second, NormalHeader);
192 IntermediateDirs.push_back(Dir);
194 // Retrieve our parent path.
195 DirName = llvm::sys::path::parent_path(DirName);
199 // Resolve the parent path to a directory entry.
200 Dir = SourceMgr.getFileManager().getDirectory(DirName);
202 return KnownHeader();
205 // Returns 'true' if 'RequestingModule directly uses 'RequestedModule'.
206 static bool directlyUses(const Module *RequestingModule,
207 const Module *RequestedModule) {
208 return std::find(RequestingModule->DirectUses.begin(),
209 RequestingModule->DirectUses.end(),
210 RequestedModule) != RequestingModule->DirectUses.end();
213 static bool violatesPrivateInclude(Module *RequestingModule,
214 const FileEntry *IncFileEnt,
215 ModuleMap::ModuleHeaderRole Role,
216 Module *RequestedModule) {
218 // Check for consistency between the module header role
219 // as obtained from the lookup and as obtained from the module.
220 // This check is not cheap, so enable it only for debugging.
221 SmallVectorImpl<const FileEntry *> &PvtHdrs
222 = RequestedModule->PrivateHeaders;
223 SmallVectorImpl<const FileEntry *>::iterator Look
224 = std::find(PvtHdrs.begin(), PvtHdrs.end(), IncFileEnt);
225 bool IsPrivate = Look != PvtHdrs.end();
226 assert((IsPrivate && Role == ModuleMap::PrivateHeader)
227 || (!IsPrivate && Role != ModuleMap::PrivateHeader));
229 return Role == ModuleMap::PrivateHeader &&
230 RequestedModule->getTopLevelModule() != RequestingModule;
233 static Module *getTopLevelOrNull(Module *M) {
234 return M ? M->getTopLevelModule() : nullptr;
237 void ModuleMap::diagnoseHeaderInclusion(Module *RequestingModule,
238 SourceLocation FilenameLoc,
240 const FileEntry *File) {
241 // No errors for indirect modules. This may be a bit of a problem for modules
242 // with no source files.
243 if (getTopLevelOrNull(RequestingModule) != getTopLevelOrNull(SourceModule))
246 if (RequestingModule)
247 resolveUses(RequestingModule, /*Complain=*/false);
249 bool Excluded = false;
250 Module *Private = nullptr;
251 Module *NotUsed = nullptr;
253 HeadersMap::iterator Known = findKnownHeader(File);
254 if (Known != Headers.end()) {
255 for (const KnownHeader &Header : Known->second) {
256 // Excluded headers don't really belong to a module.
257 if (Header.getRole() == ModuleMap::ExcludedHeader) {
262 // If 'File' is part of 'RequestingModule' we can definitely include it.
263 if (Header.getModule() == RequestingModule)
266 // Remember private headers for later printing of a diagnostic.
267 if (violatesPrivateInclude(RequestingModule, File, Header.getRole(),
268 Header.getModule())) {
269 Private = Header.getModule();
273 // If uses need to be specified explicitly, we are only allowed to return
274 // modules that are explicitly used by the requesting module.
275 if (RequestingModule && LangOpts.ModulesDeclUse &&
276 !directlyUses(RequestingModule, Header.getModule())) {
277 NotUsed = Header.getModule();
281 // We have found a module that we can happily use.
286 // We have found a header, but it is private.
288 Diags.Report(FilenameLoc, diag::error_use_of_private_header_outside_module)
293 // We have found a module, but we don't use it.
295 Diags.Report(FilenameLoc, diag::error_undeclared_use_of_module)
296 << RequestingModule->getFullModuleName() << Filename;
300 if (Excluded || isHeaderInUmbrellaDirs(File))
303 // At this point, only non-modular includes remain.
305 if (LangOpts.ModulesStrictDeclUse) {
306 Diags.Report(FilenameLoc, diag::error_undeclared_use_of_module)
307 << RequestingModule->getFullModuleName() << Filename;
308 } else if (RequestingModule) {
309 diag::kind DiagID = RequestingModule->getTopLevelModule()->IsFramework ?
310 diag::warn_non_modular_include_in_framework_module :
311 diag::warn_non_modular_include_in_module;
312 Diags.Report(FilenameLoc, DiagID) << RequestingModule->getFullModuleName();
316 ModuleMap::KnownHeader
317 ModuleMap::findModuleForHeader(const FileEntry *File,
318 Module *RequestingModule) {
319 HeadersMap::iterator Known = findKnownHeader(File);
321 if (Known != Headers.end()) {
322 ModuleMap::KnownHeader Result = KnownHeader();
324 // Iterate over all modules that 'File' is part of to find the best fit.
325 for (SmallVectorImpl<KnownHeader>::iterator I = Known->second.begin(),
326 E = Known->second.end();
328 // Cannot use a module if the header is excluded in it.
329 if (I->getRole() == ModuleMap::ExcludedHeader)
332 // Cannot use a module if it is unavailable.
333 if (!I->getModule()->isAvailable())
336 // If 'File' is part of 'RequestingModule', 'RequestingModule' is the
337 // module we are looking for.
338 if (I->getModule() == RequestingModule)
341 // If uses need to be specified explicitly, we are only allowed to return
342 // modules that are explicitly used by the requesting module.
343 if (RequestingModule && LangOpts.ModulesDeclUse &&
344 !directlyUses(RequestingModule, I->getModule()))
348 // If 'File' is a public header of this module, this is as good as we
350 // FIXME: If we have a RequestingModule, we should prefer the header from
352 if (I->getRole() == ModuleMap::NormalHeader)
358 SmallVector<const DirectoryEntry *, 2> SkippedDirs;
359 KnownHeader H = findHeaderInUmbrellaDirs(File, SkippedDirs);
361 Module *Result = H.getModule();
363 // Search up the module stack until we find a module with an umbrella
365 Module *UmbrellaModule = Result;
366 while (!UmbrellaModule->getUmbrellaDir() && UmbrellaModule->Parent)
367 UmbrellaModule = UmbrellaModule->Parent;
369 if (UmbrellaModule->InferSubmodules) {
370 // Infer submodules for each of the directories we found between
371 // the directory of the umbrella header and the directory where
372 // the actual header is located.
373 bool Explicit = UmbrellaModule->InferExplicitSubmodules;
375 for (unsigned I = SkippedDirs.size(); I != 0; --I) {
376 // Find or create the module that corresponds to this directory name.
377 SmallString<32> NameBuf;
378 StringRef Name = sanitizeFilenameAsIdentifier(
379 llvm::sys::path::stem(SkippedDirs[I-1]->getName()), NameBuf);
380 Result = findOrCreateModule(Name, Result, UmbrellaModule->ModuleMap,
381 /*IsFramework=*/false, Explicit).first;
382 Result->IsInferred = true;
384 // Associate the module and the directory.
385 UmbrellaDirs[SkippedDirs[I-1]] = Result;
387 // If inferred submodules export everything they import, add a
388 // wildcard to the set of exports.
389 if (UmbrellaModule->InferExportWildcard && Result->Exports.empty())
390 Result->Exports.push_back(Module::ExportDecl(nullptr, true));
393 // Infer a submodule with the same name as this header file.
394 SmallString<32> NameBuf;
395 StringRef Name = sanitizeFilenameAsIdentifier(
396 llvm::sys::path::stem(File->getName()), NameBuf);
397 Result = findOrCreateModule(Name, Result, UmbrellaModule->ModuleMap,
398 /*IsFramework=*/false, Explicit).first;
399 Result->IsInferred = true;
400 Result->addTopHeader(File);
402 // If inferred submodules export everything they import, add a
403 // wildcard to the set of exports.
404 if (UmbrellaModule->InferExportWildcard && Result->Exports.empty())
405 Result->Exports.push_back(Module::ExportDecl(nullptr, true));
407 // Record each of the directories we stepped through as being part of
408 // the module we found, since the umbrella header covers them all.
409 for (unsigned I = 0, N = SkippedDirs.size(); I != N; ++I)
410 UmbrellaDirs[SkippedDirs[I]] = Result;
413 Headers[File].push_back(KnownHeader(Result, NormalHeader));
415 // If a header corresponds to an unavailable module, don't report
416 // that it maps to anything.
417 if (!Result->isAvailable())
418 return KnownHeader();
420 return Headers[File].back();
423 return KnownHeader();
426 bool ModuleMap::isHeaderInUnavailableModule(const FileEntry *Header) const {
427 return isHeaderUnavailableInModule(Header, nullptr);
431 ModuleMap::isHeaderUnavailableInModule(const FileEntry *Header,
432 const Module *RequestingModule) const {
433 HeadersMap::const_iterator Known = Headers.find(Header);
434 if (Known != Headers.end()) {
435 for (SmallVectorImpl<KnownHeader>::const_iterator
436 I = Known->second.begin(),
437 E = Known->second.end();
439 if (I->isAvailable() && (!RequestingModule ||
440 I->getModule()->isSubModuleOf(RequestingModule)))
446 const DirectoryEntry *Dir = Header->getDir();
447 SmallVector<const DirectoryEntry *, 2> SkippedDirs;
448 StringRef DirName = Dir->getName();
450 auto IsUnavailable = [&](const Module *M) {
451 return !M->isAvailable() && (!RequestingModule ||
452 M->isSubModuleOf(RequestingModule));
455 // Keep walking up the directory hierarchy, looking for a directory with
456 // an umbrella header.
458 llvm::DenseMap<const DirectoryEntry *, Module *>::const_iterator KnownDir
459 = UmbrellaDirs.find(Dir);
460 if (KnownDir != UmbrellaDirs.end()) {
461 Module *Found = KnownDir->second;
462 if (IsUnavailable(Found))
465 // Search up the module stack until we find a module with an umbrella
467 Module *UmbrellaModule = Found;
468 while (!UmbrellaModule->getUmbrellaDir() && UmbrellaModule->Parent)
469 UmbrellaModule = UmbrellaModule->Parent;
471 if (UmbrellaModule->InferSubmodules) {
472 for (unsigned I = SkippedDirs.size(); I != 0; --I) {
473 // Find or create the module that corresponds to this directory name.
474 SmallString<32> NameBuf;
475 StringRef Name = sanitizeFilenameAsIdentifier(
476 llvm::sys::path::stem(SkippedDirs[I-1]->getName()),
478 Found = lookupModuleQualified(Name, Found);
481 if (IsUnavailable(Found))
485 // Infer a submodule with the same name as this header file.
486 SmallString<32> NameBuf;
487 StringRef Name = sanitizeFilenameAsIdentifier(
488 llvm::sys::path::stem(Header->getName()),
490 Found = lookupModuleQualified(Name, Found);
495 return IsUnavailable(Found);
498 SkippedDirs.push_back(Dir);
500 // Retrieve our parent path.
501 DirName = llvm::sys::path::parent_path(DirName);
505 // Resolve the parent path to a directory entry.
506 Dir = SourceMgr.getFileManager().getDirectory(DirName);
512 Module *ModuleMap::findModule(StringRef Name) const {
513 llvm::StringMap<Module *>::const_iterator Known = Modules.find(Name);
514 if (Known != Modules.end())
515 return Known->getValue();
520 Module *ModuleMap::lookupModuleUnqualified(StringRef Name,
521 Module *Context) const {
522 for(; Context; Context = Context->Parent) {
523 if (Module *Sub = lookupModuleQualified(Name, Context))
527 return findModule(Name);
530 Module *ModuleMap::lookupModuleQualified(StringRef Name, Module *Context) const{
532 return findModule(Name);
534 return Context->findSubmodule(Name);
537 std::pair<Module *, bool>
538 ModuleMap::findOrCreateModule(StringRef Name, Module *Parent,
539 const FileEntry *ModuleMap, bool IsFramework,
541 // Try to find an existing module with this name.
542 if (Module *Sub = lookupModuleQualified(Name, Parent))
543 return std::make_pair(Sub, false);
545 // Create a new module with this name.
546 Module *Result = new Module(Name, SourceLocation(), Parent, ModuleMap,
547 IsFramework, IsExplicit);
548 if (LangOpts.CurrentModule == Name) {
549 SourceModule = Result;
550 SourceModuleName = Name;
553 Modules[Name] = Result;
554 if (!LangOpts.CurrentModule.empty() && !CompilingModule &&
555 Name == LangOpts.CurrentModule) {
556 CompilingModule = Result;
559 return std::make_pair(Result, true);
562 bool ModuleMap::canInferFrameworkModule(const DirectoryEntry *ParentDir,
563 StringRef Name, bool &IsSystem) const {
564 // Check whether we have already looked into the parent directory
566 llvm::DenseMap<const DirectoryEntry *, InferredDirectory>::const_iterator
567 inferred = InferredDirectories.find(ParentDir);
568 if (inferred == InferredDirectories.end())
571 if (!inferred->second.InferModules)
574 // We're allowed to infer for this directory, but make sure it's okay
575 // to infer this particular module.
576 bool canInfer = std::find(inferred->second.ExcludedModules.begin(),
577 inferred->second.ExcludedModules.end(),
578 Name) == inferred->second.ExcludedModules.end();
580 if (canInfer && inferred->second.InferSystemModules)
586 /// \brief For a framework module, infer the framework against which we
588 static void inferFrameworkLink(Module *Mod, const DirectoryEntry *FrameworkDir,
589 FileManager &FileMgr) {
590 assert(Mod->IsFramework && "Can only infer linking for framework modules");
591 assert(!Mod->isSubFramework() &&
592 "Can only infer linking for top-level frameworks");
594 SmallString<128> LibName;
595 LibName += FrameworkDir->getName();
596 llvm::sys::path::append(LibName, Mod->Name);
597 if (FileMgr.getFile(LibName)) {
598 Mod->LinkLibraries.push_back(Module::LinkLibrary(Mod->Name,
599 /*IsFramework=*/true));
604 ModuleMap::inferFrameworkModule(StringRef ModuleName,
605 const DirectoryEntry *FrameworkDir,
608 // Check whether we've already found this module.
609 if (Module *Mod = lookupModuleQualified(ModuleName, Parent))
612 FileManager &FileMgr = SourceMgr.getFileManager();
614 // If the framework has a parent path from which we're allowed to infer
615 // a framework module, do so.
616 const FileEntry *ModuleMapFile = nullptr;
618 // Determine whether we're allowed to infer a module map.
620 // Note: as an egregious but useful hack we use the real path here, because
621 // we might be looking at an embedded framework that symlinks out to a
622 // top-level framework, and we need to infer as if we were naming the
623 // top-level framework.
624 StringRef FrameworkDirName
625 = SourceMgr.getFileManager().getCanonicalName(FrameworkDir);
627 // In case this is a case-insensitive filesystem, make sure the canonical
628 // directory name matches ModuleName exactly. Modules are case-sensitive.
629 // FIXME: we should be able to give a fix-it hint for the correct spelling.
630 if (llvm::sys::path::stem(FrameworkDirName) != ModuleName)
633 bool canInfer = false;
634 if (llvm::sys::path::has_parent_path(FrameworkDirName)) {
635 // Figure out the parent path.
636 StringRef Parent = llvm::sys::path::parent_path(FrameworkDirName);
637 if (const DirectoryEntry *ParentDir = FileMgr.getDirectory(Parent)) {
638 // Check whether we have already looked into the parent directory
640 llvm::DenseMap<const DirectoryEntry *, InferredDirectory>::const_iterator
641 inferred = InferredDirectories.find(ParentDir);
642 if (inferred == InferredDirectories.end()) {
643 // We haven't looked here before. Load a module map, if there is
645 bool IsFrameworkDir = Parent.endswith(".framework");
646 if (const FileEntry *ModMapFile =
647 HeaderInfo.lookupModuleMapFile(ParentDir, IsFrameworkDir)) {
648 parseModuleMapFile(ModMapFile, IsSystem);
649 inferred = InferredDirectories.find(ParentDir);
652 if (inferred == InferredDirectories.end())
653 inferred = InferredDirectories.insert(
654 std::make_pair(ParentDir, InferredDirectory())).first;
657 if (inferred->second.InferModules) {
658 // We're allowed to infer for this directory, but make sure it's okay
659 // to infer this particular module.
660 StringRef Name = llvm::sys::path::stem(FrameworkDirName);
661 canInfer = std::find(inferred->second.ExcludedModules.begin(),
662 inferred->second.ExcludedModules.end(),
663 Name) == inferred->second.ExcludedModules.end();
665 if (inferred->second.InferSystemModules)
667 ModuleMapFile = inferred->second.ModuleMapFile;
672 // If we're not allowed to infer a framework module, don't.
676 ModuleMapFile = Parent->ModuleMap;
679 // Look for an umbrella header.
680 SmallString<128> UmbrellaName = StringRef(FrameworkDir->getName());
681 llvm::sys::path::append(UmbrellaName, "Headers", ModuleName + ".h");
682 const FileEntry *UmbrellaHeader = FileMgr.getFile(UmbrellaName);
684 // FIXME: If there's no umbrella header, we could probably scan the
685 // framework to load *everything*. But, it's not clear that this is a good
690 Module *Result = new Module(ModuleName, SourceLocation(), Parent, ModuleMapFile,
691 /*IsFramework=*/true, /*IsExplicit=*/false);
692 if (LangOpts.CurrentModule == ModuleName) {
693 SourceModule = Result;
694 SourceModuleName = ModuleName;
697 Result->IsSystem = IsSystem;
700 Modules[ModuleName] = Result;
702 // umbrella header "umbrella-header-name"
703 Result->Umbrella = UmbrellaHeader;
704 Headers[UmbrellaHeader].push_back(KnownHeader(Result, NormalHeader));
705 UmbrellaDirs[UmbrellaHeader->getDir()] = Result;
708 Result->Exports.push_back(Module::ExportDecl(nullptr, true));
710 // module * { export * }
711 Result->InferSubmodules = true;
712 Result->InferExportWildcard = true;
714 // Look for subframeworks.
716 SmallString<128> SubframeworksDirName
717 = StringRef(FrameworkDir->getName());
718 llvm::sys::path::append(SubframeworksDirName, "Frameworks");
719 llvm::sys::path::native(SubframeworksDirName);
720 for (llvm::sys::fs::directory_iterator
721 Dir(SubframeworksDirName.str(), EC), DirEnd;
722 Dir != DirEnd && !EC; Dir.increment(EC)) {
723 if (!StringRef(Dir->path()).endswith(".framework"))
726 if (const DirectoryEntry *SubframeworkDir
727 = FileMgr.getDirectory(Dir->path())) {
728 // Note: as an egregious but useful hack, we use the real path here and
729 // check whether it is actually a subdirectory of the parent directory.
730 // This will not be the case if the 'subframework' is actually a symlink
731 // out to a top-level framework.
732 StringRef SubframeworkDirName = FileMgr.getCanonicalName(SubframeworkDir);
733 bool FoundParent = false;
735 // Get the parent directory name.
737 = llvm::sys::path::parent_path(SubframeworkDirName);
738 if (SubframeworkDirName.empty())
741 if (FileMgr.getDirectory(SubframeworkDirName) == FrameworkDir) {
750 // FIXME: Do we want to warn about subframeworks without umbrella headers?
751 SmallString<32> NameBuf;
752 inferFrameworkModule(sanitizeFilenameAsIdentifier(
753 llvm::sys::path::stem(Dir->path()), NameBuf),
754 SubframeworkDir, IsSystem, Result);
758 // If the module is a top-level framework, automatically link against the
760 if (!Result->isSubFramework()) {
761 inferFrameworkLink(Result, FrameworkDir, FileMgr);
767 void ModuleMap::setUmbrellaHeader(Module *Mod, const FileEntry *UmbrellaHeader){
768 Headers[UmbrellaHeader].push_back(KnownHeader(Mod, NormalHeader));
769 Mod->Umbrella = UmbrellaHeader;
770 UmbrellaDirs[UmbrellaHeader->getDir()] = Mod;
773 void ModuleMap::setUmbrellaDir(Module *Mod, const DirectoryEntry *UmbrellaDir) {
774 Mod->Umbrella = UmbrellaDir;
775 UmbrellaDirs[UmbrellaDir] = Mod;
778 void ModuleMap::addHeader(Module *Mod, const FileEntry *Header,
779 ModuleHeaderRole Role) {
780 if (Role == ExcludedHeader) {
781 Mod->ExcludedHeaders.push_back(Header);
783 if (Role == PrivateHeader)
784 Mod->PrivateHeaders.push_back(Header);
786 Mod->NormalHeaders.push_back(Header);
787 bool isCompilingModuleHeader = Mod->getTopLevelModule() == CompilingModule;
788 HeaderInfo.MarkFileModuleHeader(Header, Role, isCompilingModuleHeader);
790 Headers[Header].push_back(KnownHeader(Mod, Role));
794 ModuleMap::getContainingModuleMapFile(Module *Module) const {
795 if (Module->DefinitionLoc.isInvalid())
798 return SourceMgr.getFileEntryForID(
799 SourceMgr.getFileID(Module->DefinitionLoc));
802 void ModuleMap::dump() {
803 llvm::errs() << "Modules:";
804 for (llvm::StringMap<Module *>::iterator M = Modules.begin(),
805 MEnd = Modules.end();
807 M->getValue()->print(llvm::errs(), 2);
809 llvm::errs() << "Headers:";
810 for (HeadersMap::iterator H = Headers.begin(), HEnd = Headers.end();
812 llvm::errs() << " \"" << H->first->getName() << "\" -> ";
813 for (SmallVectorImpl<KnownHeader>::const_iterator I = H->second.begin(),
816 if (I != H->second.begin())
818 llvm::errs() << I->getModule()->getFullModuleName();
820 llvm::errs() << "\n";
824 bool ModuleMap::resolveExports(Module *Mod, bool Complain) {
825 bool HadError = false;
826 for (unsigned I = 0, N = Mod->UnresolvedExports.size(); I != N; ++I) {
827 Module::ExportDecl Export = resolveExport(Mod, Mod->UnresolvedExports[I],
829 if (Export.getPointer() || Export.getInt())
830 Mod->Exports.push_back(Export);
834 Mod->UnresolvedExports.clear();
838 bool ModuleMap::resolveUses(Module *Mod, bool Complain) {
839 bool HadError = false;
840 for (unsigned I = 0, N = Mod->UnresolvedDirectUses.size(); I != N; ++I) {
842 resolveModuleId(Mod->UnresolvedDirectUses[I], Mod, Complain);
844 Mod->DirectUses.push_back(DirectUse);
848 Mod->UnresolvedDirectUses.clear();
852 bool ModuleMap::resolveConflicts(Module *Mod, bool Complain) {
853 bool HadError = false;
854 for (unsigned I = 0, N = Mod->UnresolvedConflicts.size(); I != N; ++I) {
855 Module *OtherMod = resolveModuleId(Mod->UnresolvedConflicts[I].Id,
862 Module::Conflict Conflict;
863 Conflict.Other = OtherMod;
864 Conflict.Message = Mod->UnresolvedConflicts[I].Message;
865 Mod->Conflicts.push_back(Conflict);
867 Mod->UnresolvedConflicts.clear();
871 Module *ModuleMap::inferModuleFromLocation(FullSourceLoc Loc) {
875 // Use the expansion location to determine which module we're in.
876 FullSourceLoc ExpansionLoc = Loc.getExpansionLoc();
877 if (!ExpansionLoc.isFileID())
880 const SourceManager &SrcMgr = Loc.getManager();
881 FileID ExpansionFileID = ExpansionLoc.getFileID();
883 while (const FileEntry *ExpansionFile
884 = SrcMgr.getFileEntryForID(ExpansionFileID)) {
885 // Find the module that owns this header (if any).
886 if (Module *Mod = findModuleForHeader(ExpansionFile).getModule())
889 // No module owns this header, so look up the inclusion chain to see if
890 // any included header has an associated module.
891 SourceLocation IncludeLoc = SrcMgr.getIncludeLoc(ExpansionFileID);
892 if (IncludeLoc.isInvalid())
895 ExpansionFileID = SrcMgr.getFileID(IncludeLoc);
901 //----------------------------------------------------------------------------//
902 // Module map file parser
903 //----------------------------------------------------------------------------//
906 /// \brief A token in a module map file.
937 unsigned StringLength;
938 const char *StringData;
944 StringData = nullptr;
947 bool is(TokenKind K) const { return Kind == K; }
949 SourceLocation getLocation() const {
950 return SourceLocation::getFromRawEncoding(Location);
953 StringRef getString() const {
954 return StringRef(StringData, StringLength);
958 /// \brief The set of attributes that can be attached to a module.
960 Attributes() : IsSystem(), IsExternC(), IsExhaustive() { }
962 /// \brief Whether this is a system module.
963 unsigned IsSystem : 1;
965 /// \brief Whether this is an extern "C" module.
966 unsigned IsExternC : 1;
968 /// \brief Whether this is an exhaustive set of configuration macros.
969 unsigned IsExhaustive : 1;
973 class ModuleMapParser {
975 SourceManager &SourceMgr;
977 /// \brief Default target information, used only for string literal
979 const TargetInfo *Target;
981 DiagnosticsEngine &Diags;
984 /// \brief The current module map file.
985 const FileEntry *ModuleMapFile;
987 /// \brief The directory that this module map resides in.
988 const DirectoryEntry *Directory;
990 /// \brief The directory containing Clang-supplied headers.
991 const DirectoryEntry *BuiltinIncludeDir;
993 /// \brief Whether this module map is in a system header directory.
996 /// \brief Whether an error occurred.
999 /// \brief Stores string data for the various string literals referenced
1001 llvm::BumpPtrAllocator StringData;
1003 /// \brief The current token.
1006 /// \brief The active module.
1007 Module *ActiveModule;
1009 /// \brief Consume the current token and return its location.
1010 SourceLocation consumeToken();
1012 /// \brief Skip tokens until we reach the a token with the given kind
1013 /// (or the end of the file).
1014 void skipUntil(MMToken::TokenKind K);
1016 typedef SmallVector<std::pair<std::string, SourceLocation>, 2> ModuleId;
1017 bool parseModuleId(ModuleId &Id);
1018 void parseModuleDecl();
1019 void parseExternModuleDecl();
1020 void parseRequiresDecl();
1021 void parseHeaderDecl(clang::MMToken::TokenKind,
1022 SourceLocation LeadingLoc);
1023 void parseUmbrellaDirDecl(SourceLocation UmbrellaLoc);
1024 void parseExportDecl();
1025 void parseUseDecl();
1026 void parseLinkDecl();
1027 void parseConfigMacros();
1028 void parseConflict();
1029 void parseInferredModuleDecl(bool Framework, bool Explicit);
1030 bool parseOptionalAttributes(Attributes &Attrs);
1033 explicit ModuleMapParser(Lexer &L, SourceManager &SourceMgr,
1034 const TargetInfo *Target,
1035 DiagnosticsEngine &Diags,
1037 const FileEntry *ModuleMapFile,
1038 const DirectoryEntry *Directory,
1039 const DirectoryEntry *BuiltinIncludeDir,
1041 : L(L), SourceMgr(SourceMgr), Target(Target), Diags(Diags), Map(Map),
1042 ModuleMapFile(ModuleMapFile), Directory(Directory),
1043 BuiltinIncludeDir(BuiltinIncludeDir), IsSystem(IsSystem),
1044 HadError(false), ActiveModule(nullptr)
1050 bool parseModuleMapFile();
1054 SourceLocation ModuleMapParser::consumeToken() {
1056 SourceLocation Result = Tok.getLocation();
1060 L.LexFromRawLexer(LToken);
1061 Tok.Location = LToken.getLocation().getRawEncoding();
1062 switch (LToken.getKind()) {
1063 case tok::raw_identifier: {
1064 StringRef RI = LToken.getRawIdentifier();
1065 Tok.StringData = RI.data();
1066 Tok.StringLength = RI.size();
1067 Tok.Kind = llvm::StringSwitch<MMToken::TokenKind>(RI)
1068 .Case("config_macros", MMToken::ConfigMacros)
1069 .Case("conflict", MMToken::Conflict)
1070 .Case("exclude", MMToken::ExcludeKeyword)
1071 .Case("explicit", MMToken::ExplicitKeyword)
1072 .Case("export", MMToken::ExportKeyword)
1073 .Case("extern", MMToken::ExternKeyword)
1074 .Case("framework", MMToken::FrameworkKeyword)
1075 .Case("header", MMToken::HeaderKeyword)
1076 .Case("link", MMToken::LinkKeyword)
1077 .Case("module", MMToken::ModuleKeyword)
1078 .Case("private", MMToken::PrivateKeyword)
1079 .Case("requires", MMToken::RequiresKeyword)
1080 .Case("umbrella", MMToken::UmbrellaKeyword)
1081 .Case("use", MMToken::UseKeyword)
1082 .Default(MMToken::Identifier);
1087 Tok.Kind = MMToken::Comma;
1091 Tok.Kind = MMToken::EndOfFile;
1095 Tok.Kind = MMToken::LBrace;
1099 Tok.Kind = MMToken::LSquare;
1103 Tok.Kind = MMToken::Period;
1107 Tok.Kind = MMToken::RBrace;
1111 Tok.Kind = MMToken::RSquare;
1115 Tok.Kind = MMToken::Star;
1119 Tok.Kind = MMToken::Exclaim;
1122 case tok::string_literal: {
1123 if (LToken.hasUDSuffix()) {
1124 Diags.Report(LToken.getLocation(), diag::err_invalid_string_udl);
1129 // Parse the string literal.
1130 LangOptions LangOpts;
1131 StringLiteralParser StringLiteral(LToken, SourceMgr, LangOpts, *Target);
1132 if (StringLiteral.hadError)
1135 // Copy the string literal into our string data allocator.
1136 unsigned Length = StringLiteral.GetStringLength();
1137 char *Saved = StringData.Allocate<char>(Length + 1);
1138 memcpy(Saved, StringLiteral.GetString().data(), Length);
1142 Tok.Kind = MMToken::StringLiteral;
1143 Tok.StringData = Saved;
1144 Tok.StringLength = Length;
1152 Diags.Report(LToken.getLocation(), diag::err_mmap_unknown_token);
1160 void ModuleMapParser::skipUntil(MMToken::TokenKind K) {
1161 unsigned braceDepth = 0;
1162 unsigned squareDepth = 0;
1165 case MMToken::EndOfFile:
1168 case MMToken::LBrace:
1169 if (Tok.is(K) && braceDepth == 0 && squareDepth == 0)
1175 case MMToken::LSquare:
1176 if (Tok.is(K) && braceDepth == 0 && squareDepth == 0)
1182 case MMToken::RBrace:
1189 case MMToken::RSquare:
1190 if (squareDepth > 0)
1197 if (braceDepth == 0 && squareDepth == 0 && Tok.is(K))
1206 /// \brief Parse a module-id.
1210 /// identifier '.' module-id
1212 /// \returns true if an error occurred, false otherwise.
1213 bool ModuleMapParser::parseModuleId(ModuleId &Id) {
1216 if (Tok.is(MMToken::Identifier) || Tok.is(MMToken::StringLiteral)) {
1217 Id.push_back(std::make_pair(Tok.getString(), Tok.getLocation()));
1220 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module_name);
1224 if (!Tok.is(MMToken::Period))
1234 /// \brief Enumerates the known attributes.
1235 enum AttributeKind {
1236 /// \brief An unknown attribute.
1238 /// \brief The 'system' attribute.
1240 /// \brief The 'extern_c' attribute.
1242 /// \brief The 'exhaustive' attribute.
1247 /// \brief Parse a module declaration.
1249 /// module-declaration:
1250 /// 'extern' 'module' module-id string-literal
1251 /// 'explicit'[opt] 'framework'[opt] 'module' module-id attributes[opt]
1252 /// { module-member* }
1255 /// requires-declaration
1256 /// header-declaration
1257 /// submodule-declaration
1258 /// export-declaration
1259 /// link-declaration
1261 /// submodule-declaration:
1262 /// module-declaration
1263 /// inferred-submodule-declaration
1264 void ModuleMapParser::parseModuleDecl() {
1265 assert(Tok.is(MMToken::ExplicitKeyword) || Tok.is(MMToken::ModuleKeyword) ||
1266 Tok.is(MMToken::FrameworkKeyword) || Tok.is(MMToken::ExternKeyword));
1267 if (Tok.is(MMToken::ExternKeyword)) {
1268 parseExternModuleDecl();
1272 // Parse 'explicit' or 'framework' keyword, if present.
1273 SourceLocation ExplicitLoc;
1274 bool Explicit = false;
1275 bool Framework = false;
1277 // Parse 'explicit' keyword, if present.
1278 if (Tok.is(MMToken::ExplicitKeyword)) {
1279 ExplicitLoc = consumeToken();
1283 // Parse 'framework' keyword, if present.
1284 if (Tok.is(MMToken::FrameworkKeyword)) {
1289 // Parse 'module' keyword.
1290 if (!Tok.is(MMToken::ModuleKeyword)) {
1291 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module);
1296 consumeToken(); // 'module' keyword
1298 // If we have a wildcard for the module name, this is an inferred submodule.
1300 if (Tok.is(MMToken::Star))
1301 return parseInferredModuleDecl(Framework, Explicit);
1303 // Parse the module name.
1305 if (parseModuleId(Id)) {
1311 if (Id.size() > 1) {
1312 Diags.Report(Id.front().second, diag::err_mmap_nested_submodule_id)
1313 << SourceRange(Id.front().second, Id.back().second);
1318 } else if (Id.size() == 1 && Explicit) {
1319 // Top-level modules can't be explicit.
1320 Diags.Report(ExplicitLoc, diag::err_mmap_explicit_top_level);
1322 ExplicitLoc = SourceLocation();
1326 Module *PreviousActiveModule = ActiveModule;
1327 if (Id.size() > 1) {
1328 // This module map defines a submodule. Go find the module of which it
1330 ActiveModule = nullptr;
1331 for (unsigned I = 0, N = Id.size() - 1; I != N; ++I) {
1332 if (Module *Next = Map.lookupModuleQualified(Id[I].first, ActiveModule)) {
1333 ActiveModule = Next;
1338 Diags.Report(Id[I].second, diag::err_mmap_missing_module_qualified)
1340 << ActiveModule->getTopLevelModule()->getFullModuleName();
1342 Diags.Report(Id[I].second, diag::err_mmap_expected_module_name);
1349 StringRef ModuleName = Id.back().first;
1350 SourceLocation ModuleNameLoc = Id.back().second;
1352 // Parse the optional attribute list.
1354 parseOptionalAttributes(Attrs);
1356 // Parse the opening brace.
1357 if (!Tok.is(MMToken::LBrace)) {
1358 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_lbrace)
1363 SourceLocation LBraceLoc = consumeToken();
1365 // Determine whether this (sub)module has already been defined.
1366 if (Module *Existing = Map.lookupModuleQualified(ModuleName, ActiveModule)) {
1367 if (Existing->DefinitionLoc.isInvalid() && !ActiveModule) {
1368 // Skip the module definition.
1369 skipUntil(MMToken::RBrace);
1370 if (Tok.is(MMToken::RBrace))
1373 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
1374 Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
1380 Diags.Report(ModuleNameLoc, diag::err_mmap_module_redefinition)
1382 Diags.Report(Existing->DefinitionLoc, diag::note_mmap_prev_definition);
1384 // Skip the module definition.
1385 skipUntil(MMToken::RBrace);
1386 if (Tok.is(MMToken::RBrace))
1393 // If this is a submodule, use the parent's module map, since we don't want
1394 // the private module map file.
1395 const FileEntry *ModuleMap = ActiveModule ? ActiveModule->ModuleMap
1398 // Start defining this module.
1399 ActiveModule = Map.findOrCreateModule(ModuleName, ActiveModule, ModuleMap,
1400 Framework, Explicit).first;
1401 ActiveModule->DefinitionLoc = ModuleNameLoc;
1402 if (Attrs.IsSystem || IsSystem)
1403 ActiveModule->IsSystem = true;
1404 if (Attrs.IsExternC)
1405 ActiveModule->IsExternC = true;
1410 case MMToken::EndOfFile:
1411 case MMToken::RBrace:
1415 case MMToken::ConfigMacros:
1416 parseConfigMacros();
1419 case MMToken::Conflict:
1423 case MMToken::ExplicitKeyword:
1424 case MMToken::ExternKeyword:
1425 case MMToken::FrameworkKeyword:
1426 case MMToken::ModuleKeyword:
1430 case MMToken::ExportKeyword:
1434 case MMToken::UseKeyword:
1438 case MMToken::RequiresKeyword:
1439 parseRequiresDecl();
1442 case MMToken::UmbrellaKeyword: {
1443 SourceLocation UmbrellaLoc = consumeToken();
1444 if (Tok.is(MMToken::HeaderKeyword))
1445 parseHeaderDecl(MMToken::UmbrellaKeyword, UmbrellaLoc);
1447 parseUmbrellaDirDecl(UmbrellaLoc);
1451 case MMToken::ExcludeKeyword: {
1452 SourceLocation ExcludeLoc = consumeToken();
1453 if (Tok.is(MMToken::HeaderKeyword)) {
1454 parseHeaderDecl(MMToken::ExcludeKeyword, ExcludeLoc);
1456 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
1462 case MMToken::PrivateKeyword: {
1463 SourceLocation PrivateLoc = consumeToken();
1464 if (Tok.is(MMToken::HeaderKeyword)) {
1465 parseHeaderDecl(MMToken::PrivateKeyword, PrivateLoc);
1467 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
1473 case MMToken::HeaderKeyword:
1474 parseHeaderDecl(MMToken::HeaderKeyword, SourceLocation());
1477 case MMToken::LinkKeyword:
1482 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_member);
1488 if (Tok.is(MMToken::RBrace))
1491 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
1492 Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
1496 // If the active module is a top-level framework, and there are no link
1497 // libraries, automatically link against the framework.
1498 if (ActiveModule->IsFramework && !ActiveModule->isSubFramework() &&
1499 ActiveModule->LinkLibraries.empty()) {
1500 inferFrameworkLink(ActiveModule, Directory, SourceMgr.getFileManager());
1503 // If the module meets all requirements but is still unavailable, mark the
1504 // whole tree as unavailable to prevent it from building.
1505 if (!ActiveModule->IsAvailable && !ActiveModule->IsMissingRequirement &&
1506 ActiveModule->Parent) {
1507 ActiveModule->getTopLevelModule()->markUnavailable();
1508 ActiveModule->getTopLevelModule()->MissingHeaders.append(
1509 ActiveModule->MissingHeaders.begin(), ActiveModule->MissingHeaders.end());
1512 // We're done parsing this module. Pop back to the previous module.
1513 ActiveModule = PreviousActiveModule;
1516 /// \brief Parse an extern module declaration.
1518 /// extern module-declaration:
1519 /// 'extern' 'module' module-id string-literal
1520 void ModuleMapParser::parseExternModuleDecl() {
1521 assert(Tok.is(MMToken::ExternKeyword));
1522 consumeToken(); // 'extern' keyword
1524 // Parse 'module' keyword.
1525 if (!Tok.is(MMToken::ModuleKeyword)) {
1526 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module);
1531 consumeToken(); // 'module' keyword
1533 // Parse the module name.
1535 if (parseModuleId(Id)) {
1540 // Parse the referenced module map file name.
1541 if (!Tok.is(MMToken::StringLiteral)) {
1542 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_mmap_file);
1546 std::string FileName = Tok.getString();
1547 consumeToken(); // filename
1549 StringRef FileNameRef = FileName;
1550 SmallString<128> ModuleMapFileName;
1551 if (llvm::sys::path::is_relative(FileNameRef)) {
1552 ModuleMapFileName += Directory->getName();
1553 llvm::sys::path::append(ModuleMapFileName, FileName);
1554 FileNameRef = ModuleMapFileName.str();
1556 if (const FileEntry *File = SourceMgr.getFileManager().getFile(FileNameRef))
1557 Map.parseModuleMapFile(File, /*IsSystem=*/false);
1560 /// \brief Parse a requires declaration.
1562 /// requires-declaration:
1563 /// 'requires' feature-list
1566 /// feature ',' feature-list
1570 /// '!'[opt] identifier
1571 void ModuleMapParser::parseRequiresDecl() {
1572 assert(Tok.is(MMToken::RequiresKeyword));
1574 // Parse 'requires' keyword.
1577 // Parse the feature-list.
1579 bool RequiredState = true;
1580 if (Tok.is(MMToken::Exclaim)) {
1581 RequiredState = false;
1585 if (!Tok.is(MMToken::Identifier)) {
1586 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_feature);
1591 // Consume the feature name.
1592 std::string Feature = Tok.getString();
1595 // Add this feature.
1596 ActiveModule->addRequirement(Feature, RequiredState,
1597 Map.LangOpts, *Map.Target);
1599 if (!Tok.is(MMToken::Comma))
1602 // Consume the comma.
1607 /// \brief Append to \p Paths the set of paths needed to get to the
1608 /// subframework in which the given module lives.
1609 static void appendSubframeworkPaths(Module *Mod,
1610 SmallVectorImpl<char> &Path) {
1611 // Collect the framework names from the given module to the top-level module.
1612 SmallVector<StringRef, 2> Paths;
1613 for (; Mod; Mod = Mod->Parent) {
1614 if (Mod->IsFramework)
1615 Paths.push_back(Mod->Name);
1621 // Add Frameworks/Name.framework for each subframework.
1622 for (unsigned I = Paths.size() - 1; I != 0; --I)
1623 llvm::sys::path::append(Path, "Frameworks", Paths[I-1] + ".framework");
1626 /// \brief Parse a header declaration.
1628 /// header-declaration:
1629 /// 'umbrella'[opt] 'header' string-literal
1630 /// 'exclude'[opt] 'header' string-literal
1631 void ModuleMapParser::parseHeaderDecl(MMToken::TokenKind LeadingToken,
1632 SourceLocation LeadingLoc) {
1633 assert(Tok.is(MMToken::HeaderKeyword));
1636 // Parse the header name.
1637 if (!Tok.is(MMToken::StringLiteral)) {
1638 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
1643 Module::HeaderDirective Header;
1644 Header.FileName = Tok.getString();
1645 Header.FileNameLoc = consumeToken();
1647 // Check whether we already have an umbrella.
1648 if (LeadingToken == MMToken::UmbrellaKeyword && ActiveModule->Umbrella) {
1649 Diags.Report(Header.FileNameLoc, diag::err_mmap_umbrella_clash)
1650 << ActiveModule->getFullModuleName();
1655 // Look for this file.
1656 const FileEntry *File = nullptr;
1657 const FileEntry *BuiltinFile = nullptr;
1658 SmallString<128> PathName;
1659 if (llvm::sys::path::is_absolute(Header.FileName)) {
1660 PathName = Header.FileName;
1661 File = SourceMgr.getFileManager().getFile(PathName);
1663 // Search for the header file within the search directory.
1664 PathName = Directory->getName();
1665 unsigned PathLength = PathName.size();
1667 if (ActiveModule->isPartOfFramework()) {
1668 appendSubframeworkPaths(ActiveModule, PathName);
1670 // Check whether this file is in the public headers.
1671 llvm::sys::path::append(PathName, "Headers", Header.FileName);
1672 File = SourceMgr.getFileManager().getFile(PathName);
1675 // Check whether this file is in the private headers.
1676 PathName.resize(PathLength);
1677 llvm::sys::path::append(PathName, "PrivateHeaders", Header.FileName);
1678 File = SourceMgr.getFileManager().getFile(PathName);
1681 // Lookup for normal headers.
1682 llvm::sys::path::append(PathName, Header.FileName);
1683 File = SourceMgr.getFileManager().getFile(PathName);
1685 // If this is a system module with a top-level header, this header
1686 // may have a counterpart (or replacement) in the set of headers
1687 // supplied by Clang. Find that builtin header.
1688 if (ActiveModule->IsSystem && LeadingToken != MMToken::UmbrellaKeyword &&
1689 BuiltinIncludeDir && BuiltinIncludeDir != Directory &&
1690 isBuiltinHeader(Header.FileName)) {
1691 SmallString<128> BuiltinPathName(BuiltinIncludeDir->getName());
1692 llvm::sys::path::append(BuiltinPathName, Header.FileName);
1693 BuiltinFile = SourceMgr.getFileManager().getFile(BuiltinPathName);
1695 // If Clang supplies this header but the underlying system does not,
1696 // just silently swap in our builtin version. Otherwise, we'll end
1697 // up adding both (later).
1698 if (!File && BuiltinFile) {
1700 BuiltinFile = nullptr;
1706 // FIXME: We shouldn't be eagerly stat'ing every file named in a module map.
1707 // Come up with a lazy way to do this.
1709 if (LeadingToken == MMToken::UmbrellaKeyword) {
1710 const DirectoryEntry *UmbrellaDir = File->getDir();
1711 if (Module *UmbrellaModule = Map.UmbrellaDirs[UmbrellaDir]) {
1712 Diags.Report(LeadingLoc, diag::err_mmap_umbrella_clash)
1713 << UmbrellaModule->getFullModuleName();
1716 // Record this umbrella header.
1717 Map.setUmbrellaHeader(ActiveModule, File);
1720 // Record this header.
1721 ModuleMap::ModuleHeaderRole Role = ModuleMap::NormalHeader;
1722 if (LeadingToken == MMToken::ExcludeKeyword)
1723 Role = ModuleMap::ExcludedHeader;
1724 else if (LeadingToken == MMToken::PrivateKeyword)
1725 Role = ModuleMap::PrivateHeader;
1727 assert(LeadingToken == MMToken::HeaderKeyword);
1729 Map.addHeader(ActiveModule, File, Role);
1731 // If there is a builtin counterpart to this file, add it now.
1733 Map.addHeader(ActiveModule, BuiltinFile, Role);
1735 } else if (LeadingToken != MMToken::ExcludeKeyword) {
1736 // Ignore excluded header files. They're optional anyway.
1738 // If we find a module that has a missing header, we mark this module as
1739 // unavailable and store the header directive for displaying diagnostics.
1740 Header.IsUmbrella = LeadingToken == MMToken::UmbrellaKeyword;
1741 ActiveModule->markUnavailable();
1742 ActiveModule->MissingHeaders.push_back(Header);
1746 /// \brief Parse an umbrella directory declaration.
1748 /// umbrella-dir-declaration:
1749 /// umbrella string-literal
1750 void ModuleMapParser::parseUmbrellaDirDecl(SourceLocation UmbrellaLoc) {
1751 // Parse the directory name.
1752 if (!Tok.is(MMToken::StringLiteral)) {
1753 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
1759 std::string DirName = Tok.getString();
1760 SourceLocation DirNameLoc = consumeToken();
1762 // Check whether we already have an umbrella.
1763 if (ActiveModule->Umbrella) {
1764 Diags.Report(DirNameLoc, diag::err_mmap_umbrella_clash)
1765 << ActiveModule->getFullModuleName();
1770 // Look for this file.
1771 const DirectoryEntry *Dir = nullptr;
1772 if (llvm::sys::path::is_absolute(DirName))
1773 Dir = SourceMgr.getFileManager().getDirectory(DirName);
1775 SmallString<128> PathName;
1776 PathName = Directory->getName();
1777 llvm::sys::path::append(PathName, DirName);
1778 Dir = SourceMgr.getFileManager().getDirectory(PathName);
1782 Diags.Report(DirNameLoc, diag::err_mmap_umbrella_dir_not_found)
1788 if (Module *OwningModule = Map.UmbrellaDirs[Dir]) {
1789 Diags.Report(UmbrellaLoc, diag::err_mmap_umbrella_clash)
1790 << OwningModule->getFullModuleName();
1795 // Record this umbrella directory.
1796 Map.setUmbrellaDir(ActiveModule, Dir);
1799 /// \brief Parse a module export declaration.
1801 /// export-declaration:
1802 /// 'export' wildcard-module-id
1804 /// wildcard-module-id:
1807 /// identifier '.' wildcard-module-id
1808 void ModuleMapParser::parseExportDecl() {
1809 assert(Tok.is(MMToken::ExportKeyword));
1810 SourceLocation ExportLoc = consumeToken();
1812 // Parse the module-id with an optional wildcard at the end.
1813 ModuleId ParsedModuleId;
1814 bool Wildcard = false;
1816 if (Tok.is(MMToken::Identifier)) {
1817 ParsedModuleId.push_back(std::make_pair(Tok.getString(),
1818 Tok.getLocation()));
1821 if (Tok.is(MMToken::Period)) {
1829 if(Tok.is(MMToken::Star)) {
1835 Diags.Report(Tok.getLocation(), diag::err_mmap_module_id);
1840 Module::UnresolvedExportDecl Unresolved = {
1841 ExportLoc, ParsedModuleId, Wildcard
1843 ActiveModule->UnresolvedExports.push_back(Unresolved);
1846 /// \brief Parse a module uses declaration.
1848 /// uses-declaration:
1849 /// 'uses' wildcard-module-id
1850 void ModuleMapParser::parseUseDecl() {
1851 assert(Tok.is(MMToken::UseKeyword));
1853 // Parse the module-id.
1854 ModuleId ParsedModuleId;
1855 parseModuleId(ParsedModuleId);
1857 ActiveModule->UnresolvedDirectUses.push_back(ParsedModuleId);
1860 /// \brief Parse a link declaration.
1862 /// module-declaration:
1863 /// 'link' 'framework'[opt] string-literal
1864 void ModuleMapParser::parseLinkDecl() {
1865 assert(Tok.is(MMToken::LinkKeyword));
1866 SourceLocation LinkLoc = consumeToken();
1868 // Parse the optional 'framework' keyword.
1869 bool IsFramework = false;
1870 if (Tok.is(MMToken::FrameworkKeyword)) {
1875 // Parse the library name
1876 if (!Tok.is(MMToken::StringLiteral)) {
1877 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_library_name)
1878 << IsFramework << SourceRange(LinkLoc);
1883 std::string LibraryName = Tok.getString();
1885 ActiveModule->LinkLibraries.push_back(Module::LinkLibrary(LibraryName,
1889 /// \brief Parse a configuration macro declaration.
1891 /// module-declaration:
1892 /// 'config_macros' attributes[opt] config-macro-list?
1894 /// config-macro-list:
1895 /// identifier (',' identifier)?
1896 void ModuleMapParser::parseConfigMacros() {
1897 assert(Tok.is(MMToken::ConfigMacros));
1898 SourceLocation ConfigMacrosLoc = consumeToken();
1900 // Only top-level modules can have configuration macros.
1901 if (ActiveModule->Parent) {
1902 Diags.Report(ConfigMacrosLoc, diag::err_mmap_config_macro_submodule);
1905 // Parse the optional attributes.
1907 parseOptionalAttributes(Attrs);
1908 if (Attrs.IsExhaustive && !ActiveModule->Parent) {
1909 ActiveModule->ConfigMacrosExhaustive = true;
1912 // If we don't have an identifier, we're done.
1913 if (!Tok.is(MMToken::Identifier))
1916 // Consume the first identifier.
1917 if (!ActiveModule->Parent) {
1918 ActiveModule->ConfigMacros.push_back(Tok.getString().str());
1923 // If there's a comma, consume it.
1924 if (!Tok.is(MMToken::Comma))
1928 // We expect to see a macro name here.
1929 if (!Tok.is(MMToken::Identifier)) {
1930 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_config_macro);
1934 // Consume the macro name.
1935 if (!ActiveModule->Parent) {
1936 ActiveModule->ConfigMacros.push_back(Tok.getString().str());
1942 /// \brief Format a module-id into a string.
1943 static std::string formatModuleId(const ModuleId &Id) {
1946 llvm::raw_string_ostream OS(result);
1948 for (unsigned I = 0, N = Id.size(); I != N; ++I) {
1958 /// \brief Parse a conflict declaration.
1960 /// module-declaration:
1961 /// 'conflict' module-id ',' string-literal
1962 void ModuleMapParser::parseConflict() {
1963 assert(Tok.is(MMToken::Conflict));
1964 SourceLocation ConflictLoc = consumeToken();
1965 Module::UnresolvedConflict Conflict;
1967 // Parse the module-id.
1968 if (parseModuleId(Conflict.Id))
1972 if (!Tok.is(MMToken::Comma)) {
1973 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_conflicts_comma)
1974 << SourceRange(ConflictLoc);
1979 // Parse the message.
1980 if (!Tok.is(MMToken::StringLiteral)) {
1981 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_conflicts_message)
1982 << formatModuleId(Conflict.Id);
1985 Conflict.Message = Tok.getString().str();
1988 // Add this unresolved conflict.
1989 ActiveModule->UnresolvedConflicts.push_back(Conflict);
1992 /// \brief Parse an inferred module declaration (wildcard modules).
1994 /// module-declaration:
1995 /// 'explicit'[opt] 'framework'[opt] 'module' * attributes[opt]
1996 /// { inferred-module-member* }
1998 /// inferred-module-member:
2000 /// 'exclude' identifier
2001 void ModuleMapParser::parseInferredModuleDecl(bool Framework, bool Explicit) {
2002 assert(Tok.is(MMToken::Star));
2003 SourceLocation StarLoc = consumeToken();
2004 bool Failed = false;
2006 // Inferred modules must be submodules.
2007 if (!ActiveModule && !Framework) {
2008 Diags.Report(StarLoc, diag::err_mmap_top_level_inferred_submodule);
2013 // Inferred modules must have umbrella directories.
2014 if (!Failed && ActiveModule->IsAvailable &&
2015 !ActiveModule->getUmbrellaDir()) {
2016 Diags.Report(StarLoc, diag::err_mmap_inferred_no_umbrella);
2020 // Check for redefinition of an inferred module.
2021 if (!Failed && ActiveModule->InferSubmodules) {
2022 Diags.Report(StarLoc, diag::err_mmap_inferred_redef);
2023 if (ActiveModule->InferredSubmoduleLoc.isValid())
2024 Diags.Report(ActiveModule->InferredSubmoduleLoc,
2025 diag::note_mmap_prev_definition);
2029 // Check for the 'framework' keyword, which is not permitted here.
2031 Diags.Report(StarLoc, diag::err_mmap_inferred_framework_submodule);
2034 } else if (Explicit) {
2035 Diags.Report(StarLoc, diag::err_mmap_explicit_inferred_framework);
2039 // If there were any problems with this inferred submodule, skip its body.
2041 if (Tok.is(MMToken::LBrace)) {
2043 skipUntil(MMToken::RBrace);
2044 if (Tok.is(MMToken::RBrace))
2051 // Parse optional attributes.
2053 parseOptionalAttributes(Attrs);
2056 // Note that we have an inferred submodule.
2057 ActiveModule->InferSubmodules = true;
2058 ActiveModule->InferredSubmoduleLoc = StarLoc;
2059 ActiveModule->InferExplicitSubmodules = Explicit;
2061 // We'll be inferring framework modules for this directory.
2062 Map.InferredDirectories[Directory].InferModules = true;
2063 Map.InferredDirectories[Directory].InferSystemModules = Attrs.IsSystem;
2064 Map.InferredDirectories[Directory].ModuleMapFile = ModuleMapFile;
2065 // FIXME: Handle the 'framework' keyword.
2068 // Parse the opening brace.
2069 if (!Tok.is(MMToken::LBrace)) {
2070 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_lbrace_wildcard);
2074 SourceLocation LBraceLoc = consumeToken();
2076 // Parse the body of the inferred submodule.
2080 case MMToken::EndOfFile:
2081 case MMToken::RBrace:
2085 case MMToken::ExcludeKeyword: {
2087 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member)
2088 << (ActiveModule != nullptr);
2094 if (!Tok.is(MMToken::Identifier)) {
2095 Diags.Report(Tok.getLocation(), diag::err_mmap_missing_exclude_name);
2099 Map.InferredDirectories[Directory].ExcludedModules
2100 .push_back(Tok.getString());
2105 case MMToken::ExportKeyword:
2106 if (!ActiveModule) {
2107 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member)
2108 << (ActiveModule != nullptr);
2114 if (Tok.is(MMToken::Star))
2115 ActiveModule->InferExportWildcard = true;
2117 Diags.Report(Tok.getLocation(),
2118 diag::err_mmap_expected_export_wildcard);
2122 case MMToken::ExplicitKeyword:
2123 case MMToken::ModuleKeyword:
2124 case MMToken::HeaderKeyword:
2125 case MMToken::PrivateKeyword:
2126 case MMToken::UmbrellaKeyword:
2128 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member)
2129 << (ActiveModule != nullptr);
2135 if (Tok.is(MMToken::RBrace))
2138 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
2139 Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
2144 /// \brief Parse optional attributes.
2147 /// attribute attributes
2153 /// \param Attrs Will be filled in with the parsed attributes.
2155 /// \returns true if an error occurred, false otherwise.
2156 bool ModuleMapParser::parseOptionalAttributes(Attributes &Attrs) {
2157 bool HadError = false;
2159 while (Tok.is(MMToken::LSquare)) {
2161 SourceLocation LSquareLoc = consumeToken();
2163 // Check whether we have an attribute name here.
2164 if (!Tok.is(MMToken::Identifier)) {
2165 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_attribute);
2166 skipUntil(MMToken::RSquare);
2167 if (Tok.is(MMToken::RSquare))
2172 // Decode the attribute name.
2173 AttributeKind Attribute
2174 = llvm::StringSwitch<AttributeKind>(Tok.getString())
2175 .Case("exhaustive", AT_exhaustive)
2176 .Case("extern_c", AT_extern_c)
2177 .Case("system", AT_system)
2178 .Default(AT_unknown);
2179 switch (Attribute) {
2181 Diags.Report(Tok.getLocation(), diag::warn_mmap_unknown_attribute)
2186 Attrs.IsSystem = true;
2190 Attrs.IsExternC = true;
2194 Attrs.IsExhaustive = true;
2200 if (!Tok.is(MMToken::RSquare)) {
2201 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rsquare);
2202 Diags.Report(LSquareLoc, diag::note_mmap_lsquare_match);
2203 skipUntil(MMToken::RSquare);
2207 if (Tok.is(MMToken::RSquare))
2214 /// \brief Parse a module map file.
2216 /// module-map-file:
2217 /// module-declaration*
2218 bool ModuleMapParser::parseModuleMapFile() {
2221 case MMToken::EndOfFile:
2224 case MMToken::ExplicitKeyword:
2225 case MMToken::ExternKeyword:
2226 case MMToken::ModuleKeyword:
2227 case MMToken::FrameworkKeyword:
2231 case MMToken::Comma:
2232 case MMToken::ConfigMacros:
2233 case MMToken::Conflict:
2234 case MMToken::Exclaim:
2235 case MMToken::ExcludeKeyword:
2236 case MMToken::ExportKeyword:
2237 case MMToken::HeaderKeyword:
2238 case MMToken::Identifier:
2239 case MMToken::LBrace:
2240 case MMToken::LinkKeyword:
2241 case MMToken::LSquare:
2242 case MMToken::Period:
2243 case MMToken::PrivateKeyword:
2244 case MMToken::RBrace:
2245 case MMToken::RSquare:
2246 case MMToken::RequiresKeyword:
2248 case MMToken::StringLiteral:
2249 case MMToken::UmbrellaKeyword:
2250 case MMToken::UseKeyword:
2251 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module);
2259 bool ModuleMap::parseModuleMapFile(const FileEntry *File, bool IsSystem) {
2260 llvm::DenseMap<const FileEntry *, bool>::iterator Known
2261 = ParsedModuleMap.find(File);
2262 if (Known != ParsedModuleMap.end())
2263 return Known->second;
2265 assert(Target && "Missing target information");
2266 auto FileCharacter = IsSystem ? SrcMgr::C_System : SrcMgr::C_User;
2267 FileID ID = SourceMgr.createFileID(File, SourceLocation(), FileCharacter);
2268 const llvm::MemoryBuffer *Buffer = SourceMgr.getBuffer(ID);
2270 return ParsedModuleMap[File] = true;
2272 // Find the directory for the module. For frameworks, that may require going
2273 // up from the 'Modules' directory.
2274 const DirectoryEntry *Dir = File->getDir();
2275 StringRef DirName(Dir->getName());
2276 if (llvm::sys::path::filename(DirName) == "Modules") {
2277 DirName = llvm::sys::path::parent_path(DirName);
2278 if (DirName.endswith(".framework"))
2279 Dir = SourceMgr.getFileManager().getDirectory(DirName);
2280 assert(Dir && "parent must exist");
2283 // Parse this module map file.
2284 Lexer L(ID, SourceMgr.getBuffer(ID), SourceMgr, MMapLangOpts);
2285 ModuleMapParser Parser(L, SourceMgr, Target, Diags, *this, File, Dir,
2286 BuiltinIncludeDir, IsSystem);
2287 bool Result = Parser.parseModuleMapFile();
2288 ParsedModuleMap[File] = Result;