1 //===--- ModuleMap.h - Describe the layout of modules -----------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the ModuleMap interface, which describes the layout of a
11 // module as it relates to headers.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 
16 #ifndef LLVM_CLANG_LEX_MODULEMAP_H
17 #define LLVM_CLANG_LEX_MODULEMAP_H
18 
19 #include "clang/Basic/LangOptions.h"
20 #include "clang/Basic/Module.h"
21 #include "clang/Basic/SourceLocation.h"
22 #include "clang/Basic/SourceManager.h"
23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/IntrusiveRefCntPtr.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/StringMap.h"
27 #include "llvm/ADT/StringRef.h"
28 #include <string>
29 
30 namespace clang {
31 
32 class DirectoryEntry;
33 class FileEntry;
34 class FileManager;
35 class DiagnosticConsumer;
36 class DiagnosticsEngine;
37 class HeaderSearch;
38 class ModuleMapParser;
39 
40 /// \brief A mechanism to observe the actions of the module map parser as it
41 /// reads module map files.
42 class ModuleMapCallbacks {
43 public:
44   virtual ~ModuleMapCallbacks() {}
45 
46   /// \brief Called when a module map file has been read.
47   ///
48   /// \param FileStart A SourceLocation referring to the start of the file's
49   /// contents.
50   /// \param File The file itself.
51   /// \param IsSystem Whether this is a module map from a system include path.
52   virtual void moduleMapFileRead(SourceLocation FileStart,
53                                  const FileEntry &File, bool IsSystem) {}
54 
55   /// \brief Called when a header is added during module map parsing.
56   ///
57   /// \param Filename The header file itself.
58   virtual void moduleMapAddHeader(StringRef Filename) {}
59 
60   /// \brief Called when an umbrella header is added during module map parsing.
61   ///
62   /// \param FileMgr FileManager instance
63   /// \param Header The umbrella header to collect.
64   virtual void moduleMapAddUmbrellaHeader(FileManager *FileMgr,
65                                           const FileEntry *Header) {}
66 };
67 
68 class ModuleMap {
69   SourceManager &SourceMgr;
70   DiagnosticsEngine &Diags;
71   const LangOptions &LangOpts;
72   const TargetInfo *Target;
73   HeaderSearch &HeaderInfo;
74 
75   llvm::SmallVector<std::unique_ptr<ModuleMapCallbacks>, 1> Callbacks;
76 
77   /// \brief The directory used for Clang-supplied, builtin include headers,
78   /// such as "stdint.h".
79   const DirectoryEntry *BuiltinIncludeDir;
80 
81   /// \brief Language options used to parse the module map itself.
82   ///
83   /// These are always simple C language options.
84   LangOptions MMapLangOpts;
85 
86   // The module that the main source file is associated with (the module
87   // named LangOpts::CurrentModule, if we've loaded it).
88   Module *SourceModule;
89 
90   /// \brief The top-level modules that are known.
91   llvm::StringMap<Module *> Modules;
92 
93   /// \brief The number of modules we have created in total.
94   unsigned NumCreatedModules;
95 
96 public:
97   /// \brief Flags describing the role of a module header.
98   enum ModuleHeaderRole {
99     /// \brief This header is normally included in the module.
100     NormalHeader  = 0x0,
101     /// \brief This header is included but private.
102     PrivateHeader = 0x1,
103     /// \brief This header is part of the module (for layering purposes) but
104     /// should be textually included.
105     TextualHeader = 0x2,
106     // Caution: Adding an enumerator needs other changes.
107     // Adjust the number of bits for KnownHeader::Storage.
108     // Adjust the bitfield HeaderFileInfo::HeaderRole size.
109     // Adjust the HeaderFileInfoTrait::ReadData streaming.
110     // Adjust the HeaderFileInfoTrait::EmitData streaming.
111     // Adjust ModuleMap::addHeader.
112   };
113 
114   /// \brief A header that is known to reside within a given module,
115   /// whether it was included or excluded.
116   class KnownHeader {
117     llvm::PointerIntPair<Module *, 2, ModuleHeaderRole> Storage;
118 
119   public:
120     KnownHeader() : Storage(nullptr, NormalHeader) { }
121     KnownHeader(Module *M, ModuleHeaderRole Role) : Storage(M, Role) { }
122 
123     friend bool operator==(const KnownHeader &A, const KnownHeader &B) {
124       return A.Storage == B.Storage;
125     }
126     friend bool operator!=(const KnownHeader &A, const KnownHeader &B) {
127       return A.Storage != B.Storage;
128     }
129 
130     /// \brief Retrieve the module the header is stored in.
131     Module *getModule() const { return Storage.getPointer(); }
132 
133     /// \brief The role of this header within the module.
134     ModuleHeaderRole getRole() const { return Storage.getInt(); }
135 
136     /// \brief Whether this header is available in the module.
137     bool isAvailable() const {
138       return getModule()->isAvailable();
139     }
140 
141     /// \brief Whether this header is accessible from the specified module.
142     bool isAccessibleFrom(Module *M) const {
143       return !(getRole() & PrivateHeader) ||
144              (M && M->getTopLevelModule() == getModule()->getTopLevelModule());
145     }
146 
147     // \brief Whether this known header is valid (i.e., it has an
148     // associated module).
149     explicit operator bool() const {
150       return Storage.getPointer() != nullptr;
151     }
152   };
153 
154   typedef llvm::SmallPtrSet<const FileEntry *, 1> AdditionalModMapsSet;
155 
156 private:
157   typedef llvm::DenseMap<const FileEntry *, SmallVector<KnownHeader, 1> >
158   HeadersMap;
159 
160   /// \brief Mapping from each header to the module that owns the contents of
161   /// that header.
162   HeadersMap Headers;
163 
164   /// \brief Mapping from directories with umbrella headers to the module
165   /// that is generated from the umbrella header.
166   ///
167   /// This mapping is used to map headers that haven't explicitly been named
168   /// in the module map over to the module that includes them via its umbrella
169   /// header.
170   llvm::DenseMap<const DirectoryEntry *, Module *> UmbrellaDirs;
171 
172   /// \brief The set of attributes that can be attached to a module.
173   struct Attributes {
174     Attributes() : IsSystem(), IsExternC(), IsExhaustive() {}
175 
176     /// \brief Whether this is a system module.
177     unsigned IsSystem : 1;
178 
179     /// \brief Whether this is an extern "C" module.
180     unsigned IsExternC : 1;
181 
182     /// \brief Whether this is an exhaustive set of configuration macros.
183     unsigned IsExhaustive : 1;
184   };
185 
186   /// \brief A directory for which framework modules can be inferred.
187   struct InferredDirectory {
188     InferredDirectory() : InferModules() {}
189 
190     /// \brief Whether to infer modules from this directory.
191     unsigned InferModules : 1;
192 
193     /// \brief The attributes to use for inferred modules.
194     Attributes Attrs;
195 
196     /// \brief If \c InferModules is non-zero, the module map file that allowed
197     /// inferred modules.  Otherwise, nullptr.
198     const FileEntry *ModuleMapFile;
199 
200     /// \brief The names of modules that cannot be inferred within this
201     /// directory.
202     SmallVector<std::string, 2> ExcludedModules;
203   };
204 
205   /// \brief A mapping from directories to information about inferring
206   /// framework modules from within those directories.
207   llvm::DenseMap<const DirectoryEntry *, InferredDirectory> InferredDirectories;
208 
209   /// A mapping from an inferred module to the module map that allowed the
210   /// inference.
211   llvm::DenseMap<const Module *, const FileEntry *> InferredModuleAllowedBy;
212 
213   llvm::DenseMap<const Module *, AdditionalModMapsSet> AdditionalModMaps;
214 
215   /// \brief Describes whether we haved parsed a particular file as a module
216   /// map.
217   llvm::DenseMap<const FileEntry *, bool> ParsedModuleMap;
218 
219   friend class ModuleMapParser;
220 
221   /// \brief Resolve the given export declaration into an actual export
222   /// declaration.
223   ///
224   /// \param Mod The module in which we're resolving the export declaration.
225   ///
226   /// \param Unresolved The export declaration to resolve.
227   ///
228   /// \param Complain Whether this routine should complain about unresolvable
229   /// exports.
230   ///
231   /// \returns The resolved export declaration, which will have a NULL pointer
232   /// if the export could not be resolved.
233   Module::ExportDecl
234   resolveExport(Module *Mod, const Module::UnresolvedExportDecl &Unresolved,
235                 bool Complain) const;
236 
237   /// \brief Resolve the given module id to an actual module.
238   ///
239   /// \param Id The module-id to resolve.
240   ///
241   /// \param Mod The module in which we're resolving the module-id.
242   ///
243   /// \param Complain Whether this routine should complain about unresolvable
244   /// module-ids.
245   ///
246   /// \returns The resolved module, or null if the module-id could not be
247   /// resolved.
248   Module *resolveModuleId(const ModuleId &Id, Module *Mod, bool Complain) const;
249 
250   /// \brief Looks up the modules that \p File corresponds to.
251   ///
252   /// If \p File represents a builtin header within Clang's builtin include
253   /// directory, this also loads all of the module maps to see if it will get
254   /// associated with a specific module (e.g. in /usr/include).
255   HeadersMap::iterator findKnownHeader(const FileEntry *File);
256 
257   /// \brief Searches for a module whose umbrella directory contains \p File.
258   ///
259   /// \param File The header to search for.
260   ///
261   /// \param IntermediateDirs On success, contains the set of directories
262   /// searched before finding \p File.
263   KnownHeader findHeaderInUmbrellaDirs(const FileEntry *File,
264                     SmallVectorImpl<const DirectoryEntry *> &IntermediateDirs);
265 
266   /// \brief Given that \p File is not in the Headers map, look it up within
267   /// umbrella directories and find or create a module for it.
268   KnownHeader findOrCreateModuleForHeaderInUmbrellaDir(const FileEntry *File);
269 
270   /// \brief A convenience method to determine if \p File is (possibly nested)
271   /// in an umbrella directory.
272   bool isHeaderInUmbrellaDirs(const FileEntry *File) {
273     SmallVector<const DirectoryEntry *, 2> IntermediateDirs;
274     return static_cast<bool>(findHeaderInUmbrellaDirs(File, IntermediateDirs));
275   }
276 
277   Module *inferFrameworkModule(const DirectoryEntry *FrameworkDir,
278                                Attributes Attrs, Module *Parent);
279 
280 public:
281   /// \brief Construct a new module map.
282   ///
283   /// \param SourceMgr The source manager used to find module files and headers.
284   /// This source manager should be shared with the header-search mechanism,
285   /// since they will refer to the same headers.
286   ///
287   /// \param Diags A diagnostic engine used for diagnostics.
288   ///
289   /// \param LangOpts Language options for this translation unit.
290   ///
291   /// \param Target The target for this translation unit.
292   ModuleMap(SourceManager &SourceMgr, DiagnosticsEngine &Diags,
293             const LangOptions &LangOpts, const TargetInfo *Target,
294             HeaderSearch &HeaderInfo);
295 
296   /// \brief Destroy the module map.
297   ///
298   ~ModuleMap();
299 
300   /// \brief Set the target information.
301   void setTarget(const TargetInfo &Target);
302 
303   /// \brief Set the directory that contains Clang-supplied include
304   /// files, such as our stdarg.h or tgmath.h.
305   void setBuiltinIncludeDir(const DirectoryEntry *Dir) {
306     BuiltinIncludeDir = Dir;
307   }
308 
309   /// \brief Add a module map callback.
310   void addModuleMapCallbacks(std::unique_ptr<ModuleMapCallbacks> Callback) {
311     Callbacks.push_back(std::move(Callback));
312   }
313 
314   /// \brief Retrieve the module that owns the given header file, if any.
315   ///
316   /// \param File The header file that is likely to be included.
317   ///
318   /// \returns The module KnownHeader, which provides the module that owns the
319   /// given header file.  The KnownHeader is default constructed to indicate
320   /// that no module owns this header file.
321   KnownHeader findModuleForHeader(const FileEntry *File);
322 
323   /// \brief Retrieve all the modules that contain the given header file. This
324   /// may not include umbrella modules, nor information from external sources,
325   /// if they have not yet been inferred / loaded.
326   ///
327   /// Typically, \ref findModuleForHeader should be used instead, as it picks
328   /// the preferred module for the header.
329   ArrayRef<KnownHeader> findAllModulesForHeader(const FileEntry *File) const;
330 
331   /// \brief Reports errors if a module must not include a specific file.
332   ///
333   /// \param RequestingModule The module including a file.
334   ///
335   /// \param RequestingModuleIsModuleInterface \c true if the inclusion is in
336   ///        the interface of RequestingModule, \c false if it's in the
337   ///        implementation of RequestingModule. Value is ignored and
338   ///        meaningless if RequestingModule is nullptr.
339   ///
340   /// \param FilenameLoc The location of the inclusion's filename.
341   ///
342   /// \param Filename The included filename as written.
343   ///
344   /// \param File The included file.
345   void diagnoseHeaderInclusion(Module *RequestingModule,
346                                bool RequestingModuleIsModuleInterface,
347                                SourceLocation FilenameLoc, StringRef Filename,
348                                const FileEntry *File);
349 
350   /// \brief Determine whether the given header is part of a module
351   /// marked 'unavailable'.
352   bool isHeaderInUnavailableModule(const FileEntry *Header) const;
353 
354   /// \brief Determine whether the given header is unavailable as part
355   /// of the specified module.
356   bool isHeaderUnavailableInModule(const FileEntry *Header,
357                                    const Module *RequestingModule) const;
358 
359   /// \brief Retrieve a module with the given name.
360   ///
361   /// \param Name The name of the module to look up.
362   ///
363   /// \returns The named module, if known; otherwise, returns null.
364   Module *findModule(StringRef Name) const;
365 
366   /// \brief Retrieve a module with the given name using lexical name lookup,
367   /// starting at the given context.
368   ///
369   /// \param Name The name of the module to look up.
370   ///
371   /// \param Context The module context, from which we will perform lexical
372   /// name lookup.
373   ///
374   /// \returns The named module, if known; otherwise, returns null.
375   Module *lookupModuleUnqualified(StringRef Name, Module *Context) const;
376 
377   /// \brief Retrieve a module with the given name within the given context,
378   /// using direct (qualified) name lookup.
379   ///
380   /// \param Name The name of the module to look up.
381   ///
382   /// \param Context The module for which we will look for a submodule. If
383   /// null, we will look for a top-level module.
384   ///
385   /// \returns The named submodule, if known; otherwose, returns null.
386   Module *lookupModuleQualified(StringRef Name, Module *Context) const;
387 
388   /// \brief Find a new module or submodule, or create it if it does not already
389   /// exist.
390   ///
391   /// \param Name The name of the module to find or create.
392   ///
393   /// \param Parent The module that will act as the parent of this submodule,
394   /// or NULL to indicate that this is a top-level module.
395   ///
396   /// \param IsFramework Whether this is a framework module.
397   ///
398   /// \param IsExplicit Whether this is an explicit submodule.
399   ///
400   /// \returns The found or newly-created module, along with a boolean value
401   /// that will be true if the module is newly-created.
402   std::pair<Module *, bool> findOrCreateModule(StringRef Name, Module *Parent,
403                                                bool IsFramework,
404                                                bool IsExplicit);
405 
406   /// \brief Create a new module for a C++ Modules TS module interface unit.
407   /// The module must not already exist, and will be configured for the current
408   /// compilation.
409   ///
410   /// Note that this also sets the current module to the newly-created module.
411   ///
412   /// \returns The newly-created module.
413   Module *createModuleForInterfaceUnit(SourceLocation Loc, StringRef Name);
414 
415   /// \brief Infer the contents of a framework module map from the given
416   /// framework directory.
417   Module *inferFrameworkModule(const DirectoryEntry *FrameworkDir,
418                                bool IsSystem, Module *Parent);
419 
420   /// \brief Retrieve the module map file containing the definition of the given
421   /// module.
422   ///
423   /// \param Module The module whose module map file will be returned, if known.
424   ///
425   /// \returns The file entry for the module map file containing the given
426   /// module, or NULL if the module definition was inferred.
427   const FileEntry *getContainingModuleMapFile(const Module *Module) const;
428 
429   /// \brief Get the module map file that (along with the module name) uniquely
430   /// identifies this module.
431   ///
432   /// The particular module that \c Name refers to may depend on how the module
433   /// was found in header search. However, the combination of \c Name and
434   /// this module map will be globally unique for top-level modules. In the case
435   /// of inferred modules, returns the module map that allowed the inference
436   /// (e.g. contained 'module *'). Otherwise, returns
437   /// getContainingModuleMapFile().
438   const FileEntry *getModuleMapFileForUniquing(const Module *M) const;
439 
440   void setInferredModuleAllowedBy(Module *M, const FileEntry *ModuleMap);
441 
442   /// \brief Get any module map files other than getModuleMapFileForUniquing(M)
443   /// that define submodules of a top-level module \p M. This is cheaper than
444   /// getting the module map file for each submodule individually, since the
445   /// expected number of results is very small.
446   AdditionalModMapsSet *getAdditionalModuleMapFiles(const Module *M) {
447     auto I = AdditionalModMaps.find(M);
448     if (I == AdditionalModMaps.end())
449       return nullptr;
450     return &I->second;
451   }
452 
453   void addAdditionalModuleMapFile(const Module *M, const FileEntry *ModuleMap) {
454     AdditionalModMaps[M].insert(ModuleMap);
455   }
456 
457   /// \brief Resolve all of the unresolved exports in the given module.
458   ///
459   /// \param Mod The module whose exports should be resolved.
460   ///
461   /// \param Complain Whether to emit diagnostics for failures.
462   ///
463   /// \returns true if any errors were encountered while resolving exports,
464   /// false otherwise.
465   bool resolveExports(Module *Mod, bool Complain);
466 
467   /// \brief Resolve all of the unresolved uses in the given module.
468   ///
469   /// \param Mod The module whose uses should be resolved.
470   ///
471   /// \param Complain Whether to emit diagnostics for failures.
472   ///
473   /// \returns true if any errors were encountered while resolving uses,
474   /// false otherwise.
475   bool resolveUses(Module *Mod, bool Complain);
476 
477   /// \brief Resolve all of the unresolved conflicts in the given module.
478   ///
479   /// \param Mod The module whose conflicts should be resolved.
480   ///
481   /// \param Complain Whether to emit diagnostics for failures.
482   ///
483   /// \returns true if any errors were encountered while resolving conflicts,
484   /// false otherwise.
485   bool resolveConflicts(Module *Mod, bool Complain);
486 
487   /// \brief Infers the (sub)module based on the given source location and
488   /// source manager.
489   ///
490   /// \param Loc The location within the source that we are querying, along
491   /// with its source manager.
492   ///
493   /// \returns The module that owns this source location, or null if no
494   /// module owns this source location.
495   Module *inferModuleFromLocation(FullSourceLoc Loc);
496 
497   /// \brief Sets the umbrella header of the given module to the given
498   /// header.
499   void setUmbrellaHeader(Module *Mod, const FileEntry *UmbrellaHeader,
500                          Twine NameAsWritten);
501 
502   /// \brief Sets the umbrella directory of the given module to the given
503   /// directory.
504   void setUmbrellaDir(Module *Mod, const DirectoryEntry *UmbrellaDir,
505                       Twine NameAsWritten);
506 
507   /// \brief Adds this header to the given module.
508   /// \param Role The role of the header wrt the module.
509   void addHeader(Module *Mod, Module::Header Header,
510                  ModuleHeaderRole Role, bool Imported = false);
511 
512   /// \brief Marks this header as being excluded from the given module.
513   void excludeHeader(Module *Mod, Module::Header Header);
514 
515   /// \brief Parse the given module map file, and record any modules we
516   /// encounter.
517   ///
518   /// \param File The file to be parsed.
519   ///
520   /// \param IsSystem Whether this module map file is in a system header
521   /// directory, and therefore should be considered a system module.
522   ///
523   /// \param HomeDir The directory in which relative paths within this module
524   ///        map file will be resolved.
525   ///
526   /// \param ExternModuleLoc The location of the "extern module" declaration
527   ///        that caused us to load this module map file, if any.
528   ///
529   /// \returns true if an error occurred, false otherwise.
530   bool parseModuleMapFile(const FileEntry *File, bool IsSystem,
531                           const DirectoryEntry *HomeDir,
532                           SourceLocation ExternModuleLoc = SourceLocation());
533 
534   /// \brief Dump the contents of the module map, for debugging purposes.
535   void dump();
536 
537   typedef llvm::StringMap<Module *>::const_iterator module_iterator;
538   module_iterator module_begin() const { return Modules.begin(); }
539   module_iterator module_end()   const { return Modules.end(); }
540 };
541 
542 }
543 #endif
544