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/Path.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(SourceManager &SourceMgr, DiagnosticConsumer &DC,
87 const LangOptions &LangOpts, const TargetInfo *Target,
88 HeaderSearch &HeaderInfo)
89 : SourceMgr(SourceMgr), LangOpts(LangOpts), Target(Target),
90 HeaderInfo(HeaderInfo), BuiltinIncludeDir(0), CompilingModule(0),
92 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(new DiagnosticIDs);
93 Diags = IntrusiveRefCntPtr<DiagnosticsEngine>(
94 new DiagnosticsEngine(DiagIDs, new DiagnosticOptions));
95 Diags->setClient(new ForwardingDiagnosticConsumer(DC),
96 /*ShouldOwnClient=*/true);
97 Diags->setSourceManager(&SourceMgr);
100 ModuleMap::~ModuleMap() {
101 for (llvm::StringMap<Module *>::iterator I = Modules.begin(),
102 IEnd = Modules.end();
104 delete I->getValue();
108 void ModuleMap::setTarget(const TargetInfo &Target) {
109 assert((!this->Target || this->Target == &Target) &&
110 "Improper target override");
111 this->Target = &Target;
114 /// \brief "Sanitize" a filename so that it can be used as an identifier.
115 static StringRef sanitizeFilenameAsIdentifier(StringRef Name,
116 SmallVectorImpl<char> &Buffer) {
120 if (!isValidIdentifier(Name)) {
121 // If we don't already have something with the form of an identifier,
122 // create a buffer with the sanitized name.
124 if (isDigit(Name[0]))
125 Buffer.push_back('_');
126 Buffer.reserve(Buffer.size() + Name.size());
127 for (unsigned I = 0, N = Name.size(); I != N; ++I) {
128 if (isIdentifierBody(Name[I]))
129 Buffer.push_back(Name[I]);
131 Buffer.push_back('_');
134 Name = StringRef(Buffer.data(), Buffer.size());
137 while (llvm::StringSwitch<bool>(Name)
138 #define KEYWORD(Keyword,Conditions) .Case(#Keyword, true)
139 #define ALIAS(Keyword, AliasOf, Conditions) .Case(Keyword, true)
140 #include "clang/Basic/TokenKinds.def"
142 if (Name.data() != Buffer.data())
143 Buffer.append(Name.begin(), Name.end());
144 Buffer.push_back('_');
145 Name = StringRef(Buffer.data(), Buffer.size());
151 /// \brief Determine whether the given file name is the name of a builtin
152 /// header, supplied by Clang to replace, override, or augment existing system
154 static bool isBuiltinHeader(StringRef FileName) {
155 return llvm::StringSwitch<bool>(FileName)
156 .Case("float.h", true)
157 .Case("iso646.h", true)
158 .Case("limits.h", true)
159 .Case("stdalign.h", true)
160 .Case("stdarg.h", true)
161 .Case("stdbool.h", true)
162 .Case("stddef.h", true)
163 .Case("stdint.h", true)
164 .Case("tgmath.h", true)
165 .Case("unwind.h", true)
169 ModuleMap::KnownHeader
170 ModuleMap::findModuleForHeader(const FileEntry *File,
171 Module *RequestingModule) {
172 HeadersMap::iterator Known = Headers.find(File);
173 if (Known != Headers.end()) {
174 ModuleMap::KnownHeader Result = KnownHeader();
176 // Iterate over all modules that 'File' is part of to find the best fit.
177 for (SmallVectorImpl<KnownHeader>::iterator I = Known->second.begin(),
178 E = Known->second.end();
180 // Cannot use a module if the header is excluded or unavailable in it.
181 if (I->getRole() == ModuleMap::ExcludedHeader ||
182 !I->getModule()->isAvailable())
185 // If 'File' is part of 'RequestingModule', 'RequestingModule' is the
186 // module we are looking for.
187 if (I->getModule() == RequestingModule)
190 // If uses need to be specified explicitly, we are only allowed to return
191 // modules that are explicitly used by the requesting module.
192 if (RequestingModule && LangOpts.ModulesDeclUse &&
193 std::find(RequestingModule->DirectUses.begin(),
194 RequestingModule->DirectUses.end(),
195 I->getModule()) == RequestingModule->DirectUses.end())
198 // If 'File' is a public header of this module, this is as good as we
200 if (I->getRole() == ModuleMap::NormalHeader)
206 // If we've found a builtin header within Clang's builtin include directory,
207 // load all of the module maps to see if it will get associated with a
208 // specific module (e.g., in /usr/include).
209 if (File->getDir() == BuiltinIncludeDir &&
210 isBuiltinHeader(llvm::sys::path::filename(File->getName()))) {
211 HeaderInfo.loadTopLevelSystemModules();
214 if (Headers.find(File) != Headers.end())
215 return findModuleForHeader(File, RequestingModule);
218 const DirectoryEntry *Dir = File->getDir();
219 SmallVector<const DirectoryEntry *, 2> SkippedDirs;
221 // Note: as an egregious but useful hack we use the real path here, because
222 // frameworks moving from top-level frameworks to embedded frameworks tend
223 // to be symlinked from the top-level location to the embedded location,
224 // and we need to resolve lookups as if we had found the embedded location.
225 StringRef DirName = SourceMgr.getFileManager().getCanonicalName(Dir);
227 // Keep walking up the directory hierarchy, looking for a directory with
228 // an umbrella header.
230 llvm::DenseMap<const DirectoryEntry *, Module *>::iterator KnownDir
231 = UmbrellaDirs.find(Dir);
232 if (KnownDir != UmbrellaDirs.end()) {
233 Module *Result = KnownDir->second;
235 // Search up the module stack until we find a module with an umbrella
237 Module *UmbrellaModule = Result;
238 while (!UmbrellaModule->getUmbrellaDir() && UmbrellaModule->Parent)
239 UmbrellaModule = UmbrellaModule->Parent;
241 if (UmbrellaModule->InferSubmodules) {
242 // Infer submodules for each of the directories we found between
243 // the directory of the umbrella header and the directory where
244 // the actual header is located.
245 bool Explicit = UmbrellaModule->InferExplicitSubmodules;
247 for (unsigned I = SkippedDirs.size(); I != 0; --I) {
248 // Find or create the module that corresponds to this directory name.
249 SmallString<32> NameBuf;
250 StringRef Name = sanitizeFilenameAsIdentifier(
251 llvm::sys::path::stem(SkippedDirs[I-1]->getName()),
253 Result = findOrCreateModule(Name, Result, /*IsFramework=*/false,
256 // Associate the module and the directory.
257 UmbrellaDirs[SkippedDirs[I-1]] = Result;
259 // If inferred submodules export everything they import, add a
260 // wildcard to the set of exports.
261 if (UmbrellaModule->InferExportWildcard && Result->Exports.empty())
262 Result->Exports.push_back(Module::ExportDecl(0, true));
265 // Infer a submodule with the same name as this header file.
266 SmallString<32> NameBuf;
267 StringRef Name = sanitizeFilenameAsIdentifier(
268 llvm::sys::path::stem(File->getName()), NameBuf);
269 Result = findOrCreateModule(Name, Result, /*IsFramework=*/false,
271 Result->addTopHeader(File);
273 // If inferred submodules export everything they import, add a
274 // wildcard to the set of exports.
275 if (UmbrellaModule->InferExportWildcard && Result->Exports.empty())
276 Result->Exports.push_back(Module::ExportDecl(0, true));
278 // Record each of the directories we stepped through as being part of
279 // the module we found, since the umbrella header covers them all.
280 for (unsigned I = 0, N = SkippedDirs.size(); I != N; ++I)
281 UmbrellaDirs[SkippedDirs[I]] = Result;
284 Headers[File].push_back(KnownHeader(Result, NormalHeader));
286 // If a header corresponds to an unavailable module, don't report
287 // that it maps to anything.
288 if (!Result->isAvailable())
289 return KnownHeader();
291 return Headers[File].back();
294 SkippedDirs.push_back(Dir);
296 // Retrieve our parent path.
297 DirName = llvm::sys::path::parent_path(DirName);
301 // Resolve the parent path to a directory entry.
302 Dir = SourceMgr.getFileManager().getDirectory(DirName);
305 return KnownHeader();
308 bool ModuleMap::isHeaderInUnavailableModule(const FileEntry *Header) const {
309 HeadersMap::const_iterator Known = Headers.find(Header);
310 if (Known != Headers.end()) {
311 for (SmallVectorImpl<KnownHeader>::const_iterator
312 I = Known->second.begin(),
313 E = Known->second.end();
315 if (I->isAvailable())
321 const DirectoryEntry *Dir = Header->getDir();
322 SmallVector<const DirectoryEntry *, 2> SkippedDirs;
323 StringRef DirName = Dir->getName();
325 // Keep walking up the directory hierarchy, looking for a directory with
326 // an umbrella header.
328 llvm::DenseMap<const DirectoryEntry *, Module *>::const_iterator KnownDir
329 = UmbrellaDirs.find(Dir);
330 if (KnownDir != UmbrellaDirs.end()) {
331 Module *Found = KnownDir->second;
332 if (!Found->isAvailable())
335 // Search up the module stack until we find a module with an umbrella
337 Module *UmbrellaModule = Found;
338 while (!UmbrellaModule->getUmbrellaDir() && UmbrellaModule->Parent)
339 UmbrellaModule = UmbrellaModule->Parent;
341 if (UmbrellaModule->InferSubmodules) {
342 for (unsigned I = SkippedDirs.size(); I != 0; --I) {
343 // Find or create the module that corresponds to this directory name.
344 SmallString<32> NameBuf;
345 StringRef Name = sanitizeFilenameAsIdentifier(
346 llvm::sys::path::stem(SkippedDirs[I-1]->getName()),
348 Found = lookupModuleQualified(Name, Found);
351 if (!Found->isAvailable())
355 // Infer a submodule with the same name as this header file.
356 SmallString<32> NameBuf;
357 StringRef Name = sanitizeFilenameAsIdentifier(
358 llvm::sys::path::stem(Header->getName()),
360 Found = lookupModuleQualified(Name, Found);
365 return !Found->isAvailable();
368 SkippedDirs.push_back(Dir);
370 // Retrieve our parent path.
371 DirName = llvm::sys::path::parent_path(DirName);
375 // Resolve the parent path to a directory entry.
376 Dir = SourceMgr.getFileManager().getDirectory(DirName);
382 Module *ModuleMap::findModule(StringRef Name) const {
383 llvm::StringMap<Module *>::const_iterator Known = Modules.find(Name);
384 if (Known != Modules.end())
385 return Known->getValue();
390 Module *ModuleMap::lookupModuleUnqualified(StringRef Name,
391 Module *Context) const {
392 for(; Context; Context = Context->Parent) {
393 if (Module *Sub = lookupModuleQualified(Name, Context))
397 return findModule(Name);
400 Module *ModuleMap::lookupModuleQualified(StringRef Name, Module *Context) const{
402 return findModule(Name);
404 return Context->findSubmodule(Name);
407 std::pair<Module *, bool>
408 ModuleMap::findOrCreateModule(StringRef Name, Module *Parent, bool IsFramework,
410 // Try to find an existing module with this name.
411 if (Module *Sub = lookupModuleQualified(Name, Parent))
412 return std::make_pair(Sub, false);
414 // Create a new module with this name.
415 Module *Result = new Module(Name, SourceLocation(), Parent, IsFramework,
417 if (LangOpts.CurrentModule == Name) {
418 SourceModule = Result;
419 SourceModuleName = Name;
422 Modules[Name] = Result;
423 if (!LangOpts.CurrentModule.empty() && !CompilingModule &&
424 Name == LangOpts.CurrentModule) {
425 CompilingModule = Result;
428 return std::make_pair(Result, true);
431 bool ModuleMap::canInferFrameworkModule(const DirectoryEntry *ParentDir,
432 StringRef Name, bool &IsSystem) const {
433 // Check whether we have already looked into the parent directory
435 llvm::DenseMap<const DirectoryEntry *, InferredDirectory>::const_iterator
436 inferred = InferredDirectories.find(ParentDir);
437 if (inferred == InferredDirectories.end())
440 if (!inferred->second.InferModules)
443 // We're allowed to infer for this directory, but make sure it's okay
444 // to infer this particular module.
445 bool canInfer = std::find(inferred->second.ExcludedModules.begin(),
446 inferred->second.ExcludedModules.end(),
447 Name) == inferred->second.ExcludedModules.end();
449 if (canInfer && inferred->second.InferSystemModules)
455 /// \brief For a framework module, infer the framework against which we
457 static void inferFrameworkLink(Module *Mod, const DirectoryEntry *FrameworkDir,
458 FileManager &FileMgr) {
459 assert(Mod->IsFramework && "Can only infer linking for framework modules");
460 assert(!Mod->isSubFramework() &&
461 "Can only infer linking for top-level frameworks");
463 SmallString<128> LibName;
464 LibName += FrameworkDir->getName();
465 llvm::sys::path::append(LibName, Mod->Name);
466 if (FileMgr.getFile(LibName)) {
467 Mod->LinkLibraries.push_back(Module::LinkLibrary(Mod->Name,
468 /*IsFramework=*/true));
473 ModuleMap::inferFrameworkModule(StringRef ModuleName,
474 const DirectoryEntry *FrameworkDir,
477 // Check whether we've already found this module.
478 if (Module *Mod = lookupModuleQualified(ModuleName, Parent))
481 FileManager &FileMgr = SourceMgr.getFileManager();
483 // If the framework has a parent path from which we're allowed to infer
484 // a framework module, do so.
486 // Determine whether we're allowed to infer a module map.
488 // Note: as an egregious but useful hack we use the real path here, because
489 // we might be looking at an embedded framework that symlinks out to a
490 // top-level framework, and we need to infer as if we were naming the
491 // top-level framework.
492 StringRef FrameworkDirName
493 = SourceMgr.getFileManager().getCanonicalName(FrameworkDir);
495 bool canInfer = false;
496 if (llvm::sys::path::has_parent_path(FrameworkDirName)) {
497 // Figure out the parent path.
498 StringRef Parent = llvm::sys::path::parent_path(FrameworkDirName);
499 if (const DirectoryEntry *ParentDir = FileMgr.getDirectory(Parent)) {
500 // Check whether we have already looked into the parent directory
502 llvm::DenseMap<const DirectoryEntry *, InferredDirectory>::const_iterator
503 inferred = InferredDirectories.find(ParentDir);
504 if (inferred == InferredDirectories.end()) {
505 // We haven't looked here before. Load a module map, if there is
507 SmallString<128> ModMapPath = Parent;
508 llvm::sys::path::append(ModMapPath, "module.map");
509 if (const FileEntry *ModMapFile = FileMgr.getFile(ModMapPath)) {
510 parseModuleMapFile(ModMapFile, IsSystem);
511 inferred = InferredDirectories.find(ParentDir);
514 if (inferred == InferredDirectories.end())
515 inferred = InferredDirectories.insert(
516 std::make_pair(ParentDir, InferredDirectory())).first;
519 if (inferred->second.InferModules) {
520 // We're allowed to infer for this directory, but make sure it's okay
521 // to infer this particular module.
522 StringRef Name = llvm::sys::path::stem(FrameworkDirName);
523 canInfer = std::find(inferred->second.ExcludedModules.begin(),
524 inferred->second.ExcludedModules.end(),
525 Name) == inferred->second.ExcludedModules.end();
527 if (inferred->second.InferSystemModules)
533 // If we're not allowed to infer a framework module, don't.
539 // Look for an umbrella header.
540 SmallString<128> UmbrellaName = StringRef(FrameworkDir->getName());
541 llvm::sys::path::append(UmbrellaName, "Headers", ModuleName + ".h");
542 const FileEntry *UmbrellaHeader = FileMgr.getFile(UmbrellaName);
544 // FIXME: If there's no umbrella header, we could probably scan the
545 // framework to load *everything*. But, it's not clear that this is a good
550 Module *Result = new Module(ModuleName, SourceLocation(), Parent,
551 /*IsFramework=*/true, /*IsExplicit=*/false);
552 if (LangOpts.CurrentModule == ModuleName) {
553 SourceModule = Result;
554 SourceModuleName = ModuleName;
557 Result->IsSystem = IsSystem;
560 Modules[ModuleName] = Result;
562 // umbrella header "umbrella-header-name"
563 Result->Umbrella = UmbrellaHeader;
564 Headers[UmbrellaHeader].push_back(KnownHeader(Result, NormalHeader));
565 UmbrellaDirs[UmbrellaHeader->getDir()] = Result;
568 Result->Exports.push_back(Module::ExportDecl(0, true));
570 // module * { export * }
571 Result->InferSubmodules = true;
572 Result->InferExportWildcard = true;
574 // Look for subframeworks.
576 SmallString<128> SubframeworksDirName
577 = StringRef(FrameworkDir->getName());
578 llvm::sys::path::append(SubframeworksDirName, "Frameworks");
579 llvm::sys::path::native(SubframeworksDirName);
580 for (llvm::sys::fs::directory_iterator
581 Dir(SubframeworksDirName.str(), EC), DirEnd;
582 Dir != DirEnd && !EC; Dir.increment(EC)) {
583 if (!StringRef(Dir->path()).endswith(".framework"))
586 if (const DirectoryEntry *SubframeworkDir
587 = FileMgr.getDirectory(Dir->path())) {
588 // Note: as an egregious but useful hack, we use the real path here and
589 // check whether it is actually a subdirectory of the parent directory.
590 // This will not be the case if the 'subframework' is actually a symlink
591 // out to a top-level framework.
592 StringRef SubframeworkDirName = FileMgr.getCanonicalName(SubframeworkDir);
593 bool FoundParent = false;
595 // Get the parent directory name.
597 = llvm::sys::path::parent_path(SubframeworkDirName);
598 if (SubframeworkDirName.empty())
601 if (FileMgr.getDirectory(SubframeworkDirName) == FrameworkDir) {
610 // FIXME: Do we want to warn about subframeworks without umbrella headers?
611 SmallString<32> NameBuf;
612 inferFrameworkModule(sanitizeFilenameAsIdentifier(
613 llvm::sys::path::stem(Dir->path()), NameBuf),
614 SubframeworkDir, IsSystem, Result);
618 // If the module is a top-level framework, automatically link against the
620 if (!Result->isSubFramework()) {
621 inferFrameworkLink(Result, FrameworkDir, FileMgr);
627 void ModuleMap::setUmbrellaHeader(Module *Mod, const FileEntry *UmbrellaHeader){
628 Headers[UmbrellaHeader].push_back(KnownHeader(Mod, NormalHeader));
629 Mod->Umbrella = UmbrellaHeader;
630 UmbrellaDirs[UmbrellaHeader->getDir()] = Mod;
633 void ModuleMap::setUmbrellaDir(Module *Mod, const DirectoryEntry *UmbrellaDir) {
634 Mod->Umbrella = UmbrellaDir;
635 UmbrellaDirs[UmbrellaDir] = Mod;
638 void ModuleMap::addHeader(Module *Mod, const FileEntry *Header,
639 ModuleHeaderRole Role) {
640 if (Role == ExcludedHeader) {
641 Mod->ExcludedHeaders.push_back(Header);
643 if (Role == PrivateHeader)
644 Mod->PrivateHeaders.push_back(Header);
646 Mod->NormalHeaders.push_back(Header);
647 bool isCompilingModuleHeader = Mod->getTopLevelModule() == CompilingModule;
648 HeaderInfo.MarkFileModuleHeader(Header, Role, isCompilingModuleHeader);
650 Headers[Header].push_back(KnownHeader(Mod, Role));
654 ModuleMap::getContainingModuleMapFile(Module *Module) const {
655 if (Module->DefinitionLoc.isInvalid())
658 return SourceMgr.getFileEntryForID(
659 SourceMgr.getFileID(Module->DefinitionLoc));
662 void ModuleMap::dump() {
663 llvm::errs() << "Modules:";
664 for (llvm::StringMap<Module *>::iterator M = Modules.begin(),
665 MEnd = Modules.end();
667 M->getValue()->print(llvm::errs(), 2);
669 llvm::errs() << "Headers:";
670 for (HeadersMap::iterator H = Headers.begin(), HEnd = Headers.end();
672 llvm::errs() << " \"" << H->first->getName() << "\" -> ";
673 for (SmallVectorImpl<KnownHeader>::const_iterator I = H->second.begin(),
676 if (I != H->second.begin())
678 llvm::errs() << I->getModule()->getFullModuleName();
680 llvm::errs() << "\n";
684 bool ModuleMap::resolveExports(Module *Mod, bool Complain) {
685 bool HadError = false;
686 for (unsigned I = 0, N = Mod->UnresolvedExports.size(); I != N; ++I) {
687 Module::ExportDecl Export = resolveExport(Mod, Mod->UnresolvedExports[I],
689 if (Export.getPointer() || Export.getInt())
690 Mod->Exports.push_back(Export);
694 Mod->UnresolvedExports.clear();
698 bool ModuleMap::resolveUses(Module *Mod, bool Complain) {
699 bool HadError = false;
700 for (unsigned I = 0, N = Mod->UnresolvedDirectUses.size(); I != N; ++I) {
702 resolveModuleId(Mod->UnresolvedDirectUses[I], Mod, Complain);
704 Mod->DirectUses.push_back(DirectUse);
708 Mod->UnresolvedDirectUses.clear();
712 bool ModuleMap::resolveConflicts(Module *Mod, bool Complain) {
713 bool HadError = false;
714 for (unsigned I = 0, N = Mod->UnresolvedConflicts.size(); I != N; ++I) {
715 Module *OtherMod = resolveModuleId(Mod->UnresolvedConflicts[I].Id,
722 Module::Conflict Conflict;
723 Conflict.Other = OtherMod;
724 Conflict.Message = Mod->UnresolvedConflicts[I].Message;
725 Mod->Conflicts.push_back(Conflict);
727 Mod->UnresolvedConflicts.clear();
731 Module *ModuleMap::inferModuleFromLocation(FullSourceLoc Loc) {
735 // Use the expansion location to determine which module we're in.
736 FullSourceLoc ExpansionLoc = Loc.getExpansionLoc();
737 if (!ExpansionLoc.isFileID())
741 const SourceManager &SrcMgr = Loc.getManager();
742 FileID ExpansionFileID = ExpansionLoc.getFileID();
744 while (const FileEntry *ExpansionFile
745 = SrcMgr.getFileEntryForID(ExpansionFileID)) {
746 // Find the module that owns this header (if any).
747 if (Module *Mod = findModuleForHeader(ExpansionFile).getModule())
750 // No module owns this header, so look up the inclusion chain to see if
751 // any included header has an associated module.
752 SourceLocation IncludeLoc = SrcMgr.getIncludeLoc(ExpansionFileID);
753 if (IncludeLoc.isInvalid())
756 ExpansionFileID = SrcMgr.getFileID(IncludeLoc);
762 //----------------------------------------------------------------------------//
763 // Module map file parser
764 //----------------------------------------------------------------------------//
767 /// \brief A token in a module map file.
798 unsigned StringLength;
799 const char *StringData;
808 bool is(TokenKind K) const { return Kind == K; }
810 SourceLocation getLocation() const {
811 return SourceLocation::getFromRawEncoding(Location);
814 StringRef getString() const {
815 return StringRef(StringData, StringLength);
819 /// \brief The set of attributes that can be attached to a module.
821 Attributes() : IsSystem(), IsExhaustive() { }
823 /// \brief Whether this is a system module.
824 unsigned IsSystem : 1;
826 /// \brief Whether this is an exhaustive set of configuration macros.
827 unsigned IsExhaustive : 1;
831 class ModuleMapParser {
833 SourceManager &SourceMgr;
835 /// \brief Default target information, used only for string literal
837 const TargetInfo *Target;
839 DiagnosticsEngine &Diags;
842 /// \brief The directory that this module map resides in.
843 const DirectoryEntry *Directory;
845 /// \brief The directory containing Clang-supplied headers.
846 const DirectoryEntry *BuiltinIncludeDir;
848 /// \brief Whether this module map is in a system header directory.
851 /// \brief Whether an error occurred.
854 /// \brief Stores string data for the various string literals referenced
856 llvm::BumpPtrAllocator StringData;
858 /// \brief The current token.
861 /// \brief The active module.
862 Module *ActiveModule;
864 /// \brief Consume the current token and return its location.
865 SourceLocation consumeToken();
867 /// \brief Skip tokens until we reach the a token with the given kind
868 /// (or the end of the file).
869 void skipUntil(MMToken::TokenKind K);
871 typedef SmallVector<std::pair<std::string, SourceLocation>, 2> ModuleId;
872 bool parseModuleId(ModuleId &Id);
873 void parseModuleDecl();
874 void parseExternModuleDecl();
875 void parseRequiresDecl();
876 void parseHeaderDecl(clang::MMToken::TokenKind,
877 SourceLocation LeadingLoc);
878 void parseUmbrellaDirDecl(SourceLocation UmbrellaLoc);
879 void parseExportDecl();
881 void parseLinkDecl();
882 void parseConfigMacros();
883 void parseConflict();
884 void parseInferredModuleDecl(bool Framework, bool Explicit);
885 bool parseOptionalAttributes(Attributes &Attrs);
887 const DirectoryEntry *getOverriddenHeaderSearchDir();
890 explicit ModuleMapParser(Lexer &L, SourceManager &SourceMgr,
891 const TargetInfo *Target,
892 DiagnosticsEngine &Diags,
894 const DirectoryEntry *Directory,
895 const DirectoryEntry *BuiltinIncludeDir,
897 : L(L), SourceMgr(SourceMgr), Target(Target), Diags(Diags), Map(Map),
898 Directory(Directory), BuiltinIncludeDir(BuiltinIncludeDir),
899 IsSystem(IsSystem), HadError(false), ActiveModule(0)
905 bool parseModuleMapFile();
909 SourceLocation ModuleMapParser::consumeToken() {
911 SourceLocation Result = Tok.getLocation();
915 L.LexFromRawLexer(LToken);
916 Tok.Location = LToken.getLocation().getRawEncoding();
917 switch (LToken.getKind()) {
918 case tok::raw_identifier:
919 Tok.StringData = LToken.getRawIdentifierData();
920 Tok.StringLength = LToken.getLength();
921 Tok.Kind = llvm::StringSwitch<MMToken::TokenKind>(Tok.getString())
922 .Case("config_macros", MMToken::ConfigMacros)
923 .Case("conflict", MMToken::Conflict)
924 .Case("exclude", MMToken::ExcludeKeyword)
925 .Case("explicit", MMToken::ExplicitKeyword)
926 .Case("export", MMToken::ExportKeyword)
927 .Case("extern", MMToken::ExternKeyword)
928 .Case("framework", MMToken::FrameworkKeyword)
929 .Case("header", MMToken::HeaderKeyword)
930 .Case("link", MMToken::LinkKeyword)
931 .Case("module", MMToken::ModuleKeyword)
932 .Case("private", MMToken::PrivateKeyword)
933 .Case("requires", MMToken::RequiresKeyword)
934 .Case("umbrella", MMToken::UmbrellaKeyword)
935 .Case("use", MMToken::UseKeyword)
936 .Default(MMToken::Identifier);
940 Tok.Kind = MMToken::Comma;
944 Tok.Kind = MMToken::EndOfFile;
948 Tok.Kind = MMToken::LBrace;
952 Tok.Kind = MMToken::LSquare;
956 Tok.Kind = MMToken::Period;
960 Tok.Kind = MMToken::RBrace;
964 Tok.Kind = MMToken::RSquare;
968 Tok.Kind = MMToken::Star;
972 Tok.Kind = MMToken::Exclaim;
975 case tok::string_literal: {
976 if (LToken.hasUDSuffix()) {
977 Diags.Report(LToken.getLocation(), diag::err_invalid_string_udl);
982 // Parse the string literal.
983 LangOptions LangOpts;
984 StringLiteralParser StringLiteral(<oken, 1, SourceMgr, LangOpts, *Target);
985 if (StringLiteral.hadError)
988 // Copy the string literal into our string data allocator.
989 unsigned Length = StringLiteral.GetStringLength();
990 char *Saved = StringData.Allocate<char>(Length + 1);
991 memcpy(Saved, StringLiteral.GetString().data(), Length);
995 Tok.Kind = MMToken::StringLiteral;
996 Tok.StringData = Saved;
997 Tok.StringLength = Length;
1005 Diags.Report(LToken.getLocation(), diag::err_mmap_unknown_token);
1013 void ModuleMapParser::skipUntil(MMToken::TokenKind K) {
1014 unsigned braceDepth = 0;
1015 unsigned squareDepth = 0;
1018 case MMToken::EndOfFile:
1021 case MMToken::LBrace:
1022 if (Tok.is(K) && braceDepth == 0 && squareDepth == 0)
1028 case MMToken::LSquare:
1029 if (Tok.is(K) && braceDepth == 0 && squareDepth == 0)
1035 case MMToken::RBrace:
1042 case MMToken::RSquare:
1043 if (squareDepth > 0)
1050 if (braceDepth == 0 && squareDepth == 0 && Tok.is(K))
1059 /// \brief Parse a module-id.
1063 /// identifier '.' module-id
1065 /// \returns true if an error occurred, false otherwise.
1066 bool ModuleMapParser::parseModuleId(ModuleId &Id) {
1069 if (Tok.is(MMToken::Identifier)) {
1070 Id.push_back(std::make_pair(Tok.getString(), Tok.getLocation()));
1073 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module_name);
1077 if (!Tok.is(MMToken::Period))
1087 /// \brief Enumerates the known attributes.
1088 enum AttributeKind {
1089 /// \brief An unknown attribute.
1091 /// \brief The 'system' attribute.
1093 /// \brief The 'exhaustive' attribute.
1098 /// \brief Parse a module declaration.
1100 /// module-declaration:
1101 /// 'extern' 'module' module-id string-literal
1102 /// 'explicit'[opt] 'framework'[opt] 'module' module-id attributes[opt]
1103 /// { module-member* }
1106 /// requires-declaration
1107 /// header-declaration
1108 /// submodule-declaration
1109 /// export-declaration
1110 /// link-declaration
1112 /// submodule-declaration:
1113 /// module-declaration
1114 /// inferred-submodule-declaration
1115 void ModuleMapParser::parseModuleDecl() {
1116 assert(Tok.is(MMToken::ExplicitKeyword) || Tok.is(MMToken::ModuleKeyword) ||
1117 Tok.is(MMToken::FrameworkKeyword) || Tok.is(MMToken::ExternKeyword));
1118 if (Tok.is(MMToken::ExternKeyword)) {
1119 parseExternModuleDecl();
1123 // Parse 'explicit' or 'framework' keyword, if present.
1124 SourceLocation ExplicitLoc;
1125 bool Explicit = false;
1126 bool Framework = false;
1128 // Parse 'explicit' keyword, if present.
1129 if (Tok.is(MMToken::ExplicitKeyword)) {
1130 ExplicitLoc = consumeToken();
1134 // Parse 'framework' keyword, if present.
1135 if (Tok.is(MMToken::FrameworkKeyword)) {
1140 // Parse 'module' keyword.
1141 if (!Tok.is(MMToken::ModuleKeyword)) {
1142 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module);
1147 consumeToken(); // 'module' keyword
1149 // If we have a wildcard for the module name, this is an inferred submodule.
1151 if (Tok.is(MMToken::Star))
1152 return parseInferredModuleDecl(Framework, Explicit);
1154 // Parse the module name.
1156 if (parseModuleId(Id)) {
1162 if (Id.size() > 1) {
1163 Diags.Report(Id.front().second, diag::err_mmap_nested_submodule_id)
1164 << SourceRange(Id.front().second, Id.back().second);
1169 } else if (Id.size() == 1 && Explicit) {
1170 // Top-level modules can't be explicit.
1171 Diags.Report(ExplicitLoc, diag::err_mmap_explicit_top_level);
1173 ExplicitLoc = SourceLocation();
1177 Module *PreviousActiveModule = ActiveModule;
1178 if (Id.size() > 1) {
1179 // This module map defines a submodule. Go find the module of which it
1182 for (unsigned I = 0, N = Id.size() - 1; I != N; ++I) {
1183 if (Module *Next = Map.lookupModuleQualified(Id[I].first, ActiveModule)) {
1184 ActiveModule = Next;
1189 Diags.Report(Id[I].second, diag::err_mmap_missing_module_qualified)
1190 << Id[I].first << ActiveModule->getTopLevelModule();
1192 Diags.Report(Id[I].second, diag::err_mmap_expected_module_name);
1199 StringRef ModuleName = Id.back().first;
1200 SourceLocation ModuleNameLoc = Id.back().second;
1202 // Parse the optional attribute list.
1204 parseOptionalAttributes(Attrs);
1206 // Parse the opening brace.
1207 if (!Tok.is(MMToken::LBrace)) {
1208 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_lbrace)
1213 SourceLocation LBraceLoc = consumeToken();
1215 // Determine whether this (sub)module has already been defined.
1216 if (Module *Existing = Map.lookupModuleQualified(ModuleName, ActiveModule)) {
1217 if (Existing->DefinitionLoc.isInvalid() && !ActiveModule) {
1218 // Skip the module definition.
1219 skipUntil(MMToken::RBrace);
1220 if (Tok.is(MMToken::RBrace))
1223 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
1224 Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
1230 Diags.Report(ModuleNameLoc, diag::err_mmap_module_redefinition)
1232 Diags.Report(Existing->DefinitionLoc, diag::note_mmap_prev_definition);
1234 // Skip the module definition.
1235 skipUntil(MMToken::RBrace);
1236 if (Tok.is(MMToken::RBrace))
1243 // Start defining this module.
1244 ActiveModule = Map.findOrCreateModule(ModuleName, ActiveModule, Framework,
1246 ActiveModule->DefinitionLoc = ModuleNameLoc;
1247 if (Attrs.IsSystem || IsSystem)
1248 ActiveModule->IsSystem = true;
1253 case MMToken::EndOfFile:
1254 case MMToken::RBrace:
1258 case MMToken::ConfigMacros:
1259 parseConfigMacros();
1262 case MMToken::Conflict:
1266 case MMToken::ExplicitKeyword:
1267 case MMToken::ExternKeyword:
1268 case MMToken::FrameworkKeyword:
1269 case MMToken::ModuleKeyword:
1273 case MMToken::ExportKeyword:
1277 case MMToken::UseKeyword:
1281 case MMToken::RequiresKeyword:
1282 parseRequiresDecl();
1285 case MMToken::UmbrellaKeyword: {
1286 SourceLocation UmbrellaLoc = consumeToken();
1287 if (Tok.is(MMToken::HeaderKeyword))
1288 parseHeaderDecl(MMToken::UmbrellaKeyword, UmbrellaLoc);
1290 parseUmbrellaDirDecl(UmbrellaLoc);
1294 case MMToken::ExcludeKeyword: {
1295 SourceLocation ExcludeLoc = consumeToken();
1296 if (Tok.is(MMToken::HeaderKeyword)) {
1297 parseHeaderDecl(MMToken::ExcludeKeyword, ExcludeLoc);
1299 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
1305 case MMToken::PrivateKeyword: {
1306 SourceLocation PrivateLoc = consumeToken();
1307 if (Tok.is(MMToken::HeaderKeyword)) {
1308 parseHeaderDecl(MMToken::PrivateKeyword, PrivateLoc);
1310 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
1316 case MMToken::HeaderKeyword:
1317 parseHeaderDecl(MMToken::HeaderKeyword, SourceLocation());
1320 case MMToken::LinkKeyword:
1325 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_member);
1331 if (Tok.is(MMToken::RBrace))
1334 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
1335 Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
1339 // If the active module is a top-level framework, and there are no link
1340 // libraries, automatically link against the framework.
1341 if (ActiveModule->IsFramework && !ActiveModule->isSubFramework() &&
1342 ActiveModule->LinkLibraries.empty()) {
1343 inferFrameworkLink(ActiveModule, Directory, SourceMgr.getFileManager());
1346 // We're done parsing this module. Pop back to the previous module.
1347 ActiveModule = PreviousActiveModule;
1350 /// \brief Parse an extern module declaration.
1352 /// extern module-declaration:
1353 /// 'extern' 'module' module-id string-literal
1354 void ModuleMapParser::parseExternModuleDecl() {
1355 assert(Tok.is(MMToken::ExternKeyword));
1356 consumeToken(); // 'extern' keyword
1358 // Parse 'module' keyword.
1359 if (!Tok.is(MMToken::ModuleKeyword)) {
1360 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module);
1365 consumeToken(); // 'module' keyword
1367 // Parse the module name.
1369 if (parseModuleId(Id)) {
1374 // Parse the referenced module map file name.
1375 if (!Tok.is(MMToken::StringLiteral)) {
1376 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_mmap_file);
1380 std::string FileName = Tok.getString();
1381 consumeToken(); // filename
1383 StringRef FileNameRef = FileName;
1384 SmallString<128> ModuleMapFileName;
1385 if (llvm::sys::path::is_relative(FileNameRef)) {
1386 ModuleMapFileName += Directory->getName();
1387 llvm::sys::path::append(ModuleMapFileName, FileName);
1388 FileNameRef = ModuleMapFileName.str();
1390 if (const FileEntry *File = SourceMgr.getFileManager().getFile(FileNameRef))
1391 Map.parseModuleMapFile(File, /*IsSystem=*/false);
1394 /// \brief Parse a requires declaration.
1396 /// requires-declaration:
1397 /// 'requires' feature-list
1400 /// feature ',' feature-list
1404 /// '!'[opt] identifier
1405 void ModuleMapParser::parseRequiresDecl() {
1406 assert(Tok.is(MMToken::RequiresKeyword));
1408 // Parse 'requires' keyword.
1411 // Parse the feature-list.
1413 bool RequiredState = true;
1414 if (Tok.is(MMToken::Exclaim)) {
1415 RequiredState = false;
1419 if (!Tok.is(MMToken::Identifier)) {
1420 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_feature);
1425 // Consume the feature name.
1426 std::string Feature = Tok.getString();
1429 // Add this feature.
1430 ActiveModule->addRequirement(Feature, RequiredState,
1431 Map.LangOpts, *Map.Target);
1433 if (!Tok.is(MMToken::Comma))
1436 // Consume the comma.
1441 /// \brief Append to \p Paths the set of paths needed to get to the
1442 /// subframework in which the given module lives.
1443 static void appendSubframeworkPaths(Module *Mod,
1444 SmallVectorImpl<char> &Path) {
1445 // Collect the framework names from the given module to the top-level module.
1446 SmallVector<StringRef, 2> Paths;
1447 for (; Mod; Mod = Mod->Parent) {
1448 if (Mod->IsFramework)
1449 Paths.push_back(Mod->Name);
1455 // Add Frameworks/Name.framework for each subframework.
1456 for (unsigned I = Paths.size() - 1; I != 0; --I)
1457 llvm::sys::path::append(Path, "Frameworks", Paths[I-1] + ".framework");
1460 /// \brief Parse a header declaration.
1462 /// header-declaration:
1463 /// 'umbrella'[opt] 'header' string-literal
1464 /// 'exclude'[opt] 'header' string-literal
1465 void ModuleMapParser::parseHeaderDecl(MMToken::TokenKind LeadingToken,
1466 SourceLocation LeadingLoc) {
1467 assert(Tok.is(MMToken::HeaderKeyword));
1470 // Parse the header name.
1471 if (!Tok.is(MMToken::StringLiteral)) {
1472 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
1477 std::string FileName = Tok.getString();
1478 SourceLocation FileNameLoc = consumeToken();
1480 // Check whether we already have an umbrella.
1481 if (LeadingToken == MMToken::UmbrellaKeyword && ActiveModule->Umbrella) {
1482 Diags.Report(FileNameLoc, diag::err_mmap_umbrella_clash)
1483 << ActiveModule->getFullModuleName();
1488 // Look for this file.
1489 const FileEntry *File = 0;
1490 const FileEntry *BuiltinFile = 0;
1491 SmallString<128> PathName;
1492 if (llvm::sys::path::is_absolute(FileName)) {
1493 PathName = FileName;
1494 File = SourceMgr.getFileManager().getFile(PathName);
1495 } else if (const DirectoryEntry *Dir = getOverriddenHeaderSearchDir()) {
1496 PathName = Dir->getName();
1497 llvm::sys::path::append(PathName, FileName);
1498 File = SourceMgr.getFileManager().getFile(PathName);
1500 // Search for the header file within the search directory.
1501 PathName = Directory->getName();
1502 unsigned PathLength = PathName.size();
1504 if (ActiveModule->isPartOfFramework()) {
1505 appendSubframeworkPaths(ActiveModule, PathName);
1507 // Check whether this file is in the public headers.
1508 llvm::sys::path::append(PathName, "Headers", FileName);
1509 File = SourceMgr.getFileManager().getFile(PathName);
1512 // Check whether this file is in the private headers.
1513 PathName.resize(PathLength);
1514 llvm::sys::path::append(PathName, "PrivateHeaders", FileName);
1515 File = SourceMgr.getFileManager().getFile(PathName);
1518 // Lookup for normal headers.
1519 llvm::sys::path::append(PathName, FileName);
1520 File = SourceMgr.getFileManager().getFile(PathName);
1522 // If this is a system module with a top-level header, this header
1523 // may have a counterpart (or replacement) in the set of headers
1524 // supplied by Clang. Find that builtin header.
1525 if (ActiveModule->IsSystem && LeadingToken != MMToken::UmbrellaKeyword &&
1526 BuiltinIncludeDir && BuiltinIncludeDir != Directory &&
1527 isBuiltinHeader(FileName)) {
1528 SmallString<128> BuiltinPathName(BuiltinIncludeDir->getName());
1529 llvm::sys::path::append(BuiltinPathName, FileName);
1530 BuiltinFile = SourceMgr.getFileManager().getFile(BuiltinPathName);
1532 // If Clang supplies this header but the underlying system does not,
1533 // just silently swap in our builtin version. Otherwise, we'll end
1534 // up adding both (later).
1535 if (!File && BuiltinFile) {
1543 // FIXME: We shouldn't be eagerly stat'ing every file named in a module map.
1544 // Come up with a lazy way to do this.
1546 if (LeadingToken == MMToken::UmbrellaKeyword) {
1547 const DirectoryEntry *UmbrellaDir = File->getDir();
1548 if (Module *UmbrellaModule = Map.UmbrellaDirs[UmbrellaDir]) {
1549 Diags.Report(LeadingLoc, diag::err_mmap_umbrella_clash)
1550 << UmbrellaModule->getFullModuleName();
1553 // Record this umbrella header.
1554 Map.setUmbrellaHeader(ActiveModule, File);
1557 // Record this header.
1558 ModuleMap::ModuleHeaderRole Role = ModuleMap::NormalHeader;
1559 if (LeadingToken == MMToken::ExcludeKeyword)
1560 Role = ModuleMap::ExcludedHeader;
1561 else if (LeadingToken == MMToken::PrivateKeyword)
1562 Role = ModuleMap::PrivateHeader;
1564 assert(LeadingToken == MMToken::HeaderKeyword);
1566 Map.addHeader(ActiveModule, File, Role);
1568 // If there is a builtin counterpart to this file, add it now.
1570 Map.addHeader(ActiveModule, BuiltinFile, Role);
1572 } else if (LeadingToken != MMToken::ExcludeKeyword) {
1573 // Ignore excluded header files. They're optional anyway.
1575 Diags.Report(FileNameLoc, diag::err_mmap_header_not_found)
1576 << (LeadingToken == MMToken::UmbrellaKeyword) << FileName;
1581 /// \brief Parse an umbrella directory declaration.
1583 /// umbrella-dir-declaration:
1584 /// umbrella string-literal
1585 void ModuleMapParser::parseUmbrellaDirDecl(SourceLocation UmbrellaLoc) {
1586 // Parse the directory name.
1587 if (!Tok.is(MMToken::StringLiteral)) {
1588 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
1594 std::string DirName = Tok.getString();
1595 SourceLocation DirNameLoc = consumeToken();
1597 // Check whether we already have an umbrella.
1598 if (ActiveModule->Umbrella) {
1599 Diags.Report(DirNameLoc, diag::err_mmap_umbrella_clash)
1600 << ActiveModule->getFullModuleName();
1605 // Look for this file.
1606 const DirectoryEntry *Dir = 0;
1607 if (llvm::sys::path::is_absolute(DirName))
1608 Dir = SourceMgr.getFileManager().getDirectory(DirName);
1610 SmallString<128> PathName;
1611 PathName = Directory->getName();
1612 llvm::sys::path::append(PathName, DirName);
1613 Dir = SourceMgr.getFileManager().getDirectory(PathName);
1617 Diags.Report(DirNameLoc, diag::err_mmap_umbrella_dir_not_found)
1623 if (Module *OwningModule = Map.UmbrellaDirs[Dir]) {
1624 Diags.Report(UmbrellaLoc, diag::err_mmap_umbrella_clash)
1625 << OwningModule->getFullModuleName();
1630 // Record this umbrella directory.
1631 Map.setUmbrellaDir(ActiveModule, Dir);
1634 /// \brief Parse a module export declaration.
1636 /// export-declaration:
1637 /// 'export' wildcard-module-id
1639 /// wildcard-module-id:
1642 /// identifier '.' wildcard-module-id
1643 void ModuleMapParser::parseExportDecl() {
1644 assert(Tok.is(MMToken::ExportKeyword));
1645 SourceLocation ExportLoc = consumeToken();
1647 // Parse the module-id with an optional wildcard at the end.
1648 ModuleId ParsedModuleId;
1649 bool Wildcard = false;
1651 if (Tok.is(MMToken::Identifier)) {
1652 ParsedModuleId.push_back(std::make_pair(Tok.getString(),
1653 Tok.getLocation()));
1656 if (Tok.is(MMToken::Period)) {
1664 if(Tok.is(MMToken::Star)) {
1670 Diags.Report(Tok.getLocation(), diag::err_mmap_module_id);
1675 Module::UnresolvedExportDecl Unresolved = {
1676 ExportLoc, ParsedModuleId, Wildcard
1678 ActiveModule->UnresolvedExports.push_back(Unresolved);
1681 /// \brief Parse a module uses declaration.
1683 /// uses-declaration:
1684 /// 'uses' wildcard-module-id
1685 void ModuleMapParser::parseUseDecl() {
1686 assert(Tok.is(MMToken::UseKeyword));
1688 // Parse the module-id.
1689 ModuleId ParsedModuleId;
1692 if (Tok.is(MMToken::Identifier)) {
1693 ParsedModuleId.push_back(
1694 std::make_pair(Tok.getString(), Tok.getLocation()));
1697 if (Tok.is(MMToken::Period)) {
1705 Diags.Report(Tok.getLocation(), diag::err_mmap_module_id);
1710 ActiveModule->UnresolvedDirectUses.push_back(ParsedModuleId);
1713 /// \brief Parse a link declaration.
1715 /// module-declaration:
1716 /// 'link' 'framework'[opt] string-literal
1717 void ModuleMapParser::parseLinkDecl() {
1718 assert(Tok.is(MMToken::LinkKeyword));
1719 SourceLocation LinkLoc = consumeToken();
1721 // Parse the optional 'framework' keyword.
1722 bool IsFramework = false;
1723 if (Tok.is(MMToken::FrameworkKeyword)) {
1728 // Parse the library name
1729 if (!Tok.is(MMToken::StringLiteral)) {
1730 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_library_name)
1731 << IsFramework << SourceRange(LinkLoc);
1736 std::string LibraryName = Tok.getString();
1738 ActiveModule->LinkLibraries.push_back(Module::LinkLibrary(LibraryName,
1742 /// \brief Parse a configuration macro declaration.
1744 /// module-declaration:
1745 /// 'config_macros' attributes[opt] config-macro-list?
1747 /// config-macro-list:
1748 /// identifier (',' identifier)?
1749 void ModuleMapParser::parseConfigMacros() {
1750 assert(Tok.is(MMToken::ConfigMacros));
1751 SourceLocation ConfigMacrosLoc = consumeToken();
1753 // Only top-level modules can have configuration macros.
1754 if (ActiveModule->Parent) {
1755 Diags.Report(ConfigMacrosLoc, diag::err_mmap_config_macro_submodule);
1758 // Parse the optional attributes.
1760 parseOptionalAttributes(Attrs);
1761 if (Attrs.IsExhaustive && !ActiveModule->Parent) {
1762 ActiveModule->ConfigMacrosExhaustive = true;
1765 // If we don't have an identifier, we're done.
1766 if (!Tok.is(MMToken::Identifier))
1769 // Consume the first identifier.
1770 if (!ActiveModule->Parent) {
1771 ActiveModule->ConfigMacros.push_back(Tok.getString().str());
1776 // If there's a comma, consume it.
1777 if (!Tok.is(MMToken::Comma))
1781 // We expect to see a macro name here.
1782 if (!Tok.is(MMToken::Identifier)) {
1783 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_config_macro);
1787 // Consume the macro name.
1788 if (!ActiveModule->Parent) {
1789 ActiveModule->ConfigMacros.push_back(Tok.getString().str());
1795 /// \brief Format a module-id into a string.
1796 static std::string formatModuleId(const ModuleId &Id) {
1799 llvm::raw_string_ostream OS(result);
1801 for (unsigned I = 0, N = Id.size(); I != N; ++I) {
1811 /// \brief Parse a conflict declaration.
1813 /// module-declaration:
1814 /// 'conflict' module-id ',' string-literal
1815 void ModuleMapParser::parseConflict() {
1816 assert(Tok.is(MMToken::Conflict));
1817 SourceLocation ConflictLoc = consumeToken();
1818 Module::UnresolvedConflict Conflict;
1820 // Parse the module-id.
1821 if (parseModuleId(Conflict.Id))
1825 if (!Tok.is(MMToken::Comma)) {
1826 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_conflicts_comma)
1827 << SourceRange(ConflictLoc);
1832 // Parse the message.
1833 if (!Tok.is(MMToken::StringLiteral)) {
1834 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_conflicts_message)
1835 << formatModuleId(Conflict.Id);
1838 Conflict.Message = Tok.getString().str();
1841 // Add this unresolved conflict.
1842 ActiveModule->UnresolvedConflicts.push_back(Conflict);
1845 /// \brief Parse an inferred module declaration (wildcard modules).
1847 /// module-declaration:
1848 /// 'explicit'[opt] 'framework'[opt] 'module' * attributes[opt]
1849 /// { inferred-module-member* }
1851 /// inferred-module-member:
1853 /// 'exclude' identifier
1854 void ModuleMapParser::parseInferredModuleDecl(bool Framework, bool Explicit) {
1855 assert(Tok.is(MMToken::Star));
1856 SourceLocation StarLoc = consumeToken();
1857 bool Failed = false;
1859 // Inferred modules must be submodules.
1860 if (!ActiveModule && !Framework) {
1861 Diags.Report(StarLoc, diag::err_mmap_top_level_inferred_submodule);
1866 // Inferred modules must have umbrella directories.
1867 if (!Failed && !ActiveModule->getUmbrellaDir()) {
1868 Diags.Report(StarLoc, diag::err_mmap_inferred_no_umbrella);
1872 // Check for redefinition of an inferred module.
1873 if (!Failed && ActiveModule->InferSubmodules) {
1874 Diags.Report(StarLoc, diag::err_mmap_inferred_redef);
1875 if (ActiveModule->InferredSubmoduleLoc.isValid())
1876 Diags.Report(ActiveModule->InferredSubmoduleLoc,
1877 diag::note_mmap_prev_definition);
1881 // Check for the 'framework' keyword, which is not permitted here.
1883 Diags.Report(StarLoc, diag::err_mmap_inferred_framework_submodule);
1886 } else if (Explicit) {
1887 Diags.Report(StarLoc, diag::err_mmap_explicit_inferred_framework);
1891 // If there were any problems with this inferred submodule, skip its body.
1893 if (Tok.is(MMToken::LBrace)) {
1895 skipUntil(MMToken::RBrace);
1896 if (Tok.is(MMToken::RBrace))
1903 // Parse optional attributes.
1905 parseOptionalAttributes(Attrs);
1908 // Note that we have an inferred submodule.
1909 ActiveModule->InferSubmodules = true;
1910 ActiveModule->InferredSubmoduleLoc = StarLoc;
1911 ActiveModule->InferExplicitSubmodules = Explicit;
1913 // We'll be inferring framework modules for this directory.
1914 Map.InferredDirectories[Directory].InferModules = true;
1915 Map.InferredDirectories[Directory].InferSystemModules = Attrs.IsSystem;
1918 // Parse the opening brace.
1919 if (!Tok.is(MMToken::LBrace)) {
1920 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_lbrace_wildcard);
1924 SourceLocation LBraceLoc = consumeToken();
1926 // Parse the body of the inferred submodule.
1930 case MMToken::EndOfFile:
1931 case MMToken::RBrace:
1935 case MMToken::ExcludeKeyword: {
1937 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member)
1938 << (ActiveModule != 0);
1944 if (!Tok.is(MMToken::Identifier)) {
1945 Diags.Report(Tok.getLocation(), diag::err_mmap_missing_exclude_name);
1949 Map.InferredDirectories[Directory].ExcludedModules
1950 .push_back(Tok.getString());
1955 case MMToken::ExportKeyword:
1956 if (!ActiveModule) {
1957 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member)
1958 << (ActiveModule != 0);
1964 if (Tok.is(MMToken::Star))
1965 ActiveModule->InferExportWildcard = true;
1967 Diags.Report(Tok.getLocation(),
1968 diag::err_mmap_expected_export_wildcard);
1972 case MMToken::ExplicitKeyword:
1973 case MMToken::ModuleKeyword:
1974 case MMToken::HeaderKeyword:
1975 case MMToken::PrivateKeyword:
1976 case MMToken::UmbrellaKeyword:
1978 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member)
1979 << (ActiveModule != 0);
1985 if (Tok.is(MMToken::RBrace))
1988 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
1989 Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
1994 /// \brief Parse optional attributes.
1997 /// attribute attributes
2003 /// \param Attrs Will be filled in with the parsed attributes.
2005 /// \returns true if an error occurred, false otherwise.
2006 bool ModuleMapParser::parseOptionalAttributes(Attributes &Attrs) {
2007 bool HadError = false;
2009 while (Tok.is(MMToken::LSquare)) {
2011 SourceLocation LSquareLoc = consumeToken();
2013 // Check whether we have an attribute name here.
2014 if (!Tok.is(MMToken::Identifier)) {
2015 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_attribute);
2016 skipUntil(MMToken::RSquare);
2017 if (Tok.is(MMToken::RSquare))
2022 // Decode the attribute name.
2023 AttributeKind Attribute
2024 = llvm::StringSwitch<AttributeKind>(Tok.getString())
2025 .Case("exhaustive", AT_exhaustive)
2026 .Case("system", AT_system)
2027 .Default(AT_unknown);
2028 switch (Attribute) {
2030 Diags.Report(Tok.getLocation(), diag::warn_mmap_unknown_attribute)
2035 Attrs.IsSystem = true;
2039 Attrs.IsExhaustive = true;
2045 if (!Tok.is(MMToken::RSquare)) {
2046 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rsquare);
2047 Diags.Report(LSquareLoc, diag::note_mmap_lsquare_match);
2048 skipUntil(MMToken::RSquare);
2052 if (Tok.is(MMToken::RSquare))
2059 /// \brief If there is a specific header search directory due the presence
2060 /// of an umbrella directory, retrieve that directory. Otherwise, returns null.
2061 const DirectoryEntry *ModuleMapParser::getOverriddenHeaderSearchDir() {
2062 for (Module *Mod = ActiveModule; Mod; Mod = Mod->Parent) {
2063 // If we have an umbrella directory, use that.
2064 if (Mod->hasUmbrellaDir())
2065 return Mod->getUmbrellaDir();
2067 // If we have a framework directory, stop looking.
2068 if (Mod->IsFramework)
2075 /// \brief Parse a module map file.
2077 /// module-map-file:
2078 /// module-declaration*
2079 bool ModuleMapParser::parseModuleMapFile() {
2082 case MMToken::EndOfFile:
2085 case MMToken::ExplicitKeyword:
2086 case MMToken::ExternKeyword:
2087 case MMToken::ModuleKeyword:
2088 case MMToken::FrameworkKeyword:
2092 case MMToken::Comma:
2093 case MMToken::ConfigMacros:
2094 case MMToken::Conflict:
2095 case MMToken::Exclaim:
2096 case MMToken::ExcludeKeyword:
2097 case MMToken::ExportKeyword:
2098 case MMToken::HeaderKeyword:
2099 case MMToken::Identifier:
2100 case MMToken::LBrace:
2101 case MMToken::LinkKeyword:
2102 case MMToken::LSquare:
2103 case MMToken::Period:
2104 case MMToken::PrivateKeyword:
2105 case MMToken::RBrace:
2106 case MMToken::RSquare:
2107 case MMToken::RequiresKeyword:
2109 case MMToken::StringLiteral:
2110 case MMToken::UmbrellaKeyword:
2111 case MMToken::UseKeyword:
2112 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module);
2120 bool ModuleMap::parseModuleMapFile(const FileEntry *File, bool IsSystem) {
2121 llvm::DenseMap<const FileEntry *, bool>::iterator Known
2122 = ParsedModuleMap.find(File);
2123 if (Known != ParsedModuleMap.end())
2124 return Known->second;
2126 assert(Target != 0 && "Missing target information");
2127 FileID ID = SourceMgr.createFileID(File, SourceLocation(), SrcMgr::C_User);
2128 const llvm::MemoryBuffer *Buffer = SourceMgr.getBuffer(ID);
2130 return ParsedModuleMap[File] = true;
2132 // Parse this module map file.
2133 Lexer L(ID, SourceMgr.getBuffer(ID), SourceMgr, MMapLangOpts);
2134 Diags->getClient()->BeginSourceFile(MMapLangOpts);
2135 ModuleMapParser Parser(L, SourceMgr, Target, *Diags, *this, File->getDir(),
2136 BuiltinIncludeDir, IsSystem);
2137 bool Result = Parser.parseModuleMapFile();
2138 Diags->getClient()->EndSourceFile();
2139 ParsedModuleMap[File] = Result;