xref: /llvm-project/clang/lib/Lex/ModuleMap.cpp (revision b171a59bfd152346ca068c73ccb61fe28643d024)
1 //===--- ModuleMap.cpp - Describe the layout of modules ---------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the ModuleMap implementation, which describes the layout
11 // of a module as it relates to headers.
12 //
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/HeaderSearchOptions.h"
23 #include "clang/Lex/LexDiagnostic.h"
24 #include "clang/Lex/Lexer.h"
25 #include "clang/Lex/LiteralSupport.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/ADT/StringSwitch.h"
28 #include "llvm/Support/Allocator.h"
29 #include "llvm/Support/FileSystem.h"
30 #include "llvm/Support/Host.h"
31 #include "llvm/Support/Path.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include <stdlib.h>
34 #if defined(LLVM_ON_UNIX)
35 #include <limits.h>
36 #endif
37 using namespace clang;
38 
39 Module::ExportDecl
40 ModuleMap::resolveExport(Module *Mod,
41                          const Module::UnresolvedExportDecl &Unresolved,
42                          bool Complain) const {
43   // We may have just a wildcard.
44   if (Unresolved.Id.empty()) {
45     assert(Unresolved.Wildcard && "Invalid unresolved export");
46     return Module::ExportDecl(nullptr, true);
47   }
48 
49   // Resolve the module-id.
50   Module *Context = resolveModuleId(Unresolved.Id, Mod, Complain);
51   if (!Context)
52     return Module::ExportDecl();
53 
54   return Module::ExportDecl(Context, Unresolved.Wildcard);
55 }
56 
57 Module *ModuleMap::resolveModuleId(const ModuleId &Id, Module *Mod,
58                                    bool Complain) const {
59   // Find the starting module.
60   Module *Context = lookupModuleUnqualified(Id[0].first, Mod);
61   if (!Context) {
62     if (Complain)
63       Diags.Report(Id[0].second, diag::err_mmap_missing_module_unqualified)
64       << Id[0].first << Mod->getFullModuleName();
65 
66     return nullptr;
67   }
68 
69   // Dig into the module path.
70   for (unsigned I = 1, N = Id.size(); I != N; ++I) {
71     Module *Sub = lookupModuleQualified(Id[I].first, Context);
72     if (!Sub) {
73       if (Complain)
74         Diags.Report(Id[I].second, diag::err_mmap_missing_module_qualified)
75         << Id[I].first << Context->getFullModuleName()
76         << SourceRange(Id[0].second, Id[I-1].second);
77 
78       return nullptr;
79     }
80 
81     Context = Sub;
82   }
83 
84   return Context;
85 }
86 
87 ModuleMap::ModuleMap(SourceManager &SourceMgr, DiagnosticsEngine &Diags,
88                      const LangOptions &LangOpts, const TargetInfo *Target,
89                      HeaderSearch &HeaderInfo)
90     : SourceMgr(SourceMgr), Diags(Diags), LangOpts(LangOpts), Target(Target),
91       HeaderInfo(HeaderInfo), BuiltinIncludeDir(nullptr),
92       SourceModule(nullptr), NumCreatedModules(0) {
93   MMapLangOpts.LineComment = true;
94 }
95 
96 ModuleMap::~ModuleMap() {
97   for (auto &M : Modules)
98     delete M.getValue();
99 }
100 
101 void ModuleMap::setTarget(const TargetInfo &Target) {
102   assert((!this->Target || this->Target == &Target) &&
103          "Improper target override");
104   this->Target = &Target;
105 }
106 
107 /// \brief "Sanitize" a filename so that it can be used as an identifier.
108 static StringRef sanitizeFilenameAsIdentifier(StringRef Name,
109                                               SmallVectorImpl<char> &Buffer) {
110   if (Name.empty())
111     return Name;
112 
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.
116     Buffer.clear();
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]);
123       else
124         Buffer.push_back('_');
125     }
126 
127     Name = StringRef(Buffer.data(), Buffer.size());
128   }
129 
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"
134            .Default(false)) {
135     if (Name.data() != Buffer.data())
136       Buffer.append(Name.begin(), Name.end());
137     Buffer.push_back('_');
138     Name = StringRef(Buffer.data(), Buffer.size());
139   }
140 
141   return Name;
142 }
143 
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
146 /// headers.
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("stdatomic.h", true)
155            .Case("stdbool.h", true)
156            .Case("stddef.h", true)
157            .Case("stdint.h", true)
158            .Case("tgmath.h", true)
159            .Case("unwind.h", true)
160            .Default(false);
161 }
162 
163 ModuleMap::HeadersMap::iterator
164 ModuleMap::findKnownHeader(const FileEntry *File) {
165   HeadersMap::iterator Known = Headers.find(File);
166   if (HeaderInfo.getHeaderSearchOpts().ImplicitModuleMaps &&
167       Known == Headers.end() && File->getDir() == BuiltinIncludeDir &&
168       isBuiltinHeader(llvm::sys::path::filename(File->getName()))) {
169     HeaderInfo.loadTopLevelSystemModules();
170     return Headers.find(File);
171   }
172   return Known;
173 }
174 
175 ModuleMap::KnownHeader
176 ModuleMap::findHeaderInUmbrellaDirs(const FileEntry *File,
177                     SmallVectorImpl<const DirectoryEntry *> &IntermediateDirs) {
178   if (UmbrellaDirs.empty())
179     return KnownHeader();
180 
181   const DirectoryEntry *Dir = File->getDir();
182   assert(Dir && "file in no directory");
183 
184   // Note: as an egregious but useful hack we use the real path here, because
185   // frameworks moving from top-level frameworks to embedded frameworks tend
186   // to be symlinked from the top-level location to the embedded location,
187   // and we need to resolve lookups as if we had found the embedded location.
188   StringRef DirName = SourceMgr.getFileManager().getCanonicalName(Dir);
189 
190   // Keep walking up the directory hierarchy, looking for a directory with
191   // an umbrella header.
192   do {
193     auto KnownDir = UmbrellaDirs.find(Dir);
194     if (KnownDir != UmbrellaDirs.end())
195       return KnownHeader(KnownDir->second, NormalHeader);
196 
197     IntermediateDirs.push_back(Dir);
198 
199     // Retrieve our parent path.
200     DirName = llvm::sys::path::parent_path(DirName);
201     if (DirName.empty())
202       break;
203 
204     // Resolve the parent path to a directory entry.
205     Dir = SourceMgr.getFileManager().getDirectory(DirName);
206   } while (Dir);
207   return KnownHeader();
208 }
209 
210 static bool violatesPrivateInclude(Module *RequestingModule,
211                                    const FileEntry *IncFileEnt,
212                                    ModuleMap::KnownHeader Header) {
213 #ifndef NDEBUG
214   if (Header.getRole() & ModuleMap::PrivateHeader) {
215     // Check for consistency between the module header role
216     // as obtained from the lookup and as obtained from the module.
217     // This check is not cheap, so enable it only for debugging.
218     bool IsPrivate = false;
219     SmallVectorImpl<Module::Header> *HeaderList[] = {
220         &Header.getModule()->Headers[Module::HK_Private],
221         &Header.getModule()->Headers[Module::HK_PrivateTextual]};
222     for (auto *Hs : HeaderList)
223       IsPrivate |=
224           std::find_if(Hs->begin(), Hs->end(), [&](const Module::Header &H) {
225             return H.Entry == IncFileEnt;
226           }) != Hs->end();
227     assert(IsPrivate && "inconsistent headers and roles");
228   }
229 #endif
230   return !Header.isAccessibleFrom(RequestingModule);
231 }
232 
233 static Module *getTopLevelOrNull(Module *M) {
234   return M ? M->getTopLevelModule() : nullptr;
235 }
236 
237 void ModuleMap::diagnoseHeaderInclusion(Module *RequestingModule,
238                                         bool RequestingModuleIsModuleInterface,
239                                         SourceLocation FilenameLoc,
240                                         StringRef Filename,
241                                         const FileEntry *File) {
242   // No errors for indirect modules. This may be a bit of a problem for modules
243   // with no source files.
244   if (getTopLevelOrNull(RequestingModule) != getTopLevelOrNull(SourceModule))
245     return;
246 
247   if (RequestingModule)
248     resolveUses(RequestingModule, /*Complain=*/false);
249 
250   bool Excluded = false;
251   Module *Private = nullptr;
252   Module *NotUsed = nullptr;
253 
254   HeadersMap::iterator Known = findKnownHeader(File);
255   if (Known != Headers.end()) {
256     for (const KnownHeader &Header : Known->second) {
257       // Remember private headers for later printing of a diagnostic.
258       if (violatesPrivateInclude(RequestingModule, File, Header)) {
259         Private = Header.getModule();
260         continue;
261       }
262 
263       // If uses need to be specified explicitly, we are only allowed to return
264       // modules that are explicitly used by the requesting module.
265       if (RequestingModule && LangOpts.ModulesDeclUse &&
266           !RequestingModule->directlyUses(Header.getModule())) {
267         NotUsed = Header.getModule();
268         continue;
269       }
270 
271       // We have found a module that we can happily use.
272       return;
273     }
274 
275     Excluded = true;
276   }
277 
278   // We have found a header, but it is private.
279   if (Private) {
280     Diags.Report(FilenameLoc, diag::warn_use_of_private_header_outside_module)
281         << Filename;
282     return;
283   }
284 
285   // We have found a module, but we don't use it.
286   if (NotUsed) {
287     Diags.Report(FilenameLoc, diag::err_undeclared_use_of_module)
288         << RequestingModule->getFullModuleName() << Filename;
289     return;
290   }
291 
292   if (Excluded || isHeaderInUmbrellaDirs(File))
293     return;
294 
295   // At this point, only non-modular includes remain.
296 
297   if (LangOpts.ModulesStrictDeclUse) {
298     Diags.Report(FilenameLoc, diag::err_undeclared_use_of_module)
299         << RequestingModule->getFullModuleName() << Filename;
300   } else if (RequestingModule && RequestingModuleIsModuleInterface) {
301     diag::kind DiagID = RequestingModule->getTopLevelModule()->IsFramework ?
302         diag::warn_non_modular_include_in_framework_module :
303         diag::warn_non_modular_include_in_module;
304     Diags.Report(FilenameLoc, DiagID) << RequestingModule->getFullModuleName();
305   }
306 }
307 
308 static bool isBetterKnownHeader(const ModuleMap::KnownHeader &New,
309                                 const ModuleMap::KnownHeader &Old) {
310   // Prefer available modules.
311   if (New.getModule()->isAvailable() && !Old.getModule()->isAvailable())
312     return true;
313 
314   // Prefer a public header over a private header.
315   if ((New.getRole() & ModuleMap::PrivateHeader) !=
316       (Old.getRole() & ModuleMap::PrivateHeader))
317     return !(New.getRole() & ModuleMap::PrivateHeader);
318 
319   // Prefer a non-textual header over a textual header.
320   if ((New.getRole() & ModuleMap::TextualHeader) !=
321       (Old.getRole() & ModuleMap::TextualHeader))
322     return !(New.getRole() & ModuleMap::TextualHeader);
323 
324   // Don't have a reason to choose between these. Just keep the first one.
325   return false;
326 }
327 
328 ModuleMap::KnownHeader ModuleMap::findModuleForHeader(const FileEntry *File) {
329   auto MakeResult = [&](ModuleMap::KnownHeader R) -> ModuleMap::KnownHeader {
330     if (R.getRole() & ModuleMap::TextualHeader)
331       return ModuleMap::KnownHeader();
332     return R;
333   };
334 
335   HeadersMap::iterator Known = findKnownHeader(File);
336   if (Known != Headers.end()) {
337     ModuleMap::KnownHeader Result;
338     // Iterate over all modules that 'File' is part of to find the best fit.
339     for (KnownHeader &H : Known->second) {
340       // Prefer a header from the source module over all others.
341       if (H.getModule()->getTopLevelModule() == SourceModule)
342         return MakeResult(H);
343       if (!Result || isBetterKnownHeader(H, Result))
344         Result = H;
345     }
346     return MakeResult(Result);
347   }
348 
349   return MakeResult(findOrCreateModuleForHeaderInUmbrellaDir(File));
350 }
351 
352 ModuleMap::KnownHeader
353 ModuleMap::findOrCreateModuleForHeaderInUmbrellaDir(const FileEntry *File) {
354   assert(!Headers.count(File) && "already have a module for this header");
355 
356   SmallVector<const DirectoryEntry *, 2> SkippedDirs;
357   KnownHeader H = findHeaderInUmbrellaDirs(File, SkippedDirs);
358   if (H) {
359     Module *Result = H.getModule();
360 
361     // Search up the module stack until we find a module with an umbrella
362     // directory.
363     Module *UmbrellaModule = Result;
364     while (!UmbrellaModule->getUmbrellaDir() && UmbrellaModule->Parent)
365       UmbrellaModule = UmbrellaModule->Parent;
366 
367     if (UmbrellaModule->InferSubmodules) {
368       const FileEntry *UmbrellaModuleMap =
369           getModuleMapFileForUniquing(UmbrellaModule);
370 
371       // Infer submodules for each of the directories we found between
372       // the directory of the umbrella header and the directory where
373       // the actual header is located.
374       bool Explicit = UmbrellaModule->InferExplicitSubmodules;
375 
376       for (unsigned I = SkippedDirs.size(); I != 0; --I) {
377         // Find or create the module that corresponds to this directory name.
378         SmallString<32> NameBuf;
379         StringRef Name = sanitizeFilenameAsIdentifier(
380             llvm::sys::path::stem(SkippedDirs[I-1]->getName()), NameBuf);
381         Result = findOrCreateModule(Name, Result, /*IsFramework=*/false,
382                                     Explicit).first;
383         InferredModuleAllowedBy[Result] = UmbrellaModuleMap;
384         Result->IsInferred = true;
385 
386         // Associate the module and the directory.
387         UmbrellaDirs[SkippedDirs[I-1]] = Result;
388 
389         // If inferred submodules export everything they import, add a
390         // wildcard to the set of exports.
391         if (UmbrellaModule->InferExportWildcard && Result->Exports.empty())
392           Result->Exports.push_back(Module::ExportDecl(nullptr, true));
393       }
394 
395       // Infer a submodule with the same name as this header file.
396       SmallString<32> NameBuf;
397       StringRef Name = sanitizeFilenameAsIdentifier(
398                          llvm::sys::path::stem(File->getName()), NameBuf);
399       Result = findOrCreateModule(Name, Result, /*IsFramework=*/false,
400                                   Explicit).first;
401       InferredModuleAllowedBy[Result] = UmbrellaModuleMap;
402       Result->IsInferred = true;
403       Result->addTopHeader(File);
404 
405       // If inferred submodules export everything they import, add a
406       // wildcard to the set of exports.
407       if (UmbrellaModule->InferExportWildcard && Result->Exports.empty())
408         Result->Exports.push_back(Module::ExportDecl(nullptr, true));
409     } else {
410       // Record each of the directories we stepped through as being part of
411       // the module we found, since the umbrella header covers them all.
412       for (unsigned I = 0, N = SkippedDirs.size(); I != N; ++I)
413         UmbrellaDirs[SkippedDirs[I]] = Result;
414     }
415 
416     KnownHeader Header(Result, NormalHeader);
417     Headers[File].push_back(Header);
418     return Header;
419   }
420 
421   return KnownHeader();
422 }
423 
424 ArrayRef<ModuleMap::KnownHeader>
425 ModuleMap::findAllModulesForHeader(const FileEntry *File) const {
426   auto It = Headers.find(File);
427   if (It == Headers.end())
428     return None;
429   return It->second;
430 }
431 
432 bool ModuleMap::isHeaderInUnavailableModule(const FileEntry *Header) const {
433   return isHeaderUnavailableInModule(Header, nullptr);
434 }
435 
436 bool
437 ModuleMap::isHeaderUnavailableInModule(const FileEntry *Header,
438                                        const Module *RequestingModule) const {
439   HeadersMap::const_iterator Known = Headers.find(Header);
440   if (Known != Headers.end()) {
441     for (SmallVectorImpl<KnownHeader>::const_iterator
442              I = Known->second.begin(),
443              E = Known->second.end();
444          I != E; ++I) {
445       if (I->isAvailable() && (!RequestingModule ||
446                                I->getModule()->isSubModuleOf(RequestingModule)))
447         return false;
448     }
449     return true;
450   }
451 
452   const DirectoryEntry *Dir = Header->getDir();
453   SmallVector<const DirectoryEntry *, 2> SkippedDirs;
454   StringRef DirName = Dir->getName();
455 
456   auto IsUnavailable = [&](const Module *M) {
457     return !M->isAvailable() && (!RequestingModule ||
458                                  M->isSubModuleOf(RequestingModule));
459   };
460 
461   // Keep walking up the directory hierarchy, looking for a directory with
462   // an umbrella header.
463   do {
464     llvm::DenseMap<const DirectoryEntry *, Module *>::const_iterator KnownDir
465       = UmbrellaDirs.find(Dir);
466     if (KnownDir != UmbrellaDirs.end()) {
467       Module *Found = KnownDir->second;
468       if (IsUnavailable(Found))
469         return true;
470 
471       // Search up the module stack until we find a module with an umbrella
472       // directory.
473       Module *UmbrellaModule = Found;
474       while (!UmbrellaModule->getUmbrellaDir() && UmbrellaModule->Parent)
475         UmbrellaModule = UmbrellaModule->Parent;
476 
477       if (UmbrellaModule->InferSubmodules) {
478         for (unsigned I = SkippedDirs.size(); I != 0; --I) {
479           // Find or create the module that corresponds to this directory name.
480           SmallString<32> NameBuf;
481           StringRef Name = sanitizeFilenameAsIdentifier(
482                              llvm::sys::path::stem(SkippedDirs[I-1]->getName()),
483                              NameBuf);
484           Found = lookupModuleQualified(Name, Found);
485           if (!Found)
486             return false;
487           if (IsUnavailable(Found))
488             return true;
489         }
490 
491         // Infer a submodule with the same name as this header file.
492         SmallString<32> NameBuf;
493         StringRef Name = sanitizeFilenameAsIdentifier(
494                            llvm::sys::path::stem(Header->getName()),
495                            NameBuf);
496         Found = lookupModuleQualified(Name, Found);
497         if (!Found)
498           return false;
499       }
500 
501       return IsUnavailable(Found);
502     }
503 
504     SkippedDirs.push_back(Dir);
505 
506     // Retrieve our parent path.
507     DirName = llvm::sys::path::parent_path(DirName);
508     if (DirName.empty())
509       break;
510 
511     // Resolve the parent path to a directory entry.
512     Dir = SourceMgr.getFileManager().getDirectory(DirName);
513   } while (Dir);
514 
515   return false;
516 }
517 
518 Module *ModuleMap::findModule(StringRef Name) const {
519   llvm::StringMap<Module *>::const_iterator Known = Modules.find(Name);
520   if (Known != Modules.end())
521     return Known->getValue();
522 
523   return nullptr;
524 }
525 
526 Module *ModuleMap::lookupModuleUnqualified(StringRef Name,
527                                            Module *Context) const {
528   for(; Context; Context = Context->Parent) {
529     if (Module *Sub = lookupModuleQualified(Name, Context))
530       return Sub;
531   }
532 
533   return findModule(Name);
534 }
535 
536 Module *ModuleMap::lookupModuleQualified(StringRef Name, Module *Context) const{
537   if (!Context)
538     return findModule(Name);
539 
540   return Context->findSubmodule(Name);
541 }
542 
543 std::pair<Module *, bool>
544 ModuleMap::findOrCreateModule(StringRef Name, Module *Parent, bool IsFramework,
545                               bool IsExplicit) {
546   // Try to find an existing module with this name.
547   if (Module *Sub = lookupModuleQualified(Name, Parent))
548     return std::make_pair(Sub, false);
549 
550   // Create a new module with this name.
551   Module *Result = new Module(Name, SourceLocation(), Parent,
552                               IsFramework, IsExplicit, NumCreatedModules++);
553   if (!Parent) {
554     if (LangOpts.CurrentModule == Name)
555       SourceModule = Result;
556     Modules[Name] = Result;
557   }
558   return std::make_pair(Result, true);
559 }
560 
561 /// \brief For a framework module, infer the framework against which we
562 /// should link.
563 static void inferFrameworkLink(Module *Mod, const DirectoryEntry *FrameworkDir,
564                                FileManager &FileMgr) {
565   assert(Mod->IsFramework && "Can only infer linking for framework modules");
566   assert(!Mod->isSubFramework() &&
567          "Can only infer linking for top-level frameworks");
568 
569   SmallString<128> LibName;
570   LibName += FrameworkDir->getName();
571   llvm::sys::path::append(LibName, Mod->Name);
572 
573   // The library name of a framework has more than one possible extension since
574   // the introduction of the text-based dynamic library format. We need to check
575   // for both before we give up.
576   static const char *frameworkExtensions[] = {"", ".tbd"};
577   for (const auto *extension : frameworkExtensions) {
578     llvm::sys::path::replace_extension(LibName, extension);
579     if (FileMgr.getFile(LibName)) {
580       Mod->LinkLibraries.push_back(Module::LinkLibrary(Mod->Name,
581                                                        /*IsFramework=*/true));
582       return;
583     }
584   }
585 }
586 
587 Module *ModuleMap::inferFrameworkModule(const DirectoryEntry *FrameworkDir,
588                                         bool IsSystem, Module *Parent) {
589   Attributes Attrs;
590   Attrs.IsSystem = IsSystem;
591   return inferFrameworkModule(FrameworkDir, Attrs, Parent);
592 }
593 
594 Module *ModuleMap::inferFrameworkModule(const DirectoryEntry *FrameworkDir,
595                                         Attributes Attrs, Module *Parent) {
596   // Note: as an egregious but useful hack we use the real path here, because
597   // we might be looking at an embedded framework that symlinks out to a
598   // top-level framework, and we need to infer as if we were naming the
599   // top-level framework.
600   StringRef FrameworkDirName =
601       SourceMgr.getFileManager().getCanonicalName(FrameworkDir);
602 
603   // In case this is a case-insensitive filesystem, use the canonical
604   // directory name as the ModuleName, since modules are case-sensitive.
605   // FIXME: we should be able to give a fix-it hint for the correct spelling.
606   SmallString<32> ModuleNameStorage;
607   StringRef ModuleName = sanitizeFilenameAsIdentifier(
608       llvm::sys::path::stem(FrameworkDirName), ModuleNameStorage);
609 
610   // Check whether we've already found this module.
611   if (Module *Mod = lookupModuleQualified(ModuleName, Parent))
612     return Mod;
613 
614   FileManager &FileMgr = SourceMgr.getFileManager();
615 
616   // If the framework has a parent path from which we're allowed to infer
617   // a framework module, do so.
618   const FileEntry *ModuleMapFile = nullptr;
619   if (!Parent) {
620     // Determine whether we're allowed to infer a module map.
621     bool canInfer = false;
622     if (llvm::sys::path::has_parent_path(FrameworkDirName)) {
623       // Figure out the parent path.
624       StringRef Parent = llvm::sys::path::parent_path(FrameworkDirName);
625       if (const DirectoryEntry *ParentDir = FileMgr.getDirectory(Parent)) {
626         // Check whether we have already looked into the parent directory
627         // for a module map.
628         llvm::DenseMap<const DirectoryEntry *, InferredDirectory>::const_iterator
629           inferred = InferredDirectories.find(ParentDir);
630         if (inferred == InferredDirectories.end()) {
631           // We haven't looked here before. Load a module map, if there is
632           // one.
633           bool IsFrameworkDir = Parent.endswith(".framework");
634           if (const FileEntry *ModMapFile =
635                 HeaderInfo.lookupModuleMapFile(ParentDir, IsFrameworkDir)) {
636             parseModuleMapFile(ModMapFile, Attrs.IsSystem, ParentDir);
637             inferred = InferredDirectories.find(ParentDir);
638           }
639 
640           if (inferred == InferredDirectories.end())
641             inferred = InferredDirectories.insert(
642                          std::make_pair(ParentDir, InferredDirectory())).first;
643         }
644 
645         if (inferred->second.InferModules) {
646           // We're allowed to infer for this directory, but make sure it's okay
647           // to infer this particular module.
648           StringRef Name = llvm::sys::path::stem(FrameworkDirName);
649           canInfer = std::find(inferred->second.ExcludedModules.begin(),
650                                inferred->second.ExcludedModules.end(),
651                                Name) == inferred->second.ExcludedModules.end();
652 
653           Attrs.IsSystem |= inferred->second.Attrs.IsSystem;
654           Attrs.IsExternC |= inferred->second.Attrs.IsExternC;
655           Attrs.IsExhaustive |= inferred->second.Attrs.IsExhaustive;
656           ModuleMapFile = inferred->second.ModuleMapFile;
657         }
658       }
659     }
660 
661     // If we're not allowed to infer a framework module, don't.
662     if (!canInfer)
663       return nullptr;
664   } else
665     ModuleMapFile = getModuleMapFileForUniquing(Parent);
666 
667 
668   // Look for an umbrella header.
669   SmallString<128> UmbrellaName = StringRef(FrameworkDir->getName());
670   llvm::sys::path::append(UmbrellaName, "Headers", ModuleName + ".h");
671   const FileEntry *UmbrellaHeader = FileMgr.getFile(UmbrellaName);
672 
673   // FIXME: If there's no umbrella header, we could probably scan the
674   // framework to load *everything*. But, it's not clear that this is a good
675   // idea.
676   if (!UmbrellaHeader)
677     return nullptr;
678 
679   Module *Result = new Module(ModuleName, SourceLocation(), Parent,
680                               /*IsFramework=*/true, /*IsExplicit=*/false,
681                               NumCreatedModules++);
682   InferredModuleAllowedBy[Result] = ModuleMapFile;
683   Result->IsInferred = true;
684   if (!Parent) {
685     if (LangOpts.CurrentModule == ModuleName)
686       SourceModule = Result;
687     Modules[ModuleName] = Result;
688   }
689 
690   Result->IsSystem |= Attrs.IsSystem;
691   Result->IsExternC |= Attrs.IsExternC;
692   Result->ConfigMacrosExhaustive |= Attrs.IsExhaustive;
693   Result->Directory = FrameworkDir;
694 
695   // umbrella header "umbrella-header-name"
696   //
697   // The "Headers/" component of the name is implied because this is
698   // a framework module.
699   setUmbrellaHeader(Result, UmbrellaHeader, ModuleName + ".h");
700 
701   // export *
702   Result->Exports.push_back(Module::ExportDecl(nullptr, true));
703 
704   // module * { export * }
705   Result->InferSubmodules = true;
706   Result->InferExportWildcard = true;
707 
708   // Look for subframeworks.
709   std::error_code EC;
710   SmallString<128> SubframeworksDirName
711     = StringRef(FrameworkDir->getName());
712   llvm::sys::path::append(SubframeworksDirName, "Frameworks");
713   llvm::sys::path::native(SubframeworksDirName);
714   vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
715   for (vfs::directory_iterator Dir = FS.dir_begin(SubframeworksDirName, EC),
716                                DirEnd;
717        Dir != DirEnd && !EC; Dir.increment(EC)) {
718     if (!StringRef(Dir->getName()).endswith(".framework"))
719       continue;
720 
721     if (const DirectoryEntry *SubframeworkDir =
722             FileMgr.getDirectory(Dir->getName())) {
723       // Note: as an egregious but useful hack, we use the real path here and
724       // check whether it is actually a subdirectory of the parent directory.
725       // This will not be the case if the 'subframework' is actually a symlink
726       // out to a top-level framework.
727       StringRef SubframeworkDirName = FileMgr.getCanonicalName(SubframeworkDir);
728       bool FoundParent = false;
729       do {
730         // Get the parent directory name.
731         SubframeworkDirName
732           = llvm::sys::path::parent_path(SubframeworkDirName);
733         if (SubframeworkDirName.empty())
734           break;
735 
736         if (FileMgr.getDirectory(SubframeworkDirName) == FrameworkDir) {
737           FoundParent = true;
738           break;
739         }
740       } while (true);
741 
742       if (!FoundParent)
743         continue;
744 
745       // FIXME: Do we want to warn about subframeworks without umbrella headers?
746       inferFrameworkModule(SubframeworkDir, Attrs, Result);
747     }
748   }
749 
750   // If the module is a top-level framework, automatically link against the
751   // framework.
752   if (!Result->isSubFramework()) {
753     inferFrameworkLink(Result, FrameworkDir, FileMgr);
754   }
755 
756   return Result;
757 }
758 
759 void ModuleMap::setUmbrellaHeader(Module *Mod, const FileEntry *UmbrellaHeader,
760                                   Twine NameAsWritten) {
761   Headers[UmbrellaHeader].push_back(KnownHeader(Mod, NormalHeader));
762   Mod->Umbrella = UmbrellaHeader;
763   Mod->UmbrellaAsWritten = NameAsWritten.str();
764   UmbrellaDirs[UmbrellaHeader->getDir()] = Mod;
765 
766   // Notify callbacks that we just added a new header.
767   for (const auto &Cb : Callbacks)
768     Cb->moduleMapAddUmbrellaHeader(&SourceMgr.getFileManager(), UmbrellaHeader);
769 }
770 
771 void ModuleMap::setUmbrellaDir(Module *Mod, const DirectoryEntry *UmbrellaDir,
772                                Twine NameAsWritten) {
773   Mod->Umbrella = UmbrellaDir;
774   Mod->UmbrellaAsWritten = NameAsWritten.str();
775   UmbrellaDirs[UmbrellaDir] = Mod;
776 }
777 
778 static Module::HeaderKind headerRoleToKind(ModuleMap::ModuleHeaderRole Role) {
779   switch ((int)Role) {
780   default: llvm_unreachable("unknown header role");
781   case ModuleMap::NormalHeader:
782     return Module::HK_Normal;
783   case ModuleMap::PrivateHeader:
784     return Module::HK_Private;
785   case ModuleMap::TextualHeader:
786     return Module::HK_Textual;
787   case ModuleMap::PrivateHeader | ModuleMap::TextualHeader:
788     return Module::HK_PrivateTextual;
789   }
790 }
791 
792 void ModuleMap::addHeader(Module *Mod, Module::Header Header,
793                           ModuleHeaderRole Role, bool Imported) {
794   KnownHeader KH(Mod, Role);
795 
796   // Only add each header to the headers list once.
797   // FIXME: Should we diagnose if a header is listed twice in the
798   // same module definition?
799   auto &HeaderList = Headers[Header.Entry];
800   for (auto H : HeaderList)
801     if (H == KH)
802       return;
803 
804   HeaderList.push_back(KH);
805   Mod->Headers[headerRoleToKind(Role)].push_back(std::move(Header));
806 
807   bool isCompilingModuleHeader =
808       LangOpts.CompilingModule && Mod->getTopLevelModule() == SourceModule;
809   if (!Imported || isCompilingModuleHeader) {
810     // When we import HeaderFileInfo, the external source is expected to
811     // set the isModuleHeader flag itself.
812     HeaderInfo.MarkFileModuleHeader(Header.Entry, Role,
813                                     isCompilingModuleHeader);
814   }
815 
816   // Notify callbacks that we just added a new header.
817   for (const auto &Cb : Callbacks)
818     Cb->moduleMapAddHeader(Header.Entry->getName());
819 }
820 
821 void ModuleMap::excludeHeader(Module *Mod, Module::Header Header) {
822   // Add this as a known header so we won't implicitly add it to any
823   // umbrella directory module.
824   // FIXME: Should we only exclude it from umbrella modules within the
825   // specified module?
826   (void) Headers[Header.Entry];
827 
828   Mod->Headers[Module::HK_Excluded].push_back(std::move(Header));
829 }
830 
831 const FileEntry *
832 ModuleMap::getContainingModuleMapFile(const Module *Module) const {
833   if (Module->DefinitionLoc.isInvalid())
834     return nullptr;
835 
836   return SourceMgr.getFileEntryForID(
837            SourceMgr.getFileID(Module->DefinitionLoc));
838 }
839 
840 const FileEntry *ModuleMap::getModuleMapFileForUniquing(const Module *M) const {
841   if (M->IsInferred) {
842     assert(InferredModuleAllowedBy.count(M) && "missing inferred module map");
843     return InferredModuleAllowedBy.find(M)->second;
844   }
845   return getContainingModuleMapFile(M);
846 }
847 
848 void ModuleMap::setInferredModuleAllowedBy(Module *M, const FileEntry *ModMap) {
849   assert(M->IsInferred && "module not inferred");
850   InferredModuleAllowedBy[M] = ModMap;
851 }
852 
853 LLVM_DUMP_METHOD void ModuleMap::dump() {
854   llvm::errs() << "Modules:";
855   for (llvm::StringMap<Module *>::iterator M = Modules.begin(),
856                                         MEnd = Modules.end();
857        M != MEnd; ++M)
858     M->getValue()->print(llvm::errs(), 2);
859 
860   llvm::errs() << "Headers:";
861   for (HeadersMap::iterator H = Headers.begin(), HEnd = Headers.end();
862        H != HEnd; ++H) {
863     llvm::errs() << "  \"" << H->first->getName() << "\" -> ";
864     for (SmallVectorImpl<KnownHeader>::const_iterator I = H->second.begin(),
865                                                       E = H->second.end();
866          I != E; ++I) {
867       if (I != H->second.begin())
868         llvm::errs() << ",";
869       llvm::errs() << I->getModule()->getFullModuleName();
870     }
871     llvm::errs() << "\n";
872   }
873 }
874 
875 bool ModuleMap::resolveExports(Module *Mod, bool Complain) {
876   auto Unresolved = std::move(Mod->UnresolvedExports);
877   Mod->UnresolvedExports.clear();
878   for (auto &UE : Unresolved) {
879     Module::ExportDecl Export = resolveExport(Mod, UE, Complain);
880     if (Export.getPointer() || Export.getInt())
881       Mod->Exports.push_back(Export);
882     else
883       Mod->UnresolvedExports.push_back(UE);
884   }
885   return !Mod->UnresolvedExports.empty();
886 }
887 
888 bool ModuleMap::resolveUses(Module *Mod, bool Complain) {
889   auto Unresolved = std::move(Mod->UnresolvedDirectUses);
890   Mod->UnresolvedDirectUses.clear();
891   for (auto &UDU : Unresolved) {
892     Module *DirectUse = resolveModuleId(UDU, Mod, Complain);
893     if (DirectUse)
894       Mod->DirectUses.push_back(DirectUse);
895     else
896       Mod->UnresolvedDirectUses.push_back(UDU);
897   }
898   return !Mod->UnresolvedDirectUses.empty();
899 }
900 
901 bool ModuleMap::resolveConflicts(Module *Mod, bool Complain) {
902   auto Unresolved = std::move(Mod->UnresolvedConflicts);
903   Mod->UnresolvedConflicts.clear();
904   for (auto &UC : Unresolved) {
905     if (Module *OtherMod = resolveModuleId(UC.Id, Mod, Complain)) {
906       Module::Conflict Conflict;
907       Conflict.Other = OtherMod;
908       Conflict.Message = UC.Message;
909       Mod->Conflicts.push_back(Conflict);
910     } else
911       Mod->UnresolvedConflicts.push_back(UC);
912   }
913   return !Mod->UnresolvedConflicts.empty();
914 }
915 
916 Module *ModuleMap::inferModuleFromLocation(FullSourceLoc Loc) {
917   if (Loc.isInvalid())
918     return nullptr;
919 
920   // Use the expansion location to determine which module we're in.
921   FullSourceLoc ExpansionLoc = Loc.getExpansionLoc();
922   if (!ExpansionLoc.isFileID())
923     return nullptr;
924 
925   const SourceManager &SrcMgr = Loc.getManager();
926   FileID ExpansionFileID = ExpansionLoc.getFileID();
927 
928   while (const FileEntry *ExpansionFile
929            = SrcMgr.getFileEntryForID(ExpansionFileID)) {
930     // Find the module that owns this header (if any).
931     if (Module *Mod = findModuleForHeader(ExpansionFile).getModule())
932       return Mod;
933 
934     // No module owns this header, so look up the inclusion chain to see if
935     // any included header has an associated module.
936     SourceLocation IncludeLoc = SrcMgr.getIncludeLoc(ExpansionFileID);
937     if (IncludeLoc.isInvalid())
938       return nullptr;
939 
940     ExpansionFileID = SrcMgr.getFileID(IncludeLoc);
941   }
942 
943   return nullptr;
944 }
945 
946 //----------------------------------------------------------------------------//
947 // Module map file parser
948 //----------------------------------------------------------------------------//
949 
950 namespace clang {
951   /// \brief A token in a module map file.
952   struct MMToken {
953     enum TokenKind {
954       Comma,
955       ConfigMacros,
956       Conflict,
957       EndOfFile,
958       HeaderKeyword,
959       Identifier,
960       Exclaim,
961       ExcludeKeyword,
962       ExplicitKeyword,
963       ExportKeyword,
964       ExternKeyword,
965       FrameworkKeyword,
966       LinkKeyword,
967       ModuleKeyword,
968       Period,
969       PrivateKeyword,
970       UmbrellaKeyword,
971       UseKeyword,
972       RequiresKeyword,
973       Star,
974       StringLiteral,
975       TextualKeyword,
976       LBrace,
977       RBrace,
978       LSquare,
979       RSquare
980     } Kind;
981 
982     unsigned Location;
983     unsigned StringLength;
984     const char *StringData;
985 
986     void clear() {
987       Kind = EndOfFile;
988       Location = 0;
989       StringLength = 0;
990       StringData = nullptr;
991     }
992 
993     bool is(TokenKind K) const { return Kind == K; }
994 
995     SourceLocation getLocation() const {
996       return SourceLocation::getFromRawEncoding(Location);
997     }
998 
999     StringRef getString() const {
1000       return StringRef(StringData, StringLength);
1001     }
1002   };
1003 
1004   class ModuleMapParser {
1005     Lexer &L;
1006     SourceManager &SourceMgr;
1007 
1008     /// \brief Default target information, used only for string literal
1009     /// parsing.
1010     const TargetInfo *Target;
1011 
1012     DiagnosticsEngine &Diags;
1013     ModuleMap &Map;
1014 
1015     /// \brief The current module map file.
1016     const FileEntry *ModuleMapFile;
1017 
1018     /// \brief The directory that file names in this module map file should
1019     /// be resolved relative to.
1020     const DirectoryEntry *Directory;
1021 
1022     /// \brief The directory containing Clang-supplied headers.
1023     const DirectoryEntry *BuiltinIncludeDir;
1024 
1025     /// \brief Whether this module map is in a system header directory.
1026     bool IsSystem;
1027 
1028     /// \brief Whether an error occurred.
1029     bool HadError;
1030 
1031     /// \brief Stores string data for the various string literals referenced
1032     /// during parsing.
1033     llvm::BumpPtrAllocator StringData;
1034 
1035     /// \brief The current token.
1036     MMToken Tok;
1037 
1038     /// \brief The active module.
1039     Module *ActiveModule;
1040 
1041     /// \brief Whether a module uses the 'requires excluded' hack to mark its
1042     /// contents as 'textual'.
1043     ///
1044     /// On older Darwin SDK versions, 'requires excluded' is used to mark the
1045     /// contents of the Darwin.C.excluded (assert.h) and Tcl.Private modules as
1046     /// non-modular headers.  For backwards compatibility, we continue to
1047     /// support this idiom for just these modules, and map the headers to
1048     /// 'textual' to match the original intent.
1049     llvm::SmallPtrSet<Module *, 2> UsesRequiresExcludedHack;
1050 
1051     /// \brief Consume the current token and return its location.
1052     SourceLocation consumeToken();
1053 
1054     /// \brief Skip tokens until we reach the a token with the given kind
1055     /// (or the end of the file).
1056     void skipUntil(MMToken::TokenKind K);
1057 
1058     typedef SmallVector<std::pair<std::string, SourceLocation>, 2> ModuleId;
1059     bool parseModuleId(ModuleId &Id);
1060     void parseModuleDecl();
1061     void parseExternModuleDecl();
1062     void parseRequiresDecl();
1063     void parseHeaderDecl(clang::MMToken::TokenKind,
1064                          SourceLocation LeadingLoc);
1065     void parseUmbrellaDirDecl(SourceLocation UmbrellaLoc);
1066     void parseExportDecl();
1067     void parseUseDecl();
1068     void parseLinkDecl();
1069     void parseConfigMacros();
1070     void parseConflict();
1071     void parseInferredModuleDecl(bool Framework, bool Explicit);
1072 
1073     typedef ModuleMap::Attributes Attributes;
1074     bool parseOptionalAttributes(Attributes &Attrs);
1075 
1076   public:
1077     explicit ModuleMapParser(Lexer &L, SourceManager &SourceMgr,
1078                              const TargetInfo *Target,
1079                              DiagnosticsEngine &Diags,
1080                              ModuleMap &Map,
1081                              const FileEntry *ModuleMapFile,
1082                              const DirectoryEntry *Directory,
1083                              const DirectoryEntry *BuiltinIncludeDir,
1084                              bool IsSystem)
1085       : L(L), SourceMgr(SourceMgr), Target(Target), Diags(Diags), Map(Map),
1086         ModuleMapFile(ModuleMapFile), Directory(Directory),
1087         BuiltinIncludeDir(BuiltinIncludeDir), IsSystem(IsSystem),
1088         HadError(false), ActiveModule(nullptr)
1089     {
1090       Tok.clear();
1091       consumeToken();
1092     }
1093 
1094     bool parseModuleMapFile();
1095   };
1096 }
1097 
1098 SourceLocation ModuleMapParser::consumeToken() {
1099 retry:
1100   SourceLocation Result = Tok.getLocation();
1101   Tok.clear();
1102 
1103   Token LToken;
1104   L.LexFromRawLexer(LToken);
1105   Tok.Location = LToken.getLocation().getRawEncoding();
1106   switch (LToken.getKind()) {
1107   case tok::raw_identifier: {
1108     StringRef RI = LToken.getRawIdentifier();
1109     Tok.StringData = RI.data();
1110     Tok.StringLength = RI.size();
1111     Tok.Kind = llvm::StringSwitch<MMToken::TokenKind>(RI)
1112                  .Case("config_macros", MMToken::ConfigMacros)
1113                  .Case("conflict", MMToken::Conflict)
1114                  .Case("exclude", MMToken::ExcludeKeyword)
1115                  .Case("explicit", MMToken::ExplicitKeyword)
1116                  .Case("export", MMToken::ExportKeyword)
1117                  .Case("extern", MMToken::ExternKeyword)
1118                  .Case("framework", MMToken::FrameworkKeyword)
1119                  .Case("header", MMToken::HeaderKeyword)
1120                  .Case("link", MMToken::LinkKeyword)
1121                  .Case("module", MMToken::ModuleKeyword)
1122                  .Case("private", MMToken::PrivateKeyword)
1123                  .Case("requires", MMToken::RequiresKeyword)
1124                  .Case("textual", MMToken::TextualKeyword)
1125                  .Case("umbrella", MMToken::UmbrellaKeyword)
1126                  .Case("use", MMToken::UseKeyword)
1127                  .Default(MMToken::Identifier);
1128     break;
1129   }
1130 
1131   case tok::comma:
1132     Tok.Kind = MMToken::Comma;
1133     break;
1134 
1135   case tok::eof:
1136     Tok.Kind = MMToken::EndOfFile;
1137     break;
1138 
1139   case tok::l_brace:
1140     Tok.Kind = MMToken::LBrace;
1141     break;
1142 
1143   case tok::l_square:
1144     Tok.Kind = MMToken::LSquare;
1145     break;
1146 
1147   case tok::period:
1148     Tok.Kind = MMToken::Period;
1149     break;
1150 
1151   case tok::r_brace:
1152     Tok.Kind = MMToken::RBrace;
1153     break;
1154 
1155   case tok::r_square:
1156     Tok.Kind = MMToken::RSquare;
1157     break;
1158 
1159   case tok::star:
1160     Tok.Kind = MMToken::Star;
1161     break;
1162 
1163   case tok::exclaim:
1164     Tok.Kind = MMToken::Exclaim;
1165     break;
1166 
1167   case tok::string_literal: {
1168     if (LToken.hasUDSuffix()) {
1169       Diags.Report(LToken.getLocation(), diag::err_invalid_string_udl);
1170       HadError = true;
1171       goto retry;
1172     }
1173 
1174     // Parse the string literal.
1175     LangOptions LangOpts;
1176     StringLiteralParser StringLiteral(LToken, SourceMgr, LangOpts, *Target);
1177     if (StringLiteral.hadError)
1178       goto retry;
1179 
1180     // Copy the string literal into our string data allocator.
1181     unsigned Length = StringLiteral.GetStringLength();
1182     char *Saved = StringData.Allocate<char>(Length + 1);
1183     memcpy(Saved, StringLiteral.GetString().data(), Length);
1184     Saved[Length] = 0;
1185 
1186     // Form the token.
1187     Tok.Kind = MMToken::StringLiteral;
1188     Tok.StringData = Saved;
1189     Tok.StringLength = Length;
1190     break;
1191   }
1192 
1193   case tok::comment:
1194     goto retry;
1195 
1196   default:
1197     Diags.Report(LToken.getLocation(), diag::err_mmap_unknown_token);
1198     HadError = true;
1199     goto retry;
1200   }
1201 
1202   return Result;
1203 }
1204 
1205 void ModuleMapParser::skipUntil(MMToken::TokenKind K) {
1206   unsigned braceDepth = 0;
1207   unsigned squareDepth = 0;
1208   do {
1209     switch (Tok.Kind) {
1210     case MMToken::EndOfFile:
1211       return;
1212 
1213     case MMToken::LBrace:
1214       if (Tok.is(K) && braceDepth == 0 && squareDepth == 0)
1215         return;
1216 
1217       ++braceDepth;
1218       break;
1219 
1220     case MMToken::LSquare:
1221       if (Tok.is(K) && braceDepth == 0 && squareDepth == 0)
1222         return;
1223 
1224       ++squareDepth;
1225       break;
1226 
1227     case MMToken::RBrace:
1228       if (braceDepth > 0)
1229         --braceDepth;
1230       else if (Tok.is(K))
1231         return;
1232       break;
1233 
1234     case MMToken::RSquare:
1235       if (squareDepth > 0)
1236         --squareDepth;
1237       else if (Tok.is(K))
1238         return;
1239       break;
1240 
1241     default:
1242       if (braceDepth == 0 && squareDepth == 0 && Tok.is(K))
1243         return;
1244       break;
1245     }
1246 
1247    consumeToken();
1248   } while (true);
1249 }
1250 
1251 /// \brief Parse a module-id.
1252 ///
1253 ///   module-id:
1254 ///     identifier
1255 ///     identifier '.' module-id
1256 ///
1257 /// \returns true if an error occurred, false otherwise.
1258 bool ModuleMapParser::parseModuleId(ModuleId &Id) {
1259   Id.clear();
1260   do {
1261     if (Tok.is(MMToken::Identifier) || Tok.is(MMToken::StringLiteral)) {
1262       Id.push_back(std::make_pair(Tok.getString(), Tok.getLocation()));
1263       consumeToken();
1264     } else {
1265       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module_name);
1266       return true;
1267     }
1268 
1269     if (!Tok.is(MMToken::Period))
1270       break;
1271 
1272     consumeToken();
1273   } while (true);
1274 
1275   return false;
1276 }
1277 
1278 namespace {
1279   /// \brief Enumerates the known attributes.
1280   enum AttributeKind {
1281     /// \brief An unknown attribute.
1282     AT_unknown,
1283     /// \brief The 'system' attribute.
1284     AT_system,
1285     /// \brief The 'extern_c' attribute.
1286     AT_extern_c,
1287     /// \brief The 'exhaustive' attribute.
1288     AT_exhaustive
1289   };
1290 }
1291 
1292 /// \brief Parse a module declaration.
1293 ///
1294 ///   module-declaration:
1295 ///     'extern' 'module' module-id string-literal
1296 ///     'explicit'[opt] 'framework'[opt] 'module' module-id attributes[opt]
1297 ///       { module-member* }
1298 ///
1299 ///   module-member:
1300 ///     requires-declaration
1301 ///     header-declaration
1302 ///     submodule-declaration
1303 ///     export-declaration
1304 ///     link-declaration
1305 ///
1306 ///   submodule-declaration:
1307 ///     module-declaration
1308 ///     inferred-submodule-declaration
1309 void ModuleMapParser::parseModuleDecl() {
1310   assert(Tok.is(MMToken::ExplicitKeyword) || Tok.is(MMToken::ModuleKeyword) ||
1311          Tok.is(MMToken::FrameworkKeyword) || Tok.is(MMToken::ExternKeyword));
1312   if (Tok.is(MMToken::ExternKeyword)) {
1313     parseExternModuleDecl();
1314     return;
1315   }
1316 
1317   // Parse 'explicit' or 'framework' keyword, if present.
1318   SourceLocation ExplicitLoc;
1319   bool Explicit = false;
1320   bool Framework = false;
1321 
1322   // Parse 'explicit' keyword, if present.
1323   if (Tok.is(MMToken::ExplicitKeyword)) {
1324     ExplicitLoc = consumeToken();
1325     Explicit = true;
1326   }
1327 
1328   // Parse 'framework' keyword, if present.
1329   if (Tok.is(MMToken::FrameworkKeyword)) {
1330     consumeToken();
1331     Framework = true;
1332   }
1333 
1334   // Parse 'module' keyword.
1335   if (!Tok.is(MMToken::ModuleKeyword)) {
1336     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module);
1337     consumeToken();
1338     HadError = true;
1339     return;
1340   }
1341   consumeToken(); // 'module' keyword
1342 
1343   // If we have a wildcard for the module name, this is an inferred submodule.
1344   // Parse it.
1345   if (Tok.is(MMToken::Star))
1346     return parseInferredModuleDecl(Framework, Explicit);
1347 
1348   // Parse the module name.
1349   ModuleId Id;
1350   if (parseModuleId(Id)) {
1351     HadError = true;
1352     return;
1353   }
1354 
1355   if (ActiveModule) {
1356     if (Id.size() > 1) {
1357       Diags.Report(Id.front().second, diag::err_mmap_nested_submodule_id)
1358         << SourceRange(Id.front().second, Id.back().second);
1359 
1360       HadError = true;
1361       return;
1362     }
1363   } else if (Id.size() == 1 && Explicit) {
1364     // Top-level modules can't be explicit.
1365     Diags.Report(ExplicitLoc, diag::err_mmap_explicit_top_level);
1366     Explicit = false;
1367     ExplicitLoc = SourceLocation();
1368     HadError = true;
1369   }
1370 
1371   Module *PreviousActiveModule = ActiveModule;
1372   if (Id.size() > 1) {
1373     // This module map defines a submodule. Go find the module of which it
1374     // is a submodule.
1375     ActiveModule = nullptr;
1376     const Module *TopLevelModule = nullptr;
1377     for (unsigned I = 0, N = Id.size() - 1; I != N; ++I) {
1378       if (Module *Next = Map.lookupModuleQualified(Id[I].first, ActiveModule)) {
1379         if (I == 0)
1380           TopLevelModule = Next;
1381         ActiveModule = Next;
1382         continue;
1383       }
1384 
1385       if (ActiveModule) {
1386         Diags.Report(Id[I].second, diag::err_mmap_missing_module_qualified)
1387           << Id[I].first
1388           << ActiveModule->getTopLevelModule()->getFullModuleName();
1389       } else {
1390         Diags.Report(Id[I].second, diag::err_mmap_expected_module_name);
1391       }
1392       HadError = true;
1393       return;
1394     }
1395 
1396     if (ModuleMapFile != Map.getContainingModuleMapFile(TopLevelModule)) {
1397       assert(ModuleMapFile != Map.getModuleMapFileForUniquing(TopLevelModule) &&
1398              "submodule defined in same file as 'module *' that allowed its "
1399              "top-level module");
1400       Map.addAdditionalModuleMapFile(TopLevelModule, ModuleMapFile);
1401     }
1402   }
1403 
1404   StringRef ModuleName = Id.back().first;
1405   SourceLocation ModuleNameLoc = Id.back().second;
1406 
1407   // Parse the optional attribute list.
1408   Attributes Attrs;
1409   if (parseOptionalAttributes(Attrs))
1410     return;
1411 
1412 
1413   // Parse the opening brace.
1414   if (!Tok.is(MMToken::LBrace)) {
1415     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_lbrace)
1416       << ModuleName;
1417     HadError = true;
1418     return;
1419   }
1420   SourceLocation LBraceLoc = consumeToken();
1421 
1422   // Determine whether this (sub)module has already been defined.
1423   if (Module *Existing = Map.lookupModuleQualified(ModuleName, ActiveModule)) {
1424     if (Existing->DefinitionLoc.isInvalid() && !ActiveModule) {
1425       // Skip the module definition.
1426       skipUntil(MMToken::RBrace);
1427       if (Tok.is(MMToken::RBrace))
1428         consumeToken();
1429       else {
1430         Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
1431         Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
1432         HadError = true;
1433       }
1434       return;
1435     }
1436 
1437     Diags.Report(ModuleNameLoc, diag::err_mmap_module_redefinition)
1438       << ModuleName;
1439     Diags.Report(Existing->DefinitionLoc, diag::note_mmap_prev_definition);
1440 
1441     // Skip the module definition.
1442     skipUntil(MMToken::RBrace);
1443     if (Tok.is(MMToken::RBrace))
1444       consumeToken();
1445 
1446     HadError = true;
1447     return;
1448   }
1449 
1450   // Start defining this module.
1451   ActiveModule = Map.findOrCreateModule(ModuleName, ActiveModule, Framework,
1452                                         Explicit).first;
1453   ActiveModule->DefinitionLoc = ModuleNameLoc;
1454   if (Attrs.IsSystem || IsSystem)
1455     ActiveModule->IsSystem = true;
1456   if (Attrs.IsExternC)
1457     ActiveModule->IsExternC = true;
1458   ActiveModule->Directory = Directory;
1459 
1460   bool Done = false;
1461   do {
1462     switch (Tok.Kind) {
1463     case MMToken::EndOfFile:
1464     case MMToken::RBrace:
1465       Done = true;
1466       break;
1467 
1468     case MMToken::ConfigMacros:
1469       parseConfigMacros();
1470       break;
1471 
1472     case MMToken::Conflict:
1473       parseConflict();
1474       break;
1475 
1476     case MMToken::ExplicitKeyword:
1477     case MMToken::ExternKeyword:
1478     case MMToken::FrameworkKeyword:
1479     case MMToken::ModuleKeyword:
1480       parseModuleDecl();
1481       break;
1482 
1483     case MMToken::ExportKeyword:
1484       parseExportDecl();
1485       break;
1486 
1487     case MMToken::UseKeyword:
1488       parseUseDecl();
1489       break;
1490 
1491     case MMToken::RequiresKeyword:
1492       parseRequiresDecl();
1493       break;
1494 
1495     case MMToken::TextualKeyword:
1496       parseHeaderDecl(MMToken::TextualKeyword, consumeToken());
1497       break;
1498 
1499     case MMToken::UmbrellaKeyword: {
1500       SourceLocation UmbrellaLoc = consumeToken();
1501       if (Tok.is(MMToken::HeaderKeyword))
1502         parseHeaderDecl(MMToken::UmbrellaKeyword, UmbrellaLoc);
1503       else
1504         parseUmbrellaDirDecl(UmbrellaLoc);
1505       break;
1506     }
1507 
1508     case MMToken::ExcludeKeyword:
1509       parseHeaderDecl(MMToken::ExcludeKeyword, consumeToken());
1510       break;
1511 
1512     case MMToken::PrivateKeyword:
1513       parseHeaderDecl(MMToken::PrivateKeyword, consumeToken());
1514       break;
1515 
1516     case MMToken::HeaderKeyword:
1517       parseHeaderDecl(MMToken::HeaderKeyword, consumeToken());
1518       break;
1519 
1520     case MMToken::LinkKeyword:
1521       parseLinkDecl();
1522       break;
1523 
1524     default:
1525       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_member);
1526       consumeToken();
1527       break;
1528     }
1529   } while (!Done);
1530 
1531   if (Tok.is(MMToken::RBrace))
1532     consumeToken();
1533   else {
1534     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
1535     Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
1536     HadError = true;
1537   }
1538 
1539   // If the active module is a top-level framework, and there are no link
1540   // libraries, automatically link against the framework.
1541   if (ActiveModule->IsFramework && !ActiveModule->isSubFramework() &&
1542       ActiveModule->LinkLibraries.empty()) {
1543     inferFrameworkLink(ActiveModule, Directory, SourceMgr.getFileManager());
1544   }
1545 
1546   // If the module meets all requirements but is still unavailable, mark the
1547   // whole tree as unavailable to prevent it from building.
1548   if (!ActiveModule->IsAvailable && !ActiveModule->IsMissingRequirement &&
1549       ActiveModule->Parent) {
1550     ActiveModule->getTopLevelModule()->markUnavailable();
1551     ActiveModule->getTopLevelModule()->MissingHeaders.append(
1552       ActiveModule->MissingHeaders.begin(), ActiveModule->MissingHeaders.end());
1553   }
1554 
1555   // We're done parsing this module. Pop back to the previous module.
1556   ActiveModule = PreviousActiveModule;
1557 }
1558 
1559 /// \brief Parse an extern module declaration.
1560 ///
1561 ///   extern module-declaration:
1562 ///     'extern' 'module' module-id string-literal
1563 void ModuleMapParser::parseExternModuleDecl() {
1564   assert(Tok.is(MMToken::ExternKeyword));
1565   SourceLocation ExternLoc = consumeToken(); // 'extern' keyword
1566 
1567   // Parse 'module' keyword.
1568   if (!Tok.is(MMToken::ModuleKeyword)) {
1569     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module);
1570     consumeToken();
1571     HadError = true;
1572     return;
1573   }
1574   consumeToken(); // 'module' keyword
1575 
1576   // Parse the module name.
1577   ModuleId Id;
1578   if (parseModuleId(Id)) {
1579     HadError = true;
1580     return;
1581   }
1582 
1583   // Parse the referenced module map file name.
1584   if (!Tok.is(MMToken::StringLiteral)) {
1585     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_mmap_file);
1586     HadError = true;
1587     return;
1588   }
1589   std::string FileName = Tok.getString();
1590   consumeToken(); // filename
1591 
1592   StringRef FileNameRef = FileName;
1593   SmallString<128> ModuleMapFileName;
1594   if (llvm::sys::path::is_relative(FileNameRef)) {
1595     ModuleMapFileName += Directory->getName();
1596     llvm::sys::path::append(ModuleMapFileName, FileName);
1597     FileNameRef = ModuleMapFileName;
1598   }
1599   if (const FileEntry *File = SourceMgr.getFileManager().getFile(FileNameRef))
1600     Map.parseModuleMapFile(
1601         File, /*IsSystem=*/false,
1602         Map.HeaderInfo.getHeaderSearchOpts().ModuleMapFileHomeIsCwd
1603             ? Directory
1604             : File->getDir(), ExternLoc);
1605 }
1606 
1607 /// Whether to add the requirement \p Feature to the module \p M.
1608 ///
1609 /// This preserves backwards compatibility for two hacks in the Darwin system
1610 /// module map files:
1611 ///
1612 /// 1. The use of 'requires excluded' to make headers non-modular, which
1613 ///    should really be mapped to 'textual' now that we have this feature.  We
1614 ///    drop the 'excluded' requirement, and set \p IsRequiresExcludedHack to
1615 ///    true.  Later, this bit will be used to map all the headers inside this
1616 ///    module to 'textual'.
1617 ///
1618 ///    This affects Darwin.C.excluded (for assert.h) and Tcl.Private.
1619 ///
1620 /// 2. Removes a bogus cplusplus requirement from IOKit.avc.  This requirement
1621 ///    was never correct and causes issues now that we check it, so drop it.
1622 static bool shouldAddRequirement(Module *M, StringRef Feature,
1623                                  bool &IsRequiresExcludedHack) {
1624   static const StringRef DarwinCExcluded[] = {"Darwin", "C", "excluded"};
1625   static const StringRef TclPrivate[] = {"Tcl", "Private"};
1626   static const StringRef IOKitAVC[] = {"IOKit", "avc"};
1627 
1628   if (Feature == "excluded" && (M->fullModuleNameIs(DarwinCExcluded) ||
1629                                 M->fullModuleNameIs(TclPrivate))) {
1630     IsRequiresExcludedHack = true;
1631     return false;
1632   } else if (Feature == "cplusplus" && M->fullModuleNameIs(IOKitAVC)) {
1633     return false;
1634   }
1635 
1636   return true;
1637 }
1638 
1639 /// \brief Parse a requires declaration.
1640 ///
1641 ///   requires-declaration:
1642 ///     'requires' feature-list
1643 ///
1644 ///   feature-list:
1645 ///     feature ',' feature-list
1646 ///     feature
1647 ///
1648 ///   feature:
1649 ///     '!'[opt] identifier
1650 void ModuleMapParser::parseRequiresDecl() {
1651   assert(Tok.is(MMToken::RequiresKeyword));
1652 
1653   // Parse 'requires' keyword.
1654   consumeToken();
1655 
1656   // Parse the feature-list.
1657   do {
1658     bool RequiredState = true;
1659     if (Tok.is(MMToken::Exclaim)) {
1660       RequiredState = false;
1661       consumeToken();
1662     }
1663 
1664     if (!Tok.is(MMToken::Identifier)) {
1665       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_feature);
1666       HadError = true;
1667       return;
1668     }
1669 
1670     // Consume the feature name.
1671     std::string Feature = Tok.getString();
1672     consumeToken();
1673 
1674     bool IsRequiresExcludedHack = false;
1675     bool ShouldAddRequirement =
1676         shouldAddRequirement(ActiveModule, Feature, IsRequiresExcludedHack);
1677 
1678     if (IsRequiresExcludedHack)
1679       UsesRequiresExcludedHack.insert(ActiveModule);
1680 
1681     if (ShouldAddRequirement) {
1682       // Add this feature.
1683       ActiveModule->addRequirement(Feature, RequiredState, Map.LangOpts,
1684                                    *Map.Target);
1685     }
1686 
1687     if (!Tok.is(MMToken::Comma))
1688       break;
1689 
1690     // Consume the comma.
1691     consumeToken();
1692   } while (true);
1693 }
1694 
1695 /// \brief Append to \p Paths the set of paths needed to get to the
1696 /// subframework in which the given module lives.
1697 static void appendSubframeworkPaths(Module *Mod,
1698                                     SmallVectorImpl<char> &Path) {
1699   // Collect the framework names from the given module to the top-level module.
1700   SmallVector<StringRef, 2> Paths;
1701   for (; Mod; Mod = Mod->Parent) {
1702     if (Mod->IsFramework)
1703       Paths.push_back(Mod->Name);
1704   }
1705 
1706   if (Paths.empty())
1707     return;
1708 
1709   // Add Frameworks/Name.framework for each subframework.
1710   for (unsigned I = Paths.size() - 1; I != 0; --I)
1711     llvm::sys::path::append(Path, "Frameworks", Paths[I-1] + ".framework");
1712 }
1713 
1714 /// \brief Parse a header declaration.
1715 ///
1716 ///   header-declaration:
1717 ///     'textual'[opt] 'header' string-literal
1718 ///     'private' 'textual'[opt] 'header' string-literal
1719 ///     'exclude' 'header' string-literal
1720 ///     'umbrella' 'header' string-literal
1721 ///
1722 /// FIXME: Support 'private textual header'.
1723 void ModuleMapParser::parseHeaderDecl(MMToken::TokenKind LeadingToken,
1724                                       SourceLocation LeadingLoc) {
1725   // We've already consumed the first token.
1726   ModuleMap::ModuleHeaderRole Role = ModuleMap::NormalHeader;
1727   if (LeadingToken == MMToken::PrivateKeyword) {
1728     Role = ModuleMap::PrivateHeader;
1729     // 'private' may optionally be followed by 'textual'.
1730     if (Tok.is(MMToken::TextualKeyword)) {
1731       LeadingToken = Tok.Kind;
1732       consumeToken();
1733     }
1734   }
1735 
1736   if (LeadingToken == MMToken::TextualKeyword)
1737     Role = ModuleMap::ModuleHeaderRole(Role | ModuleMap::TextualHeader);
1738 
1739   if (UsesRequiresExcludedHack.count(ActiveModule)) {
1740     // Mark this header 'textual' (see doc comment for
1741     // Module::UsesRequiresExcludedHack).
1742     Role = ModuleMap::ModuleHeaderRole(Role | ModuleMap::TextualHeader);
1743   }
1744 
1745   if (LeadingToken != MMToken::HeaderKeyword) {
1746     if (!Tok.is(MMToken::HeaderKeyword)) {
1747       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
1748           << (LeadingToken == MMToken::PrivateKeyword ? "private" :
1749               LeadingToken == MMToken::ExcludeKeyword ? "exclude" :
1750               LeadingToken == MMToken::TextualKeyword ? "textual" : "umbrella");
1751       return;
1752     }
1753     consumeToken();
1754   }
1755 
1756   // Parse the header name.
1757   if (!Tok.is(MMToken::StringLiteral)) {
1758     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
1759       << "header";
1760     HadError = true;
1761     return;
1762   }
1763   Module::UnresolvedHeaderDirective Header;
1764   Header.FileName = Tok.getString();
1765   Header.FileNameLoc = consumeToken();
1766 
1767   // Check whether we already have an umbrella.
1768   if (LeadingToken == MMToken::UmbrellaKeyword && ActiveModule->Umbrella) {
1769     Diags.Report(Header.FileNameLoc, diag::err_mmap_umbrella_clash)
1770       << ActiveModule->getFullModuleName();
1771     HadError = true;
1772     return;
1773   }
1774 
1775   // Look for this file.
1776   const FileEntry *File = nullptr;
1777   const FileEntry *BuiltinFile = nullptr;
1778   SmallString<128> RelativePathName;
1779   if (llvm::sys::path::is_absolute(Header.FileName)) {
1780     RelativePathName = Header.FileName;
1781     File = SourceMgr.getFileManager().getFile(RelativePathName);
1782   } else {
1783     // Search for the header file within the search directory.
1784     SmallString<128> FullPathName(Directory->getName());
1785     unsigned FullPathLength = FullPathName.size();
1786 
1787     if (ActiveModule->isPartOfFramework()) {
1788       appendSubframeworkPaths(ActiveModule, RelativePathName);
1789 
1790       // Check whether this file is in the public headers.
1791       llvm::sys::path::append(RelativePathName, "Headers", Header.FileName);
1792       llvm::sys::path::append(FullPathName, RelativePathName);
1793       File = SourceMgr.getFileManager().getFile(FullPathName);
1794 
1795       if (!File) {
1796         // Check whether this file is in the private headers.
1797         // FIXME: Should we retain the subframework paths here?
1798         RelativePathName.clear();
1799         FullPathName.resize(FullPathLength);
1800         llvm::sys::path::append(RelativePathName, "PrivateHeaders",
1801                                 Header.FileName);
1802         llvm::sys::path::append(FullPathName, RelativePathName);
1803         File = SourceMgr.getFileManager().getFile(FullPathName);
1804       }
1805     } else {
1806       // Lookup for normal headers.
1807       llvm::sys::path::append(RelativePathName, Header.FileName);
1808       llvm::sys::path::append(FullPathName, RelativePathName);
1809       File = SourceMgr.getFileManager().getFile(FullPathName);
1810 
1811       // If this is a system module with a top-level header, this header
1812       // may have a counterpart (or replacement) in the set of headers
1813       // supplied by Clang. Find that builtin header.
1814       if (ActiveModule->IsSystem && LeadingToken != MMToken::UmbrellaKeyword &&
1815           BuiltinIncludeDir && BuiltinIncludeDir != Directory &&
1816           isBuiltinHeader(Header.FileName)) {
1817         SmallString<128> BuiltinPathName(BuiltinIncludeDir->getName());
1818         llvm::sys::path::append(BuiltinPathName, Header.FileName);
1819         BuiltinFile = SourceMgr.getFileManager().getFile(BuiltinPathName);
1820 
1821         // If Clang supplies this header but the underlying system does not,
1822         // just silently swap in our builtin version. Otherwise, we'll end
1823         // up adding both (later).
1824         //
1825         // For local visibility, entirely replace the system file with our
1826         // one and textually include the system one. We need to pass macros
1827         // from our header to the system one if we #include_next it.
1828         //
1829         // FIXME: Can we do this in all cases?
1830         if (BuiltinFile && (!File || Map.LangOpts.ModulesLocalVisibility)) {
1831           File = BuiltinFile;
1832           RelativePathName = BuiltinPathName;
1833           BuiltinFile = nullptr;
1834         }
1835       }
1836     }
1837   }
1838 
1839   // FIXME: We shouldn't be eagerly stat'ing every file named in a module map.
1840   // Come up with a lazy way to do this.
1841   if (File) {
1842     if (LeadingToken == MMToken::UmbrellaKeyword) {
1843       const DirectoryEntry *UmbrellaDir = File->getDir();
1844       if (Module *UmbrellaModule = Map.UmbrellaDirs[UmbrellaDir]) {
1845         Diags.Report(LeadingLoc, diag::err_mmap_umbrella_clash)
1846           << UmbrellaModule->getFullModuleName();
1847         HadError = true;
1848       } else {
1849         // Record this umbrella header.
1850         Map.setUmbrellaHeader(ActiveModule, File, RelativePathName.str());
1851       }
1852     } else if (LeadingToken == MMToken::ExcludeKeyword) {
1853       Module::Header H = {RelativePathName.str(), File};
1854       Map.excludeHeader(ActiveModule, H);
1855     } else {
1856       // If there is a builtin counterpart to this file, add it now, before
1857       // the "real" header, so we build the built-in one first when building
1858       // the module.
1859       if (BuiltinFile) {
1860         // FIXME: Taking the name from the FileEntry is unstable and can give
1861         // different results depending on how we've previously named that file
1862         // in this build.
1863         Module::Header H = { BuiltinFile->getName(), BuiltinFile };
1864         Map.addHeader(ActiveModule, H, Role);
1865       }
1866 
1867       // Record this header.
1868       Module::Header H = { RelativePathName.str(), File };
1869       Map.addHeader(ActiveModule, H, Role);
1870     }
1871   } else if (LeadingToken != MMToken::ExcludeKeyword) {
1872     // Ignore excluded header files. They're optional anyway.
1873 
1874     // If we find a module that has a missing header, we mark this module as
1875     // unavailable and store the header directive for displaying diagnostics.
1876     Header.IsUmbrella = LeadingToken == MMToken::UmbrellaKeyword;
1877     ActiveModule->markUnavailable();
1878     ActiveModule->MissingHeaders.push_back(Header);
1879   }
1880 }
1881 
1882 static int compareModuleHeaders(const Module::Header *A,
1883                                 const Module::Header *B) {
1884   return A->NameAsWritten.compare(B->NameAsWritten);
1885 }
1886 
1887 /// \brief Parse an umbrella directory declaration.
1888 ///
1889 ///   umbrella-dir-declaration:
1890 ///     umbrella string-literal
1891 void ModuleMapParser::parseUmbrellaDirDecl(SourceLocation UmbrellaLoc) {
1892   // Parse the directory name.
1893   if (!Tok.is(MMToken::StringLiteral)) {
1894     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
1895       << "umbrella";
1896     HadError = true;
1897     return;
1898   }
1899 
1900   std::string DirName = Tok.getString();
1901   SourceLocation DirNameLoc = consumeToken();
1902 
1903   // Check whether we already have an umbrella.
1904   if (ActiveModule->Umbrella) {
1905     Diags.Report(DirNameLoc, diag::err_mmap_umbrella_clash)
1906       << ActiveModule->getFullModuleName();
1907     HadError = true;
1908     return;
1909   }
1910 
1911   // Look for this file.
1912   const DirectoryEntry *Dir = nullptr;
1913   if (llvm::sys::path::is_absolute(DirName))
1914     Dir = SourceMgr.getFileManager().getDirectory(DirName);
1915   else {
1916     SmallString<128> PathName;
1917     PathName = Directory->getName();
1918     llvm::sys::path::append(PathName, DirName);
1919     Dir = SourceMgr.getFileManager().getDirectory(PathName);
1920   }
1921 
1922   if (!Dir) {
1923     Diags.Report(DirNameLoc, diag::err_mmap_umbrella_dir_not_found)
1924       << DirName;
1925     HadError = true;
1926     return;
1927   }
1928 
1929   if (UsesRequiresExcludedHack.count(ActiveModule)) {
1930     // Mark this header 'textual' (see doc comment for
1931     // ModuleMapParser::UsesRequiresExcludedHack). Although iterating over the
1932     // directory is relatively expensive, in practice this only applies to the
1933     // uncommonly used Tcl module on Darwin platforms.
1934     std::error_code EC;
1935     SmallVector<Module::Header, 6> Headers;
1936     vfs::FileSystem &FS = *SourceMgr.getFileManager().getVirtualFileSystem();
1937     for (vfs::recursive_directory_iterator I(FS, Dir->getName(), EC), E;
1938          I != E && !EC; I.increment(EC)) {
1939       if (const FileEntry *FE =
1940               SourceMgr.getFileManager().getFile(I->getName())) {
1941 
1942         Module::Header Header = {I->getName(), FE};
1943         Headers.push_back(std::move(Header));
1944       }
1945     }
1946 
1947     // Sort header paths so that the pcm doesn't depend on iteration order.
1948     llvm::array_pod_sort(Headers.begin(), Headers.end(), compareModuleHeaders);
1949 
1950     for (auto &Header : Headers)
1951       Map.addHeader(ActiveModule, std::move(Header), ModuleMap::TextualHeader);
1952     return;
1953   }
1954 
1955   if (Module *OwningModule = Map.UmbrellaDirs[Dir]) {
1956     Diags.Report(UmbrellaLoc, diag::err_mmap_umbrella_clash)
1957       << OwningModule->getFullModuleName();
1958     HadError = true;
1959     return;
1960   }
1961 
1962   // Record this umbrella directory.
1963   Map.setUmbrellaDir(ActiveModule, Dir, DirName);
1964 }
1965 
1966 /// \brief Parse a module export declaration.
1967 ///
1968 ///   export-declaration:
1969 ///     'export' wildcard-module-id
1970 ///
1971 ///   wildcard-module-id:
1972 ///     identifier
1973 ///     '*'
1974 ///     identifier '.' wildcard-module-id
1975 void ModuleMapParser::parseExportDecl() {
1976   assert(Tok.is(MMToken::ExportKeyword));
1977   SourceLocation ExportLoc = consumeToken();
1978 
1979   // Parse the module-id with an optional wildcard at the end.
1980   ModuleId ParsedModuleId;
1981   bool Wildcard = false;
1982   do {
1983     // FIXME: Support string-literal module names here.
1984     if (Tok.is(MMToken::Identifier)) {
1985       ParsedModuleId.push_back(std::make_pair(Tok.getString(),
1986                                               Tok.getLocation()));
1987       consumeToken();
1988 
1989       if (Tok.is(MMToken::Period)) {
1990         consumeToken();
1991         continue;
1992       }
1993 
1994       break;
1995     }
1996 
1997     if(Tok.is(MMToken::Star)) {
1998       Wildcard = true;
1999       consumeToken();
2000       break;
2001     }
2002 
2003     Diags.Report(Tok.getLocation(), diag::err_mmap_module_id);
2004     HadError = true;
2005     return;
2006   } while (true);
2007 
2008   Module::UnresolvedExportDecl Unresolved = {
2009     ExportLoc, ParsedModuleId, Wildcard
2010   };
2011   ActiveModule->UnresolvedExports.push_back(Unresolved);
2012 }
2013 
2014 /// \brief Parse a module use declaration.
2015 ///
2016 ///   use-declaration:
2017 ///     'use' wildcard-module-id
2018 void ModuleMapParser::parseUseDecl() {
2019   assert(Tok.is(MMToken::UseKeyword));
2020   auto KWLoc = consumeToken();
2021   // Parse the module-id.
2022   ModuleId ParsedModuleId;
2023   parseModuleId(ParsedModuleId);
2024 
2025   if (ActiveModule->Parent)
2026     Diags.Report(KWLoc, diag::err_mmap_use_decl_submodule);
2027   else
2028     ActiveModule->UnresolvedDirectUses.push_back(ParsedModuleId);
2029 }
2030 
2031 /// \brief Parse a link declaration.
2032 ///
2033 ///   module-declaration:
2034 ///     'link' 'framework'[opt] string-literal
2035 void ModuleMapParser::parseLinkDecl() {
2036   assert(Tok.is(MMToken::LinkKeyword));
2037   SourceLocation LinkLoc = consumeToken();
2038 
2039   // Parse the optional 'framework' keyword.
2040   bool IsFramework = false;
2041   if (Tok.is(MMToken::FrameworkKeyword)) {
2042     consumeToken();
2043     IsFramework = true;
2044   }
2045 
2046   // Parse the library name
2047   if (!Tok.is(MMToken::StringLiteral)) {
2048     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_library_name)
2049       << IsFramework << SourceRange(LinkLoc);
2050     HadError = true;
2051     return;
2052   }
2053 
2054   std::string LibraryName = Tok.getString();
2055   consumeToken();
2056   ActiveModule->LinkLibraries.push_back(Module::LinkLibrary(LibraryName,
2057                                                             IsFramework));
2058 }
2059 
2060 /// \brief Parse a configuration macro declaration.
2061 ///
2062 ///   module-declaration:
2063 ///     'config_macros' attributes[opt] config-macro-list?
2064 ///
2065 ///   config-macro-list:
2066 ///     identifier (',' identifier)?
2067 void ModuleMapParser::parseConfigMacros() {
2068   assert(Tok.is(MMToken::ConfigMacros));
2069   SourceLocation ConfigMacrosLoc = consumeToken();
2070 
2071   // Only top-level modules can have configuration macros.
2072   if (ActiveModule->Parent) {
2073     Diags.Report(ConfigMacrosLoc, diag::err_mmap_config_macro_submodule);
2074   }
2075 
2076   // Parse the optional attributes.
2077   Attributes Attrs;
2078   if (parseOptionalAttributes(Attrs))
2079     return;
2080 
2081   if (Attrs.IsExhaustive && !ActiveModule->Parent) {
2082     ActiveModule->ConfigMacrosExhaustive = true;
2083   }
2084 
2085   // If we don't have an identifier, we're done.
2086   // FIXME: Support macros with the same name as a keyword here.
2087   if (!Tok.is(MMToken::Identifier))
2088     return;
2089 
2090   // Consume the first identifier.
2091   if (!ActiveModule->Parent) {
2092     ActiveModule->ConfigMacros.push_back(Tok.getString().str());
2093   }
2094   consumeToken();
2095 
2096   do {
2097     // If there's a comma, consume it.
2098     if (!Tok.is(MMToken::Comma))
2099       break;
2100     consumeToken();
2101 
2102     // We expect to see a macro name here.
2103     // FIXME: Support macros with the same name as a keyword here.
2104     if (!Tok.is(MMToken::Identifier)) {
2105       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_config_macro);
2106       break;
2107     }
2108 
2109     // Consume the macro name.
2110     if (!ActiveModule->Parent) {
2111       ActiveModule->ConfigMacros.push_back(Tok.getString().str());
2112     }
2113     consumeToken();
2114   } while (true);
2115 }
2116 
2117 /// \brief Format a module-id into a string.
2118 static std::string formatModuleId(const ModuleId &Id) {
2119   std::string result;
2120   {
2121     llvm::raw_string_ostream OS(result);
2122 
2123     for (unsigned I = 0, N = Id.size(); I != N; ++I) {
2124       if (I)
2125         OS << ".";
2126       OS << Id[I].first;
2127     }
2128   }
2129 
2130   return result;
2131 }
2132 
2133 /// \brief Parse a conflict declaration.
2134 ///
2135 ///   module-declaration:
2136 ///     'conflict' module-id ',' string-literal
2137 void ModuleMapParser::parseConflict() {
2138   assert(Tok.is(MMToken::Conflict));
2139   SourceLocation ConflictLoc = consumeToken();
2140   Module::UnresolvedConflict Conflict;
2141 
2142   // Parse the module-id.
2143   if (parseModuleId(Conflict.Id))
2144     return;
2145 
2146   // Parse the ','.
2147   if (!Tok.is(MMToken::Comma)) {
2148     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_conflicts_comma)
2149       << SourceRange(ConflictLoc);
2150     return;
2151   }
2152   consumeToken();
2153 
2154   // Parse the message.
2155   if (!Tok.is(MMToken::StringLiteral)) {
2156     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_conflicts_message)
2157       << formatModuleId(Conflict.Id);
2158     return;
2159   }
2160   Conflict.Message = Tok.getString().str();
2161   consumeToken();
2162 
2163   // Add this unresolved conflict.
2164   ActiveModule->UnresolvedConflicts.push_back(Conflict);
2165 }
2166 
2167 /// \brief Parse an inferred module declaration (wildcard modules).
2168 ///
2169 ///   module-declaration:
2170 ///     'explicit'[opt] 'framework'[opt] 'module' * attributes[opt]
2171 ///       { inferred-module-member* }
2172 ///
2173 ///   inferred-module-member:
2174 ///     'export' '*'
2175 ///     'exclude' identifier
2176 void ModuleMapParser::parseInferredModuleDecl(bool Framework, bool Explicit) {
2177   assert(Tok.is(MMToken::Star));
2178   SourceLocation StarLoc = consumeToken();
2179   bool Failed = false;
2180 
2181   // Inferred modules must be submodules.
2182   if (!ActiveModule && !Framework) {
2183     Diags.Report(StarLoc, diag::err_mmap_top_level_inferred_submodule);
2184     Failed = true;
2185   }
2186 
2187   if (ActiveModule) {
2188     // Inferred modules must have umbrella directories.
2189     if (!Failed && ActiveModule->IsAvailable &&
2190         !ActiveModule->getUmbrellaDir()) {
2191       Diags.Report(StarLoc, diag::err_mmap_inferred_no_umbrella);
2192       Failed = true;
2193     }
2194 
2195     // Check for redefinition of an inferred module.
2196     if (!Failed && ActiveModule->InferSubmodules) {
2197       Diags.Report(StarLoc, diag::err_mmap_inferred_redef);
2198       if (ActiveModule->InferredSubmoduleLoc.isValid())
2199         Diags.Report(ActiveModule->InferredSubmoduleLoc,
2200                      diag::note_mmap_prev_definition);
2201       Failed = true;
2202     }
2203 
2204     // Check for the 'framework' keyword, which is not permitted here.
2205     if (Framework) {
2206       Diags.Report(StarLoc, diag::err_mmap_inferred_framework_submodule);
2207       Framework = false;
2208     }
2209   } else if (Explicit) {
2210     Diags.Report(StarLoc, diag::err_mmap_explicit_inferred_framework);
2211     Explicit = false;
2212   }
2213 
2214   // If there were any problems with this inferred submodule, skip its body.
2215   if (Failed) {
2216     if (Tok.is(MMToken::LBrace)) {
2217       consumeToken();
2218       skipUntil(MMToken::RBrace);
2219       if (Tok.is(MMToken::RBrace))
2220         consumeToken();
2221     }
2222     HadError = true;
2223     return;
2224   }
2225 
2226   // Parse optional attributes.
2227   Attributes Attrs;
2228   if (parseOptionalAttributes(Attrs))
2229     return;
2230 
2231   if (ActiveModule) {
2232     // Note that we have an inferred submodule.
2233     ActiveModule->InferSubmodules = true;
2234     ActiveModule->InferredSubmoduleLoc = StarLoc;
2235     ActiveModule->InferExplicitSubmodules = Explicit;
2236   } else {
2237     // We'll be inferring framework modules for this directory.
2238     Map.InferredDirectories[Directory].InferModules = true;
2239     Map.InferredDirectories[Directory].Attrs = Attrs;
2240     Map.InferredDirectories[Directory].ModuleMapFile = ModuleMapFile;
2241     // FIXME: Handle the 'framework' keyword.
2242   }
2243 
2244   // Parse the opening brace.
2245   if (!Tok.is(MMToken::LBrace)) {
2246     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_lbrace_wildcard);
2247     HadError = true;
2248     return;
2249   }
2250   SourceLocation LBraceLoc = consumeToken();
2251 
2252   // Parse the body of the inferred submodule.
2253   bool Done = false;
2254   do {
2255     switch (Tok.Kind) {
2256     case MMToken::EndOfFile:
2257     case MMToken::RBrace:
2258       Done = true;
2259       break;
2260 
2261     case MMToken::ExcludeKeyword: {
2262       if (ActiveModule) {
2263         Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member)
2264           << (ActiveModule != nullptr);
2265         consumeToken();
2266         break;
2267       }
2268 
2269       consumeToken();
2270       // FIXME: Support string-literal module names here.
2271       if (!Tok.is(MMToken::Identifier)) {
2272         Diags.Report(Tok.getLocation(), diag::err_mmap_missing_exclude_name);
2273         break;
2274       }
2275 
2276       Map.InferredDirectories[Directory].ExcludedModules
2277         .push_back(Tok.getString());
2278       consumeToken();
2279       break;
2280     }
2281 
2282     case MMToken::ExportKeyword:
2283       if (!ActiveModule) {
2284         Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member)
2285           << (ActiveModule != nullptr);
2286         consumeToken();
2287         break;
2288       }
2289 
2290       consumeToken();
2291       if (Tok.is(MMToken::Star))
2292         ActiveModule->InferExportWildcard = true;
2293       else
2294         Diags.Report(Tok.getLocation(),
2295                      diag::err_mmap_expected_export_wildcard);
2296       consumeToken();
2297       break;
2298 
2299     case MMToken::ExplicitKeyword:
2300     case MMToken::ModuleKeyword:
2301     case MMToken::HeaderKeyword:
2302     case MMToken::PrivateKeyword:
2303     case MMToken::UmbrellaKeyword:
2304     default:
2305       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member)
2306           << (ActiveModule != nullptr);
2307       consumeToken();
2308       break;
2309     }
2310   } while (!Done);
2311 
2312   if (Tok.is(MMToken::RBrace))
2313     consumeToken();
2314   else {
2315     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
2316     Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
2317     HadError = true;
2318   }
2319 }
2320 
2321 /// \brief Parse optional attributes.
2322 ///
2323 ///   attributes:
2324 ///     attribute attributes
2325 ///     attribute
2326 ///
2327 ///   attribute:
2328 ///     [ identifier ]
2329 ///
2330 /// \param Attrs Will be filled in with the parsed attributes.
2331 ///
2332 /// \returns true if an error occurred, false otherwise.
2333 bool ModuleMapParser::parseOptionalAttributes(Attributes &Attrs) {
2334   bool HadError = false;
2335 
2336   while (Tok.is(MMToken::LSquare)) {
2337     // Consume the '['.
2338     SourceLocation LSquareLoc = consumeToken();
2339 
2340     // Check whether we have an attribute name here.
2341     if (!Tok.is(MMToken::Identifier)) {
2342       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_attribute);
2343       skipUntil(MMToken::RSquare);
2344       if (Tok.is(MMToken::RSquare))
2345         consumeToken();
2346       HadError = true;
2347     }
2348 
2349     // Decode the attribute name.
2350     AttributeKind Attribute
2351       = llvm::StringSwitch<AttributeKind>(Tok.getString())
2352           .Case("exhaustive", AT_exhaustive)
2353           .Case("extern_c", AT_extern_c)
2354           .Case("system", AT_system)
2355           .Default(AT_unknown);
2356     switch (Attribute) {
2357     case AT_unknown:
2358       Diags.Report(Tok.getLocation(), diag::warn_mmap_unknown_attribute)
2359         << Tok.getString();
2360       break;
2361 
2362     case AT_system:
2363       Attrs.IsSystem = true;
2364       break;
2365 
2366     case AT_extern_c:
2367       Attrs.IsExternC = true;
2368       break;
2369 
2370     case AT_exhaustive:
2371       Attrs.IsExhaustive = true;
2372       break;
2373     }
2374     consumeToken();
2375 
2376     // Consume the ']'.
2377     if (!Tok.is(MMToken::RSquare)) {
2378       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rsquare);
2379       Diags.Report(LSquareLoc, diag::note_mmap_lsquare_match);
2380       skipUntil(MMToken::RSquare);
2381       HadError = true;
2382     }
2383 
2384     if (Tok.is(MMToken::RSquare))
2385       consumeToken();
2386   }
2387 
2388   return HadError;
2389 }
2390 
2391 /// \brief Parse a module map file.
2392 ///
2393 ///   module-map-file:
2394 ///     module-declaration*
2395 bool ModuleMapParser::parseModuleMapFile() {
2396   do {
2397     switch (Tok.Kind) {
2398     case MMToken::EndOfFile:
2399       return HadError;
2400 
2401     case MMToken::ExplicitKeyword:
2402     case MMToken::ExternKeyword:
2403     case MMToken::ModuleKeyword:
2404     case MMToken::FrameworkKeyword:
2405       parseModuleDecl();
2406       break;
2407 
2408     case MMToken::Comma:
2409     case MMToken::ConfigMacros:
2410     case MMToken::Conflict:
2411     case MMToken::Exclaim:
2412     case MMToken::ExcludeKeyword:
2413     case MMToken::ExportKeyword:
2414     case MMToken::HeaderKeyword:
2415     case MMToken::Identifier:
2416     case MMToken::LBrace:
2417     case MMToken::LinkKeyword:
2418     case MMToken::LSquare:
2419     case MMToken::Period:
2420     case MMToken::PrivateKeyword:
2421     case MMToken::RBrace:
2422     case MMToken::RSquare:
2423     case MMToken::RequiresKeyword:
2424     case MMToken::Star:
2425     case MMToken::StringLiteral:
2426     case MMToken::TextualKeyword:
2427     case MMToken::UmbrellaKeyword:
2428     case MMToken::UseKeyword:
2429       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module);
2430       HadError = true;
2431       consumeToken();
2432       break;
2433     }
2434   } while (true);
2435 }
2436 
2437 bool ModuleMap::parseModuleMapFile(const FileEntry *File, bool IsSystem,
2438                                    const DirectoryEntry *Dir,
2439                                    SourceLocation ExternModuleLoc) {
2440   llvm::DenseMap<const FileEntry *, bool>::iterator Known
2441     = ParsedModuleMap.find(File);
2442   if (Known != ParsedModuleMap.end())
2443     return Known->second;
2444 
2445   assert(Target && "Missing target information");
2446   auto FileCharacter = IsSystem ? SrcMgr::C_System : SrcMgr::C_User;
2447   FileID ID = SourceMgr.createFileID(File, ExternModuleLoc, FileCharacter);
2448   const llvm::MemoryBuffer *Buffer = SourceMgr.getBuffer(ID);
2449   if (!Buffer)
2450     return ParsedModuleMap[File] = true;
2451 
2452   // Parse this module map file.
2453   Lexer L(ID, SourceMgr.getBuffer(ID), SourceMgr, MMapLangOpts);
2454   SourceLocation Start = L.getSourceLocation();
2455   ModuleMapParser Parser(L, SourceMgr, Target, Diags, *this, File, Dir,
2456                          BuiltinIncludeDir, IsSystem);
2457   bool Result = Parser.parseModuleMapFile();
2458   ParsedModuleMap[File] = Result;
2459 
2460   // Notify callbacks that we parsed it.
2461   for (const auto &Cb : Callbacks)
2462     Cb->moduleMapFileRead(Start, *File, IsSystem);
2463   return Result;
2464 }
2465