xref: /llvm-project/clang/lib/Lex/ModuleMap.cpp (revision 90b0a1fc58cc0987d748eb02ecadee743d2efd97)
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   StringRef MapFileName(ModuleMapFile->getName());
1895   if (MapFileName.endswith("module.private.modulemap") ||
1896       MapFileName.endswith("module_private.map")) {
1897     ActiveModule->ModuleMapIsPrivate = true;
1898   }
1899 
1900   // Private modules named as FooPrivate, Foo.Private or similar are likely a
1901   // user error; provide warnings, notes and fixits to direct users to use
1902   // Foo_Private instead.
1903   SourceLocation StartLoc =
1904       SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
1905   if (Map.HeaderInfo.getHeaderSearchOpts().ImplicitModuleMaps &&
1906       !Diags.isIgnored(diag::warn_mmap_mismatched_private_submodule,
1907                        StartLoc) &&
1908       !Diags.isIgnored(diag::warn_mmap_mismatched_private_module_name,
1909                        StartLoc) &&
1910       ActiveModule->ModuleMapIsPrivate)
1911     diagnosePrivateModules(Map, Diags, ActiveModule, LastInlineParentLoc);
1912 
1913   bool Done = false;
1914   do {
1915     switch (Tok.Kind) {
1916     case MMToken::EndOfFile:
1917     case MMToken::RBrace:
1918       Done = true;
1919       break;
1920 
1921     case MMToken::ConfigMacros:
1922       parseConfigMacros();
1923       break;
1924 
1925     case MMToken::Conflict:
1926       parseConflict();
1927       break;
1928 
1929     case MMToken::ExplicitKeyword:
1930     case MMToken::ExternKeyword:
1931     case MMToken::FrameworkKeyword:
1932     case MMToken::ModuleKeyword:
1933       parseModuleDecl();
1934       break;
1935 
1936     case MMToken::ExportKeyword:
1937       parseExportDecl();
1938       break;
1939 
1940     case MMToken::ExportAsKeyword:
1941       parseExportAsDecl();
1942       break;
1943 
1944     case MMToken::UseKeyword:
1945       parseUseDecl();
1946       break;
1947 
1948     case MMToken::RequiresKeyword:
1949       parseRequiresDecl();
1950       break;
1951 
1952     case MMToken::TextualKeyword:
1953       parseHeaderDecl(MMToken::TextualKeyword, consumeToken());
1954       break;
1955 
1956     case MMToken::UmbrellaKeyword: {
1957       SourceLocation UmbrellaLoc = consumeToken();
1958       if (Tok.is(MMToken::HeaderKeyword))
1959         parseHeaderDecl(MMToken::UmbrellaKeyword, UmbrellaLoc);
1960       else
1961         parseUmbrellaDirDecl(UmbrellaLoc);
1962       break;
1963     }
1964 
1965     case MMToken::ExcludeKeyword:
1966       parseHeaderDecl(MMToken::ExcludeKeyword, consumeToken());
1967       break;
1968 
1969     case MMToken::PrivateKeyword:
1970       parseHeaderDecl(MMToken::PrivateKeyword, consumeToken());
1971       break;
1972 
1973     case MMToken::HeaderKeyword:
1974       parseHeaderDecl(MMToken::HeaderKeyword, consumeToken());
1975       break;
1976 
1977     case MMToken::LinkKeyword:
1978       parseLinkDecl();
1979       break;
1980 
1981     default:
1982       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_member);
1983       consumeToken();
1984       break;
1985     }
1986   } while (!Done);
1987 
1988   if (Tok.is(MMToken::RBrace))
1989     consumeToken();
1990   else {
1991     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
1992     Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
1993     HadError = true;
1994   }
1995 
1996   // If the active module is a top-level framework, and there are no link
1997   // libraries, automatically link against the framework.
1998   if (ActiveModule->IsFramework && !ActiveModule->isSubFramework() &&
1999       ActiveModule->LinkLibraries.empty()) {
2000     inferFrameworkLink(ActiveModule, Directory, SourceMgr.getFileManager());
2001   }
2002 
2003   // If the module meets all requirements but is still unavailable, mark the
2004   // whole tree as unavailable to prevent it from building.
2005   if (!ActiveModule->IsAvailable && !ActiveModule->IsMissingRequirement &&
2006       ActiveModule->Parent) {
2007     ActiveModule->getTopLevelModule()->markUnavailable();
2008     ActiveModule->getTopLevelModule()->MissingHeaders.append(
2009       ActiveModule->MissingHeaders.begin(), ActiveModule->MissingHeaders.end());
2010   }
2011 
2012   // We're done parsing this module. Pop back to the previous module.
2013   ActiveModule = PreviousActiveModule;
2014 }
2015 
2016 /// \brief Parse an extern module declaration.
2017 ///
2018 ///   extern module-declaration:
2019 ///     'extern' 'module' module-id string-literal
2020 void ModuleMapParser::parseExternModuleDecl() {
2021   assert(Tok.is(MMToken::ExternKeyword));
2022   SourceLocation ExternLoc = consumeToken(); // 'extern' keyword
2023 
2024   // Parse 'module' keyword.
2025   if (!Tok.is(MMToken::ModuleKeyword)) {
2026     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module);
2027     consumeToken();
2028     HadError = true;
2029     return;
2030   }
2031   consumeToken(); // 'module' keyword
2032 
2033   // Parse the module name.
2034   ModuleId Id;
2035   if (parseModuleId(Id)) {
2036     HadError = true;
2037     return;
2038   }
2039 
2040   // Parse the referenced module map file name.
2041   if (!Tok.is(MMToken::StringLiteral)) {
2042     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_mmap_file);
2043     HadError = true;
2044     return;
2045   }
2046   std::string FileName = Tok.getString();
2047   consumeToken(); // filename
2048 
2049   StringRef FileNameRef = FileName;
2050   SmallString<128> ModuleMapFileName;
2051   if (llvm::sys::path::is_relative(FileNameRef)) {
2052     ModuleMapFileName += Directory->getName();
2053     llvm::sys::path::append(ModuleMapFileName, FileName);
2054     FileNameRef = ModuleMapFileName;
2055   }
2056   if (const FileEntry *File = SourceMgr.getFileManager().getFile(FileNameRef))
2057     Map.parseModuleMapFile(
2058         File, /*IsSystem=*/false,
2059         Map.HeaderInfo.getHeaderSearchOpts().ModuleMapFileHomeIsCwd
2060             ? Directory
2061             : File->getDir(),
2062         FileID(), nullptr, ExternLoc);
2063 }
2064 
2065 /// Whether to add the requirement \p Feature to the module \p M.
2066 ///
2067 /// This preserves backwards compatibility for two hacks in the Darwin system
2068 /// module map files:
2069 ///
2070 /// 1. The use of 'requires excluded' to make headers non-modular, which
2071 ///    should really be mapped to 'textual' now that we have this feature.  We
2072 ///    drop the 'excluded' requirement, and set \p IsRequiresExcludedHack to
2073 ///    true.  Later, this bit will be used to map all the headers inside this
2074 ///    module to 'textual'.
2075 ///
2076 ///    This affects Darwin.C.excluded (for assert.h) and Tcl.Private.
2077 ///
2078 /// 2. Removes a bogus cplusplus requirement from IOKit.avc.  This requirement
2079 ///    was never correct and causes issues now that we check it, so drop it.
2080 static bool shouldAddRequirement(Module *M, StringRef Feature,
2081                                  bool &IsRequiresExcludedHack) {
2082   if (Feature == "excluded" &&
2083       (M->fullModuleNameIs({"Darwin", "C", "excluded"}) ||
2084        M->fullModuleNameIs({"Tcl", "Private"}))) {
2085     IsRequiresExcludedHack = true;
2086     return false;
2087   } else if (Feature == "cplusplus" && M->fullModuleNameIs({"IOKit", "avc"})) {
2088     return false;
2089   }
2090 
2091   return true;
2092 }
2093 
2094 /// \brief Parse a requires declaration.
2095 ///
2096 ///   requires-declaration:
2097 ///     'requires' feature-list
2098 ///
2099 ///   feature-list:
2100 ///     feature ',' feature-list
2101 ///     feature
2102 ///
2103 ///   feature:
2104 ///     '!'[opt] identifier
2105 void ModuleMapParser::parseRequiresDecl() {
2106   assert(Tok.is(MMToken::RequiresKeyword));
2107 
2108   // Parse 'requires' keyword.
2109   consumeToken();
2110 
2111   // Parse the feature-list.
2112   do {
2113     bool RequiredState = true;
2114     if (Tok.is(MMToken::Exclaim)) {
2115       RequiredState = false;
2116       consumeToken();
2117     }
2118 
2119     if (!Tok.is(MMToken::Identifier)) {
2120       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_feature);
2121       HadError = true;
2122       return;
2123     }
2124 
2125     // Consume the feature name.
2126     std::string Feature = Tok.getString();
2127     consumeToken();
2128 
2129     bool IsRequiresExcludedHack = false;
2130     bool ShouldAddRequirement =
2131         shouldAddRequirement(ActiveModule, Feature, IsRequiresExcludedHack);
2132 
2133     if (IsRequiresExcludedHack)
2134       UsesRequiresExcludedHack.insert(ActiveModule);
2135 
2136     if (ShouldAddRequirement) {
2137       // Add this feature.
2138       ActiveModule->addRequirement(Feature, RequiredState, Map.LangOpts,
2139                                    *Map.Target);
2140     }
2141 
2142     if (!Tok.is(MMToken::Comma))
2143       break;
2144 
2145     // Consume the comma.
2146     consumeToken();
2147   } while (true);
2148 }
2149 
2150 /// \brief Parse a header declaration.
2151 ///
2152 ///   header-declaration:
2153 ///     'textual'[opt] 'header' string-literal
2154 ///     'private' 'textual'[opt] 'header' string-literal
2155 ///     'exclude' 'header' string-literal
2156 ///     'umbrella' 'header' string-literal
2157 ///
2158 /// FIXME: Support 'private textual header'.
2159 void ModuleMapParser::parseHeaderDecl(MMToken::TokenKind LeadingToken,
2160                                       SourceLocation LeadingLoc) {
2161   // We've already consumed the first token.
2162   ModuleMap::ModuleHeaderRole Role = ModuleMap::NormalHeader;
2163   if (LeadingToken == MMToken::PrivateKeyword) {
2164     Role = ModuleMap::PrivateHeader;
2165     // 'private' may optionally be followed by 'textual'.
2166     if (Tok.is(MMToken::TextualKeyword)) {
2167       LeadingToken = Tok.Kind;
2168       consumeToken();
2169     }
2170   }
2171 
2172   if (LeadingToken == MMToken::TextualKeyword)
2173     Role = ModuleMap::ModuleHeaderRole(Role | ModuleMap::TextualHeader);
2174 
2175   if (UsesRequiresExcludedHack.count(ActiveModule)) {
2176     // Mark this header 'textual' (see doc comment for
2177     // Module::UsesRequiresExcludedHack).
2178     Role = ModuleMap::ModuleHeaderRole(Role | ModuleMap::TextualHeader);
2179   }
2180 
2181   if (LeadingToken != MMToken::HeaderKeyword) {
2182     if (!Tok.is(MMToken::HeaderKeyword)) {
2183       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
2184           << (LeadingToken == MMToken::PrivateKeyword ? "private" :
2185               LeadingToken == MMToken::ExcludeKeyword ? "exclude" :
2186               LeadingToken == MMToken::TextualKeyword ? "textual" : "umbrella");
2187       return;
2188     }
2189     consumeToken();
2190   }
2191 
2192   // Parse the header name.
2193   if (!Tok.is(MMToken::StringLiteral)) {
2194     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
2195       << "header";
2196     HadError = true;
2197     return;
2198   }
2199   Module::UnresolvedHeaderDirective Header;
2200   Header.FileName = Tok.getString();
2201   Header.FileNameLoc = consumeToken();
2202   Header.IsUmbrella = LeadingToken == MMToken::UmbrellaKeyword;
2203   Header.Kind =
2204       (LeadingToken == MMToken::ExcludeKeyword ? Module::HK_Excluded
2205                                                : Map.headerRoleToKind(Role));
2206 
2207   // Check whether we already have an umbrella.
2208   if (Header.IsUmbrella && ActiveModule->Umbrella) {
2209     Diags.Report(Header.FileNameLoc, diag::err_mmap_umbrella_clash)
2210       << ActiveModule->getFullModuleName();
2211     HadError = true;
2212     return;
2213   }
2214 
2215   // If we were given stat information, parse it so we can skip looking for
2216   // the file.
2217   if (Tok.is(MMToken::LBrace)) {
2218     SourceLocation LBraceLoc = consumeToken();
2219 
2220     while (!Tok.is(MMToken::RBrace) && !Tok.is(MMToken::EndOfFile)) {
2221       enum Attribute { Size, ModTime, Unknown };
2222       StringRef Str = Tok.getString();
2223       SourceLocation Loc = consumeToken();
2224       switch (llvm::StringSwitch<Attribute>(Str)
2225                   .Case("size", Size)
2226                   .Case("mtime", ModTime)
2227                   .Default(Unknown)) {
2228       case Size:
2229         if (Header.Size)
2230           Diags.Report(Loc, diag::err_mmap_duplicate_header_attribute) << Str;
2231         if (!Tok.is(MMToken::IntegerLiteral)) {
2232           Diags.Report(Tok.getLocation(),
2233                        diag::err_mmap_invalid_header_attribute_value) << Str;
2234           skipUntil(MMToken::RBrace);
2235           break;
2236         }
2237         Header.Size = Tok.getInteger();
2238         consumeToken();
2239         break;
2240 
2241       case ModTime:
2242         if (Header.ModTime)
2243           Diags.Report(Loc, diag::err_mmap_duplicate_header_attribute) << Str;
2244         if (!Tok.is(MMToken::IntegerLiteral)) {
2245           Diags.Report(Tok.getLocation(),
2246                        diag::err_mmap_invalid_header_attribute_value) << Str;
2247           skipUntil(MMToken::RBrace);
2248           break;
2249         }
2250         Header.ModTime = Tok.getInteger();
2251         consumeToken();
2252         break;
2253 
2254       case Unknown:
2255         Diags.Report(Loc, diag::err_mmap_expected_header_attribute);
2256         skipUntil(MMToken::RBrace);
2257         break;
2258       }
2259     }
2260 
2261     if (Tok.is(MMToken::RBrace))
2262       consumeToken();
2263     else {
2264       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
2265       Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
2266       HadError = true;
2267     }
2268   }
2269 
2270   Map.addUnresolvedHeader(ActiveModule, std::move(Header));
2271 }
2272 
2273 static int compareModuleHeaders(const Module::Header *A,
2274                                 const Module::Header *B) {
2275   return A->NameAsWritten.compare(B->NameAsWritten);
2276 }
2277 
2278 /// \brief Parse an umbrella directory declaration.
2279 ///
2280 ///   umbrella-dir-declaration:
2281 ///     umbrella string-literal
2282 void ModuleMapParser::parseUmbrellaDirDecl(SourceLocation UmbrellaLoc) {
2283   // Parse the directory name.
2284   if (!Tok.is(MMToken::StringLiteral)) {
2285     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
2286       << "umbrella";
2287     HadError = true;
2288     return;
2289   }
2290 
2291   std::string DirName = Tok.getString();
2292   SourceLocation DirNameLoc = consumeToken();
2293 
2294   // Check whether we already have an umbrella.
2295   if (ActiveModule->Umbrella) {
2296     Diags.Report(DirNameLoc, diag::err_mmap_umbrella_clash)
2297       << ActiveModule->getFullModuleName();
2298     HadError = true;
2299     return;
2300   }
2301 
2302   // Look for this file.
2303   const DirectoryEntry *Dir = nullptr;
2304   if (llvm::sys::path::is_absolute(DirName))
2305     Dir = SourceMgr.getFileManager().getDirectory(DirName);
2306   else {
2307     SmallString<128> PathName;
2308     PathName = Directory->getName();
2309     llvm::sys::path::append(PathName, DirName);
2310     Dir = SourceMgr.getFileManager().getDirectory(PathName);
2311   }
2312 
2313   if (!Dir) {
2314     Diags.Report(DirNameLoc, diag::warn_mmap_umbrella_dir_not_found)
2315       << DirName;
2316     return;
2317   }
2318 
2319   if (UsesRequiresExcludedHack.count(ActiveModule)) {
2320     // Mark this header 'textual' (see doc comment for
2321     // ModuleMapParser::UsesRequiresExcludedHack). Although iterating over the
2322     // directory is relatively expensive, in practice this only applies to the
2323     // uncommonly used Tcl module on Darwin platforms.
2324     std::error_code EC;
2325     SmallVector<Module::Header, 6> Headers;
2326     vfs::FileSystem &FS = *SourceMgr.getFileManager().getVirtualFileSystem();
2327     for (vfs::recursive_directory_iterator I(FS, Dir->getName(), EC), E;
2328          I != E && !EC; I.increment(EC)) {
2329       if (const FileEntry *FE =
2330               SourceMgr.getFileManager().getFile(I->getName())) {
2331 
2332         Module::Header Header = {I->getName(), FE};
2333         Headers.push_back(std::move(Header));
2334       }
2335     }
2336 
2337     // Sort header paths so that the pcm doesn't depend on iteration order.
2338     llvm::array_pod_sort(Headers.begin(), Headers.end(), compareModuleHeaders);
2339 
2340     for (auto &Header : Headers)
2341       Map.addHeader(ActiveModule, std::move(Header), ModuleMap::TextualHeader);
2342     return;
2343   }
2344 
2345   if (Module *OwningModule = Map.UmbrellaDirs[Dir]) {
2346     Diags.Report(UmbrellaLoc, diag::err_mmap_umbrella_clash)
2347       << OwningModule->getFullModuleName();
2348     HadError = true;
2349     return;
2350   }
2351 
2352   // Record this umbrella directory.
2353   Map.setUmbrellaDir(ActiveModule, Dir, DirName);
2354 }
2355 
2356 /// \brief Parse a module export declaration.
2357 ///
2358 ///   export-declaration:
2359 ///     'export' wildcard-module-id
2360 ///
2361 ///   wildcard-module-id:
2362 ///     identifier
2363 ///     '*'
2364 ///     identifier '.' wildcard-module-id
2365 void ModuleMapParser::parseExportDecl() {
2366   assert(Tok.is(MMToken::ExportKeyword));
2367   SourceLocation ExportLoc = consumeToken();
2368 
2369   // Parse the module-id with an optional wildcard at the end.
2370   ModuleId ParsedModuleId;
2371   bool Wildcard = false;
2372   do {
2373     // FIXME: Support string-literal module names here.
2374     if (Tok.is(MMToken::Identifier)) {
2375       ParsedModuleId.push_back(std::make_pair(Tok.getString(),
2376                                               Tok.getLocation()));
2377       consumeToken();
2378 
2379       if (Tok.is(MMToken::Period)) {
2380         consumeToken();
2381         continue;
2382       }
2383 
2384       break;
2385     }
2386 
2387     if(Tok.is(MMToken::Star)) {
2388       Wildcard = true;
2389       consumeToken();
2390       break;
2391     }
2392 
2393     Diags.Report(Tok.getLocation(), diag::err_mmap_module_id);
2394     HadError = true;
2395     return;
2396   } while (true);
2397 
2398   Module::UnresolvedExportDecl Unresolved = {
2399     ExportLoc, ParsedModuleId, Wildcard
2400   };
2401   ActiveModule->UnresolvedExports.push_back(Unresolved);
2402 }
2403 
2404 /// \brief Parse a module export_as declaration.
2405 ///
2406 ///   export-as-declaration:
2407 ///     'export_as' identifier
2408 void ModuleMapParser::parseExportAsDecl() {
2409   assert(Tok.is(MMToken::ExportAsKeyword));
2410   consumeToken();
2411 
2412   if (!Tok.is(MMToken::Identifier)) {
2413     Diags.Report(Tok.getLocation(), diag::err_mmap_module_id);
2414     HadError = true;
2415     return;
2416   }
2417 
2418   if (ActiveModule->Parent) {
2419     Diags.Report(Tok.getLocation(), diag::err_mmap_submodule_export_as);
2420     consumeToken();
2421     return;
2422   }
2423 
2424   if (!ActiveModule->ExportAsModule.empty()) {
2425     if (ActiveModule->ExportAsModule == Tok.getString()) {
2426       Diags.Report(Tok.getLocation(), diag::warn_mmap_redundant_export_as)
2427         << ActiveModule->Name << Tok.getString();
2428     } else {
2429       Diags.Report(Tok.getLocation(), diag::err_mmap_conflicting_export_as)
2430         << ActiveModule->Name << ActiveModule->ExportAsModule
2431         << Tok.getString();
2432     }
2433   }
2434 
2435   ActiveModule->ExportAsModule = Tok.getString();
2436   Map.addLinkAsDependency(ActiveModule);
2437 
2438   consumeToken();
2439 }
2440 
2441 /// \brief Parse a module use declaration.
2442 ///
2443 ///   use-declaration:
2444 ///     'use' wildcard-module-id
2445 void ModuleMapParser::parseUseDecl() {
2446   assert(Tok.is(MMToken::UseKeyword));
2447   auto KWLoc = consumeToken();
2448   // Parse the module-id.
2449   ModuleId ParsedModuleId;
2450   parseModuleId(ParsedModuleId);
2451 
2452   if (ActiveModule->Parent)
2453     Diags.Report(KWLoc, diag::err_mmap_use_decl_submodule);
2454   else
2455     ActiveModule->UnresolvedDirectUses.push_back(ParsedModuleId);
2456 }
2457 
2458 /// \brief Parse a link declaration.
2459 ///
2460 ///   module-declaration:
2461 ///     'link' 'framework'[opt] string-literal
2462 void ModuleMapParser::parseLinkDecl() {
2463   assert(Tok.is(MMToken::LinkKeyword));
2464   SourceLocation LinkLoc = consumeToken();
2465 
2466   // Parse the optional 'framework' keyword.
2467   bool IsFramework = false;
2468   if (Tok.is(MMToken::FrameworkKeyword)) {
2469     consumeToken();
2470     IsFramework = true;
2471   }
2472 
2473   // Parse the library name
2474   if (!Tok.is(MMToken::StringLiteral)) {
2475     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_library_name)
2476       << IsFramework << SourceRange(LinkLoc);
2477     HadError = true;
2478     return;
2479   }
2480 
2481   std::string LibraryName = Tok.getString();
2482   consumeToken();
2483   ActiveModule->LinkLibraries.push_back(Module::LinkLibrary(LibraryName,
2484                                                             IsFramework));
2485 }
2486 
2487 /// \brief Parse a configuration macro declaration.
2488 ///
2489 ///   module-declaration:
2490 ///     'config_macros' attributes[opt] config-macro-list?
2491 ///
2492 ///   config-macro-list:
2493 ///     identifier (',' identifier)?
2494 void ModuleMapParser::parseConfigMacros() {
2495   assert(Tok.is(MMToken::ConfigMacros));
2496   SourceLocation ConfigMacrosLoc = consumeToken();
2497 
2498   // Only top-level modules can have configuration macros.
2499   if (ActiveModule->Parent) {
2500     Diags.Report(ConfigMacrosLoc, diag::err_mmap_config_macro_submodule);
2501   }
2502 
2503   // Parse the optional attributes.
2504   Attributes Attrs;
2505   if (parseOptionalAttributes(Attrs))
2506     return;
2507 
2508   if (Attrs.IsExhaustive && !ActiveModule->Parent) {
2509     ActiveModule->ConfigMacrosExhaustive = true;
2510   }
2511 
2512   // If we don't have an identifier, we're done.
2513   // FIXME: Support macros with the same name as a keyword here.
2514   if (!Tok.is(MMToken::Identifier))
2515     return;
2516 
2517   // Consume the first identifier.
2518   if (!ActiveModule->Parent) {
2519     ActiveModule->ConfigMacros.push_back(Tok.getString().str());
2520   }
2521   consumeToken();
2522 
2523   do {
2524     // If there's a comma, consume it.
2525     if (!Tok.is(MMToken::Comma))
2526       break;
2527     consumeToken();
2528 
2529     // We expect to see a macro name here.
2530     // FIXME: Support macros with the same name as a keyword here.
2531     if (!Tok.is(MMToken::Identifier)) {
2532       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_config_macro);
2533       break;
2534     }
2535 
2536     // Consume the macro name.
2537     if (!ActiveModule->Parent) {
2538       ActiveModule->ConfigMacros.push_back(Tok.getString().str());
2539     }
2540     consumeToken();
2541   } while (true);
2542 }
2543 
2544 /// \brief Format a module-id into a string.
2545 static std::string formatModuleId(const ModuleId &Id) {
2546   std::string result;
2547   {
2548     llvm::raw_string_ostream OS(result);
2549 
2550     for (unsigned I = 0, N = Id.size(); I != N; ++I) {
2551       if (I)
2552         OS << ".";
2553       OS << Id[I].first;
2554     }
2555   }
2556 
2557   return result;
2558 }
2559 
2560 /// \brief Parse a conflict declaration.
2561 ///
2562 ///   module-declaration:
2563 ///     'conflict' module-id ',' string-literal
2564 void ModuleMapParser::parseConflict() {
2565   assert(Tok.is(MMToken::Conflict));
2566   SourceLocation ConflictLoc = consumeToken();
2567   Module::UnresolvedConflict Conflict;
2568 
2569   // Parse the module-id.
2570   if (parseModuleId(Conflict.Id))
2571     return;
2572 
2573   // Parse the ','.
2574   if (!Tok.is(MMToken::Comma)) {
2575     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_conflicts_comma)
2576       << SourceRange(ConflictLoc);
2577     return;
2578   }
2579   consumeToken();
2580 
2581   // Parse the message.
2582   if (!Tok.is(MMToken::StringLiteral)) {
2583     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_conflicts_message)
2584       << formatModuleId(Conflict.Id);
2585     return;
2586   }
2587   Conflict.Message = Tok.getString().str();
2588   consumeToken();
2589 
2590   // Add this unresolved conflict.
2591   ActiveModule->UnresolvedConflicts.push_back(Conflict);
2592 }
2593 
2594 /// \brief Parse an inferred module declaration (wildcard modules).
2595 ///
2596 ///   module-declaration:
2597 ///     'explicit'[opt] 'framework'[opt] 'module' * attributes[opt]
2598 ///       { inferred-module-member* }
2599 ///
2600 ///   inferred-module-member:
2601 ///     'export' '*'
2602 ///     'exclude' identifier
2603 void ModuleMapParser::parseInferredModuleDecl(bool Framework, bool Explicit) {
2604   assert(Tok.is(MMToken::Star));
2605   SourceLocation StarLoc = consumeToken();
2606   bool Failed = false;
2607 
2608   // Inferred modules must be submodules.
2609   if (!ActiveModule && !Framework) {
2610     Diags.Report(StarLoc, diag::err_mmap_top_level_inferred_submodule);
2611     Failed = true;
2612   }
2613 
2614   if (ActiveModule) {
2615     // Inferred modules must have umbrella directories.
2616     if (!Failed && ActiveModule->IsAvailable &&
2617         !ActiveModule->getUmbrellaDir()) {
2618       Diags.Report(StarLoc, diag::err_mmap_inferred_no_umbrella);
2619       Failed = true;
2620     }
2621 
2622     // Check for redefinition of an inferred module.
2623     if (!Failed && ActiveModule->InferSubmodules) {
2624       Diags.Report(StarLoc, diag::err_mmap_inferred_redef);
2625       if (ActiveModule->InferredSubmoduleLoc.isValid())
2626         Diags.Report(ActiveModule->InferredSubmoduleLoc,
2627                      diag::note_mmap_prev_definition);
2628       Failed = true;
2629     }
2630 
2631     // Check for the 'framework' keyword, which is not permitted here.
2632     if (Framework) {
2633       Diags.Report(StarLoc, diag::err_mmap_inferred_framework_submodule);
2634       Framework = false;
2635     }
2636   } else if (Explicit) {
2637     Diags.Report(StarLoc, diag::err_mmap_explicit_inferred_framework);
2638     Explicit = false;
2639   }
2640 
2641   // If there were any problems with this inferred submodule, skip its body.
2642   if (Failed) {
2643     if (Tok.is(MMToken::LBrace)) {
2644       consumeToken();
2645       skipUntil(MMToken::RBrace);
2646       if (Tok.is(MMToken::RBrace))
2647         consumeToken();
2648     }
2649     HadError = true;
2650     return;
2651   }
2652 
2653   // Parse optional attributes.
2654   Attributes Attrs;
2655   if (parseOptionalAttributes(Attrs))
2656     return;
2657 
2658   if (ActiveModule) {
2659     // Note that we have an inferred submodule.
2660     ActiveModule->InferSubmodules = true;
2661     ActiveModule->InferredSubmoduleLoc = StarLoc;
2662     ActiveModule->InferExplicitSubmodules = Explicit;
2663   } else {
2664     // We'll be inferring framework modules for this directory.
2665     Map.InferredDirectories[Directory].InferModules = true;
2666     Map.InferredDirectories[Directory].Attrs = Attrs;
2667     Map.InferredDirectories[Directory].ModuleMapFile = ModuleMapFile;
2668     // FIXME: Handle the 'framework' keyword.
2669   }
2670 
2671   // Parse the opening brace.
2672   if (!Tok.is(MMToken::LBrace)) {
2673     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_lbrace_wildcard);
2674     HadError = true;
2675     return;
2676   }
2677   SourceLocation LBraceLoc = consumeToken();
2678 
2679   // Parse the body of the inferred submodule.
2680   bool Done = false;
2681   do {
2682     switch (Tok.Kind) {
2683     case MMToken::EndOfFile:
2684     case MMToken::RBrace:
2685       Done = true;
2686       break;
2687 
2688     case MMToken::ExcludeKeyword:
2689       if (ActiveModule) {
2690         Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member)
2691           << (ActiveModule != nullptr);
2692         consumeToken();
2693         break;
2694       }
2695 
2696       consumeToken();
2697       // FIXME: Support string-literal module names here.
2698       if (!Tok.is(MMToken::Identifier)) {
2699         Diags.Report(Tok.getLocation(), diag::err_mmap_missing_exclude_name);
2700         break;
2701       }
2702 
2703       Map.InferredDirectories[Directory].ExcludedModules
2704         .push_back(Tok.getString());
2705       consumeToken();
2706       break;
2707 
2708     case MMToken::ExportKeyword:
2709       if (!ActiveModule) {
2710         Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member)
2711           << (ActiveModule != nullptr);
2712         consumeToken();
2713         break;
2714       }
2715 
2716       consumeToken();
2717       if (Tok.is(MMToken::Star))
2718         ActiveModule->InferExportWildcard = true;
2719       else
2720         Diags.Report(Tok.getLocation(),
2721                      diag::err_mmap_expected_export_wildcard);
2722       consumeToken();
2723       break;
2724 
2725     case MMToken::ExplicitKeyword:
2726     case MMToken::ModuleKeyword:
2727     case MMToken::HeaderKeyword:
2728     case MMToken::PrivateKeyword:
2729     case MMToken::UmbrellaKeyword:
2730     default:
2731       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member)
2732           << (ActiveModule != nullptr);
2733       consumeToken();
2734       break;
2735     }
2736   } while (!Done);
2737 
2738   if (Tok.is(MMToken::RBrace))
2739     consumeToken();
2740   else {
2741     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
2742     Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
2743     HadError = true;
2744   }
2745 }
2746 
2747 /// \brief Parse optional attributes.
2748 ///
2749 ///   attributes:
2750 ///     attribute attributes
2751 ///     attribute
2752 ///
2753 ///   attribute:
2754 ///     [ identifier ]
2755 ///
2756 /// \param Attrs Will be filled in with the parsed attributes.
2757 ///
2758 /// \returns true if an error occurred, false otherwise.
2759 bool ModuleMapParser::parseOptionalAttributes(Attributes &Attrs) {
2760   bool HadError = false;
2761 
2762   while (Tok.is(MMToken::LSquare)) {
2763     // Consume the '['.
2764     SourceLocation LSquareLoc = consumeToken();
2765 
2766     // Check whether we have an attribute name here.
2767     if (!Tok.is(MMToken::Identifier)) {
2768       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_attribute);
2769       skipUntil(MMToken::RSquare);
2770       if (Tok.is(MMToken::RSquare))
2771         consumeToken();
2772       HadError = true;
2773     }
2774 
2775     // Decode the attribute name.
2776     AttributeKind Attribute
2777       = llvm::StringSwitch<AttributeKind>(Tok.getString())
2778           .Case("exhaustive", AT_exhaustive)
2779           .Case("extern_c", AT_extern_c)
2780           .Case("no_undeclared_includes", AT_no_undeclared_includes)
2781           .Case("system", AT_system)
2782           .Default(AT_unknown);
2783     switch (Attribute) {
2784     case AT_unknown:
2785       Diags.Report(Tok.getLocation(), diag::warn_mmap_unknown_attribute)
2786         << Tok.getString();
2787       break;
2788 
2789     case AT_system:
2790       Attrs.IsSystem = true;
2791       break;
2792 
2793     case AT_extern_c:
2794       Attrs.IsExternC = true;
2795       break;
2796 
2797     case AT_exhaustive:
2798       Attrs.IsExhaustive = true;
2799       break;
2800 
2801     case AT_no_undeclared_includes:
2802       Attrs.NoUndeclaredIncludes = true;
2803       break;
2804     }
2805     consumeToken();
2806 
2807     // Consume the ']'.
2808     if (!Tok.is(MMToken::RSquare)) {
2809       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rsquare);
2810       Diags.Report(LSquareLoc, diag::note_mmap_lsquare_match);
2811       skipUntil(MMToken::RSquare);
2812       HadError = true;
2813     }
2814 
2815     if (Tok.is(MMToken::RSquare))
2816       consumeToken();
2817   }
2818 
2819   return HadError;
2820 }
2821 
2822 /// \brief Parse a module map file.
2823 ///
2824 ///   module-map-file:
2825 ///     module-declaration*
2826 bool ModuleMapParser::parseModuleMapFile() {
2827   do {
2828     switch (Tok.Kind) {
2829     case MMToken::EndOfFile:
2830       return HadError;
2831 
2832     case MMToken::ExplicitKeyword:
2833     case MMToken::ExternKeyword:
2834     case MMToken::ModuleKeyword:
2835     case MMToken::FrameworkKeyword:
2836       parseModuleDecl();
2837       break;
2838 
2839     case MMToken::Comma:
2840     case MMToken::ConfigMacros:
2841     case MMToken::Conflict:
2842     case MMToken::Exclaim:
2843     case MMToken::ExcludeKeyword:
2844     case MMToken::ExportKeyword:
2845     case MMToken::ExportAsKeyword:
2846     case MMToken::HeaderKeyword:
2847     case MMToken::Identifier:
2848     case MMToken::LBrace:
2849     case MMToken::LinkKeyword:
2850     case MMToken::LSquare:
2851     case MMToken::Period:
2852     case MMToken::PrivateKeyword:
2853     case MMToken::RBrace:
2854     case MMToken::RSquare:
2855     case MMToken::RequiresKeyword:
2856     case MMToken::Star:
2857     case MMToken::StringLiteral:
2858     case MMToken::IntegerLiteral:
2859     case MMToken::TextualKeyword:
2860     case MMToken::UmbrellaKeyword:
2861     case MMToken::UseKeyword:
2862       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module);
2863       HadError = true;
2864       consumeToken();
2865       break;
2866     }
2867   } while (true);
2868 }
2869 
2870 bool ModuleMap::parseModuleMapFile(const FileEntry *File, bool IsSystem,
2871                                    const DirectoryEntry *Dir, FileID ID,
2872                                    unsigned *Offset,
2873                                    SourceLocation ExternModuleLoc) {
2874   assert(Target && "Missing target information");
2875   llvm::DenseMap<const FileEntry *, bool>::iterator Known
2876     = ParsedModuleMap.find(File);
2877   if (Known != ParsedModuleMap.end())
2878     return Known->second;
2879 
2880   // If the module map file wasn't already entered, do so now.
2881   if (ID.isInvalid()) {
2882     auto FileCharacter =
2883         IsSystem ? SrcMgr::C_System_ModuleMap : SrcMgr::C_User_ModuleMap;
2884     ID = SourceMgr.createFileID(File, ExternModuleLoc, FileCharacter);
2885   }
2886 
2887   assert(Target && "Missing target information");
2888   const llvm::MemoryBuffer *Buffer = SourceMgr.getBuffer(ID);
2889   if (!Buffer)
2890     return ParsedModuleMap[File] = true;
2891   assert((!Offset || *Offset <= Buffer->getBufferSize()) &&
2892          "invalid buffer offset");
2893 
2894   // Parse this module map file.
2895   Lexer L(SourceMgr.getLocForStartOfFile(ID), MMapLangOpts,
2896           Buffer->getBufferStart(),
2897           Buffer->getBufferStart() + (Offset ? *Offset : 0),
2898           Buffer->getBufferEnd());
2899   SourceLocation Start = L.getSourceLocation();
2900   ModuleMapParser Parser(L, SourceMgr, Target, Diags, *this, File, Dir,
2901                          IsSystem);
2902   bool Result = Parser.parseModuleMapFile();
2903   ParsedModuleMap[File] = Result;
2904 
2905   if (Offset) {
2906     auto Loc = SourceMgr.getDecomposedLoc(Parser.getLocation());
2907     assert(Loc.first == ID && "stopped in a different file?");
2908     *Offset = Loc.second;
2909   }
2910 
2911   // Notify callbacks that we parsed it.
2912   for (const auto &Cb : Callbacks)
2913     Cb->moduleMapFileRead(Start, *File, IsSystem);
2914 
2915   return Result;
2916 }
2917