ModuleMap.cpp 34 KB

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