ModuleMap.cpp 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697
  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/Basic/Diagnostic.h"
  16. #include "clang/Basic/DiagnosticOptions.h"
  17. #include "clang/Basic/FileManager.h"
  18. #include "clang/Basic/TargetInfo.h"
  19. #include "clang/Basic/TargetOptions.h"
  20. #include "clang/Lex/LexDiagnostic.h"
  21. #include "clang/Lex/Lexer.h"
  22. #include "clang/Lex/LiteralSupport.h"
  23. #include "llvm/ADT/StringRef.h"
  24. #include "llvm/ADT/StringSwitch.h"
  25. #include "llvm/Support/Allocator.h"
  26. #include "llvm/Support/FileSystem.h"
  27. #include "llvm/Support/Host.h"
  28. #include "llvm/Support/PathV2.h"
  29. #include "llvm/Support/raw_ostream.h"
  30. #include <stdlib.h>
  31. using namespace clang;
  32. Module::ExportDecl
  33. ModuleMap::resolveExport(Module *Mod,
  34. const Module::UnresolvedExportDecl &Unresolved,
  35. bool Complain) {
  36. // We may have just a wildcard.
  37. if (Unresolved.Id.empty()) {
  38. assert(Unresolved.Wildcard && "Invalid unresolved export");
  39. return Module::ExportDecl(0, true);
  40. }
  41. // Find the starting module.
  42. Module *Context = lookupModuleUnqualified(Unresolved.Id[0].first, Mod);
  43. if (!Context) {
  44. if (Complain)
  45. Diags->Report(Unresolved.Id[0].second,
  46. diag::err_mmap_missing_module_unqualified)
  47. << Unresolved.Id[0].first << Mod->getFullModuleName();
  48. return Module::ExportDecl();
  49. }
  50. // Dig into the module path.
  51. for (unsigned I = 1, N = Unresolved.Id.size(); I != N; ++I) {
  52. Module *Sub = lookupModuleQualified(Unresolved.Id[I].first,
  53. Context);
  54. if (!Sub) {
  55. if (Complain)
  56. Diags->Report(Unresolved.Id[I].second,
  57. diag::err_mmap_missing_module_qualified)
  58. << Unresolved.Id[I].first << Context->getFullModuleName()
  59. << SourceRange(Unresolved.Id[0].second, Unresolved.Id[I-1].second);
  60. return Module::ExportDecl();
  61. }
  62. Context = Sub;
  63. }
  64. return Module::ExportDecl(Context, Unresolved.Wildcard);
  65. }
  66. ModuleMap::ModuleMap(FileManager &FileMgr, const DiagnosticConsumer &DC,
  67. const LangOptions &LangOpts, const TargetInfo *Target)
  68. : LangOpts(LangOpts), Target(Target), BuiltinIncludeDir(0)
  69. {
  70. IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(new DiagnosticIDs);
  71. Diags = IntrusiveRefCntPtr<DiagnosticsEngine>(
  72. new DiagnosticsEngine(DiagIDs, new DiagnosticOptions));
  73. Diags->setClient(DC.clone(*Diags), /*ShouldOwnClient=*/true);
  74. SourceMgr = new SourceManager(*Diags, FileMgr);
  75. }
  76. ModuleMap::~ModuleMap() {
  77. for (llvm::StringMap<Module *>::iterator I = Modules.begin(),
  78. IEnd = Modules.end();
  79. I != IEnd; ++I) {
  80. delete I->getValue();
  81. }
  82. delete SourceMgr;
  83. }
  84. void ModuleMap::setTarget(const TargetInfo &Target) {
  85. assert((!this->Target || this->Target == &Target) &&
  86. "Improper target override");
  87. this->Target = &Target;
  88. }
  89. /// \brief "Sanitize" a filename so that it can be used as an identifier.
  90. static StringRef sanitizeFilenameAsIdentifier(StringRef Name,
  91. SmallVectorImpl<char> &Buffer) {
  92. if (Name.empty())
  93. return Name;
  94. // Check whether the filename is already an identifier; this is the common
  95. // case.
  96. bool isIdentifier = true;
  97. for (unsigned I = 0, N = Name.size(); I != N; ++I) {
  98. if (isalpha(Name[I]) || Name[I] == '_' || (isdigit(Name[I]) && I > 0))
  99. continue;
  100. isIdentifier = false;
  101. break;
  102. }
  103. if (!isIdentifier) {
  104. // If we don't already have something with the form of an identifier,
  105. // create a buffer with the sanitized name.
  106. Buffer.clear();
  107. if (isdigit(Name[0]))
  108. Buffer.push_back('_');
  109. Buffer.reserve(Buffer.size() + Name.size());
  110. for (unsigned I = 0, N = Name.size(); I != N; ++I) {
  111. if (isalnum(Name[I]) || isspace(Name[I]))
  112. Buffer.push_back(Name[I]);
  113. else
  114. Buffer.push_back('_');
  115. }
  116. Name = StringRef(Buffer.data(), Buffer.size());
  117. }
  118. while (llvm::StringSwitch<bool>(Name)
  119. #define KEYWORD(Keyword,Conditions) .Case(#Keyword, true)
  120. #define ALIAS(Keyword, AliasOf, Conditions) .Case(Keyword, true)
  121. #include "clang/Basic/TokenKinds.def"
  122. .Default(false)) {
  123. if (Name.data() != Buffer.data())
  124. Buffer.append(Name.begin(), Name.end());
  125. Buffer.push_back('_');
  126. Name = StringRef(Buffer.data(), Buffer.size());
  127. }
  128. return Name;
  129. }
  130. Module *ModuleMap::findModuleForHeader(const FileEntry *File) {
  131. HeadersMap::iterator Known = Headers.find(File);
  132. if (Known != Headers.end()) {
  133. // If a header is not available, don't report that it maps to anything.
  134. if (!Known->second.isAvailable())
  135. return 0;
  136. return Known->second.getModule();
  137. }
  138. const DirectoryEntry *Dir = File->getDir();
  139. llvm::SmallVector<const DirectoryEntry *, 2> SkippedDirs;
  140. StringRef DirName = Dir->getName();
  141. // Keep walking up the directory hierarchy, looking for a directory with
  142. // an umbrella header.
  143. do {
  144. llvm::DenseMap<const DirectoryEntry *, Module *>::iterator KnownDir
  145. = UmbrellaDirs.find(Dir);
  146. if (KnownDir != UmbrellaDirs.end()) {
  147. Module *Result = KnownDir->second;
  148. // Search up the module stack until we find a module with an umbrella
  149. // directory.
  150. Module *UmbrellaModule = Result;
  151. while (!UmbrellaModule->getUmbrellaDir() && UmbrellaModule->Parent)
  152. UmbrellaModule = UmbrellaModule->Parent;
  153. if (UmbrellaModule->InferSubmodules) {
  154. // Infer submodules for each of the directories we found between
  155. // the directory of the umbrella header and the directory where
  156. // the actual header is located.
  157. bool Explicit = UmbrellaModule->InferExplicitSubmodules;
  158. for (unsigned I = SkippedDirs.size(); I != 0; --I) {
  159. // Find or create the module that corresponds to this directory name.
  160. SmallString<32> NameBuf;
  161. StringRef Name = sanitizeFilenameAsIdentifier(
  162. llvm::sys::path::stem(SkippedDirs[I-1]->getName()),
  163. NameBuf);
  164. Result = findOrCreateModule(Name, Result, /*IsFramework=*/false,
  165. Explicit).first;
  166. // Associate the module and the directory.
  167. UmbrellaDirs[SkippedDirs[I-1]] = Result;
  168. // If inferred submodules export everything they import, add a
  169. // wildcard to the set of exports.
  170. if (UmbrellaModule->InferExportWildcard && Result->Exports.empty())
  171. Result->Exports.push_back(Module::ExportDecl(0, true));
  172. }
  173. // Infer a submodule with the same name as this header file.
  174. SmallString<32> NameBuf;
  175. StringRef Name = sanitizeFilenameAsIdentifier(
  176. llvm::sys::path::stem(File->getName()), NameBuf);
  177. Result = findOrCreateModule(Name, Result, /*IsFramework=*/false,
  178. Explicit).first;
  179. Result->TopHeaders.insert(File);
  180. // If inferred submodules export everything they import, add a
  181. // wildcard to the set of exports.
  182. if (UmbrellaModule->InferExportWildcard && Result->Exports.empty())
  183. Result->Exports.push_back(Module::ExportDecl(0, true));
  184. } else {
  185. // Record each of the directories we stepped through as being part of
  186. // the module we found, since the umbrella header covers them all.
  187. for (unsigned I = 0, N = SkippedDirs.size(); I != N; ++I)
  188. UmbrellaDirs[SkippedDirs[I]] = Result;
  189. }
  190. Headers[File] = KnownHeader(Result, /*Excluded=*/false);
  191. // If a header corresponds to an unavailable module, don't report
  192. // that it maps to anything.
  193. if (!Result->isAvailable())
  194. return 0;
  195. return Result;
  196. }
  197. SkippedDirs.push_back(Dir);
  198. // Retrieve our parent path.
  199. DirName = llvm::sys::path::parent_path(DirName);
  200. if (DirName.empty())
  201. break;
  202. // Resolve the parent path to a directory entry.
  203. Dir = SourceMgr->getFileManager().getDirectory(DirName);
  204. } while (Dir);
  205. return 0;
  206. }
  207. bool ModuleMap::isHeaderInUnavailableModule(const FileEntry *Header) {
  208. HeadersMap::iterator Known = Headers.find(Header);
  209. if (Known != Headers.end())
  210. return !Known->second.isAvailable();
  211. const DirectoryEntry *Dir = Header->getDir();
  212. llvm::SmallVector<const DirectoryEntry *, 2> SkippedDirs;
  213. StringRef DirName = Dir->getName();
  214. // Keep walking up the directory hierarchy, looking for a directory with
  215. // an umbrella header.
  216. do {
  217. llvm::DenseMap<const DirectoryEntry *, Module *>::iterator KnownDir
  218. = UmbrellaDirs.find(Dir);
  219. if (KnownDir != UmbrellaDirs.end()) {
  220. Module *Found = KnownDir->second;
  221. if (!Found->isAvailable())
  222. return true;
  223. // Search up the module stack until we find a module with an umbrella
  224. // directory.
  225. Module *UmbrellaModule = Found;
  226. while (!UmbrellaModule->getUmbrellaDir() && UmbrellaModule->Parent)
  227. UmbrellaModule = UmbrellaModule->Parent;
  228. if (UmbrellaModule->InferSubmodules) {
  229. for (unsigned I = SkippedDirs.size(); I != 0; --I) {
  230. // Find or create the module that corresponds to this directory name.
  231. SmallString<32> NameBuf;
  232. StringRef Name = sanitizeFilenameAsIdentifier(
  233. llvm::sys::path::stem(SkippedDirs[I-1]->getName()),
  234. NameBuf);
  235. Found = lookupModuleQualified(Name, Found);
  236. if (!Found)
  237. return false;
  238. if (!Found->isAvailable())
  239. return true;
  240. }
  241. // Infer a submodule with the same name as this header file.
  242. SmallString<32> NameBuf;
  243. StringRef Name = sanitizeFilenameAsIdentifier(
  244. llvm::sys::path::stem(Header->getName()),
  245. NameBuf);
  246. Found = lookupModuleQualified(Name, Found);
  247. if (!Found)
  248. return false;
  249. }
  250. return !Found->isAvailable();
  251. }
  252. SkippedDirs.push_back(Dir);
  253. // Retrieve our parent path.
  254. DirName = llvm::sys::path::parent_path(DirName);
  255. if (DirName.empty())
  256. break;
  257. // Resolve the parent path to a directory entry.
  258. Dir = SourceMgr->getFileManager().getDirectory(DirName);
  259. } while (Dir);
  260. return false;
  261. }
  262. Module *ModuleMap::findModule(StringRef Name) {
  263. llvm::StringMap<Module *>::iterator Known = Modules.find(Name);
  264. if (Known != Modules.end())
  265. return Known->getValue();
  266. return 0;
  267. }
  268. Module *ModuleMap::lookupModuleUnqualified(StringRef Name, Module *Context) {
  269. for(; Context; Context = Context->Parent) {
  270. if (Module *Sub = lookupModuleQualified(Name, Context))
  271. return Sub;
  272. }
  273. return findModule(Name);
  274. }
  275. Module *ModuleMap::lookupModuleQualified(StringRef Name, Module *Context) {
  276. if (!Context)
  277. return findModule(Name);
  278. return Context->findSubmodule(Name);
  279. }
  280. std::pair<Module *, bool>
  281. ModuleMap::findOrCreateModule(StringRef Name, Module *Parent, bool IsFramework,
  282. bool IsExplicit) {
  283. // Try to find an existing module with this name.
  284. if (Module *Sub = lookupModuleQualified(Name, Parent))
  285. return std::make_pair(Sub, false);
  286. // Create a new module with this name.
  287. Module *Result = new Module(Name, SourceLocation(), Parent, IsFramework,
  288. IsExplicit);
  289. if (!Parent)
  290. Modules[Name] = Result;
  291. return std::make_pair(Result, true);
  292. }
  293. bool ModuleMap::canInferFrameworkModule(const DirectoryEntry *ParentDir,
  294. StringRef Name, bool &IsSystem) {
  295. // Check whether we have already looked into the parent directory
  296. // for a module map.
  297. llvm::DenseMap<const DirectoryEntry *, InferredDirectory>::iterator
  298. inferred = InferredDirectories.find(ParentDir);
  299. if (inferred == InferredDirectories.end())
  300. return false;
  301. if (!inferred->second.InferModules)
  302. return false;
  303. // We're allowed to infer for this directory, but make sure it's okay
  304. // to infer this particular module.
  305. bool canInfer = std::find(inferred->second.ExcludedModules.begin(),
  306. inferred->second.ExcludedModules.end(),
  307. Name) == inferred->second.ExcludedModules.end();
  308. if (canInfer && inferred->second.InferSystemModules)
  309. IsSystem = true;
  310. return canInfer;
  311. }
  312. Module *
  313. ModuleMap::inferFrameworkModule(StringRef ModuleName,
  314. const DirectoryEntry *FrameworkDir,
  315. bool IsSystem,
  316. Module *Parent) {
  317. // Check whether we've already found this module.
  318. if (Module *Mod = lookupModuleQualified(ModuleName, Parent))
  319. return Mod;
  320. FileManager &FileMgr = SourceMgr->getFileManager();
  321. // If the framework has a parent path from which we're allowed to infer
  322. // a framework module, do so.
  323. if (!Parent) {
  324. bool canInfer = false;
  325. if (llvm::sys::path::has_parent_path(FrameworkDir->getName())) {
  326. // Figure out the parent path.
  327. StringRef Parent = llvm::sys::path::parent_path(FrameworkDir->getName());
  328. if (const DirectoryEntry *ParentDir = FileMgr.getDirectory(Parent)) {
  329. // Check whether we have already looked into the parent directory
  330. // for a module map.
  331. llvm::DenseMap<const DirectoryEntry *, InferredDirectory>::iterator
  332. inferred = InferredDirectories.find(ParentDir);
  333. if (inferred == InferredDirectories.end()) {
  334. // We haven't looked here before. Load a module map, if there is
  335. // one.
  336. SmallString<128> ModMapPath = Parent;
  337. llvm::sys::path::append(ModMapPath, "module.map");
  338. if (const FileEntry *ModMapFile = FileMgr.getFile(ModMapPath)) {
  339. parseModuleMapFile(ModMapFile);
  340. inferred = InferredDirectories.find(ParentDir);
  341. }
  342. if (inferred == InferredDirectories.end())
  343. inferred = InferredDirectories.insert(
  344. std::make_pair(ParentDir, InferredDirectory())).first;
  345. }
  346. if (inferred->second.InferModules) {
  347. // We're allowed to infer for this directory, but make sure it's okay
  348. // to infer this particular module.
  349. StringRef Name = llvm::sys::path::filename(FrameworkDir->getName());
  350. canInfer = std::find(inferred->second.ExcludedModules.begin(),
  351. inferred->second.ExcludedModules.end(),
  352. Name) == inferred->second.ExcludedModules.end();
  353. if (inferred->second.InferSystemModules)
  354. IsSystem = true;
  355. }
  356. }
  357. }
  358. // If we're not allowed to infer a framework module, don't.
  359. if (!canInfer)
  360. return 0;
  361. }
  362. // Look for an umbrella header.
  363. SmallString<128> UmbrellaName = StringRef(FrameworkDir->getName());
  364. llvm::sys::path::append(UmbrellaName, "Headers");
  365. llvm::sys::path::append(UmbrellaName, ModuleName + ".h");
  366. const FileEntry *UmbrellaHeader = FileMgr.getFile(UmbrellaName);
  367. // FIXME: If there's no umbrella header, we could probably scan the
  368. // framework to load *everything*. But, it's not clear that this is a good
  369. // idea.
  370. if (!UmbrellaHeader)
  371. return 0;
  372. Module *Result = new Module(ModuleName, SourceLocation(), Parent,
  373. /*IsFramework=*/true, /*IsExplicit=*/false);
  374. if (IsSystem)
  375. Result->IsSystem = IsSystem;
  376. if (!Parent)
  377. Modules[ModuleName] = Result;
  378. // umbrella header "umbrella-header-name"
  379. Result->Umbrella = UmbrellaHeader;
  380. Headers[UmbrellaHeader] = KnownHeader(Result, /*Excluded=*/false);
  381. UmbrellaDirs[UmbrellaHeader->getDir()] = Result;
  382. // export *
  383. Result->Exports.push_back(Module::ExportDecl(0, true));
  384. // module * { export * }
  385. Result->InferSubmodules = true;
  386. Result->InferExportWildcard = true;
  387. // Look for subframeworks.
  388. llvm::error_code EC;
  389. SmallString<128> SubframeworksDirName
  390. = StringRef(FrameworkDir->getName());
  391. llvm::sys::path::append(SubframeworksDirName, "Frameworks");
  392. SmallString<128> SubframeworksDirNameNative;
  393. llvm::sys::path::native(SubframeworksDirName.str(),
  394. SubframeworksDirNameNative);
  395. for (llvm::sys::fs::directory_iterator
  396. Dir(SubframeworksDirNameNative.str(), EC), DirEnd;
  397. Dir != DirEnd && !EC; Dir.increment(EC)) {
  398. if (!StringRef(Dir->path()).endswith(".framework"))
  399. continue;
  400. if (const DirectoryEntry *SubframeworkDir
  401. = FileMgr.getDirectory(Dir->path())) {
  402. // Note: as an egregious but useful hack, we use the real path here and
  403. // check whether it is actually a subdirectory of the parent directory.
  404. // This will not be the case if the 'subframework' is actually a symlink
  405. // out to a top-level framework.
  406. #ifdef LLVM_ON_UNIX
  407. char RealSubframeworkDirName[PATH_MAX];
  408. if (realpath(Dir->path().c_str(), RealSubframeworkDirName)) {
  409. StringRef SubframeworkDirName = RealSubframeworkDirName;
  410. bool FoundParent = false;
  411. do {
  412. // Get the parent directory name.
  413. SubframeworkDirName
  414. = llvm::sys::path::parent_path(SubframeworkDirName);
  415. if (SubframeworkDirName.empty())
  416. break;
  417. if (FileMgr.getDirectory(SubframeworkDirName) == FrameworkDir) {
  418. FoundParent = true;
  419. break;
  420. }
  421. } while (true);
  422. if (!FoundParent)
  423. continue;
  424. }
  425. #endif
  426. // FIXME: Do we want to warn about subframeworks without umbrella headers?
  427. SmallString<32> NameBuf;
  428. inferFrameworkModule(sanitizeFilenameAsIdentifier(
  429. llvm::sys::path::stem(Dir->path()), NameBuf),
  430. SubframeworkDir, IsSystem, Result);
  431. }
  432. }
  433. return Result;
  434. }
  435. void ModuleMap::setUmbrellaHeader(Module *Mod, const FileEntry *UmbrellaHeader){
  436. Headers[UmbrellaHeader] = KnownHeader(Mod, /*Excluded=*/false);
  437. Mod->Umbrella = UmbrellaHeader;
  438. UmbrellaDirs[UmbrellaHeader->getDir()] = Mod;
  439. }
  440. void ModuleMap::setUmbrellaDir(Module *Mod, const DirectoryEntry *UmbrellaDir) {
  441. Mod->Umbrella = UmbrellaDir;
  442. UmbrellaDirs[UmbrellaDir] = Mod;
  443. }
  444. void ModuleMap::addHeader(Module *Mod, const FileEntry *Header,
  445. bool Excluded) {
  446. if (Excluded)
  447. Mod->ExcludedHeaders.push_back(Header);
  448. else
  449. Mod->Headers.push_back(Header);
  450. Headers[Header] = KnownHeader(Mod, Excluded);
  451. }
  452. const FileEntry *
  453. ModuleMap::getContainingModuleMapFile(Module *Module) {
  454. if (Module->DefinitionLoc.isInvalid() || !SourceMgr)
  455. return 0;
  456. return SourceMgr->getFileEntryForID(
  457. SourceMgr->getFileID(Module->DefinitionLoc));
  458. }
  459. void ModuleMap::dump() {
  460. llvm::errs() << "Modules:";
  461. for (llvm::StringMap<Module *>::iterator M = Modules.begin(),
  462. MEnd = Modules.end();
  463. M != MEnd; ++M)
  464. M->getValue()->print(llvm::errs(), 2);
  465. llvm::errs() << "Headers:";
  466. for (HeadersMap::iterator H = Headers.begin(), HEnd = Headers.end();
  467. H != HEnd; ++H) {
  468. llvm::errs() << " \"" << H->first->getName() << "\" -> "
  469. << H->second.getModule()->getFullModuleName() << "\n";
  470. }
  471. }
  472. bool ModuleMap::resolveExports(Module *Mod, bool Complain) {
  473. bool HadError = false;
  474. for (unsigned I = 0, N = Mod->UnresolvedExports.size(); I != N; ++I) {
  475. Module::ExportDecl Export = resolveExport(Mod, Mod->UnresolvedExports[I],
  476. Complain);
  477. if (Export.getPointer() || Export.getInt())
  478. Mod->Exports.push_back(Export);
  479. else
  480. HadError = true;
  481. }
  482. Mod->UnresolvedExports.clear();
  483. return HadError;
  484. }
  485. Module *ModuleMap::inferModuleFromLocation(FullSourceLoc Loc) {
  486. if (Loc.isInvalid())
  487. return 0;
  488. // Use the expansion location to determine which module we're in.
  489. FullSourceLoc ExpansionLoc = Loc.getExpansionLoc();
  490. if (!ExpansionLoc.isFileID())
  491. return 0;
  492. const SourceManager &SrcMgr = Loc.getManager();
  493. FileID ExpansionFileID = ExpansionLoc.getFileID();
  494. while (const FileEntry *ExpansionFile
  495. = SrcMgr.getFileEntryForID(ExpansionFileID)) {
  496. // Find the module that owns this header (if any).
  497. if (Module *Mod = findModuleForHeader(ExpansionFile))
  498. return Mod;
  499. // No module owns this header, so look up the inclusion chain to see if
  500. // any included header has an associated module.
  501. SourceLocation IncludeLoc = SrcMgr.getIncludeLoc(ExpansionFileID);
  502. if (IncludeLoc.isInvalid())
  503. return 0;
  504. ExpansionFileID = SrcMgr.getFileID(IncludeLoc);
  505. }
  506. return 0;
  507. }
  508. //----------------------------------------------------------------------------//
  509. // Module map file parser
  510. //----------------------------------------------------------------------------//
  511. namespace clang {
  512. /// \brief A token in a module map file.
  513. struct MMToken {
  514. enum TokenKind {
  515. Comma,
  516. EndOfFile,
  517. HeaderKeyword,
  518. Identifier,
  519. ExcludeKeyword,
  520. ExplicitKeyword,
  521. ExportKeyword,
  522. FrameworkKeyword,
  523. ModuleKeyword,
  524. Period,
  525. UmbrellaKeyword,
  526. RequiresKeyword,
  527. Star,
  528. StringLiteral,
  529. LBrace,
  530. RBrace,
  531. LSquare,
  532. RSquare
  533. } Kind;
  534. unsigned Location;
  535. unsigned StringLength;
  536. const char *StringData;
  537. void clear() {
  538. Kind = EndOfFile;
  539. Location = 0;
  540. StringLength = 0;
  541. StringData = 0;
  542. }
  543. bool is(TokenKind K) const { return Kind == K; }
  544. SourceLocation getLocation() const {
  545. return SourceLocation::getFromRawEncoding(Location);
  546. }
  547. StringRef getString() const {
  548. return StringRef(StringData, StringLength);
  549. }
  550. };
  551. /// \brief The set of attributes that can be attached to a module.
  552. struct Attributes {
  553. Attributes() : IsSystem() { }
  554. /// \brief Whether this is a system module.
  555. unsigned IsSystem : 1;
  556. };
  557. class ModuleMapParser {
  558. Lexer &L;
  559. SourceManager &SourceMgr;
  560. /// \brief Default target information, used only for string literal
  561. /// parsing.
  562. const TargetInfo *Target;
  563. DiagnosticsEngine &Diags;
  564. ModuleMap &Map;
  565. /// \brief The directory that this module map resides in.
  566. const DirectoryEntry *Directory;
  567. /// \brief The directory containing Clang-supplied headers.
  568. const DirectoryEntry *BuiltinIncludeDir;
  569. /// \brief Whether an error occurred.
  570. bool HadError;
  571. /// \brief Stores string data for the various string literals referenced
  572. /// during parsing.
  573. llvm::BumpPtrAllocator StringData;
  574. /// \brief The current token.
  575. MMToken Tok;
  576. /// \brief The active module.
  577. Module *ActiveModule;
  578. /// \brief Consume the current token and return its location.
  579. SourceLocation consumeToken();
  580. /// \brief Skip tokens until we reach the a token with the given kind
  581. /// (or the end of the file).
  582. void skipUntil(MMToken::TokenKind K);
  583. typedef llvm::SmallVector<std::pair<std::string, SourceLocation>, 2>
  584. ModuleId;
  585. bool parseModuleId(ModuleId &Id);
  586. void parseModuleDecl();
  587. void parseRequiresDecl();
  588. void parseHeaderDecl(SourceLocation UmbrellaLoc, SourceLocation ExcludeLoc);
  589. void parseUmbrellaDirDecl(SourceLocation UmbrellaLoc);
  590. void parseExportDecl();
  591. void parseInferredModuleDecl(bool Framework, bool Explicit);
  592. bool parseOptionalAttributes(Attributes &Attrs);
  593. const DirectoryEntry *getOverriddenHeaderSearchDir();
  594. public:
  595. explicit ModuleMapParser(Lexer &L, SourceManager &SourceMgr,
  596. const TargetInfo *Target,
  597. DiagnosticsEngine &Diags,
  598. ModuleMap &Map,
  599. const DirectoryEntry *Directory,
  600. const DirectoryEntry *BuiltinIncludeDir)
  601. : L(L), SourceMgr(SourceMgr), Target(Target), Diags(Diags), Map(Map),
  602. Directory(Directory), BuiltinIncludeDir(BuiltinIncludeDir),
  603. HadError(false), ActiveModule(0)
  604. {
  605. Tok.clear();
  606. consumeToken();
  607. }
  608. bool parseModuleMapFile();
  609. };
  610. }
  611. SourceLocation ModuleMapParser::consumeToken() {
  612. retry:
  613. SourceLocation Result = Tok.getLocation();
  614. Tok.clear();
  615. Token LToken;
  616. L.LexFromRawLexer(LToken);
  617. Tok.Location = LToken.getLocation().getRawEncoding();
  618. switch (LToken.getKind()) {
  619. case tok::raw_identifier:
  620. Tok.StringData = LToken.getRawIdentifierData();
  621. Tok.StringLength = LToken.getLength();
  622. Tok.Kind = llvm::StringSwitch<MMToken::TokenKind>(Tok.getString())
  623. .Case("header", MMToken::HeaderKeyword)
  624. .Case("exclude", MMToken::ExcludeKeyword)
  625. .Case("explicit", MMToken::ExplicitKeyword)
  626. .Case("export", MMToken::ExportKeyword)
  627. .Case("framework", MMToken::FrameworkKeyword)
  628. .Case("module", MMToken::ModuleKeyword)
  629. .Case("requires", MMToken::RequiresKeyword)
  630. .Case("umbrella", MMToken::UmbrellaKeyword)
  631. .Default(MMToken::Identifier);
  632. break;
  633. case tok::comma:
  634. Tok.Kind = MMToken::Comma;
  635. break;
  636. case tok::eof:
  637. Tok.Kind = MMToken::EndOfFile;
  638. break;
  639. case tok::l_brace:
  640. Tok.Kind = MMToken::LBrace;
  641. break;
  642. case tok::l_square:
  643. Tok.Kind = MMToken::LSquare;
  644. break;
  645. case tok::period:
  646. Tok.Kind = MMToken::Period;
  647. break;
  648. case tok::r_brace:
  649. Tok.Kind = MMToken::RBrace;
  650. break;
  651. case tok::r_square:
  652. Tok.Kind = MMToken::RSquare;
  653. break;
  654. case tok::star:
  655. Tok.Kind = MMToken::Star;
  656. break;
  657. case tok::string_literal: {
  658. if (LToken.hasUDSuffix()) {
  659. Diags.Report(LToken.getLocation(), diag::err_invalid_string_udl);
  660. HadError = true;
  661. goto retry;
  662. }
  663. // Parse the string literal.
  664. LangOptions LangOpts;
  665. StringLiteralParser StringLiteral(&LToken, 1, SourceMgr, LangOpts, *Target);
  666. if (StringLiteral.hadError)
  667. goto retry;
  668. // Copy the string literal into our string data allocator.
  669. unsigned Length = StringLiteral.GetStringLength();
  670. char *Saved = StringData.Allocate<char>(Length + 1);
  671. memcpy(Saved, StringLiteral.GetString().data(), Length);
  672. Saved[Length] = 0;
  673. // Form the token.
  674. Tok.Kind = MMToken::StringLiteral;
  675. Tok.StringData = Saved;
  676. Tok.StringLength = Length;
  677. break;
  678. }
  679. case tok::comment:
  680. goto retry;
  681. default:
  682. Diags.Report(LToken.getLocation(), diag::err_mmap_unknown_token);
  683. HadError = true;
  684. goto retry;
  685. }
  686. return Result;
  687. }
  688. void ModuleMapParser::skipUntil(MMToken::TokenKind K) {
  689. unsigned braceDepth = 0;
  690. unsigned squareDepth = 0;
  691. do {
  692. switch (Tok.Kind) {
  693. case MMToken::EndOfFile:
  694. return;
  695. case MMToken::LBrace:
  696. if (Tok.is(K) && braceDepth == 0 && squareDepth == 0)
  697. return;
  698. ++braceDepth;
  699. break;
  700. case MMToken::LSquare:
  701. if (Tok.is(K) && braceDepth == 0 && squareDepth == 0)
  702. return;
  703. ++squareDepth;
  704. break;
  705. case MMToken::RBrace:
  706. if (braceDepth > 0)
  707. --braceDepth;
  708. else if (Tok.is(K))
  709. return;
  710. break;
  711. case MMToken::RSquare:
  712. if (squareDepth > 0)
  713. --squareDepth;
  714. else if (Tok.is(K))
  715. return;
  716. break;
  717. default:
  718. if (braceDepth == 0 && squareDepth == 0 && Tok.is(K))
  719. return;
  720. break;
  721. }
  722. consumeToken();
  723. } while (true);
  724. }
  725. /// \brief Parse a module-id.
  726. ///
  727. /// module-id:
  728. /// identifier
  729. /// identifier '.' module-id
  730. ///
  731. /// \returns true if an error occurred, false otherwise.
  732. bool ModuleMapParser::parseModuleId(ModuleId &Id) {
  733. Id.clear();
  734. do {
  735. if (Tok.is(MMToken::Identifier)) {
  736. Id.push_back(std::make_pair(Tok.getString(), Tok.getLocation()));
  737. consumeToken();
  738. } else {
  739. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module_name);
  740. return true;
  741. }
  742. if (!Tok.is(MMToken::Period))
  743. break;
  744. consumeToken();
  745. } while (true);
  746. return false;
  747. }
  748. namespace {
  749. /// \brief Enumerates the known attributes.
  750. enum AttributeKind {
  751. /// \brief An unknown attribute.
  752. AT_unknown,
  753. /// \brief The 'system' attribute.
  754. AT_system
  755. };
  756. }
  757. /// \brief Parse a module declaration.
  758. ///
  759. /// module-declaration:
  760. /// 'explicit'[opt] 'framework'[opt] 'module' module-id attributes[opt]
  761. /// { module-member* }
  762. ///
  763. /// module-member:
  764. /// requires-declaration
  765. /// header-declaration
  766. /// submodule-declaration
  767. /// export-declaration
  768. ///
  769. /// submodule-declaration:
  770. /// module-declaration
  771. /// inferred-submodule-declaration
  772. void ModuleMapParser::parseModuleDecl() {
  773. assert(Tok.is(MMToken::ExplicitKeyword) || Tok.is(MMToken::ModuleKeyword) ||
  774. Tok.is(MMToken::FrameworkKeyword));
  775. // Parse 'explicit' or 'framework' keyword, if present.
  776. SourceLocation ExplicitLoc;
  777. bool Explicit = false;
  778. bool Framework = false;
  779. // Parse 'explicit' keyword, if present.
  780. if (Tok.is(MMToken::ExplicitKeyword)) {
  781. ExplicitLoc = consumeToken();
  782. Explicit = true;
  783. }
  784. // Parse 'framework' keyword, if present.
  785. if (Tok.is(MMToken::FrameworkKeyword)) {
  786. consumeToken();
  787. Framework = true;
  788. }
  789. // Parse 'module' keyword.
  790. if (!Tok.is(MMToken::ModuleKeyword)) {
  791. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module);
  792. consumeToken();
  793. HadError = true;
  794. return;
  795. }
  796. consumeToken(); // 'module' keyword
  797. // If we have a wildcard for the module name, this is an inferred submodule.
  798. // Parse it.
  799. if (Tok.is(MMToken::Star))
  800. return parseInferredModuleDecl(Framework, Explicit);
  801. // Parse the module name.
  802. ModuleId Id;
  803. if (parseModuleId(Id)) {
  804. HadError = true;
  805. return;
  806. }
  807. if (ActiveModule) {
  808. if (Id.size() > 1) {
  809. Diags.Report(Id.front().second, diag::err_mmap_nested_submodule_id)
  810. << SourceRange(Id.front().second, Id.back().second);
  811. HadError = true;
  812. return;
  813. }
  814. } else if (Id.size() == 1 && Explicit) {
  815. // Top-level modules can't be explicit.
  816. Diags.Report(ExplicitLoc, diag::err_mmap_explicit_top_level);
  817. Explicit = false;
  818. ExplicitLoc = SourceLocation();
  819. HadError = true;
  820. }
  821. Module *PreviousActiveModule = ActiveModule;
  822. if (Id.size() > 1) {
  823. // This module map defines a submodule. Go find the module of which it
  824. // is a submodule.
  825. ActiveModule = 0;
  826. for (unsigned I = 0, N = Id.size() - 1; I != N; ++I) {
  827. if (Module *Next = Map.lookupModuleQualified(Id[I].first, ActiveModule)) {
  828. ActiveModule = Next;
  829. continue;
  830. }
  831. if (ActiveModule) {
  832. Diags.Report(Id[I].second, diag::err_mmap_missing_module_qualified)
  833. << Id[I].first << ActiveModule->getTopLevelModule();
  834. } else {
  835. Diags.Report(Id[I].second, diag::err_mmap_expected_module_name);
  836. }
  837. HadError = true;
  838. return;
  839. }
  840. }
  841. StringRef ModuleName = Id.back().first;
  842. SourceLocation ModuleNameLoc = Id.back().second;
  843. // Parse the optional attribute list.
  844. Attributes Attrs;
  845. parseOptionalAttributes(Attrs);
  846. // Parse the opening brace.
  847. if (!Tok.is(MMToken::LBrace)) {
  848. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_lbrace)
  849. << ModuleName;
  850. HadError = true;
  851. return;
  852. }
  853. SourceLocation LBraceLoc = consumeToken();
  854. // Determine whether this (sub)module has already been defined.
  855. if (Module *Existing = Map.lookupModuleQualified(ModuleName, ActiveModule)) {
  856. if (Existing->DefinitionLoc.isInvalid() && !ActiveModule) {
  857. // Skip the module definition.
  858. skipUntil(MMToken::RBrace);
  859. if (Tok.is(MMToken::RBrace))
  860. consumeToken();
  861. else {
  862. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
  863. Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
  864. HadError = true;
  865. }
  866. return;
  867. }
  868. Diags.Report(ModuleNameLoc, diag::err_mmap_module_redefinition)
  869. << ModuleName;
  870. Diags.Report(Existing->DefinitionLoc, diag::note_mmap_prev_definition);
  871. // Skip the module definition.
  872. skipUntil(MMToken::RBrace);
  873. if (Tok.is(MMToken::RBrace))
  874. consumeToken();
  875. HadError = true;
  876. return;
  877. }
  878. // Start defining this module.
  879. ActiveModule = Map.findOrCreateModule(ModuleName, ActiveModule, Framework,
  880. Explicit).first;
  881. ActiveModule->DefinitionLoc = ModuleNameLoc;
  882. if (Attrs.IsSystem)
  883. ActiveModule->IsSystem = true;
  884. bool Done = false;
  885. do {
  886. switch (Tok.Kind) {
  887. case MMToken::EndOfFile:
  888. case MMToken::RBrace:
  889. Done = true;
  890. break;
  891. case MMToken::ExplicitKeyword:
  892. case MMToken::FrameworkKeyword:
  893. case MMToken::ModuleKeyword:
  894. parseModuleDecl();
  895. break;
  896. case MMToken::ExportKeyword:
  897. parseExportDecl();
  898. break;
  899. case MMToken::RequiresKeyword:
  900. parseRequiresDecl();
  901. break;
  902. case MMToken::UmbrellaKeyword: {
  903. SourceLocation UmbrellaLoc = consumeToken();
  904. if (Tok.is(MMToken::HeaderKeyword))
  905. parseHeaderDecl(UmbrellaLoc, SourceLocation());
  906. else
  907. parseUmbrellaDirDecl(UmbrellaLoc);
  908. break;
  909. }
  910. case MMToken::ExcludeKeyword: {
  911. SourceLocation ExcludeLoc = consumeToken();
  912. if (Tok.is(MMToken::HeaderKeyword)) {
  913. parseHeaderDecl(SourceLocation(), ExcludeLoc);
  914. } else {
  915. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
  916. << "exclude";
  917. }
  918. break;
  919. }
  920. case MMToken::HeaderKeyword:
  921. parseHeaderDecl(SourceLocation(), SourceLocation());
  922. break;
  923. default:
  924. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_member);
  925. consumeToken();
  926. break;
  927. }
  928. } while (!Done);
  929. if (Tok.is(MMToken::RBrace))
  930. consumeToken();
  931. else {
  932. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
  933. Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
  934. HadError = true;
  935. }
  936. // We're done parsing this module. Pop back to the previous module.
  937. ActiveModule = PreviousActiveModule;
  938. }
  939. /// \brief Parse a requires declaration.
  940. ///
  941. /// requires-declaration:
  942. /// 'requires' feature-list
  943. ///
  944. /// feature-list:
  945. /// identifier ',' feature-list
  946. /// identifier
  947. void ModuleMapParser::parseRequiresDecl() {
  948. assert(Tok.is(MMToken::RequiresKeyword));
  949. // Parse 'requires' keyword.
  950. consumeToken();
  951. // Parse the feature-list.
  952. do {
  953. if (!Tok.is(MMToken::Identifier)) {
  954. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_feature);
  955. HadError = true;
  956. return;
  957. }
  958. // Consume the feature name.
  959. std::string Feature = Tok.getString();
  960. consumeToken();
  961. // Add this feature.
  962. ActiveModule->addRequirement(Feature, Map.LangOpts, *Map.Target);
  963. if (!Tok.is(MMToken::Comma))
  964. break;
  965. // Consume the comma.
  966. consumeToken();
  967. } while (true);
  968. }
  969. /// \brief Append to \p Paths the set of paths needed to get to the
  970. /// subframework in which the given module lives.
  971. static void appendSubframeworkPaths(Module *Mod,
  972. llvm::SmallVectorImpl<char> &Path) {
  973. // Collect the framework names from the given module to the top-level module.
  974. llvm::SmallVector<StringRef, 2> Paths;
  975. for (; Mod; Mod = Mod->Parent) {
  976. if (Mod->IsFramework)
  977. Paths.push_back(Mod->Name);
  978. }
  979. if (Paths.empty())
  980. return;
  981. // Add Frameworks/Name.framework for each subframework.
  982. for (unsigned I = Paths.size() - 1; I != 0; --I) {
  983. llvm::sys::path::append(Path, "Frameworks");
  984. llvm::sys::path::append(Path, Paths[I-1] + ".framework");
  985. }
  986. }
  987. /// \brief Determine whether the given file name is the name of a builtin
  988. /// header, supplied by Clang to replace, override, or augment existing system
  989. /// headers.
  990. static bool isBuiltinHeader(StringRef FileName) {
  991. return llvm::StringSwitch<bool>(FileName)
  992. .Case("float.h", true)
  993. .Case("iso646.h", true)
  994. .Case("limits.h", true)
  995. .Case("stdalign.h", true)
  996. .Case("stdarg.h", true)
  997. .Case("stdbool.h", true)
  998. .Case("stddef.h", true)
  999. .Case("stdint.h", true)
  1000. .Case("tgmath.h", true)
  1001. .Case("unwind.h", true)
  1002. .Default(false);
  1003. }
  1004. /// \brief Parse a header declaration.
  1005. ///
  1006. /// header-declaration:
  1007. /// 'umbrella'[opt] 'header' string-literal
  1008. /// 'exclude'[opt] 'header' string-literal
  1009. void ModuleMapParser::parseHeaderDecl(SourceLocation UmbrellaLoc,
  1010. SourceLocation ExcludeLoc) {
  1011. assert(Tok.is(MMToken::HeaderKeyword));
  1012. consumeToken();
  1013. bool Umbrella = UmbrellaLoc.isValid();
  1014. bool Exclude = ExcludeLoc.isValid();
  1015. assert(!(Umbrella && Exclude) && "Cannot have both 'umbrella' and 'exclude'");
  1016. // Parse the header name.
  1017. if (!Tok.is(MMToken::StringLiteral)) {
  1018. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
  1019. << "header";
  1020. HadError = true;
  1021. return;
  1022. }
  1023. std::string FileName = Tok.getString();
  1024. SourceLocation FileNameLoc = consumeToken();
  1025. // Check whether we already have an umbrella.
  1026. if (Umbrella && ActiveModule->Umbrella) {
  1027. Diags.Report(FileNameLoc, diag::err_mmap_umbrella_clash)
  1028. << ActiveModule->getFullModuleName();
  1029. HadError = true;
  1030. return;
  1031. }
  1032. // Look for this file.
  1033. const FileEntry *File = 0;
  1034. const FileEntry *BuiltinFile = 0;
  1035. SmallString<128> PathName;
  1036. if (llvm::sys::path::is_absolute(FileName)) {
  1037. PathName = FileName;
  1038. File = SourceMgr.getFileManager().getFile(PathName);
  1039. } else if (const DirectoryEntry *Dir = getOverriddenHeaderSearchDir()) {
  1040. PathName = Dir->getName();
  1041. llvm::sys::path::append(PathName, FileName);
  1042. File = SourceMgr.getFileManager().getFile(PathName);
  1043. } else {
  1044. // Search for the header file within the search directory.
  1045. PathName = Directory->getName();
  1046. unsigned PathLength = PathName.size();
  1047. if (ActiveModule->isPartOfFramework()) {
  1048. appendSubframeworkPaths(ActiveModule, PathName);
  1049. // Check whether this file is in the public headers.
  1050. llvm::sys::path::append(PathName, "Headers");
  1051. llvm::sys::path::append(PathName, FileName);
  1052. File = SourceMgr.getFileManager().getFile(PathName);
  1053. if (!File) {
  1054. // Check whether this file is in the private headers.
  1055. PathName.resize(PathLength);
  1056. llvm::sys::path::append(PathName, "PrivateHeaders");
  1057. llvm::sys::path::append(PathName, FileName);
  1058. File = SourceMgr.getFileManager().getFile(PathName);
  1059. }
  1060. } else {
  1061. // Lookup for normal headers.
  1062. llvm::sys::path::append(PathName, FileName);
  1063. File = SourceMgr.getFileManager().getFile(PathName);
  1064. // If this is a system module with a top-level header, this header
  1065. // may have a counterpart (or replacement) in the set of headers
  1066. // supplied by Clang. Find that builtin header.
  1067. if (ActiveModule->IsSystem && !Umbrella && BuiltinIncludeDir &&
  1068. BuiltinIncludeDir != Directory && isBuiltinHeader(FileName)) {
  1069. SmallString<128> BuiltinPathName(BuiltinIncludeDir->getName());
  1070. llvm::sys::path::append(BuiltinPathName, FileName);
  1071. BuiltinFile = SourceMgr.getFileManager().getFile(BuiltinPathName);
  1072. // If Clang supplies this header but the underlying system does not,
  1073. // just silently swap in our builtin version. Otherwise, we'll end
  1074. // up adding both (later).
  1075. if (!File && BuiltinFile) {
  1076. File = BuiltinFile;
  1077. BuiltinFile = 0;
  1078. }
  1079. }
  1080. }
  1081. }
  1082. // FIXME: We shouldn't be eagerly stat'ing every file named in a module map.
  1083. // Come up with a lazy way to do this.
  1084. if (File) {
  1085. if (ModuleMap::KnownHeader OwningModule = Map.Headers[File]) {
  1086. Diags.Report(FileNameLoc, diag::err_mmap_header_conflict)
  1087. << FileName << OwningModule.getModule()->getFullModuleName();
  1088. HadError = true;
  1089. } else if (Umbrella) {
  1090. const DirectoryEntry *UmbrellaDir = File->getDir();
  1091. if (Module *UmbrellaModule = Map.UmbrellaDirs[UmbrellaDir]) {
  1092. Diags.Report(UmbrellaLoc, diag::err_mmap_umbrella_clash)
  1093. << UmbrellaModule->getFullModuleName();
  1094. HadError = true;
  1095. } else {
  1096. // Record this umbrella header.
  1097. Map.setUmbrellaHeader(ActiveModule, File);
  1098. }
  1099. } else {
  1100. // Record this header.
  1101. Map.addHeader(ActiveModule, File, Exclude);
  1102. // If there is a builtin counterpart to this file, add it now.
  1103. if (BuiltinFile)
  1104. Map.addHeader(ActiveModule, BuiltinFile, Exclude);
  1105. }
  1106. } else if (!Exclude) {
  1107. // Ignore excluded header files. They're optional anyway.
  1108. Diags.Report(FileNameLoc, diag::err_mmap_header_not_found)
  1109. << Umbrella << FileName;
  1110. HadError = true;
  1111. }
  1112. }
  1113. /// \brief Parse an umbrella directory declaration.
  1114. ///
  1115. /// umbrella-dir-declaration:
  1116. /// umbrella string-literal
  1117. void ModuleMapParser::parseUmbrellaDirDecl(SourceLocation UmbrellaLoc) {
  1118. // Parse the directory name.
  1119. if (!Tok.is(MMToken::StringLiteral)) {
  1120. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
  1121. << "umbrella";
  1122. HadError = true;
  1123. return;
  1124. }
  1125. std::string DirName = Tok.getString();
  1126. SourceLocation DirNameLoc = consumeToken();
  1127. // Check whether we already have an umbrella.
  1128. if (ActiveModule->Umbrella) {
  1129. Diags.Report(DirNameLoc, diag::err_mmap_umbrella_clash)
  1130. << ActiveModule->getFullModuleName();
  1131. HadError = true;
  1132. return;
  1133. }
  1134. // Look for this file.
  1135. const DirectoryEntry *Dir = 0;
  1136. if (llvm::sys::path::is_absolute(DirName))
  1137. Dir = SourceMgr.getFileManager().getDirectory(DirName);
  1138. else {
  1139. SmallString<128> PathName;
  1140. PathName = Directory->getName();
  1141. llvm::sys::path::append(PathName, DirName);
  1142. Dir = SourceMgr.getFileManager().getDirectory(PathName);
  1143. }
  1144. if (!Dir) {
  1145. Diags.Report(DirNameLoc, diag::err_mmap_umbrella_dir_not_found)
  1146. << DirName;
  1147. HadError = true;
  1148. return;
  1149. }
  1150. if (Module *OwningModule = Map.UmbrellaDirs[Dir]) {
  1151. Diags.Report(UmbrellaLoc, diag::err_mmap_umbrella_clash)
  1152. << OwningModule->getFullModuleName();
  1153. HadError = true;
  1154. return;
  1155. }
  1156. // Record this umbrella directory.
  1157. Map.setUmbrellaDir(ActiveModule, Dir);
  1158. }
  1159. /// \brief Parse a module export declaration.
  1160. ///
  1161. /// export-declaration:
  1162. /// 'export' wildcard-module-id
  1163. ///
  1164. /// wildcard-module-id:
  1165. /// identifier
  1166. /// '*'
  1167. /// identifier '.' wildcard-module-id
  1168. void ModuleMapParser::parseExportDecl() {
  1169. assert(Tok.is(MMToken::ExportKeyword));
  1170. SourceLocation ExportLoc = consumeToken();
  1171. // Parse the module-id with an optional wildcard at the end.
  1172. ModuleId ParsedModuleId;
  1173. bool Wildcard = false;
  1174. do {
  1175. if (Tok.is(MMToken::Identifier)) {
  1176. ParsedModuleId.push_back(std::make_pair(Tok.getString(),
  1177. Tok.getLocation()));
  1178. consumeToken();
  1179. if (Tok.is(MMToken::Period)) {
  1180. consumeToken();
  1181. continue;
  1182. }
  1183. break;
  1184. }
  1185. if(Tok.is(MMToken::Star)) {
  1186. Wildcard = true;
  1187. consumeToken();
  1188. break;
  1189. }
  1190. Diags.Report(Tok.getLocation(), diag::err_mmap_export_module_id);
  1191. HadError = true;
  1192. return;
  1193. } while (true);
  1194. Module::UnresolvedExportDecl Unresolved = {
  1195. ExportLoc, ParsedModuleId, Wildcard
  1196. };
  1197. ActiveModule->UnresolvedExports.push_back(Unresolved);
  1198. }
  1199. /// \brief Parse an inferried module declaration (wildcard modules).
  1200. ///
  1201. /// module-declaration:
  1202. /// 'explicit'[opt] 'framework'[opt] 'module' * attributes[opt]
  1203. /// { inferred-module-member* }
  1204. ///
  1205. /// inferred-module-member:
  1206. /// 'export' '*'
  1207. /// 'exclude' identifier
  1208. void ModuleMapParser::parseInferredModuleDecl(bool Framework, bool Explicit) {
  1209. assert(Tok.is(MMToken::Star));
  1210. SourceLocation StarLoc = consumeToken();
  1211. bool Failed = false;
  1212. // Inferred modules must be submodules.
  1213. if (!ActiveModule && !Framework) {
  1214. Diags.Report(StarLoc, diag::err_mmap_top_level_inferred_submodule);
  1215. Failed = true;
  1216. }
  1217. if (ActiveModule) {
  1218. // Inferred modules must have umbrella directories.
  1219. if (!Failed && !ActiveModule->getUmbrellaDir()) {
  1220. Diags.Report(StarLoc, diag::err_mmap_inferred_no_umbrella);
  1221. Failed = true;
  1222. }
  1223. // Check for redefinition of an inferred module.
  1224. if (!Failed && ActiveModule->InferSubmodules) {
  1225. Diags.Report(StarLoc, diag::err_mmap_inferred_redef);
  1226. if (ActiveModule->InferredSubmoduleLoc.isValid())
  1227. Diags.Report(ActiveModule->InferredSubmoduleLoc,
  1228. diag::note_mmap_prev_definition);
  1229. Failed = true;
  1230. }
  1231. // Check for the 'framework' keyword, which is not permitted here.
  1232. if (Framework) {
  1233. Diags.Report(StarLoc, diag::err_mmap_inferred_framework_submodule);
  1234. Framework = false;
  1235. }
  1236. } else if (Explicit) {
  1237. Diags.Report(StarLoc, diag::err_mmap_explicit_inferred_framework);
  1238. Explicit = false;
  1239. }
  1240. // If there were any problems with this inferred submodule, skip its body.
  1241. if (Failed) {
  1242. if (Tok.is(MMToken::LBrace)) {
  1243. consumeToken();
  1244. skipUntil(MMToken::RBrace);
  1245. if (Tok.is(MMToken::RBrace))
  1246. consumeToken();
  1247. }
  1248. HadError = true;
  1249. return;
  1250. }
  1251. // Parse optional attributes.
  1252. Attributes Attrs;
  1253. parseOptionalAttributes(Attrs);
  1254. if (ActiveModule) {
  1255. // Note that we have an inferred submodule.
  1256. ActiveModule->InferSubmodules = true;
  1257. ActiveModule->InferredSubmoduleLoc = StarLoc;
  1258. ActiveModule->InferExplicitSubmodules = Explicit;
  1259. } else {
  1260. // We'll be inferring framework modules for this directory.
  1261. Map.InferredDirectories[Directory].InferModules = true;
  1262. Map.InferredDirectories[Directory].InferSystemModules = Attrs.IsSystem;
  1263. }
  1264. // Parse the opening brace.
  1265. if (!Tok.is(MMToken::LBrace)) {
  1266. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_lbrace_wildcard);
  1267. HadError = true;
  1268. return;
  1269. }
  1270. SourceLocation LBraceLoc = consumeToken();
  1271. // Parse the body of the inferred submodule.
  1272. bool Done = false;
  1273. do {
  1274. switch (Tok.Kind) {
  1275. case MMToken::EndOfFile:
  1276. case MMToken::RBrace:
  1277. Done = true;
  1278. break;
  1279. case MMToken::ExcludeKeyword: {
  1280. if (ActiveModule) {
  1281. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member)
  1282. << (ActiveModule != 0);
  1283. consumeToken();
  1284. break;
  1285. }
  1286. consumeToken();
  1287. if (!Tok.is(MMToken::Identifier)) {
  1288. Diags.Report(Tok.getLocation(), diag::err_mmap_missing_exclude_name);
  1289. break;
  1290. }
  1291. Map.InferredDirectories[Directory].ExcludedModules
  1292. .push_back(Tok.getString());
  1293. consumeToken();
  1294. break;
  1295. }
  1296. case MMToken::ExportKeyword:
  1297. if (!ActiveModule) {
  1298. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member)
  1299. << (ActiveModule != 0);
  1300. consumeToken();
  1301. break;
  1302. }
  1303. consumeToken();
  1304. if (Tok.is(MMToken::Star))
  1305. ActiveModule->InferExportWildcard = true;
  1306. else
  1307. Diags.Report(Tok.getLocation(),
  1308. diag::err_mmap_expected_export_wildcard);
  1309. consumeToken();
  1310. break;
  1311. case MMToken::ExplicitKeyword:
  1312. case MMToken::ModuleKeyword:
  1313. case MMToken::HeaderKeyword:
  1314. case MMToken::UmbrellaKeyword:
  1315. default:
  1316. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member)
  1317. << (ActiveModule != 0);
  1318. consumeToken();
  1319. break;
  1320. }
  1321. } while (!Done);
  1322. if (Tok.is(MMToken::RBrace))
  1323. consumeToken();
  1324. else {
  1325. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
  1326. Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
  1327. HadError = true;
  1328. }
  1329. }
  1330. /// \brief Parse optional attributes.
  1331. ///
  1332. /// attributes:
  1333. /// attribute attributes
  1334. /// attribute
  1335. ///
  1336. /// attribute:
  1337. /// [ identifier ]
  1338. ///
  1339. /// \param Attrs Will be filled in with the parsed attributes.
  1340. ///
  1341. /// \returns true if an error occurred, false otherwise.
  1342. bool ModuleMapParser::parseOptionalAttributes(Attributes &Attrs) {
  1343. bool HadError = false;
  1344. while (Tok.is(MMToken::LSquare)) {
  1345. // Consume the '['.
  1346. SourceLocation LSquareLoc = consumeToken();
  1347. // Check whether we have an attribute name here.
  1348. if (!Tok.is(MMToken::Identifier)) {
  1349. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_attribute);
  1350. skipUntil(MMToken::RSquare);
  1351. if (Tok.is(MMToken::RSquare))
  1352. consumeToken();
  1353. HadError = true;
  1354. }
  1355. // Decode the attribute name.
  1356. AttributeKind Attribute
  1357. = llvm::StringSwitch<AttributeKind>(Tok.getString())
  1358. .Case("system", AT_system)
  1359. .Default(AT_unknown);
  1360. switch (Attribute) {
  1361. case AT_unknown:
  1362. Diags.Report(Tok.getLocation(), diag::warn_mmap_unknown_attribute)
  1363. << Tok.getString();
  1364. break;
  1365. case AT_system:
  1366. Attrs.IsSystem = true;
  1367. break;
  1368. }
  1369. consumeToken();
  1370. // Consume the ']'.
  1371. if (!Tok.is(MMToken::RSquare)) {
  1372. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rsquare);
  1373. Diags.Report(LSquareLoc, diag::note_mmap_lsquare_match);
  1374. skipUntil(MMToken::RSquare);
  1375. HadError = true;
  1376. }
  1377. if (Tok.is(MMToken::RSquare))
  1378. consumeToken();
  1379. }
  1380. return HadError;
  1381. }
  1382. /// \brief If there is a specific header search directory due the presence
  1383. /// of an umbrella directory, retrieve that directory. Otherwise, returns null.
  1384. const DirectoryEntry *ModuleMapParser::getOverriddenHeaderSearchDir() {
  1385. for (Module *Mod = ActiveModule; Mod; Mod = Mod->Parent) {
  1386. // If we have an umbrella directory, use that.
  1387. if (Mod->hasUmbrellaDir())
  1388. return Mod->getUmbrellaDir();
  1389. // If we have a framework directory, stop looking.
  1390. if (Mod->IsFramework)
  1391. return 0;
  1392. }
  1393. return 0;
  1394. }
  1395. /// \brief Parse a module map file.
  1396. ///
  1397. /// module-map-file:
  1398. /// module-declaration*
  1399. bool ModuleMapParser::parseModuleMapFile() {
  1400. do {
  1401. switch (Tok.Kind) {
  1402. case MMToken::EndOfFile:
  1403. return HadError;
  1404. case MMToken::ExplicitKeyword:
  1405. case MMToken::ModuleKeyword:
  1406. case MMToken::FrameworkKeyword:
  1407. parseModuleDecl();
  1408. break;
  1409. case MMToken::Comma:
  1410. case MMToken::ExcludeKeyword:
  1411. case MMToken::ExportKeyword:
  1412. case MMToken::HeaderKeyword:
  1413. case MMToken::Identifier:
  1414. case MMToken::LBrace:
  1415. case MMToken::LSquare:
  1416. case MMToken::Period:
  1417. case MMToken::RBrace:
  1418. case MMToken::RSquare:
  1419. case MMToken::RequiresKeyword:
  1420. case MMToken::Star:
  1421. case MMToken::StringLiteral:
  1422. case MMToken::UmbrellaKeyword:
  1423. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module);
  1424. HadError = true;
  1425. consumeToken();
  1426. break;
  1427. }
  1428. } while (true);
  1429. }
  1430. bool ModuleMap::parseModuleMapFile(const FileEntry *File) {
  1431. assert(Target != 0 && "Missing target information");
  1432. FileID ID = SourceMgr->createFileID(File, SourceLocation(), SrcMgr::C_User);
  1433. const llvm::MemoryBuffer *Buffer = SourceMgr->getBuffer(ID);
  1434. if (!Buffer)
  1435. return true;
  1436. // Parse this module map file.
  1437. Lexer L(ID, SourceMgr->getBuffer(ID), *SourceMgr, MMapLangOpts);
  1438. Diags->getClient()->BeginSourceFile(MMapLangOpts);
  1439. ModuleMapParser Parser(L, *SourceMgr, Target, *Diags, *this, File->getDir(),
  1440. BuiltinIncludeDir);
  1441. bool Result = Parser.parseModuleMapFile();
  1442. Diags->getClient()->EndSourceFile();
  1443. return Result;
  1444. }