ModuleMap.h 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- ModuleMap.h - Describe the layout of modules -------------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // This file defines the ModuleMap interface, which describes the layout of a
  15. // module as it relates to headers.
  16. //
  17. //===----------------------------------------------------------------------===//
  18. #ifndef LLVM_CLANG_LEX_MODULEMAP_H
  19. #define LLVM_CLANG_LEX_MODULEMAP_H
  20. #include "clang/Basic/IdentifierTable.h"
  21. #include "clang/Basic/LangOptions.h"
  22. #include "clang/Basic/Module.h"
  23. #include "clang/Basic/SourceLocation.h"
  24. #include "llvm/ADT/ArrayRef.h"
  25. #include "llvm/ADT/DenseMap.h"
  26. #include "llvm/ADT/PointerIntPair.h"
  27. #include "llvm/ADT/SmallPtrSet.h"
  28. #include "llvm/ADT/SmallVector.h"
  29. #include "llvm/ADT/StringMap.h"
  30. #include "llvm/ADT/StringRef.h"
  31. #include "llvm/ADT/StringSet.h"
  32. #include "llvm/ADT/TinyPtrVector.h"
  33. #include "llvm/ADT/Twine.h"
  34. #include <ctime>
  35. #include <memory>
  36. #include <optional>
  37. #include <string>
  38. #include <utility>
  39. namespace clang {
  40. class DiagnosticsEngine;
  41. class DirectoryEntry;
  42. class FileEntry;
  43. class FileManager;
  44. class HeaderSearch;
  45. class SourceManager;
  46. /// A mechanism to observe the actions of the module map parser as it
  47. /// reads module map files.
  48. class ModuleMapCallbacks {
  49. virtual void anchor();
  50. public:
  51. virtual ~ModuleMapCallbacks() = default;
  52. /// Called when a module map file has been read.
  53. ///
  54. /// \param FileStart A SourceLocation referring to the start of the file's
  55. /// contents.
  56. /// \param File The file itself.
  57. /// \param IsSystem Whether this is a module map from a system include path.
  58. virtual void moduleMapFileRead(SourceLocation FileStart,
  59. const FileEntry &File, bool IsSystem) {}
  60. /// Called when a header is added during module map parsing.
  61. ///
  62. /// \param Filename The header file itself.
  63. virtual void moduleMapAddHeader(StringRef Filename) {}
  64. /// Called when an umbrella header is added during module map parsing.
  65. ///
  66. /// \param FileMgr FileManager instance
  67. /// \param Header The umbrella header to collect.
  68. virtual void moduleMapAddUmbrellaHeader(FileManager *FileMgr,
  69. const FileEntry *Header) {}
  70. };
  71. class ModuleMap {
  72. SourceManager &SourceMgr;
  73. DiagnosticsEngine &Diags;
  74. const LangOptions &LangOpts;
  75. const TargetInfo *Target;
  76. HeaderSearch &HeaderInfo;
  77. llvm::SmallVector<std::unique_ptr<ModuleMapCallbacks>, 1> Callbacks;
  78. /// The directory used for Clang-supplied, builtin include headers,
  79. /// such as "stdint.h".
  80. const DirectoryEntry *BuiltinIncludeDir = nullptr;
  81. /// Language options used to parse the module map itself.
  82. ///
  83. /// These are always simple C language options.
  84. LangOptions MMapLangOpts;
  85. /// The module that the main source file is associated with (the module
  86. /// named LangOpts::CurrentModule, if we've loaded it).
  87. Module *SourceModule = nullptr;
  88. /// Submodules of the current module that have not yet been attached to it.
  89. /// (Ownership is transferred if/when we create an enclosing module.)
  90. llvm::SmallVector<std::unique_ptr<Module>, 8> PendingSubmodules;
  91. /// The top-level modules that are known.
  92. llvm::StringMap<Module *> Modules;
  93. /// Module loading cache that includes submodules, indexed by IdentifierInfo.
  94. /// nullptr is stored for modules that are known to fail to load.
  95. llvm::DenseMap<const IdentifierInfo *, Module *> CachedModuleLoads;
  96. /// Shadow modules created while building this module map.
  97. llvm::SmallVector<Module*, 2> ShadowModules;
  98. /// The number of modules we have created in total.
  99. unsigned NumCreatedModules = 0;
  100. /// In case a module has a export_as entry, it might have a pending link
  101. /// name to be determined if that module is imported.
  102. llvm::StringMap<llvm::StringSet<>> PendingLinkAsModule;
  103. public:
  104. /// Use PendingLinkAsModule information to mark top level link names that
  105. /// are going to be replaced by export_as aliases.
  106. void resolveLinkAsDependencies(Module *Mod);
  107. /// Make module to use export_as as the link dependency name if enough
  108. /// information is available or add it to a pending list otherwise.
  109. void addLinkAsDependency(Module *Mod);
  110. /// Flags describing the role of a module header.
  111. enum ModuleHeaderRole {
  112. /// This header is normally included in the module.
  113. NormalHeader = 0x0,
  114. /// This header is included but private.
  115. PrivateHeader = 0x1,
  116. /// This header is part of the module (for layering purposes) but
  117. /// should be textually included.
  118. TextualHeader = 0x2,
  119. /// This header is explicitly excluded from the module.
  120. ExcludedHeader = 0x4,
  121. // Caution: Adding an enumerator needs other changes.
  122. // Adjust the number of bits for KnownHeader::Storage.
  123. // Adjust the HeaderFileInfoTrait::ReadData streaming.
  124. // Adjust the HeaderFileInfoTrait::EmitData streaming.
  125. // Adjust ModuleMap::addHeader.
  126. };
  127. /// Convert a header kind to a role. Requires Kind to not be HK_Excluded.
  128. static ModuleHeaderRole headerKindToRole(Module::HeaderKind Kind);
  129. /// Convert a header role to a kind.
  130. static Module::HeaderKind headerRoleToKind(ModuleHeaderRole Role);
  131. /// Check if the header with the given role is a modular one.
  132. static bool isModular(ModuleHeaderRole Role);
  133. /// A header that is known to reside within a given module,
  134. /// whether it was included or excluded.
  135. class KnownHeader {
  136. llvm::PointerIntPair<Module *, 3, ModuleHeaderRole> Storage;
  137. public:
  138. KnownHeader() : Storage(nullptr, NormalHeader) {}
  139. KnownHeader(Module *M, ModuleHeaderRole Role) : Storage(M, Role) {}
  140. friend bool operator==(const KnownHeader &A, const KnownHeader &B) {
  141. return A.Storage == B.Storage;
  142. }
  143. friend bool operator!=(const KnownHeader &A, const KnownHeader &B) {
  144. return A.Storage != B.Storage;
  145. }
  146. /// Retrieve the module the header is stored in.
  147. Module *getModule() const { return Storage.getPointer(); }
  148. /// The role of this header within the module.
  149. ModuleHeaderRole getRole() const { return Storage.getInt(); }
  150. /// Whether this header is available in the module.
  151. bool isAvailable() const {
  152. return getRole() != ExcludedHeader && getModule()->isAvailable();
  153. }
  154. /// Whether this header is accessible from the specified module.
  155. bool isAccessibleFrom(Module *M) const {
  156. return !(getRole() & PrivateHeader) ||
  157. (M && M->getTopLevelModule() == getModule()->getTopLevelModule());
  158. }
  159. // Whether this known header is valid (i.e., it has an
  160. // associated module).
  161. explicit operator bool() const {
  162. return Storage.getPointer() != nullptr;
  163. }
  164. };
  165. using AdditionalModMapsSet = llvm::SmallPtrSet<const FileEntry *, 1>;
  166. private:
  167. friend class ModuleMapParser;
  168. using HeadersMap =
  169. llvm::DenseMap<const FileEntry *, SmallVector<KnownHeader, 1>>;
  170. /// Mapping from each header to the module that owns the contents of
  171. /// that header.
  172. HeadersMap Headers;
  173. /// Map from file sizes to modules with lazy header directives of that size.
  174. mutable llvm::DenseMap<off_t, llvm::TinyPtrVector<Module*>> LazyHeadersBySize;
  175. /// Map from mtimes to modules with lazy header directives with those mtimes.
  176. mutable llvm::DenseMap<time_t, llvm::TinyPtrVector<Module*>>
  177. LazyHeadersByModTime;
  178. /// Mapping from directories with umbrella headers to the module
  179. /// that is generated from the umbrella header.
  180. ///
  181. /// This mapping is used to map headers that haven't explicitly been named
  182. /// in the module map over to the module that includes them via its umbrella
  183. /// header.
  184. llvm::DenseMap<const DirectoryEntry *, Module *> UmbrellaDirs;
  185. /// A generation counter that is used to test whether modules of the
  186. /// same name may shadow or are illegal redefinitions.
  187. ///
  188. /// Modules from earlier scopes may shadow modules from later ones.
  189. /// Modules from the same scope may not have the same name.
  190. unsigned CurrentModuleScopeID = 0;
  191. llvm::DenseMap<Module *, unsigned> ModuleScopeIDs;
  192. /// The set of attributes that can be attached to a module.
  193. struct Attributes {
  194. /// Whether this is a system module.
  195. unsigned IsSystem : 1;
  196. /// Whether this is an extern "C" module.
  197. unsigned IsExternC : 1;
  198. /// Whether this is an exhaustive set of configuration macros.
  199. unsigned IsExhaustive : 1;
  200. /// Whether files in this module can only include non-modular headers
  201. /// and headers from used modules.
  202. unsigned NoUndeclaredIncludes : 1;
  203. Attributes()
  204. : IsSystem(false), IsExternC(false), IsExhaustive(false),
  205. NoUndeclaredIncludes(false) {}
  206. };
  207. /// A directory for which framework modules can be inferred.
  208. struct InferredDirectory {
  209. /// Whether to infer modules from this directory.
  210. unsigned InferModules : 1;
  211. /// The attributes to use for inferred modules.
  212. Attributes Attrs;
  213. /// If \c InferModules is non-zero, the module map file that allowed
  214. /// inferred modules. Otherwise, nullptr.
  215. const FileEntry *ModuleMapFile;
  216. /// The names of modules that cannot be inferred within this
  217. /// directory.
  218. SmallVector<std::string, 2> ExcludedModules;
  219. InferredDirectory() : InferModules(false) {}
  220. };
  221. /// A mapping from directories to information about inferring
  222. /// framework modules from within those directories.
  223. llvm::DenseMap<const DirectoryEntry *, InferredDirectory> InferredDirectories;
  224. /// A mapping from an inferred module to the module map that allowed the
  225. /// inference.
  226. llvm::DenseMap<const Module *, const FileEntry *> InferredModuleAllowedBy;
  227. llvm::DenseMap<const Module *, AdditionalModMapsSet> AdditionalModMaps;
  228. /// Describes whether we haved parsed a particular file as a module
  229. /// map.
  230. llvm::DenseMap<const FileEntry *, bool> ParsedModuleMap;
  231. /// Resolve the given export declaration into an actual export
  232. /// declaration.
  233. ///
  234. /// \param Mod The module in which we're resolving the export declaration.
  235. ///
  236. /// \param Unresolved The export declaration to resolve.
  237. ///
  238. /// \param Complain Whether this routine should complain about unresolvable
  239. /// exports.
  240. ///
  241. /// \returns The resolved export declaration, which will have a NULL pointer
  242. /// if the export could not be resolved.
  243. Module::ExportDecl
  244. resolveExport(Module *Mod, const Module::UnresolvedExportDecl &Unresolved,
  245. bool Complain) const;
  246. /// Resolve the given module id to an actual module.
  247. ///
  248. /// \param Id The module-id to resolve.
  249. ///
  250. /// \param Mod The module in which we're resolving the module-id.
  251. ///
  252. /// \param Complain Whether this routine should complain about unresolvable
  253. /// module-ids.
  254. ///
  255. /// \returns The resolved module, or null if the module-id could not be
  256. /// resolved.
  257. Module *resolveModuleId(const ModuleId &Id, Module *Mod, bool Complain) const;
  258. /// Add an unresolved header to a module.
  259. ///
  260. /// \param Mod The module in which we're adding the unresolved header
  261. /// directive.
  262. /// \param Header The unresolved header directive.
  263. /// \param NeedsFramework If Mod is not a framework but a missing header would
  264. /// be found in case Mod was, set it to true. False otherwise.
  265. void addUnresolvedHeader(Module *Mod,
  266. Module::UnresolvedHeaderDirective Header,
  267. bool &NeedsFramework);
  268. /// Look up the given header directive to find an actual header file.
  269. ///
  270. /// \param M The module in which we're resolving the header directive.
  271. /// \param Header The header directive to resolve.
  272. /// \param RelativePathName Filled in with the relative path name from the
  273. /// module to the resolved header.
  274. /// \param NeedsFramework If M is not a framework but a missing header would
  275. /// be found in case M was, set it to true. False otherwise.
  276. /// \return The resolved file, if any.
  277. OptionalFileEntryRef
  278. findHeader(Module *M, const Module::UnresolvedHeaderDirective &Header,
  279. SmallVectorImpl<char> &RelativePathName, bool &NeedsFramework);
  280. /// Resolve the given header directive.
  281. ///
  282. /// \param M The module in which we're resolving the header directive.
  283. /// \param Header The header directive to resolve.
  284. /// \param NeedsFramework If M is not a framework but a missing header would
  285. /// be found in case M was, set it to true. False otherwise.
  286. void resolveHeader(Module *M, const Module::UnresolvedHeaderDirective &Header,
  287. bool &NeedsFramework);
  288. /// Attempt to resolve the specified header directive as naming a builtin
  289. /// header.
  290. /// \return \c true if a corresponding builtin header was found.
  291. bool resolveAsBuiltinHeader(Module *M,
  292. const Module::UnresolvedHeaderDirective &Header);
  293. /// Looks up the modules that \p File corresponds to.
  294. ///
  295. /// If \p File represents a builtin header within Clang's builtin include
  296. /// directory, this also loads all of the module maps to see if it will get
  297. /// associated with a specific module (e.g. in /usr/include).
  298. HeadersMap::iterator findKnownHeader(const FileEntry *File);
  299. /// Searches for a module whose umbrella directory contains \p File.
  300. ///
  301. /// \param File The header to search for.
  302. ///
  303. /// \param IntermediateDirs On success, contains the set of directories
  304. /// searched before finding \p File.
  305. KnownHeader findHeaderInUmbrellaDirs(const FileEntry *File,
  306. SmallVectorImpl<const DirectoryEntry *> &IntermediateDirs);
  307. /// Given that \p File is not in the Headers map, look it up within
  308. /// umbrella directories and find or create a module for it.
  309. KnownHeader findOrCreateModuleForHeaderInUmbrellaDir(const FileEntry *File);
  310. /// A convenience method to determine if \p File is (possibly nested)
  311. /// in an umbrella directory.
  312. bool isHeaderInUmbrellaDirs(const FileEntry *File) {
  313. SmallVector<const DirectoryEntry *, 2> IntermediateDirs;
  314. return static_cast<bool>(findHeaderInUmbrellaDirs(File, IntermediateDirs));
  315. }
  316. Module *inferFrameworkModule(const DirectoryEntry *FrameworkDir,
  317. Attributes Attrs, Module *Parent);
  318. public:
  319. /// Construct a new module map.
  320. ///
  321. /// \param SourceMgr The source manager used to find module files and headers.
  322. /// This source manager should be shared with the header-search mechanism,
  323. /// since they will refer to the same headers.
  324. ///
  325. /// \param Diags A diagnostic engine used for diagnostics.
  326. ///
  327. /// \param LangOpts Language options for this translation unit.
  328. ///
  329. /// \param Target The target for this translation unit.
  330. ModuleMap(SourceManager &SourceMgr, DiagnosticsEngine &Diags,
  331. const LangOptions &LangOpts, const TargetInfo *Target,
  332. HeaderSearch &HeaderInfo);
  333. /// Destroy the module map.
  334. ~ModuleMap();
  335. /// Set the target information.
  336. void setTarget(const TargetInfo &Target);
  337. /// Set the directory that contains Clang-supplied include
  338. /// files, such as our stdarg.h or tgmath.h.
  339. void setBuiltinIncludeDir(const DirectoryEntry *Dir) {
  340. BuiltinIncludeDir = Dir;
  341. }
  342. /// Get the directory that contains Clang-supplied include files.
  343. const DirectoryEntry *getBuiltinDir() const {
  344. return BuiltinIncludeDir;
  345. }
  346. /// Is this a compiler builtin header?
  347. static bool isBuiltinHeader(StringRef FileName);
  348. bool isBuiltinHeader(const FileEntry *File);
  349. /// Add a module map callback.
  350. void addModuleMapCallbacks(std::unique_ptr<ModuleMapCallbacks> Callback) {
  351. Callbacks.push_back(std::move(Callback));
  352. }
  353. /// Retrieve the module that owns the given header file, if any. Note that
  354. /// this does not implicitly load module maps, except for builtin headers,
  355. /// and does not consult the external source. (Those checks are the
  356. /// responsibility of \ref HeaderSearch.)
  357. ///
  358. /// \param File The header file that is likely to be included.
  359. ///
  360. /// \param AllowTextual If \c true and \p File is a textual header, return
  361. /// its owning module. Otherwise, no KnownHeader will be returned if the
  362. /// file is only known as a textual header.
  363. ///
  364. /// \returns The module KnownHeader, which provides the module that owns the
  365. /// given header file. The KnownHeader is default constructed to indicate
  366. /// that no module owns this header file.
  367. KnownHeader findModuleForHeader(const FileEntry *File,
  368. bool AllowTextual = false,
  369. bool AllowExcluded = false);
  370. /// Retrieve all the modules that contain the given header file. Note that
  371. /// this does not implicitly load module maps, except for builtin headers,
  372. /// and does not consult the external source. (Those checks are the
  373. /// responsibility of \ref HeaderSearch.)
  374. ///
  375. /// Typically, \ref findModuleForHeader should be used instead, as it picks
  376. /// the preferred module for the header.
  377. ArrayRef<KnownHeader> findAllModulesForHeader(const FileEntry *File);
  378. /// Like \ref findAllModulesForHeader, but do not attempt to infer module
  379. /// ownership from umbrella headers if we've not already done so.
  380. ArrayRef<KnownHeader>
  381. findResolvedModulesForHeader(const FileEntry *File) const;
  382. /// Resolve all lazy header directives for the specified file.
  383. ///
  384. /// This ensures that the HeaderFileInfo on HeaderSearch is up to date. This
  385. /// is effectively internal, but is exposed so HeaderSearch can call it.
  386. void resolveHeaderDirectives(const FileEntry *File) const;
  387. /// Resolve lazy header directives for the specified module. If File is
  388. /// provided, only headers with same size and modtime are resolved. If File
  389. /// is not set, all headers are resolved.
  390. void resolveHeaderDirectives(Module *Mod,
  391. std::optional<const FileEntry *> File) const;
  392. /// Reports errors if a module must not include a specific file.
  393. ///
  394. /// \param RequestingModule The module including a file.
  395. ///
  396. /// \param RequestingModuleIsModuleInterface \c true if the inclusion is in
  397. /// the interface of RequestingModule, \c false if it's in the
  398. /// implementation of RequestingModule. Value is ignored and
  399. /// meaningless if RequestingModule is nullptr.
  400. ///
  401. /// \param FilenameLoc The location of the inclusion's filename.
  402. ///
  403. /// \param Filename The included filename as written.
  404. ///
  405. /// \param File The included file.
  406. void diagnoseHeaderInclusion(Module *RequestingModule,
  407. bool RequestingModuleIsModuleInterface,
  408. SourceLocation FilenameLoc, StringRef Filename,
  409. FileEntryRef File);
  410. /// Determine whether the given header is part of a module
  411. /// marked 'unavailable'.
  412. bool isHeaderInUnavailableModule(const FileEntry *Header) const;
  413. /// Determine whether the given header is unavailable as part
  414. /// of the specified module.
  415. bool isHeaderUnavailableInModule(const FileEntry *Header,
  416. const Module *RequestingModule) const;
  417. /// Retrieve a module with the given name.
  418. ///
  419. /// \param Name The name of the module to look up.
  420. ///
  421. /// \returns The named module, if known; otherwise, returns null.
  422. Module *findModule(StringRef Name) const;
  423. /// Retrieve a module with the given name using lexical name lookup,
  424. /// starting at the given context.
  425. ///
  426. /// \param Name The name of the module to look up.
  427. ///
  428. /// \param Context The module context, from which we will perform lexical
  429. /// name lookup.
  430. ///
  431. /// \returns The named module, if known; otherwise, returns null.
  432. Module *lookupModuleUnqualified(StringRef Name, Module *Context) const;
  433. /// Retrieve a module with the given name within the given context,
  434. /// using direct (qualified) name lookup.
  435. ///
  436. /// \param Name The name of the module to look up.
  437. ///
  438. /// \param Context The module for which we will look for a submodule. If
  439. /// null, we will look for a top-level module.
  440. ///
  441. /// \returns The named submodule, if known; otherwose, returns null.
  442. Module *lookupModuleQualified(StringRef Name, Module *Context) const;
  443. /// Find a new module or submodule, or create it if it does not already
  444. /// exist.
  445. ///
  446. /// \param Name The name of the module to find or create.
  447. ///
  448. /// \param Parent The module that will act as the parent of this submodule,
  449. /// or nullptr to indicate that this is a top-level module.
  450. ///
  451. /// \param IsFramework Whether this is a framework module.
  452. ///
  453. /// \param IsExplicit Whether this is an explicit submodule.
  454. ///
  455. /// \returns The found or newly-created module, along with a boolean value
  456. /// that will be true if the module is newly-created.
  457. std::pair<Module *, bool> findOrCreateModule(StringRef Name, Module *Parent,
  458. bool IsFramework,
  459. bool IsExplicit);
  460. /// Create a global module fragment for a C++ module unit.
  461. ///
  462. /// We model the global module fragment as a submodule of the module
  463. /// interface unit. Unfortunately, we can't create the module interface
  464. /// unit's Module until later, because we don't know what it will be called
  465. /// usually. See C++20 [module.unit]/7.2 for the case we could know its
  466. /// parent.
  467. Module *createGlobalModuleFragmentForModuleUnit(SourceLocation Loc,
  468. Module *Parent = nullptr);
  469. /// Create a global module fragment for a C++ module interface unit.
  470. Module *createPrivateModuleFragmentForInterfaceUnit(Module *Parent,
  471. SourceLocation Loc);
  472. /// Create a new module for a C++ module interface unit.
  473. /// The module must not already exist, and will be configured for the current
  474. /// compilation.
  475. ///
  476. /// Note that this also sets the current module to the newly-created module.
  477. ///
  478. /// \returns The newly-created module.
  479. Module *createModuleForInterfaceUnit(SourceLocation Loc, StringRef Name);
  480. /// Create a C++20 header unit.
  481. Module *createHeaderUnit(SourceLocation Loc, StringRef Name,
  482. Module::Header H);
  483. /// Infer the contents of a framework module map from the given
  484. /// framework directory.
  485. Module *inferFrameworkModule(const DirectoryEntry *FrameworkDir,
  486. bool IsSystem, Module *Parent);
  487. /// Create a new top-level module that is shadowed by
  488. /// \p ShadowingModule.
  489. Module *createShadowedModule(StringRef Name, bool IsFramework,
  490. Module *ShadowingModule);
  491. /// Creates a new declaration scope for module names, allowing
  492. /// previously defined modules to shadow definitions from the new scope.
  493. ///
  494. /// \note Module names from earlier scopes will shadow names from the new
  495. /// scope, which is the opposite of how shadowing works for variables.
  496. void finishModuleDeclarationScope() { CurrentModuleScopeID += 1; }
  497. bool mayShadowNewModule(Module *ExistingModule) {
  498. assert(!ExistingModule->Parent && "expected top-level module");
  499. assert(ModuleScopeIDs.count(ExistingModule) && "unknown module");
  500. return ModuleScopeIDs[ExistingModule] < CurrentModuleScopeID;
  501. }
  502. /// Check whether a framework module can be inferred in the given directory.
  503. bool canInferFrameworkModule(const DirectoryEntry *Dir) const {
  504. auto It = InferredDirectories.find(Dir);
  505. return It != InferredDirectories.end() && It->getSecond().InferModules;
  506. }
  507. /// Retrieve the module map file containing the definition of the given
  508. /// module.
  509. ///
  510. /// \param Module The module whose module map file will be returned, if known.
  511. ///
  512. /// \returns The file entry for the module map file containing the given
  513. /// module, or nullptr if the module definition was inferred.
  514. OptionalFileEntryRef getContainingModuleMapFile(const Module *Module) const;
  515. /// Get the module map file that (along with the module name) uniquely
  516. /// identifies this module.
  517. ///
  518. /// The particular module that \c Name refers to may depend on how the module
  519. /// was found in header search. However, the combination of \c Name and
  520. /// this module map will be globally unique for top-level modules. In the case
  521. /// of inferred modules, returns the module map that allowed the inference
  522. /// (e.g. contained 'module *'). Otherwise, returns
  523. /// getContainingModuleMapFile().
  524. OptionalFileEntryRef getModuleMapFileForUniquing(const Module *M) const;
  525. void setInferredModuleAllowedBy(Module *M, const FileEntry *ModMap);
  526. /// Canonicalize \p Path in a manner suitable for a module map file. In
  527. /// particular, this canonicalizes the parent directory separately from the
  528. /// filename so that it does not affect header resolution relative to the
  529. /// modulemap.
  530. ///
  531. /// \returns an error code if any filesystem operations failed. In this case
  532. /// \p Path is not modified.
  533. std::error_code canonicalizeModuleMapPath(SmallVectorImpl<char> &Path);
  534. /// Get any module map files other than getModuleMapFileForUniquing(M)
  535. /// that define submodules of a top-level module \p M. This is cheaper than
  536. /// getting the module map file for each submodule individually, since the
  537. /// expected number of results is very small.
  538. AdditionalModMapsSet *getAdditionalModuleMapFiles(const Module *M) {
  539. auto I = AdditionalModMaps.find(M);
  540. if (I == AdditionalModMaps.end())
  541. return nullptr;
  542. return &I->second;
  543. }
  544. void addAdditionalModuleMapFile(const Module *M, const FileEntry *ModuleMap);
  545. /// Resolve all of the unresolved exports in the given module.
  546. ///
  547. /// \param Mod The module whose exports should be resolved.
  548. ///
  549. /// \param Complain Whether to emit diagnostics for failures.
  550. ///
  551. /// \returns true if any errors were encountered while resolving exports,
  552. /// false otherwise.
  553. bool resolveExports(Module *Mod, bool Complain);
  554. /// Resolve all of the unresolved uses in the given module.
  555. ///
  556. /// \param Mod The module whose uses should be resolved.
  557. ///
  558. /// \param Complain Whether to emit diagnostics for failures.
  559. ///
  560. /// \returns true if any errors were encountered while resolving uses,
  561. /// false otherwise.
  562. bool resolveUses(Module *Mod, bool Complain);
  563. /// Resolve all of the unresolved conflicts in the given module.
  564. ///
  565. /// \param Mod The module whose conflicts should be resolved.
  566. ///
  567. /// \param Complain Whether to emit diagnostics for failures.
  568. ///
  569. /// \returns true if any errors were encountered while resolving conflicts,
  570. /// false otherwise.
  571. bool resolveConflicts(Module *Mod, bool Complain);
  572. /// Sets the umbrella header of the given module to the given
  573. /// header.
  574. void setUmbrellaHeader(Module *Mod, FileEntryRef UmbrellaHeader,
  575. const Twine &NameAsWritten,
  576. const Twine &PathRelativeToRootModuleDirectory);
  577. /// Sets the umbrella directory of the given module to the given
  578. /// directory.
  579. void setUmbrellaDir(Module *Mod, const DirectoryEntry *UmbrellaDir,
  580. const Twine &NameAsWritten,
  581. const Twine &PathRelativeToRootModuleDirectory);
  582. /// Adds this header to the given module.
  583. /// \param Role The role of the header wrt the module.
  584. void addHeader(Module *Mod, Module::Header Header,
  585. ModuleHeaderRole Role, bool Imported = false);
  586. /// Parse the given module map file, and record any modules we
  587. /// encounter.
  588. ///
  589. /// \param File The file to be parsed.
  590. ///
  591. /// \param IsSystem Whether this module map file is in a system header
  592. /// directory, and therefore should be considered a system module.
  593. ///
  594. /// \param HomeDir The directory in which relative paths within this module
  595. /// map file will be resolved.
  596. ///
  597. /// \param ID The FileID of the file to process, if we've already entered it.
  598. ///
  599. /// \param Offset [inout] On input the offset at which to start parsing. On
  600. /// output, the offset at which the module map terminated.
  601. ///
  602. /// \param ExternModuleLoc The location of the "extern module" declaration
  603. /// that caused us to load this module map file, if any.
  604. ///
  605. /// \returns true if an error occurred, false otherwise.
  606. bool parseModuleMapFile(const FileEntry *File, bool IsSystem,
  607. const DirectoryEntry *HomeDir,
  608. FileID ID = FileID(), unsigned *Offset = nullptr,
  609. SourceLocation ExternModuleLoc = SourceLocation());
  610. /// Dump the contents of the module map, for debugging purposes.
  611. void dump();
  612. using module_iterator = llvm::StringMap<Module *>::const_iterator;
  613. module_iterator module_begin() const { return Modules.begin(); }
  614. module_iterator module_end() const { return Modules.end(); }
  615. llvm::iterator_range<module_iterator> modules() const {
  616. return {module_begin(), module_end()};
  617. }
  618. /// Cache a module load. M might be nullptr.
  619. void cacheModuleLoad(const IdentifierInfo &II, Module *M) {
  620. CachedModuleLoads[&II] = M;
  621. }
  622. /// Return a cached module load.
  623. std::optional<Module *> getCachedModuleLoad(const IdentifierInfo &II) {
  624. auto I = CachedModuleLoads.find(&II);
  625. if (I == CachedModuleLoads.end())
  626. return std::nullopt;
  627. return I->second;
  628. }
  629. };
  630. } // namespace clang
  631. #endif // LLVM_CLANG_LEX_MODULEMAP_H
  632. #ifdef __GNUC__
  633. #pragma GCC diagnostic pop
  634. #endif