ModuleMap.cpp 79 KB

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