]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/include/clang/Lex/ModuleMap.h
Import Zstandard 1.2.0
[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 Get the directory that contains Clang-supplied include files.
320   const DirectoryEntry *getBuiltinDir() const {
321     return BuiltinIncludeDir;
322   }
323
324   /// \brief Is this a compiler builtin header?
325   static bool isBuiltinHeader(StringRef FileName);
326
327   /// \brief Add a module map callback.
328   void addModuleMapCallbacks(std::unique_ptr<ModuleMapCallbacks> Callback) {
329     Callbacks.push_back(std::move(Callback));
330   }
331
332   /// \brief Retrieve the module that owns the given header file, if any.
333   ///
334   /// \param File The header file that is likely to be included.
335   ///
336   /// \param AllowTextual If \c true and \p File is a textual header, return
337   /// its owning module. Otherwise, no KnownHeader will be returned if the
338   /// file is only known as a textual header.
339   ///
340   /// \returns The module KnownHeader, which provides the module that owns the
341   /// given header file.  The KnownHeader is default constructed to indicate
342   /// that no module owns this header file.
343   KnownHeader findModuleForHeader(const FileEntry *File,
344                                   bool AllowTextual = false);
345
346   /// \brief Retrieve all the modules that contain the given header file. This
347   /// may not include umbrella modules, nor information from external sources,
348   /// if they have not yet been inferred / loaded.
349   ///
350   /// Typically, \ref findModuleForHeader should be used instead, as it picks
351   /// the preferred module for the header.
352   ArrayRef<KnownHeader> findAllModulesForHeader(const FileEntry *File) const;
353
354   /// \brief Reports errors if a module must not include a specific file.
355   ///
356   /// \param RequestingModule The module including a file.
357   ///
358   /// \param RequestingModuleIsModuleInterface \c true if the inclusion is in
359   ///        the interface of RequestingModule, \c false if it's in the
360   ///        implementation of RequestingModule. Value is ignored and
361   ///        meaningless if RequestingModule is nullptr.
362   ///
363   /// \param FilenameLoc The location of the inclusion's filename.
364   ///
365   /// \param Filename The included filename as written.
366   ///
367   /// \param File The included file.
368   void diagnoseHeaderInclusion(Module *RequestingModule,
369                                bool RequestingModuleIsModuleInterface,
370                                SourceLocation FilenameLoc, StringRef Filename,
371                                const FileEntry *File);
372
373   /// \brief Determine whether the given header is part of a module
374   /// marked 'unavailable'.
375   bool isHeaderInUnavailableModule(const FileEntry *Header) const;
376
377   /// \brief Determine whether the given header is unavailable as part
378   /// of the specified module.
379   bool isHeaderUnavailableInModule(const FileEntry *Header,
380                                    const Module *RequestingModule) const;
381
382   /// \brief Retrieve a module with the given name.
383   ///
384   /// \param Name The name of the module to look up.
385   ///
386   /// \returns The named module, if known; otherwise, returns null.
387   Module *findModule(StringRef Name) const;
388
389   /// \brief Retrieve a module with the given name using lexical name lookup,
390   /// starting at the given context.
391   ///
392   /// \param Name The name of the module to look up.
393   ///
394   /// \param Context The module context, from which we will perform lexical
395   /// name lookup.
396   ///
397   /// \returns The named module, if known; otherwise, returns null.
398   Module *lookupModuleUnqualified(StringRef Name, Module *Context) const;
399
400   /// \brief Retrieve a module with the given name within the given context,
401   /// using direct (qualified) name lookup.
402   ///
403   /// \param Name The name of the module to look up.
404   /// 
405   /// \param Context The module for which we will look for a submodule. If
406   /// null, we will look for a top-level module.
407   ///
408   /// \returns The named submodule, if known; otherwose, returns null.
409   Module *lookupModuleQualified(StringRef Name, Module *Context) const;
410   
411   /// \brief Find a new module or submodule, or create it if it does not already
412   /// exist.
413   ///
414   /// \param Name The name of the module to find or create.
415   ///
416   /// \param Parent The module that will act as the parent of this submodule,
417   /// or NULL to indicate that this is a top-level module.
418   ///
419   /// \param IsFramework Whether this is a framework module.
420   ///
421   /// \param IsExplicit Whether this is an explicit submodule.
422   ///
423   /// \returns The found or newly-created module, along with a boolean value
424   /// that will be true if the module is newly-created.
425   std::pair<Module *, bool> findOrCreateModule(StringRef Name, Module *Parent,
426                                                bool IsFramework,
427                                                bool IsExplicit);
428
429   /// \brief Create a new module for a C++ Modules TS module interface unit.
430   /// The module must not already exist, and will be configured for the current
431   /// compilation.
432   ///
433   /// Note that this also sets the current module to the newly-created module.
434   ///
435   /// \returns The newly-created module.
436   Module *createModuleForInterfaceUnit(SourceLocation Loc, StringRef Name);
437
438   /// \brief Infer the contents of a framework module map from the given
439   /// framework directory.
440   Module *inferFrameworkModule(const DirectoryEntry *FrameworkDir,
441                                bool IsSystem, Module *Parent);
442
443   /// \brief Retrieve the module map file containing the definition of the given
444   /// module.
445   ///
446   /// \param Module The module whose module map file will be returned, if known.
447   ///
448   /// \returns The file entry for the module map file containing the given
449   /// module, or NULL if the module definition was inferred.
450   const FileEntry *getContainingModuleMapFile(const Module *Module) const;
451
452   /// \brief Get the module map file that (along with the module name) uniquely
453   /// identifies this module.
454   ///
455   /// The particular module that \c Name refers to may depend on how the module
456   /// was found in header search. However, the combination of \c Name and
457   /// this module map will be globally unique for top-level modules. In the case
458   /// of inferred modules, returns the module map that allowed the inference
459   /// (e.g. contained 'module *'). Otherwise, returns
460   /// getContainingModuleMapFile().
461   const FileEntry *getModuleMapFileForUniquing(const Module *M) const;
462
463   void setInferredModuleAllowedBy(Module *M, const FileEntry *ModuleMap);
464
465   /// \brief Get any module map files other than getModuleMapFileForUniquing(M)
466   /// that define submodules of a top-level module \p M. This is cheaper than
467   /// getting the module map file for each submodule individually, since the
468   /// expected number of results is very small.
469   AdditionalModMapsSet *getAdditionalModuleMapFiles(const Module *M) {
470     auto I = AdditionalModMaps.find(M);
471     if (I == AdditionalModMaps.end())
472       return nullptr;
473     return &I->second;
474   }
475
476   void addAdditionalModuleMapFile(const Module *M, const FileEntry *ModuleMap) {
477     AdditionalModMaps[M].insert(ModuleMap);
478   }
479
480   /// \brief Resolve all of the unresolved exports in the given module.
481   ///
482   /// \param Mod The module whose exports should be resolved.
483   ///
484   /// \param Complain Whether to emit diagnostics for failures.
485   ///
486   /// \returns true if any errors were encountered while resolving exports,
487   /// false otherwise.
488   bool resolveExports(Module *Mod, bool Complain);
489
490   /// \brief Resolve all of the unresolved uses in the given module.
491   ///
492   /// \param Mod The module whose uses should be resolved.
493   ///
494   /// \param Complain Whether to emit diagnostics for failures.
495   ///
496   /// \returns true if any errors were encountered while resolving uses,
497   /// false otherwise.
498   bool resolveUses(Module *Mod, bool Complain);
499
500   /// \brief Resolve all of the unresolved conflicts in the given module.
501   ///
502   /// \param Mod The module whose conflicts should be resolved.
503   ///
504   /// \param Complain Whether to emit diagnostics for failures.
505   ///
506   /// \returns true if any errors were encountered while resolving conflicts,
507   /// false otherwise.
508   bool resolveConflicts(Module *Mod, bool Complain);
509
510   /// \brief Infers the (sub)module based on the given source location and
511   /// source manager.
512   ///
513   /// \param Loc The location within the source that we are querying, along
514   /// with its source manager.
515   ///
516   /// \returns The module that owns this source location, or null if no
517   /// module owns this source location.
518   Module *inferModuleFromLocation(FullSourceLoc Loc);
519   
520   /// \brief Sets the umbrella header of the given module to the given
521   /// header.
522   void setUmbrellaHeader(Module *Mod, const FileEntry *UmbrellaHeader,
523                          Twine NameAsWritten);
524
525   /// \brief Sets the umbrella directory of the given module to the given
526   /// directory.
527   void setUmbrellaDir(Module *Mod, const DirectoryEntry *UmbrellaDir,
528                       Twine NameAsWritten);
529
530   /// \brief Adds this header to the given module.
531   /// \param Role The role of the header wrt the module.
532   void addHeader(Module *Mod, Module::Header Header,
533                  ModuleHeaderRole Role, bool Imported = false);
534
535   /// \brief Marks this header as being excluded from the given module.
536   void excludeHeader(Module *Mod, Module::Header Header);
537
538   /// \brief Parse the given module map file, and record any modules we 
539   /// encounter.
540   ///
541   /// \param File The file to be parsed.
542   ///
543   /// \param IsSystem Whether this module map file is in a system header
544   /// directory, and therefore should be considered a system module.
545   ///
546   /// \param HomeDir The directory in which relative paths within this module
547   ///        map file will be resolved.
548   ///
549   /// \param ExternModuleLoc The location of the "extern module" declaration
550   ///        that caused us to load this module map file, if any.
551   ///
552   /// \returns true if an error occurred, false otherwise.
553   bool parseModuleMapFile(const FileEntry *File, bool IsSystem,
554                           const DirectoryEntry *HomeDir,
555                           SourceLocation ExternModuleLoc = SourceLocation());
556     
557   /// \brief Dump the contents of the module map, for debugging purposes.
558   void dump();
559   
560   typedef llvm::StringMap<Module *>::const_iterator module_iterator;
561   module_iterator module_begin() const { return Modules.begin(); }
562   module_iterator module_end()   const { return Modules.end(); }
563 };
564   
565 } // end namespace clang
566
567 #endif // LLVM_CLANG_LEX_MODULEMAP_H