ModuleMap.cpp 95 KB

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