1718292f2SDouglas Gregor //===--- ModuleMap.cpp - Describe the layout of modules ---------*- C++ -*-===//
2718292f2SDouglas Gregor //
3718292f2SDouglas Gregor //                     The LLVM Compiler Infrastructure
4718292f2SDouglas Gregor //
5718292f2SDouglas Gregor // This file is distributed under the University of Illinois Open Source
6718292f2SDouglas Gregor // License. See LICENSE.TXT for details.
7718292f2SDouglas Gregor //
8718292f2SDouglas Gregor //===----------------------------------------------------------------------===//
9718292f2SDouglas Gregor //
10718292f2SDouglas Gregor // This file defines the ModuleMap implementation, which describes the layout
11718292f2SDouglas Gregor // of a module as it relates to headers.
12718292f2SDouglas Gregor //
13718292f2SDouglas Gregor //===----------------------------------------------------------------------===//
14718292f2SDouglas Gregor #include "clang/Lex/ModuleMap.h"
15a7d03840SJordan Rose #include "clang/Basic/CharInfo.h"
16718292f2SDouglas Gregor #include "clang/Basic/Diagnostic.h"
17811db4eaSDouglas Gregor #include "clang/Basic/DiagnosticOptions.h"
18718292f2SDouglas Gregor #include "clang/Basic/FileManager.h"
19718292f2SDouglas Gregor #include "clang/Basic/TargetInfo.h"
20718292f2SDouglas Gregor #include "clang/Basic/TargetOptions.h"
21b146baabSArgyrios Kyrtzidis #include "clang/Lex/HeaderSearch.h"
223a02247dSChandler Carruth #include "clang/Lex/LexDiagnostic.h"
233a02247dSChandler Carruth #include "clang/Lex/Lexer.h"
243a02247dSChandler Carruth #include "clang/Lex/LiteralSupport.h"
253a02247dSChandler Carruth #include "llvm/ADT/StringRef.h"
263a02247dSChandler Carruth #include "llvm/ADT/StringSwitch.h"
27718292f2SDouglas Gregor #include "llvm/Support/Allocator.h"
28e89dbc1dSDouglas Gregor #include "llvm/Support/FileSystem.h"
29718292f2SDouglas Gregor #include "llvm/Support/Host.h"
30552c169eSRafael Espindola #include "llvm/Support/Path.h"
31718292f2SDouglas Gregor #include "llvm/Support/raw_ostream.h"
3207c22b78SDouglas Gregor #include <stdlib.h>
3301c7cfa2SDouglas Gregor #if defined(LLVM_ON_UNIX)
34eadae014SDmitri Gribenko #include <limits.h>
3501c7cfa2SDouglas Gregor #endif
36718292f2SDouglas Gregor using namespace clang;
37718292f2SDouglas Gregor 
382b82c2a5SDouglas Gregor Module::ExportDecl
392b82c2a5SDouglas Gregor ModuleMap::resolveExport(Module *Mod,
402b82c2a5SDouglas Gregor                          const Module::UnresolvedExportDecl &Unresolved,
41e4412640SArgyrios Kyrtzidis                          bool Complain) const {
42f5eedd05SDouglas Gregor   // We may have just a wildcard.
43f5eedd05SDouglas Gregor   if (Unresolved.Id.empty()) {
44f5eedd05SDouglas Gregor     assert(Unresolved.Wildcard && "Invalid unresolved export");
45f5eedd05SDouglas Gregor     return Module::ExportDecl(0, true);
46f5eedd05SDouglas Gregor   }
47f5eedd05SDouglas Gregor 
48fb912657SDouglas Gregor   // Resolve the module-id.
49fb912657SDouglas Gregor   Module *Context = resolveModuleId(Unresolved.Id, Mod, Complain);
50fb912657SDouglas Gregor   if (!Context)
51fb912657SDouglas Gregor     return Module::ExportDecl();
52fb912657SDouglas Gregor 
53fb912657SDouglas Gregor   return Module::ExportDecl(Context, Unresolved.Wildcard);
54fb912657SDouglas Gregor }
55fb912657SDouglas Gregor 
56fb912657SDouglas Gregor Module *ModuleMap::resolveModuleId(const ModuleId &Id, Module *Mod,
57fb912657SDouglas Gregor                                    bool Complain) const {
582b82c2a5SDouglas Gregor   // Find the starting module.
59fb912657SDouglas Gregor   Module *Context = lookupModuleUnqualified(Id[0].first, Mod);
602b82c2a5SDouglas Gregor   if (!Context) {
612b82c2a5SDouglas Gregor     if (Complain)
62fb912657SDouglas Gregor       Diags->Report(Id[0].second, diag::err_mmap_missing_module_unqualified)
63fb912657SDouglas Gregor       << Id[0].first << Mod->getFullModuleName();
642b82c2a5SDouglas Gregor 
65fb912657SDouglas Gregor     return 0;
662b82c2a5SDouglas Gregor   }
672b82c2a5SDouglas Gregor 
682b82c2a5SDouglas Gregor   // Dig into the module path.
69fb912657SDouglas Gregor   for (unsigned I = 1, N = Id.size(); I != N; ++I) {
70fb912657SDouglas Gregor     Module *Sub = lookupModuleQualified(Id[I].first, Context);
712b82c2a5SDouglas Gregor     if (!Sub) {
722b82c2a5SDouglas Gregor       if (Complain)
73fb912657SDouglas Gregor         Diags->Report(Id[I].second, diag::err_mmap_missing_module_qualified)
74fb912657SDouglas Gregor         << Id[I].first << Context->getFullModuleName()
75fb912657SDouglas Gregor         << SourceRange(Id[0].second, Id[I-1].second);
762b82c2a5SDouglas Gregor 
77fb912657SDouglas Gregor       return 0;
782b82c2a5SDouglas Gregor     }
792b82c2a5SDouglas Gregor 
802b82c2a5SDouglas Gregor     Context = Sub;
812b82c2a5SDouglas Gregor   }
822b82c2a5SDouglas Gregor 
83fb912657SDouglas Gregor   return Context;
842b82c2a5SDouglas Gregor }
852b82c2a5SDouglas Gregor 
866b930967SDouglas Gregor ModuleMap::ModuleMap(FileManager &FileMgr, DiagnosticConsumer &DC,
87b146baabSArgyrios Kyrtzidis                      const LangOptions &LangOpts, const TargetInfo *Target,
88b146baabSArgyrios Kyrtzidis                      HeaderSearch &HeaderInfo)
89b146baabSArgyrios Kyrtzidis   : LangOpts(LangOpts), Target(Target), HeaderInfo(HeaderInfo),
906f722b4eSArgyrios Kyrtzidis     BuiltinIncludeDir(0), CompilingModule(0)
911fb5c3a6SDouglas Gregor {
92c95d8192SDylan Noblesmith   IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(new DiagnosticIDs);
93c95d8192SDylan Noblesmith   Diags = IntrusiveRefCntPtr<DiagnosticsEngine>(
94811db4eaSDouglas Gregor             new DiagnosticsEngine(DiagIDs, new DiagnosticOptions));
956b930967SDouglas Gregor   Diags->setClient(new ForwardingDiagnosticConsumer(DC),
966b930967SDouglas Gregor                    /*ShouldOwnClient=*/true);
97718292f2SDouglas Gregor   SourceMgr = new SourceManager(*Diags, FileMgr);
98718292f2SDouglas Gregor }
99718292f2SDouglas Gregor 
100718292f2SDouglas Gregor ModuleMap::~ModuleMap() {
1015acdf59eSDouglas Gregor   for (llvm::StringMap<Module *>::iterator I = Modules.begin(),
1025acdf59eSDouglas Gregor                                         IEnd = Modules.end();
1035acdf59eSDouglas Gregor        I != IEnd; ++I) {
1045acdf59eSDouglas Gregor     delete I->getValue();
1055acdf59eSDouglas Gregor   }
1065acdf59eSDouglas Gregor 
107718292f2SDouglas Gregor   delete SourceMgr;
108718292f2SDouglas Gregor }
109718292f2SDouglas Gregor 
11089929282SDouglas Gregor void ModuleMap::setTarget(const TargetInfo &Target) {
11189929282SDouglas Gregor   assert((!this->Target || this->Target == &Target) &&
11289929282SDouglas Gregor          "Improper target override");
11389929282SDouglas Gregor   this->Target = &Target;
11489929282SDouglas Gregor }
11589929282SDouglas Gregor 
116056396aeSDouglas Gregor /// \brief "Sanitize" a filename so that it can be used as an identifier.
117056396aeSDouglas Gregor static StringRef sanitizeFilenameAsIdentifier(StringRef Name,
118056396aeSDouglas Gregor                                               SmallVectorImpl<char> &Buffer) {
119056396aeSDouglas Gregor   if (Name.empty())
120056396aeSDouglas Gregor     return Name;
121056396aeSDouglas Gregor 
122a7d03840SJordan Rose   if (!isValidIdentifier(Name)) {
123056396aeSDouglas Gregor     // If we don't already have something with the form of an identifier,
124056396aeSDouglas Gregor     // create a buffer with the sanitized name.
125056396aeSDouglas Gregor     Buffer.clear();
126a7d03840SJordan Rose     if (isDigit(Name[0]))
127056396aeSDouglas Gregor       Buffer.push_back('_');
128056396aeSDouglas Gregor     Buffer.reserve(Buffer.size() + Name.size());
129056396aeSDouglas Gregor     for (unsigned I = 0, N = Name.size(); I != N; ++I) {
130a7d03840SJordan Rose       if (isIdentifierBody(Name[I]))
131056396aeSDouglas Gregor         Buffer.push_back(Name[I]);
132056396aeSDouglas Gregor       else
133056396aeSDouglas Gregor         Buffer.push_back('_');
134056396aeSDouglas Gregor     }
135056396aeSDouglas Gregor 
136056396aeSDouglas Gregor     Name = StringRef(Buffer.data(), Buffer.size());
137056396aeSDouglas Gregor   }
138056396aeSDouglas Gregor 
139056396aeSDouglas Gregor   while (llvm::StringSwitch<bool>(Name)
140056396aeSDouglas Gregor #define KEYWORD(Keyword,Conditions) .Case(#Keyword, true)
141056396aeSDouglas Gregor #define ALIAS(Keyword, AliasOf, Conditions) .Case(Keyword, true)
142056396aeSDouglas Gregor #include "clang/Basic/TokenKinds.def"
143056396aeSDouglas Gregor            .Default(false)) {
144056396aeSDouglas Gregor     if (Name.data() != Buffer.data())
145056396aeSDouglas Gregor       Buffer.append(Name.begin(), Name.end());
146056396aeSDouglas Gregor     Buffer.push_back('_');
147056396aeSDouglas Gregor     Name = StringRef(Buffer.data(), Buffer.size());
148056396aeSDouglas Gregor   }
149056396aeSDouglas Gregor 
150056396aeSDouglas Gregor   return Name;
151056396aeSDouglas Gregor }
152056396aeSDouglas Gregor 
15334d52749SDouglas Gregor /// \brief Determine whether the given file name is the name of a builtin
15434d52749SDouglas Gregor /// header, supplied by Clang to replace, override, or augment existing system
15534d52749SDouglas Gregor /// headers.
15634d52749SDouglas Gregor static bool isBuiltinHeader(StringRef FileName) {
15734d52749SDouglas Gregor   return llvm::StringSwitch<bool>(FileName)
15834d52749SDouglas Gregor            .Case("float.h", true)
15934d52749SDouglas Gregor            .Case("iso646.h", true)
16034d52749SDouglas Gregor            .Case("limits.h", true)
16134d52749SDouglas Gregor            .Case("stdalign.h", true)
16234d52749SDouglas Gregor            .Case("stdarg.h", true)
16334d52749SDouglas Gregor            .Case("stdbool.h", true)
16434d52749SDouglas Gregor            .Case("stddef.h", true)
16534d52749SDouglas Gregor            .Case("stdint.h", true)
16634d52749SDouglas Gregor            .Case("tgmath.h", true)
16734d52749SDouglas Gregor            .Case("unwind.h", true)
16834d52749SDouglas Gregor            .Default(false);
16934d52749SDouglas Gregor }
17034d52749SDouglas Gregor 
171b53e5483SLawrence Crowl ModuleMap::KnownHeader ModuleMap::findModuleForHeader(const FileEntry *File) {
17259527666SDouglas Gregor   HeadersMap::iterator Known = Headers.find(File);
1731fb5c3a6SDouglas Gregor   if (Known != Headers.end()) {
17459527666SDouglas Gregor     // If a header is not available, don't report that it maps to anything.
17559527666SDouglas Gregor     if (!Known->second.isAvailable())
176b53e5483SLawrence Crowl       return KnownHeader();
1771fb5c3a6SDouglas Gregor 
178b53e5483SLawrence Crowl     return Known->second;
1791fb5c3a6SDouglas Gregor   }
180ab0c8a84SDouglas Gregor 
18134d52749SDouglas Gregor   // If we've found a builtin header within Clang's builtin include directory,
18234d52749SDouglas Gregor   // load all of the module maps to see if it will get associated with a
18334d52749SDouglas Gregor   // specific module (e.g., in /usr/include).
18434d52749SDouglas Gregor   if (File->getDir() == BuiltinIncludeDir &&
18534d52749SDouglas Gregor       isBuiltinHeader(llvm::sys::path::filename(File->getName()))) {
18664a1fa5cSDouglas Gregor     HeaderInfo.loadTopLevelSystemModules();
18734d52749SDouglas Gregor 
18834d52749SDouglas Gregor     // Check again.
18934d52749SDouglas Gregor     Known = Headers.find(File);
19034d52749SDouglas Gregor     if (Known != Headers.end()) {
19134d52749SDouglas Gregor       // If a header is not available, don't report that it maps to anything.
19234d52749SDouglas Gregor       if (!Known->second.isAvailable())
193b53e5483SLawrence Crowl         return KnownHeader();
19434d52749SDouglas Gregor 
195b53e5483SLawrence Crowl       return Known->second;
19634d52749SDouglas Gregor     }
19734d52749SDouglas Gregor   }
19834d52749SDouglas Gregor 
199b65dbfffSDouglas Gregor   const DirectoryEntry *Dir = File->getDir();
200f857950dSDmitri Gribenko   SmallVector<const DirectoryEntry *, 2> SkippedDirs;
201e00c8b20SDouglas Gregor 
20274260502SDouglas Gregor   // Note: as an egregious but useful hack we use the real path here, because
20374260502SDouglas Gregor   // frameworks moving from top-level frameworks to embedded frameworks tend
20474260502SDouglas Gregor   // to be symlinked from the top-level location to the embedded location,
20574260502SDouglas Gregor   // and we need to resolve lookups as if we had found the embedded location.
206e00c8b20SDouglas Gregor   StringRef DirName = SourceMgr->getFileManager().getCanonicalName(Dir);
207a89c5ac4SDouglas Gregor 
208a89c5ac4SDouglas Gregor   // Keep walking up the directory hierarchy, looking for a directory with
209a89c5ac4SDouglas Gregor   // an umbrella header.
210b65dbfffSDouglas Gregor   do {
211a89c5ac4SDouglas Gregor     llvm::DenseMap<const DirectoryEntry *, Module *>::iterator KnownDir
212a89c5ac4SDouglas Gregor       = UmbrellaDirs.find(Dir);
213a89c5ac4SDouglas Gregor     if (KnownDir != UmbrellaDirs.end()) {
214a89c5ac4SDouglas Gregor       Module *Result = KnownDir->second;
215930a85ccSDouglas Gregor 
216930a85ccSDouglas Gregor       // Search up the module stack until we find a module with an umbrella
21773141fa9SDouglas Gregor       // directory.
218930a85ccSDouglas Gregor       Module *UmbrellaModule = Result;
21973141fa9SDouglas Gregor       while (!UmbrellaModule->getUmbrellaDir() && UmbrellaModule->Parent)
220930a85ccSDouglas Gregor         UmbrellaModule = UmbrellaModule->Parent;
221930a85ccSDouglas Gregor 
222930a85ccSDouglas Gregor       if (UmbrellaModule->InferSubmodules) {
223a89c5ac4SDouglas Gregor         // Infer submodules for each of the directories we found between
224a89c5ac4SDouglas Gregor         // the directory of the umbrella header and the directory where
225a89c5ac4SDouglas Gregor         // the actual header is located.
2269458f82dSDouglas Gregor         bool Explicit = UmbrellaModule->InferExplicitSubmodules;
2279458f82dSDouglas Gregor 
2287033127bSDouglas Gregor         for (unsigned I = SkippedDirs.size(); I != 0; --I) {
229a89c5ac4SDouglas Gregor           // Find or create the module that corresponds to this directory name.
230056396aeSDouglas Gregor           SmallString<32> NameBuf;
231056396aeSDouglas Gregor           StringRef Name = sanitizeFilenameAsIdentifier(
232056396aeSDouglas Gregor                              llvm::sys::path::stem(SkippedDirs[I-1]->getName()),
233056396aeSDouglas Gregor                              NameBuf);
234a89c5ac4SDouglas Gregor           Result = findOrCreateModule(Name, Result, /*IsFramework=*/false,
2359458f82dSDouglas Gregor                                       Explicit).first;
236a89c5ac4SDouglas Gregor 
237a89c5ac4SDouglas Gregor           // Associate the module and the directory.
238a89c5ac4SDouglas Gregor           UmbrellaDirs[SkippedDirs[I-1]] = Result;
239a89c5ac4SDouglas Gregor 
240a89c5ac4SDouglas Gregor           // If inferred submodules export everything they import, add a
241a89c5ac4SDouglas Gregor           // wildcard to the set of exports.
242930a85ccSDouglas Gregor           if (UmbrellaModule->InferExportWildcard && Result->Exports.empty())
243a89c5ac4SDouglas Gregor             Result->Exports.push_back(Module::ExportDecl(0, true));
244a89c5ac4SDouglas Gregor         }
245a89c5ac4SDouglas Gregor 
246a89c5ac4SDouglas Gregor         // Infer a submodule with the same name as this header file.
247056396aeSDouglas Gregor         SmallString<32> NameBuf;
248056396aeSDouglas Gregor         StringRef Name = sanitizeFilenameAsIdentifier(
249056396aeSDouglas Gregor                            llvm::sys::path::stem(File->getName()), NameBuf);
250a89c5ac4SDouglas Gregor         Result = findOrCreateModule(Name, Result, /*IsFramework=*/false,
2519458f82dSDouglas Gregor                                     Explicit).first;
2523c5305c1SArgyrios Kyrtzidis         Result->addTopHeader(File);
253a89c5ac4SDouglas Gregor 
254a89c5ac4SDouglas Gregor         // If inferred submodules export everything they import, add a
255a89c5ac4SDouglas Gregor         // wildcard to the set of exports.
256930a85ccSDouglas Gregor         if (UmbrellaModule->InferExportWildcard && Result->Exports.empty())
257a89c5ac4SDouglas Gregor           Result->Exports.push_back(Module::ExportDecl(0, true));
258a89c5ac4SDouglas Gregor       } else {
259a89c5ac4SDouglas Gregor         // Record each of the directories we stepped through as being part of
260a89c5ac4SDouglas Gregor         // the module we found, since the umbrella header covers them all.
261a89c5ac4SDouglas Gregor         for (unsigned I = 0, N = SkippedDirs.size(); I != N; ++I)
262a89c5ac4SDouglas Gregor           UmbrellaDirs[SkippedDirs[I]] = Result;
263a89c5ac4SDouglas Gregor       }
264a89c5ac4SDouglas Gregor 
265b53e5483SLawrence Crowl       Headers[File] = KnownHeader(Result, NormalHeader);
2661fb5c3a6SDouglas Gregor 
2671fb5c3a6SDouglas Gregor       // If a header corresponds to an unavailable module, don't report
2681fb5c3a6SDouglas Gregor       // that it maps to anything.
2691fb5c3a6SDouglas Gregor       if (!Result->isAvailable())
270b53e5483SLawrence Crowl         return KnownHeader();
2711fb5c3a6SDouglas Gregor 
272b53e5483SLawrence Crowl       return Headers[File];
273a89c5ac4SDouglas Gregor     }
274a89c5ac4SDouglas Gregor 
275a89c5ac4SDouglas Gregor     SkippedDirs.push_back(Dir);
276a89c5ac4SDouglas Gregor 
277b65dbfffSDouglas Gregor     // Retrieve our parent path.
278b65dbfffSDouglas Gregor     DirName = llvm::sys::path::parent_path(DirName);
279b65dbfffSDouglas Gregor     if (DirName.empty())
280b65dbfffSDouglas Gregor       break;
281b65dbfffSDouglas Gregor 
282b65dbfffSDouglas Gregor     // Resolve the parent path to a directory entry.
283b65dbfffSDouglas Gregor     Dir = SourceMgr->getFileManager().getDirectory(DirName);
284a89c5ac4SDouglas Gregor   } while (Dir);
285b65dbfffSDouglas Gregor 
286b53e5483SLawrence Crowl   return KnownHeader();
287ab0c8a84SDouglas Gregor }
288ab0c8a84SDouglas Gregor 
289e4412640SArgyrios Kyrtzidis bool ModuleMap::isHeaderInUnavailableModule(const FileEntry *Header) const {
290e4412640SArgyrios Kyrtzidis   HeadersMap::const_iterator Known = Headers.find(Header);
2911fb5c3a6SDouglas Gregor   if (Known != Headers.end())
29259527666SDouglas Gregor     return !Known->second.isAvailable();
2931fb5c3a6SDouglas Gregor 
2941fb5c3a6SDouglas Gregor   const DirectoryEntry *Dir = Header->getDir();
295f857950dSDmitri Gribenko   SmallVector<const DirectoryEntry *, 2> SkippedDirs;
2961fb5c3a6SDouglas Gregor   StringRef DirName = Dir->getName();
2971fb5c3a6SDouglas Gregor 
2981fb5c3a6SDouglas Gregor   // Keep walking up the directory hierarchy, looking for a directory with
2991fb5c3a6SDouglas Gregor   // an umbrella header.
3001fb5c3a6SDouglas Gregor   do {
301e4412640SArgyrios Kyrtzidis     llvm::DenseMap<const DirectoryEntry *, Module *>::const_iterator KnownDir
3021fb5c3a6SDouglas Gregor       = UmbrellaDirs.find(Dir);
3031fb5c3a6SDouglas Gregor     if (KnownDir != UmbrellaDirs.end()) {
3041fb5c3a6SDouglas Gregor       Module *Found = KnownDir->second;
3051fb5c3a6SDouglas Gregor       if (!Found->isAvailable())
3061fb5c3a6SDouglas Gregor         return true;
3071fb5c3a6SDouglas Gregor 
3081fb5c3a6SDouglas Gregor       // Search up the module stack until we find a module with an umbrella
3091fb5c3a6SDouglas Gregor       // directory.
3101fb5c3a6SDouglas Gregor       Module *UmbrellaModule = Found;
3111fb5c3a6SDouglas Gregor       while (!UmbrellaModule->getUmbrellaDir() && UmbrellaModule->Parent)
3121fb5c3a6SDouglas Gregor         UmbrellaModule = UmbrellaModule->Parent;
3131fb5c3a6SDouglas Gregor 
3141fb5c3a6SDouglas Gregor       if (UmbrellaModule->InferSubmodules) {
3151fb5c3a6SDouglas Gregor         for (unsigned I = SkippedDirs.size(); I != 0; --I) {
3161fb5c3a6SDouglas Gregor           // Find or create the module that corresponds to this directory name.
317056396aeSDouglas Gregor           SmallString<32> NameBuf;
318056396aeSDouglas Gregor           StringRef Name = sanitizeFilenameAsIdentifier(
319056396aeSDouglas Gregor                              llvm::sys::path::stem(SkippedDirs[I-1]->getName()),
320056396aeSDouglas Gregor                              NameBuf);
3211fb5c3a6SDouglas Gregor           Found = lookupModuleQualified(Name, Found);
3221fb5c3a6SDouglas Gregor           if (!Found)
3231fb5c3a6SDouglas Gregor             return false;
3241fb5c3a6SDouglas Gregor           if (!Found->isAvailable())
3251fb5c3a6SDouglas Gregor             return true;
3261fb5c3a6SDouglas Gregor         }
3271fb5c3a6SDouglas Gregor 
3281fb5c3a6SDouglas Gregor         // Infer a submodule with the same name as this header file.
329056396aeSDouglas Gregor         SmallString<32> NameBuf;
330056396aeSDouglas Gregor         StringRef Name = sanitizeFilenameAsIdentifier(
331056396aeSDouglas Gregor                            llvm::sys::path::stem(Header->getName()),
332056396aeSDouglas Gregor                            NameBuf);
3331fb5c3a6SDouglas Gregor         Found = lookupModuleQualified(Name, Found);
3341fb5c3a6SDouglas Gregor         if (!Found)
3351fb5c3a6SDouglas Gregor           return false;
3361fb5c3a6SDouglas Gregor       }
3371fb5c3a6SDouglas Gregor 
3381fb5c3a6SDouglas Gregor       return !Found->isAvailable();
3391fb5c3a6SDouglas Gregor     }
3401fb5c3a6SDouglas Gregor 
3411fb5c3a6SDouglas Gregor     SkippedDirs.push_back(Dir);
3421fb5c3a6SDouglas Gregor 
3431fb5c3a6SDouglas Gregor     // Retrieve our parent path.
3441fb5c3a6SDouglas Gregor     DirName = llvm::sys::path::parent_path(DirName);
3451fb5c3a6SDouglas Gregor     if (DirName.empty())
3461fb5c3a6SDouglas Gregor       break;
3471fb5c3a6SDouglas Gregor 
3481fb5c3a6SDouglas Gregor     // Resolve the parent path to a directory entry.
3491fb5c3a6SDouglas Gregor     Dir = SourceMgr->getFileManager().getDirectory(DirName);
3501fb5c3a6SDouglas Gregor   } while (Dir);
3511fb5c3a6SDouglas Gregor 
3521fb5c3a6SDouglas Gregor   return false;
3531fb5c3a6SDouglas Gregor }
3541fb5c3a6SDouglas Gregor 
355e4412640SArgyrios Kyrtzidis Module *ModuleMap::findModule(StringRef Name) const {
356e4412640SArgyrios Kyrtzidis   llvm::StringMap<Module *>::const_iterator Known = Modules.find(Name);
35788bdfb0eSDouglas Gregor   if (Known != Modules.end())
35888bdfb0eSDouglas Gregor     return Known->getValue();
35988bdfb0eSDouglas Gregor 
36088bdfb0eSDouglas Gregor   return 0;
36188bdfb0eSDouglas Gregor }
36288bdfb0eSDouglas Gregor 
363e4412640SArgyrios Kyrtzidis Module *ModuleMap::lookupModuleUnqualified(StringRef Name,
364e4412640SArgyrios Kyrtzidis                                            Module *Context) const {
3652b82c2a5SDouglas Gregor   for(; Context; Context = Context->Parent) {
3662b82c2a5SDouglas Gregor     if (Module *Sub = lookupModuleQualified(Name, Context))
3672b82c2a5SDouglas Gregor       return Sub;
3682b82c2a5SDouglas Gregor   }
3692b82c2a5SDouglas Gregor 
3702b82c2a5SDouglas Gregor   return findModule(Name);
3712b82c2a5SDouglas Gregor }
3722b82c2a5SDouglas Gregor 
373e4412640SArgyrios Kyrtzidis Module *ModuleMap::lookupModuleQualified(StringRef Name, Module *Context) const{
3742b82c2a5SDouglas Gregor   if (!Context)
3752b82c2a5SDouglas Gregor     return findModule(Name);
3762b82c2a5SDouglas Gregor 
377eb90e830SDouglas Gregor   return Context->findSubmodule(Name);
3782b82c2a5SDouglas Gregor }
3792b82c2a5SDouglas Gregor 
380de3ef502SDouglas Gregor std::pair<Module *, bool>
38169021974SDouglas Gregor ModuleMap::findOrCreateModule(StringRef Name, Module *Parent, bool IsFramework,
38269021974SDouglas Gregor                               bool IsExplicit) {
38369021974SDouglas Gregor   // Try to find an existing module with this name.
384eb90e830SDouglas Gregor   if (Module *Sub = lookupModuleQualified(Name, Parent))
385eb90e830SDouglas Gregor     return std::make_pair(Sub, false);
38669021974SDouglas Gregor 
38769021974SDouglas Gregor   // Create a new module with this name.
38869021974SDouglas Gregor   Module *Result = new Module(Name, SourceLocation(), Parent, IsFramework,
38969021974SDouglas Gregor                               IsExplicit);
3906f722b4eSArgyrios Kyrtzidis   if (!Parent) {
39169021974SDouglas Gregor     Modules[Name] = Result;
3926f722b4eSArgyrios Kyrtzidis     if (!LangOpts.CurrentModule.empty() && !CompilingModule &&
3936f722b4eSArgyrios Kyrtzidis         Name == LangOpts.CurrentModule) {
3946f722b4eSArgyrios Kyrtzidis       CompilingModule = Result;
3956f722b4eSArgyrios Kyrtzidis     }
3966f722b4eSArgyrios Kyrtzidis   }
39769021974SDouglas Gregor   return std::make_pair(Result, true);
39869021974SDouglas Gregor }
39969021974SDouglas Gregor 
4009194a91dSDouglas Gregor bool ModuleMap::canInferFrameworkModule(const DirectoryEntry *ParentDir,
401e4412640SArgyrios Kyrtzidis                                         StringRef Name, bool &IsSystem) const {
4029194a91dSDouglas Gregor   // Check whether we have already looked into the parent directory
4039194a91dSDouglas Gregor   // for a module map.
404e4412640SArgyrios Kyrtzidis   llvm::DenseMap<const DirectoryEntry *, InferredDirectory>::const_iterator
4059194a91dSDouglas Gregor     inferred = InferredDirectories.find(ParentDir);
4069194a91dSDouglas Gregor   if (inferred == InferredDirectories.end())
4079194a91dSDouglas Gregor     return false;
4089194a91dSDouglas Gregor 
4099194a91dSDouglas Gregor   if (!inferred->second.InferModules)
4109194a91dSDouglas Gregor     return false;
4119194a91dSDouglas Gregor 
4129194a91dSDouglas Gregor   // We're allowed to infer for this directory, but make sure it's okay
4139194a91dSDouglas Gregor   // to infer this particular module.
4149194a91dSDouglas Gregor   bool canInfer = std::find(inferred->second.ExcludedModules.begin(),
4159194a91dSDouglas Gregor                             inferred->second.ExcludedModules.end(),
4169194a91dSDouglas Gregor                             Name) == inferred->second.ExcludedModules.end();
4179194a91dSDouglas Gregor 
4189194a91dSDouglas Gregor   if (canInfer && inferred->second.InferSystemModules)
4199194a91dSDouglas Gregor     IsSystem = true;
4209194a91dSDouglas Gregor 
4219194a91dSDouglas Gregor   return canInfer;
4229194a91dSDouglas Gregor }
4239194a91dSDouglas Gregor 
42411dfe6feSDouglas Gregor /// \brief For a framework module, infer the framework against which we
42511dfe6feSDouglas Gregor /// should link.
42611dfe6feSDouglas Gregor static void inferFrameworkLink(Module *Mod, const DirectoryEntry *FrameworkDir,
42711dfe6feSDouglas Gregor                                FileManager &FileMgr) {
42811dfe6feSDouglas Gregor   assert(Mod->IsFramework && "Can only infer linking for framework modules");
42911dfe6feSDouglas Gregor   assert(!Mod->isSubFramework() &&
43011dfe6feSDouglas Gregor          "Can only infer linking for top-level frameworks");
43111dfe6feSDouglas Gregor 
43211dfe6feSDouglas Gregor   SmallString<128> LibName;
43311dfe6feSDouglas Gregor   LibName += FrameworkDir->getName();
43411dfe6feSDouglas Gregor   llvm::sys::path::append(LibName, Mod->Name);
43511dfe6feSDouglas Gregor   if (FileMgr.getFile(LibName)) {
43611dfe6feSDouglas Gregor     Mod->LinkLibraries.push_back(Module::LinkLibrary(Mod->Name,
43711dfe6feSDouglas Gregor                                                      /*IsFramework=*/true));
43811dfe6feSDouglas Gregor   }
43911dfe6feSDouglas Gregor }
44011dfe6feSDouglas Gregor 
441de3ef502SDouglas Gregor Module *
44256c64013SDouglas Gregor ModuleMap::inferFrameworkModule(StringRef ModuleName,
443e89dbc1dSDouglas Gregor                                 const DirectoryEntry *FrameworkDir,
444a686e1b0SDouglas Gregor                                 bool IsSystem,
445e89dbc1dSDouglas Gregor                                 Module *Parent) {
44656c64013SDouglas Gregor   // Check whether we've already found this module.
447e89dbc1dSDouglas Gregor   if (Module *Mod = lookupModuleQualified(ModuleName, Parent))
448e89dbc1dSDouglas Gregor     return Mod;
449e89dbc1dSDouglas Gregor 
450e89dbc1dSDouglas Gregor   FileManager &FileMgr = SourceMgr->getFileManager();
45156c64013SDouglas Gregor 
4529194a91dSDouglas Gregor   // If the framework has a parent path from which we're allowed to infer
4539194a91dSDouglas Gregor   // a framework module, do so.
4549194a91dSDouglas Gregor   if (!Parent) {
4554ddf2221SDouglas Gregor     // Determine whether we're allowed to infer a module map.
456e00c8b20SDouglas Gregor 
4574ddf2221SDouglas Gregor     // Note: as an egregious but useful hack we use the real path here, because
4584ddf2221SDouglas Gregor     // we might be looking at an embedded framework that symlinks out to a
4594ddf2221SDouglas Gregor     // top-level framework, and we need to infer as if we were naming the
4604ddf2221SDouglas Gregor     // top-level framework.
461e00c8b20SDouglas Gregor     StringRef FrameworkDirName
462e00c8b20SDouglas Gregor       = SourceMgr->getFileManager().getCanonicalName(FrameworkDir);
4634ddf2221SDouglas Gregor 
4649194a91dSDouglas Gregor     bool canInfer = false;
4654ddf2221SDouglas Gregor     if (llvm::sys::path::has_parent_path(FrameworkDirName)) {
4669194a91dSDouglas Gregor       // Figure out the parent path.
4674ddf2221SDouglas Gregor       StringRef Parent = llvm::sys::path::parent_path(FrameworkDirName);
4689194a91dSDouglas Gregor       if (const DirectoryEntry *ParentDir = FileMgr.getDirectory(Parent)) {
4699194a91dSDouglas Gregor         // Check whether we have already looked into the parent directory
4709194a91dSDouglas Gregor         // for a module map.
471e4412640SArgyrios Kyrtzidis         llvm::DenseMap<const DirectoryEntry *, InferredDirectory>::const_iterator
4729194a91dSDouglas Gregor           inferred = InferredDirectories.find(ParentDir);
4739194a91dSDouglas Gregor         if (inferred == InferredDirectories.end()) {
4749194a91dSDouglas Gregor           // We haven't looked here before. Load a module map, if there is
4759194a91dSDouglas Gregor           // one.
4769194a91dSDouglas Gregor           SmallString<128> ModMapPath = Parent;
4779194a91dSDouglas Gregor           llvm::sys::path::append(ModMapPath, "module.map");
4789194a91dSDouglas Gregor           if (const FileEntry *ModMapFile = FileMgr.getFile(ModMapPath)) {
479963c5535SDouglas Gregor             parseModuleMapFile(ModMapFile, IsSystem);
4809194a91dSDouglas Gregor             inferred = InferredDirectories.find(ParentDir);
4819194a91dSDouglas Gregor           }
4829194a91dSDouglas Gregor 
4839194a91dSDouglas Gregor           if (inferred == InferredDirectories.end())
4849194a91dSDouglas Gregor             inferred = InferredDirectories.insert(
4859194a91dSDouglas Gregor                          std::make_pair(ParentDir, InferredDirectory())).first;
4869194a91dSDouglas Gregor         }
4879194a91dSDouglas Gregor 
4889194a91dSDouglas Gregor         if (inferred->second.InferModules) {
4899194a91dSDouglas Gregor           // We're allowed to infer for this directory, but make sure it's okay
4909194a91dSDouglas Gregor           // to infer this particular module.
4914ddf2221SDouglas Gregor           StringRef Name = llvm::sys::path::stem(FrameworkDirName);
4929194a91dSDouglas Gregor           canInfer = std::find(inferred->second.ExcludedModules.begin(),
4939194a91dSDouglas Gregor                                inferred->second.ExcludedModules.end(),
4949194a91dSDouglas Gregor                                Name) == inferred->second.ExcludedModules.end();
4959194a91dSDouglas Gregor 
4969194a91dSDouglas Gregor           if (inferred->second.InferSystemModules)
4979194a91dSDouglas Gregor             IsSystem = true;
4989194a91dSDouglas Gregor         }
4999194a91dSDouglas Gregor       }
5009194a91dSDouglas Gregor     }
5019194a91dSDouglas Gregor 
5029194a91dSDouglas Gregor     // If we're not allowed to infer a framework module, don't.
5039194a91dSDouglas Gregor     if (!canInfer)
5049194a91dSDouglas Gregor       return 0;
5059194a91dSDouglas Gregor   }
5069194a91dSDouglas Gregor 
5079194a91dSDouglas Gregor 
50856c64013SDouglas Gregor   // Look for an umbrella header.
5092c1dd271SDylan Noblesmith   SmallString<128> UmbrellaName = StringRef(FrameworkDir->getName());
51017381a06SBenjamin Kramer   llvm::sys::path::append(UmbrellaName, "Headers", ModuleName + ".h");
511e89dbc1dSDouglas Gregor   const FileEntry *UmbrellaHeader = FileMgr.getFile(UmbrellaName);
51256c64013SDouglas Gregor 
51356c64013SDouglas Gregor   // FIXME: If there's no umbrella header, we could probably scan the
51456c64013SDouglas Gregor   // framework to load *everything*. But, it's not clear that this is a good
51556c64013SDouglas Gregor   // idea.
51656c64013SDouglas Gregor   if (!UmbrellaHeader)
51756c64013SDouglas Gregor     return 0;
51856c64013SDouglas Gregor 
519e89dbc1dSDouglas Gregor   Module *Result = new Module(ModuleName, SourceLocation(), Parent,
520e89dbc1dSDouglas Gregor                               /*IsFramework=*/true, /*IsExplicit=*/false);
521a686e1b0SDouglas Gregor   if (IsSystem)
522a686e1b0SDouglas Gregor     Result->IsSystem = IsSystem;
523a686e1b0SDouglas Gregor 
524eb90e830SDouglas Gregor   if (!Parent)
525e89dbc1dSDouglas Gregor     Modules[ModuleName] = Result;
526e89dbc1dSDouglas Gregor 
527322f633cSDouglas Gregor   // umbrella header "umbrella-header-name"
52873141fa9SDouglas Gregor   Result->Umbrella = UmbrellaHeader;
529b53e5483SLawrence Crowl   Headers[UmbrellaHeader] = KnownHeader(Result, NormalHeader);
5304dc71835SDouglas Gregor   UmbrellaDirs[UmbrellaHeader->getDir()] = Result;
531d8bd7537SDouglas Gregor 
532d8bd7537SDouglas Gregor   // export *
533d8bd7537SDouglas Gregor   Result->Exports.push_back(Module::ExportDecl(0, true));
534d8bd7537SDouglas Gregor 
535a89c5ac4SDouglas Gregor   // module * { export * }
536a89c5ac4SDouglas Gregor   Result->InferSubmodules = true;
537a89c5ac4SDouglas Gregor   Result->InferExportWildcard = true;
538a89c5ac4SDouglas Gregor 
539e89dbc1dSDouglas Gregor   // Look for subframeworks.
540e89dbc1dSDouglas Gregor   llvm::error_code EC;
5412c1dd271SDylan Noblesmith   SmallString<128> SubframeworksDirName
542ddaa69cbSDouglas Gregor     = StringRef(FrameworkDir->getName());
543e89dbc1dSDouglas Gregor   llvm::sys::path::append(SubframeworksDirName, "Frameworks");
544*2d4d8cb3SBenjamin Kramer   llvm::sys::path::native(SubframeworksDirName);
545ddaa69cbSDouglas Gregor   for (llvm::sys::fs::directory_iterator
546*2d4d8cb3SBenjamin Kramer          Dir(SubframeworksDirName.str(), EC), DirEnd;
547e89dbc1dSDouglas Gregor        Dir != DirEnd && !EC; Dir.increment(EC)) {
548e89dbc1dSDouglas Gregor     if (!StringRef(Dir->path()).endswith(".framework"))
549e89dbc1dSDouglas Gregor       continue;
550f2161a70SDouglas Gregor 
551e89dbc1dSDouglas Gregor     if (const DirectoryEntry *SubframeworkDir
552e89dbc1dSDouglas Gregor           = FileMgr.getDirectory(Dir->path())) {
55307c22b78SDouglas Gregor       // Note: as an egregious but useful hack, we use the real path here and
55407c22b78SDouglas Gregor       // check whether it is actually a subdirectory of the parent directory.
55507c22b78SDouglas Gregor       // This will not be the case if the 'subframework' is actually a symlink
55607c22b78SDouglas Gregor       // out to a top-level framework.
557e00c8b20SDouglas Gregor       StringRef SubframeworkDirName = FileMgr.getCanonicalName(SubframeworkDir);
55807c22b78SDouglas Gregor       bool FoundParent = false;
55907c22b78SDouglas Gregor       do {
56007c22b78SDouglas Gregor         // Get the parent directory name.
56107c22b78SDouglas Gregor         SubframeworkDirName
56207c22b78SDouglas Gregor           = llvm::sys::path::parent_path(SubframeworkDirName);
56307c22b78SDouglas Gregor         if (SubframeworkDirName.empty())
56407c22b78SDouglas Gregor           break;
56507c22b78SDouglas Gregor 
56607c22b78SDouglas Gregor         if (FileMgr.getDirectory(SubframeworkDirName) == FrameworkDir) {
56707c22b78SDouglas Gregor           FoundParent = true;
56807c22b78SDouglas Gregor           break;
56907c22b78SDouglas Gregor         }
57007c22b78SDouglas Gregor       } while (true);
57107c22b78SDouglas Gregor 
57207c22b78SDouglas Gregor       if (!FoundParent)
57307c22b78SDouglas Gregor         continue;
57407c22b78SDouglas Gregor 
575e89dbc1dSDouglas Gregor       // FIXME: Do we want to warn about subframeworks without umbrella headers?
576056396aeSDouglas Gregor       SmallString<32> NameBuf;
577056396aeSDouglas Gregor       inferFrameworkModule(sanitizeFilenameAsIdentifier(
578056396aeSDouglas Gregor                              llvm::sys::path::stem(Dir->path()), NameBuf),
579056396aeSDouglas Gregor                            SubframeworkDir, IsSystem, Result);
580e89dbc1dSDouglas Gregor     }
581e89dbc1dSDouglas Gregor   }
582e89dbc1dSDouglas Gregor 
58311dfe6feSDouglas Gregor   // If the module is a top-level framework, automatically link against the
58411dfe6feSDouglas Gregor   // framework.
58511dfe6feSDouglas Gregor   if (!Result->isSubFramework()) {
58611dfe6feSDouglas Gregor     inferFrameworkLink(Result, FrameworkDir, FileMgr);
58711dfe6feSDouglas Gregor   }
58811dfe6feSDouglas Gregor 
58956c64013SDouglas Gregor   return Result;
59056c64013SDouglas Gregor }
59156c64013SDouglas Gregor 
592a89c5ac4SDouglas Gregor void ModuleMap::setUmbrellaHeader(Module *Mod, const FileEntry *UmbrellaHeader){
593b53e5483SLawrence Crowl   Headers[UmbrellaHeader] = KnownHeader(Mod, NormalHeader);
59473141fa9SDouglas Gregor   Mod->Umbrella = UmbrellaHeader;
5957033127bSDouglas Gregor   UmbrellaDirs[UmbrellaHeader->getDir()] = Mod;
596a89c5ac4SDouglas Gregor }
597a89c5ac4SDouglas Gregor 
598524e33e1SDouglas Gregor void ModuleMap::setUmbrellaDir(Module *Mod, const DirectoryEntry *UmbrellaDir) {
599524e33e1SDouglas Gregor   Mod->Umbrella = UmbrellaDir;
600524e33e1SDouglas Gregor   UmbrellaDirs[UmbrellaDir] = Mod;
601524e33e1SDouglas Gregor }
602524e33e1SDouglas Gregor 
60359527666SDouglas Gregor void ModuleMap::addHeader(Module *Mod, const FileEntry *Header,
604b53e5483SLawrence Crowl                           ModuleHeaderRole Role) {
605b53e5483SLawrence Crowl   if (Role == ExcludedHeader) {
60659527666SDouglas Gregor     Mod->ExcludedHeaders.push_back(Header);
607b146baabSArgyrios Kyrtzidis   } else {
608b53e5483SLawrence Crowl     if (Role == PrivateHeader)
609b53e5483SLawrence Crowl       Mod->PrivateHeaders.push_back(Header);
610b53e5483SLawrence Crowl     else
611b53e5483SLawrence Crowl       Mod->NormalHeaders.push_back(Header);
6126f722b4eSArgyrios Kyrtzidis     bool isCompilingModuleHeader = Mod->getTopLevelModule() == CompilingModule;
613b53e5483SLawrence Crowl     HeaderInfo.MarkFileModuleHeader(Header, Role, isCompilingModuleHeader);
614b146baabSArgyrios Kyrtzidis   }
615b53e5483SLawrence Crowl   Headers[Header] = KnownHeader(Mod, Role);
616a89c5ac4SDouglas Gregor }
617a89c5ac4SDouglas Gregor 
618514b636aSDouglas Gregor const FileEntry *
619e4412640SArgyrios Kyrtzidis ModuleMap::getContainingModuleMapFile(Module *Module) const {
620514b636aSDouglas Gregor   if (Module->DefinitionLoc.isInvalid() || !SourceMgr)
621514b636aSDouglas Gregor     return 0;
622514b636aSDouglas Gregor 
623514b636aSDouglas Gregor   return SourceMgr->getFileEntryForID(
624514b636aSDouglas Gregor            SourceMgr->getFileID(Module->DefinitionLoc));
625514b636aSDouglas Gregor }
626514b636aSDouglas Gregor 
627718292f2SDouglas Gregor void ModuleMap::dump() {
628718292f2SDouglas Gregor   llvm::errs() << "Modules:";
629718292f2SDouglas Gregor   for (llvm::StringMap<Module *>::iterator M = Modules.begin(),
630718292f2SDouglas Gregor                                         MEnd = Modules.end();
631718292f2SDouglas Gregor        M != MEnd; ++M)
632d28d1b8dSDouglas Gregor     M->getValue()->print(llvm::errs(), 2);
633718292f2SDouglas Gregor 
634718292f2SDouglas Gregor   llvm::errs() << "Headers:";
63559527666SDouglas Gregor   for (HeadersMap::iterator H = Headers.begin(), HEnd = Headers.end();
636718292f2SDouglas Gregor        H != HEnd; ++H) {
637718292f2SDouglas Gregor     llvm::errs() << "  \"" << H->first->getName() << "\" -> "
63859527666SDouglas Gregor                  << H->second.getModule()->getFullModuleName() << "\n";
639718292f2SDouglas Gregor   }
640718292f2SDouglas Gregor }
641718292f2SDouglas Gregor 
6422b82c2a5SDouglas Gregor bool ModuleMap::resolveExports(Module *Mod, bool Complain) {
6432b82c2a5SDouglas Gregor   bool HadError = false;
6442b82c2a5SDouglas Gregor   for (unsigned I = 0, N = Mod->UnresolvedExports.size(); I != N; ++I) {
6452b82c2a5SDouglas Gregor     Module::ExportDecl Export = resolveExport(Mod, Mod->UnresolvedExports[I],
6462b82c2a5SDouglas Gregor                                               Complain);
647f5eedd05SDouglas Gregor     if (Export.getPointer() || Export.getInt())
6482b82c2a5SDouglas Gregor       Mod->Exports.push_back(Export);
6492b82c2a5SDouglas Gregor     else
6502b82c2a5SDouglas Gregor       HadError = true;
6512b82c2a5SDouglas Gregor   }
6522b82c2a5SDouglas Gregor   Mod->UnresolvedExports.clear();
6532b82c2a5SDouglas Gregor   return HadError;
6542b82c2a5SDouglas Gregor }
6552b82c2a5SDouglas Gregor 
656fb912657SDouglas Gregor bool ModuleMap::resolveConflicts(Module *Mod, bool Complain) {
657fb912657SDouglas Gregor   bool HadError = false;
658fb912657SDouglas Gregor   for (unsigned I = 0, N = Mod->UnresolvedConflicts.size(); I != N; ++I) {
659fb912657SDouglas Gregor     Module *OtherMod = resolveModuleId(Mod->UnresolvedConflicts[I].Id,
660fb912657SDouglas Gregor                                        Mod, Complain);
661fb912657SDouglas Gregor     if (!OtherMod) {
662fb912657SDouglas Gregor       HadError = true;
663fb912657SDouglas Gregor       continue;
664fb912657SDouglas Gregor     }
665fb912657SDouglas Gregor 
666fb912657SDouglas Gregor     Module::Conflict Conflict;
667fb912657SDouglas Gregor     Conflict.Other = OtherMod;
668fb912657SDouglas Gregor     Conflict.Message = Mod->UnresolvedConflicts[I].Message;
669fb912657SDouglas Gregor     Mod->Conflicts.push_back(Conflict);
670fb912657SDouglas Gregor   }
671fb912657SDouglas Gregor   Mod->UnresolvedConflicts.clear();
672fb912657SDouglas Gregor   return HadError;
673fb912657SDouglas Gregor }
674fb912657SDouglas Gregor 
6750093b3c7SDouglas Gregor Module *ModuleMap::inferModuleFromLocation(FullSourceLoc Loc) {
6760093b3c7SDouglas Gregor   if (Loc.isInvalid())
6770093b3c7SDouglas Gregor     return 0;
6780093b3c7SDouglas Gregor 
6790093b3c7SDouglas Gregor   // Use the expansion location to determine which module we're in.
6800093b3c7SDouglas Gregor   FullSourceLoc ExpansionLoc = Loc.getExpansionLoc();
6810093b3c7SDouglas Gregor   if (!ExpansionLoc.isFileID())
6820093b3c7SDouglas Gregor     return 0;
6830093b3c7SDouglas Gregor 
6840093b3c7SDouglas Gregor 
6850093b3c7SDouglas Gregor   const SourceManager &SrcMgr = Loc.getManager();
6860093b3c7SDouglas Gregor   FileID ExpansionFileID = ExpansionLoc.getFileID();
687224d8a74SDouglas Gregor 
688224d8a74SDouglas Gregor   while (const FileEntry *ExpansionFile
689224d8a74SDouglas Gregor            = SrcMgr.getFileEntryForID(ExpansionFileID)) {
690224d8a74SDouglas Gregor     // Find the module that owns this header (if any).
691b53e5483SLawrence Crowl     if (Module *Mod = findModuleForHeader(ExpansionFile).getModule())
692224d8a74SDouglas Gregor       return Mod;
693224d8a74SDouglas Gregor 
694224d8a74SDouglas Gregor     // No module owns this header, so look up the inclusion chain to see if
695224d8a74SDouglas Gregor     // any included header has an associated module.
696224d8a74SDouglas Gregor     SourceLocation IncludeLoc = SrcMgr.getIncludeLoc(ExpansionFileID);
697224d8a74SDouglas Gregor     if (IncludeLoc.isInvalid())
6980093b3c7SDouglas Gregor       return 0;
6990093b3c7SDouglas Gregor 
700224d8a74SDouglas Gregor     ExpansionFileID = SrcMgr.getFileID(IncludeLoc);
701224d8a74SDouglas Gregor   }
702224d8a74SDouglas Gregor 
703224d8a74SDouglas Gregor   return 0;
7040093b3c7SDouglas Gregor }
7050093b3c7SDouglas Gregor 
706718292f2SDouglas Gregor //----------------------------------------------------------------------------//
707718292f2SDouglas Gregor // Module map file parser
708718292f2SDouglas Gregor //----------------------------------------------------------------------------//
709718292f2SDouglas Gregor 
710718292f2SDouglas Gregor namespace clang {
711718292f2SDouglas Gregor   /// \brief A token in a module map file.
712718292f2SDouglas Gregor   struct MMToken {
713718292f2SDouglas Gregor     enum TokenKind {
7141fb5c3a6SDouglas Gregor       Comma,
71535b13eceSDouglas Gregor       ConfigMacros,
716fb912657SDouglas Gregor       Conflict,
717718292f2SDouglas Gregor       EndOfFile,
718718292f2SDouglas Gregor       HeaderKeyword,
719718292f2SDouglas Gregor       Identifier,
72059527666SDouglas Gregor       ExcludeKeyword,
721718292f2SDouglas Gregor       ExplicitKeyword,
7222b82c2a5SDouglas Gregor       ExportKeyword,
72397292843SDaniel Jasper       ExternKeyword,
724755b2055SDouglas Gregor       FrameworkKeyword,
7256ddfca91SDouglas Gregor       LinkKeyword,
726718292f2SDouglas Gregor       ModuleKeyword,
7272b82c2a5SDouglas Gregor       Period,
728b53e5483SLawrence Crowl       PrivateKeyword,
729718292f2SDouglas Gregor       UmbrellaKeyword,
7301fb5c3a6SDouglas Gregor       RequiresKeyword,
7312b82c2a5SDouglas Gregor       Star,
732718292f2SDouglas Gregor       StringLiteral,
733718292f2SDouglas Gregor       LBrace,
734a686e1b0SDouglas Gregor       RBrace,
735a686e1b0SDouglas Gregor       LSquare,
736a686e1b0SDouglas Gregor       RSquare
737718292f2SDouglas Gregor     } Kind;
738718292f2SDouglas Gregor 
739718292f2SDouglas Gregor     unsigned Location;
740718292f2SDouglas Gregor     unsigned StringLength;
741718292f2SDouglas Gregor     const char *StringData;
742718292f2SDouglas Gregor 
743718292f2SDouglas Gregor     void clear() {
744718292f2SDouglas Gregor       Kind = EndOfFile;
745718292f2SDouglas Gregor       Location = 0;
746718292f2SDouglas Gregor       StringLength = 0;
747718292f2SDouglas Gregor       StringData = 0;
748718292f2SDouglas Gregor     }
749718292f2SDouglas Gregor 
750718292f2SDouglas Gregor     bool is(TokenKind K) const { return Kind == K; }
751718292f2SDouglas Gregor 
752718292f2SDouglas Gregor     SourceLocation getLocation() const {
753718292f2SDouglas Gregor       return SourceLocation::getFromRawEncoding(Location);
754718292f2SDouglas Gregor     }
755718292f2SDouglas Gregor 
756718292f2SDouglas Gregor     StringRef getString() const {
757718292f2SDouglas Gregor       return StringRef(StringData, StringLength);
758718292f2SDouglas Gregor     }
759718292f2SDouglas Gregor   };
760718292f2SDouglas Gregor 
7619194a91dSDouglas Gregor   /// \brief The set of attributes that can be attached to a module.
7624442605fSBill Wendling   struct Attributes {
76335b13eceSDouglas Gregor     Attributes() : IsSystem(), IsExhaustive() { }
7649194a91dSDouglas Gregor 
7659194a91dSDouglas Gregor     /// \brief Whether this is a system module.
7669194a91dSDouglas Gregor     unsigned IsSystem : 1;
76735b13eceSDouglas Gregor 
76835b13eceSDouglas Gregor     /// \brief Whether this is an exhaustive set of configuration macros.
76935b13eceSDouglas Gregor     unsigned IsExhaustive : 1;
7709194a91dSDouglas Gregor   };
7719194a91dSDouglas Gregor 
7729194a91dSDouglas Gregor 
773718292f2SDouglas Gregor   class ModuleMapParser {
774718292f2SDouglas Gregor     Lexer &L;
775718292f2SDouglas Gregor     SourceManager &SourceMgr;
776bc10b9fbSDouglas Gregor 
777bc10b9fbSDouglas Gregor     /// \brief Default target information, used only for string literal
778bc10b9fbSDouglas Gregor     /// parsing.
779bc10b9fbSDouglas Gregor     const TargetInfo *Target;
780bc10b9fbSDouglas Gregor 
781718292f2SDouglas Gregor     DiagnosticsEngine &Diags;
782718292f2SDouglas Gregor     ModuleMap &Map;
783718292f2SDouglas Gregor 
7845257fc63SDouglas Gregor     /// \brief The directory that this module map resides in.
7855257fc63SDouglas Gregor     const DirectoryEntry *Directory;
7865257fc63SDouglas Gregor 
7873ec6663bSDouglas Gregor     /// \brief The directory containing Clang-supplied headers.
7883ec6663bSDouglas Gregor     const DirectoryEntry *BuiltinIncludeDir;
7893ec6663bSDouglas Gregor 
790963c5535SDouglas Gregor     /// \brief Whether this module map is in a system header directory.
791963c5535SDouglas Gregor     bool IsSystem;
792963c5535SDouglas Gregor 
793718292f2SDouglas Gregor     /// \brief Whether an error occurred.
794718292f2SDouglas Gregor     bool HadError;
795718292f2SDouglas Gregor 
796718292f2SDouglas Gregor     /// \brief Stores string data for the various string literals referenced
797718292f2SDouglas Gregor     /// during parsing.
798718292f2SDouglas Gregor     llvm::BumpPtrAllocator StringData;
799718292f2SDouglas Gregor 
800718292f2SDouglas Gregor     /// \brief The current token.
801718292f2SDouglas Gregor     MMToken Tok;
802718292f2SDouglas Gregor 
803718292f2SDouglas Gregor     /// \brief The active module.
804de3ef502SDouglas Gregor     Module *ActiveModule;
805718292f2SDouglas Gregor 
806718292f2SDouglas Gregor     /// \brief Consume the current token and return its location.
807718292f2SDouglas Gregor     SourceLocation consumeToken();
808718292f2SDouglas Gregor 
809718292f2SDouglas Gregor     /// \brief Skip tokens until we reach the a token with the given kind
810718292f2SDouglas Gregor     /// (or the end of the file).
811718292f2SDouglas Gregor     void skipUntil(MMToken::TokenKind K);
812718292f2SDouglas Gregor 
813f857950dSDmitri Gribenko     typedef SmallVector<std::pair<std::string, SourceLocation>, 2> ModuleId;
814e7ab3669SDouglas Gregor     bool parseModuleId(ModuleId &Id);
815718292f2SDouglas Gregor     void parseModuleDecl();
81697292843SDaniel Jasper     void parseExternModuleDecl();
8171fb5c3a6SDouglas Gregor     void parseRequiresDecl();
818b53e5483SLawrence Crowl     void parseHeaderDecl(clang::MMToken::TokenKind,
819b53e5483SLawrence Crowl                          SourceLocation LeadingLoc);
820524e33e1SDouglas Gregor     void parseUmbrellaDirDecl(SourceLocation UmbrellaLoc);
8212b82c2a5SDouglas Gregor     void parseExportDecl();
8226ddfca91SDouglas Gregor     void parseLinkDecl();
82335b13eceSDouglas Gregor     void parseConfigMacros();
824fb912657SDouglas Gregor     void parseConflict();
8259194a91dSDouglas Gregor     void parseInferredModuleDecl(bool Framework, bool Explicit);
8264442605fSBill Wendling     bool parseOptionalAttributes(Attributes &Attrs);
827718292f2SDouglas Gregor 
8287033127bSDouglas Gregor     const DirectoryEntry *getOverriddenHeaderSearchDir();
8297033127bSDouglas Gregor 
830718292f2SDouglas Gregor   public:
831718292f2SDouglas Gregor     explicit ModuleMapParser(Lexer &L, SourceManager &SourceMgr,
832bc10b9fbSDouglas Gregor                              const TargetInfo *Target,
833718292f2SDouglas Gregor                              DiagnosticsEngine &Diags,
8345257fc63SDouglas Gregor                              ModuleMap &Map,
8353ec6663bSDouglas Gregor                              const DirectoryEntry *Directory,
836963c5535SDouglas Gregor                              const DirectoryEntry *BuiltinIncludeDir,
837963c5535SDouglas Gregor                              bool IsSystem)
838bc10b9fbSDouglas Gregor       : L(L), SourceMgr(SourceMgr), Target(Target), Diags(Diags), Map(Map),
8393ec6663bSDouglas Gregor         Directory(Directory), BuiltinIncludeDir(BuiltinIncludeDir),
840963c5535SDouglas Gregor         IsSystem(IsSystem), HadError(false), ActiveModule(0)
841718292f2SDouglas Gregor     {
842718292f2SDouglas Gregor       Tok.clear();
843718292f2SDouglas Gregor       consumeToken();
844718292f2SDouglas Gregor     }
845718292f2SDouglas Gregor 
846718292f2SDouglas Gregor     bool parseModuleMapFile();
847718292f2SDouglas Gregor   };
848718292f2SDouglas Gregor }
849718292f2SDouglas Gregor 
850718292f2SDouglas Gregor SourceLocation ModuleMapParser::consumeToken() {
851718292f2SDouglas Gregor retry:
852718292f2SDouglas Gregor   SourceLocation Result = Tok.getLocation();
853718292f2SDouglas Gregor   Tok.clear();
854718292f2SDouglas Gregor 
855718292f2SDouglas Gregor   Token LToken;
856718292f2SDouglas Gregor   L.LexFromRawLexer(LToken);
857718292f2SDouglas Gregor   Tok.Location = LToken.getLocation().getRawEncoding();
858718292f2SDouglas Gregor   switch (LToken.getKind()) {
859718292f2SDouglas Gregor   case tok::raw_identifier:
860718292f2SDouglas Gregor     Tok.StringData = LToken.getRawIdentifierData();
861718292f2SDouglas Gregor     Tok.StringLength = LToken.getLength();
862718292f2SDouglas Gregor     Tok.Kind = llvm::StringSwitch<MMToken::TokenKind>(Tok.getString())
86335b13eceSDouglas Gregor                  .Case("config_macros", MMToken::ConfigMacros)
864fb912657SDouglas Gregor                  .Case("conflict", MMToken::Conflict)
86559527666SDouglas Gregor                  .Case("exclude", MMToken::ExcludeKeyword)
866718292f2SDouglas Gregor                  .Case("explicit", MMToken::ExplicitKeyword)
8672b82c2a5SDouglas Gregor                  .Case("export", MMToken::ExportKeyword)
86897292843SDaniel Jasper                  .Case("extern", MMToken::ExternKeyword)
869755b2055SDouglas Gregor                  .Case("framework", MMToken::FrameworkKeyword)
87035b13eceSDouglas Gregor                  .Case("header", MMToken::HeaderKeyword)
8716ddfca91SDouglas Gregor                  .Case("link", MMToken::LinkKeyword)
872718292f2SDouglas Gregor                  .Case("module", MMToken::ModuleKeyword)
873b53e5483SLawrence Crowl                  .Case("private", MMToken::PrivateKeyword)
8741fb5c3a6SDouglas Gregor                  .Case("requires", MMToken::RequiresKeyword)
875718292f2SDouglas Gregor                  .Case("umbrella", MMToken::UmbrellaKeyword)
876718292f2SDouglas Gregor                  .Default(MMToken::Identifier);
877718292f2SDouglas Gregor     break;
878718292f2SDouglas Gregor 
8791fb5c3a6SDouglas Gregor   case tok::comma:
8801fb5c3a6SDouglas Gregor     Tok.Kind = MMToken::Comma;
8811fb5c3a6SDouglas Gregor     break;
8821fb5c3a6SDouglas Gregor 
883718292f2SDouglas Gregor   case tok::eof:
884718292f2SDouglas Gregor     Tok.Kind = MMToken::EndOfFile;
885718292f2SDouglas Gregor     break;
886718292f2SDouglas Gregor 
887718292f2SDouglas Gregor   case tok::l_brace:
888718292f2SDouglas Gregor     Tok.Kind = MMToken::LBrace;
889718292f2SDouglas Gregor     break;
890718292f2SDouglas Gregor 
891a686e1b0SDouglas Gregor   case tok::l_square:
892a686e1b0SDouglas Gregor     Tok.Kind = MMToken::LSquare;
893a686e1b0SDouglas Gregor     break;
894a686e1b0SDouglas Gregor 
8952b82c2a5SDouglas Gregor   case tok::period:
8962b82c2a5SDouglas Gregor     Tok.Kind = MMToken::Period;
8972b82c2a5SDouglas Gregor     break;
8982b82c2a5SDouglas Gregor 
899718292f2SDouglas Gregor   case tok::r_brace:
900718292f2SDouglas Gregor     Tok.Kind = MMToken::RBrace;
901718292f2SDouglas Gregor     break;
902718292f2SDouglas Gregor 
903a686e1b0SDouglas Gregor   case tok::r_square:
904a686e1b0SDouglas Gregor     Tok.Kind = MMToken::RSquare;
905a686e1b0SDouglas Gregor     break;
906a686e1b0SDouglas Gregor 
9072b82c2a5SDouglas Gregor   case tok::star:
9082b82c2a5SDouglas Gregor     Tok.Kind = MMToken::Star;
9092b82c2a5SDouglas Gregor     break;
9102b82c2a5SDouglas Gregor 
911718292f2SDouglas Gregor   case tok::string_literal: {
912d67aea28SRichard Smith     if (LToken.hasUDSuffix()) {
913d67aea28SRichard Smith       Diags.Report(LToken.getLocation(), diag::err_invalid_string_udl);
914d67aea28SRichard Smith       HadError = true;
915d67aea28SRichard Smith       goto retry;
916d67aea28SRichard Smith     }
917d67aea28SRichard Smith 
918718292f2SDouglas Gregor     // Parse the string literal.
919718292f2SDouglas Gregor     LangOptions LangOpts;
920718292f2SDouglas Gregor     StringLiteralParser StringLiteral(&LToken, 1, SourceMgr, LangOpts, *Target);
921718292f2SDouglas Gregor     if (StringLiteral.hadError)
922718292f2SDouglas Gregor       goto retry;
923718292f2SDouglas Gregor 
924718292f2SDouglas Gregor     // Copy the string literal into our string data allocator.
925718292f2SDouglas Gregor     unsigned Length = StringLiteral.GetStringLength();
926718292f2SDouglas Gregor     char *Saved = StringData.Allocate<char>(Length + 1);
927718292f2SDouglas Gregor     memcpy(Saved, StringLiteral.GetString().data(), Length);
928718292f2SDouglas Gregor     Saved[Length] = 0;
929718292f2SDouglas Gregor 
930718292f2SDouglas Gregor     // Form the token.
931718292f2SDouglas Gregor     Tok.Kind = MMToken::StringLiteral;
932718292f2SDouglas Gregor     Tok.StringData = Saved;
933718292f2SDouglas Gregor     Tok.StringLength = Length;
934718292f2SDouglas Gregor     break;
935718292f2SDouglas Gregor   }
936718292f2SDouglas Gregor 
937718292f2SDouglas Gregor   case tok::comment:
938718292f2SDouglas Gregor     goto retry;
939718292f2SDouglas Gregor 
940718292f2SDouglas Gregor   default:
941718292f2SDouglas Gregor     Diags.Report(LToken.getLocation(), diag::err_mmap_unknown_token);
942718292f2SDouglas Gregor     HadError = true;
943718292f2SDouglas Gregor     goto retry;
944718292f2SDouglas Gregor   }
945718292f2SDouglas Gregor 
946718292f2SDouglas Gregor   return Result;
947718292f2SDouglas Gregor }
948718292f2SDouglas Gregor 
949718292f2SDouglas Gregor void ModuleMapParser::skipUntil(MMToken::TokenKind K) {
950718292f2SDouglas Gregor   unsigned braceDepth = 0;
951a686e1b0SDouglas Gregor   unsigned squareDepth = 0;
952718292f2SDouglas Gregor   do {
953718292f2SDouglas Gregor     switch (Tok.Kind) {
954718292f2SDouglas Gregor     case MMToken::EndOfFile:
955718292f2SDouglas Gregor       return;
956718292f2SDouglas Gregor 
957718292f2SDouglas Gregor     case MMToken::LBrace:
958a686e1b0SDouglas Gregor       if (Tok.is(K) && braceDepth == 0 && squareDepth == 0)
959718292f2SDouglas Gregor         return;
960718292f2SDouglas Gregor 
961718292f2SDouglas Gregor       ++braceDepth;
962718292f2SDouglas Gregor       break;
963718292f2SDouglas Gregor 
964a686e1b0SDouglas Gregor     case MMToken::LSquare:
965a686e1b0SDouglas Gregor       if (Tok.is(K) && braceDepth == 0 && squareDepth == 0)
966a686e1b0SDouglas Gregor         return;
967a686e1b0SDouglas Gregor 
968a686e1b0SDouglas Gregor       ++squareDepth;
969a686e1b0SDouglas Gregor       break;
970a686e1b0SDouglas Gregor 
971718292f2SDouglas Gregor     case MMToken::RBrace:
972718292f2SDouglas Gregor       if (braceDepth > 0)
973718292f2SDouglas Gregor         --braceDepth;
974718292f2SDouglas Gregor       else if (Tok.is(K))
975718292f2SDouglas Gregor         return;
976718292f2SDouglas Gregor       break;
977718292f2SDouglas Gregor 
978a686e1b0SDouglas Gregor     case MMToken::RSquare:
979a686e1b0SDouglas Gregor       if (squareDepth > 0)
980a686e1b0SDouglas Gregor         --squareDepth;
981a686e1b0SDouglas Gregor       else if (Tok.is(K))
982a686e1b0SDouglas Gregor         return;
983a686e1b0SDouglas Gregor       break;
984a686e1b0SDouglas Gregor 
985718292f2SDouglas Gregor     default:
986a686e1b0SDouglas Gregor       if (braceDepth == 0 && squareDepth == 0 && Tok.is(K))
987718292f2SDouglas Gregor         return;
988718292f2SDouglas Gregor       break;
989718292f2SDouglas Gregor     }
990718292f2SDouglas Gregor 
991718292f2SDouglas Gregor    consumeToken();
992718292f2SDouglas Gregor   } while (true);
993718292f2SDouglas Gregor }
994718292f2SDouglas Gregor 
995e7ab3669SDouglas Gregor /// \brief Parse a module-id.
996e7ab3669SDouglas Gregor ///
997e7ab3669SDouglas Gregor ///   module-id:
998e7ab3669SDouglas Gregor ///     identifier
999e7ab3669SDouglas Gregor ///     identifier '.' module-id
1000e7ab3669SDouglas Gregor ///
1001e7ab3669SDouglas Gregor /// \returns true if an error occurred, false otherwise.
1002e7ab3669SDouglas Gregor bool ModuleMapParser::parseModuleId(ModuleId &Id) {
1003e7ab3669SDouglas Gregor   Id.clear();
1004e7ab3669SDouglas Gregor   do {
1005e7ab3669SDouglas Gregor     if (Tok.is(MMToken::Identifier)) {
1006e7ab3669SDouglas Gregor       Id.push_back(std::make_pair(Tok.getString(), Tok.getLocation()));
1007e7ab3669SDouglas Gregor       consumeToken();
1008e7ab3669SDouglas Gregor     } else {
1009e7ab3669SDouglas Gregor       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module_name);
1010e7ab3669SDouglas Gregor       return true;
1011e7ab3669SDouglas Gregor     }
1012e7ab3669SDouglas Gregor 
1013e7ab3669SDouglas Gregor     if (!Tok.is(MMToken::Period))
1014e7ab3669SDouglas Gregor       break;
1015e7ab3669SDouglas Gregor 
1016e7ab3669SDouglas Gregor     consumeToken();
1017e7ab3669SDouglas Gregor   } while (true);
1018e7ab3669SDouglas Gregor 
1019e7ab3669SDouglas Gregor   return false;
1020e7ab3669SDouglas Gregor }
1021e7ab3669SDouglas Gregor 
1022a686e1b0SDouglas Gregor namespace {
1023a686e1b0SDouglas Gregor   /// \brief Enumerates the known attributes.
1024a686e1b0SDouglas Gregor   enum AttributeKind {
1025a686e1b0SDouglas Gregor     /// \brief An unknown attribute.
1026a686e1b0SDouglas Gregor     AT_unknown,
1027a686e1b0SDouglas Gregor     /// \brief The 'system' attribute.
102835b13eceSDouglas Gregor     AT_system,
102935b13eceSDouglas Gregor     /// \brief The 'exhaustive' attribute.
103035b13eceSDouglas Gregor     AT_exhaustive
1031a686e1b0SDouglas Gregor   };
1032a686e1b0SDouglas Gregor }
1033a686e1b0SDouglas Gregor 
1034718292f2SDouglas Gregor /// \brief Parse a module declaration.
1035718292f2SDouglas Gregor ///
1036718292f2SDouglas Gregor ///   module-declaration:
103797292843SDaniel Jasper ///     'extern' 'module' module-id string-literal
1038a686e1b0SDouglas Gregor ///     'explicit'[opt] 'framework'[opt] 'module' module-id attributes[opt]
1039a686e1b0SDouglas Gregor ///       { module-member* }
1040a686e1b0SDouglas Gregor ///
1041718292f2SDouglas Gregor ///   module-member:
10421fb5c3a6SDouglas Gregor ///     requires-declaration
1043718292f2SDouglas Gregor ///     header-declaration
1044e7ab3669SDouglas Gregor ///     submodule-declaration
10452b82c2a5SDouglas Gregor ///     export-declaration
10466ddfca91SDouglas Gregor ///     link-declaration
104773441091SDouglas Gregor ///
104873441091SDouglas Gregor ///   submodule-declaration:
104973441091SDouglas Gregor ///     module-declaration
105073441091SDouglas Gregor ///     inferred-submodule-declaration
1051718292f2SDouglas Gregor void ModuleMapParser::parseModuleDecl() {
1052755b2055SDouglas Gregor   assert(Tok.is(MMToken::ExplicitKeyword) || Tok.is(MMToken::ModuleKeyword) ||
105397292843SDaniel Jasper          Tok.is(MMToken::FrameworkKeyword) || Tok.is(MMToken::ExternKeyword));
105497292843SDaniel Jasper   if (Tok.is(MMToken::ExternKeyword)) {
105597292843SDaniel Jasper     parseExternModuleDecl();
105697292843SDaniel Jasper     return;
105797292843SDaniel Jasper   }
105897292843SDaniel Jasper 
1059f2161a70SDouglas Gregor   // Parse 'explicit' or 'framework' keyword, if present.
1060e7ab3669SDouglas Gregor   SourceLocation ExplicitLoc;
1061718292f2SDouglas Gregor   bool Explicit = false;
1062f2161a70SDouglas Gregor   bool Framework = false;
1063755b2055SDouglas Gregor 
1064f2161a70SDouglas Gregor   // Parse 'explicit' keyword, if present.
1065f2161a70SDouglas Gregor   if (Tok.is(MMToken::ExplicitKeyword)) {
1066e7ab3669SDouglas Gregor     ExplicitLoc = consumeToken();
1067f2161a70SDouglas Gregor     Explicit = true;
1068f2161a70SDouglas Gregor   }
1069f2161a70SDouglas Gregor 
1070f2161a70SDouglas Gregor   // Parse 'framework' keyword, if present.
1071755b2055SDouglas Gregor   if (Tok.is(MMToken::FrameworkKeyword)) {
1072755b2055SDouglas Gregor     consumeToken();
1073755b2055SDouglas Gregor     Framework = true;
1074755b2055SDouglas Gregor   }
1075718292f2SDouglas Gregor 
1076718292f2SDouglas Gregor   // Parse 'module' keyword.
1077718292f2SDouglas Gregor   if (!Tok.is(MMToken::ModuleKeyword)) {
1078d6343c99SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module);
1079718292f2SDouglas Gregor     consumeToken();
1080718292f2SDouglas Gregor     HadError = true;
1081718292f2SDouglas Gregor     return;
1082718292f2SDouglas Gregor   }
1083718292f2SDouglas Gregor   consumeToken(); // 'module' keyword
1084718292f2SDouglas Gregor 
108573441091SDouglas Gregor   // If we have a wildcard for the module name, this is an inferred submodule.
108673441091SDouglas Gregor   // Parse it.
108773441091SDouglas Gregor   if (Tok.is(MMToken::Star))
10889194a91dSDouglas Gregor     return parseInferredModuleDecl(Framework, Explicit);
108973441091SDouglas Gregor 
1090718292f2SDouglas Gregor   // Parse the module name.
1091e7ab3669SDouglas Gregor   ModuleId Id;
1092e7ab3669SDouglas Gregor   if (parseModuleId(Id)) {
1093718292f2SDouglas Gregor     HadError = true;
1094718292f2SDouglas Gregor     return;
1095718292f2SDouglas Gregor   }
1096e7ab3669SDouglas Gregor 
1097e7ab3669SDouglas Gregor   if (ActiveModule) {
1098e7ab3669SDouglas Gregor     if (Id.size() > 1) {
1099e7ab3669SDouglas Gregor       Diags.Report(Id.front().second, diag::err_mmap_nested_submodule_id)
1100e7ab3669SDouglas Gregor         << SourceRange(Id.front().second, Id.back().second);
1101e7ab3669SDouglas Gregor 
1102e7ab3669SDouglas Gregor       HadError = true;
1103e7ab3669SDouglas Gregor       return;
1104e7ab3669SDouglas Gregor     }
1105e7ab3669SDouglas Gregor   } else if (Id.size() == 1 && Explicit) {
1106e7ab3669SDouglas Gregor     // Top-level modules can't be explicit.
1107e7ab3669SDouglas Gregor     Diags.Report(ExplicitLoc, diag::err_mmap_explicit_top_level);
1108e7ab3669SDouglas Gregor     Explicit = false;
1109e7ab3669SDouglas Gregor     ExplicitLoc = SourceLocation();
1110e7ab3669SDouglas Gregor     HadError = true;
1111e7ab3669SDouglas Gregor   }
1112e7ab3669SDouglas Gregor 
1113e7ab3669SDouglas Gregor   Module *PreviousActiveModule = ActiveModule;
1114e7ab3669SDouglas Gregor   if (Id.size() > 1) {
1115e7ab3669SDouglas Gregor     // This module map defines a submodule. Go find the module of which it
1116e7ab3669SDouglas Gregor     // is a submodule.
1117e7ab3669SDouglas Gregor     ActiveModule = 0;
1118e7ab3669SDouglas Gregor     for (unsigned I = 0, N = Id.size() - 1; I != N; ++I) {
1119e7ab3669SDouglas Gregor       if (Module *Next = Map.lookupModuleQualified(Id[I].first, ActiveModule)) {
1120e7ab3669SDouglas Gregor         ActiveModule = Next;
1121e7ab3669SDouglas Gregor         continue;
1122e7ab3669SDouglas Gregor       }
1123e7ab3669SDouglas Gregor 
1124e7ab3669SDouglas Gregor       if (ActiveModule) {
1125e7ab3669SDouglas Gregor         Diags.Report(Id[I].second, diag::err_mmap_missing_module_qualified)
1126e7ab3669SDouglas Gregor           << Id[I].first << ActiveModule->getTopLevelModule();
1127e7ab3669SDouglas Gregor       } else {
1128e7ab3669SDouglas Gregor         Diags.Report(Id[I].second, diag::err_mmap_expected_module_name);
1129e7ab3669SDouglas Gregor       }
1130e7ab3669SDouglas Gregor       HadError = true;
1131e7ab3669SDouglas Gregor       return;
1132e7ab3669SDouglas Gregor     }
1133e7ab3669SDouglas Gregor   }
1134e7ab3669SDouglas Gregor 
1135e7ab3669SDouglas Gregor   StringRef ModuleName = Id.back().first;
1136e7ab3669SDouglas Gregor   SourceLocation ModuleNameLoc = Id.back().second;
1137718292f2SDouglas Gregor 
1138a686e1b0SDouglas Gregor   // Parse the optional attribute list.
11394442605fSBill Wendling   Attributes Attrs;
11409194a91dSDouglas Gregor   parseOptionalAttributes(Attrs);
1141a686e1b0SDouglas Gregor 
1142718292f2SDouglas Gregor   // Parse the opening brace.
1143718292f2SDouglas Gregor   if (!Tok.is(MMToken::LBrace)) {
1144718292f2SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_lbrace)
1145718292f2SDouglas Gregor       << ModuleName;
1146718292f2SDouglas Gregor     HadError = true;
1147718292f2SDouglas Gregor     return;
1148718292f2SDouglas Gregor   }
1149718292f2SDouglas Gregor   SourceLocation LBraceLoc = consumeToken();
1150718292f2SDouglas Gregor 
1151718292f2SDouglas Gregor   // Determine whether this (sub)module has already been defined.
1152eb90e830SDouglas Gregor   if (Module *Existing = Map.lookupModuleQualified(ModuleName, ActiveModule)) {
1153fcc54a3bSDouglas Gregor     if (Existing->DefinitionLoc.isInvalid() && !ActiveModule) {
1154fcc54a3bSDouglas Gregor       // Skip the module definition.
1155fcc54a3bSDouglas Gregor       skipUntil(MMToken::RBrace);
1156fcc54a3bSDouglas Gregor       if (Tok.is(MMToken::RBrace))
1157fcc54a3bSDouglas Gregor         consumeToken();
1158fcc54a3bSDouglas Gregor       else {
1159fcc54a3bSDouglas Gregor         Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
1160fcc54a3bSDouglas Gregor         Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
1161fcc54a3bSDouglas Gregor         HadError = true;
1162fcc54a3bSDouglas Gregor       }
1163fcc54a3bSDouglas Gregor       return;
1164fcc54a3bSDouglas Gregor     }
1165fcc54a3bSDouglas Gregor 
1166718292f2SDouglas Gregor     Diags.Report(ModuleNameLoc, diag::err_mmap_module_redefinition)
1167718292f2SDouglas Gregor       << ModuleName;
1168eb90e830SDouglas Gregor     Diags.Report(Existing->DefinitionLoc, diag::note_mmap_prev_definition);
1169718292f2SDouglas Gregor 
1170718292f2SDouglas Gregor     // Skip the module definition.
1171718292f2SDouglas Gregor     skipUntil(MMToken::RBrace);
1172718292f2SDouglas Gregor     if (Tok.is(MMToken::RBrace))
1173718292f2SDouglas Gregor       consumeToken();
1174718292f2SDouglas Gregor 
1175718292f2SDouglas Gregor     HadError = true;
1176718292f2SDouglas Gregor     return;
1177718292f2SDouglas Gregor   }
1178718292f2SDouglas Gregor 
1179718292f2SDouglas Gregor   // Start defining this module.
1180eb90e830SDouglas Gregor   ActiveModule = Map.findOrCreateModule(ModuleName, ActiveModule, Framework,
1181eb90e830SDouglas Gregor                                         Explicit).first;
1182eb90e830SDouglas Gregor   ActiveModule->DefinitionLoc = ModuleNameLoc;
1183963c5535SDouglas Gregor   if (Attrs.IsSystem || IsSystem)
1184a686e1b0SDouglas Gregor     ActiveModule->IsSystem = true;
1185718292f2SDouglas Gregor 
1186718292f2SDouglas Gregor   bool Done = false;
1187718292f2SDouglas Gregor   do {
1188718292f2SDouglas Gregor     switch (Tok.Kind) {
1189718292f2SDouglas Gregor     case MMToken::EndOfFile:
1190718292f2SDouglas Gregor     case MMToken::RBrace:
1191718292f2SDouglas Gregor       Done = true;
1192718292f2SDouglas Gregor       break;
1193718292f2SDouglas Gregor 
119435b13eceSDouglas Gregor     case MMToken::ConfigMacros:
119535b13eceSDouglas Gregor       parseConfigMacros();
119635b13eceSDouglas Gregor       break;
119735b13eceSDouglas Gregor 
1198fb912657SDouglas Gregor     case MMToken::Conflict:
1199fb912657SDouglas Gregor       parseConflict();
1200fb912657SDouglas Gregor       break;
1201fb912657SDouglas Gregor 
1202718292f2SDouglas Gregor     case MMToken::ExplicitKeyword:
120397292843SDaniel Jasper     case MMToken::ExternKeyword:
1204f2161a70SDouglas Gregor     case MMToken::FrameworkKeyword:
1205718292f2SDouglas Gregor     case MMToken::ModuleKeyword:
1206718292f2SDouglas Gregor       parseModuleDecl();
1207718292f2SDouglas Gregor       break;
1208718292f2SDouglas Gregor 
12092b82c2a5SDouglas Gregor     case MMToken::ExportKeyword:
12102b82c2a5SDouglas Gregor       parseExportDecl();
12112b82c2a5SDouglas Gregor       break;
12122b82c2a5SDouglas Gregor 
12131fb5c3a6SDouglas Gregor     case MMToken::RequiresKeyword:
12141fb5c3a6SDouglas Gregor       parseRequiresDecl();
12151fb5c3a6SDouglas Gregor       break;
12161fb5c3a6SDouglas Gregor 
1217524e33e1SDouglas Gregor     case MMToken::UmbrellaKeyword: {
1218524e33e1SDouglas Gregor       SourceLocation UmbrellaLoc = consumeToken();
1219524e33e1SDouglas Gregor       if (Tok.is(MMToken::HeaderKeyword))
1220b53e5483SLawrence Crowl         parseHeaderDecl(MMToken::UmbrellaKeyword, UmbrellaLoc);
1221524e33e1SDouglas Gregor       else
1222524e33e1SDouglas Gregor         parseUmbrellaDirDecl(UmbrellaLoc);
1223718292f2SDouglas Gregor       break;
1224524e33e1SDouglas Gregor     }
1225718292f2SDouglas Gregor 
122659527666SDouglas Gregor     case MMToken::ExcludeKeyword: {
122759527666SDouglas Gregor       SourceLocation ExcludeLoc = consumeToken();
122859527666SDouglas Gregor       if (Tok.is(MMToken::HeaderKeyword)) {
1229b53e5483SLawrence Crowl         parseHeaderDecl(MMToken::ExcludeKeyword, ExcludeLoc);
123059527666SDouglas Gregor       } else {
123159527666SDouglas Gregor         Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
123259527666SDouglas Gregor           << "exclude";
123359527666SDouglas Gregor       }
123459527666SDouglas Gregor       break;
123559527666SDouglas Gregor     }
123659527666SDouglas Gregor 
1237b53e5483SLawrence Crowl     case MMToken::PrivateKeyword: {
1238b53e5483SLawrence Crowl       SourceLocation PrivateLoc = consumeToken();
1239b53e5483SLawrence Crowl       if (Tok.is(MMToken::HeaderKeyword)) {
1240b53e5483SLawrence Crowl         parseHeaderDecl(MMToken::PrivateKeyword, PrivateLoc);
1241b53e5483SLawrence Crowl       } else {
1242b53e5483SLawrence Crowl         Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
1243b53e5483SLawrence Crowl           << "private";
1244b53e5483SLawrence Crowl       }
1245b53e5483SLawrence Crowl       break;
1246b53e5483SLawrence Crowl     }
1247b53e5483SLawrence Crowl 
1248322f633cSDouglas Gregor     case MMToken::HeaderKeyword:
1249b53e5483SLawrence Crowl       parseHeaderDecl(MMToken::HeaderKeyword, SourceLocation());
1250718292f2SDouglas Gregor       break;
1251718292f2SDouglas Gregor 
12526ddfca91SDouglas Gregor     case MMToken::LinkKeyword:
12536ddfca91SDouglas Gregor       parseLinkDecl();
12546ddfca91SDouglas Gregor       break;
12556ddfca91SDouglas Gregor 
1256718292f2SDouglas Gregor     default:
1257718292f2SDouglas Gregor       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_member);
1258718292f2SDouglas Gregor       consumeToken();
1259718292f2SDouglas Gregor       break;
1260718292f2SDouglas Gregor     }
1261718292f2SDouglas Gregor   } while (!Done);
1262718292f2SDouglas Gregor 
1263718292f2SDouglas Gregor   if (Tok.is(MMToken::RBrace))
1264718292f2SDouglas Gregor     consumeToken();
1265718292f2SDouglas Gregor   else {
1266718292f2SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
1267718292f2SDouglas Gregor     Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
1268718292f2SDouglas Gregor     HadError = true;
1269718292f2SDouglas Gregor   }
1270718292f2SDouglas Gregor 
127111dfe6feSDouglas Gregor   // If the active module is a top-level framework, and there are no link
127211dfe6feSDouglas Gregor   // libraries, automatically link against the framework.
127311dfe6feSDouglas Gregor   if (ActiveModule->IsFramework && !ActiveModule->isSubFramework() &&
127411dfe6feSDouglas Gregor       ActiveModule->LinkLibraries.empty()) {
127511dfe6feSDouglas Gregor     inferFrameworkLink(ActiveModule, Directory, SourceMgr.getFileManager());
127611dfe6feSDouglas Gregor   }
127711dfe6feSDouglas Gregor 
1278e7ab3669SDouglas Gregor   // We're done parsing this module. Pop back to the previous module.
1279e7ab3669SDouglas Gregor   ActiveModule = PreviousActiveModule;
1280718292f2SDouglas Gregor }
1281718292f2SDouglas Gregor 
128297292843SDaniel Jasper /// \brief Parse an extern module declaration.
128397292843SDaniel Jasper ///
128497292843SDaniel Jasper ///   extern module-declaration:
128597292843SDaniel Jasper ///     'extern' 'module' module-id string-literal
128697292843SDaniel Jasper void ModuleMapParser::parseExternModuleDecl() {
128797292843SDaniel Jasper   assert(Tok.is(MMToken::ExternKeyword));
128897292843SDaniel Jasper   consumeToken(); // 'extern' keyword
128997292843SDaniel Jasper 
129097292843SDaniel Jasper   // Parse 'module' keyword.
129197292843SDaniel Jasper   if (!Tok.is(MMToken::ModuleKeyword)) {
129297292843SDaniel Jasper     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module);
129397292843SDaniel Jasper     consumeToken();
129497292843SDaniel Jasper     HadError = true;
129597292843SDaniel Jasper     return;
129697292843SDaniel Jasper   }
129797292843SDaniel Jasper   consumeToken(); // 'module' keyword
129897292843SDaniel Jasper 
129997292843SDaniel Jasper   // Parse the module name.
130097292843SDaniel Jasper   ModuleId Id;
130197292843SDaniel Jasper   if (parseModuleId(Id)) {
130297292843SDaniel Jasper     HadError = true;
130397292843SDaniel Jasper     return;
130497292843SDaniel Jasper   }
130597292843SDaniel Jasper 
130697292843SDaniel Jasper   // Parse the referenced module map file name.
130797292843SDaniel Jasper   if (!Tok.is(MMToken::StringLiteral)) {
130897292843SDaniel Jasper     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_mmap_file);
130997292843SDaniel Jasper     HadError = true;
131097292843SDaniel Jasper     return;
131197292843SDaniel Jasper   }
131297292843SDaniel Jasper   std::string FileName = Tok.getString();
131397292843SDaniel Jasper   consumeToken(); // filename
131497292843SDaniel Jasper 
131597292843SDaniel Jasper   StringRef FileNameRef = FileName;
131697292843SDaniel Jasper   SmallString<128> ModuleMapFileName;
131797292843SDaniel Jasper   if (llvm::sys::path::is_relative(FileNameRef)) {
131897292843SDaniel Jasper     ModuleMapFileName += Directory->getName();
131997292843SDaniel Jasper     llvm::sys::path::append(ModuleMapFileName, FileName);
132097292843SDaniel Jasper     FileNameRef = ModuleMapFileName.str();
132197292843SDaniel Jasper   }
132297292843SDaniel Jasper   if (const FileEntry *File = SourceMgr.getFileManager().getFile(FileNameRef))
132397292843SDaniel Jasper     Map.parseModuleMapFile(File, /*IsSystem=*/false);
132497292843SDaniel Jasper }
132597292843SDaniel Jasper 
13261fb5c3a6SDouglas Gregor /// \brief Parse a requires declaration.
13271fb5c3a6SDouglas Gregor ///
13281fb5c3a6SDouglas Gregor ///   requires-declaration:
13291fb5c3a6SDouglas Gregor ///     'requires' feature-list
13301fb5c3a6SDouglas Gregor ///
13311fb5c3a6SDouglas Gregor ///   feature-list:
13321fb5c3a6SDouglas Gregor ///     identifier ',' feature-list
13331fb5c3a6SDouglas Gregor ///     identifier
13341fb5c3a6SDouglas Gregor void ModuleMapParser::parseRequiresDecl() {
13351fb5c3a6SDouglas Gregor   assert(Tok.is(MMToken::RequiresKeyword));
13361fb5c3a6SDouglas Gregor 
13371fb5c3a6SDouglas Gregor   // Parse 'requires' keyword.
13381fb5c3a6SDouglas Gregor   consumeToken();
13391fb5c3a6SDouglas Gregor 
13401fb5c3a6SDouglas Gregor   // Parse the feature-list.
13411fb5c3a6SDouglas Gregor   do {
13421fb5c3a6SDouglas Gregor     if (!Tok.is(MMToken::Identifier)) {
13431fb5c3a6SDouglas Gregor       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_feature);
13441fb5c3a6SDouglas Gregor       HadError = true;
13451fb5c3a6SDouglas Gregor       return;
13461fb5c3a6SDouglas Gregor     }
13471fb5c3a6SDouglas Gregor 
13481fb5c3a6SDouglas Gregor     // Consume the feature name.
13491fb5c3a6SDouglas Gregor     std::string Feature = Tok.getString();
13501fb5c3a6SDouglas Gregor     consumeToken();
13511fb5c3a6SDouglas Gregor 
13521fb5c3a6SDouglas Gregor     // Add this feature.
135389929282SDouglas Gregor     ActiveModule->addRequirement(Feature, Map.LangOpts, *Map.Target);
13541fb5c3a6SDouglas Gregor 
13551fb5c3a6SDouglas Gregor     if (!Tok.is(MMToken::Comma))
13561fb5c3a6SDouglas Gregor       break;
13571fb5c3a6SDouglas Gregor 
13581fb5c3a6SDouglas Gregor     // Consume the comma.
13591fb5c3a6SDouglas Gregor     consumeToken();
13601fb5c3a6SDouglas Gregor   } while (true);
13611fb5c3a6SDouglas Gregor }
13621fb5c3a6SDouglas Gregor 
1363f2161a70SDouglas Gregor /// \brief Append to \p Paths the set of paths needed to get to the
1364f2161a70SDouglas Gregor /// subframework in which the given module lives.
1365bf8da9d7SBenjamin Kramer static void appendSubframeworkPaths(Module *Mod,
1366f857950dSDmitri Gribenko                                     SmallVectorImpl<char> &Path) {
1367f2161a70SDouglas Gregor   // Collect the framework names from the given module to the top-level module.
1368f857950dSDmitri Gribenko   SmallVector<StringRef, 2> Paths;
1369f2161a70SDouglas Gregor   for (; Mod; Mod = Mod->Parent) {
1370f2161a70SDouglas Gregor     if (Mod->IsFramework)
1371f2161a70SDouglas Gregor       Paths.push_back(Mod->Name);
1372f2161a70SDouglas Gregor   }
1373f2161a70SDouglas Gregor 
1374f2161a70SDouglas Gregor   if (Paths.empty())
1375f2161a70SDouglas Gregor     return;
1376f2161a70SDouglas Gregor 
1377f2161a70SDouglas Gregor   // Add Frameworks/Name.framework for each subframework.
137817381a06SBenjamin Kramer   for (unsigned I = Paths.size() - 1; I != 0; --I)
137917381a06SBenjamin Kramer     llvm::sys::path::append(Path, "Frameworks", Paths[I-1] + ".framework");
1380f2161a70SDouglas Gregor }
1381f2161a70SDouglas Gregor 
1382718292f2SDouglas Gregor /// \brief Parse a header declaration.
1383718292f2SDouglas Gregor ///
1384718292f2SDouglas Gregor ///   header-declaration:
1385322f633cSDouglas Gregor ///     'umbrella'[opt] 'header' string-literal
138659527666SDouglas Gregor ///     'exclude'[opt] 'header' string-literal
1387b53e5483SLawrence Crowl void ModuleMapParser::parseHeaderDecl(MMToken::TokenKind LeadingToken,
1388b53e5483SLawrence Crowl                                       SourceLocation LeadingLoc) {
1389718292f2SDouglas Gregor   assert(Tok.is(MMToken::HeaderKeyword));
13901871ed3dSBenjamin Kramer   consumeToken();
1391718292f2SDouglas Gregor 
1392718292f2SDouglas Gregor   // Parse the header name.
1393718292f2SDouglas Gregor   if (!Tok.is(MMToken::StringLiteral)) {
1394718292f2SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
1395718292f2SDouglas Gregor       << "header";
1396718292f2SDouglas Gregor     HadError = true;
1397718292f2SDouglas Gregor     return;
1398718292f2SDouglas Gregor   }
1399e7ab3669SDouglas Gregor   std::string FileName = Tok.getString();
1400718292f2SDouglas Gregor   SourceLocation FileNameLoc = consumeToken();
1401718292f2SDouglas Gregor 
1402524e33e1SDouglas Gregor   // Check whether we already have an umbrella.
1403b53e5483SLawrence Crowl   if (LeadingToken == MMToken::UmbrellaKeyword && ActiveModule->Umbrella) {
1404524e33e1SDouglas Gregor     Diags.Report(FileNameLoc, diag::err_mmap_umbrella_clash)
1405524e33e1SDouglas Gregor       << ActiveModule->getFullModuleName();
1406322f633cSDouglas Gregor     HadError = true;
1407322f633cSDouglas Gregor     return;
1408322f633cSDouglas Gregor   }
1409322f633cSDouglas Gregor 
14105257fc63SDouglas Gregor   // Look for this file.
1411e7ab3669SDouglas Gregor   const FileEntry *File = 0;
14123ec6663bSDouglas Gregor   const FileEntry *BuiltinFile = 0;
14132c1dd271SDylan Noblesmith   SmallString<128> PathName;
1414e7ab3669SDouglas Gregor   if (llvm::sys::path::is_absolute(FileName)) {
1415e7ab3669SDouglas Gregor     PathName = FileName;
1416e7ab3669SDouglas Gregor     File = SourceMgr.getFileManager().getFile(PathName);
14177033127bSDouglas Gregor   } else if (const DirectoryEntry *Dir = getOverriddenHeaderSearchDir()) {
14187033127bSDouglas Gregor     PathName = Dir->getName();
14197033127bSDouglas Gregor     llvm::sys::path::append(PathName, FileName);
14207033127bSDouglas Gregor     File = SourceMgr.getFileManager().getFile(PathName);
1421e7ab3669SDouglas Gregor   } else {
1422e7ab3669SDouglas Gregor     // Search for the header file within the search directory.
14237033127bSDouglas Gregor     PathName = Directory->getName();
1424e7ab3669SDouglas Gregor     unsigned PathLength = PathName.size();
1425755b2055SDouglas Gregor 
1426f2161a70SDouglas Gregor     if (ActiveModule->isPartOfFramework()) {
1427f2161a70SDouglas Gregor       appendSubframeworkPaths(ActiveModule, PathName);
1428755b2055SDouglas Gregor 
1429e7ab3669SDouglas Gregor       // Check whether this file is in the public headers.
143017381a06SBenjamin Kramer       llvm::sys::path::append(PathName, "Headers", FileName);
1431e7ab3669SDouglas Gregor       File = SourceMgr.getFileManager().getFile(PathName);
1432e7ab3669SDouglas Gregor 
1433e7ab3669SDouglas Gregor       if (!File) {
1434e7ab3669SDouglas Gregor         // Check whether this file is in the private headers.
1435e7ab3669SDouglas Gregor         PathName.resize(PathLength);
143617381a06SBenjamin Kramer         llvm::sys::path::append(PathName, "PrivateHeaders", FileName);
1437e7ab3669SDouglas Gregor         File = SourceMgr.getFileManager().getFile(PathName);
1438e7ab3669SDouglas Gregor       }
1439e7ab3669SDouglas Gregor     } else {
1440e7ab3669SDouglas Gregor       // Lookup for normal headers.
1441e7ab3669SDouglas Gregor       llvm::sys::path::append(PathName, FileName);
1442e7ab3669SDouglas Gregor       File = SourceMgr.getFileManager().getFile(PathName);
14433ec6663bSDouglas Gregor 
14443ec6663bSDouglas Gregor       // If this is a system module with a top-level header, this header
14453ec6663bSDouglas Gregor       // may have a counterpart (or replacement) in the set of headers
14463ec6663bSDouglas Gregor       // supplied by Clang. Find that builtin header.
1447b53e5483SLawrence Crowl       if (ActiveModule->IsSystem && LeadingToken != MMToken::UmbrellaKeyword &&
1448b53e5483SLawrence Crowl           BuiltinIncludeDir && BuiltinIncludeDir != Directory &&
1449b53e5483SLawrence Crowl           isBuiltinHeader(FileName)) {
14502c1dd271SDylan Noblesmith         SmallString<128> BuiltinPathName(BuiltinIncludeDir->getName());
14513ec6663bSDouglas Gregor         llvm::sys::path::append(BuiltinPathName, FileName);
14523ec6663bSDouglas Gregor         BuiltinFile = SourceMgr.getFileManager().getFile(BuiltinPathName);
14533ec6663bSDouglas Gregor 
14543ec6663bSDouglas Gregor         // If Clang supplies this header but the underlying system does not,
14553ec6663bSDouglas Gregor         // just silently swap in our builtin version. Otherwise, we'll end
14563ec6663bSDouglas Gregor         // up adding both (later).
14573ec6663bSDouglas Gregor         if (!File && BuiltinFile) {
14583ec6663bSDouglas Gregor           File = BuiltinFile;
14593ec6663bSDouglas Gregor           BuiltinFile = 0;
14603ec6663bSDouglas Gregor         }
14613ec6663bSDouglas Gregor       }
1462e7ab3669SDouglas Gregor     }
1463e7ab3669SDouglas Gregor   }
14645257fc63SDouglas Gregor 
14655257fc63SDouglas Gregor   // FIXME: We shouldn't be eagerly stat'ing every file named in a module map.
14665257fc63SDouglas Gregor   // Come up with a lazy way to do this.
1467e7ab3669SDouglas Gregor   if (File) {
146859527666SDouglas Gregor     if (ModuleMap::KnownHeader OwningModule = Map.Headers[File]) {
14695257fc63SDouglas Gregor       Diags.Report(FileNameLoc, diag::err_mmap_header_conflict)
147059527666SDouglas Gregor         << FileName << OwningModule.getModule()->getFullModuleName();
14715257fc63SDouglas Gregor       HadError = true;
1472b53e5483SLawrence Crowl     } else if (LeadingToken == MMToken::UmbrellaKeyword) {
1473322f633cSDouglas Gregor       const DirectoryEntry *UmbrellaDir = File->getDir();
147459527666SDouglas Gregor       if (Module *UmbrellaModule = Map.UmbrellaDirs[UmbrellaDir]) {
1475b53e5483SLawrence Crowl         Diags.Report(LeadingLoc, diag::err_mmap_umbrella_clash)
147659527666SDouglas Gregor           << UmbrellaModule->getFullModuleName();
1477322f633cSDouglas Gregor         HadError = true;
14785257fc63SDouglas Gregor       } else {
1479322f633cSDouglas Gregor         // Record this umbrella header.
1480322f633cSDouglas Gregor         Map.setUmbrellaHeader(ActiveModule, File);
1481322f633cSDouglas Gregor       }
1482322f633cSDouglas Gregor     } else {
1483322f633cSDouglas Gregor       // Record this header.
1484b53e5483SLawrence Crowl       ModuleMap::ModuleHeaderRole Role = ModuleMap::NormalHeader;
1485b53e5483SLawrence Crowl       if (LeadingToken == MMToken::ExcludeKeyword)
1486b53e5483SLawrence Crowl         Role = ModuleMap::ExcludedHeader;
1487b53e5483SLawrence Crowl       else if (LeadingToken == MMToken::PrivateKeyword)
1488b53e5483SLawrence Crowl         Role = ModuleMap::PrivateHeader;
1489b53e5483SLawrence Crowl       else
1490b53e5483SLawrence Crowl         assert(LeadingToken == MMToken::HeaderKeyword);
1491b53e5483SLawrence Crowl 
1492b53e5483SLawrence Crowl       Map.addHeader(ActiveModule, File, Role);
14933ec6663bSDouglas Gregor 
14943ec6663bSDouglas Gregor       // If there is a builtin counterpart to this file, add it now.
14953ec6663bSDouglas Gregor       if (BuiltinFile)
1496b53e5483SLawrence Crowl         Map.addHeader(ActiveModule, BuiltinFile, Role);
14975257fc63SDouglas Gregor     }
1498b53e5483SLawrence Crowl   } else if (LeadingToken != MMToken::ExcludeKeyword) {
14994b27a64bSDouglas Gregor     // Ignore excluded header files. They're optional anyway.
15004b27a64bSDouglas Gregor 
15015257fc63SDouglas Gregor     Diags.Report(FileNameLoc, diag::err_mmap_header_not_found)
1502b53e5483SLawrence Crowl       << (LeadingToken == MMToken::UmbrellaKeyword) << FileName;
15035257fc63SDouglas Gregor     HadError = true;
15045257fc63SDouglas Gregor   }
1505718292f2SDouglas Gregor }
1506718292f2SDouglas Gregor 
1507524e33e1SDouglas Gregor /// \brief Parse an umbrella directory declaration.
1508524e33e1SDouglas Gregor ///
1509524e33e1SDouglas Gregor ///   umbrella-dir-declaration:
1510524e33e1SDouglas Gregor ///     umbrella string-literal
1511524e33e1SDouglas Gregor void ModuleMapParser::parseUmbrellaDirDecl(SourceLocation UmbrellaLoc) {
1512524e33e1SDouglas Gregor   // Parse the directory name.
1513524e33e1SDouglas Gregor   if (!Tok.is(MMToken::StringLiteral)) {
1514524e33e1SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
1515524e33e1SDouglas Gregor       << "umbrella";
1516524e33e1SDouglas Gregor     HadError = true;
1517524e33e1SDouglas Gregor     return;
1518524e33e1SDouglas Gregor   }
1519524e33e1SDouglas Gregor 
1520524e33e1SDouglas Gregor   std::string DirName = Tok.getString();
1521524e33e1SDouglas Gregor   SourceLocation DirNameLoc = consumeToken();
1522524e33e1SDouglas Gregor 
1523524e33e1SDouglas Gregor   // Check whether we already have an umbrella.
1524524e33e1SDouglas Gregor   if (ActiveModule->Umbrella) {
1525524e33e1SDouglas Gregor     Diags.Report(DirNameLoc, diag::err_mmap_umbrella_clash)
1526524e33e1SDouglas Gregor       << ActiveModule->getFullModuleName();
1527524e33e1SDouglas Gregor     HadError = true;
1528524e33e1SDouglas Gregor     return;
1529524e33e1SDouglas Gregor   }
1530524e33e1SDouglas Gregor 
1531524e33e1SDouglas Gregor   // Look for this file.
1532524e33e1SDouglas Gregor   const DirectoryEntry *Dir = 0;
1533524e33e1SDouglas Gregor   if (llvm::sys::path::is_absolute(DirName))
1534524e33e1SDouglas Gregor     Dir = SourceMgr.getFileManager().getDirectory(DirName);
1535524e33e1SDouglas Gregor   else {
15362c1dd271SDylan Noblesmith     SmallString<128> PathName;
1537524e33e1SDouglas Gregor     PathName = Directory->getName();
1538524e33e1SDouglas Gregor     llvm::sys::path::append(PathName, DirName);
1539524e33e1SDouglas Gregor     Dir = SourceMgr.getFileManager().getDirectory(PathName);
1540524e33e1SDouglas Gregor   }
1541524e33e1SDouglas Gregor 
1542524e33e1SDouglas Gregor   if (!Dir) {
1543524e33e1SDouglas Gregor     Diags.Report(DirNameLoc, diag::err_mmap_umbrella_dir_not_found)
1544524e33e1SDouglas Gregor       << DirName;
1545524e33e1SDouglas Gregor     HadError = true;
1546524e33e1SDouglas Gregor     return;
1547524e33e1SDouglas Gregor   }
1548524e33e1SDouglas Gregor 
1549524e33e1SDouglas Gregor   if (Module *OwningModule = Map.UmbrellaDirs[Dir]) {
1550524e33e1SDouglas Gregor     Diags.Report(UmbrellaLoc, diag::err_mmap_umbrella_clash)
1551524e33e1SDouglas Gregor       << OwningModule->getFullModuleName();
1552524e33e1SDouglas Gregor     HadError = true;
1553524e33e1SDouglas Gregor     return;
1554524e33e1SDouglas Gregor   }
1555524e33e1SDouglas Gregor 
1556524e33e1SDouglas Gregor   // Record this umbrella directory.
1557524e33e1SDouglas Gregor   Map.setUmbrellaDir(ActiveModule, Dir);
1558524e33e1SDouglas Gregor }
1559524e33e1SDouglas Gregor 
15602b82c2a5SDouglas Gregor /// \brief Parse a module export declaration.
15612b82c2a5SDouglas Gregor ///
15622b82c2a5SDouglas Gregor ///   export-declaration:
15632b82c2a5SDouglas Gregor ///     'export' wildcard-module-id
15642b82c2a5SDouglas Gregor ///
15652b82c2a5SDouglas Gregor ///   wildcard-module-id:
15662b82c2a5SDouglas Gregor ///     identifier
15672b82c2a5SDouglas Gregor ///     '*'
15682b82c2a5SDouglas Gregor ///     identifier '.' wildcard-module-id
15692b82c2a5SDouglas Gregor void ModuleMapParser::parseExportDecl() {
15702b82c2a5SDouglas Gregor   assert(Tok.is(MMToken::ExportKeyword));
15712b82c2a5SDouglas Gregor   SourceLocation ExportLoc = consumeToken();
15722b82c2a5SDouglas Gregor 
15732b82c2a5SDouglas Gregor   // Parse the module-id with an optional wildcard at the end.
15742b82c2a5SDouglas Gregor   ModuleId ParsedModuleId;
15752b82c2a5SDouglas Gregor   bool Wildcard = false;
15762b82c2a5SDouglas Gregor   do {
15772b82c2a5SDouglas Gregor     if (Tok.is(MMToken::Identifier)) {
15782b82c2a5SDouglas Gregor       ParsedModuleId.push_back(std::make_pair(Tok.getString(),
15792b82c2a5SDouglas Gregor                                               Tok.getLocation()));
15802b82c2a5SDouglas Gregor       consumeToken();
15812b82c2a5SDouglas Gregor 
15822b82c2a5SDouglas Gregor       if (Tok.is(MMToken::Period)) {
15832b82c2a5SDouglas Gregor         consumeToken();
15842b82c2a5SDouglas Gregor         continue;
15852b82c2a5SDouglas Gregor       }
15862b82c2a5SDouglas Gregor 
15872b82c2a5SDouglas Gregor       break;
15882b82c2a5SDouglas Gregor     }
15892b82c2a5SDouglas Gregor 
15902b82c2a5SDouglas Gregor     if(Tok.is(MMToken::Star)) {
15912b82c2a5SDouglas Gregor       Wildcard = true;
1592f5eedd05SDouglas Gregor       consumeToken();
15932b82c2a5SDouglas Gregor       break;
15942b82c2a5SDouglas Gregor     }
15952b82c2a5SDouglas Gregor 
15962b82c2a5SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_export_module_id);
15972b82c2a5SDouglas Gregor     HadError = true;
15982b82c2a5SDouglas Gregor     return;
15992b82c2a5SDouglas Gregor   } while (true);
16002b82c2a5SDouglas Gregor 
16012b82c2a5SDouglas Gregor   Module::UnresolvedExportDecl Unresolved = {
16022b82c2a5SDouglas Gregor     ExportLoc, ParsedModuleId, Wildcard
16032b82c2a5SDouglas Gregor   };
16042b82c2a5SDouglas Gregor   ActiveModule->UnresolvedExports.push_back(Unresolved);
16052b82c2a5SDouglas Gregor }
16062b82c2a5SDouglas Gregor 
16076ddfca91SDouglas Gregor /// \brief Parse a link declaration.
16086ddfca91SDouglas Gregor ///
16096ddfca91SDouglas Gregor ///   module-declaration:
16106ddfca91SDouglas Gregor ///     'link' 'framework'[opt] string-literal
16116ddfca91SDouglas Gregor void ModuleMapParser::parseLinkDecl() {
16126ddfca91SDouglas Gregor   assert(Tok.is(MMToken::LinkKeyword));
16136ddfca91SDouglas Gregor   SourceLocation LinkLoc = consumeToken();
16146ddfca91SDouglas Gregor 
16156ddfca91SDouglas Gregor   // Parse the optional 'framework' keyword.
16166ddfca91SDouglas Gregor   bool IsFramework = false;
16176ddfca91SDouglas Gregor   if (Tok.is(MMToken::FrameworkKeyword)) {
16186ddfca91SDouglas Gregor     consumeToken();
16196ddfca91SDouglas Gregor     IsFramework = true;
16206ddfca91SDouglas Gregor   }
16216ddfca91SDouglas Gregor 
16226ddfca91SDouglas Gregor   // Parse the library name
16236ddfca91SDouglas Gregor   if (!Tok.is(MMToken::StringLiteral)) {
16246ddfca91SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_library_name)
16256ddfca91SDouglas Gregor       << IsFramework << SourceRange(LinkLoc);
16266ddfca91SDouglas Gregor     HadError = true;
16276ddfca91SDouglas Gregor     return;
16286ddfca91SDouglas Gregor   }
16296ddfca91SDouglas Gregor 
16306ddfca91SDouglas Gregor   std::string LibraryName = Tok.getString();
16316ddfca91SDouglas Gregor   consumeToken();
16326ddfca91SDouglas Gregor   ActiveModule->LinkLibraries.push_back(Module::LinkLibrary(LibraryName,
16336ddfca91SDouglas Gregor                                                             IsFramework));
16346ddfca91SDouglas Gregor }
16356ddfca91SDouglas Gregor 
163635b13eceSDouglas Gregor /// \brief Parse a configuration macro declaration.
163735b13eceSDouglas Gregor ///
163835b13eceSDouglas Gregor ///   module-declaration:
163935b13eceSDouglas Gregor ///     'config_macros' attributes[opt] config-macro-list?
164035b13eceSDouglas Gregor ///
164135b13eceSDouglas Gregor ///   config-macro-list:
164235b13eceSDouglas Gregor ///     identifier (',' identifier)?
164335b13eceSDouglas Gregor void ModuleMapParser::parseConfigMacros() {
164435b13eceSDouglas Gregor   assert(Tok.is(MMToken::ConfigMacros));
164535b13eceSDouglas Gregor   SourceLocation ConfigMacrosLoc = consumeToken();
164635b13eceSDouglas Gregor 
164735b13eceSDouglas Gregor   // Only top-level modules can have configuration macros.
164835b13eceSDouglas Gregor   if (ActiveModule->Parent) {
164935b13eceSDouglas Gregor     Diags.Report(ConfigMacrosLoc, diag::err_mmap_config_macro_submodule);
165035b13eceSDouglas Gregor   }
165135b13eceSDouglas Gregor 
165235b13eceSDouglas Gregor   // Parse the optional attributes.
165335b13eceSDouglas Gregor   Attributes Attrs;
165435b13eceSDouglas Gregor   parseOptionalAttributes(Attrs);
165535b13eceSDouglas Gregor   if (Attrs.IsExhaustive && !ActiveModule->Parent) {
165635b13eceSDouglas Gregor     ActiveModule->ConfigMacrosExhaustive = true;
165735b13eceSDouglas Gregor   }
165835b13eceSDouglas Gregor 
165935b13eceSDouglas Gregor   // If we don't have an identifier, we're done.
166035b13eceSDouglas Gregor   if (!Tok.is(MMToken::Identifier))
166135b13eceSDouglas Gregor     return;
166235b13eceSDouglas Gregor 
166335b13eceSDouglas Gregor   // Consume the first identifier.
166435b13eceSDouglas Gregor   if (!ActiveModule->Parent) {
166535b13eceSDouglas Gregor     ActiveModule->ConfigMacros.push_back(Tok.getString().str());
166635b13eceSDouglas Gregor   }
166735b13eceSDouglas Gregor   consumeToken();
166835b13eceSDouglas Gregor 
166935b13eceSDouglas Gregor   do {
167035b13eceSDouglas Gregor     // If there's a comma, consume it.
167135b13eceSDouglas Gregor     if (!Tok.is(MMToken::Comma))
167235b13eceSDouglas Gregor       break;
167335b13eceSDouglas Gregor     consumeToken();
167435b13eceSDouglas Gregor 
167535b13eceSDouglas Gregor     // We expect to see a macro name here.
167635b13eceSDouglas Gregor     if (!Tok.is(MMToken::Identifier)) {
167735b13eceSDouglas Gregor       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_config_macro);
167835b13eceSDouglas Gregor       break;
167935b13eceSDouglas Gregor     }
168035b13eceSDouglas Gregor 
168135b13eceSDouglas Gregor     // Consume the macro name.
168235b13eceSDouglas Gregor     if (!ActiveModule->Parent) {
168335b13eceSDouglas Gregor       ActiveModule->ConfigMacros.push_back(Tok.getString().str());
168435b13eceSDouglas Gregor     }
168535b13eceSDouglas Gregor     consumeToken();
168635b13eceSDouglas Gregor   } while (true);
168735b13eceSDouglas Gregor }
168835b13eceSDouglas Gregor 
1689fb912657SDouglas Gregor /// \brief Format a module-id into a string.
1690fb912657SDouglas Gregor static std::string formatModuleId(const ModuleId &Id) {
1691fb912657SDouglas Gregor   std::string result;
1692fb912657SDouglas Gregor   {
1693fb912657SDouglas Gregor     llvm::raw_string_ostream OS(result);
1694fb912657SDouglas Gregor 
1695fb912657SDouglas Gregor     for (unsigned I = 0, N = Id.size(); I != N; ++I) {
1696fb912657SDouglas Gregor       if (I)
1697fb912657SDouglas Gregor         OS << ".";
1698fb912657SDouglas Gregor       OS << Id[I].first;
1699fb912657SDouglas Gregor     }
1700fb912657SDouglas Gregor   }
1701fb912657SDouglas Gregor 
1702fb912657SDouglas Gregor   return result;
1703fb912657SDouglas Gregor }
1704fb912657SDouglas Gregor 
1705fb912657SDouglas Gregor /// \brief Parse a conflict declaration.
1706fb912657SDouglas Gregor ///
1707fb912657SDouglas Gregor ///   module-declaration:
1708fb912657SDouglas Gregor ///     'conflict' module-id ',' string-literal
1709fb912657SDouglas Gregor void ModuleMapParser::parseConflict() {
1710fb912657SDouglas Gregor   assert(Tok.is(MMToken::Conflict));
1711fb912657SDouglas Gregor   SourceLocation ConflictLoc = consumeToken();
1712fb912657SDouglas Gregor   Module::UnresolvedConflict Conflict;
1713fb912657SDouglas Gregor 
1714fb912657SDouglas Gregor   // Parse the module-id.
1715fb912657SDouglas Gregor   if (parseModuleId(Conflict.Id))
1716fb912657SDouglas Gregor     return;
1717fb912657SDouglas Gregor 
1718fb912657SDouglas Gregor   // Parse the ','.
1719fb912657SDouglas Gregor   if (!Tok.is(MMToken::Comma)) {
1720fb912657SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_conflicts_comma)
1721fb912657SDouglas Gregor       << SourceRange(ConflictLoc);
1722fb912657SDouglas Gregor     return;
1723fb912657SDouglas Gregor   }
1724fb912657SDouglas Gregor   consumeToken();
1725fb912657SDouglas Gregor 
1726fb912657SDouglas Gregor   // Parse the message.
1727fb912657SDouglas Gregor   if (!Tok.is(MMToken::StringLiteral)) {
1728fb912657SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_conflicts_message)
1729fb912657SDouglas Gregor       << formatModuleId(Conflict.Id);
1730fb912657SDouglas Gregor     return;
1731fb912657SDouglas Gregor   }
1732fb912657SDouglas Gregor   Conflict.Message = Tok.getString().str();
1733fb912657SDouglas Gregor   consumeToken();
1734fb912657SDouglas Gregor 
1735fb912657SDouglas Gregor   // Add this unresolved conflict.
1736fb912657SDouglas Gregor   ActiveModule->UnresolvedConflicts.push_back(Conflict);
1737fb912657SDouglas Gregor }
1738fb912657SDouglas Gregor 
17396ddfca91SDouglas Gregor /// \brief Parse an inferred module declaration (wildcard modules).
17409194a91dSDouglas Gregor ///
17419194a91dSDouglas Gregor ///   module-declaration:
17429194a91dSDouglas Gregor ///     'explicit'[opt] 'framework'[opt] 'module' * attributes[opt]
17439194a91dSDouglas Gregor ///       { inferred-module-member* }
17449194a91dSDouglas Gregor ///
17459194a91dSDouglas Gregor ///   inferred-module-member:
17469194a91dSDouglas Gregor ///     'export' '*'
17479194a91dSDouglas Gregor ///     'exclude' identifier
17489194a91dSDouglas Gregor void ModuleMapParser::parseInferredModuleDecl(bool Framework, bool Explicit) {
174973441091SDouglas Gregor   assert(Tok.is(MMToken::Star));
175073441091SDouglas Gregor   SourceLocation StarLoc = consumeToken();
175173441091SDouglas Gregor   bool Failed = false;
175273441091SDouglas Gregor 
175373441091SDouglas Gregor   // Inferred modules must be submodules.
17549194a91dSDouglas Gregor   if (!ActiveModule && !Framework) {
175573441091SDouglas Gregor     Diags.Report(StarLoc, diag::err_mmap_top_level_inferred_submodule);
175673441091SDouglas Gregor     Failed = true;
175773441091SDouglas Gregor   }
175873441091SDouglas Gregor 
17599194a91dSDouglas Gregor   if (ActiveModule) {
1760524e33e1SDouglas Gregor     // Inferred modules must have umbrella directories.
1761524e33e1SDouglas Gregor     if (!Failed && !ActiveModule->getUmbrellaDir()) {
176273441091SDouglas Gregor       Diags.Report(StarLoc, diag::err_mmap_inferred_no_umbrella);
176373441091SDouglas Gregor       Failed = true;
176473441091SDouglas Gregor     }
176573441091SDouglas Gregor 
176673441091SDouglas Gregor     // Check for redefinition of an inferred module.
1767dd005f69SDouglas Gregor     if (!Failed && ActiveModule->InferSubmodules) {
176873441091SDouglas Gregor       Diags.Report(StarLoc, diag::err_mmap_inferred_redef);
1769dd005f69SDouglas Gregor       if (ActiveModule->InferredSubmoduleLoc.isValid())
1770dd005f69SDouglas Gregor         Diags.Report(ActiveModule->InferredSubmoduleLoc,
177173441091SDouglas Gregor                      diag::note_mmap_prev_definition);
177273441091SDouglas Gregor       Failed = true;
177373441091SDouglas Gregor     }
177473441091SDouglas Gregor 
17759194a91dSDouglas Gregor     // Check for the 'framework' keyword, which is not permitted here.
17769194a91dSDouglas Gregor     if (Framework) {
17779194a91dSDouglas Gregor       Diags.Report(StarLoc, diag::err_mmap_inferred_framework_submodule);
17789194a91dSDouglas Gregor       Framework = false;
17799194a91dSDouglas Gregor     }
17809194a91dSDouglas Gregor   } else if (Explicit) {
17819194a91dSDouglas Gregor     Diags.Report(StarLoc, diag::err_mmap_explicit_inferred_framework);
17829194a91dSDouglas Gregor     Explicit = false;
17839194a91dSDouglas Gregor   }
17849194a91dSDouglas Gregor 
178573441091SDouglas Gregor   // If there were any problems with this inferred submodule, skip its body.
178673441091SDouglas Gregor   if (Failed) {
178773441091SDouglas Gregor     if (Tok.is(MMToken::LBrace)) {
178873441091SDouglas Gregor       consumeToken();
178973441091SDouglas Gregor       skipUntil(MMToken::RBrace);
179073441091SDouglas Gregor       if (Tok.is(MMToken::RBrace))
179173441091SDouglas Gregor         consumeToken();
179273441091SDouglas Gregor     }
179373441091SDouglas Gregor     HadError = true;
179473441091SDouglas Gregor     return;
179573441091SDouglas Gregor   }
179673441091SDouglas Gregor 
17979194a91dSDouglas Gregor   // Parse optional attributes.
17984442605fSBill Wendling   Attributes Attrs;
17999194a91dSDouglas Gregor   parseOptionalAttributes(Attrs);
18009194a91dSDouglas Gregor 
18019194a91dSDouglas Gregor   if (ActiveModule) {
180273441091SDouglas Gregor     // Note that we have an inferred submodule.
1803dd005f69SDouglas Gregor     ActiveModule->InferSubmodules = true;
1804dd005f69SDouglas Gregor     ActiveModule->InferredSubmoduleLoc = StarLoc;
1805dd005f69SDouglas Gregor     ActiveModule->InferExplicitSubmodules = Explicit;
18069194a91dSDouglas Gregor   } else {
18079194a91dSDouglas Gregor     // We'll be inferring framework modules for this directory.
18089194a91dSDouglas Gregor     Map.InferredDirectories[Directory].InferModules = true;
18099194a91dSDouglas Gregor     Map.InferredDirectories[Directory].InferSystemModules = Attrs.IsSystem;
18109194a91dSDouglas Gregor   }
181173441091SDouglas Gregor 
181273441091SDouglas Gregor   // Parse the opening brace.
181373441091SDouglas Gregor   if (!Tok.is(MMToken::LBrace)) {
181473441091SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_lbrace_wildcard);
181573441091SDouglas Gregor     HadError = true;
181673441091SDouglas Gregor     return;
181773441091SDouglas Gregor   }
181873441091SDouglas Gregor   SourceLocation LBraceLoc = consumeToken();
181973441091SDouglas Gregor 
182073441091SDouglas Gregor   // Parse the body of the inferred submodule.
182173441091SDouglas Gregor   bool Done = false;
182273441091SDouglas Gregor   do {
182373441091SDouglas Gregor     switch (Tok.Kind) {
182473441091SDouglas Gregor     case MMToken::EndOfFile:
182573441091SDouglas Gregor     case MMToken::RBrace:
182673441091SDouglas Gregor       Done = true;
182773441091SDouglas Gregor       break;
182873441091SDouglas Gregor 
18299194a91dSDouglas Gregor     case MMToken::ExcludeKeyword: {
18309194a91dSDouglas Gregor       if (ActiveModule) {
18319194a91dSDouglas Gregor         Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member)
1832162405daSDouglas Gregor           << (ActiveModule != 0);
18339194a91dSDouglas Gregor         consumeToken();
18349194a91dSDouglas Gregor         break;
18359194a91dSDouglas Gregor       }
18369194a91dSDouglas Gregor 
18379194a91dSDouglas Gregor       consumeToken();
18389194a91dSDouglas Gregor       if (!Tok.is(MMToken::Identifier)) {
18399194a91dSDouglas Gregor         Diags.Report(Tok.getLocation(), diag::err_mmap_missing_exclude_name);
18409194a91dSDouglas Gregor         break;
18419194a91dSDouglas Gregor       }
18429194a91dSDouglas Gregor 
18439194a91dSDouglas Gregor       Map.InferredDirectories[Directory].ExcludedModules
18449194a91dSDouglas Gregor         .push_back(Tok.getString());
18459194a91dSDouglas Gregor       consumeToken();
18469194a91dSDouglas Gregor       break;
18479194a91dSDouglas Gregor     }
18489194a91dSDouglas Gregor 
18499194a91dSDouglas Gregor     case MMToken::ExportKeyword:
18509194a91dSDouglas Gregor       if (!ActiveModule) {
18519194a91dSDouglas Gregor         Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member)
1852162405daSDouglas Gregor           << (ActiveModule != 0);
18539194a91dSDouglas Gregor         consumeToken();
18549194a91dSDouglas Gregor         break;
18559194a91dSDouglas Gregor       }
18569194a91dSDouglas Gregor 
185773441091SDouglas Gregor       consumeToken();
185873441091SDouglas Gregor       if (Tok.is(MMToken::Star))
1859dd005f69SDouglas Gregor         ActiveModule->InferExportWildcard = true;
186073441091SDouglas Gregor       else
186173441091SDouglas Gregor         Diags.Report(Tok.getLocation(),
186273441091SDouglas Gregor                      diag::err_mmap_expected_export_wildcard);
186373441091SDouglas Gregor       consumeToken();
186473441091SDouglas Gregor       break;
186573441091SDouglas Gregor 
186673441091SDouglas Gregor     case MMToken::ExplicitKeyword:
186773441091SDouglas Gregor     case MMToken::ModuleKeyword:
186873441091SDouglas Gregor     case MMToken::HeaderKeyword:
1869b53e5483SLawrence Crowl     case MMToken::PrivateKeyword:
187073441091SDouglas Gregor     case MMToken::UmbrellaKeyword:
187173441091SDouglas Gregor     default:
18729194a91dSDouglas Gregor       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member)
1873162405daSDouglas Gregor           << (ActiveModule != 0);
187473441091SDouglas Gregor       consumeToken();
187573441091SDouglas Gregor       break;
187673441091SDouglas Gregor     }
187773441091SDouglas Gregor   } while (!Done);
187873441091SDouglas Gregor 
187973441091SDouglas Gregor   if (Tok.is(MMToken::RBrace))
188073441091SDouglas Gregor     consumeToken();
188173441091SDouglas Gregor   else {
188273441091SDouglas Gregor     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
188373441091SDouglas Gregor     Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
188473441091SDouglas Gregor     HadError = true;
188573441091SDouglas Gregor   }
188673441091SDouglas Gregor }
188773441091SDouglas Gregor 
18889194a91dSDouglas Gregor /// \brief Parse optional attributes.
18899194a91dSDouglas Gregor ///
18909194a91dSDouglas Gregor ///   attributes:
18919194a91dSDouglas Gregor ///     attribute attributes
18929194a91dSDouglas Gregor ///     attribute
18939194a91dSDouglas Gregor ///
18949194a91dSDouglas Gregor ///   attribute:
18959194a91dSDouglas Gregor ///     [ identifier ]
18969194a91dSDouglas Gregor ///
18979194a91dSDouglas Gregor /// \param Attrs Will be filled in with the parsed attributes.
18989194a91dSDouglas Gregor ///
18999194a91dSDouglas Gregor /// \returns true if an error occurred, false otherwise.
19004442605fSBill Wendling bool ModuleMapParser::parseOptionalAttributes(Attributes &Attrs) {
19019194a91dSDouglas Gregor   bool HadError = false;
19029194a91dSDouglas Gregor 
19039194a91dSDouglas Gregor   while (Tok.is(MMToken::LSquare)) {
19049194a91dSDouglas Gregor     // Consume the '['.
19059194a91dSDouglas Gregor     SourceLocation LSquareLoc = consumeToken();
19069194a91dSDouglas Gregor 
19079194a91dSDouglas Gregor     // Check whether we have an attribute name here.
19089194a91dSDouglas Gregor     if (!Tok.is(MMToken::Identifier)) {
19099194a91dSDouglas Gregor       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_attribute);
19109194a91dSDouglas Gregor       skipUntil(MMToken::RSquare);
19119194a91dSDouglas Gregor       if (Tok.is(MMToken::RSquare))
19129194a91dSDouglas Gregor         consumeToken();
19139194a91dSDouglas Gregor       HadError = true;
19149194a91dSDouglas Gregor     }
19159194a91dSDouglas Gregor 
19169194a91dSDouglas Gregor     // Decode the attribute name.
19179194a91dSDouglas Gregor     AttributeKind Attribute
19189194a91dSDouglas Gregor       = llvm::StringSwitch<AttributeKind>(Tok.getString())
191935b13eceSDouglas Gregor           .Case("exhaustive", AT_exhaustive)
19209194a91dSDouglas Gregor           .Case("system", AT_system)
19219194a91dSDouglas Gregor           .Default(AT_unknown);
19229194a91dSDouglas Gregor     switch (Attribute) {
19239194a91dSDouglas Gregor     case AT_unknown:
19249194a91dSDouglas Gregor       Diags.Report(Tok.getLocation(), diag::warn_mmap_unknown_attribute)
19259194a91dSDouglas Gregor         << Tok.getString();
19269194a91dSDouglas Gregor       break;
19279194a91dSDouglas Gregor 
19289194a91dSDouglas Gregor     case AT_system:
19299194a91dSDouglas Gregor       Attrs.IsSystem = true;
19309194a91dSDouglas Gregor       break;
193135b13eceSDouglas Gregor 
193235b13eceSDouglas Gregor     case AT_exhaustive:
193335b13eceSDouglas Gregor       Attrs.IsExhaustive = true;
193435b13eceSDouglas Gregor       break;
19359194a91dSDouglas Gregor     }
19369194a91dSDouglas Gregor     consumeToken();
19379194a91dSDouglas Gregor 
19389194a91dSDouglas Gregor     // Consume the ']'.
19399194a91dSDouglas Gregor     if (!Tok.is(MMToken::RSquare)) {
19409194a91dSDouglas Gregor       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rsquare);
19419194a91dSDouglas Gregor       Diags.Report(LSquareLoc, diag::note_mmap_lsquare_match);
19429194a91dSDouglas Gregor       skipUntil(MMToken::RSquare);
19439194a91dSDouglas Gregor       HadError = true;
19449194a91dSDouglas Gregor     }
19459194a91dSDouglas Gregor 
19469194a91dSDouglas Gregor     if (Tok.is(MMToken::RSquare))
19479194a91dSDouglas Gregor       consumeToken();
19489194a91dSDouglas Gregor   }
19499194a91dSDouglas Gregor 
19509194a91dSDouglas Gregor   return HadError;
19519194a91dSDouglas Gregor }
19529194a91dSDouglas Gregor 
19537033127bSDouglas Gregor /// \brief If there is a specific header search directory due the presence
19547033127bSDouglas Gregor /// of an umbrella directory, retrieve that directory. Otherwise, returns null.
19557033127bSDouglas Gregor const DirectoryEntry *ModuleMapParser::getOverriddenHeaderSearchDir() {
19567033127bSDouglas Gregor   for (Module *Mod = ActiveModule; Mod; Mod = Mod->Parent) {
19577033127bSDouglas Gregor     // If we have an umbrella directory, use that.
19587033127bSDouglas Gregor     if (Mod->hasUmbrellaDir())
19597033127bSDouglas Gregor       return Mod->getUmbrellaDir();
19607033127bSDouglas Gregor 
19617033127bSDouglas Gregor     // If we have a framework directory, stop looking.
19627033127bSDouglas Gregor     if (Mod->IsFramework)
19637033127bSDouglas Gregor       return 0;
19647033127bSDouglas Gregor   }
19657033127bSDouglas Gregor 
19667033127bSDouglas Gregor   return 0;
19677033127bSDouglas Gregor }
19687033127bSDouglas Gregor 
1969718292f2SDouglas Gregor /// \brief Parse a module map file.
1970718292f2SDouglas Gregor ///
1971718292f2SDouglas Gregor ///   module-map-file:
1972718292f2SDouglas Gregor ///     module-declaration*
1973718292f2SDouglas Gregor bool ModuleMapParser::parseModuleMapFile() {
1974718292f2SDouglas Gregor   do {
1975718292f2SDouglas Gregor     switch (Tok.Kind) {
1976718292f2SDouglas Gregor     case MMToken::EndOfFile:
1977718292f2SDouglas Gregor       return HadError;
1978718292f2SDouglas Gregor 
1979e7ab3669SDouglas Gregor     case MMToken::ExplicitKeyword:
198097292843SDaniel Jasper     case MMToken::ExternKeyword:
1981718292f2SDouglas Gregor     case MMToken::ModuleKeyword:
1982755b2055SDouglas Gregor     case MMToken::FrameworkKeyword:
1983718292f2SDouglas Gregor       parseModuleDecl();
1984718292f2SDouglas Gregor       break;
1985718292f2SDouglas Gregor 
19861fb5c3a6SDouglas Gregor     case MMToken::Comma:
198735b13eceSDouglas Gregor     case MMToken::ConfigMacros:
1988fb912657SDouglas Gregor     case MMToken::Conflict:
198959527666SDouglas Gregor     case MMToken::ExcludeKeyword:
19902b82c2a5SDouglas Gregor     case MMToken::ExportKeyword:
1991718292f2SDouglas Gregor     case MMToken::HeaderKeyword:
1992718292f2SDouglas Gregor     case MMToken::Identifier:
1993718292f2SDouglas Gregor     case MMToken::LBrace:
19946ddfca91SDouglas Gregor     case MMToken::LinkKeyword:
1995a686e1b0SDouglas Gregor     case MMToken::LSquare:
19962b82c2a5SDouglas Gregor     case MMToken::Period:
1997b53e5483SLawrence Crowl     case MMToken::PrivateKeyword:
1998718292f2SDouglas Gregor     case MMToken::RBrace:
1999a686e1b0SDouglas Gregor     case MMToken::RSquare:
20001fb5c3a6SDouglas Gregor     case MMToken::RequiresKeyword:
20012b82c2a5SDouglas Gregor     case MMToken::Star:
2002718292f2SDouglas Gregor     case MMToken::StringLiteral:
2003718292f2SDouglas Gregor     case MMToken::UmbrellaKeyword:
2004718292f2SDouglas Gregor       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module);
2005718292f2SDouglas Gregor       HadError = true;
2006718292f2SDouglas Gregor       consumeToken();
2007718292f2SDouglas Gregor       break;
2008718292f2SDouglas Gregor     }
2009718292f2SDouglas Gregor   } while (true);
2010718292f2SDouglas Gregor }
2011718292f2SDouglas Gregor 
2012963c5535SDouglas Gregor bool ModuleMap::parseModuleMapFile(const FileEntry *File, bool IsSystem) {
20134ddf2221SDouglas Gregor   llvm::DenseMap<const FileEntry *, bool>::iterator Known
20144ddf2221SDouglas Gregor     = ParsedModuleMap.find(File);
20154ddf2221SDouglas Gregor   if (Known != ParsedModuleMap.end())
20164ddf2221SDouglas Gregor     return Known->second;
20174ddf2221SDouglas Gregor 
201889929282SDouglas Gregor   assert(Target != 0 && "Missing target information");
2019718292f2SDouglas Gregor   FileID ID = SourceMgr->createFileID(File, SourceLocation(), SrcMgr::C_User);
2020718292f2SDouglas Gregor   const llvm::MemoryBuffer *Buffer = SourceMgr->getBuffer(ID);
2021718292f2SDouglas Gregor   if (!Buffer)
20224ddf2221SDouglas Gregor     return ParsedModuleMap[File] = true;
2023718292f2SDouglas Gregor 
2024718292f2SDouglas Gregor   // Parse this module map file.
20251fb5c3a6SDouglas Gregor   Lexer L(ID, SourceMgr->getBuffer(ID), *SourceMgr, MMapLangOpts);
20261fb5c3a6SDouglas Gregor   Diags->getClient()->BeginSourceFile(MMapLangOpts);
2027bc10b9fbSDouglas Gregor   ModuleMapParser Parser(L, *SourceMgr, Target, *Diags, *this, File->getDir(),
2028963c5535SDouglas Gregor                          BuiltinIncludeDir, IsSystem);
2029718292f2SDouglas Gregor   bool Result = Parser.parseModuleMapFile();
2030718292f2SDouglas Gregor   Diags->getClient()->EndSourceFile();
20314ddf2221SDouglas Gregor   ParsedModuleMap[File] = Result;
2032718292f2SDouglas Gregor   return Result;
2033718292f2SDouglas Gregor }
2034