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 
20592669ee4SDaniel Jasper // 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) {
21792669ee4SDaniel Jasper   #ifndef NDEBUG
21892669ee4SDaniel Jasper   // Check for consistency between the module header role
21992669ee4SDaniel Jasper   // as obtained from the lookup and as obtained from the module.
22092669ee4SDaniel Jasper   // This check is not cheap, so enable it only for debugging.
22192669ee4SDaniel Jasper   SmallVectorImpl<const FileEntry *> &PvtHdrs
22292669ee4SDaniel Jasper       = RequestedModule->PrivateHeaders;
22392669ee4SDaniel Jasper   SmallVectorImpl<const FileEntry *>::iterator Look
22492669ee4SDaniel Jasper       = std::find(PvtHdrs.begin(), PvtHdrs.end(), IncFileEnt);
22592669ee4SDaniel Jasper   bool IsPrivate = Look != PvtHdrs.end();
22692669ee4SDaniel Jasper   assert((IsPrivate && Role == ModuleMap::PrivateHeader)
22792669ee4SDaniel Jasper                || (!IsPrivate && Role != ModuleMap::PrivateHeader));
22892669ee4SDaniel Jasper   #endif
22992669ee4SDaniel Jasper   return Role == ModuleMap::PrivateHeader &&
23092669ee4SDaniel Jasper          RequestedModule->getTopLevelModule() != RequestingModule;
23192669ee4SDaniel Jasper }
23292669ee4SDaniel Jasper 
23371e1a64fSBen Langmuir static Module *getTopLevelOrNull(Module *M) {
23471e1a64fSBen Langmuir   return M ? M->getTopLevelModule() : nullptr;
23571e1a64fSBen Langmuir }
23671e1a64fSBen Langmuir 
23792669ee4SDaniel Jasper void ModuleMap::diagnoseHeaderInclusion(Module *RequestingModule,
23892669ee4SDaniel Jasper                                         SourceLocation FilenameLoc,
23992669ee4SDaniel Jasper                                         StringRef Filename,
24092669ee4SDaniel Jasper                                         const FileEntry *File) {
24192669ee4SDaniel Jasper   // No errors for indirect modules. This may be a bit of a problem for modules
24292669ee4SDaniel Jasper   // with no source files.
24371e1a64fSBen Langmuir   if (getTopLevelOrNull(RequestingModule) != getTopLevelOrNull(SourceModule))
24492669ee4SDaniel Jasper     return;
24592669ee4SDaniel Jasper 
24692669ee4SDaniel Jasper   if (RequestingModule)
24792669ee4SDaniel Jasper     resolveUses(RequestingModule, /*Complain=*/false);
24892669ee4SDaniel Jasper 
24971e1a64fSBen Langmuir   bool Excluded = false;
250d2d442caSCraig Topper   Module *Private = nullptr;
251d2d442caSCraig Topper   Module *NotUsed = nullptr;
25271e1a64fSBen Langmuir 
25371e1a64fSBen Langmuir   HeadersMap::iterator Known = findKnownHeader(File);
25471e1a64fSBen Langmuir   if (Known != Headers.end()) {
25571e1a64fSBen Langmuir     for (const KnownHeader &Header : Known->second) {
25692669ee4SDaniel Jasper       // Excluded headers don't really belong to a module.
25771e1a64fSBen Langmuir       if (Header.getRole() == ModuleMap::ExcludedHeader) {
25871e1a64fSBen Langmuir         Excluded = true;
25992669ee4SDaniel Jasper         continue;
26071e1a64fSBen Langmuir       }
26192669ee4SDaniel Jasper 
26292669ee4SDaniel Jasper       // If 'File' is part of 'RequestingModule' we can definitely include it.
26371e1a64fSBen Langmuir       if (Header.getModule() == RequestingModule)
26492669ee4SDaniel Jasper         return;
26592669ee4SDaniel Jasper 
26692669ee4SDaniel Jasper       // Remember private headers for later printing of a diagnostic.
26771e1a64fSBen Langmuir       if (violatesPrivateInclude(RequestingModule, File, Header.getRole(),
26871e1a64fSBen Langmuir                                  Header.getModule())) {
26971e1a64fSBen Langmuir         Private = Header.getModule();
27092669ee4SDaniel Jasper         continue;
27192669ee4SDaniel Jasper       }
27292669ee4SDaniel Jasper 
27392669ee4SDaniel Jasper       // If uses need to be specified explicitly, we are only allowed to return
27492669ee4SDaniel Jasper       // modules that are explicitly used by the requesting module.
27592669ee4SDaniel Jasper       if (RequestingModule && LangOpts.ModulesDeclUse &&
27671e1a64fSBen Langmuir           !directlyUses(RequestingModule, Header.getModule())) {
27771e1a64fSBen Langmuir         NotUsed = Header.getModule();
27892669ee4SDaniel Jasper         continue;
27992669ee4SDaniel Jasper       }
28092669ee4SDaniel Jasper 
28192669ee4SDaniel Jasper       // We have found a module that we can happily use.
28292669ee4SDaniel Jasper       return;
28392669ee4SDaniel Jasper     }
28471e1a64fSBen Langmuir   }
28592669ee4SDaniel Jasper 
28692669ee4SDaniel Jasper   // We have found a header, but it is private.
287d2d442caSCraig Topper   if (Private) {
28892669ee4SDaniel Jasper     Diags.Report(FilenameLoc, diag::error_use_of_private_header_outside_module)
28992669ee4SDaniel Jasper         << Filename;
29092669ee4SDaniel Jasper     return;
29192669ee4SDaniel Jasper   }
29292669ee4SDaniel Jasper 
29392669ee4SDaniel Jasper   // We have found a module, but we don't use it.
294d2d442caSCraig Topper   if (NotUsed) {
29592669ee4SDaniel Jasper     Diags.Report(FilenameLoc, diag::error_undeclared_use_of_module)
29692669ee4SDaniel Jasper         << RequestingModule->getFullModuleName() << Filename;
29792669ee4SDaniel Jasper     return;
29892669ee4SDaniel Jasper   }
29992669ee4SDaniel Jasper 
30071e1a64fSBen Langmuir   if (Excluded || isHeaderInUmbrellaDirs(File))
30171e1a64fSBen Langmuir     return;
30271e1a64fSBen Langmuir 
30371e1a64fSBen Langmuir   // At this point, only non-modular includes remain.
30471e1a64fSBen Langmuir 
30571e1a64fSBen Langmuir   if (LangOpts.ModulesStrictDeclUse) {
30671e1a64fSBen Langmuir     Diags.Report(FilenameLoc, diag::error_undeclared_use_of_module)
30771e1a64fSBen Langmuir         << RequestingModule->getFullModuleName() << Filename;
30871e1a64fSBen Langmuir   } else if (RequestingModule) {
30971e1a64fSBen Langmuir     diag::kind DiagID = RequestingModule->getTopLevelModule()->IsFramework ?
31071e1a64fSBen Langmuir         diag::warn_non_modular_include_in_framework_module :
31171e1a64fSBen Langmuir         diag::warn_non_modular_include_in_module;
31271e1a64fSBen Langmuir     Diags.Report(FilenameLoc, DiagID) << RequestingModule->getFullModuleName();
31371e1a64fSBen Langmuir   }
31492669ee4SDaniel Jasper }
31592669ee4SDaniel Jasper 
31692669ee4SDaniel Jasper ModuleMap::KnownHeader
31792669ee4SDaniel Jasper ModuleMap::findModuleForHeader(const FileEntry *File,
31892669ee4SDaniel Jasper                                Module *RequestingModule) {
31992669ee4SDaniel Jasper   HeadersMap::iterator Known = findKnownHeader(File);
3204eaf0a6cSDaniel Jasper 
3211fb5c3a6SDouglas Gregor   if (Known != Headers.end()) {
32297da9178SDaniel Jasper     ModuleMap::KnownHeader Result = KnownHeader();
3231fb5c3a6SDouglas Gregor 
32497da9178SDaniel Jasper     // Iterate over all modules that 'File' is part of to find the best fit.
32597da9178SDaniel Jasper     for (SmallVectorImpl<KnownHeader>::iterator I = Known->second.begin(),
32697da9178SDaniel Jasper                                                 E = Known->second.end();
32797da9178SDaniel Jasper          I != E; ++I) {
3284eaf0a6cSDaniel Jasper       // Cannot use a module if the header is excluded in it.
3294eaf0a6cSDaniel Jasper       if (I->getRole() == ModuleMap::ExcludedHeader)
3304eaf0a6cSDaniel Jasper         continue;
3314eaf0a6cSDaniel Jasper 
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)
33997da9178SDaniel Jasper         return *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 
34797da9178SDaniel Jasper       Result = *I;
34897da9178SDaniel Jasper       // If 'File' is a public header of this module, this is as good as we
34997da9178SDaniel Jasper       // are going to get.
3508c71eba1SRichard Smith       // FIXME: If we have a RequestingModule, we should prefer the header from
3518c71eba1SRichard Smith       // that module.
35297da9178SDaniel Jasper       if (I->getRole() == ModuleMap::NormalHeader)
35397da9178SDaniel Jasper         break;
35497da9178SDaniel Jasper     }
35597da9178SDaniel Jasper     return Result;
3561fb5c3a6SDouglas Gregor   }
357ab0c8a84SDouglas Gregor 
358f857950dSDmitri Gribenko   SmallVector<const DirectoryEntry *, 2> SkippedDirs;
3594469138eSBen Langmuir   KnownHeader H = findHeaderInUmbrellaDirs(File, SkippedDirs);
3604469138eSBen Langmuir   if (H) {
3614469138eSBen Langmuir     Module *Result = H.getModule();
362930a85ccSDouglas Gregor 
363930a85ccSDouglas Gregor     // Search up the module stack until we find a module with an umbrella
36473141fa9SDouglas Gregor     // directory.
365930a85ccSDouglas Gregor     Module *UmbrellaModule = Result;
36673141fa9SDouglas Gregor     while (!UmbrellaModule->getUmbrellaDir() && UmbrellaModule->Parent)
367930a85ccSDouglas Gregor       UmbrellaModule = UmbrellaModule->Parent;
368930a85ccSDouglas Gregor 
369930a85ccSDouglas Gregor     if (UmbrellaModule->InferSubmodules) {
370a89c5ac4SDouglas Gregor       // Infer submodules for each of the directories we found between
371a89c5ac4SDouglas Gregor       // the directory of the umbrella header and the directory where
372a89c5ac4SDouglas Gregor       // the actual header is located.
3739458f82dSDouglas Gregor       bool Explicit = UmbrellaModule->InferExplicitSubmodules;
3749458f82dSDouglas Gregor 
3757033127bSDouglas Gregor       for (unsigned I = SkippedDirs.size(); I != 0; --I) {
376a89c5ac4SDouglas Gregor         // Find or create the module that corresponds to this directory name.
377056396aeSDouglas Gregor         SmallString<32> NameBuf;
378056396aeSDouglas Gregor         StringRef Name = sanitizeFilenameAsIdentifier(
3794469138eSBen Langmuir             llvm::sys::path::stem(SkippedDirs[I-1]->getName()), NameBuf);
380beee15e7SBen Langmuir         Result = findOrCreateModule(Name, Result, UmbrellaModule->ModuleMap,
381beee15e7SBen Langmuir                                     /*IsFramework=*/false, Explicit).first;
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);
397beee15e7SBen Langmuir       Result = findOrCreateModule(Name, Result, UmbrellaModule->ModuleMap,
398beee15e7SBen Langmuir                                   /*IsFramework=*/false, Explicit).first;
399ffbafa2aSBen Langmuir       Result->IsInferred = true;
4003c5305c1SArgyrios Kyrtzidis       Result->addTopHeader(File);
401a89c5ac4SDouglas Gregor 
402a89c5ac4SDouglas Gregor       // If inferred submodules export everything they import, add a
403a89c5ac4SDouglas Gregor       // wildcard to the set of exports.
404930a85ccSDouglas Gregor       if (UmbrellaModule->InferExportWildcard && Result->Exports.empty())
405d2d442caSCraig Topper         Result->Exports.push_back(Module::ExportDecl(nullptr, true));
406a89c5ac4SDouglas Gregor     } else {
407a89c5ac4SDouglas Gregor       // Record each of the directories we stepped through as being part of
408a89c5ac4SDouglas Gregor       // the module we found, since the umbrella header covers them all.
409a89c5ac4SDouglas Gregor       for (unsigned I = 0, N = SkippedDirs.size(); I != N; ++I)
410a89c5ac4SDouglas Gregor         UmbrellaDirs[SkippedDirs[I]] = Result;
411a89c5ac4SDouglas Gregor     }
412a89c5ac4SDouglas Gregor 
41397da9178SDaniel Jasper     Headers[File].push_back(KnownHeader(Result, NormalHeader));
4141fb5c3a6SDouglas Gregor 
4151fb5c3a6SDouglas Gregor     // If a header corresponds to an unavailable module, don't report
4161fb5c3a6SDouglas Gregor     // that it maps to anything.
4171fb5c3a6SDouglas Gregor     if (!Result->isAvailable())
418b53e5483SLawrence Crowl       return KnownHeader();
4191fb5c3a6SDouglas Gregor 
42097da9178SDaniel Jasper     return Headers[File].back();
421a89c5ac4SDouglas Gregor   }
422a89c5ac4SDouglas Gregor 
423b53e5483SLawrence Crowl   return KnownHeader();
424ab0c8a84SDouglas Gregor }
425ab0c8a84SDouglas Gregor 
426e4412640SArgyrios Kyrtzidis bool ModuleMap::isHeaderInUnavailableModule(const FileEntry *Header) const {
427d2d442caSCraig Topper   return isHeaderUnavailableInModule(Header, nullptr);
42850996ce1SRichard Smith }
42950996ce1SRichard Smith 
43062bcd925SDmitri Gribenko bool
43162bcd925SDmitri Gribenko ModuleMap::isHeaderUnavailableInModule(const FileEntry *Header,
43262bcd925SDmitri Gribenko                                        const Module *RequestingModule) const {
433e4412640SArgyrios Kyrtzidis   HeadersMap::const_iterator Known = Headers.find(Header);
43497da9178SDaniel Jasper   if (Known != Headers.end()) {
43597da9178SDaniel Jasper     for (SmallVectorImpl<KnownHeader>::const_iterator
43697da9178SDaniel Jasper              I = Known->second.begin(),
43797da9178SDaniel Jasper              E = Known->second.end();
43897da9178SDaniel Jasper          I != E; ++I) {
43950996ce1SRichard Smith       if (I->isAvailable() && (!RequestingModule ||
44050996ce1SRichard Smith                                I->getModule()->isSubModuleOf(RequestingModule)))
44197da9178SDaniel Jasper         return false;
44297da9178SDaniel Jasper     }
44397da9178SDaniel Jasper     return true;
44497da9178SDaniel Jasper   }
4451fb5c3a6SDouglas Gregor 
4461fb5c3a6SDouglas Gregor   const DirectoryEntry *Dir = Header->getDir();
447f857950dSDmitri Gribenko   SmallVector<const DirectoryEntry *, 2> SkippedDirs;
4481fb5c3a6SDouglas Gregor   StringRef DirName = Dir->getName();
4491fb5c3a6SDouglas Gregor 
45050996ce1SRichard Smith   auto IsUnavailable = [&](const Module *M) {
45150996ce1SRichard Smith     return !M->isAvailable() && (!RequestingModule ||
45250996ce1SRichard Smith                                  M->isSubModuleOf(RequestingModule));
45350996ce1SRichard Smith   };
45450996ce1SRichard Smith 
4551fb5c3a6SDouglas Gregor   // Keep walking up the directory hierarchy, looking for a directory with
4561fb5c3a6SDouglas Gregor   // an umbrella header.
4571fb5c3a6SDouglas Gregor   do {
458e4412640SArgyrios Kyrtzidis     llvm::DenseMap<const DirectoryEntry *, Module *>::const_iterator KnownDir
4591fb5c3a6SDouglas Gregor       = UmbrellaDirs.find(Dir);
4601fb5c3a6SDouglas Gregor     if (KnownDir != UmbrellaDirs.end()) {
4611fb5c3a6SDouglas Gregor       Module *Found = KnownDir->second;
46250996ce1SRichard Smith       if (IsUnavailable(Found))
4631fb5c3a6SDouglas Gregor         return true;
4641fb5c3a6SDouglas Gregor 
4651fb5c3a6SDouglas Gregor       // Search up the module stack until we find a module with an umbrella
4661fb5c3a6SDouglas Gregor       // directory.
4671fb5c3a6SDouglas Gregor       Module *UmbrellaModule = Found;
4681fb5c3a6SDouglas Gregor       while (!UmbrellaModule->getUmbrellaDir() && UmbrellaModule->Parent)
4691fb5c3a6SDouglas Gregor         UmbrellaModule = UmbrellaModule->Parent;
4701fb5c3a6SDouglas Gregor 
4711fb5c3a6SDouglas Gregor       if (UmbrellaModule->InferSubmodules) {
4721fb5c3a6SDouglas Gregor         for (unsigned I = SkippedDirs.size(); I != 0; --I) {
4731fb5c3a6SDouglas Gregor           // Find or create the module that corresponds to this directory name.
474056396aeSDouglas Gregor           SmallString<32> NameBuf;
475056396aeSDouglas Gregor           StringRef Name = sanitizeFilenameAsIdentifier(
476056396aeSDouglas Gregor                              llvm::sys::path::stem(SkippedDirs[I-1]->getName()),
477056396aeSDouglas Gregor                              NameBuf);
4781fb5c3a6SDouglas Gregor           Found = lookupModuleQualified(Name, Found);
4791fb5c3a6SDouglas Gregor           if (!Found)
4801fb5c3a6SDouglas Gregor             return false;
48150996ce1SRichard Smith           if (IsUnavailable(Found))
4821fb5c3a6SDouglas Gregor             return true;
4831fb5c3a6SDouglas Gregor         }
4841fb5c3a6SDouglas Gregor 
4851fb5c3a6SDouglas Gregor         // Infer a submodule with the same name as this header file.
486056396aeSDouglas Gregor         SmallString<32> NameBuf;
487056396aeSDouglas Gregor         StringRef Name = sanitizeFilenameAsIdentifier(
488056396aeSDouglas Gregor                            llvm::sys::path::stem(Header->getName()),
489056396aeSDouglas Gregor                            NameBuf);
4901fb5c3a6SDouglas Gregor         Found = lookupModuleQualified(Name, Found);
4911fb5c3a6SDouglas Gregor         if (!Found)
4921fb5c3a6SDouglas Gregor           return false;
4931fb5c3a6SDouglas Gregor       }
4941fb5c3a6SDouglas Gregor 
49550996ce1SRichard Smith       return IsUnavailable(Found);
4961fb5c3a6SDouglas Gregor     }
4971fb5c3a6SDouglas Gregor 
4981fb5c3a6SDouglas Gregor     SkippedDirs.push_back(Dir);
4991fb5c3a6SDouglas Gregor 
5001fb5c3a6SDouglas Gregor     // Retrieve our parent path.
5011fb5c3a6SDouglas Gregor     DirName = llvm::sys::path::parent_path(DirName);
5021fb5c3a6SDouglas Gregor     if (DirName.empty())
5031fb5c3a6SDouglas Gregor       break;
5041fb5c3a6SDouglas Gregor 
5051fb5c3a6SDouglas Gregor     // Resolve the parent path to a directory entry.
5061f76c4e8SManuel Klimek     Dir = SourceMgr.getFileManager().getDirectory(DirName);
5071fb5c3a6SDouglas Gregor   } while (Dir);
5081fb5c3a6SDouglas Gregor 
5091fb5c3a6SDouglas Gregor   return false;
5101fb5c3a6SDouglas Gregor }
5111fb5c3a6SDouglas Gregor 
512e4412640SArgyrios Kyrtzidis Module *ModuleMap::findModule(StringRef Name) const {
513e4412640SArgyrios Kyrtzidis   llvm::StringMap<Module *>::const_iterator Known = Modules.find(Name);
51488bdfb0eSDouglas Gregor   if (Known != Modules.end())
51588bdfb0eSDouglas Gregor     return Known->getValue();
51688bdfb0eSDouglas Gregor 
517d2d442caSCraig Topper   return nullptr;
51888bdfb0eSDouglas Gregor }
51988bdfb0eSDouglas Gregor 
520e4412640SArgyrios Kyrtzidis Module *ModuleMap::lookupModuleUnqualified(StringRef Name,
521e4412640SArgyrios Kyrtzidis                                            Module *Context) const {
5222b82c2a5SDouglas Gregor   for(; Context; Context = Context->Parent) {
5232b82c2a5SDouglas Gregor     if (Module *Sub = lookupModuleQualified(Name, Context))
5242b82c2a5SDouglas Gregor       return Sub;
5252b82c2a5SDouglas Gregor   }
5262b82c2a5SDouglas Gregor 
5272b82c2a5SDouglas Gregor   return findModule(Name);
5282b82c2a5SDouglas Gregor }
5292b82c2a5SDouglas Gregor 
530e4412640SArgyrios Kyrtzidis Module *ModuleMap::lookupModuleQualified(StringRef Name, Module *Context) const{
5312b82c2a5SDouglas Gregor   if (!Context)
5322b82c2a5SDouglas Gregor     return findModule(Name);
5332b82c2a5SDouglas Gregor 
534eb90e830SDouglas Gregor   return Context->findSubmodule(Name);
5352b82c2a5SDouglas Gregor }
5362b82c2a5SDouglas Gregor 
537de3ef502SDouglas Gregor std::pair<Module *, bool>
538beee15e7SBen Langmuir ModuleMap::findOrCreateModule(StringRef Name, Module *Parent,
539beee15e7SBen Langmuir                               const FileEntry *ModuleMap, 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.
546beee15e7SBen Langmuir   Module *Result = new Module(Name, SourceLocation(), Parent, ModuleMap,
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 
627*6b7f7345SBen Langmuir     // In case this is a case-insensitive filesystem, make sure the canonical
628*6b7f7345SBen Langmuir     // directory name matches ModuleName exactly. Modules are case-sensitive.
629*6b7f7345SBen Langmuir     // FIXME: we should be able to give a fix-it hint for the correct spelling.
630*6b7f7345SBen Langmuir     if (llvm::sys::path::stem(FrameworkDirName) != ModuleName)
631*6b7f7345SBen Langmuir       return nullptr;
632*6b7f7345SBen 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
676beee15e7SBen Langmuir     ModuleMapFile = Parent->ModuleMap;
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 
690beee15e7SBen Langmuir   Module *Result = new Module(ModuleName, SourceLocation(), Parent, ModuleMapFile,
691e89dbc1dSDouglas Gregor                               /*IsFramework=*/true, /*IsExplicit=*/false);
692ba7f2f71SDaniel Jasper   if (LangOpts.CurrentModule == ModuleName) {
693ba7f2f71SDaniel Jasper     SourceModule = Result;
694ba7f2f71SDaniel Jasper     SourceModuleName = ModuleName;
695ba7f2f71SDaniel Jasper   }
696a686e1b0SDouglas Gregor   if (IsSystem)
697a686e1b0SDouglas Gregor     Result->IsSystem = IsSystem;
698a686e1b0SDouglas Gregor 
699eb90e830SDouglas Gregor   if (!Parent)
700e89dbc1dSDouglas Gregor     Modules[ModuleName] = Result;
701e89dbc1dSDouglas Gregor 
702322f633cSDouglas Gregor   // umbrella header "umbrella-header-name"
70373141fa9SDouglas Gregor   Result->Umbrella = UmbrellaHeader;
70497da9178SDaniel Jasper   Headers[UmbrellaHeader].push_back(KnownHeader(Result, NormalHeader));
7054dc71835SDouglas Gregor   UmbrellaDirs[UmbrellaHeader->getDir()] = Result;
706d8bd7537SDouglas Gregor 
707d8bd7537SDouglas Gregor   // export *
708d2d442caSCraig Topper   Result->Exports.push_back(Module::ExportDecl(nullptr, true));
709d8bd7537SDouglas Gregor 
710a89c5ac4SDouglas Gregor   // module * { export * }
711a89c5ac4SDouglas Gregor   Result->InferSubmodules = true;
712a89c5ac4SDouglas Gregor   Result->InferExportWildcard = true;
713a89c5ac4SDouglas Gregor 
714e89dbc1dSDouglas Gregor   // Look for subframeworks.
715c080917eSRafael Espindola   std::error_code EC;
7162c1dd271SDylan Noblesmith   SmallString<128> SubframeworksDirName
717ddaa69cbSDouglas Gregor     = StringRef(FrameworkDir->getName());
718e89dbc1dSDouglas Gregor   llvm::sys::path::append(SubframeworksDirName, "Frameworks");
7192d4d8cb3SBenjamin Kramer   llvm::sys::path::native(SubframeworksDirName);
720ddaa69cbSDouglas Gregor   for (llvm::sys::fs::directory_iterator
7212d4d8cb3SBenjamin Kramer          Dir(SubframeworksDirName.str(), EC), DirEnd;
722e89dbc1dSDouglas Gregor        Dir != DirEnd && !EC; Dir.increment(EC)) {
723e89dbc1dSDouglas Gregor     if (!StringRef(Dir->path()).endswith(".framework"))
724e89dbc1dSDouglas Gregor       continue;
725f2161a70SDouglas Gregor 
726e89dbc1dSDouglas Gregor     if (const DirectoryEntry *SubframeworkDir
727e89dbc1dSDouglas Gregor           = FileMgr.getDirectory(Dir->path())) {
72807c22b78SDouglas Gregor       // Note: as an egregious but useful hack, we use the real path here and
72907c22b78SDouglas Gregor       // check whether it is actually a subdirectory of the parent directory.
73007c22b78SDouglas Gregor       // This will not be the case if the 'subframework' is actually a symlink
73107c22b78SDouglas Gregor       // out to a top-level framework.
732e00c8b20SDouglas Gregor       StringRef SubframeworkDirName = FileMgr.getCanonicalName(SubframeworkDir);
73307c22b78SDouglas Gregor       bool FoundParent = false;
73407c22b78SDouglas Gregor       do {
73507c22b78SDouglas Gregor         // Get the parent directory name.
73607c22b78SDouglas Gregor         SubframeworkDirName
73707c22b78SDouglas Gregor           = llvm::sys::path::parent_path(SubframeworkDirName);
73807c22b78SDouglas Gregor         if (SubframeworkDirName.empty())
73907c22b78SDouglas Gregor           break;
74007c22b78SDouglas Gregor 
74107c22b78SDouglas Gregor         if (FileMgr.getDirectory(SubframeworkDirName) == FrameworkDir) {
74207c22b78SDouglas Gregor           FoundParent = true;
74307c22b78SDouglas Gregor           break;
74407c22b78SDouglas Gregor         }
74507c22b78SDouglas Gregor       } while (true);
74607c22b78SDouglas Gregor 
74707c22b78SDouglas Gregor       if (!FoundParent)
74807c22b78SDouglas Gregor         continue;
74907c22b78SDouglas Gregor 
750e89dbc1dSDouglas Gregor       // FIXME: Do we want to warn about subframeworks without umbrella headers?
751056396aeSDouglas Gregor       SmallString<32> NameBuf;
752056396aeSDouglas Gregor       inferFrameworkModule(sanitizeFilenameAsIdentifier(
753056396aeSDouglas Gregor                              llvm::sys::path::stem(Dir->path()), NameBuf),
754056396aeSDouglas Gregor                            SubframeworkDir, IsSystem, Result);
755e89dbc1dSDouglas Gregor     }
756e89dbc1dSDouglas Gregor   }
757e89dbc1dSDouglas Gregor 
75811dfe6feSDouglas Gregor   // If the module is a top-level framework, automatically link against the
75911dfe6feSDouglas Gregor   // framework.
76011dfe6feSDouglas Gregor   if (!Result->isSubFramework()) {
76111dfe6feSDouglas Gregor     inferFrameworkLink(Result, FrameworkDir, FileMgr);
76211dfe6feSDouglas Gregor   }
76311dfe6feSDouglas Gregor 
76456c64013SDouglas Gregor   return Result;
76556c64013SDouglas Gregor }
76656c64013SDouglas Gregor 
767a89c5ac4SDouglas Gregor void ModuleMap::setUmbrellaHeader(Module *Mod, const FileEntry *UmbrellaHeader){
76897da9178SDaniel Jasper   Headers[UmbrellaHeader].push_back(KnownHeader(Mod, NormalHeader));
76973141fa9SDouglas Gregor   Mod->Umbrella = UmbrellaHeader;
7707033127bSDouglas Gregor   UmbrellaDirs[UmbrellaHeader->getDir()] = Mod;
771a89c5ac4SDouglas Gregor }
772a89c5ac4SDouglas Gregor 
773524e33e1SDouglas Gregor void ModuleMap::setUmbrellaDir(Module *Mod, const DirectoryEntry *UmbrellaDir) {
774524e33e1SDouglas Gregor   Mod->Umbrella = UmbrellaDir;
775524e33e1SDouglas Gregor   UmbrellaDirs[UmbrellaDir] = Mod;
776524e33e1SDouglas Gregor }
777524e33e1SDouglas Gregor 
77859527666SDouglas Gregor void ModuleMap::addHeader(Module *Mod, const FileEntry *Header,
779b53e5483SLawrence Crowl                           ModuleHeaderRole Role) {
780b53e5483SLawrence Crowl   if (Role == ExcludedHeader) {
78159527666SDouglas Gregor     Mod->ExcludedHeaders.push_back(Header);
782b146baabSArgyrios Kyrtzidis   } else {
783b53e5483SLawrence Crowl     if (Role == PrivateHeader)
784b53e5483SLawrence Crowl       Mod->PrivateHeaders.push_back(Header);
785b53e5483SLawrence Crowl     else
786b53e5483SLawrence Crowl       Mod->NormalHeaders.push_back(Header);
7876f722b4eSArgyrios Kyrtzidis     bool isCompilingModuleHeader = Mod->getTopLevelModule() == CompilingModule;
788b53e5483SLawrence Crowl     HeaderInfo.MarkFileModuleHeader(Header, Role, isCompilingModuleHeader);
789b146baabSArgyrios Kyrtzidis   }
79097da9178SDaniel Jasper   Headers[Header].push_back(KnownHeader(Mod, Role));
791a89c5ac4SDouglas Gregor }
792a89c5ac4SDouglas Gregor 
793514b636aSDouglas Gregor const FileEntry *
794e4412640SArgyrios Kyrtzidis ModuleMap::getContainingModuleMapFile(Module *Module) const {
7951f76c4e8SManuel Klimek   if (Module->DefinitionLoc.isInvalid())
796d2d442caSCraig Topper     return nullptr;
797514b636aSDouglas Gregor 
7981f76c4e8SManuel Klimek   return SourceMgr.getFileEntryForID(
7991f76c4e8SManuel Klimek            SourceMgr.getFileID(Module->DefinitionLoc));
800514b636aSDouglas Gregor }
801514b636aSDouglas Gregor 
802718292f2SDouglas Gregor void ModuleMap::dump() {
803718292f2SDouglas Gregor   llvm::errs() << "Modules:";
804718292f2SDouglas Gregor   for (llvm::StringMap<Module *>::iterator M = Modules.begin(),
805718292f2SDouglas Gregor                                         MEnd = Modules.end();
806718292f2SDouglas Gregor        M != MEnd; ++M)
807d28d1b8dSDouglas Gregor     M->getValue()->print(llvm::errs(), 2);
808718292f2SDouglas Gregor 
809718292f2SDouglas Gregor   llvm::errs() << "Headers:";
81059527666SDouglas Gregor   for (HeadersMap::iterator H = Headers.begin(), HEnd = Headers.end();
811718292f2SDouglas Gregor        H != HEnd; ++H) {
81297da9178SDaniel Jasper     llvm::errs() << "  \"" << H->first->getName() << "\" -> ";
81397da9178SDaniel Jasper     for (SmallVectorImpl<KnownHeader>::const_iterator I = H->second.begin(),
81497da9178SDaniel Jasper                                                       E = H->second.end();
81597da9178SDaniel Jasper          I != E; ++I) {
81697da9178SDaniel Jasper       if (I != H->second.begin())
81797da9178SDaniel Jasper         llvm::errs() << ",";
81897da9178SDaniel Jasper       llvm::errs() << I->getModule()->getFullModuleName();
81997da9178SDaniel Jasper     }
82097da9178SDaniel Jasper     llvm::errs() << "\n";
821718292f2SDouglas Gregor   }
822718292f2SDouglas Gregor }
823718292f2SDouglas Gregor 
8242b82c2a5SDouglas Gregor bool ModuleMap::resolveExports(Module *Mod, bool Complain) {
8252b82c2a5SDouglas Gregor   bool HadError = false;
8262b82c2a5SDouglas Gregor   for (unsigned I = 0, N = Mod->UnresolvedExports.size(); I != N; ++I) {
8272b82c2a5SDouglas Gregor     Module::ExportDecl Export = resolveExport(Mod, Mod->UnresolvedExports[I],
8282b82c2a5SDouglas Gregor                                               Complain);
829f5eedd05SDouglas Gregor     if (Export.getPointer() || Export.getInt())
8302b82c2a5SDouglas Gregor       Mod->Exports.push_back(Export);
8312b82c2a5SDouglas Gregor     else
8322b82c2a5SDouglas Gregor       HadError = true;
8332b82c2a5SDouglas Gregor   }
8342b82c2a5SDouglas Gregor   Mod->UnresolvedExports.clear();
8352b82c2a5SDouglas Gregor   return HadError;
8362b82c2a5SDouglas Gregor }
8372b82c2a5SDouglas Gregor 
838ba7f2f71SDaniel Jasper bool ModuleMap::resolveUses(Module *Mod, bool Complain) {
839ba7f2f71SDaniel Jasper   bool HadError = false;
840ba7f2f71SDaniel Jasper   for (unsigned I = 0, N = Mod->UnresolvedDirectUses.size(); I != N; ++I) {
841ba7f2f71SDaniel Jasper     Module *DirectUse =
842ba7f2f71SDaniel Jasper         resolveModuleId(Mod->UnresolvedDirectUses[I], Mod, Complain);
843ba7f2f71SDaniel Jasper     if (DirectUse)
844ba7f2f71SDaniel Jasper       Mod->DirectUses.push_back(DirectUse);
845ba7f2f71SDaniel Jasper     else
846ba7f2f71SDaniel Jasper       HadError = true;
847ba7f2f71SDaniel Jasper   }
848ba7f2f71SDaniel Jasper   Mod->UnresolvedDirectUses.clear();
849ba7f2f71SDaniel Jasper   return HadError;
850ba7f2f71SDaniel Jasper }
851ba7f2f71SDaniel Jasper 
852fb912657SDouglas Gregor bool ModuleMap::resolveConflicts(Module *Mod, bool Complain) {
853fb912657SDouglas Gregor   bool HadError = false;
854fb912657SDouglas Gregor   for (unsigned I = 0, N = Mod->UnresolvedConflicts.size(); I != N; ++I) {
855fb912657SDouglas Gregor     Module *OtherMod = resolveModuleId(Mod->UnresolvedConflicts[I].Id,
856fb912657SDouglas Gregor                                        Mod, Complain);
857fb912657SDouglas Gregor     if (!OtherMod) {
858fb912657SDouglas Gregor       HadError = true;
859fb912657SDouglas Gregor       continue;
860fb912657SDouglas Gregor     }
861fb912657SDouglas Gregor 
862fb912657SDouglas Gregor     Module::Conflict Conflict;
863fb912657SDouglas Gregor     Conflict.Other = OtherMod;
864fb912657SDouglas Gregor     Conflict.Message = Mod->UnresolvedConflicts[I].Message;
865fb912657SDouglas Gregor     Mod->Conflicts.push_back(Conflict);
866fb912657SDouglas Gregor   }
867fb912657SDouglas Gregor   Mod->UnresolvedConflicts.clear();
868fb912657SDouglas Gregor   return HadError;
869fb912657SDouglas Gregor }
870fb912657SDouglas Gregor 
8710093b3c7SDouglas Gregor Module *ModuleMap::inferModuleFromLocation(FullSourceLoc Loc) {
8720093b3c7SDouglas Gregor   if (Loc.isInvalid())
873d2d442caSCraig Topper     return nullptr;
8740093b3c7SDouglas Gregor 
8750093b3c7SDouglas Gregor   // Use the expansion location to determine which module we're in.
8760093b3c7SDouglas Gregor   FullSourceLoc ExpansionLoc = Loc.getExpansionLoc();
8770093b3c7SDouglas Gregor   if (!ExpansionLoc.isFileID())
878d2d442caSCraig Topper     return nullptr;
8790093b3c7SDouglas Gregor 
8800093b3c7SDouglas Gregor   const SourceManager &SrcMgr = Loc.getManager();
8810093b3c7SDouglas Gregor   FileID ExpansionFileID = ExpansionLoc.getFileID();
882224d8a74SDouglas Gregor 
883224d8a74SDouglas Gregor   while (const FileEntry *ExpansionFile
884224d8a74SDouglas Gregor            = SrcMgr.getFileEntryForID(ExpansionFileID)) {
885224d8a74SDouglas Gregor     // Find the module that owns this header (if any).
886b53e5483SLawrence Crowl     if (Module *Mod = findModuleForHeader(ExpansionFile).getModule())
887224d8a74SDouglas Gregor       return Mod;
888224d8a74SDouglas Gregor 
889224d8a74SDouglas Gregor     // No module owns this header, so look up the inclusion chain to see if
890224d8a74SDouglas Gregor     // any included header has an associated module.
891224d8a74SDouglas Gregor     SourceLocation IncludeLoc = SrcMgr.getIncludeLoc(ExpansionFileID);
892224d8a74SDouglas Gregor     if (IncludeLoc.isInvalid())
893d2d442caSCraig Topper       return nullptr;
8940093b3c7SDouglas Gregor 
895224d8a74SDouglas Gregor     ExpansionFileID = SrcMgr.getFileID(IncludeLoc);
896224d8a74SDouglas Gregor   }
897224d8a74SDouglas Gregor 
898d2d442caSCraig Topper   return nullptr;
8990093b3c7SDouglas Gregor }
9000093b3c7SDouglas Gregor 
901718292f2SDouglas Gregor //----------------------------------------------------------------------------//
902718292f2SDouglas Gregor // Module map file parser
903718292f2SDouglas Gregor //----------------------------------------------------------------------------//
904718292f2SDouglas Gregor 
905718292f2SDouglas Gregor namespace clang {
906718292f2SDouglas Gregor   /// \brief A token in a module map file.
907718292f2SDouglas Gregor   struct MMToken {
908718292f2SDouglas Gregor     enum TokenKind {
9091fb5c3a6SDouglas Gregor       Comma,
91035b13eceSDouglas Gregor       ConfigMacros,
911fb912657SDouglas Gregor       Conflict,
912718292f2SDouglas Gregor       EndOfFile,
913718292f2SDouglas Gregor       HeaderKeyword,
914718292f2SDouglas Gregor       Identifier,
915a3feee2aSRichard Smith       Exclaim,
91659527666SDouglas Gregor       ExcludeKeyword,
917718292f2SDouglas Gregor       ExplicitKeyword,
9182b82c2a5SDouglas Gregor       ExportKeyword,
91997292843SDaniel Jasper       ExternKeyword,
920755b2055SDouglas Gregor       FrameworkKeyword,
9216ddfca91SDouglas Gregor       LinkKeyword,
922718292f2SDouglas Gregor       ModuleKeyword,
9232b82c2a5SDouglas Gregor       Period,
924b53e5483SLawrence Crowl       PrivateKeyword,
925718292f2SDouglas Gregor       UmbrellaKeyword,
926ba7f2f71SDaniel Jasper       UseKeyword,
9271fb5c3a6SDouglas Gregor       RequiresKeyword,
9282b82c2a5SDouglas Gregor       Star,
929718292f2SDouglas Gregor       StringLiteral,
930718292f2SDouglas Gregor       LBrace,
931a686e1b0SDouglas Gregor       RBrace,
932a686e1b0SDouglas Gregor       LSquare,
933a686e1b0SDouglas Gregor       RSquare
934718292f2SDouglas Gregor     } Kind;
935718292f2SDouglas Gregor 
936718292f2SDouglas Gregor     unsigned Location;
937718292f2SDouglas Gregor     unsigned StringLength;
938718292f2SDouglas Gregor     const char *StringData;
939718292f2SDouglas Gregor 
940718292f2SDouglas Gregor     void clear() {
941718292f2SDouglas Gregor       Kind = EndOfFile;
942718292f2SDouglas Gregor       Location = 0;
943718292f2SDouglas Gregor       StringLength = 0;
944d2d442caSCraig Topper       StringData = nullptr;
945718292f2SDouglas Gregor     }
946718292f2SDouglas Gregor 
947718292f2SDouglas Gregor     bool is(TokenKind K) const { return Kind == K; }
948718292f2SDouglas Gregor 
949718292f2SDouglas Gregor     SourceLocation getLocation() const {
950718292f2SDouglas Gregor       return SourceLocation::getFromRawEncoding(Location);
951718292f2SDouglas Gregor     }
952718292f2SDouglas Gregor 
953718292f2SDouglas Gregor     StringRef getString() const {
954718292f2SDouglas Gregor       return StringRef(StringData, StringLength);
955718292f2SDouglas Gregor     }
956718292f2SDouglas Gregor   };
957718292f2SDouglas Gregor 
9589194a91dSDouglas Gregor   /// \brief The set of attributes that can be attached to a module.
9594442605fSBill Wendling   struct Attributes {
96077944868SRichard Smith     Attributes() : IsSystem(), IsExternC(), IsExhaustive() { }
9619194a91dSDouglas Gregor 
9629194a91dSDouglas Gregor     /// \brief Whether this is a system module.
9639194a91dSDouglas Gregor     unsigned IsSystem : 1;
96435b13eceSDouglas Gregor 
96577944868SRichard Smith     /// \brief Whether this is an extern "C" module.
96677944868SRichard Smith     unsigned IsExternC : 1;
96777944868SRichard Smith 
96835b13eceSDouglas Gregor     /// \brief Whether this is an exhaustive set of configuration macros.
96935b13eceSDouglas Gregor     unsigned IsExhaustive : 1;
9709194a91dSDouglas Gregor   };
9719194a91dSDouglas Gregor 
9729194a91dSDouglas Gregor 
973718292f2SDouglas Gregor   class ModuleMapParser {
974718292f2SDouglas Gregor     Lexer &L;
975718292f2SDouglas Gregor     SourceManager &SourceMgr;
976bc10b9fbSDouglas Gregor 
977bc10b9fbSDouglas Gregor     /// \brief Default target information, used only for string literal
978bc10b9fbSDouglas Gregor     /// parsing.
979bc10b9fbSDouglas Gregor     const TargetInfo *Target;
980bc10b9fbSDouglas Gregor 
981718292f2SDouglas Gregor     DiagnosticsEngine &Diags;
982718292f2SDouglas Gregor     ModuleMap &Map;
983718292f2SDouglas Gregor 
984beee15e7SBen Langmuir     /// \brief The current module map file.
985beee15e7SBen Langmuir     const FileEntry *ModuleMapFile;
986beee15e7SBen Langmuir 
9875257fc63SDouglas Gregor     /// \brief The directory that this module map resides in.
9885257fc63SDouglas Gregor     const DirectoryEntry *Directory;
9895257fc63SDouglas Gregor 
9903ec6663bSDouglas Gregor     /// \brief The directory containing Clang-supplied headers.
9913ec6663bSDouglas Gregor     const DirectoryEntry *BuiltinIncludeDir;
9923ec6663bSDouglas Gregor 
993963c5535SDouglas Gregor     /// \brief Whether this module map is in a system header directory.
994963c5535SDouglas Gregor     bool IsSystem;
995963c5535SDouglas Gregor 
996718292f2SDouglas Gregor     /// \brief Whether an error occurred.
997718292f2SDouglas Gregor     bool HadError;
998718292f2SDouglas Gregor 
999718292f2SDouglas Gregor     /// \brief Stores string data for the various string literals referenced
1000718292f2SDouglas Gregor     /// during parsing.
1001718292f2SDouglas Gregor     llvm::BumpPtrAllocator StringData;
1002718292f2SDouglas Gregor 
1003718292f2SDouglas Gregor     /// \brief The current token.
1004718292f2SDouglas Gregor     MMToken Tok;
1005718292f2SDouglas Gregor 
1006718292f2SDouglas Gregor     /// \brief The active module.
1007de3ef502SDouglas Gregor     Module *ActiveModule;
1008718292f2SDouglas Gregor 
1009718292f2SDouglas Gregor     /// \brief Consume the current token and return its location.
1010718292f2SDouglas Gregor     SourceLocation consumeToken();
1011718292f2SDouglas Gregor 
1012718292f2SDouglas Gregor     /// \brief Skip tokens until we reach the a token with the given kind
1013718292f2SDouglas Gregor     /// (or the end of the file).
1014718292f2SDouglas Gregor     void skipUntil(MMToken::TokenKind K);
1015718292f2SDouglas Gregor 
1016f857950dSDmitri Gribenko     typedef SmallVector<std::pair<std::string, SourceLocation>, 2> ModuleId;
1017e7ab3669SDouglas Gregor     bool parseModuleId(ModuleId &Id);
1018718292f2SDouglas Gregor     void parseModuleDecl();
101997292843SDaniel Jasper     void parseExternModuleDecl();
10201fb5c3a6SDouglas Gregor     void parseRequiresDecl();
1021b53e5483SLawrence Crowl     void parseHeaderDecl(clang::MMToken::TokenKind,
1022b53e5483SLawrence Crowl                          SourceLocation LeadingLoc);
1023524e33e1SDouglas Gregor     void parseUmbrellaDirDecl(SourceLocation UmbrellaLoc);
10242b82c2a5SDouglas Gregor     void parseExportDecl();
1025ba7f2f71SDaniel Jasper     void parseUseDecl();
10266ddfca91SDouglas Gregor     void parseLinkDecl();
102735b13eceSDouglas Gregor     void parseConfigMacros();
1028fb912657SDouglas Gregor     void parseConflict();
10299194a91dSDouglas Gregor     void parseInferredModuleDecl(bool Framework, bool Explicit);
10304442605fSBill Wendling     bool parseOptionalAttributes(Attributes &Attrs);
1031718292f2SDouglas Gregor 
1032718292f2SDouglas Gregor   public:
1033718292f2SDouglas Gregor     explicit ModuleMapParser(Lexer &L, SourceManager &SourceMgr,
1034bc10b9fbSDouglas Gregor                              const TargetInfo *Target,
1035718292f2SDouglas Gregor                              DiagnosticsEngine &Diags,
10365257fc63SDouglas Gregor                              ModuleMap &Map,
1037beee15e7SBen Langmuir                              const FileEntry *ModuleMapFile,
10383ec6663bSDouglas Gregor                              const DirectoryEntry *Directory,
1039963c5535SDouglas Gregor                              const DirectoryEntry *BuiltinIncludeDir,
1040963c5535SDouglas Gregor                              bool IsSystem)
1041bc10b9fbSDouglas Gregor       : L(L), SourceMgr(SourceMgr), Target(Target), Diags(Diags), Map(Map),
1042beee15e7SBen Langmuir         ModuleMapFile(ModuleMapFile), Directory(Directory),
1043beee15e7SBen Langmuir         BuiltinIncludeDir(BuiltinIncludeDir), IsSystem(IsSystem),
1044d2d442caSCraig Topper         HadError(false), ActiveModule(nullptr)
1045718292f2SDouglas Gregor     {
1046718292f2SDouglas Gregor       Tok.clear();
1047718292f2SDouglas Gregor       consumeToken();
1048718292f2SDouglas Gregor     }
1049718292f2SDouglas Gregor 
1050718292f2SDouglas Gregor     bool parseModuleMapFile();
1051718292f2SDouglas Gregor   };
1052718292f2SDouglas Gregor }
1053718292f2SDouglas Gregor 
1054718292f2SDouglas Gregor SourceLocation ModuleMapParser::consumeToken() {
1055718292f2SDouglas Gregor retry:
1056718292f2SDouglas Gregor   SourceLocation Result = Tok.getLocation();
1057718292f2SDouglas Gregor   Tok.clear();
1058718292f2SDouglas Gregor 
1059718292f2SDouglas Gregor   Token LToken;
1060718292f2SDouglas Gregor   L.LexFromRawLexer(LToken);
1061718292f2SDouglas Gregor   Tok.Location = LToken.getLocation().getRawEncoding();
1062718292f2SDouglas Gregor   switch (LToken.getKind()) {
10632d57cea2SAlp Toker   case tok::raw_identifier: {
10642d57cea2SAlp Toker     StringRef RI = LToken.getRawIdentifier();
10652d57cea2SAlp Toker     Tok.StringData = RI.data();
10662d57cea2SAlp Toker     Tok.StringLength = RI.size();
10672d57cea2SAlp Toker     Tok.Kind = llvm::StringSwitch<MMToken::TokenKind>(RI)
106835b13eceSDouglas Gregor                  .Case("config_macros", MMToken::ConfigMacros)
1069fb912657SDouglas Gregor                  .Case("conflict", MMToken::Conflict)
107059527666SDouglas Gregor                  .Case("exclude", MMToken::ExcludeKeyword)
1071718292f2SDouglas Gregor                  .Case("explicit", MMToken::ExplicitKeyword)
10722b82c2a5SDouglas Gregor                  .Case("export", MMToken::ExportKeyword)
107397292843SDaniel Jasper                  .Case("extern", MMToken::ExternKeyword)
1074755b2055SDouglas Gregor                  .Case("framework", MMToken::FrameworkKeyword)
107535b13eceSDouglas Gregor                  .Case("header", MMToken::HeaderKeyword)
10766ddfca91SDouglas Gregor                  .Case("link", MMToken::LinkKeyword)
1077718292f2SDouglas Gregor                  .Case("module", MMToken::ModuleKeyword)
1078b53e5483SLawrence Crowl                  .Case("private", MMToken::PrivateKeyword)
10791fb5c3a6SDouglas Gregor                  .Case("requires", MMToken::RequiresKeyword)
1080718292f2SDouglas Gregor                  .Case("umbrella", MMToken::UmbrellaKeyword)
1081ba7f2f71SDaniel Jasper                  .Case("use", MMToken::UseKeyword)
1082718292f2SDouglas Gregor                  .Default(MMToken::Identifier);
1083718292f2SDouglas Gregor     break;
10842d57cea2SAlp Toker   }
1085718292f2SDouglas Gregor 
10861fb5c3a6SDouglas Gregor   case tok::comma:
10871fb5c3a6SDouglas Gregor     Tok.Kind = MMToken::Comma;
10881fb5c3a6SDouglas Gregor     break;
10891fb5c3a6SDouglas Gregor 
1090718292f2SDouglas Gregor   case tok::eof:
1091718292f2SDouglas Gregor     Tok.Kind = MMToken::EndOfFile;
1092718292f2SDouglas Gregor     break;
1093718292f2SDouglas Gregor 
1094718292f2SDouglas Gregor   case tok::l_brace:
1095718292f2SDouglas Gregor     Tok.Kind = MMToken::LBrace;
1096718292f2SDouglas Gregor     break;
1097718292f2SDouglas Gregor 
1098a686e1b0SDouglas Gregor   case tok::l_square:
1099a686e1b0SDouglas Gregor     Tok.Kind = MMToken::LSquare;
1100a686e1b0SDouglas Gregor     break;
1101a686e1b0SDouglas Gregor 
11022b82c2a5SDouglas Gregor   case tok::period:
11032b82c2a5SDouglas Gregor     Tok.Kind = MMToken::Period;
11042b82c2a5SDouglas Gregor     break;
11052b82c2a5SDouglas Gregor 
1106718292f2SDouglas Gregor   case tok::r_brace:
1107718292f2SDouglas Gregor     Tok.Kind = MMToken::RBrace;
1108718292f2SDouglas Gregor     break;
1109718292f2SDouglas Gregor 
1110a686e1b0SDouglas Gregor   case tok::r_square:
1111a686e1b0SDouglas Gregor     Tok.Kind = MMToken::RSquare;
1112a686e1b0SDouglas Gregor     break;
1113a686e1b0SDouglas Gregor 
11142b82c2a5SDouglas Gregor   case tok::star:
11152b82c2a5SDouglas Gregor     Tok.Kind = MMToken::Star;
11162b82c2a5SDouglas Gregor     break;
11172b82c2a5SDouglas Gregor 
1118a3feee2aSRichard Smith   case tok::exclaim:
1119a3feee2aSRichard Smith     Tok.Kind = MMToken::Exclaim;
1120a3feee2aSRichard Smith     break;
1121a3feee2aSRichard Smith 
1122718292f2SDouglas Gregor   case tok::string_literal: {
1123d67aea28SRichard Smith     if (LToken.hasUDSuffix()) {
1124d67aea28SRichard Smith       Diags.Report(LToken.getLocation(), diag::err_invalid_string_udl);
1125d67aea28SRichard Smith       HadError = true;
1126d67aea28SRichard Smith       goto retry;
1127d67aea28SRichard Smith     }
1128d67aea28SRichard Smith 
1129718292f2SDouglas Gregor     // Parse the string literal.
1130718292f2SDouglas Gregor     LangOptions LangOpts;
11319d5583efSCraig Topper     StringLiteralParser StringLiteral(LToken, SourceMgr, LangOpts, *Target);
1132718292f2SDouglas Gregor     if (StringLiteral.hadError)
1133718292f2SDouglas Gregor       goto retry;
1134718292f2SDouglas Gregor 
1135718292f2SDouglas Gregor     // Copy the string literal into our string data allocator.
1136718292f2SDouglas Gregor     unsigned Length = StringLiteral.GetStringLength();
1137718292f2SDouglas Gregor     char *Saved = StringData.Allocate<char>(Length + 1);
1138718292f2SDouglas Gregor     memcpy(Saved, StringLiteral.GetString().data(), Length);
1139718292f2SDouglas Gregor     Saved[Length] = 0;
1140718292f2SDouglas Gregor 
1141718292f2SDouglas Gregor     // Form the token.
1142718292f2SDouglas Gregor     Tok.Kind = MMToken::StringLiteral;
1143718292f2SDouglas Gregor     Tok.StringData = Saved;
1144718292f2SDouglas Gregor     Tok.StringLength = Length;
1145718292f2SDouglas Gregor     break;
1146718292f2SDouglas Gregor   }
1147718292f2SDouglas Gregor 
1148718292f2SDouglas Gregor   case tok::comment:
1149718292f2SDouglas Gregor     goto retry;
1150718292f2SDouglas Gregor 
1151718292f2SDouglas Gregor   default:
1152718292f2SDouglas Gregor     Diags.Report(LToken.getLocation(), diag::err_mmap_unknown_token);
1153718292f2SDouglas Gregor     HadError = true;
1154718292f2SDouglas Gregor     goto retry;
1155718292f2SDouglas Gregor   }
1156718292f2SDouglas Gregor 
1157718292f2SDouglas Gregor   return Result;
1158718292f2SDouglas Gregor }
1159718292f2SDouglas Gregor 
1160718292f2SDouglas Gregor void ModuleMapParser::skipUntil(MMToken::TokenKind K) {
1161718292f2SDouglas Gregor   unsigned braceDepth = 0;
1162a686e1b0SDouglas Gregor   unsigned squareDepth = 0;
1163718292f2SDouglas Gregor   do {
1164718292f2SDouglas Gregor     switch (Tok.Kind) {
1165718292f2SDouglas Gregor     case MMToken::EndOfFile:
1166718292f2SDouglas Gregor       return;
1167718292f2SDouglas Gregor 
1168718292f2SDouglas Gregor     case MMToken::LBrace:
1169a686e1b0SDouglas Gregor       if (Tok.is(K) && braceDepth == 0 && squareDepth == 0)
1170718292f2SDouglas Gregor         return;
1171718292f2SDouglas Gregor 
1172718292f2SDouglas Gregor       ++braceDepth;
1173718292f2SDouglas Gregor       break;
1174718292f2SDouglas Gregor 
1175a686e1b0SDouglas Gregor     case MMToken::LSquare:
1176a686e1b0SDouglas Gregor       if (Tok.is(K) && braceDepth == 0 && squareDepth == 0)
1177a686e1b0SDouglas Gregor         return;
1178a686e1b0SDouglas Gregor 
1179a686e1b0SDouglas Gregor       ++squareDepth;
1180a686e1b0SDouglas Gregor       break;
1181a686e1b0SDouglas Gregor 
1182718292f2SDouglas Gregor     case MMToken::RBrace:
1183718292f2SDouglas Gregor       if (braceDepth > 0)
1184718292f2SDouglas Gregor         --braceDepth;
1185718292f2SDouglas Gregor       else if (Tok.is(K))
1186718292f2SDouglas Gregor         return;
1187718292f2SDouglas Gregor       break;
1188718292f2SDouglas Gregor 
1189a686e1b0SDouglas Gregor     case MMToken::RSquare:
1190a686e1b0SDouglas Gregor       if (squareDepth > 0)
1191a686e1b0SDouglas Gregor         --squareDepth;
1192a686e1b0SDouglas Gregor       else if (Tok.is(K))
1193a686e1b0SDouglas Gregor         return;
1194a686e1b0SDouglas Gregor       break;
1195a686e1b0SDouglas Gregor 
1196718292f2SDouglas Gregor     default:
1197a686e1b0SDouglas Gregor       if (braceDepth == 0 && squareDepth == 0 && Tok.is(K))
1198718292f2SDouglas Gregor         return;
1199718292f2SDouglas Gregor       break;
1200718292f2SDouglas Gregor     }
1201718292f2SDouglas Gregor 
1202718292f2SDouglas Gregor    consumeToken();
1203718292f2SDouglas Gregor   } while (true);
1204718292f2SDouglas Gregor }
1205718292f2SDouglas Gregor 
1206e7ab3669SDouglas Gregor /// \brief Parse a module-id.
1207e7ab3669SDouglas Gregor ///
1208e7ab3669SDouglas Gregor ///   module-id:
1209e7ab3669SDouglas Gregor ///     identifier
1210e7ab3669SDouglas Gregor ///     identifier '.' module-id
1211e7ab3669SDouglas Gregor ///
1212e7ab3669SDouglas Gregor /// \returns true if an error occurred, false otherwise.
1213e7ab3669SDouglas Gregor bool ModuleMapParser::parseModuleId(ModuleId &Id) {
1214e7ab3669SDouglas Gregor   Id.clear();
1215e7ab3669SDouglas Gregor   do {
12163cd34c76SDaniel Jasper     if (Tok.is(MMToken::Identifier) || Tok.is(MMToken::StringLiteral)) {
1217e7ab3669SDouglas Gregor       Id.push_back(std::make_pair(Tok.getString(), Tok.getLocation()));
1218e7ab3669SDouglas Gregor       consumeToken();
1219e7ab3669SDouglas Gregor     } else {
1220e7ab3669SDouglas Gregor       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module_name);
1221e7ab3669SDouglas Gregor       return true;
1222e7ab3669SDouglas Gregor     }
1223e7ab3669SDouglas Gregor 
1224e7ab3669SDouglas Gregor     if (!Tok.is(MMToken::Period))
1225e7ab3669SDouglas Gregor       break;
1226e7ab3669SDouglas Gregor 
1227e7ab3669SDouglas Gregor     consumeToken();
1228e7ab3669SDouglas Gregor   } while (true);
1229e7ab3669SDouglas Gregor 
1230e7ab3669SDouglas Gregor   return false;
1231e7ab3669SDouglas Gregor }
1232e7ab3669SDouglas Gregor 
1233a686e1b0SDouglas Gregor namespace {
1234a686e1b0SDouglas Gregor   /// \brief Enumerates the known attributes.
1235a686e1b0SDouglas Gregor   enum AttributeKind {
1236a686e1b0SDouglas Gregor     /// \brief An unknown attribute.
1237a686e1b0SDouglas Gregor     AT_unknown,
1238a686e1b0SDouglas Gregor     /// \brief The 'system' attribute.
123935b13eceSDouglas Gregor     AT_system,
124077944868SRichard Smith     /// \brief The 'extern_c' attribute.
124177944868SRichard Smith     AT_extern_c,
124235b13eceSDouglas Gregor     /// \brief The 'exhaustive' attribute.
124335b13eceSDouglas Gregor     AT_exhaustive
1244a686e1b0SDouglas Gregor   };
1245a686e1b0SDouglas Gregor }
1246a686e1b0SDouglas Gregor 
1247718292f2SDouglas Gregor /// \brief Parse a module declaration.
1248718292f2SDouglas Gregor ///
1249718292f2SDouglas Gregor ///   module-declaration:
125097292843SDaniel Jasper ///     'extern' 'module' module-id string-literal
1251a686e1b0SDouglas Gregor ///     'explicit'[opt] 'framework'[opt] 'module' module-id attributes[opt]
1252a686e1b0SDouglas Gregor ///       { module-member* }
1253a686e1b0SDouglas Gregor ///
1254718292f2SDouglas Gregor ///   module-member:
12551fb5c3a6SDouglas Gregor ///     requires-declaration
1256718292f2SDouglas Gregor ///     header-declaration
1257e7ab3669SDouglas Gregor ///     submodule-declaration
12582b82c2a5SDouglas Gregor ///     export-declaration
12596ddfca91SDouglas Gregor ///     link-declaration
126073441091SDouglas Gregor ///
126173441091SDouglas Gregor ///   submodule-declaration:
126273441091SDouglas Gregor ///     module-declaration
126373441091SDouglas Gregor ///     inferred-submodule-declaration
1264718292f2SDouglas Gregor void ModuleMapParser::parseModuleDecl() {
1265755b2055SDouglas Gregor   assert(Tok.is(MMToken::ExplicitKeyword) || Tok.is(MMToken::ModuleKeyword) ||
126697292843SDaniel Jasper          Tok.is(MMToken::FrameworkKeyword) || Tok.is(MMToken::ExternKeyword));
126797292843SDaniel Jasper   if (Tok.is(MMToken::ExternKeyword)) {
126897292843SDaniel Jasper     parseExternModuleDecl();
126997292843SDaniel Jasper     return;
127097292843SDaniel Jasper   }
127197292843SDaniel Jasper 
1272f2161a70SDouglas Gregor   // Parse 'explicit' or 'framework' keyword, if present.
1273e7ab3669SDouglas Gregor   SourceLocation ExplicitLoc;
1274718292f2SDouglas Gregor   bool Explicit = false;
1275f2161a70SDouglas Gregor   bool Framework = false;
1276755b2055SDouglas Gregor 
1277f2161a70SDouglas Gregor   // Parse 'explicit' keyword, if present.
1278f2161a70SDouglas Gregor   if (Tok.is(MMToken::ExplicitKeyword)) {
1279e7ab3669SDouglas Gregor     ExplicitLoc = consumeToken();
1280f2161a70SDouglas Gregor     Explicit = true;
1281f2161a70SDouglas Gregor   }
1282f2161a70SDouglas Gregor 
1283f2161a70SDouglas Gregor   // Parse 'framework' keyword, if present.
1284755b2055SDouglas Gregor   if (Tok.is(MMToken::FrameworkKeyword)) {
1285755b2055SDouglas Gregor     consumeToken();
1286755b2055SDouglas Gregor     Framework = true;
1287755b2055SDouglas Gregor   }
1288718292f2SDouglas Gregor 
1289718292f2SDouglas Gregor   // Parse 'module' keyword.
1290718292f2SDouglas Gregor   if (!Tok.is(MMToken::ModuleKeyword)) {
1291d6343c99SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module);
1292718292f2SDouglas Gregor     consumeToken();
1293718292f2SDouglas Gregor     HadError = true;
1294718292f2SDouglas Gregor     return;
1295718292f2SDouglas Gregor   }
1296718292f2SDouglas Gregor   consumeToken(); // 'module' keyword
1297718292f2SDouglas Gregor 
129873441091SDouglas Gregor   // If we have a wildcard for the module name, this is an inferred submodule.
129973441091SDouglas Gregor   // Parse it.
130073441091SDouglas Gregor   if (Tok.is(MMToken::Star))
13019194a91dSDouglas Gregor     return parseInferredModuleDecl(Framework, Explicit);
130273441091SDouglas Gregor 
1303718292f2SDouglas Gregor   // Parse the module name.
1304e7ab3669SDouglas Gregor   ModuleId Id;
1305e7ab3669SDouglas Gregor   if (parseModuleId(Id)) {
1306718292f2SDouglas Gregor     HadError = true;
1307718292f2SDouglas Gregor     return;
1308718292f2SDouglas Gregor   }
1309e7ab3669SDouglas Gregor 
1310e7ab3669SDouglas Gregor   if (ActiveModule) {
1311e7ab3669SDouglas Gregor     if (Id.size() > 1) {
1312e7ab3669SDouglas Gregor       Diags.Report(Id.front().second, diag::err_mmap_nested_submodule_id)
1313e7ab3669SDouglas Gregor         << SourceRange(Id.front().second, Id.back().second);
1314e7ab3669SDouglas Gregor 
1315e7ab3669SDouglas Gregor       HadError = true;
1316e7ab3669SDouglas Gregor       return;
1317e7ab3669SDouglas Gregor     }
1318e7ab3669SDouglas Gregor   } else if (Id.size() == 1 && Explicit) {
1319e7ab3669SDouglas Gregor     // Top-level modules can't be explicit.
1320e7ab3669SDouglas Gregor     Diags.Report(ExplicitLoc, diag::err_mmap_explicit_top_level);
1321e7ab3669SDouglas Gregor     Explicit = false;
1322e7ab3669SDouglas Gregor     ExplicitLoc = SourceLocation();
1323e7ab3669SDouglas Gregor     HadError = true;
1324e7ab3669SDouglas Gregor   }
1325e7ab3669SDouglas Gregor 
1326e7ab3669SDouglas Gregor   Module *PreviousActiveModule = ActiveModule;
1327e7ab3669SDouglas Gregor   if (Id.size() > 1) {
1328e7ab3669SDouglas Gregor     // This module map defines a submodule. Go find the module of which it
1329e7ab3669SDouglas Gregor     // is a submodule.
1330d2d442caSCraig Topper     ActiveModule = nullptr;
1331e7ab3669SDouglas Gregor     for (unsigned I = 0, N = Id.size() - 1; I != N; ++I) {
1332e7ab3669SDouglas Gregor       if (Module *Next = Map.lookupModuleQualified(Id[I].first, ActiveModule)) {
1333e7ab3669SDouglas Gregor         ActiveModule = Next;
1334e7ab3669SDouglas Gregor         continue;
1335e7ab3669SDouglas Gregor       }
1336e7ab3669SDouglas Gregor 
1337e7ab3669SDouglas Gregor       if (ActiveModule) {
1338e7ab3669SDouglas Gregor         Diags.Report(Id[I].second, diag::err_mmap_missing_module_qualified)
13395b5d21eaSRichard Smith           << Id[I].first
13405b5d21eaSRichard Smith           << ActiveModule->getTopLevelModule()->getFullModuleName();
1341e7ab3669SDouglas Gregor       } else {
1342e7ab3669SDouglas Gregor         Diags.Report(Id[I].second, diag::err_mmap_expected_module_name);
1343e7ab3669SDouglas Gregor       }
1344e7ab3669SDouglas Gregor       HadError = true;
1345e7ab3669SDouglas Gregor       return;
1346e7ab3669SDouglas Gregor     }
1347e7ab3669SDouglas Gregor   }
1348e7ab3669SDouglas Gregor 
1349e7ab3669SDouglas Gregor   StringRef ModuleName = Id.back().first;
1350e7ab3669SDouglas Gregor   SourceLocation ModuleNameLoc = Id.back().second;
1351718292f2SDouglas Gregor 
1352a686e1b0SDouglas Gregor   // Parse the optional attribute list.
13534442605fSBill Wendling   Attributes Attrs;
13549194a91dSDouglas Gregor   parseOptionalAttributes(Attrs);
1355a686e1b0SDouglas Gregor 
1356718292f2SDouglas Gregor   // Parse the opening brace.
1357718292f2SDouglas Gregor   if (!Tok.is(MMToken::LBrace)) {
1358718292f2SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_lbrace)
1359718292f2SDouglas Gregor       << ModuleName;
1360718292f2SDouglas Gregor     HadError = true;
1361718292f2SDouglas Gregor     return;
1362718292f2SDouglas Gregor   }
1363718292f2SDouglas Gregor   SourceLocation LBraceLoc = consumeToken();
1364718292f2SDouglas Gregor 
1365718292f2SDouglas Gregor   // Determine whether this (sub)module has already been defined.
1366eb90e830SDouglas Gregor   if (Module *Existing = Map.lookupModuleQualified(ModuleName, ActiveModule)) {
1367fcc54a3bSDouglas Gregor     if (Existing->DefinitionLoc.isInvalid() && !ActiveModule) {
1368fcc54a3bSDouglas Gregor       // Skip the module definition.
1369fcc54a3bSDouglas Gregor       skipUntil(MMToken::RBrace);
1370fcc54a3bSDouglas Gregor       if (Tok.is(MMToken::RBrace))
1371fcc54a3bSDouglas Gregor         consumeToken();
1372fcc54a3bSDouglas Gregor       else {
1373fcc54a3bSDouglas Gregor         Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
1374fcc54a3bSDouglas Gregor         Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
1375fcc54a3bSDouglas Gregor         HadError = true;
1376fcc54a3bSDouglas Gregor       }
1377fcc54a3bSDouglas Gregor       return;
1378fcc54a3bSDouglas Gregor     }
1379fcc54a3bSDouglas Gregor 
1380718292f2SDouglas Gregor     Diags.Report(ModuleNameLoc, diag::err_mmap_module_redefinition)
1381718292f2SDouglas Gregor       << ModuleName;
1382eb90e830SDouglas Gregor     Diags.Report(Existing->DefinitionLoc, diag::note_mmap_prev_definition);
1383718292f2SDouglas Gregor 
1384718292f2SDouglas Gregor     // Skip the module definition.
1385718292f2SDouglas Gregor     skipUntil(MMToken::RBrace);
1386718292f2SDouglas Gregor     if (Tok.is(MMToken::RBrace))
1387718292f2SDouglas Gregor       consumeToken();
1388718292f2SDouglas Gregor 
1389718292f2SDouglas Gregor     HadError = true;
1390718292f2SDouglas Gregor     return;
1391718292f2SDouglas Gregor   }
1392718292f2SDouglas Gregor 
1393beee15e7SBen Langmuir   // If this is a submodule, use the parent's module map, since we don't want
1394beee15e7SBen Langmuir   // the private module map file.
1395beee15e7SBen Langmuir   const FileEntry *ModuleMap = ActiveModule ? ActiveModule->ModuleMap
1396beee15e7SBen Langmuir                                             : ModuleMapFile;
1397beee15e7SBen Langmuir 
1398718292f2SDouglas Gregor   // Start defining this module.
1399beee15e7SBen Langmuir   ActiveModule = Map.findOrCreateModule(ModuleName, ActiveModule, ModuleMap,
1400beee15e7SBen Langmuir                                         Framework, Explicit).first;
1401eb90e830SDouglas Gregor   ActiveModule->DefinitionLoc = ModuleNameLoc;
1402963c5535SDouglas Gregor   if (Attrs.IsSystem || IsSystem)
1403a686e1b0SDouglas Gregor     ActiveModule->IsSystem = true;
140477944868SRichard Smith   if (Attrs.IsExternC)
140577944868SRichard Smith     ActiveModule->IsExternC = true;
1406718292f2SDouglas Gregor 
1407718292f2SDouglas Gregor   bool Done = false;
1408718292f2SDouglas Gregor   do {
1409718292f2SDouglas Gregor     switch (Tok.Kind) {
1410718292f2SDouglas Gregor     case MMToken::EndOfFile:
1411718292f2SDouglas Gregor     case MMToken::RBrace:
1412718292f2SDouglas Gregor       Done = true;
1413718292f2SDouglas Gregor       break;
1414718292f2SDouglas Gregor 
141535b13eceSDouglas Gregor     case MMToken::ConfigMacros:
141635b13eceSDouglas Gregor       parseConfigMacros();
141735b13eceSDouglas Gregor       break;
141835b13eceSDouglas Gregor 
1419fb912657SDouglas Gregor     case MMToken::Conflict:
1420fb912657SDouglas Gregor       parseConflict();
1421fb912657SDouglas Gregor       break;
1422fb912657SDouglas Gregor 
1423718292f2SDouglas Gregor     case MMToken::ExplicitKeyword:
142497292843SDaniel Jasper     case MMToken::ExternKeyword:
1425f2161a70SDouglas Gregor     case MMToken::FrameworkKeyword:
1426718292f2SDouglas Gregor     case MMToken::ModuleKeyword:
1427718292f2SDouglas Gregor       parseModuleDecl();
1428718292f2SDouglas Gregor       break;
1429718292f2SDouglas Gregor 
14302b82c2a5SDouglas Gregor     case MMToken::ExportKeyword:
14312b82c2a5SDouglas Gregor       parseExportDecl();
14322b82c2a5SDouglas Gregor       break;
14332b82c2a5SDouglas Gregor 
1434ba7f2f71SDaniel Jasper     case MMToken::UseKeyword:
1435ba7f2f71SDaniel Jasper       parseUseDecl();
1436ba7f2f71SDaniel Jasper       break;
1437ba7f2f71SDaniel Jasper 
14381fb5c3a6SDouglas Gregor     case MMToken::RequiresKeyword:
14391fb5c3a6SDouglas Gregor       parseRequiresDecl();
14401fb5c3a6SDouglas Gregor       break;
14411fb5c3a6SDouglas Gregor 
1442524e33e1SDouglas Gregor     case MMToken::UmbrellaKeyword: {
1443524e33e1SDouglas Gregor       SourceLocation UmbrellaLoc = consumeToken();
1444524e33e1SDouglas Gregor       if (Tok.is(MMToken::HeaderKeyword))
1445b53e5483SLawrence Crowl         parseHeaderDecl(MMToken::UmbrellaKeyword, UmbrellaLoc);
1446524e33e1SDouglas Gregor       else
1447524e33e1SDouglas Gregor         parseUmbrellaDirDecl(UmbrellaLoc);
1448718292f2SDouglas Gregor       break;
1449524e33e1SDouglas Gregor     }
1450718292f2SDouglas Gregor 
145159527666SDouglas Gregor     case MMToken::ExcludeKeyword: {
145259527666SDouglas Gregor       SourceLocation ExcludeLoc = consumeToken();
145359527666SDouglas Gregor       if (Tok.is(MMToken::HeaderKeyword)) {
1454b53e5483SLawrence Crowl         parseHeaderDecl(MMToken::ExcludeKeyword, ExcludeLoc);
145559527666SDouglas Gregor       } else {
145659527666SDouglas Gregor         Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
145759527666SDouglas Gregor           << "exclude";
145859527666SDouglas Gregor       }
145959527666SDouglas Gregor       break;
146059527666SDouglas Gregor     }
146159527666SDouglas Gregor 
1462b53e5483SLawrence Crowl     case MMToken::PrivateKeyword: {
1463b53e5483SLawrence Crowl       SourceLocation PrivateLoc = consumeToken();
1464b53e5483SLawrence Crowl       if (Tok.is(MMToken::HeaderKeyword)) {
1465b53e5483SLawrence Crowl         parseHeaderDecl(MMToken::PrivateKeyword, PrivateLoc);
1466b53e5483SLawrence Crowl       } else {
1467b53e5483SLawrence Crowl         Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
1468b53e5483SLawrence Crowl           << "private";
1469b53e5483SLawrence Crowl       }
1470b53e5483SLawrence Crowl       break;
1471b53e5483SLawrence Crowl     }
1472b53e5483SLawrence Crowl 
1473322f633cSDouglas Gregor     case MMToken::HeaderKeyword:
1474b53e5483SLawrence Crowl       parseHeaderDecl(MMToken::HeaderKeyword, SourceLocation());
1475718292f2SDouglas Gregor       break;
1476718292f2SDouglas Gregor 
14776ddfca91SDouglas Gregor     case MMToken::LinkKeyword:
14786ddfca91SDouglas Gregor       parseLinkDecl();
14796ddfca91SDouglas Gregor       break;
14806ddfca91SDouglas Gregor 
1481718292f2SDouglas Gregor     default:
1482718292f2SDouglas Gregor       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_member);
1483718292f2SDouglas Gregor       consumeToken();
1484718292f2SDouglas Gregor       break;
1485718292f2SDouglas Gregor     }
1486718292f2SDouglas Gregor   } while (!Done);
1487718292f2SDouglas Gregor 
1488718292f2SDouglas Gregor   if (Tok.is(MMToken::RBrace))
1489718292f2SDouglas Gregor     consumeToken();
1490718292f2SDouglas Gregor   else {
1491718292f2SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
1492718292f2SDouglas Gregor     Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
1493718292f2SDouglas Gregor     HadError = true;
1494718292f2SDouglas Gregor   }
1495718292f2SDouglas Gregor 
149611dfe6feSDouglas Gregor   // If the active module is a top-level framework, and there are no link
149711dfe6feSDouglas Gregor   // libraries, automatically link against the framework.
149811dfe6feSDouglas Gregor   if (ActiveModule->IsFramework && !ActiveModule->isSubFramework() &&
149911dfe6feSDouglas Gregor       ActiveModule->LinkLibraries.empty()) {
150011dfe6feSDouglas Gregor     inferFrameworkLink(ActiveModule, Directory, SourceMgr.getFileManager());
150111dfe6feSDouglas Gregor   }
150211dfe6feSDouglas Gregor 
1503ec8c9752SBen Langmuir   // If the module meets all requirements but is still unavailable, mark the
1504ec8c9752SBen Langmuir   // whole tree as unavailable to prevent it from building.
1505ec8c9752SBen Langmuir   if (!ActiveModule->IsAvailable && !ActiveModule->IsMissingRequirement &&
1506ec8c9752SBen Langmuir       ActiveModule->Parent) {
1507ec8c9752SBen Langmuir     ActiveModule->getTopLevelModule()->markUnavailable();
1508ec8c9752SBen Langmuir     ActiveModule->getTopLevelModule()->MissingHeaders.append(
1509ec8c9752SBen Langmuir       ActiveModule->MissingHeaders.begin(), ActiveModule->MissingHeaders.end());
1510ec8c9752SBen Langmuir   }
1511ec8c9752SBen Langmuir 
1512e7ab3669SDouglas Gregor   // We're done parsing this module. Pop back to the previous module.
1513e7ab3669SDouglas Gregor   ActiveModule = PreviousActiveModule;
1514718292f2SDouglas Gregor }
1515718292f2SDouglas Gregor 
151697292843SDaniel Jasper /// \brief Parse an extern module declaration.
151797292843SDaniel Jasper ///
151897292843SDaniel Jasper ///   extern module-declaration:
151997292843SDaniel Jasper ///     'extern' 'module' module-id string-literal
152097292843SDaniel Jasper void ModuleMapParser::parseExternModuleDecl() {
152197292843SDaniel Jasper   assert(Tok.is(MMToken::ExternKeyword));
152297292843SDaniel Jasper   consumeToken(); // 'extern' keyword
152397292843SDaniel Jasper 
152497292843SDaniel Jasper   // Parse 'module' keyword.
152597292843SDaniel Jasper   if (!Tok.is(MMToken::ModuleKeyword)) {
152697292843SDaniel Jasper     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module);
152797292843SDaniel Jasper     consumeToken();
152897292843SDaniel Jasper     HadError = true;
152997292843SDaniel Jasper     return;
153097292843SDaniel Jasper   }
153197292843SDaniel Jasper   consumeToken(); // 'module' keyword
153297292843SDaniel Jasper 
153397292843SDaniel Jasper   // Parse the module name.
153497292843SDaniel Jasper   ModuleId Id;
153597292843SDaniel Jasper   if (parseModuleId(Id)) {
153697292843SDaniel Jasper     HadError = true;
153797292843SDaniel Jasper     return;
153897292843SDaniel Jasper   }
153997292843SDaniel Jasper 
154097292843SDaniel Jasper   // Parse the referenced module map file name.
154197292843SDaniel Jasper   if (!Tok.is(MMToken::StringLiteral)) {
154297292843SDaniel Jasper     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_mmap_file);
154397292843SDaniel Jasper     HadError = true;
154497292843SDaniel Jasper     return;
154597292843SDaniel Jasper   }
154697292843SDaniel Jasper   std::string FileName = Tok.getString();
154797292843SDaniel Jasper   consumeToken(); // filename
154897292843SDaniel Jasper 
154997292843SDaniel Jasper   StringRef FileNameRef = FileName;
155097292843SDaniel Jasper   SmallString<128> ModuleMapFileName;
155197292843SDaniel Jasper   if (llvm::sys::path::is_relative(FileNameRef)) {
155297292843SDaniel Jasper     ModuleMapFileName += Directory->getName();
155397292843SDaniel Jasper     llvm::sys::path::append(ModuleMapFileName, FileName);
155497292843SDaniel Jasper     FileNameRef = ModuleMapFileName.str();
155597292843SDaniel Jasper   }
155697292843SDaniel Jasper   if (const FileEntry *File = SourceMgr.getFileManager().getFile(FileNameRef))
155797292843SDaniel Jasper     Map.parseModuleMapFile(File, /*IsSystem=*/false);
155897292843SDaniel Jasper }
155997292843SDaniel Jasper 
15601fb5c3a6SDouglas Gregor /// \brief Parse a requires declaration.
15611fb5c3a6SDouglas Gregor ///
15621fb5c3a6SDouglas Gregor ///   requires-declaration:
15631fb5c3a6SDouglas Gregor ///     'requires' feature-list
15641fb5c3a6SDouglas Gregor ///
15651fb5c3a6SDouglas Gregor ///   feature-list:
1566a3feee2aSRichard Smith ///     feature ',' feature-list
1567a3feee2aSRichard Smith ///     feature
1568a3feee2aSRichard Smith ///
1569a3feee2aSRichard Smith ///   feature:
1570a3feee2aSRichard Smith ///     '!'[opt] identifier
15711fb5c3a6SDouglas Gregor void ModuleMapParser::parseRequiresDecl() {
15721fb5c3a6SDouglas Gregor   assert(Tok.is(MMToken::RequiresKeyword));
15731fb5c3a6SDouglas Gregor 
15741fb5c3a6SDouglas Gregor   // Parse 'requires' keyword.
15751fb5c3a6SDouglas Gregor   consumeToken();
15761fb5c3a6SDouglas Gregor 
15771fb5c3a6SDouglas Gregor   // Parse the feature-list.
15781fb5c3a6SDouglas Gregor   do {
1579a3feee2aSRichard Smith     bool RequiredState = true;
1580a3feee2aSRichard Smith     if (Tok.is(MMToken::Exclaim)) {
1581a3feee2aSRichard Smith       RequiredState = false;
1582a3feee2aSRichard Smith       consumeToken();
1583a3feee2aSRichard Smith     }
1584a3feee2aSRichard Smith 
15851fb5c3a6SDouglas Gregor     if (!Tok.is(MMToken::Identifier)) {
15861fb5c3a6SDouglas Gregor       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_feature);
15871fb5c3a6SDouglas Gregor       HadError = true;
15881fb5c3a6SDouglas Gregor       return;
15891fb5c3a6SDouglas Gregor     }
15901fb5c3a6SDouglas Gregor 
15911fb5c3a6SDouglas Gregor     // Consume the feature name.
15921fb5c3a6SDouglas Gregor     std::string Feature = Tok.getString();
15931fb5c3a6SDouglas Gregor     consumeToken();
15941fb5c3a6SDouglas Gregor 
15951fb5c3a6SDouglas Gregor     // Add this feature.
1596a3feee2aSRichard Smith     ActiveModule->addRequirement(Feature, RequiredState,
1597a3feee2aSRichard Smith                                  Map.LangOpts, *Map.Target);
15981fb5c3a6SDouglas Gregor 
15991fb5c3a6SDouglas Gregor     if (!Tok.is(MMToken::Comma))
16001fb5c3a6SDouglas Gregor       break;
16011fb5c3a6SDouglas Gregor 
16021fb5c3a6SDouglas Gregor     // Consume the comma.
16031fb5c3a6SDouglas Gregor     consumeToken();
16041fb5c3a6SDouglas Gregor   } while (true);
16051fb5c3a6SDouglas Gregor }
16061fb5c3a6SDouglas Gregor 
1607f2161a70SDouglas Gregor /// \brief Append to \p Paths the set of paths needed to get to the
1608f2161a70SDouglas Gregor /// subframework in which the given module lives.
1609bf8da9d7SBenjamin Kramer static void appendSubframeworkPaths(Module *Mod,
1610f857950dSDmitri Gribenko                                     SmallVectorImpl<char> &Path) {
1611f2161a70SDouglas Gregor   // Collect the framework names from the given module to the top-level module.
1612f857950dSDmitri Gribenko   SmallVector<StringRef, 2> Paths;
1613f2161a70SDouglas Gregor   for (; Mod; Mod = Mod->Parent) {
1614f2161a70SDouglas Gregor     if (Mod->IsFramework)
1615f2161a70SDouglas Gregor       Paths.push_back(Mod->Name);
1616f2161a70SDouglas Gregor   }
1617f2161a70SDouglas Gregor 
1618f2161a70SDouglas Gregor   if (Paths.empty())
1619f2161a70SDouglas Gregor     return;
1620f2161a70SDouglas Gregor 
1621f2161a70SDouglas Gregor   // Add Frameworks/Name.framework for each subframework.
162217381a06SBenjamin Kramer   for (unsigned I = Paths.size() - 1; I != 0; --I)
162317381a06SBenjamin Kramer     llvm::sys::path::append(Path, "Frameworks", Paths[I-1] + ".framework");
1624f2161a70SDouglas Gregor }
1625f2161a70SDouglas Gregor 
1626718292f2SDouglas Gregor /// \brief Parse a header declaration.
1627718292f2SDouglas Gregor ///
1628718292f2SDouglas Gregor ///   header-declaration:
1629322f633cSDouglas Gregor ///     'umbrella'[opt] 'header' string-literal
163059527666SDouglas Gregor ///     'exclude'[opt] 'header' string-literal
1631b53e5483SLawrence Crowl void ModuleMapParser::parseHeaderDecl(MMToken::TokenKind LeadingToken,
1632b53e5483SLawrence Crowl                                       SourceLocation LeadingLoc) {
1633718292f2SDouglas Gregor   assert(Tok.is(MMToken::HeaderKeyword));
16341871ed3dSBenjamin Kramer   consumeToken();
1635718292f2SDouglas Gregor 
1636718292f2SDouglas Gregor   // Parse the header name.
1637718292f2SDouglas Gregor   if (!Tok.is(MMToken::StringLiteral)) {
1638718292f2SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
1639718292f2SDouglas Gregor       << "header";
1640718292f2SDouglas Gregor     HadError = true;
1641718292f2SDouglas Gregor     return;
1642718292f2SDouglas Gregor   }
16430761a8a0SDaniel Jasper   Module::HeaderDirective Header;
16440761a8a0SDaniel Jasper   Header.FileName = Tok.getString();
16450761a8a0SDaniel Jasper   Header.FileNameLoc = consumeToken();
1646718292f2SDouglas Gregor 
1647524e33e1SDouglas Gregor   // Check whether we already have an umbrella.
1648b53e5483SLawrence Crowl   if (LeadingToken == MMToken::UmbrellaKeyword && ActiveModule->Umbrella) {
16490761a8a0SDaniel Jasper     Diags.Report(Header.FileNameLoc, diag::err_mmap_umbrella_clash)
1650524e33e1SDouglas Gregor       << ActiveModule->getFullModuleName();
1651322f633cSDouglas Gregor     HadError = true;
1652322f633cSDouglas Gregor     return;
1653322f633cSDouglas Gregor   }
1654322f633cSDouglas Gregor 
16555257fc63SDouglas Gregor   // Look for this file.
1656d2d442caSCraig Topper   const FileEntry *File = nullptr;
1657d2d442caSCraig Topper   const FileEntry *BuiltinFile = nullptr;
16582c1dd271SDylan Noblesmith   SmallString<128> PathName;
16590761a8a0SDaniel Jasper   if (llvm::sys::path::is_absolute(Header.FileName)) {
16600761a8a0SDaniel Jasper     PathName = Header.FileName;
1661e7ab3669SDouglas Gregor     File = SourceMgr.getFileManager().getFile(PathName);
1662e7ab3669SDouglas Gregor   } else {
1663e7ab3669SDouglas Gregor     // Search for the header file within the search directory.
16647033127bSDouglas Gregor     PathName = Directory->getName();
1665e7ab3669SDouglas Gregor     unsigned PathLength = PathName.size();
1666755b2055SDouglas Gregor 
1667f2161a70SDouglas Gregor     if (ActiveModule->isPartOfFramework()) {
1668f2161a70SDouglas Gregor       appendSubframeworkPaths(ActiveModule, PathName);
1669755b2055SDouglas Gregor 
1670e7ab3669SDouglas Gregor       // Check whether this file is in the public headers.
16710761a8a0SDaniel Jasper       llvm::sys::path::append(PathName, "Headers", Header.FileName);
1672e7ab3669SDouglas Gregor       File = SourceMgr.getFileManager().getFile(PathName);
1673e7ab3669SDouglas Gregor 
1674e7ab3669SDouglas Gregor       if (!File) {
1675e7ab3669SDouglas Gregor         // Check whether this file is in the private headers.
1676e7ab3669SDouglas Gregor         PathName.resize(PathLength);
16770761a8a0SDaniel Jasper         llvm::sys::path::append(PathName, "PrivateHeaders", Header.FileName);
1678e7ab3669SDouglas Gregor         File = SourceMgr.getFileManager().getFile(PathName);
1679e7ab3669SDouglas Gregor       }
1680e7ab3669SDouglas Gregor     } else {
1681e7ab3669SDouglas Gregor       // Lookup for normal headers.
16820761a8a0SDaniel Jasper       llvm::sys::path::append(PathName, Header.FileName);
1683e7ab3669SDouglas Gregor       File = SourceMgr.getFileManager().getFile(PathName);
16843ec6663bSDouglas Gregor 
16853ec6663bSDouglas Gregor       // If this is a system module with a top-level header, this header
16863ec6663bSDouglas Gregor       // may have a counterpart (or replacement) in the set of headers
16873ec6663bSDouglas Gregor       // supplied by Clang. Find that builtin header.
1688b53e5483SLawrence Crowl       if (ActiveModule->IsSystem && LeadingToken != MMToken::UmbrellaKeyword &&
1689b53e5483SLawrence Crowl           BuiltinIncludeDir && BuiltinIncludeDir != Directory &&
16900761a8a0SDaniel Jasper           isBuiltinHeader(Header.FileName)) {
16912c1dd271SDylan Noblesmith         SmallString<128> BuiltinPathName(BuiltinIncludeDir->getName());
16920761a8a0SDaniel Jasper         llvm::sys::path::append(BuiltinPathName, Header.FileName);
16933ec6663bSDouglas Gregor         BuiltinFile = SourceMgr.getFileManager().getFile(BuiltinPathName);
16943ec6663bSDouglas Gregor 
16953ec6663bSDouglas Gregor         // If Clang supplies this header but the underlying system does not,
16963ec6663bSDouglas Gregor         // just silently swap in our builtin version. Otherwise, we'll end
16973ec6663bSDouglas Gregor         // up adding both (later).
16983ec6663bSDouglas Gregor         if (!File && BuiltinFile) {
16993ec6663bSDouglas Gregor           File = BuiltinFile;
1700d2d442caSCraig Topper           BuiltinFile = nullptr;
17013ec6663bSDouglas Gregor         }
17023ec6663bSDouglas Gregor       }
1703e7ab3669SDouglas Gregor     }
1704e7ab3669SDouglas Gregor   }
17055257fc63SDouglas Gregor 
17065257fc63SDouglas Gregor   // FIXME: We shouldn't be eagerly stat'ing every file named in a module map.
17075257fc63SDouglas Gregor   // Come up with a lazy way to do this.
1708e7ab3669SDouglas Gregor   if (File) {
170997da9178SDaniel Jasper     if (LeadingToken == MMToken::UmbrellaKeyword) {
1710322f633cSDouglas Gregor       const DirectoryEntry *UmbrellaDir = File->getDir();
171159527666SDouglas Gregor       if (Module *UmbrellaModule = Map.UmbrellaDirs[UmbrellaDir]) {
1712b53e5483SLawrence Crowl         Diags.Report(LeadingLoc, diag::err_mmap_umbrella_clash)
171359527666SDouglas Gregor           << UmbrellaModule->getFullModuleName();
1714322f633cSDouglas Gregor         HadError = true;
17155257fc63SDouglas Gregor       } else {
1716322f633cSDouglas Gregor         // Record this umbrella header.
1717322f633cSDouglas Gregor         Map.setUmbrellaHeader(ActiveModule, File);
1718322f633cSDouglas Gregor       }
1719322f633cSDouglas Gregor     } else {
1720322f633cSDouglas Gregor       // Record this header.
1721b53e5483SLawrence Crowl       ModuleMap::ModuleHeaderRole Role = ModuleMap::NormalHeader;
1722b53e5483SLawrence Crowl       if (LeadingToken == MMToken::ExcludeKeyword)
1723b53e5483SLawrence Crowl         Role = ModuleMap::ExcludedHeader;
1724b53e5483SLawrence Crowl       else if (LeadingToken == MMToken::PrivateKeyword)
1725b53e5483SLawrence Crowl         Role = ModuleMap::PrivateHeader;
1726b53e5483SLawrence Crowl       else
1727b53e5483SLawrence Crowl         assert(LeadingToken == MMToken::HeaderKeyword);
1728b53e5483SLawrence Crowl 
1729b53e5483SLawrence Crowl       Map.addHeader(ActiveModule, File, Role);
17303ec6663bSDouglas Gregor 
17313ec6663bSDouglas Gregor       // If there is a builtin counterpart to this file, add it now.
17323ec6663bSDouglas Gregor       if (BuiltinFile)
1733b53e5483SLawrence Crowl         Map.addHeader(ActiveModule, BuiltinFile, Role);
17345257fc63SDouglas Gregor     }
1735b53e5483SLawrence Crowl   } else if (LeadingToken != MMToken::ExcludeKeyword) {
17364b27a64bSDouglas Gregor     // Ignore excluded header files. They're optional anyway.
17374b27a64bSDouglas Gregor 
17380761a8a0SDaniel Jasper     // If we find a module that has a missing header, we mark this module as
17390761a8a0SDaniel Jasper     // unavailable and store the header directive for displaying diagnostics.
17400761a8a0SDaniel Jasper     Header.IsUmbrella = LeadingToken == MMToken::UmbrellaKeyword;
1741ec8c9752SBen Langmuir     ActiveModule->markUnavailable();
17420761a8a0SDaniel Jasper     ActiveModule->MissingHeaders.push_back(Header);
17435257fc63SDouglas Gregor   }
1744718292f2SDouglas Gregor }
1745718292f2SDouglas Gregor 
1746524e33e1SDouglas Gregor /// \brief Parse an umbrella directory declaration.
1747524e33e1SDouglas Gregor ///
1748524e33e1SDouglas Gregor ///   umbrella-dir-declaration:
1749524e33e1SDouglas Gregor ///     umbrella string-literal
1750524e33e1SDouglas Gregor void ModuleMapParser::parseUmbrellaDirDecl(SourceLocation UmbrellaLoc) {
1751524e33e1SDouglas Gregor   // Parse the directory name.
1752524e33e1SDouglas Gregor   if (!Tok.is(MMToken::StringLiteral)) {
1753524e33e1SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
1754524e33e1SDouglas Gregor       << "umbrella";
1755524e33e1SDouglas Gregor     HadError = true;
1756524e33e1SDouglas Gregor     return;
1757524e33e1SDouglas Gregor   }
1758524e33e1SDouglas Gregor 
1759524e33e1SDouglas Gregor   std::string DirName = Tok.getString();
1760524e33e1SDouglas Gregor   SourceLocation DirNameLoc = consumeToken();
1761524e33e1SDouglas Gregor 
1762524e33e1SDouglas Gregor   // Check whether we already have an umbrella.
1763524e33e1SDouglas Gregor   if (ActiveModule->Umbrella) {
1764524e33e1SDouglas Gregor     Diags.Report(DirNameLoc, diag::err_mmap_umbrella_clash)
1765524e33e1SDouglas Gregor       << ActiveModule->getFullModuleName();
1766524e33e1SDouglas Gregor     HadError = true;
1767524e33e1SDouglas Gregor     return;
1768524e33e1SDouglas Gregor   }
1769524e33e1SDouglas Gregor 
1770524e33e1SDouglas Gregor   // Look for this file.
1771d2d442caSCraig Topper   const DirectoryEntry *Dir = nullptr;
1772524e33e1SDouglas Gregor   if (llvm::sys::path::is_absolute(DirName))
1773524e33e1SDouglas Gregor     Dir = SourceMgr.getFileManager().getDirectory(DirName);
1774524e33e1SDouglas Gregor   else {
17752c1dd271SDylan Noblesmith     SmallString<128> PathName;
1776524e33e1SDouglas Gregor     PathName = Directory->getName();
1777524e33e1SDouglas Gregor     llvm::sys::path::append(PathName, DirName);
1778524e33e1SDouglas Gregor     Dir = SourceMgr.getFileManager().getDirectory(PathName);
1779524e33e1SDouglas Gregor   }
1780524e33e1SDouglas Gregor 
1781524e33e1SDouglas Gregor   if (!Dir) {
1782524e33e1SDouglas Gregor     Diags.Report(DirNameLoc, diag::err_mmap_umbrella_dir_not_found)
1783524e33e1SDouglas Gregor       << DirName;
1784524e33e1SDouglas Gregor     HadError = true;
1785524e33e1SDouglas Gregor     return;
1786524e33e1SDouglas Gregor   }
1787524e33e1SDouglas Gregor 
1788524e33e1SDouglas Gregor   if (Module *OwningModule = Map.UmbrellaDirs[Dir]) {
1789524e33e1SDouglas Gregor     Diags.Report(UmbrellaLoc, diag::err_mmap_umbrella_clash)
1790524e33e1SDouglas Gregor       << OwningModule->getFullModuleName();
1791524e33e1SDouglas Gregor     HadError = true;
1792524e33e1SDouglas Gregor     return;
1793524e33e1SDouglas Gregor   }
1794524e33e1SDouglas Gregor 
1795524e33e1SDouglas Gregor   // Record this umbrella directory.
1796524e33e1SDouglas Gregor   Map.setUmbrellaDir(ActiveModule, Dir);
1797524e33e1SDouglas Gregor }
1798524e33e1SDouglas Gregor 
17992b82c2a5SDouglas Gregor /// \brief Parse a module export declaration.
18002b82c2a5SDouglas Gregor ///
18012b82c2a5SDouglas Gregor ///   export-declaration:
18022b82c2a5SDouglas Gregor ///     'export' wildcard-module-id
18032b82c2a5SDouglas Gregor ///
18042b82c2a5SDouglas Gregor ///   wildcard-module-id:
18052b82c2a5SDouglas Gregor ///     identifier
18062b82c2a5SDouglas Gregor ///     '*'
18072b82c2a5SDouglas Gregor ///     identifier '.' wildcard-module-id
18082b82c2a5SDouglas Gregor void ModuleMapParser::parseExportDecl() {
18092b82c2a5SDouglas Gregor   assert(Tok.is(MMToken::ExportKeyword));
18102b82c2a5SDouglas Gregor   SourceLocation ExportLoc = consumeToken();
18112b82c2a5SDouglas Gregor 
18122b82c2a5SDouglas Gregor   // Parse the module-id with an optional wildcard at the end.
18132b82c2a5SDouglas Gregor   ModuleId ParsedModuleId;
18142b82c2a5SDouglas Gregor   bool Wildcard = false;
18152b82c2a5SDouglas Gregor   do {
18162b82c2a5SDouglas Gregor     if (Tok.is(MMToken::Identifier)) {
18172b82c2a5SDouglas Gregor       ParsedModuleId.push_back(std::make_pair(Tok.getString(),
18182b82c2a5SDouglas Gregor                                               Tok.getLocation()));
18192b82c2a5SDouglas Gregor       consumeToken();
18202b82c2a5SDouglas Gregor 
18212b82c2a5SDouglas Gregor       if (Tok.is(MMToken::Period)) {
18222b82c2a5SDouglas Gregor         consumeToken();
18232b82c2a5SDouglas Gregor         continue;
18242b82c2a5SDouglas Gregor       }
18252b82c2a5SDouglas Gregor 
18262b82c2a5SDouglas Gregor       break;
18272b82c2a5SDouglas Gregor     }
18282b82c2a5SDouglas Gregor 
18292b82c2a5SDouglas Gregor     if(Tok.is(MMToken::Star)) {
18302b82c2a5SDouglas Gregor       Wildcard = true;
1831f5eedd05SDouglas Gregor       consumeToken();
18322b82c2a5SDouglas Gregor       break;
18332b82c2a5SDouglas Gregor     }
18342b82c2a5SDouglas Gregor 
1835ba7f2f71SDaniel Jasper     Diags.Report(Tok.getLocation(), diag::err_mmap_module_id);
18362b82c2a5SDouglas Gregor     HadError = true;
18372b82c2a5SDouglas Gregor     return;
18382b82c2a5SDouglas Gregor   } while (true);
18392b82c2a5SDouglas Gregor 
18402b82c2a5SDouglas Gregor   Module::UnresolvedExportDecl Unresolved = {
18412b82c2a5SDouglas Gregor     ExportLoc, ParsedModuleId, Wildcard
18422b82c2a5SDouglas Gregor   };
18432b82c2a5SDouglas Gregor   ActiveModule->UnresolvedExports.push_back(Unresolved);
18442b82c2a5SDouglas Gregor }
18452b82c2a5SDouglas Gregor 
1846ba7f2f71SDaniel Jasper /// \brief Parse a module uses declaration.
1847ba7f2f71SDaniel Jasper ///
1848ba7f2f71SDaniel Jasper ///   uses-declaration:
1849ba7f2f71SDaniel Jasper ///     'uses' wildcard-module-id
1850ba7f2f71SDaniel Jasper void ModuleMapParser::parseUseDecl() {
1851ba7f2f71SDaniel Jasper   assert(Tok.is(MMToken::UseKeyword));
1852ba7f2f71SDaniel Jasper   consumeToken();
1853ba7f2f71SDaniel Jasper   // Parse the module-id.
1854ba7f2f71SDaniel Jasper   ModuleId ParsedModuleId;
18553cd34c76SDaniel Jasper   parseModuleId(ParsedModuleId);
1856ba7f2f71SDaniel Jasper 
1857ba7f2f71SDaniel Jasper   ActiveModule->UnresolvedDirectUses.push_back(ParsedModuleId);
1858ba7f2f71SDaniel Jasper }
1859ba7f2f71SDaniel Jasper 
18606ddfca91SDouglas Gregor /// \brief Parse a link declaration.
18616ddfca91SDouglas Gregor ///
18626ddfca91SDouglas Gregor ///   module-declaration:
18636ddfca91SDouglas Gregor ///     'link' 'framework'[opt] string-literal
18646ddfca91SDouglas Gregor void ModuleMapParser::parseLinkDecl() {
18656ddfca91SDouglas Gregor   assert(Tok.is(MMToken::LinkKeyword));
18666ddfca91SDouglas Gregor   SourceLocation LinkLoc = consumeToken();
18676ddfca91SDouglas Gregor 
18686ddfca91SDouglas Gregor   // Parse the optional 'framework' keyword.
18696ddfca91SDouglas Gregor   bool IsFramework = false;
18706ddfca91SDouglas Gregor   if (Tok.is(MMToken::FrameworkKeyword)) {
18716ddfca91SDouglas Gregor     consumeToken();
18726ddfca91SDouglas Gregor     IsFramework = true;
18736ddfca91SDouglas Gregor   }
18746ddfca91SDouglas Gregor 
18756ddfca91SDouglas Gregor   // Parse the library name
18766ddfca91SDouglas Gregor   if (!Tok.is(MMToken::StringLiteral)) {
18776ddfca91SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_library_name)
18786ddfca91SDouglas Gregor       << IsFramework << SourceRange(LinkLoc);
18796ddfca91SDouglas Gregor     HadError = true;
18806ddfca91SDouglas Gregor     return;
18816ddfca91SDouglas Gregor   }
18826ddfca91SDouglas Gregor 
18836ddfca91SDouglas Gregor   std::string LibraryName = Tok.getString();
18846ddfca91SDouglas Gregor   consumeToken();
18856ddfca91SDouglas Gregor   ActiveModule->LinkLibraries.push_back(Module::LinkLibrary(LibraryName,
18866ddfca91SDouglas Gregor                                                             IsFramework));
18876ddfca91SDouglas Gregor }
18886ddfca91SDouglas Gregor 
188935b13eceSDouglas Gregor /// \brief Parse a configuration macro declaration.
189035b13eceSDouglas Gregor ///
189135b13eceSDouglas Gregor ///   module-declaration:
189235b13eceSDouglas Gregor ///     'config_macros' attributes[opt] config-macro-list?
189335b13eceSDouglas Gregor ///
189435b13eceSDouglas Gregor ///   config-macro-list:
189535b13eceSDouglas Gregor ///     identifier (',' identifier)?
189635b13eceSDouglas Gregor void ModuleMapParser::parseConfigMacros() {
189735b13eceSDouglas Gregor   assert(Tok.is(MMToken::ConfigMacros));
189835b13eceSDouglas Gregor   SourceLocation ConfigMacrosLoc = consumeToken();
189935b13eceSDouglas Gregor 
190035b13eceSDouglas Gregor   // Only top-level modules can have configuration macros.
190135b13eceSDouglas Gregor   if (ActiveModule->Parent) {
190235b13eceSDouglas Gregor     Diags.Report(ConfigMacrosLoc, diag::err_mmap_config_macro_submodule);
190335b13eceSDouglas Gregor   }
190435b13eceSDouglas Gregor 
190535b13eceSDouglas Gregor   // Parse the optional attributes.
190635b13eceSDouglas Gregor   Attributes Attrs;
190735b13eceSDouglas Gregor   parseOptionalAttributes(Attrs);
190835b13eceSDouglas Gregor   if (Attrs.IsExhaustive && !ActiveModule->Parent) {
190935b13eceSDouglas Gregor     ActiveModule->ConfigMacrosExhaustive = true;
191035b13eceSDouglas Gregor   }
191135b13eceSDouglas Gregor 
191235b13eceSDouglas Gregor   // If we don't have an identifier, we're done.
191335b13eceSDouglas Gregor   if (!Tok.is(MMToken::Identifier))
191435b13eceSDouglas Gregor     return;
191535b13eceSDouglas Gregor 
191635b13eceSDouglas Gregor   // Consume the first identifier.
191735b13eceSDouglas Gregor   if (!ActiveModule->Parent) {
191835b13eceSDouglas Gregor     ActiveModule->ConfigMacros.push_back(Tok.getString().str());
191935b13eceSDouglas Gregor   }
192035b13eceSDouglas Gregor   consumeToken();
192135b13eceSDouglas Gregor 
192235b13eceSDouglas Gregor   do {
192335b13eceSDouglas Gregor     // If there's a comma, consume it.
192435b13eceSDouglas Gregor     if (!Tok.is(MMToken::Comma))
192535b13eceSDouglas Gregor       break;
192635b13eceSDouglas Gregor     consumeToken();
192735b13eceSDouglas Gregor 
192835b13eceSDouglas Gregor     // We expect to see a macro name here.
192935b13eceSDouglas Gregor     if (!Tok.is(MMToken::Identifier)) {
193035b13eceSDouglas Gregor       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_config_macro);
193135b13eceSDouglas Gregor       break;
193235b13eceSDouglas Gregor     }
193335b13eceSDouglas Gregor 
193435b13eceSDouglas Gregor     // Consume the macro name.
193535b13eceSDouglas Gregor     if (!ActiveModule->Parent) {
193635b13eceSDouglas Gregor       ActiveModule->ConfigMacros.push_back(Tok.getString().str());
193735b13eceSDouglas Gregor     }
193835b13eceSDouglas Gregor     consumeToken();
193935b13eceSDouglas Gregor   } while (true);
194035b13eceSDouglas Gregor }
194135b13eceSDouglas Gregor 
1942fb912657SDouglas Gregor /// \brief Format a module-id into a string.
1943fb912657SDouglas Gregor static std::string formatModuleId(const ModuleId &Id) {
1944fb912657SDouglas Gregor   std::string result;
1945fb912657SDouglas Gregor   {
1946fb912657SDouglas Gregor     llvm::raw_string_ostream OS(result);
1947fb912657SDouglas Gregor 
1948fb912657SDouglas Gregor     for (unsigned I = 0, N = Id.size(); I != N; ++I) {
1949fb912657SDouglas Gregor       if (I)
1950fb912657SDouglas Gregor         OS << ".";
1951fb912657SDouglas Gregor       OS << Id[I].first;
1952fb912657SDouglas Gregor     }
1953fb912657SDouglas Gregor   }
1954fb912657SDouglas Gregor 
1955fb912657SDouglas Gregor   return result;
1956fb912657SDouglas Gregor }
1957fb912657SDouglas Gregor 
1958fb912657SDouglas Gregor /// \brief Parse a conflict declaration.
1959fb912657SDouglas Gregor ///
1960fb912657SDouglas Gregor ///   module-declaration:
1961fb912657SDouglas Gregor ///     'conflict' module-id ',' string-literal
1962fb912657SDouglas Gregor void ModuleMapParser::parseConflict() {
1963fb912657SDouglas Gregor   assert(Tok.is(MMToken::Conflict));
1964fb912657SDouglas Gregor   SourceLocation ConflictLoc = consumeToken();
1965fb912657SDouglas Gregor   Module::UnresolvedConflict Conflict;
1966fb912657SDouglas Gregor 
1967fb912657SDouglas Gregor   // Parse the module-id.
1968fb912657SDouglas Gregor   if (parseModuleId(Conflict.Id))
1969fb912657SDouglas Gregor     return;
1970fb912657SDouglas Gregor 
1971fb912657SDouglas Gregor   // Parse the ','.
1972fb912657SDouglas Gregor   if (!Tok.is(MMToken::Comma)) {
1973fb912657SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_conflicts_comma)
1974fb912657SDouglas Gregor       << SourceRange(ConflictLoc);
1975fb912657SDouglas Gregor     return;
1976fb912657SDouglas Gregor   }
1977fb912657SDouglas Gregor   consumeToken();
1978fb912657SDouglas Gregor 
1979fb912657SDouglas Gregor   // Parse the message.
1980fb912657SDouglas Gregor   if (!Tok.is(MMToken::StringLiteral)) {
1981fb912657SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_conflicts_message)
1982fb912657SDouglas Gregor       << formatModuleId(Conflict.Id);
1983fb912657SDouglas Gregor     return;
1984fb912657SDouglas Gregor   }
1985fb912657SDouglas Gregor   Conflict.Message = Tok.getString().str();
1986fb912657SDouglas Gregor   consumeToken();
1987fb912657SDouglas Gregor 
1988fb912657SDouglas Gregor   // Add this unresolved conflict.
1989fb912657SDouglas Gregor   ActiveModule->UnresolvedConflicts.push_back(Conflict);
1990fb912657SDouglas Gregor }
1991fb912657SDouglas Gregor 
19926ddfca91SDouglas Gregor /// \brief Parse an inferred module declaration (wildcard modules).
19939194a91dSDouglas Gregor ///
19949194a91dSDouglas Gregor ///   module-declaration:
19959194a91dSDouglas Gregor ///     'explicit'[opt] 'framework'[opt] 'module' * attributes[opt]
19969194a91dSDouglas Gregor ///       { inferred-module-member* }
19979194a91dSDouglas Gregor ///
19989194a91dSDouglas Gregor ///   inferred-module-member:
19999194a91dSDouglas Gregor ///     'export' '*'
20009194a91dSDouglas Gregor ///     'exclude' identifier
20019194a91dSDouglas Gregor void ModuleMapParser::parseInferredModuleDecl(bool Framework, bool Explicit) {
200273441091SDouglas Gregor   assert(Tok.is(MMToken::Star));
200373441091SDouglas Gregor   SourceLocation StarLoc = consumeToken();
200473441091SDouglas Gregor   bool Failed = false;
200573441091SDouglas Gregor 
200673441091SDouglas Gregor   // Inferred modules must be submodules.
20079194a91dSDouglas Gregor   if (!ActiveModule && !Framework) {
200873441091SDouglas Gregor     Diags.Report(StarLoc, diag::err_mmap_top_level_inferred_submodule);
200973441091SDouglas Gregor     Failed = true;
201073441091SDouglas Gregor   }
201173441091SDouglas Gregor 
20129194a91dSDouglas Gregor   if (ActiveModule) {
2013524e33e1SDouglas Gregor     // Inferred modules must have umbrella directories.
20144898cde4SBen Langmuir     if (!Failed && ActiveModule->IsAvailable &&
20154898cde4SBen Langmuir         !ActiveModule->getUmbrellaDir()) {
201673441091SDouglas Gregor       Diags.Report(StarLoc, diag::err_mmap_inferred_no_umbrella);
201773441091SDouglas Gregor       Failed = true;
201873441091SDouglas Gregor     }
201973441091SDouglas Gregor 
202073441091SDouglas Gregor     // Check for redefinition of an inferred module.
2021dd005f69SDouglas Gregor     if (!Failed && ActiveModule->InferSubmodules) {
202273441091SDouglas Gregor       Diags.Report(StarLoc, diag::err_mmap_inferred_redef);
2023dd005f69SDouglas Gregor       if (ActiveModule->InferredSubmoduleLoc.isValid())
2024dd005f69SDouglas Gregor         Diags.Report(ActiveModule->InferredSubmoduleLoc,
202573441091SDouglas Gregor                      diag::note_mmap_prev_definition);
202673441091SDouglas Gregor       Failed = true;
202773441091SDouglas Gregor     }
202873441091SDouglas Gregor 
20299194a91dSDouglas Gregor     // Check for the 'framework' keyword, which is not permitted here.
20309194a91dSDouglas Gregor     if (Framework) {
20319194a91dSDouglas Gregor       Diags.Report(StarLoc, diag::err_mmap_inferred_framework_submodule);
20329194a91dSDouglas Gregor       Framework = false;
20339194a91dSDouglas Gregor     }
20349194a91dSDouglas Gregor   } else if (Explicit) {
20359194a91dSDouglas Gregor     Diags.Report(StarLoc, diag::err_mmap_explicit_inferred_framework);
20369194a91dSDouglas Gregor     Explicit = false;
20379194a91dSDouglas Gregor   }
20389194a91dSDouglas Gregor 
203973441091SDouglas Gregor   // If there were any problems with this inferred submodule, skip its body.
204073441091SDouglas Gregor   if (Failed) {
204173441091SDouglas Gregor     if (Tok.is(MMToken::LBrace)) {
204273441091SDouglas Gregor       consumeToken();
204373441091SDouglas Gregor       skipUntil(MMToken::RBrace);
204473441091SDouglas Gregor       if (Tok.is(MMToken::RBrace))
204573441091SDouglas Gregor         consumeToken();
204673441091SDouglas Gregor     }
204773441091SDouglas Gregor     HadError = true;
204873441091SDouglas Gregor     return;
204973441091SDouglas Gregor   }
205073441091SDouglas Gregor 
20519194a91dSDouglas Gregor   // Parse optional attributes.
20524442605fSBill Wendling   Attributes Attrs;
20539194a91dSDouglas Gregor   parseOptionalAttributes(Attrs);
20549194a91dSDouglas Gregor 
20559194a91dSDouglas Gregor   if (ActiveModule) {
205673441091SDouglas Gregor     // Note that we have an inferred submodule.
2057dd005f69SDouglas Gregor     ActiveModule->InferSubmodules = true;
2058dd005f69SDouglas Gregor     ActiveModule->InferredSubmoduleLoc = StarLoc;
2059dd005f69SDouglas Gregor     ActiveModule->InferExplicitSubmodules = Explicit;
20609194a91dSDouglas Gregor   } else {
20619194a91dSDouglas Gregor     // We'll be inferring framework modules for this directory.
20629194a91dSDouglas Gregor     Map.InferredDirectories[Directory].InferModules = true;
20639194a91dSDouglas Gregor     Map.InferredDirectories[Directory].InferSystemModules = Attrs.IsSystem;
2064beee15e7SBen Langmuir     Map.InferredDirectories[Directory].ModuleMapFile = ModuleMapFile;
2065131daca0SRichard Smith     // FIXME: Handle the 'framework' keyword.
20669194a91dSDouglas Gregor   }
206773441091SDouglas Gregor 
206873441091SDouglas Gregor   // Parse the opening brace.
206973441091SDouglas Gregor   if (!Tok.is(MMToken::LBrace)) {
207073441091SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_lbrace_wildcard);
207173441091SDouglas Gregor     HadError = true;
207273441091SDouglas Gregor     return;
207373441091SDouglas Gregor   }
207473441091SDouglas Gregor   SourceLocation LBraceLoc = consumeToken();
207573441091SDouglas Gregor 
207673441091SDouglas Gregor   // Parse the body of the inferred submodule.
207773441091SDouglas Gregor   bool Done = false;
207873441091SDouglas Gregor   do {
207973441091SDouglas Gregor     switch (Tok.Kind) {
208073441091SDouglas Gregor     case MMToken::EndOfFile:
208173441091SDouglas Gregor     case MMToken::RBrace:
208273441091SDouglas Gregor       Done = true;
208373441091SDouglas Gregor       break;
208473441091SDouglas Gregor 
20859194a91dSDouglas Gregor     case MMToken::ExcludeKeyword: {
20869194a91dSDouglas Gregor       if (ActiveModule) {
20879194a91dSDouglas Gregor         Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member)
2088d2d442caSCraig Topper           << (ActiveModule != nullptr);
20899194a91dSDouglas Gregor         consumeToken();
20909194a91dSDouglas Gregor         break;
20919194a91dSDouglas Gregor       }
20929194a91dSDouglas Gregor 
20939194a91dSDouglas Gregor       consumeToken();
20949194a91dSDouglas Gregor       if (!Tok.is(MMToken::Identifier)) {
20959194a91dSDouglas Gregor         Diags.Report(Tok.getLocation(), diag::err_mmap_missing_exclude_name);
20969194a91dSDouglas Gregor         break;
20979194a91dSDouglas Gregor       }
20989194a91dSDouglas Gregor 
20999194a91dSDouglas Gregor       Map.InferredDirectories[Directory].ExcludedModules
21009194a91dSDouglas Gregor         .push_back(Tok.getString());
21019194a91dSDouglas Gregor       consumeToken();
21029194a91dSDouglas Gregor       break;
21039194a91dSDouglas Gregor     }
21049194a91dSDouglas Gregor 
21059194a91dSDouglas Gregor     case MMToken::ExportKeyword:
21069194a91dSDouglas Gregor       if (!ActiveModule) {
21079194a91dSDouglas Gregor         Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member)
2108d2d442caSCraig Topper           << (ActiveModule != nullptr);
21099194a91dSDouglas Gregor         consumeToken();
21109194a91dSDouglas Gregor         break;
21119194a91dSDouglas Gregor       }
21129194a91dSDouglas Gregor 
211373441091SDouglas Gregor       consumeToken();
211473441091SDouglas Gregor       if (Tok.is(MMToken::Star))
2115dd005f69SDouglas Gregor         ActiveModule->InferExportWildcard = true;
211673441091SDouglas Gregor       else
211773441091SDouglas Gregor         Diags.Report(Tok.getLocation(),
211873441091SDouglas Gregor                      diag::err_mmap_expected_export_wildcard);
211973441091SDouglas Gregor       consumeToken();
212073441091SDouglas Gregor       break;
212173441091SDouglas Gregor 
212273441091SDouglas Gregor     case MMToken::ExplicitKeyword:
212373441091SDouglas Gregor     case MMToken::ModuleKeyword:
212473441091SDouglas Gregor     case MMToken::HeaderKeyword:
2125b53e5483SLawrence Crowl     case MMToken::PrivateKeyword:
212673441091SDouglas Gregor     case MMToken::UmbrellaKeyword:
212773441091SDouglas Gregor     default:
21289194a91dSDouglas Gregor       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member)
2129d2d442caSCraig Topper           << (ActiveModule != nullptr);
213073441091SDouglas Gregor       consumeToken();
213173441091SDouglas Gregor       break;
213273441091SDouglas Gregor     }
213373441091SDouglas Gregor   } while (!Done);
213473441091SDouglas Gregor 
213573441091SDouglas Gregor   if (Tok.is(MMToken::RBrace))
213673441091SDouglas Gregor     consumeToken();
213773441091SDouglas Gregor   else {
213873441091SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
213973441091SDouglas Gregor     Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
214073441091SDouglas Gregor     HadError = true;
214173441091SDouglas Gregor   }
214273441091SDouglas Gregor }
214373441091SDouglas Gregor 
21449194a91dSDouglas Gregor /// \brief Parse optional attributes.
21459194a91dSDouglas Gregor ///
21469194a91dSDouglas Gregor ///   attributes:
21479194a91dSDouglas Gregor ///     attribute attributes
21489194a91dSDouglas Gregor ///     attribute
21499194a91dSDouglas Gregor ///
21509194a91dSDouglas Gregor ///   attribute:
21519194a91dSDouglas Gregor ///     [ identifier ]
21529194a91dSDouglas Gregor ///
21539194a91dSDouglas Gregor /// \param Attrs Will be filled in with the parsed attributes.
21549194a91dSDouglas Gregor ///
21559194a91dSDouglas Gregor /// \returns true if an error occurred, false otherwise.
21564442605fSBill Wendling bool ModuleMapParser::parseOptionalAttributes(Attributes &Attrs) {
21579194a91dSDouglas Gregor   bool HadError = false;
21589194a91dSDouglas Gregor 
21599194a91dSDouglas Gregor   while (Tok.is(MMToken::LSquare)) {
21609194a91dSDouglas Gregor     // Consume the '['.
21619194a91dSDouglas Gregor     SourceLocation LSquareLoc = consumeToken();
21629194a91dSDouglas Gregor 
21639194a91dSDouglas Gregor     // Check whether we have an attribute name here.
21649194a91dSDouglas Gregor     if (!Tok.is(MMToken::Identifier)) {
21659194a91dSDouglas Gregor       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_attribute);
21669194a91dSDouglas Gregor       skipUntil(MMToken::RSquare);
21679194a91dSDouglas Gregor       if (Tok.is(MMToken::RSquare))
21689194a91dSDouglas Gregor         consumeToken();
21699194a91dSDouglas Gregor       HadError = true;
21709194a91dSDouglas Gregor     }
21719194a91dSDouglas Gregor 
21729194a91dSDouglas Gregor     // Decode the attribute name.
21739194a91dSDouglas Gregor     AttributeKind Attribute
21749194a91dSDouglas Gregor       = llvm::StringSwitch<AttributeKind>(Tok.getString())
217535b13eceSDouglas Gregor           .Case("exhaustive", AT_exhaustive)
217677944868SRichard Smith           .Case("extern_c", AT_extern_c)
21779194a91dSDouglas Gregor           .Case("system", AT_system)
21789194a91dSDouglas Gregor           .Default(AT_unknown);
21799194a91dSDouglas Gregor     switch (Attribute) {
21809194a91dSDouglas Gregor     case AT_unknown:
21819194a91dSDouglas Gregor       Diags.Report(Tok.getLocation(), diag::warn_mmap_unknown_attribute)
21829194a91dSDouglas Gregor         << Tok.getString();
21839194a91dSDouglas Gregor       break;
21849194a91dSDouglas Gregor 
21859194a91dSDouglas Gregor     case AT_system:
21869194a91dSDouglas Gregor       Attrs.IsSystem = true;
21879194a91dSDouglas Gregor       break;
218835b13eceSDouglas Gregor 
218977944868SRichard Smith     case AT_extern_c:
219077944868SRichard Smith       Attrs.IsExternC = true;
219177944868SRichard Smith       break;
219277944868SRichard Smith 
219335b13eceSDouglas Gregor     case AT_exhaustive:
219435b13eceSDouglas Gregor       Attrs.IsExhaustive = true;
219535b13eceSDouglas Gregor       break;
21969194a91dSDouglas Gregor     }
21979194a91dSDouglas Gregor     consumeToken();
21989194a91dSDouglas Gregor 
21999194a91dSDouglas Gregor     // Consume the ']'.
22009194a91dSDouglas Gregor     if (!Tok.is(MMToken::RSquare)) {
22019194a91dSDouglas Gregor       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rsquare);
22029194a91dSDouglas Gregor       Diags.Report(LSquareLoc, diag::note_mmap_lsquare_match);
22039194a91dSDouglas Gregor       skipUntil(MMToken::RSquare);
22049194a91dSDouglas Gregor       HadError = true;
22059194a91dSDouglas Gregor     }
22069194a91dSDouglas Gregor 
22079194a91dSDouglas Gregor     if (Tok.is(MMToken::RSquare))
22089194a91dSDouglas Gregor       consumeToken();
22099194a91dSDouglas Gregor   }
22109194a91dSDouglas Gregor 
22119194a91dSDouglas Gregor   return HadError;
22129194a91dSDouglas Gregor }
22139194a91dSDouglas Gregor 
2214718292f2SDouglas Gregor /// \brief Parse a module map file.
2215718292f2SDouglas Gregor ///
2216718292f2SDouglas Gregor ///   module-map-file:
2217718292f2SDouglas Gregor ///     module-declaration*
2218718292f2SDouglas Gregor bool ModuleMapParser::parseModuleMapFile() {
2219718292f2SDouglas Gregor   do {
2220718292f2SDouglas Gregor     switch (Tok.Kind) {
2221718292f2SDouglas Gregor     case MMToken::EndOfFile:
2222718292f2SDouglas Gregor       return HadError;
2223718292f2SDouglas Gregor 
2224e7ab3669SDouglas Gregor     case MMToken::ExplicitKeyword:
222597292843SDaniel Jasper     case MMToken::ExternKeyword:
2226718292f2SDouglas Gregor     case MMToken::ModuleKeyword:
2227755b2055SDouglas Gregor     case MMToken::FrameworkKeyword:
2228718292f2SDouglas Gregor       parseModuleDecl();
2229718292f2SDouglas Gregor       break;
2230718292f2SDouglas Gregor 
22311fb5c3a6SDouglas Gregor     case MMToken::Comma:
223235b13eceSDouglas Gregor     case MMToken::ConfigMacros:
2233fb912657SDouglas Gregor     case MMToken::Conflict:
2234a3feee2aSRichard Smith     case MMToken::Exclaim:
223559527666SDouglas Gregor     case MMToken::ExcludeKeyword:
22362b82c2a5SDouglas Gregor     case MMToken::ExportKeyword:
2237718292f2SDouglas Gregor     case MMToken::HeaderKeyword:
2238718292f2SDouglas Gregor     case MMToken::Identifier:
2239718292f2SDouglas Gregor     case MMToken::LBrace:
22406ddfca91SDouglas Gregor     case MMToken::LinkKeyword:
2241a686e1b0SDouglas Gregor     case MMToken::LSquare:
22422b82c2a5SDouglas Gregor     case MMToken::Period:
2243b53e5483SLawrence Crowl     case MMToken::PrivateKeyword:
2244718292f2SDouglas Gregor     case MMToken::RBrace:
2245a686e1b0SDouglas Gregor     case MMToken::RSquare:
22461fb5c3a6SDouglas Gregor     case MMToken::RequiresKeyword:
22472b82c2a5SDouglas Gregor     case MMToken::Star:
2248718292f2SDouglas Gregor     case MMToken::StringLiteral:
2249718292f2SDouglas Gregor     case MMToken::UmbrellaKeyword:
2250ba7f2f71SDaniel Jasper     case MMToken::UseKeyword:
2251718292f2SDouglas Gregor       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module);
2252718292f2SDouglas Gregor       HadError = true;
2253718292f2SDouglas Gregor       consumeToken();
2254718292f2SDouglas Gregor       break;
2255718292f2SDouglas Gregor     }
2256718292f2SDouglas Gregor   } while (true);
2257718292f2SDouglas Gregor }
2258718292f2SDouglas Gregor 
2259963c5535SDouglas Gregor bool ModuleMap::parseModuleMapFile(const FileEntry *File, bool IsSystem) {
22604ddf2221SDouglas Gregor   llvm::DenseMap<const FileEntry *, bool>::iterator Known
22614ddf2221SDouglas Gregor     = ParsedModuleMap.find(File);
22624ddf2221SDouglas Gregor   if (Known != ParsedModuleMap.end())
22634ddf2221SDouglas Gregor     return Known->second;
22644ddf2221SDouglas Gregor 
2265d2d442caSCraig Topper   assert(Target && "Missing target information");
2266cb69b57bSBen Langmuir   auto FileCharacter = IsSystem ? SrcMgr::C_System : SrcMgr::C_User;
2267cb69b57bSBen Langmuir   FileID ID = SourceMgr.createFileID(File, SourceLocation(), FileCharacter);
22681f76c4e8SManuel Klimek   const llvm::MemoryBuffer *Buffer = SourceMgr.getBuffer(ID);
2269718292f2SDouglas Gregor   if (!Buffer)
22704ddf2221SDouglas Gregor     return ParsedModuleMap[File] = true;
2271718292f2SDouglas Gregor 
2272984e1df7SBen Langmuir   // Find the directory for the module. For frameworks, that may require going
2273984e1df7SBen Langmuir   // up from the 'Modules' directory.
2274984e1df7SBen Langmuir   const DirectoryEntry *Dir = File->getDir();
2275984e1df7SBen Langmuir   StringRef DirName(Dir->getName());
2276984e1df7SBen Langmuir   if (llvm::sys::path::filename(DirName) == "Modules") {
2277984e1df7SBen Langmuir     DirName = llvm::sys::path::parent_path(DirName);
2278984e1df7SBen Langmuir     if (DirName.endswith(".framework"))
2279984e1df7SBen Langmuir       Dir = SourceMgr.getFileManager().getDirectory(DirName);
2280984e1df7SBen Langmuir     assert(Dir && "parent must exist");
2281984e1df7SBen Langmuir   }
2282984e1df7SBen Langmuir 
2283718292f2SDouglas Gregor   // Parse this module map file.
22841f76c4e8SManuel Klimek   Lexer L(ID, SourceMgr.getBuffer(ID), SourceMgr, MMapLangOpts);
2285beee15e7SBen Langmuir   ModuleMapParser Parser(L, SourceMgr, Target, Diags, *this, File, Dir,
2286963c5535SDouglas Gregor                          BuiltinIncludeDir, IsSystem);
2287718292f2SDouglas Gregor   bool Result = Parser.parseModuleMapFile();
22884ddf2221SDouglas Gregor   ParsedModuleMap[File] = Result;
2289718292f2SDouglas Gregor   return Result;
2290718292f2SDouglas Gregor }
2291