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