1 //===- ModuleMap.cpp - Describe the layout of modules ---------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file defines the ModuleMap implementation, which describes the layout 11 // of a module as it relates to headers. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "clang/Lex/ModuleMap.h" 16 #include "clang/Basic/CharInfo.h" 17 #include "clang/Basic/Diagnostic.h" 18 #include "clang/Basic/FileManager.h" 19 #include "clang/Basic/LLVM.h" 20 #include "clang/Basic/LangOptions.h" 21 #include "clang/Basic/Module.h" 22 #include "clang/Basic/SourceLocation.h" 23 #include "clang/Basic/SourceManager.h" 24 #include "clang/Basic/TargetInfo.h" 25 #include "clang/Basic/VirtualFileSystem.h" 26 #include "clang/Lex/HeaderSearch.h" 27 #include "clang/Lex/HeaderSearchOptions.h" 28 #include "clang/Lex/LexDiagnostic.h" 29 #include "clang/Lex/Lexer.h" 30 #include "clang/Lex/LiteralSupport.h" 31 #include "clang/Lex/Token.h" 32 #include "llvm/ADT/DenseMap.h" 33 #include "llvm/ADT/None.h" 34 #include "llvm/ADT/STLExtras.h" 35 #include "llvm/ADT/SmallPtrSet.h" 36 #include "llvm/ADT/SmallString.h" 37 #include "llvm/ADT/SmallVector.h" 38 #include "llvm/ADT/StringMap.h" 39 #include "llvm/ADT/StringRef.h" 40 #include "llvm/ADT/StringSwitch.h" 41 #include "llvm/Support/Allocator.h" 42 #include "llvm/Support/Compiler.h" 43 #include "llvm/Support/ErrorHandling.h" 44 #include "llvm/Support/MemoryBuffer.h" 45 #include "llvm/Support/Path.h" 46 #include "llvm/Support/raw_ostream.h" 47 #include <algorithm> 48 #include <cassert> 49 #include <cstdint> 50 #include <cstring> 51 #include <string> 52 #include <system_error> 53 #include <utility> 54 55 using namespace clang; 56 57 void ModuleMap::resolveLinkAsDependencies(Module *Mod) { 58 auto PendingLinkAs = PendingLinkAsModule.find(Mod->Name); 59 if (PendingLinkAs != PendingLinkAsModule.end()) { 60 for (auto &Name : PendingLinkAs->second) { 61 auto *M = findModule(Name.getKey()); 62 if (M) 63 M->UseExportAsModuleLinkName = true; 64 } 65 } 66 } 67 68 void ModuleMap::addLinkAsDependency(Module *Mod) { 69 if (findModule(Mod->ExportAsModule)) 70 Mod->UseExportAsModuleLinkName = true; 71 else 72 PendingLinkAsModule[Mod->ExportAsModule].insert(Mod->Name); 73 } 74 75 Module::HeaderKind ModuleMap::headerRoleToKind(ModuleHeaderRole Role) { 76 switch ((int)Role) { 77 default: llvm_unreachable("unknown header role"); 78 case NormalHeader: 79 return Module::HK_Normal; 80 case PrivateHeader: 81 return Module::HK_Private; 82 case TextualHeader: 83 return Module::HK_Textual; 84 case PrivateHeader | TextualHeader: 85 return Module::HK_PrivateTextual; 86 } 87 } 88 89 ModuleMap::ModuleHeaderRole 90 ModuleMap::headerKindToRole(Module::HeaderKind Kind) { 91 switch ((int)Kind) { 92 case Module::HK_Normal: 93 return NormalHeader; 94 case Module::HK_Private: 95 return PrivateHeader; 96 case Module::HK_Textual: 97 return TextualHeader; 98 case Module::HK_PrivateTextual: 99 return ModuleHeaderRole(PrivateHeader | TextualHeader); 100 case Module::HK_Excluded: 101 llvm_unreachable("unexpected header kind"); 102 } 103 llvm_unreachable("unknown header kind"); 104 } 105 106 Module::ExportDecl 107 ModuleMap::resolveExport(Module *Mod, 108 const Module::UnresolvedExportDecl &Unresolved, 109 bool Complain) const { 110 // We may have just a wildcard. 111 if (Unresolved.Id.empty()) { 112 assert(Unresolved.Wildcard && "Invalid unresolved export"); 113 return Module::ExportDecl(nullptr, true); 114 } 115 116 // Resolve the module-id. 117 Module *Context = resolveModuleId(Unresolved.Id, Mod, Complain); 118 if (!Context) 119 return {}; 120 121 return Module::ExportDecl(Context, Unresolved.Wildcard); 122 } 123 124 Module *ModuleMap::resolveModuleId(const ModuleId &Id, Module *Mod, 125 bool Complain) const { 126 // Find the starting module. 127 Module *Context = lookupModuleUnqualified(Id[0].first, Mod); 128 if (!Context) { 129 if (Complain) 130 Diags.Report(Id[0].second, diag::err_mmap_missing_module_unqualified) 131 << Id[0].first << Mod->getFullModuleName(); 132 133 return nullptr; 134 } 135 136 // Dig into the module path. 137 for (unsigned I = 1, N = Id.size(); I != N; ++I) { 138 Module *Sub = lookupModuleQualified(Id[I].first, Context); 139 if (!Sub) { 140 if (Complain) 141 Diags.Report(Id[I].second, diag::err_mmap_missing_module_qualified) 142 << Id[I].first << Context->getFullModuleName() 143 << SourceRange(Id[0].second, Id[I-1].second); 144 145 return nullptr; 146 } 147 148 Context = Sub; 149 } 150 151 return Context; 152 } 153 154 /// Append to \p Paths the set of paths needed to get to the 155 /// subframework in which the given module lives. 156 static void appendSubframeworkPaths(Module *Mod, 157 SmallVectorImpl<char> &Path) { 158 // Collect the framework names from the given module to the top-level module. 159 SmallVector<StringRef, 2> Paths; 160 for (; Mod; Mod = Mod->Parent) { 161 if (Mod->IsFramework) 162 Paths.push_back(Mod->Name); 163 } 164 165 if (Paths.empty()) 166 return; 167 168 // Add Frameworks/Name.framework for each subframework. 169 for (unsigned I = Paths.size() - 1; I != 0; --I) 170 llvm::sys::path::append(Path, "Frameworks", Paths[I-1] + ".framework"); 171 } 172 173 const FileEntry *ModuleMap::findHeader( 174 Module *M, const Module::UnresolvedHeaderDirective &Header, 175 SmallVectorImpl<char> &RelativePathName, bool &NeedsFramework) { 176 // Search for the header file within the module's home directory. 177 auto *Directory = M->Directory; 178 SmallString<128> FullPathName(Directory->getName()); 179 180 auto GetFile = [&](StringRef Filename) -> const FileEntry * { 181 auto *File = SourceMgr.getFileManager().getFile(Filename); 182 if (!File || 183 (Header.Size && File->getSize() != *Header.Size) || 184 (Header.ModTime && File->getModificationTime() != *Header.ModTime)) 185 return nullptr; 186 return File; 187 }; 188 189 auto GetFrameworkFile = [&]() -> const FileEntry * { 190 unsigned FullPathLength = FullPathName.size(); 191 appendSubframeworkPaths(M, RelativePathName); 192 unsigned RelativePathLength = RelativePathName.size(); 193 194 // Check whether this file is in the public headers. 195 llvm::sys::path::append(RelativePathName, "Headers", Header.FileName); 196 llvm::sys::path::append(FullPathName, RelativePathName); 197 if (auto *File = GetFile(FullPathName)) 198 return File; 199 200 // Check whether this file is in the private headers. 201 // Ideally, private modules in the form 'FrameworkName.Private' should 202 // be defined as 'module FrameworkName.Private', and not as 203 // 'framework module FrameworkName.Private', since a 'Private.Framework' 204 // does not usually exist. However, since both are currently widely used 205 // for private modules, make sure we find the right path in both cases. 206 if (M->IsFramework && M->Name == "Private") 207 RelativePathName.clear(); 208 else 209 RelativePathName.resize(RelativePathLength); 210 FullPathName.resize(FullPathLength); 211 llvm::sys::path::append(RelativePathName, "PrivateHeaders", 212 Header.FileName); 213 llvm::sys::path::append(FullPathName, RelativePathName); 214 return GetFile(FullPathName); 215 }; 216 217 if (llvm::sys::path::is_absolute(Header.FileName)) { 218 RelativePathName.clear(); 219 RelativePathName.append(Header.FileName.begin(), Header.FileName.end()); 220 return GetFile(Header.FileName); 221 } 222 223 if (M->isPartOfFramework()) 224 return GetFrameworkFile(); 225 226 // Lookup for normal headers. 227 llvm::sys::path::append(RelativePathName, Header.FileName); 228 llvm::sys::path::append(FullPathName, RelativePathName); 229 auto *NormalHdrFile = GetFile(FullPathName); 230 231 if (M && !NormalHdrFile && Directory->getName().endswith(".framework")) { 232 // The lack of 'framework' keyword in a module declaration it's a simple 233 // mistake we can diagnose when the header exists within the proper 234 // framework style path. 235 FullPathName.assign(Directory->getName()); 236 RelativePathName.clear(); 237 if (GetFrameworkFile()) { 238 Diags.Report(Header.FileNameLoc, 239 diag::warn_mmap_incomplete_framework_module_declaration) 240 << Header.FileName << M->getFullModuleName(); 241 NeedsFramework = true; 242 } 243 return nullptr; 244 } 245 246 return NormalHdrFile; 247 } 248 249 void ModuleMap::resolveHeader(Module *Mod, 250 const Module::UnresolvedHeaderDirective &Header, 251 bool &NeedsFramework) { 252 SmallString<128> RelativePathName; 253 if (const FileEntry *File = 254 findHeader(Mod, Header, RelativePathName, NeedsFramework)) { 255 if (Header.IsUmbrella) { 256 const DirectoryEntry *UmbrellaDir = File->getDir(); 257 if (Module *UmbrellaMod = UmbrellaDirs[UmbrellaDir]) 258 Diags.Report(Header.FileNameLoc, diag::err_mmap_umbrella_clash) 259 << UmbrellaMod->getFullModuleName(); 260 else 261 // Record this umbrella header. 262 setUmbrellaHeader(Mod, File, RelativePathName.str()); 263 } else { 264 Module::Header H = {RelativePathName.str(), File}; 265 if (Header.Kind == Module::HK_Excluded) 266 excludeHeader(Mod, H); 267 else 268 addHeader(Mod, H, headerKindToRole(Header.Kind)); 269 } 270 } else if (Header.HasBuiltinHeader && !Header.Size && !Header.ModTime) { 271 // There's a builtin header but no corresponding on-disk header. Assume 272 // this was supposed to modularize the builtin header alone. 273 } else if (Header.Kind == Module::HK_Excluded) { 274 // Ignore missing excluded header files. They're optional anyway. 275 } else { 276 // If we find a module that has a missing header, we mark this module as 277 // unavailable and store the header directive for displaying diagnostics. 278 Mod->MissingHeaders.push_back(Header); 279 // A missing header with stat information doesn't make the module 280 // unavailable; this keeps our behavior consistent as headers are lazily 281 // resolved. (Such a module still can't be built though, except from 282 // preprocessed source.) 283 if (!Header.Size && !Header.ModTime) 284 Mod->markUnavailable(); 285 } 286 } 287 288 bool ModuleMap::resolveAsBuiltinHeader( 289 Module *Mod, const Module::UnresolvedHeaderDirective &Header) { 290 if (Header.Kind == Module::HK_Excluded || 291 llvm::sys::path::is_absolute(Header.FileName) || 292 Mod->isPartOfFramework() || !Mod->IsSystem || Header.IsUmbrella || 293 !BuiltinIncludeDir || BuiltinIncludeDir == Mod->Directory || 294 !isBuiltinHeader(Header.FileName)) 295 return false; 296 297 // This is a system module with a top-level header. This header 298 // may have a counterpart (or replacement) in the set of headers 299 // supplied by Clang. Find that builtin header. 300 SmallString<128> Path; 301 llvm::sys::path::append(Path, BuiltinIncludeDir->getName(), Header.FileName); 302 auto *File = SourceMgr.getFileManager().getFile(Path); 303 if (!File) 304 return false; 305 306 auto Role = headerKindToRole(Header.Kind); 307 Module::Header H = {Path.str(), File}; 308 addHeader(Mod, H, Role); 309 return true; 310 } 311 312 ModuleMap::ModuleMap(SourceManager &SourceMgr, DiagnosticsEngine &Diags, 313 const LangOptions &LangOpts, const TargetInfo *Target, 314 HeaderSearch &HeaderInfo) 315 : SourceMgr(SourceMgr), Diags(Diags), LangOpts(LangOpts), Target(Target), 316 HeaderInfo(HeaderInfo) { 317 MMapLangOpts.LineComment = true; 318 } 319 320 ModuleMap::~ModuleMap() { 321 for (auto &M : Modules) 322 delete M.getValue(); 323 for (auto *M : ShadowModules) 324 delete M; 325 } 326 327 void ModuleMap::setTarget(const TargetInfo &Target) { 328 assert((!this->Target || this->Target == &Target) && 329 "Improper target override"); 330 this->Target = &Target; 331 } 332 333 /// "Sanitize" a filename so that it can be used as an identifier. 334 static StringRef sanitizeFilenameAsIdentifier(StringRef Name, 335 SmallVectorImpl<char> &Buffer) { 336 if (Name.empty()) 337 return Name; 338 339 if (!isValidIdentifier(Name)) { 340 // If we don't already have something with the form of an identifier, 341 // create a buffer with the sanitized name. 342 Buffer.clear(); 343 if (isDigit(Name[0])) 344 Buffer.push_back('_'); 345 Buffer.reserve(Buffer.size() + Name.size()); 346 for (unsigned I = 0, N = Name.size(); I != N; ++I) { 347 if (isIdentifierBody(Name[I])) 348 Buffer.push_back(Name[I]); 349 else 350 Buffer.push_back('_'); 351 } 352 353 Name = StringRef(Buffer.data(), Buffer.size()); 354 } 355 356 while (llvm::StringSwitch<bool>(Name) 357 #define KEYWORD(Keyword,Conditions) .Case(#Keyword, true) 358 #define ALIAS(Keyword, AliasOf, Conditions) .Case(Keyword, true) 359 #include "clang/Basic/TokenKinds.def" 360 .Default(false)) { 361 if (Name.data() != Buffer.data()) 362 Buffer.append(Name.begin(), Name.end()); 363 Buffer.push_back('_'); 364 Name = StringRef(Buffer.data(), Buffer.size()); 365 } 366 367 return Name; 368 } 369 370 /// Determine whether the given file name is the name of a builtin 371 /// header, supplied by Clang to replace, override, or augment existing system 372 /// headers. 373 bool ModuleMap::isBuiltinHeader(StringRef FileName) { 374 return llvm::StringSwitch<bool>(FileName) 375 .Case("float.h", true) 376 .Case("iso646.h", true) 377 .Case("limits.h", true) 378 .Case("stdalign.h", true) 379 .Case("stdarg.h", true) 380 .Case("stdatomic.h", true) 381 .Case("stdbool.h", true) 382 .Case("stddef.h", true) 383 .Case("stdint.h", true) 384 .Case("tgmath.h", true) 385 .Case("unwind.h", true) 386 .Default(false); 387 } 388 389 ModuleMap::HeadersMap::iterator 390 ModuleMap::findKnownHeader(const FileEntry *File) { 391 resolveHeaderDirectives(File); 392 HeadersMap::iterator Known = Headers.find(File); 393 if (HeaderInfo.getHeaderSearchOpts().ImplicitModuleMaps && 394 Known == Headers.end() && File->getDir() == BuiltinIncludeDir && 395 ModuleMap::isBuiltinHeader(llvm::sys::path::filename(File->getName()))) { 396 HeaderInfo.loadTopLevelSystemModules(); 397 return Headers.find(File); 398 } 399 return Known; 400 } 401 402 ModuleMap::KnownHeader 403 ModuleMap::findHeaderInUmbrellaDirs(const FileEntry *File, 404 SmallVectorImpl<const DirectoryEntry *> &IntermediateDirs) { 405 if (UmbrellaDirs.empty()) 406 return {}; 407 408 const DirectoryEntry *Dir = File->getDir(); 409 assert(Dir && "file in no directory"); 410 411 // Note: as an egregious but useful hack we use the real path here, because 412 // frameworks moving from top-level frameworks to embedded frameworks tend 413 // to be symlinked from the top-level location to the embedded location, 414 // and we need to resolve lookups as if we had found the embedded location. 415 StringRef DirName = SourceMgr.getFileManager().getCanonicalName(Dir); 416 417 // Keep walking up the directory hierarchy, looking for a directory with 418 // an umbrella header. 419 do { 420 auto KnownDir = UmbrellaDirs.find(Dir); 421 if (KnownDir != UmbrellaDirs.end()) 422 return KnownHeader(KnownDir->second, NormalHeader); 423 424 IntermediateDirs.push_back(Dir); 425 426 // Retrieve our parent path. 427 DirName = llvm::sys::path::parent_path(DirName); 428 if (DirName.empty()) 429 break; 430 431 // Resolve the parent path to a directory entry. 432 Dir = SourceMgr.getFileManager().getDirectory(DirName); 433 } while (Dir); 434 return {}; 435 } 436 437 static bool violatesPrivateInclude(Module *RequestingModule, 438 const FileEntry *IncFileEnt, 439 ModuleMap::KnownHeader Header) { 440 #ifndef NDEBUG 441 if (Header.getRole() & ModuleMap::PrivateHeader) { 442 // Check for consistency between the module header role 443 // as obtained from the lookup and as obtained from the module. 444 // This check is not cheap, so enable it only for debugging. 445 bool IsPrivate = false; 446 SmallVectorImpl<Module::Header> *HeaderList[] = { 447 &Header.getModule()->Headers[Module::HK_Private], 448 &Header.getModule()->Headers[Module::HK_PrivateTextual]}; 449 for (auto *Hs : HeaderList) 450 IsPrivate |= 451 std::find_if(Hs->begin(), Hs->end(), [&](const Module::Header &H) { 452 return H.Entry == IncFileEnt; 453 }) != Hs->end(); 454 assert(IsPrivate && "inconsistent headers and roles"); 455 } 456 #endif 457 return !Header.isAccessibleFrom(RequestingModule); 458 } 459 460 static Module *getTopLevelOrNull(Module *M) { 461 return M ? M->getTopLevelModule() : nullptr; 462 } 463 464 void ModuleMap::diagnoseHeaderInclusion(Module *RequestingModule, 465 bool RequestingModuleIsModuleInterface, 466 SourceLocation FilenameLoc, 467 StringRef Filename, 468 const FileEntry *File) { 469 // No errors for indirect modules. This may be a bit of a problem for modules 470 // with no source files. 471 if (getTopLevelOrNull(RequestingModule) != getTopLevelOrNull(SourceModule)) 472 return; 473 474 if (RequestingModule) { 475 resolveUses(RequestingModule, /*Complain=*/false); 476 resolveHeaderDirectives(RequestingModule); 477 } 478 479 bool Excluded = false; 480 Module *Private = nullptr; 481 Module *NotUsed = nullptr; 482 483 HeadersMap::iterator Known = findKnownHeader(File); 484 if (Known != Headers.end()) { 485 for (const KnownHeader &Header : Known->second) { 486 // Remember private headers for later printing of a diagnostic. 487 if (violatesPrivateInclude(RequestingModule, File, Header)) { 488 Private = Header.getModule(); 489 continue; 490 } 491 492 // If uses need to be specified explicitly, we are only allowed to return 493 // modules that are explicitly used by the requesting module. 494 if (RequestingModule && LangOpts.ModulesDeclUse && 495 !RequestingModule->directlyUses(Header.getModule())) { 496 NotUsed = Header.getModule(); 497 continue; 498 } 499 500 // We have found a module that we can happily use. 501 return; 502 } 503 504 Excluded = true; 505 } 506 507 // We have found a header, but it is private. 508 if (Private) { 509 Diags.Report(FilenameLoc, diag::warn_use_of_private_header_outside_module) 510 << Filename; 511 return; 512 } 513 514 // We have found a module, but we don't use it. 515 if (NotUsed) { 516 Diags.Report(FilenameLoc, diag::err_undeclared_use_of_module) 517 << RequestingModule->getTopLevelModule()->Name << Filename; 518 return; 519 } 520 521 if (Excluded || isHeaderInUmbrellaDirs(File)) 522 return; 523 524 // At this point, only non-modular includes remain. 525 526 if (LangOpts.ModulesStrictDeclUse) { 527 Diags.Report(FilenameLoc, diag::err_undeclared_use_of_module) 528 << RequestingModule->getTopLevelModule()->Name << Filename; 529 } else if (RequestingModule && RequestingModuleIsModuleInterface && 530 LangOpts.isCompilingModule()) { 531 // Do not diagnose when we are not compiling a module. 532 diag::kind DiagID = RequestingModule->getTopLevelModule()->IsFramework ? 533 diag::warn_non_modular_include_in_framework_module : 534 diag::warn_non_modular_include_in_module; 535 Diags.Report(FilenameLoc, DiagID) << RequestingModule->getFullModuleName() 536 << File->getName(); 537 } 538 } 539 540 static bool isBetterKnownHeader(const ModuleMap::KnownHeader &New, 541 const ModuleMap::KnownHeader &Old) { 542 // Prefer available modules. 543 if (New.getModule()->isAvailable() && !Old.getModule()->isAvailable()) 544 return true; 545 546 // Prefer a public header over a private header. 547 if ((New.getRole() & ModuleMap::PrivateHeader) != 548 (Old.getRole() & ModuleMap::PrivateHeader)) 549 return !(New.getRole() & ModuleMap::PrivateHeader); 550 551 // Prefer a non-textual header over a textual header. 552 if ((New.getRole() & ModuleMap::TextualHeader) != 553 (Old.getRole() & ModuleMap::TextualHeader)) 554 return !(New.getRole() & ModuleMap::TextualHeader); 555 556 // Don't have a reason to choose between these. Just keep the first one. 557 return false; 558 } 559 560 ModuleMap::KnownHeader ModuleMap::findModuleForHeader(const FileEntry *File, 561 bool AllowTextual) { 562 auto MakeResult = [&](ModuleMap::KnownHeader R) -> ModuleMap::KnownHeader { 563 if (!AllowTextual && R.getRole() & ModuleMap::TextualHeader) 564 return {}; 565 return R; 566 }; 567 568 HeadersMap::iterator Known = findKnownHeader(File); 569 if (Known != Headers.end()) { 570 ModuleMap::KnownHeader Result; 571 // Iterate over all modules that 'File' is part of to find the best fit. 572 for (KnownHeader &H : Known->second) { 573 // Prefer a header from the source module over all others. 574 if (H.getModule()->getTopLevelModule() == SourceModule) 575 return MakeResult(H); 576 if (!Result || isBetterKnownHeader(H, Result)) 577 Result = H; 578 } 579 return MakeResult(Result); 580 } 581 582 return MakeResult(findOrCreateModuleForHeaderInUmbrellaDir(File)); 583 } 584 585 ModuleMap::KnownHeader 586 ModuleMap::findOrCreateModuleForHeaderInUmbrellaDir(const FileEntry *File) { 587 assert(!Headers.count(File) && "already have a module for this header"); 588 589 SmallVector<const DirectoryEntry *, 2> SkippedDirs; 590 KnownHeader H = findHeaderInUmbrellaDirs(File, SkippedDirs); 591 if (H) { 592 Module *Result = H.getModule(); 593 594 // Search up the module stack until we find a module with an umbrella 595 // directory. 596 Module *UmbrellaModule = Result; 597 while (!UmbrellaModule->getUmbrellaDir() && UmbrellaModule->Parent) 598 UmbrellaModule = UmbrellaModule->Parent; 599 600 if (UmbrellaModule->InferSubmodules) { 601 const FileEntry *UmbrellaModuleMap = 602 getModuleMapFileForUniquing(UmbrellaModule); 603 604 // Infer submodules for each of the directories we found between 605 // the directory of the umbrella header and the directory where 606 // the actual header is located. 607 bool Explicit = UmbrellaModule->InferExplicitSubmodules; 608 609 for (unsigned I = SkippedDirs.size(); I != 0; --I) { 610 // Find or create the module that corresponds to this directory name. 611 SmallString<32> NameBuf; 612 StringRef Name = sanitizeFilenameAsIdentifier( 613 llvm::sys::path::stem(SkippedDirs[I-1]->getName()), NameBuf); 614 Result = findOrCreateModule(Name, Result, /*IsFramework=*/false, 615 Explicit).first; 616 InferredModuleAllowedBy[Result] = UmbrellaModuleMap; 617 Result->IsInferred = true; 618 619 // Associate the module and the directory. 620 UmbrellaDirs[SkippedDirs[I-1]] = Result; 621 622 // If inferred submodules export everything they import, add a 623 // wildcard to the set of exports. 624 if (UmbrellaModule->InferExportWildcard && Result->Exports.empty()) 625 Result->Exports.push_back(Module::ExportDecl(nullptr, true)); 626 } 627 628 // Infer a submodule with the same name as this header file. 629 SmallString<32> NameBuf; 630 StringRef Name = sanitizeFilenameAsIdentifier( 631 llvm::sys::path::stem(File->getName()), NameBuf); 632 Result = findOrCreateModule(Name, Result, /*IsFramework=*/false, 633 Explicit).first; 634 InferredModuleAllowedBy[Result] = UmbrellaModuleMap; 635 Result->IsInferred = true; 636 Result->addTopHeader(File); 637 638 // If inferred submodules export everything they import, add a 639 // wildcard to the set of exports. 640 if (UmbrellaModule->InferExportWildcard && Result->Exports.empty()) 641 Result->Exports.push_back(Module::ExportDecl(nullptr, true)); 642 } else { 643 // Record each of the directories we stepped through as being part of 644 // the module we found, since the umbrella header covers them all. 645 for (unsigned I = 0, N = SkippedDirs.size(); I != N; ++I) 646 UmbrellaDirs[SkippedDirs[I]] = Result; 647 } 648 649 KnownHeader Header(Result, NormalHeader); 650 Headers[File].push_back(Header); 651 return Header; 652 } 653 654 return {}; 655 } 656 657 ArrayRef<ModuleMap::KnownHeader> 658 ModuleMap::findAllModulesForHeader(const FileEntry *File) const { 659 resolveHeaderDirectives(File); 660 auto It = Headers.find(File); 661 if (It == Headers.end()) 662 return None; 663 return It->second; 664 } 665 666 bool ModuleMap::isHeaderInUnavailableModule(const FileEntry *Header) const { 667 return isHeaderUnavailableInModule(Header, nullptr); 668 } 669 670 bool 671 ModuleMap::isHeaderUnavailableInModule(const FileEntry *Header, 672 const Module *RequestingModule) const { 673 resolveHeaderDirectives(Header); 674 HeadersMap::const_iterator Known = Headers.find(Header); 675 if (Known != Headers.end()) { 676 for (SmallVectorImpl<KnownHeader>::const_iterator 677 I = Known->second.begin(), 678 E = Known->second.end(); 679 I != E; ++I) { 680 681 if (I->isAvailable() && 682 (!RequestingModule || 683 I->getModule()->isSubModuleOf(RequestingModule))) { 684 // When no requesting module is available, the caller is looking if a 685 // header is part a module by only looking into the module map. This is 686 // done by warn_uncovered_module_header checks; don't consider textual 687 // headers part of it in this mode, otherwise we get misleading warnings 688 // that a umbrella header is not including a textual header. 689 if (!RequestingModule && I->getRole() == ModuleMap::TextualHeader) 690 continue; 691 return false; 692 } 693 } 694 return true; 695 } 696 697 const DirectoryEntry *Dir = Header->getDir(); 698 SmallVector<const DirectoryEntry *, 2> SkippedDirs; 699 StringRef DirName = Dir->getName(); 700 701 auto IsUnavailable = [&](const Module *M) { 702 return !M->isAvailable() && (!RequestingModule || 703 M->isSubModuleOf(RequestingModule)); 704 }; 705 706 // Keep walking up the directory hierarchy, looking for a directory with 707 // an umbrella header. 708 do { 709 llvm::DenseMap<const DirectoryEntry *, Module *>::const_iterator KnownDir 710 = UmbrellaDirs.find(Dir); 711 if (KnownDir != UmbrellaDirs.end()) { 712 Module *Found = KnownDir->second; 713 if (IsUnavailable(Found)) 714 return true; 715 716 // Search up the module stack until we find a module with an umbrella 717 // directory. 718 Module *UmbrellaModule = Found; 719 while (!UmbrellaModule->getUmbrellaDir() && UmbrellaModule->Parent) 720 UmbrellaModule = UmbrellaModule->Parent; 721 722 if (UmbrellaModule->InferSubmodules) { 723 for (unsigned I = SkippedDirs.size(); I != 0; --I) { 724 // Find or create the module that corresponds to this directory name. 725 SmallString<32> NameBuf; 726 StringRef Name = sanitizeFilenameAsIdentifier( 727 llvm::sys::path::stem(SkippedDirs[I-1]->getName()), 728 NameBuf); 729 Found = lookupModuleQualified(Name, Found); 730 if (!Found) 731 return false; 732 if (IsUnavailable(Found)) 733 return true; 734 } 735 736 // Infer a submodule with the same name as this header file. 737 SmallString<32> NameBuf; 738 StringRef Name = sanitizeFilenameAsIdentifier( 739 llvm::sys::path::stem(Header->getName()), 740 NameBuf); 741 Found = lookupModuleQualified(Name, Found); 742 if (!Found) 743 return false; 744 } 745 746 return IsUnavailable(Found); 747 } 748 749 SkippedDirs.push_back(Dir); 750 751 // Retrieve our parent path. 752 DirName = llvm::sys::path::parent_path(DirName); 753 if (DirName.empty()) 754 break; 755 756 // Resolve the parent path to a directory entry. 757 Dir = SourceMgr.getFileManager().getDirectory(DirName); 758 } while (Dir); 759 760 return false; 761 } 762 763 Module *ModuleMap::findModule(StringRef Name) const { 764 llvm::StringMap<Module *>::const_iterator Known = Modules.find(Name); 765 if (Known != Modules.end()) 766 return Known->getValue(); 767 768 return nullptr; 769 } 770 771 Module *ModuleMap::lookupModuleUnqualified(StringRef Name, 772 Module *Context) const { 773 for(; Context; Context = Context->Parent) { 774 if (Module *Sub = lookupModuleQualified(Name, Context)) 775 return Sub; 776 } 777 778 return findModule(Name); 779 } 780 781 Module *ModuleMap::lookupModuleQualified(StringRef Name, Module *Context) const{ 782 if (!Context) 783 return findModule(Name); 784 785 return Context->findSubmodule(Name); 786 } 787 788 std::pair<Module *, bool> ModuleMap::findOrCreateModule(StringRef Name, 789 Module *Parent, 790 bool IsFramework, 791 bool IsExplicit) { 792 // Try to find an existing module with this name. 793 if (Module *Sub = lookupModuleQualified(Name, Parent)) 794 return std::make_pair(Sub, false); 795 796 // Create a new module with this name. 797 Module *Result = new Module(Name, SourceLocation(), Parent, IsFramework, 798 IsExplicit, NumCreatedModules++); 799 if (!Parent) { 800 if (LangOpts.CurrentModule == Name) 801 SourceModule = Result; 802 Modules[Name] = Result; 803 ModuleScopeIDs[Result] = CurrentModuleScopeID; 804 } 805 return std::make_pair(Result, true); 806 } 807 808 Module *ModuleMap::createGlobalModuleForInterfaceUnit(SourceLocation Loc) { 809 PendingSubmodules.emplace_back( 810 new Module("<global>", Loc, nullptr, /*IsFramework*/ false, 811 /*IsExplicit*/ true, NumCreatedModules++)); 812 PendingSubmodules.back()->Kind = Module::GlobalModuleFragment; 813 return PendingSubmodules.back().get(); 814 } 815 816 Module *ModuleMap::createModuleForInterfaceUnit(SourceLocation Loc, 817 StringRef Name, 818 Module *GlobalModule) { 819 assert(LangOpts.CurrentModule == Name && "module name mismatch"); 820 assert(!Modules[Name] && "redefining existing module"); 821 822 auto *Result = 823 new Module(Name, Loc, nullptr, /*IsFramework*/ false, 824 /*IsExplicit*/ false, NumCreatedModules++); 825 Result->Kind = Module::ModuleInterfaceUnit; 826 Modules[Name] = SourceModule = Result; 827 828 // Reparent the current global module fragment as a submodule of this module. 829 for (auto &Submodule : PendingSubmodules) { 830 Submodule->setParent(Result); 831 Submodule.release(); // now owned by parent 832 } 833 PendingSubmodules.clear(); 834 835 // Mark the main source file as being within the newly-created module so that 836 // declarations and macros are properly visibility-restricted to it. 837 auto *MainFile = SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()); 838 assert(MainFile && "no input file for module interface"); 839 Headers[MainFile].push_back(KnownHeader(Result, PrivateHeader)); 840 841 return Result; 842 } 843 844 Module *ModuleMap::createHeaderModule(StringRef Name, 845 ArrayRef<Module::Header> Headers) { 846 assert(LangOpts.CurrentModule == Name && "module name mismatch"); 847 assert(!Modules[Name] && "redefining existing module"); 848 849 auto *Result = 850 new Module(Name, SourceLocation(), nullptr, /*IsFramework*/ false, 851 /*IsExplicit*/ false, NumCreatedModules++); 852 Result->Kind = Module::ModuleInterfaceUnit; 853 Modules[Name] = SourceModule = Result; 854 855 for (const Module::Header &H : Headers) { 856 auto *M = new Module(H.NameAsWritten, SourceLocation(), Result, 857 /*IsFramework*/ false, 858 /*IsExplicit*/ true, NumCreatedModules++); 859 // Header modules are implicitly 'export *'. 860 M->Exports.push_back(Module::ExportDecl(nullptr, true)); 861 addHeader(M, H, NormalHeader); 862 } 863 864 return Result; 865 } 866 867 /// For a framework module, infer the framework against which we 868 /// should link. 869 static void inferFrameworkLink(Module *Mod, const DirectoryEntry *FrameworkDir, 870 FileManager &FileMgr) { 871 assert(Mod->IsFramework && "Can only infer linking for framework modules"); 872 assert(!Mod->isSubFramework() && 873 "Can only infer linking for top-level frameworks"); 874 875 SmallString<128> LibName; 876 LibName += FrameworkDir->getName(); 877 llvm::sys::path::append(LibName, Mod->Name); 878 879 // The library name of a framework has more than one possible extension since 880 // the introduction of the text-based dynamic library format. We need to check 881 // for both before we give up. 882 for (const char *extension : {"", ".tbd"}) { 883 llvm::sys::path::replace_extension(LibName, extension); 884 if (FileMgr.getFile(LibName)) { 885 Mod->LinkLibraries.push_back(Module::LinkLibrary(Mod->Name, 886 /*IsFramework=*/true)); 887 return; 888 } 889 } 890 } 891 892 Module *ModuleMap::inferFrameworkModule(const DirectoryEntry *FrameworkDir, 893 bool IsSystem, Module *Parent) { 894 Attributes Attrs; 895 Attrs.IsSystem = IsSystem; 896 return inferFrameworkModule(FrameworkDir, Attrs, Parent); 897 } 898 899 Module *ModuleMap::inferFrameworkModule(const DirectoryEntry *FrameworkDir, 900 Attributes Attrs, Module *Parent) { 901 // Note: as an egregious but useful hack we use the real path here, because 902 // we might be looking at an embedded framework that symlinks out to a 903 // top-level framework, and we need to infer as if we were naming the 904 // top-level framework. 905 StringRef FrameworkDirName = 906 SourceMgr.getFileManager().getCanonicalName(FrameworkDir); 907 908 // In case this is a case-insensitive filesystem, use the canonical 909 // directory name as the ModuleName, since modules are case-sensitive. 910 // FIXME: we should be able to give a fix-it hint for the correct spelling. 911 SmallString<32> ModuleNameStorage; 912 StringRef ModuleName = sanitizeFilenameAsIdentifier( 913 llvm::sys::path::stem(FrameworkDirName), ModuleNameStorage); 914 915 // Check whether we've already found this module. 916 if (Module *Mod = lookupModuleQualified(ModuleName, Parent)) 917 return Mod; 918 919 FileManager &FileMgr = SourceMgr.getFileManager(); 920 921 // If the framework has a parent path from which we're allowed to infer 922 // a framework module, do so. 923 const FileEntry *ModuleMapFile = nullptr; 924 if (!Parent) { 925 // Determine whether we're allowed to infer a module map. 926 bool canInfer = false; 927 if (llvm::sys::path::has_parent_path(FrameworkDirName)) { 928 // Figure out the parent path. 929 StringRef Parent = llvm::sys::path::parent_path(FrameworkDirName); 930 if (const DirectoryEntry *ParentDir = FileMgr.getDirectory(Parent)) { 931 // Check whether we have already looked into the parent directory 932 // for a module map. 933 llvm::DenseMap<const DirectoryEntry *, InferredDirectory>::const_iterator 934 inferred = InferredDirectories.find(ParentDir); 935 if (inferred == InferredDirectories.end()) { 936 // We haven't looked here before. Load a module map, if there is 937 // one. 938 bool IsFrameworkDir = Parent.endswith(".framework"); 939 if (const FileEntry *ModMapFile = 940 HeaderInfo.lookupModuleMapFile(ParentDir, IsFrameworkDir)) { 941 parseModuleMapFile(ModMapFile, Attrs.IsSystem, ParentDir); 942 inferred = InferredDirectories.find(ParentDir); 943 } 944 945 if (inferred == InferredDirectories.end()) 946 inferred = InferredDirectories.insert( 947 std::make_pair(ParentDir, InferredDirectory())).first; 948 } 949 950 if (inferred->second.InferModules) { 951 // We're allowed to infer for this directory, but make sure it's okay 952 // to infer this particular module. 953 StringRef Name = llvm::sys::path::stem(FrameworkDirName); 954 canInfer = std::find(inferred->second.ExcludedModules.begin(), 955 inferred->second.ExcludedModules.end(), 956 Name) == inferred->second.ExcludedModules.end(); 957 958 Attrs.IsSystem |= inferred->second.Attrs.IsSystem; 959 Attrs.IsExternC |= inferred->second.Attrs.IsExternC; 960 Attrs.IsExhaustive |= inferred->second.Attrs.IsExhaustive; 961 Attrs.NoUndeclaredIncludes |= 962 inferred->second.Attrs.NoUndeclaredIncludes; 963 ModuleMapFile = inferred->second.ModuleMapFile; 964 } 965 } 966 } 967 968 // If we're not allowed to infer a framework module, don't. 969 if (!canInfer) 970 return nullptr; 971 } else 972 ModuleMapFile = getModuleMapFileForUniquing(Parent); 973 974 975 // Look for an umbrella header. 976 SmallString<128> UmbrellaName = StringRef(FrameworkDir->getName()); 977 llvm::sys::path::append(UmbrellaName, "Headers", ModuleName + ".h"); 978 const FileEntry *UmbrellaHeader = FileMgr.getFile(UmbrellaName); 979 980 // FIXME: If there's no umbrella header, we could probably scan the 981 // framework to load *everything*. But, it's not clear that this is a good 982 // idea. 983 if (!UmbrellaHeader) 984 return nullptr; 985 986 Module *Result = new Module(ModuleName, SourceLocation(), Parent, 987 /*IsFramework=*/true, /*IsExplicit=*/false, 988 NumCreatedModules++); 989 InferredModuleAllowedBy[Result] = ModuleMapFile; 990 Result->IsInferred = true; 991 if (!Parent) { 992 if (LangOpts.CurrentModule == ModuleName) 993 SourceModule = Result; 994 Modules[ModuleName] = Result; 995 ModuleScopeIDs[Result] = CurrentModuleScopeID; 996 } 997 998 Result->IsSystem |= Attrs.IsSystem; 999 Result->IsExternC |= Attrs.IsExternC; 1000 Result->ConfigMacrosExhaustive |= Attrs.IsExhaustive; 1001 Result->NoUndeclaredIncludes |= Attrs.NoUndeclaredIncludes; 1002 Result->Directory = FrameworkDir; 1003 1004 // umbrella header "umbrella-header-name" 1005 // 1006 // The "Headers/" component of the name is implied because this is 1007 // a framework module. 1008 setUmbrellaHeader(Result, UmbrellaHeader, ModuleName + ".h"); 1009 1010 // export * 1011 Result->Exports.push_back(Module::ExportDecl(nullptr, true)); 1012 1013 // module * { export * } 1014 Result->InferSubmodules = true; 1015 Result->InferExportWildcard = true; 1016 1017 // Look for subframeworks. 1018 std::error_code EC; 1019 SmallString<128> SubframeworksDirName 1020 = StringRef(FrameworkDir->getName()); 1021 llvm::sys::path::append(SubframeworksDirName, "Frameworks"); 1022 llvm::sys::path::native(SubframeworksDirName); 1023 vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem(); 1024 for (vfs::directory_iterator Dir = FS.dir_begin(SubframeworksDirName, EC), 1025 DirEnd; 1026 Dir != DirEnd && !EC; Dir.increment(EC)) { 1027 if (!StringRef(Dir->path()).endswith(".framework")) 1028 continue; 1029 1030 if (const DirectoryEntry *SubframeworkDir = 1031 FileMgr.getDirectory(Dir->path())) { 1032 // Note: as an egregious but useful hack, we use the real path here and 1033 // check whether it is actually a subdirectory of the parent directory. 1034 // This will not be the case if the 'subframework' is actually a symlink 1035 // out to a top-level framework. 1036 StringRef SubframeworkDirName = FileMgr.getCanonicalName(SubframeworkDir); 1037 bool FoundParent = false; 1038 do { 1039 // Get the parent directory name. 1040 SubframeworkDirName 1041 = llvm::sys::path::parent_path(SubframeworkDirName); 1042 if (SubframeworkDirName.empty()) 1043 break; 1044 1045 if (FileMgr.getDirectory(SubframeworkDirName) == FrameworkDir) { 1046 FoundParent = true; 1047 break; 1048 } 1049 } while (true); 1050 1051 if (!FoundParent) 1052 continue; 1053 1054 // FIXME: Do we want to warn about subframeworks without umbrella headers? 1055 inferFrameworkModule(SubframeworkDir, Attrs, Result); 1056 } 1057 } 1058 1059 // If the module is a top-level framework, automatically link against the 1060 // framework. 1061 if (!Result->isSubFramework()) { 1062 inferFrameworkLink(Result, FrameworkDir, FileMgr); 1063 } 1064 1065 return Result; 1066 } 1067 1068 Module *ModuleMap::createShadowedModule(StringRef Name, bool IsFramework, 1069 Module *ShadowingModule) { 1070 1071 // Create a new module with this name. 1072 Module *Result = 1073 new Module(Name, SourceLocation(), /*Parent=*/nullptr, IsFramework, 1074 /*IsExplicit=*/false, NumCreatedModules++); 1075 Result->ShadowingModule = ShadowingModule; 1076 Result->IsAvailable = false; 1077 ModuleScopeIDs[Result] = CurrentModuleScopeID; 1078 ShadowModules.push_back(Result); 1079 1080 return Result; 1081 } 1082 1083 void ModuleMap::setUmbrellaHeader(Module *Mod, const FileEntry *UmbrellaHeader, 1084 Twine NameAsWritten) { 1085 Headers[UmbrellaHeader].push_back(KnownHeader(Mod, NormalHeader)); 1086 Mod->Umbrella = UmbrellaHeader; 1087 Mod->UmbrellaAsWritten = NameAsWritten.str(); 1088 UmbrellaDirs[UmbrellaHeader->getDir()] = Mod; 1089 1090 // Notify callbacks that we just added a new header. 1091 for (const auto &Cb : Callbacks) 1092 Cb->moduleMapAddUmbrellaHeader(&SourceMgr.getFileManager(), UmbrellaHeader); 1093 } 1094 1095 void ModuleMap::setUmbrellaDir(Module *Mod, const DirectoryEntry *UmbrellaDir, 1096 Twine NameAsWritten) { 1097 Mod->Umbrella = UmbrellaDir; 1098 Mod->UmbrellaAsWritten = NameAsWritten.str(); 1099 UmbrellaDirs[UmbrellaDir] = Mod; 1100 } 1101 1102 void ModuleMap::addUnresolvedHeader(Module *Mod, 1103 Module::UnresolvedHeaderDirective Header, 1104 bool &NeedsFramework) { 1105 // If there is a builtin counterpart to this file, add it now so it can 1106 // wrap the system header. 1107 if (resolveAsBuiltinHeader(Mod, Header)) { 1108 // If we have both a builtin and system version of the file, the 1109 // builtin version may want to inject macros into the system header, so 1110 // force the system header to be treated as a textual header in this 1111 // case. 1112 Header.Kind = headerRoleToKind(ModuleMap::ModuleHeaderRole( 1113 headerKindToRole(Header.Kind) | ModuleMap::TextualHeader)); 1114 Header.HasBuiltinHeader = true; 1115 } 1116 1117 // If possible, don't stat the header until we need to. This requires the 1118 // user to have provided us with some stat information about the file. 1119 // FIXME: Add support for lazily stat'ing umbrella headers and excluded 1120 // headers. 1121 if ((Header.Size || Header.ModTime) && !Header.IsUmbrella && 1122 Header.Kind != Module::HK_Excluded) { 1123 // We expect more variation in mtime than size, so if we're given both, 1124 // use the mtime as the key. 1125 if (Header.ModTime) 1126 LazyHeadersByModTime[*Header.ModTime].push_back(Mod); 1127 else 1128 LazyHeadersBySize[*Header.Size].push_back(Mod); 1129 Mod->UnresolvedHeaders.push_back(Header); 1130 return; 1131 } 1132 1133 // We don't have stat information or can't defer looking this file up. 1134 // Perform the lookup now. 1135 resolveHeader(Mod, Header, NeedsFramework); 1136 } 1137 1138 void ModuleMap::resolveHeaderDirectives(const FileEntry *File) const { 1139 auto BySize = LazyHeadersBySize.find(File->getSize()); 1140 if (BySize != LazyHeadersBySize.end()) { 1141 for (auto *M : BySize->second) 1142 resolveHeaderDirectives(M); 1143 LazyHeadersBySize.erase(BySize); 1144 } 1145 1146 auto ByModTime = LazyHeadersByModTime.find(File->getModificationTime()); 1147 if (ByModTime != LazyHeadersByModTime.end()) { 1148 for (auto *M : ByModTime->second) 1149 resolveHeaderDirectives(M); 1150 LazyHeadersByModTime.erase(ByModTime); 1151 } 1152 } 1153 1154 void ModuleMap::resolveHeaderDirectives(Module *Mod) const { 1155 bool NeedsFramework = false; 1156 for (auto &Header : Mod->UnresolvedHeaders) 1157 // This operation is logically const; we're just changing how we represent 1158 // the header information for this file. 1159 const_cast<ModuleMap*>(this)->resolveHeader(Mod, Header, NeedsFramework); 1160 Mod->UnresolvedHeaders.clear(); 1161 } 1162 1163 void ModuleMap::addHeader(Module *Mod, Module::Header Header, 1164 ModuleHeaderRole Role, bool Imported) { 1165 KnownHeader KH(Mod, Role); 1166 1167 // Only add each header to the headers list once. 1168 // FIXME: Should we diagnose if a header is listed twice in the 1169 // same module definition? 1170 auto &HeaderList = Headers[Header.Entry]; 1171 for (auto H : HeaderList) 1172 if (H == KH) 1173 return; 1174 1175 HeaderList.push_back(KH); 1176 Mod->Headers[headerRoleToKind(Role)].push_back(Header); 1177 1178 bool isCompilingModuleHeader = 1179 LangOpts.isCompilingModule() && Mod->getTopLevelModule() == SourceModule; 1180 if (!Imported || isCompilingModuleHeader) { 1181 // When we import HeaderFileInfo, the external source is expected to 1182 // set the isModuleHeader flag itself. 1183 HeaderInfo.MarkFileModuleHeader(Header.Entry, Role, 1184 isCompilingModuleHeader); 1185 } 1186 1187 // Notify callbacks that we just added a new header. 1188 for (const auto &Cb : Callbacks) 1189 Cb->moduleMapAddHeader(Header.Entry->getName()); 1190 } 1191 1192 void ModuleMap::excludeHeader(Module *Mod, Module::Header Header) { 1193 // Add this as a known header so we won't implicitly add it to any 1194 // umbrella directory module. 1195 // FIXME: Should we only exclude it from umbrella modules within the 1196 // specified module? 1197 (void) Headers[Header.Entry]; 1198 1199 Mod->Headers[Module::HK_Excluded].push_back(std::move(Header)); 1200 } 1201 1202 const FileEntry * 1203 ModuleMap::getContainingModuleMapFile(const Module *Module) const { 1204 if (Module->DefinitionLoc.isInvalid()) 1205 return nullptr; 1206 1207 return SourceMgr.getFileEntryForID( 1208 SourceMgr.getFileID(Module->DefinitionLoc)); 1209 } 1210 1211 const FileEntry *ModuleMap::getModuleMapFileForUniquing(const Module *M) const { 1212 if (M->IsInferred) { 1213 assert(InferredModuleAllowedBy.count(M) && "missing inferred module map"); 1214 return InferredModuleAllowedBy.find(M)->second; 1215 } 1216 return getContainingModuleMapFile(M); 1217 } 1218 1219 void ModuleMap::setInferredModuleAllowedBy(Module *M, const FileEntry *ModMap) { 1220 assert(M->IsInferred && "module not inferred"); 1221 InferredModuleAllowedBy[M] = ModMap; 1222 } 1223 1224 LLVM_DUMP_METHOD void ModuleMap::dump() { 1225 llvm::errs() << "Modules:"; 1226 for (llvm::StringMap<Module *>::iterator M = Modules.begin(), 1227 MEnd = Modules.end(); 1228 M != MEnd; ++M) 1229 M->getValue()->print(llvm::errs(), 2); 1230 1231 llvm::errs() << "Headers:"; 1232 for (HeadersMap::iterator H = Headers.begin(), HEnd = Headers.end(); 1233 H != HEnd; ++H) { 1234 llvm::errs() << " \"" << H->first->getName() << "\" -> "; 1235 for (SmallVectorImpl<KnownHeader>::const_iterator I = H->second.begin(), 1236 E = H->second.end(); 1237 I != E; ++I) { 1238 if (I != H->second.begin()) 1239 llvm::errs() << ","; 1240 llvm::errs() << I->getModule()->getFullModuleName(); 1241 } 1242 llvm::errs() << "\n"; 1243 } 1244 } 1245 1246 bool ModuleMap::resolveExports(Module *Mod, bool Complain) { 1247 auto Unresolved = std::move(Mod->UnresolvedExports); 1248 Mod->UnresolvedExports.clear(); 1249 for (auto &UE : Unresolved) { 1250 Module::ExportDecl Export = resolveExport(Mod, UE, Complain); 1251 if (Export.getPointer() || Export.getInt()) 1252 Mod->Exports.push_back(Export); 1253 else 1254 Mod->UnresolvedExports.push_back(UE); 1255 } 1256 return !Mod->UnresolvedExports.empty(); 1257 } 1258 1259 bool ModuleMap::resolveUses(Module *Mod, bool Complain) { 1260 auto Unresolved = std::move(Mod->UnresolvedDirectUses); 1261 Mod->UnresolvedDirectUses.clear(); 1262 for (auto &UDU : Unresolved) { 1263 Module *DirectUse = resolveModuleId(UDU, Mod, Complain); 1264 if (DirectUse) 1265 Mod->DirectUses.push_back(DirectUse); 1266 else 1267 Mod->UnresolvedDirectUses.push_back(UDU); 1268 } 1269 return !Mod->UnresolvedDirectUses.empty(); 1270 } 1271 1272 bool ModuleMap::resolveConflicts(Module *Mod, bool Complain) { 1273 auto Unresolved = std::move(Mod->UnresolvedConflicts); 1274 Mod->UnresolvedConflicts.clear(); 1275 for (auto &UC : Unresolved) { 1276 if (Module *OtherMod = resolveModuleId(UC.Id, Mod, Complain)) { 1277 Module::Conflict Conflict; 1278 Conflict.Other = OtherMod; 1279 Conflict.Message = UC.Message; 1280 Mod->Conflicts.push_back(Conflict); 1281 } else 1282 Mod->UnresolvedConflicts.push_back(UC); 1283 } 1284 return !Mod->UnresolvedConflicts.empty(); 1285 } 1286 1287 //----------------------------------------------------------------------------// 1288 // Module map file parser 1289 //----------------------------------------------------------------------------// 1290 1291 namespace clang { 1292 1293 /// A token in a module map file. 1294 struct MMToken { 1295 enum TokenKind { 1296 Comma, 1297 ConfigMacros, 1298 Conflict, 1299 EndOfFile, 1300 HeaderKeyword, 1301 Identifier, 1302 Exclaim, 1303 ExcludeKeyword, 1304 ExplicitKeyword, 1305 ExportKeyword, 1306 ExportAsKeyword, 1307 ExternKeyword, 1308 FrameworkKeyword, 1309 LinkKeyword, 1310 ModuleKeyword, 1311 Period, 1312 PrivateKeyword, 1313 UmbrellaKeyword, 1314 UseKeyword, 1315 RequiresKeyword, 1316 Star, 1317 StringLiteral, 1318 IntegerLiteral, 1319 TextualKeyword, 1320 LBrace, 1321 RBrace, 1322 LSquare, 1323 RSquare 1324 } Kind; 1325 1326 unsigned Location; 1327 unsigned StringLength; 1328 union { 1329 // If Kind != IntegerLiteral. 1330 const char *StringData; 1331 1332 // If Kind == IntegerLiteral. 1333 uint64_t IntegerValue; 1334 }; 1335 1336 void clear() { 1337 Kind = EndOfFile; 1338 Location = 0; 1339 StringLength = 0; 1340 StringData = nullptr; 1341 } 1342 1343 bool is(TokenKind K) const { return Kind == K; } 1344 1345 SourceLocation getLocation() const { 1346 return SourceLocation::getFromRawEncoding(Location); 1347 } 1348 1349 uint64_t getInteger() const { 1350 return Kind == IntegerLiteral ? IntegerValue : 0; 1351 } 1352 1353 StringRef getString() const { 1354 return Kind == IntegerLiteral ? StringRef() 1355 : StringRef(StringData, StringLength); 1356 } 1357 }; 1358 1359 class ModuleMapParser { 1360 Lexer &L; 1361 SourceManager &SourceMgr; 1362 1363 /// Default target information, used only for string literal 1364 /// parsing. 1365 const TargetInfo *Target; 1366 1367 DiagnosticsEngine &Diags; 1368 ModuleMap ⤅ 1369 1370 /// The current module map file. 1371 const FileEntry *ModuleMapFile; 1372 1373 /// Source location of most recent parsed module declaration 1374 SourceLocation CurrModuleDeclLoc; 1375 1376 /// The directory that file names in this module map file should 1377 /// be resolved relative to. 1378 const DirectoryEntry *Directory; 1379 1380 /// Whether this module map is in a system header directory. 1381 bool IsSystem; 1382 1383 /// Whether an error occurred. 1384 bool HadError = false; 1385 1386 /// Stores string data for the various string literals referenced 1387 /// during parsing. 1388 llvm::BumpPtrAllocator StringData; 1389 1390 /// The current token. 1391 MMToken Tok; 1392 1393 /// The active module. 1394 Module *ActiveModule = nullptr; 1395 1396 /// Whether a module uses the 'requires excluded' hack to mark its 1397 /// contents as 'textual'. 1398 /// 1399 /// On older Darwin SDK versions, 'requires excluded' is used to mark the 1400 /// contents of the Darwin.C.excluded (assert.h) and Tcl.Private modules as 1401 /// non-modular headers. For backwards compatibility, we continue to 1402 /// support this idiom for just these modules, and map the headers to 1403 /// 'textual' to match the original intent. 1404 llvm::SmallPtrSet<Module *, 2> UsesRequiresExcludedHack; 1405 1406 /// Consume the current token and return its location. 1407 SourceLocation consumeToken(); 1408 1409 /// Skip tokens until we reach the a token with the given kind 1410 /// (or the end of the file). 1411 void skipUntil(MMToken::TokenKind K); 1412 1413 using ModuleId = SmallVector<std::pair<std::string, SourceLocation>, 2>; 1414 1415 bool parseModuleId(ModuleId &Id); 1416 void parseModuleDecl(); 1417 void parseExternModuleDecl(); 1418 void parseRequiresDecl(); 1419 void parseHeaderDecl(MMToken::TokenKind, SourceLocation LeadingLoc); 1420 void parseUmbrellaDirDecl(SourceLocation UmbrellaLoc); 1421 void parseExportDecl(); 1422 void parseExportAsDecl(); 1423 void parseUseDecl(); 1424 void parseLinkDecl(); 1425 void parseConfigMacros(); 1426 void parseConflict(); 1427 void parseInferredModuleDecl(bool Framework, bool Explicit); 1428 1429 /// Private modules are canonicalized as Foo_Private. Clang provides extra 1430 /// module map search logic to find the appropriate private module when PCH 1431 /// is used with implicit module maps. Warn when private modules are written 1432 /// in other ways (FooPrivate and Foo.Private), providing notes and fixits. 1433 void diagnosePrivateModules(SourceLocation ExplicitLoc, 1434 SourceLocation FrameworkLoc); 1435 1436 using Attributes = ModuleMap::Attributes; 1437 1438 bool parseOptionalAttributes(Attributes &Attrs); 1439 1440 public: 1441 explicit ModuleMapParser(Lexer &L, SourceManager &SourceMgr, 1442 const TargetInfo *Target, DiagnosticsEngine &Diags, 1443 ModuleMap &Map, const FileEntry *ModuleMapFile, 1444 const DirectoryEntry *Directory, bool IsSystem) 1445 : L(L), SourceMgr(SourceMgr), Target(Target), Diags(Diags), Map(Map), 1446 ModuleMapFile(ModuleMapFile), Directory(Directory), 1447 IsSystem(IsSystem) { 1448 Tok.clear(); 1449 consumeToken(); 1450 } 1451 1452 bool parseModuleMapFile(); 1453 1454 bool terminatedByDirective() { return false; } 1455 SourceLocation getLocation() { return Tok.getLocation(); } 1456 }; 1457 1458 } // namespace clang 1459 1460 SourceLocation ModuleMapParser::consumeToken() { 1461 SourceLocation Result = Tok.getLocation(); 1462 1463 retry: 1464 Tok.clear(); 1465 Token LToken; 1466 L.LexFromRawLexer(LToken); 1467 Tok.Location = LToken.getLocation().getRawEncoding(); 1468 switch (LToken.getKind()) { 1469 case tok::raw_identifier: { 1470 StringRef RI = LToken.getRawIdentifier(); 1471 Tok.StringData = RI.data(); 1472 Tok.StringLength = RI.size(); 1473 Tok.Kind = llvm::StringSwitch<MMToken::TokenKind>(RI) 1474 .Case("config_macros", MMToken::ConfigMacros) 1475 .Case("conflict", MMToken::Conflict) 1476 .Case("exclude", MMToken::ExcludeKeyword) 1477 .Case("explicit", MMToken::ExplicitKeyword) 1478 .Case("export", MMToken::ExportKeyword) 1479 .Case("export_as", MMToken::ExportAsKeyword) 1480 .Case("extern", MMToken::ExternKeyword) 1481 .Case("framework", MMToken::FrameworkKeyword) 1482 .Case("header", MMToken::HeaderKeyword) 1483 .Case("link", MMToken::LinkKeyword) 1484 .Case("module", MMToken::ModuleKeyword) 1485 .Case("private", MMToken::PrivateKeyword) 1486 .Case("requires", MMToken::RequiresKeyword) 1487 .Case("textual", MMToken::TextualKeyword) 1488 .Case("umbrella", MMToken::UmbrellaKeyword) 1489 .Case("use", MMToken::UseKeyword) 1490 .Default(MMToken::Identifier); 1491 break; 1492 } 1493 1494 case tok::comma: 1495 Tok.Kind = MMToken::Comma; 1496 break; 1497 1498 case tok::eof: 1499 Tok.Kind = MMToken::EndOfFile; 1500 break; 1501 1502 case tok::l_brace: 1503 Tok.Kind = MMToken::LBrace; 1504 break; 1505 1506 case tok::l_square: 1507 Tok.Kind = MMToken::LSquare; 1508 break; 1509 1510 case tok::period: 1511 Tok.Kind = MMToken::Period; 1512 break; 1513 1514 case tok::r_brace: 1515 Tok.Kind = MMToken::RBrace; 1516 break; 1517 1518 case tok::r_square: 1519 Tok.Kind = MMToken::RSquare; 1520 break; 1521 1522 case tok::star: 1523 Tok.Kind = MMToken::Star; 1524 break; 1525 1526 case tok::exclaim: 1527 Tok.Kind = MMToken::Exclaim; 1528 break; 1529 1530 case tok::string_literal: { 1531 if (LToken.hasUDSuffix()) { 1532 Diags.Report(LToken.getLocation(), diag::err_invalid_string_udl); 1533 HadError = true; 1534 goto retry; 1535 } 1536 1537 // Parse the string literal. 1538 LangOptions LangOpts; 1539 StringLiteralParser StringLiteral(LToken, SourceMgr, LangOpts, *Target); 1540 if (StringLiteral.hadError) 1541 goto retry; 1542 1543 // Copy the string literal into our string data allocator. 1544 unsigned Length = StringLiteral.GetStringLength(); 1545 char *Saved = StringData.Allocate<char>(Length + 1); 1546 memcpy(Saved, StringLiteral.GetString().data(), Length); 1547 Saved[Length] = 0; 1548 1549 // Form the token. 1550 Tok.Kind = MMToken::StringLiteral; 1551 Tok.StringData = Saved; 1552 Tok.StringLength = Length; 1553 break; 1554 } 1555 1556 case tok::numeric_constant: { 1557 // We don't support any suffixes or other complications. 1558 SmallString<32> SpellingBuffer; 1559 SpellingBuffer.resize(LToken.getLength() + 1); 1560 const char *Start = SpellingBuffer.data(); 1561 unsigned Length = 1562 Lexer::getSpelling(LToken, Start, SourceMgr, L.getLangOpts()); 1563 uint64_t Value; 1564 if (StringRef(Start, Length).getAsInteger(0, Value)) { 1565 Diags.Report(Tok.getLocation(), diag::err_mmap_unknown_token); 1566 HadError = true; 1567 goto retry; 1568 } 1569 1570 Tok.Kind = MMToken::IntegerLiteral; 1571 Tok.IntegerValue = Value; 1572 break; 1573 } 1574 1575 case tok::comment: 1576 goto retry; 1577 1578 case tok::hash: 1579 // A module map can be terminated prematurely by 1580 // #pragma clang module contents 1581 // When building the module, we'll treat the rest of the file as the 1582 // contents of the module. 1583 { 1584 auto NextIsIdent = [&](StringRef Str) -> bool { 1585 L.LexFromRawLexer(LToken); 1586 return !LToken.isAtStartOfLine() && LToken.is(tok::raw_identifier) && 1587 LToken.getRawIdentifier() == Str; 1588 }; 1589 if (NextIsIdent("pragma") && NextIsIdent("clang") && 1590 NextIsIdent("module") && NextIsIdent("contents")) { 1591 Tok.Kind = MMToken::EndOfFile; 1592 break; 1593 } 1594 } 1595 LLVM_FALLTHROUGH; 1596 1597 default: 1598 Diags.Report(Tok.getLocation(), diag::err_mmap_unknown_token); 1599 HadError = true; 1600 goto retry; 1601 } 1602 1603 return Result; 1604 } 1605 1606 void ModuleMapParser::skipUntil(MMToken::TokenKind K) { 1607 unsigned braceDepth = 0; 1608 unsigned squareDepth = 0; 1609 do { 1610 switch (Tok.Kind) { 1611 case MMToken::EndOfFile: 1612 return; 1613 1614 case MMToken::LBrace: 1615 if (Tok.is(K) && braceDepth == 0 && squareDepth == 0) 1616 return; 1617 1618 ++braceDepth; 1619 break; 1620 1621 case MMToken::LSquare: 1622 if (Tok.is(K) && braceDepth == 0 && squareDepth == 0) 1623 return; 1624 1625 ++squareDepth; 1626 break; 1627 1628 case MMToken::RBrace: 1629 if (braceDepth > 0) 1630 --braceDepth; 1631 else if (Tok.is(K)) 1632 return; 1633 break; 1634 1635 case MMToken::RSquare: 1636 if (squareDepth > 0) 1637 --squareDepth; 1638 else if (Tok.is(K)) 1639 return; 1640 break; 1641 1642 default: 1643 if (braceDepth == 0 && squareDepth == 0 && Tok.is(K)) 1644 return; 1645 break; 1646 } 1647 1648 consumeToken(); 1649 } while (true); 1650 } 1651 1652 /// Parse a module-id. 1653 /// 1654 /// module-id: 1655 /// identifier 1656 /// identifier '.' module-id 1657 /// 1658 /// \returns true if an error occurred, false otherwise. 1659 bool ModuleMapParser::parseModuleId(ModuleId &Id) { 1660 Id.clear(); 1661 do { 1662 if (Tok.is(MMToken::Identifier) || Tok.is(MMToken::StringLiteral)) { 1663 Id.push_back(std::make_pair(Tok.getString(), Tok.getLocation())); 1664 consumeToken(); 1665 } else { 1666 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module_name); 1667 return true; 1668 } 1669 1670 if (!Tok.is(MMToken::Period)) 1671 break; 1672 1673 consumeToken(); 1674 } while (true); 1675 1676 return false; 1677 } 1678 1679 namespace { 1680 1681 /// Enumerates the known attributes. 1682 enum AttributeKind { 1683 /// An unknown attribute. 1684 AT_unknown, 1685 1686 /// The 'system' attribute. 1687 AT_system, 1688 1689 /// The 'extern_c' attribute. 1690 AT_extern_c, 1691 1692 /// The 'exhaustive' attribute. 1693 AT_exhaustive, 1694 1695 /// The 'no_undeclared_includes' attribute. 1696 AT_no_undeclared_includes 1697 }; 1698 1699 } // namespace 1700 1701 /// Private modules are canonicalized as Foo_Private. Clang provides extra 1702 /// module map search logic to find the appropriate private module when PCH 1703 /// is used with implicit module maps. Warn when private modules are written 1704 /// in other ways (FooPrivate and Foo.Private), providing notes and fixits. 1705 void ModuleMapParser::diagnosePrivateModules(SourceLocation ExplicitLoc, 1706 SourceLocation FrameworkLoc) { 1707 auto GenNoteAndFixIt = [&](StringRef BadName, StringRef Canonical, 1708 const Module *M, SourceRange ReplLoc) { 1709 auto D = Diags.Report(ActiveModule->DefinitionLoc, 1710 diag::note_mmap_rename_top_level_private_module); 1711 D << BadName << M->Name; 1712 D << FixItHint::CreateReplacement(ReplLoc, Canonical); 1713 }; 1714 1715 for (auto E = Map.module_begin(); E != Map.module_end(); ++E) { 1716 auto const *M = E->getValue(); 1717 if (M->Directory != ActiveModule->Directory) 1718 continue; 1719 1720 SmallString<128> FullName(ActiveModule->getFullModuleName()); 1721 if (!FullName.startswith(M->Name) && !FullName.endswith("Private")) 1722 continue; 1723 SmallString<128> FixedPrivModDecl; 1724 SmallString<128> Canonical(M->Name); 1725 Canonical.append("_Private"); 1726 1727 // Foo.Private -> Foo_Private 1728 if (ActiveModule->Parent && ActiveModule->Name == "Private" && !M->Parent && 1729 M->Name == ActiveModule->Parent->Name) { 1730 Diags.Report(ActiveModule->DefinitionLoc, 1731 diag::warn_mmap_mismatched_private_submodule) 1732 << FullName; 1733 1734 SourceLocation FixItInitBegin = CurrModuleDeclLoc; 1735 if (FrameworkLoc.isValid()) 1736 FixItInitBegin = FrameworkLoc; 1737 if (ExplicitLoc.isValid()) 1738 FixItInitBegin = ExplicitLoc; 1739 1740 if (FrameworkLoc.isValid() || ActiveModule->Parent->IsFramework) 1741 FixedPrivModDecl.append("framework "); 1742 FixedPrivModDecl.append("module "); 1743 FixedPrivModDecl.append(Canonical); 1744 1745 GenNoteAndFixIt(FullName, FixedPrivModDecl, M, 1746 SourceRange(FixItInitBegin, ActiveModule->DefinitionLoc)); 1747 continue; 1748 } 1749 1750 // FooPrivate and whatnots -> Foo_Private 1751 if (!ActiveModule->Parent && !M->Parent && M->Name != ActiveModule->Name && 1752 ActiveModule->Name != Canonical) { 1753 Diags.Report(ActiveModule->DefinitionLoc, 1754 diag::warn_mmap_mismatched_private_module_name) 1755 << ActiveModule->Name; 1756 GenNoteAndFixIt(ActiveModule->Name, Canonical, M, 1757 SourceRange(ActiveModule->DefinitionLoc)); 1758 } 1759 } 1760 } 1761 1762 /// Parse a module declaration. 1763 /// 1764 /// module-declaration: 1765 /// 'extern' 'module' module-id string-literal 1766 /// 'explicit'[opt] 'framework'[opt] 'module' module-id attributes[opt] 1767 /// { module-member* } 1768 /// 1769 /// module-member: 1770 /// requires-declaration 1771 /// header-declaration 1772 /// submodule-declaration 1773 /// export-declaration 1774 /// export-as-declaration 1775 /// link-declaration 1776 /// 1777 /// submodule-declaration: 1778 /// module-declaration 1779 /// inferred-submodule-declaration 1780 void ModuleMapParser::parseModuleDecl() { 1781 assert(Tok.is(MMToken::ExplicitKeyword) || Tok.is(MMToken::ModuleKeyword) || 1782 Tok.is(MMToken::FrameworkKeyword) || Tok.is(MMToken::ExternKeyword)); 1783 if (Tok.is(MMToken::ExternKeyword)) { 1784 parseExternModuleDecl(); 1785 return; 1786 } 1787 1788 // Parse 'explicit' or 'framework' keyword, if present. 1789 SourceLocation ExplicitLoc; 1790 SourceLocation FrameworkLoc; 1791 bool Explicit = false; 1792 bool Framework = false; 1793 1794 // Parse 'explicit' keyword, if present. 1795 if (Tok.is(MMToken::ExplicitKeyword)) { 1796 ExplicitLoc = consumeToken(); 1797 Explicit = true; 1798 } 1799 1800 // Parse 'framework' keyword, if present. 1801 if (Tok.is(MMToken::FrameworkKeyword)) { 1802 FrameworkLoc = consumeToken(); 1803 Framework = true; 1804 } 1805 1806 // Parse 'module' keyword. 1807 if (!Tok.is(MMToken::ModuleKeyword)) { 1808 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module); 1809 consumeToken(); 1810 HadError = true; 1811 return; 1812 } 1813 CurrModuleDeclLoc = consumeToken(); // 'module' keyword 1814 1815 // If we have a wildcard for the module name, this is an inferred submodule. 1816 // Parse it. 1817 if (Tok.is(MMToken::Star)) 1818 return parseInferredModuleDecl(Framework, Explicit); 1819 1820 // Parse the module name. 1821 ModuleId Id; 1822 if (parseModuleId(Id)) { 1823 HadError = true; 1824 return; 1825 } 1826 1827 if (ActiveModule) { 1828 if (Id.size() > 1) { 1829 Diags.Report(Id.front().second, diag::err_mmap_nested_submodule_id) 1830 << SourceRange(Id.front().second, Id.back().second); 1831 1832 HadError = true; 1833 return; 1834 } 1835 } else if (Id.size() == 1 && Explicit) { 1836 // Top-level modules can't be explicit. 1837 Diags.Report(ExplicitLoc, diag::err_mmap_explicit_top_level); 1838 Explicit = false; 1839 ExplicitLoc = SourceLocation(); 1840 HadError = true; 1841 } 1842 1843 Module *PreviousActiveModule = ActiveModule; 1844 if (Id.size() > 1) { 1845 // This module map defines a submodule. Go find the module of which it 1846 // is a submodule. 1847 ActiveModule = nullptr; 1848 const Module *TopLevelModule = nullptr; 1849 for (unsigned I = 0, N = Id.size() - 1; I != N; ++I) { 1850 if (Module *Next = Map.lookupModuleQualified(Id[I].first, ActiveModule)) { 1851 if (I == 0) 1852 TopLevelModule = Next; 1853 ActiveModule = Next; 1854 continue; 1855 } 1856 1857 if (ActiveModule) { 1858 Diags.Report(Id[I].second, diag::err_mmap_missing_module_qualified) 1859 << Id[I].first 1860 << ActiveModule->getTopLevelModule()->getFullModuleName(); 1861 } else { 1862 Diags.Report(Id[I].second, diag::err_mmap_expected_module_name); 1863 } 1864 HadError = true; 1865 return; 1866 } 1867 1868 if (ModuleMapFile != Map.getContainingModuleMapFile(TopLevelModule)) { 1869 assert(ModuleMapFile != Map.getModuleMapFileForUniquing(TopLevelModule) && 1870 "submodule defined in same file as 'module *' that allowed its " 1871 "top-level module"); 1872 Map.addAdditionalModuleMapFile(TopLevelModule, ModuleMapFile); 1873 } 1874 } 1875 1876 StringRef ModuleName = Id.back().first; 1877 SourceLocation ModuleNameLoc = Id.back().second; 1878 1879 // Parse the optional attribute list. 1880 Attributes Attrs; 1881 if (parseOptionalAttributes(Attrs)) 1882 return; 1883 1884 // Parse the opening brace. 1885 if (!Tok.is(MMToken::LBrace)) { 1886 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_lbrace) 1887 << ModuleName; 1888 HadError = true; 1889 return; 1890 } 1891 SourceLocation LBraceLoc = consumeToken(); 1892 1893 // Determine whether this (sub)module has already been defined. 1894 Module *ShadowingModule = nullptr; 1895 if (Module *Existing = Map.lookupModuleQualified(ModuleName, ActiveModule)) { 1896 // We might see a (re)definition of a module that we already have a 1897 // definition for in two cases: 1898 // - If we loaded one definition from an AST file and we've just found a 1899 // corresponding definition in a module map file, or 1900 bool LoadedFromASTFile = Existing->DefinitionLoc.isInvalid(); 1901 // - If we're building a (preprocessed) module and we've just loaded the 1902 // module map file from which it was created. 1903 bool ParsedAsMainInput = 1904 Map.LangOpts.getCompilingModule() == LangOptions::CMK_ModuleMap && 1905 Map.LangOpts.CurrentModule == ModuleName && 1906 SourceMgr.getDecomposedLoc(ModuleNameLoc).first != 1907 SourceMgr.getDecomposedLoc(Existing->DefinitionLoc).first; 1908 if (!ActiveModule && (LoadedFromASTFile || ParsedAsMainInput)) { 1909 // Skip the module definition. 1910 skipUntil(MMToken::RBrace); 1911 if (Tok.is(MMToken::RBrace)) 1912 consumeToken(); 1913 else { 1914 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace); 1915 Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match); 1916 HadError = true; 1917 } 1918 return; 1919 } 1920 1921 if (!Existing->Parent && Map.mayShadowNewModule(Existing)) { 1922 ShadowingModule = Existing; 1923 } else { 1924 // This is not a shawdowed module decl, it is an illegal redefinition. 1925 Diags.Report(ModuleNameLoc, diag::err_mmap_module_redefinition) 1926 << ModuleName; 1927 Diags.Report(Existing->DefinitionLoc, diag::note_mmap_prev_definition); 1928 1929 // Skip the module definition. 1930 skipUntil(MMToken::RBrace); 1931 if (Tok.is(MMToken::RBrace)) 1932 consumeToken(); 1933 1934 HadError = true; 1935 return; 1936 } 1937 } 1938 1939 // Start defining this module. 1940 if (ShadowingModule) { 1941 ActiveModule = 1942 Map.createShadowedModule(ModuleName, Framework, ShadowingModule); 1943 } else { 1944 ActiveModule = 1945 Map.findOrCreateModule(ModuleName, ActiveModule, Framework, Explicit) 1946 .first; 1947 } 1948 1949 ActiveModule->DefinitionLoc = ModuleNameLoc; 1950 if (Attrs.IsSystem || IsSystem) 1951 ActiveModule->IsSystem = true; 1952 if (Attrs.IsExternC) 1953 ActiveModule->IsExternC = true; 1954 if (Attrs.NoUndeclaredIncludes || 1955 (!ActiveModule->Parent && ModuleName == "Darwin")) 1956 ActiveModule->NoUndeclaredIncludes = true; 1957 ActiveModule->Directory = Directory; 1958 1959 StringRef MapFileName(ModuleMapFile->getName()); 1960 if (MapFileName.endswith("module.private.modulemap") || 1961 MapFileName.endswith("module_private.map")) { 1962 ActiveModule->ModuleMapIsPrivate = true; 1963 } 1964 1965 // Private modules named as FooPrivate, Foo.Private or similar are likely a 1966 // user error; provide warnings, notes and fixits to direct users to use 1967 // Foo_Private instead. 1968 SourceLocation StartLoc = 1969 SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID()); 1970 if (Map.HeaderInfo.getHeaderSearchOpts().ImplicitModuleMaps && 1971 !Diags.isIgnored(diag::warn_mmap_mismatched_private_submodule, 1972 StartLoc) && 1973 !Diags.isIgnored(diag::warn_mmap_mismatched_private_module_name, 1974 StartLoc) && 1975 ActiveModule->ModuleMapIsPrivate) 1976 diagnosePrivateModules(ExplicitLoc, FrameworkLoc); 1977 1978 bool Done = false; 1979 do { 1980 switch (Tok.Kind) { 1981 case MMToken::EndOfFile: 1982 case MMToken::RBrace: 1983 Done = true; 1984 break; 1985 1986 case MMToken::ConfigMacros: 1987 parseConfigMacros(); 1988 break; 1989 1990 case MMToken::Conflict: 1991 parseConflict(); 1992 break; 1993 1994 case MMToken::ExplicitKeyword: 1995 case MMToken::ExternKeyword: 1996 case MMToken::FrameworkKeyword: 1997 case MMToken::ModuleKeyword: 1998 parseModuleDecl(); 1999 break; 2000 2001 case MMToken::ExportKeyword: 2002 parseExportDecl(); 2003 break; 2004 2005 case MMToken::ExportAsKeyword: 2006 parseExportAsDecl(); 2007 break; 2008 2009 case MMToken::UseKeyword: 2010 parseUseDecl(); 2011 break; 2012 2013 case MMToken::RequiresKeyword: 2014 parseRequiresDecl(); 2015 break; 2016 2017 case MMToken::TextualKeyword: 2018 parseHeaderDecl(MMToken::TextualKeyword, consumeToken()); 2019 break; 2020 2021 case MMToken::UmbrellaKeyword: { 2022 SourceLocation UmbrellaLoc = consumeToken(); 2023 if (Tok.is(MMToken::HeaderKeyword)) 2024 parseHeaderDecl(MMToken::UmbrellaKeyword, UmbrellaLoc); 2025 else 2026 parseUmbrellaDirDecl(UmbrellaLoc); 2027 break; 2028 } 2029 2030 case MMToken::ExcludeKeyword: 2031 parseHeaderDecl(MMToken::ExcludeKeyword, consumeToken()); 2032 break; 2033 2034 case MMToken::PrivateKeyword: 2035 parseHeaderDecl(MMToken::PrivateKeyword, consumeToken()); 2036 break; 2037 2038 case MMToken::HeaderKeyword: 2039 parseHeaderDecl(MMToken::HeaderKeyword, consumeToken()); 2040 break; 2041 2042 case MMToken::LinkKeyword: 2043 parseLinkDecl(); 2044 break; 2045 2046 default: 2047 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_member); 2048 consumeToken(); 2049 break; 2050 } 2051 } while (!Done); 2052 2053 if (Tok.is(MMToken::RBrace)) 2054 consumeToken(); 2055 else { 2056 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace); 2057 Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match); 2058 HadError = true; 2059 } 2060 2061 // If the active module is a top-level framework, and there are no link 2062 // libraries, automatically link against the framework. 2063 if (ActiveModule->IsFramework && !ActiveModule->isSubFramework() && 2064 ActiveModule->LinkLibraries.empty()) { 2065 inferFrameworkLink(ActiveModule, Directory, SourceMgr.getFileManager()); 2066 } 2067 2068 // If the module meets all requirements but is still unavailable, mark the 2069 // whole tree as unavailable to prevent it from building. 2070 if (!ActiveModule->IsAvailable && !ActiveModule->IsMissingRequirement && 2071 ActiveModule->Parent) { 2072 ActiveModule->getTopLevelModule()->markUnavailable(); 2073 ActiveModule->getTopLevelModule()->MissingHeaders.append( 2074 ActiveModule->MissingHeaders.begin(), ActiveModule->MissingHeaders.end()); 2075 } 2076 2077 // We're done parsing this module. Pop back to the previous module. 2078 ActiveModule = PreviousActiveModule; 2079 } 2080 2081 /// Parse an extern module declaration. 2082 /// 2083 /// extern module-declaration: 2084 /// 'extern' 'module' module-id string-literal 2085 void ModuleMapParser::parseExternModuleDecl() { 2086 assert(Tok.is(MMToken::ExternKeyword)); 2087 SourceLocation ExternLoc = consumeToken(); // 'extern' keyword 2088 2089 // Parse 'module' keyword. 2090 if (!Tok.is(MMToken::ModuleKeyword)) { 2091 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module); 2092 consumeToken(); 2093 HadError = true; 2094 return; 2095 } 2096 consumeToken(); // 'module' keyword 2097 2098 // Parse the module name. 2099 ModuleId Id; 2100 if (parseModuleId(Id)) { 2101 HadError = true; 2102 return; 2103 } 2104 2105 // Parse the referenced module map file name. 2106 if (!Tok.is(MMToken::StringLiteral)) { 2107 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_mmap_file); 2108 HadError = true; 2109 return; 2110 } 2111 std::string FileName = Tok.getString(); 2112 consumeToken(); // filename 2113 2114 StringRef FileNameRef = FileName; 2115 SmallString<128> ModuleMapFileName; 2116 if (llvm::sys::path::is_relative(FileNameRef)) { 2117 ModuleMapFileName += Directory->getName(); 2118 llvm::sys::path::append(ModuleMapFileName, FileName); 2119 FileNameRef = ModuleMapFileName; 2120 } 2121 if (const FileEntry *File = SourceMgr.getFileManager().getFile(FileNameRef)) 2122 Map.parseModuleMapFile( 2123 File, /*IsSystem=*/false, 2124 Map.HeaderInfo.getHeaderSearchOpts().ModuleMapFileHomeIsCwd 2125 ? Directory 2126 : File->getDir(), 2127 FileID(), nullptr, ExternLoc); 2128 } 2129 2130 /// Whether to add the requirement \p Feature to the module \p M. 2131 /// 2132 /// This preserves backwards compatibility for two hacks in the Darwin system 2133 /// module map files: 2134 /// 2135 /// 1. The use of 'requires excluded' to make headers non-modular, which 2136 /// should really be mapped to 'textual' now that we have this feature. We 2137 /// drop the 'excluded' requirement, and set \p IsRequiresExcludedHack to 2138 /// true. Later, this bit will be used to map all the headers inside this 2139 /// module to 'textual'. 2140 /// 2141 /// This affects Darwin.C.excluded (for assert.h) and Tcl.Private. 2142 /// 2143 /// 2. Removes a bogus cplusplus requirement from IOKit.avc. This requirement 2144 /// was never correct and causes issues now that we check it, so drop it. 2145 static bool shouldAddRequirement(Module *M, StringRef Feature, 2146 bool &IsRequiresExcludedHack) { 2147 if (Feature == "excluded" && 2148 (M->fullModuleNameIs({"Darwin", "C", "excluded"}) || 2149 M->fullModuleNameIs({"Tcl", "Private"}))) { 2150 IsRequiresExcludedHack = true; 2151 return false; 2152 } else if (Feature == "cplusplus" && M->fullModuleNameIs({"IOKit", "avc"})) { 2153 return false; 2154 } 2155 2156 return true; 2157 } 2158 2159 /// Parse a requires declaration. 2160 /// 2161 /// requires-declaration: 2162 /// 'requires' feature-list 2163 /// 2164 /// feature-list: 2165 /// feature ',' feature-list 2166 /// feature 2167 /// 2168 /// feature: 2169 /// '!'[opt] identifier 2170 void ModuleMapParser::parseRequiresDecl() { 2171 assert(Tok.is(MMToken::RequiresKeyword)); 2172 2173 // Parse 'requires' keyword. 2174 consumeToken(); 2175 2176 // Parse the feature-list. 2177 do { 2178 bool RequiredState = true; 2179 if (Tok.is(MMToken::Exclaim)) { 2180 RequiredState = false; 2181 consumeToken(); 2182 } 2183 2184 if (!Tok.is(MMToken::Identifier)) { 2185 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_feature); 2186 HadError = true; 2187 return; 2188 } 2189 2190 // Consume the feature name. 2191 std::string Feature = Tok.getString(); 2192 consumeToken(); 2193 2194 bool IsRequiresExcludedHack = false; 2195 bool ShouldAddRequirement = 2196 shouldAddRequirement(ActiveModule, Feature, IsRequiresExcludedHack); 2197 2198 if (IsRequiresExcludedHack) 2199 UsesRequiresExcludedHack.insert(ActiveModule); 2200 2201 if (ShouldAddRequirement) { 2202 // Add this feature. 2203 ActiveModule->addRequirement(Feature, RequiredState, Map.LangOpts, 2204 *Map.Target); 2205 } 2206 2207 if (!Tok.is(MMToken::Comma)) 2208 break; 2209 2210 // Consume the comma. 2211 consumeToken(); 2212 } while (true); 2213 } 2214 2215 /// Parse a header declaration. 2216 /// 2217 /// header-declaration: 2218 /// 'textual'[opt] 'header' string-literal 2219 /// 'private' 'textual'[opt] 'header' string-literal 2220 /// 'exclude' 'header' string-literal 2221 /// 'umbrella' 'header' string-literal 2222 /// 2223 /// FIXME: Support 'private textual header'. 2224 void ModuleMapParser::parseHeaderDecl(MMToken::TokenKind LeadingToken, 2225 SourceLocation LeadingLoc) { 2226 // We've already consumed the first token. 2227 ModuleMap::ModuleHeaderRole Role = ModuleMap::NormalHeader; 2228 if (LeadingToken == MMToken::PrivateKeyword) { 2229 Role = ModuleMap::PrivateHeader; 2230 // 'private' may optionally be followed by 'textual'. 2231 if (Tok.is(MMToken::TextualKeyword)) { 2232 LeadingToken = Tok.Kind; 2233 consumeToken(); 2234 } 2235 } 2236 2237 if (LeadingToken == MMToken::TextualKeyword) 2238 Role = ModuleMap::ModuleHeaderRole(Role | ModuleMap::TextualHeader); 2239 2240 if (UsesRequiresExcludedHack.count(ActiveModule)) { 2241 // Mark this header 'textual' (see doc comment for 2242 // Module::UsesRequiresExcludedHack). 2243 Role = ModuleMap::ModuleHeaderRole(Role | ModuleMap::TextualHeader); 2244 } 2245 2246 if (LeadingToken != MMToken::HeaderKeyword) { 2247 if (!Tok.is(MMToken::HeaderKeyword)) { 2248 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header) 2249 << (LeadingToken == MMToken::PrivateKeyword ? "private" : 2250 LeadingToken == MMToken::ExcludeKeyword ? "exclude" : 2251 LeadingToken == MMToken::TextualKeyword ? "textual" : "umbrella"); 2252 return; 2253 } 2254 consumeToken(); 2255 } 2256 2257 // Parse the header name. 2258 if (!Tok.is(MMToken::StringLiteral)) { 2259 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header) 2260 << "header"; 2261 HadError = true; 2262 return; 2263 } 2264 Module::UnresolvedHeaderDirective Header; 2265 Header.FileName = Tok.getString(); 2266 Header.FileNameLoc = consumeToken(); 2267 Header.IsUmbrella = LeadingToken == MMToken::UmbrellaKeyword; 2268 Header.Kind = 2269 (LeadingToken == MMToken::ExcludeKeyword ? Module::HK_Excluded 2270 : Map.headerRoleToKind(Role)); 2271 2272 // Check whether we already have an umbrella. 2273 if (Header.IsUmbrella && ActiveModule->Umbrella) { 2274 Diags.Report(Header.FileNameLoc, diag::err_mmap_umbrella_clash) 2275 << ActiveModule->getFullModuleName(); 2276 HadError = true; 2277 return; 2278 } 2279 2280 // If we were given stat information, parse it so we can skip looking for 2281 // the file. 2282 if (Tok.is(MMToken::LBrace)) { 2283 SourceLocation LBraceLoc = consumeToken(); 2284 2285 while (!Tok.is(MMToken::RBrace) && !Tok.is(MMToken::EndOfFile)) { 2286 enum Attribute { Size, ModTime, Unknown }; 2287 StringRef Str = Tok.getString(); 2288 SourceLocation Loc = consumeToken(); 2289 switch (llvm::StringSwitch<Attribute>(Str) 2290 .Case("size", Size) 2291 .Case("mtime", ModTime) 2292 .Default(Unknown)) { 2293 case Size: 2294 if (Header.Size) 2295 Diags.Report(Loc, diag::err_mmap_duplicate_header_attribute) << Str; 2296 if (!Tok.is(MMToken::IntegerLiteral)) { 2297 Diags.Report(Tok.getLocation(), 2298 diag::err_mmap_invalid_header_attribute_value) << Str; 2299 skipUntil(MMToken::RBrace); 2300 break; 2301 } 2302 Header.Size = Tok.getInteger(); 2303 consumeToken(); 2304 break; 2305 2306 case ModTime: 2307 if (Header.ModTime) 2308 Diags.Report(Loc, diag::err_mmap_duplicate_header_attribute) << Str; 2309 if (!Tok.is(MMToken::IntegerLiteral)) { 2310 Diags.Report(Tok.getLocation(), 2311 diag::err_mmap_invalid_header_attribute_value) << Str; 2312 skipUntil(MMToken::RBrace); 2313 break; 2314 } 2315 Header.ModTime = Tok.getInteger(); 2316 consumeToken(); 2317 break; 2318 2319 case Unknown: 2320 Diags.Report(Loc, diag::err_mmap_expected_header_attribute); 2321 skipUntil(MMToken::RBrace); 2322 break; 2323 } 2324 } 2325 2326 if (Tok.is(MMToken::RBrace)) 2327 consumeToken(); 2328 else { 2329 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace); 2330 Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match); 2331 HadError = true; 2332 } 2333 } 2334 2335 bool NeedsFramework = false; 2336 Map.addUnresolvedHeader(ActiveModule, std::move(Header), NeedsFramework); 2337 2338 if (NeedsFramework && ActiveModule) 2339 Diags.Report(CurrModuleDeclLoc, diag::note_mmap_add_framework_keyword) 2340 << ActiveModule->getFullModuleName() 2341 << FixItHint::CreateReplacement(CurrModuleDeclLoc, "framework module"); 2342 } 2343 2344 static int compareModuleHeaders(const Module::Header *A, 2345 const Module::Header *B) { 2346 return A->NameAsWritten.compare(B->NameAsWritten); 2347 } 2348 2349 /// Parse an umbrella directory declaration. 2350 /// 2351 /// umbrella-dir-declaration: 2352 /// umbrella string-literal 2353 void ModuleMapParser::parseUmbrellaDirDecl(SourceLocation UmbrellaLoc) { 2354 // Parse the directory name. 2355 if (!Tok.is(MMToken::StringLiteral)) { 2356 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header) 2357 << "umbrella"; 2358 HadError = true; 2359 return; 2360 } 2361 2362 std::string DirName = Tok.getString(); 2363 SourceLocation DirNameLoc = consumeToken(); 2364 2365 // Check whether we already have an umbrella. 2366 if (ActiveModule->Umbrella) { 2367 Diags.Report(DirNameLoc, diag::err_mmap_umbrella_clash) 2368 << ActiveModule->getFullModuleName(); 2369 HadError = true; 2370 return; 2371 } 2372 2373 // Look for this file. 2374 const DirectoryEntry *Dir = nullptr; 2375 if (llvm::sys::path::is_absolute(DirName)) 2376 Dir = SourceMgr.getFileManager().getDirectory(DirName); 2377 else { 2378 SmallString<128> PathName; 2379 PathName = Directory->getName(); 2380 llvm::sys::path::append(PathName, DirName); 2381 Dir = SourceMgr.getFileManager().getDirectory(PathName); 2382 } 2383 2384 if (!Dir) { 2385 Diags.Report(DirNameLoc, diag::warn_mmap_umbrella_dir_not_found) 2386 << DirName; 2387 return; 2388 } 2389 2390 if (UsesRequiresExcludedHack.count(ActiveModule)) { 2391 // Mark this header 'textual' (see doc comment for 2392 // ModuleMapParser::UsesRequiresExcludedHack). Although iterating over the 2393 // directory is relatively expensive, in practice this only applies to the 2394 // uncommonly used Tcl module on Darwin platforms. 2395 std::error_code EC; 2396 SmallVector<Module::Header, 6> Headers; 2397 vfs::FileSystem &FS = *SourceMgr.getFileManager().getVirtualFileSystem(); 2398 for (vfs::recursive_directory_iterator I(FS, Dir->getName(), EC), E; 2399 I != E && !EC; I.increment(EC)) { 2400 if (const FileEntry *FE = SourceMgr.getFileManager().getFile(I->path())) { 2401 2402 Module::Header Header = {I->path(), FE}; 2403 Headers.push_back(std::move(Header)); 2404 } 2405 } 2406 2407 // Sort header paths so that the pcm doesn't depend on iteration order. 2408 llvm::array_pod_sort(Headers.begin(), Headers.end(), compareModuleHeaders); 2409 2410 for (auto &Header : Headers) 2411 Map.addHeader(ActiveModule, std::move(Header), ModuleMap::TextualHeader); 2412 return; 2413 } 2414 2415 if (Module *OwningModule = Map.UmbrellaDirs[Dir]) { 2416 Diags.Report(UmbrellaLoc, diag::err_mmap_umbrella_clash) 2417 << OwningModule->getFullModuleName(); 2418 HadError = true; 2419 return; 2420 } 2421 2422 // Record this umbrella directory. 2423 Map.setUmbrellaDir(ActiveModule, Dir, DirName); 2424 } 2425 2426 /// Parse a module export declaration. 2427 /// 2428 /// export-declaration: 2429 /// 'export' wildcard-module-id 2430 /// 2431 /// wildcard-module-id: 2432 /// identifier 2433 /// '*' 2434 /// identifier '.' wildcard-module-id 2435 void ModuleMapParser::parseExportDecl() { 2436 assert(Tok.is(MMToken::ExportKeyword)); 2437 SourceLocation ExportLoc = consumeToken(); 2438 2439 // Parse the module-id with an optional wildcard at the end. 2440 ModuleId ParsedModuleId; 2441 bool Wildcard = false; 2442 do { 2443 // FIXME: Support string-literal module names here. 2444 if (Tok.is(MMToken::Identifier)) { 2445 ParsedModuleId.push_back(std::make_pair(Tok.getString(), 2446 Tok.getLocation())); 2447 consumeToken(); 2448 2449 if (Tok.is(MMToken::Period)) { 2450 consumeToken(); 2451 continue; 2452 } 2453 2454 break; 2455 } 2456 2457 if(Tok.is(MMToken::Star)) { 2458 Wildcard = true; 2459 consumeToken(); 2460 break; 2461 } 2462 2463 Diags.Report(Tok.getLocation(), diag::err_mmap_module_id); 2464 HadError = true; 2465 return; 2466 } while (true); 2467 2468 Module::UnresolvedExportDecl Unresolved = { 2469 ExportLoc, ParsedModuleId, Wildcard 2470 }; 2471 ActiveModule->UnresolvedExports.push_back(Unresolved); 2472 } 2473 2474 /// Parse a module export_as declaration. 2475 /// 2476 /// export-as-declaration: 2477 /// 'export_as' identifier 2478 void ModuleMapParser::parseExportAsDecl() { 2479 assert(Tok.is(MMToken::ExportAsKeyword)); 2480 consumeToken(); 2481 2482 if (!Tok.is(MMToken::Identifier)) { 2483 Diags.Report(Tok.getLocation(), diag::err_mmap_module_id); 2484 HadError = true; 2485 return; 2486 } 2487 2488 if (ActiveModule->Parent) { 2489 Diags.Report(Tok.getLocation(), diag::err_mmap_submodule_export_as); 2490 consumeToken(); 2491 return; 2492 } 2493 2494 if (!ActiveModule->ExportAsModule.empty()) { 2495 if (ActiveModule->ExportAsModule == Tok.getString()) { 2496 Diags.Report(Tok.getLocation(), diag::warn_mmap_redundant_export_as) 2497 << ActiveModule->Name << Tok.getString(); 2498 } else { 2499 Diags.Report(Tok.getLocation(), diag::err_mmap_conflicting_export_as) 2500 << ActiveModule->Name << ActiveModule->ExportAsModule 2501 << Tok.getString(); 2502 } 2503 } 2504 2505 ActiveModule->ExportAsModule = Tok.getString(); 2506 Map.addLinkAsDependency(ActiveModule); 2507 2508 consumeToken(); 2509 } 2510 2511 /// Parse a module use declaration. 2512 /// 2513 /// use-declaration: 2514 /// 'use' wildcard-module-id 2515 void ModuleMapParser::parseUseDecl() { 2516 assert(Tok.is(MMToken::UseKeyword)); 2517 auto KWLoc = consumeToken(); 2518 // Parse the module-id. 2519 ModuleId ParsedModuleId; 2520 parseModuleId(ParsedModuleId); 2521 2522 if (ActiveModule->Parent) 2523 Diags.Report(KWLoc, diag::err_mmap_use_decl_submodule); 2524 else 2525 ActiveModule->UnresolvedDirectUses.push_back(ParsedModuleId); 2526 } 2527 2528 /// Parse a link declaration. 2529 /// 2530 /// module-declaration: 2531 /// 'link' 'framework'[opt] string-literal 2532 void ModuleMapParser::parseLinkDecl() { 2533 assert(Tok.is(MMToken::LinkKeyword)); 2534 SourceLocation LinkLoc = consumeToken(); 2535 2536 // Parse the optional 'framework' keyword. 2537 bool IsFramework = false; 2538 if (Tok.is(MMToken::FrameworkKeyword)) { 2539 consumeToken(); 2540 IsFramework = true; 2541 } 2542 2543 // Parse the library name 2544 if (!Tok.is(MMToken::StringLiteral)) { 2545 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_library_name) 2546 << IsFramework << SourceRange(LinkLoc); 2547 HadError = true; 2548 return; 2549 } 2550 2551 std::string LibraryName = Tok.getString(); 2552 consumeToken(); 2553 ActiveModule->LinkLibraries.push_back(Module::LinkLibrary(LibraryName, 2554 IsFramework)); 2555 } 2556 2557 /// Parse a configuration macro declaration. 2558 /// 2559 /// module-declaration: 2560 /// 'config_macros' attributes[opt] config-macro-list? 2561 /// 2562 /// config-macro-list: 2563 /// identifier (',' identifier)? 2564 void ModuleMapParser::parseConfigMacros() { 2565 assert(Tok.is(MMToken::ConfigMacros)); 2566 SourceLocation ConfigMacrosLoc = consumeToken(); 2567 2568 // Only top-level modules can have configuration macros. 2569 if (ActiveModule->Parent) { 2570 Diags.Report(ConfigMacrosLoc, diag::err_mmap_config_macro_submodule); 2571 } 2572 2573 // Parse the optional attributes. 2574 Attributes Attrs; 2575 if (parseOptionalAttributes(Attrs)) 2576 return; 2577 2578 if (Attrs.IsExhaustive && !ActiveModule->Parent) { 2579 ActiveModule->ConfigMacrosExhaustive = true; 2580 } 2581 2582 // If we don't have an identifier, we're done. 2583 // FIXME: Support macros with the same name as a keyword here. 2584 if (!Tok.is(MMToken::Identifier)) 2585 return; 2586 2587 // Consume the first identifier. 2588 if (!ActiveModule->Parent) { 2589 ActiveModule->ConfigMacros.push_back(Tok.getString().str()); 2590 } 2591 consumeToken(); 2592 2593 do { 2594 // If there's a comma, consume it. 2595 if (!Tok.is(MMToken::Comma)) 2596 break; 2597 consumeToken(); 2598 2599 // We expect to see a macro name here. 2600 // FIXME: Support macros with the same name as a keyword here. 2601 if (!Tok.is(MMToken::Identifier)) { 2602 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_config_macro); 2603 break; 2604 } 2605 2606 // Consume the macro name. 2607 if (!ActiveModule->Parent) { 2608 ActiveModule->ConfigMacros.push_back(Tok.getString().str()); 2609 } 2610 consumeToken(); 2611 } while (true); 2612 } 2613 2614 /// Format a module-id into a string. 2615 static std::string formatModuleId(const ModuleId &Id) { 2616 std::string result; 2617 { 2618 llvm::raw_string_ostream OS(result); 2619 2620 for (unsigned I = 0, N = Id.size(); I != N; ++I) { 2621 if (I) 2622 OS << "."; 2623 OS << Id[I].first; 2624 } 2625 } 2626 2627 return result; 2628 } 2629 2630 /// Parse a conflict declaration. 2631 /// 2632 /// module-declaration: 2633 /// 'conflict' module-id ',' string-literal 2634 void ModuleMapParser::parseConflict() { 2635 assert(Tok.is(MMToken::Conflict)); 2636 SourceLocation ConflictLoc = consumeToken(); 2637 Module::UnresolvedConflict Conflict; 2638 2639 // Parse the module-id. 2640 if (parseModuleId(Conflict.Id)) 2641 return; 2642 2643 // Parse the ','. 2644 if (!Tok.is(MMToken::Comma)) { 2645 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_conflicts_comma) 2646 << SourceRange(ConflictLoc); 2647 return; 2648 } 2649 consumeToken(); 2650 2651 // Parse the message. 2652 if (!Tok.is(MMToken::StringLiteral)) { 2653 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_conflicts_message) 2654 << formatModuleId(Conflict.Id); 2655 return; 2656 } 2657 Conflict.Message = Tok.getString().str(); 2658 consumeToken(); 2659 2660 // Add this unresolved conflict. 2661 ActiveModule->UnresolvedConflicts.push_back(Conflict); 2662 } 2663 2664 /// Parse an inferred module declaration (wildcard modules). 2665 /// 2666 /// module-declaration: 2667 /// 'explicit'[opt] 'framework'[opt] 'module' * attributes[opt] 2668 /// { inferred-module-member* } 2669 /// 2670 /// inferred-module-member: 2671 /// 'export' '*' 2672 /// 'exclude' identifier 2673 void ModuleMapParser::parseInferredModuleDecl(bool Framework, bool Explicit) { 2674 assert(Tok.is(MMToken::Star)); 2675 SourceLocation StarLoc = consumeToken(); 2676 bool Failed = false; 2677 2678 // Inferred modules must be submodules. 2679 if (!ActiveModule && !Framework) { 2680 Diags.Report(StarLoc, diag::err_mmap_top_level_inferred_submodule); 2681 Failed = true; 2682 } 2683 2684 if (ActiveModule) { 2685 // Inferred modules must have umbrella directories. 2686 if (!Failed && ActiveModule->IsAvailable && 2687 !ActiveModule->getUmbrellaDir()) { 2688 Diags.Report(StarLoc, diag::err_mmap_inferred_no_umbrella); 2689 Failed = true; 2690 } 2691 2692 // Check for redefinition of an inferred module. 2693 if (!Failed && ActiveModule->InferSubmodules) { 2694 Diags.Report(StarLoc, diag::err_mmap_inferred_redef); 2695 if (ActiveModule->InferredSubmoduleLoc.isValid()) 2696 Diags.Report(ActiveModule->InferredSubmoduleLoc, 2697 diag::note_mmap_prev_definition); 2698 Failed = true; 2699 } 2700 2701 // Check for the 'framework' keyword, which is not permitted here. 2702 if (Framework) { 2703 Diags.Report(StarLoc, diag::err_mmap_inferred_framework_submodule); 2704 Framework = false; 2705 } 2706 } else if (Explicit) { 2707 Diags.Report(StarLoc, diag::err_mmap_explicit_inferred_framework); 2708 Explicit = false; 2709 } 2710 2711 // If there were any problems with this inferred submodule, skip its body. 2712 if (Failed) { 2713 if (Tok.is(MMToken::LBrace)) { 2714 consumeToken(); 2715 skipUntil(MMToken::RBrace); 2716 if (Tok.is(MMToken::RBrace)) 2717 consumeToken(); 2718 } 2719 HadError = true; 2720 return; 2721 } 2722 2723 // Parse optional attributes. 2724 Attributes Attrs; 2725 if (parseOptionalAttributes(Attrs)) 2726 return; 2727 2728 if (ActiveModule) { 2729 // Note that we have an inferred submodule. 2730 ActiveModule->InferSubmodules = true; 2731 ActiveModule->InferredSubmoduleLoc = StarLoc; 2732 ActiveModule->InferExplicitSubmodules = Explicit; 2733 } else { 2734 // We'll be inferring framework modules for this directory. 2735 Map.InferredDirectories[Directory].InferModules = true; 2736 Map.InferredDirectories[Directory].Attrs = Attrs; 2737 Map.InferredDirectories[Directory].ModuleMapFile = ModuleMapFile; 2738 // FIXME: Handle the 'framework' keyword. 2739 } 2740 2741 // Parse the opening brace. 2742 if (!Tok.is(MMToken::LBrace)) { 2743 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_lbrace_wildcard); 2744 HadError = true; 2745 return; 2746 } 2747 SourceLocation LBraceLoc = consumeToken(); 2748 2749 // Parse the body of the inferred submodule. 2750 bool Done = false; 2751 do { 2752 switch (Tok.Kind) { 2753 case MMToken::EndOfFile: 2754 case MMToken::RBrace: 2755 Done = true; 2756 break; 2757 2758 case MMToken::ExcludeKeyword: 2759 if (ActiveModule) { 2760 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member) 2761 << (ActiveModule != nullptr); 2762 consumeToken(); 2763 break; 2764 } 2765 2766 consumeToken(); 2767 // FIXME: Support string-literal module names here. 2768 if (!Tok.is(MMToken::Identifier)) { 2769 Diags.Report(Tok.getLocation(), diag::err_mmap_missing_exclude_name); 2770 break; 2771 } 2772 2773 Map.InferredDirectories[Directory].ExcludedModules 2774 .push_back(Tok.getString()); 2775 consumeToken(); 2776 break; 2777 2778 case MMToken::ExportKeyword: 2779 if (!ActiveModule) { 2780 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member) 2781 << (ActiveModule != nullptr); 2782 consumeToken(); 2783 break; 2784 } 2785 2786 consumeToken(); 2787 if (Tok.is(MMToken::Star)) 2788 ActiveModule->InferExportWildcard = true; 2789 else 2790 Diags.Report(Tok.getLocation(), 2791 diag::err_mmap_expected_export_wildcard); 2792 consumeToken(); 2793 break; 2794 2795 case MMToken::ExplicitKeyword: 2796 case MMToken::ModuleKeyword: 2797 case MMToken::HeaderKeyword: 2798 case MMToken::PrivateKeyword: 2799 case MMToken::UmbrellaKeyword: 2800 default: 2801 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member) 2802 << (ActiveModule != nullptr); 2803 consumeToken(); 2804 break; 2805 } 2806 } while (!Done); 2807 2808 if (Tok.is(MMToken::RBrace)) 2809 consumeToken(); 2810 else { 2811 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace); 2812 Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match); 2813 HadError = true; 2814 } 2815 } 2816 2817 /// Parse optional attributes. 2818 /// 2819 /// attributes: 2820 /// attribute attributes 2821 /// attribute 2822 /// 2823 /// attribute: 2824 /// [ identifier ] 2825 /// 2826 /// \param Attrs Will be filled in with the parsed attributes. 2827 /// 2828 /// \returns true if an error occurred, false otherwise. 2829 bool ModuleMapParser::parseOptionalAttributes(Attributes &Attrs) { 2830 bool HadError = false; 2831 2832 while (Tok.is(MMToken::LSquare)) { 2833 // Consume the '['. 2834 SourceLocation LSquareLoc = consumeToken(); 2835 2836 // Check whether we have an attribute name here. 2837 if (!Tok.is(MMToken::Identifier)) { 2838 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_attribute); 2839 skipUntil(MMToken::RSquare); 2840 if (Tok.is(MMToken::RSquare)) 2841 consumeToken(); 2842 HadError = true; 2843 } 2844 2845 // Decode the attribute name. 2846 AttributeKind Attribute 2847 = llvm::StringSwitch<AttributeKind>(Tok.getString()) 2848 .Case("exhaustive", AT_exhaustive) 2849 .Case("extern_c", AT_extern_c) 2850 .Case("no_undeclared_includes", AT_no_undeclared_includes) 2851 .Case("system", AT_system) 2852 .Default(AT_unknown); 2853 switch (Attribute) { 2854 case AT_unknown: 2855 Diags.Report(Tok.getLocation(), diag::warn_mmap_unknown_attribute) 2856 << Tok.getString(); 2857 break; 2858 2859 case AT_system: 2860 Attrs.IsSystem = true; 2861 break; 2862 2863 case AT_extern_c: 2864 Attrs.IsExternC = true; 2865 break; 2866 2867 case AT_exhaustive: 2868 Attrs.IsExhaustive = true; 2869 break; 2870 2871 case AT_no_undeclared_includes: 2872 Attrs.NoUndeclaredIncludes = true; 2873 break; 2874 } 2875 consumeToken(); 2876 2877 // Consume the ']'. 2878 if (!Tok.is(MMToken::RSquare)) { 2879 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rsquare); 2880 Diags.Report(LSquareLoc, diag::note_mmap_lsquare_match); 2881 skipUntil(MMToken::RSquare); 2882 HadError = true; 2883 } 2884 2885 if (Tok.is(MMToken::RSquare)) 2886 consumeToken(); 2887 } 2888 2889 return HadError; 2890 } 2891 2892 /// Parse a module map file. 2893 /// 2894 /// module-map-file: 2895 /// module-declaration* 2896 bool ModuleMapParser::parseModuleMapFile() { 2897 do { 2898 switch (Tok.Kind) { 2899 case MMToken::EndOfFile: 2900 return HadError; 2901 2902 case MMToken::ExplicitKeyword: 2903 case MMToken::ExternKeyword: 2904 case MMToken::ModuleKeyword: 2905 case MMToken::FrameworkKeyword: 2906 parseModuleDecl(); 2907 break; 2908 2909 case MMToken::Comma: 2910 case MMToken::ConfigMacros: 2911 case MMToken::Conflict: 2912 case MMToken::Exclaim: 2913 case MMToken::ExcludeKeyword: 2914 case MMToken::ExportKeyword: 2915 case MMToken::ExportAsKeyword: 2916 case MMToken::HeaderKeyword: 2917 case MMToken::Identifier: 2918 case MMToken::LBrace: 2919 case MMToken::LinkKeyword: 2920 case MMToken::LSquare: 2921 case MMToken::Period: 2922 case MMToken::PrivateKeyword: 2923 case MMToken::RBrace: 2924 case MMToken::RSquare: 2925 case MMToken::RequiresKeyword: 2926 case MMToken::Star: 2927 case MMToken::StringLiteral: 2928 case MMToken::IntegerLiteral: 2929 case MMToken::TextualKeyword: 2930 case MMToken::UmbrellaKeyword: 2931 case MMToken::UseKeyword: 2932 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module); 2933 HadError = true; 2934 consumeToken(); 2935 break; 2936 } 2937 } while (true); 2938 } 2939 2940 bool ModuleMap::parseModuleMapFile(const FileEntry *File, bool IsSystem, 2941 const DirectoryEntry *Dir, FileID ID, 2942 unsigned *Offset, 2943 SourceLocation ExternModuleLoc) { 2944 assert(Target && "Missing target information"); 2945 llvm::DenseMap<const FileEntry *, bool>::iterator Known 2946 = ParsedModuleMap.find(File); 2947 if (Known != ParsedModuleMap.end()) 2948 return Known->second; 2949 2950 // If the module map file wasn't already entered, do so now. 2951 if (ID.isInvalid()) { 2952 auto FileCharacter = 2953 IsSystem ? SrcMgr::C_System_ModuleMap : SrcMgr::C_User_ModuleMap; 2954 ID = SourceMgr.createFileID(File, ExternModuleLoc, FileCharacter); 2955 } 2956 2957 assert(Target && "Missing target information"); 2958 const llvm::MemoryBuffer *Buffer = SourceMgr.getBuffer(ID); 2959 if (!Buffer) 2960 return ParsedModuleMap[File] = true; 2961 assert((!Offset || *Offset <= Buffer->getBufferSize()) && 2962 "invalid buffer offset"); 2963 2964 // Parse this module map file. 2965 Lexer L(SourceMgr.getLocForStartOfFile(ID), MMapLangOpts, 2966 Buffer->getBufferStart(), 2967 Buffer->getBufferStart() + (Offset ? *Offset : 0), 2968 Buffer->getBufferEnd()); 2969 SourceLocation Start = L.getSourceLocation(); 2970 ModuleMapParser Parser(L, SourceMgr, Target, Diags, *this, File, Dir, 2971 IsSystem); 2972 bool Result = Parser.parseModuleMapFile(); 2973 ParsedModuleMap[File] = Result; 2974 2975 if (Offset) { 2976 auto Loc = SourceMgr.getDecomposedLoc(Parser.getLocation()); 2977 assert(Loc.first == ID && "stopped in a different file?"); 2978 *Offset = Loc.second; 2979 } 2980 2981 // Notify callbacks that we parsed it. 2982 for (const auto &Cb : Callbacks) 2983 Cb->moduleMapFileRead(Start, *File, IsSystem); 2984 2985 return Result; 2986 } 2987