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