]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/include/clang/Lex/ModuleMap.h
Update lldb to trunk r290819 and resolve conflicts.
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / 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 #ifndef LLVM_CLANG_LEX_MODULEMAP_H
16 #define LLVM_CLANG_LEX_MODULEMAP_H
17
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"
30 #include <algorithm>
31 #include <memory>
32 #include <string>
33 #include <utility>
34
35 namespace clang {
36
37 class DirectoryEntry;
38 class FileEntry;
39 class FileManager;
40 class DiagnosticConsumer;
41 class DiagnosticsEngine;
42 class HeaderSearch;
43 class ModuleMapParser;
44
45 /// \brief A mechanism to observe the actions of the module map parser as it
46 /// reads module map files.
47 class ModuleMapCallbacks {
48 public:
49   virtual ~ModuleMapCallbacks() = default;
50
51   /// \brief Called when a module map file has been read.
52   ///
53   /// \param FileStart A SourceLocation referring to the start of the file's
54   /// contents.
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) {}
59
60   /// \brief Called when a header is added during module map parsing.
61   ///
62   /// \param Filename The header file itself.
63   virtual void moduleMapAddHeader(StringRef Filename) {}
64
65   /// \brief Called when an umbrella header is added during module map parsing.
66   ///
67   /// \param FileMgr FileManager instance
68   /// \param Header The umbrella header to collect.
69   virtual void moduleMapAddUmbrellaHeader(FileManager *FileMgr,
70                                           const FileEntry *Header) {}
71 };
72   
73 class ModuleMap {
74   SourceManager &SourceMgr;
75   DiagnosticsEngine &Diags;
76   const LangOptions &LangOpts;
77   const TargetInfo *Target;
78   HeaderSearch &HeaderInfo;
79
80   llvm::SmallVector<std::unique_ptr<ModuleMapCallbacks>, 1> Callbacks;
81   
82   /// \brief The directory used for Clang-supplied, builtin include headers,
83   /// such as "stdint.h".
84   const DirectoryEntry *BuiltinIncludeDir;
85   
86   /// \brief Language options used to parse the module map itself.
87   ///
88   /// These are always simple C language options.
89   LangOptions MMapLangOpts;
90
91   // The module that the main source file is associated with (the module
92   // named LangOpts::CurrentModule, if we've loaded it).
93   Module *SourceModule;
94
95   /// \brief The top-level modules that are known.
96   llvm::StringMap<Module *> Modules;
97
98   /// \brief The number of modules we have created in total.
99   unsigned NumCreatedModules;
100
101 public:
102   /// \brief Flags describing the role of a module header.
103   enum ModuleHeaderRole {
104     /// \brief This header is normally included in the module.
105     NormalHeader  = 0x0,
106     /// \brief This header is included but private.
107     PrivateHeader = 0x1,
108     /// \brief This header is part of the module (for layering purposes) but
109     /// should be textually included.
110     TextualHeader = 0x2,
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.
117   };
118
119   /// \brief A header that is known to reside within a given module,
120   /// whether it was included or excluded.
121   class KnownHeader {
122     llvm::PointerIntPair<Module *, 2, ModuleHeaderRole> Storage;
123
124   public:
125     KnownHeader() : Storage(nullptr, NormalHeader) { }
126     KnownHeader(Module *M, ModuleHeaderRole Role) : Storage(M, Role) { }
127
128     friend bool operator==(const KnownHeader &A, const KnownHeader &B) {
129       return A.Storage == B.Storage;
130     }
131     friend bool operator!=(const KnownHeader &A, const KnownHeader &B) {
132       return A.Storage != B.Storage;
133     }
134
135     /// \brief Retrieve the module the header is stored in.
136     Module *getModule() const { return Storage.getPointer(); }
137
138     /// \brief The role of this header within the module.
139     ModuleHeaderRole getRole() const { return Storage.getInt(); }
140
141     /// \brief Whether this header is available in the module.
142     bool isAvailable() const {
143       return getModule()->isAvailable();
144     }
145
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());
150     }
151
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;
156     }
157   };
158
159   typedef llvm::SmallPtrSet<const FileEntry *, 1> AdditionalModMapsSet;
160
161 private:
162   typedef llvm::DenseMap<const FileEntry *, SmallVector<KnownHeader, 1>>
163   HeadersMap;
164
165   /// \brief Mapping from each header to the module that owns the contents of
166   /// that header.
167   HeadersMap Headers;
168   
169   /// \brief Mapping from directories with umbrella headers to the module
170   /// that is generated from the umbrella header.
171   ///
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
174   /// header.
175   llvm::DenseMap<const DirectoryEntry *, Module *> UmbrellaDirs;
176
177   /// \brief The set of attributes that can be attached to a module.
178   struct Attributes {
179     Attributes()
180         : IsSystem(), IsExternC(), IsExhaustive(), NoUndeclaredIncludes() {}
181
182     /// \brief Whether this is a system module.
183     unsigned IsSystem : 1;
184
185     /// \brief Whether this is an extern "C" module.
186     unsigned IsExternC : 1;
187
188     /// \brief Whether this is an exhaustive set of configuration macros.
189     unsigned IsExhaustive : 1;
190
191     /// \brief Whether files in this module can only include non-modular headers
192     /// and headers from used modules.
193     unsigned NoUndeclaredIncludes : 1;
194   };
195
196   /// \brief A directory for which framework modules can be inferred.
197   struct InferredDirectory {
198     InferredDirectory() : InferModules() {}
199
200     /// \brief Whether to infer modules from this directory.
201     unsigned InferModules : 1;
202
203     /// \brief The attributes to use for inferred modules.
204     Attributes Attrs;
205
206     /// \brief If \c InferModules is non-zero, the module map file that allowed
207     /// inferred modules.  Otherwise, nullptr.
208     const FileEntry *ModuleMapFile;
209
210     /// \brief The names of modules that cannot be inferred within this
211     /// directory.
212     SmallVector<std::string, 2> ExcludedModules;
213   };
214
215   /// \brief A mapping from directories to information about inferring
216   /// framework modules from within those directories.
217   llvm::DenseMap<const DirectoryEntry *, InferredDirectory> InferredDirectories;
218
219   /// A mapping from an inferred module to the module map that allowed the
220   /// inference.
221   llvm::DenseMap<const Module *, const FileEntry *> InferredModuleAllowedBy;
222
223   llvm::DenseMap<const Module *, AdditionalModMapsSet> AdditionalModMaps;
224
225   /// \brief Describes whether we haved parsed a particular file as a module
226   /// map.
227   llvm::DenseMap<const FileEntry *, bool> ParsedModuleMap;
228
229   friend class ModuleMapParser;
230   
231   /// \brief Resolve the given export declaration into an actual export
232   /// declaration.
233   ///
234   /// \param Mod The module in which we're resolving the export declaration.
235   ///
236   /// \param Unresolved The export declaration to resolve.
237   ///
238   /// \param Complain Whether this routine should complain about unresolvable
239   /// exports.
240   ///
241   /// \returns The resolved export declaration, which will have a NULL pointer
242   /// if the export could not be resolved.
243   Module::ExportDecl 
244   resolveExport(Module *Mod, const Module::UnresolvedExportDecl &Unresolved,
245                 bool Complain) const;
246
247   /// \brief Resolve the given module id to an actual module.
248   ///
249   /// \param Id The module-id to resolve.
250   ///
251   /// \param Mod The module in which we're resolving the module-id.
252   ///
253   /// \param Complain Whether this routine should complain about unresolvable
254   /// module-ids.
255   ///
256   /// \returns The resolved module, or null if the module-id could not be
257   /// resolved.
258   Module *resolveModuleId(const ModuleId &Id, Module *Mod, bool Complain) const;
259
260   /// \brief Looks up the modules that \p File corresponds to.
261   ///
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);
266
267   /// \brief Searches for a module whose umbrella directory contains \p File.
268   ///
269   /// \param File The header to search for.
270   ///
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);
275
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);
279
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));
285   }
286
287   Module *inferFrameworkModule(const DirectoryEntry *FrameworkDir,
288                                Attributes Attrs, Module *Parent);
289
290 public:
291   /// \brief Construct a new module map.
292   ///
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.
296   ///
297   /// \param Diags A diagnostic engine used for diagnostics.
298   ///
299   /// \param LangOpts Language options for this translation unit.
300   ///
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);
305
306   /// \brief Destroy the module map.
307   ///
308   ~ModuleMap();
309
310   /// \brief Set the target information.
311   void setTarget(const TargetInfo &Target);
312
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;
317   }
318
319   /// \brief Add a module map callback.
320   void addModuleMapCallbacks(std::unique_ptr<ModuleMapCallbacks> Callback) {
321     Callbacks.push_back(std::move(Callback));
322   }
323
324   /// \brief Retrieve the module that owns the given header file, if any.
325   ///
326   /// \param File The header file that is likely to be included.
327   ///
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.
331   ///
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);
337
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.
341   ///
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;
345
346   /// \brief Reports errors if a module must not include a specific file.
347   ///
348   /// \param RequestingModule The module including a file.
349   ///
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.
354   ///
355   /// \param FilenameLoc The location of the inclusion's filename.
356   ///
357   /// \param Filename The included filename as written.
358   ///
359   /// \param File The included file.
360   void diagnoseHeaderInclusion(Module *RequestingModule,
361                                bool RequestingModuleIsModuleInterface,
362                                SourceLocation FilenameLoc, StringRef Filename,
363                                const FileEntry *File);
364
365   /// \brief Determine whether the given header is part of a module
366   /// marked 'unavailable'.
367   bool isHeaderInUnavailableModule(const FileEntry *Header) const;
368
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;
373
374   /// \brief Retrieve a module with the given name.
375   ///
376   /// \param Name The name of the module to look up.
377   ///
378   /// \returns The named module, if known; otherwise, returns null.
379   Module *findModule(StringRef Name) const;
380
381   /// \brief Retrieve a module with the given name using lexical name lookup,
382   /// starting at the given context.
383   ///
384   /// \param Name The name of the module to look up.
385   ///
386   /// \param Context The module context, from which we will perform lexical
387   /// name lookup.
388   ///
389   /// \returns The named module, if known; otherwise, returns null.
390   Module *lookupModuleUnqualified(StringRef Name, Module *Context) const;
391
392   /// \brief Retrieve a module with the given name within the given context,
393   /// using direct (qualified) name lookup.
394   ///
395   /// \param Name The name of the module to look up.
396   /// 
397   /// \param Context The module for which we will look for a submodule. If
398   /// null, we will look for a top-level module.
399   ///
400   /// \returns The named submodule, if known; otherwose, returns null.
401   Module *lookupModuleQualified(StringRef Name, Module *Context) const;
402   
403   /// \brief Find a new module or submodule, or create it if it does not already
404   /// exist.
405   ///
406   /// \param Name The name of the module to find or create.
407   ///
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.
410   ///
411   /// \param IsFramework Whether this is a framework module.
412   ///
413   /// \param IsExplicit Whether this is an explicit submodule.
414   ///
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,
418                                                bool IsFramework,
419                                                bool IsExplicit);
420
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
423   /// compilation.
424   ///
425   /// Note that this also sets the current module to the newly-created module.
426   ///
427   /// \returns The newly-created module.
428   Module *createModuleForInterfaceUnit(SourceLocation Loc, StringRef Name);
429
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);
434
435   /// \brief Retrieve the module map file containing the definition of the given
436   /// module.
437   ///
438   /// \param Module The module whose module map file will be returned, if known.
439   ///
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;
443
444   /// \brief Get the module map file that (along with the module name) uniquely
445   /// identifies this module.
446   ///
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;
454
455   void setInferredModuleAllowedBy(Module *M, const FileEntry *ModuleMap);
456
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())
464       return nullptr;
465     return &I->second;
466   }
467
468   void addAdditionalModuleMapFile(const Module *M, const FileEntry *ModuleMap) {
469     AdditionalModMaps[M].insert(ModuleMap);
470   }
471
472   /// \brief Resolve all of the unresolved exports in the given module.
473   ///
474   /// \param Mod The module whose exports should be resolved.
475   ///
476   /// \param Complain Whether to emit diagnostics for failures.
477   ///
478   /// \returns true if any errors were encountered while resolving exports,
479   /// false otherwise.
480   bool resolveExports(Module *Mod, bool Complain);
481
482   /// \brief Resolve all of the unresolved uses in the given module.
483   ///
484   /// \param Mod The module whose uses should be resolved.
485   ///
486   /// \param Complain Whether to emit diagnostics for failures.
487   ///
488   /// \returns true if any errors were encountered while resolving uses,
489   /// false otherwise.
490   bool resolveUses(Module *Mod, bool Complain);
491
492   /// \brief Resolve all of the unresolved conflicts in the given module.
493   ///
494   /// \param Mod The module whose conflicts should be resolved.
495   ///
496   /// \param Complain Whether to emit diagnostics for failures.
497   ///
498   /// \returns true if any errors were encountered while resolving conflicts,
499   /// false otherwise.
500   bool resolveConflicts(Module *Mod, bool Complain);
501
502   /// \brief Infers the (sub)module based on the given source location and
503   /// source manager.
504   ///
505   /// \param Loc The location within the source that we are querying, along
506   /// with its source manager.
507   ///
508   /// \returns The module that owns this source location, or null if no
509   /// module owns this source location.
510   Module *inferModuleFromLocation(FullSourceLoc Loc);
511   
512   /// \brief Sets the umbrella header of the given module to the given
513   /// header.
514   void setUmbrellaHeader(Module *Mod, const FileEntry *UmbrellaHeader,
515                          Twine NameAsWritten);
516
517   /// \brief Sets the umbrella directory of the given module to the given
518   /// directory.
519   void setUmbrellaDir(Module *Mod, const DirectoryEntry *UmbrellaDir,
520                       Twine NameAsWritten);
521
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);
526
527   /// \brief Marks this header as being excluded from the given module.
528   void excludeHeader(Module *Mod, Module::Header Header);
529
530   /// \brief Parse the given module map file, and record any modules we 
531   /// encounter.
532   ///
533   /// \param File The file to be parsed.
534   ///
535   /// \param IsSystem Whether this module map file is in a system header
536   /// directory, and therefore should be considered a system module.
537   ///
538   /// \param HomeDir The directory in which relative paths within this module
539   ///        map file will be resolved.
540   ///
541   /// \param ExternModuleLoc The location of the "extern module" declaration
542   ///        that caused us to load this module map file, if any.
543   ///
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());
548     
549   /// \brief Dump the contents of the module map, for debugging purposes.
550   void dump();
551   
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(); }
555 };
556   
557 } // end namespace clang
558
559 #endif // LLVM_CLANG_LEX_MODULEMAP_H