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/HeaderSearchOptions.h"
23 #include "clang/Lex/LexDiagnostic.h"
24 #include "clang/Lex/Lexer.h"
25 #include "clang/Lex/LiteralSupport.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/ADT/StringSwitch.h"
28 #include "llvm/Support/Allocator.h"
29 #include "llvm/Support/FileSystem.h"
30 #include "llvm/Support/Host.h"
31 #include "llvm/Support/Path.h"
32 #include "llvm/Support/raw_ostream.h"
34 #if defined(LLVM_ON_UNIX)
37 using namespace clang;
40 ModuleMap::resolveExport(Module *Mod,
41 const Module::UnresolvedExportDecl &Unresolved,
42 bool Complain) const {
43 // We may have just a wildcard.
44 if (Unresolved.Id.empty()) {
45 assert(Unresolved.Wildcard && "Invalid unresolved export");
46 return Module::ExportDecl(nullptr, true);
49 // Resolve the module-id.
50 Module *Context = resolveModuleId(Unresolved.Id, Mod, Complain);
52 return Module::ExportDecl();
54 return Module::ExportDecl(Context, Unresolved.Wildcard);
57 Module *ModuleMap::resolveModuleId(const ModuleId &Id, Module *Mod,
58 bool Complain) const {
59 // Find the starting module.
60 Module *Context = lookupModuleUnqualified(Id[0].first, Mod);
63 Diags.Report(Id[0].second, diag::err_mmap_missing_module_unqualified)
64 << Id[0].first << Mod->getFullModuleName();
69 // Dig into the module path.
70 for (unsigned I = 1, N = Id.size(); I != N; ++I) {
71 Module *Sub = lookupModuleQualified(Id[I].first, Context);
74 Diags.Report(Id[I].second, diag::err_mmap_missing_module_qualified)
75 << Id[I].first << Context->getFullModuleName()
76 << SourceRange(Id[0].second, Id[I-1].second);
87 ModuleMap::ModuleMap(SourceManager &SourceMgr, DiagnosticsEngine &Diags,
88 const LangOptions &LangOpts, const TargetInfo *Target,
89 HeaderSearch &HeaderInfo)
90 : SourceMgr(SourceMgr), Diags(Diags), LangOpts(LangOpts), Target(Target),
91 HeaderInfo(HeaderInfo), BuiltinIncludeDir(nullptr),
92 SourceModule(nullptr), NumCreatedModules(0) {
93 MMapLangOpts.LineComment = true;
96 ModuleMap::~ModuleMap() {
97 for (auto &M : Modules)
101 void ModuleMap::setTarget(const TargetInfo &Target) {
102 assert((!this->Target || this->Target == &Target) &&
103 "Improper target override");
104 this->Target = &Target;
107 /// \brief "Sanitize" a filename so that it can be used as an identifier.
108 static StringRef sanitizeFilenameAsIdentifier(StringRef Name,
109 SmallVectorImpl<char> &Buffer) {
113 if (!isValidIdentifier(Name)) {
114 // If we don't already have something with the form of an identifier,
115 // create a buffer with the sanitized name.
117 if (isDigit(Name[0]))
118 Buffer.push_back('_');
119 Buffer.reserve(Buffer.size() + Name.size());
120 for (unsigned I = 0, N = Name.size(); I != N; ++I) {
121 if (isIdentifierBody(Name[I]))
122 Buffer.push_back(Name[I]);
124 Buffer.push_back('_');
127 Name = StringRef(Buffer.data(), Buffer.size());
130 while (llvm::StringSwitch<bool>(Name)
131 #define KEYWORD(Keyword,Conditions) .Case(#Keyword, true)
132 #define ALIAS(Keyword, AliasOf, Conditions) .Case(Keyword, true)
133 #include "clang/Basic/TokenKinds.def"
135 if (Name.data() != Buffer.data())
136 Buffer.append(Name.begin(), Name.end());
137 Buffer.push_back('_');
138 Name = StringRef(Buffer.data(), Buffer.size());
144 /// \brief Determine whether the given file name is the name of a builtin
145 /// header, supplied by Clang to replace, override, or augment existing system
147 bool ModuleMap::isBuiltinHeader(StringRef FileName) {
148 return llvm::StringSwitch<bool>(FileName)
149 .Case("float.h", true)
150 .Case("iso646.h", true)
151 .Case("limits.h", true)
152 .Case("stdalign.h", true)
153 .Case("stdarg.h", true)
154 .Case("stdatomic.h", true)
155 .Case("stdbool.h", true)
156 .Case("stddef.h", true)
157 .Case("stdint.h", true)
158 .Case("tgmath.h", true)
159 .Case("unwind.h", true)
163 ModuleMap::HeadersMap::iterator
164 ModuleMap::findKnownHeader(const FileEntry *File) {
165 HeadersMap::iterator Known = Headers.find(File);
166 if (HeaderInfo.getHeaderSearchOpts().ImplicitModuleMaps &&
167 Known == Headers.end() && File->getDir() == BuiltinIncludeDir &&
168 ModuleMap::isBuiltinHeader(llvm::sys::path::filename(File->getName()))) {
169 HeaderInfo.loadTopLevelSystemModules();
170 return Headers.find(File);
175 ModuleMap::KnownHeader
176 ModuleMap::findHeaderInUmbrellaDirs(const FileEntry *File,
177 SmallVectorImpl<const DirectoryEntry *> &IntermediateDirs) {
178 if (UmbrellaDirs.empty())
179 return KnownHeader();
181 const DirectoryEntry *Dir = File->getDir();
182 assert(Dir && "file in no directory");
184 // Note: as an egregious but useful hack we use the real path here, because
185 // frameworks moving from top-level frameworks to embedded frameworks tend
186 // to be symlinked from the top-level location to the embedded location,
187 // and we need to resolve lookups as if we had found the embedded location.
188 StringRef DirName = SourceMgr.getFileManager().getCanonicalName(Dir);
190 // Keep walking up the directory hierarchy, looking for a directory with
191 // an umbrella header.
193 auto KnownDir = UmbrellaDirs.find(Dir);
194 if (KnownDir != UmbrellaDirs.end())
195 return KnownHeader(KnownDir->second, NormalHeader);
197 IntermediateDirs.push_back(Dir);
199 // Retrieve our parent path.
200 DirName = llvm::sys::path::parent_path(DirName);
204 // Resolve the parent path to a directory entry.
205 Dir = SourceMgr.getFileManager().getDirectory(DirName);
207 return KnownHeader();
210 static bool violatesPrivateInclude(Module *RequestingModule,
211 const FileEntry *IncFileEnt,
212 ModuleMap::KnownHeader Header) {
214 if (Header.getRole() & ModuleMap::PrivateHeader) {
215 // Check for consistency between the module header role
216 // as obtained from the lookup and as obtained from the module.
217 // This check is not cheap, so enable it only for debugging.
218 bool IsPrivate = false;
219 SmallVectorImpl<Module::Header> *HeaderList[] = {
220 &Header.getModule()->Headers[Module::HK_Private],
221 &Header.getModule()->Headers[Module::HK_PrivateTextual]};
222 for (auto *Hs : HeaderList)
224 std::find_if(Hs->begin(), Hs->end(), [&](const Module::Header &H) {
225 return H.Entry == IncFileEnt;
227 assert(IsPrivate && "inconsistent headers and roles");
230 return !Header.isAccessibleFrom(RequestingModule);
233 static Module *getTopLevelOrNull(Module *M) {
234 return M ? M->getTopLevelModule() : nullptr;
237 void ModuleMap::diagnoseHeaderInclusion(Module *RequestingModule,
238 bool RequestingModuleIsModuleInterface,
239 SourceLocation FilenameLoc,
241 const FileEntry *File) {
242 // No errors for indirect modules. This may be a bit of a problem for modules
243 // with no source files.
244 if (getTopLevelOrNull(RequestingModule) != getTopLevelOrNull(SourceModule))
247 if (RequestingModule)
248 resolveUses(RequestingModule, /*Complain=*/false);
250 bool Excluded = false;
251 Module *Private = nullptr;
252 Module *NotUsed = nullptr;
254 HeadersMap::iterator Known = findKnownHeader(File);
255 if (Known != Headers.end()) {
256 for (const KnownHeader &Header : Known->second) {
257 // Remember private headers for later printing of a diagnostic.
258 if (violatesPrivateInclude(RequestingModule, File, Header)) {
259 Private = Header.getModule();
263 // If uses need to be specified explicitly, we are only allowed to return
264 // modules that are explicitly used by the requesting module.
265 if (RequestingModule && LangOpts.ModulesDeclUse &&
266 !RequestingModule->directlyUses(Header.getModule())) {
267 NotUsed = Header.getModule();
271 // We have found a module that we can happily use.
278 // We have found a header, but it is private.
280 Diags.Report(FilenameLoc, diag::warn_use_of_private_header_outside_module)
285 // We have found a module, but we don't use it.
287 Diags.Report(FilenameLoc, diag::err_undeclared_use_of_module)
288 << RequestingModule->getFullModuleName() << Filename;
292 if (Excluded || isHeaderInUmbrellaDirs(File))
295 // At this point, only non-modular includes remain.
297 if (LangOpts.ModulesStrictDeclUse) {
298 Diags.Report(FilenameLoc, diag::err_undeclared_use_of_module)
299 << RequestingModule->getFullModuleName() << Filename;
300 } else if (RequestingModule && RequestingModuleIsModuleInterface &&
301 LangOpts.isCompilingModule()) {
302 // Do not diagnose when we are not compiling a module.
303 diag::kind DiagID = RequestingModule->getTopLevelModule()->IsFramework ?
304 diag::warn_non_modular_include_in_framework_module :
305 diag::warn_non_modular_include_in_module;
306 Diags.Report(FilenameLoc, DiagID) << RequestingModule->getFullModuleName()
311 static bool isBetterKnownHeader(const ModuleMap::KnownHeader &New,
312 const ModuleMap::KnownHeader &Old) {
313 // Prefer available modules.
314 if (New.getModule()->isAvailable() && !Old.getModule()->isAvailable())
317 // Prefer a public header over a private header.
318 if ((New.getRole() & ModuleMap::PrivateHeader) !=
319 (Old.getRole() & ModuleMap::PrivateHeader))
320 return !(New.getRole() & ModuleMap::PrivateHeader);
322 // Prefer a non-textual header over a textual header.
323 if ((New.getRole() & ModuleMap::TextualHeader) !=
324 (Old.getRole() & ModuleMap::TextualHeader))
325 return !(New.getRole() & ModuleMap::TextualHeader);
327 // Don't have a reason to choose between these. Just keep the first one.
331 ModuleMap::KnownHeader ModuleMap::findModuleForHeader(const FileEntry *File,
333 auto MakeResult = [&](ModuleMap::KnownHeader R) -> ModuleMap::KnownHeader {
334 if (!AllowTextual && R.getRole() & ModuleMap::TextualHeader)
335 return ModuleMap::KnownHeader();
339 HeadersMap::iterator Known = findKnownHeader(File);
340 if (Known != Headers.end()) {
341 ModuleMap::KnownHeader Result;
342 // Iterate over all modules that 'File' is part of to find the best fit.
343 for (KnownHeader &H : Known->second) {
344 // Prefer a header from the source module over all others.
345 if (H.getModule()->getTopLevelModule() == SourceModule)
346 return MakeResult(H);
347 if (!Result || isBetterKnownHeader(H, Result))
350 return MakeResult(Result);
353 return MakeResult(findOrCreateModuleForHeaderInUmbrellaDir(File));
356 ModuleMap::KnownHeader
357 ModuleMap::findOrCreateModuleForHeaderInUmbrellaDir(const FileEntry *File) {
358 assert(!Headers.count(File) && "already have a module for this header");
360 SmallVector<const DirectoryEntry *, 2> SkippedDirs;
361 KnownHeader H = findHeaderInUmbrellaDirs(File, SkippedDirs);
363 Module *Result = H.getModule();
365 // Search up the module stack until we find a module with an umbrella
367 Module *UmbrellaModule = Result;
368 while (!UmbrellaModule->getUmbrellaDir() && UmbrellaModule->Parent)
369 UmbrellaModule = UmbrellaModule->Parent;
371 if (UmbrellaModule->InferSubmodules) {
372 const FileEntry *UmbrellaModuleMap =
373 getModuleMapFileForUniquing(UmbrellaModule);
375 // Infer submodules for each of the directories we found between
376 // the directory of the umbrella header and the directory where
377 // the actual header is located.
378 bool Explicit = UmbrellaModule->InferExplicitSubmodules;
380 for (unsigned I = SkippedDirs.size(); I != 0; --I) {
381 // Find or create the module that corresponds to this directory name.
382 SmallString<32> NameBuf;
383 StringRef Name = sanitizeFilenameAsIdentifier(
384 llvm::sys::path::stem(SkippedDirs[I-1]->getName()), NameBuf);
385 Result = findOrCreateModule(Name, Result, /*IsFramework=*/false,
387 InferredModuleAllowedBy[Result] = UmbrellaModuleMap;
388 Result->IsInferred = true;
390 // Associate the module and the directory.
391 UmbrellaDirs[SkippedDirs[I-1]] = Result;
393 // If inferred submodules export everything they import, add a
394 // wildcard to the set of exports.
395 if (UmbrellaModule->InferExportWildcard && Result->Exports.empty())
396 Result->Exports.push_back(Module::ExportDecl(nullptr, true));
399 // Infer a submodule with the same name as this header file.
400 SmallString<32> NameBuf;
401 StringRef Name = sanitizeFilenameAsIdentifier(
402 llvm::sys::path::stem(File->getName()), NameBuf);
403 Result = findOrCreateModule(Name, Result, /*IsFramework=*/false,
405 InferredModuleAllowedBy[Result] = UmbrellaModuleMap;
406 Result->IsInferred = true;
407 Result->addTopHeader(File);
409 // If inferred submodules export everything they import, add a
410 // wildcard to the set of exports.
411 if (UmbrellaModule->InferExportWildcard && Result->Exports.empty())
412 Result->Exports.push_back(Module::ExportDecl(nullptr, true));
414 // Record each of the directories we stepped through as being part of
415 // the module we found, since the umbrella header covers them all.
416 for (unsigned I = 0, N = SkippedDirs.size(); I != N; ++I)
417 UmbrellaDirs[SkippedDirs[I]] = Result;
420 KnownHeader Header(Result, NormalHeader);
421 Headers[File].push_back(Header);
425 return KnownHeader();
428 ArrayRef<ModuleMap::KnownHeader>
429 ModuleMap::findAllModulesForHeader(const FileEntry *File) const {
430 auto It = Headers.find(File);
431 if (It == Headers.end())
436 bool ModuleMap::isHeaderInUnavailableModule(const FileEntry *Header) const {
437 return isHeaderUnavailableInModule(Header, nullptr);
441 ModuleMap::isHeaderUnavailableInModule(const FileEntry *Header,
442 const Module *RequestingModule) const {
443 HeadersMap::const_iterator Known = Headers.find(Header);
444 if (Known != Headers.end()) {
445 for (SmallVectorImpl<KnownHeader>::const_iterator
446 I = Known->second.begin(),
447 E = Known->second.end();
450 if (I->isAvailable() &&
451 (!RequestingModule ||
452 I->getModule()->isSubModuleOf(RequestingModule))) {
453 // When no requesting module is available, the caller is looking if a
454 // header is part a module by only looking into the module map. This is
455 // done by warn_uncovered_module_header checks; don't consider textual
456 // headers part of it in this mode, otherwise we get misleading warnings
457 // that a umbrella header is not including a textual header.
458 if (!RequestingModule && I->getRole() == ModuleMap::TextualHeader)
466 const DirectoryEntry *Dir = Header->getDir();
467 SmallVector<const DirectoryEntry *, 2> SkippedDirs;
468 StringRef DirName = Dir->getName();
470 auto IsUnavailable = [&](const Module *M) {
471 return !M->isAvailable() && (!RequestingModule ||
472 M->isSubModuleOf(RequestingModule));
475 // Keep walking up the directory hierarchy, looking for a directory with
476 // an umbrella header.
478 llvm::DenseMap<const DirectoryEntry *, Module *>::const_iterator KnownDir
479 = UmbrellaDirs.find(Dir);
480 if (KnownDir != UmbrellaDirs.end()) {
481 Module *Found = KnownDir->second;
482 if (IsUnavailable(Found))
485 // Search up the module stack until we find a module with an umbrella
487 Module *UmbrellaModule = Found;
488 while (!UmbrellaModule->getUmbrellaDir() && UmbrellaModule->Parent)
489 UmbrellaModule = UmbrellaModule->Parent;
491 if (UmbrellaModule->InferSubmodules) {
492 for (unsigned I = SkippedDirs.size(); I != 0; --I) {
493 // Find or create the module that corresponds to this directory name.
494 SmallString<32> NameBuf;
495 StringRef Name = sanitizeFilenameAsIdentifier(
496 llvm::sys::path::stem(SkippedDirs[I-1]->getName()),
498 Found = lookupModuleQualified(Name, Found);
501 if (IsUnavailable(Found))
505 // Infer a submodule with the same name as this header file.
506 SmallString<32> NameBuf;
507 StringRef Name = sanitizeFilenameAsIdentifier(
508 llvm::sys::path::stem(Header->getName()),
510 Found = lookupModuleQualified(Name, Found);
515 return IsUnavailable(Found);
518 SkippedDirs.push_back(Dir);
520 // Retrieve our parent path.
521 DirName = llvm::sys::path::parent_path(DirName);
525 // Resolve the parent path to a directory entry.
526 Dir = SourceMgr.getFileManager().getDirectory(DirName);
532 Module *ModuleMap::findModule(StringRef Name) const {
533 llvm::StringMap<Module *>::const_iterator Known = Modules.find(Name);
534 if (Known != Modules.end())
535 return Known->getValue();
540 Module *ModuleMap::lookupModuleUnqualified(StringRef Name,
541 Module *Context) const {
542 for(; Context; Context = Context->Parent) {
543 if (Module *Sub = lookupModuleQualified(Name, Context))
547 return findModule(Name);
550 Module *ModuleMap::lookupModuleQualified(StringRef Name, Module *Context) const{
552 return findModule(Name);
554 return Context->findSubmodule(Name);
557 std::pair<Module *, bool> ModuleMap::findOrCreateModule(StringRef Name,
561 // Try to find an existing module with this name.
562 if (Module *Sub = lookupModuleQualified(Name, Parent))
563 return std::make_pair(Sub, false);
565 // Create a new module with this name.
566 Module *Result = new Module(Name, SourceLocation(), Parent, IsFramework,
567 IsExplicit, NumCreatedModules++);
569 if (LangOpts.CurrentModule == Name)
570 SourceModule = Result;
571 Modules[Name] = Result;
573 return std::make_pair(Result, true);
576 Module *ModuleMap::createModuleForInterfaceUnit(SourceLocation Loc,
578 assert(LangOpts.CurrentModule == Name && "module name mismatch");
579 assert(!Modules[Name] && "redefining existing module");
582 new Module(Name, Loc, nullptr, /*IsFramework*/ false,
583 /*IsExplicit*/ false, NumCreatedModules++);
584 Result->Kind = Module::ModuleInterfaceUnit;
585 Modules[Name] = SourceModule = Result;
587 // Mark the main source file as being within the newly-created module so that
588 // declarations and macros are properly visibility-restricted to it.
589 auto *MainFile = SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
590 assert(MainFile && "no input file for module interface");
591 Headers[MainFile].push_back(KnownHeader(Result, PrivateHeader));
596 /// \brief For a framework module, infer the framework against which we
598 static void inferFrameworkLink(Module *Mod, const DirectoryEntry *FrameworkDir,
599 FileManager &FileMgr) {
600 assert(Mod->IsFramework && "Can only infer linking for framework modules");
601 assert(!Mod->isSubFramework() &&
602 "Can only infer linking for top-level frameworks");
604 SmallString<128> LibName;
605 LibName += FrameworkDir->getName();
606 llvm::sys::path::append(LibName, Mod->Name);
608 // The library name of a framework has more than one possible extension since
609 // the introduction of the text-based dynamic library format. We need to check
610 // for both before we give up.
611 for (const char *extension : {"", ".tbd"}) {
612 llvm::sys::path::replace_extension(LibName, extension);
613 if (FileMgr.getFile(LibName)) {
614 Mod->LinkLibraries.push_back(Module::LinkLibrary(Mod->Name,
615 /*IsFramework=*/true));
621 Module *ModuleMap::inferFrameworkModule(const DirectoryEntry *FrameworkDir,
622 bool IsSystem, Module *Parent) {
624 Attrs.IsSystem = IsSystem;
625 return inferFrameworkModule(FrameworkDir, Attrs, Parent);
628 Module *ModuleMap::inferFrameworkModule(const DirectoryEntry *FrameworkDir,
629 Attributes Attrs, Module *Parent) {
630 // Note: as an egregious but useful hack we use the real path here, because
631 // we might be looking at an embedded framework that symlinks out to a
632 // top-level framework, and we need to infer as if we were naming the
633 // top-level framework.
634 StringRef FrameworkDirName =
635 SourceMgr.getFileManager().getCanonicalName(FrameworkDir);
637 // In case this is a case-insensitive filesystem, use the canonical
638 // directory name as the ModuleName, since modules are case-sensitive.
639 // FIXME: we should be able to give a fix-it hint for the correct spelling.
640 SmallString<32> ModuleNameStorage;
641 StringRef ModuleName = sanitizeFilenameAsIdentifier(
642 llvm::sys::path::stem(FrameworkDirName), ModuleNameStorage);
644 // Check whether we've already found this module.
645 if (Module *Mod = lookupModuleQualified(ModuleName, Parent))
648 FileManager &FileMgr = SourceMgr.getFileManager();
650 // If the framework has a parent path from which we're allowed to infer
651 // a framework module, do so.
652 const FileEntry *ModuleMapFile = nullptr;
654 // Determine whether we're allowed to infer a module map.
655 bool canInfer = false;
656 if (llvm::sys::path::has_parent_path(FrameworkDirName)) {
657 // Figure out the parent path.
658 StringRef Parent = llvm::sys::path::parent_path(FrameworkDirName);
659 if (const DirectoryEntry *ParentDir = FileMgr.getDirectory(Parent)) {
660 // Check whether we have already looked into the parent directory
662 llvm::DenseMap<const DirectoryEntry *, InferredDirectory>::const_iterator
663 inferred = InferredDirectories.find(ParentDir);
664 if (inferred == InferredDirectories.end()) {
665 // We haven't looked here before. Load a module map, if there is
667 bool IsFrameworkDir = Parent.endswith(".framework");
668 if (const FileEntry *ModMapFile =
669 HeaderInfo.lookupModuleMapFile(ParentDir, IsFrameworkDir)) {
670 parseModuleMapFile(ModMapFile, Attrs.IsSystem, ParentDir);
671 inferred = InferredDirectories.find(ParentDir);
674 if (inferred == InferredDirectories.end())
675 inferred = InferredDirectories.insert(
676 std::make_pair(ParentDir, InferredDirectory())).first;
679 if (inferred->second.InferModules) {
680 // We're allowed to infer for this directory, but make sure it's okay
681 // to infer this particular module.
682 StringRef Name = llvm::sys::path::stem(FrameworkDirName);
683 canInfer = std::find(inferred->second.ExcludedModules.begin(),
684 inferred->second.ExcludedModules.end(),
685 Name) == inferred->second.ExcludedModules.end();
687 Attrs.IsSystem |= inferred->second.Attrs.IsSystem;
688 Attrs.IsExternC |= inferred->second.Attrs.IsExternC;
689 Attrs.IsExhaustive |= inferred->second.Attrs.IsExhaustive;
690 Attrs.NoUndeclaredIncludes |=
691 inferred->second.Attrs.NoUndeclaredIncludes;
692 ModuleMapFile = inferred->second.ModuleMapFile;
697 // If we're not allowed to infer a framework module, don't.
701 ModuleMapFile = getModuleMapFileForUniquing(Parent);
704 // Look for an umbrella header.
705 SmallString<128> UmbrellaName = StringRef(FrameworkDir->getName());
706 llvm::sys::path::append(UmbrellaName, "Headers", ModuleName + ".h");
707 const FileEntry *UmbrellaHeader = FileMgr.getFile(UmbrellaName);
709 // FIXME: If there's no umbrella header, we could probably scan the
710 // framework to load *everything*. But, it's not clear that this is a good
715 Module *Result = new Module(ModuleName, SourceLocation(), Parent,
716 /*IsFramework=*/true, /*IsExplicit=*/false,
717 NumCreatedModules++);
718 InferredModuleAllowedBy[Result] = ModuleMapFile;
719 Result->IsInferred = true;
721 if (LangOpts.CurrentModule == ModuleName)
722 SourceModule = Result;
723 Modules[ModuleName] = Result;
726 Result->IsSystem |= Attrs.IsSystem;
727 Result->IsExternC |= Attrs.IsExternC;
728 Result->ConfigMacrosExhaustive |= Attrs.IsExhaustive;
729 Result->NoUndeclaredIncludes |= Attrs.NoUndeclaredIncludes;
730 Result->Directory = FrameworkDir;
732 // umbrella header "umbrella-header-name"
734 // The "Headers/" component of the name is implied because this is
735 // a framework module.
736 setUmbrellaHeader(Result, UmbrellaHeader, ModuleName + ".h");
739 Result->Exports.push_back(Module::ExportDecl(nullptr, true));
741 // module * { export * }
742 Result->InferSubmodules = true;
743 Result->InferExportWildcard = true;
745 // Look for subframeworks.
747 SmallString<128> SubframeworksDirName
748 = StringRef(FrameworkDir->getName());
749 llvm::sys::path::append(SubframeworksDirName, "Frameworks");
750 llvm::sys::path::native(SubframeworksDirName);
751 vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
752 for (vfs::directory_iterator Dir = FS.dir_begin(SubframeworksDirName, EC),
754 Dir != DirEnd && !EC; Dir.increment(EC)) {
755 if (!StringRef(Dir->getName()).endswith(".framework"))
758 if (const DirectoryEntry *SubframeworkDir =
759 FileMgr.getDirectory(Dir->getName())) {
760 // Note: as an egregious but useful hack, we use the real path here and
761 // check whether it is actually a subdirectory of the parent directory.
762 // This will not be the case if the 'subframework' is actually a symlink
763 // out to a top-level framework.
764 StringRef SubframeworkDirName = FileMgr.getCanonicalName(SubframeworkDir);
765 bool FoundParent = false;
767 // Get the parent directory name.
769 = llvm::sys::path::parent_path(SubframeworkDirName);
770 if (SubframeworkDirName.empty())
773 if (FileMgr.getDirectory(SubframeworkDirName) == FrameworkDir) {
782 // FIXME: Do we want to warn about subframeworks without umbrella headers?
783 inferFrameworkModule(SubframeworkDir, Attrs, Result);
787 // If the module is a top-level framework, automatically link against the
789 if (!Result->isSubFramework()) {
790 inferFrameworkLink(Result, FrameworkDir, FileMgr);
796 void ModuleMap::setUmbrellaHeader(Module *Mod, const FileEntry *UmbrellaHeader,
797 Twine NameAsWritten) {
798 Headers[UmbrellaHeader].push_back(KnownHeader(Mod, NormalHeader));
799 Mod->Umbrella = UmbrellaHeader;
800 Mod->UmbrellaAsWritten = NameAsWritten.str();
801 UmbrellaDirs[UmbrellaHeader->getDir()] = Mod;
803 // Notify callbacks that we just added a new header.
804 for (const auto &Cb : Callbacks)
805 Cb->moduleMapAddUmbrellaHeader(&SourceMgr.getFileManager(), UmbrellaHeader);
808 void ModuleMap::setUmbrellaDir(Module *Mod, const DirectoryEntry *UmbrellaDir,
809 Twine NameAsWritten) {
810 Mod->Umbrella = UmbrellaDir;
811 Mod->UmbrellaAsWritten = NameAsWritten.str();
812 UmbrellaDirs[UmbrellaDir] = Mod;
815 static Module::HeaderKind headerRoleToKind(ModuleMap::ModuleHeaderRole Role) {
817 default: llvm_unreachable("unknown header role");
818 case ModuleMap::NormalHeader:
819 return Module::HK_Normal;
820 case ModuleMap::PrivateHeader:
821 return Module::HK_Private;
822 case ModuleMap::TextualHeader:
823 return Module::HK_Textual;
824 case ModuleMap::PrivateHeader | ModuleMap::TextualHeader:
825 return Module::HK_PrivateTextual;
829 void ModuleMap::addHeader(Module *Mod, Module::Header Header,
830 ModuleHeaderRole Role, bool Imported) {
831 KnownHeader KH(Mod, Role);
833 // Only add each header to the headers list once.
834 // FIXME: Should we diagnose if a header is listed twice in the
835 // same module definition?
836 auto &HeaderList = Headers[Header.Entry];
837 for (auto H : HeaderList)
841 HeaderList.push_back(KH);
842 Mod->Headers[headerRoleToKind(Role)].push_back(Header);
844 bool isCompilingModuleHeader =
845 LangOpts.isCompilingModule() && Mod->getTopLevelModule() == SourceModule;
846 if (!Imported || isCompilingModuleHeader) {
847 // When we import HeaderFileInfo, the external source is expected to
848 // set the isModuleHeader flag itself.
849 HeaderInfo.MarkFileModuleHeader(Header.Entry, Role,
850 isCompilingModuleHeader);
853 // Notify callbacks that we just added a new header.
854 for (const auto &Cb : Callbacks)
855 Cb->moduleMapAddHeader(Header.Entry->getName());
858 void ModuleMap::excludeHeader(Module *Mod, Module::Header Header) {
859 // Add this as a known header so we won't implicitly add it to any
860 // umbrella directory module.
861 // FIXME: Should we only exclude it from umbrella modules within the
863 (void) Headers[Header.Entry];
865 Mod->Headers[Module::HK_Excluded].push_back(std::move(Header));
869 ModuleMap::getContainingModuleMapFile(const Module *Module) const {
870 if (Module->DefinitionLoc.isInvalid())
873 return SourceMgr.getFileEntryForID(
874 SourceMgr.getFileID(Module->DefinitionLoc));
877 const FileEntry *ModuleMap::getModuleMapFileForUniquing(const Module *M) const {
879 assert(InferredModuleAllowedBy.count(M) && "missing inferred module map");
880 return InferredModuleAllowedBy.find(M)->second;
882 return getContainingModuleMapFile(M);
885 void ModuleMap::setInferredModuleAllowedBy(Module *M, const FileEntry *ModMap) {
886 assert(M->IsInferred && "module not inferred");
887 InferredModuleAllowedBy[M] = ModMap;
890 LLVM_DUMP_METHOD void ModuleMap::dump() {
891 llvm::errs() << "Modules:";
892 for (llvm::StringMap<Module *>::iterator M = Modules.begin(),
893 MEnd = Modules.end();
895 M->getValue()->print(llvm::errs(), 2);
897 llvm::errs() << "Headers:";
898 for (HeadersMap::iterator H = Headers.begin(), HEnd = Headers.end();
900 llvm::errs() << " \"" << H->first->getName() << "\" -> ";
901 for (SmallVectorImpl<KnownHeader>::const_iterator I = H->second.begin(),
904 if (I != H->second.begin())
906 llvm::errs() << I->getModule()->getFullModuleName();
908 llvm::errs() << "\n";
912 bool ModuleMap::resolveExports(Module *Mod, bool Complain) {
913 auto Unresolved = std::move(Mod->UnresolvedExports);
914 Mod->UnresolvedExports.clear();
915 for (auto &UE : Unresolved) {
916 Module::ExportDecl Export = resolveExport(Mod, UE, Complain);
917 if (Export.getPointer() || Export.getInt())
918 Mod->Exports.push_back(Export);
920 Mod->UnresolvedExports.push_back(UE);
922 return !Mod->UnresolvedExports.empty();
925 bool ModuleMap::resolveUses(Module *Mod, bool Complain) {
926 auto Unresolved = std::move(Mod->UnresolvedDirectUses);
927 Mod->UnresolvedDirectUses.clear();
928 for (auto &UDU : Unresolved) {
929 Module *DirectUse = resolveModuleId(UDU, Mod, Complain);
931 Mod->DirectUses.push_back(DirectUse);
933 Mod->UnresolvedDirectUses.push_back(UDU);
935 return !Mod->UnresolvedDirectUses.empty();
938 bool ModuleMap::resolveConflicts(Module *Mod, bool Complain) {
939 auto Unresolved = std::move(Mod->UnresolvedConflicts);
940 Mod->UnresolvedConflicts.clear();
941 for (auto &UC : Unresolved) {
942 if (Module *OtherMod = resolveModuleId(UC.Id, Mod, Complain)) {
943 Module::Conflict Conflict;
944 Conflict.Other = OtherMod;
945 Conflict.Message = UC.Message;
946 Mod->Conflicts.push_back(Conflict);
948 Mod->UnresolvedConflicts.push_back(UC);
950 return !Mod->UnresolvedConflicts.empty();
953 //----------------------------------------------------------------------------//
954 // Module map file parser
955 //----------------------------------------------------------------------------//
958 /// \brief A token in a module map file.
990 unsigned StringLength;
991 const char *StringData;
997 StringData = nullptr;
1000 bool is(TokenKind K) const { return Kind == K; }
1002 SourceLocation getLocation() const {
1003 return SourceLocation::getFromRawEncoding(Location);
1006 StringRef getString() const {
1007 return StringRef(StringData, StringLength);
1011 class ModuleMapParser {
1013 SourceManager &SourceMgr;
1015 /// \brief Default target information, used only for string literal
1017 const TargetInfo *Target;
1019 DiagnosticsEngine &Diags;
1022 /// \brief The current module map file.
1023 const FileEntry *ModuleMapFile;
1025 /// \brief The directory that file names in this module map file should
1026 /// be resolved relative to.
1027 const DirectoryEntry *Directory;
1029 /// \brief The directory containing Clang-supplied headers.
1030 const DirectoryEntry *BuiltinIncludeDir;
1032 /// \brief Whether this module map is in a system header directory.
1035 /// \brief Whether an error occurred.
1038 /// \brief Stores string data for the various string literals referenced
1040 llvm::BumpPtrAllocator StringData;
1042 /// \brief The current token.
1045 /// \brief The active module.
1046 Module *ActiveModule;
1048 /// \brief Whether a module uses the 'requires excluded' hack to mark its
1049 /// contents as 'textual'.
1051 /// On older Darwin SDK versions, 'requires excluded' is used to mark the
1052 /// contents of the Darwin.C.excluded (assert.h) and Tcl.Private modules as
1053 /// non-modular headers. For backwards compatibility, we continue to
1054 /// support this idiom for just these modules, and map the headers to
1055 /// 'textual' to match the original intent.
1056 llvm::SmallPtrSet<Module *, 2> UsesRequiresExcludedHack;
1058 /// \brief Consume the current token and return its location.
1059 SourceLocation consumeToken();
1061 /// \brief Skip tokens until we reach the a token with the given kind
1062 /// (or the end of the file).
1063 void skipUntil(MMToken::TokenKind K);
1065 typedef SmallVector<std::pair<std::string, SourceLocation>, 2> ModuleId;
1066 bool parseModuleId(ModuleId &Id);
1067 void parseModuleDecl();
1068 void parseExternModuleDecl();
1069 void parseRequiresDecl();
1070 void parseHeaderDecl(clang::MMToken::TokenKind,
1071 SourceLocation LeadingLoc);
1072 void parseUmbrellaDirDecl(SourceLocation UmbrellaLoc);
1073 void parseExportDecl();
1074 void parseUseDecl();
1075 void parseLinkDecl();
1076 void parseConfigMacros();
1077 void parseConflict();
1078 void parseInferredModuleDecl(bool Framework, bool Explicit);
1080 typedef ModuleMap::Attributes Attributes;
1081 bool parseOptionalAttributes(Attributes &Attrs);
1084 explicit ModuleMapParser(Lexer &L, SourceManager &SourceMgr,
1085 const TargetInfo *Target,
1086 DiagnosticsEngine &Diags,
1088 const FileEntry *ModuleMapFile,
1089 const DirectoryEntry *Directory,
1090 const DirectoryEntry *BuiltinIncludeDir,
1092 : L(L), SourceMgr(SourceMgr), Target(Target), Diags(Diags), Map(Map),
1093 ModuleMapFile(ModuleMapFile), Directory(Directory),
1094 BuiltinIncludeDir(BuiltinIncludeDir), IsSystem(IsSystem),
1095 HadError(false), ActiveModule(nullptr)
1101 bool parseModuleMapFile();
1103 bool terminatedByDirective() { return false; }
1104 SourceLocation getLocation() { return Tok.getLocation(); }
1108 SourceLocation ModuleMapParser::consumeToken() {
1109 SourceLocation Result = Tok.getLocation();
1114 L.LexFromRawLexer(LToken);
1115 Tok.Location = LToken.getLocation().getRawEncoding();
1116 switch (LToken.getKind()) {
1117 case tok::raw_identifier: {
1118 StringRef RI = LToken.getRawIdentifier();
1119 Tok.StringData = RI.data();
1120 Tok.StringLength = RI.size();
1121 Tok.Kind = llvm::StringSwitch<MMToken::TokenKind>(RI)
1122 .Case("config_macros", MMToken::ConfigMacros)
1123 .Case("conflict", MMToken::Conflict)
1124 .Case("exclude", MMToken::ExcludeKeyword)
1125 .Case("explicit", MMToken::ExplicitKeyword)
1126 .Case("export", MMToken::ExportKeyword)
1127 .Case("extern", MMToken::ExternKeyword)
1128 .Case("framework", MMToken::FrameworkKeyword)
1129 .Case("header", MMToken::HeaderKeyword)
1130 .Case("link", MMToken::LinkKeyword)
1131 .Case("module", MMToken::ModuleKeyword)
1132 .Case("private", MMToken::PrivateKeyword)
1133 .Case("requires", MMToken::RequiresKeyword)
1134 .Case("textual", MMToken::TextualKeyword)
1135 .Case("umbrella", MMToken::UmbrellaKeyword)
1136 .Case("use", MMToken::UseKeyword)
1137 .Default(MMToken::Identifier);
1142 Tok.Kind = MMToken::Comma;
1146 Tok.Kind = MMToken::EndOfFile;
1150 Tok.Kind = MMToken::LBrace;
1154 Tok.Kind = MMToken::LSquare;
1158 Tok.Kind = MMToken::Period;
1162 Tok.Kind = MMToken::RBrace;
1166 Tok.Kind = MMToken::RSquare;
1170 Tok.Kind = MMToken::Star;
1174 Tok.Kind = MMToken::Exclaim;
1177 case tok::string_literal: {
1178 if (LToken.hasUDSuffix()) {
1179 Diags.Report(LToken.getLocation(), diag::err_invalid_string_udl);
1184 // Parse the string literal.
1185 LangOptions LangOpts;
1186 StringLiteralParser StringLiteral(LToken, SourceMgr, LangOpts, *Target);
1187 if (StringLiteral.hadError)
1190 // Copy the string literal into our string data allocator.
1191 unsigned Length = StringLiteral.GetStringLength();
1192 char *Saved = StringData.Allocate<char>(Length + 1);
1193 memcpy(Saved, StringLiteral.GetString().data(), Length);
1197 Tok.Kind = MMToken::StringLiteral;
1198 Tok.StringData = Saved;
1199 Tok.StringLength = Length;
1207 // A module map can be terminated prematurely by
1208 // #pragma clang module contents
1209 // When building the module, we'll treat the rest of the file as the
1210 // contents of the module.
1212 auto NextIsIdent = [&](StringRef Str) -> bool {
1213 L.LexFromRawLexer(LToken);
1214 return !LToken.isAtStartOfLine() && LToken.is(tok::raw_identifier) &&
1215 LToken.getRawIdentifier() == Str;
1217 if (NextIsIdent("pragma") && NextIsIdent("clang") &&
1218 NextIsIdent("module") && NextIsIdent("contents")) {
1219 Tok.Kind = MMToken::EndOfFile;
1226 Diags.Report(Tok.getLocation(), diag::err_mmap_unknown_token);
1234 void ModuleMapParser::skipUntil(MMToken::TokenKind K) {
1235 unsigned braceDepth = 0;
1236 unsigned squareDepth = 0;
1239 case MMToken::EndOfFile:
1242 case MMToken::LBrace:
1243 if (Tok.is(K) && braceDepth == 0 && squareDepth == 0)
1249 case MMToken::LSquare:
1250 if (Tok.is(K) && braceDepth == 0 && squareDepth == 0)
1256 case MMToken::RBrace:
1263 case MMToken::RSquare:
1264 if (squareDepth > 0)
1271 if (braceDepth == 0 && squareDepth == 0 && Tok.is(K))
1280 /// \brief Parse a module-id.
1284 /// identifier '.' module-id
1286 /// \returns true if an error occurred, false otherwise.
1287 bool ModuleMapParser::parseModuleId(ModuleId &Id) {
1290 if (Tok.is(MMToken::Identifier) || Tok.is(MMToken::StringLiteral)) {
1291 Id.push_back(std::make_pair(Tok.getString(), Tok.getLocation()));
1294 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module_name);
1298 if (!Tok.is(MMToken::Period))
1308 /// \brief Enumerates the known attributes.
1309 enum AttributeKind {
1310 /// \brief An unknown attribute.
1312 /// \brief The 'system' attribute.
1314 /// \brief The 'extern_c' attribute.
1316 /// \brief The 'exhaustive' attribute.
1318 /// \brief The 'no_undeclared_includes' attribute.
1319 AT_no_undeclared_includes
1323 /// \brief Parse a module declaration.
1325 /// module-declaration:
1326 /// 'extern' 'module' module-id string-literal
1327 /// 'explicit'[opt] 'framework'[opt] 'module' module-id attributes[opt]
1328 /// { module-member* }
1331 /// requires-declaration
1332 /// header-declaration
1333 /// submodule-declaration
1334 /// export-declaration
1335 /// link-declaration
1337 /// submodule-declaration:
1338 /// module-declaration
1339 /// inferred-submodule-declaration
1340 void ModuleMapParser::parseModuleDecl() {
1341 assert(Tok.is(MMToken::ExplicitKeyword) || Tok.is(MMToken::ModuleKeyword) ||
1342 Tok.is(MMToken::FrameworkKeyword) || Tok.is(MMToken::ExternKeyword));
1343 if (Tok.is(MMToken::ExternKeyword)) {
1344 parseExternModuleDecl();
1348 // Parse 'explicit' or 'framework' keyword, if present.
1349 SourceLocation ExplicitLoc;
1350 bool Explicit = false;
1351 bool Framework = false;
1353 // Parse 'explicit' keyword, if present.
1354 if (Tok.is(MMToken::ExplicitKeyword)) {
1355 ExplicitLoc = consumeToken();
1359 // Parse 'framework' keyword, if present.
1360 if (Tok.is(MMToken::FrameworkKeyword)) {
1365 // Parse 'module' keyword.
1366 if (!Tok.is(MMToken::ModuleKeyword)) {
1367 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module);
1372 consumeToken(); // 'module' keyword
1374 // If we have a wildcard for the module name, this is an inferred submodule.
1376 if (Tok.is(MMToken::Star))
1377 return parseInferredModuleDecl(Framework, Explicit);
1379 // Parse the module name.
1381 if (parseModuleId(Id)) {
1387 if (Id.size() > 1) {
1388 Diags.Report(Id.front().second, diag::err_mmap_nested_submodule_id)
1389 << SourceRange(Id.front().second, Id.back().second);
1394 } else if (Id.size() == 1 && Explicit) {
1395 // Top-level modules can't be explicit.
1396 Diags.Report(ExplicitLoc, diag::err_mmap_explicit_top_level);
1398 ExplicitLoc = SourceLocation();
1402 Module *PreviousActiveModule = ActiveModule;
1403 if (Id.size() > 1) {
1404 // This module map defines a submodule. Go find the module of which it
1406 ActiveModule = nullptr;
1407 const Module *TopLevelModule = nullptr;
1408 for (unsigned I = 0, N = Id.size() - 1; I != N; ++I) {
1409 if (Module *Next = Map.lookupModuleQualified(Id[I].first, ActiveModule)) {
1411 TopLevelModule = Next;
1412 ActiveModule = Next;
1417 Diags.Report(Id[I].second, diag::err_mmap_missing_module_qualified)
1419 << ActiveModule->getTopLevelModule()->getFullModuleName();
1421 Diags.Report(Id[I].second, diag::err_mmap_expected_module_name);
1427 if (ModuleMapFile != Map.getContainingModuleMapFile(TopLevelModule)) {
1428 assert(ModuleMapFile != Map.getModuleMapFileForUniquing(TopLevelModule) &&
1429 "submodule defined in same file as 'module *' that allowed its "
1430 "top-level module");
1431 Map.addAdditionalModuleMapFile(TopLevelModule, ModuleMapFile);
1435 StringRef ModuleName = Id.back().first;
1436 SourceLocation ModuleNameLoc = Id.back().second;
1438 // Parse the optional attribute list.
1440 if (parseOptionalAttributes(Attrs))
1444 // Parse the opening brace.
1445 if (!Tok.is(MMToken::LBrace)) {
1446 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_lbrace)
1451 SourceLocation LBraceLoc = consumeToken();
1453 // Determine whether this (sub)module has already been defined.
1454 if (Module *Existing = Map.lookupModuleQualified(ModuleName, ActiveModule)) {
1455 // We might see a (re)definition of a module that we already have a
1456 // definition for in two cases:
1457 // - If we loaded one definition from an AST file and we've just found a
1458 // corresponding definition in a module map file, or
1459 bool LoadedFromASTFile = Existing->DefinitionLoc.isInvalid();
1460 // - If we're building a (preprocessed) module and we've just loaded the
1461 // module map file from which it was created.
1462 bool ParsedAsMainInput =
1463 Map.LangOpts.getCompilingModule() == LangOptions::CMK_ModuleMap &&
1464 Map.LangOpts.CurrentModule == ModuleName &&
1465 SourceMgr.getDecomposedLoc(ModuleNameLoc).first !=
1466 SourceMgr.getDecomposedLoc(Existing->DefinitionLoc).first;
1467 if (!ActiveModule && (LoadedFromASTFile || ParsedAsMainInput)) {
1468 // Skip the module definition.
1469 skipUntil(MMToken::RBrace);
1470 if (Tok.is(MMToken::RBrace))
1473 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
1474 Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
1480 Diags.Report(ModuleNameLoc, diag::err_mmap_module_redefinition)
1482 Diags.Report(Existing->DefinitionLoc, diag::note_mmap_prev_definition);
1484 // Skip the module definition.
1485 skipUntil(MMToken::RBrace);
1486 if (Tok.is(MMToken::RBrace))
1493 // Start defining this module.
1494 ActiveModule = Map.findOrCreateModule(ModuleName, ActiveModule, Framework,
1496 ActiveModule->DefinitionLoc = ModuleNameLoc;
1497 if (Attrs.IsSystem || IsSystem)
1498 ActiveModule->IsSystem = true;
1499 if (Attrs.IsExternC)
1500 ActiveModule->IsExternC = true;
1501 if (Attrs.NoUndeclaredIncludes ||
1502 (!ActiveModule->Parent && ModuleName == "Darwin"))
1503 ActiveModule->NoUndeclaredIncludes = true;
1504 ActiveModule->Directory = Directory;
1506 if (!ActiveModule->Parent) {
1507 StringRef MapFileName(ModuleMapFile->getName());
1508 if (MapFileName.endswith("module.private.modulemap") ||
1509 MapFileName.endswith("module_private.map")) {
1510 // Adding a top-level module from a private modulemap is likely a
1511 // user error; we check to see if there's another top-level module
1512 // defined in the non-private map in the same dir, and if so emit a
1514 for (auto E = Map.module_begin(); E != Map.module_end(); ++E) {
1515 auto const *M = E->getValue();
1517 M->Directory == ActiveModule->Directory &&
1518 M->Name != ActiveModule->Name) {
1519 Diags.Report(ActiveModule->DefinitionLoc,
1520 diag::warn_mmap_mismatched_top_level_private)
1521 << ActiveModule->Name << M->Name;
1522 // The pattern we're defending against here is typically due to
1523 // a module named FooPrivate which is supposed to be a submodule
1524 // called Foo.Private. Emit a fixit in that case.
1526 Diags.Report(ActiveModule->DefinitionLoc,
1527 diag::note_mmap_rename_top_level_private_as_submodule);
1528 D << ActiveModule->Name << M->Name;
1529 StringRef Bad(ActiveModule->Name);
1530 if (Bad.consume_back("Private")) {
1531 SmallString<128> Fixed = Bad;
1532 Fixed.append(".Private");
1533 D << FixItHint::CreateReplacement(ActiveModule->DefinitionLoc,
1545 case MMToken::EndOfFile:
1546 case MMToken::RBrace:
1550 case MMToken::ConfigMacros:
1551 parseConfigMacros();
1554 case MMToken::Conflict:
1558 case MMToken::ExplicitKeyword:
1559 case MMToken::ExternKeyword:
1560 case MMToken::FrameworkKeyword:
1561 case MMToken::ModuleKeyword:
1565 case MMToken::ExportKeyword:
1569 case MMToken::UseKeyword:
1573 case MMToken::RequiresKeyword:
1574 parseRequiresDecl();
1577 case MMToken::TextualKeyword:
1578 parseHeaderDecl(MMToken::TextualKeyword, consumeToken());
1581 case MMToken::UmbrellaKeyword: {
1582 SourceLocation UmbrellaLoc = consumeToken();
1583 if (Tok.is(MMToken::HeaderKeyword))
1584 parseHeaderDecl(MMToken::UmbrellaKeyword, UmbrellaLoc);
1586 parseUmbrellaDirDecl(UmbrellaLoc);
1590 case MMToken::ExcludeKeyword:
1591 parseHeaderDecl(MMToken::ExcludeKeyword, consumeToken());
1594 case MMToken::PrivateKeyword:
1595 parseHeaderDecl(MMToken::PrivateKeyword, consumeToken());
1598 case MMToken::HeaderKeyword:
1599 parseHeaderDecl(MMToken::HeaderKeyword, consumeToken());
1602 case MMToken::LinkKeyword:
1607 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_member);
1613 if (Tok.is(MMToken::RBrace))
1616 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
1617 Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
1621 // If the active module is a top-level framework, and there are no link
1622 // libraries, automatically link against the framework.
1623 if (ActiveModule->IsFramework && !ActiveModule->isSubFramework() &&
1624 ActiveModule->LinkLibraries.empty()) {
1625 inferFrameworkLink(ActiveModule, Directory, SourceMgr.getFileManager());
1628 // If the module meets all requirements but is still unavailable, mark the
1629 // whole tree as unavailable to prevent it from building.
1630 if (!ActiveModule->IsAvailable && !ActiveModule->IsMissingRequirement &&
1631 ActiveModule->Parent) {
1632 ActiveModule->getTopLevelModule()->markUnavailable();
1633 ActiveModule->getTopLevelModule()->MissingHeaders.append(
1634 ActiveModule->MissingHeaders.begin(), ActiveModule->MissingHeaders.end());
1637 // We're done parsing this module. Pop back to the previous module.
1638 ActiveModule = PreviousActiveModule;
1641 /// \brief Parse an extern module declaration.
1643 /// extern module-declaration:
1644 /// 'extern' 'module' module-id string-literal
1645 void ModuleMapParser::parseExternModuleDecl() {
1646 assert(Tok.is(MMToken::ExternKeyword));
1647 SourceLocation ExternLoc = consumeToken(); // 'extern' keyword
1649 // Parse 'module' keyword.
1650 if (!Tok.is(MMToken::ModuleKeyword)) {
1651 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module);
1656 consumeToken(); // 'module' keyword
1658 // Parse the module name.
1660 if (parseModuleId(Id)) {
1665 // Parse the referenced module map file name.
1666 if (!Tok.is(MMToken::StringLiteral)) {
1667 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_mmap_file);
1671 std::string FileName = Tok.getString();
1672 consumeToken(); // filename
1674 StringRef FileNameRef = FileName;
1675 SmallString<128> ModuleMapFileName;
1676 if (llvm::sys::path::is_relative(FileNameRef)) {
1677 ModuleMapFileName += Directory->getName();
1678 llvm::sys::path::append(ModuleMapFileName, FileName);
1679 FileNameRef = ModuleMapFileName;
1681 if (const FileEntry *File = SourceMgr.getFileManager().getFile(FileNameRef))
1682 Map.parseModuleMapFile(
1683 File, /*IsSystem=*/false,
1684 Map.HeaderInfo.getHeaderSearchOpts().ModuleMapFileHomeIsCwd
1687 FileID(), nullptr, ExternLoc);
1690 /// Whether to add the requirement \p Feature to the module \p M.
1692 /// This preserves backwards compatibility for two hacks in the Darwin system
1693 /// module map files:
1695 /// 1. The use of 'requires excluded' to make headers non-modular, which
1696 /// should really be mapped to 'textual' now that we have this feature. We
1697 /// drop the 'excluded' requirement, and set \p IsRequiresExcludedHack to
1698 /// true. Later, this bit will be used to map all the headers inside this
1699 /// module to 'textual'.
1701 /// This affects Darwin.C.excluded (for assert.h) and Tcl.Private.
1703 /// 2. Removes a bogus cplusplus requirement from IOKit.avc. This requirement
1704 /// was never correct and causes issues now that we check it, so drop it.
1705 static bool shouldAddRequirement(Module *M, StringRef Feature,
1706 bool &IsRequiresExcludedHack) {
1707 if (Feature == "excluded" &&
1708 (M->fullModuleNameIs({"Darwin", "C", "excluded"}) ||
1709 M->fullModuleNameIs({"Tcl", "Private"}))) {
1710 IsRequiresExcludedHack = true;
1712 } else if (Feature == "cplusplus" && M->fullModuleNameIs({"IOKit", "avc"})) {
1719 /// \brief Parse a requires declaration.
1721 /// requires-declaration:
1722 /// 'requires' feature-list
1725 /// feature ',' feature-list
1729 /// '!'[opt] identifier
1730 void ModuleMapParser::parseRequiresDecl() {
1731 assert(Tok.is(MMToken::RequiresKeyword));
1733 // Parse 'requires' keyword.
1736 // Parse the feature-list.
1738 bool RequiredState = true;
1739 if (Tok.is(MMToken::Exclaim)) {
1740 RequiredState = false;
1744 if (!Tok.is(MMToken::Identifier)) {
1745 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_feature);
1750 // Consume the feature name.
1751 std::string Feature = Tok.getString();
1754 bool IsRequiresExcludedHack = false;
1755 bool ShouldAddRequirement =
1756 shouldAddRequirement(ActiveModule, Feature, IsRequiresExcludedHack);
1758 if (IsRequiresExcludedHack)
1759 UsesRequiresExcludedHack.insert(ActiveModule);
1761 if (ShouldAddRequirement) {
1762 // Add this feature.
1763 ActiveModule->addRequirement(Feature, RequiredState, Map.LangOpts,
1767 if (!Tok.is(MMToken::Comma))
1770 // Consume the comma.
1775 /// \brief Append to \p Paths the set of paths needed to get to the
1776 /// subframework in which the given module lives.
1777 static void appendSubframeworkPaths(Module *Mod,
1778 SmallVectorImpl<char> &Path) {
1779 // Collect the framework names from the given module to the top-level module.
1780 SmallVector<StringRef, 2> Paths;
1781 for (; Mod; Mod = Mod->Parent) {
1782 if (Mod->IsFramework)
1783 Paths.push_back(Mod->Name);
1789 // Add Frameworks/Name.framework for each subframework.
1790 for (unsigned I = Paths.size() - 1; I != 0; --I)
1791 llvm::sys::path::append(Path, "Frameworks", Paths[I-1] + ".framework");
1794 /// \brief Parse a header declaration.
1796 /// header-declaration:
1797 /// 'textual'[opt] 'header' string-literal
1798 /// 'private' 'textual'[opt] 'header' string-literal
1799 /// 'exclude' 'header' string-literal
1800 /// 'umbrella' 'header' string-literal
1802 /// FIXME: Support 'private textual header'.
1803 void ModuleMapParser::parseHeaderDecl(MMToken::TokenKind LeadingToken,
1804 SourceLocation LeadingLoc) {
1805 // We've already consumed the first token.
1806 ModuleMap::ModuleHeaderRole Role = ModuleMap::NormalHeader;
1807 if (LeadingToken == MMToken::PrivateKeyword) {
1808 Role = ModuleMap::PrivateHeader;
1809 // 'private' may optionally be followed by 'textual'.
1810 if (Tok.is(MMToken::TextualKeyword)) {
1811 LeadingToken = Tok.Kind;
1816 if (LeadingToken == MMToken::TextualKeyword)
1817 Role = ModuleMap::ModuleHeaderRole(Role | ModuleMap::TextualHeader);
1819 if (UsesRequiresExcludedHack.count(ActiveModule)) {
1820 // Mark this header 'textual' (see doc comment for
1821 // Module::UsesRequiresExcludedHack).
1822 Role = ModuleMap::ModuleHeaderRole(Role | ModuleMap::TextualHeader);
1825 if (LeadingToken != MMToken::HeaderKeyword) {
1826 if (!Tok.is(MMToken::HeaderKeyword)) {
1827 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
1828 << (LeadingToken == MMToken::PrivateKeyword ? "private" :
1829 LeadingToken == MMToken::ExcludeKeyword ? "exclude" :
1830 LeadingToken == MMToken::TextualKeyword ? "textual" : "umbrella");
1836 // Parse the header name.
1837 if (!Tok.is(MMToken::StringLiteral)) {
1838 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
1843 Module::UnresolvedHeaderDirective Header;
1844 Header.FileName = Tok.getString();
1845 Header.FileNameLoc = consumeToken();
1847 // Check whether we already have an umbrella.
1848 if (LeadingToken == MMToken::UmbrellaKeyword && ActiveModule->Umbrella) {
1849 Diags.Report(Header.FileNameLoc, diag::err_mmap_umbrella_clash)
1850 << ActiveModule->getFullModuleName();
1855 // Look for this file.
1856 const FileEntry *File = nullptr;
1857 const FileEntry *BuiltinFile = nullptr;
1858 SmallString<128> RelativePathName;
1859 if (llvm::sys::path::is_absolute(Header.FileName)) {
1860 RelativePathName = Header.FileName;
1861 File = SourceMgr.getFileManager().getFile(RelativePathName);
1863 // Search for the header file within the search directory.
1864 SmallString<128> FullPathName(Directory->getName());
1865 unsigned FullPathLength = FullPathName.size();
1867 if (ActiveModule->isPartOfFramework()) {
1868 appendSubframeworkPaths(ActiveModule, RelativePathName);
1869 unsigned RelativePathLength = RelativePathName.size();
1871 // Check whether this file is in the public headers.
1872 llvm::sys::path::append(RelativePathName, "Headers", Header.FileName);
1873 llvm::sys::path::append(FullPathName, RelativePathName);
1874 File = SourceMgr.getFileManager().getFile(FullPathName);
1876 // Check whether this file is in the private headers.
1878 // Ideally, private modules in the form 'FrameworkName.Private' should
1879 // be defined as 'module FrameworkName.Private', and not as
1880 // 'framework module FrameworkName.Private', since a 'Private.Framework'
1881 // does not usually exist. However, since both are currently widely used
1882 // for private modules, make sure we find the right path in both cases.
1883 if (ActiveModule->IsFramework && ActiveModule->Name == "Private")
1884 RelativePathName.clear();
1886 RelativePathName.resize(RelativePathLength);
1887 FullPathName.resize(FullPathLength);
1888 llvm::sys::path::append(RelativePathName, "PrivateHeaders",
1890 llvm::sys::path::append(FullPathName, RelativePathName);
1891 File = SourceMgr.getFileManager().getFile(FullPathName);
1894 // Lookup for normal headers.
1895 llvm::sys::path::append(RelativePathName, Header.FileName);
1896 llvm::sys::path::append(FullPathName, RelativePathName);
1897 File = SourceMgr.getFileManager().getFile(FullPathName);
1899 // If this is a system module with a top-level header, this header
1900 // may have a counterpart (or replacement) in the set of headers
1901 // supplied by Clang. Find that builtin header.
1902 if (ActiveModule->IsSystem && LeadingToken != MMToken::UmbrellaKeyword &&
1903 BuiltinIncludeDir && BuiltinIncludeDir != Directory &&
1904 ModuleMap::isBuiltinHeader(Header.FileName)) {
1905 SmallString<128> BuiltinPathName(BuiltinIncludeDir->getName());
1906 llvm::sys::path::append(BuiltinPathName, Header.FileName);
1907 BuiltinFile = SourceMgr.getFileManager().getFile(BuiltinPathName);
1909 // If Clang supplies this header but the underlying system does not,
1910 // just silently swap in our builtin version. Otherwise, we'll end
1911 // up adding both (later).
1912 if (BuiltinFile && !File) {
1914 RelativePathName = BuiltinPathName;
1915 BuiltinFile = nullptr;
1921 // FIXME: We shouldn't be eagerly stat'ing every file named in a module map.
1922 // Come up with a lazy way to do this.
1924 if (LeadingToken == MMToken::UmbrellaKeyword) {
1925 const DirectoryEntry *UmbrellaDir = File->getDir();
1926 if (Module *UmbrellaModule = Map.UmbrellaDirs[UmbrellaDir]) {
1927 Diags.Report(LeadingLoc, diag::err_mmap_umbrella_clash)
1928 << UmbrellaModule->getFullModuleName();
1931 // Record this umbrella header.
1932 Map.setUmbrellaHeader(ActiveModule, File, RelativePathName.str());
1934 } else if (LeadingToken == MMToken::ExcludeKeyword) {
1935 Module::Header H = {RelativePathName.str(), File};
1936 Map.excludeHeader(ActiveModule, H);
1938 // If there is a builtin counterpart to this file, add it now so it can
1939 // wrap the system header.
1941 // FIXME: Taking the name from the FileEntry is unstable and can give
1942 // different results depending on how we've previously named that file
1944 Module::Header H = { BuiltinFile->getName(), BuiltinFile };
1945 Map.addHeader(ActiveModule, H, Role);
1947 // If we have both a builtin and system version of the file, the
1948 // builtin version may want to inject macros into the system header, so
1949 // force the system header to be treated as a textual header in this
1951 Role = ModuleMap::ModuleHeaderRole(Role | ModuleMap::TextualHeader);
1954 // Record this header.
1955 Module::Header H = { RelativePathName.str(), File };
1956 Map.addHeader(ActiveModule, H, Role);
1958 } else if (LeadingToken != MMToken::ExcludeKeyword) {
1959 // Ignore excluded header files. They're optional anyway.
1961 // If we find a module that has a missing header, we mark this module as
1962 // unavailable and store the header directive for displaying diagnostics.
1963 Header.IsUmbrella = LeadingToken == MMToken::UmbrellaKeyword;
1964 ActiveModule->markUnavailable();
1965 ActiveModule->MissingHeaders.push_back(Header);
1969 static int compareModuleHeaders(const Module::Header *A,
1970 const Module::Header *B) {
1971 return A->NameAsWritten.compare(B->NameAsWritten);
1974 /// \brief Parse an umbrella directory declaration.
1976 /// umbrella-dir-declaration:
1977 /// umbrella string-literal
1978 void ModuleMapParser::parseUmbrellaDirDecl(SourceLocation UmbrellaLoc) {
1979 // Parse the directory name.
1980 if (!Tok.is(MMToken::StringLiteral)) {
1981 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
1987 std::string DirName = Tok.getString();
1988 SourceLocation DirNameLoc = consumeToken();
1990 // Check whether we already have an umbrella.
1991 if (ActiveModule->Umbrella) {
1992 Diags.Report(DirNameLoc, diag::err_mmap_umbrella_clash)
1993 << ActiveModule->getFullModuleName();
1998 // Look for this file.
1999 const DirectoryEntry *Dir = nullptr;
2000 if (llvm::sys::path::is_absolute(DirName))
2001 Dir = SourceMgr.getFileManager().getDirectory(DirName);
2003 SmallString<128> PathName;
2004 PathName = Directory->getName();
2005 llvm::sys::path::append(PathName, DirName);
2006 Dir = SourceMgr.getFileManager().getDirectory(PathName);
2010 Diags.Report(DirNameLoc, diag::warn_mmap_umbrella_dir_not_found)
2015 if (UsesRequiresExcludedHack.count(ActiveModule)) {
2016 // Mark this header 'textual' (see doc comment for
2017 // ModuleMapParser::UsesRequiresExcludedHack). Although iterating over the
2018 // directory is relatively expensive, in practice this only applies to the
2019 // uncommonly used Tcl module on Darwin platforms.
2021 SmallVector<Module::Header, 6> Headers;
2022 vfs::FileSystem &FS = *SourceMgr.getFileManager().getVirtualFileSystem();
2023 for (vfs::recursive_directory_iterator I(FS, Dir->getName(), EC), E;
2024 I != E && !EC; I.increment(EC)) {
2025 if (const FileEntry *FE =
2026 SourceMgr.getFileManager().getFile(I->getName())) {
2028 Module::Header Header = {I->getName(), FE};
2029 Headers.push_back(std::move(Header));
2033 // Sort header paths so that the pcm doesn't depend on iteration order.
2034 llvm::array_pod_sort(Headers.begin(), Headers.end(), compareModuleHeaders);
2036 for (auto &Header : Headers)
2037 Map.addHeader(ActiveModule, std::move(Header), ModuleMap::TextualHeader);
2041 if (Module *OwningModule = Map.UmbrellaDirs[Dir]) {
2042 Diags.Report(UmbrellaLoc, diag::err_mmap_umbrella_clash)
2043 << OwningModule->getFullModuleName();
2048 // Record this umbrella directory.
2049 Map.setUmbrellaDir(ActiveModule, Dir, DirName);
2052 /// \brief Parse a module export declaration.
2054 /// export-declaration:
2055 /// 'export' wildcard-module-id
2057 /// wildcard-module-id:
2060 /// identifier '.' wildcard-module-id
2061 void ModuleMapParser::parseExportDecl() {
2062 assert(Tok.is(MMToken::ExportKeyword));
2063 SourceLocation ExportLoc = consumeToken();
2065 // Parse the module-id with an optional wildcard at the end.
2066 ModuleId ParsedModuleId;
2067 bool Wildcard = false;
2069 // FIXME: Support string-literal module names here.
2070 if (Tok.is(MMToken::Identifier)) {
2071 ParsedModuleId.push_back(std::make_pair(Tok.getString(),
2072 Tok.getLocation()));
2075 if (Tok.is(MMToken::Period)) {
2083 if(Tok.is(MMToken::Star)) {
2089 Diags.Report(Tok.getLocation(), diag::err_mmap_module_id);
2094 Module::UnresolvedExportDecl Unresolved = {
2095 ExportLoc, ParsedModuleId, Wildcard
2097 ActiveModule->UnresolvedExports.push_back(Unresolved);
2100 /// \brief Parse a module use declaration.
2102 /// use-declaration:
2103 /// 'use' wildcard-module-id
2104 void ModuleMapParser::parseUseDecl() {
2105 assert(Tok.is(MMToken::UseKeyword));
2106 auto KWLoc = consumeToken();
2107 // Parse the module-id.
2108 ModuleId ParsedModuleId;
2109 parseModuleId(ParsedModuleId);
2111 if (ActiveModule->Parent)
2112 Diags.Report(KWLoc, diag::err_mmap_use_decl_submodule);
2114 ActiveModule->UnresolvedDirectUses.push_back(ParsedModuleId);
2117 /// \brief Parse a link declaration.
2119 /// module-declaration:
2120 /// 'link' 'framework'[opt] string-literal
2121 void ModuleMapParser::parseLinkDecl() {
2122 assert(Tok.is(MMToken::LinkKeyword));
2123 SourceLocation LinkLoc = consumeToken();
2125 // Parse the optional 'framework' keyword.
2126 bool IsFramework = false;
2127 if (Tok.is(MMToken::FrameworkKeyword)) {
2132 // Parse the library name
2133 if (!Tok.is(MMToken::StringLiteral)) {
2134 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_library_name)
2135 << IsFramework << SourceRange(LinkLoc);
2140 std::string LibraryName = Tok.getString();
2142 ActiveModule->LinkLibraries.push_back(Module::LinkLibrary(LibraryName,
2146 /// \brief Parse a configuration macro declaration.
2148 /// module-declaration:
2149 /// 'config_macros' attributes[opt] config-macro-list?
2151 /// config-macro-list:
2152 /// identifier (',' identifier)?
2153 void ModuleMapParser::parseConfigMacros() {
2154 assert(Tok.is(MMToken::ConfigMacros));
2155 SourceLocation ConfigMacrosLoc = consumeToken();
2157 // Only top-level modules can have configuration macros.
2158 if (ActiveModule->Parent) {
2159 Diags.Report(ConfigMacrosLoc, diag::err_mmap_config_macro_submodule);
2162 // Parse the optional attributes.
2164 if (parseOptionalAttributes(Attrs))
2167 if (Attrs.IsExhaustive && !ActiveModule->Parent) {
2168 ActiveModule->ConfigMacrosExhaustive = true;
2171 // If we don't have an identifier, we're done.
2172 // FIXME: Support macros with the same name as a keyword here.
2173 if (!Tok.is(MMToken::Identifier))
2176 // Consume the first identifier.
2177 if (!ActiveModule->Parent) {
2178 ActiveModule->ConfigMacros.push_back(Tok.getString().str());
2183 // If there's a comma, consume it.
2184 if (!Tok.is(MMToken::Comma))
2188 // We expect to see a macro name here.
2189 // FIXME: Support macros with the same name as a keyword here.
2190 if (!Tok.is(MMToken::Identifier)) {
2191 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_config_macro);
2195 // Consume the macro name.
2196 if (!ActiveModule->Parent) {
2197 ActiveModule->ConfigMacros.push_back(Tok.getString().str());
2203 /// \brief Format a module-id into a string.
2204 static std::string formatModuleId(const ModuleId &Id) {
2207 llvm::raw_string_ostream OS(result);
2209 for (unsigned I = 0, N = Id.size(); I != N; ++I) {
2219 /// \brief Parse a conflict declaration.
2221 /// module-declaration:
2222 /// 'conflict' module-id ',' string-literal
2223 void ModuleMapParser::parseConflict() {
2224 assert(Tok.is(MMToken::Conflict));
2225 SourceLocation ConflictLoc = consumeToken();
2226 Module::UnresolvedConflict Conflict;
2228 // Parse the module-id.
2229 if (parseModuleId(Conflict.Id))
2233 if (!Tok.is(MMToken::Comma)) {
2234 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_conflicts_comma)
2235 << SourceRange(ConflictLoc);
2240 // Parse the message.
2241 if (!Tok.is(MMToken::StringLiteral)) {
2242 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_conflicts_message)
2243 << formatModuleId(Conflict.Id);
2246 Conflict.Message = Tok.getString().str();
2249 // Add this unresolved conflict.
2250 ActiveModule->UnresolvedConflicts.push_back(Conflict);
2253 /// \brief Parse an inferred module declaration (wildcard modules).
2255 /// module-declaration:
2256 /// 'explicit'[opt] 'framework'[opt] 'module' * attributes[opt]
2257 /// { inferred-module-member* }
2259 /// inferred-module-member:
2261 /// 'exclude' identifier
2262 void ModuleMapParser::parseInferredModuleDecl(bool Framework, bool Explicit) {
2263 assert(Tok.is(MMToken::Star));
2264 SourceLocation StarLoc = consumeToken();
2265 bool Failed = false;
2267 // Inferred modules must be submodules.
2268 if (!ActiveModule && !Framework) {
2269 Diags.Report(StarLoc, diag::err_mmap_top_level_inferred_submodule);
2274 // Inferred modules must have umbrella directories.
2275 if (!Failed && ActiveModule->IsAvailable &&
2276 !ActiveModule->getUmbrellaDir()) {
2277 Diags.Report(StarLoc, diag::err_mmap_inferred_no_umbrella);
2281 // Check for redefinition of an inferred module.
2282 if (!Failed && ActiveModule->InferSubmodules) {
2283 Diags.Report(StarLoc, diag::err_mmap_inferred_redef);
2284 if (ActiveModule->InferredSubmoduleLoc.isValid())
2285 Diags.Report(ActiveModule->InferredSubmoduleLoc,
2286 diag::note_mmap_prev_definition);
2290 // Check for the 'framework' keyword, which is not permitted here.
2292 Diags.Report(StarLoc, diag::err_mmap_inferred_framework_submodule);
2295 } else if (Explicit) {
2296 Diags.Report(StarLoc, diag::err_mmap_explicit_inferred_framework);
2300 // If there were any problems with this inferred submodule, skip its body.
2302 if (Tok.is(MMToken::LBrace)) {
2304 skipUntil(MMToken::RBrace);
2305 if (Tok.is(MMToken::RBrace))
2312 // Parse optional attributes.
2314 if (parseOptionalAttributes(Attrs))
2318 // Note that we have an inferred submodule.
2319 ActiveModule->InferSubmodules = true;
2320 ActiveModule->InferredSubmoduleLoc = StarLoc;
2321 ActiveModule->InferExplicitSubmodules = Explicit;
2323 // We'll be inferring framework modules for this directory.
2324 Map.InferredDirectories[Directory].InferModules = true;
2325 Map.InferredDirectories[Directory].Attrs = Attrs;
2326 Map.InferredDirectories[Directory].ModuleMapFile = ModuleMapFile;
2327 // FIXME: Handle the 'framework' keyword.
2330 // Parse the opening brace.
2331 if (!Tok.is(MMToken::LBrace)) {
2332 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_lbrace_wildcard);
2336 SourceLocation LBraceLoc = consumeToken();
2338 // Parse the body of the inferred submodule.
2342 case MMToken::EndOfFile:
2343 case MMToken::RBrace:
2347 case MMToken::ExcludeKeyword: {
2349 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member)
2350 << (ActiveModule != nullptr);
2356 // FIXME: Support string-literal module names here.
2357 if (!Tok.is(MMToken::Identifier)) {
2358 Diags.Report(Tok.getLocation(), diag::err_mmap_missing_exclude_name);
2362 Map.InferredDirectories[Directory].ExcludedModules
2363 .push_back(Tok.getString());
2368 case MMToken::ExportKeyword:
2369 if (!ActiveModule) {
2370 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member)
2371 << (ActiveModule != nullptr);
2377 if (Tok.is(MMToken::Star))
2378 ActiveModule->InferExportWildcard = true;
2380 Diags.Report(Tok.getLocation(),
2381 diag::err_mmap_expected_export_wildcard);
2385 case MMToken::ExplicitKeyword:
2386 case MMToken::ModuleKeyword:
2387 case MMToken::HeaderKeyword:
2388 case MMToken::PrivateKeyword:
2389 case MMToken::UmbrellaKeyword:
2391 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member)
2392 << (ActiveModule != nullptr);
2398 if (Tok.is(MMToken::RBrace))
2401 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
2402 Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
2407 /// \brief Parse optional attributes.
2410 /// attribute attributes
2416 /// \param Attrs Will be filled in with the parsed attributes.
2418 /// \returns true if an error occurred, false otherwise.
2419 bool ModuleMapParser::parseOptionalAttributes(Attributes &Attrs) {
2420 bool HadError = false;
2422 while (Tok.is(MMToken::LSquare)) {
2424 SourceLocation LSquareLoc = consumeToken();
2426 // Check whether we have an attribute name here.
2427 if (!Tok.is(MMToken::Identifier)) {
2428 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_attribute);
2429 skipUntil(MMToken::RSquare);
2430 if (Tok.is(MMToken::RSquare))
2435 // Decode the attribute name.
2436 AttributeKind Attribute
2437 = llvm::StringSwitch<AttributeKind>(Tok.getString())
2438 .Case("exhaustive", AT_exhaustive)
2439 .Case("extern_c", AT_extern_c)
2440 .Case("no_undeclared_includes", AT_no_undeclared_includes)
2441 .Case("system", AT_system)
2442 .Default(AT_unknown);
2443 switch (Attribute) {
2445 Diags.Report(Tok.getLocation(), diag::warn_mmap_unknown_attribute)
2450 Attrs.IsSystem = true;
2454 Attrs.IsExternC = true;
2458 Attrs.IsExhaustive = true;
2461 case AT_no_undeclared_includes:
2462 Attrs.NoUndeclaredIncludes = true;
2468 if (!Tok.is(MMToken::RSquare)) {
2469 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rsquare);
2470 Diags.Report(LSquareLoc, diag::note_mmap_lsquare_match);
2471 skipUntil(MMToken::RSquare);
2475 if (Tok.is(MMToken::RSquare))
2482 /// \brief Parse a module map file.
2484 /// module-map-file:
2485 /// module-declaration*
2486 bool ModuleMapParser::parseModuleMapFile() {
2489 case MMToken::EndOfFile:
2492 case MMToken::ExplicitKeyword:
2493 case MMToken::ExternKeyword:
2494 case MMToken::ModuleKeyword:
2495 case MMToken::FrameworkKeyword:
2499 case MMToken::Comma:
2500 case MMToken::ConfigMacros:
2501 case MMToken::Conflict:
2502 case MMToken::Exclaim:
2503 case MMToken::ExcludeKeyword:
2504 case MMToken::ExportKeyword:
2505 case MMToken::HeaderKeyword:
2506 case MMToken::Identifier:
2507 case MMToken::LBrace:
2508 case MMToken::LinkKeyword:
2509 case MMToken::LSquare:
2510 case MMToken::Period:
2511 case MMToken::PrivateKeyword:
2512 case MMToken::RBrace:
2513 case MMToken::RSquare:
2514 case MMToken::RequiresKeyword:
2516 case MMToken::StringLiteral:
2517 case MMToken::TextualKeyword:
2518 case MMToken::UmbrellaKeyword:
2519 case MMToken::UseKeyword:
2520 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module);
2528 bool ModuleMap::parseModuleMapFile(const FileEntry *File, bool IsSystem,
2529 const DirectoryEntry *Dir, FileID ID,
2531 SourceLocation ExternModuleLoc) {
2532 assert(Target && "Missing target information");
2533 llvm::DenseMap<const FileEntry *, bool>::iterator Known
2534 = ParsedModuleMap.find(File);
2535 if (Known != ParsedModuleMap.end())
2536 return Known->second;
2538 // If the module map file wasn't already entered, do so now.
2539 if (ID.isInvalid()) {
2540 auto FileCharacter = IsSystem ? SrcMgr::C_System : SrcMgr::C_User;
2541 ID = SourceMgr.createFileID(File, ExternModuleLoc, FileCharacter);
2544 assert(Target && "Missing target information");
2545 const llvm::MemoryBuffer *Buffer = SourceMgr.getBuffer(ID);
2547 return ParsedModuleMap[File] = true;
2548 assert((!Offset || *Offset <= Buffer->getBufferSize()) &&
2549 "invalid buffer offset");
2551 // Parse this module map file.
2552 Lexer L(SourceMgr.getLocForStartOfFile(ID), MMapLangOpts,
2553 Buffer->getBufferStart(),
2554 Buffer->getBufferStart() + (Offset ? *Offset : 0),
2555 Buffer->getBufferEnd());
2556 SourceLocation Start = L.getSourceLocation();
2557 ModuleMapParser Parser(L, SourceMgr, Target, Diags, *this, File, Dir,
2558 BuiltinIncludeDir, IsSystem);
2559 bool Result = Parser.parseModuleMapFile();
2560 ParsedModuleMap[File] = Result;
2563 auto Loc = SourceMgr.getDecomposedLoc(Parser.getLocation());
2564 assert(Loc.first == ID && "stopped in a different file?");
2565 *Offset = Loc.second;
2568 // Notify callbacks that we parsed it.
2569 for (const auto &Cb : Callbacks)
2570 Cb->moduleMapFileRead(Start, *File, IsSystem);