1718292f2SDouglas Gregor //===--- ModuleMap.cpp - Describe the layout of modules ---------*- C++ -*-===//
2718292f2SDouglas Gregor //
3718292f2SDouglas Gregor //                     The LLVM Compiler Infrastructure
4718292f2SDouglas Gregor //
5718292f2SDouglas Gregor // This file is distributed under the University of Illinois Open Source
6718292f2SDouglas Gregor // License. See LICENSE.TXT for details.
7718292f2SDouglas Gregor //
8718292f2SDouglas Gregor //===----------------------------------------------------------------------===//
9718292f2SDouglas Gregor //
10718292f2SDouglas Gregor // This file defines the ModuleMap implementation, which describes the layout
11718292f2SDouglas Gregor // of a module as it relates to headers.
12718292f2SDouglas Gregor //
13718292f2SDouglas Gregor //===----------------------------------------------------------------------===//
14718292f2SDouglas Gregor #include "clang/Lex/ModuleMap.h"
15a7d03840SJordan Rose #include "clang/Basic/CharInfo.h"
16718292f2SDouglas Gregor #include "clang/Basic/Diagnostic.h"
17811db4eaSDouglas Gregor #include "clang/Basic/DiagnosticOptions.h"
18718292f2SDouglas Gregor #include "clang/Basic/FileManager.h"
19718292f2SDouglas Gregor #include "clang/Basic/TargetInfo.h"
20718292f2SDouglas Gregor #include "clang/Basic/TargetOptions.h"
21b146baabSArgyrios Kyrtzidis #include "clang/Lex/HeaderSearch.h"
229acb99e3SRichard Smith #include "clang/Lex/HeaderSearchOptions.h"
233a02247dSChandler Carruth #include "clang/Lex/LexDiagnostic.h"
243a02247dSChandler Carruth #include "clang/Lex/Lexer.h"
253a02247dSChandler Carruth #include "clang/Lex/LiteralSupport.h"
263a02247dSChandler Carruth #include "llvm/ADT/StringRef.h"
273a02247dSChandler Carruth #include "llvm/ADT/StringSwitch.h"
28718292f2SDouglas Gregor #include "llvm/Support/Allocator.h"
29e89dbc1dSDouglas Gregor #include "llvm/Support/FileSystem.h"
30718292f2SDouglas Gregor #include "llvm/Support/Host.h"
31552c169eSRafael Espindola #include "llvm/Support/Path.h"
32718292f2SDouglas Gregor #include "llvm/Support/raw_ostream.h"
3307c22b78SDouglas Gregor #include <stdlib.h>
3401c7cfa2SDouglas Gregor #if defined(LLVM_ON_UNIX)
35eadae014SDmitri Gribenko #include <limits.h>
3601c7cfa2SDouglas Gregor #endif
37718292f2SDouglas Gregor using namespace clang;
38718292f2SDouglas Gregor 
392b82c2a5SDouglas Gregor Module::ExportDecl
402b82c2a5SDouglas Gregor ModuleMap::resolveExport(Module *Mod,
412b82c2a5SDouglas Gregor                          const Module::UnresolvedExportDecl &Unresolved,
42e4412640SArgyrios Kyrtzidis                          bool Complain) const {
43f5eedd05SDouglas Gregor   // We may have just a wildcard.
44f5eedd05SDouglas Gregor   if (Unresolved.Id.empty()) {
45f5eedd05SDouglas Gregor     assert(Unresolved.Wildcard && "Invalid unresolved export");
46d2d442caSCraig Topper     return Module::ExportDecl(nullptr, true);
47f5eedd05SDouglas Gregor   }
48f5eedd05SDouglas Gregor 
49fb912657SDouglas Gregor   // Resolve the module-id.
50fb912657SDouglas Gregor   Module *Context = resolveModuleId(Unresolved.Id, Mod, Complain);
51fb912657SDouglas Gregor   if (!Context)
52fb912657SDouglas Gregor     return Module::ExportDecl();
53fb912657SDouglas Gregor 
54fb912657SDouglas Gregor   return Module::ExportDecl(Context, Unresolved.Wildcard);
55fb912657SDouglas Gregor }
56fb912657SDouglas Gregor 
57fb912657SDouglas Gregor Module *ModuleMap::resolveModuleId(const ModuleId &Id, Module *Mod,
58fb912657SDouglas Gregor                                    bool Complain) const {
592b82c2a5SDouglas Gregor   // Find the starting module.
60fb912657SDouglas Gregor   Module *Context = lookupModuleUnqualified(Id[0].first, Mod);
612b82c2a5SDouglas Gregor   if (!Context) {
622b82c2a5SDouglas Gregor     if (Complain)
630761a8a0SDaniel Jasper       Diags.Report(Id[0].second, diag::err_mmap_missing_module_unqualified)
64fb912657SDouglas Gregor       << Id[0].first << Mod->getFullModuleName();
652b82c2a5SDouglas Gregor 
66d2d442caSCraig Topper     return nullptr;
672b82c2a5SDouglas Gregor   }
682b82c2a5SDouglas Gregor 
692b82c2a5SDouglas Gregor   // Dig into the module path.
70fb912657SDouglas Gregor   for (unsigned I = 1, N = Id.size(); I != N; ++I) {
71fb912657SDouglas Gregor     Module *Sub = lookupModuleQualified(Id[I].first, Context);
722b82c2a5SDouglas Gregor     if (!Sub) {
732b82c2a5SDouglas Gregor       if (Complain)
740761a8a0SDaniel Jasper         Diags.Report(Id[I].second, diag::err_mmap_missing_module_qualified)
75fb912657SDouglas Gregor         << Id[I].first << Context->getFullModuleName()
76fb912657SDouglas Gregor         << SourceRange(Id[0].second, Id[I-1].second);
772b82c2a5SDouglas Gregor 
78d2d442caSCraig Topper       return nullptr;
792b82c2a5SDouglas Gregor     }
802b82c2a5SDouglas Gregor 
812b82c2a5SDouglas Gregor     Context = Sub;
822b82c2a5SDouglas Gregor   }
832b82c2a5SDouglas Gregor 
84fb912657SDouglas Gregor   return Context;
852b82c2a5SDouglas Gregor }
862b82c2a5SDouglas Gregor 
870761a8a0SDaniel Jasper ModuleMap::ModuleMap(SourceManager &SourceMgr, DiagnosticsEngine &Diags,
88b146baabSArgyrios Kyrtzidis                      const LangOptions &LangOpts, const TargetInfo *Target,
89b146baabSArgyrios Kyrtzidis                      HeaderSearch &HeaderInfo)
900761a8a0SDaniel Jasper     : SourceMgr(SourceMgr), Diags(Diags), LangOpts(LangOpts), Target(Target),
91d2d442caSCraig Topper       HeaderInfo(HeaderInfo), BuiltinIncludeDir(nullptr),
92*a7e2cc68SRichard Smith       CompilingModule(nullptr), SourceModule(nullptr), NumCreatedModules(0) {
930414b857SRichard Smith   MMapLangOpts.LineComment = true;
940414b857SRichard Smith }
95718292f2SDouglas Gregor 
96718292f2SDouglas Gregor ModuleMap::~ModuleMap() {
975acdf59eSDouglas Gregor   for (llvm::StringMap<Module *>::iterator I = Modules.begin(),
985acdf59eSDouglas Gregor                                         IEnd = Modules.end();
995acdf59eSDouglas Gregor        I != IEnd; ++I) {
1005acdf59eSDouglas Gregor     delete I->getValue();
1015acdf59eSDouglas Gregor   }
102718292f2SDouglas Gregor }
103718292f2SDouglas Gregor 
10489929282SDouglas Gregor void ModuleMap::setTarget(const TargetInfo &Target) {
10589929282SDouglas Gregor   assert((!this->Target || this->Target == &Target) &&
10689929282SDouglas Gregor          "Improper target override");
10789929282SDouglas Gregor   this->Target = &Target;
10889929282SDouglas Gregor }
10989929282SDouglas Gregor 
110056396aeSDouglas Gregor /// \brief "Sanitize" a filename so that it can be used as an identifier.
111056396aeSDouglas Gregor static StringRef sanitizeFilenameAsIdentifier(StringRef Name,
112056396aeSDouglas Gregor                                               SmallVectorImpl<char> &Buffer) {
113056396aeSDouglas Gregor   if (Name.empty())
114056396aeSDouglas Gregor     return Name;
115056396aeSDouglas Gregor 
116a7d03840SJordan Rose   if (!isValidIdentifier(Name)) {
117056396aeSDouglas Gregor     // If we don't already have something with the form of an identifier,
118056396aeSDouglas Gregor     // create a buffer with the sanitized name.
119056396aeSDouglas Gregor     Buffer.clear();
120a7d03840SJordan Rose     if (isDigit(Name[0]))
121056396aeSDouglas Gregor       Buffer.push_back('_');
122056396aeSDouglas Gregor     Buffer.reserve(Buffer.size() + Name.size());
123056396aeSDouglas Gregor     for (unsigned I = 0, N = Name.size(); I != N; ++I) {
124a7d03840SJordan Rose       if (isIdentifierBody(Name[I]))
125056396aeSDouglas Gregor         Buffer.push_back(Name[I]);
126056396aeSDouglas Gregor       else
127056396aeSDouglas Gregor         Buffer.push_back('_');
128056396aeSDouglas Gregor     }
129056396aeSDouglas Gregor 
130056396aeSDouglas Gregor     Name = StringRef(Buffer.data(), Buffer.size());
131056396aeSDouglas Gregor   }
132056396aeSDouglas Gregor 
133056396aeSDouglas Gregor   while (llvm::StringSwitch<bool>(Name)
134056396aeSDouglas Gregor #define KEYWORD(Keyword,Conditions) .Case(#Keyword, true)
135056396aeSDouglas Gregor #define ALIAS(Keyword, AliasOf, Conditions) .Case(Keyword, true)
136056396aeSDouglas Gregor #include "clang/Basic/TokenKinds.def"
137056396aeSDouglas Gregor            .Default(false)) {
138056396aeSDouglas Gregor     if (Name.data() != Buffer.data())
139056396aeSDouglas Gregor       Buffer.append(Name.begin(), Name.end());
140056396aeSDouglas Gregor     Buffer.push_back('_');
141056396aeSDouglas Gregor     Name = StringRef(Buffer.data(), Buffer.size());
142056396aeSDouglas Gregor   }
143056396aeSDouglas Gregor 
144056396aeSDouglas Gregor   return Name;
145056396aeSDouglas Gregor }
146056396aeSDouglas Gregor 
14734d52749SDouglas Gregor /// \brief Determine whether the given file name is the name of a builtin
14834d52749SDouglas Gregor /// header, supplied by Clang to replace, override, or augment existing system
14934d52749SDouglas Gregor /// headers.
15034d52749SDouglas Gregor static bool isBuiltinHeader(StringRef FileName) {
15134d52749SDouglas Gregor   return llvm::StringSwitch<bool>(FileName)
15234d52749SDouglas Gregor            .Case("float.h", true)
15334d52749SDouglas Gregor            .Case("iso646.h", true)
15434d52749SDouglas Gregor            .Case("limits.h", true)
15534d52749SDouglas Gregor            .Case("stdalign.h", true)
15634d52749SDouglas Gregor            .Case("stdarg.h", true)
15734d52749SDouglas Gregor            .Case("stdbool.h", true)
15834d52749SDouglas Gregor            .Case("stddef.h", true)
15934d52749SDouglas Gregor            .Case("stdint.h", true)
16034d52749SDouglas Gregor            .Case("tgmath.h", true)
16134d52749SDouglas Gregor            .Case("unwind.h", true)
16234d52749SDouglas Gregor            .Default(false);
16334d52749SDouglas Gregor }
16434d52749SDouglas Gregor 
16592669ee4SDaniel Jasper ModuleMap::HeadersMap::iterator
16692669ee4SDaniel Jasper ModuleMap::findKnownHeader(const FileEntry *File) {
16759527666SDouglas Gregor   HeadersMap::iterator Known = Headers.find(File);
1684eaf0a6cSDaniel Jasper   if (Known == Headers.end() && File->getDir() == BuiltinIncludeDir &&
1694eaf0a6cSDaniel Jasper       isBuiltinHeader(llvm::sys::path::filename(File->getName()))) {
1704eaf0a6cSDaniel Jasper     HeaderInfo.loadTopLevelSystemModules();
17192669ee4SDaniel Jasper     return Headers.find(File);
1724eaf0a6cSDaniel Jasper   }
17392669ee4SDaniel Jasper   return Known;
17492669ee4SDaniel Jasper }
17592669ee4SDaniel Jasper 
1764469138eSBen Langmuir ModuleMap::KnownHeader
1774469138eSBen Langmuir ModuleMap::findHeaderInUmbrellaDirs(const FileEntry *File,
1784469138eSBen Langmuir                     SmallVectorImpl<const DirectoryEntry *> &IntermediateDirs) {
1794469138eSBen Langmuir   const DirectoryEntry *Dir = File->getDir();
1804469138eSBen Langmuir   assert(Dir && "file in no directory");
1814469138eSBen Langmuir 
1824469138eSBen Langmuir   // Note: as an egregious but useful hack we use the real path here, because
1834469138eSBen Langmuir   // frameworks moving from top-level frameworks to embedded frameworks tend
1844469138eSBen Langmuir   // to be symlinked from the top-level location to the embedded location,
1854469138eSBen Langmuir   // and we need to resolve lookups as if we had found the embedded location.
1864469138eSBen Langmuir   StringRef DirName = SourceMgr.getFileManager().getCanonicalName(Dir);
1874469138eSBen Langmuir 
1884469138eSBen Langmuir   // Keep walking up the directory hierarchy, looking for a directory with
1894469138eSBen Langmuir   // an umbrella header.
1904469138eSBen Langmuir   do {
1914469138eSBen Langmuir     auto KnownDir = UmbrellaDirs.find(Dir);
1924469138eSBen Langmuir     if (KnownDir != UmbrellaDirs.end())
1934469138eSBen Langmuir       return KnownHeader(KnownDir->second, NormalHeader);
1944469138eSBen Langmuir 
1954469138eSBen Langmuir     IntermediateDirs.push_back(Dir);
1964469138eSBen Langmuir 
1974469138eSBen Langmuir     // Retrieve our parent path.
1984469138eSBen Langmuir     DirName = llvm::sys::path::parent_path(DirName);
1994469138eSBen Langmuir     if (DirName.empty())
2004469138eSBen Langmuir       break;
2014469138eSBen Langmuir 
2024469138eSBen Langmuir     // Resolve the parent path to a directory entry.
2034469138eSBen Langmuir     Dir = SourceMgr.getFileManager().getDirectory(DirName);
2044469138eSBen Langmuir   } while (Dir);
2054469138eSBen Langmuir   return KnownHeader();
2064469138eSBen Langmuir }
2074469138eSBen Langmuir 
20892669ee4SDaniel Jasper static bool violatesPrivateInclude(Module *RequestingModule,
20992669ee4SDaniel Jasper                                    const FileEntry *IncFileEnt,
21092669ee4SDaniel Jasper                                    ModuleMap::ModuleHeaderRole Role,
21192669ee4SDaniel Jasper                                    Module *RequestedModule) {
212202210b3SRichard Smith   bool IsPrivateRole = Role & ModuleMap::PrivateHeader;
21392669ee4SDaniel Jasper #ifndef NDEBUG
2142708e520SRichard Smith   if (IsPrivateRole) {
21592669ee4SDaniel Jasper     // Check for consistency between the module header role
21692669ee4SDaniel Jasper     // as obtained from the lookup and as obtained from the module.
21792669ee4SDaniel Jasper     // This check is not cheap, so enable it only for debugging.
2182708e520SRichard Smith     bool IsPrivate = false;
2192708e520SRichard Smith     SmallVectorImpl<Module::Header> *HeaderList[] = {
2202708e520SRichard Smith         &RequestedModule->Headers[Module::HK_Private],
2212708e520SRichard Smith         &RequestedModule->Headers[Module::HK_PrivateTextual]};
2222708e520SRichard Smith     for (auto *Hs : HeaderList)
2232708e520SRichard Smith       IsPrivate |=
2242708e520SRichard Smith           std::find_if(Hs->begin(), Hs->end(), [&](const Module::Header &H) {
2253c1a41adSRichard Smith             return H.Entry == IncFileEnt;
2262708e520SRichard Smith           }) != Hs->end();
2272708e520SRichard Smith     assert((!IsPrivateRole || IsPrivate) && "inconsistent headers and roles");
22800bc95ecSRichard Smith   }
22992669ee4SDaniel Jasper #endif
230202210b3SRichard Smith   return IsPrivateRole &&
2318f4d3ff1SRichard Smith          // FIXME: Should we map RequestingModule to its top-level module here
2328f4d3ff1SRichard Smith          //        too? This check is redundant with the isSubModuleOf check in
2338f4d3ff1SRichard Smith          //        diagnoseHeaderInclusion.
23492669ee4SDaniel Jasper          RequestedModule->getTopLevelModule() != RequestingModule;
23592669ee4SDaniel Jasper }
23692669ee4SDaniel Jasper 
23771e1a64fSBen Langmuir static Module *getTopLevelOrNull(Module *M) {
23871e1a64fSBen Langmuir   return M ? M->getTopLevelModule() : nullptr;
23971e1a64fSBen Langmuir }
24071e1a64fSBen Langmuir 
24192669ee4SDaniel Jasper void ModuleMap::diagnoseHeaderInclusion(Module *RequestingModule,
24292669ee4SDaniel Jasper                                         SourceLocation FilenameLoc,
24392669ee4SDaniel Jasper                                         StringRef Filename,
24492669ee4SDaniel Jasper                                         const FileEntry *File) {
24592669ee4SDaniel Jasper   // No errors for indirect modules. This may be a bit of a problem for modules
24692669ee4SDaniel Jasper   // with no source files.
24771e1a64fSBen Langmuir   if (getTopLevelOrNull(RequestingModule) != getTopLevelOrNull(SourceModule))
24892669ee4SDaniel Jasper     return;
24992669ee4SDaniel Jasper 
25092669ee4SDaniel Jasper   if (RequestingModule)
25192669ee4SDaniel Jasper     resolveUses(RequestingModule, /*Complain=*/false);
25292669ee4SDaniel Jasper 
25371e1a64fSBen Langmuir   bool Excluded = false;
254d2d442caSCraig Topper   Module *Private = nullptr;
255d2d442caSCraig Topper   Module *NotUsed = nullptr;
25671e1a64fSBen Langmuir 
25771e1a64fSBen Langmuir   HeadersMap::iterator Known = findKnownHeader(File);
25871e1a64fSBen Langmuir   if (Known != Headers.end()) {
25971e1a64fSBen Langmuir     for (const KnownHeader &Header : Known->second) {
26092669ee4SDaniel Jasper       // If 'File' is part of 'RequestingModule' we can definitely include it.
2610ab544f1SDaniel Jasper       if (Header.getModule() &&
2620ab544f1SDaniel Jasper           Header.getModule()->isSubModuleOf(RequestingModule))
26392669ee4SDaniel Jasper         return;
26492669ee4SDaniel Jasper 
26592669ee4SDaniel Jasper       // Remember private headers for later printing of a diagnostic.
26671e1a64fSBen Langmuir       if (violatesPrivateInclude(RequestingModule, File, Header.getRole(),
26771e1a64fSBen Langmuir                                  Header.getModule())) {
26871e1a64fSBen Langmuir         Private = Header.getModule();
26992669ee4SDaniel Jasper         continue;
27092669ee4SDaniel Jasper       }
27192669ee4SDaniel Jasper 
27292669ee4SDaniel Jasper       // If uses need to be specified explicitly, we are only allowed to return
27392669ee4SDaniel Jasper       // modules that are explicitly used by the requesting module.
27492669ee4SDaniel Jasper       if (RequestingModule && LangOpts.ModulesDeclUse &&
2758f4d3ff1SRichard Smith           !RequestingModule->directlyUses(Header.getModule())) {
27671e1a64fSBen Langmuir         NotUsed = Header.getModule();
27792669ee4SDaniel Jasper         continue;
27892669ee4SDaniel Jasper       }
27992669ee4SDaniel Jasper 
28092669ee4SDaniel Jasper       // We have found a module that we can happily use.
28192669ee4SDaniel Jasper       return;
28292669ee4SDaniel Jasper     }
283feb54b6dSRichard Smith 
284feb54b6dSRichard Smith     Excluded = true;
28571e1a64fSBen Langmuir   }
28692669ee4SDaniel Jasper 
28792669ee4SDaniel Jasper   // We have found a header, but it is private.
288d2d442caSCraig Topper   if (Private) {
28911152dd5SRichard Smith     Diags.Report(FilenameLoc, diag::warn_use_of_private_header_outside_module)
29092669ee4SDaniel Jasper         << Filename;
29192669ee4SDaniel Jasper     return;
29292669ee4SDaniel Jasper   }
29392669ee4SDaniel Jasper 
29492669ee4SDaniel Jasper   // We have found a module, but we don't use it.
295d2d442caSCraig Topper   if (NotUsed) {
29611152dd5SRichard Smith     Diags.Report(FilenameLoc, diag::err_undeclared_use_of_module)
29792669ee4SDaniel Jasper         << RequestingModule->getFullModuleName() << Filename;
29892669ee4SDaniel Jasper     return;
29992669ee4SDaniel Jasper   }
30092669ee4SDaniel Jasper 
30171e1a64fSBen Langmuir   if (Excluded || isHeaderInUmbrellaDirs(File))
30271e1a64fSBen Langmuir     return;
30371e1a64fSBen Langmuir 
30471e1a64fSBen Langmuir   // At this point, only non-modular includes remain.
30571e1a64fSBen Langmuir 
30671e1a64fSBen Langmuir   if (LangOpts.ModulesStrictDeclUse) {
30711152dd5SRichard Smith     Diags.Report(FilenameLoc, diag::err_undeclared_use_of_module)
30871e1a64fSBen Langmuir         << RequestingModule->getFullModuleName() << Filename;
30971e1a64fSBen Langmuir   } else if (RequestingModule) {
31071e1a64fSBen Langmuir     diag::kind DiagID = RequestingModule->getTopLevelModule()->IsFramework ?
31171e1a64fSBen Langmuir         diag::warn_non_modular_include_in_framework_module :
31271e1a64fSBen Langmuir         diag::warn_non_modular_include_in_module;
31371e1a64fSBen Langmuir     Diags.Report(FilenameLoc, DiagID) << RequestingModule->getFullModuleName();
31471e1a64fSBen Langmuir   }
31592669ee4SDaniel Jasper }
31692669ee4SDaniel Jasper 
317ec87a50aSRichard Smith static bool isBetterKnownHeader(const ModuleMap::KnownHeader &New,
318ec87a50aSRichard Smith                                 const ModuleMap::KnownHeader &Old) {
319ec87a50aSRichard Smith   // Prefer a public header over a private header.
320ec87a50aSRichard Smith   if ((New.getRole() & ModuleMap::PrivateHeader) !=
321ec87a50aSRichard Smith       (Old.getRole() & ModuleMap::PrivateHeader))
322ec87a50aSRichard Smith     return !(New.getRole() & ModuleMap::PrivateHeader);
323ec87a50aSRichard Smith 
324ec87a50aSRichard Smith   // Prefer a non-textual header over a textual header.
325ec87a50aSRichard Smith   if ((New.getRole() & ModuleMap::TextualHeader) !=
326ec87a50aSRichard Smith       (Old.getRole() & ModuleMap::TextualHeader))
327ec87a50aSRichard Smith     return !(New.getRole() & ModuleMap::TextualHeader);
328ec87a50aSRichard Smith 
329ec87a50aSRichard Smith   // Don't have a reason to choose between these. Just keep the first one.
330ec87a50aSRichard Smith   return false;
331ec87a50aSRichard Smith }
332ec87a50aSRichard Smith 
33392669ee4SDaniel Jasper ModuleMap::KnownHeader
33492669ee4SDaniel Jasper ModuleMap::findModuleForHeader(const FileEntry *File,
335306d8920SRichard Smith                                Module *RequestingModule,
336306d8920SRichard Smith                                bool IncludeTextualHeaders) {
33792669ee4SDaniel Jasper   HeadersMap::iterator Known = findKnownHeader(File);
3384eaf0a6cSDaniel Jasper 
339306d8920SRichard Smith   auto MakeResult = [&](ModuleMap::KnownHeader R) -> ModuleMap::KnownHeader {
340202210b3SRichard Smith     if (!IncludeTextualHeaders && (R.getRole() & ModuleMap::TextualHeader))
341306d8920SRichard Smith       return ModuleMap::KnownHeader();
342306d8920SRichard Smith     return R;
343306d8920SRichard Smith   };
344306d8920SRichard Smith 
3451fb5c3a6SDouglas Gregor   if (Known != Headers.end()) {
346202210b3SRichard Smith     ModuleMap::KnownHeader Result;
3471fb5c3a6SDouglas Gregor 
34897da9178SDaniel Jasper     // Iterate over all modules that 'File' is part of to find the best fit.
34997da9178SDaniel Jasper     for (SmallVectorImpl<KnownHeader>::iterator I = Known->second.begin(),
35097da9178SDaniel Jasper                                                 E = Known->second.end();
35197da9178SDaniel Jasper          I != E; ++I) {
3524eaf0a6cSDaniel Jasper       // Cannot use a module if it is unavailable.
3534eaf0a6cSDaniel Jasper       if (!I->getModule()->isAvailable())
35497da9178SDaniel Jasper         continue;
35597da9178SDaniel Jasper 
35697da9178SDaniel Jasper       // If 'File' is part of 'RequestingModule', 'RequestingModule' is the
35797da9178SDaniel Jasper       // module we are looking for.
35897da9178SDaniel Jasper       if (I->getModule() == RequestingModule)
359306d8920SRichard Smith         return MakeResult(*I);
36097da9178SDaniel Jasper 
36197da9178SDaniel Jasper       // If uses need to be specified explicitly, we are only allowed to return
36297da9178SDaniel Jasper       // modules that are explicitly used by the requesting module.
36397da9178SDaniel Jasper       if (RequestingModule && LangOpts.ModulesDeclUse &&
3648f4d3ff1SRichard Smith           !RequestingModule->directlyUses(I->getModule()))
36597da9178SDaniel Jasper         continue;
3664eaf0a6cSDaniel Jasper 
367ec87a50aSRichard Smith       if (!Result || isBetterKnownHeader(*I, Result))
36897da9178SDaniel Jasper         Result = *I;
36997da9178SDaniel Jasper     }
370306d8920SRichard Smith     return MakeResult(Result);
3711fb5c3a6SDouglas Gregor   }
372ab0c8a84SDouglas Gregor 
373f857950dSDmitri Gribenko   SmallVector<const DirectoryEntry *, 2> SkippedDirs;
3744469138eSBen Langmuir   KnownHeader H = findHeaderInUmbrellaDirs(File, SkippedDirs);
3754469138eSBen Langmuir   if (H) {
3764469138eSBen Langmuir     Module *Result = H.getModule();
377930a85ccSDouglas Gregor 
378930a85ccSDouglas Gregor     // Search up the module stack until we find a module with an umbrella
37973141fa9SDouglas Gregor     // directory.
380930a85ccSDouglas Gregor     Module *UmbrellaModule = Result;
38173141fa9SDouglas Gregor     while (!UmbrellaModule->getUmbrellaDir() && UmbrellaModule->Parent)
382930a85ccSDouglas Gregor       UmbrellaModule = UmbrellaModule->Parent;
383930a85ccSDouglas Gregor 
384930a85ccSDouglas Gregor     if (UmbrellaModule->InferSubmodules) {
3859d6448b1SBen Langmuir       const FileEntry *UmbrellaModuleMap =
3869d6448b1SBen Langmuir           getModuleMapFileForUniquing(UmbrellaModule);
3879d6448b1SBen Langmuir 
388a89c5ac4SDouglas Gregor       // Infer submodules for each of the directories we found between
389a89c5ac4SDouglas Gregor       // the directory of the umbrella header and the directory where
390a89c5ac4SDouglas Gregor       // the actual header is located.
3919458f82dSDouglas Gregor       bool Explicit = UmbrellaModule->InferExplicitSubmodules;
3929458f82dSDouglas Gregor 
3937033127bSDouglas Gregor       for (unsigned I = SkippedDirs.size(); I != 0; --I) {
394a89c5ac4SDouglas Gregor         // Find or create the module that corresponds to this directory name.
395056396aeSDouglas Gregor         SmallString<32> NameBuf;
396056396aeSDouglas Gregor         StringRef Name = sanitizeFilenameAsIdentifier(
3974469138eSBen Langmuir             llvm::sys::path::stem(SkippedDirs[I-1]->getName()), NameBuf);
3989d6448b1SBen Langmuir         Result = findOrCreateModule(Name, Result, /*IsFramework=*/false,
3999d6448b1SBen Langmuir                                     Explicit).first;
4009d6448b1SBen Langmuir         InferredModuleAllowedBy[Result] = UmbrellaModuleMap;
401ffbafa2aSBen Langmuir         Result->IsInferred = true;
402a89c5ac4SDouglas Gregor 
403a89c5ac4SDouglas Gregor         // Associate the module and the directory.
404a89c5ac4SDouglas Gregor         UmbrellaDirs[SkippedDirs[I-1]] = Result;
405a89c5ac4SDouglas Gregor 
406a89c5ac4SDouglas Gregor         // If inferred submodules export everything they import, add a
407a89c5ac4SDouglas Gregor         // wildcard to the set of exports.
408930a85ccSDouglas Gregor         if (UmbrellaModule->InferExportWildcard && Result->Exports.empty())
409d2d442caSCraig Topper           Result->Exports.push_back(Module::ExportDecl(nullptr, true));
410a89c5ac4SDouglas Gregor       }
411a89c5ac4SDouglas Gregor 
412a89c5ac4SDouglas Gregor       // Infer a submodule with the same name as this header file.
413056396aeSDouglas Gregor       SmallString<32> NameBuf;
414056396aeSDouglas Gregor       StringRef Name = sanitizeFilenameAsIdentifier(
415056396aeSDouglas Gregor                          llvm::sys::path::stem(File->getName()), NameBuf);
4169d6448b1SBen Langmuir       Result = findOrCreateModule(Name, Result, /*IsFramework=*/false,
4179d6448b1SBen Langmuir                                   Explicit).first;
4189d6448b1SBen Langmuir       InferredModuleAllowedBy[Result] = UmbrellaModuleMap;
419ffbafa2aSBen Langmuir       Result->IsInferred = true;
4203c5305c1SArgyrios Kyrtzidis       Result->addTopHeader(File);
421a89c5ac4SDouglas Gregor 
422a89c5ac4SDouglas Gregor       // If inferred submodules export everything they import, add a
423a89c5ac4SDouglas Gregor       // wildcard to the set of exports.
424930a85ccSDouglas Gregor       if (UmbrellaModule->InferExportWildcard && Result->Exports.empty())
425d2d442caSCraig Topper         Result->Exports.push_back(Module::ExportDecl(nullptr, true));
426a89c5ac4SDouglas Gregor     } else {
427a89c5ac4SDouglas Gregor       // Record each of the directories we stepped through as being part of
428a89c5ac4SDouglas Gregor       // the module we found, since the umbrella header covers them all.
429a89c5ac4SDouglas Gregor       for (unsigned I = 0, N = SkippedDirs.size(); I != N; ++I)
430a89c5ac4SDouglas Gregor         UmbrellaDirs[SkippedDirs[I]] = Result;
431a89c5ac4SDouglas Gregor     }
432a89c5ac4SDouglas Gregor 
43397da9178SDaniel Jasper     Headers[File].push_back(KnownHeader(Result, NormalHeader));
4341fb5c3a6SDouglas Gregor 
4351fb5c3a6SDouglas Gregor     // If a header corresponds to an unavailable module, don't report
4361fb5c3a6SDouglas Gregor     // that it maps to anything.
4371fb5c3a6SDouglas Gregor     if (!Result->isAvailable())
438b53e5483SLawrence Crowl       return KnownHeader();
4391fb5c3a6SDouglas Gregor 
440306d8920SRichard Smith     return MakeResult(Headers[File].back());
441a89c5ac4SDouglas Gregor   }
442a89c5ac4SDouglas Gregor 
443b53e5483SLawrence Crowl   return KnownHeader();
444ab0c8a84SDouglas Gregor }
445ab0c8a84SDouglas Gregor 
446e4412640SArgyrios Kyrtzidis bool ModuleMap::isHeaderInUnavailableModule(const FileEntry *Header) const {
447d2d442caSCraig Topper   return isHeaderUnavailableInModule(Header, nullptr);
44850996ce1SRichard Smith }
44950996ce1SRichard Smith 
45062bcd925SDmitri Gribenko bool
45162bcd925SDmitri Gribenko ModuleMap::isHeaderUnavailableInModule(const FileEntry *Header,
45262bcd925SDmitri Gribenko                                        const Module *RequestingModule) const {
453e4412640SArgyrios Kyrtzidis   HeadersMap::const_iterator Known = Headers.find(Header);
45497da9178SDaniel Jasper   if (Known != Headers.end()) {
45597da9178SDaniel Jasper     for (SmallVectorImpl<KnownHeader>::const_iterator
45697da9178SDaniel Jasper              I = Known->second.begin(),
45797da9178SDaniel Jasper              E = Known->second.end();
45897da9178SDaniel Jasper          I != E; ++I) {
45950996ce1SRichard Smith       if (I->isAvailable() && (!RequestingModule ||
46050996ce1SRichard Smith                                I->getModule()->isSubModuleOf(RequestingModule)))
46197da9178SDaniel Jasper         return false;
46297da9178SDaniel Jasper     }
46397da9178SDaniel Jasper     return true;
46497da9178SDaniel Jasper   }
4651fb5c3a6SDouglas Gregor 
4661fb5c3a6SDouglas Gregor   const DirectoryEntry *Dir = Header->getDir();
467f857950dSDmitri Gribenko   SmallVector<const DirectoryEntry *, 2> SkippedDirs;
4681fb5c3a6SDouglas Gregor   StringRef DirName = Dir->getName();
4691fb5c3a6SDouglas Gregor 
47050996ce1SRichard Smith   auto IsUnavailable = [&](const Module *M) {
47150996ce1SRichard Smith     return !M->isAvailable() && (!RequestingModule ||
47250996ce1SRichard Smith                                  M->isSubModuleOf(RequestingModule));
47350996ce1SRichard Smith   };
47450996ce1SRichard Smith 
4751fb5c3a6SDouglas Gregor   // Keep walking up the directory hierarchy, looking for a directory with
4761fb5c3a6SDouglas Gregor   // an umbrella header.
4771fb5c3a6SDouglas Gregor   do {
478e4412640SArgyrios Kyrtzidis     llvm::DenseMap<const DirectoryEntry *, Module *>::const_iterator KnownDir
4791fb5c3a6SDouglas Gregor       = UmbrellaDirs.find(Dir);
4801fb5c3a6SDouglas Gregor     if (KnownDir != UmbrellaDirs.end()) {
4811fb5c3a6SDouglas Gregor       Module *Found = KnownDir->second;
48250996ce1SRichard Smith       if (IsUnavailable(Found))
4831fb5c3a6SDouglas Gregor         return true;
4841fb5c3a6SDouglas Gregor 
4851fb5c3a6SDouglas Gregor       // Search up the module stack until we find a module with an umbrella
4861fb5c3a6SDouglas Gregor       // directory.
4871fb5c3a6SDouglas Gregor       Module *UmbrellaModule = Found;
4881fb5c3a6SDouglas Gregor       while (!UmbrellaModule->getUmbrellaDir() && UmbrellaModule->Parent)
4891fb5c3a6SDouglas Gregor         UmbrellaModule = UmbrellaModule->Parent;
4901fb5c3a6SDouglas Gregor 
4911fb5c3a6SDouglas Gregor       if (UmbrellaModule->InferSubmodules) {
4921fb5c3a6SDouglas Gregor         for (unsigned I = SkippedDirs.size(); I != 0; --I) {
4931fb5c3a6SDouglas Gregor           // Find or create the module that corresponds to this directory name.
494056396aeSDouglas Gregor           SmallString<32> NameBuf;
495056396aeSDouglas Gregor           StringRef Name = sanitizeFilenameAsIdentifier(
496056396aeSDouglas Gregor                              llvm::sys::path::stem(SkippedDirs[I-1]->getName()),
497056396aeSDouglas Gregor                              NameBuf);
4981fb5c3a6SDouglas Gregor           Found = lookupModuleQualified(Name, Found);
4991fb5c3a6SDouglas Gregor           if (!Found)
5001fb5c3a6SDouglas Gregor             return false;
50150996ce1SRichard Smith           if (IsUnavailable(Found))
5021fb5c3a6SDouglas Gregor             return true;
5031fb5c3a6SDouglas Gregor         }
5041fb5c3a6SDouglas Gregor 
5051fb5c3a6SDouglas Gregor         // Infer a submodule with the same name as this header file.
506056396aeSDouglas Gregor         SmallString<32> NameBuf;
507056396aeSDouglas Gregor         StringRef Name = sanitizeFilenameAsIdentifier(
508056396aeSDouglas Gregor                            llvm::sys::path::stem(Header->getName()),
509056396aeSDouglas Gregor                            NameBuf);
5101fb5c3a6SDouglas Gregor         Found = lookupModuleQualified(Name, Found);
5111fb5c3a6SDouglas Gregor         if (!Found)
5121fb5c3a6SDouglas Gregor           return false;
5131fb5c3a6SDouglas Gregor       }
5141fb5c3a6SDouglas Gregor 
51550996ce1SRichard Smith       return IsUnavailable(Found);
5161fb5c3a6SDouglas Gregor     }
5171fb5c3a6SDouglas Gregor 
5181fb5c3a6SDouglas Gregor     SkippedDirs.push_back(Dir);
5191fb5c3a6SDouglas Gregor 
5201fb5c3a6SDouglas Gregor     // Retrieve our parent path.
5211fb5c3a6SDouglas Gregor     DirName = llvm::sys::path::parent_path(DirName);
5221fb5c3a6SDouglas Gregor     if (DirName.empty())
5231fb5c3a6SDouglas Gregor       break;
5241fb5c3a6SDouglas Gregor 
5251fb5c3a6SDouglas Gregor     // Resolve the parent path to a directory entry.
5261f76c4e8SManuel Klimek     Dir = SourceMgr.getFileManager().getDirectory(DirName);
5271fb5c3a6SDouglas Gregor   } while (Dir);
5281fb5c3a6SDouglas Gregor 
5291fb5c3a6SDouglas Gregor   return false;
5301fb5c3a6SDouglas Gregor }
5311fb5c3a6SDouglas Gregor 
532e4412640SArgyrios Kyrtzidis Module *ModuleMap::findModule(StringRef Name) const {
533e4412640SArgyrios Kyrtzidis   llvm::StringMap<Module *>::const_iterator Known = Modules.find(Name);
53488bdfb0eSDouglas Gregor   if (Known != Modules.end())
53588bdfb0eSDouglas Gregor     return Known->getValue();
53688bdfb0eSDouglas Gregor 
537d2d442caSCraig Topper   return nullptr;
53888bdfb0eSDouglas Gregor }
53988bdfb0eSDouglas Gregor 
540e4412640SArgyrios Kyrtzidis Module *ModuleMap::lookupModuleUnqualified(StringRef Name,
541e4412640SArgyrios Kyrtzidis                                            Module *Context) const {
5422b82c2a5SDouglas Gregor   for(; Context; Context = Context->Parent) {
5432b82c2a5SDouglas Gregor     if (Module *Sub = lookupModuleQualified(Name, Context))
5442b82c2a5SDouglas Gregor       return Sub;
5452b82c2a5SDouglas Gregor   }
5462b82c2a5SDouglas Gregor 
5472b82c2a5SDouglas Gregor   return findModule(Name);
5482b82c2a5SDouglas Gregor }
5492b82c2a5SDouglas Gregor 
550e4412640SArgyrios Kyrtzidis Module *ModuleMap::lookupModuleQualified(StringRef Name, Module *Context) const{
5512b82c2a5SDouglas Gregor   if (!Context)
5522b82c2a5SDouglas Gregor     return findModule(Name);
5532b82c2a5SDouglas Gregor 
554eb90e830SDouglas Gregor   return Context->findSubmodule(Name);
5552b82c2a5SDouglas Gregor }
5562b82c2a5SDouglas Gregor 
557de3ef502SDouglas Gregor std::pair<Module *, bool>
5589d6448b1SBen Langmuir ModuleMap::findOrCreateModule(StringRef Name, Module *Parent, bool IsFramework,
55969021974SDouglas Gregor                               bool IsExplicit) {
56069021974SDouglas Gregor   // Try to find an existing module with this name.
561eb90e830SDouglas Gregor   if (Module *Sub = lookupModuleQualified(Name, Parent))
562eb90e830SDouglas Gregor     return std::make_pair(Sub, false);
56369021974SDouglas Gregor 
56469021974SDouglas Gregor   // Create a new module with this name.
5659d6448b1SBen Langmuir   Module *Result = new Module(Name, SourceLocation(), Parent,
566*a7e2cc68SRichard Smith                               IsFramework, IsExplicit, NumCreatedModules++);
567ba7f2f71SDaniel Jasper   if (LangOpts.CurrentModule == Name) {
568ba7f2f71SDaniel Jasper     SourceModule = Result;
569ba7f2f71SDaniel Jasper     SourceModuleName = Name;
570ba7f2f71SDaniel Jasper   }
5716f722b4eSArgyrios Kyrtzidis   if (!Parent) {
57269021974SDouglas Gregor     Modules[Name] = Result;
5736f722b4eSArgyrios Kyrtzidis     if (!LangOpts.CurrentModule.empty() && !CompilingModule &&
5746f722b4eSArgyrios Kyrtzidis         Name == LangOpts.CurrentModule) {
5756f722b4eSArgyrios Kyrtzidis       CompilingModule = Result;
5766f722b4eSArgyrios Kyrtzidis     }
5776f722b4eSArgyrios Kyrtzidis   }
57869021974SDouglas Gregor   return std::make_pair(Result, true);
57969021974SDouglas Gregor }
58069021974SDouglas Gregor 
58111dfe6feSDouglas Gregor /// \brief For a framework module, infer the framework against which we
58211dfe6feSDouglas Gregor /// should link.
58311dfe6feSDouglas Gregor static void inferFrameworkLink(Module *Mod, const DirectoryEntry *FrameworkDir,
58411dfe6feSDouglas Gregor                                FileManager &FileMgr) {
58511dfe6feSDouglas Gregor   assert(Mod->IsFramework && "Can only infer linking for framework modules");
58611dfe6feSDouglas Gregor   assert(!Mod->isSubFramework() &&
58711dfe6feSDouglas Gregor          "Can only infer linking for top-level frameworks");
58811dfe6feSDouglas Gregor 
58911dfe6feSDouglas Gregor   SmallString<128> LibName;
59011dfe6feSDouglas Gregor   LibName += FrameworkDir->getName();
59111dfe6feSDouglas Gregor   llvm::sys::path::append(LibName, Mod->Name);
59211dfe6feSDouglas Gregor   if (FileMgr.getFile(LibName)) {
59311dfe6feSDouglas Gregor     Mod->LinkLibraries.push_back(Module::LinkLibrary(Mod->Name,
59411dfe6feSDouglas Gregor                                                      /*IsFramework=*/true));
59511dfe6feSDouglas Gregor   }
59611dfe6feSDouglas Gregor }
59711dfe6feSDouglas Gregor 
598de3ef502SDouglas Gregor Module *
59956c64013SDouglas Gregor ModuleMap::inferFrameworkModule(StringRef ModuleName,
600e89dbc1dSDouglas Gregor                                 const DirectoryEntry *FrameworkDir,
601a686e1b0SDouglas Gregor                                 bool IsSystem,
602e89dbc1dSDouglas Gregor                                 Module *Parent) {
603c1d88ea5SBen Langmuir   Attributes Attrs;
604c1d88ea5SBen Langmuir   Attrs.IsSystem = IsSystem;
605c1d88ea5SBen Langmuir   return inferFrameworkModule(ModuleName, FrameworkDir, Attrs, Parent);
606c1d88ea5SBen Langmuir }
607c1d88ea5SBen Langmuir 
608c1d88ea5SBen Langmuir Module *ModuleMap::inferFrameworkModule(StringRef ModuleName,
609c1d88ea5SBen Langmuir                                         const DirectoryEntry *FrameworkDir,
610c1d88ea5SBen Langmuir                                         Attributes Attrs, Module *Parent) {
611c1d88ea5SBen Langmuir 
61256c64013SDouglas Gregor   // Check whether we've already found this module.
613e89dbc1dSDouglas Gregor   if (Module *Mod = lookupModuleQualified(ModuleName, Parent))
614e89dbc1dSDouglas Gregor     return Mod;
615e89dbc1dSDouglas Gregor 
6161f76c4e8SManuel Klimek   FileManager &FileMgr = SourceMgr.getFileManager();
61756c64013SDouglas Gregor 
6189194a91dSDouglas Gregor   // If the framework has a parent path from which we're allowed to infer
6199194a91dSDouglas Gregor   // a framework module, do so.
620beee15e7SBen Langmuir   const FileEntry *ModuleMapFile = nullptr;
6219194a91dSDouglas Gregor   if (!Parent) {
6224ddf2221SDouglas Gregor     // Determine whether we're allowed to infer a module map.
623e00c8b20SDouglas Gregor 
6244ddf2221SDouglas Gregor     // Note: as an egregious but useful hack we use the real path here, because
6254ddf2221SDouglas Gregor     // we might be looking at an embedded framework that symlinks out to a
6264ddf2221SDouglas Gregor     // top-level framework, and we need to infer as if we were naming the
6274ddf2221SDouglas Gregor     // top-level framework.
628e00c8b20SDouglas Gregor     StringRef FrameworkDirName
6291f76c4e8SManuel Klimek       = SourceMgr.getFileManager().getCanonicalName(FrameworkDir);
6304ddf2221SDouglas Gregor 
6316b7f7345SBen Langmuir     // In case this is a case-insensitive filesystem, make sure the canonical
6326b7f7345SBen Langmuir     // directory name matches ModuleName exactly. Modules are case-sensitive.
6336b7f7345SBen Langmuir     // FIXME: we should be able to give a fix-it hint for the correct spelling.
6346b7f7345SBen Langmuir     if (llvm::sys::path::stem(FrameworkDirName) != ModuleName)
6356b7f7345SBen Langmuir       return nullptr;
6366b7f7345SBen Langmuir 
6379194a91dSDouglas Gregor     bool canInfer = false;
6384ddf2221SDouglas Gregor     if (llvm::sys::path::has_parent_path(FrameworkDirName)) {
6399194a91dSDouglas Gregor       // Figure out the parent path.
6404ddf2221SDouglas Gregor       StringRef Parent = llvm::sys::path::parent_path(FrameworkDirName);
6419194a91dSDouglas Gregor       if (const DirectoryEntry *ParentDir = FileMgr.getDirectory(Parent)) {
6429194a91dSDouglas Gregor         // Check whether we have already looked into the parent directory
6439194a91dSDouglas Gregor         // for a module map.
644e4412640SArgyrios Kyrtzidis         llvm::DenseMap<const DirectoryEntry *, InferredDirectory>::const_iterator
6459194a91dSDouglas Gregor           inferred = InferredDirectories.find(ParentDir);
6469194a91dSDouglas Gregor         if (inferred == InferredDirectories.end()) {
6479194a91dSDouglas Gregor           // We haven't looked here before. Load a module map, if there is
6489194a91dSDouglas Gregor           // one.
649984e1df7SBen Langmuir           bool IsFrameworkDir = Parent.endswith(".framework");
650984e1df7SBen Langmuir           if (const FileEntry *ModMapFile =
651984e1df7SBen Langmuir                 HeaderInfo.lookupModuleMapFile(ParentDir, IsFrameworkDir)) {
652c1d88ea5SBen Langmuir             parseModuleMapFile(ModMapFile, Attrs.IsSystem, ParentDir);
6539194a91dSDouglas Gregor             inferred = InferredDirectories.find(ParentDir);
6549194a91dSDouglas Gregor           }
6559194a91dSDouglas Gregor 
6569194a91dSDouglas Gregor           if (inferred == InferredDirectories.end())
6579194a91dSDouglas Gregor             inferred = InferredDirectories.insert(
6589194a91dSDouglas Gregor                          std::make_pair(ParentDir, InferredDirectory())).first;
6599194a91dSDouglas Gregor         }
6609194a91dSDouglas Gregor 
6619194a91dSDouglas Gregor         if (inferred->second.InferModules) {
6629194a91dSDouglas Gregor           // We're allowed to infer for this directory, but make sure it's okay
6639194a91dSDouglas Gregor           // to infer this particular module.
6644ddf2221SDouglas Gregor           StringRef Name = llvm::sys::path::stem(FrameworkDirName);
6659194a91dSDouglas Gregor           canInfer = std::find(inferred->second.ExcludedModules.begin(),
6669194a91dSDouglas Gregor                                inferred->second.ExcludedModules.end(),
6679194a91dSDouglas Gregor                                Name) == inferred->second.ExcludedModules.end();
6689194a91dSDouglas Gregor 
669c1d88ea5SBen Langmuir           Attrs.IsSystem |= inferred->second.Attrs.IsSystem;
670c1d88ea5SBen Langmuir           Attrs.IsExternC |= inferred->second.Attrs.IsExternC;
671c1d88ea5SBen Langmuir           Attrs.IsExhaustive |= inferred->second.Attrs.IsExhaustive;
672beee15e7SBen Langmuir           ModuleMapFile = inferred->second.ModuleMapFile;
6739194a91dSDouglas Gregor         }
6749194a91dSDouglas Gregor       }
6759194a91dSDouglas Gregor     }
6769194a91dSDouglas Gregor 
6779194a91dSDouglas Gregor     // If we're not allowed to infer a framework module, don't.
6789194a91dSDouglas Gregor     if (!canInfer)
679d2d442caSCraig Topper       return nullptr;
680beee15e7SBen Langmuir   } else
6819d6448b1SBen Langmuir     ModuleMapFile = getModuleMapFileForUniquing(Parent);
6829194a91dSDouglas Gregor 
6839194a91dSDouglas Gregor 
68456c64013SDouglas Gregor   // Look for an umbrella header.
6852c1dd271SDylan Noblesmith   SmallString<128> UmbrellaName = StringRef(FrameworkDir->getName());
68617381a06SBenjamin Kramer   llvm::sys::path::append(UmbrellaName, "Headers", ModuleName + ".h");
687e89dbc1dSDouglas Gregor   const FileEntry *UmbrellaHeader = FileMgr.getFile(UmbrellaName);
68856c64013SDouglas Gregor 
68956c64013SDouglas Gregor   // FIXME: If there's no umbrella header, we could probably scan the
69056c64013SDouglas Gregor   // framework to load *everything*. But, it's not clear that this is a good
69156c64013SDouglas Gregor   // idea.
69256c64013SDouglas Gregor   if (!UmbrellaHeader)
693d2d442caSCraig Topper     return nullptr;
69456c64013SDouglas Gregor 
6959d6448b1SBen Langmuir   Module *Result = new Module(ModuleName, SourceLocation(), Parent,
696*a7e2cc68SRichard Smith                               /*IsFramework=*/true, /*IsExplicit=*/false,
697*a7e2cc68SRichard Smith                               NumCreatedModules++);
6989d6448b1SBen Langmuir   InferredModuleAllowedBy[Result] = ModuleMapFile;
6999d6448b1SBen Langmuir   Result->IsInferred = true;
700ba7f2f71SDaniel Jasper   if (LangOpts.CurrentModule == ModuleName) {
701ba7f2f71SDaniel Jasper     SourceModule = Result;
702ba7f2f71SDaniel Jasper     SourceModuleName = ModuleName;
703ba7f2f71SDaniel Jasper   }
704c1d88ea5SBen Langmuir 
705c1d88ea5SBen Langmuir   Result->IsSystem |= Attrs.IsSystem;
706c1d88ea5SBen Langmuir   Result->IsExternC |= Attrs.IsExternC;
707c1d88ea5SBen Langmuir   Result->ConfigMacrosExhaustive |= Attrs.IsExhaustive;
708a686e1b0SDouglas Gregor 
709eb90e830SDouglas Gregor   if (!Parent)
710e89dbc1dSDouglas Gregor     Modules[ModuleName] = Result;
711e89dbc1dSDouglas Gregor 
712322f633cSDouglas Gregor   // umbrella header "umbrella-header-name"
71373141fa9SDouglas Gregor   Result->Umbrella = UmbrellaHeader;
71497da9178SDaniel Jasper   Headers[UmbrellaHeader].push_back(KnownHeader(Result, NormalHeader));
7154dc71835SDouglas Gregor   UmbrellaDirs[UmbrellaHeader->getDir()] = Result;
716d8bd7537SDouglas Gregor 
717d8bd7537SDouglas Gregor   // export *
718d2d442caSCraig Topper   Result->Exports.push_back(Module::ExportDecl(nullptr, true));
719d8bd7537SDouglas Gregor 
720a89c5ac4SDouglas Gregor   // module * { export * }
721a89c5ac4SDouglas Gregor   Result->InferSubmodules = true;
722a89c5ac4SDouglas Gregor   Result->InferExportWildcard = true;
723a89c5ac4SDouglas Gregor 
724e89dbc1dSDouglas Gregor   // Look for subframeworks.
725c080917eSRafael Espindola   std::error_code EC;
7262c1dd271SDylan Noblesmith   SmallString<128> SubframeworksDirName
727ddaa69cbSDouglas Gregor     = StringRef(FrameworkDir->getName());
728e89dbc1dSDouglas Gregor   llvm::sys::path::append(SubframeworksDirName, "Frameworks");
7292d4d8cb3SBenjamin Kramer   llvm::sys::path::native(SubframeworksDirName);
73092e1b62dSYaron Keren   for (llvm::sys::fs::directory_iterator Dir(SubframeworksDirName, EC), DirEnd;
731e89dbc1dSDouglas Gregor        Dir != DirEnd && !EC; Dir.increment(EC)) {
732e89dbc1dSDouglas Gregor     if (!StringRef(Dir->path()).endswith(".framework"))
733e89dbc1dSDouglas Gregor       continue;
734f2161a70SDouglas Gregor 
735e89dbc1dSDouglas Gregor     if (const DirectoryEntry *SubframeworkDir
736e89dbc1dSDouglas Gregor           = FileMgr.getDirectory(Dir->path())) {
73707c22b78SDouglas Gregor       // Note: as an egregious but useful hack, we use the real path here and
73807c22b78SDouglas Gregor       // check whether it is actually a subdirectory of the parent directory.
73907c22b78SDouglas Gregor       // This will not be the case if the 'subframework' is actually a symlink
74007c22b78SDouglas Gregor       // out to a top-level framework.
741e00c8b20SDouglas Gregor       StringRef SubframeworkDirName = FileMgr.getCanonicalName(SubframeworkDir);
74207c22b78SDouglas Gregor       bool FoundParent = false;
74307c22b78SDouglas Gregor       do {
74407c22b78SDouglas Gregor         // Get the parent directory name.
74507c22b78SDouglas Gregor         SubframeworkDirName
74607c22b78SDouglas Gregor           = llvm::sys::path::parent_path(SubframeworkDirName);
74707c22b78SDouglas Gregor         if (SubframeworkDirName.empty())
74807c22b78SDouglas Gregor           break;
74907c22b78SDouglas Gregor 
75007c22b78SDouglas Gregor         if (FileMgr.getDirectory(SubframeworkDirName) == FrameworkDir) {
75107c22b78SDouglas Gregor           FoundParent = true;
75207c22b78SDouglas Gregor           break;
75307c22b78SDouglas Gregor         }
75407c22b78SDouglas Gregor       } while (true);
75507c22b78SDouglas Gregor 
75607c22b78SDouglas Gregor       if (!FoundParent)
75707c22b78SDouglas Gregor         continue;
75807c22b78SDouglas Gregor 
759e89dbc1dSDouglas Gregor       // FIXME: Do we want to warn about subframeworks without umbrella headers?
760056396aeSDouglas Gregor       SmallString<32> NameBuf;
761056396aeSDouglas Gregor       inferFrameworkModule(sanitizeFilenameAsIdentifier(
762056396aeSDouglas Gregor                                llvm::sys::path::stem(Dir->path()), NameBuf),
763c1d88ea5SBen Langmuir                            SubframeworkDir, Attrs, Result);
764e89dbc1dSDouglas Gregor     }
765e89dbc1dSDouglas Gregor   }
766e89dbc1dSDouglas Gregor 
76711dfe6feSDouglas Gregor   // If the module is a top-level framework, automatically link against the
76811dfe6feSDouglas Gregor   // framework.
76911dfe6feSDouglas Gregor   if (!Result->isSubFramework()) {
77011dfe6feSDouglas Gregor     inferFrameworkLink(Result, FrameworkDir, FileMgr);
77111dfe6feSDouglas Gregor   }
77211dfe6feSDouglas Gregor 
77356c64013SDouglas Gregor   return Result;
77456c64013SDouglas Gregor }
77556c64013SDouglas Gregor 
776a89c5ac4SDouglas Gregor void ModuleMap::setUmbrellaHeader(Module *Mod, const FileEntry *UmbrellaHeader){
77797da9178SDaniel Jasper   Headers[UmbrellaHeader].push_back(KnownHeader(Mod, NormalHeader));
77873141fa9SDouglas Gregor   Mod->Umbrella = UmbrellaHeader;
7797033127bSDouglas Gregor   UmbrellaDirs[UmbrellaHeader->getDir()] = Mod;
780a89c5ac4SDouglas Gregor }
781a89c5ac4SDouglas Gregor 
782524e33e1SDouglas Gregor void ModuleMap::setUmbrellaDir(Module *Mod, const DirectoryEntry *UmbrellaDir) {
783524e33e1SDouglas Gregor   Mod->Umbrella = UmbrellaDir;
784524e33e1SDouglas Gregor   UmbrellaDirs[UmbrellaDir] = Mod;
785524e33e1SDouglas Gregor }
786524e33e1SDouglas Gregor 
7873c1a41adSRichard Smith static Module::HeaderKind headerRoleToKind(ModuleMap::ModuleHeaderRole Role) {
7880e98d938SNAKAMURA Takumi   switch ((int)Role) {
7893c1a41adSRichard Smith   default: llvm_unreachable("unknown header role");
7903c1a41adSRichard Smith   case ModuleMap::NormalHeader:
7913c1a41adSRichard Smith     return Module::HK_Normal;
7923c1a41adSRichard Smith   case ModuleMap::PrivateHeader:
7933c1a41adSRichard Smith     return Module::HK_Private;
7943c1a41adSRichard Smith   case ModuleMap::TextualHeader:
7953c1a41adSRichard Smith     return Module::HK_Textual;
7963c1a41adSRichard Smith   case ModuleMap::PrivateHeader | ModuleMap::TextualHeader:
7973c1a41adSRichard Smith     return Module::HK_PrivateTextual;
7983c1a41adSRichard Smith   }
7990e98d938SNAKAMURA Takumi }
800202210b3SRichard Smith 
8013c1a41adSRichard Smith void ModuleMap::addHeader(Module *Mod, Module::Header Header,
8023c1a41adSRichard Smith                           ModuleHeaderRole Role) {
803202210b3SRichard Smith   if (!(Role & TextualHeader)) {
8046f722b4eSArgyrios Kyrtzidis     bool isCompilingModuleHeader = Mod->getTopLevelModule() == CompilingModule;
8053c1a41adSRichard Smith     HeaderInfo.MarkFileModuleHeader(Header.Entry, Role,
8063c1a41adSRichard Smith                                     isCompilingModuleHeader);
807b146baabSArgyrios Kyrtzidis   }
8083c1a41adSRichard Smith   Headers[Header.Entry].push_back(KnownHeader(Mod, Role));
8093c1a41adSRichard Smith 
8103c1a41adSRichard Smith   Mod->Headers[headerRoleToKind(Role)].push_back(std::move(Header));
811a89c5ac4SDouglas Gregor }
812a89c5ac4SDouglas Gregor 
8133c1a41adSRichard Smith void ModuleMap::excludeHeader(Module *Mod, Module::Header Header) {
814feb54b6dSRichard Smith   // Add this as a known header so we won't implicitly add it to any
815feb54b6dSRichard Smith   // umbrella directory module.
816feb54b6dSRichard Smith   // FIXME: Should we only exclude it from umbrella modules within the
817feb54b6dSRichard Smith   // specified module?
8183c1a41adSRichard Smith   (void) Headers[Header.Entry];
8193c1a41adSRichard Smith 
8203c1a41adSRichard Smith   Mod->Headers[Module::HK_Excluded].push_back(std::move(Header));
821feb54b6dSRichard Smith }
822feb54b6dSRichard Smith 
823514b636aSDouglas Gregor const FileEntry *
8244b8a9e95SBen Langmuir ModuleMap::getContainingModuleMapFile(const Module *Module) const {
8251f76c4e8SManuel Klimek   if (Module->DefinitionLoc.isInvalid())
826d2d442caSCraig Topper     return nullptr;
827514b636aSDouglas Gregor 
8281f76c4e8SManuel Klimek   return SourceMgr.getFileEntryForID(
8291f76c4e8SManuel Klimek            SourceMgr.getFileID(Module->DefinitionLoc));
830514b636aSDouglas Gregor }
831514b636aSDouglas Gregor 
8324b8a9e95SBen Langmuir const FileEntry *ModuleMap::getModuleMapFileForUniquing(const Module *M) const {
8339d6448b1SBen Langmuir   if (M->IsInferred) {
8349d6448b1SBen Langmuir     assert(InferredModuleAllowedBy.count(M) && "missing inferred module map");
8359d6448b1SBen Langmuir     return InferredModuleAllowedBy.find(M)->second;
8369d6448b1SBen Langmuir   }
8379d6448b1SBen Langmuir   return getContainingModuleMapFile(M);
8389d6448b1SBen Langmuir }
8399d6448b1SBen Langmuir 
8409d6448b1SBen Langmuir void ModuleMap::setInferredModuleAllowedBy(Module *M, const FileEntry *ModMap) {
8419d6448b1SBen Langmuir   assert(M->IsInferred && "module not inferred");
8429d6448b1SBen Langmuir   InferredModuleAllowedBy[M] = ModMap;
8439d6448b1SBen Langmuir }
8449d6448b1SBen Langmuir 
845718292f2SDouglas Gregor void ModuleMap::dump() {
846718292f2SDouglas Gregor   llvm::errs() << "Modules:";
847718292f2SDouglas Gregor   for (llvm::StringMap<Module *>::iterator M = Modules.begin(),
848718292f2SDouglas Gregor                                         MEnd = Modules.end();
849718292f2SDouglas Gregor        M != MEnd; ++M)
850d28d1b8dSDouglas Gregor     M->getValue()->print(llvm::errs(), 2);
851718292f2SDouglas Gregor 
852718292f2SDouglas Gregor   llvm::errs() << "Headers:";
85359527666SDouglas Gregor   for (HeadersMap::iterator H = Headers.begin(), HEnd = Headers.end();
854718292f2SDouglas Gregor        H != HEnd; ++H) {
85597da9178SDaniel Jasper     llvm::errs() << "  \"" << H->first->getName() << "\" -> ";
85697da9178SDaniel Jasper     for (SmallVectorImpl<KnownHeader>::const_iterator I = H->second.begin(),
85797da9178SDaniel Jasper                                                       E = H->second.end();
85897da9178SDaniel Jasper          I != E; ++I) {
85997da9178SDaniel Jasper       if (I != H->second.begin())
86097da9178SDaniel Jasper         llvm::errs() << ",";
86197da9178SDaniel Jasper       llvm::errs() << I->getModule()->getFullModuleName();
86297da9178SDaniel Jasper     }
86397da9178SDaniel Jasper     llvm::errs() << "\n";
864718292f2SDouglas Gregor   }
865718292f2SDouglas Gregor }
866718292f2SDouglas Gregor 
8672b82c2a5SDouglas Gregor bool ModuleMap::resolveExports(Module *Mod, bool Complain) {
8682b82c2a5SDouglas Gregor   bool HadError = false;
8692b82c2a5SDouglas Gregor   for (unsigned I = 0, N = Mod->UnresolvedExports.size(); I != N; ++I) {
8702b82c2a5SDouglas Gregor     Module::ExportDecl Export = resolveExport(Mod, Mod->UnresolvedExports[I],
8712b82c2a5SDouglas Gregor                                               Complain);
872f5eedd05SDouglas Gregor     if (Export.getPointer() || Export.getInt())
8732b82c2a5SDouglas Gregor       Mod->Exports.push_back(Export);
8742b82c2a5SDouglas Gregor     else
8752b82c2a5SDouglas Gregor       HadError = true;
8762b82c2a5SDouglas Gregor   }
8772b82c2a5SDouglas Gregor   Mod->UnresolvedExports.clear();
8782b82c2a5SDouglas Gregor   return HadError;
8792b82c2a5SDouglas Gregor }
8802b82c2a5SDouglas Gregor 
881ba7f2f71SDaniel Jasper bool ModuleMap::resolveUses(Module *Mod, bool Complain) {
882ba7f2f71SDaniel Jasper   bool HadError = false;
883ba7f2f71SDaniel Jasper   for (unsigned I = 0, N = Mod->UnresolvedDirectUses.size(); I != N; ++I) {
884ba7f2f71SDaniel Jasper     Module *DirectUse =
885ba7f2f71SDaniel Jasper         resolveModuleId(Mod->UnresolvedDirectUses[I], Mod, Complain);
886ba7f2f71SDaniel Jasper     if (DirectUse)
887ba7f2f71SDaniel Jasper       Mod->DirectUses.push_back(DirectUse);
888ba7f2f71SDaniel Jasper     else
889ba7f2f71SDaniel Jasper       HadError = true;
890ba7f2f71SDaniel Jasper   }
891ba7f2f71SDaniel Jasper   Mod->UnresolvedDirectUses.clear();
892ba7f2f71SDaniel Jasper   return HadError;
893ba7f2f71SDaniel Jasper }
894ba7f2f71SDaniel Jasper 
895fb912657SDouglas Gregor bool ModuleMap::resolveConflicts(Module *Mod, bool Complain) {
896fb912657SDouglas Gregor   bool HadError = false;
897fb912657SDouglas Gregor   for (unsigned I = 0, N = Mod->UnresolvedConflicts.size(); I != N; ++I) {
898fb912657SDouglas Gregor     Module *OtherMod = resolveModuleId(Mod->UnresolvedConflicts[I].Id,
899fb912657SDouglas Gregor                                        Mod, Complain);
900fb912657SDouglas Gregor     if (!OtherMod) {
901fb912657SDouglas Gregor       HadError = true;
902fb912657SDouglas Gregor       continue;
903fb912657SDouglas Gregor     }
904fb912657SDouglas Gregor 
905fb912657SDouglas Gregor     Module::Conflict Conflict;
906fb912657SDouglas Gregor     Conflict.Other = OtherMod;
907fb912657SDouglas Gregor     Conflict.Message = Mod->UnresolvedConflicts[I].Message;
908fb912657SDouglas Gregor     Mod->Conflicts.push_back(Conflict);
909fb912657SDouglas Gregor   }
910fb912657SDouglas Gregor   Mod->UnresolvedConflicts.clear();
911fb912657SDouglas Gregor   return HadError;
912fb912657SDouglas Gregor }
913fb912657SDouglas Gregor 
9140093b3c7SDouglas Gregor Module *ModuleMap::inferModuleFromLocation(FullSourceLoc Loc) {
9150093b3c7SDouglas Gregor   if (Loc.isInvalid())
916d2d442caSCraig Topper     return nullptr;
9170093b3c7SDouglas Gregor 
9180093b3c7SDouglas Gregor   // Use the expansion location to determine which module we're in.
9190093b3c7SDouglas Gregor   FullSourceLoc ExpansionLoc = Loc.getExpansionLoc();
9200093b3c7SDouglas Gregor   if (!ExpansionLoc.isFileID())
921d2d442caSCraig Topper     return nullptr;
9220093b3c7SDouglas Gregor 
9230093b3c7SDouglas Gregor   const SourceManager &SrcMgr = Loc.getManager();
9240093b3c7SDouglas Gregor   FileID ExpansionFileID = ExpansionLoc.getFileID();
925224d8a74SDouglas Gregor 
926224d8a74SDouglas Gregor   while (const FileEntry *ExpansionFile
927224d8a74SDouglas Gregor            = SrcMgr.getFileEntryForID(ExpansionFileID)) {
928224d8a74SDouglas Gregor     // Find the module that owns this header (if any).
929b53e5483SLawrence Crowl     if (Module *Mod = findModuleForHeader(ExpansionFile).getModule())
930224d8a74SDouglas Gregor       return Mod;
931224d8a74SDouglas Gregor 
932224d8a74SDouglas Gregor     // No module owns this header, so look up the inclusion chain to see if
933224d8a74SDouglas Gregor     // any included header has an associated module.
934224d8a74SDouglas Gregor     SourceLocation IncludeLoc = SrcMgr.getIncludeLoc(ExpansionFileID);
935224d8a74SDouglas Gregor     if (IncludeLoc.isInvalid())
936d2d442caSCraig Topper       return nullptr;
9370093b3c7SDouglas Gregor 
938224d8a74SDouglas Gregor     ExpansionFileID = SrcMgr.getFileID(IncludeLoc);
939224d8a74SDouglas Gregor   }
940224d8a74SDouglas Gregor 
941d2d442caSCraig Topper   return nullptr;
9420093b3c7SDouglas Gregor }
9430093b3c7SDouglas Gregor 
944718292f2SDouglas Gregor //----------------------------------------------------------------------------//
945718292f2SDouglas Gregor // Module map file parser
946718292f2SDouglas Gregor //----------------------------------------------------------------------------//
947718292f2SDouglas Gregor 
948718292f2SDouglas Gregor namespace clang {
949718292f2SDouglas Gregor   /// \brief A token in a module map file.
950718292f2SDouglas Gregor   struct MMToken {
951718292f2SDouglas Gregor     enum TokenKind {
9521fb5c3a6SDouglas Gregor       Comma,
95335b13eceSDouglas Gregor       ConfigMacros,
954fb912657SDouglas Gregor       Conflict,
955718292f2SDouglas Gregor       EndOfFile,
956718292f2SDouglas Gregor       HeaderKeyword,
957718292f2SDouglas Gregor       Identifier,
958a3feee2aSRichard Smith       Exclaim,
95959527666SDouglas Gregor       ExcludeKeyword,
960718292f2SDouglas Gregor       ExplicitKeyword,
9612b82c2a5SDouglas Gregor       ExportKeyword,
96297292843SDaniel Jasper       ExternKeyword,
963755b2055SDouglas Gregor       FrameworkKeyword,
9646ddfca91SDouglas Gregor       LinkKeyword,
965718292f2SDouglas Gregor       ModuleKeyword,
9662b82c2a5SDouglas Gregor       Period,
967b53e5483SLawrence Crowl       PrivateKeyword,
968718292f2SDouglas Gregor       UmbrellaKeyword,
969ba7f2f71SDaniel Jasper       UseKeyword,
9701fb5c3a6SDouglas Gregor       RequiresKeyword,
9712b82c2a5SDouglas Gregor       Star,
972718292f2SDouglas Gregor       StringLiteral,
973306d8920SRichard Smith       TextualKeyword,
974718292f2SDouglas Gregor       LBrace,
975a686e1b0SDouglas Gregor       RBrace,
976a686e1b0SDouglas Gregor       LSquare,
977a686e1b0SDouglas Gregor       RSquare
978718292f2SDouglas Gregor     } Kind;
979718292f2SDouglas Gregor 
980718292f2SDouglas Gregor     unsigned Location;
981718292f2SDouglas Gregor     unsigned StringLength;
982718292f2SDouglas Gregor     const char *StringData;
983718292f2SDouglas Gregor 
984718292f2SDouglas Gregor     void clear() {
985718292f2SDouglas Gregor       Kind = EndOfFile;
986718292f2SDouglas Gregor       Location = 0;
987718292f2SDouglas Gregor       StringLength = 0;
988d2d442caSCraig Topper       StringData = nullptr;
989718292f2SDouglas Gregor     }
990718292f2SDouglas Gregor 
991718292f2SDouglas Gregor     bool is(TokenKind K) const { return Kind == K; }
992718292f2SDouglas Gregor 
993718292f2SDouglas Gregor     SourceLocation getLocation() const {
994718292f2SDouglas Gregor       return SourceLocation::getFromRawEncoding(Location);
995718292f2SDouglas Gregor     }
996718292f2SDouglas Gregor 
997718292f2SDouglas Gregor     StringRef getString() const {
998718292f2SDouglas Gregor       return StringRef(StringData, StringLength);
999718292f2SDouglas Gregor     }
1000718292f2SDouglas Gregor   };
1001718292f2SDouglas Gregor 
1002718292f2SDouglas Gregor   class ModuleMapParser {
1003718292f2SDouglas Gregor     Lexer &L;
1004718292f2SDouglas Gregor     SourceManager &SourceMgr;
1005bc10b9fbSDouglas Gregor 
1006bc10b9fbSDouglas Gregor     /// \brief Default target information, used only for string literal
1007bc10b9fbSDouglas Gregor     /// parsing.
1008bc10b9fbSDouglas Gregor     const TargetInfo *Target;
1009bc10b9fbSDouglas Gregor 
1010718292f2SDouglas Gregor     DiagnosticsEngine &Diags;
1011718292f2SDouglas Gregor     ModuleMap &Map;
1012718292f2SDouglas Gregor 
1013beee15e7SBen Langmuir     /// \brief The current module map file.
1014beee15e7SBen Langmuir     const FileEntry *ModuleMapFile;
1015beee15e7SBen Langmuir 
10169acb99e3SRichard Smith     /// \brief The directory that file names in this module map file should
10179acb99e3SRichard Smith     /// be resolved relative to.
10185257fc63SDouglas Gregor     const DirectoryEntry *Directory;
10195257fc63SDouglas Gregor 
10203ec6663bSDouglas Gregor     /// \brief The directory containing Clang-supplied headers.
10213ec6663bSDouglas Gregor     const DirectoryEntry *BuiltinIncludeDir;
10223ec6663bSDouglas Gregor 
1023963c5535SDouglas Gregor     /// \brief Whether this module map is in a system header directory.
1024963c5535SDouglas Gregor     bool IsSystem;
1025963c5535SDouglas Gregor 
1026718292f2SDouglas Gregor     /// \brief Whether an error occurred.
1027718292f2SDouglas Gregor     bool HadError;
1028718292f2SDouglas Gregor 
1029718292f2SDouglas Gregor     /// \brief Stores string data for the various string literals referenced
1030718292f2SDouglas Gregor     /// during parsing.
1031718292f2SDouglas Gregor     llvm::BumpPtrAllocator StringData;
1032718292f2SDouglas Gregor 
1033718292f2SDouglas Gregor     /// \brief The current token.
1034718292f2SDouglas Gregor     MMToken Tok;
1035718292f2SDouglas Gregor 
1036718292f2SDouglas Gregor     /// \brief The active module.
1037de3ef502SDouglas Gregor     Module *ActiveModule;
1038718292f2SDouglas Gregor 
1039718292f2SDouglas Gregor     /// \brief Consume the current token and return its location.
1040718292f2SDouglas Gregor     SourceLocation consumeToken();
1041718292f2SDouglas Gregor 
1042718292f2SDouglas Gregor     /// \brief Skip tokens until we reach the a token with the given kind
1043718292f2SDouglas Gregor     /// (or the end of the file).
1044718292f2SDouglas Gregor     void skipUntil(MMToken::TokenKind K);
1045718292f2SDouglas Gregor 
1046f857950dSDmitri Gribenko     typedef SmallVector<std::pair<std::string, SourceLocation>, 2> ModuleId;
1047e7ab3669SDouglas Gregor     bool parseModuleId(ModuleId &Id);
1048718292f2SDouglas Gregor     void parseModuleDecl();
104997292843SDaniel Jasper     void parseExternModuleDecl();
10501fb5c3a6SDouglas Gregor     void parseRequiresDecl();
1051b53e5483SLawrence Crowl     void parseHeaderDecl(clang::MMToken::TokenKind,
1052b53e5483SLawrence Crowl                          SourceLocation LeadingLoc);
1053524e33e1SDouglas Gregor     void parseUmbrellaDirDecl(SourceLocation UmbrellaLoc);
10542b82c2a5SDouglas Gregor     void parseExportDecl();
1055ba7f2f71SDaniel Jasper     void parseUseDecl();
10566ddfca91SDouglas Gregor     void parseLinkDecl();
105735b13eceSDouglas Gregor     void parseConfigMacros();
1058fb912657SDouglas Gregor     void parseConflict();
10599194a91dSDouglas Gregor     void parseInferredModuleDecl(bool Framework, bool Explicit);
1060c1d88ea5SBen Langmuir 
1061c1d88ea5SBen Langmuir     typedef ModuleMap::Attributes Attributes;
10624442605fSBill Wendling     bool parseOptionalAttributes(Attributes &Attrs);
1063718292f2SDouglas Gregor 
1064718292f2SDouglas Gregor   public:
1065718292f2SDouglas Gregor     explicit ModuleMapParser(Lexer &L, SourceManager &SourceMgr,
1066bc10b9fbSDouglas Gregor                              const TargetInfo *Target,
1067718292f2SDouglas Gregor                              DiagnosticsEngine &Diags,
10685257fc63SDouglas Gregor                              ModuleMap &Map,
1069beee15e7SBen Langmuir                              const FileEntry *ModuleMapFile,
10703ec6663bSDouglas Gregor                              const DirectoryEntry *Directory,
1071963c5535SDouglas Gregor                              const DirectoryEntry *BuiltinIncludeDir,
1072963c5535SDouglas Gregor                              bool IsSystem)
1073bc10b9fbSDouglas Gregor       : L(L), SourceMgr(SourceMgr), Target(Target), Diags(Diags), Map(Map),
1074beee15e7SBen Langmuir         ModuleMapFile(ModuleMapFile), Directory(Directory),
1075beee15e7SBen Langmuir         BuiltinIncludeDir(BuiltinIncludeDir), IsSystem(IsSystem),
1076d2d442caSCraig Topper         HadError(false), ActiveModule(nullptr)
1077718292f2SDouglas Gregor     {
1078718292f2SDouglas Gregor       Tok.clear();
1079718292f2SDouglas Gregor       consumeToken();
1080718292f2SDouglas Gregor     }
1081718292f2SDouglas Gregor 
1082718292f2SDouglas Gregor     bool parseModuleMapFile();
1083718292f2SDouglas Gregor   };
1084718292f2SDouglas Gregor }
1085718292f2SDouglas Gregor 
1086718292f2SDouglas Gregor SourceLocation ModuleMapParser::consumeToken() {
1087718292f2SDouglas Gregor retry:
1088718292f2SDouglas Gregor   SourceLocation Result = Tok.getLocation();
1089718292f2SDouglas Gregor   Tok.clear();
1090718292f2SDouglas Gregor 
1091718292f2SDouglas Gregor   Token LToken;
1092718292f2SDouglas Gregor   L.LexFromRawLexer(LToken);
1093718292f2SDouglas Gregor   Tok.Location = LToken.getLocation().getRawEncoding();
1094718292f2SDouglas Gregor   switch (LToken.getKind()) {
10952d57cea2SAlp Toker   case tok::raw_identifier: {
10962d57cea2SAlp Toker     StringRef RI = LToken.getRawIdentifier();
10972d57cea2SAlp Toker     Tok.StringData = RI.data();
10982d57cea2SAlp Toker     Tok.StringLength = RI.size();
10992d57cea2SAlp Toker     Tok.Kind = llvm::StringSwitch<MMToken::TokenKind>(RI)
110035b13eceSDouglas Gregor                  .Case("config_macros", MMToken::ConfigMacros)
1101fb912657SDouglas Gregor                  .Case("conflict", MMToken::Conflict)
110259527666SDouglas Gregor                  .Case("exclude", MMToken::ExcludeKeyword)
1103718292f2SDouglas Gregor                  .Case("explicit", MMToken::ExplicitKeyword)
11042b82c2a5SDouglas Gregor                  .Case("export", MMToken::ExportKeyword)
110597292843SDaniel Jasper                  .Case("extern", MMToken::ExternKeyword)
1106755b2055SDouglas Gregor                  .Case("framework", MMToken::FrameworkKeyword)
110735b13eceSDouglas Gregor                  .Case("header", MMToken::HeaderKeyword)
11086ddfca91SDouglas Gregor                  .Case("link", MMToken::LinkKeyword)
1109718292f2SDouglas Gregor                  .Case("module", MMToken::ModuleKeyword)
1110b53e5483SLawrence Crowl                  .Case("private", MMToken::PrivateKeyword)
11111fb5c3a6SDouglas Gregor                  .Case("requires", MMToken::RequiresKeyword)
1112306d8920SRichard Smith                  .Case("textual", MMToken::TextualKeyword)
1113718292f2SDouglas Gregor                  .Case("umbrella", MMToken::UmbrellaKeyword)
1114ba7f2f71SDaniel Jasper                  .Case("use", MMToken::UseKeyword)
1115718292f2SDouglas Gregor                  .Default(MMToken::Identifier);
1116718292f2SDouglas Gregor     break;
11172d57cea2SAlp Toker   }
1118718292f2SDouglas Gregor 
11191fb5c3a6SDouglas Gregor   case tok::comma:
11201fb5c3a6SDouglas Gregor     Tok.Kind = MMToken::Comma;
11211fb5c3a6SDouglas Gregor     break;
11221fb5c3a6SDouglas Gregor 
1123718292f2SDouglas Gregor   case tok::eof:
1124718292f2SDouglas Gregor     Tok.Kind = MMToken::EndOfFile;
1125718292f2SDouglas Gregor     break;
1126718292f2SDouglas Gregor 
1127718292f2SDouglas Gregor   case tok::l_brace:
1128718292f2SDouglas Gregor     Tok.Kind = MMToken::LBrace;
1129718292f2SDouglas Gregor     break;
1130718292f2SDouglas Gregor 
1131a686e1b0SDouglas Gregor   case tok::l_square:
1132a686e1b0SDouglas Gregor     Tok.Kind = MMToken::LSquare;
1133a686e1b0SDouglas Gregor     break;
1134a686e1b0SDouglas Gregor 
11352b82c2a5SDouglas Gregor   case tok::period:
11362b82c2a5SDouglas Gregor     Tok.Kind = MMToken::Period;
11372b82c2a5SDouglas Gregor     break;
11382b82c2a5SDouglas Gregor 
1139718292f2SDouglas Gregor   case tok::r_brace:
1140718292f2SDouglas Gregor     Tok.Kind = MMToken::RBrace;
1141718292f2SDouglas Gregor     break;
1142718292f2SDouglas Gregor 
1143a686e1b0SDouglas Gregor   case tok::r_square:
1144a686e1b0SDouglas Gregor     Tok.Kind = MMToken::RSquare;
1145a686e1b0SDouglas Gregor     break;
1146a686e1b0SDouglas Gregor 
11472b82c2a5SDouglas Gregor   case tok::star:
11482b82c2a5SDouglas Gregor     Tok.Kind = MMToken::Star;
11492b82c2a5SDouglas Gregor     break;
11502b82c2a5SDouglas Gregor 
1151a3feee2aSRichard Smith   case tok::exclaim:
1152a3feee2aSRichard Smith     Tok.Kind = MMToken::Exclaim;
1153a3feee2aSRichard Smith     break;
1154a3feee2aSRichard Smith 
1155718292f2SDouglas Gregor   case tok::string_literal: {
1156d67aea28SRichard Smith     if (LToken.hasUDSuffix()) {
1157d67aea28SRichard Smith       Diags.Report(LToken.getLocation(), diag::err_invalid_string_udl);
1158d67aea28SRichard Smith       HadError = true;
1159d67aea28SRichard Smith       goto retry;
1160d67aea28SRichard Smith     }
1161d67aea28SRichard Smith 
1162718292f2SDouglas Gregor     // Parse the string literal.
1163718292f2SDouglas Gregor     LangOptions LangOpts;
11649d5583efSCraig Topper     StringLiteralParser StringLiteral(LToken, SourceMgr, LangOpts, *Target);
1165718292f2SDouglas Gregor     if (StringLiteral.hadError)
1166718292f2SDouglas Gregor       goto retry;
1167718292f2SDouglas Gregor 
1168718292f2SDouglas Gregor     // Copy the string literal into our string data allocator.
1169718292f2SDouglas Gregor     unsigned Length = StringLiteral.GetStringLength();
1170718292f2SDouglas Gregor     char *Saved = StringData.Allocate<char>(Length + 1);
1171718292f2SDouglas Gregor     memcpy(Saved, StringLiteral.GetString().data(), Length);
1172718292f2SDouglas Gregor     Saved[Length] = 0;
1173718292f2SDouglas Gregor 
1174718292f2SDouglas Gregor     // Form the token.
1175718292f2SDouglas Gregor     Tok.Kind = MMToken::StringLiteral;
1176718292f2SDouglas Gregor     Tok.StringData = Saved;
1177718292f2SDouglas Gregor     Tok.StringLength = Length;
1178718292f2SDouglas Gregor     break;
1179718292f2SDouglas Gregor   }
1180718292f2SDouglas Gregor 
1181718292f2SDouglas Gregor   case tok::comment:
1182718292f2SDouglas Gregor     goto retry;
1183718292f2SDouglas Gregor 
1184718292f2SDouglas Gregor   default:
1185718292f2SDouglas Gregor     Diags.Report(LToken.getLocation(), diag::err_mmap_unknown_token);
1186718292f2SDouglas Gregor     HadError = true;
1187718292f2SDouglas Gregor     goto retry;
1188718292f2SDouglas Gregor   }
1189718292f2SDouglas Gregor 
1190718292f2SDouglas Gregor   return Result;
1191718292f2SDouglas Gregor }
1192718292f2SDouglas Gregor 
1193718292f2SDouglas Gregor void ModuleMapParser::skipUntil(MMToken::TokenKind K) {
1194718292f2SDouglas Gregor   unsigned braceDepth = 0;
1195a686e1b0SDouglas Gregor   unsigned squareDepth = 0;
1196718292f2SDouglas Gregor   do {
1197718292f2SDouglas Gregor     switch (Tok.Kind) {
1198718292f2SDouglas Gregor     case MMToken::EndOfFile:
1199718292f2SDouglas Gregor       return;
1200718292f2SDouglas Gregor 
1201718292f2SDouglas Gregor     case MMToken::LBrace:
1202a686e1b0SDouglas Gregor       if (Tok.is(K) && braceDepth == 0 && squareDepth == 0)
1203718292f2SDouglas Gregor         return;
1204718292f2SDouglas Gregor 
1205718292f2SDouglas Gregor       ++braceDepth;
1206718292f2SDouglas Gregor       break;
1207718292f2SDouglas Gregor 
1208a686e1b0SDouglas Gregor     case MMToken::LSquare:
1209a686e1b0SDouglas Gregor       if (Tok.is(K) && braceDepth == 0 && squareDepth == 0)
1210a686e1b0SDouglas Gregor         return;
1211a686e1b0SDouglas Gregor 
1212a686e1b0SDouglas Gregor       ++squareDepth;
1213a686e1b0SDouglas Gregor       break;
1214a686e1b0SDouglas Gregor 
1215718292f2SDouglas Gregor     case MMToken::RBrace:
1216718292f2SDouglas Gregor       if (braceDepth > 0)
1217718292f2SDouglas Gregor         --braceDepth;
1218718292f2SDouglas Gregor       else if (Tok.is(K))
1219718292f2SDouglas Gregor         return;
1220718292f2SDouglas Gregor       break;
1221718292f2SDouglas Gregor 
1222a686e1b0SDouglas Gregor     case MMToken::RSquare:
1223a686e1b0SDouglas Gregor       if (squareDepth > 0)
1224a686e1b0SDouglas Gregor         --squareDepth;
1225a686e1b0SDouglas Gregor       else if (Tok.is(K))
1226a686e1b0SDouglas Gregor         return;
1227a686e1b0SDouglas Gregor       break;
1228a686e1b0SDouglas Gregor 
1229718292f2SDouglas Gregor     default:
1230a686e1b0SDouglas Gregor       if (braceDepth == 0 && squareDepth == 0 && Tok.is(K))
1231718292f2SDouglas Gregor         return;
1232718292f2SDouglas Gregor       break;
1233718292f2SDouglas Gregor     }
1234718292f2SDouglas Gregor 
1235718292f2SDouglas Gregor    consumeToken();
1236718292f2SDouglas Gregor   } while (true);
1237718292f2SDouglas Gregor }
1238718292f2SDouglas Gregor 
1239e7ab3669SDouglas Gregor /// \brief Parse a module-id.
1240e7ab3669SDouglas Gregor ///
1241e7ab3669SDouglas Gregor ///   module-id:
1242e7ab3669SDouglas Gregor ///     identifier
1243e7ab3669SDouglas Gregor ///     identifier '.' module-id
1244e7ab3669SDouglas Gregor ///
1245e7ab3669SDouglas Gregor /// \returns true if an error occurred, false otherwise.
1246e7ab3669SDouglas Gregor bool ModuleMapParser::parseModuleId(ModuleId &Id) {
1247e7ab3669SDouglas Gregor   Id.clear();
1248e7ab3669SDouglas Gregor   do {
12493cd34c76SDaniel Jasper     if (Tok.is(MMToken::Identifier) || Tok.is(MMToken::StringLiteral)) {
1250e7ab3669SDouglas Gregor       Id.push_back(std::make_pair(Tok.getString(), Tok.getLocation()));
1251e7ab3669SDouglas Gregor       consumeToken();
1252e7ab3669SDouglas Gregor     } else {
1253e7ab3669SDouglas Gregor       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module_name);
1254e7ab3669SDouglas Gregor       return true;
1255e7ab3669SDouglas Gregor     }
1256e7ab3669SDouglas Gregor 
1257e7ab3669SDouglas Gregor     if (!Tok.is(MMToken::Period))
1258e7ab3669SDouglas Gregor       break;
1259e7ab3669SDouglas Gregor 
1260e7ab3669SDouglas Gregor     consumeToken();
1261e7ab3669SDouglas Gregor   } while (true);
1262e7ab3669SDouglas Gregor 
1263e7ab3669SDouglas Gregor   return false;
1264e7ab3669SDouglas Gregor }
1265e7ab3669SDouglas Gregor 
1266a686e1b0SDouglas Gregor namespace {
1267a686e1b0SDouglas Gregor   /// \brief Enumerates the known attributes.
1268a686e1b0SDouglas Gregor   enum AttributeKind {
1269a686e1b0SDouglas Gregor     /// \brief An unknown attribute.
1270a686e1b0SDouglas Gregor     AT_unknown,
1271a686e1b0SDouglas Gregor     /// \brief The 'system' attribute.
127235b13eceSDouglas Gregor     AT_system,
127377944868SRichard Smith     /// \brief The 'extern_c' attribute.
127477944868SRichard Smith     AT_extern_c,
127535b13eceSDouglas Gregor     /// \brief The 'exhaustive' attribute.
127635b13eceSDouglas Gregor     AT_exhaustive
1277a686e1b0SDouglas Gregor   };
1278a686e1b0SDouglas Gregor }
1279a686e1b0SDouglas Gregor 
1280718292f2SDouglas Gregor /// \brief Parse a module declaration.
1281718292f2SDouglas Gregor ///
1282718292f2SDouglas Gregor ///   module-declaration:
128397292843SDaniel Jasper ///     'extern' 'module' module-id string-literal
1284a686e1b0SDouglas Gregor ///     'explicit'[opt] 'framework'[opt] 'module' module-id attributes[opt]
1285a686e1b0SDouglas Gregor ///       { module-member* }
1286a686e1b0SDouglas Gregor ///
1287718292f2SDouglas Gregor ///   module-member:
12881fb5c3a6SDouglas Gregor ///     requires-declaration
1289718292f2SDouglas Gregor ///     header-declaration
1290e7ab3669SDouglas Gregor ///     submodule-declaration
12912b82c2a5SDouglas Gregor ///     export-declaration
12926ddfca91SDouglas Gregor ///     link-declaration
129373441091SDouglas Gregor ///
129473441091SDouglas Gregor ///   submodule-declaration:
129573441091SDouglas Gregor ///     module-declaration
129673441091SDouglas Gregor ///     inferred-submodule-declaration
1297718292f2SDouglas Gregor void ModuleMapParser::parseModuleDecl() {
1298755b2055SDouglas Gregor   assert(Tok.is(MMToken::ExplicitKeyword) || Tok.is(MMToken::ModuleKeyword) ||
129997292843SDaniel Jasper          Tok.is(MMToken::FrameworkKeyword) || Tok.is(MMToken::ExternKeyword));
130097292843SDaniel Jasper   if (Tok.is(MMToken::ExternKeyword)) {
130197292843SDaniel Jasper     parseExternModuleDecl();
130297292843SDaniel Jasper     return;
130397292843SDaniel Jasper   }
130497292843SDaniel Jasper 
1305f2161a70SDouglas Gregor   // Parse 'explicit' or 'framework' keyword, if present.
1306e7ab3669SDouglas Gregor   SourceLocation ExplicitLoc;
1307718292f2SDouglas Gregor   bool Explicit = false;
1308f2161a70SDouglas Gregor   bool Framework = false;
1309755b2055SDouglas Gregor 
1310f2161a70SDouglas Gregor   // Parse 'explicit' keyword, if present.
1311f2161a70SDouglas Gregor   if (Tok.is(MMToken::ExplicitKeyword)) {
1312e7ab3669SDouglas Gregor     ExplicitLoc = consumeToken();
1313f2161a70SDouglas Gregor     Explicit = true;
1314f2161a70SDouglas Gregor   }
1315f2161a70SDouglas Gregor 
1316f2161a70SDouglas Gregor   // Parse 'framework' keyword, if present.
1317755b2055SDouglas Gregor   if (Tok.is(MMToken::FrameworkKeyword)) {
1318755b2055SDouglas Gregor     consumeToken();
1319755b2055SDouglas Gregor     Framework = true;
1320755b2055SDouglas Gregor   }
1321718292f2SDouglas Gregor 
1322718292f2SDouglas Gregor   // Parse 'module' keyword.
1323718292f2SDouglas Gregor   if (!Tok.is(MMToken::ModuleKeyword)) {
1324d6343c99SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module);
1325718292f2SDouglas Gregor     consumeToken();
1326718292f2SDouglas Gregor     HadError = true;
1327718292f2SDouglas Gregor     return;
1328718292f2SDouglas Gregor   }
1329718292f2SDouglas Gregor   consumeToken(); // 'module' keyword
1330718292f2SDouglas Gregor 
133173441091SDouglas Gregor   // If we have a wildcard for the module name, this is an inferred submodule.
133273441091SDouglas Gregor   // Parse it.
133373441091SDouglas Gregor   if (Tok.is(MMToken::Star))
13349194a91dSDouglas Gregor     return parseInferredModuleDecl(Framework, Explicit);
133573441091SDouglas Gregor 
1336718292f2SDouglas Gregor   // Parse the module name.
1337e7ab3669SDouglas Gregor   ModuleId Id;
1338e7ab3669SDouglas Gregor   if (parseModuleId(Id)) {
1339718292f2SDouglas Gregor     HadError = true;
1340718292f2SDouglas Gregor     return;
1341718292f2SDouglas Gregor   }
1342e7ab3669SDouglas Gregor 
1343e7ab3669SDouglas Gregor   if (ActiveModule) {
1344e7ab3669SDouglas Gregor     if (Id.size() > 1) {
1345e7ab3669SDouglas Gregor       Diags.Report(Id.front().second, diag::err_mmap_nested_submodule_id)
1346e7ab3669SDouglas Gregor         << SourceRange(Id.front().second, Id.back().second);
1347e7ab3669SDouglas Gregor 
1348e7ab3669SDouglas Gregor       HadError = true;
1349e7ab3669SDouglas Gregor       return;
1350e7ab3669SDouglas Gregor     }
1351e7ab3669SDouglas Gregor   } else if (Id.size() == 1 && Explicit) {
1352e7ab3669SDouglas Gregor     // Top-level modules can't be explicit.
1353e7ab3669SDouglas Gregor     Diags.Report(ExplicitLoc, diag::err_mmap_explicit_top_level);
1354e7ab3669SDouglas Gregor     Explicit = false;
1355e7ab3669SDouglas Gregor     ExplicitLoc = SourceLocation();
1356e7ab3669SDouglas Gregor     HadError = true;
1357e7ab3669SDouglas Gregor   }
1358e7ab3669SDouglas Gregor 
1359e7ab3669SDouglas Gregor   Module *PreviousActiveModule = ActiveModule;
1360e7ab3669SDouglas Gregor   if (Id.size() > 1) {
1361e7ab3669SDouglas Gregor     // This module map defines a submodule. Go find the module of which it
1362e7ab3669SDouglas Gregor     // is a submodule.
1363d2d442caSCraig Topper     ActiveModule = nullptr;
13644b8a9e95SBen Langmuir     const Module *TopLevelModule = nullptr;
1365e7ab3669SDouglas Gregor     for (unsigned I = 0, N = Id.size() - 1; I != N; ++I) {
1366e7ab3669SDouglas Gregor       if (Module *Next = Map.lookupModuleQualified(Id[I].first, ActiveModule)) {
13674b8a9e95SBen Langmuir         if (I == 0)
13684b8a9e95SBen Langmuir           TopLevelModule = Next;
1369e7ab3669SDouglas Gregor         ActiveModule = Next;
1370e7ab3669SDouglas Gregor         continue;
1371e7ab3669SDouglas Gregor       }
1372e7ab3669SDouglas Gregor 
1373e7ab3669SDouglas Gregor       if (ActiveModule) {
1374e7ab3669SDouglas Gregor         Diags.Report(Id[I].second, diag::err_mmap_missing_module_qualified)
13755b5d21eaSRichard Smith           << Id[I].first
13765b5d21eaSRichard Smith           << ActiveModule->getTopLevelModule()->getFullModuleName();
1377e7ab3669SDouglas Gregor       } else {
1378e7ab3669SDouglas Gregor         Diags.Report(Id[I].second, diag::err_mmap_expected_module_name);
1379e7ab3669SDouglas Gregor       }
1380e7ab3669SDouglas Gregor       HadError = true;
1381e7ab3669SDouglas Gregor       return;
1382e7ab3669SDouglas Gregor     }
13834b8a9e95SBen Langmuir 
13844b8a9e95SBen Langmuir     if (ModuleMapFile != Map.getContainingModuleMapFile(TopLevelModule)) {
13854b8a9e95SBen Langmuir       assert(ModuleMapFile != Map.getModuleMapFileForUniquing(TopLevelModule) &&
13864b8a9e95SBen Langmuir              "submodule defined in same file as 'module *' that allowed its "
13874b8a9e95SBen Langmuir              "top-level module");
13884b8a9e95SBen Langmuir       Map.addAdditionalModuleMapFile(TopLevelModule, ModuleMapFile);
13894b8a9e95SBen Langmuir     }
1390e7ab3669SDouglas Gregor   }
1391e7ab3669SDouglas Gregor 
1392e7ab3669SDouglas Gregor   StringRef ModuleName = Id.back().first;
1393e7ab3669SDouglas Gregor   SourceLocation ModuleNameLoc = Id.back().second;
1394718292f2SDouglas Gregor 
1395a686e1b0SDouglas Gregor   // Parse the optional attribute list.
13964442605fSBill Wendling   Attributes Attrs;
13979194a91dSDouglas Gregor   parseOptionalAttributes(Attrs);
1398a686e1b0SDouglas Gregor 
1399718292f2SDouglas Gregor   // Parse the opening brace.
1400718292f2SDouglas Gregor   if (!Tok.is(MMToken::LBrace)) {
1401718292f2SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_lbrace)
1402718292f2SDouglas Gregor       << ModuleName;
1403718292f2SDouglas Gregor     HadError = true;
1404718292f2SDouglas Gregor     return;
1405718292f2SDouglas Gregor   }
1406718292f2SDouglas Gregor   SourceLocation LBraceLoc = consumeToken();
1407718292f2SDouglas Gregor 
1408718292f2SDouglas Gregor   // Determine whether this (sub)module has already been defined.
1409eb90e830SDouglas Gregor   if (Module *Existing = Map.lookupModuleQualified(ModuleName, ActiveModule)) {
1410fcc54a3bSDouglas Gregor     if (Existing->DefinitionLoc.isInvalid() && !ActiveModule) {
1411fcc54a3bSDouglas Gregor       // Skip the module definition.
1412fcc54a3bSDouglas Gregor       skipUntil(MMToken::RBrace);
1413fcc54a3bSDouglas Gregor       if (Tok.is(MMToken::RBrace))
1414fcc54a3bSDouglas Gregor         consumeToken();
1415fcc54a3bSDouglas Gregor       else {
1416fcc54a3bSDouglas Gregor         Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
1417fcc54a3bSDouglas Gregor         Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
1418fcc54a3bSDouglas Gregor         HadError = true;
1419fcc54a3bSDouglas Gregor       }
1420fcc54a3bSDouglas Gregor       return;
1421fcc54a3bSDouglas Gregor     }
1422fcc54a3bSDouglas Gregor 
1423718292f2SDouglas Gregor     Diags.Report(ModuleNameLoc, diag::err_mmap_module_redefinition)
1424718292f2SDouglas Gregor       << ModuleName;
1425eb90e830SDouglas Gregor     Diags.Report(Existing->DefinitionLoc, diag::note_mmap_prev_definition);
1426718292f2SDouglas Gregor 
1427718292f2SDouglas Gregor     // Skip the module definition.
1428718292f2SDouglas Gregor     skipUntil(MMToken::RBrace);
1429718292f2SDouglas Gregor     if (Tok.is(MMToken::RBrace))
1430718292f2SDouglas Gregor       consumeToken();
1431718292f2SDouglas Gregor 
1432718292f2SDouglas Gregor     HadError = true;
1433718292f2SDouglas Gregor     return;
1434718292f2SDouglas Gregor   }
1435718292f2SDouglas Gregor 
1436718292f2SDouglas Gregor   // Start defining this module.
14379d6448b1SBen Langmuir   ActiveModule = Map.findOrCreateModule(ModuleName, ActiveModule, Framework,
14389d6448b1SBen Langmuir                                         Explicit).first;
1439eb90e830SDouglas Gregor   ActiveModule->DefinitionLoc = ModuleNameLoc;
1440963c5535SDouglas Gregor   if (Attrs.IsSystem || IsSystem)
1441a686e1b0SDouglas Gregor     ActiveModule->IsSystem = true;
144277944868SRichard Smith   if (Attrs.IsExternC)
144377944868SRichard Smith     ActiveModule->IsExternC = true;
14443c1a41adSRichard Smith   ActiveModule->Directory = Directory;
1445718292f2SDouglas Gregor 
1446718292f2SDouglas Gregor   bool Done = false;
1447718292f2SDouglas Gregor   do {
1448718292f2SDouglas Gregor     switch (Tok.Kind) {
1449718292f2SDouglas Gregor     case MMToken::EndOfFile:
1450718292f2SDouglas Gregor     case MMToken::RBrace:
1451718292f2SDouglas Gregor       Done = true;
1452718292f2SDouglas Gregor       break;
1453718292f2SDouglas Gregor 
145435b13eceSDouglas Gregor     case MMToken::ConfigMacros:
145535b13eceSDouglas Gregor       parseConfigMacros();
145635b13eceSDouglas Gregor       break;
145735b13eceSDouglas Gregor 
1458fb912657SDouglas Gregor     case MMToken::Conflict:
1459fb912657SDouglas Gregor       parseConflict();
1460fb912657SDouglas Gregor       break;
1461fb912657SDouglas Gregor 
1462718292f2SDouglas Gregor     case MMToken::ExplicitKeyword:
146397292843SDaniel Jasper     case MMToken::ExternKeyword:
1464f2161a70SDouglas Gregor     case MMToken::FrameworkKeyword:
1465718292f2SDouglas Gregor     case MMToken::ModuleKeyword:
1466718292f2SDouglas Gregor       parseModuleDecl();
1467718292f2SDouglas Gregor       break;
1468718292f2SDouglas Gregor 
14692b82c2a5SDouglas Gregor     case MMToken::ExportKeyword:
14702b82c2a5SDouglas Gregor       parseExportDecl();
14712b82c2a5SDouglas Gregor       break;
14722b82c2a5SDouglas Gregor 
1473ba7f2f71SDaniel Jasper     case MMToken::UseKeyword:
1474ba7f2f71SDaniel Jasper       parseUseDecl();
1475ba7f2f71SDaniel Jasper       break;
1476ba7f2f71SDaniel Jasper 
14771fb5c3a6SDouglas Gregor     case MMToken::RequiresKeyword:
14781fb5c3a6SDouglas Gregor       parseRequiresDecl();
14791fb5c3a6SDouglas Gregor       break;
14801fb5c3a6SDouglas Gregor 
1481202210b3SRichard Smith     case MMToken::TextualKeyword:
1482202210b3SRichard Smith       parseHeaderDecl(MMToken::TextualKeyword, consumeToken());
1483306d8920SRichard Smith       break;
1484306d8920SRichard Smith 
1485524e33e1SDouglas Gregor     case MMToken::UmbrellaKeyword: {
1486524e33e1SDouglas Gregor       SourceLocation UmbrellaLoc = consumeToken();
1487524e33e1SDouglas Gregor       if (Tok.is(MMToken::HeaderKeyword))
1488b53e5483SLawrence Crowl         parseHeaderDecl(MMToken::UmbrellaKeyword, UmbrellaLoc);
1489524e33e1SDouglas Gregor       else
1490524e33e1SDouglas Gregor         parseUmbrellaDirDecl(UmbrellaLoc);
1491718292f2SDouglas Gregor       break;
1492524e33e1SDouglas Gregor     }
1493718292f2SDouglas Gregor 
1494202210b3SRichard Smith     case MMToken::ExcludeKeyword:
1495202210b3SRichard Smith       parseHeaderDecl(MMToken::ExcludeKeyword, consumeToken());
149659527666SDouglas Gregor       break;
149759527666SDouglas Gregor 
1498202210b3SRichard Smith     case MMToken::PrivateKeyword:
1499202210b3SRichard Smith       parseHeaderDecl(MMToken::PrivateKeyword, consumeToken());
1500b53e5483SLawrence Crowl       break;
1501b53e5483SLawrence Crowl 
1502322f633cSDouglas Gregor     case MMToken::HeaderKeyword:
1503202210b3SRichard Smith       parseHeaderDecl(MMToken::HeaderKeyword, consumeToken());
1504718292f2SDouglas Gregor       break;
1505718292f2SDouglas Gregor 
15066ddfca91SDouglas Gregor     case MMToken::LinkKeyword:
15076ddfca91SDouglas Gregor       parseLinkDecl();
15086ddfca91SDouglas Gregor       break;
15096ddfca91SDouglas Gregor 
1510718292f2SDouglas Gregor     default:
1511718292f2SDouglas Gregor       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_member);
1512718292f2SDouglas Gregor       consumeToken();
1513718292f2SDouglas Gregor       break;
1514718292f2SDouglas Gregor     }
1515718292f2SDouglas Gregor   } while (!Done);
1516718292f2SDouglas Gregor 
1517718292f2SDouglas Gregor   if (Tok.is(MMToken::RBrace))
1518718292f2SDouglas Gregor     consumeToken();
1519718292f2SDouglas Gregor   else {
1520718292f2SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
1521718292f2SDouglas Gregor     Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
1522718292f2SDouglas Gregor     HadError = true;
1523718292f2SDouglas Gregor   }
1524718292f2SDouglas Gregor 
152511dfe6feSDouglas Gregor   // If the active module is a top-level framework, and there are no link
152611dfe6feSDouglas Gregor   // libraries, automatically link against the framework.
152711dfe6feSDouglas Gregor   if (ActiveModule->IsFramework && !ActiveModule->isSubFramework() &&
152811dfe6feSDouglas Gregor       ActiveModule->LinkLibraries.empty()) {
152911dfe6feSDouglas Gregor     inferFrameworkLink(ActiveModule, Directory, SourceMgr.getFileManager());
153011dfe6feSDouglas Gregor   }
153111dfe6feSDouglas Gregor 
1532ec8c9752SBen Langmuir   // If the module meets all requirements but is still unavailable, mark the
1533ec8c9752SBen Langmuir   // whole tree as unavailable to prevent it from building.
1534ec8c9752SBen Langmuir   if (!ActiveModule->IsAvailable && !ActiveModule->IsMissingRequirement &&
1535ec8c9752SBen Langmuir       ActiveModule->Parent) {
1536ec8c9752SBen Langmuir     ActiveModule->getTopLevelModule()->markUnavailable();
1537ec8c9752SBen Langmuir     ActiveModule->getTopLevelModule()->MissingHeaders.append(
1538ec8c9752SBen Langmuir       ActiveModule->MissingHeaders.begin(), ActiveModule->MissingHeaders.end());
1539ec8c9752SBen Langmuir   }
1540ec8c9752SBen Langmuir 
1541e7ab3669SDouglas Gregor   // We're done parsing this module. Pop back to the previous module.
1542e7ab3669SDouglas Gregor   ActiveModule = PreviousActiveModule;
1543718292f2SDouglas Gregor }
1544718292f2SDouglas Gregor 
154597292843SDaniel Jasper /// \brief Parse an extern module declaration.
154697292843SDaniel Jasper ///
154797292843SDaniel Jasper ///   extern module-declaration:
154897292843SDaniel Jasper ///     'extern' 'module' module-id string-literal
154997292843SDaniel Jasper void ModuleMapParser::parseExternModuleDecl() {
155097292843SDaniel Jasper   assert(Tok.is(MMToken::ExternKeyword));
155197292843SDaniel Jasper   consumeToken(); // 'extern' keyword
155297292843SDaniel Jasper 
155397292843SDaniel Jasper   // Parse 'module' keyword.
155497292843SDaniel Jasper   if (!Tok.is(MMToken::ModuleKeyword)) {
155597292843SDaniel Jasper     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module);
155697292843SDaniel Jasper     consumeToken();
155797292843SDaniel Jasper     HadError = true;
155897292843SDaniel Jasper     return;
155997292843SDaniel Jasper   }
156097292843SDaniel Jasper   consumeToken(); // 'module' keyword
156197292843SDaniel Jasper 
156297292843SDaniel Jasper   // Parse the module name.
156397292843SDaniel Jasper   ModuleId Id;
156497292843SDaniel Jasper   if (parseModuleId(Id)) {
156597292843SDaniel Jasper     HadError = true;
156697292843SDaniel Jasper     return;
156797292843SDaniel Jasper   }
156897292843SDaniel Jasper 
156997292843SDaniel Jasper   // Parse the referenced module map file name.
157097292843SDaniel Jasper   if (!Tok.is(MMToken::StringLiteral)) {
157197292843SDaniel Jasper     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_mmap_file);
157297292843SDaniel Jasper     HadError = true;
157397292843SDaniel Jasper     return;
157497292843SDaniel Jasper   }
157597292843SDaniel Jasper   std::string FileName = Tok.getString();
157697292843SDaniel Jasper   consumeToken(); // filename
157797292843SDaniel Jasper 
157897292843SDaniel Jasper   StringRef FileNameRef = FileName;
157997292843SDaniel Jasper   SmallString<128> ModuleMapFileName;
158097292843SDaniel Jasper   if (llvm::sys::path::is_relative(FileNameRef)) {
158197292843SDaniel Jasper     ModuleMapFileName += Directory->getName();
158297292843SDaniel Jasper     llvm::sys::path::append(ModuleMapFileName, FileName);
158392e1b62dSYaron Keren     FileNameRef = ModuleMapFileName;
158497292843SDaniel Jasper   }
158597292843SDaniel Jasper   if (const FileEntry *File = SourceMgr.getFileManager().getFile(FileNameRef))
15869acb99e3SRichard Smith     Map.parseModuleMapFile(
15879acb99e3SRichard Smith         File, /*IsSystem=*/false,
15889acb99e3SRichard Smith         Map.HeaderInfo.getHeaderSearchOpts().ModuleMapFileHomeIsCwd
15899acb99e3SRichard Smith             ? Directory
15909acb99e3SRichard Smith             : File->getDir());
159197292843SDaniel Jasper }
159297292843SDaniel Jasper 
15931fb5c3a6SDouglas Gregor /// \brief Parse a requires declaration.
15941fb5c3a6SDouglas Gregor ///
15951fb5c3a6SDouglas Gregor ///   requires-declaration:
15961fb5c3a6SDouglas Gregor ///     'requires' feature-list
15971fb5c3a6SDouglas Gregor ///
15981fb5c3a6SDouglas Gregor ///   feature-list:
1599a3feee2aSRichard Smith ///     feature ',' feature-list
1600a3feee2aSRichard Smith ///     feature
1601a3feee2aSRichard Smith ///
1602a3feee2aSRichard Smith ///   feature:
1603a3feee2aSRichard Smith ///     '!'[opt] identifier
16041fb5c3a6SDouglas Gregor void ModuleMapParser::parseRequiresDecl() {
16051fb5c3a6SDouglas Gregor   assert(Tok.is(MMToken::RequiresKeyword));
16061fb5c3a6SDouglas Gregor 
16071fb5c3a6SDouglas Gregor   // Parse 'requires' keyword.
16081fb5c3a6SDouglas Gregor   consumeToken();
16091fb5c3a6SDouglas Gregor 
16101fb5c3a6SDouglas Gregor   // Parse the feature-list.
16111fb5c3a6SDouglas Gregor   do {
1612a3feee2aSRichard Smith     bool RequiredState = true;
1613a3feee2aSRichard Smith     if (Tok.is(MMToken::Exclaim)) {
1614a3feee2aSRichard Smith       RequiredState = false;
1615a3feee2aSRichard Smith       consumeToken();
1616a3feee2aSRichard Smith     }
1617a3feee2aSRichard Smith 
16181fb5c3a6SDouglas Gregor     if (!Tok.is(MMToken::Identifier)) {
16191fb5c3a6SDouglas Gregor       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_feature);
16201fb5c3a6SDouglas Gregor       HadError = true;
16211fb5c3a6SDouglas Gregor       return;
16221fb5c3a6SDouglas Gregor     }
16231fb5c3a6SDouglas Gregor 
16241fb5c3a6SDouglas Gregor     // Consume the feature name.
16251fb5c3a6SDouglas Gregor     std::string Feature = Tok.getString();
16261fb5c3a6SDouglas Gregor     consumeToken();
16271fb5c3a6SDouglas Gregor 
16281fb5c3a6SDouglas Gregor     // Add this feature.
1629a3feee2aSRichard Smith     ActiveModule->addRequirement(Feature, RequiredState,
1630a3feee2aSRichard Smith                                  Map.LangOpts, *Map.Target);
16311fb5c3a6SDouglas Gregor 
16321fb5c3a6SDouglas Gregor     if (!Tok.is(MMToken::Comma))
16331fb5c3a6SDouglas Gregor       break;
16341fb5c3a6SDouglas Gregor 
16351fb5c3a6SDouglas Gregor     // Consume the comma.
16361fb5c3a6SDouglas Gregor     consumeToken();
16371fb5c3a6SDouglas Gregor   } while (true);
16381fb5c3a6SDouglas Gregor }
16391fb5c3a6SDouglas Gregor 
1640f2161a70SDouglas Gregor /// \brief Append to \p Paths the set of paths needed to get to the
1641f2161a70SDouglas Gregor /// subframework in which the given module lives.
1642bf8da9d7SBenjamin Kramer static void appendSubframeworkPaths(Module *Mod,
1643f857950dSDmitri Gribenko                                     SmallVectorImpl<char> &Path) {
1644f2161a70SDouglas Gregor   // Collect the framework names from the given module to the top-level module.
1645f857950dSDmitri Gribenko   SmallVector<StringRef, 2> Paths;
1646f2161a70SDouglas Gregor   for (; Mod; Mod = Mod->Parent) {
1647f2161a70SDouglas Gregor     if (Mod->IsFramework)
1648f2161a70SDouglas Gregor       Paths.push_back(Mod->Name);
1649f2161a70SDouglas Gregor   }
1650f2161a70SDouglas Gregor 
1651f2161a70SDouglas Gregor   if (Paths.empty())
1652f2161a70SDouglas Gregor     return;
1653f2161a70SDouglas Gregor 
1654f2161a70SDouglas Gregor   // Add Frameworks/Name.framework for each subframework.
165517381a06SBenjamin Kramer   for (unsigned I = Paths.size() - 1; I != 0; --I)
165617381a06SBenjamin Kramer     llvm::sys::path::append(Path, "Frameworks", Paths[I-1] + ".framework");
1657f2161a70SDouglas Gregor }
1658f2161a70SDouglas Gregor 
1659718292f2SDouglas Gregor /// \brief Parse a header declaration.
1660718292f2SDouglas Gregor ///
1661718292f2SDouglas Gregor ///   header-declaration:
1662306d8920SRichard Smith ///     'textual'[opt] 'header' string-literal
1663202210b3SRichard Smith ///     'private' 'textual'[opt] 'header' string-literal
1664202210b3SRichard Smith ///     'exclude' 'header' string-literal
1665202210b3SRichard Smith ///     'umbrella' 'header' string-literal
1666306d8920SRichard Smith ///
1667306d8920SRichard Smith /// FIXME: Support 'private textual header'.
1668b53e5483SLawrence Crowl void ModuleMapParser::parseHeaderDecl(MMToken::TokenKind LeadingToken,
1669b53e5483SLawrence Crowl                                       SourceLocation LeadingLoc) {
1670202210b3SRichard Smith   // We've already consumed the first token.
1671202210b3SRichard Smith   ModuleMap::ModuleHeaderRole Role = ModuleMap::NormalHeader;
1672202210b3SRichard Smith   if (LeadingToken == MMToken::PrivateKeyword) {
1673202210b3SRichard Smith     Role = ModuleMap::PrivateHeader;
1674202210b3SRichard Smith     // 'private' may optionally be followed by 'textual'.
1675202210b3SRichard Smith     if (Tok.is(MMToken::TextualKeyword)) {
1676202210b3SRichard Smith       LeadingToken = Tok.Kind;
16771871ed3dSBenjamin Kramer       consumeToken();
1678202210b3SRichard Smith     }
1679202210b3SRichard Smith   }
1680202210b3SRichard Smith   if (LeadingToken == MMToken::TextualKeyword)
1681202210b3SRichard Smith     Role = ModuleMap::ModuleHeaderRole(Role | ModuleMap::TextualHeader);
1682202210b3SRichard Smith 
1683202210b3SRichard Smith   if (LeadingToken != MMToken::HeaderKeyword) {
1684202210b3SRichard Smith     if (!Tok.is(MMToken::HeaderKeyword)) {
1685202210b3SRichard Smith       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
1686202210b3SRichard Smith           << (LeadingToken == MMToken::PrivateKeyword ? "private" :
1687202210b3SRichard Smith               LeadingToken == MMToken::ExcludeKeyword ? "exclude" :
1688202210b3SRichard Smith               LeadingToken == MMToken::TextualKeyword ? "textual" : "umbrella");
1689202210b3SRichard Smith       return;
1690202210b3SRichard Smith     }
1691202210b3SRichard Smith     consumeToken();
1692202210b3SRichard Smith   }
1693718292f2SDouglas Gregor 
1694718292f2SDouglas Gregor   // Parse the header name.
1695718292f2SDouglas Gregor   if (!Tok.is(MMToken::StringLiteral)) {
1696718292f2SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
1697718292f2SDouglas Gregor       << "header";
1698718292f2SDouglas Gregor     HadError = true;
1699718292f2SDouglas Gregor     return;
1700718292f2SDouglas Gregor   }
17013c1a41adSRichard Smith   Module::UnresolvedHeaderDirective Header;
17020761a8a0SDaniel Jasper   Header.FileName = Tok.getString();
17030761a8a0SDaniel Jasper   Header.FileNameLoc = consumeToken();
1704718292f2SDouglas Gregor 
1705524e33e1SDouglas Gregor   // Check whether we already have an umbrella.
1706b53e5483SLawrence Crowl   if (LeadingToken == MMToken::UmbrellaKeyword && ActiveModule->Umbrella) {
17070761a8a0SDaniel Jasper     Diags.Report(Header.FileNameLoc, diag::err_mmap_umbrella_clash)
1708524e33e1SDouglas Gregor       << ActiveModule->getFullModuleName();
1709322f633cSDouglas Gregor     HadError = true;
1710322f633cSDouglas Gregor     return;
1711322f633cSDouglas Gregor   }
1712322f633cSDouglas Gregor 
17135257fc63SDouglas Gregor   // Look for this file.
1714d2d442caSCraig Topper   const FileEntry *File = nullptr;
1715d2d442caSCraig Topper   const FileEntry *BuiltinFile = nullptr;
17163c1a41adSRichard Smith   SmallString<128> RelativePathName;
17170761a8a0SDaniel Jasper   if (llvm::sys::path::is_absolute(Header.FileName)) {
17183c1a41adSRichard Smith     RelativePathName = Header.FileName;
17193c1a41adSRichard Smith     File = SourceMgr.getFileManager().getFile(RelativePathName);
1720e7ab3669SDouglas Gregor   } else {
1721e7ab3669SDouglas Gregor     // Search for the header file within the search directory.
17223c1a41adSRichard Smith     SmallString<128> FullPathName(Directory->getName());
17233c1a41adSRichard Smith     unsigned FullPathLength = FullPathName.size();
1724755b2055SDouglas Gregor 
1725f2161a70SDouglas Gregor     if (ActiveModule->isPartOfFramework()) {
17263c1a41adSRichard Smith       appendSubframeworkPaths(ActiveModule, RelativePathName);
1727755b2055SDouglas Gregor 
1728e7ab3669SDouglas Gregor       // Check whether this file is in the public headers.
17293c1a41adSRichard Smith       llvm::sys::path::append(RelativePathName, "Headers", Header.FileName);
173092e1b62dSYaron Keren       llvm::sys::path::append(FullPathName, RelativePathName);
17313c1a41adSRichard Smith       File = SourceMgr.getFileManager().getFile(FullPathName);
1732e7ab3669SDouglas Gregor 
1733e7ab3669SDouglas Gregor       if (!File) {
1734e7ab3669SDouglas Gregor         // Check whether this file is in the private headers.
17353c1a41adSRichard Smith         // FIXME: Should we retain the subframework paths here?
17363c1a41adSRichard Smith         RelativePathName.clear();
17373c1a41adSRichard Smith         FullPathName.resize(FullPathLength);
17383c1a41adSRichard Smith         llvm::sys::path::append(RelativePathName, "PrivateHeaders",
17393c1a41adSRichard Smith                                 Header.FileName);
174092e1b62dSYaron Keren         llvm::sys::path::append(FullPathName, RelativePathName);
17413c1a41adSRichard Smith         File = SourceMgr.getFileManager().getFile(FullPathName);
1742e7ab3669SDouglas Gregor       }
1743e7ab3669SDouglas Gregor     } else {
1744e7ab3669SDouglas Gregor       // Lookup for normal headers.
17453c1a41adSRichard Smith       llvm::sys::path::append(RelativePathName, Header.FileName);
174692e1b62dSYaron Keren       llvm::sys::path::append(FullPathName, RelativePathName);
17473c1a41adSRichard Smith       File = SourceMgr.getFileManager().getFile(FullPathName);
17483ec6663bSDouglas Gregor 
17493ec6663bSDouglas Gregor       // If this is a system module with a top-level header, this header
17503ec6663bSDouglas Gregor       // may have a counterpart (or replacement) in the set of headers
17513ec6663bSDouglas Gregor       // supplied by Clang. Find that builtin header.
1752b53e5483SLawrence Crowl       if (ActiveModule->IsSystem && LeadingToken != MMToken::UmbrellaKeyword &&
1753b53e5483SLawrence Crowl           BuiltinIncludeDir && BuiltinIncludeDir != Directory &&
17540761a8a0SDaniel Jasper           isBuiltinHeader(Header.FileName)) {
17552c1dd271SDylan Noblesmith         SmallString<128> BuiltinPathName(BuiltinIncludeDir->getName());
17560761a8a0SDaniel Jasper         llvm::sys::path::append(BuiltinPathName, Header.FileName);
17573ec6663bSDouglas Gregor         BuiltinFile = SourceMgr.getFileManager().getFile(BuiltinPathName);
17583ec6663bSDouglas Gregor 
17593ec6663bSDouglas Gregor         // If Clang supplies this header but the underlying system does not,
17603ec6663bSDouglas Gregor         // just silently swap in our builtin version. Otherwise, we'll end
17613ec6663bSDouglas Gregor         // up adding both (later).
17623ec6663bSDouglas Gregor         if (!File && BuiltinFile) {
17633ec6663bSDouglas Gregor           File = BuiltinFile;
17643c1a41adSRichard Smith           RelativePathName = BuiltinPathName;
1765d2d442caSCraig Topper           BuiltinFile = nullptr;
17663ec6663bSDouglas Gregor         }
17673ec6663bSDouglas Gregor       }
1768e7ab3669SDouglas Gregor     }
1769e7ab3669SDouglas Gregor   }
17705257fc63SDouglas Gregor 
17715257fc63SDouglas Gregor   // FIXME: We shouldn't be eagerly stat'ing every file named in a module map.
17725257fc63SDouglas Gregor   // Come up with a lazy way to do this.
1773e7ab3669SDouglas Gregor   if (File) {
177497da9178SDaniel Jasper     if (LeadingToken == MMToken::UmbrellaKeyword) {
1775322f633cSDouglas Gregor       const DirectoryEntry *UmbrellaDir = File->getDir();
177659527666SDouglas Gregor       if (Module *UmbrellaModule = Map.UmbrellaDirs[UmbrellaDir]) {
1777b53e5483SLawrence Crowl         Diags.Report(LeadingLoc, diag::err_mmap_umbrella_clash)
177859527666SDouglas Gregor           << UmbrellaModule->getFullModuleName();
1779322f633cSDouglas Gregor         HadError = true;
17805257fc63SDouglas Gregor       } else {
1781322f633cSDouglas Gregor         // Record this umbrella header.
1782322f633cSDouglas Gregor         Map.setUmbrellaHeader(ActiveModule, File);
1783322f633cSDouglas Gregor       }
1784feb54b6dSRichard Smith     } else if (LeadingToken == MMToken::ExcludeKeyword) {
17850101b540SHans Wennborg       Module::Header H = {RelativePathName.str(), File};
17860101b540SHans Wennborg       Map.excludeHeader(ActiveModule, H);
1787322f633cSDouglas Gregor     } else {
178825d50758SRichard Smith       // If there is a builtin counterpart to this file, add it now, before
178925d50758SRichard Smith       // the "real" header, so we build the built-in one first when building
179025d50758SRichard Smith       // the module.
17910101b540SHans Wennborg       if (BuiltinFile) {
17923c1a41adSRichard Smith         // FIXME: Taking the name from the FileEntry is unstable and can give
17933c1a41adSRichard Smith         // different results depending on how we've previously named that file
17943c1a41adSRichard Smith         // in this build.
17950101b540SHans Wennborg         Module::Header H = { BuiltinFile->getName(), BuiltinFile };
17960101b540SHans Wennborg         Map.addHeader(ActiveModule, H, Role);
17970101b540SHans Wennborg       }
179825d50758SRichard Smith 
1799202210b3SRichard Smith       // Record this header.
18000101b540SHans Wennborg       Module::Header H = { RelativePathName.str(), File };
18010101b540SHans Wennborg       Map.addHeader(ActiveModule, H, Role);
18025257fc63SDouglas Gregor     }
1803b53e5483SLawrence Crowl   } else if (LeadingToken != MMToken::ExcludeKeyword) {
18044b27a64bSDouglas Gregor     // Ignore excluded header files. They're optional anyway.
18054b27a64bSDouglas Gregor 
18060761a8a0SDaniel Jasper     // If we find a module that has a missing header, we mark this module as
18070761a8a0SDaniel Jasper     // unavailable and store the header directive for displaying diagnostics.
18080761a8a0SDaniel Jasper     Header.IsUmbrella = LeadingToken == MMToken::UmbrellaKeyword;
1809ec8c9752SBen Langmuir     ActiveModule->markUnavailable();
18100761a8a0SDaniel Jasper     ActiveModule->MissingHeaders.push_back(Header);
18115257fc63SDouglas Gregor   }
1812718292f2SDouglas Gregor }
1813718292f2SDouglas Gregor 
1814524e33e1SDouglas Gregor /// \brief Parse an umbrella directory declaration.
1815524e33e1SDouglas Gregor ///
1816524e33e1SDouglas Gregor ///   umbrella-dir-declaration:
1817524e33e1SDouglas Gregor ///     umbrella string-literal
1818524e33e1SDouglas Gregor void ModuleMapParser::parseUmbrellaDirDecl(SourceLocation UmbrellaLoc) {
1819524e33e1SDouglas Gregor   // Parse the directory name.
1820524e33e1SDouglas Gregor   if (!Tok.is(MMToken::StringLiteral)) {
1821524e33e1SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
1822524e33e1SDouglas Gregor       << "umbrella";
1823524e33e1SDouglas Gregor     HadError = true;
1824524e33e1SDouglas Gregor     return;
1825524e33e1SDouglas Gregor   }
1826524e33e1SDouglas Gregor 
1827524e33e1SDouglas Gregor   std::string DirName = Tok.getString();
1828524e33e1SDouglas Gregor   SourceLocation DirNameLoc = consumeToken();
1829524e33e1SDouglas Gregor 
1830524e33e1SDouglas Gregor   // Check whether we already have an umbrella.
1831524e33e1SDouglas Gregor   if (ActiveModule->Umbrella) {
1832524e33e1SDouglas Gregor     Diags.Report(DirNameLoc, diag::err_mmap_umbrella_clash)
1833524e33e1SDouglas Gregor       << ActiveModule->getFullModuleName();
1834524e33e1SDouglas Gregor     HadError = true;
1835524e33e1SDouglas Gregor     return;
1836524e33e1SDouglas Gregor   }
1837524e33e1SDouglas Gregor 
1838524e33e1SDouglas Gregor   // Look for this file.
1839d2d442caSCraig Topper   const DirectoryEntry *Dir = nullptr;
1840524e33e1SDouglas Gregor   if (llvm::sys::path::is_absolute(DirName))
1841524e33e1SDouglas Gregor     Dir = SourceMgr.getFileManager().getDirectory(DirName);
1842524e33e1SDouglas Gregor   else {
18432c1dd271SDylan Noblesmith     SmallString<128> PathName;
1844524e33e1SDouglas Gregor     PathName = Directory->getName();
1845524e33e1SDouglas Gregor     llvm::sys::path::append(PathName, DirName);
1846524e33e1SDouglas Gregor     Dir = SourceMgr.getFileManager().getDirectory(PathName);
1847524e33e1SDouglas Gregor   }
1848524e33e1SDouglas Gregor 
1849524e33e1SDouglas Gregor   if (!Dir) {
1850524e33e1SDouglas Gregor     Diags.Report(DirNameLoc, diag::err_mmap_umbrella_dir_not_found)
1851524e33e1SDouglas Gregor       << DirName;
1852524e33e1SDouglas Gregor     HadError = true;
1853524e33e1SDouglas Gregor     return;
1854524e33e1SDouglas Gregor   }
1855524e33e1SDouglas Gregor 
1856524e33e1SDouglas Gregor   if (Module *OwningModule = Map.UmbrellaDirs[Dir]) {
1857524e33e1SDouglas Gregor     Diags.Report(UmbrellaLoc, diag::err_mmap_umbrella_clash)
1858524e33e1SDouglas Gregor       << OwningModule->getFullModuleName();
1859524e33e1SDouglas Gregor     HadError = true;
1860524e33e1SDouglas Gregor     return;
1861524e33e1SDouglas Gregor   }
1862524e33e1SDouglas Gregor 
1863524e33e1SDouglas Gregor   // Record this umbrella directory.
1864524e33e1SDouglas Gregor   Map.setUmbrellaDir(ActiveModule, Dir);
1865524e33e1SDouglas Gregor }
1866524e33e1SDouglas Gregor 
18672b82c2a5SDouglas Gregor /// \brief Parse a module export declaration.
18682b82c2a5SDouglas Gregor ///
18692b82c2a5SDouglas Gregor ///   export-declaration:
18702b82c2a5SDouglas Gregor ///     'export' wildcard-module-id
18712b82c2a5SDouglas Gregor ///
18722b82c2a5SDouglas Gregor ///   wildcard-module-id:
18732b82c2a5SDouglas Gregor ///     identifier
18742b82c2a5SDouglas Gregor ///     '*'
18752b82c2a5SDouglas Gregor ///     identifier '.' wildcard-module-id
18762b82c2a5SDouglas Gregor void ModuleMapParser::parseExportDecl() {
18772b82c2a5SDouglas Gregor   assert(Tok.is(MMToken::ExportKeyword));
18782b82c2a5SDouglas Gregor   SourceLocation ExportLoc = consumeToken();
18792b82c2a5SDouglas Gregor 
18802b82c2a5SDouglas Gregor   // Parse the module-id with an optional wildcard at the end.
18812b82c2a5SDouglas Gregor   ModuleId ParsedModuleId;
18822b82c2a5SDouglas Gregor   bool Wildcard = false;
18832b82c2a5SDouglas Gregor   do {
1884306d8920SRichard Smith     // FIXME: Support string-literal module names here.
18852b82c2a5SDouglas Gregor     if (Tok.is(MMToken::Identifier)) {
18862b82c2a5SDouglas Gregor       ParsedModuleId.push_back(std::make_pair(Tok.getString(),
18872b82c2a5SDouglas Gregor                                               Tok.getLocation()));
18882b82c2a5SDouglas Gregor       consumeToken();
18892b82c2a5SDouglas Gregor 
18902b82c2a5SDouglas Gregor       if (Tok.is(MMToken::Period)) {
18912b82c2a5SDouglas Gregor         consumeToken();
18922b82c2a5SDouglas Gregor         continue;
18932b82c2a5SDouglas Gregor       }
18942b82c2a5SDouglas Gregor 
18952b82c2a5SDouglas Gregor       break;
18962b82c2a5SDouglas Gregor     }
18972b82c2a5SDouglas Gregor 
18982b82c2a5SDouglas Gregor     if(Tok.is(MMToken::Star)) {
18992b82c2a5SDouglas Gregor       Wildcard = true;
1900f5eedd05SDouglas Gregor       consumeToken();
19012b82c2a5SDouglas Gregor       break;
19022b82c2a5SDouglas Gregor     }
19032b82c2a5SDouglas Gregor 
1904ba7f2f71SDaniel Jasper     Diags.Report(Tok.getLocation(), diag::err_mmap_module_id);
19052b82c2a5SDouglas Gregor     HadError = true;
19062b82c2a5SDouglas Gregor     return;
19072b82c2a5SDouglas Gregor   } while (true);
19082b82c2a5SDouglas Gregor 
19092b82c2a5SDouglas Gregor   Module::UnresolvedExportDecl Unresolved = {
19102b82c2a5SDouglas Gregor     ExportLoc, ParsedModuleId, Wildcard
19112b82c2a5SDouglas Gregor   };
19122b82c2a5SDouglas Gregor   ActiveModule->UnresolvedExports.push_back(Unresolved);
19132b82c2a5SDouglas Gregor }
19142b82c2a5SDouglas Gregor 
19158f4d3ff1SRichard Smith /// \brief Parse a module use declaration.
1916ba7f2f71SDaniel Jasper ///
19178f4d3ff1SRichard Smith ///   use-declaration:
19188f4d3ff1SRichard Smith ///     'use' wildcard-module-id
1919ba7f2f71SDaniel Jasper void ModuleMapParser::parseUseDecl() {
1920ba7f2f71SDaniel Jasper   assert(Tok.is(MMToken::UseKeyword));
19218f4d3ff1SRichard Smith   auto KWLoc = consumeToken();
1922ba7f2f71SDaniel Jasper   // Parse the module-id.
1923ba7f2f71SDaniel Jasper   ModuleId ParsedModuleId;
19243cd34c76SDaniel Jasper   parseModuleId(ParsedModuleId);
1925ba7f2f71SDaniel Jasper 
19268f4d3ff1SRichard Smith   if (ActiveModule->Parent)
19278f4d3ff1SRichard Smith     Diags.Report(KWLoc, diag::err_mmap_use_decl_submodule);
19288f4d3ff1SRichard Smith   else
1929ba7f2f71SDaniel Jasper     ActiveModule->UnresolvedDirectUses.push_back(ParsedModuleId);
1930ba7f2f71SDaniel Jasper }
1931ba7f2f71SDaniel Jasper 
19326ddfca91SDouglas Gregor /// \brief Parse a link declaration.
19336ddfca91SDouglas Gregor ///
19346ddfca91SDouglas Gregor ///   module-declaration:
19356ddfca91SDouglas Gregor ///     'link' 'framework'[opt] string-literal
19366ddfca91SDouglas Gregor void ModuleMapParser::parseLinkDecl() {
19376ddfca91SDouglas Gregor   assert(Tok.is(MMToken::LinkKeyword));
19386ddfca91SDouglas Gregor   SourceLocation LinkLoc = consumeToken();
19396ddfca91SDouglas Gregor 
19406ddfca91SDouglas Gregor   // Parse the optional 'framework' keyword.
19416ddfca91SDouglas Gregor   bool IsFramework = false;
19426ddfca91SDouglas Gregor   if (Tok.is(MMToken::FrameworkKeyword)) {
19436ddfca91SDouglas Gregor     consumeToken();
19446ddfca91SDouglas Gregor     IsFramework = true;
19456ddfca91SDouglas Gregor   }
19466ddfca91SDouglas Gregor 
19476ddfca91SDouglas Gregor   // Parse the library name
19486ddfca91SDouglas Gregor   if (!Tok.is(MMToken::StringLiteral)) {
19496ddfca91SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_library_name)
19506ddfca91SDouglas Gregor       << IsFramework << SourceRange(LinkLoc);
19516ddfca91SDouglas Gregor     HadError = true;
19526ddfca91SDouglas Gregor     return;
19536ddfca91SDouglas Gregor   }
19546ddfca91SDouglas Gregor 
19556ddfca91SDouglas Gregor   std::string LibraryName = Tok.getString();
19566ddfca91SDouglas Gregor   consumeToken();
19576ddfca91SDouglas Gregor   ActiveModule->LinkLibraries.push_back(Module::LinkLibrary(LibraryName,
19586ddfca91SDouglas Gregor                                                             IsFramework));
19596ddfca91SDouglas Gregor }
19606ddfca91SDouglas Gregor 
196135b13eceSDouglas Gregor /// \brief Parse a configuration macro declaration.
196235b13eceSDouglas Gregor ///
196335b13eceSDouglas Gregor ///   module-declaration:
196435b13eceSDouglas Gregor ///     'config_macros' attributes[opt] config-macro-list?
196535b13eceSDouglas Gregor ///
196635b13eceSDouglas Gregor ///   config-macro-list:
196735b13eceSDouglas Gregor ///     identifier (',' identifier)?
196835b13eceSDouglas Gregor void ModuleMapParser::parseConfigMacros() {
196935b13eceSDouglas Gregor   assert(Tok.is(MMToken::ConfigMacros));
197035b13eceSDouglas Gregor   SourceLocation ConfigMacrosLoc = consumeToken();
197135b13eceSDouglas Gregor 
197235b13eceSDouglas Gregor   // Only top-level modules can have configuration macros.
197335b13eceSDouglas Gregor   if (ActiveModule->Parent) {
197435b13eceSDouglas Gregor     Diags.Report(ConfigMacrosLoc, diag::err_mmap_config_macro_submodule);
197535b13eceSDouglas Gregor   }
197635b13eceSDouglas Gregor 
197735b13eceSDouglas Gregor   // Parse the optional attributes.
197835b13eceSDouglas Gregor   Attributes Attrs;
197935b13eceSDouglas Gregor   parseOptionalAttributes(Attrs);
198035b13eceSDouglas Gregor   if (Attrs.IsExhaustive && !ActiveModule->Parent) {
198135b13eceSDouglas Gregor     ActiveModule->ConfigMacrosExhaustive = true;
198235b13eceSDouglas Gregor   }
198335b13eceSDouglas Gregor 
198435b13eceSDouglas Gregor   // If we don't have an identifier, we're done.
1985306d8920SRichard Smith   // FIXME: Support macros with the same name as a keyword here.
198635b13eceSDouglas Gregor   if (!Tok.is(MMToken::Identifier))
198735b13eceSDouglas Gregor     return;
198835b13eceSDouglas Gregor 
198935b13eceSDouglas Gregor   // Consume the first identifier.
199035b13eceSDouglas Gregor   if (!ActiveModule->Parent) {
199135b13eceSDouglas Gregor     ActiveModule->ConfigMacros.push_back(Tok.getString().str());
199235b13eceSDouglas Gregor   }
199335b13eceSDouglas Gregor   consumeToken();
199435b13eceSDouglas Gregor 
199535b13eceSDouglas Gregor   do {
199635b13eceSDouglas Gregor     // If there's a comma, consume it.
199735b13eceSDouglas Gregor     if (!Tok.is(MMToken::Comma))
199835b13eceSDouglas Gregor       break;
199935b13eceSDouglas Gregor     consumeToken();
200035b13eceSDouglas Gregor 
200135b13eceSDouglas Gregor     // We expect to see a macro name here.
2002306d8920SRichard Smith     // FIXME: Support macros with the same name as a keyword here.
200335b13eceSDouglas Gregor     if (!Tok.is(MMToken::Identifier)) {
200435b13eceSDouglas Gregor       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_config_macro);
200535b13eceSDouglas Gregor       break;
200635b13eceSDouglas Gregor     }
200735b13eceSDouglas Gregor 
200835b13eceSDouglas Gregor     // Consume the macro name.
200935b13eceSDouglas Gregor     if (!ActiveModule->Parent) {
201035b13eceSDouglas Gregor       ActiveModule->ConfigMacros.push_back(Tok.getString().str());
201135b13eceSDouglas Gregor     }
201235b13eceSDouglas Gregor     consumeToken();
201335b13eceSDouglas Gregor   } while (true);
201435b13eceSDouglas Gregor }
201535b13eceSDouglas Gregor 
2016fb912657SDouglas Gregor /// \brief Format a module-id into a string.
2017fb912657SDouglas Gregor static std::string formatModuleId(const ModuleId &Id) {
2018fb912657SDouglas Gregor   std::string result;
2019fb912657SDouglas Gregor   {
2020fb912657SDouglas Gregor     llvm::raw_string_ostream OS(result);
2021fb912657SDouglas Gregor 
2022fb912657SDouglas Gregor     for (unsigned I = 0, N = Id.size(); I != N; ++I) {
2023fb912657SDouglas Gregor       if (I)
2024fb912657SDouglas Gregor         OS << ".";
2025fb912657SDouglas Gregor       OS << Id[I].first;
2026fb912657SDouglas Gregor     }
2027fb912657SDouglas Gregor   }
2028fb912657SDouglas Gregor 
2029fb912657SDouglas Gregor   return result;
2030fb912657SDouglas Gregor }
2031fb912657SDouglas Gregor 
2032fb912657SDouglas Gregor /// \brief Parse a conflict declaration.
2033fb912657SDouglas Gregor ///
2034fb912657SDouglas Gregor ///   module-declaration:
2035fb912657SDouglas Gregor ///     'conflict' module-id ',' string-literal
2036fb912657SDouglas Gregor void ModuleMapParser::parseConflict() {
2037fb912657SDouglas Gregor   assert(Tok.is(MMToken::Conflict));
2038fb912657SDouglas Gregor   SourceLocation ConflictLoc = consumeToken();
2039fb912657SDouglas Gregor   Module::UnresolvedConflict Conflict;
2040fb912657SDouglas Gregor 
2041fb912657SDouglas Gregor   // Parse the module-id.
2042fb912657SDouglas Gregor   if (parseModuleId(Conflict.Id))
2043fb912657SDouglas Gregor     return;
2044fb912657SDouglas Gregor 
2045fb912657SDouglas Gregor   // Parse the ','.
2046fb912657SDouglas Gregor   if (!Tok.is(MMToken::Comma)) {
2047fb912657SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_conflicts_comma)
2048fb912657SDouglas Gregor       << SourceRange(ConflictLoc);
2049fb912657SDouglas Gregor     return;
2050fb912657SDouglas Gregor   }
2051fb912657SDouglas Gregor   consumeToken();
2052fb912657SDouglas Gregor 
2053fb912657SDouglas Gregor   // Parse the message.
2054fb912657SDouglas Gregor   if (!Tok.is(MMToken::StringLiteral)) {
2055fb912657SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_conflicts_message)
2056fb912657SDouglas Gregor       << formatModuleId(Conflict.Id);
2057fb912657SDouglas Gregor     return;
2058fb912657SDouglas Gregor   }
2059fb912657SDouglas Gregor   Conflict.Message = Tok.getString().str();
2060fb912657SDouglas Gregor   consumeToken();
2061fb912657SDouglas Gregor 
2062fb912657SDouglas Gregor   // Add this unresolved conflict.
2063fb912657SDouglas Gregor   ActiveModule->UnresolvedConflicts.push_back(Conflict);
2064fb912657SDouglas Gregor }
2065fb912657SDouglas Gregor 
20666ddfca91SDouglas Gregor /// \brief Parse an inferred module declaration (wildcard modules).
20679194a91dSDouglas Gregor ///
20689194a91dSDouglas Gregor ///   module-declaration:
20699194a91dSDouglas Gregor ///     'explicit'[opt] 'framework'[opt] 'module' * attributes[opt]
20709194a91dSDouglas Gregor ///       { inferred-module-member* }
20719194a91dSDouglas Gregor ///
20729194a91dSDouglas Gregor ///   inferred-module-member:
20739194a91dSDouglas Gregor ///     'export' '*'
20749194a91dSDouglas Gregor ///     'exclude' identifier
20759194a91dSDouglas Gregor void ModuleMapParser::parseInferredModuleDecl(bool Framework, bool Explicit) {
207673441091SDouglas Gregor   assert(Tok.is(MMToken::Star));
207773441091SDouglas Gregor   SourceLocation StarLoc = consumeToken();
207873441091SDouglas Gregor   bool Failed = false;
207973441091SDouglas Gregor 
208073441091SDouglas Gregor   // Inferred modules must be submodules.
20819194a91dSDouglas Gregor   if (!ActiveModule && !Framework) {
208273441091SDouglas Gregor     Diags.Report(StarLoc, diag::err_mmap_top_level_inferred_submodule);
208373441091SDouglas Gregor     Failed = true;
208473441091SDouglas Gregor   }
208573441091SDouglas Gregor 
20869194a91dSDouglas Gregor   if (ActiveModule) {
2087524e33e1SDouglas Gregor     // Inferred modules must have umbrella directories.
20884898cde4SBen Langmuir     if (!Failed && ActiveModule->IsAvailable &&
20894898cde4SBen Langmuir         !ActiveModule->getUmbrellaDir()) {
209073441091SDouglas Gregor       Diags.Report(StarLoc, diag::err_mmap_inferred_no_umbrella);
209173441091SDouglas Gregor       Failed = true;
209273441091SDouglas Gregor     }
209373441091SDouglas Gregor 
209473441091SDouglas Gregor     // Check for redefinition of an inferred module.
2095dd005f69SDouglas Gregor     if (!Failed && ActiveModule->InferSubmodules) {
209673441091SDouglas Gregor       Diags.Report(StarLoc, diag::err_mmap_inferred_redef);
2097dd005f69SDouglas Gregor       if (ActiveModule->InferredSubmoduleLoc.isValid())
2098dd005f69SDouglas Gregor         Diags.Report(ActiveModule->InferredSubmoduleLoc,
209973441091SDouglas Gregor                      diag::note_mmap_prev_definition);
210073441091SDouglas Gregor       Failed = true;
210173441091SDouglas Gregor     }
210273441091SDouglas Gregor 
21039194a91dSDouglas Gregor     // Check for the 'framework' keyword, which is not permitted here.
21049194a91dSDouglas Gregor     if (Framework) {
21059194a91dSDouglas Gregor       Diags.Report(StarLoc, diag::err_mmap_inferred_framework_submodule);
21069194a91dSDouglas Gregor       Framework = false;
21079194a91dSDouglas Gregor     }
21089194a91dSDouglas Gregor   } else if (Explicit) {
21099194a91dSDouglas Gregor     Diags.Report(StarLoc, diag::err_mmap_explicit_inferred_framework);
21109194a91dSDouglas Gregor     Explicit = false;
21119194a91dSDouglas Gregor   }
21129194a91dSDouglas Gregor 
211373441091SDouglas Gregor   // If there were any problems with this inferred submodule, skip its body.
211473441091SDouglas Gregor   if (Failed) {
211573441091SDouglas Gregor     if (Tok.is(MMToken::LBrace)) {
211673441091SDouglas Gregor       consumeToken();
211773441091SDouglas Gregor       skipUntil(MMToken::RBrace);
211873441091SDouglas Gregor       if (Tok.is(MMToken::RBrace))
211973441091SDouglas Gregor         consumeToken();
212073441091SDouglas Gregor     }
212173441091SDouglas Gregor     HadError = true;
212273441091SDouglas Gregor     return;
212373441091SDouglas Gregor   }
212473441091SDouglas Gregor 
21259194a91dSDouglas Gregor   // Parse optional attributes.
21264442605fSBill Wendling   Attributes Attrs;
21279194a91dSDouglas Gregor   parseOptionalAttributes(Attrs);
21289194a91dSDouglas Gregor 
21299194a91dSDouglas Gregor   if (ActiveModule) {
213073441091SDouglas Gregor     // Note that we have an inferred submodule.
2131dd005f69SDouglas Gregor     ActiveModule->InferSubmodules = true;
2132dd005f69SDouglas Gregor     ActiveModule->InferredSubmoduleLoc = StarLoc;
2133dd005f69SDouglas Gregor     ActiveModule->InferExplicitSubmodules = Explicit;
21349194a91dSDouglas Gregor   } else {
21359194a91dSDouglas Gregor     // We'll be inferring framework modules for this directory.
21369194a91dSDouglas Gregor     Map.InferredDirectories[Directory].InferModules = true;
2137c1d88ea5SBen Langmuir     Map.InferredDirectories[Directory].Attrs = Attrs;
2138beee15e7SBen Langmuir     Map.InferredDirectories[Directory].ModuleMapFile = ModuleMapFile;
2139131daca0SRichard Smith     // FIXME: Handle the 'framework' keyword.
21409194a91dSDouglas Gregor   }
214173441091SDouglas Gregor 
214273441091SDouglas Gregor   // Parse the opening brace.
214373441091SDouglas Gregor   if (!Tok.is(MMToken::LBrace)) {
214473441091SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_lbrace_wildcard);
214573441091SDouglas Gregor     HadError = true;
214673441091SDouglas Gregor     return;
214773441091SDouglas Gregor   }
214873441091SDouglas Gregor   SourceLocation LBraceLoc = consumeToken();
214973441091SDouglas Gregor 
215073441091SDouglas Gregor   // Parse the body of the inferred submodule.
215173441091SDouglas Gregor   bool Done = false;
215273441091SDouglas Gregor   do {
215373441091SDouglas Gregor     switch (Tok.Kind) {
215473441091SDouglas Gregor     case MMToken::EndOfFile:
215573441091SDouglas Gregor     case MMToken::RBrace:
215673441091SDouglas Gregor       Done = true;
215773441091SDouglas Gregor       break;
215873441091SDouglas Gregor 
21599194a91dSDouglas Gregor     case MMToken::ExcludeKeyword: {
21609194a91dSDouglas Gregor       if (ActiveModule) {
21619194a91dSDouglas Gregor         Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member)
2162d2d442caSCraig Topper           << (ActiveModule != nullptr);
21639194a91dSDouglas Gregor         consumeToken();
21649194a91dSDouglas Gregor         break;
21659194a91dSDouglas Gregor       }
21669194a91dSDouglas Gregor 
21679194a91dSDouglas Gregor       consumeToken();
2168306d8920SRichard Smith       // FIXME: Support string-literal module names here.
21699194a91dSDouglas Gregor       if (!Tok.is(MMToken::Identifier)) {
21709194a91dSDouglas Gregor         Diags.Report(Tok.getLocation(), diag::err_mmap_missing_exclude_name);
21719194a91dSDouglas Gregor         break;
21729194a91dSDouglas Gregor       }
21739194a91dSDouglas Gregor 
21749194a91dSDouglas Gregor       Map.InferredDirectories[Directory].ExcludedModules
21759194a91dSDouglas Gregor         .push_back(Tok.getString());
21769194a91dSDouglas Gregor       consumeToken();
21779194a91dSDouglas Gregor       break;
21789194a91dSDouglas Gregor     }
21799194a91dSDouglas Gregor 
21809194a91dSDouglas Gregor     case MMToken::ExportKeyword:
21819194a91dSDouglas Gregor       if (!ActiveModule) {
21829194a91dSDouglas Gregor         Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member)
2183d2d442caSCraig Topper           << (ActiveModule != nullptr);
21849194a91dSDouglas Gregor         consumeToken();
21859194a91dSDouglas Gregor         break;
21869194a91dSDouglas Gregor       }
21879194a91dSDouglas Gregor 
218873441091SDouglas Gregor       consumeToken();
218973441091SDouglas Gregor       if (Tok.is(MMToken::Star))
2190dd005f69SDouglas Gregor         ActiveModule->InferExportWildcard = true;
219173441091SDouglas Gregor       else
219273441091SDouglas Gregor         Diags.Report(Tok.getLocation(),
219373441091SDouglas Gregor                      diag::err_mmap_expected_export_wildcard);
219473441091SDouglas Gregor       consumeToken();
219573441091SDouglas Gregor       break;
219673441091SDouglas Gregor 
219773441091SDouglas Gregor     case MMToken::ExplicitKeyword:
219873441091SDouglas Gregor     case MMToken::ModuleKeyword:
219973441091SDouglas Gregor     case MMToken::HeaderKeyword:
2200b53e5483SLawrence Crowl     case MMToken::PrivateKeyword:
220173441091SDouglas Gregor     case MMToken::UmbrellaKeyword:
220273441091SDouglas Gregor     default:
22039194a91dSDouglas Gregor       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member)
2204d2d442caSCraig Topper           << (ActiveModule != nullptr);
220573441091SDouglas Gregor       consumeToken();
220673441091SDouglas Gregor       break;
220773441091SDouglas Gregor     }
220873441091SDouglas Gregor   } while (!Done);
220973441091SDouglas Gregor 
221073441091SDouglas Gregor   if (Tok.is(MMToken::RBrace))
221173441091SDouglas Gregor     consumeToken();
221273441091SDouglas Gregor   else {
221373441091SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
221473441091SDouglas Gregor     Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
221573441091SDouglas Gregor     HadError = true;
221673441091SDouglas Gregor   }
221773441091SDouglas Gregor }
221873441091SDouglas Gregor 
22199194a91dSDouglas Gregor /// \brief Parse optional attributes.
22209194a91dSDouglas Gregor ///
22219194a91dSDouglas Gregor ///   attributes:
22229194a91dSDouglas Gregor ///     attribute attributes
22239194a91dSDouglas Gregor ///     attribute
22249194a91dSDouglas Gregor ///
22259194a91dSDouglas Gregor ///   attribute:
22269194a91dSDouglas Gregor ///     [ identifier ]
22279194a91dSDouglas Gregor ///
22289194a91dSDouglas Gregor /// \param Attrs Will be filled in with the parsed attributes.
22299194a91dSDouglas Gregor ///
22309194a91dSDouglas Gregor /// \returns true if an error occurred, false otherwise.
22314442605fSBill Wendling bool ModuleMapParser::parseOptionalAttributes(Attributes &Attrs) {
22329194a91dSDouglas Gregor   bool HadError = false;
22339194a91dSDouglas Gregor 
22349194a91dSDouglas Gregor   while (Tok.is(MMToken::LSquare)) {
22359194a91dSDouglas Gregor     // Consume the '['.
22369194a91dSDouglas Gregor     SourceLocation LSquareLoc = consumeToken();
22379194a91dSDouglas Gregor 
22389194a91dSDouglas Gregor     // Check whether we have an attribute name here.
22399194a91dSDouglas Gregor     if (!Tok.is(MMToken::Identifier)) {
22409194a91dSDouglas Gregor       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_attribute);
22419194a91dSDouglas Gregor       skipUntil(MMToken::RSquare);
22429194a91dSDouglas Gregor       if (Tok.is(MMToken::RSquare))
22439194a91dSDouglas Gregor         consumeToken();
22449194a91dSDouglas Gregor       HadError = true;
22459194a91dSDouglas Gregor     }
22469194a91dSDouglas Gregor 
22479194a91dSDouglas Gregor     // Decode the attribute name.
22489194a91dSDouglas Gregor     AttributeKind Attribute
22499194a91dSDouglas Gregor       = llvm::StringSwitch<AttributeKind>(Tok.getString())
225035b13eceSDouglas Gregor           .Case("exhaustive", AT_exhaustive)
225177944868SRichard Smith           .Case("extern_c", AT_extern_c)
22529194a91dSDouglas Gregor           .Case("system", AT_system)
22539194a91dSDouglas Gregor           .Default(AT_unknown);
22549194a91dSDouglas Gregor     switch (Attribute) {
22559194a91dSDouglas Gregor     case AT_unknown:
22569194a91dSDouglas Gregor       Diags.Report(Tok.getLocation(), diag::warn_mmap_unknown_attribute)
22579194a91dSDouglas Gregor         << Tok.getString();
22589194a91dSDouglas Gregor       break;
22599194a91dSDouglas Gregor 
22609194a91dSDouglas Gregor     case AT_system:
22619194a91dSDouglas Gregor       Attrs.IsSystem = true;
22629194a91dSDouglas Gregor       break;
226335b13eceSDouglas Gregor 
226477944868SRichard Smith     case AT_extern_c:
226577944868SRichard Smith       Attrs.IsExternC = true;
226677944868SRichard Smith       break;
226777944868SRichard Smith 
226835b13eceSDouglas Gregor     case AT_exhaustive:
226935b13eceSDouglas Gregor       Attrs.IsExhaustive = true;
227035b13eceSDouglas Gregor       break;
22719194a91dSDouglas Gregor     }
22729194a91dSDouglas Gregor     consumeToken();
22739194a91dSDouglas Gregor 
22749194a91dSDouglas Gregor     // Consume the ']'.
22759194a91dSDouglas Gregor     if (!Tok.is(MMToken::RSquare)) {
22769194a91dSDouglas Gregor       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rsquare);
22779194a91dSDouglas Gregor       Diags.Report(LSquareLoc, diag::note_mmap_lsquare_match);
22789194a91dSDouglas Gregor       skipUntil(MMToken::RSquare);
22799194a91dSDouglas Gregor       HadError = true;
22809194a91dSDouglas Gregor     }
22819194a91dSDouglas Gregor 
22829194a91dSDouglas Gregor     if (Tok.is(MMToken::RSquare))
22839194a91dSDouglas Gregor       consumeToken();
22849194a91dSDouglas Gregor   }
22859194a91dSDouglas Gregor 
22869194a91dSDouglas Gregor   return HadError;
22879194a91dSDouglas Gregor }
22889194a91dSDouglas Gregor 
2289718292f2SDouglas Gregor /// \brief Parse a module map file.
2290718292f2SDouglas Gregor ///
2291718292f2SDouglas Gregor ///   module-map-file:
2292718292f2SDouglas Gregor ///     module-declaration*
2293718292f2SDouglas Gregor bool ModuleMapParser::parseModuleMapFile() {
2294718292f2SDouglas Gregor   do {
2295718292f2SDouglas Gregor     switch (Tok.Kind) {
2296718292f2SDouglas Gregor     case MMToken::EndOfFile:
2297718292f2SDouglas Gregor       return HadError;
2298718292f2SDouglas Gregor 
2299e7ab3669SDouglas Gregor     case MMToken::ExplicitKeyword:
230097292843SDaniel Jasper     case MMToken::ExternKeyword:
2301718292f2SDouglas Gregor     case MMToken::ModuleKeyword:
2302755b2055SDouglas Gregor     case MMToken::FrameworkKeyword:
2303718292f2SDouglas Gregor       parseModuleDecl();
2304718292f2SDouglas Gregor       break;
2305718292f2SDouglas Gregor 
23061fb5c3a6SDouglas Gregor     case MMToken::Comma:
230735b13eceSDouglas Gregor     case MMToken::ConfigMacros:
2308fb912657SDouglas Gregor     case MMToken::Conflict:
2309a3feee2aSRichard Smith     case MMToken::Exclaim:
231059527666SDouglas Gregor     case MMToken::ExcludeKeyword:
23112b82c2a5SDouglas Gregor     case MMToken::ExportKeyword:
2312718292f2SDouglas Gregor     case MMToken::HeaderKeyword:
2313718292f2SDouglas Gregor     case MMToken::Identifier:
2314718292f2SDouglas Gregor     case MMToken::LBrace:
23156ddfca91SDouglas Gregor     case MMToken::LinkKeyword:
2316a686e1b0SDouglas Gregor     case MMToken::LSquare:
23172b82c2a5SDouglas Gregor     case MMToken::Period:
2318b53e5483SLawrence Crowl     case MMToken::PrivateKeyword:
2319718292f2SDouglas Gregor     case MMToken::RBrace:
2320a686e1b0SDouglas Gregor     case MMToken::RSquare:
23211fb5c3a6SDouglas Gregor     case MMToken::RequiresKeyword:
23222b82c2a5SDouglas Gregor     case MMToken::Star:
2323718292f2SDouglas Gregor     case MMToken::StringLiteral:
2324b8afebe2SRichard Smith     case MMToken::TextualKeyword:
2325718292f2SDouglas Gregor     case MMToken::UmbrellaKeyword:
2326ba7f2f71SDaniel Jasper     case MMToken::UseKeyword:
2327718292f2SDouglas Gregor       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module);
2328718292f2SDouglas Gregor       HadError = true;
2329718292f2SDouglas Gregor       consumeToken();
2330718292f2SDouglas Gregor       break;
2331718292f2SDouglas Gregor     }
2332718292f2SDouglas Gregor   } while (true);
2333718292f2SDouglas Gregor }
2334718292f2SDouglas Gregor 
23359acb99e3SRichard Smith bool ModuleMap::parseModuleMapFile(const FileEntry *File, bool IsSystem,
23369acb99e3SRichard Smith                                    const DirectoryEntry *Dir) {
23374ddf2221SDouglas Gregor   llvm::DenseMap<const FileEntry *, bool>::iterator Known
23384ddf2221SDouglas Gregor     = ParsedModuleMap.find(File);
23394ddf2221SDouglas Gregor   if (Known != ParsedModuleMap.end())
23404ddf2221SDouglas Gregor     return Known->second;
23414ddf2221SDouglas Gregor 
2342d2d442caSCraig Topper   assert(Target && "Missing target information");
2343cb69b57bSBen Langmuir   auto FileCharacter = IsSystem ? SrcMgr::C_System : SrcMgr::C_User;
2344cb69b57bSBen Langmuir   FileID ID = SourceMgr.createFileID(File, SourceLocation(), FileCharacter);
23451f76c4e8SManuel Klimek   const llvm::MemoryBuffer *Buffer = SourceMgr.getBuffer(ID);
2346718292f2SDouglas Gregor   if (!Buffer)
23474ddf2221SDouglas Gregor     return ParsedModuleMap[File] = true;
2348718292f2SDouglas Gregor 
2349718292f2SDouglas Gregor   // Parse this module map file.
23501f76c4e8SManuel Klimek   Lexer L(ID, SourceMgr.getBuffer(ID), SourceMgr, MMapLangOpts);
2351beee15e7SBen Langmuir   ModuleMapParser Parser(L, SourceMgr, Target, Diags, *this, File, Dir,
2352963c5535SDouglas Gregor                          BuiltinIncludeDir, IsSystem);
2353718292f2SDouglas Gregor   bool Result = Parser.parseModuleMapFile();
23544ddf2221SDouglas Gregor   ParsedModuleMap[File] = Result;
2355718292f2SDouglas Gregor   return Result;
2356718292f2SDouglas Gregor }
2357