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