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