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