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