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