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