ModuleMap.cpp 36 KB

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