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