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