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,
2124eb8393cSRichard Smith                                    ModuleMap::KnownHeader Header) {
21392669ee4SDaniel Jasper #ifndef NDEBUG
2144eb8393cSRichard 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[] = {
2204eb8393cSRichard Smith         &Header.getModule()->Headers[Module::HK_Private],
2214eb8393cSRichard 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();
2274eb8393cSRichard Smith     assert(IsPrivate && "inconsistent headers and roles");
22800bc95ecSRichard Smith   }
22992669ee4SDaniel Jasper #endif
2304eb8393cSRichard 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.
2584eb8393cSRichard 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;
300a67e4d32SManman Ren   } else if (RequestingModule && RequestingModuleIsModuleInterface &&
301a67e4d32SManman Ren              LangOpts.isCompilingModule()) {
302a67e4d32SManman Ren     // Do not diagnose when we are not compiling a module.
30371e1a64fSBen Langmuir     diag::kind DiagID = RequestingModule->getTopLevelModule()->IsFramework ?
30471e1a64fSBen Langmuir         diag::warn_non_modular_include_in_framework_module :
30571e1a64fSBen Langmuir         diag::warn_non_modular_include_in_module;
30671e1a64fSBen Langmuir     Diags.Report(FilenameLoc, DiagID) << RequestingModule->getFullModuleName();
30771e1a64fSBen Langmuir   }
30892669ee4SDaniel Jasper }
30992669ee4SDaniel Jasper 
310ec87a50aSRichard Smith static bool isBetterKnownHeader(const ModuleMap::KnownHeader &New,
311ec87a50aSRichard Smith                                 const ModuleMap::KnownHeader &Old) {
3128b7c0398SSean Silva   // Prefer available modules.
3138b7c0398SSean Silva   if (New.getModule()->isAvailable() && !Old.getModule()->isAvailable())
3148b7c0398SSean Silva     return true;
3158b7c0398SSean Silva 
316ec87a50aSRichard Smith   // Prefer a public header over a private header.
317ec87a50aSRichard Smith   if ((New.getRole() & ModuleMap::PrivateHeader) !=
318ec87a50aSRichard Smith       (Old.getRole() & ModuleMap::PrivateHeader))
319ec87a50aSRichard Smith     return !(New.getRole() & ModuleMap::PrivateHeader);
320ec87a50aSRichard Smith 
321ec87a50aSRichard Smith   // Prefer a non-textual header over a textual header.
322ec87a50aSRichard Smith   if ((New.getRole() & ModuleMap::TextualHeader) !=
323ec87a50aSRichard Smith       (Old.getRole() & ModuleMap::TextualHeader))
324ec87a50aSRichard Smith     return !(New.getRole() & ModuleMap::TextualHeader);
325ec87a50aSRichard Smith 
326ec87a50aSRichard Smith   // Don't have a reason to choose between these. Just keep the first one.
327ec87a50aSRichard Smith   return false;
328ec87a50aSRichard Smith }
329ec87a50aSRichard Smith 
330*ed84df00SBruno Cardoso Lopes ModuleMap::KnownHeader ModuleMap::findModuleForHeader(const FileEntry *File,
331*ed84df00SBruno Cardoso Lopes                                                       bool AllowTextual) {
332306d8920SRichard Smith   auto MakeResult = [&](ModuleMap::KnownHeader R) -> ModuleMap::KnownHeader {
333*ed84df00SBruno Cardoso Lopes     if (!AllowTextual && R.getRole() & ModuleMap::TextualHeader)
334306d8920SRichard Smith       return ModuleMap::KnownHeader();
335306d8920SRichard Smith     return R;
336306d8920SRichard Smith   };
337306d8920SRichard Smith 
3384881e8b2SSean Silva   HeadersMap::iterator Known = findKnownHeader(File);
3391fb5c3a6SDouglas Gregor   if (Known != Headers.end()) {
340202210b3SRichard Smith     ModuleMap::KnownHeader Result;
34197da9178SDaniel Jasper     // Iterate over all modules that 'File' is part of to find the best fit.
3424881e8b2SSean Silva     for (KnownHeader &H : Known->second) {
3437e82e019SRichard Smith       // Prefer a header from the source module over all others.
3447e82e019SRichard Smith       if (H.getModule()->getTopLevelModule() == SourceModule)
3452f633e7cSRichard Smith         return MakeResult(H);
3464881e8b2SSean Silva       if (!Result || isBetterKnownHeader(H, Result))
3474881e8b2SSean Silva         Result = H;
34897da9178SDaniel Jasper     }
349306d8920SRichard Smith     return MakeResult(Result);
3501fb5c3a6SDouglas Gregor   }
351ab0c8a84SDouglas Gregor 
352386bb073SRichard Smith   return MakeResult(findOrCreateModuleForHeaderInUmbrellaDir(File));
353386bb073SRichard Smith }
354386bb073SRichard Smith 
355386bb073SRichard Smith ModuleMap::KnownHeader
356386bb073SRichard Smith ModuleMap::findOrCreateModuleForHeaderInUmbrellaDir(const FileEntry *File) {
357386bb073SRichard Smith   assert(!Headers.count(File) && "already have a module for this header");
358386bb073SRichard Smith 
359f857950dSDmitri Gribenko   SmallVector<const DirectoryEntry *, 2> SkippedDirs;
3604469138eSBen Langmuir   KnownHeader H = findHeaderInUmbrellaDirs(File, SkippedDirs);
3614469138eSBen Langmuir   if (H) {
3624469138eSBen Langmuir     Module *Result = H.getModule();
363930a85ccSDouglas Gregor 
364930a85ccSDouglas Gregor     // Search up the module stack until we find a module with an umbrella
36573141fa9SDouglas Gregor     // directory.
366930a85ccSDouglas Gregor     Module *UmbrellaModule = Result;
36773141fa9SDouglas Gregor     while (!UmbrellaModule->getUmbrellaDir() && UmbrellaModule->Parent)
368930a85ccSDouglas Gregor       UmbrellaModule = UmbrellaModule->Parent;
369930a85ccSDouglas Gregor 
370930a85ccSDouglas Gregor     if (UmbrellaModule->InferSubmodules) {
3719d6448b1SBen Langmuir       const FileEntry *UmbrellaModuleMap =
3729d6448b1SBen Langmuir           getModuleMapFileForUniquing(UmbrellaModule);
3739d6448b1SBen Langmuir 
374a89c5ac4SDouglas Gregor       // Infer submodules for each of the directories we found between
375a89c5ac4SDouglas Gregor       // the directory of the umbrella header and the directory where
376a89c5ac4SDouglas Gregor       // the actual header is located.
3779458f82dSDouglas Gregor       bool Explicit = UmbrellaModule->InferExplicitSubmodules;
3789458f82dSDouglas Gregor 
3797033127bSDouglas Gregor       for (unsigned I = SkippedDirs.size(); I != 0; --I) {
380a89c5ac4SDouglas Gregor         // Find or create the module that corresponds to this directory name.
381056396aeSDouglas Gregor         SmallString<32> NameBuf;
382056396aeSDouglas Gregor         StringRef Name = sanitizeFilenameAsIdentifier(
3834469138eSBen Langmuir             llvm::sys::path::stem(SkippedDirs[I-1]->getName()), NameBuf);
3849d6448b1SBen Langmuir         Result = findOrCreateModule(Name, Result, /*IsFramework=*/false,
3859d6448b1SBen Langmuir                                     Explicit).first;
3869d6448b1SBen Langmuir         InferredModuleAllowedBy[Result] = UmbrellaModuleMap;
387ffbafa2aSBen Langmuir         Result->IsInferred = true;
388a89c5ac4SDouglas Gregor 
389a89c5ac4SDouglas Gregor         // Associate the module and the directory.
390a89c5ac4SDouglas Gregor         UmbrellaDirs[SkippedDirs[I-1]] = Result;
391a89c5ac4SDouglas Gregor 
392a89c5ac4SDouglas Gregor         // If inferred submodules export everything they import, add a
393a89c5ac4SDouglas Gregor         // wildcard to the set of exports.
394930a85ccSDouglas Gregor         if (UmbrellaModule->InferExportWildcard && Result->Exports.empty())
395d2d442caSCraig Topper           Result->Exports.push_back(Module::ExportDecl(nullptr, true));
396a89c5ac4SDouglas Gregor       }
397a89c5ac4SDouglas Gregor 
398a89c5ac4SDouglas Gregor       // Infer a submodule with the same name as this header file.
399056396aeSDouglas Gregor       SmallString<32> NameBuf;
400056396aeSDouglas Gregor       StringRef Name = sanitizeFilenameAsIdentifier(
401056396aeSDouglas Gregor                          llvm::sys::path::stem(File->getName()), NameBuf);
4029d6448b1SBen Langmuir       Result = findOrCreateModule(Name, Result, /*IsFramework=*/false,
4039d6448b1SBen Langmuir                                   Explicit).first;
4049d6448b1SBen Langmuir       InferredModuleAllowedBy[Result] = UmbrellaModuleMap;
405ffbafa2aSBen Langmuir       Result->IsInferred = true;
4063c5305c1SArgyrios Kyrtzidis       Result->addTopHeader(File);
407a89c5ac4SDouglas Gregor 
408a89c5ac4SDouglas Gregor       // If inferred submodules export everything they import, add a
409a89c5ac4SDouglas Gregor       // wildcard to the set of exports.
410930a85ccSDouglas Gregor       if (UmbrellaModule->InferExportWildcard && Result->Exports.empty())
411d2d442caSCraig Topper         Result->Exports.push_back(Module::ExportDecl(nullptr, true));
412a89c5ac4SDouglas Gregor     } else {
413a89c5ac4SDouglas Gregor       // Record each of the directories we stepped through as being part of
414a89c5ac4SDouglas Gregor       // the module we found, since the umbrella header covers them all.
415a89c5ac4SDouglas Gregor       for (unsigned I = 0, N = SkippedDirs.size(); I != N; ++I)
416a89c5ac4SDouglas Gregor         UmbrellaDirs[SkippedDirs[I]] = Result;
417a89c5ac4SDouglas Gregor     }
418a89c5ac4SDouglas Gregor 
419386bb073SRichard Smith     KnownHeader Header(Result, NormalHeader);
420386bb073SRichard Smith     Headers[File].push_back(Header);
421386bb073SRichard Smith     return Header;
422a89c5ac4SDouglas Gregor   }
423a89c5ac4SDouglas Gregor 
424b53e5483SLawrence Crowl   return KnownHeader();
425ab0c8a84SDouglas Gregor }
426ab0c8a84SDouglas Gregor 
427386bb073SRichard Smith ArrayRef<ModuleMap::KnownHeader>
428386bb073SRichard Smith ModuleMap::findAllModulesForHeader(const FileEntry *File) const {
429386bb073SRichard Smith   auto It = Headers.find(File);
430386bb073SRichard Smith   if (It == Headers.end())
431386bb073SRichard Smith     return None;
432386bb073SRichard Smith   return It->second;
433386bb073SRichard Smith }
434386bb073SRichard Smith 
435e4412640SArgyrios Kyrtzidis bool ModuleMap::isHeaderInUnavailableModule(const FileEntry *Header) const {
436d2d442caSCraig Topper   return isHeaderUnavailableInModule(Header, nullptr);
43750996ce1SRichard Smith }
43850996ce1SRichard Smith 
43962bcd925SDmitri Gribenko bool
44062bcd925SDmitri Gribenko ModuleMap::isHeaderUnavailableInModule(const FileEntry *Header,
44162bcd925SDmitri Gribenko                                        const Module *RequestingModule) const {
442e4412640SArgyrios Kyrtzidis   HeadersMap::const_iterator Known = Headers.find(Header);
44397da9178SDaniel Jasper   if (Known != Headers.end()) {
44497da9178SDaniel Jasper     for (SmallVectorImpl<KnownHeader>::const_iterator
44597da9178SDaniel Jasper              I = Known->second.begin(),
44697da9178SDaniel Jasper              E = Known->second.end();
44797da9178SDaniel Jasper          I != E; ++I) {
44850996ce1SRichard Smith       if (I->isAvailable() && (!RequestingModule ||
44950996ce1SRichard Smith                                I->getModule()->isSubModuleOf(RequestingModule)))
45097da9178SDaniel Jasper         return false;
45197da9178SDaniel Jasper     }
45297da9178SDaniel Jasper     return true;
45397da9178SDaniel Jasper   }
4541fb5c3a6SDouglas Gregor 
4551fb5c3a6SDouglas Gregor   const DirectoryEntry *Dir = Header->getDir();
456f857950dSDmitri Gribenko   SmallVector<const DirectoryEntry *, 2> SkippedDirs;
4571fb5c3a6SDouglas Gregor   StringRef DirName = Dir->getName();
4581fb5c3a6SDouglas Gregor 
45950996ce1SRichard Smith   auto IsUnavailable = [&](const Module *M) {
46050996ce1SRichard Smith     return !M->isAvailable() && (!RequestingModule ||
46150996ce1SRichard Smith                                  M->isSubModuleOf(RequestingModule));
46250996ce1SRichard Smith   };
46350996ce1SRichard Smith 
4641fb5c3a6SDouglas Gregor   // Keep walking up the directory hierarchy, looking for a directory with
4651fb5c3a6SDouglas Gregor   // an umbrella header.
4661fb5c3a6SDouglas Gregor   do {
467e4412640SArgyrios Kyrtzidis     llvm::DenseMap<const DirectoryEntry *, Module *>::const_iterator KnownDir
4681fb5c3a6SDouglas Gregor       = UmbrellaDirs.find(Dir);
4691fb5c3a6SDouglas Gregor     if (KnownDir != UmbrellaDirs.end()) {
4701fb5c3a6SDouglas Gregor       Module *Found = KnownDir->second;
47150996ce1SRichard Smith       if (IsUnavailable(Found))
4721fb5c3a6SDouglas Gregor         return true;
4731fb5c3a6SDouglas Gregor 
4741fb5c3a6SDouglas Gregor       // Search up the module stack until we find a module with an umbrella
4751fb5c3a6SDouglas Gregor       // directory.
4761fb5c3a6SDouglas Gregor       Module *UmbrellaModule = Found;
4771fb5c3a6SDouglas Gregor       while (!UmbrellaModule->getUmbrellaDir() && UmbrellaModule->Parent)
4781fb5c3a6SDouglas Gregor         UmbrellaModule = UmbrellaModule->Parent;
4791fb5c3a6SDouglas Gregor 
4801fb5c3a6SDouglas Gregor       if (UmbrellaModule->InferSubmodules) {
4811fb5c3a6SDouglas Gregor         for (unsigned I = SkippedDirs.size(); I != 0; --I) {
4821fb5c3a6SDouglas Gregor           // Find or create the module that corresponds to this directory name.
483056396aeSDouglas Gregor           SmallString<32> NameBuf;
484056396aeSDouglas Gregor           StringRef Name = sanitizeFilenameAsIdentifier(
485056396aeSDouglas Gregor                              llvm::sys::path::stem(SkippedDirs[I-1]->getName()),
486056396aeSDouglas Gregor                              NameBuf);
4871fb5c3a6SDouglas Gregor           Found = lookupModuleQualified(Name, Found);
4881fb5c3a6SDouglas Gregor           if (!Found)
4891fb5c3a6SDouglas Gregor             return false;
49050996ce1SRichard Smith           if (IsUnavailable(Found))
4911fb5c3a6SDouglas Gregor             return true;
4921fb5c3a6SDouglas Gregor         }
4931fb5c3a6SDouglas Gregor 
4941fb5c3a6SDouglas Gregor         // Infer a submodule with the same name as this header file.
495056396aeSDouglas Gregor         SmallString<32> NameBuf;
496056396aeSDouglas Gregor         StringRef Name = sanitizeFilenameAsIdentifier(
497056396aeSDouglas Gregor                            llvm::sys::path::stem(Header->getName()),
498056396aeSDouglas Gregor                            NameBuf);
4991fb5c3a6SDouglas Gregor         Found = lookupModuleQualified(Name, Found);
5001fb5c3a6SDouglas Gregor         if (!Found)
5011fb5c3a6SDouglas Gregor           return false;
5021fb5c3a6SDouglas Gregor       }
5031fb5c3a6SDouglas Gregor 
50450996ce1SRichard Smith       return IsUnavailable(Found);
5051fb5c3a6SDouglas Gregor     }
5061fb5c3a6SDouglas Gregor 
5071fb5c3a6SDouglas Gregor     SkippedDirs.push_back(Dir);
5081fb5c3a6SDouglas Gregor 
5091fb5c3a6SDouglas Gregor     // Retrieve our parent path.
5101fb5c3a6SDouglas Gregor     DirName = llvm::sys::path::parent_path(DirName);
5111fb5c3a6SDouglas Gregor     if (DirName.empty())
5121fb5c3a6SDouglas Gregor       break;
5131fb5c3a6SDouglas Gregor 
5141fb5c3a6SDouglas Gregor     // Resolve the parent path to a directory entry.
5151f76c4e8SManuel Klimek     Dir = SourceMgr.getFileManager().getDirectory(DirName);
5161fb5c3a6SDouglas Gregor   } while (Dir);
5171fb5c3a6SDouglas Gregor 
5181fb5c3a6SDouglas Gregor   return false;
5191fb5c3a6SDouglas Gregor }
5201fb5c3a6SDouglas Gregor 
521e4412640SArgyrios Kyrtzidis Module *ModuleMap::findModule(StringRef Name) const {
522e4412640SArgyrios Kyrtzidis   llvm::StringMap<Module *>::const_iterator Known = Modules.find(Name);
52388bdfb0eSDouglas Gregor   if (Known != Modules.end())
52488bdfb0eSDouglas Gregor     return Known->getValue();
52588bdfb0eSDouglas Gregor 
526d2d442caSCraig Topper   return nullptr;
52788bdfb0eSDouglas Gregor }
52888bdfb0eSDouglas Gregor 
529e4412640SArgyrios Kyrtzidis Module *ModuleMap::lookupModuleUnqualified(StringRef Name,
530e4412640SArgyrios Kyrtzidis                                            Module *Context) const {
5312b82c2a5SDouglas Gregor   for(; Context; Context = Context->Parent) {
5322b82c2a5SDouglas Gregor     if (Module *Sub = lookupModuleQualified(Name, Context))
5332b82c2a5SDouglas Gregor       return Sub;
5342b82c2a5SDouglas Gregor   }
5352b82c2a5SDouglas Gregor 
5362b82c2a5SDouglas Gregor   return findModule(Name);
5372b82c2a5SDouglas Gregor }
5382b82c2a5SDouglas Gregor 
539e4412640SArgyrios Kyrtzidis Module *ModuleMap::lookupModuleQualified(StringRef Name, Module *Context) const{
5402b82c2a5SDouglas Gregor   if (!Context)
5412b82c2a5SDouglas Gregor     return findModule(Name);
5422b82c2a5SDouglas Gregor 
543eb90e830SDouglas Gregor   return Context->findSubmodule(Name);
5442b82c2a5SDouglas Gregor }
5452b82c2a5SDouglas Gregor 
546de3ef502SDouglas Gregor std::pair<Module *, bool>
5479d6448b1SBen Langmuir ModuleMap::findOrCreateModule(StringRef Name, Module *Parent, bool IsFramework,
54869021974SDouglas Gregor                               bool IsExplicit) {
54969021974SDouglas Gregor   // Try to find an existing module with this name.
550eb90e830SDouglas Gregor   if (Module *Sub = lookupModuleQualified(Name, Parent))
551eb90e830SDouglas Gregor     return std::make_pair(Sub, false);
55269021974SDouglas Gregor 
55369021974SDouglas Gregor   // Create a new module with this name.
5549d6448b1SBen Langmuir   Module *Result = new Module(Name, SourceLocation(), Parent,
555a7e2cc68SRichard Smith                               IsFramework, IsExplicit, NumCreatedModules++);
5566f722b4eSArgyrios Kyrtzidis   if (!Parent) {
5577e82e019SRichard Smith     if (LangOpts.CurrentModule == Name)
5587e82e019SRichard Smith       SourceModule = Result;
55969021974SDouglas Gregor     Modules[Name] = Result;
5606f722b4eSArgyrios Kyrtzidis   }
56169021974SDouglas Gregor   return std::make_pair(Result, true);
56269021974SDouglas Gregor }
56369021974SDouglas Gregor 
564bbcc9f04SRichard Smith Module *ModuleMap::createModuleForInterfaceUnit(SourceLocation Loc,
565bbcc9f04SRichard Smith                                                 StringRef Name) {
566bbcc9f04SRichard Smith   assert(LangOpts.CurrentModule == Name && "module name mismatch");
567bbcc9f04SRichard Smith   assert(!Modules[Name] && "redefining existing module");
568bbcc9f04SRichard Smith 
569bbcc9f04SRichard Smith   auto *Result =
570bbcc9f04SRichard Smith       new Module(Name, Loc, nullptr, /*IsFramework*/ false,
571bbcc9f04SRichard Smith                  /*IsExplicit*/ false, NumCreatedModules++);
572bbcc9f04SRichard Smith   Modules[Name] = SourceModule = Result;
573bbcc9f04SRichard Smith 
574bbcc9f04SRichard Smith   // Mark the main source file as being within the newly-created module so that
575bbcc9f04SRichard Smith   // declarations and macros are properly visibility-restricted to it.
576bbcc9f04SRichard Smith   auto *MainFile = SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
577bbcc9f04SRichard Smith   assert(MainFile && "no input file for module interface");
578bbcc9f04SRichard Smith   Headers[MainFile].push_back(KnownHeader(Result, PrivateHeader));
579bbcc9f04SRichard Smith 
580bbcc9f04SRichard Smith   return Result;
581bbcc9f04SRichard Smith }
582bbcc9f04SRichard Smith 
58311dfe6feSDouglas Gregor /// \brief For a framework module, infer the framework against which we
58411dfe6feSDouglas Gregor /// should link.
58511dfe6feSDouglas Gregor static void inferFrameworkLink(Module *Mod, const DirectoryEntry *FrameworkDir,
58611dfe6feSDouglas Gregor                                FileManager &FileMgr) {
58711dfe6feSDouglas Gregor   assert(Mod->IsFramework && "Can only infer linking for framework modules");
58811dfe6feSDouglas Gregor   assert(!Mod->isSubFramework() &&
58911dfe6feSDouglas Gregor          "Can only infer linking for top-level frameworks");
59011dfe6feSDouglas Gregor 
59111dfe6feSDouglas Gregor   SmallString<128> LibName;
59211dfe6feSDouglas Gregor   LibName += FrameworkDir->getName();
59311dfe6feSDouglas Gregor   llvm::sys::path::append(LibName, Mod->Name);
5948aaae5a9SJuergen Ributzka 
5958aaae5a9SJuergen Ributzka   // The library name of a framework has more than one possible extension since
5968aaae5a9SJuergen Ributzka   // the introduction of the text-based dynamic library format. We need to check
5978aaae5a9SJuergen Ributzka   // for both before we give up.
5988aaae5a9SJuergen Ributzka   static const char *frameworkExtensions[] = {"", ".tbd"};
5998aaae5a9SJuergen Ributzka   for (const auto *extension : frameworkExtensions) {
6008aaae5a9SJuergen Ributzka     llvm::sys::path::replace_extension(LibName, extension);
60111dfe6feSDouglas Gregor     if (FileMgr.getFile(LibName)) {
60211dfe6feSDouglas Gregor       Mod->LinkLibraries.push_back(Module::LinkLibrary(Mod->Name,
60311dfe6feSDouglas Gregor                                                        /*IsFramework=*/true));
6048aaae5a9SJuergen Ributzka       return;
6058aaae5a9SJuergen Ributzka     }
60611dfe6feSDouglas Gregor   }
60711dfe6feSDouglas Gregor }
60811dfe6feSDouglas Gregor 
609a525400dSBen Langmuir Module *ModuleMap::inferFrameworkModule(const DirectoryEntry *FrameworkDir,
610a525400dSBen Langmuir                                         bool IsSystem, Module *Parent) {
611c1d88ea5SBen Langmuir   Attributes Attrs;
612c1d88ea5SBen Langmuir   Attrs.IsSystem = IsSystem;
613a525400dSBen Langmuir   return inferFrameworkModule(FrameworkDir, Attrs, Parent);
614c1d88ea5SBen Langmuir }
615c1d88ea5SBen Langmuir 
616a525400dSBen Langmuir Module *ModuleMap::inferFrameworkModule(const DirectoryEntry *FrameworkDir,
617c1d88ea5SBen Langmuir                                         Attributes Attrs, Module *Parent) {
618a525400dSBen Langmuir   // Note: as an egregious but useful hack we use the real path here, because
619a525400dSBen Langmuir   // we might be looking at an embedded framework that symlinks out to a
620a525400dSBen Langmuir   // top-level framework, and we need to infer as if we were naming the
621a525400dSBen Langmuir   // top-level framework.
622a525400dSBen Langmuir   StringRef FrameworkDirName =
623a525400dSBen Langmuir       SourceMgr.getFileManager().getCanonicalName(FrameworkDir);
624a525400dSBen Langmuir 
625a525400dSBen Langmuir   // In case this is a case-insensitive filesystem, use the canonical
626a525400dSBen Langmuir   // directory name as the ModuleName, since modules are case-sensitive.
627a525400dSBen Langmuir   // FIXME: we should be able to give a fix-it hint for the correct spelling.
628a525400dSBen Langmuir   SmallString<32> ModuleNameStorage;
629a525400dSBen Langmuir   StringRef ModuleName = sanitizeFilenameAsIdentifier(
630a525400dSBen Langmuir       llvm::sys::path::stem(FrameworkDirName), ModuleNameStorage);
631c1d88ea5SBen Langmuir 
63256c64013SDouglas Gregor   // Check whether we've already found this module.
633e89dbc1dSDouglas Gregor   if (Module *Mod = lookupModuleQualified(ModuleName, Parent))
634e89dbc1dSDouglas Gregor     return Mod;
635e89dbc1dSDouglas Gregor 
6361f76c4e8SManuel Klimek   FileManager &FileMgr = SourceMgr.getFileManager();
63756c64013SDouglas Gregor 
6389194a91dSDouglas Gregor   // If the framework has a parent path from which we're allowed to infer
6399194a91dSDouglas Gregor   // a framework module, do so.
640beee15e7SBen Langmuir   const FileEntry *ModuleMapFile = nullptr;
6419194a91dSDouglas Gregor   if (!Parent) {
6424ddf2221SDouglas Gregor     // Determine whether we're allowed to infer a module map.
6439194a91dSDouglas Gregor     bool canInfer = false;
6444ddf2221SDouglas Gregor     if (llvm::sys::path::has_parent_path(FrameworkDirName)) {
6459194a91dSDouglas Gregor       // Figure out the parent path.
6464ddf2221SDouglas Gregor       StringRef Parent = llvm::sys::path::parent_path(FrameworkDirName);
6479194a91dSDouglas Gregor       if (const DirectoryEntry *ParentDir = FileMgr.getDirectory(Parent)) {
6489194a91dSDouglas Gregor         // Check whether we have already looked into the parent directory
6499194a91dSDouglas Gregor         // for a module map.
650e4412640SArgyrios Kyrtzidis         llvm::DenseMap<const DirectoryEntry *, InferredDirectory>::const_iterator
6519194a91dSDouglas Gregor           inferred = InferredDirectories.find(ParentDir);
6529194a91dSDouglas Gregor         if (inferred == InferredDirectories.end()) {
6539194a91dSDouglas Gregor           // We haven't looked here before. Load a module map, if there is
6549194a91dSDouglas Gregor           // one.
655984e1df7SBen Langmuir           bool IsFrameworkDir = Parent.endswith(".framework");
656984e1df7SBen Langmuir           if (const FileEntry *ModMapFile =
657984e1df7SBen Langmuir                 HeaderInfo.lookupModuleMapFile(ParentDir, IsFrameworkDir)) {
658c1d88ea5SBen Langmuir             parseModuleMapFile(ModMapFile, Attrs.IsSystem, ParentDir);
6599194a91dSDouglas Gregor             inferred = InferredDirectories.find(ParentDir);
6609194a91dSDouglas Gregor           }
6619194a91dSDouglas Gregor 
6629194a91dSDouglas Gregor           if (inferred == InferredDirectories.end())
6639194a91dSDouglas Gregor             inferred = InferredDirectories.insert(
6649194a91dSDouglas Gregor                          std::make_pair(ParentDir, InferredDirectory())).first;
6659194a91dSDouglas Gregor         }
6669194a91dSDouglas Gregor 
6679194a91dSDouglas Gregor         if (inferred->second.InferModules) {
6689194a91dSDouglas Gregor           // We're allowed to infer for this directory, but make sure it's okay
6699194a91dSDouglas Gregor           // to infer this particular module.
6704ddf2221SDouglas Gregor           StringRef Name = llvm::sys::path::stem(FrameworkDirName);
6719194a91dSDouglas Gregor           canInfer = std::find(inferred->second.ExcludedModules.begin(),
6729194a91dSDouglas Gregor                                inferred->second.ExcludedModules.end(),
6739194a91dSDouglas Gregor                                Name) == inferred->second.ExcludedModules.end();
6749194a91dSDouglas Gregor 
675c1d88ea5SBen Langmuir           Attrs.IsSystem |= inferred->second.Attrs.IsSystem;
676c1d88ea5SBen Langmuir           Attrs.IsExternC |= inferred->second.Attrs.IsExternC;
677c1d88ea5SBen Langmuir           Attrs.IsExhaustive |= inferred->second.Attrs.IsExhaustive;
678*ed84df00SBruno Cardoso Lopes           Attrs.NoUndeclaredIncludes |=
679*ed84df00SBruno Cardoso Lopes               inferred->second.Attrs.NoUndeclaredIncludes;
680beee15e7SBen Langmuir           ModuleMapFile = inferred->second.ModuleMapFile;
6819194a91dSDouglas Gregor         }
6829194a91dSDouglas Gregor       }
6839194a91dSDouglas Gregor     }
6849194a91dSDouglas Gregor 
6859194a91dSDouglas Gregor     // If we're not allowed to infer a framework module, don't.
6869194a91dSDouglas Gregor     if (!canInfer)
687d2d442caSCraig Topper       return nullptr;
688beee15e7SBen Langmuir   } else
6899d6448b1SBen Langmuir     ModuleMapFile = getModuleMapFileForUniquing(Parent);
6909194a91dSDouglas Gregor 
6919194a91dSDouglas Gregor 
69256c64013SDouglas Gregor   // Look for an umbrella header.
6932c1dd271SDylan Noblesmith   SmallString<128> UmbrellaName = StringRef(FrameworkDir->getName());
69417381a06SBenjamin Kramer   llvm::sys::path::append(UmbrellaName, "Headers", ModuleName + ".h");
695e89dbc1dSDouglas Gregor   const FileEntry *UmbrellaHeader = FileMgr.getFile(UmbrellaName);
69656c64013SDouglas Gregor 
69756c64013SDouglas Gregor   // FIXME: If there's no umbrella header, we could probably scan the
69856c64013SDouglas Gregor   // framework to load *everything*. But, it's not clear that this is a good
69956c64013SDouglas Gregor   // idea.
70056c64013SDouglas Gregor   if (!UmbrellaHeader)
701d2d442caSCraig Topper     return nullptr;
70256c64013SDouglas Gregor 
7039d6448b1SBen Langmuir   Module *Result = new Module(ModuleName, SourceLocation(), Parent,
704a7e2cc68SRichard Smith                               /*IsFramework=*/true, /*IsExplicit=*/false,
705a7e2cc68SRichard Smith                               NumCreatedModules++);
7069d6448b1SBen Langmuir   InferredModuleAllowedBy[Result] = ModuleMapFile;
7079d6448b1SBen Langmuir   Result->IsInferred = true;
7087e82e019SRichard Smith   if (!Parent) {
7097e82e019SRichard Smith     if (LangOpts.CurrentModule == ModuleName)
710ba7f2f71SDaniel Jasper       SourceModule = Result;
7117e82e019SRichard Smith     Modules[ModuleName] = Result;
712ba7f2f71SDaniel Jasper   }
713c1d88ea5SBen Langmuir 
714c1d88ea5SBen Langmuir   Result->IsSystem |= Attrs.IsSystem;
715c1d88ea5SBen Langmuir   Result->IsExternC |= Attrs.IsExternC;
716c1d88ea5SBen Langmuir   Result->ConfigMacrosExhaustive |= Attrs.IsExhaustive;
717*ed84df00SBruno Cardoso Lopes   Result->NoUndeclaredIncludes |= Attrs.NoUndeclaredIncludes;
7182b63d15fSRichard Smith   Result->Directory = FrameworkDir;
719a686e1b0SDouglas Gregor 
720322f633cSDouglas Gregor   // umbrella header "umbrella-header-name"
7212b63d15fSRichard Smith   //
7222b63d15fSRichard Smith   // The "Headers/" component of the name is implied because this is
7232b63d15fSRichard Smith   // a framework module.
7242b63d15fSRichard Smith   setUmbrellaHeader(Result, UmbrellaHeader, ModuleName + ".h");
725d8bd7537SDouglas Gregor 
726d8bd7537SDouglas Gregor   // export *
727d2d442caSCraig Topper   Result->Exports.push_back(Module::ExportDecl(nullptr, true));
728d8bd7537SDouglas Gregor 
729a89c5ac4SDouglas Gregor   // module * { export * }
730a89c5ac4SDouglas Gregor   Result->InferSubmodules = true;
731a89c5ac4SDouglas Gregor   Result->InferExportWildcard = true;
732a89c5ac4SDouglas Gregor 
733e89dbc1dSDouglas Gregor   // Look for subframeworks.
734c080917eSRafael Espindola   std::error_code EC;
7352c1dd271SDylan Noblesmith   SmallString<128> SubframeworksDirName
736ddaa69cbSDouglas Gregor     = StringRef(FrameworkDir->getName());
737e89dbc1dSDouglas Gregor   llvm::sys::path::append(SubframeworksDirName, "Frameworks");
7382d4d8cb3SBenjamin Kramer   llvm::sys::path::native(SubframeworksDirName);
739b171a59bSBruno Cardoso Lopes   vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
740b171a59bSBruno Cardoso Lopes   for (vfs::directory_iterator Dir = FS.dir_begin(SubframeworksDirName, EC),
741b171a59bSBruno Cardoso Lopes                                DirEnd;
742e89dbc1dSDouglas Gregor        Dir != DirEnd && !EC; Dir.increment(EC)) {
743b171a59bSBruno Cardoso Lopes     if (!StringRef(Dir->getName()).endswith(".framework"))
744e89dbc1dSDouglas Gregor       continue;
745f2161a70SDouglas Gregor 
746b171a59bSBruno Cardoso Lopes     if (const DirectoryEntry *SubframeworkDir =
747b171a59bSBruno Cardoso Lopes             FileMgr.getDirectory(Dir->getName())) {
74807c22b78SDouglas Gregor       // Note: as an egregious but useful hack, we use the real path here and
74907c22b78SDouglas Gregor       // check whether it is actually a subdirectory of the parent directory.
75007c22b78SDouglas Gregor       // This will not be the case if the 'subframework' is actually a symlink
75107c22b78SDouglas Gregor       // out to a top-level framework.
752e00c8b20SDouglas Gregor       StringRef SubframeworkDirName = FileMgr.getCanonicalName(SubframeworkDir);
75307c22b78SDouglas Gregor       bool FoundParent = false;
75407c22b78SDouglas Gregor       do {
75507c22b78SDouglas Gregor         // Get the parent directory name.
75607c22b78SDouglas Gregor         SubframeworkDirName
75707c22b78SDouglas Gregor           = llvm::sys::path::parent_path(SubframeworkDirName);
75807c22b78SDouglas Gregor         if (SubframeworkDirName.empty())
75907c22b78SDouglas Gregor           break;
76007c22b78SDouglas Gregor 
76107c22b78SDouglas Gregor         if (FileMgr.getDirectory(SubframeworkDirName) == FrameworkDir) {
76207c22b78SDouglas Gregor           FoundParent = true;
76307c22b78SDouglas Gregor           break;
76407c22b78SDouglas Gregor         }
76507c22b78SDouglas Gregor       } while (true);
76607c22b78SDouglas Gregor 
76707c22b78SDouglas Gregor       if (!FoundParent)
76807c22b78SDouglas Gregor         continue;
76907c22b78SDouglas Gregor 
770e89dbc1dSDouglas Gregor       // FIXME: Do we want to warn about subframeworks without umbrella headers?
771a525400dSBen Langmuir       inferFrameworkModule(SubframeworkDir, Attrs, Result);
772e89dbc1dSDouglas Gregor     }
773e89dbc1dSDouglas Gregor   }
774e89dbc1dSDouglas Gregor 
77511dfe6feSDouglas Gregor   // If the module is a top-level framework, automatically link against the
77611dfe6feSDouglas Gregor   // framework.
77711dfe6feSDouglas Gregor   if (!Result->isSubFramework()) {
77811dfe6feSDouglas Gregor     inferFrameworkLink(Result, FrameworkDir, FileMgr);
77911dfe6feSDouglas Gregor   }
78011dfe6feSDouglas Gregor 
78156c64013SDouglas Gregor   return Result;
78256c64013SDouglas Gregor }
78356c64013SDouglas Gregor 
7842b63d15fSRichard Smith void ModuleMap::setUmbrellaHeader(Module *Mod, const FileEntry *UmbrellaHeader,
7852b63d15fSRichard Smith                                   Twine NameAsWritten) {
78697da9178SDaniel Jasper   Headers[UmbrellaHeader].push_back(KnownHeader(Mod, NormalHeader));
78773141fa9SDouglas Gregor   Mod->Umbrella = UmbrellaHeader;
7882b63d15fSRichard Smith   Mod->UmbrellaAsWritten = NameAsWritten.str();
7897033127bSDouglas Gregor   UmbrellaDirs[UmbrellaHeader->getDir()] = Mod;
790b3a0fa48SBruno Cardoso Lopes 
791b3a0fa48SBruno Cardoso Lopes   // Notify callbacks that we just added a new header.
792b3a0fa48SBruno Cardoso Lopes   for (const auto &Cb : Callbacks)
793b3a0fa48SBruno Cardoso Lopes     Cb->moduleMapAddUmbrellaHeader(&SourceMgr.getFileManager(), UmbrellaHeader);
794a89c5ac4SDouglas Gregor }
795a89c5ac4SDouglas Gregor 
7962b63d15fSRichard Smith void ModuleMap::setUmbrellaDir(Module *Mod, const DirectoryEntry *UmbrellaDir,
7972b63d15fSRichard Smith                                Twine NameAsWritten) {
798524e33e1SDouglas Gregor   Mod->Umbrella = UmbrellaDir;
7992b63d15fSRichard Smith   Mod->UmbrellaAsWritten = NameAsWritten.str();
800524e33e1SDouglas Gregor   UmbrellaDirs[UmbrellaDir] = Mod;
801524e33e1SDouglas Gregor }
802524e33e1SDouglas Gregor 
8033c1a41adSRichard Smith static Module::HeaderKind headerRoleToKind(ModuleMap::ModuleHeaderRole Role) {
8040e98d938SNAKAMURA Takumi   switch ((int)Role) {
8053c1a41adSRichard Smith   default: llvm_unreachable("unknown header role");
8063c1a41adSRichard Smith   case ModuleMap::NormalHeader:
8073c1a41adSRichard Smith     return Module::HK_Normal;
8083c1a41adSRichard Smith   case ModuleMap::PrivateHeader:
8093c1a41adSRichard Smith     return Module::HK_Private;
8103c1a41adSRichard Smith   case ModuleMap::TextualHeader:
8113c1a41adSRichard Smith     return Module::HK_Textual;
8123c1a41adSRichard Smith   case ModuleMap::PrivateHeader | ModuleMap::TextualHeader:
8133c1a41adSRichard Smith     return Module::HK_PrivateTextual;
8143c1a41adSRichard Smith   }
8150e98d938SNAKAMURA Takumi }
816202210b3SRichard Smith 
8173c1a41adSRichard Smith void ModuleMap::addHeader(Module *Mod, Module::Header Header,
818d8879c85SRichard Smith                           ModuleHeaderRole Role, bool Imported) {
819386bb073SRichard Smith   KnownHeader KH(Mod, Role);
8203c1a41adSRichard Smith 
821386bb073SRichard Smith   // Only add each header to the headers list once.
822386bb073SRichard Smith   // FIXME: Should we diagnose if a header is listed twice in the
823386bb073SRichard Smith   // same module definition?
824386bb073SRichard Smith   auto &HeaderList = Headers[Header.Entry];
825386bb073SRichard Smith   for (auto H : HeaderList)
826386bb073SRichard Smith     if (H == KH)
827386bb073SRichard Smith       return;
828386bb073SRichard Smith 
829386bb073SRichard Smith   HeaderList.push_back(KH);
8303c1a41adSRichard Smith   Mod->Headers[headerRoleToKind(Role)].push_back(std::move(Header));
831386bb073SRichard Smith 
8327e82e019SRichard Smith   bool isCompilingModuleHeader =
833bbcc9f04SRichard Smith       LangOpts.isCompilingModule() && Mod->getTopLevelModule() == SourceModule;
834d8879c85SRichard Smith   if (!Imported || isCompilingModuleHeader) {
835d8879c85SRichard Smith     // When we import HeaderFileInfo, the external source is expected to
836d8879c85SRichard Smith     // set the isModuleHeader flag itself.
837d8879c85SRichard Smith     HeaderInfo.MarkFileModuleHeader(Header.Entry, Role,
838d8879c85SRichard Smith                                     isCompilingModuleHeader);
839d8879c85SRichard Smith   }
840e62cfd7cSBruno Cardoso Lopes 
841e62cfd7cSBruno Cardoso Lopes   // Notify callbacks that we just added a new header.
842e62cfd7cSBruno Cardoso Lopes   for (const auto &Cb : Callbacks)
843f0841790SBruno Cardoso Lopes     Cb->moduleMapAddHeader(Header.Entry->getName());
844a89c5ac4SDouglas Gregor }
845a89c5ac4SDouglas Gregor 
8463c1a41adSRichard Smith void ModuleMap::excludeHeader(Module *Mod, Module::Header Header) {
847feb54b6dSRichard Smith   // Add this as a known header so we won't implicitly add it to any
848feb54b6dSRichard Smith   // umbrella directory module.
849feb54b6dSRichard Smith   // FIXME: Should we only exclude it from umbrella modules within the
850feb54b6dSRichard Smith   // specified module?
8513c1a41adSRichard Smith   (void) Headers[Header.Entry];
8523c1a41adSRichard Smith 
8533c1a41adSRichard Smith   Mod->Headers[Module::HK_Excluded].push_back(std::move(Header));
854feb54b6dSRichard Smith }
855feb54b6dSRichard Smith 
856514b636aSDouglas Gregor const FileEntry *
8574b8a9e95SBen Langmuir ModuleMap::getContainingModuleMapFile(const Module *Module) const {
8581f76c4e8SManuel Klimek   if (Module->DefinitionLoc.isInvalid())
859d2d442caSCraig Topper     return nullptr;
860514b636aSDouglas Gregor 
8611f76c4e8SManuel Klimek   return SourceMgr.getFileEntryForID(
8621f76c4e8SManuel Klimek            SourceMgr.getFileID(Module->DefinitionLoc));
863514b636aSDouglas Gregor }
864514b636aSDouglas Gregor 
8654b8a9e95SBen Langmuir const FileEntry *ModuleMap::getModuleMapFileForUniquing(const Module *M) const {
8669d6448b1SBen Langmuir   if (M->IsInferred) {
8679d6448b1SBen Langmuir     assert(InferredModuleAllowedBy.count(M) && "missing inferred module map");
8689d6448b1SBen Langmuir     return InferredModuleAllowedBy.find(M)->second;
8699d6448b1SBen Langmuir   }
8709d6448b1SBen Langmuir   return getContainingModuleMapFile(M);
8719d6448b1SBen Langmuir }
8729d6448b1SBen Langmuir 
8739d6448b1SBen Langmuir void ModuleMap::setInferredModuleAllowedBy(Module *M, const FileEntry *ModMap) {
8749d6448b1SBen Langmuir   assert(M->IsInferred && "module not inferred");
8759d6448b1SBen Langmuir   InferredModuleAllowedBy[M] = ModMap;
8769d6448b1SBen Langmuir }
8779d6448b1SBen Langmuir 
878cdae941eSYaron Keren LLVM_DUMP_METHOD void ModuleMap::dump() {
879718292f2SDouglas Gregor   llvm::errs() << "Modules:";
880718292f2SDouglas Gregor   for (llvm::StringMap<Module *>::iterator M = Modules.begin(),
881718292f2SDouglas Gregor                                         MEnd = Modules.end();
882718292f2SDouglas Gregor        M != MEnd; ++M)
883d28d1b8dSDouglas Gregor     M->getValue()->print(llvm::errs(), 2);
884718292f2SDouglas Gregor 
885718292f2SDouglas Gregor   llvm::errs() << "Headers:";
88659527666SDouglas Gregor   for (HeadersMap::iterator H = Headers.begin(), HEnd = Headers.end();
887718292f2SDouglas Gregor        H != HEnd; ++H) {
88897da9178SDaniel Jasper     llvm::errs() << "  \"" << H->first->getName() << "\" -> ";
88997da9178SDaniel Jasper     for (SmallVectorImpl<KnownHeader>::const_iterator I = H->second.begin(),
89097da9178SDaniel Jasper                                                       E = H->second.end();
89197da9178SDaniel Jasper          I != E; ++I) {
89297da9178SDaniel Jasper       if (I != H->second.begin())
89397da9178SDaniel Jasper         llvm::errs() << ",";
89497da9178SDaniel Jasper       llvm::errs() << I->getModule()->getFullModuleName();
89597da9178SDaniel Jasper     }
89697da9178SDaniel Jasper     llvm::errs() << "\n";
897718292f2SDouglas Gregor   }
898718292f2SDouglas Gregor }
899718292f2SDouglas Gregor 
9002b82c2a5SDouglas Gregor bool ModuleMap::resolveExports(Module *Mod, bool Complain) {
90142413141SRichard Smith   auto Unresolved = std::move(Mod->UnresolvedExports);
90242413141SRichard Smith   Mod->UnresolvedExports.clear();
90342413141SRichard Smith   for (auto &UE : Unresolved) {
90442413141SRichard Smith     Module::ExportDecl Export = resolveExport(Mod, UE, Complain);
905f5eedd05SDouglas Gregor     if (Export.getPointer() || Export.getInt())
9062b82c2a5SDouglas Gregor       Mod->Exports.push_back(Export);
9072b82c2a5SDouglas Gregor     else
90842413141SRichard Smith       Mod->UnresolvedExports.push_back(UE);
9092b82c2a5SDouglas Gregor   }
91042413141SRichard Smith   return !Mod->UnresolvedExports.empty();
9112b82c2a5SDouglas Gregor }
9122b82c2a5SDouglas Gregor 
913ba7f2f71SDaniel Jasper bool ModuleMap::resolveUses(Module *Mod, bool Complain) {
91442413141SRichard Smith   auto Unresolved = std::move(Mod->UnresolvedDirectUses);
91542413141SRichard Smith   Mod->UnresolvedDirectUses.clear();
91642413141SRichard Smith   for (auto &UDU : Unresolved) {
91742413141SRichard Smith     Module *DirectUse = resolveModuleId(UDU, Mod, Complain);
918ba7f2f71SDaniel Jasper     if (DirectUse)
919ba7f2f71SDaniel Jasper       Mod->DirectUses.push_back(DirectUse);
920ba7f2f71SDaniel Jasper     else
92142413141SRichard Smith       Mod->UnresolvedDirectUses.push_back(UDU);
922ba7f2f71SDaniel Jasper   }
92342413141SRichard Smith   return !Mod->UnresolvedDirectUses.empty();
924ba7f2f71SDaniel Jasper }
925ba7f2f71SDaniel Jasper 
926fb912657SDouglas Gregor bool ModuleMap::resolveConflicts(Module *Mod, bool Complain) {
92742413141SRichard Smith   auto Unresolved = std::move(Mod->UnresolvedConflicts);
92842413141SRichard Smith   Mod->UnresolvedConflicts.clear();
92942413141SRichard Smith   for (auto &UC : Unresolved) {
93042413141SRichard Smith     if (Module *OtherMod = resolveModuleId(UC.Id, Mod, Complain)) {
931fb912657SDouglas Gregor       Module::Conflict Conflict;
932fb912657SDouglas Gregor       Conflict.Other = OtherMod;
93342413141SRichard Smith       Conflict.Message = UC.Message;
934fb912657SDouglas Gregor       Mod->Conflicts.push_back(Conflict);
93542413141SRichard Smith     } else
93642413141SRichard Smith       Mod->UnresolvedConflicts.push_back(UC);
937fb912657SDouglas Gregor   }
93842413141SRichard Smith   return !Mod->UnresolvedConflicts.empty();
939fb912657SDouglas Gregor }
940fb912657SDouglas Gregor 
9410093b3c7SDouglas Gregor Module *ModuleMap::inferModuleFromLocation(FullSourceLoc Loc) {
9420093b3c7SDouglas Gregor   if (Loc.isInvalid())
943d2d442caSCraig Topper     return nullptr;
9440093b3c7SDouglas Gregor 
9457ffd0b44SDavid Majnemer   if (UmbrellaDirs.empty() && Headers.empty())
9467ffd0b44SDavid Majnemer     return nullptr;
9477ffd0b44SDavid Majnemer 
9480093b3c7SDouglas Gregor   // Use the expansion location to determine which module we're in.
9490093b3c7SDouglas Gregor   FullSourceLoc ExpansionLoc = Loc.getExpansionLoc();
9500093b3c7SDouglas Gregor   if (!ExpansionLoc.isFileID())
951d2d442caSCraig Topper     return nullptr;
9520093b3c7SDouglas Gregor 
9530093b3c7SDouglas Gregor   const SourceManager &SrcMgr = Loc.getManager();
9540093b3c7SDouglas Gregor   FileID ExpansionFileID = ExpansionLoc.getFileID();
955224d8a74SDouglas Gregor 
956224d8a74SDouglas Gregor   while (const FileEntry *ExpansionFile
957224d8a74SDouglas Gregor            = SrcMgr.getFileEntryForID(ExpansionFileID)) {
958224d8a74SDouglas Gregor     // Find the module that owns this header (if any).
959b53e5483SLawrence Crowl     if (Module *Mod = findModuleForHeader(ExpansionFile).getModule())
960224d8a74SDouglas Gregor       return Mod;
961224d8a74SDouglas Gregor 
962224d8a74SDouglas Gregor     // No module owns this header, so look up the inclusion chain to see if
963224d8a74SDouglas Gregor     // any included header has an associated module.
964224d8a74SDouglas Gregor     SourceLocation IncludeLoc = SrcMgr.getIncludeLoc(ExpansionFileID);
965224d8a74SDouglas Gregor     if (IncludeLoc.isInvalid())
966d2d442caSCraig Topper       return nullptr;
9670093b3c7SDouglas Gregor 
968224d8a74SDouglas Gregor     ExpansionFileID = SrcMgr.getFileID(IncludeLoc);
969224d8a74SDouglas Gregor   }
970224d8a74SDouglas Gregor 
971d2d442caSCraig Topper   return nullptr;
9720093b3c7SDouglas Gregor }
9730093b3c7SDouglas Gregor 
974718292f2SDouglas Gregor //----------------------------------------------------------------------------//
975718292f2SDouglas Gregor // Module map file parser
976718292f2SDouglas Gregor //----------------------------------------------------------------------------//
977718292f2SDouglas Gregor 
978718292f2SDouglas Gregor namespace clang {
979718292f2SDouglas Gregor   /// \brief A token in a module map file.
980718292f2SDouglas Gregor   struct MMToken {
981718292f2SDouglas Gregor     enum TokenKind {
9821fb5c3a6SDouglas Gregor       Comma,
98335b13eceSDouglas Gregor       ConfigMacros,
984fb912657SDouglas Gregor       Conflict,
985718292f2SDouglas Gregor       EndOfFile,
986718292f2SDouglas Gregor       HeaderKeyword,
987718292f2SDouglas Gregor       Identifier,
988a3feee2aSRichard Smith       Exclaim,
98959527666SDouglas Gregor       ExcludeKeyword,
990718292f2SDouglas Gregor       ExplicitKeyword,
9912b82c2a5SDouglas Gregor       ExportKeyword,
99297292843SDaniel Jasper       ExternKeyword,
993755b2055SDouglas Gregor       FrameworkKeyword,
9946ddfca91SDouglas Gregor       LinkKeyword,
995718292f2SDouglas Gregor       ModuleKeyword,
9962b82c2a5SDouglas Gregor       Period,
997b53e5483SLawrence Crowl       PrivateKeyword,
998718292f2SDouglas Gregor       UmbrellaKeyword,
999ba7f2f71SDaniel Jasper       UseKeyword,
10001fb5c3a6SDouglas Gregor       RequiresKeyword,
10012b82c2a5SDouglas Gregor       Star,
1002718292f2SDouglas Gregor       StringLiteral,
1003306d8920SRichard Smith       TextualKeyword,
1004718292f2SDouglas Gregor       LBrace,
1005a686e1b0SDouglas Gregor       RBrace,
1006a686e1b0SDouglas Gregor       LSquare,
1007a686e1b0SDouglas Gregor       RSquare
1008718292f2SDouglas Gregor     } Kind;
1009718292f2SDouglas Gregor 
1010718292f2SDouglas Gregor     unsigned Location;
1011718292f2SDouglas Gregor     unsigned StringLength;
1012718292f2SDouglas Gregor     const char *StringData;
1013718292f2SDouglas Gregor 
1014718292f2SDouglas Gregor     void clear() {
1015718292f2SDouglas Gregor       Kind = EndOfFile;
1016718292f2SDouglas Gregor       Location = 0;
1017718292f2SDouglas Gregor       StringLength = 0;
1018d2d442caSCraig Topper       StringData = nullptr;
1019718292f2SDouglas Gregor     }
1020718292f2SDouglas Gregor 
1021718292f2SDouglas Gregor     bool is(TokenKind K) const { return Kind == K; }
1022718292f2SDouglas Gregor 
1023718292f2SDouglas Gregor     SourceLocation getLocation() const {
1024718292f2SDouglas Gregor       return SourceLocation::getFromRawEncoding(Location);
1025718292f2SDouglas Gregor     }
1026718292f2SDouglas Gregor 
1027718292f2SDouglas Gregor     StringRef getString() const {
1028718292f2SDouglas Gregor       return StringRef(StringData, StringLength);
1029718292f2SDouglas Gregor     }
1030718292f2SDouglas Gregor   };
1031718292f2SDouglas Gregor 
1032718292f2SDouglas Gregor   class ModuleMapParser {
1033718292f2SDouglas Gregor     Lexer &L;
1034718292f2SDouglas Gregor     SourceManager &SourceMgr;
1035bc10b9fbSDouglas Gregor 
1036bc10b9fbSDouglas Gregor     /// \brief Default target information, used only for string literal
1037bc10b9fbSDouglas Gregor     /// parsing.
1038bc10b9fbSDouglas Gregor     const TargetInfo *Target;
1039bc10b9fbSDouglas Gregor 
1040718292f2SDouglas Gregor     DiagnosticsEngine &Diags;
1041718292f2SDouglas Gregor     ModuleMap &Map;
1042718292f2SDouglas Gregor 
1043beee15e7SBen Langmuir     /// \brief The current module map file.
1044beee15e7SBen Langmuir     const FileEntry *ModuleMapFile;
1045beee15e7SBen Langmuir 
10469acb99e3SRichard Smith     /// \brief The directory that file names in this module map file should
10479acb99e3SRichard Smith     /// be resolved relative to.
10485257fc63SDouglas Gregor     const DirectoryEntry *Directory;
10495257fc63SDouglas Gregor 
10503ec6663bSDouglas Gregor     /// \brief The directory containing Clang-supplied headers.
10513ec6663bSDouglas Gregor     const DirectoryEntry *BuiltinIncludeDir;
10523ec6663bSDouglas Gregor 
1053963c5535SDouglas Gregor     /// \brief Whether this module map is in a system header directory.
1054963c5535SDouglas Gregor     bool IsSystem;
1055963c5535SDouglas Gregor 
1056718292f2SDouglas Gregor     /// \brief Whether an error occurred.
1057718292f2SDouglas Gregor     bool HadError;
1058718292f2SDouglas Gregor 
1059718292f2SDouglas Gregor     /// \brief Stores string data for the various string literals referenced
1060718292f2SDouglas Gregor     /// during parsing.
1061718292f2SDouglas Gregor     llvm::BumpPtrAllocator StringData;
1062718292f2SDouglas Gregor 
1063718292f2SDouglas Gregor     /// \brief The current token.
1064718292f2SDouglas Gregor     MMToken Tok;
1065718292f2SDouglas Gregor 
1066718292f2SDouglas Gregor     /// \brief The active module.
1067de3ef502SDouglas Gregor     Module *ActiveModule;
1068718292f2SDouglas Gregor 
10697ff29148SBen Langmuir     /// \brief Whether a module uses the 'requires excluded' hack to mark its
10707ff29148SBen Langmuir     /// contents as 'textual'.
10717ff29148SBen Langmuir     ///
10727ff29148SBen Langmuir     /// On older Darwin SDK versions, 'requires excluded' is used to mark the
10737ff29148SBen Langmuir     /// contents of the Darwin.C.excluded (assert.h) and Tcl.Private modules as
10747ff29148SBen Langmuir     /// non-modular headers.  For backwards compatibility, we continue to
10757ff29148SBen Langmuir     /// support this idiom for just these modules, and map the headers to
10767ff29148SBen Langmuir     /// 'textual' to match the original intent.
10777ff29148SBen Langmuir     llvm::SmallPtrSet<Module *, 2> UsesRequiresExcludedHack;
10787ff29148SBen Langmuir 
1079718292f2SDouglas Gregor     /// \brief Consume the current token and return its location.
1080718292f2SDouglas Gregor     SourceLocation consumeToken();
1081718292f2SDouglas Gregor 
1082718292f2SDouglas Gregor     /// \brief Skip tokens until we reach the a token with the given kind
1083718292f2SDouglas Gregor     /// (or the end of the file).
1084718292f2SDouglas Gregor     void skipUntil(MMToken::TokenKind K);
1085718292f2SDouglas Gregor 
1086f857950dSDmitri Gribenko     typedef SmallVector<std::pair<std::string, SourceLocation>, 2> ModuleId;
1087e7ab3669SDouglas Gregor     bool parseModuleId(ModuleId &Id);
1088718292f2SDouglas Gregor     void parseModuleDecl();
108997292843SDaniel Jasper     void parseExternModuleDecl();
10901fb5c3a6SDouglas Gregor     void parseRequiresDecl();
1091b53e5483SLawrence Crowl     void parseHeaderDecl(clang::MMToken::TokenKind,
1092b53e5483SLawrence Crowl                          SourceLocation LeadingLoc);
1093524e33e1SDouglas Gregor     void parseUmbrellaDirDecl(SourceLocation UmbrellaLoc);
10942b82c2a5SDouglas Gregor     void parseExportDecl();
1095ba7f2f71SDaniel Jasper     void parseUseDecl();
10966ddfca91SDouglas Gregor     void parseLinkDecl();
109735b13eceSDouglas Gregor     void parseConfigMacros();
1098fb912657SDouglas Gregor     void parseConflict();
10999194a91dSDouglas Gregor     void parseInferredModuleDecl(bool Framework, bool Explicit);
1100c1d88ea5SBen Langmuir 
1101c1d88ea5SBen Langmuir     typedef ModuleMap::Attributes Attributes;
11024442605fSBill Wendling     bool parseOptionalAttributes(Attributes &Attrs);
1103718292f2SDouglas Gregor 
1104718292f2SDouglas Gregor   public:
1105718292f2SDouglas Gregor     explicit ModuleMapParser(Lexer &L, SourceManager &SourceMgr,
1106bc10b9fbSDouglas Gregor                              const TargetInfo *Target,
1107718292f2SDouglas Gregor                              DiagnosticsEngine &Diags,
11085257fc63SDouglas Gregor                              ModuleMap &Map,
1109beee15e7SBen Langmuir                              const FileEntry *ModuleMapFile,
11103ec6663bSDouglas Gregor                              const DirectoryEntry *Directory,
1111963c5535SDouglas Gregor                              const DirectoryEntry *BuiltinIncludeDir,
1112963c5535SDouglas Gregor                              bool IsSystem)
1113bc10b9fbSDouglas Gregor       : L(L), SourceMgr(SourceMgr), Target(Target), Diags(Diags), Map(Map),
1114beee15e7SBen Langmuir         ModuleMapFile(ModuleMapFile), Directory(Directory),
1115beee15e7SBen Langmuir         BuiltinIncludeDir(BuiltinIncludeDir), IsSystem(IsSystem),
1116d2d442caSCraig Topper         HadError(false), ActiveModule(nullptr)
1117718292f2SDouglas Gregor     {
1118718292f2SDouglas Gregor       Tok.clear();
1119718292f2SDouglas Gregor       consumeToken();
1120718292f2SDouglas Gregor     }
1121718292f2SDouglas Gregor 
1122718292f2SDouglas Gregor     bool parseModuleMapFile();
1123718292f2SDouglas Gregor   };
1124ab9db510SAlexander Kornienko }
1125718292f2SDouglas Gregor 
1126718292f2SDouglas Gregor SourceLocation ModuleMapParser::consumeToken() {
1127718292f2SDouglas Gregor retry:
1128718292f2SDouglas Gregor   SourceLocation Result = Tok.getLocation();
1129718292f2SDouglas Gregor   Tok.clear();
1130718292f2SDouglas Gregor 
1131718292f2SDouglas Gregor   Token LToken;
1132718292f2SDouglas Gregor   L.LexFromRawLexer(LToken);
1133718292f2SDouglas Gregor   Tok.Location = LToken.getLocation().getRawEncoding();
1134718292f2SDouglas Gregor   switch (LToken.getKind()) {
11352d57cea2SAlp Toker   case tok::raw_identifier: {
11362d57cea2SAlp Toker     StringRef RI = LToken.getRawIdentifier();
11372d57cea2SAlp Toker     Tok.StringData = RI.data();
11382d57cea2SAlp Toker     Tok.StringLength = RI.size();
11392d57cea2SAlp Toker     Tok.Kind = llvm::StringSwitch<MMToken::TokenKind>(RI)
114035b13eceSDouglas Gregor                  .Case("config_macros", MMToken::ConfigMacros)
1141fb912657SDouglas Gregor                  .Case("conflict", MMToken::Conflict)
114259527666SDouglas Gregor                  .Case("exclude", MMToken::ExcludeKeyword)
1143718292f2SDouglas Gregor                  .Case("explicit", MMToken::ExplicitKeyword)
11442b82c2a5SDouglas Gregor                  .Case("export", MMToken::ExportKeyword)
114597292843SDaniel Jasper                  .Case("extern", MMToken::ExternKeyword)
1146755b2055SDouglas Gregor                  .Case("framework", MMToken::FrameworkKeyword)
114735b13eceSDouglas Gregor                  .Case("header", MMToken::HeaderKeyword)
11486ddfca91SDouglas Gregor                  .Case("link", MMToken::LinkKeyword)
1149718292f2SDouglas Gregor                  .Case("module", MMToken::ModuleKeyword)
1150b53e5483SLawrence Crowl                  .Case("private", MMToken::PrivateKeyword)
11511fb5c3a6SDouglas Gregor                  .Case("requires", MMToken::RequiresKeyword)
1152306d8920SRichard Smith                  .Case("textual", MMToken::TextualKeyword)
1153718292f2SDouglas Gregor                  .Case("umbrella", MMToken::UmbrellaKeyword)
1154ba7f2f71SDaniel Jasper                  .Case("use", MMToken::UseKeyword)
1155718292f2SDouglas Gregor                  .Default(MMToken::Identifier);
1156718292f2SDouglas Gregor     break;
11572d57cea2SAlp Toker   }
1158718292f2SDouglas Gregor 
11591fb5c3a6SDouglas Gregor   case tok::comma:
11601fb5c3a6SDouglas Gregor     Tok.Kind = MMToken::Comma;
11611fb5c3a6SDouglas Gregor     break;
11621fb5c3a6SDouglas Gregor 
1163718292f2SDouglas Gregor   case tok::eof:
1164718292f2SDouglas Gregor     Tok.Kind = MMToken::EndOfFile;
1165718292f2SDouglas Gregor     break;
1166718292f2SDouglas Gregor 
1167718292f2SDouglas Gregor   case tok::l_brace:
1168718292f2SDouglas Gregor     Tok.Kind = MMToken::LBrace;
1169718292f2SDouglas Gregor     break;
1170718292f2SDouglas Gregor 
1171a686e1b0SDouglas Gregor   case tok::l_square:
1172a686e1b0SDouglas Gregor     Tok.Kind = MMToken::LSquare;
1173a686e1b0SDouglas Gregor     break;
1174a686e1b0SDouglas Gregor 
11752b82c2a5SDouglas Gregor   case tok::period:
11762b82c2a5SDouglas Gregor     Tok.Kind = MMToken::Period;
11772b82c2a5SDouglas Gregor     break;
11782b82c2a5SDouglas Gregor 
1179718292f2SDouglas Gregor   case tok::r_brace:
1180718292f2SDouglas Gregor     Tok.Kind = MMToken::RBrace;
1181718292f2SDouglas Gregor     break;
1182718292f2SDouglas Gregor 
1183a686e1b0SDouglas Gregor   case tok::r_square:
1184a686e1b0SDouglas Gregor     Tok.Kind = MMToken::RSquare;
1185a686e1b0SDouglas Gregor     break;
1186a686e1b0SDouglas Gregor 
11872b82c2a5SDouglas Gregor   case tok::star:
11882b82c2a5SDouglas Gregor     Tok.Kind = MMToken::Star;
11892b82c2a5SDouglas Gregor     break;
11902b82c2a5SDouglas Gregor 
1191a3feee2aSRichard Smith   case tok::exclaim:
1192a3feee2aSRichard Smith     Tok.Kind = MMToken::Exclaim;
1193a3feee2aSRichard Smith     break;
1194a3feee2aSRichard Smith 
1195718292f2SDouglas Gregor   case tok::string_literal: {
1196d67aea28SRichard Smith     if (LToken.hasUDSuffix()) {
1197d67aea28SRichard Smith       Diags.Report(LToken.getLocation(), diag::err_invalid_string_udl);
1198d67aea28SRichard Smith       HadError = true;
1199d67aea28SRichard Smith       goto retry;
1200d67aea28SRichard Smith     }
1201d67aea28SRichard Smith 
1202718292f2SDouglas Gregor     // Parse the string literal.
1203718292f2SDouglas Gregor     LangOptions LangOpts;
12049d5583efSCraig Topper     StringLiteralParser StringLiteral(LToken, SourceMgr, LangOpts, *Target);
1205718292f2SDouglas Gregor     if (StringLiteral.hadError)
1206718292f2SDouglas Gregor       goto retry;
1207718292f2SDouglas Gregor 
1208718292f2SDouglas Gregor     // Copy the string literal into our string data allocator.
1209718292f2SDouglas Gregor     unsigned Length = StringLiteral.GetStringLength();
1210718292f2SDouglas Gregor     char *Saved = StringData.Allocate<char>(Length + 1);
1211718292f2SDouglas Gregor     memcpy(Saved, StringLiteral.GetString().data(), Length);
1212718292f2SDouglas Gregor     Saved[Length] = 0;
1213718292f2SDouglas Gregor 
1214718292f2SDouglas Gregor     // Form the token.
1215718292f2SDouglas Gregor     Tok.Kind = MMToken::StringLiteral;
1216718292f2SDouglas Gregor     Tok.StringData = Saved;
1217718292f2SDouglas Gregor     Tok.StringLength = Length;
1218718292f2SDouglas Gregor     break;
1219718292f2SDouglas Gregor   }
1220718292f2SDouglas Gregor 
1221718292f2SDouglas Gregor   case tok::comment:
1222718292f2SDouglas Gregor     goto retry;
1223718292f2SDouglas Gregor 
1224718292f2SDouglas Gregor   default:
1225718292f2SDouglas Gregor     Diags.Report(LToken.getLocation(), diag::err_mmap_unknown_token);
1226718292f2SDouglas Gregor     HadError = true;
1227718292f2SDouglas Gregor     goto retry;
1228718292f2SDouglas Gregor   }
1229718292f2SDouglas Gregor 
1230718292f2SDouglas Gregor   return Result;
1231718292f2SDouglas Gregor }
1232718292f2SDouglas Gregor 
1233718292f2SDouglas Gregor void ModuleMapParser::skipUntil(MMToken::TokenKind K) {
1234718292f2SDouglas Gregor   unsigned braceDepth = 0;
1235a686e1b0SDouglas Gregor   unsigned squareDepth = 0;
1236718292f2SDouglas Gregor   do {
1237718292f2SDouglas Gregor     switch (Tok.Kind) {
1238718292f2SDouglas Gregor     case MMToken::EndOfFile:
1239718292f2SDouglas Gregor       return;
1240718292f2SDouglas Gregor 
1241718292f2SDouglas Gregor     case MMToken::LBrace:
1242a686e1b0SDouglas Gregor       if (Tok.is(K) && braceDepth == 0 && squareDepth == 0)
1243718292f2SDouglas Gregor         return;
1244718292f2SDouglas Gregor 
1245718292f2SDouglas Gregor       ++braceDepth;
1246718292f2SDouglas Gregor       break;
1247718292f2SDouglas Gregor 
1248a686e1b0SDouglas Gregor     case MMToken::LSquare:
1249a686e1b0SDouglas Gregor       if (Tok.is(K) && braceDepth == 0 && squareDepth == 0)
1250a686e1b0SDouglas Gregor         return;
1251a686e1b0SDouglas Gregor 
1252a686e1b0SDouglas Gregor       ++squareDepth;
1253a686e1b0SDouglas Gregor       break;
1254a686e1b0SDouglas Gregor 
1255718292f2SDouglas Gregor     case MMToken::RBrace:
1256718292f2SDouglas Gregor       if (braceDepth > 0)
1257718292f2SDouglas Gregor         --braceDepth;
1258718292f2SDouglas Gregor       else if (Tok.is(K))
1259718292f2SDouglas Gregor         return;
1260718292f2SDouglas Gregor       break;
1261718292f2SDouglas Gregor 
1262a686e1b0SDouglas Gregor     case MMToken::RSquare:
1263a686e1b0SDouglas Gregor       if (squareDepth > 0)
1264a686e1b0SDouglas Gregor         --squareDepth;
1265a686e1b0SDouglas Gregor       else if (Tok.is(K))
1266a686e1b0SDouglas Gregor         return;
1267a686e1b0SDouglas Gregor       break;
1268a686e1b0SDouglas Gregor 
1269718292f2SDouglas Gregor     default:
1270a686e1b0SDouglas Gregor       if (braceDepth == 0 && squareDepth == 0 && Tok.is(K))
1271718292f2SDouglas Gregor         return;
1272718292f2SDouglas Gregor       break;
1273718292f2SDouglas Gregor     }
1274718292f2SDouglas Gregor 
1275718292f2SDouglas Gregor    consumeToken();
1276718292f2SDouglas Gregor   } while (true);
1277718292f2SDouglas Gregor }
1278718292f2SDouglas Gregor 
1279e7ab3669SDouglas Gregor /// \brief Parse a module-id.
1280e7ab3669SDouglas Gregor ///
1281e7ab3669SDouglas Gregor ///   module-id:
1282e7ab3669SDouglas Gregor ///     identifier
1283e7ab3669SDouglas Gregor ///     identifier '.' module-id
1284e7ab3669SDouglas Gregor ///
1285e7ab3669SDouglas Gregor /// \returns true if an error occurred, false otherwise.
1286e7ab3669SDouglas Gregor bool ModuleMapParser::parseModuleId(ModuleId &Id) {
1287e7ab3669SDouglas Gregor   Id.clear();
1288e7ab3669SDouglas Gregor   do {
12893cd34c76SDaniel Jasper     if (Tok.is(MMToken::Identifier) || Tok.is(MMToken::StringLiteral)) {
1290e7ab3669SDouglas Gregor       Id.push_back(std::make_pair(Tok.getString(), Tok.getLocation()));
1291e7ab3669SDouglas Gregor       consumeToken();
1292e7ab3669SDouglas Gregor     } else {
1293e7ab3669SDouglas Gregor       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module_name);
1294e7ab3669SDouglas Gregor       return true;
1295e7ab3669SDouglas Gregor     }
1296e7ab3669SDouglas Gregor 
1297e7ab3669SDouglas Gregor     if (!Tok.is(MMToken::Period))
1298e7ab3669SDouglas Gregor       break;
1299e7ab3669SDouglas Gregor 
1300e7ab3669SDouglas Gregor     consumeToken();
1301e7ab3669SDouglas Gregor   } while (true);
1302e7ab3669SDouglas Gregor 
1303e7ab3669SDouglas Gregor   return false;
1304e7ab3669SDouglas Gregor }
1305e7ab3669SDouglas Gregor 
1306a686e1b0SDouglas Gregor namespace {
1307a686e1b0SDouglas Gregor   /// \brief Enumerates the known attributes.
1308a686e1b0SDouglas Gregor   enum AttributeKind {
1309a686e1b0SDouglas Gregor     /// \brief An unknown attribute.
1310a686e1b0SDouglas Gregor     AT_unknown,
1311a686e1b0SDouglas Gregor     /// \brief The 'system' attribute.
131235b13eceSDouglas Gregor     AT_system,
131377944868SRichard Smith     /// \brief The 'extern_c' attribute.
131477944868SRichard Smith     AT_extern_c,
131535b13eceSDouglas Gregor     /// \brief The 'exhaustive' attribute.
1316*ed84df00SBruno Cardoso Lopes     AT_exhaustive,
1317*ed84df00SBruno Cardoso Lopes     /// \brief The 'no_undeclared_includes' attribute.
1318*ed84df00SBruno Cardoso Lopes     AT_no_undeclared_includes
1319a686e1b0SDouglas Gregor   };
1320ab9db510SAlexander Kornienko }
1321a686e1b0SDouglas Gregor 
1322718292f2SDouglas Gregor /// \brief Parse a module declaration.
1323718292f2SDouglas Gregor ///
1324718292f2SDouglas Gregor ///   module-declaration:
132597292843SDaniel Jasper ///     'extern' 'module' module-id string-literal
1326a686e1b0SDouglas Gregor ///     'explicit'[opt] 'framework'[opt] 'module' module-id attributes[opt]
1327a686e1b0SDouglas Gregor ///       { module-member* }
1328a686e1b0SDouglas Gregor ///
1329718292f2SDouglas Gregor ///   module-member:
13301fb5c3a6SDouglas Gregor ///     requires-declaration
1331718292f2SDouglas Gregor ///     header-declaration
1332e7ab3669SDouglas Gregor ///     submodule-declaration
13332b82c2a5SDouglas Gregor ///     export-declaration
13346ddfca91SDouglas Gregor ///     link-declaration
133573441091SDouglas Gregor ///
133673441091SDouglas Gregor ///   submodule-declaration:
133773441091SDouglas Gregor ///     module-declaration
133873441091SDouglas Gregor ///     inferred-submodule-declaration
1339718292f2SDouglas Gregor void ModuleMapParser::parseModuleDecl() {
1340755b2055SDouglas Gregor   assert(Tok.is(MMToken::ExplicitKeyword) || Tok.is(MMToken::ModuleKeyword) ||
134197292843SDaniel Jasper          Tok.is(MMToken::FrameworkKeyword) || Tok.is(MMToken::ExternKeyword));
134297292843SDaniel Jasper   if (Tok.is(MMToken::ExternKeyword)) {
134397292843SDaniel Jasper     parseExternModuleDecl();
134497292843SDaniel Jasper     return;
134597292843SDaniel Jasper   }
134697292843SDaniel Jasper 
1347f2161a70SDouglas Gregor   // Parse 'explicit' or 'framework' keyword, if present.
1348e7ab3669SDouglas Gregor   SourceLocation ExplicitLoc;
1349718292f2SDouglas Gregor   bool Explicit = false;
1350f2161a70SDouglas Gregor   bool Framework = false;
1351755b2055SDouglas Gregor 
1352f2161a70SDouglas Gregor   // Parse 'explicit' keyword, if present.
1353f2161a70SDouglas Gregor   if (Tok.is(MMToken::ExplicitKeyword)) {
1354e7ab3669SDouglas Gregor     ExplicitLoc = consumeToken();
1355f2161a70SDouglas Gregor     Explicit = true;
1356f2161a70SDouglas Gregor   }
1357f2161a70SDouglas Gregor 
1358f2161a70SDouglas Gregor   // Parse 'framework' keyword, if present.
1359755b2055SDouglas Gregor   if (Tok.is(MMToken::FrameworkKeyword)) {
1360755b2055SDouglas Gregor     consumeToken();
1361755b2055SDouglas Gregor     Framework = true;
1362755b2055SDouglas Gregor   }
1363718292f2SDouglas Gregor 
1364718292f2SDouglas Gregor   // Parse 'module' keyword.
1365718292f2SDouglas Gregor   if (!Tok.is(MMToken::ModuleKeyword)) {
1366d6343c99SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module);
1367718292f2SDouglas Gregor     consumeToken();
1368718292f2SDouglas Gregor     HadError = true;
1369718292f2SDouglas Gregor     return;
1370718292f2SDouglas Gregor   }
1371718292f2SDouglas Gregor   consumeToken(); // 'module' keyword
1372718292f2SDouglas Gregor 
137373441091SDouglas Gregor   // If we have a wildcard for the module name, this is an inferred submodule.
137473441091SDouglas Gregor   // Parse it.
137573441091SDouglas Gregor   if (Tok.is(MMToken::Star))
13769194a91dSDouglas Gregor     return parseInferredModuleDecl(Framework, Explicit);
137773441091SDouglas Gregor 
1378718292f2SDouglas Gregor   // Parse the module name.
1379e7ab3669SDouglas Gregor   ModuleId Id;
1380e7ab3669SDouglas Gregor   if (parseModuleId(Id)) {
1381718292f2SDouglas Gregor     HadError = true;
1382718292f2SDouglas Gregor     return;
1383718292f2SDouglas Gregor   }
1384e7ab3669SDouglas Gregor 
1385e7ab3669SDouglas Gregor   if (ActiveModule) {
1386e7ab3669SDouglas Gregor     if (Id.size() > 1) {
1387e7ab3669SDouglas Gregor       Diags.Report(Id.front().second, diag::err_mmap_nested_submodule_id)
1388e7ab3669SDouglas Gregor         << SourceRange(Id.front().second, Id.back().second);
1389e7ab3669SDouglas Gregor 
1390e7ab3669SDouglas Gregor       HadError = true;
1391e7ab3669SDouglas Gregor       return;
1392e7ab3669SDouglas Gregor     }
1393e7ab3669SDouglas Gregor   } else if (Id.size() == 1 && Explicit) {
1394e7ab3669SDouglas Gregor     // Top-level modules can't be explicit.
1395e7ab3669SDouglas Gregor     Diags.Report(ExplicitLoc, diag::err_mmap_explicit_top_level);
1396e7ab3669SDouglas Gregor     Explicit = false;
1397e7ab3669SDouglas Gregor     ExplicitLoc = SourceLocation();
1398e7ab3669SDouglas Gregor     HadError = true;
1399e7ab3669SDouglas Gregor   }
1400e7ab3669SDouglas Gregor 
1401e7ab3669SDouglas Gregor   Module *PreviousActiveModule = ActiveModule;
1402e7ab3669SDouglas Gregor   if (Id.size() > 1) {
1403e7ab3669SDouglas Gregor     // This module map defines a submodule. Go find the module of which it
1404e7ab3669SDouglas Gregor     // is a submodule.
1405d2d442caSCraig Topper     ActiveModule = nullptr;
14064b8a9e95SBen Langmuir     const Module *TopLevelModule = nullptr;
1407e7ab3669SDouglas Gregor     for (unsigned I = 0, N = Id.size() - 1; I != N; ++I) {
1408e7ab3669SDouglas Gregor       if (Module *Next = Map.lookupModuleQualified(Id[I].first, ActiveModule)) {
14094b8a9e95SBen Langmuir         if (I == 0)
14104b8a9e95SBen Langmuir           TopLevelModule = Next;
1411e7ab3669SDouglas Gregor         ActiveModule = Next;
1412e7ab3669SDouglas Gregor         continue;
1413e7ab3669SDouglas Gregor       }
1414e7ab3669SDouglas Gregor 
1415e7ab3669SDouglas Gregor       if (ActiveModule) {
1416e7ab3669SDouglas Gregor         Diags.Report(Id[I].second, diag::err_mmap_missing_module_qualified)
14175b5d21eaSRichard Smith           << Id[I].first
14185b5d21eaSRichard Smith           << ActiveModule->getTopLevelModule()->getFullModuleName();
1419e7ab3669SDouglas Gregor       } else {
1420e7ab3669SDouglas Gregor         Diags.Report(Id[I].second, diag::err_mmap_expected_module_name);
1421e7ab3669SDouglas Gregor       }
1422e7ab3669SDouglas Gregor       HadError = true;
1423e7ab3669SDouglas Gregor       return;
1424e7ab3669SDouglas Gregor     }
14254b8a9e95SBen Langmuir 
14264b8a9e95SBen Langmuir     if (ModuleMapFile != Map.getContainingModuleMapFile(TopLevelModule)) {
14274b8a9e95SBen Langmuir       assert(ModuleMapFile != Map.getModuleMapFileForUniquing(TopLevelModule) &&
14284b8a9e95SBen Langmuir              "submodule defined in same file as 'module *' that allowed its "
14294b8a9e95SBen Langmuir              "top-level module");
14304b8a9e95SBen Langmuir       Map.addAdditionalModuleMapFile(TopLevelModule, ModuleMapFile);
14314b8a9e95SBen Langmuir     }
1432e7ab3669SDouglas Gregor   }
1433e7ab3669SDouglas Gregor 
1434e7ab3669SDouglas Gregor   StringRef ModuleName = Id.back().first;
1435e7ab3669SDouglas Gregor   SourceLocation ModuleNameLoc = Id.back().second;
1436718292f2SDouglas Gregor 
1437a686e1b0SDouglas Gregor   // Parse the optional attribute list.
14384442605fSBill Wendling   Attributes Attrs;
14395d29dee0SDavide Italiano   if (parseOptionalAttributes(Attrs))
14405d29dee0SDavide Italiano     return;
14415d29dee0SDavide Italiano 
1442a686e1b0SDouglas Gregor 
1443718292f2SDouglas Gregor   // Parse the opening brace.
1444718292f2SDouglas Gregor   if (!Tok.is(MMToken::LBrace)) {
1445718292f2SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_lbrace)
1446718292f2SDouglas Gregor       << ModuleName;
1447718292f2SDouglas Gregor     HadError = true;
1448718292f2SDouglas Gregor     return;
1449718292f2SDouglas Gregor   }
1450718292f2SDouglas Gregor   SourceLocation LBraceLoc = consumeToken();
1451718292f2SDouglas Gregor 
1452718292f2SDouglas Gregor   // Determine whether this (sub)module has already been defined.
1453eb90e830SDouglas Gregor   if (Module *Existing = Map.lookupModuleQualified(ModuleName, ActiveModule)) {
1454fcc54a3bSDouglas Gregor     if (Existing->DefinitionLoc.isInvalid() && !ActiveModule) {
1455fcc54a3bSDouglas Gregor       // Skip the module definition.
1456fcc54a3bSDouglas Gregor       skipUntil(MMToken::RBrace);
1457fcc54a3bSDouglas Gregor       if (Tok.is(MMToken::RBrace))
1458fcc54a3bSDouglas Gregor         consumeToken();
1459fcc54a3bSDouglas Gregor       else {
1460fcc54a3bSDouglas Gregor         Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
1461fcc54a3bSDouglas Gregor         Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
1462fcc54a3bSDouglas Gregor         HadError = true;
1463fcc54a3bSDouglas Gregor       }
1464fcc54a3bSDouglas Gregor       return;
1465fcc54a3bSDouglas Gregor     }
1466fcc54a3bSDouglas Gregor 
1467718292f2SDouglas Gregor     Diags.Report(ModuleNameLoc, diag::err_mmap_module_redefinition)
1468718292f2SDouglas Gregor       << ModuleName;
1469eb90e830SDouglas Gregor     Diags.Report(Existing->DefinitionLoc, diag::note_mmap_prev_definition);
1470718292f2SDouglas Gregor 
1471718292f2SDouglas Gregor     // Skip the module definition.
1472718292f2SDouglas Gregor     skipUntil(MMToken::RBrace);
1473718292f2SDouglas Gregor     if (Tok.is(MMToken::RBrace))
1474718292f2SDouglas Gregor       consumeToken();
1475718292f2SDouglas Gregor 
1476718292f2SDouglas Gregor     HadError = true;
1477718292f2SDouglas Gregor     return;
1478718292f2SDouglas Gregor   }
1479718292f2SDouglas Gregor 
1480718292f2SDouglas Gregor   // Start defining this module.
14819d6448b1SBen Langmuir   ActiveModule = Map.findOrCreateModule(ModuleName, ActiveModule, Framework,
14829d6448b1SBen Langmuir                                         Explicit).first;
1483eb90e830SDouglas Gregor   ActiveModule->DefinitionLoc = ModuleNameLoc;
1484963c5535SDouglas Gregor   if (Attrs.IsSystem || IsSystem)
1485a686e1b0SDouglas Gregor     ActiveModule->IsSystem = true;
148677944868SRichard Smith   if (Attrs.IsExternC)
148777944868SRichard Smith     ActiveModule->IsExternC = true;
1488*ed84df00SBruno Cardoso Lopes   if (Attrs.NoUndeclaredIncludes ||
1489*ed84df00SBruno Cardoso Lopes       (!ActiveModule->Parent && ModuleName == "Darwin"))
1490*ed84df00SBruno Cardoso Lopes     ActiveModule->NoUndeclaredIncludes = true;
14913c1a41adSRichard Smith   ActiveModule->Directory = Directory;
1492718292f2SDouglas Gregor 
1493718292f2SDouglas Gregor   bool Done = false;
1494718292f2SDouglas Gregor   do {
1495718292f2SDouglas Gregor     switch (Tok.Kind) {
1496718292f2SDouglas Gregor     case MMToken::EndOfFile:
1497718292f2SDouglas Gregor     case MMToken::RBrace:
1498718292f2SDouglas Gregor       Done = true;
1499718292f2SDouglas Gregor       break;
1500718292f2SDouglas Gregor 
150135b13eceSDouglas Gregor     case MMToken::ConfigMacros:
150235b13eceSDouglas Gregor       parseConfigMacros();
150335b13eceSDouglas Gregor       break;
150435b13eceSDouglas Gregor 
1505fb912657SDouglas Gregor     case MMToken::Conflict:
1506fb912657SDouglas Gregor       parseConflict();
1507fb912657SDouglas Gregor       break;
1508fb912657SDouglas Gregor 
1509718292f2SDouglas Gregor     case MMToken::ExplicitKeyword:
151097292843SDaniel Jasper     case MMToken::ExternKeyword:
1511f2161a70SDouglas Gregor     case MMToken::FrameworkKeyword:
1512718292f2SDouglas Gregor     case MMToken::ModuleKeyword:
1513718292f2SDouglas Gregor       parseModuleDecl();
1514718292f2SDouglas Gregor       break;
1515718292f2SDouglas Gregor 
15162b82c2a5SDouglas Gregor     case MMToken::ExportKeyword:
15172b82c2a5SDouglas Gregor       parseExportDecl();
15182b82c2a5SDouglas Gregor       break;
15192b82c2a5SDouglas Gregor 
1520ba7f2f71SDaniel Jasper     case MMToken::UseKeyword:
1521ba7f2f71SDaniel Jasper       parseUseDecl();
1522ba7f2f71SDaniel Jasper       break;
1523ba7f2f71SDaniel Jasper 
15241fb5c3a6SDouglas Gregor     case MMToken::RequiresKeyword:
15251fb5c3a6SDouglas Gregor       parseRequiresDecl();
15261fb5c3a6SDouglas Gregor       break;
15271fb5c3a6SDouglas Gregor 
1528202210b3SRichard Smith     case MMToken::TextualKeyword:
1529202210b3SRichard Smith       parseHeaderDecl(MMToken::TextualKeyword, consumeToken());
1530306d8920SRichard Smith       break;
1531306d8920SRichard Smith 
1532524e33e1SDouglas Gregor     case MMToken::UmbrellaKeyword: {
1533524e33e1SDouglas Gregor       SourceLocation UmbrellaLoc = consumeToken();
1534524e33e1SDouglas Gregor       if (Tok.is(MMToken::HeaderKeyword))
1535b53e5483SLawrence Crowl         parseHeaderDecl(MMToken::UmbrellaKeyword, UmbrellaLoc);
1536524e33e1SDouglas Gregor       else
1537524e33e1SDouglas Gregor         parseUmbrellaDirDecl(UmbrellaLoc);
1538718292f2SDouglas Gregor       break;
1539524e33e1SDouglas Gregor     }
1540718292f2SDouglas Gregor 
1541202210b3SRichard Smith     case MMToken::ExcludeKeyword:
1542202210b3SRichard Smith       parseHeaderDecl(MMToken::ExcludeKeyword, consumeToken());
154359527666SDouglas Gregor       break;
154459527666SDouglas Gregor 
1545202210b3SRichard Smith     case MMToken::PrivateKeyword:
1546202210b3SRichard Smith       parseHeaderDecl(MMToken::PrivateKeyword, consumeToken());
1547b53e5483SLawrence Crowl       break;
1548b53e5483SLawrence Crowl 
1549322f633cSDouglas Gregor     case MMToken::HeaderKeyword:
1550202210b3SRichard Smith       parseHeaderDecl(MMToken::HeaderKeyword, consumeToken());
1551718292f2SDouglas Gregor       break;
1552718292f2SDouglas Gregor 
15536ddfca91SDouglas Gregor     case MMToken::LinkKeyword:
15546ddfca91SDouglas Gregor       parseLinkDecl();
15556ddfca91SDouglas Gregor       break;
15566ddfca91SDouglas Gregor 
1557718292f2SDouglas Gregor     default:
1558718292f2SDouglas Gregor       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_member);
1559718292f2SDouglas Gregor       consumeToken();
1560718292f2SDouglas Gregor       break;
1561718292f2SDouglas Gregor     }
1562718292f2SDouglas Gregor   } while (!Done);
1563718292f2SDouglas Gregor 
1564718292f2SDouglas Gregor   if (Tok.is(MMToken::RBrace))
1565718292f2SDouglas Gregor     consumeToken();
1566718292f2SDouglas Gregor   else {
1567718292f2SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
1568718292f2SDouglas Gregor     Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
1569718292f2SDouglas Gregor     HadError = true;
1570718292f2SDouglas Gregor   }
1571718292f2SDouglas Gregor 
157211dfe6feSDouglas Gregor   // If the active module is a top-level framework, and there are no link
157311dfe6feSDouglas Gregor   // libraries, automatically link against the framework.
157411dfe6feSDouglas Gregor   if (ActiveModule->IsFramework && !ActiveModule->isSubFramework() &&
157511dfe6feSDouglas Gregor       ActiveModule->LinkLibraries.empty()) {
157611dfe6feSDouglas Gregor     inferFrameworkLink(ActiveModule, Directory, SourceMgr.getFileManager());
157711dfe6feSDouglas Gregor   }
157811dfe6feSDouglas Gregor 
1579ec8c9752SBen Langmuir   // If the module meets all requirements but is still unavailable, mark the
1580ec8c9752SBen Langmuir   // whole tree as unavailable to prevent it from building.
1581ec8c9752SBen Langmuir   if (!ActiveModule->IsAvailable && !ActiveModule->IsMissingRequirement &&
1582ec8c9752SBen Langmuir       ActiveModule->Parent) {
1583ec8c9752SBen Langmuir     ActiveModule->getTopLevelModule()->markUnavailable();
1584ec8c9752SBen Langmuir     ActiveModule->getTopLevelModule()->MissingHeaders.append(
1585ec8c9752SBen Langmuir       ActiveModule->MissingHeaders.begin(), ActiveModule->MissingHeaders.end());
1586ec8c9752SBen Langmuir   }
1587ec8c9752SBen Langmuir 
1588e7ab3669SDouglas Gregor   // We're done parsing this module. Pop back to the previous module.
1589e7ab3669SDouglas Gregor   ActiveModule = PreviousActiveModule;
1590718292f2SDouglas Gregor }
1591718292f2SDouglas Gregor 
159297292843SDaniel Jasper /// \brief Parse an extern module declaration.
159397292843SDaniel Jasper ///
159497292843SDaniel Jasper ///   extern module-declaration:
159597292843SDaniel Jasper ///     'extern' 'module' module-id string-literal
159697292843SDaniel Jasper void ModuleMapParser::parseExternModuleDecl() {
159797292843SDaniel Jasper   assert(Tok.is(MMToken::ExternKeyword));
1598ae6df27eSRichard Smith   SourceLocation ExternLoc = consumeToken(); // 'extern' keyword
159997292843SDaniel Jasper 
160097292843SDaniel Jasper   // Parse 'module' keyword.
160197292843SDaniel Jasper   if (!Tok.is(MMToken::ModuleKeyword)) {
160297292843SDaniel Jasper     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module);
160397292843SDaniel Jasper     consumeToken();
160497292843SDaniel Jasper     HadError = true;
160597292843SDaniel Jasper     return;
160697292843SDaniel Jasper   }
160797292843SDaniel Jasper   consumeToken(); // 'module' keyword
160897292843SDaniel Jasper 
160997292843SDaniel Jasper   // Parse the module name.
161097292843SDaniel Jasper   ModuleId Id;
161197292843SDaniel Jasper   if (parseModuleId(Id)) {
161297292843SDaniel Jasper     HadError = true;
161397292843SDaniel Jasper     return;
161497292843SDaniel Jasper   }
161597292843SDaniel Jasper 
161697292843SDaniel Jasper   // Parse the referenced module map file name.
161797292843SDaniel Jasper   if (!Tok.is(MMToken::StringLiteral)) {
161897292843SDaniel Jasper     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_mmap_file);
161997292843SDaniel Jasper     HadError = true;
162097292843SDaniel Jasper     return;
162197292843SDaniel Jasper   }
162297292843SDaniel Jasper   std::string FileName = Tok.getString();
162397292843SDaniel Jasper   consumeToken(); // filename
162497292843SDaniel Jasper 
162597292843SDaniel Jasper   StringRef FileNameRef = FileName;
162697292843SDaniel Jasper   SmallString<128> ModuleMapFileName;
162797292843SDaniel Jasper   if (llvm::sys::path::is_relative(FileNameRef)) {
162897292843SDaniel Jasper     ModuleMapFileName += Directory->getName();
162997292843SDaniel Jasper     llvm::sys::path::append(ModuleMapFileName, FileName);
163092e1b62dSYaron Keren     FileNameRef = ModuleMapFileName;
163197292843SDaniel Jasper   }
163297292843SDaniel Jasper   if (const FileEntry *File = SourceMgr.getFileManager().getFile(FileNameRef))
16339acb99e3SRichard Smith     Map.parseModuleMapFile(
16349acb99e3SRichard Smith         File, /*IsSystem=*/false,
16359acb99e3SRichard Smith         Map.HeaderInfo.getHeaderSearchOpts().ModuleMapFileHomeIsCwd
16369acb99e3SRichard Smith             ? Directory
1637ae6df27eSRichard Smith             : File->getDir(), ExternLoc);
163897292843SDaniel Jasper }
163997292843SDaniel Jasper 
16407ff29148SBen Langmuir /// Whether to add the requirement \p Feature to the module \p M.
16417ff29148SBen Langmuir ///
16427ff29148SBen Langmuir /// This preserves backwards compatibility for two hacks in the Darwin system
16437ff29148SBen Langmuir /// module map files:
16447ff29148SBen Langmuir ///
16457ff29148SBen Langmuir /// 1. The use of 'requires excluded' to make headers non-modular, which
16467ff29148SBen Langmuir ///    should really be mapped to 'textual' now that we have this feature.  We
16477ff29148SBen Langmuir ///    drop the 'excluded' requirement, and set \p IsRequiresExcludedHack to
16487ff29148SBen Langmuir ///    true.  Later, this bit will be used to map all the headers inside this
16497ff29148SBen Langmuir ///    module to 'textual'.
16507ff29148SBen Langmuir ///
16517ff29148SBen Langmuir ///    This affects Darwin.C.excluded (for assert.h) and Tcl.Private.
16527ff29148SBen Langmuir ///
16537ff29148SBen Langmuir /// 2. Removes a bogus cplusplus requirement from IOKit.avc.  This requirement
16547ff29148SBen Langmuir ///    was never correct and causes issues now that we check it, so drop it.
16557ff29148SBen Langmuir static bool shouldAddRequirement(Module *M, StringRef Feature,
16567ff29148SBen Langmuir                                  bool &IsRequiresExcludedHack) {
16577ff29148SBen Langmuir   static const StringRef DarwinCExcluded[] = {"Darwin", "C", "excluded"};
16587ff29148SBen Langmuir   static const StringRef TclPrivate[] = {"Tcl", "Private"};
16597ff29148SBen Langmuir   static const StringRef IOKitAVC[] = {"IOKit", "avc"};
16607ff29148SBen Langmuir 
16617ff29148SBen Langmuir   if (Feature == "excluded" && (M->fullModuleNameIs(DarwinCExcluded) ||
16627ff29148SBen Langmuir                                 M->fullModuleNameIs(TclPrivate))) {
16637ff29148SBen Langmuir     IsRequiresExcludedHack = true;
16647ff29148SBen Langmuir     return false;
16657ff29148SBen Langmuir   } else if (Feature == "cplusplus" && M->fullModuleNameIs(IOKitAVC)) {
16667ff29148SBen Langmuir     return false;
16677ff29148SBen Langmuir   }
16687ff29148SBen Langmuir 
16697ff29148SBen Langmuir   return true;
16707ff29148SBen Langmuir }
16717ff29148SBen Langmuir 
16721fb5c3a6SDouglas Gregor /// \brief Parse a requires declaration.
16731fb5c3a6SDouglas Gregor ///
16741fb5c3a6SDouglas Gregor ///   requires-declaration:
16751fb5c3a6SDouglas Gregor ///     'requires' feature-list
16761fb5c3a6SDouglas Gregor ///
16771fb5c3a6SDouglas Gregor ///   feature-list:
1678a3feee2aSRichard Smith ///     feature ',' feature-list
1679a3feee2aSRichard Smith ///     feature
1680a3feee2aSRichard Smith ///
1681a3feee2aSRichard Smith ///   feature:
1682a3feee2aSRichard Smith ///     '!'[opt] identifier
16831fb5c3a6SDouglas Gregor void ModuleMapParser::parseRequiresDecl() {
16841fb5c3a6SDouglas Gregor   assert(Tok.is(MMToken::RequiresKeyword));
16851fb5c3a6SDouglas Gregor 
16861fb5c3a6SDouglas Gregor   // Parse 'requires' keyword.
16871fb5c3a6SDouglas Gregor   consumeToken();
16881fb5c3a6SDouglas Gregor 
16891fb5c3a6SDouglas Gregor   // Parse the feature-list.
16901fb5c3a6SDouglas Gregor   do {
1691a3feee2aSRichard Smith     bool RequiredState = true;
1692a3feee2aSRichard Smith     if (Tok.is(MMToken::Exclaim)) {
1693a3feee2aSRichard Smith       RequiredState = false;
1694a3feee2aSRichard Smith       consumeToken();
1695a3feee2aSRichard Smith     }
1696a3feee2aSRichard Smith 
16971fb5c3a6SDouglas Gregor     if (!Tok.is(MMToken::Identifier)) {
16981fb5c3a6SDouglas Gregor       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_feature);
16991fb5c3a6SDouglas Gregor       HadError = true;
17001fb5c3a6SDouglas Gregor       return;
17011fb5c3a6SDouglas Gregor     }
17021fb5c3a6SDouglas Gregor 
17031fb5c3a6SDouglas Gregor     // Consume the feature name.
17041fb5c3a6SDouglas Gregor     std::string Feature = Tok.getString();
17051fb5c3a6SDouglas Gregor     consumeToken();
17061fb5c3a6SDouglas Gregor 
17077ff29148SBen Langmuir     bool IsRequiresExcludedHack = false;
17087ff29148SBen Langmuir     bool ShouldAddRequirement =
17097ff29148SBen Langmuir         shouldAddRequirement(ActiveModule, Feature, IsRequiresExcludedHack);
17107ff29148SBen Langmuir 
17117ff29148SBen Langmuir     if (IsRequiresExcludedHack)
17127ff29148SBen Langmuir       UsesRequiresExcludedHack.insert(ActiveModule);
17137ff29148SBen Langmuir 
17147ff29148SBen Langmuir     if (ShouldAddRequirement) {
17151fb5c3a6SDouglas Gregor       // Add this feature.
17167ff29148SBen Langmuir       ActiveModule->addRequirement(Feature, RequiredState, Map.LangOpts,
17177ff29148SBen Langmuir                                    *Map.Target);
17187ff29148SBen Langmuir     }
17191fb5c3a6SDouglas Gregor 
17201fb5c3a6SDouglas Gregor     if (!Tok.is(MMToken::Comma))
17211fb5c3a6SDouglas Gregor       break;
17221fb5c3a6SDouglas Gregor 
17231fb5c3a6SDouglas Gregor     // Consume the comma.
17241fb5c3a6SDouglas Gregor     consumeToken();
17251fb5c3a6SDouglas Gregor   } while (true);
17261fb5c3a6SDouglas Gregor }
17271fb5c3a6SDouglas Gregor 
1728f2161a70SDouglas Gregor /// \brief Append to \p Paths the set of paths needed to get to the
1729f2161a70SDouglas Gregor /// subframework in which the given module lives.
1730bf8da9d7SBenjamin Kramer static void appendSubframeworkPaths(Module *Mod,
1731f857950dSDmitri Gribenko                                     SmallVectorImpl<char> &Path) {
1732f2161a70SDouglas Gregor   // Collect the framework names from the given module to the top-level module.
1733f857950dSDmitri Gribenko   SmallVector<StringRef, 2> Paths;
1734f2161a70SDouglas Gregor   for (; Mod; Mod = Mod->Parent) {
1735f2161a70SDouglas Gregor     if (Mod->IsFramework)
1736f2161a70SDouglas Gregor       Paths.push_back(Mod->Name);
1737f2161a70SDouglas Gregor   }
1738f2161a70SDouglas Gregor 
1739f2161a70SDouglas Gregor   if (Paths.empty())
1740f2161a70SDouglas Gregor     return;
1741f2161a70SDouglas Gregor 
1742f2161a70SDouglas Gregor   // Add Frameworks/Name.framework for each subframework.
174317381a06SBenjamin Kramer   for (unsigned I = Paths.size() - 1; I != 0; --I)
174417381a06SBenjamin Kramer     llvm::sys::path::append(Path, "Frameworks", Paths[I-1] + ".framework");
1745f2161a70SDouglas Gregor }
1746f2161a70SDouglas Gregor 
1747718292f2SDouglas Gregor /// \brief Parse a header declaration.
1748718292f2SDouglas Gregor ///
1749718292f2SDouglas Gregor ///   header-declaration:
1750306d8920SRichard Smith ///     'textual'[opt] 'header' string-literal
1751202210b3SRichard Smith ///     'private' 'textual'[opt] 'header' string-literal
1752202210b3SRichard Smith ///     'exclude' 'header' string-literal
1753202210b3SRichard Smith ///     'umbrella' 'header' string-literal
1754306d8920SRichard Smith ///
1755306d8920SRichard Smith /// FIXME: Support 'private textual header'.
1756b53e5483SLawrence Crowl void ModuleMapParser::parseHeaderDecl(MMToken::TokenKind LeadingToken,
1757b53e5483SLawrence Crowl                                       SourceLocation LeadingLoc) {
1758202210b3SRichard Smith   // We've already consumed the first token.
1759202210b3SRichard Smith   ModuleMap::ModuleHeaderRole Role = ModuleMap::NormalHeader;
1760202210b3SRichard Smith   if (LeadingToken == MMToken::PrivateKeyword) {
1761202210b3SRichard Smith     Role = ModuleMap::PrivateHeader;
1762202210b3SRichard Smith     // 'private' may optionally be followed by 'textual'.
1763202210b3SRichard Smith     if (Tok.is(MMToken::TextualKeyword)) {
1764202210b3SRichard Smith       LeadingToken = Tok.Kind;
17651871ed3dSBenjamin Kramer       consumeToken();
1766202210b3SRichard Smith     }
1767202210b3SRichard Smith   }
17687ff29148SBen Langmuir 
1769202210b3SRichard Smith   if (LeadingToken == MMToken::TextualKeyword)
1770202210b3SRichard Smith     Role = ModuleMap::ModuleHeaderRole(Role | ModuleMap::TextualHeader);
1771202210b3SRichard Smith 
17727ff29148SBen Langmuir   if (UsesRequiresExcludedHack.count(ActiveModule)) {
17737ff29148SBen Langmuir     // Mark this header 'textual' (see doc comment for
17747ff29148SBen Langmuir     // Module::UsesRequiresExcludedHack).
17757ff29148SBen Langmuir     Role = ModuleMap::ModuleHeaderRole(Role | ModuleMap::TextualHeader);
17767ff29148SBen Langmuir   }
17777ff29148SBen Langmuir 
1778202210b3SRichard Smith   if (LeadingToken != MMToken::HeaderKeyword) {
1779202210b3SRichard Smith     if (!Tok.is(MMToken::HeaderKeyword)) {
1780202210b3SRichard Smith       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
1781202210b3SRichard Smith           << (LeadingToken == MMToken::PrivateKeyword ? "private" :
1782202210b3SRichard Smith               LeadingToken == MMToken::ExcludeKeyword ? "exclude" :
1783202210b3SRichard Smith               LeadingToken == MMToken::TextualKeyword ? "textual" : "umbrella");
1784202210b3SRichard Smith       return;
1785202210b3SRichard Smith     }
1786202210b3SRichard Smith     consumeToken();
1787202210b3SRichard Smith   }
1788718292f2SDouglas Gregor 
1789718292f2SDouglas Gregor   // Parse the header name.
1790718292f2SDouglas Gregor   if (!Tok.is(MMToken::StringLiteral)) {
1791718292f2SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
1792718292f2SDouglas Gregor       << "header";
1793718292f2SDouglas Gregor     HadError = true;
1794718292f2SDouglas Gregor     return;
1795718292f2SDouglas Gregor   }
17963c1a41adSRichard Smith   Module::UnresolvedHeaderDirective Header;
17970761a8a0SDaniel Jasper   Header.FileName = Tok.getString();
17980761a8a0SDaniel Jasper   Header.FileNameLoc = consumeToken();
1799718292f2SDouglas Gregor 
1800524e33e1SDouglas Gregor   // Check whether we already have an umbrella.
1801b53e5483SLawrence Crowl   if (LeadingToken == MMToken::UmbrellaKeyword && ActiveModule->Umbrella) {
18020761a8a0SDaniel Jasper     Diags.Report(Header.FileNameLoc, diag::err_mmap_umbrella_clash)
1803524e33e1SDouglas Gregor       << ActiveModule->getFullModuleName();
1804322f633cSDouglas Gregor     HadError = true;
1805322f633cSDouglas Gregor     return;
1806322f633cSDouglas Gregor   }
1807322f633cSDouglas Gregor 
18085257fc63SDouglas Gregor   // Look for this file.
1809d2d442caSCraig Topper   const FileEntry *File = nullptr;
1810d2d442caSCraig Topper   const FileEntry *BuiltinFile = nullptr;
18113c1a41adSRichard Smith   SmallString<128> RelativePathName;
18120761a8a0SDaniel Jasper   if (llvm::sys::path::is_absolute(Header.FileName)) {
18133c1a41adSRichard Smith     RelativePathName = Header.FileName;
18143c1a41adSRichard Smith     File = SourceMgr.getFileManager().getFile(RelativePathName);
1815e7ab3669SDouglas Gregor   } else {
1816e7ab3669SDouglas Gregor     // Search for the header file within the search directory.
18173c1a41adSRichard Smith     SmallString<128> FullPathName(Directory->getName());
18183c1a41adSRichard Smith     unsigned FullPathLength = FullPathName.size();
1819755b2055SDouglas Gregor 
1820f2161a70SDouglas Gregor     if (ActiveModule->isPartOfFramework()) {
18213c1a41adSRichard Smith       appendSubframeworkPaths(ActiveModule, RelativePathName);
1822755b2055SDouglas Gregor 
1823e7ab3669SDouglas Gregor       // Check whether this file is in the public headers.
18243c1a41adSRichard Smith       llvm::sys::path::append(RelativePathName, "Headers", Header.FileName);
182592e1b62dSYaron Keren       llvm::sys::path::append(FullPathName, RelativePathName);
18263c1a41adSRichard Smith       File = SourceMgr.getFileManager().getFile(FullPathName);
1827e7ab3669SDouglas Gregor 
1828e7ab3669SDouglas Gregor       if (!File) {
1829e7ab3669SDouglas Gregor         // Check whether this file is in the private headers.
18303c1a41adSRichard Smith         // FIXME: Should we retain the subframework paths here?
18313c1a41adSRichard Smith         RelativePathName.clear();
18323c1a41adSRichard Smith         FullPathName.resize(FullPathLength);
18333c1a41adSRichard Smith         llvm::sys::path::append(RelativePathName, "PrivateHeaders",
18343c1a41adSRichard Smith                                 Header.FileName);
183592e1b62dSYaron Keren         llvm::sys::path::append(FullPathName, RelativePathName);
18363c1a41adSRichard Smith         File = SourceMgr.getFileManager().getFile(FullPathName);
1837e7ab3669SDouglas Gregor       }
1838e7ab3669SDouglas Gregor     } else {
1839e7ab3669SDouglas Gregor       // Lookup for normal headers.
18403c1a41adSRichard Smith       llvm::sys::path::append(RelativePathName, Header.FileName);
184192e1b62dSYaron Keren       llvm::sys::path::append(FullPathName, RelativePathName);
18423c1a41adSRichard Smith       File = SourceMgr.getFileManager().getFile(FullPathName);
18433ec6663bSDouglas Gregor 
18443ec6663bSDouglas Gregor       // If this is a system module with a top-level header, this header
18453ec6663bSDouglas Gregor       // may have a counterpart (or replacement) in the set of headers
18463ec6663bSDouglas Gregor       // supplied by Clang. Find that builtin header.
1847b53e5483SLawrence Crowl       if (ActiveModule->IsSystem && LeadingToken != MMToken::UmbrellaKeyword &&
1848b53e5483SLawrence Crowl           BuiltinIncludeDir && BuiltinIncludeDir != Directory &&
18490761a8a0SDaniel Jasper           isBuiltinHeader(Header.FileName)) {
18502c1dd271SDylan Noblesmith         SmallString<128> BuiltinPathName(BuiltinIncludeDir->getName());
18510761a8a0SDaniel Jasper         llvm::sys::path::append(BuiltinPathName, Header.FileName);
18523ec6663bSDouglas Gregor         BuiltinFile = SourceMgr.getFileManager().getFile(BuiltinPathName);
18533ec6663bSDouglas Gregor 
18543ec6663bSDouglas Gregor         // If Clang supplies this header but the underlying system does not,
18553ec6663bSDouglas Gregor         // just silently swap in our builtin version. Otherwise, we'll end
18563ec6663bSDouglas Gregor         // up adding both (later).
1857*ed84df00SBruno Cardoso Lopes         if (BuiltinFile && !File) {
18583ec6663bSDouglas Gregor           File = BuiltinFile;
18593c1a41adSRichard Smith           RelativePathName = BuiltinPathName;
1860d2d442caSCraig Topper           BuiltinFile = nullptr;
18613ec6663bSDouglas Gregor         }
18623ec6663bSDouglas Gregor       }
1863e7ab3669SDouglas Gregor     }
1864e7ab3669SDouglas Gregor   }
18655257fc63SDouglas Gregor 
18665257fc63SDouglas Gregor   // FIXME: We shouldn't be eagerly stat'ing every file named in a module map.
18675257fc63SDouglas Gregor   // Come up with a lazy way to do this.
1868e7ab3669SDouglas Gregor   if (File) {
186997da9178SDaniel Jasper     if (LeadingToken == MMToken::UmbrellaKeyword) {
1870322f633cSDouglas Gregor       const DirectoryEntry *UmbrellaDir = File->getDir();
187159527666SDouglas Gregor       if (Module *UmbrellaModule = Map.UmbrellaDirs[UmbrellaDir]) {
1872b53e5483SLawrence Crowl         Diags.Report(LeadingLoc, diag::err_mmap_umbrella_clash)
187359527666SDouglas Gregor           << UmbrellaModule->getFullModuleName();
1874322f633cSDouglas Gregor         HadError = true;
18755257fc63SDouglas Gregor       } else {
1876322f633cSDouglas Gregor         // Record this umbrella header.
18772b63d15fSRichard Smith         Map.setUmbrellaHeader(ActiveModule, File, RelativePathName.str());
1878322f633cSDouglas Gregor       }
1879feb54b6dSRichard Smith     } else if (LeadingToken == MMToken::ExcludeKeyword) {
18800101b540SHans Wennborg       Module::Header H = {RelativePathName.str(), File};
18810101b540SHans Wennborg       Map.excludeHeader(ActiveModule, H);
1882322f633cSDouglas Gregor     } else {
1883*ed84df00SBruno Cardoso Lopes       // If there is a builtin counterpart to this file, add it now as a textual
1884*ed84df00SBruno Cardoso Lopes       // header, so it can be #include_next'd by the wrapper header, and can
1885*ed84df00SBruno Cardoso Lopes       // receive macros from the wrapper header.
18860101b540SHans Wennborg       if (BuiltinFile) {
18873c1a41adSRichard Smith         // FIXME: Taking the name from the FileEntry is unstable and can give
18883c1a41adSRichard Smith         // different results depending on how we've previously named that file
18893c1a41adSRichard Smith         // in this build.
18900101b540SHans Wennborg         Module::Header H = { BuiltinFile->getName(), BuiltinFile };
1891*ed84df00SBruno Cardoso Lopes         Map.addHeader(ActiveModule, H, ModuleMap::ModuleHeaderRole(
1892*ed84df00SBruno Cardoso Lopes                                            Role | ModuleMap::TextualHeader));
18930101b540SHans Wennborg       }
189425d50758SRichard Smith 
1895202210b3SRichard Smith       // Record this header.
18960101b540SHans Wennborg       Module::Header H = { RelativePathName.str(), File };
18970101b540SHans Wennborg       Map.addHeader(ActiveModule, H, Role);
18985257fc63SDouglas Gregor     }
1899b53e5483SLawrence Crowl   } else if (LeadingToken != MMToken::ExcludeKeyword) {
19004b27a64bSDouglas Gregor     // Ignore excluded header files. They're optional anyway.
19014b27a64bSDouglas Gregor 
19020761a8a0SDaniel Jasper     // If we find a module that has a missing header, we mark this module as
19030761a8a0SDaniel Jasper     // unavailable and store the header directive for displaying diagnostics.
19040761a8a0SDaniel Jasper     Header.IsUmbrella = LeadingToken == MMToken::UmbrellaKeyword;
1905ec8c9752SBen Langmuir     ActiveModule->markUnavailable();
19060761a8a0SDaniel Jasper     ActiveModule->MissingHeaders.push_back(Header);
19075257fc63SDouglas Gregor   }
1908718292f2SDouglas Gregor }
1909718292f2SDouglas Gregor 
191041f81994SBen Langmuir static int compareModuleHeaders(const Module::Header *A,
191141f81994SBen Langmuir                                 const Module::Header *B) {
191241f81994SBen Langmuir   return A->NameAsWritten.compare(B->NameAsWritten);
191341f81994SBen Langmuir }
191441f81994SBen Langmuir 
1915524e33e1SDouglas Gregor /// \brief Parse an umbrella directory declaration.
1916524e33e1SDouglas Gregor ///
1917524e33e1SDouglas Gregor ///   umbrella-dir-declaration:
1918524e33e1SDouglas Gregor ///     umbrella string-literal
1919524e33e1SDouglas Gregor void ModuleMapParser::parseUmbrellaDirDecl(SourceLocation UmbrellaLoc) {
1920524e33e1SDouglas Gregor   // Parse the directory name.
1921524e33e1SDouglas Gregor   if (!Tok.is(MMToken::StringLiteral)) {
1922524e33e1SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
1923524e33e1SDouglas Gregor       << "umbrella";
1924524e33e1SDouglas Gregor     HadError = true;
1925524e33e1SDouglas Gregor     return;
1926524e33e1SDouglas Gregor   }
1927524e33e1SDouglas Gregor 
1928524e33e1SDouglas Gregor   std::string DirName = Tok.getString();
1929524e33e1SDouglas Gregor   SourceLocation DirNameLoc = consumeToken();
1930524e33e1SDouglas Gregor 
1931524e33e1SDouglas Gregor   // Check whether we already have an umbrella.
1932524e33e1SDouglas Gregor   if (ActiveModule->Umbrella) {
1933524e33e1SDouglas Gregor     Diags.Report(DirNameLoc, diag::err_mmap_umbrella_clash)
1934524e33e1SDouglas Gregor       << ActiveModule->getFullModuleName();
1935524e33e1SDouglas Gregor     HadError = true;
1936524e33e1SDouglas Gregor     return;
1937524e33e1SDouglas Gregor   }
1938524e33e1SDouglas Gregor 
1939524e33e1SDouglas Gregor   // Look for this file.
1940d2d442caSCraig Topper   const DirectoryEntry *Dir = nullptr;
1941524e33e1SDouglas Gregor   if (llvm::sys::path::is_absolute(DirName))
1942524e33e1SDouglas Gregor     Dir = SourceMgr.getFileManager().getDirectory(DirName);
1943524e33e1SDouglas Gregor   else {
19442c1dd271SDylan Noblesmith     SmallString<128> PathName;
1945524e33e1SDouglas Gregor     PathName = Directory->getName();
1946524e33e1SDouglas Gregor     llvm::sys::path::append(PathName, DirName);
1947524e33e1SDouglas Gregor     Dir = SourceMgr.getFileManager().getDirectory(PathName);
1948524e33e1SDouglas Gregor   }
1949524e33e1SDouglas Gregor 
1950524e33e1SDouglas Gregor   if (!Dir) {
1951524e33e1SDouglas Gregor     Diags.Report(DirNameLoc, diag::err_mmap_umbrella_dir_not_found)
1952524e33e1SDouglas Gregor       << DirName;
1953524e33e1SDouglas Gregor     HadError = true;
1954524e33e1SDouglas Gregor     return;
1955524e33e1SDouglas Gregor   }
1956524e33e1SDouglas Gregor 
19577ff29148SBen Langmuir   if (UsesRequiresExcludedHack.count(ActiveModule)) {
19587ff29148SBen Langmuir     // Mark this header 'textual' (see doc comment for
19597ff29148SBen Langmuir     // ModuleMapParser::UsesRequiresExcludedHack). Although iterating over the
19607ff29148SBen Langmuir     // directory is relatively expensive, in practice this only applies to the
19617ff29148SBen Langmuir     // uncommonly used Tcl module on Darwin platforms.
19627ff29148SBen Langmuir     std::error_code EC;
19637ff29148SBen Langmuir     SmallVector<Module::Header, 6> Headers;
1964b171a59bSBruno Cardoso Lopes     vfs::FileSystem &FS = *SourceMgr.getFileManager().getVirtualFileSystem();
1965b171a59bSBruno Cardoso Lopes     for (vfs::recursive_directory_iterator I(FS, Dir->getName(), EC), E;
19667ff29148SBen Langmuir          I != E && !EC; I.increment(EC)) {
1967b171a59bSBruno Cardoso Lopes       if (const FileEntry *FE =
1968b171a59bSBruno Cardoso Lopes               SourceMgr.getFileManager().getFile(I->getName())) {
19697ff29148SBen Langmuir 
1970b171a59bSBruno Cardoso Lopes         Module::Header Header = {I->getName(), FE};
19717ff29148SBen Langmuir         Headers.push_back(std::move(Header));
19727ff29148SBen Langmuir       }
19737ff29148SBen Langmuir     }
19747ff29148SBen Langmuir 
19757ff29148SBen Langmuir     // Sort header paths so that the pcm doesn't depend on iteration order.
197641f81994SBen Langmuir     llvm::array_pod_sort(Headers.begin(), Headers.end(), compareModuleHeaders);
197741f81994SBen Langmuir 
19787ff29148SBen Langmuir     for (auto &Header : Headers)
19797ff29148SBen Langmuir       Map.addHeader(ActiveModule, std::move(Header), ModuleMap::TextualHeader);
19807ff29148SBen Langmuir     return;
19817ff29148SBen Langmuir   }
19827ff29148SBen Langmuir 
1983524e33e1SDouglas Gregor   if (Module *OwningModule = Map.UmbrellaDirs[Dir]) {
1984524e33e1SDouglas Gregor     Diags.Report(UmbrellaLoc, diag::err_mmap_umbrella_clash)
1985524e33e1SDouglas Gregor       << OwningModule->getFullModuleName();
1986524e33e1SDouglas Gregor     HadError = true;
1987524e33e1SDouglas Gregor     return;
1988524e33e1SDouglas Gregor   }
1989524e33e1SDouglas Gregor 
1990524e33e1SDouglas Gregor   // Record this umbrella directory.
19912b63d15fSRichard Smith   Map.setUmbrellaDir(ActiveModule, Dir, DirName);
1992524e33e1SDouglas Gregor }
1993524e33e1SDouglas Gregor 
19942b82c2a5SDouglas Gregor /// \brief Parse a module export declaration.
19952b82c2a5SDouglas Gregor ///
19962b82c2a5SDouglas Gregor ///   export-declaration:
19972b82c2a5SDouglas Gregor ///     'export' wildcard-module-id
19982b82c2a5SDouglas Gregor ///
19992b82c2a5SDouglas Gregor ///   wildcard-module-id:
20002b82c2a5SDouglas Gregor ///     identifier
20012b82c2a5SDouglas Gregor ///     '*'
20022b82c2a5SDouglas Gregor ///     identifier '.' wildcard-module-id
20032b82c2a5SDouglas Gregor void ModuleMapParser::parseExportDecl() {
20042b82c2a5SDouglas Gregor   assert(Tok.is(MMToken::ExportKeyword));
20052b82c2a5SDouglas Gregor   SourceLocation ExportLoc = consumeToken();
20062b82c2a5SDouglas Gregor 
20072b82c2a5SDouglas Gregor   // Parse the module-id with an optional wildcard at the end.
20082b82c2a5SDouglas Gregor   ModuleId ParsedModuleId;
20092b82c2a5SDouglas Gregor   bool Wildcard = false;
20102b82c2a5SDouglas Gregor   do {
2011306d8920SRichard Smith     // FIXME: Support string-literal module names here.
20122b82c2a5SDouglas Gregor     if (Tok.is(MMToken::Identifier)) {
20132b82c2a5SDouglas Gregor       ParsedModuleId.push_back(std::make_pair(Tok.getString(),
20142b82c2a5SDouglas Gregor                                               Tok.getLocation()));
20152b82c2a5SDouglas Gregor       consumeToken();
20162b82c2a5SDouglas Gregor 
20172b82c2a5SDouglas Gregor       if (Tok.is(MMToken::Period)) {
20182b82c2a5SDouglas Gregor         consumeToken();
20192b82c2a5SDouglas Gregor         continue;
20202b82c2a5SDouglas Gregor       }
20212b82c2a5SDouglas Gregor 
20222b82c2a5SDouglas Gregor       break;
20232b82c2a5SDouglas Gregor     }
20242b82c2a5SDouglas Gregor 
20252b82c2a5SDouglas Gregor     if(Tok.is(MMToken::Star)) {
20262b82c2a5SDouglas Gregor       Wildcard = true;
2027f5eedd05SDouglas Gregor       consumeToken();
20282b82c2a5SDouglas Gregor       break;
20292b82c2a5SDouglas Gregor     }
20302b82c2a5SDouglas Gregor 
2031ba7f2f71SDaniel Jasper     Diags.Report(Tok.getLocation(), diag::err_mmap_module_id);
20322b82c2a5SDouglas Gregor     HadError = true;
20332b82c2a5SDouglas Gregor     return;
20342b82c2a5SDouglas Gregor   } while (true);
20352b82c2a5SDouglas Gregor 
20362b82c2a5SDouglas Gregor   Module::UnresolvedExportDecl Unresolved = {
20372b82c2a5SDouglas Gregor     ExportLoc, ParsedModuleId, Wildcard
20382b82c2a5SDouglas Gregor   };
20392b82c2a5SDouglas Gregor   ActiveModule->UnresolvedExports.push_back(Unresolved);
20402b82c2a5SDouglas Gregor }
20412b82c2a5SDouglas Gregor 
20428f4d3ff1SRichard Smith /// \brief Parse a module use declaration.
2043ba7f2f71SDaniel Jasper ///
20448f4d3ff1SRichard Smith ///   use-declaration:
20458f4d3ff1SRichard Smith ///     'use' wildcard-module-id
2046ba7f2f71SDaniel Jasper void ModuleMapParser::parseUseDecl() {
2047ba7f2f71SDaniel Jasper   assert(Tok.is(MMToken::UseKeyword));
20488f4d3ff1SRichard Smith   auto KWLoc = consumeToken();
2049ba7f2f71SDaniel Jasper   // Parse the module-id.
2050ba7f2f71SDaniel Jasper   ModuleId ParsedModuleId;
20513cd34c76SDaniel Jasper   parseModuleId(ParsedModuleId);
2052ba7f2f71SDaniel Jasper 
20538f4d3ff1SRichard Smith   if (ActiveModule->Parent)
20548f4d3ff1SRichard Smith     Diags.Report(KWLoc, diag::err_mmap_use_decl_submodule);
20558f4d3ff1SRichard Smith   else
2056ba7f2f71SDaniel Jasper     ActiveModule->UnresolvedDirectUses.push_back(ParsedModuleId);
2057ba7f2f71SDaniel Jasper }
2058ba7f2f71SDaniel Jasper 
20596ddfca91SDouglas Gregor /// \brief Parse a link declaration.
20606ddfca91SDouglas Gregor ///
20616ddfca91SDouglas Gregor ///   module-declaration:
20626ddfca91SDouglas Gregor ///     'link' 'framework'[opt] string-literal
20636ddfca91SDouglas Gregor void ModuleMapParser::parseLinkDecl() {
20646ddfca91SDouglas Gregor   assert(Tok.is(MMToken::LinkKeyword));
20656ddfca91SDouglas Gregor   SourceLocation LinkLoc = consumeToken();
20666ddfca91SDouglas Gregor 
20676ddfca91SDouglas Gregor   // Parse the optional 'framework' keyword.
20686ddfca91SDouglas Gregor   bool IsFramework = false;
20696ddfca91SDouglas Gregor   if (Tok.is(MMToken::FrameworkKeyword)) {
20706ddfca91SDouglas Gregor     consumeToken();
20716ddfca91SDouglas Gregor     IsFramework = true;
20726ddfca91SDouglas Gregor   }
20736ddfca91SDouglas Gregor 
20746ddfca91SDouglas Gregor   // Parse the library name
20756ddfca91SDouglas Gregor   if (!Tok.is(MMToken::StringLiteral)) {
20766ddfca91SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_library_name)
20776ddfca91SDouglas Gregor       << IsFramework << SourceRange(LinkLoc);
20786ddfca91SDouglas Gregor     HadError = true;
20796ddfca91SDouglas Gregor     return;
20806ddfca91SDouglas Gregor   }
20816ddfca91SDouglas Gregor 
20826ddfca91SDouglas Gregor   std::string LibraryName = Tok.getString();
20836ddfca91SDouglas Gregor   consumeToken();
20846ddfca91SDouglas Gregor   ActiveModule->LinkLibraries.push_back(Module::LinkLibrary(LibraryName,
20856ddfca91SDouglas Gregor                                                             IsFramework));
20866ddfca91SDouglas Gregor }
20876ddfca91SDouglas Gregor 
208835b13eceSDouglas Gregor /// \brief Parse a configuration macro declaration.
208935b13eceSDouglas Gregor ///
209035b13eceSDouglas Gregor ///   module-declaration:
209135b13eceSDouglas Gregor ///     'config_macros' attributes[opt] config-macro-list?
209235b13eceSDouglas Gregor ///
209335b13eceSDouglas Gregor ///   config-macro-list:
209435b13eceSDouglas Gregor ///     identifier (',' identifier)?
209535b13eceSDouglas Gregor void ModuleMapParser::parseConfigMacros() {
209635b13eceSDouglas Gregor   assert(Tok.is(MMToken::ConfigMacros));
209735b13eceSDouglas Gregor   SourceLocation ConfigMacrosLoc = consumeToken();
209835b13eceSDouglas Gregor 
209935b13eceSDouglas Gregor   // Only top-level modules can have configuration macros.
210035b13eceSDouglas Gregor   if (ActiveModule->Parent) {
210135b13eceSDouglas Gregor     Diags.Report(ConfigMacrosLoc, diag::err_mmap_config_macro_submodule);
210235b13eceSDouglas Gregor   }
210335b13eceSDouglas Gregor 
210435b13eceSDouglas Gregor   // Parse the optional attributes.
210535b13eceSDouglas Gregor   Attributes Attrs;
21065d29dee0SDavide Italiano   if (parseOptionalAttributes(Attrs))
21075d29dee0SDavide Italiano     return;
21085d29dee0SDavide Italiano 
210935b13eceSDouglas Gregor   if (Attrs.IsExhaustive && !ActiveModule->Parent) {
211035b13eceSDouglas Gregor     ActiveModule->ConfigMacrosExhaustive = true;
211135b13eceSDouglas Gregor   }
211235b13eceSDouglas Gregor 
211335b13eceSDouglas Gregor   // If we don't have an identifier, we're done.
2114306d8920SRichard Smith   // FIXME: Support macros with the same name as a keyword here.
211535b13eceSDouglas Gregor   if (!Tok.is(MMToken::Identifier))
211635b13eceSDouglas Gregor     return;
211735b13eceSDouglas Gregor 
211835b13eceSDouglas Gregor   // Consume the first identifier.
211935b13eceSDouglas Gregor   if (!ActiveModule->Parent) {
212035b13eceSDouglas Gregor     ActiveModule->ConfigMacros.push_back(Tok.getString().str());
212135b13eceSDouglas Gregor   }
212235b13eceSDouglas Gregor   consumeToken();
212335b13eceSDouglas Gregor 
212435b13eceSDouglas Gregor   do {
212535b13eceSDouglas Gregor     // If there's a comma, consume it.
212635b13eceSDouglas Gregor     if (!Tok.is(MMToken::Comma))
212735b13eceSDouglas Gregor       break;
212835b13eceSDouglas Gregor     consumeToken();
212935b13eceSDouglas Gregor 
213035b13eceSDouglas Gregor     // We expect to see a macro name here.
2131306d8920SRichard Smith     // FIXME: Support macros with the same name as a keyword here.
213235b13eceSDouglas Gregor     if (!Tok.is(MMToken::Identifier)) {
213335b13eceSDouglas Gregor       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_config_macro);
213435b13eceSDouglas Gregor       break;
213535b13eceSDouglas Gregor     }
213635b13eceSDouglas Gregor 
213735b13eceSDouglas Gregor     // Consume the macro name.
213835b13eceSDouglas Gregor     if (!ActiveModule->Parent) {
213935b13eceSDouglas Gregor       ActiveModule->ConfigMacros.push_back(Tok.getString().str());
214035b13eceSDouglas Gregor     }
214135b13eceSDouglas Gregor     consumeToken();
214235b13eceSDouglas Gregor   } while (true);
214335b13eceSDouglas Gregor }
214435b13eceSDouglas Gregor 
2145fb912657SDouglas Gregor /// \brief Format a module-id into a string.
2146fb912657SDouglas Gregor static std::string formatModuleId(const ModuleId &Id) {
2147fb912657SDouglas Gregor   std::string result;
2148fb912657SDouglas Gregor   {
2149fb912657SDouglas Gregor     llvm::raw_string_ostream OS(result);
2150fb912657SDouglas Gregor 
2151fb912657SDouglas Gregor     for (unsigned I = 0, N = Id.size(); I != N; ++I) {
2152fb912657SDouglas Gregor       if (I)
2153fb912657SDouglas Gregor         OS << ".";
2154fb912657SDouglas Gregor       OS << Id[I].first;
2155fb912657SDouglas Gregor     }
2156fb912657SDouglas Gregor   }
2157fb912657SDouglas Gregor 
2158fb912657SDouglas Gregor   return result;
2159fb912657SDouglas Gregor }
2160fb912657SDouglas Gregor 
2161fb912657SDouglas Gregor /// \brief Parse a conflict declaration.
2162fb912657SDouglas Gregor ///
2163fb912657SDouglas Gregor ///   module-declaration:
2164fb912657SDouglas Gregor ///     'conflict' module-id ',' string-literal
2165fb912657SDouglas Gregor void ModuleMapParser::parseConflict() {
2166fb912657SDouglas Gregor   assert(Tok.is(MMToken::Conflict));
2167fb912657SDouglas Gregor   SourceLocation ConflictLoc = consumeToken();
2168fb912657SDouglas Gregor   Module::UnresolvedConflict Conflict;
2169fb912657SDouglas Gregor 
2170fb912657SDouglas Gregor   // Parse the module-id.
2171fb912657SDouglas Gregor   if (parseModuleId(Conflict.Id))
2172fb912657SDouglas Gregor     return;
2173fb912657SDouglas Gregor 
2174fb912657SDouglas Gregor   // Parse the ','.
2175fb912657SDouglas Gregor   if (!Tok.is(MMToken::Comma)) {
2176fb912657SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_conflicts_comma)
2177fb912657SDouglas Gregor       << SourceRange(ConflictLoc);
2178fb912657SDouglas Gregor     return;
2179fb912657SDouglas Gregor   }
2180fb912657SDouglas Gregor   consumeToken();
2181fb912657SDouglas Gregor 
2182fb912657SDouglas Gregor   // Parse the message.
2183fb912657SDouglas Gregor   if (!Tok.is(MMToken::StringLiteral)) {
2184fb912657SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_conflicts_message)
2185fb912657SDouglas Gregor       << formatModuleId(Conflict.Id);
2186fb912657SDouglas Gregor     return;
2187fb912657SDouglas Gregor   }
2188fb912657SDouglas Gregor   Conflict.Message = Tok.getString().str();
2189fb912657SDouglas Gregor   consumeToken();
2190fb912657SDouglas Gregor 
2191fb912657SDouglas Gregor   // Add this unresolved conflict.
2192fb912657SDouglas Gregor   ActiveModule->UnresolvedConflicts.push_back(Conflict);
2193fb912657SDouglas Gregor }
2194fb912657SDouglas Gregor 
21956ddfca91SDouglas Gregor /// \brief Parse an inferred module declaration (wildcard modules).
21969194a91dSDouglas Gregor ///
21979194a91dSDouglas Gregor ///   module-declaration:
21989194a91dSDouglas Gregor ///     'explicit'[opt] 'framework'[opt] 'module' * attributes[opt]
21999194a91dSDouglas Gregor ///       { inferred-module-member* }
22009194a91dSDouglas Gregor ///
22019194a91dSDouglas Gregor ///   inferred-module-member:
22029194a91dSDouglas Gregor ///     'export' '*'
22039194a91dSDouglas Gregor ///     'exclude' identifier
22049194a91dSDouglas Gregor void ModuleMapParser::parseInferredModuleDecl(bool Framework, bool Explicit) {
220573441091SDouglas Gregor   assert(Tok.is(MMToken::Star));
220673441091SDouglas Gregor   SourceLocation StarLoc = consumeToken();
220773441091SDouglas Gregor   bool Failed = false;
220873441091SDouglas Gregor 
220973441091SDouglas Gregor   // Inferred modules must be submodules.
22109194a91dSDouglas Gregor   if (!ActiveModule && !Framework) {
221173441091SDouglas Gregor     Diags.Report(StarLoc, diag::err_mmap_top_level_inferred_submodule);
221273441091SDouglas Gregor     Failed = true;
221373441091SDouglas Gregor   }
221473441091SDouglas Gregor 
22159194a91dSDouglas Gregor   if (ActiveModule) {
2216524e33e1SDouglas Gregor     // Inferred modules must have umbrella directories.
22174898cde4SBen Langmuir     if (!Failed && ActiveModule->IsAvailable &&
22184898cde4SBen Langmuir         !ActiveModule->getUmbrellaDir()) {
221973441091SDouglas Gregor       Diags.Report(StarLoc, diag::err_mmap_inferred_no_umbrella);
222073441091SDouglas Gregor       Failed = true;
222173441091SDouglas Gregor     }
222273441091SDouglas Gregor 
222373441091SDouglas Gregor     // Check for redefinition of an inferred module.
2224dd005f69SDouglas Gregor     if (!Failed && ActiveModule->InferSubmodules) {
222573441091SDouglas Gregor       Diags.Report(StarLoc, diag::err_mmap_inferred_redef);
2226dd005f69SDouglas Gregor       if (ActiveModule->InferredSubmoduleLoc.isValid())
2227dd005f69SDouglas Gregor         Diags.Report(ActiveModule->InferredSubmoduleLoc,
222873441091SDouglas Gregor                      diag::note_mmap_prev_definition);
222973441091SDouglas Gregor       Failed = true;
223073441091SDouglas Gregor     }
223173441091SDouglas Gregor 
22329194a91dSDouglas Gregor     // Check for the 'framework' keyword, which is not permitted here.
22339194a91dSDouglas Gregor     if (Framework) {
22349194a91dSDouglas Gregor       Diags.Report(StarLoc, diag::err_mmap_inferred_framework_submodule);
22359194a91dSDouglas Gregor       Framework = false;
22369194a91dSDouglas Gregor     }
22379194a91dSDouglas Gregor   } else if (Explicit) {
22389194a91dSDouglas Gregor     Diags.Report(StarLoc, diag::err_mmap_explicit_inferred_framework);
22399194a91dSDouglas Gregor     Explicit = false;
22409194a91dSDouglas Gregor   }
22419194a91dSDouglas Gregor 
224273441091SDouglas Gregor   // If there were any problems with this inferred submodule, skip its body.
224373441091SDouglas Gregor   if (Failed) {
224473441091SDouglas Gregor     if (Tok.is(MMToken::LBrace)) {
224573441091SDouglas Gregor       consumeToken();
224673441091SDouglas Gregor       skipUntil(MMToken::RBrace);
224773441091SDouglas Gregor       if (Tok.is(MMToken::RBrace))
224873441091SDouglas Gregor         consumeToken();
224973441091SDouglas Gregor     }
225073441091SDouglas Gregor     HadError = true;
225173441091SDouglas Gregor     return;
225273441091SDouglas Gregor   }
225373441091SDouglas Gregor 
22549194a91dSDouglas Gregor   // Parse optional attributes.
22554442605fSBill Wendling   Attributes Attrs;
22565d29dee0SDavide Italiano   if (parseOptionalAttributes(Attrs))
22575d29dee0SDavide Italiano     return;
22589194a91dSDouglas Gregor 
22599194a91dSDouglas Gregor   if (ActiveModule) {
226073441091SDouglas Gregor     // Note that we have an inferred submodule.
2261dd005f69SDouglas Gregor     ActiveModule->InferSubmodules = true;
2262dd005f69SDouglas Gregor     ActiveModule->InferredSubmoduleLoc = StarLoc;
2263dd005f69SDouglas Gregor     ActiveModule->InferExplicitSubmodules = Explicit;
22649194a91dSDouglas Gregor   } else {
22659194a91dSDouglas Gregor     // We'll be inferring framework modules for this directory.
22669194a91dSDouglas Gregor     Map.InferredDirectories[Directory].InferModules = true;
2267c1d88ea5SBen Langmuir     Map.InferredDirectories[Directory].Attrs = Attrs;
2268beee15e7SBen Langmuir     Map.InferredDirectories[Directory].ModuleMapFile = ModuleMapFile;
2269131daca0SRichard Smith     // FIXME: Handle the 'framework' keyword.
22709194a91dSDouglas Gregor   }
227173441091SDouglas Gregor 
227273441091SDouglas Gregor   // Parse the opening brace.
227373441091SDouglas Gregor   if (!Tok.is(MMToken::LBrace)) {
227473441091SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_lbrace_wildcard);
227573441091SDouglas Gregor     HadError = true;
227673441091SDouglas Gregor     return;
227773441091SDouglas Gregor   }
227873441091SDouglas Gregor   SourceLocation LBraceLoc = consumeToken();
227973441091SDouglas Gregor 
228073441091SDouglas Gregor   // Parse the body of the inferred submodule.
228173441091SDouglas Gregor   bool Done = false;
228273441091SDouglas Gregor   do {
228373441091SDouglas Gregor     switch (Tok.Kind) {
228473441091SDouglas Gregor     case MMToken::EndOfFile:
228573441091SDouglas Gregor     case MMToken::RBrace:
228673441091SDouglas Gregor       Done = true;
228773441091SDouglas Gregor       break;
228873441091SDouglas Gregor 
22899194a91dSDouglas Gregor     case MMToken::ExcludeKeyword: {
22909194a91dSDouglas Gregor       if (ActiveModule) {
22919194a91dSDouglas Gregor         Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member)
2292d2d442caSCraig Topper           << (ActiveModule != nullptr);
22939194a91dSDouglas Gregor         consumeToken();
22949194a91dSDouglas Gregor         break;
22959194a91dSDouglas Gregor       }
22969194a91dSDouglas Gregor 
22979194a91dSDouglas Gregor       consumeToken();
2298306d8920SRichard Smith       // FIXME: Support string-literal module names here.
22999194a91dSDouglas Gregor       if (!Tok.is(MMToken::Identifier)) {
23009194a91dSDouglas Gregor         Diags.Report(Tok.getLocation(), diag::err_mmap_missing_exclude_name);
23019194a91dSDouglas Gregor         break;
23029194a91dSDouglas Gregor       }
23039194a91dSDouglas Gregor 
23049194a91dSDouglas Gregor       Map.InferredDirectories[Directory].ExcludedModules
23059194a91dSDouglas Gregor         .push_back(Tok.getString());
23069194a91dSDouglas Gregor       consumeToken();
23079194a91dSDouglas Gregor       break;
23089194a91dSDouglas Gregor     }
23099194a91dSDouglas Gregor 
23109194a91dSDouglas Gregor     case MMToken::ExportKeyword:
23119194a91dSDouglas Gregor       if (!ActiveModule) {
23129194a91dSDouglas Gregor         Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member)
2313d2d442caSCraig Topper           << (ActiveModule != nullptr);
23149194a91dSDouglas Gregor         consumeToken();
23159194a91dSDouglas Gregor         break;
23169194a91dSDouglas Gregor       }
23179194a91dSDouglas Gregor 
231873441091SDouglas Gregor       consumeToken();
231973441091SDouglas Gregor       if (Tok.is(MMToken::Star))
2320dd005f69SDouglas Gregor         ActiveModule->InferExportWildcard = true;
232173441091SDouglas Gregor       else
232273441091SDouglas Gregor         Diags.Report(Tok.getLocation(),
232373441091SDouglas Gregor                      diag::err_mmap_expected_export_wildcard);
232473441091SDouglas Gregor       consumeToken();
232573441091SDouglas Gregor       break;
232673441091SDouglas Gregor 
232773441091SDouglas Gregor     case MMToken::ExplicitKeyword:
232873441091SDouglas Gregor     case MMToken::ModuleKeyword:
232973441091SDouglas Gregor     case MMToken::HeaderKeyword:
2330b53e5483SLawrence Crowl     case MMToken::PrivateKeyword:
233173441091SDouglas Gregor     case MMToken::UmbrellaKeyword:
233273441091SDouglas Gregor     default:
23339194a91dSDouglas Gregor       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member)
2334d2d442caSCraig Topper           << (ActiveModule != nullptr);
233573441091SDouglas Gregor       consumeToken();
233673441091SDouglas Gregor       break;
233773441091SDouglas Gregor     }
233873441091SDouglas Gregor   } while (!Done);
233973441091SDouglas Gregor 
234073441091SDouglas Gregor   if (Tok.is(MMToken::RBrace))
234173441091SDouglas Gregor     consumeToken();
234273441091SDouglas Gregor   else {
234373441091SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
234473441091SDouglas Gregor     Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
234573441091SDouglas Gregor     HadError = true;
234673441091SDouglas Gregor   }
234773441091SDouglas Gregor }
234873441091SDouglas Gregor 
23499194a91dSDouglas Gregor /// \brief Parse optional attributes.
23509194a91dSDouglas Gregor ///
23519194a91dSDouglas Gregor ///   attributes:
23529194a91dSDouglas Gregor ///     attribute attributes
23539194a91dSDouglas Gregor ///     attribute
23549194a91dSDouglas Gregor ///
23559194a91dSDouglas Gregor ///   attribute:
23569194a91dSDouglas Gregor ///     [ identifier ]
23579194a91dSDouglas Gregor ///
23589194a91dSDouglas Gregor /// \param Attrs Will be filled in with the parsed attributes.
23599194a91dSDouglas Gregor ///
23609194a91dSDouglas Gregor /// \returns true if an error occurred, false otherwise.
23614442605fSBill Wendling bool ModuleMapParser::parseOptionalAttributes(Attributes &Attrs) {
23629194a91dSDouglas Gregor   bool HadError = false;
23639194a91dSDouglas Gregor 
23649194a91dSDouglas Gregor   while (Tok.is(MMToken::LSquare)) {
23659194a91dSDouglas Gregor     // Consume the '['.
23669194a91dSDouglas Gregor     SourceLocation LSquareLoc = consumeToken();
23679194a91dSDouglas Gregor 
23689194a91dSDouglas Gregor     // Check whether we have an attribute name here.
23699194a91dSDouglas Gregor     if (!Tok.is(MMToken::Identifier)) {
23709194a91dSDouglas Gregor       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_attribute);
23719194a91dSDouglas Gregor       skipUntil(MMToken::RSquare);
23729194a91dSDouglas Gregor       if (Tok.is(MMToken::RSquare))
23739194a91dSDouglas Gregor         consumeToken();
23749194a91dSDouglas Gregor       HadError = true;
23759194a91dSDouglas Gregor     }
23769194a91dSDouglas Gregor 
23779194a91dSDouglas Gregor     // Decode the attribute name.
23789194a91dSDouglas Gregor     AttributeKind Attribute
23799194a91dSDouglas Gregor       = llvm::StringSwitch<AttributeKind>(Tok.getString())
238035b13eceSDouglas Gregor           .Case("exhaustive", AT_exhaustive)
238177944868SRichard Smith           .Case("extern_c", AT_extern_c)
2382*ed84df00SBruno Cardoso Lopes           .Case("no_undeclared_includes", AT_no_undeclared_includes)
23839194a91dSDouglas Gregor           .Case("system", AT_system)
23849194a91dSDouglas Gregor           .Default(AT_unknown);
23859194a91dSDouglas Gregor     switch (Attribute) {
23869194a91dSDouglas Gregor     case AT_unknown:
23879194a91dSDouglas Gregor       Diags.Report(Tok.getLocation(), diag::warn_mmap_unknown_attribute)
23889194a91dSDouglas Gregor         << Tok.getString();
23899194a91dSDouglas Gregor       break;
23909194a91dSDouglas Gregor 
23919194a91dSDouglas Gregor     case AT_system:
23929194a91dSDouglas Gregor       Attrs.IsSystem = true;
23939194a91dSDouglas Gregor       break;
239435b13eceSDouglas Gregor 
239577944868SRichard Smith     case AT_extern_c:
239677944868SRichard Smith       Attrs.IsExternC = true;
239777944868SRichard Smith       break;
239877944868SRichard Smith 
239935b13eceSDouglas Gregor     case AT_exhaustive:
240035b13eceSDouglas Gregor       Attrs.IsExhaustive = true;
240135b13eceSDouglas Gregor       break;
2402*ed84df00SBruno Cardoso Lopes 
2403*ed84df00SBruno Cardoso Lopes     case AT_no_undeclared_includes:
2404*ed84df00SBruno Cardoso Lopes       Attrs.NoUndeclaredIncludes = true;
2405*ed84df00SBruno Cardoso Lopes       break;
24069194a91dSDouglas Gregor     }
24079194a91dSDouglas Gregor     consumeToken();
24089194a91dSDouglas Gregor 
24099194a91dSDouglas Gregor     // Consume the ']'.
24109194a91dSDouglas Gregor     if (!Tok.is(MMToken::RSquare)) {
24119194a91dSDouglas Gregor       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rsquare);
24129194a91dSDouglas Gregor       Diags.Report(LSquareLoc, diag::note_mmap_lsquare_match);
24139194a91dSDouglas Gregor       skipUntil(MMToken::RSquare);
24149194a91dSDouglas Gregor       HadError = true;
24159194a91dSDouglas Gregor     }
24169194a91dSDouglas Gregor 
24179194a91dSDouglas Gregor     if (Tok.is(MMToken::RSquare))
24189194a91dSDouglas Gregor       consumeToken();
24199194a91dSDouglas Gregor   }
24209194a91dSDouglas Gregor 
24219194a91dSDouglas Gregor   return HadError;
24229194a91dSDouglas Gregor }
24239194a91dSDouglas Gregor 
2424718292f2SDouglas Gregor /// \brief Parse a module map file.
2425718292f2SDouglas Gregor ///
2426718292f2SDouglas Gregor ///   module-map-file:
2427718292f2SDouglas Gregor ///     module-declaration*
2428718292f2SDouglas Gregor bool ModuleMapParser::parseModuleMapFile() {
2429718292f2SDouglas Gregor   do {
2430718292f2SDouglas Gregor     switch (Tok.Kind) {
2431718292f2SDouglas Gregor     case MMToken::EndOfFile:
2432718292f2SDouglas Gregor       return HadError;
2433718292f2SDouglas Gregor 
2434e7ab3669SDouglas Gregor     case MMToken::ExplicitKeyword:
243597292843SDaniel Jasper     case MMToken::ExternKeyword:
2436718292f2SDouglas Gregor     case MMToken::ModuleKeyword:
2437755b2055SDouglas Gregor     case MMToken::FrameworkKeyword:
2438718292f2SDouglas Gregor       parseModuleDecl();
2439718292f2SDouglas Gregor       break;
2440718292f2SDouglas Gregor 
24411fb5c3a6SDouglas Gregor     case MMToken::Comma:
244235b13eceSDouglas Gregor     case MMToken::ConfigMacros:
2443fb912657SDouglas Gregor     case MMToken::Conflict:
2444a3feee2aSRichard Smith     case MMToken::Exclaim:
244559527666SDouglas Gregor     case MMToken::ExcludeKeyword:
24462b82c2a5SDouglas Gregor     case MMToken::ExportKeyword:
2447718292f2SDouglas Gregor     case MMToken::HeaderKeyword:
2448718292f2SDouglas Gregor     case MMToken::Identifier:
2449718292f2SDouglas Gregor     case MMToken::LBrace:
24506ddfca91SDouglas Gregor     case MMToken::LinkKeyword:
2451a686e1b0SDouglas Gregor     case MMToken::LSquare:
24522b82c2a5SDouglas Gregor     case MMToken::Period:
2453b53e5483SLawrence Crowl     case MMToken::PrivateKeyword:
2454718292f2SDouglas Gregor     case MMToken::RBrace:
2455a686e1b0SDouglas Gregor     case MMToken::RSquare:
24561fb5c3a6SDouglas Gregor     case MMToken::RequiresKeyword:
24572b82c2a5SDouglas Gregor     case MMToken::Star:
2458718292f2SDouglas Gregor     case MMToken::StringLiteral:
2459b8afebe2SRichard Smith     case MMToken::TextualKeyword:
2460718292f2SDouglas Gregor     case MMToken::UmbrellaKeyword:
2461ba7f2f71SDaniel Jasper     case MMToken::UseKeyword:
2462718292f2SDouglas Gregor       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module);
2463718292f2SDouglas Gregor       HadError = true;
2464718292f2SDouglas Gregor       consumeToken();
2465718292f2SDouglas Gregor       break;
2466718292f2SDouglas Gregor     }
2467718292f2SDouglas Gregor   } while (true);
2468718292f2SDouglas Gregor }
2469718292f2SDouglas Gregor 
24709acb99e3SRichard Smith bool ModuleMap::parseModuleMapFile(const FileEntry *File, bool IsSystem,
2471ae6df27eSRichard Smith                                    const DirectoryEntry *Dir,
2472ae6df27eSRichard Smith                                    SourceLocation ExternModuleLoc) {
24734ddf2221SDouglas Gregor   llvm::DenseMap<const FileEntry *, bool>::iterator Known
24744ddf2221SDouglas Gregor     = ParsedModuleMap.find(File);
24754ddf2221SDouglas Gregor   if (Known != ParsedModuleMap.end())
24764ddf2221SDouglas Gregor     return Known->second;
24774ddf2221SDouglas Gregor 
2478d2d442caSCraig Topper   assert(Target && "Missing target information");
2479cb69b57bSBen Langmuir   auto FileCharacter = IsSystem ? SrcMgr::C_System : SrcMgr::C_User;
2480ae6df27eSRichard Smith   FileID ID = SourceMgr.createFileID(File, ExternModuleLoc, FileCharacter);
24811f76c4e8SManuel Klimek   const llvm::MemoryBuffer *Buffer = SourceMgr.getBuffer(ID);
2482718292f2SDouglas Gregor   if (!Buffer)
24834ddf2221SDouglas Gregor     return ParsedModuleMap[File] = true;
2484718292f2SDouglas Gregor 
2485718292f2SDouglas Gregor   // Parse this module map file.
24861f76c4e8SManuel Klimek   Lexer L(ID, SourceMgr.getBuffer(ID), SourceMgr, MMapLangOpts);
24872a6edb30SRichard Smith   SourceLocation Start = L.getSourceLocation();
2488beee15e7SBen Langmuir   ModuleMapParser Parser(L, SourceMgr, Target, Diags, *this, File, Dir,
2489963c5535SDouglas Gregor                          BuiltinIncludeDir, IsSystem);
2490718292f2SDouglas Gregor   bool Result = Parser.parseModuleMapFile();
24914ddf2221SDouglas Gregor   ParsedModuleMap[File] = Result;
24922a6edb30SRichard Smith 
24932a6edb30SRichard Smith   // Notify callbacks that we parsed it.
24942a6edb30SRichard Smith   for (const auto &Cb : Callbacks)
24952a6edb30SRichard Smith     Cb->moduleMapFileRead(Start, *File, IsSystem);
2496718292f2SDouglas Gregor   return Result;
2497718292f2SDouglas Gregor }
2498