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