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