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