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