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