1 //===--- ModuleMap.cpp - Describe the layout of modules ---------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the ModuleMap implementation, which describes the layout
11 // of a module as it relates to headers.
13 //===----------------------------------------------------------------------===//
14 #include "clang/Lex/ModuleMap.h"
15 #include "clang/Basic/CharInfo.h"
16 #include "clang/Basic/Diagnostic.h"
17 #include "clang/Basic/DiagnosticOptions.h"
18 #include "clang/Basic/FileManager.h"
19 #include "clang/Basic/TargetInfo.h"
20 #include "clang/Basic/TargetOptions.h"
21 #include "clang/Lex/HeaderSearch.h"
22 #include "clang/Lex/LexDiagnostic.h"
23 #include "clang/Lex/Lexer.h"
24 #include "clang/Lex/LiteralSupport.h"
25 #include "llvm/ADT/StringRef.h"
26 #include "llvm/ADT/StringSwitch.h"
27 #include "llvm/Support/Allocator.h"
28 #include "llvm/Support/FileSystem.h"
29 #include "llvm/Support/Host.h"
30 #include "llvm/Support/PathV2.h"
31 #include "llvm/Support/raw_ostream.h"
33 #if defined(LLVM_ON_UNIX)
36 using namespace clang;
39 ModuleMap::resolveExport(Module *Mod,
40 const Module::UnresolvedExportDecl &Unresolved,
41 bool Complain) const {
42 // We may have just a wildcard.
43 if (Unresolved.Id.empty()) {
44 assert(Unresolved.Wildcard && "Invalid unresolved export");
45 return Module::ExportDecl(0, true);
48 // Resolve the module-id.
49 Module *Context = resolveModuleId(Unresolved.Id, Mod, Complain);
51 return Module::ExportDecl();
53 return Module::ExportDecl(Context, Unresolved.Wildcard);
56 Module *ModuleMap::resolveModuleId(const ModuleId &Id, Module *Mod,
57 bool Complain) const {
58 // Find the starting module.
59 Module *Context = lookupModuleUnqualified(Id[0].first, Mod);
62 Diags->Report(Id[0].second, diag::err_mmap_missing_module_unqualified)
63 << Id[0].first << Mod->getFullModuleName();
68 // Dig into the module path.
69 for (unsigned I = 1, N = Id.size(); I != N; ++I) {
70 Module *Sub = lookupModuleQualified(Id[I].first, Context);
73 Diags->Report(Id[I].second, diag::err_mmap_missing_module_qualified)
74 << Id[I].first << Context->getFullModuleName()
75 << SourceRange(Id[0].second, Id[I-1].second);
86 ModuleMap::ModuleMap(FileManager &FileMgr, const DiagnosticConsumer &DC,
87 const LangOptions &LangOpts, const TargetInfo *Target,
88 HeaderSearch &HeaderInfo)
89 : LangOpts(LangOpts), Target(Target), HeaderInfo(HeaderInfo),
92 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(new DiagnosticIDs);
93 Diags = IntrusiveRefCntPtr<DiagnosticsEngine>(
94 new DiagnosticsEngine(DiagIDs, new DiagnosticOptions));
95 Diags->setClient(DC.clone(*Diags), /*ShouldOwnClient=*/true);
96 SourceMgr = new SourceManager(*Diags, FileMgr);
99 ModuleMap::~ModuleMap() {
100 for (llvm::StringMap<Module *>::iterator I = Modules.begin(),
101 IEnd = Modules.end();
103 delete I->getValue();
109 void ModuleMap::setTarget(const TargetInfo &Target) {
110 assert((!this->Target || this->Target == &Target) &&
111 "Improper target override");
112 this->Target = &Target;
115 /// \brief "Sanitize" a filename so that it can be used as an identifier.
116 static StringRef sanitizeFilenameAsIdentifier(StringRef Name,
117 SmallVectorImpl<char> &Buffer) {
121 if (!isValidIdentifier(Name)) {
122 // If we don't already have something with the form of an identifier,
123 // create a buffer with the sanitized name.
125 if (isDigit(Name[0]))
126 Buffer.push_back('_');
127 Buffer.reserve(Buffer.size() + Name.size());
128 for (unsigned I = 0, N = Name.size(); I != N; ++I) {
129 if (isIdentifierBody(Name[I]))
130 Buffer.push_back(Name[I]);
132 Buffer.push_back('_');
135 Name = StringRef(Buffer.data(), Buffer.size());
138 while (llvm::StringSwitch<bool>(Name)
139 #define KEYWORD(Keyword,Conditions) .Case(#Keyword, true)
140 #define ALIAS(Keyword, AliasOf, Conditions) .Case(Keyword, true)
141 #include "clang/Basic/TokenKinds.def"
143 if (Name.data() != Buffer.data())
144 Buffer.append(Name.begin(), Name.end());
145 Buffer.push_back('_');
146 Name = StringRef(Buffer.data(), Buffer.size());
152 Module *ModuleMap::findModuleForHeader(const FileEntry *File) {
153 HeadersMap::iterator Known = Headers.find(File);
154 if (Known != Headers.end()) {
155 // If a header is not available, don't report that it maps to anything.
156 if (!Known->second.isAvailable())
159 return Known->second.getModule();
162 const DirectoryEntry *Dir = File->getDir();
163 SmallVector<const DirectoryEntry *, 2> SkippedDirs;
165 // Note: as an egregious but useful hack we use the real path here, because
166 // frameworks moving from top-level frameworks to embedded frameworks tend
167 // to be symlinked from the top-level location to the embedded location,
168 // and we need to resolve lookups as if we had found the embedded location.
169 StringRef DirName = SourceMgr->getFileManager().getCanonicalName(Dir);
171 // Keep walking up the directory hierarchy, looking for a directory with
172 // an umbrella header.
174 llvm::DenseMap<const DirectoryEntry *, Module *>::iterator KnownDir
175 = UmbrellaDirs.find(Dir);
176 if (KnownDir != UmbrellaDirs.end()) {
177 Module *Result = KnownDir->second;
179 // Search up the module stack until we find a module with an umbrella
181 Module *UmbrellaModule = Result;
182 while (!UmbrellaModule->getUmbrellaDir() && UmbrellaModule->Parent)
183 UmbrellaModule = UmbrellaModule->Parent;
185 if (UmbrellaModule->InferSubmodules) {
186 // Infer submodules for each of the directories we found between
187 // the directory of the umbrella header and the directory where
188 // the actual header is located.
189 bool Explicit = UmbrellaModule->InferExplicitSubmodules;
191 for (unsigned I = SkippedDirs.size(); I != 0; --I) {
192 // Find or create the module that corresponds to this directory name.
193 SmallString<32> NameBuf;
194 StringRef Name = sanitizeFilenameAsIdentifier(
195 llvm::sys::path::stem(SkippedDirs[I-1]->getName()),
197 Result = findOrCreateModule(Name, Result, /*IsFramework=*/false,
200 // Associate the module and the directory.
201 UmbrellaDirs[SkippedDirs[I-1]] = Result;
203 // If inferred submodules export everything they import, add a
204 // wildcard to the set of exports.
205 if (UmbrellaModule->InferExportWildcard && Result->Exports.empty())
206 Result->Exports.push_back(Module::ExportDecl(0, true));
209 // Infer a submodule with the same name as this header file.
210 SmallString<32> NameBuf;
211 StringRef Name = sanitizeFilenameAsIdentifier(
212 llvm::sys::path::stem(File->getName()), NameBuf);
213 Result = findOrCreateModule(Name, Result, /*IsFramework=*/false,
215 Result->addTopHeader(File);
217 // If inferred submodules export everything they import, add a
218 // wildcard to the set of exports.
219 if (UmbrellaModule->InferExportWildcard && Result->Exports.empty())
220 Result->Exports.push_back(Module::ExportDecl(0, true));
222 // Record each of the directories we stepped through as being part of
223 // the module we found, since the umbrella header covers them all.
224 for (unsigned I = 0, N = SkippedDirs.size(); I != N; ++I)
225 UmbrellaDirs[SkippedDirs[I]] = Result;
228 Headers[File] = KnownHeader(Result, /*Excluded=*/false);
230 // If a header corresponds to an unavailable module, don't report
231 // that it maps to anything.
232 if (!Result->isAvailable())
238 SkippedDirs.push_back(Dir);
240 // Retrieve our parent path.
241 DirName = llvm::sys::path::parent_path(DirName);
245 // Resolve the parent path to a directory entry.
246 Dir = SourceMgr->getFileManager().getDirectory(DirName);
252 bool ModuleMap::isHeaderInUnavailableModule(const FileEntry *Header) const {
253 HeadersMap::const_iterator Known = Headers.find(Header);
254 if (Known != Headers.end())
255 return !Known->second.isAvailable();
257 const DirectoryEntry *Dir = Header->getDir();
258 SmallVector<const DirectoryEntry *, 2> SkippedDirs;
259 StringRef DirName = Dir->getName();
261 // Keep walking up the directory hierarchy, looking for a directory with
262 // an umbrella header.
264 llvm::DenseMap<const DirectoryEntry *, Module *>::const_iterator KnownDir
265 = UmbrellaDirs.find(Dir);
266 if (KnownDir != UmbrellaDirs.end()) {
267 Module *Found = KnownDir->second;
268 if (!Found->isAvailable())
271 // Search up the module stack until we find a module with an umbrella
273 Module *UmbrellaModule = Found;
274 while (!UmbrellaModule->getUmbrellaDir() && UmbrellaModule->Parent)
275 UmbrellaModule = UmbrellaModule->Parent;
277 if (UmbrellaModule->InferSubmodules) {
278 for (unsigned I = SkippedDirs.size(); I != 0; --I) {
279 // Find or create the module that corresponds to this directory name.
280 SmallString<32> NameBuf;
281 StringRef Name = sanitizeFilenameAsIdentifier(
282 llvm::sys::path::stem(SkippedDirs[I-1]->getName()),
284 Found = lookupModuleQualified(Name, Found);
287 if (!Found->isAvailable())
291 // Infer a submodule with the same name as this header file.
292 SmallString<32> NameBuf;
293 StringRef Name = sanitizeFilenameAsIdentifier(
294 llvm::sys::path::stem(Header->getName()),
296 Found = lookupModuleQualified(Name, Found);
301 return !Found->isAvailable();
304 SkippedDirs.push_back(Dir);
306 // Retrieve our parent path.
307 DirName = llvm::sys::path::parent_path(DirName);
311 // Resolve the parent path to a directory entry.
312 Dir = SourceMgr->getFileManager().getDirectory(DirName);
318 Module *ModuleMap::findModule(StringRef Name) const {
319 llvm::StringMap<Module *>::const_iterator Known = Modules.find(Name);
320 if (Known != Modules.end())
321 return Known->getValue();
326 Module *ModuleMap::lookupModuleUnqualified(StringRef Name,
327 Module *Context) const {
328 for(; Context; Context = Context->Parent) {
329 if (Module *Sub = lookupModuleQualified(Name, Context))
333 return findModule(Name);
336 Module *ModuleMap::lookupModuleQualified(StringRef Name, Module *Context) const{
338 return findModule(Name);
340 return Context->findSubmodule(Name);
343 std::pair<Module *, bool>
344 ModuleMap::findOrCreateModule(StringRef Name, Module *Parent, bool IsFramework,
346 // Try to find an existing module with this name.
347 if (Module *Sub = lookupModuleQualified(Name, Parent))
348 return std::make_pair(Sub, false);
350 // Create a new module with this name.
351 Module *Result = new Module(Name, SourceLocation(), Parent, IsFramework,
354 Modules[Name] = Result;
355 return std::make_pair(Result, true);
358 bool ModuleMap::canInferFrameworkModule(const DirectoryEntry *ParentDir,
359 StringRef Name, bool &IsSystem) const {
360 // Check whether we have already looked into the parent directory
362 llvm::DenseMap<const DirectoryEntry *, InferredDirectory>::const_iterator
363 inferred = InferredDirectories.find(ParentDir);
364 if (inferred == InferredDirectories.end())
367 if (!inferred->second.InferModules)
370 // We're allowed to infer for this directory, but make sure it's okay
371 // to infer this particular module.
372 bool canInfer = std::find(inferred->second.ExcludedModules.begin(),
373 inferred->second.ExcludedModules.end(),
374 Name) == inferred->second.ExcludedModules.end();
376 if (canInfer && inferred->second.InferSystemModules)
382 /// \brief For a framework module, infer the framework against which we
384 static void inferFrameworkLink(Module *Mod, const DirectoryEntry *FrameworkDir,
385 FileManager &FileMgr) {
386 assert(Mod->IsFramework && "Can only infer linking for framework modules");
387 assert(!Mod->isSubFramework() &&
388 "Can only infer linking for top-level frameworks");
390 SmallString<128> LibName;
391 LibName += FrameworkDir->getName();
392 llvm::sys::path::append(LibName, Mod->Name);
393 if (FileMgr.getFile(LibName)) {
394 Mod->LinkLibraries.push_back(Module::LinkLibrary(Mod->Name,
395 /*IsFramework=*/true));
400 ModuleMap::inferFrameworkModule(StringRef ModuleName,
401 const DirectoryEntry *FrameworkDir,
404 // Check whether we've already found this module.
405 if (Module *Mod = lookupModuleQualified(ModuleName, Parent))
408 FileManager &FileMgr = SourceMgr->getFileManager();
410 // If the framework has a parent path from which we're allowed to infer
411 // a framework module, do so.
413 // Determine whether we're allowed to infer a module map.
415 // Note: as an egregious but useful hack we use the real path here, because
416 // we might be looking at an embedded framework that symlinks out to a
417 // top-level framework, and we need to infer as if we were naming the
418 // top-level framework.
419 StringRef FrameworkDirName
420 = SourceMgr->getFileManager().getCanonicalName(FrameworkDir);
422 bool canInfer = false;
423 if (llvm::sys::path::has_parent_path(FrameworkDirName)) {
424 // Figure out the parent path.
425 StringRef Parent = llvm::sys::path::parent_path(FrameworkDirName);
426 if (const DirectoryEntry *ParentDir = FileMgr.getDirectory(Parent)) {
427 // Check whether we have already looked into the parent directory
429 llvm::DenseMap<const DirectoryEntry *, InferredDirectory>::const_iterator
430 inferred = InferredDirectories.find(ParentDir);
431 if (inferred == InferredDirectories.end()) {
432 // We haven't looked here before. Load a module map, if there is
434 SmallString<128> ModMapPath = Parent;
435 llvm::sys::path::append(ModMapPath, "module.map");
436 if (const FileEntry *ModMapFile = FileMgr.getFile(ModMapPath)) {
437 parseModuleMapFile(ModMapFile);
438 inferred = InferredDirectories.find(ParentDir);
441 if (inferred == InferredDirectories.end())
442 inferred = InferredDirectories.insert(
443 std::make_pair(ParentDir, InferredDirectory())).first;
446 if (inferred->second.InferModules) {
447 // We're allowed to infer for this directory, but make sure it's okay
448 // to infer this particular module.
449 StringRef Name = llvm::sys::path::stem(FrameworkDirName);
450 canInfer = std::find(inferred->second.ExcludedModules.begin(),
451 inferred->second.ExcludedModules.end(),
452 Name) == inferred->second.ExcludedModules.end();
454 if (inferred->second.InferSystemModules)
460 // If we're not allowed to infer a framework module, don't.
466 // Look for an umbrella header.
467 SmallString<128> UmbrellaName = StringRef(FrameworkDir->getName());
468 llvm::sys::path::append(UmbrellaName, "Headers");
469 llvm::sys::path::append(UmbrellaName, ModuleName + ".h");
470 const FileEntry *UmbrellaHeader = FileMgr.getFile(UmbrellaName);
472 // FIXME: If there's no umbrella header, we could probably scan the
473 // framework to load *everything*. But, it's not clear that this is a good
478 Module *Result = new Module(ModuleName, SourceLocation(), Parent,
479 /*IsFramework=*/true, /*IsExplicit=*/false);
481 Result->IsSystem = IsSystem;
484 Modules[ModuleName] = Result;
486 // umbrella header "umbrella-header-name"
487 Result->Umbrella = UmbrellaHeader;
488 Headers[UmbrellaHeader] = KnownHeader(Result, /*Excluded=*/false);
489 UmbrellaDirs[UmbrellaHeader->getDir()] = Result;
492 Result->Exports.push_back(Module::ExportDecl(0, true));
494 // module * { export * }
495 Result->InferSubmodules = true;
496 Result->InferExportWildcard = true;
498 // Look for subframeworks.
500 SmallString<128> SubframeworksDirName
501 = StringRef(FrameworkDir->getName());
502 llvm::sys::path::append(SubframeworksDirName, "Frameworks");
503 SmallString<128> SubframeworksDirNameNative;
504 llvm::sys::path::native(SubframeworksDirName.str(),
505 SubframeworksDirNameNative);
506 for (llvm::sys::fs::directory_iterator
507 Dir(SubframeworksDirNameNative.str(), EC), DirEnd;
508 Dir != DirEnd && !EC; Dir.increment(EC)) {
509 if (!StringRef(Dir->path()).endswith(".framework"))
512 if (const DirectoryEntry *SubframeworkDir
513 = FileMgr.getDirectory(Dir->path())) {
514 // Note: as an egregious but useful hack, we use the real path here and
515 // check whether it is actually a subdirectory of the parent directory.
516 // This will not be the case if the 'subframework' is actually a symlink
517 // out to a top-level framework.
518 StringRef SubframeworkDirName = FileMgr.getCanonicalName(SubframeworkDir);
519 bool FoundParent = false;
521 // Get the parent directory name.
523 = llvm::sys::path::parent_path(SubframeworkDirName);
524 if (SubframeworkDirName.empty())
527 if (FileMgr.getDirectory(SubframeworkDirName) == FrameworkDir) {
536 // FIXME: Do we want to warn about subframeworks without umbrella headers?
537 SmallString<32> NameBuf;
538 inferFrameworkModule(sanitizeFilenameAsIdentifier(
539 llvm::sys::path::stem(Dir->path()), NameBuf),
540 SubframeworkDir, IsSystem, Result);
544 // If the module is a top-level framework, automatically link against the
546 if (!Result->isSubFramework()) {
547 inferFrameworkLink(Result, FrameworkDir, FileMgr);
553 void ModuleMap::setUmbrellaHeader(Module *Mod, const FileEntry *UmbrellaHeader){
554 Headers[UmbrellaHeader] = KnownHeader(Mod, /*Excluded=*/false);
555 Mod->Umbrella = UmbrellaHeader;
556 UmbrellaDirs[UmbrellaHeader->getDir()] = Mod;
559 void ModuleMap::setUmbrellaDir(Module *Mod, const DirectoryEntry *UmbrellaDir) {
560 Mod->Umbrella = UmbrellaDir;
561 UmbrellaDirs[UmbrellaDir] = Mod;
564 void ModuleMap::addHeader(Module *Mod, const FileEntry *Header,
567 Mod->ExcludedHeaders.push_back(Header);
569 Mod->Headers.push_back(Header);
570 HeaderInfo.MarkFileModuleHeader(Header);
572 Headers[Header] = KnownHeader(Mod, Excluded);
576 ModuleMap::getContainingModuleMapFile(Module *Module) const {
577 if (Module->DefinitionLoc.isInvalid() || !SourceMgr)
580 return SourceMgr->getFileEntryForID(
581 SourceMgr->getFileID(Module->DefinitionLoc));
584 void ModuleMap::dump() {
585 llvm::errs() << "Modules:";
586 for (llvm::StringMap<Module *>::iterator M = Modules.begin(),
587 MEnd = Modules.end();
589 M->getValue()->print(llvm::errs(), 2);
591 llvm::errs() << "Headers:";
592 for (HeadersMap::iterator H = Headers.begin(), HEnd = Headers.end();
594 llvm::errs() << " \"" << H->first->getName() << "\" -> "
595 << H->second.getModule()->getFullModuleName() << "\n";
599 bool ModuleMap::resolveExports(Module *Mod, bool Complain) {
600 bool HadError = false;
601 for (unsigned I = 0, N = Mod->UnresolvedExports.size(); I != N; ++I) {
602 Module::ExportDecl Export = resolveExport(Mod, Mod->UnresolvedExports[I],
604 if (Export.getPointer() || Export.getInt())
605 Mod->Exports.push_back(Export);
609 Mod->UnresolvedExports.clear();
613 bool ModuleMap::resolveConflicts(Module *Mod, bool Complain) {
614 bool HadError = false;
615 for (unsigned I = 0, N = Mod->UnresolvedConflicts.size(); I != N; ++I) {
616 Module *OtherMod = resolveModuleId(Mod->UnresolvedConflicts[I].Id,
623 Module::Conflict Conflict;
624 Conflict.Other = OtherMod;
625 Conflict.Message = Mod->UnresolvedConflicts[I].Message;
626 Mod->Conflicts.push_back(Conflict);
628 Mod->UnresolvedConflicts.clear();
632 Module *ModuleMap::inferModuleFromLocation(FullSourceLoc Loc) {
636 // Use the expansion location to determine which module we're in.
637 FullSourceLoc ExpansionLoc = Loc.getExpansionLoc();
638 if (!ExpansionLoc.isFileID())
642 const SourceManager &SrcMgr = Loc.getManager();
643 FileID ExpansionFileID = ExpansionLoc.getFileID();
645 while (const FileEntry *ExpansionFile
646 = SrcMgr.getFileEntryForID(ExpansionFileID)) {
647 // Find the module that owns this header (if any).
648 if (Module *Mod = findModuleForHeader(ExpansionFile))
651 // No module owns this header, so look up the inclusion chain to see if
652 // any included header has an associated module.
653 SourceLocation IncludeLoc = SrcMgr.getIncludeLoc(ExpansionFileID);
654 if (IncludeLoc.isInvalid())
657 ExpansionFileID = SrcMgr.getFileID(IncludeLoc);
663 //----------------------------------------------------------------------------//
664 // Module map file parser
665 //----------------------------------------------------------------------------//
668 /// \brief A token in a module map file.
695 unsigned StringLength;
696 const char *StringData;
705 bool is(TokenKind K) const { return Kind == K; }
707 SourceLocation getLocation() const {
708 return SourceLocation::getFromRawEncoding(Location);
711 StringRef getString() const {
712 return StringRef(StringData, StringLength);
716 /// \brief The set of attributes that can be attached to a module.
718 Attributes() : IsSystem(), IsExhaustive() { }
720 /// \brief Whether this is a system module.
721 unsigned IsSystem : 1;
723 /// \brief Whether this is an exhaustive set of configuration macros.
724 unsigned IsExhaustive : 1;
728 class ModuleMapParser {
730 SourceManager &SourceMgr;
732 /// \brief Default target information, used only for string literal
734 const TargetInfo *Target;
736 DiagnosticsEngine &Diags;
739 /// \brief The directory that this module map resides in.
740 const DirectoryEntry *Directory;
742 /// \brief The directory containing Clang-supplied headers.
743 const DirectoryEntry *BuiltinIncludeDir;
745 /// \brief Whether an error occurred.
748 /// \brief Stores string data for the various string literals referenced
750 llvm::BumpPtrAllocator StringData;
752 /// \brief The current token.
755 /// \brief The active module.
756 Module *ActiveModule;
758 /// \brief Consume the current token and return its location.
759 SourceLocation consumeToken();
761 /// \brief Skip tokens until we reach the a token with the given kind
762 /// (or the end of the file).
763 void skipUntil(MMToken::TokenKind K);
765 typedef SmallVector<std::pair<std::string, SourceLocation>, 2> ModuleId;
766 bool parseModuleId(ModuleId &Id);
767 void parseModuleDecl();
768 void parseRequiresDecl();
769 void parseHeaderDecl(SourceLocation UmbrellaLoc, SourceLocation ExcludeLoc);
770 void parseUmbrellaDirDecl(SourceLocation UmbrellaLoc);
771 void parseExportDecl();
772 void parseLinkDecl();
773 void parseConfigMacros();
774 void parseConflict();
775 void parseInferredModuleDecl(bool Framework, bool Explicit);
776 bool parseOptionalAttributes(Attributes &Attrs);
778 const DirectoryEntry *getOverriddenHeaderSearchDir();
781 explicit ModuleMapParser(Lexer &L, SourceManager &SourceMgr,
782 const TargetInfo *Target,
783 DiagnosticsEngine &Diags,
785 const DirectoryEntry *Directory,
786 const DirectoryEntry *BuiltinIncludeDir)
787 : L(L), SourceMgr(SourceMgr), Target(Target), Diags(Diags), Map(Map),
788 Directory(Directory), BuiltinIncludeDir(BuiltinIncludeDir),
789 HadError(false), ActiveModule(0)
795 bool parseModuleMapFile();
799 SourceLocation ModuleMapParser::consumeToken() {
801 SourceLocation Result = Tok.getLocation();
805 L.LexFromRawLexer(LToken);
806 Tok.Location = LToken.getLocation().getRawEncoding();
807 switch (LToken.getKind()) {
808 case tok::raw_identifier:
809 Tok.StringData = LToken.getRawIdentifierData();
810 Tok.StringLength = LToken.getLength();
811 Tok.Kind = llvm::StringSwitch<MMToken::TokenKind>(Tok.getString())
812 .Case("config_macros", MMToken::ConfigMacros)
813 .Case("conflict", MMToken::Conflict)
814 .Case("exclude", MMToken::ExcludeKeyword)
815 .Case("explicit", MMToken::ExplicitKeyword)
816 .Case("export", MMToken::ExportKeyword)
817 .Case("framework", MMToken::FrameworkKeyword)
818 .Case("header", MMToken::HeaderKeyword)
819 .Case("link", MMToken::LinkKeyword)
820 .Case("module", MMToken::ModuleKeyword)
821 .Case("requires", MMToken::RequiresKeyword)
822 .Case("umbrella", MMToken::UmbrellaKeyword)
823 .Default(MMToken::Identifier);
827 Tok.Kind = MMToken::Comma;
831 Tok.Kind = MMToken::EndOfFile;
835 Tok.Kind = MMToken::LBrace;
839 Tok.Kind = MMToken::LSquare;
843 Tok.Kind = MMToken::Period;
847 Tok.Kind = MMToken::RBrace;
851 Tok.Kind = MMToken::RSquare;
855 Tok.Kind = MMToken::Star;
858 case tok::string_literal: {
859 if (LToken.hasUDSuffix()) {
860 Diags.Report(LToken.getLocation(), diag::err_invalid_string_udl);
865 // Parse the string literal.
866 LangOptions LangOpts;
867 StringLiteralParser StringLiteral(<oken, 1, SourceMgr, LangOpts, *Target);
868 if (StringLiteral.hadError)
871 // Copy the string literal into our string data allocator.
872 unsigned Length = StringLiteral.GetStringLength();
873 char *Saved = StringData.Allocate<char>(Length + 1);
874 memcpy(Saved, StringLiteral.GetString().data(), Length);
878 Tok.Kind = MMToken::StringLiteral;
879 Tok.StringData = Saved;
880 Tok.StringLength = Length;
888 Diags.Report(LToken.getLocation(), diag::err_mmap_unknown_token);
896 void ModuleMapParser::skipUntil(MMToken::TokenKind K) {
897 unsigned braceDepth = 0;
898 unsigned squareDepth = 0;
901 case MMToken::EndOfFile:
904 case MMToken::LBrace:
905 if (Tok.is(K) && braceDepth == 0 && squareDepth == 0)
911 case MMToken::LSquare:
912 if (Tok.is(K) && braceDepth == 0 && squareDepth == 0)
918 case MMToken::RBrace:
925 case MMToken::RSquare:
933 if (braceDepth == 0 && squareDepth == 0 && Tok.is(K))
942 /// \brief Parse a module-id.
946 /// identifier '.' module-id
948 /// \returns true if an error occurred, false otherwise.
949 bool ModuleMapParser::parseModuleId(ModuleId &Id) {
952 if (Tok.is(MMToken::Identifier)) {
953 Id.push_back(std::make_pair(Tok.getString(), Tok.getLocation()));
956 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module_name);
960 if (!Tok.is(MMToken::Period))
970 /// \brief Enumerates the known attributes.
972 /// \brief An unknown attribute.
974 /// \brief The 'system' attribute.
976 /// \brief The 'exhaustive' attribute.
981 /// \brief Parse a module declaration.
983 /// module-declaration:
984 /// 'explicit'[opt] 'framework'[opt] 'module' module-id attributes[opt]
985 /// { module-member* }
988 /// requires-declaration
989 /// header-declaration
990 /// submodule-declaration
991 /// export-declaration
994 /// submodule-declaration:
995 /// module-declaration
996 /// inferred-submodule-declaration
997 void ModuleMapParser::parseModuleDecl() {
998 assert(Tok.is(MMToken::ExplicitKeyword) || Tok.is(MMToken::ModuleKeyword) ||
999 Tok.is(MMToken::FrameworkKeyword));
1000 // Parse 'explicit' or 'framework' keyword, if present.
1001 SourceLocation ExplicitLoc;
1002 bool Explicit = false;
1003 bool Framework = false;
1005 // Parse 'explicit' keyword, if present.
1006 if (Tok.is(MMToken::ExplicitKeyword)) {
1007 ExplicitLoc = consumeToken();
1011 // Parse 'framework' keyword, if present.
1012 if (Tok.is(MMToken::FrameworkKeyword)) {
1017 // Parse 'module' keyword.
1018 if (!Tok.is(MMToken::ModuleKeyword)) {
1019 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module);
1024 consumeToken(); // 'module' keyword
1026 // If we have a wildcard for the module name, this is an inferred submodule.
1028 if (Tok.is(MMToken::Star))
1029 return parseInferredModuleDecl(Framework, Explicit);
1031 // Parse the module name.
1033 if (parseModuleId(Id)) {
1039 if (Id.size() > 1) {
1040 Diags.Report(Id.front().second, diag::err_mmap_nested_submodule_id)
1041 << SourceRange(Id.front().second, Id.back().second);
1046 } else if (Id.size() == 1 && Explicit) {
1047 // Top-level modules can't be explicit.
1048 Diags.Report(ExplicitLoc, diag::err_mmap_explicit_top_level);
1050 ExplicitLoc = SourceLocation();
1054 Module *PreviousActiveModule = ActiveModule;
1055 if (Id.size() > 1) {
1056 // This module map defines a submodule. Go find the module of which it
1059 for (unsigned I = 0, N = Id.size() - 1; I != N; ++I) {
1060 if (Module *Next = Map.lookupModuleQualified(Id[I].first, ActiveModule)) {
1061 ActiveModule = Next;
1066 Diags.Report(Id[I].second, diag::err_mmap_missing_module_qualified)
1067 << Id[I].first << ActiveModule->getTopLevelModule();
1069 Diags.Report(Id[I].second, diag::err_mmap_expected_module_name);
1076 StringRef ModuleName = Id.back().first;
1077 SourceLocation ModuleNameLoc = Id.back().second;
1079 // Parse the optional attribute list.
1081 parseOptionalAttributes(Attrs);
1083 // Parse the opening brace.
1084 if (!Tok.is(MMToken::LBrace)) {
1085 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_lbrace)
1090 SourceLocation LBraceLoc = consumeToken();
1092 // Determine whether this (sub)module has already been defined.
1093 if (Module *Existing = Map.lookupModuleQualified(ModuleName, ActiveModule)) {
1094 if (Existing->DefinitionLoc.isInvalid() && !ActiveModule) {
1095 // Skip the module definition.
1096 skipUntil(MMToken::RBrace);
1097 if (Tok.is(MMToken::RBrace))
1100 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
1101 Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
1107 Diags.Report(ModuleNameLoc, diag::err_mmap_module_redefinition)
1109 Diags.Report(Existing->DefinitionLoc, diag::note_mmap_prev_definition);
1111 // Skip the module definition.
1112 skipUntil(MMToken::RBrace);
1113 if (Tok.is(MMToken::RBrace))
1120 // Start defining this module.
1121 ActiveModule = Map.findOrCreateModule(ModuleName, ActiveModule, Framework,
1123 ActiveModule->DefinitionLoc = ModuleNameLoc;
1125 ActiveModule->IsSystem = true;
1130 case MMToken::EndOfFile:
1131 case MMToken::RBrace:
1135 case MMToken::ConfigMacros:
1136 parseConfigMacros();
1139 case MMToken::Conflict:
1143 case MMToken::ExplicitKeyword:
1144 case MMToken::FrameworkKeyword:
1145 case MMToken::ModuleKeyword:
1149 case MMToken::ExportKeyword:
1153 case MMToken::RequiresKeyword:
1154 parseRequiresDecl();
1157 case MMToken::UmbrellaKeyword: {
1158 SourceLocation UmbrellaLoc = consumeToken();
1159 if (Tok.is(MMToken::HeaderKeyword))
1160 parseHeaderDecl(UmbrellaLoc, SourceLocation());
1162 parseUmbrellaDirDecl(UmbrellaLoc);
1166 case MMToken::ExcludeKeyword: {
1167 SourceLocation ExcludeLoc = consumeToken();
1168 if (Tok.is(MMToken::HeaderKeyword)) {
1169 parseHeaderDecl(SourceLocation(), ExcludeLoc);
1171 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
1177 case MMToken::HeaderKeyword:
1178 parseHeaderDecl(SourceLocation(), SourceLocation());
1181 case MMToken::LinkKeyword:
1186 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_member);
1192 if (Tok.is(MMToken::RBrace))
1195 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
1196 Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
1200 // If the active module is a top-level framework, and there are no link
1201 // libraries, automatically link against the framework.
1202 if (ActiveModule->IsFramework && !ActiveModule->isSubFramework() &&
1203 ActiveModule->LinkLibraries.empty()) {
1204 inferFrameworkLink(ActiveModule, Directory, SourceMgr.getFileManager());
1207 // We're done parsing this module. Pop back to the previous module.
1208 ActiveModule = PreviousActiveModule;
1211 /// \brief Parse a requires declaration.
1213 /// requires-declaration:
1214 /// 'requires' feature-list
1217 /// identifier ',' feature-list
1219 void ModuleMapParser::parseRequiresDecl() {
1220 assert(Tok.is(MMToken::RequiresKeyword));
1222 // Parse 'requires' keyword.
1225 // Parse the feature-list.
1227 if (!Tok.is(MMToken::Identifier)) {
1228 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_feature);
1233 // Consume the feature name.
1234 std::string Feature = Tok.getString();
1237 // Add this feature.
1238 ActiveModule->addRequirement(Feature, Map.LangOpts, *Map.Target);
1240 if (!Tok.is(MMToken::Comma))
1243 // Consume the comma.
1248 /// \brief Append to \p Paths the set of paths needed to get to the
1249 /// subframework in which the given module lives.
1250 static void appendSubframeworkPaths(Module *Mod,
1251 SmallVectorImpl<char> &Path) {
1252 // Collect the framework names from the given module to the top-level module.
1253 SmallVector<StringRef, 2> Paths;
1254 for (; Mod; Mod = Mod->Parent) {
1255 if (Mod->IsFramework)
1256 Paths.push_back(Mod->Name);
1262 // Add Frameworks/Name.framework for each subframework.
1263 for (unsigned I = Paths.size() - 1; I != 0; --I) {
1264 llvm::sys::path::append(Path, "Frameworks");
1265 llvm::sys::path::append(Path, Paths[I-1] + ".framework");
1269 /// \brief Determine whether the given file name is the name of a builtin
1270 /// header, supplied by Clang to replace, override, or augment existing system
1272 static bool isBuiltinHeader(StringRef FileName) {
1273 return llvm::StringSwitch<bool>(FileName)
1274 .Case("float.h", true)
1275 .Case("iso646.h", true)
1276 .Case("limits.h", true)
1277 .Case("stdalign.h", true)
1278 .Case("stdarg.h", true)
1279 .Case("stdbool.h", true)
1280 .Case("stddef.h", true)
1281 .Case("stdint.h", true)
1282 .Case("tgmath.h", true)
1283 .Case("unwind.h", true)
1287 /// \brief Parse a header declaration.
1289 /// header-declaration:
1290 /// 'umbrella'[opt] 'header' string-literal
1291 /// 'exclude'[opt] 'header' string-literal
1292 void ModuleMapParser::parseHeaderDecl(SourceLocation UmbrellaLoc,
1293 SourceLocation ExcludeLoc) {
1294 assert(Tok.is(MMToken::HeaderKeyword));
1297 bool Umbrella = UmbrellaLoc.isValid();
1298 bool Exclude = ExcludeLoc.isValid();
1299 assert(!(Umbrella && Exclude) && "Cannot have both 'umbrella' and 'exclude'");
1300 // Parse the header name.
1301 if (!Tok.is(MMToken::StringLiteral)) {
1302 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
1307 std::string FileName = Tok.getString();
1308 SourceLocation FileNameLoc = consumeToken();
1310 // Check whether we already have an umbrella.
1311 if (Umbrella && ActiveModule->Umbrella) {
1312 Diags.Report(FileNameLoc, diag::err_mmap_umbrella_clash)
1313 << ActiveModule->getFullModuleName();
1318 // Look for this file.
1319 const FileEntry *File = 0;
1320 const FileEntry *BuiltinFile = 0;
1321 SmallString<128> PathName;
1322 if (llvm::sys::path::is_absolute(FileName)) {
1323 PathName = FileName;
1324 File = SourceMgr.getFileManager().getFile(PathName);
1325 } else if (const DirectoryEntry *Dir = getOverriddenHeaderSearchDir()) {
1326 PathName = Dir->getName();
1327 llvm::sys::path::append(PathName, FileName);
1328 File = SourceMgr.getFileManager().getFile(PathName);
1330 // Search for the header file within the search directory.
1331 PathName = Directory->getName();
1332 unsigned PathLength = PathName.size();
1334 if (ActiveModule->isPartOfFramework()) {
1335 appendSubframeworkPaths(ActiveModule, PathName);
1337 // Check whether this file is in the public headers.
1338 llvm::sys::path::append(PathName, "Headers");
1339 llvm::sys::path::append(PathName, FileName);
1340 File = SourceMgr.getFileManager().getFile(PathName);
1343 // Check whether this file is in the private headers.
1344 PathName.resize(PathLength);
1345 llvm::sys::path::append(PathName, "PrivateHeaders");
1346 llvm::sys::path::append(PathName, FileName);
1347 File = SourceMgr.getFileManager().getFile(PathName);
1350 // Lookup for normal headers.
1351 llvm::sys::path::append(PathName, FileName);
1352 File = SourceMgr.getFileManager().getFile(PathName);
1354 // If this is a system module with a top-level header, this header
1355 // may have a counterpart (or replacement) in the set of headers
1356 // supplied by Clang. Find that builtin header.
1357 if (ActiveModule->IsSystem && !Umbrella && BuiltinIncludeDir &&
1358 BuiltinIncludeDir != Directory && isBuiltinHeader(FileName)) {
1359 SmallString<128> BuiltinPathName(BuiltinIncludeDir->getName());
1360 llvm::sys::path::append(BuiltinPathName, FileName);
1361 BuiltinFile = SourceMgr.getFileManager().getFile(BuiltinPathName);
1363 // If Clang supplies this header but the underlying system does not,
1364 // just silently swap in our builtin version. Otherwise, we'll end
1365 // up adding both (later).
1366 if (!File && BuiltinFile) {
1374 // FIXME: We shouldn't be eagerly stat'ing every file named in a module map.
1375 // Come up with a lazy way to do this.
1377 if (ModuleMap::KnownHeader OwningModule = Map.Headers[File]) {
1378 Diags.Report(FileNameLoc, diag::err_mmap_header_conflict)
1379 << FileName << OwningModule.getModule()->getFullModuleName();
1381 } else if (Umbrella) {
1382 const DirectoryEntry *UmbrellaDir = File->getDir();
1383 if (Module *UmbrellaModule = Map.UmbrellaDirs[UmbrellaDir]) {
1384 Diags.Report(UmbrellaLoc, diag::err_mmap_umbrella_clash)
1385 << UmbrellaModule->getFullModuleName();
1388 // Record this umbrella header.
1389 Map.setUmbrellaHeader(ActiveModule, File);
1392 // Record this header.
1393 Map.addHeader(ActiveModule, File, Exclude);
1395 // If there is a builtin counterpart to this file, add it now.
1397 Map.addHeader(ActiveModule, BuiltinFile, Exclude);
1399 } else if (!Exclude) {
1400 // Ignore excluded header files. They're optional anyway.
1402 Diags.Report(FileNameLoc, diag::err_mmap_header_not_found)
1403 << Umbrella << FileName;
1408 /// \brief Parse an umbrella directory declaration.
1410 /// umbrella-dir-declaration:
1411 /// umbrella string-literal
1412 void ModuleMapParser::parseUmbrellaDirDecl(SourceLocation UmbrellaLoc) {
1413 // Parse the directory name.
1414 if (!Tok.is(MMToken::StringLiteral)) {
1415 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
1421 std::string DirName = Tok.getString();
1422 SourceLocation DirNameLoc = consumeToken();
1424 // Check whether we already have an umbrella.
1425 if (ActiveModule->Umbrella) {
1426 Diags.Report(DirNameLoc, diag::err_mmap_umbrella_clash)
1427 << ActiveModule->getFullModuleName();
1432 // Look for this file.
1433 const DirectoryEntry *Dir = 0;
1434 if (llvm::sys::path::is_absolute(DirName))
1435 Dir = SourceMgr.getFileManager().getDirectory(DirName);
1437 SmallString<128> PathName;
1438 PathName = Directory->getName();
1439 llvm::sys::path::append(PathName, DirName);
1440 Dir = SourceMgr.getFileManager().getDirectory(PathName);
1444 Diags.Report(DirNameLoc, diag::err_mmap_umbrella_dir_not_found)
1450 if (Module *OwningModule = Map.UmbrellaDirs[Dir]) {
1451 Diags.Report(UmbrellaLoc, diag::err_mmap_umbrella_clash)
1452 << OwningModule->getFullModuleName();
1457 // Record this umbrella directory.
1458 Map.setUmbrellaDir(ActiveModule, Dir);
1461 /// \brief Parse a module export declaration.
1463 /// export-declaration:
1464 /// 'export' wildcard-module-id
1466 /// wildcard-module-id:
1469 /// identifier '.' wildcard-module-id
1470 void ModuleMapParser::parseExportDecl() {
1471 assert(Tok.is(MMToken::ExportKeyword));
1472 SourceLocation ExportLoc = consumeToken();
1474 // Parse the module-id with an optional wildcard at the end.
1475 ModuleId ParsedModuleId;
1476 bool Wildcard = false;
1478 if (Tok.is(MMToken::Identifier)) {
1479 ParsedModuleId.push_back(std::make_pair(Tok.getString(),
1480 Tok.getLocation()));
1483 if (Tok.is(MMToken::Period)) {
1491 if(Tok.is(MMToken::Star)) {
1497 Diags.Report(Tok.getLocation(), diag::err_mmap_export_module_id);
1502 Module::UnresolvedExportDecl Unresolved = {
1503 ExportLoc, ParsedModuleId, Wildcard
1505 ActiveModule->UnresolvedExports.push_back(Unresolved);
1508 /// \brief Parse a link declaration.
1510 /// module-declaration:
1511 /// 'link' 'framework'[opt] string-literal
1512 void ModuleMapParser::parseLinkDecl() {
1513 assert(Tok.is(MMToken::LinkKeyword));
1514 SourceLocation LinkLoc = consumeToken();
1516 // Parse the optional 'framework' keyword.
1517 bool IsFramework = false;
1518 if (Tok.is(MMToken::FrameworkKeyword)) {
1523 // Parse the library name
1524 if (!Tok.is(MMToken::StringLiteral)) {
1525 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_library_name)
1526 << IsFramework << SourceRange(LinkLoc);
1531 std::string LibraryName = Tok.getString();
1533 ActiveModule->LinkLibraries.push_back(Module::LinkLibrary(LibraryName,
1537 /// \brief Parse a configuration macro declaration.
1539 /// module-declaration:
1540 /// 'config_macros' attributes[opt] config-macro-list?
1542 /// config-macro-list:
1543 /// identifier (',' identifier)?
1544 void ModuleMapParser::parseConfigMacros() {
1545 assert(Tok.is(MMToken::ConfigMacros));
1546 SourceLocation ConfigMacrosLoc = consumeToken();
1548 // Only top-level modules can have configuration macros.
1549 if (ActiveModule->Parent) {
1550 Diags.Report(ConfigMacrosLoc, diag::err_mmap_config_macro_submodule);
1553 // Parse the optional attributes.
1555 parseOptionalAttributes(Attrs);
1556 if (Attrs.IsExhaustive && !ActiveModule->Parent) {
1557 ActiveModule->ConfigMacrosExhaustive = true;
1560 // If we don't have an identifier, we're done.
1561 if (!Tok.is(MMToken::Identifier))
1564 // Consume the first identifier.
1565 if (!ActiveModule->Parent) {
1566 ActiveModule->ConfigMacros.push_back(Tok.getString().str());
1571 // If there's a comma, consume it.
1572 if (!Tok.is(MMToken::Comma))
1576 // We expect to see a macro name here.
1577 if (!Tok.is(MMToken::Identifier)) {
1578 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_config_macro);
1582 // Consume the macro name.
1583 if (!ActiveModule->Parent) {
1584 ActiveModule->ConfigMacros.push_back(Tok.getString().str());
1590 /// \brief Format a module-id into a string.
1591 static std::string formatModuleId(const ModuleId &Id) {
1594 llvm::raw_string_ostream OS(result);
1596 for (unsigned I = 0, N = Id.size(); I != N; ++I) {
1606 /// \brief Parse a conflict declaration.
1608 /// module-declaration:
1609 /// 'conflict' module-id ',' string-literal
1610 void ModuleMapParser::parseConflict() {
1611 assert(Tok.is(MMToken::Conflict));
1612 SourceLocation ConflictLoc = consumeToken();
1613 Module::UnresolvedConflict Conflict;
1615 // Parse the module-id.
1616 if (parseModuleId(Conflict.Id))
1620 if (!Tok.is(MMToken::Comma)) {
1621 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_conflicts_comma)
1622 << SourceRange(ConflictLoc);
1627 // Parse the message.
1628 if (!Tok.is(MMToken::StringLiteral)) {
1629 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_conflicts_message)
1630 << formatModuleId(Conflict.Id);
1633 Conflict.Message = Tok.getString().str();
1636 // Add this unresolved conflict.
1637 ActiveModule->UnresolvedConflicts.push_back(Conflict);
1640 /// \brief Parse an inferred module declaration (wildcard modules).
1642 /// module-declaration:
1643 /// 'explicit'[opt] 'framework'[opt] 'module' * attributes[opt]
1644 /// { inferred-module-member* }
1646 /// inferred-module-member:
1648 /// 'exclude' identifier
1649 void ModuleMapParser::parseInferredModuleDecl(bool Framework, bool Explicit) {
1650 assert(Tok.is(MMToken::Star));
1651 SourceLocation StarLoc = consumeToken();
1652 bool Failed = false;
1654 // Inferred modules must be submodules.
1655 if (!ActiveModule && !Framework) {
1656 Diags.Report(StarLoc, diag::err_mmap_top_level_inferred_submodule);
1661 // Inferred modules must have umbrella directories.
1662 if (!Failed && !ActiveModule->getUmbrellaDir()) {
1663 Diags.Report(StarLoc, diag::err_mmap_inferred_no_umbrella);
1667 // Check for redefinition of an inferred module.
1668 if (!Failed && ActiveModule->InferSubmodules) {
1669 Diags.Report(StarLoc, diag::err_mmap_inferred_redef);
1670 if (ActiveModule->InferredSubmoduleLoc.isValid())
1671 Diags.Report(ActiveModule->InferredSubmoduleLoc,
1672 diag::note_mmap_prev_definition);
1676 // Check for the 'framework' keyword, which is not permitted here.
1678 Diags.Report(StarLoc, diag::err_mmap_inferred_framework_submodule);
1681 } else if (Explicit) {
1682 Diags.Report(StarLoc, diag::err_mmap_explicit_inferred_framework);
1686 // If there were any problems with this inferred submodule, skip its body.
1688 if (Tok.is(MMToken::LBrace)) {
1690 skipUntil(MMToken::RBrace);
1691 if (Tok.is(MMToken::RBrace))
1698 // Parse optional attributes.
1700 parseOptionalAttributes(Attrs);
1703 // Note that we have an inferred submodule.
1704 ActiveModule->InferSubmodules = true;
1705 ActiveModule->InferredSubmoduleLoc = StarLoc;
1706 ActiveModule->InferExplicitSubmodules = Explicit;
1708 // We'll be inferring framework modules for this directory.
1709 Map.InferredDirectories[Directory].InferModules = true;
1710 Map.InferredDirectories[Directory].InferSystemModules = Attrs.IsSystem;
1713 // Parse the opening brace.
1714 if (!Tok.is(MMToken::LBrace)) {
1715 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_lbrace_wildcard);
1719 SourceLocation LBraceLoc = consumeToken();
1721 // Parse the body of the inferred submodule.
1725 case MMToken::EndOfFile:
1726 case MMToken::RBrace:
1730 case MMToken::ExcludeKeyword: {
1732 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member)
1733 << (ActiveModule != 0);
1739 if (!Tok.is(MMToken::Identifier)) {
1740 Diags.Report(Tok.getLocation(), diag::err_mmap_missing_exclude_name);
1744 Map.InferredDirectories[Directory].ExcludedModules
1745 .push_back(Tok.getString());
1750 case MMToken::ExportKeyword:
1751 if (!ActiveModule) {
1752 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member)
1753 << (ActiveModule != 0);
1759 if (Tok.is(MMToken::Star))
1760 ActiveModule->InferExportWildcard = true;
1762 Diags.Report(Tok.getLocation(),
1763 diag::err_mmap_expected_export_wildcard);
1767 case MMToken::ExplicitKeyword:
1768 case MMToken::ModuleKeyword:
1769 case MMToken::HeaderKeyword:
1770 case MMToken::UmbrellaKeyword:
1772 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member)
1773 << (ActiveModule != 0);
1779 if (Tok.is(MMToken::RBrace))
1782 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
1783 Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
1788 /// \brief Parse optional attributes.
1791 /// attribute attributes
1797 /// \param Attrs Will be filled in with the parsed attributes.
1799 /// \returns true if an error occurred, false otherwise.
1800 bool ModuleMapParser::parseOptionalAttributes(Attributes &Attrs) {
1801 bool HadError = false;
1803 while (Tok.is(MMToken::LSquare)) {
1805 SourceLocation LSquareLoc = consumeToken();
1807 // Check whether we have an attribute name here.
1808 if (!Tok.is(MMToken::Identifier)) {
1809 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_attribute);
1810 skipUntil(MMToken::RSquare);
1811 if (Tok.is(MMToken::RSquare))
1816 // Decode the attribute name.
1817 AttributeKind Attribute
1818 = llvm::StringSwitch<AttributeKind>(Tok.getString())
1819 .Case("exhaustive", AT_exhaustive)
1820 .Case("system", AT_system)
1821 .Default(AT_unknown);
1822 switch (Attribute) {
1824 Diags.Report(Tok.getLocation(), diag::warn_mmap_unknown_attribute)
1829 Attrs.IsSystem = true;
1833 Attrs.IsExhaustive = true;
1839 if (!Tok.is(MMToken::RSquare)) {
1840 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rsquare);
1841 Diags.Report(LSquareLoc, diag::note_mmap_lsquare_match);
1842 skipUntil(MMToken::RSquare);
1846 if (Tok.is(MMToken::RSquare))
1853 /// \brief If there is a specific header search directory due the presence
1854 /// of an umbrella directory, retrieve that directory. Otherwise, returns null.
1855 const DirectoryEntry *ModuleMapParser::getOverriddenHeaderSearchDir() {
1856 for (Module *Mod = ActiveModule; Mod; Mod = Mod->Parent) {
1857 // If we have an umbrella directory, use that.
1858 if (Mod->hasUmbrellaDir())
1859 return Mod->getUmbrellaDir();
1861 // If we have a framework directory, stop looking.
1862 if (Mod->IsFramework)
1869 /// \brief Parse a module map file.
1871 /// module-map-file:
1872 /// module-declaration*
1873 bool ModuleMapParser::parseModuleMapFile() {
1876 case MMToken::EndOfFile:
1879 case MMToken::ExplicitKeyword:
1880 case MMToken::ModuleKeyword:
1881 case MMToken::FrameworkKeyword:
1885 case MMToken::Comma:
1886 case MMToken::ConfigMacros:
1887 case MMToken::Conflict:
1888 case MMToken::ExcludeKeyword:
1889 case MMToken::ExportKeyword:
1890 case MMToken::HeaderKeyword:
1891 case MMToken::Identifier:
1892 case MMToken::LBrace:
1893 case MMToken::LinkKeyword:
1894 case MMToken::LSquare:
1895 case MMToken::Period:
1896 case MMToken::RBrace:
1897 case MMToken::RSquare:
1898 case MMToken::RequiresKeyword:
1900 case MMToken::StringLiteral:
1901 case MMToken::UmbrellaKeyword:
1902 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module);
1910 bool ModuleMap::parseModuleMapFile(const FileEntry *File) {
1911 llvm::DenseMap<const FileEntry *, bool>::iterator Known
1912 = ParsedModuleMap.find(File);
1913 if (Known != ParsedModuleMap.end())
1914 return Known->second;
1916 assert(Target != 0 && "Missing target information");
1917 FileID ID = SourceMgr->createFileID(File, SourceLocation(), SrcMgr::C_User);
1918 const llvm::MemoryBuffer *Buffer = SourceMgr->getBuffer(ID);
1920 return ParsedModuleMap[File] = true;
1922 // Parse this module map file.
1923 Lexer L(ID, SourceMgr->getBuffer(ID), *SourceMgr, MMapLangOpts);
1924 Diags->getClient()->BeginSourceFile(MMapLangOpts);
1925 ModuleMapParser Parser(L, *SourceMgr, Target, *Diags, *this, File->getDir(),
1927 bool Result = Parser.parseModuleMapFile();
1928 Diags->getClient()->EndSourceFile();
1929 ParsedModuleMap[File] = Result;