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