1 //===--- ModuleMap.h - Describe the layout of modules -----------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the ModuleMap interface, which describes the layout of a
11 // module as it relates to headers.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_CLANG_LEX_MODULEMAP_H
16 #define LLVM_CLANG_LEX_MODULEMAP_H
18 #include "clang/Basic/LangOptions.h"
19 #include "clang/Basic/Module.h"
20 #include "clang/Basic/SourceLocation.h"
21 #include "clang/Basic/SourceManager.h"
22 #include "llvm/ADT/ArrayRef.h"
23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/PointerIntPair.h"
25 #include "llvm/ADT/SmallPtrSet.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/ADT/StringMap.h"
28 #include "llvm/ADT/StringRef.h"
29 #include "llvm/ADT/Twine.h"
40 class DiagnosticConsumer;
41 class DiagnosticsEngine;
43 class ModuleMapParser;
45 /// \brief A mechanism to observe the actions of the module map parser as it
46 /// reads module map files.
47 class ModuleMapCallbacks {
49 virtual ~ModuleMapCallbacks() = default;
51 /// \brief Called when a module map file has been read.
53 /// \param FileStart A SourceLocation referring to the start of the file's
55 /// \param File The file itself.
56 /// \param IsSystem Whether this is a module map from a system include path.
57 virtual void moduleMapFileRead(SourceLocation FileStart,
58 const FileEntry &File, bool IsSystem) {}
60 /// \brief Called when a header is added during module map parsing.
62 /// \param Filename The header file itself.
63 virtual void moduleMapAddHeader(StringRef Filename) {}
65 /// \brief Called when an umbrella header is added during module map parsing.
67 /// \param FileMgr FileManager instance
68 /// \param Header The umbrella header to collect.
69 virtual void moduleMapAddUmbrellaHeader(FileManager *FileMgr,
70 const FileEntry *Header) {}
74 SourceManager &SourceMgr;
75 DiagnosticsEngine &Diags;
76 const LangOptions &LangOpts;
77 const TargetInfo *Target;
78 HeaderSearch &HeaderInfo;
80 llvm::SmallVector<std::unique_ptr<ModuleMapCallbacks>, 1> Callbacks;
82 /// \brief The directory used for Clang-supplied, builtin include headers,
83 /// such as "stdint.h".
84 const DirectoryEntry *BuiltinIncludeDir;
86 /// \brief Language options used to parse the module map itself.
88 /// These are always simple C language options.
89 LangOptions MMapLangOpts;
91 // The module that the main source file is associated with (the module
92 // named LangOpts::CurrentModule, if we've loaded it).
95 /// \brief The top-level modules that are known.
96 llvm::StringMap<Module *> Modules;
98 /// \brief The number of modules we have created in total.
99 unsigned NumCreatedModules;
102 /// \brief Flags describing the role of a module header.
103 enum ModuleHeaderRole {
104 /// \brief This header is normally included in the module.
106 /// \brief This header is included but private.
108 /// \brief This header is part of the module (for layering purposes) but
109 /// should be textually included.
111 // Caution: Adding an enumerator needs other changes.
112 // Adjust the number of bits for KnownHeader::Storage.
113 // Adjust the bitfield HeaderFileInfo::HeaderRole size.
114 // Adjust the HeaderFileInfoTrait::ReadData streaming.
115 // Adjust the HeaderFileInfoTrait::EmitData streaming.
116 // Adjust ModuleMap::addHeader.
119 /// \brief A header that is known to reside within a given module,
120 /// whether it was included or excluded.
122 llvm::PointerIntPair<Module *, 2, ModuleHeaderRole> Storage;
125 KnownHeader() : Storage(nullptr, NormalHeader) { }
126 KnownHeader(Module *M, ModuleHeaderRole Role) : Storage(M, Role) { }
128 friend bool operator==(const KnownHeader &A, const KnownHeader &B) {
129 return A.Storage == B.Storage;
131 friend bool operator!=(const KnownHeader &A, const KnownHeader &B) {
132 return A.Storage != B.Storage;
135 /// \brief Retrieve the module the header is stored in.
136 Module *getModule() const { return Storage.getPointer(); }
138 /// \brief The role of this header within the module.
139 ModuleHeaderRole getRole() const { return Storage.getInt(); }
141 /// \brief Whether this header is available in the module.
142 bool isAvailable() const {
143 return getModule()->isAvailable();
146 /// \brief Whether this header is accessible from the specified module.
147 bool isAccessibleFrom(Module *M) const {
148 return !(getRole() & PrivateHeader) ||
149 (M && M->getTopLevelModule() == getModule()->getTopLevelModule());
152 // \brief Whether this known header is valid (i.e., it has an
153 // associated module).
154 explicit operator bool() const {
155 return Storage.getPointer() != nullptr;
159 typedef llvm::SmallPtrSet<const FileEntry *, 1> AdditionalModMapsSet;
162 typedef llvm::DenseMap<const FileEntry *, SmallVector<KnownHeader, 1>>
165 /// \brief Mapping from each header to the module that owns the contents of
169 /// \brief Mapping from directories with umbrella headers to the module
170 /// that is generated from the umbrella header.
172 /// This mapping is used to map headers that haven't explicitly been named
173 /// in the module map over to the module that includes them via its umbrella
175 llvm::DenseMap<const DirectoryEntry *, Module *> UmbrellaDirs;
177 /// \brief The set of attributes that can be attached to a module.
180 : IsSystem(), IsExternC(), IsExhaustive(), NoUndeclaredIncludes() {}
182 /// \brief Whether this is a system module.
183 unsigned IsSystem : 1;
185 /// \brief Whether this is an extern "C" module.
186 unsigned IsExternC : 1;
188 /// \brief Whether this is an exhaustive set of configuration macros.
189 unsigned IsExhaustive : 1;
191 /// \brief Whether files in this module can only include non-modular headers
192 /// and headers from used modules.
193 unsigned NoUndeclaredIncludes : 1;
196 /// \brief A directory for which framework modules can be inferred.
197 struct InferredDirectory {
198 InferredDirectory() : InferModules() {}
200 /// \brief Whether to infer modules from this directory.
201 unsigned InferModules : 1;
203 /// \brief The attributes to use for inferred modules.
206 /// \brief If \c InferModules is non-zero, the module map file that allowed
207 /// inferred modules. Otherwise, nullptr.
208 const FileEntry *ModuleMapFile;
210 /// \brief The names of modules that cannot be inferred within this
212 SmallVector<std::string, 2> ExcludedModules;
215 /// \brief A mapping from directories to information about inferring
216 /// framework modules from within those directories.
217 llvm::DenseMap<const DirectoryEntry *, InferredDirectory> InferredDirectories;
219 /// A mapping from an inferred module to the module map that allowed the
221 llvm::DenseMap<const Module *, const FileEntry *> InferredModuleAllowedBy;
223 llvm::DenseMap<const Module *, AdditionalModMapsSet> AdditionalModMaps;
225 /// \brief Describes whether we haved parsed a particular file as a module
227 llvm::DenseMap<const FileEntry *, bool> ParsedModuleMap;
229 friend class ModuleMapParser;
231 /// \brief Resolve the given export declaration into an actual export
234 /// \param Mod The module in which we're resolving the export declaration.
236 /// \param Unresolved The export declaration to resolve.
238 /// \param Complain Whether this routine should complain about unresolvable
241 /// \returns The resolved export declaration, which will have a NULL pointer
242 /// if the export could not be resolved.
244 resolveExport(Module *Mod, const Module::UnresolvedExportDecl &Unresolved,
245 bool Complain) const;
247 /// \brief Resolve the given module id to an actual module.
249 /// \param Id The module-id to resolve.
251 /// \param Mod The module in which we're resolving the module-id.
253 /// \param Complain Whether this routine should complain about unresolvable
256 /// \returns The resolved module, or null if the module-id could not be
258 Module *resolveModuleId(const ModuleId &Id, Module *Mod, bool Complain) const;
260 /// \brief Looks up the modules that \p File corresponds to.
262 /// If \p File represents a builtin header within Clang's builtin include
263 /// directory, this also loads all of the module maps to see if it will get
264 /// associated with a specific module (e.g. in /usr/include).
265 HeadersMap::iterator findKnownHeader(const FileEntry *File);
267 /// \brief Searches for a module whose umbrella directory contains \p File.
269 /// \param File The header to search for.
271 /// \param IntermediateDirs On success, contains the set of directories
272 /// searched before finding \p File.
273 KnownHeader findHeaderInUmbrellaDirs(const FileEntry *File,
274 SmallVectorImpl<const DirectoryEntry *> &IntermediateDirs);
276 /// \brief Given that \p File is not in the Headers map, look it up within
277 /// umbrella directories and find or create a module for it.
278 KnownHeader findOrCreateModuleForHeaderInUmbrellaDir(const FileEntry *File);
280 /// \brief A convenience method to determine if \p File is (possibly nested)
281 /// in an umbrella directory.
282 bool isHeaderInUmbrellaDirs(const FileEntry *File) {
283 SmallVector<const DirectoryEntry *, 2> IntermediateDirs;
284 return static_cast<bool>(findHeaderInUmbrellaDirs(File, IntermediateDirs));
287 Module *inferFrameworkModule(const DirectoryEntry *FrameworkDir,
288 Attributes Attrs, Module *Parent);
291 /// \brief Construct a new module map.
293 /// \param SourceMgr The source manager used to find module files and headers.
294 /// This source manager should be shared with the header-search mechanism,
295 /// since they will refer to the same headers.
297 /// \param Diags A diagnostic engine used for diagnostics.
299 /// \param LangOpts Language options for this translation unit.
301 /// \param Target The target for this translation unit.
302 ModuleMap(SourceManager &SourceMgr, DiagnosticsEngine &Diags,
303 const LangOptions &LangOpts, const TargetInfo *Target,
304 HeaderSearch &HeaderInfo);
306 /// \brief Destroy the module map.
310 /// \brief Set the target information.
311 void setTarget(const TargetInfo &Target);
313 /// \brief Set the directory that contains Clang-supplied include
314 /// files, such as our stdarg.h or tgmath.h.
315 void setBuiltinIncludeDir(const DirectoryEntry *Dir) {
316 BuiltinIncludeDir = Dir;
319 /// \brief Add a module map callback.
320 void addModuleMapCallbacks(std::unique_ptr<ModuleMapCallbacks> Callback) {
321 Callbacks.push_back(std::move(Callback));
324 /// \brief Retrieve the module that owns the given header file, if any.
326 /// \param File The header file that is likely to be included.
328 /// \param AllowTextual If \c true and \p File is a textual header, return
329 /// its owning module. Otherwise, no KnownHeader will be returned if the
330 /// file is only known as a textual header.
332 /// \returns The module KnownHeader, which provides the module that owns the
333 /// given header file. The KnownHeader is default constructed to indicate
334 /// that no module owns this header file.
335 KnownHeader findModuleForHeader(const FileEntry *File,
336 bool AllowTextual = false);
338 /// \brief Retrieve all the modules that contain the given header file. This
339 /// may not include umbrella modules, nor information from external sources,
340 /// if they have not yet been inferred / loaded.
342 /// Typically, \ref findModuleForHeader should be used instead, as it picks
343 /// the preferred module for the header.
344 ArrayRef<KnownHeader> findAllModulesForHeader(const FileEntry *File) const;
346 /// \brief Reports errors if a module must not include a specific file.
348 /// \param RequestingModule The module including a file.
350 /// \param RequestingModuleIsModuleInterface \c true if the inclusion is in
351 /// the interface of RequestingModule, \c false if it's in the
352 /// implementation of RequestingModule. Value is ignored and
353 /// meaningless if RequestingModule is nullptr.
355 /// \param FilenameLoc The location of the inclusion's filename.
357 /// \param Filename The included filename as written.
359 /// \param File The included file.
360 void diagnoseHeaderInclusion(Module *RequestingModule,
361 bool RequestingModuleIsModuleInterface,
362 SourceLocation FilenameLoc, StringRef Filename,
363 const FileEntry *File);
365 /// \brief Determine whether the given header is part of a module
366 /// marked 'unavailable'.
367 bool isHeaderInUnavailableModule(const FileEntry *Header) const;
369 /// \brief Determine whether the given header is unavailable as part
370 /// of the specified module.
371 bool isHeaderUnavailableInModule(const FileEntry *Header,
372 const Module *RequestingModule) const;
374 /// \brief Retrieve a module with the given name.
376 /// \param Name The name of the module to look up.
378 /// \returns The named module, if known; otherwise, returns null.
379 Module *findModule(StringRef Name) const;
381 /// \brief Retrieve a module with the given name using lexical name lookup,
382 /// starting at the given context.
384 /// \param Name The name of the module to look up.
386 /// \param Context The module context, from which we will perform lexical
389 /// \returns The named module, if known; otherwise, returns null.
390 Module *lookupModuleUnqualified(StringRef Name, Module *Context) const;
392 /// \brief Retrieve a module with the given name within the given context,
393 /// using direct (qualified) name lookup.
395 /// \param Name The name of the module to look up.
397 /// \param Context The module for which we will look for a submodule. If
398 /// null, we will look for a top-level module.
400 /// \returns The named submodule, if known; otherwose, returns null.
401 Module *lookupModuleQualified(StringRef Name, Module *Context) const;
403 /// \brief Find a new module or submodule, or create it if it does not already
406 /// \param Name The name of the module to find or create.
408 /// \param Parent The module that will act as the parent of this submodule,
409 /// or NULL to indicate that this is a top-level module.
411 /// \param IsFramework Whether this is a framework module.
413 /// \param IsExplicit Whether this is an explicit submodule.
415 /// \returns The found or newly-created module, along with a boolean value
416 /// that will be true if the module is newly-created.
417 std::pair<Module *, bool> findOrCreateModule(StringRef Name, Module *Parent,
421 /// \brief Create a new module for a C++ Modules TS module interface unit.
422 /// The module must not already exist, and will be configured for the current
425 /// Note that this also sets the current module to the newly-created module.
427 /// \returns The newly-created module.
428 Module *createModuleForInterfaceUnit(SourceLocation Loc, StringRef Name);
430 /// \brief Infer the contents of a framework module map from the given
431 /// framework directory.
432 Module *inferFrameworkModule(const DirectoryEntry *FrameworkDir,
433 bool IsSystem, Module *Parent);
435 /// \brief Retrieve the module map file containing the definition of the given
438 /// \param Module The module whose module map file will be returned, if known.
440 /// \returns The file entry for the module map file containing the given
441 /// module, or NULL if the module definition was inferred.
442 const FileEntry *getContainingModuleMapFile(const Module *Module) const;
444 /// \brief Get the module map file that (along with the module name) uniquely
445 /// identifies this module.
447 /// The particular module that \c Name refers to may depend on how the module
448 /// was found in header search. However, the combination of \c Name and
449 /// this module map will be globally unique for top-level modules. In the case
450 /// of inferred modules, returns the module map that allowed the inference
451 /// (e.g. contained 'module *'). Otherwise, returns
452 /// getContainingModuleMapFile().
453 const FileEntry *getModuleMapFileForUniquing(const Module *M) const;
455 void setInferredModuleAllowedBy(Module *M, const FileEntry *ModuleMap);
457 /// \brief Get any module map files other than getModuleMapFileForUniquing(M)
458 /// that define submodules of a top-level module \p M. This is cheaper than
459 /// getting the module map file for each submodule individually, since the
460 /// expected number of results is very small.
461 AdditionalModMapsSet *getAdditionalModuleMapFiles(const Module *M) {
462 auto I = AdditionalModMaps.find(M);
463 if (I == AdditionalModMaps.end())
468 void addAdditionalModuleMapFile(const Module *M, const FileEntry *ModuleMap) {
469 AdditionalModMaps[M].insert(ModuleMap);
472 /// \brief Resolve all of the unresolved exports in the given module.
474 /// \param Mod The module whose exports should be resolved.
476 /// \param Complain Whether to emit diagnostics for failures.
478 /// \returns true if any errors were encountered while resolving exports,
480 bool resolveExports(Module *Mod, bool Complain);
482 /// \brief Resolve all of the unresolved uses in the given module.
484 /// \param Mod The module whose uses should be resolved.
486 /// \param Complain Whether to emit diagnostics for failures.
488 /// \returns true if any errors were encountered while resolving uses,
490 bool resolveUses(Module *Mod, bool Complain);
492 /// \brief Resolve all of the unresolved conflicts in the given module.
494 /// \param Mod The module whose conflicts should be resolved.
496 /// \param Complain Whether to emit diagnostics for failures.
498 /// \returns true if any errors were encountered while resolving conflicts,
500 bool resolveConflicts(Module *Mod, bool Complain);
502 /// \brief Infers the (sub)module based on the given source location and
505 /// \param Loc The location within the source that we are querying, along
506 /// with its source manager.
508 /// \returns The module that owns this source location, or null if no
509 /// module owns this source location.
510 Module *inferModuleFromLocation(FullSourceLoc Loc);
512 /// \brief Sets the umbrella header of the given module to the given
514 void setUmbrellaHeader(Module *Mod, const FileEntry *UmbrellaHeader,
515 Twine NameAsWritten);
517 /// \brief Sets the umbrella directory of the given module to the given
519 void setUmbrellaDir(Module *Mod, const DirectoryEntry *UmbrellaDir,
520 Twine NameAsWritten);
522 /// \brief Adds this header to the given module.
523 /// \param Role The role of the header wrt the module.
524 void addHeader(Module *Mod, Module::Header Header,
525 ModuleHeaderRole Role, bool Imported = false);
527 /// \brief Marks this header as being excluded from the given module.
528 void excludeHeader(Module *Mod, Module::Header Header);
530 /// \brief Parse the given module map file, and record any modules we
533 /// \param File The file to be parsed.
535 /// \param IsSystem Whether this module map file is in a system header
536 /// directory, and therefore should be considered a system module.
538 /// \param HomeDir The directory in which relative paths within this module
539 /// map file will be resolved.
541 /// \param ExternModuleLoc The location of the "extern module" declaration
542 /// that caused us to load this module map file, if any.
544 /// \returns true if an error occurred, false otherwise.
545 bool parseModuleMapFile(const FileEntry *File, bool IsSystem,
546 const DirectoryEntry *HomeDir,
547 SourceLocation ExternModuleLoc = SourceLocation());
549 /// \brief Dump the contents of the module map, for debugging purposes.
552 typedef llvm::StringMap<Module *>::const_iterator module_iterator;
553 module_iterator module_begin() const { return Modules.begin(); }
554 module_iterator module_end() const { return Modules.end(); }
557 } // end namespace clang
559 #endif // LLVM_CLANG_LEX_MODULEMAP_H