ModuleMap.cpp 38 KB

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