ModuleMap.cpp 96 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988
  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/Lex/HeaderSearch.h"
  25. #include "clang/Lex/HeaderSearchOptions.h"
  26. #include "clang/Lex/LexDiagnostic.h"
  27. #include "clang/Lex/Lexer.h"
  28. #include "clang/Lex/LiteralSupport.h"
  29. #include "clang/Lex/Token.h"
  30. #include "llvm/ADT/DenseMap.h"
  31. #include "llvm/ADT/None.h"
  32. #include "llvm/ADT/STLExtras.h"
  33. #include "llvm/ADT/SmallPtrSet.h"
  34. #include "llvm/ADT/SmallString.h"
  35. #include "llvm/ADT/SmallVector.h"
  36. #include "llvm/ADT/StringMap.h"
  37. #include "llvm/ADT/StringRef.h"
  38. #include "llvm/ADT/StringSwitch.h"
  39. #include "llvm/Support/Allocator.h"
  40. #include "llvm/Support/Compiler.h"
  41. #include "llvm/Support/ErrorHandling.h"
  42. #include "llvm/Support/MemoryBuffer.h"
  43. #include "llvm/Support/Path.h"
  44. #include "llvm/Support/VirtualFileSystem.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. PendingSubmodules.emplace_back(
  704. new Module("<global>", Loc, nullptr, /*IsFramework*/ false,
  705. /*IsExplicit*/ true, NumCreatedModules++));
  706. PendingSubmodules.back()->Kind = Module::GlobalModuleFragment;
  707. return PendingSubmodules.back().get();
  708. }
  709. Module *ModuleMap::createModuleForInterfaceUnit(SourceLocation Loc,
  710. StringRef Name,
  711. Module *GlobalModule) {
  712. assert(LangOpts.CurrentModule == Name && "module name mismatch");
  713. assert(!Modules[Name] && "redefining existing module");
  714. auto *Result =
  715. new Module(Name, Loc, nullptr, /*IsFramework*/ false,
  716. /*IsExplicit*/ false, NumCreatedModules++);
  717. Result->Kind = Module::ModuleInterfaceUnit;
  718. Modules[Name] = SourceModule = Result;
  719. // Reparent the current global module fragment as a submodule of this module.
  720. for (auto &Submodule : PendingSubmodules) {
  721. Submodule->setParent(Result);
  722. Submodule.release(); // now owned by parent
  723. }
  724. PendingSubmodules.clear();
  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. Module *ModuleMap::createHeaderModule(StringRef Name,
  733. ArrayRef<Module::Header> Headers) {
  734. assert(LangOpts.CurrentModule == Name && "module name mismatch");
  735. assert(!Modules[Name] && "redefining existing module");
  736. auto *Result =
  737. new Module(Name, SourceLocation(), nullptr, /*IsFramework*/ false,
  738. /*IsExplicit*/ false, NumCreatedModules++);
  739. Result->Kind = Module::ModuleInterfaceUnit;
  740. Modules[Name] = SourceModule = Result;
  741. for (const Module::Header &H : Headers) {
  742. auto *M = new Module(H.NameAsWritten, SourceLocation(), Result,
  743. /*IsFramework*/ false,
  744. /*IsExplicit*/ true, NumCreatedModules++);
  745. // Header modules are implicitly 'export *'.
  746. M->Exports.push_back(Module::ExportDecl(nullptr, true));
  747. addHeader(M, H, NormalHeader);
  748. }
  749. return Result;
  750. }
  751. /// For a framework module, infer the framework against which we
  752. /// should link.
  753. static void inferFrameworkLink(Module *Mod, const DirectoryEntry *FrameworkDir,
  754. FileManager &FileMgr) {
  755. assert(Mod->IsFramework && "Can only infer linking for framework modules");
  756. assert(!Mod->isSubFramework() &&
  757. "Can only infer linking for top-level frameworks");
  758. SmallString<128> LibName;
  759. LibName += FrameworkDir->getName();
  760. llvm::sys::path::append(LibName, Mod->Name);
  761. // The library name of a framework has more than one possible extension since
  762. // the introduction of the text-based dynamic library format. We need to check
  763. // for both before we give up.
  764. for (const char *extension : {"", ".tbd"}) {
  765. llvm::sys::path::replace_extension(LibName, extension);
  766. if (FileMgr.getFile(LibName)) {
  767. Mod->LinkLibraries.push_back(Module::LinkLibrary(Mod->Name,
  768. /*IsFramework=*/true));
  769. return;
  770. }
  771. }
  772. }
  773. Module *ModuleMap::inferFrameworkModule(const DirectoryEntry *FrameworkDir,
  774. bool IsSystem, Module *Parent) {
  775. Attributes Attrs;
  776. Attrs.IsSystem = IsSystem;
  777. return inferFrameworkModule(FrameworkDir, Attrs, Parent);
  778. }
  779. Module *ModuleMap::inferFrameworkModule(const DirectoryEntry *FrameworkDir,
  780. Attributes Attrs, Module *Parent) {
  781. // Note: as an egregious but useful hack we use the real path here, because
  782. // we might be looking at an embedded framework that symlinks out to a
  783. // top-level framework, and we need to infer as if we were naming the
  784. // top-level framework.
  785. StringRef FrameworkDirName =
  786. SourceMgr.getFileManager().getCanonicalName(FrameworkDir);
  787. // In case this is a case-insensitive filesystem, use the canonical
  788. // directory name as the ModuleName, since modules are case-sensitive.
  789. // FIXME: we should be able to give a fix-it hint for the correct spelling.
  790. SmallString<32> ModuleNameStorage;
  791. StringRef ModuleName = sanitizeFilenameAsIdentifier(
  792. llvm::sys::path::stem(FrameworkDirName), ModuleNameStorage);
  793. // Check whether we've already found this module.
  794. if (Module *Mod = lookupModuleQualified(ModuleName, Parent))
  795. return Mod;
  796. FileManager &FileMgr = SourceMgr.getFileManager();
  797. // If the framework has a parent path from which we're allowed to infer
  798. // a framework module, do so.
  799. const FileEntry *ModuleMapFile = nullptr;
  800. if (!Parent) {
  801. // Determine whether we're allowed to infer a module map.
  802. bool canInfer = false;
  803. if (llvm::sys::path::has_parent_path(FrameworkDirName)) {
  804. // Figure out the parent path.
  805. StringRef Parent = llvm::sys::path::parent_path(FrameworkDirName);
  806. if (const DirectoryEntry *ParentDir = FileMgr.getDirectory(Parent)) {
  807. // Check whether we have already looked into the parent directory
  808. // for a module map.
  809. llvm::DenseMap<const DirectoryEntry *, InferredDirectory>::const_iterator
  810. inferred = InferredDirectories.find(ParentDir);
  811. if (inferred == InferredDirectories.end()) {
  812. // We haven't looked here before. Load a module map, if there is
  813. // one.
  814. bool IsFrameworkDir = Parent.endswith(".framework");
  815. if (const FileEntry *ModMapFile =
  816. HeaderInfo.lookupModuleMapFile(ParentDir, IsFrameworkDir)) {
  817. parseModuleMapFile(ModMapFile, Attrs.IsSystem, ParentDir);
  818. inferred = InferredDirectories.find(ParentDir);
  819. }
  820. if (inferred == InferredDirectories.end())
  821. inferred = InferredDirectories.insert(
  822. std::make_pair(ParentDir, InferredDirectory())).first;
  823. }
  824. if (inferred->second.InferModules) {
  825. // We're allowed to infer for this directory, but make sure it's okay
  826. // to infer this particular module.
  827. StringRef Name = llvm::sys::path::stem(FrameworkDirName);
  828. canInfer = std::find(inferred->second.ExcludedModules.begin(),
  829. inferred->second.ExcludedModules.end(),
  830. Name) == inferred->second.ExcludedModules.end();
  831. Attrs.IsSystem |= inferred->second.Attrs.IsSystem;
  832. Attrs.IsExternC |= inferred->second.Attrs.IsExternC;
  833. Attrs.IsExhaustive |= inferred->second.Attrs.IsExhaustive;
  834. Attrs.NoUndeclaredIncludes |=
  835. inferred->second.Attrs.NoUndeclaredIncludes;
  836. ModuleMapFile = inferred->second.ModuleMapFile;
  837. }
  838. }
  839. }
  840. // If we're not allowed to infer a framework module, don't.
  841. if (!canInfer)
  842. return nullptr;
  843. } else
  844. ModuleMapFile = getModuleMapFileForUniquing(Parent);
  845. // Look for an umbrella header.
  846. SmallString<128> UmbrellaName = StringRef(FrameworkDir->getName());
  847. llvm::sys::path::append(UmbrellaName, "Headers", ModuleName + ".h");
  848. const FileEntry *UmbrellaHeader = FileMgr.getFile(UmbrellaName);
  849. // FIXME: If there's no umbrella header, we could probably scan the
  850. // framework to load *everything*. But, it's not clear that this is a good
  851. // idea.
  852. if (!UmbrellaHeader)
  853. return nullptr;
  854. Module *Result = new Module(ModuleName, SourceLocation(), Parent,
  855. /*IsFramework=*/true, /*IsExplicit=*/false,
  856. NumCreatedModules++);
  857. InferredModuleAllowedBy[Result] = ModuleMapFile;
  858. Result->IsInferred = true;
  859. if (!Parent) {
  860. if (LangOpts.CurrentModule == ModuleName)
  861. SourceModule = Result;
  862. Modules[ModuleName] = Result;
  863. ModuleScopeIDs[Result] = CurrentModuleScopeID;
  864. }
  865. Result->IsSystem |= Attrs.IsSystem;
  866. Result->IsExternC |= Attrs.IsExternC;
  867. Result->ConfigMacrosExhaustive |= Attrs.IsExhaustive;
  868. Result->NoUndeclaredIncludes |= Attrs.NoUndeclaredIncludes;
  869. Result->Directory = FrameworkDir;
  870. // umbrella header "umbrella-header-name"
  871. //
  872. // The "Headers/" component of the name is implied because this is
  873. // a framework module.
  874. setUmbrellaHeader(Result, UmbrellaHeader, ModuleName + ".h");
  875. // export *
  876. Result->Exports.push_back(Module::ExportDecl(nullptr, true));
  877. // module * { export * }
  878. Result->InferSubmodules = true;
  879. Result->InferExportWildcard = true;
  880. // Look for subframeworks.
  881. std::error_code EC;
  882. SmallString<128> SubframeworksDirName
  883. = StringRef(FrameworkDir->getName());
  884. llvm::sys::path::append(SubframeworksDirName, "Frameworks");
  885. llvm::sys::path::native(SubframeworksDirName);
  886. llvm::vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
  887. for (llvm::vfs::directory_iterator
  888. Dir = FS.dir_begin(SubframeworksDirName, EC),
  889. DirEnd;
  890. Dir != DirEnd && !EC; Dir.increment(EC)) {
  891. if (!StringRef(Dir->path()).endswith(".framework"))
  892. continue;
  893. if (const DirectoryEntry *SubframeworkDir =
  894. FileMgr.getDirectory(Dir->path())) {
  895. // Note: as an egregious but useful hack, we use the real path here and
  896. // check whether it is actually a subdirectory of the parent directory.
  897. // This will not be the case if the 'subframework' is actually a symlink
  898. // out to a top-level framework.
  899. StringRef SubframeworkDirName = FileMgr.getCanonicalName(SubframeworkDir);
  900. bool FoundParent = false;
  901. do {
  902. // Get the parent directory name.
  903. SubframeworkDirName
  904. = llvm::sys::path::parent_path(SubframeworkDirName);
  905. if (SubframeworkDirName.empty())
  906. break;
  907. if (FileMgr.getDirectory(SubframeworkDirName) == FrameworkDir) {
  908. FoundParent = true;
  909. break;
  910. }
  911. } while (true);
  912. if (!FoundParent)
  913. continue;
  914. // FIXME: Do we want to warn about subframeworks without umbrella headers?
  915. inferFrameworkModule(SubframeworkDir, Attrs, Result);
  916. }
  917. }
  918. // If the module is a top-level framework, automatically link against the
  919. // framework.
  920. if (!Result->isSubFramework()) {
  921. inferFrameworkLink(Result, FrameworkDir, FileMgr);
  922. }
  923. return Result;
  924. }
  925. Module *ModuleMap::createShadowedModule(StringRef Name, bool IsFramework,
  926. Module *ShadowingModule) {
  927. // Create a new module with this name.
  928. Module *Result =
  929. new Module(Name, SourceLocation(), /*Parent=*/nullptr, IsFramework,
  930. /*IsExplicit=*/false, NumCreatedModules++);
  931. Result->ShadowingModule = ShadowingModule;
  932. Result->IsAvailable = false;
  933. ModuleScopeIDs[Result] = CurrentModuleScopeID;
  934. ShadowModules.push_back(Result);
  935. return Result;
  936. }
  937. void ModuleMap::setUmbrellaHeader(Module *Mod, const FileEntry *UmbrellaHeader,
  938. Twine NameAsWritten) {
  939. Headers[UmbrellaHeader].push_back(KnownHeader(Mod, NormalHeader));
  940. Mod->Umbrella = UmbrellaHeader;
  941. Mod->UmbrellaAsWritten = NameAsWritten.str();
  942. UmbrellaDirs[UmbrellaHeader->getDir()] = Mod;
  943. // Notify callbacks that we just added a new header.
  944. for (const auto &Cb : Callbacks)
  945. Cb->moduleMapAddUmbrellaHeader(&SourceMgr.getFileManager(), UmbrellaHeader);
  946. }
  947. void ModuleMap::setUmbrellaDir(Module *Mod, const DirectoryEntry *UmbrellaDir,
  948. Twine NameAsWritten) {
  949. Mod->Umbrella = UmbrellaDir;
  950. Mod->UmbrellaAsWritten = NameAsWritten.str();
  951. UmbrellaDirs[UmbrellaDir] = Mod;
  952. }
  953. void ModuleMap::addUnresolvedHeader(Module *Mod,
  954. Module::UnresolvedHeaderDirective Header,
  955. bool &NeedsFramework) {
  956. // If there is a builtin counterpart to this file, add it now so it can
  957. // wrap the system header.
  958. if (resolveAsBuiltinHeader(Mod, Header)) {
  959. // If we have both a builtin and system version of the file, the
  960. // builtin version may want to inject macros into the system header, so
  961. // force the system header to be treated as a textual header in this
  962. // case.
  963. Header.Kind = headerRoleToKind(ModuleMap::ModuleHeaderRole(
  964. headerKindToRole(Header.Kind) | ModuleMap::TextualHeader));
  965. Header.HasBuiltinHeader = true;
  966. }
  967. // If possible, don't stat the header until we need to. This requires the
  968. // user to have provided us with some stat information about the file.
  969. // FIXME: Add support for lazily stat'ing umbrella headers and excluded
  970. // headers.
  971. if ((Header.Size || Header.ModTime) && !Header.IsUmbrella &&
  972. Header.Kind != Module::HK_Excluded) {
  973. // We expect more variation in mtime than size, so if we're given both,
  974. // use the mtime as the key.
  975. if (Header.ModTime)
  976. LazyHeadersByModTime[*Header.ModTime].push_back(Mod);
  977. else
  978. LazyHeadersBySize[*Header.Size].push_back(Mod);
  979. Mod->UnresolvedHeaders.push_back(Header);
  980. return;
  981. }
  982. // We don't have stat information or can't defer looking this file up.
  983. // Perform the lookup now.
  984. resolveHeader(Mod, Header, NeedsFramework);
  985. }
  986. void ModuleMap::resolveHeaderDirectives(const FileEntry *File) const {
  987. auto BySize = LazyHeadersBySize.find(File->getSize());
  988. if (BySize != LazyHeadersBySize.end()) {
  989. for (auto *M : BySize->second)
  990. resolveHeaderDirectives(M);
  991. LazyHeadersBySize.erase(BySize);
  992. }
  993. auto ByModTime = LazyHeadersByModTime.find(File->getModificationTime());
  994. if (ByModTime != LazyHeadersByModTime.end()) {
  995. for (auto *M : ByModTime->second)
  996. resolveHeaderDirectives(M);
  997. LazyHeadersByModTime.erase(ByModTime);
  998. }
  999. }
  1000. void ModuleMap::resolveHeaderDirectives(Module *Mod) const {
  1001. bool NeedsFramework = false;
  1002. for (auto &Header : Mod->UnresolvedHeaders)
  1003. // This operation is logically const; we're just changing how we represent
  1004. // the header information for this file.
  1005. const_cast<ModuleMap*>(this)->resolveHeader(Mod, Header, NeedsFramework);
  1006. Mod->UnresolvedHeaders.clear();
  1007. }
  1008. void ModuleMap::addHeader(Module *Mod, Module::Header Header,
  1009. ModuleHeaderRole Role, bool Imported) {
  1010. KnownHeader KH(Mod, Role);
  1011. // Only add each header to the headers list once.
  1012. // FIXME: Should we diagnose if a header is listed twice in the
  1013. // same module definition?
  1014. auto &HeaderList = Headers[Header.Entry];
  1015. for (auto H : HeaderList)
  1016. if (H == KH)
  1017. return;
  1018. HeaderList.push_back(KH);
  1019. Mod->Headers[headerRoleToKind(Role)].push_back(Header);
  1020. bool isCompilingModuleHeader =
  1021. LangOpts.isCompilingModule() && Mod->getTopLevelModule() == SourceModule;
  1022. if (!Imported || isCompilingModuleHeader) {
  1023. // When we import HeaderFileInfo, the external source is expected to
  1024. // set the isModuleHeader flag itself.
  1025. HeaderInfo.MarkFileModuleHeader(Header.Entry, Role,
  1026. isCompilingModuleHeader);
  1027. }
  1028. // Notify callbacks that we just added a new header.
  1029. for (const auto &Cb : Callbacks)
  1030. Cb->moduleMapAddHeader(Header.Entry->getName());
  1031. }
  1032. void ModuleMap::excludeHeader(Module *Mod, Module::Header Header) {
  1033. // Add this as a known header so we won't implicitly add it to any
  1034. // umbrella directory module.
  1035. // FIXME: Should we only exclude it from umbrella modules within the
  1036. // specified module?
  1037. (void) Headers[Header.Entry];
  1038. Mod->Headers[Module::HK_Excluded].push_back(std::move(Header));
  1039. }
  1040. const FileEntry *
  1041. ModuleMap::getContainingModuleMapFile(const Module *Module) const {
  1042. if (Module->DefinitionLoc.isInvalid())
  1043. return nullptr;
  1044. return SourceMgr.getFileEntryForID(
  1045. SourceMgr.getFileID(Module->DefinitionLoc));
  1046. }
  1047. const FileEntry *ModuleMap::getModuleMapFileForUniquing(const Module *M) const {
  1048. if (M->IsInferred) {
  1049. assert(InferredModuleAllowedBy.count(M) && "missing inferred module map");
  1050. return InferredModuleAllowedBy.find(M)->second;
  1051. }
  1052. return getContainingModuleMapFile(M);
  1053. }
  1054. void ModuleMap::setInferredModuleAllowedBy(Module *M, const FileEntry *ModMap) {
  1055. assert(M->IsInferred && "module not inferred");
  1056. InferredModuleAllowedBy[M] = ModMap;
  1057. }
  1058. LLVM_DUMP_METHOD void ModuleMap::dump() {
  1059. llvm::errs() << "Modules:";
  1060. for (llvm::StringMap<Module *>::iterator M = Modules.begin(),
  1061. MEnd = Modules.end();
  1062. M != MEnd; ++M)
  1063. M->getValue()->print(llvm::errs(), 2);
  1064. llvm::errs() << "Headers:";
  1065. for (HeadersMap::iterator H = Headers.begin(), HEnd = Headers.end();
  1066. H != HEnd; ++H) {
  1067. llvm::errs() << " \"" << H->first->getName() << "\" -> ";
  1068. for (SmallVectorImpl<KnownHeader>::const_iterator I = H->second.begin(),
  1069. E = H->second.end();
  1070. I != E; ++I) {
  1071. if (I != H->second.begin())
  1072. llvm::errs() << ",";
  1073. llvm::errs() << I->getModule()->getFullModuleName();
  1074. }
  1075. llvm::errs() << "\n";
  1076. }
  1077. }
  1078. bool ModuleMap::resolveExports(Module *Mod, bool Complain) {
  1079. auto Unresolved = std::move(Mod->UnresolvedExports);
  1080. Mod->UnresolvedExports.clear();
  1081. for (auto &UE : Unresolved) {
  1082. Module::ExportDecl Export = resolveExport(Mod, UE, Complain);
  1083. if (Export.getPointer() || Export.getInt())
  1084. Mod->Exports.push_back(Export);
  1085. else
  1086. Mod->UnresolvedExports.push_back(UE);
  1087. }
  1088. return !Mod->UnresolvedExports.empty();
  1089. }
  1090. bool ModuleMap::resolveUses(Module *Mod, bool Complain) {
  1091. auto Unresolved = std::move(Mod->UnresolvedDirectUses);
  1092. Mod->UnresolvedDirectUses.clear();
  1093. for (auto &UDU : Unresolved) {
  1094. Module *DirectUse = resolveModuleId(UDU, Mod, Complain);
  1095. if (DirectUse)
  1096. Mod->DirectUses.push_back(DirectUse);
  1097. else
  1098. Mod->UnresolvedDirectUses.push_back(UDU);
  1099. }
  1100. return !Mod->UnresolvedDirectUses.empty();
  1101. }
  1102. bool ModuleMap::resolveConflicts(Module *Mod, bool Complain) {
  1103. auto Unresolved = std::move(Mod->UnresolvedConflicts);
  1104. Mod->UnresolvedConflicts.clear();
  1105. for (auto &UC : Unresolved) {
  1106. if (Module *OtherMod = resolveModuleId(UC.Id, Mod, Complain)) {
  1107. Module::Conflict Conflict;
  1108. Conflict.Other = OtherMod;
  1109. Conflict.Message = UC.Message;
  1110. Mod->Conflicts.push_back(Conflict);
  1111. } else
  1112. Mod->UnresolvedConflicts.push_back(UC);
  1113. }
  1114. return !Mod->UnresolvedConflicts.empty();
  1115. }
  1116. //----------------------------------------------------------------------------//
  1117. // Module map file parser
  1118. //----------------------------------------------------------------------------//
  1119. namespace clang {
  1120. /// A token in a module map file.
  1121. struct MMToken {
  1122. enum TokenKind {
  1123. Comma,
  1124. ConfigMacros,
  1125. Conflict,
  1126. EndOfFile,
  1127. HeaderKeyword,
  1128. Identifier,
  1129. Exclaim,
  1130. ExcludeKeyword,
  1131. ExplicitKeyword,
  1132. ExportKeyword,
  1133. ExportAsKeyword,
  1134. ExternKeyword,
  1135. FrameworkKeyword,
  1136. LinkKeyword,
  1137. ModuleKeyword,
  1138. Period,
  1139. PrivateKeyword,
  1140. UmbrellaKeyword,
  1141. UseKeyword,
  1142. RequiresKeyword,
  1143. Star,
  1144. StringLiteral,
  1145. IntegerLiteral,
  1146. TextualKeyword,
  1147. LBrace,
  1148. RBrace,
  1149. LSquare,
  1150. RSquare
  1151. } Kind;
  1152. unsigned Location;
  1153. unsigned StringLength;
  1154. union {
  1155. // If Kind != IntegerLiteral.
  1156. const char *StringData;
  1157. // If Kind == IntegerLiteral.
  1158. uint64_t IntegerValue;
  1159. };
  1160. void clear() {
  1161. Kind = EndOfFile;
  1162. Location = 0;
  1163. StringLength = 0;
  1164. StringData = nullptr;
  1165. }
  1166. bool is(TokenKind K) const { return Kind == K; }
  1167. SourceLocation getLocation() const {
  1168. return SourceLocation::getFromRawEncoding(Location);
  1169. }
  1170. uint64_t getInteger() const {
  1171. return Kind == IntegerLiteral ? IntegerValue : 0;
  1172. }
  1173. StringRef getString() const {
  1174. return Kind == IntegerLiteral ? StringRef()
  1175. : StringRef(StringData, StringLength);
  1176. }
  1177. };
  1178. class ModuleMapParser {
  1179. Lexer &L;
  1180. SourceManager &SourceMgr;
  1181. /// Default target information, used only for string literal
  1182. /// parsing.
  1183. const TargetInfo *Target;
  1184. DiagnosticsEngine &Diags;
  1185. ModuleMap &Map;
  1186. /// The current module map file.
  1187. const FileEntry *ModuleMapFile;
  1188. /// Source location of most recent parsed module declaration
  1189. SourceLocation CurrModuleDeclLoc;
  1190. /// The directory that file names in this module map file should
  1191. /// be resolved relative to.
  1192. const DirectoryEntry *Directory;
  1193. /// Whether this module map is in a system header directory.
  1194. bool IsSystem;
  1195. /// Whether an error occurred.
  1196. bool HadError = false;
  1197. /// Stores string data for the various string literals referenced
  1198. /// during parsing.
  1199. llvm::BumpPtrAllocator StringData;
  1200. /// The current token.
  1201. MMToken Tok;
  1202. /// The active module.
  1203. Module *ActiveModule = nullptr;
  1204. /// Whether a module uses the 'requires excluded' hack to mark its
  1205. /// contents as 'textual'.
  1206. ///
  1207. /// On older Darwin SDK versions, 'requires excluded' is used to mark the
  1208. /// contents of the Darwin.C.excluded (assert.h) and Tcl.Private modules as
  1209. /// non-modular headers. For backwards compatibility, we continue to
  1210. /// support this idiom for just these modules, and map the headers to
  1211. /// 'textual' to match the original intent.
  1212. llvm::SmallPtrSet<Module *, 2> UsesRequiresExcludedHack;
  1213. /// Consume the current token and return its location.
  1214. SourceLocation consumeToken();
  1215. /// Skip tokens until we reach the a token with the given kind
  1216. /// (or the end of the file).
  1217. void skipUntil(MMToken::TokenKind K);
  1218. using ModuleId = SmallVector<std::pair<std::string, SourceLocation>, 2>;
  1219. bool parseModuleId(ModuleId &Id);
  1220. void parseModuleDecl();
  1221. void parseExternModuleDecl();
  1222. void parseRequiresDecl();
  1223. void parseHeaderDecl(MMToken::TokenKind, SourceLocation LeadingLoc);
  1224. void parseUmbrellaDirDecl(SourceLocation UmbrellaLoc);
  1225. void parseExportDecl();
  1226. void parseExportAsDecl();
  1227. void parseUseDecl();
  1228. void parseLinkDecl();
  1229. void parseConfigMacros();
  1230. void parseConflict();
  1231. void parseInferredModuleDecl(bool Framework, bool Explicit);
  1232. /// Private modules are canonicalized as Foo_Private. Clang provides extra
  1233. /// module map search logic to find the appropriate private module when PCH
  1234. /// is used with implicit module maps. Warn when private modules are written
  1235. /// in other ways (FooPrivate and Foo.Private), providing notes and fixits.
  1236. void diagnosePrivateModules(SourceLocation ExplicitLoc,
  1237. SourceLocation FrameworkLoc);
  1238. using Attributes = ModuleMap::Attributes;
  1239. bool parseOptionalAttributes(Attributes &Attrs);
  1240. public:
  1241. explicit ModuleMapParser(Lexer &L, SourceManager &SourceMgr,
  1242. const TargetInfo *Target, DiagnosticsEngine &Diags,
  1243. ModuleMap &Map, const FileEntry *ModuleMapFile,
  1244. const DirectoryEntry *Directory, bool IsSystem)
  1245. : L(L), SourceMgr(SourceMgr), Target(Target), Diags(Diags), Map(Map),
  1246. ModuleMapFile(ModuleMapFile), Directory(Directory),
  1247. IsSystem(IsSystem) {
  1248. Tok.clear();
  1249. consumeToken();
  1250. }
  1251. bool parseModuleMapFile();
  1252. bool terminatedByDirective() { return false; }
  1253. SourceLocation getLocation() { return Tok.getLocation(); }
  1254. };
  1255. } // namespace clang
  1256. SourceLocation ModuleMapParser::consumeToken() {
  1257. SourceLocation Result = Tok.getLocation();
  1258. retry:
  1259. Tok.clear();
  1260. Token LToken;
  1261. L.LexFromRawLexer(LToken);
  1262. Tok.Location = LToken.getLocation().getRawEncoding();
  1263. switch (LToken.getKind()) {
  1264. case tok::raw_identifier: {
  1265. StringRef RI = LToken.getRawIdentifier();
  1266. Tok.StringData = RI.data();
  1267. Tok.StringLength = RI.size();
  1268. Tok.Kind = llvm::StringSwitch<MMToken::TokenKind>(RI)
  1269. .Case("config_macros", MMToken::ConfigMacros)
  1270. .Case("conflict", MMToken::Conflict)
  1271. .Case("exclude", MMToken::ExcludeKeyword)
  1272. .Case("explicit", MMToken::ExplicitKeyword)
  1273. .Case("export", MMToken::ExportKeyword)
  1274. .Case("export_as", MMToken::ExportAsKeyword)
  1275. .Case("extern", MMToken::ExternKeyword)
  1276. .Case("framework", MMToken::FrameworkKeyword)
  1277. .Case("header", MMToken::HeaderKeyword)
  1278. .Case("link", MMToken::LinkKeyword)
  1279. .Case("module", MMToken::ModuleKeyword)
  1280. .Case("private", MMToken::PrivateKeyword)
  1281. .Case("requires", MMToken::RequiresKeyword)
  1282. .Case("textual", MMToken::TextualKeyword)
  1283. .Case("umbrella", MMToken::UmbrellaKeyword)
  1284. .Case("use", MMToken::UseKeyword)
  1285. .Default(MMToken::Identifier);
  1286. break;
  1287. }
  1288. case tok::comma:
  1289. Tok.Kind = MMToken::Comma;
  1290. break;
  1291. case tok::eof:
  1292. Tok.Kind = MMToken::EndOfFile;
  1293. break;
  1294. case tok::l_brace:
  1295. Tok.Kind = MMToken::LBrace;
  1296. break;
  1297. case tok::l_square:
  1298. Tok.Kind = MMToken::LSquare;
  1299. break;
  1300. case tok::period:
  1301. Tok.Kind = MMToken::Period;
  1302. break;
  1303. case tok::r_brace:
  1304. Tok.Kind = MMToken::RBrace;
  1305. break;
  1306. case tok::r_square:
  1307. Tok.Kind = MMToken::RSquare;
  1308. break;
  1309. case tok::star:
  1310. Tok.Kind = MMToken::Star;
  1311. break;
  1312. case tok::exclaim:
  1313. Tok.Kind = MMToken::Exclaim;
  1314. break;
  1315. case tok::string_literal: {
  1316. if (LToken.hasUDSuffix()) {
  1317. Diags.Report(LToken.getLocation(), diag::err_invalid_string_udl);
  1318. HadError = true;
  1319. goto retry;
  1320. }
  1321. // Parse the string literal.
  1322. LangOptions LangOpts;
  1323. StringLiteralParser StringLiteral(LToken, SourceMgr, LangOpts, *Target);
  1324. if (StringLiteral.hadError)
  1325. goto retry;
  1326. // Copy the string literal into our string data allocator.
  1327. unsigned Length = StringLiteral.GetStringLength();
  1328. char *Saved = StringData.Allocate<char>(Length + 1);
  1329. memcpy(Saved, StringLiteral.GetString().data(), Length);
  1330. Saved[Length] = 0;
  1331. // Form the token.
  1332. Tok.Kind = MMToken::StringLiteral;
  1333. Tok.StringData = Saved;
  1334. Tok.StringLength = Length;
  1335. break;
  1336. }
  1337. case tok::numeric_constant: {
  1338. // We don't support any suffixes or other complications.
  1339. SmallString<32> SpellingBuffer;
  1340. SpellingBuffer.resize(LToken.getLength() + 1);
  1341. const char *Start = SpellingBuffer.data();
  1342. unsigned Length =
  1343. Lexer::getSpelling(LToken, Start, SourceMgr, L.getLangOpts());
  1344. uint64_t Value;
  1345. if (StringRef(Start, Length).getAsInteger(0, Value)) {
  1346. Diags.Report(Tok.getLocation(), diag::err_mmap_unknown_token);
  1347. HadError = true;
  1348. goto retry;
  1349. }
  1350. Tok.Kind = MMToken::IntegerLiteral;
  1351. Tok.IntegerValue = Value;
  1352. break;
  1353. }
  1354. case tok::comment:
  1355. goto retry;
  1356. case tok::hash:
  1357. // A module map can be terminated prematurely by
  1358. // #pragma clang module contents
  1359. // When building the module, we'll treat the rest of the file as the
  1360. // contents of the module.
  1361. {
  1362. auto NextIsIdent = [&](StringRef Str) -> bool {
  1363. L.LexFromRawLexer(LToken);
  1364. return !LToken.isAtStartOfLine() && LToken.is(tok::raw_identifier) &&
  1365. LToken.getRawIdentifier() == Str;
  1366. };
  1367. if (NextIsIdent("pragma") && NextIsIdent("clang") &&
  1368. NextIsIdent("module") && NextIsIdent("contents")) {
  1369. Tok.Kind = MMToken::EndOfFile;
  1370. break;
  1371. }
  1372. }
  1373. LLVM_FALLTHROUGH;
  1374. default:
  1375. Diags.Report(Tok.getLocation(), diag::err_mmap_unknown_token);
  1376. HadError = true;
  1377. goto retry;
  1378. }
  1379. return Result;
  1380. }
  1381. void ModuleMapParser::skipUntil(MMToken::TokenKind K) {
  1382. unsigned braceDepth = 0;
  1383. unsigned squareDepth = 0;
  1384. do {
  1385. switch (Tok.Kind) {
  1386. case MMToken::EndOfFile:
  1387. return;
  1388. case MMToken::LBrace:
  1389. if (Tok.is(K) && braceDepth == 0 && squareDepth == 0)
  1390. return;
  1391. ++braceDepth;
  1392. break;
  1393. case MMToken::LSquare:
  1394. if (Tok.is(K) && braceDepth == 0 && squareDepth == 0)
  1395. return;
  1396. ++squareDepth;
  1397. break;
  1398. case MMToken::RBrace:
  1399. if (braceDepth > 0)
  1400. --braceDepth;
  1401. else if (Tok.is(K))
  1402. return;
  1403. break;
  1404. case MMToken::RSquare:
  1405. if (squareDepth > 0)
  1406. --squareDepth;
  1407. else if (Tok.is(K))
  1408. return;
  1409. break;
  1410. default:
  1411. if (braceDepth == 0 && squareDepth == 0 && Tok.is(K))
  1412. return;
  1413. break;
  1414. }
  1415. consumeToken();
  1416. } while (true);
  1417. }
  1418. /// Parse a module-id.
  1419. ///
  1420. /// module-id:
  1421. /// identifier
  1422. /// identifier '.' module-id
  1423. ///
  1424. /// \returns true if an error occurred, false otherwise.
  1425. bool ModuleMapParser::parseModuleId(ModuleId &Id) {
  1426. Id.clear();
  1427. do {
  1428. if (Tok.is(MMToken::Identifier) || Tok.is(MMToken::StringLiteral)) {
  1429. Id.push_back(std::make_pair(Tok.getString(), Tok.getLocation()));
  1430. consumeToken();
  1431. } else {
  1432. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module_name);
  1433. return true;
  1434. }
  1435. if (!Tok.is(MMToken::Period))
  1436. break;
  1437. consumeToken();
  1438. } while (true);
  1439. return false;
  1440. }
  1441. namespace {
  1442. /// Enumerates the known attributes.
  1443. enum AttributeKind {
  1444. /// An unknown attribute.
  1445. AT_unknown,
  1446. /// The 'system' attribute.
  1447. AT_system,
  1448. /// The 'extern_c' attribute.
  1449. AT_extern_c,
  1450. /// The 'exhaustive' attribute.
  1451. AT_exhaustive,
  1452. /// The 'no_undeclared_includes' attribute.
  1453. AT_no_undeclared_includes
  1454. };
  1455. } // namespace
  1456. /// Private modules are canonicalized as Foo_Private. Clang provides extra
  1457. /// module map search logic to find the appropriate private module when PCH
  1458. /// is used with implicit module maps. Warn when private modules are written
  1459. /// in other ways (FooPrivate and Foo.Private), providing notes and fixits.
  1460. void ModuleMapParser::diagnosePrivateModules(SourceLocation ExplicitLoc,
  1461. SourceLocation FrameworkLoc) {
  1462. auto GenNoteAndFixIt = [&](StringRef BadName, StringRef Canonical,
  1463. const Module *M, SourceRange ReplLoc) {
  1464. auto D = Diags.Report(ActiveModule->DefinitionLoc,
  1465. diag::note_mmap_rename_top_level_private_module);
  1466. D << BadName << M->Name;
  1467. D << FixItHint::CreateReplacement(ReplLoc, Canonical);
  1468. };
  1469. for (auto E = Map.module_begin(); E != Map.module_end(); ++E) {
  1470. auto const *M = E->getValue();
  1471. if (M->Directory != ActiveModule->Directory)
  1472. continue;
  1473. SmallString<128> FullName(ActiveModule->getFullModuleName());
  1474. if (!FullName.startswith(M->Name) && !FullName.endswith("Private"))
  1475. continue;
  1476. SmallString<128> FixedPrivModDecl;
  1477. SmallString<128> Canonical(M->Name);
  1478. Canonical.append("_Private");
  1479. // Foo.Private -> Foo_Private
  1480. if (ActiveModule->Parent && ActiveModule->Name == "Private" && !M->Parent &&
  1481. M->Name == ActiveModule->Parent->Name) {
  1482. Diags.Report(ActiveModule->DefinitionLoc,
  1483. diag::warn_mmap_mismatched_private_submodule)
  1484. << FullName;
  1485. SourceLocation FixItInitBegin = CurrModuleDeclLoc;
  1486. if (FrameworkLoc.isValid())
  1487. FixItInitBegin = FrameworkLoc;
  1488. if (ExplicitLoc.isValid())
  1489. FixItInitBegin = ExplicitLoc;
  1490. if (FrameworkLoc.isValid() || ActiveModule->Parent->IsFramework)
  1491. FixedPrivModDecl.append("framework ");
  1492. FixedPrivModDecl.append("module ");
  1493. FixedPrivModDecl.append(Canonical);
  1494. GenNoteAndFixIt(FullName, FixedPrivModDecl, M,
  1495. SourceRange(FixItInitBegin, ActiveModule->DefinitionLoc));
  1496. continue;
  1497. }
  1498. // FooPrivate and whatnots -> Foo_Private
  1499. if (!ActiveModule->Parent && !M->Parent && M->Name != ActiveModule->Name &&
  1500. ActiveModule->Name != Canonical) {
  1501. Diags.Report(ActiveModule->DefinitionLoc,
  1502. diag::warn_mmap_mismatched_private_module_name)
  1503. << ActiveModule->Name;
  1504. GenNoteAndFixIt(ActiveModule->Name, Canonical, M,
  1505. SourceRange(ActiveModule->DefinitionLoc));
  1506. }
  1507. }
  1508. }
  1509. /// Parse a module declaration.
  1510. ///
  1511. /// module-declaration:
  1512. /// 'extern' 'module' module-id string-literal
  1513. /// 'explicit'[opt] 'framework'[opt] 'module' module-id attributes[opt]
  1514. /// { module-member* }
  1515. ///
  1516. /// module-member:
  1517. /// requires-declaration
  1518. /// header-declaration
  1519. /// submodule-declaration
  1520. /// export-declaration
  1521. /// export-as-declaration
  1522. /// link-declaration
  1523. ///
  1524. /// submodule-declaration:
  1525. /// module-declaration
  1526. /// inferred-submodule-declaration
  1527. void ModuleMapParser::parseModuleDecl() {
  1528. assert(Tok.is(MMToken::ExplicitKeyword) || Tok.is(MMToken::ModuleKeyword) ||
  1529. Tok.is(MMToken::FrameworkKeyword) || Tok.is(MMToken::ExternKeyword));
  1530. if (Tok.is(MMToken::ExternKeyword)) {
  1531. parseExternModuleDecl();
  1532. return;
  1533. }
  1534. // Parse 'explicit' or 'framework' keyword, if present.
  1535. SourceLocation ExplicitLoc;
  1536. SourceLocation FrameworkLoc;
  1537. bool Explicit = false;
  1538. bool Framework = false;
  1539. // Parse 'explicit' keyword, if present.
  1540. if (Tok.is(MMToken::ExplicitKeyword)) {
  1541. ExplicitLoc = consumeToken();
  1542. Explicit = true;
  1543. }
  1544. // Parse 'framework' keyword, if present.
  1545. if (Tok.is(MMToken::FrameworkKeyword)) {
  1546. FrameworkLoc = consumeToken();
  1547. Framework = true;
  1548. }
  1549. // Parse 'module' keyword.
  1550. if (!Tok.is(MMToken::ModuleKeyword)) {
  1551. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module);
  1552. consumeToken();
  1553. HadError = true;
  1554. return;
  1555. }
  1556. CurrModuleDeclLoc = consumeToken(); // 'module' keyword
  1557. // If we have a wildcard for the module name, this is an inferred submodule.
  1558. // Parse it.
  1559. if (Tok.is(MMToken::Star))
  1560. return parseInferredModuleDecl(Framework, Explicit);
  1561. // Parse the module name.
  1562. ModuleId Id;
  1563. if (parseModuleId(Id)) {
  1564. HadError = true;
  1565. return;
  1566. }
  1567. if (ActiveModule) {
  1568. if (Id.size() > 1) {
  1569. Diags.Report(Id.front().second, diag::err_mmap_nested_submodule_id)
  1570. << SourceRange(Id.front().second, Id.back().second);
  1571. HadError = true;
  1572. return;
  1573. }
  1574. } else if (Id.size() == 1 && Explicit) {
  1575. // Top-level modules can't be explicit.
  1576. Diags.Report(ExplicitLoc, diag::err_mmap_explicit_top_level);
  1577. Explicit = false;
  1578. ExplicitLoc = SourceLocation();
  1579. HadError = true;
  1580. }
  1581. Module *PreviousActiveModule = ActiveModule;
  1582. if (Id.size() > 1) {
  1583. // This module map defines a submodule. Go find the module of which it
  1584. // is a submodule.
  1585. ActiveModule = nullptr;
  1586. const Module *TopLevelModule = nullptr;
  1587. for (unsigned I = 0, N = Id.size() - 1; I != N; ++I) {
  1588. if (Module *Next = Map.lookupModuleQualified(Id[I].first, ActiveModule)) {
  1589. if (I == 0)
  1590. TopLevelModule = Next;
  1591. ActiveModule = Next;
  1592. continue;
  1593. }
  1594. if (ActiveModule) {
  1595. Diags.Report(Id[I].second, diag::err_mmap_missing_module_qualified)
  1596. << Id[I].first
  1597. << ActiveModule->getTopLevelModule()->getFullModuleName();
  1598. } else {
  1599. Diags.Report(Id[I].second, diag::err_mmap_expected_module_name);
  1600. }
  1601. HadError = true;
  1602. return;
  1603. }
  1604. if (ModuleMapFile != Map.getContainingModuleMapFile(TopLevelModule)) {
  1605. assert(ModuleMapFile != Map.getModuleMapFileForUniquing(TopLevelModule) &&
  1606. "submodule defined in same file as 'module *' that allowed its "
  1607. "top-level module");
  1608. Map.addAdditionalModuleMapFile(TopLevelModule, ModuleMapFile);
  1609. }
  1610. }
  1611. StringRef ModuleName = Id.back().first;
  1612. SourceLocation ModuleNameLoc = Id.back().second;
  1613. // Parse the optional attribute list.
  1614. Attributes Attrs;
  1615. if (parseOptionalAttributes(Attrs))
  1616. return;
  1617. // Parse the opening brace.
  1618. if (!Tok.is(MMToken::LBrace)) {
  1619. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_lbrace)
  1620. << ModuleName;
  1621. HadError = true;
  1622. return;
  1623. }
  1624. SourceLocation LBraceLoc = consumeToken();
  1625. // Determine whether this (sub)module has already been defined.
  1626. Module *ShadowingModule = nullptr;
  1627. if (Module *Existing = Map.lookupModuleQualified(ModuleName, ActiveModule)) {
  1628. // We might see a (re)definition of a module that we already have a
  1629. // definition for in two cases:
  1630. // - If we loaded one definition from an AST file and we've just found a
  1631. // corresponding definition in a module map file, or
  1632. bool LoadedFromASTFile = Existing->DefinitionLoc.isInvalid();
  1633. // - If we're building a (preprocessed) module and we've just loaded the
  1634. // module map file from which it was created.
  1635. bool ParsedAsMainInput =
  1636. Map.LangOpts.getCompilingModule() == LangOptions::CMK_ModuleMap &&
  1637. Map.LangOpts.CurrentModule == ModuleName &&
  1638. SourceMgr.getDecomposedLoc(ModuleNameLoc).first !=
  1639. SourceMgr.getDecomposedLoc(Existing->DefinitionLoc).first;
  1640. if (!ActiveModule && (LoadedFromASTFile || ParsedAsMainInput)) {
  1641. // Skip the module definition.
  1642. skipUntil(MMToken::RBrace);
  1643. if (Tok.is(MMToken::RBrace))
  1644. consumeToken();
  1645. else {
  1646. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
  1647. Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
  1648. HadError = true;
  1649. }
  1650. return;
  1651. }
  1652. if (!Existing->Parent && Map.mayShadowNewModule(Existing)) {
  1653. ShadowingModule = Existing;
  1654. } else {
  1655. // This is not a shawdowed module decl, it is an illegal redefinition.
  1656. Diags.Report(ModuleNameLoc, diag::err_mmap_module_redefinition)
  1657. << ModuleName;
  1658. Diags.Report(Existing->DefinitionLoc, diag::note_mmap_prev_definition);
  1659. // Skip the module definition.
  1660. skipUntil(MMToken::RBrace);
  1661. if (Tok.is(MMToken::RBrace))
  1662. consumeToken();
  1663. HadError = true;
  1664. return;
  1665. }
  1666. }
  1667. // Start defining this module.
  1668. if (ShadowingModule) {
  1669. ActiveModule =
  1670. Map.createShadowedModule(ModuleName, Framework, ShadowingModule);
  1671. } else {
  1672. ActiveModule =
  1673. Map.findOrCreateModule(ModuleName, ActiveModule, Framework, Explicit)
  1674. .first;
  1675. }
  1676. ActiveModule->DefinitionLoc = ModuleNameLoc;
  1677. if (Attrs.IsSystem || IsSystem)
  1678. ActiveModule->IsSystem = true;
  1679. if (Attrs.IsExternC)
  1680. ActiveModule->IsExternC = true;
  1681. if (Attrs.NoUndeclaredIncludes ||
  1682. (!ActiveModule->Parent && ModuleName == "Darwin"))
  1683. ActiveModule->NoUndeclaredIncludes = true;
  1684. ActiveModule->Directory = Directory;
  1685. StringRef MapFileName(ModuleMapFile->getName());
  1686. if (MapFileName.endswith("module.private.modulemap") ||
  1687. MapFileName.endswith("module_private.map")) {
  1688. ActiveModule->ModuleMapIsPrivate = true;
  1689. }
  1690. // Private modules named as FooPrivate, Foo.Private or similar are likely a
  1691. // user error; provide warnings, notes and fixits to direct users to use
  1692. // Foo_Private instead.
  1693. SourceLocation StartLoc =
  1694. SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
  1695. if (Map.HeaderInfo.getHeaderSearchOpts().ImplicitModuleMaps &&
  1696. !Diags.isIgnored(diag::warn_mmap_mismatched_private_submodule,
  1697. StartLoc) &&
  1698. !Diags.isIgnored(diag::warn_mmap_mismatched_private_module_name,
  1699. StartLoc) &&
  1700. ActiveModule->ModuleMapIsPrivate)
  1701. diagnosePrivateModules(ExplicitLoc, FrameworkLoc);
  1702. bool Done = false;
  1703. do {
  1704. switch (Tok.Kind) {
  1705. case MMToken::EndOfFile:
  1706. case MMToken::RBrace:
  1707. Done = true;
  1708. break;
  1709. case MMToken::ConfigMacros:
  1710. parseConfigMacros();
  1711. break;
  1712. case MMToken::Conflict:
  1713. parseConflict();
  1714. break;
  1715. case MMToken::ExplicitKeyword:
  1716. case MMToken::ExternKeyword:
  1717. case MMToken::FrameworkKeyword:
  1718. case MMToken::ModuleKeyword:
  1719. parseModuleDecl();
  1720. break;
  1721. case MMToken::ExportKeyword:
  1722. parseExportDecl();
  1723. break;
  1724. case MMToken::ExportAsKeyword:
  1725. parseExportAsDecl();
  1726. break;
  1727. case MMToken::UseKeyword:
  1728. parseUseDecl();
  1729. break;
  1730. case MMToken::RequiresKeyword:
  1731. parseRequiresDecl();
  1732. break;
  1733. case MMToken::TextualKeyword:
  1734. parseHeaderDecl(MMToken::TextualKeyword, consumeToken());
  1735. break;
  1736. case MMToken::UmbrellaKeyword: {
  1737. SourceLocation UmbrellaLoc = consumeToken();
  1738. if (Tok.is(MMToken::HeaderKeyword))
  1739. parseHeaderDecl(MMToken::UmbrellaKeyword, UmbrellaLoc);
  1740. else
  1741. parseUmbrellaDirDecl(UmbrellaLoc);
  1742. break;
  1743. }
  1744. case MMToken::ExcludeKeyword:
  1745. parseHeaderDecl(MMToken::ExcludeKeyword, consumeToken());
  1746. break;
  1747. case MMToken::PrivateKeyword:
  1748. parseHeaderDecl(MMToken::PrivateKeyword, consumeToken());
  1749. break;
  1750. case MMToken::HeaderKeyword:
  1751. parseHeaderDecl(MMToken::HeaderKeyword, consumeToken());
  1752. break;
  1753. case MMToken::LinkKeyword:
  1754. parseLinkDecl();
  1755. break;
  1756. default:
  1757. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_member);
  1758. consumeToken();
  1759. break;
  1760. }
  1761. } while (!Done);
  1762. if (Tok.is(MMToken::RBrace))
  1763. consumeToken();
  1764. else {
  1765. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
  1766. Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
  1767. HadError = true;
  1768. }
  1769. // If the active module is a top-level framework, and there are no link
  1770. // libraries, automatically link against the framework.
  1771. if (ActiveModule->IsFramework && !ActiveModule->isSubFramework() &&
  1772. ActiveModule->LinkLibraries.empty()) {
  1773. inferFrameworkLink(ActiveModule, Directory, SourceMgr.getFileManager());
  1774. }
  1775. // If the module meets all requirements but is still unavailable, mark the
  1776. // whole tree as unavailable to prevent it from building.
  1777. if (!ActiveModule->IsAvailable && !ActiveModule->IsMissingRequirement &&
  1778. ActiveModule->Parent) {
  1779. ActiveModule->getTopLevelModule()->markUnavailable();
  1780. ActiveModule->getTopLevelModule()->MissingHeaders.append(
  1781. ActiveModule->MissingHeaders.begin(), ActiveModule->MissingHeaders.end());
  1782. }
  1783. // We're done parsing this module. Pop back to the previous module.
  1784. ActiveModule = PreviousActiveModule;
  1785. }
  1786. /// Parse an extern module declaration.
  1787. ///
  1788. /// extern module-declaration:
  1789. /// 'extern' 'module' module-id string-literal
  1790. void ModuleMapParser::parseExternModuleDecl() {
  1791. assert(Tok.is(MMToken::ExternKeyword));
  1792. SourceLocation ExternLoc = consumeToken(); // 'extern' keyword
  1793. // Parse 'module' keyword.
  1794. if (!Tok.is(MMToken::ModuleKeyword)) {
  1795. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module);
  1796. consumeToken();
  1797. HadError = true;
  1798. return;
  1799. }
  1800. consumeToken(); // 'module' keyword
  1801. // Parse the module name.
  1802. ModuleId Id;
  1803. if (parseModuleId(Id)) {
  1804. HadError = true;
  1805. return;
  1806. }
  1807. // Parse the referenced module map file name.
  1808. if (!Tok.is(MMToken::StringLiteral)) {
  1809. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_mmap_file);
  1810. HadError = true;
  1811. return;
  1812. }
  1813. std::string FileName = Tok.getString();
  1814. consumeToken(); // filename
  1815. StringRef FileNameRef = FileName;
  1816. SmallString<128> ModuleMapFileName;
  1817. if (llvm::sys::path::is_relative(FileNameRef)) {
  1818. ModuleMapFileName += Directory->getName();
  1819. llvm::sys::path::append(ModuleMapFileName, FileName);
  1820. FileNameRef = ModuleMapFileName;
  1821. }
  1822. if (const FileEntry *File = SourceMgr.getFileManager().getFile(FileNameRef))
  1823. Map.parseModuleMapFile(
  1824. File, /*IsSystem=*/false,
  1825. Map.HeaderInfo.getHeaderSearchOpts().ModuleMapFileHomeIsCwd
  1826. ? Directory
  1827. : File->getDir(),
  1828. FileID(), nullptr, ExternLoc);
  1829. }
  1830. /// Whether to add the requirement \p Feature to the module \p M.
  1831. ///
  1832. /// This preserves backwards compatibility for two hacks in the Darwin system
  1833. /// module map files:
  1834. ///
  1835. /// 1. The use of 'requires excluded' to make headers non-modular, which
  1836. /// should really be mapped to 'textual' now that we have this feature. We
  1837. /// drop the 'excluded' requirement, and set \p IsRequiresExcludedHack to
  1838. /// true. Later, this bit will be used to map all the headers inside this
  1839. /// module to 'textual'.
  1840. ///
  1841. /// This affects Darwin.C.excluded (for assert.h) and Tcl.Private.
  1842. ///
  1843. /// 2. Removes a bogus cplusplus requirement from IOKit.avc. This requirement
  1844. /// was never correct and causes issues now that we check it, so drop it.
  1845. static bool shouldAddRequirement(Module *M, StringRef Feature,
  1846. bool &IsRequiresExcludedHack) {
  1847. if (Feature == "excluded" &&
  1848. (M->fullModuleNameIs({"Darwin", "C", "excluded"}) ||
  1849. M->fullModuleNameIs({"Tcl", "Private"}))) {
  1850. IsRequiresExcludedHack = true;
  1851. return false;
  1852. } else if (Feature == "cplusplus" && M->fullModuleNameIs({"IOKit", "avc"})) {
  1853. return false;
  1854. }
  1855. return true;
  1856. }
  1857. /// Parse a requires declaration.
  1858. ///
  1859. /// requires-declaration:
  1860. /// 'requires' feature-list
  1861. ///
  1862. /// feature-list:
  1863. /// feature ',' feature-list
  1864. /// feature
  1865. ///
  1866. /// feature:
  1867. /// '!'[opt] identifier
  1868. void ModuleMapParser::parseRequiresDecl() {
  1869. assert(Tok.is(MMToken::RequiresKeyword));
  1870. // Parse 'requires' keyword.
  1871. consumeToken();
  1872. // Parse the feature-list.
  1873. do {
  1874. bool RequiredState = true;
  1875. if (Tok.is(MMToken::Exclaim)) {
  1876. RequiredState = false;
  1877. consumeToken();
  1878. }
  1879. if (!Tok.is(MMToken::Identifier)) {
  1880. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_feature);
  1881. HadError = true;
  1882. return;
  1883. }
  1884. // Consume the feature name.
  1885. std::string Feature = Tok.getString();
  1886. consumeToken();
  1887. bool IsRequiresExcludedHack = false;
  1888. bool ShouldAddRequirement =
  1889. shouldAddRequirement(ActiveModule, Feature, IsRequiresExcludedHack);
  1890. if (IsRequiresExcludedHack)
  1891. UsesRequiresExcludedHack.insert(ActiveModule);
  1892. if (ShouldAddRequirement) {
  1893. // Add this feature.
  1894. ActiveModule->addRequirement(Feature, RequiredState, Map.LangOpts,
  1895. *Map.Target);
  1896. }
  1897. if (!Tok.is(MMToken::Comma))
  1898. break;
  1899. // Consume the comma.
  1900. consumeToken();
  1901. } while (true);
  1902. }
  1903. /// Parse a header declaration.
  1904. ///
  1905. /// header-declaration:
  1906. /// 'textual'[opt] 'header' string-literal
  1907. /// 'private' 'textual'[opt] 'header' string-literal
  1908. /// 'exclude' 'header' string-literal
  1909. /// 'umbrella' 'header' string-literal
  1910. ///
  1911. /// FIXME: Support 'private textual header'.
  1912. void ModuleMapParser::parseHeaderDecl(MMToken::TokenKind LeadingToken,
  1913. SourceLocation LeadingLoc) {
  1914. // We've already consumed the first token.
  1915. ModuleMap::ModuleHeaderRole Role = ModuleMap::NormalHeader;
  1916. if (LeadingToken == MMToken::PrivateKeyword) {
  1917. Role = ModuleMap::PrivateHeader;
  1918. // 'private' may optionally be followed by 'textual'.
  1919. if (Tok.is(MMToken::TextualKeyword)) {
  1920. LeadingToken = Tok.Kind;
  1921. consumeToken();
  1922. }
  1923. }
  1924. if (LeadingToken == MMToken::TextualKeyword)
  1925. Role = ModuleMap::ModuleHeaderRole(Role | ModuleMap::TextualHeader);
  1926. if (UsesRequiresExcludedHack.count(ActiveModule)) {
  1927. // Mark this header 'textual' (see doc comment for
  1928. // Module::UsesRequiresExcludedHack).
  1929. Role = ModuleMap::ModuleHeaderRole(Role | ModuleMap::TextualHeader);
  1930. }
  1931. if (LeadingToken != MMToken::HeaderKeyword) {
  1932. if (!Tok.is(MMToken::HeaderKeyword)) {
  1933. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
  1934. << (LeadingToken == MMToken::PrivateKeyword ? "private" :
  1935. LeadingToken == MMToken::ExcludeKeyword ? "exclude" :
  1936. LeadingToken == MMToken::TextualKeyword ? "textual" : "umbrella");
  1937. return;
  1938. }
  1939. consumeToken();
  1940. }
  1941. // Parse the header name.
  1942. if (!Tok.is(MMToken::StringLiteral)) {
  1943. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
  1944. << "header";
  1945. HadError = true;
  1946. return;
  1947. }
  1948. Module::UnresolvedHeaderDirective Header;
  1949. Header.FileName = Tok.getString();
  1950. Header.FileNameLoc = consumeToken();
  1951. Header.IsUmbrella = LeadingToken == MMToken::UmbrellaKeyword;
  1952. Header.Kind =
  1953. (LeadingToken == MMToken::ExcludeKeyword ? Module::HK_Excluded
  1954. : Map.headerRoleToKind(Role));
  1955. // Check whether we already have an umbrella.
  1956. if (Header.IsUmbrella && ActiveModule->Umbrella) {
  1957. Diags.Report(Header.FileNameLoc, diag::err_mmap_umbrella_clash)
  1958. << ActiveModule->getFullModuleName();
  1959. HadError = true;
  1960. return;
  1961. }
  1962. // If we were given stat information, parse it so we can skip looking for
  1963. // the file.
  1964. if (Tok.is(MMToken::LBrace)) {
  1965. SourceLocation LBraceLoc = consumeToken();
  1966. while (!Tok.is(MMToken::RBrace) && !Tok.is(MMToken::EndOfFile)) {
  1967. enum Attribute { Size, ModTime, Unknown };
  1968. StringRef Str = Tok.getString();
  1969. SourceLocation Loc = consumeToken();
  1970. switch (llvm::StringSwitch<Attribute>(Str)
  1971. .Case("size", Size)
  1972. .Case("mtime", ModTime)
  1973. .Default(Unknown)) {
  1974. case Size:
  1975. if (Header.Size)
  1976. Diags.Report(Loc, diag::err_mmap_duplicate_header_attribute) << Str;
  1977. if (!Tok.is(MMToken::IntegerLiteral)) {
  1978. Diags.Report(Tok.getLocation(),
  1979. diag::err_mmap_invalid_header_attribute_value) << Str;
  1980. skipUntil(MMToken::RBrace);
  1981. break;
  1982. }
  1983. Header.Size = Tok.getInteger();
  1984. consumeToken();
  1985. break;
  1986. case ModTime:
  1987. if (Header.ModTime)
  1988. Diags.Report(Loc, diag::err_mmap_duplicate_header_attribute) << Str;
  1989. if (!Tok.is(MMToken::IntegerLiteral)) {
  1990. Diags.Report(Tok.getLocation(),
  1991. diag::err_mmap_invalid_header_attribute_value) << Str;
  1992. skipUntil(MMToken::RBrace);
  1993. break;
  1994. }
  1995. Header.ModTime = Tok.getInteger();
  1996. consumeToken();
  1997. break;
  1998. case Unknown:
  1999. Diags.Report(Loc, diag::err_mmap_expected_header_attribute);
  2000. skipUntil(MMToken::RBrace);
  2001. break;
  2002. }
  2003. }
  2004. if (Tok.is(MMToken::RBrace))
  2005. consumeToken();
  2006. else {
  2007. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
  2008. Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
  2009. HadError = true;
  2010. }
  2011. }
  2012. bool NeedsFramework = false;
  2013. Map.addUnresolvedHeader(ActiveModule, std::move(Header), NeedsFramework);
  2014. if (NeedsFramework && ActiveModule)
  2015. Diags.Report(CurrModuleDeclLoc, diag::note_mmap_add_framework_keyword)
  2016. << ActiveModule->getFullModuleName()
  2017. << FixItHint::CreateReplacement(CurrModuleDeclLoc, "framework module");
  2018. }
  2019. static int compareModuleHeaders(const Module::Header *A,
  2020. const Module::Header *B) {
  2021. return A->NameAsWritten.compare(B->NameAsWritten);
  2022. }
  2023. /// Parse an umbrella directory declaration.
  2024. ///
  2025. /// umbrella-dir-declaration:
  2026. /// umbrella string-literal
  2027. void ModuleMapParser::parseUmbrellaDirDecl(SourceLocation UmbrellaLoc) {
  2028. // Parse the directory name.
  2029. if (!Tok.is(MMToken::StringLiteral)) {
  2030. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
  2031. << "umbrella";
  2032. HadError = true;
  2033. return;
  2034. }
  2035. std::string DirName = Tok.getString();
  2036. SourceLocation DirNameLoc = consumeToken();
  2037. // Check whether we already have an umbrella.
  2038. if (ActiveModule->Umbrella) {
  2039. Diags.Report(DirNameLoc, diag::err_mmap_umbrella_clash)
  2040. << ActiveModule->getFullModuleName();
  2041. HadError = true;
  2042. return;
  2043. }
  2044. // Look for this file.
  2045. const DirectoryEntry *Dir = nullptr;
  2046. if (llvm::sys::path::is_absolute(DirName))
  2047. Dir = SourceMgr.getFileManager().getDirectory(DirName);
  2048. else {
  2049. SmallString<128> PathName;
  2050. PathName = Directory->getName();
  2051. llvm::sys::path::append(PathName, DirName);
  2052. Dir = SourceMgr.getFileManager().getDirectory(PathName);
  2053. }
  2054. if (!Dir) {
  2055. Diags.Report(DirNameLoc, diag::warn_mmap_umbrella_dir_not_found)
  2056. << DirName;
  2057. return;
  2058. }
  2059. if (UsesRequiresExcludedHack.count(ActiveModule)) {
  2060. // Mark this header 'textual' (see doc comment for
  2061. // ModuleMapParser::UsesRequiresExcludedHack). Although iterating over the
  2062. // directory is relatively expensive, in practice this only applies to the
  2063. // uncommonly used Tcl module on Darwin platforms.
  2064. std::error_code EC;
  2065. SmallVector<Module::Header, 6> Headers;
  2066. llvm::vfs::FileSystem &FS =
  2067. *SourceMgr.getFileManager().getVirtualFileSystem();
  2068. for (llvm::vfs::recursive_directory_iterator I(FS, Dir->getName(), EC), E;
  2069. I != E && !EC; I.increment(EC)) {
  2070. if (const FileEntry *FE = SourceMgr.getFileManager().getFile(I->path())) {
  2071. Module::Header Header = {I->path(), FE};
  2072. Headers.push_back(std::move(Header));
  2073. }
  2074. }
  2075. // Sort header paths so that the pcm doesn't depend on iteration order.
  2076. llvm::array_pod_sort(Headers.begin(), Headers.end(), compareModuleHeaders);
  2077. for (auto &Header : Headers)
  2078. Map.addHeader(ActiveModule, std::move(Header), ModuleMap::TextualHeader);
  2079. return;
  2080. }
  2081. if (Module *OwningModule = Map.UmbrellaDirs[Dir]) {
  2082. Diags.Report(UmbrellaLoc, diag::err_mmap_umbrella_clash)
  2083. << OwningModule->getFullModuleName();
  2084. HadError = true;
  2085. return;
  2086. }
  2087. // Record this umbrella directory.
  2088. Map.setUmbrellaDir(ActiveModule, Dir, DirName);
  2089. }
  2090. /// Parse a module export declaration.
  2091. ///
  2092. /// export-declaration:
  2093. /// 'export' wildcard-module-id
  2094. ///
  2095. /// wildcard-module-id:
  2096. /// identifier
  2097. /// '*'
  2098. /// identifier '.' wildcard-module-id
  2099. void ModuleMapParser::parseExportDecl() {
  2100. assert(Tok.is(MMToken::ExportKeyword));
  2101. SourceLocation ExportLoc = consumeToken();
  2102. // Parse the module-id with an optional wildcard at the end.
  2103. ModuleId ParsedModuleId;
  2104. bool Wildcard = false;
  2105. do {
  2106. // FIXME: Support string-literal module names here.
  2107. if (Tok.is(MMToken::Identifier)) {
  2108. ParsedModuleId.push_back(std::make_pair(Tok.getString(),
  2109. Tok.getLocation()));
  2110. consumeToken();
  2111. if (Tok.is(MMToken::Period)) {
  2112. consumeToken();
  2113. continue;
  2114. }
  2115. break;
  2116. }
  2117. if(Tok.is(MMToken::Star)) {
  2118. Wildcard = true;
  2119. consumeToken();
  2120. break;
  2121. }
  2122. Diags.Report(Tok.getLocation(), diag::err_mmap_module_id);
  2123. HadError = true;
  2124. return;
  2125. } while (true);
  2126. Module::UnresolvedExportDecl Unresolved = {
  2127. ExportLoc, ParsedModuleId, Wildcard
  2128. };
  2129. ActiveModule->UnresolvedExports.push_back(Unresolved);
  2130. }
  2131. /// Parse a module export_as declaration.
  2132. ///
  2133. /// export-as-declaration:
  2134. /// 'export_as' identifier
  2135. void ModuleMapParser::parseExportAsDecl() {
  2136. assert(Tok.is(MMToken::ExportAsKeyword));
  2137. consumeToken();
  2138. if (!Tok.is(MMToken::Identifier)) {
  2139. Diags.Report(Tok.getLocation(), diag::err_mmap_module_id);
  2140. HadError = true;
  2141. return;
  2142. }
  2143. if (ActiveModule->Parent) {
  2144. Diags.Report(Tok.getLocation(), diag::err_mmap_submodule_export_as);
  2145. consumeToken();
  2146. return;
  2147. }
  2148. if (!ActiveModule->ExportAsModule.empty()) {
  2149. if (ActiveModule->ExportAsModule == Tok.getString()) {
  2150. Diags.Report(Tok.getLocation(), diag::warn_mmap_redundant_export_as)
  2151. << ActiveModule->Name << Tok.getString();
  2152. } else {
  2153. Diags.Report(Tok.getLocation(), diag::err_mmap_conflicting_export_as)
  2154. << ActiveModule->Name << ActiveModule->ExportAsModule
  2155. << Tok.getString();
  2156. }
  2157. }
  2158. ActiveModule->ExportAsModule = Tok.getString();
  2159. Map.addLinkAsDependency(ActiveModule);
  2160. consumeToken();
  2161. }
  2162. /// Parse a module use declaration.
  2163. ///
  2164. /// use-declaration:
  2165. /// 'use' wildcard-module-id
  2166. void ModuleMapParser::parseUseDecl() {
  2167. assert(Tok.is(MMToken::UseKeyword));
  2168. auto KWLoc = consumeToken();
  2169. // Parse the module-id.
  2170. ModuleId ParsedModuleId;
  2171. parseModuleId(ParsedModuleId);
  2172. if (ActiveModule->Parent)
  2173. Diags.Report(KWLoc, diag::err_mmap_use_decl_submodule);
  2174. else
  2175. ActiveModule->UnresolvedDirectUses.push_back(ParsedModuleId);
  2176. }
  2177. /// Parse a link declaration.
  2178. ///
  2179. /// module-declaration:
  2180. /// 'link' 'framework'[opt] string-literal
  2181. void ModuleMapParser::parseLinkDecl() {
  2182. assert(Tok.is(MMToken::LinkKeyword));
  2183. SourceLocation LinkLoc = consumeToken();
  2184. // Parse the optional 'framework' keyword.
  2185. bool IsFramework = false;
  2186. if (Tok.is(MMToken::FrameworkKeyword)) {
  2187. consumeToken();
  2188. IsFramework = true;
  2189. }
  2190. // Parse the library name
  2191. if (!Tok.is(MMToken::StringLiteral)) {
  2192. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_library_name)
  2193. << IsFramework << SourceRange(LinkLoc);
  2194. HadError = true;
  2195. return;
  2196. }
  2197. std::string LibraryName = Tok.getString();
  2198. consumeToken();
  2199. ActiveModule->LinkLibraries.push_back(Module::LinkLibrary(LibraryName,
  2200. IsFramework));
  2201. }
  2202. /// Parse a configuration macro declaration.
  2203. ///
  2204. /// module-declaration:
  2205. /// 'config_macros' attributes[opt] config-macro-list?
  2206. ///
  2207. /// config-macro-list:
  2208. /// identifier (',' identifier)?
  2209. void ModuleMapParser::parseConfigMacros() {
  2210. assert(Tok.is(MMToken::ConfigMacros));
  2211. SourceLocation ConfigMacrosLoc = consumeToken();
  2212. // Only top-level modules can have configuration macros.
  2213. if (ActiveModule->Parent) {
  2214. Diags.Report(ConfigMacrosLoc, diag::err_mmap_config_macro_submodule);
  2215. }
  2216. // Parse the optional attributes.
  2217. Attributes Attrs;
  2218. if (parseOptionalAttributes(Attrs))
  2219. return;
  2220. if (Attrs.IsExhaustive && !ActiveModule->Parent) {
  2221. ActiveModule->ConfigMacrosExhaustive = true;
  2222. }
  2223. // If we don't have an identifier, we're done.
  2224. // FIXME: Support macros with the same name as a keyword here.
  2225. if (!Tok.is(MMToken::Identifier))
  2226. return;
  2227. // Consume the first identifier.
  2228. if (!ActiveModule->Parent) {
  2229. ActiveModule->ConfigMacros.push_back(Tok.getString().str());
  2230. }
  2231. consumeToken();
  2232. do {
  2233. // If there's a comma, consume it.
  2234. if (!Tok.is(MMToken::Comma))
  2235. break;
  2236. consumeToken();
  2237. // We expect to see a macro name here.
  2238. // FIXME: Support macros with the same name as a keyword here.
  2239. if (!Tok.is(MMToken::Identifier)) {
  2240. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_config_macro);
  2241. break;
  2242. }
  2243. // Consume the macro name.
  2244. if (!ActiveModule->Parent) {
  2245. ActiveModule->ConfigMacros.push_back(Tok.getString().str());
  2246. }
  2247. consumeToken();
  2248. } while (true);
  2249. }
  2250. /// Format a module-id into a string.
  2251. static std::string formatModuleId(const ModuleId &Id) {
  2252. std::string result;
  2253. {
  2254. llvm::raw_string_ostream OS(result);
  2255. for (unsigned I = 0, N = Id.size(); I != N; ++I) {
  2256. if (I)
  2257. OS << ".";
  2258. OS << Id[I].first;
  2259. }
  2260. }
  2261. return result;
  2262. }
  2263. /// Parse a conflict declaration.
  2264. ///
  2265. /// module-declaration:
  2266. /// 'conflict' module-id ',' string-literal
  2267. void ModuleMapParser::parseConflict() {
  2268. assert(Tok.is(MMToken::Conflict));
  2269. SourceLocation ConflictLoc = consumeToken();
  2270. Module::UnresolvedConflict Conflict;
  2271. // Parse the module-id.
  2272. if (parseModuleId(Conflict.Id))
  2273. return;
  2274. // Parse the ','.
  2275. if (!Tok.is(MMToken::Comma)) {
  2276. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_conflicts_comma)
  2277. << SourceRange(ConflictLoc);
  2278. return;
  2279. }
  2280. consumeToken();
  2281. // Parse the message.
  2282. if (!Tok.is(MMToken::StringLiteral)) {
  2283. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_conflicts_message)
  2284. << formatModuleId(Conflict.Id);
  2285. return;
  2286. }
  2287. Conflict.Message = Tok.getString().str();
  2288. consumeToken();
  2289. // Add this unresolved conflict.
  2290. ActiveModule->UnresolvedConflicts.push_back(Conflict);
  2291. }
  2292. /// Parse an inferred module declaration (wildcard modules).
  2293. ///
  2294. /// module-declaration:
  2295. /// 'explicit'[opt] 'framework'[opt] 'module' * attributes[opt]
  2296. /// { inferred-module-member* }
  2297. ///
  2298. /// inferred-module-member:
  2299. /// 'export' '*'
  2300. /// 'exclude' identifier
  2301. void ModuleMapParser::parseInferredModuleDecl(bool Framework, bool Explicit) {
  2302. assert(Tok.is(MMToken::Star));
  2303. SourceLocation StarLoc = consumeToken();
  2304. bool Failed = false;
  2305. // Inferred modules must be submodules.
  2306. if (!ActiveModule && !Framework) {
  2307. Diags.Report(StarLoc, diag::err_mmap_top_level_inferred_submodule);
  2308. Failed = true;
  2309. }
  2310. if (ActiveModule) {
  2311. // Inferred modules must have umbrella directories.
  2312. if (!Failed && ActiveModule->IsAvailable &&
  2313. !ActiveModule->getUmbrellaDir()) {
  2314. Diags.Report(StarLoc, diag::err_mmap_inferred_no_umbrella);
  2315. Failed = true;
  2316. }
  2317. // Check for redefinition of an inferred module.
  2318. if (!Failed && ActiveModule->InferSubmodules) {
  2319. Diags.Report(StarLoc, diag::err_mmap_inferred_redef);
  2320. if (ActiveModule->InferredSubmoduleLoc.isValid())
  2321. Diags.Report(ActiveModule->InferredSubmoduleLoc,
  2322. diag::note_mmap_prev_definition);
  2323. Failed = true;
  2324. }
  2325. // Check for the 'framework' keyword, which is not permitted here.
  2326. if (Framework) {
  2327. Diags.Report(StarLoc, diag::err_mmap_inferred_framework_submodule);
  2328. Framework = false;
  2329. }
  2330. } else if (Explicit) {
  2331. Diags.Report(StarLoc, diag::err_mmap_explicit_inferred_framework);
  2332. Explicit = false;
  2333. }
  2334. // If there were any problems with this inferred submodule, skip its body.
  2335. if (Failed) {
  2336. if (Tok.is(MMToken::LBrace)) {
  2337. consumeToken();
  2338. skipUntil(MMToken::RBrace);
  2339. if (Tok.is(MMToken::RBrace))
  2340. consumeToken();
  2341. }
  2342. HadError = true;
  2343. return;
  2344. }
  2345. // Parse optional attributes.
  2346. Attributes Attrs;
  2347. if (parseOptionalAttributes(Attrs))
  2348. return;
  2349. if (ActiveModule) {
  2350. // Note that we have an inferred submodule.
  2351. ActiveModule->InferSubmodules = true;
  2352. ActiveModule->InferredSubmoduleLoc = StarLoc;
  2353. ActiveModule->InferExplicitSubmodules = Explicit;
  2354. } else {
  2355. // We'll be inferring framework modules for this directory.
  2356. Map.InferredDirectories[Directory].InferModules = true;
  2357. Map.InferredDirectories[Directory].Attrs = Attrs;
  2358. Map.InferredDirectories[Directory].ModuleMapFile = ModuleMapFile;
  2359. // FIXME: Handle the 'framework' keyword.
  2360. }
  2361. // Parse the opening brace.
  2362. if (!Tok.is(MMToken::LBrace)) {
  2363. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_lbrace_wildcard);
  2364. HadError = true;
  2365. return;
  2366. }
  2367. SourceLocation LBraceLoc = consumeToken();
  2368. // Parse the body of the inferred submodule.
  2369. bool Done = false;
  2370. do {
  2371. switch (Tok.Kind) {
  2372. case MMToken::EndOfFile:
  2373. case MMToken::RBrace:
  2374. Done = true;
  2375. break;
  2376. case MMToken::ExcludeKeyword:
  2377. if (ActiveModule) {
  2378. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member)
  2379. << (ActiveModule != nullptr);
  2380. consumeToken();
  2381. break;
  2382. }
  2383. consumeToken();
  2384. // FIXME: Support string-literal module names here.
  2385. if (!Tok.is(MMToken::Identifier)) {
  2386. Diags.Report(Tok.getLocation(), diag::err_mmap_missing_exclude_name);
  2387. break;
  2388. }
  2389. Map.InferredDirectories[Directory].ExcludedModules
  2390. .push_back(Tok.getString());
  2391. consumeToken();
  2392. break;
  2393. case MMToken::ExportKeyword:
  2394. if (!ActiveModule) {
  2395. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member)
  2396. << (ActiveModule != nullptr);
  2397. consumeToken();
  2398. break;
  2399. }
  2400. consumeToken();
  2401. if (Tok.is(MMToken::Star))
  2402. ActiveModule->InferExportWildcard = true;
  2403. else
  2404. Diags.Report(Tok.getLocation(),
  2405. diag::err_mmap_expected_export_wildcard);
  2406. consumeToken();
  2407. break;
  2408. case MMToken::ExplicitKeyword:
  2409. case MMToken::ModuleKeyword:
  2410. case MMToken::HeaderKeyword:
  2411. case MMToken::PrivateKeyword:
  2412. case MMToken::UmbrellaKeyword:
  2413. default:
  2414. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member)
  2415. << (ActiveModule != nullptr);
  2416. consumeToken();
  2417. break;
  2418. }
  2419. } while (!Done);
  2420. if (Tok.is(MMToken::RBrace))
  2421. consumeToken();
  2422. else {
  2423. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
  2424. Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
  2425. HadError = true;
  2426. }
  2427. }
  2428. /// Parse optional attributes.
  2429. ///
  2430. /// attributes:
  2431. /// attribute attributes
  2432. /// attribute
  2433. ///
  2434. /// attribute:
  2435. /// [ identifier ]
  2436. ///
  2437. /// \param Attrs Will be filled in with the parsed attributes.
  2438. ///
  2439. /// \returns true if an error occurred, false otherwise.
  2440. bool ModuleMapParser::parseOptionalAttributes(Attributes &Attrs) {
  2441. bool HadError = false;
  2442. while (Tok.is(MMToken::LSquare)) {
  2443. // Consume the '['.
  2444. SourceLocation LSquareLoc = consumeToken();
  2445. // Check whether we have an attribute name here.
  2446. if (!Tok.is(MMToken::Identifier)) {
  2447. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_attribute);
  2448. skipUntil(MMToken::RSquare);
  2449. if (Tok.is(MMToken::RSquare))
  2450. consumeToken();
  2451. HadError = true;
  2452. }
  2453. // Decode the attribute name.
  2454. AttributeKind Attribute
  2455. = llvm::StringSwitch<AttributeKind>(Tok.getString())
  2456. .Case("exhaustive", AT_exhaustive)
  2457. .Case("extern_c", AT_extern_c)
  2458. .Case("no_undeclared_includes", AT_no_undeclared_includes)
  2459. .Case("system", AT_system)
  2460. .Default(AT_unknown);
  2461. switch (Attribute) {
  2462. case AT_unknown:
  2463. Diags.Report(Tok.getLocation(), diag::warn_mmap_unknown_attribute)
  2464. << Tok.getString();
  2465. break;
  2466. case AT_system:
  2467. Attrs.IsSystem = true;
  2468. break;
  2469. case AT_extern_c:
  2470. Attrs.IsExternC = true;
  2471. break;
  2472. case AT_exhaustive:
  2473. Attrs.IsExhaustive = true;
  2474. break;
  2475. case AT_no_undeclared_includes:
  2476. Attrs.NoUndeclaredIncludes = true;
  2477. break;
  2478. }
  2479. consumeToken();
  2480. // Consume the ']'.
  2481. if (!Tok.is(MMToken::RSquare)) {
  2482. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rsquare);
  2483. Diags.Report(LSquareLoc, diag::note_mmap_lsquare_match);
  2484. skipUntil(MMToken::RSquare);
  2485. HadError = true;
  2486. }
  2487. if (Tok.is(MMToken::RSquare))
  2488. consumeToken();
  2489. }
  2490. return HadError;
  2491. }
  2492. /// Parse a module map file.
  2493. ///
  2494. /// module-map-file:
  2495. /// module-declaration*
  2496. bool ModuleMapParser::parseModuleMapFile() {
  2497. do {
  2498. switch (Tok.Kind) {
  2499. case MMToken::EndOfFile:
  2500. return HadError;
  2501. case MMToken::ExplicitKeyword:
  2502. case MMToken::ExternKeyword:
  2503. case MMToken::ModuleKeyword:
  2504. case MMToken::FrameworkKeyword:
  2505. parseModuleDecl();
  2506. break;
  2507. case MMToken::Comma:
  2508. case MMToken::ConfigMacros:
  2509. case MMToken::Conflict:
  2510. case MMToken::Exclaim:
  2511. case MMToken::ExcludeKeyword:
  2512. case MMToken::ExportKeyword:
  2513. case MMToken::ExportAsKeyword:
  2514. case MMToken::HeaderKeyword:
  2515. case MMToken::Identifier:
  2516. case MMToken::LBrace:
  2517. case MMToken::LinkKeyword:
  2518. case MMToken::LSquare:
  2519. case MMToken::Period:
  2520. case MMToken::PrivateKeyword:
  2521. case MMToken::RBrace:
  2522. case MMToken::RSquare:
  2523. case MMToken::RequiresKeyword:
  2524. case MMToken::Star:
  2525. case MMToken::StringLiteral:
  2526. case MMToken::IntegerLiteral:
  2527. case MMToken::TextualKeyword:
  2528. case MMToken::UmbrellaKeyword:
  2529. case MMToken::UseKeyword:
  2530. Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module);
  2531. HadError = true;
  2532. consumeToken();
  2533. break;
  2534. }
  2535. } while (true);
  2536. }
  2537. bool ModuleMap::parseModuleMapFile(const FileEntry *File, bool IsSystem,
  2538. const DirectoryEntry *Dir, FileID ID,
  2539. unsigned *Offset,
  2540. SourceLocation ExternModuleLoc) {
  2541. assert(Target && "Missing target information");
  2542. llvm::DenseMap<const FileEntry *, bool>::iterator Known
  2543. = ParsedModuleMap.find(File);
  2544. if (Known != ParsedModuleMap.end())
  2545. return Known->second;
  2546. // If the module map file wasn't already entered, do so now.
  2547. if (ID.isInvalid()) {
  2548. auto FileCharacter =
  2549. IsSystem ? SrcMgr::C_System_ModuleMap : SrcMgr::C_User_ModuleMap;
  2550. ID = SourceMgr.createFileID(File, ExternModuleLoc, FileCharacter);
  2551. }
  2552. assert(Target && "Missing target information");
  2553. const llvm::MemoryBuffer *Buffer = SourceMgr.getBuffer(ID);
  2554. if (!Buffer)
  2555. return ParsedModuleMap[File] = true;
  2556. assert((!Offset || *Offset <= Buffer->getBufferSize()) &&
  2557. "invalid buffer offset");
  2558. // Parse this module map file.
  2559. Lexer L(SourceMgr.getLocForStartOfFile(ID), MMapLangOpts,
  2560. Buffer->getBufferStart(),
  2561. Buffer->getBufferStart() + (Offset ? *Offset : 0),
  2562. Buffer->getBufferEnd());
  2563. SourceLocation Start = L.getSourceLocation();
  2564. ModuleMapParser Parser(L, SourceMgr, Target, Diags, *this, File, Dir,
  2565. IsSystem);
  2566. bool Result = Parser.parseModuleMapFile();
  2567. ParsedModuleMap[File] = Result;
  2568. if (Offset) {
  2569. auto Loc = SourceMgr.getDecomposedLoc(Parser.getLocation());
  2570. assert(Loc.first == ID && "stopped in a different file?");
  2571. *Offset = Loc.second;
  2572. }
  2573. // Notify callbacks that we parsed it.
  2574. for (const auto &Cb : Callbacks)
  2575. Cb->moduleMapFileRead(Start, *File, IsSystem);
  2576. return Result;
  2577. }