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;
949ffe5a35SDavid Blaikie   MMapLangOpts.ModularCodegen = LangOpts.ModularCodegen;
950414b857SRichard Smith }
96718292f2SDouglas Gregor 
97718292f2SDouglas Gregor ModuleMap::~ModuleMap() {
9821668754SDavide Italiano   for (auto &M : Modules)
9921668754SDavide Italiano     delete M.getValue();
100718292f2SDouglas Gregor }
101718292f2SDouglas Gregor 
10289929282SDouglas Gregor void ModuleMap::setTarget(const TargetInfo &Target) {
10389929282SDouglas Gregor   assert((!this->Target || this->Target == &Target) &&
10489929282SDouglas Gregor          "Improper target override");
10589929282SDouglas Gregor   this->Target = &Target;
10689929282SDouglas Gregor }
10789929282SDouglas Gregor 
108056396aeSDouglas Gregor /// \brief "Sanitize" a filename so that it can be used as an identifier.
109056396aeSDouglas Gregor static StringRef sanitizeFilenameAsIdentifier(StringRef Name,
110056396aeSDouglas Gregor                                               SmallVectorImpl<char> &Buffer) {
111056396aeSDouglas Gregor   if (Name.empty())
112056396aeSDouglas Gregor     return Name;
113056396aeSDouglas Gregor 
114a7d03840SJordan Rose   if (!isValidIdentifier(Name)) {
115056396aeSDouglas Gregor     // If we don't already have something with the form of an identifier,
116056396aeSDouglas Gregor     // create a buffer with the sanitized name.
117056396aeSDouglas Gregor     Buffer.clear();
118a7d03840SJordan Rose     if (isDigit(Name[0]))
119056396aeSDouglas Gregor       Buffer.push_back('_');
120056396aeSDouglas Gregor     Buffer.reserve(Buffer.size() + Name.size());
121056396aeSDouglas Gregor     for (unsigned I = 0, N = Name.size(); I != N; ++I) {
122a7d03840SJordan Rose       if (isIdentifierBody(Name[I]))
123056396aeSDouglas Gregor         Buffer.push_back(Name[I]);
124056396aeSDouglas Gregor       else
125056396aeSDouglas Gregor         Buffer.push_back('_');
126056396aeSDouglas Gregor     }
127056396aeSDouglas Gregor 
128056396aeSDouglas Gregor     Name = StringRef(Buffer.data(), Buffer.size());
129056396aeSDouglas Gregor   }
130056396aeSDouglas Gregor 
131056396aeSDouglas Gregor   while (llvm::StringSwitch<bool>(Name)
132056396aeSDouglas Gregor #define KEYWORD(Keyword,Conditions) .Case(#Keyword, true)
133056396aeSDouglas Gregor #define ALIAS(Keyword, AliasOf, Conditions) .Case(Keyword, true)
134056396aeSDouglas Gregor #include "clang/Basic/TokenKinds.def"
135056396aeSDouglas Gregor            .Default(false)) {
136056396aeSDouglas Gregor     if (Name.data() != Buffer.data())
137056396aeSDouglas Gregor       Buffer.append(Name.begin(), Name.end());
138056396aeSDouglas Gregor     Buffer.push_back('_');
139056396aeSDouglas Gregor     Name = StringRef(Buffer.data(), Buffer.size());
140056396aeSDouglas Gregor   }
141056396aeSDouglas Gregor 
142056396aeSDouglas Gregor   return Name;
143056396aeSDouglas Gregor }
144056396aeSDouglas Gregor 
14534d52749SDouglas Gregor /// \brief Determine whether the given file name is the name of a builtin
14634d52749SDouglas Gregor /// header, supplied by Clang to replace, override, or augment existing system
14734d52749SDouglas Gregor /// headers.
148ba1b5c98SBruno Cardoso Lopes bool ModuleMap::isBuiltinHeader(StringRef FileName) {
14934d52749SDouglas Gregor   return llvm::StringSwitch<bool>(FileName)
15034d52749SDouglas Gregor            .Case("float.h", true)
15134d52749SDouglas Gregor            .Case("iso646.h", true)
15234d52749SDouglas Gregor            .Case("limits.h", true)
15334d52749SDouglas Gregor            .Case("stdalign.h", true)
15434d52749SDouglas Gregor            .Case("stdarg.h", true)
1553c4b1290SBen Langmuir            .Case("stdatomic.h", true)
15634d52749SDouglas Gregor            .Case("stdbool.h", true)
15734d52749SDouglas Gregor            .Case("stddef.h", true)
15834d52749SDouglas Gregor            .Case("stdint.h", true)
15934d52749SDouglas Gregor            .Case("tgmath.h", true)
16034d52749SDouglas Gregor            .Case("unwind.h", true)
16134d52749SDouglas Gregor            .Default(false);
16234d52749SDouglas Gregor }
16334d52749SDouglas Gregor 
16492669ee4SDaniel Jasper ModuleMap::HeadersMap::iterator
16592669ee4SDaniel Jasper ModuleMap::findKnownHeader(const FileEntry *File) {
16659527666SDouglas Gregor   HeadersMap::iterator Known = Headers.find(File);
16747972afdSRichard Smith   if (HeaderInfo.getHeaderSearchOpts().ImplicitModuleMaps &&
16847972afdSRichard Smith       Known == Headers.end() && File->getDir() == BuiltinIncludeDir &&
169ba1b5c98SBruno Cardoso Lopes       ModuleMap::isBuiltinHeader(llvm::sys::path::filename(File->getName()))) {
1704eaf0a6cSDaniel Jasper     HeaderInfo.loadTopLevelSystemModules();
17192669ee4SDaniel Jasper     return Headers.find(File);
1724eaf0a6cSDaniel Jasper   }
17392669ee4SDaniel Jasper   return Known;
17492669ee4SDaniel Jasper }
17592669ee4SDaniel Jasper 
1764469138eSBen Langmuir ModuleMap::KnownHeader
1774469138eSBen Langmuir ModuleMap::findHeaderInUmbrellaDirs(const FileEntry *File,
1784469138eSBen Langmuir                     SmallVectorImpl<const DirectoryEntry *> &IntermediateDirs) {
17947972afdSRichard Smith   if (UmbrellaDirs.empty())
18047972afdSRichard Smith     return KnownHeader();
18147972afdSRichard Smith 
1824469138eSBen Langmuir   const DirectoryEntry *Dir = File->getDir();
1834469138eSBen Langmuir   assert(Dir && "file in no directory");
1844469138eSBen Langmuir 
1854469138eSBen Langmuir   // Note: as an egregious but useful hack we use the real path here, because
1864469138eSBen Langmuir   // frameworks moving from top-level frameworks to embedded frameworks tend
1874469138eSBen Langmuir   // to be symlinked from the top-level location to the embedded location,
1884469138eSBen Langmuir   // and we need to resolve lookups as if we had found the embedded location.
1894469138eSBen Langmuir   StringRef DirName = SourceMgr.getFileManager().getCanonicalName(Dir);
1904469138eSBen Langmuir 
1914469138eSBen Langmuir   // Keep walking up the directory hierarchy, looking for a directory with
1924469138eSBen Langmuir   // an umbrella header.
1934469138eSBen Langmuir   do {
1944469138eSBen Langmuir     auto KnownDir = UmbrellaDirs.find(Dir);
1954469138eSBen Langmuir     if (KnownDir != UmbrellaDirs.end())
1964469138eSBen Langmuir       return KnownHeader(KnownDir->second, NormalHeader);
1974469138eSBen Langmuir 
1984469138eSBen Langmuir     IntermediateDirs.push_back(Dir);
1994469138eSBen Langmuir 
2004469138eSBen Langmuir     // Retrieve our parent path.
2014469138eSBen Langmuir     DirName = llvm::sys::path::parent_path(DirName);
2024469138eSBen Langmuir     if (DirName.empty())
2034469138eSBen Langmuir       break;
2044469138eSBen Langmuir 
2054469138eSBen Langmuir     // Resolve the parent path to a directory entry.
2064469138eSBen Langmuir     Dir = SourceMgr.getFileManager().getDirectory(DirName);
2074469138eSBen Langmuir   } while (Dir);
2084469138eSBen Langmuir   return KnownHeader();
2094469138eSBen Langmuir }
2104469138eSBen Langmuir 
21192669ee4SDaniel Jasper static bool violatesPrivateInclude(Module *RequestingModule,
21292669ee4SDaniel Jasper                                    const FileEntry *IncFileEnt,
2134eb8393cSRichard Smith                                    ModuleMap::KnownHeader Header) {
21492669ee4SDaniel Jasper #ifndef NDEBUG
2154eb8393cSRichard Smith   if (Header.getRole() & ModuleMap::PrivateHeader) {
21692669ee4SDaniel Jasper     // Check for consistency between the module header role
21792669ee4SDaniel Jasper     // as obtained from the lookup and as obtained from the module.
21892669ee4SDaniel Jasper     // This check is not cheap, so enable it only for debugging.
2192708e520SRichard Smith     bool IsPrivate = false;
2202708e520SRichard Smith     SmallVectorImpl<Module::Header> *HeaderList[] = {
2214eb8393cSRichard Smith         &Header.getModule()->Headers[Module::HK_Private],
2224eb8393cSRichard Smith         &Header.getModule()->Headers[Module::HK_PrivateTextual]};
2232708e520SRichard Smith     for (auto *Hs : HeaderList)
2242708e520SRichard Smith       IsPrivate |=
2252708e520SRichard Smith           std::find_if(Hs->begin(), Hs->end(), [&](const Module::Header &H) {
2263c1a41adSRichard Smith             return H.Entry == IncFileEnt;
2272708e520SRichard Smith           }) != Hs->end();
2284eb8393cSRichard Smith     assert(IsPrivate && "inconsistent headers and roles");
22900bc95ecSRichard Smith   }
23092669ee4SDaniel Jasper #endif
2314eb8393cSRichard Smith   return !Header.isAccessibleFrom(RequestingModule);
23292669ee4SDaniel Jasper }
23392669ee4SDaniel Jasper 
23471e1a64fSBen Langmuir static Module *getTopLevelOrNull(Module *M) {
23571e1a64fSBen Langmuir   return M ? M->getTopLevelModule() : nullptr;
23671e1a64fSBen Langmuir }
23771e1a64fSBen Langmuir 
23892669ee4SDaniel Jasper void ModuleMap::diagnoseHeaderInclusion(Module *RequestingModule,
2398d4e90b3SRichard Smith                                         bool RequestingModuleIsModuleInterface,
24092669ee4SDaniel Jasper                                         SourceLocation FilenameLoc,
24192669ee4SDaniel Jasper                                         StringRef Filename,
24292669ee4SDaniel Jasper                                         const FileEntry *File) {
24392669ee4SDaniel Jasper   // No errors for indirect modules. This may be a bit of a problem for modules
24492669ee4SDaniel Jasper   // with no source files.
24571e1a64fSBen Langmuir   if (getTopLevelOrNull(RequestingModule) != getTopLevelOrNull(SourceModule))
24692669ee4SDaniel Jasper     return;
24792669ee4SDaniel Jasper 
24892669ee4SDaniel Jasper   if (RequestingModule)
24992669ee4SDaniel Jasper     resolveUses(RequestingModule, /*Complain=*/false);
25092669ee4SDaniel Jasper 
25171e1a64fSBen Langmuir   bool Excluded = false;
252d2d442caSCraig Topper   Module *Private = nullptr;
253d2d442caSCraig Topper   Module *NotUsed = nullptr;
25471e1a64fSBen Langmuir 
25571e1a64fSBen Langmuir   HeadersMap::iterator Known = findKnownHeader(File);
25671e1a64fSBen Langmuir   if (Known != Headers.end()) {
25771e1a64fSBen Langmuir     for (const KnownHeader &Header : Known->second) {
25892669ee4SDaniel Jasper       // Remember private headers for later printing of a diagnostic.
2594eb8393cSRichard Smith       if (violatesPrivateInclude(RequestingModule, File, Header)) {
26071e1a64fSBen Langmuir         Private = Header.getModule();
26192669ee4SDaniel Jasper         continue;
26292669ee4SDaniel Jasper       }
26392669ee4SDaniel Jasper 
26492669ee4SDaniel Jasper       // If uses need to be specified explicitly, we are only allowed to return
26592669ee4SDaniel Jasper       // modules that are explicitly used by the requesting module.
26692669ee4SDaniel Jasper       if (RequestingModule && LangOpts.ModulesDeclUse &&
2678f4d3ff1SRichard Smith           !RequestingModule->directlyUses(Header.getModule())) {
26871e1a64fSBen Langmuir         NotUsed = Header.getModule();
26992669ee4SDaniel Jasper         continue;
27092669ee4SDaniel Jasper       }
27192669ee4SDaniel Jasper 
27292669ee4SDaniel Jasper       // We have found a module that we can happily use.
27392669ee4SDaniel Jasper       return;
27492669ee4SDaniel Jasper     }
275feb54b6dSRichard Smith 
276feb54b6dSRichard Smith     Excluded = true;
27771e1a64fSBen Langmuir   }
27892669ee4SDaniel Jasper 
27992669ee4SDaniel Jasper   // We have found a header, but it is private.
280d2d442caSCraig Topper   if (Private) {
28111152dd5SRichard Smith     Diags.Report(FilenameLoc, diag::warn_use_of_private_header_outside_module)
28292669ee4SDaniel Jasper         << Filename;
28392669ee4SDaniel Jasper     return;
28492669ee4SDaniel Jasper   }
28592669ee4SDaniel Jasper 
28692669ee4SDaniel Jasper   // We have found a module, but we don't use it.
287d2d442caSCraig Topper   if (NotUsed) {
28811152dd5SRichard Smith     Diags.Report(FilenameLoc, diag::err_undeclared_use_of_module)
28992669ee4SDaniel Jasper         << RequestingModule->getFullModuleName() << Filename;
29092669ee4SDaniel Jasper     return;
29192669ee4SDaniel Jasper   }
29292669ee4SDaniel Jasper 
29371e1a64fSBen Langmuir   if (Excluded || isHeaderInUmbrellaDirs(File))
29471e1a64fSBen Langmuir     return;
29571e1a64fSBen Langmuir 
29671e1a64fSBen Langmuir   // At this point, only non-modular includes remain.
29771e1a64fSBen Langmuir 
29871e1a64fSBen Langmuir   if (LangOpts.ModulesStrictDeclUse) {
29911152dd5SRichard Smith     Diags.Report(FilenameLoc, diag::err_undeclared_use_of_module)
30071e1a64fSBen Langmuir         << RequestingModule->getFullModuleName() << Filename;
301a67e4d32SManman Ren   } else if (RequestingModule && RequestingModuleIsModuleInterface &&
302a67e4d32SManman Ren              LangOpts.isCompilingModule()) {
303a67e4d32SManman Ren     // Do not diagnose when we are not compiling a module.
30471e1a64fSBen Langmuir     diag::kind DiagID = RequestingModule->getTopLevelModule()->IsFramework ?
30571e1a64fSBen Langmuir         diag::warn_non_modular_include_in_framework_module :
30671e1a64fSBen Langmuir         diag::warn_non_modular_include_in_module;
30770a7738fSManman Ren     Diags.Report(FilenameLoc, DiagID) << RequestingModule->getFullModuleName()
30870a7738fSManman Ren         << File->getName();
30971e1a64fSBen Langmuir   }
31092669ee4SDaniel Jasper }
31192669ee4SDaniel Jasper 
312ec87a50aSRichard Smith static bool isBetterKnownHeader(const ModuleMap::KnownHeader &New,
313ec87a50aSRichard Smith                                 const ModuleMap::KnownHeader &Old) {
3148b7c0398SSean Silva   // Prefer available modules.
3158b7c0398SSean Silva   if (New.getModule()->isAvailable() && !Old.getModule()->isAvailable())
3168b7c0398SSean Silva     return true;
3178b7c0398SSean Silva 
318ec87a50aSRichard Smith   // Prefer a public header over a private header.
319ec87a50aSRichard Smith   if ((New.getRole() & ModuleMap::PrivateHeader) !=
320ec87a50aSRichard Smith       (Old.getRole() & ModuleMap::PrivateHeader))
321ec87a50aSRichard Smith     return !(New.getRole() & ModuleMap::PrivateHeader);
322ec87a50aSRichard Smith 
323ec87a50aSRichard Smith   // Prefer a non-textual header over a textual header.
324ec87a50aSRichard Smith   if ((New.getRole() & ModuleMap::TextualHeader) !=
325ec87a50aSRichard Smith       (Old.getRole() & ModuleMap::TextualHeader))
326ec87a50aSRichard Smith     return !(New.getRole() & ModuleMap::TextualHeader);
327ec87a50aSRichard Smith 
328ec87a50aSRichard Smith   // Don't have a reason to choose between these. Just keep the first one.
329ec87a50aSRichard Smith   return false;
330ec87a50aSRichard Smith }
331ec87a50aSRichard Smith 
332ed84df00SBruno Cardoso Lopes ModuleMap::KnownHeader ModuleMap::findModuleForHeader(const FileEntry *File,
333ed84df00SBruno Cardoso Lopes                                                       bool AllowTextual) {
334306d8920SRichard Smith   auto MakeResult = [&](ModuleMap::KnownHeader R) -> ModuleMap::KnownHeader {
335ed84df00SBruno Cardoso Lopes     if (!AllowTextual && R.getRole() & ModuleMap::TextualHeader)
336306d8920SRichard Smith       return ModuleMap::KnownHeader();
337306d8920SRichard Smith     return R;
338306d8920SRichard Smith   };
339306d8920SRichard Smith 
3404881e8b2SSean Silva   HeadersMap::iterator Known = findKnownHeader(File);
3411fb5c3a6SDouglas Gregor   if (Known != Headers.end()) {
342202210b3SRichard Smith     ModuleMap::KnownHeader Result;
34397da9178SDaniel Jasper     // Iterate over all modules that 'File' is part of to find the best fit.
3444881e8b2SSean Silva     for (KnownHeader &H : Known->second) {
3457e82e019SRichard Smith       // Prefer a header from the source module over all others.
3467e82e019SRichard Smith       if (H.getModule()->getTopLevelModule() == SourceModule)
3472f633e7cSRichard Smith         return MakeResult(H);
3484881e8b2SSean Silva       if (!Result || isBetterKnownHeader(H, Result))
3494881e8b2SSean Silva         Result = H;
35097da9178SDaniel Jasper     }
351306d8920SRichard Smith     return MakeResult(Result);
3521fb5c3a6SDouglas Gregor   }
353ab0c8a84SDouglas Gregor 
354386bb073SRichard Smith   return MakeResult(findOrCreateModuleForHeaderInUmbrellaDir(File));
355386bb073SRichard Smith }
356386bb073SRichard Smith 
357386bb073SRichard Smith ModuleMap::KnownHeader
358386bb073SRichard Smith ModuleMap::findOrCreateModuleForHeaderInUmbrellaDir(const FileEntry *File) {
359386bb073SRichard Smith   assert(!Headers.count(File) && "already have a module for this header");
360386bb073SRichard Smith 
361f857950dSDmitri Gribenko   SmallVector<const DirectoryEntry *, 2> SkippedDirs;
3624469138eSBen Langmuir   KnownHeader H = findHeaderInUmbrellaDirs(File, SkippedDirs);
3634469138eSBen Langmuir   if (H) {
3644469138eSBen Langmuir     Module *Result = H.getModule();
365930a85ccSDouglas Gregor 
366930a85ccSDouglas Gregor     // Search up the module stack until we find a module with an umbrella
36773141fa9SDouglas Gregor     // directory.
368930a85ccSDouglas Gregor     Module *UmbrellaModule = Result;
36973141fa9SDouglas Gregor     while (!UmbrellaModule->getUmbrellaDir() && UmbrellaModule->Parent)
370930a85ccSDouglas Gregor       UmbrellaModule = UmbrellaModule->Parent;
371930a85ccSDouglas Gregor 
372930a85ccSDouglas Gregor     if (UmbrellaModule->InferSubmodules) {
3739d6448b1SBen Langmuir       const FileEntry *UmbrellaModuleMap =
3749d6448b1SBen Langmuir           getModuleMapFileForUniquing(UmbrellaModule);
3759d6448b1SBen Langmuir 
376a89c5ac4SDouglas Gregor       // Infer submodules for each of the directories we found between
377a89c5ac4SDouglas Gregor       // the directory of the umbrella header and the directory where
378a89c5ac4SDouglas Gregor       // the actual header is located.
3799458f82dSDouglas Gregor       bool Explicit = UmbrellaModule->InferExplicitSubmodules;
3809458f82dSDouglas Gregor 
3817033127bSDouglas Gregor       for (unsigned I = SkippedDirs.size(); I != 0; --I) {
382a89c5ac4SDouglas Gregor         // Find or create the module that corresponds to this directory name.
383056396aeSDouglas Gregor         SmallString<32> NameBuf;
384056396aeSDouglas Gregor         StringRef Name = sanitizeFilenameAsIdentifier(
3854469138eSBen Langmuir             llvm::sys::path::stem(SkippedDirs[I-1]->getName()), NameBuf);
3869d6448b1SBen Langmuir         Result = findOrCreateModule(Name, Result, /*IsFramework=*/false,
3879d6448b1SBen Langmuir                                     Explicit).first;
3889d6448b1SBen Langmuir         InferredModuleAllowedBy[Result] = UmbrellaModuleMap;
389ffbafa2aSBen Langmuir         Result->IsInferred = true;
390a89c5ac4SDouglas Gregor 
391a89c5ac4SDouglas Gregor         // Associate the module and the directory.
392a89c5ac4SDouglas Gregor         UmbrellaDirs[SkippedDirs[I-1]] = Result;
393a89c5ac4SDouglas Gregor 
394a89c5ac4SDouglas Gregor         // If inferred submodules export everything they import, add a
395a89c5ac4SDouglas Gregor         // wildcard to the set of exports.
396930a85ccSDouglas Gregor         if (UmbrellaModule->InferExportWildcard && Result->Exports.empty())
397d2d442caSCraig Topper           Result->Exports.push_back(Module::ExportDecl(nullptr, true));
398a89c5ac4SDouglas Gregor       }
399a89c5ac4SDouglas Gregor 
400a89c5ac4SDouglas Gregor       // Infer a submodule with the same name as this header file.
401056396aeSDouglas Gregor       SmallString<32> NameBuf;
402056396aeSDouglas Gregor       StringRef Name = sanitizeFilenameAsIdentifier(
403056396aeSDouglas Gregor                          llvm::sys::path::stem(File->getName()), NameBuf);
4049d6448b1SBen Langmuir       Result = findOrCreateModule(Name, Result, /*IsFramework=*/false,
4059d6448b1SBen Langmuir                                   Explicit).first;
4069d6448b1SBen Langmuir       InferredModuleAllowedBy[Result] = UmbrellaModuleMap;
407ffbafa2aSBen Langmuir       Result->IsInferred = true;
4083c5305c1SArgyrios Kyrtzidis       Result->addTopHeader(File);
409a89c5ac4SDouglas Gregor 
410a89c5ac4SDouglas Gregor       // If inferred submodules export everything they import, add a
411a89c5ac4SDouglas Gregor       // wildcard to the set of exports.
412930a85ccSDouglas Gregor       if (UmbrellaModule->InferExportWildcard && Result->Exports.empty())
413d2d442caSCraig Topper         Result->Exports.push_back(Module::ExportDecl(nullptr, true));
414a89c5ac4SDouglas Gregor     } else {
415a89c5ac4SDouglas Gregor       // Record each of the directories we stepped through as being part of
416a89c5ac4SDouglas Gregor       // the module we found, since the umbrella header covers them all.
417a89c5ac4SDouglas Gregor       for (unsigned I = 0, N = SkippedDirs.size(); I != N; ++I)
418a89c5ac4SDouglas Gregor         UmbrellaDirs[SkippedDirs[I]] = Result;
419a89c5ac4SDouglas Gregor     }
420a89c5ac4SDouglas Gregor 
421386bb073SRichard Smith     KnownHeader Header(Result, NormalHeader);
422386bb073SRichard Smith     Headers[File].push_back(Header);
423386bb073SRichard Smith     return Header;
424a89c5ac4SDouglas Gregor   }
425a89c5ac4SDouglas Gregor 
426b53e5483SLawrence Crowl   return KnownHeader();
427ab0c8a84SDouglas Gregor }
428ab0c8a84SDouglas Gregor 
429386bb073SRichard Smith ArrayRef<ModuleMap::KnownHeader>
430386bb073SRichard Smith ModuleMap::findAllModulesForHeader(const FileEntry *File) const {
431386bb073SRichard Smith   auto It = Headers.find(File);
432386bb073SRichard Smith   if (It == Headers.end())
433386bb073SRichard Smith     return None;
434386bb073SRichard Smith   return It->second;
435386bb073SRichard Smith }
436386bb073SRichard Smith 
437e4412640SArgyrios Kyrtzidis bool ModuleMap::isHeaderInUnavailableModule(const FileEntry *Header) const {
438d2d442caSCraig Topper   return isHeaderUnavailableInModule(Header, nullptr);
43950996ce1SRichard Smith }
44050996ce1SRichard Smith 
44162bcd925SDmitri Gribenko bool
44262bcd925SDmitri Gribenko ModuleMap::isHeaderUnavailableInModule(const FileEntry *Header,
44362bcd925SDmitri Gribenko                                        const Module *RequestingModule) const {
444e4412640SArgyrios Kyrtzidis   HeadersMap::const_iterator Known = Headers.find(Header);
44597da9178SDaniel Jasper   if (Known != Headers.end()) {
44697da9178SDaniel Jasper     for (SmallVectorImpl<KnownHeader>::const_iterator
44797da9178SDaniel Jasper              I = Known->second.begin(),
44897da9178SDaniel Jasper              E = Known->second.end();
44997da9178SDaniel Jasper          I != E; ++I) {
450052d95a6SBruno Cardoso Lopes 
451052d95a6SBruno Cardoso Lopes       if (I->isAvailable() &&
452052d95a6SBruno Cardoso Lopes           (!RequestingModule ||
453052d95a6SBruno Cardoso Lopes            I->getModule()->isSubModuleOf(RequestingModule))) {
454052d95a6SBruno Cardoso Lopes         // When no requesting module is available, the caller is looking if a
455052d95a6SBruno Cardoso Lopes         // header is part a module by only looking into the module map. This is
456052d95a6SBruno Cardoso Lopes         // done by warn_uncovered_module_header checks; don't consider textual
457052d95a6SBruno Cardoso Lopes         // headers part of it in this mode, otherwise we get misleading warnings
458052d95a6SBruno Cardoso Lopes         // that a umbrella header is not including a textual header.
459052d95a6SBruno Cardoso Lopes         if (!RequestingModule && I->getRole() == ModuleMap::TextualHeader)
460052d95a6SBruno Cardoso Lopes           continue;
46197da9178SDaniel Jasper         return false;
46297da9178SDaniel Jasper       }
463052d95a6SBruno Cardoso Lopes     }
46497da9178SDaniel Jasper     return true;
46597da9178SDaniel Jasper   }
4661fb5c3a6SDouglas Gregor 
4671fb5c3a6SDouglas Gregor   const DirectoryEntry *Dir = Header->getDir();
468f857950dSDmitri Gribenko   SmallVector<const DirectoryEntry *, 2> SkippedDirs;
4691fb5c3a6SDouglas Gregor   StringRef DirName = Dir->getName();
4701fb5c3a6SDouglas Gregor 
47150996ce1SRichard Smith   auto IsUnavailable = [&](const Module *M) {
47250996ce1SRichard Smith     return !M->isAvailable() && (!RequestingModule ||
47350996ce1SRichard Smith                                  M->isSubModuleOf(RequestingModule));
47450996ce1SRichard Smith   };
47550996ce1SRichard Smith 
4761fb5c3a6SDouglas Gregor   // Keep walking up the directory hierarchy, looking for a directory with
4771fb5c3a6SDouglas Gregor   // an umbrella header.
4781fb5c3a6SDouglas Gregor   do {
479e4412640SArgyrios Kyrtzidis     llvm::DenseMap<const DirectoryEntry *, Module *>::const_iterator KnownDir
4801fb5c3a6SDouglas Gregor       = UmbrellaDirs.find(Dir);
4811fb5c3a6SDouglas Gregor     if (KnownDir != UmbrellaDirs.end()) {
4821fb5c3a6SDouglas Gregor       Module *Found = KnownDir->second;
48350996ce1SRichard Smith       if (IsUnavailable(Found))
4841fb5c3a6SDouglas Gregor         return true;
4851fb5c3a6SDouglas Gregor 
4861fb5c3a6SDouglas Gregor       // Search up the module stack until we find a module with an umbrella
4871fb5c3a6SDouglas Gregor       // directory.
4881fb5c3a6SDouglas Gregor       Module *UmbrellaModule = Found;
4891fb5c3a6SDouglas Gregor       while (!UmbrellaModule->getUmbrellaDir() && UmbrellaModule->Parent)
4901fb5c3a6SDouglas Gregor         UmbrellaModule = UmbrellaModule->Parent;
4911fb5c3a6SDouglas Gregor 
4921fb5c3a6SDouglas Gregor       if (UmbrellaModule->InferSubmodules) {
4931fb5c3a6SDouglas Gregor         for (unsigned I = SkippedDirs.size(); I != 0; --I) {
4941fb5c3a6SDouglas Gregor           // Find or create the module that corresponds to this directory name.
495056396aeSDouglas Gregor           SmallString<32> NameBuf;
496056396aeSDouglas Gregor           StringRef Name = sanitizeFilenameAsIdentifier(
497056396aeSDouglas Gregor                              llvm::sys::path::stem(SkippedDirs[I-1]->getName()),
498056396aeSDouglas Gregor                              NameBuf);
4991fb5c3a6SDouglas Gregor           Found = lookupModuleQualified(Name, Found);
5001fb5c3a6SDouglas Gregor           if (!Found)
5011fb5c3a6SDouglas Gregor             return false;
50250996ce1SRichard Smith           if (IsUnavailable(Found))
5031fb5c3a6SDouglas Gregor             return true;
5041fb5c3a6SDouglas Gregor         }
5051fb5c3a6SDouglas Gregor 
5061fb5c3a6SDouglas Gregor         // Infer a submodule with the same name as this header file.
507056396aeSDouglas Gregor         SmallString<32> NameBuf;
508056396aeSDouglas Gregor         StringRef Name = sanitizeFilenameAsIdentifier(
509056396aeSDouglas Gregor                            llvm::sys::path::stem(Header->getName()),
510056396aeSDouglas Gregor                            NameBuf);
5111fb5c3a6SDouglas Gregor         Found = lookupModuleQualified(Name, Found);
5121fb5c3a6SDouglas Gregor         if (!Found)
5131fb5c3a6SDouglas Gregor           return false;
5141fb5c3a6SDouglas Gregor       }
5151fb5c3a6SDouglas Gregor 
51650996ce1SRichard Smith       return IsUnavailable(Found);
5171fb5c3a6SDouglas Gregor     }
5181fb5c3a6SDouglas Gregor 
5191fb5c3a6SDouglas Gregor     SkippedDirs.push_back(Dir);
5201fb5c3a6SDouglas Gregor 
5211fb5c3a6SDouglas Gregor     // Retrieve our parent path.
5221fb5c3a6SDouglas Gregor     DirName = llvm::sys::path::parent_path(DirName);
5231fb5c3a6SDouglas Gregor     if (DirName.empty())
5241fb5c3a6SDouglas Gregor       break;
5251fb5c3a6SDouglas Gregor 
5261fb5c3a6SDouglas Gregor     // Resolve the parent path to a directory entry.
5271f76c4e8SManuel Klimek     Dir = SourceMgr.getFileManager().getDirectory(DirName);
5281fb5c3a6SDouglas Gregor   } while (Dir);
5291fb5c3a6SDouglas Gregor 
5301fb5c3a6SDouglas Gregor   return false;
5311fb5c3a6SDouglas Gregor }
5321fb5c3a6SDouglas Gregor 
533e4412640SArgyrios Kyrtzidis Module *ModuleMap::findModule(StringRef Name) const {
534e4412640SArgyrios Kyrtzidis   llvm::StringMap<Module *>::const_iterator Known = Modules.find(Name);
53588bdfb0eSDouglas Gregor   if (Known != Modules.end())
53688bdfb0eSDouglas Gregor     return Known->getValue();
53788bdfb0eSDouglas Gregor 
538d2d442caSCraig Topper   return nullptr;
53988bdfb0eSDouglas Gregor }
54088bdfb0eSDouglas Gregor 
541e4412640SArgyrios Kyrtzidis Module *ModuleMap::lookupModuleUnqualified(StringRef Name,
542e4412640SArgyrios Kyrtzidis                                            Module *Context) const {
5432b82c2a5SDouglas Gregor   for(; Context; Context = Context->Parent) {
5442b82c2a5SDouglas Gregor     if (Module *Sub = lookupModuleQualified(Name, Context))
5452b82c2a5SDouglas Gregor       return Sub;
5462b82c2a5SDouglas Gregor   }
5472b82c2a5SDouglas Gregor 
5482b82c2a5SDouglas Gregor   return findModule(Name);
5492b82c2a5SDouglas Gregor }
5502b82c2a5SDouglas Gregor 
551e4412640SArgyrios Kyrtzidis Module *ModuleMap::lookupModuleQualified(StringRef Name, Module *Context) const{
5522b82c2a5SDouglas Gregor   if (!Context)
5532b82c2a5SDouglas Gregor     return findModule(Name);
5542b82c2a5SDouglas Gregor 
555eb90e830SDouglas Gregor   return Context->findSubmodule(Name);
5562b82c2a5SDouglas Gregor }
5572b82c2a5SDouglas Gregor 
5589ffe5a35SDavid Blaikie std::pair<Module *, bool> ModuleMap::findOrCreateModule(StringRef Name,
5599ffe5a35SDavid Blaikie                                                         Module *Parent,
5609ffe5a35SDavid Blaikie                                                         bool IsFramework,
56169021974SDouglas Gregor                                                         bool IsExplicit) {
56269021974SDouglas Gregor   // Try to find an existing module with this name.
563eb90e830SDouglas Gregor   if (Module *Sub = lookupModuleQualified(Name, Parent))
564eb90e830SDouglas Gregor     return std::make_pair(Sub, false);
56569021974SDouglas Gregor 
56669021974SDouglas Gregor   // Create a new module with this name.
5679ffe5a35SDavid Blaikie   Module *Result = new Module(Name, SourceLocation(), Parent, IsFramework,
5689ffe5a35SDavid Blaikie                               IsExplicit, NumCreatedModules++);
5696f722b4eSArgyrios Kyrtzidis   if (!Parent) {
5707e82e019SRichard Smith     if (LangOpts.CurrentModule == Name)
5717e82e019SRichard Smith       SourceModule = Result;
57269021974SDouglas Gregor     Modules[Name] = Result;
5736f722b4eSArgyrios Kyrtzidis   }
57469021974SDouglas Gregor   return std::make_pair(Result, true);
57569021974SDouglas Gregor }
57669021974SDouglas Gregor 
577bbcc9f04SRichard Smith Module *ModuleMap::createModuleForInterfaceUnit(SourceLocation Loc,
578bbcc9f04SRichard Smith                                                 StringRef Name) {
579bbcc9f04SRichard Smith   assert(LangOpts.CurrentModule == Name && "module name mismatch");
580bbcc9f04SRichard Smith   assert(!Modules[Name] && "redefining existing module");
581bbcc9f04SRichard Smith 
582bbcc9f04SRichard Smith   auto *Result =
583bbcc9f04SRichard Smith       new Module(Name, Loc, nullptr, /*IsFramework*/ false,
584bbcc9f04SRichard Smith                  /*IsExplicit*/ false, NumCreatedModules++);
585bbcc9f04SRichard Smith   Modules[Name] = SourceModule = Result;
586bbcc9f04SRichard Smith 
587bbcc9f04SRichard Smith   // Mark the main source file as being within the newly-created module so that
588bbcc9f04SRichard Smith   // declarations and macros are properly visibility-restricted to it.
589bbcc9f04SRichard Smith   auto *MainFile = SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
590bbcc9f04SRichard Smith   assert(MainFile && "no input file for module interface");
591bbcc9f04SRichard Smith   Headers[MainFile].push_back(KnownHeader(Result, PrivateHeader));
592bbcc9f04SRichard Smith 
593bbcc9f04SRichard Smith   return Result;
594bbcc9f04SRichard Smith }
595bbcc9f04SRichard Smith 
59611dfe6feSDouglas Gregor /// \brief For a framework module, infer the framework against which we
59711dfe6feSDouglas Gregor /// should link.
59811dfe6feSDouglas Gregor static void inferFrameworkLink(Module *Mod, const DirectoryEntry *FrameworkDir,
59911dfe6feSDouglas Gregor                                FileManager &FileMgr) {
60011dfe6feSDouglas Gregor   assert(Mod->IsFramework && "Can only infer linking for framework modules");
60111dfe6feSDouglas Gregor   assert(!Mod->isSubFramework() &&
60211dfe6feSDouglas Gregor          "Can only infer linking for top-level frameworks");
60311dfe6feSDouglas Gregor 
60411dfe6feSDouglas Gregor   SmallString<128> LibName;
60511dfe6feSDouglas Gregor   LibName += FrameworkDir->getName();
60611dfe6feSDouglas Gregor   llvm::sys::path::append(LibName, Mod->Name);
6078aaae5a9SJuergen Ributzka 
6088aaae5a9SJuergen Ributzka   // The library name of a framework has more than one possible extension since
6098aaae5a9SJuergen Ributzka   // the introduction of the text-based dynamic library format. We need to check
6108aaae5a9SJuergen Ributzka   // for both before we give up.
6118013e81dSBenjamin Kramer   for (const char *extension : {"", ".tbd"}) {
6128aaae5a9SJuergen Ributzka     llvm::sys::path::replace_extension(LibName, extension);
61311dfe6feSDouglas Gregor     if (FileMgr.getFile(LibName)) {
61411dfe6feSDouglas Gregor       Mod->LinkLibraries.push_back(Module::LinkLibrary(Mod->Name,
61511dfe6feSDouglas Gregor                                                        /*IsFramework=*/true));
6168aaae5a9SJuergen Ributzka       return;
6178aaae5a9SJuergen Ributzka     }
61811dfe6feSDouglas Gregor   }
61911dfe6feSDouglas Gregor }
62011dfe6feSDouglas Gregor 
621a525400dSBen Langmuir Module *ModuleMap::inferFrameworkModule(const DirectoryEntry *FrameworkDir,
622a525400dSBen Langmuir                                         bool IsSystem, Module *Parent) {
623c1d88ea5SBen Langmuir   Attributes Attrs;
624c1d88ea5SBen Langmuir   Attrs.IsSystem = IsSystem;
625a525400dSBen Langmuir   return inferFrameworkModule(FrameworkDir, Attrs, Parent);
626c1d88ea5SBen Langmuir }
627c1d88ea5SBen Langmuir 
628a525400dSBen Langmuir Module *ModuleMap::inferFrameworkModule(const DirectoryEntry *FrameworkDir,
629c1d88ea5SBen Langmuir                                         Attributes Attrs, Module *Parent) {
630a525400dSBen Langmuir   // Note: as an egregious but useful hack we use the real path here, because
631a525400dSBen Langmuir   // we might be looking at an embedded framework that symlinks out to a
632a525400dSBen Langmuir   // top-level framework, and we need to infer as if we were naming the
633a525400dSBen Langmuir   // top-level framework.
634a525400dSBen Langmuir   StringRef FrameworkDirName =
635a525400dSBen Langmuir       SourceMgr.getFileManager().getCanonicalName(FrameworkDir);
636a525400dSBen Langmuir 
637a525400dSBen Langmuir   // In case this is a case-insensitive filesystem, use the canonical
638a525400dSBen Langmuir   // directory name as the ModuleName, since modules are case-sensitive.
639a525400dSBen Langmuir   // FIXME: we should be able to give a fix-it hint for the correct spelling.
640a525400dSBen Langmuir   SmallString<32> ModuleNameStorage;
641a525400dSBen Langmuir   StringRef ModuleName = sanitizeFilenameAsIdentifier(
642a525400dSBen Langmuir       llvm::sys::path::stem(FrameworkDirName), ModuleNameStorage);
643c1d88ea5SBen Langmuir 
64456c64013SDouglas Gregor   // Check whether we've already found this module.
645e89dbc1dSDouglas Gregor   if (Module *Mod = lookupModuleQualified(ModuleName, Parent))
646e89dbc1dSDouglas Gregor     return Mod;
647e89dbc1dSDouglas Gregor 
6481f76c4e8SManuel Klimek   FileManager &FileMgr = SourceMgr.getFileManager();
64956c64013SDouglas Gregor 
6509194a91dSDouglas Gregor   // If the framework has a parent path from which we're allowed to infer
6519194a91dSDouglas Gregor   // a framework module, do so.
652beee15e7SBen Langmuir   const FileEntry *ModuleMapFile = nullptr;
6539194a91dSDouglas Gregor   if (!Parent) {
6544ddf2221SDouglas Gregor     // Determine whether we're allowed to infer a module map.
6559194a91dSDouglas Gregor     bool canInfer = false;
6564ddf2221SDouglas Gregor     if (llvm::sys::path::has_parent_path(FrameworkDirName)) {
6579194a91dSDouglas Gregor       // Figure out the parent path.
6584ddf2221SDouglas Gregor       StringRef Parent = llvm::sys::path::parent_path(FrameworkDirName);
6599194a91dSDouglas Gregor       if (const DirectoryEntry *ParentDir = FileMgr.getDirectory(Parent)) {
6609194a91dSDouglas Gregor         // Check whether we have already looked into the parent directory
6619194a91dSDouglas Gregor         // for a module map.
662e4412640SArgyrios Kyrtzidis         llvm::DenseMap<const DirectoryEntry *, InferredDirectory>::const_iterator
6639194a91dSDouglas Gregor           inferred = InferredDirectories.find(ParentDir);
6649194a91dSDouglas Gregor         if (inferred == InferredDirectories.end()) {
6659194a91dSDouglas Gregor           // We haven't looked here before. Load a module map, if there is
6669194a91dSDouglas Gregor           // one.
667984e1df7SBen Langmuir           bool IsFrameworkDir = Parent.endswith(".framework");
668984e1df7SBen Langmuir           if (const FileEntry *ModMapFile =
669984e1df7SBen Langmuir                 HeaderInfo.lookupModuleMapFile(ParentDir, IsFrameworkDir)) {
670c1d88ea5SBen Langmuir             parseModuleMapFile(ModMapFile, Attrs.IsSystem, ParentDir);
6719194a91dSDouglas Gregor             inferred = InferredDirectories.find(ParentDir);
6729194a91dSDouglas Gregor           }
6739194a91dSDouglas Gregor 
6749194a91dSDouglas Gregor           if (inferred == InferredDirectories.end())
6759194a91dSDouglas Gregor             inferred = InferredDirectories.insert(
6769194a91dSDouglas Gregor                          std::make_pair(ParentDir, InferredDirectory())).first;
6779194a91dSDouglas Gregor         }
6789194a91dSDouglas Gregor 
6799194a91dSDouglas Gregor         if (inferred->second.InferModules) {
6809194a91dSDouglas Gregor           // We're allowed to infer for this directory, but make sure it's okay
6819194a91dSDouglas Gregor           // to infer this particular module.
6824ddf2221SDouglas Gregor           StringRef Name = llvm::sys::path::stem(FrameworkDirName);
6839194a91dSDouglas Gregor           canInfer = std::find(inferred->second.ExcludedModules.begin(),
6849194a91dSDouglas Gregor                                inferred->second.ExcludedModules.end(),
6859194a91dSDouglas Gregor                                Name) == inferred->second.ExcludedModules.end();
6869194a91dSDouglas Gregor 
687c1d88ea5SBen Langmuir           Attrs.IsSystem |= inferred->second.Attrs.IsSystem;
688c1d88ea5SBen Langmuir           Attrs.IsExternC |= inferred->second.Attrs.IsExternC;
689c1d88ea5SBen Langmuir           Attrs.IsExhaustive |= inferred->second.Attrs.IsExhaustive;
690ed84df00SBruno Cardoso Lopes           Attrs.NoUndeclaredIncludes |=
691ed84df00SBruno Cardoso Lopes               inferred->second.Attrs.NoUndeclaredIncludes;
692beee15e7SBen Langmuir           ModuleMapFile = inferred->second.ModuleMapFile;
6939194a91dSDouglas Gregor         }
6949194a91dSDouglas Gregor       }
6959194a91dSDouglas Gregor     }
6969194a91dSDouglas Gregor 
6979194a91dSDouglas Gregor     // If we're not allowed to infer a framework module, don't.
6989194a91dSDouglas Gregor     if (!canInfer)
699d2d442caSCraig Topper       return nullptr;
700beee15e7SBen Langmuir   } else
7019d6448b1SBen Langmuir     ModuleMapFile = getModuleMapFileForUniquing(Parent);
7029194a91dSDouglas Gregor 
7039194a91dSDouglas Gregor 
70456c64013SDouglas Gregor   // Look for an umbrella header.
7052c1dd271SDylan Noblesmith   SmallString<128> UmbrellaName = StringRef(FrameworkDir->getName());
70617381a06SBenjamin Kramer   llvm::sys::path::append(UmbrellaName, "Headers", ModuleName + ".h");
707e89dbc1dSDouglas Gregor   const FileEntry *UmbrellaHeader = FileMgr.getFile(UmbrellaName);
70856c64013SDouglas Gregor 
70956c64013SDouglas Gregor   // FIXME: If there's no umbrella header, we could probably scan the
71056c64013SDouglas Gregor   // framework to load *everything*. But, it's not clear that this is a good
71156c64013SDouglas Gregor   // idea.
71256c64013SDouglas Gregor   if (!UmbrellaHeader)
713d2d442caSCraig Topper     return nullptr;
71456c64013SDouglas Gregor 
7159d6448b1SBen Langmuir   Module *Result = new Module(ModuleName, SourceLocation(), Parent,
716a7e2cc68SRichard Smith                               /*IsFramework=*/true, /*IsExplicit=*/false,
717a7e2cc68SRichard Smith                               NumCreatedModules++);
7189d6448b1SBen Langmuir   InferredModuleAllowedBy[Result] = ModuleMapFile;
7199d6448b1SBen Langmuir   Result->IsInferred = true;
7207e82e019SRichard Smith   if (!Parent) {
7217e82e019SRichard Smith     if (LangOpts.CurrentModule == ModuleName)
722ba7f2f71SDaniel Jasper       SourceModule = Result;
7237e82e019SRichard Smith     Modules[ModuleName] = Result;
724ba7f2f71SDaniel Jasper   }
725c1d88ea5SBen Langmuir 
726c1d88ea5SBen Langmuir   Result->IsSystem |= Attrs.IsSystem;
727c1d88ea5SBen Langmuir   Result->IsExternC |= Attrs.IsExternC;
728c1d88ea5SBen Langmuir   Result->ConfigMacrosExhaustive |= Attrs.IsExhaustive;
729ed84df00SBruno Cardoso Lopes   Result->NoUndeclaredIncludes |= Attrs.NoUndeclaredIncludes;
7302b63d15fSRichard Smith   Result->Directory = FrameworkDir;
731a686e1b0SDouglas Gregor 
732322f633cSDouglas Gregor   // umbrella header "umbrella-header-name"
7332b63d15fSRichard Smith   //
7342b63d15fSRichard Smith   // The "Headers/" component of the name is implied because this is
7352b63d15fSRichard Smith   // a framework module.
7362b63d15fSRichard Smith   setUmbrellaHeader(Result, UmbrellaHeader, ModuleName + ".h");
737d8bd7537SDouglas Gregor 
738d8bd7537SDouglas Gregor   // export *
739d2d442caSCraig Topper   Result->Exports.push_back(Module::ExportDecl(nullptr, true));
740d8bd7537SDouglas Gregor 
741a89c5ac4SDouglas Gregor   // module * { export * }
742a89c5ac4SDouglas Gregor   Result->InferSubmodules = true;
743a89c5ac4SDouglas Gregor   Result->InferExportWildcard = true;
744a89c5ac4SDouglas Gregor 
745e89dbc1dSDouglas Gregor   // Look for subframeworks.
746c080917eSRafael Espindola   std::error_code EC;
7472c1dd271SDylan Noblesmith   SmallString<128> SubframeworksDirName
748ddaa69cbSDouglas Gregor     = StringRef(FrameworkDir->getName());
749e89dbc1dSDouglas Gregor   llvm::sys::path::append(SubframeworksDirName, "Frameworks");
7502d4d8cb3SBenjamin Kramer   llvm::sys::path::native(SubframeworksDirName);
751b171a59bSBruno Cardoso Lopes   vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
752b171a59bSBruno Cardoso Lopes   for (vfs::directory_iterator Dir = FS.dir_begin(SubframeworksDirName, EC),
753b171a59bSBruno Cardoso Lopes                                DirEnd;
754e89dbc1dSDouglas Gregor        Dir != DirEnd && !EC; Dir.increment(EC)) {
755b171a59bSBruno Cardoso Lopes     if (!StringRef(Dir->getName()).endswith(".framework"))
756e89dbc1dSDouglas Gregor       continue;
757f2161a70SDouglas Gregor 
758b171a59bSBruno Cardoso Lopes     if (const DirectoryEntry *SubframeworkDir =
759b171a59bSBruno Cardoso Lopes             FileMgr.getDirectory(Dir->getName())) {
76007c22b78SDouglas Gregor       // Note: as an egregious but useful hack, we use the real path here and
76107c22b78SDouglas Gregor       // check whether it is actually a subdirectory of the parent directory.
76207c22b78SDouglas Gregor       // This will not be the case if the 'subframework' is actually a symlink
76307c22b78SDouglas Gregor       // out to a top-level framework.
764e00c8b20SDouglas Gregor       StringRef SubframeworkDirName = FileMgr.getCanonicalName(SubframeworkDir);
76507c22b78SDouglas Gregor       bool FoundParent = false;
76607c22b78SDouglas Gregor       do {
76707c22b78SDouglas Gregor         // Get the parent directory name.
76807c22b78SDouglas Gregor         SubframeworkDirName
76907c22b78SDouglas Gregor           = llvm::sys::path::parent_path(SubframeworkDirName);
77007c22b78SDouglas Gregor         if (SubframeworkDirName.empty())
77107c22b78SDouglas Gregor           break;
77207c22b78SDouglas Gregor 
77307c22b78SDouglas Gregor         if (FileMgr.getDirectory(SubframeworkDirName) == FrameworkDir) {
77407c22b78SDouglas Gregor           FoundParent = true;
77507c22b78SDouglas Gregor           break;
77607c22b78SDouglas Gregor         }
77707c22b78SDouglas Gregor       } while (true);
77807c22b78SDouglas Gregor 
77907c22b78SDouglas Gregor       if (!FoundParent)
78007c22b78SDouglas Gregor         continue;
78107c22b78SDouglas Gregor 
782e89dbc1dSDouglas Gregor       // FIXME: Do we want to warn about subframeworks without umbrella headers?
783a525400dSBen Langmuir       inferFrameworkModule(SubframeworkDir, Attrs, Result);
784e89dbc1dSDouglas Gregor     }
785e89dbc1dSDouglas Gregor   }
786e89dbc1dSDouglas Gregor 
78711dfe6feSDouglas Gregor   // If the module is a top-level framework, automatically link against the
78811dfe6feSDouglas Gregor   // framework.
78911dfe6feSDouglas Gregor   if (!Result->isSubFramework()) {
79011dfe6feSDouglas Gregor     inferFrameworkLink(Result, FrameworkDir, FileMgr);
79111dfe6feSDouglas Gregor   }
79211dfe6feSDouglas Gregor 
79356c64013SDouglas Gregor   return Result;
79456c64013SDouglas Gregor }
79556c64013SDouglas Gregor 
7962b63d15fSRichard Smith void ModuleMap::setUmbrellaHeader(Module *Mod, const FileEntry *UmbrellaHeader,
7972b63d15fSRichard Smith                                   Twine NameAsWritten) {
79897da9178SDaniel Jasper   Headers[UmbrellaHeader].push_back(KnownHeader(Mod, NormalHeader));
79973141fa9SDouglas Gregor   Mod->Umbrella = UmbrellaHeader;
8002b63d15fSRichard Smith   Mod->UmbrellaAsWritten = NameAsWritten.str();
8017033127bSDouglas Gregor   UmbrellaDirs[UmbrellaHeader->getDir()] = Mod;
802b3a0fa48SBruno Cardoso Lopes 
803b3a0fa48SBruno Cardoso Lopes   // Notify callbacks that we just added a new header.
804b3a0fa48SBruno Cardoso Lopes   for (const auto &Cb : Callbacks)
805b3a0fa48SBruno Cardoso Lopes     Cb->moduleMapAddUmbrellaHeader(&SourceMgr.getFileManager(), UmbrellaHeader);
806a89c5ac4SDouglas Gregor }
807a89c5ac4SDouglas Gregor 
8082b63d15fSRichard Smith void ModuleMap::setUmbrellaDir(Module *Mod, const DirectoryEntry *UmbrellaDir,
8092b63d15fSRichard Smith                                Twine NameAsWritten) {
810524e33e1SDouglas Gregor   Mod->Umbrella = UmbrellaDir;
8112b63d15fSRichard Smith   Mod->UmbrellaAsWritten = NameAsWritten.str();
812524e33e1SDouglas Gregor   UmbrellaDirs[UmbrellaDir] = Mod;
813524e33e1SDouglas Gregor }
814524e33e1SDouglas Gregor 
8153c1a41adSRichard Smith static Module::HeaderKind headerRoleToKind(ModuleMap::ModuleHeaderRole Role) {
8160e98d938SNAKAMURA Takumi   switch ((int)Role) {
8173c1a41adSRichard Smith   default: llvm_unreachable("unknown header role");
8183c1a41adSRichard Smith   case ModuleMap::NormalHeader:
8193c1a41adSRichard Smith     return Module::HK_Normal;
8203c1a41adSRichard Smith   case ModuleMap::PrivateHeader:
8213c1a41adSRichard Smith     return Module::HK_Private;
8223c1a41adSRichard Smith   case ModuleMap::TextualHeader:
8233c1a41adSRichard Smith     return Module::HK_Textual;
8243c1a41adSRichard Smith   case ModuleMap::PrivateHeader | ModuleMap::TextualHeader:
8253c1a41adSRichard Smith     return Module::HK_PrivateTextual;
8263c1a41adSRichard Smith   }
8270e98d938SNAKAMURA Takumi }
828202210b3SRichard Smith 
8293c1a41adSRichard Smith void ModuleMap::addHeader(Module *Mod, Module::Header Header,
830d8879c85SRichard Smith                           ModuleHeaderRole Role, bool Imported) {
831386bb073SRichard Smith   KnownHeader KH(Mod, Role);
8323c1a41adSRichard Smith 
833386bb073SRichard Smith   // Only add each header to the headers list once.
834386bb073SRichard Smith   // FIXME: Should we diagnose if a header is listed twice in the
835386bb073SRichard Smith   // same module definition?
836386bb073SRichard Smith   auto &HeaderList = Headers[Header.Entry];
837386bb073SRichard Smith   for (auto H : HeaderList)
838386bb073SRichard Smith     if (H == KH)
839386bb073SRichard Smith       return;
840386bb073SRichard Smith 
841386bb073SRichard Smith   HeaderList.push_back(KH);
8421ec383c7SPiotr Padlewski   Mod->Headers[headerRoleToKind(Role)].push_back(Header);
843386bb073SRichard Smith 
8447e82e019SRichard Smith   bool isCompilingModuleHeader =
845bbcc9f04SRichard Smith       LangOpts.isCompilingModule() && Mod->getTopLevelModule() == SourceModule;
846d8879c85SRichard Smith   if (!Imported || isCompilingModuleHeader) {
847d8879c85SRichard Smith     // When we import HeaderFileInfo, the external source is expected to
848d8879c85SRichard Smith     // set the isModuleHeader flag itself.
849d8879c85SRichard Smith     HeaderInfo.MarkFileModuleHeader(Header.Entry, Role,
850d8879c85SRichard Smith                                     isCompilingModuleHeader);
851d8879c85SRichard Smith   }
852e62cfd7cSBruno Cardoso Lopes 
853e62cfd7cSBruno Cardoso Lopes   // Notify callbacks that we just added a new header.
854e62cfd7cSBruno Cardoso Lopes   for (const auto &Cb : Callbacks)
855f0841790SBruno Cardoso Lopes     Cb->moduleMapAddHeader(Header.Entry->getName());
856a89c5ac4SDouglas Gregor }
857a89c5ac4SDouglas Gregor 
8583c1a41adSRichard Smith void ModuleMap::excludeHeader(Module *Mod, Module::Header Header) {
859feb54b6dSRichard Smith   // Add this as a known header so we won't implicitly add it to any
860feb54b6dSRichard Smith   // umbrella directory module.
861feb54b6dSRichard Smith   // FIXME: Should we only exclude it from umbrella modules within the
862feb54b6dSRichard Smith   // specified module?
8633c1a41adSRichard Smith   (void) Headers[Header.Entry];
8643c1a41adSRichard Smith 
8653c1a41adSRichard Smith   Mod->Headers[Module::HK_Excluded].push_back(std::move(Header));
866feb54b6dSRichard Smith }
867feb54b6dSRichard Smith 
868514b636aSDouglas Gregor const FileEntry *
8694b8a9e95SBen Langmuir ModuleMap::getContainingModuleMapFile(const Module *Module) const {
8701f76c4e8SManuel Klimek   if (Module->DefinitionLoc.isInvalid())
871d2d442caSCraig Topper     return nullptr;
872514b636aSDouglas Gregor 
8731f76c4e8SManuel Klimek   return SourceMgr.getFileEntryForID(
8741f76c4e8SManuel Klimek            SourceMgr.getFileID(Module->DefinitionLoc));
875514b636aSDouglas Gregor }
876514b636aSDouglas Gregor 
8774b8a9e95SBen Langmuir const FileEntry *ModuleMap::getModuleMapFileForUniquing(const Module *M) const {
8789d6448b1SBen Langmuir   if (M->IsInferred) {
8799d6448b1SBen Langmuir     assert(InferredModuleAllowedBy.count(M) && "missing inferred module map");
8809d6448b1SBen Langmuir     return InferredModuleAllowedBy.find(M)->second;
8819d6448b1SBen Langmuir   }
8829d6448b1SBen Langmuir   return getContainingModuleMapFile(M);
8839d6448b1SBen Langmuir }
8849d6448b1SBen Langmuir 
8859d6448b1SBen Langmuir void ModuleMap::setInferredModuleAllowedBy(Module *M, const FileEntry *ModMap) {
8869d6448b1SBen Langmuir   assert(M->IsInferred && "module not inferred");
8879d6448b1SBen Langmuir   InferredModuleAllowedBy[M] = ModMap;
8889d6448b1SBen Langmuir }
8899d6448b1SBen Langmuir 
890cdae941eSYaron Keren LLVM_DUMP_METHOD void ModuleMap::dump() {
891718292f2SDouglas Gregor   llvm::errs() << "Modules:";
892718292f2SDouglas Gregor   for (llvm::StringMap<Module *>::iterator M = Modules.begin(),
893718292f2SDouglas Gregor                                         MEnd = Modules.end();
894718292f2SDouglas Gregor        M != MEnd; ++M)
895d28d1b8dSDouglas Gregor     M->getValue()->print(llvm::errs(), 2);
896718292f2SDouglas Gregor 
897718292f2SDouglas Gregor   llvm::errs() << "Headers:";
89859527666SDouglas Gregor   for (HeadersMap::iterator H = Headers.begin(), HEnd = Headers.end();
899718292f2SDouglas Gregor        H != HEnd; ++H) {
90097da9178SDaniel Jasper     llvm::errs() << "  \"" << H->first->getName() << "\" -> ";
90197da9178SDaniel Jasper     for (SmallVectorImpl<KnownHeader>::const_iterator I = H->second.begin(),
90297da9178SDaniel Jasper                                                       E = H->second.end();
90397da9178SDaniel Jasper          I != E; ++I) {
90497da9178SDaniel Jasper       if (I != H->second.begin())
90597da9178SDaniel Jasper         llvm::errs() << ",";
90697da9178SDaniel Jasper       llvm::errs() << I->getModule()->getFullModuleName();
90797da9178SDaniel Jasper     }
90897da9178SDaniel Jasper     llvm::errs() << "\n";
909718292f2SDouglas Gregor   }
910718292f2SDouglas Gregor }
911718292f2SDouglas Gregor 
9122b82c2a5SDouglas Gregor bool ModuleMap::resolveExports(Module *Mod, bool Complain) {
91342413141SRichard Smith   auto Unresolved = std::move(Mod->UnresolvedExports);
91442413141SRichard Smith   Mod->UnresolvedExports.clear();
91542413141SRichard Smith   for (auto &UE : Unresolved) {
91642413141SRichard Smith     Module::ExportDecl Export = resolveExport(Mod, UE, Complain);
917f5eedd05SDouglas Gregor     if (Export.getPointer() || Export.getInt())
9182b82c2a5SDouglas Gregor       Mod->Exports.push_back(Export);
9192b82c2a5SDouglas Gregor     else
92042413141SRichard Smith       Mod->UnresolvedExports.push_back(UE);
9212b82c2a5SDouglas Gregor   }
92242413141SRichard Smith   return !Mod->UnresolvedExports.empty();
9232b82c2a5SDouglas Gregor }
9242b82c2a5SDouglas Gregor 
925ba7f2f71SDaniel Jasper bool ModuleMap::resolveUses(Module *Mod, bool Complain) {
92642413141SRichard Smith   auto Unresolved = std::move(Mod->UnresolvedDirectUses);
92742413141SRichard Smith   Mod->UnresolvedDirectUses.clear();
92842413141SRichard Smith   for (auto &UDU : Unresolved) {
92942413141SRichard Smith     Module *DirectUse = resolveModuleId(UDU, Mod, Complain);
930ba7f2f71SDaniel Jasper     if (DirectUse)
931ba7f2f71SDaniel Jasper       Mod->DirectUses.push_back(DirectUse);
932ba7f2f71SDaniel Jasper     else
93342413141SRichard Smith       Mod->UnresolvedDirectUses.push_back(UDU);
934ba7f2f71SDaniel Jasper   }
93542413141SRichard Smith   return !Mod->UnresolvedDirectUses.empty();
936ba7f2f71SDaniel Jasper }
937ba7f2f71SDaniel Jasper 
938fb912657SDouglas Gregor bool ModuleMap::resolveConflicts(Module *Mod, bool Complain) {
93942413141SRichard Smith   auto Unresolved = std::move(Mod->UnresolvedConflicts);
94042413141SRichard Smith   Mod->UnresolvedConflicts.clear();
94142413141SRichard Smith   for (auto &UC : Unresolved) {
94242413141SRichard Smith     if (Module *OtherMod = resolveModuleId(UC.Id, Mod, Complain)) {
943fb912657SDouglas Gregor       Module::Conflict Conflict;
944fb912657SDouglas Gregor       Conflict.Other = OtherMod;
94542413141SRichard Smith       Conflict.Message = UC.Message;
946fb912657SDouglas Gregor       Mod->Conflicts.push_back(Conflict);
94742413141SRichard Smith     } else
94842413141SRichard Smith       Mod->UnresolvedConflicts.push_back(UC);
949fb912657SDouglas Gregor   }
95042413141SRichard Smith   return !Mod->UnresolvedConflicts.empty();
951fb912657SDouglas Gregor }
952fb912657SDouglas Gregor 
9530093b3c7SDouglas Gregor Module *ModuleMap::inferModuleFromLocation(FullSourceLoc Loc) {
9540093b3c7SDouglas Gregor   if (Loc.isInvalid())
955d2d442caSCraig Topper     return nullptr;
9560093b3c7SDouglas Gregor 
9577ffd0b44SDavid Majnemer   if (UmbrellaDirs.empty() && Headers.empty())
9587ffd0b44SDavid Majnemer     return nullptr;
9597ffd0b44SDavid Majnemer 
9600093b3c7SDouglas Gregor   // Use the expansion location to determine which module we're in.
9610093b3c7SDouglas Gregor   FullSourceLoc ExpansionLoc = Loc.getExpansionLoc();
9620093b3c7SDouglas Gregor   if (!ExpansionLoc.isFileID())
963d2d442caSCraig Topper     return nullptr;
9640093b3c7SDouglas Gregor 
9650093b3c7SDouglas Gregor   const SourceManager &SrcMgr = Loc.getManager();
9660093b3c7SDouglas Gregor   FileID ExpansionFileID = ExpansionLoc.getFileID();
967224d8a74SDouglas Gregor 
968224d8a74SDouglas Gregor   while (const FileEntry *ExpansionFile
969224d8a74SDouglas Gregor            = SrcMgr.getFileEntryForID(ExpansionFileID)) {
970224d8a74SDouglas Gregor     // Find the module that owns this header (if any).
971b53e5483SLawrence Crowl     if (Module *Mod = findModuleForHeader(ExpansionFile).getModule())
972224d8a74SDouglas Gregor       return Mod;
973224d8a74SDouglas Gregor 
974224d8a74SDouglas Gregor     // No module owns this header, so look up the inclusion chain to see if
975224d8a74SDouglas Gregor     // any included header has an associated module.
976224d8a74SDouglas Gregor     SourceLocation IncludeLoc = SrcMgr.getIncludeLoc(ExpansionFileID);
977224d8a74SDouglas Gregor     if (IncludeLoc.isInvalid())
978d2d442caSCraig Topper       return nullptr;
9790093b3c7SDouglas Gregor 
980224d8a74SDouglas Gregor     ExpansionFileID = SrcMgr.getFileID(IncludeLoc);
981224d8a74SDouglas Gregor   }
982224d8a74SDouglas Gregor 
983d2d442caSCraig Topper   return nullptr;
9840093b3c7SDouglas Gregor }
9850093b3c7SDouglas Gregor 
986718292f2SDouglas Gregor //----------------------------------------------------------------------------//
987718292f2SDouglas Gregor // Module map file parser
988718292f2SDouglas Gregor //----------------------------------------------------------------------------//
989718292f2SDouglas Gregor 
990718292f2SDouglas Gregor namespace clang {
991718292f2SDouglas Gregor   /// \brief A token in a module map file.
992718292f2SDouglas Gregor   struct MMToken {
993718292f2SDouglas Gregor     enum TokenKind {
9941fb5c3a6SDouglas Gregor       Comma,
99535b13eceSDouglas Gregor       ConfigMacros,
996fb912657SDouglas Gregor       Conflict,
997718292f2SDouglas Gregor       EndOfFile,
998718292f2SDouglas Gregor       HeaderKeyword,
999718292f2SDouglas Gregor       Identifier,
1000a3feee2aSRichard Smith       Exclaim,
100159527666SDouglas Gregor       ExcludeKeyword,
1002718292f2SDouglas Gregor       ExplicitKeyword,
10032b82c2a5SDouglas Gregor       ExportKeyword,
100497292843SDaniel Jasper       ExternKeyword,
1005755b2055SDouglas Gregor       FrameworkKeyword,
10066ddfca91SDouglas Gregor       LinkKeyword,
1007718292f2SDouglas Gregor       ModuleKeyword,
10082b82c2a5SDouglas Gregor       Period,
1009b53e5483SLawrence Crowl       PrivateKeyword,
1010718292f2SDouglas Gregor       UmbrellaKeyword,
1011ba7f2f71SDaniel Jasper       UseKeyword,
10121fb5c3a6SDouglas Gregor       RequiresKeyword,
10132b82c2a5SDouglas Gregor       Star,
1014718292f2SDouglas Gregor       StringLiteral,
1015306d8920SRichard Smith       TextualKeyword,
1016718292f2SDouglas Gregor       LBrace,
1017a686e1b0SDouglas Gregor       RBrace,
1018a686e1b0SDouglas Gregor       LSquare,
1019a686e1b0SDouglas Gregor       RSquare
1020718292f2SDouglas Gregor     } Kind;
1021718292f2SDouglas Gregor 
1022718292f2SDouglas Gregor     unsigned Location;
1023718292f2SDouglas Gregor     unsigned StringLength;
1024718292f2SDouglas Gregor     const char *StringData;
1025718292f2SDouglas Gregor 
1026718292f2SDouglas Gregor     void clear() {
1027718292f2SDouglas Gregor       Kind = EndOfFile;
1028718292f2SDouglas Gregor       Location = 0;
1029718292f2SDouglas Gregor       StringLength = 0;
1030d2d442caSCraig Topper       StringData = nullptr;
1031718292f2SDouglas Gregor     }
1032718292f2SDouglas Gregor 
1033718292f2SDouglas Gregor     bool is(TokenKind K) const { return Kind == K; }
1034718292f2SDouglas Gregor 
1035718292f2SDouglas Gregor     SourceLocation getLocation() const {
1036718292f2SDouglas Gregor       return SourceLocation::getFromRawEncoding(Location);
1037718292f2SDouglas Gregor     }
1038718292f2SDouglas Gregor 
1039718292f2SDouglas Gregor     StringRef getString() const {
1040718292f2SDouglas Gregor       return StringRef(StringData, StringLength);
1041718292f2SDouglas Gregor     }
1042718292f2SDouglas Gregor   };
1043718292f2SDouglas Gregor 
1044718292f2SDouglas Gregor   class ModuleMapParser {
1045718292f2SDouglas Gregor     Lexer &L;
1046718292f2SDouglas Gregor     SourceManager &SourceMgr;
1047bc10b9fbSDouglas Gregor 
1048bc10b9fbSDouglas Gregor     /// \brief Default target information, used only for string literal
1049bc10b9fbSDouglas Gregor     /// parsing.
1050bc10b9fbSDouglas Gregor     const TargetInfo *Target;
1051bc10b9fbSDouglas Gregor 
1052718292f2SDouglas Gregor     DiagnosticsEngine &Diags;
1053718292f2SDouglas Gregor     ModuleMap &Map;
1054718292f2SDouglas Gregor 
1055beee15e7SBen Langmuir     /// \brief The current module map file.
1056beee15e7SBen Langmuir     const FileEntry *ModuleMapFile;
1057beee15e7SBen Langmuir 
10589acb99e3SRichard Smith     /// \brief The directory that file names in this module map file should
10599acb99e3SRichard Smith     /// be resolved relative to.
10605257fc63SDouglas Gregor     const DirectoryEntry *Directory;
10615257fc63SDouglas Gregor 
10623ec6663bSDouglas Gregor     /// \brief The directory containing Clang-supplied headers.
10633ec6663bSDouglas Gregor     const DirectoryEntry *BuiltinIncludeDir;
10643ec6663bSDouglas Gregor 
1065963c5535SDouglas Gregor     /// \brief Whether this module map is in a system header directory.
1066963c5535SDouglas Gregor     bool IsSystem;
1067963c5535SDouglas Gregor 
1068718292f2SDouglas Gregor     /// \brief Whether an error occurred.
1069718292f2SDouglas Gregor     bool HadError;
1070718292f2SDouglas Gregor 
1071718292f2SDouglas Gregor     /// \brief Stores string data for the various string literals referenced
1072718292f2SDouglas Gregor     /// during parsing.
1073718292f2SDouglas Gregor     llvm::BumpPtrAllocator StringData;
1074718292f2SDouglas Gregor 
1075718292f2SDouglas Gregor     /// \brief The current token.
1076718292f2SDouglas Gregor     MMToken Tok;
1077718292f2SDouglas Gregor 
1078718292f2SDouglas Gregor     /// \brief The active module.
1079de3ef502SDouglas Gregor     Module *ActiveModule;
1080718292f2SDouglas Gregor 
10817ff29148SBen Langmuir     /// \brief Whether a module uses the 'requires excluded' hack to mark its
10827ff29148SBen Langmuir     /// contents as 'textual'.
10837ff29148SBen Langmuir     ///
10847ff29148SBen Langmuir     /// On older Darwin SDK versions, 'requires excluded' is used to mark the
10857ff29148SBen Langmuir     /// contents of the Darwin.C.excluded (assert.h) and Tcl.Private modules as
10867ff29148SBen Langmuir     /// non-modular headers.  For backwards compatibility, we continue to
10877ff29148SBen Langmuir     /// support this idiom for just these modules, and map the headers to
10887ff29148SBen Langmuir     /// 'textual' to match the original intent.
10897ff29148SBen Langmuir     llvm::SmallPtrSet<Module *, 2> UsesRequiresExcludedHack;
10907ff29148SBen Langmuir 
1091718292f2SDouglas Gregor     /// \brief Consume the current token and return its location.
1092718292f2SDouglas Gregor     SourceLocation consumeToken();
1093718292f2SDouglas Gregor 
1094718292f2SDouglas Gregor     /// \brief Skip tokens until we reach the a token with the given kind
1095718292f2SDouglas Gregor     /// (or the end of the file).
1096718292f2SDouglas Gregor     void skipUntil(MMToken::TokenKind K);
1097718292f2SDouglas Gregor 
1098f857950dSDmitri Gribenko     typedef SmallVector<std::pair<std::string, SourceLocation>, 2> ModuleId;
1099e7ab3669SDouglas Gregor     bool parseModuleId(ModuleId &Id);
1100718292f2SDouglas Gregor     void parseModuleDecl();
110197292843SDaniel Jasper     void parseExternModuleDecl();
11021fb5c3a6SDouglas Gregor     void parseRequiresDecl();
1103b53e5483SLawrence Crowl     void parseHeaderDecl(clang::MMToken::TokenKind,
1104b53e5483SLawrence Crowl                          SourceLocation LeadingLoc);
1105524e33e1SDouglas Gregor     void parseUmbrellaDirDecl(SourceLocation UmbrellaLoc);
11062b82c2a5SDouglas Gregor     void parseExportDecl();
1107ba7f2f71SDaniel Jasper     void parseUseDecl();
11086ddfca91SDouglas Gregor     void parseLinkDecl();
110935b13eceSDouglas Gregor     void parseConfigMacros();
1110fb912657SDouglas Gregor     void parseConflict();
11119194a91dSDouglas Gregor     void parseInferredModuleDecl(bool Framework, bool Explicit);
1112c1d88ea5SBen Langmuir 
1113c1d88ea5SBen Langmuir     typedef ModuleMap::Attributes Attributes;
11144442605fSBill Wendling     bool parseOptionalAttributes(Attributes &Attrs);
1115718292f2SDouglas Gregor 
1116718292f2SDouglas Gregor   public:
1117718292f2SDouglas Gregor     explicit ModuleMapParser(Lexer &L, SourceManager &SourceMgr,
1118bc10b9fbSDouglas Gregor                              const TargetInfo *Target,
1119718292f2SDouglas Gregor                              DiagnosticsEngine &Diags,
11205257fc63SDouglas Gregor                              ModuleMap &Map,
1121beee15e7SBen Langmuir                              const FileEntry *ModuleMapFile,
11223ec6663bSDouglas Gregor                              const DirectoryEntry *Directory,
1123963c5535SDouglas Gregor                              const DirectoryEntry *BuiltinIncludeDir,
1124963c5535SDouglas Gregor                              bool IsSystem)
1125bc10b9fbSDouglas Gregor       : L(L), SourceMgr(SourceMgr), Target(Target), Diags(Diags), Map(Map),
1126beee15e7SBen Langmuir         ModuleMapFile(ModuleMapFile), Directory(Directory),
1127beee15e7SBen Langmuir         BuiltinIncludeDir(BuiltinIncludeDir), IsSystem(IsSystem),
1128d2d442caSCraig Topper         HadError(false), ActiveModule(nullptr)
1129718292f2SDouglas Gregor     {
1130718292f2SDouglas Gregor       Tok.clear();
1131718292f2SDouglas Gregor       consumeToken();
1132718292f2SDouglas Gregor     }
1133718292f2SDouglas Gregor 
1134718292f2SDouglas Gregor     bool parseModuleMapFile();
1135718292f2SDouglas Gregor   };
1136ab9db510SAlexander Kornienko }
1137718292f2SDouglas Gregor 
1138718292f2SDouglas Gregor SourceLocation ModuleMapParser::consumeToken() {
1139718292f2SDouglas Gregor retry:
1140718292f2SDouglas Gregor   SourceLocation Result = Tok.getLocation();
1141718292f2SDouglas Gregor   Tok.clear();
1142718292f2SDouglas Gregor 
1143718292f2SDouglas Gregor   Token LToken;
1144718292f2SDouglas Gregor   L.LexFromRawLexer(LToken);
1145718292f2SDouglas Gregor   Tok.Location = LToken.getLocation().getRawEncoding();
1146718292f2SDouglas Gregor   switch (LToken.getKind()) {
11472d57cea2SAlp Toker   case tok::raw_identifier: {
11482d57cea2SAlp Toker     StringRef RI = LToken.getRawIdentifier();
11492d57cea2SAlp Toker     Tok.StringData = RI.data();
11502d57cea2SAlp Toker     Tok.StringLength = RI.size();
11512d57cea2SAlp Toker     Tok.Kind = llvm::StringSwitch<MMToken::TokenKind>(RI)
115235b13eceSDouglas Gregor                  .Case("config_macros", MMToken::ConfigMacros)
1153fb912657SDouglas Gregor                  .Case("conflict", MMToken::Conflict)
115459527666SDouglas Gregor                  .Case("exclude", MMToken::ExcludeKeyword)
1155718292f2SDouglas Gregor                  .Case("explicit", MMToken::ExplicitKeyword)
11562b82c2a5SDouglas Gregor                  .Case("export", MMToken::ExportKeyword)
115797292843SDaniel Jasper                  .Case("extern", MMToken::ExternKeyword)
1158755b2055SDouglas Gregor                  .Case("framework", MMToken::FrameworkKeyword)
115935b13eceSDouglas Gregor                  .Case("header", MMToken::HeaderKeyword)
11606ddfca91SDouglas Gregor                  .Case("link", MMToken::LinkKeyword)
1161718292f2SDouglas Gregor                  .Case("module", MMToken::ModuleKeyword)
1162b53e5483SLawrence Crowl                  .Case("private", MMToken::PrivateKeyword)
11631fb5c3a6SDouglas Gregor                  .Case("requires", MMToken::RequiresKeyword)
1164306d8920SRichard Smith                  .Case("textual", MMToken::TextualKeyword)
1165718292f2SDouglas Gregor                  .Case("umbrella", MMToken::UmbrellaKeyword)
1166ba7f2f71SDaniel Jasper                  .Case("use", MMToken::UseKeyword)
1167718292f2SDouglas Gregor                  .Default(MMToken::Identifier);
1168718292f2SDouglas Gregor     break;
11692d57cea2SAlp Toker   }
1170718292f2SDouglas Gregor 
11711fb5c3a6SDouglas Gregor   case tok::comma:
11721fb5c3a6SDouglas Gregor     Tok.Kind = MMToken::Comma;
11731fb5c3a6SDouglas Gregor     break;
11741fb5c3a6SDouglas Gregor 
1175718292f2SDouglas Gregor   case tok::eof:
1176718292f2SDouglas Gregor     Tok.Kind = MMToken::EndOfFile;
1177718292f2SDouglas Gregor     break;
1178718292f2SDouglas Gregor 
1179718292f2SDouglas Gregor   case tok::l_brace:
1180718292f2SDouglas Gregor     Tok.Kind = MMToken::LBrace;
1181718292f2SDouglas Gregor     break;
1182718292f2SDouglas Gregor 
1183a686e1b0SDouglas Gregor   case tok::l_square:
1184a686e1b0SDouglas Gregor     Tok.Kind = MMToken::LSquare;
1185a686e1b0SDouglas Gregor     break;
1186a686e1b0SDouglas Gregor 
11872b82c2a5SDouglas Gregor   case tok::period:
11882b82c2a5SDouglas Gregor     Tok.Kind = MMToken::Period;
11892b82c2a5SDouglas Gregor     break;
11902b82c2a5SDouglas Gregor 
1191718292f2SDouglas Gregor   case tok::r_brace:
1192718292f2SDouglas Gregor     Tok.Kind = MMToken::RBrace;
1193718292f2SDouglas Gregor     break;
1194718292f2SDouglas Gregor 
1195a686e1b0SDouglas Gregor   case tok::r_square:
1196a686e1b0SDouglas Gregor     Tok.Kind = MMToken::RSquare;
1197a686e1b0SDouglas Gregor     break;
1198a686e1b0SDouglas Gregor 
11992b82c2a5SDouglas Gregor   case tok::star:
12002b82c2a5SDouglas Gregor     Tok.Kind = MMToken::Star;
12012b82c2a5SDouglas Gregor     break;
12022b82c2a5SDouglas Gregor 
1203a3feee2aSRichard Smith   case tok::exclaim:
1204a3feee2aSRichard Smith     Tok.Kind = MMToken::Exclaim;
1205a3feee2aSRichard Smith     break;
1206a3feee2aSRichard Smith 
1207718292f2SDouglas Gregor   case tok::string_literal: {
1208d67aea28SRichard Smith     if (LToken.hasUDSuffix()) {
1209d67aea28SRichard Smith       Diags.Report(LToken.getLocation(), diag::err_invalid_string_udl);
1210d67aea28SRichard Smith       HadError = true;
1211d67aea28SRichard Smith       goto retry;
1212d67aea28SRichard Smith     }
1213d67aea28SRichard Smith 
1214718292f2SDouglas Gregor     // Parse the string literal.
1215718292f2SDouglas Gregor     LangOptions LangOpts;
12169d5583efSCraig Topper     StringLiteralParser StringLiteral(LToken, SourceMgr, LangOpts, *Target);
1217718292f2SDouglas Gregor     if (StringLiteral.hadError)
1218718292f2SDouglas Gregor       goto retry;
1219718292f2SDouglas Gregor 
1220718292f2SDouglas Gregor     // Copy the string literal into our string data allocator.
1221718292f2SDouglas Gregor     unsigned Length = StringLiteral.GetStringLength();
1222718292f2SDouglas Gregor     char *Saved = StringData.Allocate<char>(Length + 1);
1223718292f2SDouglas Gregor     memcpy(Saved, StringLiteral.GetString().data(), Length);
1224718292f2SDouglas Gregor     Saved[Length] = 0;
1225718292f2SDouglas Gregor 
1226718292f2SDouglas Gregor     // Form the token.
1227718292f2SDouglas Gregor     Tok.Kind = MMToken::StringLiteral;
1228718292f2SDouglas Gregor     Tok.StringData = Saved;
1229718292f2SDouglas Gregor     Tok.StringLength = Length;
1230718292f2SDouglas Gregor     break;
1231718292f2SDouglas Gregor   }
1232718292f2SDouglas Gregor 
1233718292f2SDouglas Gregor   case tok::comment:
1234718292f2SDouglas Gregor     goto retry;
1235718292f2SDouglas Gregor 
1236718292f2SDouglas Gregor   default:
1237718292f2SDouglas Gregor     Diags.Report(LToken.getLocation(), diag::err_mmap_unknown_token);
1238718292f2SDouglas Gregor     HadError = true;
1239718292f2SDouglas Gregor     goto retry;
1240718292f2SDouglas Gregor   }
1241718292f2SDouglas Gregor 
1242718292f2SDouglas Gregor   return Result;
1243718292f2SDouglas Gregor }
1244718292f2SDouglas Gregor 
1245718292f2SDouglas Gregor void ModuleMapParser::skipUntil(MMToken::TokenKind K) {
1246718292f2SDouglas Gregor   unsigned braceDepth = 0;
1247a686e1b0SDouglas Gregor   unsigned squareDepth = 0;
1248718292f2SDouglas Gregor   do {
1249718292f2SDouglas Gregor     switch (Tok.Kind) {
1250718292f2SDouglas Gregor     case MMToken::EndOfFile:
1251718292f2SDouglas Gregor       return;
1252718292f2SDouglas Gregor 
1253718292f2SDouglas Gregor     case MMToken::LBrace:
1254a686e1b0SDouglas Gregor       if (Tok.is(K) && braceDepth == 0 && squareDepth == 0)
1255718292f2SDouglas Gregor         return;
1256718292f2SDouglas Gregor 
1257718292f2SDouglas Gregor       ++braceDepth;
1258718292f2SDouglas Gregor       break;
1259718292f2SDouglas Gregor 
1260a686e1b0SDouglas Gregor     case MMToken::LSquare:
1261a686e1b0SDouglas Gregor       if (Tok.is(K) && braceDepth == 0 && squareDepth == 0)
1262a686e1b0SDouglas Gregor         return;
1263a686e1b0SDouglas Gregor 
1264a686e1b0SDouglas Gregor       ++squareDepth;
1265a686e1b0SDouglas Gregor       break;
1266a686e1b0SDouglas Gregor 
1267718292f2SDouglas Gregor     case MMToken::RBrace:
1268718292f2SDouglas Gregor       if (braceDepth > 0)
1269718292f2SDouglas Gregor         --braceDepth;
1270718292f2SDouglas Gregor       else if (Tok.is(K))
1271718292f2SDouglas Gregor         return;
1272718292f2SDouglas Gregor       break;
1273718292f2SDouglas Gregor 
1274a686e1b0SDouglas Gregor     case MMToken::RSquare:
1275a686e1b0SDouglas Gregor       if (squareDepth > 0)
1276a686e1b0SDouglas Gregor         --squareDepth;
1277a686e1b0SDouglas Gregor       else if (Tok.is(K))
1278a686e1b0SDouglas Gregor         return;
1279a686e1b0SDouglas Gregor       break;
1280a686e1b0SDouglas Gregor 
1281718292f2SDouglas Gregor     default:
1282a686e1b0SDouglas Gregor       if (braceDepth == 0 && squareDepth == 0 && Tok.is(K))
1283718292f2SDouglas Gregor         return;
1284718292f2SDouglas Gregor       break;
1285718292f2SDouglas Gregor     }
1286718292f2SDouglas Gregor 
1287718292f2SDouglas Gregor    consumeToken();
1288718292f2SDouglas Gregor   } while (true);
1289718292f2SDouglas Gregor }
1290718292f2SDouglas Gregor 
1291e7ab3669SDouglas Gregor /// \brief Parse a module-id.
1292e7ab3669SDouglas Gregor ///
1293e7ab3669SDouglas Gregor ///   module-id:
1294e7ab3669SDouglas Gregor ///     identifier
1295e7ab3669SDouglas Gregor ///     identifier '.' module-id
1296e7ab3669SDouglas Gregor ///
1297e7ab3669SDouglas Gregor /// \returns true if an error occurred, false otherwise.
1298e7ab3669SDouglas Gregor bool ModuleMapParser::parseModuleId(ModuleId &Id) {
1299e7ab3669SDouglas Gregor   Id.clear();
1300e7ab3669SDouglas Gregor   do {
13013cd34c76SDaniel Jasper     if (Tok.is(MMToken::Identifier) || Tok.is(MMToken::StringLiteral)) {
1302e7ab3669SDouglas Gregor       Id.push_back(std::make_pair(Tok.getString(), Tok.getLocation()));
1303e7ab3669SDouglas Gregor       consumeToken();
1304e7ab3669SDouglas Gregor     } else {
1305e7ab3669SDouglas Gregor       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module_name);
1306e7ab3669SDouglas Gregor       return true;
1307e7ab3669SDouglas Gregor     }
1308e7ab3669SDouglas Gregor 
1309e7ab3669SDouglas Gregor     if (!Tok.is(MMToken::Period))
1310e7ab3669SDouglas Gregor       break;
1311e7ab3669SDouglas Gregor 
1312e7ab3669SDouglas Gregor     consumeToken();
1313e7ab3669SDouglas Gregor   } while (true);
1314e7ab3669SDouglas Gregor 
1315e7ab3669SDouglas Gregor   return false;
1316e7ab3669SDouglas Gregor }
1317e7ab3669SDouglas Gregor 
1318a686e1b0SDouglas Gregor namespace {
1319a686e1b0SDouglas Gregor   /// \brief Enumerates the known attributes.
1320a686e1b0SDouglas Gregor   enum AttributeKind {
1321a686e1b0SDouglas Gregor     /// \brief An unknown attribute.
1322a686e1b0SDouglas Gregor     AT_unknown,
1323a686e1b0SDouglas Gregor     /// \brief The 'system' attribute.
132435b13eceSDouglas Gregor     AT_system,
132577944868SRichard Smith     /// \brief The 'extern_c' attribute.
132677944868SRichard Smith     AT_extern_c,
132735b13eceSDouglas Gregor     /// \brief The 'exhaustive' attribute.
1328ed84df00SBruno Cardoso Lopes     AT_exhaustive,
1329ed84df00SBruno Cardoso Lopes     /// \brief The 'no_undeclared_includes' attribute.
1330ed84df00SBruno Cardoso Lopes     AT_no_undeclared_includes
1331a686e1b0SDouglas Gregor   };
1332ab9db510SAlexander Kornienko }
1333a686e1b0SDouglas Gregor 
1334718292f2SDouglas Gregor /// \brief Parse a module declaration.
1335718292f2SDouglas Gregor ///
1336718292f2SDouglas Gregor ///   module-declaration:
133797292843SDaniel Jasper ///     'extern' 'module' module-id string-literal
1338a686e1b0SDouglas Gregor ///     'explicit'[opt] 'framework'[opt] 'module' module-id attributes[opt]
1339a686e1b0SDouglas Gregor ///       { module-member* }
1340a686e1b0SDouglas Gregor ///
1341718292f2SDouglas Gregor ///   module-member:
13421fb5c3a6SDouglas Gregor ///     requires-declaration
1343718292f2SDouglas Gregor ///     header-declaration
1344e7ab3669SDouglas Gregor ///     submodule-declaration
13452b82c2a5SDouglas Gregor ///     export-declaration
13466ddfca91SDouglas Gregor ///     link-declaration
134773441091SDouglas Gregor ///
134873441091SDouglas Gregor ///   submodule-declaration:
134973441091SDouglas Gregor ///     module-declaration
135073441091SDouglas Gregor ///     inferred-submodule-declaration
1351718292f2SDouglas Gregor void ModuleMapParser::parseModuleDecl() {
1352755b2055SDouglas Gregor   assert(Tok.is(MMToken::ExplicitKeyword) || Tok.is(MMToken::ModuleKeyword) ||
135397292843SDaniel Jasper          Tok.is(MMToken::FrameworkKeyword) || Tok.is(MMToken::ExternKeyword));
135497292843SDaniel Jasper   if (Tok.is(MMToken::ExternKeyword)) {
135597292843SDaniel Jasper     parseExternModuleDecl();
135697292843SDaniel Jasper     return;
135797292843SDaniel Jasper   }
135897292843SDaniel Jasper 
1359f2161a70SDouglas Gregor   // Parse 'explicit' or 'framework' keyword, if present.
1360e7ab3669SDouglas Gregor   SourceLocation ExplicitLoc;
1361718292f2SDouglas Gregor   bool Explicit = false;
1362f2161a70SDouglas Gregor   bool Framework = false;
1363755b2055SDouglas Gregor 
1364f2161a70SDouglas Gregor   // Parse 'explicit' keyword, if present.
1365f2161a70SDouglas Gregor   if (Tok.is(MMToken::ExplicitKeyword)) {
1366e7ab3669SDouglas Gregor     ExplicitLoc = consumeToken();
1367f2161a70SDouglas Gregor     Explicit = true;
1368f2161a70SDouglas Gregor   }
1369f2161a70SDouglas Gregor 
1370f2161a70SDouglas Gregor   // Parse 'framework' keyword, if present.
1371755b2055SDouglas Gregor   if (Tok.is(MMToken::FrameworkKeyword)) {
1372755b2055SDouglas Gregor     consumeToken();
1373755b2055SDouglas Gregor     Framework = true;
1374755b2055SDouglas Gregor   }
1375718292f2SDouglas Gregor 
1376718292f2SDouglas Gregor   // Parse 'module' keyword.
1377718292f2SDouglas Gregor   if (!Tok.is(MMToken::ModuleKeyword)) {
1378d6343c99SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module);
1379718292f2SDouglas Gregor     consumeToken();
1380718292f2SDouglas Gregor     HadError = true;
1381718292f2SDouglas Gregor     return;
1382718292f2SDouglas Gregor   }
1383718292f2SDouglas Gregor   consumeToken(); // 'module' keyword
1384718292f2SDouglas Gregor 
138573441091SDouglas Gregor   // If we have a wildcard for the module name, this is an inferred submodule.
138673441091SDouglas Gregor   // Parse it.
138773441091SDouglas Gregor   if (Tok.is(MMToken::Star))
13889194a91dSDouglas Gregor     return parseInferredModuleDecl(Framework, Explicit);
138973441091SDouglas Gregor 
1390718292f2SDouglas Gregor   // Parse the module name.
1391e7ab3669SDouglas Gregor   ModuleId Id;
1392e7ab3669SDouglas Gregor   if (parseModuleId(Id)) {
1393718292f2SDouglas Gregor     HadError = true;
1394718292f2SDouglas Gregor     return;
1395718292f2SDouglas Gregor   }
1396e7ab3669SDouglas Gregor 
1397e7ab3669SDouglas Gregor   if (ActiveModule) {
1398e7ab3669SDouglas Gregor     if (Id.size() > 1) {
1399e7ab3669SDouglas Gregor       Diags.Report(Id.front().second, diag::err_mmap_nested_submodule_id)
1400e7ab3669SDouglas Gregor         << SourceRange(Id.front().second, Id.back().second);
1401e7ab3669SDouglas Gregor 
1402e7ab3669SDouglas Gregor       HadError = true;
1403e7ab3669SDouglas Gregor       return;
1404e7ab3669SDouglas Gregor     }
1405e7ab3669SDouglas Gregor   } else if (Id.size() == 1 && Explicit) {
1406e7ab3669SDouglas Gregor     // Top-level modules can't be explicit.
1407e7ab3669SDouglas Gregor     Diags.Report(ExplicitLoc, diag::err_mmap_explicit_top_level);
1408e7ab3669SDouglas Gregor     Explicit = false;
1409e7ab3669SDouglas Gregor     ExplicitLoc = SourceLocation();
1410e7ab3669SDouglas Gregor     HadError = true;
1411e7ab3669SDouglas Gregor   }
1412e7ab3669SDouglas Gregor 
1413e7ab3669SDouglas Gregor   Module *PreviousActiveModule = ActiveModule;
1414e7ab3669SDouglas Gregor   if (Id.size() > 1) {
1415e7ab3669SDouglas Gregor     // This module map defines a submodule. Go find the module of which it
1416e7ab3669SDouglas Gregor     // is a submodule.
1417d2d442caSCraig Topper     ActiveModule = nullptr;
14184b8a9e95SBen Langmuir     const Module *TopLevelModule = nullptr;
1419e7ab3669SDouglas Gregor     for (unsigned I = 0, N = Id.size() - 1; I != N; ++I) {
1420e7ab3669SDouglas Gregor       if (Module *Next = Map.lookupModuleQualified(Id[I].first, ActiveModule)) {
14214b8a9e95SBen Langmuir         if (I == 0)
14224b8a9e95SBen Langmuir           TopLevelModule = Next;
1423e7ab3669SDouglas Gregor         ActiveModule = Next;
1424e7ab3669SDouglas Gregor         continue;
1425e7ab3669SDouglas Gregor       }
1426e7ab3669SDouglas Gregor 
1427e7ab3669SDouglas Gregor       if (ActiveModule) {
1428e7ab3669SDouglas Gregor         Diags.Report(Id[I].second, diag::err_mmap_missing_module_qualified)
14295b5d21eaSRichard Smith           << Id[I].first
14305b5d21eaSRichard Smith           << ActiveModule->getTopLevelModule()->getFullModuleName();
1431e7ab3669SDouglas Gregor       } else {
1432e7ab3669SDouglas Gregor         Diags.Report(Id[I].second, diag::err_mmap_expected_module_name);
1433e7ab3669SDouglas Gregor       }
1434e7ab3669SDouglas Gregor       HadError = true;
1435e7ab3669SDouglas Gregor       return;
1436e7ab3669SDouglas Gregor     }
14374b8a9e95SBen Langmuir 
14384b8a9e95SBen Langmuir     if (ModuleMapFile != Map.getContainingModuleMapFile(TopLevelModule)) {
14394b8a9e95SBen Langmuir       assert(ModuleMapFile != Map.getModuleMapFileForUniquing(TopLevelModule) &&
14404b8a9e95SBen Langmuir              "submodule defined in same file as 'module *' that allowed its "
14414b8a9e95SBen Langmuir              "top-level module");
14424b8a9e95SBen Langmuir       Map.addAdditionalModuleMapFile(TopLevelModule, ModuleMapFile);
14434b8a9e95SBen Langmuir     }
1444e7ab3669SDouglas Gregor   }
1445e7ab3669SDouglas Gregor 
1446e7ab3669SDouglas Gregor   StringRef ModuleName = Id.back().first;
1447e7ab3669SDouglas Gregor   SourceLocation ModuleNameLoc = Id.back().second;
1448718292f2SDouglas Gregor 
1449a686e1b0SDouglas Gregor   // Parse the optional attribute list.
14504442605fSBill Wendling   Attributes Attrs;
14515d29dee0SDavide Italiano   if (parseOptionalAttributes(Attrs))
14525d29dee0SDavide Italiano     return;
14535d29dee0SDavide Italiano 
1454a686e1b0SDouglas Gregor 
1455718292f2SDouglas Gregor   // Parse the opening brace.
1456718292f2SDouglas Gregor   if (!Tok.is(MMToken::LBrace)) {
1457718292f2SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_lbrace)
1458718292f2SDouglas Gregor       << ModuleName;
1459718292f2SDouglas Gregor     HadError = true;
1460718292f2SDouglas Gregor     return;
1461718292f2SDouglas Gregor   }
1462718292f2SDouglas Gregor   SourceLocation LBraceLoc = consumeToken();
1463718292f2SDouglas Gregor 
1464718292f2SDouglas Gregor   // Determine whether this (sub)module has already been defined.
1465eb90e830SDouglas Gregor   if (Module *Existing = Map.lookupModuleQualified(ModuleName, ActiveModule)) {
1466fcc54a3bSDouglas Gregor     if (Existing->DefinitionLoc.isInvalid() && !ActiveModule) {
1467fcc54a3bSDouglas Gregor       // Skip the module definition.
1468fcc54a3bSDouglas Gregor       skipUntil(MMToken::RBrace);
1469fcc54a3bSDouglas Gregor       if (Tok.is(MMToken::RBrace))
1470fcc54a3bSDouglas Gregor         consumeToken();
1471fcc54a3bSDouglas Gregor       else {
1472fcc54a3bSDouglas Gregor         Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
1473fcc54a3bSDouglas Gregor         Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
1474fcc54a3bSDouglas Gregor         HadError = true;
1475fcc54a3bSDouglas Gregor       }
1476fcc54a3bSDouglas Gregor       return;
1477fcc54a3bSDouglas Gregor     }
1478fcc54a3bSDouglas Gregor 
1479718292f2SDouglas Gregor     Diags.Report(ModuleNameLoc, diag::err_mmap_module_redefinition)
1480718292f2SDouglas Gregor       << ModuleName;
1481eb90e830SDouglas Gregor     Diags.Report(Existing->DefinitionLoc, diag::note_mmap_prev_definition);
1482718292f2SDouglas Gregor 
1483718292f2SDouglas Gregor     // Skip the module definition.
1484718292f2SDouglas Gregor     skipUntil(MMToken::RBrace);
1485718292f2SDouglas Gregor     if (Tok.is(MMToken::RBrace))
1486718292f2SDouglas Gregor       consumeToken();
1487718292f2SDouglas Gregor 
1488718292f2SDouglas Gregor     HadError = true;
1489718292f2SDouglas Gregor     return;
1490718292f2SDouglas Gregor   }
1491718292f2SDouglas Gregor 
1492718292f2SDouglas Gregor   // Start defining this module.
14939d6448b1SBen Langmuir   ActiveModule = Map.findOrCreateModule(ModuleName, ActiveModule, Framework,
14949d6448b1SBen Langmuir                                         Explicit).first;
1495eb90e830SDouglas Gregor   ActiveModule->DefinitionLoc = ModuleNameLoc;
1496963c5535SDouglas Gregor   if (Attrs.IsSystem || IsSystem)
1497a686e1b0SDouglas Gregor     ActiveModule->IsSystem = true;
149877944868SRichard Smith   if (Attrs.IsExternC)
149977944868SRichard Smith     ActiveModule->IsExternC = true;
1500ed84df00SBruno Cardoso Lopes   if (Attrs.NoUndeclaredIncludes ||
1501ed84df00SBruno Cardoso Lopes       (!ActiveModule->Parent && ModuleName == "Darwin"))
1502ed84df00SBruno Cardoso Lopes     ActiveModule->NoUndeclaredIncludes = true;
15033c1a41adSRichard Smith   ActiveModule->Directory = Directory;
1504718292f2SDouglas Gregor 
15054d867640SGraydon Hoare   if (!ActiveModule->Parent) {
15064d867640SGraydon Hoare     StringRef MapFileName(ModuleMapFile->getName());
15074d867640SGraydon Hoare     if (MapFileName.endswith("module.private.modulemap") ||
15084d867640SGraydon Hoare         MapFileName.endswith("module_private.map")) {
15094d867640SGraydon Hoare       // Adding a top-level module from a private modulemap is likely a
15104d867640SGraydon Hoare       // user error; we check to see if there's another top-level module
15114d867640SGraydon Hoare       // defined in the non-private map in the same dir, and if so emit a
15124d867640SGraydon Hoare       // warning.
15134d867640SGraydon Hoare       for (auto E = Map.module_begin(); E != Map.module_end(); ++E) {
15144d867640SGraydon Hoare         auto const *M = E->getValue();
15154d867640SGraydon Hoare         if (!M->Parent &&
15164d867640SGraydon Hoare             M->Directory == ActiveModule->Directory &&
15174d867640SGraydon Hoare             M->Name != ActiveModule->Name) {
15184d867640SGraydon Hoare           Diags.Report(ActiveModule->DefinitionLoc,
15194d867640SGraydon Hoare                        diag::warn_mmap_mismatched_top_level_private)
15204d867640SGraydon Hoare             << ActiveModule->Name << M->Name;
15214d867640SGraydon Hoare           // The pattern we're defending against here is typically due to
15224d867640SGraydon Hoare           // a module named FooPrivate which is supposed to be a submodule
15234d867640SGraydon Hoare           // called Foo.Private. Emit a fixit in that case.
15244d867640SGraydon Hoare           auto D =
15254d867640SGraydon Hoare             Diags.Report(ActiveModule->DefinitionLoc,
15264d867640SGraydon Hoare                          diag::note_mmap_rename_top_level_private_as_submodule);
15274d867640SGraydon Hoare           D << ActiveModule->Name << M->Name;
15284d867640SGraydon Hoare           StringRef Bad(ActiveModule->Name);
15294d867640SGraydon Hoare           if (Bad.consume_back("Private")) {
15304d867640SGraydon Hoare             SmallString<128> Fixed = Bad;
15314d867640SGraydon Hoare             Fixed.append(".Private");
15324d867640SGraydon Hoare             D << FixItHint::CreateReplacement(ActiveModule->DefinitionLoc,
15334d867640SGraydon Hoare                                               Fixed);
15344d867640SGraydon Hoare           }
15354d867640SGraydon Hoare           break;
15364d867640SGraydon Hoare         }
15374d867640SGraydon Hoare       }
15384d867640SGraydon Hoare     }
15394d867640SGraydon Hoare   }
15404d867640SGraydon Hoare 
1541718292f2SDouglas Gregor   bool Done = false;
1542718292f2SDouglas Gregor   do {
1543718292f2SDouglas Gregor     switch (Tok.Kind) {
1544718292f2SDouglas Gregor     case MMToken::EndOfFile:
1545718292f2SDouglas Gregor     case MMToken::RBrace:
1546718292f2SDouglas Gregor       Done = true;
1547718292f2SDouglas Gregor       break;
1548718292f2SDouglas Gregor 
154935b13eceSDouglas Gregor     case MMToken::ConfigMacros:
155035b13eceSDouglas Gregor       parseConfigMacros();
155135b13eceSDouglas Gregor       break;
155235b13eceSDouglas Gregor 
1553fb912657SDouglas Gregor     case MMToken::Conflict:
1554fb912657SDouglas Gregor       parseConflict();
1555fb912657SDouglas Gregor       break;
1556fb912657SDouglas Gregor 
1557718292f2SDouglas Gregor     case MMToken::ExplicitKeyword:
155897292843SDaniel Jasper     case MMToken::ExternKeyword:
1559f2161a70SDouglas Gregor     case MMToken::FrameworkKeyword:
1560718292f2SDouglas Gregor     case MMToken::ModuleKeyword:
1561718292f2SDouglas Gregor       parseModuleDecl();
1562718292f2SDouglas Gregor       break;
1563718292f2SDouglas Gregor 
15642b82c2a5SDouglas Gregor     case MMToken::ExportKeyword:
15652b82c2a5SDouglas Gregor       parseExportDecl();
15662b82c2a5SDouglas Gregor       break;
15672b82c2a5SDouglas Gregor 
1568ba7f2f71SDaniel Jasper     case MMToken::UseKeyword:
1569ba7f2f71SDaniel Jasper       parseUseDecl();
1570ba7f2f71SDaniel Jasper       break;
1571ba7f2f71SDaniel Jasper 
15721fb5c3a6SDouglas Gregor     case MMToken::RequiresKeyword:
15731fb5c3a6SDouglas Gregor       parseRequiresDecl();
15741fb5c3a6SDouglas Gregor       break;
15751fb5c3a6SDouglas Gregor 
1576202210b3SRichard Smith     case MMToken::TextualKeyword:
1577202210b3SRichard Smith       parseHeaderDecl(MMToken::TextualKeyword, consumeToken());
1578306d8920SRichard Smith       break;
1579306d8920SRichard Smith 
1580524e33e1SDouglas Gregor     case MMToken::UmbrellaKeyword: {
1581524e33e1SDouglas Gregor       SourceLocation UmbrellaLoc = consumeToken();
1582524e33e1SDouglas Gregor       if (Tok.is(MMToken::HeaderKeyword))
1583b53e5483SLawrence Crowl         parseHeaderDecl(MMToken::UmbrellaKeyword, UmbrellaLoc);
1584524e33e1SDouglas Gregor       else
1585524e33e1SDouglas Gregor         parseUmbrellaDirDecl(UmbrellaLoc);
1586718292f2SDouglas Gregor       break;
1587524e33e1SDouglas Gregor     }
1588718292f2SDouglas Gregor 
1589202210b3SRichard Smith     case MMToken::ExcludeKeyword:
1590202210b3SRichard Smith       parseHeaderDecl(MMToken::ExcludeKeyword, consumeToken());
159159527666SDouglas Gregor       break;
159259527666SDouglas Gregor 
1593202210b3SRichard Smith     case MMToken::PrivateKeyword:
1594202210b3SRichard Smith       parseHeaderDecl(MMToken::PrivateKeyword, consumeToken());
1595b53e5483SLawrence Crowl       break;
1596b53e5483SLawrence Crowl 
1597322f633cSDouglas Gregor     case MMToken::HeaderKeyword:
1598202210b3SRichard Smith       parseHeaderDecl(MMToken::HeaderKeyword, consumeToken());
1599718292f2SDouglas Gregor       break;
1600718292f2SDouglas Gregor 
16016ddfca91SDouglas Gregor     case MMToken::LinkKeyword:
16026ddfca91SDouglas Gregor       parseLinkDecl();
16036ddfca91SDouglas Gregor       break;
16046ddfca91SDouglas Gregor 
1605718292f2SDouglas Gregor     default:
1606718292f2SDouglas Gregor       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_member);
1607718292f2SDouglas Gregor       consumeToken();
1608718292f2SDouglas Gregor       break;
1609718292f2SDouglas Gregor     }
1610718292f2SDouglas Gregor   } while (!Done);
1611718292f2SDouglas Gregor 
1612718292f2SDouglas Gregor   if (Tok.is(MMToken::RBrace))
1613718292f2SDouglas Gregor     consumeToken();
1614718292f2SDouglas Gregor   else {
1615718292f2SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
1616718292f2SDouglas Gregor     Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
1617718292f2SDouglas Gregor     HadError = true;
1618718292f2SDouglas Gregor   }
1619718292f2SDouglas Gregor 
162011dfe6feSDouglas Gregor   // If the active module is a top-level framework, and there are no link
162111dfe6feSDouglas Gregor   // libraries, automatically link against the framework.
162211dfe6feSDouglas Gregor   if (ActiveModule->IsFramework && !ActiveModule->isSubFramework() &&
162311dfe6feSDouglas Gregor       ActiveModule->LinkLibraries.empty()) {
162411dfe6feSDouglas Gregor     inferFrameworkLink(ActiveModule, Directory, SourceMgr.getFileManager());
162511dfe6feSDouglas Gregor   }
162611dfe6feSDouglas Gregor 
1627ec8c9752SBen Langmuir   // If the module meets all requirements but is still unavailable, mark the
1628ec8c9752SBen Langmuir   // whole tree as unavailable to prevent it from building.
1629ec8c9752SBen Langmuir   if (!ActiveModule->IsAvailable && !ActiveModule->IsMissingRequirement &&
1630ec8c9752SBen Langmuir       ActiveModule->Parent) {
1631ec8c9752SBen Langmuir     ActiveModule->getTopLevelModule()->markUnavailable();
1632ec8c9752SBen Langmuir     ActiveModule->getTopLevelModule()->MissingHeaders.append(
1633ec8c9752SBen Langmuir       ActiveModule->MissingHeaders.begin(), ActiveModule->MissingHeaders.end());
1634ec8c9752SBen Langmuir   }
1635ec8c9752SBen Langmuir 
1636e7ab3669SDouglas Gregor   // We're done parsing this module. Pop back to the previous module.
1637e7ab3669SDouglas Gregor   ActiveModule = PreviousActiveModule;
1638718292f2SDouglas Gregor }
1639718292f2SDouglas Gregor 
164097292843SDaniel Jasper /// \brief Parse an extern module declaration.
164197292843SDaniel Jasper ///
164297292843SDaniel Jasper ///   extern module-declaration:
164397292843SDaniel Jasper ///     'extern' 'module' module-id string-literal
164497292843SDaniel Jasper void ModuleMapParser::parseExternModuleDecl() {
164597292843SDaniel Jasper   assert(Tok.is(MMToken::ExternKeyword));
1646ae6df27eSRichard Smith   SourceLocation ExternLoc = consumeToken(); // 'extern' keyword
164797292843SDaniel Jasper 
164897292843SDaniel Jasper   // Parse 'module' keyword.
164997292843SDaniel Jasper   if (!Tok.is(MMToken::ModuleKeyword)) {
165097292843SDaniel Jasper     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module);
165197292843SDaniel Jasper     consumeToken();
165297292843SDaniel Jasper     HadError = true;
165397292843SDaniel Jasper     return;
165497292843SDaniel Jasper   }
165597292843SDaniel Jasper   consumeToken(); // 'module' keyword
165697292843SDaniel Jasper 
165797292843SDaniel Jasper   // Parse the module name.
165897292843SDaniel Jasper   ModuleId Id;
165997292843SDaniel Jasper   if (parseModuleId(Id)) {
166097292843SDaniel Jasper     HadError = true;
166197292843SDaniel Jasper     return;
166297292843SDaniel Jasper   }
166397292843SDaniel Jasper 
166497292843SDaniel Jasper   // Parse the referenced module map file name.
166597292843SDaniel Jasper   if (!Tok.is(MMToken::StringLiteral)) {
166697292843SDaniel Jasper     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_mmap_file);
166797292843SDaniel Jasper     HadError = true;
166897292843SDaniel Jasper     return;
166997292843SDaniel Jasper   }
167097292843SDaniel Jasper   std::string FileName = Tok.getString();
167197292843SDaniel Jasper   consumeToken(); // filename
167297292843SDaniel Jasper 
167397292843SDaniel Jasper   StringRef FileNameRef = FileName;
167497292843SDaniel Jasper   SmallString<128> ModuleMapFileName;
167597292843SDaniel Jasper   if (llvm::sys::path::is_relative(FileNameRef)) {
167697292843SDaniel Jasper     ModuleMapFileName += Directory->getName();
167797292843SDaniel Jasper     llvm::sys::path::append(ModuleMapFileName, FileName);
167892e1b62dSYaron Keren     FileNameRef = ModuleMapFileName;
167997292843SDaniel Jasper   }
168097292843SDaniel Jasper   if (const FileEntry *File = SourceMgr.getFileManager().getFile(FileNameRef))
16819acb99e3SRichard Smith     Map.parseModuleMapFile(
16829acb99e3SRichard Smith         File, /*IsSystem=*/false,
16839acb99e3SRichard Smith         Map.HeaderInfo.getHeaderSearchOpts().ModuleMapFileHomeIsCwd
16849acb99e3SRichard Smith             ? Directory
1685ae6df27eSRichard Smith             : File->getDir(), ExternLoc);
168697292843SDaniel Jasper }
168797292843SDaniel Jasper 
16887ff29148SBen Langmuir /// Whether to add the requirement \p Feature to the module \p M.
16897ff29148SBen Langmuir ///
16907ff29148SBen Langmuir /// This preserves backwards compatibility for two hacks in the Darwin system
16917ff29148SBen Langmuir /// module map files:
16927ff29148SBen Langmuir ///
16937ff29148SBen Langmuir /// 1. The use of 'requires excluded' to make headers non-modular, which
16947ff29148SBen Langmuir ///    should really be mapped to 'textual' now that we have this feature.  We
16957ff29148SBen Langmuir ///    drop the 'excluded' requirement, and set \p IsRequiresExcludedHack to
16967ff29148SBen Langmuir ///    true.  Later, this bit will be used to map all the headers inside this
16977ff29148SBen Langmuir ///    module to 'textual'.
16987ff29148SBen Langmuir ///
16997ff29148SBen Langmuir ///    This affects Darwin.C.excluded (for assert.h) and Tcl.Private.
17007ff29148SBen Langmuir ///
17017ff29148SBen Langmuir /// 2. Removes a bogus cplusplus requirement from IOKit.avc.  This requirement
17027ff29148SBen Langmuir ///    was never correct and causes issues now that we check it, so drop it.
17037ff29148SBen Langmuir static bool shouldAddRequirement(Module *M, StringRef Feature,
17047ff29148SBen Langmuir                                  bool &IsRequiresExcludedHack) {
17058013e81dSBenjamin Kramer   if (Feature == "excluded" &&
17068013e81dSBenjamin Kramer       (M->fullModuleNameIs({"Darwin", "C", "excluded"}) ||
17078013e81dSBenjamin Kramer        M->fullModuleNameIs({"Tcl", "Private"}))) {
17087ff29148SBen Langmuir     IsRequiresExcludedHack = true;
17097ff29148SBen Langmuir     return false;
17108013e81dSBenjamin Kramer   } else if (Feature == "cplusplus" && M->fullModuleNameIs({"IOKit", "avc"})) {
17117ff29148SBen Langmuir     return false;
17127ff29148SBen Langmuir   }
17137ff29148SBen Langmuir 
17147ff29148SBen Langmuir   return true;
17157ff29148SBen Langmuir }
17167ff29148SBen Langmuir 
17171fb5c3a6SDouglas Gregor /// \brief Parse a requires declaration.
17181fb5c3a6SDouglas Gregor ///
17191fb5c3a6SDouglas Gregor ///   requires-declaration:
17201fb5c3a6SDouglas Gregor ///     'requires' feature-list
17211fb5c3a6SDouglas Gregor ///
17221fb5c3a6SDouglas Gregor ///   feature-list:
1723a3feee2aSRichard Smith ///     feature ',' feature-list
1724a3feee2aSRichard Smith ///     feature
1725a3feee2aSRichard Smith ///
1726a3feee2aSRichard Smith ///   feature:
1727a3feee2aSRichard Smith ///     '!'[opt] identifier
17281fb5c3a6SDouglas Gregor void ModuleMapParser::parseRequiresDecl() {
17291fb5c3a6SDouglas Gregor   assert(Tok.is(MMToken::RequiresKeyword));
17301fb5c3a6SDouglas Gregor 
17311fb5c3a6SDouglas Gregor   // Parse 'requires' keyword.
17321fb5c3a6SDouglas Gregor   consumeToken();
17331fb5c3a6SDouglas Gregor 
17341fb5c3a6SDouglas Gregor   // Parse the feature-list.
17351fb5c3a6SDouglas Gregor   do {
1736a3feee2aSRichard Smith     bool RequiredState = true;
1737a3feee2aSRichard Smith     if (Tok.is(MMToken::Exclaim)) {
1738a3feee2aSRichard Smith       RequiredState = false;
1739a3feee2aSRichard Smith       consumeToken();
1740a3feee2aSRichard Smith     }
1741a3feee2aSRichard Smith 
17421fb5c3a6SDouglas Gregor     if (!Tok.is(MMToken::Identifier)) {
17431fb5c3a6SDouglas Gregor       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_feature);
17441fb5c3a6SDouglas Gregor       HadError = true;
17451fb5c3a6SDouglas Gregor       return;
17461fb5c3a6SDouglas Gregor     }
17471fb5c3a6SDouglas Gregor 
17481fb5c3a6SDouglas Gregor     // Consume the feature name.
17491fb5c3a6SDouglas Gregor     std::string Feature = Tok.getString();
17501fb5c3a6SDouglas Gregor     consumeToken();
17511fb5c3a6SDouglas Gregor 
17527ff29148SBen Langmuir     bool IsRequiresExcludedHack = false;
17537ff29148SBen Langmuir     bool ShouldAddRequirement =
17547ff29148SBen Langmuir         shouldAddRequirement(ActiveModule, Feature, IsRequiresExcludedHack);
17557ff29148SBen Langmuir 
17567ff29148SBen Langmuir     if (IsRequiresExcludedHack)
17577ff29148SBen Langmuir       UsesRequiresExcludedHack.insert(ActiveModule);
17587ff29148SBen Langmuir 
17597ff29148SBen Langmuir     if (ShouldAddRequirement) {
17601fb5c3a6SDouglas Gregor       // Add this feature.
17617ff29148SBen Langmuir       ActiveModule->addRequirement(Feature, RequiredState, Map.LangOpts,
17627ff29148SBen Langmuir                                    *Map.Target);
17637ff29148SBen Langmuir     }
17641fb5c3a6SDouglas Gregor 
17651fb5c3a6SDouglas Gregor     if (!Tok.is(MMToken::Comma))
17661fb5c3a6SDouglas Gregor       break;
17671fb5c3a6SDouglas Gregor 
17681fb5c3a6SDouglas Gregor     // Consume the comma.
17691fb5c3a6SDouglas Gregor     consumeToken();
17701fb5c3a6SDouglas Gregor   } while (true);
17711fb5c3a6SDouglas Gregor }
17721fb5c3a6SDouglas Gregor 
1773f2161a70SDouglas Gregor /// \brief Append to \p Paths the set of paths needed to get to the
1774f2161a70SDouglas Gregor /// subframework in which the given module lives.
1775bf8da9d7SBenjamin Kramer static void appendSubframeworkPaths(Module *Mod,
1776f857950dSDmitri Gribenko                                     SmallVectorImpl<char> &Path) {
1777f2161a70SDouglas Gregor   // Collect the framework names from the given module to the top-level module.
1778f857950dSDmitri Gribenko   SmallVector<StringRef, 2> Paths;
1779f2161a70SDouglas Gregor   for (; Mod; Mod = Mod->Parent) {
1780f2161a70SDouglas Gregor     if (Mod->IsFramework)
1781f2161a70SDouglas Gregor       Paths.push_back(Mod->Name);
1782f2161a70SDouglas Gregor   }
1783f2161a70SDouglas Gregor 
1784f2161a70SDouglas Gregor   if (Paths.empty())
1785f2161a70SDouglas Gregor     return;
1786f2161a70SDouglas Gregor 
1787f2161a70SDouglas Gregor   // Add Frameworks/Name.framework for each subframework.
178817381a06SBenjamin Kramer   for (unsigned I = Paths.size() - 1; I != 0; --I)
178917381a06SBenjamin Kramer     llvm::sys::path::append(Path, "Frameworks", Paths[I-1] + ".framework");
1790f2161a70SDouglas Gregor }
1791f2161a70SDouglas Gregor 
1792718292f2SDouglas Gregor /// \brief Parse a header declaration.
1793718292f2SDouglas Gregor ///
1794718292f2SDouglas Gregor ///   header-declaration:
1795306d8920SRichard Smith ///     'textual'[opt] 'header' string-literal
1796202210b3SRichard Smith ///     'private' 'textual'[opt] 'header' string-literal
1797202210b3SRichard Smith ///     'exclude' 'header' string-literal
1798202210b3SRichard Smith ///     'umbrella' 'header' string-literal
1799306d8920SRichard Smith ///
1800306d8920SRichard Smith /// FIXME: Support 'private textual header'.
1801b53e5483SLawrence Crowl void ModuleMapParser::parseHeaderDecl(MMToken::TokenKind LeadingToken,
1802b53e5483SLawrence Crowl                                       SourceLocation LeadingLoc) {
1803202210b3SRichard Smith   // We've already consumed the first token.
1804202210b3SRichard Smith   ModuleMap::ModuleHeaderRole Role = ModuleMap::NormalHeader;
1805202210b3SRichard Smith   if (LeadingToken == MMToken::PrivateKeyword) {
1806202210b3SRichard Smith     Role = ModuleMap::PrivateHeader;
1807202210b3SRichard Smith     // 'private' may optionally be followed by 'textual'.
1808202210b3SRichard Smith     if (Tok.is(MMToken::TextualKeyword)) {
1809202210b3SRichard Smith       LeadingToken = Tok.Kind;
18101871ed3dSBenjamin Kramer       consumeToken();
1811202210b3SRichard Smith     }
1812202210b3SRichard Smith   }
18137ff29148SBen Langmuir 
1814202210b3SRichard Smith   if (LeadingToken == MMToken::TextualKeyword)
1815202210b3SRichard Smith     Role = ModuleMap::ModuleHeaderRole(Role | ModuleMap::TextualHeader);
1816202210b3SRichard Smith 
18177ff29148SBen Langmuir   if (UsesRequiresExcludedHack.count(ActiveModule)) {
18187ff29148SBen Langmuir     // Mark this header 'textual' (see doc comment for
18197ff29148SBen Langmuir     // Module::UsesRequiresExcludedHack).
18207ff29148SBen Langmuir     Role = ModuleMap::ModuleHeaderRole(Role | ModuleMap::TextualHeader);
18217ff29148SBen Langmuir   }
18227ff29148SBen Langmuir 
1823202210b3SRichard Smith   if (LeadingToken != MMToken::HeaderKeyword) {
1824202210b3SRichard Smith     if (!Tok.is(MMToken::HeaderKeyword)) {
1825202210b3SRichard Smith       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
1826202210b3SRichard Smith           << (LeadingToken == MMToken::PrivateKeyword ? "private" :
1827202210b3SRichard Smith               LeadingToken == MMToken::ExcludeKeyword ? "exclude" :
1828202210b3SRichard Smith               LeadingToken == MMToken::TextualKeyword ? "textual" : "umbrella");
1829202210b3SRichard Smith       return;
1830202210b3SRichard Smith     }
1831202210b3SRichard Smith     consumeToken();
1832202210b3SRichard Smith   }
1833718292f2SDouglas Gregor 
1834718292f2SDouglas Gregor   // Parse the header name.
1835718292f2SDouglas Gregor   if (!Tok.is(MMToken::StringLiteral)) {
1836718292f2SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
1837718292f2SDouglas Gregor       << "header";
1838718292f2SDouglas Gregor     HadError = true;
1839718292f2SDouglas Gregor     return;
1840718292f2SDouglas Gregor   }
18413c1a41adSRichard Smith   Module::UnresolvedHeaderDirective Header;
18420761a8a0SDaniel Jasper   Header.FileName = Tok.getString();
18430761a8a0SDaniel Jasper   Header.FileNameLoc = consumeToken();
1844718292f2SDouglas Gregor 
1845524e33e1SDouglas Gregor   // Check whether we already have an umbrella.
1846b53e5483SLawrence Crowl   if (LeadingToken == MMToken::UmbrellaKeyword && ActiveModule->Umbrella) {
18470761a8a0SDaniel Jasper     Diags.Report(Header.FileNameLoc, diag::err_mmap_umbrella_clash)
1848524e33e1SDouglas Gregor       << ActiveModule->getFullModuleName();
1849322f633cSDouglas Gregor     HadError = true;
1850322f633cSDouglas Gregor     return;
1851322f633cSDouglas Gregor   }
1852322f633cSDouglas Gregor 
18535257fc63SDouglas Gregor   // Look for this file.
1854d2d442caSCraig Topper   const FileEntry *File = nullptr;
1855d2d442caSCraig Topper   const FileEntry *BuiltinFile = nullptr;
18563c1a41adSRichard Smith   SmallString<128> RelativePathName;
18570761a8a0SDaniel Jasper   if (llvm::sys::path::is_absolute(Header.FileName)) {
18583c1a41adSRichard Smith     RelativePathName = Header.FileName;
18593c1a41adSRichard Smith     File = SourceMgr.getFileManager().getFile(RelativePathName);
1860e7ab3669SDouglas Gregor   } else {
1861e7ab3669SDouglas Gregor     // Search for the header file within the search directory.
18623c1a41adSRichard Smith     SmallString<128> FullPathName(Directory->getName());
18633c1a41adSRichard Smith     unsigned FullPathLength = FullPathName.size();
1864755b2055SDouglas Gregor 
1865f2161a70SDouglas Gregor     if (ActiveModule->isPartOfFramework()) {
18663c1a41adSRichard Smith       appendSubframeworkPaths(ActiveModule, RelativePathName);
1867*08ebd61aSBruno Cardoso Lopes       unsigned RelativePathLength = RelativePathName.size();
1868755b2055SDouglas Gregor 
1869e7ab3669SDouglas Gregor       // Check whether this file is in the public headers.
18703c1a41adSRichard Smith       llvm::sys::path::append(RelativePathName, "Headers", Header.FileName);
187192e1b62dSYaron Keren       llvm::sys::path::append(FullPathName, RelativePathName);
18723c1a41adSRichard Smith       File = SourceMgr.getFileManager().getFile(FullPathName);
1873e7ab3669SDouglas Gregor 
1874e7ab3669SDouglas Gregor       // Check whether this file is in the private headers.
1875*08ebd61aSBruno Cardoso Lopes       if (!File) {
1876*08ebd61aSBruno Cardoso Lopes         // Ideally, private modules in the form 'FrameworkName.Private' should
1877*08ebd61aSBruno Cardoso Lopes         // be defined as 'module FrameworkName.Private', and not as
1878*08ebd61aSBruno Cardoso Lopes         // 'framework module FrameworkName.Private', since a 'Private.Framework'
1879*08ebd61aSBruno Cardoso Lopes         // does not usually exist. However, since both are currently widely used
1880*08ebd61aSBruno Cardoso Lopes         // for private modules, make sure we find the right path in both cases.
1881*08ebd61aSBruno Cardoso Lopes         RelativePathName.resize(ActiveModule->IsFramework ? 0
1882*08ebd61aSBruno Cardoso Lopes                                                           : RelativePathLength);
18833c1a41adSRichard Smith         FullPathName.resize(FullPathLength);
18843c1a41adSRichard Smith         llvm::sys::path::append(RelativePathName, "PrivateHeaders",
18853c1a41adSRichard Smith                                 Header.FileName);
188692e1b62dSYaron Keren         llvm::sys::path::append(FullPathName, RelativePathName);
18873c1a41adSRichard Smith         File = SourceMgr.getFileManager().getFile(FullPathName);
1888e7ab3669SDouglas Gregor       }
1889e7ab3669SDouglas Gregor     } else {
1890e7ab3669SDouglas Gregor       // Lookup for normal headers.
18913c1a41adSRichard Smith       llvm::sys::path::append(RelativePathName, Header.FileName);
189292e1b62dSYaron Keren       llvm::sys::path::append(FullPathName, RelativePathName);
18933c1a41adSRichard Smith       File = SourceMgr.getFileManager().getFile(FullPathName);
18943ec6663bSDouglas Gregor 
18953ec6663bSDouglas Gregor       // If this is a system module with a top-level header, this header
18963ec6663bSDouglas Gregor       // may have a counterpart (or replacement) in the set of headers
18973ec6663bSDouglas Gregor       // supplied by Clang. Find that builtin header.
1898b53e5483SLawrence Crowl       if (ActiveModule->IsSystem && LeadingToken != MMToken::UmbrellaKeyword &&
1899b53e5483SLawrence Crowl           BuiltinIncludeDir && BuiltinIncludeDir != Directory &&
1900ba1b5c98SBruno Cardoso Lopes           ModuleMap::isBuiltinHeader(Header.FileName)) {
19012c1dd271SDylan Noblesmith         SmallString<128> BuiltinPathName(BuiltinIncludeDir->getName());
19020761a8a0SDaniel Jasper         llvm::sys::path::append(BuiltinPathName, Header.FileName);
19033ec6663bSDouglas Gregor         BuiltinFile = SourceMgr.getFileManager().getFile(BuiltinPathName);
19043ec6663bSDouglas Gregor 
19053ec6663bSDouglas Gregor         // If Clang supplies this header but the underlying system does not,
19063ec6663bSDouglas Gregor         // just silently swap in our builtin version. Otherwise, we'll end
19073ec6663bSDouglas Gregor         // up adding both (later).
1908ed84df00SBruno Cardoso Lopes         if (BuiltinFile && !File) {
19093ec6663bSDouglas Gregor           File = BuiltinFile;
19103c1a41adSRichard Smith           RelativePathName = BuiltinPathName;
1911d2d442caSCraig Topper           BuiltinFile = nullptr;
19123ec6663bSDouglas Gregor         }
19133ec6663bSDouglas Gregor       }
1914e7ab3669SDouglas Gregor     }
1915e7ab3669SDouglas Gregor   }
19165257fc63SDouglas Gregor 
19175257fc63SDouglas Gregor   // FIXME: We shouldn't be eagerly stat'ing every file named in a module map.
19185257fc63SDouglas Gregor   // Come up with a lazy way to do this.
1919e7ab3669SDouglas Gregor   if (File) {
192097da9178SDaniel Jasper     if (LeadingToken == MMToken::UmbrellaKeyword) {
1921322f633cSDouglas Gregor       const DirectoryEntry *UmbrellaDir = File->getDir();
192259527666SDouglas Gregor       if (Module *UmbrellaModule = Map.UmbrellaDirs[UmbrellaDir]) {
1923b53e5483SLawrence Crowl         Diags.Report(LeadingLoc, diag::err_mmap_umbrella_clash)
192459527666SDouglas Gregor           << UmbrellaModule->getFullModuleName();
1925322f633cSDouglas Gregor         HadError = true;
19265257fc63SDouglas Gregor       } else {
1927322f633cSDouglas Gregor         // Record this umbrella header.
19282b63d15fSRichard Smith         Map.setUmbrellaHeader(ActiveModule, File, RelativePathName.str());
1929322f633cSDouglas Gregor       }
1930feb54b6dSRichard Smith     } else if (LeadingToken == MMToken::ExcludeKeyword) {
19310101b540SHans Wennborg       Module::Header H = {RelativePathName.str(), File};
19320101b540SHans Wennborg       Map.excludeHeader(ActiveModule, H);
1933322f633cSDouglas Gregor     } else {
193415881ed0SRichard Smith       // If there is a builtin counterpart to this file, add it now so it can
193515881ed0SRichard Smith       // wrap the system header.
19360101b540SHans Wennborg       if (BuiltinFile) {
19373c1a41adSRichard Smith         // FIXME: Taking the name from the FileEntry is unstable and can give
19383c1a41adSRichard Smith         // different results depending on how we've previously named that file
19393c1a41adSRichard Smith         // in this build.
19400101b540SHans Wennborg         Module::Header H = { BuiltinFile->getName(), BuiltinFile };
194115881ed0SRichard Smith         Map.addHeader(ActiveModule, H, Role);
194215881ed0SRichard Smith 
194315881ed0SRichard Smith         // If we have both a builtin and system version of the file, the
194415881ed0SRichard Smith         // builtin version may want to inject macros into the system header, so
194515881ed0SRichard Smith         // force the system header to be treated as a textual header in this
194615881ed0SRichard Smith         // case.
194715881ed0SRichard Smith         Role = ModuleMap::ModuleHeaderRole(Role | ModuleMap::TextualHeader);
19480101b540SHans Wennborg       }
194925d50758SRichard Smith 
1950202210b3SRichard Smith       // Record this header.
19510101b540SHans Wennborg       Module::Header H = { RelativePathName.str(), File };
19520101b540SHans Wennborg       Map.addHeader(ActiveModule, H, Role);
19535257fc63SDouglas Gregor     }
1954b53e5483SLawrence Crowl   } else if (LeadingToken != MMToken::ExcludeKeyword) {
19554b27a64bSDouglas Gregor     // Ignore excluded header files. They're optional anyway.
19564b27a64bSDouglas Gregor 
19570761a8a0SDaniel Jasper     // If we find a module that has a missing header, we mark this module as
19580761a8a0SDaniel Jasper     // unavailable and store the header directive for displaying diagnostics.
19590761a8a0SDaniel Jasper     Header.IsUmbrella = LeadingToken == MMToken::UmbrellaKeyword;
1960ec8c9752SBen Langmuir     ActiveModule->markUnavailable();
19610761a8a0SDaniel Jasper     ActiveModule->MissingHeaders.push_back(Header);
19625257fc63SDouglas Gregor   }
1963718292f2SDouglas Gregor }
1964718292f2SDouglas Gregor 
196541f81994SBen Langmuir static int compareModuleHeaders(const Module::Header *A,
196641f81994SBen Langmuir                                 const Module::Header *B) {
196741f81994SBen Langmuir   return A->NameAsWritten.compare(B->NameAsWritten);
196841f81994SBen Langmuir }
196941f81994SBen Langmuir 
1970524e33e1SDouglas Gregor /// \brief Parse an umbrella directory declaration.
1971524e33e1SDouglas Gregor ///
1972524e33e1SDouglas Gregor ///   umbrella-dir-declaration:
1973524e33e1SDouglas Gregor ///     umbrella string-literal
1974524e33e1SDouglas Gregor void ModuleMapParser::parseUmbrellaDirDecl(SourceLocation UmbrellaLoc) {
1975524e33e1SDouglas Gregor   // Parse the directory name.
1976524e33e1SDouglas Gregor   if (!Tok.is(MMToken::StringLiteral)) {
1977524e33e1SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
1978524e33e1SDouglas Gregor       << "umbrella";
1979524e33e1SDouglas Gregor     HadError = true;
1980524e33e1SDouglas Gregor     return;
1981524e33e1SDouglas Gregor   }
1982524e33e1SDouglas Gregor 
1983524e33e1SDouglas Gregor   std::string DirName = Tok.getString();
1984524e33e1SDouglas Gregor   SourceLocation DirNameLoc = consumeToken();
1985524e33e1SDouglas Gregor 
1986524e33e1SDouglas Gregor   // Check whether we already have an umbrella.
1987524e33e1SDouglas Gregor   if (ActiveModule->Umbrella) {
1988524e33e1SDouglas Gregor     Diags.Report(DirNameLoc, diag::err_mmap_umbrella_clash)
1989524e33e1SDouglas Gregor       << ActiveModule->getFullModuleName();
1990524e33e1SDouglas Gregor     HadError = true;
1991524e33e1SDouglas Gregor     return;
1992524e33e1SDouglas Gregor   }
1993524e33e1SDouglas Gregor 
1994524e33e1SDouglas Gregor   // Look for this file.
1995d2d442caSCraig Topper   const DirectoryEntry *Dir = nullptr;
1996524e33e1SDouglas Gregor   if (llvm::sys::path::is_absolute(DirName))
1997524e33e1SDouglas Gregor     Dir = SourceMgr.getFileManager().getDirectory(DirName);
1998524e33e1SDouglas Gregor   else {
19992c1dd271SDylan Noblesmith     SmallString<128> PathName;
2000524e33e1SDouglas Gregor     PathName = Directory->getName();
2001524e33e1SDouglas Gregor     llvm::sys::path::append(PathName, DirName);
2002524e33e1SDouglas Gregor     Dir = SourceMgr.getFileManager().getDirectory(PathName);
2003524e33e1SDouglas Gregor   }
2004524e33e1SDouglas Gregor 
2005524e33e1SDouglas Gregor   if (!Dir) {
2006524e33e1SDouglas Gregor     Diags.Report(DirNameLoc, diag::err_mmap_umbrella_dir_not_found)
2007524e33e1SDouglas Gregor       << DirName;
2008524e33e1SDouglas Gregor     HadError = true;
2009524e33e1SDouglas Gregor     return;
2010524e33e1SDouglas Gregor   }
2011524e33e1SDouglas Gregor 
20127ff29148SBen Langmuir   if (UsesRequiresExcludedHack.count(ActiveModule)) {
20137ff29148SBen Langmuir     // Mark this header 'textual' (see doc comment for
20147ff29148SBen Langmuir     // ModuleMapParser::UsesRequiresExcludedHack). Although iterating over the
20157ff29148SBen Langmuir     // directory is relatively expensive, in practice this only applies to the
20167ff29148SBen Langmuir     // uncommonly used Tcl module on Darwin platforms.
20177ff29148SBen Langmuir     std::error_code EC;
20187ff29148SBen Langmuir     SmallVector<Module::Header, 6> Headers;
2019b171a59bSBruno Cardoso Lopes     vfs::FileSystem &FS = *SourceMgr.getFileManager().getVirtualFileSystem();
2020b171a59bSBruno Cardoso Lopes     for (vfs::recursive_directory_iterator I(FS, Dir->getName(), EC), E;
20217ff29148SBen Langmuir          I != E && !EC; I.increment(EC)) {
2022b171a59bSBruno Cardoso Lopes       if (const FileEntry *FE =
2023b171a59bSBruno Cardoso Lopes               SourceMgr.getFileManager().getFile(I->getName())) {
20247ff29148SBen Langmuir 
2025b171a59bSBruno Cardoso Lopes         Module::Header Header = {I->getName(), FE};
20267ff29148SBen Langmuir         Headers.push_back(std::move(Header));
20277ff29148SBen Langmuir       }
20287ff29148SBen Langmuir     }
20297ff29148SBen Langmuir 
20307ff29148SBen Langmuir     // Sort header paths so that the pcm doesn't depend on iteration order.
203141f81994SBen Langmuir     llvm::array_pod_sort(Headers.begin(), Headers.end(), compareModuleHeaders);
203241f81994SBen Langmuir 
20337ff29148SBen Langmuir     for (auto &Header : Headers)
20347ff29148SBen Langmuir       Map.addHeader(ActiveModule, std::move(Header), ModuleMap::TextualHeader);
20357ff29148SBen Langmuir     return;
20367ff29148SBen Langmuir   }
20377ff29148SBen Langmuir 
2038524e33e1SDouglas Gregor   if (Module *OwningModule = Map.UmbrellaDirs[Dir]) {
2039524e33e1SDouglas Gregor     Diags.Report(UmbrellaLoc, diag::err_mmap_umbrella_clash)
2040524e33e1SDouglas Gregor       << OwningModule->getFullModuleName();
2041524e33e1SDouglas Gregor     HadError = true;
2042524e33e1SDouglas Gregor     return;
2043524e33e1SDouglas Gregor   }
2044524e33e1SDouglas Gregor 
2045524e33e1SDouglas Gregor   // Record this umbrella directory.
20462b63d15fSRichard Smith   Map.setUmbrellaDir(ActiveModule, Dir, DirName);
2047524e33e1SDouglas Gregor }
2048524e33e1SDouglas Gregor 
20492b82c2a5SDouglas Gregor /// \brief Parse a module export declaration.
20502b82c2a5SDouglas Gregor ///
20512b82c2a5SDouglas Gregor ///   export-declaration:
20522b82c2a5SDouglas Gregor ///     'export' wildcard-module-id
20532b82c2a5SDouglas Gregor ///
20542b82c2a5SDouglas Gregor ///   wildcard-module-id:
20552b82c2a5SDouglas Gregor ///     identifier
20562b82c2a5SDouglas Gregor ///     '*'
20572b82c2a5SDouglas Gregor ///     identifier '.' wildcard-module-id
20582b82c2a5SDouglas Gregor void ModuleMapParser::parseExportDecl() {
20592b82c2a5SDouglas Gregor   assert(Tok.is(MMToken::ExportKeyword));
20602b82c2a5SDouglas Gregor   SourceLocation ExportLoc = consumeToken();
20612b82c2a5SDouglas Gregor 
20622b82c2a5SDouglas Gregor   // Parse the module-id with an optional wildcard at the end.
20632b82c2a5SDouglas Gregor   ModuleId ParsedModuleId;
20642b82c2a5SDouglas Gregor   bool Wildcard = false;
20652b82c2a5SDouglas Gregor   do {
2066306d8920SRichard Smith     // FIXME: Support string-literal module names here.
20672b82c2a5SDouglas Gregor     if (Tok.is(MMToken::Identifier)) {
20682b82c2a5SDouglas Gregor       ParsedModuleId.push_back(std::make_pair(Tok.getString(),
20692b82c2a5SDouglas Gregor                                               Tok.getLocation()));
20702b82c2a5SDouglas Gregor       consumeToken();
20712b82c2a5SDouglas Gregor 
20722b82c2a5SDouglas Gregor       if (Tok.is(MMToken::Period)) {
20732b82c2a5SDouglas Gregor         consumeToken();
20742b82c2a5SDouglas Gregor         continue;
20752b82c2a5SDouglas Gregor       }
20762b82c2a5SDouglas Gregor 
20772b82c2a5SDouglas Gregor       break;
20782b82c2a5SDouglas Gregor     }
20792b82c2a5SDouglas Gregor 
20802b82c2a5SDouglas Gregor     if(Tok.is(MMToken::Star)) {
20812b82c2a5SDouglas Gregor       Wildcard = true;
2082f5eedd05SDouglas Gregor       consumeToken();
20832b82c2a5SDouglas Gregor       break;
20842b82c2a5SDouglas Gregor     }
20852b82c2a5SDouglas Gregor 
2086ba7f2f71SDaniel Jasper     Diags.Report(Tok.getLocation(), diag::err_mmap_module_id);
20872b82c2a5SDouglas Gregor     HadError = true;
20882b82c2a5SDouglas Gregor     return;
20892b82c2a5SDouglas Gregor   } while (true);
20902b82c2a5SDouglas Gregor 
20912b82c2a5SDouglas Gregor   Module::UnresolvedExportDecl Unresolved = {
20922b82c2a5SDouglas Gregor     ExportLoc, ParsedModuleId, Wildcard
20932b82c2a5SDouglas Gregor   };
20942b82c2a5SDouglas Gregor   ActiveModule->UnresolvedExports.push_back(Unresolved);
20952b82c2a5SDouglas Gregor }
20962b82c2a5SDouglas Gregor 
20978f4d3ff1SRichard Smith /// \brief Parse a module use declaration.
2098ba7f2f71SDaniel Jasper ///
20998f4d3ff1SRichard Smith ///   use-declaration:
21008f4d3ff1SRichard Smith ///     'use' wildcard-module-id
2101ba7f2f71SDaniel Jasper void ModuleMapParser::parseUseDecl() {
2102ba7f2f71SDaniel Jasper   assert(Tok.is(MMToken::UseKeyword));
21038f4d3ff1SRichard Smith   auto KWLoc = consumeToken();
2104ba7f2f71SDaniel Jasper   // Parse the module-id.
2105ba7f2f71SDaniel Jasper   ModuleId ParsedModuleId;
21063cd34c76SDaniel Jasper   parseModuleId(ParsedModuleId);
2107ba7f2f71SDaniel Jasper 
21088f4d3ff1SRichard Smith   if (ActiveModule->Parent)
21098f4d3ff1SRichard Smith     Diags.Report(KWLoc, diag::err_mmap_use_decl_submodule);
21108f4d3ff1SRichard Smith   else
2111ba7f2f71SDaniel Jasper     ActiveModule->UnresolvedDirectUses.push_back(ParsedModuleId);
2112ba7f2f71SDaniel Jasper }
2113ba7f2f71SDaniel Jasper 
21146ddfca91SDouglas Gregor /// \brief Parse a link declaration.
21156ddfca91SDouglas Gregor ///
21166ddfca91SDouglas Gregor ///   module-declaration:
21176ddfca91SDouglas Gregor ///     'link' 'framework'[opt] string-literal
21186ddfca91SDouglas Gregor void ModuleMapParser::parseLinkDecl() {
21196ddfca91SDouglas Gregor   assert(Tok.is(MMToken::LinkKeyword));
21206ddfca91SDouglas Gregor   SourceLocation LinkLoc = consumeToken();
21216ddfca91SDouglas Gregor 
21226ddfca91SDouglas Gregor   // Parse the optional 'framework' keyword.
21236ddfca91SDouglas Gregor   bool IsFramework = false;
21246ddfca91SDouglas Gregor   if (Tok.is(MMToken::FrameworkKeyword)) {
21256ddfca91SDouglas Gregor     consumeToken();
21266ddfca91SDouglas Gregor     IsFramework = true;
21276ddfca91SDouglas Gregor   }
21286ddfca91SDouglas Gregor 
21296ddfca91SDouglas Gregor   // Parse the library name
21306ddfca91SDouglas Gregor   if (!Tok.is(MMToken::StringLiteral)) {
21316ddfca91SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_library_name)
21326ddfca91SDouglas Gregor       << IsFramework << SourceRange(LinkLoc);
21336ddfca91SDouglas Gregor     HadError = true;
21346ddfca91SDouglas Gregor     return;
21356ddfca91SDouglas Gregor   }
21366ddfca91SDouglas Gregor 
21376ddfca91SDouglas Gregor   std::string LibraryName = Tok.getString();
21386ddfca91SDouglas Gregor   consumeToken();
21396ddfca91SDouglas Gregor   ActiveModule->LinkLibraries.push_back(Module::LinkLibrary(LibraryName,
21406ddfca91SDouglas Gregor                                                             IsFramework));
21416ddfca91SDouglas Gregor }
21426ddfca91SDouglas Gregor 
214335b13eceSDouglas Gregor /// \brief Parse a configuration macro declaration.
214435b13eceSDouglas Gregor ///
214535b13eceSDouglas Gregor ///   module-declaration:
214635b13eceSDouglas Gregor ///     'config_macros' attributes[opt] config-macro-list?
214735b13eceSDouglas Gregor ///
214835b13eceSDouglas Gregor ///   config-macro-list:
214935b13eceSDouglas Gregor ///     identifier (',' identifier)?
215035b13eceSDouglas Gregor void ModuleMapParser::parseConfigMacros() {
215135b13eceSDouglas Gregor   assert(Tok.is(MMToken::ConfigMacros));
215235b13eceSDouglas Gregor   SourceLocation ConfigMacrosLoc = consumeToken();
215335b13eceSDouglas Gregor 
215435b13eceSDouglas Gregor   // Only top-level modules can have configuration macros.
215535b13eceSDouglas Gregor   if (ActiveModule->Parent) {
215635b13eceSDouglas Gregor     Diags.Report(ConfigMacrosLoc, diag::err_mmap_config_macro_submodule);
215735b13eceSDouglas Gregor   }
215835b13eceSDouglas Gregor 
215935b13eceSDouglas Gregor   // Parse the optional attributes.
216035b13eceSDouglas Gregor   Attributes Attrs;
21615d29dee0SDavide Italiano   if (parseOptionalAttributes(Attrs))
21625d29dee0SDavide Italiano     return;
21635d29dee0SDavide Italiano 
216435b13eceSDouglas Gregor   if (Attrs.IsExhaustive && !ActiveModule->Parent) {
216535b13eceSDouglas Gregor     ActiveModule->ConfigMacrosExhaustive = true;
216635b13eceSDouglas Gregor   }
216735b13eceSDouglas Gregor 
216835b13eceSDouglas Gregor   // If we don't have an identifier, we're done.
2169306d8920SRichard Smith   // FIXME: Support macros with the same name as a keyword here.
217035b13eceSDouglas Gregor   if (!Tok.is(MMToken::Identifier))
217135b13eceSDouglas Gregor     return;
217235b13eceSDouglas Gregor 
217335b13eceSDouglas Gregor   // Consume the first identifier.
217435b13eceSDouglas Gregor   if (!ActiveModule->Parent) {
217535b13eceSDouglas Gregor     ActiveModule->ConfigMacros.push_back(Tok.getString().str());
217635b13eceSDouglas Gregor   }
217735b13eceSDouglas Gregor   consumeToken();
217835b13eceSDouglas Gregor 
217935b13eceSDouglas Gregor   do {
218035b13eceSDouglas Gregor     // If there's a comma, consume it.
218135b13eceSDouglas Gregor     if (!Tok.is(MMToken::Comma))
218235b13eceSDouglas Gregor       break;
218335b13eceSDouglas Gregor     consumeToken();
218435b13eceSDouglas Gregor 
218535b13eceSDouglas Gregor     // We expect to see a macro name here.
2186306d8920SRichard Smith     // FIXME: Support macros with the same name as a keyword here.
218735b13eceSDouglas Gregor     if (!Tok.is(MMToken::Identifier)) {
218835b13eceSDouglas Gregor       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_config_macro);
218935b13eceSDouglas Gregor       break;
219035b13eceSDouglas Gregor     }
219135b13eceSDouglas Gregor 
219235b13eceSDouglas Gregor     // Consume the macro name.
219335b13eceSDouglas Gregor     if (!ActiveModule->Parent) {
219435b13eceSDouglas Gregor       ActiveModule->ConfigMacros.push_back(Tok.getString().str());
219535b13eceSDouglas Gregor     }
219635b13eceSDouglas Gregor     consumeToken();
219735b13eceSDouglas Gregor   } while (true);
219835b13eceSDouglas Gregor }
219935b13eceSDouglas Gregor 
2200fb912657SDouglas Gregor /// \brief Format a module-id into a string.
2201fb912657SDouglas Gregor static std::string formatModuleId(const ModuleId &Id) {
2202fb912657SDouglas Gregor   std::string result;
2203fb912657SDouglas Gregor   {
2204fb912657SDouglas Gregor     llvm::raw_string_ostream OS(result);
2205fb912657SDouglas Gregor 
2206fb912657SDouglas Gregor     for (unsigned I = 0, N = Id.size(); I != N; ++I) {
2207fb912657SDouglas Gregor       if (I)
2208fb912657SDouglas Gregor         OS << ".";
2209fb912657SDouglas Gregor       OS << Id[I].first;
2210fb912657SDouglas Gregor     }
2211fb912657SDouglas Gregor   }
2212fb912657SDouglas Gregor 
2213fb912657SDouglas Gregor   return result;
2214fb912657SDouglas Gregor }
2215fb912657SDouglas Gregor 
2216fb912657SDouglas Gregor /// \brief Parse a conflict declaration.
2217fb912657SDouglas Gregor ///
2218fb912657SDouglas Gregor ///   module-declaration:
2219fb912657SDouglas Gregor ///     'conflict' module-id ',' string-literal
2220fb912657SDouglas Gregor void ModuleMapParser::parseConflict() {
2221fb912657SDouglas Gregor   assert(Tok.is(MMToken::Conflict));
2222fb912657SDouglas Gregor   SourceLocation ConflictLoc = consumeToken();
2223fb912657SDouglas Gregor   Module::UnresolvedConflict Conflict;
2224fb912657SDouglas Gregor 
2225fb912657SDouglas Gregor   // Parse the module-id.
2226fb912657SDouglas Gregor   if (parseModuleId(Conflict.Id))
2227fb912657SDouglas Gregor     return;
2228fb912657SDouglas Gregor 
2229fb912657SDouglas Gregor   // Parse the ','.
2230fb912657SDouglas Gregor   if (!Tok.is(MMToken::Comma)) {
2231fb912657SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_conflicts_comma)
2232fb912657SDouglas Gregor       << SourceRange(ConflictLoc);
2233fb912657SDouglas Gregor     return;
2234fb912657SDouglas Gregor   }
2235fb912657SDouglas Gregor   consumeToken();
2236fb912657SDouglas Gregor 
2237fb912657SDouglas Gregor   // Parse the message.
2238fb912657SDouglas Gregor   if (!Tok.is(MMToken::StringLiteral)) {
2239fb912657SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_conflicts_message)
2240fb912657SDouglas Gregor       << formatModuleId(Conflict.Id);
2241fb912657SDouglas Gregor     return;
2242fb912657SDouglas Gregor   }
2243fb912657SDouglas Gregor   Conflict.Message = Tok.getString().str();
2244fb912657SDouglas Gregor   consumeToken();
2245fb912657SDouglas Gregor 
2246fb912657SDouglas Gregor   // Add this unresolved conflict.
2247fb912657SDouglas Gregor   ActiveModule->UnresolvedConflicts.push_back(Conflict);
2248fb912657SDouglas Gregor }
2249fb912657SDouglas Gregor 
22506ddfca91SDouglas Gregor /// \brief Parse an inferred module declaration (wildcard modules).
22519194a91dSDouglas Gregor ///
22529194a91dSDouglas Gregor ///   module-declaration:
22539194a91dSDouglas Gregor ///     'explicit'[opt] 'framework'[opt] 'module' * attributes[opt]
22549194a91dSDouglas Gregor ///       { inferred-module-member* }
22559194a91dSDouglas Gregor ///
22569194a91dSDouglas Gregor ///   inferred-module-member:
22579194a91dSDouglas Gregor ///     'export' '*'
22589194a91dSDouglas Gregor ///     'exclude' identifier
22599194a91dSDouglas Gregor void ModuleMapParser::parseInferredModuleDecl(bool Framework, bool Explicit) {
226073441091SDouglas Gregor   assert(Tok.is(MMToken::Star));
226173441091SDouglas Gregor   SourceLocation StarLoc = consumeToken();
226273441091SDouglas Gregor   bool Failed = false;
226373441091SDouglas Gregor 
226473441091SDouglas Gregor   // Inferred modules must be submodules.
22659194a91dSDouglas Gregor   if (!ActiveModule && !Framework) {
226673441091SDouglas Gregor     Diags.Report(StarLoc, diag::err_mmap_top_level_inferred_submodule);
226773441091SDouglas Gregor     Failed = true;
226873441091SDouglas Gregor   }
226973441091SDouglas Gregor 
22709194a91dSDouglas Gregor   if (ActiveModule) {
2271524e33e1SDouglas Gregor     // Inferred modules must have umbrella directories.
22724898cde4SBen Langmuir     if (!Failed && ActiveModule->IsAvailable &&
22734898cde4SBen Langmuir         !ActiveModule->getUmbrellaDir()) {
227473441091SDouglas Gregor       Diags.Report(StarLoc, diag::err_mmap_inferred_no_umbrella);
227573441091SDouglas Gregor       Failed = true;
227673441091SDouglas Gregor     }
227773441091SDouglas Gregor 
227873441091SDouglas Gregor     // Check for redefinition of an inferred module.
2279dd005f69SDouglas Gregor     if (!Failed && ActiveModule->InferSubmodules) {
228073441091SDouglas Gregor       Diags.Report(StarLoc, diag::err_mmap_inferred_redef);
2281dd005f69SDouglas Gregor       if (ActiveModule->InferredSubmoduleLoc.isValid())
2282dd005f69SDouglas Gregor         Diags.Report(ActiveModule->InferredSubmoduleLoc,
228373441091SDouglas Gregor                      diag::note_mmap_prev_definition);
228473441091SDouglas Gregor       Failed = true;
228573441091SDouglas Gregor     }
228673441091SDouglas Gregor 
22879194a91dSDouglas Gregor     // Check for the 'framework' keyword, which is not permitted here.
22889194a91dSDouglas Gregor     if (Framework) {
22899194a91dSDouglas Gregor       Diags.Report(StarLoc, diag::err_mmap_inferred_framework_submodule);
22909194a91dSDouglas Gregor       Framework = false;
22919194a91dSDouglas Gregor     }
22929194a91dSDouglas Gregor   } else if (Explicit) {
22939194a91dSDouglas Gregor     Diags.Report(StarLoc, diag::err_mmap_explicit_inferred_framework);
22949194a91dSDouglas Gregor     Explicit = false;
22959194a91dSDouglas Gregor   }
22969194a91dSDouglas Gregor 
229773441091SDouglas Gregor   // If there were any problems with this inferred submodule, skip its body.
229873441091SDouglas Gregor   if (Failed) {
229973441091SDouglas Gregor     if (Tok.is(MMToken::LBrace)) {
230073441091SDouglas Gregor       consumeToken();
230173441091SDouglas Gregor       skipUntil(MMToken::RBrace);
230273441091SDouglas Gregor       if (Tok.is(MMToken::RBrace))
230373441091SDouglas Gregor         consumeToken();
230473441091SDouglas Gregor     }
230573441091SDouglas Gregor     HadError = true;
230673441091SDouglas Gregor     return;
230773441091SDouglas Gregor   }
230873441091SDouglas Gregor 
23099194a91dSDouglas Gregor   // Parse optional attributes.
23104442605fSBill Wendling   Attributes Attrs;
23115d29dee0SDavide Italiano   if (parseOptionalAttributes(Attrs))
23125d29dee0SDavide Italiano     return;
23139194a91dSDouglas Gregor 
23149194a91dSDouglas Gregor   if (ActiveModule) {
231573441091SDouglas Gregor     // Note that we have an inferred submodule.
2316dd005f69SDouglas Gregor     ActiveModule->InferSubmodules = true;
2317dd005f69SDouglas Gregor     ActiveModule->InferredSubmoduleLoc = StarLoc;
2318dd005f69SDouglas Gregor     ActiveModule->InferExplicitSubmodules = Explicit;
23199194a91dSDouglas Gregor   } else {
23209194a91dSDouglas Gregor     // We'll be inferring framework modules for this directory.
23219194a91dSDouglas Gregor     Map.InferredDirectories[Directory].InferModules = true;
2322c1d88ea5SBen Langmuir     Map.InferredDirectories[Directory].Attrs = Attrs;
2323beee15e7SBen Langmuir     Map.InferredDirectories[Directory].ModuleMapFile = ModuleMapFile;
2324131daca0SRichard Smith     // FIXME: Handle the 'framework' keyword.
23259194a91dSDouglas Gregor   }
232673441091SDouglas Gregor 
232773441091SDouglas Gregor   // Parse the opening brace.
232873441091SDouglas Gregor   if (!Tok.is(MMToken::LBrace)) {
232973441091SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_lbrace_wildcard);
233073441091SDouglas Gregor     HadError = true;
233173441091SDouglas Gregor     return;
233273441091SDouglas Gregor   }
233373441091SDouglas Gregor   SourceLocation LBraceLoc = consumeToken();
233473441091SDouglas Gregor 
233573441091SDouglas Gregor   // Parse the body of the inferred submodule.
233673441091SDouglas Gregor   bool Done = false;
233773441091SDouglas Gregor   do {
233873441091SDouglas Gregor     switch (Tok.Kind) {
233973441091SDouglas Gregor     case MMToken::EndOfFile:
234073441091SDouglas Gregor     case MMToken::RBrace:
234173441091SDouglas Gregor       Done = true;
234273441091SDouglas Gregor       break;
234373441091SDouglas Gregor 
23449194a91dSDouglas Gregor     case MMToken::ExcludeKeyword: {
23459194a91dSDouglas Gregor       if (ActiveModule) {
23469194a91dSDouglas Gregor         Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member)
2347d2d442caSCraig Topper           << (ActiveModule != nullptr);
23489194a91dSDouglas Gregor         consumeToken();
23499194a91dSDouglas Gregor         break;
23509194a91dSDouglas Gregor       }
23519194a91dSDouglas Gregor 
23529194a91dSDouglas Gregor       consumeToken();
2353306d8920SRichard Smith       // FIXME: Support string-literal module names here.
23549194a91dSDouglas Gregor       if (!Tok.is(MMToken::Identifier)) {
23559194a91dSDouglas Gregor         Diags.Report(Tok.getLocation(), diag::err_mmap_missing_exclude_name);
23569194a91dSDouglas Gregor         break;
23579194a91dSDouglas Gregor       }
23589194a91dSDouglas Gregor 
23599194a91dSDouglas Gregor       Map.InferredDirectories[Directory].ExcludedModules
23609194a91dSDouglas Gregor         .push_back(Tok.getString());
23619194a91dSDouglas Gregor       consumeToken();
23629194a91dSDouglas Gregor       break;
23639194a91dSDouglas Gregor     }
23649194a91dSDouglas Gregor 
23659194a91dSDouglas Gregor     case MMToken::ExportKeyword:
23669194a91dSDouglas Gregor       if (!ActiveModule) {
23679194a91dSDouglas Gregor         Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member)
2368d2d442caSCraig Topper           << (ActiveModule != nullptr);
23699194a91dSDouglas Gregor         consumeToken();
23709194a91dSDouglas Gregor         break;
23719194a91dSDouglas Gregor       }
23729194a91dSDouglas Gregor 
237373441091SDouglas Gregor       consumeToken();
237473441091SDouglas Gregor       if (Tok.is(MMToken::Star))
2375dd005f69SDouglas Gregor         ActiveModule->InferExportWildcard = true;
237673441091SDouglas Gregor       else
237773441091SDouglas Gregor         Diags.Report(Tok.getLocation(),
237873441091SDouglas Gregor                      diag::err_mmap_expected_export_wildcard);
237973441091SDouglas Gregor       consumeToken();
238073441091SDouglas Gregor       break;
238173441091SDouglas Gregor 
238273441091SDouglas Gregor     case MMToken::ExplicitKeyword:
238373441091SDouglas Gregor     case MMToken::ModuleKeyword:
238473441091SDouglas Gregor     case MMToken::HeaderKeyword:
2385b53e5483SLawrence Crowl     case MMToken::PrivateKeyword:
238673441091SDouglas Gregor     case MMToken::UmbrellaKeyword:
238773441091SDouglas Gregor     default:
23889194a91dSDouglas Gregor       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member)
2389d2d442caSCraig Topper           << (ActiveModule != nullptr);
239073441091SDouglas Gregor       consumeToken();
239173441091SDouglas Gregor       break;
239273441091SDouglas Gregor     }
239373441091SDouglas Gregor   } while (!Done);
239473441091SDouglas Gregor 
239573441091SDouglas Gregor   if (Tok.is(MMToken::RBrace))
239673441091SDouglas Gregor     consumeToken();
239773441091SDouglas Gregor   else {
239873441091SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
239973441091SDouglas Gregor     Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
240073441091SDouglas Gregor     HadError = true;
240173441091SDouglas Gregor   }
240273441091SDouglas Gregor }
240373441091SDouglas Gregor 
24049194a91dSDouglas Gregor /// \brief Parse optional attributes.
24059194a91dSDouglas Gregor ///
24069194a91dSDouglas Gregor ///   attributes:
24079194a91dSDouglas Gregor ///     attribute attributes
24089194a91dSDouglas Gregor ///     attribute
24099194a91dSDouglas Gregor ///
24109194a91dSDouglas Gregor ///   attribute:
24119194a91dSDouglas Gregor ///     [ identifier ]
24129194a91dSDouglas Gregor ///
24139194a91dSDouglas Gregor /// \param Attrs Will be filled in with the parsed attributes.
24149194a91dSDouglas Gregor ///
24159194a91dSDouglas Gregor /// \returns true if an error occurred, false otherwise.
24164442605fSBill Wendling bool ModuleMapParser::parseOptionalAttributes(Attributes &Attrs) {
24179194a91dSDouglas Gregor   bool HadError = false;
24189194a91dSDouglas Gregor 
24199194a91dSDouglas Gregor   while (Tok.is(MMToken::LSquare)) {
24209194a91dSDouglas Gregor     // Consume the '['.
24219194a91dSDouglas Gregor     SourceLocation LSquareLoc = consumeToken();
24229194a91dSDouglas Gregor 
24239194a91dSDouglas Gregor     // Check whether we have an attribute name here.
24249194a91dSDouglas Gregor     if (!Tok.is(MMToken::Identifier)) {
24259194a91dSDouglas Gregor       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_attribute);
24269194a91dSDouglas Gregor       skipUntil(MMToken::RSquare);
24279194a91dSDouglas Gregor       if (Tok.is(MMToken::RSquare))
24289194a91dSDouglas Gregor         consumeToken();
24299194a91dSDouglas Gregor       HadError = true;
24309194a91dSDouglas Gregor     }
24319194a91dSDouglas Gregor 
24329194a91dSDouglas Gregor     // Decode the attribute name.
24339194a91dSDouglas Gregor     AttributeKind Attribute
24349194a91dSDouglas Gregor       = llvm::StringSwitch<AttributeKind>(Tok.getString())
243535b13eceSDouglas Gregor           .Case("exhaustive", AT_exhaustive)
243677944868SRichard Smith           .Case("extern_c", AT_extern_c)
2437ed84df00SBruno Cardoso Lopes           .Case("no_undeclared_includes", AT_no_undeclared_includes)
24389194a91dSDouglas Gregor           .Case("system", AT_system)
24399194a91dSDouglas Gregor           .Default(AT_unknown);
24409194a91dSDouglas Gregor     switch (Attribute) {
24419194a91dSDouglas Gregor     case AT_unknown:
24429194a91dSDouglas Gregor       Diags.Report(Tok.getLocation(), diag::warn_mmap_unknown_attribute)
24439194a91dSDouglas Gregor         << Tok.getString();
24449194a91dSDouglas Gregor       break;
24459194a91dSDouglas Gregor 
24469194a91dSDouglas Gregor     case AT_system:
24479194a91dSDouglas Gregor       Attrs.IsSystem = true;
24489194a91dSDouglas Gregor       break;
244935b13eceSDouglas Gregor 
245077944868SRichard Smith     case AT_extern_c:
245177944868SRichard Smith       Attrs.IsExternC = true;
245277944868SRichard Smith       break;
245377944868SRichard Smith 
245435b13eceSDouglas Gregor     case AT_exhaustive:
245535b13eceSDouglas Gregor       Attrs.IsExhaustive = true;
245635b13eceSDouglas Gregor       break;
2457ed84df00SBruno Cardoso Lopes 
2458ed84df00SBruno Cardoso Lopes     case AT_no_undeclared_includes:
2459ed84df00SBruno Cardoso Lopes       Attrs.NoUndeclaredIncludes = true;
2460ed84df00SBruno Cardoso Lopes       break;
24619194a91dSDouglas Gregor     }
24629194a91dSDouglas Gregor     consumeToken();
24639194a91dSDouglas Gregor 
24649194a91dSDouglas Gregor     // Consume the ']'.
24659194a91dSDouglas Gregor     if (!Tok.is(MMToken::RSquare)) {
24669194a91dSDouglas Gregor       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rsquare);
24679194a91dSDouglas Gregor       Diags.Report(LSquareLoc, diag::note_mmap_lsquare_match);
24689194a91dSDouglas Gregor       skipUntil(MMToken::RSquare);
24699194a91dSDouglas Gregor       HadError = true;
24709194a91dSDouglas Gregor     }
24719194a91dSDouglas Gregor 
24729194a91dSDouglas Gregor     if (Tok.is(MMToken::RSquare))
24739194a91dSDouglas Gregor       consumeToken();
24749194a91dSDouglas Gregor   }
24759194a91dSDouglas Gregor 
24769194a91dSDouglas Gregor   return HadError;
24779194a91dSDouglas Gregor }
24789194a91dSDouglas Gregor 
2479718292f2SDouglas Gregor /// \brief Parse a module map file.
2480718292f2SDouglas Gregor ///
2481718292f2SDouglas Gregor ///   module-map-file:
2482718292f2SDouglas Gregor ///     module-declaration*
2483718292f2SDouglas Gregor bool ModuleMapParser::parseModuleMapFile() {
2484718292f2SDouglas Gregor   do {
2485718292f2SDouglas Gregor     switch (Tok.Kind) {
2486718292f2SDouglas Gregor     case MMToken::EndOfFile:
2487718292f2SDouglas Gregor       return HadError;
2488718292f2SDouglas Gregor 
2489e7ab3669SDouglas Gregor     case MMToken::ExplicitKeyword:
249097292843SDaniel Jasper     case MMToken::ExternKeyword:
2491718292f2SDouglas Gregor     case MMToken::ModuleKeyword:
2492755b2055SDouglas Gregor     case MMToken::FrameworkKeyword:
2493718292f2SDouglas Gregor       parseModuleDecl();
2494718292f2SDouglas Gregor       break;
2495718292f2SDouglas Gregor 
24961fb5c3a6SDouglas Gregor     case MMToken::Comma:
249735b13eceSDouglas Gregor     case MMToken::ConfigMacros:
2498fb912657SDouglas Gregor     case MMToken::Conflict:
2499a3feee2aSRichard Smith     case MMToken::Exclaim:
250059527666SDouglas Gregor     case MMToken::ExcludeKeyword:
25012b82c2a5SDouglas Gregor     case MMToken::ExportKeyword:
2502718292f2SDouglas Gregor     case MMToken::HeaderKeyword:
2503718292f2SDouglas Gregor     case MMToken::Identifier:
2504718292f2SDouglas Gregor     case MMToken::LBrace:
25056ddfca91SDouglas Gregor     case MMToken::LinkKeyword:
2506a686e1b0SDouglas Gregor     case MMToken::LSquare:
25072b82c2a5SDouglas Gregor     case MMToken::Period:
2508b53e5483SLawrence Crowl     case MMToken::PrivateKeyword:
2509718292f2SDouglas Gregor     case MMToken::RBrace:
2510a686e1b0SDouglas Gregor     case MMToken::RSquare:
25111fb5c3a6SDouglas Gregor     case MMToken::RequiresKeyword:
25122b82c2a5SDouglas Gregor     case MMToken::Star:
2513718292f2SDouglas Gregor     case MMToken::StringLiteral:
2514b8afebe2SRichard Smith     case MMToken::TextualKeyword:
2515718292f2SDouglas Gregor     case MMToken::UmbrellaKeyword:
2516ba7f2f71SDaniel Jasper     case MMToken::UseKeyword:
2517718292f2SDouglas Gregor       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module);
2518718292f2SDouglas Gregor       HadError = true;
2519718292f2SDouglas Gregor       consumeToken();
2520718292f2SDouglas Gregor       break;
2521718292f2SDouglas Gregor     }
2522718292f2SDouglas Gregor   } while (true);
2523718292f2SDouglas Gregor }
2524718292f2SDouglas Gregor 
25259acb99e3SRichard Smith bool ModuleMap::parseModuleMapFile(const FileEntry *File, bool IsSystem,
2526ae6df27eSRichard Smith                                    const DirectoryEntry *Dir,
2527ae6df27eSRichard Smith                                    SourceLocation ExternModuleLoc) {
25284ddf2221SDouglas Gregor   llvm::DenseMap<const FileEntry *, bool>::iterator Known
25294ddf2221SDouglas Gregor     = ParsedModuleMap.find(File);
25304ddf2221SDouglas Gregor   if (Known != ParsedModuleMap.end())
25314ddf2221SDouglas Gregor     return Known->second;
25324ddf2221SDouglas Gregor 
2533d2d442caSCraig Topper   assert(Target && "Missing target information");
2534cb69b57bSBen Langmuir   auto FileCharacter = IsSystem ? SrcMgr::C_System : SrcMgr::C_User;
2535ae6df27eSRichard Smith   FileID ID = SourceMgr.createFileID(File, ExternModuleLoc, FileCharacter);
25361f76c4e8SManuel Klimek   const llvm::MemoryBuffer *Buffer = SourceMgr.getBuffer(ID);
2537718292f2SDouglas Gregor   if (!Buffer)
25384ddf2221SDouglas Gregor     return ParsedModuleMap[File] = true;
2539718292f2SDouglas Gregor 
2540718292f2SDouglas Gregor   // Parse this module map file.
25411f76c4e8SManuel Klimek   Lexer L(ID, SourceMgr.getBuffer(ID), SourceMgr, MMapLangOpts);
25422a6edb30SRichard Smith   SourceLocation Start = L.getSourceLocation();
2543beee15e7SBen Langmuir   ModuleMapParser Parser(L, SourceMgr, Target, Diags, *this, File, Dir,
2544963c5535SDouglas Gregor                          BuiltinIncludeDir, IsSystem);
2545718292f2SDouglas Gregor   bool Result = Parser.parseModuleMapFile();
25464ddf2221SDouglas Gregor   ParsedModuleMap[File] = Result;
25472a6edb30SRichard Smith 
25482a6edb30SRichard Smith   // Notify callbacks that we parsed it.
25492a6edb30SRichard Smith   for (const auto &Cb : Callbacks)
25502a6edb30SRichard Smith     Cb->moduleMapFileRead(Start, *File, IsSystem);
2551718292f2SDouglas Gregor   return Result;
2552718292f2SDouglas Gregor }
2553