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