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