ModuleMap.cpp 78 KB

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