ModuleMap.cpp 81 KB

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