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