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