1 //===--- ModuleMap.cpp - Describe the layout of modules ---------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the ModuleMap implementation, which describes the layout
11 // of a module as it relates to headers.
12 //
13 //===----------------------------------------------------------------------===//
14 #include "clang/Lex/ModuleMap.h"
15 #include "clang/Basic/CharInfo.h"
16 #include "clang/Basic/Diagnostic.h"
17 #include "clang/Basic/DiagnosticOptions.h"
18 #include "clang/Basic/FileManager.h"
19 #include "clang/Basic/TargetInfo.h"
20 #include "clang/Basic/TargetOptions.h"
21 #include "clang/Lex/HeaderSearch.h"
22 #include "clang/Lex/LexDiagnostic.h"
23 #include "clang/Lex/Lexer.h"
24 #include "clang/Lex/LiteralSupport.h"
25 #include "llvm/ADT/StringRef.h"
26 #include "llvm/ADT/StringSwitch.h"
27 #include "llvm/Support/Allocator.h"
28 #include "llvm/Support/FileSystem.h"
29 #include "llvm/Support/Host.h"
30 #include "llvm/Support/Path.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include <stdlib.h>
33 #if defined(LLVM_ON_UNIX)
34 #include <limits.h>
35 #endif
36 using namespace clang;
37 
38 Module::ExportDecl
39 ModuleMap::resolveExport(Module *Mod,
40                          const Module::UnresolvedExportDecl &Unresolved,
41                          bool Complain) const {
42   // We may have just a wildcard.
43   if (Unresolved.Id.empty()) {
44     assert(Unresolved.Wildcard && "Invalid unresolved export");
45     return Module::ExportDecl(0, true);
46   }
47 
48   // Resolve the module-id.
49   Module *Context = resolveModuleId(Unresolved.Id, Mod, Complain);
50   if (!Context)
51     return Module::ExportDecl();
52 
53   return Module::ExportDecl(Context, Unresolved.Wildcard);
54 }
55 
56 Module *ModuleMap::resolveModuleId(const ModuleId &Id, Module *Mod,
57                                    bool Complain) const {
58   // Find the starting module.
59   Module *Context = lookupModuleUnqualified(Id[0].first, Mod);
60   if (!Context) {
61     if (Complain)
62       Diags.Report(Id[0].second, diag::err_mmap_missing_module_unqualified)
63       << Id[0].first << Mod->getFullModuleName();
64 
65     return 0;
66   }
67 
68   // Dig into the module path.
69   for (unsigned I = 1, N = Id.size(); I != N; ++I) {
70     Module *Sub = lookupModuleQualified(Id[I].first, Context);
71     if (!Sub) {
72       if (Complain)
73         Diags.Report(Id[I].second, diag::err_mmap_missing_module_qualified)
74         << Id[I].first << Context->getFullModuleName()
75         << SourceRange(Id[0].second, Id[I-1].second);
76 
77       return 0;
78     }
79 
80     Context = Sub;
81   }
82 
83   return Context;
84 }
85 
86 ModuleMap::ModuleMap(SourceManager &SourceMgr, DiagnosticsEngine &Diags,
87                      const LangOptions &LangOpts, const TargetInfo *Target,
88                      HeaderSearch &HeaderInfo)
89     : SourceMgr(SourceMgr), Diags(Diags), LangOpts(LangOpts), Target(Target),
90       HeaderInfo(HeaderInfo), BuiltinIncludeDir(0), CompilingModule(0),
91       SourceModule(0) {}
92 
93 ModuleMap::~ModuleMap() {
94   for (llvm::StringMap<Module *>::iterator I = Modules.begin(),
95                                         IEnd = Modules.end();
96        I != IEnd; ++I) {
97     delete I->getValue();
98   }
99 }
100 
101 void ModuleMap::setTarget(const TargetInfo &Target) {
102   assert((!this->Target || this->Target == &Target) &&
103          "Improper target override");
104   this->Target = &Target;
105 }
106 
107 /// \brief "Sanitize" a filename so that it can be used as an identifier.
108 static StringRef sanitizeFilenameAsIdentifier(StringRef Name,
109                                               SmallVectorImpl<char> &Buffer) {
110   if (Name.empty())
111     return Name;
112 
113   if (!isValidIdentifier(Name)) {
114     // If we don't already have something with the form of an identifier,
115     // create a buffer with the sanitized name.
116     Buffer.clear();
117     if (isDigit(Name[0]))
118       Buffer.push_back('_');
119     Buffer.reserve(Buffer.size() + Name.size());
120     for (unsigned I = 0, N = Name.size(); I != N; ++I) {
121       if (isIdentifierBody(Name[I]))
122         Buffer.push_back(Name[I]);
123       else
124         Buffer.push_back('_');
125     }
126 
127     Name = StringRef(Buffer.data(), Buffer.size());
128   }
129 
130   while (llvm::StringSwitch<bool>(Name)
131 #define KEYWORD(Keyword,Conditions) .Case(#Keyword, true)
132 #define ALIAS(Keyword, AliasOf, Conditions) .Case(Keyword, true)
133 #include "clang/Basic/TokenKinds.def"
134            .Default(false)) {
135     if (Name.data() != Buffer.data())
136       Buffer.append(Name.begin(), Name.end());
137     Buffer.push_back('_');
138     Name = StringRef(Buffer.data(), Buffer.size());
139   }
140 
141   return Name;
142 }
143 
144 /// \brief Determine whether the given file name is the name of a builtin
145 /// header, supplied by Clang to replace, override, or augment existing system
146 /// headers.
147 static bool isBuiltinHeader(StringRef FileName) {
148   return llvm::StringSwitch<bool>(FileName)
149            .Case("float.h", true)
150            .Case("iso646.h", true)
151            .Case("limits.h", true)
152            .Case("stdalign.h", true)
153            .Case("stdarg.h", true)
154            .Case("stdbool.h", true)
155            .Case("stddef.h", true)
156            .Case("stdint.h", true)
157            .Case("tgmath.h", true)
158            .Case("unwind.h", true)
159            .Default(false);
160 }
161 
162 ModuleMap::KnownHeader
163 ModuleMap::findModuleForHeader(const FileEntry *File,
164                                Module *RequestingModule,
165                                bool *FoundInModule) {
166   HeadersMap::iterator Known = Headers.find(File);
167 
168   // If we've found a builtin header within Clang's builtin include directory,
169   // load all of the module maps to see if it will get associated with a
170   // specific module (e.g., in /usr/include).
171   if (Known == Headers.end() && File->getDir() == BuiltinIncludeDir &&
172       isBuiltinHeader(llvm::sys::path::filename(File->getName()))) {
173     HeaderInfo.loadTopLevelSystemModules();
174     Known = Headers.find(File);
175   }
176 
177   if (Known != Headers.end()) {
178     ModuleMap::KnownHeader Result = KnownHeader();
179 
180     // Iterate over all modules that 'File' is part of to find the best fit.
181     for (SmallVectorImpl<KnownHeader>::iterator I = Known->second.begin(),
182                                                 E = Known->second.end();
183          I != E; ++I) {
184       // Cannot use a module if the header is excluded in it.
185       if (I->getRole() == ModuleMap::ExcludedHeader)
186         continue;
187 
188       if (FoundInModule)
189         *FoundInModule = true;
190 
191       // Cannot use a module if it is unavailable.
192       if (!I->getModule()->isAvailable())
193         continue;
194 
195       // If 'File' is part of 'RequestingModule', 'RequestingModule' is the
196       // module we are looking for.
197       if (I->getModule() == RequestingModule)
198         return *I;
199 
200       // If uses need to be specified explicitly, we are only allowed to return
201       // modules that are explicitly used by the requesting module.
202       if (RequestingModule && LangOpts.ModulesDeclUse &&
203           std::find(RequestingModule->DirectUses.begin(),
204                     RequestingModule->DirectUses.end(),
205                     I->getModule()) == RequestingModule->DirectUses.end())
206         continue;
207 
208       Result = *I;
209       // If 'File' is a public header of this module, this is as good as we
210       // are going to get.
211       if (I->getRole() == ModuleMap::NormalHeader)
212         break;
213     }
214     return Result;
215   }
216 
217   const DirectoryEntry *Dir = File->getDir();
218   SmallVector<const DirectoryEntry *, 2> SkippedDirs;
219 
220   // Note: as an egregious but useful hack we use the real path here, because
221   // frameworks moving from top-level frameworks to embedded frameworks tend
222   // to be symlinked from the top-level location to the embedded location,
223   // and we need to resolve lookups as if we had found the embedded location.
224   StringRef DirName = SourceMgr.getFileManager().getCanonicalName(Dir);
225 
226   // Keep walking up the directory hierarchy, looking for a directory with
227   // an umbrella header.
228   do {
229     llvm::DenseMap<const DirectoryEntry *, Module *>::iterator KnownDir
230       = UmbrellaDirs.find(Dir);
231     if (KnownDir != UmbrellaDirs.end()) {
232       Module *Result = KnownDir->second;
233 
234       // Search up the module stack until we find a module with an umbrella
235       // directory.
236       Module *UmbrellaModule = Result;
237       while (!UmbrellaModule->getUmbrellaDir() && UmbrellaModule->Parent)
238         UmbrellaModule = UmbrellaModule->Parent;
239 
240       if (UmbrellaModule->InferSubmodules) {
241         // Infer submodules for each of the directories we found between
242         // the directory of the umbrella header and the directory where
243         // the actual header is located.
244         bool Explicit = UmbrellaModule->InferExplicitSubmodules;
245 
246         for (unsigned I = SkippedDirs.size(); I != 0; --I) {
247           // Find or create the module that corresponds to this directory name.
248           SmallString<32> NameBuf;
249           StringRef Name = sanitizeFilenameAsIdentifier(
250                              llvm::sys::path::stem(SkippedDirs[I-1]->getName()),
251                              NameBuf);
252           Result = findOrCreateModule(Name, Result, /*IsFramework=*/false,
253                                       Explicit).first;
254 
255           // Associate the module and the directory.
256           UmbrellaDirs[SkippedDirs[I-1]] = Result;
257 
258           // If inferred submodules export everything they import, add a
259           // wildcard to the set of exports.
260           if (UmbrellaModule->InferExportWildcard && Result->Exports.empty())
261             Result->Exports.push_back(Module::ExportDecl(0, true));
262         }
263 
264         // Infer a submodule with the same name as this header file.
265         SmallString<32> NameBuf;
266         StringRef Name = sanitizeFilenameAsIdentifier(
267                            llvm::sys::path::stem(File->getName()), NameBuf);
268         Result = findOrCreateModule(Name, Result, /*IsFramework=*/false,
269                                     Explicit).first;
270         Result->addTopHeader(File);
271 
272         // If inferred submodules export everything they import, add a
273         // wildcard to the set of exports.
274         if (UmbrellaModule->InferExportWildcard && Result->Exports.empty())
275           Result->Exports.push_back(Module::ExportDecl(0, true));
276       } else {
277         // Record each of the directories we stepped through as being part of
278         // the module we found, since the umbrella header covers them all.
279         for (unsigned I = 0, N = SkippedDirs.size(); I != N; ++I)
280           UmbrellaDirs[SkippedDirs[I]] = Result;
281       }
282 
283       Headers[File].push_back(KnownHeader(Result, NormalHeader));
284 
285       // If a header corresponds to an unavailable module, don't report
286       // that it maps to anything.
287       if (!Result->isAvailable())
288         return KnownHeader();
289 
290       return Headers[File].back();
291     }
292 
293     SkippedDirs.push_back(Dir);
294 
295     // Retrieve our parent path.
296     DirName = llvm::sys::path::parent_path(DirName);
297     if (DirName.empty())
298       break;
299 
300     // Resolve the parent path to a directory entry.
301     Dir = SourceMgr.getFileManager().getDirectory(DirName);
302   } while (Dir);
303 
304   return KnownHeader();
305 }
306 
307 bool ModuleMap::isHeaderInUnavailableModule(const FileEntry *Header) const {
308   HeadersMap::const_iterator Known = Headers.find(Header);
309   if (Known != Headers.end()) {
310     for (SmallVectorImpl<KnownHeader>::const_iterator
311              I = Known->second.begin(),
312              E = Known->second.end();
313          I != E; ++I) {
314       if (I->isAvailable())
315         return false;
316     }
317     return true;
318   }
319 
320   const DirectoryEntry *Dir = Header->getDir();
321   SmallVector<const DirectoryEntry *, 2> SkippedDirs;
322   StringRef DirName = Dir->getName();
323 
324   // Keep walking up the directory hierarchy, looking for a directory with
325   // an umbrella header.
326   do {
327     llvm::DenseMap<const DirectoryEntry *, Module *>::const_iterator KnownDir
328       = UmbrellaDirs.find(Dir);
329     if (KnownDir != UmbrellaDirs.end()) {
330       Module *Found = KnownDir->second;
331       if (!Found->isAvailable())
332         return true;
333 
334       // Search up the module stack until we find a module with an umbrella
335       // directory.
336       Module *UmbrellaModule = Found;
337       while (!UmbrellaModule->getUmbrellaDir() && UmbrellaModule->Parent)
338         UmbrellaModule = UmbrellaModule->Parent;
339 
340       if (UmbrellaModule->InferSubmodules) {
341         for (unsigned I = SkippedDirs.size(); I != 0; --I) {
342           // Find or create the module that corresponds to this directory name.
343           SmallString<32> NameBuf;
344           StringRef Name = sanitizeFilenameAsIdentifier(
345                              llvm::sys::path::stem(SkippedDirs[I-1]->getName()),
346                              NameBuf);
347           Found = lookupModuleQualified(Name, Found);
348           if (!Found)
349             return false;
350           if (!Found->isAvailable())
351             return true;
352         }
353 
354         // Infer a submodule with the same name as this header file.
355         SmallString<32> NameBuf;
356         StringRef Name = sanitizeFilenameAsIdentifier(
357                            llvm::sys::path::stem(Header->getName()),
358                            NameBuf);
359         Found = lookupModuleQualified(Name, Found);
360         if (!Found)
361           return false;
362       }
363 
364       return !Found->isAvailable();
365     }
366 
367     SkippedDirs.push_back(Dir);
368 
369     // Retrieve our parent path.
370     DirName = llvm::sys::path::parent_path(DirName);
371     if (DirName.empty())
372       break;
373 
374     // Resolve the parent path to a directory entry.
375     Dir = SourceMgr.getFileManager().getDirectory(DirName);
376   } while (Dir);
377 
378   return false;
379 }
380 
381 Module *ModuleMap::findModule(StringRef Name) const {
382   llvm::StringMap<Module *>::const_iterator Known = Modules.find(Name);
383   if (Known != Modules.end())
384     return Known->getValue();
385 
386   return 0;
387 }
388 
389 Module *ModuleMap::lookupModuleUnqualified(StringRef Name,
390                                            Module *Context) const {
391   for(; Context; Context = Context->Parent) {
392     if (Module *Sub = lookupModuleQualified(Name, Context))
393       return Sub;
394   }
395 
396   return findModule(Name);
397 }
398 
399 Module *ModuleMap::lookupModuleQualified(StringRef Name, Module *Context) const{
400   if (!Context)
401     return findModule(Name);
402 
403   return Context->findSubmodule(Name);
404 }
405 
406 std::pair<Module *, bool>
407 ModuleMap::findOrCreateModule(StringRef Name, Module *Parent, bool IsFramework,
408                               bool IsExplicit) {
409   // Try to find an existing module with this name.
410   if (Module *Sub = lookupModuleQualified(Name, Parent))
411     return std::make_pair(Sub, false);
412 
413   // Create a new module with this name.
414   Module *Result = new Module(Name, SourceLocation(), Parent, IsFramework,
415                               IsExplicit);
416   if (LangOpts.CurrentModule == Name) {
417     SourceModule = Result;
418     SourceModuleName = Name;
419   }
420   if (!Parent) {
421     Modules[Name] = Result;
422     if (!LangOpts.CurrentModule.empty() && !CompilingModule &&
423         Name == LangOpts.CurrentModule) {
424       CompilingModule = Result;
425     }
426   }
427   return std::make_pair(Result, true);
428 }
429 
430 bool ModuleMap::canInferFrameworkModule(const DirectoryEntry *ParentDir,
431                                         StringRef Name, bool &IsSystem) const {
432   // Check whether we have already looked into the parent directory
433   // for a module map.
434   llvm::DenseMap<const DirectoryEntry *, InferredDirectory>::const_iterator
435     inferred = InferredDirectories.find(ParentDir);
436   if (inferred == InferredDirectories.end())
437     return false;
438 
439   if (!inferred->second.InferModules)
440     return false;
441 
442   // We're allowed to infer for this directory, but make sure it's okay
443   // to infer this particular module.
444   bool canInfer = std::find(inferred->second.ExcludedModules.begin(),
445                             inferred->second.ExcludedModules.end(),
446                             Name) == inferred->second.ExcludedModules.end();
447 
448   if (canInfer && inferred->second.InferSystemModules)
449     IsSystem = true;
450 
451   return canInfer;
452 }
453 
454 /// \brief For a framework module, infer the framework against which we
455 /// should link.
456 static void inferFrameworkLink(Module *Mod, const DirectoryEntry *FrameworkDir,
457                                FileManager &FileMgr) {
458   assert(Mod->IsFramework && "Can only infer linking for framework modules");
459   assert(!Mod->isSubFramework() &&
460          "Can only infer linking for top-level frameworks");
461 
462   SmallString<128> LibName;
463   LibName += FrameworkDir->getName();
464   llvm::sys::path::append(LibName, Mod->Name);
465   if (FileMgr.getFile(LibName)) {
466     Mod->LinkLibraries.push_back(Module::LinkLibrary(Mod->Name,
467                                                      /*IsFramework=*/true));
468   }
469 }
470 
471 Module *
472 ModuleMap::inferFrameworkModule(StringRef ModuleName,
473                                 const DirectoryEntry *FrameworkDir,
474                                 bool IsSystem,
475                                 Module *Parent) {
476   // Check whether we've already found this module.
477   if (Module *Mod = lookupModuleQualified(ModuleName, Parent))
478     return Mod;
479 
480   FileManager &FileMgr = SourceMgr.getFileManager();
481 
482   // If the framework has a parent path from which we're allowed to infer
483   // a framework module, do so.
484   if (!Parent) {
485     // Determine whether we're allowed to infer a module map.
486 
487     // Note: as an egregious but useful hack we use the real path here, because
488     // we might be looking at an embedded framework that symlinks out to a
489     // top-level framework, and we need to infer as if we were naming the
490     // top-level framework.
491     StringRef FrameworkDirName
492       = SourceMgr.getFileManager().getCanonicalName(FrameworkDir);
493 
494     bool canInfer = false;
495     if (llvm::sys::path::has_parent_path(FrameworkDirName)) {
496       // Figure out the parent path.
497       StringRef Parent = llvm::sys::path::parent_path(FrameworkDirName);
498       if (const DirectoryEntry *ParentDir = FileMgr.getDirectory(Parent)) {
499         // Check whether we have already looked into the parent directory
500         // for a module map.
501         llvm::DenseMap<const DirectoryEntry *, InferredDirectory>::const_iterator
502           inferred = InferredDirectories.find(ParentDir);
503         if (inferred == InferredDirectories.end()) {
504           // We haven't looked here before. Load a module map, if there is
505           // one.
506           SmallString<128> ModMapPath = Parent;
507           llvm::sys::path::append(ModMapPath, "module.map");
508           if (const FileEntry *ModMapFile = FileMgr.getFile(ModMapPath)) {
509             parseModuleMapFile(ModMapFile, IsSystem);
510             inferred = InferredDirectories.find(ParentDir);
511           }
512 
513           if (inferred == InferredDirectories.end())
514             inferred = InferredDirectories.insert(
515                          std::make_pair(ParentDir, InferredDirectory())).first;
516         }
517 
518         if (inferred->second.InferModules) {
519           // We're allowed to infer for this directory, but make sure it's okay
520           // to infer this particular module.
521           StringRef Name = llvm::sys::path::stem(FrameworkDirName);
522           canInfer = std::find(inferred->second.ExcludedModules.begin(),
523                                inferred->second.ExcludedModules.end(),
524                                Name) == inferred->second.ExcludedModules.end();
525 
526           if (inferred->second.InferSystemModules)
527             IsSystem = true;
528         }
529       }
530     }
531 
532     // If we're not allowed to infer a framework module, don't.
533     if (!canInfer)
534       return 0;
535   }
536 
537 
538   // Look for an umbrella header.
539   SmallString<128> UmbrellaName = StringRef(FrameworkDir->getName());
540   llvm::sys::path::append(UmbrellaName, "Headers", ModuleName + ".h");
541   const FileEntry *UmbrellaHeader = FileMgr.getFile(UmbrellaName);
542 
543   // FIXME: If there's no umbrella header, we could probably scan the
544   // framework to load *everything*. But, it's not clear that this is a good
545   // idea.
546   if (!UmbrellaHeader)
547     return 0;
548 
549   Module *Result = new Module(ModuleName, SourceLocation(), Parent,
550                               /*IsFramework=*/true, /*IsExplicit=*/false);
551   if (LangOpts.CurrentModule == ModuleName) {
552     SourceModule = Result;
553     SourceModuleName = ModuleName;
554   }
555   if (IsSystem)
556     Result->IsSystem = IsSystem;
557 
558   if (!Parent)
559     Modules[ModuleName] = Result;
560 
561   // umbrella header "umbrella-header-name"
562   Result->Umbrella = UmbrellaHeader;
563   Headers[UmbrellaHeader].push_back(KnownHeader(Result, NormalHeader));
564   UmbrellaDirs[UmbrellaHeader->getDir()] = Result;
565 
566   // export *
567   Result->Exports.push_back(Module::ExportDecl(0, true));
568 
569   // module * { export * }
570   Result->InferSubmodules = true;
571   Result->InferExportWildcard = true;
572 
573   // Look for subframeworks.
574   llvm::error_code EC;
575   SmallString<128> SubframeworksDirName
576     = StringRef(FrameworkDir->getName());
577   llvm::sys::path::append(SubframeworksDirName, "Frameworks");
578   llvm::sys::path::native(SubframeworksDirName);
579   for (llvm::sys::fs::directory_iterator
580          Dir(SubframeworksDirName.str(), EC), DirEnd;
581        Dir != DirEnd && !EC; Dir.increment(EC)) {
582     if (!StringRef(Dir->path()).endswith(".framework"))
583       continue;
584 
585     if (const DirectoryEntry *SubframeworkDir
586           = FileMgr.getDirectory(Dir->path())) {
587       // Note: as an egregious but useful hack, we use the real path here and
588       // check whether it is actually a subdirectory of the parent directory.
589       // This will not be the case if the 'subframework' is actually a symlink
590       // out to a top-level framework.
591       StringRef SubframeworkDirName = FileMgr.getCanonicalName(SubframeworkDir);
592       bool FoundParent = false;
593       do {
594         // Get the parent directory name.
595         SubframeworkDirName
596           = llvm::sys::path::parent_path(SubframeworkDirName);
597         if (SubframeworkDirName.empty())
598           break;
599 
600         if (FileMgr.getDirectory(SubframeworkDirName) == FrameworkDir) {
601           FoundParent = true;
602           break;
603         }
604       } while (true);
605 
606       if (!FoundParent)
607         continue;
608 
609       // FIXME: Do we want to warn about subframeworks without umbrella headers?
610       SmallString<32> NameBuf;
611       inferFrameworkModule(sanitizeFilenameAsIdentifier(
612                              llvm::sys::path::stem(Dir->path()), NameBuf),
613                            SubframeworkDir, IsSystem, Result);
614     }
615   }
616 
617   // If the module is a top-level framework, automatically link against the
618   // framework.
619   if (!Result->isSubFramework()) {
620     inferFrameworkLink(Result, FrameworkDir, FileMgr);
621   }
622 
623   return Result;
624 }
625 
626 void ModuleMap::setUmbrellaHeader(Module *Mod, const FileEntry *UmbrellaHeader){
627   Headers[UmbrellaHeader].push_back(KnownHeader(Mod, NormalHeader));
628   Mod->Umbrella = UmbrellaHeader;
629   UmbrellaDirs[UmbrellaHeader->getDir()] = Mod;
630 }
631 
632 void ModuleMap::setUmbrellaDir(Module *Mod, const DirectoryEntry *UmbrellaDir) {
633   Mod->Umbrella = UmbrellaDir;
634   UmbrellaDirs[UmbrellaDir] = Mod;
635 }
636 
637 void ModuleMap::addHeader(Module *Mod, const FileEntry *Header,
638                           ModuleHeaderRole Role) {
639   if (Role == ExcludedHeader) {
640     Mod->ExcludedHeaders.push_back(Header);
641   } else {
642     if (Role == PrivateHeader)
643       Mod->PrivateHeaders.push_back(Header);
644     else
645       Mod->NormalHeaders.push_back(Header);
646     bool isCompilingModuleHeader = Mod->getTopLevelModule() == CompilingModule;
647     HeaderInfo.MarkFileModuleHeader(Header, Role, isCompilingModuleHeader);
648   }
649   Headers[Header].push_back(KnownHeader(Mod, Role));
650 }
651 
652 const FileEntry *
653 ModuleMap::getContainingModuleMapFile(Module *Module) const {
654   if (Module->DefinitionLoc.isInvalid())
655     return 0;
656 
657   return SourceMgr.getFileEntryForID(
658            SourceMgr.getFileID(Module->DefinitionLoc));
659 }
660 
661 void ModuleMap::dump() {
662   llvm::errs() << "Modules:";
663   for (llvm::StringMap<Module *>::iterator M = Modules.begin(),
664                                         MEnd = Modules.end();
665        M != MEnd; ++M)
666     M->getValue()->print(llvm::errs(), 2);
667 
668   llvm::errs() << "Headers:";
669   for (HeadersMap::iterator H = Headers.begin(), HEnd = Headers.end();
670        H != HEnd; ++H) {
671     llvm::errs() << "  \"" << H->first->getName() << "\" -> ";
672     for (SmallVectorImpl<KnownHeader>::const_iterator I = H->second.begin(),
673                                                       E = H->second.end();
674          I != E; ++I) {
675       if (I != H->second.begin())
676         llvm::errs() << ",";
677       llvm::errs() << I->getModule()->getFullModuleName();
678     }
679     llvm::errs() << "\n";
680   }
681 }
682 
683 bool ModuleMap::resolveExports(Module *Mod, bool Complain) {
684   bool HadError = false;
685   for (unsigned I = 0, N = Mod->UnresolvedExports.size(); I != N; ++I) {
686     Module::ExportDecl Export = resolveExport(Mod, Mod->UnresolvedExports[I],
687                                               Complain);
688     if (Export.getPointer() || Export.getInt())
689       Mod->Exports.push_back(Export);
690     else
691       HadError = true;
692   }
693   Mod->UnresolvedExports.clear();
694   return HadError;
695 }
696 
697 bool ModuleMap::resolveUses(Module *Mod, bool Complain) {
698   bool HadError = false;
699   for (unsigned I = 0, N = Mod->UnresolvedDirectUses.size(); I != N; ++I) {
700     Module *DirectUse =
701         resolveModuleId(Mod->UnresolvedDirectUses[I], Mod, Complain);
702     if (DirectUse)
703       Mod->DirectUses.push_back(DirectUse);
704     else
705       HadError = true;
706   }
707   Mod->UnresolvedDirectUses.clear();
708   return HadError;
709 }
710 
711 bool ModuleMap::resolveConflicts(Module *Mod, bool Complain) {
712   bool HadError = false;
713   for (unsigned I = 0, N = Mod->UnresolvedConflicts.size(); I != N; ++I) {
714     Module *OtherMod = resolveModuleId(Mod->UnresolvedConflicts[I].Id,
715                                        Mod, Complain);
716     if (!OtherMod) {
717       HadError = true;
718       continue;
719     }
720 
721     Module::Conflict Conflict;
722     Conflict.Other = OtherMod;
723     Conflict.Message = Mod->UnresolvedConflicts[I].Message;
724     Mod->Conflicts.push_back(Conflict);
725   }
726   Mod->UnresolvedConflicts.clear();
727   return HadError;
728 }
729 
730 Module *ModuleMap::inferModuleFromLocation(FullSourceLoc Loc) {
731   if (Loc.isInvalid())
732     return 0;
733 
734   // Use the expansion location to determine which module we're in.
735   FullSourceLoc ExpansionLoc = Loc.getExpansionLoc();
736   if (!ExpansionLoc.isFileID())
737     return 0;
738 
739 
740   const SourceManager &SrcMgr = Loc.getManager();
741   FileID ExpansionFileID = ExpansionLoc.getFileID();
742 
743   while (const FileEntry *ExpansionFile
744            = SrcMgr.getFileEntryForID(ExpansionFileID)) {
745     // Find the module that owns this header (if any).
746     if (Module *Mod = findModuleForHeader(ExpansionFile).getModule())
747       return Mod;
748 
749     // No module owns this header, so look up the inclusion chain to see if
750     // any included header has an associated module.
751     SourceLocation IncludeLoc = SrcMgr.getIncludeLoc(ExpansionFileID);
752     if (IncludeLoc.isInvalid())
753       return 0;
754 
755     ExpansionFileID = SrcMgr.getFileID(IncludeLoc);
756   }
757 
758   return 0;
759 }
760 
761 //----------------------------------------------------------------------------//
762 // Module map file parser
763 //----------------------------------------------------------------------------//
764 
765 namespace clang {
766   /// \brief A token in a module map file.
767   struct MMToken {
768     enum TokenKind {
769       Comma,
770       ConfigMacros,
771       Conflict,
772       EndOfFile,
773       HeaderKeyword,
774       Identifier,
775       Exclaim,
776       ExcludeKeyword,
777       ExplicitKeyword,
778       ExportKeyword,
779       ExternKeyword,
780       FrameworkKeyword,
781       LinkKeyword,
782       ModuleKeyword,
783       Period,
784       PrivateKeyword,
785       UmbrellaKeyword,
786       UseKeyword,
787       RequiresKeyword,
788       Star,
789       StringLiteral,
790       LBrace,
791       RBrace,
792       LSquare,
793       RSquare
794     } Kind;
795 
796     unsigned Location;
797     unsigned StringLength;
798     const char *StringData;
799 
800     void clear() {
801       Kind = EndOfFile;
802       Location = 0;
803       StringLength = 0;
804       StringData = 0;
805     }
806 
807     bool is(TokenKind K) const { return Kind == K; }
808 
809     SourceLocation getLocation() const {
810       return SourceLocation::getFromRawEncoding(Location);
811     }
812 
813     StringRef getString() const {
814       return StringRef(StringData, StringLength);
815     }
816   };
817 
818   /// \brief The set of attributes that can be attached to a module.
819   struct Attributes {
820     Attributes() : IsSystem(), IsExhaustive() { }
821 
822     /// \brief Whether this is a system module.
823     unsigned IsSystem : 1;
824 
825     /// \brief Whether this is an exhaustive set of configuration macros.
826     unsigned IsExhaustive : 1;
827   };
828 
829 
830   class ModuleMapParser {
831     Lexer &L;
832     SourceManager &SourceMgr;
833 
834     /// \brief Default target information, used only for string literal
835     /// parsing.
836     const TargetInfo *Target;
837 
838     DiagnosticsEngine &Diags;
839     ModuleMap &Map;
840 
841     /// \brief The directory that this module map resides in.
842     const DirectoryEntry *Directory;
843 
844     /// \brief The directory containing Clang-supplied headers.
845     const DirectoryEntry *BuiltinIncludeDir;
846 
847     /// \brief Whether this module map is in a system header directory.
848     bool IsSystem;
849 
850     /// \brief Whether an error occurred.
851     bool HadError;
852 
853     /// \brief Stores string data for the various string literals referenced
854     /// during parsing.
855     llvm::BumpPtrAllocator StringData;
856 
857     /// \brief The current token.
858     MMToken Tok;
859 
860     /// \brief The active module.
861     Module *ActiveModule;
862 
863     /// \brief Consume the current token and return its location.
864     SourceLocation consumeToken();
865 
866     /// \brief Skip tokens until we reach the a token with the given kind
867     /// (or the end of the file).
868     void skipUntil(MMToken::TokenKind K);
869 
870     typedef SmallVector<std::pair<std::string, SourceLocation>, 2> ModuleId;
871     bool parseModuleId(ModuleId &Id);
872     void parseModuleDecl();
873     void parseExternModuleDecl();
874     void parseRequiresDecl();
875     void parseHeaderDecl(clang::MMToken::TokenKind,
876                          SourceLocation LeadingLoc);
877     void parseUmbrellaDirDecl(SourceLocation UmbrellaLoc);
878     void parseExportDecl();
879     void parseUseDecl();
880     void parseLinkDecl();
881     void parseConfigMacros();
882     void parseConflict();
883     void parseInferredModuleDecl(bool Framework, bool Explicit);
884     bool parseOptionalAttributes(Attributes &Attrs);
885 
886     const DirectoryEntry *getOverriddenHeaderSearchDir();
887 
888   public:
889     explicit ModuleMapParser(Lexer &L, SourceManager &SourceMgr,
890                              const TargetInfo *Target,
891                              DiagnosticsEngine &Diags,
892                              ModuleMap &Map,
893                              const DirectoryEntry *Directory,
894                              const DirectoryEntry *BuiltinIncludeDir,
895                              bool IsSystem)
896       : L(L), SourceMgr(SourceMgr), Target(Target), Diags(Diags), Map(Map),
897         Directory(Directory), BuiltinIncludeDir(BuiltinIncludeDir),
898         IsSystem(IsSystem), HadError(false), ActiveModule(0)
899     {
900       Tok.clear();
901       consumeToken();
902     }
903 
904     bool parseModuleMapFile();
905   };
906 }
907 
908 SourceLocation ModuleMapParser::consumeToken() {
909 retry:
910   SourceLocation Result = Tok.getLocation();
911   Tok.clear();
912 
913   Token LToken;
914   L.LexFromRawLexer(LToken);
915   Tok.Location = LToken.getLocation().getRawEncoding();
916   switch (LToken.getKind()) {
917   case tok::raw_identifier:
918     Tok.StringData = LToken.getRawIdentifierData();
919     Tok.StringLength = LToken.getLength();
920     Tok.Kind = llvm::StringSwitch<MMToken::TokenKind>(Tok.getString())
921                  .Case("config_macros", MMToken::ConfigMacros)
922                  .Case("conflict", MMToken::Conflict)
923                  .Case("exclude", MMToken::ExcludeKeyword)
924                  .Case("explicit", MMToken::ExplicitKeyword)
925                  .Case("export", MMToken::ExportKeyword)
926                  .Case("extern", MMToken::ExternKeyword)
927                  .Case("framework", MMToken::FrameworkKeyword)
928                  .Case("header", MMToken::HeaderKeyword)
929                  .Case("link", MMToken::LinkKeyword)
930                  .Case("module", MMToken::ModuleKeyword)
931                  .Case("private", MMToken::PrivateKeyword)
932                  .Case("requires", MMToken::RequiresKeyword)
933                  .Case("umbrella", MMToken::UmbrellaKeyword)
934                  .Case("use", MMToken::UseKeyword)
935                  .Default(MMToken::Identifier);
936     break;
937 
938   case tok::comma:
939     Tok.Kind = MMToken::Comma;
940     break;
941 
942   case tok::eof:
943     Tok.Kind = MMToken::EndOfFile;
944     break;
945 
946   case tok::l_brace:
947     Tok.Kind = MMToken::LBrace;
948     break;
949 
950   case tok::l_square:
951     Tok.Kind = MMToken::LSquare;
952     break;
953 
954   case tok::period:
955     Tok.Kind = MMToken::Period;
956     break;
957 
958   case tok::r_brace:
959     Tok.Kind = MMToken::RBrace;
960     break;
961 
962   case tok::r_square:
963     Tok.Kind = MMToken::RSquare;
964     break;
965 
966   case tok::star:
967     Tok.Kind = MMToken::Star;
968     break;
969 
970   case tok::exclaim:
971     Tok.Kind = MMToken::Exclaim;
972     break;
973 
974   case tok::string_literal: {
975     if (LToken.hasUDSuffix()) {
976       Diags.Report(LToken.getLocation(), diag::err_invalid_string_udl);
977       HadError = true;
978       goto retry;
979     }
980 
981     // Parse the string literal.
982     LangOptions LangOpts;
983     StringLiteralParser StringLiteral(&LToken, 1, SourceMgr, LangOpts, *Target);
984     if (StringLiteral.hadError)
985       goto retry;
986 
987     // Copy the string literal into our string data allocator.
988     unsigned Length = StringLiteral.GetStringLength();
989     char *Saved = StringData.Allocate<char>(Length + 1);
990     memcpy(Saved, StringLiteral.GetString().data(), Length);
991     Saved[Length] = 0;
992 
993     // Form the token.
994     Tok.Kind = MMToken::StringLiteral;
995     Tok.StringData = Saved;
996     Tok.StringLength = Length;
997     break;
998   }
999 
1000   case tok::comment:
1001     goto retry;
1002 
1003   default:
1004     Diags.Report(LToken.getLocation(), diag::err_mmap_unknown_token);
1005     HadError = true;
1006     goto retry;
1007   }
1008 
1009   return Result;
1010 }
1011 
1012 void ModuleMapParser::skipUntil(MMToken::TokenKind K) {
1013   unsigned braceDepth = 0;
1014   unsigned squareDepth = 0;
1015   do {
1016     switch (Tok.Kind) {
1017     case MMToken::EndOfFile:
1018       return;
1019 
1020     case MMToken::LBrace:
1021       if (Tok.is(K) && braceDepth == 0 && squareDepth == 0)
1022         return;
1023 
1024       ++braceDepth;
1025       break;
1026 
1027     case MMToken::LSquare:
1028       if (Tok.is(K) && braceDepth == 0 && squareDepth == 0)
1029         return;
1030 
1031       ++squareDepth;
1032       break;
1033 
1034     case MMToken::RBrace:
1035       if (braceDepth > 0)
1036         --braceDepth;
1037       else if (Tok.is(K))
1038         return;
1039       break;
1040 
1041     case MMToken::RSquare:
1042       if (squareDepth > 0)
1043         --squareDepth;
1044       else if (Tok.is(K))
1045         return;
1046       break;
1047 
1048     default:
1049       if (braceDepth == 0 && squareDepth == 0 && Tok.is(K))
1050         return;
1051       break;
1052     }
1053 
1054    consumeToken();
1055   } while (true);
1056 }
1057 
1058 /// \brief Parse a module-id.
1059 ///
1060 ///   module-id:
1061 ///     identifier
1062 ///     identifier '.' module-id
1063 ///
1064 /// \returns true if an error occurred, false otherwise.
1065 bool ModuleMapParser::parseModuleId(ModuleId &Id) {
1066   Id.clear();
1067   do {
1068     if (Tok.is(MMToken::Identifier) || Tok.is(MMToken::StringLiteral)) {
1069       Id.push_back(std::make_pair(Tok.getString(), Tok.getLocation()));
1070       consumeToken();
1071     } else {
1072       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module_name);
1073       return true;
1074     }
1075 
1076     if (!Tok.is(MMToken::Period))
1077       break;
1078 
1079     consumeToken();
1080   } while (true);
1081 
1082   return false;
1083 }
1084 
1085 namespace {
1086   /// \brief Enumerates the known attributes.
1087   enum AttributeKind {
1088     /// \brief An unknown attribute.
1089     AT_unknown,
1090     /// \brief The 'system' attribute.
1091     AT_system,
1092     /// \brief The 'exhaustive' attribute.
1093     AT_exhaustive
1094   };
1095 }
1096 
1097 /// \brief Parse a module declaration.
1098 ///
1099 ///   module-declaration:
1100 ///     'extern' 'module' module-id string-literal
1101 ///     'explicit'[opt] 'framework'[opt] 'module' module-id attributes[opt]
1102 ///       { module-member* }
1103 ///
1104 ///   module-member:
1105 ///     requires-declaration
1106 ///     header-declaration
1107 ///     submodule-declaration
1108 ///     export-declaration
1109 ///     link-declaration
1110 ///
1111 ///   submodule-declaration:
1112 ///     module-declaration
1113 ///     inferred-submodule-declaration
1114 void ModuleMapParser::parseModuleDecl() {
1115   assert(Tok.is(MMToken::ExplicitKeyword) || Tok.is(MMToken::ModuleKeyword) ||
1116          Tok.is(MMToken::FrameworkKeyword) || Tok.is(MMToken::ExternKeyword));
1117   if (Tok.is(MMToken::ExternKeyword)) {
1118     parseExternModuleDecl();
1119     return;
1120   }
1121 
1122   // Parse 'explicit' or 'framework' keyword, if present.
1123   SourceLocation ExplicitLoc;
1124   bool Explicit = false;
1125   bool Framework = false;
1126 
1127   // Parse 'explicit' keyword, if present.
1128   if (Tok.is(MMToken::ExplicitKeyword)) {
1129     ExplicitLoc = consumeToken();
1130     Explicit = true;
1131   }
1132 
1133   // Parse 'framework' keyword, if present.
1134   if (Tok.is(MMToken::FrameworkKeyword)) {
1135     consumeToken();
1136     Framework = true;
1137   }
1138 
1139   // Parse 'module' keyword.
1140   if (!Tok.is(MMToken::ModuleKeyword)) {
1141     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module);
1142     consumeToken();
1143     HadError = true;
1144     return;
1145   }
1146   consumeToken(); // 'module' keyword
1147 
1148   // If we have a wildcard for the module name, this is an inferred submodule.
1149   // Parse it.
1150   if (Tok.is(MMToken::Star))
1151     return parseInferredModuleDecl(Framework, Explicit);
1152 
1153   // Parse the module name.
1154   ModuleId Id;
1155   if (parseModuleId(Id)) {
1156     HadError = true;
1157     return;
1158   }
1159 
1160   if (ActiveModule) {
1161     if (Id.size() > 1) {
1162       Diags.Report(Id.front().second, diag::err_mmap_nested_submodule_id)
1163         << SourceRange(Id.front().second, Id.back().second);
1164 
1165       HadError = true;
1166       return;
1167     }
1168   } else if (Id.size() == 1 && Explicit) {
1169     // Top-level modules can't be explicit.
1170     Diags.Report(ExplicitLoc, diag::err_mmap_explicit_top_level);
1171     Explicit = false;
1172     ExplicitLoc = SourceLocation();
1173     HadError = true;
1174   }
1175 
1176   Module *PreviousActiveModule = ActiveModule;
1177   if (Id.size() > 1) {
1178     // This module map defines a submodule. Go find the module of which it
1179     // is a submodule.
1180     ActiveModule = 0;
1181     for (unsigned I = 0, N = Id.size() - 1; I != N; ++I) {
1182       if (Module *Next = Map.lookupModuleQualified(Id[I].first, ActiveModule)) {
1183         ActiveModule = Next;
1184         continue;
1185       }
1186 
1187       if (ActiveModule) {
1188         Diags.Report(Id[I].second, diag::err_mmap_missing_module_qualified)
1189           << Id[I].first << ActiveModule->getTopLevelModule();
1190       } else {
1191         Diags.Report(Id[I].second, diag::err_mmap_expected_module_name);
1192       }
1193       HadError = true;
1194       return;
1195     }
1196   }
1197 
1198   StringRef ModuleName = Id.back().first;
1199   SourceLocation ModuleNameLoc = Id.back().second;
1200 
1201   // Parse the optional attribute list.
1202   Attributes Attrs;
1203   parseOptionalAttributes(Attrs);
1204 
1205   // Parse the opening brace.
1206   if (!Tok.is(MMToken::LBrace)) {
1207     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_lbrace)
1208       << ModuleName;
1209     HadError = true;
1210     return;
1211   }
1212   SourceLocation LBraceLoc = consumeToken();
1213 
1214   // Determine whether this (sub)module has already been defined.
1215   if (Module *Existing = Map.lookupModuleQualified(ModuleName, ActiveModule)) {
1216     if (Existing->DefinitionLoc.isInvalid() && !ActiveModule) {
1217       // Skip the module definition.
1218       skipUntil(MMToken::RBrace);
1219       if (Tok.is(MMToken::RBrace))
1220         consumeToken();
1221       else {
1222         Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
1223         Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
1224         HadError = true;
1225       }
1226       return;
1227     }
1228 
1229     Diags.Report(ModuleNameLoc, diag::err_mmap_module_redefinition)
1230       << ModuleName;
1231     Diags.Report(Existing->DefinitionLoc, diag::note_mmap_prev_definition);
1232 
1233     // Skip the module definition.
1234     skipUntil(MMToken::RBrace);
1235     if (Tok.is(MMToken::RBrace))
1236       consumeToken();
1237 
1238     HadError = true;
1239     return;
1240   }
1241 
1242   // Start defining this module.
1243   ActiveModule = Map.findOrCreateModule(ModuleName, ActiveModule, Framework,
1244                                         Explicit).first;
1245   ActiveModule->DefinitionLoc = ModuleNameLoc;
1246   if (Attrs.IsSystem || IsSystem)
1247     ActiveModule->IsSystem = true;
1248 
1249   bool Done = false;
1250   do {
1251     switch (Tok.Kind) {
1252     case MMToken::EndOfFile:
1253     case MMToken::RBrace:
1254       Done = true;
1255       break;
1256 
1257     case MMToken::ConfigMacros:
1258       parseConfigMacros();
1259       break;
1260 
1261     case MMToken::Conflict:
1262       parseConflict();
1263       break;
1264 
1265     case MMToken::ExplicitKeyword:
1266     case MMToken::ExternKeyword:
1267     case MMToken::FrameworkKeyword:
1268     case MMToken::ModuleKeyword:
1269       parseModuleDecl();
1270       break;
1271 
1272     case MMToken::ExportKeyword:
1273       parseExportDecl();
1274       break;
1275 
1276     case MMToken::UseKeyword:
1277       parseUseDecl();
1278       break;
1279 
1280     case MMToken::RequiresKeyword:
1281       parseRequiresDecl();
1282       break;
1283 
1284     case MMToken::UmbrellaKeyword: {
1285       SourceLocation UmbrellaLoc = consumeToken();
1286       if (Tok.is(MMToken::HeaderKeyword))
1287         parseHeaderDecl(MMToken::UmbrellaKeyword, UmbrellaLoc);
1288       else
1289         parseUmbrellaDirDecl(UmbrellaLoc);
1290       break;
1291     }
1292 
1293     case MMToken::ExcludeKeyword: {
1294       SourceLocation ExcludeLoc = consumeToken();
1295       if (Tok.is(MMToken::HeaderKeyword)) {
1296         parseHeaderDecl(MMToken::ExcludeKeyword, ExcludeLoc);
1297       } else {
1298         Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
1299           << "exclude";
1300       }
1301       break;
1302     }
1303 
1304     case MMToken::PrivateKeyword: {
1305       SourceLocation PrivateLoc = consumeToken();
1306       if (Tok.is(MMToken::HeaderKeyword)) {
1307         parseHeaderDecl(MMToken::PrivateKeyword, PrivateLoc);
1308       } else {
1309         Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
1310           << "private";
1311       }
1312       break;
1313     }
1314 
1315     case MMToken::HeaderKeyword:
1316       parseHeaderDecl(MMToken::HeaderKeyword, SourceLocation());
1317       break;
1318 
1319     case MMToken::LinkKeyword:
1320       parseLinkDecl();
1321       break;
1322 
1323     default:
1324       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_member);
1325       consumeToken();
1326       break;
1327     }
1328   } while (!Done);
1329 
1330   if (Tok.is(MMToken::RBrace))
1331     consumeToken();
1332   else {
1333     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
1334     Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
1335     HadError = true;
1336   }
1337 
1338   // If the active module is a top-level framework, and there are no link
1339   // libraries, automatically link against the framework.
1340   if (ActiveModule->IsFramework && !ActiveModule->isSubFramework() &&
1341       ActiveModule->LinkLibraries.empty()) {
1342     inferFrameworkLink(ActiveModule, Directory, SourceMgr.getFileManager());
1343   }
1344 
1345   // We're done parsing this module. Pop back to the previous module.
1346   ActiveModule = PreviousActiveModule;
1347 }
1348 
1349 /// \brief Parse an extern module declaration.
1350 ///
1351 ///   extern module-declaration:
1352 ///     'extern' 'module' module-id string-literal
1353 void ModuleMapParser::parseExternModuleDecl() {
1354   assert(Tok.is(MMToken::ExternKeyword));
1355   consumeToken(); // 'extern' keyword
1356 
1357   // Parse 'module' keyword.
1358   if (!Tok.is(MMToken::ModuleKeyword)) {
1359     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module);
1360     consumeToken();
1361     HadError = true;
1362     return;
1363   }
1364   consumeToken(); // 'module' keyword
1365 
1366   // Parse the module name.
1367   ModuleId Id;
1368   if (parseModuleId(Id)) {
1369     HadError = true;
1370     return;
1371   }
1372 
1373   // Parse the referenced module map file name.
1374   if (!Tok.is(MMToken::StringLiteral)) {
1375     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_mmap_file);
1376     HadError = true;
1377     return;
1378   }
1379   std::string FileName = Tok.getString();
1380   consumeToken(); // filename
1381 
1382   StringRef FileNameRef = FileName;
1383   SmallString<128> ModuleMapFileName;
1384   if (llvm::sys::path::is_relative(FileNameRef)) {
1385     ModuleMapFileName += Directory->getName();
1386     llvm::sys::path::append(ModuleMapFileName, FileName);
1387     FileNameRef = ModuleMapFileName.str();
1388   }
1389   if (const FileEntry *File = SourceMgr.getFileManager().getFile(FileNameRef))
1390     Map.parseModuleMapFile(File, /*IsSystem=*/false);
1391 }
1392 
1393 /// \brief Parse a requires declaration.
1394 ///
1395 ///   requires-declaration:
1396 ///     'requires' feature-list
1397 ///
1398 ///   feature-list:
1399 ///     feature ',' feature-list
1400 ///     feature
1401 ///
1402 ///   feature:
1403 ///     '!'[opt] identifier
1404 void ModuleMapParser::parseRequiresDecl() {
1405   assert(Tok.is(MMToken::RequiresKeyword));
1406 
1407   // Parse 'requires' keyword.
1408   consumeToken();
1409 
1410   // Parse the feature-list.
1411   do {
1412     bool RequiredState = true;
1413     if (Tok.is(MMToken::Exclaim)) {
1414       RequiredState = false;
1415       consumeToken();
1416     }
1417 
1418     if (!Tok.is(MMToken::Identifier)) {
1419       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_feature);
1420       HadError = true;
1421       return;
1422     }
1423 
1424     // Consume the feature name.
1425     std::string Feature = Tok.getString();
1426     consumeToken();
1427 
1428     // Add this feature.
1429     ActiveModule->addRequirement(Feature, RequiredState,
1430                                  Map.LangOpts, *Map.Target);
1431 
1432     if (!Tok.is(MMToken::Comma))
1433       break;
1434 
1435     // Consume the comma.
1436     consumeToken();
1437   } while (true);
1438 }
1439 
1440 /// \brief Append to \p Paths the set of paths needed to get to the
1441 /// subframework in which the given module lives.
1442 static void appendSubframeworkPaths(Module *Mod,
1443                                     SmallVectorImpl<char> &Path) {
1444   // Collect the framework names from the given module to the top-level module.
1445   SmallVector<StringRef, 2> Paths;
1446   for (; Mod; Mod = Mod->Parent) {
1447     if (Mod->IsFramework)
1448       Paths.push_back(Mod->Name);
1449   }
1450 
1451   if (Paths.empty())
1452     return;
1453 
1454   // Add Frameworks/Name.framework for each subframework.
1455   for (unsigned I = Paths.size() - 1; I != 0; --I)
1456     llvm::sys::path::append(Path, "Frameworks", Paths[I-1] + ".framework");
1457 }
1458 
1459 /// \brief Parse a header declaration.
1460 ///
1461 ///   header-declaration:
1462 ///     'umbrella'[opt] 'header' string-literal
1463 ///     'exclude'[opt] 'header' string-literal
1464 void ModuleMapParser::parseHeaderDecl(MMToken::TokenKind LeadingToken,
1465                                       SourceLocation LeadingLoc) {
1466   assert(Tok.is(MMToken::HeaderKeyword));
1467   consumeToken();
1468 
1469   // Parse the header name.
1470   if (!Tok.is(MMToken::StringLiteral)) {
1471     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
1472       << "header";
1473     HadError = true;
1474     return;
1475   }
1476   Module::HeaderDirective Header;
1477   Header.FileName = Tok.getString();
1478   Header.FileNameLoc = consumeToken();
1479 
1480   // Check whether we already have an umbrella.
1481   if (LeadingToken == MMToken::UmbrellaKeyword && ActiveModule->Umbrella) {
1482     Diags.Report(Header.FileNameLoc, diag::err_mmap_umbrella_clash)
1483       << ActiveModule->getFullModuleName();
1484     HadError = true;
1485     return;
1486   }
1487 
1488   // Look for this file.
1489   const FileEntry *File = 0;
1490   const FileEntry *BuiltinFile = 0;
1491   SmallString<128> PathName;
1492   if (llvm::sys::path::is_absolute(Header.FileName)) {
1493     PathName = Header.FileName;
1494     File = SourceMgr.getFileManager().getFile(PathName);
1495   } else if (const DirectoryEntry *Dir = getOverriddenHeaderSearchDir()) {
1496     PathName = Dir->getName();
1497     llvm::sys::path::append(PathName, Header.FileName);
1498     File = SourceMgr.getFileManager().getFile(PathName);
1499   } else {
1500     // Search for the header file within the search directory.
1501     PathName = Directory->getName();
1502     unsigned PathLength = PathName.size();
1503 
1504     if (ActiveModule->isPartOfFramework()) {
1505       appendSubframeworkPaths(ActiveModule, PathName);
1506 
1507       // Check whether this file is in the public headers.
1508       llvm::sys::path::append(PathName, "Headers", Header.FileName);
1509       File = SourceMgr.getFileManager().getFile(PathName);
1510 
1511       if (!File) {
1512         // Check whether this file is in the private headers.
1513         PathName.resize(PathLength);
1514         llvm::sys::path::append(PathName, "PrivateHeaders", Header.FileName);
1515         File = SourceMgr.getFileManager().getFile(PathName);
1516       }
1517     } else {
1518       // Lookup for normal headers.
1519       llvm::sys::path::append(PathName, Header.FileName);
1520       File = SourceMgr.getFileManager().getFile(PathName);
1521 
1522       // If this is a system module with a top-level header, this header
1523       // may have a counterpart (or replacement) in the set of headers
1524       // supplied by Clang. Find that builtin header.
1525       if (ActiveModule->IsSystem && LeadingToken != MMToken::UmbrellaKeyword &&
1526           BuiltinIncludeDir && BuiltinIncludeDir != Directory &&
1527           isBuiltinHeader(Header.FileName)) {
1528         SmallString<128> BuiltinPathName(BuiltinIncludeDir->getName());
1529         llvm::sys::path::append(BuiltinPathName, Header.FileName);
1530         BuiltinFile = SourceMgr.getFileManager().getFile(BuiltinPathName);
1531 
1532         // If Clang supplies this header but the underlying system does not,
1533         // just silently swap in our builtin version. Otherwise, we'll end
1534         // up adding both (later).
1535         if (!File && BuiltinFile) {
1536           File = BuiltinFile;
1537           BuiltinFile = 0;
1538         }
1539       }
1540     }
1541   }
1542 
1543   // FIXME: We shouldn't be eagerly stat'ing every file named in a module map.
1544   // Come up with a lazy way to do this.
1545   if (File) {
1546     if (LeadingToken == MMToken::UmbrellaKeyword) {
1547       const DirectoryEntry *UmbrellaDir = File->getDir();
1548       if (Module *UmbrellaModule = Map.UmbrellaDirs[UmbrellaDir]) {
1549         Diags.Report(LeadingLoc, diag::err_mmap_umbrella_clash)
1550           << UmbrellaModule->getFullModuleName();
1551         HadError = true;
1552       } else {
1553         // Record this umbrella header.
1554         Map.setUmbrellaHeader(ActiveModule, File);
1555       }
1556     } else {
1557       // Record this header.
1558       ModuleMap::ModuleHeaderRole Role = ModuleMap::NormalHeader;
1559       if (LeadingToken == MMToken::ExcludeKeyword)
1560         Role = ModuleMap::ExcludedHeader;
1561       else if (LeadingToken == MMToken::PrivateKeyword)
1562         Role = ModuleMap::PrivateHeader;
1563       else
1564         assert(LeadingToken == MMToken::HeaderKeyword);
1565 
1566       Map.addHeader(ActiveModule, File, Role);
1567 
1568       // If there is a builtin counterpart to this file, add it now.
1569       if (BuiltinFile)
1570         Map.addHeader(ActiveModule, BuiltinFile, Role);
1571     }
1572   } else if (LeadingToken != MMToken::ExcludeKeyword) {
1573     // Ignore excluded header files. They're optional anyway.
1574 
1575     // If we find a module that has a missing header, we mark this module as
1576     // unavailable and store the header directive for displaying diagnostics.
1577     // Other submodules in the same module can still be used.
1578     Header.IsUmbrella = LeadingToken == MMToken::UmbrellaKeyword;
1579     ActiveModule->IsAvailable = false;
1580     ActiveModule->MissingHeaders.push_back(Header);
1581   }
1582 }
1583 
1584 /// \brief Parse an umbrella directory declaration.
1585 ///
1586 ///   umbrella-dir-declaration:
1587 ///     umbrella string-literal
1588 void ModuleMapParser::parseUmbrellaDirDecl(SourceLocation UmbrellaLoc) {
1589   // Parse the directory name.
1590   if (!Tok.is(MMToken::StringLiteral)) {
1591     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
1592       << "umbrella";
1593     HadError = true;
1594     return;
1595   }
1596 
1597   std::string DirName = Tok.getString();
1598   SourceLocation DirNameLoc = consumeToken();
1599 
1600   // Check whether we already have an umbrella.
1601   if (ActiveModule->Umbrella) {
1602     Diags.Report(DirNameLoc, diag::err_mmap_umbrella_clash)
1603       << ActiveModule->getFullModuleName();
1604     HadError = true;
1605     return;
1606   }
1607 
1608   // Look for this file.
1609   const DirectoryEntry *Dir = 0;
1610   if (llvm::sys::path::is_absolute(DirName))
1611     Dir = SourceMgr.getFileManager().getDirectory(DirName);
1612   else {
1613     SmallString<128> PathName;
1614     PathName = Directory->getName();
1615     llvm::sys::path::append(PathName, DirName);
1616     Dir = SourceMgr.getFileManager().getDirectory(PathName);
1617   }
1618 
1619   if (!Dir) {
1620     Diags.Report(DirNameLoc, diag::err_mmap_umbrella_dir_not_found)
1621       << DirName;
1622     HadError = true;
1623     return;
1624   }
1625 
1626   if (Module *OwningModule = Map.UmbrellaDirs[Dir]) {
1627     Diags.Report(UmbrellaLoc, diag::err_mmap_umbrella_clash)
1628       << OwningModule->getFullModuleName();
1629     HadError = true;
1630     return;
1631   }
1632 
1633   // Record this umbrella directory.
1634   Map.setUmbrellaDir(ActiveModule, Dir);
1635 }
1636 
1637 /// \brief Parse a module export declaration.
1638 ///
1639 ///   export-declaration:
1640 ///     'export' wildcard-module-id
1641 ///
1642 ///   wildcard-module-id:
1643 ///     identifier
1644 ///     '*'
1645 ///     identifier '.' wildcard-module-id
1646 void ModuleMapParser::parseExportDecl() {
1647   assert(Tok.is(MMToken::ExportKeyword));
1648   SourceLocation ExportLoc = consumeToken();
1649 
1650   // Parse the module-id with an optional wildcard at the end.
1651   ModuleId ParsedModuleId;
1652   bool Wildcard = false;
1653   do {
1654     if (Tok.is(MMToken::Identifier)) {
1655       ParsedModuleId.push_back(std::make_pair(Tok.getString(),
1656                                               Tok.getLocation()));
1657       consumeToken();
1658 
1659       if (Tok.is(MMToken::Period)) {
1660         consumeToken();
1661         continue;
1662       }
1663 
1664       break;
1665     }
1666 
1667     if(Tok.is(MMToken::Star)) {
1668       Wildcard = true;
1669       consumeToken();
1670       break;
1671     }
1672 
1673     Diags.Report(Tok.getLocation(), diag::err_mmap_module_id);
1674     HadError = true;
1675     return;
1676   } while (true);
1677 
1678   Module::UnresolvedExportDecl Unresolved = {
1679     ExportLoc, ParsedModuleId, Wildcard
1680   };
1681   ActiveModule->UnresolvedExports.push_back(Unresolved);
1682 }
1683 
1684 /// \brief Parse a module uses declaration.
1685 ///
1686 ///   uses-declaration:
1687 ///     'uses' wildcard-module-id
1688 void ModuleMapParser::parseUseDecl() {
1689   assert(Tok.is(MMToken::UseKeyword));
1690   consumeToken();
1691   // Parse the module-id.
1692   ModuleId ParsedModuleId;
1693   parseModuleId(ParsedModuleId);
1694 
1695   ActiveModule->UnresolvedDirectUses.push_back(ParsedModuleId);
1696 }
1697 
1698 /// \brief Parse a link declaration.
1699 ///
1700 ///   module-declaration:
1701 ///     'link' 'framework'[opt] string-literal
1702 void ModuleMapParser::parseLinkDecl() {
1703   assert(Tok.is(MMToken::LinkKeyword));
1704   SourceLocation LinkLoc = consumeToken();
1705 
1706   // Parse the optional 'framework' keyword.
1707   bool IsFramework = false;
1708   if (Tok.is(MMToken::FrameworkKeyword)) {
1709     consumeToken();
1710     IsFramework = true;
1711   }
1712 
1713   // Parse the library name
1714   if (!Tok.is(MMToken::StringLiteral)) {
1715     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_library_name)
1716       << IsFramework << SourceRange(LinkLoc);
1717     HadError = true;
1718     return;
1719   }
1720 
1721   std::string LibraryName = Tok.getString();
1722   consumeToken();
1723   ActiveModule->LinkLibraries.push_back(Module::LinkLibrary(LibraryName,
1724                                                             IsFramework));
1725 }
1726 
1727 /// \brief Parse a configuration macro declaration.
1728 ///
1729 ///   module-declaration:
1730 ///     'config_macros' attributes[opt] config-macro-list?
1731 ///
1732 ///   config-macro-list:
1733 ///     identifier (',' identifier)?
1734 void ModuleMapParser::parseConfigMacros() {
1735   assert(Tok.is(MMToken::ConfigMacros));
1736   SourceLocation ConfigMacrosLoc = consumeToken();
1737 
1738   // Only top-level modules can have configuration macros.
1739   if (ActiveModule->Parent) {
1740     Diags.Report(ConfigMacrosLoc, diag::err_mmap_config_macro_submodule);
1741   }
1742 
1743   // Parse the optional attributes.
1744   Attributes Attrs;
1745   parseOptionalAttributes(Attrs);
1746   if (Attrs.IsExhaustive && !ActiveModule->Parent) {
1747     ActiveModule->ConfigMacrosExhaustive = true;
1748   }
1749 
1750   // If we don't have an identifier, we're done.
1751   if (!Tok.is(MMToken::Identifier))
1752     return;
1753 
1754   // Consume the first identifier.
1755   if (!ActiveModule->Parent) {
1756     ActiveModule->ConfigMacros.push_back(Tok.getString().str());
1757   }
1758   consumeToken();
1759 
1760   do {
1761     // If there's a comma, consume it.
1762     if (!Tok.is(MMToken::Comma))
1763       break;
1764     consumeToken();
1765 
1766     // We expect to see a macro name here.
1767     if (!Tok.is(MMToken::Identifier)) {
1768       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_config_macro);
1769       break;
1770     }
1771 
1772     // Consume the macro name.
1773     if (!ActiveModule->Parent) {
1774       ActiveModule->ConfigMacros.push_back(Tok.getString().str());
1775     }
1776     consumeToken();
1777   } while (true);
1778 }
1779 
1780 /// \brief Format a module-id into a string.
1781 static std::string formatModuleId(const ModuleId &Id) {
1782   std::string result;
1783   {
1784     llvm::raw_string_ostream OS(result);
1785 
1786     for (unsigned I = 0, N = Id.size(); I != N; ++I) {
1787       if (I)
1788         OS << ".";
1789       OS << Id[I].first;
1790     }
1791   }
1792 
1793   return result;
1794 }
1795 
1796 /// \brief Parse a conflict declaration.
1797 ///
1798 ///   module-declaration:
1799 ///     'conflict' module-id ',' string-literal
1800 void ModuleMapParser::parseConflict() {
1801   assert(Tok.is(MMToken::Conflict));
1802   SourceLocation ConflictLoc = consumeToken();
1803   Module::UnresolvedConflict Conflict;
1804 
1805   // Parse the module-id.
1806   if (parseModuleId(Conflict.Id))
1807     return;
1808 
1809   // Parse the ','.
1810   if (!Tok.is(MMToken::Comma)) {
1811     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_conflicts_comma)
1812       << SourceRange(ConflictLoc);
1813     return;
1814   }
1815   consumeToken();
1816 
1817   // Parse the message.
1818   if (!Tok.is(MMToken::StringLiteral)) {
1819     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_conflicts_message)
1820       << formatModuleId(Conflict.Id);
1821     return;
1822   }
1823   Conflict.Message = Tok.getString().str();
1824   consumeToken();
1825 
1826   // Add this unresolved conflict.
1827   ActiveModule->UnresolvedConflicts.push_back(Conflict);
1828 }
1829 
1830 /// \brief Parse an inferred module declaration (wildcard modules).
1831 ///
1832 ///   module-declaration:
1833 ///     'explicit'[opt] 'framework'[opt] 'module' * attributes[opt]
1834 ///       { inferred-module-member* }
1835 ///
1836 ///   inferred-module-member:
1837 ///     'export' '*'
1838 ///     'exclude' identifier
1839 void ModuleMapParser::parseInferredModuleDecl(bool Framework, bool Explicit) {
1840   assert(Tok.is(MMToken::Star));
1841   SourceLocation StarLoc = consumeToken();
1842   bool Failed = false;
1843 
1844   // Inferred modules must be submodules.
1845   if (!ActiveModule && !Framework) {
1846     Diags.Report(StarLoc, diag::err_mmap_top_level_inferred_submodule);
1847     Failed = true;
1848   }
1849 
1850   if (ActiveModule) {
1851     // Inferred modules must have umbrella directories.
1852     if (!Failed && !ActiveModule->getUmbrellaDir()) {
1853       Diags.Report(StarLoc, diag::err_mmap_inferred_no_umbrella);
1854       Failed = true;
1855     }
1856 
1857     // Check for redefinition of an inferred module.
1858     if (!Failed && ActiveModule->InferSubmodules) {
1859       Diags.Report(StarLoc, diag::err_mmap_inferred_redef);
1860       if (ActiveModule->InferredSubmoduleLoc.isValid())
1861         Diags.Report(ActiveModule->InferredSubmoduleLoc,
1862                      diag::note_mmap_prev_definition);
1863       Failed = true;
1864     }
1865 
1866     // Check for the 'framework' keyword, which is not permitted here.
1867     if (Framework) {
1868       Diags.Report(StarLoc, diag::err_mmap_inferred_framework_submodule);
1869       Framework = false;
1870     }
1871   } else if (Explicit) {
1872     Diags.Report(StarLoc, diag::err_mmap_explicit_inferred_framework);
1873     Explicit = false;
1874   }
1875 
1876   // If there were any problems with this inferred submodule, skip its body.
1877   if (Failed) {
1878     if (Tok.is(MMToken::LBrace)) {
1879       consumeToken();
1880       skipUntil(MMToken::RBrace);
1881       if (Tok.is(MMToken::RBrace))
1882         consumeToken();
1883     }
1884     HadError = true;
1885     return;
1886   }
1887 
1888   // Parse optional attributes.
1889   Attributes Attrs;
1890   parseOptionalAttributes(Attrs);
1891 
1892   if (ActiveModule) {
1893     // Note that we have an inferred submodule.
1894     ActiveModule->InferSubmodules = true;
1895     ActiveModule->InferredSubmoduleLoc = StarLoc;
1896     ActiveModule->InferExplicitSubmodules = Explicit;
1897   } else {
1898     // We'll be inferring framework modules for this directory.
1899     Map.InferredDirectories[Directory].InferModules = true;
1900     Map.InferredDirectories[Directory].InferSystemModules = Attrs.IsSystem;
1901   }
1902 
1903   // Parse the opening brace.
1904   if (!Tok.is(MMToken::LBrace)) {
1905     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_lbrace_wildcard);
1906     HadError = true;
1907     return;
1908   }
1909   SourceLocation LBraceLoc = consumeToken();
1910 
1911   // Parse the body of the inferred submodule.
1912   bool Done = false;
1913   do {
1914     switch (Tok.Kind) {
1915     case MMToken::EndOfFile:
1916     case MMToken::RBrace:
1917       Done = true;
1918       break;
1919 
1920     case MMToken::ExcludeKeyword: {
1921       if (ActiveModule) {
1922         Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member)
1923           << (ActiveModule != 0);
1924         consumeToken();
1925         break;
1926       }
1927 
1928       consumeToken();
1929       if (!Tok.is(MMToken::Identifier)) {
1930         Diags.Report(Tok.getLocation(), diag::err_mmap_missing_exclude_name);
1931         break;
1932       }
1933 
1934       Map.InferredDirectories[Directory].ExcludedModules
1935         .push_back(Tok.getString());
1936       consumeToken();
1937       break;
1938     }
1939 
1940     case MMToken::ExportKeyword:
1941       if (!ActiveModule) {
1942         Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member)
1943           << (ActiveModule != 0);
1944         consumeToken();
1945         break;
1946       }
1947 
1948       consumeToken();
1949       if (Tok.is(MMToken::Star))
1950         ActiveModule->InferExportWildcard = true;
1951       else
1952         Diags.Report(Tok.getLocation(),
1953                      diag::err_mmap_expected_export_wildcard);
1954       consumeToken();
1955       break;
1956 
1957     case MMToken::ExplicitKeyword:
1958     case MMToken::ModuleKeyword:
1959     case MMToken::HeaderKeyword:
1960     case MMToken::PrivateKeyword:
1961     case MMToken::UmbrellaKeyword:
1962     default:
1963       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member)
1964           << (ActiveModule != 0);
1965       consumeToken();
1966       break;
1967     }
1968   } while (!Done);
1969 
1970   if (Tok.is(MMToken::RBrace))
1971     consumeToken();
1972   else {
1973     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
1974     Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
1975     HadError = true;
1976   }
1977 }
1978 
1979 /// \brief Parse optional attributes.
1980 ///
1981 ///   attributes:
1982 ///     attribute attributes
1983 ///     attribute
1984 ///
1985 ///   attribute:
1986 ///     [ identifier ]
1987 ///
1988 /// \param Attrs Will be filled in with the parsed attributes.
1989 ///
1990 /// \returns true if an error occurred, false otherwise.
1991 bool ModuleMapParser::parseOptionalAttributes(Attributes &Attrs) {
1992   bool HadError = false;
1993 
1994   while (Tok.is(MMToken::LSquare)) {
1995     // Consume the '['.
1996     SourceLocation LSquareLoc = consumeToken();
1997 
1998     // Check whether we have an attribute name here.
1999     if (!Tok.is(MMToken::Identifier)) {
2000       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_attribute);
2001       skipUntil(MMToken::RSquare);
2002       if (Tok.is(MMToken::RSquare))
2003         consumeToken();
2004       HadError = true;
2005     }
2006 
2007     // Decode the attribute name.
2008     AttributeKind Attribute
2009       = llvm::StringSwitch<AttributeKind>(Tok.getString())
2010           .Case("exhaustive", AT_exhaustive)
2011           .Case("system", AT_system)
2012           .Default(AT_unknown);
2013     switch (Attribute) {
2014     case AT_unknown:
2015       Diags.Report(Tok.getLocation(), diag::warn_mmap_unknown_attribute)
2016         << Tok.getString();
2017       break;
2018 
2019     case AT_system:
2020       Attrs.IsSystem = true;
2021       break;
2022 
2023     case AT_exhaustive:
2024       Attrs.IsExhaustive = true;
2025       break;
2026     }
2027     consumeToken();
2028 
2029     // Consume the ']'.
2030     if (!Tok.is(MMToken::RSquare)) {
2031       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rsquare);
2032       Diags.Report(LSquareLoc, diag::note_mmap_lsquare_match);
2033       skipUntil(MMToken::RSquare);
2034       HadError = true;
2035     }
2036 
2037     if (Tok.is(MMToken::RSquare))
2038       consumeToken();
2039   }
2040 
2041   return HadError;
2042 }
2043 
2044 /// \brief If there is a specific header search directory due the presence
2045 /// of an umbrella directory, retrieve that directory. Otherwise, returns null.
2046 const DirectoryEntry *ModuleMapParser::getOverriddenHeaderSearchDir() {
2047   for (Module *Mod = ActiveModule; Mod; Mod = Mod->Parent) {
2048     // If we have an umbrella directory, use that.
2049     if (Mod->hasUmbrellaDir())
2050       return Mod->getUmbrellaDir();
2051 
2052     // If we have a framework directory, stop looking.
2053     if (Mod->IsFramework)
2054       return 0;
2055   }
2056 
2057   return 0;
2058 }
2059 
2060 /// \brief Parse a module map file.
2061 ///
2062 ///   module-map-file:
2063 ///     module-declaration*
2064 bool ModuleMapParser::parseModuleMapFile() {
2065   do {
2066     switch (Tok.Kind) {
2067     case MMToken::EndOfFile:
2068       return HadError;
2069 
2070     case MMToken::ExplicitKeyword:
2071     case MMToken::ExternKeyword:
2072     case MMToken::ModuleKeyword:
2073     case MMToken::FrameworkKeyword:
2074       parseModuleDecl();
2075       break;
2076 
2077     case MMToken::Comma:
2078     case MMToken::ConfigMacros:
2079     case MMToken::Conflict:
2080     case MMToken::Exclaim:
2081     case MMToken::ExcludeKeyword:
2082     case MMToken::ExportKeyword:
2083     case MMToken::HeaderKeyword:
2084     case MMToken::Identifier:
2085     case MMToken::LBrace:
2086     case MMToken::LinkKeyword:
2087     case MMToken::LSquare:
2088     case MMToken::Period:
2089     case MMToken::PrivateKeyword:
2090     case MMToken::RBrace:
2091     case MMToken::RSquare:
2092     case MMToken::RequiresKeyword:
2093     case MMToken::Star:
2094     case MMToken::StringLiteral:
2095     case MMToken::UmbrellaKeyword:
2096     case MMToken::UseKeyword:
2097       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module);
2098       HadError = true;
2099       consumeToken();
2100       break;
2101     }
2102   } while (true);
2103 }
2104 
2105 bool ModuleMap::parseModuleMapFile(const FileEntry *File, bool IsSystem) {
2106   llvm::DenseMap<const FileEntry *, bool>::iterator Known
2107     = ParsedModuleMap.find(File);
2108   if (Known != ParsedModuleMap.end())
2109     return Known->second;
2110 
2111   assert(Target != 0 && "Missing target information");
2112   FileID ID = SourceMgr.createFileID(File, SourceLocation(), SrcMgr::C_User);
2113   const llvm::MemoryBuffer *Buffer = SourceMgr.getBuffer(ID);
2114   if (!Buffer)
2115     return ParsedModuleMap[File] = true;
2116 
2117   // Parse this module map file.
2118   Lexer L(ID, SourceMgr.getBuffer(ID), SourceMgr, MMapLangOpts);
2119   ModuleMapParser Parser(L, SourceMgr, Target, Diags, *this, File->getDir(),
2120                          BuiltinIncludeDir, IsSystem);
2121   bool Result = Parser.parseModuleMapFile();
2122   ParsedModuleMap[File] = Result;
2123   return Result;
2124 }
2125