xref: /llvm-project/clang/lib/Lex/ModuleMap.cpp (revision ddaa69cb281dca0220c9e28f42d30fbe6b66d2be)
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/Lex/Lexer.h"
16 #include "clang/Lex/LiteralSupport.h"
17 #include "clang/Lex/LexDiagnostic.h"
18 #include "clang/Basic/Diagnostic.h"
19 #include "clang/Basic/FileManager.h"
20 #include "clang/Basic/TargetInfo.h"
21 #include "clang/Basic/TargetOptions.h"
22 #include "llvm/Support/Allocator.h"
23 #include "llvm/Support/FileSystem.h"
24 #include "llvm/Support/Host.h"
25 #include "llvm/Support/PathV2.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include "llvm/ADT/StringRef.h"
28 #include "llvm/ADT/StringSwitch.h"
29 using namespace clang;
30 
31 Module::ExportDecl
32 ModuleMap::resolveExport(Module *Mod,
33                          const Module::UnresolvedExportDecl &Unresolved,
34                          bool Complain) {
35   // We may have just a wildcard.
36   if (Unresolved.Id.empty()) {
37     assert(Unresolved.Wildcard && "Invalid unresolved export");
38     return Module::ExportDecl(0, true);
39   }
40 
41   // Find the starting module.
42   Module *Context = lookupModuleUnqualified(Unresolved.Id[0].first, Mod);
43   if (!Context) {
44     if (Complain)
45       Diags->Report(Unresolved.Id[0].second,
46                     diag::err_mmap_missing_module_unqualified)
47         << Unresolved.Id[0].first << Mod->getFullModuleName();
48 
49     return Module::ExportDecl();
50   }
51 
52   // Dig into the module path.
53   for (unsigned I = 1, N = Unresolved.Id.size(); I != N; ++I) {
54     Module *Sub = lookupModuleQualified(Unresolved.Id[I].first,
55                                         Context);
56     if (!Sub) {
57       if (Complain)
58         Diags->Report(Unresolved.Id[I].second,
59                       diag::err_mmap_missing_module_qualified)
60           << Unresolved.Id[I].first << Context->getFullModuleName()
61           << SourceRange(Unresolved.Id[0].second, Unresolved.Id[I-1].second);
62 
63       return Module::ExportDecl();
64     }
65 
66     Context = Sub;
67   }
68 
69   return Module::ExportDecl(Context, Unresolved.Wildcard);
70 }
71 
72 ModuleMap::ModuleMap(FileManager &FileMgr, const DiagnosticConsumer &DC) {
73   llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(new DiagnosticIDs);
74   Diags = llvm::IntrusiveRefCntPtr<DiagnosticsEngine>(
75             new DiagnosticsEngine(DiagIDs));
76   Diags->setClient(DC.clone(*Diags), /*ShouldOwnClient=*/true);
77   SourceMgr = new SourceManager(*Diags, FileMgr);
78 }
79 
80 ModuleMap::~ModuleMap() {
81   for (llvm::StringMap<Module *>::iterator I = Modules.begin(),
82                                         IEnd = Modules.end();
83        I != IEnd; ++I) {
84     delete I->getValue();
85   }
86 
87   delete SourceMgr;
88 }
89 
90 Module *ModuleMap::findModuleForHeader(const FileEntry *File) {
91   llvm::DenseMap<const FileEntry *, Module *>::iterator Known
92     = Headers.find(File);
93   if (Known != Headers.end())
94     return Known->second;
95 
96   const DirectoryEntry *Dir = File->getDir();
97   llvm::SmallVector<const DirectoryEntry *, 2> SkippedDirs;
98   StringRef DirName = Dir->getName();
99 
100   // Keep walking up the directory hierarchy, looking for a directory with
101   // an umbrella header.
102   do {
103     llvm::DenseMap<const DirectoryEntry *, Module *>::iterator KnownDir
104       = UmbrellaDirs.find(Dir);
105     if (KnownDir != UmbrellaDirs.end()) {
106       Module *Result = KnownDir->second;
107 
108       // Search up the module stack until we find a module with an umbrella
109       // header.
110       Module *UmbrellaModule = Result;
111       while (!UmbrellaModule->UmbrellaHeader && UmbrellaModule->Parent)
112         UmbrellaModule = UmbrellaModule->Parent;
113 
114       if (UmbrellaModule->InferSubmodules) {
115         // Infer submodules for each of the directories we found between
116         // the directory of the umbrella header and the directory where
117         // the actual header is located.
118 
119         // For a framework module, the umbrella directory is the framework
120         // directory, so strip off the "Headers" or "PrivateHeaders".
121         bool Explicit = UmbrellaModule->InferExplicitSubmodules;
122         unsigned LastSkippedDir = SkippedDirs.size();
123         if (LastSkippedDir && UmbrellaModule->IsFramework) {
124           if (llvm::sys::path::filename(SkippedDirs.back()->getName())
125                 == "PrivateHeaders") {
126             // For private headers, add an explicit "Private" module.
127             // FIXME: This feels somewhat hackish. Do we want to introduce
128             // some kind of "umbrella directory" here?
129             Result = findOrCreateModule("Private", Result,
130                                         /*IsFramework=*/false,
131                                         /*IsExplicit=*/true).first;
132             Explicit = true;
133           }
134 
135           --LastSkippedDir;
136         }
137 
138         for (unsigned I = LastSkippedDir; I != 0; --I) {
139           // Find or create the module that corresponds to this directory name.
140           StringRef Name = llvm::sys::path::stem(SkippedDirs[I-1]->getName());
141           Result = findOrCreateModule(Name, Result, /*IsFramework=*/false,
142                                       Explicit).first;
143 
144           // Associate the module and the directory.
145           UmbrellaDirs[SkippedDirs[I-1]] = Result;
146 
147           // If inferred submodules export everything they import, add a
148           // wildcard to the set of exports.
149           if (UmbrellaModule->InferExportWildcard && Result->Exports.empty())
150             Result->Exports.push_back(Module::ExportDecl(0, true));
151         }
152 
153         // Infer a submodule with the same name as this header file.
154         StringRef Name = llvm::sys::path::stem(File->getName());
155         Result = findOrCreateModule(Name, Result, /*IsFramework=*/false,
156                                     Explicit).first;
157 
158         // If inferred submodules export everything they import, add a
159         // wildcard to the set of exports.
160         if (UmbrellaModule->InferExportWildcard && Result->Exports.empty())
161           Result->Exports.push_back(Module::ExportDecl(0, true));
162       } else {
163         // Record each of the directories we stepped through as being part of
164         // the module we found, since the umbrella header covers them all.
165         for (unsigned I = 0, N = SkippedDirs.size(); I != N; ++I)
166           UmbrellaDirs[SkippedDirs[I]] = Result;
167       }
168 
169       Headers[File] = Result;
170       return Result;
171     }
172 
173     SkippedDirs.push_back(Dir);
174 
175     // Retrieve our parent path.
176     DirName = llvm::sys::path::parent_path(DirName);
177     if (DirName.empty())
178       break;
179 
180     // Resolve the parent path to a directory entry.
181     Dir = SourceMgr->getFileManager().getDirectory(DirName);
182   } while (Dir);
183 
184   return 0;
185 }
186 
187 Module *ModuleMap::findModule(StringRef Name) {
188   llvm::StringMap<Module *>::iterator Known = Modules.find(Name);
189   if (Known != Modules.end())
190     return Known->getValue();
191 
192   return 0;
193 }
194 
195 Module *ModuleMap::lookupModuleUnqualified(StringRef Name, Module *Context) {
196   for(; Context; Context = Context->Parent) {
197     if (Module *Sub = lookupModuleQualified(Name, Context))
198       return Sub;
199   }
200 
201   return findModule(Name);
202 }
203 
204 Module *ModuleMap::lookupModuleQualified(StringRef Name, Module *Context) {
205   if (!Context)
206     return findModule(Name);
207 
208   llvm::StringMap<Module *>::iterator Sub = Context->SubModules.find(Name);
209   if (Sub != Context->SubModules.end())
210     return Sub->getValue();
211 
212   return 0;
213 }
214 
215 std::pair<Module *, bool>
216 ModuleMap::findOrCreateModule(StringRef Name, Module *Parent, bool IsFramework,
217                               bool IsExplicit) {
218   // Try to find an existing module with this name.
219   if (Module *Found = Parent? Parent->SubModules[Name] : Modules[Name])
220     return std::make_pair(Found, false);
221 
222   // Create a new module with this name.
223   Module *Result = new Module(Name, SourceLocation(), Parent, IsFramework,
224                               IsExplicit);
225   if (Parent)
226     Parent->SubModules[Name] = Result;
227   else
228     Modules[Name] = Result;
229   return std::make_pair(Result, true);
230 }
231 
232 Module *
233 ModuleMap::inferFrameworkModule(StringRef ModuleName,
234                                 const DirectoryEntry *FrameworkDir,
235                                 Module *Parent) {
236   // Check whether we've already found this module.
237   if (Module *Mod = lookupModuleQualified(ModuleName, Parent))
238     return Mod;
239 
240   FileManager &FileMgr = SourceMgr->getFileManager();
241 
242   // Look for an umbrella header.
243   llvm::SmallString<128> UmbrellaName = StringRef(FrameworkDir->getName());
244   llvm::sys::path::append(UmbrellaName, "Headers");
245   llvm::sys::path::append(UmbrellaName, ModuleName + ".h");
246   const FileEntry *UmbrellaHeader = FileMgr.getFile(UmbrellaName);
247 
248   // FIXME: If there's no umbrella header, we could probably scan the
249   // framework to load *everything*. But, it's not clear that this is a good
250   // idea.
251   if (!UmbrellaHeader)
252     return 0;
253 
254   Module *Result = new Module(ModuleName, SourceLocation(), Parent,
255                               /*IsFramework=*/true, /*IsExplicit=*/false);
256 
257   if (Parent)
258     Parent->SubModules[ModuleName] = Result;
259   else
260     Modules[ModuleName] = Result;
261 
262   // umbrella "umbrella-header-name"
263   Result->UmbrellaHeader = UmbrellaHeader;
264   Headers[UmbrellaHeader] = Result;
265   UmbrellaDirs[FrameworkDir] = Result;
266 
267   // export *
268   Result->Exports.push_back(Module::ExportDecl(0, true));
269 
270   // module * { export * }
271   Result->InferSubmodules = true;
272   Result->InferExportWildcard = true;
273 
274   // Look for subframeworks.
275   llvm::error_code EC;
276   llvm::SmallString<128> SubframeworksDirName
277     = StringRef(FrameworkDir->getName());
278   llvm::sys::path::append(SubframeworksDirName, "Frameworks");
279   llvm::SmallString<128> SubframeworksDirNameNative;
280   llvm::sys::path::native(SubframeworksDirName.str(),
281                           SubframeworksDirNameNative);
282   for (llvm::sys::fs::directory_iterator
283          Dir(SubframeworksDirNameNative.str(), EC), DirEnd;
284        Dir != DirEnd && !EC; Dir.increment(EC)) {
285     if (!StringRef(Dir->path()).endswith(".framework"))
286       continue;
287 
288     if (const DirectoryEntry *SubframeworkDir
289           = FileMgr.getDirectory(Dir->path())) {
290       // FIXME: Do we want to warn about subframeworks without umbrella headers?
291       inferFrameworkModule(llvm::sys::path::stem(Dir->path()), SubframeworkDir,
292                            Result);
293     }
294   }
295 
296   // Look for private headers.
297   Module *ModulePrivate = 0;
298   llvm::SmallString<128> PrivateHeadersDirName(FrameworkDir->getName());
299   llvm::sys::path::append(PrivateHeadersDirName, "PrivateHeaders");
300   llvm::SmallString<128> PrivateHeadersDirNameNative;
301   llvm::sys::path::native(PrivateHeadersDirName.str(),
302                           PrivateHeadersDirNameNative);
303   for (llvm::sys::fs::directory_iterator
304          Dir(PrivateHeadersDirNameNative.str(), EC), DirEnd;
305        Dir != DirEnd && !EC; Dir.increment(EC)) {
306     // Check whether this entry has an extension typically associated with
307     // headers.
308     if (!llvm::StringSwitch<bool>(llvm::sys::path::extension(Dir->path()))
309            .Cases(".h", ".H", ".hh", ".hpp", true)
310            .Default(false))
311       continue;
312 
313     if (const FileEntry *PrivateHeader = FileMgr.getFile(Dir->path())) {
314       // Create the "private" submodule, if we haven't done so already.
315       if (!ModulePrivate) {
316         ModulePrivate = findOrCreateModule("Private", Result,
317                                            /*IsFramework=*/false,
318                                            /*IsExplicit=*/true).first;
319       }
320 
321       Module *Sub = findOrCreateModule(llvm::sys::path::stem(Dir->path()),
322                                        ModulePrivate, /*IsFramework=*/false,
323                                        /*IsExplicit=*/true).first;
324       // header "the private header"
325       Sub->Headers.push_back(PrivateHeader);
326 
327       // export *
328       Sub->Exports.push_back(Module::ExportDecl(0, true));
329 
330       Headers[PrivateHeader] = Sub;
331     }
332   }
333 
334   return Result;
335 }
336 
337 void ModuleMap::setUmbrellaHeader(Module *Mod, const FileEntry *UmbrellaHeader){
338   Headers[UmbrellaHeader] = Mod;
339   Mod->UmbrellaHeader = UmbrellaHeader;
340 
341   const DirectoryEntry *UmbrellaDir = UmbrellaHeader->getDir();
342   if (Mod->IsFramework)
343     UmbrellaDir = SourceMgr->getFileManager().getDirectory(
344                     llvm::sys::path::parent_path(UmbrellaDir->getName()));
345 
346   UmbrellaDirs[UmbrellaDir] = Mod;
347 }
348 
349 void ModuleMap::addHeader(Module *Mod, const FileEntry *Header) {
350   Mod->Headers.push_back(Header);
351   Headers[Header] = Mod;
352 }
353 
354 const FileEntry *
355 ModuleMap::getContainingModuleMapFile(Module *Module) {
356   if (Module->DefinitionLoc.isInvalid() || !SourceMgr)
357     return 0;
358 
359   return SourceMgr->getFileEntryForID(
360            SourceMgr->getFileID(Module->DefinitionLoc));
361 }
362 
363 void ModuleMap::dump() {
364   llvm::errs() << "Modules:";
365   for (llvm::StringMap<Module *>::iterator M = Modules.begin(),
366                                         MEnd = Modules.end();
367        M != MEnd; ++M)
368     M->getValue()->print(llvm::errs(), 2);
369 
370   llvm::errs() << "Headers:";
371   for (llvm::DenseMap<const FileEntry *, Module *>::iterator
372             H = Headers.begin(),
373          HEnd = Headers.end();
374        H != HEnd; ++H) {
375     llvm::errs() << "  \"" << H->first->getName() << "\" -> "
376                  << H->second->getFullModuleName() << "\n";
377   }
378 }
379 
380 bool ModuleMap::resolveExports(Module *Mod, bool Complain) {
381   bool HadError = false;
382   for (unsigned I = 0, N = Mod->UnresolvedExports.size(); I != N; ++I) {
383     Module::ExportDecl Export = resolveExport(Mod, Mod->UnresolvedExports[I],
384                                               Complain);
385     if (Export.getPointer() || Export.getInt())
386       Mod->Exports.push_back(Export);
387     else
388       HadError = true;
389   }
390   Mod->UnresolvedExports.clear();
391   return HadError;
392 }
393 
394 Module *ModuleMap::inferModuleFromLocation(FullSourceLoc Loc) {
395   if (Loc.isInvalid())
396     return 0;
397 
398   // Use the expansion location to determine which module we're in.
399   FullSourceLoc ExpansionLoc = Loc.getExpansionLoc();
400   if (!ExpansionLoc.isFileID())
401     return 0;
402 
403 
404   const SourceManager &SrcMgr = Loc.getManager();
405   FileID ExpansionFileID = ExpansionLoc.getFileID();
406   const FileEntry *ExpansionFile = SrcMgr.getFileEntryForID(ExpansionFileID);
407   if (!ExpansionFile)
408     return 0;
409 
410   // Find the module that owns this header.
411   return findModuleForHeader(ExpansionFile);
412 }
413 
414 //----------------------------------------------------------------------------//
415 // Module map file parser
416 //----------------------------------------------------------------------------//
417 
418 namespace clang {
419   /// \brief A token in a module map file.
420   struct MMToken {
421     enum TokenKind {
422       EndOfFile,
423       HeaderKeyword,
424       Identifier,
425       ExplicitKeyword,
426       ExportKeyword,
427       FrameworkKeyword,
428       ModuleKeyword,
429       Period,
430       UmbrellaKeyword,
431       Star,
432       StringLiteral,
433       LBrace,
434       RBrace
435     } Kind;
436 
437     unsigned Location;
438     unsigned StringLength;
439     const char *StringData;
440 
441     void clear() {
442       Kind = EndOfFile;
443       Location = 0;
444       StringLength = 0;
445       StringData = 0;
446     }
447 
448     bool is(TokenKind K) const { return Kind == K; }
449 
450     SourceLocation getLocation() const {
451       return SourceLocation::getFromRawEncoding(Location);
452     }
453 
454     StringRef getString() const {
455       return StringRef(StringData, StringLength);
456     }
457   };
458 
459   class ModuleMapParser {
460     Lexer &L;
461     SourceManager &SourceMgr;
462     DiagnosticsEngine &Diags;
463     ModuleMap &Map;
464 
465     /// \brief The directory that this module map resides in.
466     const DirectoryEntry *Directory;
467 
468     /// \brief Whether an error occurred.
469     bool HadError;
470 
471     /// \brief Default target information, used only for string literal
472     /// parsing.
473     TargetInfo *Target;
474 
475     /// \brief Stores string data for the various string literals referenced
476     /// during parsing.
477     llvm::BumpPtrAllocator StringData;
478 
479     /// \brief The current token.
480     MMToken Tok;
481 
482     /// \brief The active module.
483     Module *ActiveModule;
484 
485     /// \brief Consume the current token and return its location.
486     SourceLocation consumeToken();
487 
488     /// \brief Skip tokens until we reach the a token with the given kind
489     /// (or the end of the file).
490     void skipUntil(MMToken::TokenKind K);
491 
492     typedef llvm::SmallVector<std::pair<std::string, SourceLocation>, 2>
493       ModuleId;
494     bool parseModuleId(ModuleId &Id);
495     void parseModuleDecl();
496     void parseUmbrellaDecl();
497     void parseHeaderDecl();
498     void parseExportDecl();
499     void parseInferredSubmoduleDecl(bool Explicit);
500 
501   public:
502     explicit ModuleMapParser(Lexer &L, SourceManager &SourceMgr,
503                              DiagnosticsEngine &Diags,
504                              ModuleMap &Map,
505                              const DirectoryEntry *Directory)
506       : L(L), SourceMgr(SourceMgr), Diags(Diags), Map(Map),
507         Directory(Directory), HadError(false), ActiveModule(0)
508     {
509       TargetOptions TargetOpts;
510       TargetOpts.Triple = llvm::sys::getDefaultTargetTriple();
511       Target = TargetInfo::CreateTargetInfo(Diags, TargetOpts);
512 
513       Tok.clear();
514       consumeToken();
515     }
516 
517     bool parseModuleMapFile();
518   };
519 }
520 
521 SourceLocation ModuleMapParser::consumeToken() {
522 retry:
523   SourceLocation Result = Tok.getLocation();
524   Tok.clear();
525 
526   Token LToken;
527   L.LexFromRawLexer(LToken);
528   Tok.Location = LToken.getLocation().getRawEncoding();
529   switch (LToken.getKind()) {
530   case tok::raw_identifier:
531     Tok.StringData = LToken.getRawIdentifierData();
532     Tok.StringLength = LToken.getLength();
533     Tok.Kind = llvm::StringSwitch<MMToken::TokenKind>(Tok.getString())
534                  .Case("header", MMToken::HeaderKeyword)
535                  .Case("explicit", MMToken::ExplicitKeyword)
536                  .Case("export", MMToken::ExportKeyword)
537                  .Case("framework", MMToken::FrameworkKeyword)
538                  .Case("module", MMToken::ModuleKeyword)
539                  .Case("umbrella", MMToken::UmbrellaKeyword)
540                  .Default(MMToken::Identifier);
541     break;
542 
543   case tok::eof:
544     Tok.Kind = MMToken::EndOfFile;
545     break;
546 
547   case tok::l_brace:
548     Tok.Kind = MMToken::LBrace;
549     break;
550 
551   case tok::period:
552     Tok.Kind = MMToken::Period;
553     break;
554 
555   case tok::r_brace:
556     Tok.Kind = MMToken::RBrace;
557     break;
558 
559   case tok::star:
560     Tok.Kind = MMToken::Star;
561     break;
562 
563   case tok::string_literal: {
564     // Parse the string literal.
565     LangOptions LangOpts;
566     StringLiteralParser StringLiteral(&LToken, 1, SourceMgr, LangOpts, *Target);
567     if (StringLiteral.hadError)
568       goto retry;
569 
570     // Copy the string literal into our string data allocator.
571     unsigned Length = StringLiteral.GetStringLength();
572     char *Saved = StringData.Allocate<char>(Length + 1);
573     memcpy(Saved, StringLiteral.GetString().data(), Length);
574     Saved[Length] = 0;
575 
576     // Form the token.
577     Tok.Kind = MMToken::StringLiteral;
578     Tok.StringData = Saved;
579     Tok.StringLength = Length;
580     break;
581   }
582 
583   case tok::comment:
584     goto retry;
585 
586   default:
587     Diags.Report(LToken.getLocation(), diag::err_mmap_unknown_token);
588     HadError = true;
589     goto retry;
590   }
591 
592   return Result;
593 }
594 
595 void ModuleMapParser::skipUntil(MMToken::TokenKind K) {
596   unsigned braceDepth = 0;
597   do {
598     switch (Tok.Kind) {
599     case MMToken::EndOfFile:
600       return;
601 
602     case MMToken::LBrace:
603       if (Tok.is(K) && braceDepth == 0)
604         return;
605 
606       ++braceDepth;
607       break;
608 
609     case MMToken::RBrace:
610       if (braceDepth > 0)
611         --braceDepth;
612       else if (Tok.is(K))
613         return;
614       break;
615 
616     default:
617       if (braceDepth == 0 && Tok.is(K))
618         return;
619       break;
620     }
621 
622    consumeToken();
623   } while (true);
624 }
625 
626 /// \brief Parse a module-id.
627 ///
628 ///   module-id:
629 ///     identifier
630 ///     identifier '.' module-id
631 ///
632 /// \returns true if an error occurred, false otherwise.
633 bool ModuleMapParser::parseModuleId(ModuleId &Id) {
634   Id.clear();
635   do {
636     if (Tok.is(MMToken::Identifier)) {
637       Id.push_back(std::make_pair(Tok.getString(), Tok.getLocation()));
638       consumeToken();
639     } else {
640       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module_name);
641       return true;
642     }
643 
644     if (!Tok.is(MMToken::Period))
645       break;
646 
647     consumeToken();
648   } while (true);
649 
650   return false;
651 }
652 
653 /// \brief Parse a module declaration.
654 ///
655 ///   module-declaration:
656 ///     'explicit'[opt] 'framework'[opt] 'module' module-id { module-member* }
657 ///
658 ///   module-member:
659 ///     umbrella-declaration
660 ///     header-declaration
661 ///     submodule-declaration
662 ///     export-declaration
663 ///
664 ///   submodule-declaration:
665 ///     module-declaration
666 ///     inferred-submodule-declaration
667 void ModuleMapParser::parseModuleDecl() {
668   assert(Tok.is(MMToken::ExplicitKeyword) || Tok.is(MMToken::ModuleKeyword) ||
669          Tok.is(MMToken::FrameworkKeyword));
670   // Parse 'explicit' or 'framework' keyword, if present.
671   SourceLocation ExplicitLoc;
672   bool Explicit = false;
673   bool Framework = false;
674 
675   // Parse 'explicit' keyword, if present.
676   if (Tok.is(MMToken::ExplicitKeyword)) {
677     ExplicitLoc = consumeToken();
678     Explicit = true;
679   }
680 
681   // Parse 'framework' keyword, if present.
682   if (Tok.is(MMToken::FrameworkKeyword)) {
683     consumeToken();
684     Framework = true;
685   }
686 
687   // Parse 'module' keyword.
688   if (!Tok.is(MMToken::ModuleKeyword)) {
689     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module);
690     consumeToken();
691     HadError = true;
692     return;
693   }
694   consumeToken(); // 'module' keyword
695 
696   // If we have a wildcard for the module name, this is an inferred submodule.
697   // Parse it.
698   if (Tok.is(MMToken::Star))
699     return parseInferredSubmoduleDecl(Explicit);
700 
701   // Parse the module name.
702   ModuleId Id;
703   if (parseModuleId(Id)) {
704     HadError = true;
705     return;
706   }
707 
708   if (ActiveModule) {
709     if (Id.size() > 1) {
710       Diags.Report(Id.front().second, diag::err_mmap_nested_submodule_id)
711         << SourceRange(Id.front().second, Id.back().second);
712 
713       HadError = true;
714       return;
715     }
716   } else if (Id.size() == 1 && Explicit) {
717     // Top-level modules can't be explicit.
718     Diags.Report(ExplicitLoc, diag::err_mmap_explicit_top_level);
719     Explicit = false;
720     ExplicitLoc = SourceLocation();
721     HadError = true;
722   }
723 
724   Module *PreviousActiveModule = ActiveModule;
725   if (Id.size() > 1) {
726     // This module map defines a submodule. Go find the module of which it
727     // is a submodule.
728     ActiveModule = 0;
729     for (unsigned I = 0, N = Id.size() - 1; I != N; ++I) {
730       if (Module *Next = Map.lookupModuleQualified(Id[I].first, ActiveModule)) {
731         ActiveModule = Next;
732         continue;
733       }
734 
735       if (ActiveModule) {
736         Diags.Report(Id[I].second, diag::err_mmap_missing_module_qualified)
737           << Id[I].first << ActiveModule->getTopLevelModule();
738       } else {
739         Diags.Report(Id[I].second, diag::err_mmap_expected_module_name);
740       }
741       HadError = true;
742       return;
743     }
744   }
745 
746   StringRef ModuleName = Id.back().first;
747   SourceLocation ModuleNameLoc = Id.back().second;
748 
749   // Parse the opening brace.
750   if (!Tok.is(MMToken::LBrace)) {
751     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_lbrace)
752       << ModuleName;
753     HadError = true;
754     return;
755   }
756   SourceLocation LBraceLoc = consumeToken();
757 
758   // Determine whether this (sub)module has already been defined.
759   llvm::StringMap<Module *> &ModuleSpace
760     = ActiveModule? ActiveModule->SubModules : Map.Modules;
761   llvm::StringMap<Module *>::iterator ExistingModule
762     = ModuleSpace.find(ModuleName);
763   if (ExistingModule != ModuleSpace.end()) {
764     Diags.Report(ModuleNameLoc, diag::err_mmap_module_redefinition)
765       << ModuleName;
766     Diags.Report(ExistingModule->getValue()->DefinitionLoc,
767                  diag::note_mmap_prev_definition);
768 
769     // Skip the module definition.
770     skipUntil(MMToken::RBrace);
771     if (Tok.is(MMToken::RBrace))
772       consumeToken();
773 
774     HadError = true;
775     return;
776   }
777 
778   // Start defining this module.
779   ActiveModule = new Module(ModuleName, ModuleNameLoc, ActiveModule, Framework,
780                             Explicit);
781   ModuleSpace[ModuleName] = ActiveModule;
782 
783   bool Done = false;
784   do {
785     switch (Tok.Kind) {
786     case MMToken::EndOfFile:
787     case MMToken::RBrace:
788       Done = true;
789       break;
790 
791     case MMToken::ExplicitKeyword:
792     case MMToken::FrameworkKeyword:
793     case MMToken::ModuleKeyword:
794       parseModuleDecl();
795       break;
796 
797     case MMToken::ExportKeyword:
798       parseExportDecl();
799       break;
800 
801     case MMToken::HeaderKeyword:
802       parseHeaderDecl();
803       break;
804 
805     case MMToken::UmbrellaKeyword:
806       parseUmbrellaDecl();
807       break;
808 
809     default:
810       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_member);
811       consumeToken();
812       break;
813     }
814   } while (!Done);
815 
816   if (Tok.is(MMToken::RBrace))
817     consumeToken();
818   else {
819     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
820     Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
821     HadError = true;
822   }
823 
824   // We're done parsing this module. Pop back to the previous module.
825   ActiveModule = PreviousActiveModule;
826 }
827 
828 /// \brief Append to \p Paths the set of paths needed to get to the
829 /// subframework in which the given module lives.
830 void appendSubframeworkPaths(Module *Mod, llvm::SmallVectorImpl<char> &Path) {
831   // Collect the framework names from the given module to the top-level module.
832   llvm::SmallVector<StringRef, 2> Paths;
833   for (; Mod; Mod = Mod->Parent) {
834     if (Mod->IsFramework)
835       Paths.push_back(Mod->Name);
836   }
837 
838   if (Paths.empty())
839     return;
840 
841   // Add Frameworks/Name.framework for each subframework.
842   for (unsigned I = Paths.size() - 1; I != 0; --I) {
843     llvm::sys::path::append(Path, "Frameworks");
844     llvm::sys::path::append(Path, Paths[I-1] + ".framework");
845   }
846 }
847 
848 /// \brief Parse an umbrella header declaration.
849 ///
850 ///   umbrella-declaration:
851 ///     'umbrella' string-literal
852 void ModuleMapParser::parseUmbrellaDecl() {
853   assert(Tok.is(MMToken::UmbrellaKeyword));
854   SourceLocation UmbrellaLoc = consumeToken();
855 
856   // Parse the header name.
857   if (!Tok.is(MMToken::StringLiteral)) {
858     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
859       << "umbrella";
860     HadError = true;
861     return;
862   }
863   std::string FileName = Tok.getString();
864   SourceLocation FileNameLoc = consumeToken();
865 
866   // Check whether we already have an umbrella header.
867   if (ActiveModule->UmbrellaHeader) {
868     Diags.Report(FileNameLoc, diag::err_mmap_umbrella_header_conflict)
869       << ActiveModule->getFullModuleName()
870       << ActiveModule->UmbrellaHeader->getName();
871     HadError = true;
872     return;
873   }
874 
875   // Look for this file.
876   llvm::SmallString<128> PathName;
877   const FileEntry *File = 0;
878 
879   if (llvm::sys::path::is_absolute(FileName)) {
880     PathName = FileName;
881     File = SourceMgr.getFileManager().getFile(PathName);
882   } else {
883     // Search for the header file within the search directory.
884     PathName += Directory->getName();
885     unsigned PathLength = PathName.size();
886 
887     if (ActiveModule->isPartOfFramework()) {
888       appendSubframeworkPaths(ActiveModule, PathName);
889 
890       // Check whether this file is in the public headers.
891       llvm::sys::path::append(PathName, "Headers");
892       llvm::sys::path::append(PathName, FileName);
893       File = SourceMgr.getFileManager().getFile(PathName);
894 
895       if (!File) {
896         // Check whether this file is in the private headers.
897         PathName.resize(PathLength);
898         llvm::sys::path::append(PathName, "PrivateHeaders");
899         llvm::sys::path::append(PathName, FileName);
900         File = SourceMgr.getFileManager().getFile(PathName);
901       }
902     } else {
903       // Lookup for normal headers.
904       llvm::sys::path::append(PathName, FileName);
905       File = SourceMgr.getFileManager().getFile(PathName);
906     }
907   }
908 
909   // FIXME: We shouldn't be eagerly stat'ing every file named in a module map.
910   // Come up with a lazy way to do this.
911   if (File) {
912     const DirectoryEntry *UmbrellaDir = File->getDir();
913     if (ActiveModule->IsFramework) {
914       // For framework modules, use the framework directory as the umbrella
915       // directory.
916       UmbrellaDir = SourceMgr.getFileManager().getDirectory(
917                       llvm::sys::path::parent_path(UmbrellaDir->getName()));
918     }
919 
920     if (const Module *OwningModule = Map.Headers[File]) {
921       Diags.Report(FileNameLoc, diag::err_mmap_header_conflict)
922         << FileName << OwningModule->getFullModuleName();
923       HadError = true;
924     } else if ((OwningModule = Map.UmbrellaDirs[UmbrellaDir])) {
925       Diags.Report(UmbrellaLoc, diag::err_mmap_umbrella_clash)
926         << OwningModule->getFullModuleName();
927       HadError = true;
928     } else {
929       // Record this umbrella header.
930       Map.setUmbrellaHeader(ActiveModule, File);
931     }
932   } else {
933     Diags.Report(FileNameLoc, diag::err_mmap_header_not_found)
934       << true << FileName;
935     HadError = true;
936   }
937 }
938 
939 /// \brief Parse a header declaration.
940 ///
941 ///   header-declaration:
942 ///     'header' string-literal
943 void ModuleMapParser::parseHeaderDecl() {
944   assert(Tok.is(MMToken::HeaderKeyword));
945   consumeToken();
946 
947   // Parse the header name.
948   if (!Tok.is(MMToken::StringLiteral)) {
949     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
950       << "header";
951     HadError = true;
952     return;
953   }
954   std::string FileName = Tok.getString();
955   SourceLocation FileNameLoc = consumeToken();
956 
957   // Look for this file.
958   const FileEntry *File = 0;
959   llvm::SmallString<128> PathName;
960   if (llvm::sys::path::is_absolute(FileName)) {
961     PathName = FileName;
962     File = SourceMgr.getFileManager().getFile(PathName);
963   } else {
964     // Search for the header file within the search directory.
965     PathName += Directory->getName();
966     unsigned PathLength = PathName.size();
967 
968     if (ActiveModule->isPartOfFramework()) {
969       appendSubframeworkPaths(ActiveModule, PathName);
970 
971       // Check whether this file is in the public headers.
972       llvm::sys::path::append(PathName, "Headers");
973       llvm::sys::path::append(PathName, FileName);
974       File = SourceMgr.getFileManager().getFile(PathName);
975 
976       if (!File) {
977         // Check whether this file is in the private headers.
978         PathName.resize(PathLength);
979         llvm::sys::path::append(PathName, "PrivateHeaders");
980         llvm::sys::path::append(PathName, FileName);
981         File = SourceMgr.getFileManager().getFile(PathName);
982       }
983     } else {
984       // Lookup for normal headers.
985       llvm::sys::path::append(PathName, FileName);
986       File = SourceMgr.getFileManager().getFile(PathName);
987     }
988   }
989 
990   // FIXME: We shouldn't be eagerly stat'ing every file named in a module map.
991   // Come up with a lazy way to do this.
992   if (File) {
993     if (const Module *OwningModule = Map.Headers[File]) {
994       Diags.Report(FileNameLoc, diag::err_mmap_header_conflict)
995         << FileName << OwningModule->getFullModuleName();
996       HadError = true;
997     } else {
998       // Record this file.
999       Map.addHeader(ActiveModule, File);
1000     }
1001   } else {
1002     Diags.Report(FileNameLoc, diag::err_mmap_header_not_found)
1003       << false << FileName;
1004     HadError = true;
1005   }
1006 }
1007 
1008 /// \brief Parse a module export declaration.
1009 ///
1010 ///   export-declaration:
1011 ///     'export' wildcard-module-id
1012 ///
1013 ///   wildcard-module-id:
1014 ///     identifier
1015 ///     '*'
1016 ///     identifier '.' wildcard-module-id
1017 void ModuleMapParser::parseExportDecl() {
1018   assert(Tok.is(MMToken::ExportKeyword));
1019   SourceLocation ExportLoc = consumeToken();
1020 
1021   // Parse the module-id with an optional wildcard at the end.
1022   ModuleId ParsedModuleId;
1023   bool Wildcard = false;
1024   do {
1025     if (Tok.is(MMToken::Identifier)) {
1026       ParsedModuleId.push_back(std::make_pair(Tok.getString(),
1027                                               Tok.getLocation()));
1028       consumeToken();
1029 
1030       if (Tok.is(MMToken::Period)) {
1031         consumeToken();
1032         continue;
1033       }
1034 
1035       break;
1036     }
1037 
1038     if(Tok.is(MMToken::Star)) {
1039       Wildcard = true;
1040       consumeToken();
1041       break;
1042     }
1043 
1044     Diags.Report(Tok.getLocation(), diag::err_mmap_export_module_id);
1045     HadError = true;
1046     return;
1047   } while (true);
1048 
1049   Module::UnresolvedExportDecl Unresolved = {
1050     ExportLoc, ParsedModuleId, Wildcard
1051   };
1052   ActiveModule->UnresolvedExports.push_back(Unresolved);
1053 }
1054 
1055 void ModuleMapParser::parseInferredSubmoduleDecl(bool Explicit) {
1056   assert(Tok.is(MMToken::Star));
1057   SourceLocation StarLoc = consumeToken();
1058   bool Failed = false;
1059 
1060   // Inferred modules must be submodules.
1061   if (!ActiveModule) {
1062     Diags.Report(StarLoc, diag::err_mmap_top_level_inferred_submodule);
1063     Failed = true;
1064   }
1065 
1066   // Inferred modules must have umbrella headers.
1067   if (!Failed && !ActiveModule->UmbrellaHeader) {
1068     Diags.Report(StarLoc, diag::err_mmap_inferred_no_umbrella);
1069     Failed = true;
1070   }
1071 
1072   // Check for redefinition of an inferred module.
1073   if (!Failed && ActiveModule->InferSubmodules) {
1074     Diags.Report(StarLoc, diag::err_mmap_inferred_redef);
1075     if (ActiveModule->InferredSubmoduleLoc.isValid())
1076       Diags.Report(ActiveModule->InferredSubmoduleLoc,
1077                    diag::note_mmap_prev_definition);
1078     Failed = true;
1079   }
1080 
1081   // If there were any problems with this inferred submodule, skip its body.
1082   if (Failed) {
1083     if (Tok.is(MMToken::LBrace)) {
1084       consumeToken();
1085       skipUntil(MMToken::RBrace);
1086       if (Tok.is(MMToken::RBrace))
1087         consumeToken();
1088     }
1089     HadError = true;
1090     return;
1091   }
1092 
1093   // Note that we have an inferred submodule.
1094   ActiveModule->InferSubmodules = true;
1095   ActiveModule->InferredSubmoduleLoc = StarLoc;
1096   ActiveModule->InferExplicitSubmodules = Explicit;
1097 
1098   // Parse the opening brace.
1099   if (!Tok.is(MMToken::LBrace)) {
1100     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_lbrace_wildcard);
1101     HadError = true;
1102     return;
1103   }
1104   SourceLocation LBraceLoc = consumeToken();
1105 
1106   // Parse the body of the inferred submodule.
1107   bool Done = false;
1108   do {
1109     switch (Tok.Kind) {
1110     case MMToken::EndOfFile:
1111     case MMToken::RBrace:
1112       Done = true;
1113       break;
1114 
1115     case MMToken::ExportKeyword: {
1116       consumeToken();
1117       if (Tok.is(MMToken::Star))
1118         ActiveModule->InferExportWildcard = true;
1119       else
1120         Diags.Report(Tok.getLocation(),
1121                      diag::err_mmap_expected_export_wildcard);
1122       consumeToken();
1123       break;
1124     }
1125 
1126     case MMToken::ExplicitKeyword:
1127     case MMToken::ModuleKeyword:
1128     case MMToken::HeaderKeyword:
1129     case MMToken::UmbrellaKeyword:
1130     default:
1131       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_wildcard_member);
1132       consumeToken();
1133       break;
1134     }
1135   } while (!Done);
1136 
1137   if (Tok.is(MMToken::RBrace))
1138     consumeToken();
1139   else {
1140     Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
1141     Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
1142     HadError = true;
1143   }
1144 }
1145 
1146 /// \brief Parse a module map file.
1147 ///
1148 ///   module-map-file:
1149 ///     module-declaration*
1150 bool ModuleMapParser::parseModuleMapFile() {
1151   do {
1152     switch (Tok.Kind) {
1153     case MMToken::EndOfFile:
1154       return HadError;
1155 
1156     case MMToken::ExplicitKeyword:
1157     case MMToken::ModuleKeyword:
1158     case MMToken::FrameworkKeyword:
1159       parseModuleDecl();
1160       break;
1161 
1162     case MMToken::ExportKeyword:
1163     case MMToken::HeaderKeyword:
1164     case MMToken::Identifier:
1165     case MMToken::LBrace:
1166     case MMToken::Period:
1167     case MMToken::RBrace:
1168     case MMToken::Star:
1169     case MMToken::StringLiteral:
1170     case MMToken::UmbrellaKeyword:
1171       Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module);
1172       HadError = true;
1173       consumeToken();
1174       break;
1175     }
1176   } while (true);
1177 
1178   return HadError;
1179 }
1180 
1181 bool ModuleMap::parseModuleMapFile(const FileEntry *File) {
1182   FileID ID = SourceMgr->createFileID(File, SourceLocation(), SrcMgr::C_User);
1183   const llvm::MemoryBuffer *Buffer = SourceMgr->getBuffer(ID);
1184   if (!Buffer)
1185     return true;
1186 
1187   // Parse this module map file.
1188   Lexer L(ID, SourceMgr->getBuffer(ID), *SourceMgr, LangOpts);
1189   Diags->getClient()->BeginSourceFile(LangOpts);
1190   ModuleMapParser Parser(L, *SourceMgr, *Diags, *this, File->getDir());
1191   bool Result = Parser.parseModuleMapFile();
1192   Diags->getClient()->EndSourceFile();
1193 
1194   return Result;
1195 }
1196