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"
223a02247dSChandler Carruth #include "clang/Lex/LexDiagnostic.h"
233a02247dSChandler Carruth #include "clang/Lex/Lexer.h"
243a02247dSChandler Carruth #include "clang/Lex/LiteralSupport.h"
253a02247dSChandler Carruth #include "llvm/ADT/StringRef.h"
263a02247dSChandler Carruth #include "llvm/ADT/StringSwitch.h"
27718292f2SDouglas Gregor #include "llvm/Support/Allocator.h"
28e89dbc1dSDouglas Gregor #include "llvm/Support/FileSystem.h"
29718292f2SDouglas Gregor #include "llvm/Support/Host.h"
30552c169eSRafael Espindola #include "llvm/Support/Path.h"
31718292f2SDouglas Gregor #include "llvm/Support/raw_ostream.h"
3207c22b78SDouglas Gregor #include <stdlib.h>
3301c7cfa2SDouglas Gregor #if defined(LLVM_ON_UNIX)
34eadae014SDmitri Gribenko #include <limits.h>
3501c7cfa2SDouglas Gregor #endif
36718292f2SDouglas Gregor using namespace clang;
37718292f2SDouglas Gregor 
382b82c2a5SDouglas Gregor Module::ExportDecl
392b82c2a5SDouglas Gregor ModuleMap::resolveExport(Module *Mod,
402b82c2a5SDouglas Gregor                          const Module::UnresolvedExportDecl &Unresolved,
41e4412640SArgyrios Kyrtzidis                          bool Complain) const {
42f5eedd05SDouglas Gregor   // We may have just a wildcard.
43f5eedd05SDouglas Gregor   if (Unresolved.Id.empty()) {
44f5eedd05SDouglas Gregor     assert(Unresolved.Wildcard && "Invalid unresolved export");
45d2d442caSCraig Topper     return Module::ExportDecl(nullptr, true);
46f5eedd05SDouglas Gregor   }
47f5eedd05SDouglas Gregor 
48fb912657SDouglas Gregor   // Resolve the module-id.
49fb912657SDouglas Gregor   Module *Context = resolveModuleId(Unresolved.Id, Mod, Complain);
50fb912657SDouglas Gregor   if (!Context)
51fb912657SDouglas Gregor     return Module::ExportDecl();
52fb912657SDouglas Gregor 
53fb912657SDouglas Gregor   return Module::ExportDecl(Context, Unresolved.Wildcard);
54fb912657SDouglas Gregor }
55fb912657SDouglas Gregor 
56fb912657SDouglas Gregor Module *ModuleMap::resolveModuleId(const ModuleId &Id, Module *Mod,
57fb912657SDouglas Gregor                                    bool Complain) const {
582b82c2a5SDouglas Gregor   // Find the starting module.
59fb912657SDouglas Gregor   Module *Context = lookupModuleUnqualified(Id[0].first, Mod);
602b82c2a5SDouglas Gregor   if (!Context) {
612b82c2a5SDouglas Gregor     if (Complain)
620761a8a0SDaniel Jasper       Diags.Report(Id[0].second, diag::err_mmap_missing_module_unqualified)
63fb912657SDouglas Gregor       << Id[0].first << Mod->getFullModuleName();
642b82c2a5SDouglas Gregor 
65d2d442caSCraig Topper     return nullptr;
662b82c2a5SDouglas Gregor   }
672b82c2a5SDouglas Gregor 
682b82c2a5SDouglas Gregor   // Dig into the module path.
69fb912657SDouglas Gregor   for (unsigned I = 1, N = Id.size(); I != N; ++I) {
70fb912657SDouglas Gregor     Module *Sub = lookupModuleQualified(Id[I].first, Context);
712b82c2a5SDouglas Gregor     if (!Sub) {
722b82c2a5SDouglas Gregor       if (Complain)
730761a8a0SDaniel Jasper         Diags.Report(Id[I].second, diag::err_mmap_missing_module_qualified)
74fb912657SDouglas Gregor         << Id[I].first << Context->getFullModuleName()
75fb912657SDouglas Gregor         << SourceRange(Id[0].second, Id[I-1].second);
762b82c2a5SDouglas Gregor 
77d2d442caSCraig Topper       return nullptr;
782b82c2a5SDouglas Gregor     }
792b82c2a5SDouglas Gregor 
802b82c2a5SDouglas Gregor     Context = Sub;
812b82c2a5SDouglas Gregor   }
822b82c2a5SDouglas Gregor 
83fb912657SDouglas Gregor   return Context;
842b82c2a5SDouglas Gregor }
852b82c2a5SDouglas Gregor 
860761a8a0SDaniel Jasper ModuleMap::ModuleMap(SourceManager &SourceMgr, DiagnosticsEngine &Diags,
87b146baabSArgyrios Kyrtzidis                      const LangOptions &LangOpts, const TargetInfo *Target,
88b146baabSArgyrios Kyrtzidis                      HeaderSearch &HeaderInfo)
890761a8a0SDaniel Jasper     : SourceMgr(SourceMgr), Diags(Diags), LangOpts(LangOpts), Target(Target),
90d2d442caSCraig Topper       HeaderInfo(HeaderInfo), BuiltinIncludeDir(nullptr),
91d2d442caSCraig Topper       CompilingModule(nullptr), SourceModule(nullptr) {}
92718292f2SDouglas Gregor 
93718292f2SDouglas Gregor ModuleMap::~ModuleMap() {
945acdf59eSDouglas Gregor   for (llvm::StringMap<Module *>::iterator I = Modules.begin(),
955acdf59eSDouglas Gregor                                         IEnd = Modules.end();
965acdf59eSDouglas Gregor        I != IEnd; ++I) {
975acdf59eSDouglas Gregor     delete I->getValue();
985acdf59eSDouglas Gregor   }
99718292f2SDouglas Gregor }
100718292f2SDouglas Gregor 
10189929282SDouglas Gregor void ModuleMap::setTarget(const TargetInfo &Target) {
10289929282SDouglas Gregor   assert((!this->Target || this->Target == &Target) &&
10389929282SDouglas Gregor          "Improper target override");
10489929282SDouglas Gregor   this->Target = &Target;
10589929282SDouglas Gregor }
10689929282SDouglas Gregor 
107056396aeSDouglas Gregor /// \brief "Sanitize" a filename so that it can be used as an identifier.
108056396aeSDouglas Gregor static StringRef sanitizeFilenameAsIdentifier(StringRef Name,
109056396aeSDouglas Gregor                                               SmallVectorImpl<char> &Buffer) {
110056396aeSDouglas Gregor   if (Name.empty())
111056396aeSDouglas Gregor     return Name;
112056396aeSDouglas Gregor 
113a7d03840SJordan Rose   if (!isValidIdentifier(Name)) {
114056396aeSDouglas Gregor     // If we don't already have something with the form of an identifier,
115056396aeSDouglas Gregor     // create a buffer with the sanitized name.
116056396aeSDouglas Gregor     Buffer.clear();
117a7d03840SJordan Rose     if (isDigit(Name[0]))
118056396aeSDouglas Gregor       Buffer.push_back('_');
119056396aeSDouglas Gregor     Buffer.reserve(Buffer.size() + Name.size());
120056396aeSDouglas Gregor     for (unsigned I = 0, N = Name.size(); I != N; ++I) {
121a7d03840SJordan Rose       if (isIdentifierBody(Name[I]))
122056396aeSDouglas Gregor         Buffer.push_back(Name[I]);
123056396aeSDouglas Gregor       else
124056396aeSDouglas Gregor         Buffer.push_back('_');
125056396aeSDouglas Gregor     }
126056396aeSDouglas Gregor 
127056396aeSDouglas Gregor     Name = StringRef(Buffer.data(), Buffer.size());
128056396aeSDouglas Gregor   }
129056396aeSDouglas Gregor 
130056396aeSDouglas Gregor   while (llvm::StringSwitch<bool>(Name)
131056396aeSDouglas Gregor #define KEYWORD(Keyword,Conditions) .Case(#Keyword, true)
132056396aeSDouglas Gregor #define ALIAS(Keyword, AliasOf, Conditions) .Case(Keyword, true)
133056396aeSDouglas Gregor #include "clang/Basic/TokenKinds.def"
134056396aeSDouglas Gregor            .Default(false)) {
135056396aeSDouglas Gregor     if (Name.data() != Buffer.data())
136056396aeSDouglas Gregor       Buffer.append(Name.begin(), Name.end());
137056396aeSDouglas Gregor     Buffer.push_back('_');
138056396aeSDouglas Gregor     Name = StringRef(Buffer.data(), Buffer.size());
139056396aeSDouglas Gregor   }
140056396aeSDouglas Gregor 
141056396aeSDouglas Gregor   return Name;
142056396aeSDouglas Gregor }
143056396aeSDouglas Gregor 
14434d52749SDouglas Gregor /// \brief Determine whether the given file name is the name of a builtin
14534d52749SDouglas Gregor /// header, supplied by Clang to replace, override, or augment existing system
14634d52749SDouglas Gregor /// headers.
14734d52749SDouglas Gregor static bool isBuiltinHeader(StringRef FileName) {
14834d52749SDouglas Gregor   return llvm::StringSwitch<bool>(FileName)
14934d52749SDouglas Gregor            .Case("float.h", true)
15034d52749SDouglas Gregor            .Case("iso646.h", true)
15134d52749SDouglas Gregor            .Case("limits.h", true)
15234d52749SDouglas Gregor            .Case("stdalign.h", true)
15334d52749SDouglas Gregor            .Case("stdarg.h", true)
15434d52749SDouglas Gregor            .Case("stdbool.h", true)
15534d52749SDouglas Gregor            .Case("stddef.h", true)
15634d52749SDouglas Gregor            .Case("stdint.h", true)
15734d52749SDouglas Gregor            .Case("tgmath.h", true)
15834d52749SDouglas Gregor            .Case("unwind.h", true)
15934d52749SDouglas Gregor            .Default(false);
16034d52749SDouglas Gregor }
16134d52749SDouglas Gregor 
16292669ee4SDaniel Jasper ModuleMap::HeadersMap::iterator
16392669ee4SDaniel Jasper ModuleMap::findKnownHeader(const FileEntry *File) {
16459527666SDouglas Gregor   HeadersMap::iterator Known = Headers.find(File);
1654eaf0a6cSDaniel Jasper   if (Known == Headers.end() && File->getDir() == BuiltinIncludeDir &&
1664eaf0a6cSDaniel Jasper       isBuiltinHeader(llvm::sys::path::filename(File->getName()))) {
1674eaf0a6cSDaniel Jasper     HeaderInfo.loadTopLevelSystemModules();
16892669ee4SDaniel Jasper     return Headers.find(File);
1694eaf0a6cSDaniel Jasper   }
17092669ee4SDaniel Jasper   return Known;
17192669ee4SDaniel Jasper }
17292669ee4SDaniel Jasper 
1734469138eSBen Langmuir ModuleMap::KnownHeader
1744469138eSBen Langmuir ModuleMap::findHeaderInUmbrellaDirs(const FileEntry *File,
1754469138eSBen Langmuir                     SmallVectorImpl<const DirectoryEntry *> &IntermediateDirs) {
1764469138eSBen Langmuir   const DirectoryEntry *Dir = File->getDir();
1774469138eSBen Langmuir   assert(Dir && "file in no directory");
1784469138eSBen Langmuir 
1794469138eSBen Langmuir   // Note: as an egregious but useful hack we use the real path here, because
1804469138eSBen Langmuir   // frameworks moving from top-level frameworks to embedded frameworks tend
1814469138eSBen Langmuir   // to be symlinked from the top-level location to the embedded location,
1824469138eSBen Langmuir   // and we need to resolve lookups as if we had found the embedded location.
1834469138eSBen Langmuir   StringRef DirName = SourceMgr.getFileManager().getCanonicalName(Dir);
1844469138eSBen Langmuir 
1854469138eSBen Langmuir   // Keep walking up the directory hierarchy, looking for a directory with
1864469138eSBen Langmuir   // an umbrella header.
1874469138eSBen Langmuir   do {
1884469138eSBen Langmuir     auto KnownDir = UmbrellaDirs.find(Dir);
1894469138eSBen Langmuir     if (KnownDir != UmbrellaDirs.end())
1904469138eSBen Langmuir       return KnownHeader(KnownDir->second, NormalHeader);
1914469138eSBen Langmuir 
1924469138eSBen Langmuir     IntermediateDirs.push_back(Dir);
1934469138eSBen Langmuir 
1944469138eSBen Langmuir     // Retrieve our parent path.
1954469138eSBen Langmuir     DirName = llvm::sys::path::parent_path(DirName);
1964469138eSBen Langmuir     if (DirName.empty())
1974469138eSBen Langmuir       break;
1984469138eSBen Langmuir 
1994469138eSBen Langmuir     // Resolve the parent path to a directory entry.
2004469138eSBen Langmuir     Dir = SourceMgr.getFileManager().getDirectory(DirName);
2014469138eSBen Langmuir   } while (Dir);
2024469138eSBen Langmuir   return KnownHeader();
2034469138eSBen Langmuir }
2044469138eSBen Langmuir 
205202210b3SRichard Smith // Returns true if RequestingModule directly uses RequestedModule.
20692669ee4SDaniel Jasper static bool directlyUses(const Module *RequestingModule,
20792669ee4SDaniel Jasper                          const Module *RequestedModule) {
20892669ee4SDaniel Jasper   return std::find(RequestingModule->DirectUses.begin(),
20992669ee4SDaniel Jasper                    RequestingModule->DirectUses.end(),
21092669ee4SDaniel Jasper                    RequestedModule) != RequestingModule->DirectUses.end();
21192669ee4SDaniel Jasper }
21292669ee4SDaniel Jasper 
21392669ee4SDaniel Jasper static bool violatesPrivateInclude(Module *RequestingModule,
21492669ee4SDaniel Jasper                                    const FileEntry *IncFileEnt,
21592669ee4SDaniel Jasper                                    ModuleMap::ModuleHeaderRole Role,
21692669ee4SDaniel Jasper                                    Module *RequestedModule) {
217202210b3SRichard Smith   bool IsPrivateRole = Role & ModuleMap::PrivateHeader;
21892669ee4SDaniel Jasper #ifndef NDEBUG
21992669ee4SDaniel Jasper   // Check for consistency between the module header role
22092669ee4SDaniel Jasper   // as obtained from the lookup and as obtained from the module.
22192669ee4SDaniel Jasper   // This check is not cheap, so enable it only for debugging.
222202210b3SRichard Smith   bool IsPrivate = false;
223*0ef0aecaSHans Wennborg   auto HeaderList = {&RequestedModule->PrivateHeaders,
224*0ef0aecaSHans Wennborg                      &RequestedModule->PrivateTextualHeaders};
225*0ef0aecaSHans Wennborg   for (auto *Hdrs : HeaderList)
226202210b3SRichard Smith     IsPrivate |=
227202210b3SRichard Smith         std::find(Hdrs->begin(), Hdrs->end(), IncFileEnt) != Hdrs->end();
228202210b3SRichard Smith   assert(IsPrivate == IsPrivateRole && "inconsistent headers and roles");
22992669ee4SDaniel Jasper #endif
230202210b3SRichard Smith   return IsPrivateRole &&
23192669ee4SDaniel Jasper          RequestedModule->getTopLevelModule() != 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,
23992669ee4SDaniel Jasper                                         SourceLocation FilenameLoc,
24092669ee4SDaniel Jasper                                         StringRef Filename,
24192669ee4SDaniel Jasper                                         const FileEntry *File) {
24292669ee4SDaniel Jasper   // No errors for indirect modules. This may be a bit of a problem for modules
24392669ee4SDaniel Jasper   // with no source files.
24471e1a64fSBen Langmuir   if (getTopLevelOrNull(RequestingModule) != getTopLevelOrNull(SourceModule))
24592669ee4SDaniel Jasper     return;
24692669ee4SDaniel Jasper 
24792669ee4SDaniel Jasper   if (RequestingModule)
24892669ee4SDaniel Jasper     resolveUses(RequestingModule, /*Complain=*/false);
24992669ee4SDaniel Jasper 
25071e1a64fSBen Langmuir   bool Excluded = false;
251d2d442caSCraig Topper   Module *Private = nullptr;
252d2d442caSCraig Topper   Module *NotUsed = nullptr;
25371e1a64fSBen Langmuir 
25471e1a64fSBen Langmuir   HeadersMap::iterator Known = findKnownHeader(File);
25571e1a64fSBen Langmuir   if (Known != Headers.end()) {
25671e1a64fSBen Langmuir     for (const KnownHeader &Header : Known->second) {
25792669ee4SDaniel Jasper       // If 'File' is part of 'RequestingModule' we can definitely include it.
25871e1a64fSBen Langmuir       if (Header.getModule() == RequestingModule)
25992669ee4SDaniel Jasper         return;
26092669ee4SDaniel Jasper 
26192669ee4SDaniel Jasper       // Remember private headers for later printing of a diagnostic.
26271e1a64fSBen Langmuir       if (violatesPrivateInclude(RequestingModule, File, Header.getRole(),
26371e1a64fSBen Langmuir                                  Header.getModule())) {
26471e1a64fSBen Langmuir         Private = Header.getModule();
26592669ee4SDaniel Jasper         continue;
26692669ee4SDaniel Jasper       }
26792669ee4SDaniel Jasper 
26892669ee4SDaniel Jasper       // If uses need to be specified explicitly, we are only allowed to return
26992669ee4SDaniel Jasper       // modules that are explicitly used by the requesting module.
27092669ee4SDaniel Jasper       if (RequestingModule && LangOpts.ModulesDeclUse &&
27171e1a64fSBen Langmuir           !directlyUses(RequestingModule, Header.getModule())) {
27271e1a64fSBen Langmuir         NotUsed = Header.getModule();
27392669ee4SDaniel Jasper         continue;
27492669ee4SDaniel Jasper       }
27592669ee4SDaniel Jasper 
27692669ee4SDaniel Jasper       // We have found a module that we can happily use.
27792669ee4SDaniel Jasper       return;
27892669ee4SDaniel Jasper     }
279feb54b6dSRichard Smith 
280feb54b6dSRichard Smith     Excluded = true;
28171e1a64fSBen Langmuir   }
28292669ee4SDaniel Jasper 
28392669ee4SDaniel Jasper   // We have found a header, but it is private.
284d2d442caSCraig Topper   if (Private) {
28592669ee4SDaniel Jasper     Diags.Report(FilenameLoc, diag::error_use_of_private_header_outside_module)
28692669ee4SDaniel Jasper         << Filename;
28792669ee4SDaniel Jasper     return;
28892669ee4SDaniel Jasper   }
28992669ee4SDaniel Jasper 
29092669ee4SDaniel Jasper   // We have found a module, but we don't use it.
291d2d442caSCraig Topper   if (NotUsed) {
29292669ee4SDaniel Jasper     Diags.Report(FilenameLoc, diag::error_undeclared_use_of_module)
29392669ee4SDaniel Jasper         << RequestingModule->getFullModuleName() << Filename;
29492669ee4SDaniel Jasper     return;
29592669ee4SDaniel Jasper   }
29692669ee4SDaniel Jasper 
29771e1a64fSBen Langmuir   if (Excluded || isHeaderInUmbrellaDirs(File))
29871e1a64fSBen Langmuir     return;
29971e1a64fSBen Langmuir 
30071e1a64fSBen Langmuir   // At this point, only non-modular includes remain.
30171e1a64fSBen Langmuir 
30271e1a64fSBen Langmuir   if (LangOpts.ModulesStrictDeclUse) {
30371e1a64fSBen Langmuir     Diags.Report(FilenameLoc, diag::error_undeclared_use_of_module)
30471e1a64fSBen Langmuir         << RequestingModule->getFullModuleName() << Filename;
30571e1a64fSBen Langmuir   } else if (RequestingModule) {
30671e1a64fSBen Langmuir     diag::kind DiagID = RequestingModule->getTopLevelModule()->IsFramework ?
30771e1a64fSBen Langmuir         diag::warn_non_modular_include_in_framework_module :
30871e1a64fSBen Langmuir         diag::warn_non_modular_include_in_module;
30971e1a64fSBen Langmuir     Diags.Report(FilenameLoc, DiagID) << RequestingModule->getFullModuleName();
31071e1a64fSBen Langmuir   }
31192669ee4SDaniel Jasper }
31292669ee4SDaniel Jasper 
31392669ee4SDaniel Jasper ModuleMap::KnownHeader
31492669ee4SDaniel Jasper ModuleMap::findModuleForHeader(const FileEntry *File,
315306d8920SRichard Smith                                Module *RequestingModule,
316306d8920SRichard Smith                                bool IncludeTextualHeaders) {
31792669ee4SDaniel Jasper   HeadersMap::iterator Known = findKnownHeader(File);
3184eaf0a6cSDaniel Jasper 
319306d8920SRichard Smith   auto MakeResult = [&](ModuleMap::KnownHeader R) -> ModuleMap::KnownHeader {
320202210b3SRichard Smith     if (!IncludeTextualHeaders && (R.getRole() & ModuleMap::TextualHeader))
321306d8920SRichard Smith       return ModuleMap::KnownHeader();
322306d8920SRichard Smith     return R;
323306d8920SRichard Smith   };
324306d8920SRichard Smith 
3251fb5c3a6SDouglas Gregor   if (Known != Headers.end()) {
326202210b3SRichard Smith     ModuleMap::KnownHeader Result;
3271fb5c3a6SDouglas Gregor 
32897da9178SDaniel Jasper     // Iterate over all modules that 'File' is part of to find the best fit.
32997da9178SDaniel Jasper     for (SmallVectorImpl<KnownHeader>::iterator I = Known->second.begin(),
33097da9178SDaniel Jasper                                                 E = Known->second.end();
33197da9178SDaniel Jasper          I != E; ++I) {
3324eaf0a6cSDaniel Jasper       // Cannot use a module if it is unavailable.
3334eaf0a6cSDaniel Jasper       if (!I->getModule()->isAvailable())
33497da9178SDaniel Jasper         continue;
33597da9178SDaniel Jasper 
33697da9178SDaniel Jasper       // If 'File' is part of 'RequestingModule', 'RequestingModule' is the
33797da9178SDaniel Jasper       // module we are looking for.
33897da9178SDaniel Jasper       if (I->getModule() == RequestingModule)
339306d8920SRichard Smith         return MakeResult(*I);
34097da9178SDaniel Jasper 
34197da9178SDaniel Jasper       // If uses need to be specified explicitly, we are only allowed to return
34297da9178SDaniel Jasper       // modules that are explicitly used by the requesting module.
34397da9178SDaniel Jasper       if (RequestingModule && LangOpts.ModulesDeclUse &&
34492669ee4SDaniel Jasper           !directlyUses(RequestingModule, I->getModule()))
34597da9178SDaniel Jasper         continue;
3464eaf0a6cSDaniel Jasper 
347202210b3SRichard Smith       // Prefer a public header over a private header.
348202210b3SRichard Smith       if (!Result || (Result.getRole() & ModuleMap::PrivateHeader))
34997da9178SDaniel Jasper         Result = *I;
35097da9178SDaniel Jasper     }
351306d8920SRichard Smith     return MakeResult(Result);
3521fb5c3a6SDouglas Gregor   }
353ab0c8a84SDouglas Gregor 
354f857950dSDmitri Gribenko   SmallVector<const DirectoryEntry *, 2> SkippedDirs;
3554469138eSBen Langmuir   KnownHeader H = findHeaderInUmbrellaDirs(File, SkippedDirs);
3564469138eSBen Langmuir   if (H) {
3574469138eSBen Langmuir     Module *Result = H.getModule();
358930a85ccSDouglas Gregor 
359930a85ccSDouglas Gregor     // Search up the module stack until we find a module with an umbrella
36073141fa9SDouglas Gregor     // directory.
361930a85ccSDouglas Gregor     Module *UmbrellaModule = Result;
36273141fa9SDouglas Gregor     while (!UmbrellaModule->getUmbrellaDir() && UmbrellaModule->Parent)
363930a85ccSDouglas Gregor       UmbrellaModule = UmbrellaModule->Parent;
364930a85ccSDouglas Gregor 
365930a85ccSDouglas Gregor     if (UmbrellaModule->InferSubmodules) {
3669d6448b1SBen Langmuir       const FileEntry *UmbrellaModuleMap =
3679d6448b1SBen Langmuir           getModuleMapFileForUniquing(UmbrellaModule);
3689d6448b1SBen Langmuir 
369a89c5ac4SDouglas Gregor       // Infer submodules for each of the directories we found between
370a89c5ac4SDouglas Gregor       // the directory of the umbrella header and the directory where
371a89c5ac4SDouglas Gregor       // the actual header is located.
3729458f82dSDouglas Gregor       bool Explicit = UmbrellaModule->InferExplicitSubmodules;
3739458f82dSDouglas Gregor 
3747033127bSDouglas Gregor       for (unsigned I = SkippedDirs.size(); I != 0; --I) {
375a89c5ac4SDouglas Gregor         // Find or create the module that corresponds to this directory name.
376056396aeSDouglas Gregor         SmallString<32> NameBuf;
377056396aeSDouglas Gregor         StringRef Name = sanitizeFilenameAsIdentifier(
3784469138eSBen Langmuir             llvm::sys::path::stem(SkippedDirs[I-1]->getName()), NameBuf);
3799d6448b1SBen Langmuir         Result = findOrCreateModule(Name, Result, /*IsFramework=*/false,
3809d6448b1SBen Langmuir                                     Explicit).first;
3819d6448b1SBen Langmuir         InferredModuleAllowedBy[Result] = UmbrellaModuleMap;
382ffbafa2aSBen Langmuir         Result->IsInferred = true;
383a89c5ac4SDouglas Gregor 
384a89c5ac4SDouglas Gregor         // Associate the module and the directory.
385a89c5ac4SDouglas Gregor         UmbrellaDirs[SkippedDirs[I-1]] = Result;
386a89c5ac4SDouglas Gregor 
387a89c5ac4SDouglas Gregor         // If inferred submodules export everything they import, add a
388a89c5ac4SDouglas Gregor         // wildcard to the set of exports.
389930a85ccSDouglas Gregor         if (UmbrellaModule->InferExportWildcard && Result->Exports.empty())
390d2d442caSCraig Topper           Result->Exports.push_back(Module::ExportDecl(nullptr, true));
391a89c5ac4SDouglas Gregor       }
392a89c5ac4SDouglas Gregor 
393a89c5ac4SDouglas Gregor       // Infer a submodule with the same name as this header file.
394056396aeSDouglas Gregor       SmallString<32> NameBuf;
395056396aeSDouglas Gregor       StringRef Name = sanitizeFilenameAsIdentifier(
396056396aeSDouglas Gregor                          llvm::sys::path::stem(File->getName()), NameBuf);
3979d6448b1SBen Langmuir       Result = findOrCreateModule(Name, Result, /*IsFramework=*/false,
3989d6448b1SBen Langmuir                                   Explicit).first;
3999d6448b1SBen Langmuir       InferredModuleAllowedBy[Result] = UmbrellaModuleMap;
400ffbafa2aSBen Langmuir       Result->IsInferred = true;
4013c5305c1SArgyrios Kyrtzidis       Result->addTopHeader(File);
402a89c5ac4SDouglas Gregor 
403a89c5ac4SDouglas Gregor       // If inferred submodules export everything they import, add a
404a89c5ac4SDouglas Gregor       // wildcard to the set of exports.
405930a85ccSDouglas Gregor       if (UmbrellaModule->InferExportWildcard && Result->Exports.empty())
406d2d442caSCraig Topper         Result->Exports.push_back(Module::ExportDecl(nullptr, true));
407a89c5ac4SDouglas Gregor     } else {
408a89c5ac4SDouglas Gregor       // Record each of the directories we stepped through as being part of
409a89c5ac4SDouglas Gregor       // the module we found, since the umbrella header covers them all.
410a89c5ac4SDouglas Gregor       for (unsigned I = 0, N = SkippedDirs.size(); I != N; ++I)
411a89c5ac4SDouglas Gregor         UmbrellaDirs[SkippedDirs[I]] = Result;
412a89c5ac4SDouglas Gregor     }
413a89c5ac4SDouglas Gregor 
41497da9178SDaniel Jasper     Headers[File].push_back(KnownHeader(Result, NormalHeader));
4151fb5c3a6SDouglas Gregor 
4161fb5c3a6SDouglas Gregor     // If a header corresponds to an unavailable module, don't report
4171fb5c3a6SDouglas Gregor     // that it maps to anything.
4181fb5c3a6SDouglas Gregor     if (!Result->isAvailable())
419b53e5483SLawrence Crowl       return KnownHeader();
4201fb5c3a6SDouglas Gregor 
421306d8920SRichard Smith     return MakeResult(Headers[File].back());
422a89c5ac4SDouglas Gregor   }
423a89c5ac4SDouglas Gregor 
424b53e5483SLawrence Crowl   return KnownHeader();
425ab0c8a84SDouglas Gregor }
426ab0c8a84SDouglas Gregor 
427e4412640SArgyrios Kyrtzidis bool ModuleMap::isHeaderInUnavailableModule(const FileEntry *Header) const {
428d2d442caSCraig Topper   return isHeaderUnavailableInModule(Header, nullptr);
42950996ce1SRichard Smith }
43050996ce1SRichard Smith 
43162bcd925SDmitri Gribenko bool
43262bcd925SDmitri Gribenko ModuleMap::isHeaderUnavailableInModule(const FileEntry *Header,
43362bcd925SDmitri Gribenko                                        const Module *RequestingModule) const {
434e4412640SArgyrios Kyrtzidis   HeadersMap::const_iterator Known = Headers.find(Header);
43597da9178SDaniel Jasper   if (Known != Headers.end()) {
43697da9178SDaniel Jasper     for (SmallVectorImpl<KnownHeader>::const_iterator
43797da9178SDaniel Jasper              I = Known->second.begin(),
43897da9178SDaniel Jasper              E = Known->second.end();
43997da9178SDaniel Jasper          I != E; ++I) {
44050996ce1SRichard Smith       if (I->isAvailable() && (!RequestingModule ||
44150996ce1SRichard Smith                                I->getModule()->isSubModuleOf(RequestingModule)))
44297da9178SDaniel Jasper         return false;
44397da9178SDaniel Jasper     }
44497da9178SDaniel Jasper     return true;
44597da9178SDaniel Jasper   }
4461fb5c3a6SDouglas Gregor 
4471fb5c3a6SDouglas Gregor   const DirectoryEntry *Dir = Header->getDir();
448f857950dSDmitri Gribenko   SmallVector<const DirectoryEntry *, 2> SkippedDirs;
4491fb5c3a6SDouglas Gregor   StringRef DirName = Dir->getName();
4501fb5c3a6SDouglas Gregor 
45150996ce1SRichard Smith   auto IsUnavailable = [&](const Module *M) {
45250996ce1SRichard Smith     return !M->isAvailable() && (!RequestingModule ||
45350996ce1SRichard Smith                                  M->isSubModuleOf(RequestingModule));
45450996ce1SRichard Smith   };
45550996ce1SRichard Smith 
4561fb5c3a6SDouglas Gregor   // Keep walking up the directory hierarchy, looking for a directory with
4571fb5c3a6SDouglas Gregor   // an umbrella header.
4581fb5c3a6SDouglas Gregor   do {
459e4412640SArgyrios Kyrtzidis     llvm::DenseMap<const DirectoryEntry *, Module *>::const_iterator KnownDir
4601fb5c3a6SDouglas Gregor       = UmbrellaDirs.find(Dir);
4611fb5c3a6SDouglas Gregor     if (KnownDir != UmbrellaDirs.end()) {
4621fb5c3a6SDouglas Gregor       Module *Found = KnownDir->second;
46350996ce1SRichard Smith       if (IsUnavailable(Found))
4641fb5c3a6SDouglas Gregor         return true;
4651fb5c3a6SDouglas Gregor 
4661fb5c3a6SDouglas Gregor       // Search up the module stack until we find a module with an umbrella
4671fb5c3a6SDouglas Gregor       // directory.
4681fb5c3a6SDouglas Gregor       Module *UmbrellaModule = Found;
4691fb5c3a6SDouglas Gregor       while (!UmbrellaModule->getUmbrellaDir() && UmbrellaModule->Parent)
4701fb5c3a6SDouglas Gregor         UmbrellaModule = UmbrellaModule->Parent;
4711fb5c3a6SDouglas Gregor 
4721fb5c3a6SDouglas Gregor       if (UmbrellaModule->InferSubmodules) {
4731fb5c3a6SDouglas Gregor         for (unsigned I = SkippedDirs.size(); I != 0; --I) {
4741fb5c3a6SDouglas Gregor           // Find or create the module that corresponds to this directory name.
475056396aeSDouglas Gregor           SmallString<32> NameBuf;
476056396aeSDouglas Gregor           StringRef Name = sanitizeFilenameAsIdentifier(
477056396aeSDouglas Gregor                              llvm::sys::path::stem(SkippedDirs[I-1]->getName()),
478056396aeSDouglas Gregor                              NameBuf);
4791fb5c3a6SDouglas Gregor           Found = lookupModuleQualified(Name, Found);
4801fb5c3a6SDouglas Gregor           if (!Found)
4811fb5c3a6SDouglas Gregor             return false;
48250996ce1SRichard Smith           if (IsUnavailable(Found))
4831fb5c3a6SDouglas Gregor             return true;
4841fb5c3a6SDouglas Gregor         }
4851fb5c3a6SDouglas Gregor 
4861fb5c3a6SDouglas Gregor         // Infer a submodule with the same name as this header file.
487056396aeSDouglas Gregor         SmallString<32> NameBuf;
488056396aeSDouglas Gregor         StringRef Name = sanitizeFilenameAsIdentifier(
489056396aeSDouglas Gregor                            llvm::sys::path::stem(Header->getName()),
490056396aeSDouglas Gregor                            NameBuf);
4911fb5c3a6SDouglas Gregor         Found = lookupModuleQualified(Name, Found);
4921fb5c3a6SDouglas Gregor         if (!Found)
4931fb5c3a6SDouglas Gregor           return false;
4941fb5c3a6SDouglas Gregor       }
4951fb5c3a6SDouglas Gregor 
49650996ce1SRichard Smith       return IsUnavailable(Found);
4971fb5c3a6SDouglas Gregor     }
4981fb5c3a6SDouglas Gregor 
4991fb5c3a6SDouglas Gregor     SkippedDirs.push_back(Dir);
5001fb5c3a6SDouglas Gregor 
5011fb5c3a6SDouglas Gregor     // Retrieve our parent path.
5021fb5c3a6SDouglas Gregor     DirName = llvm::sys::path::parent_path(DirName);
5031fb5c3a6SDouglas Gregor     if (DirName.empty())
5041fb5c3a6SDouglas Gregor       break;
5051fb5c3a6SDouglas Gregor 
5061fb5c3a6SDouglas Gregor     // Resolve the parent path to a directory entry.
5071f76c4e8SManuel Klimek     Dir = SourceMgr.getFileManager().getDirectory(DirName);
5081fb5c3a6SDouglas Gregor   } while (Dir);
5091fb5c3a6SDouglas Gregor 
5101fb5c3a6SDouglas Gregor   return false;
5111fb5c3a6SDouglas Gregor }
5121fb5c3a6SDouglas Gregor 
513e4412640SArgyrios Kyrtzidis Module *ModuleMap::findModule(StringRef Name) const {
514e4412640SArgyrios Kyrtzidis   llvm::StringMap<Module *>::const_iterator Known = Modules.find(Name);
51588bdfb0eSDouglas Gregor   if (Known != Modules.end())
51688bdfb0eSDouglas Gregor     return Known->getValue();
51788bdfb0eSDouglas Gregor 
518d2d442caSCraig Topper   return nullptr;
51988bdfb0eSDouglas Gregor }
52088bdfb0eSDouglas Gregor 
521e4412640SArgyrios Kyrtzidis Module *ModuleMap::lookupModuleUnqualified(StringRef Name,
522e4412640SArgyrios Kyrtzidis                                            Module *Context) const {
5232b82c2a5SDouglas Gregor   for(; Context; Context = Context->Parent) {
5242b82c2a5SDouglas Gregor     if (Module *Sub = lookupModuleQualified(Name, Context))
5252b82c2a5SDouglas Gregor       return Sub;
5262b82c2a5SDouglas Gregor   }
5272b82c2a5SDouglas Gregor 
5282b82c2a5SDouglas Gregor   return findModule(Name);
5292b82c2a5SDouglas Gregor }
5302b82c2a5SDouglas Gregor 
531e4412640SArgyrios Kyrtzidis Module *ModuleMap::lookupModuleQualified(StringRef Name, Module *Context) const{
5322b82c2a5SDouglas Gregor   if (!Context)
5332b82c2a5SDouglas Gregor     return findModule(Name);
5342b82c2a5SDouglas Gregor 
535eb90e830SDouglas Gregor   return Context->findSubmodule(Name);
5362b82c2a5SDouglas Gregor }
5372b82c2a5SDouglas Gregor 
538de3ef502SDouglas Gregor std::pair<Module *, bool>
5399d6448b1SBen Langmuir ModuleMap::findOrCreateModule(StringRef Name, Module *Parent, bool IsFramework,
54069021974SDouglas Gregor                               bool IsExplicit) {
54169021974SDouglas Gregor   // Try to find an existing module with this name.
542eb90e830SDouglas Gregor   if (Module *Sub = lookupModuleQualified(Name, Parent))
543eb90e830SDouglas Gregor     return std::make_pair(Sub, false);
54469021974SDouglas Gregor 
54569021974SDouglas Gregor   // Create a new module with this name.
5469d6448b1SBen Langmuir   Module *Result = new Module(Name, SourceLocation(), Parent,
547beee15e7SBen Langmuir                               IsFramework, IsExplicit);
548ba7f2f71SDaniel Jasper   if (LangOpts.CurrentModule == Name) {
549ba7f2f71SDaniel Jasper     SourceModule = Result;
550ba7f2f71SDaniel Jasper     SourceModuleName = Name;
551ba7f2f71SDaniel Jasper   }
5526f722b4eSArgyrios Kyrtzidis   if (!Parent) {
55369021974SDouglas Gregor     Modules[Name] = Result;
5546f722b4eSArgyrios Kyrtzidis     if (!LangOpts.CurrentModule.empty() && !CompilingModule &&
5556f722b4eSArgyrios Kyrtzidis         Name == LangOpts.CurrentModule) {
5566f722b4eSArgyrios Kyrtzidis       CompilingModule = Result;
5576f722b4eSArgyrios Kyrtzidis     }
5586f722b4eSArgyrios Kyrtzidis   }
55969021974SDouglas Gregor   return std::make_pair(Result, true);
56069021974SDouglas Gregor }
56169021974SDouglas Gregor 
5629194a91dSDouglas Gregor bool ModuleMap::canInferFrameworkModule(const DirectoryEntry *ParentDir,
563e4412640SArgyrios Kyrtzidis                                         StringRef Name, bool &IsSystem) const {
5649194a91dSDouglas Gregor   // Check whether we have already looked into the parent directory
5659194a91dSDouglas Gregor   // for a module map.
566e4412640SArgyrios Kyrtzidis   llvm::DenseMap<const DirectoryEntry *, InferredDirectory>::const_iterator
5679194a91dSDouglas Gregor     inferred = InferredDirectories.find(ParentDir);
5689194a91dSDouglas Gregor   if (inferred == InferredDirectories.end())
5699194a91dSDouglas Gregor     return false;
5709194a91dSDouglas Gregor 
5719194a91dSDouglas Gregor   if (!inferred->second.InferModules)
5729194a91dSDouglas Gregor     return false;
5739194a91dSDouglas Gregor 
5749194a91dSDouglas Gregor   // We're allowed to infer for this directory, but make sure it's okay
5759194a91dSDouglas Gregor   // to infer this particular module.
5769194a91dSDouglas Gregor   bool canInfer = std::find(inferred->second.ExcludedModules.begin(),
5779194a91dSDouglas Gregor                             inferred->second.ExcludedModules.end(),
5789194a91dSDouglas Gregor                             Name) == inferred->second.ExcludedModules.end();
5799194a91dSDouglas Gregor 
5809194a91dSDouglas Gregor   if (canInfer && inferred->second.InferSystemModules)
5819194a91dSDouglas Gregor     IsSystem = true;
5829194a91dSDouglas Gregor 
5839194a91dSDouglas Gregor   return canInfer;
5849194a91dSDouglas Gregor }
5859194a91dSDouglas Gregor 
58611dfe6feSDouglas Gregor /// \brief For a framework module, infer the framework against which we
58711dfe6feSDouglas Gregor /// should link.
58811dfe6feSDouglas Gregor static void inferFrameworkLink(Module *Mod, const DirectoryEntry *FrameworkDir,
58911dfe6feSDouglas Gregor                                FileManager &FileMgr) {
59011dfe6feSDouglas Gregor   assert(Mod->IsFramework && "Can only infer linking for framework modules");
59111dfe6feSDouglas Gregor   assert(!Mod->isSubFramework() &&
59211dfe6feSDouglas Gregor          "Can only infer linking for top-level frameworks");
59311dfe6feSDouglas Gregor 
59411dfe6feSDouglas Gregor   SmallString<128> LibName;
59511dfe6feSDouglas Gregor   LibName += FrameworkDir->getName();
59611dfe6feSDouglas Gregor   llvm::sys::path::append(LibName, Mod->Name);
59711dfe6feSDouglas Gregor   if (FileMgr.getFile(LibName)) {
59811dfe6feSDouglas Gregor     Mod->LinkLibraries.push_back(Module::LinkLibrary(Mod->Name,
59911dfe6feSDouglas Gregor                                                      /*IsFramework=*/true));
60011dfe6feSDouglas Gregor   }
60111dfe6feSDouglas Gregor }
60211dfe6feSDouglas Gregor 
603de3ef502SDouglas Gregor Module *
60456c64013SDouglas Gregor ModuleMap::inferFrameworkModule(StringRef ModuleName,
605e89dbc1dSDouglas Gregor                                 const DirectoryEntry *FrameworkDir,
606a686e1b0SDouglas Gregor                                 bool IsSystem,
607e89dbc1dSDouglas Gregor                                 Module *Parent) {
60856c64013SDouglas Gregor   // Check whether we've already found this module.
609e89dbc1dSDouglas Gregor   if (Module *Mod = lookupModuleQualified(ModuleName, Parent))
610e89dbc1dSDouglas Gregor     return Mod;
611e89dbc1dSDouglas Gregor 
6121f76c4e8SManuel Klimek   FileManager &FileMgr = SourceMgr.getFileManager();
61356c64013SDouglas Gregor 
6149194a91dSDouglas Gregor   // If the framework has a parent path from which we're allowed to infer
6159194a91dSDouglas Gregor   // a framework module, do so.
616beee15e7SBen Langmuir   const FileEntry *ModuleMapFile = nullptr;
6179194a91dSDouglas Gregor   if (!Parent) {
6184ddf2221SDouglas Gregor     // Determine whether we're allowed to infer a module map.
619e00c8b20SDouglas Gregor 
6204ddf2221SDouglas Gregor     // Note: as an egregious but useful hack we use the real path here, because
6214ddf2221SDouglas Gregor     // we might be looking at an embedded framework that symlinks out to a
6224ddf2221SDouglas Gregor     // top-level framework, and we need to infer as if we were naming the
6234ddf2221SDouglas Gregor     // top-level framework.
624e00c8b20SDouglas Gregor     StringRef FrameworkDirName
6251f76c4e8SManuel Klimek       = SourceMgr.getFileManager().getCanonicalName(FrameworkDir);
6264ddf2221SDouglas Gregor 
6276b7f7345SBen Langmuir     // In case this is a case-insensitive filesystem, make sure the canonical
6286b7f7345SBen Langmuir     // directory name matches ModuleName exactly. Modules are case-sensitive.
6296b7f7345SBen Langmuir     // FIXME: we should be able to give a fix-it hint for the correct spelling.
6306b7f7345SBen Langmuir     if (llvm::sys::path::stem(FrameworkDirName) != ModuleName)
6316b7f7345SBen Langmuir       return nullptr;
6326b7f7345SBen Langmuir 
6339194a91dSDouglas Gregor     bool canInfer = false;
6344ddf2221SDouglas Gregor     if (llvm::sys::path::has_parent_path(FrameworkDirName)) {
6359194a91dSDouglas Gregor       // Figure out the parent path.
6364ddf2221SDouglas Gregor       StringRef Parent = llvm::sys::path::parent_path(FrameworkDirName);
6379194a91dSDouglas Gregor       if (const DirectoryEntry *ParentDir = FileMgr.getDirectory(Parent)) {
6389194a91dSDouglas Gregor         // Check whether we have already looked into the parent directory
6399194a91dSDouglas Gregor         // for a module map.
640e4412640SArgyrios Kyrtzidis         llvm::DenseMap<const DirectoryEntry *, InferredDirectory>::const_iterator
6419194a91dSDouglas Gregor           inferred = InferredDirectories.find(ParentDir);
6429194a91dSDouglas Gregor         if (inferred == InferredDirectories.end()) {
6439194a91dSDouglas Gregor           // We haven't looked here before. Load a module map, if there is
6449194a91dSDouglas Gregor           // one.
645984e1df7SBen Langmuir           bool IsFrameworkDir = Parent.endswith(".framework");
646984e1df7SBen Langmuir           if (const FileEntry *ModMapFile =
647984e1df7SBen Langmuir                 HeaderInfo.lookupModuleMapFile(ParentDir, IsFrameworkDir)) {
648963c5535SDouglas Gregor             parseModuleMapFile(ModMapFile, IsSystem);
6499194a91dSDouglas Gregor             inferred = InferredDirectories.find(ParentDir);
6509194a91dSDouglas Gregor           }
6519194a91dSDouglas Gregor 
6529194a91dSDouglas Gregor           if (inferred == InferredDirectories.end())
6539194a91dSDouglas Gregor             inferred = InferredDirectories.insert(
6549194a91dSDouglas Gregor                          std::make_pair(ParentDir, InferredDirectory())).first;
6559194a91dSDouglas Gregor         }
6569194a91dSDouglas Gregor 
6579194a91dSDouglas Gregor         if (inferred->second.InferModules) {
6589194a91dSDouglas Gregor           // We're allowed to infer for this directory, but make sure it's okay
6599194a91dSDouglas Gregor           // to infer this particular module.
6604ddf2221SDouglas Gregor           StringRef Name = llvm::sys::path::stem(FrameworkDirName);
6619194a91dSDouglas Gregor           canInfer = std::find(inferred->second.ExcludedModules.begin(),
6629194a91dSDouglas Gregor                                inferred->second.ExcludedModules.end(),
6639194a91dSDouglas Gregor                                Name) == inferred->second.ExcludedModules.end();
6649194a91dSDouglas Gregor 
6659194a91dSDouglas Gregor           if (inferred->second.InferSystemModules)
6669194a91dSDouglas Gregor             IsSystem = true;
667beee15e7SBen Langmuir           ModuleMapFile = inferred->second.ModuleMapFile;
6689194a91dSDouglas Gregor         }
6699194a91dSDouglas Gregor       }
6709194a91dSDouglas Gregor     }
6719194a91dSDouglas Gregor 
6729194a91dSDouglas Gregor     // If we're not allowed to infer a framework module, don't.
6739194a91dSDouglas Gregor     if (!canInfer)
674d2d442caSCraig Topper       return nullptr;
675beee15e7SBen Langmuir   } else
6769d6448b1SBen Langmuir     ModuleMapFile = getModuleMapFileForUniquing(Parent);
6779194a91dSDouglas Gregor 
6789194a91dSDouglas Gregor 
67956c64013SDouglas Gregor   // Look for an umbrella header.
6802c1dd271SDylan Noblesmith   SmallString<128> UmbrellaName = StringRef(FrameworkDir->getName());
68117381a06SBenjamin Kramer   llvm::sys::path::append(UmbrellaName, "Headers", ModuleName + ".h");
682e89dbc1dSDouglas Gregor   const FileEntry *UmbrellaHeader = FileMgr.getFile(UmbrellaName);
68356c64013SDouglas Gregor 
68456c64013SDouglas Gregor   // FIXME: If there's no umbrella header, we could probably scan the
68556c64013SDouglas Gregor   // framework to load *everything*. But, it's not clear that this is a good
68656c64013SDouglas Gregor   // idea.
68756c64013SDouglas Gregor   if (!UmbrellaHeader)
688d2d442caSCraig Topper     return nullptr;
68956c64013SDouglas Gregor 
6909d6448b1SBen Langmuir   Module *Result = new Module(ModuleName, SourceLocation(), Parent,
691e89dbc1dSDouglas Gregor                               /*IsFramework=*/true, /*IsExplicit=*/false);
6929d6448b1SBen Langmuir   InferredModuleAllowedBy[Result] = ModuleMapFile;
6939d6448b1SBen Langmuir   Result->IsInferred = true;
694ba7f2f71SDaniel Jasper   if (LangOpts.CurrentModule == ModuleName) {
695ba7f2f71SDaniel Jasper     SourceModule = Result;
696ba7f2f71SDaniel Jasper     SourceModuleName = ModuleName;
697ba7f2f71SDaniel Jasper   }
698a686e1b0SDouglas Gregor   if (IsSystem)
699a686e1b0SDouglas Gregor     Result->IsSystem = IsSystem;
700a686e1b0SDouglas Gregor 
701eb90e830SDouglas Gregor   if (!Parent)
702e89dbc1dSDouglas Gregor     Modules[ModuleName] = Result;
703e89dbc1dSDouglas Gregor 
704322f633cSDouglas Gregor   // umbrella header "umbrella-header-name"
70573141fa9SDouglas Gregor   Result->Umbrella = UmbrellaHeader;
70697da9178SDaniel Jasper   Headers[UmbrellaHeader].push_back(KnownHeader(Result, NormalHeader));
7074dc71835SDouglas Gregor   UmbrellaDirs[UmbrellaHeader->getDir()] = Result;
708d8bd7537SDouglas Gregor 
709d8bd7537SDouglas Gregor   // export *
710d2d442caSCraig Topper   Result->Exports.push_back(Module::ExportDecl(nullptr, true));
711d8bd7537SDouglas Gregor 
712a89c5ac4SDouglas Gregor   // module * { export * }
713a89c5ac4SDouglas Gregor   Result->InferSubmodules = true;
714a89c5ac4SDouglas Gregor   Result->InferExportWildcard = true;
715a89c5ac4SDouglas Gregor 
716e89dbc1dSDouglas Gregor   // Look for subframeworks.
717c080917eSRafael Espindola   std::error_code EC;
7182c1dd271SDylan Noblesmith   SmallString<128> SubframeworksDirName
719ddaa69cbSDouglas Gregor     = StringRef(FrameworkDir->getName());
720e89dbc1dSDouglas Gregor   llvm::sys::path::append(SubframeworksDirName, "Frameworks");
7212d4d8cb3SBenjamin Kramer   llvm::sys::path::native(SubframeworksDirName);
722ddaa69cbSDouglas Gregor   for (llvm::sys::fs::directory_iterator
7232d4d8cb3SBenjamin Kramer          Dir(SubframeworksDirName.str(), EC), DirEnd;
724e89dbc1dSDouglas Gregor        Dir != DirEnd && !EC; Dir.increment(EC)) {
725e89dbc1dSDouglas Gregor     if (!StringRef(Dir->path()).endswith(".framework"))
726e89dbc1dSDouglas Gregor       continue;
727f2161a70SDouglas Gregor 
728e89dbc1dSDouglas Gregor     if (const DirectoryEntry *SubframeworkDir
729e89dbc1dSDouglas Gregor           = FileMgr.getDirectory(Dir->path())) {
73007c22b78SDouglas Gregor       // Note: as an egregious but useful hack, we use the real path here and
73107c22b78SDouglas Gregor       // check whether it is actually a subdirectory of the parent directory.
73207c22b78SDouglas Gregor       // This will not be the case if the 'subframework' is actually a symlink
73307c22b78SDouglas Gregor       // out to a top-level framework.
734e00c8b20SDouglas Gregor       StringRef SubframeworkDirName = FileMgr.getCanonicalName(SubframeworkDir);
73507c22b78SDouglas Gregor       bool FoundParent = false;
73607c22b78SDouglas Gregor       do {
73707c22b78SDouglas Gregor         // Get the parent directory name.
73807c22b78SDouglas Gregor         SubframeworkDirName
73907c22b78SDouglas Gregor           = llvm::sys::path::parent_path(SubframeworkDirName);
74007c22b78SDouglas Gregor         if (SubframeworkDirName.empty())
74107c22b78SDouglas Gregor           break;
74207c22b78SDouglas Gregor 
74307c22b78SDouglas Gregor         if (FileMgr.getDirectory(SubframeworkDirName) == FrameworkDir) {
74407c22b78SDouglas Gregor           FoundParent = true;
74507c22b78SDouglas Gregor           break;
74607c22b78SDouglas Gregor         }
74707c22b78SDouglas Gregor       } while (true);
74807c22b78SDouglas Gregor 
74907c22b78SDouglas Gregor       if (!FoundParent)
75007c22b78SDouglas Gregor         continue;
75107c22b78SDouglas Gregor 
752e89dbc1dSDouglas Gregor       // FIXME: Do we want to warn about subframeworks without umbrella headers?
753056396aeSDouglas Gregor       SmallString<32> NameBuf;
754056396aeSDouglas Gregor       inferFrameworkModule(sanitizeFilenameAsIdentifier(
755056396aeSDouglas Gregor                              llvm::sys::path::stem(Dir->path()), NameBuf),
756056396aeSDouglas Gregor                            SubframeworkDir, IsSystem, Result);
757e89dbc1dSDouglas Gregor     }
758e89dbc1dSDouglas Gregor   }
759e89dbc1dSDouglas Gregor 
76011dfe6feSDouglas Gregor   // If the module is a top-level framework, automatically link against the
76111dfe6feSDouglas Gregor   // framework.
76211dfe6feSDouglas Gregor   if (!Result->isSubFramework()) {
76311dfe6feSDouglas Gregor     inferFrameworkLink(Result, FrameworkDir, FileMgr);
76411dfe6feSDouglas Gregor   }
76511dfe6feSDouglas Gregor 
76656c64013SDouglas Gregor   return Result;
76756c64013SDouglas Gregor }
76856c64013SDouglas Gregor 
769a89c5ac4SDouglas Gregor void ModuleMap::setUmbrellaHeader(Module *Mod, const FileEntry *UmbrellaHeader){
77097da9178SDaniel Jasper   Headers[UmbrellaHeader].push_back(KnownHeader(Mod, NormalHeader));
77173141fa9SDouglas Gregor   Mod->Umbrella = UmbrellaHeader;
7727033127bSDouglas Gregor   UmbrellaDirs[UmbrellaHeader->getDir()] = Mod;
773a89c5ac4SDouglas Gregor }
774a89c5ac4SDouglas Gregor 
775524e33e1SDouglas Gregor void ModuleMap::setUmbrellaDir(Module *Mod, const DirectoryEntry *UmbrellaDir) {
776524e33e1SDouglas Gregor   Mod->Umbrella = UmbrellaDir;
777524e33e1SDouglas Gregor   UmbrellaDirs[UmbrellaDir] = Mod;
778524e33e1SDouglas Gregor }
779524e33e1SDouglas Gregor 
78059527666SDouglas Gregor void ModuleMap::addHeader(Module *Mod, const FileEntry *Header,
781b53e5483SLawrence Crowl                           ModuleHeaderRole Role) {
7820e98d938SNAKAMURA Takumi   switch ((int)Role) {
7830e98d938SNAKAMURA Takumi   default:
7840e98d938SNAKAMURA Takumi     llvm_unreachable("unknown header role");
7850e98d938SNAKAMURA Takumi   case NormalHeader:
7860e98d938SNAKAMURA Takumi     Mod->NormalHeaders.push_back(Header);
7870e98d938SNAKAMURA Takumi     break;
7880e98d938SNAKAMURA Takumi   case PrivateHeader:
7890e98d938SNAKAMURA Takumi     Mod->PrivateHeaders.push_back(Header);
7900e98d938SNAKAMURA Takumi     break;
7910e98d938SNAKAMURA Takumi   case TextualHeader:
7920e98d938SNAKAMURA Takumi     Mod->TextualHeaders.push_back(Header);
7930e98d938SNAKAMURA Takumi     break;
7940e98d938SNAKAMURA Takumi   case PrivateHeader | TextualHeader:
7950e98d938SNAKAMURA Takumi     Mod->PrivateTextualHeaders.push_back(Header);
7960e98d938SNAKAMURA Takumi     break;
7970e98d938SNAKAMURA Takumi   }
798202210b3SRichard Smith 
799202210b3SRichard Smith   if (!(Role & TextualHeader)) {
8006f722b4eSArgyrios Kyrtzidis     bool isCompilingModuleHeader = Mod->getTopLevelModule() == CompilingModule;
801b53e5483SLawrence Crowl     HeaderInfo.MarkFileModuleHeader(Header, Role, isCompilingModuleHeader);
802b146baabSArgyrios Kyrtzidis   }
80397da9178SDaniel Jasper   Headers[Header].push_back(KnownHeader(Mod, Role));
804a89c5ac4SDouglas Gregor }
805a89c5ac4SDouglas Gregor 
806feb54b6dSRichard Smith void ModuleMap::excludeHeader(Module *Mod, const FileEntry *Header) {
807feb54b6dSRichard Smith   Mod->ExcludedHeaders.push_back(Header);
808feb54b6dSRichard Smith 
809feb54b6dSRichard Smith   // Add this as a known header so we won't implicitly add it to any
810feb54b6dSRichard Smith   // umbrella directory module.
811feb54b6dSRichard Smith   // FIXME: Should we only exclude it from umbrella modules within the
812feb54b6dSRichard Smith   // specified module?
813feb54b6dSRichard Smith   (void) Headers[Header];
814feb54b6dSRichard Smith }
815feb54b6dSRichard Smith 
816514b636aSDouglas Gregor const FileEntry *
8174b8a9e95SBen Langmuir ModuleMap::getContainingModuleMapFile(const Module *Module) const {
8181f76c4e8SManuel Klimek   if (Module->DefinitionLoc.isInvalid())
819d2d442caSCraig Topper     return nullptr;
820514b636aSDouglas Gregor 
8211f76c4e8SManuel Klimek   return SourceMgr.getFileEntryForID(
8221f76c4e8SManuel Klimek            SourceMgr.getFileID(Module->DefinitionLoc));
823514b636aSDouglas Gregor }
824514b636aSDouglas Gregor 
8254b8a9e95SBen Langmuir const FileEntry *ModuleMap::getModuleMapFileForUniquing(const Module *M) const {
8269d6448b1SBen Langmuir   if (M->IsInferred) {
8279d6448b1SBen Langmuir     assert(InferredModuleAllowedBy.count(M) && "missing inferred module map");
8289d6448b1SBen Langmuir     return InferredModuleAllowedBy.find(M)->second;
8299d6448b1SBen Langmuir   }
8309d6448b1SBen Langmuir   return getContainingModuleMapFile(M);
8319d6448b1SBen Langmuir }
8329d6448b1SBen Langmuir 
8339d6448b1SBen Langmuir void ModuleMap::setInferredModuleAllowedBy(Module *M, const FileEntry *ModMap) {
8349d6448b1SBen Langmuir   assert(M->IsInferred && "module not inferred");
8359d6448b1SBen Langmuir   InferredModuleAllowedBy[M] = ModMap;
8369d6448b1SBen Langmuir }
8379d6448b1SBen Langmuir 
838718292f2SDouglas Gregor void ModuleMap::dump() {
839718292f2SDouglas Gregor   llvm::errs() << "Modules:";
840718292f2SDouglas Gregor   for (llvm::StringMap<Module *>::iterator M = Modules.begin(),
841718292f2SDouglas Gregor                                         MEnd = Modules.end();
842718292f2SDouglas Gregor        M != MEnd; ++M)
843d28d1b8dSDouglas Gregor     M->getValue()->print(llvm::errs(), 2);
844718292f2SDouglas Gregor 
845718292f2SDouglas Gregor   llvm::errs() << "Headers:";
84659527666SDouglas Gregor   for (HeadersMap::iterator H = Headers.begin(), HEnd = Headers.end();
847718292f2SDouglas Gregor        H != HEnd; ++H) {
84897da9178SDaniel Jasper     llvm::errs() << "  \"" << H->first->getName() << "\" -> ";
84997da9178SDaniel Jasper     for (SmallVectorImpl<KnownHeader>::const_iterator I = H->second.begin(),
85097da9178SDaniel Jasper                                                       E = H->second.end();
85197da9178SDaniel Jasper          I != E; ++I) {
85297da9178SDaniel Jasper       if (I != H->second.begin())
85397da9178SDaniel Jasper         llvm::errs() << ",";
85497da9178SDaniel Jasper       llvm::errs() << I->getModule()->getFullModuleName();
85597da9178SDaniel Jasper     }
85697da9178SDaniel Jasper     llvm::errs() << "\n";
857718292f2SDouglas Gregor   }
858718292f2SDouglas Gregor }
859718292f2SDouglas Gregor 
8602b82c2a5SDouglas Gregor bool ModuleMap::resolveExports(Module *Mod, bool Complain) {
8612b82c2a5SDouglas Gregor   bool HadError = false;
8622b82c2a5SDouglas Gregor   for (unsigned I = 0, N = Mod->UnresolvedExports.size(); I != N; ++I) {
8632b82c2a5SDouglas Gregor     Module::ExportDecl Export = resolveExport(Mod, Mod->UnresolvedExports[I],
8642b82c2a5SDouglas Gregor                                               Complain);
865f5eedd05SDouglas Gregor     if (Export.getPointer() || Export.getInt())
8662b82c2a5SDouglas Gregor       Mod->Exports.push_back(Export);
8672b82c2a5SDouglas Gregor     else
8682b82c2a5SDouglas Gregor       HadError = true;
8692b82c2a5SDouglas Gregor   }
8702b82c2a5SDouglas Gregor   Mod->UnresolvedExports.clear();
8712b82c2a5SDouglas Gregor   return HadError;
8722b82c2a5SDouglas Gregor }
8732b82c2a5SDouglas Gregor 
874ba7f2f71SDaniel Jasper bool ModuleMap::resolveUses(Module *Mod, bool Complain) {
875ba7f2f71SDaniel Jasper   bool HadError = false;
876ba7f2f71SDaniel Jasper   for (unsigned I = 0, N = Mod->UnresolvedDirectUses.size(); I != N; ++I) {
877ba7f2f71SDaniel Jasper     Module *DirectUse =
878ba7f2f71SDaniel Jasper         resolveModuleId(Mod->UnresolvedDirectUses[I], Mod, Complain);
879ba7f2f71SDaniel Jasper     if (DirectUse)
880ba7f2f71SDaniel Jasper       Mod->DirectUses.push_back(DirectUse);
881ba7f2f71SDaniel Jasper     else
882ba7f2f71SDaniel Jasper       HadError = true;
883ba7f2f71SDaniel Jasper   }
884ba7f2f71SDaniel Jasper   Mod->UnresolvedDirectUses.clear();
885ba7f2f71SDaniel Jasper   return HadError;
886ba7f2f71SDaniel Jasper }
887ba7f2f71SDaniel Jasper 
888fb912657SDouglas Gregor bool ModuleMap::resolveConflicts(Module *Mod, bool Complain) {
889fb912657SDouglas Gregor   bool HadError = false;
890fb912657SDouglas Gregor   for (unsigned I = 0, N = Mod->UnresolvedConflicts.size(); I != N; ++I) {
891fb912657SDouglas Gregor     Module *OtherMod = resolveModuleId(Mod->UnresolvedConflicts[I].Id,
892fb912657SDouglas Gregor                                        Mod, Complain);
893fb912657SDouglas Gregor     if (!OtherMod) {
894fb912657SDouglas Gregor       HadError = true;
895fb912657SDouglas Gregor       continue;
896fb912657SDouglas Gregor     }
897fb912657SDouglas Gregor 
898fb912657SDouglas Gregor     Module::Conflict Conflict;
899fb912657SDouglas Gregor     Conflict.Other = OtherMod;
900fb912657SDouglas Gregor     Conflict.Message = Mod->UnresolvedConflicts[I].Message;
901fb912657SDouglas Gregor     Mod->Conflicts.push_back(Conflict);
902fb912657SDouglas Gregor   }
903fb912657SDouglas Gregor   Mod->UnresolvedConflicts.clear();
904fb912657SDouglas Gregor   return HadError;
905fb912657SDouglas Gregor }
906fb912657SDouglas Gregor 
9070093b3c7SDouglas Gregor Module *ModuleMap::inferModuleFromLocation(FullSourceLoc Loc) {
9080093b3c7SDouglas Gregor   if (Loc.isInvalid())
909d2d442caSCraig Topper     return nullptr;
9100093b3c7SDouglas Gregor 
9110093b3c7SDouglas Gregor   // Use the expansion location to determine which module we're in.
9120093b3c7SDouglas Gregor   FullSourceLoc ExpansionLoc = Loc.getExpansionLoc();
9130093b3c7SDouglas Gregor   if (!ExpansionLoc.isFileID())
914d2d442caSCraig Topper     return nullptr;
9150093b3c7SDouglas Gregor 
9160093b3c7SDouglas Gregor   const SourceManager &SrcMgr = Loc.getManager();
9170093b3c7SDouglas Gregor   FileID ExpansionFileID = ExpansionLoc.getFileID();
918224d8a74SDouglas Gregor 
919224d8a74SDouglas Gregor   while (const FileEntry *ExpansionFile
920224d8a74SDouglas Gregor            = SrcMgr.getFileEntryForID(ExpansionFileID)) {
921224d8a74SDouglas Gregor     // Find the module that owns this header (if any).
922b53e5483SLawrence Crowl     if (Module *Mod = findModuleForHeader(ExpansionFile).getModule())
923224d8a74SDouglas Gregor       return Mod;
924224d8a74SDouglas Gregor 
925224d8a74SDouglas Gregor     // No module owns this header, so look up the inclusion chain to see if
926224d8a74SDouglas Gregor     // any included header has an associated module.
927224d8a74SDouglas Gregor     SourceLocation IncludeLoc = SrcMgr.getIncludeLoc(ExpansionFileID);
928224d8a74SDouglas Gregor     if (IncludeLoc.isInvalid())
929d2d442caSCraig Topper       return nullptr;
9300093b3c7SDouglas Gregor 
931224d8a74SDouglas Gregor     ExpansionFileID = SrcMgr.getFileID(IncludeLoc);
932224d8a74SDouglas Gregor   }
933224d8a74SDouglas Gregor 
934d2d442caSCraig Topper   return nullptr;
9350093b3c7SDouglas Gregor }
9360093b3c7SDouglas Gregor 
937718292f2SDouglas Gregor //----------------------------------------------------------------------------//
938718292f2SDouglas Gregor // Module map file parser
939718292f2SDouglas Gregor //----------------------------------------------------------------------------//
940718292f2SDouglas Gregor 
941718292f2SDouglas Gregor namespace clang {
942718292f2SDouglas Gregor   /// \brief A token in a module map file.
943718292f2SDouglas Gregor   struct MMToken {
944718292f2SDouglas Gregor     enum TokenKind {
9451fb5c3a6SDouglas Gregor       Comma,
94635b13eceSDouglas Gregor       ConfigMacros,
947fb912657SDouglas Gregor       Conflict,
948718292f2SDouglas Gregor       EndOfFile,
949718292f2SDouglas Gregor       HeaderKeyword,
950718292f2SDouglas Gregor       Identifier,
951a3feee2aSRichard Smith       Exclaim,
95259527666SDouglas Gregor       ExcludeKeyword,
953718292f2SDouglas Gregor       ExplicitKeyword,
9542b82c2a5SDouglas Gregor       ExportKeyword,
95597292843SDaniel Jasper       ExternKeyword,
956755b2055SDouglas Gregor       FrameworkKeyword,
9576ddfca91SDouglas Gregor       LinkKeyword,
958718292f2SDouglas Gregor       ModuleKeyword,
9592b82c2a5SDouglas Gregor       Period,
960b53e5483SLawrence Crowl       PrivateKeyword,
961718292f2SDouglas Gregor       UmbrellaKeyword,
962ba7f2f71SDaniel Jasper       UseKeyword,
9631fb5c3a6SDouglas Gregor       RequiresKeyword,
9642b82c2a5SDouglas Gregor       Star,
965718292f2SDouglas Gregor       StringLiteral,
966306d8920SRichard Smith       TextualKeyword,
967718292f2SDouglas Gregor       LBrace,
968a686e1b0SDouglas Gregor       RBrace,
969a686e1b0SDouglas Gregor       LSquare,
970a686e1b0SDouglas Gregor       RSquare
971718292f2SDouglas Gregor     } Kind;
972718292f2SDouglas Gregor 
973718292f2SDouglas Gregor     unsigned Location;
974718292f2SDouglas Gregor     unsigned StringLength;
975718292f2SDouglas Gregor     const char *StringData;
976718292f2SDouglas Gregor 
977718292f2SDouglas Gregor     void clear() {
978718292f2SDouglas Gregor       Kind = EndOfFile;
979718292f2SDouglas Gregor       Location = 0;
980718292f2SDouglas Gregor       StringLength = 0;
981d2d442caSCraig Topper       StringData = nullptr;
982718292f2SDouglas Gregor     }
983718292f2SDouglas Gregor 
984718292f2SDouglas Gregor     bool is(TokenKind K) const { return Kind == K; }
985718292f2SDouglas Gregor 
986718292f2SDouglas Gregor     SourceLocation getLocation() const {
987718292f2SDouglas Gregor       return SourceLocation::getFromRawEncoding(Location);
988718292f2SDouglas Gregor     }
989718292f2SDouglas Gregor 
990718292f2SDouglas Gregor     StringRef getString() const {
991718292f2SDouglas Gregor       return StringRef(StringData, StringLength);
992718292f2SDouglas Gregor     }
993718292f2SDouglas Gregor   };
994718292f2SDouglas Gregor 
9959194a91dSDouglas Gregor   /// \brief The set of attributes that can be attached to a module.
9964442605fSBill Wendling   struct Attributes {
99777944868SRichard Smith     Attributes() : IsSystem(), IsExternC(), IsExhaustive() { }
9989194a91dSDouglas Gregor 
9999194a91dSDouglas Gregor     /// \brief Whether this is a system module.
10009194a91dSDouglas Gregor     unsigned IsSystem : 1;
100135b13eceSDouglas Gregor 
100277944868SRichard Smith     /// \brief Whether this is an extern "C" module.
100377944868SRichard Smith     unsigned IsExternC : 1;
100477944868SRichard Smith 
100535b13eceSDouglas Gregor     /// \brief Whether this is an exhaustive set of configuration macros.
100635b13eceSDouglas Gregor     unsigned IsExhaustive : 1;
10079194a91dSDouglas Gregor   };
10089194a91dSDouglas Gregor 
10099194a91dSDouglas Gregor 
1010718292f2SDouglas Gregor   class ModuleMapParser {
1011718292f2SDouglas Gregor     Lexer &L;
1012718292f2SDouglas Gregor     SourceManager &SourceMgr;
1013bc10b9fbSDouglas Gregor 
1014bc10b9fbSDouglas Gregor     /// \brief Default target information, used only for string literal
1015bc10b9fbSDouglas Gregor     /// parsing.
1016bc10b9fbSDouglas Gregor     const TargetInfo *Target;
1017bc10b9fbSDouglas Gregor 
1018718292f2SDouglas Gregor     DiagnosticsEngine &Diags;
1019718292f2SDouglas Gregor     ModuleMap &Map;
1020718292f2SDouglas Gregor 
1021beee15e7SBen Langmuir     /// \brief The current module map file.
1022beee15e7SBen Langmuir     const FileEntry *ModuleMapFile;
1023beee15e7SBen Langmuir 
10245257fc63SDouglas Gregor     /// \brief The directory that this module map resides in.
10255257fc63SDouglas Gregor     const DirectoryEntry *Directory;
10265257fc63SDouglas Gregor 
10273ec6663bSDouglas Gregor     /// \brief The directory containing Clang-supplied headers.
10283ec6663bSDouglas Gregor     const DirectoryEntry *BuiltinIncludeDir;
10293ec6663bSDouglas Gregor 
1030963c5535SDouglas Gregor     /// \brief Whether this module map is in a system header directory.
1031963c5535SDouglas Gregor     bool IsSystem;
1032963c5535SDouglas Gregor 
1033718292f2SDouglas Gregor     /// \brief Whether an error occurred.
1034718292f2SDouglas Gregor     bool HadError;
1035718292f2SDouglas Gregor 
1036718292f2SDouglas Gregor     /// \brief Stores string data for the various string literals referenced
1037718292f2SDouglas Gregor     /// during parsing.
1038718292f2SDouglas Gregor     llvm::BumpPtrAllocator StringData;
1039718292f2SDouglas Gregor 
1040718292f2SDouglas Gregor     /// \brief The current token.
1041718292f2SDouglas Gregor     MMToken Tok;
1042718292f2SDouglas Gregor 
1043718292f2SDouglas Gregor     /// \brief The active module.
1044de3ef502SDouglas Gregor     Module *ActiveModule;
1045718292f2SDouglas Gregor 
1046718292f2SDouglas Gregor     /// \brief Consume the current token and return its location.
1047718292f2SDouglas Gregor     SourceLocation consumeToken();
1048718292f2SDouglas Gregor 
1049718292f2SDouglas Gregor     /// \brief Skip tokens until we reach the a token with the given kind
1050718292f2SDouglas Gregor     /// (or the end of the file).
1051718292f2SDouglas Gregor     void skipUntil(MMToken::TokenKind K);
1052718292f2SDouglas Gregor 
1053f857950dSDmitri Gribenko     typedef SmallVector<std::pair<std::string, SourceLocation>, 2> ModuleId;
1054e7ab3669SDouglas Gregor     bool parseModuleId(ModuleId &Id);
1055718292f2SDouglas Gregor     void parseModuleDecl();
105697292843SDaniel Jasper     void parseExternModuleDecl();
10571fb5c3a6SDouglas Gregor     void parseRequiresDecl();
1058b53e5483SLawrence Crowl     void parseHeaderDecl(clang::MMToken::TokenKind,
1059b53e5483SLawrence Crowl                          SourceLocation LeadingLoc);
1060524e33e1SDouglas Gregor     void parseUmbrellaDirDecl(SourceLocation UmbrellaLoc);
10612b82c2a5SDouglas Gregor     void parseExportDecl();
1062ba7f2f71SDaniel Jasper     void parseUseDecl();
10636ddfca91SDouglas Gregor     void parseLinkDecl();
106435b13eceSDouglas Gregor     void parseConfigMacros();
1065fb912657SDouglas Gregor     void parseConflict();
10669194a91dSDouglas Gregor     void parseInferredModuleDecl(bool Framework, bool Explicit);
10674442605fSBill Wendling     bool parseOptionalAttributes(Attributes &Attrs);
1068718292f2SDouglas Gregor 
1069718292f2SDouglas Gregor   public:
1070718292f2SDouglas Gregor     explicit ModuleMapParser(Lexer &L, SourceManager &SourceMgr,
1071bc10b9fbSDouglas Gregor                              const TargetInfo *Target,
1072718292f2SDouglas Gregor                              DiagnosticsEngine &Diags,
10735257fc63SDouglas Gregor                              ModuleMap &Map,
1074beee15e7SBen Langmuir                              const FileEntry *ModuleMapFile,
10753ec6663bSDouglas Gregor                              const DirectoryEntry *Directory,
1076963c5535SDouglas Gregor                              const DirectoryEntry *BuiltinIncludeDir,
1077963c5535SDouglas Gregor                              bool IsSystem)
1078bc10b9fbSDouglas Gregor       : L(L), SourceMgr(SourceMgr), Target(Target), Diags(Diags), Map(Map),
1079beee15e7SBen Langmuir         ModuleMapFile(ModuleMapFile), Directory(Directory),
1080beee15e7SBen Langmuir         BuiltinIncludeDir(BuiltinIncludeDir), IsSystem(IsSystem),
1081d2d442caSCraig Topper         HadError(false), ActiveModule(nullptr)
1082718292f2SDouglas Gregor     {
1083718292f2SDouglas Gregor       Tok.clear();
1084718292f2SDouglas Gregor       consumeToken();
1085718292f2SDouglas Gregor     }
1086718292f2SDouglas Gregor 
1087718292f2SDouglas Gregor     bool parseModuleMapFile();
1088718292f2SDouglas Gregor   };
1089718292f2SDouglas Gregor }
1090718292f2SDouglas Gregor 
1091718292f2SDouglas Gregor SourceLocation ModuleMapParser::consumeToken() {
1092718292f2SDouglas Gregor retry:
1093718292f2SDouglas Gregor   SourceLocation Result = Tok.getLocation();
1094718292f2SDouglas Gregor   Tok.clear();
1095718292f2SDouglas Gregor 
1096718292f2SDouglas Gregor   Token LToken;
1097718292f2SDouglas Gregor   L.LexFromRawLexer(LToken);
1098718292f2SDouglas Gregor   Tok.Location = LToken.getLocation().getRawEncoding();
1099718292f2SDouglas Gregor   switch (LToken.getKind()) {
11002d57cea2SAlp Toker   case tok::raw_identifier: {
11012d57cea2SAlp Toker     StringRef RI = LToken.getRawIdentifier();
11022d57cea2SAlp Toker     Tok.StringData = RI.data();
11032d57cea2SAlp Toker     Tok.StringLength = RI.size();
11042d57cea2SAlp Toker     Tok.Kind = llvm::StringSwitch<MMToken::TokenKind>(RI)
110535b13eceSDouglas Gregor                  .Case("config_macros", MMToken::ConfigMacros)
1106fb912657SDouglas Gregor                  .Case("conflict", MMToken::Conflict)
110759527666SDouglas Gregor                  .Case("exclude", MMToken::ExcludeKeyword)
1108718292f2SDouglas Gregor                  .Case("explicit", MMToken::ExplicitKeyword)
11092b82c2a5SDouglas Gregor                  .Case("export", MMToken::ExportKeyword)
111097292843SDaniel Jasper                  .Case("extern", MMToken::ExternKeyword)
1111755b2055SDouglas Gregor                  .Case("framework", MMToken::FrameworkKeyword)
111235b13eceSDouglas Gregor                  .Case("header", MMToken::HeaderKeyword)
11136ddfca91SDouglas Gregor                  .Case("link", MMToken::LinkKeyword)
1114718292f2SDouglas Gregor                  .Case("module", MMToken::ModuleKeyword)
1115b53e5483SLawrence Crowl                  .Case("private", MMToken::PrivateKeyword)
11161fb5c3a6SDouglas Gregor                  .Case("requires", MMToken::RequiresKeyword)
1117306d8920SRichard Smith                  .Case("textual", MMToken::TextualKeyword)
1118718292f2SDouglas Gregor                  .Case("umbrella", MMToken::UmbrellaKeyword)
1119ba7f2f71SDaniel Jasper                  .Case("use", MMToken::UseKeyword)
1120718292f2SDouglas Gregor                  .Default(MMToken::Identifier);
1121718292f2SDouglas Gregor     break;
11222d57cea2SAlp Toker   }
1123718292f2SDouglas Gregor 
11241fb5c3a6SDouglas Gregor   case tok::comma:
11251fb5c3a6SDouglas Gregor     Tok.Kind = MMToken::Comma;
11261fb5c3a6SDouglas Gregor     break;
11271fb5c3a6SDouglas Gregor 
1128718292f2SDouglas Gregor   case tok::eof:
1129718292f2SDouglas Gregor     Tok.Kind = MMToken::EndOfFile;
1130718292f2SDouglas Gregor     break;
1131718292f2SDouglas Gregor 
1132718292f2SDouglas Gregor   case tok::l_brace:
1133718292f2SDouglas Gregor     Tok.Kind = MMToken::LBrace;
1134718292f2SDouglas Gregor     break;
1135718292f2SDouglas Gregor 
1136a686e1b0SDouglas Gregor   case tok::l_square:
1137a686e1b0SDouglas Gregor     Tok.Kind = MMToken::LSquare;
1138a686e1b0SDouglas Gregor     break;
1139a686e1b0SDouglas Gregor 
11402b82c2a5SDouglas Gregor   case tok::period:
11412b82c2a5SDouglas Gregor     Tok.Kind = MMToken::Period;
11422b82c2a5SDouglas Gregor     break;
11432b82c2a5SDouglas Gregor 
1144718292f2SDouglas Gregor   case tok::r_brace:
1145718292f2SDouglas Gregor     Tok.Kind = MMToken::RBrace;
1146718292f2SDouglas Gregor     break;
1147718292f2SDouglas Gregor 
1148a686e1b0SDouglas Gregor   case tok::r_square:
1149a686e1b0SDouglas Gregor     Tok.Kind = MMToken::RSquare;
1150a686e1b0SDouglas Gregor     break;
1151a686e1b0SDouglas Gregor 
11522b82c2a5SDouglas Gregor   case tok::star:
11532b82c2a5SDouglas Gregor     Tok.Kind = MMToken::Star;
11542b82c2a5SDouglas Gregor     break;
11552b82c2a5SDouglas Gregor 
1156a3feee2aSRichard Smith   case tok::exclaim:
1157a3feee2aSRichard Smith     Tok.Kind = MMToken::Exclaim;
1158a3feee2aSRichard Smith     break;
1159a3feee2aSRichard Smith 
1160718292f2SDouglas Gregor   case tok::string_literal: {
1161d67aea28SRichard Smith     if (LToken.hasUDSuffix()) {
1162d67aea28SRichard Smith       Diags.Report(LToken.getLocation(), diag::err_invalid_string_udl);
1163d67aea28SRichard Smith       HadError = true;
1164d67aea28SRichard Smith       goto retry;
1165d67aea28SRichard Smith     }
1166d67aea28SRichard Smith 
1167718292f2SDouglas Gregor     // Parse the string literal.
1168718292f2SDouglas Gregor     LangOptions LangOpts;
11699d5583efSCraig Topper     StringLiteralParser StringLiteral(LToken, SourceMgr, LangOpts, *Target);
1170718292f2SDouglas Gregor     if (StringLiteral.hadError)
1171718292f2SDouglas Gregor       goto retry;
1172718292f2SDouglas Gregor 
1173718292f2SDouglas Gregor     // Copy the string literal into our string data allocator.
1174718292f2SDouglas Gregor     unsigned Length = StringLiteral.GetStringLength();
1175718292f2SDouglas Gregor     char *Saved = StringData.Allocate<char>(Length + 1);
1176718292f2SDouglas Gregor     memcpy(Saved, StringLiteral.GetString().data(), Length);
1177718292f2SDouglas Gregor     Saved[Length] = 0;
1178718292f2SDouglas Gregor 
1179718292f2SDouglas Gregor     // Form the token.
1180718292f2SDouglas Gregor     Tok.Kind = MMToken::StringLiteral;
1181718292f2SDouglas Gregor     Tok.StringData = Saved;
1182718292f2SDouglas Gregor     Tok.StringLength = Length;
1183718292f2SDouglas Gregor     break;
1184718292f2SDouglas Gregor   }
1185718292f2SDouglas Gregor 
1186718292f2SDouglas Gregor   case tok::comment:
1187718292f2SDouglas Gregor     goto retry;
1188718292f2SDouglas Gregor 
1189718292f2SDouglas Gregor   default:
1190718292f2SDouglas Gregor     Diags.Report(LToken.getLocation(), diag::err_mmap_unknown_token);
1191718292f2SDouglas Gregor     HadError = true;
1192718292f2SDouglas Gregor     goto retry;
1193718292f2SDouglas Gregor   }
1194718292f2SDouglas Gregor 
1195718292f2SDouglas Gregor   return Result;
1196718292f2SDouglas Gregor }
1197718292f2SDouglas Gregor 
1198718292f2SDouglas Gregor void ModuleMapParser::skipUntil(MMToken::TokenKind K) {
1199718292f2SDouglas Gregor   unsigned braceDepth = 0;
1200a686e1b0SDouglas Gregor   unsigned squareDepth = 0;
1201718292f2SDouglas Gregor   do {
1202718292f2SDouglas Gregor     switch (Tok.Kind) {
1203718292f2SDouglas Gregor     case MMToken::EndOfFile:
1204718292f2SDouglas Gregor       return;
1205718292f2SDouglas Gregor 
1206718292f2SDouglas Gregor     case MMToken::LBrace:
1207a686e1b0SDouglas Gregor       if (Tok.is(K) && braceDepth == 0 && squareDepth == 0)
1208718292f2SDouglas Gregor         return;
1209718292f2SDouglas Gregor 
1210718292f2SDouglas Gregor       ++braceDepth;
1211718292f2SDouglas Gregor       break;
1212718292f2SDouglas Gregor 
1213a686e1b0SDouglas Gregor     case MMToken::LSquare:
1214a686e1b0SDouglas Gregor       if (Tok.is(K) && braceDepth == 0 && squareDepth == 0)
1215a686e1b0SDouglas Gregor         return;
1216a686e1b0SDouglas Gregor 
1217a686e1b0SDouglas Gregor       ++squareDepth;
1218a686e1b0SDouglas Gregor       break;
1219a686e1b0SDouglas Gregor 
1220718292f2SDouglas Gregor     case MMToken::RBrace:
1221718292f2SDouglas Gregor       if (braceDepth > 0)
1222718292f2SDouglas Gregor         --braceDepth;
1223718292f2SDouglas Gregor       else if (Tok.is(K))
1224718292f2SDouglas Gregor         return;
1225718292f2SDouglas Gregor       break;
1226718292f2SDouglas Gregor 
1227a686e1b0SDouglas Gregor     case MMToken::RSquare:
1228a686e1b0SDouglas Gregor       if (squareDepth > 0)
1229a686e1b0SDouglas Gregor         --squareDepth;
1230a686e1b0SDouglas Gregor       else if (Tok.is(K))
1231a686e1b0SDouglas Gregor         return;
1232a686e1b0SDouglas Gregor       break;
1233a686e1b0SDouglas Gregor 
1234718292f2SDouglas Gregor     default:
1235a686e1b0SDouglas Gregor       if (braceDepth == 0 && squareDepth == 0 && Tok.is(K))
1236718292f2SDouglas Gregor         return;
1237718292f2SDouglas Gregor       break;
1238718292f2SDouglas Gregor     }
1239718292f2SDouglas Gregor 
1240718292f2SDouglas Gregor    consumeToken();
1241718292f2SDouglas Gregor   } while (true);
1242718292f2SDouglas Gregor }
1243718292f2SDouglas Gregor 
1244e7ab3669SDouglas Gregor /// \brief Parse a module-id.
1245e7ab3669SDouglas Gregor ///
1246e7ab3669SDouglas Gregor ///   module-id:
1247e7ab3669SDouglas Gregor ///     identifier
1248e7ab3669SDouglas Gregor ///     identifier '.' module-id
1249e7ab3669SDouglas Gregor ///
1250e7ab3669SDouglas Gregor /// \returns true if an error occurred, false otherwise.
1251e7ab3669SDouglas Gregor bool ModuleMapParser::parseModuleId(ModuleId &Id) {
1252e7ab3669SDouglas Gregor   Id.clear();
1253e7ab3669SDouglas Gregor   do {
12543cd34c76SDaniel Jasper     if (Tok.is(MMToken::Identifier) || Tok.is(MMToken::StringLiteral)) {
1255e7ab3669SDouglas Gregor       Id.push_back(std::make_pair(Tok.getString(), Tok.getLocation()));
1256e7ab3669SDouglas Gregor       consumeToken();
1257e7ab3669SDouglas Gregor     } else {
1258e7ab3669SDouglas Gregor       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module_name);
1259e7ab3669SDouglas Gregor       return true;
1260e7ab3669SDouglas Gregor     }
1261e7ab3669SDouglas Gregor 
1262e7ab3669SDouglas Gregor     if (!Tok.is(MMToken::Period))
1263e7ab3669SDouglas Gregor       break;
1264e7ab3669SDouglas Gregor 
1265e7ab3669SDouglas Gregor     consumeToken();
1266e7ab3669SDouglas Gregor   } while (true);
1267e7ab3669SDouglas Gregor 
1268e7ab3669SDouglas Gregor   return false;
1269e7ab3669SDouglas Gregor }
1270e7ab3669SDouglas Gregor 
1271a686e1b0SDouglas Gregor namespace {
1272a686e1b0SDouglas Gregor   /// \brief Enumerates the known attributes.
1273a686e1b0SDouglas Gregor   enum AttributeKind {
1274a686e1b0SDouglas Gregor     /// \brief An unknown attribute.
1275a686e1b0SDouglas Gregor     AT_unknown,
1276a686e1b0SDouglas Gregor     /// \brief The 'system' attribute.
127735b13eceSDouglas Gregor     AT_system,
127877944868SRichard Smith     /// \brief The 'extern_c' attribute.
127977944868SRichard Smith     AT_extern_c,
128035b13eceSDouglas Gregor     /// \brief The 'exhaustive' attribute.
128135b13eceSDouglas Gregor     AT_exhaustive
1282a686e1b0SDouglas Gregor   };
1283a686e1b0SDouglas Gregor }
1284a686e1b0SDouglas Gregor 
1285718292f2SDouglas Gregor /// \brief Parse a module declaration.
1286718292f2SDouglas Gregor ///
1287718292f2SDouglas Gregor ///   module-declaration:
128897292843SDaniel Jasper ///     'extern' 'module' module-id string-literal
1289a686e1b0SDouglas Gregor ///     'explicit'[opt] 'framework'[opt] 'module' module-id attributes[opt]
1290a686e1b0SDouglas Gregor ///       { module-member* }
1291a686e1b0SDouglas Gregor ///
1292718292f2SDouglas Gregor ///   module-member:
12931fb5c3a6SDouglas Gregor ///     requires-declaration
1294718292f2SDouglas Gregor ///     header-declaration
1295e7ab3669SDouglas Gregor ///     submodule-declaration
12962b82c2a5SDouglas Gregor ///     export-declaration
12976ddfca91SDouglas Gregor ///     link-declaration
129873441091SDouglas Gregor ///
129973441091SDouglas Gregor ///   submodule-declaration:
130073441091SDouglas Gregor ///     module-declaration
130173441091SDouglas Gregor ///     inferred-submodule-declaration
1302718292f2SDouglas Gregor void ModuleMapParser::parseModuleDecl() {
1303755b2055SDouglas Gregor   assert(Tok.is(MMToken::ExplicitKeyword) || Tok.is(MMToken::ModuleKeyword) ||
130497292843SDaniel Jasper          Tok.is(MMToken::FrameworkKeyword) || Tok.is(MMToken::ExternKeyword));
130597292843SDaniel Jasper   if (Tok.is(MMToken::ExternKeyword)) {
130697292843SDaniel Jasper     parseExternModuleDecl();
130797292843SDaniel Jasper     return;
130897292843SDaniel Jasper   }
130997292843SDaniel Jasper 
1310f2161a70SDouglas Gregor   // Parse 'explicit' or 'framework' keyword, if present.
1311e7ab3669SDouglas Gregor   SourceLocation ExplicitLoc;
1312718292f2SDouglas Gregor   bool Explicit = false;
1313f2161a70SDouglas Gregor   bool Framework = false;
1314755b2055SDouglas Gregor 
1315f2161a70SDouglas Gregor   // Parse 'explicit' keyword, if present.
1316f2161a70SDouglas Gregor   if (Tok.is(MMToken::ExplicitKeyword)) {
1317e7ab3669SDouglas Gregor     ExplicitLoc = consumeToken();
1318f2161a70SDouglas Gregor     Explicit = true;
1319f2161a70SDouglas Gregor   }
1320f2161a70SDouglas Gregor 
1321f2161a70SDouglas Gregor   // Parse 'framework' keyword, if present.
1322755b2055SDouglas Gregor   if (Tok.is(MMToken::FrameworkKeyword)) {
1323755b2055SDouglas Gregor     consumeToken();
1324755b2055SDouglas Gregor     Framework = true;
1325755b2055SDouglas Gregor   }
1326718292f2SDouglas Gregor 
1327718292f2SDouglas Gregor   // Parse 'module' keyword.
1328718292f2SDouglas Gregor   if (!Tok.is(MMToken::ModuleKeyword)) {
1329d6343c99SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module);
1330718292f2SDouglas Gregor     consumeToken();
1331718292f2SDouglas Gregor     HadError = true;
1332718292f2SDouglas Gregor     return;
1333718292f2SDouglas Gregor   }
1334718292f2SDouglas Gregor   consumeToken(); // 'module' keyword
1335718292f2SDouglas Gregor 
133673441091SDouglas Gregor   // If we have a wildcard for the module name, this is an inferred submodule.
133773441091SDouglas Gregor   // Parse it.
133873441091SDouglas Gregor   if (Tok.is(MMToken::Star))
13399194a91dSDouglas Gregor     return parseInferredModuleDecl(Framework, Explicit);
134073441091SDouglas Gregor 
1341718292f2SDouglas Gregor   // Parse the module name.
1342e7ab3669SDouglas Gregor   ModuleId Id;
1343e7ab3669SDouglas Gregor   if (parseModuleId(Id)) {
1344718292f2SDouglas Gregor     HadError = true;
1345718292f2SDouglas Gregor     return;
1346718292f2SDouglas Gregor   }
1347e7ab3669SDouglas Gregor 
1348e7ab3669SDouglas Gregor   if (ActiveModule) {
1349e7ab3669SDouglas Gregor     if (Id.size() > 1) {
1350e7ab3669SDouglas Gregor       Diags.Report(Id.front().second, diag::err_mmap_nested_submodule_id)
1351e7ab3669SDouglas Gregor         << SourceRange(Id.front().second, Id.back().second);
1352e7ab3669SDouglas Gregor 
1353e7ab3669SDouglas Gregor       HadError = true;
1354e7ab3669SDouglas Gregor       return;
1355e7ab3669SDouglas Gregor     }
1356e7ab3669SDouglas Gregor   } else if (Id.size() == 1 && Explicit) {
1357e7ab3669SDouglas Gregor     // Top-level modules can't be explicit.
1358e7ab3669SDouglas Gregor     Diags.Report(ExplicitLoc, diag::err_mmap_explicit_top_level);
1359e7ab3669SDouglas Gregor     Explicit = false;
1360e7ab3669SDouglas Gregor     ExplicitLoc = SourceLocation();
1361e7ab3669SDouglas Gregor     HadError = true;
1362e7ab3669SDouglas Gregor   }
1363e7ab3669SDouglas Gregor 
1364e7ab3669SDouglas Gregor   Module *PreviousActiveModule = ActiveModule;
1365e7ab3669SDouglas Gregor   if (Id.size() > 1) {
1366e7ab3669SDouglas Gregor     // This module map defines a submodule. Go find the module of which it
1367e7ab3669SDouglas Gregor     // is a submodule.
1368d2d442caSCraig Topper     ActiveModule = nullptr;
13694b8a9e95SBen Langmuir     const Module *TopLevelModule = nullptr;
1370e7ab3669SDouglas Gregor     for (unsigned I = 0, N = Id.size() - 1; I != N; ++I) {
1371e7ab3669SDouglas Gregor       if (Module *Next = Map.lookupModuleQualified(Id[I].first, ActiveModule)) {
13724b8a9e95SBen Langmuir         if (I == 0)
13734b8a9e95SBen Langmuir           TopLevelModule = Next;
1374e7ab3669SDouglas Gregor         ActiveModule = Next;
1375e7ab3669SDouglas Gregor         continue;
1376e7ab3669SDouglas Gregor       }
1377e7ab3669SDouglas Gregor 
1378e7ab3669SDouglas Gregor       if (ActiveModule) {
1379e7ab3669SDouglas Gregor         Diags.Report(Id[I].second, diag::err_mmap_missing_module_qualified)
13805b5d21eaSRichard Smith           << Id[I].first
13815b5d21eaSRichard Smith           << ActiveModule->getTopLevelModule()->getFullModuleName();
1382e7ab3669SDouglas Gregor       } else {
1383e7ab3669SDouglas Gregor         Diags.Report(Id[I].second, diag::err_mmap_expected_module_name);
1384e7ab3669SDouglas Gregor       }
1385e7ab3669SDouglas Gregor       HadError = true;
1386e7ab3669SDouglas Gregor       return;
1387e7ab3669SDouglas Gregor     }
13884b8a9e95SBen Langmuir 
13894b8a9e95SBen Langmuir     if (ModuleMapFile != Map.getContainingModuleMapFile(TopLevelModule)) {
13904b8a9e95SBen Langmuir       assert(ModuleMapFile != Map.getModuleMapFileForUniquing(TopLevelModule) &&
13914b8a9e95SBen Langmuir              "submodule defined in same file as 'module *' that allowed its "
13924b8a9e95SBen Langmuir              "top-level module");
13934b8a9e95SBen Langmuir       Map.addAdditionalModuleMapFile(TopLevelModule, ModuleMapFile);
13944b8a9e95SBen Langmuir     }
1395e7ab3669SDouglas Gregor   }
1396e7ab3669SDouglas Gregor 
1397e7ab3669SDouglas Gregor   StringRef ModuleName = Id.back().first;
1398e7ab3669SDouglas Gregor   SourceLocation ModuleNameLoc = Id.back().second;
1399718292f2SDouglas Gregor 
1400a686e1b0SDouglas Gregor   // Parse the optional attribute list.
14014442605fSBill Wendling   Attributes Attrs;
14029194a91dSDouglas Gregor   parseOptionalAttributes(Attrs);
1403a686e1b0SDouglas Gregor 
1404718292f2SDouglas Gregor   // Parse the opening brace.
1405718292f2SDouglas Gregor   if (!Tok.is(MMToken::LBrace)) {
1406718292f2SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_lbrace)
1407718292f2SDouglas Gregor       << ModuleName;
1408718292f2SDouglas Gregor     HadError = true;
1409718292f2SDouglas Gregor     return;
1410718292f2SDouglas Gregor   }
1411718292f2SDouglas Gregor   SourceLocation LBraceLoc = consumeToken();
1412718292f2SDouglas Gregor 
1413718292f2SDouglas Gregor   // Determine whether this (sub)module has already been defined.
1414eb90e830SDouglas Gregor   if (Module *Existing = Map.lookupModuleQualified(ModuleName, ActiveModule)) {
1415fcc54a3bSDouglas Gregor     if (Existing->DefinitionLoc.isInvalid() && !ActiveModule) {
1416fcc54a3bSDouglas Gregor       // Skip the module definition.
1417fcc54a3bSDouglas Gregor       skipUntil(MMToken::RBrace);
1418fcc54a3bSDouglas Gregor       if (Tok.is(MMToken::RBrace))
1419fcc54a3bSDouglas Gregor         consumeToken();
1420fcc54a3bSDouglas Gregor       else {
1421fcc54a3bSDouglas Gregor         Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
1422fcc54a3bSDouglas Gregor         Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
1423fcc54a3bSDouglas Gregor         HadError = true;
1424fcc54a3bSDouglas Gregor       }
1425fcc54a3bSDouglas Gregor       return;
1426fcc54a3bSDouglas Gregor     }
1427fcc54a3bSDouglas Gregor 
1428718292f2SDouglas Gregor     Diags.Report(ModuleNameLoc, diag::err_mmap_module_redefinition)
1429718292f2SDouglas Gregor       << ModuleName;
1430eb90e830SDouglas Gregor     Diags.Report(Existing->DefinitionLoc, diag::note_mmap_prev_definition);
1431718292f2SDouglas Gregor 
1432718292f2SDouglas Gregor     // Skip the module definition.
1433718292f2SDouglas Gregor     skipUntil(MMToken::RBrace);
1434718292f2SDouglas Gregor     if (Tok.is(MMToken::RBrace))
1435718292f2SDouglas Gregor       consumeToken();
1436718292f2SDouglas Gregor 
1437718292f2SDouglas Gregor     HadError = true;
1438718292f2SDouglas Gregor     return;
1439718292f2SDouglas Gregor   }
1440718292f2SDouglas Gregor 
1441718292f2SDouglas Gregor   // Start defining this module.
14429d6448b1SBen Langmuir   ActiveModule = Map.findOrCreateModule(ModuleName, ActiveModule, Framework,
14439d6448b1SBen Langmuir                                         Explicit).first;
1444eb90e830SDouglas Gregor   ActiveModule->DefinitionLoc = ModuleNameLoc;
1445963c5535SDouglas Gregor   if (Attrs.IsSystem || IsSystem)
1446a686e1b0SDouglas Gregor     ActiveModule->IsSystem = true;
144777944868SRichard Smith   if (Attrs.IsExternC)
144877944868SRichard Smith     ActiveModule->IsExternC = true;
1449718292f2SDouglas Gregor 
1450718292f2SDouglas Gregor   bool Done = false;
1451718292f2SDouglas Gregor   do {
1452718292f2SDouglas Gregor     switch (Tok.Kind) {
1453718292f2SDouglas Gregor     case MMToken::EndOfFile:
1454718292f2SDouglas Gregor     case MMToken::RBrace:
1455718292f2SDouglas Gregor       Done = true;
1456718292f2SDouglas Gregor       break;
1457718292f2SDouglas Gregor 
145835b13eceSDouglas Gregor     case MMToken::ConfigMacros:
145935b13eceSDouglas Gregor       parseConfigMacros();
146035b13eceSDouglas Gregor       break;
146135b13eceSDouglas Gregor 
1462fb912657SDouglas Gregor     case MMToken::Conflict:
1463fb912657SDouglas Gregor       parseConflict();
1464fb912657SDouglas Gregor       break;
1465fb912657SDouglas Gregor 
1466718292f2SDouglas Gregor     case MMToken::ExplicitKeyword:
146797292843SDaniel Jasper     case MMToken::ExternKeyword:
1468f2161a70SDouglas Gregor     case MMToken::FrameworkKeyword:
1469718292f2SDouglas Gregor     case MMToken::ModuleKeyword:
1470718292f2SDouglas Gregor       parseModuleDecl();
1471718292f2SDouglas Gregor       break;
1472718292f2SDouglas Gregor 
14732b82c2a5SDouglas Gregor     case MMToken::ExportKeyword:
14742b82c2a5SDouglas Gregor       parseExportDecl();
14752b82c2a5SDouglas Gregor       break;
14762b82c2a5SDouglas Gregor 
1477ba7f2f71SDaniel Jasper     case MMToken::UseKeyword:
1478ba7f2f71SDaniel Jasper       parseUseDecl();
1479ba7f2f71SDaniel Jasper       break;
1480ba7f2f71SDaniel Jasper 
14811fb5c3a6SDouglas Gregor     case MMToken::RequiresKeyword:
14821fb5c3a6SDouglas Gregor       parseRequiresDecl();
14831fb5c3a6SDouglas Gregor       break;
14841fb5c3a6SDouglas Gregor 
1485202210b3SRichard Smith     case MMToken::TextualKeyword:
1486202210b3SRichard Smith       parseHeaderDecl(MMToken::TextualKeyword, consumeToken());
1487306d8920SRichard Smith       break;
1488306d8920SRichard Smith 
1489524e33e1SDouglas Gregor     case MMToken::UmbrellaKeyword: {
1490524e33e1SDouglas Gregor       SourceLocation UmbrellaLoc = consumeToken();
1491524e33e1SDouglas Gregor       if (Tok.is(MMToken::HeaderKeyword))
1492b53e5483SLawrence Crowl         parseHeaderDecl(MMToken::UmbrellaKeyword, UmbrellaLoc);
1493524e33e1SDouglas Gregor       else
1494524e33e1SDouglas Gregor         parseUmbrellaDirDecl(UmbrellaLoc);
1495718292f2SDouglas Gregor       break;
1496524e33e1SDouglas Gregor     }
1497718292f2SDouglas Gregor 
1498202210b3SRichard Smith     case MMToken::ExcludeKeyword:
1499202210b3SRichard Smith       parseHeaderDecl(MMToken::ExcludeKeyword, consumeToken());
150059527666SDouglas Gregor       break;
150159527666SDouglas Gregor 
1502202210b3SRichard Smith     case MMToken::PrivateKeyword:
1503202210b3SRichard Smith       parseHeaderDecl(MMToken::PrivateKeyword, consumeToken());
1504b53e5483SLawrence Crowl       break;
1505b53e5483SLawrence Crowl 
1506322f633cSDouglas Gregor     case MMToken::HeaderKeyword:
1507202210b3SRichard Smith       parseHeaderDecl(MMToken::HeaderKeyword, consumeToken());
1508718292f2SDouglas Gregor       break;
1509718292f2SDouglas Gregor 
15106ddfca91SDouglas Gregor     case MMToken::LinkKeyword:
15116ddfca91SDouglas Gregor       parseLinkDecl();
15126ddfca91SDouglas Gregor       break;
15136ddfca91SDouglas Gregor 
1514718292f2SDouglas Gregor     default:
1515718292f2SDouglas Gregor       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_member);
1516718292f2SDouglas Gregor       consumeToken();
1517718292f2SDouglas Gregor       break;
1518718292f2SDouglas Gregor     }
1519718292f2SDouglas Gregor   } while (!Done);
1520718292f2SDouglas Gregor 
1521718292f2SDouglas Gregor   if (Tok.is(MMToken::RBrace))
1522718292f2SDouglas Gregor     consumeToken();
1523718292f2SDouglas Gregor   else {
1524718292f2SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
1525718292f2SDouglas Gregor     Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
1526718292f2SDouglas Gregor     HadError = true;
1527718292f2SDouglas Gregor   }
1528718292f2SDouglas Gregor 
152911dfe6feSDouglas Gregor   // If the active module is a top-level framework, and there are no link
153011dfe6feSDouglas Gregor   // libraries, automatically link against the framework.
153111dfe6feSDouglas Gregor   if (ActiveModule->IsFramework && !ActiveModule->isSubFramework() &&
153211dfe6feSDouglas Gregor       ActiveModule->LinkLibraries.empty()) {
153311dfe6feSDouglas Gregor     inferFrameworkLink(ActiveModule, Directory, SourceMgr.getFileManager());
153411dfe6feSDouglas Gregor   }
153511dfe6feSDouglas Gregor 
1536ec8c9752SBen Langmuir   // If the module meets all requirements but is still unavailable, mark the
1537ec8c9752SBen Langmuir   // whole tree as unavailable to prevent it from building.
1538ec8c9752SBen Langmuir   if (!ActiveModule->IsAvailable && !ActiveModule->IsMissingRequirement &&
1539ec8c9752SBen Langmuir       ActiveModule->Parent) {
1540ec8c9752SBen Langmuir     ActiveModule->getTopLevelModule()->markUnavailable();
1541ec8c9752SBen Langmuir     ActiveModule->getTopLevelModule()->MissingHeaders.append(
1542ec8c9752SBen Langmuir       ActiveModule->MissingHeaders.begin(), ActiveModule->MissingHeaders.end());
1543ec8c9752SBen Langmuir   }
1544ec8c9752SBen Langmuir 
1545e7ab3669SDouglas Gregor   // We're done parsing this module. Pop back to the previous module.
1546e7ab3669SDouglas Gregor   ActiveModule = PreviousActiveModule;
1547718292f2SDouglas Gregor }
1548718292f2SDouglas Gregor 
154997292843SDaniel Jasper /// \brief Parse an extern module declaration.
155097292843SDaniel Jasper ///
155197292843SDaniel Jasper ///   extern module-declaration:
155297292843SDaniel Jasper ///     'extern' 'module' module-id string-literal
155397292843SDaniel Jasper void ModuleMapParser::parseExternModuleDecl() {
155497292843SDaniel Jasper   assert(Tok.is(MMToken::ExternKeyword));
155597292843SDaniel Jasper   consumeToken(); // 'extern' keyword
155697292843SDaniel Jasper 
155797292843SDaniel Jasper   // Parse 'module' keyword.
155897292843SDaniel Jasper   if (!Tok.is(MMToken::ModuleKeyword)) {
155997292843SDaniel Jasper     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module);
156097292843SDaniel Jasper     consumeToken();
156197292843SDaniel Jasper     HadError = true;
156297292843SDaniel Jasper     return;
156397292843SDaniel Jasper   }
156497292843SDaniel Jasper   consumeToken(); // 'module' keyword
156597292843SDaniel Jasper 
156697292843SDaniel Jasper   // Parse the module name.
156797292843SDaniel Jasper   ModuleId Id;
156897292843SDaniel Jasper   if (parseModuleId(Id)) {
156997292843SDaniel Jasper     HadError = true;
157097292843SDaniel Jasper     return;
157197292843SDaniel Jasper   }
157297292843SDaniel Jasper 
157397292843SDaniel Jasper   // Parse the referenced module map file name.
157497292843SDaniel Jasper   if (!Tok.is(MMToken::StringLiteral)) {
157597292843SDaniel Jasper     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_mmap_file);
157697292843SDaniel Jasper     HadError = true;
157797292843SDaniel Jasper     return;
157897292843SDaniel Jasper   }
157997292843SDaniel Jasper   std::string FileName = Tok.getString();
158097292843SDaniel Jasper   consumeToken(); // filename
158197292843SDaniel Jasper 
158297292843SDaniel Jasper   StringRef FileNameRef = FileName;
158397292843SDaniel Jasper   SmallString<128> ModuleMapFileName;
158497292843SDaniel Jasper   if (llvm::sys::path::is_relative(FileNameRef)) {
158597292843SDaniel Jasper     ModuleMapFileName += Directory->getName();
158697292843SDaniel Jasper     llvm::sys::path::append(ModuleMapFileName, FileName);
158797292843SDaniel Jasper     FileNameRef = ModuleMapFileName.str();
158897292843SDaniel Jasper   }
158997292843SDaniel Jasper   if (const FileEntry *File = SourceMgr.getFileManager().getFile(FileNameRef))
159097292843SDaniel Jasper     Map.parseModuleMapFile(File, /*IsSystem=*/false);
159197292843SDaniel Jasper }
159297292843SDaniel Jasper 
15931fb5c3a6SDouglas Gregor /// \brief Parse a requires declaration.
15941fb5c3a6SDouglas Gregor ///
15951fb5c3a6SDouglas Gregor ///   requires-declaration:
15961fb5c3a6SDouglas Gregor ///     'requires' feature-list
15971fb5c3a6SDouglas Gregor ///
15981fb5c3a6SDouglas Gregor ///   feature-list:
1599a3feee2aSRichard Smith ///     feature ',' feature-list
1600a3feee2aSRichard Smith ///     feature
1601a3feee2aSRichard Smith ///
1602a3feee2aSRichard Smith ///   feature:
1603a3feee2aSRichard Smith ///     '!'[opt] identifier
16041fb5c3a6SDouglas Gregor void ModuleMapParser::parseRequiresDecl() {
16051fb5c3a6SDouglas Gregor   assert(Tok.is(MMToken::RequiresKeyword));
16061fb5c3a6SDouglas Gregor 
16071fb5c3a6SDouglas Gregor   // Parse 'requires' keyword.
16081fb5c3a6SDouglas Gregor   consumeToken();
16091fb5c3a6SDouglas Gregor 
16101fb5c3a6SDouglas Gregor   // Parse the feature-list.
16111fb5c3a6SDouglas Gregor   do {
1612a3feee2aSRichard Smith     bool RequiredState = true;
1613a3feee2aSRichard Smith     if (Tok.is(MMToken::Exclaim)) {
1614a3feee2aSRichard Smith       RequiredState = false;
1615a3feee2aSRichard Smith       consumeToken();
1616a3feee2aSRichard Smith     }
1617a3feee2aSRichard Smith 
16181fb5c3a6SDouglas Gregor     if (!Tok.is(MMToken::Identifier)) {
16191fb5c3a6SDouglas Gregor       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_feature);
16201fb5c3a6SDouglas Gregor       HadError = true;
16211fb5c3a6SDouglas Gregor       return;
16221fb5c3a6SDouglas Gregor     }
16231fb5c3a6SDouglas Gregor 
16241fb5c3a6SDouglas Gregor     // Consume the feature name.
16251fb5c3a6SDouglas Gregor     std::string Feature = Tok.getString();
16261fb5c3a6SDouglas Gregor     consumeToken();
16271fb5c3a6SDouglas Gregor 
16281fb5c3a6SDouglas Gregor     // Add this feature.
1629a3feee2aSRichard Smith     ActiveModule->addRequirement(Feature, RequiredState,
1630a3feee2aSRichard Smith                                  Map.LangOpts, *Map.Target);
16311fb5c3a6SDouglas Gregor 
16321fb5c3a6SDouglas Gregor     if (!Tok.is(MMToken::Comma))
16331fb5c3a6SDouglas Gregor       break;
16341fb5c3a6SDouglas Gregor 
16351fb5c3a6SDouglas Gregor     // Consume the comma.
16361fb5c3a6SDouglas Gregor     consumeToken();
16371fb5c3a6SDouglas Gregor   } while (true);
16381fb5c3a6SDouglas Gregor }
16391fb5c3a6SDouglas Gregor 
1640f2161a70SDouglas Gregor /// \brief Append to \p Paths the set of paths needed to get to the
1641f2161a70SDouglas Gregor /// subframework in which the given module lives.
1642bf8da9d7SBenjamin Kramer static void appendSubframeworkPaths(Module *Mod,
1643f857950dSDmitri Gribenko                                     SmallVectorImpl<char> &Path) {
1644f2161a70SDouglas Gregor   // Collect the framework names from the given module to the top-level module.
1645f857950dSDmitri Gribenko   SmallVector<StringRef, 2> Paths;
1646f2161a70SDouglas Gregor   for (; Mod; Mod = Mod->Parent) {
1647f2161a70SDouglas Gregor     if (Mod->IsFramework)
1648f2161a70SDouglas Gregor       Paths.push_back(Mod->Name);
1649f2161a70SDouglas Gregor   }
1650f2161a70SDouglas Gregor 
1651f2161a70SDouglas Gregor   if (Paths.empty())
1652f2161a70SDouglas Gregor     return;
1653f2161a70SDouglas Gregor 
1654f2161a70SDouglas Gregor   // Add Frameworks/Name.framework for each subframework.
165517381a06SBenjamin Kramer   for (unsigned I = Paths.size() - 1; I != 0; --I)
165617381a06SBenjamin Kramer     llvm::sys::path::append(Path, "Frameworks", Paths[I-1] + ".framework");
1657f2161a70SDouglas Gregor }
1658f2161a70SDouglas Gregor 
1659718292f2SDouglas Gregor /// \brief Parse a header declaration.
1660718292f2SDouglas Gregor ///
1661718292f2SDouglas Gregor ///   header-declaration:
1662306d8920SRichard Smith ///     'textual'[opt] 'header' string-literal
1663202210b3SRichard Smith ///     'private' 'textual'[opt] 'header' string-literal
1664202210b3SRichard Smith ///     'exclude' 'header' string-literal
1665202210b3SRichard Smith ///     'umbrella' 'header' string-literal
1666306d8920SRichard Smith ///
1667306d8920SRichard Smith /// FIXME: Support 'private textual header'.
1668b53e5483SLawrence Crowl void ModuleMapParser::parseHeaderDecl(MMToken::TokenKind LeadingToken,
1669b53e5483SLawrence Crowl                                       SourceLocation LeadingLoc) {
1670202210b3SRichard Smith   // We've already consumed the first token.
1671202210b3SRichard Smith   ModuleMap::ModuleHeaderRole Role = ModuleMap::NormalHeader;
1672202210b3SRichard Smith   if (LeadingToken == MMToken::PrivateKeyword) {
1673202210b3SRichard Smith     Role = ModuleMap::PrivateHeader;
1674202210b3SRichard Smith     // 'private' may optionally be followed by 'textual'.
1675202210b3SRichard Smith     if (Tok.is(MMToken::TextualKeyword)) {
1676202210b3SRichard Smith       LeadingToken = Tok.Kind;
16771871ed3dSBenjamin Kramer       consumeToken();
1678202210b3SRichard Smith     }
1679202210b3SRichard Smith   }
1680202210b3SRichard Smith   if (LeadingToken == MMToken::TextualKeyword)
1681202210b3SRichard Smith     Role = ModuleMap::ModuleHeaderRole(Role | ModuleMap::TextualHeader);
1682202210b3SRichard Smith 
1683202210b3SRichard Smith   if (LeadingToken != MMToken::HeaderKeyword) {
1684202210b3SRichard Smith     if (!Tok.is(MMToken::HeaderKeyword)) {
1685202210b3SRichard Smith       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
1686202210b3SRichard Smith           << (LeadingToken == MMToken::PrivateKeyword ? "private" :
1687202210b3SRichard Smith               LeadingToken == MMToken::ExcludeKeyword ? "exclude" :
1688202210b3SRichard Smith               LeadingToken == MMToken::TextualKeyword ? "textual" : "umbrella");
1689202210b3SRichard Smith       return;
1690202210b3SRichard Smith     }
1691202210b3SRichard Smith     consumeToken();
1692202210b3SRichard Smith   }
1693718292f2SDouglas Gregor 
1694718292f2SDouglas Gregor   // Parse the header name.
1695718292f2SDouglas Gregor   if (!Tok.is(MMToken::StringLiteral)) {
1696718292f2SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
1697718292f2SDouglas Gregor       << "header";
1698718292f2SDouglas Gregor     HadError = true;
1699718292f2SDouglas Gregor     return;
1700718292f2SDouglas Gregor   }
17010761a8a0SDaniel Jasper   Module::HeaderDirective Header;
17020761a8a0SDaniel Jasper   Header.FileName = Tok.getString();
17030761a8a0SDaniel Jasper   Header.FileNameLoc = consumeToken();
1704718292f2SDouglas Gregor 
1705524e33e1SDouglas Gregor   // Check whether we already have an umbrella.
1706b53e5483SLawrence Crowl   if (LeadingToken == MMToken::UmbrellaKeyword && ActiveModule->Umbrella) {
17070761a8a0SDaniel Jasper     Diags.Report(Header.FileNameLoc, diag::err_mmap_umbrella_clash)
1708524e33e1SDouglas Gregor       << ActiveModule->getFullModuleName();
1709322f633cSDouglas Gregor     HadError = true;
1710322f633cSDouglas Gregor     return;
1711322f633cSDouglas Gregor   }
1712322f633cSDouglas Gregor 
17135257fc63SDouglas Gregor   // Look for this file.
1714d2d442caSCraig Topper   const FileEntry *File = nullptr;
1715d2d442caSCraig Topper   const FileEntry *BuiltinFile = nullptr;
17162c1dd271SDylan Noblesmith   SmallString<128> PathName;
17170761a8a0SDaniel Jasper   if (llvm::sys::path::is_absolute(Header.FileName)) {
17180761a8a0SDaniel Jasper     PathName = Header.FileName;
1719e7ab3669SDouglas Gregor     File = SourceMgr.getFileManager().getFile(PathName);
1720e7ab3669SDouglas Gregor   } else {
1721e7ab3669SDouglas Gregor     // Search for the header file within the search directory.
17227033127bSDouglas Gregor     PathName = Directory->getName();
1723e7ab3669SDouglas Gregor     unsigned PathLength = PathName.size();
1724755b2055SDouglas Gregor 
1725f2161a70SDouglas Gregor     if (ActiveModule->isPartOfFramework()) {
1726f2161a70SDouglas Gregor       appendSubframeworkPaths(ActiveModule, PathName);
1727755b2055SDouglas Gregor 
1728e7ab3669SDouglas Gregor       // Check whether this file is in the public headers.
17290761a8a0SDaniel Jasper       llvm::sys::path::append(PathName, "Headers", Header.FileName);
1730e7ab3669SDouglas Gregor       File = SourceMgr.getFileManager().getFile(PathName);
1731e7ab3669SDouglas Gregor 
1732e7ab3669SDouglas Gregor       if (!File) {
1733e7ab3669SDouglas Gregor         // Check whether this file is in the private headers.
1734e7ab3669SDouglas Gregor         PathName.resize(PathLength);
17350761a8a0SDaniel Jasper         llvm::sys::path::append(PathName, "PrivateHeaders", Header.FileName);
1736e7ab3669SDouglas Gregor         File = SourceMgr.getFileManager().getFile(PathName);
1737e7ab3669SDouglas Gregor       }
1738e7ab3669SDouglas Gregor     } else {
1739e7ab3669SDouglas Gregor       // Lookup for normal headers.
17400761a8a0SDaniel Jasper       llvm::sys::path::append(PathName, Header.FileName);
1741e7ab3669SDouglas Gregor       File = SourceMgr.getFileManager().getFile(PathName);
17423ec6663bSDouglas Gregor 
17433ec6663bSDouglas Gregor       // If this is a system module with a top-level header, this header
17443ec6663bSDouglas Gregor       // may have a counterpart (or replacement) in the set of headers
17453ec6663bSDouglas Gregor       // supplied by Clang. Find that builtin header.
1746b53e5483SLawrence Crowl       if (ActiveModule->IsSystem && LeadingToken != MMToken::UmbrellaKeyword &&
1747b53e5483SLawrence Crowl           BuiltinIncludeDir && BuiltinIncludeDir != Directory &&
17480761a8a0SDaniel Jasper           isBuiltinHeader(Header.FileName)) {
17492c1dd271SDylan Noblesmith         SmallString<128> BuiltinPathName(BuiltinIncludeDir->getName());
17500761a8a0SDaniel Jasper         llvm::sys::path::append(BuiltinPathName, Header.FileName);
17513ec6663bSDouglas Gregor         BuiltinFile = SourceMgr.getFileManager().getFile(BuiltinPathName);
17523ec6663bSDouglas Gregor 
17533ec6663bSDouglas Gregor         // If Clang supplies this header but the underlying system does not,
17543ec6663bSDouglas Gregor         // just silently swap in our builtin version. Otherwise, we'll end
17553ec6663bSDouglas Gregor         // up adding both (later).
17563ec6663bSDouglas Gregor         if (!File && BuiltinFile) {
17573ec6663bSDouglas Gregor           File = BuiltinFile;
1758d2d442caSCraig Topper           BuiltinFile = nullptr;
17593ec6663bSDouglas Gregor         }
17603ec6663bSDouglas Gregor       }
1761e7ab3669SDouglas Gregor     }
1762e7ab3669SDouglas Gregor   }
17635257fc63SDouglas Gregor 
17645257fc63SDouglas Gregor   // FIXME: We shouldn't be eagerly stat'ing every file named in a module map.
17655257fc63SDouglas Gregor   // Come up with a lazy way to do this.
1766e7ab3669SDouglas Gregor   if (File) {
176797da9178SDaniel Jasper     if (LeadingToken == MMToken::UmbrellaKeyword) {
1768322f633cSDouglas Gregor       const DirectoryEntry *UmbrellaDir = File->getDir();
176959527666SDouglas Gregor       if (Module *UmbrellaModule = Map.UmbrellaDirs[UmbrellaDir]) {
1770b53e5483SLawrence Crowl         Diags.Report(LeadingLoc, diag::err_mmap_umbrella_clash)
177159527666SDouglas Gregor           << UmbrellaModule->getFullModuleName();
1772322f633cSDouglas Gregor         HadError = true;
17735257fc63SDouglas Gregor       } else {
1774322f633cSDouglas Gregor         // Record this umbrella header.
1775322f633cSDouglas Gregor         Map.setUmbrellaHeader(ActiveModule, File);
1776322f633cSDouglas Gregor       }
1777feb54b6dSRichard Smith     } else if (LeadingToken == MMToken::ExcludeKeyword) {
1778feb54b6dSRichard Smith       Map.excludeHeader(ActiveModule, File);
1779322f633cSDouglas Gregor     } else {
178025d50758SRichard Smith       // If there is a builtin counterpart to this file, add it now, before
178125d50758SRichard Smith       // the "real" header, so we build the built-in one first when building
178225d50758SRichard Smith       // the module.
17833ec6663bSDouglas Gregor       if (BuiltinFile)
1784b53e5483SLawrence Crowl         Map.addHeader(ActiveModule, BuiltinFile, Role);
178525d50758SRichard Smith 
1786202210b3SRichard Smith       // Record this header.
178725d50758SRichard Smith       Map.addHeader(ActiveModule, File, Role);
17885257fc63SDouglas Gregor     }
1789b53e5483SLawrence Crowl   } else if (LeadingToken != MMToken::ExcludeKeyword) {
17904b27a64bSDouglas Gregor     // Ignore excluded header files. They're optional anyway.
17914b27a64bSDouglas Gregor 
17920761a8a0SDaniel Jasper     // If we find a module that has a missing header, we mark this module as
17930761a8a0SDaniel Jasper     // unavailable and store the header directive for displaying diagnostics.
17940761a8a0SDaniel Jasper     Header.IsUmbrella = LeadingToken == MMToken::UmbrellaKeyword;
1795ec8c9752SBen Langmuir     ActiveModule->markUnavailable();
17960761a8a0SDaniel Jasper     ActiveModule->MissingHeaders.push_back(Header);
17975257fc63SDouglas Gregor   }
1798718292f2SDouglas Gregor }
1799718292f2SDouglas Gregor 
1800524e33e1SDouglas Gregor /// \brief Parse an umbrella directory declaration.
1801524e33e1SDouglas Gregor ///
1802524e33e1SDouglas Gregor ///   umbrella-dir-declaration:
1803524e33e1SDouglas Gregor ///     umbrella string-literal
1804524e33e1SDouglas Gregor void ModuleMapParser::parseUmbrellaDirDecl(SourceLocation UmbrellaLoc) {
1805524e33e1SDouglas Gregor   // Parse the directory name.
1806524e33e1SDouglas Gregor   if (!Tok.is(MMToken::StringLiteral)) {
1807524e33e1SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
1808524e33e1SDouglas Gregor       << "umbrella";
1809524e33e1SDouglas Gregor     HadError = true;
1810524e33e1SDouglas Gregor     return;
1811524e33e1SDouglas Gregor   }
1812524e33e1SDouglas Gregor 
1813524e33e1SDouglas Gregor   std::string DirName = Tok.getString();
1814524e33e1SDouglas Gregor   SourceLocation DirNameLoc = consumeToken();
1815524e33e1SDouglas Gregor 
1816524e33e1SDouglas Gregor   // Check whether we already have an umbrella.
1817524e33e1SDouglas Gregor   if (ActiveModule->Umbrella) {
1818524e33e1SDouglas Gregor     Diags.Report(DirNameLoc, diag::err_mmap_umbrella_clash)
1819524e33e1SDouglas Gregor       << ActiveModule->getFullModuleName();
1820524e33e1SDouglas Gregor     HadError = true;
1821524e33e1SDouglas Gregor     return;
1822524e33e1SDouglas Gregor   }
1823524e33e1SDouglas Gregor 
1824524e33e1SDouglas Gregor   // Look for this file.
1825d2d442caSCraig Topper   const DirectoryEntry *Dir = nullptr;
1826524e33e1SDouglas Gregor   if (llvm::sys::path::is_absolute(DirName))
1827524e33e1SDouglas Gregor     Dir = SourceMgr.getFileManager().getDirectory(DirName);
1828524e33e1SDouglas Gregor   else {
18292c1dd271SDylan Noblesmith     SmallString<128> PathName;
1830524e33e1SDouglas Gregor     PathName = Directory->getName();
1831524e33e1SDouglas Gregor     llvm::sys::path::append(PathName, DirName);
1832524e33e1SDouglas Gregor     Dir = SourceMgr.getFileManager().getDirectory(PathName);
1833524e33e1SDouglas Gregor   }
1834524e33e1SDouglas Gregor 
1835524e33e1SDouglas Gregor   if (!Dir) {
1836524e33e1SDouglas Gregor     Diags.Report(DirNameLoc, diag::err_mmap_umbrella_dir_not_found)
1837524e33e1SDouglas Gregor       << DirName;
1838524e33e1SDouglas Gregor     HadError = true;
1839524e33e1SDouglas Gregor     return;
1840524e33e1SDouglas Gregor   }
1841524e33e1SDouglas Gregor 
1842524e33e1SDouglas Gregor   if (Module *OwningModule = Map.UmbrellaDirs[Dir]) {
1843524e33e1SDouglas Gregor     Diags.Report(UmbrellaLoc, diag::err_mmap_umbrella_clash)
1844524e33e1SDouglas Gregor       << OwningModule->getFullModuleName();
1845524e33e1SDouglas Gregor     HadError = true;
1846524e33e1SDouglas Gregor     return;
1847524e33e1SDouglas Gregor   }
1848524e33e1SDouglas Gregor 
1849524e33e1SDouglas Gregor   // Record this umbrella directory.
1850524e33e1SDouglas Gregor   Map.setUmbrellaDir(ActiveModule, Dir);
1851524e33e1SDouglas Gregor }
1852524e33e1SDouglas Gregor 
18532b82c2a5SDouglas Gregor /// \brief Parse a module export declaration.
18542b82c2a5SDouglas Gregor ///
18552b82c2a5SDouglas Gregor ///   export-declaration:
18562b82c2a5SDouglas Gregor ///     'export' wildcard-module-id
18572b82c2a5SDouglas Gregor ///
18582b82c2a5SDouglas Gregor ///   wildcard-module-id:
18592b82c2a5SDouglas Gregor ///     identifier
18602b82c2a5SDouglas Gregor ///     '*'
18612b82c2a5SDouglas Gregor ///     identifier '.' wildcard-module-id
18622b82c2a5SDouglas Gregor void ModuleMapParser::parseExportDecl() {
18632b82c2a5SDouglas Gregor   assert(Tok.is(MMToken::ExportKeyword));
18642b82c2a5SDouglas Gregor   SourceLocation ExportLoc = consumeToken();
18652b82c2a5SDouglas Gregor 
18662b82c2a5SDouglas Gregor   // Parse the module-id with an optional wildcard at the end.
18672b82c2a5SDouglas Gregor   ModuleId ParsedModuleId;
18682b82c2a5SDouglas Gregor   bool Wildcard = false;
18692b82c2a5SDouglas Gregor   do {
1870306d8920SRichard Smith     // FIXME: Support string-literal module names here.
18712b82c2a5SDouglas Gregor     if (Tok.is(MMToken::Identifier)) {
18722b82c2a5SDouglas Gregor       ParsedModuleId.push_back(std::make_pair(Tok.getString(),
18732b82c2a5SDouglas Gregor                                               Tok.getLocation()));
18742b82c2a5SDouglas Gregor       consumeToken();
18752b82c2a5SDouglas Gregor 
18762b82c2a5SDouglas Gregor       if (Tok.is(MMToken::Period)) {
18772b82c2a5SDouglas Gregor         consumeToken();
18782b82c2a5SDouglas Gregor         continue;
18792b82c2a5SDouglas Gregor       }
18802b82c2a5SDouglas Gregor 
18812b82c2a5SDouglas Gregor       break;
18822b82c2a5SDouglas Gregor     }
18832b82c2a5SDouglas Gregor 
18842b82c2a5SDouglas Gregor     if(Tok.is(MMToken::Star)) {
18852b82c2a5SDouglas Gregor       Wildcard = true;
1886f5eedd05SDouglas Gregor       consumeToken();
18872b82c2a5SDouglas Gregor       break;
18882b82c2a5SDouglas Gregor     }
18892b82c2a5SDouglas Gregor 
1890ba7f2f71SDaniel Jasper     Diags.Report(Tok.getLocation(), diag::err_mmap_module_id);
18912b82c2a5SDouglas Gregor     HadError = true;
18922b82c2a5SDouglas Gregor     return;
18932b82c2a5SDouglas Gregor   } while (true);
18942b82c2a5SDouglas Gregor 
18952b82c2a5SDouglas Gregor   Module::UnresolvedExportDecl Unresolved = {
18962b82c2a5SDouglas Gregor     ExportLoc, ParsedModuleId, Wildcard
18972b82c2a5SDouglas Gregor   };
18982b82c2a5SDouglas Gregor   ActiveModule->UnresolvedExports.push_back(Unresolved);
18992b82c2a5SDouglas Gregor }
19002b82c2a5SDouglas Gregor 
1901ba7f2f71SDaniel Jasper /// \brief Parse a module uses declaration.
1902ba7f2f71SDaniel Jasper ///
1903ba7f2f71SDaniel Jasper ///   uses-declaration:
1904ba7f2f71SDaniel Jasper ///     'uses' wildcard-module-id
1905ba7f2f71SDaniel Jasper void ModuleMapParser::parseUseDecl() {
1906ba7f2f71SDaniel Jasper   assert(Tok.is(MMToken::UseKeyword));
1907ba7f2f71SDaniel Jasper   consumeToken();
1908ba7f2f71SDaniel Jasper   // Parse the module-id.
1909ba7f2f71SDaniel Jasper   ModuleId ParsedModuleId;
19103cd34c76SDaniel Jasper   parseModuleId(ParsedModuleId);
1911ba7f2f71SDaniel Jasper 
1912ba7f2f71SDaniel Jasper   ActiveModule->UnresolvedDirectUses.push_back(ParsedModuleId);
1913ba7f2f71SDaniel Jasper }
1914ba7f2f71SDaniel Jasper 
19156ddfca91SDouglas Gregor /// \brief Parse a link declaration.
19166ddfca91SDouglas Gregor ///
19176ddfca91SDouglas Gregor ///   module-declaration:
19186ddfca91SDouglas Gregor ///     'link' 'framework'[opt] string-literal
19196ddfca91SDouglas Gregor void ModuleMapParser::parseLinkDecl() {
19206ddfca91SDouglas Gregor   assert(Tok.is(MMToken::LinkKeyword));
19216ddfca91SDouglas Gregor   SourceLocation LinkLoc = consumeToken();
19226ddfca91SDouglas Gregor 
19236ddfca91SDouglas Gregor   // Parse the optional 'framework' keyword.
19246ddfca91SDouglas Gregor   bool IsFramework = false;
19256ddfca91SDouglas Gregor   if (Tok.is(MMToken::FrameworkKeyword)) {
19266ddfca91SDouglas Gregor     consumeToken();
19276ddfca91SDouglas Gregor     IsFramework = true;
19286ddfca91SDouglas Gregor   }
19296ddfca91SDouglas Gregor 
19306ddfca91SDouglas Gregor   // Parse the library name
19316ddfca91SDouglas Gregor   if (!Tok.is(MMToken::StringLiteral)) {
19326ddfca91SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_library_name)
19336ddfca91SDouglas Gregor       << IsFramework << SourceRange(LinkLoc);
19346ddfca91SDouglas Gregor     HadError = true;
19356ddfca91SDouglas Gregor     return;
19366ddfca91SDouglas Gregor   }
19376ddfca91SDouglas Gregor 
19386ddfca91SDouglas Gregor   std::string LibraryName = Tok.getString();
19396ddfca91SDouglas Gregor   consumeToken();
19406ddfca91SDouglas Gregor   ActiveModule->LinkLibraries.push_back(Module::LinkLibrary(LibraryName,
19416ddfca91SDouglas Gregor                                                             IsFramework));
19426ddfca91SDouglas Gregor }
19436ddfca91SDouglas Gregor 
194435b13eceSDouglas Gregor /// \brief Parse a configuration macro declaration.
194535b13eceSDouglas Gregor ///
194635b13eceSDouglas Gregor ///   module-declaration:
194735b13eceSDouglas Gregor ///     'config_macros' attributes[opt] config-macro-list?
194835b13eceSDouglas Gregor ///
194935b13eceSDouglas Gregor ///   config-macro-list:
195035b13eceSDouglas Gregor ///     identifier (',' identifier)?
195135b13eceSDouglas Gregor void ModuleMapParser::parseConfigMacros() {
195235b13eceSDouglas Gregor   assert(Tok.is(MMToken::ConfigMacros));
195335b13eceSDouglas Gregor   SourceLocation ConfigMacrosLoc = consumeToken();
195435b13eceSDouglas Gregor 
195535b13eceSDouglas Gregor   // Only top-level modules can have configuration macros.
195635b13eceSDouglas Gregor   if (ActiveModule->Parent) {
195735b13eceSDouglas Gregor     Diags.Report(ConfigMacrosLoc, diag::err_mmap_config_macro_submodule);
195835b13eceSDouglas Gregor   }
195935b13eceSDouglas Gregor 
196035b13eceSDouglas Gregor   // Parse the optional attributes.
196135b13eceSDouglas Gregor   Attributes Attrs;
196235b13eceSDouglas Gregor   parseOptionalAttributes(Attrs);
196335b13eceSDouglas Gregor   if (Attrs.IsExhaustive && !ActiveModule->Parent) {
196435b13eceSDouglas Gregor     ActiveModule->ConfigMacrosExhaustive = true;
196535b13eceSDouglas Gregor   }
196635b13eceSDouglas Gregor 
196735b13eceSDouglas Gregor   // If we don't have an identifier, we're done.
1968306d8920SRichard Smith   // FIXME: Support macros with the same name as a keyword here.
196935b13eceSDouglas Gregor   if (!Tok.is(MMToken::Identifier))
197035b13eceSDouglas Gregor     return;
197135b13eceSDouglas Gregor 
197235b13eceSDouglas Gregor   // Consume the first identifier.
197335b13eceSDouglas Gregor   if (!ActiveModule->Parent) {
197435b13eceSDouglas Gregor     ActiveModule->ConfigMacros.push_back(Tok.getString().str());
197535b13eceSDouglas Gregor   }
197635b13eceSDouglas Gregor   consumeToken();
197735b13eceSDouglas Gregor 
197835b13eceSDouglas Gregor   do {
197935b13eceSDouglas Gregor     // If there's a comma, consume it.
198035b13eceSDouglas Gregor     if (!Tok.is(MMToken::Comma))
198135b13eceSDouglas Gregor       break;
198235b13eceSDouglas Gregor     consumeToken();
198335b13eceSDouglas Gregor 
198435b13eceSDouglas Gregor     // We expect to see a macro name here.
1985306d8920SRichard Smith     // FIXME: Support macros with the same name as a keyword here.
198635b13eceSDouglas Gregor     if (!Tok.is(MMToken::Identifier)) {
198735b13eceSDouglas Gregor       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_config_macro);
198835b13eceSDouglas Gregor       break;
198935b13eceSDouglas Gregor     }
199035b13eceSDouglas Gregor 
199135b13eceSDouglas Gregor     // Consume the macro name.
199235b13eceSDouglas Gregor     if (!ActiveModule->Parent) {
199335b13eceSDouglas Gregor       ActiveModule->ConfigMacros.push_back(Tok.getString().str());
199435b13eceSDouglas Gregor     }
199535b13eceSDouglas Gregor     consumeToken();
199635b13eceSDouglas Gregor   } while (true);
199735b13eceSDouglas Gregor }
199835b13eceSDouglas Gregor 
1999fb912657SDouglas Gregor /// \brief Format a module-id into a string.
2000fb912657SDouglas Gregor static std::string formatModuleId(const ModuleId &Id) {
2001fb912657SDouglas Gregor   std::string result;
2002fb912657SDouglas Gregor   {
2003fb912657SDouglas Gregor     llvm::raw_string_ostream OS(result);
2004fb912657SDouglas Gregor 
2005fb912657SDouglas Gregor     for (unsigned I = 0, N = Id.size(); I != N; ++I) {
2006fb912657SDouglas Gregor       if (I)
2007fb912657SDouglas Gregor         OS << ".";
2008fb912657SDouglas Gregor       OS << Id[I].first;
2009fb912657SDouglas Gregor     }
2010fb912657SDouglas Gregor   }
2011fb912657SDouglas Gregor 
2012fb912657SDouglas Gregor   return result;
2013fb912657SDouglas Gregor }
2014fb912657SDouglas Gregor 
2015fb912657SDouglas Gregor /// \brief Parse a conflict declaration.
2016fb912657SDouglas Gregor ///
2017fb912657SDouglas Gregor ///   module-declaration:
2018fb912657SDouglas Gregor ///     'conflict' module-id ',' string-literal
2019fb912657SDouglas Gregor void ModuleMapParser::parseConflict() {
2020fb912657SDouglas Gregor   assert(Tok.is(MMToken::Conflict));
2021fb912657SDouglas Gregor   SourceLocation ConflictLoc = consumeToken();
2022fb912657SDouglas Gregor   Module::UnresolvedConflict Conflict;
2023fb912657SDouglas Gregor 
2024fb912657SDouglas Gregor   // Parse the module-id.
2025fb912657SDouglas Gregor   if (parseModuleId(Conflict.Id))
2026fb912657SDouglas Gregor     return;
2027fb912657SDouglas Gregor 
2028fb912657SDouglas Gregor   // Parse the ','.
2029fb912657SDouglas Gregor   if (!Tok.is(MMToken::Comma)) {
2030fb912657SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_conflicts_comma)
2031fb912657SDouglas Gregor       << SourceRange(ConflictLoc);
2032fb912657SDouglas Gregor     return;
2033fb912657SDouglas Gregor   }
2034fb912657SDouglas Gregor   consumeToken();
2035fb912657SDouglas Gregor 
2036fb912657SDouglas Gregor   // Parse the message.
2037fb912657SDouglas Gregor   if (!Tok.is(MMToken::StringLiteral)) {
2038fb912657SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_conflicts_message)
2039fb912657SDouglas Gregor       << formatModuleId(Conflict.Id);
2040fb912657SDouglas Gregor     return;
2041fb912657SDouglas Gregor   }
2042fb912657SDouglas Gregor   Conflict.Message = Tok.getString().str();
2043fb912657SDouglas Gregor   consumeToken();
2044fb912657SDouglas Gregor 
2045fb912657SDouglas Gregor   // Add this unresolved conflict.
2046fb912657SDouglas Gregor   ActiveModule->UnresolvedConflicts.push_back(Conflict);
2047fb912657SDouglas Gregor }
2048fb912657SDouglas Gregor 
20496ddfca91SDouglas Gregor /// \brief Parse an inferred module declaration (wildcard modules).
20509194a91dSDouglas Gregor ///
20519194a91dSDouglas Gregor ///   module-declaration:
20529194a91dSDouglas Gregor ///     'explicit'[opt] 'framework'[opt] 'module' * attributes[opt]
20539194a91dSDouglas Gregor ///       { inferred-module-member* }
20549194a91dSDouglas Gregor ///
20559194a91dSDouglas Gregor ///   inferred-module-member:
20569194a91dSDouglas Gregor ///     'export' '*'
20579194a91dSDouglas Gregor ///     'exclude' identifier
20589194a91dSDouglas Gregor void ModuleMapParser::parseInferredModuleDecl(bool Framework, bool Explicit) {
205973441091SDouglas Gregor   assert(Tok.is(MMToken::Star));
206073441091SDouglas Gregor   SourceLocation StarLoc = consumeToken();
206173441091SDouglas Gregor   bool Failed = false;
206273441091SDouglas Gregor 
206373441091SDouglas Gregor   // Inferred modules must be submodules.
20649194a91dSDouglas Gregor   if (!ActiveModule && !Framework) {
206573441091SDouglas Gregor     Diags.Report(StarLoc, diag::err_mmap_top_level_inferred_submodule);
206673441091SDouglas Gregor     Failed = true;
206773441091SDouglas Gregor   }
206873441091SDouglas Gregor 
20699194a91dSDouglas Gregor   if (ActiveModule) {
2070524e33e1SDouglas Gregor     // Inferred modules must have umbrella directories.
20714898cde4SBen Langmuir     if (!Failed && ActiveModule->IsAvailable &&
20724898cde4SBen Langmuir         !ActiveModule->getUmbrellaDir()) {
207373441091SDouglas Gregor       Diags.Report(StarLoc, diag::err_mmap_inferred_no_umbrella);
207473441091SDouglas Gregor       Failed = true;
207573441091SDouglas Gregor     }
207673441091SDouglas Gregor 
207773441091SDouglas Gregor     // Check for redefinition of an inferred module.
2078dd005f69SDouglas Gregor     if (!Failed && ActiveModule->InferSubmodules) {
207973441091SDouglas Gregor       Diags.Report(StarLoc, diag::err_mmap_inferred_redef);
2080dd005f69SDouglas Gregor       if (ActiveModule->InferredSubmoduleLoc.isValid())
2081dd005f69SDouglas Gregor         Diags.Report(ActiveModule->InferredSubmoduleLoc,
208273441091SDouglas Gregor                      diag::note_mmap_prev_definition);
208373441091SDouglas Gregor       Failed = true;
208473441091SDouglas Gregor     }
208573441091SDouglas Gregor 
20869194a91dSDouglas Gregor     // Check for the 'framework' keyword, which is not permitted here.
20879194a91dSDouglas Gregor     if (Framework) {
20889194a91dSDouglas Gregor       Diags.Report(StarLoc, diag::err_mmap_inferred_framework_submodule);
20899194a91dSDouglas Gregor       Framework = false;
20909194a91dSDouglas Gregor     }
20919194a91dSDouglas Gregor   } else if (Explicit) {
20929194a91dSDouglas Gregor     Diags.Report(StarLoc, diag::err_mmap_explicit_inferred_framework);
20939194a91dSDouglas Gregor     Explicit = false;
20949194a91dSDouglas Gregor   }
20959194a91dSDouglas Gregor 
209673441091SDouglas Gregor   // If there were any problems with this inferred submodule, skip its body.
209773441091SDouglas Gregor   if (Failed) {
209873441091SDouglas Gregor     if (Tok.is(MMToken::LBrace)) {
209973441091SDouglas Gregor       consumeToken();
210073441091SDouglas Gregor       skipUntil(MMToken::RBrace);
210173441091SDouglas Gregor       if (Tok.is(MMToken::RBrace))
210273441091SDouglas Gregor         consumeToken();
210373441091SDouglas Gregor     }
210473441091SDouglas Gregor     HadError = true;
210573441091SDouglas Gregor     return;
210673441091SDouglas Gregor   }
210773441091SDouglas Gregor 
21089194a91dSDouglas Gregor   // Parse optional attributes.
21094442605fSBill Wendling   Attributes Attrs;
21109194a91dSDouglas Gregor   parseOptionalAttributes(Attrs);
21119194a91dSDouglas Gregor 
21129194a91dSDouglas Gregor   if (ActiveModule) {
211373441091SDouglas Gregor     // Note that we have an inferred submodule.
2114dd005f69SDouglas Gregor     ActiveModule->InferSubmodules = true;
2115dd005f69SDouglas Gregor     ActiveModule->InferredSubmoduleLoc = StarLoc;
2116dd005f69SDouglas Gregor     ActiveModule->InferExplicitSubmodules = Explicit;
21179194a91dSDouglas Gregor   } else {
21189194a91dSDouglas Gregor     // We'll be inferring framework modules for this directory.
21199194a91dSDouglas Gregor     Map.InferredDirectories[Directory].InferModules = true;
21209194a91dSDouglas Gregor     Map.InferredDirectories[Directory].InferSystemModules = Attrs.IsSystem;
2121beee15e7SBen Langmuir     Map.InferredDirectories[Directory].ModuleMapFile = ModuleMapFile;
2122131daca0SRichard Smith     // FIXME: Handle the 'framework' keyword.
21239194a91dSDouglas Gregor   }
212473441091SDouglas Gregor 
212573441091SDouglas Gregor   // Parse the opening brace.
212673441091SDouglas Gregor   if (!Tok.is(MMToken::LBrace)) {
212773441091SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_lbrace_wildcard);
212873441091SDouglas Gregor     HadError = true;
212973441091SDouglas Gregor     return;
213073441091SDouglas Gregor   }
213173441091SDouglas Gregor   SourceLocation LBraceLoc = consumeToken();
213273441091SDouglas Gregor 
213373441091SDouglas Gregor   // Parse the body of the inferred submodule.
213473441091SDouglas Gregor   bool Done = false;
213573441091SDouglas Gregor   do {
213673441091SDouglas Gregor     switch (Tok.Kind) {
213773441091SDouglas Gregor     case MMToken::EndOfFile:
213873441091SDouglas Gregor     case MMToken::RBrace:
213973441091SDouglas Gregor       Done = true;
214073441091SDouglas Gregor       break;
214173441091SDouglas Gregor 
21429194a91dSDouglas Gregor     case MMToken::ExcludeKeyword: {
21439194a91dSDouglas Gregor       if (ActiveModule) {
21449194a91dSDouglas Gregor         Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member)
2145d2d442caSCraig Topper           << (ActiveModule != nullptr);
21469194a91dSDouglas Gregor         consumeToken();
21479194a91dSDouglas Gregor         break;
21489194a91dSDouglas Gregor       }
21499194a91dSDouglas Gregor 
21509194a91dSDouglas Gregor       consumeToken();
2151306d8920SRichard Smith       // FIXME: Support string-literal module names here.
21529194a91dSDouglas Gregor       if (!Tok.is(MMToken::Identifier)) {
21539194a91dSDouglas Gregor         Diags.Report(Tok.getLocation(), diag::err_mmap_missing_exclude_name);
21549194a91dSDouglas Gregor         break;
21559194a91dSDouglas Gregor       }
21569194a91dSDouglas Gregor 
21579194a91dSDouglas Gregor       Map.InferredDirectories[Directory].ExcludedModules
21589194a91dSDouglas Gregor         .push_back(Tok.getString());
21599194a91dSDouglas Gregor       consumeToken();
21609194a91dSDouglas Gregor       break;
21619194a91dSDouglas Gregor     }
21629194a91dSDouglas Gregor 
21639194a91dSDouglas Gregor     case MMToken::ExportKeyword:
21649194a91dSDouglas Gregor       if (!ActiveModule) {
21659194a91dSDouglas Gregor         Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member)
2166d2d442caSCraig Topper           << (ActiveModule != nullptr);
21679194a91dSDouglas Gregor         consumeToken();
21689194a91dSDouglas Gregor         break;
21699194a91dSDouglas Gregor       }
21709194a91dSDouglas Gregor 
217173441091SDouglas Gregor       consumeToken();
217273441091SDouglas Gregor       if (Tok.is(MMToken::Star))
2173dd005f69SDouglas Gregor         ActiveModule->InferExportWildcard = true;
217473441091SDouglas Gregor       else
217573441091SDouglas Gregor         Diags.Report(Tok.getLocation(),
217673441091SDouglas Gregor                      diag::err_mmap_expected_export_wildcard);
217773441091SDouglas Gregor       consumeToken();
217873441091SDouglas Gregor       break;
217973441091SDouglas Gregor 
218073441091SDouglas Gregor     case MMToken::ExplicitKeyword:
218173441091SDouglas Gregor     case MMToken::ModuleKeyword:
218273441091SDouglas Gregor     case MMToken::HeaderKeyword:
2183b53e5483SLawrence Crowl     case MMToken::PrivateKeyword:
218473441091SDouglas Gregor     case MMToken::UmbrellaKeyword:
218573441091SDouglas Gregor     default:
21869194a91dSDouglas Gregor       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member)
2187d2d442caSCraig Topper           << (ActiveModule != nullptr);
218873441091SDouglas Gregor       consumeToken();
218973441091SDouglas Gregor       break;
219073441091SDouglas Gregor     }
219173441091SDouglas Gregor   } while (!Done);
219273441091SDouglas Gregor 
219373441091SDouglas Gregor   if (Tok.is(MMToken::RBrace))
219473441091SDouglas Gregor     consumeToken();
219573441091SDouglas Gregor   else {
219673441091SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
219773441091SDouglas Gregor     Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
219873441091SDouglas Gregor     HadError = true;
219973441091SDouglas Gregor   }
220073441091SDouglas Gregor }
220173441091SDouglas Gregor 
22029194a91dSDouglas Gregor /// \brief Parse optional attributes.
22039194a91dSDouglas Gregor ///
22049194a91dSDouglas Gregor ///   attributes:
22059194a91dSDouglas Gregor ///     attribute attributes
22069194a91dSDouglas Gregor ///     attribute
22079194a91dSDouglas Gregor ///
22089194a91dSDouglas Gregor ///   attribute:
22099194a91dSDouglas Gregor ///     [ identifier ]
22109194a91dSDouglas Gregor ///
22119194a91dSDouglas Gregor /// \param Attrs Will be filled in with the parsed attributes.
22129194a91dSDouglas Gregor ///
22139194a91dSDouglas Gregor /// \returns true if an error occurred, false otherwise.
22144442605fSBill Wendling bool ModuleMapParser::parseOptionalAttributes(Attributes &Attrs) {
22159194a91dSDouglas Gregor   bool HadError = false;
22169194a91dSDouglas Gregor 
22179194a91dSDouglas Gregor   while (Tok.is(MMToken::LSquare)) {
22189194a91dSDouglas Gregor     // Consume the '['.
22199194a91dSDouglas Gregor     SourceLocation LSquareLoc = consumeToken();
22209194a91dSDouglas Gregor 
22219194a91dSDouglas Gregor     // Check whether we have an attribute name here.
22229194a91dSDouglas Gregor     if (!Tok.is(MMToken::Identifier)) {
22239194a91dSDouglas Gregor       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_attribute);
22249194a91dSDouglas Gregor       skipUntil(MMToken::RSquare);
22259194a91dSDouglas Gregor       if (Tok.is(MMToken::RSquare))
22269194a91dSDouglas Gregor         consumeToken();
22279194a91dSDouglas Gregor       HadError = true;
22289194a91dSDouglas Gregor     }
22299194a91dSDouglas Gregor 
22309194a91dSDouglas Gregor     // Decode the attribute name.
22319194a91dSDouglas Gregor     AttributeKind Attribute
22329194a91dSDouglas Gregor       = llvm::StringSwitch<AttributeKind>(Tok.getString())
223335b13eceSDouglas Gregor           .Case("exhaustive", AT_exhaustive)
223477944868SRichard Smith           .Case("extern_c", AT_extern_c)
22359194a91dSDouglas Gregor           .Case("system", AT_system)
22369194a91dSDouglas Gregor           .Default(AT_unknown);
22379194a91dSDouglas Gregor     switch (Attribute) {
22389194a91dSDouglas Gregor     case AT_unknown:
22399194a91dSDouglas Gregor       Diags.Report(Tok.getLocation(), diag::warn_mmap_unknown_attribute)
22409194a91dSDouglas Gregor         << Tok.getString();
22419194a91dSDouglas Gregor       break;
22429194a91dSDouglas Gregor 
22439194a91dSDouglas Gregor     case AT_system:
22449194a91dSDouglas Gregor       Attrs.IsSystem = true;
22459194a91dSDouglas Gregor       break;
224635b13eceSDouglas Gregor 
224777944868SRichard Smith     case AT_extern_c:
224877944868SRichard Smith       Attrs.IsExternC = true;
224977944868SRichard Smith       break;
225077944868SRichard Smith 
225135b13eceSDouglas Gregor     case AT_exhaustive:
225235b13eceSDouglas Gregor       Attrs.IsExhaustive = true;
225335b13eceSDouglas Gregor       break;
22549194a91dSDouglas Gregor     }
22559194a91dSDouglas Gregor     consumeToken();
22569194a91dSDouglas Gregor 
22579194a91dSDouglas Gregor     // Consume the ']'.
22589194a91dSDouglas Gregor     if (!Tok.is(MMToken::RSquare)) {
22599194a91dSDouglas Gregor       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rsquare);
22609194a91dSDouglas Gregor       Diags.Report(LSquareLoc, diag::note_mmap_lsquare_match);
22619194a91dSDouglas Gregor       skipUntil(MMToken::RSquare);
22629194a91dSDouglas Gregor       HadError = true;
22639194a91dSDouglas Gregor     }
22649194a91dSDouglas Gregor 
22659194a91dSDouglas Gregor     if (Tok.is(MMToken::RSquare))
22669194a91dSDouglas Gregor       consumeToken();
22679194a91dSDouglas Gregor   }
22689194a91dSDouglas Gregor 
22699194a91dSDouglas Gregor   return HadError;
22709194a91dSDouglas Gregor }
22719194a91dSDouglas Gregor 
2272718292f2SDouglas Gregor /// \brief Parse a module map file.
2273718292f2SDouglas Gregor ///
2274718292f2SDouglas Gregor ///   module-map-file:
2275718292f2SDouglas Gregor ///     module-declaration*
2276718292f2SDouglas Gregor bool ModuleMapParser::parseModuleMapFile() {
2277718292f2SDouglas Gregor   do {
2278718292f2SDouglas Gregor     switch (Tok.Kind) {
2279718292f2SDouglas Gregor     case MMToken::EndOfFile:
2280718292f2SDouglas Gregor       return HadError;
2281718292f2SDouglas Gregor 
2282e7ab3669SDouglas Gregor     case MMToken::ExplicitKeyword:
228397292843SDaniel Jasper     case MMToken::ExternKeyword:
2284718292f2SDouglas Gregor     case MMToken::ModuleKeyword:
2285755b2055SDouglas Gregor     case MMToken::FrameworkKeyword:
2286718292f2SDouglas Gregor       parseModuleDecl();
2287718292f2SDouglas Gregor       break;
2288718292f2SDouglas Gregor 
22891fb5c3a6SDouglas Gregor     case MMToken::Comma:
229035b13eceSDouglas Gregor     case MMToken::ConfigMacros:
2291fb912657SDouglas Gregor     case MMToken::Conflict:
2292a3feee2aSRichard Smith     case MMToken::Exclaim:
229359527666SDouglas Gregor     case MMToken::ExcludeKeyword:
22942b82c2a5SDouglas Gregor     case MMToken::ExportKeyword:
2295718292f2SDouglas Gregor     case MMToken::HeaderKeyword:
2296718292f2SDouglas Gregor     case MMToken::Identifier:
2297718292f2SDouglas Gregor     case MMToken::LBrace:
22986ddfca91SDouglas Gregor     case MMToken::LinkKeyword:
2299a686e1b0SDouglas Gregor     case MMToken::LSquare:
23002b82c2a5SDouglas Gregor     case MMToken::Period:
2301b53e5483SLawrence Crowl     case MMToken::PrivateKeyword:
2302718292f2SDouglas Gregor     case MMToken::RBrace:
2303a686e1b0SDouglas Gregor     case MMToken::RSquare:
23041fb5c3a6SDouglas Gregor     case MMToken::RequiresKeyword:
23052b82c2a5SDouglas Gregor     case MMToken::Star:
2306718292f2SDouglas Gregor     case MMToken::StringLiteral:
2307b8afebe2SRichard Smith     case MMToken::TextualKeyword:
2308718292f2SDouglas Gregor     case MMToken::UmbrellaKeyword:
2309ba7f2f71SDaniel Jasper     case MMToken::UseKeyword:
2310718292f2SDouglas Gregor       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module);
2311718292f2SDouglas Gregor       HadError = true;
2312718292f2SDouglas Gregor       consumeToken();
2313718292f2SDouglas Gregor       break;
2314718292f2SDouglas Gregor     }
2315718292f2SDouglas Gregor   } while (true);
2316718292f2SDouglas Gregor }
2317718292f2SDouglas Gregor 
2318963c5535SDouglas Gregor bool ModuleMap::parseModuleMapFile(const FileEntry *File, bool IsSystem) {
23194ddf2221SDouglas Gregor   llvm::DenseMap<const FileEntry *, bool>::iterator Known
23204ddf2221SDouglas Gregor     = ParsedModuleMap.find(File);
23214ddf2221SDouglas Gregor   if (Known != ParsedModuleMap.end())
23224ddf2221SDouglas Gregor     return Known->second;
23234ddf2221SDouglas Gregor 
2324d2d442caSCraig Topper   assert(Target && "Missing target information");
2325cb69b57bSBen Langmuir   auto FileCharacter = IsSystem ? SrcMgr::C_System : SrcMgr::C_User;
2326cb69b57bSBen Langmuir   FileID ID = SourceMgr.createFileID(File, SourceLocation(), FileCharacter);
23271f76c4e8SManuel Klimek   const llvm::MemoryBuffer *Buffer = SourceMgr.getBuffer(ID);
2328718292f2SDouglas Gregor   if (!Buffer)
23294ddf2221SDouglas Gregor     return ParsedModuleMap[File] = true;
2330718292f2SDouglas Gregor 
2331984e1df7SBen Langmuir   // Find the directory for the module. For frameworks, that may require going
2332984e1df7SBen Langmuir   // up from the 'Modules' directory.
2333984e1df7SBen Langmuir   const DirectoryEntry *Dir = File->getDir();
2334984e1df7SBen Langmuir   StringRef DirName(Dir->getName());
2335984e1df7SBen Langmuir   if (llvm::sys::path::filename(DirName) == "Modules") {
2336984e1df7SBen Langmuir     DirName = llvm::sys::path::parent_path(DirName);
2337984e1df7SBen Langmuir     if (DirName.endswith(".framework"))
2338984e1df7SBen Langmuir       Dir = SourceMgr.getFileManager().getDirectory(DirName);
2339984e1df7SBen Langmuir     assert(Dir && "parent must exist");
2340984e1df7SBen Langmuir   }
2341984e1df7SBen Langmuir 
2342718292f2SDouglas Gregor   // Parse this module map file.
23431f76c4e8SManuel Klimek   Lexer L(ID, SourceMgr.getBuffer(ID), SourceMgr, MMapLangOpts);
2344beee15e7SBen Langmuir   ModuleMapParser Parser(L, SourceMgr, Target, Diags, *this, File, Dir,
2345963c5535SDouglas Gregor                          BuiltinIncludeDir, IsSystem);
2346718292f2SDouglas Gregor   bool Result = Parser.parseModuleMapFile();
23474ddf2221SDouglas Gregor   ParsedModuleMap[File] = Result;
2348718292f2SDouglas Gregor   return Result;
2349718292f2SDouglas Gregor }
2350