ModuleMap.cpp 59 KB

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