ModuleMap.cpp 81 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534
  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/HeaderSearchOptions.h"
  23. #include "clang/Lex/LexDiagnostic.h"
  24. #include "clang/Lex/Lexer.h"
  25. #include "clang/Lex/LiteralSupport.h"
  26. #include "llvm/ADT/StringRef.h"
  27. #include "llvm/ADT/StringSwitch.h"
  28. #include "llvm/Support/Allocator.h"
  29. #include "llvm/Support/FileSystem.h"
  30. #include "llvm/Support/Host.h"
  31. #include "llvm/Support/Path.h"
  32. #include "llvm/Support/raw_ostream.h"
  33. #include <stdlib.h>
  34. #if defined(LLVM_ON_UNIX)
  35. #include <limits.h>
  36. #endif
  37. using namespace clang;
  38. Module::ExportDecl
  39. ModuleMap::resolveExport(Module *Mod,
  40. const Module::UnresolvedExportDecl &Unresolved,
  41. bool Complain) const {
  42. // We may have just a wildcard.
  43. if (Unresolved.Id.empty()) {
  44. assert(Unresolved.Wildcard && "Invalid unresolved export");
  45. return Module::ExportDecl(nullptr, true);
  46. }
  47. // Resolve the module-id.
  48. Module *Context = resolveModuleId(Unresolved.Id, Mod, Complain);
  49. if (!Context)
  50. return Module::ExportDecl();
  51. return Module::ExportDecl(Context, Unresolved.Wildcard);
  52. }
  53. Module *ModuleMap::resolveModuleId(const ModuleId &Id, Module *Mod,
  54. bool Complain) const {
  55. // Find the starting module.
  56. Module *Context = lookupModuleUnqualified(Id[0].first, Mod);
  57. if (!Context) {
  58. if (Complain)
  59. Diags.Report(Id[0].second, diag::err_mmap_missing_module_unqualified)
  60. << Id[0].first << Mod->getFullModuleName();
  61. return nullptr;
  62. }
  63. // Dig into the module path.
  64. for (unsigned I = 1, N = Id.size(); I != N; ++I) {
  65. Module *Sub = lookupModuleQualified(Id[I].first, Context);
  66. if (!Sub) {
  67. if (Complain)
  68. Diags.Report(Id[I].second, diag::err_mmap_missing_module_qualified)
  69. << Id[I].first << Context->getFullModuleName()
  70. << SourceRange(Id[0].second, Id[I-1].second);
  71. return nullptr;
  72. }
  73. Context = Sub;
  74. }
  75. return Context;
  76. }
  77. ModuleMap::ModuleMap(SourceManager &SourceMgr, DiagnosticsEngine &Diags,
  78. const LangOptions &LangOpts, const TargetInfo *Target,
  79. HeaderSearch &HeaderInfo)
  80. : SourceMgr(SourceMgr), Diags(Diags), LangOpts(LangOpts), Target(Target),
  81. HeaderInfo(HeaderInfo), BuiltinIncludeDir(nullptr),
  82. SourceModule(nullptr), NumCreatedModules(0) {
  83. MMapLangOpts.LineComment = true;
  84. }
  85. ModuleMap::~ModuleMap() {
  86. for (auto &M : Modules)
  87. delete M.getValue();
  88. }
  89. void ModuleMap::setTarget(const TargetInfo &Target) {
  90. assert((!this->Target || this->Target == &Target) &&
  91. "Improper target override");
  92. this->Target = &Target;
  93. }
  94. /// \brief "Sanitize" a filename so that it can be used as an identifier.
  95. static StringRef sanitizeFilenameAsIdentifier(StringRef Name,
  96. SmallVectorImpl<char> &Buffer) {
  97. if (Name.empty())
  98. return Name;
  99. if (!isValidIdentifier(Name)) {
  100. // If we don't already have something with the form of an identifier,
  101. // create a buffer with the sanitized name.
  102. Buffer.clear();
  103. if (isDigit(Name[0]))
  104. Buffer.push_back('_');
  105. Buffer.reserve(Buffer.size() + Name.size());
  106. for (unsigned I = 0, N = Name.size(); I != N; ++I) {
  107. if (isIdentifierBody(Name[I]))
  108. Buffer.push_back(Name[I]);
  109. else
  110. Buffer.push_back('_');
  111. }
  112. Name = StringRef(Buffer.data(), Buffer.size());
  113. }
  114. while (llvm::StringSwitch<bool>(Name)
  115. #define KEYWORD(Keyword,Conditions) .Case(#Keyword, true)
  116. #define ALIAS(Keyword, AliasOf, Conditions) .Case(Keyword, true)
  117. #include "clang/Basic/TokenKinds.def"
  118. .Default(false)) {
  119. if (Name.data() != Buffer.data())
  120. Buffer.append(Name.begin(), Name.end());
  121. Buffer.push_back('_');
  122. Name = StringRef(Buffer.data(), Buffer.size());
  123. }
  124. return Name;
  125. }
  126. /// \brief Determine whether the given file name is the name of a builtin
  127. /// header, supplied by Clang to replace, override, or augment existing system
  128. /// headers.
  129. bool ModuleMap::isBuiltinHeader(StringRef FileName) {
  130. return llvm::StringSwitch<bool>(FileName)
  131. .Case("float.h", true)
  132. .Case("iso646.h", true)
  133. .Case("limits.h", true)
  134. .Case("stdalign.h", true)
  135. .Case("stdarg.h", true)
  136. .Case("stdatomic.h", true)
  137. .Case("stdbool.h", true)
  138. .Case("stddef.h", true)
  139. .Case("stdint.h", true)
  140. .Case("tgmath.h", true)
  141. .Case("unwind.h", true)
  142. .Default(false);
  143. }
  144. ModuleMap::HeadersMap::iterator
  145. ModuleMap::findKnownHeader(const FileEntry *File) {
  146. HeadersMap::iterator Known = Headers.find(File);
  147. if (HeaderInfo.getHeaderSearchOpts().ImplicitModuleMaps &&
  148. Known == Headers.end() && File->getDir() == BuiltinIncludeDir &&
  149. ModuleMap::isBuiltinHeader(llvm::sys::path::filename(File->getName()))) {
  150. HeaderInfo.loadTopLevelSystemModules();
  151. return Headers.find(File);
  152. }
  153. return Known;
  154. }
  155. ModuleMap::KnownHeader
  156. ModuleMap::findHeaderInUmbrellaDirs(const FileEntry *File,
  157. SmallVectorImpl<const DirectoryEntry *> &IntermediateDirs) {
  158. if (UmbrellaDirs.empty())
  159. return KnownHeader();
  160. const DirectoryEntry *Dir = File->getDir();
  161. assert(Dir && "file in no directory");
  162. // Note: as an egregious but useful hack we use the real path here, because
  163. // frameworks moving from top-level frameworks to embedded frameworks tend
  164. // to be symlinked from the top-level location to the embedded location,
  165. // and we need to resolve lookups as if we had found the embedded location.
  166. StringRef DirName = SourceMgr.getFileManager().getCanonicalName(Dir);
  167. // Keep walking up the directory hierarchy, looking for a directory with
  168. // an umbrella header.
  169. do {
  170. auto KnownDir = UmbrellaDirs.find(Dir);
  171. if (KnownDir != UmbrellaDirs.end())
  172. return KnownHeader(KnownDir->second, NormalHeader);
  173. IntermediateDirs.push_back(Dir);
  174. // Retrieve our parent path.
  175. DirName = llvm::sys::path::parent_path(DirName);
  176. if (DirName.empty())
  177. break;
  178. // Resolve the parent path to a directory entry.
  179. Dir = SourceMgr.getFileManager().getDirectory(DirName);
  180. } while (Dir);
  181. return KnownHeader();
  182. }
  183. static bool violatesPrivateInclude(Module *RequestingModule,
  184. const FileEntry *IncFileEnt,
  185. ModuleMap::KnownHeader Header) {
  186. #ifndef NDEBUG
  187. if (Header.getRole() & ModuleMap::PrivateHeader) {
  188. // Check for consistency between the module header role
  189. // as obtained from the lookup and as obtained from the module.
  190. // This check is not cheap, so enable it only for debugging.
  191. bool IsPrivate = false;
  192. SmallVectorImpl<Module::Header> *HeaderList[] = {
  193. &Header.getModule()->Headers[Module::HK_Private],
  194. &Header.getModule()->Headers[Module::HK_PrivateTextual]};
  195. for (auto *Hs : HeaderList)
  196. IsPrivate |=
  197. std::find_if(Hs->begin(), Hs->end(), [&](const Module::Header &H) {
  198. return H.Entry == IncFileEnt;
  199. }) != Hs->end();
  200. assert(IsPrivate && "inconsistent headers and roles");
  201. }
  202. #endif
  203. return !Header.isAccessibleFrom(RequestingModule);
  204. }
  205. static Module *getTopLevelOrNull(Module *M) {
  206. return M ? M->getTopLevelModule() : nullptr;
  207. }
  208. void ModuleMap::diagnoseHeaderInclusion(Module *RequestingModule,
  209. bool RequestingModuleIsModuleInterface,
  210. SourceLocation FilenameLoc,
  211. StringRef Filename,
  212. const FileEntry *File) {
  213. // No errors for indirect modules. This may be a bit of a problem for modules
  214. // with no source files.
  215. if (getTopLevelOrNull(RequestingModule) != getTopLevelOrNull(SourceModule))
  216. return;
  217. if (RequestingModule)
  218. resolveUses(RequestingModule, /*Complain=*/false);
  219. bool Excluded = false;
  220. Module *Private = nullptr;
  221. Module *NotUsed = nullptr;
  222. HeadersMap::iterator Known = findKnownHeader(File);
  223. if (Known != Headers.end()) {
  224. for (const KnownHeader &Header : Known->second) {
  225. // Remember private headers for later printing of a diagnostic.
  226. if (violatesPrivateInclude(RequestingModule, File, Header)) {
  227. Private = Header.getModule();
  228. continue;
  229. }
  230. // If uses need to be specified explicitly, we are only allowed to return
  231. // modules that are explicitly used by the requesting module.
  232. if (RequestingModule && LangOpts.ModulesDeclUse &&
  233. !RequestingModule->directlyUses(Header.getModule())) {
  234. NotUsed = Header.getModule();
  235. continue;
  236. }
  237. // We have found a module that we can happily use.
  238. return;
  239. }
  240. Excluded = true;
  241. }
  242. // We have found a header, but it is private.
  243. if (Private) {
  244. Diags.Report(FilenameLoc, diag::warn_use_of_private_header_outside_module)
  245. << Filename;
  246. return;
  247. }
  248. // We have found a module, but we don't use it.
  249. if (NotUsed) {
  250. Diags.Report(FilenameLoc, diag::err_undeclared_use_of_module)
  251. << RequestingModule->getFullModuleName() << Filename;
  252. return;
  253. }
  254. if (Excluded || isHeaderInUmbrellaDirs(File))
  255. return;
  256. // At this point, only non-modular includes remain.
  257. if (LangOpts.ModulesStrictDeclUse) {
  258. Diags.Report(FilenameLoc, diag::err_undeclared_use_of_module)
  259. << RequestingModule->getFullModuleName() << Filename;
  260. } else if (RequestingModule && RequestingModuleIsModuleInterface &&
  261. LangOpts.isCompilingModule()) {
  262. // Do not diagnose when we are not compiling a module.
  263. diag::kind DiagID = RequestingModule->getTopLevelModule()->IsFramework ?
  264. diag::warn_non_modular_include_in_framework_module :
  265. diag::warn_non_modular_include_in_module;
  266. Diags.Report(FilenameLoc, DiagID) << RequestingModule->getFullModuleName()
  267. << File->getName();
  268. }
  269. }
  270. static bool isBetterKnownHeader(const ModuleMap::KnownHeader &New,
  271. const ModuleMap::KnownHeader &Old) {
  272. // Prefer available modules.
  273. if (New.getModule()->isAvailable() && !Old.getModule()->isAvailable())
  274. return true;
  275. // Prefer a public header over a private header.
  276. if ((New.getRole() & ModuleMap::PrivateHeader) !=
  277. (Old.getRole() & ModuleMap::PrivateHeader))
  278. return !(New.getRole() & ModuleMap::PrivateHeader);
  279. // Prefer a non-textual header over a textual header.
  280. if ((New.getRole() & ModuleMap::TextualHeader) !=
  281. (Old.getRole() & ModuleMap::TextualHeader))
  282. return !(New.getRole() & ModuleMap::TextualHeader);
  283. // Don't have a reason to choose between these. Just keep the first one.
  284. return false;
  285. }
  286. ModuleMap::KnownHeader ModuleMap::findModuleForHeader(const FileEntry *File,
  287. bool AllowTextual) {
  288. auto MakeResult = [&](ModuleMap::KnownHeader R) -> ModuleMap::KnownHeader {
  289. if (!AllowTextual && R.getRole() & ModuleMap::TextualHeader)
  290. return ModuleMap::KnownHeader();
  291. return R;
  292. };
  293. HeadersMap::iterator Known = findKnownHeader(File);
  294. if (Known != Headers.end()) {
  295. ModuleMap::KnownHeader Result;
  296. // Iterate over all modules that 'File' is part of to find the best fit.
  297. for (KnownHeader &H : Known->second) {
  298. // Prefer a header from the source module over all others.
  299. if (H.getModule()->getTopLevelModule() == SourceModule)
  300. return MakeResult(H);
  301. if (!Result || isBetterKnownHeader(H, Result))
  302. Result = H;
  303. }
  304. return MakeResult(Result);
  305. }
  306. return MakeResult(findOrCreateModuleForHeaderInUmbrellaDir(File));
  307. }
  308. ModuleMap::KnownHeader
  309. ModuleMap::findOrCreateModuleForHeaderInUmbrellaDir(const FileEntry *File) {
  310. assert(!Headers.count(File) && "already have a module for this header");
  311. SmallVector<const DirectoryEntry *, 2> SkippedDirs;
  312. KnownHeader H = findHeaderInUmbrellaDirs(File, SkippedDirs);
  313. if (H) {
  314. Module *Result = H.getModule();
  315. // Search up the module stack until we find a module with an umbrella
  316. // directory.
  317. Module *UmbrellaModule = Result;
  318. while (!UmbrellaModule->getUmbrellaDir() && UmbrellaModule->Parent)
  319. UmbrellaModule = UmbrellaModule->Parent;
  320. if (UmbrellaModule->InferSubmodules) {
  321. const FileEntry *UmbrellaModuleMap =
  322. getModuleMapFileForUniquing(UmbrellaModule);
  323. // Infer submodules for each of the directories we found between
  324. // the directory of the umbrella header and the directory where
  325. // the actual header is located.
  326. bool Explicit = UmbrellaModule->InferExplicitSubmodules;
  327. for (unsigned I = SkippedDirs.size(); I != 0; --I) {
  328. // Find or create the module that corresponds to this directory name.
  329. SmallString<32> NameBuf;
  330. StringRef Name = sanitizeFilenameAsIdentifier(
  331. llvm::sys::path::stem(SkippedDirs[I-1]->getName()), NameBuf);
  332. Result = findOrCreateModule(Name, Result, /*IsFramework=*/false,
  333. Explicit).first;
  334. InferredModuleAllowedBy[Result] = UmbrellaModuleMap;
  335. Result->IsInferred = true;
  336. // Associate the module and the directory.
  337. UmbrellaDirs[SkippedDirs[I-1]] = Result;
  338. // If inferred submodules export everything they import, add a
  339. // wildcard to the set of exports.
  340. if (UmbrellaModule->InferExportWildcard && Result->Exports.empty())
  341. Result->Exports.push_back(Module::ExportDecl(nullptr, true));
  342. }
  343. // Infer a submodule with the same name as this header file.
  344. SmallString<32> NameBuf;
  345. StringRef Name = sanitizeFilenameAsIdentifier(
  346. llvm::sys::path::stem(File->getName()), NameBuf);
  347. Result = findOrCreateModule(Name, Result, /*IsFramework=*/false,
  348. Explicit).first;
  349. InferredModuleAllowedBy[Result] = UmbrellaModuleMap;
  350. Result->IsInferred = true;
  351. Result->addTopHeader(File);
  352. // If inferred submodules export everything they import, add a
  353. // wildcard to the set of exports.
  354. if (UmbrellaModule->InferExportWildcard && Result->Exports.empty())
  355. Result->Exports.push_back(Module::ExportDecl(nullptr, true));
  356. } else {
  357. // Record each of the directories we stepped through as being part of
  358. // the module we found, since the umbrella header covers them all.
  359. for (unsigned I = 0, N = SkippedDirs.size(); I != N; ++I)
  360. UmbrellaDirs[SkippedDirs[I]] = Result;
  361. }
  362. KnownHeader Header(Result, NormalHeader);
  363. Headers[File].push_back(Header);
  364. return Header;
  365. }
  366. return KnownHeader();
  367. }
  368. ArrayRef<ModuleMap::KnownHeader>
  369. ModuleMap::findAllModulesForHeader(const FileEntry *File) const {
  370. auto It = Headers.find(File);
  371. if (It == Headers.end())
  372. return None;
  373. return It->second;
  374. }
  375. bool ModuleMap::isHeaderInUnavailableModule(const FileEntry *Header) const {
  376. return isHeaderUnavailableInModule(Header, nullptr);
  377. }
  378. bool
  379. ModuleMap::isHeaderUnavailableInModule(const FileEntry *Header,
  380. const Module *RequestingModule) const {
  381. HeadersMap::const_iterator Known = Headers.find(Header);
  382. if (Known != Headers.end()) {
  383. for (SmallVectorImpl<KnownHeader>::const_iterator
  384. I = Known->second.begin(),
  385. E = Known->second.end();
  386. I != E; ++I) {
  387. if (I->isAvailable() && (!RequestingModule ||
  388. I->getModule()->isSubModuleOf(RequestingModule)))
  389. return false;
  390. }
  391. return true;
  392. }
  393. const DirectoryEntry *Dir = Header->getDir();
  394. SmallVector<const DirectoryEntry *, 2> SkippedDirs;
  395. StringRef DirName = Dir->getName();
  396. auto IsUnavailable = [&](const Module *M) {
  397. return !M->isAvailable() && (!RequestingModule ||
  398. M->isSubModuleOf(RequestingModule));
  399. };
  400. // Keep walking up the directory hierarchy, looking for a directory with
  401. // an umbrella header.
  402. do {
  403. llvm::DenseMap<const DirectoryEntry *, Module *>::const_iterator KnownDir
  404. = UmbrellaDirs.find(Dir);
  405. if (KnownDir != UmbrellaDirs.end()) {
  406. Module *Found = KnownDir->second;
  407. if (IsUnavailable(Found))
  408. return true;
  409. // Search up the module stack until we find a module with an umbrella
  410. // directory.
  411. Module *UmbrellaModule = Found;
  412. while (!UmbrellaModule->getUmbrellaDir() && UmbrellaModule->Parent)
  413. UmbrellaModule = UmbrellaModule->Parent;
  414. if (UmbrellaModule->InferSubmodules) {
  415. for (unsigned I = SkippedDirs.size(); I != 0; --I) {
  416. // Find or create the module that corresponds to this directory name.
  417. SmallString<32> NameBuf;
  418. StringRef Name = sanitizeFilenameAsIdentifier(
  419. llvm::sys::path::stem(SkippedDirs[I-1]->getName()),
  420. NameBuf);
  421. Found = lookupModuleQualified(Name, Found);
  422. if (!Found)
  423. return false;
  424. if (IsUnavailable(Found))
  425. return true;
  426. }
  427. // Infer a submodule with the same name as this header file.
  428. SmallString<32> NameBuf;
  429. StringRef Name = sanitizeFilenameAsIdentifier(
  430. llvm::sys::path::stem(Header->getName()),
  431. NameBuf);
  432. Found = lookupModuleQualified(Name, Found);
  433. if (!Found)
  434. return false;
  435. }
  436. return IsUnavailable(Found);
  437. }
  438. SkippedDirs.push_back(Dir);
  439. // Retrieve our parent path.
  440. DirName = llvm::sys::path::parent_path(DirName);
  441. if (DirName.empty())
  442. break;
  443. // Resolve the parent path to a directory entry.
  444. Dir = SourceMgr.getFileManager().getDirectory(DirName);
  445. } while (Dir);
  446. return false;
  447. }
  448. Module *ModuleMap::findModule(StringRef Name) const {
  449. llvm::StringMap<Module *>::const_iterator Known = Modules.find(Name);
  450. if (Known != Modules.end())
  451. return Known->getValue();
  452. return nullptr;
  453. }
  454. Module *ModuleMap::lookupModuleUnqualified(StringRef Name,
  455. Module *Context) const {
  456. for(; Context; Context = Context->Parent) {
  457. if (Module *Sub = lookupModuleQualified(Name, Context))
  458. return Sub;
  459. }
  460. return findModule(Name);
  461. }
  462. Module *ModuleMap::lookupModuleQualified(StringRef Name, Module *Context) const{
  463. if (!Context)
  464. return findModule(Name);
  465. return Context->findSubmodule(Name);
  466. }
  467. std::pair<Module *, bool>
  468. ModuleMap::findOrCreateModule(StringRef Name, Module *Parent, bool IsFramework,
  469. bool IsExplicit) {
  470. // Try to find an existing module with this name.
  471. if (Module *Sub = lookupModuleQualified(Name, Parent))
  472. return std::make_pair(Sub, false);
  473. // Create a new module with this name.
  474. Module *Result = new Module(Name, SourceLocation(), Parent,
  475. IsFramework, IsExplicit, NumCreatedModules++);
  476. if (!Parent) {
  477. if (LangOpts.CurrentModule == Name)
  478. SourceModule = Result;
  479. Modules[Name] = Result;
  480. }
  481. return std::make_pair(Result, true);
  482. }
  483. Module *ModuleMap::createModuleForInterfaceUnit(SourceLocation Loc,
  484. StringRef Name) {
  485. assert(LangOpts.CurrentModule == Name && "module name mismatch");
  486. assert(!Modules[Name] && "redefining existing module");
  487. auto *Result =
  488. new Module(Name, Loc, nullptr, /*IsFramework*/ false,
  489. /*IsExplicit*/ false, NumCreatedModules++);
  490. Modules[Name] = SourceModule = Result;
  491. // Mark the main source file as being within the newly-created module so that
  492. // declarations and macros are properly visibility-restricted to it.
  493. auto *MainFile = SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
  494. assert(MainFile && "no input file for module interface");
  495. Headers[MainFile].push_back(KnownHeader(Result, PrivateHeader));
  496. return Result;
  497. }
  498. /// \brief For a framework module, infer the framework against which we
  499. /// should link.
  500. static void inferFrameworkLink(Module *Mod, const DirectoryEntry *FrameworkDir,
  501. FileManager &FileMgr) {
  502. assert(Mod->IsFramework && "Can only infer linking for framework modules");
  503. assert(!Mod->isSubFramework() &&
  504. "Can only infer linking for top-level frameworks");
  505. SmallString<128> LibName;
  506. LibName += FrameworkDir->getName();
  507. llvm::sys::path::append(LibName, Mod->Name);
  508. // The library name of a framework has more than one possible extension since
  509. // the introduction of the text-based dynamic library format. We need to check
  510. // for both before we give up.
  511. for (const char *extension : {"", ".tbd"}) {
  512. llvm::sys::path::replace_extension(LibName, extension);
  513. if (FileMgr.getFile(LibName)) {
  514. Mod->LinkLibraries.push_back(Module::LinkLibrary(Mod->Name,
  515. /*IsFramework=*/true));
  516. return;
  517. }
  518. }
  519. }
  520. Module *ModuleMap::inferFrameworkModule(const DirectoryEntry *FrameworkDir,
  521. bool IsSystem, Module *Parent) {
  522. Attributes Attrs;
  523. Attrs.IsSystem = IsSystem;
  524. return inferFrameworkModule(FrameworkDir, Attrs, Parent);
  525. }
  526. Module *ModuleMap::inferFrameworkModule(const DirectoryEntry *FrameworkDir,
  527. Attributes Attrs, Module *Parent) {
  528. // Note: as an egregious but useful hack we use the real path here, because
  529. // we might be looking at an embedded framework that symlinks out to a
  530. // top-level framework, and we need to infer as if we were naming the
  531. // top-level framework.
  532. StringRef FrameworkDirName =
  533. SourceMgr.getFileManager().getCanonicalName(FrameworkDir);
  534. // In case this is a case-insensitive filesystem, use the canonical
  535. // directory name as the ModuleName, since modules are case-sensitive.
  536. // FIXME: we should be able to give a fix-it hint for the correct spelling.
  537. SmallString<32> ModuleNameStorage;
  538. StringRef ModuleName = sanitizeFilenameAsIdentifier(
  539. llvm::sys::path::stem(FrameworkDirName), ModuleNameStorage);
  540. // Check whether we've already found this module.
  541. if (Module *Mod = lookupModuleQualified(ModuleName, Parent))
  542. return Mod;
  543. FileManager &FileMgr = SourceMgr.getFileManager();
  544. // If the framework has a parent path from which we're allowed to infer
  545. // a framework module, do so.
  546. const FileEntry *ModuleMapFile = nullptr;
  547. if (!Parent) {
  548. // Determine whether we're allowed to infer a module map.
  549. bool canInfer = false;
  550. if (llvm::sys::path::has_parent_path(FrameworkDirName)) {
  551. // Figure out the parent path.
  552. StringRef Parent = llvm::sys::path::parent_path(FrameworkDirName);
  553. if (const DirectoryEntry *ParentDir = FileMgr.getDirectory(Parent)) {
  554. // Check whether we have already looked into the parent directory
  555. // for a module map.
  556. llvm::DenseMap<const DirectoryEntry *, InferredDirectory>::const_iterator
  557. inferred = InferredDirectories.find(ParentDir);
  558. if (inferred == InferredDirectories.end()) {
  559. // We haven't looked here before. Load a module map, if there is
  560. // one.
  561. bool IsFrameworkDir = Parent.endswith(".framework");
  562. if (const FileEntry *ModMapFile =
  563. HeaderInfo.lookupModuleMapFile(ParentDir, IsFrameworkDir)) {
  564. parseModuleMapFile(ModMapFile, Attrs.IsSystem, ParentDir);
  565. inferred = InferredDirectories.find(ParentDir);
  566. }
  567. if (inferred == InferredDirectories.end())
  568. inferred = InferredDirectories.insert(
  569. std::make_pair(ParentDir, InferredDirectory())).first;
  570. }
  571. if (inferred->second.InferModules) {
  572. // We're allowed to infer for this directory, but make sure it's okay
  573. // to infer this particular module.
  574. StringRef Name = llvm::sys::path::stem(FrameworkDirName);
  575. canInfer = std::find(inferred->second.ExcludedModules.begin(),
  576. inferred->second.ExcludedModules.end(),
  577. Name) == inferred->second.ExcludedModules.end();
  578. Attrs.IsSystem |= inferred->second.Attrs.IsSystem;
  579. Attrs.IsExternC |= inferred->second.Attrs.IsExternC;
  580. Attrs.IsExhaustive |= inferred->second.Attrs.IsExhaustive;
  581. Attrs.NoUndeclaredIncludes |=
  582. inferred->second.Attrs.NoUndeclaredIncludes;
  583. ModuleMapFile = inferred->second.ModuleMapFile;
  584. }
  585. }
  586. }
  587. // If we're not allowed to infer a framework module, don't.
  588. if (!canInfer)
  589. return nullptr;
  590. } else
  591. ModuleMapFile = getModuleMapFileForUniquing(Parent);
  592. // Look for an umbrella header.
  593. SmallString<128> UmbrellaName = StringRef(FrameworkDir->getName());
  594. llvm::sys::path::append(UmbrellaName, "Headers", ModuleName + ".h");
  595. const FileEntry *UmbrellaHeader = FileMgr.getFile(UmbrellaName);
  596. // FIXME: If there's no umbrella header, we could probably scan the
  597. // framework to load *everything*. But, it's not clear that this is a good
  598. // idea.
  599. if (!UmbrellaHeader)
  600. return nullptr;
  601. Module *Result = new Module(ModuleName, SourceLocation(), Parent,
  602. /*IsFramework=*/true, /*IsExplicit=*/false,
  603. NumCreatedModules++);
  604. InferredModuleAllowedBy[Result] = ModuleMapFile;
  605. Result->IsInferred = true;
  606. if (!Parent) {
  607. if (LangOpts.CurrentModule == ModuleName)
  608. SourceModule = Result;
  609. Modules[ModuleName] = Result;
  610. }
  611. Result->IsSystem |= Attrs.IsSystem;
  612. Result->IsExternC |= Attrs.IsExternC;
  613. Result->ConfigMacrosExhaustive |= Attrs.IsExhaustive;
  614. Result->NoUndeclaredIncludes |= Attrs.NoUndeclaredIncludes;
  615. Result->Directory = FrameworkDir;
  616. // umbrella header "umbrella-header-name"
  617. //
  618. // The "Headers/" component of the name is implied because this is
  619. // a framework module.
  620. setUmbrellaHeader(Result, UmbrellaHeader, ModuleName + ".h");
  621. // export *
  622. Result->Exports.push_back(Module::ExportDecl(nullptr, true));
  623. // module * { export * }
  624. Result->InferSubmodules = true;
  625. Result->InferExportWildcard = true;
  626. // Look for subframeworks.
  627. std::error_code EC;
  628. SmallString<128> SubframeworksDirName
  629. = StringRef(FrameworkDir->getName());
  630. llvm::sys::path::append(SubframeworksDirName, "Frameworks");
  631. llvm::sys::path::native(SubframeworksDirName);
  632. vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
  633. for (vfs::directory_iterator Dir = FS.dir_begin(SubframeworksDirName, EC),
  634. DirEnd;
  635. Dir != DirEnd && !EC; Dir.increment(EC)) {
  636. if (!StringRef(Dir->getName()).endswith(".framework"))
  637. continue;
  638. if (const DirectoryEntry *SubframeworkDir =
  639. FileMgr.getDirectory(Dir->getName())) {
  640. // Note: as an egregious but useful hack, we use the real path here and
  641. // check whether it is actually a subdirectory of the parent directory.
  642. // This will not be the case if the 'subframework' is actually a symlink
  643. // out to a top-level framework.
  644. StringRef SubframeworkDirName = FileMgr.getCanonicalName(SubframeworkDir);
  645. bool FoundParent = false;
  646. do {
  647. // Get the parent directory name.
  648. SubframeworkDirName
  649. = llvm::sys::path::parent_path(SubframeworkDirName);
  650. if (SubframeworkDirName.empty())
  651. break;
  652. if (FileMgr.getDirectory(SubframeworkDirName) == FrameworkDir) {
  653. FoundParent = true;
  654. break;
  655. }
  656. } while (true);
  657. if (!FoundParent)
  658. continue;
  659. // FIXME: Do we want to warn about subframeworks without umbrella headers?
  660. inferFrameworkModule(SubframeworkDir, Attrs, Result);
  661. }
  662. }
  663. // If the module is a top-level framework, automatically link against the
  664. // framework.
  665. if (!Result->isSubFramework()) {
  666. inferFrameworkLink(Result, FrameworkDir, FileMgr);
  667. }
  668. return Result;
  669. }
  670. void ModuleMap::setUmbrellaHeader(Module *Mod, const FileEntry *UmbrellaHeader,
  671. Twine NameAsWritten) {
  672. Headers[UmbrellaHeader].push_back(KnownHeader(Mod, NormalHeader));
  673. Mod->Umbrella = UmbrellaHeader;
  674. Mod->UmbrellaAsWritten = NameAsWritten.str();
  675. UmbrellaDirs[UmbrellaHeader->getDir()] = Mod;
  676. // Notify callbacks that we just added a new header.
  677. for (const auto &Cb : Callbacks)
  678. Cb->moduleMapAddUmbrellaHeader(&SourceMgr.getFileManager(), UmbrellaHeader);
  679. }
  680. void ModuleMap::setUmbrellaDir(Module *Mod, const DirectoryEntry *UmbrellaDir,
  681. Twine NameAsWritten) {
  682. Mod->Umbrella = UmbrellaDir;
  683. Mod->UmbrellaAsWritten = NameAsWritten.str();
  684. UmbrellaDirs[UmbrellaDir] = Mod;
  685. }
  686. static Module::HeaderKind headerRoleToKind(ModuleMap::ModuleHeaderRole Role) {
  687. switch ((int)Role) {
  688. default: llvm_unreachable("unknown header role");
  689. case ModuleMap::NormalHeader:
  690. return Module::HK_Normal;
  691. case ModuleMap::PrivateHeader:
  692. return Module::HK_Private;
  693. case ModuleMap::TextualHeader:
  694. return Module::HK_Textual;
  695. case ModuleMap::PrivateHeader | ModuleMap::TextualHeader:
  696. return Module::HK_PrivateTextual;
  697. }
  698. }
  699. void ModuleMap::addHeader(Module *Mod, Module::Header Header,
  700. ModuleHeaderRole Role, bool Imported) {
  701. KnownHeader KH(Mod, Role);
  702. // Only add each header to the headers list once.
  703. // FIXME: Should we diagnose if a header is listed twice in the
  704. // same module definition?
  705. auto &HeaderList = Headers[Header.Entry];
  706. for (auto H : HeaderList)
  707. if (H == KH)
  708. return;
  709. HeaderList.push_back(KH);
  710. Mod->Headers[headerRoleToKind(Role)].push_back(Header);
  711. bool isCompilingModuleHeader =
  712. LangOpts.isCompilingModule() && Mod->getTopLevelModule() == SourceModule;
  713. if (!Imported || isCompilingModuleHeader) {
  714. // When we import HeaderFileInfo, the external source is expected to
  715. // set the isModuleHeader flag itself.
  716. HeaderInfo.MarkFileModuleHeader(Header.Entry, Role,
  717. isCompilingModuleHeader);
  718. }
  719. // Notify callbacks that we just added a new header.
  720. for (const auto &Cb : Callbacks)
  721. Cb->moduleMapAddHeader(Header.Entry->getName());
  722. }
  723. void ModuleMap::excludeHeader(Module *Mod, Module::Header Header) {
  724. // Add this as a known header so we won't implicitly add it to any
  725. // umbrella directory module.
  726. // FIXME: Should we only exclude it from umbrella modules within the
  727. // specified module?
  728. (void) Headers[Header.Entry];
  729. Mod->Headers[Module::HK_Excluded].push_back(std::move(Header));
  730. }
  731. const FileEntry *
  732. ModuleMap::getContainingModuleMapFile(const Module *Module) const {
  733. if (Module->DefinitionLoc.isInvalid())
  734. return nullptr;
  735. return SourceMgr.getFileEntryForID(
  736. SourceMgr.getFileID(Module->DefinitionLoc));
  737. }
  738. const FileEntry *ModuleMap::getModuleMapFileForUniquing(const Module *M) const {
  739. if (M->IsInferred) {
  740. assert(InferredModuleAllowedBy.count(M) && "missing inferred module map");
  741. return InferredModuleAllowedBy.find(M)->second;
  742. }
  743. return getContainingModuleMapFile(M);
  744. }
  745. void ModuleMap::setInferredModuleAllowedBy(Module *M, const FileEntry *ModMap) {
  746. assert(M->IsInferred && "module not inferred");
  747. InferredModuleAllowedBy[M] = ModMap;
  748. }
  749. LLVM_DUMP_METHOD void ModuleMap::dump() {
  750. llvm::errs() << "Modules:";
  751. for (llvm::StringMap<Module *>::iterator M = Modules.begin(),
  752. MEnd = Modules.end();
  753. M != MEnd; ++M)
  754. M->getValue()->print(llvm::errs(), 2);
  755. llvm::errs() << "Headers:";
  756. for (HeadersMap::iterator H = Headers.begin(), HEnd = Headers.end();
  757. H != HEnd; ++H) {
  758. llvm::errs() << " \"" << H->first->getName() << "\" -> ";
  759. for (SmallVectorImpl<KnownHeader>::const_iterator I = H->second.begin(),
  760. E = H->second.end();
  761. I != E; ++I) {
  762. if (I != H->second.begin())
  763. llvm::errs() << ",";
  764. llvm::errs() << I->getModule()->getFullModuleName();
  765. }
  766. llvm::errs() << "\n";
  767. }
  768. }
  769. bool ModuleMap::resolveExports(Module *Mod, bool Complain) {
  770. auto Unresolved = std::move(Mod->UnresolvedExports);
  771. Mod->UnresolvedExports.clear();
  772. for (auto &UE : Unresolved) {
  773. Module::ExportDecl Export = resolveExport(Mod, UE, Complain);
  774. if (Export.getPointer() || Export.getInt())
  775. Mod->Exports.push_back(Export);
  776. else
  777. Mod->UnresolvedExports.push_back(UE);
  778. }
  779. return !Mod->UnresolvedExports.empty();
  780. }
  781. bool ModuleMap::resolveUses(Module *Mod, bool Complain) {
  782. auto Unresolved = std::move(Mod->UnresolvedDirectUses);
  783. Mod->UnresolvedDirectUses.clear();
  784. for (auto &UDU : Unresolved) {
  785. Module *DirectUse = resolveModuleId(UDU, Mod, Complain);
  786. if (DirectUse)
  787. Mod->DirectUses.push_back(DirectUse);
  788. else
  789. Mod->UnresolvedDirectUses.push_back(UDU);
  790. }
  791. return !Mod->UnresolvedDirectUses.empty();
  792. }
  793. bool ModuleMap::resolveConflicts(Module *Mod, bool Complain) {
  794. auto Unresolved = std::move(Mod->UnresolvedConflicts);
  795. Mod->UnresolvedConflicts.clear();
  796. for (auto &UC : Unresolved) {
  797. if (Module *OtherMod = resolveModuleId(UC.Id, Mod, Complain)) {
  798. Module::Conflict Conflict;
  799. Conflict.Other = OtherMod;
  800. Conflict.Message = UC.Message;
  801. Mod->Conflicts.push_back(Conflict);
  802. } else
  803. Mod->UnresolvedConflicts.push_back(UC);
  804. }
  805. return !Mod->UnresolvedConflicts.empty();
  806. }
  807. Module *ModuleMap::inferModuleFromLocation(FullSourceLoc Loc) {
  808. if (Loc.isInvalid())
  809. return nullptr;
  810. if (UmbrellaDirs.empty() && Headers.empty())
  811. return nullptr;
  812. // Use the expansion location to determine which module we're in.
  813. FullSourceLoc ExpansionLoc = Loc.getExpansionLoc();
  814. if (!ExpansionLoc.isFileID())
  815. return nullptr;
  816. const SourceManager &SrcMgr = Loc.getManager();
  817. FileID ExpansionFileID = ExpansionLoc.getFileID();
  818. while (const FileEntry *ExpansionFile
  819. = SrcMgr.getFileEntryForID(ExpansionFileID)) {
  820. // Find the module that owns this header (if any).
  821. if (Module *Mod = findModuleForHeader(ExpansionFile).getModule())
  822. return Mod;
  823. // No module owns this header, so look up the inclusion chain to see if
  824. // any included header has an associated module.
  825. SourceLocation IncludeLoc = SrcMgr.getIncludeLoc(ExpansionFileID);
  826. if (IncludeLoc.isInvalid())
  827. return nullptr;
  828. ExpansionFileID = SrcMgr.getFileID(IncludeLoc);
  829. }
  830. return nullptr;
  831. }
  832. //----------------------------------------------------------------------------//
  833. // Module map file parser
  834. //----------------------------------------------------------------------------//
  835. namespace clang {
  836. /// \brief A token in a module map file.
  837. struct MMToken {
  838. enum TokenKind {
  839. Comma,
  840. ConfigMacros,
  841. Conflict,
  842. EndOfFile,
  843. HeaderKeyword,
  844. Identifier,
  845. Exclaim,
  846. ExcludeKeyword,
  847. ExplicitKeyword,
  848. ExportKeyword,
  849. ExternKeyword,
  850. FrameworkKeyword,
  851. LinkKeyword,
  852. ModuleKeyword,
  853. Period,
  854. PrivateKeyword,
  855. UmbrellaKeyword,
  856. UseKeyword,
  857. RequiresKeyword,
  858. Star,
  859. StringLiteral,
  860. TextualKeyword,
  861. LBrace,
  862. RBrace,
  863. LSquare,
  864. RSquare
  865. } Kind;
  866. unsigned Location;
  867. unsigned StringLength;
  868. const char *StringData;
  869. void clear() {
  870. Kind = EndOfFile;
  871. Location = 0;
  872. StringLength = 0;
  873. StringData = nullptr;
  874. }
  875. bool is(TokenKind K) const { return Kind == K; }
  876. SourceLocation getLocation() const {
  877. return SourceLocation::getFromRawEncoding(Location);
  878. }
  879. StringRef getString() const {
  880. return StringRef(StringData, StringLength);
  881. }
  882. };
  883. class ModuleMapParser {
  884. Lexer &L;
  885. SourceManager &SourceMgr;
  886. /// \brief Default target information, used only for string literal
  887. /// parsing.
  888. const TargetInfo *Target;
  889. DiagnosticsEngine &Diags;
  890. ModuleMap &Map;
  891. /// \brief The current module map file.
  892. const FileEntry *ModuleMapFile;
  893. /// \brief The directory that file names in this module map file should
  894. /// be resolved relative to.
  895. const DirectoryEntry *Directory;
  896. /// \brief The directory containing Clang-supplied headers.
  897. const DirectoryEntry *BuiltinIncludeDir;
  898. /// \brief Whether this module map is in a system header directory.
  899. bool IsSystem;
  900. /// \brief Whether an error occurred.
  901. bool HadError;
  902. /// \brief Stores string data for the various string literals referenced
  903. /// during parsing.
  904. llvm::BumpPtrAllocator StringData;
  905. /// \brief The current token.
  906. MMToken Tok;
  907. /// \brief The active module.
  908. Module *ActiveModule;
  909. /// \brief Whether a module uses the 'requires excluded' hack to mark its
  910. /// contents as 'textual'.
  911. ///
  912. /// On older Darwin SDK versions, 'requires excluded' is used to mark the
  913. /// contents of the Darwin.C.excluded (assert.h) and Tcl.Private modules as
  914. /// non-modular headers. For backwards compatibility, we continue to
  915. /// support this idiom for just these modules, and map the headers to
  916. /// 'textual' to match the original intent.
  917. llvm::SmallPtrSet<Module *, 2> UsesRequiresExcludedHack;
  918. /// \brief Consume the current token and return its location.
  919. SourceLocation consumeToken();
  920. /// \brief Skip tokens until we reach the a token with the given kind
  921. /// (or the end of the file).
  922. void skipUntil(MMToken::TokenKind K);
  923. typedef SmallVector<std::pair<std::string, SourceLocation>, 2> ModuleId;
  924. bool parseModuleId(ModuleId &Id);
  925. void parseModuleDecl();
  926. void parseExternModuleDecl();
  927. void parseRequiresDecl();
  928. void parseHeaderDecl(clang::MMToken::TokenKind,
  929. SourceLocation LeadingLoc);
  930. void parseUmbrellaDirDecl(SourceLocation UmbrellaLoc);
  931. void parseExportDecl();
  932. void parseUseDecl();
  933. void parseLinkDecl();
  934. void parseConfigMacros();
  935. void parseConflict();
  936. void parseInferredModuleDecl(bool Framework, bool Explicit);
  937. typedef ModuleMap::Attributes Attributes;
  938. bool parseOptionalAttributes(Attributes &Attrs);
  939. public:
  940. explicit ModuleMapParser(Lexer &L, SourceManager &SourceMgr,
  941. const TargetInfo *Target,
  942. DiagnosticsEngine &Diags,
  943. ModuleMap &Map,
  944. const FileEntry *ModuleMapFile,
  945. const DirectoryEntry *Directory,
  946. const DirectoryEntry *BuiltinIncludeDir,
  947. bool IsSystem)
  948. : L(L), SourceMgr(SourceMgr), Target(Target), Diags(Diags), Map(Map),
  949. ModuleMapFile(ModuleMapFile), Directory(Directory),
  950. BuiltinIncludeDir(BuiltinIncludeDir), IsSystem(IsSystem),
  951. HadError(false), ActiveModule(nullptr)
  952. {
  953. Tok.clear();
  954. consumeToken();
  955. }
  956. bool parseModuleMapFile();
  957. };
  958. }
  959. SourceLocation ModuleMapParser::consumeToken() {
  960. retry:
  961. SourceLocation Result = Tok.getLocation();
  962. Tok.clear();
  963. Token LToken;
  964. L.LexFromRawLexer(LToken);
  965. Tok.Location = LToken.getLocation().getRawEncoding();
  966. switch (LToken.getKind()) {
  967. case tok::raw_identifier: {
  968. StringRef RI = LToken.getRawIdentifier();
  969. Tok.StringData = RI.data();
  970. Tok.StringLength = RI.size();
  971. Tok.Kind = llvm::StringSwitch<MMToken::TokenKind>(RI)
  972. .Case("config_macros", MMToken::ConfigMacros)
  973. .Case("conflict", MMToken::Conflict)
  974. .Case("exclude", MMToken::ExcludeKeyword)
  975. .Case("explicit", MMToken::ExplicitKeyword)
  976. .Case("export", MMToken::ExportKeyword)
  977. .Case("extern", MMToken::ExternKeyword)
  978. .Case("framework", MMToken::FrameworkKeyword)
  979. .Case("header", MMToken::HeaderKeyword)
  980. .Case("link", MMToken::LinkKeyword)
  981. .Case("module", MMToken::ModuleKeyword)
  982. .Case("private", MMToken::PrivateKeyword)
  983. .Case("requires", MMToken::RequiresKeyword)
  984. .Case("textual", MMToken::TextualKeyword)
  985. .Case("umbrella", MMToken::UmbrellaKeyword)
  986. .Case("use", MMToken::UseKeyword)
  987. .Default(MMToken::Identifier);
  988. break;
  989. }
  990. case tok::comma:
  991. Tok.Kind = MMToken::Comma;
  992. break;
  993. case tok::eof:
  994. Tok.Kind = MMToken::EndOfFile;
  995. break;
  996. case tok::l_brace:
  997. Tok.Kind = MMToken::LBrace;
  998. break;
  999. case tok::l_square:
  1000. Tok.Kind = MMToken::LSquare;
  1001. break;
  1002. case tok::period:
  1003. Tok.Kind = MMToken::Period;
  1004. break;
  1005. case tok::r_brace:
  1006. Tok.Kind = MMToken::RBrace;
  1007. break;
  1008. case tok::r_square:
  1009. Tok.Kind = MMToken::RSquare;
  1010. break;
  1011. case tok::star:
  1012. Tok.Kind = MMToken::Star;
  1013. break;
  1014. case tok::exclaim:
  1015. Tok.Kind = MMToken::Exclaim;
  1016. break;
  1017. case tok::string_literal: {
  1018. if (LToken.hasUDSuffix()) {
  1019. Diags.Report(LToken.getLocation(), diag::err_invalid_string_udl);
  1020. HadError = true;
  1021. goto retry;
  1022. }
  1023. // Parse the string literal.
  1024. LangOptions LangOpts;
  1025. StringLiteralParser StringLiteral(LToken, SourceMgr, LangOpts, *Target);
  1026. if (StringLiteral.hadError)
  1027. goto retry;
  1028. // Copy the string literal into our string data allocator.
  1029. unsigned Length = StringLiteral.GetStringLength();
  1030. char *Saved = StringData.Allocate<char>(Length + 1);
  1031. memcpy(Saved, StringLiteral.GetString().data(), Length);
  1032. Saved[Length] = 0;
  1033. // Form the token.
  1034. Tok.Kind = MMToken::StringLiteral;
  1035. Tok.StringData = Saved;
  1036. Tok.StringLength = Length;
  1037. break;
  1038. }
  1039. case tok::comment:
  1040. goto retry;
  1041. default:
  1042. Diags.Report(LToken.getLocation(), diag::err_mmap_unknown_token);
  1043. HadError = true;
  1044. goto retry;
  1045. }
  1046. return Result;
  1047. }
  1048. void ModuleMapParser::skipUntil(MMToken::TokenKind K) {
  1049. unsigned braceDepth = 0;
  1050. unsigned squareDepth = 0;
  1051. do {
  1052. switch (Tok.Kind) {
  1053. case MMToken::EndOfFile:
  1054. return;
  1055. case MMToken::LBrace:
  1056. if (Tok.is(K) && braceDepth == 0 && squareDepth == 0)
  1057. return;
  1058. ++braceDepth;
  1059. break;
  1060. case MMToken::LSquare:
  1061. if (Tok.is(K) && braceDepth == 0 && squareDepth == 0)
  1062. return;
  1063. ++squareDepth;
  1064. break;
  1065. case MMToken::RBrace:
  1066. if (braceDepth > 0)
  1067. --braceDepth;
  1068. else if (Tok.is(K))
  1069. return;
  1070. break;
  1071. case MMToken::RSquare:
  1072. if (squareDepth > 0)
  1073. --squareDepth;
  1074. else if (Tok.is(K))
  1075. return;
  1076. break;
  1077. default:
  1078. if (braceDepth == 0 && squareDepth == 0 && Tok.is(K))
  1079. return;
  1080. break;
  1081. }
  1082. consumeToken();
  1083. } while (true);
  1084. }
  1085. /// \brief Parse a module-id.
  1086. ///
  1087. /// module-id:
  1088. /// identifier
  1089. /// identifier '.' module-id
  1090. ///
  1091. /// \returns true if an error occurred, false otherwise.
  1092. bool ModuleMapParser::parseModuleId(ModuleId &Id) {
  1093. Id.clear();
  1094. do {
  1095. if (Tok.is(MMToken::Identifier) || Tok.is(MMToken::StringLiteral)) {
  1096. Id.push_back(std::make_pair(Tok.getString(), Tok.getLocation()));
  1097. consumeToken();
  1098. } else {
  1099. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module_name);
  1100. return true;
  1101. }
  1102. if (!Tok.is(MMToken::Period))
  1103. break;
  1104. consumeToken();
  1105. } while (true);
  1106. return false;
  1107. }
  1108. namespace {
  1109. /// \brief Enumerates the known attributes.
  1110. enum AttributeKind {
  1111. /// \brief An unknown attribute.
  1112. AT_unknown,
  1113. /// \brief The 'system' attribute.
  1114. AT_system,
  1115. /// \brief The 'extern_c' attribute.
  1116. AT_extern_c,
  1117. /// \brief The 'exhaustive' attribute.
  1118. AT_exhaustive,
  1119. /// \brief The 'no_undeclared_includes' attribute.
  1120. AT_no_undeclared_includes
  1121. };
  1122. }
  1123. /// \brief Parse a module declaration.
  1124. ///
  1125. /// module-declaration:
  1126. /// 'extern' 'module' module-id string-literal
  1127. /// 'explicit'[opt] 'framework'[opt] 'module' module-id attributes[opt]
  1128. /// { module-member* }
  1129. ///
  1130. /// module-member:
  1131. /// requires-declaration
  1132. /// header-declaration
  1133. /// submodule-declaration
  1134. /// export-declaration
  1135. /// link-declaration
  1136. ///
  1137. /// submodule-declaration:
  1138. /// module-declaration
  1139. /// inferred-submodule-declaration
  1140. void ModuleMapParser::parseModuleDecl() {
  1141. assert(Tok.is(MMToken::ExplicitKeyword) || Tok.is(MMToken::ModuleKeyword) ||
  1142. Tok.is(MMToken::FrameworkKeyword) || Tok.is(MMToken::ExternKeyword));
  1143. if (Tok.is(MMToken::ExternKeyword)) {
  1144. parseExternModuleDecl();
  1145. return;
  1146. }
  1147. // Parse 'explicit' or 'framework' keyword, if present.
  1148. SourceLocation ExplicitLoc;
  1149. bool Explicit = false;
  1150. bool Framework = false;
  1151. // Parse 'explicit' keyword, if present.
  1152. if (Tok.is(MMToken::ExplicitKeyword)) {
  1153. ExplicitLoc = consumeToken();
  1154. Explicit = true;
  1155. }
  1156. // Parse 'framework' keyword, if present.
  1157. if (Tok.is(MMToken::FrameworkKeyword)) {
  1158. consumeToken();
  1159. Framework = true;
  1160. }
  1161. // Parse 'module' keyword.
  1162. if (!Tok.is(MMToken::ModuleKeyword)) {
  1163. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module);
  1164. consumeToken();
  1165. HadError = true;
  1166. return;
  1167. }
  1168. consumeToken(); // 'module' keyword
  1169. // If we have a wildcard for the module name, this is an inferred submodule.
  1170. // Parse it.
  1171. if (Tok.is(MMToken::Star))
  1172. return parseInferredModuleDecl(Framework, Explicit);
  1173. // Parse the module name.
  1174. ModuleId Id;
  1175. if (parseModuleId(Id)) {
  1176. HadError = true;
  1177. return;
  1178. }
  1179. if (ActiveModule) {
  1180. if (Id.size() > 1) {
  1181. Diags.Report(Id.front().second, diag::err_mmap_nested_submodule_id)
  1182. << SourceRange(Id.front().second, Id.back().second);
  1183. HadError = true;
  1184. return;
  1185. }
  1186. } else if (Id.size() == 1 && Explicit) {
  1187. // Top-level modules can't be explicit.
  1188. Diags.Report(ExplicitLoc, diag::err_mmap_explicit_top_level);
  1189. Explicit = false;
  1190. ExplicitLoc = SourceLocation();
  1191. HadError = true;
  1192. }
  1193. Module *PreviousActiveModule = ActiveModule;
  1194. if (Id.size() > 1) {
  1195. // This module map defines a submodule. Go find the module of which it
  1196. // is a submodule.
  1197. ActiveModule = nullptr;
  1198. const Module *TopLevelModule = nullptr;
  1199. for (unsigned I = 0, N = Id.size() - 1; I != N; ++I) {
  1200. if (Module *Next = Map.lookupModuleQualified(Id[I].first, ActiveModule)) {
  1201. if (I == 0)
  1202. TopLevelModule = Next;
  1203. ActiveModule = Next;
  1204. continue;
  1205. }
  1206. if (ActiveModule) {
  1207. Diags.Report(Id[I].second, diag::err_mmap_missing_module_qualified)
  1208. << Id[I].first
  1209. << ActiveModule->getTopLevelModule()->getFullModuleName();
  1210. } else {
  1211. Diags.Report(Id[I].second, diag::err_mmap_expected_module_name);
  1212. }
  1213. HadError = true;
  1214. return;
  1215. }
  1216. if (ModuleMapFile != Map.getContainingModuleMapFile(TopLevelModule)) {
  1217. assert(ModuleMapFile != Map.getModuleMapFileForUniquing(TopLevelModule) &&
  1218. "submodule defined in same file as 'module *' that allowed its "
  1219. "top-level module");
  1220. Map.addAdditionalModuleMapFile(TopLevelModule, ModuleMapFile);
  1221. }
  1222. }
  1223. StringRef ModuleName = Id.back().first;
  1224. SourceLocation ModuleNameLoc = Id.back().second;
  1225. // Parse the optional attribute list.
  1226. Attributes Attrs;
  1227. if (parseOptionalAttributes(Attrs))
  1228. return;
  1229. // Parse the opening brace.
  1230. if (!Tok.is(MMToken::LBrace)) {
  1231. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_lbrace)
  1232. << ModuleName;
  1233. HadError = true;
  1234. return;
  1235. }
  1236. SourceLocation LBraceLoc = consumeToken();
  1237. // Determine whether this (sub)module has already been defined.
  1238. if (Module *Existing = Map.lookupModuleQualified(ModuleName, ActiveModule)) {
  1239. if (Existing->DefinitionLoc.isInvalid() && !ActiveModule) {
  1240. // Skip the module definition.
  1241. skipUntil(MMToken::RBrace);
  1242. if (Tok.is(MMToken::RBrace))
  1243. consumeToken();
  1244. else {
  1245. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
  1246. Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
  1247. HadError = true;
  1248. }
  1249. return;
  1250. }
  1251. Diags.Report(ModuleNameLoc, diag::err_mmap_module_redefinition)
  1252. << ModuleName;
  1253. Diags.Report(Existing->DefinitionLoc, diag::note_mmap_prev_definition);
  1254. // Skip the module definition.
  1255. skipUntil(MMToken::RBrace);
  1256. if (Tok.is(MMToken::RBrace))
  1257. consumeToken();
  1258. HadError = true;
  1259. return;
  1260. }
  1261. // Start defining this module.
  1262. ActiveModule = Map.findOrCreateModule(ModuleName, ActiveModule, Framework,
  1263. Explicit).first;
  1264. ActiveModule->DefinitionLoc = ModuleNameLoc;
  1265. if (Attrs.IsSystem || IsSystem)
  1266. ActiveModule->IsSystem = true;
  1267. if (Attrs.IsExternC)
  1268. ActiveModule->IsExternC = true;
  1269. if (Attrs.NoUndeclaredIncludes ||
  1270. (!ActiveModule->Parent && ModuleName == "Darwin"))
  1271. ActiveModule->NoUndeclaredIncludes = true;
  1272. ActiveModule->Directory = Directory;
  1273. if (!ActiveModule->Parent) {
  1274. StringRef MapFileName(ModuleMapFile->getName());
  1275. if (MapFileName.endswith("module.private.modulemap") ||
  1276. MapFileName.endswith("module_private.map")) {
  1277. // Adding a top-level module from a private modulemap is likely a
  1278. // user error; we check to see if there's another top-level module
  1279. // defined in the non-private map in the same dir, and if so emit a
  1280. // warning.
  1281. for (auto E = Map.module_begin(); E != Map.module_end(); ++E) {
  1282. auto const *M = E->getValue();
  1283. if (!M->Parent &&
  1284. M->Directory == ActiveModule->Directory &&
  1285. M->Name != ActiveModule->Name) {
  1286. Diags.Report(ActiveModule->DefinitionLoc,
  1287. diag::warn_mmap_mismatched_top_level_private)
  1288. << ActiveModule->Name << M->Name;
  1289. // The pattern we're defending against here is typically due to
  1290. // a module named FooPrivate which is supposed to be a submodule
  1291. // called Foo.Private. Emit a fixit in that case.
  1292. auto D =
  1293. Diags.Report(ActiveModule->DefinitionLoc,
  1294. diag::note_mmap_rename_top_level_private_as_submodule);
  1295. D << ActiveModule->Name << M->Name;
  1296. StringRef Bad(ActiveModule->Name);
  1297. if (Bad.consume_back("Private")) {
  1298. SmallString<128> Fixed = Bad;
  1299. Fixed.append(".Private");
  1300. D << FixItHint::CreateReplacement(ActiveModule->DefinitionLoc,
  1301. Fixed);
  1302. }
  1303. break;
  1304. }
  1305. }
  1306. }
  1307. }
  1308. bool Done = false;
  1309. do {
  1310. switch (Tok.Kind) {
  1311. case MMToken::EndOfFile:
  1312. case MMToken::RBrace:
  1313. Done = true;
  1314. break;
  1315. case MMToken::ConfigMacros:
  1316. parseConfigMacros();
  1317. break;
  1318. case MMToken::Conflict:
  1319. parseConflict();
  1320. break;
  1321. case MMToken::ExplicitKeyword:
  1322. case MMToken::ExternKeyword:
  1323. case MMToken::FrameworkKeyword:
  1324. case MMToken::ModuleKeyword:
  1325. parseModuleDecl();
  1326. break;
  1327. case MMToken::ExportKeyword:
  1328. parseExportDecl();
  1329. break;
  1330. case MMToken::UseKeyword:
  1331. parseUseDecl();
  1332. break;
  1333. case MMToken::RequiresKeyword:
  1334. parseRequiresDecl();
  1335. break;
  1336. case MMToken::TextualKeyword:
  1337. parseHeaderDecl(MMToken::TextualKeyword, consumeToken());
  1338. break;
  1339. case MMToken::UmbrellaKeyword: {
  1340. SourceLocation UmbrellaLoc = consumeToken();
  1341. if (Tok.is(MMToken::HeaderKeyword))
  1342. parseHeaderDecl(MMToken::UmbrellaKeyword, UmbrellaLoc);
  1343. else
  1344. parseUmbrellaDirDecl(UmbrellaLoc);
  1345. break;
  1346. }
  1347. case MMToken::ExcludeKeyword:
  1348. parseHeaderDecl(MMToken::ExcludeKeyword, consumeToken());
  1349. break;
  1350. case MMToken::PrivateKeyword:
  1351. parseHeaderDecl(MMToken::PrivateKeyword, consumeToken());
  1352. break;
  1353. case MMToken::HeaderKeyword:
  1354. parseHeaderDecl(MMToken::HeaderKeyword, consumeToken());
  1355. break;
  1356. case MMToken::LinkKeyword:
  1357. parseLinkDecl();
  1358. break;
  1359. default:
  1360. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_member);
  1361. consumeToken();
  1362. break;
  1363. }
  1364. } while (!Done);
  1365. if (Tok.is(MMToken::RBrace))
  1366. consumeToken();
  1367. else {
  1368. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
  1369. Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
  1370. HadError = true;
  1371. }
  1372. // If the active module is a top-level framework, and there are no link
  1373. // libraries, automatically link against the framework.
  1374. if (ActiveModule->IsFramework && !ActiveModule->isSubFramework() &&
  1375. ActiveModule->LinkLibraries.empty()) {
  1376. inferFrameworkLink(ActiveModule, Directory, SourceMgr.getFileManager());
  1377. }
  1378. // If the module meets all requirements but is still unavailable, mark the
  1379. // whole tree as unavailable to prevent it from building.
  1380. if (!ActiveModule->IsAvailable && !ActiveModule->IsMissingRequirement &&
  1381. ActiveModule->Parent) {
  1382. ActiveModule->getTopLevelModule()->markUnavailable();
  1383. ActiveModule->getTopLevelModule()->MissingHeaders.append(
  1384. ActiveModule->MissingHeaders.begin(), ActiveModule->MissingHeaders.end());
  1385. }
  1386. // We're done parsing this module. Pop back to the previous module.
  1387. ActiveModule = PreviousActiveModule;
  1388. }
  1389. /// \brief Parse an extern module declaration.
  1390. ///
  1391. /// extern module-declaration:
  1392. /// 'extern' 'module' module-id string-literal
  1393. void ModuleMapParser::parseExternModuleDecl() {
  1394. assert(Tok.is(MMToken::ExternKeyword));
  1395. SourceLocation ExternLoc = consumeToken(); // 'extern' keyword
  1396. // Parse 'module' keyword.
  1397. if (!Tok.is(MMToken::ModuleKeyword)) {
  1398. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module);
  1399. consumeToken();
  1400. HadError = true;
  1401. return;
  1402. }
  1403. consumeToken(); // 'module' keyword
  1404. // Parse the module name.
  1405. ModuleId Id;
  1406. if (parseModuleId(Id)) {
  1407. HadError = true;
  1408. return;
  1409. }
  1410. // Parse the referenced module map file name.
  1411. if (!Tok.is(MMToken::StringLiteral)) {
  1412. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_mmap_file);
  1413. HadError = true;
  1414. return;
  1415. }
  1416. std::string FileName = Tok.getString();
  1417. consumeToken(); // filename
  1418. StringRef FileNameRef = FileName;
  1419. SmallString<128> ModuleMapFileName;
  1420. if (llvm::sys::path::is_relative(FileNameRef)) {
  1421. ModuleMapFileName += Directory->getName();
  1422. llvm::sys::path::append(ModuleMapFileName, FileName);
  1423. FileNameRef = ModuleMapFileName;
  1424. }
  1425. if (const FileEntry *File = SourceMgr.getFileManager().getFile(FileNameRef))
  1426. Map.parseModuleMapFile(
  1427. File, /*IsSystem=*/false,
  1428. Map.HeaderInfo.getHeaderSearchOpts().ModuleMapFileHomeIsCwd
  1429. ? Directory
  1430. : File->getDir(), ExternLoc);
  1431. }
  1432. /// Whether to add the requirement \p Feature to the module \p M.
  1433. ///
  1434. /// This preserves backwards compatibility for two hacks in the Darwin system
  1435. /// module map files:
  1436. ///
  1437. /// 1. The use of 'requires excluded' to make headers non-modular, which
  1438. /// should really be mapped to 'textual' now that we have this feature. We
  1439. /// drop the 'excluded' requirement, and set \p IsRequiresExcludedHack to
  1440. /// true. Later, this bit will be used to map all the headers inside this
  1441. /// module to 'textual'.
  1442. ///
  1443. /// This affects Darwin.C.excluded (for assert.h) and Tcl.Private.
  1444. ///
  1445. /// 2. Removes a bogus cplusplus requirement from IOKit.avc. This requirement
  1446. /// was never correct and causes issues now that we check it, so drop it.
  1447. static bool shouldAddRequirement(Module *M, StringRef Feature,
  1448. bool &IsRequiresExcludedHack) {
  1449. if (Feature == "excluded" &&
  1450. (M->fullModuleNameIs({"Darwin", "C", "excluded"}) ||
  1451. M->fullModuleNameIs({"Tcl", "Private"}))) {
  1452. IsRequiresExcludedHack = true;
  1453. return false;
  1454. } else if (Feature == "cplusplus" && M->fullModuleNameIs({"IOKit", "avc"})) {
  1455. return false;
  1456. }
  1457. return true;
  1458. }
  1459. /// \brief Parse a requires declaration.
  1460. ///
  1461. /// requires-declaration:
  1462. /// 'requires' feature-list
  1463. ///
  1464. /// feature-list:
  1465. /// feature ',' feature-list
  1466. /// feature
  1467. ///
  1468. /// feature:
  1469. /// '!'[opt] identifier
  1470. void ModuleMapParser::parseRequiresDecl() {
  1471. assert(Tok.is(MMToken::RequiresKeyword));
  1472. // Parse 'requires' keyword.
  1473. consumeToken();
  1474. // Parse the feature-list.
  1475. do {
  1476. bool RequiredState = true;
  1477. if (Tok.is(MMToken::Exclaim)) {
  1478. RequiredState = false;
  1479. consumeToken();
  1480. }
  1481. if (!Tok.is(MMToken::Identifier)) {
  1482. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_feature);
  1483. HadError = true;
  1484. return;
  1485. }
  1486. // Consume the feature name.
  1487. std::string Feature = Tok.getString();
  1488. consumeToken();
  1489. bool IsRequiresExcludedHack = false;
  1490. bool ShouldAddRequirement =
  1491. shouldAddRequirement(ActiveModule, Feature, IsRequiresExcludedHack);
  1492. if (IsRequiresExcludedHack)
  1493. UsesRequiresExcludedHack.insert(ActiveModule);
  1494. if (ShouldAddRequirement) {
  1495. // Add this feature.
  1496. ActiveModule->addRequirement(Feature, RequiredState, Map.LangOpts,
  1497. *Map.Target);
  1498. }
  1499. if (!Tok.is(MMToken::Comma))
  1500. break;
  1501. // Consume the comma.
  1502. consumeToken();
  1503. } while (true);
  1504. }
  1505. /// \brief Append to \p Paths the set of paths needed to get to the
  1506. /// subframework in which the given module lives.
  1507. static void appendSubframeworkPaths(Module *Mod,
  1508. SmallVectorImpl<char> &Path) {
  1509. // Collect the framework names from the given module to the top-level module.
  1510. SmallVector<StringRef, 2> Paths;
  1511. for (; Mod; Mod = Mod->Parent) {
  1512. if (Mod->IsFramework)
  1513. Paths.push_back(Mod->Name);
  1514. }
  1515. if (Paths.empty())
  1516. return;
  1517. // Add Frameworks/Name.framework for each subframework.
  1518. for (unsigned I = Paths.size() - 1; I != 0; --I)
  1519. llvm::sys::path::append(Path, "Frameworks", Paths[I-1] + ".framework");
  1520. }
  1521. /// \brief Parse a header declaration.
  1522. ///
  1523. /// header-declaration:
  1524. /// 'textual'[opt] 'header' string-literal
  1525. /// 'private' 'textual'[opt] 'header' string-literal
  1526. /// 'exclude' 'header' string-literal
  1527. /// 'umbrella' 'header' string-literal
  1528. ///
  1529. /// FIXME: Support 'private textual header'.
  1530. void ModuleMapParser::parseHeaderDecl(MMToken::TokenKind LeadingToken,
  1531. SourceLocation LeadingLoc) {
  1532. // We've already consumed the first token.
  1533. ModuleMap::ModuleHeaderRole Role = ModuleMap::NormalHeader;
  1534. if (LeadingToken == MMToken::PrivateKeyword) {
  1535. Role = ModuleMap::PrivateHeader;
  1536. // 'private' may optionally be followed by 'textual'.
  1537. if (Tok.is(MMToken::TextualKeyword)) {
  1538. LeadingToken = Tok.Kind;
  1539. consumeToken();
  1540. }
  1541. }
  1542. if (LeadingToken == MMToken::TextualKeyword)
  1543. Role = ModuleMap::ModuleHeaderRole(Role | ModuleMap::TextualHeader);
  1544. if (UsesRequiresExcludedHack.count(ActiveModule)) {
  1545. // Mark this header 'textual' (see doc comment for
  1546. // Module::UsesRequiresExcludedHack).
  1547. Role = ModuleMap::ModuleHeaderRole(Role | ModuleMap::TextualHeader);
  1548. }
  1549. if (LeadingToken != MMToken::HeaderKeyword) {
  1550. if (!Tok.is(MMToken::HeaderKeyword)) {
  1551. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
  1552. << (LeadingToken == MMToken::PrivateKeyword ? "private" :
  1553. LeadingToken == MMToken::ExcludeKeyword ? "exclude" :
  1554. LeadingToken == MMToken::TextualKeyword ? "textual" : "umbrella");
  1555. return;
  1556. }
  1557. consumeToken();
  1558. }
  1559. // Parse the header name.
  1560. if (!Tok.is(MMToken::StringLiteral)) {
  1561. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
  1562. << "header";
  1563. HadError = true;
  1564. return;
  1565. }
  1566. Module::UnresolvedHeaderDirective Header;
  1567. Header.FileName = Tok.getString();
  1568. Header.FileNameLoc = consumeToken();
  1569. // Check whether we already have an umbrella.
  1570. if (LeadingToken == MMToken::UmbrellaKeyword && ActiveModule->Umbrella) {
  1571. Diags.Report(Header.FileNameLoc, diag::err_mmap_umbrella_clash)
  1572. << ActiveModule->getFullModuleName();
  1573. HadError = true;
  1574. return;
  1575. }
  1576. // Look for this file.
  1577. const FileEntry *File = nullptr;
  1578. const FileEntry *BuiltinFile = nullptr;
  1579. SmallString<128> RelativePathName;
  1580. if (llvm::sys::path::is_absolute(Header.FileName)) {
  1581. RelativePathName = Header.FileName;
  1582. File = SourceMgr.getFileManager().getFile(RelativePathName);
  1583. } else {
  1584. // Search for the header file within the search directory.
  1585. SmallString<128> FullPathName(Directory->getName());
  1586. unsigned FullPathLength = FullPathName.size();
  1587. if (ActiveModule->isPartOfFramework()) {
  1588. appendSubframeworkPaths(ActiveModule, RelativePathName);
  1589. // Check whether this file is in the public headers.
  1590. llvm::sys::path::append(RelativePathName, "Headers", Header.FileName);
  1591. llvm::sys::path::append(FullPathName, RelativePathName);
  1592. File = SourceMgr.getFileManager().getFile(FullPathName);
  1593. if (!File) {
  1594. // Check whether this file is in the private headers.
  1595. // FIXME: Should we retain the subframework paths here?
  1596. RelativePathName.clear();
  1597. FullPathName.resize(FullPathLength);
  1598. llvm::sys::path::append(RelativePathName, "PrivateHeaders",
  1599. Header.FileName);
  1600. llvm::sys::path::append(FullPathName, RelativePathName);
  1601. File = SourceMgr.getFileManager().getFile(FullPathName);
  1602. }
  1603. } else {
  1604. // Lookup for normal headers.
  1605. llvm::sys::path::append(RelativePathName, Header.FileName);
  1606. llvm::sys::path::append(FullPathName, RelativePathName);
  1607. File = SourceMgr.getFileManager().getFile(FullPathName);
  1608. // If this is a system module with a top-level header, this header
  1609. // may have a counterpart (or replacement) in the set of headers
  1610. // supplied by Clang. Find that builtin header.
  1611. if (ActiveModule->IsSystem && LeadingToken != MMToken::UmbrellaKeyword &&
  1612. BuiltinIncludeDir && BuiltinIncludeDir != Directory &&
  1613. ModuleMap::isBuiltinHeader(Header.FileName)) {
  1614. SmallString<128> BuiltinPathName(BuiltinIncludeDir->getName());
  1615. llvm::sys::path::append(BuiltinPathName, Header.FileName);
  1616. BuiltinFile = SourceMgr.getFileManager().getFile(BuiltinPathName);
  1617. // If Clang supplies this header but the underlying system does not,
  1618. // just silently swap in our builtin version. Otherwise, we'll end
  1619. // up adding both (later).
  1620. if (BuiltinFile && !File) {
  1621. File = BuiltinFile;
  1622. RelativePathName = BuiltinPathName;
  1623. BuiltinFile = nullptr;
  1624. }
  1625. }
  1626. }
  1627. }
  1628. // FIXME: We shouldn't be eagerly stat'ing every file named in a module map.
  1629. // Come up with a lazy way to do this.
  1630. if (File) {
  1631. if (LeadingToken == MMToken::UmbrellaKeyword) {
  1632. const DirectoryEntry *UmbrellaDir = File->getDir();
  1633. if (Module *UmbrellaModule = Map.UmbrellaDirs[UmbrellaDir]) {
  1634. Diags.Report(LeadingLoc, diag::err_mmap_umbrella_clash)
  1635. << UmbrellaModule->getFullModuleName();
  1636. HadError = true;
  1637. } else {
  1638. // Record this umbrella header.
  1639. Map.setUmbrellaHeader(ActiveModule, File, RelativePathName.str());
  1640. }
  1641. } else if (LeadingToken == MMToken::ExcludeKeyword) {
  1642. Module::Header H = {RelativePathName.str(), File};
  1643. Map.excludeHeader(ActiveModule, H);
  1644. } else {
  1645. // If there is a builtin counterpart to this file, add it now so it can
  1646. // wrap the system header.
  1647. if (BuiltinFile) {
  1648. // FIXME: Taking the name from the FileEntry is unstable and can give
  1649. // different results depending on how we've previously named that file
  1650. // in this build.
  1651. Module::Header H = { BuiltinFile->getName(), BuiltinFile };
  1652. Map.addHeader(ActiveModule, H, Role);
  1653. // If we have both a builtin and system version of the file, the
  1654. // builtin version may want to inject macros into the system header, so
  1655. // force the system header to be treated as a textual header in this
  1656. // case.
  1657. Role = ModuleMap::ModuleHeaderRole(Role | ModuleMap::TextualHeader);
  1658. }
  1659. // Record this header.
  1660. Module::Header H = { RelativePathName.str(), File };
  1661. Map.addHeader(ActiveModule, H, Role);
  1662. }
  1663. } else if (LeadingToken != MMToken::ExcludeKeyword) {
  1664. // Ignore excluded header files. They're optional anyway.
  1665. // If we find a module that has a missing header, we mark this module as
  1666. // unavailable and store the header directive for displaying diagnostics.
  1667. Header.IsUmbrella = LeadingToken == MMToken::UmbrellaKeyword;
  1668. ActiveModule->markUnavailable();
  1669. ActiveModule->MissingHeaders.push_back(Header);
  1670. }
  1671. }
  1672. static int compareModuleHeaders(const Module::Header *A,
  1673. const Module::Header *B) {
  1674. return A->NameAsWritten.compare(B->NameAsWritten);
  1675. }
  1676. /// \brief Parse an umbrella directory declaration.
  1677. ///
  1678. /// umbrella-dir-declaration:
  1679. /// umbrella string-literal
  1680. void ModuleMapParser::parseUmbrellaDirDecl(SourceLocation UmbrellaLoc) {
  1681. // Parse the directory name.
  1682. if (!Tok.is(MMToken::StringLiteral)) {
  1683. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
  1684. << "umbrella";
  1685. HadError = true;
  1686. return;
  1687. }
  1688. std::string DirName = Tok.getString();
  1689. SourceLocation DirNameLoc = consumeToken();
  1690. // Check whether we already have an umbrella.
  1691. if (ActiveModule->Umbrella) {
  1692. Diags.Report(DirNameLoc, diag::err_mmap_umbrella_clash)
  1693. << ActiveModule->getFullModuleName();
  1694. HadError = true;
  1695. return;
  1696. }
  1697. // Look for this file.
  1698. const DirectoryEntry *Dir = nullptr;
  1699. if (llvm::sys::path::is_absolute(DirName))
  1700. Dir = SourceMgr.getFileManager().getDirectory(DirName);
  1701. else {
  1702. SmallString<128> PathName;
  1703. PathName = Directory->getName();
  1704. llvm::sys::path::append(PathName, DirName);
  1705. Dir = SourceMgr.getFileManager().getDirectory(PathName);
  1706. }
  1707. if (!Dir) {
  1708. Diags.Report(DirNameLoc, diag::err_mmap_umbrella_dir_not_found)
  1709. << DirName;
  1710. HadError = true;
  1711. return;
  1712. }
  1713. if (UsesRequiresExcludedHack.count(ActiveModule)) {
  1714. // Mark this header 'textual' (see doc comment for
  1715. // ModuleMapParser::UsesRequiresExcludedHack). Although iterating over the
  1716. // directory is relatively expensive, in practice this only applies to the
  1717. // uncommonly used Tcl module on Darwin platforms.
  1718. std::error_code EC;
  1719. SmallVector<Module::Header, 6> Headers;
  1720. vfs::FileSystem &FS = *SourceMgr.getFileManager().getVirtualFileSystem();
  1721. for (vfs::recursive_directory_iterator I(FS, Dir->getName(), EC), E;
  1722. I != E && !EC; I.increment(EC)) {
  1723. if (const FileEntry *FE =
  1724. SourceMgr.getFileManager().getFile(I->getName())) {
  1725. Module::Header Header = {I->getName(), FE};
  1726. Headers.push_back(std::move(Header));
  1727. }
  1728. }
  1729. // Sort header paths so that the pcm doesn't depend on iteration order.
  1730. llvm::array_pod_sort(Headers.begin(), Headers.end(), compareModuleHeaders);
  1731. for (auto &Header : Headers)
  1732. Map.addHeader(ActiveModule, std::move(Header), ModuleMap::TextualHeader);
  1733. return;
  1734. }
  1735. if (Module *OwningModule = Map.UmbrellaDirs[Dir]) {
  1736. Diags.Report(UmbrellaLoc, diag::err_mmap_umbrella_clash)
  1737. << OwningModule->getFullModuleName();
  1738. HadError = true;
  1739. return;
  1740. }
  1741. // Record this umbrella directory.
  1742. Map.setUmbrellaDir(ActiveModule, Dir, DirName);
  1743. }
  1744. /// \brief Parse a module export declaration.
  1745. ///
  1746. /// export-declaration:
  1747. /// 'export' wildcard-module-id
  1748. ///
  1749. /// wildcard-module-id:
  1750. /// identifier
  1751. /// '*'
  1752. /// identifier '.' wildcard-module-id
  1753. void ModuleMapParser::parseExportDecl() {
  1754. assert(Tok.is(MMToken::ExportKeyword));
  1755. SourceLocation ExportLoc = consumeToken();
  1756. // Parse the module-id with an optional wildcard at the end.
  1757. ModuleId ParsedModuleId;
  1758. bool Wildcard = false;
  1759. do {
  1760. // FIXME: Support string-literal module names here.
  1761. if (Tok.is(MMToken::Identifier)) {
  1762. ParsedModuleId.push_back(std::make_pair(Tok.getString(),
  1763. Tok.getLocation()));
  1764. consumeToken();
  1765. if (Tok.is(MMToken::Period)) {
  1766. consumeToken();
  1767. continue;
  1768. }
  1769. break;
  1770. }
  1771. if(Tok.is(MMToken::Star)) {
  1772. Wildcard = true;
  1773. consumeToken();
  1774. break;
  1775. }
  1776. Diags.Report(Tok.getLocation(), diag::err_mmap_module_id);
  1777. HadError = true;
  1778. return;
  1779. } while (true);
  1780. Module::UnresolvedExportDecl Unresolved = {
  1781. ExportLoc, ParsedModuleId, Wildcard
  1782. };
  1783. ActiveModule->UnresolvedExports.push_back(Unresolved);
  1784. }
  1785. /// \brief Parse a module use declaration.
  1786. ///
  1787. /// use-declaration:
  1788. /// 'use' wildcard-module-id
  1789. void ModuleMapParser::parseUseDecl() {
  1790. assert(Tok.is(MMToken::UseKeyword));
  1791. auto KWLoc = consumeToken();
  1792. // Parse the module-id.
  1793. ModuleId ParsedModuleId;
  1794. parseModuleId(ParsedModuleId);
  1795. if (ActiveModule->Parent)
  1796. Diags.Report(KWLoc, diag::err_mmap_use_decl_submodule);
  1797. else
  1798. ActiveModule->UnresolvedDirectUses.push_back(ParsedModuleId);
  1799. }
  1800. /// \brief Parse a link declaration.
  1801. ///
  1802. /// module-declaration:
  1803. /// 'link' 'framework'[opt] string-literal
  1804. void ModuleMapParser::parseLinkDecl() {
  1805. assert(Tok.is(MMToken::LinkKeyword));
  1806. SourceLocation LinkLoc = consumeToken();
  1807. // Parse the optional 'framework' keyword.
  1808. bool IsFramework = false;
  1809. if (Tok.is(MMToken::FrameworkKeyword)) {
  1810. consumeToken();
  1811. IsFramework = true;
  1812. }
  1813. // Parse the library name
  1814. if (!Tok.is(MMToken::StringLiteral)) {
  1815. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_library_name)
  1816. << IsFramework << SourceRange(LinkLoc);
  1817. HadError = true;
  1818. return;
  1819. }
  1820. std::string LibraryName = Tok.getString();
  1821. consumeToken();
  1822. ActiveModule->LinkLibraries.push_back(Module::LinkLibrary(LibraryName,
  1823. IsFramework));
  1824. }
  1825. /// \brief Parse a configuration macro declaration.
  1826. ///
  1827. /// module-declaration:
  1828. /// 'config_macros' attributes[opt] config-macro-list?
  1829. ///
  1830. /// config-macro-list:
  1831. /// identifier (',' identifier)?
  1832. void ModuleMapParser::parseConfigMacros() {
  1833. assert(Tok.is(MMToken::ConfigMacros));
  1834. SourceLocation ConfigMacrosLoc = consumeToken();
  1835. // Only top-level modules can have configuration macros.
  1836. if (ActiveModule->Parent) {
  1837. Diags.Report(ConfigMacrosLoc, diag::err_mmap_config_macro_submodule);
  1838. }
  1839. // Parse the optional attributes.
  1840. Attributes Attrs;
  1841. if (parseOptionalAttributes(Attrs))
  1842. return;
  1843. if (Attrs.IsExhaustive && !ActiveModule->Parent) {
  1844. ActiveModule->ConfigMacrosExhaustive = true;
  1845. }
  1846. // If we don't have an identifier, we're done.
  1847. // FIXME: Support macros with the same name as a keyword here.
  1848. if (!Tok.is(MMToken::Identifier))
  1849. return;
  1850. // Consume the first identifier.
  1851. if (!ActiveModule->Parent) {
  1852. ActiveModule->ConfigMacros.push_back(Tok.getString().str());
  1853. }
  1854. consumeToken();
  1855. do {
  1856. // If there's a comma, consume it.
  1857. if (!Tok.is(MMToken::Comma))
  1858. break;
  1859. consumeToken();
  1860. // We expect to see a macro name here.
  1861. // FIXME: Support macros with the same name as a keyword here.
  1862. if (!Tok.is(MMToken::Identifier)) {
  1863. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_config_macro);
  1864. break;
  1865. }
  1866. // Consume the macro name.
  1867. if (!ActiveModule->Parent) {
  1868. ActiveModule->ConfigMacros.push_back(Tok.getString().str());
  1869. }
  1870. consumeToken();
  1871. } while (true);
  1872. }
  1873. /// \brief Format a module-id into a string.
  1874. static std::string formatModuleId(const ModuleId &Id) {
  1875. std::string result;
  1876. {
  1877. llvm::raw_string_ostream OS(result);
  1878. for (unsigned I = 0, N = Id.size(); I != N; ++I) {
  1879. if (I)
  1880. OS << ".";
  1881. OS << Id[I].first;
  1882. }
  1883. }
  1884. return result;
  1885. }
  1886. /// \brief Parse a conflict declaration.
  1887. ///
  1888. /// module-declaration:
  1889. /// 'conflict' module-id ',' string-literal
  1890. void ModuleMapParser::parseConflict() {
  1891. assert(Tok.is(MMToken::Conflict));
  1892. SourceLocation ConflictLoc = consumeToken();
  1893. Module::UnresolvedConflict Conflict;
  1894. // Parse the module-id.
  1895. if (parseModuleId(Conflict.Id))
  1896. return;
  1897. // Parse the ','.
  1898. if (!Tok.is(MMToken::Comma)) {
  1899. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_conflicts_comma)
  1900. << SourceRange(ConflictLoc);
  1901. return;
  1902. }
  1903. consumeToken();
  1904. // Parse the message.
  1905. if (!Tok.is(MMToken::StringLiteral)) {
  1906. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_conflicts_message)
  1907. << formatModuleId(Conflict.Id);
  1908. return;
  1909. }
  1910. Conflict.Message = Tok.getString().str();
  1911. consumeToken();
  1912. // Add this unresolved conflict.
  1913. ActiveModule->UnresolvedConflicts.push_back(Conflict);
  1914. }
  1915. /// \brief Parse an inferred module declaration (wildcard modules).
  1916. ///
  1917. /// module-declaration:
  1918. /// 'explicit'[opt] 'framework'[opt] 'module' * attributes[opt]
  1919. /// { inferred-module-member* }
  1920. ///
  1921. /// inferred-module-member:
  1922. /// 'export' '*'
  1923. /// 'exclude' identifier
  1924. void ModuleMapParser::parseInferredModuleDecl(bool Framework, bool Explicit) {
  1925. assert(Tok.is(MMToken::Star));
  1926. SourceLocation StarLoc = consumeToken();
  1927. bool Failed = false;
  1928. // Inferred modules must be submodules.
  1929. if (!ActiveModule && !Framework) {
  1930. Diags.Report(StarLoc, diag::err_mmap_top_level_inferred_submodule);
  1931. Failed = true;
  1932. }
  1933. if (ActiveModule) {
  1934. // Inferred modules must have umbrella directories.
  1935. if (!Failed && ActiveModule->IsAvailable &&
  1936. !ActiveModule->getUmbrellaDir()) {
  1937. Diags.Report(StarLoc, diag::err_mmap_inferred_no_umbrella);
  1938. Failed = true;
  1939. }
  1940. // Check for redefinition of an inferred module.
  1941. if (!Failed && ActiveModule->InferSubmodules) {
  1942. Diags.Report(StarLoc, diag::err_mmap_inferred_redef);
  1943. if (ActiveModule->InferredSubmoduleLoc.isValid())
  1944. Diags.Report(ActiveModule->InferredSubmoduleLoc,
  1945. diag::note_mmap_prev_definition);
  1946. Failed = true;
  1947. }
  1948. // Check for the 'framework' keyword, which is not permitted here.
  1949. if (Framework) {
  1950. Diags.Report(StarLoc, diag::err_mmap_inferred_framework_submodule);
  1951. Framework = false;
  1952. }
  1953. } else if (Explicit) {
  1954. Diags.Report(StarLoc, diag::err_mmap_explicit_inferred_framework);
  1955. Explicit = false;
  1956. }
  1957. // If there were any problems with this inferred submodule, skip its body.
  1958. if (Failed) {
  1959. if (Tok.is(MMToken::LBrace)) {
  1960. consumeToken();
  1961. skipUntil(MMToken::RBrace);
  1962. if (Tok.is(MMToken::RBrace))
  1963. consumeToken();
  1964. }
  1965. HadError = true;
  1966. return;
  1967. }
  1968. // Parse optional attributes.
  1969. Attributes Attrs;
  1970. if (parseOptionalAttributes(Attrs))
  1971. return;
  1972. if (ActiveModule) {
  1973. // Note that we have an inferred submodule.
  1974. ActiveModule->InferSubmodules = true;
  1975. ActiveModule->InferredSubmoduleLoc = StarLoc;
  1976. ActiveModule->InferExplicitSubmodules = Explicit;
  1977. } else {
  1978. // We'll be inferring framework modules for this directory.
  1979. Map.InferredDirectories[Directory].InferModules = true;
  1980. Map.InferredDirectories[Directory].Attrs = Attrs;
  1981. Map.InferredDirectories[Directory].ModuleMapFile = ModuleMapFile;
  1982. // FIXME: Handle the 'framework' keyword.
  1983. }
  1984. // Parse the opening brace.
  1985. if (!Tok.is(MMToken::LBrace)) {
  1986. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_lbrace_wildcard);
  1987. HadError = true;
  1988. return;
  1989. }
  1990. SourceLocation LBraceLoc = consumeToken();
  1991. // Parse the body of the inferred submodule.
  1992. bool Done = false;
  1993. do {
  1994. switch (Tok.Kind) {
  1995. case MMToken::EndOfFile:
  1996. case MMToken::RBrace:
  1997. Done = true;
  1998. break;
  1999. case MMToken::ExcludeKeyword: {
  2000. if (ActiveModule) {
  2001. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member)
  2002. << (ActiveModule != nullptr);
  2003. consumeToken();
  2004. break;
  2005. }
  2006. consumeToken();
  2007. // FIXME: Support string-literal module names here.
  2008. if (!Tok.is(MMToken::Identifier)) {
  2009. Diags.Report(Tok.getLocation(), diag::err_mmap_missing_exclude_name);
  2010. break;
  2011. }
  2012. Map.InferredDirectories[Directory].ExcludedModules
  2013. .push_back(Tok.getString());
  2014. consumeToken();
  2015. break;
  2016. }
  2017. case MMToken::ExportKeyword:
  2018. if (!ActiveModule) {
  2019. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member)
  2020. << (ActiveModule != nullptr);
  2021. consumeToken();
  2022. break;
  2023. }
  2024. consumeToken();
  2025. if (Tok.is(MMToken::Star))
  2026. ActiveModule->InferExportWildcard = true;
  2027. else
  2028. Diags.Report(Tok.getLocation(),
  2029. diag::err_mmap_expected_export_wildcard);
  2030. consumeToken();
  2031. break;
  2032. case MMToken::ExplicitKeyword:
  2033. case MMToken::ModuleKeyword:
  2034. case MMToken::HeaderKeyword:
  2035. case MMToken::PrivateKeyword:
  2036. case MMToken::UmbrellaKeyword:
  2037. default:
  2038. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member)
  2039. << (ActiveModule != nullptr);
  2040. consumeToken();
  2041. break;
  2042. }
  2043. } while (!Done);
  2044. if (Tok.is(MMToken::RBrace))
  2045. consumeToken();
  2046. else {
  2047. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
  2048. Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
  2049. HadError = true;
  2050. }
  2051. }
  2052. /// \brief Parse optional attributes.
  2053. ///
  2054. /// attributes:
  2055. /// attribute attributes
  2056. /// attribute
  2057. ///
  2058. /// attribute:
  2059. /// [ identifier ]
  2060. ///
  2061. /// \param Attrs Will be filled in with the parsed attributes.
  2062. ///
  2063. /// \returns true if an error occurred, false otherwise.
  2064. bool ModuleMapParser::parseOptionalAttributes(Attributes &Attrs) {
  2065. bool HadError = false;
  2066. while (Tok.is(MMToken::LSquare)) {
  2067. // Consume the '['.
  2068. SourceLocation LSquareLoc = consumeToken();
  2069. // Check whether we have an attribute name here.
  2070. if (!Tok.is(MMToken::Identifier)) {
  2071. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_attribute);
  2072. skipUntil(MMToken::RSquare);
  2073. if (Tok.is(MMToken::RSquare))
  2074. consumeToken();
  2075. HadError = true;
  2076. }
  2077. // Decode the attribute name.
  2078. AttributeKind Attribute
  2079. = llvm::StringSwitch<AttributeKind>(Tok.getString())
  2080. .Case("exhaustive", AT_exhaustive)
  2081. .Case("extern_c", AT_extern_c)
  2082. .Case("no_undeclared_includes", AT_no_undeclared_includes)
  2083. .Case("system", AT_system)
  2084. .Default(AT_unknown);
  2085. switch (Attribute) {
  2086. case AT_unknown:
  2087. Diags.Report(Tok.getLocation(), diag::warn_mmap_unknown_attribute)
  2088. << Tok.getString();
  2089. break;
  2090. case AT_system:
  2091. Attrs.IsSystem = true;
  2092. break;
  2093. case AT_extern_c:
  2094. Attrs.IsExternC = true;
  2095. break;
  2096. case AT_exhaustive:
  2097. Attrs.IsExhaustive = true;
  2098. break;
  2099. case AT_no_undeclared_includes:
  2100. Attrs.NoUndeclaredIncludes = true;
  2101. break;
  2102. }
  2103. consumeToken();
  2104. // Consume the ']'.
  2105. if (!Tok.is(MMToken::RSquare)) {
  2106. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rsquare);
  2107. Diags.Report(LSquareLoc, diag::note_mmap_lsquare_match);
  2108. skipUntil(MMToken::RSquare);
  2109. HadError = true;
  2110. }
  2111. if (Tok.is(MMToken::RSquare))
  2112. consumeToken();
  2113. }
  2114. return HadError;
  2115. }
  2116. /// \brief Parse a module map file.
  2117. ///
  2118. /// module-map-file:
  2119. /// module-declaration*
  2120. bool ModuleMapParser::parseModuleMapFile() {
  2121. do {
  2122. switch (Tok.Kind) {
  2123. case MMToken::EndOfFile:
  2124. return HadError;
  2125. case MMToken::ExplicitKeyword:
  2126. case MMToken::ExternKeyword:
  2127. case MMToken::ModuleKeyword:
  2128. case MMToken::FrameworkKeyword:
  2129. parseModuleDecl();
  2130. break;
  2131. case MMToken::Comma:
  2132. case MMToken::ConfigMacros:
  2133. case MMToken::Conflict:
  2134. case MMToken::Exclaim:
  2135. case MMToken::ExcludeKeyword:
  2136. case MMToken::ExportKeyword:
  2137. case MMToken::HeaderKeyword:
  2138. case MMToken::Identifier:
  2139. case MMToken::LBrace:
  2140. case MMToken::LinkKeyword:
  2141. case MMToken::LSquare:
  2142. case MMToken::Period:
  2143. case MMToken::PrivateKeyword:
  2144. case MMToken::RBrace:
  2145. case MMToken::RSquare:
  2146. case MMToken::RequiresKeyword:
  2147. case MMToken::Star:
  2148. case MMToken::StringLiteral:
  2149. case MMToken::TextualKeyword:
  2150. case MMToken::UmbrellaKeyword:
  2151. case MMToken::UseKeyword:
  2152. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module);
  2153. HadError = true;
  2154. consumeToken();
  2155. break;
  2156. }
  2157. } while (true);
  2158. }
  2159. bool ModuleMap::parseModuleMapFile(const FileEntry *File, bool IsSystem,
  2160. const DirectoryEntry *Dir,
  2161. SourceLocation ExternModuleLoc) {
  2162. llvm::DenseMap<const FileEntry *, bool>::iterator Known
  2163. = ParsedModuleMap.find(File);
  2164. if (Known != ParsedModuleMap.end())
  2165. return Known->second;
  2166. assert(Target && "Missing target information");
  2167. auto FileCharacter = IsSystem ? SrcMgr::C_System : SrcMgr::C_User;
  2168. FileID ID = SourceMgr.createFileID(File, ExternModuleLoc, FileCharacter);
  2169. const llvm::MemoryBuffer *Buffer = SourceMgr.getBuffer(ID);
  2170. if (!Buffer)
  2171. return ParsedModuleMap[File] = true;
  2172. // Parse this module map file.
  2173. Lexer L(ID, SourceMgr.getBuffer(ID), SourceMgr, MMapLangOpts);
  2174. SourceLocation Start = L.getSourceLocation();
  2175. ModuleMapParser Parser(L, SourceMgr, Target, Diags, *this, File, Dir,
  2176. BuiltinIncludeDir, IsSystem);
  2177. bool Result = Parser.parseModuleMapFile();
  2178. ParsedModuleMap[File] = Result;
  2179. // Notify callbacks that we parsed it.
  2180. for (const auto &Cb : Callbacks)
  2181. Cb->moduleMapFileRead(Start, *File, IsSystem);
  2182. return Result;
  2183. }