1718292f2SDouglas Gregor //===--- ModuleMap.cpp - Describe the layout of modules ---------*- C++ -*-===//
2718292f2SDouglas Gregor //
3718292f2SDouglas Gregor //                     The LLVM Compiler Infrastructure
4718292f2SDouglas Gregor //
5718292f2SDouglas Gregor // This file is distributed under the University of Illinois Open Source
6718292f2SDouglas Gregor // License. See LICENSE.TXT for details.
7718292f2SDouglas Gregor //
8718292f2SDouglas Gregor //===----------------------------------------------------------------------===//
9718292f2SDouglas Gregor //
10718292f2SDouglas Gregor // This file defines the ModuleMap implementation, which describes the layout
11718292f2SDouglas Gregor // of a module as it relates to headers.
12718292f2SDouglas Gregor //
13718292f2SDouglas Gregor //===----------------------------------------------------------------------===//
14718292f2SDouglas Gregor #include "clang/Lex/ModuleMap.h"
15a7d03840SJordan Rose #include "clang/Basic/CharInfo.h"
16718292f2SDouglas Gregor #include "clang/Basic/Diagnostic.h"
17811db4eaSDouglas Gregor #include "clang/Basic/DiagnosticOptions.h"
18718292f2SDouglas Gregor #include "clang/Basic/FileManager.h"
19718292f2SDouglas Gregor #include "clang/Basic/TargetInfo.h"
20718292f2SDouglas Gregor #include "clang/Basic/TargetOptions.h"
21b146baabSArgyrios Kyrtzidis #include "clang/Lex/HeaderSearch.h"
229acb99e3SRichard Smith #include "clang/Lex/HeaderSearchOptions.h"
233a02247dSChandler Carruth #include "clang/Lex/LexDiagnostic.h"
243a02247dSChandler Carruth #include "clang/Lex/Lexer.h"
253a02247dSChandler Carruth #include "clang/Lex/LiteralSupport.h"
263a02247dSChandler Carruth #include "llvm/ADT/StringRef.h"
273a02247dSChandler Carruth #include "llvm/ADT/StringSwitch.h"
28718292f2SDouglas Gregor #include "llvm/Support/Allocator.h"
29e89dbc1dSDouglas Gregor #include "llvm/Support/FileSystem.h"
30718292f2SDouglas Gregor #include "llvm/Support/Host.h"
31552c169eSRafael Espindola #include "llvm/Support/Path.h"
32718292f2SDouglas Gregor #include "llvm/Support/raw_ostream.h"
3307c22b78SDouglas Gregor #include <stdlib.h>
3401c7cfa2SDouglas Gregor #if defined(LLVM_ON_UNIX)
35eadae014SDmitri Gribenko #include <limits.h>
3601c7cfa2SDouglas Gregor #endif
37718292f2SDouglas Gregor using namespace clang;
38718292f2SDouglas Gregor 
392b82c2a5SDouglas Gregor Module::ExportDecl
402b82c2a5SDouglas Gregor ModuleMap::resolveExport(Module *Mod,
412b82c2a5SDouglas Gregor                          const Module::UnresolvedExportDecl &Unresolved,
42e4412640SArgyrios Kyrtzidis                          bool Complain) const {
43f5eedd05SDouglas Gregor   // We may have just a wildcard.
44f5eedd05SDouglas Gregor   if (Unresolved.Id.empty()) {
45f5eedd05SDouglas Gregor     assert(Unresolved.Wildcard && "Invalid unresolved export");
46d2d442caSCraig Topper     return Module::ExportDecl(nullptr, true);
47f5eedd05SDouglas Gregor   }
48f5eedd05SDouglas Gregor 
49fb912657SDouglas Gregor   // Resolve the module-id.
50fb912657SDouglas Gregor   Module *Context = resolveModuleId(Unresolved.Id, Mod, Complain);
51fb912657SDouglas Gregor   if (!Context)
52fb912657SDouglas Gregor     return Module::ExportDecl();
53fb912657SDouglas Gregor 
54fb912657SDouglas Gregor   return Module::ExportDecl(Context, Unresolved.Wildcard);
55fb912657SDouglas Gregor }
56fb912657SDouglas Gregor 
57fb912657SDouglas Gregor Module *ModuleMap::resolveModuleId(const ModuleId &Id, Module *Mod,
58fb912657SDouglas Gregor                                    bool Complain) const {
592b82c2a5SDouglas Gregor   // Find the starting module.
60fb912657SDouglas Gregor   Module *Context = lookupModuleUnqualified(Id[0].first, Mod);
612b82c2a5SDouglas Gregor   if (!Context) {
622b82c2a5SDouglas Gregor     if (Complain)
630761a8a0SDaniel Jasper       Diags.Report(Id[0].second, diag::err_mmap_missing_module_unqualified)
64fb912657SDouglas Gregor       << Id[0].first << Mod->getFullModuleName();
652b82c2a5SDouglas Gregor 
66d2d442caSCraig Topper     return nullptr;
672b82c2a5SDouglas Gregor   }
682b82c2a5SDouglas Gregor 
692b82c2a5SDouglas Gregor   // Dig into the module path.
70fb912657SDouglas Gregor   for (unsigned I = 1, N = Id.size(); I != N; ++I) {
71fb912657SDouglas Gregor     Module *Sub = lookupModuleQualified(Id[I].first, Context);
722b82c2a5SDouglas Gregor     if (!Sub) {
732b82c2a5SDouglas Gregor       if (Complain)
740761a8a0SDaniel Jasper         Diags.Report(Id[I].second, diag::err_mmap_missing_module_qualified)
75fb912657SDouglas Gregor         << Id[I].first << Context->getFullModuleName()
76fb912657SDouglas Gregor         << SourceRange(Id[0].second, Id[I-1].second);
772b82c2a5SDouglas Gregor 
78d2d442caSCraig Topper       return nullptr;
792b82c2a5SDouglas Gregor     }
802b82c2a5SDouglas Gregor 
812b82c2a5SDouglas Gregor     Context = Sub;
822b82c2a5SDouglas Gregor   }
832b82c2a5SDouglas Gregor 
84fb912657SDouglas Gregor   return Context;
852b82c2a5SDouglas Gregor }
862b82c2a5SDouglas Gregor 
870761a8a0SDaniel Jasper ModuleMap::ModuleMap(SourceManager &SourceMgr, DiagnosticsEngine &Diags,
88b146baabSArgyrios Kyrtzidis                      const LangOptions &LangOpts, const TargetInfo *Target,
89b146baabSArgyrios Kyrtzidis                      HeaderSearch &HeaderInfo)
900761a8a0SDaniel Jasper     : SourceMgr(SourceMgr), Diags(Diags), LangOpts(LangOpts), Target(Target),
91d2d442caSCraig Topper       HeaderInfo(HeaderInfo), BuiltinIncludeDir(nullptr),
927e82e019SRichard Smith       SourceModule(nullptr), NumCreatedModules(0) {
930414b857SRichard Smith   MMapLangOpts.LineComment = true;
940414b857SRichard Smith }
95718292f2SDouglas Gregor 
96718292f2SDouglas Gregor ModuleMap::~ModuleMap() {
9721668754SDavide Italiano   for (auto &M : Modules)
9821668754SDavide Italiano     delete M.getValue();
99718292f2SDouglas Gregor }
100718292f2SDouglas Gregor 
10189929282SDouglas Gregor void ModuleMap::setTarget(const TargetInfo &Target) {
10289929282SDouglas Gregor   assert((!this->Target || this->Target == &Target) &&
10389929282SDouglas Gregor          "Improper target override");
10489929282SDouglas Gregor   this->Target = &Target;
10589929282SDouglas Gregor }
10689929282SDouglas Gregor 
107056396aeSDouglas Gregor /// \brief "Sanitize" a filename so that it can be used as an identifier.
108056396aeSDouglas Gregor static StringRef sanitizeFilenameAsIdentifier(StringRef Name,
109056396aeSDouglas Gregor                                               SmallVectorImpl<char> &Buffer) {
110056396aeSDouglas Gregor   if (Name.empty())
111056396aeSDouglas Gregor     return Name;
112056396aeSDouglas Gregor 
113a7d03840SJordan Rose   if (!isValidIdentifier(Name)) {
114056396aeSDouglas Gregor     // If we don't already have something with the form of an identifier,
115056396aeSDouglas Gregor     // create a buffer with the sanitized name.
116056396aeSDouglas Gregor     Buffer.clear();
117a7d03840SJordan Rose     if (isDigit(Name[0]))
118056396aeSDouglas Gregor       Buffer.push_back('_');
119056396aeSDouglas Gregor     Buffer.reserve(Buffer.size() + Name.size());
120056396aeSDouglas Gregor     for (unsigned I = 0, N = Name.size(); I != N; ++I) {
121a7d03840SJordan Rose       if (isIdentifierBody(Name[I]))
122056396aeSDouglas Gregor         Buffer.push_back(Name[I]);
123056396aeSDouglas Gregor       else
124056396aeSDouglas Gregor         Buffer.push_back('_');
125056396aeSDouglas Gregor     }
126056396aeSDouglas Gregor 
127056396aeSDouglas Gregor     Name = StringRef(Buffer.data(), Buffer.size());
128056396aeSDouglas Gregor   }
129056396aeSDouglas Gregor 
130056396aeSDouglas Gregor   while (llvm::StringSwitch<bool>(Name)
131056396aeSDouglas Gregor #define KEYWORD(Keyword,Conditions) .Case(#Keyword, true)
132056396aeSDouglas Gregor #define ALIAS(Keyword, AliasOf, Conditions) .Case(Keyword, true)
133056396aeSDouglas Gregor #include "clang/Basic/TokenKinds.def"
134056396aeSDouglas Gregor            .Default(false)) {
135056396aeSDouglas Gregor     if (Name.data() != Buffer.data())
136056396aeSDouglas Gregor       Buffer.append(Name.begin(), Name.end());
137056396aeSDouglas Gregor     Buffer.push_back('_');
138056396aeSDouglas Gregor     Name = StringRef(Buffer.data(), Buffer.size());
139056396aeSDouglas Gregor   }
140056396aeSDouglas Gregor 
141056396aeSDouglas Gregor   return Name;
142056396aeSDouglas Gregor }
143056396aeSDouglas Gregor 
14434d52749SDouglas Gregor /// \brief Determine whether the given file name is the name of a builtin
14534d52749SDouglas Gregor /// header, supplied by Clang to replace, override, or augment existing system
14634d52749SDouglas Gregor /// headers.
14734d52749SDouglas Gregor static bool isBuiltinHeader(StringRef FileName) {
14834d52749SDouglas Gregor   return llvm::StringSwitch<bool>(FileName)
14934d52749SDouglas Gregor            .Case("float.h", true)
15034d52749SDouglas Gregor            .Case("iso646.h", true)
15134d52749SDouglas Gregor            .Case("limits.h", true)
15234d52749SDouglas Gregor            .Case("stdalign.h", true)
15334d52749SDouglas Gregor            .Case("stdarg.h", true)
1543c4b1290SBen Langmuir            .Case("stdatomic.h", true)
15534d52749SDouglas Gregor            .Case("stdbool.h", true)
15634d52749SDouglas Gregor            .Case("stddef.h", true)
15734d52749SDouglas Gregor            .Case("stdint.h", true)
15834d52749SDouglas Gregor            .Case("tgmath.h", true)
15934d52749SDouglas Gregor            .Case("unwind.h", true)
16034d52749SDouglas Gregor            .Default(false);
16134d52749SDouglas Gregor }
16234d52749SDouglas Gregor 
16392669ee4SDaniel Jasper ModuleMap::HeadersMap::iterator
16492669ee4SDaniel Jasper ModuleMap::findKnownHeader(const FileEntry *File) {
16559527666SDouglas Gregor   HeadersMap::iterator Known = Headers.find(File);
16647972afdSRichard Smith   if (HeaderInfo.getHeaderSearchOpts().ImplicitModuleMaps &&
16747972afdSRichard Smith       Known == Headers.end() && File->getDir() == BuiltinIncludeDir &&
1684eaf0a6cSDaniel Jasper       isBuiltinHeader(llvm::sys::path::filename(File->getName()))) {
1694eaf0a6cSDaniel Jasper     HeaderInfo.loadTopLevelSystemModules();
17092669ee4SDaniel Jasper     return Headers.find(File);
1714eaf0a6cSDaniel Jasper   }
17292669ee4SDaniel Jasper   return Known;
17392669ee4SDaniel Jasper }
17492669ee4SDaniel Jasper 
1754469138eSBen Langmuir ModuleMap::KnownHeader
1764469138eSBen Langmuir ModuleMap::findHeaderInUmbrellaDirs(const FileEntry *File,
1774469138eSBen Langmuir                     SmallVectorImpl<const DirectoryEntry *> &IntermediateDirs) {
17847972afdSRichard Smith   if (UmbrellaDirs.empty())
17947972afdSRichard Smith     return KnownHeader();
18047972afdSRichard Smith 
1814469138eSBen Langmuir   const DirectoryEntry *Dir = File->getDir();
1824469138eSBen Langmuir   assert(Dir && "file in no directory");
1834469138eSBen Langmuir 
1844469138eSBen Langmuir   // Note: as an egregious but useful hack we use the real path here, because
1854469138eSBen Langmuir   // frameworks moving from top-level frameworks to embedded frameworks tend
1864469138eSBen Langmuir   // to be symlinked from the top-level location to the embedded location,
1874469138eSBen Langmuir   // and we need to resolve lookups as if we had found the embedded location.
1884469138eSBen Langmuir   StringRef DirName = SourceMgr.getFileManager().getCanonicalName(Dir);
1894469138eSBen Langmuir 
1904469138eSBen Langmuir   // Keep walking up the directory hierarchy, looking for a directory with
1914469138eSBen Langmuir   // an umbrella header.
1924469138eSBen Langmuir   do {
1934469138eSBen Langmuir     auto KnownDir = UmbrellaDirs.find(Dir);
1944469138eSBen Langmuir     if (KnownDir != UmbrellaDirs.end())
1954469138eSBen Langmuir       return KnownHeader(KnownDir->second, NormalHeader);
1964469138eSBen Langmuir 
1974469138eSBen Langmuir     IntermediateDirs.push_back(Dir);
1984469138eSBen Langmuir 
1994469138eSBen Langmuir     // Retrieve our parent path.
2004469138eSBen Langmuir     DirName = llvm::sys::path::parent_path(DirName);
2014469138eSBen Langmuir     if (DirName.empty())
2024469138eSBen Langmuir       break;
2034469138eSBen Langmuir 
2044469138eSBen Langmuir     // Resolve the parent path to a directory entry.
2054469138eSBen Langmuir     Dir = SourceMgr.getFileManager().getDirectory(DirName);
2064469138eSBen Langmuir   } while (Dir);
2074469138eSBen Langmuir   return KnownHeader();
2084469138eSBen Langmuir }
2094469138eSBen Langmuir 
21092669ee4SDaniel Jasper static bool violatesPrivateInclude(Module *RequestingModule,
21192669ee4SDaniel Jasper                                    const FileEntry *IncFileEnt,
212*4eb8393cSRichard Smith                                    ModuleMap::KnownHeader Header) {
21392669ee4SDaniel Jasper #ifndef NDEBUG
214*4eb8393cSRichard Smith   if (Header.getRole() & ModuleMap::PrivateHeader) {
21592669ee4SDaniel Jasper     // Check for consistency between the module header role
21692669ee4SDaniel Jasper     // as obtained from the lookup and as obtained from the module.
21792669ee4SDaniel Jasper     // This check is not cheap, so enable it only for debugging.
2182708e520SRichard Smith     bool IsPrivate = false;
2192708e520SRichard Smith     SmallVectorImpl<Module::Header> *HeaderList[] = {
220*4eb8393cSRichard Smith         &Header.getModule()->Headers[Module::HK_Private],
221*4eb8393cSRichard Smith         &Header.getModule()->Headers[Module::HK_PrivateTextual]};
2222708e520SRichard Smith     for (auto *Hs : HeaderList)
2232708e520SRichard Smith       IsPrivate |=
2242708e520SRichard Smith           std::find_if(Hs->begin(), Hs->end(), [&](const Module::Header &H) {
2253c1a41adSRichard Smith             return H.Entry == IncFileEnt;
2262708e520SRichard Smith           }) != Hs->end();
227*4eb8393cSRichard Smith     assert(IsPrivate && "inconsistent headers and roles");
22800bc95ecSRichard Smith   }
22992669ee4SDaniel Jasper #endif
230*4eb8393cSRichard Smith   return !Header.isAccessibleFrom(RequestingModule);
23192669ee4SDaniel Jasper }
23292669ee4SDaniel Jasper 
23371e1a64fSBen Langmuir static Module *getTopLevelOrNull(Module *M) {
23471e1a64fSBen Langmuir   return M ? M->getTopLevelModule() : nullptr;
23571e1a64fSBen Langmuir }
23671e1a64fSBen Langmuir 
23792669ee4SDaniel Jasper void ModuleMap::diagnoseHeaderInclusion(Module *RequestingModule,
2388d4e90b3SRichard Smith                                         bool RequestingModuleIsModuleInterface,
23992669ee4SDaniel Jasper                                         SourceLocation FilenameLoc,
24092669ee4SDaniel Jasper                                         StringRef Filename,
24192669ee4SDaniel Jasper                                         const FileEntry *File) {
24292669ee4SDaniel Jasper   // No errors for indirect modules. This may be a bit of a problem for modules
24392669ee4SDaniel Jasper   // with no source files.
24471e1a64fSBen Langmuir   if (getTopLevelOrNull(RequestingModule) != getTopLevelOrNull(SourceModule))
24592669ee4SDaniel Jasper     return;
24692669ee4SDaniel Jasper 
24792669ee4SDaniel Jasper   if (RequestingModule)
24892669ee4SDaniel Jasper     resolveUses(RequestingModule, /*Complain=*/false);
24992669ee4SDaniel Jasper 
25071e1a64fSBen Langmuir   bool Excluded = false;
251d2d442caSCraig Topper   Module *Private = nullptr;
252d2d442caSCraig Topper   Module *NotUsed = nullptr;
25371e1a64fSBen Langmuir 
25471e1a64fSBen Langmuir   HeadersMap::iterator Known = findKnownHeader(File);
25571e1a64fSBen Langmuir   if (Known != Headers.end()) {
25671e1a64fSBen Langmuir     for (const KnownHeader &Header : Known->second) {
25792669ee4SDaniel Jasper       // Remember private headers for later printing of a diagnostic.
258*4eb8393cSRichard Smith       if (violatesPrivateInclude(RequestingModule, File, Header)) {
25971e1a64fSBen Langmuir         Private = Header.getModule();
26092669ee4SDaniel Jasper         continue;
26192669ee4SDaniel Jasper       }
26292669ee4SDaniel Jasper 
26392669ee4SDaniel Jasper       // If uses need to be specified explicitly, we are only allowed to return
26492669ee4SDaniel Jasper       // modules that are explicitly used by the requesting module.
26592669ee4SDaniel Jasper       if (RequestingModule && LangOpts.ModulesDeclUse &&
2668f4d3ff1SRichard Smith           !RequestingModule->directlyUses(Header.getModule())) {
26771e1a64fSBen Langmuir         NotUsed = Header.getModule();
26892669ee4SDaniel Jasper         continue;
26992669ee4SDaniel Jasper       }
27092669ee4SDaniel Jasper 
27192669ee4SDaniel Jasper       // We have found a module that we can happily use.
27292669ee4SDaniel Jasper       return;
27392669ee4SDaniel Jasper     }
274feb54b6dSRichard Smith 
275feb54b6dSRichard Smith     Excluded = true;
27671e1a64fSBen Langmuir   }
27792669ee4SDaniel Jasper 
27892669ee4SDaniel Jasper   // We have found a header, but it is private.
279d2d442caSCraig Topper   if (Private) {
28011152dd5SRichard Smith     Diags.Report(FilenameLoc, diag::warn_use_of_private_header_outside_module)
28192669ee4SDaniel Jasper         << Filename;
28292669ee4SDaniel Jasper     return;
28392669ee4SDaniel Jasper   }
28492669ee4SDaniel Jasper 
28592669ee4SDaniel Jasper   // We have found a module, but we don't use it.
286d2d442caSCraig Topper   if (NotUsed) {
28711152dd5SRichard Smith     Diags.Report(FilenameLoc, diag::err_undeclared_use_of_module)
28892669ee4SDaniel Jasper         << RequestingModule->getFullModuleName() << Filename;
28992669ee4SDaniel Jasper     return;
29092669ee4SDaniel Jasper   }
29192669ee4SDaniel Jasper 
29271e1a64fSBen Langmuir   if (Excluded || isHeaderInUmbrellaDirs(File))
29371e1a64fSBen Langmuir     return;
29471e1a64fSBen Langmuir 
29571e1a64fSBen Langmuir   // At this point, only non-modular includes remain.
29671e1a64fSBen Langmuir 
29771e1a64fSBen Langmuir   if (LangOpts.ModulesStrictDeclUse) {
29811152dd5SRichard Smith     Diags.Report(FilenameLoc, diag::err_undeclared_use_of_module)
29971e1a64fSBen Langmuir         << RequestingModule->getFullModuleName() << Filename;
3008d4e90b3SRichard Smith   } else if (RequestingModule && RequestingModuleIsModuleInterface) {
30171e1a64fSBen Langmuir     diag::kind DiagID = RequestingModule->getTopLevelModule()->IsFramework ?
30271e1a64fSBen Langmuir         diag::warn_non_modular_include_in_framework_module :
30371e1a64fSBen Langmuir         diag::warn_non_modular_include_in_module;
30471e1a64fSBen Langmuir     Diags.Report(FilenameLoc, DiagID) << RequestingModule->getFullModuleName();
30571e1a64fSBen Langmuir   }
30692669ee4SDaniel Jasper }
30792669ee4SDaniel Jasper 
308ec87a50aSRichard Smith static bool isBetterKnownHeader(const ModuleMap::KnownHeader &New,
309ec87a50aSRichard Smith                                 const ModuleMap::KnownHeader &Old) {
3108b7c0398SSean Silva   // Prefer available modules.
3118b7c0398SSean Silva   if (New.getModule()->isAvailable() && !Old.getModule()->isAvailable())
3128b7c0398SSean Silva     return true;
3138b7c0398SSean Silva 
314ec87a50aSRichard Smith   // Prefer a public header over a private header.
315ec87a50aSRichard Smith   if ((New.getRole() & ModuleMap::PrivateHeader) !=
316ec87a50aSRichard Smith       (Old.getRole() & ModuleMap::PrivateHeader))
317ec87a50aSRichard Smith     return !(New.getRole() & ModuleMap::PrivateHeader);
318ec87a50aSRichard Smith 
319ec87a50aSRichard Smith   // Prefer a non-textual header over a textual header.
320ec87a50aSRichard Smith   if ((New.getRole() & ModuleMap::TextualHeader) !=
321ec87a50aSRichard Smith       (Old.getRole() & ModuleMap::TextualHeader))
322ec87a50aSRichard Smith     return !(New.getRole() & ModuleMap::TextualHeader);
323ec87a50aSRichard Smith 
324ec87a50aSRichard Smith   // Don't have a reason to choose between these. Just keep the first one.
325ec87a50aSRichard Smith   return false;
326ec87a50aSRichard Smith }
327ec87a50aSRichard Smith 
3284881e8b2SSean Silva ModuleMap::KnownHeader ModuleMap::findModuleForHeader(const FileEntry *File) {
329306d8920SRichard Smith   auto MakeResult = [&](ModuleMap::KnownHeader R) -> ModuleMap::KnownHeader {
3308230e5eeSSean Silva     if (R.getRole() & ModuleMap::TextualHeader)
331306d8920SRichard Smith       return ModuleMap::KnownHeader();
332306d8920SRichard Smith     return R;
333306d8920SRichard Smith   };
334306d8920SRichard Smith 
3354881e8b2SSean Silva   HeadersMap::iterator Known = findKnownHeader(File);
3361fb5c3a6SDouglas Gregor   if (Known != Headers.end()) {
337202210b3SRichard Smith     ModuleMap::KnownHeader Result;
33897da9178SDaniel Jasper     // Iterate over all modules that 'File' is part of to find the best fit.
3394881e8b2SSean Silva     for (KnownHeader &H : Known->second) {
3407e82e019SRichard Smith       // Prefer a header from the source module over all others.
3417e82e019SRichard Smith       if (H.getModule()->getTopLevelModule() == SourceModule)
3422f633e7cSRichard Smith         return MakeResult(H);
3434881e8b2SSean Silva       if (!Result || isBetterKnownHeader(H, Result))
3444881e8b2SSean Silva         Result = H;
34597da9178SDaniel Jasper     }
346306d8920SRichard Smith     return MakeResult(Result);
3471fb5c3a6SDouglas Gregor   }
348ab0c8a84SDouglas Gregor 
349386bb073SRichard Smith   return MakeResult(findOrCreateModuleForHeaderInUmbrellaDir(File));
350386bb073SRichard Smith }
351386bb073SRichard Smith 
352386bb073SRichard Smith ModuleMap::KnownHeader
353386bb073SRichard Smith ModuleMap::findOrCreateModuleForHeaderInUmbrellaDir(const FileEntry *File) {
354386bb073SRichard Smith   assert(!Headers.count(File) && "already have a module for this header");
355386bb073SRichard Smith 
356f857950dSDmitri Gribenko   SmallVector<const DirectoryEntry *, 2> SkippedDirs;
3574469138eSBen Langmuir   KnownHeader H = findHeaderInUmbrellaDirs(File, SkippedDirs);
3584469138eSBen Langmuir   if (H) {
3594469138eSBen Langmuir     Module *Result = H.getModule();
360930a85ccSDouglas Gregor 
361930a85ccSDouglas Gregor     // Search up the module stack until we find a module with an umbrella
36273141fa9SDouglas Gregor     // directory.
363930a85ccSDouglas Gregor     Module *UmbrellaModule = Result;
36473141fa9SDouglas Gregor     while (!UmbrellaModule->getUmbrellaDir() && UmbrellaModule->Parent)
365930a85ccSDouglas Gregor       UmbrellaModule = UmbrellaModule->Parent;
366930a85ccSDouglas Gregor 
367930a85ccSDouglas Gregor     if (UmbrellaModule->InferSubmodules) {
3689d6448b1SBen Langmuir       const FileEntry *UmbrellaModuleMap =
3699d6448b1SBen Langmuir           getModuleMapFileForUniquing(UmbrellaModule);
3709d6448b1SBen Langmuir 
371a89c5ac4SDouglas Gregor       // Infer submodules for each of the directories we found between
372a89c5ac4SDouglas Gregor       // the directory of the umbrella header and the directory where
373a89c5ac4SDouglas Gregor       // the actual header is located.
3749458f82dSDouglas Gregor       bool Explicit = UmbrellaModule->InferExplicitSubmodules;
3759458f82dSDouglas Gregor 
3767033127bSDouglas Gregor       for (unsigned I = SkippedDirs.size(); I != 0; --I) {
377a89c5ac4SDouglas Gregor         // Find or create the module that corresponds to this directory name.
378056396aeSDouglas Gregor         SmallString<32> NameBuf;
379056396aeSDouglas Gregor         StringRef Name = sanitizeFilenameAsIdentifier(
3804469138eSBen Langmuir             llvm::sys::path::stem(SkippedDirs[I-1]->getName()), NameBuf);
3819d6448b1SBen Langmuir         Result = findOrCreateModule(Name, Result, /*IsFramework=*/false,
3829d6448b1SBen Langmuir                                     Explicit).first;
3839d6448b1SBen Langmuir         InferredModuleAllowedBy[Result] = UmbrellaModuleMap;
384ffbafa2aSBen Langmuir         Result->IsInferred = true;
385a89c5ac4SDouglas Gregor 
386a89c5ac4SDouglas Gregor         // Associate the module and the directory.
387a89c5ac4SDouglas Gregor         UmbrellaDirs[SkippedDirs[I-1]] = Result;
388a89c5ac4SDouglas Gregor 
389a89c5ac4SDouglas Gregor         // If inferred submodules export everything they import, add a
390a89c5ac4SDouglas Gregor         // wildcard to the set of exports.
391930a85ccSDouglas Gregor         if (UmbrellaModule->InferExportWildcard && Result->Exports.empty())
392d2d442caSCraig Topper           Result->Exports.push_back(Module::ExportDecl(nullptr, true));
393a89c5ac4SDouglas Gregor       }
394a89c5ac4SDouglas Gregor 
395a89c5ac4SDouglas Gregor       // Infer a submodule with the same name as this header file.
396056396aeSDouglas Gregor       SmallString<32> NameBuf;
397056396aeSDouglas Gregor       StringRef Name = sanitizeFilenameAsIdentifier(
398056396aeSDouglas Gregor                          llvm::sys::path::stem(File->getName()), NameBuf);
3999d6448b1SBen Langmuir       Result = findOrCreateModule(Name, Result, /*IsFramework=*/false,
4009d6448b1SBen Langmuir                                   Explicit).first;
4019d6448b1SBen Langmuir       InferredModuleAllowedBy[Result] = UmbrellaModuleMap;
402ffbafa2aSBen Langmuir       Result->IsInferred = true;
4033c5305c1SArgyrios Kyrtzidis       Result->addTopHeader(File);
404a89c5ac4SDouglas Gregor 
405a89c5ac4SDouglas Gregor       // If inferred submodules export everything they import, add a
406a89c5ac4SDouglas Gregor       // wildcard to the set of exports.
407930a85ccSDouglas Gregor       if (UmbrellaModule->InferExportWildcard && Result->Exports.empty())
408d2d442caSCraig Topper         Result->Exports.push_back(Module::ExportDecl(nullptr, true));
409a89c5ac4SDouglas Gregor     } else {
410a89c5ac4SDouglas Gregor       // Record each of the directories we stepped through as being part of
411a89c5ac4SDouglas Gregor       // the module we found, since the umbrella header covers them all.
412a89c5ac4SDouglas Gregor       for (unsigned I = 0, N = SkippedDirs.size(); I != N; ++I)
413a89c5ac4SDouglas Gregor         UmbrellaDirs[SkippedDirs[I]] = Result;
414a89c5ac4SDouglas Gregor     }
415a89c5ac4SDouglas Gregor 
416386bb073SRichard Smith     KnownHeader Header(Result, NormalHeader);
417386bb073SRichard Smith     Headers[File].push_back(Header);
418386bb073SRichard Smith     return Header;
419a89c5ac4SDouglas Gregor   }
420a89c5ac4SDouglas Gregor 
421b53e5483SLawrence Crowl   return KnownHeader();
422ab0c8a84SDouglas Gregor }
423ab0c8a84SDouglas Gregor 
424386bb073SRichard Smith ArrayRef<ModuleMap::KnownHeader>
425386bb073SRichard Smith ModuleMap::findAllModulesForHeader(const FileEntry *File) const {
426386bb073SRichard Smith   auto It = Headers.find(File);
427386bb073SRichard Smith   if (It == Headers.end())
428386bb073SRichard Smith     return None;
429386bb073SRichard Smith   return It->second;
430386bb073SRichard Smith }
431386bb073SRichard Smith 
432e4412640SArgyrios Kyrtzidis bool ModuleMap::isHeaderInUnavailableModule(const FileEntry *Header) const {
433d2d442caSCraig Topper   return isHeaderUnavailableInModule(Header, nullptr);
43450996ce1SRichard Smith }
43550996ce1SRichard Smith 
43662bcd925SDmitri Gribenko bool
43762bcd925SDmitri Gribenko ModuleMap::isHeaderUnavailableInModule(const FileEntry *Header,
43862bcd925SDmitri Gribenko                                        const Module *RequestingModule) const {
439e4412640SArgyrios Kyrtzidis   HeadersMap::const_iterator Known = Headers.find(Header);
44097da9178SDaniel Jasper   if (Known != Headers.end()) {
44197da9178SDaniel Jasper     for (SmallVectorImpl<KnownHeader>::const_iterator
44297da9178SDaniel Jasper              I = Known->second.begin(),
44397da9178SDaniel Jasper              E = Known->second.end();
44497da9178SDaniel Jasper          I != E; ++I) {
44550996ce1SRichard Smith       if (I->isAvailable() && (!RequestingModule ||
44650996ce1SRichard Smith                                I->getModule()->isSubModuleOf(RequestingModule)))
44797da9178SDaniel Jasper         return false;
44897da9178SDaniel Jasper     }
44997da9178SDaniel Jasper     return true;
45097da9178SDaniel Jasper   }
4511fb5c3a6SDouglas Gregor 
4521fb5c3a6SDouglas Gregor   const DirectoryEntry *Dir = Header->getDir();
453f857950dSDmitri Gribenko   SmallVector<const DirectoryEntry *, 2> SkippedDirs;
4541fb5c3a6SDouglas Gregor   StringRef DirName = Dir->getName();
4551fb5c3a6SDouglas Gregor 
45650996ce1SRichard Smith   auto IsUnavailable = [&](const Module *M) {
45750996ce1SRichard Smith     return !M->isAvailable() && (!RequestingModule ||
45850996ce1SRichard Smith                                  M->isSubModuleOf(RequestingModule));
45950996ce1SRichard Smith   };
46050996ce1SRichard Smith 
4611fb5c3a6SDouglas Gregor   // Keep walking up the directory hierarchy, looking for a directory with
4621fb5c3a6SDouglas Gregor   // an umbrella header.
4631fb5c3a6SDouglas Gregor   do {
464e4412640SArgyrios Kyrtzidis     llvm::DenseMap<const DirectoryEntry *, Module *>::const_iterator KnownDir
4651fb5c3a6SDouglas Gregor       = UmbrellaDirs.find(Dir);
4661fb5c3a6SDouglas Gregor     if (KnownDir != UmbrellaDirs.end()) {
4671fb5c3a6SDouglas Gregor       Module *Found = KnownDir->second;
46850996ce1SRichard Smith       if (IsUnavailable(Found))
4691fb5c3a6SDouglas Gregor         return true;
4701fb5c3a6SDouglas Gregor 
4711fb5c3a6SDouglas Gregor       // Search up the module stack until we find a module with an umbrella
4721fb5c3a6SDouglas Gregor       // directory.
4731fb5c3a6SDouglas Gregor       Module *UmbrellaModule = Found;
4741fb5c3a6SDouglas Gregor       while (!UmbrellaModule->getUmbrellaDir() && UmbrellaModule->Parent)
4751fb5c3a6SDouglas Gregor         UmbrellaModule = UmbrellaModule->Parent;
4761fb5c3a6SDouglas Gregor 
4771fb5c3a6SDouglas Gregor       if (UmbrellaModule->InferSubmodules) {
4781fb5c3a6SDouglas Gregor         for (unsigned I = SkippedDirs.size(); I != 0; --I) {
4791fb5c3a6SDouglas Gregor           // Find or create the module that corresponds to this directory name.
480056396aeSDouglas Gregor           SmallString<32> NameBuf;
481056396aeSDouglas Gregor           StringRef Name = sanitizeFilenameAsIdentifier(
482056396aeSDouglas Gregor                              llvm::sys::path::stem(SkippedDirs[I-1]->getName()),
483056396aeSDouglas Gregor                              NameBuf);
4841fb5c3a6SDouglas Gregor           Found = lookupModuleQualified(Name, Found);
4851fb5c3a6SDouglas Gregor           if (!Found)
4861fb5c3a6SDouglas Gregor             return false;
48750996ce1SRichard Smith           if (IsUnavailable(Found))
4881fb5c3a6SDouglas Gregor             return true;
4891fb5c3a6SDouglas Gregor         }
4901fb5c3a6SDouglas Gregor 
4911fb5c3a6SDouglas Gregor         // Infer a submodule with the same name as this header file.
492056396aeSDouglas Gregor         SmallString<32> NameBuf;
493056396aeSDouglas Gregor         StringRef Name = sanitizeFilenameAsIdentifier(
494056396aeSDouglas Gregor                            llvm::sys::path::stem(Header->getName()),
495056396aeSDouglas Gregor                            NameBuf);
4961fb5c3a6SDouglas Gregor         Found = lookupModuleQualified(Name, Found);
4971fb5c3a6SDouglas Gregor         if (!Found)
4981fb5c3a6SDouglas Gregor           return false;
4991fb5c3a6SDouglas Gregor       }
5001fb5c3a6SDouglas Gregor 
50150996ce1SRichard Smith       return IsUnavailable(Found);
5021fb5c3a6SDouglas Gregor     }
5031fb5c3a6SDouglas Gregor 
5041fb5c3a6SDouglas Gregor     SkippedDirs.push_back(Dir);
5051fb5c3a6SDouglas Gregor 
5061fb5c3a6SDouglas Gregor     // Retrieve our parent path.
5071fb5c3a6SDouglas Gregor     DirName = llvm::sys::path::parent_path(DirName);
5081fb5c3a6SDouglas Gregor     if (DirName.empty())
5091fb5c3a6SDouglas Gregor       break;
5101fb5c3a6SDouglas Gregor 
5111fb5c3a6SDouglas Gregor     // Resolve the parent path to a directory entry.
5121f76c4e8SManuel Klimek     Dir = SourceMgr.getFileManager().getDirectory(DirName);
5131fb5c3a6SDouglas Gregor   } while (Dir);
5141fb5c3a6SDouglas Gregor 
5151fb5c3a6SDouglas Gregor   return false;
5161fb5c3a6SDouglas Gregor }
5171fb5c3a6SDouglas Gregor 
518e4412640SArgyrios Kyrtzidis Module *ModuleMap::findModule(StringRef Name) const {
519e4412640SArgyrios Kyrtzidis   llvm::StringMap<Module *>::const_iterator Known = Modules.find(Name);
52088bdfb0eSDouglas Gregor   if (Known != Modules.end())
52188bdfb0eSDouglas Gregor     return Known->getValue();
52288bdfb0eSDouglas Gregor 
523d2d442caSCraig Topper   return nullptr;
52488bdfb0eSDouglas Gregor }
52588bdfb0eSDouglas Gregor 
526e4412640SArgyrios Kyrtzidis Module *ModuleMap::lookupModuleUnqualified(StringRef Name,
527e4412640SArgyrios Kyrtzidis                                            Module *Context) const {
5282b82c2a5SDouglas Gregor   for(; Context; Context = Context->Parent) {
5292b82c2a5SDouglas Gregor     if (Module *Sub = lookupModuleQualified(Name, Context))
5302b82c2a5SDouglas Gregor       return Sub;
5312b82c2a5SDouglas Gregor   }
5322b82c2a5SDouglas Gregor 
5332b82c2a5SDouglas Gregor   return findModule(Name);
5342b82c2a5SDouglas Gregor }
5352b82c2a5SDouglas Gregor 
536e4412640SArgyrios Kyrtzidis Module *ModuleMap::lookupModuleQualified(StringRef Name, Module *Context) const{
5372b82c2a5SDouglas Gregor   if (!Context)
5382b82c2a5SDouglas Gregor     return findModule(Name);
5392b82c2a5SDouglas Gregor 
540eb90e830SDouglas Gregor   return Context->findSubmodule(Name);
5412b82c2a5SDouglas Gregor }
5422b82c2a5SDouglas Gregor 
543de3ef502SDouglas Gregor std::pair<Module *, bool>
5449d6448b1SBen Langmuir ModuleMap::findOrCreateModule(StringRef Name, Module *Parent, bool IsFramework,
54569021974SDouglas Gregor                               bool IsExplicit) {
54669021974SDouglas Gregor   // Try to find an existing module with this name.
547eb90e830SDouglas Gregor   if (Module *Sub = lookupModuleQualified(Name, Parent))
548eb90e830SDouglas Gregor     return std::make_pair(Sub, false);
54969021974SDouglas Gregor 
55069021974SDouglas Gregor   // Create a new module with this name.
5519d6448b1SBen Langmuir   Module *Result = new Module(Name, SourceLocation(), Parent,
552a7e2cc68SRichard Smith                               IsFramework, IsExplicit, NumCreatedModules++);
5536f722b4eSArgyrios Kyrtzidis   if (!Parent) {
5547e82e019SRichard Smith     if (LangOpts.CurrentModule == Name)
5557e82e019SRichard Smith       SourceModule = Result;
55669021974SDouglas Gregor     Modules[Name] = Result;
5576f722b4eSArgyrios Kyrtzidis   }
55869021974SDouglas Gregor   return std::make_pair(Result, true);
55969021974SDouglas Gregor }
56069021974SDouglas Gregor 
56111dfe6feSDouglas Gregor /// \brief For a framework module, infer the framework against which we
56211dfe6feSDouglas Gregor /// should link.
56311dfe6feSDouglas Gregor static void inferFrameworkLink(Module *Mod, const DirectoryEntry *FrameworkDir,
56411dfe6feSDouglas Gregor                                FileManager &FileMgr) {
56511dfe6feSDouglas Gregor   assert(Mod->IsFramework && "Can only infer linking for framework modules");
56611dfe6feSDouglas Gregor   assert(!Mod->isSubFramework() &&
56711dfe6feSDouglas Gregor          "Can only infer linking for top-level frameworks");
56811dfe6feSDouglas Gregor 
56911dfe6feSDouglas Gregor   SmallString<128> LibName;
57011dfe6feSDouglas Gregor   LibName += FrameworkDir->getName();
57111dfe6feSDouglas Gregor   llvm::sys::path::append(LibName, Mod->Name);
5728aaae5a9SJuergen Ributzka 
5738aaae5a9SJuergen Ributzka   // The library name of a framework has more than one possible extension since
5748aaae5a9SJuergen Ributzka   // the introduction of the text-based dynamic library format. We need to check
5758aaae5a9SJuergen Ributzka   // for both before we give up.
5768aaae5a9SJuergen Ributzka   static const char *frameworkExtensions[] = {"", ".tbd"};
5778aaae5a9SJuergen Ributzka   for (const auto *extension : frameworkExtensions) {
5788aaae5a9SJuergen Ributzka     llvm::sys::path::replace_extension(LibName, extension);
57911dfe6feSDouglas Gregor     if (FileMgr.getFile(LibName)) {
58011dfe6feSDouglas Gregor       Mod->LinkLibraries.push_back(Module::LinkLibrary(Mod->Name,
58111dfe6feSDouglas Gregor                                                        /*IsFramework=*/true));
5828aaae5a9SJuergen Ributzka       return;
5838aaae5a9SJuergen Ributzka     }
58411dfe6feSDouglas Gregor   }
58511dfe6feSDouglas Gregor }
58611dfe6feSDouglas Gregor 
587a525400dSBen Langmuir Module *ModuleMap::inferFrameworkModule(const DirectoryEntry *FrameworkDir,
588a525400dSBen Langmuir                                         bool IsSystem, Module *Parent) {
589c1d88ea5SBen Langmuir   Attributes Attrs;
590c1d88ea5SBen Langmuir   Attrs.IsSystem = IsSystem;
591a525400dSBen Langmuir   return inferFrameworkModule(FrameworkDir, Attrs, Parent);
592c1d88ea5SBen Langmuir }
593c1d88ea5SBen Langmuir 
594a525400dSBen Langmuir Module *ModuleMap::inferFrameworkModule(const DirectoryEntry *FrameworkDir,
595c1d88ea5SBen Langmuir                                         Attributes Attrs, Module *Parent) {
596a525400dSBen Langmuir   // Note: as an egregious but useful hack we use the real path here, because
597a525400dSBen Langmuir   // we might be looking at an embedded framework that symlinks out to a
598a525400dSBen Langmuir   // top-level framework, and we need to infer as if we were naming the
599a525400dSBen Langmuir   // top-level framework.
600a525400dSBen Langmuir   StringRef FrameworkDirName =
601a525400dSBen Langmuir       SourceMgr.getFileManager().getCanonicalName(FrameworkDir);
602a525400dSBen Langmuir 
603a525400dSBen Langmuir   // In case this is a case-insensitive filesystem, use the canonical
604a525400dSBen Langmuir   // directory name as the ModuleName, since modules are case-sensitive.
605a525400dSBen Langmuir   // FIXME: we should be able to give a fix-it hint for the correct spelling.
606a525400dSBen Langmuir   SmallString<32> ModuleNameStorage;
607a525400dSBen Langmuir   StringRef ModuleName = sanitizeFilenameAsIdentifier(
608a525400dSBen Langmuir       llvm::sys::path::stem(FrameworkDirName), ModuleNameStorage);
609c1d88ea5SBen Langmuir 
61056c64013SDouglas Gregor   // Check whether we've already found this module.
611e89dbc1dSDouglas Gregor   if (Module *Mod = lookupModuleQualified(ModuleName, Parent))
612e89dbc1dSDouglas Gregor     return Mod;
613e89dbc1dSDouglas Gregor 
6141f76c4e8SManuel Klimek   FileManager &FileMgr = SourceMgr.getFileManager();
61556c64013SDouglas Gregor 
6169194a91dSDouglas Gregor   // If the framework has a parent path from which we're allowed to infer
6179194a91dSDouglas Gregor   // a framework module, do so.
618beee15e7SBen Langmuir   const FileEntry *ModuleMapFile = nullptr;
6199194a91dSDouglas Gregor   if (!Parent) {
6204ddf2221SDouglas Gregor     // Determine whether we're allowed to infer a module map.
6219194a91dSDouglas Gregor     bool canInfer = false;
6224ddf2221SDouglas Gregor     if (llvm::sys::path::has_parent_path(FrameworkDirName)) {
6239194a91dSDouglas Gregor       // Figure out the parent path.
6244ddf2221SDouglas Gregor       StringRef Parent = llvm::sys::path::parent_path(FrameworkDirName);
6259194a91dSDouglas Gregor       if (const DirectoryEntry *ParentDir = FileMgr.getDirectory(Parent)) {
6269194a91dSDouglas Gregor         // Check whether we have already looked into the parent directory
6279194a91dSDouglas Gregor         // for a module map.
628e4412640SArgyrios Kyrtzidis         llvm::DenseMap<const DirectoryEntry *, InferredDirectory>::const_iterator
6299194a91dSDouglas Gregor           inferred = InferredDirectories.find(ParentDir);
6309194a91dSDouglas Gregor         if (inferred == InferredDirectories.end()) {
6319194a91dSDouglas Gregor           // We haven't looked here before. Load a module map, if there is
6329194a91dSDouglas Gregor           // one.
633984e1df7SBen Langmuir           bool IsFrameworkDir = Parent.endswith(".framework");
634984e1df7SBen Langmuir           if (const FileEntry *ModMapFile =
635984e1df7SBen Langmuir                 HeaderInfo.lookupModuleMapFile(ParentDir, IsFrameworkDir)) {
636c1d88ea5SBen Langmuir             parseModuleMapFile(ModMapFile, Attrs.IsSystem, ParentDir);
6379194a91dSDouglas Gregor             inferred = InferredDirectories.find(ParentDir);
6389194a91dSDouglas Gregor           }
6399194a91dSDouglas Gregor 
6409194a91dSDouglas Gregor           if (inferred == InferredDirectories.end())
6419194a91dSDouglas Gregor             inferred = InferredDirectories.insert(
6429194a91dSDouglas Gregor                          std::make_pair(ParentDir, InferredDirectory())).first;
6439194a91dSDouglas Gregor         }
6449194a91dSDouglas Gregor 
6459194a91dSDouglas Gregor         if (inferred->second.InferModules) {
6469194a91dSDouglas Gregor           // We're allowed to infer for this directory, but make sure it's okay
6479194a91dSDouglas Gregor           // to infer this particular module.
6484ddf2221SDouglas Gregor           StringRef Name = llvm::sys::path::stem(FrameworkDirName);
6499194a91dSDouglas Gregor           canInfer = std::find(inferred->second.ExcludedModules.begin(),
6509194a91dSDouglas Gregor                                inferred->second.ExcludedModules.end(),
6519194a91dSDouglas Gregor                                Name) == inferred->second.ExcludedModules.end();
6529194a91dSDouglas Gregor 
653c1d88ea5SBen Langmuir           Attrs.IsSystem |= inferred->second.Attrs.IsSystem;
654c1d88ea5SBen Langmuir           Attrs.IsExternC |= inferred->second.Attrs.IsExternC;
655c1d88ea5SBen Langmuir           Attrs.IsExhaustive |= inferred->second.Attrs.IsExhaustive;
656beee15e7SBen Langmuir           ModuleMapFile = inferred->second.ModuleMapFile;
6579194a91dSDouglas Gregor         }
6589194a91dSDouglas Gregor       }
6599194a91dSDouglas Gregor     }
6609194a91dSDouglas Gregor 
6619194a91dSDouglas Gregor     // If we're not allowed to infer a framework module, don't.
6629194a91dSDouglas Gregor     if (!canInfer)
663d2d442caSCraig Topper       return nullptr;
664beee15e7SBen Langmuir   } else
6659d6448b1SBen Langmuir     ModuleMapFile = getModuleMapFileForUniquing(Parent);
6669194a91dSDouglas Gregor 
6679194a91dSDouglas Gregor 
66856c64013SDouglas Gregor   // Look for an umbrella header.
6692c1dd271SDylan Noblesmith   SmallString<128> UmbrellaName = StringRef(FrameworkDir->getName());
67017381a06SBenjamin Kramer   llvm::sys::path::append(UmbrellaName, "Headers", ModuleName + ".h");
671e89dbc1dSDouglas Gregor   const FileEntry *UmbrellaHeader = FileMgr.getFile(UmbrellaName);
67256c64013SDouglas Gregor 
67356c64013SDouglas Gregor   // FIXME: If there's no umbrella header, we could probably scan the
67456c64013SDouglas Gregor   // framework to load *everything*. But, it's not clear that this is a good
67556c64013SDouglas Gregor   // idea.
67656c64013SDouglas Gregor   if (!UmbrellaHeader)
677d2d442caSCraig Topper     return nullptr;
67856c64013SDouglas Gregor 
6799d6448b1SBen Langmuir   Module *Result = new Module(ModuleName, SourceLocation(), Parent,
680a7e2cc68SRichard Smith                               /*IsFramework=*/true, /*IsExplicit=*/false,
681a7e2cc68SRichard Smith                               NumCreatedModules++);
6829d6448b1SBen Langmuir   InferredModuleAllowedBy[Result] = ModuleMapFile;
6839d6448b1SBen Langmuir   Result->IsInferred = true;
6847e82e019SRichard Smith   if (!Parent) {
6857e82e019SRichard Smith     if (LangOpts.CurrentModule == ModuleName)
686ba7f2f71SDaniel Jasper       SourceModule = Result;
6877e82e019SRichard Smith     Modules[ModuleName] = Result;
688ba7f2f71SDaniel Jasper   }
689c1d88ea5SBen Langmuir 
690c1d88ea5SBen Langmuir   Result->IsSystem |= Attrs.IsSystem;
691c1d88ea5SBen Langmuir   Result->IsExternC |= Attrs.IsExternC;
692c1d88ea5SBen Langmuir   Result->ConfigMacrosExhaustive |= Attrs.IsExhaustive;
6932b63d15fSRichard Smith   Result->Directory = FrameworkDir;
694a686e1b0SDouglas Gregor 
695322f633cSDouglas Gregor   // umbrella header "umbrella-header-name"
6962b63d15fSRichard Smith   //
6972b63d15fSRichard Smith   // The "Headers/" component of the name is implied because this is
6982b63d15fSRichard Smith   // a framework module.
6992b63d15fSRichard Smith   setUmbrellaHeader(Result, UmbrellaHeader, ModuleName + ".h");
700d8bd7537SDouglas Gregor 
701d8bd7537SDouglas Gregor   // export *
702d2d442caSCraig Topper   Result->Exports.push_back(Module::ExportDecl(nullptr, true));
703d8bd7537SDouglas Gregor 
704a89c5ac4SDouglas Gregor   // module * { export * }
705a89c5ac4SDouglas Gregor   Result->InferSubmodules = true;
706a89c5ac4SDouglas Gregor   Result->InferExportWildcard = true;
707a89c5ac4SDouglas Gregor 
708e89dbc1dSDouglas Gregor   // Look for subframeworks.
709c080917eSRafael Espindola   std::error_code EC;
7102c1dd271SDylan Noblesmith   SmallString<128> SubframeworksDirName
711ddaa69cbSDouglas Gregor     = StringRef(FrameworkDir->getName());
712e89dbc1dSDouglas Gregor   llvm::sys::path::append(SubframeworksDirName, "Frameworks");
7132d4d8cb3SBenjamin Kramer   llvm::sys::path::native(SubframeworksDirName);
71492e1b62dSYaron Keren   for (llvm::sys::fs::directory_iterator Dir(SubframeworksDirName, EC), DirEnd;
715e89dbc1dSDouglas Gregor        Dir != DirEnd && !EC; Dir.increment(EC)) {
716e89dbc1dSDouglas Gregor     if (!StringRef(Dir->path()).endswith(".framework"))
717e89dbc1dSDouglas Gregor       continue;
718f2161a70SDouglas Gregor 
719e89dbc1dSDouglas Gregor     if (const DirectoryEntry *SubframeworkDir
720e89dbc1dSDouglas Gregor           = FileMgr.getDirectory(Dir->path())) {
72107c22b78SDouglas Gregor       // Note: as an egregious but useful hack, we use the real path here and
72207c22b78SDouglas Gregor       // check whether it is actually a subdirectory of the parent directory.
72307c22b78SDouglas Gregor       // This will not be the case if the 'subframework' is actually a symlink
72407c22b78SDouglas Gregor       // out to a top-level framework.
725e00c8b20SDouglas Gregor       StringRef SubframeworkDirName = FileMgr.getCanonicalName(SubframeworkDir);
72607c22b78SDouglas Gregor       bool FoundParent = false;
72707c22b78SDouglas Gregor       do {
72807c22b78SDouglas Gregor         // Get the parent directory name.
72907c22b78SDouglas Gregor         SubframeworkDirName
73007c22b78SDouglas Gregor           = llvm::sys::path::parent_path(SubframeworkDirName);
73107c22b78SDouglas Gregor         if (SubframeworkDirName.empty())
73207c22b78SDouglas Gregor           break;
73307c22b78SDouglas Gregor 
73407c22b78SDouglas Gregor         if (FileMgr.getDirectory(SubframeworkDirName) == FrameworkDir) {
73507c22b78SDouglas Gregor           FoundParent = true;
73607c22b78SDouglas Gregor           break;
73707c22b78SDouglas Gregor         }
73807c22b78SDouglas Gregor       } while (true);
73907c22b78SDouglas Gregor 
74007c22b78SDouglas Gregor       if (!FoundParent)
74107c22b78SDouglas Gregor         continue;
74207c22b78SDouglas Gregor 
743e89dbc1dSDouglas Gregor       // FIXME: Do we want to warn about subframeworks without umbrella headers?
744a525400dSBen Langmuir       inferFrameworkModule(SubframeworkDir, Attrs, Result);
745e89dbc1dSDouglas Gregor     }
746e89dbc1dSDouglas Gregor   }
747e89dbc1dSDouglas Gregor 
74811dfe6feSDouglas Gregor   // If the module is a top-level framework, automatically link against the
74911dfe6feSDouglas Gregor   // framework.
75011dfe6feSDouglas Gregor   if (!Result->isSubFramework()) {
75111dfe6feSDouglas Gregor     inferFrameworkLink(Result, FrameworkDir, FileMgr);
75211dfe6feSDouglas Gregor   }
75311dfe6feSDouglas Gregor 
75456c64013SDouglas Gregor   return Result;
75556c64013SDouglas Gregor }
75656c64013SDouglas Gregor 
7572b63d15fSRichard Smith void ModuleMap::setUmbrellaHeader(Module *Mod, const FileEntry *UmbrellaHeader,
7582b63d15fSRichard Smith                                   Twine NameAsWritten) {
75997da9178SDaniel Jasper   Headers[UmbrellaHeader].push_back(KnownHeader(Mod, NormalHeader));
76073141fa9SDouglas Gregor   Mod->Umbrella = UmbrellaHeader;
7612b63d15fSRichard Smith   Mod->UmbrellaAsWritten = NameAsWritten.str();
7627033127bSDouglas Gregor   UmbrellaDirs[UmbrellaHeader->getDir()] = Mod;
763a89c5ac4SDouglas Gregor }
764a89c5ac4SDouglas Gregor 
7652b63d15fSRichard Smith void ModuleMap::setUmbrellaDir(Module *Mod, const DirectoryEntry *UmbrellaDir,
7662b63d15fSRichard Smith                                Twine NameAsWritten) {
767524e33e1SDouglas Gregor   Mod->Umbrella = UmbrellaDir;
7682b63d15fSRichard Smith   Mod->UmbrellaAsWritten = NameAsWritten.str();
769524e33e1SDouglas Gregor   UmbrellaDirs[UmbrellaDir] = Mod;
770524e33e1SDouglas Gregor }
771524e33e1SDouglas Gregor 
7723c1a41adSRichard Smith static Module::HeaderKind headerRoleToKind(ModuleMap::ModuleHeaderRole Role) {
7730e98d938SNAKAMURA Takumi   switch ((int)Role) {
7743c1a41adSRichard Smith   default: llvm_unreachable("unknown header role");
7753c1a41adSRichard Smith   case ModuleMap::NormalHeader:
7763c1a41adSRichard Smith     return Module::HK_Normal;
7773c1a41adSRichard Smith   case ModuleMap::PrivateHeader:
7783c1a41adSRichard Smith     return Module::HK_Private;
7793c1a41adSRichard Smith   case ModuleMap::TextualHeader:
7803c1a41adSRichard Smith     return Module::HK_Textual;
7813c1a41adSRichard Smith   case ModuleMap::PrivateHeader | ModuleMap::TextualHeader:
7823c1a41adSRichard Smith     return Module::HK_PrivateTextual;
7833c1a41adSRichard Smith   }
7840e98d938SNAKAMURA Takumi }
785202210b3SRichard Smith 
7863c1a41adSRichard Smith void ModuleMap::addHeader(Module *Mod, Module::Header Header,
787d8879c85SRichard Smith                           ModuleHeaderRole Role, bool Imported) {
788386bb073SRichard Smith   KnownHeader KH(Mod, Role);
7893c1a41adSRichard Smith 
790386bb073SRichard Smith   // Only add each header to the headers list once.
791386bb073SRichard Smith   // FIXME: Should we diagnose if a header is listed twice in the
792386bb073SRichard Smith   // same module definition?
793386bb073SRichard Smith   auto &HeaderList = Headers[Header.Entry];
794386bb073SRichard Smith   for (auto H : HeaderList)
795386bb073SRichard Smith     if (H == KH)
796386bb073SRichard Smith       return;
797386bb073SRichard Smith 
798386bb073SRichard Smith   HeaderList.push_back(KH);
7993c1a41adSRichard Smith   Mod->Headers[headerRoleToKind(Role)].push_back(std::move(Header));
800386bb073SRichard Smith 
8017e82e019SRichard Smith   bool isCompilingModuleHeader =
8027e82e019SRichard Smith       LangOpts.CompilingModule && Mod->getTopLevelModule() == SourceModule;
803d8879c85SRichard Smith   if (!Imported || isCompilingModuleHeader) {
804d8879c85SRichard Smith     // When we import HeaderFileInfo, the external source is expected to
805d8879c85SRichard Smith     // set the isModuleHeader flag itself.
806d8879c85SRichard Smith     HeaderInfo.MarkFileModuleHeader(Header.Entry, Role,
807d8879c85SRichard Smith                                     isCompilingModuleHeader);
808d8879c85SRichard Smith   }
809e62cfd7cSBruno Cardoso Lopes 
810e62cfd7cSBruno Cardoso Lopes   // Notify callbacks that we just added a new header.
811e62cfd7cSBruno Cardoso Lopes   for (const auto &Cb : Callbacks)
812e62cfd7cSBruno Cardoso Lopes     Cb->moduleMapAddHeader(*Header.Entry);
813a89c5ac4SDouglas Gregor }
814a89c5ac4SDouglas Gregor 
8153c1a41adSRichard Smith void ModuleMap::excludeHeader(Module *Mod, Module::Header Header) {
816feb54b6dSRichard Smith   // Add this as a known header so we won't implicitly add it to any
817feb54b6dSRichard Smith   // umbrella directory module.
818feb54b6dSRichard Smith   // FIXME: Should we only exclude it from umbrella modules within the
819feb54b6dSRichard Smith   // specified module?
8203c1a41adSRichard Smith   (void) Headers[Header.Entry];
8213c1a41adSRichard Smith 
8223c1a41adSRichard Smith   Mod->Headers[Module::HK_Excluded].push_back(std::move(Header));
823feb54b6dSRichard Smith }
824feb54b6dSRichard Smith 
825514b636aSDouglas Gregor const FileEntry *
8264b8a9e95SBen Langmuir ModuleMap::getContainingModuleMapFile(const Module *Module) const {
8271f76c4e8SManuel Klimek   if (Module->DefinitionLoc.isInvalid())
828d2d442caSCraig Topper     return nullptr;
829514b636aSDouglas Gregor 
8301f76c4e8SManuel Klimek   return SourceMgr.getFileEntryForID(
8311f76c4e8SManuel Klimek            SourceMgr.getFileID(Module->DefinitionLoc));
832514b636aSDouglas Gregor }
833514b636aSDouglas Gregor 
8344b8a9e95SBen Langmuir const FileEntry *ModuleMap::getModuleMapFileForUniquing(const Module *M) const {
8359d6448b1SBen Langmuir   if (M->IsInferred) {
8369d6448b1SBen Langmuir     assert(InferredModuleAllowedBy.count(M) && "missing inferred module map");
8379d6448b1SBen Langmuir     return InferredModuleAllowedBy.find(M)->second;
8389d6448b1SBen Langmuir   }
8399d6448b1SBen Langmuir   return getContainingModuleMapFile(M);
8409d6448b1SBen Langmuir }
8419d6448b1SBen Langmuir 
8429d6448b1SBen Langmuir void ModuleMap::setInferredModuleAllowedBy(Module *M, const FileEntry *ModMap) {
8439d6448b1SBen Langmuir   assert(M->IsInferred && "module not inferred");
8449d6448b1SBen Langmuir   InferredModuleAllowedBy[M] = ModMap;
8459d6448b1SBen Langmuir }
8469d6448b1SBen Langmuir 
847cdae941eSYaron Keren LLVM_DUMP_METHOD void ModuleMap::dump() {
848718292f2SDouglas Gregor   llvm::errs() << "Modules:";
849718292f2SDouglas Gregor   for (llvm::StringMap<Module *>::iterator M = Modules.begin(),
850718292f2SDouglas Gregor                                         MEnd = Modules.end();
851718292f2SDouglas Gregor        M != MEnd; ++M)
852d28d1b8dSDouglas Gregor     M->getValue()->print(llvm::errs(), 2);
853718292f2SDouglas Gregor 
854718292f2SDouglas Gregor   llvm::errs() << "Headers:";
85559527666SDouglas Gregor   for (HeadersMap::iterator H = Headers.begin(), HEnd = Headers.end();
856718292f2SDouglas Gregor        H != HEnd; ++H) {
85797da9178SDaniel Jasper     llvm::errs() << "  \"" << H->first->getName() << "\" -> ";
85897da9178SDaniel Jasper     for (SmallVectorImpl<KnownHeader>::const_iterator I = H->second.begin(),
85997da9178SDaniel Jasper                                                       E = H->second.end();
86097da9178SDaniel Jasper          I != E; ++I) {
86197da9178SDaniel Jasper       if (I != H->second.begin())
86297da9178SDaniel Jasper         llvm::errs() << ",";
86397da9178SDaniel Jasper       llvm::errs() << I->getModule()->getFullModuleName();
86497da9178SDaniel Jasper     }
86597da9178SDaniel Jasper     llvm::errs() << "\n";
866718292f2SDouglas Gregor   }
867718292f2SDouglas Gregor }
868718292f2SDouglas Gregor 
8692b82c2a5SDouglas Gregor bool ModuleMap::resolveExports(Module *Mod, bool Complain) {
87042413141SRichard Smith   auto Unresolved = std::move(Mod->UnresolvedExports);
87142413141SRichard Smith   Mod->UnresolvedExports.clear();
87242413141SRichard Smith   for (auto &UE : Unresolved) {
87342413141SRichard Smith     Module::ExportDecl Export = resolveExport(Mod, UE, Complain);
874f5eedd05SDouglas Gregor     if (Export.getPointer() || Export.getInt())
8752b82c2a5SDouglas Gregor       Mod->Exports.push_back(Export);
8762b82c2a5SDouglas Gregor     else
87742413141SRichard Smith       Mod->UnresolvedExports.push_back(UE);
8782b82c2a5SDouglas Gregor   }
87942413141SRichard Smith   return !Mod->UnresolvedExports.empty();
8802b82c2a5SDouglas Gregor }
8812b82c2a5SDouglas Gregor 
882ba7f2f71SDaniel Jasper bool ModuleMap::resolveUses(Module *Mod, bool Complain) {
88342413141SRichard Smith   auto Unresolved = std::move(Mod->UnresolvedDirectUses);
88442413141SRichard Smith   Mod->UnresolvedDirectUses.clear();
88542413141SRichard Smith   for (auto &UDU : Unresolved) {
88642413141SRichard Smith     Module *DirectUse = resolveModuleId(UDU, Mod, Complain);
887ba7f2f71SDaniel Jasper     if (DirectUse)
888ba7f2f71SDaniel Jasper       Mod->DirectUses.push_back(DirectUse);
889ba7f2f71SDaniel Jasper     else
89042413141SRichard Smith       Mod->UnresolvedDirectUses.push_back(UDU);
891ba7f2f71SDaniel Jasper   }
89242413141SRichard Smith   return !Mod->UnresolvedDirectUses.empty();
893ba7f2f71SDaniel Jasper }
894ba7f2f71SDaniel Jasper 
895fb912657SDouglas Gregor bool ModuleMap::resolveConflicts(Module *Mod, bool Complain) {
89642413141SRichard Smith   auto Unresolved = std::move(Mod->UnresolvedConflicts);
89742413141SRichard Smith   Mod->UnresolvedConflicts.clear();
89842413141SRichard Smith   for (auto &UC : Unresolved) {
89942413141SRichard Smith     if (Module *OtherMod = resolveModuleId(UC.Id, Mod, Complain)) {
900fb912657SDouglas Gregor       Module::Conflict Conflict;
901fb912657SDouglas Gregor       Conflict.Other = OtherMod;
90242413141SRichard Smith       Conflict.Message = UC.Message;
903fb912657SDouglas Gregor       Mod->Conflicts.push_back(Conflict);
90442413141SRichard Smith     } else
90542413141SRichard Smith       Mod->UnresolvedConflicts.push_back(UC);
906fb912657SDouglas Gregor   }
90742413141SRichard Smith   return !Mod->UnresolvedConflicts.empty();
908fb912657SDouglas Gregor }
909fb912657SDouglas Gregor 
9100093b3c7SDouglas Gregor Module *ModuleMap::inferModuleFromLocation(FullSourceLoc Loc) {
9110093b3c7SDouglas Gregor   if (Loc.isInvalid())
912d2d442caSCraig Topper     return nullptr;
9130093b3c7SDouglas Gregor 
9140093b3c7SDouglas Gregor   // Use the expansion location to determine which module we're in.
9150093b3c7SDouglas Gregor   FullSourceLoc ExpansionLoc = Loc.getExpansionLoc();
9160093b3c7SDouglas Gregor   if (!ExpansionLoc.isFileID())
917d2d442caSCraig Topper     return nullptr;
9180093b3c7SDouglas Gregor 
9190093b3c7SDouglas Gregor   const SourceManager &SrcMgr = Loc.getManager();
9200093b3c7SDouglas Gregor   FileID ExpansionFileID = ExpansionLoc.getFileID();
921224d8a74SDouglas Gregor 
922224d8a74SDouglas Gregor   while (const FileEntry *ExpansionFile
923224d8a74SDouglas Gregor            = SrcMgr.getFileEntryForID(ExpansionFileID)) {
924224d8a74SDouglas Gregor     // Find the module that owns this header (if any).
925b53e5483SLawrence Crowl     if (Module *Mod = findModuleForHeader(ExpansionFile).getModule())
926224d8a74SDouglas Gregor       return Mod;
927224d8a74SDouglas Gregor 
928224d8a74SDouglas Gregor     // No module owns this header, so look up the inclusion chain to see if
929224d8a74SDouglas Gregor     // any included header has an associated module.
930224d8a74SDouglas Gregor     SourceLocation IncludeLoc = SrcMgr.getIncludeLoc(ExpansionFileID);
931224d8a74SDouglas Gregor     if (IncludeLoc.isInvalid())
932d2d442caSCraig Topper       return nullptr;
9330093b3c7SDouglas Gregor 
934224d8a74SDouglas Gregor     ExpansionFileID = SrcMgr.getFileID(IncludeLoc);
935224d8a74SDouglas Gregor   }
936224d8a74SDouglas Gregor 
937d2d442caSCraig Topper   return nullptr;
9380093b3c7SDouglas Gregor }
9390093b3c7SDouglas Gregor 
940718292f2SDouglas Gregor //----------------------------------------------------------------------------//
941718292f2SDouglas Gregor // Module map file parser
942718292f2SDouglas Gregor //----------------------------------------------------------------------------//
943718292f2SDouglas Gregor 
944718292f2SDouglas Gregor namespace clang {
945718292f2SDouglas Gregor   /// \brief A token in a module map file.
946718292f2SDouglas Gregor   struct MMToken {
947718292f2SDouglas Gregor     enum TokenKind {
9481fb5c3a6SDouglas Gregor       Comma,
94935b13eceSDouglas Gregor       ConfigMacros,
950fb912657SDouglas Gregor       Conflict,
951718292f2SDouglas Gregor       EndOfFile,
952718292f2SDouglas Gregor       HeaderKeyword,
953718292f2SDouglas Gregor       Identifier,
954a3feee2aSRichard Smith       Exclaim,
95559527666SDouglas Gregor       ExcludeKeyword,
956718292f2SDouglas Gregor       ExplicitKeyword,
9572b82c2a5SDouglas Gregor       ExportKeyword,
95897292843SDaniel Jasper       ExternKeyword,
959755b2055SDouglas Gregor       FrameworkKeyword,
9606ddfca91SDouglas Gregor       LinkKeyword,
961718292f2SDouglas Gregor       ModuleKeyword,
9622b82c2a5SDouglas Gregor       Period,
963b53e5483SLawrence Crowl       PrivateKeyword,
964718292f2SDouglas Gregor       UmbrellaKeyword,
965ba7f2f71SDaniel Jasper       UseKeyword,
9661fb5c3a6SDouglas Gregor       RequiresKeyword,
9672b82c2a5SDouglas Gregor       Star,
968718292f2SDouglas Gregor       StringLiteral,
969306d8920SRichard Smith       TextualKeyword,
970718292f2SDouglas Gregor       LBrace,
971a686e1b0SDouglas Gregor       RBrace,
972a686e1b0SDouglas Gregor       LSquare,
973a686e1b0SDouglas Gregor       RSquare
974718292f2SDouglas Gregor     } Kind;
975718292f2SDouglas Gregor 
976718292f2SDouglas Gregor     unsigned Location;
977718292f2SDouglas Gregor     unsigned StringLength;
978718292f2SDouglas Gregor     const char *StringData;
979718292f2SDouglas Gregor 
980718292f2SDouglas Gregor     void clear() {
981718292f2SDouglas Gregor       Kind = EndOfFile;
982718292f2SDouglas Gregor       Location = 0;
983718292f2SDouglas Gregor       StringLength = 0;
984d2d442caSCraig Topper       StringData = nullptr;
985718292f2SDouglas Gregor     }
986718292f2SDouglas Gregor 
987718292f2SDouglas Gregor     bool is(TokenKind K) const { return Kind == K; }
988718292f2SDouglas Gregor 
989718292f2SDouglas Gregor     SourceLocation getLocation() const {
990718292f2SDouglas Gregor       return SourceLocation::getFromRawEncoding(Location);
991718292f2SDouglas Gregor     }
992718292f2SDouglas Gregor 
993718292f2SDouglas Gregor     StringRef getString() const {
994718292f2SDouglas Gregor       return StringRef(StringData, StringLength);
995718292f2SDouglas Gregor     }
996718292f2SDouglas Gregor   };
997718292f2SDouglas Gregor 
998718292f2SDouglas Gregor   class ModuleMapParser {
999718292f2SDouglas Gregor     Lexer &L;
1000718292f2SDouglas Gregor     SourceManager &SourceMgr;
1001bc10b9fbSDouglas Gregor 
1002bc10b9fbSDouglas Gregor     /// \brief Default target information, used only for string literal
1003bc10b9fbSDouglas Gregor     /// parsing.
1004bc10b9fbSDouglas Gregor     const TargetInfo *Target;
1005bc10b9fbSDouglas Gregor 
1006718292f2SDouglas Gregor     DiagnosticsEngine &Diags;
1007718292f2SDouglas Gregor     ModuleMap &Map;
1008718292f2SDouglas Gregor 
1009beee15e7SBen Langmuir     /// \brief The current module map file.
1010beee15e7SBen Langmuir     const FileEntry *ModuleMapFile;
1011beee15e7SBen Langmuir 
10129acb99e3SRichard Smith     /// \brief The directory that file names in this module map file should
10139acb99e3SRichard Smith     /// be resolved relative to.
10145257fc63SDouglas Gregor     const DirectoryEntry *Directory;
10155257fc63SDouglas Gregor 
10163ec6663bSDouglas Gregor     /// \brief The directory containing Clang-supplied headers.
10173ec6663bSDouglas Gregor     const DirectoryEntry *BuiltinIncludeDir;
10183ec6663bSDouglas Gregor 
1019963c5535SDouglas Gregor     /// \brief Whether this module map is in a system header directory.
1020963c5535SDouglas Gregor     bool IsSystem;
1021963c5535SDouglas Gregor 
1022718292f2SDouglas Gregor     /// \brief Whether an error occurred.
1023718292f2SDouglas Gregor     bool HadError;
1024718292f2SDouglas Gregor 
1025718292f2SDouglas Gregor     /// \brief Stores string data for the various string literals referenced
1026718292f2SDouglas Gregor     /// during parsing.
1027718292f2SDouglas Gregor     llvm::BumpPtrAllocator StringData;
1028718292f2SDouglas Gregor 
1029718292f2SDouglas Gregor     /// \brief The current token.
1030718292f2SDouglas Gregor     MMToken Tok;
1031718292f2SDouglas Gregor 
1032718292f2SDouglas Gregor     /// \brief The active module.
1033de3ef502SDouglas Gregor     Module *ActiveModule;
1034718292f2SDouglas Gregor 
10357ff29148SBen Langmuir     /// \brief Whether a module uses the 'requires excluded' hack to mark its
10367ff29148SBen Langmuir     /// contents as 'textual'.
10377ff29148SBen Langmuir     ///
10387ff29148SBen Langmuir     /// On older Darwin SDK versions, 'requires excluded' is used to mark the
10397ff29148SBen Langmuir     /// contents of the Darwin.C.excluded (assert.h) and Tcl.Private modules as
10407ff29148SBen Langmuir     /// non-modular headers.  For backwards compatibility, we continue to
10417ff29148SBen Langmuir     /// support this idiom for just these modules, and map the headers to
10427ff29148SBen Langmuir     /// 'textual' to match the original intent.
10437ff29148SBen Langmuir     llvm::SmallPtrSet<Module *, 2> UsesRequiresExcludedHack;
10447ff29148SBen Langmuir 
1045718292f2SDouglas Gregor     /// \brief Consume the current token and return its location.
1046718292f2SDouglas Gregor     SourceLocation consumeToken();
1047718292f2SDouglas Gregor 
1048718292f2SDouglas Gregor     /// \brief Skip tokens until we reach the a token with the given kind
1049718292f2SDouglas Gregor     /// (or the end of the file).
1050718292f2SDouglas Gregor     void skipUntil(MMToken::TokenKind K);
1051718292f2SDouglas Gregor 
1052f857950dSDmitri Gribenko     typedef SmallVector<std::pair<std::string, SourceLocation>, 2> ModuleId;
1053e7ab3669SDouglas Gregor     bool parseModuleId(ModuleId &Id);
1054718292f2SDouglas Gregor     void parseModuleDecl();
105597292843SDaniel Jasper     void parseExternModuleDecl();
10561fb5c3a6SDouglas Gregor     void parseRequiresDecl();
1057b53e5483SLawrence Crowl     void parseHeaderDecl(clang::MMToken::TokenKind,
1058b53e5483SLawrence Crowl                          SourceLocation LeadingLoc);
1059524e33e1SDouglas Gregor     void parseUmbrellaDirDecl(SourceLocation UmbrellaLoc);
10602b82c2a5SDouglas Gregor     void parseExportDecl();
1061ba7f2f71SDaniel Jasper     void parseUseDecl();
10626ddfca91SDouglas Gregor     void parseLinkDecl();
106335b13eceSDouglas Gregor     void parseConfigMacros();
1064fb912657SDouglas Gregor     void parseConflict();
10659194a91dSDouglas Gregor     void parseInferredModuleDecl(bool Framework, bool Explicit);
1066c1d88ea5SBen Langmuir 
1067c1d88ea5SBen Langmuir     typedef ModuleMap::Attributes Attributes;
10684442605fSBill Wendling     bool parseOptionalAttributes(Attributes &Attrs);
1069718292f2SDouglas Gregor 
1070718292f2SDouglas Gregor   public:
1071718292f2SDouglas Gregor     explicit ModuleMapParser(Lexer &L, SourceManager &SourceMgr,
1072bc10b9fbSDouglas Gregor                              const TargetInfo *Target,
1073718292f2SDouglas Gregor                              DiagnosticsEngine &Diags,
10745257fc63SDouglas Gregor                              ModuleMap &Map,
1075beee15e7SBen Langmuir                              const FileEntry *ModuleMapFile,
10763ec6663bSDouglas Gregor                              const DirectoryEntry *Directory,
1077963c5535SDouglas Gregor                              const DirectoryEntry *BuiltinIncludeDir,
1078963c5535SDouglas Gregor                              bool IsSystem)
1079bc10b9fbSDouglas Gregor       : L(L), SourceMgr(SourceMgr), Target(Target), Diags(Diags), Map(Map),
1080beee15e7SBen Langmuir         ModuleMapFile(ModuleMapFile), Directory(Directory),
1081beee15e7SBen Langmuir         BuiltinIncludeDir(BuiltinIncludeDir), IsSystem(IsSystem),
1082d2d442caSCraig Topper         HadError(false), ActiveModule(nullptr)
1083718292f2SDouglas Gregor     {
1084718292f2SDouglas Gregor       Tok.clear();
1085718292f2SDouglas Gregor       consumeToken();
1086718292f2SDouglas Gregor     }
1087718292f2SDouglas Gregor 
1088718292f2SDouglas Gregor     bool parseModuleMapFile();
1089718292f2SDouglas Gregor   };
1090ab9db510SAlexander Kornienko }
1091718292f2SDouglas Gregor 
1092718292f2SDouglas Gregor SourceLocation ModuleMapParser::consumeToken() {
1093718292f2SDouglas Gregor retry:
1094718292f2SDouglas Gregor   SourceLocation Result = Tok.getLocation();
1095718292f2SDouglas Gregor   Tok.clear();
1096718292f2SDouglas Gregor 
1097718292f2SDouglas Gregor   Token LToken;
1098718292f2SDouglas Gregor   L.LexFromRawLexer(LToken);
1099718292f2SDouglas Gregor   Tok.Location = LToken.getLocation().getRawEncoding();
1100718292f2SDouglas Gregor   switch (LToken.getKind()) {
11012d57cea2SAlp Toker   case tok::raw_identifier: {
11022d57cea2SAlp Toker     StringRef RI = LToken.getRawIdentifier();
11032d57cea2SAlp Toker     Tok.StringData = RI.data();
11042d57cea2SAlp Toker     Tok.StringLength = RI.size();
11052d57cea2SAlp Toker     Tok.Kind = llvm::StringSwitch<MMToken::TokenKind>(RI)
110635b13eceSDouglas Gregor                  .Case("config_macros", MMToken::ConfigMacros)
1107fb912657SDouglas Gregor                  .Case("conflict", MMToken::Conflict)
110859527666SDouglas Gregor                  .Case("exclude", MMToken::ExcludeKeyword)
1109718292f2SDouglas Gregor                  .Case("explicit", MMToken::ExplicitKeyword)
11102b82c2a5SDouglas Gregor                  .Case("export", MMToken::ExportKeyword)
111197292843SDaniel Jasper                  .Case("extern", MMToken::ExternKeyword)
1112755b2055SDouglas Gregor                  .Case("framework", MMToken::FrameworkKeyword)
111335b13eceSDouglas Gregor                  .Case("header", MMToken::HeaderKeyword)
11146ddfca91SDouglas Gregor                  .Case("link", MMToken::LinkKeyword)
1115718292f2SDouglas Gregor                  .Case("module", MMToken::ModuleKeyword)
1116b53e5483SLawrence Crowl                  .Case("private", MMToken::PrivateKeyword)
11171fb5c3a6SDouglas Gregor                  .Case("requires", MMToken::RequiresKeyword)
1118306d8920SRichard Smith                  .Case("textual", MMToken::TextualKeyword)
1119718292f2SDouglas Gregor                  .Case("umbrella", MMToken::UmbrellaKeyword)
1120ba7f2f71SDaniel Jasper                  .Case("use", MMToken::UseKeyword)
1121718292f2SDouglas Gregor                  .Default(MMToken::Identifier);
1122718292f2SDouglas Gregor     break;
11232d57cea2SAlp Toker   }
1124718292f2SDouglas Gregor 
11251fb5c3a6SDouglas Gregor   case tok::comma:
11261fb5c3a6SDouglas Gregor     Tok.Kind = MMToken::Comma;
11271fb5c3a6SDouglas Gregor     break;
11281fb5c3a6SDouglas Gregor 
1129718292f2SDouglas Gregor   case tok::eof:
1130718292f2SDouglas Gregor     Tok.Kind = MMToken::EndOfFile;
1131718292f2SDouglas Gregor     break;
1132718292f2SDouglas Gregor 
1133718292f2SDouglas Gregor   case tok::l_brace:
1134718292f2SDouglas Gregor     Tok.Kind = MMToken::LBrace;
1135718292f2SDouglas Gregor     break;
1136718292f2SDouglas Gregor 
1137a686e1b0SDouglas Gregor   case tok::l_square:
1138a686e1b0SDouglas Gregor     Tok.Kind = MMToken::LSquare;
1139a686e1b0SDouglas Gregor     break;
1140a686e1b0SDouglas Gregor 
11412b82c2a5SDouglas Gregor   case tok::period:
11422b82c2a5SDouglas Gregor     Tok.Kind = MMToken::Period;
11432b82c2a5SDouglas Gregor     break;
11442b82c2a5SDouglas Gregor 
1145718292f2SDouglas Gregor   case tok::r_brace:
1146718292f2SDouglas Gregor     Tok.Kind = MMToken::RBrace;
1147718292f2SDouglas Gregor     break;
1148718292f2SDouglas Gregor 
1149a686e1b0SDouglas Gregor   case tok::r_square:
1150a686e1b0SDouglas Gregor     Tok.Kind = MMToken::RSquare;
1151a686e1b0SDouglas Gregor     break;
1152a686e1b0SDouglas Gregor 
11532b82c2a5SDouglas Gregor   case tok::star:
11542b82c2a5SDouglas Gregor     Tok.Kind = MMToken::Star;
11552b82c2a5SDouglas Gregor     break;
11562b82c2a5SDouglas Gregor 
1157a3feee2aSRichard Smith   case tok::exclaim:
1158a3feee2aSRichard Smith     Tok.Kind = MMToken::Exclaim;
1159a3feee2aSRichard Smith     break;
1160a3feee2aSRichard Smith 
1161718292f2SDouglas Gregor   case tok::string_literal: {
1162d67aea28SRichard Smith     if (LToken.hasUDSuffix()) {
1163d67aea28SRichard Smith       Diags.Report(LToken.getLocation(), diag::err_invalid_string_udl);
1164d67aea28SRichard Smith       HadError = true;
1165d67aea28SRichard Smith       goto retry;
1166d67aea28SRichard Smith     }
1167d67aea28SRichard Smith 
1168718292f2SDouglas Gregor     // Parse the string literal.
1169718292f2SDouglas Gregor     LangOptions LangOpts;
11709d5583efSCraig Topper     StringLiteralParser StringLiteral(LToken, SourceMgr, LangOpts, *Target);
1171718292f2SDouglas Gregor     if (StringLiteral.hadError)
1172718292f2SDouglas Gregor       goto retry;
1173718292f2SDouglas Gregor 
1174718292f2SDouglas Gregor     // Copy the string literal into our string data allocator.
1175718292f2SDouglas Gregor     unsigned Length = StringLiteral.GetStringLength();
1176718292f2SDouglas Gregor     char *Saved = StringData.Allocate<char>(Length + 1);
1177718292f2SDouglas Gregor     memcpy(Saved, StringLiteral.GetString().data(), Length);
1178718292f2SDouglas Gregor     Saved[Length] = 0;
1179718292f2SDouglas Gregor 
1180718292f2SDouglas Gregor     // Form the token.
1181718292f2SDouglas Gregor     Tok.Kind = MMToken::StringLiteral;
1182718292f2SDouglas Gregor     Tok.StringData = Saved;
1183718292f2SDouglas Gregor     Tok.StringLength = Length;
1184718292f2SDouglas Gregor     break;
1185718292f2SDouglas Gregor   }
1186718292f2SDouglas Gregor 
1187718292f2SDouglas Gregor   case tok::comment:
1188718292f2SDouglas Gregor     goto retry;
1189718292f2SDouglas Gregor 
1190718292f2SDouglas Gregor   default:
1191718292f2SDouglas Gregor     Diags.Report(LToken.getLocation(), diag::err_mmap_unknown_token);
1192718292f2SDouglas Gregor     HadError = true;
1193718292f2SDouglas Gregor     goto retry;
1194718292f2SDouglas Gregor   }
1195718292f2SDouglas Gregor 
1196718292f2SDouglas Gregor   return Result;
1197718292f2SDouglas Gregor }
1198718292f2SDouglas Gregor 
1199718292f2SDouglas Gregor void ModuleMapParser::skipUntil(MMToken::TokenKind K) {
1200718292f2SDouglas Gregor   unsigned braceDepth = 0;
1201a686e1b0SDouglas Gregor   unsigned squareDepth = 0;
1202718292f2SDouglas Gregor   do {
1203718292f2SDouglas Gregor     switch (Tok.Kind) {
1204718292f2SDouglas Gregor     case MMToken::EndOfFile:
1205718292f2SDouglas Gregor       return;
1206718292f2SDouglas Gregor 
1207718292f2SDouglas Gregor     case MMToken::LBrace:
1208a686e1b0SDouglas Gregor       if (Tok.is(K) && braceDepth == 0 && squareDepth == 0)
1209718292f2SDouglas Gregor         return;
1210718292f2SDouglas Gregor 
1211718292f2SDouglas Gregor       ++braceDepth;
1212718292f2SDouglas Gregor       break;
1213718292f2SDouglas Gregor 
1214a686e1b0SDouglas Gregor     case MMToken::LSquare:
1215a686e1b0SDouglas Gregor       if (Tok.is(K) && braceDepth == 0 && squareDepth == 0)
1216a686e1b0SDouglas Gregor         return;
1217a686e1b0SDouglas Gregor 
1218a686e1b0SDouglas Gregor       ++squareDepth;
1219a686e1b0SDouglas Gregor       break;
1220a686e1b0SDouglas Gregor 
1221718292f2SDouglas Gregor     case MMToken::RBrace:
1222718292f2SDouglas Gregor       if (braceDepth > 0)
1223718292f2SDouglas Gregor         --braceDepth;
1224718292f2SDouglas Gregor       else if (Tok.is(K))
1225718292f2SDouglas Gregor         return;
1226718292f2SDouglas Gregor       break;
1227718292f2SDouglas Gregor 
1228a686e1b0SDouglas Gregor     case MMToken::RSquare:
1229a686e1b0SDouglas Gregor       if (squareDepth > 0)
1230a686e1b0SDouglas Gregor         --squareDepth;
1231a686e1b0SDouglas Gregor       else if (Tok.is(K))
1232a686e1b0SDouglas Gregor         return;
1233a686e1b0SDouglas Gregor       break;
1234a686e1b0SDouglas Gregor 
1235718292f2SDouglas Gregor     default:
1236a686e1b0SDouglas Gregor       if (braceDepth == 0 && squareDepth == 0 && Tok.is(K))
1237718292f2SDouglas Gregor         return;
1238718292f2SDouglas Gregor       break;
1239718292f2SDouglas Gregor     }
1240718292f2SDouglas Gregor 
1241718292f2SDouglas Gregor    consumeToken();
1242718292f2SDouglas Gregor   } while (true);
1243718292f2SDouglas Gregor }
1244718292f2SDouglas Gregor 
1245e7ab3669SDouglas Gregor /// \brief Parse a module-id.
1246e7ab3669SDouglas Gregor ///
1247e7ab3669SDouglas Gregor ///   module-id:
1248e7ab3669SDouglas Gregor ///     identifier
1249e7ab3669SDouglas Gregor ///     identifier '.' module-id
1250e7ab3669SDouglas Gregor ///
1251e7ab3669SDouglas Gregor /// \returns true if an error occurred, false otherwise.
1252e7ab3669SDouglas Gregor bool ModuleMapParser::parseModuleId(ModuleId &Id) {
1253e7ab3669SDouglas Gregor   Id.clear();
1254e7ab3669SDouglas Gregor   do {
12553cd34c76SDaniel Jasper     if (Tok.is(MMToken::Identifier) || Tok.is(MMToken::StringLiteral)) {
1256e7ab3669SDouglas Gregor       Id.push_back(std::make_pair(Tok.getString(), Tok.getLocation()));
1257e7ab3669SDouglas Gregor       consumeToken();
1258e7ab3669SDouglas Gregor     } else {
1259e7ab3669SDouglas Gregor       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module_name);
1260e7ab3669SDouglas Gregor       return true;
1261e7ab3669SDouglas Gregor     }
1262e7ab3669SDouglas Gregor 
1263e7ab3669SDouglas Gregor     if (!Tok.is(MMToken::Period))
1264e7ab3669SDouglas Gregor       break;
1265e7ab3669SDouglas Gregor 
1266e7ab3669SDouglas Gregor     consumeToken();
1267e7ab3669SDouglas Gregor   } while (true);
1268e7ab3669SDouglas Gregor 
1269e7ab3669SDouglas Gregor   return false;
1270e7ab3669SDouglas Gregor }
1271e7ab3669SDouglas Gregor 
1272a686e1b0SDouglas Gregor namespace {
1273a686e1b0SDouglas Gregor   /// \brief Enumerates the known attributes.
1274a686e1b0SDouglas Gregor   enum AttributeKind {
1275a686e1b0SDouglas Gregor     /// \brief An unknown attribute.
1276a686e1b0SDouglas Gregor     AT_unknown,
1277a686e1b0SDouglas Gregor     /// \brief The 'system' attribute.
127835b13eceSDouglas Gregor     AT_system,
127977944868SRichard Smith     /// \brief The 'extern_c' attribute.
128077944868SRichard Smith     AT_extern_c,
128135b13eceSDouglas Gregor     /// \brief The 'exhaustive' attribute.
128235b13eceSDouglas Gregor     AT_exhaustive
1283a686e1b0SDouglas Gregor   };
1284ab9db510SAlexander Kornienko }
1285a686e1b0SDouglas Gregor 
1286718292f2SDouglas Gregor /// \brief Parse a module declaration.
1287718292f2SDouglas Gregor ///
1288718292f2SDouglas Gregor ///   module-declaration:
128997292843SDaniel Jasper ///     'extern' 'module' module-id string-literal
1290a686e1b0SDouglas Gregor ///     'explicit'[opt] 'framework'[opt] 'module' module-id attributes[opt]
1291a686e1b0SDouglas Gregor ///       { module-member* }
1292a686e1b0SDouglas Gregor ///
1293718292f2SDouglas Gregor ///   module-member:
12941fb5c3a6SDouglas Gregor ///     requires-declaration
1295718292f2SDouglas Gregor ///     header-declaration
1296e7ab3669SDouglas Gregor ///     submodule-declaration
12972b82c2a5SDouglas Gregor ///     export-declaration
12986ddfca91SDouglas Gregor ///     link-declaration
129973441091SDouglas Gregor ///
130073441091SDouglas Gregor ///   submodule-declaration:
130173441091SDouglas Gregor ///     module-declaration
130273441091SDouglas Gregor ///     inferred-submodule-declaration
1303718292f2SDouglas Gregor void ModuleMapParser::parseModuleDecl() {
1304755b2055SDouglas Gregor   assert(Tok.is(MMToken::ExplicitKeyword) || Tok.is(MMToken::ModuleKeyword) ||
130597292843SDaniel Jasper          Tok.is(MMToken::FrameworkKeyword) || Tok.is(MMToken::ExternKeyword));
130697292843SDaniel Jasper   if (Tok.is(MMToken::ExternKeyword)) {
130797292843SDaniel Jasper     parseExternModuleDecl();
130897292843SDaniel Jasper     return;
130997292843SDaniel Jasper   }
131097292843SDaniel Jasper 
1311f2161a70SDouglas Gregor   // Parse 'explicit' or 'framework' keyword, if present.
1312e7ab3669SDouglas Gregor   SourceLocation ExplicitLoc;
1313718292f2SDouglas Gregor   bool Explicit = false;
1314f2161a70SDouglas Gregor   bool Framework = false;
1315755b2055SDouglas Gregor 
1316f2161a70SDouglas Gregor   // Parse 'explicit' keyword, if present.
1317f2161a70SDouglas Gregor   if (Tok.is(MMToken::ExplicitKeyword)) {
1318e7ab3669SDouglas Gregor     ExplicitLoc = consumeToken();
1319f2161a70SDouglas Gregor     Explicit = true;
1320f2161a70SDouglas Gregor   }
1321f2161a70SDouglas Gregor 
1322f2161a70SDouglas Gregor   // Parse 'framework' keyword, if present.
1323755b2055SDouglas Gregor   if (Tok.is(MMToken::FrameworkKeyword)) {
1324755b2055SDouglas Gregor     consumeToken();
1325755b2055SDouglas Gregor     Framework = true;
1326755b2055SDouglas Gregor   }
1327718292f2SDouglas Gregor 
1328718292f2SDouglas Gregor   // Parse 'module' keyword.
1329718292f2SDouglas Gregor   if (!Tok.is(MMToken::ModuleKeyword)) {
1330d6343c99SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module);
1331718292f2SDouglas Gregor     consumeToken();
1332718292f2SDouglas Gregor     HadError = true;
1333718292f2SDouglas Gregor     return;
1334718292f2SDouglas Gregor   }
1335718292f2SDouglas Gregor   consumeToken(); // 'module' keyword
1336718292f2SDouglas Gregor 
133773441091SDouglas Gregor   // If we have a wildcard for the module name, this is an inferred submodule.
133873441091SDouglas Gregor   // Parse it.
133973441091SDouglas Gregor   if (Tok.is(MMToken::Star))
13409194a91dSDouglas Gregor     return parseInferredModuleDecl(Framework, Explicit);
134173441091SDouglas Gregor 
1342718292f2SDouglas Gregor   // Parse the module name.
1343e7ab3669SDouglas Gregor   ModuleId Id;
1344e7ab3669SDouglas Gregor   if (parseModuleId(Id)) {
1345718292f2SDouglas Gregor     HadError = true;
1346718292f2SDouglas Gregor     return;
1347718292f2SDouglas Gregor   }
1348e7ab3669SDouglas Gregor 
1349e7ab3669SDouglas Gregor   if (ActiveModule) {
1350e7ab3669SDouglas Gregor     if (Id.size() > 1) {
1351e7ab3669SDouglas Gregor       Diags.Report(Id.front().second, diag::err_mmap_nested_submodule_id)
1352e7ab3669SDouglas Gregor         << SourceRange(Id.front().second, Id.back().second);
1353e7ab3669SDouglas Gregor 
1354e7ab3669SDouglas Gregor       HadError = true;
1355e7ab3669SDouglas Gregor       return;
1356e7ab3669SDouglas Gregor     }
1357e7ab3669SDouglas Gregor   } else if (Id.size() == 1 && Explicit) {
1358e7ab3669SDouglas Gregor     // Top-level modules can't be explicit.
1359e7ab3669SDouglas Gregor     Diags.Report(ExplicitLoc, diag::err_mmap_explicit_top_level);
1360e7ab3669SDouglas Gregor     Explicit = false;
1361e7ab3669SDouglas Gregor     ExplicitLoc = SourceLocation();
1362e7ab3669SDouglas Gregor     HadError = true;
1363e7ab3669SDouglas Gregor   }
1364e7ab3669SDouglas Gregor 
1365e7ab3669SDouglas Gregor   Module *PreviousActiveModule = ActiveModule;
1366e7ab3669SDouglas Gregor   if (Id.size() > 1) {
1367e7ab3669SDouglas Gregor     // This module map defines a submodule. Go find the module of which it
1368e7ab3669SDouglas Gregor     // is a submodule.
1369d2d442caSCraig Topper     ActiveModule = nullptr;
13704b8a9e95SBen Langmuir     const Module *TopLevelModule = nullptr;
1371e7ab3669SDouglas Gregor     for (unsigned I = 0, N = Id.size() - 1; I != N; ++I) {
1372e7ab3669SDouglas Gregor       if (Module *Next = Map.lookupModuleQualified(Id[I].first, ActiveModule)) {
13734b8a9e95SBen Langmuir         if (I == 0)
13744b8a9e95SBen Langmuir           TopLevelModule = Next;
1375e7ab3669SDouglas Gregor         ActiveModule = Next;
1376e7ab3669SDouglas Gregor         continue;
1377e7ab3669SDouglas Gregor       }
1378e7ab3669SDouglas Gregor 
1379e7ab3669SDouglas Gregor       if (ActiveModule) {
1380e7ab3669SDouglas Gregor         Diags.Report(Id[I].second, diag::err_mmap_missing_module_qualified)
13815b5d21eaSRichard Smith           << Id[I].first
13825b5d21eaSRichard Smith           << ActiveModule->getTopLevelModule()->getFullModuleName();
1383e7ab3669SDouglas Gregor       } else {
1384e7ab3669SDouglas Gregor         Diags.Report(Id[I].second, diag::err_mmap_expected_module_name);
1385e7ab3669SDouglas Gregor       }
1386e7ab3669SDouglas Gregor       HadError = true;
1387e7ab3669SDouglas Gregor       return;
1388e7ab3669SDouglas Gregor     }
13894b8a9e95SBen Langmuir 
13904b8a9e95SBen Langmuir     if (ModuleMapFile != Map.getContainingModuleMapFile(TopLevelModule)) {
13914b8a9e95SBen Langmuir       assert(ModuleMapFile != Map.getModuleMapFileForUniquing(TopLevelModule) &&
13924b8a9e95SBen Langmuir              "submodule defined in same file as 'module *' that allowed its "
13934b8a9e95SBen Langmuir              "top-level module");
13944b8a9e95SBen Langmuir       Map.addAdditionalModuleMapFile(TopLevelModule, ModuleMapFile);
13954b8a9e95SBen Langmuir     }
1396e7ab3669SDouglas Gregor   }
1397e7ab3669SDouglas Gregor 
1398e7ab3669SDouglas Gregor   StringRef ModuleName = Id.back().first;
1399e7ab3669SDouglas Gregor   SourceLocation ModuleNameLoc = Id.back().second;
1400718292f2SDouglas Gregor 
1401a686e1b0SDouglas Gregor   // Parse the optional attribute list.
14024442605fSBill Wendling   Attributes Attrs;
14035d29dee0SDavide Italiano   if (parseOptionalAttributes(Attrs))
14045d29dee0SDavide Italiano     return;
14055d29dee0SDavide Italiano 
1406a686e1b0SDouglas Gregor 
1407718292f2SDouglas Gregor   // Parse the opening brace.
1408718292f2SDouglas Gregor   if (!Tok.is(MMToken::LBrace)) {
1409718292f2SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_lbrace)
1410718292f2SDouglas Gregor       << ModuleName;
1411718292f2SDouglas Gregor     HadError = true;
1412718292f2SDouglas Gregor     return;
1413718292f2SDouglas Gregor   }
1414718292f2SDouglas Gregor   SourceLocation LBraceLoc = consumeToken();
1415718292f2SDouglas Gregor 
1416718292f2SDouglas Gregor   // Determine whether this (sub)module has already been defined.
1417eb90e830SDouglas Gregor   if (Module *Existing = Map.lookupModuleQualified(ModuleName, ActiveModule)) {
1418fcc54a3bSDouglas Gregor     if (Existing->DefinitionLoc.isInvalid() && !ActiveModule) {
1419fcc54a3bSDouglas Gregor       // Skip the module definition.
1420fcc54a3bSDouglas Gregor       skipUntil(MMToken::RBrace);
1421fcc54a3bSDouglas Gregor       if (Tok.is(MMToken::RBrace))
1422fcc54a3bSDouglas Gregor         consumeToken();
1423fcc54a3bSDouglas Gregor       else {
1424fcc54a3bSDouglas Gregor         Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
1425fcc54a3bSDouglas Gregor         Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
1426fcc54a3bSDouglas Gregor         HadError = true;
1427fcc54a3bSDouglas Gregor       }
1428fcc54a3bSDouglas Gregor       return;
1429fcc54a3bSDouglas Gregor     }
1430fcc54a3bSDouglas Gregor 
1431718292f2SDouglas Gregor     Diags.Report(ModuleNameLoc, diag::err_mmap_module_redefinition)
1432718292f2SDouglas Gregor       << ModuleName;
1433eb90e830SDouglas Gregor     Diags.Report(Existing->DefinitionLoc, diag::note_mmap_prev_definition);
1434718292f2SDouglas Gregor 
1435718292f2SDouglas Gregor     // Skip the module definition.
1436718292f2SDouglas Gregor     skipUntil(MMToken::RBrace);
1437718292f2SDouglas Gregor     if (Tok.is(MMToken::RBrace))
1438718292f2SDouglas Gregor       consumeToken();
1439718292f2SDouglas Gregor 
1440718292f2SDouglas Gregor     HadError = true;
1441718292f2SDouglas Gregor     return;
1442718292f2SDouglas Gregor   }
1443718292f2SDouglas Gregor 
1444718292f2SDouglas Gregor   // Start defining this module.
14459d6448b1SBen Langmuir   ActiveModule = Map.findOrCreateModule(ModuleName, ActiveModule, Framework,
14469d6448b1SBen Langmuir                                         Explicit).first;
1447eb90e830SDouglas Gregor   ActiveModule->DefinitionLoc = ModuleNameLoc;
1448963c5535SDouglas Gregor   if (Attrs.IsSystem || IsSystem)
1449a686e1b0SDouglas Gregor     ActiveModule->IsSystem = true;
145077944868SRichard Smith   if (Attrs.IsExternC)
145177944868SRichard Smith     ActiveModule->IsExternC = true;
14523c1a41adSRichard Smith   ActiveModule->Directory = Directory;
1453718292f2SDouglas Gregor 
1454718292f2SDouglas Gregor   bool Done = false;
1455718292f2SDouglas Gregor   do {
1456718292f2SDouglas Gregor     switch (Tok.Kind) {
1457718292f2SDouglas Gregor     case MMToken::EndOfFile:
1458718292f2SDouglas Gregor     case MMToken::RBrace:
1459718292f2SDouglas Gregor       Done = true;
1460718292f2SDouglas Gregor       break;
1461718292f2SDouglas Gregor 
146235b13eceSDouglas Gregor     case MMToken::ConfigMacros:
146335b13eceSDouglas Gregor       parseConfigMacros();
146435b13eceSDouglas Gregor       break;
146535b13eceSDouglas Gregor 
1466fb912657SDouglas Gregor     case MMToken::Conflict:
1467fb912657SDouglas Gregor       parseConflict();
1468fb912657SDouglas Gregor       break;
1469fb912657SDouglas Gregor 
1470718292f2SDouglas Gregor     case MMToken::ExplicitKeyword:
147197292843SDaniel Jasper     case MMToken::ExternKeyword:
1472f2161a70SDouglas Gregor     case MMToken::FrameworkKeyword:
1473718292f2SDouglas Gregor     case MMToken::ModuleKeyword:
1474718292f2SDouglas Gregor       parseModuleDecl();
1475718292f2SDouglas Gregor       break;
1476718292f2SDouglas Gregor 
14772b82c2a5SDouglas Gregor     case MMToken::ExportKeyword:
14782b82c2a5SDouglas Gregor       parseExportDecl();
14792b82c2a5SDouglas Gregor       break;
14802b82c2a5SDouglas Gregor 
1481ba7f2f71SDaniel Jasper     case MMToken::UseKeyword:
1482ba7f2f71SDaniel Jasper       parseUseDecl();
1483ba7f2f71SDaniel Jasper       break;
1484ba7f2f71SDaniel Jasper 
14851fb5c3a6SDouglas Gregor     case MMToken::RequiresKeyword:
14861fb5c3a6SDouglas Gregor       parseRequiresDecl();
14871fb5c3a6SDouglas Gregor       break;
14881fb5c3a6SDouglas Gregor 
1489202210b3SRichard Smith     case MMToken::TextualKeyword:
1490202210b3SRichard Smith       parseHeaderDecl(MMToken::TextualKeyword, consumeToken());
1491306d8920SRichard Smith       break;
1492306d8920SRichard Smith 
1493524e33e1SDouglas Gregor     case MMToken::UmbrellaKeyword: {
1494524e33e1SDouglas Gregor       SourceLocation UmbrellaLoc = consumeToken();
1495524e33e1SDouglas Gregor       if (Tok.is(MMToken::HeaderKeyword))
1496b53e5483SLawrence Crowl         parseHeaderDecl(MMToken::UmbrellaKeyword, UmbrellaLoc);
1497524e33e1SDouglas Gregor       else
1498524e33e1SDouglas Gregor         parseUmbrellaDirDecl(UmbrellaLoc);
1499718292f2SDouglas Gregor       break;
1500524e33e1SDouglas Gregor     }
1501718292f2SDouglas Gregor 
1502202210b3SRichard Smith     case MMToken::ExcludeKeyword:
1503202210b3SRichard Smith       parseHeaderDecl(MMToken::ExcludeKeyword, consumeToken());
150459527666SDouglas Gregor       break;
150559527666SDouglas Gregor 
1506202210b3SRichard Smith     case MMToken::PrivateKeyword:
1507202210b3SRichard Smith       parseHeaderDecl(MMToken::PrivateKeyword, consumeToken());
1508b53e5483SLawrence Crowl       break;
1509b53e5483SLawrence Crowl 
1510322f633cSDouglas Gregor     case MMToken::HeaderKeyword:
1511202210b3SRichard Smith       parseHeaderDecl(MMToken::HeaderKeyword, consumeToken());
1512718292f2SDouglas Gregor       break;
1513718292f2SDouglas Gregor 
15146ddfca91SDouglas Gregor     case MMToken::LinkKeyword:
15156ddfca91SDouglas Gregor       parseLinkDecl();
15166ddfca91SDouglas Gregor       break;
15176ddfca91SDouglas Gregor 
1518718292f2SDouglas Gregor     default:
1519718292f2SDouglas Gregor       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_member);
1520718292f2SDouglas Gregor       consumeToken();
1521718292f2SDouglas Gregor       break;
1522718292f2SDouglas Gregor     }
1523718292f2SDouglas Gregor   } while (!Done);
1524718292f2SDouglas Gregor 
1525718292f2SDouglas Gregor   if (Tok.is(MMToken::RBrace))
1526718292f2SDouglas Gregor     consumeToken();
1527718292f2SDouglas Gregor   else {
1528718292f2SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
1529718292f2SDouglas Gregor     Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
1530718292f2SDouglas Gregor     HadError = true;
1531718292f2SDouglas Gregor   }
1532718292f2SDouglas Gregor 
153311dfe6feSDouglas Gregor   // If the active module is a top-level framework, and there are no link
153411dfe6feSDouglas Gregor   // libraries, automatically link against the framework.
153511dfe6feSDouglas Gregor   if (ActiveModule->IsFramework && !ActiveModule->isSubFramework() &&
153611dfe6feSDouglas Gregor       ActiveModule->LinkLibraries.empty()) {
153711dfe6feSDouglas Gregor     inferFrameworkLink(ActiveModule, Directory, SourceMgr.getFileManager());
153811dfe6feSDouglas Gregor   }
153911dfe6feSDouglas Gregor 
1540ec8c9752SBen Langmuir   // If the module meets all requirements but is still unavailable, mark the
1541ec8c9752SBen Langmuir   // whole tree as unavailable to prevent it from building.
1542ec8c9752SBen Langmuir   if (!ActiveModule->IsAvailable && !ActiveModule->IsMissingRequirement &&
1543ec8c9752SBen Langmuir       ActiveModule->Parent) {
1544ec8c9752SBen Langmuir     ActiveModule->getTopLevelModule()->markUnavailable();
1545ec8c9752SBen Langmuir     ActiveModule->getTopLevelModule()->MissingHeaders.append(
1546ec8c9752SBen Langmuir       ActiveModule->MissingHeaders.begin(), ActiveModule->MissingHeaders.end());
1547ec8c9752SBen Langmuir   }
1548ec8c9752SBen Langmuir 
1549e7ab3669SDouglas Gregor   // We're done parsing this module. Pop back to the previous module.
1550e7ab3669SDouglas Gregor   ActiveModule = PreviousActiveModule;
1551718292f2SDouglas Gregor }
1552718292f2SDouglas Gregor 
155397292843SDaniel Jasper /// \brief Parse an extern module declaration.
155497292843SDaniel Jasper ///
155597292843SDaniel Jasper ///   extern module-declaration:
155697292843SDaniel Jasper ///     'extern' 'module' module-id string-literal
155797292843SDaniel Jasper void ModuleMapParser::parseExternModuleDecl() {
155897292843SDaniel Jasper   assert(Tok.is(MMToken::ExternKeyword));
1559ae6df27eSRichard Smith   SourceLocation ExternLoc = consumeToken(); // 'extern' keyword
156097292843SDaniel Jasper 
156197292843SDaniel Jasper   // Parse 'module' keyword.
156297292843SDaniel Jasper   if (!Tok.is(MMToken::ModuleKeyword)) {
156397292843SDaniel Jasper     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module);
156497292843SDaniel Jasper     consumeToken();
156597292843SDaniel Jasper     HadError = true;
156697292843SDaniel Jasper     return;
156797292843SDaniel Jasper   }
156897292843SDaniel Jasper   consumeToken(); // 'module' keyword
156997292843SDaniel Jasper 
157097292843SDaniel Jasper   // Parse the module name.
157197292843SDaniel Jasper   ModuleId Id;
157297292843SDaniel Jasper   if (parseModuleId(Id)) {
157397292843SDaniel Jasper     HadError = true;
157497292843SDaniel Jasper     return;
157597292843SDaniel Jasper   }
157697292843SDaniel Jasper 
157797292843SDaniel Jasper   // Parse the referenced module map file name.
157897292843SDaniel Jasper   if (!Tok.is(MMToken::StringLiteral)) {
157997292843SDaniel Jasper     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_mmap_file);
158097292843SDaniel Jasper     HadError = true;
158197292843SDaniel Jasper     return;
158297292843SDaniel Jasper   }
158397292843SDaniel Jasper   std::string FileName = Tok.getString();
158497292843SDaniel Jasper   consumeToken(); // filename
158597292843SDaniel Jasper 
158697292843SDaniel Jasper   StringRef FileNameRef = FileName;
158797292843SDaniel Jasper   SmallString<128> ModuleMapFileName;
158897292843SDaniel Jasper   if (llvm::sys::path::is_relative(FileNameRef)) {
158997292843SDaniel Jasper     ModuleMapFileName += Directory->getName();
159097292843SDaniel Jasper     llvm::sys::path::append(ModuleMapFileName, FileName);
159192e1b62dSYaron Keren     FileNameRef = ModuleMapFileName;
159297292843SDaniel Jasper   }
159397292843SDaniel Jasper   if (const FileEntry *File = SourceMgr.getFileManager().getFile(FileNameRef))
15949acb99e3SRichard Smith     Map.parseModuleMapFile(
15959acb99e3SRichard Smith         File, /*IsSystem=*/false,
15969acb99e3SRichard Smith         Map.HeaderInfo.getHeaderSearchOpts().ModuleMapFileHomeIsCwd
15979acb99e3SRichard Smith             ? Directory
1598ae6df27eSRichard Smith             : File->getDir(), ExternLoc);
159997292843SDaniel Jasper }
160097292843SDaniel Jasper 
16017ff29148SBen Langmuir /// Whether to add the requirement \p Feature to the module \p M.
16027ff29148SBen Langmuir ///
16037ff29148SBen Langmuir /// This preserves backwards compatibility for two hacks in the Darwin system
16047ff29148SBen Langmuir /// module map files:
16057ff29148SBen Langmuir ///
16067ff29148SBen Langmuir /// 1. The use of 'requires excluded' to make headers non-modular, which
16077ff29148SBen Langmuir ///    should really be mapped to 'textual' now that we have this feature.  We
16087ff29148SBen Langmuir ///    drop the 'excluded' requirement, and set \p IsRequiresExcludedHack to
16097ff29148SBen Langmuir ///    true.  Later, this bit will be used to map all the headers inside this
16107ff29148SBen Langmuir ///    module to 'textual'.
16117ff29148SBen Langmuir ///
16127ff29148SBen Langmuir ///    This affects Darwin.C.excluded (for assert.h) and Tcl.Private.
16137ff29148SBen Langmuir ///
16147ff29148SBen Langmuir /// 2. Removes a bogus cplusplus requirement from IOKit.avc.  This requirement
16157ff29148SBen Langmuir ///    was never correct and causes issues now that we check it, so drop it.
16167ff29148SBen Langmuir static bool shouldAddRequirement(Module *M, StringRef Feature,
16177ff29148SBen Langmuir                                  bool &IsRequiresExcludedHack) {
16187ff29148SBen Langmuir   static const StringRef DarwinCExcluded[] = {"Darwin", "C", "excluded"};
16197ff29148SBen Langmuir   static const StringRef TclPrivate[] = {"Tcl", "Private"};
16207ff29148SBen Langmuir   static const StringRef IOKitAVC[] = {"IOKit", "avc"};
16217ff29148SBen Langmuir 
16227ff29148SBen Langmuir   if (Feature == "excluded" && (M->fullModuleNameIs(DarwinCExcluded) ||
16237ff29148SBen Langmuir                                 M->fullModuleNameIs(TclPrivate))) {
16247ff29148SBen Langmuir     IsRequiresExcludedHack = true;
16257ff29148SBen Langmuir     return false;
16267ff29148SBen Langmuir   } else if (Feature == "cplusplus" && M->fullModuleNameIs(IOKitAVC)) {
16277ff29148SBen Langmuir     return false;
16287ff29148SBen Langmuir   }
16297ff29148SBen Langmuir 
16307ff29148SBen Langmuir   return true;
16317ff29148SBen Langmuir }
16327ff29148SBen Langmuir 
16331fb5c3a6SDouglas Gregor /// \brief Parse a requires declaration.
16341fb5c3a6SDouglas Gregor ///
16351fb5c3a6SDouglas Gregor ///   requires-declaration:
16361fb5c3a6SDouglas Gregor ///     'requires' feature-list
16371fb5c3a6SDouglas Gregor ///
16381fb5c3a6SDouglas Gregor ///   feature-list:
1639a3feee2aSRichard Smith ///     feature ',' feature-list
1640a3feee2aSRichard Smith ///     feature
1641a3feee2aSRichard Smith ///
1642a3feee2aSRichard Smith ///   feature:
1643a3feee2aSRichard Smith ///     '!'[opt] identifier
16441fb5c3a6SDouglas Gregor void ModuleMapParser::parseRequiresDecl() {
16451fb5c3a6SDouglas Gregor   assert(Tok.is(MMToken::RequiresKeyword));
16461fb5c3a6SDouglas Gregor 
16471fb5c3a6SDouglas Gregor   // Parse 'requires' keyword.
16481fb5c3a6SDouglas Gregor   consumeToken();
16491fb5c3a6SDouglas Gregor 
16501fb5c3a6SDouglas Gregor   // Parse the feature-list.
16511fb5c3a6SDouglas Gregor   do {
1652a3feee2aSRichard Smith     bool RequiredState = true;
1653a3feee2aSRichard Smith     if (Tok.is(MMToken::Exclaim)) {
1654a3feee2aSRichard Smith       RequiredState = false;
1655a3feee2aSRichard Smith       consumeToken();
1656a3feee2aSRichard Smith     }
1657a3feee2aSRichard Smith 
16581fb5c3a6SDouglas Gregor     if (!Tok.is(MMToken::Identifier)) {
16591fb5c3a6SDouglas Gregor       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_feature);
16601fb5c3a6SDouglas Gregor       HadError = true;
16611fb5c3a6SDouglas Gregor       return;
16621fb5c3a6SDouglas Gregor     }
16631fb5c3a6SDouglas Gregor 
16641fb5c3a6SDouglas Gregor     // Consume the feature name.
16651fb5c3a6SDouglas Gregor     std::string Feature = Tok.getString();
16661fb5c3a6SDouglas Gregor     consumeToken();
16671fb5c3a6SDouglas Gregor 
16687ff29148SBen Langmuir     bool IsRequiresExcludedHack = false;
16697ff29148SBen Langmuir     bool ShouldAddRequirement =
16707ff29148SBen Langmuir         shouldAddRequirement(ActiveModule, Feature, IsRequiresExcludedHack);
16717ff29148SBen Langmuir 
16727ff29148SBen Langmuir     if (IsRequiresExcludedHack)
16737ff29148SBen Langmuir       UsesRequiresExcludedHack.insert(ActiveModule);
16747ff29148SBen Langmuir 
16757ff29148SBen Langmuir     if (ShouldAddRequirement) {
16761fb5c3a6SDouglas Gregor       // Add this feature.
16777ff29148SBen Langmuir       ActiveModule->addRequirement(Feature, RequiredState, Map.LangOpts,
16787ff29148SBen Langmuir                                    *Map.Target);
16797ff29148SBen Langmuir     }
16801fb5c3a6SDouglas Gregor 
16811fb5c3a6SDouglas Gregor     if (!Tok.is(MMToken::Comma))
16821fb5c3a6SDouglas Gregor       break;
16831fb5c3a6SDouglas Gregor 
16841fb5c3a6SDouglas Gregor     // Consume the comma.
16851fb5c3a6SDouglas Gregor     consumeToken();
16861fb5c3a6SDouglas Gregor   } while (true);
16871fb5c3a6SDouglas Gregor }
16881fb5c3a6SDouglas Gregor 
1689f2161a70SDouglas Gregor /// \brief Append to \p Paths the set of paths needed to get to the
1690f2161a70SDouglas Gregor /// subframework in which the given module lives.
1691bf8da9d7SBenjamin Kramer static void appendSubframeworkPaths(Module *Mod,
1692f857950dSDmitri Gribenko                                     SmallVectorImpl<char> &Path) {
1693f2161a70SDouglas Gregor   // Collect the framework names from the given module to the top-level module.
1694f857950dSDmitri Gribenko   SmallVector<StringRef, 2> Paths;
1695f2161a70SDouglas Gregor   for (; Mod; Mod = Mod->Parent) {
1696f2161a70SDouglas Gregor     if (Mod->IsFramework)
1697f2161a70SDouglas Gregor       Paths.push_back(Mod->Name);
1698f2161a70SDouglas Gregor   }
1699f2161a70SDouglas Gregor 
1700f2161a70SDouglas Gregor   if (Paths.empty())
1701f2161a70SDouglas Gregor     return;
1702f2161a70SDouglas Gregor 
1703f2161a70SDouglas Gregor   // Add Frameworks/Name.framework for each subframework.
170417381a06SBenjamin Kramer   for (unsigned I = Paths.size() - 1; I != 0; --I)
170517381a06SBenjamin Kramer     llvm::sys::path::append(Path, "Frameworks", Paths[I-1] + ".framework");
1706f2161a70SDouglas Gregor }
1707f2161a70SDouglas Gregor 
1708718292f2SDouglas Gregor /// \brief Parse a header declaration.
1709718292f2SDouglas Gregor ///
1710718292f2SDouglas Gregor ///   header-declaration:
1711306d8920SRichard Smith ///     'textual'[opt] 'header' string-literal
1712202210b3SRichard Smith ///     'private' 'textual'[opt] 'header' string-literal
1713202210b3SRichard Smith ///     'exclude' 'header' string-literal
1714202210b3SRichard Smith ///     'umbrella' 'header' string-literal
1715306d8920SRichard Smith ///
1716306d8920SRichard Smith /// FIXME: Support 'private textual header'.
1717b53e5483SLawrence Crowl void ModuleMapParser::parseHeaderDecl(MMToken::TokenKind LeadingToken,
1718b53e5483SLawrence Crowl                                       SourceLocation LeadingLoc) {
1719202210b3SRichard Smith   // We've already consumed the first token.
1720202210b3SRichard Smith   ModuleMap::ModuleHeaderRole Role = ModuleMap::NormalHeader;
1721202210b3SRichard Smith   if (LeadingToken == MMToken::PrivateKeyword) {
1722202210b3SRichard Smith     Role = ModuleMap::PrivateHeader;
1723202210b3SRichard Smith     // 'private' may optionally be followed by 'textual'.
1724202210b3SRichard Smith     if (Tok.is(MMToken::TextualKeyword)) {
1725202210b3SRichard Smith       LeadingToken = Tok.Kind;
17261871ed3dSBenjamin Kramer       consumeToken();
1727202210b3SRichard Smith     }
1728202210b3SRichard Smith   }
17297ff29148SBen Langmuir 
1730202210b3SRichard Smith   if (LeadingToken == MMToken::TextualKeyword)
1731202210b3SRichard Smith     Role = ModuleMap::ModuleHeaderRole(Role | ModuleMap::TextualHeader);
1732202210b3SRichard Smith 
17337ff29148SBen Langmuir   if (UsesRequiresExcludedHack.count(ActiveModule)) {
17347ff29148SBen Langmuir     // Mark this header 'textual' (see doc comment for
17357ff29148SBen Langmuir     // Module::UsesRequiresExcludedHack).
17367ff29148SBen Langmuir     Role = ModuleMap::ModuleHeaderRole(Role | ModuleMap::TextualHeader);
17377ff29148SBen Langmuir   }
17387ff29148SBen Langmuir 
1739202210b3SRichard Smith   if (LeadingToken != MMToken::HeaderKeyword) {
1740202210b3SRichard Smith     if (!Tok.is(MMToken::HeaderKeyword)) {
1741202210b3SRichard Smith       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
1742202210b3SRichard Smith           << (LeadingToken == MMToken::PrivateKeyword ? "private" :
1743202210b3SRichard Smith               LeadingToken == MMToken::ExcludeKeyword ? "exclude" :
1744202210b3SRichard Smith               LeadingToken == MMToken::TextualKeyword ? "textual" : "umbrella");
1745202210b3SRichard Smith       return;
1746202210b3SRichard Smith     }
1747202210b3SRichard Smith     consumeToken();
1748202210b3SRichard Smith   }
1749718292f2SDouglas Gregor 
1750718292f2SDouglas Gregor   // Parse the header name.
1751718292f2SDouglas Gregor   if (!Tok.is(MMToken::StringLiteral)) {
1752718292f2SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
1753718292f2SDouglas Gregor       << "header";
1754718292f2SDouglas Gregor     HadError = true;
1755718292f2SDouglas Gregor     return;
1756718292f2SDouglas Gregor   }
17573c1a41adSRichard Smith   Module::UnresolvedHeaderDirective Header;
17580761a8a0SDaniel Jasper   Header.FileName = Tok.getString();
17590761a8a0SDaniel Jasper   Header.FileNameLoc = consumeToken();
1760718292f2SDouglas Gregor 
1761524e33e1SDouglas Gregor   // Check whether we already have an umbrella.
1762b53e5483SLawrence Crowl   if (LeadingToken == MMToken::UmbrellaKeyword && ActiveModule->Umbrella) {
17630761a8a0SDaniel Jasper     Diags.Report(Header.FileNameLoc, diag::err_mmap_umbrella_clash)
1764524e33e1SDouglas Gregor       << ActiveModule->getFullModuleName();
1765322f633cSDouglas Gregor     HadError = true;
1766322f633cSDouglas Gregor     return;
1767322f633cSDouglas Gregor   }
1768322f633cSDouglas Gregor 
17695257fc63SDouglas Gregor   // Look for this file.
1770d2d442caSCraig Topper   const FileEntry *File = nullptr;
1771d2d442caSCraig Topper   const FileEntry *BuiltinFile = nullptr;
17723c1a41adSRichard Smith   SmallString<128> RelativePathName;
17730761a8a0SDaniel Jasper   if (llvm::sys::path::is_absolute(Header.FileName)) {
17743c1a41adSRichard Smith     RelativePathName = Header.FileName;
17753c1a41adSRichard Smith     File = SourceMgr.getFileManager().getFile(RelativePathName);
1776e7ab3669SDouglas Gregor   } else {
1777e7ab3669SDouglas Gregor     // Search for the header file within the search directory.
17783c1a41adSRichard Smith     SmallString<128> FullPathName(Directory->getName());
17793c1a41adSRichard Smith     unsigned FullPathLength = FullPathName.size();
1780755b2055SDouglas Gregor 
1781f2161a70SDouglas Gregor     if (ActiveModule->isPartOfFramework()) {
17823c1a41adSRichard Smith       appendSubframeworkPaths(ActiveModule, RelativePathName);
1783755b2055SDouglas Gregor 
1784e7ab3669SDouglas Gregor       // Check whether this file is in the public headers.
17853c1a41adSRichard Smith       llvm::sys::path::append(RelativePathName, "Headers", Header.FileName);
178692e1b62dSYaron Keren       llvm::sys::path::append(FullPathName, RelativePathName);
17873c1a41adSRichard Smith       File = SourceMgr.getFileManager().getFile(FullPathName);
1788e7ab3669SDouglas Gregor 
1789e7ab3669SDouglas Gregor       if (!File) {
1790e7ab3669SDouglas Gregor         // Check whether this file is in the private headers.
17913c1a41adSRichard Smith         // FIXME: Should we retain the subframework paths here?
17923c1a41adSRichard Smith         RelativePathName.clear();
17933c1a41adSRichard Smith         FullPathName.resize(FullPathLength);
17943c1a41adSRichard Smith         llvm::sys::path::append(RelativePathName, "PrivateHeaders",
17953c1a41adSRichard Smith                                 Header.FileName);
179692e1b62dSYaron Keren         llvm::sys::path::append(FullPathName, RelativePathName);
17973c1a41adSRichard Smith         File = SourceMgr.getFileManager().getFile(FullPathName);
1798e7ab3669SDouglas Gregor       }
1799e7ab3669SDouglas Gregor     } else {
1800e7ab3669SDouglas Gregor       // Lookup for normal headers.
18013c1a41adSRichard Smith       llvm::sys::path::append(RelativePathName, Header.FileName);
180292e1b62dSYaron Keren       llvm::sys::path::append(FullPathName, RelativePathName);
18033c1a41adSRichard Smith       File = SourceMgr.getFileManager().getFile(FullPathName);
18043ec6663bSDouglas Gregor 
18053ec6663bSDouglas Gregor       // If this is a system module with a top-level header, this header
18063ec6663bSDouglas Gregor       // may have a counterpart (or replacement) in the set of headers
18073ec6663bSDouglas Gregor       // supplied by Clang. Find that builtin header.
1808b53e5483SLawrence Crowl       if (ActiveModule->IsSystem && LeadingToken != MMToken::UmbrellaKeyword &&
1809b53e5483SLawrence Crowl           BuiltinIncludeDir && BuiltinIncludeDir != Directory &&
18100761a8a0SDaniel Jasper           isBuiltinHeader(Header.FileName)) {
18112c1dd271SDylan Noblesmith         SmallString<128> BuiltinPathName(BuiltinIncludeDir->getName());
18120761a8a0SDaniel Jasper         llvm::sys::path::append(BuiltinPathName, Header.FileName);
18133ec6663bSDouglas Gregor         BuiltinFile = SourceMgr.getFileManager().getFile(BuiltinPathName);
18143ec6663bSDouglas Gregor 
18153ec6663bSDouglas Gregor         // If Clang supplies this header but the underlying system does not,
18163ec6663bSDouglas Gregor         // just silently swap in our builtin version. Otherwise, we'll end
18173ec6663bSDouglas Gregor         // up adding both (later).
181842413141SRichard Smith         //
181942413141SRichard Smith         // For local visibility, entirely replace the system file with our
182042413141SRichard Smith         // one and textually include the system one. We need to pass macros
182142413141SRichard Smith         // from our header to the system one if we #include_next it.
182242413141SRichard Smith         //
182342413141SRichard Smith         // FIXME: Can we do this in all cases?
182442413141SRichard Smith         if (BuiltinFile && (!File || Map.LangOpts.ModulesLocalVisibility)) {
18253ec6663bSDouglas Gregor           File = BuiltinFile;
18263c1a41adSRichard Smith           RelativePathName = BuiltinPathName;
1827d2d442caSCraig Topper           BuiltinFile = nullptr;
18283ec6663bSDouglas Gregor         }
18293ec6663bSDouglas Gregor       }
1830e7ab3669SDouglas Gregor     }
1831e7ab3669SDouglas Gregor   }
18325257fc63SDouglas Gregor 
18335257fc63SDouglas Gregor   // FIXME: We shouldn't be eagerly stat'ing every file named in a module map.
18345257fc63SDouglas Gregor   // Come up with a lazy way to do this.
1835e7ab3669SDouglas Gregor   if (File) {
183697da9178SDaniel Jasper     if (LeadingToken == MMToken::UmbrellaKeyword) {
1837322f633cSDouglas Gregor       const DirectoryEntry *UmbrellaDir = File->getDir();
183859527666SDouglas Gregor       if (Module *UmbrellaModule = Map.UmbrellaDirs[UmbrellaDir]) {
1839b53e5483SLawrence Crowl         Diags.Report(LeadingLoc, diag::err_mmap_umbrella_clash)
184059527666SDouglas Gregor           << UmbrellaModule->getFullModuleName();
1841322f633cSDouglas Gregor         HadError = true;
18425257fc63SDouglas Gregor       } else {
1843322f633cSDouglas Gregor         // Record this umbrella header.
18442b63d15fSRichard Smith         Map.setUmbrellaHeader(ActiveModule, File, RelativePathName.str());
1845322f633cSDouglas Gregor       }
1846feb54b6dSRichard Smith     } else if (LeadingToken == MMToken::ExcludeKeyword) {
18470101b540SHans Wennborg       Module::Header H = {RelativePathName.str(), File};
18480101b540SHans Wennborg       Map.excludeHeader(ActiveModule, H);
1849322f633cSDouglas Gregor     } else {
185025d50758SRichard Smith       // If there is a builtin counterpart to this file, add it now, before
185125d50758SRichard Smith       // the "real" header, so we build the built-in one first when building
185225d50758SRichard Smith       // the module.
18530101b540SHans Wennborg       if (BuiltinFile) {
18543c1a41adSRichard Smith         // FIXME: Taking the name from the FileEntry is unstable and can give
18553c1a41adSRichard Smith         // different results depending on how we've previously named that file
18563c1a41adSRichard Smith         // in this build.
18570101b540SHans Wennborg         Module::Header H = { BuiltinFile->getName(), BuiltinFile };
18580101b540SHans Wennborg         Map.addHeader(ActiveModule, H, Role);
18590101b540SHans Wennborg       }
186025d50758SRichard Smith 
1861202210b3SRichard Smith       // Record this header.
18620101b540SHans Wennborg       Module::Header H = { RelativePathName.str(), File };
18630101b540SHans Wennborg       Map.addHeader(ActiveModule, H, Role);
18645257fc63SDouglas Gregor     }
1865b53e5483SLawrence Crowl   } else if (LeadingToken != MMToken::ExcludeKeyword) {
18664b27a64bSDouglas Gregor     // Ignore excluded header files. They're optional anyway.
18674b27a64bSDouglas Gregor 
18680761a8a0SDaniel Jasper     // If we find a module that has a missing header, we mark this module as
18690761a8a0SDaniel Jasper     // unavailable and store the header directive for displaying diagnostics.
18700761a8a0SDaniel Jasper     Header.IsUmbrella = LeadingToken == MMToken::UmbrellaKeyword;
1871ec8c9752SBen Langmuir     ActiveModule->markUnavailable();
18720761a8a0SDaniel Jasper     ActiveModule->MissingHeaders.push_back(Header);
18735257fc63SDouglas Gregor   }
1874718292f2SDouglas Gregor }
1875718292f2SDouglas Gregor 
187641f81994SBen Langmuir static int compareModuleHeaders(const Module::Header *A,
187741f81994SBen Langmuir                                 const Module::Header *B) {
187841f81994SBen Langmuir   return A->NameAsWritten.compare(B->NameAsWritten);
187941f81994SBen Langmuir }
188041f81994SBen Langmuir 
1881524e33e1SDouglas Gregor /// \brief Parse an umbrella directory declaration.
1882524e33e1SDouglas Gregor ///
1883524e33e1SDouglas Gregor ///   umbrella-dir-declaration:
1884524e33e1SDouglas Gregor ///     umbrella string-literal
1885524e33e1SDouglas Gregor void ModuleMapParser::parseUmbrellaDirDecl(SourceLocation UmbrellaLoc) {
1886524e33e1SDouglas Gregor   // Parse the directory name.
1887524e33e1SDouglas Gregor   if (!Tok.is(MMToken::StringLiteral)) {
1888524e33e1SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
1889524e33e1SDouglas Gregor       << "umbrella";
1890524e33e1SDouglas Gregor     HadError = true;
1891524e33e1SDouglas Gregor     return;
1892524e33e1SDouglas Gregor   }
1893524e33e1SDouglas Gregor 
1894524e33e1SDouglas Gregor   std::string DirName = Tok.getString();
1895524e33e1SDouglas Gregor   SourceLocation DirNameLoc = consumeToken();
1896524e33e1SDouglas Gregor 
1897524e33e1SDouglas Gregor   // Check whether we already have an umbrella.
1898524e33e1SDouglas Gregor   if (ActiveModule->Umbrella) {
1899524e33e1SDouglas Gregor     Diags.Report(DirNameLoc, diag::err_mmap_umbrella_clash)
1900524e33e1SDouglas Gregor       << ActiveModule->getFullModuleName();
1901524e33e1SDouglas Gregor     HadError = true;
1902524e33e1SDouglas Gregor     return;
1903524e33e1SDouglas Gregor   }
1904524e33e1SDouglas Gregor 
1905524e33e1SDouglas Gregor   // Look for this file.
1906d2d442caSCraig Topper   const DirectoryEntry *Dir = nullptr;
1907524e33e1SDouglas Gregor   if (llvm::sys::path::is_absolute(DirName))
1908524e33e1SDouglas Gregor     Dir = SourceMgr.getFileManager().getDirectory(DirName);
1909524e33e1SDouglas Gregor   else {
19102c1dd271SDylan Noblesmith     SmallString<128> PathName;
1911524e33e1SDouglas Gregor     PathName = Directory->getName();
1912524e33e1SDouglas Gregor     llvm::sys::path::append(PathName, DirName);
1913524e33e1SDouglas Gregor     Dir = SourceMgr.getFileManager().getDirectory(PathName);
1914524e33e1SDouglas Gregor   }
1915524e33e1SDouglas Gregor 
1916524e33e1SDouglas Gregor   if (!Dir) {
1917524e33e1SDouglas Gregor     Diags.Report(DirNameLoc, diag::err_mmap_umbrella_dir_not_found)
1918524e33e1SDouglas Gregor       << DirName;
1919524e33e1SDouglas Gregor     HadError = true;
1920524e33e1SDouglas Gregor     return;
1921524e33e1SDouglas Gregor   }
1922524e33e1SDouglas Gregor 
19237ff29148SBen Langmuir   if (UsesRequiresExcludedHack.count(ActiveModule)) {
19247ff29148SBen Langmuir     // Mark this header 'textual' (see doc comment for
19257ff29148SBen Langmuir     // ModuleMapParser::UsesRequiresExcludedHack). Although iterating over the
19267ff29148SBen Langmuir     // directory is relatively expensive, in practice this only applies to the
19277ff29148SBen Langmuir     // uncommonly used Tcl module on Darwin platforms.
19287ff29148SBen Langmuir     std::error_code EC;
19297ff29148SBen Langmuir     SmallVector<Module::Header, 6> Headers;
19307ff29148SBen Langmuir     for (llvm::sys::fs::recursive_directory_iterator I(Dir->getName(), EC), E;
19317ff29148SBen Langmuir          I != E && !EC; I.increment(EC)) {
19327ff29148SBen Langmuir       if (const FileEntry *FE = SourceMgr.getFileManager().getFile(I->path())) {
19337ff29148SBen Langmuir 
19347ff29148SBen Langmuir         Module::Header Header = {I->path(), FE};
19357ff29148SBen Langmuir         Headers.push_back(std::move(Header));
19367ff29148SBen Langmuir       }
19377ff29148SBen Langmuir     }
19387ff29148SBen Langmuir 
19397ff29148SBen Langmuir     // Sort header paths so that the pcm doesn't depend on iteration order.
194041f81994SBen Langmuir     llvm::array_pod_sort(Headers.begin(), Headers.end(), compareModuleHeaders);
194141f81994SBen Langmuir 
19427ff29148SBen Langmuir     for (auto &Header : Headers)
19437ff29148SBen Langmuir       Map.addHeader(ActiveModule, std::move(Header), ModuleMap::TextualHeader);
19447ff29148SBen Langmuir     return;
19457ff29148SBen Langmuir   }
19467ff29148SBen Langmuir 
1947524e33e1SDouglas Gregor   if (Module *OwningModule = Map.UmbrellaDirs[Dir]) {
1948524e33e1SDouglas Gregor     Diags.Report(UmbrellaLoc, diag::err_mmap_umbrella_clash)
1949524e33e1SDouglas Gregor       << OwningModule->getFullModuleName();
1950524e33e1SDouglas Gregor     HadError = true;
1951524e33e1SDouglas Gregor     return;
1952524e33e1SDouglas Gregor   }
1953524e33e1SDouglas Gregor 
1954524e33e1SDouglas Gregor   // Record this umbrella directory.
19552b63d15fSRichard Smith   Map.setUmbrellaDir(ActiveModule, Dir, DirName);
1956524e33e1SDouglas Gregor }
1957524e33e1SDouglas Gregor 
19582b82c2a5SDouglas Gregor /// \brief Parse a module export declaration.
19592b82c2a5SDouglas Gregor ///
19602b82c2a5SDouglas Gregor ///   export-declaration:
19612b82c2a5SDouglas Gregor ///     'export' wildcard-module-id
19622b82c2a5SDouglas Gregor ///
19632b82c2a5SDouglas Gregor ///   wildcard-module-id:
19642b82c2a5SDouglas Gregor ///     identifier
19652b82c2a5SDouglas Gregor ///     '*'
19662b82c2a5SDouglas Gregor ///     identifier '.' wildcard-module-id
19672b82c2a5SDouglas Gregor void ModuleMapParser::parseExportDecl() {
19682b82c2a5SDouglas Gregor   assert(Tok.is(MMToken::ExportKeyword));
19692b82c2a5SDouglas Gregor   SourceLocation ExportLoc = consumeToken();
19702b82c2a5SDouglas Gregor 
19712b82c2a5SDouglas Gregor   // Parse the module-id with an optional wildcard at the end.
19722b82c2a5SDouglas Gregor   ModuleId ParsedModuleId;
19732b82c2a5SDouglas Gregor   bool Wildcard = false;
19742b82c2a5SDouglas Gregor   do {
1975306d8920SRichard Smith     // FIXME: Support string-literal module names here.
19762b82c2a5SDouglas Gregor     if (Tok.is(MMToken::Identifier)) {
19772b82c2a5SDouglas Gregor       ParsedModuleId.push_back(std::make_pair(Tok.getString(),
19782b82c2a5SDouglas Gregor                                               Tok.getLocation()));
19792b82c2a5SDouglas Gregor       consumeToken();
19802b82c2a5SDouglas Gregor 
19812b82c2a5SDouglas Gregor       if (Tok.is(MMToken::Period)) {
19822b82c2a5SDouglas Gregor         consumeToken();
19832b82c2a5SDouglas Gregor         continue;
19842b82c2a5SDouglas Gregor       }
19852b82c2a5SDouglas Gregor 
19862b82c2a5SDouglas Gregor       break;
19872b82c2a5SDouglas Gregor     }
19882b82c2a5SDouglas Gregor 
19892b82c2a5SDouglas Gregor     if(Tok.is(MMToken::Star)) {
19902b82c2a5SDouglas Gregor       Wildcard = true;
1991f5eedd05SDouglas Gregor       consumeToken();
19922b82c2a5SDouglas Gregor       break;
19932b82c2a5SDouglas Gregor     }
19942b82c2a5SDouglas Gregor 
1995ba7f2f71SDaniel Jasper     Diags.Report(Tok.getLocation(), diag::err_mmap_module_id);
19962b82c2a5SDouglas Gregor     HadError = true;
19972b82c2a5SDouglas Gregor     return;
19982b82c2a5SDouglas Gregor   } while (true);
19992b82c2a5SDouglas Gregor 
20002b82c2a5SDouglas Gregor   Module::UnresolvedExportDecl Unresolved = {
20012b82c2a5SDouglas Gregor     ExportLoc, ParsedModuleId, Wildcard
20022b82c2a5SDouglas Gregor   };
20032b82c2a5SDouglas Gregor   ActiveModule->UnresolvedExports.push_back(Unresolved);
20042b82c2a5SDouglas Gregor }
20052b82c2a5SDouglas Gregor 
20068f4d3ff1SRichard Smith /// \brief Parse a module use declaration.
2007ba7f2f71SDaniel Jasper ///
20088f4d3ff1SRichard Smith ///   use-declaration:
20098f4d3ff1SRichard Smith ///     'use' wildcard-module-id
2010ba7f2f71SDaniel Jasper void ModuleMapParser::parseUseDecl() {
2011ba7f2f71SDaniel Jasper   assert(Tok.is(MMToken::UseKeyword));
20128f4d3ff1SRichard Smith   auto KWLoc = consumeToken();
2013ba7f2f71SDaniel Jasper   // Parse the module-id.
2014ba7f2f71SDaniel Jasper   ModuleId ParsedModuleId;
20153cd34c76SDaniel Jasper   parseModuleId(ParsedModuleId);
2016ba7f2f71SDaniel Jasper 
20178f4d3ff1SRichard Smith   if (ActiveModule->Parent)
20188f4d3ff1SRichard Smith     Diags.Report(KWLoc, diag::err_mmap_use_decl_submodule);
20198f4d3ff1SRichard Smith   else
2020ba7f2f71SDaniel Jasper     ActiveModule->UnresolvedDirectUses.push_back(ParsedModuleId);
2021ba7f2f71SDaniel Jasper }
2022ba7f2f71SDaniel Jasper 
20236ddfca91SDouglas Gregor /// \brief Parse a link declaration.
20246ddfca91SDouglas Gregor ///
20256ddfca91SDouglas Gregor ///   module-declaration:
20266ddfca91SDouglas Gregor ///     'link' 'framework'[opt] string-literal
20276ddfca91SDouglas Gregor void ModuleMapParser::parseLinkDecl() {
20286ddfca91SDouglas Gregor   assert(Tok.is(MMToken::LinkKeyword));
20296ddfca91SDouglas Gregor   SourceLocation LinkLoc = consumeToken();
20306ddfca91SDouglas Gregor 
20316ddfca91SDouglas Gregor   // Parse the optional 'framework' keyword.
20326ddfca91SDouglas Gregor   bool IsFramework = false;
20336ddfca91SDouglas Gregor   if (Tok.is(MMToken::FrameworkKeyword)) {
20346ddfca91SDouglas Gregor     consumeToken();
20356ddfca91SDouglas Gregor     IsFramework = true;
20366ddfca91SDouglas Gregor   }
20376ddfca91SDouglas Gregor 
20386ddfca91SDouglas Gregor   // Parse the library name
20396ddfca91SDouglas Gregor   if (!Tok.is(MMToken::StringLiteral)) {
20406ddfca91SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_library_name)
20416ddfca91SDouglas Gregor       << IsFramework << SourceRange(LinkLoc);
20426ddfca91SDouglas Gregor     HadError = true;
20436ddfca91SDouglas Gregor     return;
20446ddfca91SDouglas Gregor   }
20456ddfca91SDouglas Gregor 
20466ddfca91SDouglas Gregor   std::string LibraryName = Tok.getString();
20476ddfca91SDouglas Gregor   consumeToken();
20486ddfca91SDouglas Gregor   ActiveModule->LinkLibraries.push_back(Module::LinkLibrary(LibraryName,
20496ddfca91SDouglas Gregor                                                             IsFramework));
20506ddfca91SDouglas Gregor }
20516ddfca91SDouglas Gregor 
205235b13eceSDouglas Gregor /// \brief Parse a configuration macro declaration.
205335b13eceSDouglas Gregor ///
205435b13eceSDouglas Gregor ///   module-declaration:
205535b13eceSDouglas Gregor ///     'config_macros' attributes[opt] config-macro-list?
205635b13eceSDouglas Gregor ///
205735b13eceSDouglas Gregor ///   config-macro-list:
205835b13eceSDouglas Gregor ///     identifier (',' identifier)?
205935b13eceSDouglas Gregor void ModuleMapParser::parseConfigMacros() {
206035b13eceSDouglas Gregor   assert(Tok.is(MMToken::ConfigMacros));
206135b13eceSDouglas Gregor   SourceLocation ConfigMacrosLoc = consumeToken();
206235b13eceSDouglas Gregor 
206335b13eceSDouglas Gregor   // Only top-level modules can have configuration macros.
206435b13eceSDouglas Gregor   if (ActiveModule->Parent) {
206535b13eceSDouglas Gregor     Diags.Report(ConfigMacrosLoc, diag::err_mmap_config_macro_submodule);
206635b13eceSDouglas Gregor   }
206735b13eceSDouglas Gregor 
206835b13eceSDouglas Gregor   // Parse the optional attributes.
206935b13eceSDouglas Gregor   Attributes Attrs;
20705d29dee0SDavide Italiano   if (parseOptionalAttributes(Attrs))
20715d29dee0SDavide Italiano     return;
20725d29dee0SDavide Italiano 
207335b13eceSDouglas Gregor   if (Attrs.IsExhaustive && !ActiveModule->Parent) {
207435b13eceSDouglas Gregor     ActiveModule->ConfigMacrosExhaustive = true;
207535b13eceSDouglas Gregor   }
207635b13eceSDouglas Gregor 
207735b13eceSDouglas Gregor   // If we don't have an identifier, we're done.
2078306d8920SRichard Smith   // FIXME: Support macros with the same name as a keyword here.
207935b13eceSDouglas Gregor   if (!Tok.is(MMToken::Identifier))
208035b13eceSDouglas Gregor     return;
208135b13eceSDouglas Gregor 
208235b13eceSDouglas Gregor   // Consume the first identifier.
208335b13eceSDouglas Gregor   if (!ActiveModule->Parent) {
208435b13eceSDouglas Gregor     ActiveModule->ConfigMacros.push_back(Tok.getString().str());
208535b13eceSDouglas Gregor   }
208635b13eceSDouglas Gregor   consumeToken();
208735b13eceSDouglas Gregor 
208835b13eceSDouglas Gregor   do {
208935b13eceSDouglas Gregor     // If there's a comma, consume it.
209035b13eceSDouglas Gregor     if (!Tok.is(MMToken::Comma))
209135b13eceSDouglas Gregor       break;
209235b13eceSDouglas Gregor     consumeToken();
209335b13eceSDouglas Gregor 
209435b13eceSDouglas Gregor     // We expect to see a macro name here.
2095306d8920SRichard Smith     // FIXME: Support macros with the same name as a keyword here.
209635b13eceSDouglas Gregor     if (!Tok.is(MMToken::Identifier)) {
209735b13eceSDouglas Gregor       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_config_macro);
209835b13eceSDouglas Gregor       break;
209935b13eceSDouglas Gregor     }
210035b13eceSDouglas Gregor 
210135b13eceSDouglas Gregor     // Consume the macro name.
210235b13eceSDouglas Gregor     if (!ActiveModule->Parent) {
210335b13eceSDouglas Gregor       ActiveModule->ConfigMacros.push_back(Tok.getString().str());
210435b13eceSDouglas Gregor     }
210535b13eceSDouglas Gregor     consumeToken();
210635b13eceSDouglas Gregor   } while (true);
210735b13eceSDouglas Gregor }
210835b13eceSDouglas Gregor 
2109fb912657SDouglas Gregor /// \brief Format a module-id into a string.
2110fb912657SDouglas Gregor static std::string formatModuleId(const ModuleId &Id) {
2111fb912657SDouglas Gregor   std::string result;
2112fb912657SDouglas Gregor   {
2113fb912657SDouglas Gregor     llvm::raw_string_ostream OS(result);
2114fb912657SDouglas Gregor 
2115fb912657SDouglas Gregor     for (unsigned I = 0, N = Id.size(); I != N; ++I) {
2116fb912657SDouglas Gregor       if (I)
2117fb912657SDouglas Gregor         OS << ".";
2118fb912657SDouglas Gregor       OS << Id[I].first;
2119fb912657SDouglas Gregor     }
2120fb912657SDouglas Gregor   }
2121fb912657SDouglas Gregor 
2122fb912657SDouglas Gregor   return result;
2123fb912657SDouglas Gregor }
2124fb912657SDouglas Gregor 
2125fb912657SDouglas Gregor /// \brief Parse a conflict declaration.
2126fb912657SDouglas Gregor ///
2127fb912657SDouglas Gregor ///   module-declaration:
2128fb912657SDouglas Gregor ///     'conflict' module-id ',' string-literal
2129fb912657SDouglas Gregor void ModuleMapParser::parseConflict() {
2130fb912657SDouglas Gregor   assert(Tok.is(MMToken::Conflict));
2131fb912657SDouglas Gregor   SourceLocation ConflictLoc = consumeToken();
2132fb912657SDouglas Gregor   Module::UnresolvedConflict Conflict;
2133fb912657SDouglas Gregor 
2134fb912657SDouglas Gregor   // Parse the module-id.
2135fb912657SDouglas Gregor   if (parseModuleId(Conflict.Id))
2136fb912657SDouglas Gregor     return;
2137fb912657SDouglas Gregor 
2138fb912657SDouglas Gregor   // Parse the ','.
2139fb912657SDouglas Gregor   if (!Tok.is(MMToken::Comma)) {
2140fb912657SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_conflicts_comma)
2141fb912657SDouglas Gregor       << SourceRange(ConflictLoc);
2142fb912657SDouglas Gregor     return;
2143fb912657SDouglas Gregor   }
2144fb912657SDouglas Gregor   consumeToken();
2145fb912657SDouglas Gregor 
2146fb912657SDouglas Gregor   // Parse the message.
2147fb912657SDouglas Gregor   if (!Tok.is(MMToken::StringLiteral)) {
2148fb912657SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_conflicts_message)
2149fb912657SDouglas Gregor       << formatModuleId(Conflict.Id);
2150fb912657SDouglas Gregor     return;
2151fb912657SDouglas Gregor   }
2152fb912657SDouglas Gregor   Conflict.Message = Tok.getString().str();
2153fb912657SDouglas Gregor   consumeToken();
2154fb912657SDouglas Gregor 
2155fb912657SDouglas Gregor   // Add this unresolved conflict.
2156fb912657SDouglas Gregor   ActiveModule->UnresolvedConflicts.push_back(Conflict);
2157fb912657SDouglas Gregor }
2158fb912657SDouglas Gregor 
21596ddfca91SDouglas Gregor /// \brief Parse an inferred module declaration (wildcard modules).
21609194a91dSDouglas Gregor ///
21619194a91dSDouglas Gregor ///   module-declaration:
21629194a91dSDouglas Gregor ///     'explicit'[opt] 'framework'[opt] 'module' * attributes[opt]
21639194a91dSDouglas Gregor ///       { inferred-module-member* }
21649194a91dSDouglas Gregor ///
21659194a91dSDouglas Gregor ///   inferred-module-member:
21669194a91dSDouglas Gregor ///     'export' '*'
21679194a91dSDouglas Gregor ///     'exclude' identifier
21689194a91dSDouglas Gregor void ModuleMapParser::parseInferredModuleDecl(bool Framework, bool Explicit) {
216973441091SDouglas Gregor   assert(Tok.is(MMToken::Star));
217073441091SDouglas Gregor   SourceLocation StarLoc = consumeToken();
217173441091SDouglas Gregor   bool Failed = false;
217273441091SDouglas Gregor 
217373441091SDouglas Gregor   // Inferred modules must be submodules.
21749194a91dSDouglas Gregor   if (!ActiveModule && !Framework) {
217573441091SDouglas Gregor     Diags.Report(StarLoc, diag::err_mmap_top_level_inferred_submodule);
217673441091SDouglas Gregor     Failed = true;
217773441091SDouglas Gregor   }
217873441091SDouglas Gregor 
21799194a91dSDouglas Gregor   if (ActiveModule) {
2180524e33e1SDouglas Gregor     // Inferred modules must have umbrella directories.
21814898cde4SBen Langmuir     if (!Failed && ActiveModule->IsAvailable &&
21824898cde4SBen Langmuir         !ActiveModule->getUmbrellaDir()) {
218373441091SDouglas Gregor       Diags.Report(StarLoc, diag::err_mmap_inferred_no_umbrella);
218473441091SDouglas Gregor       Failed = true;
218573441091SDouglas Gregor     }
218673441091SDouglas Gregor 
218773441091SDouglas Gregor     // Check for redefinition of an inferred module.
2188dd005f69SDouglas Gregor     if (!Failed && ActiveModule->InferSubmodules) {
218973441091SDouglas Gregor       Diags.Report(StarLoc, diag::err_mmap_inferred_redef);
2190dd005f69SDouglas Gregor       if (ActiveModule->InferredSubmoduleLoc.isValid())
2191dd005f69SDouglas Gregor         Diags.Report(ActiveModule->InferredSubmoduleLoc,
219273441091SDouglas Gregor                      diag::note_mmap_prev_definition);
219373441091SDouglas Gregor       Failed = true;
219473441091SDouglas Gregor     }
219573441091SDouglas Gregor 
21969194a91dSDouglas Gregor     // Check for the 'framework' keyword, which is not permitted here.
21979194a91dSDouglas Gregor     if (Framework) {
21989194a91dSDouglas Gregor       Diags.Report(StarLoc, diag::err_mmap_inferred_framework_submodule);
21999194a91dSDouglas Gregor       Framework = false;
22009194a91dSDouglas Gregor     }
22019194a91dSDouglas Gregor   } else if (Explicit) {
22029194a91dSDouglas Gregor     Diags.Report(StarLoc, diag::err_mmap_explicit_inferred_framework);
22039194a91dSDouglas Gregor     Explicit = false;
22049194a91dSDouglas Gregor   }
22059194a91dSDouglas Gregor 
220673441091SDouglas Gregor   // If there were any problems with this inferred submodule, skip its body.
220773441091SDouglas Gregor   if (Failed) {
220873441091SDouglas Gregor     if (Tok.is(MMToken::LBrace)) {
220973441091SDouglas Gregor       consumeToken();
221073441091SDouglas Gregor       skipUntil(MMToken::RBrace);
221173441091SDouglas Gregor       if (Tok.is(MMToken::RBrace))
221273441091SDouglas Gregor         consumeToken();
221373441091SDouglas Gregor     }
221473441091SDouglas Gregor     HadError = true;
221573441091SDouglas Gregor     return;
221673441091SDouglas Gregor   }
221773441091SDouglas Gregor 
22189194a91dSDouglas Gregor   // Parse optional attributes.
22194442605fSBill Wendling   Attributes Attrs;
22205d29dee0SDavide Italiano   if (parseOptionalAttributes(Attrs))
22215d29dee0SDavide Italiano     return;
22229194a91dSDouglas Gregor 
22239194a91dSDouglas Gregor   if (ActiveModule) {
222473441091SDouglas Gregor     // Note that we have an inferred submodule.
2225dd005f69SDouglas Gregor     ActiveModule->InferSubmodules = true;
2226dd005f69SDouglas Gregor     ActiveModule->InferredSubmoduleLoc = StarLoc;
2227dd005f69SDouglas Gregor     ActiveModule->InferExplicitSubmodules = Explicit;
22289194a91dSDouglas Gregor   } else {
22299194a91dSDouglas Gregor     // We'll be inferring framework modules for this directory.
22309194a91dSDouglas Gregor     Map.InferredDirectories[Directory].InferModules = true;
2231c1d88ea5SBen Langmuir     Map.InferredDirectories[Directory].Attrs = Attrs;
2232beee15e7SBen Langmuir     Map.InferredDirectories[Directory].ModuleMapFile = ModuleMapFile;
2233131daca0SRichard Smith     // FIXME: Handle the 'framework' keyword.
22349194a91dSDouglas Gregor   }
223573441091SDouglas Gregor 
223673441091SDouglas Gregor   // Parse the opening brace.
223773441091SDouglas Gregor   if (!Tok.is(MMToken::LBrace)) {
223873441091SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_lbrace_wildcard);
223973441091SDouglas Gregor     HadError = true;
224073441091SDouglas Gregor     return;
224173441091SDouglas Gregor   }
224273441091SDouglas Gregor   SourceLocation LBraceLoc = consumeToken();
224373441091SDouglas Gregor 
224473441091SDouglas Gregor   // Parse the body of the inferred submodule.
224573441091SDouglas Gregor   bool Done = false;
224673441091SDouglas Gregor   do {
224773441091SDouglas Gregor     switch (Tok.Kind) {
224873441091SDouglas Gregor     case MMToken::EndOfFile:
224973441091SDouglas Gregor     case MMToken::RBrace:
225073441091SDouglas Gregor       Done = true;
225173441091SDouglas Gregor       break;
225273441091SDouglas Gregor 
22539194a91dSDouglas Gregor     case MMToken::ExcludeKeyword: {
22549194a91dSDouglas Gregor       if (ActiveModule) {
22559194a91dSDouglas Gregor         Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member)
2256d2d442caSCraig Topper           << (ActiveModule != nullptr);
22579194a91dSDouglas Gregor         consumeToken();
22589194a91dSDouglas Gregor         break;
22599194a91dSDouglas Gregor       }
22609194a91dSDouglas Gregor 
22619194a91dSDouglas Gregor       consumeToken();
2262306d8920SRichard Smith       // FIXME: Support string-literal module names here.
22639194a91dSDouglas Gregor       if (!Tok.is(MMToken::Identifier)) {
22649194a91dSDouglas Gregor         Diags.Report(Tok.getLocation(), diag::err_mmap_missing_exclude_name);
22659194a91dSDouglas Gregor         break;
22669194a91dSDouglas Gregor       }
22679194a91dSDouglas Gregor 
22689194a91dSDouglas Gregor       Map.InferredDirectories[Directory].ExcludedModules
22699194a91dSDouglas Gregor         .push_back(Tok.getString());
22709194a91dSDouglas Gregor       consumeToken();
22719194a91dSDouglas Gregor       break;
22729194a91dSDouglas Gregor     }
22739194a91dSDouglas Gregor 
22749194a91dSDouglas Gregor     case MMToken::ExportKeyword:
22759194a91dSDouglas Gregor       if (!ActiveModule) {
22769194a91dSDouglas Gregor         Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member)
2277d2d442caSCraig Topper           << (ActiveModule != nullptr);
22789194a91dSDouglas Gregor         consumeToken();
22799194a91dSDouglas Gregor         break;
22809194a91dSDouglas Gregor       }
22819194a91dSDouglas Gregor 
228273441091SDouglas Gregor       consumeToken();
228373441091SDouglas Gregor       if (Tok.is(MMToken::Star))
2284dd005f69SDouglas Gregor         ActiveModule->InferExportWildcard = true;
228573441091SDouglas Gregor       else
228673441091SDouglas Gregor         Diags.Report(Tok.getLocation(),
228773441091SDouglas Gregor                      diag::err_mmap_expected_export_wildcard);
228873441091SDouglas Gregor       consumeToken();
228973441091SDouglas Gregor       break;
229073441091SDouglas Gregor 
229173441091SDouglas Gregor     case MMToken::ExplicitKeyword:
229273441091SDouglas Gregor     case MMToken::ModuleKeyword:
229373441091SDouglas Gregor     case MMToken::HeaderKeyword:
2294b53e5483SLawrence Crowl     case MMToken::PrivateKeyword:
229573441091SDouglas Gregor     case MMToken::UmbrellaKeyword:
229673441091SDouglas Gregor     default:
22979194a91dSDouglas Gregor       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member)
2298d2d442caSCraig Topper           << (ActiveModule != nullptr);
229973441091SDouglas Gregor       consumeToken();
230073441091SDouglas Gregor       break;
230173441091SDouglas Gregor     }
230273441091SDouglas Gregor   } while (!Done);
230373441091SDouglas Gregor 
230473441091SDouglas Gregor   if (Tok.is(MMToken::RBrace))
230573441091SDouglas Gregor     consumeToken();
230673441091SDouglas Gregor   else {
230773441091SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
230873441091SDouglas Gregor     Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
230973441091SDouglas Gregor     HadError = true;
231073441091SDouglas Gregor   }
231173441091SDouglas Gregor }
231273441091SDouglas Gregor 
23139194a91dSDouglas Gregor /// \brief Parse optional attributes.
23149194a91dSDouglas Gregor ///
23159194a91dSDouglas Gregor ///   attributes:
23169194a91dSDouglas Gregor ///     attribute attributes
23179194a91dSDouglas Gregor ///     attribute
23189194a91dSDouglas Gregor ///
23199194a91dSDouglas Gregor ///   attribute:
23209194a91dSDouglas Gregor ///     [ identifier ]
23219194a91dSDouglas Gregor ///
23229194a91dSDouglas Gregor /// \param Attrs Will be filled in with the parsed attributes.
23239194a91dSDouglas Gregor ///
23249194a91dSDouglas Gregor /// \returns true if an error occurred, false otherwise.
23254442605fSBill Wendling bool ModuleMapParser::parseOptionalAttributes(Attributes &Attrs) {
23269194a91dSDouglas Gregor   bool HadError = false;
23279194a91dSDouglas Gregor 
23289194a91dSDouglas Gregor   while (Tok.is(MMToken::LSquare)) {
23299194a91dSDouglas Gregor     // Consume the '['.
23309194a91dSDouglas Gregor     SourceLocation LSquareLoc = consumeToken();
23319194a91dSDouglas Gregor 
23329194a91dSDouglas Gregor     // Check whether we have an attribute name here.
23339194a91dSDouglas Gregor     if (!Tok.is(MMToken::Identifier)) {
23349194a91dSDouglas Gregor       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_attribute);
23359194a91dSDouglas Gregor       skipUntil(MMToken::RSquare);
23369194a91dSDouglas Gregor       if (Tok.is(MMToken::RSquare))
23379194a91dSDouglas Gregor         consumeToken();
23389194a91dSDouglas Gregor       HadError = true;
23399194a91dSDouglas Gregor     }
23409194a91dSDouglas Gregor 
23419194a91dSDouglas Gregor     // Decode the attribute name.
23429194a91dSDouglas Gregor     AttributeKind Attribute
23439194a91dSDouglas Gregor       = llvm::StringSwitch<AttributeKind>(Tok.getString())
234435b13eceSDouglas Gregor           .Case("exhaustive", AT_exhaustive)
234577944868SRichard Smith           .Case("extern_c", AT_extern_c)
23469194a91dSDouglas Gregor           .Case("system", AT_system)
23479194a91dSDouglas Gregor           .Default(AT_unknown);
23489194a91dSDouglas Gregor     switch (Attribute) {
23499194a91dSDouglas Gregor     case AT_unknown:
23509194a91dSDouglas Gregor       Diags.Report(Tok.getLocation(), diag::warn_mmap_unknown_attribute)
23519194a91dSDouglas Gregor         << Tok.getString();
23529194a91dSDouglas Gregor       break;
23539194a91dSDouglas Gregor 
23549194a91dSDouglas Gregor     case AT_system:
23559194a91dSDouglas Gregor       Attrs.IsSystem = true;
23569194a91dSDouglas Gregor       break;
235735b13eceSDouglas Gregor 
235877944868SRichard Smith     case AT_extern_c:
235977944868SRichard Smith       Attrs.IsExternC = true;
236077944868SRichard Smith       break;
236177944868SRichard Smith 
236235b13eceSDouglas Gregor     case AT_exhaustive:
236335b13eceSDouglas Gregor       Attrs.IsExhaustive = true;
236435b13eceSDouglas Gregor       break;
23659194a91dSDouglas Gregor     }
23669194a91dSDouglas Gregor     consumeToken();
23679194a91dSDouglas Gregor 
23689194a91dSDouglas Gregor     // Consume the ']'.
23699194a91dSDouglas Gregor     if (!Tok.is(MMToken::RSquare)) {
23709194a91dSDouglas Gregor       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rsquare);
23719194a91dSDouglas Gregor       Diags.Report(LSquareLoc, diag::note_mmap_lsquare_match);
23729194a91dSDouglas Gregor       skipUntil(MMToken::RSquare);
23739194a91dSDouglas Gregor       HadError = true;
23749194a91dSDouglas Gregor     }
23759194a91dSDouglas Gregor 
23769194a91dSDouglas Gregor     if (Tok.is(MMToken::RSquare))
23779194a91dSDouglas Gregor       consumeToken();
23789194a91dSDouglas Gregor   }
23799194a91dSDouglas Gregor 
23809194a91dSDouglas Gregor   return HadError;
23819194a91dSDouglas Gregor }
23829194a91dSDouglas Gregor 
2383718292f2SDouglas Gregor /// \brief Parse a module map file.
2384718292f2SDouglas Gregor ///
2385718292f2SDouglas Gregor ///   module-map-file:
2386718292f2SDouglas Gregor ///     module-declaration*
2387718292f2SDouglas Gregor bool ModuleMapParser::parseModuleMapFile() {
2388718292f2SDouglas Gregor   do {
2389718292f2SDouglas Gregor     switch (Tok.Kind) {
2390718292f2SDouglas Gregor     case MMToken::EndOfFile:
2391718292f2SDouglas Gregor       return HadError;
2392718292f2SDouglas Gregor 
2393e7ab3669SDouglas Gregor     case MMToken::ExplicitKeyword:
239497292843SDaniel Jasper     case MMToken::ExternKeyword:
2395718292f2SDouglas Gregor     case MMToken::ModuleKeyword:
2396755b2055SDouglas Gregor     case MMToken::FrameworkKeyword:
2397718292f2SDouglas Gregor       parseModuleDecl();
2398718292f2SDouglas Gregor       break;
2399718292f2SDouglas Gregor 
24001fb5c3a6SDouglas Gregor     case MMToken::Comma:
240135b13eceSDouglas Gregor     case MMToken::ConfigMacros:
2402fb912657SDouglas Gregor     case MMToken::Conflict:
2403a3feee2aSRichard Smith     case MMToken::Exclaim:
240459527666SDouglas Gregor     case MMToken::ExcludeKeyword:
24052b82c2a5SDouglas Gregor     case MMToken::ExportKeyword:
2406718292f2SDouglas Gregor     case MMToken::HeaderKeyword:
2407718292f2SDouglas Gregor     case MMToken::Identifier:
2408718292f2SDouglas Gregor     case MMToken::LBrace:
24096ddfca91SDouglas Gregor     case MMToken::LinkKeyword:
2410a686e1b0SDouglas Gregor     case MMToken::LSquare:
24112b82c2a5SDouglas Gregor     case MMToken::Period:
2412b53e5483SLawrence Crowl     case MMToken::PrivateKeyword:
2413718292f2SDouglas Gregor     case MMToken::RBrace:
2414a686e1b0SDouglas Gregor     case MMToken::RSquare:
24151fb5c3a6SDouglas Gregor     case MMToken::RequiresKeyword:
24162b82c2a5SDouglas Gregor     case MMToken::Star:
2417718292f2SDouglas Gregor     case MMToken::StringLiteral:
2418b8afebe2SRichard Smith     case MMToken::TextualKeyword:
2419718292f2SDouglas Gregor     case MMToken::UmbrellaKeyword:
2420ba7f2f71SDaniel Jasper     case MMToken::UseKeyword:
2421718292f2SDouglas Gregor       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module);
2422718292f2SDouglas Gregor       HadError = true;
2423718292f2SDouglas Gregor       consumeToken();
2424718292f2SDouglas Gregor       break;
2425718292f2SDouglas Gregor     }
2426718292f2SDouglas Gregor   } while (true);
2427718292f2SDouglas Gregor }
2428718292f2SDouglas Gregor 
24299acb99e3SRichard Smith bool ModuleMap::parseModuleMapFile(const FileEntry *File, bool IsSystem,
2430ae6df27eSRichard Smith                                    const DirectoryEntry *Dir,
2431ae6df27eSRichard Smith                                    SourceLocation ExternModuleLoc) {
24324ddf2221SDouglas Gregor   llvm::DenseMap<const FileEntry *, bool>::iterator Known
24334ddf2221SDouglas Gregor     = ParsedModuleMap.find(File);
24344ddf2221SDouglas Gregor   if (Known != ParsedModuleMap.end())
24354ddf2221SDouglas Gregor     return Known->second;
24364ddf2221SDouglas Gregor 
2437d2d442caSCraig Topper   assert(Target && "Missing target information");
2438cb69b57bSBen Langmuir   auto FileCharacter = IsSystem ? SrcMgr::C_System : SrcMgr::C_User;
2439ae6df27eSRichard Smith   FileID ID = SourceMgr.createFileID(File, ExternModuleLoc, FileCharacter);
24401f76c4e8SManuel Klimek   const llvm::MemoryBuffer *Buffer = SourceMgr.getBuffer(ID);
2441718292f2SDouglas Gregor   if (!Buffer)
24424ddf2221SDouglas Gregor     return ParsedModuleMap[File] = true;
2443718292f2SDouglas Gregor 
2444718292f2SDouglas Gregor   // Parse this module map file.
24451f76c4e8SManuel Klimek   Lexer L(ID, SourceMgr.getBuffer(ID), SourceMgr, MMapLangOpts);
24462a6edb30SRichard Smith   SourceLocation Start = L.getSourceLocation();
2447beee15e7SBen Langmuir   ModuleMapParser Parser(L, SourceMgr, Target, Diags, *this, File, Dir,
2448963c5535SDouglas Gregor                          BuiltinIncludeDir, IsSystem);
2449718292f2SDouglas Gregor   bool Result = Parser.parseModuleMapFile();
24504ddf2221SDouglas Gregor   ParsedModuleMap[File] = Result;
24512a6edb30SRichard Smith 
24522a6edb30SRichard Smith   // Notify callbacks that we parsed it.
24532a6edb30SRichard Smith   for (const auto &Cb : Callbacks)
24542a6edb30SRichard Smith     Cb->moduleMapFileRead(Start, *File, IsSystem);
2455718292f2SDouglas Gregor   return Result;
2456718292f2SDouglas Gregor }
2457