1 //===--- ModuleMap.cpp - Describe the layout of modules ---------*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file defines the ModuleMap implementation, which describes the layout 11 // of a module as it relates to headers. 12 // 13 //===----------------------------------------------------------------------===// 14 #include "clang/Lex/ModuleMap.h" 15 #include "clang/Basic/CharInfo.h" 16 #include "clang/Basic/Diagnostic.h" 17 #include "clang/Basic/DiagnosticOptions.h" 18 #include "clang/Basic/FileManager.h" 19 #include "clang/Basic/TargetInfo.h" 20 #include "clang/Basic/TargetOptions.h" 21 #include "clang/Lex/HeaderSearch.h" 22 #include "clang/Lex/LexDiagnostic.h" 23 #include "clang/Lex/Lexer.h" 24 #include "clang/Lex/LiteralSupport.h" 25 #include "llvm/ADT/StringRef.h" 26 #include "llvm/ADT/StringSwitch.h" 27 #include "llvm/Support/Allocator.h" 28 #include "llvm/Support/FileSystem.h" 29 #include "llvm/Support/Host.h" 30 #include "llvm/Support/Path.h" 31 #include "llvm/Support/raw_ostream.h" 32 #include <stdlib.h> 33 #if defined(LLVM_ON_UNIX) 34 #include <limits.h> 35 #endif 36 using namespace clang; 37 38 Module::ExportDecl 39 ModuleMap::resolveExport(Module *Mod, 40 const Module::UnresolvedExportDecl &Unresolved, 41 bool Complain) const { 42 // We may have just a wildcard. 43 if (Unresolved.Id.empty()) { 44 assert(Unresolved.Wildcard && "Invalid unresolved export"); 45 return Module::ExportDecl(0, true); 46 } 47 48 // Resolve the module-id. 49 Module *Context = resolveModuleId(Unresolved.Id, Mod, Complain); 50 if (!Context) 51 return Module::ExportDecl(); 52 53 return Module::ExportDecl(Context, Unresolved.Wildcard); 54 } 55 56 Module *ModuleMap::resolveModuleId(const ModuleId &Id, Module *Mod, 57 bool Complain) const { 58 // Find the starting module. 59 Module *Context = lookupModuleUnqualified(Id[0].first, Mod); 60 if (!Context) { 61 if (Complain) 62 Diags.Report(Id[0].second, diag::err_mmap_missing_module_unqualified) 63 << Id[0].first << Mod->getFullModuleName(); 64 65 return 0; 66 } 67 68 // Dig into the module path. 69 for (unsigned I = 1, N = Id.size(); I != N; ++I) { 70 Module *Sub = lookupModuleQualified(Id[I].first, Context); 71 if (!Sub) { 72 if (Complain) 73 Diags.Report(Id[I].second, diag::err_mmap_missing_module_qualified) 74 << Id[I].first << Context->getFullModuleName() 75 << SourceRange(Id[0].second, Id[I-1].second); 76 77 return 0; 78 } 79 80 Context = Sub; 81 } 82 83 return Context; 84 } 85 86 ModuleMap::ModuleMap(SourceManager &SourceMgr, DiagnosticsEngine &Diags, 87 const LangOptions &LangOpts, const TargetInfo *Target, 88 HeaderSearch &HeaderInfo) 89 : SourceMgr(SourceMgr), Diags(Diags), LangOpts(LangOpts), Target(Target), 90 HeaderInfo(HeaderInfo), BuiltinIncludeDir(0), CompilingModule(0), 91 SourceModule(0) {} 92 93 ModuleMap::~ModuleMap() { 94 for (llvm::StringMap<Module *>::iterator I = Modules.begin(), 95 IEnd = Modules.end(); 96 I != IEnd; ++I) { 97 delete I->getValue(); 98 } 99 } 100 101 void ModuleMap::setTarget(const TargetInfo &Target) { 102 assert((!this->Target || this->Target == &Target) && 103 "Improper target override"); 104 this->Target = &Target; 105 } 106 107 /// \brief "Sanitize" a filename so that it can be used as an identifier. 108 static StringRef sanitizeFilenameAsIdentifier(StringRef Name, 109 SmallVectorImpl<char> &Buffer) { 110 if (Name.empty()) 111 return Name; 112 113 if (!isValidIdentifier(Name)) { 114 // If we don't already have something with the form of an identifier, 115 // create a buffer with the sanitized name. 116 Buffer.clear(); 117 if (isDigit(Name[0])) 118 Buffer.push_back('_'); 119 Buffer.reserve(Buffer.size() + Name.size()); 120 for (unsigned I = 0, N = Name.size(); I != N; ++I) { 121 if (isIdentifierBody(Name[I])) 122 Buffer.push_back(Name[I]); 123 else 124 Buffer.push_back('_'); 125 } 126 127 Name = StringRef(Buffer.data(), Buffer.size()); 128 } 129 130 while (llvm::StringSwitch<bool>(Name) 131 #define KEYWORD(Keyword,Conditions) .Case(#Keyword, true) 132 #define ALIAS(Keyword, AliasOf, Conditions) .Case(Keyword, true) 133 #include "clang/Basic/TokenKinds.def" 134 .Default(false)) { 135 if (Name.data() != Buffer.data()) 136 Buffer.append(Name.begin(), Name.end()); 137 Buffer.push_back('_'); 138 Name = StringRef(Buffer.data(), Buffer.size()); 139 } 140 141 return Name; 142 } 143 144 /// \brief Determine whether the given file name is the name of a builtin 145 /// header, supplied by Clang to replace, override, or augment existing system 146 /// headers. 147 static bool isBuiltinHeader(StringRef FileName) { 148 return llvm::StringSwitch<bool>(FileName) 149 .Case("float.h", true) 150 .Case("iso646.h", true) 151 .Case("limits.h", true) 152 .Case("stdalign.h", true) 153 .Case("stdarg.h", true) 154 .Case("stdbool.h", true) 155 .Case("stddef.h", true) 156 .Case("stdint.h", true) 157 .Case("tgmath.h", true) 158 .Case("unwind.h", true) 159 .Default(false); 160 } 161 162 ModuleMap::HeadersMap::iterator 163 ModuleMap::findKnownHeader(const FileEntry *File) { 164 HeadersMap::iterator Known = Headers.find(File); 165 if (Known == Headers.end() && File->getDir() == BuiltinIncludeDir && 166 isBuiltinHeader(llvm::sys::path::filename(File->getName()))) { 167 HeaderInfo.loadTopLevelSystemModules(); 168 return Headers.find(File); 169 } 170 return Known; 171 } 172 173 ModuleMap::KnownHeader 174 ModuleMap::findHeaderInUmbrellaDirs(const FileEntry *File, 175 SmallVectorImpl<const DirectoryEntry *> &IntermediateDirs) { 176 const DirectoryEntry *Dir = File->getDir(); 177 assert(Dir && "file in no directory"); 178 179 // Note: as an egregious but useful hack we use the real path here, because 180 // frameworks moving from top-level frameworks to embedded frameworks tend 181 // to be symlinked from the top-level location to the embedded location, 182 // and we need to resolve lookups as if we had found the embedded location. 183 StringRef DirName = SourceMgr.getFileManager().getCanonicalName(Dir); 184 185 // Keep walking up the directory hierarchy, looking for a directory with 186 // an umbrella header. 187 do { 188 auto KnownDir = UmbrellaDirs.find(Dir); 189 if (KnownDir != UmbrellaDirs.end()) 190 return KnownHeader(KnownDir->second, NormalHeader); 191 192 IntermediateDirs.push_back(Dir); 193 194 // Retrieve our parent path. 195 DirName = llvm::sys::path::parent_path(DirName); 196 if (DirName.empty()) 197 break; 198 199 // Resolve the parent path to a directory entry. 200 Dir = SourceMgr.getFileManager().getDirectory(DirName); 201 } while (Dir); 202 return KnownHeader(); 203 } 204 205 // Returns 'true' if 'RequestingModule directly uses 'RequestedModule'. 206 static bool directlyUses(const Module *RequestingModule, 207 const Module *RequestedModule) { 208 return std::find(RequestingModule->DirectUses.begin(), 209 RequestingModule->DirectUses.end(), 210 RequestedModule) != RequestingModule->DirectUses.end(); 211 } 212 213 static bool violatesPrivateInclude(Module *RequestingModule, 214 const FileEntry *IncFileEnt, 215 ModuleMap::ModuleHeaderRole Role, 216 Module *RequestedModule) { 217 #ifndef NDEBUG 218 // Check for consistency between the module header role 219 // as obtained from the lookup and as obtained from the module. 220 // This check is not cheap, so enable it only for debugging. 221 SmallVectorImpl<const FileEntry *> &PvtHdrs 222 = RequestedModule->PrivateHeaders; 223 SmallVectorImpl<const FileEntry *>::iterator Look 224 = std::find(PvtHdrs.begin(), PvtHdrs.end(), IncFileEnt); 225 bool IsPrivate = Look != PvtHdrs.end(); 226 assert((IsPrivate && Role == ModuleMap::PrivateHeader) 227 || (!IsPrivate && Role != ModuleMap::PrivateHeader)); 228 #endif 229 return Role == ModuleMap::PrivateHeader && 230 RequestedModule->getTopLevelModule() != RequestingModule; 231 } 232 233 void ModuleMap::diagnoseHeaderInclusion(Module *RequestingModule, 234 SourceLocation FilenameLoc, 235 StringRef Filename, 236 const FileEntry *File) { 237 // No errors for indirect modules. This may be a bit of a problem for modules 238 // with no source files. 239 if (RequestingModule != SourceModule) 240 return; 241 242 if (RequestingModule) 243 resolveUses(RequestingModule, /*Complain=*/false); 244 245 HeadersMap::iterator Known = findKnownHeader(File); 246 if (Known == Headers.end()) { 247 if (LangOpts.ModulesStrictDeclUse) 248 Diags.Report(FilenameLoc, diag::error_undeclared_use_of_module) 249 << RequestingModule->getFullModuleName() << Filename; 250 return; 251 } 252 253 Module *Private = NULL; 254 Module *NotUsed = NULL; 255 for (SmallVectorImpl<KnownHeader>::iterator I = Known->second.begin(), 256 E = Known->second.end(); 257 I != E; ++I) { 258 // Excluded headers don't really belong to a module. 259 if (I->getRole() == ModuleMap::ExcludedHeader) 260 continue; 261 262 // If 'File' is part of 'RequestingModule' we can definitely include it. 263 if (I->getModule() == RequestingModule) 264 return; 265 266 // Remember private headers for later printing of a diagnostic. 267 if (violatesPrivateInclude(RequestingModule, File, I->getRole(), 268 I->getModule())) { 269 Private = I->getModule(); 270 continue; 271 } 272 273 // If uses need to be specified explicitly, we are only allowed to return 274 // modules that are explicitly used by the requesting module. 275 if (RequestingModule && LangOpts.ModulesDeclUse && 276 !directlyUses(RequestingModule, I->getModule())) { 277 NotUsed = I->getModule(); 278 continue; 279 } 280 281 // We have found a module that we can happily use. 282 return; 283 } 284 285 // We have found a header, but it is private. 286 if (Private != NULL) { 287 Diags.Report(FilenameLoc, diag::error_use_of_private_header_outside_module) 288 << Filename; 289 return; 290 } 291 292 // We have found a module, but we don't use it. 293 if (NotUsed != NULL) { 294 Diags.Report(FilenameLoc, diag::error_undeclared_use_of_module) 295 << RequestingModule->getFullModuleName() << Filename; 296 return; 297 } 298 299 // Headers for which we have not found a module are fine to include. 300 } 301 302 ModuleMap::KnownHeader 303 ModuleMap::findModuleForHeader(const FileEntry *File, 304 Module *RequestingModule) { 305 HeadersMap::iterator Known = findKnownHeader(File); 306 307 if (Known != Headers.end()) { 308 ModuleMap::KnownHeader Result = KnownHeader(); 309 310 // Iterate over all modules that 'File' is part of to find the best fit. 311 for (SmallVectorImpl<KnownHeader>::iterator I = Known->second.begin(), 312 E = Known->second.end(); 313 I != E; ++I) { 314 // Cannot use a module if the header is excluded in it. 315 if (I->getRole() == ModuleMap::ExcludedHeader) 316 continue; 317 318 // Cannot use a module if it is unavailable. 319 if (!I->getModule()->isAvailable()) 320 continue; 321 322 // If 'File' is part of 'RequestingModule', 'RequestingModule' is the 323 // module we are looking for. 324 if (I->getModule() == RequestingModule) 325 return *I; 326 327 // If uses need to be specified explicitly, we are only allowed to return 328 // modules that are explicitly used by the requesting module. 329 if (RequestingModule && LangOpts.ModulesDeclUse && 330 !directlyUses(RequestingModule, I->getModule())) 331 continue; 332 333 Result = *I; 334 // If 'File' is a public header of this module, this is as good as we 335 // are going to get. 336 // FIXME: If we have a RequestingModule, we should prefer the header from 337 // that module. 338 if (I->getRole() == ModuleMap::NormalHeader) 339 break; 340 } 341 return Result; 342 } 343 344 SmallVector<const DirectoryEntry *, 2> SkippedDirs; 345 KnownHeader H = findHeaderInUmbrellaDirs(File, SkippedDirs); 346 if (H) { 347 Module *Result = H.getModule(); 348 349 // Search up the module stack until we find a module with an umbrella 350 // directory. 351 Module *UmbrellaModule = Result; 352 while (!UmbrellaModule->getUmbrellaDir() && UmbrellaModule->Parent) 353 UmbrellaModule = UmbrellaModule->Parent; 354 355 if (UmbrellaModule->InferSubmodules) { 356 // Infer submodules for each of the directories we found between 357 // the directory of the umbrella header and the directory where 358 // the actual header is located. 359 bool Explicit = UmbrellaModule->InferExplicitSubmodules; 360 361 for (unsigned I = SkippedDirs.size(); I != 0; --I) { 362 // Find or create the module that corresponds to this directory name. 363 SmallString<32> NameBuf; 364 StringRef Name = sanitizeFilenameAsIdentifier( 365 llvm::sys::path::stem(SkippedDirs[I-1]->getName()), NameBuf); 366 Result = findOrCreateModule(Name, Result, UmbrellaModule->ModuleMap, 367 /*IsFramework=*/false, Explicit).first; 368 369 // Associate the module and the directory. 370 UmbrellaDirs[SkippedDirs[I-1]] = Result; 371 372 // If inferred submodules export everything they import, add a 373 // wildcard to the set of exports. 374 if (UmbrellaModule->InferExportWildcard && Result->Exports.empty()) 375 Result->Exports.push_back(Module::ExportDecl(0, true)); 376 } 377 378 // Infer a submodule with the same name as this header file. 379 SmallString<32> NameBuf; 380 StringRef Name = sanitizeFilenameAsIdentifier( 381 llvm::sys::path::stem(File->getName()), NameBuf); 382 Result = findOrCreateModule(Name, Result, UmbrellaModule->ModuleMap, 383 /*IsFramework=*/false, Explicit).first; 384 Result->addTopHeader(File); 385 386 // If inferred submodules export everything they import, add a 387 // wildcard to the set of exports. 388 if (UmbrellaModule->InferExportWildcard && Result->Exports.empty()) 389 Result->Exports.push_back(Module::ExportDecl(0, true)); 390 } else { 391 // Record each of the directories we stepped through as being part of 392 // the module we found, since the umbrella header covers them all. 393 for (unsigned I = 0, N = SkippedDirs.size(); I != N; ++I) 394 UmbrellaDirs[SkippedDirs[I]] = Result; 395 } 396 397 Headers[File].push_back(KnownHeader(Result, NormalHeader)); 398 399 // If a header corresponds to an unavailable module, don't report 400 // that it maps to anything. 401 if (!Result->isAvailable()) 402 return KnownHeader(); 403 404 return Headers[File].back(); 405 } 406 407 return KnownHeader(); 408 } 409 410 bool ModuleMap::isHeaderInUnavailableModule(const FileEntry *Header) const { 411 return isHeaderUnavailableInModule(Header, 0); 412 } 413 414 bool 415 ModuleMap::isHeaderUnavailableInModule(const FileEntry *Header, 416 const Module *RequestingModule) const { 417 HeadersMap::const_iterator Known = Headers.find(Header); 418 if (Known != Headers.end()) { 419 for (SmallVectorImpl<KnownHeader>::const_iterator 420 I = Known->second.begin(), 421 E = Known->second.end(); 422 I != E; ++I) { 423 if (I->isAvailable() && (!RequestingModule || 424 I->getModule()->isSubModuleOf(RequestingModule))) 425 return false; 426 } 427 return true; 428 } 429 430 const DirectoryEntry *Dir = Header->getDir(); 431 SmallVector<const DirectoryEntry *, 2> SkippedDirs; 432 StringRef DirName = Dir->getName(); 433 434 auto IsUnavailable = [&](const Module *M) { 435 return !M->isAvailable() && (!RequestingModule || 436 M->isSubModuleOf(RequestingModule)); 437 }; 438 439 // Keep walking up the directory hierarchy, looking for a directory with 440 // an umbrella header. 441 do { 442 llvm::DenseMap<const DirectoryEntry *, Module *>::const_iterator KnownDir 443 = UmbrellaDirs.find(Dir); 444 if (KnownDir != UmbrellaDirs.end()) { 445 Module *Found = KnownDir->second; 446 if (IsUnavailable(Found)) 447 return true; 448 449 // Search up the module stack until we find a module with an umbrella 450 // directory. 451 Module *UmbrellaModule = Found; 452 while (!UmbrellaModule->getUmbrellaDir() && UmbrellaModule->Parent) 453 UmbrellaModule = UmbrellaModule->Parent; 454 455 if (UmbrellaModule->InferSubmodules) { 456 for (unsigned I = SkippedDirs.size(); I != 0; --I) { 457 // Find or create the module that corresponds to this directory name. 458 SmallString<32> NameBuf; 459 StringRef Name = sanitizeFilenameAsIdentifier( 460 llvm::sys::path::stem(SkippedDirs[I-1]->getName()), 461 NameBuf); 462 Found = lookupModuleQualified(Name, Found); 463 if (!Found) 464 return false; 465 if (IsUnavailable(Found)) 466 return true; 467 } 468 469 // Infer a submodule with the same name as this header file. 470 SmallString<32> NameBuf; 471 StringRef Name = sanitizeFilenameAsIdentifier( 472 llvm::sys::path::stem(Header->getName()), 473 NameBuf); 474 Found = lookupModuleQualified(Name, Found); 475 if (!Found) 476 return false; 477 } 478 479 return IsUnavailable(Found); 480 } 481 482 SkippedDirs.push_back(Dir); 483 484 // Retrieve our parent path. 485 DirName = llvm::sys::path::parent_path(DirName); 486 if (DirName.empty()) 487 break; 488 489 // Resolve the parent path to a directory entry. 490 Dir = SourceMgr.getFileManager().getDirectory(DirName); 491 } while (Dir); 492 493 return false; 494 } 495 496 Module *ModuleMap::findModule(StringRef Name) const { 497 llvm::StringMap<Module *>::const_iterator Known = Modules.find(Name); 498 if (Known != Modules.end()) 499 return Known->getValue(); 500 501 return 0; 502 } 503 504 Module *ModuleMap::lookupModuleUnqualified(StringRef Name, 505 Module *Context) const { 506 for(; Context; Context = Context->Parent) { 507 if (Module *Sub = lookupModuleQualified(Name, Context)) 508 return Sub; 509 } 510 511 return findModule(Name); 512 } 513 514 Module *ModuleMap::lookupModuleQualified(StringRef Name, Module *Context) const{ 515 if (!Context) 516 return findModule(Name); 517 518 return Context->findSubmodule(Name); 519 } 520 521 std::pair<Module *, bool> 522 ModuleMap::findOrCreateModule(StringRef Name, Module *Parent, 523 const FileEntry *ModuleMap, bool IsFramework, 524 bool IsExplicit) { 525 // Try to find an existing module with this name. 526 if (Module *Sub = lookupModuleQualified(Name, Parent)) 527 return std::make_pair(Sub, false); 528 529 // Create a new module with this name. 530 Module *Result = new Module(Name, SourceLocation(), Parent, ModuleMap, 531 IsFramework, IsExplicit); 532 if (LangOpts.CurrentModule == Name) { 533 SourceModule = Result; 534 SourceModuleName = Name; 535 } 536 if (!Parent) { 537 Modules[Name] = Result; 538 if (!LangOpts.CurrentModule.empty() && !CompilingModule && 539 Name == LangOpts.CurrentModule) { 540 CompilingModule = Result; 541 } 542 } 543 return std::make_pair(Result, true); 544 } 545 546 bool ModuleMap::canInferFrameworkModule(const DirectoryEntry *ParentDir, 547 StringRef Name, bool &IsSystem) const { 548 // Check whether we have already looked into the parent directory 549 // for a module map. 550 llvm::DenseMap<const DirectoryEntry *, InferredDirectory>::const_iterator 551 inferred = InferredDirectories.find(ParentDir); 552 if (inferred == InferredDirectories.end()) 553 return false; 554 555 if (!inferred->second.InferModules) 556 return false; 557 558 // We're allowed to infer for this directory, but make sure it's okay 559 // to infer this particular module. 560 bool canInfer = std::find(inferred->second.ExcludedModules.begin(), 561 inferred->second.ExcludedModules.end(), 562 Name) == inferred->second.ExcludedModules.end(); 563 564 if (canInfer && inferred->second.InferSystemModules) 565 IsSystem = true; 566 567 return canInfer; 568 } 569 570 /// \brief For a framework module, infer the framework against which we 571 /// should link. 572 static void inferFrameworkLink(Module *Mod, const DirectoryEntry *FrameworkDir, 573 FileManager &FileMgr) { 574 assert(Mod->IsFramework && "Can only infer linking for framework modules"); 575 assert(!Mod->isSubFramework() && 576 "Can only infer linking for top-level frameworks"); 577 578 SmallString<128> LibName; 579 LibName += FrameworkDir->getName(); 580 llvm::sys::path::append(LibName, Mod->Name); 581 if (FileMgr.getFile(LibName)) { 582 Mod->LinkLibraries.push_back(Module::LinkLibrary(Mod->Name, 583 /*IsFramework=*/true)); 584 } 585 } 586 587 Module * 588 ModuleMap::inferFrameworkModule(StringRef ModuleName, 589 const DirectoryEntry *FrameworkDir, 590 bool IsSystem, 591 Module *Parent) { 592 // Check whether we've already found this module. 593 if (Module *Mod = lookupModuleQualified(ModuleName, Parent)) 594 return Mod; 595 596 FileManager &FileMgr = SourceMgr.getFileManager(); 597 598 // If the framework has a parent path from which we're allowed to infer 599 // a framework module, do so. 600 const FileEntry *ModuleMapFile = nullptr; 601 if (!Parent) { 602 // Determine whether we're allowed to infer a module map. 603 604 // Note: as an egregious but useful hack we use the real path here, because 605 // we might be looking at an embedded framework that symlinks out to a 606 // top-level framework, and we need to infer as if we were naming the 607 // top-level framework. 608 StringRef FrameworkDirName 609 = SourceMgr.getFileManager().getCanonicalName(FrameworkDir); 610 611 bool canInfer = false; 612 if (llvm::sys::path::has_parent_path(FrameworkDirName)) { 613 // Figure out the parent path. 614 StringRef Parent = llvm::sys::path::parent_path(FrameworkDirName); 615 if (const DirectoryEntry *ParentDir = FileMgr.getDirectory(Parent)) { 616 // Check whether we have already looked into the parent directory 617 // for a module map. 618 llvm::DenseMap<const DirectoryEntry *, InferredDirectory>::const_iterator 619 inferred = InferredDirectories.find(ParentDir); 620 if (inferred == InferredDirectories.end()) { 621 // We haven't looked here before. Load a module map, if there is 622 // one. 623 bool IsFrameworkDir = Parent.endswith(".framework"); 624 if (const FileEntry *ModMapFile = 625 HeaderInfo.lookupModuleMapFile(ParentDir, IsFrameworkDir)) { 626 parseModuleMapFile(ModMapFile, IsSystem); 627 inferred = InferredDirectories.find(ParentDir); 628 } 629 630 if (inferred == InferredDirectories.end()) 631 inferred = InferredDirectories.insert( 632 std::make_pair(ParentDir, InferredDirectory())).first; 633 } 634 635 if (inferred->second.InferModules) { 636 // We're allowed to infer for this directory, but make sure it's okay 637 // to infer this particular module. 638 StringRef Name = llvm::sys::path::stem(FrameworkDirName); 639 canInfer = std::find(inferred->second.ExcludedModules.begin(), 640 inferred->second.ExcludedModules.end(), 641 Name) == inferred->second.ExcludedModules.end(); 642 643 if (inferred->second.InferSystemModules) 644 IsSystem = true; 645 ModuleMapFile = inferred->second.ModuleMapFile; 646 } 647 } 648 } 649 650 // If we're not allowed to infer a framework module, don't. 651 if (!canInfer) 652 return 0; 653 } else 654 ModuleMapFile = Parent->ModuleMap; 655 656 657 // Look for an umbrella header. 658 SmallString<128> UmbrellaName = StringRef(FrameworkDir->getName()); 659 llvm::sys::path::append(UmbrellaName, "Headers", ModuleName + ".h"); 660 const FileEntry *UmbrellaHeader = FileMgr.getFile(UmbrellaName); 661 662 // FIXME: If there's no umbrella header, we could probably scan the 663 // framework to load *everything*. But, it's not clear that this is a good 664 // idea. 665 if (!UmbrellaHeader) 666 return 0; 667 668 Module *Result = new Module(ModuleName, SourceLocation(), Parent, ModuleMapFile, 669 /*IsFramework=*/true, /*IsExplicit=*/false); 670 if (LangOpts.CurrentModule == ModuleName) { 671 SourceModule = Result; 672 SourceModuleName = ModuleName; 673 } 674 if (IsSystem) 675 Result->IsSystem = IsSystem; 676 677 if (!Parent) 678 Modules[ModuleName] = Result; 679 680 // umbrella header "umbrella-header-name" 681 Result->Umbrella = UmbrellaHeader; 682 Headers[UmbrellaHeader].push_back(KnownHeader(Result, NormalHeader)); 683 UmbrellaDirs[UmbrellaHeader->getDir()] = Result; 684 685 // export * 686 Result->Exports.push_back(Module::ExportDecl(0, true)); 687 688 // module * { export * } 689 Result->InferSubmodules = true; 690 Result->InferExportWildcard = true; 691 692 // Look for subframeworks. 693 llvm::error_code EC; 694 SmallString<128> SubframeworksDirName 695 = StringRef(FrameworkDir->getName()); 696 llvm::sys::path::append(SubframeworksDirName, "Frameworks"); 697 llvm::sys::path::native(SubframeworksDirName); 698 for (llvm::sys::fs::directory_iterator 699 Dir(SubframeworksDirName.str(), EC), DirEnd; 700 Dir != DirEnd && !EC; Dir.increment(EC)) { 701 if (!StringRef(Dir->path()).endswith(".framework")) 702 continue; 703 704 if (const DirectoryEntry *SubframeworkDir 705 = FileMgr.getDirectory(Dir->path())) { 706 // Note: as an egregious but useful hack, we use the real path here and 707 // check whether it is actually a subdirectory of the parent directory. 708 // This will not be the case if the 'subframework' is actually a symlink 709 // out to a top-level framework. 710 StringRef SubframeworkDirName = FileMgr.getCanonicalName(SubframeworkDir); 711 bool FoundParent = false; 712 do { 713 // Get the parent directory name. 714 SubframeworkDirName 715 = llvm::sys::path::parent_path(SubframeworkDirName); 716 if (SubframeworkDirName.empty()) 717 break; 718 719 if (FileMgr.getDirectory(SubframeworkDirName) == FrameworkDir) { 720 FoundParent = true; 721 break; 722 } 723 } while (true); 724 725 if (!FoundParent) 726 continue; 727 728 // FIXME: Do we want to warn about subframeworks without umbrella headers? 729 SmallString<32> NameBuf; 730 inferFrameworkModule(sanitizeFilenameAsIdentifier( 731 llvm::sys::path::stem(Dir->path()), NameBuf), 732 SubframeworkDir, IsSystem, Result); 733 } 734 } 735 736 // If the module is a top-level framework, automatically link against the 737 // framework. 738 if (!Result->isSubFramework()) { 739 inferFrameworkLink(Result, FrameworkDir, FileMgr); 740 } 741 742 return Result; 743 } 744 745 void ModuleMap::setUmbrellaHeader(Module *Mod, const FileEntry *UmbrellaHeader){ 746 Headers[UmbrellaHeader].push_back(KnownHeader(Mod, NormalHeader)); 747 Mod->Umbrella = UmbrellaHeader; 748 UmbrellaDirs[UmbrellaHeader->getDir()] = Mod; 749 } 750 751 void ModuleMap::setUmbrellaDir(Module *Mod, const DirectoryEntry *UmbrellaDir) { 752 Mod->Umbrella = UmbrellaDir; 753 UmbrellaDirs[UmbrellaDir] = Mod; 754 } 755 756 void ModuleMap::addHeader(Module *Mod, const FileEntry *Header, 757 ModuleHeaderRole Role) { 758 if (Role == ExcludedHeader) { 759 Mod->ExcludedHeaders.push_back(Header); 760 } else { 761 if (Role == PrivateHeader) 762 Mod->PrivateHeaders.push_back(Header); 763 else 764 Mod->NormalHeaders.push_back(Header); 765 bool isCompilingModuleHeader = Mod->getTopLevelModule() == CompilingModule; 766 HeaderInfo.MarkFileModuleHeader(Header, Role, isCompilingModuleHeader); 767 } 768 Headers[Header].push_back(KnownHeader(Mod, Role)); 769 } 770 771 const FileEntry * 772 ModuleMap::getContainingModuleMapFile(Module *Module) const { 773 if (Module->DefinitionLoc.isInvalid()) 774 return 0; 775 776 return SourceMgr.getFileEntryForID( 777 SourceMgr.getFileID(Module->DefinitionLoc)); 778 } 779 780 void ModuleMap::dump() { 781 llvm::errs() << "Modules:"; 782 for (llvm::StringMap<Module *>::iterator M = Modules.begin(), 783 MEnd = Modules.end(); 784 M != MEnd; ++M) 785 M->getValue()->print(llvm::errs(), 2); 786 787 llvm::errs() << "Headers:"; 788 for (HeadersMap::iterator H = Headers.begin(), HEnd = Headers.end(); 789 H != HEnd; ++H) { 790 llvm::errs() << " \"" << H->first->getName() << "\" -> "; 791 for (SmallVectorImpl<KnownHeader>::const_iterator I = H->second.begin(), 792 E = H->second.end(); 793 I != E; ++I) { 794 if (I != H->second.begin()) 795 llvm::errs() << ","; 796 llvm::errs() << I->getModule()->getFullModuleName(); 797 } 798 llvm::errs() << "\n"; 799 } 800 } 801 802 bool ModuleMap::resolveExports(Module *Mod, bool Complain) { 803 bool HadError = false; 804 for (unsigned I = 0, N = Mod->UnresolvedExports.size(); I != N; ++I) { 805 Module::ExportDecl Export = resolveExport(Mod, Mod->UnresolvedExports[I], 806 Complain); 807 if (Export.getPointer() || Export.getInt()) 808 Mod->Exports.push_back(Export); 809 else 810 HadError = true; 811 } 812 Mod->UnresolvedExports.clear(); 813 return HadError; 814 } 815 816 bool ModuleMap::resolveUses(Module *Mod, bool Complain) { 817 bool HadError = false; 818 for (unsigned I = 0, N = Mod->UnresolvedDirectUses.size(); I != N; ++I) { 819 Module *DirectUse = 820 resolveModuleId(Mod->UnresolvedDirectUses[I], Mod, Complain); 821 if (DirectUse) 822 Mod->DirectUses.push_back(DirectUse); 823 else 824 HadError = true; 825 } 826 Mod->UnresolvedDirectUses.clear(); 827 return HadError; 828 } 829 830 bool ModuleMap::resolveConflicts(Module *Mod, bool Complain) { 831 bool HadError = false; 832 for (unsigned I = 0, N = Mod->UnresolvedConflicts.size(); I != N; ++I) { 833 Module *OtherMod = resolveModuleId(Mod->UnresolvedConflicts[I].Id, 834 Mod, Complain); 835 if (!OtherMod) { 836 HadError = true; 837 continue; 838 } 839 840 Module::Conflict Conflict; 841 Conflict.Other = OtherMod; 842 Conflict.Message = Mod->UnresolvedConflicts[I].Message; 843 Mod->Conflicts.push_back(Conflict); 844 } 845 Mod->UnresolvedConflicts.clear(); 846 return HadError; 847 } 848 849 Module *ModuleMap::inferModuleFromLocation(FullSourceLoc Loc) { 850 if (Loc.isInvalid()) 851 return 0; 852 853 // Use the expansion location to determine which module we're in. 854 FullSourceLoc ExpansionLoc = Loc.getExpansionLoc(); 855 if (!ExpansionLoc.isFileID()) 856 return 0; 857 858 859 const SourceManager &SrcMgr = Loc.getManager(); 860 FileID ExpansionFileID = ExpansionLoc.getFileID(); 861 862 while (const FileEntry *ExpansionFile 863 = SrcMgr.getFileEntryForID(ExpansionFileID)) { 864 // Find the module that owns this header (if any). 865 if (Module *Mod = findModuleForHeader(ExpansionFile).getModule()) 866 return Mod; 867 868 // No module owns this header, so look up the inclusion chain to see if 869 // any included header has an associated module. 870 SourceLocation IncludeLoc = SrcMgr.getIncludeLoc(ExpansionFileID); 871 if (IncludeLoc.isInvalid()) 872 return 0; 873 874 ExpansionFileID = SrcMgr.getFileID(IncludeLoc); 875 } 876 877 return 0; 878 } 879 880 //----------------------------------------------------------------------------// 881 // Module map file parser 882 //----------------------------------------------------------------------------// 883 884 namespace clang { 885 /// \brief A token in a module map file. 886 struct MMToken { 887 enum TokenKind { 888 Comma, 889 ConfigMacros, 890 Conflict, 891 EndOfFile, 892 HeaderKeyword, 893 Identifier, 894 Exclaim, 895 ExcludeKeyword, 896 ExplicitKeyword, 897 ExportKeyword, 898 ExternKeyword, 899 FrameworkKeyword, 900 LinkKeyword, 901 ModuleKeyword, 902 Period, 903 PrivateKeyword, 904 UmbrellaKeyword, 905 UseKeyword, 906 RequiresKeyword, 907 Star, 908 StringLiteral, 909 LBrace, 910 RBrace, 911 LSquare, 912 RSquare 913 } Kind; 914 915 unsigned Location; 916 unsigned StringLength; 917 const char *StringData; 918 919 void clear() { 920 Kind = EndOfFile; 921 Location = 0; 922 StringLength = 0; 923 StringData = 0; 924 } 925 926 bool is(TokenKind K) const { return Kind == K; } 927 928 SourceLocation getLocation() const { 929 return SourceLocation::getFromRawEncoding(Location); 930 } 931 932 StringRef getString() const { 933 return StringRef(StringData, StringLength); 934 } 935 }; 936 937 /// \brief The set of attributes that can be attached to a module. 938 struct Attributes { 939 Attributes() : IsSystem(), IsExternC(), IsExhaustive() { } 940 941 /// \brief Whether this is a system module. 942 unsigned IsSystem : 1; 943 944 /// \brief Whether this is an extern "C" module. 945 unsigned IsExternC : 1; 946 947 /// \brief Whether this is an exhaustive set of configuration macros. 948 unsigned IsExhaustive : 1; 949 }; 950 951 952 class ModuleMapParser { 953 Lexer &L; 954 SourceManager &SourceMgr; 955 956 /// \brief Default target information, used only for string literal 957 /// parsing. 958 const TargetInfo *Target; 959 960 DiagnosticsEngine &Diags; 961 ModuleMap ⤅ 962 963 /// \brief The current module map file. 964 const FileEntry *ModuleMapFile; 965 966 /// \brief The directory that this module map resides in. 967 const DirectoryEntry *Directory; 968 969 /// \brief The directory containing Clang-supplied headers. 970 const DirectoryEntry *BuiltinIncludeDir; 971 972 /// \brief Whether this module map is in a system header directory. 973 bool IsSystem; 974 975 /// \brief Whether an error occurred. 976 bool HadError; 977 978 /// \brief Stores string data for the various string literals referenced 979 /// during parsing. 980 llvm::BumpPtrAllocator StringData; 981 982 /// \brief The current token. 983 MMToken Tok; 984 985 /// \brief The active module. 986 Module *ActiveModule; 987 988 /// \brief Consume the current token and return its location. 989 SourceLocation consumeToken(); 990 991 /// \brief Skip tokens until we reach the a token with the given kind 992 /// (or the end of the file). 993 void skipUntil(MMToken::TokenKind K); 994 995 typedef SmallVector<std::pair<std::string, SourceLocation>, 2> ModuleId; 996 bool parseModuleId(ModuleId &Id); 997 void parseModuleDecl(); 998 void parseExternModuleDecl(); 999 void parseRequiresDecl(); 1000 void parseHeaderDecl(clang::MMToken::TokenKind, 1001 SourceLocation LeadingLoc); 1002 void parseUmbrellaDirDecl(SourceLocation UmbrellaLoc); 1003 void parseExportDecl(); 1004 void parseUseDecl(); 1005 void parseLinkDecl(); 1006 void parseConfigMacros(); 1007 void parseConflict(); 1008 void parseInferredModuleDecl(bool Framework, bool Explicit); 1009 bool parseOptionalAttributes(Attributes &Attrs); 1010 1011 public: 1012 explicit ModuleMapParser(Lexer &L, SourceManager &SourceMgr, 1013 const TargetInfo *Target, 1014 DiagnosticsEngine &Diags, 1015 ModuleMap &Map, 1016 const FileEntry *ModuleMapFile, 1017 const DirectoryEntry *Directory, 1018 const DirectoryEntry *BuiltinIncludeDir, 1019 bool IsSystem) 1020 : L(L), SourceMgr(SourceMgr), Target(Target), Diags(Diags), Map(Map), 1021 ModuleMapFile(ModuleMapFile), Directory(Directory), 1022 BuiltinIncludeDir(BuiltinIncludeDir), IsSystem(IsSystem), 1023 HadError(false), ActiveModule(0) 1024 { 1025 Tok.clear(); 1026 consumeToken(); 1027 } 1028 1029 bool parseModuleMapFile(); 1030 }; 1031 } 1032 1033 SourceLocation ModuleMapParser::consumeToken() { 1034 retry: 1035 SourceLocation Result = Tok.getLocation(); 1036 Tok.clear(); 1037 1038 Token LToken; 1039 L.LexFromRawLexer(LToken); 1040 Tok.Location = LToken.getLocation().getRawEncoding(); 1041 switch (LToken.getKind()) { 1042 case tok::raw_identifier: 1043 Tok.StringData = LToken.getRawIdentifierData(); 1044 Tok.StringLength = LToken.getLength(); 1045 Tok.Kind = llvm::StringSwitch<MMToken::TokenKind>(Tok.getString()) 1046 .Case("config_macros", MMToken::ConfigMacros) 1047 .Case("conflict", MMToken::Conflict) 1048 .Case("exclude", MMToken::ExcludeKeyword) 1049 .Case("explicit", MMToken::ExplicitKeyword) 1050 .Case("export", MMToken::ExportKeyword) 1051 .Case("extern", MMToken::ExternKeyword) 1052 .Case("framework", MMToken::FrameworkKeyword) 1053 .Case("header", MMToken::HeaderKeyword) 1054 .Case("link", MMToken::LinkKeyword) 1055 .Case("module", MMToken::ModuleKeyword) 1056 .Case("private", MMToken::PrivateKeyword) 1057 .Case("requires", MMToken::RequiresKeyword) 1058 .Case("umbrella", MMToken::UmbrellaKeyword) 1059 .Case("use", MMToken::UseKeyword) 1060 .Default(MMToken::Identifier); 1061 break; 1062 1063 case tok::comma: 1064 Tok.Kind = MMToken::Comma; 1065 break; 1066 1067 case tok::eof: 1068 Tok.Kind = MMToken::EndOfFile; 1069 break; 1070 1071 case tok::l_brace: 1072 Tok.Kind = MMToken::LBrace; 1073 break; 1074 1075 case tok::l_square: 1076 Tok.Kind = MMToken::LSquare; 1077 break; 1078 1079 case tok::period: 1080 Tok.Kind = MMToken::Period; 1081 break; 1082 1083 case tok::r_brace: 1084 Tok.Kind = MMToken::RBrace; 1085 break; 1086 1087 case tok::r_square: 1088 Tok.Kind = MMToken::RSquare; 1089 break; 1090 1091 case tok::star: 1092 Tok.Kind = MMToken::Star; 1093 break; 1094 1095 case tok::exclaim: 1096 Tok.Kind = MMToken::Exclaim; 1097 break; 1098 1099 case tok::string_literal: { 1100 if (LToken.hasUDSuffix()) { 1101 Diags.Report(LToken.getLocation(), diag::err_invalid_string_udl); 1102 HadError = true; 1103 goto retry; 1104 } 1105 1106 // Parse the string literal. 1107 LangOptions LangOpts; 1108 StringLiteralParser StringLiteral(<oken, 1, SourceMgr, LangOpts, *Target); 1109 if (StringLiteral.hadError) 1110 goto retry; 1111 1112 // Copy the string literal into our string data allocator. 1113 unsigned Length = StringLiteral.GetStringLength(); 1114 char *Saved = StringData.Allocate<char>(Length + 1); 1115 memcpy(Saved, StringLiteral.GetString().data(), Length); 1116 Saved[Length] = 0; 1117 1118 // Form the token. 1119 Tok.Kind = MMToken::StringLiteral; 1120 Tok.StringData = Saved; 1121 Tok.StringLength = Length; 1122 break; 1123 } 1124 1125 case tok::comment: 1126 goto retry; 1127 1128 default: 1129 Diags.Report(LToken.getLocation(), diag::err_mmap_unknown_token); 1130 HadError = true; 1131 goto retry; 1132 } 1133 1134 return Result; 1135 } 1136 1137 void ModuleMapParser::skipUntil(MMToken::TokenKind K) { 1138 unsigned braceDepth = 0; 1139 unsigned squareDepth = 0; 1140 do { 1141 switch (Tok.Kind) { 1142 case MMToken::EndOfFile: 1143 return; 1144 1145 case MMToken::LBrace: 1146 if (Tok.is(K) && braceDepth == 0 && squareDepth == 0) 1147 return; 1148 1149 ++braceDepth; 1150 break; 1151 1152 case MMToken::LSquare: 1153 if (Tok.is(K) && braceDepth == 0 && squareDepth == 0) 1154 return; 1155 1156 ++squareDepth; 1157 break; 1158 1159 case MMToken::RBrace: 1160 if (braceDepth > 0) 1161 --braceDepth; 1162 else if (Tok.is(K)) 1163 return; 1164 break; 1165 1166 case MMToken::RSquare: 1167 if (squareDepth > 0) 1168 --squareDepth; 1169 else if (Tok.is(K)) 1170 return; 1171 break; 1172 1173 default: 1174 if (braceDepth == 0 && squareDepth == 0 && Tok.is(K)) 1175 return; 1176 break; 1177 } 1178 1179 consumeToken(); 1180 } while (true); 1181 } 1182 1183 /// \brief Parse a module-id. 1184 /// 1185 /// module-id: 1186 /// identifier 1187 /// identifier '.' module-id 1188 /// 1189 /// \returns true if an error occurred, false otherwise. 1190 bool ModuleMapParser::parseModuleId(ModuleId &Id) { 1191 Id.clear(); 1192 do { 1193 if (Tok.is(MMToken::Identifier) || Tok.is(MMToken::StringLiteral)) { 1194 Id.push_back(std::make_pair(Tok.getString(), Tok.getLocation())); 1195 consumeToken(); 1196 } else { 1197 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module_name); 1198 return true; 1199 } 1200 1201 if (!Tok.is(MMToken::Period)) 1202 break; 1203 1204 consumeToken(); 1205 } while (true); 1206 1207 return false; 1208 } 1209 1210 namespace { 1211 /// \brief Enumerates the known attributes. 1212 enum AttributeKind { 1213 /// \brief An unknown attribute. 1214 AT_unknown, 1215 /// \brief The 'system' attribute. 1216 AT_system, 1217 /// \brief The 'extern_c' attribute. 1218 AT_extern_c, 1219 /// \brief The 'exhaustive' attribute. 1220 AT_exhaustive 1221 }; 1222 } 1223 1224 /// \brief Parse a module declaration. 1225 /// 1226 /// module-declaration: 1227 /// 'extern' 'module' module-id string-literal 1228 /// 'explicit'[opt] 'framework'[opt] 'module' module-id attributes[opt] 1229 /// { module-member* } 1230 /// 1231 /// module-member: 1232 /// requires-declaration 1233 /// header-declaration 1234 /// submodule-declaration 1235 /// export-declaration 1236 /// link-declaration 1237 /// 1238 /// submodule-declaration: 1239 /// module-declaration 1240 /// inferred-submodule-declaration 1241 void ModuleMapParser::parseModuleDecl() { 1242 assert(Tok.is(MMToken::ExplicitKeyword) || Tok.is(MMToken::ModuleKeyword) || 1243 Tok.is(MMToken::FrameworkKeyword) || Tok.is(MMToken::ExternKeyword)); 1244 if (Tok.is(MMToken::ExternKeyword)) { 1245 parseExternModuleDecl(); 1246 return; 1247 } 1248 1249 // Parse 'explicit' or 'framework' keyword, if present. 1250 SourceLocation ExplicitLoc; 1251 bool Explicit = false; 1252 bool Framework = false; 1253 1254 // Parse 'explicit' keyword, if present. 1255 if (Tok.is(MMToken::ExplicitKeyword)) { 1256 ExplicitLoc = consumeToken(); 1257 Explicit = true; 1258 } 1259 1260 // Parse 'framework' keyword, if present. 1261 if (Tok.is(MMToken::FrameworkKeyword)) { 1262 consumeToken(); 1263 Framework = true; 1264 } 1265 1266 // Parse 'module' keyword. 1267 if (!Tok.is(MMToken::ModuleKeyword)) { 1268 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module); 1269 consumeToken(); 1270 HadError = true; 1271 return; 1272 } 1273 consumeToken(); // 'module' keyword 1274 1275 // If we have a wildcard for the module name, this is an inferred submodule. 1276 // Parse it. 1277 if (Tok.is(MMToken::Star)) 1278 return parseInferredModuleDecl(Framework, Explicit); 1279 1280 // Parse the module name. 1281 ModuleId Id; 1282 if (parseModuleId(Id)) { 1283 HadError = true; 1284 return; 1285 } 1286 1287 if (ActiveModule) { 1288 if (Id.size() > 1) { 1289 Diags.Report(Id.front().second, diag::err_mmap_nested_submodule_id) 1290 << SourceRange(Id.front().second, Id.back().second); 1291 1292 HadError = true; 1293 return; 1294 } 1295 } else if (Id.size() == 1 && Explicit) { 1296 // Top-level modules can't be explicit. 1297 Diags.Report(ExplicitLoc, diag::err_mmap_explicit_top_level); 1298 Explicit = false; 1299 ExplicitLoc = SourceLocation(); 1300 HadError = true; 1301 } 1302 1303 Module *PreviousActiveModule = ActiveModule; 1304 if (Id.size() > 1) { 1305 // This module map defines a submodule. Go find the module of which it 1306 // is a submodule. 1307 ActiveModule = 0; 1308 for (unsigned I = 0, N = Id.size() - 1; I != N; ++I) { 1309 if (Module *Next = Map.lookupModuleQualified(Id[I].first, ActiveModule)) { 1310 ActiveModule = Next; 1311 continue; 1312 } 1313 1314 if (ActiveModule) { 1315 Diags.Report(Id[I].second, diag::err_mmap_missing_module_qualified) 1316 << Id[I].first 1317 << ActiveModule->getTopLevelModule()->getFullModuleName(); 1318 } else { 1319 Diags.Report(Id[I].second, diag::err_mmap_expected_module_name); 1320 } 1321 HadError = true; 1322 return; 1323 } 1324 } 1325 1326 StringRef ModuleName = Id.back().first; 1327 SourceLocation ModuleNameLoc = Id.back().second; 1328 1329 // Parse the optional attribute list. 1330 Attributes Attrs; 1331 parseOptionalAttributes(Attrs); 1332 1333 // Parse the opening brace. 1334 if (!Tok.is(MMToken::LBrace)) { 1335 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_lbrace) 1336 << ModuleName; 1337 HadError = true; 1338 return; 1339 } 1340 SourceLocation LBraceLoc = consumeToken(); 1341 1342 // Determine whether this (sub)module has already been defined. 1343 if (Module *Existing = Map.lookupModuleQualified(ModuleName, ActiveModule)) { 1344 if (Existing->DefinitionLoc.isInvalid() && !ActiveModule) { 1345 // Skip the module definition. 1346 skipUntil(MMToken::RBrace); 1347 if (Tok.is(MMToken::RBrace)) 1348 consumeToken(); 1349 else { 1350 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace); 1351 Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match); 1352 HadError = true; 1353 } 1354 return; 1355 } 1356 1357 Diags.Report(ModuleNameLoc, diag::err_mmap_module_redefinition) 1358 << ModuleName; 1359 Diags.Report(Existing->DefinitionLoc, diag::note_mmap_prev_definition); 1360 1361 // Skip the module definition. 1362 skipUntil(MMToken::RBrace); 1363 if (Tok.is(MMToken::RBrace)) 1364 consumeToken(); 1365 1366 HadError = true; 1367 return; 1368 } 1369 1370 // If this is a submodule, use the parent's module map, since we don't want 1371 // the private module map file. 1372 const FileEntry *ModuleMap = ActiveModule ? ActiveModule->ModuleMap 1373 : ModuleMapFile; 1374 1375 // Start defining this module. 1376 ActiveModule = Map.findOrCreateModule(ModuleName, ActiveModule, ModuleMap, 1377 Framework, Explicit).first; 1378 ActiveModule->DefinitionLoc = ModuleNameLoc; 1379 if (Attrs.IsSystem || IsSystem) 1380 ActiveModule->IsSystem = true; 1381 if (Attrs.IsExternC) 1382 ActiveModule->IsExternC = true; 1383 1384 bool Done = false; 1385 do { 1386 switch (Tok.Kind) { 1387 case MMToken::EndOfFile: 1388 case MMToken::RBrace: 1389 Done = true; 1390 break; 1391 1392 case MMToken::ConfigMacros: 1393 parseConfigMacros(); 1394 break; 1395 1396 case MMToken::Conflict: 1397 parseConflict(); 1398 break; 1399 1400 case MMToken::ExplicitKeyword: 1401 case MMToken::ExternKeyword: 1402 case MMToken::FrameworkKeyword: 1403 case MMToken::ModuleKeyword: 1404 parseModuleDecl(); 1405 break; 1406 1407 case MMToken::ExportKeyword: 1408 parseExportDecl(); 1409 break; 1410 1411 case MMToken::UseKeyword: 1412 parseUseDecl(); 1413 break; 1414 1415 case MMToken::RequiresKeyword: 1416 parseRequiresDecl(); 1417 break; 1418 1419 case MMToken::UmbrellaKeyword: { 1420 SourceLocation UmbrellaLoc = consumeToken(); 1421 if (Tok.is(MMToken::HeaderKeyword)) 1422 parseHeaderDecl(MMToken::UmbrellaKeyword, UmbrellaLoc); 1423 else 1424 parseUmbrellaDirDecl(UmbrellaLoc); 1425 break; 1426 } 1427 1428 case MMToken::ExcludeKeyword: { 1429 SourceLocation ExcludeLoc = consumeToken(); 1430 if (Tok.is(MMToken::HeaderKeyword)) { 1431 parseHeaderDecl(MMToken::ExcludeKeyword, ExcludeLoc); 1432 } else { 1433 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header) 1434 << "exclude"; 1435 } 1436 break; 1437 } 1438 1439 case MMToken::PrivateKeyword: { 1440 SourceLocation PrivateLoc = consumeToken(); 1441 if (Tok.is(MMToken::HeaderKeyword)) { 1442 parseHeaderDecl(MMToken::PrivateKeyword, PrivateLoc); 1443 } else { 1444 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header) 1445 << "private"; 1446 } 1447 break; 1448 } 1449 1450 case MMToken::HeaderKeyword: 1451 parseHeaderDecl(MMToken::HeaderKeyword, SourceLocation()); 1452 break; 1453 1454 case MMToken::LinkKeyword: 1455 parseLinkDecl(); 1456 break; 1457 1458 default: 1459 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_member); 1460 consumeToken(); 1461 break; 1462 } 1463 } while (!Done); 1464 1465 if (Tok.is(MMToken::RBrace)) 1466 consumeToken(); 1467 else { 1468 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace); 1469 Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match); 1470 HadError = true; 1471 } 1472 1473 // If the active module is a top-level framework, and there are no link 1474 // libraries, automatically link against the framework. 1475 if (ActiveModule->IsFramework && !ActiveModule->isSubFramework() && 1476 ActiveModule->LinkLibraries.empty()) { 1477 inferFrameworkLink(ActiveModule, Directory, SourceMgr.getFileManager()); 1478 } 1479 1480 // If the module meets all requirements but is still unavailable, mark the 1481 // whole tree as unavailable to prevent it from building. 1482 if (!ActiveModule->IsAvailable && !ActiveModule->IsMissingRequirement && 1483 ActiveModule->Parent) { 1484 ActiveModule->getTopLevelModule()->markUnavailable(); 1485 ActiveModule->getTopLevelModule()->MissingHeaders.append( 1486 ActiveModule->MissingHeaders.begin(), ActiveModule->MissingHeaders.end()); 1487 } 1488 1489 // We're done parsing this module. Pop back to the previous module. 1490 ActiveModule = PreviousActiveModule; 1491 } 1492 1493 /// \brief Parse an extern module declaration. 1494 /// 1495 /// extern module-declaration: 1496 /// 'extern' 'module' module-id string-literal 1497 void ModuleMapParser::parseExternModuleDecl() { 1498 assert(Tok.is(MMToken::ExternKeyword)); 1499 consumeToken(); // 'extern' keyword 1500 1501 // Parse 'module' keyword. 1502 if (!Tok.is(MMToken::ModuleKeyword)) { 1503 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module); 1504 consumeToken(); 1505 HadError = true; 1506 return; 1507 } 1508 consumeToken(); // 'module' keyword 1509 1510 // Parse the module name. 1511 ModuleId Id; 1512 if (parseModuleId(Id)) { 1513 HadError = true; 1514 return; 1515 } 1516 1517 // Parse the referenced module map file name. 1518 if (!Tok.is(MMToken::StringLiteral)) { 1519 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_mmap_file); 1520 HadError = true; 1521 return; 1522 } 1523 std::string FileName = Tok.getString(); 1524 consumeToken(); // filename 1525 1526 StringRef FileNameRef = FileName; 1527 SmallString<128> ModuleMapFileName; 1528 if (llvm::sys::path::is_relative(FileNameRef)) { 1529 ModuleMapFileName += Directory->getName(); 1530 llvm::sys::path::append(ModuleMapFileName, FileName); 1531 FileNameRef = ModuleMapFileName.str(); 1532 } 1533 if (const FileEntry *File = SourceMgr.getFileManager().getFile(FileNameRef)) 1534 Map.parseModuleMapFile(File, /*IsSystem=*/false); 1535 } 1536 1537 /// \brief Parse a requires declaration. 1538 /// 1539 /// requires-declaration: 1540 /// 'requires' feature-list 1541 /// 1542 /// feature-list: 1543 /// feature ',' feature-list 1544 /// feature 1545 /// 1546 /// feature: 1547 /// '!'[opt] identifier 1548 void ModuleMapParser::parseRequiresDecl() { 1549 assert(Tok.is(MMToken::RequiresKeyword)); 1550 1551 // Parse 'requires' keyword. 1552 consumeToken(); 1553 1554 // Parse the feature-list. 1555 do { 1556 bool RequiredState = true; 1557 if (Tok.is(MMToken::Exclaim)) { 1558 RequiredState = false; 1559 consumeToken(); 1560 } 1561 1562 if (!Tok.is(MMToken::Identifier)) { 1563 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_feature); 1564 HadError = true; 1565 return; 1566 } 1567 1568 // Consume the feature name. 1569 std::string Feature = Tok.getString(); 1570 consumeToken(); 1571 1572 // Add this feature. 1573 ActiveModule->addRequirement(Feature, RequiredState, 1574 Map.LangOpts, *Map.Target); 1575 1576 if (!Tok.is(MMToken::Comma)) 1577 break; 1578 1579 // Consume the comma. 1580 consumeToken(); 1581 } while (true); 1582 } 1583 1584 /// \brief Append to \p Paths the set of paths needed to get to the 1585 /// subframework in which the given module lives. 1586 static void appendSubframeworkPaths(Module *Mod, 1587 SmallVectorImpl<char> &Path) { 1588 // Collect the framework names from the given module to the top-level module. 1589 SmallVector<StringRef, 2> Paths; 1590 for (; Mod; Mod = Mod->Parent) { 1591 if (Mod->IsFramework) 1592 Paths.push_back(Mod->Name); 1593 } 1594 1595 if (Paths.empty()) 1596 return; 1597 1598 // Add Frameworks/Name.framework for each subframework. 1599 for (unsigned I = Paths.size() - 1; I != 0; --I) 1600 llvm::sys::path::append(Path, "Frameworks", Paths[I-1] + ".framework"); 1601 } 1602 1603 /// \brief Parse a header declaration. 1604 /// 1605 /// header-declaration: 1606 /// 'umbrella'[opt] 'header' string-literal 1607 /// 'exclude'[opt] 'header' string-literal 1608 void ModuleMapParser::parseHeaderDecl(MMToken::TokenKind LeadingToken, 1609 SourceLocation LeadingLoc) { 1610 assert(Tok.is(MMToken::HeaderKeyword)); 1611 consumeToken(); 1612 1613 // Parse the header name. 1614 if (!Tok.is(MMToken::StringLiteral)) { 1615 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header) 1616 << "header"; 1617 HadError = true; 1618 return; 1619 } 1620 Module::HeaderDirective Header; 1621 Header.FileName = Tok.getString(); 1622 Header.FileNameLoc = consumeToken(); 1623 1624 // Check whether we already have an umbrella. 1625 if (LeadingToken == MMToken::UmbrellaKeyword && ActiveModule->Umbrella) { 1626 Diags.Report(Header.FileNameLoc, diag::err_mmap_umbrella_clash) 1627 << ActiveModule->getFullModuleName(); 1628 HadError = true; 1629 return; 1630 } 1631 1632 // Look for this file. 1633 const FileEntry *File = 0; 1634 const FileEntry *BuiltinFile = 0; 1635 SmallString<128> PathName; 1636 if (llvm::sys::path::is_absolute(Header.FileName)) { 1637 PathName = Header.FileName; 1638 File = SourceMgr.getFileManager().getFile(PathName); 1639 } else { 1640 // Search for the header file within the search directory. 1641 PathName = Directory->getName(); 1642 unsigned PathLength = PathName.size(); 1643 1644 if (ActiveModule->isPartOfFramework()) { 1645 appendSubframeworkPaths(ActiveModule, PathName); 1646 1647 // Check whether this file is in the public headers. 1648 llvm::sys::path::append(PathName, "Headers", Header.FileName); 1649 File = SourceMgr.getFileManager().getFile(PathName); 1650 1651 if (!File) { 1652 // Check whether this file is in the private headers. 1653 PathName.resize(PathLength); 1654 llvm::sys::path::append(PathName, "PrivateHeaders", Header.FileName); 1655 File = SourceMgr.getFileManager().getFile(PathName); 1656 } 1657 } else { 1658 // Lookup for normal headers. 1659 llvm::sys::path::append(PathName, Header.FileName); 1660 File = SourceMgr.getFileManager().getFile(PathName); 1661 1662 // If this is a system module with a top-level header, this header 1663 // may have a counterpart (or replacement) in the set of headers 1664 // supplied by Clang. Find that builtin header. 1665 if (ActiveModule->IsSystem && LeadingToken != MMToken::UmbrellaKeyword && 1666 BuiltinIncludeDir && BuiltinIncludeDir != Directory && 1667 isBuiltinHeader(Header.FileName)) { 1668 SmallString<128> BuiltinPathName(BuiltinIncludeDir->getName()); 1669 llvm::sys::path::append(BuiltinPathName, Header.FileName); 1670 BuiltinFile = SourceMgr.getFileManager().getFile(BuiltinPathName); 1671 1672 // If Clang supplies this header but the underlying system does not, 1673 // just silently swap in our builtin version. Otherwise, we'll end 1674 // up adding both (later). 1675 if (!File && BuiltinFile) { 1676 File = BuiltinFile; 1677 BuiltinFile = 0; 1678 } 1679 } 1680 } 1681 } 1682 1683 // FIXME: We shouldn't be eagerly stat'ing every file named in a module map. 1684 // Come up with a lazy way to do this. 1685 if (File) { 1686 if (LeadingToken == MMToken::UmbrellaKeyword) { 1687 const DirectoryEntry *UmbrellaDir = File->getDir(); 1688 if (Module *UmbrellaModule = Map.UmbrellaDirs[UmbrellaDir]) { 1689 Diags.Report(LeadingLoc, diag::err_mmap_umbrella_clash) 1690 << UmbrellaModule->getFullModuleName(); 1691 HadError = true; 1692 } else { 1693 // Record this umbrella header. 1694 Map.setUmbrellaHeader(ActiveModule, File); 1695 } 1696 } else { 1697 // Record this header. 1698 ModuleMap::ModuleHeaderRole Role = ModuleMap::NormalHeader; 1699 if (LeadingToken == MMToken::ExcludeKeyword) 1700 Role = ModuleMap::ExcludedHeader; 1701 else if (LeadingToken == MMToken::PrivateKeyword) 1702 Role = ModuleMap::PrivateHeader; 1703 else 1704 assert(LeadingToken == MMToken::HeaderKeyword); 1705 1706 Map.addHeader(ActiveModule, File, Role); 1707 1708 // If there is a builtin counterpart to this file, add it now. 1709 if (BuiltinFile) 1710 Map.addHeader(ActiveModule, BuiltinFile, Role); 1711 } 1712 } else if (LeadingToken != MMToken::ExcludeKeyword) { 1713 // Ignore excluded header files. They're optional anyway. 1714 1715 // If we find a module that has a missing header, we mark this module as 1716 // unavailable and store the header directive for displaying diagnostics. 1717 Header.IsUmbrella = LeadingToken == MMToken::UmbrellaKeyword; 1718 ActiveModule->markUnavailable(); 1719 ActiveModule->MissingHeaders.push_back(Header); 1720 } 1721 } 1722 1723 /// \brief Parse an umbrella directory declaration. 1724 /// 1725 /// umbrella-dir-declaration: 1726 /// umbrella string-literal 1727 void ModuleMapParser::parseUmbrellaDirDecl(SourceLocation UmbrellaLoc) { 1728 // Parse the directory name. 1729 if (!Tok.is(MMToken::StringLiteral)) { 1730 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header) 1731 << "umbrella"; 1732 HadError = true; 1733 return; 1734 } 1735 1736 std::string DirName = Tok.getString(); 1737 SourceLocation DirNameLoc = consumeToken(); 1738 1739 // Check whether we already have an umbrella. 1740 if (ActiveModule->Umbrella) { 1741 Diags.Report(DirNameLoc, diag::err_mmap_umbrella_clash) 1742 << ActiveModule->getFullModuleName(); 1743 HadError = true; 1744 return; 1745 } 1746 1747 // Look for this file. 1748 const DirectoryEntry *Dir = 0; 1749 if (llvm::sys::path::is_absolute(DirName)) 1750 Dir = SourceMgr.getFileManager().getDirectory(DirName); 1751 else { 1752 SmallString<128> PathName; 1753 PathName = Directory->getName(); 1754 llvm::sys::path::append(PathName, DirName); 1755 Dir = SourceMgr.getFileManager().getDirectory(PathName); 1756 } 1757 1758 if (!Dir) { 1759 Diags.Report(DirNameLoc, diag::err_mmap_umbrella_dir_not_found) 1760 << DirName; 1761 HadError = true; 1762 return; 1763 } 1764 1765 if (Module *OwningModule = Map.UmbrellaDirs[Dir]) { 1766 Diags.Report(UmbrellaLoc, diag::err_mmap_umbrella_clash) 1767 << OwningModule->getFullModuleName(); 1768 HadError = true; 1769 return; 1770 } 1771 1772 // Record this umbrella directory. 1773 Map.setUmbrellaDir(ActiveModule, Dir); 1774 } 1775 1776 /// \brief Parse a module export declaration. 1777 /// 1778 /// export-declaration: 1779 /// 'export' wildcard-module-id 1780 /// 1781 /// wildcard-module-id: 1782 /// identifier 1783 /// '*' 1784 /// identifier '.' wildcard-module-id 1785 void ModuleMapParser::parseExportDecl() { 1786 assert(Tok.is(MMToken::ExportKeyword)); 1787 SourceLocation ExportLoc = consumeToken(); 1788 1789 // Parse the module-id with an optional wildcard at the end. 1790 ModuleId ParsedModuleId; 1791 bool Wildcard = false; 1792 do { 1793 if (Tok.is(MMToken::Identifier)) { 1794 ParsedModuleId.push_back(std::make_pair(Tok.getString(), 1795 Tok.getLocation())); 1796 consumeToken(); 1797 1798 if (Tok.is(MMToken::Period)) { 1799 consumeToken(); 1800 continue; 1801 } 1802 1803 break; 1804 } 1805 1806 if(Tok.is(MMToken::Star)) { 1807 Wildcard = true; 1808 consumeToken(); 1809 break; 1810 } 1811 1812 Diags.Report(Tok.getLocation(), diag::err_mmap_module_id); 1813 HadError = true; 1814 return; 1815 } while (true); 1816 1817 Module::UnresolvedExportDecl Unresolved = { 1818 ExportLoc, ParsedModuleId, Wildcard 1819 }; 1820 ActiveModule->UnresolvedExports.push_back(Unresolved); 1821 } 1822 1823 /// \brief Parse a module uses declaration. 1824 /// 1825 /// uses-declaration: 1826 /// 'uses' wildcard-module-id 1827 void ModuleMapParser::parseUseDecl() { 1828 assert(Tok.is(MMToken::UseKeyword)); 1829 consumeToken(); 1830 // Parse the module-id. 1831 ModuleId ParsedModuleId; 1832 parseModuleId(ParsedModuleId); 1833 1834 ActiveModule->UnresolvedDirectUses.push_back(ParsedModuleId); 1835 } 1836 1837 /// \brief Parse a link declaration. 1838 /// 1839 /// module-declaration: 1840 /// 'link' 'framework'[opt] string-literal 1841 void ModuleMapParser::parseLinkDecl() { 1842 assert(Tok.is(MMToken::LinkKeyword)); 1843 SourceLocation LinkLoc = consumeToken(); 1844 1845 // Parse the optional 'framework' keyword. 1846 bool IsFramework = false; 1847 if (Tok.is(MMToken::FrameworkKeyword)) { 1848 consumeToken(); 1849 IsFramework = true; 1850 } 1851 1852 // Parse the library name 1853 if (!Tok.is(MMToken::StringLiteral)) { 1854 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_library_name) 1855 << IsFramework << SourceRange(LinkLoc); 1856 HadError = true; 1857 return; 1858 } 1859 1860 std::string LibraryName = Tok.getString(); 1861 consumeToken(); 1862 ActiveModule->LinkLibraries.push_back(Module::LinkLibrary(LibraryName, 1863 IsFramework)); 1864 } 1865 1866 /// \brief Parse a configuration macro declaration. 1867 /// 1868 /// module-declaration: 1869 /// 'config_macros' attributes[opt] config-macro-list? 1870 /// 1871 /// config-macro-list: 1872 /// identifier (',' identifier)? 1873 void ModuleMapParser::parseConfigMacros() { 1874 assert(Tok.is(MMToken::ConfigMacros)); 1875 SourceLocation ConfigMacrosLoc = consumeToken(); 1876 1877 // Only top-level modules can have configuration macros. 1878 if (ActiveModule->Parent) { 1879 Diags.Report(ConfigMacrosLoc, diag::err_mmap_config_macro_submodule); 1880 } 1881 1882 // Parse the optional attributes. 1883 Attributes Attrs; 1884 parseOptionalAttributes(Attrs); 1885 if (Attrs.IsExhaustive && !ActiveModule->Parent) { 1886 ActiveModule->ConfigMacrosExhaustive = true; 1887 } 1888 1889 // If we don't have an identifier, we're done. 1890 if (!Tok.is(MMToken::Identifier)) 1891 return; 1892 1893 // Consume the first identifier. 1894 if (!ActiveModule->Parent) { 1895 ActiveModule->ConfigMacros.push_back(Tok.getString().str()); 1896 } 1897 consumeToken(); 1898 1899 do { 1900 // If there's a comma, consume it. 1901 if (!Tok.is(MMToken::Comma)) 1902 break; 1903 consumeToken(); 1904 1905 // We expect to see a macro name here. 1906 if (!Tok.is(MMToken::Identifier)) { 1907 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_config_macro); 1908 break; 1909 } 1910 1911 // Consume the macro name. 1912 if (!ActiveModule->Parent) { 1913 ActiveModule->ConfigMacros.push_back(Tok.getString().str()); 1914 } 1915 consumeToken(); 1916 } while (true); 1917 } 1918 1919 /// \brief Format a module-id into a string. 1920 static std::string formatModuleId(const ModuleId &Id) { 1921 std::string result; 1922 { 1923 llvm::raw_string_ostream OS(result); 1924 1925 for (unsigned I = 0, N = Id.size(); I != N; ++I) { 1926 if (I) 1927 OS << "."; 1928 OS << Id[I].first; 1929 } 1930 } 1931 1932 return result; 1933 } 1934 1935 /// \brief Parse a conflict declaration. 1936 /// 1937 /// module-declaration: 1938 /// 'conflict' module-id ',' string-literal 1939 void ModuleMapParser::parseConflict() { 1940 assert(Tok.is(MMToken::Conflict)); 1941 SourceLocation ConflictLoc = consumeToken(); 1942 Module::UnresolvedConflict Conflict; 1943 1944 // Parse the module-id. 1945 if (parseModuleId(Conflict.Id)) 1946 return; 1947 1948 // Parse the ','. 1949 if (!Tok.is(MMToken::Comma)) { 1950 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_conflicts_comma) 1951 << SourceRange(ConflictLoc); 1952 return; 1953 } 1954 consumeToken(); 1955 1956 // Parse the message. 1957 if (!Tok.is(MMToken::StringLiteral)) { 1958 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_conflicts_message) 1959 << formatModuleId(Conflict.Id); 1960 return; 1961 } 1962 Conflict.Message = Tok.getString().str(); 1963 consumeToken(); 1964 1965 // Add this unresolved conflict. 1966 ActiveModule->UnresolvedConflicts.push_back(Conflict); 1967 } 1968 1969 /// \brief Parse an inferred module declaration (wildcard modules). 1970 /// 1971 /// module-declaration: 1972 /// 'explicit'[opt] 'framework'[opt] 'module' * attributes[opt] 1973 /// { inferred-module-member* } 1974 /// 1975 /// inferred-module-member: 1976 /// 'export' '*' 1977 /// 'exclude' identifier 1978 void ModuleMapParser::parseInferredModuleDecl(bool Framework, bool Explicit) { 1979 assert(Tok.is(MMToken::Star)); 1980 SourceLocation StarLoc = consumeToken(); 1981 bool Failed = false; 1982 1983 // Inferred modules must be submodules. 1984 if (!ActiveModule && !Framework) { 1985 Diags.Report(StarLoc, diag::err_mmap_top_level_inferred_submodule); 1986 Failed = true; 1987 } 1988 1989 if (ActiveModule) { 1990 // Inferred modules must have umbrella directories. 1991 if (!Failed && ActiveModule->IsAvailable && 1992 !ActiveModule->getUmbrellaDir()) { 1993 Diags.Report(StarLoc, diag::err_mmap_inferred_no_umbrella); 1994 Failed = true; 1995 } 1996 1997 // Check for redefinition of an inferred module. 1998 if (!Failed && ActiveModule->InferSubmodules) { 1999 Diags.Report(StarLoc, diag::err_mmap_inferred_redef); 2000 if (ActiveModule->InferredSubmoduleLoc.isValid()) 2001 Diags.Report(ActiveModule->InferredSubmoduleLoc, 2002 diag::note_mmap_prev_definition); 2003 Failed = true; 2004 } 2005 2006 // Check for the 'framework' keyword, which is not permitted here. 2007 if (Framework) { 2008 Diags.Report(StarLoc, diag::err_mmap_inferred_framework_submodule); 2009 Framework = false; 2010 } 2011 } else if (Explicit) { 2012 Diags.Report(StarLoc, diag::err_mmap_explicit_inferred_framework); 2013 Explicit = false; 2014 } 2015 2016 // If there were any problems with this inferred submodule, skip its body. 2017 if (Failed) { 2018 if (Tok.is(MMToken::LBrace)) { 2019 consumeToken(); 2020 skipUntil(MMToken::RBrace); 2021 if (Tok.is(MMToken::RBrace)) 2022 consumeToken(); 2023 } 2024 HadError = true; 2025 return; 2026 } 2027 2028 // Parse optional attributes. 2029 Attributes Attrs; 2030 parseOptionalAttributes(Attrs); 2031 2032 if (ActiveModule) { 2033 // Note that we have an inferred submodule. 2034 ActiveModule->InferSubmodules = true; 2035 ActiveModule->InferredSubmoduleLoc = StarLoc; 2036 ActiveModule->InferExplicitSubmodules = Explicit; 2037 } else { 2038 // We'll be inferring framework modules for this directory. 2039 Map.InferredDirectories[Directory].InferModules = true; 2040 Map.InferredDirectories[Directory].InferSystemModules = Attrs.IsSystem; 2041 Map.InferredDirectories[Directory].ModuleMapFile = ModuleMapFile; 2042 // FIXME: Handle the 'framework' keyword. 2043 } 2044 2045 // Parse the opening brace. 2046 if (!Tok.is(MMToken::LBrace)) { 2047 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_lbrace_wildcard); 2048 HadError = true; 2049 return; 2050 } 2051 SourceLocation LBraceLoc = consumeToken(); 2052 2053 // Parse the body of the inferred submodule. 2054 bool Done = false; 2055 do { 2056 switch (Tok.Kind) { 2057 case MMToken::EndOfFile: 2058 case MMToken::RBrace: 2059 Done = true; 2060 break; 2061 2062 case MMToken::ExcludeKeyword: { 2063 if (ActiveModule) { 2064 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member) 2065 << (ActiveModule != 0); 2066 consumeToken(); 2067 break; 2068 } 2069 2070 consumeToken(); 2071 if (!Tok.is(MMToken::Identifier)) { 2072 Diags.Report(Tok.getLocation(), diag::err_mmap_missing_exclude_name); 2073 break; 2074 } 2075 2076 Map.InferredDirectories[Directory].ExcludedModules 2077 .push_back(Tok.getString()); 2078 consumeToken(); 2079 break; 2080 } 2081 2082 case MMToken::ExportKeyword: 2083 if (!ActiveModule) { 2084 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member) 2085 << (ActiveModule != 0); 2086 consumeToken(); 2087 break; 2088 } 2089 2090 consumeToken(); 2091 if (Tok.is(MMToken::Star)) 2092 ActiveModule->InferExportWildcard = true; 2093 else 2094 Diags.Report(Tok.getLocation(), 2095 diag::err_mmap_expected_export_wildcard); 2096 consumeToken(); 2097 break; 2098 2099 case MMToken::ExplicitKeyword: 2100 case MMToken::ModuleKeyword: 2101 case MMToken::HeaderKeyword: 2102 case MMToken::PrivateKeyword: 2103 case MMToken::UmbrellaKeyword: 2104 default: 2105 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member) 2106 << (ActiveModule != 0); 2107 consumeToken(); 2108 break; 2109 } 2110 } while (!Done); 2111 2112 if (Tok.is(MMToken::RBrace)) 2113 consumeToken(); 2114 else { 2115 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace); 2116 Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match); 2117 HadError = true; 2118 } 2119 } 2120 2121 /// \brief Parse optional attributes. 2122 /// 2123 /// attributes: 2124 /// attribute attributes 2125 /// attribute 2126 /// 2127 /// attribute: 2128 /// [ identifier ] 2129 /// 2130 /// \param Attrs Will be filled in with the parsed attributes. 2131 /// 2132 /// \returns true if an error occurred, false otherwise. 2133 bool ModuleMapParser::parseOptionalAttributes(Attributes &Attrs) { 2134 bool HadError = false; 2135 2136 while (Tok.is(MMToken::LSquare)) { 2137 // Consume the '['. 2138 SourceLocation LSquareLoc = consumeToken(); 2139 2140 // Check whether we have an attribute name here. 2141 if (!Tok.is(MMToken::Identifier)) { 2142 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_attribute); 2143 skipUntil(MMToken::RSquare); 2144 if (Tok.is(MMToken::RSquare)) 2145 consumeToken(); 2146 HadError = true; 2147 } 2148 2149 // Decode the attribute name. 2150 AttributeKind Attribute 2151 = llvm::StringSwitch<AttributeKind>(Tok.getString()) 2152 .Case("exhaustive", AT_exhaustive) 2153 .Case("extern_c", AT_extern_c) 2154 .Case("system", AT_system) 2155 .Default(AT_unknown); 2156 switch (Attribute) { 2157 case AT_unknown: 2158 Diags.Report(Tok.getLocation(), diag::warn_mmap_unknown_attribute) 2159 << Tok.getString(); 2160 break; 2161 2162 case AT_system: 2163 Attrs.IsSystem = true; 2164 break; 2165 2166 case AT_extern_c: 2167 Attrs.IsExternC = true; 2168 break; 2169 2170 case AT_exhaustive: 2171 Attrs.IsExhaustive = true; 2172 break; 2173 } 2174 consumeToken(); 2175 2176 // Consume the ']'. 2177 if (!Tok.is(MMToken::RSquare)) { 2178 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rsquare); 2179 Diags.Report(LSquareLoc, diag::note_mmap_lsquare_match); 2180 skipUntil(MMToken::RSquare); 2181 HadError = true; 2182 } 2183 2184 if (Tok.is(MMToken::RSquare)) 2185 consumeToken(); 2186 } 2187 2188 return HadError; 2189 } 2190 2191 /// \brief Parse a module map file. 2192 /// 2193 /// module-map-file: 2194 /// module-declaration* 2195 bool ModuleMapParser::parseModuleMapFile() { 2196 do { 2197 switch (Tok.Kind) { 2198 case MMToken::EndOfFile: 2199 return HadError; 2200 2201 case MMToken::ExplicitKeyword: 2202 case MMToken::ExternKeyword: 2203 case MMToken::ModuleKeyword: 2204 case MMToken::FrameworkKeyword: 2205 parseModuleDecl(); 2206 break; 2207 2208 case MMToken::Comma: 2209 case MMToken::ConfigMacros: 2210 case MMToken::Conflict: 2211 case MMToken::Exclaim: 2212 case MMToken::ExcludeKeyword: 2213 case MMToken::ExportKeyword: 2214 case MMToken::HeaderKeyword: 2215 case MMToken::Identifier: 2216 case MMToken::LBrace: 2217 case MMToken::LinkKeyword: 2218 case MMToken::LSquare: 2219 case MMToken::Period: 2220 case MMToken::PrivateKeyword: 2221 case MMToken::RBrace: 2222 case MMToken::RSquare: 2223 case MMToken::RequiresKeyword: 2224 case MMToken::Star: 2225 case MMToken::StringLiteral: 2226 case MMToken::UmbrellaKeyword: 2227 case MMToken::UseKeyword: 2228 Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module); 2229 HadError = true; 2230 consumeToken(); 2231 break; 2232 } 2233 } while (true); 2234 } 2235 2236 bool ModuleMap::parseModuleMapFile(const FileEntry *File, bool IsSystem) { 2237 llvm::DenseMap<const FileEntry *, bool>::iterator Known 2238 = ParsedModuleMap.find(File); 2239 if (Known != ParsedModuleMap.end()) 2240 return Known->second; 2241 2242 assert(Target != 0 && "Missing target information"); 2243 auto FileCharacter = IsSystem ? SrcMgr::C_System : SrcMgr::C_User; 2244 FileID ID = SourceMgr.createFileID(File, SourceLocation(), FileCharacter); 2245 const llvm::MemoryBuffer *Buffer = SourceMgr.getBuffer(ID); 2246 if (!Buffer) 2247 return ParsedModuleMap[File] = true; 2248 2249 // Find the directory for the module. For frameworks, that may require going 2250 // up from the 'Modules' directory. 2251 const DirectoryEntry *Dir = File->getDir(); 2252 StringRef DirName(Dir->getName()); 2253 if (llvm::sys::path::filename(DirName) == "Modules") { 2254 DirName = llvm::sys::path::parent_path(DirName); 2255 if (DirName.endswith(".framework")) 2256 Dir = SourceMgr.getFileManager().getDirectory(DirName); 2257 assert(Dir && "parent must exist"); 2258 } 2259 2260 // Parse this module map file. 2261 Lexer L(ID, SourceMgr.getBuffer(ID), SourceMgr, MMapLangOpts); 2262 ModuleMapParser Parser(L, SourceMgr, Target, Diags, *this, File, Dir, 2263 BuiltinIncludeDir, IsSystem); 2264 bool Result = Parser.parseModuleMapFile(); 2265 ParsedModuleMap[File] = Result; 2266 return Result; 2267 } 2268