]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Lex/ModuleMap.cpp
Merge from vendor branch importing dtc 1.4.3
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / Lex / ModuleMap.cpp
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/HeaderSearchOptions.h"
23 #include "clang/Lex/LexDiagnostic.h"
24 #include "clang/Lex/Lexer.h"
25 #include "clang/Lex/LiteralSupport.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/ADT/StringSwitch.h"
28 #include "llvm/Support/Allocator.h"
29 #include "llvm/Support/FileSystem.h"
30 #include "llvm/Support/Host.h"
31 #include "llvm/Support/Path.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include <stdlib.h>
34 #if defined(LLVM_ON_UNIX)
35 #include <limits.h>
36 #endif
37 using namespace clang;
38
39 Module::ExportDecl 
40 ModuleMap::resolveExport(Module *Mod, 
41                          const Module::UnresolvedExportDecl &Unresolved,
42                          bool Complain) const {
43   // We may have just a wildcard.
44   if (Unresolved.Id.empty()) {
45     assert(Unresolved.Wildcard && "Invalid unresolved export");
46     return Module::ExportDecl(nullptr, true);
47   }
48   
49   // Resolve the module-id.
50   Module *Context = resolveModuleId(Unresolved.Id, Mod, Complain);
51   if (!Context)
52     return Module::ExportDecl();
53
54   return Module::ExportDecl(Context, Unresolved.Wildcard);
55 }
56
57 Module *ModuleMap::resolveModuleId(const ModuleId &Id, Module *Mod,
58                                    bool Complain) const {
59   // Find the starting module.
60   Module *Context = lookupModuleUnqualified(Id[0].first, Mod);
61   if (!Context) {
62     if (Complain)
63       Diags.Report(Id[0].second, diag::err_mmap_missing_module_unqualified)
64       << Id[0].first << Mod->getFullModuleName();
65
66     return nullptr;
67   }
68
69   // Dig into the module path.
70   for (unsigned I = 1, N = Id.size(); I != N; ++I) {
71     Module *Sub = lookupModuleQualified(Id[I].first, Context);
72     if (!Sub) {
73       if (Complain)
74         Diags.Report(Id[I].second, diag::err_mmap_missing_module_qualified)
75         << Id[I].first << Context->getFullModuleName()
76         << SourceRange(Id[0].second, Id[I-1].second);
77
78       return nullptr;
79     }
80
81     Context = Sub;
82   }
83
84   return Context;
85 }
86
87 ModuleMap::ModuleMap(SourceManager &SourceMgr, DiagnosticsEngine &Diags,
88                      const LangOptions &LangOpts, const TargetInfo *Target,
89                      HeaderSearch &HeaderInfo)
90     : SourceMgr(SourceMgr), Diags(Diags), LangOpts(LangOpts), Target(Target),
91       HeaderInfo(HeaderInfo), BuiltinIncludeDir(nullptr),
92       SourceModule(nullptr), NumCreatedModules(0) {
93   MMapLangOpts.LineComment = true;
94 }
95
96 ModuleMap::~ModuleMap() {
97   for (auto &M : Modules)
98     delete M.getValue();
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 bool ModuleMap::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("stdatomic.h", true)
155            .Case("stdbool.h", true)
156            .Case("stddef.h", true)
157            .Case("stdint.h", true)
158            .Case("tgmath.h", true)
159            .Case("unwind.h", true)
160            .Default(false);
161 }
162
163 ModuleMap::HeadersMap::iterator
164 ModuleMap::findKnownHeader(const FileEntry *File) {
165   HeadersMap::iterator Known = Headers.find(File);
166   if (HeaderInfo.getHeaderSearchOpts().ImplicitModuleMaps &&
167       Known == Headers.end() && File->getDir() == BuiltinIncludeDir &&
168       ModuleMap::isBuiltinHeader(llvm::sys::path::filename(File->getName()))) {
169     HeaderInfo.loadTopLevelSystemModules();
170     return Headers.find(File);
171   }
172   return Known;
173 }
174
175 ModuleMap::KnownHeader
176 ModuleMap::findHeaderInUmbrellaDirs(const FileEntry *File,
177                     SmallVectorImpl<const DirectoryEntry *> &IntermediateDirs) {
178   if (UmbrellaDirs.empty())
179     return KnownHeader();
180
181   const DirectoryEntry *Dir = File->getDir();
182   assert(Dir && "file in no directory");
183
184   // Note: as an egregious but useful hack we use the real path here, because
185   // frameworks moving from top-level frameworks to embedded frameworks tend
186   // to be symlinked from the top-level location to the embedded location,
187   // and we need to resolve lookups as if we had found the embedded location.
188   StringRef DirName = SourceMgr.getFileManager().getCanonicalName(Dir);
189
190   // Keep walking up the directory hierarchy, looking for a directory with
191   // an umbrella header.
192   do {
193     auto KnownDir = UmbrellaDirs.find(Dir);
194     if (KnownDir != UmbrellaDirs.end())
195       return KnownHeader(KnownDir->second, NormalHeader);
196
197     IntermediateDirs.push_back(Dir);
198
199     // Retrieve our parent path.
200     DirName = llvm::sys::path::parent_path(DirName);
201     if (DirName.empty())
202       break;
203
204     // Resolve the parent path to a directory entry.
205     Dir = SourceMgr.getFileManager().getDirectory(DirName);
206   } while (Dir);
207   return KnownHeader();
208 }
209
210 static bool violatesPrivateInclude(Module *RequestingModule,
211                                    const FileEntry *IncFileEnt,
212                                    ModuleMap::KnownHeader Header) {
213 #ifndef NDEBUG
214   if (Header.getRole() & ModuleMap::PrivateHeader) {
215     // Check for consistency between the module header role
216     // as obtained from the lookup and as obtained from the module.
217     // This check is not cheap, so enable it only for debugging.
218     bool IsPrivate = false;
219     SmallVectorImpl<Module::Header> *HeaderList[] = {
220         &Header.getModule()->Headers[Module::HK_Private],
221         &Header.getModule()->Headers[Module::HK_PrivateTextual]};
222     for (auto *Hs : HeaderList)
223       IsPrivate |=
224           std::find_if(Hs->begin(), Hs->end(), [&](const Module::Header &H) {
225             return H.Entry == IncFileEnt;
226           }) != Hs->end();
227     assert(IsPrivate && "inconsistent headers and roles");
228   }
229 #endif
230   return !Header.isAccessibleFrom(RequestingModule);
231 }
232
233 static Module *getTopLevelOrNull(Module *M) {
234   return M ? M->getTopLevelModule() : nullptr;
235 }
236
237 void ModuleMap::diagnoseHeaderInclusion(Module *RequestingModule,
238                                         bool RequestingModuleIsModuleInterface,
239                                         SourceLocation FilenameLoc,
240                                         StringRef Filename,
241                                         const FileEntry *File) {
242   // No errors for indirect modules. This may be a bit of a problem for modules
243   // with no source files.
244   if (getTopLevelOrNull(RequestingModule) != getTopLevelOrNull(SourceModule))
245     return;
246
247   if (RequestingModule)
248     resolveUses(RequestingModule, /*Complain=*/false);
249
250   bool Excluded = false;
251   Module *Private = nullptr;
252   Module *NotUsed = nullptr;
253
254   HeadersMap::iterator Known = findKnownHeader(File);
255   if (Known != Headers.end()) {
256     for (const KnownHeader &Header : Known->second) {
257       // Remember private headers for later printing of a diagnostic.
258       if (violatesPrivateInclude(RequestingModule, File, Header)) {
259         Private = Header.getModule();
260         continue;
261       }
262
263       // If uses need to be specified explicitly, we are only allowed to return
264       // modules that are explicitly used by the requesting module.
265       if (RequestingModule && LangOpts.ModulesDeclUse &&
266           !RequestingModule->directlyUses(Header.getModule())) {
267         NotUsed = Header.getModule();
268         continue;
269       }
270
271       // We have found a module that we can happily use.
272       return;
273     }
274
275     Excluded = true;
276   }
277
278   // We have found a header, but it is private.
279   if (Private) {
280     Diags.Report(FilenameLoc, diag::warn_use_of_private_header_outside_module)
281         << Filename;
282     return;
283   }
284
285   // We have found a module, but we don't use it.
286   if (NotUsed) {
287     Diags.Report(FilenameLoc, diag::err_undeclared_use_of_module)
288         << RequestingModule->getFullModuleName() << Filename;
289     return;
290   }
291
292   if (Excluded || isHeaderInUmbrellaDirs(File))
293     return;
294
295   // At this point, only non-modular includes remain.
296
297   if (LangOpts.ModulesStrictDeclUse) {
298     Diags.Report(FilenameLoc, diag::err_undeclared_use_of_module)
299         << RequestingModule->getFullModuleName() << Filename;
300   } else if (RequestingModule && RequestingModuleIsModuleInterface &&
301              LangOpts.isCompilingModule()) {
302     // Do not diagnose when we are not compiling a module. 
303     diag::kind DiagID = RequestingModule->getTopLevelModule()->IsFramework ?
304         diag::warn_non_modular_include_in_framework_module :
305         diag::warn_non_modular_include_in_module;
306     Diags.Report(FilenameLoc, DiagID) << RequestingModule->getFullModuleName()
307         << File->getName();
308   }
309 }
310
311 static bool isBetterKnownHeader(const ModuleMap::KnownHeader &New,
312                                 const ModuleMap::KnownHeader &Old) {
313   // Prefer available modules.
314   if (New.getModule()->isAvailable() && !Old.getModule()->isAvailable())
315     return true;
316
317   // Prefer a public header over a private header.
318   if ((New.getRole() & ModuleMap::PrivateHeader) !=
319       (Old.getRole() & ModuleMap::PrivateHeader))
320     return !(New.getRole() & ModuleMap::PrivateHeader);
321
322   // Prefer a non-textual header over a textual header.
323   if ((New.getRole() & ModuleMap::TextualHeader) !=
324       (Old.getRole() & ModuleMap::TextualHeader))
325     return !(New.getRole() & ModuleMap::TextualHeader);
326
327   // Don't have a reason to choose between these. Just keep the first one.
328   return false;
329 }
330
331 ModuleMap::KnownHeader ModuleMap::findModuleForHeader(const FileEntry *File,
332                                                       bool AllowTextual) {
333   auto MakeResult = [&](ModuleMap::KnownHeader R) -> ModuleMap::KnownHeader {
334     if (!AllowTextual && R.getRole() & ModuleMap::TextualHeader)
335       return ModuleMap::KnownHeader();
336     return R;
337   };
338
339   HeadersMap::iterator Known = findKnownHeader(File);
340   if (Known != Headers.end()) {
341     ModuleMap::KnownHeader Result;
342     // Iterate over all modules that 'File' is part of to find the best fit.
343     for (KnownHeader &H : Known->second) {
344       // Prefer a header from the source module over all others.
345       if (H.getModule()->getTopLevelModule() == SourceModule)
346         return MakeResult(H);
347       if (!Result || isBetterKnownHeader(H, Result))
348         Result = H;
349     }
350     return MakeResult(Result);
351   }
352
353   return MakeResult(findOrCreateModuleForHeaderInUmbrellaDir(File));
354 }
355
356 ModuleMap::KnownHeader
357 ModuleMap::findOrCreateModuleForHeaderInUmbrellaDir(const FileEntry *File) {
358   assert(!Headers.count(File) && "already have a module for this header");
359
360   SmallVector<const DirectoryEntry *, 2> SkippedDirs;
361   KnownHeader H = findHeaderInUmbrellaDirs(File, SkippedDirs);
362   if (H) {
363     Module *Result = H.getModule();
364
365     // Search up the module stack until we find a module with an umbrella
366     // directory.
367     Module *UmbrellaModule = Result;
368     while (!UmbrellaModule->getUmbrellaDir() && UmbrellaModule->Parent)
369       UmbrellaModule = UmbrellaModule->Parent;
370
371     if (UmbrellaModule->InferSubmodules) {
372       const FileEntry *UmbrellaModuleMap =
373           getModuleMapFileForUniquing(UmbrellaModule);
374
375       // Infer submodules for each of the directories we found between
376       // the directory of the umbrella header and the directory where
377       // the actual header is located.
378       bool Explicit = UmbrellaModule->InferExplicitSubmodules;
379
380       for (unsigned I = SkippedDirs.size(); I != 0; --I) {
381         // Find or create the module that corresponds to this directory name.
382         SmallString<32> NameBuf;
383         StringRef Name = sanitizeFilenameAsIdentifier(
384             llvm::sys::path::stem(SkippedDirs[I-1]->getName()), NameBuf);
385         Result = findOrCreateModule(Name, Result, /*IsFramework=*/false,
386                                     Explicit).first;
387         InferredModuleAllowedBy[Result] = UmbrellaModuleMap;
388         Result->IsInferred = true;
389
390         // Associate the module and the directory.
391         UmbrellaDirs[SkippedDirs[I-1]] = Result;
392
393         // If inferred submodules export everything they import, add a
394         // wildcard to the set of exports.
395         if (UmbrellaModule->InferExportWildcard && Result->Exports.empty())
396           Result->Exports.push_back(Module::ExportDecl(nullptr, true));
397       }
398
399       // Infer a submodule with the same name as this header file.
400       SmallString<32> NameBuf;
401       StringRef Name = sanitizeFilenameAsIdentifier(
402                          llvm::sys::path::stem(File->getName()), NameBuf);
403       Result = findOrCreateModule(Name, Result, /*IsFramework=*/false,
404                                   Explicit).first;
405       InferredModuleAllowedBy[Result] = UmbrellaModuleMap;
406       Result->IsInferred = true;
407       Result->addTopHeader(File);
408
409       // If inferred submodules export everything they import, add a
410       // wildcard to the set of exports.
411       if (UmbrellaModule->InferExportWildcard && Result->Exports.empty())
412         Result->Exports.push_back(Module::ExportDecl(nullptr, true));
413     } else {
414       // Record each of the directories we stepped through as being part of
415       // the module we found, since the umbrella header covers them all.
416       for (unsigned I = 0, N = SkippedDirs.size(); I != N; ++I)
417         UmbrellaDirs[SkippedDirs[I]] = Result;
418     }
419
420     KnownHeader Header(Result, NormalHeader);
421     Headers[File].push_back(Header);
422     return Header;
423   }
424
425   return KnownHeader();
426 }
427
428 ArrayRef<ModuleMap::KnownHeader>
429 ModuleMap::findAllModulesForHeader(const FileEntry *File) const {
430   auto It = Headers.find(File);
431   if (It == Headers.end())
432     return None;
433   return It->second;
434 }
435
436 bool ModuleMap::isHeaderInUnavailableModule(const FileEntry *Header) const {
437   return isHeaderUnavailableInModule(Header, nullptr);
438 }
439
440 bool
441 ModuleMap::isHeaderUnavailableInModule(const FileEntry *Header,
442                                        const Module *RequestingModule) const {
443   HeadersMap::const_iterator Known = Headers.find(Header);
444   if (Known != Headers.end()) {
445     for (SmallVectorImpl<KnownHeader>::const_iterator
446              I = Known->second.begin(),
447              E = Known->second.end();
448          I != E; ++I) {
449
450       if (I->isAvailable() &&
451           (!RequestingModule ||
452            I->getModule()->isSubModuleOf(RequestingModule))) {
453         // When no requesting module is available, the caller is looking if a
454         // header is part a module by only looking into the module map. This is
455         // done by warn_uncovered_module_header checks; don't consider textual
456         // headers part of it in this mode, otherwise we get misleading warnings
457         // that a umbrella header is not including a textual header.
458         if (!RequestingModule && I->getRole() == ModuleMap::TextualHeader)
459           continue;
460         return false;
461       }
462     }
463     return true;
464   }
465
466   const DirectoryEntry *Dir = Header->getDir();
467   SmallVector<const DirectoryEntry *, 2> SkippedDirs;
468   StringRef DirName = Dir->getName();
469
470   auto IsUnavailable = [&](const Module *M) {
471     return !M->isAvailable() && (!RequestingModule ||
472                                  M->isSubModuleOf(RequestingModule));
473   };
474
475   // Keep walking up the directory hierarchy, looking for a directory with
476   // an umbrella header.
477   do {
478     llvm::DenseMap<const DirectoryEntry *, Module *>::const_iterator KnownDir
479       = UmbrellaDirs.find(Dir);
480     if (KnownDir != UmbrellaDirs.end()) {
481       Module *Found = KnownDir->second;
482       if (IsUnavailable(Found))
483         return true;
484
485       // Search up the module stack until we find a module with an umbrella
486       // directory.
487       Module *UmbrellaModule = Found;
488       while (!UmbrellaModule->getUmbrellaDir() && UmbrellaModule->Parent)
489         UmbrellaModule = UmbrellaModule->Parent;
490
491       if (UmbrellaModule->InferSubmodules) {
492         for (unsigned I = SkippedDirs.size(); I != 0; --I) {
493           // Find or create the module that corresponds to this directory name.
494           SmallString<32> NameBuf;
495           StringRef Name = sanitizeFilenameAsIdentifier(
496                              llvm::sys::path::stem(SkippedDirs[I-1]->getName()),
497                              NameBuf);
498           Found = lookupModuleQualified(Name, Found);
499           if (!Found)
500             return false;
501           if (IsUnavailable(Found))
502             return true;
503         }
504         
505         // Infer a submodule with the same name as this header file.
506         SmallString<32> NameBuf;
507         StringRef Name = sanitizeFilenameAsIdentifier(
508                            llvm::sys::path::stem(Header->getName()),
509                            NameBuf);
510         Found = lookupModuleQualified(Name, Found);
511         if (!Found)
512           return false;
513       }
514
515       return IsUnavailable(Found);
516     }
517     
518     SkippedDirs.push_back(Dir);
519     
520     // Retrieve our parent path.
521     DirName = llvm::sys::path::parent_path(DirName);
522     if (DirName.empty())
523       break;
524     
525     // Resolve the parent path to a directory entry.
526     Dir = SourceMgr.getFileManager().getDirectory(DirName);
527   } while (Dir);
528   
529   return false;
530 }
531
532 Module *ModuleMap::findModule(StringRef Name) const {
533   llvm::StringMap<Module *>::const_iterator Known = Modules.find(Name);
534   if (Known != Modules.end())
535     return Known->getValue();
536
537   return nullptr;
538 }
539
540 Module *ModuleMap::lookupModuleUnqualified(StringRef Name,
541                                            Module *Context) const {
542   for(; Context; Context = Context->Parent) {
543     if (Module *Sub = lookupModuleQualified(Name, Context))
544       return Sub;
545   }
546   
547   return findModule(Name);
548 }
549
550 Module *ModuleMap::lookupModuleQualified(StringRef Name, Module *Context) const{
551   if (!Context)
552     return findModule(Name);
553   
554   return Context->findSubmodule(Name);
555 }
556
557 std::pair<Module *, bool> 
558 ModuleMap::findOrCreateModule(StringRef Name, Module *Parent, bool IsFramework,
559                               bool IsExplicit) {
560   // Try to find an existing module with this name.
561   if (Module *Sub = lookupModuleQualified(Name, Parent))
562     return std::make_pair(Sub, false);
563   
564   // Create a new module with this name.
565   Module *Result = new Module(Name, SourceLocation(), Parent,
566                               IsFramework, IsExplicit, NumCreatedModules++);
567   if (!Parent) {
568     if (LangOpts.CurrentModule == Name)
569       SourceModule = Result;
570     Modules[Name] = Result;
571   }
572   return std::make_pair(Result, true);
573 }
574
575 Module *ModuleMap::createModuleForInterfaceUnit(SourceLocation Loc,
576                                                 StringRef Name) {
577   assert(LangOpts.CurrentModule == Name && "module name mismatch");
578   assert(!Modules[Name] && "redefining existing module");
579
580   auto *Result =
581       new Module(Name, Loc, nullptr, /*IsFramework*/ false,
582                  /*IsExplicit*/ false, NumCreatedModules++);
583   Modules[Name] = SourceModule = Result;
584
585   // Mark the main source file as being within the newly-created module so that
586   // declarations and macros are properly visibility-restricted to it.
587   auto *MainFile = SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
588   assert(MainFile && "no input file for module interface");
589   Headers[MainFile].push_back(KnownHeader(Result, PrivateHeader));
590
591   return Result;
592 }
593
594 /// \brief For a framework module, infer the framework against which we
595 /// should link.
596 static void inferFrameworkLink(Module *Mod, const DirectoryEntry *FrameworkDir,
597                                FileManager &FileMgr) {
598   assert(Mod->IsFramework && "Can only infer linking for framework modules");
599   assert(!Mod->isSubFramework() &&
600          "Can only infer linking for top-level frameworks");
601
602   SmallString<128> LibName;
603   LibName += FrameworkDir->getName();
604   llvm::sys::path::append(LibName, Mod->Name);
605
606   // The library name of a framework has more than one possible extension since
607   // the introduction of the text-based dynamic library format. We need to check
608   // for both before we give up.
609   for (const char *extension : {"", ".tbd"}) {
610     llvm::sys::path::replace_extension(LibName, extension);
611     if (FileMgr.getFile(LibName)) {
612       Mod->LinkLibraries.push_back(Module::LinkLibrary(Mod->Name,
613                                                        /*IsFramework=*/true));
614       return;
615     }
616   }
617 }
618
619 Module *ModuleMap::inferFrameworkModule(const DirectoryEntry *FrameworkDir,
620                                         bool IsSystem, Module *Parent) {
621   Attributes Attrs;
622   Attrs.IsSystem = IsSystem;
623   return inferFrameworkModule(FrameworkDir, Attrs, Parent);
624 }
625
626 Module *ModuleMap::inferFrameworkModule(const DirectoryEntry *FrameworkDir,
627                                         Attributes Attrs, Module *Parent) {
628   // Note: as an egregious but useful hack we use the real path here, because
629   // we might be looking at an embedded framework that symlinks out to a
630   // top-level framework, and we need to infer as if we were naming the
631   // top-level framework.
632   StringRef FrameworkDirName =
633       SourceMgr.getFileManager().getCanonicalName(FrameworkDir);
634
635   // In case this is a case-insensitive filesystem, use the canonical
636   // directory name as the ModuleName, since modules are case-sensitive.
637   // FIXME: we should be able to give a fix-it hint for the correct spelling.
638   SmallString<32> ModuleNameStorage;
639   StringRef ModuleName = sanitizeFilenameAsIdentifier(
640       llvm::sys::path::stem(FrameworkDirName), ModuleNameStorage);
641
642   // Check whether we've already found this module.
643   if (Module *Mod = lookupModuleQualified(ModuleName, Parent))
644     return Mod;
645   
646   FileManager &FileMgr = SourceMgr.getFileManager();
647
648   // If the framework has a parent path from which we're allowed to infer
649   // a framework module, do so.
650   const FileEntry *ModuleMapFile = nullptr;
651   if (!Parent) {
652     // Determine whether we're allowed to infer a module map.
653     bool canInfer = false;
654     if (llvm::sys::path::has_parent_path(FrameworkDirName)) {
655       // Figure out the parent path.
656       StringRef Parent = llvm::sys::path::parent_path(FrameworkDirName);
657       if (const DirectoryEntry *ParentDir = FileMgr.getDirectory(Parent)) {
658         // Check whether we have already looked into the parent directory
659         // for a module map.
660         llvm::DenseMap<const DirectoryEntry *, InferredDirectory>::const_iterator
661           inferred = InferredDirectories.find(ParentDir);
662         if (inferred == InferredDirectories.end()) {
663           // We haven't looked here before. Load a module map, if there is
664           // one.
665           bool IsFrameworkDir = Parent.endswith(".framework");
666           if (const FileEntry *ModMapFile =
667                 HeaderInfo.lookupModuleMapFile(ParentDir, IsFrameworkDir)) {
668             parseModuleMapFile(ModMapFile, Attrs.IsSystem, ParentDir);
669             inferred = InferredDirectories.find(ParentDir);
670           }
671
672           if (inferred == InferredDirectories.end())
673             inferred = InferredDirectories.insert(
674                          std::make_pair(ParentDir, InferredDirectory())).first;
675         }
676
677         if (inferred->second.InferModules) {
678           // We're allowed to infer for this directory, but make sure it's okay
679           // to infer this particular module.
680           StringRef Name = llvm::sys::path::stem(FrameworkDirName);
681           canInfer = std::find(inferred->second.ExcludedModules.begin(),
682                                inferred->second.ExcludedModules.end(),
683                                Name) == inferred->second.ExcludedModules.end();
684
685           Attrs.IsSystem |= inferred->second.Attrs.IsSystem;
686           Attrs.IsExternC |= inferred->second.Attrs.IsExternC;
687           Attrs.IsExhaustive |= inferred->second.Attrs.IsExhaustive;
688           Attrs.NoUndeclaredIncludes |=
689               inferred->second.Attrs.NoUndeclaredIncludes;
690           ModuleMapFile = inferred->second.ModuleMapFile;
691         }
692       }
693     }
694
695     // If we're not allowed to infer a framework module, don't.
696     if (!canInfer)
697       return nullptr;
698   } else
699     ModuleMapFile = getModuleMapFileForUniquing(Parent);
700
701
702   // Look for an umbrella header.
703   SmallString<128> UmbrellaName = StringRef(FrameworkDir->getName());
704   llvm::sys::path::append(UmbrellaName, "Headers", ModuleName + ".h");
705   const FileEntry *UmbrellaHeader = FileMgr.getFile(UmbrellaName);
706   
707   // FIXME: If there's no umbrella header, we could probably scan the
708   // framework to load *everything*. But, it's not clear that this is a good
709   // idea.
710   if (!UmbrellaHeader)
711     return nullptr;
712
713   Module *Result = new Module(ModuleName, SourceLocation(), Parent,
714                               /*IsFramework=*/true, /*IsExplicit=*/false,
715                               NumCreatedModules++);
716   InferredModuleAllowedBy[Result] = ModuleMapFile;
717   Result->IsInferred = true;
718   if (!Parent) {
719     if (LangOpts.CurrentModule == ModuleName)
720       SourceModule = Result;
721     Modules[ModuleName] = Result;
722   }
723
724   Result->IsSystem |= Attrs.IsSystem;
725   Result->IsExternC |= Attrs.IsExternC;
726   Result->ConfigMacrosExhaustive |= Attrs.IsExhaustive;
727   Result->NoUndeclaredIncludes |= Attrs.NoUndeclaredIncludes;
728   Result->Directory = FrameworkDir;
729
730   // umbrella header "umbrella-header-name"
731   //
732   // The "Headers/" component of the name is implied because this is
733   // a framework module.
734   setUmbrellaHeader(Result, UmbrellaHeader, ModuleName + ".h");
735   
736   // export *
737   Result->Exports.push_back(Module::ExportDecl(nullptr, true));
738
739   // module * { export * }
740   Result->InferSubmodules = true;
741   Result->InferExportWildcard = true;
742   
743   // Look for subframeworks.
744   std::error_code EC;
745   SmallString<128> SubframeworksDirName
746     = StringRef(FrameworkDir->getName());
747   llvm::sys::path::append(SubframeworksDirName, "Frameworks");
748   llvm::sys::path::native(SubframeworksDirName);
749   vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
750   for (vfs::directory_iterator Dir = FS.dir_begin(SubframeworksDirName, EC),
751                                DirEnd;
752        Dir != DirEnd && !EC; Dir.increment(EC)) {
753     if (!StringRef(Dir->getName()).endswith(".framework"))
754       continue;
755
756     if (const DirectoryEntry *SubframeworkDir =
757             FileMgr.getDirectory(Dir->getName())) {
758       // Note: as an egregious but useful hack, we use the real path here and
759       // check whether it is actually a subdirectory of the parent directory.
760       // This will not be the case if the 'subframework' is actually a symlink
761       // out to a top-level framework.
762       StringRef SubframeworkDirName = FileMgr.getCanonicalName(SubframeworkDir);
763       bool FoundParent = false;
764       do {
765         // Get the parent directory name.
766         SubframeworkDirName
767           = llvm::sys::path::parent_path(SubframeworkDirName);
768         if (SubframeworkDirName.empty())
769           break;
770
771         if (FileMgr.getDirectory(SubframeworkDirName) == FrameworkDir) {
772           FoundParent = true;
773           break;
774         }
775       } while (true);
776
777       if (!FoundParent)
778         continue;
779
780       // FIXME: Do we want to warn about subframeworks without umbrella headers?
781       inferFrameworkModule(SubframeworkDir, Attrs, Result);
782     }
783   }
784
785   // If the module is a top-level framework, automatically link against the
786   // framework.
787   if (!Result->isSubFramework()) {
788     inferFrameworkLink(Result, FrameworkDir, FileMgr);
789   }
790
791   return Result;
792 }
793
794 void ModuleMap::setUmbrellaHeader(Module *Mod, const FileEntry *UmbrellaHeader,
795                                   Twine NameAsWritten) {
796   Headers[UmbrellaHeader].push_back(KnownHeader(Mod, NormalHeader));
797   Mod->Umbrella = UmbrellaHeader;
798   Mod->UmbrellaAsWritten = NameAsWritten.str();
799   UmbrellaDirs[UmbrellaHeader->getDir()] = Mod;
800
801   // Notify callbacks that we just added a new header.
802   for (const auto &Cb : Callbacks)
803     Cb->moduleMapAddUmbrellaHeader(&SourceMgr.getFileManager(), UmbrellaHeader);
804 }
805
806 void ModuleMap::setUmbrellaDir(Module *Mod, const DirectoryEntry *UmbrellaDir,
807                                Twine NameAsWritten) {
808   Mod->Umbrella = UmbrellaDir;
809   Mod->UmbrellaAsWritten = NameAsWritten.str();
810   UmbrellaDirs[UmbrellaDir] = Mod;
811 }
812
813 static Module::HeaderKind headerRoleToKind(ModuleMap::ModuleHeaderRole Role) {
814   switch ((int)Role) {
815   default: llvm_unreachable("unknown header role");
816   case ModuleMap::NormalHeader:
817     return Module::HK_Normal;
818   case ModuleMap::PrivateHeader:
819     return Module::HK_Private;
820   case ModuleMap::TextualHeader:
821     return Module::HK_Textual;
822   case ModuleMap::PrivateHeader | ModuleMap::TextualHeader:
823     return Module::HK_PrivateTextual;
824   }
825 }
826
827 void ModuleMap::addHeader(Module *Mod, Module::Header Header,
828                           ModuleHeaderRole Role, bool Imported) {
829   KnownHeader KH(Mod, Role);
830
831   // Only add each header to the headers list once.
832   // FIXME: Should we diagnose if a header is listed twice in the
833   // same module definition?
834   auto &HeaderList = Headers[Header.Entry];
835   for (auto H : HeaderList)
836     if (H == KH)
837       return;
838
839   HeaderList.push_back(KH);
840   Mod->Headers[headerRoleToKind(Role)].push_back(Header);
841
842   bool isCompilingModuleHeader =
843       LangOpts.isCompilingModule() && Mod->getTopLevelModule() == SourceModule;
844   if (!Imported || isCompilingModuleHeader) {
845     // When we import HeaderFileInfo, the external source is expected to
846     // set the isModuleHeader flag itself.
847     HeaderInfo.MarkFileModuleHeader(Header.Entry, Role,
848                                     isCompilingModuleHeader);
849   }
850
851   // Notify callbacks that we just added a new header.
852   for (const auto &Cb : Callbacks)
853     Cb->moduleMapAddHeader(Header.Entry->getName());
854 }
855
856 void ModuleMap::excludeHeader(Module *Mod, Module::Header Header) {
857   // Add this as a known header so we won't implicitly add it to any
858   // umbrella directory module.
859   // FIXME: Should we only exclude it from umbrella modules within the
860   // specified module?
861   (void) Headers[Header.Entry];
862
863   Mod->Headers[Module::HK_Excluded].push_back(std::move(Header));
864 }
865
866 const FileEntry *
867 ModuleMap::getContainingModuleMapFile(const Module *Module) const {
868   if (Module->DefinitionLoc.isInvalid())
869     return nullptr;
870
871   return SourceMgr.getFileEntryForID(
872            SourceMgr.getFileID(Module->DefinitionLoc));
873 }
874
875 const FileEntry *ModuleMap::getModuleMapFileForUniquing(const Module *M) const {
876   if (M->IsInferred) {
877     assert(InferredModuleAllowedBy.count(M) && "missing inferred module map");
878     return InferredModuleAllowedBy.find(M)->second;
879   }
880   return getContainingModuleMapFile(M);
881 }
882
883 void ModuleMap::setInferredModuleAllowedBy(Module *M, const FileEntry *ModMap) {
884   assert(M->IsInferred && "module not inferred");
885   InferredModuleAllowedBy[M] = ModMap;
886 }
887
888 LLVM_DUMP_METHOD void ModuleMap::dump() {
889   llvm::errs() << "Modules:";
890   for (llvm::StringMap<Module *>::iterator M = Modules.begin(), 
891                                         MEnd = Modules.end(); 
892        M != MEnd; ++M)
893     M->getValue()->print(llvm::errs(), 2);
894   
895   llvm::errs() << "Headers:";
896   for (HeadersMap::iterator H = Headers.begin(), HEnd = Headers.end();
897        H != HEnd; ++H) {
898     llvm::errs() << "  \"" << H->first->getName() << "\" -> ";
899     for (SmallVectorImpl<KnownHeader>::const_iterator I = H->second.begin(),
900                                                       E = H->second.end();
901          I != E; ++I) {
902       if (I != H->second.begin())
903         llvm::errs() << ",";
904       llvm::errs() << I->getModule()->getFullModuleName();
905     }
906     llvm::errs() << "\n";
907   }
908 }
909
910 bool ModuleMap::resolveExports(Module *Mod, bool Complain) {
911   auto Unresolved = std::move(Mod->UnresolvedExports);
912   Mod->UnresolvedExports.clear();
913   for (auto &UE : Unresolved) {
914     Module::ExportDecl Export = resolveExport(Mod, UE, Complain);
915     if (Export.getPointer() || Export.getInt())
916       Mod->Exports.push_back(Export);
917     else
918       Mod->UnresolvedExports.push_back(UE);
919   }
920   return !Mod->UnresolvedExports.empty();
921 }
922
923 bool ModuleMap::resolveUses(Module *Mod, bool Complain) {
924   auto Unresolved = std::move(Mod->UnresolvedDirectUses);
925   Mod->UnresolvedDirectUses.clear();
926   for (auto &UDU : Unresolved) {
927     Module *DirectUse = resolveModuleId(UDU, Mod, Complain);
928     if (DirectUse)
929       Mod->DirectUses.push_back(DirectUse);
930     else
931       Mod->UnresolvedDirectUses.push_back(UDU);
932   }
933   return !Mod->UnresolvedDirectUses.empty();
934 }
935
936 bool ModuleMap::resolveConflicts(Module *Mod, bool Complain) {
937   auto Unresolved = std::move(Mod->UnresolvedConflicts);
938   Mod->UnresolvedConflicts.clear();
939   for (auto &UC : Unresolved) {
940     if (Module *OtherMod = resolveModuleId(UC.Id, Mod, Complain)) {
941       Module::Conflict Conflict;
942       Conflict.Other = OtherMod;
943       Conflict.Message = UC.Message;
944       Mod->Conflicts.push_back(Conflict);
945     } else
946       Mod->UnresolvedConflicts.push_back(UC);
947   }
948   return !Mod->UnresolvedConflicts.empty();
949 }
950
951 Module *ModuleMap::inferModuleFromLocation(FullSourceLoc Loc) {
952   if (Loc.isInvalid())
953     return nullptr;
954
955   if (UmbrellaDirs.empty() && Headers.empty())
956     return nullptr;
957
958   // Use the expansion location to determine which module we're in.
959   FullSourceLoc ExpansionLoc = Loc.getExpansionLoc();
960   if (!ExpansionLoc.isFileID())
961     return nullptr;
962
963   const SourceManager &SrcMgr = Loc.getManager();
964   FileID ExpansionFileID = ExpansionLoc.getFileID();
965   
966   while (const FileEntry *ExpansionFile
967            = SrcMgr.getFileEntryForID(ExpansionFileID)) {
968     // Find the module that owns this header (if any).
969     if (Module *Mod = findModuleForHeader(ExpansionFile).getModule())
970       return Mod;
971     
972     // No module owns this header, so look up the inclusion chain to see if
973     // any included header has an associated module.
974     SourceLocation IncludeLoc = SrcMgr.getIncludeLoc(ExpansionFileID);
975     if (IncludeLoc.isInvalid())
976       return nullptr;
977
978     ExpansionFileID = SrcMgr.getFileID(IncludeLoc);
979   }
980
981   return nullptr;
982 }
983
984 //----------------------------------------------------------------------------//
985 // Module map file parser
986 //----------------------------------------------------------------------------//
987
988 namespace clang {
989   /// \brief A token in a module map file.
990   struct MMToken {
991     enum TokenKind {
992       Comma,
993       ConfigMacros,
994       Conflict,
995       EndOfFile,
996       HeaderKeyword,
997       Identifier,
998       Exclaim,
999       ExcludeKeyword,
1000       ExplicitKeyword,
1001       ExportKeyword,
1002       ExternKeyword,
1003       FrameworkKeyword,
1004       LinkKeyword,
1005       ModuleKeyword,
1006       Period,
1007       PrivateKeyword,
1008       UmbrellaKeyword,
1009       UseKeyword,
1010       RequiresKeyword,
1011       Star,
1012       StringLiteral,
1013       TextualKeyword,
1014       LBrace,
1015       RBrace,
1016       LSquare,
1017       RSquare
1018     } Kind;
1019     
1020     unsigned Location;
1021     unsigned StringLength;
1022     const char *StringData;
1023     
1024     void clear() {
1025       Kind = EndOfFile;
1026       Location = 0;
1027       StringLength = 0;
1028       StringData = nullptr;
1029     }
1030     
1031     bool is(TokenKind K) const { return Kind == K; }
1032     
1033     SourceLocation getLocation() const {
1034       return SourceLocation::getFromRawEncoding(Location);
1035     }
1036     
1037     StringRef getString() const {
1038       return StringRef(StringData, StringLength);
1039     }
1040   };
1041
1042   class ModuleMapParser {
1043     Lexer &L;
1044     SourceManager &SourceMgr;
1045
1046     /// \brief Default target information, used only for string literal
1047     /// parsing.
1048     const TargetInfo *Target;
1049
1050     DiagnosticsEngine &Diags;
1051     ModuleMap &Map;
1052
1053     /// \brief The current module map file.
1054     const FileEntry *ModuleMapFile;
1055     
1056     /// \brief The directory that file names in this module map file should
1057     /// be resolved relative to.
1058     const DirectoryEntry *Directory;
1059
1060     /// \brief The directory containing Clang-supplied headers.
1061     const DirectoryEntry *BuiltinIncludeDir;
1062
1063     /// \brief Whether this module map is in a system header directory.
1064     bool IsSystem;
1065     
1066     /// \brief Whether an error occurred.
1067     bool HadError;
1068         
1069     /// \brief Stores string data for the various string literals referenced
1070     /// during parsing.
1071     llvm::BumpPtrAllocator StringData;
1072     
1073     /// \brief The current token.
1074     MMToken Tok;
1075     
1076     /// \brief The active module.
1077     Module *ActiveModule;
1078
1079     /// \brief Whether a module uses the 'requires excluded' hack to mark its
1080     /// contents as 'textual'.
1081     ///
1082     /// On older Darwin SDK versions, 'requires excluded' is used to mark the
1083     /// contents of the Darwin.C.excluded (assert.h) and Tcl.Private modules as
1084     /// non-modular headers.  For backwards compatibility, we continue to
1085     /// support this idiom for just these modules, and map the headers to
1086     /// 'textual' to match the original intent.
1087     llvm::SmallPtrSet<Module *, 2> UsesRequiresExcludedHack;
1088
1089     /// \brief Consume the current token and return its location.
1090     SourceLocation consumeToken();
1091     
1092     /// \brief Skip tokens until we reach the a token with the given kind
1093     /// (or the end of the file).
1094     void skipUntil(MMToken::TokenKind K);
1095
1096     typedef SmallVector<std::pair<std::string, SourceLocation>, 2> ModuleId;
1097     bool parseModuleId(ModuleId &Id);
1098     void parseModuleDecl();
1099     void parseExternModuleDecl();
1100     void parseRequiresDecl();
1101     void parseHeaderDecl(clang::MMToken::TokenKind,
1102                          SourceLocation LeadingLoc);
1103     void parseUmbrellaDirDecl(SourceLocation UmbrellaLoc);
1104     void parseExportDecl();
1105     void parseUseDecl();
1106     void parseLinkDecl();
1107     void parseConfigMacros();
1108     void parseConflict();
1109     void parseInferredModuleDecl(bool Framework, bool Explicit);
1110
1111     typedef ModuleMap::Attributes Attributes;
1112     bool parseOptionalAttributes(Attributes &Attrs);
1113     
1114   public:
1115     explicit ModuleMapParser(Lexer &L, SourceManager &SourceMgr, 
1116                              const TargetInfo *Target,
1117                              DiagnosticsEngine &Diags,
1118                              ModuleMap &Map,
1119                              const FileEntry *ModuleMapFile,
1120                              const DirectoryEntry *Directory,
1121                              const DirectoryEntry *BuiltinIncludeDir,
1122                              bool IsSystem)
1123       : L(L), SourceMgr(SourceMgr), Target(Target), Diags(Diags), Map(Map), 
1124         ModuleMapFile(ModuleMapFile), Directory(Directory),
1125         BuiltinIncludeDir(BuiltinIncludeDir), IsSystem(IsSystem),
1126         HadError(false), ActiveModule(nullptr)
1127     {
1128       Tok.clear();
1129       consumeToken();
1130     }
1131     
1132     bool parseModuleMapFile();
1133   };
1134 }
1135
1136 SourceLocation ModuleMapParser::consumeToken() {
1137 retry:
1138   SourceLocation Result = Tok.getLocation();
1139   Tok.clear();
1140   
1141   Token LToken;
1142   L.LexFromRawLexer(LToken);
1143   Tok.Location = LToken.getLocation().getRawEncoding();
1144   switch (LToken.getKind()) {
1145   case tok::raw_identifier: {
1146     StringRef RI = LToken.getRawIdentifier();
1147     Tok.StringData = RI.data();
1148     Tok.StringLength = RI.size();
1149     Tok.Kind = llvm::StringSwitch<MMToken::TokenKind>(RI)
1150                  .Case("config_macros", MMToken::ConfigMacros)
1151                  .Case("conflict", MMToken::Conflict)
1152                  .Case("exclude", MMToken::ExcludeKeyword)
1153                  .Case("explicit", MMToken::ExplicitKeyword)
1154                  .Case("export", MMToken::ExportKeyword)
1155                  .Case("extern", MMToken::ExternKeyword)
1156                  .Case("framework", MMToken::FrameworkKeyword)
1157                  .Case("header", MMToken::HeaderKeyword)
1158                  .Case("link", MMToken::LinkKeyword)
1159                  .Case("module", MMToken::ModuleKeyword)
1160                  .Case("private", MMToken::PrivateKeyword)
1161                  .Case("requires", MMToken::RequiresKeyword)
1162                  .Case("textual", MMToken::TextualKeyword)
1163                  .Case("umbrella", MMToken::UmbrellaKeyword)
1164                  .Case("use", MMToken::UseKeyword)
1165                  .Default(MMToken::Identifier);
1166     break;
1167   }
1168
1169   case tok::comma:
1170     Tok.Kind = MMToken::Comma;
1171     break;
1172
1173   case tok::eof:
1174     Tok.Kind = MMToken::EndOfFile;
1175     break;
1176       
1177   case tok::l_brace:
1178     Tok.Kind = MMToken::LBrace;
1179     break;
1180
1181   case tok::l_square:
1182     Tok.Kind = MMToken::LSquare;
1183     break;
1184       
1185   case tok::period:
1186     Tok.Kind = MMToken::Period;
1187     break;
1188       
1189   case tok::r_brace:
1190     Tok.Kind = MMToken::RBrace;
1191     break;
1192       
1193   case tok::r_square:
1194     Tok.Kind = MMToken::RSquare;
1195     break;
1196       
1197   case tok::star:
1198     Tok.Kind = MMToken::Star;
1199     break;
1200       
1201   case tok::exclaim:
1202     Tok.Kind = MMToken::Exclaim;
1203     break;
1204       
1205   case tok::string_literal: {
1206     if (LToken.hasUDSuffix()) {
1207       Diags.Report(LToken.getLocation(), diag::err_invalid_string_udl);
1208       HadError = true;
1209       goto retry;
1210     }
1211
1212     // Parse the string literal.
1213     LangOptions LangOpts;
1214     StringLiteralParser StringLiteral(LToken, SourceMgr, LangOpts, *Target);
1215     if (StringLiteral.hadError)
1216       goto retry;
1217     
1218     // Copy the string literal into our string data allocator.
1219     unsigned Length = StringLiteral.GetStringLength();
1220     char *Saved = StringData.Allocate<char>(Length + 1);
1221     memcpy(Saved, StringLiteral.GetString().data(), Length);
1222     Saved[Length] = 0;
1223     
1224     // Form the token.
1225     Tok.Kind = MMToken::StringLiteral;
1226     Tok.StringData = Saved;
1227     Tok.StringLength = Length;
1228     break;
1229   }
1230       
1231   case tok::comment:
1232     goto retry;
1233       
1234   default:
1235     Diags.Report(LToken.getLocation(), diag::err_mmap_unknown_token);
1236     HadError = true;
1237     goto retry;
1238   }
1239   
1240   return Result;
1241 }
1242
1243 void ModuleMapParser::skipUntil(MMToken::TokenKind K) {
1244   unsigned braceDepth = 0;
1245   unsigned squareDepth = 0;
1246   do {
1247     switch (Tok.Kind) {
1248     case MMToken::EndOfFile:
1249       return;
1250
1251     case MMToken::LBrace:
1252       if (Tok.is(K) && braceDepth == 0 && squareDepth == 0)
1253         return;
1254         
1255       ++braceDepth;
1256       break;
1257
1258     case MMToken::LSquare:
1259       if (Tok.is(K) && braceDepth == 0 && squareDepth == 0)
1260         return;
1261       
1262       ++squareDepth;
1263       break;
1264
1265     case MMToken::RBrace:
1266       if (braceDepth > 0)
1267         --braceDepth;
1268       else if (Tok.is(K))
1269         return;
1270       break;
1271
1272     case MMToken::RSquare:
1273       if (squareDepth > 0)
1274         --squareDepth;
1275       else if (Tok.is(K))
1276         return;
1277       break;
1278
1279     default:
1280       if (braceDepth == 0 && squareDepth == 0 && Tok.is(K))
1281         return;
1282       break;
1283     }
1284     
1285    consumeToken();
1286   } while (true);
1287 }
1288
1289 /// \brief Parse a module-id.
1290 ///
1291 ///   module-id:
1292 ///     identifier
1293 ///     identifier '.' module-id
1294 ///
1295 /// \returns true if an error occurred, false otherwise.
1296 bool ModuleMapParser::parseModuleId(ModuleId &Id) {
1297   Id.clear();
1298   do {
1299     if (Tok.is(MMToken::Identifier) || Tok.is(MMToken::StringLiteral)) {
1300       Id.push_back(std::make_pair(Tok.getString(), Tok.getLocation()));
1301       consumeToken();
1302     } else {
1303       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module_name);
1304       return true;
1305     }
1306     
1307     if (!Tok.is(MMToken::Period))
1308       break;
1309     
1310     consumeToken();
1311   } while (true);
1312   
1313   return false;
1314 }
1315
1316 namespace {
1317   /// \brief Enumerates the known attributes.
1318   enum AttributeKind {
1319     /// \brief An unknown attribute.
1320     AT_unknown,
1321     /// \brief The 'system' attribute.
1322     AT_system,
1323     /// \brief The 'extern_c' attribute.
1324     AT_extern_c,
1325     /// \brief The 'exhaustive' attribute.
1326     AT_exhaustive,
1327     /// \brief The 'no_undeclared_includes' attribute.
1328     AT_no_undeclared_includes
1329   };
1330 }
1331
1332 /// \brief Parse a module declaration.
1333 ///
1334 ///   module-declaration:
1335 ///     'extern' 'module' module-id string-literal
1336 ///     'explicit'[opt] 'framework'[opt] 'module' module-id attributes[opt] 
1337 ///       { module-member* }
1338 ///
1339 ///   module-member:
1340 ///     requires-declaration
1341 ///     header-declaration
1342 ///     submodule-declaration
1343 ///     export-declaration
1344 ///     link-declaration
1345 ///
1346 ///   submodule-declaration:
1347 ///     module-declaration
1348 ///     inferred-submodule-declaration
1349 void ModuleMapParser::parseModuleDecl() {
1350   assert(Tok.is(MMToken::ExplicitKeyword) || Tok.is(MMToken::ModuleKeyword) ||
1351          Tok.is(MMToken::FrameworkKeyword) || Tok.is(MMToken::ExternKeyword));
1352   if (Tok.is(MMToken::ExternKeyword)) {
1353     parseExternModuleDecl();
1354     return;
1355   }
1356
1357   // Parse 'explicit' or 'framework' keyword, if present.
1358   SourceLocation ExplicitLoc;
1359   bool Explicit = false;
1360   bool Framework = false;
1361
1362   // Parse 'explicit' keyword, if present.
1363   if (Tok.is(MMToken::ExplicitKeyword)) {
1364     ExplicitLoc = consumeToken();
1365     Explicit = true;
1366   }
1367
1368   // Parse 'framework' keyword, if present.
1369   if (Tok.is(MMToken::FrameworkKeyword)) {
1370     consumeToken();
1371     Framework = true;
1372   } 
1373   
1374   // Parse 'module' keyword.
1375   if (!Tok.is(MMToken::ModuleKeyword)) {
1376     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module);
1377     consumeToken();
1378     HadError = true;
1379     return;
1380   }
1381   consumeToken(); // 'module' keyword
1382
1383   // If we have a wildcard for the module name, this is an inferred submodule.
1384   // Parse it. 
1385   if (Tok.is(MMToken::Star))
1386     return parseInferredModuleDecl(Framework, Explicit);
1387   
1388   // Parse the module name.
1389   ModuleId Id;
1390   if (parseModuleId(Id)) {
1391     HadError = true;
1392     return;
1393   }
1394
1395   if (ActiveModule) {
1396     if (Id.size() > 1) {
1397       Diags.Report(Id.front().second, diag::err_mmap_nested_submodule_id)
1398         << SourceRange(Id.front().second, Id.back().second);
1399       
1400       HadError = true;
1401       return;
1402     }
1403   } else if (Id.size() == 1 && Explicit) {
1404     // Top-level modules can't be explicit.
1405     Diags.Report(ExplicitLoc, diag::err_mmap_explicit_top_level);
1406     Explicit = false;
1407     ExplicitLoc = SourceLocation();
1408     HadError = true;
1409   }
1410   
1411   Module *PreviousActiveModule = ActiveModule;  
1412   if (Id.size() > 1) {
1413     // This module map defines a submodule. Go find the module of which it
1414     // is a submodule.
1415     ActiveModule = nullptr;
1416     const Module *TopLevelModule = nullptr;
1417     for (unsigned I = 0, N = Id.size() - 1; I != N; ++I) {
1418       if (Module *Next = Map.lookupModuleQualified(Id[I].first, ActiveModule)) {
1419         if (I == 0)
1420           TopLevelModule = Next;
1421         ActiveModule = Next;
1422         continue;
1423       }
1424       
1425       if (ActiveModule) {
1426         Diags.Report(Id[I].second, diag::err_mmap_missing_module_qualified)
1427           << Id[I].first
1428           << ActiveModule->getTopLevelModule()->getFullModuleName();
1429       } else {
1430         Diags.Report(Id[I].second, diag::err_mmap_expected_module_name);
1431       }
1432       HadError = true;
1433       return;
1434     }
1435
1436     if (ModuleMapFile != Map.getContainingModuleMapFile(TopLevelModule)) {
1437       assert(ModuleMapFile != Map.getModuleMapFileForUniquing(TopLevelModule) &&
1438              "submodule defined in same file as 'module *' that allowed its "
1439              "top-level module");
1440       Map.addAdditionalModuleMapFile(TopLevelModule, ModuleMapFile);
1441     }
1442   }
1443   
1444   StringRef ModuleName = Id.back().first;
1445   SourceLocation ModuleNameLoc = Id.back().second;
1446   
1447   // Parse the optional attribute list.
1448   Attributes Attrs;
1449   if (parseOptionalAttributes(Attrs))
1450     return;
1451
1452   
1453   // Parse the opening brace.
1454   if (!Tok.is(MMToken::LBrace)) {
1455     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_lbrace)
1456       << ModuleName;
1457     HadError = true;
1458     return;
1459   }  
1460   SourceLocation LBraceLoc = consumeToken();
1461   
1462   // Determine whether this (sub)module has already been defined.
1463   if (Module *Existing = Map.lookupModuleQualified(ModuleName, ActiveModule)) {
1464     if (Existing->DefinitionLoc.isInvalid() && !ActiveModule) {
1465       // Skip the module definition.
1466       skipUntil(MMToken::RBrace);
1467       if (Tok.is(MMToken::RBrace))
1468         consumeToken();
1469       else {
1470         Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
1471         Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
1472         HadError = true;        
1473       }
1474       return;
1475     }
1476     
1477     Diags.Report(ModuleNameLoc, diag::err_mmap_module_redefinition)
1478       << ModuleName;
1479     Diags.Report(Existing->DefinitionLoc, diag::note_mmap_prev_definition);
1480     
1481     // Skip the module definition.
1482     skipUntil(MMToken::RBrace);
1483     if (Tok.is(MMToken::RBrace))
1484       consumeToken();
1485     
1486     HadError = true;
1487     return;
1488   }
1489
1490   // Start defining this module.
1491   ActiveModule = Map.findOrCreateModule(ModuleName, ActiveModule, Framework,
1492                                         Explicit).first;
1493   ActiveModule->DefinitionLoc = ModuleNameLoc;
1494   if (Attrs.IsSystem || IsSystem)
1495     ActiveModule->IsSystem = true;
1496   if (Attrs.IsExternC)
1497     ActiveModule->IsExternC = true;
1498   if (Attrs.NoUndeclaredIncludes ||
1499       (!ActiveModule->Parent && ModuleName == "Darwin"))
1500     ActiveModule->NoUndeclaredIncludes = true;
1501   ActiveModule->Directory = Directory;
1502
1503   if (!ActiveModule->Parent) {
1504     StringRef MapFileName(ModuleMapFile->getName());
1505     if (MapFileName.endswith("module.private.modulemap") ||
1506         MapFileName.endswith("module_private.map")) {
1507       // Adding a top-level module from a private modulemap is likely a
1508       // user error; we check to see if there's another top-level module
1509       // defined in the non-private map in the same dir, and if so emit a
1510       // warning.
1511       for (auto E = Map.module_begin(); E != Map.module_end(); ++E) {
1512         auto const *M = E->getValue();
1513         if (!M->Parent &&
1514             M->Directory == ActiveModule->Directory &&
1515             M->Name != ActiveModule->Name) {
1516           Diags.Report(ActiveModule->DefinitionLoc,
1517                        diag::warn_mmap_mismatched_top_level_private)
1518             << ActiveModule->Name << M->Name;
1519           // The pattern we're defending against here is typically due to
1520           // a module named FooPrivate which is supposed to be a submodule
1521           // called Foo.Private. Emit a fixit in that case.
1522           auto D =
1523             Diags.Report(ActiveModule->DefinitionLoc,
1524                          diag::note_mmap_rename_top_level_private_as_submodule);
1525           D << ActiveModule->Name << M->Name;
1526           StringRef Bad(ActiveModule->Name);
1527           if (Bad.consume_back("Private")) {
1528             SmallString<128> Fixed = Bad;
1529             Fixed.append(".Private");
1530             D << FixItHint::CreateReplacement(ActiveModule->DefinitionLoc,
1531                                               Fixed);
1532           }
1533           break;
1534         }
1535       }
1536     }
1537   }
1538
1539   bool Done = false;
1540   do {
1541     switch (Tok.Kind) {
1542     case MMToken::EndOfFile:
1543     case MMToken::RBrace:
1544       Done = true;
1545       break;
1546
1547     case MMToken::ConfigMacros:
1548       parseConfigMacros();
1549       break;
1550
1551     case MMToken::Conflict:
1552       parseConflict();
1553       break;
1554
1555     case MMToken::ExplicitKeyword:
1556     case MMToken::ExternKeyword:
1557     case MMToken::FrameworkKeyword:
1558     case MMToken::ModuleKeyword:
1559       parseModuleDecl();
1560       break;
1561
1562     case MMToken::ExportKeyword:
1563       parseExportDecl();
1564       break;
1565
1566     case MMToken::UseKeyword:
1567       parseUseDecl();
1568       break;
1569         
1570     case MMToken::RequiresKeyword:
1571       parseRequiresDecl();
1572       break;
1573
1574     case MMToken::TextualKeyword:
1575       parseHeaderDecl(MMToken::TextualKeyword, consumeToken());
1576       break;
1577
1578     case MMToken::UmbrellaKeyword: {
1579       SourceLocation UmbrellaLoc = consumeToken();
1580       if (Tok.is(MMToken::HeaderKeyword))
1581         parseHeaderDecl(MMToken::UmbrellaKeyword, UmbrellaLoc);
1582       else
1583         parseUmbrellaDirDecl(UmbrellaLoc);
1584       break;
1585     }
1586
1587     case MMToken::ExcludeKeyword:
1588       parseHeaderDecl(MMToken::ExcludeKeyword, consumeToken());
1589       break;
1590
1591     case MMToken::PrivateKeyword:
1592       parseHeaderDecl(MMToken::PrivateKeyword, consumeToken());
1593       break;
1594
1595     case MMToken::HeaderKeyword:
1596       parseHeaderDecl(MMToken::HeaderKeyword, consumeToken());
1597       break;
1598
1599     case MMToken::LinkKeyword:
1600       parseLinkDecl();
1601       break;
1602
1603     default:
1604       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_member);
1605       consumeToken();
1606       break;        
1607     }
1608   } while (!Done);
1609
1610   if (Tok.is(MMToken::RBrace))
1611     consumeToken();
1612   else {
1613     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
1614     Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
1615     HadError = true;
1616   }
1617
1618   // If the active module is a top-level framework, and there are no link
1619   // libraries, automatically link against the framework.
1620   if (ActiveModule->IsFramework && !ActiveModule->isSubFramework() &&
1621       ActiveModule->LinkLibraries.empty()) {
1622     inferFrameworkLink(ActiveModule, Directory, SourceMgr.getFileManager());
1623   }
1624
1625   // If the module meets all requirements but is still unavailable, mark the
1626   // whole tree as unavailable to prevent it from building.
1627   if (!ActiveModule->IsAvailable && !ActiveModule->IsMissingRequirement &&
1628       ActiveModule->Parent) {
1629     ActiveModule->getTopLevelModule()->markUnavailable();
1630     ActiveModule->getTopLevelModule()->MissingHeaders.append(
1631       ActiveModule->MissingHeaders.begin(), ActiveModule->MissingHeaders.end());
1632   }
1633
1634   // We're done parsing this module. Pop back to the previous module.
1635   ActiveModule = PreviousActiveModule;
1636 }
1637
1638 /// \brief Parse an extern module declaration.
1639 ///
1640 ///   extern module-declaration:
1641 ///     'extern' 'module' module-id string-literal
1642 void ModuleMapParser::parseExternModuleDecl() {
1643   assert(Tok.is(MMToken::ExternKeyword));
1644   SourceLocation ExternLoc = consumeToken(); // 'extern' keyword
1645
1646   // Parse 'module' keyword.
1647   if (!Tok.is(MMToken::ModuleKeyword)) {
1648     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module);
1649     consumeToken();
1650     HadError = true;
1651     return;
1652   }
1653   consumeToken(); // 'module' keyword
1654
1655   // Parse the module name.
1656   ModuleId Id;
1657   if (parseModuleId(Id)) {
1658     HadError = true;
1659     return;
1660   }
1661
1662   // Parse the referenced module map file name.
1663   if (!Tok.is(MMToken::StringLiteral)) {
1664     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_mmap_file);
1665     HadError = true;
1666     return;
1667   }
1668   std::string FileName = Tok.getString();
1669   consumeToken(); // filename
1670
1671   StringRef FileNameRef = FileName;
1672   SmallString<128> ModuleMapFileName;
1673   if (llvm::sys::path::is_relative(FileNameRef)) {
1674     ModuleMapFileName += Directory->getName();
1675     llvm::sys::path::append(ModuleMapFileName, FileName);
1676     FileNameRef = ModuleMapFileName;
1677   }
1678   if (const FileEntry *File = SourceMgr.getFileManager().getFile(FileNameRef))
1679     Map.parseModuleMapFile(
1680         File, /*IsSystem=*/false,
1681         Map.HeaderInfo.getHeaderSearchOpts().ModuleMapFileHomeIsCwd
1682             ? Directory
1683             : File->getDir(), ExternLoc);
1684 }
1685
1686 /// Whether to add the requirement \p Feature to the module \p M.
1687 ///
1688 /// This preserves backwards compatibility for two hacks in the Darwin system
1689 /// module map files:
1690 ///
1691 /// 1. The use of 'requires excluded' to make headers non-modular, which
1692 ///    should really be mapped to 'textual' now that we have this feature.  We
1693 ///    drop the 'excluded' requirement, and set \p IsRequiresExcludedHack to
1694 ///    true.  Later, this bit will be used to map all the headers inside this
1695 ///    module to 'textual'.
1696 ///
1697 ///    This affects Darwin.C.excluded (for assert.h) and Tcl.Private.
1698 ///
1699 /// 2. Removes a bogus cplusplus requirement from IOKit.avc.  This requirement
1700 ///    was never correct and causes issues now that we check it, so drop it.
1701 static bool shouldAddRequirement(Module *M, StringRef Feature,
1702                                  bool &IsRequiresExcludedHack) {
1703   if (Feature == "excluded" &&
1704       (M->fullModuleNameIs({"Darwin", "C", "excluded"}) ||
1705        M->fullModuleNameIs({"Tcl", "Private"}))) {
1706     IsRequiresExcludedHack = true;
1707     return false;
1708   } else if (Feature == "cplusplus" && M->fullModuleNameIs({"IOKit", "avc"})) {
1709     return false;
1710   }
1711
1712   return true;
1713 }
1714
1715 /// \brief Parse a requires declaration.
1716 ///
1717 ///   requires-declaration:
1718 ///     'requires' feature-list
1719 ///
1720 ///   feature-list:
1721 ///     feature ',' feature-list
1722 ///     feature
1723 ///
1724 ///   feature:
1725 ///     '!'[opt] identifier
1726 void ModuleMapParser::parseRequiresDecl() {
1727   assert(Tok.is(MMToken::RequiresKeyword));
1728
1729   // Parse 'requires' keyword.
1730   consumeToken();
1731
1732   // Parse the feature-list.
1733   do {
1734     bool RequiredState = true;
1735     if (Tok.is(MMToken::Exclaim)) {
1736       RequiredState = false;
1737       consumeToken();
1738     }
1739
1740     if (!Tok.is(MMToken::Identifier)) {
1741       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_feature);
1742       HadError = true;
1743       return;
1744     }
1745
1746     // Consume the feature name.
1747     std::string Feature = Tok.getString();
1748     consumeToken();
1749
1750     bool IsRequiresExcludedHack = false;
1751     bool ShouldAddRequirement =
1752         shouldAddRequirement(ActiveModule, Feature, IsRequiresExcludedHack);
1753
1754     if (IsRequiresExcludedHack)
1755       UsesRequiresExcludedHack.insert(ActiveModule);
1756
1757     if (ShouldAddRequirement) {
1758       // Add this feature.
1759       ActiveModule->addRequirement(Feature, RequiredState, Map.LangOpts,
1760                                    *Map.Target);
1761     }
1762
1763     if (!Tok.is(MMToken::Comma))
1764       break;
1765
1766     // Consume the comma.
1767     consumeToken();
1768   } while (true);
1769 }
1770
1771 /// \brief Append to \p Paths the set of paths needed to get to the 
1772 /// subframework in which the given module lives.
1773 static void appendSubframeworkPaths(Module *Mod,
1774                                     SmallVectorImpl<char> &Path) {
1775   // Collect the framework names from the given module to the top-level module.
1776   SmallVector<StringRef, 2> Paths;
1777   for (; Mod; Mod = Mod->Parent) {
1778     if (Mod->IsFramework)
1779       Paths.push_back(Mod->Name);
1780   }
1781   
1782   if (Paths.empty())
1783     return;
1784   
1785   // Add Frameworks/Name.framework for each subframework.
1786   for (unsigned I = Paths.size() - 1; I != 0; --I)
1787     llvm::sys::path::append(Path, "Frameworks", Paths[I-1] + ".framework");
1788 }
1789
1790 /// \brief Parse a header declaration.
1791 ///
1792 ///   header-declaration:
1793 ///     'textual'[opt] 'header' string-literal
1794 ///     'private' 'textual'[opt] 'header' string-literal
1795 ///     'exclude' 'header' string-literal
1796 ///     'umbrella' 'header' string-literal
1797 ///
1798 /// FIXME: Support 'private textual header'.
1799 void ModuleMapParser::parseHeaderDecl(MMToken::TokenKind LeadingToken,
1800                                       SourceLocation LeadingLoc) {
1801   // We've already consumed the first token.
1802   ModuleMap::ModuleHeaderRole Role = ModuleMap::NormalHeader;
1803   if (LeadingToken == MMToken::PrivateKeyword) {
1804     Role = ModuleMap::PrivateHeader;
1805     // 'private' may optionally be followed by 'textual'.
1806     if (Tok.is(MMToken::TextualKeyword)) {
1807       LeadingToken = Tok.Kind;
1808       consumeToken();
1809     }
1810   }
1811
1812   if (LeadingToken == MMToken::TextualKeyword)
1813     Role = ModuleMap::ModuleHeaderRole(Role | ModuleMap::TextualHeader);
1814
1815   if (UsesRequiresExcludedHack.count(ActiveModule)) {
1816     // Mark this header 'textual' (see doc comment for
1817     // Module::UsesRequiresExcludedHack).
1818     Role = ModuleMap::ModuleHeaderRole(Role | ModuleMap::TextualHeader);
1819   }
1820
1821   if (LeadingToken != MMToken::HeaderKeyword) {
1822     if (!Tok.is(MMToken::HeaderKeyword)) {
1823       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
1824           << (LeadingToken == MMToken::PrivateKeyword ? "private" :
1825               LeadingToken == MMToken::ExcludeKeyword ? "exclude" :
1826               LeadingToken == MMToken::TextualKeyword ? "textual" : "umbrella");
1827       return;
1828     }
1829     consumeToken();
1830   }
1831
1832   // Parse the header name.
1833   if (!Tok.is(MMToken::StringLiteral)) {
1834     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header) 
1835       << "header";
1836     HadError = true;
1837     return;
1838   }
1839   Module::UnresolvedHeaderDirective Header;
1840   Header.FileName = Tok.getString();
1841   Header.FileNameLoc = consumeToken();
1842   
1843   // Check whether we already have an umbrella.
1844   if (LeadingToken == MMToken::UmbrellaKeyword && ActiveModule->Umbrella) {
1845     Diags.Report(Header.FileNameLoc, diag::err_mmap_umbrella_clash)
1846       << ActiveModule->getFullModuleName();
1847     HadError = true;
1848     return;
1849   }
1850
1851   // Look for this file.
1852   const FileEntry *File = nullptr;
1853   const FileEntry *BuiltinFile = nullptr;
1854   SmallString<128> RelativePathName;
1855   if (llvm::sys::path::is_absolute(Header.FileName)) {
1856     RelativePathName = Header.FileName;
1857     File = SourceMgr.getFileManager().getFile(RelativePathName);
1858   } else {
1859     // Search for the header file within the search directory.
1860     SmallString<128> FullPathName(Directory->getName());
1861     unsigned FullPathLength = FullPathName.size();
1862     
1863     if (ActiveModule->isPartOfFramework()) {
1864       appendSubframeworkPaths(ActiveModule, RelativePathName);
1865       
1866       // Check whether this file is in the public headers.
1867       llvm::sys::path::append(RelativePathName, "Headers", Header.FileName);
1868       llvm::sys::path::append(FullPathName, RelativePathName);
1869       File = SourceMgr.getFileManager().getFile(FullPathName);
1870       
1871       if (!File) {
1872         // Check whether this file is in the private headers.
1873         // FIXME: Should we retain the subframework paths here?
1874         RelativePathName.clear();
1875         FullPathName.resize(FullPathLength);
1876         llvm::sys::path::append(RelativePathName, "PrivateHeaders",
1877                                 Header.FileName);
1878         llvm::sys::path::append(FullPathName, RelativePathName);
1879         File = SourceMgr.getFileManager().getFile(FullPathName);
1880       }
1881     } else {
1882       // Lookup for normal headers.
1883       llvm::sys::path::append(RelativePathName, Header.FileName);
1884       llvm::sys::path::append(FullPathName, RelativePathName);
1885       File = SourceMgr.getFileManager().getFile(FullPathName);
1886
1887       // If this is a system module with a top-level header, this header
1888       // may have a counterpart (or replacement) in the set of headers
1889       // supplied by Clang. Find that builtin header.
1890       if (ActiveModule->IsSystem && LeadingToken != MMToken::UmbrellaKeyword &&
1891           BuiltinIncludeDir && BuiltinIncludeDir != Directory &&
1892           ModuleMap::isBuiltinHeader(Header.FileName)) {
1893         SmallString<128> BuiltinPathName(BuiltinIncludeDir->getName());
1894         llvm::sys::path::append(BuiltinPathName, Header.FileName);
1895         BuiltinFile = SourceMgr.getFileManager().getFile(BuiltinPathName);
1896
1897         // If Clang supplies this header but the underlying system does not,
1898         // just silently swap in our builtin version. Otherwise, we'll end
1899         // up adding both (later).
1900         if (BuiltinFile && !File) {
1901           File = BuiltinFile;
1902           RelativePathName = BuiltinPathName;
1903           BuiltinFile = nullptr;
1904         }
1905       }
1906     }
1907   }
1908
1909   // FIXME: We shouldn't be eagerly stat'ing every file named in a module map.
1910   // Come up with a lazy way to do this.
1911   if (File) {
1912     if (LeadingToken == MMToken::UmbrellaKeyword) {
1913       const DirectoryEntry *UmbrellaDir = File->getDir();
1914       if (Module *UmbrellaModule = Map.UmbrellaDirs[UmbrellaDir]) {
1915         Diags.Report(LeadingLoc, diag::err_mmap_umbrella_clash)
1916           << UmbrellaModule->getFullModuleName();
1917         HadError = true;
1918       } else {
1919         // Record this umbrella header.
1920         Map.setUmbrellaHeader(ActiveModule, File, RelativePathName.str());
1921       }
1922     } else if (LeadingToken == MMToken::ExcludeKeyword) {
1923       Module::Header H = {RelativePathName.str(), File};
1924       Map.excludeHeader(ActiveModule, H);
1925     } else {
1926       // If there is a builtin counterpart to this file, add it now so it can
1927       // wrap the system header.
1928       if (BuiltinFile) {
1929         // FIXME: Taking the name from the FileEntry is unstable and can give
1930         // different results depending on how we've previously named that file
1931         // in this build.
1932         Module::Header H = { BuiltinFile->getName(), BuiltinFile };
1933         Map.addHeader(ActiveModule, H, Role);
1934
1935         // If we have both a builtin and system version of the file, the
1936         // builtin version may want to inject macros into the system header, so
1937         // force the system header to be treated as a textual header in this
1938         // case.
1939         Role = ModuleMap::ModuleHeaderRole(Role | ModuleMap::TextualHeader);
1940       }
1941
1942       // Record this header.
1943       Module::Header H = { RelativePathName.str(), File };
1944       Map.addHeader(ActiveModule, H, Role);
1945     }
1946   } else if (LeadingToken != MMToken::ExcludeKeyword) {
1947     // Ignore excluded header files. They're optional anyway.
1948
1949     // If we find a module that has a missing header, we mark this module as
1950     // unavailable and store the header directive for displaying diagnostics.
1951     Header.IsUmbrella = LeadingToken == MMToken::UmbrellaKeyword;
1952     ActiveModule->markUnavailable();
1953     ActiveModule->MissingHeaders.push_back(Header);
1954   }
1955 }
1956
1957 static int compareModuleHeaders(const Module::Header *A,
1958                                 const Module::Header *B) {
1959   return A->NameAsWritten.compare(B->NameAsWritten);
1960 }
1961
1962 /// \brief Parse an umbrella directory declaration.
1963 ///
1964 ///   umbrella-dir-declaration:
1965 ///     umbrella string-literal
1966 void ModuleMapParser::parseUmbrellaDirDecl(SourceLocation UmbrellaLoc) {
1967   // Parse the directory name.
1968   if (!Tok.is(MMToken::StringLiteral)) {
1969     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header) 
1970       << "umbrella";
1971     HadError = true;
1972     return;
1973   }
1974
1975   std::string DirName = Tok.getString();
1976   SourceLocation DirNameLoc = consumeToken();
1977   
1978   // Check whether we already have an umbrella.
1979   if (ActiveModule->Umbrella) {
1980     Diags.Report(DirNameLoc, diag::err_mmap_umbrella_clash)
1981       << ActiveModule->getFullModuleName();
1982     HadError = true;
1983     return;
1984   }
1985
1986   // Look for this file.
1987   const DirectoryEntry *Dir = nullptr;
1988   if (llvm::sys::path::is_absolute(DirName))
1989     Dir = SourceMgr.getFileManager().getDirectory(DirName);
1990   else {
1991     SmallString<128> PathName;
1992     PathName = Directory->getName();
1993     llvm::sys::path::append(PathName, DirName);
1994     Dir = SourceMgr.getFileManager().getDirectory(PathName);
1995   }
1996   
1997   if (!Dir) {
1998     Diags.Report(DirNameLoc, diag::err_mmap_umbrella_dir_not_found)
1999       << DirName;
2000     HadError = true;
2001     return;
2002   }
2003
2004   if (UsesRequiresExcludedHack.count(ActiveModule)) {
2005     // Mark this header 'textual' (see doc comment for
2006     // ModuleMapParser::UsesRequiresExcludedHack). Although iterating over the
2007     // directory is relatively expensive, in practice this only applies to the
2008     // uncommonly used Tcl module on Darwin platforms.
2009     std::error_code EC;
2010     SmallVector<Module::Header, 6> Headers;
2011     vfs::FileSystem &FS = *SourceMgr.getFileManager().getVirtualFileSystem();
2012     for (vfs::recursive_directory_iterator I(FS, Dir->getName(), EC), E;
2013          I != E && !EC; I.increment(EC)) {
2014       if (const FileEntry *FE =
2015               SourceMgr.getFileManager().getFile(I->getName())) {
2016
2017         Module::Header Header = {I->getName(), FE};
2018         Headers.push_back(std::move(Header));
2019       }
2020     }
2021
2022     // Sort header paths so that the pcm doesn't depend on iteration order.
2023     llvm::array_pod_sort(Headers.begin(), Headers.end(), compareModuleHeaders);
2024
2025     for (auto &Header : Headers)
2026       Map.addHeader(ActiveModule, std::move(Header), ModuleMap::TextualHeader);
2027     return;
2028   }
2029
2030   if (Module *OwningModule = Map.UmbrellaDirs[Dir]) {
2031     Diags.Report(UmbrellaLoc, diag::err_mmap_umbrella_clash)
2032       << OwningModule->getFullModuleName();
2033     HadError = true;
2034     return;
2035   }
2036
2037   // Record this umbrella directory.
2038   Map.setUmbrellaDir(ActiveModule, Dir, DirName);
2039 }
2040
2041 /// \brief Parse a module export declaration.
2042 ///
2043 ///   export-declaration:
2044 ///     'export' wildcard-module-id
2045 ///
2046 ///   wildcard-module-id:
2047 ///     identifier
2048 ///     '*'
2049 ///     identifier '.' wildcard-module-id
2050 void ModuleMapParser::parseExportDecl() {
2051   assert(Tok.is(MMToken::ExportKeyword));
2052   SourceLocation ExportLoc = consumeToken();
2053   
2054   // Parse the module-id with an optional wildcard at the end.
2055   ModuleId ParsedModuleId;
2056   bool Wildcard = false;
2057   do {
2058     // FIXME: Support string-literal module names here.
2059     if (Tok.is(MMToken::Identifier)) {
2060       ParsedModuleId.push_back(std::make_pair(Tok.getString(), 
2061                                               Tok.getLocation()));
2062       consumeToken();
2063       
2064       if (Tok.is(MMToken::Period)) {
2065         consumeToken();
2066         continue;
2067       } 
2068       
2069       break;
2070     }
2071     
2072     if(Tok.is(MMToken::Star)) {
2073       Wildcard = true;
2074       consumeToken();
2075       break;
2076     }
2077     
2078     Diags.Report(Tok.getLocation(), diag::err_mmap_module_id);
2079     HadError = true;
2080     return;
2081   } while (true);
2082   
2083   Module::UnresolvedExportDecl Unresolved = { 
2084     ExportLoc, ParsedModuleId, Wildcard 
2085   };
2086   ActiveModule->UnresolvedExports.push_back(Unresolved);
2087 }
2088
2089 /// \brief Parse a module use declaration.
2090 ///
2091 ///   use-declaration:
2092 ///     'use' wildcard-module-id
2093 void ModuleMapParser::parseUseDecl() {
2094   assert(Tok.is(MMToken::UseKeyword));
2095   auto KWLoc = consumeToken();
2096   // Parse the module-id.
2097   ModuleId ParsedModuleId;
2098   parseModuleId(ParsedModuleId);
2099
2100   if (ActiveModule->Parent)
2101     Diags.Report(KWLoc, diag::err_mmap_use_decl_submodule);
2102   else
2103     ActiveModule->UnresolvedDirectUses.push_back(ParsedModuleId);
2104 }
2105
2106 /// \brief Parse a link declaration.
2107 ///
2108 ///   module-declaration:
2109 ///     'link' 'framework'[opt] string-literal
2110 void ModuleMapParser::parseLinkDecl() {
2111   assert(Tok.is(MMToken::LinkKeyword));
2112   SourceLocation LinkLoc = consumeToken();
2113
2114   // Parse the optional 'framework' keyword.
2115   bool IsFramework = false;
2116   if (Tok.is(MMToken::FrameworkKeyword)) {
2117     consumeToken();
2118     IsFramework = true;
2119   }
2120
2121   // Parse the library name
2122   if (!Tok.is(MMToken::StringLiteral)) {
2123     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_library_name)
2124       << IsFramework << SourceRange(LinkLoc);
2125     HadError = true;
2126     return;
2127   }
2128
2129   std::string LibraryName = Tok.getString();
2130   consumeToken();
2131   ActiveModule->LinkLibraries.push_back(Module::LinkLibrary(LibraryName,
2132                                                             IsFramework));
2133 }
2134
2135 /// \brief Parse a configuration macro declaration.
2136 ///
2137 ///   module-declaration:
2138 ///     'config_macros' attributes[opt] config-macro-list?
2139 ///
2140 ///   config-macro-list:
2141 ///     identifier (',' identifier)?
2142 void ModuleMapParser::parseConfigMacros() {
2143   assert(Tok.is(MMToken::ConfigMacros));
2144   SourceLocation ConfigMacrosLoc = consumeToken();
2145
2146   // Only top-level modules can have configuration macros.
2147   if (ActiveModule->Parent) {
2148     Diags.Report(ConfigMacrosLoc, diag::err_mmap_config_macro_submodule);
2149   }
2150
2151   // Parse the optional attributes.
2152   Attributes Attrs;
2153   if (parseOptionalAttributes(Attrs))
2154     return;
2155
2156   if (Attrs.IsExhaustive && !ActiveModule->Parent) {
2157     ActiveModule->ConfigMacrosExhaustive = true;
2158   }
2159
2160   // If we don't have an identifier, we're done.
2161   // FIXME: Support macros with the same name as a keyword here.
2162   if (!Tok.is(MMToken::Identifier))
2163     return;
2164
2165   // Consume the first identifier.
2166   if (!ActiveModule->Parent) {
2167     ActiveModule->ConfigMacros.push_back(Tok.getString().str());
2168   }
2169   consumeToken();
2170
2171   do {
2172     // If there's a comma, consume it.
2173     if (!Tok.is(MMToken::Comma))
2174       break;
2175     consumeToken();
2176
2177     // We expect to see a macro name here.
2178     // FIXME: Support macros with the same name as a keyword here.
2179     if (!Tok.is(MMToken::Identifier)) {
2180       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_config_macro);
2181       break;
2182     }
2183
2184     // Consume the macro name.
2185     if (!ActiveModule->Parent) {
2186       ActiveModule->ConfigMacros.push_back(Tok.getString().str());
2187     }
2188     consumeToken();
2189   } while (true);
2190 }
2191
2192 /// \brief Format a module-id into a string.
2193 static std::string formatModuleId(const ModuleId &Id) {
2194   std::string result;
2195   {
2196     llvm::raw_string_ostream OS(result);
2197
2198     for (unsigned I = 0, N = Id.size(); I != N; ++I) {
2199       if (I)
2200         OS << ".";
2201       OS << Id[I].first;
2202     }
2203   }
2204
2205   return result;
2206 }
2207
2208 /// \brief Parse a conflict declaration.
2209 ///
2210 ///   module-declaration:
2211 ///     'conflict' module-id ',' string-literal
2212 void ModuleMapParser::parseConflict() {
2213   assert(Tok.is(MMToken::Conflict));
2214   SourceLocation ConflictLoc = consumeToken();
2215   Module::UnresolvedConflict Conflict;
2216
2217   // Parse the module-id.
2218   if (parseModuleId(Conflict.Id))
2219     return;
2220
2221   // Parse the ','.
2222   if (!Tok.is(MMToken::Comma)) {
2223     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_conflicts_comma)
2224       << SourceRange(ConflictLoc);
2225     return;
2226   }
2227   consumeToken();
2228
2229   // Parse the message.
2230   if (!Tok.is(MMToken::StringLiteral)) {
2231     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_conflicts_message)
2232       << formatModuleId(Conflict.Id);
2233     return;
2234   }
2235   Conflict.Message = Tok.getString().str();
2236   consumeToken();
2237
2238   // Add this unresolved conflict.
2239   ActiveModule->UnresolvedConflicts.push_back(Conflict);
2240 }
2241
2242 /// \brief Parse an inferred module declaration (wildcard modules).
2243 ///
2244 ///   module-declaration:
2245 ///     'explicit'[opt] 'framework'[opt] 'module' * attributes[opt]
2246 ///       { inferred-module-member* }
2247 ///
2248 ///   inferred-module-member:
2249 ///     'export' '*'
2250 ///     'exclude' identifier
2251 void ModuleMapParser::parseInferredModuleDecl(bool Framework, bool Explicit) {
2252   assert(Tok.is(MMToken::Star));
2253   SourceLocation StarLoc = consumeToken();
2254   bool Failed = false;
2255
2256   // Inferred modules must be submodules.
2257   if (!ActiveModule && !Framework) {
2258     Diags.Report(StarLoc, diag::err_mmap_top_level_inferred_submodule);
2259     Failed = true;
2260   }
2261
2262   if (ActiveModule) {
2263     // Inferred modules must have umbrella directories.
2264     if (!Failed && ActiveModule->IsAvailable &&
2265         !ActiveModule->getUmbrellaDir()) {
2266       Diags.Report(StarLoc, diag::err_mmap_inferred_no_umbrella);
2267       Failed = true;
2268     }
2269     
2270     // Check for redefinition of an inferred module.
2271     if (!Failed && ActiveModule->InferSubmodules) {
2272       Diags.Report(StarLoc, diag::err_mmap_inferred_redef);
2273       if (ActiveModule->InferredSubmoduleLoc.isValid())
2274         Diags.Report(ActiveModule->InferredSubmoduleLoc,
2275                      diag::note_mmap_prev_definition);
2276       Failed = true;
2277     }
2278
2279     // Check for the 'framework' keyword, which is not permitted here.
2280     if (Framework) {
2281       Diags.Report(StarLoc, diag::err_mmap_inferred_framework_submodule);
2282       Framework = false;
2283     }
2284   } else if (Explicit) {
2285     Diags.Report(StarLoc, diag::err_mmap_explicit_inferred_framework);
2286     Explicit = false;
2287   }
2288
2289   // If there were any problems with this inferred submodule, skip its body.
2290   if (Failed) {
2291     if (Tok.is(MMToken::LBrace)) {
2292       consumeToken();
2293       skipUntil(MMToken::RBrace);
2294       if (Tok.is(MMToken::RBrace))
2295         consumeToken();
2296     }
2297     HadError = true;
2298     return;
2299   }
2300
2301   // Parse optional attributes.
2302   Attributes Attrs;
2303   if (parseOptionalAttributes(Attrs))
2304     return;
2305
2306   if (ActiveModule) {
2307     // Note that we have an inferred submodule.
2308     ActiveModule->InferSubmodules = true;
2309     ActiveModule->InferredSubmoduleLoc = StarLoc;
2310     ActiveModule->InferExplicitSubmodules = Explicit;
2311   } else {
2312     // We'll be inferring framework modules for this directory.
2313     Map.InferredDirectories[Directory].InferModules = true;
2314     Map.InferredDirectories[Directory].Attrs = Attrs;
2315     Map.InferredDirectories[Directory].ModuleMapFile = ModuleMapFile;
2316     // FIXME: Handle the 'framework' keyword.
2317   }
2318
2319   // Parse the opening brace.
2320   if (!Tok.is(MMToken::LBrace)) {
2321     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_lbrace_wildcard);
2322     HadError = true;
2323     return;
2324   }  
2325   SourceLocation LBraceLoc = consumeToken();
2326
2327   // Parse the body of the inferred submodule.
2328   bool Done = false;
2329   do {
2330     switch (Tok.Kind) {
2331     case MMToken::EndOfFile:
2332     case MMToken::RBrace:
2333       Done = true;
2334       break;
2335
2336     case MMToken::ExcludeKeyword: {
2337       if (ActiveModule) {
2338         Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member)
2339           << (ActiveModule != nullptr);
2340         consumeToken();
2341         break;
2342       }
2343
2344       consumeToken();
2345       // FIXME: Support string-literal module names here.
2346       if (!Tok.is(MMToken::Identifier)) {
2347         Diags.Report(Tok.getLocation(), diag::err_mmap_missing_exclude_name);
2348         break;
2349       }
2350
2351       Map.InferredDirectories[Directory].ExcludedModules
2352         .push_back(Tok.getString());
2353       consumeToken();
2354       break;
2355     }
2356
2357     case MMToken::ExportKeyword:
2358       if (!ActiveModule) {
2359         Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member)
2360           << (ActiveModule != nullptr);
2361         consumeToken();
2362         break;
2363       }
2364
2365       consumeToken();
2366       if (Tok.is(MMToken::Star)) 
2367         ActiveModule->InferExportWildcard = true;
2368       else
2369         Diags.Report(Tok.getLocation(), 
2370                      diag::err_mmap_expected_export_wildcard);
2371       consumeToken();
2372       break;
2373
2374     case MMToken::ExplicitKeyword:
2375     case MMToken::ModuleKeyword:
2376     case MMToken::HeaderKeyword:
2377     case MMToken::PrivateKeyword:
2378     case MMToken::UmbrellaKeyword:
2379     default:
2380       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member)
2381           << (ActiveModule != nullptr);
2382       consumeToken();
2383       break;        
2384     }
2385   } while (!Done);
2386   
2387   if (Tok.is(MMToken::RBrace))
2388     consumeToken();
2389   else {
2390     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
2391     Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
2392     HadError = true;
2393   }
2394 }
2395
2396 /// \brief Parse optional attributes.
2397 ///
2398 ///   attributes:
2399 ///     attribute attributes
2400 ///     attribute
2401 ///
2402 ///   attribute:
2403 ///     [ identifier ]
2404 ///
2405 /// \param Attrs Will be filled in with the parsed attributes.
2406 ///
2407 /// \returns true if an error occurred, false otherwise.
2408 bool ModuleMapParser::parseOptionalAttributes(Attributes &Attrs) {
2409   bool HadError = false;
2410   
2411   while (Tok.is(MMToken::LSquare)) {
2412     // Consume the '['.
2413     SourceLocation LSquareLoc = consumeToken();
2414
2415     // Check whether we have an attribute name here.
2416     if (!Tok.is(MMToken::Identifier)) {
2417       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_attribute);
2418       skipUntil(MMToken::RSquare);
2419       if (Tok.is(MMToken::RSquare))
2420         consumeToken();
2421       HadError = true;
2422     }
2423
2424     // Decode the attribute name.
2425     AttributeKind Attribute
2426       = llvm::StringSwitch<AttributeKind>(Tok.getString())
2427           .Case("exhaustive", AT_exhaustive)
2428           .Case("extern_c", AT_extern_c)
2429           .Case("no_undeclared_includes", AT_no_undeclared_includes)
2430           .Case("system", AT_system)
2431           .Default(AT_unknown);
2432     switch (Attribute) {
2433     case AT_unknown:
2434       Diags.Report(Tok.getLocation(), diag::warn_mmap_unknown_attribute)
2435         << Tok.getString();
2436       break;
2437
2438     case AT_system:
2439       Attrs.IsSystem = true;
2440       break;
2441
2442     case AT_extern_c:
2443       Attrs.IsExternC = true;
2444       break;
2445
2446     case AT_exhaustive:
2447       Attrs.IsExhaustive = true;
2448       break;
2449
2450     case AT_no_undeclared_includes:
2451       Attrs.NoUndeclaredIncludes = true;
2452       break;
2453     }
2454     consumeToken();
2455
2456     // Consume the ']'.
2457     if (!Tok.is(MMToken::RSquare)) {
2458       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rsquare);
2459       Diags.Report(LSquareLoc, diag::note_mmap_lsquare_match);
2460       skipUntil(MMToken::RSquare);
2461       HadError = true;
2462     }
2463
2464     if (Tok.is(MMToken::RSquare))
2465       consumeToken();
2466   }
2467
2468   return HadError;
2469 }
2470
2471 /// \brief Parse a module map file.
2472 ///
2473 ///   module-map-file:
2474 ///     module-declaration*
2475 bool ModuleMapParser::parseModuleMapFile() {
2476   do {
2477     switch (Tok.Kind) {
2478     case MMToken::EndOfFile:
2479       return HadError;
2480       
2481     case MMToken::ExplicitKeyword:
2482     case MMToken::ExternKeyword:
2483     case MMToken::ModuleKeyword:
2484     case MMToken::FrameworkKeyword:
2485       parseModuleDecl();
2486       break;
2487
2488     case MMToken::Comma:
2489     case MMToken::ConfigMacros:
2490     case MMToken::Conflict:
2491     case MMToken::Exclaim:
2492     case MMToken::ExcludeKeyword:
2493     case MMToken::ExportKeyword:
2494     case MMToken::HeaderKeyword:
2495     case MMToken::Identifier:
2496     case MMToken::LBrace:
2497     case MMToken::LinkKeyword:
2498     case MMToken::LSquare:
2499     case MMToken::Period:
2500     case MMToken::PrivateKeyword:
2501     case MMToken::RBrace:
2502     case MMToken::RSquare:
2503     case MMToken::RequiresKeyword:
2504     case MMToken::Star:
2505     case MMToken::StringLiteral:
2506     case MMToken::TextualKeyword:
2507     case MMToken::UmbrellaKeyword:
2508     case MMToken::UseKeyword:
2509       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module);
2510       HadError = true;
2511       consumeToken();
2512       break;
2513     }
2514   } while (true);
2515 }
2516
2517 bool ModuleMap::parseModuleMapFile(const FileEntry *File, bool IsSystem,
2518                                    const DirectoryEntry *Dir,
2519                                    SourceLocation ExternModuleLoc) {
2520   llvm::DenseMap<const FileEntry *, bool>::iterator Known
2521     = ParsedModuleMap.find(File);
2522   if (Known != ParsedModuleMap.end())
2523     return Known->second;
2524
2525   assert(Target && "Missing target information");
2526   auto FileCharacter = IsSystem ? SrcMgr::C_System : SrcMgr::C_User;
2527   FileID ID = SourceMgr.createFileID(File, ExternModuleLoc, FileCharacter);
2528   const llvm::MemoryBuffer *Buffer = SourceMgr.getBuffer(ID);
2529   if (!Buffer)
2530     return ParsedModuleMap[File] = true;
2531
2532   // Parse this module map file.
2533   Lexer L(ID, SourceMgr.getBuffer(ID), SourceMgr, MMapLangOpts);
2534   SourceLocation Start = L.getSourceLocation();
2535   ModuleMapParser Parser(L, SourceMgr, Target, Diags, *this, File, Dir,
2536                          BuiltinIncludeDir, IsSystem);
2537   bool Result = Parser.parseModuleMapFile();
2538   ParsedModuleMap[File] = Result;
2539
2540   // Notify callbacks that we parsed it.
2541   for (const auto &Cb : Callbacks)
2542     Cb->moduleMapFileRead(Start, *File, IsSystem);
2543   return Result;
2544 }