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