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