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