]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/include/clang/Lex/ModuleMap.h
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r304149, and update
[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   /// Resolve the given header directive to an actual header file.
261   ///
262   /// \param M The module in which we're resolving the header directive.
263   /// \param Header The header directive to resolve.
264   /// \param RelativePathName Filled in with the relative path name from the
265   ///        module to the resolved header.
266   /// \return The resolved file, if any.
267   const FileEntry *resolveHeader(Module *M,
268                                  Module::UnresolvedHeaderDirective Header,
269                                  SmallVectorImpl<char> &RelativePathName);
270
271   /// Attempt to resolve the specified header directive as naming a builtin
272   /// header.
273   const FileEntry *
274   resolveAsBuiltinHeader(Module *M, Module::UnresolvedHeaderDirective Header,
275                          SmallVectorImpl<char> &BuiltinPathName);
276
277   /// \brief Looks up the modules that \p File corresponds to.
278   ///
279   /// If \p File represents a builtin header within Clang's builtin include
280   /// directory, this also loads all of the module maps to see if it will get
281   /// associated with a specific module (e.g. in /usr/include).
282   HeadersMap::iterator findKnownHeader(const FileEntry *File);
283
284   /// \brief Searches for a module whose umbrella directory contains \p File.
285   ///
286   /// \param File The header to search for.
287   ///
288   /// \param IntermediateDirs On success, contains the set of directories
289   /// searched before finding \p File.
290   KnownHeader findHeaderInUmbrellaDirs(const FileEntry *File,
291                     SmallVectorImpl<const DirectoryEntry *> &IntermediateDirs);
292
293   /// \brief Given that \p File is not in the Headers map, look it up within
294   /// umbrella directories and find or create a module for it.
295   KnownHeader findOrCreateModuleForHeaderInUmbrellaDir(const FileEntry *File);
296
297   /// \brief A convenience method to determine if \p File is (possibly nested)
298   /// in an umbrella directory.
299   bool isHeaderInUmbrellaDirs(const FileEntry *File) {
300     SmallVector<const DirectoryEntry *, 2> IntermediateDirs;
301     return static_cast<bool>(findHeaderInUmbrellaDirs(File, IntermediateDirs));
302   }
303
304   Module *inferFrameworkModule(const DirectoryEntry *FrameworkDir,
305                                Attributes Attrs, Module *Parent);
306
307 public:
308   /// \brief Construct a new module map.
309   ///
310   /// \param SourceMgr The source manager used to find module files and headers.
311   /// This source manager should be shared with the header-search mechanism,
312   /// since they will refer to the same headers.
313   ///
314   /// \param Diags A diagnostic engine used for diagnostics.
315   ///
316   /// \param LangOpts Language options for this translation unit.
317   ///
318   /// \param Target The target for this translation unit.
319   ModuleMap(SourceManager &SourceMgr, DiagnosticsEngine &Diags,
320             const LangOptions &LangOpts, const TargetInfo *Target,
321             HeaderSearch &HeaderInfo);
322
323   /// \brief Destroy the module map.
324   ///
325   ~ModuleMap();
326
327   /// \brief Set the target information.
328   void setTarget(const TargetInfo &Target);
329
330   /// \brief Set the directory that contains Clang-supplied include
331   /// files, such as our stdarg.h or tgmath.h.
332   void setBuiltinIncludeDir(const DirectoryEntry *Dir) {
333     BuiltinIncludeDir = Dir;
334   }
335
336   /// \brief Get the directory that contains Clang-supplied include files.
337   const DirectoryEntry *getBuiltinDir() const {
338     return BuiltinIncludeDir;
339   }
340
341   /// \brief Is this a compiler builtin header?
342   static bool isBuiltinHeader(StringRef FileName);
343
344   /// \brief Add a module map callback.
345   void addModuleMapCallbacks(std::unique_ptr<ModuleMapCallbacks> Callback) {
346     Callbacks.push_back(std::move(Callback));
347   }
348
349   /// \brief Retrieve the module that owns the given header file, if any.
350   ///
351   /// \param File The header file that is likely to be included.
352   ///
353   /// \param AllowTextual If \c true and \p File is a textual header, return
354   /// its owning module. Otherwise, no KnownHeader will be returned if the
355   /// file is only known as a textual header.
356   ///
357   /// \returns The module KnownHeader, which provides the module that owns the
358   /// given header file.  The KnownHeader is default constructed to indicate
359   /// that no module owns this header file.
360   KnownHeader findModuleForHeader(const FileEntry *File,
361                                   bool AllowTextual = false);
362
363   /// \brief Retrieve all the modules that contain the given header file. This
364   /// may not include umbrella modules, nor information from external sources,
365   /// if they have not yet been inferred / loaded.
366   ///
367   /// Typically, \ref findModuleForHeader should be used instead, as it picks
368   /// the preferred module for the header.
369   ArrayRef<KnownHeader> findAllModulesForHeader(const FileEntry *File) const;
370
371   /// \brief Reports errors if a module must not include a specific file.
372   ///
373   /// \param RequestingModule The module including a file.
374   ///
375   /// \param RequestingModuleIsModuleInterface \c true if the inclusion is in
376   ///        the interface of RequestingModule, \c false if it's in the
377   ///        implementation of RequestingModule. Value is ignored and
378   ///        meaningless if RequestingModule is nullptr.
379   ///
380   /// \param FilenameLoc The location of the inclusion's filename.
381   ///
382   /// \param Filename The included filename as written.
383   ///
384   /// \param File The included file.
385   void diagnoseHeaderInclusion(Module *RequestingModule,
386                                bool RequestingModuleIsModuleInterface,
387                                SourceLocation FilenameLoc, StringRef Filename,
388                                const FileEntry *File);
389
390   /// \brief Determine whether the given header is part of a module
391   /// marked 'unavailable'.
392   bool isHeaderInUnavailableModule(const FileEntry *Header) const;
393
394   /// \brief Determine whether the given header is unavailable as part
395   /// of the specified module.
396   bool isHeaderUnavailableInModule(const FileEntry *Header,
397                                    const Module *RequestingModule) const;
398
399   /// \brief Retrieve a module with the given name.
400   ///
401   /// \param Name The name of the module to look up.
402   ///
403   /// \returns The named module, if known; otherwise, returns null.
404   Module *findModule(StringRef Name) const;
405
406   /// \brief Retrieve a module with the given name using lexical name lookup,
407   /// starting at the given context.
408   ///
409   /// \param Name The name of the module to look up.
410   ///
411   /// \param Context The module context, from which we will perform lexical
412   /// name lookup.
413   ///
414   /// \returns The named module, if known; otherwise, returns null.
415   Module *lookupModuleUnqualified(StringRef Name, Module *Context) const;
416
417   /// \brief Retrieve a module with the given name within the given context,
418   /// using direct (qualified) name lookup.
419   ///
420   /// \param Name The name of the module to look up.
421   /// 
422   /// \param Context The module for which we will look for a submodule. If
423   /// null, we will look for a top-level module.
424   ///
425   /// \returns The named submodule, if known; otherwose, returns null.
426   Module *lookupModuleQualified(StringRef Name, Module *Context) const;
427   
428   /// \brief Find a new module or submodule, or create it if it does not already
429   /// exist.
430   ///
431   /// \param Name The name of the module to find or create.
432   ///
433   /// \param Parent The module that will act as the parent of this submodule,
434   /// or NULL to indicate that this is a top-level module.
435   ///
436   /// \param IsFramework Whether this is a framework module.
437   ///
438   /// \param IsExplicit Whether this is an explicit submodule.
439   ///
440   /// \returns The found or newly-created module, along with a boolean value
441   /// that will be true if the module is newly-created.
442   std::pair<Module *, bool> findOrCreateModule(StringRef Name, Module *Parent,
443                                                bool IsFramework,
444                                                bool IsExplicit);
445
446   /// \brief Create a new module for a C++ Modules TS module interface unit.
447   /// The module must not already exist, and will be configured for the current
448   /// compilation.
449   ///
450   /// Note that this also sets the current module to the newly-created module.
451   ///
452   /// \returns The newly-created module.
453   Module *createModuleForInterfaceUnit(SourceLocation Loc, StringRef Name);
454
455   /// \brief Infer the contents of a framework module map from the given
456   /// framework directory.
457   Module *inferFrameworkModule(const DirectoryEntry *FrameworkDir,
458                                bool IsSystem, Module *Parent);
459
460   /// \brief Retrieve the module map file containing the definition of the given
461   /// module.
462   ///
463   /// \param Module The module whose module map file will be returned, if known.
464   ///
465   /// \returns The file entry for the module map file containing the given
466   /// module, or NULL if the module definition was inferred.
467   const FileEntry *getContainingModuleMapFile(const Module *Module) const;
468
469   /// \brief Get the module map file that (along with the module name) uniquely
470   /// identifies this module.
471   ///
472   /// The particular module that \c Name refers to may depend on how the module
473   /// was found in header search. However, the combination of \c Name and
474   /// this module map will be globally unique for top-level modules. In the case
475   /// of inferred modules, returns the module map that allowed the inference
476   /// (e.g. contained 'module *'). Otherwise, returns
477   /// getContainingModuleMapFile().
478   const FileEntry *getModuleMapFileForUniquing(const Module *M) const;
479
480   void setInferredModuleAllowedBy(Module *M, const FileEntry *ModuleMap);
481
482   /// \brief Get any module map files other than getModuleMapFileForUniquing(M)
483   /// that define submodules of a top-level module \p M. This is cheaper than
484   /// getting the module map file for each submodule individually, since the
485   /// expected number of results is very small.
486   AdditionalModMapsSet *getAdditionalModuleMapFiles(const Module *M) {
487     auto I = AdditionalModMaps.find(M);
488     if (I == AdditionalModMaps.end())
489       return nullptr;
490     return &I->second;
491   }
492
493   void addAdditionalModuleMapFile(const Module *M, const FileEntry *ModuleMap) {
494     AdditionalModMaps[M].insert(ModuleMap);
495   }
496
497   /// \brief Resolve all of the unresolved exports in the given module.
498   ///
499   /// \param Mod The module whose exports should be resolved.
500   ///
501   /// \param Complain Whether to emit diagnostics for failures.
502   ///
503   /// \returns true if any errors were encountered while resolving exports,
504   /// false otherwise.
505   bool resolveExports(Module *Mod, bool Complain);
506
507   /// \brief Resolve all of the unresolved uses in the given module.
508   ///
509   /// \param Mod The module whose uses should be resolved.
510   ///
511   /// \param Complain Whether to emit diagnostics for failures.
512   ///
513   /// \returns true if any errors were encountered while resolving uses,
514   /// false otherwise.
515   bool resolveUses(Module *Mod, bool Complain);
516
517   /// \brief Resolve all of the unresolved conflicts in the given module.
518   ///
519   /// \param Mod The module whose conflicts should be resolved.
520   ///
521   /// \param Complain Whether to emit diagnostics for failures.
522   ///
523   /// \returns true if any errors were encountered while resolving conflicts,
524   /// false otherwise.
525   bool resolveConflicts(Module *Mod, bool Complain);
526
527   /// \brief Sets the umbrella header of the given module to the given
528   /// header.
529   void setUmbrellaHeader(Module *Mod, const FileEntry *UmbrellaHeader,
530                          Twine NameAsWritten);
531
532   /// \brief Sets the umbrella directory of the given module to the given
533   /// directory.
534   void setUmbrellaDir(Module *Mod, const DirectoryEntry *UmbrellaDir,
535                       Twine NameAsWritten);
536
537   /// \brief Adds this header to the given module.
538   /// \param Role The role of the header wrt the module.
539   void addHeader(Module *Mod, Module::Header Header,
540                  ModuleHeaderRole Role, bool Imported = false);
541
542   /// \brief Marks this header as being excluded from the given module.
543   void excludeHeader(Module *Mod, Module::Header Header);
544
545   /// \brief Parse the given module map file, and record any modules we 
546   /// encounter.
547   ///
548   /// \param File The file to be parsed.
549   ///
550   /// \param IsSystem Whether this module map file is in a system header
551   /// directory, and therefore should be considered a system module.
552   ///
553   /// \param HomeDir The directory in which relative paths within this module
554   ///        map file will be resolved.
555   ///
556   /// \param ID The FileID of the file to process, if we've already entered it.
557   ///
558   /// \param Offset [inout] On input the offset at which to start parsing. On
559   ///        output, the offset at which the module map terminated.
560   ///
561   /// \param ExternModuleLoc The location of the "extern module" declaration
562   ///        that caused us to load this module map file, if any.
563   ///
564   /// \returns true if an error occurred, false otherwise.
565   bool parseModuleMapFile(const FileEntry *File, bool IsSystem,
566                           const DirectoryEntry *HomeDir, FileID ID = FileID(),
567                           unsigned *Offset = nullptr,
568                           SourceLocation ExternModuleLoc = SourceLocation());
569
570   /// \brief Dump the contents of the module map, for debugging purposes.
571   void dump();
572   
573   typedef llvm::StringMap<Module *>::const_iterator module_iterator;
574   module_iterator module_begin() const { return Modules.begin(); }
575   module_iterator module_end()   const { return Modules.end(); }
576 };
577   
578 } // end namespace clang
579
580 #endif // LLVM_CLANG_LEX_MODULEMAP_H