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