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