ModuleMap.cpp 94 KB

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