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