ModuleMap.cpp 95 KB

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