ModuleMap.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032
  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/Lex/Lexer.h"
  16. #include "clang/Lex/LiteralSupport.h"
  17. #include "clang/Lex/LexDiagnostic.h"
  18. #include "clang/Basic/Diagnostic.h"
  19. #include "clang/Basic/FileManager.h"
  20. #include "clang/Basic/TargetInfo.h"
  21. #include "clang/Basic/TargetOptions.h"
  22. #include "llvm/Support/Allocator.h"
  23. #include "llvm/Support/Host.h"
  24. #include "llvm/Support/PathV2.h"
  25. #include "llvm/Support/raw_ostream.h"
  26. #include "llvm/ADT/StringRef.h"
  27. #include "llvm/ADT/StringSwitch.h"
  28. using namespace clang;
  29. Module::ExportDecl
  30. ModuleMap::resolveExport(Module *Mod,
  31. const Module::UnresolvedExportDecl &Unresolved,
  32. bool Complain) {
  33. // We may have just a wildcard.
  34. if (Unresolved.Id.empty()) {
  35. assert(Unresolved.Wildcard && "Invalid unresolved export");
  36. return Module::ExportDecl(0, true);
  37. }
  38. // Find the starting module.
  39. Module *Context = lookupModuleUnqualified(Unresolved.Id[0].first, Mod);
  40. if (!Context) {
  41. if (Complain)
  42. Diags->Report(Unresolved.Id[0].second,
  43. diag::err_mmap_missing_module_unqualified)
  44. << Unresolved.Id[0].first << Mod->getFullModuleName();
  45. return Module::ExportDecl();
  46. }
  47. // Dig into the module path.
  48. for (unsigned I = 1, N = Unresolved.Id.size(); I != N; ++I) {
  49. Module *Sub = lookupModuleQualified(Unresolved.Id[I].first,
  50. Context);
  51. if (!Sub) {
  52. if (Complain)
  53. Diags->Report(Unresolved.Id[I].second,
  54. diag::err_mmap_missing_module_qualified)
  55. << Unresolved.Id[I].first << Context->getFullModuleName()
  56. << SourceRange(Unresolved.Id[0].second, Unresolved.Id[I-1].second);
  57. return Module::ExportDecl();
  58. }
  59. Context = Sub;
  60. }
  61. return Module::ExportDecl(Context, Unresolved.Wildcard);
  62. }
  63. ModuleMap::ModuleMap(FileManager &FileMgr, const DiagnosticConsumer &DC) {
  64. llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(new DiagnosticIDs);
  65. Diags = llvm::IntrusiveRefCntPtr<DiagnosticsEngine>(
  66. new DiagnosticsEngine(DiagIDs));
  67. Diags->setClient(DC.clone(*Diags), /*ShouldOwnClient=*/true);
  68. SourceMgr = new SourceManager(*Diags, FileMgr);
  69. }
  70. ModuleMap::~ModuleMap() {
  71. for (llvm::StringMap<Module *>::iterator I = Modules.begin(),
  72. IEnd = Modules.end();
  73. I != IEnd; ++I) {
  74. delete I->getValue();
  75. }
  76. delete SourceMgr;
  77. }
  78. Module *ModuleMap::findModuleForHeader(const FileEntry *File) {
  79. llvm::DenseMap<const FileEntry *, Module *>::iterator Known
  80. = Headers.find(File);
  81. if (Known != Headers.end())
  82. return Known->second;
  83. const DirectoryEntry *Dir = File->getDir();
  84. llvm::SmallVector<const DirectoryEntry *, 2> SkippedDirs;
  85. StringRef DirName = Dir->getName();
  86. // Keep walking up the directory hierarchy, looking for a directory with
  87. // an umbrella header.
  88. do {
  89. llvm::DenseMap<const DirectoryEntry *, Module *>::iterator KnownDir
  90. = UmbrellaDirs.find(Dir);
  91. if (KnownDir != UmbrellaDirs.end()) {
  92. Module *Result = KnownDir->second;
  93. // Search up the module stack until we find a module with an umbrella
  94. // header.
  95. Module *UmbrellaModule = Result;
  96. while (!UmbrellaModule->UmbrellaHeader && UmbrellaModule->Parent)
  97. UmbrellaModule = UmbrellaModule->Parent;
  98. if (UmbrellaModule->InferSubmodules) {
  99. // Infer submodules for each of the directories we found between
  100. // the directory of the umbrella header and the directory where
  101. // the actual header is located.
  102. // For a framework module, the umbrella directory is the framework
  103. // directory, so strip off the "Headers" or "PrivateHeaders".
  104. // FIXME: Should we tack on an "explicit" for PrivateHeaders? That
  105. // might be what we want, but it feels like a hack.
  106. unsigned LastSkippedDir = SkippedDirs.size();
  107. if (LastSkippedDir && UmbrellaModule->IsFramework)
  108. --LastSkippedDir;
  109. for (unsigned I = LastSkippedDir; I != 0; --I) {
  110. // Find or create the module that corresponds to this directory name.
  111. StringRef Name = llvm::sys::path::stem(SkippedDirs[I-1]->getName());
  112. Result = findOrCreateModule(Name, Result, /*IsFramework=*/false,
  113. UmbrellaModule->InferExplicitSubmodules).first;
  114. // Associate the module and the directory.
  115. UmbrellaDirs[SkippedDirs[I-1]] = Result;
  116. // If inferred submodules export everything they import, add a
  117. // wildcard to the set of exports.
  118. if (UmbrellaModule->InferExportWildcard && Result->Exports.empty())
  119. Result->Exports.push_back(Module::ExportDecl(0, true));
  120. }
  121. // Infer a submodule with the same name as this header file.
  122. StringRef Name = llvm::sys::path::stem(File->getName());
  123. Result = findOrCreateModule(Name, Result, /*IsFramework=*/false,
  124. UmbrellaModule->InferExplicitSubmodules).first;
  125. // If inferred submodules export everything they import, add a
  126. // wildcard to the set of exports.
  127. if (UmbrellaModule->InferExportWildcard && Result->Exports.empty())
  128. Result->Exports.push_back(Module::ExportDecl(0, true));
  129. } else {
  130. // Record each of the directories we stepped through as being part of
  131. // the module we found, since the umbrella header covers them all.
  132. for (unsigned I = 0, N = SkippedDirs.size(); I != N; ++I)
  133. UmbrellaDirs[SkippedDirs[I]] = Result;
  134. }
  135. Headers[File] = Result;
  136. return Result;
  137. }
  138. SkippedDirs.push_back(Dir);
  139. // Retrieve our parent path.
  140. DirName = llvm::sys::path::parent_path(DirName);
  141. if (DirName.empty())
  142. break;
  143. // Resolve the parent path to a directory entry.
  144. Dir = SourceMgr->getFileManager().getDirectory(DirName);
  145. } while (Dir);
  146. return 0;
  147. }
  148. Module *ModuleMap::findModule(StringRef Name) {
  149. llvm::StringMap<Module *>::iterator Known = Modules.find(Name);
  150. if (Known != Modules.end())
  151. return Known->getValue();
  152. return 0;
  153. }
  154. Module *ModuleMap::lookupModuleUnqualified(StringRef Name, Module *Context) {
  155. for(; Context; Context = Context->Parent) {
  156. if (Module *Sub = lookupModuleQualified(Name, Context))
  157. return Sub;
  158. }
  159. return findModule(Name);
  160. }
  161. Module *ModuleMap::lookupModuleQualified(StringRef Name, Module *Context) {
  162. if (!Context)
  163. return findModule(Name);
  164. llvm::StringMap<Module *>::iterator Sub = Context->SubModules.find(Name);
  165. if (Sub != Context->SubModules.end())
  166. return Sub->getValue();
  167. return 0;
  168. }
  169. std::pair<Module *, bool>
  170. ModuleMap::findOrCreateModule(StringRef Name, Module *Parent, bool IsFramework,
  171. bool IsExplicit) {
  172. // Try to find an existing module with this name.
  173. if (Module *Found = Parent? Parent->SubModules[Name] : Modules[Name])
  174. return std::make_pair(Found, false);
  175. // Create a new module with this name.
  176. Module *Result = new Module(Name, SourceLocation(), Parent, IsFramework,
  177. IsExplicit);
  178. if (Parent)
  179. Parent->SubModules[Name] = Result;
  180. else
  181. Modules[Name] = Result;
  182. return std::make_pair(Result, true);
  183. }
  184. Module *
  185. ModuleMap::inferFrameworkModule(StringRef ModuleName,
  186. const DirectoryEntry *FrameworkDir) {
  187. // Check whether we've already found this module.
  188. if (Module *Module = findModule(ModuleName))
  189. return Module;
  190. // Look for an umbrella header.
  191. llvm::SmallString<128> UmbrellaName = StringRef(FrameworkDir->getName());
  192. llvm::sys::path::append(UmbrellaName, "Headers");
  193. llvm::sys::path::append(UmbrellaName, ModuleName + ".h");
  194. const FileEntry *UmbrellaHeader
  195. = SourceMgr->getFileManager().getFile(UmbrellaName);
  196. // FIXME: If there's no umbrella header, we could probably scan the
  197. // framework to load *everything*. But, it's not clear that this is a good
  198. // idea.
  199. if (!UmbrellaHeader)
  200. return 0;
  201. Module *Result = new Module(ModuleName, SourceLocation(),
  202. /*IsFramework=*/true);
  203. // umbrella "umbrella-header-name"
  204. Result->UmbrellaHeader = UmbrellaHeader;
  205. Headers[UmbrellaHeader] = Result;
  206. UmbrellaDirs[FrameworkDir] = Result;
  207. // export *
  208. Result->Exports.push_back(Module::ExportDecl(0, true));
  209. // module * { export * }
  210. Result->InferSubmodules = true;
  211. Result->InferExportWildcard = true;
  212. // FIXME: Look for subframeworks.
  213. Modules[ModuleName] = Result;
  214. return Result;
  215. }
  216. void ModuleMap::setUmbrellaHeader(Module *Mod, const FileEntry *UmbrellaHeader){
  217. Headers[UmbrellaHeader] = Mod;
  218. Mod->UmbrellaHeader = UmbrellaHeader;
  219. const DirectoryEntry *UmbrellaDir = UmbrellaHeader->getDir();
  220. if (Mod->IsFramework)
  221. UmbrellaDir = SourceMgr->getFileManager().getDirectory(
  222. llvm::sys::path::parent_path(UmbrellaDir->getName()));
  223. UmbrellaDirs[UmbrellaDir] = Mod;
  224. }
  225. void ModuleMap::addHeader(Module *Mod, const FileEntry *Header) {
  226. Mod->Headers.push_back(Header);
  227. Headers[Header] = Mod;
  228. }
  229. const FileEntry *
  230. ModuleMap::getContainingModuleMapFile(Module *Module) {
  231. if (Module->DefinitionLoc.isInvalid() || !SourceMgr)
  232. return 0;
  233. return SourceMgr->getFileEntryForID(
  234. SourceMgr->getFileID(Module->DefinitionLoc));
  235. }
  236. void ModuleMap::dump() {
  237. llvm::errs() << "Modules:";
  238. for (llvm::StringMap<Module *>::iterator M = Modules.begin(),
  239. MEnd = Modules.end();
  240. M != MEnd; ++M)
  241. M->getValue()->print(llvm::errs(), 2);
  242. llvm::errs() << "Headers:";
  243. for (llvm::DenseMap<const FileEntry *, Module *>::iterator
  244. H = Headers.begin(),
  245. HEnd = Headers.end();
  246. H != HEnd; ++H) {
  247. llvm::errs() << " \"" << H->first->getName() << "\" -> "
  248. << H->second->getFullModuleName() << "\n";
  249. }
  250. }
  251. bool ModuleMap::resolveExports(Module *Mod, bool Complain) {
  252. bool HadError = false;
  253. for (unsigned I = 0, N = Mod->UnresolvedExports.size(); I != N; ++I) {
  254. Module::ExportDecl Export = resolveExport(Mod, Mod->UnresolvedExports[I],
  255. Complain);
  256. if (Export.getPointer() || Export.getInt())
  257. Mod->Exports.push_back(Export);
  258. else
  259. HadError = true;
  260. }
  261. Mod->UnresolvedExports.clear();
  262. return HadError;
  263. }
  264. Module *ModuleMap::inferModuleFromLocation(FullSourceLoc Loc) {
  265. if (Loc.isInvalid())
  266. return 0;
  267. // Use the expansion location to determine which module we're in.
  268. FullSourceLoc ExpansionLoc = Loc.getExpansionLoc();
  269. if (!ExpansionLoc.isFileID())
  270. return 0;
  271. const SourceManager &SrcMgr = Loc.getManager();
  272. FileID ExpansionFileID = ExpansionLoc.getFileID();
  273. const FileEntry *ExpansionFile = SrcMgr.getFileEntryForID(ExpansionFileID);
  274. if (!ExpansionFile)
  275. return 0;
  276. // Find the module that owns this header.
  277. return findModuleForHeader(ExpansionFile);
  278. }
  279. //----------------------------------------------------------------------------//
  280. // Module map file parser
  281. //----------------------------------------------------------------------------//
  282. namespace clang {
  283. /// \brief A token in a module map file.
  284. struct MMToken {
  285. enum TokenKind {
  286. EndOfFile,
  287. HeaderKeyword,
  288. Identifier,
  289. ExplicitKeyword,
  290. ExportKeyword,
  291. FrameworkKeyword,
  292. ModuleKeyword,
  293. Period,
  294. UmbrellaKeyword,
  295. Star,
  296. StringLiteral,
  297. LBrace,
  298. RBrace
  299. } Kind;
  300. unsigned Location;
  301. unsigned StringLength;
  302. const char *StringData;
  303. void clear() {
  304. Kind = EndOfFile;
  305. Location = 0;
  306. StringLength = 0;
  307. StringData = 0;
  308. }
  309. bool is(TokenKind K) const { return Kind == K; }
  310. SourceLocation getLocation() const {
  311. return SourceLocation::getFromRawEncoding(Location);
  312. }
  313. StringRef getString() const {
  314. return StringRef(StringData, StringLength);
  315. }
  316. };
  317. class ModuleMapParser {
  318. Lexer &L;
  319. SourceManager &SourceMgr;
  320. DiagnosticsEngine &Diags;
  321. ModuleMap &Map;
  322. /// \brief The directory that this module map resides in.
  323. const DirectoryEntry *Directory;
  324. /// \brief Whether an error occurred.
  325. bool HadError;
  326. /// \brief Default target information, used only for string literal
  327. /// parsing.
  328. TargetInfo *Target;
  329. /// \brief Stores string data for the various string literals referenced
  330. /// during parsing.
  331. llvm::BumpPtrAllocator StringData;
  332. /// \brief The current token.
  333. MMToken Tok;
  334. /// \brief The active module.
  335. Module *ActiveModule;
  336. /// \brief Consume the current token and return its location.
  337. SourceLocation consumeToken();
  338. /// \brief Skip tokens until we reach the a token with the given kind
  339. /// (or the end of the file).
  340. void skipUntil(MMToken::TokenKind K);
  341. void parseModuleDecl();
  342. void parseUmbrellaDecl();
  343. void parseHeaderDecl();
  344. void parseExportDecl();
  345. void parseInferredSubmoduleDecl(bool Explicit);
  346. public:
  347. explicit ModuleMapParser(Lexer &L, SourceManager &SourceMgr,
  348. DiagnosticsEngine &Diags,
  349. ModuleMap &Map,
  350. const DirectoryEntry *Directory)
  351. : L(L), SourceMgr(SourceMgr), Diags(Diags), Map(Map),
  352. Directory(Directory), HadError(false), ActiveModule(0)
  353. {
  354. TargetOptions TargetOpts;
  355. TargetOpts.Triple = llvm::sys::getDefaultTargetTriple();
  356. Target = TargetInfo::CreateTargetInfo(Diags, TargetOpts);
  357. Tok.clear();
  358. consumeToken();
  359. }
  360. bool parseModuleMapFile();
  361. };
  362. }
  363. SourceLocation ModuleMapParser::consumeToken() {
  364. retry:
  365. SourceLocation Result = Tok.getLocation();
  366. Tok.clear();
  367. Token LToken;
  368. L.LexFromRawLexer(LToken);
  369. Tok.Location = LToken.getLocation().getRawEncoding();
  370. switch (LToken.getKind()) {
  371. case tok::raw_identifier:
  372. Tok.StringData = LToken.getRawIdentifierData();
  373. Tok.StringLength = LToken.getLength();
  374. Tok.Kind = llvm::StringSwitch<MMToken::TokenKind>(Tok.getString())
  375. .Case("header", MMToken::HeaderKeyword)
  376. .Case("explicit", MMToken::ExplicitKeyword)
  377. .Case("export", MMToken::ExportKeyword)
  378. .Case("framework", MMToken::FrameworkKeyword)
  379. .Case("module", MMToken::ModuleKeyword)
  380. .Case("umbrella", MMToken::UmbrellaKeyword)
  381. .Default(MMToken::Identifier);
  382. break;
  383. case tok::eof:
  384. Tok.Kind = MMToken::EndOfFile;
  385. break;
  386. case tok::l_brace:
  387. Tok.Kind = MMToken::LBrace;
  388. break;
  389. case tok::period:
  390. Tok.Kind = MMToken::Period;
  391. break;
  392. case tok::r_brace:
  393. Tok.Kind = MMToken::RBrace;
  394. break;
  395. case tok::star:
  396. Tok.Kind = MMToken::Star;
  397. break;
  398. case tok::string_literal: {
  399. // Parse the string literal.
  400. LangOptions LangOpts;
  401. StringLiteralParser StringLiteral(&LToken, 1, SourceMgr, LangOpts, *Target);
  402. if (StringLiteral.hadError)
  403. goto retry;
  404. // Copy the string literal into our string data allocator.
  405. unsigned Length = StringLiteral.GetStringLength();
  406. char *Saved = StringData.Allocate<char>(Length + 1);
  407. memcpy(Saved, StringLiteral.GetString().data(), Length);
  408. Saved[Length] = 0;
  409. // Form the token.
  410. Tok.Kind = MMToken::StringLiteral;
  411. Tok.StringData = Saved;
  412. Tok.StringLength = Length;
  413. break;
  414. }
  415. case tok::comment:
  416. goto retry;
  417. default:
  418. Diags.Report(LToken.getLocation(), diag::err_mmap_unknown_token);
  419. HadError = true;
  420. goto retry;
  421. }
  422. return Result;
  423. }
  424. void ModuleMapParser::skipUntil(MMToken::TokenKind K) {
  425. unsigned braceDepth = 0;
  426. do {
  427. switch (Tok.Kind) {
  428. case MMToken::EndOfFile:
  429. return;
  430. case MMToken::LBrace:
  431. if (Tok.is(K) && braceDepth == 0)
  432. return;
  433. ++braceDepth;
  434. break;
  435. case MMToken::RBrace:
  436. if (braceDepth > 0)
  437. --braceDepth;
  438. else if (Tok.is(K))
  439. return;
  440. break;
  441. default:
  442. if (braceDepth == 0 && Tok.is(K))
  443. return;
  444. break;
  445. }
  446. consumeToken();
  447. } while (true);
  448. }
  449. /// \brief Parse a module declaration.
  450. ///
  451. /// module-declaration:
  452. /// 'framework'[opt] 'module' identifier { module-member* }
  453. ///
  454. /// module-member:
  455. /// umbrella-declaration
  456. /// header-declaration
  457. /// 'explicit'[opt] submodule-declaration
  458. /// export-declaration
  459. ///
  460. /// submodule-declaration:
  461. /// module-declaration
  462. /// inferred-submodule-declaration
  463. void ModuleMapParser::parseModuleDecl() {
  464. assert(Tok.is(MMToken::ExplicitKeyword) || Tok.is(MMToken::ModuleKeyword) ||
  465. Tok.is(MMToken::FrameworkKeyword));
  466. // Parse 'explicit' or 'framework' keyword, if present.
  467. bool Explicit = false;
  468. bool Framework = false;
  469. // Parse 'explicit' keyword, if present.
  470. if (Tok.is(MMToken::ExplicitKeyword)) {
  471. consumeToken();
  472. Explicit = true;
  473. }
  474. // Parse 'framework' keyword, if present.
  475. if (Tok.is(MMToken::FrameworkKeyword)) {
  476. consumeToken();
  477. Framework = true;
  478. }
  479. // Parse 'module' keyword.
  480. if (!Tok.is(MMToken::ModuleKeyword)) {
  481. Diags.Report(Tok.getLocation(),
  482. diag::err_mmap_expected_module_after_explicit);
  483. consumeToken();
  484. HadError = true;
  485. return;
  486. }
  487. consumeToken(); // 'module' keyword
  488. // If we have a wildcard for the module name, this is an inferred submodule.
  489. // Parse it.
  490. if (Tok.is(MMToken::Star))
  491. return parseInferredSubmoduleDecl(Explicit);
  492. // Parse the module name.
  493. if (!Tok.is(MMToken::Identifier)) {
  494. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module_name);
  495. HadError = true;
  496. return;
  497. }
  498. StringRef ModuleName = Tok.getString();
  499. SourceLocation ModuleNameLoc = consumeToken();
  500. // Parse the opening brace.
  501. if (!Tok.is(MMToken::LBrace)) {
  502. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_lbrace)
  503. << ModuleName;
  504. HadError = true;
  505. return;
  506. }
  507. SourceLocation LBraceLoc = consumeToken();
  508. // Determine whether this (sub)module has already been defined.
  509. llvm::StringMap<Module *> &ModuleSpace
  510. = ActiveModule? ActiveModule->SubModules : Map.Modules;
  511. llvm::StringMap<Module *>::iterator ExistingModule
  512. = ModuleSpace.find(ModuleName);
  513. if (ExistingModule != ModuleSpace.end()) {
  514. Diags.Report(ModuleNameLoc, diag::err_mmap_module_redefinition)
  515. << ModuleName;
  516. Diags.Report(ExistingModule->getValue()->DefinitionLoc,
  517. diag::note_mmap_prev_definition);
  518. // Skip the module definition.
  519. skipUntil(MMToken::RBrace);
  520. if (Tok.is(MMToken::RBrace))
  521. consumeToken();
  522. HadError = true;
  523. return;
  524. }
  525. // Start defining this module.
  526. ActiveModule = new Module(ModuleName, ModuleNameLoc, ActiveModule, Framework,
  527. Explicit);
  528. ModuleSpace[ModuleName] = ActiveModule;
  529. bool Done = false;
  530. do {
  531. switch (Tok.Kind) {
  532. case MMToken::EndOfFile:
  533. case MMToken::RBrace:
  534. Done = true;
  535. break;
  536. case MMToken::ExplicitKeyword:
  537. case MMToken::FrameworkKeyword:
  538. case MMToken::ModuleKeyword:
  539. parseModuleDecl();
  540. break;
  541. case MMToken::ExportKeyword:
  542. parseExportDecl();
  543. break;
  544. case MMToken::HeaderKeyword:
  545. parseHeaderDecl();
  546. break;
  547. case MMToken::UmbrellaKeyword:
  548. parseUmbrellaDecl();
  549. break;
  550. default:
  551. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_member);
  552. consumeToken();
  553. break;
  554. }
  555. } while (!Done);
  556. if (Tok.is(MMToken::RBrace))
  557. consumeToken();
  558. else {
  559. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
  560. Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
  561. HadError = true;
  562. }
  563. // We're done parsing this module. Pop back to our parent scope.
  564. ActiveModule = ActiveModule->Parent;
  565. }
  566. /// \brief Append to \p Paths the set of paths needed to get to the
  567. /// subframework in which the given module lives.
  568. void appendSubframeworkPaths(Module *Mod, llvm::SmallVectorImpl<char> &Path) {
  569. // Collect the framework names from the given module to the top-level module.
  570. llvm::SmallVector<StringRef, 2> Paths;
  571. for (; Mod; Mod = Mod->Parent) {
  572. if (Mod->IsFramework)
  573. Paths.push_back(Mod->Name);
  574. }
  575. if (Paths.empty())
  576. return;
  577. // Add Frameworks/Name.framework for each subframework.
  578. for (unsigned I = Paths.size() - 1; I != 0; --I) {
  579. llvm::sys::path::append(Path, "Frameworks");
  580. llvm::sys::path::append(Path, Paths[I-1] + ".framework");
  581. }
  582. }
  583. /// \brief Parse an umbrella header declaration.
  584. ///
  585. /// umbrella-declaration:
  586. /// 'umbrella' string-literal
  587. void ModuleMapParser::parseUmbrellaDecl() {
  588. assert(Tok.is(MMToken::UmbrellaKeyword));
  589. SourceLocation UmbrellaLoc = consumeToken();
  590. // Parse the header name.
  591. if (!Tok.is(MMToken::StringLiteral)) {
  592. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
  593. << "umbrella";
  594. HadError = true;
  595. return;
  596. }
  597. StringRef FileName = Tok.getString();
  598. SourceLocation FileNameLoc = consumeToken();
  599. // Check whether we already have an umbrella header.
  600. if (ActiveModule->UmbrellaHeader) {
  601. Diags.Report(FileNameLoc, diag::err_mmap_umbrella_header_conflict)
  602. << ActiveModule->getFullModuleName()
  603. << ActiveModule->UmbrellaHeader->getName();
  604. HadError = true;
  605. return;
  606. }
  607. // Look for this file.
  608. llvm::SmallString<128> PathName;
  609. const FileEntry *File = 0;
  610. if (llvm::sys::path::is_absolute(FileName)) {
  611. PathName = FileName;
  612. File = SourceMgr.getFileManager().getFile(PathName);
  613. } else {
  614. // Search for the header file within the search directory.
  615. PathName += Directory->getName();
  616. unsigned PathLength = PathName.size();
  617. if (ActiveModule->isPartOfFramework()) {
  618. appendSubframeworkPaths(ActiveModule, PathName);
  619. // Check whether this file is in the public headers.
  620. llvm::sys::path::append(PathName, "Headers");
  621. llvm::sys::path::append(PathName, FileName);
  622. File = SourceMgr.getFileManager().getFile(PathName);
  623. if (!File) {
  624. // Check whether this file is in the private headers.
  625. PathName.resize(PathLength);
  626. llvm::sys::path::append(PathName, "PrivateHeaders");
  627. llvm::sys::path::append(PathName, FileName);
  628. File = SourceMgr.getFileManager().getFile(PathName);
  629. }
  630. } else {
  631. // Lookup for normal headers.
  632. llvm::sys::path::append(PathName, FileName);
  633. File = SourceMgr.getFileManager().getFile(PathName);
  634. }
  635. }
  636. // FIXME: We shouldn't be eagerly stat'ing every file named in a module map.
  637. // Come up with a lazy way to do this.
  638. if (File) {
  639. const DirectoryEntry *UmbrellaDir = File->getDir();
  640. if (ActiveModule->IsFramework) {
  641. // For framework modules, use the framework directory as the umbrella
  642. // directory.
  643. UmbrellaDir = SourceMgr.getFileManager().getDirectory(
  644. llvm::sys::path::parent_path(UmbrellaDir->getName()));
  645. }
  646. if (const Module *OwningModule = Map.Headers[File]) {
  647. Diags.Report(FileNameLoc, diag::err_mmap_header_conflict)
  648. << FileName << OwningModule->getFullModuleName();
  649. HadError = true;
  650. } else if ((OwningModule = Map.UmbrellaDirs[UmbrellaDir])) {
  651. Diags.Report(UmbrellaLoc, diag::err_mmap_umbrella_clash)
  652. << OwningModule->getFullModuleName();
  653. HadError = true;
  654. } else {
  655. // Record this umbrella header.
  656. Map.setUmbrellaHeader(ActiveModule, File);
  657. }
  658. } else {
  659. Diags.Report(FileNameLoc, diag::err_mmap_header_not_found)
  660. << true << FileName;
  661. HadError = true;
  662. }
  663. }
  664. /// \brief Parse a header declaration.
  665. ///
  666. /// header-declaration:
  667. /// 'header' string-literal
  668. void ModuleMapParser::parseHeaderDecl() {
  669. assert(Tok.is(MMToken::HeaderKeyword));
  670. consumeToken();
  671. // Parse the header name.
  672. if (!Tok.is(MMToken::StringLiteral)) {
  673. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
  674. << "header";
  675. HadError = true;
  676. return;
  677. }
  678. StringRef FileName = Tok.getString();
  679. SourceLocation FileNameLoc = consumeToken();
  680. // Look for this file.
  681. llvm::SmallString<128> PathName;
  682. if (llvm::sys::path::is_relative(FileName)) {
  683. // FIXME: Change this search to also look for private headers!
  684. PathName += Directory->getName();
  685. if (ActiveModule->isPartOfFramework()) {
  686. appendSubframeworkPaths(ActiveModule, PathName);
  687. llvm::sys::path::append(PathName, "Headers");
  688. }
  689. }
  690. llvm::sys::path::append(PathName, FileName);
  691. // FIXME: We shouldn't be eagerly stat'ing every file named in a module map.
  692. // Come up with a lazy way to do this.
  693. if (const FileEntry *File = SourceMgr.getFileManager().getFile(PathName)) {
  694. if (const Module *OwningModule = Map.Headers[File]) {
  695. Diags.Report(FileNameLoc, diag::err_mmap_header_conflict)
  696. << FileName << OwningModule->getFullModuleName();
  697. HadError = true;
  698. } else {
  699. // Record this file.
  700. Map.addHeader(ActiveModule, File);
  701. }
  702. } else {
  703. Diags.Report(FileNameLoc, diag::err_mmap_header_not_found)
  704. << false << FileName;
  705. HadError = true;
  706. }
  707. }
  708. /// \brief Parse a module export declaration.
  709. ///
  710. /// export-declaration:
  711. /// 'export' wildcard-module-id
  712. ///
  713. /// wildcard-module-id:
  714. /// identifier
  715. /// '*'
  716. /// identifier '.' wildcard-module-id
  717. void ModuleMapParser::parseExportDecl() {
  718. assert(Tok.is(MMToken::ExportKeyword));
  719. SourceLocation ExportLoc = consumeToken();
  720. // Parse the module-id with an optional wildcard at the end.
  721. ModuleId ParsedModuleId;
  722. bool Wildcard = false;
  723. do {
  724. if (Tok.is(MMToken::Identifier)) {
  725. ParsedModuleId.push_back(std::make_pair(Tok.getString(),
  726. Tok.getLocation()));
  727. consumeToken();
  728. if (Tok.is(MMToken::Period)) {
  729. consumeToken();
  730. continue;
  731. }
  732. break;
  733. }
  734. if(Tok.is(MMToken::Star)) {
  735. Wildcard = true;
  736. consumeToken();
  737. break;
  738. }
  739. Diags.Report(Tok.getLocation(), diag::err_mmap_export_module_id);
  740. HadError = true;
  741. return;
  742. } while (true);
  743. Module::UnresolvedExportDecl Unresolved = {
  744. ExportLoc, ParsedModuleId, Wildcard
  745. };
  746. ActiveModule->UnresolvedExports.push_back(Unresolved);
  747. }
  748. void ModuleMapParser::parseInferredSubmoduleDecl(bool Explicit) {
  749. assert(Tok.is(MMToken::Star));
  750. SourceLocation StarLoc = consumeToken();
  751. bool Failed = false;
  752. // Inferred modules must be submodules.
  753. if (!ActiveModule) {
  754. Diags.Report(StarLoc, diag::err_mmap_top_level_inferred_submodule);
  755. Failed = true;
  756. }
  757. // Inferred modules must have umbrella headers.
  758. if (!Failed && !ActiveModule->getTopLevelModule()->UmbrellaHeader) {
  759. Diags.Report(StarLoc, diag::err_mmap_inferred_no_umbrella);
  760. Failed = true;
  761. }
  762. // Check for redefinition of an inferred module.
  763. if (!Failed && ActiveModule->getTopLevelModule()->InferSubmodules) {
  764. Diags.Report(StarLoc, diag::err_mmap_inferred_redef);
  765. if (ActiveModule->getTopLevelModule()->InferredSubmoduleLoc.isValid())
  766. Diags.Report(ActiveModule->getTopLevelModule()->InferredSubmoduleLoc,
  767. diag::note_mmap_prev_definition);
  768. Failed = true;
  769. }
  770. // If there were any problems with this inferred submodule, skip its body.
  771. if (Failed) {
  772. if (Tok.is(MMToken::LBrace)) {
  773. consumeToken();
  774. skipUntil(MMToken::RBrace);
  775. if (Tok.is(MMToken::RBrace))
  776. consumeToken();
  777. }
  778. HadError = true;
  779. return;
  780. }
  781. // Note that we have an inferred submodule.
  782. Module *TopModule = ActiveModule->getTopLevelModule();
  783. TopModule->InferSubmodules = true;
  784. TopModule->InferredSubmoduleLoc = StarLoc;
  785. TopModule->InferExplicitSubmodules = Explicit;
  786. // Parse the opening brace.
  787. if (!Tok.is(MMToken::LBrace)) {
  788. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_lbrace_wildcard);
  789. HadError = true;
  790. return;
  791. }
  792. SourceLocation LBraceLoc = consumeToken();
  793. // Parse the body of the inferred submodule.
  794. bool Done = false;
  795. do {
  796. switch (Tok.Kind) {
  797. case MMToken::EndOfFile:
  798. case MMToken::RBrace:
  799. Done = true;
  800. break;
  801. case MMToken::ExportKeyword: {
  802. consumeToken();
  803. if (Tok.is(MMToken::Star))
  804. TopModule->InferExportWildcard = true;
  805. else
  806. Diags.Report(Tok.getLocation(),
  807. diag::err_mmap_expected_export_wildcard);
  808. consumeToken();
  809. break;
  810. }
  811. case MMToken::ExplicitKeyword:
  812. case MMToken::ModuleKeyword:
  813. case MMToken::HeaderKeyword:
  814. case MMToken::UmbrellaKeyword:
  815. default:
  816. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_wildcard_member);
  817. consumeToken();
  818. break;
  819. }
  820. } while (!Done);
  821. if (Tok.is(MMToken::RBrace))
  822. consumeToken();
  823. else {
  824. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
  825. Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
  826. HadError = true;
  827. }
  828. }
  829. /// \brief Parse a module map file.
  830. ///
  831. /// module-map-file:
  832. /// module-declaration*
  833. bool ModuleMapParser::parseModuleMapFile() {
  834. do {
  835. switch (Tok.Kind) {
  836. case MMToken::EndOfFile:
  837. return HadError;
  838. case MMToken::ModuleKeyword:
  839. case MMToken::FrameworkKeyword:
  840. parseModuleDecl();
  841. break;
  842. case MMToken::ExplicitKeyword:
  843. case MMToken::ExportKeyword:
  844. case MMToken::HeaderKeyword:
  845. case MMToken::Identifier:
  846. case MMToken::LBrace:
  847. case MMToken::Period:
  848. case MMToken::RBrace:
  849. case MMToken::Star:
  850. case MMToken::StringLiteral:
  851. case MMToken::UmbrellaKeyword:
  852. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module);
  853. HadError = true;
  854. consumeToken();
  855. break;
  856. }
  857. } while (true);
  858. return HadError;
  859. }
  860. bool ModuleMap::parseModuleMapFile(const FileEntry *File) {
  861. FileID ID = SourceMgr->createFileID(File, SourceLocation(), SrcMgr::C_User);
  862. const llvm::MemoryBuffer *Buffer = SourceMgr->getBuffer(ID);
  863. if (!Buffer)
  864. return true;
  865. // Parse this module map file.
  866. Lexer L(ID, SourceMgr->getBuffer(ID), *SourceMgr, LangOpts);
  867. Diags->getClient()->BeginSourceFile(LangOpts);
  868. ModuleMapParser Parser(L, *SourceMgr, *Diags, *this, File->getDir());
  869. bool Result = Parser.parseModuleMapFile();
  870. Diags->getClient()->EndSourceFile();
  871. return Result;
  872. }