ModuleMap.cpp 96 KB

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