ModuleMap.cpp 98 KB

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