ModuleMap.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  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. //----------------------------------------------------------------------------//
  30. // Module
  31. //----------------------------------------------------------------------------//
  32. std::string ModuleMap::Module::getFullModuleName() const {
  33. llvm::SmallVector<StringRef, 2> Names;
  34. // Build up the set of module names (from innermost to outermost).
  35. for (const Module *M = this; M; M = M->Parent)
  36. Names.push_back(M->Name);
  37. std::string Result;
  38. for (llvm::SmallVector<StringRef, 2>::reverse_iterator I = Names.rbegin(),
  39. IEnd = Names.rend();
  40. I != IEnd; ++I) {
  41. if (!Result.empty())
  42. Result += '.';
  43. Result += *I;
  44. }
  45. return Result;
  46. }
  47. StringRef ModuleMap::Module::getTopLevelModuleName() const {
  48. const Module *Top = this;
  49. while (Top->Parent)
  50. Top = Top->Parent;
  51. return Top->Name;
  52. }
  53. //----------------------------------------------------------------------------//
  54. // Module map
  55. //----------------------------------------------------------------------------//
  56. ModuleMap::ModuleMap(FileManager &FileMgr, const DiagnosticConsumer &DC) {
  57. llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(new DiagnosticIDs);
  58. Diags = llvm::IntrusiveRefCntPtr<DiagnosticsEngine>(
  59. new DiagnosticsEngine(DiagIDs));
  60. Diags->setClient(DC.clone(*Diags), /*ShouldOwnClient=*/true);
  61. SourceMgr = new SourceManager(*Diags, FileMgr);
  62. }
  63. ModuleMap::~ModuleMap() {
  64. delete SourceMgr;
  65. }
  66. ModuleMap::Module *ModuleMap::findModuleForHeader(const FileEntry *File) {
  67. llvm::DenseMap<const FileEntry *, Module *>::iterator Known
  68. = Headers.find(File);
  69. if (Known != Headers.end())
  70. return Known->second;
  71. return 0;
  72. }
  73. ModuleMap::Module *ModuleMap::findModule(StringRef Name) {
  74. llvm::StringMap<Module *>::iterator Known = Modules.find(Name);
  75. if (Known != Modules.end())
  76. return Known->getValue();
  77. return 0;
  78. }
  79. static void indent(llvm::raw_ostream &OS, unsigned Spaces) {
  80. OS << std::string(' ', Spaces);
  81. }
  82. static void dumpModule(llvm::raw_ostream &OS, ModuleMap::Module *M,
  83. unsigned Indent) {
  84. indent(OS, Indent);
  85. if (M->IsExplicit)
  86. OS << "explicit ";
  87. OS << M->Name << " {\n";
  88. if (M->UmbrellaHeader) {
  89. indent(OS, Indent + 2);
  90. OS << "umbrella \"" << M->UmbrellaHeader->getName() << "\"\n";
  91. }
  92. for (unsigned I = 0, N = M->Headers.size(); I != N; ++I) {
  93. indent(OS, Indent + 2);
  94. OS << "header \"" << M->Headers[I]->getName() << "\"\n";
  95. }
  96. for (llvm::StringMap<ModuleMap::Module *>::iterator
  97. MI = M->SubModules.begin(),
  98. MIEnd = M->SubModules.end();
  99. MI != MIEnd; ++MI)
  100. dumpModule(llvm::errs(), MI->getValue(), Indent + 2);
  101. indent(OS, Indent);
  102. OS << "}\n";
  103. }
  104. void ModuleMap::dump() {
  105. llvm::errs() << "Modules:";
  106. for (llvm::StringMap<Module *>::iterator M = Modules.begin(),
  107. MEnd = Modules.end();
  108. M != MEnd; ++M)
  109. dumpModule(llvm::errs(), M->getValue(), 2);
  110. llvm::errs() << "Headers:";
  111. for (llvm::DenseMap<const FileEntry *, Module *>::iterator
  112. H = Headers.begin(),
  113. HEnd = Headers.end();
  114. H != HEnd; ++H) {
  115. llvm::errs() << " \"" << H->first->getName() << "\" -> "
  116. << H->second->getFullModuleName() << "\n";
  117. }
  118. }
  119. //----------------------------------------------------------------------------//
  120. // Module map file parser
  121. //----------------------------------------------------------------------------//
  122. namespace clang {
  123. /// \brief A token in a module map file.
  124. struct MMToken {
  125. enum TokenKind {
  126. EndOfFile,
  127. HeaderKeyword,
  128. Identifier,
  129. ExplicitKeyword,
  130. ModuleKeyword,
  131. UmbrellaKeyword,
  132. StringLiteral,
  133. LBrace,
  134. RBrace
  135. } Kind;
  136. unsigned Location;
  137. unsigned StringLength;
  138. const char *StringData;
  139. void clear() {
  140. Kind = EndOfFile;
  141. Location = 0;
  142. StringLength = 0;
  143. StringData = 0;
  144. }
  145. bool is(TokenKind K) const { return Kind == K; }
  146. SourceLocation getLocation() const {
  147. return SourceLocation::getFromRawEncoding(Location);
  148. }
  149. StringRef getString() const {
  150. return StringRef(StringData, StringLength);
  151. }
  152. };
  153. class ModuleMapParser {
  154. Lexer &L;
  155. SourceManager &SourceMgr;
  156. DiagnosticsEngine &Diags;
  157. ModuleMap &Map;
  158. /// \brief The directory that this module map resides in.
  159. const DirectoryEntry *Directory;
  160. /// \brief Whether an error occurred.
  161. bool HadError;
  162. /// \brief Default target information, used only for string literal
  163. /// parsing.
  164. TargetInfo *Target;
  165. /// \brief Stores string data for the various string literals referenced
  166. /// during parsing.
  167. llvm::BumpPtrAllocator StringData;
  168. /// \brief The current token.
  169. MMToken Tok;
  170. /// \brief The active module.
  171. ModuleMap::Module *ActiveModule;
  172. /// \brief Consume the current token and return its location.
  173. SourceLocation consumeToken();
  174. /// \brief Skip tokens until we reach the a token with the given kind
  175. /// (or the end of the file).
  176. void skipUntil(MMToken::TokenKind K);
  177. void parseModuleDecl();
  178. void parseUmbrellaDecl();
  179. void parseHeaderDecl();
  180. public:
  181. typedef ModuleMap::Module Module;
  182. explicit ModuleMapParser(Lexer &L, SourceManager &SourceMgr,
  183. DiagnosticsEngine &Diags,
  184. ModuleMap &Map,
  185. const DirectoryEntry *Directory)
  186. : L(L), SourceMgr(SourceMgr), Diags(Diags), Map(Map),
  187. Directory(Directory), HadError(false), ActiveModule(0)
  188. {
  189. TargetOptions TargetOpts;
  190. TargetOpts.Triple = llvm::sys::getDefaultTargetTriple();
  191. Target = TargetInfo::CreateTargetInfo(Diags, TargetOpts);
  192. Tok.clear();
  193. consumeToken();
  194. }
  195. bool parseModuleMapFile();
  196. };
  197. }
  198. SourceLocation ModuleMapParser::consumeToken() {
  199. retry:
  200. SourceLocation Result = Tok.getLocation();
  201. Tok.clear();
  202. Token LToken;
  203. L.LexFromRawLexer(LToken);
  204. Tok.Location = LToken.getLocation().getRawEncoding();
  205. switch (LToken.getKind()) {
  206. case tok::raw_identifier:
  207. Tok.StringData = LToken.getRawIdentifierData();
  208. Tok.StringLength = LToken.getLength();
  209. Tok.Kind = llvm::StringSwitch<MMToken::TokenKind>(Tok.getString())
  210. .Case("header", MMToken::HeaderKeyword)
  211. .Case("explicit", MMToken::ExplicitKeyword)
  212. .Case("module", MMToken::ModuleKeyword)
  213. .Case("umbrella", MMToken::UmbrellaKeyword)
  214. .Default(MMToken::Identifier);
  215. break;
  216. case tok::eof:
  217. Tok.Kind = MMToken::EndOfFile;
  218. break;
  219. case tok::l_brace:
  220. Tok.Kind = MMToken::LBrace;
  221. break;
  222. case tok::r_brace:
  223. Tok.Kind = MMToken::RBrace;
  224. break;
  225. case tok::string_literal: {
  226. // Parse the string literal.
  227. LangOptions LangOpts;
  228. StringLiteralParser StringLiteral(&LToken, 1, SourceMgr, LangOpts, *Target);
  229. if (StringLiteral.hadError)
  230. goto retry;
  231. // Copy the string literal into our string data allocator.
  232. unsigned Length = StringLiteral.GetStringLength();
  233. char *Saved = StringData.Allocate<char>(Length + 1);
  234. memcpy(Saved, StringLiteral.GetString().data(), Length);
  235. Saved[Length] = 0;
  236. // Form the token.
  237. Tok.Kind = MMToken::StringLiteral;
  238. Tok.StringData = Saved;
  239. Tok.StringLength = Length;
  240. break;
  241. }
  242. case tok::comment:
  243. goto retry;
  244. default:
  245. Diags.Report(LToken.getLocation(), diag::err_mmap_unknown_token);
  246. HadError = true;
  247. goto retry;
  248. }
  249. return Result;
  250. }
  251. void ModuleMapParser::skipUntil(MMToken::TokenKind K) {
  252. unsigned braceDepth = 0;
  253. do {
  254. switch (Tok.Kind) {
  255. case MMToken::EndOfFile:
  256. return;
  257. case MMToken::LBrace:
  258. if (Tok.is(K) && braceDepth == 0)
  259. return;
  260. ++braceDepth;
  261. break;
  262. case MMToken::RBrace:
  263. if (braceDepth > 0)
  264. --braceDepth;
  265. else if (Tok.is(K))
  266. return;
  267. break;
  268. default:
  269. if (braceDepth == 0 && Tok.is(K))
  270. return;
  271. break;
  272. }
  273. consumeToken();
  274. } while (true);
  275. }
  276. /// \brief Parse a module declaration.
  277. ///
  278. /// module-declaration:
  279. /// 'module' identifier { module-member* }
  280. ///
  281. /// module-member:
  282. /// umbrella-declaration
  283. /// header-declaration
  284. /// 'explicit'[opt] module-declaration
  285. void ModuleMapParser::parseModuleDecl() {
  286. assert(Tok.is(MMToken::ExplicitKeyword) || Tok.is(MMToken::ModuleKeyword));
  287. // Parse 'explicit' keyword, if present.
  288. bool Explicit = false;
  289. if (Tok.is(MMToken::ExplicitKeyword)) {
  290. consumeToken();
  291. Explicit = true;
  292. }
  293. // Parse 'module' keyword.
  294. if (!Tok.is(MMToken::ModuleKeyword)) {
  295. Diags.Report(Tok.getLocation(),
  296. diag::err_mmap_expected_module_after_explicit);
  297. consumeToken();
  298. HadError = true;
  299. return;
  300. }
  301. consumeToken(); // 'module' keyword
  302. // Parse the module name.
  303. if (!Tok.is(MMToken::Identifier)) {
  304. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module_name);
  305. HadError = true;
  306. return;
  307. }
  308. StringRef ModuleName = Tok.getString();
  309. SourceLocation ModuleNameLoc = consumeToken();
  310. // Parse the opening brace.
  311. if (!Tok.is(MMToken::LBrace)) {
  312. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_lbrace)
  313. << ModuleName;
  314. HadError = true;
  315. return;
  316. }
  317. SourceLocation LBraceLoc = consumeToken();
  318. // Determine whether this (sub)module has already been defined.
  319. llvm::StringMap<Module *> &ModuleSpace
  320. = ActiveModule? ActiveModule->SubModules : Map.Modules;
  321. llvm::StringMap<Module *>::iterator ExistingModule
  322. = ModuleSpace.find(ModuleName);
  323. if (ExistingModule != ModuleSpace.end()) {
  324. Diags.Report(ModuleNameLoc, diag::err_mmap_module_redefinition)
  325. << ModuleName;
  326. Diags.Report(ExistingModule->getValue()->DefinitionLoc,
  327. diag::note_mmap_prev_definition);
  328. // Skip the module definition.
  329. skipUntil(MMToken::RBrace);
  330. if (Tok.is(MMToken::RBrace))
  331. consumeToken();
  332. HadError = true;
  333. return;
  334. }
  335. // Start defining this module.
  336. ActiveModule = new Module(ModuleName, ModuleNameLoc, ActiveModule, Explicit);
  337. ModuleSpace[ModuleName] = ActiveModule;
  338. bool Done = false;
  339. do {
  340. switch (Tok.Kind) {
  341. case MMToken::EndOfFile:
  342. case MMToken::RBrace:
  343. Done = true;
  344. break;
  345. case MMToken::ExplicitKeyword:
  346. case MMToken::ModuleKeyword:
  347. parseModuleDecl();
  348. break;
  349. case MMToken::HeaderKeyword:
  350. parseHeaderDecl();
  351. break;
  352. case MMToken::UmbrellaKeyword:
  353. parseUmbrellaDecl();
  354. break;
  355. default:
  356. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_member);
  357. consumeToken();
  358. break;
  359. }
  360. } while (!Done);
  361. if (Tok.is(MMToken::RBrace))
  362. consumeToken();
  363. else {
  364. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
  365. Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
  366. HadError = true;
  367. }
  368. // We're done parsing this module. Pop back to our parent scope.
  369. ActiveModule = ActiveModule->Parent;
  370. }
  371. /// \brief Parse an umbrella header declaration.
  372. ///
  373. /// umbrella-declaration:
  374. /// 'umbrella' string-literal
  375. void ModuleMapParser::parseUmbrellaDecl() {
  376. assert(Tok.is(MMToken::UmbrellaKeyword));
  377. SourceLocation UmbrellaLoc = consumeToken();
  378. // Parse the header name.
  379. if (!Tok.is(MMToken::StringLiteral)) {
  380. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
  381. << "umbrella";
  382. HadError = true;
  383. return;
  384. }
  385. StringRef FileName = Tok.getString();
  386. SourceLocation FileNameLoc = consumeToken();
  387. // Check whether we already have an umbrella header.
  388. if (ActiveModule->UmbrellaHeader) {
  389. Diags.Report(FileNameLoc, diag::err_mmap_umbrella_header_conflict)
  390. << ActiveModule->getFullModuleName()
  391. << ActiveModule->UmbrellaHeader->getName();
  392. HadError = true;
  393. return;
  394. }
  395. // Only top-level modules can have umbrella headers.
  396. if (ActiveModule->Parent) {
  397. Diags.Report(UmbrellaLoc, diag::err_mmap_umbrella_header_submodule)
  398. << ActiveModule->getFullModuleName();
  399. HadError = true;
  400. return;
  401. }
  402. // Look for this file.
  403. llvm::SmallString<128> PathName;
  404. PathName += Directory->getName();
  405. llvm::sys::path::append(PathName, FileName);
  406. // FIXME: We shouldn't be eagerly stat'ing every file named in a module map.
  407. // Come up with a lazy way to do this.
  408. if (const FileEntry *File = SourceMgr.getFileManager().getFile(PathName)) {
  409. if (const Module *OwningModule = Map.Headers[File]) {
  410. Diags.Report(FileNameLoc, diag::err_mmap_header_conflict)
  411. << FileName << OwningModule->getFullModuleName();
  412. HadError = true;
  413. } else {
  414. // Record this umbrella header.
  415. ActiveModule->UmbrellaHeader = File;
  416. Map.Headers[File] = ActiveModule;
  417. }
  418. } else {
  419. Diags.Report(FileNameLoc, diag::err_mmap_header_not_found)
  420. << true << FileName;
  421. HadError = true;
  422. }
  423. }
  424. /// \brief Parse a header declaration.
  425. ///
  426. /// header-declaration:
  427. /// 'header' string-literal
  428. void ModuleMapParser::parseHeaderDecl() {
  429. assert(Tok.is(MMToken::HeaderKeyword));
  430. consumeToken();
  431. // Parse the header name.
  432. if (!Tok.is(MMToken::StringLiteral)) {
  433. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
  434. << "header";
  435. HadError = true;
  436. return;
  437. }
  438. StringRef FileName = Tok.getString();
  439. SourceLocation FileNameLoc = consumeToken();
  440. // Look for this file.
  441. llvm::SmallString<128> PathName;
  442. PathName += Directory->getName();
  443. llvm::sys::path::append(PathName, FileName);
  444. // FIXME: We shouldn't be eagerly stat'ing every file named in a module map.
  445. // Come up with a lazy way to do this.
  446. if (const FileEntry *File = SourceMgr.getFileManager().getFile(PathName)) {
  447. if (const Module *OwningModule = Map.Headers[File]) {
  448. Diags.Report(FileNameLoc, diag::err_mmap_header_conflict)
  449. << FileName << OwningModule->getFullModuleName();
  450. HadError = true;
  451. } else {
  452. // Record this file.
  453. ActiveModule->Headers.push_back(File);
  454. Map.Headers[File] = ActiveModule;
  455. }
  456. } else {
  457. Diags.Report(FileNameLoc, diag::err_mmap_header_not_found)
  458. << false << FileName;
  459. HadError = true;
  460. }
  461. }
  462. /// \brief Parse a module map file.
  463. ///
  464. /// module-map-file:
  465. /// module-declaration*
  466. bool ModuleMapParser::parseModuleMapFile() {
  467. do {
  468. switch (Tok.Kind) {
  469. case MMToken::EndOfFile:
  470. return HadError;
  471. case MMToken::ModuleKeyword:
  472. parseModuleDecl();
  473. break;
  474. case MMToken::ExplicitKeyword:
  475. case MMToken::HeaderKeyword:
  476. case MMToken::Identifier:
  477. case MMToken::LBrace:
  478. case MMToken::RBrace:
  479. case MMToken::StringLiteral:
  480. case MMToken::UmbrellaKeyword:
  481. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module);
  482. HadError = true;
  483. consumeToken();
  484. break;
  485. }
  486. } while (true);
  487. return HadError;
  488. }
  489. bool ModuleMap::parseModuleMapFile(const FileEntry *File) {
  490. FileID ID = SourceMgr->createFileID(File, SourceLocation(), SrcMgr::C_User);
  491. const llvm::MemoryBuffer *Buffer = SourceMgr->getBuffer(ID);
  492. if (!Buffer)
  493. return true;
  494. // Parse this module map file.
  495. Lexer L(ID, SourceMgr->getBuffer(ID), *SourceMgr, LangOpts);
  496. Diags->getClient()->BeginSourceFile(LangOpts);
  497. ModuleMapParser Parser(L, *SourceMgr, *Diags, *this, File->getDir());
  498. bool Result = Parser.parseModuleMapFile();
  499. Diags->getClient()->EndSourceFile();
  500. return Result;
  501. }